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, PatBox, PatEnum, PatIdent, PatLit, PatQPath, PatMac, PatRange};
34 use ast::{PatRegion, PatStruct, PatTup, PatVec, PatWild};
35 use ast::{PolyTraitRef, QSelf};
36 use ast::{Stmt, StmtKind};
37 use ast::{VariantData, StructField};
40 use ast::{Delimited, SequenceRepetition, TokenTree, TraitItem, TraitRef};
41 use ast::{Ty, TyKind, TypeBinding, TyParam, TyParamBounds};
42 use ast::UnnamedField;
43 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
44 use ast::{Visibility, WhereClause};
45 use attr::{ThinAttributes, ThinAttributesExt, AttributesExt};
46 use ast::{BinOpKind, UnOp};
48 use ast_util::{self, ident_to_path};
49 use codemap::{self, Span, BytePos, Spanned, spanned, mk_sp, CodeMap};
50 use errors::{self, DiagnosticBuilder};
51 use ext::tt::macro_parser;
54 use parse::common::{SeqSep, seq_sep_none, seq_sep_trailing_allowed};
55 use parse::lexer::{Reader, TokenAndSpan};
56 use parse::obsolete::{ParserObsoleteMethods, ObsoleteSyntax};
57 use parse::token::{self, intern, MatchNt, SubstNt, SpecialVarNt, InternedString};
58 use parse::token::{keywords, special_idents, SpecialMacroVar};
59 use parse::{new_sub_parser_from_file, ParseSess};
60 use util::parser::{AssocOp, Fixity};
65 use std::collections::HashSet;
66 use std::io::prelude::*;
68 use std::path::{Path, PathBuf};
73 flags Restrictions: u8 {
74 const RESTRICTION_STMT_EXPR = 1 << 0,
75 const RESTRICTION_NO_STRUCT_LITERAL = 1 << 1,
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 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
110 /// dropped into the token stream, which happens while parsing the result of
111 /// macro expansion). Placement of these is not as complex as I feared it would
112 /// be. The important thing is to make sure that lookahead doesn't balk at
113 /// `token::Interpolated` tokens.
114 macro_rules! maybe_whole_expr {
117 let found = match $p.token {
118 token::Interpolated(token::NtExpr(ref e)) => {
121 token::Interpolated(token::NtPath(_)) => {
122 // FIXME: The following avoids an issue with lexical borrowck scopes,
123 // but the clone is unfortunate.
124 let pt = match $p.token {
125 token::Interpolated(token::NtPath(ref pt)) => (**pt).clone(),
129 Some($p.mk_expr(span.lo, span.hi, ExprKind::Path(None, pt), None))
131 token::Interpolated(token::NtBlock(_)) => {
132 // FIXME: The following avoids an issue with lexical borrowck scopes,
133 // but the clone is unfortunate.
134 let b = match $p.token {
135 token::Interpolated(token::NtBlock(ref b)) => (*b).clone(),
139 Some($p.mk_expr(span.lo, span.hi, ExprKind::Block(b), None))
154 /// As maybe_whole_expr, but for things other than expressions
155 macro_rules! maybe_whole {
156 ($p:expr, $constructor:ident) => (
158 let found = match ($p).token {
159 token::Interpolated(token::$constructor(_)) => {
160 Some(($p).bump_and_get())
164 if let Some(token::Interpolated(token::$constructor(x))) = found {
165 return Ok(x.clone());
169 (no_clone $p:expr, $constructor:ident) => (
171 let found = match ($p).token {
172 token::Interpolated(token::$constructor(_)) => {
173 Some(($p).bump_and_get())
177 if let Some(token::Interpolated(token::$constructor(x))) = found {
182 (deref $p:expr, $constructor:ident) => (
184 let found = match ($p).token {
185 token::Interpolated(token::$constructor(_)) => {
186 Some(($p).bump_and_get())
190 if let Some(token::Interpolated(token::$constructor(x))) = found {
191 return Ok((*x).clone());
195 (Some deref $p:expr, $constructor:ident) => (
197 let found = match ($p).token {
198 token::Interpolated(token::$constructor(_)) => {
199 Some(($p).bump_and_get())
203 if let Some(token::Interpolated(token::$constructor(x))) = found {
204 return Ok(Some((*x).clone()));
208 (pair_empty $p:expr, $constructor:ident) => (
210 let found = match ($p).token {
211 token::Interpolated(token::$constructor(_)) => {
212 Some(($p).bump_and_get())
216 if let Some(token::Interpolated(token::$constructor(x))) = found {
217 return Ok((Vec::new(), x));
223 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
225 if let Some(ref attrs) = rhs {
226 lhs.extend(attrs.iter().cloned())
231 /* ident is handled by common.rs */
233 pub struct Parser<'a> {
234 pub sess: &'a ParseSess,
235 /// the current token:
236 pub token: token::Token,
237 /// the span of the current token:
239 /// the span of the prior token:
241 pub cfg: CrateConfig,
242 /// the previous token or None (only stashed sometimes).
243 pub last_token: Option<Box<token::Token>>,
244 last_token_interpolated: bool,
245 pub buffer: [TokenAndSpan; 4],
246 pub buffer_start: isize,
247 pub buffer_end: isize,
248 pub tokens_consumed: usize,
249 pub restrictions: Restrictions,
250 pub quote_depth: usize, // not (yet) related to the quasiquoter
251 pub reader: Box<Reader+'a>,
252 pub interner: Rc<token::IdentInterner>,
253 /// The set of seen errors about obsolete syntax. Used to suppress
254 /// extra detail when the same error is seen twice
255 pub obsolete_set: HashSet<ObsoleteSyntax>,
256 /// Used to determine the path to externally loaded source files
257 pub mod_path_stack: Vec<InternedString>,
258 /// Stack of spans of open delimiters. Used for error message.
259 pub open_braces: Vec<Span>,
260 /// Flag if this parser "owns" the directory that it is currently parsing
261 /// in. This will affect how nested files are looked up.
262 pub owns_directory: bool,
263 /// Name of the root module this parser originated from. If `None`, then the
264 /// name is not known. This does not change while the parser is descending
265 /// into modules, and sub-parsers have new values for this name.
266 pub root_module_name: Option<String>,
267 pub expected_tokens: Vec<TokenType>,
270 #[derive(PartialEq, Eq, Clone)]
273 Keyword(keywords::Keyword),
278 fn to_string(&self) -> String {
280 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
281 TokenType::Operator => "an operator".to_string(),
282 TokenType::Keyword(kw) => format!("`{}`", kw.to_name()),
287 fn is_plain_ident_or_underscore(t: &token::Token) -> bool {
288 t.is_plain_ident() || *t == token::Underscore
291 /// Information about the path to a module.
292 pub struct ModulePath {
294 pub path_exists: bool,
295 pub result: Result<ModulePathSuccess, ModulePathError>,
298 pub struct ModulePathSuccess {
299 pub path: ::std::path::PathBuf,
300 pub owns_directory: bool,
303 pub struct ModulePathError {
305 pub help_msg: String,
310 AttributesParsed(ThinAttributes),
311 AlreadyParsed(P<Expr>),
314 impl From<Option<ThinAttributes>> for LhsExpr {
315 fn from(o: Option<ThinAttributes>) -> Self {
316 if let Some(attrs) = o {
317 LhsExpr::AttributesParsed(attrs)
319 LhsExpr::NotYetParsed
324 impl From<P<Expr>> for LhsExpr {
325 fn from(expr: P<Expr>) -> Self {
326 LhsExpr::AlreadyParsed(expr)
330 impl<'a> Parser<'a> {
331 pub fn new(sess: &'a ParseSess,
332 cfg: ast::CrateConfig,
333 mut rdr: Box<Reader+'a>)
336 let tok0 = rdr.real_token();
338 let placeholder = TokenAndSpan {
339 tok: token::Underscore,
345 interner: token::get_ident_interner(),
352 last_token_interpolated: false,
362 restrictions: Restrictions::empty(),
364 obsolete_set: HashSet::new(),
365 mod_path_stack: Vec::new(),
366 open_braces: Vec::new(),
367 owns_directory: true,
368 root_module_name: None,
369 expected_tokens: Vec::new(),
373 /// Convert a token to a string using self's reader
374 pub fn token_to_string(token: &token::Token) -> String {
375 pprust::token_to_string(token)
378 /// Convert the current token to a string using self's reader
379 pub fn this_token_to_string(&self) -> String {
380 Parser::token_to_string(&self.token)
383 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
384 let token_str = Parser::token_to_string(t);
385 let last_span = self.last_span;
386 Err(self.span_fatal(last_span, &format!("unexpected token: `{}`", token_str)))
389 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
390 match self.expect_one_of(&[], &[]) {
392 Ok(_) => unreachable!(),
396 /// Expect and consume the token t. Signal an error if
397 /// the next token is not t.
398 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
399 if self.expected_tokens.is_empty() {
400 if self.token == *t {
404 let token_str = Parser::token_to_string(t);
405 let this_token_str = self.this_token_to_string();
406 Err(self.fatal(&format!("expected `{}`, found `{}`",
411 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
415 /// Expect next token to be edible or inedible token. If edible,
416 /// then consume it; if inedible, then return without consuming
417 /// anything. Signal a fatal error if next token is unexpected.
418 pub fn expect_one_of(&mut self,
419 edible: &[token::Token],
420 inedible: &[token::Token]) -> PResult<'a, ()>{
421 fn tokens_to_string(tokens: &[TokenType]) -> String {
422 let mut i = tokens.iter();
423 // This might be a sign we need a connect method on Iterator.
425 .map_or("".to_string(), |t| t.to_string());
426 i.enumerate().fold(b, |mut b, (i, ref a)| {
427 if tokens.len() > 2 && i == tokens.len() - 2 {
429 } else if tokens.len() == 2 && i == tokens.len() - 2 {
434 b.push_str(&*a.to_string());
438 if edible.contains(&self.token) {
441 } else if inedible.contains(&self.token) {
442 // leave it in the input
445 let mut expected = edible.iter()
446 .map(|x| TokenType::Token(x.clone()))
447 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
448 .chain(self.expected_tokens.iter().cloned())
449 .collect::<Vec<_>>();
450 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
452 let expect = tokens_to_string(&expected[..]);
453 let actual = self.this_token_to_string();
455 &(if expected.len() > 1 {
456 (format!("expected one of {}, found `{}`",
459 } else if expected.is_empty() {
460 (format!("unexpected token: `{}`",
463 (format!("expected {}, found `{}`",
471 /// Check for erroneous `ident { }`; if matches, signal error and
472 /// recover (without consuming any expected input token). Returns
473 /// true if and only if input was consumed for recovery.
474 pub fn check_for_erroneous_unit_struct_expecting(&mut self,
475 expected: &[token::Token])
477 if self.token == token::OpenDelim(token::Brace)
478 && expected.iter().all(|t| *t != token::OpenDelim(token::Brace))
479 && self.look_ahead(1, |t| *t == token::CloseDelim(token::Brace)) {
480 // matched; signal non-fatal error and recover.
481 let span = self.span;
482 self.span_err(span, "unit-like struct construction is written with no trailing `{ }`");
483 self.eat(&token::OpenDelim(token::Brace));
484 self.eat(&token::CloseDelim(token::Brace));
491 /// Commit to parsing a complete expression `e` expected to be
492 /// followed by some token from the set edible + inedible. Recover
493 /// from anticipated input errors, discarding erroneous characters.
494 pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token],
495 inedible: &[token::Token]) -> PResult<'a, ()> {
496 debug!("commit_expr {:?}", e);
497 if let ExprKind::Path(..) = e.node {
498 // might be unit-struct construction; check for recoverableinput error.
499 let expected = edible.iter()
501 .chain(inedible.iter().cloned())
502 .collect::<Vec<_>>();
503 self.check_for_erroneous_unit_struct_expecting(&expected[..]);
505 self.expect_one_of(edible, inedible)
508 pub fn commit_expr_expecting(&mut self, e: &Expr, edible: token::Token) -> PResult<'a, ()> {
509 self.commit_expr(e, &[edible], &[])
512 /// Commit to parsing a complete statement `s`, which expects to be
513 /// followed by some token from the set edible + inedible. Check
514 /// for recoverable input errors, discarding erroneous characters.
515 pub fn commit_stmt(&mut self, edible: &[token::Token],
516 inedible: &[token::Token]) -> PResult<'a, ()> {
519 .map_or(false, |t| t.is_ident() || t.is_path()) {
520 let expected = edible.iter()
522 .chain(inedible.iter().cloned())
523 .collect::<Vec<_>>();
524 self.check_for_erroneous_unit_struct_expecting(&expected);
526 self.expect_one_of(edible, inedible)
529 pub fn commit_stmt_expecting(&mut self, edible: token::Token) -> PResult<'a, ()> {
530 self.commit_stmt(&[edible], &[])
533 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
534 fn interpolated_or_expr_span(&self,
535 expr: PResult<'a, P<Expr>>)
536 -> PResult<'a, (Span, P<Expr>)> {
538 if self.last_token_interpolated {
546 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
547 self.check_strict_keywords();
548 self.check_reserved_keywords();
550 token::Ident(i, _) => {
554 token::Interpolated(token::NtIdent(..)) => {
555 self.bug("ident interpolation not converted to real token");
558 let token_str = self.this_token_to_string();
559 Err(self.fatal(&format!("expected ident, found `{}`",
565 pub fn parse_ident_or_self_type(&mut self) -> PResult<'a, ast::Ident> {
566 if self.is_self_type_ident() {
567 self.expect_self_type_ident()
573 pub fn parse_path_list_item(&mut self) -> PResult<'a, ast::PathListItem> {
574 let lo = self.span.lo;
575 let node = if self.eat_keyword(keywords::SelfValue) {
576 let rename = try!(self.parse_rename());
577 ast::PathListItemKind::Mod { id: ast::DUMMY_NODE_ID, rename: rename }
579 let ident = try!(self.parse_ident());
580 let rename = try!(self.parse_rename());
581 ast::PathListItemKind::Ident { name: ident, rename: rename, id: ast::DUMMY_NODE_ID }
583 let hi = self.last_span.hi;
584 Ok(spanned(lo, hi, node))
587 /// Check if the next token is `tok`, and return `true` if so.
589 /// This method is will automatically add `tok` to `expected_tokens` if `tok` is not
591 pub fn check(&mut self, tok: &token::Token) -> bool {
592 let is_present = self.token == *tok;
593 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
597 /// Consume token 'tok' if it exists. Returns true if the given
598 /// token was present, false otherwise.
599 pub fn eat(&mut self, tok: &token::Token) -> bool {
600 let is_present = self.check(tok);
601 if is_present { self.bump() }
605 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
606 self.expected_tokens.push(TokenType::Keyword(kw));
607 self.token.is_keyword(kw)
610 /// If the next token is the given keyword, eat it and return
611 /// true. Otherwise, return false.
612 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
613 if self.check_keyword(kw) {
621 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
622 if self.token.is_keyword(kw) {
630 /// If the given word is not a keyword, signal an error.
631 /// If the next token is not the given word, signal an error.
632 /// Otherwise, eat it.
633 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
634 if !self.eat_keyword(kw) {
641 /// Signal an error if the given string is a strict keyword
642 pub fn check_strict_keywords(&mut self) {
643 if self.token.is_strict_keyword() {
644 let token_str = self.this_token_to_string();
645 let span = self.span;
647 &format!("expected identifier, found keyword `{}`",
652 /// Signal an error if the current token is a reserved keyword
653 pub fn check_reserved_keywords(&mut self) {
654 if self.token.is_reserved_keyword() {
655 let token_str = self.this_token_to_string();
656 self.fatal(&format!("`{}` is a reserved keyword", token_str)).emit()
660 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
661 /// `&` and continue. If an `&` is not seen, signal an error.
662 fn expect_and(&mut self) -> PResult<'a, ()> {
663 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
665 token::BinOp(token::And) => {
670 let span = self.span;
671 let lo = span.lo + BytePos(1);
672 Ok(self.bump_with(token::BinOp(token::And), lo, span.hi))
674 _ => self.unexpected()
678 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
680 None => {/* everything ok */}
682 let text = suf.as_str();
684 self.span_bug(sp, "found empty literal suffix in Some")
686 self.span_err(sp, &*format!("{} with a suffix is invalid", kind));
692 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
693 /// `<` and continue. If a `<` is not seen, return false.
695 /// This is meant to be used when parsing generics on a path to get the
697 fn eat_lt(&mut self) -> bool {
698 self.expected_tokens.push(TokenType::Token(token::Lt));
704 token::BinOp(token::Shl) => {
705 let span = self.span;
706 let lo = span.lo + BytePos(1);
707 self.bump_with(token::Lt, lo, span.hi);
714 fn expect_lt(&mut self) -> PResult<'a, ()> {
722 /// Expect and consume a GT. if a >> is seen, replace it
723 /// with a single > and continue. If a GT is not seen,
725 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
726 self.expected_tokens.push(TokenType::Token(token::Gt));
732 token::BinOp(token::Shr) => {
733 let span = self.span;
734 let lo = span.lo + BytePos(1);
735 Ok(self.bump_with(token::Gt, lo, span.hi))
737 token::BinOpEq(token::Shr) => {
738 let span = self.span;
739 let lo = span.lo + BytePos(1);
740 Ok(self.bump_with(token::Ge, lo, span.hi))
743 let span = self.span;
744 let lo = span.lo + BytePos(1);
745 Ok(self.bump_with(token::Eq, lo, span.hi))
748 let gt_str = Parser::token_to_string(&token::Gt);
749 let this_token_str = self.this_token_to_string();
750 Err(self.fatal(&format!("expected `{}`, found `{}`",
757 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
758 sep: Option<token::Token>,
760 -> PResult<'a, (P<[T]>, bool)>
761 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
763 let mut v = Vec::new();
764 // This loop works by alternating back and forth between parsing types
765 // and commas. For example, given a string `A, B,>`, the parser would
766 // first parse `A`, then a comma, then `B`, then a comma. After that it
767 // would encounter a `>` and stop. This lets the parser handle trailing
768 // commas in generic parameters, because it can stop either after
769 // parsing a type or after parsing a comma.
771 if self.check(&token::Gt)
772 || self.token == token::BinOp(token::Shr)
773 || self.token == token::Ge
774 || self.token == token::BinOpEq(token::Shr) {
779 match try!(f(self)) {
780 Some(result) => v.push(result),
781 None => return Ok((P::from_vec(v), true))
784 if let Some(t) = sep.as_ref() {
785 try!(self.expect(t));
790 return Ok((P::from_vec(v), false));
793 /// Parse a sequence bracketed by '<' and '>', stopping
795 pub fn parse_seq_to_before_gt<T, F>(&mut self,
796 sep: Option<token::Token>,
798 -> PResult<'a, P<[T]>> where
799 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
801 let (result, returned) = try!(self.parse_seq_to_before_gt_or_return(sep,
802 |p| Ok(Some(try!(f(p))))));
807 pub fn parse_seq_to_gt<T, F>(&mut self,
808 sep: Option<token::Token>,
810 -> PResult<'a, P<[T]>> where
811 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
813 let v = try!(self.parse_seq_to_before_gt(sep, f));
814 try!(self.expect_gt());
818 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
819 sep: Option<token::Token>,
821 -> PResult<'a, (P<[T]>, bool)> where
822 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
824 let (v, returned) = try!(self.parse_seq_to_before_gt_or_return(sep, f));
826 try!(self.expect_gt());
828 return Ok((v, returned));
831 /// Parse a sequence, including the closing delimiter. The function
832 /// f must consume tokens until reaching the next separator or
834 pub fn parse_seq_to_end<T, F>(&mut self,
838 -> PResult<'a, Vec<T>> where
839 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
841 let val = try!(self.parse_seq_to_before_end(ket, sep, f));
846 /// Parse a sequence, not including the closing delimiter. The function
847 /// f must consume tokens until reaching the next separator or
849 pub fn parse_seq_to_before_end<T, F>(&mut self,
853 -> PResult<'a, Vec<T>> where
854 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
856 let mut first: bool = true;
858 while self.token != *ket {
861 if first { first = false; }
862 else { try!(self.expect(t)); }
866 if sep.trailing_sep_allowed && self.check(ket) { break; }
867 v.push(try!(f(self)));
872 /// Parse a sequence, including the closing delimiter. The function
873 /// f must consume tokens until reaching the next separator or
875 pub fn parse_unspanned_seq<T, F>(&mut self,
880 -> PResult<'a, Vec<T>> where
881 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
883 try!(self.expect(bra));
884 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
889 /// Parse a sequence parameter of enum variant. For consistency purposes,
890 /// these should not be empty.
891 pub fn parse_enum_variant_seq<T, F>(&mut self,
896 -> PResult<'a, Vec<T>> where
897 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
899 let result = try!(self.parse_unspanned_seq(bra, ket, sep, f));
900 if result.is_empty() {
901 let last_span = self.last_span;
902 self.span_err(last_span,
903 "nullary enum variants are written with no trailing `( )`");
908 // NB: Do not use this function unless you actually plan to place the
909 // spanned list in the AST.
910 pub fn parse_seq<T, F>(&mut self,
915 -> PResult<'a, Spanned<Vec<T>>> where
916 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
918 let lo = self.span.lo;
919 try!(self.expect(bra));
920 let result = try!(self.parse_seq_to_before_end(ket, sep, f));
921 let hi = self.span.hi;
923 Ok(spanned(lo, hi, result))
926 /// Advance the parser by one token
927 pub fn bump(&mut self) {
928 self.last_span = self.span;
929 // Stash token for error recovery (sometimes; clone is not necessarily cheap).
930 self.last_token = if self.token.is_ident() ||
931 self.token.is_path() ||
932 self.token == token::Comma {
933 Some(Box::new(self.token.clone()))
937 self.last_token_interpolated = self.token.is_interpolated();
938 let next = if self.buffer_start == self.buffer_end {
939 self.reader.real_token()
941 // Avoid token copies with `replace`.
942 let buffer_start = self.buffer_start as usize;
943 let next_index = (buffer_start + 1) & 3;
944 self.buffer_start = next_index as isize;
946 let placeholder = TokenAndSpan {
947 tok: token::Underscore,
950 mem::replace(&mut self.buffer[buffer_start], placeholder)
953 self.token = next.tok;
954 self.tokens_consumed += 1;
955 self.expected_tokens.clear();
956 // check after each token
957 self.check_unknown_macro_variable();
960 /// Advance the parser by one token and return the bumped token.
961 pub fn bump_and_get(&mut self) -> token::Token {
962 let old_token = mem::replace(&mut self.token, token::Underscore);
967 /// Advance the parser using provided token as a next one. Use this when
968 /// consuming a part of a token. For example a single `<` from `<<`.
969 pub fn bump_with(&mut self,
973 self.last_span = mk_sp(self.span.lo, lo);
974 // It would be incorrect to just stash current token, but fortunately
975 // for tokens currently using `bump_with`, last_token will be of no
977 self.last_token = None;
978 self.last_token_interpolated = false;
979 self.span = mk_sp(lo, hi);
981 self.expected_tokens.clear();
984 pub fn buffer_length(&mut self) -> isize {
985 if self.buffer_start <= self.buffer_end {
986 return self.buffer_end - self.buffer_start;
988 return (4 - self.buffer_start) + self.buffer_end;
990 pub fn look_ahead<R, F>(&mut self, distance: usize, f: F) -> R where
991 F: FnOnce(&token::Token) -> R,
993 let dist = distance as isize;
994 while self.buffer_length() < dist {
995 self.buffer[self.buffer_end as usize] = self.reader.real_token();
996 self.buffer_end = (self.buffer_end + 1) & 3;
998 f(&self.buffer[((self.buffer_start + dist - 1) & 3) as usize].tok)
1000 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1001 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1003 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1004 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1006 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1007 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1008 err.fileline_help(sp, help);
1011 pub fn bug(&self, m: &str) -> ! {
1012 self.sess.span_diagnostic.span_bug(self.span, m)
1014 pub fn warn(&self, m: &str) {
1015 self.sess.span_diagnostic.span_warn(self.span, m)
1017 pub fn span_warn(&self, sp: Span, m: &str) {
1018 self.sess.span_diagnostic.span_warn(sp, m)
1020 pub fn span_err(&self, sp: Span, m: &str) {
1021 self.sess.span_diagnostic.span_err(sp, m)
1023 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1024 self.sess.span_diagnostic.span_bug(sp, m)
1026 pub fn abort_if_errors(&self) {
1027 self.sess.span_diagnostic.abort_if_errors();
1030 pub fn diagnostic(&self) -> &'a errors::Handler {
1031 &self.sess.span_diagnostic
1034 pub fn id_to_interned_str(&mut self, id: Ident) -> InternedString {
1038 /// Is the current token one of the keywords that signals a bare function
1040 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1041 self.check_keyword(keywords::Fn) ||
1042 self.check_keyword(keywords::Unsafe) ||
1043 self.check_keyword(keywords::Extern)
1046 pub fn get_lifetime(&mut self) -> ast::Ident {
1048 token::Lifetime(ref ident) => *ident,
1049 _ => self.bug("not a lifetime"),
1053 pub fn parse_for_in_type(&mut self) -> PResult<'a, TyKind> {
1055 Parses whatever can come after a `for` keyword in a type.
1056 The `for` has already been consumed.
1060 - for <'lt> |S| -> T
1064 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1065 - for <'lt> path::foo(a, b)
1070 let lo = self.span.lo;
1072 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
1074 // examine next token to decide to do
1075 if self.token_is_bare_fn_keyword() {
1076 self.parse_ty_bare_fn(lifetime_defs)
1078 let hi = self.span.hi;
1079 let trait_ref = try!(self.parse_trait_ref());
1080 let poly_trait_ref = ast::PolyTraitRef { bound_lifetimes: lifetime_defs,
1081 trait_ref: trait_ref,
1082 span: mk_sp(lo, hi)};
1083 let other_bounds = if self.eat(&token::BinOp(token::Plus)) {
1084 try!(self.parse_ty_param_bounds(BoundParsingMode::Bare))
1089 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1090 .chain(other_bounds.into_vec())
1092 Ok(ast::TyKind::PolyTraitRef(all_bounds))
1096 pub fn parse_ty_path(&mut self) -> PResult<'a, TyKind> {
1097 Ok(TyKind::Path(None, try!(self.parse_path(LifetimeAndTypesWithoutColons))))
1100 /// parse a TyKind::BareFn type:
1101 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<ast::LifetimeDef>)
1102 -> PResult<'a, TyKind> {
1105 [unsafe] [extern "ABI"] fn <'lt> (S) -> T
1106 ^~~~^ ^~~~^ ^~~~^ ^~^ ^
1109 | | | Argument types
1115 let unsafety = try!(self.parse_unsafety());
1116 let abi = if self.eat_keyword(keywords::Extern) {
1117 try!(self.parse_opt_abi()).unwrap_or(Abi::C)
1122 try!(self.expect_keyword(keywords::Fn));
1123 let (inputs, variadic) = try!(self.parse_fn_args(false, true));
1124 let ret_ty = try!(self.parse_ret_ty());
1125 let decl = P(FnDecl {
1130 Ok(TyKind::BareFn(P(BareFnTy {
1133 lifetimes: lifetime_defs,
1138 /// Parses an obsolete closure kind (`&:`, `&mut:`, or `:`).
1139 pub fn parse_obsolete_closure_kind(&mut self) -> PResult<'a, ()> {
1140 let lo = self.span.lo;
1142 self.check(&token::BinOp(token::And)) &&
1143 self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
1144 self.look_ahead(2, |t| *t == token::Colon)
1150 self.token == token::BinOp(token::And) &&
1151 self.look_ahead(1, |t| *t == token::Colon)
1156 self.eat(&token::Colon)
1163 let span = mk_sp(lo, self.span.hi);
1164 self.obsolete(span, ObsoleteSyntax::ClosureKind);
1168 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1169 if self.eat_keyword(keywords::Unsafe) {
1170 return Ok(Unsafety::Unsafe);
1172 return Ok(Unsafety::Normal);
1176 /// Parse the items in a trait declaration
1177 pub fn parse_trait_items(&mut self) -> PResult<'a, Vec<P<TraitItem>>> {
1178 self.parse_unspanned_seq(
1179 &token::OpenDelim(token::Brace),
1180 &token::CloseDelim(token::Brace),
1182 |p| -> PResult<'a, P<TraitItem>> {
1183 maybe_whole!(no_clone p, NtTraitItem);
1184 let mut attrs = try!(p.parse_outer_attributes());
1187 let (name, node) = if p.eat_keyword(keywords::Type) {
1188 let TyParam {ident, bounds, default, ..} = try!(p.parse_ty_param());
1189 try!(p.expect(&token::Semi));
1190 (ident, TraitItemKind::Type(bounds, default))
1191 } else if p.is_const_item() {
1192 try!(p.expect_keyword(keywords::Const));
1193 let ident = try!(p.parse_ident());
1194 try!(p.expect(&token::Colon));
1195 let ty = try!(p.parse_ty_sum());
1196 let default = if p.check(&token::Eq) {
1198 let expr = try!(p.parse_expr());
1199 try!(p.commit_expr_expecting(&expr, token::Semi));
1202 try!(p.expect(&token::Semi));
1205 (ident, TraitItemKind::Const(ty, default))
1207 let (constness, unsafety, abi) = try!(p.parse_fn_front_matter());
1209 let ident = try!(p.parse_ident());
1210 let mut generics = try!(p.parse_generics());
1212 let (explicit_self, d) = try!(p.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1213 // This is somewhat dubious; We don't want to allow
1214 // argument names to be left off if there is a
1216 p.parse_arg_general(false)
1219 generics.where_clause = try!(p.parse_where_clause());
1220 let sig = ast::MethodSig {
1222 constness: constness,
1226 explicit_self: explicit_self,
1229 let body = match p.token {
1232 debug!("parse_trait_methods(): parsing required method");
1235 token::OpenDelim(token::Brace) => {
1236 debug!("parse_trait_methods(): parsing provided method");
1237 let (inner_attrs, body) =
1238 try!(p.parse_inner_attrs_and_block());
1239 attrs.extend(inner_attrs.iter().cloned());
1244 let token_str = p.this_token_to_string();
1245 return Err(p.fatal(&format!("expected `;` or `{{`, found `{}`",
1249 (ident, ast::TraitItemKind::Method(sig, body))
1253 id: ast::DUMMY_NODE_ID,
1257 span: mk_sp(lo, p.last_span.hi),
1262 /// Parse a possibly mutable type
1263 pub fn parse_mt(&mut self) -> PResult<'a, MutTy> {
1264 let mutbl = try!(self.parse_mutability());
1265 let t = try!(self.parse_ty());
1266 Ok(MutTy { ty: t, mutbl: mutbl })
1269 /// Parse optional return type [ -> TY ] in function decl
1270 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1271 if self.eat(&token::RArrow) {
1272 if self.eat(&token::Not) {
1273 Ok(FunctionRetTy::None(self.last_span))
1275 Ok(FunctionRetTy::Ty(try!(self.parse_ty())))
1278 let pos = self.span.lo;
1279 Ok(FunctionRetTy::Default(mk_sp(pos, pos)))
1283 /// Parse a type in a context where `T1+T2` is allowed.
1284 pub fn parse_ty_sum(&mut self) -> PResult<'a, P<Ty>> {
1285 let lo = self.span.lo;
1286 let lhs = try!(self.parse_ty());
1288 if !self.eat(&token::BinOp(token::Plus)) {
1292 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
1294 // In type grammar, `+` is treated like a binary operator,
1295 // and hence both L and R side are required.
1296 if bounds.is_empty() {
1297 let last_span = self.last_span;
1298 self.span_err(last_span,
1299 "at least one type parameter bound \
1300 must be specified");
1303 let sp = mk_sp(lo, self.last_span.hi);
1304 let sum = ast::TyKind::ObjectSum(lhs, bounds);
1305 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp}))
1309 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1310 maybe_whole!(no_clone self, NtTy);
1312 let lo = self.span.lo;
1314 let t = if self.check(&token::OpenDelim(token::Paren)) {
1317 // (t) is a parenthesized ty
1318 // (t,) is the type of a tuple with only one field,
1320 let mut ts = vec![];
1321 let mut last_comma = false;
1322 while self.token != token::CloseDelim(token::Paren) {
1323 ts.push(try!(self.parse_ty_sum()));
1324 if self.check(&token::Comma) {
1333 try!(self.expect(&token::CloseDelim(token::Paren)));
1334 if ts.len() == 1 && !last_comma {
1335 TyKind::Paren(ts.into_iter().nth(0).unwrap())
1339 } else if self.check(&token::BinOp(token::Star)) {
1340 // STAR POINTER (bare pointer?)
1342 TyKind::Ptr(try!(self.parse_ptr()))
1343 } else if self.check(&token::OpenDelim(token::Bracket)) {
1345 try!(self.expect(&token::OpenDelim(token::Bracket)));
1346 let t = try!(self.parse_ty_sum());
1348 // Parse the `; e` in `[ i32; e ]`
1349 // where `e` is a const expression
1350 let t = match try!(self.maybe_parse_fixed_length_of_vec()) {
1351 None => TyKind::Vec(t),
1352 Some(suffix) => TyKind::FixedLengthVec(t, suffix)
1354 try!(self.expect(&token::CloseDelim(token::Bracket)));
1356 } else if self.check(&token::BinOp(token::And)) ||
1357 self.token == token::AndAnd {
1359 try!(self.expect_and());
1360 try!(self.parse_borrowed_pointee())
1361 } else if self.check_keyword(keywords::For) {
1362 try!(self.parse_for_in_type())
1363 } else if self.token_is_bare_fn_keyword() {
1365 try!(self.parse_ty_bare_fn(Vec::new()))
1366 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1368 // In order to not be ambiguous, the type must be surrounded by parens.
1369 try!(self.expect(&token::OpenDelim(token::Paren)));
1370 let e = try!(self.parse_expr());
1371 try!(self.expect(&token::CloseDelim(token::Paren)));
1373 } else if self.eat_lt() {
1376 try!(self.parse_qualified_path(NoTypesAllowed));
1378 TyKind::Path(Some(qself), path)
1379 } else if self.check(&token::ModSep) ||
1380 self.token.is_ident() ||
1381 self.token.is_path() {
1382 let path = try!(self.parse_path(LifetimeAndTypesWithoutColons));
1383 if self.check(&token::Not) {
1386 let delim = try!(self.expect_open_delim());
1387 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
1389 |p| p.parse_token_tree()));
1390 let hi = self.span.hi;
1391 TyKind::Mac(spanned(lo, hi, Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT }))
1394 TyKind::Path(None, path)
1396 } else if self.eat(&token::Underscore) {
1397 // TYPE TO BE INFERRED
1400 let this_token_str = self.this_token_to_string();
1401 let msg = format!("expected type, found `{}`", this_token_str);
1402 return Err(self.fatal(&msg[..]));
1405 let sp = mk_sp(lo, self.last_span.hi);
1406 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp}))
1409 pub fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1410 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1411 let opt_lifetime = try!(self.parse_opt_lifetime());
1413 let mt = try!(self.parse_mt());
1414 return Ok(TyKind::Rptr(opt_lifetime, mt));
1417 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1418 let mutbl = if self.eat_keyword(keywords::Mut) {
1420 } else if self.eat_keyword(keywords::Const) {
1421 Mutability::Immutable
1423 let span = self.last_span;
1425 "bare raw pointers are no longer allowed, you should \
1426 likely use `*mut T`, but otherwise `*T` is now \
1427 known as `*const T`");
1428 Mutability::Immutable
1430 let t = try!(self.parse_ty());
1431 Ok(MutTy { ty: t, mutbl: mutbl })
1434 pub fn is_named_argument(&mut self) -> bool {
1435 let offset = match self.token {
1436 token::BinOp(token::And) => 1,
1438 _ if self.token.is_keyword(keywords::Mut) => 1,
1442 debug!("parser is_named_argument offset:{}", offset);
1445 is_plain_ident_or_underscore(&self.token)
1446 && self.look_ahead(1, |t| *t == token::Colon)
1448 self.look_ahead(offset, |t| is_plain_ident_or_underscore(t))
1449 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1453 /// This version of parse arg doesn't necessarily require
1454 /// identifier names.
1455 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1456 maybe_whole!(no_clone self, NtArg);
1458 let pat = if require_name || self.is_named_argument() {
1459 debug!("parse_arg_general parse_pat (require_name:{})",
1461 let pat = try!(self.parse_pat());
1463 try!(self.expect(&token::Colon));
1466 debug!("parse_arg_general ident_to_pat");
1467 ast_util::ident_to_pat(ast::DUMMY_NODE_ID,
1469 special_idents::invalid)
1472 let t = try!(self.parse_ty_sum());
1477 id: ast::DUMMY_NODE_ID,
1481 /// Parse a single function argument
1482 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1483 self.parse_arg_general(true)
1486 /// Parse an argument in a lambda header e.g. |arg, arg|
1487 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1488 let pat = try!(self.parse_pat());
1489 let t = if self.eat(&token::Colon) {
1490 try!(self.parse_ty_sum())
1493 id: ast::DUMMY_NODE_ID,
1494 node: TyKind::Infer,
1495 span: mk_sp(self.span.lo, self.span.hi),
1501 id: ast::DUMMY_NODE_ID
1505 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1506 if self.check(&token::Semi) {
1508 Ok(Some(try!(self.parse_expr())))
1514 /// Matches token_lit = LIT_INTEGER | ...
1515 pub fn lit_from_token(&self, tok: &token::Token) -> PResult<'a, LitKind> {
1517 token::Interpolated(token::NtExpr(ref v)) => {
1519 ExprKind::Lit(ref lit) => { Ok(lit.node.clone()) }
1520 _ => { return self.unexpected_last(tok); }
1523 token::Literal(lit, suf) => {
1524 let (suffix_illegal, out) = match lit {
1525 token::Byte(i) => (true, LitKind::Byte(parse::byte_lit(&i.as_str()).0)),
1526 token::Char(i) => (true, LitKind::Char(parse::char_lit(&i.as_str()).0)),
1528 // there are some valid suffixes for integer and
1529 // float literals, so all the handling is done
1531 token::Integer(s) => {
1532 (false, parse::integer_lit(&s.as_str(),
1533 suf.as_ref().map(|s| s.as_str()),
1534 &self.sess.span_diagnostic,
1537 token::Float(s) => {
1538 (false, parse::float_lit(&s.as_str(),
1539 suf.as_ref().map(|s| s.as_str()),
1540 &self.sess.span_diagnostic,
1546 LitKind::Str(token::intern_and_get_ident(&parse::str_lit(&s.as_str())),
1547 ast::StrStyle::Cooked))
1549 token::StrRaw(s, n) => {
1552 token::intern_and_get_ident(&parse::raw_str_lit(&s.as_str())),
1553 ast::StrStyle::Raw(n)))
1555 token::ByteStr(i) =>
1556 (true, LitKind::ByteStr(parse::byte_str_lit(&i.as_str()))),
1557 token::ByteStrRaw(i, _) =>
1559 LitKind::ByteStr(Rc::new(i.to_string().into_bytes()))),
1563 let sp = self.last_span;
1564 self.expect_no_suffix(sp, &*format!("{} literal", lit.short_name()), suf)
1569 _ => { return self.unexpected_last(tok); }
1573 /// Matches lit = true | false | token_lit
1574 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1575 let lo = self.span.lo;
1576 let lit = if self.eat_keyword(keywords::True) {
1578 } else if self.eat_keyword(keywords::False) {
1579 LitKind::Bool(false)
1581 let token = self.bump_and_get();
1582 let lit = try!(self.lit_from_token(&token));
1585 Ok(codemap::Spanned { node: lit, span: mk_sp(lo, self.last_span.hi) })
1588 /// matches '-' lit | lit
1589 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1590 let minus_lo = self.span.lo;
1591 let minus_present = self.eat(&token::BinOp(token::Minus));
1592 let lo = self.span.lo;
1593 let literal = P(try!(self.parse_lit()));
1594 let hi = self.last_span.hi;
1595 let expr = self.mk_expr(lo, hi, ExprKind::Lit(literal), None);
1598 let minus_hi = self.last_span.hi;
1599 let unary = self.mk_unary(UnOp::Neg, expr);
1600 Ok(self.mk_expr(minus_lo, minus_hi, unary, None))
1606 /// Parses qualified path.
1608 /// Assumes that the leading `<` has been parsed already.
1610 /// Qualifed paths are a part of the universal function call
1613 /// `qualified_path = <type [as trait_ref]>::path`
1615 /// See `parse_path` for `mode` meaning.
1620 /// `<T as U>::F::a::<S>`
1621 pub fn parse_qualified_path(&mut self, mode: PathParsingMode)
1622 -> PResult<'a, (QSelf, ast::Path)> {
1623 let span = self.last_span;
1624 let self_type = try!(self.parse_ty_sum());
1625 let mut path = if self.eat_keyword(keywords::As) {
1626 try!(self.parse_path(LifetimeAndTypesWithoutColons))
1637 position: path.segments.len()
1640 try!(self.expect(&token::Gt));
1641 try!(self.expect(&token::ModSep));
1643 let segments = match mode {
1644 LifetimeAndTypesWithoutColons => {
1645 try!(self.parse_path_segments_without_colons())
1647 LifetimeAndTypesWithColons => {
1648 try!(self.parse_path_segments_with_colons())
1651 try!(self.parse_path_segments_without_types())
1654 path.segments.extend(segments);
1656 path.span.hi = self.last_span.hi;
1661 /// Parses a path and optional type parameter bounds, depending on the
1662 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1663 /// bounds are permitted and whether `::` must precede type parameter
1665 pub fn parse_path(&mut self, mode: PathParsingMode) -> PResult<'a, ast::Path> {
1666 // Check for a whole path...
1667 let found = match self.token {
1668 token::Interpolated(token::NtPath(_)) => Some(self.bump_and_get()),
1671 if let Some(token::Interpolated(token::NtPath(path))) = found {
1675 let lo = self.span.lo;
1676 let is_global = self.eat(&token::ModSep);
1678 // Parse any number of segments and bound sets. A segment is an
1679 // identifier followed by an optional lifetime and a set of types.
1680 // A bound set is a set of type parameter bounds.
1681 let segments = match mode {
1682 LifetimeAndTypesWithoutColons => {
1683 try!(self.parse_path_segments_without_colons())
1685 LifetimeAndTypesWithColons => {
1686 try!(self.parse_path_segments_with_colons())
1689 try!(self.parse_path_segments_without_types())
1693 // Assemble the span.
1694 let span = mk_sp(lo, self.last_span.hi);
1696 // Assemble the result.
1705 /// - `a::b<T,U>::c<V,W>`
1706 /// - `a::b<T,U>::c(V) -> W`
1707 /// - `a::b<T,U>::c(V)`
1708 pub fn parse_path_segments_without_colons(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1709 let mut segments = Vec::new();
1711 // First, parse an identifier.
1712 let identifier = try!(self.parse_ident_or_self_type());
1714 // Parse types, optionally.
1715 let parameters = if self.eat_lt() {
1716 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1718 ast::PathParameters::AngleBracketed(ast::AngleBracketedParameterData {
1719 lifetimes: lifetimes,
1720 types: P::from_vec(types),
1721 bindings: P::from_vec(bindings),
1723 } else if self.eat(&token::OpenDelim(token::Paren)) {
1724 let lo = self.last_span.lo;
1726 let inputs = try!(self.parse_seq_to_end(
1727 &token::CloseDelim(token::Paren),
1728 seq_sep_trailing_allowed(token::Comma),
1729 |p| p.parse_ty_sum()));
1731 let output_ty = if self.eat(&token::RArrow) {
1732 Some(try!(self.parse_ty()))
1737 let hi = self.last_span.hi;
1739 ast::PathParameters::Parenthesized(ast::ParenthesizedParameterData {
1740 span: mk_sp(lo, hi),
1745 ast::PathParameters::none()
1748 // Assemble and push the result.
1749 segments.push(ast::PathSegment { identifier: identifier,
1750 parameters: parameters });
1752 // Continue only if we see a `::`
1753 if !self.eat(&token::ModSep) {
1754 return Ok(segments);
1760 /// - `a::b::<T,U>::c`
1761 pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1762 let mut segments = Vec::new();
1764 // First, parse an identifier.
1765 let identifier = try!(self.parse_ident_or_self_type());
1767 // If we do not see a `::`, stop.
1768 if !self.eat(&token::ModSep) {
1769 segments.push(ast::PathSegment {
1770 identifier: identifier,
1771 parameters: ast::PathParameters::none()
1773 return Ok(segments);
1776 // Check for a type segment.
1778 // Consumed `a::b::<`, go look for types
1779 let (lifetimes, types, bindings) = try!(self.parse_generic_values_after_lt());
1780 let parameters = ast::AngleBracketedParameterData {
1781 lifetimes: lifetimes,
1782 types: P::from_vec(types),
1783 bindings: P::from_vec(bindings),
1785 segments.push(ast::PathSegment {
1786 identifier: identifier,
1787 parameters: ast::PathParameters::AngleBracketed(parameters),
1790 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1791 if !self.eat(&token::ModSep) {
1792 return Ok(segments);
1795 // Consumed `a::`, go look for `b`
1796 segments.push(ast::PathSegment {
1797 identifier: identifier,
1798 parameters: ast::PathParameters::none(),
1807 pub fn parse_path_segments_without_types(&mut self) -> PResult<'a, Vec<ast::PathSegment>> {
1808 let mut segments = Vec::new();
1810 // First, parse an identifier.
1811 let identifier = try!(self.parse_ident_or_self_type());
1813 // Assemble and push the result.
1814 segments.push(ast::PathSegment {
1815 identifier: identifier,
1816 parameters: ast::PathParameters::none()
1819 // If we do not see a `::`, stop.
1820 if !self.eat(&token::ModSep) {
1821 return Ok(segments);
1826 /// parses 0 or 1 lifetime
1827 pub fn parse_opt_lifetime(&mut self) -> PResult<'a, Option<ast::Lifetime>> {
1829 token::Lifetime(..) => {
1830 Ok(Some(try!(self.parse_lifetime())))
1838 /// Parses a single lifetime
1839 /// Matches lifetime = LIFETIME
1840 pub fn parse_lifetime(&mut self) -> PResult<'a, ast::Lifetime> {
1842 token::Lifetime(i) => {
1843 let span = self.span;
1845 return Ok(ast::Lifetime {
1846 id: ast::DUMMY_NODE_ID,
1852 return Err(self.fatal("expected a lifetime name"));
1857 /// Parses `lifetime_defs = [ lifetime_defs { ',' lifetime_defs } ]` where `lifetime_def =
1858 /// lifetime [':' lifetimes]`
1859 pub fn parse_lifetime_defs(&mut self) -> PResult<'a, Vec<ast::LifetimeDef>> {
1861 let mut res = Vec::new();
1864 token::Lifetime(_) => {
1865 let lifetime = try!(self.parse_lifetime());
1867 if self.eat(&token::Colon) {
1868 try!(self.parse_lifetimes(token::BinOp(token::Plus)))
1872 res.push(ast::LifetimeDef { lifetime: lifetime,
1882 token::Comma => { self.bump();}
1883 token::Gt => { return Ok(res); }
1884 token::BinOp(token::Shr) => { return Ok(res); }
1886 let this_token_str = self.this_token_to_string();
1887 let msg = format!("expected `,` or `>` after lifetime \
1890 return Err(self.fatal(&msg[..]));
1896 /// matches lifetimes = ( lifetime ) | ( lifetime , lifetimes ) actually, it matches the empty
1897 /// one too, but putting that in there messes up the grammar....
1899 /// Parses zero or more comma separated lifetimes. Expects each lifetime to be followed by
1900 /// either a comma or `>`. Used when parsing type parameter lists, where we expect something
1901 /// like `<'a, 'b, T>`.
1902 pub fn parse_lifetimes(&mut self, sep: token::Token) -> PResult<'a, Vec<ast::Lifetime>> {
1904 let mut res = Vec::new();
1907 token::Lifetime(_) => {
1908 res.push(try!(self.parse_lifetime()));
1915 if self.token != sep {
1923 /// Parse mutability declaration (mut/const/imm)
1924 pub fn parse_mutability(&mut self) -> PResult<'a, Mutability> {
1925 if self.eat_keyword(keywords::Mut) {
1926 Ok(Mutability::Mutable)
1928 Ok(Mutability::Immutable)
1932 /// Parse ident COLON expr
1933 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1934 let lo = self.span.lo;
1935 let i = try!(self.parse_ident());
1936 let hi = self.last_span.hi;
1937 try!(self.expect(&token::Colon));
1938 let e = try!(self.parse_expr());
1940 ident: spanned(lo, hi, i),
1941 span: mk_sp(lo, e.span.hi),
1946 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos,
1947 node: ExprKind, attrs: ThinAttributes) -> P<Expr> {
1949 id: ast::DUMMY_NODE_ID,
1951 span: mk_sp(lo, hi),
1956 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
1957 ExprKind::Unary(unop, expr)
1960 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1961 ExprKind::Binary(binop, lhs, rhs)
1964 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
1965 ExprKind::Call(f, args)
1968 fn mk_method_call(&mut self,
1969 ident: ast::SpannedIdent,
1973 ExprKind::MethodCall(ident, tps, args)
1976 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
1977 ExprKind::Index(expr, idx)
1980 pub fn mk_range(&mut self,
1981 start: Option<P<Expr>>,
1982 end: Option<P<Expr>>)
1984 ExprKind::Range(start, end)
1987 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::ExprKind {
1988 ExprKind::Field(expr, ident)
1991 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
1992 ExprKind::TupField(expr, idx)
1995 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1996 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1997 ExprKind::AssignOp(binop, lhs, rhs)
2000 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos,
2001 m: Mac_, attrs: ThinAttributes) -> P<Expr> {
2003 id: ast::DUMMY_NODE_ID,
2004 node: ExprKind::Mac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
2005 span: mk_sp(lo, hi),
2010 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinAttributes) -> P<Expr> {
2011 let span = &self.span;
2012 let lv_lit = P(codemap::Spanned {
2013 node: LitKind::Int(i as u64, ast::LitIntType::Unsigned(UintTy::U32)),
2018 id: ast::DUMMY_NODE_ID,
2019 node: ExprKind::Lit(lv_lit),
2025 fn expect_open_delim(&mut self) -> PResult<'a, token::DelimToken> {
2026 self.expected_tokens.push(TokenType::Token(token::Gt));
2028 token::OpenDelim(delim) => {
2032 _ => Err(self.fatal("expected open delimiter")),
2036 /// At the bottom (top?) of the precedence hierarchy,
2037 /// parse things like parenthesized exprs,
2038 /// macros, return, etc.
2040 /// NB: This does not parse outer attributes,
2041 /// and is private because it only works
2042 /// correctly if called from parse_dot_or_call_expr().
2043 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2044 maybe_whole_expr!(self);
2046 // Outer attributes are already parsed and will be
2047 // added to the return value after the fact.
2049 // Therefore, prevent sub-parser from parsing
2050 // attributes by giving them a empty "already parsed" list.
2051 let mut attrs = None;
2053 let lo = self.span.lo;
2054 let mut hi = self.span.hi;
2058 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2060 token::OpenDelim(token::Paren) => {
2063 let attrs = try!(self.parse_inner_attributes())
2067 // (e) is parenthesized e
2068 // (e,) is a tuple with only one field, e
2069 let mut es = vec![];
2070 let mut trailing_comma = false;
2071 while self.token != token::CloseDelim(token::Paren) {
2072 es.push(try!(self.parse_expr()));
2073 try!(self.commit_expr(&**es.last().unwrap(), &[],
2074 &[token::Comma, token::CloseDelim(token::Paren)]));
2075 if self.check(&token::Comma) {
2076 trailing_comma = true;
2080 trailing_comma = false;
2086 hi = self.last_span.hi;
2087 return if es.len() == 1 && !trailing_comma {
2088 Ok(self.mk_expr(lo, hi, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs))
2090 Ok(self.mk_expr(lo, hi, ExprKind::Tup(es), attrs))
2093 token::OpenDelim(token::Brace) => {
2094 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2096 token::BinOp(token::Or) | token::OrOr => {
2097 let lo = self.span.lo;
2098 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2100 token::Ident(id @ ast::Ident {
2101 name: token::SELF_KEYWORD_NAME,
2103 }, token::Plain) => {
2105 let path = ast_util::ident_to_path(mk_sp(lo, hi), id);
2106 ex = ExprKind::Path(None, path);
2107 hi = self.last_span.hi;
2109 token::OpenDelim(token::Bracket) => {
2112 let inner_attrs = try!(self.parse_inner_attributes())
2114 attrs.update(|attrs| attrs.append(inner_attrs));
2116 if self.check(&token::CloseDelim(token::Bracket)) {
2119 ex = ExprKind::Vec(Vec::new());
2122 let first_expr = try!(self.parse_expr());
2123 if self.check(&token::Semi) {
2124 // Repeating array syntax: [ 0; 512 ]
2126 let count = try!(self.parse_expr());
2127 try!(self.expect(&token::CloseDelim(token::Bracket)));
2128 ex = ExprKind::Repeat(first_expr, count);
2129 } else if self.check(&token::Comma) {
2130 // Vector with two or more elements.
2132 let remaining_exprs = try!(self.parse_seq_to_end(
2133 &token::CloseDelim(token::Bracket),
2134 seq_sep_trailing_allowed(token::Comma),
2135 |p| Ok(try!(p.parse_expr()))
2137 let mut exprs = vec!(first_expr);
2138 exprs.extend(remaining_exprs);
2139 ex = ExprKind::Vec(exprs);
2141 // Vector with one element.
2142 try!(self.expect(&token::CloseDelim(token::Bracket)));
2143 ex = ExprKind::Vec(vec!(first_expr));
2146 hi = self.last_span.hi;
2151 try!(self.parse_qualified_path(LifetimeAndTypesWithColons));
2153 return Ok(self.mk_expr(lo, hi, ExprKind::Path(Some(qself), path), attrs));
2155 if self.eat_keyword(keywords::Move) {
2156 let lo = self.last_span.lo;
2157 return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2159 if self.eat_keyword(keywords::If) {
2160 return self.parse_if_expr(attrs);
2162 if self.eat_keyword(keywords::For) {
2163 let lo = self.last_span.lo;
2164 return self.parse_for_expr(None, lo, attrs);
2166 if self.eat_keyword(keywords::While) {
2167 let lo = self.last_span.lo;
2168 return self.parse_while_expr(None, lo, attrs);
2170 if self.token.is_lifetime() {
2171 let lifetime = self.get_lifetime();
2172 let lo = self.span.lo;
2174 try!(self.expect(&token::Colon));
2175 if self.eat_keyword(keywords::While) {
2176 return self.parse_while_expr(Some(lifetime), lo, attrs)
2178 if self.eat_keyword(keywords::For) {
2179 return self.parse_for_expr(Some(lifetime), lo, attrs)
2181 if self.eat_keyword(keywords::Loop) {
2182 return self.parse_loop_expr(Some(lifetime), lo, attrs)
2184 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2186 if self.eat_keyword(keywords::Loop) {
2187 let lo = self.last_span.lo;
2188 return self.parse_loop_expr(None, lo, attrs);
2190 if self.eat_keyword(keywords::Continue) {
2191 let ex = if self.token.is_lifetime() {
2192 let ex = ExprKind::Again(Some(Spanned{
2193 node: self.get_lifetime(),
2199 ExprKind::Again(None)
2201 let hi = self.last_span.hi;
2202 return Ok(self.mk_expr(lo, hi, ex, attrs));
2204 if self.eat_keyword(keywords::Match) {
2205 return self.parse_match_expr(attrs);
2207 if self.eat_keyword(keywords::Unsafe) {
2208 return self.parse_block_expr(
2210 BlockCheckMode::Unsafe(ast::UserProvided),
2213 if self.eat_keyword(keywords::Return) {
2214 if self.token.can_begin_expr() {
2215 let e = try!(self.parse_expr());
2217 ex = ExprKind::Ret(Some(e));
2219 ex = ExprKind::Ret(None);
2221 } else if self.eat_keyword(keywords::Break) {
2222 if self.token.is_lifetime() {
2223 ex = ExprKind::Break(Some(Spanned {
2224 node: self.get_lifetime(),
2229 ex = ExprKind::Break(None);
2231 hi = self.last_span.hi;
2232 } else if self.token.is_keyword(keywords::Let) {
2233 // Catch this syntax error here, instead of in `check_strict_keywords`, so
2234 // that we can explicitly mention that let is not to be used as an expression
2235 let mut db = self.fatal("expected expression, found statement (`let`)");
2236 db.note("variable declaration using `let` is a statement");
2238 } else if self.check(&token::ModSep) ||
2239 self.token.is_ident() &&
2240 !self.check_keyword(keywords::True) &&
2241 !self.check_keyword(keywords::False) {
2243 try!(self.parse_path(LifetimeAndTypesWithColons));
2245 // `!`, as an operator, is prefix, so we know this isn't that
2246 if self.check(&token::Not) {
2247 // MACRO INVOCATION expression
2250 let delim = try!(self.expect_open_delim());
2251 let tts = try!(self.parse_seq_to_end(
2252 &token::CloseDelim(delim),
2254 |p| p.parse_token_tree()));
2255 let hi = self.last_span.hi;
2257 return Ok(self.mk_mac_expr(lo,
2259 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT },
2262 if self.check(&token::OpenDelim(token::Brace)) {
2263 // This is a struct literal, unless we're prohibited
2264 // from parsing struct literals here.
2265 let prohibited = self.restrictions.contains(
2266 Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2269 // It's a struct literal.
2271 let mut fields = Vec::new();
2272 let mut base = None;
2274 let attrs = attrs.append(
2275 try!(self.parse_inner_attributes())
2276 .into_thin_attrs());
2278 while self.token != token::CloseDelim(token::Brace) {
2279 if self.eat(&token::DotDot) {
2280 base = Some(try!(self.parse_expr()));
2284 fields.push(try!(self.parse_field()));
2285 try!(self.commit_expr(&*fields.last().unwrap().expr,
2287 &[token::CloseDelim(token::Brace)]));
2291 try!(self.expect(&token::CloseDelim(token::Brace)));
2292 ex = ExprKind::Struct(pth, fields, base);
2293 return Ok(self.mk_expr(lo, hi, ex, attrs));
2298 ex = ExprKind::Path(None, pth);
2300 // other literal expression
2301 let lit = try!(self.parse_lit());
2303 ex = ExprKind::Lit(P(lit));
2308 return Ok(self.mk_expr(lo, hi, ex, attrs));
2311 fn parse_or_use_outer_attributes(&mut self,
2312 already_parsed_attrs: Option<ThinAttributes>)
2313 -> PResult<'a, ThinAttributes> {
2314 if let Some(attrs) = already_parsed_attrs {
2317 self.parse_outer_attributes().map(|a| a.into_thin_attrs())
2321 /// Parse a block or unsafe block
2322 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode,
2323 attrs: ThinAttributes)
2324 -> PResult<'a, P<Expr>> {
2326 let outer_attrs = attrs;
2327 try!(self.expect(&token::OpenDelim(token::Brace)));
2329 let inner_attrs = try!(self.parse_inner_attributes()).into_thin_attrs();
2330 let attrs = outer_attrs.append(inner_attrs);
2332 let blk = try!(self.parse_block_tail(lo, blk_mode));
2333 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprKind::Block(blk), attrs));
2336 /// parse a.b or a(13) or a[4] or just a
2337 pub fn parse_dot_or_call_expr(&mut self,
2338 already_parsed_attrs: Option<ThinAttributes>)
2339 -> PResult<'a, P<Expr>> {
2340 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2342 let b = self.parse_bottom_expr();
2343 let (span, b) = try!(self.interpolated_or_expr_span(b));
2344 self.parse_dot_or_call_expr_with(b, span.lo, attrs)
2347 pub fn parse_dot_or_call_expr_with(&mut self,
2350 attrs: ThinAttributes)
2351 -> PResult<'a, P<Expr>> {
2352 // Stitch the list of outer attributes onto the return value.
2353 // A little bit ugly, but the best way given the current code
2355 self.parse_dot_or_call_expr_with_(e0, lo)
2357 expr.map(|mut expr| {
2358 expr.attrs.update(|a| a.prepend(attrs));
2360 ExprKind::If(..) | ExprKind::IfLet(..) => {
2361 if !expr.attrs.as_attr_slice().is_empty() {
2362 // Just point to the first attribute in there...
2363 let span = expr.attrs.as_attr_slice()[0].span;
2366 "attributes are not yet allowed on `if` \
2377 // Assuming we have just parsed `.foo` (i.e., a dot and an ident), continue
2378 // parsing into an expression.
2379 fn parse_dot_suffix(&mut self,
2382 self_value: P<Expr>,
2384 -> PResult<'a, P<Expr>> {
2385 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2386 try!(self.expect_lt());
2387 try!(self.parse_generic_values_after_lt())
2389 (Vec::new(), Vec::new(), Vec::new())
2392 if !bindings.is_empty() {
2393 let last_span = self.last_span;
2394 self.span_err(last_span, "type bindings are only permitted on trait paths");
2397 Ok(match self.token {
2398 // expr.f() method call.
2399 token::OpenDelim(token::Paren) => {
2400 let mut es = try!(self.parse_unspanned_seq(
2401 &token::OpenDelim(token::Paren),
2402 &token::CloseDelim(token::Paren),
2403 seq_sep_trailing_allowed(token::Comma),
2404 |p| Ok(try!(p.parse_expr()))
2406 let hi = self.last_span.hi;
2408 es.insert(0, self_value);
2409 let id = spanned(ident_span.lo, ident_span.hi, ident);
2410 let nd = self.mk_method_call(id, tys, es);
2411 self.mk_expr(lo, hi, nd, None)
2415 if !tys.is_empty() {
2416 let last_span = self.last_span;
2417 self.span_err(last_span,
2418 "field expressions may not \
2419 have type parameters");
2422 let id = spanned(ident_span.lo, ident_span.hi, ident);
2423 let field = self.mk_field(self_value, id);
2424 self.mk_expr(lo, ident_span.hi, field, None)
2429 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: BytePos) -> PResult<'a, P<Expr>> {
2434 if self.eat(&token::Dot) {
2436 token::Ident(i, _) => {
2437 let dot_pos = self.last_span.hi;
2441 e = try!(self.parse_dot_suffix(i, mk_sp(dot_pos, hi), e, lo));
2443 token::Literal(token::Integer(n), suf) => {
2446 // A tuple index may not have a suffix
2447 self.expect_no_suffix(sp, "tuple index", suf);
2449 let dot = self.last_span.hi;
2453 let index = n.as_str().parse::<usize>().ok();
2456 let id = spanned(dot, hi, n);
2457 let field = self.mk_tup_field(e, id);
2458 e = self.mk_expr(lo, hi, field, None);
2461 let last_span = self.last_span;
2462 self.span_err(last_span, "invalid tuple or tuple struct index");
2466 token::Literal(token::Float(n), _suf) => {
2468 let last_span = self.last_span;
2469 let fstr = n.as_str();
2470 let mut err = self.diagnostic().struct_span_err(last_span,
2471 &format!("unexpected token: `{}`", n.as_str()));
2472 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2473 let float = match fstr.parse::<f64>().ok() {
2477 err.fileline_help(last_span,
2478 &format!("try parenthesizing the first index; e.g., `(foo.{}){}`",
2479 float.trunc() as usize,
2480 format!(".{}", fstr.splitn(2, ".").last().unwrap())));
2486 // FIXME Could factor this out into non_fatal_unexpected or something.
2487 let actual = self.this_token_to_string();
2488 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2490 let dot_pos = self.last_span.hi;
2491 e = try!(self.parse_dot_suffix(special_idents::invalid,
2492 mk_sp(dot_pos, dot_pos),
2498 if self.expr_is_complete(&*e) { break; }
2501 token::OpenDelim(token::Paren) => {
2502 let es = try!(self.parse_unspanned_seq(
2503 &token::OpenDelim(token::Paren),
2504 &token::CloseDelim(token::Paren),
2505 seq_sep_trailing_allowed(token::Comma),
2506 |p| Ok(try!(p.parse_expr()))
2508 hi = self.last_span.hi;
2510 let nd = self.mk_call(e, es);
2511 e = self.mk_expr(lo, hi, nd, None);
2515 // Could be either an index expression or a slicing expression.
2516 token::OpenDelim(token::Bracket) => {
2518 let ix = try!(self.parse_expr());
2520 try!(self.commit_expr_expecting(&*ix, token::CloseDelim(token::Bracket)));
2521 let index = self.mk_index(e, ix);
2522 e = self.mk_expr(lo, hi, index, None)
2530 // Parse unquoted tokens after a `$` in a token tree
2531 fn parse_unquoted(&mut self) -> PResult<'a, TokenTree> {
2532 let mut sp = self.span;
2533 let (name, namep) = match self.token {
2537 if self.token == token::OpenDelim(token::Paren) {
2538 let Spanned { node: seq, span: seq_span } = try!(self.parse_seq(
2539 &token::OpenDelim(token::Paren),
2540 &token::CloseDelim(token::Paren),
2542 |p| p.parse_token_tree()
2544 let (sep, repeat) = try!(self.parse_sep_and_kleene_op());
2545 let name_num = macro_parser::count_names(&seq);
2546 return Ok(TokenTree::Sequence(mk_sp(sp.lo, seq_span.hi),
2547 Rc::new(SequenceRepetition {
2551 num_captures: name_num
2553 } else if self.token.is_keyword_allow_following_colon(keywords::Crate) {
2555 return Ok(TokenTree::Token(sp, SpecialVarNt(SpecialMacroVar::CrateMacroVar)));
2557 sp = mk_sp(sp.lo, self.span.hi);
2558 let namep = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2559 let name = try!(self.parse_ident());
2563 token::SubstNt(name, namep) => {
2569 // continue by trying to parse the `:ident` after `$name`
2570 if self.token == token::Colon && self.look_ahead(1, |t| t.is_ident() &&
2571 !t.is_strict_keyword() &&
2572 !t.is_reserved_keyword()) {
2574 sp = mk_sp(sp.lo, self.span.hi);
2575 let kindp = match self.token { token::Ident(_, p) => p, _ => token::Plain };
2576 let nt_kind = try!(self.parse_ident());
2577 Ok(TokenTree::Token(sp, MatchNt(name, nt_kind, namep, kindp)))
2579 Ok(TokenTree::Token(sp, SubstNt(name, namep)))
2583 pub fn check_unknown_macro_variable(&mut self) {
2584 if self.quote_depth == 0 {
2586 token::SubstNt(name, _) =>
2587 self.fatal(&format!("unknown macro variable `{}`", name)).emit(),
2593 /// Parse an optional separator followed by a Kleene-style
2594 /// repetition token (+ or *).
2595 pub fn parse_sep_and_kleene_op(&mut self)
2596 -> PResult<'a, (Option<token::Token>, ast::KleeneOp)> {
2597 fn parse_kleene_op<'a>(parser: &mut Parser<'a>) -> PResult<'a, Option<ast::KleeneOp>> {
2598 match parser.token {
2599 token::BinOp(token::Star) => {
2601 Ok(Some(ast::KleeneOp::ZeroOrMore))
2603 token::BinOp(token::Plus) => {
2605 Ok(Some(ast::KleeneOp::OneOrMore))
2611 match try!(parse_kleene_op(self)) {
2612 Some(kleene_op) => return Ok((None, kleene_op)),
2616 let separator = self.bump_and_get();
2617 match try!(parse_kleene_op(self)) {
2618 Some(zerok) => Ok((Some(separator), zerok)),
2619 None => return Err(self.fatal("expected `*` or `+`"))
2623 /// parse a single token tree from the input.
2624 pub fn parse_token_tree(&mut self) -> PResult<'a, TokenTree> {
2625 // FIXME #6994: currently, this is too eager. It
2626 // parses token trees but also identifies TokenType::Sequence's
2627 // and token::SubstNt's; it's too early to know yet
2628 // whether something will be a nonterminal or a seq
2630 maybe_whole!(deref self, NtTT);
2632 // this is the fall-through for the 'match' below.
2633 // invariants: the current token is not a left-delimiter,
2634 // not an EOF, and not the desired right-delimiter (if
2635 // it were, parse_seq_to_before_end would have prevented
2636 // reaching this point.
2637 fn parse_non_delim_tt_tok<'b>(p: &mut Parser<'b>) -> PResult<'b, TokenTree> {
2638 maybe_whole!(deref p, NtTT);
2640 token::CloseDelim(_) => {
2641 let token_str = p.this_token_to_string();
2642 let mut err = p.fatal(
2643 &format!("incorrect close delimiter: `{}`", token_str));
2644 // This is a conservative error: only report the last unclosed delimiter. The
2645 // previous unclosed delimiters could actually be closed! The parser just hasn't
2646 // gotten to them yet.
2647 if let Some(&sp) = p.open_braces.last() {
2648 err.span_note(sp, "unclosed delimiter");
2652 /* we ought to allow different depths of unquotation */
2653 token::Dollar | token::SubstNt(..) if p.quote_depth > 0 => {
2657 Ok(TokenTree::Token(p.span, p.bump_and_get()))
2664 let open_braces = self.open_braces.clone();
2665 let mut err: DiagnosticBuilder<'a> =
2666 self.fatal("this file contains an un-closed delimiter");
2667 for sp in &open_braces {
2668 err.span_help(*sp, "did you mean to close this delimiter?");
2672 token::OpenDelim(delim) => {
2673 // The span for beginning of the delimited section
2674 let pre_span = self.span;
2676 // Parse the open delimiter.
2677 self.open_braces.push(self.span);
2678 let open_span = self.span;
2681 // Parse the token trees within the delimiters
2682 let tts = try!(self.parse_seq_to_before_end(
2683 &token::CloseDelim(delim),
2685 |p| p.parse_token_tree()
2688 // Parse the close delimiter.
2689 let close_span = self.span;
2691 self.open_braces.pop().unwrap();
2693 // Expand to cover the entire delimited token tree
2694 let span = Span { hi: close_span.hi, ..pre_span };
2696 Ok(TokenTree::Delimited(span, Rc::new(Delimited {
2698 open_span: open_span,
2700 close_span: close_span,
2703 _ => parse_non_delim_tt_tok(self),
2707 // parse a stream of tokens into a list of TokenTree's,
2709 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2710 let mut tts = Vec::new();
2711 while self.token != token::Eof {
2712 tts.push(try!(self.parse_token_tree()));
2717 /// Parse a prefix-unary-operator expr
2718 pub fn parse_prefix_expr(&mut self,
2719 already_parsed_attrs: Option<ThinAttributes>)
2720 -> PResult<'a, P<Expr>> {
2721 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2722 let lo = self.span.lo;
2724 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2725 let ex = match self.token {
2728 let e = self.parse_prefix_expr(None);
2729 let (span, e) = try!(self.interpolated_or_expr_span(e));
2731 self.mk_unary(UnOp::Not, e)
2733 token::BinOp(token::Minus) => {
2735 let e = self.parse_prefix_expr(None);
2736 let (span, e) = try!(self.interpolated_or_expr_span(e));
2738 self.mk_unary(UnOp::Neg, e)
2740 token::BinOp(token::Star) => {
2742 let e = self.parse_prefix_expr(None);
2743 let (span, e) = try!(self.interpolated_or_expr_span(e));
2745 self.mk_unary(UnOp::Deref, e)
2747 token::BinOp(token::And) | token::AndAnd => {
2748 try!(self.expect_and());
2749 let m = try!(self.parse_mutability());
2750 let e = self.parse_prefix_expr(None);
2751 let (span, e) = try!(self.interpolated_or_expr_span(e));
2753 ExprKind::AddrOf(m, e)
2755 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2757 let place = try!(self.parse_expr_res(
2758 Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
2761 let blk = try!(self.parse_block());
2762 let span = blk.span;
2764 let blk_expr = self.mk_expr(span.lo, span.hi, ExprKind::Block(blk),
2766 ExprKind::InPlace(place, blk_expr)
2768 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2770 let e = self.parse_prefix_expr(None);
2771 let (span, e) = try!(self.interpolated_or_expr_span(e));
2775 _ => return self.parse_dot_or_call_expr(Some(attrs))
2777 return Ok(self.mk_expr(lo, hi, ex, attrs));
2780 /// Parse an associative expression
2782 /// This parses an expression accounting for associativity and precedence of the operators in
2784 pub fn parse_assoc_expr(&mut self,
2785 already_parsed_attrs: Option<ThinAttributes>)
2786 -> PResult<'a, P<Expr>> {
2787 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2790 /// Parse an associative expression with operators of at least `min_prec` precedence
2791 pub fn parse_assoc_expr_with(&mut self,
2794 -> PResult<'a, P<Expr>> {
2795 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2798 let attrs = match lhs {
2799 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2802 if self.token == token::DotDot {
2803 return self.parse_prefix_range_expr(attrs);
2805 try!(self.parse_prefix_expr(attrs))
2810 if self.expr_is_complete(&*lhs) {
2811 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2814 self.expected_tokens.push(TokenType::Operator);
2815 while let Some(op) = AssocOp::from_token(&self.token) {
2817 let lhs_span = if self.last_token_interpolated {
2823 let cur_op_span = self.span;
2824 let restrictions = if op.is_assign_like() {
2825 self.restrictions & Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2829 if op.precedence() < min_prec {
2833 if op.is_comparison() {
2834 self.check_no_chained_comparison(&*lhs, &op);
2837 if op == AssocOp::As {
2838 let rhs = try!(self.parse_ty());
2839 lhs = self.mk_expr(lhs_span.lo, rhs.span.hi,
2840 ExprKind::Cast(lhs, rhs), None);
2842 } else if op == AssocOp::Colon {
2843 let rhs = try!(self.parse_ty());
2844 lhs = self.mk_expr(lhs_span.lo, rhs.span.hi,
2845 ExprKind::Type(lhs, rhs), None);
2847 } else if op == AssocOp::DotDot {
2848 // If we didn’t have to handle `x..`, it would be pretty easy to generalise
2849 // it to the Fixity::None code.
2851 // We have 2 alternatives here: `x..y` and `x..` The other two variants are
2852 // handled with `parse_prefix_range_expr` call above.
2853 let rhs = if self.is_at_start_of_range_notation_rhs() {
2854 let rhs = self.parse_assoc_expr_with(op.precedence() + 1,
2855 LhsExpr::NotYetParsed);
2866 let (lhs_span, rhs_span) = (lhs_span, if let Some(ref x) = rhs {
2871 let r = self.mk_range(Some(lhs), rhs);
2872 lhs = self.mk_expr(lhs_span.lo, rhs_span.hi, r, None);
2876 let rhs = try!(match op.fixity() {
2877 Fixity::Right => self.with_res(
2878 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2880 this.parse_assoc_expr_with(op.precedence(),
2881 LhsExpr::NotYetParsed)
2883 Fixity::Left => self.with_res(
2884 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2886 this.parse_assoc_expr_with(op.precedence() + 1,
2887 LhsExpr::NotYetParsed)
2889 // We currently have no non-associative operators that are not handled above by
2890 // the special cases. The code is here only for future convenience.
2891 Fixity::None => self.with_res(
2892 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2894 this.parse_assoc_expr_with(op.precedence() + 1,
2895 LhsExpr::NotYetParsed)
2900 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2901 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2902 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2903 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2904 AssocOp::Greater | AssocOp::GreaterEqual => {
2905 let ast_op = op.to_ast_binop().unwrap();
2906 let (lhs_span, rhs_span) = (lhs_span, rhs.span);
2907 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2908 self.mk_expr(lhs_span.lo, rhs_span.hi, binary, None)
2911 self.mk_expr(lhs_span.lo, rhs.span.hi, ExprKind::Assign(lhs, rhs), None),
2913 self.mk_expr(lhs_span.lo, rhs.span.hi, ExprKind::InPlace(lhs, rhs), None),
2914 AssocOp::AssignOp(k) => {
2916 token::Plus => BinOpKind::Add,
2917 token::Minus => BinOpKind::Sub,
2918 token::Star => BinOpKind::Mul,
2919 token::Slash => BinOpKind::Div,
2920 token::Percent => BinOpKind::Rem,
2921 token::Caret => BinOpKind::BitXor,
2922 token::And => BinOpKind::BitAnd,
2923 token::Or => BinOpKind::BitOr,
2924 token::Shl => BinOpKind::Shl,
2925 token::Shr => BinOpKind::Shr,
2927 let (lhs_span, rhs_span) = (lhs_span, rhs.span);
2928 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2929 self.mk_expr(lhs_span.lo, rhs_span.hi, aopexpr, None)
2931 AssocOp::As | AssocOp::Colon | AssocOp::DotDot => {
2932 self.bug("As, Colon or DotDot branch reached")
2936 if op.fixity() == Fixity::None { break }
2941 /// Produce an error if comparison operators are chained (RFC #558).
2942 /// We only need to check lhs, not rhs, because all comparison ops
2943 /// have same precedence and are left-associative
2944 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2945 debug_assert!(outer_op.is_comparison());
2947 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
2948 // respan to include both operators
2949 let op_span = mk_sp(op.span.lo, self.span.hi);
2950 let mut err = self.diagnostic().struct_span_err(op_span,
2951 "chained comparison operators require parentheses");
2952 if op.node == BinOpKind::Lt && *outer_op == AssocOp::Greater {
2953 err.fileline_help(op_span,
2954 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2962 /// Parse prefix-forms of range notation: `..expr` and `..`
2963 fn parse_prefix_range_expr(&mut self,
2964 already_parsed_attrs: Option<ThinAttributes>)
2965 -> PResult<'a, P<Expr>> {
2966 debug_assert!(self.token == token::DotDot);
2967 let attrs = try!(self.parse_or_use_outer_attributes(already_parsed_attrs));
2968 let lo = self.span.lo;
2969 let mut hi = self.span.hi;
2971 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2972 // RHS must be parsed with more associativity than DotDot.
2973 let next_prec = AssocOp::from_token(&token::DotDot).unwrap().precedence() + 1;
2974 Some(try!(self.parse_assoc_expr_with(next_prec,
2975 LhsExpr::NotYetParsed)
2983 let r = self.mk_range(None, opt_end);
2984 Ok(self.mk_expr(lo, hi, r, attrs))
2987 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2988 if self.token.can_begin_expr() {
2989 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2990 if self.token == token::OpenDelim(token::Brace) {
2991 return !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL);
2999 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3000 pub fn parse_if_expr(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3001 if self.check_keyword(keywords::Let) {
3002 return self.parse_if_let_expr(attrs);
3004 let lo = self.last_span.lo;
3005 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3006 let thn = try!(self.parse_block());
3007 let mut els: Option<P<Expr>> = None;
3008 let mut hi = thn.span.hi;
3009 if self.eat_keyword(keywords::Else) {
3010 let elexpr = try!(self.parse_else_expr());
3011 hi = elexpr.span.hi;
3014 Ok(self.mk_expr(lo, hi, ExprKind::If(cond, thn, els), attrs))
3017 /// Parse an 'if let' expression ('if' token already eaten)
3018 pub fn parse_if_let_expr(&mut self, attrs: ThinAttributes)
3019 -> PResult<'a, P<Expr>> {
3020 let lo = self.last_span.lo;
3021 try!(self.expect_keyword(keywords::Let));
3022 let pat = try!(self.parse_pat());
3023 try!(self.expect(&token::Eq));
3024 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3025 let thn = try!(self.parse_block());
3026 let (hi, els) = if self.eat_keyword(keywords::Else) {
3027 let expr = try!(self.parse_else_expr());
3028 (expr.span.hi, Some(expr))
3032 Ok(self.mk_expr(lo, hi, ExprKind::IfLet(pat, expr, thn, els), attrs))
3036 pub fn parse_lambda_expr(&mut self, lo: BytePos,
3037 capture_clause: CaptureBy,
3038 attrs: ThinAttributes)
3039 -> PResult<'a, P<Expr>>
3041 let decl = try!(self.parse_fn_block_decl());
3042 let body = match decl.output {
3043 FunctionRetTy::Default(_) => {
3044 // If no explicit return type is given, parse any
3045 // expr and wrap it up in a dummy block:
3046 let body_expr = try!(self.parse_expr());
3048 id: ast::DUMMY_NODE_ID,
3050 span: body_expr.span,
3051 expr: Some(body_expr),
3052 rules: BlockCheckMode::Default,
3056 // If an explicit return type is given, require a
3057 // block to appear (RFC 968).
3058 try!(self.parse_block())
3065 ExprKind::Closure(capture_clause, decl, body), attrs))
3068 // `else` token already eaten
3069 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3070 if self.eat_keyword(keywords::If) {
3071 return self.parse_if_expr(None);
3073 let blk = try!(self.parse_block());
3074 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprKind::Block(blk), None));
3078 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3079 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::Ident>,
3081 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3082 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3084 let pat = try!(self.parse_pat());
3085 try!(self.expect_keyword(keywords::In));
3086 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3087 let (iattrs, loop_block) = try!(self.parse_inner_attrs_and_block());
3088 let attrs = attrs.append(iattrs.into_thin_attrs());
3090 let hi = self.last_span.hi;
3092 Ok(self.mk_expr(span_lo, hi,
3093 ExprKind::ForLoop(pat, expr, loop_block, opt_ident),
3097 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3098 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::Ident>,
3100 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3101 if self.token.is_keyword(keywords::Let) {
3102 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3104 let cond = try!(self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3105 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3106 let attrs = attrs.append(iattrs.into_thin_attrs());
3107 let hi = body.span.hi;
3108 return Ok(self.mk_expr(span_lo, hi, ExprKind::While(cond, body, opt_ident),
3112 /// Parse a 'while let' expression ('while' token already eaten)
3113 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::Ident>,
3115 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
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 (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3121 let attrs = attrs.append(iattrs.into_thin_attrs());
3122 let hi = body.span.hi;
3123 return Ok(self.mk_expr(span_lo, hi, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3126 // parse `loop {...}`, `loop` token already eaten
3127 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::Ident>,
3129 attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3130 let (iattrs, body) = try!(self.parse_inner_attrs_and_block());
3131 let attrs = attrs.append(iattrs.into_thin_attrs());
3132 let hi = body.span.hi;
3133 Ok(self.mk_expr(span_lo, hi, ExprKind::Loop(body, opt_ident), attrs))
3136 // `match` token already eaten
3137 fn parse_match_expr(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Expr>> {
3138 let match_span = self.last_span;
3139 let lo = self.last_span.lo;
3140 let discriminant = try!(self.parse_expr_res(
3141 Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None));
3142 if let Err(mut e) = self.commit_expr_expecting(&*discriminant,
3143 token::OpenDelim(token::Brace)) {
3144 if self.token == token::Token::Semi {
3145 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3149 let attrs = attrs.append(
3150 try!(self.parse_inner_attributes()).into_thin_attrs());
3151 let mut arms: Vec<Arm> = Vec::new();
3152 while self.token != token::CloseDelim(token::Brace) {
3153 arms.push(try!(self.parse_arm()));
3155 let hi = self.span.hi;
3157 return Ok(self.mk_expr(lo, hi, ExprKind::Match(discriminant, arms), attrs));
3160 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3161 maybe_whole!(no_clone self, NtArm);
3163 let attrs = try!(self.parse_outer_attributes());
3164 let pats = try!(self.parse_pats());
3165 let mut guard = None;
3166 if self.eat_keyword(keywords::If) {
3167 guard = Some(try!(self.parse_expr()));
3169 try!(self.expect(&token::FatArrow));
3170 let expr = try!(self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR, None));
3173 !classify::expr_is_simple_block(&*expr)
3174 && self.token != token::CloseDelim(token::Brace);
3177 try!(self.commit_expr(&*expr, &[token::Comma], &[token::CloseDelim(token::Brace)]));
3179 self.eat(&token::Comma);
3190 /// Parse an expression
3191 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3192 self.parse_expr_res(Restrictions::empty(), None)
3195 /// Evaluate the closure with restrictions in place.
3197 /// After the closure is evaluated, restrictions are reset.
3198 pub fn with_res<F>(&mut self, r: Restrictions, f: F) -> PResult<'a, P<Expr>>
3199 where F: FnOnce(&mut Self) -> PResult<'a, P<Expr>>
3201 let old = self.restrictions;
3202 self.restrictions = r;
3204 self.restrictions = old;
3209 /// Parse an expression, subject to the given restrictions
3210 pub fn parse_expr_res(&mut self, r: Restrictions,
3211 already_parsed_attrs: Option<ThinAttributes>)
3212 -> PResult<'a, P<Expr>> {
3213 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3216 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3217 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3218 if self.check(&token::Eq) {
3220 Ok(Some(try!(self.parse_expr())))
3226 /// Parse patterns, separated by '|' s
3227 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3228 let mut pats = Vec::new();
3230 pats.push(try!(self.parse_pat()));
3231 if self.check(&token::BinOp(token::Or)) { self.bump();}
3232 else { return Ok(pats); }
3236 fn parse_pat_tuple_elements(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3237 let mut fields = vec![];
3238 if !self.check(&token::CloseDelim(token::Paren)) {
3239 fields.push(try!(self.parse_pat()));
3240 if self.look_ahead(1, |t| *t != token::CloseDelim(token::Paren)) {
3241 while self.eat(&token::Comma) &&
3242 !self.check(&token::CloseDelim(token::Paren)) {
3243 fields.push(try!(self.parse_pat()));
3246 if fields.len() == 1 {
3247 try!(self.expect(&token::Comma));
3253 fn parse_pat_vec_elements(
3255 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3256 let mut before = Vec::new();
3257 let mut slice = None;
3258 let mut after = Vec::new();
3259 let mut first = true;
3260 let mut before_slice = true;
3262 while self.token != token::CloseDelim(token::Bracket) {
3266 try!(self.expect(&token::Comma));
3268 if self.token == token::CloseDelim(token::Bracket)
3269 && (before_slice || !after.is_empty()) {
3275 if self.check(&token::DotDot) {
3278 if self.check(&token::Comma) ||
3279 self.check(&token::CloseDelim(token::Bracket)) {
3280 slice = Some(P(ast::Pat {
3281 id: ast::DUMMY_NODE_ID,
3285 before_slice = false;
3291 let subpat = try!(self.parse_pat());
3292 if before_slice && self.check(&token::DotDot) {
3294 slice = Some(subpat);
3295 before_slice = false;
3296 } else if before_slice {
3297 before.push(subpat);
3303 Ok((before, slice, after))
3306 /// Parse the fields of a struct-like pattern
3307 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>> , bool)> {
3308 let mut fields = Vec::new();
3309 let mut etc = false;
3310 let mut first = true;
3311 while self.token != token::CloseDelim(token::Brace) {
3315 try!(self.expect(&token::Comma));
3316 // accept trailing commas
3317 if self.check(&token::CloseDelim(token::Brace)) { break }
3320 let lo = self.span.lo;
3323 if self.check(&token::DotDot) {
3325 if self.token != token::CloseDelim(token::Brace) {
3326 let token_str = self.this_token_to_string();
3327 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3334 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3335 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3336 // Parsing a pattern of the form "fieldname: pat"
3337 let fieldname = try!(self.parse_ident());
3339 let pat = try!(self.parse_pat());
3341 (pat, fieldname, false)
3343 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3344 let is_box = self.eat_keyword(keywords::Box);
3345 let boxed_span_lo = self.span.lo;
3346 let is_ref = self.eat_keyword(keywords::Ref);
3347 let is_mut = self.eat_keyword(keywords::Mut);
3348 let fieldname = try!(self.parse_ident());
3349 hi = self.last_span.hi;
3351 let bind_type = match (is_ref, is_mut) {
3352 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3353 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3354 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3355 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3357 let fieldpath = codemap::Spanned{span:self.last_span, node:fieldname};
3358 let fieldpat = P(ast::Pat{
3359 id: ast::DUMMY_NODE_ID,
3360 node: PatIdent(bind_type, fieldpath, None),
3361 span: mk_sp(boxed_span_lo, hi),
3364 let subpat = if is_box {
3366 id: ast::DUMMY_NODE_ID,
3367 node: PatBox(fieldpat),
3368 span: mk_sp(lo, hi),
3373 (subpat, fieldname, true)
3376 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3377 node: ast::FieldPat { ident: fieldname,
3379 is_shorthand: is_shorthand }});
3381 return Ok((fields, etc));
3384 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3385 if self.is_path_start() {
3386 let lo = self.span.lo;
3387 let (qself, path) = if self.eat_lt() {
3388 // Parse a qualified path
3390 try!(self.parse_qualified_path(NoTypesAllowed));
3393 // Parse an unqualified path
3394 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3396 let hi = self.last_span.hi;
3397 Ok(self.mk_expr(lo, hi, ExprKind::Path(qself, path), None))
3399 self.parse_pat_literal_maybe_minus()
3403 fn is_path_start(&self) -> bool {
3404 (self.token == token::Lt || self.token == token::ModSep
3405 || self.token.is_ident() || self.token.is_path())
3406 && !self.token.is_keyword(keywords::True) && !self.token.is_keyword(keywords::False)
3409 /// Parse a pattern.
3410 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3411 maybe_whole!(self, NtPat);
3413 let lo = self.span.lo;
3416 token::Underscore => {
3421 token::BinOp(token::And) | token::AndAnd => {
3422 // Parse &pat / &mut pat
3423 try!(self.expect_and());
3424 let mutbl = try!(self.parse_mutability());
3425 if let token::Lifetime(ident) = self.token {
3426 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3429 let subpat = try!(self.parse_pat());
3430 pat = PatRegion(subpat, mutbl);
3432 token::OpenDelim(token::Paren) => {
3433 // Parse (pat,pat,pat,...) as tuple pattern
3435 let fields = try!(self.parse_pat_tuple_elements());
3436 try!(self.expect(&token::CloseDelim(token::Paren)));
3437 pat = PatTup(fields);
3439 token::OpenDelim(token::Bracket) => {
3440 // Parse [pat,pat,...] as slice pattern
3442 let (before, slice, after) = try!(self.parse_pat_vec_elements());
3443 try!(self.expect(&token::CloseDelim(token::Bracket)));
3444 pat = PatVec(before, slice, after);
3447 // At this point, token != _, &, &&, (, [
3448 if self.eat_keyword(keywords::Mut) {
3449 // Parse mut ident @ pat
3450 pat = try!(self.parse_pat_ident(BindingMode::ByValue(Mutability::Mutable)));
3451 } else if self.eat_keyword(keywords::Ref) {
3452 // Parse ref ident @ pat / ref mut ident @ pat
3453 let mutbl = try!(self.parse_mutability());
3454 pat = try!(self.parse_pat_ident(BindingMode::ByRef(mutbl)));
3455 } else if self.eat_keyword(keywords::Box) {
3457 let subpat = try!(self.parse_pat());
3458 pat = PatBox(subpat);
3459 } else if self.is_path_start() {
3460 // Parse pattern starting with a path
3461 if self.token.is_plain_ident() && self.look_ahead(1, |t| *t != token::DotDotDot &&
3462 *t != token::OpenDelim(token::Brace) &&
3463 *t != token::OpenDelim(token::Paren) &&
3464 // Contrary to its definition, a plain ident can be followed by :: in macros
3465 *t != token::ModSep) {
3466 // Plain idents have some extra abilities here compared to general paths
3467 if self.look_ahead(1, |t| *t == token::Not) {
3468 // Parse macro invocation
3469 let ident = try!(self.parse_ident());
3470 let ident_span = self.last_span;
3471 let path = ident_to_path(ident_span, ident);
3473 let delim = try!(self.expect_open_delim());
3474 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
3475 seq_sep_none(), |p| p.parse_token_tree()));
3476 let mac = Mac_ { path: path, tts: tts, ctxt: EMPTY_CTXT };
3477 pat = PatMac(codemap::Spanned {node: mac,
3478 span: mk_sp(lo, self.last_span.hi)});
3480 // Parse ident @ pat
3481 // This can give false positives and parse nullary enums,
3482 // they are dealt with later in resolve
3483 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3484 pat = try!(self.parse_pat_ident(binding_mode));
3487 let (qself, path) = if self.eat_lt() {
3488 // Parse a qualified path
3490 try!(self.parse_qualified_path(NoTypesAllowed));
3493 // Parse an unqualified path
3494 (None, try!(self.parse_path(LifetimeAndTypesWithColons)))
3497 token::DotDotDot => {
3499 let hi = self.last_span.hi;
3500 let begin = self.mk_expr(lo, hi, ExprKind::Path(qself, path), None);
3502 let end = try!(self.parse_pat_range_end());
3503 pat = PatRange(begin, end);
3505 token::OpenDelim(token::Brace) => {
3506 if qself.is_some() {
3507 return Err(self.fatal("unexpected `{` after qualified path"));
3509 // Parse struct pattern
3511 let (fields, etc) = try!(self.parse_pat_fields());
3513 pat = PatStruct(path, fields, etc);
3515 token::OpenDelim(token::Paren) => {
3516 if qself.is_some() {
3517 return Err(self.fatal("unexpected `(` after qualified path"));
3519 // Parse tuple struct or enum pattern
3520 if self.look_ahead(1, |t| *t == token::DotDot) {
3521 // This is a "top constructor only" pat
3524 try!(self.expect(&token::CloseDelim(token::Paren)));
3525 pat = PatEnum(path, None);
3527 let args = try!(self.parse_enum_variant_seq(
3528 &token::OpenDelim(token::Paren),
3529 &token::CloseDelim(token::Paren),
3530 seq_sep_trailing_allowed(token::Comma),
3531 |p| p.parse_pat()));
3532 pat = PatEnum(path, Some(args));
3537 // Parse qualified path
3538 Some(qself) => PatQPath(qself, path),
3539 // Parse nullary enum
3540 None => PatEnum(path, Some(vec![]))
3546 // Try to parse everything else as literal with optional minus
3547 let begin = try!(self.parse_pat_literal_maybe_minus());
3548 if self.eat(&token::DotDotDot) {
3549 let end = try!(self.parse_pat_range_end());
3550 pat = PatRange(begin, end);
3552 pat = PatLit(begin);
3558 let hi = self.last_span.hi;
3560 id: ast::DUMMY_NODE_ID,
3562 span: mk_sp(lo, hi),
3566 /// Parse ident or ident @ pat
3567 /// used by the copy foo and ref foo patterns to give a good
3568 /// error message when parsing mistakes like ref foo(a,b)
3569 fn parse_pat_ident(&mut self,
3570 binding_mode: ast::BindingMode)
3571 -> PResult<'a, ast::Pat_> {
3572 if !self.token.is_plain_ident() {
3573 let span = self.span;
3574 let tok_str = self.this_token_to_string();
3575 return Err(self.span_fatal(span,
3576 &format!("expected identifier, found `{}`", tok_str)))
3578 let ident = try!(self.parse_ident());
3579 let last_span = self.last_span;
3580 let name = codemap::Spanned{span: last_span, node: ident};
3581 let sub = if self.eat(&token::At) {
3582 Some(try!(self.parse_pat()))
3587 // just to be friendly, if they write something like
3589 // we end up here with ( as the current token. This shortly
3590 // leads to a parse error. Note that if there is no explicit
3591 // binding mode then we do not end up here, because the lookahead
3592 // will direct us over to parse_enum_variant()
3593 if self.token == token::OpenDelim(token::Paren) {
3594 let last_span = self.last_span;
3595 return Err(self.span_fatal(
3597 "expected identifier, found enum pattern"))
3600 Ok(PatIdent(binding_mode, name, sub))
3603 /// Parse a local variable declaration
3604 fn parse_local(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Local>> {
3605 let lo = self.span.lo;
3606 let pat = try!(self.parse_pat());
3609 if self.eat(&token::Colon) {
3610 ty = Some(try!(self.parse_ty_sum()));
3612 let init = try!(self.parse_initializer());
3617 id: ast::DUMMY_NODE_ID,
3618 span: mk_sp(lo, self.last_span.hi),
3623 /// Parse a "let" stmt
3624 fn parse_let(&mut self, attrs: ThinAttributes) -> PResult<'a, P<Decl>> {
3625 let lo = self.span.lo;
3626 let local = try!(self.parse_local(attrs));
3627 Ok(P(spanned(lo, self.last_span.hi, DeclKind::Local(local))))
3630 /// Parse a structure field
3631 fn parse_name_and_ty(&mut self, pr: Visibility,
3632 attrs: Vec<Attribute> ) -> PResult<'a, StructField> {
3634 Visibility::Inherited => self.span.lo,
3635 Visibility::Public => self.last_span.lo,
3637 if !self.token.is_plain_ident() {
3638 return Err(self.fatal("expected ident"));
3640 let name = try!(self.parse_ident());
3641 try!(self.expect(&token::Colon));
3642 let ty = try!(self.parse_ty_sum());
3643 Ok(spanned(lo, self.last_span.hi, ast::StructField_ {
3644 kind: NamedField(name, pr),
3645 id: ast::DUMMY_NODE_ID,
3651 /// Emit an expected item after attributes error.
3652 fn expected_item_err(&self, attrs: &[Attribute]) {
3653 let message = match attrs.last() {
3654 Some(&Attribute { node: ast::Attribute_ { is_sugared_doc: true, .. }, .. }) => {
3655 "expected item after doc comment"
3657 _ => "expected item after attributes",
3660 self.span_err(self.last_span, message);
3663 /// Parse a statement. may include decl.
3664 pub fn parse_stmt(&mut self) -> PResult<'a, Option<P<Stmt>>> {
3665 Ok(try!(self.parse_stmt_()).map(P))
3668 fn parse_stmt_(&mut self) -> PResult<'a, Option<Stmt>> {
3669 maybe_whole!(Some deref self, NtStmt);
3671 let attrs = try!(self.parse_outer_attributes());
3672 let lo = self.span.lo;
3674 Ok(Some(if self.check_keyword(keywords::Let) {
3675 try!(self.expect_keyword(keywords::Let));
3676 let decl = try!(self.parse_let(attrs.into_thin_attrs()));
3677 let hi = decl.span.hi;
3678 let stmt = StmtKind::Decl(decl, ast::DUMMY_NODE_ID);
3679 spanned(lo, hi, stmt)
3680 } else if self.token.is_ident()
3681 && !self.token.is_any_keyword()
3682 && self.look_ahead(1, |t| *t == token::Not) {
3683 // it's a macro invocation:
3685 // Potential trouble: if we allow macros with paths instead of
3686 // idents, we'd need to look ahead past the whole path here...
3687 let pth = try!(self.parse_path(NoTypesAllowed));
3690 let id = match self.token {
3691 token::OpenDelim(_) => token::special_idents::invalid, // no special identifier
3692 _ => try!(self.parse_ident()),
3695 // check that we're pointing at delimiters (need to check
3696 // again after the `if`, because of `parse_ident`
3697 // consuming more tokens).
3698 let delim = match self.token {
3699 token::OpenDelim(delim) => delim,
3701 // we only expect an ident if we didn't parse one
3703 let ident_str = if id.name == token::special_idents::invalid.name {
3708 let tok_str = self.this_token_to_string();
3709 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3715 let tts = try!(self.parse_unspanned_seq(
3716 &token::OpenDelim(delim),
3717 &token::CloseDelim(delim),
3719 |p| p.parse_token_tree()
3721 let hi = self.last_span.hi;
3723 let style = if delim == token::Brace {
3724 MacStmtStyle::Braces
3726 MacStmtStyle::NoBraces
3729 if id.name == token::special_idents::invalid.name {
3730 let mac = P(spanned(lo, hi, Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT }));
3731 let stmt = StmtKind::Mac(mac, style, attrs.into_thin_attrs());
3732 spanned(lo, hi, stmt)
3734 // if it has a special ident, it's definitely an item
3736 // Require a semicolon or braces.
3737 if style != MacStmtStyle::Braces {
3738 if !self.eat(&token::Semi) {
3739 let last_span = self.last_span;
3740 self.span_err(last_span,
3741 "macros that expand to items must \
3742 either be surrounded with braces or \
3743 followed by a semicolon");
3746 spanned(lo, hi, StmtKind::Decl(
3747 P(spanned(lo, hi, DeclKind::Item(
3749 lo, hi, id /*id is good here*/,
3750 ItemKind::Mac(spanned(lo, hi,
3751 Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT })),
3752 Visibility::Inherited, attrs)))),
3753 ast::DUMMY_NODE_ID))
3756 // FIXME: Bad copy of attrs
3757 match try!(self.parse_item_(attrs.clone(), false, true)) {
3760 let decl = P(spanned(lo, hi, DeclKind::Item(i)));
3761 spanned(lo, hi, StmtKind::Decl(decl, ast::DUMMY_NODE_ID))
3764 let unused_attrs = |attrs: &[_], s: &mut Self| {
3765 if attrs.len() > 0 {
3767 "expected statement after outer attribute");
3771 // Do not attempt to parse an expression if we're done here.
3772 if self.token == token::Semi {
3773 unused_attrs(&attrs, self);
3778 if self.token == token::CloseDelim(token::Brace) {
3779 unused_attrs(&attrs, self);
3783 // Remainder are line-expr stmts.
3784 let e = try!(self.parse_expr_res(
3785 Restrictions::RESTRICTION_STMT_EXPR, Some(attrs.into_thin_attrs())));
3787 let stmt = StmtKind::Expr(e, ast::DUMMY_NODE_ID);
3788 spanned(lo, hi, stmt)
3794 /// Is this expression a successfully-parsed statement?
3795 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3796 self.restrictions.contains(Restrictions::RESTRICTION_STMT_EXPR) &&
3797 !classify::expr_requires_semi_to_be_stmt(e)
3800 /// Parse a block. No inner attrs are allowed.
3801 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
3802 maybe_whole!(no_clone self, NtBlock);
3804 let lo = self.span.lo;
3806 if !self.eat(&token::OpenDelim(token::Brace)) {
3808 let tok = self.this_token_to_string();
3809 return Err(self.span_fatal_help(sp,
3810 &format!("expected `{{`, found `{}`", tok),
3811 "place this code inside a block"));
3814 self.parse_block_tail(lo, BlockCheckMode::Default)
3817 /// Parse a block. Inner attrs are allowed.
3818 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
3819 maybe_whole!(pair_empty self, NtBlock);
3821 let lo = self.span.lo;
3822 try!(self.expect(&token::OpenDelim(token::Brace)));
3823 Ok((try!(self.parse_inner_attributes()),
3824 try!(self.parse_block_tail(lo, BlockCheckMode::Default))))
3827 /// Parse the rest of a block expression or function body
3828 /// Precondition: already parsed the '{'.
3829 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> PResult<'a, P<Block>> {
3830 let mut stmts = vec![];
3831 let mut expr = None;
3833 while !self.eat(&token::CloseDelim(token::Brace)) {
3834 let Spanned {node, span} = if let Some(s) = try!(self.parse_stmt_()) {
3837 // Found only `;` or `}`.
3841 StmtKind::Expr(e, _) => {
3842 try!(self.handle_expression_like_statement(e, span, &mut stmts, &mut expr));
3844 StmtKind::Mac(mac, MacStmtStyle::NoBraces, attrs) => {
3845 // statement macro without braces; might be an
3846 // expr depending on whether a semicolon follows
3849 stmts.push(P(Spanned {
3850 node: StmtKind::Mac(mac, MacStmtStyle::Semicolon, attrs),
3851 span: mk_sp(span.lo, self.span.hi),
3856 let e = self.mk_mac_expr(span.lo, span.hi,
3857 mac.and_then(|m| m.node),
3860 let e = try!(self.parse_dot_or_call_expr_with(e, lo, attrs));
3861 let e = try!(self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e)));
3862 try!(self.handle_expression_like_statement(
3870 StmtKind::Mac(m, style, attrs) => {
3871 // statement macro; might be an expr
3874 stmts.push(P(Spanned {
3875 node: StmtKind::Mac(m, MacStmtStyle::Semicolon, attrs),
3876 span: mk_sp(span.lo, self.span.hi),
3880 token::CloseDelim(token::Brace) => {
3881 // if a block ends in `m!(arg)` without
3882 // a `;`, it must be an expr
3883 expr = Some(self.mk_mac_expr(span.lo, span.hi,
3884 m.and_then(|x| x.node),
3888 stmts.push(P(Spanned {
3889 node: StmtKind::Mac(m, style, attrs),
3895 _ => { // all other kinds of statements:
3896 let mut hi = span.hi;
3897 if classify::stmt_ends_with_semi(&node) {
3898 try!(self.commit_stmt_expecting(token::Semi));
3899 hi = self.last_span.hi;
3902 stmts.push(P(Spanned {
3904 span: mk_sp(span.lo, hi)
3913 id: ast::DUMMY_NODE_ID,
3915 span: mk_sp(lo, self.last_span.hi),
3919 fn handle_expression_like_statement(
3923 stmts: &mut Vec<P<Stmt>>,
3924 last_block_expr: &mut Option<P<Expr>>) -> PResult<'a, ()> {
3925 // expression without semicolon
3926 if classify::expr_requires_semi_to_be_stmt(&*e) {
3927 // Just check for errors and recover; do not eat semicolon yet.
3928 try!(self.commit_stmt(&[],
3929 &[token::Semi, token::CloseDelim(token::Brace)]));
3935 let span_with_semi = Span {
3937 hi: self.last_span.hi,
3938 expn_id: span.expn_id,
3940 stmts.push(P(Spanned {
3941 node: StmtKind::Semi(e, ast::DUMMY_NODE_ID),
3942 span: span_with_semi,
3945 token::CloseDelim(token::Brace) => *last_block_expr = Some(e),
3947 stmts.push(P(Spanned {
3948 node: StmtKind::Expr(e, ast::DUMMY_NODE_ID),
3956 // Parses a sequence of bounds if a `:` is found,
3957 // otherwise returns empty list.
3958 fn parse_colon_then_ty_param_bounds(&mut self,
3959 mode: BoundParsingMode)
3960 -> PResult<'a, TyParamBounds>
3962 if !self.eat(&token::Colon) {
3965 self.parse_ty_param_bounds(mode)
3969 // matches bounds = ( boundseq )?
3970 // where boundseq = ( polybound + boundseq ) | polybound
3971 // and polybound = ( 'for' '<' 'region '>' )? bound
3972 // and bound = 'region | trait_ref
3973 fn parse_ty_param_bounds(&mut self,
3974 mode: BoundParsingMode)
3975 -> PResult<'a, TyParamBounds>
3977 let mut result = vec!();
3979 let question_span = self.span;
3980 let ate_question = self.eat(&token::Question);
3982 token::Lifetime(lifetime) => {
3984 self.span_err(question_span,
3985 "`?` may only modify trait bounds, not lifetime bounds");
3987 result.push(RegionTyParamBound(ast::Lifetime {
3988 id: ast::DUMMY_NODE_ID,
3994 token::ModSep | token::Ident(..) => {
3995 let poly_trait_ref = try!(self.parse_poly_trait_ref());
3996 let modifier = if ate_question {
3997 if mode == BoundParsingMode::Modified {
3998 TraitBoundModifier::Maybe
4000 self.span_err(question_span,
4002 TraitBoundModifier::None
4005 TraitBoundModifier::None
4007 result.push(TraitTyParamBound(poly_trait_ref, modifier))
4012 if !self.eat(&token::BinOp(token::Plus)) {
4017 return Ok(P::from_vec(result));
4020 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4021 fn parse_ty_param(&mut self) -> PResult<'a, TyParam> {
4022 let span = self.span;
4023 let ident = try!(self.parse_ident());
4025 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Modified));
4027 let default = if self.check(&token::Eq) {
4029 Some(try!(self.parse_ty_sum()))
4036 id: ast::DUMMY_NODE_ID,
4043 /// Parse a set of optional generic type parameter declarations. Where
4044 /// clauses are not parsed here, and must be added later via
4045 /// `parse_where_clause()`.
4047 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4048 /// | ( < lifetimes , typaramseq ( , )? > )
4049 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4050 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4051 maybe_whole!(self, NtGenerics);
4053 if self.eat(&token::Lt) {
4054 let lifetime_defs = try!(self.parse_lifetime_defs());
4055 let mut seen_default = false;
4056 let ty_params = try!(self.parse_seq_to_gt(Some(token::Comma), |p| {
4057 try!(p.forbid_lifetime());
4058 let ty_param = try!(p.parse_ty_param());
4059 if ty_param.default.is_some() {
4060 seen_default = true;
4061 } else if seen_default {
4062 let last_span = p.last_span;
4063 p.span_err(last_span,
4064 "type parameters with a default must be trailing");
4069 lifetimes: lifetime_defs,
4070 ty_params: ty_params,
4071 where_clause: WhereClause {
4072 id: ast::DUMMY_NODE_ID,
4073 predicates: Vec::new(),
4077 Ok(ast::Generics::default())
4081 fn parse_generic_values_after_lt(&mut self) -> PResult<'a, (Vec<ast::Lifetime>,
4083 Vec<P<TypeBinding>>)> {
4084 let span_lo = self.span.lo;
4085 let lifetimes = try!(self.parse_lifetimes(token::Comma));
4087 let missing_comma = !lifetimes.is_empty() &&
4088 !self.token.is_like_gt() &&
4090 .as_ref().map_or(true,
4091 |x| &**x != &token::Comma);
4095 let msg = format!("expected `,` or `>` after lifetime \
4097 self.this_token_to_string());
4098 let mut err = self.diagnostic().struct_span_err(self.span, &msg);
4100 let span_hi = self.span.hi;
4101 let span_hi = match self.parse_ty() {
4102 Ok(..) => self.span.hi,
4103 Err(ref mut err) => {
4109 let msg = format!("did you mean a single argument type &'a Type, \
4110 or did you mean the comma-separated arguments \
4112 err.span_note(mk_sp(span_lo, span_hi), &msg);
4116 // First parse types.
4117 let (types, returned) = try!(self.parse_seq_to_gt_or_return(
4120 try!(p.forbid_lifetime());
4121 if p.look_ahead(1, |t| t == &token::Eq) {
4124 Ok(Some(try!(p.parse_ty_sum())))
4129 // If we found the `>`, don't continue.
4131 return Ok((lifetimes, types.into_vec(), Vec::new()));
4134 // Then parse type bindings.
4135 let bindings = try!(self.parse_seq_to_gt(
4138 try!(p.forbid_lifetime());
4140 let ident = try!(p.parse_ident());
4141 let found_eq = p.eat(&token::Eq);
4144 p.span_warn(span, "whoops, no =?");
4146 let ty = try!(p.parse_ty());
4147 let hi = ty.span.hi;
4148 let span = mk_sp(lo, hi);
4149 return Ok(P(TypeBinding{id: ast::DUMMY_NODE_ID,
4156 Ok((lifetimes, types.into_vec(), bindings.into_vec()))
4159 fn forbid_lifetime(&mut self) -> PResult<'a, ()> {
4160 if self.token.is_lifetime() {
4161 let span = self.span;
4162 return Err(self.span_fatal(span, "lifetime parameters must be declared \
4163 prior to type parameters"))
4168 /// Parses an optional `where` clause and places it in `generics`.
4171 /// where T : Trait<U, V> + 'b, 'a : 'b
4173 pub fn parse_where_clause(&mut self) -> PResult<'a, ast::WhereClause> {
4174 maybe_whole!(self, NtWhereClause);
4176 let mut where_clause = WhereClause {
4177 id: ast::DUMMY_NODE_ID,
4178 predicates: Vec::new(),
4181 if !self.eat_keyword(keywords::Where) {
4182 return Ok(where_clause);
4185 let mut parsed_something = false;
4187 let lo = self.span.lo;
4189 token::OpenDelim(token::Brace) => {
4193 token::Lifetime(..) => {
4194 let bounded_lifetime =
4195 try!(self.parse_lifetime());
4197 self.eat(&token::Colon);
4200 try!(self.parse_lifetimes(token::BinOp(token::Plus)));
4202 let hi = self.last_span.hi;
4203 let span = mk_sp(lo, hi);
4205 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4206 ast::WhereRegionPredicate {
4208 lifetime: bounded_lifetime,
4213 parsed_something = true;
4217 let bound_lifetimes = if self.eat_keyword(keywords::For) {
4218 // Higher ranked constraint.
4219 try!(self.expect(&token::Lt));
4220 let lifetime_defs = try!(self.parse_lifetime_defs());
4221 try!(self.expect_gt());
4227 let bounded_ty = try!(self.parse_ty());
4229 if self.eat(&token::Colon) {
4230 let bounds = try!(self.parse_ty_param_bounds(BoundParsingMode::Bare));
4231 let hi = self.last_span.hi;
4232 let span = mk_sp(lo, hi);
4234 if bounds.is_empty() {
4236 "each predicate in a `where` clause must have \
4237 at least one bound in it");
4240 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4241 ast::WhereBoundPredicate {
4243 bound_lifetimes: bound_lifetimes,
4244 bounded_ty: bounded_ty,
4248 parsed_something = true;
4249 } else if self.eat(&token::Eq) {
4250 // let ty = try!(self.parse_ty());
4251 let hi = self.last_span.hi;
4252 let span = mk_sp(lo, hi);
4253 // where_clause.predicates.push(
4254 // ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
4255 // id: ast::DUMMY_NODE_ID,
4257 // path: panic!("NYI"), //bounded_ty,
4260 // parsed_something = true;
4263 "equality constraints are not yet supported \
4264 in where clauses (#20041)");
4266 let last_span = self.last_span;
4267 self.span_err(last_span,
4268 "unexpected token in `where` clause");
4273 if !self.eat(&token::Comma) {
4278 if !parsed_something {
4279 let last_span = self.last_span;
4280 self.span_err(last_span,
4281 "a `where` clause must have at least one predicate \
4288 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4289 -> PResult<'a, (Vec<Arg> , bool)> {
4291 let mut args: Vec<Option<Arg>> =
4292 try!(self.parse_unspanned_seq(
4293 &token::OpenDelim(token::Paren),
4294 &token::CloseDelim(token::Paren),
4295 seq_sep_trailing_allowed(token::Comma),
4297 if p.token == token::DotDotDot {
4300 if p.token != token::CloseDelim(token::Paren) {
4302 return Err(p.span_fatal(span,
4303 "`...` must be last in argument list for variadic function"))
4307 return Err(p.span_fatal(span,
4308 "only foreign functions are allowed to be variadic"))
4312 Ok(Some(try!(p.parse_arg_general(named_args))))
4317 let variadic = match args.pop() {
4320 // Need to put back that last arg
4327 if variadic && args.is_empty() {
4329 "variadic function must be declared with at least one named argument");
4332 let args = args.into_iter().map(|x| x.unwrap()).collect();
4334 Ok((args, variadic))
4337 /// Parse the argument list and result type of a function declaration
4338 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4340 let (args, variadic) = try!(self.parse_fn_args(true, allow_variadic));
4341 let ret_ty = try!(self.parse_ret_ty());
4350 fn is_self_ident(&mut self) -> bool {
4352 token::Ident(id, token::Plain) => id.name == special_idents::self_.name,
4357 fn expect_self_ident(&mut self) -> PResult<'a, ast::Ident> {
4359 token::Ident(id, token::Plain) if id.name == special_idents::self_.name => {
4364 let token_str = self.this_token_to_string();
4365 return Err(self.fatal(&format!("expected `self`, found `{}`",
4371 fn is_self_type_ident(&mut self) -> bool {
4373 token::Ident(id, token::Plain) => id.name == special_idents::type_self.name,
4378 fn expect_self_type_ident(&mut self) -> PResult<'a, ast::Ident> {
4380 token::Ident(id, token::Plain) if id.name == special_idents::type_self.name => {
4385 let token_str = self.this_token_to_string();
4386 Err(self.fatal(&format!("expected `Self`, found `{}`",
4392 /// Parse the argument list and result type of a function
4393 /// that may have a self type.
4394 fn parse_fn_decl_with_self<F>(&mut self,
4395 parse_arg_fn: F) -> PResult<'a, (ExplicitSelf, P<FnDecl>)> where
4396 F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4398 fn maybe_parse_borrowed_explicit_self<'b>(this: &mut Parser<'b>)
4399 -> PResult<'b, ast::SelfKind> {
4400 // The following things are possible to see here:
4405 // fn(&'lt mut self)
4407 // We already know that the current token is `&`.
4409 if this.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4411 Ok(SelfKind::Region(None, Mutability::Immutable, try!(this.expect_self_ident())))
4412 } else if this.look_ahead(1, |t| t.is_mutability()) &&
4413 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4415 let mutability = try!(this.parse_mutability());
4416 Ok(SelfKind::Region(None, mutability, try!(this.expect_self_ident())))
4417 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4418 this.look_ahead(2, |t| t.is_keyword(keywords::SelfValue)) {
4420 let lifetime = try!(this.parse_lifetime());
4421 let ident = try!(this.expect_self_ident());
4422 Ok(SelfKind::Region(Some(lifetime), Mutability::Immutable, ident))
4423 } else if this.look_ahead(1, |t| t.is_lifetime()) &&
4424 this.look_ahead(2, |t| t.is_mutability()) &&
4425 this.look_ahead(3, |t| t.is_keyword(keywords::SelfValue)) {
4427 let lifetime = try!(this.parse_lifetime());
4428 let mutability = try!(this.parse_mutability());
4429 Ok(SelfKind::Region(Some(lifetime), mutability, try!(this.expect_self_ident())))
4431 Ok(SelfKind::Static)
4435 try!(self.expect(&token::OpenDelim(token::Paren)));
4437 // A bit of complexity and lookahead is needed here in order to be
4438 // backwards compatible.
4439 let lo = self.span.lo;
4440 let mut self_ident_lo = self.span.lo;
4441 let mut self_ident_hi = self.span.hi;
4443 let mut mutbl_self = Mutability::Immutable;
4444 let explicit_self = match self.token {
4445 token::BinOp(token::And) => {
4446 let eself = try!(maybe_parse_borrowed_explicit_self(self));
4447 self_ident_lo = self.last_span.lo;
4448 self_ident_hi = self.last_span.hi;
4451 token::BinOp(token::Star) => {
4452 // Possibly "*self" or "*mut self" -- not supported. Try to avoid
4453 // emitting cryptic "unexpected token" errors.
4455 let _mutability = if self.token.is_mutability() {
4456 try!(self.parse_mutability())
4458 Mutability::Immutable
4460 if self.is_self_ident() {
4461 let span = self.span;
4462 self.span_err(span, "cannot pass self by raw pointer");
4465 // error case, making bogus self ident:
4466 SelfKind::Value(special_idents::self_)
4468 token::Ident(..) => {
4469 if self.is_self_ident() {
4470 let self_ident = try!(self.expect_self_ident());
4472 // Determine whether this is the fully explicit form, `self:
4474 if self.eat(&token::Colon) {
4475 SelfKind::Explicit(try!(self.parse_ty_sum()), self_ident)
4477 SelfKind::Value(self_ident)
4479 } else if self.token.is_mutability() &&
4480 self.look_ahead(1, |t| t.is_keyword(keywords::SelfValue)) {
4481 mutbl_self = try!(self.parse_mutability());
4482 let self_ident = try!(self.expect_self_ident());
4484 // Determine whether this is the fully explicit form,
4486 if self.eat(&token::Colon) {
4487 SelfKind::Explicit(try!(self.parse_ty_sum()), self_ident)
4489 SelfKind::Value(self_ident)
4495 _ => SelfKind::Static,
4498 let explicit_self_sp = mk_sp(self_ident_lo, self_ident_hi);
4500 // shared fall-through for the three cases below. borrowing prevents simply
4501 // writing this as a closure
4502 macro_rules! parse_remaining_arguments {
4505 // If we parsed a self type, expect a comma before the argument list.
4509 let sep = seq_sep_trailing_allowed(token::Comma);
4510 let mut fn_inputs = try!(self.parse_seq_to_before_end(
4511 &token::CloseDelim(token::Paren),
4515 fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id));
4518 token::CloseDelim(token::Paren) => {
4519 vec!(Arg::new_self(explicit_self_sp, mutbl_self, $self_id))
4522 let token_str = self.this_token_to_string();
4523 return Err(self.fatal(&format!("expected `,` or `)`, found `{}`",
4530 let fn_inputs = match explicit_self {
4531 SelfKind::Static => {
4532 let sep = seq_sep_trailing_allowed(token::Comma);
4533 try!(self.parse_seq_to_before_end(&token::CloseDelim(token::Paren),
4536 SelfKind::Value(id) => parse_remaining_arguments!(id),
4537 SelfKind::Region(_,_,id) => parse_remaining_arguments!(id),
4538 SelfKind::Explicit(_,id) => parse_remaining_arguments!(id),
4542 try!(self.expect(&token::CloseDelim(token::Paren)));
4544 let hi = self.span.hi;
4546 let ret_ty = try!(self.parse_ret_ty());
4548 let fn_decl = P(FnDecl {
4554 Ok((spanned(lo, hi, explicit_self), fn_decl))
4557 // parse the |arg, arg| header on a lambda
4558 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4559 let inputs_captures = {
4560 if self.eat(&token::OrOr) {
4563 try!(self.expect(&token::BinOp(token::Or)));
4564 try!(self.parse_obsolete_closure_kind());
4565 let args = try!(self.parse_seq_to_before_end(
4566 &token::BinOp(token::Or),
4567 seq_sep_trailing_allowed(token::Comma),
4568 |p| p.parse_fn_block_arg()
4574 let output = try!(self.parse_ret_ty());
4577 inputs: inputs_captures,
4583 /// Parse the name and optional generic types of a function header.
4584 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4585 let id = try!(self.parse_ident());
4586 let generics = try!(self.parse_generics());
4590 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4591 node: ItemKind, vis: Visibility,
4592 attrs: Vec<Attribute>) -> P<Item> {
4596 id: ast::DUMMY_NODE_ID,
4603 /// Parse an item-position function declaration.
4604 fn parse_item_fn(&mut self,
4606 constness: Constness,
4608 -> PResult<'a, ItemInfo> {
4609 let (ident, mut generics) = try!(self.parse_fn_header());
4610 let decl = try!(self.parse_fn_decl(false));
4611 generics.where_clause = try!(self.parse_where_clause());
4612 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4613 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4616 /// true if we are looking at `const ID`, false for things like `const fn` etc
4617 pub fn is_const_item(&mut self) -> bool {
4618 self.token.is_keyword(keywords::Const) &&
4619 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4620 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4623 /// parses all the "front matter" for a `fn` declaration, up to
4624 /// and including the `fn` keyword:
4628 /// - `const unsafe fn`
4631 pub fn parse_fn_front_matter(&mut self)
4632 -> PResult<'a, (ast::Constness, ast::Unsafety, abi::Abi)> {
4633 let is_const_fn = self.eat_keyword(keywords::Const);
4634 let unsafety = try!(self.parse_unsafety());
4635 let (constness, unsafety, abi) = if is_const_fn {
4636 (Constness::Const, unsafety, Abi::Rust)
4638 let abi = if self.eat_keyword(keywords::Extern) {
4639 try!(self.parse_opt_abi()).unwrap_or(Abi::C)
4643 (Constness::NotConst, unsafety, abi)
4645 try!(self.expect_keyword(keywords::Fn));
4646 Ok((constness, unsafety, abi))
4649 /// Parse an impl item.
4650 pub fn parse_impl_item(&mut self) -> PResult<'a, P<ImplItem>> {
4651 maybe_whole!(no_clone self, NtImplItem);
4653 let mut attrs = try!(self.parse_outer_attributes());
4654 let lo = self.span.lo;
4655 let vis = try!(self.parse_visibility());
4656 let (name, node) = if self.eat_keyword(keywords::Type) {
4657 let name = try!(self.parse_ident());
4658 try!(self.expect(&token::Eq));
4659 let typ = try!(self.parse_ty_sum());
4660 try!(self.expect(&token::Semi));
4661 (name, ast::ImplItemKind::Type(typ))
4662 } else if self.is_const_item() {
4663 try!(self.expect_keyword(keywords::Const));
4664 let name = try!(self.parse_ident());
4665 try!(self.expect(&token::Colon));
4666 let typ = try!(self.parse_ty_sum());
4667 try!(self.expect(&token::Eq));
4668 let expr = try!(self.parse_expr());
4669 try!(self.commit_expr_expecting(&expr, token::Semi));
4670 (name, ast::ImplItemKind::Const(typ, expr))
4672 let (name, inner_attrs, node) = try!(self.parse_impl_method(vis));
4673 attrs.extend(inner_attrs);
4678 id: ast::DUMMY_NODE_ID,
4679 span: mk_sp(lo, self.last_span.hi),
4687 fn complain_if_pub_macro(&mut self, visa: Visibility, span: Span) {
4689 Visibility::Public => {
4690 let is_macro_rules: bool = match self.token {
4691 token::Ident(sid, _) => sid.name == intern("macro_rules"),
4695 self.diagnostic().struct_span_err(span, "can't qualify macro_rules \
4696 invocation with `pub`")
4697 .fileline_help(span, "did you mean #[macro_export]?")
4700 self.diagnostic().struct_span_err(span, "can't qualify macro \
4701 invocation with `pub`")
4702 .fileline_help(span, "try adjusting the macro to put `pub` \
4703 inside the invocation")
4707 Visibility::Inherited => (),
4711 /// Parse a method or a macro invocation in a trait impl.
4712 fn parse_impl_method(&mut self, vis: Visibility)
4713 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4714 // code copied from parse_macro_use_or_failure... abstraction!
4715 if !self.token.is_any_keyword()
4716 && self.look_ahead(1, |t| *t == token::Not)
4717 && (self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
4718 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
4721 let last_span = self.last_span;
4722 self.complain_if_pub_macro(vis, last_span);
4724 let lo = self.span.lo;
4725 let pth = try!(self.parse_path(NoTypesAllowed));
4726 try!(self.expect(&token::Not));
4728 // eat a matched-delimiter token tree:
4729 let delim = try!(self.expect_open_delim());
4730 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
4732 |p| p.parse_token_tree()));
4733 let m_ = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
4734 let m: ast::Mac = codemap::Spanned { node: m_,
4736 self.last_span.hi) };
4737 if delim != token::Brace {
4738 try!(self.expect(&token::Semi))
4740 Ok((token::special_idents::invalid, vec![], ast::ImplItemKind::Macro(m)))
4742 let (constness, unsafety, abi) = try!(self.parse_fn_front_matter());
4743 let ident = try!(self.parse_ident());
4744 let mut generics = try!(self.parse_generics());
4745 let (explicit_self, decl) = try!(self.parse_fn_decl_with_self(|p| {
4748 generics.where_clause = try!(self.parse_where_clause());
4749 let (inner_attrs, body) = try!(self.parse_inner_attrs_and_block());
4750 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4753 explicit_self: explicit_self,
4755 constness: constness,
4761 /// Parse trait Foo { ... }
4762 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4764 let ident = try!(self.parse_ident());
4765 let mut tps = try!(self.parse_generics());
4767 // Parse supertrait bounds.
4768 let bounds = try!(self.parse_colon_then_ty_param_bounds(BoundParsingMode::Bare));
4770 tps.where_clause = try!(self.parse_where_clause());
4772 let meths = try!(self.parse_trait_items());
4773 Ok((ident, ItemKind::Trait(unsafety, tps, bounds, meths), None))
4776 /// Parses items implementations variants
4777 /// impl<T> Foo { ... }
4778 /// impl<T> ToString for &'static T { ... }
4779 /// impl Send for .. {}
4780 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> PResult<'a, ItemInfo> {
4781 let impl_span = self.span;
4783 // First, parse type parameters if necessary.
4784 let mut generics = try!(self.parse_generics());
4786 // Special case: if the next identifier that follows is '(', don't
4787 // allow this to be parsed as a trait.
4788 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4790 let neg_span = self.span;
4791 let polarity = if self.eat(&token::Not) {
4792 ast::ImplPolarity::Negative
4794 ast::ImplPolarity::Positive
4798 let mut ty = try!(self.parse_ty_sum());
4800 // Parse traits, if necessary.
4801 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4802 // New-style trait. Reinterpret the type as a trait.
4804 TyKind::Path(None, ref path) => {
4806 path: (*path).clone(),
4811 self.span_err(ty.span, "not a trait");
4817 ast::ImplPolarity::Negative => {
4818 // This is a negated type implementation
4819 // `impl !MyType {}`, which is not allowed.
4820 self.span_err(neg_span, "inherent implementation can't be negated");
4827 if opt_trait.is_some() && self.eat(&token::DotDot) {
4828 if generics.is_parameterized() {
4829 self.span_err(impl_span, "default trait implementations are not \
4830 allowed to have generics");
4833 try!(self.expect(&token::OpenDelim(token::Brace)));
4834 try!(self.expect(&token::CloseDelim(token::Brace)));
4835 Ok((ast_util::impl_pretty_name(&opt_trait, None),
4836 ItemKind::DefaultImpl(unsafety, opt_trait.unwrap()), None))
4838 if opt_trait.is_some() {
4839 ty = try!(self.parse_ty_sum());
4841 generics.where_clause = try!(self.parse_where_clause());
4843 try!(self.expect(&token::OpenDelim(token::Brace)));
4844 let attrs = try!(self.parse_inner_attributes());
4846 let mut impl_items = vec![];
4847 while !self.eat(&token::CloseDelim(token::Brace)) {
4848 impl_items.push(try!(self.parse_impl_item()));
4851 Ok((ast_util::impl_pretty_name(&opt_trait, Some(&*ty)),
4852 ItemKind::Impl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4857 /// Parse a::B<String,i32>
4858 fn parse_trait_ref(&mut self) -> PResult<'a, TraitRef> {
4860 path: try!(self.parse_path(LifetimeAndTypesWithoutColons)),
4861 ref_id: ast::DUMMY_NODE_ID,
4865 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<ast::LifetimeDef>> {
4866 if self.eat_keyword(keywords::For) {
4867 try!(self.expect(&token::Lt));
4868 let lifetime_defs = try!(self.parse_lifetime_defs());
4869 try!(self.expect_gt());
4876 /// Parse for<'l> a::B<String,i32>
4877 fn parse_poly_trait_ref(&mut self) -> PResult<'a, PolyTraitRef> {
4878 let lo = self.span.lo;
4879 let lifetime_defs = try!(self.parse_late_bound_lifetime_defs());
4881 Ok(ast::PolyTraitRef {
4882 bound_lifetimes: lifetime_defs,
4883 trait_ref: try!(self.parse_trait_ref()),
4884 span: mk_sp(lo, self.last_span.hi),
4888 /// Parse struct Foo { ... }
4889 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
4890 let class_name = try!(self.parse_ident());
4891 let mut generics = try!(self.parse_generics());
4893 // There is a special case worth noting here, as reported in issue #17904.
4894 // If we are parsing a tuple struct it is the case that the where clause
4895 // should follow the field list. Like so:
4897 // struct Foo<T>(T) where T: Copy;
4899 // If we are parsing a normal record-style struct it is the case
4900 // that the where clause comes before the body, and after the generics.
4901 // So if we look ahead and see a brace or a where-clause we begin
4902 // parsing a record style struct.
4904 // Otherwise if we look ahead and see a paren we parse a tuple-style
4907 let vdata = if self.token.is_keyword(keywords::Where) {
4908 generics.where_clause = try!(self.parse_where_clause());
4909 if self.eat(&token::Semi) {
4910 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4911 VariantData::Unit(ast::DUMMY_NODE_ID)
4913 // If we see: `struct Foo<T> where T: Copy { ... }`
4914 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4917 // No `where` so: `struct Foo<T>;`
4918 } else if self.eat(&token::Semi) {
4919 VariantData::Unit(ast::DUMMY_NODE_ID)
4920 // Record-style struct definition
4921 } else if self.token == token::OpenDelim(token::Brace) {
4922 VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::Yes)),
4924 // Tuple-style struct definition with optional where-clause.
4925 } else if self.token == token::OpenDelim(token::Paren) {
4926 let body = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::Yes)),
4927 ast::DUMMY_NODE_ID);
4928 generics.where_clause = try!(self.parse_where_clause());
4929 try!(self.expect(&token::Semi));
4932 let token_str = self.this_token_to_string();
4933 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
4934 name, found `{}`", token_str)))
4937 Ok((class_name, ItemKind::Struct(vdata, generics), None))
4940 pub fn parse_record_struct_body(&mut self,
4941 parse_pub: ParsePub)
4942 -> PResult<'a, Vec<StructField>> {
4943 let mut fields = Vec::new();
4944 if self.eat(&token::OpenDelim(token::Brace)) {
4945 while self.token != token::CloseDelim(token::Brace) {
4946 fields.push(try!(self.parse_struct_decl_field(parse_pub)));
4951 let token_str = self.this_token_to_string();
4952 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
4960 pub fn parse_tuple_struct_body(&mut self,
4961 parse_pub: ParsePub)
4962 -> PResult<'a, Vec<StructField>> {
4963 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4964 // Unit like structs are handled in parse_item_struct function
4965 let fields = try!(self.parse_unspanned_seq(
4966 &token::OpenDelim(token::Paren),
4967 &token::CloseDelim(token::Paren),
4968 seq_sep_trailing_allowed(token::Comma),
4970 let attrs = try!(p.parse_outer_attributes());
4972 let struct_field_ = ast::StructField_ {
4973 kind: UnnamedField (
4974 if parse_pub == ParsePub::Yes {
4975 try!(p.parse_visibility())
4977 Visibility::Inherited
4980 id: ast::DUMMY_NODE_ID,
4981 ty: try!(p.parse_ty_sum()),
4984 Ok(spanned(lo, p.span.hi, struct_field_))
4990 /// Parse a structure field declaration
4991 pub fn parse_single_struct_field(&mut self,
4993 attrs: Vec<Attribute> )
4994 -> PResult<'a, StructField> {
4995 let a_var = try!(self.parse_name_and_ty(vis, attrs));
5000 token::CloseDelim(token::Brace) => {}
5002 let span = self.span;
5003 let token_str = self.this_token_to_string();
5004 return Err(self.span_fatal_help(span,
5005 &format!("expected `,`, or `}}`, found `{}`",
5007 "struct fields should be separated by commas"))
5013 /// Parse an element of a struct definition
5014 fn parse_struct_decl_field(&mut self, parse_pub: ParsePub) -> PResult<'a, StructField> {
5016 let attrs = try!(self.parse_outer_attributes());
5018 if self.eat_keyword(keywords::Pub) {
5019 if parse_pub == ParsePub::No {
5020 let span = self.last_span;
5021 self.span_err(span, "`pub` is not allowed here");
5023 return self.parse_single_struct_field(Visibility::Public, attrs);
5026 return self.parse_single_struct_field(Visibility::Inherited, attrs);
5029 /// Parse visibility: PUB or nothing
5030 fn parse_visibility(&mut self) -> PResult<'a, Visibility> {
5031 if self.eat_keyword(keywords::Pub) { Ok(Visibility::Public) }
5032 else { Ok(Visibility::Inherited) }
5035 /// Given a termination token, parse all of the items in a module
5036 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> PResult<'a, Mod> {
5037 let mut items = vec![];
5038 while let Some(item) = try!(self.parse_item()) {
5042 if !self.eat(term) {
5043 let token_str = self.this_token_to_string();
5044 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5047 let hi = if self.span == codemap::DUMMY_SP {
5054 inner: mk_sp(inner_lo, hi),
5059 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5060 let id = try!(self.parse_ident());
5061 try!(self.expect(&token::Colon));
5062 let ty = try!(self.parse_ty_sum());
5063 try!(self.expect(&token::Eq));
5064 let e = try!(self.parse_expr());
5065 try!(self.commit_expr_expecting(&*e, token::Semi));
5066 let item = match m {
5067 Some(m) => ItemKind::Static(ty, m, e),
5068 None => ItemKind::Const(ty, e),
5070 Ok((id, item, None))
5073 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5074 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5075 let id_span = self.span;
5076 let id = try!(self.parse_ident());
5077 if self.check(&token::Semi) {
5079 // This mod is in an external file. Let's go get it!
5080 let (m, attrs) = try!(self.eval_src_mod(id, outer_attrs, id_span));
5081 Ok((id, m, Some(attrs)))
5083 self.push_mod_path(id, outer_attrs);
5084 try!(self.expect(&token::OpenDelim(token::Brace)));
5085 let mod_inner_lo = self.span.lo;
5086 let old_owns_directory = self.owns_directory;
5087 self.owns_directory = true;
5088 let attrs = try!(self.parse_inner_attributes());
5089 let m = try!(self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo));
5090 self.owns_directory = old_owns_directory;
5091 self.pop_mod_path();
5092 Ok((id, ItemKind::Mod(m), Some(attrs)))
5096 fn push_mod_path(&mut self, id: Ident, attrs: &[Attribute]) {
5097 let default_path = self.id_to_interned_str(id);
5098 let file_path = match ::attr::first_attr_value_str_by_name(attrs, "path") {
5100 None => default_path,
5102 self.mod_path_stack.push(file_path)
5105 fn pop_mod_path(&mut self) {
5106 self.mod_path_stack.pop().unwrap();
5109 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5110 ::attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&*d))
5113 /// Returns either a path to a module, or .
5114 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath
5116 let mod_name = id.to_string();
5117 let default_path_str = format!("{}.rs", mod_name);
5118 let secondary_path_str = format!("{}/mod.rs", mod_name);
5119 let default_path = dir_path.join(&default_path_str);
5120 let secondary_path = dir_path.join(&secondary_path_str);
5121 let default_exists = codemap.file_exists(&default_path);
5122 let secondary_exists = codemap.file_exists(&secondary_path);
5124 let result = match (default_exists, secondary_exists) {
5125 (true, false) => Ok(ModulePathSuccess { path: default_path, owns_directory: false }),
5126 (false, true) => Ok(ModulePathSuccess { path: secondary_path, owns_directory: true }),
5127 (false, false) => Err(ModulePathError {
5128 err_msg: format!("file not found for module `{}`", mod_name),
5129 help_msg: format!("name the file either {} or {} inside the directory {:?}",
5132 dir_path.display()),
5134 (true, true) => Err(ModulePathError {
5135 err_msg: format!("file for module `{}` found at both {} and {}",
5138 secondary_path_str),
5139 help_msg: "delete or rename one of them to remove the ambiguity".to_owned(),
5145 path_exists: default_exists || secondary_exists,
5150 fn submod_path(&mut self,
5152 outer_attrs: &[ast::Attribute],
5153 id_sp: Span) -> PResult<'a, ModulePathSuccess> {
5154 let mut prefix = PathBuf::from(&self.sess.codemap().span_to_filename(self.span));
5156 let mut dir_path = prefix;
5157 for part in &self.mod_path_stack {
5158 dir_path.push(&**part);
5161 if let Some(p) = Parser::submod_path_from_attr(outer_attrs, &dir_path) {
5162 return Ok(ModulePathSuccess { path: p, owns_directory: true });
5165 let paths = Parser::default_submod_path(id, &dir_path, self.sess.codemap());
5167 if !self.owns_directory {
5168 let mut err = self.diagnostic().struct_span_err(id_sp,
5169 "cannot declare a new module at this location");
5170 let this_module = match self.mod_path_stack.last() {
5171 Some(name) => name.to_string(),
5172 None => self.root_module_name.as_ref().unwrap().clone(),
5174 err.span_note(id_sp,
5175 &format!("maybe move this module `{0}` to its own directory \
5178 if paths.path_exists {
5179 err.span_note(id_sp,
5180 &format!("... or maybe `use` the module `{}` instead \
5181 of possibly redeclaring it",
5187 match paths.result {
5188 Ok(succ) => Ok(succ),
5189 Err(err) => Err(self.span_fatal_help(id_sp, &err.err_msg, &err.help_msg)),
5193 /// Read a module from a source file.
5194 fn eval_src_mod(&mut self,
5196 outer_attrs: &[ast::Attribute],
5198 -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5199 let ModulePathSuccess { path, owns_directory } = try!(self.submod_path(id,
5203 self.eval_src_mod_from_path(path,
5209 fn eval_src_mod_from_path(&mut self,
5211 owns_directory: bool,
5213 id_sp: Span) -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5214 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5215 match included_mod_stack.iter().position(|p| *p == path) {
5217 let mut err = String::from("circular modules: ");
5218 let len = included_mod_stack.len();
5219 for p in &included_mod_stack[i.. len] {
5220 err.push_str(&p.to_string_lossy());
5221 err.push_str(" -> ");
5223 err.push_str(&path.to_string_lossy());
5224 return Err(self.span_fatal(id_sp, &err[..]));
5228 included_mod_stack.push(path.clone());
5229 drop(included_mod_stack);
5231 let mut p0 = new_sub_parser_from_file(self.sess,
5237 let mod_inner_lo = p0.span.lo;
5238 let mod_attrs = try!(p0.parse_inner_attributes());
5239 let m0 = try!(p0.parse_mod_items(&token::Eof, mod_inner_lo));
5240 self.sess.included_mod_stack.borrow_mut().pop();
5241 Ok((ast::ItemKind::Mod(m0), mod_attrs))
5244 /// Parse a function declaration from a foreign module
5245 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: BytePos,
5246 attrs: Vec<Attribute>) -> PResult<'a, P<ForeignItem>> {
5247 try!(self.expect_keyword(keywords::Fn));
5249 let (ident, mut generics) = try!(self.parse_fn_header());
5250 let decl = try!(self.parse_fn_decl(true));
5251 generics.where_clause = try!(self.parse_where_clause());
5252 let hi = self.span.hi;
5253 try!(self.expect(&token::Semi));
5254 Ok(P(ast::ForeignItem {
5257 node: ForeignItemKind::Fn(decl, generics),
5258 id: ast::DUMMY_NODE_ID,
5259 span: mk_sp(lo, hi),
5264 /// Parse a static item from a foreign module
5265 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: BytePos,
5266 attrs: Vec<Attribute>) -> PResult<'a, P<ForeignItem>> {
5267 try!(self.expect_keyword(keywords::Static));
5268 let mutbl = self.eat_keyword(keywords::Mut);
5270 let ident = try!(self.parse_ident());
5271 try!(self.expect(&token::Colon));
5272 let ty = try!(self.parse_ty_sum());
5273 let hi = self.span.hi;
5274 try!(self.expect(&token::Semi));
5278 node: ForeignItemKind::Static(ty, mutbl),
5279 id: ast::DUMMY_NODE_ID,
5280 span: mk_sp(lo, hi),
5285 /// Parse extern crate links
5289 /// extern crate foo;
5290 /// extern crate bar as foo;
5291 fn parse_item_extern_crate(&mut self,
5293 visibility: Visibility,
5294 attrs: Vec<Attribute>)
5295 -> PResult<'a, P<Item>> {
5297 let crate_name = try!(self.parse_ident());
5298 let (maybe_path, ident) = if let Some(ident) = try!(self.parse_rename()) {
5299 (Some(crate_name.name), ident)
5303 try!(self.expect(&token::Semi));
5305 let last_span = self.last_span;
5307 if visibility == ast::Visibility::Public {
5308 self.span_warn(mk_sp(lo, last_span.hi),
5309 "`pub extern crate` does not work as expected and should not be used. \
5310 Likely to become an error. Prefer `extern crate` and `pub use`.");
5316 ItemKind::ExternCrate(maybe_path),
5321 /// Parse `extern` for foreign ABIs
5324 /// `extern` is expected to have been
5325 /// consumed before calling this method
5331 fn parse_item_foreign_mod(&mut self,
5333 opt_abi: Option<abi::Abi>,
5334 visibility: Visibility,
5335 mut attrs: Vec<Attribute>)
5336 -> PResult<'a, P<Item>> {
5337 try!(self.expect(&token::OpenDelim(token::Brace)));
5339 let abi = opt_abi.unwrap_or(Abi::C);
5341 attrs.extend(try!(self.parse_inner_attributes()));
5343 let mut foreign_items = vec![];
5344 while let Some(item) = try!(self.parse_foreign_item()) {
5345 foreign_items.push(item);
5347 try!(self.expect(&token::CloseDelim(token::Brace)));
5349 let last_span = self.last_span;
5350 let m = ast::ForeignMod {
5352 items: foreign_items
5356 special_idents::invalid,
5357 ItemKind::ForeignMod(m),
5362 /// Parse type Foo = Bar;
5363 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5364 let ident = try!(self.parse_ident());
5365 let mut tps = try!(self.parse_generics());
5366 tps.where_clause = try!(self.parse_where_clause());
5367 try!(self.expect(&token::Eq));
5368 let ty = try!(self.parse_ty_sum());
5369 try!(self.expect(&token::Semi));
5370 Ok((ident, ItemKind::Ty(ty, tps), None))
5373 /// Parse the part of an "enum" decl following the '{'
5374 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5375 let mut variants = Vec::new();
5376 let mut all_nullary = true;
5377 let mut any_disr = None;
5378 while self.token != token::CloseDelim(token::Brace) {
5379 let variant_attrs = try!(self.parse_outer_attributes());
5380 let vlo = self.span.lo;
5383 let mut disr_expr = None;
5384 let ident = try!(self.parse_ident());
5385 if self.check(&token::OpenDelim(token::Brace)) {
5386 // Parse a struct variant.
5387 all_nullary = false;
5388 struct_def = VariantData::Struct(try!(self.parse_record_struct_body(ParsePub::No)),
5389 ast::DUMMY_NODE_ID);
5390 } else if self.check(&token::OpenDelim(token::Paren)) {
5391 all_nullary = false;
5392 struct_def = VariantData::Tuple(try!(self.parse_tuple_struct_body(ParsePub::No)),
5393 ast::DUMMY_NODE_ID);
5394 } else if self.eat(&token::Eq) {
5395 disr_expr = Some(try!(self.parse_expr()));
5396 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5397 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5399 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5402 let vr = ast::Variant_ {
5404 attrs: variant_attrs,
5406 disr_expr: disr_expr,
5408 variants.push(P(spanned(vlo, self.last_span.hi, vr)));
5410 if !self.eat(&token::Comma) { break; }
5412 try!(self.expect(&token::CloseDelim(token::Brace)));
5414 Some(disr_span) if !all_nullary =>
5415 self.span_err(disr_span,
5416 "discriminator values can only be used with a c-like enum"),
5420 Ok(ast::EnumDef { variants: variants })
5423 /// Parse an "enum" declaration
5424 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5425 let id = try!(self.parse_ident());
5426 let mut generics = try!(self.parse_generics());
5427 generics.where_clause = try!(self.parse_where_clause());
5428 try!(self.expect(&token::OpenDelim(token::Brace)));
5430 let enum_definition = try!(self.parse_enum_def(&generics));
5431 Ok((id, ItemKind::Enum(enum_definition, generics), None))
5434 /// Parses a string as an ABI spec on an extern type or module. Consumes
5435 /// the `extern` keyword, if one is found.
5436 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5438 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5440 self.expect_no_suffix(sp, "ABI spec", suf);
5442 match abi::lookup(&s.as_str()) {
5443 Some(abi) => Ok(Some(abi)),
5445 let last_span = self.last_span;
5448 &format!("invalid ABI: expected one of [{}], \
5450 abi::all_names().join(", "),
5461 /// Parse one of the items allowed by the flags.
5462 /// NB: this function no longer parses the items inside an
5464 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5465 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5466 let nt_item = match self.token {
5467 token::Interpolated(token::NtItem(ref item)) => {
5468 Some((**item).clone())
5475 let mut attrs = attrs;
5476 mem::swap(&mut item.attrs, &mut attrs);
5477 item.attrs.extend(attrs);
5478 return Ok(Some(P(item)));
5483 let lo = self.span.lo;
5485 let visibility = try!(self.parse_visibility());
5487 if self.eat_keyword(keywords::Use) {
5489 let item_ = ItemKind::Use(try!(self.parse_view_path()));
5490 try!(self.expect(&token::Semi));
5492 let last_span = self.last_span;
5493 let item = self.mk_item(lo,
5495 token::special_idents::invalid,
5499 return Ok(Some(item));
5502 if self.eat_keyword(keywords::Extern) {
5503 if self.eat_keyword(keywords::Crate) {
5504 return Ok(Some(try!(self.parse_item_extern_crate(lo, visibility, attrs))));
5507 let opt_abi = try!(self.parse_opt_abi());
5509 if self.eat_keyword(keywords::Fn) {
5510 // EXTERN FUNCTION ITEM
5511 let abi = opt_abi.unwrap_or(Abi::C);
5512 let (ident, item_, extra_attrs) =
5513 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, abi));
5514 let last_span = self.last_span;
5515 let item = self.mk_item(lo,
5520 maybe_append(attrs, extra_attrs));
5521 return Ok(Some(item));
5522 } else if self.check(&token::OpenDelim(token::Brace)) {
5523 return Ok(Some(try!(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs))));
5526 try!(self.unexpected());
5529 if self.eat_keyword(keywords::Static) {
5531 let m = if self.eat_keyword(keywords::Mut) {
5534 Mutability::Immutable
5536 let (ident, item_, extra_attrs) = try!(self.parse_item_const(Some(m)));
5537 let last_span = self.last_span;
5538 let item = self.mk_item(lo,
5543 maybe_append(attrs, extra_attrs));
5544 return Ok(Some(item));
5546 if self.eat_keyword(keywords::Const) {
5547 if self.check_keyword(keywords::Fn)
5548 || (self.check_keyword(keywords::Unsafe)
5549 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5550 // CONST FUNCTION ITEM
5551 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5557 let (ident, item_, extra_attrs) =
5558 try!(self.parse_item_fn(unsafety, Constness::Const, Abi::Rust));
5559 let last_span = self.last_span;
5560 let item = self.mk_item(lo,
5565 maybe_append(attrs, extra_attrs));
5566 return Ok(Some(item));
5570 if self.eat_keyword(keywords::Mut) {
5571 let last_span = self.last_span;
5572 self.diagnostic().struct_span_err(last_span, "const globals cannot be mutable")
5573 .fileline_help(last_span, "did you mean to declare a static?")
5576 let (ident, item_, extra_attrs) = try!(self.parse_item_const(None));
5577 let last_span = self.last_span;
5578 let item = self.mk_item(lo,
5583 maybe_append(attrs, extra_attrs));
5584 return Ok(Some(item));
5586 if self.check_keyword(keywords::Unsafe) &&
5587 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5589 // UNSAFE TRAIT ITEM
5590 try!(self.expect_keyword(keywords::Unsafe));
5591 try!(self.expect_keyword(keywords::Trait));
5592 let (ident, item_, extra_attrs) =
5593 try!(self.parse_item_trait(ast::Unsafety::Unsafe));
5594 let last_span = self.last_span;
5595 let item = self.mk_item(lo,
5600 maybe_append(attrs, extra_attrs));
5601 return Ok(Some(item));
5603 if self.check_keyword(keywords::Unsafe) &&
5604 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5607 try!(self.expect_keyword(keywords::Unsafe));
5608 try!(self.expect_keyword(keywords::Impl));
5609 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Unsafe));
5610 let last_span = self.last_span;
5611 let item = self.mk_item(lo,
5616 maybe_append(attrs, extra_attrs));
5617 return Ok(Some(item));
5619 if self.check_keyword(keywords::Fn) {
5622 let (ident, item_, extra_attrs) =
5623 try!(self.parse_item_fn(Unsafety::Normal, Constness::NotConst, Abi::Rust));
5624 let last_span = self.last_span;
5625 let item = self.mk_item(lo,
5630 maybe_append(attrs, extra_attrs));
5631 return Ok(Some(item));
5633 if self.check_keyword(keywords::Unsafe)
5634 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5635 // UNSAFE FUNCTION ITEM
5637 let abi = if self.eat_keyword(keywords::Extern) {
5638 try!(self.parse_opt_abi()).unwrap_or(Abi::C)
5642 try!(self.expect_keyword(keywords::Fn));
5643 let (ident, item_, extra_attrs) =
5644 try!(self.parse_item_fn(Unsafety::Unsafe, Constness::NotConst, abi));
5645 let last_span = self.last_span;
5646 let item = self.mk_item(lo,
5651 maybe_append(attrs, extra_attrs));
5652 return Ok(Some(item));
5654 if self.eat_keyword(keywords::Mod) {
5656 let (ident, item_, extra_attrs) =
5657 try!(self.parse_item_mod(&attrs[..]));
5658 let last_span = self.last_span;
5659 let item = self.mk_item(lo,
5664 maybe_append(attrs, extra_attrs));
5665 return Ok(Some(item));
5667 if self.eat_keyword(keywords::Type) {
5669 let (ident, item_, extra_attrs) = try!(self.parse_item_type());
5670 let last_span = self.last_span;
5671 let item = self.mk_item(lo,
5676 maybe_append(attrs, extra_attrs));
5677 return Ok(Some(item));
5679 if self.eat_keyword(keywords::Enum) {
5681 let (ident, item_, extra_attrs) = try!(self.parse_item_enum());
5682 let last_span = self.last_span;
5683 let item = self.mk_item(lo,
5688 maybe_append(attrs, extra_attrs));
5689 return Ok(Some(item));
5691 if self.eat_keyword(keywords::Trait) {
5693 let (ident, item_, extra_attrs) =
5694 try!(self.parse_item_trait(ast::Unsafety::Normal));
5695 let last_span = self.last_span;
5696 let item = self.mk_item(lo,
5701 maybe_append(attrs, extra_attrs));
5702 return Ok(Some(item));
5704 if self.eat_keyword(keywords::Impl) {
5706 let (ident, item_, extra_attrs) = try!(self.parse_item_impl(ast::Unsafety::Normal));
5707 let last_span = self.last_span;
5708 let item = self.mk_item(lo,
5713 maybe_append(attrs, extra_attrs));
5714 return Ok(Some(item));
5716 if self.eat_keyword(keywords::Struct) {
5718 let (ident, item_, extra_attrs) = try!(self.parse_item_struct());
5719 let last_span = self.last_span;
5720 let item = self.mk_item(lo,
5725 maybe_append(attrs, extra_attrs));
5726 return Ok(Some(item));
5728 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5731 /// Parse a foreign item.
5732 fn parse_foreign_item(&mut self) -> PResult<'a, Option<P<ForeignItem>>> {
5733 let attrs = try!(self.parse_outer_attributes());
5734 let lo = self.span.lo;
5735 let visibility = try!(self.parse_visibility());
5737 if self.check_keyword(keywords::Static) {
5738 // FOREIGN STATIC ITEM
5739 return Ok(Some(try!(self.parse_item_foreign_static(visibility, lo, attrs))));
5741 if self.check_keyword(keywords::Fn) || self.check_keyword(keywords::Unsafe) {
5742 // FOREIGN FUNCTION ITEM
5743 return Ok(Some(try!(self.parse_item_foreign_fn(visibility, lo, attrs))));
5746 // FIXME #5668: this will occur for a macro invocation:
5747 match try!(self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)) {
5749 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5755 /// This is the fall-through for parsing items.
5756 fn parse_macro_use_or_failure(
5758 attrs: Vec<Attribute> ,
5759 macros_allowed: bool,
5760 attributes_allowed: bool,
5762 visibility: Visibility
5763 ) -> PResult<'a, Option<P<Item>>> {
5764 if macros_allowed && !self.token.is_any_keyword()
5765 && self.look_ahead(1, |t| *t == token::Not)
5766 && (self.look_ahead(2, |t| t.is_plain_ident())
5767 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Paren))
5768 || self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))) {
5769 // MACRO INVOCATION ITEM
5771 let last_span = self.last_span;
5772 self.complain_if_pub_macro(visibility, last_span);
5774 let mac_lo = self.span.lo;
5777 let pth = try!(self.parse_path(NoTypesAllowed));
5778 try!(self.expect(&token::Not));
5780 // a 'special' identifier (like what `macro_rules!` uses)
5781 // is optional. We should eventually unify invoc syntax
5783 let id = if self.token.is_plain_ident() {
5784 try!(self.parse_ident())
5786 token::special_idents::invalid // no special identifier
5788 // eat a matched-delimiter token tree:
5789 let delim = try!(self.expect_open_delim());
5790 let tts = try!(self.parse_seq_to_end(&token::CloseDelim(delim),
5792 |p| p.parse_token_tree()));
5793 // single-variant-enum... :
5794 let m = Mac_ { path: pth, tts: tts, ctxt: EMPTY_CTXT };
5795 let m: ast::Mac = codemap::Spanned { node: m,
5797 self.last_span.hi) };
5799 if delim != token::Brace {
5800 if !self.eat(&token::Semi) {
5801 let last_span = self.last_span;
5802 self.span_err(last_span,
5803 "macros that expand to items must either \
5804 be surrounded with braces or followed by \
5809 let item_ = ItemKind::Mac(m);
5810 let last_span = self.last_span;
5811 let item = self.mk_item(lo,
5817 return Ok(Some(item));
5820 // FAILURE TO PARSE ITEM
5822 Visibility::Inherited => {}
5823 Visibility::Public => {
5824 let last_span = self.last_span;
5825 return Err(self.span_fatal(last_span, "unmatched visibility `pub`"));
5829 if !attributes_allowed && !attrs.is_empty() {
5830 self.expected_item_err(&attrs);
5835 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
5836 let attrs = try!(self.parse_outer_attributes());
5837 self.parse_item_(attrs, true, false)
5841 /// Matches view_path : MOD? non_global_path as IDENT
5842 /// | MOD? non_global_path MOD_SEP LBRACE RBRACE
5843 /// | MOD? non_global_path MOD_SEP LBRACE ident_seq RBRACE
5844 /// | MOD? non_global_path MOD_SEP STAR
5845 /// | MOD? non_global_path
5846 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
5847 let lo = self.span.lo;
5849 // Allow a leading :: because the paths are absolute either way.
5850 // This occurs with "use $crate::..." in macros.
5851 self.eat(&token::ModSep);
5853 if self.check(&token::OpenDelim(token::Brace)) {
5855 let idents = try!(self.parse_unspanned_seq(
5856 &token::OpenDelim(token::Brace),
5857 &token::CloseDelim(token::Brace),
5858 seq_sep_trailing_allowed(token::Comma),
5859 |p| p.parse_path_list_item()));
5860 let path = ast::Path {
5861 span: mk_sp(lo, self.span.hi),
5863 segments: Vec::new()
5865 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5868 let first_ident = try!(self.parse_ident());
5869 let mut path = vec!(first_ident);
5870 if let token::ModSep = self.token {
5871 // foo::bar or foo::{a,b,c} or foo::*
5872 while self.check(&token::ModSep) {
5876 token::Ident(..) => {
5877 let ident = try!(self.parse_ident());
5881 // foo::bar::{a,b,c}
5882 token::OpenDelim(token::Brace) => {
5883 let idents = try!(self.parse_unspanned_seq(
5884 &token::OpenDelim(token::Brace),
5885 &token::CloseDelim(token::Brace),
5886 seq_sep_trailing_allowed(token::Comma),
5887 |p| p.parse_path_list_item()
5889 let path = ast::Path {
5890 span: mk_sp(lo, self.span.hi),
5892 segments: path.into_iter().map(|identifier| {
5894 identifier: identifier,
5895 parameters: ast::PathParameters::none(),
5899 return Ok(P(spanned(lo, self.span.hi, ViewPathList(path, idents))));
5903 token::BinOp(token::Star) => {
5905 let path = ast::Path {
5906 span: mk_sp(lo, self.span.hi),
5908 segments: path.into_iter().map(|identifier| {
5910 identifier: identifier,
5911 parameters: ast::PathParameters::none(),
5915 return Ok(P(spanned(lo, self.span.hi, ViewPathGlob(path))));
5918 // fall-through for case foo::bar::;
5920 self.span_err(self.span, "expected identifier or `{` or `*`, found `;`");
5927 let mut rename_to = path[path.len() - 1];
5928 let path = ast::Path {
5929 span: mk_sp(lo, self.last_span.hi),
5931 segments: path.into_iter().map(|identifier| {
5933 identifier: identifier,
5934 parameters: ast::PathParameters::none(),
5938 rename_to = try!(self.parse_rename()).unwrap_or(rename_to);
5939 Ok(P(spanned(lo, self.last_span.hi, ViewPathSimple(rename_to, path))))
5942 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
5943 if self.eat_keyword(keywords::As) {
5944 self.parse_ident().map(Some)
5950 /// Parses a source module as a crate. This is the main
5951 /// entry point for the parser.
5952 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
5953 let lo = self.span.lo;
5955 attrs: try!(self.parse_inner_attributes()),
5956 module: try!(self.parse_mod_items(&token::Eof, lo)),
5957 config: self.cfg.clone(),
5958 span: mk_sp(lo, self.span.lo),
5959 exported_macros: Vec::new(),
5963 pub fn parse_optional_str(&mut self)
5964 -> Option<(InternedString,
5966 Option<ast::Name>)> {
5967 let ret = match self.token {
5968 token::Literal(token::Str_(s), suf) => {
5969 let s = self.id_to_interned_str(ast::Ident::with_empty_ctxt(s));
5970 (s, ast::StrStyle::Cooked, suf)
5972 token::Literal(token::StrRaw(s, n), suf) => {
5973 let s = self.id_to_interned_str(ast::Ident::with_empty_ctxt(s));
5974 (s, ast::StrStyle::Raw(n), suf)
5982 pub fn parse_str(&mut self) -> PResult<'a, (InternedString, StrStyle)> {
5983 match self.parse_optional_str() {
5984 Some((s, style, suf)) => {
5985 let sp = self.last_span;
5986 self.expect_no_suffix(sp, "string literal", suf);
5989 _ => Err(self.fatal("expected string literal"))