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, respan};
44 use syntax_pos::{self, Span, BytePos};
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::{self, 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, kind, ThinVec::new()));
113 token::NtBlock(ref block) => {
116 let kind = ExprKind::Block((*block).clone());
117 return Ok($p.mk_expr(span, 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:
163 pub meta_var_span: Option<Span>,
165 /// the previous token kind
166 prev_token_kind: PrevTokenKind,
167 pub restrictions: Restrictions,
168 /// The set of seen errors about obsolete syntax. Used to suppress
169 /// extra detail when the same error is seen twice
170 pub obsolete_set: HashSet<ObsoleteSyntax>,
171 /// Used to determine the path to externally loaded source files
172 pub directory: Directory,
173 /// Name of the root module this parser originated from. If `None`, then the
174 /// name is not known. This does not change while the parser is descending
175 /// into modules, and sub-parsers have new values for this name.
176 pub root_module_name: Option<String>,
177 pub expected_tokens: Vec<TokenType>,
178 token_cursor: TokenCursor,
179 pub desugar_doc_comments: bool,
180 /// Whether we should configure out of line modules as we parse.
185 frame: TokenCursorFrame,
186 stack: Vec<TokenCursorFrame>,
189 struct TokenCursorFrame {
190 delim: token::DelimToken,
193 tree_cursor: tokenstream::Cursor,
197 impl TokenCursorFrame {
198 fn new(sp: Span, delimited: &Delimited) -> Self {
200 delim: delimited.delim,
202 open_delim: delimited.delim == token::NoDelim,
203 tree_cursor: delimited.stream().into_trees(),
204 close_delim: delimited.delim == token::NoDelim,
210 fn next(&mut self) -> TokenAndSpan {
212 let tree = if !self.frame.open_delim {
213 self.frame.open_delim = true;
214 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
215 .open_tt(self.frame.span)
216 } else if let Some(tree) = self.frame.tree_cursor.next() {
218 } else if !self.frame.close_delim {
219 self.frame.close_delim = true;
220 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
221 .close_tt(self.frame.span)
222 } else if let Some(frame) = self.stack.pop() {
226 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
230 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
231 TokenTree::Delimited(sp, ref delimited) => {
232 let frame = TokenCursorFrame::new(sp, delimited);
233 self.stack.push(mem::replace(&mut self.frame, frame));
239 fn next_desugared(&mut self) -> TokenAndSpan {
240 let (sp, name) = match self.next() {
241 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
242 tok @ _ => return tok,
245 let stripped = strip_doc_comment_decoration(&name.as_str());
247 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
248 // required to wrap the text.
249 let mut num_of_hashes = 0;
251 for ch in stripped.chars() {
254 '#' if count > 0 => count + 1,
257 num_of_hashes = cmp::max(num_of_hashes, count);
260 let body = TokenTree::Delimited(sp, Delimited {
261 delim: token::Bracket,
262 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"))),
263 TokenTree::Token(sp, token::Eq),
264 TokenTree::Token(sp, token::Literal(
265 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
266 .iter().cloned().collect::<TokenStream>().into(),
269 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
270 delim: token::NoDelim,
271 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
272 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
273 .iter().cloned().collect::<TokenStream>().into()
275 [TokenTree::Token(sp, token::Pound), body]
276 .iter().cloned().collect::<TokenStream>().into()
284 #[derive(PartialEq, Eq, Clone)]
287 Keyword(keywords::Keyword),
296 fn to_string(&self) -> String {
298 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
299 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
300 TokenType::Operator => "an operator".to_string(),
301 TokenType::Lifetime => "lifetime".to_string(),
302 TokenType::Ident => "identifier".to_string(),
303 TokenType::Path => "path".to_string(),
304 TokenType::Type => "type".to_string(),
309 fn is_ident_or_underscore(t: &token::Token) -> bool {
310 t.is_ident() || *t == token::Underscore
313 /// Information about the path to a module.
314 pub struct ModulePath {
316 pub path_exists: bool,
317 pub result: Result<ModulePathSuccess, Error>,
320 pub struct ModulePathSuccess {
322 pub directory_ownership: DirectoryOwnership,
326 pub struct ModulePathError {
328 pub help_msg: String,
332 FileNotFoundForModule {
334 default_path: String,
335 secondary_path: String,
340 default_path: String,
341 secondary_path: String,
344 InclusiveRangeWithNoEnd,
348 pub fn span_err<'a>(self, sp: Span, handler: &'a errors::Handler) -> DiagnosticBuilder<'a> {
350 Error::FileNotFoundForModule { ref mod_name,
354 let mut err = struct_span_err!(handler, sp, E0583,
355 "file not found for module `{}`", mod_name);
356 err.help(&format!("name the file either {} or {} inside the directory {:?}",
362 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
363 let mut err = struct_span_err!(handler, sp, E0584,
364 "file for module `{}` found at both {} and {}",
368 err.help("delete or rename one of them to remove the ambiguity");
371 Error::UselessDocComment => {
372 let mut err = struct_span_err!(handler, sp, E0585,
373 "found a documentation comment that doesn't document anything");
374 err.help("doc comments must come before what they document, maybe a comment was \
375 intended with `//`?");
378 Error::InclusiveRangeWithNoEnd => {
379 let mut err = struct_span_err!(handler, sp, E0586,
380 "inclusive range with no end");
381 err.help("inclusive ranges must be bounded at the end (`...b` or `a...b`)");
390 AttributesParsed(ThinVec<Attribute>),
391 AlreadyParsed(P<Expr>),
394 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
395 fn from(o: Option<ThinVec<Attribute>>) -> Self {
396 if let Some(attrs) = o {
397 LhsExpr::AttributesParsed(attrs)
399 LhsExpr::NotYetParsed
404 impl From<P<Expr>> for LhsExpr {
405 fn from(expr: P<Expr>) -> Self {
406 LhsExpr::AlreadyParsed(expr)
410 /// Create a placeholder argument.
411 fn dummy_arg(span: Span) -> Arg {
412 let spanned = Spanned {
414 node: keywords::Invalid.ident()
417 id: ast::DUMMY_NODE_ID,
418 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), spanned, None),
424 id: ast::DUMMY_NODE_ID
426 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
429 impl<'a> Parser<'a> {
430 pub fn new(sess: &'a ParseSess,
432 directory: Option<Directory>,
433 desugar_doc_comments: bool)
435 let mut parser = Parser {
437 token: token::Underscore,
438 span: syntax_pos::DUMMY_SP,
439 prev_span: syntax_pos::DUMMY_SP,
441 prev_token_kind: PrevTokenKind::Other,
442 restrictions: Restrictions::empty(),
443 obsolete_set: HashSet::new(),
444 directory: Directory { path: PathBuf::new(), ownership: DirectoryOwnership::Owned },
445 root_module_name: None,
446 expected_tokens: Vec::new(),
447 token_cursor: TokenCursor {
448 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
449 delim: token::NoDelim,
454 desugar_doc_comments: desugar_doc_comments,
458 let tok = parser.next_tok();
459 parser.token = tok.tok;
460 parser.span = tok.sp;
461 if let Some(directory) = directory {
462 parser.directory = directory;
463 } else if parser.span != syntax_pos::DUMMY_SP {
464 parser.directory.path = PathBuf::from(sess.codemap().span_to_filename(parser.span));
465 parser.directory.path.pop();
467 parser.process_potential_macro_variable();
471 fn next_tok(&mut self) -> TokenAndSpan {
472 let mut next = match self.desugar_doc_comments {
473 true => self.token_cursor.next_desugared(),
474 false => self.token_cursor.next(),
476 if next.sp == syntax_pos::DUMMY_SP {
477 next.sp = self.prev_span;
482 /// Convert a token to a string using self's reader
483 pub fn token_to_string(token: &token::Token) -> String {
484 pprust::token_to_string(token)
487 /// Convert the current token to a string using self's reader
488 pub fn this_token_to_string(&self) -> String {
489 Parser::token_to_string(&self.token)
492 pub fn this_token_descr(&self) -> String {
493 let s = self.this_token_to_string();
494 if self.token.is_strict_keyword() {
495 format!("keyword `{}`", s)
496 } else if self.token.is_reserved_keyword() {
497 format!("reserved keyword `{}`", s)
503 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
504 let token_str = Parser::token_to_string(t);
505 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
508 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
509 match self.expect_one_of(&[], &[]) {
511 Ok(_) => unreachable!(),
515 /// Expect and consume the token t. Signal an error if
516 /// the next token is not t.
517 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
518 if self.expected_tokens.is_empty() {
519 if self.token == *t {
523 let token_str = Parser::token_to_string(t);
524 let this_token_str = self.this_token_to_string();
525 Err(self.fatal(&format!("expected `{}`, found `{}`",
530 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
534 /// Expect next token to be edible or inedible token. If edible,
535 /// then consume it; if inedible, then return without consuming
536 /// anything. Signal a fatal error if next token is unexpected.
537 pub fn expect_one_of(&mut self,
538 edible: &[token::Token],
539 inedible: &[token::Token]) -> PResult<'a, ()>{
540 fn tokens_to_string(tokens: &[TokenType]) -> String {
541 let mut i = tokens.iter();
542 // This might be a sign we need a connect method on Iterator.
544 .map_or("".to_string(), |t| t.to_string());
545 i.enumerate().fold(b, |mut b, (i, ref a)| {
546 if tokens.len() > 2 && i == tokens.len() - 2 {
548 } else if tokens.len() == 2 && i == tokens.len() - 2 {
553 b.push_str(&a.to_string());
557 if edible.contains(&self.token) {
560 } else if inedible.contains(&self.token) {
561 // leave it in the input
564 let mut expected = edible.iter()
565 .map(|x| TokenType::Token(x.clone()))
566 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
567 .chain(self.expected_tokens.iter().cloned())
568 .collect::<Vec<_>>();
569 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
571 let expect = tokens_to_string(&expected[..]);
572 let actual = self.this_token_to_string();
573 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
574 let short_expect = if expected.len() > 6 {
575 format!("{} possible tokens", expected.len())
579 (format!("expected one of {}, found `{}`", expect, actual),
580 (self.prev_span.next_point(), format!("expected one of {} here", short_expect)))
581 } else if expected.is_empty() {
582 (format!("unexpected token: `{}`", actual),
583 (self.prev_span, "unexpected token after this".to_string()))
585 (format!("expected {}, found `{}`", expect, actual),
586 (self.prev_span.next_point(), format!("expected {} here", expect)))
588 let mut err = self.fatal(&msg_exp);
589 let sp = if self.token == token::Token::Eof {
590 // This is EOF, don't want to point at the following char, but rather the last token
595 if self.span.contains(sp) {
596 err.span_label(self.span, &label_exp);
598 err.span_label(sp, &label_exp);
599 err.span_label(self.span, &"unexpected token");
605 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
606 fn interpolated_or_expr_span(&self,
607 expr: PResult<'a, P<Expr>>)
608 -> PResult<'a, (Span, P<Expr>)> {
610 if self.prev_token_kind == PrevTokenKind::Interpolated {
618 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
619 self.check_strict_keywords();
620 self.check_reserved_keywords();
627 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
628 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
630 let mut err = self.fatal(&format!("expected identifier, found `{}`",
631 self.this_token_to_string()));
632 if self.token == token::Underscore {
633 err.note("`_` is a wildcard pattern, not an identifier");
641 /// Check if the next token is `tok`, and return `true` if so.
643 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
645 pub fn check(&mut self, tok: &token::Token) -> bool {
646 let is_present = self.token == *tok;
647 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
651 /// Consume token 'tok' if it exists. Returns true if the given
652 /// token was present, false otherwise.
653 pub fn eat(&mut self, tok: &token::Token) -> bool {
654 let is_present = self.check(tok);
655 if is_present { self.bump() }
659 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
660 self.expected_tokens.push(TokenType::Keyword(kw));
661 self.token.is_keyword(kw)
664 /// If the next token is the given keyword, eat it and return
665 /// true. Otherwise, return false.
666 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
667 if self.check_keyword(kw) {
675 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
676 if self.token.is_keyword(kw) {
684 pub fn check_contextual_keyword(&mut self, ident: Ident) -> bool {
685 self.expected_tokens.push(TokenType::Token(token::Ident(ident)));
686 if let token::Ident(ref cur_ident) = self.token {
687 cur_ident.name == ident.name
693 pub fn eat_contextual_keyword(&mut self, ident: Ident) -> bool {
694 if self.check_contextual_keyword(ident) {
702 /// If the given word is not a keyword, signal an error.
703 /// If the next token is not the given word, signal an error.
704 /// Otherwise, eat it.
705 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
706 if !self.eat_keyword(kw) {
713 /// Signal an error if the given string is a strict keyword
714 pub fn check_strict_keywords(&mut self) {
715 if self.token.is_strict_keyword() {
716 let token_str = self.this_token_to_string();
717 let span = self.span;
719 &format!("expected identifier, found keyword `{}`",
724 /// Signal an error if the current token is a reserved keyword
725 pub fn check_reserved_keywords(&mut self) {
726 if self.token.is_reserved_keyword() {
727 let token_str = self.this_token_to_string();
728 self.fatal(&format!("`{}` is a reserved keyword", token_str)).emit()
732 fn check_ident(&mut self) -> bool {
733 if self.token.is_ident() {
736 self.expected_tokens.push(TokenType::Ident);
741 fn check_path(&mut self) -> bool {
742 if self.token.is_path_start() {
745 self.expected_tokens.push(TokenType::Path);
750 fn check_type(&mut self) -> bool {
751 if self.token.can_begin_type() {
754 self.expected_tokens.push(TokenType::Type);
759 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
760 /// `&` and continue. If an `&` is not seen, signal an error.
761 fn expect_and(&mut self) -> PResult<'a, ()> {
762 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
764 token::BinOp(token::And) => {
769 let span = self.span;
770 let lo = span.lo + BytePos(1);
771 Ok(self.bump_with(token::BinOp(token::And), Span { lo: lo, ..span }))
773 _ => self.unexpected()
777 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
779 None => {/* everything ok */}
781 let text = suf.as_str();
783 self.span_bug(sp, "found empty literal suffix in Some")
785 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
790 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
791 /// `<` and continue. If a `<` is not seen, return false.
793 /// This is meant to be used when parsing generics on a path to get the
795 fn eat_lt(&mut self) -> bool {
796 self.expected_tokens.push(TokenType::Token(token::Lt));
802 token::BinOp(token::Shl) => {
803 let span = self.span;
804 let lo = span.lo + BytePos(1);
805 self.bump_with(token::Lt, Span { lo: lo, ..span });
812 fn expect_lt(&mut self) -> PResult<'a, ()> {
820 /// Expect and consume a GT. if a >> is seen, replace it
821 /// with a single > and continue. If a GT is not seen,
823 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
824 self.expected_tokens.push(TokenType::Token(token::Gt));
830 token::BinOp(token::Shr) => {
831 let span = self.span;
832 let lo = span.lo + BytePos(1);
833 Ok(self.bump_with(token::Gt, Span { lo: lo, ..span }))
835 token::BinOpEq(token::Shr) => {
836 let span = self.span;
837 let lo = span.lo + BytePos(1);
838 Ok(self.bump_with(token::Ge, Span { lo: lo, ..span }))
841 let span = self.span;
842 let lo = span.lo + BytePos(1);
843 Ok(self.bump_with(token::Eq, Span { lo: lo, ..span }))
845 _ => self.unexpected()
849 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
850 sep: Option<token::Token>,
852 -> PResult<'a, (Vec<T>, bool)>
853 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
855 let mut v = Vec::new();
856 // This loop works by alternating back and forth between parsing types
857 // and commas. For example, given a string `A, B,>`, the parser would
858 // first parse `A`, then a comma, then `B`, then a comma. After that it
859 // would encounter a `>` and stop. This lets the parser handle trailing
860 // commas in generic parameters, because it can stop either after
861 // parsing a type or after parsing a comma.
863 if self.check(&token::Gt)
864 || self.token == token::BinOp(token::Shr)
865 || self.token == token::Ge
866 || self.token == token::BinOpEq(token::Shr) {
872 Some(result) => v.push(result),
873 None => return Ok((v, true))
876 if let Some(t) = sep.as_ref() {
882 return Ok((v, false));
885 /// Parse a sequence bracketed by '<' and '>', stopping
887 pub fn parse_seq_to_before_gt<T, F>(&mut self,
888 sep: Option<token::Token>,
890 -> PResult<'a, Vec<T>> where
891 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
893 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
894 |p| Ok(Some(f(p)?)))?;
899 pub fn parse_seq_to_gt<T, F>(&mut self,
900 sep: Option<token::Token>,
902 -> PResult<'a, Vec<T>> where
903 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
905 let v = self.parse_seq_to_before_gt(sep, f)?;
910 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
911 sep: Option<token::Token>,
913 -> PResult<'a, (Vec<T>, bool)> where
914 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
916 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
920 return Ok((v, returned));
923 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
924 /// passes through any errors encountered. Used for error recovery.
925 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
926 let handler = self.diagnostic();
928 self.parse_seq_to_before_tokens(kets,
930 |p| Ok(p.parse_token_tree()),
931 |mut e| handler.cancel(&mut e));
934 /// Parse a sequence, including the closing delimiter. The function
935 /// f must consume tokens until reaching the next separator or
937 pub fn parse_seq_to_end<T, F>(&mut self,
941 -> PResult<'a, Vec<T>> where
942 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
944 let val = self.parse_seq_to_before_end(ket, sep, f);
949 /// Parse a sequence, not including the closing delimiter. The function
950 /// f must consume tokens until reaching the next separator or
952 pub fn parse_seq_to_before_end<T, F>(&mut self,
957 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
959 self.parse_seq_to_before_tokens(&[ket], sep, f, |mut e| e.emit())
962 // `fe` is an error handler.
963 fn parse_seq_to_before_tokens<T, F, Fe>(&mut self,
964 kets: &[&token::Token],
969 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
970 Fe: FnMut(DiagnosticBuilder)
972 let mut first: bool = true;
974 while !kets.contains(&&self.token) {
976 token::CloseDelim(..) | token::Eof => break,
984 if let Err(e) = self.expect(t) {
992 if sep.trailing_sep_allowed && kets.iter().any(|k| self.check(k)) {
1008 /// Parse a sequence, including the closing delimiter. The function
1009 /// f must consume tokens until reaching the next separator or
1010 /// closing bracket.
1011 pub fn parse_unspanned_seq<T, F>(&mut self,
1016 -> PResult<'a, Vec<T>> where
1017 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1020 let result = self.parse_seq_to_before_end(ket, sep, f);
1021 if self.token == *ket {
1027 // NB: Do not use this function unless you actually plan to place the
1028 // spanned list in the AST.
1029 pub fn parse_seq<T, F>(&mut self,
1034 -> PResult<'a, Spanned<Vec<T>>> where
1035 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1039 let result = self.parse_seq_to_before_end(ket, sep, f);
1042 Ok(respan(lo.to(hi), result))
1045 /// Advance the parser by one token
1046 pub fn bump(&mut self) {
1047 if self.prev_token_kind == PrevTokenKind::Eof {
1048 // Bumping after EOF is a bad sign, usually an infinite loop.
1049 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1052 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1054 // Record last token kind for possible error recovery.
1055 self.prev_token_kind = match self.token {
1056 token::DocComment(..) => PrevTokenKind::DocComment,
1057 token::Comma => PrevTokenKind::Comma,
1058 token::Interpolated(..) => PrevTokenKind::Interpolated,
1059 token::Eof => PrevTokenKind::Eof,
1060 _ => PrevTokenKind::Other,
1063 let next = self.next_tok();
1064 self.span = next.sp;
1065 self.token = next.tok;
1066 self.expected_tokens.clear();
1067 // check after each token
1068 self.process_potential_macro_variable();
1071 /// Advance the parser using provided token as a next one. Use this when
1072 /// consuming a part of a token. For example a single `<` from `<<`.
1073 pub fn bump_with(&mut self, next: token::Token, span: Span) {
1074 self.prev_span = Span { hi: span.lo, ..self.span };
1075 // It would be incorrect to record the kind of the current token, but
1076 // fortunately for tokens currently using `bump_with`, the
1077 // prev_token_kind will be of no use anyway.
1078 self.prev_token_kind = PrevTokenKind::Other;
1081 self.expected_tokens.clear();
1084 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1085 F: FnOnce(&token::Token) -> R,
1088 return f(&self.token)
1091 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1092 Some(tree) => match tree {
1093 TokenTree::Token(_, tok) => tok,
1094 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1096 None => token::CloseDelim(self.token_cursor.frame.delim),
1099 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1100 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1102 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1103 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1105 pub fn span_fatal_err(&self, sp: Span, err: Error) -> DiagnosticBuilder<'a> {
1106 err.span_err(sp, self.diagnostic())
1108 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1109 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1113 pub fn bug(&self, m: &str) -> ! {
1114 self.sess.span_diagnostic.span_bug(self.span, m)
1116 pub fn warn(&self, m: &str) {
1117 self.sess.span_diagnostic.span_warn(self.span, m)
1119 pub fn span_warn(&self, sp: Span, m: &str) {
1120 self.sess.span_diagnostic.span_warn(sp, m)
1122 pub fn span_err(&self, sp: Span, m: &str) {
1123 self.sess.span_diagnostic.span_err(sp, m)
1125 pub fn span_err_help(&self, sp: Span, m: &str, h: &str) {
1126 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1130 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1131 self.sess.span_diagnostic.span_bug(sp, m)
1133 pub fn abort_if_errors(&self) {
1134 self.sess.span_diagnostic.abort_if_errors();
1137 fn cancel(&self, err: &mut DiagnosticBuilder) {
1138 self.sess.span_diagnostic.cancel(err)
1141 pub fn diagnostic(&self) -> &'a errors::Handler {
1142 &self.sess.span_diagnostic
1145 /// Is the current token one of the keywords that signals a bare function
1147 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1148 self.check_keyword(keywords::Fn) ||
1149 self.check_keyword(keywords::Unsafe) ||
1150 self.check_keyword(keywords::Extern)
1153 fn get_label(&mut self) -> ast::Ident {
1155 token::Lifetime(ref ident) => *ident,
1156 _ => self.bug("not a lifetime"),
1160 /// parse a TyKind::BareFn type:
1161 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<LifetimeDef>)
1162 -> PResult<'a, TyKind> {
1165 [unsafe] [extern "ABI"] fn (S) -> T
1175 let unsafety = self.parse_unsafety()?;
1176 let abi = if self.eat_keyword(keywords::Extern) {
1177 self.parse_opt_abi()?.unwrap_or(Abi::C)
1182 self.expect_keyword(keywords::Fn)?;
1183 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1184 let ret_ty = self.parse_ret_ty()?;
1185 let decl = P(FnDecl {
1190 Ok(TyKind::BareFn(P(BareFnTy {
1193 lifetimes: lifetime_defs,
1198 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1199 if self.eat_keyword(keywords::Unsafe) {
1200 return Ok(Unsafety::Unsafe);
1202 return Ok(Unsafety::Normal);
1206 /// Parse the items in a trait declaration
1207 pub fn parse_trait_item(&mut self) -> PResult<'a, TraitItem> {
1208 maybe_whole!(self, NtTraitItem, |x| x);
1209 let mut attrs = self.parse_outer_attributes()?;
1212 let (name, node) = if self.eat_keyword(keywords::Type) {
1213 let TyParam {ident, bounds, default, ..} = self.parse_ty_param(vec![])?;
1214 self.expect(&token::Semi)?;
1215 (ident, TraitItemKind::Type(bounds, default))
1216 } else if self.is_const_item() {
1217 self.expect_keyword(keywords::Const)?;
1218 let ident = self.parse_ident()?;
1219 self.expect(&token::Colon)?;
1220 let ty = self.parse_ty()?;
1221 let default = if self.check(&token::Eq) {
1223 let expr = self.parse_expr()?;
1224 self.expect(&token::Semi)?;
1227 self.expect(&token::Semi)?;
1230 (ident, TraitItemKind::Const(ty, default))
1231 } else if self.token.is_path_start() {
1232 // trait item macro.
1233 // code copied from parse_macro_use_or_failure... abstraction!
1235 let pth = self.parse_path(PathStyle::Mod)?;
1236 self.expect(&token::Not)?;
1238 // eat a matched-delimiter token tree:
1239 let (delim, tts) = self.expect_delimited_token_tree()?;
1240 if delim != token::Brace {
1241 self.expect(&token::Semi)?
1244 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
1245 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac))
1247 let (constness, unsafety, abi) = match self.parse_fn_front_matter() {
1252 token::Eof => break,
1253 token::CloseDelim(token::Brace) |
1258 token::OpenDelim(token::Brace) => {
1259 self.parse_token_tree();
1270 let ident = self.parse_ident()?;
1271 let mut generics = self.parse_generics()?;
1273 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1274 // This is somewhat dubious; We don't want to allow
1275 // argument names to be left off if there is a
1277 p.parse_arg_general(false)
1280 generics.where_clause = self.parse_where_clause()?;
1281 let sig = ast::MethodSig {
1283 constness: constness,
1289 let body = match self.token {
1292 debug!("parse_trait_methods(): parsing required method");
1295 token::OpenDelim(token::Brace) => {
1296 debug!("parse_trait_methods(): parsing provided method");
1297 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1298 attrs.extend(inner_attrs.iter().cloned());
1302 let token_str = self.this_token_to_string();
1303 return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str)));
1306 (ident, ast::TraitItemKind::Method(sig, body))
1310 id: ast::DUMMY_NODE_ID,
1314 span: lo.to(self.prev_span),
1319 /// Parse the items in a trait declaration
1320 pub fn parse_trait_items(&mut self) -> PResult<'a, Vec<TraitItem>> {
1321 self.parse_unspanned_seq(
1322 &token::OpenDelim(token::Brace),
1323 &token::CloseDelim(token::Brace),
1325 |p| -> PResult<'a, TraitItem> {
1326 p.parse_trait_item()
1330 /// Parse optional return type [ -> TY ] in function decl
1331 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1332 if self.eat(&token::RArrow) {
1333 Ok(FunctionRetTy::Ty(self.parse_ty_no_plus()?))
1335 Ok(FunctionRetTy::Default(Span { hi: self.span.lo, ..self.span }))
1340 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1341 self.parse_ty_common(true)
1344 /// Parse a type in restricted contexts where `+` is not permitted.
1345 /// Example 1: `&'a TYPE`
1346 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1347 /// Example 2: `value1 as TYPE + value2`
1348 /// `+` is prohibited to avoid interactions with expression grammar.
1349 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1350 self.parse_ty_common(false)
1353 fn parse_ty_common(&mut self, allow_plus: bool) -> PResult<'a, P<Ty>> {
1354 maybe_whole!(self, NtTy, |x| x);
1357 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1358 // `(TYPE)` is a parenthesized type.
1359 // `(TYPE,)` is a tuple with a single field of type TYPE.
1360 let mut ts = vec![];
1361 let mut last_comma = false;
1362 while self.token != token::CloseDelim(token::Paren) {
1363 ts.push(self.parse_ty()?);
1364 if self.eat(&token::Comma) {
1371 self.expect(&token::CloseDelim(token::Paren))?;
1373 if ts.len() == 1 && !last_comma {
1374 let ty = ts.into_iter().nth(0).unwrap().unwrap();
1376 // Accept `(Trait1) + Trait2 + 'a` for backward compatibility (#39318).
1377 TyKind::Path(None, ref path)
1378 if allow_plus && self.token == token::BinOp(token::Plus) => {
1380 let pt = PolyTraitRef::new(Vec::new(), path.clone(), lo.to(self.prev_span));
1381 let mut bounds = vec![TraitTyParamBound(pt, TraitBoundModifier::None)];
1382 bounds.append(&mut self.parse_ty_param_bounds()?);
1383 TyKind::TraitObject(bounds)
1385 _ => TyKind::Paren(P(ty))
1390 } else if self.eat(&token::Not) {
1393 } else if self.eat(&token::BinOp(token::Star)) {
1395 TyKind::Ptr(self.parse_ptr()?)
1396 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1398 let t = self.parse_ty()?;
1399 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1400 let t = match self.maybe_parse_fixed_length_of_vec()? {
1401 None => TyKind::Slice(t),
1402 Some(suffix) => TyKind::Array(t, suffix),
1404 self.expect(&token::CloseDelim(token::Bracket))?;
1406 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1409 self.parse_borrowed_pointee()?
1410 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1412 // In order to not be ambiguous, the type must be surrounded by parens.
1413 self.expect(&token::OpenDelim(token::Paren))?;
1414 let e = self.parse_expr()?;
1415 self.expect(&token::CloseDelim(token::Paren))?;
1417 } else if self.eat(&token::Underscore) {
1418 // A type to be inferred `_`
1420 } else if self.eat_lt() {
1422 let (qself, path) = self.parse_qualified_path(PathStyle::Type)?;
1423 TyKind::Path(Some(qself), path)
1424 } else if self.token.is_path_start() {
1426 let path = self.parse_path(PathStyle::Type)?;
1427 if self.eat(&token::Not) {
1428 // Macro invocation in type position
1429 let (_, tts) = self.expect_delimited_token_tree()?;
1430 TyKind::Mac(respan(lo.to(self.span), Mac_ { path: path, tts: tts }))
1432 // Just a type path or bound list (trait object type) starting with a trait.
1434 // `Trait1 + Trait2 + 'a`
1435 if allow_plus && self.eat(&token::BinOp(token::Plus)) {
1436 let poly_trait = PolyTraitRef::new(Vec::new(), path, lo.to(self.prev_span));
1437 let mut bounds = vec![TraitTyParamBound(poly_trait, TraitBoundModifier::None)];
1438 bounds.append(&mut self.parse_ty_param_bounds()?);
1439 TyKind::TraitObject(bounds)
1441 TyKind::Path(None, path)
1444 } else if self.token_is_bare_fn_keyword() {
1445 // Function pointer type
1446 self.parse_ty_bare_fn(Vec::new())?
1447 } else if self.check_keyword(keywords::For) {
1448 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1449 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1450 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1452 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1453 if self.token_is_bare_fn_keyword() {
1454 self.parse_ty_bare_fn(lifetime_defs)?
1456 let path = self.parse_path(PathStyle::Type)?;
1457 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
1458 let mut bounds = vec![TraitTyParamBound(poly_trait, TraitBoundModifier::None)];
1459 if allow_plus && self.eat(&token::BinOp(token::Plus)) {
1460 bounds.append(&mut self.parse_ty_param_bounds()?)
1462 TyKind::TraitObject(bounds)
1464 } else if self.eat_keyword(keywords::Impl) {
1465 // FIXME: figure out priority of `+` in `impl Trait1 + Trait2` (#34511).
1466 TyKind::ImplTrait(self.parse_ty_param_bounds()?)
1467 } else if self.check(&token::Question) {
1468 // Bound list (trait object type)
1469 // Bound lists starting with `'lt` are not currently supported (#40043)
1470 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?)
1472 let msg = format!("expected type, found {}", self.this_token_descr());
1473 return Err(self.fatal(&msg));
1476 let span = lo.to(self.prev_span);
1477 let ty = Ty { node: node, span: span, id: ast::DUMMY_NODE_ID };
1479 // Try to recover from use of `+` with incorrect priority.
1480 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1485 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1486 // Do not add `+` to expected tokens.
1487 if !allow_plus || self.token != token::BinOp(token::Plus) {
1492 let bounds = self.parse_ty_param_bounds()?;
1493 let sum_span = ty.span.to(self.prev_span);
1495 let mut err = struct_span_err!(self.sess.span_diagnostic, ty.span, E0178,
1496 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(&ty));
1497 err.span_label(ty.span, &format!("expected a path"));
1500 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1501 let sum_with_parens = pprust::to_string(|s| {
1502 use print::pp::word;
1503 use print::pprust::PrintState;
1505 word(&mut s.s, "&")?;
1506 s.print_opt_lifetime(lifetime)?;
1507 s.print_mutability(mut_ty.mutbl)?;
1509 s.print_type(&mut_ty.ty)?;
1510 s.print_bounds(" +", &bounds)?;
1513 err.span_suggestion(sum_span, "try adding parentheses:", sum_with_parens);
1515 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1516 help!(&mut err, "perhaps you forgot parentheses?");
1524 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1525 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1526 let mutbl = self.parse_mutability();
1527 let ty = self.parse_ty_no_plus()?;
1528 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1531 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1532 let mutbl = if self.eat_keyword(keywords::Mut) {
1534 } else if self.eat_keyword(keywords::Const) {
1535 Mutability::Immutable
1537 let span = self.prev_span;
1539 "expected mut or const in raw pointer type (use \
1540 `*mut T` or `*const T` as appropriate)");
1541 Mutability::Immutable
1543 let t = self.parse_ty_no_plus()?;
1544 Ok(MutTy { ty: t, mutbl: mutbl })
1547 pub fn is_named_argument(&mut self) -> bool {
1548 let offset = match self.token {
1549 token::BinOp(token::And) => 1,
1551 _ if self.token.is_keyword(keywords::Mut) => 1,
1555 debug!("parser is_named_argument offset:{}", offset);
1558 is_ident_or_underscore(&self.token)
1559 && self.look_ahead(1, |t| *t == token::Colon)
1561 self.look_ahead(offset, |t| is_ident_or_underscore(t))
1562 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1566 /// This version of parse arg doesn't necessarily require
1567 /// identifier names.
1568 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1569 maybe_whole!(self, NtArg, |x| x);
1571 let pat = if require_name || self.is_named_argument() {
1572 debug!("parse_arg_general parse_pat (require_name:{})",
1574 let pat = self.parse_pat()?;
1576 self.expect(&token::Colon)?;
1579 debug!("parse_arg_general ident_to_pat");
1580 let sp = self.prev_span;
1581 let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1583 id: ast::DUMMY_NODE_ID,
1584 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1590 let t = self.parse_ty()?;
1595 id: ast::DUMMY_NODE_ID,
1599 /// Parse a single function argument
1600 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1601 self.parse_arg_general(true)
1604 /// Parse an argument in a lambda header e.g. |arg, arg|
1605 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1606 let pat = self.parse_pat()?;
1607 let t = if self.eat(&token::Colon) {
1611 id: ast::DUMMY_NODE_ID,
1612 node: TyKind::Infer,
1619 id: ast::DUMMY_NODE_ID
1623 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1624 if self.eat(&token::Semi) {
1625 Ok(Some(self.parse_expr()?))
1631 /// Matches token_lit = LIT_INTEGER | ...
1632 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1633 let out = match self.token {
1634 token::Interpolated(ref nt) => match **nt {
1635 token::NtExpr(ref v) => match v.node {
1636 ExprKind::Lit(ref lit) => { lit.node.clone() }
1637 _ => { return self.unexpected_last(&self.token); }
1639 _ => { return self.unexpected_last(&self.token); }
1641 token::Literal(lit, suf) => {
1642 let diag = Some((self.span, &self.sess.span_diagnostic));
1643 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1647 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1652 _ => { return self.unexpected_last(&self.token); }
1659 /// Matches lit = true | false | token_lit
1660 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1662 let lit = if self.eat_keyword(keywords::True) {
1664 } else if self.eat_keyword(keywords::False) {
1665 LitKind::Bool(false)
1667 let lit = self.parse_lit_token()?;
1670 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1673 /// matches '-' lit | lit
1674 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1675 let minus_lo = self.span;
1676 let minus_present = self.eat(&token::BinOp(token::Minus));
1678 let literal = P(self.parse_lit()?);
1679 let hi = self.prev_span;
1680 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1683 let minus_hi = self.prev_span;
1684 let unary = self.mk_unary(UnOp::Neg, expr);
1685 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1691 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1693 token::Ident(sid) if self.token.is_path_segment_keyword() => {
1697 _ => self.parse_ident(),
1701 /// Parses qualified path.
1703 /// Assumes that the leading `<` has been parsed already.
1705 /// Qualifed paths are a part of the universal function call
1708 /// `qualified_path = <type [as trait_ref]>::path`
1710 /// See `parse_path` for `mode` meaning.
1715 /// `<T as U>::F::a::<S>`
1716 pub fn parse_qualified_path(&mut self, mode: PathStyle)
1717 -> PResult<'a, (QSelf, ast::Path)> {
1718 let span = self.prev_span;
1719 let self_type = self.parse_ty()?;
1720 let mut path = if self.eat_keyword(keywords::As) {
1721 self.parse_path(PathStyle::Type)?
1731 position: path.segments.len()
1734 self.expect(&token::Gt)?;
1735 self.expect(&token::ModSep)?;
1737 let segments = match mode {
1738 PathStyle::Type => {
1739 self.parse_path_segments_without_colons()?
1741 PathStyle::Expr => {
1742 self.parse_path_segments_with_colons()?
1745 self.parse_path_segments_without_types()?
1748 path.segments.extend(segments);
1750 path.span.hi = self.prev_span.hi;
1755 /// Parses a path and optional type parameter bounds, depending on the
1756 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1757 /// bounds are permitted and whether `::` must precede type parameter
1759 pub fn parse_path(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> {
1760 maybe_whole!(self, NtPath, |x| x);
1762 let lo = self.meta_var_span.unwrap_or(self.span);
1763 let is_global = self.eat(&token::ModSep);
1765 // Parse any number of segments and bound sets. A segment is an
1766 // identifier followed by an optional lifetime and a set of types.
1767 // A bound set is a set of type parameter bounds.
1768 let mut segments = match mode {
1769 PathStyle::Type => {
1770 self.parse_path_segments_without_colons()?
1772 PathStyle::Expr => {
1773 self.parse_path_segments_with_colons()?
1776 self.parse_path_segments_without_types()?
1781 segments.insert(0, PathSegment::crate_root());
1784 // Assemble the result.
1786 span: lo.to(self.prev_span),
1791 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1792 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1793 pub fn parse_path_allowing_meta(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> {
1794 let meta_ident = match self.token {
1795 token::Interpolated(ref nt) => match **nt {
1796 token::NtMeta(ref meta) => match meta.node {
1797 ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
1804 if let Some(ident) = meta_ident {
1806 return Ok(ast::Path::from_ident(self.prev_span, ident));
1808 self.parse_path(mode)
1812 /// - `a::b<T,U>::c<V,W>`
1813 /// - `a::b<T,U>::c(V) -> W`
1814 /// - `a::b<T,U>::c(V)`
1815 pub fn parse_path_segments_without_colons(&mut self) -> PResult<'a, Vec<PathSegment>> {
1816 let mut segments = Vec::new();
1818 // First, parse an identifier.
1819 let ident_span = self.span;
1820 let identifier = self.parse_path_segment_ident()?;
1822 if self.check(&token::ModSep) && self.look_ahead(1, |t| *t == token::Lt) {
1824 let prev_span = self.prev_span;
1826 let mut err = self.diagnostic().struct_span_err(prev_span,
1827 "unexpected token: `::`");
1829 "use `<...>` instead of `::<...>` if you meant to specify type arguments");
1833 // Parse types, optionally.
1834 let parameters = if self.eat_lt() {
1835 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1837 ast::AngleBracketedParameterData {
1838 lifetimes: lifetimes,
1842 } else if self.eat(&token::OpenDelim(token::Paren)) {
1843 let lo = self.prev_span;
1845 let inputs = self.parse_seq_to_end(
1846 &token::CloseDelim(token::Paren),
1847 SeqSep::trailing_allowed(token::Comma),
1850 let output_ty = if self.eat(&token::RArrow) {
1851 Some(self.parse_ty_no_plus()?)
1856 let hi = self.prev_span;
1858 Some(P(ast::PathParameters::Parenthesized(ast::ParenthesizedParameterData {
1867 // Assemble and push the result.
1868 segments.push(PathSegment {
1869 identifier: identifier,
1871 parameters: parameters
1874 // Continue only if we see a `::`
1875 if !self.eat(&token::ModSep) {
1876 return Ok(segments);
1882 /// - `a::b::<T,U>::c`
1883 pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec<PathSegment>> {
1884 let mut segments = Vec::new();
1886 // First, parse an identifier.
1887 let ident_span = self.span;
1888 let identifier = self.parse_path_segment_ident()?;
1890 // If we do not see a `::`, stop.
1891 if !self.eat(&token::ModSep) {
1892 segments.push(PathSegment::from_ident(identifier, ident_span));
1893 return Ok(segments);
1896 // Check for a type segment.
1898 // Consumed `a::b::<`, go look for types
1899 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1901 segments.push(PathSegment {
1902 identifier: identifier,
1904 parameters: ast::AngleBracketedParameterData {
1905 lifetimes: lifetimes,
1911 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1912 if !self.eat(&token::ModSep) {
1913 return Ok(segments);
1916 // Consumed `a::`, go look for `b`
1917 segments.push(PathSegment::from_ident(identifier, ident_span));
1924 pub fn parse_path_segments_without_types(&mut self)
1925 -> PResult<'a, Vec<PathSegment>> {
1926 let mut segments = Vec::new();
1928 // First, parse an identifier.
1929 let ident_span = self.span;
1930 let identifier = self.parse_path_segment_ident()?;
1932 // Assemble and push the result.
1933 segments.push(PathSegment::from_ident(identifier, ident_span));
1935 // If we do not see a `::` or see `::{`/`::*`, stop.
1936 if !self.check(&token::ModSep) || self.is_import_coupler() {
1937 return Ok(segments);
1944 fn check_lifetime(&mut self) -> bool {
1945 self.expected_tokens.push(TokenType::Lifetime);
1946 self.token.is_lifetime()
1949 /// Parse single lifetime 'a or panic.
1950 fn expect_lifetime(&mut self) -> Lifetime {
1952 token::Lifetime(ident) => {
1953 let ident_span = self.span;
1955 Lifetime { name: ident.name, span: ident_span, id: ast::DUMMY_NODE_ID }
1957 _ => self.span_bug(self.span, "not a lifetime")
1961 /// Parse mutability (`mut` or nothing).
1962 fn parse_mutability(&mut self) -> Mutability {
1963 if self.eat_keyword(keywords::Mut) {
1966 Mutability::Immutable
1970 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1971 if let token::Literal(token::Integer(name), None) = self.token {
1973 Ok(Ident::with_empty_ctxt(name))
1979 /// Parse ident (COLON expr)?
1980 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1981 let attrs = self.parse_outer_attributes()?;
1985 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1986 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1987 let fieldname = self.parse_field_name()?;
1989 hi = self.prev_span;
1990 (fieldname, self.parse_expr()?, false)
1992 let fieldname = self.parse_ident()?;
1993 hi = self.prev_span;
1995 // Mimic `x: x` for the `x` field shorthand.
1996 let path = ast::Path::from_ident(lo.to(hi), fieldname);
1997 (fieldname, self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()), true)
2000 ident: respan(lo.to(hi), fieldname),
2001 span: lo.to(expr.span),
2003 is_shorthand: is_shorthand,
2004 attrs: attrs.into(),
2008 pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2010 id: ast::DUMMY_NODE_ID,
2013 attrs: attrs.into(),
2017 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2018 ExprKind::Unary(unop, expr)
2021 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2022 ExprKind::Binary(binop, lhs, rhs)
2025 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2026 ExprKind::Call(f, args)
2029 fn mk_method_call(&mut self,
2030 ident: ast::SpannedIdent,
2034 ExprKind::MethodCall(ident, tps, args)
2037 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2038 ExprKind::Index(expr, idx)
2041 pub fn mk_range(&mut self,
2042 start: Option<P<Expr>>,
2043 end: Option<P<Expr>>,
2044 limits: RangeLimits)
2045 -> PResult<'a, ast::ExprKind> {
2046 if end.is_none() && limits == RangeLimits::Closed {
2047 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2049 Ok(ExprKind::Range(start, end, limits))
2053 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::ExprKind {
2054 ExprKind::Field(expr, ident)
2057 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2058 ExprKind::TupField(expr, idx)
2061 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2062 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2063 ExprKind::AssignOp(binop, lhs, rhs)
2066 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2068 id: ast::DUMMY_NODE_ID,
2069 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2075 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2076 let span = &self.span;
2077 let lv_lit = P(codemap::Spanned {
2078 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2083 id: ast::DUMMY_NODE_ID,
2084 node: ExprKind::Lit(lv_lit),
2090 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2092 token::OpenDelim(delim) => match self.parse_token_tree() {
2093 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2094 _ => unreachable!(),
2096 _ => Err(self.fatal("expected open delimiter")),
2100 /// At the bottom (top?) of the precedence hierarchy,
2101 /// parse things like parenthesized exprs,
2102 /// macros, return, etc.
2104 /// NB: This does not parse outer attributes,
2105 /// and is private because it only works
2106 /// correctly if called from parse_dot_or_call_expr().
2107 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2108 maybe_whole_expr!(self);
2110 // Outer attributes are already parsed and will be
2111 // added to the return value after the fact.
2113 // Therefore, prevent sub-parser from parsing
2114 // attributes by giving them a empty "already parsed" list.
2115 let mut attrs = ThinVec::new();
2118 let mut hi = self.span;
2122 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2124 token::OpenDelim(token::Paren) => {
2127 attrs.extend(self.parse_inner_attributes()?);
2129 // (e) is parenthesized e
2130 // (e,) is a tuple with only one field, e
2131 let mut es = vec![];
2132 let mut trailing_comma = false;
2133 while self.token != token::CloseDelim(token::Paren) {
2134 es.push(self.parse_expr()?);
2135 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2136 if self.check(&token::Comma) {
2137 trailing_comma = true;
2141 trailing_comma = false;
2147 hi = self.prev_span;
2148 let span = lo.to(hi);
2149 return if es.len() == 1 && !trailing_comma {
2150 Ok(self.mk_expr(span, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs))
2152 Ok(self.mk_expr(span, ExprKind::Tup(es), attrs))
2155 token::OpenDelim(token::Brace) => {
2156 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2158 token::BinOp(token::Or) | token::OrOr => {
2160 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2162 token::OpenDelim(token::Bracket) => {
2165 attrs.extend(self.parse_inner_attributes()?);
2167 if self.check(&token::CloseDelim(token::Bracket)) {
2170 ex = ExprKind::Array(Vec::new());
2173 let first_expr = self.parse_expr()?;
2174 if self.check(&token::Semi) {
2175 // Repeating array syntax: [ 0; 512 ]
2177 let count = self.parse_expr()?;
2178 self.expect(&token::CloseDelim(token::Bracket))?;
2179 ex = ExprKind::Repeat(first_expr, count);
2180 } else if self.check(&token::Comma) {
2181 // Vector with two or more elements.
2183 let remaining_exprs = self.parse_seq_to_end(
2184 &token::CloseDelim(token::Bracket),
2185 SeqSep::trailing_allowed(token::Comma),
2186 |p| Ok(p.parse_expr()?)
2188 let mut exprs = vec![first_expr];
2189 exprs.extend(remaining_exprs);
2190 ex = ExprKind::Array(exprs);
2192 // Vector with one element.
2193 self.expect(&token::CloseDelim(token::Bracket))?;
2194 ex = ExprKind::Array(vec![first_expr]);
2197 hi = self.prev_span;
2202 self.parse_qualified_path(PathStyle::Expr)?;
2204 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2206 if self.eat_keyword(keywords::Move) {
2207 let lo = self.prev_span;
2208 return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2210 if self.eat_keyword(keywords::If) {
2211 return self.parse_if_expr(attrs);
2213 if self.eat_keyword(keywords::For) {
2214 let lo = self.prev_span;
2215 return self.parse_for_expr(None, lo, attrs);
2217 if self.eat_keyword(keywords::While) {
2218 let lo = self.prev_span;
2219 return self.parse_while_expr(None, lo, attrs);
2221 if self.token.is_lifetime() {
2222 let label = Spanned { node: self.get_label(),
2226 self.expect(&token::Colon)?;
2227 if self.eat_keyword(keywords::While) {
2228 return self.parse_while_expr(Some(label), lo, attrs)
2230 if self.eat_keyword(keywords::For) {
2231 return self.parse_for_expr(Some(label), lo, attrs)
2233 if self.eat_keyword(keywords::Loop) {
2234 return self.parse_loop_expr(Some(label), lo, attrs)
2236 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2238 if self.eat_keyword(keywords::Loop) {
2239 let lo = self.prev_span;
2240 return self.parse_loop_expr(None, lo, attrs);
2242 if self.eat_keyword(keywords::Continue) {
2243 let ex = if self.token.is_lifetime() {
2244 let ex = ExprKind::Continue(Some(Spanned{
2245 node: self.get_label(),
2251 ExprKind::Continue(None)
2253 let hi = self.prev_span;
2254 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2256 if self.eat_keyword(keywords::Match) {
2257 return self.parse_match_expr(attrs);
2259 if self.eat_keyword(keywords::Unsafe) {
2260 return self.parse_block_expr(
2262 BlockCheckMode::Unsafe(ast::UserProvided),
2265 if self.is_catch_expr() {
2266 assert!(self.eat_keyword(keywords::Do));
2267 assert!(self.eat_keyword(keywords::Catch));
2268 let lo = self.prev_span;
2269 return self.parse_catch_expr(lo, attrs);
2271 if self.eat_keyword(keywords::Return) {
2272 if self.token.can_begin_expr() {
2273 let e = self.parse_expr()?;
2275 ex = ExprKind::Ret(Some(e));
2277 ex = ExprKind::Ret(None);
2279 } else if self.eat_keyword(keywords::Break) {
2280 let lt = if self.token.is_lifetime() {
2281 let spanned_lt = Spanned {
2282 node: self.get_label(),
2290 let e = if self.token.can_begin_expr()
2291 && !(self.token == token::OpenDelim(token::Brace)
2292 && self.restrictions.contains(
2293 Restrictions::RESTRICTION_NO_STRUCT_LITERAL)) {
2294 Some(self.parse_expr()?)
2298 ex = ExprKind::Break(lt, e);
2299 hi = self.prev_span;
2300 } else if self.token.is_keyword(keywords::Let) {
2301 // Catch this syntax error here, instead of in `check_strict_keywords`, so
2302 // that we can explicitly mention that let is not to be used as an expression
2303 let mut db = self.fatal("expected expression, found statement (`let`)");
2304 db.note("variable declaration using `let` is a statement");
2306 } else if self.token.is_path_start() {
2307 let pth = self.parse_path(PathStyle::Expr)?;
2309 // `!`, as an operator, is prefix, so we know this isn't that
2310 if self.eat(&token::Not) {
2311 // MACRO INVOCATION expression
2312 let (_, tts) = self.expect_delimited_token_tree()?;
2313 let hi = self.prev_span;
2314 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2316 if self.check(&token::OpenDelim(token::Brace)) {
2317 // This is a struct literal, unless we're prohibited
2318 // from parsing struct literals here.
2319 let prohibited = self.restrictions.contains(
2320 Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2323 return self.parse_struct_expr(lo, pth, attrs);
2328 ex = ExprKind::Path(None, pth);
2330 match self.parse_lit() {
2333 ex = ExprKind::Lit(P(lit));
2336 self.cancel(&mut err);
2337 let msg = format!("expected expression, found {}",
2338 self.this_token_descr());
2339 return Err(self.fatal(&msg));
2346 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2349 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2350 -> PResult<'a, P<Expr>> {
2352 let mut fields = Vec::new();
2353 let mut base = None;
2355 attrs.extend(self.parse_inner_attributes()?);
2357 while self.token != token::CloseDelim(token::Brace) {
2358 if self.eat(&token::DotDot) {
2359 match self.parse_expr() {
2365 self.recover_stmt();
2371 match self.parse_field() {
2372 Ok(f) => fields.push(f),
2375 self.recover_stmt();
2380 match self.expect_one_of(&[token::Comma],
2381 &[token::CloseDelim(token::Brace)]) {
2385 self.recover_stmt();
2391 let span = lo.to(self.span);
2392 self.expect(&token::CloseDelim(token::Brace))?;
2393 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2396 fn parse_or_use_outer_attributes(&mut self,
2397 already_parsed_attrs: Option<ThinVec<Attribute>>)
2398 -> PResult<'a, ThinVec<Attribute>> {
2399 if let Some(attrs) = already_parsed_attrs {
2402 self.parse_outer_attributes().map(|a| a.into())
2406 /// Parse a block or unsafe block
2407 pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2408 outer_attrs: ThinVec<Attribute>)
2409 -> PResult<'a, P<Expr>> {
2411 self.expect(&token::OpenDelim(token::Brace))?;
2413 let mut attrs = outer_attrs;
2414 attrs.extend(self.parse_inner_attributes()?);
2416 let blk = self.parse_block_tail(lo, blk_mode)?;
2417 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2420 /// parse a.b or a(13) or a[4] or just a
2421 pub fn parse_dot_or_call_expr(&mut self,
2422 already_parsed_attrs: Option<ThinVec<Attribute>>)
2423 -> PResult<'a, P<Expr>> {
2424 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2426 let b = self.parse_bottom_expr();
2427 let (span, b) = self.interpolated_or_expr_span(b)?;
2428 self.parse_dot_or_call_expr_with(b, span, attrs)
2431 pub fn parse_dot_or_call_expr_with(&mut self,
2434 mut attrs: ThinVec<Attribute>)
2435 -> PResult<'a, P<Expr>> {
2436 // Stitch the list of outer attributes onto the return value.
2437 // A little bit ugly, but the best way given the current code
2439 self.parse_dot_or_call_expr_with_(e0, lo)
2441 expr.map(|mut expr| {
2442 attrs.extend::<Vec<_>>(expr.attrs.into());
2445 ExprKind::If(..) | ExprKind::IfLet(..) => {
2446 if !expr.attrs.is_empty() {
2447 // Just point to the first attribute in there...
2448 let span = expr.attrs[0].span;
2451 "attributes are not yet allowed on `if` \
2462 // Assuming we have just parsed `.foo` (i.e., a dot and an ident), continue
2463 // parsing into an expression.
2464 fn parse_dot_suffix(&mut self, ident: Ident, ident_span: Span, self_value: P<Expr>, lo: Span)
2465 -> PResult<'a, P<Expr>> {
2466 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2468 let args = self.parse_generic_args()?;
2472 (Vec::new(), Vec::new(), Vec::new())
2475 if !bindings.is_empty() {
2476 let prev_span = self.prev_span;
2477 self.span_err(prev_span, "type bindings are only permitted on trait paths");
2480 Ok(match self.token {
2481 // expr.f() method call.
2482 token::OpenDelim(token::Paren) => {
2483 let mut es = self.parse_unspanned_seq(
2484 &token::OpenDelim(token::Paren),
2485 &token::CloseDelim(token::Paren),
2486 SeqSep::trailing_allowed(token::Comma),
2487 |p| Ok(p.parse_expr()?)
2489 let hi = self.prev_span;
2491 es.insert(0, self_value);
2492 let id = respan(ident_span.to(ident_span), ident);
2493 let nd = self.mk_method_call(id, tys, es);
2494 self.mk_expr(lo.to(hi), nd, ThinVec::new())
2498 if !tys.is_empty() {
2499 let prev_span = self.prev_span;
2500 self.span_err(prev_span,
2501 "field expressions may not \
2502 have type parameters");
2505 let id = respan(ident_span.to(ident_span), ident);
2506 let field = self.mk_field(self_value, id);
2507 self.mk_expr(lo.to(ident_span), field, ThinVec::new())
2512 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2517 while self.eat(&token::Question) {
2518 let hi = self.prev_span;
2519 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2523 if self.eat(&token::Dot) {
2525 token::Ident(i) => {
2526 let ident_span = self.span;
2528 e = self.parse_dot_suffix(i, ident_span, e, lo)?;
2530 token::Literal(token::Integer(n), suf) => {
2533 // A tuple index may not have a suffix
2534 self.expect_no_suffix(sp, "tuple index", suf);
2536 let dot_span = self.prev_span;
2540 let index = n.as_str().parse::<usize>().ok();
2543 let id = respan(dot_span.to(hi), n);
2544 let field = self.mk_tup_field(e, id);
2545 e = self.mk_expr(lo.to(hi), field, ThinVec::new());
2548 let prev_span = self.prev_span;
2549 self.span_err(prev_span, "invalid tuple or tuple struct index");
2553 token::Literal(token::Float(n), _suf) => {
2555 let fstr = n.as_str();
2556 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2557 &format!("unexpected token: `{}`", n));
2558 err.span_label(self.prev_span, &"unexpected token");
2559 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2560 let float = match fstr.parse::<f64>().ok() {
2564 let sugg = pprust::to_string(|s| {
2565 use print::pprust::PrintState;
2566 use print::pp::word;
2569 word(&mut s.s, ".")?;
2570 s.print_usize(float.trunc() as usize)?;
2572 word(&mut s.s, ".")?;
2573 word(&mut s.s, fstr.splitn(2, ".").last().unwrap())
2575 err.span_suggestion(
2576 lo.to(self.prev_span),
2577 "try parenthesizing the first index",
2584 // FIXME Could factor this out into non_fatal_unexpected or something.
2585 let actual = self.this_token_to_string();
2586 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2588 let dot_span = self.prev_span;
2589 e = self.parse_dot_suffix(keywords::Invalid.ident(), dot_span, e, lo)?;
2594 if self.expr_is_complete(&e) { break; }
2597 token::OpenDelim(token::Paren) => {
2598 let es = self.parse_unspanned_seq(
2599 &token::OpenDelim(token::Paren),
2600 &token::CloseDelim(token::Paren),
2601 SeqSep::trailing_allowed(token::Comma),
2602 |p| Ok(p.parse_expr()?)
2604 hi = self.prev_span;
2606 let nd = self.mk_call(e, es);
2607 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2611 // Could be either an index expression or a slicing expression.
2612 token::OpenDelim(token::Bracket) => {
2614 let ix = self.parse_expr()?;
2616 self.expect(&token::CloseDelim(token::Bracket))?;
2617 let index = self.mk_index(e, ix);
2618 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2626 pub fn process_potential_macro_variable(&mut self) {
2627 let ident = match self.token {
2628 token::SubstNt(name) => {
2629 self.fatal(&format!("unknown macro variable `{}`", name)).emit();
2632 token::Interpolated(ref nt) => {
2633 self.meta_var_span = Some(self.span);
2635 token::NtIdent(ident) => ident,
2641 self.token = token::Ident(ident.node);
2642 self.span = ident.span;
2645 /// parse a single token tree from the input.
2646 pub fn parse_token_tree(&mut self) -> TokenTree {
2648 token::OpenDelim(..) => {
2649 let frame = mem::replace(&mut self.token_cursor.frame,
2650 self.token_cursor.stack.pop().unwrap());
2651 self.span = frame.span;
2653 TokenTree::Delimited(frame.span, Delimited {
2655 tts: frame.tree_cursor.original_stream().into(),
2658 token::CloseDelim(_) | token::Eof => unreachable!(),
2660 let (token, span) = (mem::replace(&mut self.token, token::Underscore), self.span);
2662 TokenTree::Token(span, token)
2667 // parse a stream of tokens into a list of TokenTree's,
2669 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2670 let mut tts = Vec::new();
2671 while self.token != token::Eof {
2672 tts.push(self.parse_token_tree());
2677 pub fn parse_tokens(&mut self) -> TokenStream {
2678 let mut result = Vec::new();
2681 token::Eof | token::CloseDelim(..) => break,
2682 _ => result.push(self.parse_token_tree().into()),
2685 TokenStream::concat(result)
2688 /// Parse a prefix-unary-operator expr
2689 pub fn parse_prefix_expr(&mut self,
2690 already_parsed_attrs: Option<ThinVec<Attribute>>)
2691 -> PResult<'a, P<Expr>> {
2692 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2694 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2695 let (hi, ex) = match self.token {
2698 let e = self.parse_prefix_expr(None);
2699 let (span, e) = self.interpolated_or_expr_span(e)?;
2700 (span, self.mk_unary(UnOp::Not, e))
2702 token::BinOp(token::Minus) => {
2704 let e = self.parse_prefix_expr(None);
2705 let (span, e) = self.interpolated_or_expr_span(e)?;
2706 (span, self.mk_unary(UnOp::Neg, e))
2708 token::BinOp(token::Star) => {
2710 let e = self.parse_prefix_expr(None);
2711 let (span, e) = self.interpolated_or_expr_span(e)?;
2712 (span, self.mk_unary(UnOp::Deref, e))
2714 token::BinOp(token::And) | token::AndAnd => {
2716 let m = self.parse_mutability();
2717 let e = self.parse_prefix_expr(None);
2718 let (span, e) = self.interpolated_or_expr_span(e)?;
2719 (span, ExprKind::AddrOf(m, e))
2721 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2723 let place = self.parse_expr_res(
2724 Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
2727 let blk = self.parse_block()?;
2728 let span = blk.span;
2729 let blk_expr = self.mk_expr(span, ExprKind::Block(blk), ThinVec::new());
2730 (span, ExprKind::InPlace(place, blk_expr))
2732 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2734 let e = self.parse_prefix_expr(None);
2735 let (span, e) = self.interpolated_or_expr_span(e)?;
2736 (span, ExprKind::Box(e))
2738 _ => return self.parse_dot_or_call_expr(Some(attrs))
2740 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2743 /// Parse an associative expression
2745 /// This parses an expression accounting for associativity and precedence of the operators in
2747 pub fn parse_assoc_expr(&mut self,
2748 already_parsed_attrs: Option<ThinVec<Attribute>>)
2749 -> PResult<'a, P<Expr>> {
2750 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2753 /// Parse an associative expression with operators of at least `min_prec` precedence
2754 pub fn parse_assoc_expr_with(&mut self,
2757 -> PResult<'a, P<Expr>> {
2758 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2761 let attrs = match lhs {
2762 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2765 if self.token == token::DotDot || self.token == token::DotDotDot {
2766 return self.parse_prefix_range_expr(attrs);
2768 self.parse_prefix_expr(attrs)?
2772 if self.expr_is_complete(&lhs) {
2773 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2776 self.expected_tokens.push(TokenType::Operator);
2777 while let Some(op) = AssocOp::from_token(&self.token) {
2779 let lhs_span = if self.prev_token_kind == PrevTokenKind::Interpolated {
2785 let cur_op_span = self.span;
2786 let restrictions = if op.is_assign_like() {
2787 self.restrictions & Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2791 if op.precedence() < min_prec {
2795 if op.is_comparison() {
2796 self.check_no_chained_comparison(&lhs, &op);
2799 if op == AssocOp::As {
2800 let rhs = self.parse_ty_no_plus()?;
2801 lhs = self.mk_expr(lhs_span.to(rhs.span), ExprKind::Cast(lhs, rhs), ThinVec::new());
2803 } else if op == AssocOp::Colon {
2804 let rhs = self.parse_ty_no_plus()?;
2805 lhs = self.mk_expr(lhs_span.to(rhs.span), ExprKind::Type(lhs, rhs), ThinVec::new());
2807 } else if op == AssocOp::DotDot || op == AssocOp::DotDotDot {
2808 // If we didn’t have to handle `x..`/`x...`, it would be pretty easy to
2809 // generalise it to the Fixity::None code.
2811 // We have 2 alternatives here: `x..y`/`x...y` and `x..`/`x...` The other
2812 // two variants are handled with `parse_prefix_range_expr` call above.
2813 let rhs = if self.is_at_start_of_range_notation_rhs() {
2814 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2815 LhsExpr::NotYetParsed)?)
2819 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2824 let limits = if op == AssocOp::DotDot {
2825 RangeLimits::HalfOpen
2830 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2831 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2835 let rhs = match op.fixity() {
2836 Fixity::Right => self.with_res(
2837 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2839 this.parse_assoc_expr_with(op.precedence(),
2840 LhsExpr::NotYetParsed)
2842 Fixity::Left => self.with_res(
2843 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2845 this.parse_assoc_expr_with(op.precedence() + 1,
2846 LhsExpr::NotYetParsed)
2848 // We currently have no non-associative operators that are not handled above by
2849 // the special cases. The code is here only for future convenience.
2850 Fixity::None => self.with_res(
2851 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2853 this.parse_assoc_expr_with(op.precedence() + 1,
2854 LhsExpr::NotYetParsed)
2858 let span = lhs_span.to(rhs.span);
2860 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2861 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2862 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2863 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2864 AssocOp::Greater | AssocOp::GreaterEqual => {
2865 let ast_op = op.to_ast_binop().unwrap();
2866 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2867 self.mk_expr(span, binary, ThinVec::new())
2870 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2872 self.mk_expr(span, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
2873 AssocOp::AssignOp(k) => {
2875 token::Plus => BinOpKind::Add,
2876 token::Minus => BinOpKind::Sub,
2877 token::Star => BinOpKind::Mul,
2878 token::Slash => BinOpKind::Div,
2879 token::Percent => BinOpKind::Rem,
2880 token::Caret => BinOpKind::BitXor,
2881 token::And => BinOpKind::BitAnd,
2882 token::Or => BinOpKind::BitOr,
2883 token::Shl => BinOpKind::Shl,
2884 token::Shr => BinOpKind::Shr,
2886 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2887 self.mk_expr(span, aopexpr, ThinVec::new())
2889 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotDot => {
2890 self.bug("As, Colon, DotDot or DotDotDot branch reached")
2894 if op.fixity() == Fixity::None { break }
2899 /// Produce an error if comparison operators are chained (RFC #558).
2900 /// We only need to check lhs, not rhs, because all comparison ops
2901 /// have same precedence and are left-associative
2902 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2903 debug_assert!(outer_op.is_comparison());
2905 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
2906 // respan to include both operators
2907 let op_span = op.span.to(self.span);
2908 let mut err = self.diagnostic().struct_span_err(op_span,
2909 "chained comparison operators require parentheses");
2910 if op.node == BinOpKind::Lt &&
2911 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
2912 *outer_op == AssocOp::Greater // even in a case like the following:
2913 { // Foo<Bar<Baz<Qux, ()>>>
2915 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2923 /// Parse prefix-forms of range notation: `..expr`, `..`, `...expr`
2924 fn parse_prefix_range_expr(&mut self,
2925 already_parsed_attrs: Option<ThinVec<Attribute>>)
2926 -> PResult<'a, P<Expr>> {
2927 debug_assert!(self.token == token::DotDot || self.token == token::DotDotDot);
2928 let tok = self.token.clone();
2929 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2931 let mut hi = self.span;
2933 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2934 // RHS must be parsed with more associativity than the dots.
2935 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
2936 Some(self.parse_assoc_expr_with(next_prec,
2937 LhsExpr::NotYetParsed)
2945 let limits = if tok == token::DotDot {
2946 RangeLimits::HalfOpen
2951 let r = try!(self.mk_range(None,
2954 Ok(self.mk_expr(lo.to(hi), r, attrs))
2957 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2958 if self.token.can_begin_expr() {
2959 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2960 if self.token == token::OpenDelim(token::Brace) {
2961 return !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL);
2969 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2970 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
2971 if self.check_keyword(keywords::Let) {
2972 return self.parse_if_let_expr(attrs);
2974 let lo = self.prev_span;
2975 let cond = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
2976 let thn = self.parse_block()?;
2977 let mut els: Option<P<Expr>> = None;
2978 let mut hi = thn.span;
2979 if self.eat_keyword(keywords::Else) {
2980 let elexpr = self.parse_else_expr()?;
2984 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
2987 /// Parse an 'if let' expression ('if' token already eaten)
2988 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
2989 -> PResult<'a, P<Expr>> {
2990 let lo = self.prev_span;
2991 self.expect_keyword(keywords::Let)?;
2992 let pat = self.parse_pat()?;
2993 self.expect(&token::Eq)?;
2994 let expr = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
2995 let thn = self.parse_block()?;
2996 let (hi, els) = if self.eat_keyword(keywords::Else) {
2997 let expr = self.parse_else_expr()?;
2998 (expr.span, Some(expr))
3002 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pat, expr, thn, els), attrs))
3005 // `move |args| expr`
3006 pub fn parse_lambda_expr(&mut self,
3008 capture_clause: CaptureBy,
3009 attrs: ThinVec<Attribute>)
3010 -> PResult<'a, P<Expr>>
3012 let decl = self.parse_fn_block_decl()?;
3013 let decl_hi = self.prev_span;
3014 let body = match decl.output {
3015 FunctionRetTy::Default(_) => self.parse_expr()?,
3017 // If an explicit return type is given, require a
3018 // block to appear (RFC 968).
3019 let body_lo = self.span;
3020 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3026 ExprKind::Closure(capture_clause, decl, body, lo.to(decl_hi)),
3030 // `else` token already eaten
3031 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3032 if self.eat_keyword(keywords::If) {
3033 return self.parse_if_expr(ThinVec::new());
3035 let blk = self.parse_block()?;
3036 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3040 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3041 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3043 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3044 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3046 let pat = self.parse_pat()?;
3047 self.expect_keyword(keywords::In)?;
3048 let expr = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
3049 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3050 attrs.extend(iattrs);
3052 let hi = self.prev_span;
3053 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_ident), attrs))
3056 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3057 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3059 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3060 if self.token.is_keyword(keywords::Let) {
3061 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3063 let cond = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
3064 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3065 attrs.extend(iattrs);
3066 let span = span_lo.to(body.span);
3067 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_ident), attrs));
3070 /// Parse a 'while let' expression ('while' token already eaten)
3071 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3073 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3074 self.expect_keyword(keywords::Let)?;
3075 let pat = self.parse_pat()?;
3076 self.expect(&token::Eq)?;
3077 let expr = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
3078 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3079 attrs.extend(iattrs);
3080 let span = span_lo.to(body.span);
3081 return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3084 // parse `loop {...}`, `loop` token already eaten
3085 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3087 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3088 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3089 attrs.extend(iattrs);
3090 let span = span_lo.to(body.span);
3091 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_ident), attrs))
3094 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3095 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3096 -> PResult<'a, P<Expr>>
3098 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3099 attrs.extend(iattrs);
3100 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3103 // `match` token already eaten
3104 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3105 let match_span = self.prev_span;
3106 let lo = self.prev_span;
3107 let discriminant = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
3109 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3110 if self.token == token::Token::Semi {
3111 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3115 attrs.extend(self.parse_inner_attributes()?);
3117 let mut arms: Vec<Arm> = Vec::new();
3118 while self.token != token::CloseDelim(token::Brace) {
3119 match self.parse_arm() {
3120 Ok(arm) => arms.push(arm),
3122 // Recover by skipping to the end of the block.
3124 self.recover_stmt();
3125 let span = lo.to(self.span);
3126 if self.token == token::CloseDelim(token::Brace) {
3129 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3135 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3138 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3139 maybe_whole!(self, NtArm, |x| x);
3141 let attrs = self.parse_outer_attributes()?;
3142 let pats = self.parse_pats()?;
3143 let mut guard = None;
3144 if self.eat_keyword(keywords::If) {
3145 guard = Some(self.parse_expr()?);
3147 self.expect(&token::FatArrow)?;
3148 let expr = self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR, None)?;
3151 !classify::expr_is_simple_block(&expr)
3152 && self.token != token::CloseDelim(token::Brace);
3155 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3157 self.eat(&token::Comma);
3168 /// Parse an expression
3169 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3170 self.parse_expr_res(Restrictions::empty(), None)
3173 /// Evaluate the closure with restrictions in place.
3175 /// After the closure is evaluated, restrictions are reset.
3176 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3177 where F: FnOnce(&mut Self) -> T
3179 let old = self.restrictions;
3180 self.restrictions = r;
3182 self.restrictions = old;
3187 /// Parse an expression, subject to the given restrictions
3188 pub fn parse_expr_res(&mut self, r: Restrictions,
3189 already_parsed_attrs: Option<ThinVec<Attribute>>)
3190 -> PResult<'a, P<Expr>> {
3191 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3194 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3195 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3196 if self.check(&token::Eq) {
3198 Ok(Some(self.parse_expr()?))
3204 /// Parse patterns, separated by '|' s
3205 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3206 let mut pats = Vec::new();
3208 pats.push(self.parse_pat()?);
3209 if self.check(&token::BinOp(token::Or)) { self.bump();}
3210 else { return Ok(pats); }
3214 fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3215 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3216 let mut fields = vec![];
3217 let mut ddpos = None;
3219 while !self.check(&token::CloseDelim(token::Paren)) {
3220 if ddpos.is_none() && self.eat(&token::DotDot) {
3221 ddpos = Some(fields.len());
3222 if self.eat(&token::Comma) {
3223 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3224 fields.push(self.parse_pat()?);
3226 } else if ddpos.is_some() && self.eat(&token::DotDot) {
3227 // Emit a friendly error, ignore `..` and continue parsing
3228 self.span_err(self.prev_span, "`..` can only be used once per \
3229 tuple or tuple struct pattern");
3231 fields.push(self.parse_pat()?);
3234 if !self.check(&token::CloseDelim(token::Paren)) ||
3235 (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3236 self.expect(&token::Comma)?;
3243 fn parse_pat_vec_elements(
3245 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3246 let mut before = Vec::new();
3247 let mut slice = None;
3248 let mut after = Vec::new();
3249 let mut first = true;
3250 let mut before_slice = true;
3252 while self.token != token::CloseDelim(token::Bracket) {
3256 self.expect(&token::Comma)?;
3258 if self.token == token::CloseDelim(token::Bracket)
3259 && (before_slice || !after.is_empty()) {
3265 if self.eat(&token::DotDot) {
3267 if self.check(&token::Comma) ||
3268 self.check(&token::CloseDelim(token::Bracket)) {
3269 slice = Some(P(ast::Pat {
3270 id: ast::DUMMY_NODE_ID,
3271 node: PatKind::Wild,
3274 before_slice = false;
3280 let subpat = self.parse_pat()?;
3281 if before_slice && self.eat(&token::DotDot) {
3282 slice = Some(subpat);
3283 before_slice = false;
3284 } else if before_slice {
3285 before.push(subpat);
3291 Ok((before, slice, after))
3294 /// Parse the fields of a struct-like pattern
3295 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3296 let mut fields = Vec::new();
3297 let mut etc = false;
3298 let mut first = true;
3299 while self.token != token::CloseDelim(token::Brace) {
3303 self.expect(&token::Comma)?;
3304 // accept trailing commas
3305 if self.check(&token::CloseDelim(token::Brace)) { break }
3308 let attrs = self.parse_outer_attributes()?;
3312 if self.check(&token::DotDot) {
3314 if self.token != token::CloseDelim(token::Brace) {
3315 let token_str = self.this_token_to_string();
3316 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3323 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3324 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3325 // Parsing a pattern of the form "fieldname: pat"
3326 let fieldname = self.parse_field_name()?;
3328 let pat = self.parse_pat()?;
3330 (pat, fieldname, false)
3332 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3333 let is_box = self.eat_keyword(keywords::Box);
3334 let boxed_span = self.span;
3335 let is_ref = self.eat_keyword(keywords::Ref);
3336 let is_mut = self.eat_keyword(keywords::Mut);
3337 let fieldname = self.parse_ident()?;
3338 hi = self.prev_span;
3340 let bind_type = match (is_ref, is_mut) {
3341 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3342 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3343 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3344 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3346 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3347 let fieldpat = P(ast::Pat{
3348 id: ast::DUMMY_NODE_ID,
3349 node: PatKind::Ident(bind_type, fieldpath, None),
3350 span: boxed_span.to(hi),
3353 let subpat = if is_box {
3355 id: ast::DUMMY_NODE_ID,
3356 node: PatKind::Box(fieldpat),
3362 (subpat, fieldname, true)
3365 fields.push(codemap::Spanned { span: lo.to(hi),
3366 node: ast::FieldPat {
3369 is_shorthand: is_shorthand,
3370 attrs: attrs.into(),
3374 return Ok((fields, etc));
3377 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3378 if self.token.is_path_start() {
3380 let (qself, path) = if self.eat_lt() {
3381 // Parse a qualified path
3383 self.parse_qualified_path(PathStyle::Expr)?;
3386 // Parse an unqualified path
3387 (None, self.parse_path(PathStyle::Expr)?)
3389 let hi = self.prev_span;
3390 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3392 self.parse_pat_literal_maybe_minus()
3396 // helper function to decide whether to parse as ident binding or to try to do
3397 // something more complex like range patterns
3398 fn parse_as_ident(&mut self) -> bool {
3399 self.look_ahead(1, |t| match *t {
3400 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3401 token::DotDotDot | token::ModSep | token::Not => Some(false),
3402 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3403 // range pattern branch
3404 token::DotDot => None,
3406 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3407 token::Comma | token::CloseDelim(token::Bracket) => true,
3412 /// Parse a pattern.
3413 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3414 maybe_whole!(self, NtPat, |x| x);
3419 token::Underscore => {
3422 pat = PatKind::Wild;
3424 token::BinOp(token::And) | token::AndAnd => {
3425 // Parse &pat / &mut pat
3427 let mutbl = self.parse_mutability();
3428 if let token::Lifetime(ident) = self.token {
3429 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3431 let subpat = self.parse_pat()?;
3432 pat = PatKind::Ref(subpat, mutbl);
3434 token::OpenDelim(token::Paren) => {
3435 // Parse (pat,pat,pat,...) as tuple pattern
3437 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3438 self.expect(&token::CloseDelim(token::Paren))?;
3439 pat = PatKind::Tuple(fields, ddpos);
3441 token::OpenDelim(token::Bracket) => {
3442 // Parse [pat,pat,...] as slice pattern
3444 let (before, slice, after) = self.parse_pat_vec_elements()?;
3445 self.expect(&token::CloseDelim(token::Bracket))?;
3446 pat = PatKind::Slice(before, slice, after);
3448 // At this point, token != _, &, &&, (, [
3449 _ => if self.eat_keyword(keywords::Mut) {
3450 // Parse mut ident @ pat
3451 pat = self.parse_pat_ident(BindingMode::ByValue(Mutability::Mutable))?;
3452 } else if self.eat_keyword(keywords::Ref) {
3453 // Parse ref ident @ pat / ref mut ident @ pat
3454 let mutbl = self.parse_mutability();
3455 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3456 } else if self.eat_keyword(keywords::Box) {
3458 let subpat = self.parse_pat()?;
3459 pat = PatKind::Box(subpat);
3460 } else if self.token.is_ident() && !self.token.is_any_keyword() &&
3461 self.parse_as_ident() {
3462 // Parse ident @ pat
3463 // This can give false positives and parse nullary enums,
3464 // they are dealt with later in resolve
3465 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3466 pat = self.parse_pat_ident(binding_mode)?;
3467 } else if self.token.is_path_start() {
3468 // Parse pattern starting with a path
3469 let (qself, path) = if self.eat_lt() {
3470 // Parse a qualified path
3471 let (qself, path) = self.parse_qualified_path(PathStyle::Expr)?;
3474 // Parse an unqualified path
3475 (None, self.parse_path(PathStyle::Expr)?)
3478 token::Not if qself.is_none() => {
3479 // Parse macro invocation
3481 let (_, tts) = self.expect_delimited_token_tree()?;
3482 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3483 pat = PatKind::Mac(mac);
3485 token::DotDotDot | token::DotDot => {
3486 let end_kind = match self.token {
3487 token::DotDot => RangeEnd::Excluded,
3488 token::DotDotDot => RangeEnd::Included,
3489 _ => panic!("can only parse `..` or `...` for ranges (checked above)"),
3492 let span = lo.to(self.prev_span);
3493 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3495 let end = self.parse_pat_range_end()?;
3496 pat = PatKind::Range(begin, end, end_kind);
3498 token::OpenDelim(token::Brace) => {
3499 if qself.is_some() {
3500 return Err(self.fatal("unexpected `{` after qualified path"));
3502 // Parse struct pattern
3504 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3506 self.recover_stmt();
3510 pat = PatKind::Struct(path, fields, etc);
3512 token::OpenDelim(token::Paren) => {
3513 if qself.is_some() {
3514 return Err(self.fatal("unexpected `(` after qualified path"));
3516 // Parse tuple struct or enum pattern
3518 let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3519 self.expect(&token::CloseDelim(token::Paren))?;
3520 pat = PatKind::TupleStruct(path, fields, ddpos)
3522 _ => pat = PatKind::Path(qself, path),
3525 // Try to parse everything else as literal with optional minus
3526 match self.parse_pat_literal_maybe_minus() {
3528 if self.eat(&token::DotDotDot) {
3529 let end = self.parse_pat_range_end()?;
3530 pat = PatKind::Range(begin, end, RangeEnd::Included);
3531 } else if self.eat(&token::DotDot) {
3532 let end = self.parse_pat_range_end()?;
3533 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3535 pat = PatKind::Lit(begin);
3539 self.cancel(&mut err);
3540 let msg = format!("expected pattern, found {}", self.this_token_descr());
3541 return Err(self.fatal(&msg));
3548 id: ast::DUMMY_NODE_ID,
3550 span: lo.to(self.prev_span),
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_span = self.span;
3561 let ident = self.parse_ident()?;
3562 let name = codemap::Spanned{span: ident_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>> {
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: lo.to(self.prev_span),
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: lo.to(self.prev_span),
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>>> {
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 span = lo.to(self.prev_span);
3748 let kind = ItemKind::MacroDef(tts);
3749 Ok(Some(self.mk_item(span, 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()?;
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: lo.to(self.prev_span),
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: lo.to(self.prev_span),
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;
3783 self.mk_expr(lo.to(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: lo.to(self.prev_span),
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;
3827 let style = if delim == token::Brace {
3828 MacStmtStyle::Braces
3830 MacStmtStyle::NoBraces
3833 if id.name == keywords::Invalid.name() {
3834 let mac = respan(lo.to(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.to(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,
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");
3876 let span = lo.to(hi);
3878 id: ast::DUMMY_NODE_ID,
3880 node: StmtKind::Item({
3882 span, id /*id is good here*/,
3883 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
3884 Visibility::Inherited,
3890 // FIXME: Bad copy of attrs
3891 let old_directory_ownership =
3892 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
3893 let item = self.parse_item_(attrs.clone(), false, true)?;
3894 self.directory.ownership = old_directory_ownership;
3897 id: ast::DUMMY_NODE_ID,
3898 span: lo.to(i.span),
3899 node: StmtKind::Item(i),
3902 let unused_attrs = |attrs: &[_], s: &mut Self| {
3903 if attrs.len() > 0 {
3904 if s.prev_token_kind == PrevTokenKind::DocComment {
3905 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
3907 s.span_err(s.span, "expected statement after outer attribute");
3912 // Do not attempt to parse an expression if we're done here.
3913 if self.token == token::Semi {
3914 unused_attrs(&attrs, self);
3919 if self.token == token::CloseDelim(token::Brace) {
3920 unused_attrs(&attrs, self);
3924 // Remainder are line-expr stmts.
3925 let e = self.parse_expr_res(
3926 Restrictions::RESTRICTION_STMT_EXPR, Some(attrs.into()))?;
3928 id: ast::DUMMY_NODE_ID,
3929 span: lo.to(e.span),
3930 node: StmtKind::Expr(e),
3937 /// Is this expression a successfully-parsed statement?
3938 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3939 self.restrictions.contains(Restrictions::RESTRICTION_STMT_EXPR) &&
3940 !classify::expr_requires_semi_to_be_stmt(e)
3943 /// Parse a block. No inner attrs are allowed.
3944 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
3945 maybe_whole!(self, NtBlock, |x| x);
3949 if !self.eat(&token::OpenDelim(token::Brace)) {
3951 let tok = self.this_token_to_string();
3952 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
3954 // Check to see if the user has written something like
3959 // Which is valid in other languages, but not Rust.
3960 match self.parse_stmt_without_recovery(false) {
3962 let mut stmt_span = stmt.span;
3963 // expand the span to include the semicolon, if it exists
3964 if self.eat(&token::Semi) {
3965 stmt_span.hi = self.prev_span.hi;
3967 let sugg = pprust::to_string(|s| {
3968 use print::pprust::{PrintState, INDENT_UNIT};
3969 s.ibox(INDENT_UNIT)?;
3971 s.print_stmt(&stmt)?;
3972 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
3974 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
3977 self.recover_stmt_(SemiColonMode::Break);
3978 self.cancel(&mut e);
3985 self.parse_block_tail(lo, BlockCheckMode::Default)
3988 /// Parse a block. Inner attrs are allowed.
3989 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
3990 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
3993 self.expect(&token::OpenDelim(token::Brace))?;
3994 Ok((self.parse_inner_attributes()?,
3995 self.parse_block_tail(lo, BlockCheckMode::Default)?))
3998 /// Parse the rest of a block expression or function body
3999 /// Precondition: already parsed the '{'.
4000 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4001 let mut stmts = vec![];
4003 while !self.eat(&token::CloseDelim(token::Brace)) {
4004 if let Some(stmt) = self.parse_full_stmt(false)? {
4006 } else if self.token == token::Eof {
4009 // Found only `;` or `}`.
4016 id: ast::DUMMY_NODE_ID,
4018 span: lo.to(self.prev_span),
4022 /// Parse a statement, including the trailing semicolon.
4023 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4024 let mut stmt = match self.parse_stmt_(macro_legacy_warnings) {
4026 None => return Ok(None),
4030 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4031 // expression without semicolon
4032 if classify::expr_requires_semi_to_be_stmt(expr) {
4033 // Just check for errors and recover; do not eat semicolon yet.
4035 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4038 self.recover_stmt();
4042 StmtKind::Local(..) => {
4043 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4044 if macro_legacy_warnings && self.token != token::Semi {
4045 self.warn_missing_semicolon();
4047 self.expect_one_of(&[token::Semi], &[])?;
4053 if self.eat(&token::Semi) {
4054 stmt = stmt.add_trailing_semicolon();
4057 stmt.span.hi = self.prev_span.hi;
4061 fn warn_missing_semicolon(&self) {
4062 self.diagnostic().struct_span_warn(self.span, {
4063 &format!("expected `;`, found `{}`", self.this_token_to_string())
4065 "This was erroneously allowed and will become a hard error in a future release"
4069 // Parse bounds of a type parameter `BOUND + BOUND + BOUND` without trailing `+`.
4070 // BOUND = TY_BOUND | LT_BOUND
4071 // LT_BOUND = LIFETIME (e.g. `'a`)
4072 // TY_BOUND = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4073 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> 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 self.check_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(self.expect_lifetime()));
4083 } else if self.check_keyword(keywords::For) || self.check_path() {
4085 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4086 let path = self.parse_path(PathStyle::Type)?;
4087 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4088 let modifier = if question.is_some() {
4089 TraitBoundModifier::Maybe
4091 TraitBoundModifier::None
4093 bounds.push(TraitTyParamBound(poly_trait, modifier));
4098 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4106 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4107 self.parse_ty_param_bounds_common(true)
4110 // Parse bounds of a type parameter `BOUND + BOUND + BOUND` without trailing `+`.
4111 // BOUND = LT_BOUND (e.g. `'a`)
4112 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4113 let mut lifetimes = Vec::new();
4114 while self.check_lifetime() {
4115 lifetimes.push(self.expect_lifetime());
4117 if !self.eat(&token::BinOp(token::Plus)) {
4124 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4125 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4126 let span = self.span;
4127 let ident = self.parse_ident()?;
4129 // Parse optional colon and param bounds.
4130 let bounds = if self.eat(&token::Colon) {
4131 self.parse_ty_param_bounds()?
4136 let default = if self.eat(&token::Eq) {
4137 Some(self.parse_ty()?)
4143 attrs: preceding_attrs.into(),
4145 id: ast::DUMMY_NODE_ID,
4152 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4153 /// trailing comma and erroneous trailing attributes.
4154 pub fn parse_generic_params(&mut self) -> PResult<'a, (Vec<LifetimeDef>, Vec<TyParam>)> {
4155 let mut lifetime_defs = Vec::new();
4156 let mut ty_params = Vec::new();
4157 let mut seen_ty_param = false;
4159 let attrs = self.parse_outer_attributes()?;
4160 if self.check_lifetime() {
4161 let lifetime = self.expect_lifetime();
4162 // Parse lifetime parameter.
4163 let bounds = if self.eat(&token::Colon) {
4164 self.parse_lt_param_bounds()
4168 lifetime_defs.push(LifetimeDef {
4169 attrs: attrs.into(),
4174 self.span_err(self.prev_span,
4175 "lifetime parameters must be declared prior to type parameters");
4177 } else if self.check_ident() {
4178 // Parse type parameter.
4179 ty_params.push(self.parse_ty_param(attrs)?);
4180 seen_ty_param = true;
4182 // Check for trailing attributes and stop parsing.
4183 if !attrs.is_empty() {
4184 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4185 self.span_err(attrs[0].span,
4186 &format!("trailing attribute after {} parameters", param_kind));
4191 if !self.eat(&token::Comma) {
4195 Ok((lifetime_defs, ty_params))
4198 /// Parse a set of optional generic type parameter declarations. Where
4199 /// clauses are not parsed here, and must be added later via
4200 /// `parse_where_clause()`.
4202 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4203 /// | ( < lifetimes , typaramseq ( , )? > )
4204 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4205 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4206 maybe_whole!(self, NtGenerics, |x| x);
4208 let span_lo = self.span;
4210 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4213 lifetimes: lifetime_defs,
4214 ty_params: ty_params,
4215 where_clause: WhereClause {
4216 id: ast::DUMMY_NODE_ID,
4217 predicates: Vec::new(),
4219 span: span_lo.to(self.prev_span),
4222 Ok(ast::Generics::default())
4226 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4227 /// possibly including trailing comma.
4228 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4229 let mut lifetimes = Vec::new();
4230 let mut types = Vec::new();
4231 let mut bindings = Vec::new();
4232 let mut seen_type = false;
4233 let mut seen_binding = false;
4235 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4236 // Parse lifetime argument.
4237 lifetimes.push(self.expect_lifetime());
4238 if seen_type || seen_binding {
4239 self.span_err(self.prev_span,
4240 "lifetime parameters must be declared prior to type parameters");
4242 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4243 // Parse associated type binding.
4245 let ident = self.parse_ident()?;
4247 let ty = self.parse_ty()?;
4248 bindings.push(TypeBinding {
4249 id: ast::DUMMY_NODE_ID,
4252 span: lo.to(self.prev_span),
4254 seen_binding = true;
4255 } else if self.check_type() {
4256 // Parse type argument.
4257 types.push(self.parse_ty()?);
4259 self.span_err(types[types.len() - 1].span,
4260 "type parameters must be declared prior to associated type bindings");
4267 if !self.eat(&token::Comma) {
4271 Ok((lifetimes, types, bindings))
4274 /// Parses an optional `where` clause and places it in `generics`.
4277 /// where T : Trait<U, V> + 'b, 'a : 'b
4279 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4280 maybe_whole!(self, NtWhereClause, |x| x);
4282 let mut where_clause = WhereClause {
4283 id: ast::DUMMY_NODE_ID,
4284 predicates: Vec::new(),
4287 if !self.eat_keyword(keywords::Where) {
4288 return Ok(where_clause);
4291 // This is a temporary future proofing.
4293 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4294 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4295 // change, for now we refuse to parse `where < (ident | lifetime) (> | , | :)`.
4296 if token::Lt == self.token {
4297 let ident_or_lifetime = self.look_ahead(1, |t| t.is_ident() || t.is_lifetime());
4298 if ident_or_lifetime {
4299 let gt_comma_or_colon = self.look_ahead(2, |t| {
4300 *t == token::Gt || *t == token::Comma || *t == token::Colon
4302 if gt_comma_or_colon {
4303 self.span_err(self.span, "syntax `where<T>` is reserved for future use");
4310 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4311 let lifetime = self.expect_lifetime();
4312 // Bounds starting with a colon are mandatory, but possibly empty.
4313 self.expect(&token::Colon)?;
4314 let bounds = self.parse_lt_param_bounds();
4315 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4316 ast::WhereRegionPredicate {
4317 span: lo.to(self.prev_span),
4322 } else if self.check_type() {
4323 // Parse optional `for<'a, 'b>`.
4324 // This `for` is parsed greedily and applies to the whole predicate,
4325 // the bounded type can have its own `for` applying only to it.
4326 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4327 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4328 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4329 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4331 // Parse type with mandatory colon and (possibly empty) bounds,
4332 // or with mandatory equality sign and the second type.
4333 let ty = self.parse_ty()?;
4334 if self.eat(&token::Colon) {
4335 let bounds = self.parse_ty_param_bounds()?;
4336 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4337 ast::WhereBoundPredicate {
4338 span: lo.to(self.prev_span),
4339 bound_lifetimes: lifetime_defs,
4344 // FIXME: Decide what should be used here, `=` or `==`.
4345 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4346 let rhs_ty = self.parse_ty()?;
4347 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4348 ast::WhereEqPredicate {
4349 span: lo.to(self.prev_span),
4352 id: ast::DUMMY_NODE_ID,
4356 return self.unexpected();
4362 if !self.eat(&token::Comma) {
4370 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4371 -> PResult<'a, (Vec<Arg> , bool)> {
4373 let mut variadic = false;
4374 let args: Vec<Option<Arg>> =
4375 self.parse_unspanned_seq(
4376 &token::OpenDelim(token::Paren),
4377 &token::CloseDelim(token::Paren),
4378 SeqSep::trailing_allowed(token::Comma),
4380 if p.token == token::DotDotDot {
4383 if p.token != token::CloseDelim(token::Paren) {
4386 "`...` must be last in argument list for variadic function");
4391 "only foreign functions are allowed to be variadic");
4396 match p.parse_arg_general(named_args) {
4397 Ok(arg) => Ok(Some(arg)),
4400 let lo = p.prev_span;
4401 // Skip every token until next possible arg or end.
4402 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4403 // Create a placeholder argument for proper arg count (#34264).
4404 let span = lo.to(p.prev_span);
4405 Ok(Some(dummy_arg(span)))
4412 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4414 if variadic && args.is_empty() {
4416 "variadic function must be declared with at least one named argument");
4419 Ok((args, variadic))
4422 /// Parse the argument list and result type of a function declaration
4423 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4425 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4426 let ret_ty = self.parse_ret_ty()?;
4435 /// Returns the parsed optional self argument and whether a self shortcut was used.
4436 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4437 let expect_ident = |this: &mut Self| match this.token {
4438 // Preserve hygienic context.
4439 token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
4442 let isolated_self = |this: &mut Self, n| {
4443 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4444 this.look_ahead(n + 1, |t| t != &token::ModSep)
4447 // Parse optional self parameter of a method.
4448 // Only a limited set of initial token sequences is considered self parameters, anything
4449 // else is parsed as a normal function parameter list, so some lookahead is required.
4450 let eself_lo = self.span;
4451 let (eself, eself_ident) = match self.token {
4452 token::BinOp(token::And) => {
4458 if isolated_self(self, 1) {
4460 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4461 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4462 isolated_self(self, 2) {
4465 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4466 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4467 isolated_self(self, 2) {
4469 let lt = self.expect_lifetime();
4470 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4471 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4472 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4473 isolated_self(self, 3) {
4475 let lt = self.expect_lifetime();
4477 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4482 token::BinOp(token::Star) => {
4487 // Emit special error for `self` cases.
4488 if isolated_self(self, 1) {
4490 self.span_err(self.span, "cannot pass `self` by raw pointer");
4491 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4492 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4493 isolated_self(self, 2) {
4496 self.span_err(self.span, "cannot pass `self` by raw pointer");
4497 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4502 token::Ident(..) => {
4503 if isolated_self(self, 0) {
4506 let eself_ident = expect_ident(self);
4507 if self.eat(&token::Colon) {
4508 let ty = self.parse_ty()?;
4509 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4511 (SelfKind::Value(Mutability::Immutable), eself_ident)
4513 } else if self.token.is_keyword(keywords::Mut) &&
4514 isolated_self(self, 1) {
4518 let eself_ident = expect_ident(self);
4519 if self.eat(&token::Colon) {
4520 let ty = self.parse_ty()?;
4521 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
4523 (SelfKind::Value(Mutability::Mutable), eself_ident)
4529 _ => return Ok(None),
4532 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
4533 Ok(Some(Arg::from_self(eself, eself_ident)))
4536 /// Parse the parameter list and result type of a function that may have a `self` parameter.
4537 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
4538 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4540 self.expect(&token::OpenDelim(token::Paren))?;
4542 // Parse optional self argument
4543 let self_arg = self.parse_self_arg()?;
4545 // Parse the rest of the function parameter list.
4546 let sep = SeqSep::trailing_allowed(token::Comma);
4547 let fn_inputs = if let Some(self_arg) = self_arg {
4548 if self.check(&token::CloseDelim(token::Paren)) {
4550 } else if self.eat(&token::Comma) {
4551 let mut fn_inputs = vec![self_arg];
4552 fn_inputs.append(&mut self.parse_seq_to_before_end(
4553 &token::CloseDelim(token::Paren), sep, parse_arg_fn)
4557 return self.unexpected();
4560 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4563 // Parse closing paren and return type.
4564 self.expect(&token::CloseDelim(token::Paren))?;
4567 output: self.parse_ret_ty()?,
4572 // parse the |arg, arg| header on a lambda
4573 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4574 let inputs_captures = {
4575 if self.eat(&token::OrOr) {
4578 self.expect(&token::BinOp(token::Or))?;
4579 let args = self.parse_seq_to_before_end(
4580 &token::BinOp(token::Or),
4581 SeqSep::trailing_allowed(token::Comma),
4582 |p| p.parse_fn_block_arg()
4588 let output = self.parse_ret_ty()?;
4591 inputs: inputs_captures,
4597 /// Parse the name and optional generic types of a function header.
4598 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4599 let id = self.parse_ident()?;
4600 let generics = self.parse_generics()?;
4604 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
4605 attrs: Vec<Attribute>) -> P<Item> {
4609 id: ast::DUMMY_NODE_ID,
4616 /// Parse an item-position function declaration.
4617 fn parse_item_fn(&mut self,
4619 constness: Spanned<Constness>,
4621 -> PResult<'a, ItemInfo> {
4622 let (ident, mut generics) = self.parse_fn_header()?;
4623 let decl = self.parse_fn_decl(false)?;
4624 generics.where_clause = self.parse_where_clause()?;
4625 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4626 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4629 /// true if we are looking at `const ID`, false for things like `const fn` etc
4630 pub fn is_const_item(&mut self) -> bool {
4631 self.token.is_keyword(keywords::Const) &&
4632 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4633 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4636 /// parses all the "front matter" for a `fn` declaration, up to
4637 /// and including the `fn` keyword:
4641 /// - `const unsafe fn`
4644 pub fn parse_fn_front_matter(&mut self)
4645 -> PResult<'a, (Spanned<ast::Constness>,
4648 let is_const_fn = self.eat_keyword(keywords::Const);
4649 let const_span = self.prev_span;
4650 let unsafety = self.parse_unsafety()?;
4651 let (constness, unsafety, abi) = if is_const_fn {
4652 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
4654 let abi = if self.eat_keyword(keywords::Extern) {
4655 self.parse_opt_abi()?.unwrap_or(Abi::C)
4659 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
4661 self.expect_keyword(keywords::Fn)?;
4662 Ok((constness, unsafety, abi))
4665 /// Parse an impl item.
4666 pub fn parse_impl_item(&mut self) -> PResult<'a, ImplItem> {
4667 maybe_whole!(self, NtImplItem, |x| x);
4669 let mut attrs = self.parse_outer_attributes()?;
4671 let vis = self.parse_visibility(false)?;
4672 let defaultness = self.parse_defaultness()?;
4673 let (name, node) = if self.eat_keyword(keywords::Type) {
4674 let name = self.parse_ident()?;
4675 self.expect(&token::Eq)?;
4676 let typ = self.parse_ty()?;
4677 self.expect(&token::Semi)?;
4678 (name, ast::ImplItemKind::Type(typ))
4679 } else if self.is_const_item() {
4680 self.expect_keyword(keywords::Const)?;
4681 let name = self.parse_ident()?;
4682 self.expect(&token::Colon)?;
4683 let typ = self.parse_ty()?;
4684 self.expect(&token::Eq)?;
4685 let expr = self.parse_expr()?;
4686 self.expect(&token::Semi)?;
4687 (name, ast::ImplItemKind::Const(typ, expr))
4689 let (name, inner_attrs, node) = self.parse_impl_method(&vis)?;
4690 attrs.extend(inner_attrs);
4695 id: ast::DUMMY_NODE_ID,
4696 span: lo.to(self.prev_span),
4699 defaultness: defaultness,
4705 fn complain_if_pub_macro(&mut self, vis: &Visibility, sp: Span) {
4706 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
4711 fn complain_if_pub_macro_diag(&mut self, vis: &Visibility, sp: Span) -> PResult<'a, ()> {
4713 Visibility::Inherited => Ok(()),
4715 let is_macro_rules: bool = match self.token {
4716 token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
4720 let mut err = self.diagnostic()
4721 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
4722 err.help("did you mean #[macro_export]?");
4725 let mut err = self.diagnostic()
4726 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
4727 err.help("try adjusting the macro to put `pub` inside the invocation");
4734 /// Parse a method or a macro invocation in a trait impl.
4735 fn parse_impl_method(&mut self, vis: &Visibility)
4736 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4737 // code copied from parse_macro_use_or_failure... abstraction!
4738 if self.token.is_path_start() {
4741 let prev_span = self.prev_span;
4742 // Before complaining about trying to set a macro as `pub`,
4743 // check if `!` comes after the path.
4744 let err = self.complain_if_pub_macro_diag(&vis, prev_span);
4747 let pth = self.parse_path(PathStyle::Mod)?;
4748 let bang_err = self.expect(&token::Not);
4749 if let Err(mut err) = err {
4750 if let Err(mut bang_err) = bang_err {
4751 // Given this code `pub path(`, it seems like this is not setting the
4752 // visibility of a macro invocation, but rather a mistyped method declaration.
4753 // Create a diagnostic pointing out that `fn` is missing.
4755 // x | pub path(&self) {
4756 // | ^ missing `fn` for method declaration
4761 // ^^ `sp` below will point to this
4762 let sp = prev_span.between(self.prev_span);
4763 err = self.diagnostic()
4764 .struct_span_err(sp, "missing `fn` for method declaration");
4765 err.span_label(sp, &"missing `fn`");
4770 // eat a matched-delimiter token tree:
4771 let (delim, tts) = self.expect_delimited_token_tree()?;
4772 if delim != token::Brace {
4773 self.expect(&token::Semi)?
4776 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
4777 Ok((keywords::Invalid.ident(), vec![], ast::ImplItemKind::Macro(mac)))
4779 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
4780 let ident = self.parse_ident()?;
4781 let mut generics = self.parse_generics()?;
4782 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
4783 generics.where_clause = self.parse_where_clause()?;
4784 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4785 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4789 constness: constness,
4795 /// Parse trait Foo { ... }
4796 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4797 let ident = self.parse_ident()?;
4798 let mut tps = self.parse_generics()?;
4800 // Parse optional colon and supertrait bounds.
4801 let bounds = if self.eat(&token::Colon) {
4802 self.parse_ty_param_bounds()?
4807 tps.where_clause = self.parse_where_clause()?;
4809 let meths = self.parse_trait_items()?;
4810 Ok((ident, ItemKind::Trait(unsafety, tps, bounds, meths), None))
4813 /// Parses items implementations variants
4814 /// impl<T> Foo { ... }
4815 /// impl<T> ToString for &'static T { ... }
4816 /// impl Send for .. {}
4817 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> PResult<'a, ItemInfo> {
4818 let impl_span = self.span;
4820 // First, parse type parameters if necessary.
4821 let mut generics = self.parse_generics()?;
4823 // Special case: if the next identifier that follows is '(', don't
4824 // allow this to be parsed as a trait.
4825 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4827 let neg_span = self.span;
4828 let polarity = if self.eat(&token::Not) {
4829 ast::ImplPolarity::Negative
4831 ast::ImplPolarity::Positive
4835 let mut ty = self.parse_ty()?;
4837 // Parse traits, if necessary.
4838 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4839 // New-style trait. Reinterpret the type as a trait.
4841 TyKind::Path(None, ref path) => {
4843 path: (*path).clone(),
4848 self.span_err(ty.span, "not a trait");
4854 ast::ImplPolarity::Negative => {
4855 // This is a negated type implementation
4856 // `impl !MyType {}`, which is not allowed.
4857 self.span_err(neg_span, "inherent implementation can't be negated");
4864 if opt_trait.is_some() && self.eat(&token::DotDot) {
4865 if generics.is_parameterized() {
4866 self.span_err(impl_span, "default trait implementations are not \
4867 allowed to have generics");
4870 self.expect(&token::OpenDelim(token::Brace))?;
4871 self.expect(&token::CloseDelim(token::Brace))?;
4872 Ok((keywords::Invalid.ident(),
4873 ItemKind::DefaultImpl(unsafety, opt_trait.unwrap()), None))
4875 if opt_trait.is_some() {
4876 ty = self.parse_ty()?;
4878 generics.where_clause = self.parse_where_clause()?;
4880 self.expect(&token::OpenDelim(token::Brace))?;
4881 let attrs = self.parse_inner_attributes()?;
4883 let mut impl_items = vec![];
4884 while !self.eat(&token::CloseDelim(token::Brace)) {
4885 impl_items.push(self.parse_impl_item()?);
4888 Ok((keywords::Invalid.ident(),
4889 ItemKind::Impl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4894 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<LifetimeDef>> {
4895 if self.eat_keyword(keywords::For) {
4897 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4899 if !ty_params.is_empty() {
4900 self.span_err(ty_params[0].span,
4901 "only lifetime parameters can be used in this context");
4909 /// Parse struct Foo { ... }
4910 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
4911 let class_name = self.parse_ident()?;
4913 let mut generics = self.parse_generics()?;
4915 // There is a special case worth noting here, as reported in issue #17904.
4916 // If we are parsing a tuple struct it is the case that the where clause
4917 // should follow the field list. Like so:
4919 // struct Foo<T>(T) where T: Copy;
4921 // If we are parsing a normal record-style struct it is the case
4922 // that the where clause comes before the body, and after the generics.
4923 // So if we look ahead and see a brace or a where-clause we begin
4924 // parsing a record style struct.
4926 // Otherwise if we look ahead and see a paren we parse a tuple-style
4929 let vdata = if self.token.is_keyword(keywords::Where) {
4930 generics.where_clause = self.parse_where_clause()?;
4931 if self.eat(&token::Semi) {
4932 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4933 VariantData::Unit(ast::DUMMY_NODE_ID)
4935 // If we see: `struct Foo<T> where T: Copy { ... }`
4936 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
4938 // No `where` so: `struct Foo<T>;`
4939 } else if self.eat(&token::Semi) {
4940 VariantData::Unit(ast::DUMMY_NODE_ID)
4941 // Record-style struct definition
4942 } else if self.token == token::OpenDelim(token::Brace) {
4943 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
4944 // Tuple-style struct definition with optional where-clause.
4945 } else if self.token == token::OpenDelim(token::Paren) {
4946 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
4947 generics.where_clause = self.parse_where_clause()?;
4948 self.expect(&token::Semi)?;
4951 let token_str = self.this_token_to_string();
4952 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
4953 name, found `{}`", token_str)))
4956 Ok((class_name, ItemKind::Struct(vdata, generics), None))
4959 /// Parse union Foo { ... }
4960 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
4961 let class_name = self.parse_ident()?;
4963 let mut generics = self.parse_generics()?;
4965 let vdata = if self.token.is_keyword(keywords::Where) {
4966 generics.where_clause = self.parse_where_clause()?;
4967 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
4968 } else if self.token == token::OpenDelim(token::Brace) {
4969 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
4971 let token_str = self.this_token_to_string();
4972 return Err(self.fatal(&format!("expected `where` or `{{` after union \
4973 name, found `{}`", token_str)))
4976 Ok((class_name, ItemKind::Union(vdata, generics), None))
4979 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
4980 let mut fields = Vec::new();
4981 if self.eat(&token::OpenDelim(token::Brace)) {
4982 while self.token != token::CloseDelim(token::Brace) {
4983 fields.push(self.parse_struct_decl_field().map_err(|e| {
4984 self.recover_stmt();
4985 self.eat(&token::CloseDelim(token::Brace));
4992 let token_str = self.this_token_to_string();
4993 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5001 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5002 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5003 // Unit like structs are handled in parse_item_struct function
5004 let fields = self.parse_unspanned_seq(
5005 &token::OpenDelim(token::Paren),
5006 &token::CloseDelim(token::Paren),
5007 SeqSep::trailing_allowed(token::Comma),
5009 let attrs = p.parse_outer_attributes()?;
5011 let vis = p.parse_visibility(true)?;
5012 let ty = p.parse_ty()?;
5014 span: lo.to(p.span),
5017 id: ast::DUMMY_NODE_ID,
5026 /// Parse a structure field declaration
5027 pub fn parse_single_struct_field(&mut self,
5030 attrs: Vec<Attribute> )
5031 -> PResult<'a, StructField> {
5032 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5037 token::CloseDelim(token::Brace) => {}
5038 token::DocComment(_) => return Err(self.span_fatal_err(self.span,
5039 Error::UselessDocComment)),
5040 _ => return Err(self.span_fatal_help(self.span,
5041 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5042 "struct fields should be separated by commas")),
5047 /// Parse an element of a struct definition
5048 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5049 let attrs = self.parse_outer_attributes()?;
5051 let vis = self.parse_visibility(false)?;
5052 self.parse_single_struct_field(lo, vis, attrs)
5055 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5056 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5057 /// a function definition, it's not a tuple struct field) and the contents within the parens
5058 /// isn't valid, emit a proper diagnostic.
5059 fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5060 if !self.eat_keyword(keywords::Pub) {
5061 return Ok(Visibility::Inherited)
5064 if self.check(&token::OpenDelim(token::Paren)) {
5065 let start_span = self.span;
5066 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5067 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5068 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5069 // by the following tokens.
5070 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5073 self.bump(); // `crate`
5074 let vis = Visibility::Crate(self.prev_span);
5075 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5077 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5080 self.bump(); // `in`
5081 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5082 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5083 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5085 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5086 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5087 t.is_keyword(keywords::SelfValue)) {
5088 // `pub(self)` or `pub(super)`
5090 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5091 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5092 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5094 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5095 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5097 let msg = "incorrect visibility restriction";
5098 let suggestion = r##"some possible visibility restrictions are:
5099 `pub(crate)`: visible only on the current crate
5100 `pub(super)`: visible only in the current module's parent
5101 `pub(in path::to::module)`: visible only on the specified path"##;
5102 let path = self.parse_path(PathStyle::Mod)?;
5103 let path_span = self.prev_span;
5104 let help_msg = format!("to make this visible only to module `{}`, add `in` before \
5107 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5108 let sp = start_span.to(self.prev_span);
5109 let mut err = self.span_fatal_help(sp, &msg, &suggestion);
5110 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5111 err.emit(); // emit diagnostic, but continue with public visibility
5115 Ok(Visibility::Public)
5118 /// Parse defaultness: DEFAULT or nothing
5119 fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> {
5120 if self.eat_contextual_keyword(keywords::Default.ident()) {
5121 Ok(Defaultness::Default)
5123 Ok(Defaultness::Final)
5127 /// Given a termination token, parse all of the items in a module
5128 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5129 let mut items = vec![];
5130 while let Some(item) = self.parse_item()? {
5134 if !self.eat(term) {
5135 let token_str = self.this_token_to_string();
5136 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5139 let hi = if self.span == syntax_pos::DUMMY_SP {
5146 inner: inner_lo.to(hi),
5151 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5152 let id = self.parse_ident()?;
5153 self.expect(&token::Colon)?;
5154 let ty = self.parse_ty()?;
5155 self.expect(&token::Eq)?;
5156 let e = self.parse_expr()?;
5157 self.expect(&token::Semi)?;
5158 let item = match m {
5159 Some(m) => ItemKind::Static(ty, m, e),
5160 None => ItemKind::Const(ty, e),
5162 Ok((id, item, None))
5165 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5166 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5167 let (in_cfg, outer_attrs) = {
5168 let mut strip_unconfigured = ::config::StripUnconfigured {
5170 should_test: false, // irrelevant
5171 features: None, // don't perform gated feature checking
5173 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5174 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5177 let id_span = self.span;
5178 let id = self.parse_ident()?;
5179 if self.check(&token::Semi) {
5182 // This mod is in an external file. Let's go get it!
5183 let ModulePathSuccess { path, directory_ownership, warn } =
5184 self.submod_path(id, &outer_attrs, id_span)?;
5185 let (module, mut attrs) =
5186 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5188 let attr = ast::Attribute {
5189 id: attr::mk_attr_id(),
5190 style: ast::AttrStyle::Outer,
5191 path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5192 Ident::from_str("warn_directory_ownership")),
5193 tokens: TokenStream::empty(),
5194 is_sugared_doc: false,
5195 span: syntax_pos::DUMMY_SP,
5197 attr::mark_known(&attr);
5200 Ok((id, module, Some(attrs)))
5202 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5203 Ok((id, ItemKind::Mod(placeholder), None))
5206 let old_directory = self.directory.clone();
5207 self.push_directory(id, &outer_attrs);
5208 self.expect(&token::OpenDelim(token::Brace))?;
5209 let mod_inner_lo = self.span;
5210 let attrs = self.parse_inner_attributes()?;
5211 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5212 self.directory = old_directory;
5213 Ok((id, ItemKind::Mod(module), Some(attrs)))
5217 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5218 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5219 self.directory.path.push(&path.as_str());
5220 self.directory.ownership = DirectoryOwnership::Owned;
5222 self.directory.path.push(&id.name.as_str());
5226 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5227 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5230 /// Returns either a path to a module, or .
5231 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath {
5232 let mod_name = id.to_string();
5233 let default_path_str = format!("{}.rs", mod_name);
5234 let secondary_path_str = format!("{}{}mod.rs", mod_name, path::MAIN_SEPARATOR);
5235 let default_path = dir_path.join(&default_path_str);
5236 let secondary_path = dir_path.join(&secondary_path_str);
5237 let default_exists = codemap.file_exists(&default_path);
5238 let secondary_exists = codemap.file_exists(&secondary_path);
5240 let result = match (default_exists, secondary_exists) {
5241 (true, false) => Ok(ModulePathSuccess {
5243 directory_ownership: DirectoryOwnership::UnownedViaMod(false),
5246 (false, true) => Ok(ModulePathSuccess {
5247 path: secondary_path,
5248 directory_ownership: DirectoryOwnership::Owned,
5251 (false, false) => Err(Error::FileNotFoundForModule {
5252 mod_name: mod_name.clone(),
5253 default_path: default_path_str,
5254 secondary_path: secondary_path_str,
5255 dir_path: format!("{}", dir_path.display()),
5257 (true, true) => Err(Error::DuplicatePaths {
5258 mod_name: mod_name.clone(),
5259 default_path: default_path_str,
5260 secondary_path: secondary_path_str,
5266 path_exists: default_exists || secondary_exists,
5271 fn submod_path(&mut self,
5273 outer_attrs: &[ast::Attribute],
5274 id_sp: Span) -> PResult<'a, ModulePathSuccess> {
5275 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5276 return Ok(ModulePathSuccess {
5277 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5278 Some("mod.rs") => DirectoryOwnership::Owned,
5279 _ => DirectoryOwnership::UnownedViaMod(true),
5286 let paths = Parser::default_submod_path(id, &self.directory.path, self.sess.codemap());
5288 if let DirectoryOwnership::UnownedViaBlock = self.directory.ownership {
5290 "Cannot declare a non-inline module inside a block unless it has a path attribute";
5291 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5292 if paths.path_exists {
5293 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5295 err.span_note(id_sp, &msg);
5298 } else if let DirectoryOwnership::UnownedViaMod(warn) = self.directory.ownership {
5300 if let Ok(result) = paths.result {
5301 return Ok(ModulePathSuccess { warn: true, ..result });
5304 let mut err = self.diagnostic().struct_span_err(id_sp,
5305 "cannot declare a new module at this location");
5306 let this_module = match self.directory.path.file_name() {
5307 Some(file_name) => file_name.to_str().unwrap().to_owned(),
5308 None => self.root_module_name.as_ref().unwrap().clone(),
5310 err.span_note(id_sp,
5311 &format!("maybe move this module `{0}` to its own directory \
5312 via `{0}{1}mod.rs`",
5314 path::MAIN_SEPARATOR));
5315 if paths.path_exists {
5316 err.span_note(id_sp,
5317 &format!("... or maybe `use` the module `{}` instead \
5318 of possibly redeclaring it",
5325 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5329 /// Read a module from a source file.
5330 fn eval_src_mod(&mut self,
5332 directory_ownership: DirectoryOwnership,
5335 -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5336 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5337 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
5338 let mut err = String::from("circular modules: ");
5339 let len = included_mod_stack.len();
5340 for p in &included_mod_stack[i.. len] {
5341 err.push_str(&p.to_string_lossy());
5342 err.push_str(" -> ");
5344 err.push_str(&path.to_string_lossy());
5345 return Err(self.span_fatal(id_sp, &err[..]));
5347 included_mod_stack.push(path.clone());
5348 drop(included_mod_stack);
5351 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
5352 p0.cfg_mods = self.cfg_mods;
5353 let mod_inner_lo = p0.span;
5354 let mod_attrs = p0.parse_inner_attributes()?;
5355 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
5356 self.sess.included_mod_stack.borrow_mut().pop();
5357 Ok((ast::ItemKind::Mod(m0), mod_attrs))
5360 /// Parse a function declaration from a foreign module
5361 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5362 -> PResult<'a, ForeignItem> {
5363 self.expect_keyword(keywords::Fn)?;
5365 let (ident, mut generics) = self.parse_fn_header()?;
5366 let decl = self.parse_fn_decl(true)?;
5367 generics.where_clause = self.parse_where_clause()?;
5369 self.expect(&token::Semi)?;
5370 Ok(ast::ForeignItem {
5373 node: ForeignItemKind::Fn(decl, generics),
5374 id: ast::DUMMY_NODE_ID,
5380 /// Parse a static item from a foreign module
5381 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5382 -> PResult<'a, ForeignItem> {
5383 self.expect_keyword(keywords::Static)?;
5384 let mutbl = self.eat_keyword(keywords::Mut);
5386 let ident = self.parse_ident()?;
5387 self.expect(&token::Colon)?;
5388 let ty = self.parse_ty()?;
5390 self.expect(&token::Semi)?;
5394 node: ForeignItemKind::Static(ty, mutbl),
5395 id: ast::DUMMY_NODE_ID,
5401 /// Parse extern crate links
5405 /// extern crate foo;
5406 /// extern crate bar as foo;
5407 fn parse_item_extern_crate(&mut self,
5409 visibility: Visibility,
5410 attrs: Vec<Attribute>)
5411 -> PResult<'a, P<Item>> {
5413 let crate_name = self.parse_ident()?;
5414 let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
5415 (Some(crate_name.name), ident)
5419 self.expect(&token::Semi)?;
5421 let prev_span = self.prev_span;
5422 Ok(self.mk_item(lo.to(prev_span),
5424 ItemKind::ExternCrate(maybe_path),
5429 /// Parse `extern` for foreign ABIs
5432 /// `extern` is expected to have been
5433 /// consumed before calling this method
5439 fn parse_item_foreign_mod(&mut self,
5441 opt_abi: Option<abi::Abi>,
5442 visibility: Visibility,
5443 mut attrs: Vec<Attribute>)
5444 -> PResult<'a, P<Item>> {
5445 self.expect(&token::OpenDelim(token::Brace))?;
5447 let abi = opt_abi.unwrap_or(Abi::C);
5449 attrs.extend(self.parse_inner_attributes()?);
5451 let mut foreign_items = vec![];
5452 while let Some(item) = self.parse_foreign_item()? {
5453 foreign_items.push(item);
5455 self.expect(&token::CloseDelim(token::Brace))?;
5457 let prev_span = self.prev_span;
5458 let m = ast::ForeignMod {
5460 items: foreign_items
5462 let invalid = keywords::Invalid.ident();
5463 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
5466 /// Parse type Foo = Bar;
5467 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5468 let ident = self.parse_ident()?;
5469 let mut tps = self.parse_generics()?;
5470 tps.where_clause = self.parse_where_clause()?;
5471 self.expect(&token::Eq)?;
5472 let ty = self.parse_ty()?;
5473 self.expect(&token::Semi)?;
5474 Ok((ident, ItemKind::Ty(ty, tps), None))
5477 /// Parse the part of an "enum" decl following the '{'
5478 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5479 let mut variants = Vec::new();
5480 let mut all_nullary = true;
5481 let mut any_disr = None;
5482 while self.token != token::CloseDelim(token::Brace) {
5483 let variant_attrs = self.parse_outer_attributes()?;
5484 let vlo = self.span;
5487 let mut disr_expr = None;
5488 let ident = self.parse_ident()?;
5489 if self.check(&token::OpenDelim(token::Brace)) {
5490 // Parse a struct variant.
5491 all_nullary = false;
5492 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
5493 ast::DUMMY_NODE_ID);
5494 } else if self.check(&token::OpenDelim(token::Paren)) {
5495 all_nullary = false;
5496 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
5497 ast::DUMMY_NODE_ID);
5498 } else if self.eat(&token::Eq) {
5499 disr_expr = Some(self.parse_expr()?);
5500 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5501 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5503 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5506 let vr = ast::Variant_ {
5508 attrs: variant_attrs,
5510 disr_expr: disr_expr,
5512 variants.push(respan(vlo.to(self.prev_span), vr));
5514 if !self.eat(&token::Comma) { break; }
5516 self.expect(&token::CloseDelim(token::Brace))?;
5518 Some(disr_span) if !all_nullary =>
5519 self.span_err(disr_span,
5520 "discriminator values can only be used with a c-like enum"),
5524 Ok(ast::EnumDef { variants: variants })
5527 /// Parse an "enum" declaration
5528 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5529 let id = self.parse_ident()?;
5530 let mut generics = self.parse_generics()?;
5531 generics.where_clause = self.parse_where_clause()?;
5532 self.expect(&token::OpenDelim(token::Brace))?;
5534 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
5535 self.recover_stmt();
5536 self.eat(&token::CloseDelim(token::Brace));
5539 Ok((id, ItemKind::Enum(enum_definition, generics), None))
5542 /// Parses a string as an ABI spec on an extern type or module. Consumes
5543 /// the `extern` keyword, if one is found.
5544 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5546 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5548 self.expect_no_suffix(sp, "ABI spec", suf);
5550 match abi::lookup(&s.as_str()) {
5551 Some(abi) => Ok(Some(abi)),
5553 let prev_span = self.prev_span;
5556 &format!("invalid ABI: expected one of [{}], \
5558 abi::all_names().join(", "),
5569 /// Parse one of the items allowed by the flags.
5570 /// NB: this function no longer parses the items inside an
5572 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5573 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5574 maybe_whole!(self, NtItem, |item| {
5575 let mut item = item.unwrap();
5576 let mut attrs = attrs;
5577 mem::swap(&mut item.attrs, &mut attrs);
5578 item.attrs.extend(attrs);
5584 let visibility = self.parse_visibility(false)?;
5586 if self.eat_keyword(keywords::Use) {
5588 let item_ = ItemKind::Use(self.parse_view_path()?);
5589 self.expect(&token::Semi)?;
5591 let prev_span = self.prev_span;
5592 let invalid = keywords::Invalid.ident();
5593 let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
5594 return Ok(Some(item));
5597 if self.eat_keyword(keywords::Extern) {
5598 if self.eat_keyword(keywords::Crate) {
5599 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
5602 let opt_abi = self.parse_opt_abi()?;
5604 if self.eat_keyword(keywords::Fn) {
5605 // EXTERN FUNCTION ITEM
5606 let fn_span = self.prev_span;
5607 let abi = opt_abi.unwrap_or(Abi::C);
5608 let (ident, item_, extra_attrs) =
5609 self.parse_item_fn(Unsafety::Normal,
5610 respan(fn_span, Constness::NotConst),
5612 let prev_span = self.prev_span;
5613 let item = self.mk_item(lo.to(prev_span),
5617 maybe_append(attrs, extra_attrs));
5618 return Ok(Some(item));
5619 } else if self.check(&token::OpenDelim(token::Brace)) {
5620 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
5626 if self.eat_keyword(keywords::Static) {
5628 let m = if self.eat_keyword(keywords::Mut) {
5631 Mutability::Immutable
5633 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
5634 let prev_span = self.prev_span;
5635 let item = self.mk_item(lo.to(prev_span),
5639 maybe_append(attrs, extra_attrs));
5640 return Ok(Some(item));
5642 if self.eat_keyword(keywords::Const) {
5643 let const_span = self.prev_span;
5644 if self.check_keyword(keywords::Fn)
5645 || (self.check_keyword(keywords::Unsafe)
5646 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5647 // CONST FUNCTION ITEM
5648 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5654 let (ident, item_, extra_attrs) =
5655 self.parse_item_fn(unsafety,
5656 respan(const_span, Constness::Const),
5658 let prev_span = self.prev_span;
5659 let item = self.mk_item(lo.to(prev_span),
5663 maybe_append(attrs, extra_attrs));
5664 return Ok(Some(item));
5668 if self.eat_keyword(keywords::Mut) {
5669 let prev_span = self.prev_span;
5670 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
5671 .help("did you mean to declare a static?")
5674 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
5675 let prev_span = self.prev_span;
5676 let item = self.mk_item(lo.to(prev_span),
5680 maybe_append(attrs, extra_attrs));
5681 return Ok(Some(item));
5683 if self.check_keyword(keywords::Unsafe) &&
5684 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5686 // UNSAFE TRAIT ITEM
5687 self.expect_keyword(keywords::Unsafe)?;
5688 self.expect_keyword(keywords::Trait)?;
5689 let (ident, item_, extra_attrs) =
5690 self.parse_item_trait(ast::Unsafety::Unsafe)?;
5691 let prev_span = self.prev_span;
5692 let item = self.mk_item(lo.to(prev_span),
5696 maybe_append(attrs, extra_attrs));
5697 return Ok(Some(item));
5699 if self.check_keyword(keywords::Unsafe) &&
5700 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5703 self.expect_keyword(keywords::Unsafe)?;
5704 self.expect_keyword(keywords::Impl)?;
5705 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe)?;
5706 let prev_span = self.prev_span;
5707 let item = self.mk_item(lo.to(prev_span),
5711 maybe_append(attrs, extra_attrs));
5712 return Ok(Some(item));
5714 if self.check_keyword(keywords::Fn) {
5717 let fn_span = self.prev_span;
5718 let (ident, item_, extra_attrs) =
5719 self.parse_item_fn(Unsafety::Normal,
5720 respan(fn_span, Constness::NotConst),
5722 let prev_span = self.prev_span;
5723 let item = self.mk_item(lo.to(prev_span),
5727 maybe_append(attrs, extra_attrs));
5728 return Ok(Some(item));
5730 if self.check_keyword(keywords::Unsafe)
5731 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5732 // UNSAFE FUNCTION ITEM
5734 let abi = if self.eat_keyword(keywords::Extern) {
5735 self.parse_opt_abi()?.unwrap_or(Abi::C)
5739 self.expect_keyword(keywords::Fn)?;
5740 let fn_span = self.prev_span;
5741 let (ident, item_, extra_attrs) =
5742 self.parse_item_fn(Unsafety::Unsafe,
5743 respan(fn_span, Constness::NotConst),
5745 let prev_span = self.prev_span;
5746 let item = self.mk_item(lo.to(prev_span),
5750 maybe_append(attrs, extra_attrs));
5751 return Ok(Some(item));
5753 if self.eat_keyword(keywords::Mod) {
5755 let (ident, item_, extra_attrs) =
5756 self.parse_item_mod(&attrs[..])?;
5757 let prev_span = self.prev_span;
5758 let item = self.mk_item(lo.to(prev_span),
5762 maybe_append(attrs, extra_attrs));
5763 return Ok(Some(item));
5765 if self.eat_keyword(keywords::Type) {
5767 let (ident, item_, extra_attrs) = self.parse_item_type()?;
5768 let prev_span = self.prev_span;
5769 let item = self.mk_item(lo.to(prev_span),
5773 maybe_append(attrs, extra_attrs));
5774 return Ok(Some(item));
5776 if self.eat_keyword(keywords::Enum) {
5778 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
5779 let prev_span = self.prev_span;
5780 let item = self.mk_item(lo.to(prev_span),
5784 maybe_append(attrs, extra_attrs));
5785 return Ok(Some(item));
5787 if self.eat_keyword(keywords::Trait) {
5789 let (ident, item_, extra_attrs) =
5790 self.parse_item_trait(ast::Unsafety::Normal)?;
5791 let prev_span = self.prev_span;
5792 let item = self.mk_item(lo.to(prev_span),
5796 maybe_append(attrs, extra_attrs));
5797 return Ok(Some(item));
5799 if self.eat_keyword(keywords::Impl) {
5801 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal)?;
5802 let prev_span = self.prev_span;
5803 let item = self.mk_item(lo.to(prev_span),
5807 maybe_append(attrs, extra_attrs));
5808 return Ok(Some(item));
5810 if self.eat_keyword(keywords::Struct) {
5812 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
5813 let prev_span = self.prev_span;
5814 let item = self.mk_item(lo.to(prev_span),
5818 maybe_append(attrs, extra_attrs));
5819 return Ok(Some(item));
5821 if self.is_union_item() {
5824 let (ident, item_, extra_attrs) = self.parse_item_union()?;
5825 let prev_span = self.prev_span;
5826 let item = self.mk_item(lo.to(prev_span),
5830 maybe_append(attrs, extra_attrs));
5831 return Ok(Some(item));
5833 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility)? {
5834 return Ok(Some(macro_def));
5837 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5840 /// Parse a foreign item.
5841 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
5842 let attrs = self.parse_outer_attributes()?;
5844 let visibility = self.parse_visibility(false)?;
5846 if self.check_keyword(keywords::Static) {
5847 // FOREIGN STATIC ITEM
5848 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
5850 if self.check_keyword(keywords::Fn) {
5851 // FOREIGN FUNCTION ITEM
5852 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
5855 // FIXME #5668: this will occur for a macro invocation:
5856 match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
5858 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5864 /// This is the fall-through for parsing items.
5865 fn parse_macro_use_or_failure(
5867 attrs: Vec<Attribute> ,
5868 macros_allowed: bool,
5869 attributes_allowed: bool,
5871 visibility: Visibility
5872 ) -> PResult<'a, Option<P<Item>>> {
5873 if macros_allowed && self.token.is_path_start() {
5874 // MACRO INVOCATION ITEM
5876 let prev_span = self.prev_span;
5877 self.complain_if_pub_macro(&visibility, prev_span);
5879 let mac_lo = self.span;
5882 let pth = self.parse_path(PathStyle::Mod)?;
5883 self.expect(&token::Not)?;
5885 // a 'special' identifier (like what `macro_rules!` uses)
5886 // is optional. We should eventually unify invoc syntax
5888 let id = if self.token.is_ident() {
5891 keywords::Invalid.ident() // no special identifier
5893 // eat a matched-delimiter token tree:
5894 let (delim, tts) = self.expect_delimited_token_tree()?;
5895 if delim != token::Brace {
5896 if !self.eat(&token::Semi) {
5897 let prev_span = self.prev_span;
5898 self.span_err(prev_span,
5899 "macros that expand to items must either \
5900 be surrounded with braces or followed by \
5905 let hi = self.prev_span;
5906 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
5907 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
5908 return Ok(Some(item));
5911 // FAILURE TO PARSE ITEM
5913 Visibility::Inherited => {}
5915 let prev_span = self.prev_span;
5916 return Err(self.span_fatal(prev_span, "unmatched visibility `pub`"));
5920 if !attributes_allowed && !attrs.is_empty() {
5921 self.expected_item_err(&attrs);
5926 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
5927 let attrs = self.parse_outer_attributes()?;
5928 self.parse_item_(attrs, true, false)
5931 fn parse_path_list_items(&mut self) -> PResult<'a, Vec<ast::PathListItem>> {
5932 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
5933 &token::CloseDelim(token::Brace),
5934 SeqSep::trailing_allowed(token::Comma), |this| {
5936 let ident = if this.eat_keyword(keywords::SelfValue) {
5937 keywords::SelfValue.ident()
5941 let rename = this.parse_rename()?;
5942 let node = ast::PathListItem_ {
5945 id: ast::DUMMY_NODE_ID
5947 Ok(respan(lo.to(this.prev_span), node))
5952 fn is_import_coupler(&mut self) -> bool {
5953 self.check(&token::ModSep) &&
5954 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
5955 *t == token::BinOp(token::Star))
5958 /// Matches ViewPath:
5959 /// MOD_SEP? non_global_path
5960 /// MOD_SEP? non_global_path as IDENT
5961 /// MOD_SEP? non_global_path MOD_SEP STAR
5962 /// MOD_SEP? non_global_path MOD_SEP LBRACE item_seq RBRACE
5963 /// MOD_SEP? LBRACE item_seq RBRACE
5964 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
5966 if self.check(&token::OpenDelim(token::Brace)) || self.check(&token::BinOp(token::Star)) ||
5967 self.is_import_coupler() {
5968 // `{foo, bar}`, `::{foo, bar}`, `*`, or `::*`.
5969 self.eat(&token::ModSep);
5970 let prefix = ast::Path {
5971 segments: vec![PathSegment::crate_root()],
5972 span: lo.to(self.span),
5974 let view_path_kind = if self.eat(&token::BinOp(token::Star)) {
5975 ViewPathGlob(prefix)
5977 ViewPathList(prefix, self.parse_path_list_items()?)
5979 Ok(P(respan(lo.to(self.span), view_path_kind)))
5981 let prefix = self.parse_path(PathStyle::Mod)?.default_to_global();
5982 if self.is_import_coupler() {
5983 // `foo::bar::{a, b}` or `foo::bar::*`
5985 if self.check(&token::BinOp(token::Star)) {
5987 Ok(P(respan(lo.to(self.span), ViewPathGlob(prefix))))
5989 let items = self.parse_path_list_items()?;
5990 Ok(P(respan(lo.to(self.span), ViewPathList(prefix, items))))
5993 // `foo::bar` or `foo::bar as baz`
5994 let rename = self.parse_rename()?.
5995 unwrap_or(prefix.segments.last().unwrap().identifier);
5996 Ok(P(respan(lo.to(self.prev_span), ViewPathSimple(rename, prefix))))
6001 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6002 if self.eat_keyword(keywords::As) {
6003 self.parse_ident().map(Some)
6009 /// Parses a source module as a crate. This is the main
6010 /// entry point for the parser.
6011 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6014 attrs: self.parse_inner_attributes()?,
6015 module: self.parse_mod_items(&token::Eof, lo)?,
6016 span: lo.to(self.span),
6020 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6021 let ret = match self.token {
6022 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6023 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6030 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6031 match self.parse_optional_str() {
6032 Some((s, style, suf)) => {
6033 let sp = self.prev_span;
6034 self.expect_no_suffix(sp, "string literal", suf);
6037 _ => Err(self.fatal("expected string literal"))