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.
12 use ast::{AttrStyle, BareFnTy};
13 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
15 use ast::{Mod, Arg, Arm, Attribute, BindingMode, TraitItemKind};
17 use ast::{BlockCheckMode, CaptureBy};
18 use ast::{Constness, Crate};
21 use ast::{Expr, ExprKind, RangeLimits};
22 use ast::{Field, FnDecl};
23 use ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
24 use ast::{Ident, ImplItem, Item, ItemKind};
25 use ast::{Lifetime, LifetimeDef, Lit, LitKind, UintTy};
27 use ast::MacStmtStyle;
29 use ast::{MutTy, Mutability};
30 use ast::{Pat, PatKind, PathSegment};
31 use ast::{PolyTraitRef, QSelf};
32 use ast::{Stmt, StmtKind};
33 use ast::{VariantData, StructField};
36 use ast::{TraitItem, TraitRef};
37 use ast::{Ty, TyKind, TypeBinding, TyParam, TyParamBounds};
38 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
39 use ast::{Visibility, WhereClause};
40 use ast::{BinOpKind, UnOp};
43 use codemap::{self, CodeMap, Spanned, spanned, respan};
44 use syntax_pos::{self, Span, Pos, BytePos, mk_sp};
45 use errors::{self, DiagnosticBuilder};
46 use parse::{self, classify, token};
47 use parse::common::SeqSep;
48 use parse::lexer::TokenAndSpan;
49 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
50 use parse::obsolete::ObsoleteSyntax;
51 use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
52 use util::parser::{AssocOp, Fixity};
56 use tokenstream::{self, Delimited, ThinTokenStream, TokenTree, TokenStream};
57 use symbol::{Symbol, keywords};
60 use std::collections::HashSet;
61 use std::{cmp, mem, slice};
62 use std::path::{Path, PathBuf};
65 flags Restrictions: u8 {
66 const RESTRICTION_STMT_EXPR = 1 << 0,
67 const RESTRICTION_NO_STRUCT_LITERAL = 1 << 1,
71 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute> >);
73 /// How to parse a path. There are three different kinds of paths, all of which
74 /// are parsed somewhat differently.
75 #[derive(Copy, Clone, PartialEq)]
77 /// A path with no type parameters, e.g. `foo::bar::Baz`, used in imports or visibilities.
79 /// A path with a lifetime and type parameters, with no double colons
80 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`, used in types.
81 /// Paths using this style can be passed into macros expecting `path` nonterminals.
83 /// A path with a lifetime and type parameters with double colons before
84 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`, used in expressions or patterns.
88 #[derive(Clone, Copy, PartialEq)]
89 pub enum SemiColonMode {
94 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
95 /// dropped into the token stream, which happens while parsing the result of
96 /// macro expansion). Placement of these is not as complex as I feared it would
97 /// be. The important thing is to make sure that lookahead doesn't balk at
98 /// `token::Interpolated` tokens.
99 macro_rules! maybe_whole_expr {
101 if let token::Interpolated(nt) = $p.token.clone() {
103 token::NtExpr(ref e) => {
105 return Ok((*e).clone());
107 token::NtPath(ref path) => {
110 let kind = ExprKind::Path(None, (*path).clone());
111 return Ok($p.mk_expr(span.lo, span.hi, kind, ThinVec::new()));
113 token::NtBlock(ref block) => {
116 let kind = ExprKind::Block((*block).clone());
117 return Ok($p.mk_expr(span.lo, span.hi, kind, ThinVec::new()));
125 /// As maybe_whole_expr, but for things other than expressions
126 macro_rules! maybe_whole {
127 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
128 if let token::Interpolated(nt) = $p.token.clone() {
129 if let token::$constructor($x) = (*nt).clone() {
137 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
139 if let Some(ref attrs) = rhs {
140 lhs.extend(attrs.iter().cloned())
154 /* ident is handled by common.rs */
156 pub struct Parser<'a> {
157 pub sess: &'a ParseSess,
158 /// the current token:
159 pub token: token::Token,
160 /// the span of the current token:
162 /// the span of the previous token:
164 /// the previous token kind
165 prev_token_kind: PrevTokenKind,
166 pub restrictions: Restrictions,
167 /// The set of seen errors about obsolete syntax. Used to suppress
168 /// extra detail when the same error is seen twice
169 pub obsolete_set: HashSet<ObsoleteSyntax>,
170 /// Used to determine the path to externally loaded source files
171 pub directory: Directory,
172 /// Name of the root module this parser originated from. If `None`, then the
173 /// name is not known. This does not change while the parser is descending
174 /// into modules, and sub-parsers have new values for this name.
175 pub root_module_name: Option<String>,
176 pub expected_tokens: Vec<TokenType>,
177 token_cursor: TokenCursor,
178 pub desugar_doc_comments: bool,
179 /// Whether we should configure out of line modules as we parse.
184 frame: TokenCursorFrame,
185 stack: Vec<TokenCursorFrame>,
188 struct TokenCursorFrame {
189 delim: token::DelimToken,
192 tree_cursor: tokenstream::Cursor,
196 impl TokenCursorFrame {
197 fn new(sp: Span, delimited: &Delimited) -> Self {
199 delim: delimited.delim,
201 open_delim: delimited.delim == token::NoDelim,
202 tree_cursor: delimited.stream().into_trees(),
203 close_delim: delimited.delim == token::NoDelim,
209 fn next(&mut self) -> TokenAndSpan {
211 let tree = if !self.frame.open_delim {
212 self.frame.open_delim = true;
213 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
214 .open_tt(self.frame.span)
215 } else if let Some(tree) = self.frame.tree_cursor.next() {
217 } else if !self.frame.close_delim {
218 self.frame.close_delim = true;
219 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
220 .close_tt(self.frame.span)
221 } else if let Some(frame) = self.stack.pop() {
225 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
229 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
230 TokenTree::Delimited(sp, ref delimited) => {
231 let frame = TokenCursorFrame::new(sp, delimited);
232 self.stack.push(mem::replace(&mut self.frame, frame));
238 fn next_desugared(&mut self) -> TokenAndSpan {
239 let (sp, name) = match self.next() {
240 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
241 tok @ _ => return tok,
244 let stripped = strip_doc_comment_decoration(&name.as_str());
246 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
247 // required to wrap the text.
248 let mut num_of_hashes = 0;
250 for ch in stripped.chars() {
253 '#' if count > 0 => count + 1,
256 num_of_hashes = cmp::max(num_of_hashes, count);
259 let body = TokenTree::Delimited(sp, Delimited {
260 delim: token::Bracket,
261 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"))),
262 TokenTree::Token(sp, token::Eq),
263 TokenTree::Token(sp, token::Literal(
264 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
265 .iter().cloned().collect::<TokenStream>().into(),
268 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
269 delim: token::NoDelim,
270 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
271 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
272 .iter().cloned().collect::<TokenStream>().into()
274 [TokenTree::Token(sp, token::Pound), body]
275 .iter().cloned().collect::<TokenStream>().into()
283 #[derive(PartialEq, Eq, Clone)]
286 Keyword(keywords::Keyword),
295 fn to_string(&self) -> String {
297 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
298 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
299 TokenType::Operator => "an operator".to_string(),
300 TokenType::Lifetime => "lifetime".to_string(),
301 TokenType::Ident => "identifier".to_string(),
302 TokenType::Path => "path".to_string(),
303 TokenType::Type => "type".to_string(),
308 fn is_ident_or_underscore(t: &token::Token) -> bool {
309 t.is_ident() || *t == token::Underscore
312 /// Information about the path to a module.
313 pub struct ModulePath {
315 pub path_exists: bool,
316 pub result: Result<ModulePathSuccess, Error>,
319 pub struct ModulePathSuccess {
321 pub directory_ownership: DirectoryOwnership,
325 pub struct ModulePathError {
327 pub help_msg: String,
331 FileNotFoundForModule {
333 default_path: String,
334 secondary_path: String,
339 default_path: String,
340 secondary_path: String,
343 InclusiveRangeWithNoEnd,
347 pub fn span_err<'a>(self, sp: Span, handler: &'a errors::Handler) -> DiagnosticBuilder<'a> {
349 Error::FileNotFoundForModule { ref mod_name,
353 let mut err = struct_span_err!(handler, sp, E0583,
354 "file not found for module `{}`", mod_name);
355 err.help(&format!("name the file either {} or {} inside the directory {:?}",
361 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
362 let mut err = struct_span_err!(handler, sp, E0584,
363 "file for module `{}` found at both {} and {}",
367 err.help("delete or rename one of them to remove the ambiguity");
370 Error::UselessDocComment => {
371 let mut err = struct_span_err!(handler, sp, E0585,
372 "found a documentation comment that doesn't document anything");
373 err.help("doc comments must come before what they document, maybe a comment was \
374 intended with `//`?");
377 Error::InclusiveRangeWithNoEnd => {
378 let mut err = struct_span_err!(handler, sp, E0586,
379 "inclusive range with no end");
380 err.help("inclusive ranges must be bounded at the end (`...b` or `a...b`)");
389 AttributesParsed(ThinVec<Attribute>),
390 AlreadyParsed(P<Expr>),
393 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
394 fn from(o: Option<ThinVec<Attribute>>) -> Self {
395 if let Some(attrs) = o {
396 LhsExpr::AttributesParsed(attrs)
398 LhsExpr::NotYetParsed
403 impl From<P<Expr>> for LhsExpr {
404 fn from(expr: P<Expr>) -> Self {
405 LhsExpr::AlreadyParsed(expr)
409 impl<'a> Parser<'a> {
410 pub fn new(sess: &'a ParseSess,
412 directory: Option<Directory>,
413 desugar_doc_comments: bool)
415 let mut parser = Parser {
417 token: token::Underscore,
418 span: syntax_pos::DUMMY_SP,
419 prev_span: syntax_pos::DUMMY_SP,
420 prev_token_kind: PrevTokenKind::Other,
421 restrictions: Restrictions::empty(),
422 obsolete_set: HashSet::new(),
423 directory: Directory { path: PathBuf::new(), ownership: DirectoryOwnership::Owned },
424 root_module_name: None,
425 expected_tokens: Vec::new(),
426 token_cursor: TokenCursor {
427 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
428 delim: token::NoDelim,
433 desugar_doc_comments: desugar_doc_comments,
437 let tok = parser.next_tok();
438 parser.token = tok.tok;
439 parser.span = tok.sp;
440 if let Some(directory) = directory {
441 parser.directory = directory;
442 } else if parser.span != syntax_pos::DUMMY_SP {
443 parser.directory.path = PathBuf::from(sess.codemap().span_to_filename(parser.span));
444 parser.directory.path.pop();
449 fn next_tok(&mut self) -> TokenAndSpan {
450 let mut next = match self.desugar_doc_comments {
451 true => self.token_cursor.next_desugared(),
452 false => self.token_cursor.next(),
454 if next.sp == syntax_pos::DUMMY_SP {
455 next.sp = self.prev_span;
460 /// Convert a token to a string using self's reader
461 pub fn token_to_string(token: &token::Token) -> String {
462 pprust::token_to_string(token)
465 /// Convert the current token to a string using self's reader
466 pub fn this_token_to_string(&self) -> String {
467 Parser::token_to_string(&self.token)
470 pub fn this_token_descr(&self) -> String {
471 let s = self.this_token_to_string();
472 if self.token.is_strict_keyword() {
473 format!("keyword `{}`", s)
474 } else if self.token.is_reserved_keyword() {
475 format!("reserved keyword `{}`", s)
481 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
482 let token_str = Parser::token_to_string(t);
483 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
486 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
487 match self.expect_one_of(&[], &[]) {
489 Ok(_) => unreachable!(),
493 /// Expect and consume the token t. Signal an error if
494 /// the next token is not t.
495 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
496 if self.expected_tokens.is_empty() {
497 if self.token == *t {
501 let token_str = Parser::token_to_string(t);
502 let this_token_str = self.this_token_to_string();
503 Err(self.fatal(&format!("expected `{}`, found `{}`",
508 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
512 /// Expect next token to be edible or inedible token. If edible,
513 /// then consume it; if inedible, then return without consuming
514 /// anything. Signal a fatal error if next token is unexpected.
515 pub fn expect_one_of(&mut self,
516 edible: &[token::Token],
517 inedible: &[token::Token]) -> PResult<'a, ()>{
518 fn tokens_to_string(tokens: &[TokenType]) -> String {
519 let mut i = tokens.iter();
520 // This might be a sign we need a connect method on Iterator.
522 .map_or("".to_string(), |t| t.to_string());
523 i.enumerate().fold(b, |mut b, (i, ref a)| {
524 if tokens.len() > 2 && i == tokens.len() - 2 {
526 } else if tokens.len() == 2 && i == tokens.len() - 2 {
531 b.push_str(&a.to_string());
535 if edible.contains(&self.token) {
538 } else if inedible.contains(&self.token) {
539 // leave it in the input
542 let mut expected = edible.iter()
543 .map(|x| TokenType::Token(x.clone()))
544 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
545 .chain(self.expected_tokens.iter().cloned())
546 .collect::<Vec<_>>();
547 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
549 let expect = tokens_to_string(&expected[..]);
550 let actual = self.this_token_to_string();
552 &(if expected.len() > 1 {
553 (format!("expected one of {}, found `{}`",
556 } else if expected.is_empty() {
557 (format!("unexpected token: `{}`",
560 (format!("expected {}, found `{}`",
568 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
569 fn interpolated_or_expr_span(&self,
570 expr: PResult<'a, P<Expr>>)
571 -> PResult<'a, (Span, P<Expr>)> {
573 if self.prev_token_kind == PrevTokenKind::Interpolated {
581 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
582 self.check_strict_keywords();
583 self.check_reserved_keywords();
590 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
591 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
593 let mut err = self.fatal(&format!("expected identifier, found `{}`",
594 self.this_token_to_string()));
595 if self.token == token::Underscore {
596 err.note("`_` is a wildcard pattern, not an identifier");
604 /// Check if the next token is `tok`, and return `true` if so.
606 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
608 pub fn check(&mut self, tok: &token::Token) -> bool {
609 let is_present = self.token == *tok;
610 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
614 /// Consume token 'tok' if it exists. Returns true if the given
615 /// token was present, false otherwise.
616 pub fn eat(&mut self, tok: &token::Token) -> bool {
617 let is_present = self.check(tok);
618 if is_present { self.bump() }
622 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
623 self.expected_tokens.push(TokenType::Keyword(kw));
624 self.token.is_keyword(kw)
627 /// If the next token is the given keyword, eat it and return
628 /// true. Otherwise, return false.
629 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
630 if self.check_keyword(kw) {
638 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
639 if self.token.is_keyword(kw) {
647 pub fn check_contextual_keyword(&mut self, ident: Ident) -> bool {
648 self.expected_tokens.push(TokenType::Token(token::Ident(ident)));
649 if let token::Ident(ref cur_ident) = self.token {
650 cur_ident.name == ident.name
656 pub fn eat_contextual_keyword(&mut self, ident: Ident) -> bool {
657 if self.check_contextual_keyword(ident) {
665 /// If the given word is not a keyword, signal an error.
666 /// If the next token is not the given word, signal an error.
667 /// Otherwise, eat it.
668 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
669 if !self.eat_keyword(kw) {
676 /// Signal an error if the given string is a strict keyword
677 pub fn check_strict_keywords(&mut self) {
678 if self.token.is_strict_keyword() {
679 let token_str = self.this_token_to_string();
680 let span = self.span;
682 &format!("expected identifier, found keyword `{}`",
687 /// Signal an error if the current token is a reserved keyword
688 pub fn check_reserved_keywords(&mut self) {
689 if self.token.is_reserved_keyword() {
690 let token_str = self.this_token_to_string();
691 self.fatal(&format!("`{}` is a reserved keyword", token_str)).emit()
695 fn check_ident(&mut self) -> bool {
696 if self.token.is_ident() {
699 self.expected_tokens.push(TokenType::Ident);
704 fn check_path(&mut self) -> bool {
705 if self.token.is_path_start() {
708 self.expected_tokens.push(TokenType::Path);
713 fn check_type(&mut self) -> bool {
714 if self.token.can_begin_type() {
717 self.expected_tokens.push(TokenType::Type);
722 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
723 /// `&` and continue. If an `&` is not seen, signal an error.
724 fn expect_and(&mut self) -> PResult<'a, ()> {
725 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
727 token::BinOp(token::And) => {
732 let span = self.span;
733 let lo = span.lo + BytePos(1);
734 Ok(self.bump_with(token::BinOp(token::And), lo, span.hi))
736 _ => self.unexpected()
740 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
742 None => {/* everything ok */}
744 let text = suf.as_str();
746 self.span_bug(sp, "found empty literal suffix in Some")
748 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
753 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
754 /// `<` and continue. If a `<` is not seen, return false.
756 /// This is meant to be used when parsing generics on a path to get the
758 fn eat_lt(&mut self) -> bool {
759 self.expected_tokens.push(TokenType::Token(token::Lt));
765 token::BinOp(token::Shl) => {
766 let span = self.span;
767 let lo = span.lo + BytePos(1);
768 self.bump_with(token::Lt, lo, span.hi);
775 fn expect_lt(&mut self) -> PResult<'a, ()> {
783 /// Expect and consume a GT. if a >> is seen, replace it
784 /// with a single > and continue. If a GT is not seen,
786 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
787 self.expected_tokens.push(TokenType::Token(token::Gt));
793 token::BinOp(token::Shr) => {
794 let span = self.span;
795 let lo = span.lo + BytePos(1);
796 Ok(self.bump_with(token::Gt, lo, span.hi))
798 token::BinOpEq(token::Shr) => {
799 let span = self.span;
800 let lo = span.lo + BytePos(1);
801 Ok(self.bump_with(token::Ge, lo, span.hi))
804 let span = self.span;
805 let lo = span.lo + BytePos(1);
806 Ok(self.bump_with(token::Eq, lo, span.hi))
808 _ => self.unexpected()
812 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
813 sep: Option<token::Token>,
815 -> PResult<'a, (Vec<T>, bool)>
816 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
818 let mut v = Vec::new();
819 // This loop works by alternating back and forth between parsing types
820 // and commas. For example, given a string `A, B,>`, the parser would
821 // first parse `A`, then a comma, then `B`, then a comma. After that it
822 // would encounter a `>` and stop. This lets the parser handle trailing
823 // commas in generic parameters, because it can stop either after
824 // parsing a type or after parsing a comma.
826 if self.check(&token::Gt)
827 || self.token == token::BinOp(token::Shr)
828 || self.token == token::Ge
829 || self.token == token::BinOpEq(token::Shr) {
835 Some(result) => v.push(result),
836 None => return Ok((v, true))
839 if let Some(t) = sep.as_ref() {
845 return Ok((v, false));
848 /// Parse a sequence bracketed by '<' and '>', stopping
850 pub fn parse_seq_to_before_gt<T, F>(&mut self,
851 sep: Option<token::Token>,
853 -> PResult<'a, Vec<T>> where
854 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
856 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
857 |p| Ok(Some(f(p)?)))?;
862 pub fn parse_seq_to_gt<T, F>(&mut self,
863 sep: Option<token::Token>,
865 -> PResult<'a, Vec<T>> where
866 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
868 let v = self.parse_seq_to_before_gt(sep, f)?;
873 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
874 sep: Option<token::Token>,
876 -> PResult<'a, (Vec<T>, bool)> where
877 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
879 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
883 return Ok((v, returned));
886 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
887 /// passes through any errors encountered. Used for error recovery.
888 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
889 let handler = self.diagnostic();
891 self.parse_seq_to_before_tokens(kets,
893 |p| Ok(p.parse_token_tree()),
894 |mut e| handler.cancel(&mut e));
897 /// Parse a sequence, including the closing delimiter. The function
898 /// f must consume tokens until reaching the next separator or
900 pub fn parse_seq_to_end<T, F>(&mut self,
904 -> PResult<'a, Vec<T>> where
905 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
907 let val = self.parse_seq_to_before_end(ket, sep, f);
912 /// Parse a sequence, not including the closing delimiter. The function
913 /// f must consume tokens until reaching the next separator or
915 pub fn parse_seq_to_before_end<T, F>(&mut self,
920 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
922 self.parse_seq_to_before_tokens(&[ket], sep, f, |mut e| e.emit())
925 // `fe` is an error handler.
926 fn parse_seq_to_before_tokens<T, F, Fe>(&mut self,
927 kets: &[&token::Token],
932 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
933 Fe: FnMut(DiagnosticBuilder)
935 let mut first: bool = true;
937 while !kets.contains(&&self.token) {
939 token::CloseDelim(..) | token::Eof => break,
947 if let Err(e) = self.expect(t) {
955 if sep.trailing_sep_allowed && kets.iter().any(|k| self.check(k)) {
971 /// Parse a sequence, including the closing delimiter. The function
972 /// f must consume tokens until reaching the next separator or
974 pub fn parse_unspanned_seq<T, F>(&mut self,
979 -> PResult<'a, Vec<T>> where
980 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
983 let result = self.parse_seq_to_before_end(ket, sep, f);
984 if self.token == *ket {
990 // NB: Do not use this function unless you actually plan to place the
991 // spanned list in the AST.
992 pub fn parse_seq<T, F>(&mut self,
997 -> PResult<'a, Spanned<Vec<T>>> where
998 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1000 let lo = self.span.lo;
1002 let result = self.parse_seq_to_before_end(ket, sep, f);
1003 let hi = self.span.hi;
1005 Ok(spanned(lo, hi, result))
1008 /// Advance the parser by one token
1009 pub fn bump(&mut self) {
1010 if self.prev_token_kind == PrevTokenKind::Eof {
1011 // Bumping after EOF is a bad sign, usually an infinite loop.
1012 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1015 self.prev_span = self.span;
1017 // Record last token kind for possible error recovery.
1018 self.prev_token_kind = match self.token {
1019 token::DocComment(..) => PrevTokenKind::DocComment,
1020 token::Comma => PrevTokenKind::Comma,
1021 token::Interpolated(..) => PrevTokenKind::Interpolated,
1022 token::Eof => PrevTokenKind::Eof,
1023 _ => PrevTokenKind::Other,
1026 let next = self.next_tok();
1027 self.span = next.sp;
1028 self.token = next.tok;
1029 self.expected_tokens.clear();
1030 // check after each token
1031 self.check_unknown_macro_variable();
1034 /// Advance the parser using provided token as a next one. Use this when
1035 /// consuming a part of a token. For example a single `<` from `<<`.
1036 pub fn bump_with(&mut self,
1040 self.prev_span = mk_sp(self.span.lo, lo);
1041 // It would be incorrect to record the kind of the current token, but
1042 // fortunately for tokens currently using `bump_with`, the
1043 // prev_token_kind will be of no use anyway.
1044 self.prev_token_kind = PrevTokenKind::Other;
1045 self.span = mk_sp(lo, hi);
1047 self.expected_tokens.clear();
1050 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1051 F: FnOnce(&token::Token) -> R,
1054 return f(&self.token)
1057 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1058 Some(tree) => match tree {
1059 TokenTree::Token(_, tok) => tok,
1060 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1062 None => token::CloseDelim(self.token_cursor.frame.delim),
1065 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1066 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1068 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1069 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1071 pub fn span_fatal_err(&self, sp: Span, err: Error) -> DiagnosticBuilder<'a> {
1072 err.span_err(sp, self.diagnostic())
1074 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1075 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1079 pub fn bug(&self, m: &str) -> ! {
1080 self.sess.span_diagnostic.span_bug(self.span, m)
1082 pub fn warn(&self, m: &str) {
1083 self.sess.span_diagnostic.span_warn(self.span, m)
1085 pub fn span_warn(&self, sp: Span, m: &str) {
1086 self.sess.span_diagnostic.span_warn(sp, m)
1088 pub fn span_err(&self, sp: Span, m: &str) {
1089 self.sess.span_diagnostic.span_err(sp, m)
1091 pub fn span_err_help(&self, sp: Span, m: &str, h: &str) {
1092 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1096 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1097 self.sess.span_diagnostic.span_bug(sp, m)
1099 pub fn abort_if_errors(&self) {
1100 self.sess.span_diagnostic.abort_if_errors();
1103 fn cancel(&self, err: &mut DiagnosticBuilder) {
1104 self.sess.span_diagnostic.cancel(err)
1107 pub fn diagnostic(&self) -> &'a errors::Handler {
1108 &self.sess.span_diagnostic
1111 /// Is the current token one of the keywords that signals a bare function
1113 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1114 self.check_keyword(keywords::Fn) ||
1115 self.check_keyword(keywords::Unsafe) ||
1116 self.check_keyword(keywords::Extern)
1119 pub fn get_lifetime(&mut self) -> ast::Ident {
1121 token::Lifetime(ref ident) => *ident,
1122 _ => self.bug("not a lifetime"),
1126 pub fn parse_for_in_type(&mut self) -> PResult<'a, TyKind> {
1128 Parses whatever can come after a `for` keyword in a type.
1129 The `for` hasn't been consumed.
1131 - for <'lt> [unsafe] [extern "ABI"] fn (S) -> T
1132 - for <'lt> path::foo(a, b) + Trait + 'a
1135 let lo = self.span.lo;
1136 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1138 // examine next token to decide to do
1139 if self.token_is_bare_fn_keyword() {
1140 self.parse_ty_bare_fn(lifetime_defs)
1142 let hi = self.span.hi;
1143 let trait_ref = self.parse_trait_ref()?;
1144 let poly_trait_ref = PolyTraitRef { bound_lifetimes: lifetime_defs,
1145 trait_ref: trait_ref,
1146 span: mk_sp(lo, hi)};
1147 let other_bounds = if self.eat(&token::BinOp(token::Plus)) {
1148 self.parse_ty_param_bounds()?
1153 Some(TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)).into_iter()
1154 .chain(other_bounds)
1156 Ok(ast::TyKind::TraitObject(all_bounds))
1160 pub fn parse_impl_trait_type(&mut self) -> PResult<'a, TyKind> {
1161 // Parses whatever can come after a `impl` keyword in a type.
1162 // The `impl` has already been consumed.
1163 Ok(ast::TyKind::ImplTrait(self.parse_ty_param_bounds()?))
1166 pub fn parse_ty_path(&mut self) -> PResult<'a, TyKind> {
1167 Ok(TyKind::Path(None, self.parse_path(PathStyle::Type)?))
1170 /// parse a TyKind::BareFn type:
1171 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<LifetimeDef>)
1172 -> PResult<'a, TyKind> {
1175 [unsafe] [extern "ABI"] fn (S) -> T
1185 let unsafety = self.parse_unsafety()?;
1186 let abi = if self.eat_keyword(keywords::Extern) {
1187 self.parse_opt_abi()?.unwrap_or(Abi::C)
1192 self.expect_keyword(keywords::Fn)?;
1193 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1194 let ret_ty = self.parse_ret_ty()?;
1195 let decl = P(FnDecl {
1200 Ok(TyKind::BareFn(P(BareFnTy {
1203 lifetimes: lifetime_defs,
1208 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1209 if self.eat_keyword(keywords::Unsafe) {
1210 return Ok(Unsafety::Unsafe);
1212 return Ok(Unsafety::Normal);
1216 /// Parse the items in a trait declaration
1217 pub fn parse_trait_item(&mut self) -> PResult<'a, TraitItem> {
1218 maybe_whole!(self, NtTraitItem, |x| x);
1219 let mut attrs = self.parse_outer_attributes()?;
1220 let lo = self.span.lo;
1222 let (name, node) = if self.eat_keyword(keywords::Type) {
1223 let TyParam {ident, bounds, default, ..} = self.parse_ty_param(vec![])?;
1224 self.expect(&token::Semi)?;
1225 (ident, TraitItemKind::Type(bounds, default))
1226 } else if self.is_const_item() {
1227 self.expect_keyword(keywords::Const)?;
1228 let ident = self.parse_ident()?;
1229 self.expect(&token::Colon)?;
1230 let ty = self.parse_ty()?;
1231 let default = if self.check(&token::Eq) {
1233 let expr = self.parse_expr()?;
1234 self.expect(&token::Semi)?;
1237 self.expect(&token::Semi)?;
1240 (ident, TraitItemKind::Const(ty, default))
1241 } else if self.token.is_path_start() {
1242 // trait item macro.
1243 // code copied from parse_macro_use_or_failure... abstraction!
1244 let lo = self.span.lo;
1245 let pth = self.parse_path(PathStyle::Mod)?;
1246 self.expect(&token::Not)?;
1248 // eat a matched-delimiter token tree:
1249 let (delim, tts) = self.expect_delimited_token_tree()?;
1250 if delim != token::Brace {
1251 self.expect(&token::Semi)?
1254 let mac = spanned(lo, self.prev_span.hi, Mac_ { path: pth, tts: tts });
1255 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac))
1257 let (constness, unsafety, abi) = match self.parse_fn_front_matter() {
1262 token::Eof => break,
1263 token::CloseDelim(token::Brace) |
1268 token::OpenDelim(token::Brace) => {
1269 self.parse_token_tree();
1280 let ident = self.parse_ident()?;
1281 let mut generics = self.parse_generics()?;
1283 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1284 // This is somewhat dubious; We don't want to allow
1285 // argument names to be left off if there is a
1287 p.parse_arg_general(false)
1290 generics.where_clause = self.parse_where_clause()?;
1291 let sig = ast::MethodSig {
1293 constness: constness,
1299 let body = match self.token {
1302 debug!("parse_trait_methods(): parsing required method");
1305 token::OpenDelim(token::Brace) => {
1306 debug!("parse_trait_methods(): parsing provided method");
1307 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1308 attrs.extend(inner_attrs.iter().cloned());
1312 let token_str = self.this_token_to_string();
1313 return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str)));
1316 (ident, ast::TraitItemKind::Method(sig, body))
1320 id: ast::DUMMY_NODE_ID,
1324 span: mk_sp(lo, self.prev_span.hi),
1329 /// Parse the items in a trait declaration
1330 pub fn parse_trait_items(&mut self) -> PResult<'a, Vec<TraitItem>> {
1331 self.parse_unspanned_seq(
1332 &token::OpenDelim(token::Brace),
1333 &token::CloseDelim(token::Brace),
1335 |p| -> PResult<'a, TraitItem> {
1336 p.parse_trait_item()
1340 /// Parse optional return type [ -> TY ] in function decl
1341 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1342 if self.eat(&token::RArrow) {
1343 Ok(FunctionRetTy::Ty(self.parse_ty_no_plus()?))
1345 let pos = self.span.lo;
1346 Ok(FunctionRetTy::Default(mk_sp(pos, pos)))
1351 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1352 let lo = self.span.lo;
1353 let lhs = self.parse_ty_no_plus()?;
1355 if !self.eat(&token::BinOp(token::Plus)) {
1359 let mut bounds = self.parse_ty_param_bounds()?;
1361 // In type grammar, `+` is treated like a binary operator,
1362 // and hence both L and R side are required.
1363 if bounds.is_empty() {
1364 let prev_span = self.prev_span;
1365 self.span_err(prev_span,
1366 "at least one type parameter bound \
1367 must be specified");
1370 let mut lhs = lhs.unwrap();
1371 if let TyKind::Paren(ty) = lhs.node {
1372 // We have to accept the first bound in parens for backward compatibility.
1373 // Example: `(Bound) + Bound + Bound`
1376 if let TyKind::Path(None, path) = lhs.node {
1377 let poly_trait_ref = PolyTraitRef {
1378 bound_lifetimes: Vec::new(),
1379 trait_ref: TraitRef { path: path, ref_id: lhs.id },
1382 let poly_trait_ref = TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None);
1383 bounds.insert(0, poly_trait_ref);
1385 let mut err = struct_span_err!(self.sess.span_diagnostic, lhs.span, E0178,
1386 "expected a path on the left-hand side \
1388 pprust::ty_to_string(&lhs));
1389 err.span_label(lhs.span, &format!("expected a path"));
1390 let hi = bounds.iter().map(|x| match *x {
1391 TraitTyParamBound(ref tr, _) => tr.span.hi,
1392 RegionTyParamBound(ref r) => r.span.hi,
1393 }).max_by_key(|x| x.to_usize());
1394 let full_span = hi.map(|hi| Span {
1397 expn_id: lhs.span.expn_id,
1399 match (&lhs.node, full_span) {
1400 (&TyKind::Rptr(ref lifetime, ref mut_ty), Some(full_span)) => {
1401 let ty_str = pprust::to_string(|s| {
1402 use print::pp::word;
1403 use print::pprust::PrintState;
1405 word(&mut s.s, "&")?;
1406 s.print_opt_lifetime(lifetime)?;
1407 s.print_mutability(mut_ty.mutbl)?;
1409 s.print_type(&mut_ty.ty)?;
1410 s.print_bounds(" +", &bounds)?;
1413 err.span_suggestion(full_span, "try adding parentheses (per RFC 438):",
1419 "perhaps you forgot parentheses? (per RFC 438)");
1425 let sp = mk_sp(lo, self.prev_span.hi);
1426 let sum = TyKind::TraitObject(bounds);
1427 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: sum, span: sp}))
1430 /// Parse a type in restricted contexts where `+` is not permitted.
1431 /// Example 1: `&'a TYPE`
1432 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1433 /// Example 2: `value1 as TYPE + value2`
1434 /// `+` is prohibited to avoid interactions with expression grammar.
1435 pub fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1436 maybe_whole!(self, NtTy, |x| x);
1438 let lo = self.span.lo;
1440 let t = if self.eat(&token::OpenDelim(token::Paren)) {
1441 // (t) is a parenthesized ty
1442 // (t,) is the type of a tuple with only one field,
1444 let mut ts = vec![];
1445 let mut last_comma = false;
1446 while self.token != token::CloseDelim(token::Paren) {
1447 ts.push(self.parse_ty()?);
1448 if self.eat(&token::Comma) {
1456 self.expect(&token::CloseDelim(token::Paren))?;
1457 if ts.len() == 1 && !last_comma {
1458 TyKind::Paren(ts.into_iter().nth(0).unwrap())
1462 } else if self.eat(&token::Not) {
1464 } else if self.eat(&token::BinOp(token::Star)) {
1465 // STAR POINTER (bare pointer?)
1466 TyKind::Ptr(self.parse_ptr()?)
1467 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1469 let t = self.parse_ty()?;
1471 // Parse the `; e` in `[ i32; e ]`
1472 // where `e` is a const expression
1473 let t = match self.maybe_parse_fixed_length_of_vec()? {
1474 None => TyKind::Slice(t),
1475 Some(suffix) => TyKind::Array(t, suffix)
1477 self.expect(&token::CloseDelim(token::Bracket))?;
1479 } else if self.check(&token::BinOp(token::And)) ||
1480 self.check(&token::AndAnd) {
1483 self.parse_borrowed_pointee()?
1484 } else if self.check_keyword(keywords::For) {
1485 // FIXME `+` has incorrect priority in trait object types starting with `for` (#39317).
1486 self.parse_for_in_type()?
1487 } else if self.eat_keyword(keywords::Impl) {
1488 // FIXME figure out priority of `+` in `impl Trait1 + Trait2` (#34511).
1489 self.parse_impl_trait_type()?
1490 } else if self.token_is_bare_fn_keyword() {
1492 self.parse_ty_bare_fn(Vec::new())?
1493 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1495 // In order to not be ambiguous, the type must be surrounded by parens.
1496 self.expect(&token::OpenDelim(token::Paren))?;
1497 let e = self.parse_expr()?;
1498 self.expect(&token::CloseDelim(token::Paren))?;
1500 } else if self.eat_lt() {
1501 let (qself, path) = self.parse_qualified_path(PathStyle::Type)?;
1502 TyKind::Path(Some(qself), path)
1503 } else if self.token.is_path_start() {
1504 let path = self.parse_path(PathStyle::Type)?;
1505 if self.eat(&token::Not) {
1507 let (_, tts) = self.expect_delimited_token_tree()?;
1508 let hi = self.span.hi;
1509 TyKind::Mac(spanned(lo, hi, Mac_ { path: path, tts: tts }))
1512 TyKind::Path(None, path)
1514 } else if self.eat(&token::Underscore) {
1515 // TYPE TO BE INFERRED
1518 let msg = format!("expected type, found {}", self.this_token_descr());
1519 return Err(self.fatal(&msg));
1522 let sp = mk_sp(lo, self.prev_span.hi);
1523 Ok(P(Ty {id: ast::DUMMY_NODE_ID, node: t, span: sp}))
1526 pub fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1527 // look for `&'lt` or `&'foo ` and interpret `foo` as the region name:
1528 let opt_lifetime = self.eat_lifetime();
1529 let mutbl = self.parse_mutability()?;
1530 let ty = self.parse_ty_no_plus()?;
1531 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1534 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1535 let mutbl = if self.eat_keyword(keywords::Mut) {
1537 } else if self.eat_keyword(keywords::Const) {
1538 Mutability::Immutable
1540 let span = self.prev_span;
1542 "expected mut or const in raw pointer type (use \
1543 `*mut T` or `*const T` as appropriate)");
1544 Mutability::Immutable
1546 let t = self.parse_ty_no_plus()?;
1547 Ok(MutTy { ty: t, mutbl: mutbl })
1550 pub fn is_named_argument(&mut self) -> bool {
1551 let offset = match self.token {
1552 token::BinOp(token::And) => 1,
1554 _ if self.token.is_keyword(keywords::Mut) => 1,
1558 debug!("parser is_named_argument offset:{}", offset);
1561 is_ident_or_underscore(&self.token)
1562 && self.look_ahead(1, |t| *t == token::Colon)
1564 self.look_ahead(offset, |t| is_ident_or_underscore(t))
1565 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1569 /// This version of parse arg doesn't necessarily require
1570 /// identifier names.
1571 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1572 maybe_whole!(self, NtArg, |x| x);
1574 let pat = if require_name || self.is_named_argument() {
1575 debug!("parse_arg_general parse_pat (require_name:{})",
1577 let pat = self.parse_pat()?;
1579 self.expect(&token::Colon)?;
1582 debug!("parse_arg_general ident_to_pat");
1583 let sp = self.prev_span;
1584 let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1586 id: ast::DUMMY_NODE_ID,
1587 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1593 let t = self.parse_ty()?;
1598 id: ast::DUMMY_NODE_ID,
1602 /// Parse a single function argument
1603 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1604 self.parse_arg_general(true)
1607 /// Parse an argument in a lambda header e.g. |arg, arg|
1608 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1609 let pat = self.parse_pat()?;
1610 let t = if self.eat(&token::Colon) {
1614 id: ast::DUMMY_NODE_ID,
1615 node: TyKind::Infer,
1616 span: mk_sp(self.span.lo, self.span.hi),
1622 id: ast::DUMMY_NODE_ID
1626 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1627 if self.eat(&token::Semi) {
1628 Ok(Some(self.parse_expr()?))
1634 /// Matches token_lit = LIT_INTEGER | ...
1635 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1636 let out = match self.token {
1637 token::Interpolated(ref nt) => match **nt {
1638 token::NtExpr(ref v) => match v.node {
1639 ExprKind::Lit(ref lit) => { lit.node.clone() }
1640 _ => { return self.unexpected_last(&self.token); }
1642 _ => { return self.unexpected_last(&self.token); }
1644 token::Literal(lit, suf) => {
1645 let diag = Some((self.span, &self.sess.span_diagnostic));
1646 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1650 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1655 _ => { return self.unexpected_last(&self.token); }
1662 /// Matches lit = true | false | token_lit
1663 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1664 let lo = self.span.lo;
1665 let lit = if self.eat_keyword(keywords::True) {
1667 } else if self.eat_keyword(keywords::False) {
1668 LitKind::Bool(false)
1670 let lit = self.parse_lit_token()?;
1673 Ok(codemap::Spanned { node: lit, span: mk_sp(lo, self.prev_span.hi) })
1676 /// matches '-' lit | lit
1677 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1678 let minus_lo = self.span.lo;
1679 let minus_present = self.eat(&token::BinOp(token::Minus));
1680 let lo = self.span.lo;
1681 let literal = P(self.parse_lit()?);
1682 let hi = self.prev_span.hi;
1683 let expr = self.mk_expr(lo, hi, ExprKind::Lit(literal), ThinVec::new());
1686 let minus_hi = self.prev_span.hi;
1687 let unary = self.mk_unary(UnOp::Neg, expr);
1688 Ok(self.mk_expr(minus_lo, minus_hi, unary, ThinVec::new()))
1694 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1696 token::Ident(sid) if self.token.is_path_segment_keyword() => {
1700 _ => self.parse_ident(),
1704 /// Parses qualified path.
1706 /// Assumes that the leading `<` has been parsed already.
1708 /// Qualifed paths are a part of the universal function call
1711 /// `qualified_path = <type [as trait_ref]>::path`
1713 /// See `parse_path` for `mode` meaning.
1718 /// `<T as U>::F::a::<S>`
1719 pub fn parse_qualified_path(&mut self, mode: PathStyle)
1720 -> PResult<'a, (QSelf, ast::Path)> {
1721 let span = self.prev_span;
1722 let self_type = self.parse_ty()?;
1723 let mut path = if self.eat_keyword(keywords::As) {
1724 self.parse_path(PathStyle::Type)?
1734 position: path.segments.len()
1737 self.expect(&token::Gt)?;
1738 self.expect(&token::ModSep)?;
1740 let segments = match mode {
1741 PathStyle::Type => {
1742 self.parse_path_segments_without_colons()?
1744 PathStyle::Expr => {
1745 self.parse_path_segments_with_colons()?
1748 self.parse_path_segments_without_types()?
1751 path.segments.extend(segments);
1753 path.span.hi = self.prev_span.hi;
1758 /// Parses a path and optional type parameter bounds, depending on the
1759 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1760 /// bounds are permitted and whether `::` must precede type parameter
1762 pub fn parse_path(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> {
1763 maybe_whole!(self, NtPath, |x| x);
1765 let lo = self.span.lo;
1766 let is_global = self.eat(&token::ModSep);
1768 // Parse any number of segments and bound sets. A segment is an
1769 // identifier followed by an optional lifetime and a set of types.
1770 // A bound set is a set of type parameter bounds.
1771 let mut segments = match mode {
1772 PathStyle::Type => {
1773 self.parse_path_segments_without_colons()?
1775 PathStyle::Expr => {
1776 self.parse_path_segments_with_colons()?
1779 self.parse_path_segments_without_types()?
1784 segments.insert(0, PathSegment::crate_root());
1787 // Assemble the span.
1788 // FIXME(#39450) This is bogus if part of the path is macro generated.
1789 let span = mk_sp(lo, self.prev_span.hi);
1791 // Assemble the result.
1799 /// - `a::b<T,U>::c<V,W>`
1800 /// - `a::b<T,U>::c(V) -> W`
1801 /// - `a::b<T,U>::c(V)`
1802 pub fn parse_path_segments_without_colons(&mut self) -> PResult<'a, Vec<PathSegment>> {
1803 let mut segments = Vec::new();
1805 // First, parse an identifier.
1806 let identifier = self.parse_path_segment_ident()?;
1807 let ident_span = self.prev_span;
1809 if self.check(&token::ModSep) && self.look_ahead(1, |t| *t == token::Lt) {
1811 let prev_span = self.prev_span;
1813 let mut err = self.diagnostic().struct_span_err(prev_span,
1814 "unexpected token: `::`");
1816 "use `<...>` instead of `::<...>` if you meant to specify type arguments");
1820 // Parse types, optionally.
1821 let parameters = if self.eat_lt() {
1822 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1824 ast::AngleBracketedParameterData {
1825 lifetimes: lifetimes,
1829 } else if self.eat(&token::OpenDelim(token::Paren)) {
1830 let lo = self.prev_span.lo;
1832 let inputs = self.parse_seq_to_end(
1833 &token::CloseDelim(token::Paren),
1834 SeqSep::trailing_allowed(token::Comma),
1837 let output_ty = if self.eat(&token::RArrow) {
1838 Some(self.parse_ty_no_plus()?)
1843 let hi = self.prev_span.hi;
1845 Some(P(ast::PathParameters::Parenthesized(ast::ParenthesizedParameterData {
1846 span: mk_sp(lo, hi),
1854 // Assemble and push the result.
1855 segments.push(PathSegment {
1856 identifier: identifier,
1858 parameters: parameters
1861 // Continue only if we see a `::`
1862 if !self.eat(&token::ModSep) {
1863 return Ok(segments);
1869 /// - `a::b::<T,U>::c`
1870 pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec<PathSegment>> {
1871 let mut segments = Vec::new();
1873 // First, parse an identifier.
1874 let identifier = self.parse_path_segment_ident()?;
1875 let ident_span = self.prev_span;
1877 // If we do not see a `::`, stop.
1878 if !self.eat(&token::ModSep) {
1879 segments.push(PathSegment::from_ident(identifier, ident_span));
1880 return Ok(segments);
1883 // Check for a type segment.
1885 // Consumed `a::b::<`, go look for types
1886 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1888 segments.push(PathSegment {
1889 identifier: identifier,
1891 parameters: ast::AngleBracketedParameterData {
1892 lifetimes: lifetimes,
1898 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1899 if !self.eat(&token::ModSep) {
1900 return Ok(segments);
1903 // Consumed `a::`, go look for `b`
1904 segments.push(PathSegment::from_ident(identifier, ident_span));
1911 pub fn parse_path_segments_without_types(&mut self)
1912 -> PResult<'a, Vec<PathSegment>> {
1913 let mut segments = Vec::new();
1915 // First, parse an identifier.
1916 let identifier = self.parse_path_segment_ident()?;
1918 // Assemble and push the result.
1919 segments.push(PathSegment::from_ident(identifier, self.prev_span));
1921 // If we do not see a `::` or see `::{`/`::*`, stop.
1922 if !self.check(&token::ModSep) || self.is_import_coupler() {
1923 return Ok(segments);
1930 /// Parse single lifetime 'a or nothing.
1931 pub fn eat_lifetime(&mut self) -> Option<Lifetime> {
1933 token::Lifetime(ident) => {
1936 id: ast::DUMMY_NODE_ID,
1937 span: self.prev_span,
1942 self.expected_tokens.push(TokenType::Lifetime);
1948 /// Parse mutability (`mut` or nothing).
1949 pub fn parse_mutability(&mut self) -> PResult<'a, Mutability> {
1950 if self.eat_keyword(keywords::Mut) {
1951 Ok(Mutability::Mutable)
1953 Ok(Mutability::Immutable)
1957 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1958 if let token::Literal(token::Integer(name), None) = self.token {
1960 Ok(Ident::with_empty_ctxt(name))
1966 /// Parse ident (COLON expr)?
1967 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1968 let attrs = self.parse_outer_attributes()?;
1969 let lo = self.span.lo;
1972 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1973 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1974 let fieldname = self.parse_field_name()?;
1976 hi = self.prev_span.hi;
1977 (fieldname, self.parse_expr()?, false)
1979 let fieldname = self.parse_ident()?;
1980 hi = self.prev_span.hi;
1982 // Mimic `x: x` for the `x` field shorthand.
1983 let path = ast::Path::from_ident(mk_sp(lo, hi), fieldname);
1984 (fieldname, self.mk_expr(lo, hi, ExprKind::Path(None, path), ThinVec::new()), true)
1987 ident: spanned(lo, hi, fieldname),
1988 span: mk_sp(lo, expr.span.hi),
1990 is_shorthand: is_shorthand,
1991 attrs: attrs.into(),
1995 pub fn mk_expr(&mut self, lo: BytePos, hi: BytePos, node: ExprKind, attrs: ThinVec<Attribute>)
1998 id: ast::DUMMY_NODE_ID,
2000 span: mk_sp(lo, hi),
2001 attrs: attrs.into(),
2005 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2006 ExprKind::Unary(unop, expr)
2009 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2010 ExprKind::Binary(binop, lhs, rhs)
2013 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2014 ExprKind::Call(f, args)
2017 fn mk_method_call(&mut self,
2018 ident: ast::SpannedIdent,
2022 ExprKind::MethodCall(ident, tps, args)
2025 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2026 ExprKind::Index(expr, idx)
2029 pub fn mk_range(&mut self,
2030 start: Option<P<Expr>>,
2031 end: Option<P<Expr>>,
2032 limits: RangeLimits)
2033 -> PResult<'a, ast::ExprKind> {
2034 if end.is_none() && limits == RangeLimits::Closed {
2035 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2037 Ok(ExprKind::Range(start, end, limits))
2041 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::ExprKind {
2042 ExprKind::Field(expr, ident)
2045 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2046 ExprKind::TupField(expr, idx)
2049 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2050 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2051 ExprKind::AssignOp(binop, lhs, rhs)
2054 pub fn mk_mac_expr(&mut self, lo: BytePos, hi: BytePos,
2055 m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2057 id: ast::DUMMY_NODE_ID,
2058 node: ExprKind::Mac(codemap::Spanned {node: m, span: mk_sp(lo, hi)}),
2059 span: mk_sp(lo, hi),
2064 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2065 let span = &self.span;
2066 let lv_lit = P(codemap::Spanned {
2067 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2072 id: ast::DUMMY_NODE_ID,
2073 node: ExprKind::Lit(lv_lit),
2079 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2081 token::OpenDelim(delim) => match self.parse_token_tree() {
2082 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2083 _ => unreachable!(),
2085 _ => Err(self.fatal("expected open delimiter")),
2089 /// At the bottom (top?) of the precedence hierarchy,
2090 /// parse things like parenthesized exprs,
2091 /// macros, return, etc.
2093 /// NB: This does not parse outer attributes,
2094 /// and is private because it only works
2095 /// correctly if called from parse_dot_or_call_expr().
2096 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2097 maybe_whole_expr!(self);
2099 // Outer attributes are already parsed and will be
2100 // added to the return value after the fact.
2102 // Therefore, prevent sub-parser from parsing
2103 // attributes by giving them a empty "already parsed" list.
2104 let mut attrs = ThinVec::new();
2106 let lo = self.span.lo;
2107 let mut hi = self.span.hi;
2111 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2113 token::OpenDelim(token::Paren) => {
2116 attrs.extend(self.parse_inner_attributes()?);
2118 // (e) is parenthesized e
2119 // (e,) is a tuple with only one field, e
2120 let mut es = vec![];
2121 let mut trailing_comma = false;
2122 while self.token != token::CloseDelim(token::Paren) {
2123 es.push(self.parse_expr()?);
2124 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2125 if self.check(&token::Comma) {
2126 trailing_comma = true;
2130 trailing_comma = false;
2136 hi = self.prev_span.hi;
2137 return if es.len() == 1 && !trailing_comma {
2138 Ok(self.mk_expr(lo, hi, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs))
2140 Ok(self.mk_expr(lo, hi, ExprKind::Tup(es), attrs))
2143 token::OpenDelim(token::Brace) => {
2144 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2146 token::BinOp(token::Or) | token::OrOr => {
2147 let lo = self.span.lo;
2148 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2150 token::OpenDelim(token::Bracket) => {
2153 attrs.extend(self.parse_inner_attributes()?);
2155 if self.check(&token::CloseDelim(token::Bracket)) {
2158 ex = ExprKind::Array(Vec::new());
2161 let first_expr = self.parse_expr()?;
2162 if self.check(&token::Semi) {
2163 // Repeating array syntax: [ 0; 512 ]
2165 let count = self.parse_expr()?;
2166 self.expect(&token::CloseDelim(token::Bracket))?;
2167 ex = ExprKind::Repeat(first_expr, count);
2168 } else if self.check(&token::Comma) {
2169 // Vector with two or more elements.
2171 let remaining_exprs = self.parse_seq_to_end(
2172 &token::CloseDelim(token::Bracket),
2173 SeqSep::trailing_allowed(token::Comma),
2174 |p| Ok(p.parse_expr()?)
2176 let mut exprs = vec![first_expr];
2177 exprs.extend(remaining_exprs);
2178 ex = ExprKind::Array(exprs);
2180 // Vector with one element.
2181 self.expect(&token::CloseDelim(token::Bracket))?;
2182 ex = ExprKind::Array(vec![first_expr]);
2185 hi = self.prev_span.hi;
2190 self.parse_qualified_path(PathStyle::Expr)?;
2192 return Ok(self.mk_expr(lo, hi, ExprKind::Path(Some(qself), path), attrs));
2194 if self.eat_keyword(keywords::Move) {
2195 let lo = self.prev_span.lo;
2196 return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2198 if self.eat_keyword(keywords::If) {
2199 return self.parse_if_expr(attrs);
2201 if self.eat_keyword(keywords::For) {
2202 let lo = self.prev_span.lo;
2203 return self.parse_for_expr(None, lo, attrs);
2205 if self.eat_keyword(keywords::While) {
2206 let lo = self.prev_span.lo;
2207 return self.parse_while_expr(None, lo, attrs);
2209 if self.token.is_lifetime() {
2210 let label = Spanned { node: self.get_lifetime(),
2212 let lo = self.span.lo;
2214 self.expect(&token::Colon)?;
2215 if self.eat_keyword(keywords::While) {
2216 return self.parse_while_expr(Some(label), lo, attrs)
2218 if self.eat_keyword(keywords::For) {
2219 return self.parse_for_expr(Some(label), lo, attrs)
2221 if self.eat_keyword(keywords::Loop) {
2222 return self.parse_loop_expr(Some(label), lo, attrs)
2224 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2226 if self.eat_keyword(keywords::Loop) {
2227 let lo = self.prev_span.lo;
2228 return self.parse_loop_expr(None, lo, attrs);
2230 if self.eat_keyword(keywords::Continue) {
2231 let ex = if self.token.is_lifetime() {
2232 let ex = ExprKind::Continue(Some(Spanned{
2233 node: self.get_lifetime(),
2239 ExprKind::Continue(None)
2241 let hi = self.prev_span.hi;
2242 return Ok(self.mk_expr(lo, hi, ex, attrs));
2244 if self.eat_keyword(keywords::Match) {
2245 return self.parse_match_expr(attrs);
2247 if self.eat_keyword(keywords::Unsafe) {
2248 return self.parse_block_expr(
2250 BlockCheckMode::Unsafe(ast::UserProvided),
2253 if self.is_catch_expr() {
2254 assert!(self.eat_keyword(keywords::Do));
2255 assert!(self.eat_keyword(keywords::Catch));
2256 let lo = self.prev_span.lo;
2257 return self.parse_catch_expr(lo, attrs);
2259 if self.eat_keyword(keywords::Return) {
2260 if self.token.can_begin_expr() {
2261 let e = self.parse_expr()?;
2263 ex = ExprKind::Ret(Some(e));
2265 ex = ExprKind::Ret(None);
2267 } else if self.eat_keyword(keywords::Break) {
2268 let lt = if self.token.is_lifetime() {
2269 let spanned_lt = Spanned {
2270 node: self.get_lifetime(),
2278 let e = if self.token.can_begin_expr()
2279 && !(self.token == token::OpenDelim(token::Brace)
2280 && self.restrictions.contains(
2281 Restrictions::RESTRICTION_NO_STRUCT_LITERAL)) {
2282 Some(self.parse_expr()?)
2286 ex = ExprKind::Break(lt, e);
2287 hi = self.prev_span.hi;
2288 } else if self.token.is_keyword(keywords::Let) {
2289 // Catch this syntax error here, instead of in `check_strict_keywords`, so
2290 // that we can explicitly mention that let is not to be used as an expression
2291 let mut db = self.fatal("expected expression, found statement (`let`)");
2292 db.note("variable declaration using `let` is a statement");
2294 } else if self.token.is_path_start() {
2295 let pth = self.parse_path(PathStyle::Expr)?;
2297 // `!`, as an operator, is prefix, so we know this isn't that
2298 if self.eat(&token::Not) {
2299 // MACRO INVOCATION expression
2300 let (_, tts) = self.expect_delimited_token_tree()?;
2301 let hi = self.prev_span.hi;
2302 return Ok(self.mk_mac_expr(lo, hi, Mac_ { path: pth, tts: tts }, attrs));
2304 if self.check(&token::OpenDelim(token::Brace)) {
2305 // This is a struct literal, unless we're prohibited
2306 // from parsing struct literals here.
2307 let prohibited = self.restrictions.contains(
2308 Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2311 return self.parse_struct_expr(lo, pth, attrs);
2316 ex = ExprKind::Path(None, pth);
2318 match self.parse_lit() {
2321 ex = ExprKind::Lit(P(lit));
2324 self.cancel(&mut err);
2325 let msg = format!("expected expression, found {}",
2326 self.this_token_descr());
2327 return Err(self.fatal(&msg));
2334 return Ok(self.mk_expr(lo, hi, ex, attrs));
2337 fn parse_struct_expr(&mut self, lo: BytePos, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2338 -> PResult<'a, P<Expr>> {
2340 let mut fields = Vec::new();
2341 let mut base = None;
2343 attrs.extend(self.parse_inner_attributes()?);
2345 while self.token != token::CloseDelim(token::Brace) {
2346 if self.eat(&token::DotDot) {
2347 match self.parse_expr() {
2353 self.recover_stmt();
2359 match self.parse_field() {
2360 Ok(f) => fields.push(f),
2363 self.recover_stmt();
2368 match self.expect_one_of(&[token::Comma],
2369 &[token::CloseDelim(token::Brace)]) {
2373 self.recover_stmt();
2379 let hi = self.span.hi;
2380 self.expect(&token::CloseDelim(token::Brace))?;
2381 return Ok(self.mk_expr(lo, hi, ExprKind::Struct(pth, fields, base), attrs));
2384 fn parse_or_use_outer_attributes(&mut self,
2385 already_parsed_attrs: Option<ThinVec<Attribute>>)
2386 -> PResult<'a, ThinVec<Attribute>> {
2387 if let Some(attrs) = already_parsed_attrs {
2390 self.parse_outer_attributes().map(|a| a.into())
2394 /// Parse a block or unsafe block
2395 pub fn parse_block_expr(&mut self, lo: BytePos, blk_mode: BlockCheckMode,
2396 outer_attrs: ThinVec<Attribute>)
2397 -> PResult<'a, P<Expr>> {
2399 self.expect(&token::OpenDelim(token::Brace))?;
2401 let mut attrs = outer_attrs;
2402 attrs.extend(self.parse_inner_attributes()?);
2404 let blk = self.parse_block_tail(lo, blk_mode)?;
2405 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprKind::Block(blk), attrs));
2408 /// parse a.b or a(13) or a[4] or just a
2409 pub fn parse_dot_or_call_expr(&mut self,
2410 already_parsed_attrs: Option<ThinVec<Attribute>>)
2411 -> PResult<'a, P<Expr>> {
2412 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2414 let b = self.parse_bottom_expr();
2415 let (span, b) = self.interpolated_or_expr_span(b)?;
2416 self.parse_dot_or_call_expr_with(b, span.lo, attrs)
2419 pub fn parse_dot_or_call_expr_with(&mut self,
2422 mut attrs: ThinVec<Attribute>)
2423 -> PResult<'a, P<Expr>> {
2424 // Stitch the list of outer attributes onto the return value.
2425 // A little bit ugly, but the best way given the current code
2427 self.parse_dot_or_call_expr_with_(e0, lo)
2429 expr.map(|mut expr| {
2430 attrs.extend::<Vec<_>>(expr.attrs.into());
2433 ExprKind::If(..) | ExprKind::IfLet(..) => {
2434 if !expr.attrs.is_empty() {
2435 // Just point to the first attribute in there...
2436 let span = expr.attrs[0].span;
2439 "attributes are not yet allowed on `if` \
2450 // Assuming we have just parsed `.foo` (i.e., a dot and an ident), continue
2451 // parsing into an expression.
2452 fn parse_dot_suffix(&mut self,
2455 self_value: P<Expr>,
2457 -> PResult<'a, P<Expr>> {
2458 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2460 let args = self.parse_generic_args()?;
2464 (Vec::new(), Vec::new(), Vec::new())
2467 if !bindings.is_empty() {
2468 let prev_span = self.prev_span;
2469 self.span_err(prev_span, "type bindings are only permitted on trait paths");
2472 Ok(match self.token {
2473 // expr.f() method call.
2474 token::OpenDelim(token::Paren) => {
2475 let mut es = self.parse_unspanned_seq(
2476 &token::OpenDelim(token::Paren),
2477 &token::CloseDelim(token::Paren),
2478 SeqSep::trailing_allowed(token::Comma),
2479 |p| Ok(p.parse_expr()?)
2481 let hi = self.prev_span.hi;
2483 es.insert(0, self_value);
2484 let id = spanned(ident_span.lo, ident_span.hi, ident);
2485 let nd = self.mk_method_call(id, tys, es);
2486 self.mk_expr(lo, hi, nd, ThinVec::new())
2490 if !tys.is_empty() {
2491 let prev_span = self.prev_span;
2492 self.span_err(prev_span,
2493 "field expressions may not \
2494 have type parameters");
2497 let id = spanned(ident_span.lo, ident_span.hi, ident);
2498 let field = self.mk_field(self_value, id);
2499 self.mk_expr(lo, ident_span.hi, field, ThinVec::new())
2504 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: BytePos) -> PResult<'a, P<Expr>> {
2509 while self.eat(&token::Question) {
2510 let hi = self.prev_span.hi;
2511 e = self.mk_expr(lo, hi, ExprKind::Try(e), ThinVec::new());
2515 if self.eat(&token::Dot) {
2517 token::Ident(i) => {
2518 let dot_pos = self.prev_span.hi;
2522 e = self.parse_dot_suffix(i, mk_sp(dot_pos, hi), e, lo)?;
2524 token::Literal(token::Integer(n), suf) => {
2527 // A tuple index may not have a suffix
2528 self.expect_no_suffix(sp, "tuple index", suf);
2530 let dot = self.prev_span.hi;
2534 let index = n.as_str().parse::<usize>().ok();
2537 let id = spanned(dot, hi, n);
2538 let field = self.mk_tup_field(e, id);
2539 e = self.mk_expr(lo, hi, field, ThinVec::new());
2542 let prev_span = self.prev_span;
2543 self.span_err(prev_span, "invalid tuple or tuple struct index");
2547 token::Literal(token::Float(n), _suf) => {
2549 let prev_span = self.prev_span;
2550 let fstr = n.as_str();
2551 let mut err = self.diagnostic().struct_span_err(prev_span,
2552 &format!("unexpected token: `{}`", n));
2553 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2554 let float = match fstr.parse::<f64>().ok() {
2558 let sugg = pprust::to_string(|s| {
2559 use print::pprust::PrintState;
2560 use print::pp::word;
2563 word(&mut s.s, ".")?;
2564 s.print_usize(float.trunc() as usize)?;
2566 word(&mut s.s, ".")?;
2567 word(&mut s.s, fstr.splitn(2, ".").last().unwrap())
2569 err.span_suggestion(
2571 "try parenthesizing the first index",
2578 // FIXME Could factor this out into non_fatal_unexpected or something.
2579 let actual = self.this_token_to_string();
2580 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2582 let dot_pos = self.prev_span.hi;
2583 e = self.parse_dot_suffix(keywords::Invalid.ident(),
2584 mk_sp(dot_pos, dot_pos),
2590 if self.expr_is_complete(&e) { break; }
2593 token::OpenDelim(token::Paren) => {
2594 let es = self.parse_unspanned_seq(
2595 &token::OpenDelim(token::Paren),
2596 &token::CloseDelim(token::Paren),
2597 SeqSep::trailing_allowed(token::Comma),
2598 |p| Ok(p.parse_expr()?)
2600 hi = self.prev_span.hi;
2602 let nd = self.mk_call(e, es);
2603 e = self.mk_expr(lo, hi, nd, ThinVec::new());
2607 // Could be either an index expression or a slicing expression.
2608 token::OpenDelim(token::Bracket) => {
2610 let ix = self.parse_expr()?;
2612 self.expect(&token::CloseDelim(token::Bracket))?;
2613 let index = self.mk_index(e, ix);
2614 e = self.mk_expr(lo, hi, index, ThinVec::new())
2622 pub fn check_unknown_macro_variable(&mut self) {
2623 if let token::SubstNt(name) = self.token {
2624 self.fatal(&format!("unknown macro variable `{}`", name)).emit()
2628 /// parse a single token tree from the input.
2629 pub fn parse_token_tree(&mut self) -> TokenTree {
2631 token::OpenDelim(..) => {
2632 let frame = mem::replace(&mut self.token_cursor.frame,
2633 self.token_cursor.stack.pop().unwrap());
2634 self.span = frame.span;
2636 TokenTree::Delimited(frame.span, Delimited {
2638 tts: frame.tree_cursor.original_stream().into(),
2641 token::CloseDelim(_) | token::Eof => unreachable!(),
2643 let token = mem::replace(&mut self.token, token::Underscore);
2645 TokenTree::Token(self.prev_span, token)
2650 // parse a stream of tokens into a list of TokenTree's,
2652 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2653 let mut tts = Vec::new();
2654 while self.token != token::Eof {
2655 tts.push(self.parse_token_tree());
2660 pub fn parse_tokens(&mut self) -> TokenStream {
2661 let mut result = Vec::new();
2664 token::Eof | token::CloseDelim(..) => break,
2665 _ => result.push(self.parse_token_tree().into()),
2668 TokenStream::concat(result)
2671 /// Parse a prefix-unary-operator expr
2672 pub fn parse_prefix_expr(&mut self,
2673 already_parsed_attrs: Option<ThinVec<Attribute>>)
2674 -> PResult<'a, P<Expr>> {
2675 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2676 let lo = self.span.lo;
2678 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2679 let ex = match self.token {
2682 let e = self.parse_prefix_expr(None);
2683 let (span, e) = self.interpolated_or_expr_span(e)?;
2685 self.mk_unary(UnOp::Not, e)
2687 token::BinOp(token::Minus) => {
2689 let e = self.parse_prefix_expr(None);
2690 let (span, e) = self.interpolated_or_expr_span(e)?;
2692 self.mk_unary(UnOp::Neg, e)
2694 token::BinOp(token::Star) => {
2696 let e = self.parse_prefix_expr(None);
2697 let (span, e) = self.interpolated_or_expr_span(e)?;
2699 self.mk_unary(UnOp::Deref, e)
2701 token::BinOp(token::And) | token::AndAnd => {
2703 let m = self.parse_mutability()?;
2704 let e = self.parse_prefix_expr(None);
2705 let (span, e) = self.interpolated_or_expr_span(e)?;
2707 ExprKind::AddrOf(m, e)
2709 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2711 let place = self.parse_expr_res(
2712 Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
2715 let blk = self.parse_block()?;
2716 let span = blk.span;
2718 let blk_expr = self.mk_expr(span.lo, hi, ExprKind::Block(blk), ThinVec::new());
2719 ExprKind::InPlace(place, blk_expr)
2721 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2723 let e = self.parse_prefix_expr(None);
2724 let (span, e) = self.interpolated_or_expr_span(e)?;
2728 _ => return self.parse_dot_or_call_expr(Some(attrs))
2730 return Ok(self.mk_expr(lo, hi, ex, attrs));
2733 /// Parse an associative expression
2735 /// This parses an expression accounting for associativity and precedence of the operators in
2737 pub fn parse_assoc_expr(&mut self,
2738 already_parsed_attrs: Option<ThinVec<Attribute>>)
2739 -> PResult<'a, P<Expr>> {
2740 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2743 /// Parse an associative expression with operators of at least `min_prec` precedence
2744 pub fn parse_assoc_expr_with(&mut self,
2747 -> PResult<'a, P<Expr>> {
2748 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2751 let attrs = match lhs {
2752 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2755 if self.token == token::DotDot || self.token == token::DotDotDot {
2756 return self.parse_prefix_range_expr(attrs);
2758 self.parse_prefix_expr(attrs)?
2762 if self.expr_is_complete(&lhs) {
2763 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2766 self.expected_tokens.push(TokenType::Operator);
2767 while let Some(op) = AssocOp::from_token(&self.token) {
2769 let lhs_span = if self.prev_token_kind == PrevTokenKind::Interpolated {
2775 let cur_op_span = self.span;
2776 let restrictions = if op.is_assign_like() {
2777 self.restrictions & Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2781 if op.precedence() < min_prec {
2785 if op.is_comparison() {
2786 self.check_no_chained_comparison(&lhs, &op);
2789 if op == AssocOp::As {
2790 let rhs = self.parse_ty_no_plus()?;
2791 let (lo, hi) = (lhs_span.lo, rhs.span.hi);
2792 lhs = self.mk_expr(lo, hi, ExprKind::Cast(lhs, rhs), ThinVec::new());
2794 } else if op == AssocOp::Colon {
2795 let rhs = self.parse_ty_no_plus()?;
2796 let (lo, hi) = (lhs_span.lo, rhs.span.hi);
2797 lhs = self.mk_expr(lo, hi, ExprKind::Type(lhs, rhs), ThinVec::new());
2799 } else if op == AssocOp::DotDot || op == AssocOp::DotDotDot {
2800 // If we didn’t have to handle `x..`/`x...`, it would be pretty easy to
2801 // generalise it to the Fixity::None code.
2803 // We have 2 alternatives here: `x..y`/`x...y` and `x..`/`x...` The other
2804 // two variants are handled with `parse_prefix_range_expr` call above.
2805 let rhs = if self.is_at_start_of_range_notation_rhs() {
2806 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2807 LhsExpr::NotYetParsed)?)
2811 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2816 let limits = if op == AssocOp::DotDot {
2817 RangeLimits::HalfOpen
2822 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2823 lhs = self.mk_expr(lhs_span.lo, rhs_span.hi, r, ThinVec::new());
2827 let rhs = match op.fixity() {
2828 Fixity::Right => self.with_res(
2829 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2831 this.parse_assoc_expr_with(op.precedence(),
2832 LhsExpr::NotYetParsed)
2834 Fixity::Left => self.with_res(
2835 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2837 this.parse_assoc_expr_with(op.precedence() + 1,
2838 LhsExpr::NotYetParsed)
2840 // We currently have no non-associative operators that are not handled above by
2841 // the special cases. The code is here only for future convenience.
2842 Fixity::None => self.with_res(
2843 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2845 this.parse_assoc_expr_with(op.precedence() + 1,
2846 LhsExpr::NotYetParsed)
2850 let (lo, hi) = (lhs_span.lo, rhs.span.hi);
2852 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2853 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2854 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2855 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2856 AssocOp::Greater | AssocOp::GreaterEqual => {
2857 let ast_op = op.to_ast_binop().unwrap();
2858 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2859 self.mk_expr(lo, hi, binary, ThinVec::new())
2862 self.mk_expr(lo, hi, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2864 self.mk_expr(lo, hi, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
2865 AssocOp::AssignOp(k) => {
2867 token::Plus => BinOpKind::Add,
2868 token::Minus => BinOpKind::Sub,
2869 token::Star => BinOpKind::Mul,
2870 token::Slash => BinOpKind::Div,
2871 token::Percent => BinOpKind::Rem,
2872 token::Caret => BinOpKind::BitXor,
2873 token::And => BinOpKind::BitAnd,
2874 token::Or => BinOpKind::BitOr,
2875 token::Shl => BinOpKind::Shl,
2876 token::Shr => BinOpKind::Shr,
2878 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2879 self.mk_expr(lo, hi, aopexpr, ThinVec::new())
2881 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotDot => {
2882 self.bug("As, Colon, DotDot or DotDotDot branch reached")
2886 if op.fixity() == Fixity::None { break }
2891 /// Produce an error if comparison operators are chained (RFC #558).
2892 /// We only need to check lhs, not rhs, because all comparison ops
2893 /// have same precedence and are left-associative
2894 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2895 debug_assert!(outer_op.is_comparison());
2897 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
2898 // respan to include both operators
2899 let op_span = mk_sp(op.span.lo, self.span.hi);
2900 let mut err = self.diagnostic().struct_span_err(op_span,
2901 "chained comparison operators require parentheses");
2902 if op.node == BinOpKind::Lt &&
2903 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
2904 *outer_op == AssocOp::Greater // even in a case like the following:
2905 { // Foo<Bar<Baz<Qux, ()>>>
2907 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2915 /// Parse prefix-forms of range notation: `..expr`, `..`, `...expr`
2916 fn parse_prefix_range_expr(&mut self,
2917 already_parsed_attrs: Option<ThinVec<Attribute>>)
2918 -> PResult<'a, P<Expr>> {
2919 debug_assert!(self.token == token::DotDot || self.token == token::DotDotDot);
2920 let tok = self.token.clone();
2921 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2922 let lo = self.span.lo;
2923 let mut hi = self.span.hi;
2925 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2926 // RHS must be parsed with more associativity than the dots.
2927 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
2928 Some(self.parse_assoc_expr_with(next_prec,
2929 LhsExpr::NotYetParsed)
2937 let limits = if tok == token::DotDot {
2938 RangeLimits::HalfOpen
2943 let r = try!(self.mk_range(None,
2946 Ok(self.mk_expr(lo, hi, r, attrs))
2949 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2950 if self.token.can_begin_expr() {
2951 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2952 if self.token == token::OpenDelim(token::Brace) {
2953 return !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL);
2961 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2962 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
2963 if self.check_keyword(keywords::Let) {
2964 return self.parse_if_let_expr(attrs);
2966 let lo = self.prev_span.lo;
2967 let cond = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
2968 let thn = self.parse_block()?;
2969 let mut els: Option<P<Expr>> = None;
2970 let mut hi = thn.span.hi;
2971 if self.eat_keyword(keywords::Else) {
2972 let elexpr = self.parse_else_expr()?;
2973 hi = elexpr.span.hi;
2976 Ok(self.mk_expr(lo, hi, ExprKind::If(cond, thn, els), attrs))
2979 /// Parse an 'if let' expression ('if' token already eaten)
2980 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
2981 -> PResult<'a, P<Expr>> {
2982 let lo = self.prev_span.lo;
2983 self.expect_keyword(keywords::Let)?;
2984 let pat = self.parse_pat()?;
2985 self.expect(&token::Eq)?;
2986 let expr = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
2987 let thn = self.parse_block()?;
2988 let (hi, els) = if self.eat_keyword(keywords::Else) {
2989 let expr = self.parse_else_expr()?;
2990 (expr.span.hi, Some(expr))
2994 Ok(self.mk_expr(lo, hi, ExprKind::IfLet(pat, expr, thn, els), attrs))
2997 // `move |args| expr`
2998 pub fn parse_lambda_expr(&mut self,
3000 capture_clause: CaptureBy,
3001 attrs: ThinVec<Attribute>)
3002 -> PResult<'a, P<Expr>>
3004 let decl = self.parse_fn_block_decl()?;
3005 let decl_hi = self.prev_span.hi;
3006 let body = match decl.output {
3007 FunctionRetTy::Default(_) => self.parse_expr()?,
3009 // If an explicit return type is given, require a
3010 // block to appear (RFC 968).
3011 let body_lo = self.span.lo;
3012 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3019 ExprKind::Closure(capture_clause, decl, body, mk_sp(lo, decl_hi)),
3023 // `else` token already eaten
3024 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3025 if self.eat_keyword(keywords::If) {
3026 return self.parse_if_expr(ThinVec::new());
3028 let blk = self.parse_block()?;
3029 return Ok(self.mk_expr(blk.span.lo, blk.span.hi, ExprKind::Block(blk), ThinVec::new()));
3033 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3034 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3036 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3037 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3039 let pat = self.parse_pat()?;
3040 self.expect_keyword(keywords::In)?;
3041 let expr = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
3042 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3043 attrs.extend(iattrs);
3045 let hi = self.prev_span.hi;
3047 Ok(self.mk_expr(span_lo, hi,
3048 ExprKind::ForLoop(pat, expr, loop_block, opt_ident),
3052 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3053 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3055 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3056 if self.token.is_keyword(keywords::Let) {
3057 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3059 let cond = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
3060 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3061 attrs.extend(iattrs);
3062 let hi = body.span.hi;
3063 return Ok(self.mk_expr(span_lo, hi, ExprKind::While(cond, body, opt_ident),
3067 /// Parse a 'while let' expression ('while' token already eaten)
3068 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3070 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3071 self.expect_keyword(keywords::Let)?;
3072 let pat = self.parse_pat()?;
3073 self.expect(&token::Eq)?;
3074 let expr = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
3075 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3076 attrs.extend(iattrs);
3077 let hi = body.span.hi;
3078 return Ok(self.mk_expr(span_lo, hi, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3081 // parse `loop {...}`, `loop` token already eaten
3082 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3084 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3085 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3086 attrs.extend(iattrs);
3087 let hi = body.span.hi;
3088 Ok(self.mk_expr(span_lo, hi, ExprKind::Loop(body, opt_ident), attrs))
3091 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3092 pub fn parse_catch_expr(&mut self, span_lo: BytePos, mut attrs: ThinVec<Attribute>)
3093 -> PResult<'a, P<Expr>>
3095 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3096 attrs.extend(iattrs);
3097 let hi = body.span.hi;
3098 Ok(self.mk_expr(span_lo, hi, ExprKind::Catch(body), attrs))
3101 // `match` token already eaten
3102 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3103 let match_span = self.prev_span;
3104 let lo = self.prev_span.lo;
3105 let discriminant = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
3107 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3108 if self.token == token::Token::Semi {
3109 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3113 attrs.extend(self.parse_inner_attributes()?);
3115 let mut arms: Vec<Arm> = Vec::new();
3116 while self.token != token::CloseDelim(token::Brace) {
3117 match self.parse_arm() {
3118 Ok(arm) => arms.push(arm),
3120 // Recover by skipping to the end of the block.
3122 self.recover_stmt();
3123 let hi = self.span.hi;
3124 if self.token == token::CloseDelim(token::Brace) {
3127 return Ok(self.mk_expr(lo, hi, ExprKind::Match(discriminant, arms), attrs));
3131 let hi = self.span.hi;
3133 return Ok(self.mk_expr(lo, hi, ExprKind::Match(discriminant, arms), attrs));
3136 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3137 maybe_whole!(self, NtArm, |x| x);
3139 let attrs = self.parse_outer_attributes()?;
3140 let pats = self.parse_pats()?;
3141 let mut guard = None;
3142 if self.eat_keyword(keywords::If) {
3143 guard = Some(self.parse_expr()?);
3145 self.expect(&token::FatArrow)?;
3146 let expr = self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR, None)?;
3149 !classify::expr_is_simple_block(&expr)
3150 && self.token != token::CloseDelim(token::Brace);
3153 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3155 self.eat(&token::Comma);
3166 /// Parse an expression
3167 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3168 self.parse_expr_res(Restrictions::empty(), None)
3171 /// Evaluate the closure with restrictions in place.
3173 /// After the closure is evaluated, restrictions are reset.
3174 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3175 where F: FnOnce(&mut Self) -> T
3177 let old = self.restrictions;
3178 self.restrictions = r;
3180 self.restrictions = old;
3185 /// Parse an expression, subject to the given restrictions
3186 pub fn parse_expr_res(&mut self, r: Restrictions,
3187 already_parsed_attrs: Option<ThinVec<Attribute>>)
3188 -> PResult<'a, P<Expr>> {
3189 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3192 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3193 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3194 if self.check(&token::Eq) {
3196 Ok(Some(self.parse_expr()?))
3202 /// Parse patterns, separated by '|' s
3203 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3204 let mut pats = Vec::new();
3206 pats.push(self.parse_pat()?);
3207 if self.check(&token::BinOp(token::Or)) { self.bump();}
3208 else { return Ok(pats); }
3212 fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3213 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3214 let mut fields = vec![];
3215 let mut ddpos = None;
3217 while !self.check(&token::CloseDelim(token::Paren)) {
3218 if ddpos.is_none() && self.eat(&token::DotDot) {
3219 ddpos = Some(fields.len());
3220 if self.eat(&token::Comma) {
3221 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3222 fields.push(self.parse_pat()?);
3224 } else if ddpos.is_some() && self.eat(&token::DotDot) {
3225 // Emit a friendly error, ignore `..` and continue parsing
3226 self.span_err(self.prev_span, "`..` can only be used once per \
3227 tuple or tuple struct pattern");
3229 fields.push(self.parse_pat()?);
3232 if !self.check(&token::CloseDelim(token::Paren)) ||
3233 (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3234 self.expect(&token::Comma)?;
3241 fn parse_pat_vec_elements(
3243 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3244 let mut before = Vec::new();
3245 let mut slice = None;
3246 let mut after = Vec::new();
3247 let mut first = true;
3248 let mut before_slice = true;
3250 while self.token != token::CloseDelim(token::Bracket) {
3254 self.expect(&token::Comma)?;
3256 if self.token == token::CloseDelim(token::Bracket)
3257 && (before_slice || !after.is_empty()) {
3263 if self.eat(&token::DotDot) {
3265 if self.check(&token::Comma) ||
3266 self.check(&token::CloseDelim(token::Bracket)) {
3267 slice = Some(P(ast::Pat {
3268 id: ast::DUMMY_NODE_ID,
3269 node: PatKind::Wild,
3272 before_slice = false;
3278 let subpat = self.parse_pat()?;
3279 if before_slice && self.eat(&token::DotDot) {
3280 slice = Some(subpat);
3281 before_slice = false;
3282 } else if before_slice {
3283 before.push(subpat);
3289 Ok((before, slice, after))
3292 /// Parse the fields of a struct-like pattern
3293 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3294 let mut fields = Vec::new();
3295 let mut etc = false;
3296 let mut first = true;
3297 while self.token != token::CloseDelim(token::Brace) {
3301 self.expect(&token::Comma)?;
3302 // accept trailing commas
3303 if self.check(&token::CloseDelim(token::Brace)) { break }
3306 let attrs = self.parse_outer_attributes()?;
3307 let lo = self.span.lo;
3310 if self.check(&token::DotDot) {
3312 if self.token != token::CloseDelim(token::Brace) {
3313 let token_str = self.this_token_to_string();
3314 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3321 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3322 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3323 // Parsing a pattern of the form "fieldname: pat"
3324 let fieldname = self.parse_field_name()?;
3326 let pat = self.parse_pat()?;
3328 (pat, fieldname, false)
3330 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3331 let is_box = self.eat_keyword(keywords::Box);
3332 let boxed_span_lo = self.span.lo;
3333 let is_ref = self.eat_keyword(keywords::Ref);
3334 let is_mut = self.eat_keyword(keywords::Mut);
3335 let fieldname = self.parse_ident()?;
3336 hi = self.prev_span.hi;
3338 let bind_type = match (is_ref, is_mut) {
3339 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3340 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3341 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3342 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3344 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3345 let fieldpat = P(ast::Pat{
3346 id: ast::DUMMY_NODE_ID,
3347 node: PatKind::Ident(bind_type, fieldpath, None),
3348 span: mk_sp(boxed_span_lo, hi),
3351 let subpat = if is_box {
3353 id: ast::DUMMY_NODE_ID,
3354 node: PatKind::Box(fieldpat),
3355 span: mk_sp(lo, hi),
3360 (subpat, fieldname, true)
3363 fields.push(codemap::Spanned { span: mk_sp(lo, hi),
3364 node: ast::FieldPat {
3367 is_shorthand: is_shorthand,
3368 attrs: attrs.into(),
3372 return Ok((fields, etc));
3375 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3376 if self.token.is_path_start() {
3377 let lo = self.span.lo;
3378 let (qself, path) = if self.eat_lt() {
3379 // Parse a qualified path
3381 self.parse_qualified_path(PathStyle::Expr)?;
3384 // Parse an unqualified path
3385 (None, self.parse_path(PathStyle::Expr)?)
3387 let hi = self.prev_span.hi;
3388 Ok(self.mk_expr(lo, hi, ExprKind::Path(qself, path), ThinVec::new()))
3390 self.parse_pat_literal_maybe_minus()
3394 // helper function to decide whether to parse as ident binding or to try to do
3395 // something more complex like range patterns
3396 fn parse_as_ident(&mut self) -> bool {
3397 self.look_ahead(1, |t| match *t {
3398 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3399 token::DotDotDot | token::ModSep | token::Not => Some(false),
3400 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3401 // range pattern branch
3402 token::DotDot => None,
3404 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3405 token::Comma | token::CloseDelim(token::Bracket) => true,
3410 /// Parse a pattern.
3411 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3412 maybe_whole!(self, NtPat, |x| x);
3414 let lo = self.span.lo;
3417 token::Underscore => {
3420 pat = PatKind::Wild;
3422 token::BinOp(token::And) | token::AndAnd => {
3423 // Parse &pat / &mut pat
3425 let mutbl = self.parse_mutability()?;
3426 if let token::Lifetime(ident) = self.token {
3427 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3429 let subpat = self.parse_pat()?;
3430 pat = PatKind::Ref(subpat, mutbl);
3432 token::OpenDelim(token::Paren) => {
3433 // Parse (pat,pat,pat,...) as tuple pattern
3435 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3436 self.expect(&token::CloseDelim(token::Paren))?;
3437 pat = PatKind::Tuple(fields, ddpos);
3439 token::OpenDelim(token::Bracket) => {
3440 // Parse [pat,pat,...] as slice pattern
3442 let (before, slice, after) = self.parse_pat_vec_elements()?;
3443 self.expect(&token::CloseDelim(token::Bracket))?;
3444 pat = PatKind::Slice(before, slice, after);
3446 // At this point, token != _, &, &&, (, [
3447 _ => if self.eat_keyword(keywords::Mut) {
3448 // Parse mut ident @ pat
3449 pat = self.parse_pat_ident(BindingMode::ByValue(Mutability::Mutable))?;
3450 } else if self.eat_keyword(keywords::Ref) {
3451 // Parse ref ident @ pat / ref mut ident @ pat
3452 let mutbl = self.parse_mutability()?;
3453 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3454 } else if self.eat_keyword(keywords::Box) {
3456 let subpat = self.parse_pat()?;
3457 pat = PatKind::Box(subpat);
3458 } else if self.token.is_ident() && !self.token.is_any_keyword() &&
3459 self.parse_as_ident() {
3460 // Parse ident @ pat
3461 // This can give false positives and parse nullary enums,
3462 // they are dealt with later in resolve
3463 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3464 pat = self.parse_pat_ident(binding_mode)?;
3465 } else if self.token.is_path_start() {
3466 // Parse pattern starting with a path
3467 let (qself, path) = if self.eat_lt() {
3468 // Parse a qualified path
3469 let (qself, path) = self.parse_qualified_path(PathStyle::Expr)?;
3472 // Parse an unqualified path
3473 (None, self.parse_path(PathStyle::Expr)?)
3476 token::Not if qself.is_none() => {
3477 // Parse macro invocation
3479 let (_, tts) = self.expect_delimited_token_tree()?;
3480 let mac = spanned(lo, self.prev_span.hi, Mac_ { path: path, tts: tts });
3481 pat = PatKind::Mac(mac);
3483 token::DotDotDot | token::DotDot => {
3484 let end_kind = match self.token {
3485 token::DotDot => RangeEnd::Excluded,
3486 token::DotDotDot => RangeEnd::Included,
3487 _ => panic!("can only parse `..` or `...` for ranges (checked above)"),
3490 let hi = self.prev_span.hi;
3492 self.mk_expr(lo, hi, ExprKind::Path(qself, path), ThinVec::new());
3494 let end = self.parse_pat_range_end()?;
3495 pat = PatKind::Range(begin, end, end_kind);
3497 token::OpenDelim(token::Brace) => {
3498 if qself.is_some() {
3499 return Err(self.fatal("unexpected `{` after qualified path"));
3501 // Parse struct pattern
3503 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3505 self.recover_stmt();
3509 pat = PatKind::Struct(path, fields, etc);
3511 token::OpenDelim(token::Paren) => {
3512 if qself.is_some() {
3513 return Err(self.fatal("unexpected `(` after qualified path"));
3515 // Parse tuple struct or enum pattern
3517 let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3518 self.expect(&token::CloseDelim(token::Paren))?;
3519 pat = PatKind::TupleStruct(path, fields, ddpos)
3521 _ => pat = PatKind::Path(qself, path),
3524 // Try to parse everything else as literal with optional minus
3525 match self.parse_pat_literal_maybe_minus() {
3527 if self.eat(&token::DotDotDot) {
3528 let end = self.parse_pat_range_end()?;
3529 pat = PatKind::Range(begin, end, RangeEnd::Included);
3530 } else if self.eat(&token::DotDot) {
3531 let end = self.parse_pat_range_end()?;
3532 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3534 pat = PatKind::Lit(begin);
3538 self.cancel(&mut err);
3539 let msg = format!("expected pattern, found {}", self.this_token_descr());
3540 return Err(self.fatal(&msg));
3546 let hi = self.prev_span.hi;
3548 id: ast::DUMMY_NODE_ID,
3550 span: mk_sp(lo, hi),
3554 /// Parse ident or ident @ pat
3555 /// used by the copy foo and ref foo patterns to give a good
3556 /// error message when parsing mistakes like ref foo(a,b)
3557 fn parse_pat_ident(&mut self,
3558 binding_mode: ast::BindingMode)
3559 -> PResult<'a, PatKind> {
3560 let ident = self.parse_ident()?;
3561 let prev_span = self.prev_span;
3562 let name = codemap::Spanned{span: prev_span, node: ident};
3563 let sub = if self.eat(&token::At) {
3564 Some(self.parse_pat()?)
3569 // just to be friendly, if they write something like
3571 // we end up here with ( as the current token. This shortly
3572 // leads to a parse error. Note that if there is no explicit
3573 // binding mode then we do not end up here, because the lookahead
3574 // will direct us over to parse_enum_variant()
3575 if self.token == token::OpenDelim(token::Paren) {
3576 return Err(self.span_fatal(
3578 "expected identifier, found enum pattern"))
3581 Ok(PatKind::Ident(binding_mode, name, sub))
3584 /// Parse a local variable declaration
3585 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3586 let lo = self.span.lo;
3587 let pat = self.parse_pat()?;
3590 if self.eat(&token::Colon) {
3591 ty = Some(self.parse_ty()?);
3593 let init = self.parse_initializer()?;
3598 id: ast::DUMMY_NODE_ID,
3599 span: mk_sp(lo, self.prev_span.hi),
3604 /// Parse a structure field
3605 fn parse_name_and_ty(&mut self,
3608 attrs: Vec<Attribute>)
3609 -> PResult<'a, StructField> {
3610 let name = self.parse_ident()?;
3611 self.expect(&token::Colon)?;
3612 let ty = self.parse_ty()?;
3614 span: mk_sp(lo, self.prev_span.hi),
3617 id: ast::DUMMY_NODE_ID,
3623 /// Emit an expected item after attributes error.
3624 fn expected_item_err(&self, attrs: &[Attribute]) {
3625 let message = match attrs.last() {
3626 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
3627 _ => "expected item after attributes",
3630 self.span_err(self.prev_span, message);
3633 /// Parse a statement. This stops just before trailing semicolons on everything but items.
3634 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3635 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3636 Ok(self.parse_stmt_(true))
3639 // Eat tokens until we can be relatively sure we reached the end of the
3640 // statement. This is something of a best-effort heuristic.
3642 // We terminate when we find an unmatched `}` (without consuming it).
3643 fn recover_stmt(&mut self) {
3644 self.recover_stmt_(SemiColonMode::Ignore)
3646 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
3647 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
3648 // approximate - it can mean we break too early due to macros, but that
3649 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
3650 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode) {
3651 let mut brace_depth = 0;
3652 let mut bracket_depth = 0;
3653 debug!("recover_stmt_ enter loop");
3655 debug!("recover_stmt_ loop {:?}", self.token);
3657 token::OpenDelim(token::DelimToken::Brace) => {
3661 token::OpenDelim(token::DelimToken::Bracket) => {
3665 token::CloseDelim(token::DelimToken::Brace) => {
3666 if brace_depth == 0 {
3667 debug!("recover_stmt_ return - close delim {:?}", self.token);
3673 token::CloseDelim(token::DelimToken::Bracket) => {
3675 if bracket_depth < 0 {
3681 debug!("recover_stmt_ return - Eof");
3686 if break_on_semi == SemiColonMode::Break &&
3688 bracket_depth == 0 {
3689 debug!("recover_stmt_ return - Semi");
3700 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
3701 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
3703 self.recover_stmt_(SemiColonMode::Break);
3708 fn is_catch_expr(&mut self) -> bool {
3709 self.token.is_keyword(keywords::Do) &&
3710 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
3711 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
3713 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
3714 !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL)
3717 fn is_union_item(&self) -> bool {
3718 self.token.is_keyword(keywords::Union) &&
3719 self.look_ahead(1, |t| t.is_ident() && !t.is_any_keyword())
3722 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility)
3723 -> PResult<'a, Option<P<Item>>> {
3724 let lo = self.span.lo;
3726 token::Ident(ident) if ident.name == "macro_rules" => {
3727 if self.look_ahead(1, |t| *t == token::Not) {
3728 let prev_span = self.prev_span;
3729 self.complain_if_pub_macro(vis, prev_span);
3734 _ => return Ok(None),
3737 let id = self.parse_ident()?;
3738 let (delim, tts) = self.expect_delimited_token_tree()?;
3739 if delim != token::Brace {
3740 if !self.eat(&token::Semi) {
3741 let msg = "macros that expand to items must either be surrounded with braces \
3742 or followed by a semicolon";
3743 self.span_err(self.prev_span, msg);
3747 let hi = self.prev_span.hi;
3748 let kind = ItemKind::MacroDef(tts);
3749 Ok(Some(self.mk_item(lo, hi, id, kind, Visibility::Inherited, attrs.to_owned())))
3752 fn parse_stmt_without_recovery(&mut self,
3753 macro_legacy_warnings: bool)
3754 -> PResult<'a, Option<Stmt>> {
3755 maybe_whole!(self, NtStmt, |x| Some(x));
3757 let attrs = self.parse_outer_attributes()?;
3758 let lo = self.span.lo;
3760 Ok(Some(if self.eat_keyword(keywords::Let) {
3762 id: ast::DUMMY_NODE_ID,
3763 node: StmtKind::Local(self.parse_local(attrs.into())?),
3764 span: mk_sp(lo, self.prev_span.hi),
3766 } else if let Some(macro_def) = self.eat_macro_def(&attrs, &Visibility::Inherited)? {
3768 id: ast::DUMMY_NODE_ID,
3769 node: StmtKind::Item(macro_def),
3770 span: mk_sp(lo, self.prev_span.hi),
3772 // Starts like a simple path, but not a union item.
3773 } else if self.token.is_path_start() &&
3774 !self.token.is_qpath_start() &&
3775 !self.is_union_item() {
3776 let pth = self.parse_path(PathStyle::Expr)?;
3778 if !self.eat(&token::Not) {
3779 let expr = if self.check(&token::OpenDelim(token::Brace)) {
3780 self.parse_struct_expr(lo, pth, ThinVec::new())?
3782 let hi = self.prev_span.hi;
3783 self.mk_expr(lo, hi, ExprKind::Path(None, pth), ThinVec::new())
3786 let expr = self.with_res(Restrictions::RESTRICTION_STMT_EXPR, |this| {
3787 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
3788 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
3791 return Ok(Some(Stmt {
3792 id: ast::DUMMY_NODE_ID,
3793 node: StmtKind::Expr(expr),
3794 span: mk_sp(lo, self.prev_span.hi),
3798 // it's a macro invocation
3799 let id = match self.token {
3800 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
3801 _ => self.parse_ident()?,
3804 // check that we're pointing at delimiters (need to check
3805 // again after the `if`, because of `parse_ident`
3806 // consuming more tokens).
3807 let delim = match self.token {
3808 token::OpenDelim(delim) => delim,
3810 // we only expect an ident if we didn't parse one
3812 let ident_str = if id.name == keywords::Invalid.name() {
3817 let tok_str = self.this_token_to_string();
3818 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3824 let (_, tts) = self.expect_delimited_token_tree()?;
3825 let hi = self.prev_span.hi;
3827 let style = if delim == token::Brace {
3828 MacStmtStyle::Braces
3830 MacStmtStyle::NoBraces
3833 if id.name == keywords::Invalid.name() {
3834 let mac = spanned(lo, hi, Mac_ { path: pth, tts: tts });
3835 let node = if delim == token::Brace ||
3836 self.token == token::Semi || self.token == token::Eof {
3837 StmtKind::Mac(P((mac, style, attrs.into())))
3839 // We used to incorrectly stop parsing macro-expanded statements here.
3840 // If the next token will be an error anyway but could have parsed with the
3841 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
3842 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
3843 // These can continue an expression, so we can't stop parsing and warn.
3844 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
3845 token::BinOp(token::Minus) | token::BinOp(token::Star) |
3846 token::BinOp(token::And) | token::BinOp(token::Or) |
3847 token::AndAnd | token::OrOr |
3848 token::DotDot | token::DotDotDot => false,
3851 self.warn_missing_semicolon();
3852 StmtKind::Mac(P((mac, style, attrs.into())))
3854 let e = self.mk_mac_expr(lo, hi, mac.node, ThinVec::new());
3855 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
3856 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
3860 id: ast::DUMMY_NODE_ID,
3861 span: mk_sp(lo, hi),
3865 // if it has a special ident, it's definitely an item
3867 // Require a semicolon or braces.
3868 if style != MacStmtStyle::Braces {
3869 if !self.eat(&token::Semi) {
3870 self.span_err(self.prev_span,
3871 "macros that expand to items must \
3872 either be surrounded with braces or \
3873 followed by a semicolon");
3877 id: ast::DUMMY_NODE_ID,
3878 span: mk_sp(lo, hi),
3879 node: StmtKind::Item({
3881 lo, hi, id /*id is good here*/,
3882 ItemKind::Mac(spanned(lo, hi, Mac_ { path: pth, tts: tts })),
3883 Visibility::Inherited,
3889 // FIXME: Bad copy of attrs
3890 let old_directory_ownership =
3891 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
3892 let item = self.parse_item_(attrs.clone(), false, true)?;
3893 self.directory.ownership = old_directory_ownership;
3896 id: ast::DUMMY_NODE_ID,
3897 span: mk_sp(lo, i.span.hi),
3898 node: StmtKind::Item(i),
3901 let unused_attrs = |attrs: &[_], s: &mut Self| {
3902 if attrs.len() > 0 {
3903 if s.prev_token_kind == PrevTokenKind::DocComment {
3904 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
3906 s.span_err(s.span, "expected statement after outer attribute");
3911 // Do not attempt to parse an expression if we're done here.
3912 if self.token == token::Semi {
3913 unused_attrs(&attrs, self);
3918 if self.token == token::CloseDelim(token::Brace) {
3919 unused_attrs(&attrs, self);
3923 // Remainder are line-expr stmts.
3924 let e = self.parse_expr_res(
3925 Restrictions::RESTRICTION_STMT_EXPR, Some(attrs.into()))?;
3927 id: ast::DUMMY_NODE_ID,
3928 span: mk_sp(lo, e.span.hi),
3929 node: StmtKind::Expr(e),
3936 /// Is this expression a successfully-parsed statement?
3937 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3938 self.restrictions.contains(Restrictions::RESTRICTION_STMT_EXPR) &&
3939 !classify::expr_requires_semi_to_be_stmt(e)
3942 /// Parse a block. No inner attrs are allowed.
3943 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
3944 maybe_whole!(self, NtBlock, |x| x);
3946 let lo = self.span.lo;
3948 if !self.eat(&token::OpenDelim(token::Brace)) {
3950 let tok = self.this_token_to_string();
3951 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
3953 // Check to see if the user has written something like
3958 // Which is valid in other languages, but not Rust.
3959 match self.parse_stmt_without_recovery(false) {
3961 let mut stmt_span = stmt.span;
3962 // expand the span to include the semicolon, if it exists
3963 if self.eat(&token::Semi) {
3964 stmt_span.hi = self.prev_span.hi;
3966 let sugg = pprust::to_string(|s| {
3967 use print::pprust::{PrintState, INDENT_UNIT};
3968 s.ibox(INDENT_UNIT)?;
3970 s.print_stmt(&stmt)?;
3971 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
3973 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
3976 self.recover_stmt_(SemiColonMode::Break);
3977 self.cancel(&mut e);
3984 self.parse_block_tail(lo, BlockCheckMode::Default)
3987 /// Parse a block. Inner attrs are allowed.
3988 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
3989 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
3991 let lo = self.span.lo;
3992 self.expect(&token::OpenDelim(token::Brace))?;
3993 Ok((self.parse_inner_attributes()?,
3994 self.parse_block_tail(lo, BlockCheckMode::Default)?))
3997 /// Parse the rest of a block expression or function body
3998 /// Precondition: already parsed the '{'.
3999 fn parse_block_tail(&mut self, lo: BytePos, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4000 let mut stmts = vec![];
4002 while !self.eat(&token::CloseDelim(token::Brace)) {
4003 if let Some(stmt) = self.parse_full_stmt(false)? {
4005 } else if self.token == token::Eof {
4008 // Found only `;` or `}`.
4015 id: ast::DUMMY_NODE_ID,
4017 span: mk_sp(lo, self.prev_span.hi),
4021 /// Parse a statement, including the trailing semicolon.
4022 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4023 let mut stmt = match self.parse_stmt_(macro_legacy_warnings) {
4025 None => return Ok(None),
4029 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4030 // expression without semicolon
4031 if classify::expr_requires_semi_to_be_stmt(expr) {
4032 // Just check for errors and recover; do not eat semicolon yet.
4034 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4037 self.recover_stmt();
4041 StmtKind::Local(..) => {
4042 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4043 if macro_legacy_warnings && self.token != token::Semi {
4044 self.warn_missing_semicolon();
4046 self.expect_one_of(&[token::Semi], &[])?;
4052 if self.eat(&token::Semi) {
4053 stmt = stmt.add_trailing_semicolon();
4056 stmt.span.hi = self.prev_span.hi;
4060 fn warn_missing_semicolon(&self) {
4061 self.diagnostic().struct_span_warn(self.span, {
4062 &format!("expected `;`, found `{}`", self.this_token_to_string())
4064 "This was erroneously allowed and will become a hard error in a future release"
4068 // Parse bounds of a type parameter `BOUND + BOUND + BOUND` without trailing `+`.
4069 // BOUND = TY_BOUND | LT_BOUND
4070 // LT_BOUND = LIFETIME (e.g. `'a`)
4071 // TY_BOUND = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4072 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds>
4074 let mut bounds = Vec::new();
4076 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4077 if let Some(lifetime) = self.eat_lifetime() {
4078 if let Some(question_span) = question {
4079 self.span_err(question_span,
4080 "`?` may only modify trait bounds, not lifetime bounds");
4082 bounds.push(RegionTyParamBound(lifetime));
4083 } else {if self.check_keyword(keywords::For) || self.check_path() {
4084 let poly_trait_ref = self.parse_poly_trait_ref()?;
4085 let modifier = if question.is_some() {
4086 TraitBoundModifier::Maybe
4088 TraitBoundModifier::None
4090 bounds.push(TraitTyParamBound(poly_trait_ref, modifier));
4095 if !self.eat(&token::BinOp(token::Plus)) {
4103 // Parse bounds of a type parameter `BOUND + BOUND + BOUND` without trailing `+`.
4104 // BOUND = LT_BOUND (e.g. `'a`)
4105 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4106 let mut lifetimes = Vec::new();
4107 while let Some(lifetime) = self.eat_lifetime() {
4108 lifetimes.push(lifetime);
4110 if !self.eat(&token::BinOp(token::Plus)) {
4117 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4118 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4119 let span = self.span;
4120 let ident = self.parse_ident()?;
4122 // Parse optional colon and param bounds.
4123 let bounds = if self.eat(&token::Colon) {
4124 self.parse_ty_param_bounds()?
4129 let default = if self.eat(&token::Eq) {
4130 Some(self.parse_ty()?)
4136 attrs: preceding_attrs.into(),
4138 id: ast::DUMMY_NODE_ID,
4145 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4146 /// trailing comma and erroneous trailing attributes.
4147 pub fn parse_generic_params(&mut self) -> PResult<'a, (Vec<LifetimeDef>, Vec<TyParam>)> {
4148 let mut lifetime_defs = Vec::new();
4149 let mut ty_params = Vec::new();
4150 let mut seen_ty_param = false;
4152 let attrs = self.parse_outer_attributes()?;
4153 if let Some(lifetime) = self.eat_lifetime() {
4154 // Parse lifetime parameter.
4155 let bounds = if self.eat(&token::Colon) {
4156 self.parse_lt_param_bounds()
4160 lifetime_defs.push(LifetimeDef {
4161 attrs: attrs.into(),
4166 self.span_err(self.prev_span,
4167 "lifetime parameters must be declared prior to type parameters");
4169 } else {if self.check_ident() {
4170 // Parse type parameter.
4171 ty_params.push(self.parse_ty_param(attrs)?);
4172 seen_ty_param = true;
4174 // Check for trailing attributes and stop parsing.
4175 if !attrs.is_empty() {
4176 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4177 self.span_err(attrs[0].span,
4178 &format!("trailing attribute after {} parameters", param_kind));
4183 if !self.eat(&token::Comma) {
4187 Ok((lifetime_defs, ty_params))
4190 /// Parse a set of optional generic type parameter declarations. Where
4191 /// clauses are not parsed here, and must be added later via
4192 /// `parse_where_clause()`.
4194 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4195 /// | ( < lifetimes , typaramseq ( , )? > )
4196 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4197 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4198 maybe_whole!(self, NtGenerics, |x| x);
4200 let span_lo = self.span.lo;
4202 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4205 lifetimes: lifetime_defs,
4206 ty_params: ty_params,
4207 where_clause: WhereClause {
4208 id: ast::DUMMY_NODE_ID,
4209 predicates: Vec::new(),
4211 span: mk_sp(span_lo, self.prev_span.hi),
4214 Ok(ast::Generics::default())
4218 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4219 /// possibly including trailing comma.
4220 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4221 let mut lifetimes = Vec::new();
4222 let mut types = Vec::new();
4223 let mut bindings = Vec::new();
4224 let mut seen_type = false;
4225 let mut seen_binding = false;
4227 if let Some(lifetime) = self.eat_lifetime() {
4228 // Parse lifetime argument.
4229 lifetimes.push(lifetime);
4230 if seen_type || seen_binding {
4231 self.span_err(self.prev_span,
4232 "lifetime parameters must be declared prior to type parameters");
4234 } else {if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4235 // Parse associated type binding.
4236 let lo = self.span.lo;
4237 let ident = self.parse_ident()?;
4239 let ty = self.parse_ty()?;
4240 bindings.push(TypeBinding {
4241 id: ast::DUMMY_NODE_ID,
4244 span: mk_sp(lo, self.prev_span.hi),
4246 seen_binding = true;
4247 } else if self.check_type() {
4248 // Parse type argument.
4249 types.push(self.parse_ty()?);
4251 self.span_err(types[types.len() - 1].span,
4252 "type parameters must be declared prior to associated type bindings");
4259 if !self.eat(&token::Comma) {
4263 Ok((lifetimes, types, bindings))
4266 /// Parses an optional `where` clause and places it in `generics`.
4269 /// where T : Trait<U, V> + 'b, 'a : 'b
4271 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4272 maybe_whole!(self, NtWhereClause, |x| x);
4274 let mut where_clause = WhereClause {
4275 id: ast::DUMMY_NODE_ID,
4276 predicates: Vec::new(),
4279 if !self.eat_keyword(keywords::Where) {
4280 return Ok(where_clause);
4283 // This is a temporary future proofing.
4285 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4286 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4287 // change, for now we refuse to parse `where < (ident | lifetime) (> | , | :)`.
4288 if token::Lt == self.token {
4289 let ident_or_lifetime = self.look_ahead(1, |t| t.is_ident() || t.is_lifetime());
4290 if ident_or_lifetime {
4291 let gt_comma_or_colon = self.look_ahead(2, |t| {
4292 *t == token::Gt || *t == token::Comma || *t == token::Colon
4294 if gt_comma_or_colon {
4295 self.span_err(self.span, "syntax `where<T>` is reserved for future use");
4301 let lo = self.span.lo;
4302 if let Some(lifetime) = self.eat_lifetime() {
4303 // Bounds starting with a colon are mandatory, but possibly empty.
4304 self.expect(&token::Colon)?;
4305 let bounds = self.parse_lt_param_bounds();
4306 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4307 ast::WhereRegionPredicate {
4308 span: mk_sp(lo, self.prev_span.hi),
4313 } else {if self.check_type() {
4314 // Parse optional `for<'a, 'b>`.
4315 // This `for` is parsed greedily and applies to the whole predicate,
4316 // the bounded type can have its own `for` applying only to it.
4317 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4318 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4319 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4320 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4322 // Parse type with mandatory colon and (possibly empty) bounds,
4323 // or with mandatory equality sign and the second type.
4324 let ty = self.parse_ty()?;
4325 if self.eat(&token::Colon) {
4326 let bounds = self.parse_ty_param_bounds()?;
4327 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4328 ast::WhereBoundPredicate {
4329 span: mk_sp(lo, self.prev_span.hi),
4330 bound_lifetimes: lifetime_defs,
4335 // FIXME: Decide what should be used here, `=` or `==`.
4336 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4337 let rhs_ty = self.parse_ty()?;
4338 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4339 ast::WhereEqPredicate {
4340 span: mk_sp(lo, self.prev_span.hi),
4343 id: ast::DUMMY_NODE_ID,
4347 return self.unexpected();
4353 if !self.eat(&token::Comma) {
4361 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4362 -> PResult<'a, (Vec<Arg> , bool)> {
4364 let mut variadic = false;
4365 let args: Vec<Option<Arg>> =
4366 self.parse_unspanned_seq(
4367 &token::OpenDelim(token::Paren),
4368 &token::CloseDelim(token::Paren),
4369 SeqSep::trailing_allowed(token::Comma),
4371 if p.token == token::DotDotDot {
4374 if p.token != token::CloseDelim(token::Paren) {
4377 "`...` must be last in argument list for variadic function");
4382 "only foreign functions are allowed to be variadic");
4387 match p.parse_arg_general(named_args) {
4388 Ok(arg) => Ok(Some(arg)),
4391 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4399 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4401 if variadic && args.is_empty() {
4403 "variadic function must be declared with at least one named argument");
4406 Ok((args, variadic))
4409 /// Parse the argument list and result type of a function declaration
4410 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4412 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4413 let ret_ty = self.parse_ret_ty()?;
4422 /// Returns the parsed optional self argument and whether a self shortcut was used.
4423 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4424 let expect_ident = |this: &mut Self| match this.token {
4425 // Preserve hygienic context.
4426 token::Ident(ident) => { this.bump(); codemap::respan(this.prev_span, ident) }
4429 let isolated_self = |this: &mut Self, n| {
4430 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4431 this.look_ahead(n + 1, |t| t != &token::ModSep)
4434 // Parse optional self parameter of a method.
4435 // Only a limited set of initial token sequences is considered self parameters, anything
4436 // else is parsed as a normal function parameter list, so some lookahead is required.
4437 let eself_lo = self.span.lo;
4438 let (eself, eself_ident) = match self.token {
4439 token::BinOp(token::And) => {
4445 if isolated_self(self, 1) {
4447 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4448 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4449 isolated_self(self, 2) {
4452 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4453 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4454 isolated_self(self, 2) {
4456 let lt = self.eat_lifetime().expect("not a lifetime");
4457 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4458 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4459 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4460 isolated_self(self, 3) {
4462 let lt = self.eat_lifetime().expect("not a lifetime");
4464 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4469 token::BinOp(token::Star) => {
4474 // Emit special error for `self` cases.
4475 if isolated_self(self, 1) {
4477 self.span_err(self.span, "cannot pass `self` by raw pointer");
4478 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4479 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4480 isolated_self(self, 2) {
4483 self.span_err(self.span, "cannot pass `self` by raw pointer");
4484 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4489 token::Ident(..) => {
4490 if isolated_self(self, 0) {
4493 let eself_ident = expect_ident(self);
4494 if self.eat(&token::Colon) {
4495 let ty = self.parse_ty()?;
4496 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4498 (SelfKind::Value(Mutability::Immutable), eself_ident)
4500 } else if self.token.is_keyword(keywords::Mut) &&
4501 isolated_self(self, 1) {
4505 let eself_ident = expect_ident(self);
4506 if self.eat(&token::Colon) {
4507 let ty = self.parse_ty()?;
4508 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
4510 (SelfKind::Value(Mutability::Mutable), eself_ident)
4516 _ => return Ok(None),
4519 let eself = codemap::respan(mk_sp(eself_lo, self.prev_span.hi), eself);
4520 Ok(Some(Arg::from_self(eself, eself_ident)))
4523 /// Parse the parameter list and result type of a function that may have a `self` parameter.
4524 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
4525 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4527 self.expect(&token::OpenDelim(token::Paren))?;
4529 // Parse optional self argument
4530 let self_arg = self.parse_self_arg()?;
4532 // Parse the rest of the function parameter list.
4533 let sep = SeqSep::trailing_allowed(token::Comma);
4534 let fn_inputs = if let Some(self_arg) = self_arg {
4535 if self.check(&token::CloseDelim(token::Paren)) {
4537 } else if self.eat(&token::Comma) {
4538 let mut fn_inputs = vec![self_arg];
4539 fn_inputs.append(&mut self.parse_seq_to_before_end(
4540 &token::CloseDelim(token::Paren), sep, parse_arg_fn)
4544 return self.unexpected();
4547 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4550 // Parse closing paren and return type.
4551 self.expect(&token::CloseDelim(token::Paren))?;
4554 output: self.parse_ret_ty()?,
4559 // parse the |arg, arg| header on a lambda
4560 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4561 let inputs_captures = {
4562 if self.eat(&token::OrOr) {
4565 self.expect(&token::BinOp(token::Or))?;
4566 let args = self.parse_seq_to_before_end(
4567 &token::BinOp(token::Or),
4568 SeqSep::trailing_allowed(token::Comma),
4569 |p| p.parse_fn_block_arg()
4575 let output = self.parse_ret_ty()?;
4578 inputs: inputs_captures,
4584 /// Parse the name and optional generic types of a function header.
4585 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4586 let id = self.parse_ident()?;
4587 let generics = self.parse_generics()?;
4591 fn mk_item(&mut self, lo: BytePos, hi: BytePos, ident: Ident,
4592 node: ItemKind, vis: Visibility,
4593 attrs: Vec<Attribute>) -> P<Item> {
4597 id: ast::DUMMY_NODE_ID,
4604 /// Parse an item-position function declaration.
4605 fn parse_item_fn(&mut self,
4607 constness: Spanned<Constness>,
4609 -> PResult<'a, ItemInfo> {
4610 let (ident, mut generics) = self.parse_fn_header()?;
4611 let decl = self.parse_fn_decl(false)?;
4612 generics.where_clause = self.parse_where_clause()?;
4613 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4614 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4617 /// true if we are looking at `const ID`, false for things like `const fn` etc
4618 pub fn is_const_item(&mut self) -> bool {
4619 self.token.is_keyword(keywords::Const) &&
4620 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4621 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4624 /// parses all the "front matter" for a `fn` declaration, up to
4625 /// and including the `fn` keyword:
4629 /// - `const unsafe fn`
4632 pub fn parse_fn_front_matter(&mut self)
4633 -> PResult<'a, (Spanned<ast::Constness>,
4636 let is_const_fn = self.eat_keyword(keywords::Const);
4637 let const_span = self.prev_span;
4638 let unsafety = self.parse_unsafety()?;
4639 let (constness, unsafety, abi) = if is_const_fn {
4640 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
4642 let abi = if self.eat_keyword(keywords::Extern) {
4643 self.parse_opt_abi()?.unwrap_or(Abi::C)
4647 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
4649 self.expect_keyword(keywords::Fn)?;
4650 Ok((constness, unsafety, abi))
4653 /// Parse an impl item.
4654 pub fn parse_impl_item(&mut self) -> PResult<'a, ImplItem> {
4655 maybe_whole!(self, NtImplItem, |x| x);
4657 let mut attrs = self.parse_outer_attributes()?;
4658 let lo = self.span.lo;
4659 let vis = self.parse_visibility()?;
4660 let defaultness = self.parse_defaultness()?;
4661 let (name, node) = if self.eat_keyword(keywords::Type) {
4662 let name = self.parse_ident()?;
4663 self.expect(&token::Eq)?;
4664 let typ = self.parse_ty()?;
4665 self.expect(&token::Semi)?;
4666 (name, ast::ImplItemKind::Type(typ))
4667 } else if self.is_const_item() {
4668 self.expect_keyword(keywords::Const)?;
4669 let name = self.parse_ident()?;
4670 self.expect(&token::Colon)?;
4671 let typ = self.parse_ty()?;
4672 self.expect(&token::Eq)?;
4673 let expr = self.parse_expr()?;
4674 self.expect(&token::Semi)?;
4675 (name, ast::ImplItemKind::Const(typ, expr))
4677 let (name, inner_attrs, node) = self.parse_impl_method(&vis)?;
4678 attrs.extend(inner_attrs);
4683 id: ast::DUMMY_NODE_ID,
4684 span: mk_sp(lo, self.prev_span.hi),
4687 defaultness: defaultness,
4693 fn complain_if_pub_macro(&mut self, visa: &Visibility, span: Span) {
4695 Visibility::Inherited => (),
4697 let is_macro_rules: bool = match self.token {
4698 token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
4702 self.diagnostic().struct_span_err(span, "can't qualify macro_rules \
4703 invocation with `pub`")
4704 .help("did you mean #[macro_export]?")
4707 self.diagnostic().struct_span_err(span, "can't qualify macro \
4708 invocation with `pub`")
4709 .help("try adjusting the macro to put `pub` \
4710 inside the invocation")
4717 /// Parse a method or a macro invocation in a trait impl.
4718 fn parse_impl_method(&mut self, vis: &Visibility)
4719 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4720 // code copied from parse_macro_use_or_failure... abstraction!
4721 if self.token.is_path_start() {
4724 let prev_span = self.prev_span;
4725 self.complain_if_pub_macro(&vis, prev_span);
4727 let lo = self.span.lo;
4728 let pth = self.parse_path(PathStyle::Mod)?;
4729 self.expect(&token::Not)?;
4731 // eat a matched-delimiter token tree:
4732 let (delim, tts) = self.expect_delimited_token_tree()?;
4733 if delim != token::Brace {
4734 self.expect(&token::Semi)?
4737 let mac = spanned(lo, self.prev_span.hi, Mac_ { path: pth, tts: tts });
4738 Ok((keywords::Invalid.ident(), vec![], ast::ImplItemKind::Macro(mac)))
4740 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
4741 let ident = self.parse_ident()?;
4742 let mut generics = self.parse_generics()?;
4743 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
4744 generics.where_clause = self.parse_where_clause()?;
4745 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4746 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4750 constness: constness,
4756 /// Parse trait Foo { ... }
4757 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4758 let ident = self.parse_ident()?;
4759 let mut tps = self.parse_generics()?;
4761 // Parse optional colon and supertrait bounds.
4762 let bounds = if self.eat(&token::Colon) {
4763 self.parse_ty_param_bounds()?
4768 tps.where_clause = self.parse_where_clause()?;
4770 let meths = self.parse_trait_items()?;
4771 Ok((ident, ItemKind::Trait(unsafety, tps, bounds, meths), None))
4774 /// Parses items implementations variants
4775 /// impl<T> Foo { ... }
4776 /// impl<T> ToString for &'static T { ... }
4777 /// impl Send for .. {}
4778 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> PResult<'a, ItemInfo> {
4779 let impl_span = self.span;
4781 // First, parse type parameters if necessary.
4782 let mut generics = self.parse_generics()?;
4784 // Special case: if the next identifier that follows is '(', don't
4785 // allow this to be parsed as a trait.
4786 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4788 let neg_span = self.span;
4789 let polarity = if self.eat(&token::Not) {
4790 ast::ImplPolarity::Negative
4792 ast::ImplPolarity::Positive
4796 let mut ty = self.parse_ty()?;
4798 // Parse traits, if necessary.
4799 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4800 // New-style trait. Reinterpret the type as a trait.
4802 TyKind::Path(None, ref path) => {
4804 path: (*path).clone(),
4809 self.span_err(ty.span, "not a trait");
4815 ast::ImplPolarity::Negative => {
4816 // This is a negated type implementation
4817 // `impl !MyType {}`, which is not allowed.
4818 self.span_err(neg_span, "inherent implementation can't be negated");
4825 if opt_trait.is_some() && self.eat(&token::DotDot) {
4826 if generics.is_parameterized() {
4827 self.span_err(impl_span, "default trait implementations are not \
4828 allowed to have generics");
4831 self.expect(&token::OpenDelim(token::Brace))?;
4832 self.expect(&token::CloseDelim(token::Brace))?;
4833 Ok((keywords::Invalid.ident(),
4834 ItemKind::DefaultImpl(unsafety, opt_trait.unwrap()), None))
4836 if opt_trait.is_some() {
4837 ty = self.parse_ty()?;
4839 generics.where_clause = self.parse_where_clause()?;
4841 self.expect(&token::OpenDelim(token::Brace))?;
4842 let attrs = self.parse_inner_attributes()?;
4844 let mut impl_items = vec![];
4845 while !self.eat(&token::CloseDelim(token::Brace)) {
4846 impl_items.push(self.parse_impl_item()?);
4849 Ok((keywords::Invalid.ident(),
4850 ItemKind::Impl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4855 /// Parse a::B<String,i32>
4856 fn parse_trait_ref(&mut self) -> PResult<'a, TraitRef> {
4858 path: self.parse_path(PathStyle::Type)?,
4859 ref_id: ast::DUMMY_NODE_ID,
4863 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<LifetimeDef>> {
4864 if self.eat_keyword(keywords::For) {
4866 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4868 if !ty_params.is_empty() {
4869 self.span_err(ty_params[0].span,
4870 "only lifetime parameters can be used in this context");
4878 /// Parse for<'l> a::B<String,i32>
4879 fn parse_poly_trait_ref(&mut self) -> PResult<'a, PolyTraitRef> {
4880 let lo = self.span.lo;
4881 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4884 bound_lifetimes: lifetime_defs,
4885 trait_ref: self.parse_trait_ref()?,
4886 span: mk_sp(lo, self.prev_span.hi),
4890 /// Parse struct Foo { ... }
4891 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
4892 let class_name = self.parse_ident()?;
4894 let mut generics = self.parse_generics()?;
4896 // There is a special case worth noting here, as reported in issue #17904.
4897 // If we are parsing a tuple struct it is the case that the where clause
4898 // should follow the field list. Like so:
4900 // struct Foo<T>(T) where T: Copy;
4902 // If we are parsing a normal record-style struct it is the case
4903 // that the where clause comes before the body, and after the generics.
4904 // So if we look ahead and see a brace or a where-clause we begin
4905 // parsing a record style struct.
4907 // Otherwise if we look ahead and see a paren we parse a tuple-style
4910 let vdata = if self.token.is_keyword(keywords::Where) {
4911 generics.where_clause = self.parse_where_clause()?;
4912 if self.eat(&token::Semi) {
4913 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4914 VariantData::Unit(ast::DUMMY_NODE_ID)
4916 // If we see: `struct Foo<T> where T: Copy { ... }`
4917 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
4919 // No `where` so: `struct Foo<T>;`
4920 } else if self.eat(&token::Semi) {
4921 VariantData::Unit(ast::DUMMY_NODE_ID)
4922 // Record-style struct definition
4923 } else if self.token == token::OpenDelim(token::Brace) {
4924 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
4925 // Tuple-style struct definition with optional where-clause.
4926 } else if self.token == token::OpenDelim(token::Paren) {
4927 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
4928 generics.where_clause = self.parse_where_clause()?;
4929 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 /// Parse union Foo { ... }
4941 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
4942 let class_name = self.parse_ident()?;
4944 let mut generics = self.parse_generics()?;
4946 let vdata = if self.token.is_keyword(keywords::Where) {
4947 generics.where_clause = self.parse_where_clause()?;
4948 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
4949 } else if self.token == token::OpenDelim(token::Brace) {
4950 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
4952 let token_str = self.this_token_to_string();
4953 return Err(self.fatal(&format!("expected `where` or `{{` after union \
4954 name, found `{}`", token_str)))
4957 Ok((class_name, ItemKind::Union(vdata, generics), None))
4960 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
4961 let mut fields = Vec::new();
4962 if self.eat(&token::OpenDelim(token::Brace)) {
4963 while self.token != token::CloseDelim(token::Brace) {
4964 fields.push(self.parse_struct_decl_field().map_err(|e| {
4965 self.recover_stmt();
4966 self.eat(&token::CloseDelim(token::Brace));
4973 let token_str = self.this_token_to_string();
4974 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
4982 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
4983 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
4984 // Unit like structs are handled in parse_item_struct function
4985 let fields = self.parse_unspanned_seq(
4986 &token::OpenDelim(token::Paren),
4987 &token::CloseDelim(token::Paren),
4988 SeqSep::trailing_allowed(token::Comma),
4990 let attrs = p.parse_outer_attributes()?;
4992 let mut vis = p.parse_visibility()?;
4993 let ty_is_interpolated =
4994 p.token.is_interpolated() || p.look_ahead(1, |t| t.is_interpolated());
4995 let mut ty = p.parse_ty()?;
4997 // Handle `pub(path) type`, in which `vis` will be `pub` and `ty` will be `(path)`.
4998 if vis == Visibility::Public && !ty_is_interpolated &&
4999 p.token != token::Comma && p.token != token::CloseDelim(token::Paren) {
5000 ty = if let TyKind::Paren(ref path_ty) = ty.node {
5001 if let TyKind::Path(None, ref path) = path_ty.node {
5002 vis = Visibility::Restricted { path: P(path.clone()), id: path_ty.id };
5012 span: mk_sp(lo, p.span.hi),
5015 id: ast::DUMMY_NODE_ID,
5024 /// Parse a structure field declaration
5025 pub fn parse_single_struct_field(&mut self,
5028 attrs: Vec<Attribute> )
5029 -> PResult<'a, StructField> {
5030 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5035 token::CloseDelim(token::Brace) => {}
5036 token::DocComment(_) => return Err(self.span_fatal_err(self.span,
5037 Error::UselessDocComment)),
5038 _ => return Err(self.span_fatal_help(self.span,
5039 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5040 "struct fields should be separated by commas")),
5045 /// Parse an element of a struct definition
5046 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5047 let attrs = self.parse_outer_attributes()?;
5048 let lo = self.span.lo;
5049 let vis = self.parse_visibility()?;
5050 self.parse_single_struct_field(lo, vis, attrs)
5053 // Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts
5054 // `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
5055 fn parse_visibility(&mut self) -> PResult<'a, Visibility> {
5056 if !self.eat_keyword(keywords::Pub) {
5057 return Ok(Visibility::Inherited)
5060 if self.check(&token::OpenDelim(token::Paren)) {
5061 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5064 self.bump(); // `crate`
5065 let vis = Visibility::Crate(self.prev_span);
5066 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5068 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5071 self.bump(); // `in`
5072 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5073 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5074 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5076 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5077 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5078 t.is_keyword(keywords::SelfValue)) {
5079 // `pub(self)` or `pub(super)`
5081 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5082 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5083 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5088 Ok(Visibility::Public)
5091 /// Parse defaultness: DEFAULT or nothing
5092 fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> {
5093 if self.eat_contextual_keyword(keywords::Default.ident()) {
5094 Ok(Defaultness::Default)
5096 Ok(Defaultness::Final)
5100 /// Given a termination token, parse all of the items in a module
5101 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: BytePos) -> PResult<'a, Mod> {
5102 let mut items = vec![];
5103 while let Some(item) = self.parse_item()? {
5107 if !self.eat(term) {
5108 let token_str = self.this_token_to_string();
5109 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5112 let hi = if self.span == syntax_pos::DUMMY_SP {
5119 inner: mk_sp(inner_lo, hi),
5124 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5125 let id = self.parse_ident()?;
5126 self.expect(&token::Colon)?;
5127 let ty = self.parse_ty()?;
5128 self.expect(&token::Eq)?;
5129 let e = self.parse_expr()?;
5130 self.expect(&token::Semi)?;
5131 let item = match m {
5132 Some(m) => ItemKind::Static(ty, m, e),
5133 None => ItemKind::Const(ty, e),
5135 Ok((id, item, None))
5138 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5139 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5140 let (in_cfg, outer_attrs) = {
5141 let mut strip_unconfigured = ::config::StripUnconfigured {
5143 should_test: false, // irrelevant
5144 features: None, // don't perform gated feature checking
5146 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5147 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5150 let id_span = self.span;
5151 let id = self.parse_ident()?;
5152 if self.check(&token::Semi) {
5155 // This mod is in an external file. Let's go get it!
5156 let ModulePathSuccess { path, directory_ownership, warn } =
5157 self.submod_path(id, &outer_attrs, id_span)?;
5158 let (module, mut attrs) =
5159 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5161 let attr = ast::Attribute {
5162 id: attr::mk_attr_id(),
5163 style: ast::AttrStyle::Outer,
5164 path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5165 Ident::from_str("warn_directory_ownership")),
5166 tokens: TokenStream::empty(),
5167 is_sugared_doc: false,
5168 span: syntax_pos::DUMMY_SP,
5170 attr::mark_known(&attr);
5173 Ok((id, module, Some(attrs)))
5175 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5176 Ok((id, ItemKind::Mod(placeholder), None))
5179 let old_directory = self.directory.clone();
5180 self.push_directory(id, &outer_attrs);
5181 self.expect(&token::OpenDelim(token::Brace))?;
5182 let mod_inner_lo = self.span.lo;
5183 let attrs = self.parse_inner_attributes()?;
5184 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5185 self.directory = old_directory;
5186 Ok((id, ItemKind::Mod(module), Some(attrs)))
5190 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5191 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5192 self.directory.path.push(&*path.as_str());
5193 self.directory.ownership = DirectoryOwnership::Owned;
5195 self.directory.path.push(&*id.name.as_str());
5199 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5200 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&*d.as_str()))
5203 /// Returns either a path to a module, or .
5204 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath {
5205 let mod_name = id.to_string();
5206 let default_path_str = format!("{}.rs", mod_name);
5207 let secondary_path_str = format!("{}/mod.rs", mod_name);
5208 let default_path = dir_path.join(&default_path_str);
5209 let secondary_path = dir_path.join(&secondary_path_str);
5210 let default_exists = codemap.file_exists(&default_path);
5211 let secondary_exists = codemap.file_exists(&secondary_path);
5213 let result = match (default_exists, secondary_exists) {
5214 (true, false) => Ok(ModulePathSuccess {
5216 directory_ownership: DirectoryOwnership::UnownedViaMod(false),
5219 (false, true) => Ok(ModulePathSuccess {
5220 path: secondary_path,
5221 directory_ownership: DirectoryOwnership::Owned,
5224 (false, false) => Err(Error::FileNotFoundForModule {
5225 mod_name: mod_name.clone(),
5226 default_path: default_path_str,
5227 secondary_path: secondary_path_str,
5228 dir_path: format!("{}", dir_path.display()),
5230 (true, true) => Err(Error::DuplicatePaths {
5231 mod_name: mod_name.clone(),
5232 default_path: default_path_str,
5233 secondary_path: secondary_path_str,
5239 path_exists: default_exists || secondary_exists,
5244 fn submod_path(&mut self,
5246 outer_attrs: &[ast::Attribute],
5247 id_sp: Span) -> PResult<'a, ModulePathSuccess> {
5248 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5249 return Ok(ModulePathSuccess {
5250 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5251 Some("mod.rs") => DirectoryOwnership::Owned,
5252 _ => DirectoryOwnership::UnownedViaMod(true),
5259 let paths = Parser::default_submod_path(id, &self.directory.path, self.sess.codemap());
5261 if let DirectoryOwnership::UnownedViaBlock = self.directory.ownership {
5263 "Cannot declare a non-inline module inside a block unless it has a path attribute";
5264 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5265 if paths.path_exists {
5266 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5268 err.span_note(id_sp, &msg);
5271 } else if let DirectoryOwnership::UnownedViaMod(warn) = self.directory.ownership {
5273 if let Ok(result) = paths.result {
5274 return Ok(ModulePathSuccess { warn: true, ..result });
5277 let mut err = self.diagnostic().struct_span_err(id_sp,
5278 "cannot declare a new module at this location");
5279 let this_module = match self.directory.path.file_name() {
5280 Some(file_name) => file_name.to_str().unwrap().to_owned(),
5281 None => self.root_module_name.as_ref().unwrap().clone(),
5283 err.span_note(id_sp,
5284 &format!("maybe move this module `{0}` to its own directory \
5287 if paths.path_exists {
5288 err.span_note(id_sp,
5289 &format!("... or maybe `use` the module `{}` instead \
5290 of possibly redeclaring it",
5297 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5301 /// Read a module from a source file.
5302 fn eval_src_mod(&mut self,
5304 directory_ownership: DirectoryOwnership,
5307 -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5308 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5309 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
5310 let mut err = String::from("circular modules: ");
5311 let len = included_mod_stack.len();
5312 for p in &included_mod_stack[i.. len] {
5313 err.push_str(&p.to_string_lossy());
5314 err.push_str(" -> ");
5316 err.push_str(&path.to_string_lossy());
5317 return Err(self.span_fatal(id_sp, &err[..]));
5319 included_mod_stack.push(path.clone());
5320 drop(included_mod_stack);
5323 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
5324 p0.cfg_mods = self.cfg_mods;
5325 let mod_inner_lo = p0.span.lo;
5326 let mod_attrs = p0.parse_inner_attributes()?;
5327 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
5328 self.sess.included_mod_stack.borrow_mut().pop();
5329 Ok((ast::ItemKind::Mod(m0), mod_attrs))
5332 /// Parse a function declaration from a foreign module
5333 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: BytePos,
5334 attrs: Vec<Attribute>) -> PResult<'a, ForeignItem> {
5335 self.expect_keyword(keywords::Fn)?;
5337 let (ident, mut generics) = self.parse_fn_header()?;
5338 let decl = self.parse_fn_decl(true)?;
5339 generics.where_clause = self.parse_where_clause()?;
5340 let hi = self.span.hi;
5341 self.expect(&token::Semi)?;
5342 Ok(ast::ForeignItem {
5345 node: ForeignItemKind::Fn(decl, generics),
5346 id: ast::DUMMY_NODE_ID,
5347 span: mk_sp(lo, hi),
5352 /// Parse a static item from a foreign module
5353 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: BytePos,
5354 attrs: Vec<Attribute>) -> PResult<'a, ForeignItem> {
5355 self.expect_keyword(keywords::Static)?;
5356 let mutbl = self.eat_keyword(keywords::Mut);
5358 let ident = self.parse_ident()?;
5359 self.expect(&token::Colon)?;
5360 let ty = self.parse_ty()?;
5361 let hi = self.span.hi;
5362 self.expect(&token::Semi)?;
5366 node: ForeignItemKind::Static(ty, mutbl),
5367 id: ast::DUMMY_NODE_ID,
5368 span: mk_sp(lo, hi),
5373 /// Parse extern crate links
5377 /// extern crate foo;
5378 /// extern crate bar as foo;
5379 fn parse_item_extern_crate(&mut self,
5381 visibility: Visibility,
5382 attrs: Vec<Attribute>)
5383 -> PResult<'a, P<Item>> {
5385 let crate_name = self.parse_ident()?;
5386 let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
5387 (Some(crate_name.name), ident)
5391 self.expect(&token::Semi)?;
5393 let prev_span = self.prev_span;
5397 ItemKind::ExternCrate(maybe_path),
5402 /// Parse `extern` for foreign ABIs
5405 /// `extern` is expected to have been
5406 /// consumed before calling this method
5412 fn parse_item_foreign_mod(&mut self,
5414 opt_abi: Option<abi::Abi>,
5415 visibility: Visibility,
5416 mut attrs: Vec<Attribute>)
5417 -> PResult<'a, P<Item>> {
5418 self.expect(&token::OpenDelim(token::Brace))?;
5420 let abi = opt_abi.unwrap_or(Abi::C);
5422 attrs.extend(self.parse_inner_attributes()?);
5424 let mut foreign_items = vec![];
5425 while let Some(item) = self.parse_foreign_item()? {
5426 foreign_items.push(item);
5428 self.expect(&token::CloseDelim(token::Brace))?;
5430 let prev_span = self.prev_span;
5431 let m = ast::ForeignMod {
5433 items: foreign_items
5437 keywords::Invalid.ident(),
5438 ItemKind::ForeignMod(m),
5443 /// Parse type Foo = Bar;
5444 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5445 let ident = self.parse_ident()?;
5446 let mut tps = self.parse_generics()?;
5447 tps.where_clause = self.parse_where_clause()?;
5448 self.expect(&token::Eq)?;
5449 let ty = self.parse_ty()?;
5450 self.expect(&token::Semi)?;
5451 Ok((ident, ItemKind::Ty(ty, tps), None))
5454 /// Parse the part of an "enum" decl following the '{'
5455 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5456 let mut variants = Vec::new();
5457 let mut all_nullary = true;
5458 let mut any_disr = None;
5459 while self.token != token::CloseDelim(token::Brace) {
5460 let variant_attrs = self.parse_outer_attributes()?;
5461 let vlo = self.span.lo;
5464 let mut disr_expr = None;
5465 let ident = self.parse_ident()?;
5466 if self.check(&token::OpenDelim(token::Brace)) {
5467 // Parse a struct variant.
5468 all_nullary = false;
5469 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
5470 ast::DUMMY_NODE_ID);
5471 } else if self.check(&token::OpenDelim(token::Paren)) {
5472 all_nullary = false;
5473 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
5474 ast::DUMMY_NODE_ID);
5475 } else if self.eat(&token::Eq) {
5476 disr_expr = Some(self.parse_expr()?);
5477 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5478 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5480 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5483 let vr = ast::Variant_ {
5485 attrs: variant_attrs,
5487 disr_expr: disr_expr,
5489 variants.push(spanned(vlo, self.prev_span.hi, vr));
5491 if !self.eat(&token::Comma) { break; }
5493 self.expect(&token::CloseDelim(token::Brace))?;
5495 Some(disr_span) if !all_nullary =>
5496 self.span_err(disr_span,
5497 "discriminator values can only be used with a c-like enum"),
5501 Ok(ast::EnumDef { variants: variants })
5504 /// Parse an "enum" declaration
5505 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5506 let id = self.parse_ident()?;
5507 let mut generics = self.parse_generics()?;
5508 generics.where_clause = self.parse_where_clause()?;
5509 self.expect(&token::OpenDelim(token::Brace))?;
5511 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
5512 self.recover_stmt();
5513 self.eat(&token::CloseDelim(token::Brace));
5516 Ok((id, ItemKind::Enum(enum_definition, generics), None))
5519 /// Parses a string as an ABI spec on an extern type or module. Consumes
5520 /// the `extern` keyword, if one is found.
5521 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5523 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5525 self.expect_no_suffix(sp, "ABI spec", suf);
5527 match abi::lookup(&s.as_str()) {
5528 Some(abi) => Ok(Some(abi)),
5530 let prev_span = self.prev_span;
5533 &format!("invalid ABI: expected one of [{}], \
5535 abi::all_names().join(", "),
5546 /// Parse one of the items allowed by the flags.
5547 /// NB: this function no longer parses the items inside an
5549 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5550 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5551 maybe_whole!(self, NtItem, |item| {
5552 let mut item = item.unwrap();
5553 let mut attrs = attrs;
5554 mem::swap(&mut item.attrs, &mut attrs);
5555 item.attrs.extend(attrs);
5559 let lo = self.span.lo;
5561 let visibility = self.parse_visibility()?;
5563 if self.eat_keyword(keywords::Use) {
5565 let item_ = ItemKind::Use(self.parse_view_path()?);
5566 self.expect(&token::Semi)?;
5568 let prev_span = self.prev_span;
5569 let item = self.mk_item(lo,
5571 keywords::Invalid.ident(),
5575 return Ok(Some(item));
5578 if self.eat_keyword(keywords::Extern) {
5579 if self.eat_keyword(keywords::Crate) {
5580 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
5583 let opt_abi = self.parse_opt_abi()?;
5585 if self.eat_keyword(keywords::Fn) {
5586 // EXTERN FUNCTION ITEM
5587 let fn_span = self.prev_span;
5588 let abi = opt_abi.unwrap_or(Abi::C);
5589 let (ident, item_, extra_attrs) =
5590 self.parse_item_fn(Unsafety::Normal,
5591 respan(fn_span, Constness::NotConst),
5593 let prev_span = self.prev_span;
5594 let item = self.mk_item(lo,
5599 maybe_append(attrs, extra_attrs));
5600 return Ok(Some(item));
5601 } else if self.check(&token::OpenDelim(token::Brace)) {
5602 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
5608 if self.eat_keyword(keywords::Static) {
5610 let m = if self.eat_keyword(keywords::Mut) {
5613 Mutability::Immutable
5615 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
5616 let prev_span = self.prev_span;
5617 let item = self.mk_item(lo,
5622 maybe_append(attrs, extra_attrs));
5623 return Ok(Some(item));
5625 if self.eat_keyword(keywords::Const) {
5626 let const_span = self.prev_span;
5627 if self.check_keyword(keywords::Fn)
5628 || (self.check_keyword(keywords::Unsafe)
5629 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5630 // CONST FUNCTION ITEM
5631 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5637 let (ident, item_, extra_attrs) =
5638 self.parse_item_fn(unsafety,
5639 respan(const_span, Constness::Const),
5641 let prev_span = self.prev_span;
5642 let item = self.mk_item(lo,
5647 maybe_append(attrs, extra_attrs));
5648 return Ok(Some(item));
5652 if self.eat_keyword(keywords::Mut) {
5653 let prev_span = self.prev_span;
5654 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
5655 .help("did you mean to declare a static?")
5658 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
5659 let prev_span = self.prev_span;
5660 let item = self.mk_item(lo,
5665 maybe_append(attrs, extra_attrs));
5666 return Ok(Some(item));
5668 if self.check_keyword(keywords::Unsafe) &&
5669 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5671 // UNSAFE TRAIT ITEM
5672 self.expect_keyword(keywords::Unsafe)?;
5673 self.expect_keyword(keywords::Trait)?;
5674 let (ident, item_, extra_attrs) =
5675 self.parse_item_trait(ast::Unsafety::Unsafe)?;
5676 let prev_span = self.prev_span;
5677 let item = self.mk_item(lo,
5682 maybe_append(attrs, extra_attrs));
5683 return Ok(Some(item));
5685 if self.check_keyword(keywords::Unsafe) &&
5686 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5689 self.expect_keyword(keywords::Unsafe)?;
5690 self.expect_keyword(keywords::Impl)?;
5691 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe)?;
5692 let prev_span = self.prev_span;
5693 let item = self.mk_item(lo,
5698 maybe_append(attrs, extra_attrs));
5699 return Ok(Some(item));
5701 if self.check_keyword(keywords::Fn) {
5704 let fn_span = self.prev_span;
5705 let (ident, item_, extra_attrs) =
5706 self.parse_item_fn(Unsafety::Normal,
5707 respan(fn_span, Constness::NotConst),
5709 let prev_span = self.prev_span;
5710 let item = self.mk_item(lo,
5715 maybe_append(attrs, extra_attrs));
5716 return Ok(Some(item));
5718 if self.check_keyword(keywords::Unsafe)
5719 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5720 // UNSAFE FUNCTION ITEM
5722 let abi = if self.eat_keyword(keywords::Extern) {
5723 self.parse_opt_abi()?.unwrap_or(Abi::C)
5727 self.expect_keyword(keywords::Fn)?;
5728 let fn_span = self.prev_span;
5729 let (ident, item_, extra_attrs) =
5730 self.parse_item_fn(Unsafety::Unsafe,
5731 respan(fn_span, Constness::NotConst),
5733 let prev_span = self.prev_span;
5734 let item = self.mk_item(lo,
5739 maybe_append(attrs, extra_attrs));
5740 return Ok(Some(item));
5742 if self.eat_keyword(keywords::Mod) {
5744 let (ident, item_, extra_attrs) =
5745 self.parse_item_mod(&attrs[..])?;
5746 let prev_span = self.prev_span;
5747 let item = self.mk_item(lo,
5752 maybe_append(attrs, extra_attrs));
5753 return Ok(Some(item));
5755 if self.eat_keyword(keywords::Type) {
5757 let (ident, item_, extra_attrs) = self.parse_item_type()?;
5758 let prev_span = self.prev_span;
5759 let item = self.mk_item(lo,
5764 maybe_append(attrs, extra_attrs));
5765 return Ok(Some(item));
5767 if self.eat_keyword(keywords::Enum) {
5769 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
5770 let prev_span = self.prev_span;
5771 let item = self.mk_item(lo,
5776 maybe_append(attrs, extra_attrs));
5777 return Ok(Some(item));
5779 if self.eat_keyword(keywords::Trait) {
5781 let (ident, item_, extra_attrs) =
5782 self.parse_item_trait(ast::Unsafety::Normal)?;
5783 let prev_span = self.prev_span;
5784 let item = self.mk_item(lo,
5789 maybe_append(attrs, extra_attrs));
5790 return Ok(Some(item));
5792 if self.eat_keyword(keywords::Impl) {
5794 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal)?;
5795 let prev_span = self.prev_span;
5796 let item = self.mk_item(lo,
5801 maybe_append(attrs, extra_attrs));
5802 return Ok(Some(item));
5804 if self.eat_keyword(keywords::Struct) {
5806 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
5807 let prev_span = self.prev_span;
5808 let item = self.mk_item(lo,
5813 maybe_append(attrs, extra_attrs));
5814 return Ok(Some(item));
5816 if self.is_union_item() {
5819 let (ident, item_, extra_attrs) = self.parse_item_union()?;
5820 let prev_span = self.prev_span;
5821 let item = self.mk_item(lo,
5826 maybe_append(attrs, extra_attrs));
5827 return Ok(Some(item));
5829 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility)? {
5830 return Ok(Some(macro_def));
5833 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5836 /// Parse a foreign item.
5837 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
5838 let attrs = self.parse_outer_attributes()?;
5839 let lo = self.span.lo;
5840 let visibility = self.parse_visibility()?;
5842 if self.check_keyword(keywords::Static) {
5843 // FOREIGN STATIC ITEM
5844 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
5846 if self.check_keyword(keywords::Fn) {
5847 // FOREIGN FUNCTION ITEM
5848 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
5851 // FIXME #5668: this will occur for a macro invocation:
5852 match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
5854 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5860 /// This is the fall-through for parsing items.
5861 fn parse_macro_use_or_failure(
5863 attrs: Vec<Attribute> ,
5864 macros_allowed: bool,
5865 attributes_allowed: bool,
5867 visibility: Visibility
5868 ) -> PResult<'a, Option<P<Item>>> {
5869 if macros_allowed && self.token.is_path_start() {
5870 // MACRO INVOCATION ITEM
5872 let prev_span = self.prev_span;
5873 self.complain_if_pub_macro(&visibility, prev_span);
5875 let mac_lo = self.span.lo;
5878 let pth = self.parse_path(PathStyle::Mod)?;
5879 self.expect(&token::Not)?;
5881 // a 'special' identifier (like what `macro_rules!` uses)
5882 // is optional. We should eventually unify invoc syntax
5884 let id = if self.token.is_ident() {
5887 keywords::Invalid.ident() // no special identifier
5889 // eat a matched-delimiter token tree:
5890 let (delim, tts) = self.expect_delimited_token_tree()?;
5891 if delim != token::Brace {
5892 if !self.eat(&token::Semi) {
5893 let prev_span = self.prev_span;
5894 self.span_err(prev_span,
5895 "macros that expand to items must either \
5896 be surrounded with braces or followed by \
5901 let hi = self.prev_span.hi;
5902 let mac = spanned(mac_lo, hi, Mac_ { path: pth, tts: tts });
5903 let item = self.mk_item(lo, hi, id, ItemKind::Mac(mac), visibility, attrs);
5904 return Ok(Some(item));
5907 // FAILURE TO PARSE ITEM
5909 Visibility::Inherited => {}
5911 let prev_span = self.prev_span;
5912 return Err(self.span_fatal(prev_span, "unmatched visibility `pub`"));
5916 if !attributes_allowed && !attrs.is_empty() {
5917 self.expected_item_err(&attrs);
5922 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
5923 let attrs = self.parse_outer_attributes()?;
5924 self.parse_item_(attrs, true, false)
5927 fn parse_path_list_items(&mut self) -> PResult<'a, Vec<ast::PathListItem>> {
5928 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
5929 &token::CloseDelim(token::Brace),
5930 SeqSep::trailing_allowed(token::Comma), |this| {
5931 let lo = this.span.lo;
5932 let ident = if this.eat_keyword(keywords::SelfValue) {
5933 keywords::SelfValue.ident()
5937 let rename = this.parse_rename()?;
5938 let node = ast::PathListItem_ {
5941 id: ast::DUMMY_NODE_ID
5943 let hi = this.prev_span.hi;
5944 Ok(spanned(lo, hi, node))
5949 fn is_import_coupler(&mut self) -> bool {
5950 self.check(&token::ModSep) &&
5951 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
5952 *t == token::BinOp(token::Star))
5955 /// Matches ViewPath:
5956 /// MOD_SEP? non_global_path
5957 /// MOD_SEP? non_global_path as IDENT
5958 /// MOD_SEP? non_global_path MOD_SEP STAR
5959 /// MOD_SEP? non_global_path MOD_SEP LBRACE item_seq RBRACE
5960 /// MOD_SEP? LBRACE item_seq RBRACE
5961 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
5962 let lo = self.span.lo;
5963 if self.check(&token::OpenDelim(token::Brace)) || self.check(&token::BinOp(token::Star)) ||
5964 self.is_import_coupler() {
5965 // `{foo, bar}`, `::{foo, bar}`, `*`, or `::*`.
5966 self.eat(&token::ModSep);
5967 let prefix = ast::Path {
5968 segments: vec![PathSegment::crate_root()],
5969 span: mk_sp(lo, self.span.hi),
5971 let view_path_kind = if self.eat(&token::BinOp(token::Star)) {
5972 ViewPathGlob(prefix)
5974 ViewPathList(prefix, self.parse_path_list_items()?)
5976 Ok(P(spanned(lo, self.span.hi, view_path_kind)))
5978 let prefix = self.parse_path(PathStyle::Mod)?.default_to_global();
5979 if self.is_import_coupler() {
5980 // `foo::bar::{a, b}` or `foo::bar::*`
5982 if self.check(&token::BinOp(token::Star)) {
5984 Ok(P(spanned(lo, self.span.hi, ViewPathGlob(prefix))))
5986 let items = self.parse_path_list_items()?;
5987 Ok(P(spanned(lo, self.span.hi, ViewPathList(prefix, items))))
5990 // `foo::bar` or `foo::bar as baz`
5991 let rename = self.parse_rename()?.
5992 unwrap_or(prefix.segments.last().unwrap().identifier);
5993 Ok(P(spanned(lo, self.prev_span.hi, ViewPathSimple(rename, prefix))))
5998 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
5999 if self.eat_keyword(keywords::As) {
6000 self.parse_ident().map(Some)
6006 /// Parses a source module as a crate. This is the main
6007 /// entry point for the parser.
6008 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6009 let lo = self.span.lo;
6011 attrs: self.parse_inner_attributes()?,
6012 module: self.parse_mod_items(&token::Eof, lo)?,
6013 span: mk_sp(lo, self.span.lo),
6017 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6018 let ret = match self.token {
6019 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6020 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6027 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6028 match self.parse_optional_str() {
6029 Some((s, style, suf)) => {
6030 let sp = self.prev_span;
6031 self.expect_no_suffix(sp, "string literal", suf);
6034 _ => Err(self.fatal("expected string literal"))