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};
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, Ty_, TypeBinding, TyMac};
46 use ast::{TyFixedLengthVec, TyBareFn, TyTypeof, TyInfer};
47 use ast::{TyParam, TyParamBounds, TyParen, TyPath, TyPtr};
48 use ast::{TyRptr, TyTup, TyU32, TyVec};
49 use ast::TypeTraitItem;
50 use ast::UnnamedField;
51 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
52 use ast::{Visibility, WhereClause};
53 use attr::{ThinAttributes, ThinAttributesExt, AttributesExt};
54 use ast::{BinOpKind, UnOp};
56 use ast_util::{self, ident_to_path};
57 use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp, CodeMap};
58 use errors::{self, DiagnosticBuilder};
59 use ext::tt::macro_parser;
62 use parse::common::{SeqSep, seq_sep_none, seq_sep_trailing_allowed};
63 use parse::lexer::{Reader, TokenAndSpan};
64 use parse::obsolete::{ParserObsoleteMethods, ObsoleteSyntax};
65 use parse::token::{self, intern, MatchNt, SubstNt, SpecialVarNt, InternedString};
66 use parse::token::{keywords, special_idents, SpecialMacroVar};
67 use parse::{new_sub_parser_from_file, ParseSess};
68 use util::parser::{AssocOp, Fixity};
73 use std::collections::HashSet;
74 use std::io::prelude::*;
76 use std::path::{Path, PathBuf};
81 flags Restrictions: u8 {
82 const RESTRICTION_STMT_EXPR = 1 << 0,
83 const RESTRICTION_NO_STRUCT_LITERAL = 1 << 1,
87 type ItemInfo = (Ident, Item_, Option<Vec<Attribute> >);
89 /// How to parse a path. There are four different kinds of paths, all of which
90 /// are parsed somewhat differently.
91 #[derive(Copy, Clone, PartialEq)]
92 pub enum PathParsingMode {
93 /// A path with no type parameters; e.g. `foo::bar::Baz`
95 /// A path with a lifetime and type parameters, with no double colons
96 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
97 LifetimeAndTypesWithoutColons,
98 /// A path with a lifetime and type parameters with double colons before
99 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
100 LifetimeAndTypesWithColons,
103 /// How to parse a bound, whether to allow bound modifiers such as `?`.
104 #[derive(Copy, Clone, PartialEq)]
105 pub enum BoundParsingMode {
110 /// `pub` should be parsed in struct fields and not parsed in variant fields
111 #[derive(Clone, Copy, PartialEq)]
117 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
118 /// dropped into the token stream, which happens while parsing the result of
119 /// macro expansion). Placement of these is not as complex as I feared it would
120 /// be. The important thing is to make sure that lookahead doesn't balk at
121 /// `token::Interpolated` tokens.
122 macro_rules! maybe_whole_expr {
125 let found = match $p.token {
126 token::Interpolated(token::NtExpr(ref e)) => {
129 token::Interpolated(token::NtPath(_)) => {
130 // FIXME: The following avoids an issue with lexical borrowck scopes,
131 // but the clone is unfortunate.
132 let pt = match $p.token {
133 token::Interpolated(token::NtPath(ref pt)) => (**pt).clone(),
137 Some($p.mk_expr(span.lo, span.hi, ExprKind::Path(None, pt), None))
139 token::Interpolated(token::NtBlock(_)) => {
140 // FIXME: The following avoids an issue with lexical borrowck scopes,
141 // but the clone is unfortunate.
142 let b = match $p.token {
143 token::Interpolated(token::NtBlock(ref b)) => (*b).clone(),
147 Some($p.mk_expr(span.lo, span.hi, ExprKind::Block(b), None))
162 /// As maybe_whole_expr, but for things other than expressions
163 macro_rules! maybe_whole {
164 ($p:expr, $constructor:ident) => (
166 let found = match ($p).token {
167 token::Interpolated(token::$constructor(_)) => {
168 Some(($p).bump_and_get())
172 if let Some(token::Interpolated(token::$constructor(x))) = found {
173 return Ok(x.clone());
177 (no_clone $p:expr, $constructor:ident) => (
179 let found = match ($p).token {
180 token::Interpolated(token::$constructor(_)) => {
181 Some(($p).bump_and_get())
185 if let Some(token::Interpolated(token::$constructor(x))) = found {
190 (deref $p:expr, $constructor:ident) => (
192 let found = match ($p).token {
193 token::Interpolated(token::$constructor(_)) => {
194 Some(($p).bump_and_get())
198 if let Some(token::Interpolated(token::$constructor(x))) = found {
199 return Ok((*x).clone());
203 (Some deref $p:expr, $constructor:ident) => (
205 let found = match ($p).token {
206 token::Interpolated(token::$constructor(_)) => {
207 Some(($p).bump_and_get())
211 if let Some(token::Interpolated(token::$constructor(x))) = found {
212 return Ok(Some((*x).clone()));
216 (pair_empty $p:expr, $constructor:ident) => (
218 let found = match ($p).token {
219 token::Interpolated(token::$constructor(_)) => {
220 Some(($p).bump_and_get())
224 if let Some(token::Interpolated(token::$constructor(x))) = found {
225 return Ok((Vec::new(), x));
231 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
233 if let Some(ref attrs) = rhs {
234 lhs.extend(attrs.iter().cloned())
239 /* ident is handled by common.rs */
241 pub struct Parser<'a> {
242 pub sess: &'a ParseSess,
243 /// the current token:
244 pub token: token::Token,
245 /// the span of the current token:
247 /// the span of the prior token:
249 pub cfg: CrateConfig,
250 /// the previous token or None (only stashed sometimes).
251 pub last_token: Option<Box<token::Token>>,
252 last_token_interpolated: bool,
253 pub buffer: [TokenAndSpan; 4],
254 pub buffer_start: isize,
255 pub buffer_end: isize,
256 pub tokens_consumed: usize,
257 pub restrictions: Restrictions,
258 pub quote_depth: usize, // not (yet) related to the quasiquoter
259 pub reader: Box<Reader+'a>,
260 pub interner: Rc<token::IdentInterner>,
261 /// The set of seen errors about obsolete syntax. Used to suppress
262 /// extra detail when the same error is seen twice
263 pub obsolete_set: HashSet<ObsoleteSyntax>,
264 /// Used to determine the path to externally loaded source files
265 pub mod_path_stack: Vec<InternedString>,
266 /// Stack of spans of open delimiters. Used for error message.
267 pub open_braces: Vec<Span>,
268 /// Flag if this parser "owns" the directory that it is currently parsing
269 /// in. This will affect how nested files are looked up.
270 pub owns_directory: bool,
271 /// Name of the root module this parser originated from. If `None`, then the
272 /// name is not known. This does not change while the parser is descending
273 /// into modules, and sub-parsers have new values for this name.
274 pub root_module_name: Option<String>,
275 pub expected_tokens: Vec<TokenType>,
278 #[derive(PartialEq, Eq, Clone)]
281 Keyword(keywords::Keyword),
286 fn to_string(&self) -> String {
288 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
289 TokenType::Operator => "an operator".to_string(),
290 TokenType::Keyword(kw) => format!("`{}`", kw.to_name()),
295 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
296 t.is_plain_ident() || *t == token::Underscore
299 /// Information about the path to a module.
300 pub struct ModulePath {
302 pub path_exists: bool,
303 pub result: Result<ModulePathSuccess, ModulePathError>,
306 pub struct ModulePathSuccess {
307 pub path: ::std::path::PathBuf,
308 pub owns_directory: bool,
311 pub struct ModulePathError {
313 pub help_msg: String,
318 AttributesParsed(ThinAttributes),
319 AlreadyParsed(P<Expr>),
322 impl From<Option<ThinAttributes>> for LhsExpr {
323 fn from(o: Option<ThinAttributes>) -> Self {
324 if let Some(attrs) = o {
325 LhsExpr::AttributesParsed(attrs)
327 LhsExpr::NotYetParsed
332 impl From<P<Expr>> for LhsExpr {
333 fn from(expr: P<Expr>) -> Self {
334 LhsExpr::AlreadyParsed(expr)
338 impl<'a> Parser<'a> {
339 pub fn new(sess: &'a ParseSess,
340 cfg: ast::CrateConfig,
341 mut rdr: Box<Reader+'a>)
344 let tok0 = rdr.real_token();
346 let placeholder = TokenAndSpan {
347 tok: token::Underscore,
353 interner: token::get_ident_interner(),
360 last_token_interpolated: false,
370 restrictions: Restrictions::empty(),
372 obsolete_set: HashSet::new(),
373 mod_path_stack: Vec::new(),
374 open_braces: Vec::new(),
375 owns_directory: true,
376 root_module_name: None,
377 expected_tokens: Vec::new(),
381 /// Convert a token to a string using self's reader
382 pub fn token_to_string(token: &token::Token) -> String {
383 pprust::token_to_string(token)
386 /// Convert the current token to a string using self's reader
387 pub fn this_token_to_string(&self) -> String {
388 Parser::token_to_string(&self.token)
391 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
392 let token_str = Parser::token_to_string(t);
393 let last_span = self.last_span;
394 Err(self.span_fatal(last_span, &format!("unexpected token: `{}`", token_str)))
397 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
398 match self.expect_one_of(&[], &[]) {
400 Ok(_) => unreachable!(),
404 /// Expect and consume the token t. Signal an error if
405 /// the next token is not t.
406 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
407 if self.expected_tokens.is_empty() {
408 if self.token == *t {
412 let token_str = Parser::token_to_string(t);
413 let this_token_str = self.this_token_to_string();
414 Err(self.fatal(&format!("expected `{}`, found `{}`",
419 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
423 /// Expect next token to be edible or inedible token. If edible,
424 /// then consume it; if inedible, then return without consuming
425 /// anything. Signal a fatal error if next token is unexpected.
426 pub fn expect_one_of(&mut self,
427 edible: &[token::Token],
428 inedible: &[token::Token]) -> PResult<'a, ()>{
429 fn tokens_to_string(tokens: &[TokenType]) -> String {
430 let mut i = tokens.iter();
431 // This might be a sign we need a connect method on Iterator.
433 .map_or("".to_string(), |t| t.to_string());
434 i.enumerate().fold(b, |mut b, (i, ref a)| {
435 if tokens.len() > 2 && i == tokens.len() - 2 {
437 } else if tokens.len() == 2 && i == tokens.len() - 2 {
442 b.push_str(&*a.to_string());
446 if edible.contains(&self.token) {
449 } else if inedible.contains(&self.token) {
450 // leave it in the input
453 let mut expected = edible.iter()
454 .map(|x| TokenType::Token(x.clone()))
455 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
456 .chain(self.expected_tokens.iter().cloned())
457 .collect::<Vec<_>>();
458 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
460 let expect = tokens_to_string(&expected[..]);
461 let actual = self.this_token_to_string();
463 &(if expected.len() > 1 {
464 (format!("expected one of {}, found `{}`",
467 } else if expected.is_empty() {
468 (format!("unexpected token: `{}`",
471 (format!("expected {}, found `{}`",
479 /// Check for erroneous `ident { }`; if matches, signal error and
480 /// recover (without consuming any expected input token). Returns
481 /// true if and only if input was consumed for recovery.
482 pub fn check_for_erroneous_unit_struct_expecting(&mut self,
483 expected: &[token::Token])
485 if self.token == token::OpenDelim(token::Brace)
486 && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
487 && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
488 // matched; signal non-fatal error and recover.
489 let span = self.span;
490 self.span_err(span, "unit-like struct construction is written with no trailing `{ }`");
491 self.eat(&token::OpenDelim(token::Brace));
492 self.eat(&token::CloseDelim(token::Brace));
499 /// Commit to parsing a complete expression `e` expected to be
500 /// followed by some token from the set edible + inedible. Recover
501 /// from anticipated input errors, discarding erroneous characters.
502 pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token],
503 inedible: &[token::Token]) -> PResult<'a, ()> {
504 debug!("commit_expr {:?}", e);
505 if let ExprKind::Path(..) = e.node {
506 // might be unit-struct construction; check for recoverableinput error.
507 let expected = edible.iter()
509 .chain(inedible.iter().cloned())
510 .collect::<Vec<_>>();
511 self.check_for_erroneous_unit_struct_expecting(&expected[..]);
513 self.expect_one_of(edible, inedible)
516 pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) -> PResult<'a, ()> {
517 self.commit_expr(e, &[edible], &[])
520 /// Commit to parsing a complete statement `s`, which expects to be
521 /// followed by some token from the set edible + inedible. Check
522 /// for recoverable input errors, discarding erroneous characters.
523 pub fn commit_stmt(&mut self, edible: &[token::Token],
524 inedible: &[token::Token]) -> PResult<'a, ()> {
527 .map_or(false, |t| t.is_ident() || t.is_path()) {
528 let expected = edible.iter()
530 .chain(inedible.iter().cloned())
531 .collect::<Vec<_>>();
532 self.check_for_erroneous_unit_struct_expecting(&expected);
534 self.expect_one_of(edible, inedible)
537 pub fn commit_stmt_expecting(&mut self, edible: token::Token) -> PResult<'a, ()> {
538 self.commit_stmt(&[edible], &[])
541 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
542 fn interpolated_or_expr_span(&self,
543 expr: PResult<'a, P<Expr>>)
544 -> PResult<'a, (Span, P<Expr>)> {
546 if self.last_token_interpolated {
554 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
555 self.check_strict_keywords();
556 self.check_reserved_keywords();
558 token::Ident(i, _) => {
562 token::Interpolated(token::NtIdent(..)) => {
563 self.bug("ident interpolation not converted to real token");
566 let token_str = self.this_token_to_string();
567 Err(self.fatal(&format!("expected ident, found `{}`",
573 pub fn parse_ident_or_self_type(&mut self) -> PResult<'a, ast::Ident> {
574 if self.is_self_type_ident() {
575 self.expect_self_type_ident()
581 pub fn parse_path_list_item(&mut self) -> PResult<'a, ast::PathListItem> {
582 let lo = self.span.lo;
583 let node = if self.eat_keyword(keywords::SelfValue) {
584 let rename = try!(self.parse_rename());
585 ast::PathListMod { id: ast::DUMMY_NODE_ID, rename: rename }
587 let ident = try!(self.parse_ident());
588 let rename = try!(self.parse_rename());
589 ast::PathListIdent { name: ident, rename: rename, id: ast::DUMMY_NODE_ID }
591 let hi = self.last_span.hi;
592 Ok(spanned(lo, hi, node))
595 /// Check if the next token is `tok`, and return `true` if so.
597 /// This method is will automatically add `tok` to `expected_tokens` if `tok` is not
599 pub fn check(&mut self, tok: &token::Token) -> bool {
600 let is_present = self.token == *tok;
601 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
605 /// Consume token 'tok' if it exists. Returns true if the given
606 /// token was present, false otherwise.
607 pub fn eat(&mut self, tok: &token::Token) -> bool {
608 let is_present = self.check(tok);
609 if is_present { self.bump() }
613 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
614 self.expected_tokens.push(TokenType::Keyword(kw));
615 self.token.is_keyword(kw)
618 /// If the next token is the given keyword, eat it and return
619 /// true. Otherwise, return false.
620 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
621 if self.check_keyword(kw) {
629 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
630 if self.token.is_keyword(kw) {
638 /// If the given word is not a keyword, signal an error.
639 /// If the next token is not the given word, signal an error.
640 /// Otherwise, eat it.
641 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
642 if !self.eat_keyword(kw) {
649 /// Signal an error if the given string is a strict keyword
650 pub fn check_strict_keywords(&mut self) {
651 if self.token.is_strict_keyword() {
652 let token_str = self.this_token_to_string();
653 let span = self.span;
655 &format!("expected identifier, found keyword `{}`",
660 /// Signal an error if the current token is a reserved keyword
661 pub fn check_reserved_keywords(&mut self) {
662 if self.token.is_reserved_keyword() {
663 let token_str = self.this_token_to_string();
664 self.fatal(&format!("`{}` is a reserved keyword", token_str)).emit()
668 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
669 /// `&` and continue. If an `&` is not seen, signal an error.
670 fn expect_and(&mut self) -> PResult<'a, ()> {
671 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
673 token::BinOp(token::And) => {
678 let span = self.span;
679 let lo = span.lo + BytePos(1);
680 Ok(self.bump_with(token::BinOp(token::And), lo, span.hi))
682 _ => self.unexpected()
686 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
688 None => {/* everything ok */}
690 let text = suf.as_str();
692 self.span_bug(sp, "found empty literal suffix in Some")
694 self.span_err(sp, &*format!("{} with a suffix is invalid", kind));
700 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
701 /// `<` and continue. If a `<` is not seen, return false.
703 /// This is meant to be used when parsing generics on a path to get the
705 fn eat_lt(&mut self) -> bool {
706 self.expected_tokens.push(TokenType::Token(token::Lt));
712 token::BinOp(token::Shl) => {
713 let span = self.span;
714 let lo = span.lo + BytePos(1);
715 self.bump_with(token::Lt, lo, span.hi);
722 fn expect_lt(&mut self) -> PResult<'a, ()> {
730 /// Expect and consume a GT. if a >> is seen, replace it
731 /// with a single > and continue. If a GT is not seen,
733 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
734 self.expected_tokens.push(TokenType::Token(token::Gt));
740 token::BinOp(token::Shr) => {
741 let span = self.span;
742 let lo = span.lo + BytePos(1);
743 Ok(self.bump_with(token::Gt, lo, span.hi))
745 token::BinOpEq(token::Shr) => {
746 let span = self.span;
747 let lo = span.lo + BytePos(1);
748 Ok(self.bump_with(token::Ge, lo, span.hi))
751 let span = self.span;
752 let lo = span.lo + BytePos(1);
753 Ok(self.bump_with(token::Eq, lo, span.hi))
756 let gt_str = Parser::token_to_string(&token::Gt);
757 let this_token_str = self.this_token_to_string();
758 Err(self.fatal(&format!("expected `{}`, found `{}`",
765 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
766 sep: Option<token::Token>,
768 -> PResult<'a, (P<[T]>, bool)>
769 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
771 let mut v = Vec::new();
772 // This loop works by alternating back and forth between parsing types
773 // and commas. For example, given a string `A, B,>`, the parser would
774 // first parse `A`, then a comma, then `B`, then a comma. After that it
775 // would encounter a `>` and stop. This lets the parser handle trailing
776 // commas in generic parameters, because it can stop either after
777 // parsing a type or after parsing a comma.
779 if self.check(&token::Gt)
780 || self.token == token::BinOp(token::Shr)
781 || self.token == token::Ge
782 || self.token == token::BinOpEq(token::Shr) {
787 match try!(f(self)) {
788 Some(result) => v.push(result),
789 None => return Ok((P::from_vec(v), true))
792 if let Some(t) = sep.as_ref() {
793 try!(self.expect(t));
798 return Ok((P::from_vec(v), false));
801 /// Parse a sequence bracketed by '<' and '>', stopping
803 pub fn parse_seq_to_before_gt<T, F>(&mut self,
804 sep: Option<token::Token>,
806 -> PResult<'a, P<[T]>> where
807 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
809 let (result, returned) = try!(self.parse_seq_to_before_gt_or_return(sep,
810 |p| Ok(Some(try!(f(p))))));
815 pub fn parse_seq_to_gt<T, F>(&mut self,
816 sep: Option<token::Token>,
818 -> PResult<'a, P<[T]>> where
819 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
821 let v = try!(self.parse_seq_to_before_gt(sep, f));
822 try!(self.expect_gt());
826 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
827 sep: Option<token::Token>,
829 -> PResult<'a, (P<[T]>, bool)> where
830 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
832 let (v, returned) = try!(self.parse_seq_to_before_gt_or_return(sep, f));
834 try!(self.expect_gt());
836 return Ok((v, returned));
839 /// Parse a sequence, including the closing delimiter. The function
840 /// f must consume tokens until reaching the next separator or
842 pub fn parse_seq_to_end<T, F>(&mut self,
846 -> PResult<'a, Vec<T>> where
847 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
849 let val = try!(self.parse_seq_to_before_end(ket, sep, f));
854 /// Parse a sequence, not including the closing delimiter. The function
855 /// f must consume tokens until reaching the next separator or
857 pub fn parse_seq_to_before_end<T, F>(&mut self,
861 -> PResult<'a, Vec<T>> where
862 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
864 let mut first: bool = true;
866 while self.token != *ket {
869 if first { first = false; }
870 else { try!(self.expect(t)); }
874 if sep.trailing_sep_allowed && self.check(ket) { break; }
875 v.push(try!(f(self)));
880 /// Parse a sequence, including the closing delimiter. The function
881 /// f must consume tokens until reaching the next separator or
883 pub fn parse_unspanned_seq<T, F>(&mut self,
888 -> PResult<'a, Vec<T>> where
889 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
891 try!(self.expect(bra));
892 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
897 /// Parse a sequence parameter of enum variant. For consistency purposes,
898 /// these should not be empty.
899 pub fn parse_enum_variant_seq<T, F>(&mut self,
904 -> PResult<'a, Vec<T>> where
905 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
907 let result = try!(self.parse_unspanned_seq(bra, ket, sep, f));
908 if result.is_empty() {
909 let last_span = self.last_span;
910 self.span_err(last_span,
911 "nullary enum variants are written with no trailing `( )`");
916 // NB: Do not use this function unless you actually plan to place the
917 // spanned list in the AST.
918 pub fn parse_seq<T, F>(&mut self,
923 -> PResult<'a, Spanned<Vec<T>>> where
924 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
926 let lo = self.span.lo;
927 try!(self.expect(bra));
928 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
929 let hi = self.span.hi;
931 Ok(spanned(lo, hi, result))
934 /// Advance the parser by one token
935 pub fn bump(&mut self) {
936 self.last_span = self.span;
937 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
938 self.last_token = if self.token.is_ident() ||
939 self.token.is_path() ||
940 self.token == token::Comma {
941 Some(Box::new(self.token.clone()))
945 self.last_token_interpolated = self.token.is_interpolated();
946 let next = if self.buffer_start == self.buffer_end {
947 self.reader.real_token()
949 // Avoid token copies with `replace`.
950 let buffer_start = self.buffer_start as usize;
951 let next_index = (buffer_start + 1) & 3;
952 self.buffer_start = next_index as isize;
954 let placeholder = TokenAndSpan {
955 tok: token::Underscore,
958 mem::replace(&mut self.buffer[buffer_start], placeholder)
961 self.token = next.tok;
962 self.tokens_consumed += 1;
963 self.expected_tokens.clear();
964 // check after each token
965 self.check_unknown_macro_variable();
968 /// Advance the parser by one token and return the bumped token.
969 pub fn bump_and_get(&mut self) -> token::Token {
970 let old_token = mem::replace(&mut self.token, token::Underscore);
975 /// Advance the parser using provided token as a next one. Use this when
976 /// consuming a part of a token. For example a single `<` from `<<`.
977 pub fn bump_with(&mut self,
981 self.last_span = mk_sp(self.span.lo, lo);
982 // It would be incorrect to just stash current token, but fortunately
983 // for tokens currently using `bump_with`, last_token will be of no
985 self.last_token = None;
986 self.last_token_interpolated = false;
987 self.span = mk_sp(lo, hi);
989 self.expected_tokens.clear();
992 pub fn buffer_length(&mut self) -> isize {
993 if self.buffer_start <= self.buffer_end {
994 return self.buffer_end - self.buffer_start;
996 return (4 - self.buffer_start) + self.buffer_end;
998 pub fn look_ahead<R, F>(&mut self, distance: usize, f: F) -> R where
999 F: FnOnce(&token::Token) -> R,
1001 let dist = distance as isize;
1002 while self.buffer_length() < dist {
1003 self.buffer[self.buffer_end as usize] = self.reader.real_token();
1004 self.buffer_end = (self.buffer_end + 1) & 3;
1006 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as usize].tok)
1008 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1009 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1011 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1012 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1014 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1015 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1016 err.fileline_help(sp, help);
1019 pub fn bug(&self, m: &str) -> ! {
1020 self.sess.span_diagnostic.span_bug(self.span, m)
1022 pub fn warn(&self, m: &str) {
1023 self.sess.span_diagnostic.span_warn(self.span, m)
1025 pub fn span_warn(&self, sp: Span, m: &str) {
1026 self.sess.span_diagnostic.span_warn(sp, m)
1028 pub fn span_err(&self, sp: Span, m: &str) {
1029 self.sess.span_diagnostic.span_err(sp, m)
1031 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1032 self.sess.span_diagnostic.span_bug(sp, m)
1034 pub fn abort_if_errors(&self) {
1035 self.sess.span_diagnostic.abort_if_errors();
1038 pub fn diagnostic(&self) -> &'a errors::Handler {
1039 &self.sess.span_diagnostic
1042 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
1046 /// Is the current token one of the keywords that signals a bare function
1048 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1049 self.check_keyword(keywords::Fn) ||
1050 self.check_keyword(keywords::Unsafe) ||
1051 self.check_keyword(keywords::Extern)
1054 pub fn get_lifetime(&mut self) -> ast::Ident {
1056 token::Lifetime(ref ident) => *ident,
1057 _ => self.bug("not a lifetime"),
1061 pub fn parse_for_in_type(&mut self) -> PResult<'a, Ty_> {
1063 Parses whatever can come after a `for` keyword in a type.
1064 The `for` has already been consumed.
1068 - for <'lt> |S| -> T
1072 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1073 - for <'lt> path::foo(a, b)
1078 let lo = self.span.lo;
1080 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
1082 // examine next token to decide to do
1083 if self.token_is_bare_fn_keyword() {
1084 self.parse_ty_bare_fn(lifetime_defs)
1086 let hi = self.span.hi;
1087 let trait_ref = try!(self.parse_trait_ref());
1088 let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1089 trait_ref: trait_ref,
1090 span: mk_sp(lo, hi)};
1091 let other_bounds = if self.eat(&token::BinOp(token::Plus)) {
1092 try!(self.parse_ty_param_bounds(BoundParsingMode::Bare))
1097 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1098 .chain(other_bounds.into_vec())
1100 Ok(ast::TyPolyTraitRef(all_bounds))
1104 pub fn parse_ty_path(&mut self) -> PResult<'a, Ty_> {
1105 Ok(TyPath(None, try!(self.parse_path(LifetimeAndTypesWithoutColons))))
1108 /// parse a TyBareFn type:
1109 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>) -> PResult<'a, Ty_> {
1112 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1113 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1116 | | | Argument types
1122 let unsafety = try!(self.parse_unsafety());
1123 let abi = if self.eat_keyword(keywords::Extern) {
1124 try!(self.parse_opt_abi()).unwrap_or(Abi::C)
1129 try!(self.expect_keyword(keywords::Fn));
1130 let (inputs, variadic) = try!(self.parse_fn_args(false, true));
1131 let ret_ty = try!(self.parse_ret_ty());
1132 let decl = P(FnDecl {
1137 Ok(TyBareFn(P(BareFnTy {
1140 lifetimes: lifetime_defs,
1145 /// Parses an obsolete closure kind (`&:`, `&mut:`, or `:`).
1146 pub fn parse_obsolete_closure_kind(&mut self) -> PResult<'a, ()> {
1147 let lo = self.span.lo;
1149 self.check(&token::BinOp(token::And)) &&
1150 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1151 self.look_ahead(2, |t| *t == token::Colon)
1157 self.token == token::BinOp(token::And) &&
1158 self.look_ahead(1, |t| *t == token::Colon)
1163 self.eat(&token::Colon)
1170 let span = mk_sp(lo, self.span.hi);
1171 self.obsolete(span, ObsoleteSyntax::ClosureKind);
1175 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1176 if self.eat_keyword(keywords::Unsafe) {
1177 return Ok(Unsafety::Unsafe);
1179 return Ok(Unsafety::Normal);
1183 /// Parse the items in a trait declaration
1184 pub fn parse_trait_items(&mut self) -> PResult<'a, Vec<P<TraitItem>>> {
1185 self.parse_unspanned_seq(
1186 &token::OpenDelim(token::Brace),
1187 &token::CloseDelim(token::Brace),
1189 |p| -> PResult<'a, P<TraitItem>> {
1190 maybe_whole!(no_clone p, NtTraitItem);
1191 let mut attrs = try!(p.parse_outer_attributes());
1194 let (name, node) = if p.eat_keyword(keywords::Type) {
1195 let TyParam {ident, bounds, default, ..} = try!(p.parse_ty_param());
1196 try!(p.expect(&token::Semi));
1197 (ident, TypeTraitItem(bounds, default))
1198 } else if p.is_const_item() {
1199 try!(p.expect_keyword(keywords::Const));
1200 let ident = try!(p.parse_ident());
1201 try!(p.expect(&token::Colon));
1202 let ty = try!(p.parse_ty_sum());
1203 let default = if p.check(&token::Eq) {
1205 let expr = try!(p.parse_expr());
1206 try!(p.commit_expr_expecting(&expr, token::Semi));
1209 try!(p.expect(&token::Semi));
1212 (ident, ConstTraitItem(ty, default))
1214 let (constness, unsafety, abi) = try!(p.parse_fn_front_matter());
1216 let ident = try!(p.parse_ident());
1217 let mut generics = try!(p.parse_generics());
1219 let (explicit_self, d) = try!(p.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1220 // This is somewhat dubious; We don't want to allow
1221 // argument names to be left off if there is a
1223 p.parse_arg_general(false)
1226 generics.where_clause = try!(p.parse_where_clause());
1227 let sig = ast::MethodSig {
1229 constness: constness,
1233 explicit_self: explicit_self,
1236 let body = match p.token {
1239 debug!("parse_trait_methods(): parsing required method");
1242 token::OpenDelim(token::Brace) => {
1243 debug!("parse_trait_methods(): parsing provided method");
1244 let (inner_attrs, body) =
1245 try!(p.parse_inner_attrs_and_block());
1246 attrs.extend(inner_attrs.iter().cloned());
1251 let token_str = p.this_token_to_string();
1252 return Err(p.fatal(&format!("expected `;` or `{{`, found `{}`",
1256 (ident, ast::MethodTraitItem(sig, body))
1260 id: ast::DUMMY_NODE_ID,
1264 span: mk_sp(lo, p.last_span.hi),
1269 /// Parse a possibly mutable type
1270 pub fn parse_mt(&mut self) -> PResult<'a, MutTy> {
1271 let mutbl = try!(self.parse_mutability());
1272 let t = try!(self.parse_ty());
1273 Ok(MutTy { ty: t, mutbl: mutbl })
1276 /// Parse optional return type [ -> TY ] in function decl
1277 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1278 if self.eat(&token::RArrow) {
1279 if self.eat(&token::Not) {
1280 Ok(FunctionRetTy::None(self.last_span))
1282 Ok(FunctionRetTy::Ty(try!(self.parse_ty())))
1285 let pos = self.span.lo;
1286 Ok(FunctionRetTy::Default(mk_sp(pos, pos)))
1290 /// Parse a type in a context where `T1+T2` is allowed.
1291 pub fn parse_ty_sum(&mut self) -> PResult<'a, P<Ty>> {
1292 let lo = self.span.lo;
1293 let lhs = try!(self.parse_ty());
1295 if !self.eat(&token::BinOp(token::Plus)) {
1299 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
1301 // In type grammar, `+` is treated like a binary operator,
1302 // and hence both L and R side are required.
1303 if bounds.is_empty() {
1304 let last_span = self.last_span;
1305 self.span_err(last_span,
1306 "at least one type parameter bound \
1307 must be specified");
1310 let sp = mk_sp(lo, self.last_span.hi);
1311 let sum = ast::TyObjectSum(lhs, bounds);
1312 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp}))
1316 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1317 maybe_whole!(no_clone self, NtTy);
1319 let lo = self.span.lo;
1321 let t = if self.check(&token::OpenDelim(token::Paren)) {
1324 // (t) is a parenthesized ty
1325 // (t,) is the type of a tuple with only one field,
1327 let mut ts = vec![];
1328 let mut last_comma = false;
1329 while self.token != token::CloseDelim(token::Paren) {
1330 ts.push(try!(self.parse_ty_sum()));
1331 if self.check(&token::Comma) {
1340 try!(self.expect(&token::CloseDelim(token::Paren)));
1341 if ts.len() == 1 && !last_comma {
1342 TyParen(ts.into_iter().nth(0).unwrap())
1346 } else if self.check(&token::BinOp(token::Star)) {
1347 // STAR POINTER (bare pointer?)
1349 TyPtr(try!(self.parse_ptr()))
1350 } else if self.check(&token::OpenDelim(token::Bracket)) {
1352 try!(self.expect(&token::OpenDelim(token::Bracket)));
1353 let t = try!(self.parse_ty_sum());
1355 // Parse the `; e` in `[ i32; e ]`
1356 // where `e` is a const expression
1357 let t = match try!(self.maybe_parse_fixed_length_of_vec()) {
1359 Some(suffix) => TyFixedLengthVec(t, suffix)
1361 try!(self.expect(&token::CloseDelim(token::Bracket)));
1363 } else if self.check(&token::BinOp(token::And)) ||
1364 self.token == token::AndAnd {
1366 try!(self.expect_and());
1367 try!(self.parse_borrowed_pointee())
1368 } else if self.check_keyword(keywords::For) {
1369 try!(self.parse_for_in_type())
1370 } else if self.token_is_bare_fn_keyword() {
1372 try!(self.parse_ty_bare_fn(Vec::new()))
1373 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1375 // In order to not be ambiguous, the type must be surrounded by parens.
1376 try!(self.expect(&token::OpenDelim(token::Paren)));
1377 let e = try!(self.parse_expr());
1378 try!(self.expect(&token::CloseDelim(token::Paren)));
1380 } else if self.eat_lt() {
1383 try!(self.parse_qualified_path(NoTypesAllowed));
1385 TyPath(Some(qself), path)
1386 } else if self.check(&token::ModSep) ||
1387 self.token.is_ident() ||
1388 self.token.is_path() {
1389 let path = try!(self.parse_path(LifetimeAndTypesWithoutColons));
1390 if self.check(&token::Not) {
1393 let delim = try!(self.expect_open_delim());
1394 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
1396 |p| p.parse_token_tree()));
1397 let hi = self.span.hi;
1398 TyMac(spanned(lo, hi, Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT }))
1403 } else if self.eat(&token::Underscore) {
1404 // TYPE TO BE INFERRED
1407 let this_token_str = self.this_token_to_string();
1408 let msg = format!("expected type, found `{}`", this_token_str);
1409 return Err(self.fatal(&msg[..]));
1412 let sp = mk_sp(lo, self.last_span.hi);
1413 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp}))
1416 pub fn parse_borrowed_pointee(&mut self) -> PResult<'a, Ty_> {
1417 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1418 let opt_lifetime = try!(self.parse_opt_lifetime());
1420 let mt = try!(self.parse_mt());
1421 return Ok(TyRptr(opt_lifetime, mt));
1424 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1425 let mutbl = if self.eat_keyword(keywords::Mut) {
1427 } else if self.eat_keyword(keywords::Const) {
1430 let span = self.last_span;
1432 "bare raw pointers are no longer allowed, you should \
1433 likely use `*mut T`, but otherwise `*T` is now \
1434 known as `*const T`");
1437 let t = try!(self.parse_ty());
1438 Ok(MutTy { ty: t, mutbl: mutbl })
1441 pub fn is_named_argument(&mut self) -> bool {
1442 let offset = match self.token {
1443 token::BinOp(token::And) => 1,
1445 _ if self.token.is_keyword(keywords::Mut) => 1,
1449 debug!("parser is_named_argument offset:{}", offset);
1452 is_plain_ident_or_underscore(&self.token)
1453 && self.look_ahead(1, |t| *t == token::Colon)
1455 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1456 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1460 /// This version of parse arg doesn't necessarily require
1461 /// identifier names.
1462 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1463 maybe_whole!(no_clone self, NtArg);
1465 let pat = if require_name || self.is_named_argument() {
1466 debug!("parse_arg_general parse_pat (require_name:{})",
1468 let pat = try!(self.parse_pat());
1470 try!(self.expect(&token::Colon));
1473 debug!("parse_arg_general ident_to_pat");
1474 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1476 special_idents::invalid)
1479 let t = try!(self.parse_ty_sum());
1484 id: ast::DUMMY_NODE_ID,
1488 /// Parse a single function argument
1489 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1490 self.parse_arg_general(true)
1493 /// Parse an argument in a lambda header e.g. |arg, arg|
1494 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1495 let pat = try!(self.parse_pat());
1496 let t = if self.eat(&token::Colon) {
1497 try!(self.parse_ty_sum())
1500 id: ast::DUMMY_NODE_ID,
1502 span: mk_sp(self.span.lo, self.span.hi),
1508 id: ast::DUMMY_NODE_ID
1512 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1513 if self.check(&token::Semi) {
1515 Ok(Some(try!(self.parse_expr())))
1521 /// Matches token_lit = LIT_INTEGER | ...
1522 pub fn lit_from_token(&self, tok: &token::Token) -> PResult<'a, Lit_> {
1524 token::Interpolated(token::NtExpr(ref v)) => {
1526 ExprKind::Lit(ref lit) => { Ok(lit.node.clone()) }
1527 _ => { return self.unexpected_last(tok); }
1530 token::Literal(lit, suf) => {
1531 let (suffix_illegal, out) = match lit {
1532 token::Byte(i) => (true, LitByte(parse::byte_lit(&i.as_str()).0)),
1533 token::Char(i) => (true, LitChar(parse::char_lit(&i.as_str()).0)),
1535 // there are some valid suffixes for integer and
1536 // float literals, so all the handling is done
1538 token::Integer(s) => {
1539 (false, parse::integer_lit(&s.as_str(),
1540 suf.as_ref().map(|s| s.as_str()),
1541 &self.sess.span_diagnostic,
1544 token::Float(s) => {
1545 (false, parse::float_lit(&s.as_str(),
1546 suf.as_ref().map(|s| s.as_str()),
1547 &self.sess.span_diagnostic,
1553 LitStr(token::intern_and_get_ident(&parse::str_lit(&s.as_str())),
1556 token::StrRaw(s, n) => {
1559 token::intern_and_get_ident(&parse::raw_str_lit(&s.as_str())),
1562 token::ByteStr(i) =>
1563 (true, LitByteStr(parse::byte_str_lit(&i.as_str()))),
1564 token::ByteStrRaw(i, _) =>
1566 LitByteStr(Rc::new(i.to_string().into_bytes()))),
1570 let sp = self.last_span;
1571 self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1576 _ => { return self.unexpected_last(tok); }
1580 /// Matches lit = true | false | token_lit
1581 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1582 let lo = self.span.lo;
1583 let lit = if self.eat_keyword(keywords::True) {
1585 } else if self.eat_keyword(keywords::False) {
1588 let token = self.bump_and_get();
1589 let lit = try!(self.lit_from_token(&token));
1592 Ok(codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) })
1595 /// matches '-' lit | lit
1596 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1597 let minus_lo = self.span.lo;
1598 let minus_present = self.eat(&token::BinOp(token::Minus));
1599 let lo = self.span.lo;
1600 let literal = P(try!(self.parse_lit()));
1601 let hi = self.last_span.hi;
1602 let expr = self.mk_expr(lo, hi, ExprKind::Lit(literal), None);
1605 let minus_hi = self.last_span.hi;
1606 let unary = self.mk_unary(UnOp::Neg, expr);
1607 Ok(self.mk_expr(minus_lo, minus_hi, unary, None))
1613 /// Parses qualified path.
1615 /// Assumes that the leading `<` has been parsed already.
1617 /// Qualifed paths are a part of the universal function call
1620 /// `qualified_path = <type [as trait_ref]>::path`
1622 /// See `parse_path` for `mode` meaning.
1627 /// `<T as U>::F::a::<S>`
1628 pub fn parse_qualified_path(&mut self, mode: PathParsingMode)
1629 -> PResult<'a, (QSelf, ast::Path)> {
1630 let span = self.last_span;
1631 let self_type = try!(self.parse_ty_sum());
1632 let mut path = if self.eat_keyword(keywords::As) {
1633 try!(self.parse_path(LifetimeAndTypesWithoutColons))
1644 position: path.segments.len()
1647 try!(self.expect(&token::Gt));
1648 try!(self.expect(&token::ModSep));
1650 let segments = match mode {
1651 LifetimeAndTypesWithoutColons => {
1652 try!(self.parse_path_segments_without_colons())
1654 LifetimeAndTypesWithColons => {
1655 try!(self.parse_path_segments_with_colons())
1658 try!(self.parse_path_segments_without_types())
1661 path.segments.extend(segments);
1663 path.span.hi = self.last_span.hi;
1668 /// Parses a path and optional type parameter bounds, depending on the
1669 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1670 /// bounds are permitted and whether `::` must precede type parameter
1672 pub fn parse_path(&mut self, mode: PathParsingMode) -> PResult<'a, ast::Path> {
1673 // Check for a whole path...
1674 let found = match self.token {
1675 token::Interpolated(token::NtPath(_)) => Some(self.bump_and_get()),
1678 if let Some(token::Interpolated(token::NtPath(path))) = found {
1682 let lo = self.span.lo;
1683 let is_global = self.eat(&token::ModSep);
1685 // Parse any number of segments and bound sets. A segment is an
1686 // identifier followed by an optional lifetime and a set of types.
1687 // A bound set is a set of type parameter bounds.
1688 let segments = match mode {
1689 LifetimeAndTypesWithoutColons => {
1690 try!(self.parse_path_segments_without_colons())
1692 LifetimeAndTypesWithColons => {
1693 try!(self.parse_path_segments_with_colons())
1696 try!(self.parse_path_segments_without_types())
1700 // Assemble the span.
1701 let span = mk_sp(lo, self.last_span.hi);
1703 // Assemble the result.
1712 /// - `a::b<T,U>::c<V,W>`
1713 /// - `a::b<T,U>::c(V) -> W`
1714 /// - `a::b<T,U>::c(V)`
1715 pub fn parse_path_segments_without_colons(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1716 let mut segments = Vec::new();
1718 // First, parse an identifier.
1719 let identifier = try!(self.parse_ident_or_self_type());
1721 // Parse types, optionally.
1722 let parameters = if self.eat_lt() {
1723 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1725 ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
1726 lifetimes: lifetimes,
1727 types: P::from_vec(types),
1728 bindings: P::from_vec(bindings),
1730 } else if self.eat(&token::OpenDelim(token::Paren)) {
1731 let lo = self.last_span.lo;
1733 let inputs = try!(self.parse_seq_to_end(
1734 &token::CloseDelim(token::Paren),
1735 seq_sep_trailing_allowed(token::Comma),
1736 |p| p.parse_ty_sum()));
1738 let output_ty = if self.eat(&token::RArrow) {
1739 Some(try!(self.parse_ty()))
1744 let hi = self.last_span.hi;
1746 ast::PathParameters::Parenthesized(ast::ParenthesizedParameterData {
1747 span: mk_sp(lo, hi),
1752 ast::PathParameters::none()
1755 // Assemble and push the result.
1756 segments.push(ast::PathSegment { identifier: identifier,
1757 parameters: parameters });
1759 // Continue only if we see a `::`
1760 if !self.eat(&token::ModSep) {
1761 return Ok(segments);
1767 /// - `a::b::<T,U>::c`
1768 pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1769 let mut segments = Vec::new();
1771 // First, parse an identifier.
1772 let identifier = try!(self.parse_ident_or_self_type());
1774 // If we do not see a `::`, stop.
1775 if !self.eat(&token::ModSep) {
1776 segments.push(ast::PathSegment {
1777 identifier: identifier,
1778 parameters: ast::PathParameters::none()
1780 return Ok(segments);
1783 // Check for a type segment.
1785 // Consumed `a::b::<`, go look for types
1786 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1787 let parameters = ast::AngleBracketedParameterData {
1788 lifetimes: lifetimes,
1789 types: P::from_vec(types),
1790 bindings: P::from_vec(bindings),
1792 segments.push(ast::PathSegment {
1793 identifier: identifier,
1794 parameters: ast::PathParameters::AngleBracketed(parameters),
1797 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1798 if !self.eat(&token::ModSep) {
1799 return Ok(segments);
1802 // Consumed `a::`, go look for `b`
1803 segments.push(ast::PathSegment {
1804 identifier: identifier,
1805 parameters: ast::PathParameters::none(),
1814 pub fn parse_path_segments_without_types(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1815 let mut segments = Vec::new();
1817 // First, parse an identifier.
1818 let identifier = try!(self.parse_ident_or_self_type());
1820 // Assemble and push the result.
1821 segments.push(ast::PathSegment {
1822 identifier: identifier,
1823 parameters: ast::PathParameters::none()
1826 // If we do not see a `::`, stop.
1827 if !self.eat(&token::ModSep) {
1828 return Ok(segments);
1833 /// parses 0 or 1 lifetime
1834 pub fn parse_opt_lifetime(&mut self) -> PResult<'a, Option<ast::Lifetime>> {
1836 token::Lifetime(..) => {
1837 Ok(Some(try!(self.parse_lifetime())))
1845 /// Parses a single lifetime
1846 /// Matches lifetime = LIFETIME
1847 pub fn parse_lifetime(&mut self) -> PResult<'a, ast::Lifetime> {
1849 token::Lifetime(i) => {
1850 let span = self.span;
1852 return Ok(ast::Lifetime {
1853 id: ast::DUMMY_NODE_ID,
1859 return Err(self.fatal("expected a lifetime name"));
1864 /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def =
1865 /// lifetime [':' lifetimes]`
1866 pub fn parse_lifetime_defs(&mut self) -> PResult<'a, Vec<ast::LifetimeDef>> {
1868 let mut res = Vec::new();
1871 token::Lifetime(_) => {
1872 let lifetime = try!(self.parse_lifetime());
1874 if self.eat(&token::Colon) {
1875 try!(self.parse_lifetimes(token::BinOp(token::Plus)))
1879 res.push(ast::LifetimeDef { lifetime: lifetime,
1889 token::Comma => { self.bump();}
1890 token::Gt => { return Ok(res); }
1891 token::BinOp(token::Shr) => { return Ok(res); }
1893 let this_token_str = self.this_token_to_string();
1894 let msg = format!("expected `,` or `>` after lifetime \
1897 return Err(self.fatal(&msg[..]));
1903 /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
1904 /// one too, but putting that in there messes up the grammar....
1906 /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
1907 /// either a comma or `>`. Used when parsing type parameter lists, where we expect something
1908 /// like `<'a, 'b, T>`.
1909 pub fn parse_lifetimes(&mut self, sep: token::Token) -> PResult<'a, Vec<ast::Lifetime>> {
1911 let mut res = Vec::new();
1914 token::Lifetime(_) => {
1915 res.push(try!(self.parse_lifetime()));
1922 if self.token != sep {
1930 /// Parse mutability declaration (mut/const/imm)
1931 pub fn parse_mutability(&mut self) -> PResult<'a, Mutability> {
1932 if self.eat_keyword(keywords::Mut) {
1939 /// Parse ident COLON expr
1940 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1941 let lo = self.span.lo;
1942 let i = try!(self.parse_ident());
1943 let hi = self.last_span.hi;
1944 try!(self.expect(&token::Colon));
1945 let e = try!(self.parse_expr());
1947 ident: spanned(lo, hi, i),
1948 span: mk_sp(lo, e.span.hi),
1953 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos,
1954 node: ExprKind, attrs: ThinAttributes) -> P<Expr> {
1956 id: ast::DUMMY_NODE_ID,
1958 span: mk_sp(lo, hi),
1963 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
1964 ExprKind::Unary(unop, expr)
1967 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1968 ExprKind::Binary(binop, lhs, rhs)
1971 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
1972 ExprKind::Call(f, args)
1975 fn mk_method_call(&mut self,
1976 ident: ast::SpannedIdent,
1980 ExprKind::MethodCall(ident, tps, args)
1983 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
1984 ExprKind::Index(expr, idx)
1987 pub fn mk_range(&mut self,
1988 start: Option<P<Expr>>,
1989 end: Option<P<Expr>>)
1991 ExprKind::Range(start, end)
1994 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::ExprKind {
1995 ExprKind::Field(expr, ident)
1998 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
1999 ExprKind::TupField(expr, idx)
2002 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2003 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2004 ExprKind::AssignOp(binop, lhs, rhs)
2007 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos,
2008 m: Mac_, attrs: ThinAttributes) -> P<Expr> {
2010 id: ast::DUMMY_NODE_ID,
2011 node: ExprKind::Mac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
2012 span: mk_sp(lo, hi),
2017 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinAttributes) -> P<Expr> {
2018 let span = &self.span;
2019 let lv_lit = P(codemap::Spanned {
2020 node: LitInt(i as u64, ast::UnsignedIntLit(TyU32)),
2025 id: ast::DUMMY_NODE_ID,
2026 node: ExprKind::Lit(lv_lit),
2032 fn expect_open_delim(&mut self) -> PResult<'a, token::DelimToken> {
2033 self.expected_tokens.push(TokenType::Token(token::Gt));
2035 token::OpenDelim(delim) => {
2039 _ => Err(self.fatal("expected open delimiter")),
2043 /// At the bottom (top?) of the precedence hierarchy,
2044 /// parse things like parenthesized exprs,
2045 /// macros, return, etc.
2047 /// NB: This does not parse outer attributes,
2048 /// and is private because it only works
2049 /// correctly if called from parse_dot_or_call_expr().
2050 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2051 maybe_whole_expr!(self);
2053 // Outer attributes are already parsed and will be
2054 // added to the return value after the fact.
2056 // Therefore, prevent sub-parser from parsing
2057 // attributes by giving them a empty "already parsed" list.
2058 let mut attrs = None;
2060 let lo = self.span.lo;
2061 let mut hi = self.span.hi;
2065 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2067 token::OpenDelim(token::Paren) => {
2070 let attrs = try!(self.parse_inner_attributes())
2074 // (e) is parenthesized e
2075 // (e,) is a tuple with only one field, e
2076 let mut es = vec![];
2077 let mut trailing_comma = false;
2078 while self.token != token::CloseDelim(token::Paren) {
2079 es.push(try!(self.parse_expr()));
2080 try!(self.commit_expr(&**es.last().unwrap(), &[],
2081 &[token::Comma, token::CloseDelim(token::Paren)]));
2082 if self.check(&token::Comma) {
2083 trailing_comma = true;
2087 trailing_comma = false;
2093 hi = self.last_span.hi;
2094 return if es.len() == 1 && !trailing_comma {
2095 Ok(self.mk_expr(lo, hi, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs))
2097 Ok(self.mk_expr(lo, hi, ExprKind::Tup(es), attrs))
2100 token::OpenDelim(token::Brace) => {
2101 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2103 token::BinOp(token::Or) | token::OrOr => {
2104 let lo = self.span.lo;
2105 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2107 token::Ident(id @ ast::Ident {
2108 name: token::SELF_KEYWORD_NAME,
2110 }, token::Plain) => {
2112 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2113 ex = ExprKind::Path(None, path);
2114 hi = self.last_span.hi;
2116 token::OpenDelim(token::Bracket) => {
2119 let inner_attrs = try!(self.parse_inner_attributes())
2121 attrs.update(|attrs| attrs.append(inner_attrs));
2123 if self.check(&token::CloseDelim(token::Bracket)) {
2126 ex = ExprKind::Vec(Vec::new());
2129 let first_expr = try!(self.parse_expr());
2130 if self.check(&token::Semi) {
2131 // Repeating array syntax: [ 0; 512 ]
2133 let count = try!(self.parse_expr());
2134 try!(self.expect(&token::CloseDelim(token::Bracket)));
2135 ex = ExprKind::Repeat(first_expr, count);
2136 } else if self.check(&token::Comma) {
2137 // Vector with two or more elements.
2139 let remaining_exprs = try!(self.parse_seq_to_end(
2140 &token::CloseDelim(token::Bracket),
2141 seq_sep_trailing_allowed(token::Comma),
2142 |p| Ok(try!(p.parse_expr()))
2144 let mut exprs = vec!(first_expr);
2145 exprs.extend(remaining_exprs);
2146 ex = ExprKind::Vec(exprs);
2148 // Vector with one element.
2149 try!(self.expect(&token::CloseDelim(token::Bracket)));
2150 ex = ExprKind::Vec(vec!(first_expr));
2153 hi = self.last_span.hi;
2158 try!(self.parse_qualified_path(LifetimeAndTypesWithColons));
2160 return Ok(self.mk_expr(lo, hi, ExprKind::Path(Some(qself), path), attrs));
2162 if self.eat_keyword(keywords::Move) {
2163 let lo = self.last_span.lo;
2164 return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2166 if self.eat_keyword(keywords::If) {
2167 return self.parse_if_expr(attrs);
2169 if self.eat_keyword(keywords::For) {
2170 let lo = self.last_span.lo;
2171 return self.parse_for_expr(None, lo, attrs);
2173 if self.eat_keyword(keywords::While) {
2174 let lo = self.last_span.lo;
2175 return self.parse_while_expr(None, lo, attrs);
2177 if self.token.is_lifetime() {
2178 let lifetime = self.get_lifetime();
2179 let lo = self.span.lo;
2181 try!(self.expect(&token::Colon));
2182 if self.eat_keyword(keywords::While) {
2183 return self.parse_while_expr(Some(lifetime), lo, attrs)
2185 if self.eat_keyword(keywords::For) {
2186 return self.parse_for_expr(Some(lifetime), lo, attrs)
2188 if self.eat_keyword(keywords::Loop) {
2189 return self.parse_loop_expr(Some(lifetime), lo, attrs)
2191 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2193 if self.eat_keyword(keywords::Loop) {
2194 let lo = self.last_span.lo;
2195 return self.parse_loop_expr(None, lo, attrs);
2197 if self.eat_keyword(keywords::Continue) {
2198 let ex = if self.token.is_lifetime() {
2199 let ex = ExprKind::Again(Some(Spanned{
2200 node: self.get_lifetime(),
2206 ExprKind::Again(None)
2208 let hi = self.last_span.hi;
2209 return Ok(self.mk_expr(lo, hi, ex, attrs));
2211 if self.eat_keyword(keywords::Match) {
2212 return self.parse_match_expr(attrs);
2214 if self.eat_keyword(keywords::Unsafe) {
2215 return self.parse_block_expr(
2217 BlockCheckMode::Unsafe(ast::UserProvided),
2220 if self.eat_keyword(keywords::Return) {
2221 if self.token.can_begin_expr() {
2222 let e = try!(self.parse_expr());
2224 ex = ExprKind::Ret(Some(e));
2226 ex = ExprKind::Ret(None);
2228 } else if self.eat_keyword(keywords::Break) {
2229 if self.token.is_lifetime() {
2230 ex = ExprKind::Break(Some(Spanned {
2231 node: self.get_lifetime(),
2236 ex = ExprKind::Break(None);
2238 hi = self.last_span.hi;
2239 } else if self.token.is_keyword(keywords::Let) {
2240 // Catch this syntax error here, instead of in `check_strict_keywords`, so
2241 // that we can explicitly mention that let is not to be used as an expression
2242 let mut db = self.fatal("expected expression, found statement (`let`)");
2243 db.note("variable declaration using `let` is a statement");
2245 } else if self.check(&token::ModSep) ||
2246 self.token.is_ident() &&
2247 !self.check_keyword(keywords::True) &&
2248 !self.check_keyword(keywords::False) {
2250 try!(self.parse_path(LifetimeAndTypesWithColons));
2252 // `!`, as an operator, is prefix, so we know this isn't that
2253 if self.check(&token::Not) {
2254 // MACRO INVOCATION expression
2257 let delim = try!(self.expect_open_delim());
2258 let tts = try!(self.parse_seq_to_end(
2259 &token::CloseDelim(delim),
2261 |p| p.parse_token_tree()));
2262 let hi = self.last_span.hi;
2264 return Ok(self.mk_mac_expr(lo,
2266 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT },
2269 if self.check(&token::OpenDelim(token::Brace)) {
2270 // This is a struct literal, unless we're prohibited
2271 // from parsing struct literals here.
2272 let prohibited = self.restrictions.contains(
2273 Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2276 // It's a struct literal.
2278 let mut fields = Vec::new();
2279 let mut base = None;
2281 let attrs = attrs.append(
2282 try!(self.parse_inner_attributes())
2283 .into_thin_attrs());
2285 while self.token != token::CloseDelim(token::Brace) {
2286 if self.eat(&token::DotDot) {
2287 base = Some(try!(self.parse_expr()));
2291 fields.push(try!(self.parse_field()));
2292 try!(self.commit_expr(&*fields.last().unwrap().expr,
2294 &[token::CloseDelim(token::Brace)]));
2298 try!(self.expect(&token::CloseDelim(token::Brace)));
2299 ex = ExprKind::Struct(pth, fields, base);
2300 return Ok(self.mk_expr(lo, hi, ex, attrs));
2305 ex = ExprKind::Path(None, pth);
2307 // other literal expression
2308 let lit = try!(self.parse_lit());
2310 ex = ExprKind::Lit(P(lit));
2315 return Ok(self.mk_expr(lo, hi, ex, attrs));
2318 fn parse_or_use_outer_attributes(&mut self,
2319 already_parsed_attrs: Option<ThinAttributes>)
2320 -> PResult<'a, ThinAttributes> {
2321 if let Some(attrs) = already_parsed_attrs {
2324 self.parse_outer_attributes().map(|a| a.into_thin_attrs())
2328 /// Parse a block or unsafe block
2329 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode,
2330 attrs: ThinAttributes)
2331 -> PResult<'a, P<Expr>> {
2333 let outer_attrs = attrs;
2334 try!(self.expect(&token::OpenDelim(token::Brace)));
2336 let inner_attrs = try!(self.parse_inner_attributes()).into_thin_attrs();
2337 let attrs = outer_attrs.append(inner_attrs);
2339 let blk = try!(self.parse_block_tail(lo, blk_mode));
2340 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprKind::Block(blk), attrs));
2343 /// parse a.b or a(13) or a[4] or just a
2344 pub fn parse_dot_or_call_expr(&mut self,
2345 already_parsed_attrs: Option<ThinAttributes>)
2346 -> PResult<'a, P<Expr>> {
2347 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2349 let b = self.parse_bottom_expr();
2350 let (span, b) = try!(self.interpolated_or_expr_span(b));
2351 self.parse_dot_or_call_expr_with(b, span.lo, attrs)
2354 pub fn parse_dot_or_call_expr_with(&mut self,
2357 attrs: ThinAttributes)
2358 -> PResult<'a, P<Expr>> {
2359 // Stitch the list of outer attributes onto the return value.
2360 // A little bit ugly, but the best way given the current code
2362 self.parse_dot_or_call_expr_with_(e0, lo)
2364 expr.map(|mut expr| {
2365 expr.attrs.update(|a| a.prepend(attrs));
2367 ExprKind::If(..) | ExprKind::IfLet(..) => {
2368 if !expr.attrs.as_attr_slice().is_empty() {
2369 // Just point to the first attribute in there...
2370 let span = expr.attrs.as_attr_slice()[0].span;
2373 "attributes are not yet allowed on `if` \
2384 // Assuming we have just parsed `.foo` (i.e., a dot and an ident), continue
2385 // parsing into an expression.
2386 fn parse_dot_suffix(&mut self,
2389 self_value: P<Expr>,
2391 -> PResult<'a, P<Expr>> {
2392 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2393 try!(self.expect_lt());
2394 try!(self.parse_generic_values_after_lt())
2396 (Vec::new(), Vec::new(), Vec::new())
2399 if !bindings.is_empty() {
2400 let last_span = self.last_span;
2401 self.span_err(last_span, "type bindings are only permitted on trait paths");
2404 Ok(match self.token {
2405 // expr.f() method call.
2406 token::OpenDelim(token::Paren) => {
2407 let mut es = try!(self.parse_unspanned_seq(
2408 &token::OpenDelim(token::Paren),
2409 &token::CloseDelim(token::Paren),
2410 seq_sep_trailing_allowed(token::Comma),
2411 |p| Ok(try!(p.parse_expr()))
2413 let hi = self.last_span.hi;
2415 es.insert(0, self_value);
2416 let id = spanned(ident_span.lo, ident_span.hi, ident);
2417 let nd = self.mk_method_call(id, tys, es);
2418 self.mk_expr(lo, hi, nd, None)
2422 if !tys.is_empty() {
2423 let last_span = self.last_span;
2424 self.span_err(last_span,
2425 "field expressions may not \
2426 have type parameters");
2429 let id = spanned(ident_span.lo, ident_span.hi, ident);
2430 let field = self.mk_field(self_value, id);
2431 self.mk_expr(lo, ident_span.hi, field, None)
2436 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: BytePos) -> PResult<'a, P<Expr>> {
2441 if self.eat(&token::Dot) {
2443 token::Ident(i, _) => {
2444 let dot_pos = self.last_span.hi;
2448 e = try!(self.parse_dot_suffix(i, mk_sp(dot_pos, hi), e, lo));
2450 token::Literal(token::Integer(n), suf) => {
2453 // A tuple index may not have a suffix
2454 self.expect_no_suffix(sp, "tuple index", suf);
2456 let dot = self.last_span.hi;
2460 let index = n.as_str().parse::<usize>().ok();
2463 let id = spanned(dot, hi, n);
2464 let field = self.mk_tup_field(e, id);
2465 e = self.mk_expr(lo, hi, field, None);
2468 let last_span = self.last_span;
2469 self.span_err(last_span, "invalid tuple or tuple struct index");
2473 token::Literal(token::Float(n), _suf) => {
2475 let last_span = self.last_span;
2476 let fstr = n.as_str();
2477 let mut err = self.diagnostic().struct_span_err(last_span,
2478 &format!("unexpected token: `{}`", n.as_str()));
2479 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2480 let float = match fstr.parse::<f64>().ok() {
2484 err.fileline_help(last_span,
2485 &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2486 float.trunc() as usize,
2487 format!(".{}", fstr.splitn(2, ".").last().unwrap())));
2493 // FIXME Could factor this out into non_fatal_unexpected or something.
2494 let actual = self.this_token_to_string();
2495 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2497 let dot_pos = self.last_span.hi;
2498 e = try!(self.parse_dot_suffix(special_idents::invalid,
2499 mk_sp(dot_pos, dot_pos),
2505 if self.expr_is_complete(&*e) { break; }
2508 token::OpenDelim(token::Paren) => {
2509 let es = try!(self.parse_unspanned_seq(
2510 &token::OpenDelim(token::Paren),
2511 &token::CloseDelim(token::Paren),
2512 seq_sep_trailing_allowed(token::Comma),
2513 |p| Ok(try!(p.parse_expr()))
2515 hi = self.last_span.hi;
2517 let nd = self.mk_call(e, es);
2518 e = self.mk_expr(lo, hi, nd, None);
2522 // Could be either an index expression or a slicing expression.
2523 token::OpenDelim(token::Bracket) => {
2525 let ix = try!(self.parse_expr());
2527 try!(self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket)));
2528 let index = self.mk_index(e, ix);
2529 e = self.mk_expr(lo, hi, index, None)
2537 // Parse unquoted tokens after a `$` in a token tree
2538 fn parse_unquoted(&mut self) -> PResult<'a, TokenTree> {
2539 let mut sp = self.span;
2540 let (name, namep) = match self.token {
2544 if self.token == token::OpenDelim(token::Paren) {
2545 let Spanned { node: seq, span: seq_span } = try!(self.parse_seq(
2546 &token::OpenDelim(token::Paren),
2547 &token::CloseDelim(token::Paren),
2549 |p| p.parse_token_tree()
2551 let (sep, repeat) = try!(self.parse_sep_and_kleene_op());
2552 let name_num = macro_parser::count_names(&seq);
2553 return Ok(TokenTree::Sequence(mk_sp(sp.lo, seq_span.hi),
2554 Rc::new(SequenceRepetition {
2558 num_captures: name_num
2560 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2562 return Ok(TokenTree::Token(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar)));
2564 sp = mk_sp(sp.lo, self.span.hi);
2565 let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2566 let name = try!(self.parse_ident());
2570 token::SubstNt(name, namep) => {
2576 // continue by trying to parse the `:ident` after `$name`
2577 if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2578 !t.is_strict_keyword() &&
2579 !t.is_reserved_keyword()) {
2581 sp = mk_sp(sp.lo, self.span.hi);
2582 let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2583 let nt_kind = try!(self.parse_ident());
2584 Ok(TokenTree::Token(sp, MatchNt(name, nt_kind, namep, kindp)))
2586 Ok(TokenTree::Token(sp, SubstNt(name, namep)))
2590 pub fn check_unknown_macro_variable(&mut self) {
2591 if self.quote_depth == 0 {
2593 token::SubstNt(name, _) =>
2594 self.fatal(&format!("unknown macro variable `{}`", name)).emit(),
2600 /// Parse an optional separator followed by a Kleene-style
2601 /// repetition token (+ or *).
2602 pub fn parse_sep_and_kleene_op(&mut self)
2603 -> PResult<'a, (Option<token::Token>, ast::KleeneOp)> {
2604 fn parse_kleene_op<'a>(parser: &mut Parser<'a>) -> PResult<'a, Option<ast::KleeneOp>> {
2605 match parser.token {
2606 token::BinOp(token::Star) => {
2608 Ok(Some(ast::ZeroOrMore))
2610 token::BinOp(token::Plus) => {
2612 Ok(Some(ast::OneOrMore))
2618 match try!(parse_kleene_op(self)) {
2619 Some(kleene_op) => return Ok((None, kleene_op)),
2623 let separator = self.bump_and_get();
2624 match try!(parse_kleene_op(self)) {
2625 Some(zerok) => Ok((Some(separator), zerok)),
2626 None => return Err(self.fatal("expected `*` or `+`"))
2630 /// parse a single token tree from the input.
2631 pub fn parse_token_tree(&mut self) -> PResult<'a, TokenTree> {
2632 // FIXME #6994: currently, this is too eager. It
2633 // parses token trees but also identifies TokenType::Sequence's
2634 // and token::SubstNt's; it's too early to know yet
2635 // whether something will be a nonterminal or a seq
2637 maybe_whole!(deref self, NtTT);
2639 // this is the fall-through for the 'match' below.
2640 // invariants: the current token is not a left-delimiter,
2641 // not an EOF, and not the desired right-delimiter (if
2642 // it were, parse_seq_to_before_end would have prevented
2643 // reaching this point.
2644 fn parse_non_delim_tt_tok<'b>(p: &mut Parser<'b>) -> PResult<'b, TokenTree> {
2645 maybe_whole!(deref p, NtTT);
2647 token::CloseDelim(_) => {
2648 let token_str = p.this_token_to_string();
2649 let mut err = p.fatal(
2650 &format!("incorrect close delimiter: `{}`", token_str));
2651 // This is a conservative error: only report the last unclosed delimiter. The
2652 // previous unclosed delimiters could actually be closed! The parser just hasn't
2653 // gotten to them yet.
2654 if let Some(&sp) = p.open_braces.last() {
2655 err.span_note(sp, "unclosed delimiter");
2659 /* we ought to allow different depths of unquotation */
2660 token::Dollar | token::SubstNt(..) if p.quote_depth > 0 => {
2664 Ok(TokenTree::Token(p.span, p.bump_and_get()))
2671 let open_braces = self.open_braces.clone();
2672 let mut err: DiagnosticBuilder<'a> =
2673 self.fatal("this file contains an un-closed delimiter");
2674 for sp in &open_braces {
2675 err.span_help(*sp, "did you mean to close this delimiter?");
2679 token::OpenDelim(delim) => {
2680 // The span for beginning of the delimited section
2681 let pre_span = self.span;
2683 // Parse the open delimiter.
2684 self.open_braces.push(self.span);
2685 let open_span = self.span;
2688 // Parse the token trees within the delimiters
2689 let tts = try!(self.parse_seq_to_before_end(
2690 &token::CloseDelim(delim),
2692 |p| p.parse_token_tree()
2695 // Parse the close delimiter.
2696 let close_span = self.span;
2698 self.open_braces.pop().unwrap();
2700 // Expand to cover the entire delimited token tree
2701 let span = Span { hi: close_span.hi, ..pre_span };
2703 Ok(TokenTree::Delimited(span, Rc::new(Delimited {
2705 open_span: open_span,
2707 close_span: close_span,
2710 _ => parse_non_delim_tt_tok(self),
2714 // parse a stream of tokens into a list of TokenTree's,
2716 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2717 let mut tts = Vec::new();
2718 while self.token != token::Eof {
2719 tts.push(try!(self.parse_token_tree()));
2724 /// Parse a prefix-unary-operator expr
2725 pub fn parse_prefix_expr(&mut self,
2726 already_parsed_attrs: Option<ThinAttributes>)
2727 -> PResult<'a, P<Expr>> {
2728 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2729 let lo = self.span.lo;
2731 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2732 let ex = match self.token {
2735 let e = self.parse_prefix_expr(None);
2736 let (span, e) = try!(self.interpolated_or_expr_span(e));
2738 self.mk_unary(UnOp::Not, e)
2740 token::BinOp(token::Minus) => {
2742 let e = self.parse_prefix_expr(None);
2743 let (span, e) = try!(self.interpolated_or_expr_span(e));
2745 self.mk_unary(UnOp::Neg, e)
2747 token::BinOp(token::Star) => {
2749 let e = self.parse_prefix_expr(None);
2750 let (span, e) = try!(self.interpolated_or_expr_span(e));
2752 self.mk_unary(UnOp::Deref, e)
2754 token::BinOp(token::And) | token::AndAnd => {
2755 try!(self.expect_and());
2756 let m = try!(self.parse_mutability());
2757 let e = self.parse_prefix_expr(None);
2758 let (span, e) = try!(self.interpolated_or_expr_span(e));
2760 ExprKind::AddrOf(m, e)
2762 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2764 let place = try!(self.parse_expr_res(
2765 Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
2768 let blk = try!(self.parse_block());
2769 let span = blk.span;
2771 let blk_expr = self.mk_expr(span.lo, span.hi, ExprKind::Block(blk),
2773 ExprKind::InPlace(place, blk_expr)
2775 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2777 let e = self.parse_prefix_expr(None);
2778 let (span, e) = try!(self.interpolated_or_expr_span(e));
2782 _ => return self.parse_dot_or_call_expr(Some(attrs))
2784 return Ok(self.mk_expr(lo, hi, ex, attrs));
2787 /// Parse an associative expression
2789 /// This parses an expression accounting for associativity and precedence of the operators in
2791 pub fn parse_assoc_expr(&mut self,
2792 already_parsed_attrs: Option<ThinAttributes>)
2793 -> PResult<'a, P<Expr>> {
2794 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2797 /// Parse an associative expression with operators of at least `min_prec` precedence
2798 pub fn parse_assoc_expr_with(&mut self,
2801 -> PResult<'a, P<Expr>> {
2802 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2805 let attrs = match lhs {
2806 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2809 if self.token == token::DotDot {
2810 return self.parse_prefix_range_expr(attrs);
2812 try!(self.parse_prefix_expr(attrs))
2817 if self.expr_is_complete(&*lhs) {
2818 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2821 self.expected_tokens.push(TokenType::Operator);
2822 while let Some(op) = AssocOp::from_token(&self.token) {
2824 let lhs_span = if self.last_token_interpolated {
2830 let cur_op_span = self.span;
2831 let restrictions = if op.is_assign_like() {
2832 self.restrictions & Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2836 if op.precedence() < min_prec {
2840 if op.is_comparison() {
2841 self.check_no_chained_comparison(&*lhs, &op);
2844 if op == AssocOp::As {
2845 let rhs = try!(self.parse_ty());
2846 lhs = self.mk_expr(lhs_span.lo, rhs.span.hi,
2847 ExprKind::Cast(lhs, rhs), None);
2849 } else if op == AssocOp::Colon {
2850 let rhs = try!(self.parse_ty());
2851 lhs = self.mk_expr(lhs_span.lo, rhs.span.hi,
2852 ExprKind::Type(lhs, rhs), None);
2854 } else if op == AssocOp::DotDot {
2855 // If we didn’t have to handle `x..`, it would be pretty easy to generalise
2856 // it to the Fixity::None code.
2858 // We have 2 alternatives here: `x..y` and `x..` The other two variants are
2859 // handled with `parse_prefix_range_expr` call above.
2860 let rhs = if self.is_at_start_of_range_notation_rhs() {
2861 let rhs = self.parse_assoc_expr_with(op.precedence() + 1,
2862 LhsExpr::NotYetParsed);
2873 let (lhs_span, rhs_span) = (lhs_span, if let Some(ref x) = rhs {
2878 let r = self.mk_range(Some(lhs), rhs);
2879 lhs = self.mk_expr(lhs_span.lo, rhs_span.hi, r, None);
2883 let rhs = try!(match op.fixity() {
2884 Fixity::Right => self.with_res(
2885 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2887 this.parse_assoc_expr_with(op.precedence(),
2888 LhsExpr::NotYetParsed)
2890 Fixity::Left => self.with_res(
2891 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2893 this.parse_assoc_expr_with(op.precedence() + 1,
2894 LhsExpr::NotYetParsed)
2896 // We currently have no non-associative operators that are not handled above by
2897 // the special cases. The code is here only for future convenience.
2898 Fixity::None => self.with_res(
2899 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2901 this.parse_assoc_expr_with(op.precedence() + 1,
2902 LhsExpr::NotYetParsed)
2907 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2908 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2909 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2910 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2911 AssocOp::Greater | AssocOp::GreaterEqual => {
2912 let ast_op = op.to_ast_binop().unwrap();
2913 let (lhs_span, rhs_span) = (lhs_span, rhs.span);
2914 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2915 self.mk_expr(lhs_span.lo, rhs_span.hi, binary, None)
2918 self.mk_expr(lhs_span.lo, rhs.span.hi, ExprKind::Assign(lhs, rhs), None),
2920 self.mk_expr(lhs_span.lo, rhs.span.hi, ExprKind::InPlace(lhs, rhs), None),
2921 AssocOp::AssignOp(k) => {
2923 token::Plus => BinOpKind::Add,
2924 token::Minus => BinOpKind::Sub,
2925 token::Star => BinOpKind::Mul,
2926 token::Slash => BinOpKind::Div,
2927 token::Percent => BinOpKind::Rem,
2928 token::Caret => BinOpKind::BitXor,
2929 token::And => BinOpKind::BitAnd,
2930 token::Or => BinOpKind::BitOr,
2931 token::Shl => BinOpKind::Shl,
2932 token::Shr => BinOpKind::Shr,
2934 let (lhs_span, rhs_span) = (lhs_span, rhs.span);
2935 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2936 self.mk_expr(lhs_span.lo, rhs_span.hi, aopexpr, None)
2938 AssocOp::As | AssocOp::Colon | AssocOp::DotDot => {
2939 self.bug("As, Colon or DotDot branch reached")
2943 if op.fixity() == Fixity::None { break }
2948 /// Produce an error if comparison operators are chained (RFC #558).
2949 /// We only need to check lhs, not rhs, because all comparison ops
2950 /// have same precedence and are left-associative
2951 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2952 debug_assert!(outer_op.is_comparison());
2954 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
2955 // respan to include both operators
2956 let op_span = mk_sp(op.span.lo, self.span.hi);
2957 let mut err = self.diagnostic().struct_span_err(op_span,
2958 "chained comparison operators require parentheses");
2959 if op.node == BinOpKind::Lt && *outer_op == AssocOp::Greater {
2960 err.fileline_help(op_span,
2961 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2969 /// Parse prefix-forms of range notation: `..expr` and `..`
2970 fn parse_prefix_range_expr(&mut self,
2971 already_parsed_attrs: Option<ThinAttributes>)
2972 -> PResult<'a, P<Expr>> {
2973 debug_assert!(self.token == token::DotDot);
2974 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2975 let lo = self.span.lo;
2976 let mut hi = self.span.hi;
2978 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2979 // RHS must be parsed with more associativity than DotDot.
2980 let next_prec = AssocOp::from_token(&token::DotDot).unwrap().precedence() + 1;
2981 Some(try!(self.parse_assoc_expr_with(next_prec,
2982 LhsExpr::NotYetParsed)
2990 let r = self.mk_range(None, opt_end);
2991 Ok(self.mk_expr(lo, hi, r, attrs))
2994 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2995 if self.token.can_begin_expr() {
2996 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2997 if self.token == token::OpenDelim(token::Brace) {
2998 return !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL);
3006 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3007 pub fn parse_if_expr(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3008 if self.check_keyword(keywords::Let) {
3009 return self.parse_if_let_expr(attrs);
3011 let lo = self.last_span.lo;
3012 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3013 let thn = try!(self.parse_block());
3014 let mut els: Option<P<Expr>> = None;
3015 let mut hi = thn.span.hi;
3016 if self.eat_keyword(keywords::Else) {
3017 let elexpr = try!(self.parse_else_expr());
3018 hi = elexpr.span.hi;
3021 Ok(self.mk_expr(lo, hi, ExprKind::If(cond, thn, els), attrs))
3024 /// Parse an 'if let' expression ('if' token already eaten)
3025 pub fn parse_if_let_expr(&mut self, attrs: ThinAttributes)
3026 -> PResult<'a, P<Expr>> {
3027 let lo = self.last_span.lo;
3028 try!(self.expect_keyword(keywords::Let));
3029 let pat = try!(self.parse_pat());
3030 try!(self.expect(&token::Eq));
3031 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3032 let thn = try!(self.parse_block());
3033 let (hi, els) = if self.eat_keyword(keywords::Else) {
3034 let expr = try!(self.parse_else_expr());
3035 (expr.span.hi, Some(expr))
3039 Ok(self.mk_expr(lo, hi, ExprKind::IfLet(pat, expr, thn, els), attrs))
3043 pub fn parse_lambda_expr(&mut self, lo: BytePos,
3044 capture_clause: CaptureBy,
3045 attrs: ThinAttributes)
3046 -> PResult<'a, P<Expr>>
3048 let decl = try!(self.parse_fn_block_decl());
3049 let body = match decl.output {
3050 FunctionRetTy::Default(_) => {
3051 // If no explicit return type is given, parse any
3052 // expr and wrap it up in a dummy block:
3053 let body_expr = try!(self.parse_expr());
3055 id: ast::DUMMY_NODE_ID,
3057 span: body_expr.span,
3058 expr: Some(body_expr),
3059 rules: BlockCheckMode::Default,
3063 // If an explicit return type is given, require a
3064 // block to appear (RFC 968).
3065 try!(self.parse_block())
3072 ExprKind::Closure(capture_clause, decl, body), attrs))
3075 // `else` token already eaten
3076 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3077 if self.eat_keyword(keywords::If) {
3078 return self.parse_if_expr(None);
3080 let blk = try!(self.parse_block());
3081 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprKind::Block(blk), None));
3085 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3086 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>,
3088 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3089 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3091 let pat = try!(self.parse_pat());
3092 try!(self.expect_keyword(keywords::In));
3093 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3094 let (iattrs, loop_block) = try!(self.parse_inner_attrs_and_block());
3095 let attrs = attrs.append(iattrs.into_thin_attrs());
3097 let hi = self.last_span.hi;
3099 Ok(self.mk_expr(span_lo, hi,
3100 ExprKind::ForLoop(pat, expr, loop_block, opt_ident),
3104 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3105 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>,
3107 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3108 if self.token.is_keyword(keywords::Let) {
3109 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3111 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3112 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3113 let attrs = attrs.append(iattrs.into_thin_attrs());
3114 let hi = body.span.hi;
3115 return Ok(self.mk_expr(span_lo, hi, ExprKind::While(cond, body, opt_ident),
3119 /// Parse a 'while let' expression ('while' token already eaten)
3120 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>,
3122 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3123 try!(self.expect_keyword(keywords::Let));
3124 let pat = try!(self.parse_pat());
3125 try!(self.expect(&token::Eq));
3126 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3127 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3128 let attrs = attrs.append(iattrs.into_thin_attrs());
3129 let hi = body.span.hi;
3130 return Ok(self.mk_expr(span_lo, hi, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3133 // parse `loop {...}`, `loop` token already eaten
3134 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>,
3136 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3137 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3138 let attrs = attrs.append(iattrs.into_thin_attrs());
3139 let hi = body.span.hi;
3140 Ok(self.mk_expr(span_lo, hi, ExprKind::Loop(body, opt_ident), attrs))
3143 // `match` token already eaten
3144 fn parse_match_expr(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3145 let match_span = self.last_span;
3146 let lo = self.last_span.lo;
3147 let discriminant = try!(self.parse_expr_res(
3148 Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3149 if let Err(mut e) = self.commit_expr_expecting(&*discriminant,
3150 token::OpenDelim(token::Brace)) {
3151 if self.token == token::Token::Semi {
3152 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3156 let attrs = attrs.append(
3157 try!(self.parse_inner_attributes()).into_thin_attrs());
3158 let mut arms: Vec<Arm> = Vec::new();
3159 while self.token != token::CloseDelim(token::Brace) {
3160 arms.push(try!(self.parse_arm()));
3162 let hi = self.span.hi;
3164 return Ok(self.mk_expr(lo, hi, ExprKind::Match(discriminant, arms), attrs));
3167 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3168 maybe_whole!(no_clone self, NtArm);
3170 let attrs = try!(self.parse_outer_attributes());
3171 let pats = try!(self.parse_pats());
3172 let mut guard = None;
3173 if self.eat_keyword(keywords::If) {
3174 guard = Some(try!(self.parse_expr()));
3176 try!(self.expect(&token::FatArrow));
3177 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR, None));
3180 !classify::expr_is_simple_block(&*expr)
3181 && self.token != token::CloseDelim(token::Brace);
3184 try!(self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]));
3186 self.eat(&token::Comma);
3197 /// Parse an expression
3198 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3199 self.parse_expr_res(Restrictions::empty(), None)
3202 /// Evaluate the closure with restrictions in place.
3204 /// After the closure is evaluated, restrictions are reset.
3205 pub fn with_res<F>(&mut self, r: Restrictions, f: F) -> PResult<'a, P<Expr>>
3206 where F: FnOnce(&mut Self) -> PResult<'a, P<Expr>>
3208 let old = self.restrictions;
3209 self.restrictions = r;
3211 self.restrictions = old;
3216 /// Parse an expression, subject to the given restrictions
3217 pub fn parse_expr_res(&mut self, r: Restrictions,
3218 already_parsed_attrs: Option<ThinAttributes>)
3219 -> PResult<'a, P<Expr>> {
3220 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3223 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3224 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3225 if self.check(&token::Eq) {
3227 Ok(Some(try!(self.parse_expr())))
3233 /// Parse patterns, separated by '|' s
3234 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3235 let mut pats = Vec::new();
3237 pats.push(try!(self.parse_pat()));
3238 if self.check(&token::BinOp(token::Or)) { self.bump();}
3239 else { return Ok(pats); }
3243 fn parse_pat_tuple_elements(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3244 let mut fields = vec![];
3245 if !self.check(&token::CloseDelim(token::Paren)) {
3246 fields.push(try!(self.parse_pat()));
3247 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3248 while self.eat(&token::Comma) &&
3249 !self.check(&token::CloseDelim(token::Paren)) {
3250 fields.push(try!(self.parse_pat()));
3253 if fields.len() == 1 {
3254 try!(self.expect(&token::Comma));
3260 fn parse_pat_vec_elements(
3262 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3263 let mut before = Vec::new();
3264 let mut slice = None;
3265 let mut after = Vec::new();
3266 let mut first = true;
3267 let mut before_slice = true;
3269 while self.token != token::CloseDelim(token::Bracket) {
3273 try!(self.expect(&token::Comma));
3275 if self.token == token::CloseDelim(token::Bracket)
3276 && (before_slice || !after.is_empty()) {
3282 if self.check(&token::DotDot) {
3285 if self.check(&token::Comma) ||
3286 self.check(&token::CloseDelim(token::Bracket)) {
3287 slice = Some(P(ast::Pat {
3288 id: ast::DUMMY_NODE_ID,
3292 before_slice = false;
3298 let subpat = try!(self.parse_pat());
3299 if before_slice && self.check(&token::DotDot) {
3301 slice = Some(subpat);
3302 before_slice = false;
3303 } else if before_slice {
3304 before.push(subpat);
3310 Ok((before, slice, after))
3313 /// Parse the fields of a struct-like pattern
3314 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>> , bool)> {
3315 let mut fields = Vec::new();
3316 let mut etc = false;
3317 let mut first = true;
3318 while self.token != token::CloseDelim(token::Brace) {
3322 try!(self.expect(&token::Comma));
3323 // accept trailing commas
3324 if self.check(&token::CloseDelim(token::Brace)) { break }
3327 let lo = self.span.lo;
3330 if self.check(&token::DotDot) {
3332 if self.token != token::CloseDelim(token::Brace) {
3333 let token_str = self.this_token_to_string();
3334 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3341 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3342 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3343 // Parsing a pattern of the form "fieldname: pat"
3344 let fieldname = try!(self.parse_ident());
3346 let pat = try!(self.parse_pat());
3348 (pat, fieldname, false)
3350 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3351 let is_box = self.eat_keyword(keywords::Box);
3352 let boxed_span_lo = self.span.lo;
3353 let is_ref = self.eat_keyword(keywords::Ref);
3354 let is_mut = self.eat_keyword(keywords::Mut);
3355 let fieldname = try!(self.parse_ident());
3356 hi = self.last_span.hi;
3358 let bind_type = match (is_ref, is_mut) {
3359 (true, true) => BindingMode::ByRef(MutMutable),
3360 (true, false) => BindingMode::ByRef(MutImmutable),
3361 (false, true) => BindingMode::ByValue(MutMutable),
3362 (false, false) => BindingMode::ByValue(MutImmutable),
3364 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3365 let fieldpat = P(ast::Pat{
3366 id: ast::DUMMY_NODE_ID,
3367 node: PatIdent(bind_type, fieldpath, None),
3368 span: mk_sp(boxed_span_lo, hi),
3371 let subpat = if is_box {
3373 id: ast::DUMMY_NODE_ID,
3374 node: PatBox(fieldpat),
3375 span: mk_sp(lo, hi),
3380 (subpat, fieldname, true)
3383 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3384 node: ast::FieldPat { ident: fieldname,
3386 is_shorthand: is_shorthand }});
3388 return Ok((fields, etc));
3391 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3392 if self.is_path_start() {
3393 let lo = self.span.lo;
3394 let (qself, path) = if self.eat_lt() {
3395 // Parse a qualified path
3397 try!(self.parse_qualified_path(NoTypesAllowed));
3400 // Parse an unqualified path
3401 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3403 let hi = self.last_span.hi;
3404 Ok(self.mk_expr(lo, hi, ExprKind::Path(qself, path), None))
3406 self.parse_pat_literal_maybe_minus()
3410 fn is_path_start(&self) -> bool {
3411 (self.token == token::Lt || self.token == token::ModSep
3412 || self.token.is_ident() || self.token.is_path())
3413 && !self.token.is_keyword(keywords::True) && !self.token.is_keyword(keywords::False)
3416 /// Parse a pattern.
3417 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3418 maybe_whole!(self, NtPat);
3420 let lo = self.span.lo;
3423 token::Underscore => {
3428 token::BinOp(token::And) | token::AndAnd => {
3429 // Parse &pat / &mut pat
3430 try!(self.expect_and());
3431 let mutbl = try!(self.parse_mutability());
3432 if let token::Lifetime(ident) = self.token {
3433 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3436 let subpat = try!(self.parse_pat());
3437 pat = PatRegion(subpat, mutbl);
3439 token::OpenDelim(token::Paren) => {
3440 // Parse (pat,pat,pat,...) as tuple pattern
3442 let fields = try!(self.parse_pat_tuple_elements());
3443 try!(self.expect(&token::CloseDelim(token::Paren)));
3444 pat = PatTup(fields);
3446 token::OpenDelim(token::Bracket) => {
3447 // Parse [pat,pat,...] as slice pattern
3449 let (before, slice, after) = try!(self.parse_pat_vec_elements());
3450 try!(self.expect(&token::CloseDelim(token::Bracket)));
3451 pat = PatVec(before, slice, after);
3454 // At this point, token != _, &, &&, (, [
3455 if self.eat_keyword(keywords::Mut) {
3456 // Parse mut ident @ pat
3457 pat = try!(self.parse_pat_ident(BindingMode::ByValue(MutMutable)));
3458 } else if self.eat_keyword(keywords::Ref) {
3459 // Parse ref ident @ pat / ref mut ident @ pat
3460 let mutbl = try!(self.parse_mutability());
3461 pat = try!(self.parse_pat_ident(BindingMode::ByRef(mutbl)));
3462 } else if self.eat_keyword(keywords::Box) {
3464 let subpat = try!(self.parse_pat());
3465 pat = PatBox(subpat);
3466 } else if self.is_path_start() {
3467 // Parse pattern starting with a path
3468 if self.token.is_plain_ident() && self.look_ahead(1, |t| *t != token::DotDotDot &&
3469 *t != token::OpenDelim(token::Brace) &&
3470 *t != token::OpenDelim(token::Paren) &&
3471 // Contrary to its definition, a plain ident can be followed by :: in macros
3472 *t != token::ModSep) {
3473 // Plain idents have some extra abilities here compared to general paths
3474 if self.look_ahead(1, |t| *t == token::Not) {
3475 // Parse macro invocation
3476 let ident = try!(self.parse_ident());
3477 let ident_span = self.last_span;
3478 let path = ident_to_path(ident_span, ident);
3480 let delim = try!(self.expect_open_delim());
3481 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
3482 seq_sep_none(), |p| p.parse_token_tree()));
3483 let mac = Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT };
3484 pat = PatMac(codemap::Spanned {node: mac,
3485 span: mk_sp(lo, self.last_span.hi)});
3487 // Parse ident @ pat
3488 // This can give false positives and parse nullary enums,
3489 // they are dealt with later in resolve
3490 pat = try!(self.parse_pat_ident(BindingMode::ByValue(MutImmutable)));
3493 let (qself, path) = if self.eat_lt() {
3494 // Parse a qualified path
3496 try!(self.parse_qualified_path(NoTypesAllowed));
3499 // Parse an unqualified path
3500 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3503 token::DotDotDot => {
3505 let hi = self.last_span.hi;
3506 let begin = self.mk_expr(lo, hi, ExprKind::Path(qself, path), None);
3508 let end = try!(self.parse_pat_range_end());
3509 pat = PatRange(begin, end);
3511 token::OpenDelim(token::Brace) => {
3512 if qself.is_some() {
3513 return Err(self.fatal("unexpected `{` after qualified path"));
3515 // Parse struct pattern
3517 let (fields, etc) = try!(self.parse_pat_fields());
3519 pat = PatStruct(path, fields, etc);
3521 token::OpenDelim(token::Paren) => {
3522 if qself.is_some() {
3523 return Err(self.fatal("unexpected `(` after qualified path"));
3525 // Parse tuple struct or enum pattern
3526 if self.look_ahead(1, |t| *t == token::DotDot) {
3527 // This is a "top constructor only" pat
3530 try!(self.expect(&token::CloseDelim(token::Paren)));
3531 pat = PatEnum(path, None);
3533 let args = try!(self.parse_enum_variant_seq(
3534 &token::OpenDelim(token::Paren),
3535 &token::CloseDelim(token::Paren),
3536 seq_sep_trailing_allowed(token::Comma),
3537 |p| p.parse_pat()));
3538 pat = PatEnum(path, Some(args));
3543 // Parse qualified path
3544 Some(qself) => PatQPath(qself, path),
3545 // Parse nullary enum
3546 None => PatEnum(path, Some(vec![]))
3552 // Try to parse everything else as literal with optional minus
3553 let begin = try!(self.parse_pat_literal_maybe_minus());
3554 if self.eat(&token::DotDotDot) {
3555 let end = try!(self.parse_pat_range_end());
3556 pat = PatRange(begin, end);
3558 pat = PatLit(begin);
3564 let hi = self.last_span.hi;
3566 id: ast::DUMMY_NODE_ID,
3568 span: mk_sp(lo, hi),
3572 /// Parse ident or ident @ pat
3573 /// used by the copy foo and ref foo patterns to give a good
3574 /// error message when parsing mistakes like ref foo(a,b)
3575 fn parse_pat_ident(&mut self,
3576 binding_mode: ast::BindingMode)
3577 -> PResult<'a, ast::Pat_> {
3578 if !self.token.is_plain_ident() {
3579 let span = self.span;
3580 let tok_str = self.this_token_to_string();
3581 return Err(self.span_fatal(span,
3582 &format!("expected identifier, found `{}`", tok_str)))
3584 let ident = try!(self.parse_ident());
3585 let last_span = self.last_span;
3586 let name = codemap::Spanned{span: last_span, node: ident};
3587 let sub = if self.eat(&token::At) {
3588 Some(try!(self.parse_pat()))
3593 // just to be friendly, if they write something like
3595 // we end up here with ( as the current token. This shortly
3596 // leads to a parse error. Note that if there is no explicit
3597 // binding mode then we do not end up here, because the lookahead
3598 // will direct us over to parse_enum_variant()
3599 if self.token == token::OpenDelim(token::Paren) {
3600 let last_span = self.last_span;
3601 return Err(self.span_fatal(
3603 "expected identifier, found enum pattern"))
3606 Ok(PatIdent(binding_mode, name, sub))
3609 /// Parse a local variable declaration
3610 fn parse_local(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Local>> {
3611 let lo = self.span.lo;
3612 let pat = try!(self.parse_pat());
3615 if self.eat(&token::Colon) {
3616 ty = Some(try!(self.parse_ty_sum()));
3618 let init = try!(self.parse_initializer());
3623 id: ast::DUMMY_NODE_ID,
3624 span: mk_sp(lo, self.last_span.hi),
3629 /// Parse a "let" stmt
3630 fn parse_let(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Decl>> {
3631 let lo = self.span.lo;
3632 let local = try!(self.parse_local(attrs));
3633 Ok(P(spanned(lo, self.last_span.hi, DeclKind::Local(local))))
3636 /// Parse a structure field
3637 fn parse_name_and_ty(&mut self, pr: Visibility,
3638 attrs: Vec<Attribute> ) -> PResult<'a, StructField> {
3640 Inherited => self.span.lo,
3641 Public => self.last_span.lo,
3643 if !self.token.is_plain_ident() {
3644 return Err(self.fatal("expected ident"));
3646 let name = try!(self.parse_ident());
3647 try!(self.expect(&token::Colon));
3648 let ty = try!(self.parse_ty_sum());
3649 Ok(spanned(lo, self.last_span.hi, ast::StructField_ {
3650 kind: NamedField(name, pr),
3651 id: ast::DUMMY_NODE_ID,
3657 /// Emit an expected item after attributes error.
3658 fn expected_item_err(&self, attrs: &[Attribute]) {
3659 let message = match attrs.last() {
3660 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3661 "expected item after doc comment"
3663 _ => "expected item after attributes",
3666 self.span_err(self.last_span, message);
3669 /// Parse a statement. may include decl.
3670 pub fn parse_stmt(&mut self) -> PResult<'a, Option<P<Stmt>>> {
3671 Ok(try!(self.parse_stmt_()).map(P))
3674 fn parse_stmt_(&mut self) -> PResult<'a, Option<Stmt>> {
3675 maybe_whole!(Some deref self, NtStmt);
3677 let attrs = try!(self.parse_outer_attributes());
3678 let lo = self.span.lo;
3680 Ok(Some(if self.check_keyword(keywords::Let) {
3681 try!(self.expect_keyword(keywords::Let));
3682 let decl = try!(self.parse_let(attrs.into_thin_attrs()));
3683 let hi = decl.span.hi;
3684 let stmt = StmtDecl(decl, ast::DUMMY_NODE_ID);
3685 spanned(lo, hi, stmt)
3686 } else if self.token.is_ident()
3687 && !self.token.is_any_keyword()
3688 && self.look_ahead(1, |t| *t == token::Not) {
3689 // it's a macro invocation:
3691 // Potential trouble: if we allow macros with paths instead of
3692 // idents, we'd need to look ahead past the whole path here...
3693 let pth = try!(self.parse_path(NoTypesAllowed));
3696 let id = match self.token {
3697 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3698 _ => try!(self.parse_ident()),
3701 // check that we're pointing at delimiters (need to check
3702 // again after the `if`, because of `parse_ident`
3703 // consuming more tokens).
3704 let delim = match self.token {
3705 token::OpenDelim(delim) => delim,
3707 // we only expect an ident if we didn't parse one
3709 let ident_str = if id.name == token::special_idents::invalid.name {
3714 let tok_str = self.this_token_to_string();
3715 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3721 let tts = try!(self.parse_unspanned_seq(
3722 &token::OpenDelim(delim),
3723 &token::CloseDelim(delim),
3725 |p| p.parse_token_tree()
3727 let hi = self.last_span.hi;
3729 let style = if delim == token::Brace {
3732 MacStmtWithoutBraces
3735 if id.name == token::special_idents::invalid.name {
3736 let stmt = StmtMac(P(spanned(lo,
3738 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3740 attrs.into_thin_attrs());
3741 spanned(lo, hi, stmt)
3743 // if it has a special ident, it's definitely an item
3745 // Require a semicolon or braces.
3746 if style != MacStmtWithBraces {
3747 if !self.eat(&token::Semi) {
3748 let last_span = self.last_span;
3749 self.span_err(last_span,
3750 "macros that expand to items must \
3751 either be surrounded with braces or \
3752 followed by a semicolon");
3755 spanned(lo, hi, StmtDecl(
3756 P(spanned(lo, hi, DeclKind::Item(
3758 lo, hi, id /*id is good here*/,
3759 ItemMac(spanned(lo, hi,
3760 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3761 Inherited, attrs)))),
3762 ast::DUMMY_NODE_ID))
3765 // FIXME: Bad copy of attrs
3766 match try!(self.parse_item_(attrs.clone(), false, true)) {
3769 let decl = P(spanned(lo, hi, DeclKind::Item(i)));
3770 spanned(lo, hi, StmtDecl(decl, ast::DUMMY_NODE_ID))
3773 let unused_attrs = |attrs: &[_], s: &mut Self| {
3774 if attrs.len() > 0 {
3776 "expected statement after outer attribute");
3780 // Do not attempt to parse an expression if we're done here.
3781 if self.token == token::Semi {
3782 unused_attrs(&attrs, self);
3787 if self.token == token::CloseDelim(token::Brace) {
3788 unused_attrs(&attrs, self);
3792 // Remainder are line-expr stmts.
3793 let e = try!(self.parse_expr_res(
3794 Restrictions::RESTRICTION_STMT_EXPR, Some(attrs.into_thin_attrs())));
3796 let stmt = StmtExpr(e, ast::DUMMY_NODE_ID);
3797 spanned(lo, hi, stmt)
3803 /// Is this expression a successfully-parsed statement?
3804 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3805 self.restrictions.contains(Restrictions::RESTRICTION_STMT_EXPR) &&
3806 !classify::expr_requires_semi_to_be_stmt(e)
3809 /// Parse a block. No inner attrs are allowed.
3810 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
3811 maybe_whole!(no_clone self, NtBlock);
3813 let lo = self.span.lo;
3815 if !self.eat(&token::OpenDelim(token::Brace)) {
3817 let tok = self.this_token_to_string();
3818 return Err(self.span_fatal_help(sp,
3819 &format!("expected `{{`, found `{}`", tok),
3820 "place this code inside a block"));
3823 self.parse_block_tail(lo, BlockCheckMode::Default)
3826 /// Parse a block. Inner attrs are allowed.
3827 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
3828 maybe_whole!(pair_empty self, NtBlock);
3830 let lo = self.span.lo;
3831 try!(self.expect(&token::OpenDelim(token::Brace)));
3832 Ok((try!(self.parse_inner_attributes()),
3833 try!(self.parse_block_tail(lo, BlockCheckMode::Default))))
3836 /// Parse the rest of a block expression or function body
3837 /// Precondition: already parsed the '{'.
3838 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> PResult<'a, P<Block>> {
3839 let mut stmts = vec![];
3840 let mut expr = None;
3842 while !self.eat(&token::CloseDelim(token::Brace)) {
3843 let Spanned {node, span} = if let Some(s) = try!(self.parse_stmt_()) {
3846 // Found only `;` or `}`.
3851 try!(self.handle_expression_like_statement(e, span, &mut stmts, &mut expr));
3853 StmtMac(mac, MacStmtWithoutBraces, attrs) => {
3854 // statement macro without braces; might be an
3855 // expr depending on whether a semicolon follows
3858 stmts.push(P(Spanned {
3859 node: StmtMac(mac, MacStmtWithSemicolon, attrs),
3860 span: mk_sp(span.lo, self.span.hi),
3865 let e = self.mk_mac_expr(span.lo, span.hi,
3866 mac.and_then(|m| m.node),
3869 let e = try!(self.parse_dot_or_call_expr_with(e, lo, attrs));
3870 let e = try!(self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e)));
3871 try!(self.handle_expression_like_statement(
3879 StmtMac(m, style, attrs) => {
3880 // statement macro; might be an expr
3883 stmts.push(P(Spanned {
3884 node: StmtMac(m, MacStmtWithSemicolon, attrs),
3885 span: mk_sp(span.lo, self.span.hi),
3889 token::CloseDelim(token::Brace) => {
3890 // if a block ends in `m!(arg)` without
3891 // a `;`, it must be an expr
3892 expr = Some(self.mk_mac_expr(span.lo, span.hi,
3893 m.and_then(|x| x.node),
3897 stmts.push(P(Spanned {
3898 node: StmtMac(m, style, attrs),
3904 _ => { // all other kinds of statements:
3905 let mut hi = span.hi;
3906 if classify::stmt_ends_with_semi(&node) {
3907 try!(self.commit_stmt_expecting(token::Semi));
3908 hi = self.last_span.hi;
3911 stmts.push(P(Spanned {
3913 span: mk_sp(span.lo, hi)
3922 id: ast::DUMMY_NODE_ID,
3924 span: mk_sp(lo, self.last_span.hi),
3928 fn handle_expression_like_statement(
3932 stmts: &mut Vec<P<Stmt>>,
3933 last_block_expr: &mut Option<P<Expr>>) -> PResult<'a, ()> {
3934 // expression without semicolon
3935 if classify::expr_requires_semi_to_be_stmt(&*e) {
3936 // Just check for errors and recover; do not eat semicolon yet.
3937 try!(self.commit_stmt(&[],
3938 &[token::Semi, token::CloseDelim(token::Brace)]));
3944 let span_with_semi = Span {
3946 hi: self.last_span.hi,
3947 expn_id: span.expn_id,
3949 stmts.push(P(Spanned {
3950 node: StmtSemi(e, ast::DUMMY_NODE_ID),
3951 span: span_with_semi,
3954 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3956 stmts.push(P(Spanned {
3957 node: StmtExpr(e, ast::DUMMY_NODE_ID),
3965 // Parses a sequence of bounds if a `:` is found,
3966 // otherwise returns empty list.
3967 fn parse_colon_then_ty_param_bounds(&mut self,
3968 mode: BoundParsingMode)
3969 -> PResult<'a, TyParamBounds>
3971 if !self.eat(&token::Colon) {
3974 self.parse_ty_param_bounds(mode)
3978 // matches bounds = ( boundseq )?
3979 // where boundseq = ( polybound + boundseq ) | polybound
3980 // and polybound = ( 'for' '<' 'region '>' )? bound
3981 // and bound = 'region | trait_ref
3982 fn parse_ty_param_bounds(&mut self,
3983 mode: BoundParsingMode)
3984 -> PResult<'a, TyParamBounds>
3986 let mut result = vec!();
3988 let question_span = self.span;
3989 let ate_question = self.eat(&token::Question);
3991 token::Lifetime(lifetime) => {
3993 self.span_err(question_span,
3994 "`?` may only modify trait bounds, not lifetime bounds");
3996 result.push(RegionTyParamBound(ast::Lifetime {
3997 id: ast::DUMMY_NODE_ID,
4003 token::ModSep | token::Ident(..) => {
4004 let poly_trait_ref = try!(self.parse_poly_trait_ref());
4005 let modifier = if ate_question {
4006 if mode == BoundParsingMode::Modified {
4007 TraitBoundModifier::Maybe
4009 self.span_err(question_span,
4011 TraitBoundModifier::None
4014 TraitBoundModifier::None
4016 result.push(TraitTyParamBound(poly_trait_ref, modifier))
4021 if !self.eat(&token::BinOp(token::Plus)) {
4026 return Ok(P::from_vec(result));
4029 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4030 fn parse_ty_param(&mut self) -> PResult<'a, TyParam> {
4031 let span = self.span;
4032 let ident = try!(self.parse_ident());
4034 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified));
4036 let default = if self.check(&token::Eq) {
4038 Some(try!(self.parse_ty_sum()))
4045 id: ast::DUMMY_NODE_ID,
4052 /// Parse a set of optional generic type parameter declarations. Where
4053 /// clauses are not parsed here, and must be added later via
4054 /// `parse_where_clause()`.
4056 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4057 /// | ( < lifetimes , typaramseq ( , )? > )
4058 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4059 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4060 maybe_whole!(self, NtGenerics);
4062 if self.eat(&token::Lt) {
4063 let lifetime_defs = try!(self.parse_lifetime_defs());
4064 let mut seen_default = false;
4065 let ty_params = try!(self.parse_seq_to_gt(Some(token::Comma), |p| {
4066 try!(p.forbid_lifetime());
4067 let ty_param = try!(p.parse_ty_param());
4068 if ty_param.default.is_some() {
4069 seen_default = true;
4070 } else if seen_default {
4071 let last_span = p.last_span;
4072 p.span_err(last_span,
4073 "type parameters with a default must be trailing");
4078 lifetimes: lifetime_defs,
4079 ty_params: ty_params,
4080 where_clause: WhereClause {
4081 id: ast::DUMMY_NODE_ID,
4082 predicates: Vec::new(),
4086 Ok(ast::Generics::default())
4090 fn parse_generic_values_after_lt(&mut self) -> PResult<'a, (Vec<ast::Lifetime>,
4092 Vec<P<TypeBinding>>)> {
4093 let span_lo = self.span.lo;
4094 let lifetimes = try!(self.parse_lifetimes(token::Comma));
4096 let missing_comma = !lifetimes.is_empty() &&
4097 !self.token.is_like_gt() &&
4099 .as_ref().map_or(true,
4100 |x| &**x != &token::Comma);
4104 let msg = format!("expected `,` or `>` after lifetime \
4106 self.this_token_to_string());
4107 let mut err = self.diagnostic().struct_span_err(self.span, &msg);
4109 let span_hi = self.span.hi;
4110 let span_hi = match self.parse_ty() {
4111 Ok(..) => self.span.hi,
4112 Err(ref mut err) => {
4118 let msg = format!("did you mean a single argument type &'a Type, \
4119 or did you mean the comma-separated arguments \
4121 err.span_note(mk_sp(span_lo, span_hi), &msg);
4125 // First parse types.
4126 let (types, returned) = try!(self.parse_seq_to_gt_or_return(
4129 try!(p.forbid_lifetime());
4130 if p.look_ahead(1, |t| t == &token::Eq) {
4133 Ok(Some(try!(p.parse_ty_sum())))
4138 // If we found the `>`, don't continue.
4140 return Ok((lifetimes, types.into_vec(), Vec::new()));
4143 // Then parse type bindings.
4144 let bindings = try!(self.parse_seq_to_gt(
4147 try!(p.forbid_lifetime());
4149 let ident = try!(p.parse_ident());
4150 let found_eq = p.eat(&token::Eq);
4153 p.span_warn(span, "whoops, no =?");
4155 let ty = try!(p.parse_ty());
4156 let hi = ty.span.hi;
4157 let span = mk_sp(lo, hi);
4158 return Ok(P(TypeBinding{id: ast::DUMMY_NODE_ID,
4165 Ok((lifetimes, types.into_vec(), bindings.into_vec()))
4168 fn forbid_lifetime(&mut self) -> PResult<'a, ()> {
4169 if self.token.is_lifetime() {
4170 let span = self.span;
4171 return Err(self.span_fatal(span, "lifetime parameters must be declared \
4172 prior to type parameters"))
4177 /// Parses an optional `where` clause and places it in `generics`.
4180 /// where T : Trait<U, V> + 'b, 'a : 'b
4182 pub fn parse_where_clause(&mut self) -> PResult<'a, ast::WhereClause> {
4183 maybe_whole!(self, NtWhereClause);
4185 let mut where_clause = WhereClause {
4186 id: ast::DUMMY_NODE_ID,
4187 predicates: Vec::new(),
4190 if !self.eat_keyword(keywords::Where) {
4191 return Ok(where_clause);
4194 let mut parsed_something = false;
4196 let lo = self.span.lo;
4198 token::OpenDelim(token::Brace) => {
4202 token::Lifetime(..) => {
4203 let bounded_lifetime =
4204 try!(self.parse_lifetime());
4206 self.eat(&token::Colon);
4209 try!(self.parse_lifetimes(token::BinOp(token::Plus)));
4211 let hi = self.last_span.hi;
4212 let span = mk_sp(lo, hi);
4214 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4215 ast::WhereRegionPredicate {
4217 lifetime: bounded_lifetime,
4222 parsed_something = true;
4226 let bound_lifetimes = if self.eat_keyword(keywords::For) {
4227 // Higher ranked constraint.
4228 try!(self.expect(&token::Lt));
4229 let lifetime_defs = try!(self.parse_lifetime_defs());
4230 try!(self.expect_gt());
4236 let bounded_ty = try!(self.parse_ty());
4238 if self.eat(&token::Colon) {
4239 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
4240 let hi = self.last_span.hi;
4241 let span = mk_sp(lo, hi);
4243 if bounds.is_empty() {
4245 "each predicate in a `where` clause must have \
4246 at least one bound in it");
4249 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4250 ast::WhereBoundPredicate {
4252 bound_lifetimes: bound_lifetimes,
4253 bounded_ty: bounded_ty,
4257 parsed_something = true;
4258 } else if self.eat(&token::Eq) {
4259 // let ty = try!(self.parse_ty());
4260 let hi = self.last_span.hi;
4261 let span = mk_sp(lo, hi);
4262 // where_clause.predicates.push(
4263 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4264 // id: ast::DUMMY_NODE_ID,
4266 // path: panic!("NYI"), //bounded_ty,
4269 // parsed_something = true;
4272 "equality constraints are not yet supported \
4273 in where clauses (#20041)");
4275 let last_span = self.last_span;
4276 self.span_err(last_span,
4277 "unexpected token in `where` clause");
4282 if !self.eat(&token::Comma) {
4287 if !parsed_something {
4288 let last_span = self.last_span;
4289 self.span_err(last_span,
4290 "a `where` clause must have at least one predicate \
4297 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4298 -> PResult<'a, (Vec<Arg> , bool)> {
4300 let mut args: Vec<Option<Arg>> =
4301 try!(self.parse_unspanned_seq(
4302 &token::OpenDelim(token::Paren),
4303 &token::CloseDelim(token::Paren),
4304 seq_sep_trailing_allowed(token::Comma),
4306 if p.token == token::DotDotDot {
4309 if p.token != token::CloseDelim(token::Paren) {
4311 return Err(p.span_fatal(span,
4312 "`...` must be last in argument list for variadic function"))
4316 return Err(p.span_fatal(span,
4317 "only foreign functions are allowed to be variadic"))
4321 Ok(Some(try!(p.parse_arg_general(named_args))))
4326 let variadic = match args.pop() {
4329 // Need to put back that last arg
4336 if variadic && args.is_empty() {
4338 "variadic function must be declared with at least one named argument");
4341 let args = args.into_iter().map(|x| x.unwrap()).collect();
4343 Ok((args, variadic))
4346 /// Parse the argument list and result type of a function declaration
4347 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4349 let (args, variadic) = try!(self.parse_fn_args(true, allow_variadic));
4350 let ret_ty = try!(self.parse_ret_ty());
4359 fn is_self_ident(&mut self) -> bool {
4361 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4366 fn expect_self_ident(&mut self) -> PResult<'a, ast::Ident> {
4368 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4373 let token_str = self.this_token_to_string();
4374 return Err(self.fatal(&format!("expected `self`, found `{}`",
4380 fn is_self_type_ident(&mut self) -> bool {
4382 token::Ident(id, token::Plain) => id.name == special_idents::type_self.name,
4387 fn expect_self_type_ident(&mut self) -> PResult<'a, ast::Ident> {
4389 token::Ident(id, token::Plain) if id.name == special_idents::type_self.name => {
4394 let token_str = self.this_token_to_string();
4395 Err(self.fatal(&format!("expected `Self`, found `{}`",
4401 /// Parse the argument list and result type of a function
4402 /// that may have a self type.
4403 fn parse_fn_decl_with_self<F>(&mut self,
4404 parse_arg_fn: F) -> PResult<'a, (ExplicitSelf, P<FnDecl>)> where
4405 F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4407 fn maybe_parse_borrowed_explicit_self<'b>(this: &mut Parser<'b>)
4408 -> PResult<'b, ast::SelfKind> {
4409 // The following things are possible to see here:
4414 // fn(&'lt mut self)
4416 // We already know that the current token is `&`.
4418 if this.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4420 Ok(SelfKind::Region(None, MutImmutable, try!(this.expect_self_ident())))
4421 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4422 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4424 let mutability = try!(this.parse_mutability());
4425 Ok(SelfKind::Region(None, mutability, try!(this.expect_self_ident())))
4426 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4427 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4429 let lifetime = try!(this.parse_lifetime());
4430 Ok(SelfKind::Region(Some(lifetime), MutImmutable, try!(this.expect_self_ident())))
4431 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4432 this.look_ahead(2, |t| t.is_mutability()) &&
4433 this.look_ahead(3, |t| t.is_keyword(keywords::SelfValue)) {
4435 let lifetime = try!(this.parse_lifetime());
4436 let mutability = try!(this.parse_mutability());
4437 Ok(SelfKind::Region(Some(lifetime), mutability, try!(this.expect_self_ident())))
4439 Ok(SelfKind::Static)
4443 try!(self.expect(&token::OpenDelim(token::Paren)));
4445 // A bit of complexity and lookahead is needed here in order to be
4446 // backwards compatible.
4447 let lo = self.span.lo;
4448 let mut self_ident_lo = self.span.lo;
4449 let mut self_ident_hi = self.span.hi;
4451 let mut mutbl_self = MutImmutable;
4452 let explicit_self = match self.token {
4453 token::BinOp(token::And) => {
4454 let eself = try!(maybe_parse_borrowed_explicit_self(self));
4455 self_ident_lo = self.last_span.lo;
4456 self_ident_hi = self.last_span.hi;
4459 token::BinOp(token::Star) => {
4460 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4461 // emitting cryptic "unexpected token" errors.
4463 let _mutability = if self.token.is_mutability() {
4464 try!(self.parse_mutability())
4468 if self.is_self_ident() {
4469 let span = self.span;
4470 self.span_err(span, "cannot pass self by raw pointer");
4473 // error case, making bogus self ident:
4474 SelfKind::Value(special_idents::self_)
4476 token::Ident(..) => {
4477 if self.is_self_ident() {
4478 let self_ident = try!(self.expect_self_ident());
4480 // Determine whether this is the fully explicit form, `self:
4482 if self.eat(&token::Colon) {
4483 SelfKind::Explicit(try!(self.parse_ty_sum()), self_ident)
4485 SelfKind::Value(self_ident)
4487 } else if self.token.is_mutability() &&
4488 self.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4489 mutbl_self = try!(self.parse_mutability());
4490 let self_ident = try!(self.expect_self_ident());
4492 // Determine whether this is the fully explicit form,
4494 if self.eat(&token::Colon) {
4495 SelfKind::Explicit(try!(self.parse_ty_sum()), self_ident)
4497 SelfKind::Value(self_ident)
4503 _ => SelfKind::Static,
4506 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4508 // shared fall-through for the three cases below. borrowing prevents simply
4509 // writing this as a closure
4510 macro_rules! parse_remaining_arguments {
4513 // If we parsed a self type, expect a comma before the argument list.
4517 let sep = seq_sep_trailing_allowed(token::Comma);
4518 let mut fn_inputs = try!(self.parse_seq_to_before_end(
4519 &token::CloseDelim(token::Paren),
4523 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4526 token::CloseDelim(token::Paren) => {
4527 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4530 let token_str = self.this_token_to_string();
4531 return Err(self.fatal(&format!("expected `,` or `)`, found `{}`",
4538 let fn_inputs = match explicit_self {
4539 SelfKind::Static => {
4540 let sep = seq_sep_trailing_allowed(token::Comma);
4541 try!(self.parse_seq_to_before_end(&token::CloseDelim(token::Paren),
4544 SelfKind::Value(id) => parse_remaining_arguments!(id),
4545 SelfKind::Region(_,_,id) => parse_remaining_arguments!(id),
4546 SelfKind::Explicit(_,id) => parse_remaining_arguments!(id),
4550 try!(self.expect(&token::CloseDelim(token::Paren)));
4552 let hi = self.span.hi;
4554 let ret_ty = try!(self.parse_ret_ty());
4556 let fn_decl = P(FnDecl {
4562 Ok((spanned(lo, hi, explicit_self), fn_decl))
4565 // parse the |arg, arg| header on a lambda
4566 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4567 let inputs_captures = {
4568 if self.eat(&token::OrOr) {
4571 try!(self.expect(&token::BinOp(token::Or)));
4572 try!(self.parse_obsolete_closure_kind());
4573 let args = try!(self.parse_seq_to_before_end(
4574 &token::BinOp(token::Or),
4575 seq_sep_trailing_allowed(token::Comma),
4576 |p| p.parse_fn_block_arg()
4582 let output = try!(self.parse_ret_ty());
4585 inputs: inputs_captures,
4591 /// Parse the name and optional generic types of a function header.
4592 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4593 let id = try!(self.parse_ident());
4594 let generics = try!(self.parse_generics());
4598 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4599 node: Item_, vis: Visibility,
4600 attrs: Vec<Attribute>) -> P<Item> {
4604 id: ast::DUMMY_NODE_ID,
4611 /// Parse an item-position function declaration.
4612 fn parse_item_fn(&mut self,
4614 constness: Constness,
4616 -> PResult<'a, ItemInfo> {
4617 let (ident, mut generics) = try!(self.parse_fn_header());
4618 let decl = try!(self.parse_fn_decl(false));
4619 generics.where_clause = try!(self.parse_where_clause());
4620 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4621 Ok((ident, ItemFn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4624 /// true if we are looking at `const ID`, false for things like `const fn` etc
4625 pub fn is_const_item(&mut self) -> bool {
4626 self.token.is_keyword(keywords::Const) &&
4627 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4628 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4631 /// parses all the "front matter" for a `fn` declaration, up to
4632 /// and including the `fn` keyword:
4636 /// - `const unsafe fn`
4639 pub fn parse_fn_front_matter(&mut self)
4640 -> PResult<'a, (ast::Constness, ast::Unsafety, abi::Abi)> {
4641 let is_const_fn = self.eat_keyword(keywords::Const);
4642 let unsafety = try!(self.parse_unsafety());
4643 let (constness, unsafety, abi) = if is_const_fn {
4644 (Constness::Const, unsafety, Abi::Rust)
4646 let abi = if self.eat_keyword(keywords::Extern) {
4647 try!(self.parse_opt_abi()).unwrap_or(Abi::C)
4651 (Constness::NotConst, unsafety, abi)
4653 try!(self.expect_keyword(keywords::Fn));
4654 Ok((constness, unsafety, abi))
4657 /// Parse an impl item.
4658 pub fn parse_impl_item(&mut self) -> PResult<'a, P<ImplItem>> {
4659 maybe_whole!(no_clone self, NtImplItem);
4661 let mut attrs = try!(self.parse_outer_attributes());
4662 let lo = self.span.lo;
4663 let vis = try!(self.parse_visibility());
4664 let (name, node) = if self.eat_keyword(keywords::Type) {
4665 let name = try!(self.parse_ident());
4666 try!(self.expect(&token::Eq));
4667 let typ = try!(self.parse_ty_sum());
4668 try!(self.expect(&token::Semi));
4669 (name, ast::ImplItemKind::Type(typ))
4670 } else if self.is_const_item() {
4671 try!(self.expect_keyword(keywords::Const));
4672 let name = try!(self.parse_ident());
4673 try!(self.expect(&token::Colon));
4674 let typ = try!(self.parse_ty_sum());
4675 try!(self.expect(&token::Eq));
4676 let expr = try!(self.parse_expr());
4677 try!(self.commit_expr_expecting(&expr, token::Semi));
4678 (name, ast::ImplItemKind::Const(typ, expr))
4680 let (name, inner_attrs, node) = try!(self.parse_impl_method(vis));
4681 attrs.extend(inner_attrs);
4686 id: ast::DUMMY_NODE_ID,
4687 span: mk_sp(lo, self.last_span.hi),
4695 fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
4698 let is_macro_rules: bool = match self.token {
4699 token::Ident(sid, _) => sid.name == intern("macro_rules"),
4703 self.diagnostic().struct_span_err(span, "can't qualify macro_rules \
4704 invocation with `pub`")
4705 .fileline_help(span, "did you mean #[macro_export]?")
4708 self.diagnostic().struct_span_err(span, "can't qualify macro \
4709 invocation with `pub`")
4710 .fileline_help(span, "try adjusting the macro to put `pub` \
4711 inside the invocation")
4719 /// Parse a method or a macro invocation in a trait impl.
4720 fn parse_impl_method(&mut self, vis: Visibility)
4721 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4722 // code copied from parse_macro_use_or_failure... abstraction!
4723 if !self.token.is_any_keyword()
4724 && self.look_ahead(1, |t| *t == token::Not)
4725 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4726 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4729 let last_span = self.last_span;
4730 self.complain_if_pub_macro(vis, last_span);
4732 let lo = self.span.lo;
4733 let pth = try!(self.parse_path(NoTypesAllowed));
4734 try!(self.expect(&token::Not));
4736 // eat a matched-delimiter token tree:
4737 let delim = try!(self.expect_open_delim());
4738 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
4740 |p| p.parse_token_tree()));
4741 let m_ = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
4742 let m: ast::Mac = codemap::Spanned { node: m_,
4744 self.last_span.hi) };
4745 if delim != token::Brace {
4746 try!(self.expect(&token::Semi))
4748 Ok((token::special_idents::invalid, vec![], ast::ImplItemKind::Macro(m)))
4750 let (constness, unsafety, abi) = try!(self.parse_fn_front_matter());
4751 let ident = try!(self.parse_ident());
4752 let mut generics = try!(self.parse_generics());
4753 let (explicit_self, decl) = try!(self.parse_fn_decl_with_self(|p| {
4756 generics.where_clause = try!(self.parse_where_clause());
4757 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4758 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4761 explicit_self: explicit_self,
4763 constness: constness,
4769 /// Parse trait Foo { ... }
4770 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4772 let ident = try!(self.parse_ident());
4773 let mut tps = try!(self.parse_generics());
4775 // Parse supertrait bounds.
4776 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare));
4778 tps.where_clause = try!(self.parse_where_clause());
4780 let meths = try!(self.parse_trait_items());
4781 Ok((ident, ItemTrait(unsafety, tps, bounds, meths), None))
4784 /// Parses items implementations variants
4785 /// impl<T> Foo { ... }
4786 /// impl<T> ToString for &'static T { ... }
4787 /// impl Send for .. {}
4788 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> PResult<'a, ItemInfo> {
4789 let impl_span = self.span;
4791 // First, parse type parameters if necessary.
4792 let mut generics = try!(self.parse_generics());
4794 // Special case: if the next identifier that follows is '(', don't
4795 // allow this to be parsed as a trait.
4796 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4798 let neg_span = self.span;
4799 let polarity = if self.eat(&token::Not) {
4800 ast::ImplPolarity::Negative
4802 ast::ImplPolarity::Positive
4806 let mut ty = try!(self.parse_ty_sum());
4808 // Parse traits, if necessary.
4809 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4810 // New-style trait. Reinterpret the type as a trait.
4812 TyPath(None, ref path) => {
4814 path: (*path).clone(),
4819 self.span_err(ty.span, "not a trait");
4825 ast::ImplPolarity::Negative => {
4826 // This is a negated type implementation
4827 // `impl !MyType {}`, which is not allowed.
4828 self.span_err(neg_span, "inherent implementation can't be negated");
4835 if opt_trait.is_some() && self.eat(&token::DotDot) {
4836 if generics.is_parameterized() {
4837 self.span_err(impl_span, "default trait implementations are not \
4838 allowed to have generics");
4841 try!(self.expect(&token::OpenDelim(token::Brace)));
4842 try!(self.expect(&token::CloseDelim(token::Brace)));
4843 Ok((ast_util::impl_pretty_name(&opt_trait, None),
4844 ItemDefaultImpl(unsafety, opt_trait.unwrap()), None))
4846 if opt_trait.is_some() {
4847 ty = try!(self.parse_ty_sum());
4849 generics.where_clause = try!(self.parse_where_clause());
4851 try!(self.expect(&token::OpenDelim(token::Brace)));
4852 let attrs = try!(self.parse_inner_attributes());
4854 let mut impl_items = vec![];
4855 while !self.eat(&token::CloseDelim(token::Brace)) {
4856 impl_items.push(try!(self.parse_impl_item()));
4859 Ok((ast_util::impl_pretty_name(&opt_trait, Some(&*ty)),
4860 ItemImpl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4865 /// Parse a::B<String,i32>
4866 fn parse_trait_ref(&mut self) -> PResult<'a, TraitRef> {
4868 path: try!(self.parse_path(LifetimeAndTypesWithoutColons)),
4869 ref_id: ast::DUMMY_NODE_ID,
4873 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<ast::LifetimeDef>> {
4874 if self.eat_keyword(keywords::For) {
4875 try!(self.expect(&token::Lt));
4876 let lifetime_defs = try!(self.parse_lifetime_defs());
4877 try!(self.expect_gt());
4884 /// Parse for<'l> a::B<String,i32>
4885 fn parse_poly_trait_ref(&mut self) -> PResult<'a, PolyTraitRef> {
4886 let lo = self.span.lo;
4887 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
4889 Ok(ast::PolyTraitRef {
4890 bound_lifetimes: lifetime_defs,
4891 trait_ref: try!(self.parse_trait_ref()),
4892 span: mk_sp(lo, self.last_span.hi),
4896 /// Parse struct Foo { ... }
4897 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
4898 let class_name = try!(self.parse_ident());
4899 let mut generics = try!(self.parse_generics());
4901 // There is a special case worth noting here, as reported in issue #17904.
4902 // If we are parsing a tuple struct it is the case that the where clause
4903 // should follow the field list. Like so:
4905 // struct Foo<T>(T) where T: Copy;
4907 // If we are parsing a normal record-style struct it is the case
4908 // that the where clause comes before the body, and after the generics.
4909 // So if we look ahead and see a brace or a where-clause we begin
4910 // parsing a record style struct.
4912 // Otherwise if we look ahead and see a paren we parse a tuple-style
4915 let vdata = if self.token.is_keyword(keywords::Where) {
4916 generics.where_clause = try!(self.parse_where_clause());
4917 if self.eat(&token::Semi) {
4918 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4919 VariantData::Unit(ast::DUMMY_NODE_ID)
4921 // If we see: `struct Foo<T> where T: Copy { ... }`
4922 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4925 // No `where` so: `struct Foo<T>;`
4926 } else if self.eat(&token::Semi) {
4927 VariantData::Unit(ast::DUMMY_NODE_ID)
4928 // Record-style struct definition
4929 } else if self.token == token::OpenDelim(token::Brace) {
4930 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4932 // Tuple-style struct definition with optional where-clause.
4933 } else if self.token == token::OpenDelim(token::Paren) {
4934 let body = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::Yes)),
4935 ast::DUMMY_NODE_ID);
4936 generics.where_clause = try!(self.parse_where_clause());
4937 try!(self.expect(&token::Semi));
4940 let token_str = self.this_token_to_string();
4941 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
4942 name, found `{}`", token_str)))
4945 Ok((class_name, ItemStruct(vdata, generics), None))
4948 pub fn parse_record_struct_body(&mut self,
4949 parse_pub: ParsePub)
4950 -> PResult<'a, Vec<StructField>> {
4951 let mut fields = Vec::new();
4952 if self.eat(&token::OpenDelim(token::Brace)) {
4953 while self.token != token::CloseDelim(token::Brace) {
4954 fields.push(try!(self.parse_struct_decl_field(parse_pub)));
4959 let token_str = self.this_token_to_string();
4960 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
4968 pub fn parse_tuple_struct_body(&mut self,
4969 parse_pub: ParsePub)
4970 -> PResult<'a, Vec<StructField>> {
4971 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4972 // Unit like structs are handled in parse_item_struct function
4973 let fields = try!(self.parse_unspanned_seq(
4974 &token::OpenDelim(token::Paren),
4975 &token::CloseDelim(token::Paren),
4976 seq_sep_trailing_allowed(token::Comma),
4978 let attrs = try!(p.parse_outer_attributes());
4980 let struct_field_ = ast::StructField_ {
4981 kind: UnnamedField (
4982 if parse_pub == ParsePub::Yes {
4983 try!(p.parse_visibility())
4988 id: ast::DUMMY_NODE_ID,
4989 ty: try!(p.parse_ty_sum()),
4992 Ok(spanned(lo, p.span.hi, struct_field_))
4998 /// Parse a structure field declaration
4999 pub fn parse_single_struct_field(&mut self,
5001 attrs: Vec<Attribute> )
5002 -> PResult<'a, StructField> {
5003 let a_var = try!(self.parse_name_and_ty(vis, attrs));
5008 token::CloseDelim(token::Brace) => {}
5010 let span = self.span;
5011 let token_str = self.this_token_to_string();
5012 return Err(self.span_fatal_help(span,
5013 &format!("expected `,`, or `}}`, found `{}`",
5015 "struct fields should be separated by commas"))
5021 /// Parse an element of a struct definition
5022 fn parse_struct_decl_field(&mut self, parse_pub: ParsePub) -> PResult<'a, StructField> {
5024 let attrs = try!(self.parse_outer_attributes());
5026 if self.eat_keyword(keywords::Pub) {
5027 if parse_pub == ParsePub::No {
5028 let span = self.last_span;
5029 self.span_err(span, "`pub` is not allowed here");
5031 return self.parse_single_struct_field(Public, attrs);
5034 return self.parse_single_struct_field(Inherited, attrs);
5037 /// Parse visibility: PUB or nothing
5038 fn parse_visibility(&mut self) -> PResult<'a, Visibility> {
5039 if self.eat_keyword(keywords::Pub) { Ok(Public) }
5040 else { Ok(Inherited) }
5043 /// Given a termination token, parse all of the items in a module
5044 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> PResult<'a, Mod> {
5045 let mut items = vec![];
5046 while let Some(item) = try!(self.parse_item()) {
5050 if !self.eat(term) {
5051 let token_str = self.this_token_to_string();
5052 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5055 let hi = if self.span == codemap::DUMMY_SP {
5062 inner: mk_sp(inner_lo, hi),
5067 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5068 let id = try!(self.parse_ident());
5069 try!(self.expect(&token::Colon));
5070 let ty = try!(self.parse_ty_sum());
5071 try!(self.expect(&token::Eq));
5072 let e = try!(self.parse_expr());
5073 try!(self.commit_expr_expecting(&*e, token::Semi));
5074 let item = match m {
5075 Some(m) => ItemStatic(ty, m, e),
5076 None => ItemConst(ty, e),
5078 Ok((id, item, None))
5081 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5082 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5083 let id_span = self.span;
5084 let id = try!(self.parse_ident());
5085 if self.check(&token::Semi) {
5087 // This mod is in an external file. Let's go get it!
5088 let (m, attrs) = try!(self.eval_src_mod(id, outer_attrs, id_span));
5089 Ok((id, m, Some(attrs)))
5091 self.push_mod_path(id, outer_attrs);
5092 try!(self.expect(&token::OpenDelim(token::Brace)));
5093 let mod_inner_lo = self.span.lo;
5094 let old_owns_directory = self.owns_directory;
5095 self.owns_directory = true;
5096 let attrs = try!(self.parse_inner_attributes());
5097 let m = try!(self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo));
5098 self.owns_directory = old_owns_directory;
5099 self.pop_mod_path();
5100 Ok((id, ItemMod(m), Some(attrs)))
5104 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5105 let default_path = self.id_to_interned_str(id);
5106 let file_path = match ::attr::first_attr_value_str_by_name(attrs, "path") {
5108 None => default_path,
5110 self.mod_path_stack.push(file_path)
5113 fn pop_mod_path(&mut self) {
5114 self.mod_path_stack.pop().unwrap();
5117 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5118 ::attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&*d))
5121 /// Returns either a path to a module, or .
5122 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath
5124 let mod_name = id.to_string();
5125 let default_path_str = format!("{}.rs", mod_name);
5126 let secondary_path_str = format!("{}/mod.rs", mod_name);
5127 let default_path = dir_path.join(&default_path_str);
5128 let secondary_path = dir_path.join(&secondary_path_str);
5129 let default_exists = codemap.file_exists(&default_path);
5130 let secondary_exists = codemap.file_exists(&secondary_path);
5132 let result = match (default_exists, secondary_exists) {
5133 (true, false) => Ok(ModulePathSuccess { path: default_path, owns_directory: false }),
5134 (false, true) => Ok(ModulePathSuccess { path: secondary_path, owns_directory: true }),
5135 (false, false) => Err(ModulePathError {
5136 err_msg: format!("file not found for module `{}`", mod_name),
5137 help_msg: format!("name the file either {} or {} inside the directory {:?}",
5140 dir_path.display()),
5142 (true, true) => Err(ModulePathError {
5143 err_msg: format!("file for module `{}` found at both {} and {}",
5146 secondary_path_str),
5147 help_msg: "delete or rename one of them to remove the ambiguity".to_owned(),
5153 path_exists: default_exists || secondary_exists,
5158 fn submod_path(&mut self,
5160 outer_attrs: &[ast::Attribute],
5161 id_sp: Span) -> PResult<'a, ModulePathSuccess> {
5162 let mut prefix = PathBuf::from(&self.sess.codemap().span_to_filename(self.span));
5164 let mut dir_path = prefix;
5165 for part in &self.mod_path_stack {
5166 dir_path.push(&**part);
5169 if let Some(p) = Parser::submod_path_from_attr(outer_attrs, &dir_path) {
5170 return Ok(ModulePathSuccess { path: p, owns_directory: true });
5173 let paths = Parser::default_submod_path(id, &dir_path, self.sess.codemap());
5175 if !self.owns_directory {
5176 let mut err = self.diagnostic().struct_span_err(id_sp,
5177 "cannot declare a new module at this location");
5178 let this_module = match self.mod_path_stack.last() {
5179 Some(name) => name.to_string(),
5180 None => self.root_module_name.as_ref().unwrap().clone(),
5182 err.span_note(id_sp,
5183 &format!("maybe move this module `{0}` to its own directory \
5186 if paths.path_exists {
5187 err.span_note(id_sp,
5188 &format!("... or maybe `use` the module `{}` instead \
5189 of possibly redeclaring it",
5195 match paths.result {
5196 Ok(succ) => Ok(succ),
5197 Err(err) => Err(self.span_fatal_help(id_sp, &err.err_msg, &err.help_msg)),
5201 /// Read a module from a source file.
5202 fn eval_src_mod(&mut self,
5204 outer_attrs: &[ast::Attribute],
5206 -> PResult<'a, (ast::Item_, Vec<ast::Attribute> )> {
5207 let ModulePathSuccess { path, owns_directory } = try!(self.submod_path(id,
5211 self.eval_src_mod_from_path(path,
5217 fn eval_src_mod_from_path(&mut self,
5219 owns_directory: bool,
5221 id_sp: Span) -> PResult<'a, (ast::Item_, Vec<ast::Attribute> )> {
5222 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5223 match included_mod_stack.iter().position(|p| *p == path) {
5225 let mut err = String::from("circular modules: ");
5226 let len = included_mod_stack.len();
5227 for p in &included_mod_stack[i.. len] {
5228 err.push_str(&p.to_string_lossy());
5229 err.push_str(" -> ");
5231 err.push_str(&path.to_string_lossy());
5232 return Err(self.span_fatal(id_sp, &err[..]));
5236 included_mod_stack.push(path.clone());
5237 drop(included_mod_stack);
5239 let mut p0 = new_sub_parser_from_file(self.sess,
5245 let mod_inner_lo = p0.span.lo;
5246 let mod_attrs = try!(p0.parse_inner_attributes());
5247 let m0 = try!(p0.parse_mod_items(&token::Eof, mod_inner_lo));
5248 self.sess.included_mod_stack.borrow_mut().pop();
5249 Ok((ast::ItemMod(m0), mod_attrs))
5252 /// Parse a function declaration from a foreign module
5253 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: BytePos,
5254 attrs: Vec<Attribute>) -> PResult<'a, P<ForeignItem>> {
5255 try!(self.expect_keyword(keywords::Fn));
5257 let (ident, mut generics) = try!(self.parse_fn_header());
5258 let decl = try!(self.parse_fn_decl(true));
5259 generics.where_clause = try!(self.parse_where_clause());
5260 let hi = self.span.hi;
5261 try!(self.expect(&token::Semi));
5262 Ok(P(ast::ForeignItem {
5265 node: ForeignItemFn(decl, generics),
5266 id: ast::DUMMY_NODE_ID,
5267 span: mk_sp(lo, hi),
5272 /// Parse a static item from a foreign module
5273 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: BytePos,
5274 attrs: Vec<Attribute>) -> PResult<'a, P<ForeignItem>> {
5275 try!(self.expect_keyword(keywords::Static));
5276 let mutbl = self.eat_keyword(keywords::Mut);
5278 let ident = try!(self.parse_ident());
5279 try!(self.expect(&token::Colon));
5280 let ty = try!(self.parse_ty_sum());
5281 let hi = self.span.hi;
5282 try!(self.expect(&token::Semi));
5286 node: ForeignItemStatic(ty, mutbl),
5287 id: ast::DUMMY_NODE_ID,
5288 span: mk_sp(lo, hi),
5293 /// Parse extern crate links
5297 /// extern crate foo;
5298 /// extern crate bar as foo;
5299 fn parse_item_extern_crate(&mut self,
5301 visibility: Visibility,
5302 attrs: Vec<Attribute>)
5303 -> PResult<'a, P<Item>> {
5305 let crate_name = try!(self.parse_ident());
5306 let (maybe_path, ident) = if let Some(ident) = try!(self.parse_rename()) {
5307 (Some(crate_name.name), ident)
5311 try!(self.expect(&token::Semi));
5313 let last_span = self.last_span;
5315 if visibility == ast::Public {
5316 self.span_warn(mk_sp(lo, last_span.hi),
5317 "`pub extern crate` does not work as expected and should not be used. \
5318 Likely to become an error. Prefer `extern crate` and `pub use`.");
5324 ItemExternCrate(maybe_path),
5329 /// Parse `extern` for foreign ABIs
5332 /// `extern` is expected to have been
5333 /// consumed before calling this method
5339 fn parse_item_foreign_mod(&mut self,
5341 opt_abi: Option<abi::Abi>,
5342 visibility: Visibility,
5343 mut attrs: Vec<Attribute>)
5344 -> PResult<'a, P<Item>> {
5345 try!(self.expect(&token::OpenDelim(token::Brace)));
5347 let abi = opt_abi.unwrap_or(Abi::C);
5349 attrs.extend(try!(self.parse_inner_attributes()));
5351 let mut foreign_items = vec![];
5352 while let Some(item) = try!(self.parse_foreign_item()) {
5353 foreign_items.push(item);
5355 try!(self.expect(&token::CloseDelim(token::Brace)));
5357 let last_span = self.last_span;
5358 let m = ast::ForeignMod {
5360 items: foreign_items
5364 special_idents::invalid,
5370 /// Parse type Foo = Bar;
5371 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5372 let ident = try!(self.parse_ident());
5373 let mut tps = try!(self.parse_generics());
5374 tps.where_clause = try!(self.parse_where_clause());
5375 try!(self.expect(&token::Eq));
5376 let ty = try!(self.parse_ty_sum());
5377 try!(self.expect(&token::Semi));
5378 Ok((ident, ItemTy(ty, tps), None))
5381 /// Parse the part of an "enum" decl following the '{'
5382 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5383 let mut variants = Vec::new();
5384 let mut all_nullary = true;
5385 let mut any_disr = None;
5386 while self.token != token::CloseDelim(token::Brace) {
5387 let variant_attrs = try!(self.parse_outer_attributes());
5388 let vlo = self.span.lo;
5391 let mut disr_expr = None;
5392 let ident = try!(self.parse_ident());
5393 if self.check(&token::OpenDelim(token::Brace)) {
5394 // Parse a struct variant.
5395 all_nullary = false;
5396 struct_def = VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::No)),
5397 ast::DUMMY_NODE_ID);
5398 } else if self.check(&token::OpenDelim(token::Paren)) {
5399 all_nullary = false;
5400 struct_def = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::No)),
5401 ast::DUMMY_NODE_ID);
5402 } else if self.eat(&token::Eq) {
5403 disr_expr = Some(try!(self.parse_expr()));
5404 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5405 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5407 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5410 let vr = ast::Variant_ {
5412 attrs: variant_attrs,
5414 disr_expr: disr_expr,
5416 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5418 if !self.eat(&token::Comma) { break; }
5420 try!(self.expect(&token::CloseDelim(token::Brace)));
5422 Some(disr_span) if !all_nullary =>
5423 self.span_err(disr_span,
5424 "discriminator values can only be used with a c-like enum"),
5428 Ok(ast::EnumDef { variants: variants })
5431 /// Parse an "enum" declaration
5432 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5433 let id = try!(self.parse_ident());
5434 let mut generics = try!(self.parse_generics());
5435 generics.where_clause = try!(self.parse_where_clause());
5436 try!(self.expect(&token::OpenDelim(token::Brace)));
5438 let enum_definition = try!(self.parse_enum_def(&generics));
5439 Ok((id, ItemEnum(enum_definition, generics), None))
5442 /// Parses a string as an ABI spec on an extern type or module. Consumes
5443 /// the `extern` keyword, if one is found.
5444 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5446 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5448 self.expect_no_suffix(sp, "ABI spec", suf);
5450 match abi::lookup(&s.as_str()) {
5451 Some(abi) => Ok(Some(abi)),
5453 let last_span = self.last_span;
5456 &format!("invalid ABI: expected one of [{}], \
5458 abi::all_names().join(", "),
5469 /// Parse one of the items allowed by the flags.
5470 /// NB: this function no longer parses the items inside an
5472 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5473 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5474 let nt_item = match self.token {
5475 token::Interpolated(token::NtItem(ref item)) => {
5476 Some((**item).clone())
5483 let mut attrs = attrs;
5484 mem::swap(&mut item.attrs, &mut attrs);
5485 item.attrs.extend(attrs);
5486 return Ok(Some(P(item)));
5491 let lo = self.span.lo;
5493 let visibility = try!(self.parse_visibility());
5495 if self.eat_keyword(keywords::Use) {
5497 let item_ = ItemUse(try!(self.parse_view_path()));
5498 try!(self.expect(&token::Semi));
5500 let last_span = self.last_span;
5501 let item = self.mk_item(lo,
5503 token::special_idents::invalid,
5507 return Ok(Some(item));
5510 if self.eat_keyword(keywords::Extern) {
5511 if self.eat_keyword(keywords::Crate) {
5512 return Ok(Some(try!(self.parse_item_extern_crate(lo, visibility, attrs))));
5515 let opt_abi = try!(self.parse_opt_abi());
5517 if self.eat_keyword(keywords::Fn) {
5518 // EXTERN FUNCTION ITEM
5519 let abi = opt_abi.unwrap_or(Abi::C);
5520 let (ident, item_, extra_attrs) =
5521 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi));
5522 let last_span = self.last_span;
5523 let item = self.mk_item(lo,
5528 maybe_append(attrs, extra_attrs));
5529 return Ok(Some(item));
5530 } else if self.check(&token::OpenDelim(token::Brace)) {
5531 return Ok(Some(try!(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs))));
5534 try!(self.unexpected());
5537 if self.eat_keyword(keywords::Static) {
5539 let m = if self.eat_keyword(keywords::Mut) {MutMutable} else {MutImmutable};
5540 let (ident, item_, extra_attrs) = try!(self.parse_item_const(Some(m)));
5541 let last_span = self.last_span;
5542 let item = self.mk_item(lo,
5547 maybe_append(attrs, extra_attrs));
5548 return Ok(Some(item));
5550 if self.eat_keyword(keywords::Const) {
5551 if self.check_keyword(keywords::Fn)
5552 || (self.check_keyword(keywords::Unsafe)
5553 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5554 // CONST FUNCTION ITEM
5555 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5561 let (ident, item_, extra_attrs) =
5562 try!(self.parse_item_fn(unsafety, Constness::Const, Abi::Rust));
5563 let last_span = self.last_span;
5564 let item = self.mk_item(lo,
5569 maybe_append(attrs, extra_attrs));
5570 return Ok(Some(item));
5574 if self.eat_keyword(keywords::Mut) {
5575 let last_span = self.last_span;
5576 self.diagnostic().struct_span_err(last_span, "const globals cannot be mutable")
5577 .fileline_help(last_span, "did you mean to declare a static?")
5580 let (ident, item_, extra_attrs) = try!(self.parse_item_const(None));
5581 let last_span = self.last_span;
5582 let item = self.mk_item(lo,
5587 maybe_append(attrs, extra_attrs));
5588 return Ok(Some(item));
5590 if self.check_keyword(keywords::Unsafe) &&
5591 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5593 // UNSAFE TRAIT ITEM
5594 try!(self.expect_keyword(keywords::Unsafe));
5595 try!(self.expect_keyword(keywords::Trait));
5596 let (ident, item_, extra_attrs) =
5597 try!(self.parse_item_trait(ast::Unsafety::Unsafe));
5598 let last_span = self.last_span;
5599 let item = self.mk_item(lo,
5604 maybe_append(attrs, extra_attrs));
5605 return Ok(Some(item));
5607 if self.check_keyword(keywords::Unsafe) &&
5608 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5611 try!(self.expect_keyword(keywords::Unsafe));
5612 try!(self.expect_keyword(keywords::Impl));
5613 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Unsafe));
5614 let last_span = self.last_span;
5615 let item = self.mk_item(lo,
5620 maybe_append(attrs, extra_attrs));
5621 return Ok(Some(item));
5623 if self.check_keyword(keywords::Fn) {
5626 let (ident, item_, extra_attrs) =
5627 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, Abi::Rust));
5628 let last_span = self.last_span;
5629 let item = self.mk_item(lo,
5634 maybe_append(attrs, extra_attrs));
5635 return Ok(Some(item));
5637 if self.check_keyword(keywords::Unsafe)
5638 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5639 // UNSAFE FUNCTION ITEM
5641 let abi = if self.eat_keyword(keywords::Extern) {
5642 try!(self.parse_opt_abi()).unwrap_or(Abi::C)
5646 try!(self.expect_keyword(keywords::Fn));
5647 let (ident, item_, extra_attrs) =
5648 try!(self.parse_item_fn(Unsafety::Unsafe, Constness::NotConst, abi));
5649 let last_span = self.last_span;
5650 let item = self.mk_item(lo,
5655 maybe_append(attrs, extra_attrs));
5656 return Ok(Some(item));
5658 if self.eat_keyword(keywords::Mod) {
5660 let (ident, item_, extra_attrs) =
5661 try!(self.parse_item_mod(&attrs[..]));
5662 let last_span = self.last_span;
5663 let item = self.mk_item(lo,
5668 maybe_append(attrs, extra_attrs));
5669 return Ok(Some(item));
5671 if self.eat_keyword(keywords::Type) {
5673 let (ident, item_, extra_attrs) = try!(self.parse_item_type());
5674 let last_span = self.last_span;
5675 let item = self.mk_item(lo,
5680 maybe_append(attrs, extra_attrs));
5681 return Ok(Some(item));
5683 if self.eat_keyword(keywords::Enum) {
5685 let (ident, item_, extra_attrs) = try!(self.parse_item_enum());
5686 let last_span = self.last_span;
5687 let item = self.mk_item(lo,
5692 maybe_append(attrs, extra_attrs));
5693 return Ok(Some(item));
5695 if self.eat_keyword(keywords::Trait) {
5697 let (ident, item_, extra_attrs) =
5698 try!(self.parse_item_trait(ast::Unsafety::Normal));
5699 let last_span = self.last_span;
5700 let item = self.mk_item(lo,
5705 maybe_append(attrs, extra_attrs));
5706 return Ok(Some(item));
5708 if self.eat_keyword(keywords::Impl) {
5710 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Normal));
5711 let last_span = self.last_span;
5712 let item = self.mk_item(lo,
5717 maybe_append(attrs, extra_attrs));
5718 return Ok(Some(item));
5720 if self.eat_keyword(keywords::Struct) {
5722 let (ident, item_, extra_attrs) = try!(self.parse_item_struct());
5723 let last_span = self.last_span;
5724 let item = self.mk_item(lo,
5729 maybe_append(attrs, extra_attrs));
5730 return Ok(Some(item));
5732 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5735 /// Parse a foreign item.
5736 fn parse_foreign_item(&mut self) -> PResult<'a, Option<P<ForeignItem>>> {
5737 let attrs = try!(self.parse_outer_attributes());
5738 let lo = self.span.lo;
5739 let visibility = try!(self.parse_visibility());
5741 if self.check_keyword(keywords::Static) {
5742 // FOREIGN STATIC ITEM
5743 return Ok(Some(try!(self.parse_item_foreign_static(visibility, lo, attrs))));
5745 if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) {
5746 // FOREIGN FUNCTION ITEM
5747 return Ok(Some(try!(self.parse_item_foreign_fn(visibility, lo, attrs))));
5750 // FIXME #5668: this will occur for a macro invocation:
5751 match try!(self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)) {
5753 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5759 /// This is the fall-through for parsing items.
5760 fn parse_macro_use_or_failure(
5762 attrs: Vec<Attribute> ,
5763 macros_allowed: bool,
5764 attributes_allowed: bool,
5766 visibility: Visibility
5767 ) -> PResult<'a, Option<P<Item>>> {
5768 if macros_allowed && !self.token.is_any_keyword()
5769 && self.look_ahead(1, |t| *t == token::Not)
5770 && (self.look_ahead(2, |t| t.is_plain_ident())
5771 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5772 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5773 // MACRO INVOCATION ITEM
5775 let last_span = self.last_span;
5776 self.complain_if_pub_macro(visibility, last_span);
5778 let mac_lo = self.span.lo;
5781 let pth = try!(self.parse_path(NoTypesAllowed));
5782 try!(self.expect(&token::Not));
5784 // a 'special' identifier (like what `macro_rules!` uses)
5785 // is optional. We should eventually unify invoc syntax
5787 let id = if self.token.is_plain_ident() {
5788 try!(self.parse_ident())
5790 token::special_idents::invalid // no special identifier
5792 // eat a matched-delimiter token tree:
5793 let delim = try!(self.expect_open_delim());
5794 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
5796 |p| p.parse_token_tree()));
5797 // single-variant-enum... :
5798 let m = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
5799 let m: ast::Mac = codemap::Spanned { node: m,
5801 self.last_span.hi) };
5803 if delim != token::Brace {
5804 if !self.eat(&token::Semi) {
5805 let last_span = self.last_span;
5806 self.span_err(last_span,
5807 "macros that expand to items must either \
5808 be surrounded with braces or followed by \
5813 let item_ = ItemMac(m);
5814 let last_span = self.last_span;
5815 let item = self.mk_item(lo,
5821 return Ok(Some(item));
5824 // FAILURE TO PARSE ITEM
5828 let last_span = self.last_span;
5829 return Err(self.span_fatal(last_span, "unmatched visibility `pub`"));
5833 if !attributes_allowed && !attrs.is_empty() {
5834 self.expected_item_err(&attrs);
5839 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
5840 let attrs = try!(self.parse_outer_attributes());
5841 self.parse_item_(attrs, true, false)
5845 /// Matches view_path : MOD? non_global_path as IDENT
5846 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5847 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5848 /// | MOD? non_global_path MOD_SEP STAR
5849 /// | MOD? non_global_path
5850 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
5851 let lo = self.span.lo;
5853 // Allow a leading :: because the paths are absolute either way.
5854 // This occurs with "use $crate::..." in macros.
5855 self.eat(&token::ModSep);
5857 if self.check(&token::OpenDelim(token::Brace)) {
5859 let idents = try!(self.parse_unspanned_seq(
5860 &token::OpenDelim(token::Brace),
5861 &token::CloseDelim(token::Brace),
5862 seq_sep_trailing_allowed(token::Comma),
5863 |p| p.parse_path_list_item()));
5864 let path = ast::Path {
5865 span: mk_sp(lo, self.span.hi),
5867 segments: Vec::new()
5869 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5872 let first_ident = try!(self.parse_ident());
5873 let mut path = vec!(first_ident);
5874 if let token::ModSep = self.token {
5875 // foo::bar or foo::{a,b,c} or foo::*
5876 while self.check(&token::ModSep) {
5880 token::Ident(..) => {
5881 let ident = try!(self.parse_ident());
5885 // foo::bar::{a,b,c}
5886 token::OpenDelim(token::Brace) => {
5887 let idents = try!(self.parse_unspanned_seq(
5888 &token::OpenDelim(token::Brace),
5889 &token::CloseDelim(token::Brace),
5890 seq_sep_trailing_allowed(token::Comma),
5891 |p| p.parse_path_list_item()
5893 let path = ast::Path {
5894 span: mk_sp(lo, self.span.hi),
5896 segments: path.into_iter().map(|identifier| {
5898 identifier: identifier,
5899 parameters: ast::PathParameters::none(),
5903 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5907 token::BinOp(token::Star) => {
5909 let path = ast::Path {
5910 span: mk_sp(lo, self.span.hi),
5912 segments: path.into_iter().map(|identifier| {
5914 identifier: identifier,
5915 parameters: ast::PathParameters::none(),
5919 return Ok(P(spanned(lo, self.span.hi, ViewPathGlob(path))));
5922 // fall-through for case foo::bar::;
5924 self.span_err(self.span, "expected identifier or `{` or `*`, found `;`");
5931 let mut rename_to = path[path.len() - 1];
5932 let path = ast::Path {
5933 span: mk_sp(lo, self.last_span.hi),
5935 segments: path.into_iter().map(|identifier| {
5937 identifier: identifier,
5938 parameters: ast::PathParameters::none(),
5942 rename_to = try!(self.parse_rename()).unwrap_or(rename_to);
5943 Ok(P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path))))
5946 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
5947 if self.eat_keyword(keywords::As) {
5948 self.parse_ident().map(Some)
5954 /// Parses a source module as a crate. This is the main
5955 /// entry point for the parser.
5956 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
5957 let lo = self.span.lo;
5959 attrs: try!(self.parse_inner_attributes()),
5960 module: try!(self.parse_mod_items(&token::Eof, lo)),
5961 config: self.cfg.clone(),
5962 span: mk_sp(lo, self.span.lo),
5963 exported_macros: Vec::new(),
5967 pub fn parse_optional_str(&mut self)
5968 -> Option<(InternedString,
5970 Option<ast::Name>)> {
5971 let ret = match self.token {
5972 token::Literal(token::Str_(s), suf) => {
5973 (self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)), ast::CookedStr, suf)
5975 token::Literal(token::StrRaw(s, n), suf) => {
5976 (self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)), ast::RawStr(n), suf)
5984 pub fn parse_str(&mut self) -> PResult<'a, (InternedString, StrStyle)> {
5985 match self.parse_optional_str() {
5986 Some((s, style, suf)) => {
5987 let sp = self.last_span;
5988 self.expect_no_suffix(sp, "string literal", suf);
5991 _ => Err(self.fatal("expected string literal"))