1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 pub use self::PathParsingMode::*;
15 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
16 use ast::{Public, Unsafety};
17 use ast::{Mod, Arg, Arm, Attribute, BindingMode};
19 use ast::{BlockCheckMode, CaptureBy};
20 use ast::{Constness, ConstTraitItem, Crate, CrateConfig};
21 use ast::{Decl, DeclKind};
22 use ast::{EMPTY_CTXT, EnumDef, ExplicitSelf};
23 use ast::{Expr, ExprKind};
24 use ast::{Field, FnDecl};
25 use ast::{ForeignItem, ForeignItemStatic, ForeignItemFn, FunctionRetTy};
26 use ast::{Ident, Inherited, ImplItem, Item, Item_, ItemStatic};
27 use ast::{ItemEnum, ItemFn, ItemForeignMod, ItemImpl, ItemConst};
28 use ast::{ItemMac, ItemMod, ItemStruct, ItemTrait, ItemTy, ItemDefaultImpl};
29 use ast::{ItemExternCrate, ItemUse};
30 use ast::{Lit, Lit_, UintTy};
31 use ast::{LitBool, LitChar, LitByte, LitByteStr};
32 use ast::{LitStr, LitInt, Local};
33 use ast::{MacStmtWithBraces, MacStmtWithSemicolon, MacStmtWithoutBraces};
34 use ast::{MutImmutable, MutMutable, Mac_};
35 use ast::{MutTy, Mutability};
37 use ast::{Pat, PatBox, PatEnum, PatIdent, PatLit, PatQPath, PatMac, PatRange};
38 use ast::{PatRegion, PatStruct, PatTup, PatVec, PatWild};
39 use ast::{PolyTraitRef, QSelf};
40 use ast::{Stmt, StmtDecl};
41 use ast::{StmtExpr, StmtSemi, StmtMac, VariantData, StructField};
44 use ast::{Delimited, SequenceRepetition, TokenTree, TraitItem, TraitRef};
45 use ast::{Ty, TyKind, TypeBinding, TyParam, TyParamBounds};
46 use ast::TypeTraitItem;
47 use ast::UnnamedField;
48 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
49 use ast::{Visibility, WhereClause};
50 use attr::{ThinAttributes, ThinAttributesExt, AttributesExt};
51 use ast::{BinOpKind, UnOp};
53 use ast_util::{self, ident_to_path};
54 use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp, CodeMap};
55 use errors::{self, DiagnosticBuilder};
56 use ext::tt::macro_parser;
59 use parse::common::{SeqSep, seq_sep_none, seq_sep_trailing_allowed};
60 use parse::lexer::{Reader, TokenAndSpan};
61 use parse::obsolete::{ParserObsoleteMethods, ObsoleteSyntax};
62 use parse::token::{self, intern, MatchNt, SubstNt, SpecialVarNt, InternedString};
63 use parse::token::{keywords, special_idents, SpecialMacroVar};
64 use parse::{new_sub_parser_from_file, ParseSess};
65 use util::parser::{AssocOp, Fixity};
70 use std::collections::HashSet;
71 use std::io::prelude::*;
73 use std::path::{Path, PathBuf};
78 flags Restrictions: u8 {
79 const RESTRICTION_STMT_EXPR = 1 << 0,
80 const RESTRICTION_NO_STRUCT_LITERAL = 1 << 1,
84 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
86 /// How to parse a path. There are four different kinds of paths, all of which
87 /// are parsed somewhat differently.
88 #[derive(Copy, Clone, PartialEq)]
89 pub enum PathParsingMode {
90 /// A path with no type parameters; e.g. `foo::bar::Baz`
92 /// A path with a lifetime and type parameters, with no double colons
93 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
94 LifetimeAndTypesWithoutColons,
95 /// A path with a lifetime and type parameters with double colons before
96 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
97 LifetimeAndTypesWithColons,
100 /// How to parse a bound, whether to allow bound modifiers such as `?`.
101 #[derive(Copy, Clone, PartialEq)]
102 pub enum BoundParsingMode {
107 /// `pub` should be parsed in struct fields and not parsed in variant fields
108 #[derive(Clone, Copy, PartialEq)]
114 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
115 /// dropped into the token stream, which happens while parsing the result of
116 /// macro expansion). Placement of these is not as complex as I feared it would
117 /// be. The important thing is to make sure that lookahead doesn't balk at
118 /// `token::Interpolated` tokens.
119 macro_rules! maybe_whole_expr {
122 let found = match $p.token {
123 token::Interpolated(token::NtExpr(ref e)) => {
126 token::Interpolated(token::NtPath(_)) => {
127 // FIXME: The following avoids an issue with lexical borrowck scopes,
128 // but the clone is unfortunate.
129 let pt = match $p.token {
130 token::Interpolated(token::NtPath(ref pt)) => (**pt).clone(),
134 Some($p.mk_expr(span.lo, span.hi, ExprKind::Path(None, pt), None))
136 token::Interpolated(token::NtBlock(_)) => {
137 // FIXME: The following avoids an issue with lexical borrowck scopes,
138 // but the clone is unfortunate.
139 let b = match $p.token {
140 token::Interpolated(token::NtBlock(ref b)) => (*b).clone(),
144 Some($p.mk_expr(span.lo, span.hi, ExprKind::Block(b), None))
159 /// As maybe_whole_expr, but for things other than expressions
160 macro_rules! maybe_whole {
161 ($p:expr, $constructor:ident) => (
163 let found = match ($p).token {
164 token::Interpolated(token::$constructor(_)) => {
165 Some(($p).bump_and_get())
169 if let Some(token::Interpolated(token::$constructor(x))) = found {
170 return Ok(x.clone());
174 (no_clone $p:expr, $constructor:ident) => (
176 let found = match ($p).token {
177 token::Interpolated(token::$constructor(_)) => {
178 Some(($p).bump_and_get())
182 if let Some(token::Interpolated(token::$constructor(x))) = found {
187 (deref $p:expr, $constructor:ident) => (
189 let found = match ($p).token {
190 token::Interpolated(token::$constructor(_)) => {
191 Some(($p).bump_and_get())
195 if let Some(token::Interpolated(token::$constructor(x))) = found {
196 return Ok((*x).clone());
200 (Some deref $p:expr, $constructor:ident) => (
202 let found = match ($p).token {
203 token::Interpolated(token::$constructor(_)) => {
204 Some(($p).bump_and_get())
208 if let Some(token::Interpolated(token::$constructor(x))) = found {
209 return Ok(Some((*x).clone()));
213 (pair_empty $p:expr, $constructor:ident) => (
215 let found = match ($p).token {
216 token::Interpolated(token::$constructor(_)) => {
217 Some(($p).bump_and_get())
221 if let Some(token::Interpolated(token::$constructor(x))) = found {
222 return Ok((Vec::new(), x));
228 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
230 if let Some(ref attrs) = rhs {
231 lhs.extend(attrs.iter().cloned())
236 /* ident is handled by common.rs */
238 pub struct Parser<'a> {
239 pub sess: &'a ParseSess,
240 /// the current token:
241 pub token: token::Token,
242 /// the span of the current token:
244 /// the span of the prior token:
246 pub cfg: CrateConfig,
247 /// the previous token or None (only stashed sometimes).
248 pub last_token: Option<Box<token::Token>>,
249 last_token_interpolated: bool,
250 pub buffer: [TokenAndSpan; 4],
251 pub buffer_start: isize,
252 pub buffer_end: isize,
253 pub tokens_consumed: usize,
254 pub restrictions: Restrictions,
255 pub quote_depth: usize, // not (yet) related to the quasiquoter
256 pub reader: Box<Reader+'a>,
257 pub interner: Rc<token::IdentInterner>,
258 /// The set of seen errors about obsolete syntax. Used to suppress
259 /// extra detail when the same error is seen twice
260 pub obsolete_set: HashSet<ObsoleteSyntax>,
261 /// Used to determine the path to externally loaded source files
262 pub mod_path_stack: Vec<InternedString>,
263 /// Stack of spans of open delimiters. Used for error message.
264 pub open_braces: Vec<Span>,
265 /// Flag if this parser "owns" the directory that it is currently parsing
266 /// in. This will affect how nested files are looked up.
267 pub owns_directory: bool,
268 /// Name of the root module this parser originated from. If `None`, then the
269 /// name is not known. This does not change while the parser is descending
270 /// into modules, and sub-parsers have new values for this name.
271 pub root_module_name: Option<String>,
272 pub expected_tokens: Vec<TokenType>,
275 #[derive(PartialEq, Eq, Clone)]
278 Keyword(keywords::Keyword),
283 fn to_string(&self) -> String {
285 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
286 TokenType::Operator => "an operator".to_string(),
287 TokenType::Keyword(kw) => format!("`{}`", kw.to_name()),
292 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
293 t.is_plain_ident() || *t == token::Underscore
296 /// Information about the path to a module.
297 pub struct ModulePath {
299 pub path_exists: bool,
300 pub result: Result<ModulePathSuccess, ModulePathError>,
303 pub struct ModulePathSuccess {
304 pub path: ::std::path::PathBuf,
305 pub owns_directory: bool,
308 pub struct ModulePathError {
310 pub help_msg: String,
315 AttributesParsed(ThinAttributes),
316 AlreadyParsed(P<Expr>),
319 impl From<Option<ThinAttributes>> for LhsExpr {
320 fn from(o: Option<ThinAttributes>) -> Self {
321 if let Some(attrs) = o {
322 LhsExpr::AttributesParsed(attrs)
324 LhsExpr::NotYetParsed
329 impl From<P<Expr>> for LhsExpr {
330 fn from(expr: P<Expr>) -> Self {
331 LhsExpr::AlreadyParsed(expr)
335 impl<'a> Parser<'a> {
336 pub fn new(sess: &'a ParseSess,
337 cfg: ast::CrateConfig,
338 mut rdr: Box<Reader+'a>)
341 let tok0 = rdr.real_token();
343 let placeholder = TokenAndSpan {
344 tok: token::Underscore,
350 interner: token::get_ident_interner(),
357 last_token_interpolated: false,
367 restrictions: Restrictions::empty(),
369 obsolete_set: HashSet::new(),
370 mod_path_stack: Vec::new(),
371 open_braces: Vec::new(),
372 owns_directory: true,
373 root_module_name: None,
374 expected_tokens: Vec::new(),
378 /// Convert a token to a string using self's reader
379 pub fn token_to_string(token: &token::Token) -> String {
380 pprust::token_to_string(token)
383 /// Convert the current token to a string using self's reader
384 pub fn this_token_to_string(&self) -> String {
385 Parser::token_to_string(&self.token)
388 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
389 let token_str = Parser::token_to_string(t);
390 let last_span = self.last_span;
391 Err(self.span_fatal(last_span, &format!("unexpected token: `{}`", token_str)))
394 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
395 match self.expect_one_of(&[], &[]) {
397 Ok(_) => unreachable!(),
401 /// Expect and consume the token t. Signal an error if
402 /// the next token is not t.
403 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
404 if self.expected_tokens.is_empty() {
405 if self.token == *t {
409 let token_str = Parser::token_to_string(t);
410 let this_token_str = self.this_token_to_string();
411 Err(self.fatal(&format!("expected `{}`, found `{}`",
416 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
420 /// Expect next token to be edible or inedible token. If edible,
421 /// then consume it; if inedible, then return without consuming
422 /// anything. Signal a fatal error if next token is unexpected.
423 pub fn expect_one_of(&mut self,
424 edible: &[token::Token],
425 inedible: &[token::Token]) -> PResult<'a, ()>{
426 fn tokens_to_string(tokens: &[TokenType]) -> String {
427 let mut i = tokens.iter();
428 // This might be a sign we need a connect method on Iterator.
430 .map_or("".to_string(), |t| t.to_string());
431 i.enumerate().fold(b, |mut b, (i, ref a)| {
432 if tokens.len() > 2 && i == tokens.len() - 2 {
434 } else if tokens.len() == 2 && i == tokens.len() - 2 {
439 b.push_str(&*a.to_string());
443 if edible.contains(&self.token) {
446 } else if inedible.contains(&self.token) {
447 // leave it in the input
450 let mut expected = edible.iter()
451 .map(|x| TokenType::Token(x.clone()))
452 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
453 .chain(self.expected_tokens.iter().cloned())
454 .collect::<Vec<_>>();
455 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
457 let expect = tokens_to_string(&expected[..]);
458 let actual = self.this_token_to_string();
460 &(if expected.len() > 1 {
461 (format!("expected one of {}, found `{}`",
464 } else if expected.is_empty() {
465 (format!("unexpected token: `{}`",
468 (format!("expected {}, found `{}`",
476 /// Check for erroneous `ident { }`; if matches, signal error and
477 /// recover (without consuming any expected input token). Returns
478 /// true if and only if input was consumed for recovery.
479 pub fn check_for_erroneous_unit_struct_expecting(&mut self,
480 expected: &[token::Token])
482 if self.token == token::OpenDelim(token::Brace)
483 && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
484 && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
485 // matched; signal non-fatal error and recover.
486 let span = self.span;
487 self.span_err(span, "unit-like struct construction is written with no trailing `{ }`");
488 self.eat(&token::OpenDelim(token::Brace));
489 self.eat(&token::CloseDelim(token::Brace));
496 /// Commit to parsing a complete expression `e` expected to be
497 /// followed by some token from the set edible + inedible. Recover
498 /// from anticipated input errors, discarding erroneous characters.
499 pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token],
500 inedible: &[token::Token]) -> PResult<'a, ()> {
501 debug!("commit_expr {:?}", e);
502 if let ExprKind::Path(..) = e.node {
503 // might be unit-struct construction; check for recoverableinput error.
504 let expected = edible.iter()
506 .chain(inedible.iter().cloned())
507 .collect::<Vec<_>>();
508 self.check_for_erroneous_unit_struct_expecting(&expected[..]);
510 self.expect_one_of(edible, inedible)
513 pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) -> PResult<'a, ()> {
514 self.commit_expr(e, &[edible], &[])
517 /// Commit to parsing a complete statement `s`, which expects to be
518 /// followed by some token from the set edible + inedible. Check
519 /// for recoverable input errors, discarding erroneous characters.
520 pub fn commit_stmt(&mut self, edible: &[token::Token],
521 inedible: &[token::Token]) -> PResult<'a, ()> {
524 .map_or(false, |t| t.is_ident() || t.is_path()) {
525 let expected = edible.iter()
527 .chain(inedible.iter().cloned())
528 .collect::<Vec<_>>();
529 self.check_for_erroneous_unit_struct_expecting(&expected);
531 self.expect_one_of(edible, inedible)
534 pub fn commit_stmt_expecting(&mut self, edible: token::Token) -> PResult<'a, ()> {
535 self.commit_stmt(&[edible], &[])
538 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
539 fn interpolated_or_expr_span(&self,
540 expr: PResult<'a, P<Expr>>)
541 -> PResult<'a, (Span, P<Expr>)> {
543 if self.last_token_interpolated {
551 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
552 self.check_strict_keywords();
553 self.check_reserved_keywords();
555 token::Ident(i, _) => {
559 token::Interpolated(token::NtIdent(..)) => {
560 self.bug("ident interpolation not converted to real token");
563 let token_str = self.this_token_to_string();
564 Err(self.fatal(&format!("expected ident, found `{}`",
570 pub fn parse_ident_or_self_type(&mut self) -> PResult<'a, ast::Ident> {
571 if self.is_self_type_ident() {
572 self.expect_self_type_ident()
578 pub fn parse_path_list_item(&mut self) -> PResult<'a, ast::PathListItem> {
579 let lo = self.span.lo;
580 let node = if self.eat_keyword(keywords::SelfValue) {
581 let rename = try!(self.parse_rename());
582 ast::PathListMod { id: ast::DUMMY_NODE_ID, rename: rename }
584 let ident = try!(self.parse_ident());
585 let rename = try!(self.parse_rename());
586 ast::PathListIdent { name: ident, rename: rename, id: ast::DUMMY_NODE_ID }
588 let hi = self.last_span.hi;
589 Ok(spanned(lo, hi, node))
592 /// Check if the next token is `tok`, and return `true` if so.
594 /// This method is will automatically add `tok` to `expected_tokens` if `tok` is not
596 pub fn check(&mut self, tok: &token::Token) -> bool {
597 let is_present = self.token == *tok;
598 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
602 /// Consume token 'tok' if it exists. Returns true if the given
603 /// token was present, false otherwise.
604 pub fn eat(&mut self, tok: &token::Token) -> bool {
605 let is_present = self.check(tok);
606 if is_present { self.bump() }
610 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
611 self.expected_tokens.push(TokenType::Keyword(kw));
612 self.token.is_keyword(kw)
615 /// If the next token is the given keyword, eat it and return
616 /// true. Otherwise, return false.
617 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
618 if self.check_keyword(kw) {
626 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
627 if self.token.is_keyword(kw) {
635 /// If the given word is not a keyword, signal an error.
636 /// If the next token is not the given word, signal an error.
637 /// Otherwise, eat it.
638 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
639 if !self.eat_keyword(kw) {
646 /// Signal an error if the given string is a strict keyword
647 pub fn check_strict_keywords(&mut self) {
648 if self.token.is_strict_keyword() {
649 let token_str = self.this_token_to_string();
650 let span = self.span;
652 &format!("expected identifier, found keyword `{}`",
657 /// Signal an error if the current token is a reserved keyword
658 pub fn check_reserved_keywords(&mut self) {
659 if self.token.is_reserved_keyword() {
660 let token_str = self.this_token_to_string();
661 self.fatal(&format!("`{}` is a reserved keyword", token_str)).emit()
665 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
666 /// `&` and continue. If an `&` is not seen, signal an error.
667 fn expect_and(&mut self) -> PResult<'a, ()> {
668 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
670 token::BinOp(token::And) => {
675 let span = self.span;
676 let lo = span.lo + BytePos(1);
677 Ok(self.bump_with(token::BinOp(token::And), lo, span.hi))
679 _ => self.unexpected()
683 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
685 None => {/* everything ok */}
687 let text = suf.as_str();
689 self.span_bug(sp, "found empty literal suffix in Some")
691 self.span_err(sp, &*format!("{} with a suffix is invalid", kind));
697 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
698 /// `<` and continue. If a `<` is not seen, return false.
700 /// This is meant to be used when parsing generics on a path to get the
702 fn eat_lt(&mut self) -> bool {
703 self.expected_tokens.push(TokenType::Token(token::Lt));
709 token::BinOp(token::Shl) => {
710 let span = self.span;
711 let lo = span.lo + BytePos(1);
712 self.bump_with(token::Lt, lo, span.hi);
719 fn expect_lt(&mut self) -> PResult<'a, ()> {
727 /// Expect and consume a GT. if a >> is seen, replace it
728 /// with a single > and continue. If a GT is not seen,
730 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
731 self.expected_tokens.push(TokenType::Token(token::Gt));
737 token::BinOp(token::Shr) => {
738 let span = self.span;
739 let lo = span.lo + BytePos(1);
740 Ok(self.bump_with(token::Gt, lo, span.hi))
742 token::BinOpEq(token::Shr) => {
743 let span = self.span;
744 let lo = span.lo + BytePos(1);
745 Ok(self.bump_with(token::Ge, lo, span.hi))
748 let span = self.span;
749 let lo = span.lo + BytePos(1);
750 Ok(self.bump_with(token::Eq, lo, span.hi))
753 let gt_str = Parser::token_to_string(&token::Gt);
754 let this_token_str = self.this_token_to_string();
755 Err(self.fatal(&format!("expected `{}`, found `{}`",
762 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
763 sep: Option<token::Token>,
765 -> PResult<'a, (P<[T]>, bool)>
766 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
768 let mut v = Vec::new();
769 // This loop works by alternating back and forth between parsing types
770 // and commas. For example, given a string `A, B,>`, the parser would
771 // first parse `A`, then a comma, then `B`, then a comma. After that it
772 // would encounter a `>` and stop. This lets the parser handle trailing
773 // commas in generic parameters, because it can stop either after
774 // parsing a type or after parsing a comma.
776 if self.check(&token::Gt)
777 || self.token == token::BinOp(token::Shr)
778 || self.token == token::Ge
779 || self.token == token::BinOpEq(token::Shr) {
784 match try!(f(self)) {
785 Some(result) => v.push(result),
786 None => return Ok((P::from_vec(v), true))
789 if let Some(t) = sep.as_ref() {
790 try!(self.expect(t));
795 return Ok((P::from_vec(v), false));
798 /// Parse a sequence bracketed by '<' and '>', stopping
800 pub fn parse_seq_to_before_gt<T, F>(&mut self,
801 sep: Option<token::Token>,
803 -> PResult<'a, P<[T]>> where
804 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
806 let (result, returned) = try!(self.parse_seq_to_before_gt_or_return(sep,
807 |p| Ok(Some(try!(f(p))))));
812 pub fn parse_seq_to_gt<T, F>(&mut self,
813 sep: Option<token::Token>,
815 -> PResult<'a, P<[T]>> where
816 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
818 let v = try!(self.parse_seq_to_before_gt(sep, f));
819 try!(self.expect_gt());
823 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
824 sep: Option<token::Token>,
826 -> PResult<'a, (P<[T]>, bool)> where
827 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
829 let (v, returned) = try!(self.parse_seq_to_before_gt_or_return(sep, f));
831 try!(self.expect_gt());
833 return Ok((v, returned));
836 /// Parse a sequence, including the closing delimiter. The function
837 /// f must consume tokens until reaching the next separator or
839 pub fn parse_seq_to_end<T, F>(&mut self,
843 -> PResult<'a, Vec<T>> where
844 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
846 let val = try!(self.parse_seq_to_before_end(ket, sep, f));
851 /// Parse a sequence, not including the closing delimiter. The function
852 /// f must consume tokens until reaching the next separator or
854 pub fn parse_seq_to_before_end<T, F>(&mut self,
858 -> PResult<'a, Vec<T>> where
859 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
861 let mut first: bool = true;
863 while self.token != *ket {
866 if first { first = false; }
867 else { try!(self.expect(t)); }
871 if sep.trailing_sep_allowed && self.check(ket) { break; }
872 v.push(try!(f(self)));
877 /// Parse a sequence, including the closing delimiter. The function
878 /// f must consume tokens until reaching the next separator or
880 pub fn parse_unspanned_seq<T, F>(&mut self,
885 -> PResult<'a, Vec<T>> where
886 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
888 try!(self.expect(bra));
889 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
894 /// Parse a sequence parameter of enum variant. For consistency purposes,
895 /// these should not be empty.
896 pub fn parse_enum_variant_seq<T, F>(&mut self,
901 -> PResult<'a, Vec<T>> where
902 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
904 let result = try!(self.parse_unspanned_seq(bra, ket, sep, f));
905 if result.is_empty() {
906 let last_span = self.last_span;
907 self.span_err(last_span,
908 "nullary enum variants are written with no trailing `( )`");
913 // NB: Do not use this function unless you actually plan to place the
914 // spanned list in the AST.
915 pub fn parse_seq<T, F>(&mut self,
920 -> PResult<'a, Spanned<Vec<T>>> where
921 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
923 let lo = self.span.lo;
924 try!(self.expect(bra));
925 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
926 let hi = self.span.hi;
928 Ok(spanned(lo, hi, result))
931 /// Advance the parser by one token
932 pub fn bump(&mut self) {
933 self.last_span = self.span;
934 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
935 self.last_token = if self.token.is_ident() ||
936 self.token.is_path() ||
937 self.token == token::Comma {
938 Some(Box::new(self.token.clone()))
942 self.last_token_interpolated = self.token.is_interpolated();
943 let next = if self.buffer_start == self.buffer_end {
944 self.reader.real_token()
946 // Avoid token copies with `replace`.
947 let buffer_start = self.buffer_start as usize;
948 let next_index = (buffer_start + 1) & 3;
949 self.buffer_start = next_index as isize;
951 let placeholder = TokenAndSpan {
952 tok: token::Underscore,
955 mem::replace(&mut self.buffer[buffer_start], placeholder)
958 self.token = next.tok;
959 self.tokens_consumed += 1;
960 self.expected_tokens.clear();
961 // check after each token
962 self.check_unknown_macro_variable();
965 /// Advance the parser by one token and return the bumped token.
966 pub fn bump_and_get(&mut self) -> token::Token {
967 let old_token = mem::replace(&mut self.token, token::Underscore);
972 /// Advance the parser using provided token as a next one. Use this when
973 /// consuming a part of a token. For example a single `<` from `<<`.
974 pub fn bump_with(&mut self,
978 self.last_span = mk_sp(self.span.lo, lo);
979 // It would be incorrect to just stash current token, but fortunately
980 // for tokens currently using `bump_with`, last_token will be of no
982 self.last_token = None;
983 self.last_token_interpolated = false;
984 self.span = mk_sp(lo, hi);
986 self.expected_tokens.clear();
989 pub fn buffer_length(&mut self) -> isize {
990 if self.buffer_start <= self.buffer_end {
991 return self.buffer_end - self.buffer_start;
993 return (4 - self.buffer_start) + self.buffer_end;
995 pub fn look_ahead<R, F>(&mut self, distance: usize, f: F) -> R where
996 F: FnOnce(&token::Token) -> R,
998 let dist = distance as isize;
999 while self.buffer_length() < dist {
1000 self.buffer[self.buffer_end as usize] = self.reader.real_token();
1001 self.buffer_end = (self.buffer_end + 1) & 3;
1003 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as usize].tok)
1005 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1006 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1008 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1009 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1011 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1012 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1013 err.fileline_help(sp, help);
1016 pub fn bug(&self, m: &str) -> ! {
1017 self.sess.span_diagnostic.span_bug(self.span, m)
1019 pub fn warn(&self, m: &str) {
1020 self.sess.span_diagnostic.span_warn(self.span, m)
1022 pub fn span_warn(&self, sp: Span, m: &str) {
1023 self.sess.span_diagnostic.span_warn(sp, m)
1025 pub fn span_err(&self, sp: Span, m: &str) {
1026 self.sess.span_diagnostic.span_err(sp, m)
1028 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1029 self.sess.span_diagnostic.span_bug(sp, m)
1031 pub fn abort_if_errors(&self) {
1032 self.sess.span_diagnostic.abort_if_errors();
1035 pub fn diagnostic(&self) -> &'a errors::Handler {
1036 &self.sess.span_diagnostic
1039 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
1043 /// Is the current token one of the keywords that signals a bare function
1045 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1046 self.check_keyword(keywords::Fn) ||
1047 self.check_keyword(keywords::Unsafe) ||
1048 self.check_keyword(keywords::Extern)
1051 pub fn get_lifetime(&mut self) -> ast::Ident {
1053 token::Lifetime(ref ident) => *ident,
1054 _ => self.bug("not a lifetime"),
1058 pub fn parse_for_in_type(&mut self) -> PResult<'a, TyKind> {
1060 Parses whatever can come after a `for` keyword in a type.
1061 The `for` has already been consumed.
1065 - for <'lt> |S| -> T
1069 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1070 - for <'lt> path::foo(a, b)
1075 let lo = self.span.lo;
1077 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
1079 // examine next token to decide to do
1080 if self.token_is_bare_fn_keyword() {
1081 self.parse_ty_bare_fn(lifetime_defs)
1083 let hi = self.span.hi;
1084 let trait_ref = try!(self.parse_trait_ref());
1085 let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1086 trait_ref: trait_ref,
1087 span: mk_sp(lo, hi)};
1088 let other_bounds = if self.eat(&token::BinOp(token::Plus)) {
1089 try!(self.parse_ty_param_bounds(BoundParsingMode::Bare))
1094 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1095 .chain(other_bounds.into_vec())
1097 Ok(ast::TyKind::PolyTraitRef(all_bounds))
1101 pub fn parse_ty_path(&mut self) -> PResult<'a, TyKind> {
1102 Ok(TyKind::Path(None, try!(self.parse_path(LifetimeAndTypesWithoutColons))))
1105 /// parse a TyKind::BareFn type:
1106 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>)
1107 -> PResult<'a, TyKind> {
1110 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1111 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1114 | | | Argument types
1120 let unsafety = try!(self.parse_unsafety());
1121 let abi = if self.eat_keyword(keywords::Extern) {
1122 try!(self.parse_opt_abi()).unwrap_or(Abi::C)
1127 try!(self.expect_keyword(keywords::Fn));
1128 let (inputs, variadic) = try!(self.parse_fn_args(false, true));
1129 let ret_ty = try!(self.parse_ret_ty());
1130 let decl = P(FnDecl {
1135 Ok(TyKind::BareFn(P(BareFnTy {
1138 lifetimes: lifetime_defs,
1143 /// Parses an obsolete closure kind (`&:`, `&mut:`, or `:`).
1144 pub fn parse_obsolete_closure_kind(&mut self) -> PResult<'a, ()> {
1145 let lo = self.span.lo;
1147 self.check(&token::BinOp(token::And)) &&
1148 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1149 self.look_ahead(2, |t| *t == token::Colon)
1155 self.token == token::BinOp(token::And) &&
1156 self.look_ahead(1, |t| *t == token::Colon)
1161 self.eat(&token::Colon)
1168 let span = mk_sp(lo, self.span.hi);
1169 self.obsolete(span, ObsoleteSyntax::ClosureKind);
1173 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1174 if self.eat_keyword(keywords::Unsafe) {
1175 return Ok(Unsafety::Unsafe);
1177 return Ok(Unsafety::Normal);
1181 /// Parse the items in a trait declaration
1182 pub fn parse_trait_items(&mut self) -> PResult<'a, Vec<P<TraitItem>>> {
1183 self.parse_unspanned_seq(
1184 &token::OpenDelim(token::Brace),
1185 &token::CloseDelim(token::Brace),
1187 |p| -> PResult<'a, P<TraitItem>> {
1188 maybe_whole!(no_clone p, NtTraitItem);
1189 let mut attrs = try!(p.parse_outer_attributes());
1192 let (name, node) = if p.eat_keyword(keywords::Type) {
1193 let TyParam {ident, bounds, default, ..} = try!(p.parse_ty_param());
1194 try!(p.expect(&token::Semi));
1195 (ident, TypeTraitItem(bounds, default))
1196 } else if p.is_const_item() {
1197 try!(p.expect_keyword(keywords::Const));
1198 let ident = try!(p.parse_ident());
1199 try!(p.expect(&token::Colon));
1200 let ty = try!(p.parse_ty_sum());
1201 let default = if p.check(&token::Eq) {
1203 let expr = try!(p.parse_expr());
1204 try!(p.commit_expr_expecting(&expr, token::Semi));
1207 try!(p.expect(&token::Semi));
1210 (ident, ConstTraitItem(ty, default))
1212 let (constness, unsafety, abi) = try!(p.parse_fn_front_matter());
1214 let ident = try!(p.parse_ident());
1215 let mut generics = try!(p.parse_generics());
1217 let (explicit_self, d) = try!(p.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1218 // This is somewhat dubious; We don't want to allow
1219 // argument names to be left off if there is a
1221 p.parse_arg_general(false)
1224 generics.where_clause = try!(p.parse_where_clause());
1225 let sig = ast::MethodSig {
1227 constness: constness,
1231 explicit_self: explicit_self,
1234 let body = match p.token {
1237 debug!("parse_trait_methods(): parsing required method");
1240 token::OpenDelim(token::Brace) => {
1241 debug!("parse_trait_methods(): parsing provided method");
1242 let (inner_attrs, body) =
1243 try!(p.parse_inner_attrs_and_block());
1244 attrs.extend(inner_attrs.iter().cloned());
1249 let token_str = p.this_token_to_string();
1250 return Err(p.fatal(&format!("expected `;` or `{{`, found `{}`",
1254 (ident, ast::MethodTraitItem(sig, body))
1258 id: ast::DUMMY_NODE_ID,
1262 span: mk_sp(lo, p.last_span.hi),
1267 /// Parse a possibly mutable type
1268 pub fn parse_mt(&mut self) -> PResult<'a, MutTy> {
1269 let mutbl = try!(self.parse_mutability());
1270 let t = try!(self.parse_ty());
1271 Ok(MutTy { ty: t, mutbl: mutbl })
1274 /// Parse optional return type [ -> TY ] in function decl
1275 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1276 if self.eat(&token::RArrow) {
1277 if self.eat(&token::Not) {
1278 Ok(FunctionRetTy::None(self.last_span))
1280 Ok(FunctionRetTy::Ty(try!(self.parse_ty())))
1283 let pos = self.span.lo;
1284 Ok(FunctionRetTy::Default(mk_sp(pos, pos)))
1288 /// Parse a type in a context where `T1+T2` is allowed.
1289 pub fn parse_ty_sum(&mut self) -> PResult<'a, P<Ty>> {
1290 let lo = self.span.lo;
1291 let lhs = try!(self.parse_ty());
1293 if !self.eat(&token::BinOp(token::Plus)) {
1297 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
1299 // In type grammar, `+` is treated like a binary operator,
1300 // and hence both L and R side are required.
1301 if bounds.is_empty() {
1302 let last_span = self.last_span;
1303 self.span_err(last_span,
1304 "at least one type parameter bound \
1305 must be specified");
1308 let sp = mk_sp(lo, self.last_span.hi);
1309 let sum = ast::TyKind::ObjectSum(lhs, bounds);
1310 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp}))
1314 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1315 maybe_whole!(no_clone self, NtTy);
1317 let lo = self.span.lo;
1319 let t = if self.check(&token::OpenDelim(token::Paren)) {
1322 // (t) is a parenthesized ty
1323 // (t,) is the type of a tuple with only one field,
1325 let mut ts = vec![];
1326 let mut last_comma = false;
1327 while self.token != token::CloseDelim(token::Paren) {
1328 ts.push(try!(self.parse_ty_sum()));
1329 if self.check(&token::Comma) {
1338 try!(self.expect(&token::CloseDelim(token::Paren)));
1339 if ts.len() == 1 && !last_comma {
1340 TyKind::Paren(ts.into_iter().nth(0).unwrap())
1344 } else if self.check(&token::BinOp(token::Star)) {
1345 // STAR POINTER (bare pointer?)
1347 TyKind::Ptr(try!(self.parse_ptr()))
1348 } else if self.check(&token::OpenDelim(token::Bracket)) {
1350 try!(self.expect(&token::OpenDelim(token::Bracket)));
1351 let t = try!(self.parse_ty_sum());
1353 // Parse the `; e` in `[ i32; e ]`
1354 // where `e` is a const expression
1355 let t = match try!(self.maybe_parse_fixed_length_of_vec()) {
1356 None => TyKind::Vec(t),
1357 Some(suffix) => TyKind::FixedLengthVec(t, suffix)
1359 try!(self.expect(&token::CloseDelim(token::Bracket)));
1361 } else if self.check(&token::BinOp(token::And)) ||
1362 self.token == token::AndAnd {
1364 try!(self.expect_and());
1365 try!(self.parse_borrowed_pointee())
1366 } else if self.check_keyword(keywords::For) {
1367 try!(self.parse_for_in_type())
1368 } else if self.token_is_bare_fn_keyword() {
1370 try!(self.parse_ty_bare_fn(Vec::new()))
1371 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1373 // In order to not be ambiguous, the type must be surrounded by parens.
1374 try!(self.expect(&token::OpenDelim(token::Paren)));
1375 let e = try!(self.parse_expr());
1376 try!(self.expect(&token::CloseDelim(token::Paren)));
1378 } else if self.eat_lt() {
1381 try!(self.parse_qualified_path(NoTypesAllowed));
1383 TyKind::Path(Some(qself), path)
1384 } else if self.check(&token::ModSep) ||
1385 self.token.is_ident() ||
1386 self.token.is_path() {
1387 let path = try!(self.parse_path(LifetimeAndTypesWithoutColons));
1388 if self.check(&token::Not) {
1391 let delim = try!(self.expect_open_delim());
1392 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
1394 |p| p.parse_token_tree()));
1395 let hi = self.span.hi;
1396 TyKind::Mac(spanned(lo, hi, Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT }))
1399 TyKind::Path(None, path)
1401 } else if self.eat(&token::Underscore) {
1402 // TYPE TO BE INFERRED
1405 let this_token_str = self.this_token_to_string();
1406 let msg = format!("expected type, found `{}`", this_token_str);
1407 return Err(self.fatal(&msg[..]));
1410 let sp = mk_sp(lo, self.last_span.hi);
1411 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp}))
1414 pub fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1415 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1416 let opt_lifetime = try!(self.parse_opt_lifetime());
1418 let mt = try!(self.parse_mt());
1419 return Ok(TyKind::Rptr(opt_lifetime, mt));
1422 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1423 let mutbl = if self.eat_keyword(keywords::Mut) {
1425 } else if self.eat_keyword(keywords::Const) {
1428 let span = self.last_span;
1430 "bare raw pointers are no longer allowed, you should \
1431 likely use `*mut T`, but otherwise `*T` is now \
1432 known as `*const T`");
1435 let t = try!(self.parse_ty());
1436 Ok(MutTy { ty: t, mutbl: mutbl })
1439 pub fn is_named_argument(&mut self) -> bool {
1440 let offset = match self.token {
1441 token::BinOp(token::And) => 1,
1443 _ if self.token.is_keyword(keywords::Mut) => 1,
1447 debug!("parser is_named_argument offset:{}", offset);
1450 is_plain_ident_or_underscore(&self.token)
1451 && self.look_ahead(1, |t| *t == token::Colon)
1453 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1454 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1458 /// This version of parse arg doesn't necessarily require
1459 /// identifier names.
1460 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1461 maybe_whole!(no_clone self, NtArg);
1463 let pat = if require_name || self.is_named_argument() {
1464 debug!("parse_arg_general parse_pat (require_name:{})",
1466 let pat = try!(self.parse_pat());
1468 try!(self.expect(&token::Colon));
1471 debug!("parse_arg_general ident_to_pat");
1472 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1474 special_idents::invalid)
1477 let t = try!(self.parse_ty_sum());
1482 id: ast::DUMMY_NODE_ID,
1486 /// Parse a single function argument
1487 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1488 self.parse_arg_general(true)
1491 /// Parse an argument in a lambda header e.g. |arg, arg|
1492 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1493 let pat = try!(self.parse_pat());
1494 let t = if self.eat(&token::Colon) {
1495 try!(self.parse_ty_sum())
1498 id: ast::DUMMY_NODE_ID,
1499 node: TyKind::Infer,
1500 span: mk_sp(self.span.lo, self.span.hi),
1506 id: ast::DUMMY_NODE_ID
1510 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1511 if self.check(&token::Semi) {
1513 Ok(Some(try!(self.parse_expr())))
1519 /// Matches token_lit = LIT_INTEGER | ...
1520 pub fn lit_from_token(&self, tok: &token::Token) -> PResult<'a, Lit_> {
1522 token::Interpolated(token::NtExpr(ref v)) => {
1524 ExprKind::Lit(ref lit) => { Ok(lit.node.clone()) }
1525 _ => { return self.unexpected_last(tok); }
1528 token::Literal(lit, suf) => {
1529 let (suffix_illegal, out) = match lit {
1530 token::Byte(i) => (true, LitByte(parse::byte_lit(&i.as_str()).0)),
1531 token::Char(i) => (true, LitChar(parse::char_lit(&i.as_str()).0)),
1533 // there are some valid suffixes for integer and
1534 // float literals, so all the handling is done
1536 token::Integer(s) => {
1537 (false, parse::integer_lit(&s.as_str(),
1538 suf.as_ref().map(|s| s.as_str()),
1539 &self.sess.span_diagnostic,
1542 token::Float(s) => {
1543 (false, parse::float_lit(&s.as_str(),
1544 suf.as_ref().map(|s| s.as_str()),
1545 &self.sess.span_diagnostic,
1551 LitStr(token::intern_and_get_ident(&parse::str_lit(&s.as_str())),
1554 token::StrRaw(s, n) => {
1557 token::intern_and_get_ident(&parse::raw_str_lit(&s.as_str())),
1560 token::ByteStr(i) =>
1561 (true, LitByteStr(parse::byte_str_lit(&i.as_str()))),
1562 token::ByteStrRaw(i, _) =>
1564 LitByteStr(Rc::new(i.to_string().into_bytes()))),
1568 let sp = self.last_span;
1569 self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1574 _ => { return self.unexpected_last(tok); }
1578 /// Matches lit = true | false | token_lit
1579 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1580 let lo = self.span.lo;
1581 let lit = if self.eat_keyword(keywords::True) {
1583 } else if self.eat_keyword(keywords::False) {
1586 let token = self.bump_and_get();
1587 let lit = try!(self.lit_from_token(&token));
1590 Ok(codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) })
1593 /// matches '-' lit | lit
1594 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1595 let minus_lo = self.span.lo;
1596 let minus_present = self.eat(&token::BinOp(token::Minus));
1597 let lo = self.span.lo;
1598 let literal = P(try!(self.parse_lit()));
1599 let hi = self.last_span.hi;
1600 let expr = self.mk_expr(lo, hi, ExprKind::Lit(literal), None);
1603 let minus_hi = self.last_span.hi;
1604 let unary = self.mk_unary(UnOp::Neg, expr);
1605 Ok(self.mk_expr(minus_lo, minus_hi, unary, None))
1611 /// Parses qualified path.
1613 /// Assumes that the leading `<` has been parsed already.
1615 /// Qualifed paths are a part of the universal function call
1618 /// `qualified_path = <type [as trait_ref]>::path`
1620 /// See `parse_path` for `mode` meaning.
1625 /// `<T as U>::F::a::<S>`
1626 pub fn parse_qualified_path(&mut self, mode: PathParsingMode)
1627 -> PResult<'a, (QSelf, ast::Path)> {
1628 let span = self.last_span;
1629 let self_type = try!(self.parse_ty_sum());
1630 let mut path = if self.eat_keyword(keywords::As) {
1631 try!(self.parse_path(LifetimeAndTypesWithoutColons))
1642 position: path.segments.len()
1645 try!(self.expect(&token::Gt));
1646 try!(self.expect(&token::ModSep));
1648 let segments = match mode {
1649 LifetimeAndTypesWithoutColons => {
1650 try!(self.parse_path_segments_without_colons())
1652 LifetimeAndTypesWithColons => {
1653 try!(self.parse_path_segments_with_colons())
1656 try!(self.parse_path_segments_without_types())
1659 path.segments.extend(segments);
1661 path.span.hi = self.last_span.hi;
1666 /// Parses a path and optional type parameter bounds, depending on the
1667 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1668 /// bounds are permitted and whether `::` must precede type parameter
1670 pub fn parse_path(&mut self, mode: PathParsingMode) -> PResult<'a, ast::Path> {
1671 // Check for a whole path...
1672 let found = match self.token {
1673 token::Interpolated(token::NtPath(_)) => Some(self.bump_and_get()),
1676 if let Some(token::Interpolated(token::NtPath(path))) = found {
1680 let lo = self.span.lo;
1681 let is_global = self.eat(&token::ModSep);
1683 // Parse any number of segments and bound sets. A segment is an
1684 // identifier followed by an optional lifetime and a set of types.
1685 // A bound set is a set of type parameter bounds.
1686 let segments = match mode {
1687 LifetimeAndTypesWithoutColons => {
1688 try!(self.parse_path_segments_without_colons())
1690 LifetimeAndTypesWithColons => {
1691 try!(self.parse_path_segments_with_colons())
1694 try!(self.parse_path_segments_without_types())
1698 // Assemble the span.
1699 let span = mk_sp(lo, self.last_span.hi);
1701 // Assemble the result.
1710 /// - `a::b<T,U>::c<V,W>`
1711 /// - `a::b<T,U>::c(V) -> W`
1712 /// - `a::b<T,U>::c(V)`
1713 pub fn parse_path_segments_without_colons(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1714 let mut segments = Vec::new();
1716 // First, parse an identifier.
1717 let identifier = try!(self.parse_ident_or_self_type());
1719 // Parse types, optionally.
1720 let parameters = if self.eat_lt() {
1721 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1723 ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
1724 lifetimes: lifetimes,
1725 types: P::from_vec(types),
1726 bindings: P::from_vec(bindings),
1728 } else if self.eat(&token::OpenDelim(token::Paren)) {
1729 let lo = self.last_span.lo;
1731 let inputs = try!(self.parse_seq_to_end(
1732 &token::CloseDelim(token::Paren),
1733 seq_sep_trailing_allowed(token::Comma),
1734 |p| p.parse_ty_sum()));
1736 let output_ty = if self.eat(&token::RArrow) {
1737 Some(try!(self.parse_ty()))
1742 let hi = self.last_span.hi;
1744 ast::PathParameters::Parenthesized(ast::ParenthesizedParameterData {
1745 span: mk_sp(lo, hi),
1750 ast::PathParameters::none()
1753 // Assemble and push the result.
1754 segments.push(ast::PathSegment { identifier: identifier,
1755 parameters: parameters });
1757 // Continue only if we see a `::`
1758 if !self.eat(&token::ModSep) {
1759 return Ok(segments);
1765 /// - `a::b::<T,U>::c`
1766 pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1767 let mut segments = Vec::new();
1769 // First, parse an identifier.
1770 let identifier = try!(self.parse_ident_or_self_type());
1772 // If we do not see a `::`, stop.
1773 if !self.eat(&token::ModSep) {
1774 segments.push(ast::PathSegment {
1775 identifier: identifier,
1776 parameters: ast::PathParameters::none()
1778 return Ok(segments);
1781 // Check for a type segment.
1783 // Consumed `a::b::<`, go look for types
1784 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1785 let parameters = ast::AngleBracketedParameterData {
1786 lifetimes: lifetimes,
1787 types: P::from_vec(types),
1788 bindings: P::from_vec(bindings),
1790 segments.push(ast::PathSegment {
1791 identifier: identifier,
1792 parameters: ast::PathParameters::AngleBracketed(parameters),
1795 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1796 if !self.eat(&token::ModSep) {
1797 return Ok(segments);
1800 // Consumed `a::`, go look for `b`
1801 segments.push(ast::PathSegment {
1802 identifier: identifier,
1803 parameters: ast::PathParameters::none(),
1812 pub fn parse_path_segments_without_types(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1813 let mut segments = Vec::new();
1815 // First, parse an identifier.
1816 let identifier = try!(self.parse_ident_or_self_type());
1818 // Assemble and push the result.
1819 segments.push(ast::PathSegment {
1820 identifier: identifier,
1821 parameters: ast::PathParameters::none()
1824 // If we do not see a `::`, stop.
1825 if !self.eat(&token::ModSep) {
1826 return Ok(segments);
1831 /// parses 0 or 1 lifetime
1832 pub fn parse_opt_lifetime(&mut self) -> PResult<'a, Option<ast::Lifetime>> {
1834 token::Lifetime(..) => {
1835 Ok(Some(try!(self.parse_lifetime())))
1843 /// Parses a single lifetime
1844 /// Matches lifetime = LIFETIME
1845 pub fn parse_lifetime(&mut self) -> PResult<'a, ast::Lifetime> {
1847 token::Lifetime(i) => {
1848 let span = self.span;
1850 return Ok(ast::Lifetime {
1851 id: ast::DUMMY_NODE_ID,
1857 return Err(self.fatal("expected a lifetime name"));
1862 /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def =
1863 /// lifetime [':' lifetimes]`
1864 pub fn parse_lifetime_defs(&mut self) -> PResult<'a, Vec<ast::LifetimeDef>> {
1866 let mut res = Vec::new();
1869 token::Lifetime(_) => {
1870 let lifetime = try!(self.parse_lifetime());
1872 if self.eat(&token::Colon) {
1873 try!(self.parse_lifetimes(token::BinOp(token::Plus)))
1877 res.push(ast::LifetimeDef { lifetime: lifetime,
1887 token::Comma => { self.bump();}
1888 token::Gt => { return Ok(res); }
1889 token::BinOp(token::Shr) => { return Ok(res); }
1891 let this_token_str = self.this_token_to_string();
1892 let msg = format!("expected `,` or `>` after lifetime \
1895 return Err(self.fatal(&msg[..]));
1901 /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
1902 /// one too, but putting that in there messes up the grammar....
1904 /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
1905 /// either a comma or `>`. Used when parsing type parameter lists, where we expect something
1906 /// like `<'a, 'b, T>`.
1907 pub fn parse_lifetimes(&mut self, sep: token::Token) -> PResult<'a, Vec<ast::Lifetime>> {
1909 let mut res = Vec::new();
1912 token::Lifetime(_) => {
1913 res.push(try!(self.parse_lifetime()));
1920 if self.token != sep {
1928 /// Parse mutability declaration (mut/const/imm)
1929 pub fn parse_mutability(&mut self) -> PResult<'a, Mutability> {
1930 if self.eat_keyword(keywords::Mut) {
1937 /// Parse ident COLON expr
1938 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1939 let lo = self.span.lo;
1940 let i = try!(self.parse_ident());
1941 let hi = self.last_span.hi;
1942 try!(self.expect(&token::Colon));
1943 let e = try!(self.parse_expr());
1945 ident: spanned(lo, hi, i),
1946 span: mk_sp(lo, e.span.hi),
1951 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos,
1952 node: ExprKind, attrs: ThinAttributes) -> P<Expr> {
1954 id: ast::DUMMY_NODE_ID,
1956 span: mk_sp(lo, hi),
1961 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
1962 ExprKind::Unary(unop, expr)
1965 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1966 ExprKind::Binary(binop, lhs, rhs)
1969 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
1970 ExprKind::Call(f, args)
1973 fn mk_method_call(&mut self,
1974 ident: ast::SpannedIdent,
1978 ExprKind::MethodCall(ident, tps, args)
1981 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
1982 ExprKind::Index(expr, idx)
1985 pub fn mk_range(&mut self,
1986 start: Option<P<Expr>>,
1987 end: Option<P<Expr>>)
1989 ExprKind::Range(start, end)
1992 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::ExprKind {
1993 ExprKind::Field(expr, ident)
1996 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
1997 ExprKind::TupField(expr, idx)
2000 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2001 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2002 ExprKind::AssignOp(binop, lhs, rhs)
2005 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos,
2006 m: Mac_, attrs: ThinAttributes) -> P<Expr> {
2008 id: ast::DUMMY_NODE_ID,
2009 node: ExprKind::Mac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
2010 span: mk_sp(lo, hi),
2015 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinAttributes) -> P<Expr> {
2016 let span = &self.span;
2017 let lv_lit = P(codemap::Spanned {
2018 node: LitInt(i as u64, ast::UnsignedIntLit(UintTy::U32)),
2023 id: ast::DUMMY_NODE_ID,
2024 node: ExprKind::Lit(lv_lit),
2030 fn expect_open_delim(&mut self) -> PResult<'a, token::DelimToken> {
2031 self.expected_tokens.push(TokenType::Token(token::Gt));
2033 token::OpenDelim(delim) => {
2037 _ => Err(self.fatal("expected open delimiter")),
2041 /// At the bottom (top?) of the precedence hierarchy,
2042 /// parse things like parenthesized exprs,
2043 /// macros, return, etc.
2045 /// NB: This does not parse outer attributes,
2046 /// and is private because it only works
2047 /// correctly if called from parse_dot_or_call_expr().
2048 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2049 maybe_whole_expr!(self);
2051 // Outer attributes are already parsed and will be
2052 // added to the return value after the fact.
2054 // Therefore, prevent sub-parser from parsing
2055 // attributes by giving them a empty "already parsed" list.
2056 let mut attrs = None;
2058 let lo = self.span.lo;
2059 let mut hi = self.span.hi;
2063 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2065 token::OpenDelim(token::Paren) => {
2068 let attrs = try!(self.parse_inner_attributes())
2072 // (e) is parenthesized e
2073 // (e,) is a tuple with only one field, e
2074 let mut es = vec![];
2075 let mut trailing_comma = false;
2076 while self.token != token::CloseDelim(token::Paren) {
2077 es.push(try!(self.parse_expr()));
2078 try!(self.commit_expr(&**es.last().unwrap(), &[],
2079 &[token::Comma, token::CloseDelim(token::Paren)]));
2080 if self.check(&token::Comma) {
2081 trailing_comma = true;
2085 trailing_comma = false;
2091 hi = self.last_span.hi;
2092 return if es.len() == 1 && !trailing_comma {
2093 Ok(self.mk_expr(lo, hi, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs))
2095 Ok(self.mk_expr(lo, hi, ExprKind::Tup(es), attrs))
2098 token::OpenDelim(token::Brace) => {
2099 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2101 token::BinOp(token::Or) | token::OrOr => {
2102 let lo = self.span.lo;
2103 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2105 token::Ident(id @ ast::Ident {
2106 name: token::SELF_KEYWORD_NAME,
2108 }, token::Plain) => {
2110 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2111 ex = ExprKind::Path(None, path);
2112 hi = self.last_span.hi;
2114 token::OpenDelim(token::Bracket) => {
2117 let inner_attrs = try!(self.parse_inner_attributes())
2119 attrs.update(|attrs| attrs.append(inner_attrs));
2121 if self.check(&token::CloseDelim(token::Bracket)) {
2124 ex = ExprKind::Vec(Vec::new());
2127 let first_expr = try!(self.parse_expr());
2128 if self.check(&token::Semi) {
2129 // Repeating array syntax: [ 0; 512 ]
2131 let count = try!(self.parse_expr());
2132 try!(self.expect(&token::CloseDelim(token::Bracket)));
2133 ex = ExprKind::Repeat(first_expr, count);
2134 } else if self.check(&token::Comma) {
2135 // Vector with two or more elements.
2137 let remaining_exprs = try!(self.parse_seq_to_end(
2138 &token::CloseDelim(token::Bracket),
2139 seq_sep_trailing_allowed(token::Comma),
2140 |p| Ok(try!(p.parse_expr()))
2142 let mut exprs = vec!(first_expr);
2143 exprs.extend(remaining_exprs);
2144 ex = ExprKind::Vec(exprs);
2146 // Vector with one element.
2147 try!(self.expect(&token::CloseDelim(token::Bracket)));
2148 ex = ExprKind::Vec(vec!(first_expr));
2151 hi = self.last_span.hi;
2156 try!(self.parse_qualified_path(LifetimeAndTypesWithColons));
2158 return Ok(self.mk_expr(lo, hi, ExprKind::Path(Some(qself), path), attrs));
2160 if self.eat_keyword(keywords::Move) {
2161 let lo = self.last_span.lo;
2162 return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2164 if self.eat_keyword(keywords::If) {
2165 return self.parse_if_expr(attrs);
2167 if self.eat_keyword(keywords::For) {
2168 let lo = self.last_span.lo;
2169 return self.parse_for_expr(None, lo, attrs);
2171 if self.eat_keyword(keywords::While) {
2172 let lo = self.last_span.lo;
2173 return self.parse_while_expr(None, lo, attrs);
2175 if self.token.is_lifetime() {
2176 let lifetime = self.get_lifetime();
2177 let lo = self.span.lo;
2179 try!(self.expect(&token::Colon));
2180 if self.eat_keyword(keywords::While) {
2181 return self.parse_while_expr(Some(lifetime), lo, attrs)
2183 if self.eat_keyword(keywords::For) {
2184 return self.parse_for_expr(Some(lifetime), lo, attrs)
2186 if self.eat_keyword(keywords::Loop) {
2187 return self.parse_loop_expr(Some(lifetime), lo, attrs)
2189 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2191 if self.eat_keyword(keywords::Loop) {
2192 let lo = self.last_span.lo;
2193 return self.parse_loop_expr(None, lo, attrs);
2195 if self.eat_keyword(keywords::Continue) {
2196 let ex = if self.token.is_lifetime() {
2197 let ex = ExprKind::Again(Some(Spanned{
2198 node: self.get_lifetime(),
2204 ExprKind::Again(None)
2206 let hi = self.last_span.hi;
2207 return Ok(self.mk_expr(lo, hi, ex, attrs));
2209 if self.eat_keyword(keywords::Match) {
2210 return self.parse_match_expr(attrs);
2212 if self.eat_keyword(keywords::Unsafe) {
2213 return self.parse_block_expr(
2215 BlockCheckMode::Unsafe(ast::UserProvided),
2218 if self.eat_keyword(keywords::Return) {
2219 if self.token.can_begin_expr() {
2220 let e = try!(self.parse_expr());
2222 ex = ExprKind::Ret(Some(e));
2224 ex = ExprKind::Ret(None);
2226 } else if self.eat_keyword(keywords::Break) {
2227 if self.token.is_lifetime() {
2228 ex = ExprKind::Break(Some(Spanned {
2229 node: self.get_lifetime(),
2234 ex = ExprKind::Break(None);
2236 hi = self.last_span.hi;
2237 } else if self.token.is_keyword(keywords::Let) {
2238 // Catch this syntax error here, instead of in `check_strict_keywords`, so
2239 // that we can explicitly mention that let is not to be used as an expression
2240 let mut db = self.fatal("expected expression, found statement (`let`)");
2241 db.note("variable declaration using `let` is a statement");
2243 } else if self.check(&token::ModSep) ||
2244 self.token.is_ident() &&
2245 !self.check_keyword(keywords::True) &&
2246 !self.check_keyword(keywords::False) {
2248 try!(self.parse_path(LifetimeAndTypesWithColons));
2250 // `!`, as an operator, is prefix, so we know this isn't that
2251 if self.check(&token::Not) {
2252 // MACRO INVOCATION expression
2255 let delim = try!(self.expect_open_delim());
2256 let tts = try!(self.parse_seq_to_end(
2257 &token::CloseDelim(delim),
2259 |p| p.parse_token_tree()));
2260 let hi = self.last_span.hi;
2262 return Ok(self.mk_mac_expr(lo,
2264 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT },
2267 if self.check(&token::OpenDelim(token::Brace)) {
2268 // This is a struct literal, unless we're prohibited
2269 // from parsing struct literals here.
2270 let prohibited = self.restrictions.contains(
2271 Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2274 // It's a struct literal.
2276 let mut fields = Vec::new();
2277 let mut base = None;
2279 let attrs = attrs.append(
2280 try!(self.parse_inner_attributes())
2281 .into_thin_attrs());
2283 while self.token != token::CloseDelim(token::Brace) {
2284 if self.eat(&token::DotDot) {
2285 base = Some(try!(self.parse_expr()));
2289 fields.push(try!(self.parse_field()));
2290 try!(self.commit_expr(&*fields.last().unwrap().expr,
2292 &[token::CloseDelim(token::Brace)]));
2296 try!(self.expect(&token::CloseDelim(token::Brace)));
2297 ex = ExprKind::Struct(pth, fields, base);
2298 return Ok(self.mk_expr(lo, hi, ex, attrs));
2303 ex = ExprKind::Path(None, pth);
2305 // other literal expression
2306 let lit = try!(self.parse_lit());
2308 ex = ExprKind::Lit(P(lit));
2313 return Ok(self.mk_expr(lo, hi, ex, attrs));
2316 fn parse_or_use_outer_attributes(&mut self,
2317 already_parsed_attrs: Option<ThinAttributes>)
2318 -> PResult<'a, ThinAttributes> {
2319 if let Some(attrs) = already_parsed_attrs {
2322 self.parse_outer_attributes().map(|a| a.into_thin_attrs())
2326 /// Parse a block or unsafe block
2327 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode,
2328 attrs: ThinAttributes)
2329 -> PResult<'a, P<Expr>> {
2331 let outer_attrs = attrs;
2332 try!(self.expect(&token::OpenDelim(token::Brace)));
2334 let inner_attrs = try!(self.parse_inner_attributes()).into_thin_attrs();
2335 let attrs = outer_attrs.append(inner_attrs);
2337 let blk = try!(self.parse_block_tail(lo, blk_mode));
2338 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprKind::Block(blk), attrs));
2341 /// parse a.b or a(13) or a[4] or just a
2342 pub fn parse_dot_or_call_expr(&mut self,
2343 already_parsed_attrs: Option<ThinAttributes>)
2344 -> PResult<'a, P<Expr>> {
2345 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2347 let b = self.parse_bottom_expr();
2348 let (span, b) = try!(self.interpolated_or_expr_span(b));
2349 self.parse_dot_or_call_expr_with(b, span.lo, attrs)
2352 pub fn parse_dot_or_call_expr_with(&mut self,
2355 attrs: ThinAttributes)
2356 -> PResult<'a, P<Expr>> {
2357 // Stitch the list of outer attributes onto the return value.
2358 // A little bit ugly, but the best way given the current code
2360 self.parse_dot_or_call_expr_with_(e0, lo)
2362 expr.map(|mut expr| {
2363 expr.attrs.update(|a| a.prepend(attrs));
2365 ExprKind::If(..) | ExprKind::IfLet(..) => {
2366 if !expr.attrs.as_attr_slice().is_empty() {
2367 // Just point to the first attribute in there...
2368 let span = expr.attrs.as_attr_slice()[0].span;
2371 "attributes are not yet allowed on `if` \
2382 // Assuming we have just parsed `.foo` (i.e., a dot and an ident), continue
2383 // parsing into an expression.
2384 fn parse_dot_suffix(&mut self,
2387 self_value: P<Expr>,
2389 -> PResult<'a, P<Expr>> {
2390 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2391 try!(self.expect_lt());
2392 try!(self.parse_generic_values_after_lt())
2394 (Vec::new(), Vec::new(), Vec::new())
2397 if !bindings.is_empty() {
2398 let last_span = self.last_span;
2399 self.span_err(last_span, "type bindings are only permitted on trait paths");
2402 Ok(match self.token {
2403 // expr.f() method call.
2404 token::OpenDelim(token::Paren) => {
2405 let mut es = try!(self.parse_unspanned_seq(
2406 &token::OpenDelim(token::Paren),
2407 &token::CloseDelim(token::Paren),
2408 seq_sep_trailing_allowed(token::Comma),
2409 |p| Ok(try!(p.parse_expr()))
2411 let hi = self.last_span.hi;
2413 es.insert(0, self_value);
2414 let id = spanned(ident_span.lo, ident_span.hi, ident);
2415 let nd = self.mk_method_call(id, tys, es);
2416 self.mk_expr(lo, hi, nd, None)
2420 if !tys.is_empty() {
2421 let last_span = self.last_span;
2422 self.span_err(last_span,
2423 "field expressions may not \
2424 have type parameters");
2427 let id = spanned(ident_span.lo, ident_span.hi, ident);
2428 let field = self.mk_field(self_value, id);
2429 self.mk_expr(lo, ident_span.hi, field, None)
2434 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: BytePos) -> PResult<'a, P<Expr>> {
2439 if self.eat(&token::Dot) {
2441 token::Ident(i, _) => {
2442 let dot_pos = self.last_span.hi;
2446 e = try!(self.parse_dot_suffix(i, mk_sp(dot_pos, hi), e, lo));
2448 token::Literal(token::Integer(n), suf) => {
2451 // A tuple index may not have a suffix
2452 self.expect_no_suffix(sp, "tuple index", suf);
2454 let dot = self.last_span.hi;
2458 let index = n.as_str().parse::<usize>().ok();
2461 let id = spanned(dot, hi, n);
2462 let field = self.mk_tup_field(e, id);
2463 e = self.mk_expr(lo, hi, field, None);
2466 let last_span = self.last_span;
2467 self.span_err(last_span, "invalid tuple or tuple struct index");
2471 token::Literal(token::Float(n), _suf) => {
2473 let last_span = self.last_span;
2474 let fstr = n.as_str();
2475 let mut err = self.diagnostic().struct_span_err(last_span,
2476 &format!("unexpected token: `{}`", n.as_str()));
2477 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2478 let float = match fstr.parse::<f64>().ok() {
2482 err.fileline_help(last_span,
2483 &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2484 float.trunc() as usize,
2485 format!(".{}", fstr.splitn(2, ".").last().unwrap())));
2491 // FIXME Could factor this out into non_fatal_unexpected or something.
2492 let actual = self.this_token_to_string();
2493 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2495 let dot_pos = self.last_span.hi;
2496 e = try!(self.parse_dot_suffix(special_idents::invalid,
2497 mk_sp(dot_pos, dot_pos),
2503 if self.expr_is_complete(&*e) { break; }
2506 token::OpenDelim(token::Paren) => {
2507 let es = try!(self.parse_unspanned_seq(
2508 &token::OpenDelim(token::Paren),
2509 &token::CloseDelim(token::Paren),
2510 seq_sep_trailing_allowed(token::Comma),
2511 |p| Ok(try!(p.parse_expr()))
2513 hi = self.last_span.hi;
2515 let nd = self.mk_call(e, es);
2516 e = self.mk_expr(lo, hi, nd, None);
2520 // Could be either an index expression or a slicing expression.
2521 token::OpenDelim(token::Bracket) => {
2523 let ix = try!(self.parse_expr());
2525 try!(self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket)));
2526 let index = self.mk_index(e, ix);
2527 e = self.mk_expr(lo, hi, index, None)
2535 // Parse unquoted tokens after a `$` in a token tree
2536 fn parse_unquoted(&mut self) -> PResult<'a, TokenTree> {
2537 let mut sp = self.span;
2538 let (name, namep) = match self.token {
2542 if self.token == token::OpenDelim(token::Paren) {
2543 let Spanned { node: seq, span: seq_span } = try!(self.parse_seq(
2544 &token::OpenDelim(token::Paren),
2545 &token::CloseDelim(token::Paren),
2547 |p| p.parse_token_tree()
2549 let (sep, repeat) = try!(self.parse_sep_and_kleene_op());
2550 let name_num = macro_parser::count_names(&seq);
2551 return Ok(TokenTree::Sequence(mk_sp(sp.lo, seq_span.hi),
2552 Rc::new(SequenceRepetition {
2556 num_captures: name_num
2558 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2560 return Ok(TokenTree::Token(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar)));
2562 sp = mk_sp(sp.lo, self.span.hi);
2563 let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2564 let name = try!(self.parse_ident());
2568 token::SubstNt(name, namep) => {
2574 // continue by trying to parse the `:ident` after `$name`
2575 if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2576 !t.is_strict_keyword() &&
2577 !t.is_reserved_keyword()) {
2579 sp = mk_sp(sp.lo, self.span.hi);
2580 let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2581 let nt_kind = try!(self.parse_ident());
2582 Ok(TokenTree::Token(sp, MatchNt(name, nt_kind, namep, kindp)))
2584 Ok(TokenTree::Token(sp, SubstNt(name, namep)))
2588 pub fn check_unknown_macro_variable(&mut self) {
2589 if self.quote_depth == 0 {
2591 token::SubstNt(name, _) =>
2592 self.fatal(&format!("unknown macro variable `{}`", name)).emit(),
2598 /// Parse an optional separator followed by a Kleene-style
2599 /// repetition token (+ or *).
2600 pub fn parse_sep_and_kleene_op(&mut self)
2601 -> PResult<'a, (Option<token::Token>, ast::KleeneOp)> {
2602 fn parse_kleene_op<'a>(parser: &mut Parser<'a>) -> PResult<'a, Option<ast::KleeneOp>> {
2603 match parser.token {
2604 token::BinOp(token::Star) => {
2606 Ok(Some(ast::ZeroOrMore))
2608 token::BinOp(token::Plus) => {
2610 Ok(Some(ast::OneOrMore))
2616 match try!(parse_kleene_op(self)) {
2617 Some(kleene_op) => return Ok((None, kleene_op)),
2621 let separator = self.bump_and_get();
2622 match try!(parse_kleene_op(self)) {
2623 Some(zerok) => Ok((Some(separator), zerok)),
2624 None => return Err(self.fatal("expected `*` or `+`"))
2628 /// parse a single token tree from the input.
2629 pub fn parse_token_tree(&mut self) -> PResult<'a, TokenTree> {
2630 // FIXME #6994: currently, this is too eager. It
2631 // parses token trees but also identifies TokenType::Sequence's
2632 // and token::SubstNt's; it's too early to know yet
2633 // whether something will be a nonterminal or a seq
2635 maybe_whole!(deref self, NtTT);
2637 // this is the fall-through for the 'match' below.
2638 // invariants: the current token is not a left-delimiter,
2639 // not an EOF, and not the desired right-delimiter (if
2640 // it were, parse_seq_to_before_end would have prevented
2641 // reaching this point.
2642 fn parse_non_delim_tt_tok<'b>(p: &mut Parser<'b>) -> PResult<'b, TokenTree> {
2643 maybe_whole!(deref p, NtTT);
2645 token::CloseDelim(_) => {
2646 let token_str = p.this_token_to_string();
2647 let mut err = p.fatal(
2648 &format!("incorrect close delimiter: `{}`", token_str));
2649 // This is a conservative error: only report the last unclosed delimiter. The
2650 // previous unclosed delimiters could actually be closed! The parser just hasn't
2651 // gotten to them yet.
2652 if let Some(&sp) = p.open_braces.last() {
2653 err.span_note(sp, "unclosed delimiter");
2657 /* we ought to allow different depths of unquotation */
2658 token::Dollar | token::SubstNt(..) if p.quote_depth > 0 => {
2662 Ok(TokenTree::Token(p.span, p.bump_and_get()))
2669 let open_braces = self.open_braces.clone();
2670 let mut err: DiagnosticBuilder<'a> =
2671 self.fatal("this file contains an un-closed delimiter");
2672 for sp in &open_braces {
2673 err.span_help(*sp, "did you mean to close this delimiter?");
2677 token::OpenDelim(delim) => {
2678 // The span for beginning of the delimited section
2679 let pre_span = self.span;
2681 // Parse the open delimiter.
2682 self.open_braces.push(self.span);
2683 let open_span = self.span;
2686 // Parse the token trees within the delimiters
2687 let tts = try!(self.parse_seq_to_before_end(
2688 &token::CloseDelim(delim),
2690 |p| p.parse_token_tree()
2693 // Parse the close delimiter.
2694 let close_span = self.span;
2696 self.open_braces.pop().unwrap();
2698 // Expand to cover the entire delimited token tree
2699 let span = Span { hi: close_span.hi, ..pre_span };
2701 Ok(TokenTree::Delimited(span, Rc::new(Delimited {
2703 open_span: open_span,
2705 close_span: close_span,
2708 _ => parse_non_delim_tt_tok(self),
2712 // parse a stream of tokens into a list of TokenTree's,
2714 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2715 let mut tts = Vec::new();
2716 while self.token != token::Eof {
2717 tts.push(try!(self.parse_token_tree()));
2722 /// Parse a prefix-unary-operator expr
2723 pub fn parse_prefix_expr(&mut self,
2724 already_parsed_attrs: Option<ThinAttributes>)
2725 -> PResult<'a, P<Expr>> {
2726 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2727 let lo = self.span.lo;
2729 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2730 let ex = match self.token {
2733 let e = self.parse_prefix_expr(None);
2734 let (span, e) = try!(self.interpolated_or_expr_span(e));
2736 self.mk_unary(UnOp::Not, e)
2738 token::BinOp(token::Minus) => {
2740 let e = self.parse_prefix_expr(None);
2741 let (span, e) = try!(self.interpolated_or_expr_span(e));
2743 self.mk_unary(UnOp::Neg, e)
2745 token::BinOp(token::Star) => {
2747 let e = self.parse_prefix_expr(None);
2748 let (span, e) = try!(self.interpolated_or_expr_span(e));
2750 self.mk_unary(UnOp::Deref, e)
2752 token::BinOp(token::And) | token::AndAnd => {
2753 try!(self.expect_and());
2754 let m = try!(self.parse_mutability());
2755 let e = self.parse_prefix_expr(None);
2756 let (span, e) = try!(self.interpolated_or_expr_span(e));
2758 ExprKind::AddrOf(m, e)
2760 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2762 let place = try!(self.parse_expr_res(
2763 Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
2766 let blk = try!(self.parse_block());
2767 let span = blk.span;
2769 let blk_expr = self.mk_expr(span.lo, span.hi, ExprKind::Block(blk),
2771 ExprKind::InPlace(place, blk_expr)
2773 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2775 let e = self.parse_prefix_expr(None);
2776 let (span, e) = try!(self.interpolated_or_expr_span(e));
2780 _ => return self.parse_dot_or_call_expr(Some(attrs))
2782 return Ok(self.mk_expr(lo, hi, ex, attrs));
2785 /// Parse an associative expression
2787 /// This parses an expression accounting for associativity and precedence of the operators in
2789 pub fn parse_assoc_expr(&mut self,
2790 already_parsed_attrs: Option<ThinAttributes>)
2791 -> PResult<'a, P<Expr>> {
2792 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2795 /// Parse an associative expression with operators of at least `min_prec` precedence
2796 pub fn parse_assoc_expr_with(&mut self,
2799 -> PResult<'a, P<Expr>> {
2800 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2803 let attrs = match lhs {
2804 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2807 if self.token == token::DotDot {
2808 return self.parse_prefix_range_expr(attrs);
2810 try!(self.parse_prefix_expr(attrs))
2815 if self.expr_is_complete(&*lhs) {
2816 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2819 self.expected_tokens.push(TokenType::Operator);
2820 while let Some(op) = AssocOp::from_token(&self.token) {
2822 let lhs_span = if self.last_token_interpolated {
2828 let cur_op_span = self.span;
2829 let restrictions = if op.is_assign_like() {
2830 self.restrictions & Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2834 if op.precedence() < min_prec {
2838 if op.is_comparison() {
2839 self.check_no_chained_comparison(&*lhs, &op);
2842 if op == AssocOp::As {
2843 let rhs = try!(self.parse_ty());
2844 lhs = self.mk_expr(lhs_span.lo, rhs.span.hi,
2845 ExprKind::Cast(lhs, rhs), None);
2847 } else if op == AssocOp::Colon {
2848 let rhs = try!(self.parse_ty());
2849 lhs = self.mk_expr(lhs_span.lo, rhs.span.hi,
2850 ExprKind::Type(lhs, rhs), None);
2852 } else if op == AssocOp::DotDot {
2853 // If we didn’t have to handle `x..`, it would be pretty easy to generalise
2854 // it to the Fixity::None code.
2856 // We have 2 alternatives here: `x..y` and `x..` The other two variants are
2857 // handled with `parse_prefix_range_expr` call above.
2858 let rhs = if self.is_at_start_of_range_notation_rhs() {
2859 let rhs = self.parse_assoc_expr_with(op.precedence() + 1,
2860 LhsExpr::NotYetParsed);
2871 let (lhs_span, rhs_span) = (lhs_span, if let Some(ref x) = rhs {
2876 let r = self.mk_range(Some(lhs), rhs);
2877 lhs = self.mk_expr(lhs_span.lo, rhs_span.hi, r, None);
2881 let rhs = try!(match op.fixity() {
2882 Fixity::Right => self.with_res(
2883 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2885 this.parse_assoc_expr_with(op.precedence(),
2886 LhsExpr::NotYetParsed)
2888 Fixity::Left => self.with_res(
2889 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2891 this.parse_assoc_expr_with(op.precedence() + 1,
2892 LhsExpr::NotYetParsed)
2894 // We currently have no non-associative operators that are not handled above by
2895 // the special cases. The code is here only for future convenience.
2896 Fixity::None => self.with_res(
2897 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2899 this.parse_assoc_expr_with(op.precedence() + 1,
2900 LhsExpr::NotYetParsed)
2905 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2906 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2907 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2908 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2909 AssocOp::Greater | AssocOp::GreaterEqual => {
2910 let ast_op = op.to_ast_binop().unwrap();
2911 let (lhs_span, rhs_span) = (lhs_span, rhs.span);
2912 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2913 self.mk_expr(lhs_span.lo, rhs_span.hi, binary, None)
2916 self.mk_expr(lhs_span.lo, rhs.span.hi, ExprKind::Assign(lhs, rhs), None),
2918 self.mk_expr(lhs_span.lo, rhs.span.hi, ExprKind::InPlace(lhs, rhs), None),
2919 AssocOp::AssignOp(k) => {
2921 token::Plus => BinOpKind::Add,
2922 token::Minus => BinOpKind::Sub,
2923 token::Star => BinOpKind::Mul,
2924 token::Slash => BinOpKind::Div,
2925 token::Percent => BinOpKind::Rem,
2926 token::Caret => BinOpKind::BitXor,
2927 token::And => BinOpKind::BitAnd,
2928 token::Or => BinOpKind::BitOr,
2929 token::Shl => BinOpKind::Shl,
2930 token::Shr => BinOpKind::Shr,
2932 let (lhs_span, rhs_span) = (lhs_span, rhs.span);
2933 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2934 self.mk_expr(lhs_span.lo, rhs_span.hi, aopexpr, None)
2936 AssocOp::As | AssocOp::Colon | AssocOp::DotDot => {
2937 self.bug("As, Colon or DotDot branch reached")
2941 if op.fixity() == Fixity::None { break }
2946 /// Produce an error if comparison operators are chained (RFC #558).
2947 /// We only need to check lhs, not rhs, because all comparison ops
2948 /// have same precedence and are left-associative
2949 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2950 debug_assert!(outer_op.is_comparison());
2952 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
2953 // respan to include both operators
2954 let op_span = mk_sp(op.span.lo, self.span.hi);
2955 let mut err = self.diagnostic().struct_span_err(op_span,
2956 "chained comparison operators require parentheses");
2957 if op.node == BinOpKind::Lt && *outer_op == AssocOp::Greater {
2958 err.fileline_help(op_span,
2959 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2967 /// Parse prefix-forms of range notation: `..expr` and `..`
2968 fn parse_prefix_range_expr(&mut self,
2969 already_parsed_attrs: Option<ThinAttributes>)
2970 -> PResult<'a, P<Expr>> {
2971 debug_assert!(self.token == token::DotDot);
2972 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2973 let lo = self.span.lo;
2974 let mut hi = self.span.hi;
2976 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2977 // RHS must be parsed with more associativity than DotDot.
2978 let next_prec = AssocOp::from_token(&token::DotDot).unwrap().precedence() + 1;
2979 Some(try!(self.parse_assoc_expr_with(next_prec,
2980 LhsExpr::NotYetParsed)
2988 let r = self.mk_range(None, opt_end);
2989 Ok(self.mk_expr(lo, hi, r, attrs))
2992 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2993 if self.token.can_begin_expr() {
2994 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2995 if self.token == token::OpenDelim(token::Brace) {
2996 return !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL);
3004 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3005 pub fn parse_if_expr(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3006 if self.check_keyword(keywords::Let) {
3007 return self.parse_if_let_expr(attrs);
3009 let lo = self.last_span.lo;
3010 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3011 let thn = try!(self.parse_block());
3012 let mut els: Option<P<Expr>> = None;
3013 let mut hi = thn.span.hi;
3014 if self.eat_keyword(keywords::Else) {
3015 let elexpr = try!(self.parse_else_expr());
3016 hi = elexpr.span.hi;
3019 Ok(self.mk_expr(lo, hi, ExprKind::If(cond, thn, els), attrs))
3022 /// Parse an 'if let' expression ('if' token already eaten)
3023 pub fn parse_if_let_expr(&mut self, attrs: ThinAttributes)
3024 -> PResult<'a, P<Expr>> {
3025 let lo = self.last_span.lo;
3026 try!(self.expect_keyword(keywords::Let));
3027 let pat = try!(self.parse_pat());
3028 try!(self.expect(&token::Eq));
3029 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3030 let thn = try!(self.parse_block());
3031 let (hi, els) = if self.eat_keyword(keywords::Else) {
3032 let expr = try!(self.parse_else_expr());
3033 (expr.span.hi, Some(expr))
3037 Ok(self.mk_expr(lo, hi, ExprKind::IfLet(pat, expr, thn, els), attrs))
3041 pub fn parse_lambda_expr(&mut self, lo: BytePos,
3042 capture_clause: CaptureBy,
3043 attrs: ThinAttributes)
3044 -> PResult<'a, P<Expr>>
3046 let decl = try!(self.parse_fn_block_decl());
3047 let body = match decl.output {
3048 FunctionRetTy::Default(_) => {
3049 // If no explicit return type is given, parse any
3050 // expr and wrap it up in a dummy block:
3051 let body_expr = try!(self.parse_expr());
3053 id: ast::DUMMY_NODE_ID,
3055 span: body_expr.span,
3056 expr: Some(body_expr),
3057 rules: BlockCheckMode::Default,
3061 // If an explicit return type is given, require a
3062 // block to appear (RFC 968).
3063 try!(self.parse_block())
3070 ExprKind::Closure(capture_clause, decl, body), attrs))
3073 // `else` token already eaten
3074 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3075 if self.eat_keyword(keywords::If) {
3076 return self.parse_if_expr(None);
3078 let blk = try!(self.parse_block());
3079 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprKind::Block(blk), None));
3083 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3084 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>,
3086 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3087 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3089 let pat = try!(self.parse_pat());
3090 try!(self.expect_keyword(keywords::In));
3091 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3092 let (iattrs, loop_block) = try!(self.parse_inner_attrs_and_block());
3093 let attrs = attrs.append(iattrs.into_thin_attrs());
3095 let hi = self.last_span.hi;
3097 Ok(self.mk_expr(span_lo, hi,
3098 ExprKind::ForLoop(pat, expr, loop_block, opt_ident),
3102 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3103 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>,
3105 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3106 if self.token.is_keyword(keywords::Let) {
3107 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3109 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3110 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3111 let attrs = attrs.append(iattrs.into_thin_attrs());
3112 let hi = body.span.hi;
3113 return Ok(self.mk_expr(span_lo, hi, ExprKind::While(cond, body, opt_ident),
3117 /// Parse a 'while let' expression ('while' token already eaten)
3118 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>,
3120 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3121 try!(self.expect_keyword(keywords::Let));
3122 let pat = try!(self.parse_pat());
3123 try!(self.expect(&token::Eq));
3124 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3125 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3126 let attrs = attrs.append(iattrs.into_thin_attrs());
3127 let hi = body.span.hi;
3128 return Ok(self.mk_expr(span_lo, hi, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3131 // parse `loop {...}`, `loop` token already eaten
3132 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>,
3134 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3135 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3136 let attrs = attrs.append(iattrs.into_thin_attrs());
3137 let hi = body.span.hi;
3138 Ok(self.mk_expr(span_lo, hi, ExprKind::Loop(body, opt_ident), attrs))
3141 // `match` token already eaten
3142 fn parse_match_expr(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3143 let match_span = self.last_span;
3144 let lo = self.last_span.lo;
3145 let discriminant = try!(self.parse_expr_res(
3146 Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3147 if let Err(mut e) = self.commit_expr_expecting(&*discriminant,
3148 token::OpenDelim(token::Brace)) {
3149 if self.token == token::Token::Semi {
3150 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3154 let attrs = attrs.append(
3155 try!(self.parse_inner_attributes()).into_thin_attrs());
3156 let mut arms: Vec<Arm> = Vec::new();
3157 while self.token != token::CloseDelim(token::Brace) {
3158 arms.push(try!(self.parse_arm()));
3160 let hi = self.span.hi;
3162 return Ok(self.mk_expr(lo, hi, ExprKind::Match(discriminant, arms), attrs));
3165 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3166 maybe_whole!(no_clone self, NtArm);
3168 let attrs = try!(self.parse_outer_attributes());
3169 let pats = try!(self.parse_pats());
3170 let mut guard = None;
3171 if self.eat_keyword(keywords::If) {
3172 guard = Some(try!(self.parse_expr()));
3174 try!(self.expect(&token::FatArrow));
3175 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR, None));
3178 !classify::expr_is_simple_block(&*expr)
3179 && self.token != token::CloseDelim(token::Brace);
3182 try!(self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]));
3184 self.eat(&token::Comma);
3195 /// Parse an expression
3196 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3197 self.parse_expr_res(Restrictions::empty(), None)
3200 /// Evaluate the closure with restrictions in place.
3202 /// After the closure is evaluated, restrictions are reset.
3203 pub fn with_res<F>(&mut self, r: Restrictions, f: F) -> PResult<'a, P<Expr>>
3204 where F: FnOnce(&mut Self) -> PResult<'a, P<Expr>>
3206 let old = self.restrictions;
3207 self.restrictions = r;
3209 self.restrictions = old;
3214 /// Parse an expression, subject to the given restrictions
3215 pub fn parse_expr_res(&mut self, r: Restrictions,
3216 already_parsed_attrs: Option<ThinAttributes>)
3217 -> PResult<'a, P<Expr>> {
3218 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3221 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3222 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3223 if self.check(&token::Eq) {
3225 Ok(Some(try!(self.parse_expr())))
3231 /// Parse patterns, separated by '|' s
3232 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3233 let mut pats = Vec::new();
3235 pats.push(try!(self.parse_pat()));
3236 if self.check(&token::BinOp(token::Or)) { self.bump();}
3237 else { return Ok(pats); }
3241 fn parse_pat_tuple_elements(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3242 let mut fields = vec![];
3243 if !self.check(&token::CloseDelim(token::Paren)) {
3244 fields.push(try!(self.parse_pat()));
3245 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3246 while self.eat(&token::Comma) &&
3247 !self.check(&token::CloseDelim(token::Paren)) {
3248 fields.push(try!(self.parse_pat()));
3251 if fields.len() == 1 {
3252 try!(self.expect(&token::Comma));
3258 fn parse_pat_vec_elements(
3260 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3261 let mut before = Vec::new();
3262 let mut slice = None;
3263 let mut after = Vec::new();
3264 let mut first = true;
3265 let mut before_slice = true;
3267 while self.token != token::CloseDelim(token::Bracket) {
3271 try!(self.expect(&token::Comma));
3273 if self.token == token::CloseDelim(token::Bracket)
3274 && (before_slice || !after.is_empty()) {
3280 if self.check(&token::DotDot) {
3283 if self.check(&token::Comma) ||
3284 self.check(&token::CloseDelim(token::Bracket)) {
3285 slice = Some(P(ast::Pat {
3286 id: ast::DUMMY_NODE_ID,
3290 before_slice = false;
3296 let subpat = try!(self.parse_pat());
3297 if before_slice && self.check(&token::DotDot) {
3299 slice = Some(subpat);
3300 before_slice = false;
3301 } else if before_slice {
3302 before.push(subpat);
3308 Ok((before, slice, after))
3311 /// Parse the fields of a struct-like pattern
3312 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>> , bool)> {
3313 let mut fields = Vec::new();
3314 let mut etc = false;
3315 let mut first = true;
3316 while self.token != token::CloseDelim(token::Brace) {
3320 try!(self.expect(&token::Comma));
3321 // accept trailing commas
3322 if self.check(&token::CloseDelim(token::Brace)) { break }
3325 let lo = self.span.lo;
3328 if self.check(&token::DotDot) {
3330 if self.token != token::CloseDelim(token::Brace) {
3331 let token_str = self.this_token_to_string();
3332 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3339 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3340 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3341 // Parsing a pattern of the form "fieldname: pat"
3342 let fieldname = try!(self.parse_ident());
3344 let pat = try!(self.parse_pat());
3346 (pat, fieldname, false)
3348 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3349 let is_box = self.eat_keyword(keywords::Box);
3350 let boxed_span_lo = self.span.lo;
3351 let is_ref = self.eat_keyword(keywords::Ref);
3352 let is_mut = self.eat_keyword(keywords::Mut);
3353 let fieldname = try!(self.parse_ident());
3354 hi = self.last_span.hi;
3356 let bind_type = match (is_ref, is_mut) {
3357 (true, true) => BindingMode::ByRef(MutMutable),
3358 (true, false) => BindingMode::ByRef(MutImmutable),
3359 (false, true) => BindingMode::ByValue(MutMutable),
3360 (false, false) => BindingMode::ByValue(MutImmutable),
3362 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3363 let fieldpat = P(ast::Pat{
3364 id: ast::DUMMY_NODE_ID,
3365 node: PatIdent(bind_type, fieldpath, None),
3366 span: mk_sp(boxed_span_lo, hi),
3369 let subpat = if is_box {
3371 id: ast::DUMMY_NODE_ID,
3372 node: PatBox(fieldpat),
3373 span: mk_sp(lo, hi),
3378 (subpat, fieldname, true)
3381 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3382 node: ast::FieldPat { ident: fieldname,
3384 is_shorthand: is_shorthand }});
3386 return Ok((fields, etc));
3389 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3390 if self.is_path_start() {
3391 let lo = self.span.lo;
3392 let (qself, path) = if self.eat_lt() {
3393 // Parse a qualified path
3395 try!(self.parse_qualified_path(NoTypesAllowed));
3398 // Parse an unqualified path
3399 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3401 let hi = self.last_span.hi;
3402 Ok(self.mk_expr(lo, hi, ExprKind::Path(qself, path), None))
3404 self.parse_pat_literal_maybe_minus()
3408 fn is_path_start(&self) -> bool {
3409 (self.token == token::Lt || self.token == token::ModSep
3410 || self.token.is_ident() || self.token.is_path())
3411 && !self.token.is_keyword(keywords::True) && !self.token.is_keyword(keywords::False)
3414 /// Parse a pattern.
3415 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3416 maybe_whole!(self, NtPat);
3418 let lo = self.span.lo;
3421 token::Underscore => {
3426 token::BinOp(token::And) | token::AndAnd => {
3427 // Parse &pat / &mut pat
3428 try!(self.expect_and());
3429 let mutbl = try!(self.parse_mutability());
3430 if let token::Lifetime(ident) = self.token {
3431 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3434 let subpat = try!(self.parse_pat());
3435 pat = PatRegion(subpat, mutbl);
3437 token::OpenDelim(token::Paren) => {
3438 // Parse (pat,pat,pat,...) as tuple pattern
3440 let fields = try!(self.parse_pat_tuple_elements());
3441 try!(self.expect(&token::CloseDelim(token::Paren)));
3442 pat = PatTup(fields);
3444 token::OpenDelim(token::Bracket) => {
3445 // Parse [pat,pat,...] as slice pattern
3447 let (before, slice, after) = try!(self.parse_pat_vec_elements());
3448 try!(self.expect(&token::CloseDelim(token::Bracket)));
3449 pat = PatVec(before, slice, after);
3452 // At this point, token != _, &, &&, (, [
3453 if self.eat_keyword(keywords::Mut) {
3454 // Parse mut ident @ pat
3455 pat = try!(self.parse_pat_ident(BindingMode::ByValue(MutMutable)));
3456 } else if self.eat_keyword(keywords::Ref) {
3457 // Parse ref ident @ pat / ref mut ident @ pat
3458 let mutbl = try!(self.parse_mutability());
3459 pat = try!(self.parse_pat_ident(BindingMode::ByRef(mutbl)));
3460 } else if self.eat_keyword(keywords::Box) {
3462 let subpat = try!(self.parse_pat());
3463 pat = PatBox(subpat);
3464 } else if self.is_path_start() {
3465 // Parse pattern starting with a path
3466 if self.token.is_plain_ident() && self.look_ahead(1, |t| *t != token::DotDotDot &&
3467 *t != token::OpenDelim(token::Brace) &&
3468 *t != token::OpenDelim(token::Paren) &&
3469 // Contrary to its definition, a plain ident can be followed by :: in macros
3470 *t != token::ModSep) {
3471 // Plain idents have some extra abilities here compared to general paths
3472 if self.look_ahead(1, |t| *t == token::Not) {
3473 // Parse macro invocation
3474 let ident = try!(self.parse_ident());
3475 let ident_span = self.last_span;
3476 let path = ident_to_path(ident_span, ident);
3478 let delim = try!(self.expect_open_delim());
3479 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
3480 seq_sep_none(), |p| p.parse_token_tree()));
3481 let mac = Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT };
3482 pat = PatMac(codemap::Spanned {node: mac,
3483 span: mk_sp(lo, self.last_span.hi)});
3485 // Parse ident @ pat
3486 // This can give false positives and parse nullary enums,
3487 // they are dealt with later in resolve
3488 pat = try!(self.parse_pat_ident(BindingMode::ByValue(MutImmutable)));
3491 let (qself, path) = if self.eat_lt() {
3492 // Parse a qualified path
3494 try!(self.parse_qualified_path(NoTypesAllowed));
3497 // Parse an unqualified path
3498 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3501 token::DotDotDot => {
3503 let hi = self.last_span.hi;
3504 let begin = self.mk_expr(lo, hi, ExprKind::Path(qself, path), None);
3506 let end = try!(self.parse_pat_range_end());
3507 pat = PatRange(begin, end);
3509 token::OpenDelim(token::Brace) => {
3510 if qself.is_some() {
3511 return Err(self.fatal("unexpected `{` after qualified path"));
3513 // Parse struct pattern
3515 let (fields, etc) = try!(self.parse_pat_fields());
3517 pat = PatStruct(path, fields, etc);
3519 token::OpenDelim(token::Paren) => {
3520 if qself.is_some() {
3521 return Err(self.fatal("unexpected `(` after qualified path"));
3523 // Parse tuple struct or enum pattern
3524 if self.look_ahead(1, |t| *t == token::DotDot) {
3525 // This is a "top constructor only" pat
3528 try!(self.expect(&token::CloseDelim(token::Paren)));
3529 pat = PatEnum(path, None);
3531 let args = try!(self.parse_enum_variant_seq(
3532 &token::OpenDelim(token::Paren),
3533 &token::CloseDelim(token::Paren),
3534 seq_sep_trailing_allowed(token::Comma),
3535 |p| p.parse_pat()));
3536 pat = PatEnum(path, Some(args));
3541 // Parse qualified path
3542 Some(qself) => PatQPath(qself, path),
3543 // Parse nullary enum
3544 None => PatEnum(path, Some(vec![]))
3550 // Try to parse everything else as literal with optional minus
3551 let begin = try!(self.parse_pat_literal_maybe_minus());
3552 if self.eat(&token::DotDotDot) {
3553 let end = try!(self.parse_pat_range_end());
3554 pat = PatRange(begin, end);
3556 pat = PatLit(begin);
3562 let hi = self.last_span.hi;
3564 id: ast::DUMMY_NODE_ID,
3566 span: mk_sp(lo, hi),
3570 /// Parse ident or ident @ pat
3571 /// used by the copy foo and ref foo patterns to give a good
3572 /// error message when parsing mistakes like ref foo(a,b)
3573 fn parse_pat_ident(&mut self,
3574 binding_mode: ast::BindingMode)
3575 -> PResult<'a, ast::Pat_> {
3576 if !self.token.is_plain_ident() {
3577 let span = self.span;
3578 let tok_str = self.this_token_to_string();
3579 return Err(self.span_fatal(span,
3580 &format!("expected identifier, found `{}`", tok_str)))
3582 let ident = try!(self.parse_ident());
3583 let last_span = self.last_span;
3584 let name = codemap::Spanned{span: last_span, node: ident};
3585 let sub = if self.eat(&token::At) {
3586 Some(try!(self.parse_pat()))
3591 // just to be friendly, if they write something like
3593 // we end up here with ( as the current token. This shortly
3594 // leads to a parse error. Note that if there is no explicit
3595 // binding mode then we do not end up here, because the lookahead
3596 // will direct us over to parse_enum_variant()
3597 if self.token == token::OpenDelim(token::Paren) {
3598 let last_span = self.last_span;
3599 return Err(self.span_fatal(
3601 "expected identifier, found enum pattern"))
3604 Ok(PatIdent(binding_mode, name, sub))
3607 /// Parse a local variable declaration
3608 fn parse_local(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Local>> {
3609 let lo = self.span.lo;
3610 let pat = try!(self.parse_pat());
3613 if self.eat(&token::Colon) {
3614 ty = Some(try!(self.parse_ty_sum()));
3616 let init = try!(self.parse_initializer());
3621 id: ast::DUMMY_NODE_ID,
3622 span: mk_sp(lo, self.last_span.hi),
3627 /// Parse a "let" stmt
3628 fn parse_let(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Decl>> {
3629 let lo = self.span.lo;
3630 let local = try!(self.parse_local(attrs));
3631 Ok(P(spanned(lo, self.last_span.hi, DeclKind::Local(local))))
3634 /// Parse a structure field
3635 fn parse_name_and_ty(&mut self, pr: Visibility,
3636 attrs: Vec<Attribute> ) -> PResult<'a, StructField> {
3638 Inherited => self.span.lo,
3639 Public => self.last_span.lo,
3641 if !self.token.is_plain_ident() {
3642 return Err(self.fatal("expected ident"));
3644 let name = try!(self.parse_ident());
3645 try!(self.expect(&token::Colon));
3646 let ty = try!(self.parse_ty_sum());
3647 Ok(spanned(lo, self.last_span.hi, ast::StructField_ {
3648 kind: NamedField(name, pr),
3649 id: ast::DUMMY_NODE_ID,
3655 /// Emit an expected item after attributes error.
3656 fn expected_item_err(&self, attrs: &[Attribute]) {
3657 let message = match attrs.last() {
3658 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3659 "expected item after doc comment"
3661 _ => "expected item after attributes",
3664 self.span_err(self.last_span, message);
3667 /// Parse a statement. may include decl.
3668 pub fn parse_stmt(&mut self) -> PResult<'a, Option<P<Stmt>>> {
3669 Ok(try!(self.parse_stmt_()).map(P))
3672 fn parse_stmt_(&mut self) -> PResult<'a, Option<Stmt>> {
3673 maybe_whole!(Some deref self, NtStmt);
3675 let attrs = try!(self.parse_outer_attributes());
3676 let lo = self.span.lo;
3678 Ok(Some(if self.check_keyword(keywords::Let) {
3679 try!(self.expect_keyword(keywords::Let));
3680 let decl = try!(self.parse_let(attrs.into_thin_attrs()));
3681 let hi = decl.span.hi;
3682 let stmt = StmtDecl(decl, ast::DUMMY_NODE_ID);
3683 spanned(lo, hi, stmt)
3684 } else if self.token.is_ident()
3685 && !self.token.is_any_keyword()
3686 && self.look_ahead(1, |t| *t == token::Not) {
3687 // it's a macro invocation:
3689 // Potential trouble: if we allow macros with paths instead of
3690 // idents, we'd need to look ahead past the whole path here...
3691 let pth = try!(self.parse_path(NoTypesAllowed));
3694 let id = match self.token {
3695 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3696 _ => try!(self.parse_ident()),
3699 // check that we're pointing at delimiters (need to check
3700 // again after the `if`, because of `parse_ident`
3701 // consuming more tokens).
3702 let delim = match self.token {
3703 token::OpenDelim(delim) => delim,
3705 // we only expect an ident if we didn't parse one
3707 let ident_str = if id.name == token::special_idents::invalid.name {
3712 let tok_str = self.this_token_to_string();
3713 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3719 let tts = try!(self.parse_unspanned_seq(
3720 &token::OpenDelim(delim),
3721 &token::CloseDelim(delim),
3723 |p| p.parse_token_tree()
3725 let hi = self.last_span.hi;
3727 let style = if delim == token::Brace {
3730 MacStmtWithoutBraces
3733 if id.name == token::special_idents::invalid.name {
3734 let stmt = StmtMac(P(spanned(lo,
3736 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3738 attrs.into_thin_attrs());
3739 spanned(lo, hi, stmt)
3741 // if it has a special ident, it's definitely an item
3743 // Require a semicolon or braces.
3744 if style != MacStmtWithBraces {
3745 if !self.eat(&token::Semi) {
3746 let last_span = self.last_span;
3747 self.span_err(last_span,
3748 "macros that expand to items must \
3749 either be surrounded with braces or \
3750 followed by a semicolon");
3753 spanned(lo, hi, StmtDecl(
3754 P(spanned(lo, hi, DeclKind::Item(
3756 lo, hi, id /*id is good here*/,
3757 ItemMac(spanned(lo, hi,
3758 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3759 Inherited, attrs)))),
3760 ast::DUMMY_NODE_ID))
3763 // FIXME: Bad copy of attrs
3764 match try!(self.parse_item_(attrs.clone(), false, true)) {
3767 let decl = P(spanned(lo, hi, DeclKind::Item(i)));
3768 spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3771 let unused_attrs = |attrs: &[_], s: &mut Self| {
3772 if attrs.len() > 0 {
3774 "expected statement after outer attribute");
3778 // Do not attempt to parse an expression if we're done here.
3779 if self.token == token::Semi {
3780 unused_attrs(&attrs, self);
3785 if self.token == token::CloseDelim(token::Brace) {
3786 unused_attrs(&attrs, self);
3790 // Remainder are line-expr stmts.
3791 let e = try!(self.parse_expr_res(
3792 Restrictions::RESTRICTION_STMT_EXPR, Some(attrs.into_thin_attrs())));
3794 let stmt = StmtExpr(e, ast::DUMMY_NODE_ID);
3795 spanned(lo, hi, stmt)
3801 /// Is this expression a successfully-parsed statement?
3802 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3803 self.restrictions.contains(Restrictions::RESTRICTION_STMT_EXPR) &&
3804 !classify::expr_requires_semi_to_be_stmt(e)
3807 /// Parse a block. No inner attrs are allowed.
3808 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
3809 maybe_whole!(no_clone self, NtBlock);
3811 let lo = self.span.lo;
3813 if !self.eat(&token::OpenDelim(token::Brace)) {
3815 let tok = self.this_token_to_string();
3816 return Err(self.span_fatal_help(sp,
3817 &format!("expected `{{`, found `{}`", tok),
3818 "place this code inside a block"));
3821 self.parse_block_tail(lo, BlockCheckMode::Default)
3824 /// Parse a block. Inner attrs are allowed.
3825 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
3826 maybe_whole!(pair_empty self, NtBlock);
3828 let lo = self.span.lo;
3829 try!(self.expect(&token::OpenDelim(token::Brace)));
3830 Ok((try!(self.parse_inner_attributes()),
3831 try!(self.parse_block_tail(lo, BlockCheckMode::Default))))
3834 /// Parse the rest of a block expression or function body
3835 /// Precondition: already parsed the '{'.
3836 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> PResult<'a, P<Block>> {
3837 let mut stmts = vec![];
3838 let mut expr = None;
3840 while !self.eat(&token::CloseDelim(token::Brace)) {
3841 let Spanned {node, span} = if let Some(s) = try!(self.parse_stmt_()) {
3844 // Found only `;` or `}`.
3849 try!(self.handle_expression_like_statement(e, span, &mut stmts, &mut expr));
3851 StmtMac(mac, MacStmtWithoutBraces, attrs) => {
3852 // statement macro without braces; might be an
3853 // expr depending on whether a semicolon follows
3856 stmts.push(P(Spanned {
3857 node: StmtMac(mac, MacStmtWithSemicolon, attrs),
3858 span: mk_sp(span.lo, self.span.hi),
3863 let e = self.mk_mac_expr(span.lo, span.hi,
3864 mac.and_then(|m| m.node),
3867 let e = try!(self.parse_dot_or_call_expr_with(e, lo, attrs));
3868 let e = try!(self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e)));
3869 try!(self.handle_expression_like_statement(
3877 StmtMac(m, style, attrs) => {
3878 // statement macro; might be an expr
3881 stmts.push(P(Spanned {
3882 node: StmtMac(m, MacStmtWithSemicolon, attrs),
3883 span: mk_sp(span.lo, self.span.hi),
3887 token::CloseDelim(token::Brace) => {
3888 // if a block ends in `m!(arg)` without
3889 // a `;`, it must be an expr
3890 expr = Some(self.mk_mac_expr(span.lo, span.hi,
3891 m.and_then(|x| x.node),
3895 stmts.push(P(Spanned {
3896 node: StmtMac(m, style, attrs),
3902 _ => { // all other kinds of statements:
3903 let mut hi = span.hi;
3904 if classify::stmt_ends_with_semi(&node) {
3905 try!(self.commit_stmt_expecting(token::Semi));
3906 hi = self.last_span.hi;
3909 stmts.push(P(Spanned {
3911 span: mk_sp(span.lo, hi)
3920 id: ast::DUMMY_NODE_ID,
3922 span: mk_sp(lo, self.last_span.hi),
3926 fn handle_expression_like_statement(
3930 stmts: &mut Vec<P<Stmt>>,
3931 last_block_expr: &mut Option<P<Expr>>) -> PResult<'a, ()> {
3932 // expression without semicolon
3933 if classify::expr_requires_semi_to_be_stmt(&*e) {
3934 // Just check for errors and recover; do not eat semicolon yet.
3935 try!(self.commit_stmt(&[],
3936 &[token::Semi, token::CloseDelim(token::Brace)]));
3942 let span_with_semi = Span {
3944 hi: self.last_span.hi,
3945 expn_id: span.expn_id,
3947 stmts.push(P(Spanned {
3948 node: StmtSemi(e, ast::DUMMY_NODE_ID),
3949 span: span_with_semi,
3952 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3954 stmts.push(P(Spanned {
3955 node: StmtExpr(e, ast::DUMMY_NODE_ID),
3963 // Parses a sequence of bounds if a `:` is found,
3964 // otherwise returns empty list.
3965 fn parse_colon_then_ty_param_bounds(&mut self,
3966 mode: BoundParsingMode)
3967 -> PResult<'a, TyParamBounds>
3969 if !self.eat(&token::Colon) {
3972 self.parse_ty_param_bounds(mode)
3976 // matches bounds = ( boundseq )?
3977 // where boundseq = ( polybound + boundseq ) | polybound
3978 // and polybound = ( 'for' '<' 'region '>' )? bound
3979 // and bound = 'region | trait_ref
3980 fn parse_ty_param_bounds(&mut self,
3981 mode: BoundParsingMode)
3982 -> PResult<'a, TyParamBounds>
3984 let mut result = vec!();
3986 let question_span = self.span;
3987 let ate_question = self.eat(&token::Question);
3989 token::Lifetime(lifetime) => {
3991 self.span_err(question_span,
3992 "`?` may only modify trait bounds, not lifetime bounds");
3994 result.push(RegionTyParamBound(ast::Lifetime {
3995 id: ast::DUMMY_NODE_ID,
4001 token::ModSep | token::Ident(..) => {
4002 let poly_trait_ref = try!(self.parse_poly_trait_ref());
4003 let modifier = if ate_question {
4004 if mode == BoundParsingMode::Modified {
4005 TraitBoundModifier::Maybe
4007 self.span_err(question_span,
4009 TraitBoundModifier::None
4012 TraitBoundModifier::None
4014 result.push(TraitTyParamBound(poly_trait_ref, modifier))
4019 if !self.eat(&token::BinOp(token::Plus)) {
4024 return Ok(P::from_vec(result));
4027 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4028 fn parse_ty_param(&mut self) -> PResult<'a, TyParam> {
4029 let span = self.span;
4030 let ident = try!(self.parse_ident());
4032 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified));
4034 let default = if self.check(&token::Eq) {
4036 Some(try!(self.parse_ty_sum()))
4043 id: ast::DUMMY_NODE_ID,
4050 /// Parse a set of optional generic type parameter declarations. Where
4051 /// clauses are not parsed here, and must be added later via
4052 /// `parse_where_clause()`.
4054 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4055 /// | ( < lifetimes , typaramseq ( , )? > )
4056 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4057 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4058 maybe_whole!(self, NtGenerics);
4060 if self.eat(&token::Lt) {
4061 let lifetime_defs = try!(self.parse_lifetime_defs());
4062 let mut seen_default = false;
4063 let ty_params = try!(self.parse_seq_to_gt(Some(token::Comma), |p| {
4064 try!(p.forbid_lifetime());
4065 let ty_param = try!(p.parse_ty_param());
4066 if ty_param.default.is_some() {
4067 seen_default = true;
4068 } else if seen_default {
4069 let last_span = p.last_span;
4070 p.span_err(last_span,
4071 "type parameters with a default must be trailing");
4076 lifetimes: lifetime_defs,
4077 ty_params: ty_params,
4078 where_clause: WhereClause {
4079 id: ast::DUMMY_NODE_ID,
4080 predicates: Vec::new(),
4084 Ok(ast::Generics::default())
4088 fn parse_generic_values_after_lt(&mut self) -> PResult<'a, (Vec<ast::Lifetime>,
4090 Vec<P<TypeBinding>>)> {
4091 let span_lo = self.span.lo;
4092 let lifetimes = try!(self.parse_lifetimes(token::Comma));
4094 let missing_comma = !lifetimes.is_empty() &&
4095 !self.token.is_like_gt() &&
4097 .as_ref().map_or(true,
4098 |x| &**x != &token::Comma);
4102 let msg = format!("expected `,` or `>` after lifetime \
4104 self.this_token_to_string());
4105 let mut err = self.diagnostic().struct_span_err(self.span, &msg);
4107 let span_hi = self.span.hi;
4108 let span_hi = match self.parse_ty() {
4109 Ok(..) => self.span.hi,
4110 Err(ref mut err) => {
4116 let msg = format!("did you mean a single argument type &'a Type, \
4117 or did you mean the comma-separated arguments \
4119 err.span_note(mk_sp(span_lo, span_hi), &msg);
4123 // First parse types.
4124 let (types, returned) = try!(self.parse_seq_to_gt_or_return(
4127 try!(p.forbid_lifetime());
4128 if p.look_ahead(1, |t| t == &token::Eq) {
4131 Ok(Some(try!(p.parse_ty_sum())))
4136 // If we found the `>`, don't continue.
4138 return Ok((lifetimes, types.into_vec(), Vec::new()));
4141 // Then parse type bindings.
4142 let bindings = try!(self.parse_seq_to_gt(
4145 try!(p.forbid_lifetime());
4147 let ident = try!(p.parse_ident());
4148 let found_eq = p.eat(&token::Eq);
4151 p.span_warn(span, "whoops, no =?");
4153 let ty = try!(p.parse_ty());
4154 let hi = ty.span.hi;
4155 let span = mk_sp(lo, hi);
4156 return Ok(P(TypeBinding{id: ast::DUMMY_NODE_ID,
4163 Ok((lifetimes, types.into_vec(), bindings.into_vec()))
4166 fn forbid_lifetime(&mut self) -> PResult<'a, ()> {
4167 if self.token.is_lifetime() {
4168 let span = self.span;
4169 return Err(self.span_fatal(span, "lifetime parameters must be declared \
4170 prior to type parameters"))
4175 /// Parses an optional `where` clause and places it in `generics`.
4178 /// where T : Trait<U, V> + 'b, 'a : 'b
4180 pub fn parse_where_clause(&mut self) -> PResult<'a, ast::WhereClause> {
4181 maybe_whole!(self, NtWhereClause);
4183 let mut where_clause = WhereClause {
4184 id: ast::DUMMY_NODE_ID,
4185 predicates: Vec::new(),
4188 if !self.eat_keyword(keywords::Where) {
4189 return Ok(where_clause);
4192 let mut parsed_something = false;
4194 let lo = self.span.lo;
4196 token::OpenDelim(token::Brace) => {
4200 token::Lifetime(..) => {
4201 let bounded_lifetime =
4202 try!(self.parse_lifetime());
4204 self.eat(&token::Colon);
4207 try!(self.parse_lifetimes(token::BinOp(token::Plus)));
4209 let hi = self.last_span.hi;
4210 let span = mk_sp(lo, hi);
4212 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4213 ast::WhereRegionPredicate {
4215 lifetime: bounded_lifetime,
4220 parsed_something = true;
4224 let bound_lifetimes = if self.eat_keyword(keywords::For) {
4225 // Higher ranked constraint.
4226 try!(self.expect(&token::Lt));
4227 let lifetime_defs = try!(self.parse_lifetime_defs());
4228 try!(self.expect_gt());
4234 let bounded_ty = try!(self.parse_ty());
4236 if self.eat(&token::Colon) {
4237 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
4238 let hi = self.last_span.hi;
4239 let span = mk_sp(lo, hi);
4241 if bounds.is_empty() {
4243 "each predicate in a `where` clause must have \
4244 at least one bound in it");
4247 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4248 ast::WhereBoundPredicate {
4250 bound_lifetimes: bound_lifetimes,
4251 bounded_ty: bounded_ty,
4255 parsed_something = true;
4256 } else if self.eat(&token::Eq) {
4257 // let ty = try!(self.parse_ty());
4258 let hi = self.last_span.hi;
4259 let span = mk_sp(lo, hi);
4260 // where_clause.predicates.push(
4261 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4262 // id: ast::DUMMY_NODE_ID,
4264 // path: panic!("NYI"), //bounded_ty,
4267 // parsed_something = true;
4270 "equality constraints are not yet supported \
4271 in where clauses (#20041)");
4273 let last_span = self.last_span;
4274 self.span_err(last_span,
4275 "unexpected token in `where` clause");
4280 if !self.eat(&token::Comma) {
4285 if !parsed_something {
4286 let last_span = self.last_span;
4287 self.span_err(last_span,
4288 "a `where` clause must have at least one predicate \
4295 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4296 -> PResult<'a, (Vec<Arg> , bool)> {
4298 let mut args: Vec<Option<Arg>> =
4299 try!(self.parse_unspanned_seq(
4300 &token::OpenDelim(token::Paren),
4301 &token::CloseDelim(token::Paren),
4302 seq_sep_trailing_allowed(token::Comma),
4304 if p.token == token::DotDotDot {
4307 if p.token != token::CloseDelim(token::Paren) {
4309 return Err(p.span_fatal(span,
4310 "`...` must be last in argument list for variadic function"))
4314 return Err(p.span_fatal(span,
4315 "only foreign functions are allowed to be variadic"))
4319 Ok(Some(try!(p.parse_arg_general(named_args))))
4324 let variadic = match args.pop() {
4327 // Need to put back that last arg
4334 if variadic && args.is_empty() {
4336 "variadic function must be declared with at least one named argument");
4339 let args = args.into_iter().map(|x| x.unwrap()).collect();
4341 Ok((args, variadic))
4344 /// Parse the argument list and result type of a function declaration
4345 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4347 let (args, variadic) = try!(self.parse_fn_args(true, allow_variadic));
4348 let ret_ty = try!(self.parse_ret_ty());
4357 fn is_self_ident(&mut self) -> bool {
4359 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4364 fn expect_self_ident(&mut self) -> PResult<'a, ast::Ident> {
4366 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4371 let token_str = self.this_token_to_string();
4372 return Err(self.fatal(&format!("expected `self`, found `{}`",
4378 fn is_self_type_ident(&mut self) -> bool {
4380 token::Ident(id, token::Plain) => id.name == special_idents::type_self.name,
4385 fn expect_self_type_ident(&mut self) -> PResult<'a, ast::Ident> {
4387 token::Ident(id, token::Plain) if id.name == special_idents::type_self.name => {
4392 let token_str = self.this_token_to_string();
4393 Err(self.fatal(&format!("expected `Self`, found `{}`",
4399 /// Parse the argument list and result type of a function
4400 /// that may have a self type.
4401 fn parse_fn_decl_with_self<F>(&mut self,
4402 parse_arg_fn: F) -> PResult<'a, (ExplicitSelf, P<FnDecl>)> where
4403 F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4405 fn maybe_parse_borrowed_explicit_self<'b>(this: &mut Parser<'b>)
4406 -> PResult<'b, ast::SelfKind> {
4407 // The following things are possible to see here:
4412 // fn(&'lt mut self)
4414 // We already know that the current token is `&`.
4416 if this.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4418 Ok(SelfKind::Region(None, MutImmutable, try!(this.expect_self_ident())))
4419 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4420 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4422 let mutability = try!(this.parse_mutability());
4423 Ok(SelfKind::Region(None, mutability, try!(this.expect_self_ident())))
4424 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4425 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4427 let lifetime = try!(this.parse_lifetime());
4428 Ok(SelfKind::Region(Some(lifetime), MutImmutable, try!(this.expect_self_ident())))
4429 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4430 this.look_ahead(2, |t| t.is_mutability()) &&
4431 this.look_ahead(3, |t| t.is_keyword(keywords::SelfValue)) {
4433 let lifetime = try!(this.parse_lifetime());
4434 let mutability = try!(this.parse_mutability());
4435 Ok(SelfKind::Region(Some(lifetime), mutability, try!(this.expect_self_ident())))
4437 Ok(SelfKind::Static)
4441 try!(self.expect(&token::OpenDelim(token::Paren)));
4443 // A bit of complexity and lookahead is needed here in order to be
4444 // backwards compatible.
4445 let lo = self.span.lo;
4446 let mut self_ident_lo = self.span.lo;
4447 let mut self_ident_hi = self.span.hi;
4449 let mut mutbl_self = MutImmutable;
4450 let explicit_self = match self.token {
4451 token::BinOp(token::And) => {
4452 let eself = try!(maybe_parse_borrowed_explicit_self(self));
4453 self_ident_lo = self.last_span.lo;
4454 self_ident_hi = self.last_span.hi;
4457 token::BinOp(token::Star) => {
4458 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4459 // emitting cryptic "unexpected token" errors.
4461 let _mutability = if self.token.is_mutability() {
4462 try!(self.parse_mutability())
4466 if self.is_self_ident() {
4467 let span = self.span;
4468 self.span_err(span, "cannot pass self by raw pointer");
4471 // error case, making bogus self ident:
4472 SelfKind::Value(special_idents::self_)
4474 token::Ident(..) => {
4475 if self.is_self_ident() {
4476 let self_ident = try!(self.expect_self_ident());
4478 // Determine whether this is the fully explicit form, `self:
4480 if self.eat(&token::Colon) {
4481 SelfKind::Explicit(try!(self.parse_ty_sum()), self_ident)
4483 SelfKind::Value(self_ident)
4485 } else if self.token.is_mutability() &&
4486 self.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4487 mutbl_self = try!(self.parse_mutability());
4488 let self_ident = try!(self.expect_self_ident());
4490 // Determine whether this is the fully explicit form,
4492 if self.eat(&token::Colon) {
4493 SelfKind::Explicit(try!(self.parse_ty_sum()), self_ident)
4495 SelfKind::Value(self_ident)
4501 _ => SelfKind::Static,
4504 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4506 // shared fall-through for the three cases below. borrowing prevents simply
4507 // writing this as a closure
4508 macro_rules! parse_remaining_arguments {
4511 // If we parsed a self type, expect a comma before the argument list.
4515 let sep = seq_sep_trailing_allowed(token::Comma);
4516 let mut fn_inputs = try!(self.parse_seq_to_before_end(
4517 &token::CloseDelim(token::Paren),
4521 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4524 token::CloseDelim(token::Paren) => {
4525 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4528 let token_str = self.this_token_to_string();
4529 return Err(self.fatal(&format!("expected `,` or `)`, found `{}`",
4536 let fn_inputs = match explicit_self {
4537 SelfKind::Static => {
4538 let sep = seq_sep_trailing_allowed(token::Comma);
4539 try!(self.parse_seq_to_before_end(&token::CloseDelim(token::Paren),
4542 SelfKind::Value(id) => parse_remaining_arguments!(id),
4543 SelfKind::Region(_,_,id) => parse_remaining_arguments!(id),
4544 SelfKind::Explicit(_,id) => parse_remaining_arguments!(id),
4548 try!(self.expect(&token::CloseDelim(token::Paren)));
4550 let hi = self.span.hi;
4552 let ret_ty = try!(self.parse_ret_ty());
4554 let fn_decl = P(FnDecl {
4560 Ok((spanned(lo, hi, explicit_self), fn_decl))
4563 // parse the |arg, arg| header on a lambda
4564 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4565 let inputs_captures = {
4566 if self.eat(&token::OrOr) {
4569 try!(self.expect(&token::BinOp(token::Or)));
4570 try!(self.parse_obsolete_closure_kind());
4571 let args = try!(self.parse_seq_to_before_end(
4572 &token::BinOp(token::Or),
4573 seq_sep_trailing_allowed(token::Comma),
4574 |p| p.parse_fn_block_arg()
4580 let output = try!(self.parse_ret_ty());
4583 inputs: inputs_captures,
4589 /// Parse the name and optional generic types of a function header.
4590 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4591 let id = try!(self.parse_ident());
4592 let generics = try!(self.parse_generics());
4596 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4597 node: Item_, vis: Visibility,
4598 attrs: Vec<Attribute>) -> P<Item> {
4602 id: ast::DUMMY_NODE_ID,
4609 /// Parse an item-position function declaration.
4610 fn parse_item_fn(&mut self,
4612 constness: Constness,
4614 -> PResult<'a, ItemInfo> {
4615 let (ident, mut generics) = try!(self.parse_fn_header());
4616 let decl = try!(self.parse_fn_decl(false));
4617 generics.where_clause = try!(self.parse_where_clause());
4618 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4619 Ok((ident, ItemFn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4622 /// true if we are looking at `const ID`, false for things like `const fn` etc
4623 pub fn is_const_item(&mut self) -> bool {
4624 self.token.is_keyword(keywords::Const) &&
4625 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4626 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4629 /// parses all the "front matter" for a `fn` declaration, up to
4630 /// and including the `fn` keyword:
4634 /// - `const unsafe fn`
4637 pub fn parse_fn_front_matter(&mut self)
4638 -> PResult<'a, (ast::Constness, ast::Unsafety, abi::Abi)> {
4639 let is_const_fn = self.eat_keyword(keywords::Const);
4640 let unsafety = try!(self.parse_unsafety());
4641 let (constness, unsafety, abi) = if is_const_fn {
4642 (Constness::Const, unsafety, Abi::Rust)
4644 let abi = if self.eat_keyword(keywords::Extern) {
4645 try!(self.parse_opt_abi()).unwrap_or(Abi::C)
4649 (Constness::NotConst, unsafety, abi)
4651 try!(self.expect_keyword(keywords::Fn));
4652 Ok((constness, unsafety, abi))
4655 /// Parse an impl item.
4656 pub fn parse_impl_item(&mut self) -> PResult<'a, P<ImplItem>> {
4657 maybe_whole!(no_clone self, NtImplItem);
4659 let mut attrs = try!(self.parse_outer_attributes());
4660 let lo = self.span.lo;
4661 let vis = try!(self.parse_visibility());
4662 let (name, node) = if self.eat_keyword(keywords::Type) {
4663 let name = try!(self.parse_ident());
4664 try!(self.expect(&token::Eq));
4665 let typ = try!(self.parse_ty_sum());
4666 try!(self.expect(&token::Semi));
4667 (name, ast::ImplItemKind::Type(typ))
4668 } else if self.is_const_item() {
4669 try!(self.expect_keyword(keywords::Const));
4670 let name = try!(self.parse_ident());
4671 try!(self.expect(&token::Colon));
4672 let typ = try!(self.parse_ty_sum());
4673 try!(self.expect(&token::Eq));
4674 let expr = try!(self.parse_expr());
4675 try!(self.commit_expr_expecting(&expr, token::Semi));
4676 (name, ast::ImplItemKind::Const(typ, expr))
4678 let (name, inner_attrs, node) = try!(self.parse_impl_method(vis));
4679 attrs.extend(inner_attrs);
4684 id: ast::DUMMY_NODE_ID,
4685 span: mk_sp(lo, self.last_span.hi),
4693 fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
4696 let is_macro_rules: bool = match self.token {
4697 token::Ident(sid, _) => sid.name == intern("macro_rules"),
4701 self.diagnostic().struct_span_err(span, "can't qualify macro_rules \
4702 invocation with `pub`")
4703 .fileline_help(span, "did you mean #[macro_export]?")
4706 self.diagnostic().struct_span_err(span, "can't qualify macro \
4707 invocation with `pub`")
4708 .fileline_help(span, "try adjusting the macro to put `pub` \
4709 inside the invocation")
4717 /// Parse a method or a macro invocation in a trait impl.
4718 fn parse_impl_method(&mut self, vis: Visibility)
4719 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4720 // code copied from parse_macro_use_or_failure... abstraction!
4721 if !self.token.is_any_keyword()
4722 && self.look_ahead(1, |t| *t == token::Not)
4723 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4724 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4727 let last_span = self.last_span;
4728 self.complain_if_pub_macro(vis, last_span);
4730 let lo = self.span.lo;
4731 let pth = try!(self.parse_path(NoTypesAllowed));
4732 try!(self.expect(&token::Not));
4734 // eat a matched-delimiter token tree:
4735 let delim = try!(self.expect_open_delim());
4736 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
4738 |p| p.parse_token_tree()));
4739 let m_ = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
4740 let m: ast::Mac = codemap::Spanned { node: m_,
4742 self.last_span.hi) };
4743 if delim != token::Brace {
4744 try!(self.expect(&token::Semi))
4746 Ok((token::special_idents::invalid, vec![], ast::ImplItemKind::Macro(m)))
4748 let (constness, unsafety, abi) = try!(self.parse_fn_front_matter());
4749 let ident = try!(self.parse_ident());
4750 let mut generics = try!(self.parse_generics());
4751 let (explicit_self, decl) = try!(self.parse_fn_decl_with_self(|p| {
4754 generics.where_clause = try!(self.parse_where_clause());
4755 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4756 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4759 explicit_self: explicit_self,
4761 constness: constness,
4767 /// Parse trait Foo { ... }
4768 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4770 let ident = try!(self.parse_ident());
4771 let mut tps = try!(self.parse_generics());
4773 // Parse supertrait bounds.
4774 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare));
4776 tps.where_clause = try!(self.parse_where_clause());
4778 let meths = try!(self.parse_trait_items());
4779 Ok((ident, ItemTrait(unsafety, tps, bounds, meths), None))
4782 /// Parses items implementations variants
4783 /// impl<T> Foo { ... }
4784 /// impl<T> ToString for &'static T { ... }
4785 /// impl Send for .. {}
4786 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> PResult<'a, ItemInfo> {
4787 let impl_span = self.span;
4789 // First, parse type parameters if necessary.
4790 let mut generics = try!(self.parse_generics());
4792 // Special case: if the next identifier that follows is '(', don't
4793 // allow this to be parsed as a trait.
4794 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4796 let neg_span = self.span;
4797 let polarity = if self.eat(&token::Not) {
4798 ast::ImplPolarity::Negative
4800 ast::ImplPolarity::Positive
4804 let mut ty = try!(self.parse_ty_sum());
4806 // Parse traits, if necessary.
4807 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4808 // New-style trait. Reinterpret the type as a trait.
4810 TyKind::Path(None, ref path) => {
4812 path: (*path).clone(),
4817 self.span_err(ty.span, "not a trait");
4823 ast::ImplPolarity::Negative => {
4824 // This is a negated type implementation
4825 // `impl !MyType {}`, which is not allowed.
4826 self.span_err(neg_span, "inherent implementation can't be negated");
4833 if opt_trait.is_some() && self.eat(&token::DotDot) {
4834 if generics.is_parameterized() {
4835 self.span_err(impl_span, "default trait implementations are not \
4836 allowed to have generics");
4839 try!(self.expect(&token::OpenDelim(token::Brace)));
4840 try!(self.expect(&token::CloseDelim(token::Brace)));
4841 Ok((ast_util::impl_pretty_name(&opt_trait, None),
4842 ItemDefaultImpl(unsafety, opt_trait.unwrap()), None))
4844 if opt_trait.is_some() {
4845 ty = try!(self.parse_ty_sum());
4847 generics.where_clause = try!(self.parse_where_clause());
4849 try!(self.expect(&token::OpenDelim(token::Brace)));
4850 let attrs = try!(self.parse_inner_attributes());
4852 let mut impl_items = vec![];
4853 while !self.eat(&token::CloseDelim(token::Brace)) {
4854 impl_items.push(try!(self.parse_impl_item()));
4857 Ok((ast_util::impl_pretty_name(&opt_trait, Some(&*ty)),
4858 ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4863 /// Parse a::B<String,i32>
4864 fn parse_trait_ref(&mut self) -> PResult<'a, TraitRef> {
4866 path: try!(self.parse_path(LifetimeAndTypesWithoutColons)),
4867 ref_id: ast::DUMMY_NODE_ID,
4871 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<ast::LifetimeDef>> {
4872 if self.eat_keyword(keywords::For) {
4873 try!(self.expect(&token::Lt));
4874 let lifetime_defs = try!(self.parse_lifetime_defs());
4875 try!(self.expect_gt());
4882 /// Parse for<'l> a::B<String,i32>
4883 fn parse_poly_trait_ref(&mut self) -> PResult<'a, PolyTraitRef> {
4884 let lo = self.span.lo;
4885 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
4887 Ok(ast::PolyTraitRef {
4888 bound_lifetimes: lifetime_defs,
4889 trait_ref: try!(self.parse_trait_ref()),
4890 span: mk_sp(lo, self.last_span.hi),
4894 /// Parse struct Foo { ... }
4895 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
4896 let class_name = try!(self.parse_ident());
4897 let mut generics = try!(self.parse_generics());
4899 // There is a special case worth noting here, as reported in issue #17904.
4900 // If we are parsing a tuple struct it is the case that the where clause
4901 // should follow the field list. Like so:
4903 // struct Foo<T>(T) where T: Copy;
4905 // If we are parsing a normal record-style struct it is the case
4906 // that the where clause comes before the body, and after the generics.
4907 // So if we look ahead and see a brace or a where-clause we begin
4908 // parsing a record style struct.
4910 // Otherwise if we look ahead and see a paren we parse a tuple-style
4913 let vdata = if self.token.is_keyword(keywords::Where) {
4914 generics.where_clause = try!(self.parse_where_clause());
4915 if self.eat(&token::Semi) {
4916 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4917 VariantData::Unit(ast::DUMMY_NODE_ID)
4919 // If we see: `struct Foo<T> where T: Copy { ... }`
4920 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4923 // No `where` so: `struct Foo<T>;`
4924 } else if self.eat(&token::Semi) {
4925 VariantData::Unit(ast::DUMMY_NODE_ID)
4926 // Record-style struct definition
4927 } else if self.token == token::OpenDelim(token::Brace) {
4928 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4930 // Tuple-style struct definition with optional where-clause.
4931 } else if self.token == token::OpenDelim(token::Paren) {
4932 let body = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::Yes)),
4933 ast::DUMMY_NODE_ID);
4934 generics.where_clause = try!(self.parse_where_clause());
4935 try!(self.expect(&token::Semi));
4938 let token_str = self.this_token_to_string();
4939 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
4940 name, found `{}`", token_str)))
4943 Ok((class_name, ItemStruct(vdata, generics), None))
4946 pub fn parse_record_struct_body(&mut self,
4947 parse_pub: ParsePub)
4948 -> PResult<'a, Vec<StructField>> {
4949 let mut fields = Vec::new();
4950 if self.eat(&token::OpenDelim(token::Brace)) {
4951 while self.token != token::CloseDelim(token::Brace) {
4952 fields.push(try!(self.parse_struct_decl_field(parse_pub)));
4957 let token_str = self.this_token_to_string();
4958 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
4966 pub fn parse_tuple_struct_body(&mut self,
4967 parse_pub: ParsePub)
4968 -> PResult<'a, Vec<StructField>> {
4969 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4970 // Unit like structs are handled in parse_item_struct function
4971 let fields = try!(self.parse_unspanned_seq(
4972 &token::OpenDelim(token::Paren),
4973 &token::CloseDelim(token::Paren),
4974 seq_sep_trailing_allowed(token::Comma),
4976 let attrs = try!(p.parse_outer_attributes());
4978 let struct_field_ = ast::StructField_ {
4979 kind: UnnamedField (
4980 if parse_pub == ParsePub::Yes {
4981 try!(p.parse_visibility())
4986 id: ast::DUMMY_NODE_ID,
4987 ty: try!(p.parse_ty_sum()),
4990 Ok(spanned(lo, p.span.hi, struct_field_))
4996 /// Parse a structure field declaration
4997 pub fn parse_single_struct_field(&mut self,
4999 attrs: Vec<Attribute> )
5000 -> PResult<'a, StructField> {
5001 let a_var = try!(self.parse_name_and_ty(vis, attrs));
5006 token::CloseDelim(token::Brace) => {}
5008 let span = self.span;
5009 let token_str = self.this_token_to_string();
5010 return Err(self.span_fatal_help(span,
5011 &format!("expected `,`, or `}}`, found `{}`",
5013 "struct fields should be separated by commas"))
5019 /// Parse an element of a struct definition
5020 fn parse_struct_decl_field(&mut self, parse_pub: ParsePub) -> PResult<'a, StructField> {
5022 let attrs = try!(self.parse_outer_attributes());
5024 if self.eat_keyword(keywords::Pub) {
5025 if parse_pub == ParsePub::No {
5026 let span = self.last_span;
5027 self.span_err(span, "`pub` is not allowed here");
5029 return self.parse_single_struct_field(Public, attrs);
5032 return self.parse_single_struct_field(Inherited, attrs);
5035 /// Parse visibility: PUB or nothing
5036 fn parse_visibility(&mut self) -> PResult<'a, Visibility> {
5037 if self.eat_keyword(keywords::Pub) { Ok(Public) }
5038 else { Ok(Inherited) }
5041 /// Given a termination token, parse all of the items in a module
5042 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> PResult<'a, Mod> {
5043 let mut items = vec![];
5044 while let Some(item) = try!(self.parse_item()) {
5048 if !self.eat(term) {
5049 let token_str = self.this_token_to_string();
5050 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5053 let hi = if self.span == codemap::DUMMY_SP {
5060 inner: mk_sp(inner_lo, hi),
5065 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5066 let id = try!(self.parse_ident());
5067 try!(self.expect(&token::Colon));
5068 let ty = try!(self.parse_ty_sum());
5069 try!(self.expect(&token::Eq));
5070 let e = try!(self.parse_expr());
5071 try!(self.commit_expr_expecting(&*e, token::Semi));
5072 let item = match m {
5073 Some(m) => ItemStatic(ty, m, e),
5074 None => ItemConst(ty, e),
5076 Ok((id, item, None))
5079 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5080 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5081 let id_span = self.span;
5082 let id = try!(self.parse_ident());
5083 if self.check(&token::Semi) {
5085 // This mod is in an external file. Let's go get it!
5086 let (m, attrs) = try!(self.eval_src_mod(id, outer_attrs, id_span));
5087 Ok((id, m, Some(attrs)))
5089 self.push_mod_path(id, outer_attrs);
5090 try!(self.expect(&token::OpenDelim(token::Brace)));
5091 let mod_inner_lo = self.span.lo;
5092 let old_owns_directory = self.owns_directory;
5093 self.owns_directory = true;
5094 let attrs = try!(self.parse_inner_attributes());
5095 let m = try!(self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo));
5096 self.owns_directory = old_owns_directory;
5097 self.pop_mod_path();
5098 Ok((id, ItemMod(m), Some(attrs)))
5102 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5103 let default_path = self.id_to_interned_str(id);
5104 let file_path = match ::attr::first_attr_value_str_by_name(attrs, "path") {
5106 None => default_path,
5108 self.mod_path_stack.push(file_path)
5111 fn pop_mod_path(&mut self) {
5112 self.mod_path_stack.pop().unwrap();
5115 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5116 ::attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&*d))
5119 /// Returns either a path to a module, or .
5120 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath
5122 let mod_name = id.to_string();
5123 let default_path_str = format!("{}.rs", mod_name);
5124 let secondary_path_str = format!("{}/mod.rs", mod_name);
5125 let default_path = dir_path.join(&default_path_str);
5126 let secondary_path = dir_path.join(&secondary_path_str);
5127 let default_exists = codemap.file_exists(&default_path);
5128 let secondary_exists = codemap.file_exists(&secondary_path);
5130 let result = match (default_exists, secondary_exists) {
5131 (true, false) => Ok(ModulePathSuccess { path: default_path, owns_directory: false }),
5132 (false, true) => Ok(ModulePathSuccess { path: secondary_path, owns_directory: true }),
5133 (false, false) => Err(ModulePathError {
5134 err_msg: format!("file not found for module `{}`", mod_name),
5135 help_msg: format!("name the file either {} or {} inside the directory {:?}",
5138 dir_path.display()),
5140 (true, true) => Err(ModulePathError {
5141 err_msg: format!("file for module `{}` found at both {} and {}",
5144 secondary_path_str),
5145 help_msg: "delete or rename one of them to remove the ambiguity".to_owned(),
5151 path_exists: default_exists || secondary_exists,
5156 fn submod_path(&mut self,
5158 outer_attrs: &[ast::Attribute],
5159 id_sp: Span) -> PResult<'a, ModulePathSuccess> {
5160 let mut prefix = PathBuf::from(&self.sess.codemap().span_to_filename(self.span));
5162 let mut dir_path = prefix;
5163 for part in &self.mod_path_stack {
5164 dir_path.push(&**part);
5167 if let Some(p) = Parser::submod_path_from_attr(outer_attrs, &dir_path) {
5168 return Ok(ModulePathSuccess { path: p, owns_directory: true });
5171 let paths = Parser::default_submod_path(id, &dir_path, self.sess.codemap());
5173 if !self.owns_directory {
5174 let mut err = self.diagnostic().struct_span_err(id_sp,
5175 "cannot declare a new module at this location");
5176 let this_module = match self.mod_path_stack.last() {
5177 Some(name) => name.to_string(),
5178 None => self.root_module_name.as_ref().unwrap().clone(),
5180 err.span_note(id_sp,
5181 &format!("maybe move this module `{0}` to its own directory \
5184 if paths.path_exists {
5185 err.span_note(id_sp,
5186 &format!("... or maybe `use` the module `{}` instead \
5187 of possibly redeclaring it",
5193 match paths.result {
5194 Ok(succ) => Ok(succ),
5195 Err(err) => Err(self.span_fatal_help(id_sp, &err.err_msg, &err.help_msg)),
5199 /// Read a module from a source file.
5200 fn eval_src_mod(&mut self,
5202 outer_attrs: &[ast::Attribute],
5204 -> PResult<'a, (ast::Item_, Vec<ast::Attribute> )> {
5205 let ModulePathSuccess { path, owns_directory } = try!(self.submod_path(id,
5209 self.eval_src_mod_from_path(path,
5215 fn eval_src_mod_from_path(&mut self,
5217 owns_directory: bool,
5219 id_sp: Span) -> PResult<'a, (ast::Item_, Vec<ast::Attribute> )> {
5220 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5221 match included_mod_stack.iter().position(|p| *p == path) {
5223 let mut err = String::from("circular modules: ");
5224 let len = included_mod_stack.len();
5225 for p in &included_mod_stack[i.. len] {
5226 err.push_str(&p.to_string_lossy());
5227 err.push_str(" -> ");
5229 err.push_str(&path.to_string_lossy());
5230 return Err(self.span_fatal(id_sp, &err[..]));
5234 included_mod_stack.push(path.clone());
5235 drop(included_mod_stack);
5237 let mut p0 = new_sub_parser_from_file(self.sess,
5243 let mod_inner_lo = p0.span.lo;
5244 let mod_attrs = try!(p0.parse_inner_attributes());
5245 let m0 = try!(p0.parse_mod_items(&token::Eof, mod_inner_lo));
5246 self.sess.included_mod_stack.borrow_mut().pop();
5247 Ok((ast::ItemMod(m0), mod_attrs))
5250 /// Parse a function declaration from a foreign module
5251 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: BytePos,
5252 attrs: Vec<Attribute>) -> PResult<'a, P<ForeignItem>> {
5253 try!(self.expect_keyword(keywords::Fn));
5255 let (ident, mut generics) = try!(self.parse_fn_header());
5256 let decl = try!(self.parse_fn_decl(true));
5257 generics.where_clause = try!(self.parse_where_clause());
5258 let hi = self.span.hi;
5259 try!(self.expect(&token::Semi));
5260 Ok(P(ast::ForeignItem {
5263 node: ForeignItemFn(decl, generics),
5264 id: ast::DUMMY_NODE_ID,
5265 span: mk_sp(lo, hi),
5270 /// Parse a static item from a foreign module
5271 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: BytePos,
5272 attrs: Vec<Attribute>) -> PResult<'a, P<ForeignItem>> {
5273 try!(self.expect_keyword(keywords::Static));
5274 let mutbl = self.eat_keyword(keywords::Mut);
5276 let ident = try!(self.parse_ident());
5277 try!(self.expect(&token::Colon));
5278 let ty = try!(self.parse_ty_sum());
5279 let hi = self.span.hi;
5280 try!(self.expect(&token::Semi));
5284 node: ForeignItemStatic(ty, mutbl),
5285 id: ast::DUMMY_NODE_ID,
5286 span: mk_sp(lo, hi),
5291 /// Parse extern crate links
5295 /// extern crate foo;
5296 /// extern crate bar as foo;
5297 fn parse_item_extern_crate(&mut self,
5299 visibility: Visibility,
5300 attrs: Vec<Attribute>)
5301 -> PResult<'a, P<Item>> {
5303 let crate_name = try!(self.parse_ident());
5304 let (maybe_path, ident) = if let Some(ident) = try!(self.parse_rename()) {
5305 (Some(crate_name.name), ident)
5309 try!(self.expect(&token::Semi));
5311 let last_span = self.last_span;
5313 if visibility == ast::Public {
5314 self.span_warn(mk_sp(lo, last_span.hi),
5315 "`pub extern crate` does not work as expected and should not be used. \
5316 Likely to become an error. Prefer `extern crate` and `pub use`.");
5322 ItemExternCrate(maybe_path),
5327 /// Parse `extern` for foreign ABIs
5330 /// `extern` is expected to have been
5331 /// consumed before calling this method
5337 fn parse_item_foreign_mod(&mut self,
5339 opt_abi: Option<abi::Abi>,
5340 visibility: Visibility,
5341 mut attrs: Vec<Attribute>)
5342 -> PResult<'a, P<Item>> {
5343 try!(self.expect(&token::OpenDelim(token::Brace)));
5345 let abi = opt_abi.unwrap_or(Abi::C);
5347 attrs.extend(try!(self.parse_inner_attributes()));
5349 let mut foreign_items = vec![];
5350 while let Some(item) = try!(self.parse_foreign_item()) {
5351 foreign_items.push(item);
5353 try!(self.expect(&token::CloseDelim(token::Brace)));
5355 let last_span = self.last_span;
5356 let m = ast::ForeignMod {
5358 items: foreign_items
5362 special_idents::invalid,
5368 /// Parse type Foo = Bar;
5369 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5370 let ident = try!(self.parse_ident());
5371 let mut tps = try!(self.parse_generics());
5372 tps.where_clause = try!(self.parse_where_clause());
5373 try!(self.expect(&token::Eq));
5374 let ty = try!(self.parse_ty_sum());
5375 try!(self.expect(&token::Semi));
5376 Ok((ident, ItemTy(ty, tps), None))
5379 /// Parse the part of an "enum" decl following the '{'
5380 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5381 let mut variants = Vec::new();
5382 let mut all_nullary = true;
5383 let mut any_disr = None;
5384 while self.token != token::CloseDelim(token::Brace) {
5385 let variant_attrs = try!(self.parse_outer_attributes());
5386 let vlo = self.span.lo;
5389 let mut disr_expr = None;
5390 let ident = try!(self.parse_ident());
5391 if self.check(&token::OpenDelim(token::Brace)) {
5392 // Parse a struct variant.
5393 all_nullary = false;
5394 struct_def = VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::No)),
5395 ast::DUMMY_NODE_ID);
5396 } else if self.check(&token::OpenDelim(token::Paren)) {
5397 all_nullary = false;
5398 struct_def = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::No)),
5399 ast::DUMMY_NODE_ID);
5400 } else if self.eat(&token::Eq) {
5401 disr_expr = Some(try!(self.parse_expr()));
5402 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5403 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5405 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5408 let vr = ast::Variant_ {
5410 attrs: variant_attrs,
5412 disr_expr: disr_expr,
5414 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5416 if !self.eat(&token::Comma) { break; }
5418 try!(self.expect(&token::CloseDelim(token::Brace)));
5420 Some(disr_span) if !all_nullary =>
5421 self.span_err(disr_span,
5422 "discriminator values can only be used with a c-like enum"),
5426 Ok(ast::EnumDef { variants: variants })
5429 /// Parse an "enum" declaration
5430 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5431 let id = try!(self.parse_ident());
5432 let mut generics = try!(self.parse_generics());
5433 generics.where_clause = try!(self.parse_where_clause());
5434 try!(self.expect(&token::OpenDelim(token::Brace)));
5436 let enum_definition = try!(self.parse_enum_def(&generics));
5437 Ok((id, ItemEnum(enum_definition, generics), None))
5440 /// Parses a string as an ABI spec on an extern type or module. Consumes
5441 /// the `extern` keyword, if one is found.
5442 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5444 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5446 self.expect_no_suffix(sp, "ABI spec", suf);
5448 match abi::lookup(&s.as_str()) {
5449 Some(abi) => Ok(Some(abi)),
5451 let last_span = self.last_span;
5454 &format!("invalid ABI: expected one of [{}], \
5456 abi::all_names().join(", "),
5467 /// Parse one of the items allowed by the flags.
5468 /// NB: this function no longer parses the items inside an
5470 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5471 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5472 let nt_item = match self.token {
5473 token::Interpolated(token::NtItem(ref item)) => {
5474 Some((**item).clone())
5481 let mut attrs = attrs;
5482 mem::swap(&mut item.attrs, &mut attrs);
5483 item.attrs.extend(attrs);
5484 return Ok(Some(P(item)));
5489 let lo = self.span.lo;
5491 let visibility = try!(self.parse_visibility());
5493 if self.eat_keyword(keywords::Use) {
5495 let item_ = ItemUse(try!(self.parse_view_path()));
5496 try!(self.expect(&token::Semi));
5498 let last_span = self.last_span;
5499 let item = self.mk_item(lo,
5501 token::special_idents::invalid,
5505 return Ok(Some(item));
5508 if self.eat_keyword(keywords::Extern) {
5509 if self.eat_keyword(keywords::Crate) {
5510 return Ok(Some(try!(self.parse_item_extern_crate(lo, visibility, attrs))));
5513 let opt_abi = try!(self.parse_opt_abi());
5515 if self.eat_keyword(keywords::Fn) {
5516 // EXTERN FUNCTION ITEM
5517 let abi = opt_abi.unwrap_or(Abi::C);
5518 let (ident, item_, extra_attrs) =
5519 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi));
5520 let last_span = self.last_span;
5521 let item = self.mk_item(lo,
5526 maybe_append(attrs, extra_attrs));
5527 return Ok(Some(item));
5528 } else if self.check(&token::OpenDelim(token::Brace)) {
5529 return Ok(Some(try!(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs))));
5532 try!(self.unexpected());
5535 if self.eat_keyword(keywords::Static) {
5537 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
5538 let (ident, item_, extra_attrs) = try!(self.parse_item_const(Some(m)));
5539 let last_span = self.last_span;
5540 let item = self.mk_item(lo,
5545 maybe_append(attrs, extra_attrs));
5546 return Ok(Some(item));
5548 if self.eat_keyword(keywords::Const) {
5549 if self.check_keyword(keywords::Fn)
5550 || (self.check_keyword(keywords::Unsafe)
5551 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5552 // CONST FUNCTION ITEM
5553 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5559 let (ident, item_, extra_attrs) =
5560 try!(self.parse_item_fn(unsafety, Constness::Const, Abi::Rust));
5561 let last_span = self.last_span;
5562 let item = self.mk_item(lo,
5567 maybe_append(attrs, extra_attrs));
5568 return Ok(Some(item));
5572 if self.eat_keyword(keywords::Mut) {
5573 let last_span = self.last_span;
5574 self.diagnostic().struct_span_err(last_span, "const globals cannot be mutable")
5575 .fileline_help(last_span, "did you mean to declare a static?")
5578 let (ident, item_, extra_attrs) = try!(self.parse_item_const(None));
5579 let last_span = self.last_span;
5580 let item = self.mk_item(lo,
5585 maybe_append(attrs, extra_attrs));
5586 return Ok(Some(item));
5588 if self.check_keyword(keywords::Unsafe) &&
5589 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5591 // UNSAFE TRAIT ITEM
5592 try!(self.expect_keyword(keywords::Unsafe));
5593 try!(self.expect_keyword(keywords::Trait));
5594 let (ident, item_, extra_attrs) =
5595 try!(self.parse_item_trait(ast::Unsafety::Unsafe));
5596 let last_span = self.last_span;
5597 let item = self.mk_item(lo,
5602 maybe_append(attrs, extra_attrs));
5603 return Ok(Some(item));
5605 if self.check_keyword(keywords::Unsafe) &&
5606 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5609 try!(self.expect_keyword(keywords::Unsafe));
5610 try!(self.expect_keyword(keywords::Impl));
5611 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Unsafe));
5612 let last_span = self.last_span;
5613 let item = self.mk_item(lo,
5618 maybe_append(attrs, extra_attrs));
5619 return Ok(Some(item));
5621 if self.check_keyword(keywords::Fn) {
5624 let (ident, item_, extra_attrs) =
5625 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, Abi::Rust));
5626 let last_span = self.last_span;
5627 let item = self.mk_item(lo,
5632 maybe_append(attrs, extra_attrs));
5633 return Ok(Some(item));
5635 if self.check_keyword(keywords::Unsafe)
5636 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5637 // UNSAFE FUNCTION ITEM
5639 let abi = if self.eat_keyword(keywords::Extern) {
5640 try!(self.parse_opt_abi()).unwrap_or(Abi::C)
5644 try!(self.expect_keyword(keywords::Fn));
5645 let (ident, item_, extra_attrs) =
5646 try!(self.parse_item_fn(Unsafety::Unsafe, Constness::NotConst, abi));
5647 let last_span = self.last_span;
5648 let item = self.mk_item(lo,
5653 maybe_append(attrs, extra_attrs));
5654 return Ok(Some(item));
5656 if self.eat_keyword(keywords::Mod) {
5658 let (ident, item_, extra_attrs) =
5659 try!(self.parse_item_mod(&attrs[..]));
5660 let last_span = self.last_span;
5661 let item = self.mk_item(lo,
5666 maybe_append(attrs, extra_attrs));
5667 return Ok(Some(item));
5669 if self.eat_keyword(keywords::Type) {
5671 let (ident, item_, extra_attrs) = try!(self.parse_item_type());
5672 let last_span = self.last_span;
5673 let item = self.mk_item(lo,
5678 maybe_append(attrs, extra_attrs));
5679 return Ok(Some(item));
5681 if self.eat_keyword(keywords::Enum) {
5683 let (ident, item_, extra_attrs) = try!(self.parse_item_enum());
5684 let last_span = self.last_span;
5685 let item = self.mk_item(lo,
5690 maybe_append(attrs, extra_attrs));
5691 return Ok(Some(item));
5693 if self.eat_keyword(keywords::Trait) {
5695 let (ident, item_, extra_attrs) =
5696 try!(self.parse_item_trait(ast::Unsafety::Normal));
5697 let last_span = self.last_span;
5698 let item = self.mk_item(lo,
5703 maybe_append(attrs, extra_attrs));
5704 return Ok(Some(item));
5706 if self.eat_keyword(keywords::Impl) {
5708 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Normal));
5709 let last_span = self.last_span;
5710 let item = self.mk_item(lo,
5715 maybe_append(attrs, extra_attrs));
5716 return Ok(Some(item));
5718 if self.eat_keyword(keywords::Struct) {
5720 let (ident, item_, extra_attrs) = try!(self.parse_item_struct());
5721 let last_span = self.last_span;
5722 let item = self.mk_item(lo,
5727 maybe_append(attrs, extra_attrs));
5728 return Ok(Some(item));
5730 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5733 /// Parse a foreign item.
5734 fn parse_foreign_item(&mut self) -> PResult<'a, Option<P<ForeignItem>>> {
5735 let attrs = try!(self.parse_outer_attributes());
5736 let lo = self.span.lo;
5737 let visibility = try!(self.parse_visibility());
5739 if self.check_keyword(keywords::Static) {
5740 // FOREIGN STATIC ITEM
5741 return Ok(Some(try!(self.parse_item_foreign_static(visibility, lo, attrs))));
5743 if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) {
5744 // FOREIGN FUNCTION ITEM
5745 return Ok(Some(try!(self.parse_item_foreign_fn(visibility, lo, attrs))));
5748 // FIXME #5668: this will occur for a macro invocation:
5749 match try!(self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)) {
5751 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5757 /// This is the fall-through for parsing items.
5758 fn parse_macro_use_or_failure(
5760 attrs: Vec<Attribute> ,
5761 macros_allowed: bool,
5762 attributes_allowed: bool,
5764 visibility: Visibility
5765 ) -> PResult<'a, Option<P<Item>>> {
5766 if macros_allowed && !self.token.is_any_keyword()
5767 && self.look_ahead(1, |t| *t == token::Not)
5768 && (self.look_ahead(2, |t| t.is_plain_ident())
5769 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5770 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5771 // MACRO INVOCATION ITEM
5773 let last_span = self.last_span;
5774 self.complain_if_pub_macro(visibility, last_span);
5776 let mac_lo = self.span.lo;
5779 let pth = try!(self.parse_path(NoTypesAllowed));
5780 try!(self.expect(&token::Not));
5782 // a 'special' identifier (like what `macro_rules!` uses)
5783 // is optional. We should eventually unify invoc syntax
5785 let id = if self.token.is_plain_ident() {
5786 try!(self.parse_ident())
5788 token::special_idents::invalid // no special identifier
5790 // eat a matched-delimiter token tree:
5791 let delim = try!(self.expect_open_delim());
5792 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
5794 |p| p.parse_token_tree()));
5795 // single-variant-enum... :
5796 let m = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
5797 let m: ast::Mac = codemap::Spanned { node: m,
5799 self.last_span.hi) };
5801 if delim != token::Brace {
5802 if !self.eat(&token::Semi) {
5803 let last_span = self.last_span;
5804 self.span_err(last_span,
5805 "macros that expand to items must either \
5806 be surrounded with braces or followed by \
5811 let item_ = ItemMac(m);
5812 let last_span = self.last_span;
5813 let item = self.mk_item(lo,
5819 return Ok(Some(item));
5822 // FAILURE TO PARSE ITEM
5826 let last_span = self.last_span;
5827 return Err(self.span_fatal(last_span, "unmatched visibility `pub`"));
5831 if !attributes_allowed && !attrs.is_empty() {
5832 self.expected_item_err(&attrs);
5837 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
5838 let attrs = try!(self.parse_outer_attributes());
5839 self.parse_item_(attrs, true, false)
5843 /// Matches view_path : MOD? non_global_path as IDENT
5844 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5845 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5846 /// | MOD? non_global_path MOD_SEP STAR
5847 /// | MOD? non_global_path
5848 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
5849 let lo = self.span.lo;
5851 // Allow a leading :: because the paths are absolute either way.
5852 // This occurs with "use $crate::..." in macros.
5853 self.eat(&token::ModSep);
5855 if self.check(&token::OpenDelim(token::Brace)) {
5857 let idents = try!(self.parse_unspanned_seq(
5858 &token::OpenDelim(token::Brace),
5859 &token::CloseDelim(token::Brace),
5860 seq_sep_trailing_allowed(token::Comma),
5861 |p| p.parse_path_list_item()));
5862 let path = ast::Path {
5863 span: mk_sp(lo, self.span.hi),
5865 segments: Vec::new()
5867 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5870 let first_ident = try!(self.parse_ident());
5871 let mut path = vec!(first_ident);
5872 if let token::ModSep = self.token {
5873 // foo::bar or foo::{a,b,c} or foo::*
5874 while self.check(&token::ModSep) {
5878 token::Ident(..) => {
5879 let ident = try!(self.parse_ident());
5883 // foo::bar::{a,b,c}
5884 token::OpenDelim(token::Brace) => {
5885 let idents = try!(self.parse_unspanned_seq(
5886 &token::OpenDelim(token::Brace),
5887 &token::CloseDelim(token::Brace),
5888 seq_sep_trailing_allowed(token::Comma),
5889 |p| p.parse_path_list_item()
5891 let path = ast::Path {
5892 span: mk_sp(lo, self.span.hi),
5894 segments: path.into_iter().map(|identifier| {
5896 identifier: identifier,
5897 parameters: ast::PathParameters::none(),
5901 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5905 token::BinOp(token::Star) => {
5907 let path = ast::Path {
5908 span: mk_sp(lo, self.span.hi),
5910 segments: path.into_iter().map(|identifier| {
5912 identifier: identifier,
5913 parameters: ast::PathParameters::none(),
5917 return Ok(P(spanned(lo, self.span.hi, ViewPathGlob(path))));
5920 // fall-through for case foo::bar::;
5922 self.span_err(self.span, "expected identifier or `{` or `*`, found `;`");
5929 let mut rename_to = path[path.len() - 1];
5930 let path = ast::Path {
5931 span: mk_sp(lo, self.last_span.hi),
5933 segments: path.into_iter().map(|identifier| {
5935 identifier: identifier,
5936 parameters: ast::PathParameters::none(),
5940 rename_to = try!(self.parse_rename()).unwrap_or(rename_to);
5941 Ok(P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path))))
5944 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
5945 if self.eat_keyword(keywords::As) {
5946 self.parse_ident().map(Some)
5952 /// Parses a source module as a crate. This is the main
5953 /// entry point for the parser.
5954 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
5955 let lo = self.span.lo;
5957 attrs: try!(self.parse_inner_attributes()),
5958 module: try!(self.parse_mod_items(&token::Eof, lo)),
5959 config: self.cfg.clone(),
5960 span: mk_sp(lo, self.span.lo),
5961 exported_macros: Vec::new(),
5965 pub fn parse_optional_str(&mut self)
5966 -> Option<(InternedString,
5968 Option<ast::Name>)> {
5969 let ret = match self.token {
5970 token::Literal(token::Str_(s), suf) => {
5971 (self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)), ast::CookedStr, suf)
5973 token::Literal(token::StrRaw(s, n), suf) => {
5974 (self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)), ast::RawStr(n), suf)
5982 pub fn parse_str(&mut self) -> PResult<'a, (InternedString, StrStyle)> {
5983 match self.parse_optional_str() {
5984 Some((s, style, suf)) => {
5985 let sp = self.last_span;
5986 self.expect_no_suffix(sp, "string literal", suf);
5989 _ => Err(self.fatal("expected string literal"))