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};
17 use ast::{Mod, Arg, Arm, Attribute, BindingMode, TraitItemKind};
19 use ast::{BlockCheckMode, CaptureBy};
20 use ast::{Constness, 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, ForeignItemKind, FunctionRetTy};
26 use ast::{Ident, ImplItem, Item, ItemKind};
27 use ast::{Lit, LitKind, UintTy};
29 use ast::MacStmtStyle;
31 use ast::{MutTy, Mutability};
33 use ast::{Pat, PatKind};
34 use ast::{PolyTraitRef, QSelf};
35 use ast::{Stmt, StmtKind};
36 use ast::{VariantData, StructField};
39 use ast::{Delimited, SequenceRepetition, TokenTree, TraitItem, TraitRef};
40 use ast::{Ty, TyKind, TypeBinding, TyParam, TyParamBounds};
41 use ast::UnnamedField;
42 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
43 use ast::{Visibility, WhereClause};
44 use attr::{ThinAttributes, ThinAttributesExt, AttributesExt};
45 use ast::{BinOpKind, UnOp};
47 use ast_util::{self, ident_to_path};
48 use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp, CodeMap};
49 use errors::{self, DiagnosticBuilder};
50 use ext::tt::macro_parser;
53 use parse::common::{SeqSep, seq_sep_none, seq_sep_trailing_allowed};
54 use parse::lexer::{Reader, TokenAndSpan};
55 use parse::obsolete::{ParserObsoleteMethods, ObsoleteSyntax};
56 use parse::token::{self, intern, MatchNt, SubstNt, SpecialVarNt, InternedString};
57 use parse::token::{keywords, special_idents, SpecialMacroVar};
58 use parse::{new_sub_parser_from_file, ParseSess};
59 use util::parser::{AssocOp, Fixity};
64 use std::collections::HashSet;
65 use std::io::prelude::*;
67 use std::path::{Path, PathBuf};
72 flags Restrictions: u8 {
73 const RESTRICTION_STMT_EXPR = 1 << 0,
74 const RESTRICTION_NO_STRUCT_LITERAL = 1 << 1,
75 const NO_NONINLINE_MOD = 1 << 2,
79 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute> >);
81 /// How to parse a path. There are four different kinds of paths, all of which
82 /// are parsed somewhat differently.
83 #[derive(Copy, Clone, PartialEq)]
84 pub enum PathParsingMode {
85 /// A path with no type parameters; e.g. `foo::bar::Baz`
87 /// A path with a lifetime and type parameters, with no double colons
88 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`
89 LifetimeAndTypesWithoutColons,
90 /// A path with a lifetime and type parameters with double colons before
91 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`
92 LifetimeAndTypesWithColons,
95 /// How to parse a bound, whether to allow bound modifiers such as `?`.
96 #[derive(Copy, Clone, PartialEq)]
97 pub enum BoundParsingMode {
102 /// `pub` should be parsed in struct fields and not parsed in variant fields
103 #[derive(Clone, Copy, PartialEq)]
109 #[derive(Clone, Copy, PartialEq)]
110 pub enum SemiColonMode {
115 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
116 /// dropped into the token stream, which happens while parsing the result of
117 /// macro expansion). Placement of these is not as complex as I feared it would
118 /// be. The important thing is to make sure that lookahead doesn't balk at
119 /// `token::Interpolated` tokens.
120 macro_rules! maybe_whole_expr {
123 let found = match $p.token {
124 token::Interpolated(token::NtExpr(ref e)) => {
127 token::Interpolated(token::NtPath(_)) => {
128 // FIXME: The following avoids an issue with lexical borrowck scopes,
129 // but the clone is unfortunate.
130 let pt = match $p.token {
131 token::Interpolated(token::NtPath(ref pt)) => (**pt).clone(),
135 Some($p.mk_expr(span.lo, span.hi, ExprKind::Path(None, pt), None))
137 token::Interpolated(token::NtBlock(_)) => {
138 // FIXME: The following avoids an issue with lexical borrowck scopes,
139 // but the clone is unfortunate.
140 let b = match $p.token {
141 token::Interpolated(token::NtBlock(ref b)) => (*b).clone(),
145 Some($p.mk_expr(span.lo, span.hi, ExprKind::Block(b), None))
160 /// As maybe_whole_expr, but for things other than expressions
161 macro_rules! maybe_whole {
162 ($p:expr, $constructor:ident) => (
164 let found = match ($p).token {
165 token::Interpolated(token::$constructor(_)) => {
166 Some(($p).bump_and_get())
170 if let Some(token::Interpolated(token::$constructor(x))) = found {
171 return Ok(x.clone());
175 (no_clone $p:expr, $constructor:ident) => (
177 let found = match ($p).token {
178 token::Interpolated(token::$constructor(_)) => {
179 Some(($p).bump_and_get())
183 if let Some(token::Interpolated(token::$constructor(x))) = found {
188 (no_clone_from_p $p:expr, $constructor:ident) => (
190 let found = match ($p).token {
191 token::Interpolated(token::$constructor(_)) => {
192 Some(($p).bump_and_get())
196 if let Some(token::Interpolated(token::$constructor(x))) = found {
197 return Ok(x.unwrap());
201 (deref $p:expr, $constructor:ident) => (
203 let found = match ($p).token {
204 token::Interpolated(token::$constructor(_)) => {
205 Some(($p).bump_and_get())
209 if let Some(token::Interpolated(token::$constructor(x))) = found {
210 return Ok((*x).clone());
214 (Some deref $p:expr, $constructor:ident) => (
216 let found = match ($p).token {
217 token::Interpolated(token::$constructor(_)) => {
218 Some(($p).bump_and_get())
222 if let Some(token::Interpolated(token::$constructor(x))) = found {
223 return Ok(Some((*x).clone()));
227 (pair_empty $p:expr, $constructor:ident) => (
229 let found = match ($p).token {
230 token::Interpolated(token::$constructor(_)) => {
231 Some(($p).bump_and_get())
235 if let Some(token::Interpolated(token::$constructor(x))) = found {
236 return Ok((Vec::new(), x));
242 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
244 if let Some(ref attrs) = rhs {
245 lhs.extend(attrs.iter().cloned())
250 /* ident is handled by common.rs */
252 pub struct Parser<'a> {
253 pub sess: &'a ParseSess,
254 /// the current token:
255 pub token: token::Token,
256 /// the span of the current token:
258 /// the span of the prior token:
260 pub cfg: CrateConfig,
261 /// the previous token or None (only stashed sometimes).
262 pub last_token: Option<Box<token::Token>>,
263 last_token_interpolated: bool,
264 pub buffer: [TokenAndSpan; 4],
265 pub buffer_start: isize,
266 pub buffer_end: isize,
267 pub tokens_consumed: usize,
268 pub restrictions: Restrictions,
269 pub quote_depth: usize, // not (yet) related to the quasiquoter
270 pub reader: Box<Reader+'a>,
271 pub interner: Rc<token::IdentInterner>,
272 /// The set of seen errors about obsolete syntax. Used to suppress
273 /// extra detail when the same error is seen twice
274 pub obsolete_set: HashSet<ObsoleteSyntax>,
275 /// Used to determine the path to externally loaded source files
276 pub mod_path_stack: Vec<InternedString>,
277 /// Stack of spans of open delimiters. Used for error message.
278 pub open_braces: Vec<Span>,
279 /// Flag if this parser "owns" the directory that it is currently parsing
280 /// in. This will affect how nested files are looked up.
281 pub owns_directory: bool,
282 /// Name of the root module this parser originated from. If `None`, then the
283 /// name is not known. This does not change while the parser is descending
284 /// into modules, and sub-parsers have new values for this name.
285 pub root_module_name: Option<String>,
286 pub expected_tokens: Vec<TokenType>,
289 #[derive(PartialEq, Eq, Clone)]
292 Keyword(keywords::Keyword),
297 fn to_string(&self) -> String {
299 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
300 TokenType::Operator => "an operator".to_string(),
301 TokenType::Keyword(kw) => format!("`{}`", kw.to_name()),
306 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
307 t.is_plain_ident() || *t == token::Underscore
310 /// Information about the path to a module.
311 pub struct ModulePath {
313 pub path_exists: bool,
314 pub result: Result<ModulePathSuccess, ModulePathError>,
317 pub struct ModulePathSuccess {
318 pub path: ::std::path::PathBuf,
319 pub owns_directory: bool,
322 pub struct ModulePathError {
324 pub help_msg: String,
329 AttributesParsed(ThinAttributes),
330 AlreadyParsed(P<Expr>),
333 impl From<Option<ThinAttributes>> for LhsExpr {
334 fn from(o: Option<ThinAttributes>) -> Self {
335 if let Some(attrs) = o {
336 LhsExpr::AttributesParsed(attrs)
338 LhsExpr::NotYetParsed
343 impl From<P<Expr>> for LhsExpr {
344 fn from(expr: P<Expr>) -> Self {
345 LhsExpr::AlreadyParsed(expr)
349 impl<'a> Parser<'a> {
350 pub fn new(sess: &'a ParseSess,
351 cfg: ast::CrateConfig,
352 mut rdr: Box<Reader+'a>)
355 let tok0 = rdr.real_token();
357 let placeholder = TokenAndSpan {
358 tok: token::Underscore,
364 interner: token::get_ident_interner(),
371 last_token_interpolated: false,
381 restrictions: Restrictions::empty(),
383 obsolete_set: HashSet::new(),
384 mod_path_stack: Vec::new(),
385 open_braces: Vec::new(),
386 owns_directory: true,
387 root_module_name: None,
388 expected_tokens: Vec::new(),
392 /// Convert a token to a string using self's reader
393 pub fn token_to_string(token: &token::Token) -> String {
394 pprust::token_to_string(token)
397 /// Convert the current token to a string using self's reader
398 pub fn this_token_to_string(&self) -> String {
399 Parser::token_to_string(&self.token)
402 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
403 let token_str = Parser::token_to_string(t);
404 let last_span = self.last_span;
405 Err(self.span_fatal(last_span, &format!("unexpected token: `{}`", token_str)))
408 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
409 match self.expect_one_of(&[], &[]) {
411 Ok(_) => unreachable!(),
415 /// Expect and consume the token t. Signal an error if
416 /// the next token is not t.
417 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
418 if self.expected_tokens.is_empty() {
419 if self.token == *t {
423 let token_str = Parser::token_to_string(t);
424 let this_token_str = self.this_token_to_string();
425 Err(self.fatal(&format!("expected `{}`, found `{}`",
430 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
434 /// Expect next token to be edible or inedible token. If edible,
435 /// then consume it; if inedible, then return without consuming
436 /// anything. Signal a fatal error if next token is unexpected.
437 pub fn expect_one_of(&mut self,
438 edible: &[token::Token],
439 inedible: &[token::Token]) -> PResult<'a, ()>{
440 fn tokens_to_string(tokens: &[TokenType]) -> String {
441 let mut i = tokens.iter();
442 // This might be a sign we need a connect method on Iterator.
444 .map_or("".to_string(), |t| t.to_string());
445 i.enumerate().fold(b, |mut b, (i, ref a)| {
446 if tokens.len() > 2 && i == tokens.len() - 2 {
448 } else if tokens.len() == 2 && i == tokens.len() - 2 {
453 b.push_str(&a.to_string());
457 if edible.contains(&self.token) {
460 } else if inedible.contains(&self.token) {
461 // leave it in the input
464 let mut expected = edible.iter()
465 .map(|x| TokenType::Token(x.clone()))
466 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
467 .chain(self.expected_tokens.iter().cloned())
468 .collect::<Vec<_>>();
469 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
471 let expect = tokens_to_string(&expected[..]);
472 let actual = self.this_token_to_string();
474 &(if expected.len() > 1 {
475 (format!("expected one of {}, found `{}`",
478 } else if expected.is_empty() {
479 (format!("unexpected token: `{}`",
482 (format!("expected {}, found `{}`",
490 /// Check for erroneous `ident { }`; if matches, signal error and
491 /// recover (without consuming any expected input token). Returns
492 /// true if and only if input was consumed for recovery.
493 pub fn check_for_erroneous_unit_struct_expecting(&mut self,
494 expected: &[token::Token])
496 if self.token == token::OpenDelim(token::Brace)
497 && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
498 && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
499 // matched; signal non-fatal error and recover.
500 let span = self.span;
501 self.span_err(span, "unit-like struct construction is written with no trailing `{ }`");
502 self.eat(&token::OpenDelim(token::Brace));
503 self.eat(&token::CloseDelim(token::Brace));
510 /// Commit to parsing a complete expression `e` expected to be
511 /// followed by some token from the set edible + inedible. Recover
512 /// from anticipated input errors, discarding erroneous characters.
513 pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token],
514 inedible: &[token::Token]) -> PResult<'a, ()> {
515 debug!("commit_expr {:?}", e);
516 if let ExprKind::Path(..) = e.node {
517 // might be unit-struct construction; check for recoverableinput error.
518 let expected = edible.iter()
520 .chain(inedible.iter().cloned())
521 .collect::<Vec<_>>();
522 self.check_for_erroneous_unit_struct_expecting(&expected[..]);
524 self.expect_one_of(edible, inedible)
527 pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) -> PResult<'a, ()> {
528 self.commit_expr(e, &[edible], &[])
531 /// Commit to parsing a complete statement `s`, which expects to be
532 /// followed by some token from the set edible + inedible. Check
533 /// for recoverable input errors, discarding erroneous characters.
534 pub fn commit_stmt(&mut self, edible: &[token::Token],
535 inedible: &[token::Token]) -> PResult<'a, ()> {
538 .map_or(false, |t| t.is_ident() || t.is_path()) {
539 let expected = edible.iter()
541 .chain(inedible.iter().cloned())
542 .collect::<Vec<_>>();
543 self.check_for_erroneous_unit_struct_expecting(&expected);
545 self.expect_one_of(edible, inedible)
548 pub fn commit_stmt_expecting(&mut self, edible: token::Token) -> PResult<'a, ()> {
549 self.commit_stmt(&[edible], &[])
552 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
553 fn interpolated_or_expr_span(&self,
554 expr: PResult<'a, P<Expr>>)
555 -> PResult<'a, (Span, P<Expr>)> {
557 if self.last_token_interpolated {
565 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
566 self.check_strict_keywords();
567 self.check_reserved_keywords();
569 token::Ident(i, _) => {
573 token::Interpolated(token::NtIdent(..)) => {
574 self.bug("ident interpolation not converted to real token");
577 let token_str = self.this_token_to_string();
578 Err(self.fatal(&format!("expected ident, found `{}`",
584 pub fn parse_ident_or_self_type(&mut self) -> PResult<'a, ast::Ident> {
585 if self.is_self_type_ident() {
586 self.expect_self_type_ident()
592 pub fn parse_path_list_item(&mut self) -> PResult<'a, ast::PathListItem> {
593 let lo = self.span.lo;
594 let node = if self.eat_keyword(keywords::SelfValue) {
595 let rename = try!(self.parse_rename());
596 ast::PathListItemKind::Mod { id: ast::DUMMY_NODE_ID, rename: rename }
598 let ident = try!(self.parse_ident());
599 let rename = try!(self.parse_rename());
600 ast::PathListItemKind::Ident { name: ident, rename: rename, id: ast::DUMMY_NODE_ID }
602 let hi = self.last_span.hi;
603 Ok(spanned(lo, hi, node))
606 /// Check if the next token is `tok`, and return `true` if so.
608 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
610 pub fn check(&mut self, tok: &token::Token) -> bool {
611 let is_present = self.token == *tok;
612 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
616 /// Consume token 'tok' if it exists. Returns true if the given
617 /// token was present, false otherwise.
618 pub fn eat(&mut self, tok: &token::Token) -> bool {
619 let is_present = self.check(tok);
620 if is_present { self.bump() }
624 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
625 self.expected_tokens.push(TokenType::Keyword(kw));
626 self.token.is_keyword(kw)
629 /// If the next token is the given keyword, eat it and return
630 /// true. Otherwise, return false.
631 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
632 if self.check_keyword(kw) {
640 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
641 if self.token.is_keyword(kw) {
649 /// If the given word is not a keyword, signal an error.
650 /// If the next token is not the given word, signal an error.
651 /// Otherwise, eat it.
652 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
653 if !self.eat_keyword(kw) {
660 /// Signal an error if the given string is a strict keyword
661 pub fn check_strict_keywords(&mut self) {
662 if self.token.is_strict_keyword() {
663 let token_str = self.this_token_to_string();
664 let span = self.span;
666 &format!("expected identifier, found keyword `{}`",
671 /// Signal an error if the current token is a reserved keyword
672 pub fn check_reserved_keywords(&mut self) {
673 if self.token.is_reserved_keyword() {
674 let token_str = self.this_token_to_string();
675 self.fatal(&format!("`{}` is a reserved keyword", token_str)).emit()
679 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
680 /// `&` and continue. If an `&` is not seen, signal an error.
681 fn expect_and(&mut self) -> PResult<'a, ()> {
682 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
684 token::BinOp(token::And) => {
689 let span = self.span;
690 let lo = span.lo + BytePos(1);
691 Ok(self.bump_with(token::BinOp(token::And), lo, span.hi))
693 _ => self.unexpected()
697 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
699 None => {/* everything ok */}
701 let text = suf.as_str();
703 self.span_bug(sp, "found empty literal suffix in Some")
705 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
711 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
712 /// `<` and continue. If a `<` is not seen, return false.
714 /// This is meant to be used when parsing generics on a path to get the
716 fn eat_lt(&mut self) -> bool {
717 self.expected_tokens.push(TokenType::Token(token::Lt));
723 token::BinOp(token::Shl) => {
724 let span = self.span;
725 let lo = span.lo + BytePos(1);
726 self.bump_with(token::Lt, lo, span.hi);
733 fn expect_lt(&mut self) -> PResult<'a, ()> {
741 /// Expect and consume a GT. if a >> is seen, replace it
742 /// with a single > and continue. If a GT is not seen,
744 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
745 self.expected_tokens.push(TokenType::Token(token::Gt));
751 token::BinOp(token::Shr) => {
752 let span = self.span;
753 let lo = span.lo + BytePos(1);
754 Ok(self.bump_with(token::Gt, lo, span.hi))
756 token::BinOpEq(token::Shr) => {
757 let span = self.span;
758 let lo = span.lo + BytePos(1);
759 Ok(self.bump_with(token::Ge, lo, span.hi))
762 let span = self.span;
763 let lo = span.lo + BytePos(1);
764 Ok(self.bump_with(token::Eq, lo, span.hi))
767 let gt_str = Parser::token_to_string(&token::Gt);
768 let this_token_str = self.this_token_to_string();
769 Err(self.fatal(&format!("expected `{}`, found `{}`",
776 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
777 sep: Option<token::Token>,
779 -> PResult<'a, (P<[T]>, bool)>
780 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
782 let mut v = Vec::new();
783 // This loop works by alternating back and forth between parsing types
784 // and commas. For example, given a string `A, B,>`, the parser would
785 // first parse `A`, then a comma, then `B`, then a comma. After that it
786 // would encounter a `>` and stop. This lets the parser handle trailing
787 // commas in generic parameters, because it can stop either after
788 // parsing a type or after parsing a comma.
790 if self.check(&token::Gt)
791 || self.token == token::BinOp(token::Shr)
792 || self.token == token::Ge
793 || self.token == token::BinOpEq(token::Shr) {
798 match try!(f(self)) {
799 Some(result) => v.push(result),
800 None => return Ok((P::from_vec(v), true))
803 if let Some(t) = sep.as_ref() {
804 try!(self.expect(t));
809 return Ok((P::from_vec(v), false));
812 /// Parse a sequence bracketed by '<' and '>', stopping
814 pub fn parse_seq_to_before_gt<T, F>(&mut self,
815 sep: Option<token::Token>,
817 -> PResult<'a, P<[T]>> where
818 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
820 let (result, returned) = try!(self.parse_seq_to_before_gt_or_return(sep,
821 |p| Ok(Some(try!(f(p))))));
826 pub fn parse_seq_to_gt<T, F>(&mut self,
827 sep: Option<token::Token>,
829 -> PResult<'a, P<[T]>> where
830 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
832 let v = try!(self.parse_seq_to_before_gt(sep, f));
833 try!(self.expect_gt());
837 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
838 sep: Option<token::Token>,
840 -> PResult<'a, (P<[T]>, bool)> where
841 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
843 let (v, returned) = try!(self.parse_seq_to_before_gt_or_return(sep, f));
845 try!(self.expect_gt());
847 return Ok((v, returned));
850 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
851 /// passes through any errors encountered. Used for error recovery.
852 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
853 self.parse_seq_to_before_tokens(kets,
855 |p| p.parse_token_tree(),
859 /// Parse a sequence, including the closing delimiter. The function
860 /// f must consume tokens until reaching the next separator or
862 pub fn parse_seq_to_end<T, F>(&mut self,
866 -> PResult<'a, Vec<T>> where
867 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
869 let val = self.parse_seq_to_before_end(ket, sep, f);
874 /// Parse a sequence, not including the closing delimiter. The function
875 /// f must consume tokens until reaching the next separator or
877 pub fn parse_seq_to_before_end<T, F>(&mut self,
882 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
884 self.parse_seq_to_before_tokens(&[ket], sep, f, |mut e| e.emit())
887 // `fe` is an error handler.
888 fn parse_seq_to_before_tokens<T, F, Fe>(&mut self,
889 kets: &[&token::Token],
894 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
895 Fe: FnMut(DiagnosticBuilder)
897 let mut first: bool = true;
899 while !kets.contains(&&self.token) {
905 if let Err(e) = self.expect(t) {
913 if sep.trailing_sep_allowed && kets.iter().any(|k| self.check(k)) {
929 /// Parse a sequence, including the closing delimiter. The function
930 /// f must consume tokens until reaching the next separator or
932 pub fn parse_unspanned_seq<T, F>(&mut self,
937 -> PResult<'a, Vec<T>> where
938 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
940 try!(self.expect(bra));
941 let result = self.parse_seq_to_before_end(ket, sep, f);
946 /// Parse a sequence parameter of enum variant. For consistency purposes,
947 /// these should not be empty.
948 pub fn parse_enum_variant_seq<T, F>(&mut self,
953 -> PResult<'a, Vec<T>> where
954 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
956 let result = try!(self.parse_unspanned_seq(bra, ket, sep, f));
957 if result.is_empty() {
958 let last_span = self.last_span;
959 self.span_err(last_span,
960 "nullary enum variants are written with no trailing `( )`");
965 // NB: Do not use this function unless you actually plan to place the
966 // spanned list in the AST.
967 pub fn parse_seq<T, F>(&mut self,
972 -> PResult<'a, Spanned<Vec<T>>> where
973 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
975 let lo = self.span.lo;
976 try!(self.expect(bra));
977 let result = self.parse_seq_to_before_end(ket, sep, f);
978 let hi = self.span.hi;
980 Ok(spanned(lo, hi, result))
983 /// Advance the parser by one token
984 pub fn bump(&mut self) {
985 self.last_span = self.span;
986 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
987 self.last_token = if self.token.is_ident() ||
988 self.token.is_path() ||
989 self.token == token::Comma {
990 Some(Box::new(self.token.clone()))
994 self.last_token_interpolated = self.token.is_interpolated();
995 let next = if self.buffer_start == self.buffer_end {
996 self.reader.real_token()
998 // Avoid token copies with `replace`.
999 let buffer_start = self.buffer_start as usize;
1000 let next_index = (buffer_start + 1) & 3;
1001 self.buffer_start = next_index as isize;
1003 let placeholder = TokenAndSpan {
1004 tok: token::Underscore,
1007 mem::replace(&mut self.buffer[buffer_start], placeholder)
1009 self.span = next.sp;
1010 self.token = next.tok;
1011 self.tokens_consumed += 1;
1012 self.expected_tokens.clear();
1013 // check after each token
1014 self.check_unknown_macro_variable();
1017 /// Advance the parser by one token and return the bumped token.
1018 pub fn bump_and_get(&mut self) -> token::Token {
1019 let old_token = mem::replace(&mut self.token, token::Underscore);
1024 /// Advance the parser using provided token as a next one. Use this when
1025 /// consuming a part of a token. For example a single `<` from `<<`.
1026 pub fn bump_with(&mut self,
1030 self.last_span = mk_sp(self.span.lo, lo);
1031 // It would be incorrect to just stash current token, but fortunately
1032 // for tokens currently using `bump_with`, last_token will be of no
1034 self.last_token = None;
1035 self.last_token_interpolated = false;
1036 self.span = mk_sp(lo, hi);
1038 self.expected_tokens.clear();
1041 pub fn buffer_length(&mut self) -> isize {
1042 if self.buffer_start <= self.buffer_end {
1043 return self.buffer_end - self.buffer_start;
1045 return (4 - self.buffer_start) + self.buffer_end;
1047 pub fn look_ahead<R, F>(&mut self, distance: usize, f: F) -> R where
1048 F: FnOnce(&token::Token) -> R,
1050 let dist = distance as isize;
1051 while self.buffer_length() < dist {
1052 self.buffer[self.buffer_end as usize] = self.reader.real_token();
1053 self.buffer_end = (self.buffer_end + 1) & 3;
1055 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as usize].tok)
1057 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1058 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1060 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1061 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1063 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1064 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1065 err.fileline_help(sp, help);
1068 pub fn bug(&self, m: &str) -> ! {
1069 self.sess.span_diagnostic.span_bug(self.span, m)
1071 pub fn warn(&self, m: &str) {
1072 self.sess.span_diagnostic.span_warn(self.span, m)
1074 pub fn span_warn(&self, sp: Span, m: &str) {
1075 self.sess.span_diagnostic.span_warn(sp, m)
1077 pub fn span_err(&self, sp: Span, m: &str) {
1078 self.sess.span_diagnostic.span_err(sp, m)
1080 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1081 self.sess.span_diagnostic.span_bug(sp, m)
1083 pub fn abort_if_errors(&self) {
1084 self.sess.span_diagnostic.abort_if_errors();
1087 pub fn diagnostic(&self) -> &'a errors::Handler {
1088 &self.sess.span_diagnostic
1091 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
1095 /// Is the current token one of the keywords that signals a bare function
1097 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1098 self.check_keyword(keywords::Fn) ||
1099 self.check_keyword(keywords::Unsafe) ||
1100 self.check_keyword(keywords::Extern)
1103 pub fn get_lifetime(&mut self) -> ast::Ident {
1105 token::Lifetime(ref ident) => *ident,
1106 _ => self.bug("not a lifetime"),
1110 pub fn parse_for_in_type(&mut self) -> PResult<'a, TyKind> {
1112 Parses whatever can come after a `for` keyword in a type.
1113 The `for` has already been consumed.
1117 - for <'lt> |S| -> T
1121 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1122 - for <'lt> path::foo(a, b)
1127 let lo = self.span.lo;
1129 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
1131 // examine next token to decide to do
1132 if self.token_is_bare_fn_keyword() {
1133 self.parse_ty_bare_fn(lifetime_defs)
1135 let hi = self.span.hi;
1136 let trait_ref = try!(self.parse_trait_ref());
1137 let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1138 trait_ref: trait_ref,
1139 span: mk_sp(lo, hi)};
1140 let other_bounds = if self.eat(&token::BinOp(token::Plus)) {
1141 try!(self.parse_ty_param_bounds(BoundParsingMode::Bare))
1146 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1147 .chain(other_bounds.into_vec())
1149 Ok(ast::TyKind::PolyTraitRef(all_bounds))
1153 pub fn parse_ty_path(&mut self) -> PResult<'a, TyKind> {
1154 Ok(TyKind::Path(None, try!(self.parse_path(LifetimeAndTypesWithoutColons))))
1157 /// parse a TyKind::BareFn type:
1158 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>)
1159 -> PResult<'a, TyKind> {
1162 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1163 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1166 | | | Argument types
1172 let unsafety = try!(self.parse_unsafety());
1173 let abi = if self.eat_keyword(keywords::Extern) {
1174 try!(self.parse_opt_abi()).unwrap_or(Abi::C)
1179 try!(self.expect_keyword(keywords::Fn));
1180 let (inputs, variadic) = try!(self.parse_fn_args(false, true));
1181 let ret_ty = try!(self.parse_ret_ty());
1182 let decl = P(FnDecl {
1187 Ok(TyKind::BareFn(P(BareFnTy {
1190 lifetimes: lifetime_defs,
1195 /// Parses an obsolete closure kind (`&:`, `&mut:`, or `:`).
1196 pub fn parse_obsolete_closure_kind(&mut self) -> PResult<'a, ()> {
1197 let lo = self.span.lo;
1199 self.check(&token::BinOp(token::And)) &&
1200 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1201 self.look_ahead(2, |t| *t == token::Colon)
1207 self.token == token::BinOp(token::And) &&
1208 self.look_ahead(1, |t| *t == token::Colon)
1213 self.eat(&token::Colon)
1220 let span = mk_sp(lo, self.span.hi);
1221 self.obsolete(span, ObsoleteSyntax::ClosureKind);
1225 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1226 if self.eat_keyword(keywords::Unsafe) {
1227 return Ok(Unsafety::Unsafe);
1229 return Ok(Unsafety::Normal);
1233 /// Parse the items in a trait declaration
1234 pub fn parse_trait_items(&mut self) -> PResult<'a, Vec<TraitItem>> {
1235 self.parse_unspanned_seq(
1236 &token::OpenDelim(token::Brace),
1237 &token::CloseDelim(token::Brace),
1239 |p| -> PResult<'a, TraitItem> {
1240 maybe_whole!(no_clone_from_p p, NtTraitItem);
1241 let mut attrs = try!(p.parse_outer_attributes());
1244 let (name, node) = if p.eat_keyword(keywords::Type) {
1245 let TyParam {ident, bounds, default, ..} = try!(p.parse_ty_param());
1246 try!(p.expect(&token::Semi));
1247 (ident, TraitItemKind::Type(bounds, default))
1248 } else if p.is_const_item() {
1249 try!(p.expect_keyword(keywords::Const));
1250 let ident = try!(p.parse_ident());
1251 try!(p.expect(&token::Colon));
1252 let ty = try!(p.parse_ty_sum());
1253 let default = if p.check(&token::Eq) {
1255 let expr = try!(p.parse_expr());
1256 try!(p.commit_expr_expecting(&expr, token::Semi));
1259 try!(p.expect(&token::Semi));
1262 (ident, TraitItemKind::Const(ty, default))
1264 let (constness, unsafety, abi) = match p.parse_fn_front_matter() {
1269 if p.token == token::Semi {
1274 if p.token == token::OpenDelim(token::DelimToken::Brace) {
1275 try!(p.parse_token_tree());
1284 let ident = try!(p.parse_ident());
1285 let mut generics = try!(p.parse_generics());
1287 let (explicit_self, d) = try!(p.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1288 // This is somewhat dubious; We don't want to allow
1289 // argument names to be left off if there is a
1291 p.parse_arg_general(false)
1294 generics.where_clause = try!(p.parse_where_clause());
1295 let sig = ast::MethodSig {
1297 constness: constness,
1301 explicit_self: explicit_self,
1304 let body = match p.token {
1307 debug!("parse_trait_methods(): parsing required method");
1310 token::OpenDelim(token::Brace) => {
1311 debug!("parse_trait_methods(): parsing provided method");
1312 let (inner_attrs, body) =
1313 try!(p.parse_inner_attrs_and_block());
1314 attrs.extend(inner_attrs.iter().cloned());
1319 let token_str = p.this_token_to_string();
1320 return Err(p.fatal(&format!("expected `;` or `{{`, found `{}`",
1324 (ident, ast::TraitItemKind::Method(sig, body))
1328 id: ast::DUMMY_NODE_ID,
1332 span: mk_sp(lo, p.last_span.hi),
1337 /// Parse a possibly mutable type
1338 pub fn parse_mt(&mut self) -> PResult<'a, MutTy> {
1339 let mutbl = try!(self.parse_mutability());
1340 let t = try!(self.parse_ty());
1341 Ok(MutTy { ty: t, mutbl: mutbl })
1344 /// Parse optional return type [ -> TY ] in function decl
1345 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1346 if self.eat(&token::RArrow) {
1347 if self.eat(&token::Not) {
1348 Ok(FunctionRetTy::None(self.last_span))
1350 Ok(FunctionRetTy::Ty(try!(self.parse_ty())))
1353 let pos = self.span.lo;
1354 Ok(FunctionRetTy::Default(mk_sp(pos, pos)))
1358 /// Parse a type in a context where `T1+T2` is allowed.
1359 pub fn parse_ty_sum(&mut self) -> PResult<'a, P<Ty>> {
1360 let lo = self.span.lo;
1361 let lhs = try!(self.parse_ty());
1363 if !self.eat(&token::BinOp(token::Plus)) {
1367 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
1369 // In type grammar, `+` is treated like a binary operator,
1370 // and hence both L and R side are required.
1371 if bounds.is_empty() {
1372 let last_span = self.last_span;
1373 self.span_err(last_span,
1374 "at least one type parameter bound \
1375 must be specified");
1378 let sp = mk_sp(lo, self.last_span.hi);
1379 let sum = ast::TyKind::ObjectSum(lhs, bounds);
1380 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp}))
1384 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1385 maybe_whole!(no_clone self, NtTy);
1387 let lo = self.span.lo;
1389 let t = if self.check(&token::OpenDelim(token::Paren)) {
1392 // (t) is a parenthesized ty
1393 // (t,) is the type of a tuple with only one field,
1395 let mut ts = vec![];
1396 let mut last_comma = false;
1397 while self.token != token::CloseDelim(token::Paren) {
1398 ts.push(try!(self.parse_ty_sum()));
1399 if self.check(&token::Comma) {
1408 try!(self.expect(&token::CloseDelim(token::Paren)));
1409 if ts.len() == 1 && !last_comma {
1410 TyKind::Paren(ts.into_iter().nth(0).unwrap())
1414 } else if self.check(&token::BinOp(token::Star)) {
1415 // STAR POINTER (bare pointer?)
1417 TyKind::Ptr(try!(self.parse_ptr()))
1418 } else if self.check(&token::OpenDelim(token::Bracket)) {
1420 try!(self.expect(&token::OpenDelim(token::Bracket)));
1421 let t = try!(self.parse_ty_sum());
1423 // Parse the `; e` in `[ i32; e ]`
1424 // where `e` is a const expression
1425 let t = match try!(self.maybe_parse_fixed_length_of_vec()) {
1426 None => TyKind::Vec(t),
1427 Some(suffix) => TyKind::FixedLengthVec(t, suffix)
1429 try!(self.expect(&token::CloseDelim(token::Bracket)));
1431 } else if self.check(&token::BinOp(token::And)) ||
1432 self.token == token::AndAnd {
1434 try!(self.expect_and());
1435 try!(self.parse_borrowed_pointee())
1436 } else if self.check_keyword(keywords::For) {
1437 try!(self.parse_for_in_type())
1438 } else if self.token_is_bare_fn_keyword() {
1440 try!(self.parse_ty_bare_fn(Vec::new()))
1441 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1443 // In order to not be ambiguous, the type must be surrounded by parens.
1444 try!(self.expect(&token::OpenDelim(token::Paren)));
1445 let e = try!(self.parse_expr());
1446 try!(self.expect(&token::CloseDelim(token::Paren)));
1448 } else if self.eat_lt() {
1451 try!(self.parse_qualified_path(NoTypesAllowed));
1453 TyKind::Path(Some(qself), path)
1454 } else if self.check(&token::ModSep) ||
1455 self.token.is_ident() ||
1456 self.token.is_path() {
1457 let path = try!(self.parse_path(LifetimeAndTypesWithoutColons));
1458 if self.check(&token::Not) {
1461 let delim = try!(self.expect_open_delim());
1462 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
1464 |p| p.parse_token_tree()));
1465 let hi = self.span.hi;
1466 TyKind::Mac(spanned(lo, hi, Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT }))
1469 TyKind::Path(None, path)
1471 } else if self.eat(&token::Underscore) {
1472 // TYPE TO BE INFERRED
1475 let this_token_str = self.this_token_to_string();
1476 let msg = format!("expected type, found `{}`", this_token_str);
1477 return Err(self.fatal(&msg[..]));
1480 let sp = mk_sp(lo, self.last_span.hi);
1481 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp}))
1484 pub fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1485 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1486 let opt_lifetime = try!(self.parse_opt_lifetime());
1488 let mt = try!(self.parse_mt());
1489 return Ok(TyKind::Rptr(opt_lifetime, mt));
1492 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1493 let mutbl = if self.eat_keyword(keywords::Mut) {
1495 } else if self.eat_keyword(keywords::Const) {
1496 Mutability::Immutable
1498 let span = self.last_span;
1500 "bare raw pointers are no longer allowed, you should \
1501 likely use `*mut T`, but otherwise `*T` is now \
1502 known as `*const T`");
1503 Mutability::Immutable
1505 let t = try!(self.parse_ty());
1506 Ok(MutTy { ty: t, mutbl: mutbl })
1509 pub fn is_named_argument(&mut self) -> bool {
1510 let offset = match self.token {
1511 token::BinOp(token::And) => 1,
1513 _ if self.token.is_keyword(keywords::Mut) => 1,
1517 debug!("parser is_named_argument offset:{}", offset);
1520 is_plain_ident_or_underscore(&self.token)
1521 && self.look_ahead(1, |t| *t == token::Colon)
1523 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1524 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1528 /// This version of parse arg doesn't necessarily require
1529 /// identifier names.
1530 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1531 maybe_whole!(no_clone self, NtArg);
1533 let pat = if require_name || self.is_named_argument() {
1534 debug!("parse_arg_general parse_pat (require_name:{})",
1536 let pat = try!(self.parse_pat());
1538 try!(self.expect(&token::Colon));
1541 debug!("parse_arg_general ident_to_pat");
1542 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1544 special_idents::invalid)
1547 let t = try!(self.parse_ty_sum());
1552 id: ast::DUMMY_NODE_ID,
1556 /// Parse a single function argument
1557 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1558 self.parse_arg_general(true)
1561 /// Parse an argument in a lambda header e.g. |arg, arg|
1562 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1563 let pat = try!(self.parse_pat());
1564 let t = if self.eat(&token::Colon) {
1565 try!(self.parse_ty_sum())
1568 id: ast::DUMMY_NODE_ID,
1569 node: TyKind::Infer,
1570 span: mk_sp(self.span.lo, self.span.hi),
1576 id: ast::DUMMY_NODE_ID
1580 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1581 if self.check(&token::Semi) {
1583 Ok(Some(try!(self.parse_expr())))
1589 /// Matches token_lit = LIT_INTEGER | ...
1590 pub fn lit_from_token(&self, tok: &token::Token) -> PResult<'a, LitKind> {
1592 token::Interpolated(token::NtExpr(ref v)) => {
1594 ExprKind::Lit(ref lit) => { Ok(lit.node.clone()) }
1595 _ => { return self.unexpected_last(tok); }
1598 token::Literal(lit, suf) => {
1599 let (suffix_illegal, out) = match lit {
1600 token::Byte(i) => (true, LitKind::Byte(parse::byte_lit(&i.as_str()).0)),
1601 token::Char(i) => (true, LitKind::Char(parse::char_lit(&i.as_str()).0)),
1603 // there are some valid suffixes for integer and
1604 // float literals, so all the handling is done
1606 token::Integer(s) => {
1607 (false, parse::integer_lit(&s.as_str(),
1608 suf.as_ref().map(|s| s.as_str()),
1609 &self.sess.span_diagnostic,
1612 token::Float(s) => {
1613 (false, parse::float_lit(&s.as_str(),
1614 suf.as_ref().map(|s| s.as_str()),
1615 &self.sess.span_diagnostic,
1621 LitKind::Str(token::intern_and_get_ident(&parse::str_lit(&s.as_str())),
1622 ast::StrStyle::Cooked))
1624 token::StrRaw(s, n) => {
1627 token::intern_and_get_ident(&parse::raw_str_lit(&s.as_str())),
1628 ast::StrStyle::Raw(n)))
1630 token::ByteStr(i) =>
1631 (true, LitKind::ByteStr(parse::byte_str_lit(&i.as_str()))),
1632 token::ByteStrRaw(i, _) =>
1634 LitKind::ByteStr(Rc::new(i.to_string().into_bytes()))),
1638 let sp = self.last_span;
1639 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1644 _ => { return self.unexpected_last(tok); }
1648 /// Matches lit = true | false | token_lit
1649 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1650 let lo = self.span.lo;
1651 let lit = if self.eat_keyword(keywords::True) {
1653 } else if self.eat_keyword(keywords::False) {
1654 LitKind::Bool(false)
1656 let token = self.bump_and_get();
1657 let lit = try!(self.lit_from_token(&token));
1660 Ok(codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) })
1663 /// matches '-' lit | lit
1664 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1665 let minus_lo = self.span.lo;
1666 let minus_present = self.eat(&token::BinOp(token::Minus));
1667 let lo = self.span.lo;
1668 let literal = P(try!(self.parse_lit()));
1669 let hi = self.last_span.hi;
1670 let expr = self.mk_expr(lo, hi, ExprKind::Lit(literal), None);
1673 let minus_hi = self.last_span.hi;
1674 let unary = self.mk_unary(UnOp::Neg, expr);
1675 Ok(self.mk_expr(minus_lo, minus_hi, unary, None))
1681 /// Parses qualified path.
1683 /// Assumes that the leading `<` has been parsed already.
1685 /// Qualifed paths are a part of the universal function call
1688 /// `qualified_path = <type [as trait_ref]>::path`
1690 /// See `parse_path` for `mode` meaning.
1695 /// `<T as U>::F::a::<S>`
1696 pub fn parse_qualified_path(&mut self, mode: PathParsingMode)
1697 -> PResult<'a, (QSelf, ast::Path)> {
1698 let span = self.last_span;
1699 let self_type = try!(self.parse_ty_sum());
1700 let mut path = if self.eat_keyword(keywords::As) {
1701 try!(self.parse_path(LifetimeAndTypesWithoutColons))
1712 position: path.segments.len()
1715 try!(self.expect(&token::Gt));
1716 try!(self.expect(&token::ModSep));
1718 let segments = match mode {
1719 LifetimeAndTypesWithoutColons => {
1720 try!(self.parse_path_segments_without_colons())
1722 LifetimeAndTypesWithColons => {
1723 try!(self.parse_path_segments_with_colons())
1726 try!(self.parse_path_segments_without_types())
1729 path.segments.extend(segments);
1731 path.span.hi = self.last_span.hi;
1736 /// Parses a path and optional type parameter bounds, depending on the
1737 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1738 /// bounds are permitted and whether `::` must precede type parameter
1740 pub fn parse_path(&mut self, mode: PathParsingMode) -> PResult<'a, ast::Path> {
1741 // Check for a whole path...
1742 let found = match self.token {
1743 token::Interpolated(token::NtPath(_)) => Some(self.bump_and_get()),
1746 if let Some(token::Interpolated(token::NtPath(path))) = found {
1750 let lo = self.span.lo;
1751 let is_global = self.eat(&token::ModSep);
1753 // Parse any number of segments and bound sets. A segment is an
1754 // identifier followed by an optional lifetime and a set of types.
1755 // A bound set is a set of type parameter bounds.
1756 let segments = match mode {
1757 LifetimeAndTypesWithoutColons => {
1758 try!(self.parse_path_segments_without_colons())
1760 LifetimeAndTypesWithColons => {
1761 try!(self.parse_path_segments_with_colons())
1764 try!(self.parse_path_segments_without_types())
1768 // Assemble the span.
1769 let span = mk_sp(lo, self.last_span.hi);
1771 // Assemble the result.
1780 /// - `a::b<T,U>::c<V,W>`
1781 /// - `a::b<T,U>::c(V) -> W`
1782 /// - `a::b<T,U>::c(V)`
1783 pub fn parse_path_segments_without_colons(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1784 let mut segments = Vec::new();
1786 // First, parse an identifier.
1787 let identifier = try!(self.parse_ident_or_self_type());
1789 // Parse types, optionally.
1790 let parameters = if self.eat_lt() {
1791 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1793 ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
1794 lifetimes: lifetimes,
1795 types: P::from_vec(types),
1796 bindings: P::from_vec(bindings),
1798 } else if self.eat(&token::OpenDelim(token::Paren)) {
1799 let lo = self.last_span.lo;
1801 let inputs = try!(self.parse_seq_to_end(
1802 &token::CloseDelim(token::Paren),
1803 seq_sep_trailing_allowed(token::Comma),
1804 |p| p.parse_ty_sum()));
1806 let output_ty = if self.eat(&token::RArrow) {
1807 Some(try!(self.parse_ty()))
1812 let hi = self.last_span.hi;
1814 ast::PathParameters::Parenthesized(ast::ParenthesizedParameterData {
1815 span: mk_sp(lo, hi),
1820 ast::PathParameters::none()
1823 // Assemble and push the result.
1824 segments.push(ast::PathSegment { identifier: identifier,
1825 parameters: parameters });
1827 // Continue only if we see a `::`
1828 if !self.eat(&token::ModSep) {
1829 return Ok(segments);
1835 /// - `a::b::<T,U>::c`
1836 pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1837 let mut segments = Vec::new();
1839 // First, parse an identifier.
1840 let identifier = try!(self.parse_ident_or_self_type());
1842 // If we do not see a `::`, stop.
1843 if !self.eat(&token::ModSep) {
1844 segments.push(ast::PathSegment {
1845 identifier: identifier,
1846 parameters: ast::PathParameters::none()
1848 return Ok(segments);
1851 // Check for a type segment.
1853 // Consumed `a::b::<`, go look for types
1854 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1855 let parameters = ast::AngleBracketedParameterData {
1856 lifetimes: lifetimes,
1857 types: P::from_vec(types),
1858 bindings: P::from_vec(bindings),
1860 segments.push(ast::PathSegment {
1861 identifier: identifier,
1862 parameters: ast::PathParameters::AngleBracketed(parameters),
1865 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1866 if !self.eat(&token::ModSep) {
1867 return Ok(segments);
1870 // Consumed `a::`, go look for `b`
1871 segments.push(ast::PathSegment {
1872 identifier: identifier,
1873 parameters: ast::PathParameters::none(),
1882 pub fn parse_path_segments_without_types(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1883 let mut segments = Vec::new();
1885 // First, parse an identifier.
1886 let identifier = try!(self.parse_ident_or_self_type());
1888 // Assemble and push the result.
1889 segments.push(ast::PathSegment {
1890 identifier: identifier,
1891 parameters: ast::PathParameters::none()
1894 // If we do not see a `::`, stop.
1895 if !self.eat(&token::ModSep) {
1896 return Ok(segments);
1901 /// parses 0 or 1 lifetime
1902 pub fn parse_opt_lifetime(&mut self) -> PResult<'a, Option<ast::Lifetime>> {
1904 token::Lifetime(..) => {
1905 Ok(Some(try!(self.parse_lifetime())))
1913 /// Parses a single lifetime
1914 /// Matches lifetime = LIFETIME
1915 pub fn parse_lifetime(&mut self) -> PResult<'a, ast::Lifetime> {
1917 token::Lifetime(i) => {
1918 let span = self.span;
1920 return Ok(ast::Lifetime {
1921 id: ast::DUMMY_NODE_ID,
1927 return Err(self.fatal("expected a lifetime name"));
1932 /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def =
1933 /// lifetime [':' lifetimes]`
1934 pub fn parse_lifetime_defs(&mut self) -> PResult<'a, Vec<ast::LifetimeDef>> {
1936 let mut res = Vec::new();
1939 token::Lifetime(_) => {
1940 let lifetime = try!(self.parse_lifetime());
1942 if self.eat(&token::Colon) {
1943 try!(self.parse_lifetimes(token::BinOp(token::Plus)))
1947 res.push(ast::LifetimeDef { lifetime: lifetime,
1957 token::Comma => { self.bump();}
1958 token::Gt => { return Ok(res); }
1959 token::BinOp(token::Shr) => { return Ok(res); }
1961 let this_token_str = self.this_token_to_string();
1962 let msg = format!("expected `,` or `>` after lifetime \
1965 return Err(self.fatal(&msg[..]));
1971 /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
1972 /// one too, but putting that in there messes up the grammar....
1974 /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
1975 /// either a comma or `>`. Used when parsing type parameter lists, where we expect something
1976 /// like `<'a, 'b, T>`.
1977 pub fn parse_lifetimes(&mut self, sep: token::Token) -> PResult<'a, Vec<ast::Lifetime>> {
1979 let mut res = Vec::new();
1982 token::Lifetime(_) => {
1983 res.push(try!(self.parse_lifetime()));
1990 if self.token != sep {
1998 /// Parse mutability declaration (mut/const/imm)
1999 pub fn parse_mutability(&mut self) -> PResult<'a, Mutability> {
2000 if self.eat_keyword(keywords::Mut) {
2001 Ok(Mutability::Mutable)
2003 Ok(Mutability::Immutable)
2007 /// Parse ident COLON expr
2008 pub fn parse_field(&mut self) -> PResult<'a, Field> {
2009 let lo = self.span.lo;
2010 let i = try!(self.parse_ident());
2011 let hi = self.last_span.hi;
2012 try!(self.expect(&token::Colon));
2013 let e = try!(self.parse_expr());
2015 ident: spanned(lo, hi, i),
2016 span: mk_sp(lo, e.span.hi),
2021 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos,
2022 node: ExprKind, attrs: ThinAttributes) -> P<Expr> {
2024 id: ast::DUMMY_NODE_ID,
2026 span: mk_sp(lo, hi),
2031 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2032 ExprKind::Unary(unop, expr)
2035 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2036 ExprKind::Binary(binop, lhs, rhs)
2039 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2040 ExprKind::Call(f, args)
2043 fn mk_method_call(&mut self,
2044 ident: ast::SpannedIdent,
2048 ExprKind::MethodCall(ident, tps, args)
2051 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2052 ExprKind::Index(expr, idx)
2055 pub fn mk_range(&mut self,
2056 start: Option<P<Expr>>,
2057 end: Option<P<Expr>>)
2059 ExprKind::Range(start, end)
2062 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::ExprKind {
2063 ExprKind::Field(expr, ident)
2066 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2067 ExprKind::TupField(expr, idx)
2070 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2071 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2072 ExprKind::AssignOp(binop, lhs, rhs)
2075 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos,
2076 m: Mac_, attrs: ThinAttributes) -> P<Expr> {
2078 id: ast::DUMMY_NODE_ID,
2079 node: ExprKind::Mac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
2080 span: mk_sp(lo, hi),
2085 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinAttributes) -> P<Expr> {
2086 let span = &self.span;
2087 let lv_lit = P(codemap::Spanned {
2088 node: LitKind::Int(i as u64, ast::LitIntType::Unsigned(UintTy::U32)),
2093 id: ast::DUMMY_NODE_ID,
2094 node: ExprKind::Lit(lv_lit),
2100 fn expect_open_delim(&mut self) -> PResult<'a, token::DelimToken> {
2101 self.expected_tokens.push(TokenType::Token(token::Gt));
2103 token::OpenDelim(delim) => {
2107 _ => Err(self.fatal("expected open delimiter")),
2111 /// At the bottom (top?) of the precedence hierarchy,
2112 /// parse things like parenthesized exprs,
2113 /// macros, return, etc.
2115 /// NB: This does not parse outer attributes,
2116 /// and is private because it only works
2117 /// correctly if called from parse_dot_or_call_expr().
2118 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2119 maybe_whole_expr!(self);
2121 // Outer attributes are already parsed and will be
2122 // added to the return value after the fact.
2124 // Therefore, prevent sub-parser from parsing
2125 // attributes by giving them a empty "already parsed" list.
2126 let mut attrs = None;
2128 let lo = self.span.lo;
2129 let mut hi = self.span.hi;
2133 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2135 token::OpenDelim(token::Paren) => {
2138 let attrs = try!(self.parse_inner_attributes())
2142 // (e) is parenthesized e
2143 // (e,) is a tuple with only one field, e
2144 let mut es = vec![];
2145 let mut trailing_comma = false;
2146 while self.token != token::CloseDelim(token::Paren) {
2147 es.push(try!(self.parse_expr()));
2148 try!(self.commit_expr(&es.last().unwrap(), &[],
2149 &[token::Comma, token::CloseDelim(token::Paren)]));
2150 if self.check(&token::Comma) {
2151 trailing_comma = true;
2155 trailing_comma = false;
2161 hi = self.last_span.hi;
2162 return if es.len() == 1 && !trailing_comma {
2163 Ok(self.mk_expr(lo, hi, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs))
2165 Ok(self.mk_expr(lo, hi, ExprKind::Tup(es), attrs))
2168 token::OpenDelim(token::Brace) => {
2169 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2171 token::BinOp(token::Or) | token::OrOr => {
2172 let lo = self.span.lo;
2173 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2175 token::Ident(id @ ast::Ident {
2176 name: token::SELF_KEYWORD_NAME,
2178 }, token::Plain) => {
2180 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2181 ex = ExprKind::Path(None, path);
2182 hi = self.last_span.hi;
2184 token::OpenDelim(token::Bracket) => {
2187 let inner_attrs = try!(self.parse_inner_attributes())
2189 attrs.update(|attrs| attrs.append(inner_attrs));
2191 if self.check(&token::CloseDelim(token::Bracket)) {
2194 ex = ExprKind::Vec(Vec::new());
2197 let first_expr = try!(self.parse_expr());
2198 if self.check(&token::Semi) {
2199 // Repeating array syntax: [ 0; 512 ]
2201 let count = try!(self.parse_expr());
2202 try!(self.expect(&token::CloseDelim(token::Bracket)));
2203 ex = ExprKind::Repeat(first_expr, count);
2204 } else if self.check(&token::Comma) {
2205 // Vector with two or more elements.
2207 let remaining_exprs = try!(self.parse_seq_to_end(
2208 &token::CloseDelim(token::Bracket),
2209 seq_sep_trailing_allowed(token::Comma),
2210 |p| Ok(try!(p.parse_expr()))
2212 let mut exprs = vec!(first_expr);
2213 exprs.extend(remaining_exprs);
2214 ex = ExprKind::Vec(exprs);
2216 // Vector with one element.
2217 try!(self.expect(&token::CloseDelim(token::Bracket)));
2218 ex = ExprKind::Vec(vec!(first_expr));
2221 hi = self.last_span.hi;
2226 try!(self.parse_qualified_path(LifetimeAndTypesWithColons));
2228 return Ok(self.mk_expr(lo, hi, ExprKind::Path(Some(qself), path), attrs));
2230 if self.eat_keyword(keywords::Move) {
2231 let lo = self.last_span.lo;
2232 return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2234 if self.eat_keyword(keywords::If) {
2235 return self.parse_if_expr(attrs);
2237 if self.eat_keyword(keywords::For) {
2238 let lo = self.last_span.lo;
2239 return self.parse_for_expr(None, lo, attrs);
2241 if self.eat_keyword(keywords::While) {
2242 let lo = self.last_span.lo;
2243 return self.parse_while_expr(None, lo, attrs);
2245 if self.token.is_lifetime() {
2246 let lifetime = self.get_lifetime();
2247 let lo = self.span.lo;
2249 try!(self.expect(&token::Colon));
2250 if self.eat_keyword(keywords::While) {
2251 return self.parse_while_expr(Some(lifetime), lo, attrs)
2253 if self.eat_keyword(keywords::For) {
2254 return self.parse_for_expr(Some(lifetime), lo, attrs)
2256 if self.eat_keyword(keywords::Loop) {
2257 return self.parse_loop_expr(Some(lifetime), lo, attrs)
2259 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2261 if self.eat_keyword(keywords::Loop) {
2262 let lo = self.last_span.lo;
2263 return self.parse_loop_expr(None, lo, attrs);
2265 if self.eat_keyword(keywords::Continue) {
2266 let ex = if self.token.is_lifetime() {
2267 let ex = ExprKind::Again(Some(Spanned{
2268 node: self.get_lifetime(),
2274 ExprKind::Again(None)
2276 let hi = self.last_span.hi;
2277 return Ok(self.mk_expr(lo, hi, ex, attrs));
2279 if self.eat_keyword(keywords::Match) {
2280 return self.parse_match_expr(attrs);
2282 if self.eat_keyword(keywords::Unsafe) {
2283 return self.parse_block_expr(
2285 BlockCheckMode::Unsafe(ast::UserProvided),
2288 if self.eat_keyword(keywords::Return) {
2289 if self.token.can_begin_expr() {
2290 let e = try!(self.parse_expr());
2292 ex = ExprKind::Ret(Some(e));
2294 ex = ExprKind::Ret(None);
2296 } else if self.eat_keyword(keywords::Break) {
2297 if self.token.is_lifetime() {
2298 ex = ExprKind::Break(Some(Spanned {
2299 node: self.get_lifetime(),
2304 ex = ExprKind::Break(None);
2306 hi = self.last_span.hi;
2307 } else if self.token.is_keyword(keywords::Let) {
2308 // Catch this syntax error here, instead of in `check_strict_keywords`, so
2309 // that we can explicitly mention that let is not to be used as an expression
2310 let mut db = self.fatal("expected expression, found statement (`let`)");
2311 db.note("variable declaration using `let` is a statement");
2313 } else if self.check(&token::ModSep) ||
2314 self.token.is_ident() &&
2315 !self.check_keyword(keywords::True) &&
2316 !self.check_keyword(keywords::False) {
2318 try!(self.parse_path(LifetimeAndTypesWithColons));
2320 // `!`, as an operator, is prefix, so we know this isn't that
2321 if self.check(&token::Not) {
2322 // MACRO INVOCATION expression
2325 let delim = try!(self.expect_open_delim());
2326 let tts = try!(self.parse_seq_to_end(
2327 &token::CloseDelim(delim),
2329 |p| p.parse_token_tree()));
2330 let hi = self.last_span.hi;
2332 return Ok(self.mk_mac_expr(lo,
2334 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT },
2337 if self.check(&token::OpenDelim(token::Brace)) {
2338 // This is a struct literal, unless we're prohibited
2339 // from parsing struct literals here.
2340 let prohibited = self.restrictions.contains(
2341 Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2344 // It's a struct literal.
2346 let mut fields = Vec::new();
2347 let mut base = None;
2349 let attrs = attrs.append(
2350 try!(self.parse_inner_attributes())
2351 .into_thin_attrs());
2353 while self.token != token::CloseDelim(token::Brace) {
2354 if self.eat(&token::DotDot) {
2355 match self.parse_expr() {
2361 self.recover_stmt();
2367 match self.parse_field() {
2368 Ok(f) => fields.push(f),
2371 self.recover_stmt();
2376 match self.commit_expr(&fields.last().unwrap().expr,
2378 &[token::CloseDelim(token::Brace)]) {
2382 self.recover_stmt();
2389 try!(self.expect(&token::CloseDelim(token::Brace)));
2390 ex = ExprKind::Struct(pth, fields, base);
2391 return Ok(self.mk_expr(lo, hi, ex, attrs));
2396 ex = ExprKind::Path(None, pth);
2398 // other literal expression
2399 let lit = try!(self.parse_lit());
2401 ex = ExprKind::Lit(P(lit));
2406 return Ok(self.mk_expr(lo, hi, ex, attrs));
2409 fn parse_or_use_outer_attributes(&mut self,
2410 already_parsed_attrs: Option<ThinAttributes>)
2411 -> PResult<'a, ThinAttributes> {
2412 if let Some(attrs) = already_parsed_attrs {
2415 self.parse_outer_attributes().map(|a| a.into_thin_attrs())
2419 /// Parse a block or unsafe block
2420 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode,
2421 attrs: ThinAttributes)
2422 -> PResult<'a, P<Expr>> {
2424 let outer_attrs = attrs;
2425 try!(self.expect(&token::OpenDelim(token::Brace)));
2427 let inner_attrs = try!(self.parse_inner_attributes()).into_thin_attrs();
2428 let attrs = outer_attrs.append(inner_attrs);
2430 let blk = try!(self.parse_block_tail(lo, blk_mode));
2431 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprKind::Block(blk), attrs));
2434 /// parse a.b or a(13) or a[4] or just a
2435 pub fn parse_dot_or_call_expr(&mut self,
2436 already_parsed_attrs: Option<ThinAttributes>)
2437 -> PResult<'a, P<Expr>> {
2438 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2440 let b = self.parse_bottom_expr();
2441 let (span, b) = try!(self.interpolated_or_expr_span(b));
2442 self.parse_dot_or_call_expr_with(b, span.lo, attrs)
2445 pub fn parse_dot_or_call_expr_with(&mut self,
2448 attrs: ThinAttributes)
2449 -> PResult<'a, P<Expr>> {
2450 // Stitch the list of outer attributes onto the return value.
2451 // A little bit ugly, but the best way given the current code
2453 self.parse_dot_or_call_expr_with_(e0, lo)
2455 expr.map(|mut expr| {
2456 expr.attrs.update(|a| a.prepend(attrs));
2458 ExprKind::If(..) | ExprKind::IfLet(..) => {
2459 if !expr.attrs.as_attr_slice().is_empty() {
2460 // Just point to the first attribute in there...
2461 let span = expr.attrs.as_attr_slice()[0].span;
2464 "attributes are not yet allowed on `if` \
2475 // Assuming we have just parsed `.foo` (i.e., a dot and an ident), continue
2476 // parsing into an expression.
2477 fn parse_dot_suffix(&mut self,
2480 self_value: P<Expr>,
2482 -> PResult<'a, P<Expr>> {
2483 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2484 try!(self.expect_lt());
2485 try!(self.parse_generic_values_after_lt())
2487 (Vec::new(), Vec::new(), Vec::new())
2490 if !bindings.is_empty() {
2491 let last_span = self.last_span;
2492 self.span_err(last_span, "type bindings are only permitted on trait paths");
2495 Ok(match self.token {
2496 // expr.f() method call.
2497 token::OpenDelim(token::Paren) => {
2498 let mut es = try!(self.parse_unspanned_seq(
2499 &token::OpenDelim(token::Paren),
2500 &token::CloseDelim(token::Paren),
2501 seq_sep_trailing_allowed(token::Comma),
2502 |p| Ok(try!(p.parse_expr()))
2504 let hi = self.last_span.hi;
2506 es.insert(0, self_value);
2507 let id = spanned(ident_span.lo, ident_span.hi, ident);
2508 let nd = self.mk_method_call(id, tys, es);
2509 self.mk_expr(lo, hi, nd, None)
2513 if !tys.is_empty() {
2514 let last_span = self.last_span;
2515 self.span_err(last_span,
2516 "field expressions may not \
2517 have type parameters");
2520 let id = spanned(ident_span.lo, ident_span.hi, ident);
2521 let field = self.mk_field(self_value, id);
2522 self.mk_expr(lo, ident_span.hi, field, None)
2527 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: BytePos) -> PResult<'a, P<Expr>> {
2532 if self.eat(&token::Dot) {
2534 token::Ident(i, _) => {
2535 let dot_pos = self.last_span.hi;
2539 e = try!(self.parse_dot_suffix(i, mk_sp(dot_pos, hi), e, lo));
2541 token::Literal(token::Integer(n), suf) => {
2544 // A tuple index may not have a suffix
2545 self.expect_no_suffix(sp, "tuple index", suf);
2547 let dot = self.last_span.hi;
2551 let index = n.as_str().parse::<usize>().ok();
2554 let id = spanned(dot, hi, n);
2555 let field = self.mk_tup_field(e, id);
2556 e = self.mk_expr(lo, hi, field, None);
2559 let last_span = self.last_span;
2560 self.span_err(last_span, "invalid tuple or tuple struct index");
2564 token::Literal(token::Float(n), _suf) => {
2566 let last_span = self.last_span;
2567 let fstr = n.as_str();
2568 let mut err = self.diagnostic().struct_span_err(last_span,
2569 &format!("unexpected token: `{}`", n.as_str()));
2570 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2571 let float = match fstr.parse::<f64>().ok() {
2575 err.fileline_help(last_span,
2576 &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2577 float.trunc() as usize,
2578 format!(".{}", fstr.splitn(2, ".").last().unwrap())));
2584 // FIXME Could factor this out into non_fatal_unexpected or something.
2585 let actual = self.this_token_to_string();
2586 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2588 let dot_pos = self.last_span.hi;
2589 e = try!(self.parse_dot_suffix(special_idents::invalid,
2590 mk_sp(dot_pos, dot_pos),
2596 if self.expr_is_complete(&e) { break; }
2599 token::OpenDelim(token::Paren) => {
2600 let es = try!(self.parse_unspanned_seq(
2601 &token::OpenDelim(token::Paren),
2602 &token::CloseDelim(token::Paren),
2603 seq_sep_trailing_allowed(token::Comma),
2604 |p| Ok(try!(p.parse_expr()))
2606 hi = self.last_span.hi;
2608 let nd = self.mk_call(e, es);
2609 e = self.mk_expr(lo, hi, nd, None);
2613 // Could be either an index expression or a slicing expression.
2614 token::OpenDelim(token::Bracket) => {
2616 let ix = try!(self.parse_expr());
2618 try!(self.commit_expr_expecting(&ix, token::CloseDelim(token::Bracket)));
2619 let index = self.mk_index(e, ix);
2620 e = self.mk_expr(lo, hi, index, None)
2628 // Parse unquoted tokens after a `$` in a token tree
2629 fn parse_unquoted(&mut self) -> PResult<'a, TokenTree> {
2630 let mut sp = self.span;
2631 let (name, namep) = match self.token {
2635 if self.token == token::OpenDelim(token::Paren) {
2636 let Spanned { node: seq, span: seq_span } = try!(self.parse_seq(
2637 &token::OpenDelim(token::Paren),
2638 &token::CloseDelim(token::Paren),
2640 |p| p.parse_token_tree()
2642 let (sep, repeat) = try!(self.parse_sep_and_kleene_op());
2643 let name_num = macro_parser::count_names(&seq);
2644 return Ok(TokenTree::Sequence(mk_sp(sp.lo, seq_span.hi),
2645 Rc::new(SequenceRepetition {
2649 num_captures: name_num
2651 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2653 return Ok(TokenTree::Token(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar)));
2655 sp = mk_sp(sp.lo, self.span.hi);
2656 let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2657 let name = try!(self.parse_ident());
2661 token::SubstNt(name, namep) => {
2667 // continue by trying to parse the `:ident` after `$name`
2668 if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2669 !t.is_strict_keyword() &&
2670 !t.is_reserved_keyword()) {
2672 sp = mk_sp(sp.lo, self.span.hi);
2673 let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2674 let nt_kind = try!(self.parse_ident());
2675 Ok(TokenTree::Token(sp, MatchNt(name, nt_kind, namep, kindp)))
2677 Ok(TokenTree::Token(sp, SubstNt(name, namep)))
2681 pub fn check_unknown_macro_variable(&mut self) {
2682 if self.quote_depth == 0 {
2684 token::SubstNt(name, _) =>
2685 self.fatal(&format!("unknown macro variable `{}`", name)).emit(),
2691 /// Parse an optional separator followed by a Kleene-style
2692 /// repetition token (+ or *).
2693 pub fn parse_sep_and_kleene_op(&mut self)
2694 -> PResult<'a, (Option<token::Token>, ast::KleeneOp)> {
2695 fn parse_kleene_op<'a>(parser: &mut Parser<'a>) -> PResult<'a, Option<ast::KleeneOp>> {
2696 match parser.token {
2697 token::BinOp(token::Star) => {
2699 Ok(Some(ast::KleeneOp::ZeroOrMore))
2701 token::BinOp(token::Plus) => {
2703 Ok(Some(ast::KleeneOp::OneOrMore))
2709 match try!(parse_kleene_op(self)) {
2710 Some(kleene_op) => return Ok((None, kleene_op)),
2714 let separator = self.bump_and_get();
2715 match try!(parse_kleene_op(self)) {
2716 Some(zerok) => Ok((Some(separator), zerok)),
2717 None => return Err(self.fatal("expected `*` or `+`"))
2721 /// parse a single token tree from the input.
2722 pub fn parse_token_tree(&mut self) -> PResult<'a, TokenTree> {
2723 // FIXME #6994: currently, this is too eager. It
2724 // parses token trees but also identifies TokenType::Sequence's
2725 // and token::SubstNt's; it's too early to know yet
2726 // whether something will be a nonterminal or a seq
2728 maybe_whole!(deref self, NtTT);
2732 let mut err: DiagnosticBuilder<'a> =
2733 self.diagnostic().struct_span_err(self.span,
2734 "this file contains an un-closed delimiter");
2735 for sp in &self.open_braces {
2736 err.span_help(*sp, "did you mean to close this delimiter?");
2741 token::OpenDelim(delim) => {
2742 // The span for beginning of the delimited section
2743 let pre_span = self.span;
2745 // Parse the open delimiter.
2746 self.open_braces.push(self.span);
2747 let open_span = self.span;
2750 // Parse the token trees within the delimiters
2751 let tts = self.parse_seq_to_before_end(&token::CloseDelim(delim),
2753 |p| p.parse_token_tree());
2755 // Parse the close delimiter.
2756 let close_span = self.span;
2758 self.open_braces.pop().unwrap();
2760 // Expand to cover the entire delimited token tree
2761 let span = Span { hi: close_span.hi, ..pre_span };
2763 Ok(TokenTree::Delimited(span, Rc::new(Delimited {
2765 open_span: open_span,
2767 close_span: close_span,
2771 // invariants: the current token is not a left-delimiter,
2772 // not an EOF, and not the desired right-delimiter (if
2773 // it were, parse_seq_to_before_end would have prevented
2774 // reaching this point.
2775 maybe_whole!(deref self, NtTT);
2777 token::CloseDelim(_) => {
2778 let token_str = self.this_token_to_string();
2779 let mut err = self.diagnostic().struct_span_err(self.span,
2780 &format!("incorrect close delimiter: `{}`", token_str));
2781 // This is a conservative error: only report the last unclosed delimiter.
2782 // The previous unclosed delimiters could actually be closed! The parser
2783 // just hasn't gotten to them yet.
2784 if let Some(&sp) = self.open_braces.last() {
2785 err.span_note(sp, "unclosed delimiter");
2790 /* we ought to allow different depths of unquotation */
2791 token::Dollar | token::SubstNt(..) if self.quote_depth > 0 => {
2792 self.parse_unquoted()
2795 Ok(TokenTree::Token(self.span, self.bump_and_get()))
2802 // parse a stream of tokens into a list of TokenTree's,
2804 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2805 let mut tts = Vec::new();
2806 while self.token != token::Eof {
2807 tts.push(try!(self.parse_token_tree()));
2812 /// Parse a prefix-unary-operator expr
2813 pub fn parse_prefix_expr(&mut self,
2814 already_parsed_attrs: Option<ThinAttributes>)
2815 -> PResult<'a, P<Expr>> {
2816 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2817 let lo = self.span.lo;
2819 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2820 let ex = match self.token {
2823 let e = self.parse_prefix_expr(None);
2824 let (span, e) = try!(self.interpolated_or_expr_span(e));
2826 self.mk_unary(UnOp::Not, e)
2828 token::BinOp(token::Minus) => {
2830 let e = self.parse_prefix_expr(None);
2831 let (span, e) = try!(self.interpolated_or_expr_span(e));
2833 self.mk_unary(UnOp::Neg, e)
2835 token::BinOp(token::Star) => {
2837 let e = self.parse_prefix_expr(None);
2838 let (span, e) = try!(self.interpolated_or_expr_span(e));
2840 self.mk_unary(UnOp::Deref, e)
2842 token::BinOp(token::And) | token::AndAnd => {
2843 try!(self.expect_and());
2844 let m = try!(self.parse_mutability());
2845 let e = self.parse_prefix_expr(None);
2846 let (span, e) = try!(self.interpolated_or_expr_span(e));
2848 ExprKind::AddrOf(m, e)
2850 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2852 let place = try!(self.parse_expr_res(
2853 Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
2856 let blk = try!(self.parse_block());
2857 let span = blk.span;
2859 let blk_expr = self.mk_expr(span.lo, span.hi, ExprKind::Block(blk),
2861 ExprKind::InPlace(place, blk_expr)
2863 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2865 let e = self.parse_prefix_expr(None);
2866 let (span, e) = try!(self.interpolated_or_expr_span(e));
2870 _ => return self.parse_dot_or_call_expr(Some(attrs))
2872 return Ok(self.mk_expr(lo, hi, ex, attrs));
2875 /// Parse an associative expression
2877 /// This parses an expression accounting for associativity and precedence of the operators in
2879 pub fn parse_assoc_expr(&mut self,
2880 already_parsed_attrs: Option<ThinAttributes>)
2881 -> PResult<'a, P<Expr>> {
2882 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2885 /// Parse an associative expression with operators of at least `min_prec` precedence
2886 pub fn parse_assoc_expr_with(&mut self,
2889 -> PResult<'a, P<Expr>> {
2890 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2893 let attrs = match lhs {
2894 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2897 if self.token == token::DotDot {
2898 return self.parse_prefix_range_expr(attrs);
2900 try!(self.parse_prefix_expr(attrs))
2905 if self.expr_is_complete(&lhs) {
2906 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2909 self.expected_tokens.push(TokenType::Operator);
2910 while let Some(op) = AssocOp::from_token(&self.token) {
2912 let lhs_span = if self.last_token_interpolated {
2918 let cur_op_span = self.span;
2919 let restrictions = if op.is_assign_like() {
2920 self.restrictions & Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2924 if op.precedence() < min_prec {
2928 if op.is_comparison() {
2929 self.check_no_chained_comparison(&lhs, &op);
2932 if op == AssocOp::As {
2933 let rhs = try!(self.parse_ty());
2934 lhs = self.mk_expr(lhs_span.lo, rhs.span.hi,
2935 ExprKind::Cast(lhs, rhs), None);
2937 } else if op == AssocOp::Colon {
2938 let rhs = try!(self.parse_ty());
2939 lhs = self.mk_expr(lhs_span.lo, rhs.span.hi,
2940 ExprKind::Type(lhs, rhs), None);
2942 } else if op == AssocOp::DotDot {
2943 // If we didn’t have to handle `x..`, it would be pretty easy to generalise
2944 // it to the Fixity::None code.
2946 // We have 2 alternatives here: `x..y` and `x..` The other two variants are
2947 // handled with `parse_prefix_range_expr` call above.
2948 let rhs = if self.is_at_start_of_range_notation_rhs() {
2949 let rhs = self.parse_assoc_expr_with(op.precedence() + 1,
2950 LhsExpr::NotYetParsed);
2961 let (lhs_span, rhs_span) = (lhs_span, if let Some(ref x) = rhs {
2966 let r = self.mk_range(Some(lhs), rhs);
2967 lhs = self.mk_expr(lhs_span.lo, rhs_span.hi, r, None);
2971 let rhs = try!(match op.fixity() {
2972 Fixity::Right => self.with_res(
2973 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2975 this.parse_assoc_expr_with(op.precedence(),
2976 LhsExpr::NotYetParsed)
2978 Fixity::Left => self.with_res(
2979 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2981 this.parse_assoc_expr_with(op.precedence() + 1,
2982 LhsExpr::NotYetParsed)
2984 // We currently have no non-associative operators that are not handled above by
2985 // the special cases. The code is here only for future convenience.
2986 Fixity::None => self.with_res(
2987 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2989 this.parse_assoc_expr_with(op.precedence() + 1,
2990 LhsExpr::NotYetParsed)
2995 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2996 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2997 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2998 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2999 AssocOp::Greater | AssocOp::GreaterEqual => {
3000 let ast_op = op.to_ast_binop().unwrap();
3001 let (lhs_span, rhs_span) = (lhs_span, rhs.span);
3002 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
3003 self.mk_expr(lhs_span.lo, rhs_span.hi, binary, None)
3006 self.mk_expr(lhs_span.lo, rhs.span.hi, ExprKind::Assign(lhs, rhs), None),
3008 self.mk_expr(lhs_span.lo, rhs.span.hi, ExprKind::InPlace(lhs, rhs), None),
3009 AssocOp::AssignOp(k) => {
3011 token::Plus => BinOpKind::Add,
3012 token::Minus => BinOpKind::Sub,
3013 token::Star => BinOpKind::Mul,
3014 token::Slash => BinOpKind::Div,
3015 token::Percent => BinOpKind::Rem,
3016 token::Caret => BinOpKind::BitXor,
3017 token::And => BinOpKind::BitAnd,
3018 token::Or => BinOpKind::BitOr,
3019 token::Shl => BinOpKind::Shl,
3020 token::Shr => BinOpKind::Shr,
3022 let (lhs_span, rhs_span) = (lhs_span, rhs.span);
3023 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
3024 self.mk_expr(lhs_span.lo, rhs_span.hi, aopexpr, None)
3026 AssocOp::As | AssocOp::Colon | AssocOp::DotDot => {
3027 self.bug("As, Colon or DotDot branch reached")
3031 if op.fixity() == Fixity::None { break }
3036 /// Produce an error if comparison operators are chained (RFC #558).
3037 /// We only need to check lhs, not rhs, because all comparison ops
3038 /// have same precedence and are left-associative
3039 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3040 debug_assert!(outer_op.is_comparison());
3042 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3043 // respan to include both operators
3044 let op_span = mk_sp(op.span.lo, self.span.hi);
3045 let mut err = self.diagnostic().struct_span_err(op_span,
3046 "chained comparison operators require parentheses");
3047 if op.node == BinOpKind::Lt && *outer_op == AssocOp::Greater {
3048 err.fileline_help(op_span,
3049 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3057 /// Parse prefix-forms of range notation: `..expr` and `..`
3058 fn parse_prefix_range_expr(&mut self,
3059 already_parsed_attrs: Option<ThinAttributes>)
3060 -> PResult<'a, P<Expr>> {
3061 debug_assert!(self.token == token::DotDot);
3062 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
3063 let lo = self.span.lo;
3064 let mut hi = self.span.hi;
3066 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3067 // RHS must be parsed with more associativity than DotDot.
3068 let next_prec = AssocOp::from_token(&token::DotDot).unwrap().precedence() + 1;
3069 Some(try!(self.parse_assoc_expr_with(next_prec,
3070 LhsExpr::NotYetParsed)
3078 let r = self.mk_range(None, opt_end);
3079 Ok(self.mk_expr(lo, hi, r, attrs))
3082 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3083 if self.token.can_begin_expr() {
3084 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3085 if self.token == token::OpenDelim(token::Brace) {
3086 return !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL);
3094 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3095 pub fn parse_if_expr(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3096 if self.check_keyword(keywords::Let) {
3097 return self.parse_if_let_expr(attrs);
3099 let lo = self.last_span.lo;
3100 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3101 let thn = try!(self.parse_block());
3102 let mut els: Option<P<Expr>> = None;
3103 let mut hi = thn.span.hi;
3104 if self.eat_keyword(keywords::Else) {
3105 let elexpr = try!(self.parse_else_expr());
3106 hi = elexpr.span.hi;
3109 Ok(self.mk_expr(lo, hi, ExprKind::If(cond, thn, els), attrs))
3112 /// Parse an 'if let' expression ('if' token already eaten)
3113 pub fn parse_if_let_expr(&mut self, attrs: ThinAttributes)
3114 -> PResult<'a, P<Expr>> {
3115 let lo = self.last_span.lo;
3116 try!(self.expect_keyword(keywords::Let));
3117 let pat = try!(self.parse_pat());
3118 try!(self.expect(&token::Eq));
3119 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3120 let thn = try!(self.parse_block());
3121 let (hi, els) = if self.eat_keyword(keywords::Else) {
3122 let expr = try!(self.parse_else_expr());
3123 (expr.span.hi, Some(expr))
3127 Ok(self.mk_expr(lo, hi, ExprKind::IfLet(pat, expr, thn, els), attrs))
3131 pub fn parse_lambda_expr(&mut self, lo: BytePos,
3132 capture_clause: CaptureBy,
3133 attrs: ThinAttributes)
3134 -> PResult<'a, P<Expr>>
3136 let decl = try!(self.parse_fn_block_decl());
3137 let body = match decl.output {
3138 FunctionRetTy::Default(_) => {
3139 // If no explicit return type is given, parse any
3140 // expr and wrap it up in a dummy block:
3141 let body_expr = try!(self.parse_expr());
3143 id: ast::DUMMY_NODE_ID,
3145 span: body_expr.span,
3146 expr: Some(body_expr),
3147 rules: BlockCheckMode::Default,
3151 // If an explicit return type is given, require a
3152 // block to appear (RFC 968).
3153 try!(self.parse_block())
3160 ExprKind::Closure(capture_clause, decl, body), attrs))
3163 // `else` token already eaten
3164 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3165 if self.eat_keyword(keywords::If) {
3166 return self.parse_if_expr(None);
3168 let blk = try!(self.parse_block());
3169 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprKind::Block(blk), None));
3173 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3174 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>,
3176 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3177 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3179 let pat = try!(self.parse_pat());
3180 try!(self.expect_keyword(keywords::In));
3181 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3182 let (iattrs, loop_block) = try!(self.parse_inner_attrs_and_block());
3183 let attrs = attrs.append(iattrs.into_thin_attrs());
3185 let hi = self.last_span.hi;
3187 Ok(self.mk_expr(span_lo, hi,
3188 ExprKind::ForLoop(pat, expr, loop_block, opt_ident),
3192 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3193 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>,
3195 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3196 if self.token.is_keyword(keywords::Let) {
3197 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3199 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3200 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3201 let attrs = attrs.append(iattrs.into_thin_attrs());
3202 let hi = body.span.hi;
3203 return Ok(self.mk_expr(span_lo, hi, ExprKind::While(cond, body, opt_ident),
3207 /// Parse a 'while let' expression ('while' token already eaten)
3208 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>,
3210 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3211 try!(self.expect_keyword(keywords::Let));
3212 let pat = try!(self.parse_pat());
3213 try!(self.expect(&token::Eq));
3214 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3215 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3216 let attrs = attrs.append(iattrs.into_thin_attrs());
3217 let hi = body.span.hi;
3218 return Ok(self.mk_expr(span_lo, hi, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3221 // parse `loop {...}`, `loop` token already eaten
3222 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>,
3224 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3225 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3226 let attrs = attrs.append(iattrs.into_thin_attrs());
3227 let hi = body.span.hi;
3228 Ok(self.mk_expr(span_lo, hi, ExprKind::Loop(body, opt_ident), attrs))
3231 // `match` token already eaten
3232 fn parse_match_expr(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3233 let match_span = self.last_span;
3234 let lo = self.last_span.lo;
3235 let discriminant = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
3237 if let Err(mut e) = self.commit_expr_expecting(&discriminant,
3238 token::OpenDelim(token::Brace)) {
3239 if self.token == token::Token::Semi {
3240 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3244 let attrs = attrs.append(
3245 try!(self.parse_inner_attributes()).into_thin_attrs());
3246 let mut arms: Vec<Arm> = Vec::new();
3247 while self.token != token::CloseDelim(token::Brace) {
3248 match self.parse_arm() {
3249 Ok(arm) => arms.push(arm),
3251 // Recover by skipping to the end of the block.
3253 self.recover_stmt();
3254 let hi = self.span.hi;
3255 if self.token == token::CloseDelim(token::Brace) {
3258 return Ok(self.mk_expr(lo, hi, ExprKind::Match(discriminant, arms), attrs));
3262 let hi = self.span.hi;
3264 return Ok(self.mk_expr(lo, hi, ExprKind::Match(discriminant, arms), attrs));
3267 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3268 maybe_whole!(no_clone self, NtArm);
3270 let attrs = try!(self.parse_outer_attributes());
3271 let pats = try!(self.parse_pats());
3272 let mut guard = None;
3273 if self.eat_keyword(keywords::If) {
3274 guard = Some(try!(self.parse_expr()));
3276 try!(self.expect(&token::FatArrow));
3277 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR, None));
3280 !classify::expr_is_simple_block(&expr)
3281 && self.token != token::CloseDelim(token::Brace);
3284 try!(self.commit_expr(&expr, &[token::Comma], &[token::CloseDelim(token::Brace)]));
3286 self.eat(&token::Comma);
3297 /// Parse an expression
3298 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3299 self.parse_expr_res(Restrictions::empty(), None)
3302 /// Evaluate the closure with restrictions in place.
3304 /// After the closure is evaluated, restrictions are reset.
3305 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3306 where F: FnOnce(&mut Self) -> T
3308 let old = self.restrictions;
3309 self.restrictions = r;
3311 self.restrictions = old;
3316 /// Parse an expression, subject to the given restrictions
3317 pub fn parse_expr_res(&mut self, r: Restrictions,
3318 already_parsed_attrs: Option<ThinAttributes>)
3319 -> PResult<'a, P<Expr>> {
3320 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3323 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3324 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3325 if self.check(&token::Eq) {
3327 Ok(Some(try!(self.parse_expr())))
3333 /// Parse patterns, separated by '|' s
3334 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3335 let mut pats = Vec::new();
3337 pats.push(try!(self.parse_pat()));
3338 if self.check(&token::BinOp(token::Or)) { self.bump();}
3339 else { return Ok(pats); }
3343 fn parse_pat_tuple_elements(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3344 let mut fields = vec![];
3345 if !self.check(&token::CloseDelim(token::Paren)) {
3346 fields.push(try!(self.parse_pat()));
3347 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3348 while self.eat(&token::Comma) &&
3349 !self.check(&token::CloseDelim(token::Paren)) {
3350 fields.push(try!(self.parse_pat()));
3353 if fields.len() == 1 {
3354 try!(self.expect(&token::Comma));
3360 fn parse_pat_vec_elements(
3362 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3363 let mut before = Vec::new();
3364 let mut slice = None;
3365 let mut after = Vec::new();
3366 let mut first = true;
3367 let mut before_slice = true;
3369 while self.token != token::CloseDelim(token::Bracket) {
3373 try!(self.expect(&token::Comma));
3375 if self.token == token::CloseDelim(token::Bracket)
3376 && (before_slice || !after.is_empty()) {
3382 if self.check(&token::DotDot) {
3385 if self.check(&token::Comma) ||
3386 self.check(&token::CloseDelim(token::Bracket)) {
3387 slice = Some(P(ast::Pat {
3388 id: ast::DUMMY_NODE_ID,
3389 node: PatKind::Wild,
3392 before_slice = false;
3398 let subpat = try!(self.parse_pat());
3399 if before_slice && self.check(&token::DotDot) {
3401 slice = Some(subpat);
3402 before_slice = false;
3403 } else if before_slice {
3404 before.push(subpat);
3410 Ok((before, slice, after))
3413 /// Parse the fields of a struct-like pattern
3414 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>> , bool)> {
3415 let mut fields = Vec::new();
3416 let mut etc = false;
3417 let mut first = true;
3418 while self.token != token::CloseDelim(token::Brace) {
3422 try!(self.expect(&token::Comma));
3423 // accept trailing commas
3424 if self.check(&token::CloseDelim(token::Brace)) { break }
3427 let lo = self.span.lo;
3430 if self.check(&token::DotDot) {
3432 if self.token != token::CloseDelim(token::Brace) {
3433 let token_str = self.this_token_to_string();
3434 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3441 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3442 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3443 // Parsing a pattern of the form "fieldname: pat"
3444 let fieldname = try!(self.parse_ident());
3446 let pat = try!(self.parse_pat());
3448 (pat, fieldname, false)
3450 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3451 let is_box = self.eat_keyword(keywords::Box);
3452 let boxed_span_lo = self.span.lo;
3453 let is_ref = self.eat_keyword(keywords::Ref);
3454 let is_mut = self.eat_keyword(keywords::Mut);
3455 let fieldname = try!(self.parse_ident());
3456 hi = self.last_span.hi;
3458 let bind_type = match (is_ref, is_mut) {
3459 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3460 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3461 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3462 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3464 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3465 let fieldpat = P(ast::Pat{
3466 id: ast::DUMMY_NODE_ID,
3467 node: PatKind::Ident(bind_type, fieldpath, None),
3468 span: mk_sp(boxed_span_lo, hi),
3471 let subpat = if is_box {
3473 id: ast::DUMMY_NODE_ID,
3474 node: PatKind::Box(fieldpat),
3475 span: mk_sp(lo, hi),
3480 (subpat, fieldname, true)
3483 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3484 node: ast::FieldPat { ident: fieldname,
3486 is_shorthand: is_shorthand }});
3488 return Ok((fields, etc));
3491 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3492 if self.is_path_start() {
3493 let lo = self.span.lo;
3494 let (qself, path) = if self.eat_lt() {
3495 // Parse a qualified path
3497 try!(self.parse_qualified_path(NoTypesAllowed));
3500 // Parse an unqualified path
3501 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3503 let hi = self.last_span.hi;
3504 Ok(self.mk_expr(lo, hi, ExprKind::Path(qself, path), None))
3506 self.parse_pat_literal_maybe_minus()
3510 fn is_path_start(&self) -> bool {
3511 (self.token == token::Lt || self.token == token::ModSep
3512 || self.token.is_ident() || self.token.is_path())
3513 && !self.token.is_keyword(keywords::True) && !self.token.is_keyword(keywords::False)
3516 /// Parse a pattern.
3517 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3518 maybe_whole!(self, NtPat);
3520 let lo = self.span.lo;
3523 token::Underscore => {
3526 pat = PatKind::Wild;
3528 token::BinOp(token::And) | token::AndAnd => {
3529 // Parse &pat / &mut pat
3530 try!(self.expect_and());
3531 let mutbl = try!(self.parse_mutability());
3532 if let token::Lifetime(ident) = self.token {
3533 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3536 let subpat = try!(self.parse_pat());
3537 pat = PatKind::Ref(subpat, mutbl);
3539 token::OpenDelim(token::Paren) => {
3540 // Parse (pat,pat,pat,...) as tuple pattern
3542 let fields = try!(self.parse_pat_tuple_elements());
3543 try!(self.expect(&token::CloseDelim(token::Paren)));
3544 pat = PatKind::Tup(fields);
3546 token::OpenDelim(token::Bracket) => {
3547 // Parse [pat,pat,...] as slice pattern
3549 let (before, slice, after) = try!(self.parse_pat_vec_elements());
3550 try!(self.expect(&token::CloseDelim(token::Bracket)));
3551 pat = PatKind::Vec(before, slice, after);
3554 // At this point, token != _, &, &&, (, [
3555 if self.eat_keyword(keywords::Mut) {
3556 // Parse mut ident @ pat
3557 pat = try!(self.parse_pat_ident(BindingMode::ByValue(Mutability::Mutable)));
3558 } else if self.eat_keyword(keywords::Ref) {
3559 // Parse ref ident @ pat / ref mut ident @ pat
3560 let mutbl = try!(self.parse_mutability());
3561 pat = try!(self.parse_pat_ident(BindingMode::ByRef(mutbl)));
3562 } else if self.eat_keyword(keywords::Box) {
3564 let subpat = try!(self.parse_pat());
3565 pat = PatKind::Box(subpat);
3566 } else if self.is_path_start() {
3567 // Parse pattern starting with a path
3568 if self.token.is_plain_ident() && self.look_ahead(1, |t| *t != token::DotDotDot &&
3569 *t != token::OpenDelim(token::Brace) &&
3570 *t != token::OpenDelim(token::Paren) &&
3571 // Contrary to its definition, a plain ident can be followed by :: in macros
3572 *t != token::ModSep) {
3573 // Plain idents have some extra abilities here compared to general paths
3574 if self.look_ahead(1, |t| *t == token::Not) {
3575 // Parse macro invocation
3576 let ident = try!(self.parse_ident());
3577 let ident_span = self.last_span;
3578 let path = ident_to_path(ident_span, ident);
3580 let delim = try!(self.expect_open_delim());
3581 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
3582 seq_sep_none(), |p| p.parse_token_tree()));
3583 let mac = Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT };
3584 pat = PatKind::Mac(codemap::Spanned {node: mac,
3585 span: mk_sp(lo, self.last_span.hi)});
3587 // Parse ident @ pat
3588 // This can give false positives and parse nullary enums,
3589 // they are dealt with later in resolve
3590 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3591 pat = try!(self.parse_pat_ident(binding_mode));
3594 let (qself, path) = if self.eat_lt() {
3595 // Parse a qualified path
3597 try!(self.parse_qualified_path(NoTypesAllowed));
3600 // Parse an unqualified path
3601 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3604 token::DotDotDot => {
3606 let hi = self.last_span.hi;
3607 let begin = self.mk_expr(lo, hi, ExprKind::Path(qself, path), None);
3609 let end = try!(self.parse_pat_range_end());
3610 pat = PatKind::Range(begin, end);
3612 token::OpenDelim(token::Brace) => {
3613 if qself.is_some() {
3614 return Err(self.fatal("unexpected `{` after qualified path"));
3616 // Parse struct pattern
3618 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3620 self.recover_stmt();
3624 pat = PatKind::Struct(path, fields, etc);
3626 token::OpenDelim(token::Paren) => {
3627 if qself.is_some() {
3628 return Err(self.fatal("unexpected `(` after qualified path"));
3630 // Parse tuple struct or enum pattern
3631 if self.look_ahead(1, |t| *t == token::DotDot) {
3632 // This is a "top constructor only" pat
3635 try!(self.expect(&token::CloseDelim(token::Paren)));
3636 pat = PatKind::TupleStruct(path, None);
3638 let args = try!(self.parse_enum_variant_seq(
3639 &token::OpenDelim(token::Paren),
3640 &token::CloseDelim(token::Paren),
3641 seq_sep_trailing_allowed(token::Comma),
3642 |p| p.parse_pat()));
3643 pat = PatKind::TupleStruct(path, Some(args));
3648 // Parse qualified path
3649 Some(qself) => PatKind::QPath(qself, path),
3650 // Parse nullary enum
3651 None => PatKind::Path(path)
3657 // Try to parse everything else as literal with optional minus
3658 let begin = try!(self.parse_pat_literal_maybe_minus());
3659 if self.eat(&token::DotDotDot) {
3660 let end = try!(self.parse_pat_range_end());
3661 pat = PatKind::Range(begin, end);
3663 pat = PatKind::Lit(begin);
3669 let hi = self.last_span.hi;
3671 id: ast::DUMMY_NODE_ID,
3673 span: mk_sp(lo, hi),
3677 /// Parse ident or ident @ pat
3678 /// used by the copy foo and ref foo patterns to give a good
3679 /// error message when parsing mistakes like ref foo(a,b)
3680 fn parse_pat_ident(&mut self,
3681 binding_mode: ast::BindingMode)
3682 -> PResult<'a, PatKind> {
3683 if !self.token.is_plain_ident() {
3684 let span = self.span;
3685 let tok_str = self.this_token_to_string();
3686 return Err(self.span_fatal(span,
3687 &format!("expected identifier, found `{}`", tok_str)))
3689 let ident = try!(self.parse_ident());
3690 let last_span = self.last_span;
3691 let name = codemap::Spanned{span: last_span, node: ident};
3692 let sub = if self.eat(&token::At) {
3693 Some(try!(self.parse_pat()))
3698 // just to be friendly, if they write something like
3700 // we end up here with ( as the current token. This shortly
3701 // leads to a parse error. Note that if there is no explicit
3702 // binding mode then we do not end up here, because the lookahead
3703 // will direct us over to parse_enum_variant()
3704 if self.token == token::OpenDelim(token::Paren) {
3705 let last_span = self.last_span;
3706 return Err(self.span_fatal(
3708 "expected identifier, found enum pattern"))
3711 Ok(PatKind::Ident(binding_mode, name, sub))
3714 /// Parse a local variable declaration
3715 fn parse_local(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Local>> {
3716 let lo = self.span.lo;
3717 let pat = try!(self.parse_pat());
3720 if self.eat(&token::Colon) {
3721 ty = Some(try!(self.parse_ty_sum()));
3723 let init = try!(self.parse_initializer());
3728 id: ast::DUMMY_NODE_ID,
3729 span: mk_sp(lo, self.last_span.hi),
3734 /// Parse a "let" stmt
3735 fn parse_let(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Decl>> {
3736 let lo = self.span.lo;
3737 let local = try!(self.parse_local(attrs));
3738 Ok(P(spanned(lo, self.last_span.hi, DeclKind::Local(local))))
3741 /// Parse a structure field
3742 fn parse_name_and_ty(&mut self, pr: Visibility,
3743 attrs: Vec<Attribute> ) -> PResult<'a, StructField> {
3745 Visibility::Inherited => self.span.lo,
3746 Visibility::Public => self.last_span.lo,
3748 if !self.token.is_plain_ident() {
3749 return Err(self.fatal("expected ident"));
3751 let name = try!(self.parse_ident());
3752 try!(self.expect(&token::Colon));
3753 let ty = try!(self.parse_ty_sum());
3754 Ok(spanned(lo, self.last_span.hi, ast::StructField_ {
3755 kind: NamedField(name, pr),
3756 id: ast::DUMMY_NODE_ID,
3762 /// Emit an expected item after attributes error.
3763 fn expected_item_err(&self, attrs: &[Attribute]) {
3764 let message = match attrs.last() {
3765 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3766 "expected item after doc comment"
3768 _ => "expected item after attributes",
3771 self.span_err(self.last_span, message);
3774 /// Parse a statement. may include decl.
3775 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3776 Ok(self.parse_stmt_())
3779 // Eat tokens until we can be relatively sure we reached the end of the
3780 // statement. This is something of a best-effort heuristic.
3782 // We terminate when we find an unmatched `}` (without consuming it).
3783 fn recover_stmt(&mut self) {
3784 self.recover_stmt_(SemiColonMode::Ignore)
3786 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
3787 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
3788 // approximate - it can mean we break too early due to macros, but that
3789 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
3790 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode) {
3791 let mut brace_depth = 0;
3792 let mut bracket_depth = 0;
3795 token::OpenDelim(token::DelimToken::Brace) => {
3799 token::OpenDelim(token::DelimToken::Bracket) => {
3803 token::CloseDelim(token::DelimToken::Brace) => {
3804 if brace_depth == 0 {
3810 token::CloseDelim(token::DelimToken::Bracket) => {
3812 if bracket_depth < 0 {
3817 token::Eof => return,
3820 if break_on_semi == SemiColonMode::Break &&
3822 bracket_depth == 0 {
3833 fn parse_stmt_(&mut self) -> Option<Stmt> {
3834 self.parse_stmt_without_recovery().unwrap_or_else(|mut e| {
3836 self.recover_stmt_(SemiColonMode::Break);
3841 fn parse_stmt_without_recovery(&mut self) -> PResult<'a, Option<Stmt>> {
3842 maybe_whole!(Some deref self, NtStmt);
3844 let attrs = try!(self.parse_outer_attributes());
3845 let lo = self.span.lo;
3847 Ok(Some(if self.check_keyword(keywords::Let) {
3848 try!(self.expect_keyword(keywords::Let));
3849 let decl = try!(self.parse_let(attrs.into_thin_attrs()));
3850 let hi = decl.span.hi;
3851 let stmt = StmtKind::Decl(decl, ast::DUMMY_NODE_ID);
3852 spanned(lo, hi, stmt)
3853 } else if self.token.is_ident()
3854 && !self.token.is_any_keyword()
3855 && self.look_ahead(1, |t| *t == token::Not) {
3856 // it's a macro invocation:
3858 // Potential trouble: if we allow macros with paths instead of
3859 // idents, we'd need to look ahead past the whole path here...
3860 let pth = try!(self.parse_path(NoTypesAllowed));
3863 let id = match self.token {
3864 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3865 _ => try!(self.parse_ident()),
3868 // check that we're pointing at delimiters (need to check
3869 // again after the `if`, because of `parse_ident`
3870 // consuming more tokens).
3871 let delim = match self.token {
3872 token::OpenDelim(delim) => delim,
3874 // we only expect an ident if we didn't parse one
3876 let ident_str = if id.name == token::special_idents::invalid.name {
3881 let tok_str = self.this_token_to_string();
3882 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3888 let tts = try!(self.parse_unspanned_seq(
3889 &token::OpenDelim(delim),
3890 &token::CloseDelim(delim),
3892 |p| p.parse_token_tree()
3894 let hi = self.last_span.hi;
3896 let style = if delim == token::Brace {
3897 MacStmtStyle::Braces
3899 MacStmtStyle::NoBraces
3902 if id.name == token::special_idents::invalid.name {
3903 let mac = P(spanned(lo, hi, Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT }));
3904 let stmt = StmtKind::Mac(mac, style, attrs.into_thin_attrs());
3905 spanned(lo, hi, stmt)
3907 // if it has a special ident, it's definitely an item
3909 // Require a semicolon or braces.
3910 if style != MacStmtStyle::Braces {
3911 if !self.eat(&token::Semi) {
3912 let last_span = self.last_span;
3913 self.span_err(last_span,
3914 "macros that expand to items must \
3915 either be surrounded with braces or \
3916 followed by a semicolon");
3919 spanned(lo, hi, StmtKind::Decl(
3920 P(spanned(lo, hi, DeclKind::Item(
3922 lo, hi, id /*id is good here*/,
3923 ItemKind::Mac(spanned(lo, hi,
3924 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3925 Visibility::Inherited, attrs)))),
3926 ast::DUMMY_NODE_ID))
3929 // FIXME: Bad copy of attrs
3930 let restrictions = self.restrictions | Restrictions::NO_NONINLINE_MOD;
3931 match try!(self.with_res(restrictions,
3932 |this| this.parse_item_(attrs.clone(), false, true))) {
3935 let decl = P(spanned(lo, hi, DeclKind::Item(i)));
3936 spanned(lo, hi, StmtKind::Decl(decl, ast::DUMMY_NODE_ID))
3939 let unused_attrs = |attrs: &[_], s: &mut Self| {
3940 if attrs.len() > 0 {
3942 "expected statement after outer attribute");
3946 // Do not attempt to parse an expression if we're done here.
3947 if self.token == token::Semi {
3948 unused_attrs(&attrs, self);
3953 if self.token == token::CloseDelim(token::Brace) {
3954 unused_attrs(&attrs, self);
3958 // Remainder are line-expr stmts.
3959 let e = try!(self.parse_expr_res(
3960 Restrictions::RESTRICTION_STMT_EXPR, Some(attrs.into_thin_attrs())));
3962 let stmt = StmtKind::Expr(e, ast::DUMMY_NODE_ID);
3963 spanned(lo, hi, stmt)
3969 /// Is this expression a successfully-parsed statement?
3970 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3971 self.restrictions.contains(Restrictions::RESTRICTION_STMT_EXPR) &&
3972 !classify::expr_requires_semi_to_be_stmt(e)
3975 /// Parse a block. No inner attrs are allowed.
3976 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
3977 maybe_whole!(no_clone self, NtBlock);
3979 let lo = self.span.lo;
3981 if !self.eat(&token::OpenDelim(token::Brace)) {
3983 let tok = self.this_token_to_string();
3984 return Err(self.span_fatal_help(sp,
3985 &format!("expected `{{`, found `{}`", tok),
3986 "place this code inside a block"));
3989 self.parse_block_tail(lo, BlockCheckMode::Default)
3992 /// Parse a block. Inner attrs are allowed.
3993 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
3994 maybe_whole!(pair_empty self, NtBlock);
3996 let lo = self.span.lo;
3997 try!(self.expect(&token::OpenDelim(token::Brace)));
3998 Ok((try!(self.parse_inner_attributes()),
3999 try!(self.parse_block_tail(lo, BlockCheckMode::Default))))
4002 /// Parse the rest of a block expression or function body
4003 /// Precondition: already parsed the '{'.
4004 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4005 let mut stmts = vec![];
4006 let mut expr = None;
4008 while !self.eat(&token::CloseDelim(token::Brace)) {
4009 let Spanned {node, span} = if let Some(s) = self.parse_stmt_() {
4012 // Found only `;` or `}`.
4016 StmtKind::Expr(e, _) => {
4017 try!(self.handle_expression_like_statement(e, span, &mut stmts, &mut expr));
4019 StmtKind::Mac(mac, MacStmtStyle::NoBraces, attrs) => {
4020 // statement macro without braces; might be an
4021 // expr depending on whether a semicolon follows
4024 stmts.push(Spanned {
4025 node: StmtKind::Mac(mac, MacStmtStyle::Semicolon, attrs),
4026 span: mk_sp(span.lo, self.span.hi),
4031 let e = self.mk_mac_expr(span.lo, span.hi,
4032 mac.and_then(|m| m.node),
4035 let e = try!(self.parse_dot_or_call_expr_with(e, lo, attrs));
4036 let e = try!(self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e)));
4037 try!(self.handle_expression_like_statement(
4045 StmtKind::Mac(m, style, attrs) => {
4046 // statement macro; might be an expr
4049 stmts.push(Spanned {
4050 node: StmtKind::Mac(m, MacStmtStyle::Semicolon, attrs),
4051 span: mk_sp(span.lo, self.span.hi),
4055 token::CloseDelim(token::Brace) => {
4056 // if a block ends in `m!(arg)` without
4057 // a `;`, it must be an expr
4058 expr = Some(self.mk_mac_expr(span.lo, span.hi,
4059 m.and_then(|x| x.node),
4063 stmts.push(Spanned {
4064 node: StmtKind::Mac(m, style, attrs),
4070 _ => { // all other kinds of statements:
4071 let mut hi = span.hi;
4072 if classify::stmt_ends_with_semi(&node) {
4073 try!(self.commit_stmt_expecting(token::Semi));
4074 hi = self.last_span.hi;
4077 stmts.push(Spanned {
4079 span: mk_sp(span.lo, hi)
4088 id: ast::DUMMY_NODE_ID,
4090 span: mk_sp(lo, self.last_span.hi),
4094 fn handle_expression_like_statement(&mut self,
4097 stmts: &mut Vec<Stmt>,
4098 last_block_expr: &mut Option<P<Expr>>)
4099 -> PResult<'a, ()> {
4100 // expression without semicolon
4101 if classify::expr_requires_semi_to_be_stmt(&e) {
4102 // Just check for errors and recover; do not eat semicolon yet.
4104 self.commit_stmt(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4107 self.recover_stmt();
4114 let span_with_semi = Span {
4116 hi: self.last_span.hi,
4117 expn_id: span.expn_id,
4119 stmts.push(Spanned {
4120 node: StmtKind::Semi(e, ast::DUMMY_NODE_ID),
4121 span: span_with_semi,
4124 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
4126 stmts.push(Spanned {
4127 node: StmtKind::Expr(e, ast::DUMMY_NODE_ID),
4135 // Parses a sequence of bounds if a `:` is found,
4136 // otherwise returns empty list.
4137 fn parse_colon_then_ty_param_bounds(&mut self,
4138 mode: BoundParsingMode)
4139 -> PResult<'a, TyParamBounds>
4141 if !self.eat(&token::Colon) {
4144 self.parse_ty_param_bounds(mode)
4148 // matches bounds = ( boundseq )?
4149 // where boundseq = ( polybound + boundseq ) | polybound
4150 // and polybound = ( 'for' '<' 'region '>' )? bound
4151 // and bound = 'region | trait_ref
4152 fn parse_ty_param_bounds(&mut self,
4153 mode: BoundParsingMode)
4154 -> PResult<'a, TyParamBounds>
4156 let mut result = vec!();
4158 let question_span = self.span;
4159 let ate_question = self.eat(&token::Question);
4161 token::Lifetime(lifetime) => {
4163 self.span_err(question_span,
4164 "`?` may only modify trait bounds, not lifetime bounds");
4166 result.push(RegionTyParamBound(ast::Lifetime {
4167 id: ast::DUMMY_NODE_ID,
4173 token::ModSep | token::Ident(..) => {
4174 let poly_trait_ref = try!(self.parse_poly_trait_ref());
4175 let modifier = if ate_question {
4176 if mode == BoundParsingMode::Modified {
4177 TraitBoundModifier::Maybe
4179 self.span_err(question_span,
4181 TraitBoundModifier::None
4184 TraitBoundModifier::None
4186 result.push(TraitTyParamBound(poly_trait_ref, modifier))
4191 if !self.eat(&token::BinOp(token::Plus)) {
4196 return Ok(P::from_vec(result));
4199 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4200 fn parse_ty_param(&mut self) -> PResult<'a, TyParam> {
4201 let span = self.span;
4202 let ident = try!(self.parse_ident());
4204 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified));
4206 let default = if self.check(&token::Eq) {
4208 Some(try!(self.parse_ty_sum()))
4215 id: ast::DUMMY_NODE_ID,
4222 /// Parse a set of optional generic type parameter declarations. Where
4223 /// clauses are not parsed here, and must be added later via
4224 /// `parse_where_clause()`.
4226 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4227 /// | ( < lifetimes , typaramseq ( , )? > )
4228 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4229 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4230 maybe_whole!(self, NtGenerics);
4232 if self.eat(&token::Lt) {
4233 let lifetime_defs = try!(self.parse_lifetime_defs());
4234 let mut seen_default = false;
4235 let ty_params = try!(self.parse_seq_to_gt(Some(token::Comma), |p| {
4236 try!(p.forbid_lifetime());
4237 let ty_param = try!(p.parse_ty_param());
4238 if ty_param.default.is_some() {
4239 seen_default = true;
4240 } else if seen_default {
4241 let last_span = p.last_span;
4242 p.span_err(last_span,
4243 "type parameters with a default must be trailing");
4248 lifetimes: lifetime_defs,
4249 ty_params: ty_params,
4250 where_clause: WhereClause {
4251 id: ast::DUMMY_NODE_ID,
4252 predicates: Vec::new(),
4256 Ok(ast::Generics::default())
4260 fn parse_generic_values_after_lt(&mut self) -> PResult<'a, (Vec<ast::Lifetime>,
4262 Vec<TypeBinding>)> {
4263 let span_lo = self.span.lo;
4264 let lifetimes = try!(self.parse_lifetimes(token::Comma));
4266 let missing_comma = !lifetimes.is_empty() &&
4267 !self.token.is_like_gt() &&
4269 .as_ref().map_or(true,
4270 |x| &**x != &token::Comma);
4274 let msg = format!("expected `,` or `>` after lifetime \
4276 self.this_token_to_string());
4277 let mut err = self.diagnostic().struct_span_err(self.span, &msg);
4279 let span_hi = self.span.hi;
4280 let span_hi = match self.parse_ty() {
4281 Ok(..) => self.span.hi,
4282 Err(ref mut err) => {
4288 let msg = format!("did you mean a single argument type &'a Type, \
4289 or did you mean the comma-separated arguments \
4291 err.span_note(mk_sp(span_lo, span_hi), &msg);
4295 // First parse types.
4296 let (types, returned) = try!(self.parse_seq_to_gt_or_return(
4299 try!(p.forbid_lifetime());
4300 if p.look_ahead(1, |t| t == &token::Eq) {
4303 Ok(Some(try!(p.parse_ty_sum())))
4308 // If we found the `>`, don't continue.
4310 return Ok((lifetimes, types.into_vec(), Vec::new()));
4313 // Then parse type bindings.
4314 let bindings = try!(self.parse_seq_to_gt(
4317 try!(p.forbid_lifetime());
4319 let ident = try!(p.parse_ident());
4320 let found_eq = p.eat(&token::Eq);
4323 p.span_warn(span, "whoops, no =?");
4325 let ty = try!(p.parse_ty());
4326 let hi = ty.span.hi;
4327 let span = mk_sp(lo, hi);
4328 return Ok(TypeBinding{id: ast::DUMMY_NODE_ID,
4335 Ok((lifetimes, types.into_vec(), bindings.into_vec()))
4338 fn forbid_lifetime(&mut self) -> PResult<'a, ()> {
4339 if self.token.is_lifetime() {
4340 let span = self.span;
4341 return Err(self.diagnostic().struct_span_err(span, "lifetime parameters must be \
4342 declared prior to type parameters"))
4347 /// Parses an optional `where` clause and places it in `generics`.
4350 /// where T : Trait<U, V> + 'b, 'a : 'b
4352 pub fn parse_where_clause(&mut self) -> PResult<'a, ast::WhereClause> {
4353 maybe_whole!(self, NtWhereClause);
4355 let mut where_clause = WhereClause {
4356 id: ast::DUMMY_NODE_ID,
4357 predicates: Vec::new(),
4360 if !self.eat_keyword(keywords::Where) {
4361 return Ok(where_clause);
4364 let mut parsed_something = false;
4366 let lo = self.span.lo;
4368 token::OpenDelim(token::Brace) => {
4372 token::Lifetime(..) => {
4373 let bounded_lifetime =
4374 try!(self.parse_lifetime());
4376 self.eat(&token::Colon);
4379 try!(self.parse_lifetimes(token::BinOp(token::Plus)));
4381 let hi = self.last_span.hi;
4382 let span = mk_sp(lo, hi);
4384 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4385 ast::WhereRegionPredicate {
4387 lifetime: bounded_lifetime,
4392 parsed_something = true;
4396 let bound_lifetimes = if self.eat_keyword(keywords::For) {
4397 // Higher ranked constraint.
4398 try!(self.expect(&token::Lt));
4399 let lifetime_defs = try!(self.parse_lifetime_defs());
4400 try!(self.expect_gt());
4406 let bounded_ty = try!(self.parse_ty());
4408 if self.eat(&token::Colon) {
4409 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
4410 let hi = self.last_span.hi;
4411 let span = mk_sp(lo, hi);
4413 if bounds.is_empty() {
4415 "each predicate in a `where` clause must have \
4416 at least one bound in it");
4419 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4420 ast::WhereBoundPredicate {
4422 bound_lifetimes: bound_lifetimes,
4423 bounded_ty: bounded_ty,
4427 parsed_something = true;
4428 } else if self.eat(&token::Eq) {
4429 // let ty = try!(self.parse_ty());
4430 let hi = self.last_span.hi;
4431 let span = mk_sp(lo, hi);
4432 // where_clause.predicates.push(
4433 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4434 // id: ast::DUMMY_NODE_ID,
4436 // path: panic!("NYI"), //bounded_ty,
4439 // parsed_something = true;
4442 "equality constraints are not yet supported \
4443 in where clauses (#20041)");
4445 let last_span = self.last_span;
4446 self.span_err(last_span,
4447 "unexpected token in `where` clause");
4452 if !self.eat(&token::Comma) {
4457 if !parsed_something {
4458 let last_span = self.last_span;
4459 self.span_err(last_span,
4460 "a `where` clause must have at least one predicate \
4467 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4468 -> PResult<'a, (Vec<Arg> , bool)> {
4470 let mut variadic = false;
4471 let args: Vec<Option<Arg>> =
4472 try!(self.parse_unspanned_seq(
4473 &token::OpenDelim(token::Paren),
4474 &token::CloseDelim(token::Paren),
4475 seq_sep_trailing_allowed(token::Comma),
4477 if p.token == token::DotDotDot {
4480 if p.token != token::CloseDelim(token::Paren) {
4483 "`...` must be last in argument list for variadic function");
4488 "only foreign functions are allowed to be variadic");
4493 match p.parse_arg_general(named_args) {
4494 Ok(arg) => Ok(Some(arg)),
4497 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4505 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4507 if variadic && args.is_empty() {
4509 "variadic function must be declared with at least one named argument");
4512 Ok((args, variadic))
4515 /// Parse the argument list and result type of a function declaration
4516 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4518 let (args, variadic) = try!(self.parse_fn_args(true, allow_variadic));
4519 let ret_ty = try!(self.parse_ret_ty());
4528 fn is_self_ident(&mut self) -> bool {
4530 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4535 fn expect_self_ident(&mut self) -> PResult<'a, ast::Ident> {
4537 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4542 let token_str = self.this_token_to_string();
4543 return Err(self.fatal(&format!("expected `self`, found `{}`",
4549 fn is_self_type_ident(&mut self) -> bool {
4551 token::Ident(id, token::Plain) => id.name == special_idents::type_self.name,
4556 fn expect_self_type_ident(&mut self) -> PResult<'a, ast::Ident> {
4558 token::Ident(id, token::Plain) if id.name == special_idents::type_self.name => {
4563 let token_str = self.this_token_to_string();
4564 Err(self.fatal(&format!("expected `Self`, found `{}`",
4570 /// Parse the argument list and result type of a function
4571 /// that may have a self type.
4572 fn parse_fn_decl_with_self<F>(&mut self,
4573 parse_arg_fn: F) -> PResult<'a, (ExplicitSelf, P<FnDecl>)> where
4574 F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4576 fn maybe_parse_borrowed_explicit_self<'b>(this: &mut Parser<'b>)
4577 -> PResult<'b, ast::SelfKind> {
4578 // The following things are possible to see here:
4583 // fn(&'lt mut self)
4585 // We already know that the current token is `&`.
4587 if this.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4589 Ok(SelfKind::Region(None, Mutability::Immutable, try!(this.expect_self_ident())))
4590 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4591 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4593 let mutability = try!(this.parse_mutability());
4594 Ok(SelfKind::Region(None, mutability, try!(this.expect_self_ident())))
4595 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4596 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4598 let lifetime = try!(this.parse_lifetime());
4599 let ident = try!(this.expect_self_ident());
4600 Ok(SelfKind::Region(Some(lifetime), Mutability::Immutable, ident))
4601 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4602 this.look_ahead(2, |t| t.is_mutability()) &&
4603 this.look_ahead(3, |t| t.is_keyword(keywords::SelfValue)) {
4605 let lifetime = try!(this.parse_lifetime());
4606 let mutability = try!(this.parse_mutability());
4607 Ok(SelfKind::Region(Some(lifetime), mutability, try!(this.expect_self_ident())))
4609 Ok(SelfKind::Static)
4613 try!(self.expect(&token::OpenDelim(token::Paren)));
4615 // A bit of complexity and lookahead is needed here in order to be
4616 // backwards compatible.
4617 let lo = self.span.lo;
4618 let mut self_ident_lo = self.span.lo;
4619 let mut self_ident_hi = self.span.hi;
4621 let mut mutbl_self = Mutability::Immutable;
4622 let explicit_self = match self.token {
4623 token::BinOp(token::And) => {
4624 let eself = try!(maybe_parse_borrowed_explicit_self(self));
4625 self_ident_lo = self.last_span.lo;
4626 self_ident_hi = self.last_span.hi;
4629 token::BinOp(token::Star) => {
4630 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4631 // emitting cryptic "unexpected token" errors.
4633 let _mutability = if self.token.is_mutability() {
4634 try!(self.parse_mutability())
4636 Mutability::Immutable
4638 if self.is_self_ident() {
4639 let span = self.span;
4640 self.span_err(span, "cannot pass self by raw pointer");
4643 // error case, making bogus self ident:
4644 SelfKind::Value(special_idents::self_)
4646 token::Ident(..) => {
4647 if self.is_self_ident() {
4648 let self_ident = try!(self.expect_self_ident());
4650 // Determine whether this is the fully explicit form, `self:
4652 if self.eat(&token::Colon) {
4653 SelfKind::Explicit(try!(self.parse_ty_sum()), self_ident)
4655 SelfKind::Value(self_ident)
4657 } else if self.token.is_mutability() &&
4658 self.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4659 mutbl_self = try!(self.parse_mutability());
4660 let self_ident = try!(self.expect_self_ident());
4662 // Determine whether this is the fully explicit form,
4664 if self.eat(&token::Colon) {
4665 SelfKind::Explicit(try!(self.parse_ty_sum()), self_ident)
4667 SelfKind::Value(self_ident)
4673 _ => SelfKind::Static,
4676 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4678 // shared fall-through for the three cases below. borrowing prevents simply
4679 // writing this as a closure
4680 macro_rules! parse_remaining_arguments {
4683 // If we parsed a self type, expect a comma before the argument list.
4687 let sep = seq_sep_trailing_allowed(token::Comma);
4688 let mut fn_inputs = self.parse_seq_to_before_end(
4689 &token::CloseDelim(token::Paren),
4693 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4696 token::CloseDelim(token::Paren) => {
4697 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4700 let token_str = self.this_token_to_string();
4701 return Err(self.fatal(&format!("expected `,` or `)`, found `{}`",
4708 let fn_inputs = match explicit_self {
4709 SelfKind::Static => {
4710 let sep = seq_sep_trailing_allowed(token::Comma);
4711 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4713 SelfKind::Value(id) => parse_remaining_arguments!(id),
4714 SelfKind::Region(_,_,id) => parse_remaining_arguments!(id),
4715 SelfKind::Explicit(_,id) => parse_remaining_arguments!(id),
4719 try!(self.expect(&token::CloseDelim(token::Paren)));
4721 let hi = self.span.hi;
4723 let ret_ty = try!(self.parse_ret_ty());
4725 let fn_decl = P(FnDecl {
4731 Ok((spanned(lo, hi, explicit_self), fn_decl))
4734 // parse the |arg, arg| header on a lambda
4735 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4736 let inputs_captures = {
4737 if self.eat(&token::OrOr) {
4740 try!(self.expect(&token::BinOp(token::Or)));
4741 try!(self.parse_obsolete_closure_kind());
4742 let args = self.parse_seq_to_before_end(
4743 &token::BinOp(token::Or),
4744 seq_sep_trailing_allowed(token::Comma),
4745 |p| p.parse_fn_block_arg()
4751 let output = try!(self.parse_ret_ty());
4754 inputs: inputs_captures,
4760 /// Parse the name and optional generic types of a function header.
4761 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4762 let id = try!(self.parse_ident());
4763 let generics = try!(self.parse_generics());
4767 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4768 node: ItemKind, vis: Visibility,
4769 attrs: Vec<Attribute>) -> P<Item> {
4773 id: ast::DUMMY_NODE_ID,
4780 /// Parse an item-position function declaration.
4781 fn parse_item_fn(&mut self,
4783 constness: Constness,
4785 -> PResult<'a, ItemInfo> {
4786 let (ident, mut generics) = try!(self.parse_fn_header());
4787 let decl = try!(self.parse_fn_decl(false));
4788 generics.where_clause = try!(self.parse_where_clause());
4789 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4790 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4793 /// true if we are looking at `const ID`, false for things like `const fn` etc
4794 pub fn is_const_item(&mut self) -> bool {
4795 self.token.is_keyword(keywords::Const) &&
4796 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4797 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4800 /// parses all the "front matter" for a `fn` declaration, up to
4801 /// and including the `fn` keyword:
4805 /// - `const unsafe fn`
4808 pub fn parse_fn_front_matter(&mut self)
4809 -> PResult<'a, (ast::Constness, ast::Unsafety, abi::Abi)> {
4810 let is_const_fn = self.eat_keyword(keywords::Const);
4811 let unsafety = try!(self.parse_unsafety());
4812 let (constness, unsafety, abi) = if is_const_fn {
4813 (Constness::Const, unsafety, Abi::Rust)
4815 let abi = if self.eat_keyword(keywords::Extern) {
4816 try!(self.parse_opt_abi()).unwrap_or(Abi::C)
4820 (Constness::NotConst, unsafety, abi)
4822 try!(self.expect_keyword(keywords::Fn));
4823 Ok((constness, unsafety, abi))
4826 /// Parse an impl item.
4827 pub fn parse_impl_item(&mut self) -> PResult<'a, ImplItem> {
4828 maybe_whole!(no_clone_from_p self, NtImplItem);
4830 let mut attrs = try!(self.parse_outer_attributes());
4831 let lo = self.span.lo;
4832 let vis = try!(self.parse_visibility());
4833 let (name, node) = if self.eat_keyword(keywords::Type) {
4834 let name = try!(self.parse_ident());
4835 try!(self.expect(&token::Eq));
4836 let typ = try!(self.parse_ty_sum());
4837 try!(self.expect(&token::Semi));
4838 (name, ast::ImplItemKind::Type(typ))
4839 } else if self.is_const_item() {
4840 try!(self.expect_keyword(keywords::Const));
4841 let name = try!(self.parse_ident());
4842 try!(self.expect(&token::Colon));
4843 let typ = try!(self.parse_ty_sum());
4844 try!(self.expect(&token::Eq));
4845 let expr = try!(self.parse_expr());
4846 try!(self.commit_expr_expecting(&expr, token::Semi));
4847 (name, ast::ImplItemKind::Const(typ, expr))
4849 let (name, inner_attrs, node) = try!(self.parse_impl_method(vis));
4850 attrs.extend(inner_attrs);
4855 id: ast::DUMMY_NODE_ID,
4856 span: mk_sp(lo, self.last_span.hi),
4864 fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
4866 Visibility::Public => {
4867 let is_macro_rules: bool = match self.token {
4868 token::Ident(sid, _) => sid.name == intern("macro_rules"),
4872 self.diagnostic().struct_span_err(span, "can't qualify macro_rules \
4873 invocation with `pub`")
4874 .fileline_help(span, "did you mean #[macro_export]?")
4877 self.diagnostic().struct_span_err(span, "can't qualify macro \
4878 invocation with `pub`")
4879 .fileline_help(span, "try adjusting the macro to put `pub` \
4880 inside the invocation")
4884 Visibility::Inherited => (),
4888 /// Parse a method or a macro invocation in a trait impl.
4889 fn parse_impl_method(&mut self, vis: Visibility)
4890 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4891 // code copied from parse_macro_use_or_failure... abstraction!
4892 if !self.token.is_any_keyword()
4893 && self.look_ahead(1, |t| *t == token::Not)
4894 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4895 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4898 let last_span = self.last_span;
4899 self.complain_if_pub_macro(vis, last_span);
4901 let lo = self.span.lo;
4902 let pth = try!(self.parse_path(NoTypesAllowed));
4903 try!(self.expect(&token::Not));
4905 // eat a matched-delimiter token tree:
4906 let delim = try!(self.expect_open_delim());
4907 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
4909 |p| p.parse_token_tree()));
4910 let m_ = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
4911 let m: ast::Mac = codemap::Spanned { node: m_,
4913 self.last_span.hi) };
4914 if delim != token::Brace {
4915 try!(self.expect(&token::Semi))
4917 Ok((token::special_idents::invalid, vec![], ast::ImplItemKind::Macro(m)))
4919 let (constness, unsafety, abi) = try!(self.parse_fn_front_matter());
4920 let ident = try!(self.parse_ident());
4921 let mut generics = try!(self.parse_generics());
4922 let (explicit_self, decl) = try!(self.parse_fn_decl_with_self(|p| {
4925 generics.where_clause = try!(self.parse_where_clause());
4926 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4927 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4930 explicit_self: explicit_self,
4932 constness: constness,
4938 /// Parse trait Foo { ... }
4939 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4941 let ident = try!(self.parse_ident());
4942 let mut tps = try!(self.parse_generics());
4944 // Parse supertrait bounds.
4945 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare));
4947 tps.where_clause = try!(self.parse_where_clause());
4949 let meths = try!(self.parse_trait_items());
4950 Ok((ident, ItemKind::Trait(unsafety, tps, bounds, meths), None))
4953 /// Parses items implementations variants
4954 /// impl<T> Foo { ... }
4955 /// impl<T> ToString for &'static T { ... }
4956 /// impl Send for .. {}
4957 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> PResult<'a, ItemInfo> {
4958 let impl_span = self.span;
4960 // First, parse type parameters if necessary.
4961 let mut generics = try!(self.parse_generics());
4963 // Special case: if the next identifier that follows is '(', don't
4964 // allow this to be parsed as a trait.
4965 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4967 let neg_span = self.span;
4968 let polarity = if self.eat(&token::Not) {
4969 ast::ImplPolarity::Negative
4971 ast::ImplPolarity::Positive
4975 let mut ty = try!(self.parse_ty_sum());
4977 // Parse traits, if necessary.
4978 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4979 // New-style trait. Reinterpret the type as a trait.
4981 TyKind::Path(None, ref path) => {
4983 path: (*path).clone(),
4988 self.span_err(ty.span, "not a trait");
4994 ast::ImplPolarity::Negative => {
4995 // This is a negated type implementation
4996 // `impl !MyType {}`, which is not allowed.
4997 self.span_err(neg_span, "inherent implementation can't be negated");
5004 if opt_trait.is_some() && self.eat(&token::DotDot) {
5005 if generics.is_parameterized() {
5006 self.span_err(impl_span, "default trait implementations are not \
5007 allowed to have generics");
5010 try!(self.expect(&token::OpenDelim(token::Brace)));
5011 try!(self.expect(&token::CloseDelim(token::Brace)));
5012 Ok((ast_util::impl_pretty_name(&opt_trait, None),
5013 ItemKind::DefaultImpl(unsafety, opt_trait.unwrap()), None))
5015 if opt_trait.is_some() {
5016 ty = try!(self.parse_ty_sum());
5018 generics.where_clause = try!(self.parse_where_clause());
5020 try!(self.expect(&token::OpenDelim(token::Brace)));
5021 let attrs = try!(self.parse_inner_attributes());
5023 let mut impl_items = vec![];
5024 while !self.eat(&token::CloseDelim(token::Brace)) {
5025 impl_items.push(try!(self.parse_impl_item()));
5028 Ok((ast_util::impl_pretty_name(&opt_trait, Some(&ty)),
5029 ItemKind::Impl(unsafety, polarity, generics, opt_trait, ty, impl_items),
5034 /// Parse a::B<String,i32>
5035 fn parse_trait_ref(&mut self) -> PResult<'a, TraitRef> {
5037 path: try!(self.parse_path(LifetimeAndTypesWithoutColons)),
5038 ref_id: ast::DUMMY_NODE_ID,
5042 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<ast::LifetimeDef>> {
5043 if self.eat_keyword(keywords::For) {
5044 try!(self.expect(&token::Lt));
5045 let lifetime_defs = try!(self.parse_lifetime_defs());
5046 try!(self.expect_gt());
5053 /// Parse for<'l> a::B<String,i32>
5054 fn parse_poly_trait_ref(&mut self) -> PResult<'a, PolyTraitRef> {
5055 let lo = self.span.lo;
5056 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
5058 Ok(ast::PolyTraitRef {
5059 bound_lifetimes: lifetime_defs,
5060 trait_ref: try!(self.parse_trait_ref()),
5061 span: mk_sp(lo, self.last_span.hi),
5065 /// Parse struct Foo { ... }
5066 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5067 let class_name = try!(self.parse_ident());
5068 let mut generics = try!(self.parse_generics());
5070 // There is a special case worth noting here, as reported in issue #17904.
5071 // If we are parsing a tuple struct it is the case that the where clause
5072 // should follow the field list. Like so:
5074 // struct Foo<T>(T) where T: Copy;
5076 // If we are parsing a normal record-style struct it is the case
5077 // that the where clause comes before the body, and after the generics.
5078 // So if we look ahead and see a brace or a where-clause we begin
5079 // parsing a record style struct.
5081 // Otherwise if we look ahead and see a paren we parse a tuple-style
5084 let vdata = if self.token.is_keyword(keywords::Where) {
5085 generics.where_clause = try!(self.parse_where_clause());
5086 if self.eat(&token::Semi) {
5087 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5088 VariantData::Unit(ast::DUMMY_NODE_ID)
5090 // If we see: `struct Foo<T> where T: Copy { ... }`
5091 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
5094 // No `where` so: `struct Foo<T>;`
5095 } else if self.eat(&token::Semi) {
5096 VariantData::Unit(ast::DUMMY_NODE_ID)
5097 // Record-style struct definition
5098 } else if self.token == token::OpenDelim(token::Brace) {
5099 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
5101 // Tuple-style struct definition with optional where-clause.
5102 } else if self.token == token::OpenDelim(token::Paren) {
5103 let body = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::Yes)),
5104 ast::DUMMY_NODE_ID);
5105 generics.where_clause = try!(self.parse_where_clause());
5106 try!(self.expect(&token::Semi));
5109 let token_str = self.this_token_to_string();
5110 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
5111 name, found `{}`", token_str)))
5114 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5117 pub fn parse_record_struct_body(&mut self,
5118 parse_pub: ParsePub)
5119 -> PResult<'a, Vec<StructField>> {
5120 let mut fields = Vec::new();
5121 if self.eat(&token::OpenDelim(token::Brace)) {
5122 while self.token != token::CloseDelim(token::Brace) {
5123 fields.push(try!(self.parse_struct_decl_field(parse_pub)));
5128 let token_str = self.this_token_to_string();
5129 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5137 pub fn parse_tuple_struct_body(&mut self,
5138 parse_pub: ParsePub)
5139 -> PResult<'a, Vec<StructField>> {
5140 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5141 // Unit like structs are handled in parse_item_struct function
5142 let fields = try!(self.parse_unspanned_seq(
5143 &token::OpenDelim(token::Paren),
5144 &token::CloseDelim(token::Paren),
5145 seq_sep_trailing_allowed(token::Comma),
5147 let attrs = try!(p.parse_outer_attributes());
5149 let struct_field_ = ast::StructField_ {
5150 kind: UnnamedField (
5151 if parse_pub == ParsePub::Yes {
5152 try!(p.parse_visibility())
5154 Visibility::Inherited
5157 id: ast::DUMMY_NODE_ID,
5158 ty: try!(p.parse_ty_sum()),
5161 Ok(spanned(lo, p.span.hi, struct_field_))
5167 /// Parse a structure field declaration
5168 pub fn parse_single_struct_field(&mut self,
5170 attrs: Vec<Attribute> )
5171 -> PResult<'a, StructField> {
5172 let a_var = try!(self.parse_name_and_ty(vis, attrs));
5177 token::CloseDelim(token::Brace) => {}
5179 let span = self.span;
5180 let token_str = self.this_token_to_string();
5181 return Err(self.span_fatal_help(span,
5182 &format!("expected `,`, or `}}`, found `{}`",
5184 "struct fields should be separated by commas"))
5190 /// Parse an element of a struct definition
5191 fn parse_struct_decl_field(&mut self, parse_pub: ParsePub) -> PResult<'a, StructField> {
5193 let attrs = try!(self.parse_outer_attributes());
5195 if self.eat_keyword(keywords::Pub) {
5196 if parse_pub == ParsePub::No {
5197 let span = self.last_span;
5198 self.span_err(span, "`pub` is not allowed here");
5200 return self.parse_single_struct_field(Visibility::Public, attrs);
5203 return self.parse_single_struct_field(Visibility::Inherited, attrs);
5206 /// Parse visibility: PUB or nothing
5207 fn parse_visibility(&mut self) -> PResult<'a, Visibility> {
5208 if self.eat_keyword(keywords::Pub) { Ok(Visibility::Public) }
5209 else { Ok(Visibility::Inherited) }
5212 /// Given a termination token, parse all of the items in a module
5213 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> PResult<'a, Mod> {
5214 let mut items = vec![];
5215 while let Some(item) = try!(self.parse_item()) {
5219 if !self.eat(term) {
5220 let token_str = self.this_token_to_string();
5221 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5224 let hi = if self.span == codemap::DUMMY_SP {
5231 inner: mk_sp(inner_lo, hi),
5236 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5237 let id = try!(self.parse_ident());
5238 try!(self.expect(&token::Colon));
5239 let ty = try!(self.parse_ty_sum());
5240 try!(self.expect(&token::Eq));
5241 let e = try!(self.parse_expr());
5242 try!(self.commit_expr_expecting(&e, token::Semi));
5243 let item = match m {
5244 Some(m) => ItemKind::Static(ty, m, e),
5245 None => ItemKind::Const(ty, e),
5247 Ok((id, item, None))
5250 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5251 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5252 let id_span = self.span;
5253 let id = try!(self.parse_ident());
5254 if self.check(&token::Semi) {
5256 // This mod is in an external file. Let's go get it!
5257 let (m, attrs) = try!(self.eval_src_mod(id, outer_attrs, id_span));
5258 Ok((id, m, Some(attrs)))
5260 self.push_mod_path(id, outer_attrs);
5261 try!(self.expect(&token::OpenDelim(token::Brace)));
5262 let mod_inner_lo = self.span.lo;
5263 let attrs = try!(self.parse_inner_attributes());
5264 let m = try!(self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo));
5265 self.pop_mod_path();
5266 Ok((id, ItemKind::Mod(m), Some(attrs)))
5270 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5271 let default_path = self.id_to_interned_str(id);
5272 let file_path = match ::attr::first_attr_value_str_by_name(attrs, "path") {
5274 None => default_path,
5276 self.mod_path_stack.push(file_path)
5279 fn pop_mod_path(&mut self) {
5280 self.mod_path_stack.pop().unwrap();
5283 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5284 ::attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&*d))
5287 /// Returns either a path to a module, or .
5288 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath
5290 let mod_name = id.to_string();
5291 let default_path_str = format!("{}.rs", mod_name);
5292 let secondary_path_str = format!("{}/mod.rs", mod_name);
5293 let default_path = dir_path.join(&default_path_str);
5294 let secondary_path = dir_path.join(&secondary_path_str);
5295 let default_exists = codemap.file_exists(&default_path);
5296 let secondary_exists = codemap.file_exists(&secondary_path);
5298 let result = match (default_exists, secondary_exists) {
5299 (true, false) => Ok(ModulePathSuccess { path: default_path, owns_directory: false }),
5300 (false, true) => Ok(ModulePathSuccess { path: secondary_path, owns_directory: true }),
5301 (false, false) => Err(ModulePathError {
5302 err_msg: format!("file not found for module `{}`", mod_name),
5303 help_msg: format!("name the file either {} or {} inside the directory {:?}",
5306 dir_path.display()),
5308 (true, true) => Err(ModulePathError {
5309 err_msg: format!("file for module `{}` found at both {} and {}",
5312 secondary_path_str),
5313 help_msg: "delete or rename one of them to remove the ambiguity".to_owned(),
5319 path_exists: default_exists || secondary_exists,
5324 fn submod_path(&mut self,
5326 outer_attrs: &[ast::Attribute],
5327 id_sp: Span) -> PResult<'a, ModulePathSuccess> {
5328 let mut prefix = PathBuf::from(&self.sess.codemap().span_to_filename(self.span));
5330 let mut dir_path = prefix;
5331 for part in &self.mod_path_stack {
5332 dir_path.push(&**part);
5335 if let Some(p) = Parser::submod_path_from_attr(outer_attrs, &dir_path) {
5336 return Ok(ModulePathSuccess { path: p, owns_directory: true });
5339 let paths = Parser::default_submod_path(id, &dir_path, self.sess.codemap());
5341 if self.restrictions.contains(Restrictions::NO_NONINLINE_MOD) {
5343 "Cannot declare a non-inline module inside a block unless it has a path attribute";
5344 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5345 if paths.path_exists {
5346 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5348 err.span_note(id_sp, &msg);
5351 } else if !self.owns_directory {
5352 let mut err = self.diagnostic().struct_span_err(id_sp,
5353 "cannot declare a new module at this location");
5354 let this_module = match self.mod_path_stack.last() {
5355 Some(name) => name.to_string(),
5356 None => self.root_module_name.as_ref().unwrap().clone(),
5358 err.span_note(id_sp,
5359 &format!("maybe move this module `{0}` to its own directory \
5362 if paths.path_exists {
5363 err.span_note(id_sp,
5364 &format!("... or maybe `use` the module `{}` instead \
5365 of possibly redeclaring it",
5371 match paths.result {
5372 Ok(succ) => Ok(succ),
5373 Err(err) => Err(self.span_fatal_help(id_sp, &err.err_msg, &err.help_msg)),
5377 /// Read a module from a source file.
5378 fn eval_src_mod(&mut self,
5380 outer_attrs: &[ast::Attribute],
5382 -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5383 let ModulePathSuccess { path, owns_directory } = try!(self.submod_path(id,
5387 self.eval_src_mod_from_path(path,
5393 fn eval_src_mod_from_path(&mut self,
5395 owns_directory: bool,
5397 id_sp: Span) -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5398 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5399 match included_mod_stack.iter().position(|p| *p == path) {
5401 let mut err = String::from("circular modules: ");
5402 let len = included_mod_stack.len();
5403 for p in &included_mod_stack[i.. len] {
5404 err.push_str(&p.to_string_lossy());
5405 err.push_str(" -> ");
5407 err.push_str(&path.to_string_lossy());
5408 return Err(self.span_fatal(id_sp, &err[..]));
5412 included_mod_stack.push(path.clone());
5413 drop(included_mod_stack);
5415 let mut p0 = new_sub_parser_from_file(self.sess,
5421 let mod_inner_lo = p0.span.lo;
5422 let mod_attrs = try!(p0.parse_inner_attributes());
5423 let m0 = try!(p0.parse_mod_items(&token::Eof, mod_inner_lo));
5424 self.sess.included_mod_stack.borrow_mut().pop();
5425 Ok((ast::ItemKind::Mod(m0), mod_attrs))
5428 /// Parse a function declaration from a foreign module
5429 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: BytePos,
5430 attrs: Vec<Attribute>) -> PResult<'a, ForeignItem> {
5431 try!(self.expect_keyword(keywords::Fn));
5433 let (ident, mut generics) = try!(self.parse_fn_header());
5434 let decl = try!(self.parse_fn_decl(true));
5435 generics.where_clause = try!(self.parse_where_clause());
5436 let hi = self.span.hi;
5437 try!(self.expect(&token::Semi));
5438 Ok(ast::ForeignItem {
5441 node: ForeignItemKind::Fn(decl, generics),
5442 id: ast::DUMMY_NODE_ID,
5443 span: mk_sp(lo, hi),
5448 /// Parse a static item from a foreign module
5449 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: BytePos,
5450 attrs: Vec<Attribute>) -> PResult<'a, ForeignItem> {
5451 try!(self.expect_keyword(keywords::Static));
5452 let mutbl = self.eat_keyword(keywords::Mut);
5454 let ident = try!(self.parse_ident());
5455 try!(self.expect(&token::Colon));
5456 let ty = try!(self.parse_ty_sum());
5457 let hi = self.span.hi;
5458 try!(self.expect(&token::Semi));
5462 node: ForeignItemKind::Static(ty, mutbl),
5463 id: ast::DUMMY_NODE_ID,
5464 span: mk_sp(lo, hi),
5469 /// Parse extern crate links
5473 /// extern crate foo;
5474 /// extern crate bar as foo;
5475 fn parse_item_extern_crate(&mut self,
5477 visibility: Visibility,
5478 attrs: Vec<Attribute>)
5479 -> PResult<'a, P<Item>> {
5481 let crate_name = try!(self.parse_ident());
5482 let (maybe_path, ident) = if let Some(ident) = try!(self.parse_rename()) {
5483 (Some(crate_name.name), ident)
5487 try!(self.expect(&token::Semi));
5489 let last_span = self.last_span;
5491 if visibility == ast::Visibility::Public {
5492 self.span_warn(mk_sp(lo, last_span.hi),
5493 "`pub extern crate` does not work as expected and should not be used. \
5494 Likely to become an error. Prefer `extern crate` and `pub use`.");
5500 ItemKind::ExternCrate(maybe_path),
5505 /// Parse `extern` for foreign ABIs
5508 /// `extern` is expected to have been
5509 /// consumed before calling this method
5515 fn parse_item_foreign_mod(&mut self,
5517 opt_abi: Option<abi::Abi>,
5518 visibility: Visibility,
5519 mut attrs: Vec<Attribute>)
5520 -> PResult<'a, P<Item>> {
5521 try!(self.expect(&token::OpenDelim(token::Brace)));
5523 let abi = opt_abi.unwrap_or(Abi::C);
5525 attrs.extend(try!(self.parse_inner_attributes()));
5527 let mut foreign_items = vec![];
5528 while let Some(item) = try!(self.parse_foreign_item()) {
5529 foreign_items.push(item);
5531 try!(self.expect(&token::CloseDelim(token::Brace)));
5533 let last_span = self.last_span;
5534 let m = ast::ForeignMod {
5536 items: foreign_items
5540 special_idents::invalid,
5541 ItemKind::ForeignMod(m),
5546 /// Parse type Foo = Bar;
5547 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5548 let ident = try!(self.parse_ident());
5549 let mut tps = try!(self.parse_generics());
5550 tps.where_clause = try!(self.parse_where_clause());
5551 try!(self.expect(&token::Eq));
5552 let ty = try!(self.parse_ty_sum());
5553 try!(self.expect(&token::Semi));
5554 Ok((ident, ItemKind::Ty(ty, tps), None))
5557 /// Parse the part of an "enum" decl following the '{'
5558 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5559 let mut variants = Vec::new();
5560 let mut all_nullary = true;
5561 let mut any_disr = None;
5562 while self.token != token::CloseDelim(token::Brace) {
5563 let variant_attrs = try!(self.parse_outer_attributes());
5564 let vlo = self.span.lo;
5567 let mut disr_expr = None;
5568 let ident = try!(self.parse_ident());
5569 if self.check(&token::OpenDelim(token::Brace)) {
5570 // Parse a struct variant.
5571 all_nullary = false;
5572 struct_def = VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::No)),
5573 ast::DUMMY_NODE_ID);
5574 } else if self.check(&token::OpenDelim(token::Paren)) {
5575 all_nullary = false;
5576 struct_def = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::No)),
5577 ast::DUMMY_NODE_ID);
5578 } else if self.eat(&token::Eq) {
5579 disr_expr = Some(try!(self.parse_expr()));
5580 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5581 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5583 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5586 let vr = ast::Variant_ {
5588 attrs: variant_attrs,
5590 disr_expr: disr_expr,
5592 variants.push(spanned(vlo, self.last_span.hi, vr));
5594 if !self.eat(&token::Comma) { break; }
5596 try!(self.expect(&token::CloseDelim(token::Brace)));
5598 Some(disr_span) if !all_nullary =>
5599 self.span_err(disr_span,
5600 "discriminator values can only be used with a c-like enum"),
5604 Ok(ast::EnumDef { variants: variants })
5607 /// Parse an "enum" declaration
5608 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5609 let id = try!(self.parse_ident());
5610 let mut generics = try!(self.parse_generics());
5611 generics.where_clause = try!(self.parse_where_clause());
5612 try!(self.expect(&token::OpenDelim(token::Brace)));
5614 let enum_definition = try!(self.parse_enum_def(&generics));
5615 Ok((id, ItemKind::Enum(enum_definition, generics), None))
5618 /// Parses a string as an ABI spec on an extern type or module. Consumes
5619 /// the `extern` keyword, if one is found.
5620 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5622 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5624 self.expect_no_suffix(sp, "ABI spec", suf);
5626 match abi::lookup(&s.as_str()) {
5627 Some(abi) => Ok(Some(abi)),
5629 let last_span = self.last_span;
5632 &format!("invalid ABI: expected one of [{}], \
5634 abi::all_names().join(", "),
5645 /// Parse one of the items allowed by the flags.
5646 /// NB: this function no longer parses the items inside an
5648 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5649 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5650 let nt_item = match self.token {
5651 token::Interpolated(token::NtItem(ref item)) => {
5652 Some((**item).clone())
5659 let mut attrs = attrs;
5660 mem::swap(&mut item.attrs, &mut attrs);
5661 item.attrs.extend(attrs);
5662 return Ok(Some(P(item)));
5667 let lo = self.span.lo;
5669 let visibility = try!(self.parse_visibility());
5671 if self.eat_keyword(keywords::Use) {
5673 let item_ = ItemKind::Use(try!(self.parse_view_path()));
5674 try!(self.expect(&token::Semi));
5676 let last_span = self.last_span;
5677 let item = self.mk_item(lo,
5679 token::special_idents::invalid,
5683 return Ok(Some(item));
5686 if self.eat_keyword(keywords::Extern) {
5687 if self.eat_keyword(keywords::Crate) {
5688 return Ok(Some(try!(self.parse_item_extern_crate(lo, visibility, attrs))));
5691 let opt_abi = try!(self.parse_opt_abi());
5693 if self.eat_keyword(keywords::Fn) {
5694 // EXTERN FUNCTION ITEM
5695 let abi = opt_abi.unwrap_or(Abi::C);
5696 let (ident, item_, extra_attrs) =
5697 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi));
5698 let last_span = self.last_span;
5699 let item = self.mk_item(lo,
5704 maybe_append(attrs, extra_attrs));
5705 return Ok(Some(item));
5706 } else if self.check(&token::OpenDelim(token::Brace)) {
5707 return Ok(Some(try!(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs))));
5710 try!(self.unexpected());
5713 if self.eat_keyword(keywords::Static) {
5715 let m = if self.eat_keyword(keywords::Mut) {
5718 Mutability::Immutable
5720 let (ident, item_, extra_attrs) = try!(self.parse_item_const(Some(m)));
5721 let last_span = self.last_span;
5722 let item = self.mk_item(lo,
5727 maybe_append(attrs, extra_attrs));
5728 return Ok(Some(item));
5730 if self.eat_keyword(keywords::Const) {
5731 if self.check_keyword(keywords::Fn)
5732 || (self.check_keyword(keywords::Unsafe)
5733 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5734 // CONST FUNCTION ITEM
5735 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5741 let (ident, item_, extra_attrs) =
5742 try!(self.parse_item_fn(unsafety, Constness::Const, Abi::Rust));
5743 let last_span = self.last_span;
5744 let item = self.mk_item(lo,
5749 maybe_append(attrs, extra_attrs));
5750 return Ok(Some(item));
5754 if self.eat_keyword(keywords::Mut) {
5755 let last_span = self.last_span;
5756 self.diagnostic().struct_span_err(last_span, "const globals cannot be mutable")
5757 .fileline_help(last_span, "did you mean to declare a static?")
5760 let (ident, item_, extra_attrs) = try!(self.parse_item_const(None));
5761 let last_span = self.last_span;
5762 let item = self.mk_item(lo,
5767 maybe_append(attrs, extra_attrs));
5768 return Ok(Some(item));
5770 if self.check_keyword(keywords::Unsafe) &&
5771 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5773 // UNSAFE TRAIT ITEM
5774 try!(self.expect_keyword(keywords::Unsafe));
5775 try!(self.expect_keyword(keywords::Trait));
5776 let (ident, item_, extra_attrs) =
5777 try!(self.parse_item_trait(ast::Unsafety::Unsafe));
5778 let last_span = self.last_span;
5779 let item = self.mk_item(lo,
5784 maybe_append(attrs, extra_attrs));
5785 return Ok(Some(item));
5787 if self.check_keyword(keywords::Unsafe) &&
5788 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5791 try!(self.expect_keyword(keywords::Unsafe));
5792 try!(self.expect_keyword(keywords::Impl));
5793 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Unsafe));
5794 let last_span = self.last_span;
5795 let item = self.mk_item(lo,
5800 maybe_append(attrs, extra_attrs));
5801 return Ok(Some(item));
5803 if self.check_keyword(keywords::Fn) {
5806 let (ident, item_, extra_attrs) =
5807 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, Abi::Rust));
5808 let last_span = self.last_span;
5809 let item = self.mk_item(lo,
5814 maybe_append(attrs, extra_attrs));
5815 return Ok(Some(item));
5817 if self.check_keyword(keywords::Unsafe)
5818 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5819 // UNSAFE FUNCTION ITEM
5821 let abi = if self.eat_keyword(keywords::Extern) {
5822 try!(self.parse_opt_abi()).unwrap_or(Abi::C)
5826 try!(self.expect_keyword(keywords::Fn));
5827 let (ident, item_, extra_attrs) =
5828 try!(self.parse_item_fn(Unsafety::Unsafe, Constness::NotConst, abi));
5829 let last_span = self.last_span;
5830 let item = self.mk_item(lo,
5835 maybe_append(attrs, extra_attrs));
5836 return Ok(Some(item));
5838 if self.eat_keyword(keywords::Mod) {
5840 let (ident, item_, extra_attrs) =
5841 try!(self.parse_item_mod(&attrs[..]));
5842 let last_span = self.last_span;
5843 let item = self.mk_item(lo,
5848 maybe_append(attrs, extra_attrs));
5849 return Ok(Some(item));
5851 if self.eat_keyword(keywords::Type) {
5853 let (ident, item_, extra_attrs) = try!(self.parse_item_type());
5854 let last_span = self.last_span;
5855 let item = self.mk_item(lo,
5860 maybe_append(attrs, extra_attrs));
5861 return Ok(Some(item));
5863 if self.eat_keyword(keywords::Enum) {
5865 let (ident, item_, extra_attrs) = try!(self.parse_item_enum());
5866 let last_span = self.last_span;
5867 let item = self.mk_item(lo,
5872 maybe_append(attrs, extra_attrs));
5873 return Ok(Some(item));
5875 if self.eat_keyword(keywords::Trait) {
5877 let (ident, item_, extra_attrs) =
5878 try!(self.parse_item_trait(ast::Unsafety::Normal));
5879 let last_span = self.last_span;
5880 let item = self.mk_item(lo,
5885 maybe_append(attrs, extra_attrs));
5886 return Ok(Some(item));
5888 if self.eat_keyword(keywords::Impl) {
5890 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Normal));
5891 let last_span = self.last_span;
5892 let item = self.mk_item(lo,
5897 maybe_append(attrs, extra_attrs));
5898 return Ok(Some(item));
5900 if self.eat_keyword(keywords::Struct) {
5902 let (ident, item_, extra_attrs) = try!(self.parse_item_struct());
5903 let last_span = self.last_span;
5904 let item = self.mk_item(lo,
5909 maybe_append(attrs, extra_attrs));
5910 return Ok(Some(item));
5912 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5915 /// Parse a foreign item.
5916 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
5917 let attrs = try!(self.parse_outer_attributes());
5918 let lo = self.span.lo;
5919 let visibility = try!(self.parse_visibility());
5921 if self.check_keyword(keywords::Static) {
5922 // FOREIGN STATIC ITEM
5923 return Ok(Some(try!(self.parse_item_foreign_static(visibility, lo, attrs))));
5925 if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) {
5926 // FOREIGN FUNCTION ITEM
5927 return Ok(Some(try!(self.parse_item_foreign_fn(visibility, lo, attrs))));
5930 // FIXME #5668: this will occur for a macro invocation:
5931 match try!(self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)) {
5933 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5939 /// This is the fall-through for parsing items.
5940 fn parse_macro_use_or_failure(
5942 attrs: Vec<Attribute> ,
5943 macros_allowed: bool,
5944 attributes_allowed: bool,
5946 visibility: Visibility
5947 ) -> PResult<'a, Option<P<Item>>> {
5948 if macros_allowed && !self.token.is_any_keyword()
5949 && self.look_ahead(1, |t| *t == token::Not)
5950 && (self.look_ahead(2, |t| t.is_plain_ident())
5951 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5952 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5953 // MACRO INVOCATION ITEM
5955 let last_span = self.last_span;
5956 self.complain_if_pub_macro(visibility, last_span);
5958 let mac_lo = self.span.lo;
5961 let pth = try!(self.parse_path(NoTypesAllowed));
5962 try!(self.expect(&token::Not));
5964 // a 'special' identifier (like what `macro_rules!` uses)
5965 // is optional. We should eventually unify invoc syntax
5967 let id = if self.token.is_plain_ident() {
5968 try!(self.parse_ident())
5970 token::special_idents::invalid // no special identifier
5972 // eat a matched-delimiter token tree:
5973 let delim = try!(self.expect_open_delim());
5974 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
5976 |p| p.parse_token_tree()));
5977 // single-variant-enum... :
5978 let m = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
5979 let m: ast::Mac = codemap::Spanned { node: m,
5981 self.last_span.hi) };
5983 if delim != token::Brace {
5984 if !self.eat(&token::Semi) {
5985 let last_span = self.last_span;
5986 self.span_err(last_span,
5987 "macros that expand to items must either \
5988 be surrounded with braces or followed by \
5993 let item_ = ItemKind::Mac(m);
5994 let last_span = self.last_span;
5995 let item = self.mk_item(lo,
6001 return Ok(Some(item));
6004 // FAILURE TO PARSE ITEM
6006 Visibility::Inherited => {}
6007 Visibility::Public => {
6008 let last_span = self.last_span;
6009 return Err(self.span_fatal(last_span, "unmatched visibility `pub`"));
6013 if !attributes_allowed && !attrs.is_empty() {
6014 self.expected_item_err(&attrs);
6019 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6020 let attrs = try!(self.parse_outer_attributes());
6021 self.parse_item_(attrs, true, false)
6025 /// Matches view_path : MOD? non_global_path as IDENT
6026 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
6027 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
6028 /// | MOD? non_global_path MOD_SEP STAR
6029 /// | MOD? non_global_path
6030 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
6031 let lo = self.span.lo;
6033 // Allow a leading :: because the paths are absolute either way.
6034 // This occurs with "use $crate::..." in macros.
6035 self.eat(&token::ModSep);
6037 if self.check(&token::OpenDelim(token::Brace)) {
6039 let idents = try!(self.parse_unspanned_seq(
6040 &token::OpenDelim(token::Brace),
6041 &token::CloseDelim(token::Brace),
6042 seq_sep_trailing_allowed(token::Comma),
6043 |p| p.parse_path_list_item()));
6044 let path = ast::Path {
6045 span: mk_sp(lo, self.span.hi),
6047 segments: Vec::new()
6049 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
6052 let first_ident = try!(self.parse_ident());
6053 let mut path = vec!(first_ident);
6054 if let token::ModSep = self.token {
6055 // foo::bar or foo::{a,b,c} or foo::*
6056 while self.check(&token::ModSep) {
6060 token::Ident(..) => {
6061 let ident = try!(self.parse_ident());
6065 // foo::bar::{a,b,c}
6066 token::OpenDelim(token::Brace) => {
6067 let idents = try!(self.parse_unspanned_seq(
6068 &token::OpenDelim(token::Brace),
6069 &token::CloseDelim(token::Brace),
6070 seq_sep_trailing_allowed(token::Comma),
6071 |p| p.parse_path_list_item()
6073 let path = ast::Path {
6074 span: mk_sp(lo, self.span.hi),
6076 segments: path.into_iter().map(|identifier| {
6078 identifier: identifier,
6079 parameters: ast::PathParameters::none(),
6083 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
6087 token::BinOp(token::Star) => {
6089 let path = ast::Path {
6090 span: mk_sp(lo, self.span.hi),
6092 segments: path.into_iter().map(|identifier| {
6094 identifier: identifier,
6095 parameters: ast::PathParameters::none(),
6099 return Ok(P(spanned(lo, self.span.hi, ViewPathGlob(path))));
6102 // fall-through for case foo::bar::;
6104 self.span_err(self.span, "expected identifier or `{` or `*`, found `;`");
6111 let mut rename_to = path[path.len() - 1];
6112 let path = ast::Path {
6113 span: mk_sp(lo, self.last_span.hi),
6115 segments: path.into_iter().map(|identifier| {
6117 identifier: identifier,
6118 parameters: ast::PathParameters::none(),
6122 rename_to = try!(self.parse_rename()).unwrap_or(rename_to);
6123 Ok(P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path))))
6126 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6127 if self.eat_keyword(keywords::As) {
6128 self.parse_ident().map(Some)
6134 /// Parses a source module as a crate. This is the main
6135 /// entry point for the parser.
6136 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6137 let lo = self.span.lo;
6139 attrs: try!(self.parse_inner_attributes()),
6140 module: try!(self.parse_mod_items(&token::Eof, lo)),
6141 config: self.cfg.clone(),
6142 span: mk_sp(lo, self.span.lo),
6143 exported_macros: Vec::new(),
6147 pub fn parse_optional_str(&mut self)
6148 -> Option<(InternedString,
6150 Option<ast::Name>)> {
6151 let ret = match self.token {
6152 token::Literal(token::Str_(s), suf) => {
6153 let s = self.id_to_interned_str(ast::Ident::with_empty_ctxt(s));
6154 (s, ast::StrStyle::Cooked, suf)
6156 token::Literal(token::StrRaw(s, n), suf) => {
6157 let s = self.id_to_interned_str(ast::Ident::with_empty_ctxt(s));
6158 (s, ast::StrStyle::Raw(n), suf)
6166 pub fn parse_str(&mut self) -> PResult<'a, (InternedString, StrStyle)> {
6167 match self.parse_optional_str() {
6168 Some((s, style, suf)) => {
6169 let sp = self.last_span;
6170 self.expect_no_suffix(sp, "string literal", suf);
6173 _ => Err(self.fatal("expected string literal"))