diff options
| author | Mark Rousskov <mark.simulacrum@gmail.com> | 2019-12-22 17:42:04 -0500 |
|---|---|---|
| committer | Mark Rousskov <mark.simulacrum@gmail.com> | 2019-12-22 17:42:47 -0500 |
| commit | a06baa56b95674fc626b3c3fd680d6a65357fe60 (patch) | |
| tree | cd9d867c2ca3cff5c1d6b3bd73377c44649fb075 /src/librustc_parse/parser | |
| parent | 8eb7c58dbb7b32701af113bc58722d0d1fefb1eb (diff) | |
| download | rust-a06baa56b95674fc626b3c3fd680d6a65357fe60.tar.gz rust-a06baa56b95674fc626b3c3fd680d6a65357fe60.zip | |
Format the world
Diffstat (limited to 'src/librustc_parse/parser')
| -rw-r--r-- | src/librustc_parse/parser/attr.rs | 69 | ||||
| -rw-r--r-- | src/librustc_parse/parser/diagnostics.rs | 359 | ||||
| -rw-r--r-- | src/librustc_parse/parser/expr.rs | 630 | ||||
| -rw-r--r-- | src/librustc_parse/parser/generics.rs | 113 | ||||
| -rw-r--r-- | src/librustc_parse/parser/item.rs | 550 | ||||
| -rw-r--r-- | src/librustc_parse/parser/mod.rs | 325 | ||||
| -rw-r--r-- | src/librustc_parse/parser/module.rs | 108 | ||||
| -rw-r--r-- | src/librustc_parse/parser/pat.rs | 201 | ||||
| -rw-r--r-- | src/librustc_parse/parser/path.rs | 132 | ||||
| -rw-r--r-- | src/librustc_parse/parser/stmt.rs | 112 | ||||
| -rw-r--r-- | src/librustc_parse/parser/ty.rs | 61 |
11 files changed, 1257 insertions, 1403 deletions
diff --git a/src/librustc_parse/parser/attr.rs b/src/librustc_parse/parser/attr.rs index 51310fb88f6..377d43dec21 100644 --- a/src/librustc_parse/parser/attr.rs +++ b/src/librustc_parse/parser/attr.rs @@ -1,9 +1,9 @@ -use super::{Parser, TokenType, PathStyle}; +use super::{Parser, PathStyle, TokenType}; use rustc_errors::PResult; -use syntax::attr; use syntax::ast; -use syntax::util::comments; +use syntax::attr; use syntax::token::{self, Nonterminal}; +use syntax::util::comments; use syntax_pos::{Span, Symbol}; use log::debug; @@ -33,12 +33,11 @@ impl<'a> Parser<'a> { } else { DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG }; - let inner_parse_policy = - InnerAttributeParsePolicy::NotPermitted { - reason: inner_error_reason, - saw_doc_comment: just_parsed_doc_comment, - prev_attr_sp: attrs.last().and_then(|a| Some(a.span)) - }; + let inner_parse_policy = InnerAttributeParsePolicy::NotPermitted { + reason: inner_error_reason, + saw_doc_comment: just_parsed_doc_comment, + prev_attr_sp: attrs.last().and_then(|a| Some(a.span)), + }; let attr = self.parse_attribute_with_inner_parse_policy(inner_parse_policy)?; attrs.push(attr); just_parsed_doc_comment = false; @@ -47,8 +46,10 @@ impl<'a> Parser<'a> { let attr = self.mk_doc_comment(s); if attr.style != ast::AttrStyle::Outer { let mut err = self.fatal("expected outer doc comment"); - err.note("inner doc comments like this (starting with \ - `//!` or `/*!`) can only appear before items"); + err.note( + "inner doc comments like this (starting with \ + `//!` or `/*!`) can only appear before items", + ); return Err(err); } attrs.push(attr); @@ -71,16 +72,14 @@ impl<'a> Parser<'a> { /// If `permit_inner` is `true`, then a leading `!` indicates an inner /// attribute. pub fn parse_attribute(&mut self, permit_inner: bool) -> PResult<'a, ast::Attribute> { - debug!("parse_attribute: permit_inner={:?} self.token={:?}", - permit_inner, - self.token); + debug!("parse_attribute: permit_inner={:?} self.token={:?}", permit_inner, self.token); let inner_parse_policy = if permit_inner { InnerAttributeParsePolicy::Permitted } else { InnerAttributeParsePolicy::NotPermitted { reason: DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG, saw_doc_comment: false, - prev_attr_sp: None + prev_attr_sp: None, } }; self.parse_attribute_with_inner_parse_policy(inner_parse_policy) @@ -90,11 +89,12 @@ impl<'a> Parser<'a> { /// that prescribes how to handle inner attributes. fn parse_attribute_with_inner_parse_policy( &mut self, - inner_parse_policy: InnerAttributeParsePolicy<'_> + inner_parse_policy: InnerAttributeParsePolicy<'_>, ) -> PResult<'a, ast::Attribute> { - debug!("parse_attribute_with_inner_parse_policy: inner_parse_policy={:?} self.token={:?}", - inner_parse_policy, - self.token); + debug!( + "parse_attribute_with_inner_parse_policy: inner_parse_policy={:?} self.token={:?}", + inner_parse_policy, self.token + ); let (span, item, style) = match self.token.kind { token::Pound => { let lo = self.token.span; @@ -120,17 +120,19 @@ impl<'a> Parser<'a> { // Emit error if inner attribute is encountered and not permitted if style == ast::AttrStyle::Inner { - if let InnerAttributeParsePolicy::NotPermitted { reason, - saw_doc_comment, prev_attr_sp } = inner_parse_policy { + if let InnerAttributeParsePolicy::NotPermitted { + reason, + saw_doc_comment, + prev_attr_sp, + } = inner_parse_policy + { let prev_attr_note = if saw_doc_comment { "previous doc comment" } else { "previous outer attribute" }; - let mut diagnostic = self - .diagnostic() - .struct_span_err(attr_sp, reason); + let mut diagnostic = self.diagnostic().struct_span_err(attr_sp, reason); if let Some(prev_attr_sp) = prev_attr_sp { diagnostic @@ -139,10 +141,12 @@ impl<'a> Parser<'a> { } diagnostic - .note("inner attributes, like `#![no_std]`, annotate the item \ + .note( + "inner attributes, like `#![no_std]`, annotate the item \ enclosing them, and are usually found at the beginning of \ source files. Outer attributes, like `#[test]`, annotate the \ - item following them.") + item following them.", + ) .emit() } } @@ -226,11 +230,14 @@ impl<'a> Parser<'a> { if !lit.kind.is_unsuffixed() { let msg = "suffixed literals are not allowed in attributes"; - self.diagnostic().struct_span_err(lit.span, msg) - .help("instead of using a suffixed literal \ + self.diagnostic() + .struct_span_err(lit.span, msg) + .help( + "instead of using a suffixed literal \ (1u8, 1.0f32, etc.), use an unsuffixed version \ - (1, 1.0, etc.).") - .emit() + (1, 1.0, etc.).", + ) + .emit() } Ok(lit) @@ -288,7 +295,7 @@ impl<'a> Parser<'a> { Ok(meta) } None => self.unexpected(), - } + }; } let lo = self.token.span; diff --git a/src/librustc_parse/parser/diagnostics.rs b/src/librustc_parse/parser/diagnostics.rs index 353f6607c1d..f58b9a4c144 100644 --- a/src/librustc_parse/parser/diagnostics.rs +++ b/src/librustc_parse/parser/diagnostics.rs @@ -1,17 +1,19 @@ -use super::{BlockMode, PathStyle, SemiColonMode, TokenType, TokenExpectType, SeqSep, Parser}; +use super::{BlockMode, Parser, PathStyle, SemiColonMode, SeqSep, TokenExpectType, TokenType}; use rustc_data_structures::fx::FxHashSet; -use rustc_errors::{self, PResult, Applicability, DiagnosticBuilder, Handler, pluralize}; use rustc_error_codes::*; -use syntax::ast::{self, Param, BinOpKind, BindingMode, BlockCheckMode, Expr, ExprKind, Ident, Item}; -use syntax::ast::{ItemKind, Mutability, Pat, PatKind, PathSegment, QSelf, Ty, TyKind, AttrVec}; -use syntax::token::{self, TokenKind, token_can_begin_expr}; +use rustc_errors::{self, pluralize, Applicability, DiagnosticBuilder, Handler, PResult}; +use syntax::ast::{ + self, BinOpKind, BindingMode, BlockCheckMode, Expr, ExprKind, Ident, Item, Param, +}; +use syntax::ast::{AttrVec, ItemKind, Mutability, Pat, PatKind, PathSegment, QSelf, Ty, TyKind}; use syntax::print::pprust; use syntax::ptr::P; -use syntax::util::parser::AssocOp; use syntax::struct_span_err; +use syntax::token::{self, token_can_begin_expr, TokenKind}; +use syntax::util::parser::AssocOp; use syntax_pos::symbol::kw; -use syntax_pos::{Span, DUMMY_SP, MultiSpan, SpanSnippetError}; +use syntax_pos::{MultiSpan, Span, SpanSnippetError, DUMMY_SP}; use log::{debug, trace}; use std::mem; @@ -25,11 +27,7 @@ pub(super) fn dummy_arg(ident: Ident) -> Param { kind: PatKind::Ident(BindingMode::ByValue(Mutability::Not), ident, None), span: ident.span, }); - let ty = Ty { - kind: TyKind::Err, - span: ident.span, - id: ast::DUMMY_NODE_ID - }; + let ty = Ty { kind: TyKind::Err, span: ident.span, id: ast::DUMMY_NODE_ID }; Param { attrs: AttrVec::default(), id: ast::DUMMY_NODE_ID, @@ -57,11 +55,7 @@ pub enum Error { } impl Error { - fn span_err( - self, - sp: impl Into<MultiSpan>, - handler: &Handler, - ) -> DiagnosticBuilder<'_> { + fn span_err(self, sp: impl Into<MultiSpan>, handler: &Handler) -> DiagnosticBuilder<'_> { match self { Error::FileNotFoundForModule { ref mod_name, @@ -78,9 +72,7 @@ impl Error { ); err.help(&format!( "name the file either {} or {} inside the directory \"{}\"", - default_path, - secondary_path, - dir_path, + default_path, secondary_path, dir_path, )); err } @@ -104,17 +96,14 @@ impl Error { E0585, "found a documentation comment that doesn't document anything", ); - err.help("doc comments must come before what they document, maybe a comment was \ - intended with `//`?"); + err.help( + "doc comments must come before what they document, maybe a comment was \ + intended with `//`?", + ); err } Error::InclusiveRangeWithNoEnd => { - let mut err = struct_span_err!( - handler, - sp, - E0586, - "inclusive range with no end", - ); + let mut err = struct_span_err!(handler, sp, E0586, "inclusive range with no end",); err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)"); err } @@ -134,11 +123,7 @@ impl RecoverQPath for Ty { Some(P(self.clone())) } fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self { - Self { - span: path.span, - kind: TyKind::Path(qself, path), - id: ast::DUMMY_NODE_ID, - } + Self { span: path.span, kind: TyKind::Path(qself, path), id: ast::DUMMY_NODE_ID } } } @@ -147,11 +132,7 @@ impl RecoverQPath for Pat { self.to_ty() } fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self { - Self { - span: path.span, - kind: PatKind::Path(qself, path), - id: ast::DUMMY_NODE_ID, - } + Self { span: path.span, kind: PatKind::Path(qself, path), id: ast::DUMMY_NODE_ID } } } @@ -233,8 +214,8 @@ impl<'a> Parser<'a> { TokenKind::CloseDelim(token::DelimToken::Paren), ]; if let token::Ident(name, false) = self.token.kind { - if Ident::new(name, self.token.span).is_raw_guess() && - self.look_ahead(1, |t| valid_follow.contains(&t.kind)) + if Ident::new(name, self.token.span).is_raw_guess() + && self.look_ahead(1, |t| valid_follow.contains(&t.kind)) { err.span_suggestion( self.token.span, @@ -268,8 +249,7 @@ impl<'a> Parser<'a> { fn tokens_to_string(tokens: &[TokenType]) -> String { let mut i = tokens.iter(); // This might be a sign we need a connect method on `Iterator`. - let b = i.next() - .map_or(String::new(), |t| t.to_string()); + let b = i.next().map_or(String::new(), |t| t.to_string()); i.enumerate().fold(b, |mut b, (i, a)| { if tokens.len() > 2 && i == tokens.len() - 2 { b.push_str(", or "); @@ -283,7 +263,8 @@ impl<'a> Parser<'a> { }) } - let mut expected = edible.iter() + let mut expected = edible + .iter() .map(|x| TokenType::Token(x.clone())) .chain(inedible.iter().map(|x| TokenType::Token(x.clone()))) .chain(self.expected_tokens.iter().cloned()) @@ -298,16 +279,23 @@ impl<'a> Parser<'a> { } else { expect.clone() }; - (format!("expected one of {}, found {}", expect, actual), - (self.sess.source_map().next_point(self.prev_span), - format!("expected one of {}", short_expect))) + ( + format!("expected one of {}, found {}", expect, actual), + ( + self.sess.source_map().next_point(self.prev_span), + format!("expected one of {}", short_expect), + ), + ) } else if expected.is_empty() { - (format!("unexpected token: {}", actual), - (self.prev_span, "unexpected token after this".to_string())) + ( + format!("unexpected token: {}", actual), + (self.prev_span, "unexpected token after this".to_string()), + ) } else { - (format!("expected {}, found {}", expect, actual), - (self.sess.source_map().next_point(self.prev_span), - format!("expected {}", expect))) + ( + format!("expected {}, found {}", expect, actual), + (self.sess.source_map().next_point(self.prev_span), format!("expected {}", expect)), + ) }; self.last_unexpected_token_span = Some(self.token.span); let mut err = self.fatal(&msg_exp); @@ -317,10 +305,16 @@ impl<'a> Parser<'a> { } else { label_sp }; - match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt { - TokenType::Token(t) => Some(t.clone()), - _ => None, - }).collect::<Vec<_>>(), err) { + match self.recover_closing_delimiter( + &expected + .iter() + .filter_map(|tt| match tt { + TokenType::Token(t) => Some(t.clone()), + _ => None, + }) + .collect::<Vec<_>>(), + err, + ) { Err(e) => err = e, Ok(recovered) => { return Ok(recovered); @@ -391,10 +385,14 @@ impl<'a> Parser<'a> { } if allow_unstable { // Give extra information about type ascription only if it's a nightly compiler. - err.note("`#![feature(type_ascription)]` lets you annotate an expression with a \ - type: `<expr>: <type>`"); - err.note("for more information, see \ - https://github.com/rust-lang/rust/issues/23416"); + err.note( + "`#![feature(type_ascription)]` lets you annotate an expression with a \ + type: `<expr>: <type>`", + ); + err.note( + "for more information, see \ + https://github.com/rust-lang/rust/issues/23416", + ); } } } @@ -402,12 +400,11 @@ impl<'a> Parser<'a> { /// Eats and discards tokens until one of `kets` is encountered. Respects token trees, /// passes through any errors encountered. Used for error recovery. pub(super) fn eat_to_tokens(&mut self, kets: &[&TokenKind]) { - if let Err(ref mut err) = self.parse_seq_to_before_tokens( - kets, - SeqSep::none(), - TokenExpectType::Expect, - |p| Ok(p.parse_token_tree()), - ) { + if let Err(ref mut err) = + self.parse_seq_to_before_tokens(kets, SeqSep::none(), TokenExpectType::Expect, |p| { + Ok(p.parse_token_tree()) + }) + { err.cancel(); } } @@ -444,10 +441,8 @@ impl<'a> Parser<'a> { // have already been parsed): // // `x.foo::<u32>>>(3)` - let parsed_angle_bracket_args = segment.args - .as_ref() - .map(|args| args.is_angle_bracketed()) - .unwrap_or(false); + let parsed_angle_bracket_args = + segment.args.as_ref().map(|args| args.is_angle_bracketed()).unwrap_or(false); debug!( "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}", @@ -549,18 +544,15 @@ impl<'a> Parser<'a> { outer_op, ); - let mk_err_expr = |this: &Self, span| { - Ok(Some(this.mk_expr(span, ExprKind::Err, AttrVec::new()))) - }; + let mk_err_expr = + |this: &Self, span| Ok(Some(this.mk_expr(span, ExprKind::Err, AttrVec::new()))); match lhs.kind { ExprKind::Binary(op, _, _) if op.node.is_comparison() => { // Respan to include both operators. let op_span = op.span.to(self.prev_span); - let mut err = self.struct_span_err( - op_span, - "chained comparison operators require parentheses", - ); + let mut err = self + .struct_span_err(op_span, "chained comparison operators require parentheses"); let suggest = |err: &mut DiagnosticBuilder<'_>| { err.span_suggestion_verbose( @@ -573,23 +565,21 @@ impl<'a> Parser<'a> { if op.node == BinOpKind::Lt && *outer_op == AssocOp::Less || // Include `<` to provide this recommendation - *outer_op == AssocOp::Greater // even in a case like the following: - { // Foo<Bar<Baz<Qux, ()>>> + *outer_op == AssocOp::Greater + // even in a case like the following: + { + // Foo<Bar<Baz<Qux, ()>>> if *outer_op == AssocOp::Less { let snapshot = self.clone(); self.bump(); // So far we have parsed `foo<bar<`, consume the rest of the type args. - let modifiers = [ - (token::Lt, 1), - (token::Gt, -1), - (token::BinOp(token::Shr), -2), - ]; + let modifiers = + [(token::Lt, 1), (token::Gt, -1), (token::BinOp(token::Shr), -2)]; self.consume_tts(1, &modifiers[..]); - if !&[ - token::OpenDelim(token::Paren), - token::ModSep, - ].contains(&self.token.kind) { + if !&[token::OpenDelim(token::Paren), token::ModSep] + .contains(&self.token.kind) + { // We don't have `foo< bar >(` or `foo< bar >::`, so we rewind the // parser and bail out. mem::replace(self, snapshot.clone()); @@ -657,10 +647,8 @@ impl<'a> Parser<'a> { self.bump(); // `(` // Consume the fn call arguments. - let modifiers = [ - (token::OpenDelim(token::Paren), 1), - (token::CloseDelim(token::Paren), -1), - ]; + let modifiers = + [(token::OpenDelim(token::Paren), 1), (token::CloseDelim(token::Paren), -1)]; self.consume_tts(1, &modifiers[..]); if self.token.kind == token::Eof { @@ -769,16 +757,11 @@ impl<'a> Parser<'a> { ) -> PResult<'a, P<T>> { self.expect(&token::ModSep)?; - let mut path = ast::Path { - segments: Vec::new(), - span: DUMMY_SP, - }; + let mut path = ast::Path { segments: Vec::new(), span: DUMMY_SP }; self.parse_path_segments(&mut path.segments, T::PATH_STYLE)?; path.span = ty_span.to(self.prev_span); - let ty_str = self - .span_to_snippet(ty_span) - .unwrap_or_else(|_| pprust::ty_to_string(&ty)); + let ty_str = self.span_to_snippet(ty_span).unwrap_or_else(|_| pprust::ty_to_string(&ty)); self.diagnostic() .struct_span_err(path.span, "missing angle brackets in associated item path") .span_suggestion( @@ -791,14 +774,7 @@ impl<'a> Parser<'a> { .emit(); let path_span = ty_span.shrink_to_hi(); // Use an empty path since `position == 0`. - Ok(P(T::recovered( - Some(QSelf { - ty, - path_span, - position: 0, - }), - path, - ))) + Ok(P(T::recovered(Some(QSelf { ty, path_span, position: 0 }), path))) } pub(super) fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool { @@ -822,10 +798,7 @@ impl<'a> Parser<'a> { _ => None, }; if let Some(name) = previous_item_kind_name { - err.help(&format!( - "{} declarations are not followed by a semicolon", - name - )); + err.help(&format!("{} declarations are not followed by a semicolon", name)); } } err.emit(); @@ -896,9 +869,11 @@ impl<'a> Parser<'a> { return self.expect(&token::Semi).map(|_| ()); } else if !sm.is_multiline(self.prev_span.until(self.token.span)) { // The current token is in the same line as the prior token, not recoverable. - } else if self.look_ahead(1, |t| t == &token::CloseDelim(token::Brace) - || token_can_begin_expr(t) && t.kind != token::Colon - ) && [token::Comma, token::Colon].contains(&self.token.kind) { + } else if self.look_ahead(1, |t| { + t == &token::CloseDelim(token::Brace) + || token_can_begin_expr(t) && t.kind != token::Colon + }) && [token::Comma, token::Colon].contains(&self.token.kind) + { // Likely typo: `,` → `;` or `:` → `;`. This is triggered if the current token is // either `,` or `:`, and the next token could either start a new statement or is a // block close. For example: @@ -910,12 +885,14 @@ impl<'a> Parser<'a> { self.struct_span_err(sp, &msg) .span_suggestion(sp, "change this to `;`", ";".to_string(), appl) .emit(); - return Ok(()) - } else if self.look_ahead(0, |t| t == &token::CloseDelim(token::Brace) || ( - token_can_begin_expr(t) - && t != &token::Semi - && t != &token::Pound // Avoid triggering with too many trailing `#` in raw string. - )) { + return Ok(()); + } else if self.look_ahead(0, |t| { + t == &token::CloseDelim(token::Brace) + || ( + token_can_begin_expr(t) && t != &token::Semi && t != &token::Pound + // Avoid triggering with too many trailing `#` in raw string. + ) + }) { // Missing semicolon typo. This is triggered if the next token could either start a // new statement or is a block close. For example: // @@ -926,7 +903,7 @@ impl<'a> Parser<'a> { .span_label(self.token.span, "unexpected token") .span_suggestion_short(sp, "add `;` here", ";".to_string(), appl) .emit(); - return Ok(()) + return Ok(()); } self.expect(&token::Semi).map(|_| ()) // Error unconditionally } @@ -947,12 +924,17 @@ impl<'a> Parser<'a> { .span_label( extern_sp, "`extern` blocks define existing foreign functions and `fn`s \ - inside of them cannot have a body") - .help("you might have meant to write a function accessible through ffi, \ + inside of them cannot have a body", + ) + .help( + "you might have meant to write a function accessible through ffi, \ which can be done by writing `extern fn` outside of the \ - `extern` block") - .note("for more information, visit \ - https://doc.rust-lang.org/std/keyword.extern.html") + `extern` block", + ) + .note( + "for more information, visit \ + https://doc.rust-lang.org/std/keyword.extern.html", + ) .emit(); } Err(mut err) => { @@ -1000,15 +982,11 @@ impl<'a> Parser<'a> { // Handle `await { <expr> }`. // This needs to be handled separatedly from the next arm to avoid // interpreting `await { <expr> }?` as `<expr>?.await`. - self.parse_block_expr( - None, - self.token.span, - BlockCheckMode::Default, - AttrVec::new(), - ) + self.parse_block_expr(None, self.token.span, BlockCheckMode::Default, AttrVec::new()) } else { self.parse_expr() - }.map_err(|mut err| { + } + .map_err(|mut err| { err.span_label(await_sp, "while parsing this incorrect await expression"); err })?; @@ -1016,8 +994,8 @@ impl<'a> Parser<'a> { } fn error_on_incorrect_await(&self, lo: Span, hi: Span, expr: &Expr, is_question: bool) -> Span { - let expr_str = self.span_to_snippet(expr.span) - .unwrap_or_else(|_| pprust::expr_to_string(&expr)); + let expr_str = + self.span_to_snippet(expr.span).unwrap_or_else(|_| pprust::expr_to_string(&expr)); let suggestion = format!("{}.await{}", expr_str, if is_question { "?" } else { "" }); let sp = lo.to(hi); let app = match expr.kind { @@ -1032,8 +1010,8 @@ impl<'a> Parser<'a> { /// If encountering `future.await()`, consumes and emits an error. pub(super) fn recover_from_await_method_call(&mut self) { - if self.token == token::OpenDelim(token::Paren) && - self.look_ahead(1, |t| t == &token::CloseDelim(token::Paren)) + if self.token == token::OpenDelim(token::Paren) + && self.look_ahead(1, |t| t == &token::CloseDelim(token::Paren)) { // future.await() let lo = self.token.span; @@ -1046,7 +1024,8 @@ impl<'a> Parser<'a> { "`await` is not a method call, remove the parentheses", String::new(), Applicability::MachineApplicable, - ).emit() + ) + .emit() } } @@ -1094,23 +1073,22 @@ impl<'a> Parser<'a> { pub(super) fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool { (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish. - self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) - ) || - self.token.is_ident() && + self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())) + || self.token.is_ident() && match node { // `foo::` → `foo:` or `foo.bar::` → `foo.bar:` ast::ExprKind::Path(..) | ast::ExprKind::Field(..) => true, _ => false, } && !self.token.is_reserved_ident() && // v `foo:bar(baz)` - self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren)) || - self.look_ahead(1, |t| t == &token::Lt) && // `foo:bar<baz` - self.look_ahead(2, |t| t.is_ident()) || - self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz` - self.look_ahead(2, |t| t.is_ident()) || - self.look_ahead(1, |t| t == &token::ModSep) && - (self.look_ahead(2, |t| t.is_ident()) || // `foo:bar::baz` - self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>` + self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren)) + || self.look_ahead(1, |t| t == &token::Lt) && // `foo:bar<baz` + self.look_ahead(2, |t| t.is_ident()) + || self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz` + self.look_ahead(2, |t| t.is_ident()) + || self.look_ahead(1, |t| t == &token::ModSep) + && (self.look_ahead(2, |t| t.is_ident()) || // `foo:bar::baz` + self.look_ahead(2, |t| t == &token::Lt)) // `foo:bar::<baz>` } pub(super) fn recover_seq_parse_error( @@ -1150,7 +1128,7 @@ impl<'a> Parser<'a> { // this location. Emit the diagnostic and act as if the delimiter was // present for the parser's sake. - // Don't attempt to recover from this unclosed delimiter more than once. + // Don't attempt to recover from this unclosed delimiter more than once. let unmatched = self.unclosed_delims.remove(pos); let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim)); if unmatched.found_delim.is_none() { @@ -1184,7 +1162,7 @@ impl<'a> Parser<'a> { Err(err) } else { err.emit(); - self.expected_tokens.clear(); // Reduce the number of errors. + self.expected_tokens.clear(); // Reduce the number of errors. Ok(true) } } @@ -1215,17 +1193,15 @@ impl<'a> Parser<'a> { let mut brace_depth = 0; let mut bracket_depth = 0; let mut in_block = false; - debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", - break_on_semi, break_on_block); + debug!("recover_stmt_ enter loop (semi={:?}, block={:?})", break_on_semi, break_on_block); loop { debug!("recover_stmt_ loop {:?}", self.token); match self.token.kind { token::OpenDelim(token::DelimToken::Brace) => { brace_depth += 1; self.bump(); - if break_on_block == BlockMode::Break && - brace_depth == 1 && - bracket_depth == 0 { + if break_on_block == BlockMode::Break && brace_depth == 1 && bracket_depth == 0 + { in_block = true; } } @@ -1258,23 +1234,23 @@ impl<'a> Parser<'a> { } token::Semi => { self.bump(); - if break_on_semi == SemiColonMode::Break && - brace_depth == 0 && - bracket_depth == 0 { + if break_on_semi == SemiColonMode::Break + && brace_depth == 0 + && bracket_depth == 0 + { debug!("recover_stmt_ return - Semi"); break; } } - token::Comma if break_on_semi == SemiColonMode::Comma && - brace_depth == 0 && - bracket_depth == 0 => + token::Comma + if break_on_semi == SemiColonMode::Comma + && brace_depth == 0 + && bracket_depth == 0 => { debug!("recover_stmt_ return - Semi"); break; } - _ => { - self.bump() - } + _ => self.bump(), } } } @@ -1309,9 +1285,9 @@ impl<'a> Parser<'a> { .span_label(self.token.span, "doc comments are not allowed here") .emit(); self.bump(); - } else if self.token == token::Pound && self.look_ahead(1, |t| { - *t == token::OpenDelim(token::Bracket) - }) { + } else if self.token == token::Pound + && self.look_ahead(1, |t| *t == token::OpenDelim(token::Bracket)) + { let lo = self.token.span; // Skip every token until next possible arg. while self.token != token::CloseDelim(token::Bracket) { @@ -1319,12 +1295,9 @@ impl<'a> Parser<'a> { } let sp = lo.to(self.token.span); self.bump(); - self.struct_span_err( - sp, - "attributes cannot be applied to a function parameter's type", - ) - .span_label(sp, "attributes are not allowed here") - .emit(); + self.struct_span_err(sp, "attributes cannot be applied to a function parameter's type") + .span_label(sp, "attributes are not allowed here") + .emit(); } } @@ -1338,9 +1311,10 @@ impl<'a> Parser<'a> { ) -> Option<Ident> { // If we find a pattern followed by an identifier, it could be an (incorrect) // C-style parameter declaration. - if self.check_ident() && self.look_ahead(1, |t| { - *t == token::Comma || *t == token::CloseDelim(token::Paren) - }) { // `fn foo(String s) {}` + if self.check_ident() + && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseDelim(token::Paren)) + { + // `fn foo(String s) {}` let ident = self.parse_ident().unwrap(); let span = pat.span.with_hi(ident.span.hi()); @@ -1352,12 +1326,13 @@ impl<'a> Parser<'a> { ); return Some(ident); } else if let PatKind::Ident(_, ident, _) = pat.kind { - if require_name && ( - is_trait_item || - self.token == token::Comma || - self.token == token::Lt || - self.token == token::CloseDelim(token::Paren) - ) { // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}` + if require_name + && (is_trait_item + || self.token == token::Comma + || self.token == token::Lt + || self.token == token::CloseDelim(token::Paren)) + { + // `fn foo(a, b) {}`, `fn foo(a<x>, b<y>) {}` or `fn foo(usize, usize) {}` if is_self_allowed { err.span_suggestion( pat.span, @@ -1411,11 +1386,7 @@ impl<'a> Parser<'a> { .emit(); // Pretend the pattern is `_`, to avoid duplicate errors from AST validation. - let pat = P(Pat { - kind: PatKind::Wild, - span: pat.span, - id: ast::DUMMY_NODE_ID - }); + let pat = P(Pat { kind: PatKind::Wild, span: pat.span, id: ast::DUMMY_NODE_ID }); Ok((pat, ty)) } @@ -1474,10 +1445,10 @@ impl<'a> Parser<'a> { let sp = self.sess.source_map().next_point(self.token.span); (sp, format!("expected expression, found end of {}", origin)) } - _ => (self.token.span, format!( - "expected expression, found {}", - self.this_token_descr(), - )), + _ => ( + self.token.span, + format!("expected expression, found {}", self.this_token_descr(),), + ), }; let mut err = self.struct_span_err(span, &msg); let sp = self.sess.source_map().start_point(self.token.span); @@ -1516,9 +1487,9 @@ impl<'a> Parser<'a> { pub(super) fn deduplicate_recovered_params_names(&self, fn_inputs: &mut Vec<Param>) { let mut seen_inputs = FxHashSet::default(); for input in fn_inputs.iter_mut() { - let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) = ( - &input.pat.kind, &input.ty.kind, - ) { + let opt_ident = if let (PatKind::Ident(_, ident, _), TyKind::Err) = + (&input.pat.kind, &input.ty.kind) + { Some(*ident) } else { None diff --git a/src/librustc_parse/parser/expr.rs b/src/librustc_parse/parser/expr.rs index 71c9e58f58f..fa68ddf272a 100644 --- a/src/librustc_parse/parser/expr.rs +++ b/src/librustc_parse/parser/expr.rs @@ -1,22 +1,24 @@ -use super::{Parser, Restrictions, PrevTokenKind, TokenType, PathStyle, BlockMode}; -use super::{SemiColonMode, SeqSep, TokenExpectType}; -use super::pat::{GateOr, PARAM_EXPECTED}; use super::diagnostics::Error; +use super::pat::{GateOr, PARAM_EXPECTED}; +use super::{BlockMode, Parser, PathStyle, PrevTokenKind, Restrictions, TokenType}; +use super::{SemiColonMode, SeqSep, TokenExpectType}; use crate::maybe_recover_from_interpolated_ty_qpath; -use rustc_errors::{PResult, Applicability}; -use syntax::ast::{self, DUMMY_NODE_ID, AttrVec, AttrStyle, Ident, CaptureBy, Field, Lit}; -use syntax::ast::{BlockCheckMode, Expr, ExprKind, RangeLimits, Label, Movability, IsAsync, Arm}; -use syntax::ast::{Ty, TyKind, FunctionRetTy, Param, FnDecl, BinOpKind, BinOp, UnOp, Mac, AnonConst}; -use syntax::token::{self, Token, TokenKind}; +use rustc_errors::{Applicability, PResult}; +use std::mem; +use syntax::ast::{self, AttrStyle, AttrVec, CaptureBy, Field, Ident, Lit, DUMMY_NODE_ID}; +use syntax::ast::{ + AnonConst, BinOp, BinOpKind, FnDecl, FunctionRetTy, Mac, Param, Ty, TyKind, UnOp, +}; +use syntax::ast::{Arm, BlockCheckMode, Expr, ExprKind, IsAsync, Label, Movability, RangeLimits}; use syntax::print::pprust; use syntax::ptr::P; +use syntax::token::{self, Token, TokenKind}; use syntax::util::classify; use syntax::util::literal::LitError; -use syntax::util::parser::{AssocOp, Fixity, prec_let_scrutinee_needs_par}; +use syntax::util::parser::{prec_let_scrutinee_needs_par, AssocOp, Fixity}; use syntax_pos::source_map::{self, Span}; use syntax_pos::symbol::{kw, sym, Symbol}; -use std::mem; /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression /// dropped into the token stream, which happens while parsing the result of @@ -36,21 +38,25 @@ macro_rules! maybe_whole_expr { let path = path.clone(); $p.bump(); return Ok($p.mk_expr( - $p.token.span, ExprKind::Path(None, path), AttrVec::new() + $p.token.span, + ExprKind::Path(None, path), + AttrVec::new(), )); } token::NtBlock(block) => { let block = block.clone(); $p.bump(); return Ok($p.mk_expr( - $p.token.span, ExprKind::Block(block, None), AttrVec::new() + $p.token.span, + ExprKind::Block(block, None), + AttrVec::new(), )); } // N.B., `NtIdent(ident)` is normalized to `Ident` in `fn bump`. - _ => {}, + _ => {} }; } - } + }; } #[derive(Debug)] @@ -66,11 +72,7 @@ impl From<Option<AttrVec>> for LhsExpr { /// /// This conversion does not allocate. fn from(o: Option<AttrVec>) -> Self { - if let Some(attrs) = o { - LhsExpr::AttributesParsed(attrs) - } else { - LhsExpr::NotYetParsed - } + if let Some(attrs) = o { LhsExpr::AttributesParsed(attrs) } else { LhsExpr::NotYetParsed } } } @@ -99,9 +101,8 @@ impl<'a> Parser<'a> { Ok(expr) => Ok(expr), Err(mut err) => match self.token.kind { token::Ident(name, false) - if name == kw::Underscore && self.look_ahead(1, |t| { - t == &token::Comma - }) => { + if name == kw::Underscore && self.look_ahead(1, |t| t == &token::Comma) => + { // Special-case handling of `foo(_, _, _)` err.emit(); let sp = self.token.span; @@ -115,9 +116,7 @@ impl<'a> Parser<'a> { /// Parses a sequence of expressions delimited by parentheses. fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec<P<Expr>>> { - self.parse_paren_comma_seq(|p| { - p.parse_expr_catch_underscore() - }).map(|(r, _)| r) + self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore()).map(|(r, _)| r) } /// Parses an expression, subject to the given restrictions. @@ -125,7 +124,7 @@ impl<'a> Parser<'a> { pub(super) fn parse_expr_res( &mut self, r: Restrictions, - already_parsed_attrs: Option<AttrVec> + already_parsed_attrs: Option<AttrVec>, ) -> PResult<'a, P<Expr>> { self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs)) } @@ -135,10 +134,7 @@ impl<'a> Parser<'a> { /// This parses an expression accounting for associativity and precedence of the operators in /// the expression. #[inline] - fn parse_assoc_expr( - &mut self, - already_parsed_attrs: Option<AttrVec>, - ) -> PResult<'a, P<Expr>> { + fn parse_assoc_expr(&mut self, already_parsed_attrs: Option<AttrVec>) -> PResult<'a, P<Expr>> { self.parse_assoc_expr_with(0, already_parsed_attrs.into()) } @@ -177,7 +173,10 @@ impl<'a> Parser<'a> { let lhs_span = match (self.prev_token_kind, &lhs.kind) { (PrevTokenKind::Interpolated, _) => self.prev_span, (PrevTokenKind::Ident, &ExprKind::Path(None, ref path)) - if path.segments.len() == 1 => self.prev_span, + if path.segments.len() == 1 => + { + self.prev_span + } _ => lhs.span, }; @@ -209,14 +208,14 @@ impl<'a> Parser<'a> { // Special cases: if op == AssocOp::As { lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?; - continue + continue; } else if op == AssocOp::Colon { let maybe_path = self.could_ascription_be_path(&lhs.kind); self.last_type_ascription = Some((self.prev_span, maybe_path)); lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?; self.sess.gated_spans.gate(sym::type_ascription, lhs.span); - continue + continue; } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq { // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to // generalise it to the Fixity::None code. @@ -228,20 +227,14 @@ impl<'a> Parser<'a> { } else { None }; - let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs { - x.span - } else { - cur_op_span - }); - let limits = if op == AssocOp::DotDot { - RangeLimits::HalfOpen - } else { - RangeLimits::Closed - }; + let (lhs_span, rhs_span) = + (lhs.span, if let Some(ref x) = rhs { x.span } else { cur_op_span }); + let limits = + if op == AssocOp::DotDot { RangeLimits::HalfOpen } else { RangeLimits::Closed }; let r = self.mk_range(Some(lhs), rhs, limits)?; lhs = self.mk_expr(lhs_span.to(rhs_span), r, AttrVec::new()); - break + break; } let fixity = op.fixity(); @@ -252,10 +245,9 @@ impl<'a> Parser<'a> { // the special cases. The code is here only for future convenience. Fixity::None => 1, }; - let rhs = self.with_res( - restrictions - Restrictions::STMT_EXPR, - |this| this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed) - )?; + let rhs = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| { + this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed) + })?; // Make sure that the span of the parent node is larger than the span of lhs and rhs, // including the attributes. @@ -267,11 +259,24 @@ impl<'a> Parser<'a> { .map_or(lhs_span, |a| a.span); let span = lhs_span.to(rhs.span); lhs = match op { - AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide | - AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor | - AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight | - AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual | - AssocOp::Greater | AssocOp::GreaterEqual => { + AssocOp::Add + | AssocOp::Subtract + | AssocOp::Multiply + | AssocOp::Divide + | AssocOp::Modulus + | AssocOp::LAnd + | AssocOp::LOr + | AssocOp::BitXor + | AssocOp::BitAnd + | AssocOp::BitOr + | AssocOp::ShiftLeft + | AssocOp::ShiftRight + | AssocOp::Equal + | AssocOp::Less + | AssocOp::LessEqual + | AssocOp::NotEqual + | AssocOp::Greater + | AssocOp::GreaterEqual => { let ast_op = op.to_ast_binop().unwrap(); let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs); self.mk_expr(span, binary, AttrVec::new()) @@ -279,16 +284,16 @@ impl<'a> Parser<'a> { AssocOp::Assign => self.mk_expr(span, ExprKind::Assign(lhs, rhs), AttrVec::new()), AssocOp::AssignOp(k) => { let aop = match k { - token::Plus => BinOpKind::Add, - token::Minus => BinOpKind::Sub, - token::Star => BinOpKind::Mul, - token::Slash => BinOpKind::Div, + token::Plus => BinOpKind::Add, + token::Minus => BinOpKind::Sub, + token::Star => BinOpKind::Mul, + token::Slash => BinOpKind::Div, token::Percent => BinOpKind::Rem, - token::Caret => BinOpKind::BitXor, - token::And => BinOpKind::BitAnd, - token::Or => BinOpKind::BitOr, - token::Shl => BinOpKind::Shl, - token::Shr => BinOpKind::Shr, + token::Caret => BinOpKind::BitXor, + token::And => BinOpKind::BitAnd, + token::Or => BinOpKind::BitOr, + token::Shl => BinOpKind::Shl, + token::Shr => BinOpKind::Shr, }; let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs); self.mk_expr(span, aopexpr, AttrVec::new()) @@ -298,7 +303,9 @@ impl<'a> Parser<'a> { } }; - if let Fixity::None = fixity { break } + if let Fixity::None = fixity { + break; + } } if last_type_ascription_set { self.last_type_ascription = None; @@ -339,10 +346,10 @@ impl<'a> Parser<'a> { /// but the next token implies this should be parsed as an expression. /// For example: `if let Some(x) = x { x } else { 0 } / 2`. fn error_found_expr_would_be_stmt(&self, lhs: &Expr) { - let mut err = self.struct_span_err(self.token.span, &format!( - "expected expression, found `{}`", - pprust::token_to_string(&self.token), - )); + let mut err = self.struct_span_err( + self.token.span, + &format!("expected expression, found `{}`", pprust::token_to_string(&self.token),), + ); err.span_label(self.token.span, "expected expression"); self.sess.expr_parentheses_needed(&mut err, lhs.span, Some(pprust::expr_to_string(&lhs))); err.emit(); @@ -382,8 +389,8 @@ impl<'a> Parser<'a> { /// Checks if this expression is a successfully parsed statement. fn expr_is_complete(&self, e: &Expr) -> bool { - self.restrictions.contains(Restrictions::STMT_EXPR) && - !classify::expr_requires_semi_to_be_stmt(e) + self.restrictions.contains(Restrictions::STMT_EXPR) + && !classify::expr_requires_semi_to_be_stmt(e) } fn is_at_start_of_range_notation_rhs(&self) -> bool { @@ -401,16 +408,18 @@ impl<'a> Parser<'a> { /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`. fn parse_prefix_range_expr( &mut self, - already_parsed_attrs: Option<AttrVec> + already_parsed_attrs: Option<AttrVec>, ) -> PResult<'a, P<Expr>> { // Check for deprecated `...` syntax. if self.token == token::DotDotDot { self.err_dotdotdot_syntax(self.token.span); } - debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind), - "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq", - self.token); + debug_assert!( + [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind), + "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq", + self.token + ); let tok = self.token.clone(); let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?; let lo = self.token.span; @@ -419,19 +428,14 @@ impl<'a> Parser<'a> { let opt_end = if self.is_at_start_of_range_notation_rhs() { // RHS must be parsed with more associativity than the dots. let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1; - Some(self.parse_assoc_expr_with(next_prec, LhsExpr::NotYetParsed) - .map(|x| { - hi = x.span; - x - })?) + Some(self.parse_assoc_expr_with(next_prec, LhsExpr::NotYetParsed).map(|x| { + hi = x.span; + x + })?) } else { None }; - let limits = if tok == token::DotDot { - RangeLimits::HalfOpen - } else { - RangeLimits::Closed - }; + let limits = if tok == token::DotDot { RangeLimits::HalfOpen } else { RangeLimits::Closed }; let r = self.mk_range(None, opt_end, limits)?; Ok(self.mk_expr(lo.to(hi), r, attrs)) @@ -460,7 +464,7 @@ impl<'a> Parser<'a> { span_of_tilde, "use `!` to perform bitwise not", "!".to_owned(), - Applicability::MachineApplicable + Applicability::MachineApplicable, ) .emit(); (lo.to(span), self.mk_unary(UnOp::Not, e)) @@ -477,9 +481,7 @@ impl<'a> Parser<'a> { let (span, e) = self.interpolated_or_expr_span(e)?; (lo.to(span), self.mk_unary(UnOp::Deref, e)) } - token::BinOp(token::And) | token::AndAnd => { - self.parse_address_of(lo)? - } + token::BinOp(token::And) | token::AndAnd => self.parse_address_of(lo)?, token::Ident(..) if self.token.is_keyword(kw::Box) => { self.bump(); let e = self.parse_prefix_expr(None); @@ -505,16 +507,15 @@ impl<'a> Parser<'a> { // Emit the error ... self.struct_span_err( self.token.span, - &format!("unexpected {} after identifier",self.this_token_descr()) + &format!("unexpected {} after identifier", self.this_token_descr()), ) .span_suggestion_short( // Span the `not` plus trailing whitespace to avoid // trailing whitespace after the `!` in our suggestion - self.sess.source_map() - .span_until_non_whitespace(lo.to(self.token.span)), + self.sess.source_map().span_until_non_whitespace(lo.to(self.token.span)), "use `!` to perform logical negation", "!".to_owned(), - Applicability::MachineApplicable + Applicability::MachineApplicable, ) .emit(); // —and recover! (just as if we were in the block @@ -526,7 +527,9 @@ impl<'a> Parser<'a> { return self.parse_dot_or_call_expr(Some(attrs)); } } - _ => { return self.parse_dot_or_call_expr(Some(attrs)); } + _ => { + return self.parse_dot_or_call_expr(Some(attrs)); + } }; return Ok(self.mk_expr(lo.to(hi), ex, attrs)); } @@ -545,9 +548,12 @@ impl<'a> Parser<'a> { }) } - fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span, - expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind) - -> PResult<'a, P<Expr>> { + fn parse_assoc_op_cast( + &mut self, + lhs: P<Expr>, + lhs_span: Span, + expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind, + ) -> PResult<'a, P<Expr>> { let mk_expr = |this: &mut Self, rhs: P<Ty>| { this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), AttrVec::new()) }; @@ -556,9 +562,7 @@ impl<'a> Parser<'a> { // LessThan comparison after this cast. let parser_snapshot_before_type = self.clone(); match self.parse_ty_no_plus() { - Ok(rhs) => { - Ok(mk_expr(self, rhs)) - } + Ok(rhs) => Ok(mk_expr(self, rhs)), Err(mut type_err) => { // Rewind to before attempting to parse the type with generics, to recover // from situations like `x as usize < y` in which we first tried to parse @@ -592,19 +596,23 @@ impl<'a> Parser<'a> { op_noun, ); let span_after_type = parser_snapshot_after_type.token.span; - let expr = mk_expr(self, P(Ty { - span: path.span, - kind: TyKind::Path(None, path), - id: DUMMY_NODE_ID, - })); + let expr = mk_expr( + self, + P(Ty { + span: path.span, + kind: TyKind::Path(None, path), + id: DUMMY_NODE_ID, + }), + ); - let expr_str = self.span_to_snippet(expr.span) + let expr_str = self + .span_to_snippet(expr.span) .unwrap_or_else(|_| pprust::expr_to_string(&expr)); self.struct_span_err(self.token.span, &msg) .span_label( self.look_ahead(1, |t| t.span).to(span_after_type), - "interpreted as generic arguments" + "interpreted as generic arguments", ) .span_label(self.token.span, format!("not interpreted as {}", op_noun)) .span_suggestion( @@ -631,9 +639,7 @@ impl<'a> Parser<'a> { /// Parse `& mut? <expr>` or `& raw [ const | mut ] <expr>`. fn parse_address_of(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> { self.expect_and()?; - let (k, m) = if self.check_keyword(kw::Raw) - && self.look_ahead(1, Token::is_mutability) - { + let (k, m) = if self.check_keyword(kw::Raw) && self.look_ahead(1, Token::is_mutability) { let found_raw = self.eat_keyword(kw::Raw); assert!(found_raw); let mutability = self.parse_const_or_mut().unwrap(); @@ -668,14 +674,14 @@ impl<'a> Parser<'a> { // Stitch the list of outer attributes onto the return value. // A little bit ugly, but the best way given the current code // structure - self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| + self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| { expr.map(|mut expr| { attrs.extend::<Vec<_>>(expr.attrs.into()); expr.attrs = attrs; self.error_attr_on_if_expr(&expr); expr }) - ) + }) } fn error_attr_on_if_expr(&self, expr: &Expr) { @@ -711,34 +717,33 @@ impl<'a> Parser<'a> { self.expect_no_suffix(span, "a tuple index", suffix); } token::Literal(token::Lit { kind: token::Float, symbol, .. }) => { - self.bump(); - let fstr = symbol.as_str(); - let msg = format!("unexpected token: `{}`", symbol); - let mut err = self.diagnostic().struct_span_err(self.prev_span, &msg); - err.span_label(self.prev_span, "unexpected token"); - if fstr.chars().all(|x| "0123456789.".contains(x)) { - let float = match fstr.parse::<f64>().ok() { - Some(f) => f, - None => continue, - }; - let sugg = pprust::to_string(|s| { - s.popen(); - s.print_expr(&e); - s.s.word( "."); - s.print_usize(float.trunc() as usize); - s.pclose(); - s.s.word("."); - s.s.word(fstr.splitn(2, ".").last().unwrap().to_string()) - }); - err.span_suggestion( - lo.to(self.prev_span), - "try parenthesizing the first index", - sugg, - Applicability::MachineApplicable - ); - } - return Err(err); - + self.bump(); + let fstr = symbol.as_str(); + let msg = format!("unexpected token: `{}`", symbol); + let mut err = self.diagnostic().struct_span_err(self.prev_span, &msg); + err.span_label(self.prev_span, "unexpected token"); + if fstr.chars().all(|x| "0123456789.".contains(x)) { + let float = match fstr.parse::<f64>().ok() { + Some(f) => f, + None => continue, + }; + let sugg = pprust::to_string(|s| { + s.popen(); + s.print_expr(&e); + s.s.word("."); + s.print_usize(float.trunc() as usize); + s.pclose(); + s.s.word("."); + s.s.word(fstr.splitn(2, ".").last().unwrap().to_string()) + }); + err.span_suggestion( + lo.to(self.prev_span), + "try parenthesizing the first index", + sugg, + Applicability::MachineApplicable, + ); + } + return Err(err); } _ => { // FIXME Could factor this out into non_fatal_unexpected or something. @@ -748,7 +753,9 @@ impl<'a> Parser<'a> { } continue; } - if self.expr_is_complete(&e) { break; } + if self.expr_is_complete(&e) { + break; + } match self.token.kind { // expr(...) token::OpenDelim(token::Paren) => { @@ -770,7 +777,7 @@ impl<'a> Parser<'a> { let index = self.mk_index(e, ix); e = self.mk_expr(lo.to(hi), index, AttrVec::new()) } - _ => return Ok(e) + _ => return Ok(e), } } return Ok(e); @@ -797,8 +804,7 @@ impl<'a> Parser<'a> { _ => { // Field access `expr.f` if let Some(args) = segment.args { - self.span_err(args.span(), - "field expressions may not have generic arguments"); + self.span_err(args.span(), "field expressions may not have generic arguments"); } let span = lo.to(self.prev_span); @@ -895,7 +901,8 @@ impl<'a> Parser<'a> { } else if self.token.span.rust_2018() { // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly. if self.check_keyword(kw::Async) { - if self.is_async_block() { // Check for `async {` and `async move {`. + if self.is_async_block() { + // Check for `async {` and `async move {`. self.parse_async_block(attrs) } else { self.parse_closure_expr(attrs) @@ -1010,22 +1017,20 @@ impl<'a> Parser<'a> { let lo = label.ident.span; self.expect(&token::Colon)?; if self.eat_keyword(kw::While) { - return self.parse_while_expr(Some(label), lo, attrs) + return self.parse_while_expr(Some(label), lo, attrs); } if self.eat_keyword(kw::For) { - return self.parse_for_expr(Some(label), lo, attrs) + return self.parse_for_expr(Some(label), lo, attrs); } if self.eat_keyword(kw::Loop) { - return self.parse_loop_expr(Some(label), lo, attrs) + return self.parse_loop_expr(Some(label), lo, attrs); } if self.token == token::OpenDelim(token::Brace) { return self.parse_block_expr(Some(label), lo, BlockCheckMode::Default, attrs); } let msg = "expected `while`, `for`, `loop` or `{` after a label"; - self.struct_span_err(self.token.span, msg) - .span_label(self.token.span, msg) - .emit(); + self.struct_span_err(self.token.span, msg).span_label(self.token.span, msg).emit(); // Continue as an expression in an effort to recover on `'label: non_block_expr`. self.parse_expr() } @@ -1053,11 +1058,7 @@ impl<'a> Parser<'a> { /// Parse an expression if the token can begin one. fn parse_expr_opt(&mut self) -> PResult<'a, Option<P<Expr>>> { - Ok(if self.token.can_begin_expr() { - Some(self.parse_expr()?) - } else { - None - }) + Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None }) } /// Parse `"return" expr?`. @@ -1107,7 +1108,7 @@ impl<'a> Parser<'a> { symbol_unescaped, }), _ => Err(Some(lit)), - } + }, None => Err(None), } } @@ -1127,8 +1128,9 @@ impl<'a> Parser<'a> { // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where // dot would follow an optional literal, so we do this unconditionally. recovered = self.look_ahead(1, |next_token| { - if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) - = next_token.kind { + if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = + next_token.kind + { if self.token.span.hi() == next_token.span.lo() { let s = String::from("0.") + &symbol.as_str(); let kind = TokenKind::lit(token::Float, Symbol::intern(&s), suffix); @@ -1156,9 +1158,7 @@ impl<'a> Parser<'a> { self.bump(); Some(lit) } - Err(LitError::NotLiteral) => { - None - } + Err(LitError::NotLiteral) => None, Err(err) => { let span = token.span; let lit = match token.kind { @@ -1180,9 +1180,7 @@ impl<'a> Parser<'a> { fn report_lit_error(&self, err: LitError, lit: token::Lit, span: Span) { // Checks if `s` looks like i32 or u1234 etc. fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool { - s.len() > 1 - && s.starts_with(first_chars) - && s[1..].chars().all(|c| c.is_ascii_digit()) + s.len() > 1 && s.starts_with(first_chars) && s[1..].chars().all(|c| c.is_ascii_digit()) } let token::Lit { kind, suffix, .. } = lit; @@ -1221,9 +1219,7 @@ impl<'a> Parser<'a> { if looks_like_width_suffix(&['f'], &suf) { // If it looks like a width, try to be helpful. let msg = format!("invalid width `{}` for float literal", &suf[1..]); - self.struct_span_err(span, &msg) - .help("valid widths are 32 and 64") - .emit(); + self.struct_span_err(span, &msg).help("valid widths are 32 and 64").emit(); } else { let msg = format!("invalid suffix `{}` for float literal", suf); self.struct_span_err(span, &msg) @@ -1244,8 +1240,7 @@ impl<'a> Parser<'a> { .emit(); } LitError::IntTooLarge => { - self.struct_span_err(span, "integer literal is too large") - .emit(); + self.struct_span_err(span, "integer literal is too large").emit(); } } } @@ -1257,10 +1252,10 @@ impl<'a> Parser<'a> { { // #59553: warn instead of reject out of hand to allow the fix to percolate // through the ecosystem when people fix their macros - let mut err = self.sess.span_diagnostic.struct_span_warn( - sp, - &format!("suffixes on {} are invalid", kind), - ); + let mut err = self + .sess + .span_diagnostic + .struct_span_warn(sp, &format!("suffixes on {} are invalid", kind)); err.note(&format!( "`{}` is *temporarily* accepted on tuple index fields as it was \ incorrectly accepted on stable for a few releases", @@ -1271,9 +1266,7 @@ impl<'a> Parser<'a> { `proc_macro::Literal::*_unsuffixed` for code that will desugar \ to tuple field access", ); - err.note( - "for more context, see https://github.com/rust-lang/rust/issues/60210", - ); + err.note("for more context, see https://github.com/rust-lang/rust/issues/60210"); err } else { self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind)) @@ -1328,17 +1321,11 @@ impl<'a> Parser<'a> { fn parse_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P<Expr>> { let lo = self.token.span; - let movability = if self.eat_keyword(kw::Static) { - Movability::Static - } else { - Movability::Movable - }; + let movability = + if self.eat_keyword(kw::Static) { Movability::Static } else { Movability::Movable }; - let asyncness = if self.token.span.rust_2018() { - self.parse_asyncness() - } else { - IsAsync::NotAsync - }; + let asyncness = + if self.token.span.rust_2018() { self.parse_asyncness() } else { IsAsync::NotAsync }; if asyncness.is_async() { // Feature-gate `async ||` closures. self.sess.gated_spans.gate(sym::async_closure, self.prev_span); @@ -1351,7 +1338,7 @@ impl<'a> Parser<'a> { FunctionRetTy::Default(_) => { let restrictions = self.restrictions - Restrictions::STMT_EXPR; self.parse_expr_res(restrictions, None)? - }, + } _ => { // If an explicit return type is given, require a block to appear (RFC 968). let body_lo = self.token.span; @@ -1362,16 +1349,13 @@ impl<'a> Parser<'a> { Ok(self.mk_expr( lo.to(body.span), ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)), - attrs)) + attrs, + )) } /// Parses an optional `move` prefix to a closure lke construct. fn parse_capture_clause(&mut self) -> CaptureBy { - if self.eat_keyword(kw::Move) { - CaptureBy::Value - } else { - CaptureBy::Ref - } + if self.eat_keyword(kw::Move) { CaptureBy::Value } else { CaptureBy::Ref } } /// Parses the `|arg, arg|` header of a closure. @@ -1381,22 +1365,21 @@ impl<'a> Parser<'a> { Vec::new() } else { self.expect(&token::BinOp(token::Or))?; - let args = self.parse_seq_to_before_tokens( - &[&token::BinOp(token::Or), &token::OrOr], - SeqSep::trailing_allowed(token::Comma), - TokenExpectType::NoExpect, - |p| p.parse_fn_block_param() - )?.0; + let args = self + .parse_seq_to_before_tokens( + &[&token::BinOp(token::Or), &token::OrOr], + SeqSep::trailing_allowed(token::Comma), + TokenExpectType::NoExpect, + |p| p.parse_fn_block_param(), + )? + .0; self.expect_or()?; args } }; let output = self.parse_ret_ty(true, true)?; - Ok(P(FnDecl { - inputs: inputs_captures, - output, - })) + Ok(P(FnDecl { inputs: inputs_captures, output })) } /// Parses a parameter in a closure header (e.g., `|arg, arg|`). @@ -1407,11 +1390,7 @@ impl<'a> Parser<'a> { let t = if self.eat(&token::Colon) { self.parse_ty()? } else { - P(Ty { - id: DUMMY_NODE_ID, - kind: TyKind::Infer, - span: self.prev_span, - }) + P(Ty { id: DUMMY_NODE_ID, kind: TyKind::Infer, span: self.prev_span }) }; let span = lo.to(self.token.span); Ok(Param { @@ -1435,10 +1414,10 @@ impl<'a> Parser<'a> { // the dead code lint. if self.eat_keyword(kw::Else) || !cond.returns() { let sp = self.sess.source_map().next_point(lo); - let mut err = self.diagnostic() - .struct_span_err(sp, "missing condition for `if` expression"); + let mut err = + self.diagnostic().struct_span_err(sp, "missing condition for `if` expression"); err.span_label(sp, "expected if condition here"); - return Err(err) + return Err(err); } let not_block = self.token != token::OpenDelim(token::Brace); let thn = self.parse_block().map_err(|mut err| { @@ -1475,10 +1454,9 @@ impl<'a> Parser<'a> { let lo = self.prev_span; let pat = self.parse_top_pat(GateOr::No)?; self.expect(&token::Eq)?; - let expr = self.with_res( - Restrictions::NO_STRUCT_LITERAL, - |this| this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into()) - )?; + let expr = self.with_res(Restrictions::NO_STRUCT_LITERAL, |this| { + this.parse_assoc_expr_with(1 + prec_let_scrutinee_needs_par(), None.into()) + })?; let span = lo.to(expr.span); self.sess.gated_spans.gate(sym::let_chains, span); Ok(self.mk_expr(span, ExprKind::Let(pat, expr), attrs)) @@ -1499,7 +1477,7 @@ impl<'a> Parser<'a> { &mut self, opt_label: Option<Label>, span_lo: Span, - mut attrs: AttrVec + mut attrs: AttrVec, ) -> PResult<'a, P<Expr>> { // Parse: `for <src_pat> in <src_expr> <src_loop_block>` @@ -1517,9 +1495,10 @@ impl<'a> Parser<'a> { self.struct_span_err(in_span, "missing `in` in `for` loop") .span_suggestion_short( in_span, - "try adding `in` here", " in ".into(), + "try adding `in` here", + " in ".into(), // has been misleading, at least in the past (closed Issue #48492) - Applicability::MaybeIncorrect + Applicability::MaybeIncorrect, ) .emit(); } @@ -1541,7 +1520,7 @@ impl<'a> Parser<'a> { &mut self, opt_label: Option<Label>, span_lo: Span, - mut attrs: AttrVec + mut attrs: AttrVec, ) -> PResult<'a, P<Expr>> { let cond = self.parse_cond_expr()?; let (iattrs, body) = self.parse_inner_attrs_and_block()?; @@ -1555,7 +1534,7 @@ impl<'a> Parser<'a> { &mut self, opt_label: Option<Label>, span_lo: Span, - mut attrs: AttrVec + mut attrs: AttrVec, ) -> PResult<'a, P<Expr>> { let (iattrs, body) = self.parse_inner_attrs_and_block()?; attrs.extend(iattrs); @@ -1584,10 +1563,10 @@ impl<'a> Parser<'a> { match_span, "try removing this `match`", String::new(), - Applicability::MaybeIncorrect // speculative + Applicability::MaybeIncorrect, // speculative ); } - return Err(e) + return Err(e); } attrs.extend(self.parse_inner_attributes()?); @@ -1616,20 +1595,15 @@ impl<'a> Parser<'a> { let attrs = self.parse_outer_attributes()?; let lo = self.token.span; let pat = self.parse_top_pat(GateOr::No)?; - let guard = if self.eat_keyword(kw::If) { - Some(self.parse_expr()?) - } else { - None - }; + let guard = if self.eat_keyword(kw::If) { Some(self.parse_expr()?) } else { None }; let arrow_span = self.token.span; self.expect(&token::FatArrow)?; let arm_start_span = self.token.span; - let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None) - .map_err(|mut err| { - err.span_label(arrow_span, "while parsing the `match` arm starting here"); - err - })?; + let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None).map_err(|mut err| { + err.span_label(arrow_span, "while parsing the `match` arm starting here"); + err + })?; let require_comma = classify::expr_requires_semi_to_be_stmt(&expr) && self.token != token::CloseDelim(token::Brace); @@ -1638,13 +1612,14 @@ impl<'a> Parser<'a> { if require_comma { let cm = self.sess.source_map(); - self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]) - .map_err(|mut err| { + self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]).map_err( + |mut err| { match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) { (Ok(ref expr_lines), Ok(ref arm_start_lines)) - if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col - && expr_lines.lines.len() == 2 - && self.token == token::FatArrow => { + if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col + && expr_lines.lines.len() == 2 + && self.token == token::FatArrow => + { // We check whether there's any trailing code in the parse span, // if there isn't, we very likely have the following: // @@ -1660,16 +1635,19 @@ impl<'a> Parser<'a> { cm.next_point(arm_start_span), "missing a comma here to end this `match` arm", ",".to_owned(), - Applicability::MachineApplicable + Applicability::MachineApplicable, ); } _ => { - err.span_label(arrow_span, - "while parsing the `match` arm starting here"); + err.span_label( + arrow_span, + "while parsing the `match` arm starting here", + ); } } err - })?; + }, + )?; } else { self.eat(&token::Comma); } @@ -1690,8 +1668,8 @@ impl<'a> Parser<'a> { let (iattrs, body) = self.parse_inner_attrs_and_block()?; attrs.extend(iattrs); if self.eat_keyword(kw::Catch) { - let mut error = self.struct_span_err(self.prev_span, - "keyword `catch` cannot follow a `try` block"); + let mut error = + self.struct_span_err(self.prev_span, "keyword `catch` cannot follow a `try` block"); error.help("try using `match` on the result of the `try` block instead"); error.emit(); Err(error) @@ -1703,10 +1681,10 @@ impl<'a> Parser<'a> { } fn is_do_catch_block(&self) -> bool { - self.token.is_keyword(kw::Do) && - self.is_keyword_ahead(1, &[kw::Catch]) && - self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) && - !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL) + self.token.is_keyword(kw::Do) + && self.is_keyword_ahead(1, &[kw::Catch]) + && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) + && !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL) } fn is_try_block(&self) -> bool { @@ -1726,19 +1704,21 @@ impl<'a> Parser<'a> { attrs.extend(iattrs); Ok(self.mk_expr( span_lo.to(body.span), - ExprKind::Async(capture_clause, DUMMY_NODE_ID, body), attrs)) + ExprKind::Async(capture_clause, DUMMY_NODE_ID, body), + attrs, + )) } fn is_async_block(&self) -> bool { - self.token.is_keyword(kw::Async) && - ( - ( // `async move {` - self.is_keyword_ahead(1, &[kw::Move]) && - self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) - ) || ( // `async {` + self.token.is_keyword(kw::Async) + && (( + // `async move {` + self.is_keyword_ahead(1, &[kw::Move]) + && self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) + ) || ( + // `async {` self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) - ) - ) + )) } fn maybe_parse_struct_expr( @@ -1748,34 +1728,35 @@ impl<'a> Parser<'a> { attrs: &AttrVec, ) -> Option<PResult<'a, P<Expr>>> { let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL); - let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && ( - // `{ ident, ` cannot start a block. - self.look_ahead(2, |t| t == &token::Comma) || - self.look_ahead(2, |t| t == &token::Colon) && ( - // `{ ident: token, ` cannot start a block. - self.look_ahead(4, |t| t == &token::Comma) || + let certainly_not_a_block = || { + self.look_ahead(1, |t| t.is_ident()) + && ( + // `{ ident, ` cannot start a block. + self.look_ahead(2, |t| t == &token::Comma) + || self.look_ahead(2, |t| t == &token::Colon) + && ( + // `{ ident: token, ` cannot start a block. + self.look_ahead(4, |t| t == &token::Comma) || // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`. self.look_ahead(3, |t| !t.can_begin_type()) - ) - ); + ) + ) + }; if struct_allowed || certainly_not_a_block() { // This is a struct literal, but we don't can't accept them here. let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone()); if let (Ok(expr), false) = (&expr, struct_allowed) { - self.struct_span_err( - expr.span, - "struct literals are not allowed here", - ) - .multipart_suggestion( - "surround the struct literal with parentheses", - vec![ - (lo.shrink_to_lo(), "(".to_string()), - (expr.span.shrink_to_hi(), ")".to_string()), - ], - Applicability::MachineApplicable, - ) - .emit(); + self.struct_span_err(expr.span, "struct literals are not allowed here") + .multipart_suggestion( + "surround the struct literal with parentheses", + vec![ + (lo.shrink_to_lo(), "(".to_string()), + (expr.span.shrink_to_hi(), ")".to_string()), + ], + Applicability::MachineApplicable, + ) + .emit(); } return Some(expr); } @@ -1786,7 +1767,7 @@ impl<'a> Parser<'a> { &mut self, lo: Span, pth: ast::Path, - mut attrs: AttrVec + mut attrs: AttrVec, ) -> PResult<'a, P<Expr>> { let struct_sp = lo.to(self.prev_span); self.bump(); @@ -1816,7 +1797,7 @@ impl<'a> Parser<'a> { self.token.span, "remove this comma", String::new(), - Applicability::MachineApplicable + Applicability::MachineApplicable, ) .note("the base struct must always be the last field") .emit(); @@ -1859,11 +1840,12 @@ impl<'a> Parser<'a> { } } - match self.expect_one_of(&[token::Comma], - &[token::CloseDelim(token::Brace)]) { - Ok(_) => if let Some(f) = parsed_field.or(recovery_field) { - // Only include the field if there's no parse error for the field name. - fields.push(f); + match self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)]) { + Ok(_) => { + if let Some(f) = parsed_field.or(recovery_field) { + // Only include the field if there's no parse error for the field name. + fields.push(f); + } } Err(mut e) => { if let Some(f) = recovery_field { @@ -1888,34 +1870,33 @@ impl<'a> Parser<'a> { let lo = self.token.span; // Check if a colon exists one ahead. This means we're parsing a fieldname. - let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| { - t == &token::Colon || t == &token::Eq - }) { - let fieldname = self.parse_field_name()?; - - // Check for an equals token. This means the source incorrectly attempts to - // initialize a field with an eq rather than a colon. - if self.token == token::Eq { - self.diagnostic() - .struct_span_err(self.token.span, "expected `:`, found `=`") - .span_suggestion( - fieldname.span.shrink_to_hi().to(self.token.span), - "replace equals symbol with a colon", - ":".to_string(), - Applicability::MachineApplicable, - ) - .emit(); - } - self.bump(); // `:` - (fieldname, self.parse_expr()?, false) - } else { - let fieldname = self.parse_ident_common(false)?; + let (fieldname, expr, is_shorthand) = + if self.look_ahead(1, |t| t == &token::Colon || t == &token::Eq) { + let fieldname = self.parse_field_name()?; + + // Check for an equals token. This means the source incorrectly attempts to + // initialize a field with an eq rather than a colon. + if self.token == token::Eq { + self.diagnostic() + .struct_span_err(self.token.span, "expected `:`, found `=`") + .span_suggestion( + fieldname.span.shrink_to_hi().to(self.token.span), + "replace equals symbol with a colon", + ":".to_string(), + Applicability::MachineApplicable, + ) + .emit(); + } + self.bump(); // `:` + (fieldname, self.parse_expr()?, false) + } else { + let fieldname = self.parse_ident_common(false)?; - // Mimic `x: x` for the `x` field shorthand. - let path = ast::Path::from_ident(fieldname); - let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), AttrVec::new()); - (fieldname, expr, true) - }; + // Mimic `x: x` for the `x` field shorthand. + let path = ast::Path::from_ident(fieldname); + let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), AttrVec::new()); + (fieldname, expr, true) + }; Ok(ast::Field { ident: fieldname, span: lo.to(expr.span), @@ -1931,28 +1912,29 @@ impl<'a> Parser<'a> { self.struct_span_err(span, "unexpected token: `...`") .span_suggestion( span, - "use `..` for an exclusive range", "..".to_owned(), - Applicability::MaybeIncorrect + "use `..` for an exclusive range", + "..".to_owned(), + Applicability::MaybeIncorrect, ) .span_suggestion( span, - "or `..=` for an inclusive range", "..=".to_owned(), - Applicability::MaybeIncorrect + "or `..=` for an inclusive range", + "..=".to_owned(), + Applicability::MaybeIncorrect, ) .emit(); } fn err_larrow_operator(&self, span: Span) { - self.struct_span_err( - span, - "unexpected token: `<-`" - ).span_suggestion( - span, - "if you meant to write a comparison against a negative value, add a \ + self.struct_span_err(span, "unexpected token: `<-`") + .span_suggestion( + span, + "if you meant to write a comparison against a negative value, add a \ space in between `<` and `-`", - "< -".to_string(), - Applicability::MaybeIncorrect - ).emit(); + "< -".to_string(), + Applicability::MaybeIncorrect, + ) + .emit(); } fn mk_assign_op(&self, binop: BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ExprKind { @@ -1963,7 +1945,7 @@ impl<'a> Parser<'a> { &self, start: Option<P<Expr>>, end: Option<P<Expr>>, - limits: RangeLimits + limits: RangeLimits, ) -> PResult<'a, ExprKind> { if end.is_none() && limits == RangeLimits::Closed { Err(self.span_fatal_err(self.token.span, Error::InclusiveRangeWithNoEnd)) diff --git a/src/librustc_parse/parser/generics.rs b/src/librustc_parse/parser/generics.rs index 32819cca42b..113a613b913 100644 --- a/src/librustc_parse/parser/generics.rs +++ b/src/librustc_parse/parser/generics.rs @@ -1,12 +1,11 @@ use super::Parser; use rustc_errors::PResult; -use syntax::ast::{self, WhereClause, GenericParam, GenericParamKind, GenericBounds, Attribute}; -use syntax::token; +use syntax::ast::{self, Attribute, GenericBounds, GenericParam, GenericParamKind, WhereClause}; use syntax::source_map::DUMMY_SP; +use syntax::token; use syntax_pos::symbol::{kw, sym}; - impl<'a> Parser<'a> { /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`. /// @@ -19,16 +18,14 @@ impl<'a> Parser<'a> { lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime())); if !self.eat_plus() { - break + break; } } lifetimes } /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`. - fn parse_ty_param(&mut self, - preceding_attrs: Vec<Attribute>) - -> PResult<'a, GenericParam> { + fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> { let ident = self.parse_ident()?; // Parse optional colon and param bounds. @@ -38,21 +35,15 @@ impl<'a> Parser<'a> { Vec::new() }; - let default = if self.eat(&token::Eq) { - Some(self.parse_ty()?) - } else { - None - }; + let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None }; Ok(GenericParam { ident, id: ast::DUMMY_NODE_ID, attrs: preceding_attrs.into(), bounds, - kind: GenericParamKind::Type { - default, - }, - is_placeholder: false + kind: GenericParamKind::Type { default }, + is_placeholder: false, }) } @@ -71,10 +62,8 @@ impl<'a> Parser<'a> { id: ast::DUMMY_NODE_ID, attrs: preceding_attrs.into(), bounds: Vec::new(), - kind: GenericParamKind::Const { - ty, - }, - is_placeholder: false + kind: GenericParamKind::Const { ty }, + is_placeholder: false, }) } @@ -87,18 +76,15 @@ impl<'a> Parser<'a> { if self.check_lifetime() { let lifetime = self.expect_lifetime(); // Parse lifetime parameter. - let bounds = if self.eat(&token::Colon) { - self.parse_lt_param_bounds() - } else { - Vec::new() - }; + let bounds = + if self.eat(&token::Colon) { self.parse_lt_param_bounds() } else { Vec::new() }; params.push(ast::GenericParam { ident: lifetime.ident, id: lifetime.id, attrs: attrs.into(), bounds, kind: ast::GenericParamKind::Lifetime, - is_placeholder: false + is_placeholder: false, }); } else if self.check_keyword(kw::Const) { // Parse const parameter. @@ -121,7 +107,7 @@ impl<'a> Parser<'a> { Err(mut err) => { err.cancel(); std::mem::replace(self, snapshot); - break + break; } } } else { @@ -146,11 +132,11 @@ impl<'a> Parser<'a> { .emit(); } } - break + break; } if !self.eat(&token::Comma) { - break + break; } } Ok(params) @@ -174,10 +160,7 @@ impl<'a> Parser<'a> { }; Ok(ast::Generics { params, - where_clause: WhereClause { - predicates: Vec::new(), - span: DUMMY_SP, - }, + where_clause: WhereClause { predicates: Vec::new(), span: DUMMY_SP }, span, }) } @@ -188,10 +171,8 @@ impl<'a> Parser<'a> { /// where T : Trait<U, V> + 'b, 'a : 'b /// ``` pub(super) fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> { - let mut where_clause = WhereClause { - predicates: Vec::new(), - span: self.prev_span.to(self.prev_span), - }; + let mut where_clause = + WhereClause { predicates: Vec::new(), span: self.prev_span.to(self.prev_span) }; if !self.eat_keyword(kw::Where) { return Ok(where_clause); @@ -207,8 +188,8 @@ impl<'a> Parser<'a> { generics.span, "generic parameters on `where` clauses are reserved for future use", ) - .span_label(generics.span, "currently unsupported") - .emit(); + .span_label(generics.span, "currently unsupported") + .emit(); } loop { @@ -219,20 +200,16 @@ impl<'a> Parser<'a> { self.expect(&token::Colon)?; let bounds = self.parse_lt_param_bounds(); where_clause.predicates.push(ast::WherePredicate::RegionPredicate( - ast::WhereRegionPredicate { - span: lo.to(self.prev_span), - lifetime, - bounds, - } + ast::WhereRegionPredicate { span: lo.to(self.prev_span), lifetime, bounds }, )); } else if self.check_type() { where_clause.predicates.push(self.parse_ty_where_predicate()?); } else { - break + break; } if !self.eat(&token::Comma) { - break + break; } } @@ -256,26 +233,22 @@ impl<'a> Parser<'a> { let ty = self.parse_ty()?; if self.eat(&token::Colon) { let bounds = self.parse_generic_bounds(Some(self.prev_span))?; - Ok(ast::WherePredicate::BoundPredicate( - ast::WhereBoundPredicate { - span: lo.to(self.prev_span), - bound_generic_params: lifetime_defs, - bounded_ty: ty, - bounds, - } - )) + Ok(ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { + span: lo.to(self.prev_span), + bound_generic_params: lifetime_defs, + bounded_ty: ty, + bounds, + })) // FIXME: Decide what should be used here, `=` or `==`. // FIXME: We are just dropping the binders in lifetime_defs on the floor here. } else if self.eat(&token::Eq) || self.eat(&token::EqEq) { let rhs_ty = self.parse_ty()?; - Ok(ast::WherePredicate::EqPredicate( - ast::WhereEqPredicate { - span: lo.to(self.prev_span), - lhs_ty: ty, - rhs_ty, - id: ast::DUMMY_NODE_ID, - } - )) + Ok(ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { + span: lo.to(self.prev_span), + lhs_ty: ty, + rhs_ty, + id: ast::DUMMY_NODE_ID, + })) } else { self.unexpected() } @@ -298,11 +271,15 @@ impl<'a> Parser<'a> { // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`) // because this is what almost always expected in practice, qualified paths in impls // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment. - self.token == token::Lt && - (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) || - self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) && - self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma || - t == &token::Colon || t == &token::Eq) || - self.is_keyword_ahead(1, &[kw::Const])) + self.token == token::Lt + && (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) + || self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) + && self.look_ahead(2, |t| { + t == &token::Gt + || t == &token::Comma + || t == &token::Colon + || t == &token::Eq + }) + || self.is_keyword_ahead(1, &[kw::Const])) } } diff --git a/src/librustc_parse/parser/item.rs b/src/librustc_parse/parser/item.rs index ea9047d2d77..8f8e5fbb787 100644 --- a/src/librustc_parse/parser/item.rs +++ b/src/librustc_parse/parser/item.rs @@ -1,24 +1,24 @@ -use super::{Parser, PathStyle, FollowedByType}; -use super::diagnostics::{Error, dummy_arg, ConsumeClosingDelim}; +use super::diagnostics::{dummy_arg, ConsumeClosingDelim, Error}; +use super::{FollowedByType, Parser, PathStyle}; use crate::maybe_whole; -use rustc_errors::{PResult, Applicability, DiagnosticBuilder, StashKey}; use rustc_error_codes::*; -use syntax::ast::{self, DUMMY_NODE_ID, Ident, AttrVec, Attribute, AttrKind, AttrStyle}; +use rustc_errors::{Applicability, DiagnosticBuilder, PResult, StashKey}; +use syntax::ast::{self, AttrKind, AttrStyle, AttrVec, Attribute, Ident, DUMMY_NODE_ID}; use syntax::ast::{AssocItem, AssocItemKind, Item, ItemKind, UseTree, UseTreeKind}; -use syntax::ast::{PathSegment, IsAuto, Constness, IsAsync, Unsafety, Defaultness, Extern, StrLit}; -use syntax::ast::{Visibility, VisibilityKind, Mutability, FnHeader, ForeignItem, ForeignItemKind}; -use syntax::ast::{Ty, TyKind, Generics, TraitRef, EnumDef, Variant, VariantData, StructField}; -use syntax::ast::{Mac, MacArgs, MacDelimiter, Block, BindingMode, FnDecl, FnSig, SelfKind, Param}; +use syntax::ast::{BindingMode, Block, FnDecl, FnSig, Mac, MacArgs, MacDelimiter, Param, SelfKind}; +use syntax::ast::{Constness, Defaultness, Extern, IsAsync, IsAuto, PathSegment, StrLit, Unsafety}; +use syntax::ast::{EnumDef, Generics, StructField, TraitRef, Ty, TyKind, Variant, VariantData}; +use syntax::ast::{FnHeader, ForeignItem, ForeignItemKind, Mutability, Visibility, VisibilityKind}; use syntax::print::pprust; use syntax::ptr::P; -use syntax::token; -use syntax::tokenstream::{DelimSpan, TokenTree, TokenStream}; use syntax::struct_span_err; -use syntax_pos::BytePos; +use syntax::token; +use syntax::tokenstream::{DelimSpan, TokenStream, TokenTree}; use syntax_pos::source_map::{self, respan, Span}; use syntax_pos::symbol::{kw, sym, Symbol}; +use syntax_pos::BytePos; use log::debug; use std::mem; @@ -117,9 +117,7 @@ impl<'a> Parser<'a> { }; return self.parse_item_fn(lo, vis, attrs, header); } else if self.check(&token::OpenDelim(token::Brace)) { - return Ok(Some( - self.parse_item_foreign_mod(lo, abi, vis, attrs, extern_sp)?, - )); + return Ok(Some(self.parse_item_foreign_mod(lo, abi, vis, attrs, extern_sp)?)); } self.unexpected()?; @@ -175,18 +173,19 @@ impl<'a> Parser<'a> { // Parses `async unsafe? fn`. if self.check_keyword(kw::Async) { let async_span = self.token.span; - if self.is_keyword_ahead(1, &[kw::Fn]) - || self.is_keyword_ahead(2, &[kw::Fn]) - { + if self.is_keyword_ahead(1, &[kw::Fn]) || self.is_keyword_ahead(2, &[kw::Fn]) { // ASYNC FUNCTION ITEM self.bump(); // `async` let unsafety = self.parse_unsafety(); // `unsafe`? self.expect_keyword(kw::Fn)?; // `fn` let fn_span = self.prev_span; - let asyncness = respan(async_span, IsAsync::Async { - closure_id: DUMMY_NODE_ID, - return_impl_trait_id: DUMMY_NODE_ID, - }); + let asyncness = respan( + async_span, + IsAsync::Async { + closure_id: DUMMY_NODE_ID, + return_impl_trait_id: DUMMY_NODE_ID, + }, + ); self.ban_async_in_2015(async_span); let header = FnHeader { unsafety, @@ -198,20 +197,16 @@ impl<'a> Parser<'a> { } } - if self.check_keyword(kw::Unsafe) && - self.is_keyword_ahead(1, &[kw::Trait, kw::Auto]) - { + if self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto]) { // UNSAFE TRAIT ITEM self.bump(); // `unsafe` let info = self.parse_item_trait(lo, Unsafety::Unsafe)?; return self.mk_item_with_info(attrs, lo, vis, info); } - if self.check_keyword(kw::Impl) || - self.check_keyword(kw::Unsafe) && - self.is_keyword_ahead(1, &[kw::Impl]) || - self.check_keyword(kw::Default) && - self.is_keyword_ahead(1, &[kw::Impl, kw::Unsafe]) + if self.check_keyword(kw::Impl) + || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl]) + || self.check_keyword(kw::Default) && self.is_keyword_ahead(1, &[kw::Impl, kw::Unsafe]) { // IMPL ITEM let defaultness = self.parse_defaultness(); @@ -273,8 +268,7 @@ impl<'a> Parser<'a> { } if self.check_keyword(kw::Trait) - || (self.check_keyword(kw::Auto) - && self.is_keyword_ahead(1, &[kw::Trait])) + || (self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait])) { // TRAIT ITEM let info = self.parse_item_trait(lo, Unsafety::Normal)?; @@ -300,10 +294,7 @@ impl<'a> Parser<'a> { // Verify whether we have encountered a struct or method definition where the user forgot to // add the `struct` or `fn` keyword after writing `pub`: `pub S {}` - if vis.node.is_pub() && - self.check_ident() && - self.look_ahead(1, |t| *t != token::Not) - { + if vis.node.is_pub() && self.check_ident() && self.look_ahead(1, |t| *t != token::Not) { // Space between `pub` keyword and the identifier // // pub S {} @@ -314,25 +305,27 @@ impl<'a> Parser<'a> { if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) { // possible public struct definition where `struct` was forgotten let ident = self.parse_ident().unwrap(); - let msg = format!("add `struct` here to parse `{}` as a public struct", - ident); - let mut err = self.diagnostic() - .struct_span_err(sp, "missing `struct` for struct definition"); + let msg = format!("add `struct` here to parse `{}` as a public struct", ident); + let mut err = + self.diagnostic().struct_span_err(sp, "missing `struct` for struct definition"); err.span_suggestion_short( - sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative + sp, + &msg, + " struct ".into(), + Applicability::MaybeIncorrect, // speculative ); return Err(err); } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) { let ident = self.parse_ident().unwrap(); - self.bump(); // `(` + self.bump(); // `(` let kw_name = self.recover_first_param(); self.consume_block(token::Paren, ConsumeClosingDelim::Yes); let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) { self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]); - self.bump(); // `{` + self.bump(); // `{` ("fn", kw_name, false) } else if self.check(&token::OpenDelim(token::Brace)) { - self.bump(); // `{` + self.bump(); // `{` ("fn", kw_name, false) } else if self.check(&token::Colon) { let kw = "struct"; @@ -345,12 +338,13 @@ impl<'a> Parser<'a> { let mut err = self.diagnostic().struct_span_err(sp, &msg); if !ambiguous { self.consume_block(token::Brace, ConsumeClosingDelim::Yes); - let suggestion = format!("add `{}` here to parse `{}` as a public {}", - kw, - ident, - kw_name); + let suggestion = + format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name); err.span_suggestion_short( - sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable + sp, + &suggestion, + format!(" {} ", kw), + Applicability::MachineApplicable, ); } else { if let Ok(snippet) = self.span_to_snippet(ident_sp) { @@ -359,18 +353,20 @@ impl<'a> Parser<'a> { "if you meant to call a macro, try", format!("{}!", snippet), // this is the `ambiguous` conditional branch - Applicability::MaybeIncorrect + Applicability::MaybeIncorrect, ); } else { - err.help("if you meant to call a macro, remove the `pub` \ - and add a trailing `!` after the identifier"); + err.help( + "if you meant to call a macro, remove the `pub` \ + and add a trailing `!` after the identifier", + ); } } return Err(err); } else if self.look_ahead(1, |t| *t == token::Lt) { let ident = self.parse_ident().unwrap(); self.eat_to_tokens(&[&token::Gt]); - self.bump(); // `>` + self.bump(); // `>` let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) { ("fn", self.recover_first_param(), false) } else if self.check(&token::OpenDelim(token::Brace)) { @@ -417,14 +413,16 @@ impl<'a> Parser<'a> { /// This is the fall-through for parsing items. fn parse_macro_use_or_failure( &mut self, - attrs: Vec<Attribute> , + attrs: Vec<Attribute>, macros_allowed: bool, attributes_allowed: bool, lo: Span, - visibility: Visibility + visibility: Visibility, ) -> PResult<'a, Option<P<Item>>> { - if macros_allowed && self.token.is_path_start() && - !(self.is_async_fn() && self.token.span.rust_2015()) { + if macros_allowed + && self.token.is_path_start() + && !(self.is_async_fn() && self.token.span.rust_2015()) + { // MACRO INVOCATION ITEM let prev_span = self.prev_span; @@ -439,11 +437,7 @@ impl<'a> Parser<'a> { } let hi = self.prev_span; - let mac = Mac { - path, - args, - prior_type_ascription: self.last_type_ascription, - }; + let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription }; let item = self.mk_item(lo.to(hi), Ident::invalid(), ItemKind::Mac(mac), visibility, attrs); return Ok(Some(item)); @@ -464,12 +458,12 @@ impl<'a> Parser<'a> { } /// Emits an expected-item-after-attributes error. - fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> { + fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> { let message = match attrs.last() { - Some(&Attribute { kind: AttrKind::DocComment(_), .. }) => - "expected item after doc comment", - _ => - "expected item after attributes", + Some(&Attribute { kind: AttrKind::DocComment(_), .. }) => { + "expected item after doc comment" + } + _ => "expected item after attributes", }; let mut err = self.diagnostic().struct_span_err(self.prev_span, message); @@ -480,8 +474,7 @@ impl<'a> Parser<'a> { } pub(super) fn is_async_fn(&self) -> bool { - self.token.is_keyword(kw::Async) && - self.is_keyword_ahead(1, &[kw::Fn]) + self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn]) } /// Parses a macro invocation inside a `trait`, `impl` or `extern` block. @@ -491,8 +484,7 @@ impl<'a> Parser<'a> { vis: Option<&Visibility>, at_end: &mut bool, ) -> PResult<'a, Option<Mac>> { - if self.token.is_path_start() && - !(self.is_async_fn() && self.token.span.rust_2015()) { + if self.token.is_path_start() && !(self.is_async_fn() && self.token.span.rust_2015()) { let prev_span = self.prev_span; let path = self.parse_path(PathStyle::Mod)?; @@ -516,11 +508,7 @@ impl<'a> Parser<'a> { self.expect_semi()?; } - Ok(Some(Mac { - path, - args, - prior_type_ascription: self.last_type_ascription, - })) + Ok(Some(Mac { path, args, prior_type_ascription: self.last_type_ascription })) } else { Ok(None) } @@ -547,10 +535,9 @@ impl<'a> Parser<'a> { // pub path( // ^^ `sp` below will point to this let sp = prev_span.between(self.prev_span); - let mut err = self.diagnostic().struct_span_err( - sp, - &format!("{} for {}-item declaration", - expected_kinds, item_type)); + let mut err = self + .diagnostic() + .struct_span_err(sp, &format!("{} for {}-item declaration", expected_kinds, item_type)); err.span_label(sp, expected_kinds); err } @@ -564,8 +551,11 @@ impl<'a> Parser<'a> { /// We actually parse slightly more relaxed grammar for better error reporting and recovery. /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}` /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}` - fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness) - -> PResult<'a, ItemInfo> { + fn parse_item_impl( + &mut self, + unsafety: Unsafety, + defaultness: Defaultness, + ) -> PResult<'a, ItemInfo> { // First, parse generic parameters if necessary. let mut generics = if self.choose_generics_over_qpath() { self.parse_generics()? @@ -583,8 +573,8 @@ impl<'a> Parser<'a> { // Parse both types and traits as a type, then reinterpret if necessary. let err_path = |span| ast::Path::from_ident(Ident::new(kw::Invalid, span)); - let ty_first = if self.token.is_keyword(kw::For) && - self.look_ahead(1, |t| t != &token::Lt) { + let ty_first = if self.token.is_keyword(kw::For) && self.look_ahead(1, |t| t != &token::Lt) + { let span = self.prev_span.between(self.token.span); self.struct_span_err(span, "missing trait in a trait impl").emit(); P(Ty { kind: TyKind::Path(None, err_path(span)), span, id: DUMMY_NODE_ID }) @@ -620,7 +610,8 @@ impl<'a> Parser<'a> { "add `for` here", " for ".to_string(), Applicability::MachineApplicable, - ).emit(); + ) + .emit(); } let ty_first = ty_first.into_inner(); @@ -634,13 +625,27 @@ impl<'a> Parser<'a> { }; let trait_ref = TraitRef { path, ref_id: ty_first.id }; - ItemKind::Impl(unsafety, polarity, defaultness, - generics, Some(trait_ref), ty_second, impl_items) + ItemKind::Impl( + unsafety, + polarity, + defaultness, + generics, + Some(trait_ref), + ty_second, + impl_items, + ) } None => { // impl Type - ItemKind::Impl(unsafety, polarity, defaultness, - generics, None, ty_first, impl_items) + ItemKind::Impl( + unsafety, + polarity, + defaultness, + generics, + None, + ty_first, + impl_items, + ) } }; @@ -671,17 +676,20 @@ impl<'a> Parser<'a> { /// Parses defaultness (i.e., `default` or nothing). fn parse_defaultness(&mut self) -> Defaultness { // `pub` is included for better error messages - if self.check_keyword(kw::Default) && - self.is_keyword_ahead(1, &[ - kw::Impl, - kw::Const, - kw::Async, - kw::Fn, - kw::Unsafe, - kw::Extern, - kw::Type, - kw::Pub, - ]) + if self.check_keyword(kw::Default) + && self.is_keyword_ahead( + 1, + &[ + kw::Impl, + kw::Const, + kw::Async, + kw::Fn, + kw::Unsafe, + kw::Extern, + kw::Type, + kw::Pub, + ], + ) { self.bump(); // `default` Defaultness::Default @@ -693,11 +701,7 @@ impl<'a> Parser<'a> { /// Parses `auto? trait Foo { ... }` or `trait Foo = Bar;`. fn parse_item_trait(&mut self, lo: Span, unsafety: Unsafety) -> PResult<'a, ItemInfo> { // Parse optional `auto` prefix. - let is_auto = if self.eat_keyword(kw::Auto) { - IsAuto::Yes - } else { - IsAuto::No - }; + let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No }; self.expect_keyword(kw::Trait)?; let ident = self.parse_ident()?; @@ -706,19 +710,15 @@ impl<'a> Parser<'a> { // Parse optional colon and supertrait bounds. let had_colon = self.eat(&token::Colon); let span_at_colon = self.prev_span; - let bounds = if had_colon { - self.parse_generic_bounds(Some(self.prev_span))? - } else { - Vec::new() - }; + let bounds = + if had_colon { self.parse_generic_bounds(Some(self.prev_span))? } else { Vec::new() }; let span_before_eq = self.prev_span; if self.eat(&token::Eq) { // It's a trait alias. if had_colon { let span = span_at_colon.to(span_before_eq); - self.struct_span_err(span, "bounds are not allowed on trait aliases") - .emit(); + self.struct_span_err(span, "bounds are not allowed on trait aliases").emit(); } let bounds = self.parse_generic_bounds(None)?; @@ -728,15 +728,11 @@ impl<'a> Parser<'a> { let whole_span = lo.to(self.prev_span); if is_auto == IsAuto::Yes { let msg = "trait aliases cannot be `auto`"; - self.struct_span_err(whole_span, msg) - .span_label(whole_span, msg) - .emit(); + self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit(); } if unsafety != Unsafety::Normal { let msg = "trait aliases cannot be `unsafe`"; - self.struct_span_err(whole_span, msg) - .span_label(whole_span, msg) - .emit(); + self.struct_span_err(whole_span, msg).span_label(whole_span, msg).emit(); } self.sess.gated_spans.gate(sym::trait_alias, whole_span); @@ -749,8 +745,7 @@ impl<'a> Parser<'a> { let mut trait_items = vec![]; while !self.eat(&token::CloseDelim(token::Brace)) { if let token::DocComment(_) = self.token.kind { - if self.look_ahead(1, - |tok| tok == &token::CloseDelim(token::Brace)) { + if self.look_ahead(1, |tok| tok == &token::CloseDelim(token::Brace)) { struct_span_err!( self.diagnostic(), self.token.span, @@ -852,8 +847,7 @@ impl<'a> Parser<'a> { /// Returns `true` if we are looking at `const ID` /// (returns `false` for things like `const fn`, etc.). fn is_const_item(&self) -> bool { - self.token.is_keyword(kw::Const) && - !self.is_keyword_ahead(1, &[kw::Fn, kw::Unsafe]) + self.token.is_keyword(kw::Const) && !self.is_keyword_ahead(1, &[kw::Fn, kw::Unsafe]) } /// This parses the grammar: @@ -864,11 +858,7 @@ impl<'a> Parser<'a> { let ident = self.parse_ident()?; self.expect(&token::Colon)?; let ty = self.parse_ty()?; - let expr = if self.eat(&token::Eq) { - Some(self.parse_expr()?) - } else { - None - }; + let expr = if self.eat(&token::Eq) { Some(self.parse_expr()?) } else { None }; self.expect_semi()?; Ok((ident, AssocItemKind::Const(ty, expr), Generics::default())) } @@ -881,18 +871,11 @@ impl<'a> Parser<'a> { let mut generics = self.parse_generics()?; // Parse optional colon and param bounds. - let bounds = if self.eat(&token::Colon) { - self.parse_generic_bounds(None)? - } else { - Vec::new() - }; + let bounds = + if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() }; generics.where_clause = self.parse_where_clause()?; - let default = if self.eat(&token::Eq) { - Some(self.parse_ty()?) - } else { - None - }; + let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None }; self.expect_semi()?; Ok((ident, AssocItemKind::TyAlias(bounds, default), generics)) @@ -911,15 +894,16 @@ impl<'a> Parser<'a> { let lo = self.token.span; let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() }; - let kind = if self.check(&token::OpenDelim(token::Brace)) || - self.check(&token::BinOp(token::Star)) || - self.is_import_coupler() { + let kind = if self.check(&token::OpenDelim(token::Brace)) + || self.check(&token::BinOp(token::Star)) + || self.is_import_coupler() + { // `use *;` or `use ::*;` or `use {...};` or `use ::{...};` let mod_sep_ctxt = self.token.span.ctxt(); if self.eat(&token::ModSep) { - prefix.segments.push( - PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)) - ); + prefix + .segments + .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))); } self.parse_use_tree_glob_or_nested()? @@ -957,11 +941,7 @@ impl<'a> Parser<'a> { } fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> { - if self.eat_keyword(kw::As) { - self.parse_ident_or_underscore().map(Some) - } else { - Ok(None) - } + if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) } } fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> { @@ -987,7 +967,7 @@ impl<'a> Parser<'a> { &mut self, lo: Span, visibility: Visibility, - attrs: Vec<Attribute> + attrs: Vec<Attribute>, ) -> PResult<'a, P<Item>> { // Accept `extern crate name-like-this` for better diagnostics let orig_name = self.parse_crate_name_with_dashes()?; @@ -1016,7 +996,8 @@ impl<'a> Parser<'a> { let mut fixed_crate_name = false; // Accept `extern crate name-like-this` for better diagnostics. let dash = token::BinOp(token::BinOpToken::Minus); - if self.token == dash { // Do not include `-` as part of the expected tokens list. + if self.token == dash { + // Do not include `-` as part of the expected tokens list. while self.eat(&dash) { fixed_crate_name = true; replacement.push((self.prev_span, "_".to_string())); @@ -1068,10 +1049,7 @@ impl<'a> Parser<'a> { } let prev_span = self.prev_span; - let m = ast::ForeignMod { - abi, - items: foreign_items - }; + let m = ast::ForeignMod { abi, items: foreign_items }; let invalid = Ident::invalid(); Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs)) } @@ -1088,9 +1066,8 @@ impl<'a> Parser<'a> { // Treat `const` as `static` for error recovery, but don't add it to expected tokens. if self.check_keyword(kw::Static) || self.token.is_keyword(kw::Const) { if self.token.is_keyword(kw::Const) { - let mut err = self - .struct_span_err(self.token.span, "extern items cannot be `const`"); - + let mut err = + self.struct_span_err(self.token.span, "extern items cannot be `const`"); // The user wrote 'const fn' if self.is_keyword_ahead(1, &[kw::Fn, kw::Unsafe]) { @@ -1106,10 +1083,10 @@ impl<'a> Parser<'a> { return Ok(self.parse_item_foreign_fn(visibility, lo, attrs, extern_sp)?); } err.span_suggestion( - self.token.span, - "try using a static value", - "static".to_owned(), - Applicability::MachineApplicable + self.token.span, + "try using a static value", + "static".to_owned(), + Applicability::MachineApplicable, ); err.emit(); } @@ -1126,21 +1103,17 @@ impl<'a> Parser<'a> { } match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? { - Some(mac) => { - Ok( - ForeignItem { - ident: Ident::invalid(), - span: lo.to(self.prev_span), - id: DUMMY_NODE_ID, - attrs, - vis: visibility, - kind: ForeignItemKind::Macro(mac), - tokens: None, - } - ) - } + Some(mac) => Ok(ForeignItem { + ident: Ident::invalid(), + span: lo.to(self.prev_span), + id: DUMMY_NODE_ID, + attrs, + vis: visibility, + kind: ForeignItemKind::Macro(mac), + tokens: None, + }), None => { - if !attrs.is_empty() { + if !attrs.is_empty() { self.expected_item_err(&attrs)?; } @@ -1151,8 +1124,12 @@ impl<'a> Parser<'a> { /// Parses a static item from a foreign module. /// Assumes that the `static` keyword is already parsed. - fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>) - -> PResult<'a, ForeignItem> { + fn parse_item_foreign_static( + &mut self, + vis: ast::Visibility, + lo: Span, + attrs: Vec<Attribute>, + ) -> PResult<'a, ForeignItem> { let mutbl = self.parse_mutability(); let ident = self.parse_ident()?; self.expect(&token::Colon)?; @@ -1171,8 +1148,12 @@ impl<'a> Parser<'a> { } /// Parses a type from a foreign module. - fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>) - -> PResult<'a, ForeignItem> { + fn parse_item_foreign_type( + &mut self, + vis: ast::Visibility, + lo: Span, + attrs: Vec<Attribute>, + ) -> PResult<'a, ForeignItem> { self.expect_keyword(kw::Type)?; let ident = self.parse_ident()?; @@ -1254,11 +1235,7 @@ impl<'a> Parser<'a> { // The user intended that the type be inferred, // so treat this as if the user wrote e.g. `const A: _ = expr;`. - P(Ty { - kind: TyKind::Infer, - span: id.span, - id: ast::DUMMY_NODE_ID, - }) + P(Ty { kind: TyKind::Infer, span: id.span, id: ast::DUMMY_NODE_ID }) } /// Parses the grammar: @@ -1279,17 +1256,14 @@ impl<'a> Parser<'a> { let mut generics = self.parse_generics()?; generics.where_clause = self.parse_where_clause()?; - let (variants, _) = self.parse_delim_comma_seq( - token::Brace, - |p| p.parse_enum_variant(), - ).map_err(|e| { - self.recover_stmt(); - e - })?; + let (variants, _) = + self.parse_delim_comma_seq(token::Brace, |p| p.parse_enum_variant()).map_err(|e| { + self.recover_stmt(); + e + })?; - let enum_definition = EnumDef { - variants: variants.into_iter().filter_map(|v| v).collect(), - }; + let enum_definition = + EnumDef { variants: variants.into_iter().filter_map(|v| v).collect() }; Ok((id, ItemKind::Enum(enum_definition, generics), None)) } @@ -1299,7 +1273,7 @@ impl<'a> Parser<'a> { let vis = self.parse_visibility(FollowedByType::No)?; if !self.recover_nested_adt_item(kw::Enum)? { - return Ok(None) + return Ok(None); } let ident = self.parse_ident()?; @@ -1308,19 +1282,13 @@ impl<'a> Parser<'a> { let (fields, recovered) = self.parse_record_struct_body()?; VariantData::Struct(fields, recovered) } else if self.check(&token::OpenDelim(token::Paren)) { - VariantData::Tuple( - self.parse_tuple_struct_body()?, - DUMMY_NODE_ID, - ) + VariantData::Tuple(self.parse_tuple_struct_body()?, DUMMY_NODE_ID) } else { VariantData::Unit(DUMMY_NODE_ID) }; - let disr_expr = if self.eat(&token::Eq) { - Some(self.parse_anon_const_expr()?) - } else { - None - }; + let disr_expr = + if self.eat(&token::Eq) { Some(self.parse_anon_const_expr()?) } else { None }; let vr = ast::Variant { ident, @@ -1407,8 +1375,8 @@ impl<'a> Parser<'a> { VariantData::Struct(fields, recovered) } else { let token_str = self.this_token_descr(); - let mut err = self.fatal(&format!( - "expected `where` or `{{` after union name, found {}", token_str)); + let mut err = self + .fatal(&format!("expected `where` or `{{` after union name, found {}", token_str)); err.span_label(self.token.span, "expected `where` or `{` after union name"); return Err(err); }; @@ -1417,8 +1385,8 @@ impl<'a> Parser<'a> { } pub(super) fn is_union_item(&self) -> bool { - self.token.is_keyword(kw::Union) && - self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) + self.token.is_keyword(kw::Union) + && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) } fn parse_record_struct_body( @@ -1445,7 +1413,9 @@ impl<'a> Parser<'a> { } else { let token_str = self.this_token_descr(); let mut err = self.fatal(&format!( - "expected `where`, or `{{` after struct name, found {}", token_str)); + "expected `where`, or `{{` after struct name, found {}", + token_str + )); err.span_label(self.token.span, "expected `where`, or `{` after struct name"); return Err(err); } @@ -1470,7 +1440,8 @@ impl<'a> Parser<'a> { attrs, is_placeholder: false, }) - }).map(|(r, _)| r) + }) + .map(|(r, _)| r) } /// Parses an element of a struct declaration. @@ -1482,11 +1453,12 @@ impl<'a> Parser<'a> { } /// Parses a structure field declaration. - fn parse_single_struct_field(&mut self, - lo: Span, - vis: Visibility, - attrs: Vec<Attribute> ) - -> PResult<'a, StructField> { + fn parse_single_struct_field( + &mut self, + lo: Span, + vis: Visibility, + attrs: Vec<Attribute>, + ) -> PResult<'a, StructField> { let mut seen_comma: bool = false; let a_var = self.parse_name_and_ty(lo, vis, attrs)?; if self.token == token::Comma { @@ -1516,7 +1488,7 @@ impl<'a> Parser<'a> { sp, "missing comma here", ",".into(), - Applicability::MachineApplicable + Applicability::MachineApplicable, ); } return Err(err); @@ -1524,8 +1496,10 @@ impl<'a> Parser<'a> { } _ => { let sp = self.sess.source_map().next_point(self.prev_span); - let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}", - self.this_token_descr())); + let mut err = self.struct_span_err( + sp, + &format!("expected `,`, or `}}`, found {}", self.this_token_descr()), + ); if self.token.is_ident() { // This is likely another field; emit the diagnostic and keep going err.span_suggestion( @@ -1536,7 +1510,7 @@ impl<'a> Parser<'a> { ); err.emit(); } else { - return Err(err) + return Err(err); } } } @@ -1548,7 +1522,7 @@ impl<'a> Parser<'a> { &mut self, lo: Span, vis: Visibility, - attrs: Vec<Attribute> + attrs: Vec<Attribute>, ) -> PResult<'a, StructField> { let name = self.parse_ident()?; self.expect(&token::Colon)?; @@ -1568,7 +1542,7 @@ impl<'a> Parser<'a> { &mut self, attrs: &[Attribute], vis: &Visibility, - lo: Span + lo: Span, ) -> PResult<'a, Option<P<Item>>> { let (ident, def) = if self.eat_keyword(kw::Macro) { let ident = self.parse_ident()?; @@ -1595,9 +1569,10 @@ impl<'a> Parser<'a> { }; (ident, ast::MacroDef { body, legacy: false }) - } else if self.check_keyword(sym::macro_rules) && - self.look_ahead(1, |t| *t == token::Not) && - self.look_ahead(2, |t| t.is_ident()) { + } else if self.check_keyword(sym::macro_rules) + && self.look_ahead(1, |t| *t == token::Not) + && self.look_ahead(2, |t| t.is_ident()) + { let prev_span = self.prev_span; self.complain_if_pub_macro(&vis.node, prev_span); self.bump(); @@ -1628,17 +1603,19 @@ impl<'a> Parser<'a> { VisibilityKind::Inherited => {} _ => { let mut err = if self.token.is_keyword(sym::macro_rules) { - let mut err = self.diagnostic() + let mut err = self + .diagnostic() .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`"); err.span_suggestion( sp, "try exporting the macro", "#[macro_export]".to_owned(), - Applicability::MaybeIncorrect // speculative + Applicability::MaybeIncorrect, // speculative ); err } else { - let mut err = self.diagnostic() + let mut err = self + .diagnostic() .struct_span_err(sp, "can't qualify macro invocation with `pub`"); err.help("try adjusting the macro to put `pub` inside the invocation"); err @@ -1649,7 +1626,9 @@ impl<'a> Parser<'a> { } fn report_invalid_macro_expansion_item(&self) { - let has_close_delim = self.sess.source_map() + let has_close_delim = self + .sess + .source_map() .span_to_snippet(self.prev_span) .map(|s| s.ends_with(")") || s.ends_with("]")) .unwrap_or(false); @@ -1663,28 +1642,31 @@ impl<'a> Parser<'a> { self.struct_span_err( self.prev_span, "macros that expand to items must be delimited with braces or followed by a semicolon", - ).multipart_suggestion( + ) + .multipart_suggestion( "change the delimiters to curly braces", vec![ (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), "{".to_string()), (right_brace_span, '}'.to_string()), ], Applicability::MaybeIncorrect, - ).span_suggestion( + ) + .span_suggestion( self.sess.source_map().next_point(self.prev_span), "add a semicolon", ';'.to_string(), Applicability::MaybeIncorrect, - ).emit(); + ) + .emit(); } /// Checks if current token is one of tokens which cannot be nested like `kw::Enum`. In case /// it is, we try to parse the item and report error about nested types. fn recover_nested_adt_item(&mut self, keyword: Symbol) -> PResult<'a, bool> { - if (self.token.is_keyword(kw::Enum) || - self.token.is_keyword(kw::Struct) || - self.token.is_keyword(kw::Union)) - && self.look_ahead(1, |t| t.is_ident()) + if (self.token.is_keyword(kw::Enum) + || self.token.is_keyword(kw::Struct) + || self.token.is_keyword(kw::Union)) + && self.look_ahead(1, |t| t.is_ident()) { let kw_token = self.token.clone(); let kw_str = pprust::token_to_string(&kw_token); @@ -1693,29 +1675,29 @@ impl<'a> Parser<'a> { self.struct_span_err( kw_token.span, &format!("`{}` definition cannot be nested inside `{}`", kw_str, keyword), - ).span_suggestion( + ) + .span_suggestion( item.unwrap().span, &format!("consider creating a new `{}` definition instead of nesting", kw_str), String::new(), Applicability::MaybeIncorrect, - ).emit(); + ) + .emit(); // We successfully parsed the item but we must inform the caller about nested problem. - return Ok(false) + return Ok(false); } Ok(true) } - fn mk_item(&self, span: Span, ident: Ident, kind: ItemKind, vis: Visibility, - attrs: Vec<Attribute>) -> P<Item> { - P(Item { - ident, - attrs, - id: DUMMY_NODE_ID, - kind, - vis, - span, - tokens: None, - }) + fn mk_item( + &self, + span: Span, + ident: Ident, + kind: ItemKind, + vis: Visibility, + attrs: Vec<Attribute>, + ) -> P<Item> { + P(Item { ident, attrs, id: DUMMY_NODE_ID, kind, vis, span, tokens: None }) } } @@ -1738,10 +1720,8 @@ impl<'a> Parser<'a> { attrs: Vec<Attribute>, header: FnHeader, ) -> PResult<'a, Option<P<Item>>> { - let (ident, decl, generics) = self.parse_fn_sig(ParamCfg { - is_self_allowed: false, - is_name_required: |_| true, - })?; + let (ident, decl, generics) = + self.parse_fn_sig(ParamCfg { is_self_allowed: false, is_name_required: |_| true })?; let (inner_attrs, body) = self.parse_inner_attrs_and_block()?; let kind = ItemKind::Fn(FnSig { decl, header }, generics, body); self.mk_item_with_info(attrs, lo, vis, (ident, kind, Some(inner_attrs))) @@ -1756,10 +1736,8 @@ impl<'a> Parser<'a> { extern_sp: Span, ) -> PResult<'a, ForeignItem> { self.expect_keyword(kw::Fn)?; - let (ident, decl, generics) = self.parse_fn_sig(ParamCfg { - is_self_allowed: false, - is_name_required: |_| true, - })?; + let (ident, decl, generics) = + self.parse_fn_sig(ParamCfg { is_self_allowed: false, is_name_required: |_| true })?; let span = lo.to(self.token.span); self.parse_semi_or_incorrect_foreign_fn_body(&ident, extern_sp)?; Ok(ast::ForeignItem { @@ -1780,10 +1758,8 @@ impl<'a> Parser<'a> { is_name_required: fn(&token::Token) -> bool, ) -> PResult<'a, (Ident, AssocItemKind, Generics)> { let header = self.parse_fn_front_matter()?; - let (ident, decl, generics) = self.parse_fn_sig(ParamCfg { - is_self_allowed: true, - is_name_required, - })?; + let (ident, decl, generics) = + self.parse_fn_sig(ParamCfg { is_self_allowed: true, is_name_required })?; let sig = FnSig { header, decl }; let body = self.parse_assoc_fn_body(at_end, attrs)?; Ok((ident, AssocItemKind::Fn(sig, body), generics)) @@ -1811,17 +1787,15 @@ impl<'a> Parser<'a> { attrs.extend(inner_attrs.iter().cloned()); Some(body) } - token::Interpolated(ref nt) => { - match **nt { - token::NtBlock(..) => { - *at_end = true; - let (inner_attrs, body) = self.parse_inner_attrs_and_block()?; - attrs.extend(inner_attrs.iter().cloned()); - Some(body) - } - _ => return self.expected_semi_or_open_brace(), + token::Interpolated(ref nt) => match **nt { + token::NtBlock(..) => { + *at_end = true; + let (inner_attrs, body) = self.parse_inner_attrs_and_block()?; + attrs.extend(inner_attrs.iter().cloned()); + Some(body) } - } + _ => return self.expected_semi_or_open_brace(), + }, _ => return self.expected_semi_or_open_brace(), }) } @@ -1853,7 +1827,9 @@ impl<'a> Parser<'a> { // It is possible for `expect_one_of` to recover given the contents of // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't // account for this. - if !self.expect_one_of(&[], &[])? { unreachable!() } + if !self.expect_one_of(&[], &[])? { + unreachable!() + } } Ok(FnHeader { constness, unsafety, asyncness, ext }) } @@ -1948,8 +1924,10 @@ impl<'a> Parser<'a> { let parser_snapshot_before_ty = self.clone(); self.eat_incorrect_doc_comment_for_param_type(); let mut ty = self.parse_ty_for_param(); - if ty.is_ok() && self.token != token::Comma && - self.token != token::CloseDelim(token::Paren) { + if ty.is_ok() + && self.token != token::Comma + && self.token != token::CloseDelim(token::Paren) + { // This wasn't actually a type, but a pattern looking like a type, // so we are going to rollback and re-parse for recovery. ty = self.unexpected(); @@ -2003,13 +1981,11 @@ impl<'a> Parser<'a> { // Is `self` `n` tokens ahead? let is_isolated_self = |this: &Self, n| { this.is_keyword_ahead(n, &[kw::SelfLower]) - && this.look_ahead(n + 1, |t| t != &token::ModSep) + && this.look_ahead(n + 1, |t| t != &token::ModSep) }; // Is `mut self` `n` tokens ahead? - let is_isolated_mut_self = |this: &Self, n| { - this.is_keyword_ahead(n, &[kw::Mut]) - && is_isolated_self(this, n + 1) - }; + let is_isolated_mut_self = + |this: &Self, n| this.is_keyword_ahead(n, &[kw::Mut]) && is_isolated_self(this, n + 1); // Parse `self` or `self: TYPE`. We already know the current token is `self`. let parse_self_possibly_typed = |this: &mut Self, m| { let eself_ident = expect_self_ident(this); @@ -2025,9 +2001,7 @@ impl<'a> Parser<'a> { let recover_self_ptr = |this: &mut Self| { let msg = "cannot pass `self` by raw pointer"; let span = this.token.span; - this.struct_span_err(span, msg) - .span_label(span, msg) - .emit(); + this.struct_span_err(span, msg).span_label(span, msg).emit(); Ok((SelfKind::Value(Mutability::Not), expect_self_ident(this), this.prev_span)) }; @@ -2070,9 +2044,8 @@ impl<'a> Parser<'a> { recover_self_ptr(self)? } // `*mut self` and `*const self` - token::BinOp(token::Star) if - self.look_ahead(1, |t| t.is_mutability()) - && is_isolated_self(self, 2) => + token::BinOp(token::Star) + if self.look_ahead(1, |t| t.is_mutability()) && is_isolated_self(self, 2) => { self.bump(); self.bump(); @@ -2099,18 +2072,19 @@ impl<'a> Parser<'a> { token::Interpolated(ref nt) => match **nt { token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon), _ => 0, - } + }, token::BinOp(token::And) | token::AndAnd => 1, _ if self.token.is_keyword(kw::Mut) => 1, _ => 0, }; - self.look_ahead(offset, |t| t.is_ident()) && - self.look_ahead(offset + 1, |t| t == &token::Colon) + self.look_ahead(offset, |t| t.is_ident()) + && self.look_ahead(offset + 1, |t| t == &token::Colon) } fn recover_first_param(&mut self) -> &'static str { - match self.parse_outer_attributes() + match self + .parse_outer_attributes() .and_then(|_| self.parse_self_param()) .map_err(|mut e| e.cancel()) { diff --git a/src/librustc_parse/parser/mod.rs b/src/librustc_parse/parser/mod.rs index 16bc2e1a8d6..97084482025 100644 --- a/src/librustc_parse/parser/mod.rs +++ b/src/librustc_parse/parser/mod.rs @@ -1,37 +1,37 @@ pub mod attr; mod expr; -mod pat; mod item; mod module; -mod ty; +mod pat; mod path; +mod ty; pub use path::PathStyle; -mod stmt; -mod generics; mod diagnostics; +mod generics; +mod stmt; use diagnostics::Error; -use crate::{Directory, DirectoryOwnership}; use crate::lexer::UnmatchedBrace; +use crate::{Directory, DirectoryOwnership}; -use rustc_errors::{PResult, Applicability, DiagnosticBuilder, FatalError}; -use syntax::ast::{self, DUMMY_NODE_ID, AttrVec, AttrStyle, CrateSugar, Extern, Ident, Unsafety}; -use syntax::ast::{StrLit, IsAsync, MacArgs, MacDelimiter, Mutability, Visibility, VisibilityKind}; +use log::debug; +use rustc_errors::{Applicability, DiagnosticBuilder, FatalError, PResult}; +use syntax::ast::{self, AttrStyle, AttrVec, CrateSugar, Extern, Ident, Unsafety, DUMMY_NODE_ID}; +use syntax::ast::{IsAsync, MacArgs, MacDelimiter, Mutability, StrLit, Visibility, VisibilityKind}; use syntax::print::pprust; use syntax::ptr::P; -use syntax::token::{self, Token, TokenKind, DelimToken}; -use syntax::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint}; use syntax::sess::ParseSess; use syntax::struct_span_err; +use syntax::token::{self, DelimToken, Token, TokenKind}; +use syntax::tokenstream::{self, DelimSpan, TokenStream, TokenTree, TreeAndJoint}; use syntax::util::comments::{doc_comment_style, strip_doc_comment_decoration}; use syntax_pos::source_map::respan; use syntax_pos::symbol::{kw, sym, Symbol}; -use syntax_pos::{Span, BytePos, DUMMY_SP, FileName}; -use log::debug; +use syntax_pos::{BytePos, FileName, Span, DUMMY_SP}; use std::borrow::Cow; -use std::{cmp, mem, slice}; use std::path::PathBuf; +use std::{cmp, mem, slice}; use rustc_error_codes::*; @@ -82,7 +82,7 @@ macro_rules! maybe_recover_from_interpolated_ty_qpath { } } } - } + }; } #[derive(Debug, Clone, Copy, PartialEq)] @@ -216,7 +216,7 @@ impl TokenCursor { TokenTree::close_tt(self.frame.span, self.frame.delim) } else if let Some(frame) = self.stack.pop() { self.frame = frame; - continue + continue; } else { return Token::new(token::Eof, DUMMY_SP); }; @@ -264,24 +264,35 @@ impl TokenCursor { [ TokenTree::token(token::Ident(sym::doc, false), sp), TokenTree::token(token::Eq, sp), - TokenTree::token(TokenKind::lit( - token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None - ), sp), + TokenTree::token( + TokenKind::lit(token::StrRaw(num_of_hashes), Symbol::intern(&stripped), None), + sp, + ), ] - .iter().cloned().collect::<TokenStream>().into(), + .iter() + .cloned() + .collect::<TokenStream>() + .into(), ); - self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new( - delim_span, - token::NoDelim, - &if doc_comment_style(&name.as_str()) == AttrStyle::Inner { - [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body] - .iter().cloned().collect::<TokenStream>() - } else { - [TokenTree::token(token::Pound, sp), body] - .iter().cloned().collect::<TokenStream>() - }, - ))); + self.stack.push(mem::replace( + &mut self.frame, + TokenCursorFrame::new( + delim_span, + token::NoDelim, + &if doc_comment_style(&name.as_str()) == AttrStyle::Inner { + [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body] + .iter() + .cloned() + .collect::<TokenStream>() + } else { + [TokenTree::token(token::Pound, sp), body] + .iter() + .cloned() + .collect::<TokenStream>() + }, + ), + )); self.next() } @@ -330,21 +341,18 @@ struct SeqSep { impl SeqSep { fn trailing_allowed(t: TokenKind) -> SeqSep { - SeqSep { - sep: Some(t), - trailing_sep_allowed: true, - } + SeqSep { sep: Some(t), trailing_sep_allowed: true } } fn none() -> SeqSep { - SeqSep { - sep: None, - trailing_sep_allowed: false, - } + SeqSep { sep: None, trailing_sep_allowed: false } } } -pub enum FollowedByType { Yes, No } +pub enum FollowedByType { + Yes, + No, +} impl<'a> Parser<'a> { pub fn new( @@ -365,16 +373,12 @@ impl<'a> Parser<'a> { recurse_into_file_modules, directory: Directory { path: Cow::from(PathBuf::new()), - ownership: DirectoryOwnership::Owned { relative: None } + ownership: DirectoryOwnership::Owned { relative: None }, }, root_module_name: None, expected_tokens: Vec::new(), token_cursor: TokenCursor { - frame: TokenCursorFrame::new( - DelimSpan::dummy(), - token::NoDelim, - &tokens.into(), - ), + frame: TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, &tokens.into()), stack: Vec::new(), }, desugar_doc_comments, @@ -393,7 +397,8 @@ impl<'a> Parser<'a> { parser.directory = directory; } else if !parser.token.span.is_dummy() { if let Some(FileName::Real(path)) = - &sess.source_map().lookup_char_pos(parser.token.span.lo()).file.unmapped_path { + &sess.source_map().lookup_char_pos(parser.token.span.lo()).file.unmapped_path + { if let Some(directory_path) = path.parent() { parser.directory.path = Cow::from(directory_path.to_path_buf()); } @@ -503,13 +508,11 @@ impl<'a> Parser<'a> { self.bump(); Ok(Ident::new(name, span)) } - _ => { - Err(if self.prev_token_kind == PrevTokenKind::DocComment { - self.span_fatal_err(self.prev_span, Error::UselessDocComment) - } else { - self.expected_ident_found() - }) - } + _ => Err(if self.prev_token_kind == PrevTokenKind::DocComment { + self.span_fatal_err(self.prev_span, Error::UselessDocComment) + } else { + self.expected_ident_found() + }), } } @@ -519,14 +522,18 @@ impl<'a> Parser<'a> { /// encountered. fn check(&mut self, tok: &TokenKind) -> bool { let is_present = self.token == *tok; - if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); } + if !is_present { + self.expected_tokens.push(TokenType::Token(tok.clone())); + } is_present } /// Consumes a token 'tok' if it exists. Returns whether the given token was present. pub fn eat(&mut self, tok: &TokenKind) -> bool { let is_present = self.check(tok); - if is_present { self.bump() } + if is_present { + self.bump() + } is_present } @@ -561,11 +568,7 @@ impl<'a> Parser<'a> { /// If the next token is not the given word, signals an error. /// Otherwise, eats it. fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { - if !self.eat_keyword(kw) { - self.unexpected() - } else { - Ok(()) - } + if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } } fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { @@ -636,7 +639,7 @@ impl<'a> Parser<'a> { let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1)); Ok(self.bump_with(token::BinOp(token::And), span)) } - _ => self.unexpected() + _ => self.unexpected(), } } @@ -653,7 +656,7 @@ impl<'a> Parser<'a> { let span = self.token.span.with_lo(self.token.span.lo() + BytePos(1)); Ok(self.bump_with(token::BinOp(token::Or), span)) } - _ => self.unexpected() + _ => self.unexpected(), } } @@ -694,11 +697,7 @@ impl<'a> Parser<'a> { } fn expect_lt(&mut self) -> PResult<'a, ()> { - if !self.eat_lt() { - self.unexpected() - } else { - Ok(()) - } + if !self.eat_lt() { self.unexpected() } else { Ok(()) } } /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it @@ -734,17 +733,15 @@ impl<'a> Parser<'a> { } Ok(()) - }, + } None => self.unexpected(), } } fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool { - kets.iter().any(|k| { - match expect { - TokenExpectType::Expect => self.check(k), - TokenExpectType::NoExpect => self.token == **k, - } + kets.iter().any(|k| match expect { + TokenExpectType::Expect => self.check(k), + TokenExpectType::NoExpect => self.token == **k, }) } @@ -761,7 +758,7 @@ impl<'a> Parser<'a> { let mut v = vec![]; while !self.expect_any_with_type(kets, expect) { if let token::CloseDelim(..) | token::Eof = self.token.kind { - break + break; } if let Some(ref t) = sep.sep { if first { @@ -800,7 +797,7 @@ impl<'a> Parser<'a> { v.push(t); continue; - }, + } Err(mut e) => { // Parsing failed, therefore it must be something more serious // than just a missing separator. @@ -845,7 +842,7 @@ impl<'a> Parser<'a> { &mut self, ket: &TokenKind, sep: SeqSep, - f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, + f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, ) -> PResult<'a, (Vec<T>, bool /* trailing */)> { let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; if !recovered { @@ -938,10 +935,11 @@ impl<'a> Parser<'a> { looker(&match frame.tree_cursor.look_ahead(dist - 1) { Some(tree) => match tree { TokenTree::Token(token) => token, - TokenTree::Delimited(dspan, delim, _) => - Token::new(token::OpenDelim(delim), dspan.open), - } - None => Token::new(token::CloseDelim(frame.delim), frame.span.close) + TokenTree::Delimited(dspan, delim, _) => { + Token::new(token::OpenDelim(delim), dspan.open) + } + }, + None => Token::new(token::CloseDelim(frame.delim), frame.span.close), }) } @@ -953,10 +951,7 @@ impl<'a> Parser<'a> { /// Parses asyncness: `async` or nothing. fn parse_asyncness(&mut self) -> IsAsync { if self.eat_keyword(kw::Async) { - IsAsync::Async { - closure_id: DUMMY_NODE_ID, - return_impl_trait_id: DUMMY_NODE_ID, - } + IsAsync::Async { closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID } } else { IsAsync::NotAsync } @@ -964,20 +959,12 @@ impl<'a> Parser<'a> { /// Parses unsafety: `unsafe` or nothing. fn parse_unsafety(&mut self) -> Unsafety { - if self.eat_keyword(kw::Unsafe) { - Unsafety::Unsafe - } else { - Unsafety::Normal - } + if self.eat_keyword(kw::Unsafe) { Unsafety::Unsafe } else { Unsafety::Normal } } /// Parses mutability (`mut` or nothing). fn parse_mutability(&mut self) -> Mutability { - if self.eat_keyword(kw::Mut) { - Mutability::Mut - } else { - Mutability::Not - } + if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not } } /// Possibly parses mutability (`const` or `mut`). @@ -992,8 +979,8 @@ impl<'a> Parser<'a> { } fn parse_field_name(&mut self) -> PResult<'a, Ident> { - if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = - self.token.kind { + if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind + { self.expect_no_suffix(self.token.span, "a tuple index", suffix); self.bump(); Ok(Ident::new(symbol, self.prev_span)) @@ -1011,40 +998,45 @@ impl<'a> Parser<'a> { } fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> { - Ok(if self.check(&token::OpenDelim(DelimToken::Paren)) || - self.check(&token::OpenDelim(DelimToken::Bracket)) || - self.check(&token::OpenDelim(DelimToken::Brace)) { - match self.parse_token_tree() { - TokenTree::Delimited(dspan, delim, tokens) => + Ok( + if self.check(&token::OpenDelim(DelimToken::Paren)) + || self.check(&token::OpenDelim(DelimToken::Bracket)) + || self.check(&token::OpenDelim(DelimToken::Brace)) + { + match self.parse_token_tree() { + TokenTree::Delimited(dspan, delim, tokens) => // We've confirmed above that there is a delimiter so unwrapping is OK. - MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens), - _ => unreachable!(), - } - } else if !delimited_only { - if self.eat(&token::Eq) { - let eq_span = self.prev_span; - let mut is_interpolated_expr = false; - if let token::Interpolated(nt) = &self.token.kind { - if let token::NtExpr(..) = **nt { - is_interpolated_expr = true; + { + MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens) } + _ => unreachable!(), } - let token_tree = if is_interpolated_expr { - // We need to accept arbitrary interpolated expressions to continue - // supporting things like `doc = $expr` that work on stable. - // Non-literal interpolated expressions are rejected after expansion. - self.parse_token_tree() - } else { - self.parse_unsuffixed_lit()?.token_tree() - }; + } else if !delimited_only { + if self.eat(&token::Eq) { + let eq_span = self.prev_span; + let mut is_interpolated_expr = false; + if let token::Interpolated(nt) = &self.token.kind { + if let token::NtExpr(..) = **nt { + is_interpolated_expr = true; + } + } + let token_tree = if is_interpolated_expr { + // We need to accept arbitrary interpolated expressions to continue + // supporting things like `doc = $expr` that work on stable. + // Non-literal interpolated expressions are rejected after expansion. + self.parse_token_tree() + } else { + self.parse_unsuffixed_lit()?.token_tree() + }; - MacArgs::Eq(eq_span, token_tree.into()) + MacArgs::Eq(eq_span, token_tree.into()) + } else { + MacArgs::Empty + } } else { - MacArgs::Empty - } - } else { - return self.unexpected(); - }) + return self.unexpected(); + }, + ) } fn parse_or_use_outer_attributes( @@ -1060,12 +1052,13 @@ impl<'a> Parser<'a> { pub fn process_potential_macro_variable(&mut self) { self.token = match self.token.kind { - token::Dollar if self.token.span.from_expansion() && - self.look_ahead(1, |t| t.is_ident()) => { + token::Dollar + if self.token.span.from_expansion() && self.look_ahead(1, |t| t.is_ident()) => + { self.bump(); let name = match self.token.kind { token::Ident(name, _) => name, - _ => unreachable!() + _ => unreachable!(), }; let span = self.prev_span.to(self.token.span); self.diagnostic() @@ -1073,17 +1066,17 @@ impl<'a> Parser<'a> { .span_label(span, "unknown macro variable") .emit(); self.bump(); - return + return; } token::Interpolated(ref nt) => { self.meta_var_span = Some(self.token.span); // Interpolated identifier and lifetime tokens are replaced with usual identifier // and lifetime tokens, so the former are never encountered during normal parsing. match **nt { - token::NtIdent(ident, is_raw) => - Token::new(token::Ident(ident.name, is_raw), ident.span), - token::NtLifetime(ident) => - Token::new(token::Lifetime(ident.name), ident.span), + token::NtIdent(ident, is_raw) => { + Token::new(token::Ident(ident.name, is_raw), ident.span) + } + token::NtLifetime(ident) => Token::new(token::Lifetime(ident.name), ident.span), _ => return, } } @@ -1095,16 +1088,14 @@ impl<'a> Parser<'a> { pub fn parse_token_tree(&mut self) -> TokenTree { match self.token.kind { token::OpenDelim(..) => { - let frame = mem::replace(&mut self.token_cursor.frame, - self.token_cursor.stack.pop().unwrap()); + let frame = mem::replace( + &mut self.token_cursor.frame, + self.token_cursor.stack.pop().unwrap(), + ); self.token.span = frame.span.entire(); self.bump(); - TokenTree::Delimited( - frame.span, - frame.delim, - frame.tree_cursor.stream.into(), - ) - }, + TokenTree::Delimited(frame.span, frame.delim, frame.tree_cursor.stream.into()) + } token::CloseDelim(_) | token::Eof => unreachable!(), _ => { let token = self.token.take(); @@ -1168,7 +1159,7 @@ impl<'a> Parser<'a> { // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no // keyword to grab a span from for inherited visibility; an empty span at the // beginning of the current token would seem to be the "Schelling span". - return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited)) + return Ok(respan(self.token.span.shrink_to_lo(), VisibilityKind::Inherited)); } let lo = self.prev_span; @@ -1177,8 +1168,8 @@ impl<'a> Parser<'a> { // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`. // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so // by the following tokens. - if self.is_keyword_ahead(1, &[kw::Crate]) - && self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)` + if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep) + // account for `pub(crate::foo)` { // Parse `pub(crate)`. self.bump(); // `(` @@ -1192,10 +1183,7 @@ impl<'a> Parser<'a> { self.bump(); // `in` let path = self.parse_path(PathStyle::Mod)?; // `path` self.expect(&token::CloseDelim(token::Paren))?; // `)` - let vis = VisibilityKind::Restricted { - path: P(path), - id: ast::DUMMY_NODE_ID, - }; + let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID }; return Ok(respan(lo.to(self.prev_span), vis)); } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower]) @@ -1204,10 +1192,7 @@ impl<'a> Parser<'a> { self.bump(); // `(` let path = self.parse_path(PathStyle::Mod)?; // `super`/`self` self.expect(&token::CloseDelim(token::Paren))?; // `)` - let vis = VisibilityKind::Restricted { - path: P(path), - id: ast::DUMMY_NODE_ID, - }; + let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID }; return Ok(respan(lo.to(self.prev_span), vis)); } else if let FollowedByType::No = fbt { // Provide this diagnostic if a type cannot follow; @@ -1224,7 +1209,7 @@ impl<'a> Parser<'a> { fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> { self.bump(); // `(` let path = self.parse_path(PathStyle::Mod)?; - self.expect(&token::CloseDelim(token::Paren))?; // `)` + self.expect(&token::CloseDelim(token::Paren))?; // `)` let msg = "incorrect visibility restriction"; let suggestion = r##"some possible visibility restrictions are: @@ -1273,7 +1258,7 @@ impl<'a> Parser<'a> { .emit(); None } - } + }, Err(None) => None, } } @@ -1298,9 +1283,7 @@ impl<'a> Parser<'a> { // Record all tokens we parse when parsing this item. let mut tokens = Vec::new(); let prev_collecting = match self.token_cursor.frame.last_token { - LastToken::Collecting(ref mut list) => { - Some(mem::take(list)) - } + LastToken::Collecting(ref mut list) => Some(mem::take(list)), LastToken::Was(ref mut last) => { tokens.extend(last.take()); None @@ -1337,11 +1320,7 @@ impl<'a> Parser<'a> { // If we're not at EOF our current token wasn't actually consumed by // `f`, but it'll still be in our list that we pulled out. In that case // put it back. - let extra_token = if self.token != token::Eof { - collected_tokens.pop() - } else { - None - }; + let extra_token = if self.token != token::Eof { collected_tokens.pop() } else { None }; // If we were previously collecting tokens, then this was a recursive // call. In that case we need to record all the tokens we collected in @@ -1363,9 +1342,10 @@ impl<'a> Parser<'a> { /// `::{` or `::*` fn is_import_coupler(&mut self) -> bool { - self.check(&token::ModSep) && - self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) || - *t == token::BinOp(token::Star)) + self.check(&token::ModSep) + && self.look_ahead(1, |t| { + *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star) + }) } } @@ -1376,10 +1356,13 @@ crate fn make_unclosed_delims_error( // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to // `unmatched_braces` only for error recovery in the `Parser`. let found_delim = unmatched.found_delim?; - let mut err = sess.span_diagnostic.struct_span_err(unmatched.found_span, &format!( - "incorrect close delimiter: `{}`", - pprust::token_kind_to_string(&token::CloseDelim(found_delim)), - )); + let mut err = sess.span_diagnostic.struct_span_err( + unmatched.found_span, + &format!( + "incorrect close delimiter: `{}`", + pprust::token_kind_to_string(&token::CloseDelim(found_delim)), + ), + ); err.span_label(unmatched.found_span, "incorrect close delimiter"); if let Some(sp) = unmatched.candidate_span { err.span_label(sp, "close delimiter possibly meant for this"); @@ -1391,8 +1374,8 @@ crate fn make_unclosed_delims_error( } pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, sess: &ParseSess) { - *sess.reached_eof.borrow_mut() |= unclosed_delims.iter() - .any(|unmatched_delim| unmatched_delim.found_delim.is_none()); + *sess.reached_eof.borrow_mut() |= + unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()); for unmatched in unclosed_delims.drain(..) { make_unclosed_delims_error(unmatched, sess).map(|mut e| e.emit()); } diff --git a/src/librustc_parse/parser/module.rs b/src/librustc_parse/parser/module.rs index 3777e17b5a1..eaeb3af4ca2 100644 --- a/src/librustc_parse/parser/module.rs +++ b/src/librustc_parse/parser/module.rs @@ -1,14 +1,14 @@ -use super::Parser; -use super::item::ItemInfo; use super::diagnostics::Error; +use super::item::ItemInfo; +use super::Parser; use crate::{new_sub_parser_from_file, DirectoryOwnership}; use rustc_errors::PResult; +use syntax::ast::{self, Attribute, Crate, Ident, ItemKind, Mod}; use syntax::attr; -use syntax::ast::{self, Ident, Attribute, ItemKind, Mod, Crate}; use syntax::token::{self, TokenKind}; -use syntax_pos::source_map::{SourceMap, Span, DUMMY_SP, FileName}; +use syntax_pos::source_map::{FileName, SourceMap, Span, DUMMY_SP}; use syntax_pos::symbol::sym; use std::path::{self, Path, PathBuf}; @@ -39,11 +39,8 @@ impl<'a> Parser<'a> { /// Parses a `mod <foo> { ... }` or `mod <foo>;` item. pub(super) fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> { - let (in_cfg, outer_attrs) = crate::config::process_configure_mod( - self.sess, - self.cfg_mods, - outer_attrs, - ); + let (in_cfg, outer_attrs) = + crate::config::process_configure_mod(self.sess, self.cfg_mods, outer_attrs); let id_span = self.token.span; let id = self.parse_ident()?; @@ -56,11 +53,7 @@ impl<'a> Parser<'a> { self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?; Ok((id, ItemKind::Mod(module), Some(attrs))) } else { - let placeholder = ast::Mod { - inner: DUMMY_SP, - items: Vec::new(), - inline: false - }; + let placeholder = ast::Mod { inner: DUMMY_SP, items: Vec::new(), inline: false }; Ok((id, ItemKind::Mod(placeholder), None)) } } else { @@ -94,24 +87,16 @@ impl<'a> Parser<'a> { } } - let hi = if self.token.span.is_dummy() { - inner_lo - } else { - self.prev_span - }; + let hi = if self.token.span.is_dummy() { inner_lo } else { self.prev_span }; - Ok(Mod { - inner: inner_lo.to(hi), - items, - inline: true - }) + Ok(Mod { inner: inner_lo.to(hi), items, inline: true }) } fn submod_path( &mut self, id: ast::Ident, outer_attrs: &[Attribute], - id_sp: Span + id_sp: Span, ) -> PResult<'a, ModulePathSuccess> { if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) { return Ok(ModulePathSuccess { @@ -132,31 +117,32 @@ impl<'a> Parser<'a> { let relative = match self.directory.ownership { DirectoryOwnership::Owned { relative } => relative, - DirectoryOwnership::UnownedViaBlock | - DirectoryOwnership::UnownedViaMod => None, + DirectoryOwnership::UnownedViaBlock | DirectoryOwnership::UnownedViaMod => None, }; - let paths = Parser::default_submod_path( - id, relative, &self.directory.path, self.sess.source_map()); + let paths = + Parser::default_submod_path(id, relative, &self.directory.path, self.sess.source_map()); match self.directory.ownership { DirectoryOwnership::Owned { .. } => { paths.result.map_err(|err| self.span_fatal_err(id_sp, err)) - }, + } DirectoryOwnership::UnownedViaBlock => { - let msg = - "Cannot declare a non-inline module inside a block \ + let msg = "Cannot declare a non-inline module inside a block \ unless it has a path attribute"; let mut err = self.diagnostic().struct_span_err(id_sp, msg); if paths.path_exists { - let msg = format!("Maybe `use` the module `{}` instead of redeclaring it", - paths.name); + let msg = format!( + "Maybe `use` the module `{}` instead of redeclaring it", + paths.name + ); err.span_note(id_sp, &msg); } Err(err) } DirectoryOwnership::UnownedViaMod => { - let mut err = self.diagnostic().struct_span_err(id_sp, - "cannot declare a new module at this location"); + let mut err = self + .diagnostic() + .struct_span_err(id_sp, "cannot declare a new module at this location"); if !id_sp.is_dummy() { let src_path = self.sess.source_map().span_to_filename(id_sp); if let FileName::Real(src_path) = src_path { @@ -164,18 +150,27 @@ impl<'a> Parser<'a> { let mut dest_path = src_path.clone(); dest_path.set_file_name(stem); dest_path.push("mod.rs"); - err.span_note(id_sp, - &format!("maybe move this module `{}` to its own \ - directory via `{}`", src_path.display(), - dest_path.display())); + err.span_note( + id_sp, + &format!( + "maybe move this module `{}` to its own \ + directory via `{}`", + src_path.display(), + dest_path.display() + ), + ); } } } if paths.path_exists { - err.span_note(id_sp, - &format!("... or maybe `use` the module `{}` instead \ + err.span_note( + id_sp, + &format!( + "... or maybe `use` the module `{}` instead \ of possibly redeclaring it", - paths.name)); + paths.name + ), + ); } Err(err) } @@ -203,8 +198,8 @@ impl<'a> Parser<'a> { id: ast::Ident, relative: Option<ast::Ident>, dir_path: &Path, - source_map: &SourceMap) -> ModulePath - { + source_map: &SourceMap, + ) -> ModulePath { // If we're in a foo.rs file instead of a mod.rs file, // we need to look for submodules in // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than @@ -219,8 +214,8 @@ impl<'a> Parser<'a> { let mod_name = id.name.to_string(); let default_path_str = format!("{}{}.rs", relative_prefix, mod_name); - let secondary_path_str = format!("{}{}{}mod.rs", - relative_prefix, mod_name, path::MAIN_SEPARATOR); + let secondary_path_str = + format!("{}{}{}mod.rs", relative_prefix, mod_name, path::MAIN_SEPARATOR); let default_path = dir_path.join(&default_path_str); let secondary_path = dir_path.join(&secondary_path_str); let default_exists = source_map.file_exists(&default_path); @@ -229,15 +224,11 @@ impl<'a> Parser<'a> { let result = match (default_exists, secondary_exists) { (true, false) => Ok(ModulePathSuccess { path: default_path, - directory_ownership: DirectoryOwnership::Owned { - relative: Some(id), - }, + directory_ownership: DirectoryOwnership::Owned { relative: Some(id) }, }), (false, true) => Ok(ModulePathSuccess { path: secondary_path, - directory_ownership: DirectoryOwnership::Owned { - relative: None, - }, + directory_ownership: DirectoryOwnership::Owned { relative: None }, }), (false, false) => Err(Error::FileNotFoundForModule { mod_name: mod_name.clone(), @@ -252,11 +243,7 @@ impl<'a> Parser<'a> { }), }; - ModulePath { - name: mod_name, - path_exists: default_exists || secondary_exists, - result, - } + ModulePath { name: mod_name, path_exists: default_exists || secondary_exists, result } } /// Reads a module from a source file. @@ -271,7 +258,7 @@ impl<'a> Parser<'a> { if let Some(i) = included_mod_stack.iter().position(|p| *p == path) { let mut err = String::from("circular modules: "); let len = included_mod_stack.len(); - for p in &included_mod_stack[i.. len] { + for p in &included_mod_stack[i..len] { err.push_str(&p.to_string_lossy()); err.push_str(" -> "); } @@ -304,7 +291,8 @@ impl<'a> Parser<'a> { // For example, a `mod z { ... }` inside `x/y.rs` should set the current // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`. if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership { - if let Some(ident) = relative.take() { // remove the relative offset + if let Some(ident) = relative.take() { + // remove the relative offset self.directory.path.to_mut().push(&*ident.as_str()); } } diff --git a/src/librustc_parse/parser/pat.rs b/src/librustc_parse/parser/pat.rs index 33cac1aacee..9b5bf7e2378 100644 --- a/src/librustc_parse/parser/pat.rs +++ b/src/librustc_parse/parser/pat.rs @@ -1,11 +1,11 @@ use super::{Parser, PathStyle}; use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole}; -use rustc_errors::{PResult, Applicability, DiagnosticBuilder}; -use syntax::ast::{self, AttrVec, Attribute, Pat, PatKind, FieldPat, RangeEnd, RangeSyntax, Mac}; -use syntax::ast::{BindingMode, Ident, Mutability, Path, QSelf, Expr, ExprKind}; -use syntax::mut_visit::{noop_visit_pat, noop_visit_mac, MutVisitor}; -use syntax::ptr::P; +use rustc_errors::{Applicability, DiagnosticBuilder, PResult}; +use syntax::ast::{self, AttrVec, Attribute, FieldPat, Mac, Pat, PatKind, RangeEnd, RangeSyntax}; +use syntax::ast::{BindingMode, Expr, ExprKind, Ident, Mutability, Path, QSelf}; +use syntax::mut_visit::{noop_visit_mac, noop_visit_pat, MutVisitor}; use syntax::print::pprust; +use syntax::ptr::P; use syntax::token; use syntax_pos::source_map::{respan, Span, Spanned}; use syntax_pos::symbol::{kw, sym}; @@ -19,11 +19,17 @@ const WHILE_PARSING_OR_MSG: &str = "while parsing this or-pattern starting here" /// Whether or not an or-pattern should be gated when occurring in the current context. #[derive(PartialEq)] -pub(super) enum GateOr { Yes, No } +pub(super) enum GateOr { + Yes, + No, +} /// Whether or not to recover a `,` when parsing or-patterns. #[derive(PartialEq, Copy, Clone)] -enum RecoverComma { Yes, No } +enum RecoverComma { + Yes, + No, +} impl<'a> Parser<'a> { /// Parses a pattern. @@ -93,7 +99,7 @@ impl<'a> Parser<'a> { // If the next token is not a `|`, // this is not an or-pattern and we should exit here. if !self.check(&token::BinOp(token::Or)) && self.token != token::OrOr { - return Ok(first_pat) + return Ok(first_pat); } // Parse the patterns `p_1 | ... | p_n` where `n > 0`. @@ -172,7 +178,7 @@ impl<'a> Parser<'a> { self.token.span, "use a single `|` to separate multiple alternative patterns", "|".to_owned(), - Applicability::MachineApplicable + Applicability::MachineApplicable, ); if let Some(lo) = lo { err.span_label(lo, WHILE_PARSING_OR_MSG); @@ -205,13 +211,13 @@ impl<'a> Parser<'a> { seq_span, "try adding parentheses to match on a tuple..", format!("({})", seq_snippet), - Applicability::MachineApplicable + Applicability::MachineApplicable, ) .span_suggestion( seq_span, "..or a vertical bar to match on multiple alternatives", format!("{}", seq_snippet.replace(",", " |")), - Applicability::MachineApplicable + Applicability::MachineApplicable, ); } Err(err) @@ -223,7 +229,7 @@ impl<'a> Parser<'a> { while !self.check(&token::CloseDelim(token::Paren)) { self.parse_pat(None)?; if !self.eat(&token::Comma) { - return Ok(()) + return Ok(()); } } Ok(()) @@ -280,10 +286,8 @@ impl<'a> Parser<'a> { token::OpenDelim(token::Paren) => self.parse_pat_tuple_or_parens()?, token::OpenDelim(token::Bracket) => { // Parse `[pat, pat,...]` as a slice pattern. - let (pats, _) = self.parse_delim_comma_seq( - token::Bracket, - |p| p.parse_pat_with_or_inner(), - )?; + let (pats, _) = + self.parse_delim_comma_seq(token::Bracket, |p| p.parse_pat_with_or_inner())?; PatKind::Slice(pats) } token::DotDot => { @@ -307,56 +311,60 @@ impl<'a> Parser<'a> { self.parse_pat_range_to(RangeEnd::Included(RangeSyntax::DotDotDot), "...")? } // At this point, token != `&`, `&&`, `(`, `[`, `..`, `..=`, or `...`. - _ => if self.eat_keyword(kw::Underscore) { - // Parse _ - PatKind::Wild - } else if self.eat_keyword(kw::Mut) { - self.parse_pat_ident_mut()? - } else if self.eat_keyword(kw::Ref) { - // Parse ref ident @ pat / ref mut ident @ pat - let mutbl = self.parse_mutability(); - self.parse_pat_ident(BindingMode::ByRef(mutbl))? - } else if self.eat_keyword(kw::Box) { - // Parse `box pat` - let pat = self.parse_pat_with_range_pat(false, None)?; - self.sess.gated_spans.gate(sym::box_patterns, lo.to(self.prev_span)); - PatKind::Box(pat) - } else if self.can_be_ident_pat() { - // Parse `ident @ pat` - // This can give false positives and parse nullary enums, - // they are dealt with later in resolve. - self.parse_pat_ident(BindingMode::ByValue(Mutability::Not))? - } else if self.is_start_of_pat_with_path() { - // Parse pattern starting with a path - let (qself, path) = if self.eat_lt() { - // Parse a qualified path - let (qself, path) = self.parse_qpath(PathStyle::Expr)?; - (Some(qself), path) - } else { - // Parse an unqualified path - (None, self.parse_path(PathStyle::Expr)?) - }; - match self.token.kind { - token::Not if qself.is_none() => self.parse_pat_mac_invoc(path)?, - token::DotDotDot | token::DotDotEq | token::DotDot => { - self.parse_pat_range_starting_with_path(lo, qself, path)? + _ => { + if self.eat_keyword(kw::Underscore) { + // Parse _ + PatKind::Wild + } else if self.eat_keyword(kw::Mut) { + self.parse_pat_ident_mut()? + } else if self.eat_keyword(kw::Ref) { + // Parse ref ident @ pat / ref mut ident @ pat + let mutbl = self.parse_mutability(); + self.parse_pat_ident(BindingMode::ByRef(mutbl))? + } else if self.eat_keyword(kw::Box) { + // Parse `box pat` + let pat = self.parse_pat_with_range_pat(false, None)?; + self.sess.gated_spans.gate(sym::box_patterns, lo.to(self.prev_span)); + PatKind::Box(pat) + } else if self.can_be_ident_pat() { + // Parse `ident @ pat` + // This can give false positives and parse nullary enums, + // they are dealt with later in resolve. + self.parse_pat_ident(BindingMode::ByValue(Mutability::Not))? + } else if self.is_start_of_pat_with_path() { + // Parse pattern starting with a path + let (qself, path) = if self.eat_lt() { + // Parse a qualified path + let (qself, path) = self.parse_qpath(PathStyle::Expr)?; + (Some(qself), path) + } else { + // Parse an unqualified path + (None, self.parse_path(PathStyle::Expr)?) + }; + match self.token.kind { + token::Not if qself.is_none() => self.parse_pat_mac_invoc(path)?, + token::DotDotDot | token::DotDotEq | token::DotDot => { + self.parse_pat_range_starting_with_path(lo, qself, path)? + } + token::OpenDelim(token::Brace) => self.parse_pat_struct(qself, path)?, + token::OpenDelim(token::Paren) => { + self.parse_pat_tuple_struct(qself, path)? + } + _ => PatKind::Path(qself, path), } - token::OpenDelim(token::Brace) => self.parse_pat_struct(qself, path)?, - token::OpenDelim(token::Paren) => self.parse_pat_tuple_struct(qself, path)?, - _ => PatKind::Path(qself, path), - } - } else { - // Try to parse everything else as literal with optional minus - match self.parse_literal_maybe_minus() { - Ok(begin) - if self.check(&token::DotDot) - || self.check(&token::DotDotEq) - || self.check(&token::DotDotDot) => - { - self.parse_pat_range_starting_with_lit(begin)? + } else { + // Try to parse everything else as literal with optional minus + match self.parse_literal_maybe_minus() { + Ok(begin) + if self.check(&token::DotDot) + || self.check(&token::DotDotEq) + || self.check(&token::DotDotDot) => + { + self.parse_pat_range_starting_with_lit(begin)? + } + Ok(begin) => PatKind::Lit(begin), + Err(err) => return self.fatal_unexpected_non_pat(err, expected), } - Ok(begin) => PatKind::Lit(begin), - Err(err) => return self.fatal_unexpected_non_pat(err, expected), } } }; @@ -403,7 +411,7 @@ impl<'a> Parser<'a> { PatKind::Ident(..) => { applicability = Applicability::MaybeIncorrect; false // Short-circuit. - }, + } _ => true, }); @@ -435,22 +443,21 @@ impl<'a> Parser<'a> { fn ban_pat_range_if_ambiguous(&self, pat: &Pat) -> PResult<'a, ()> { match pat.kind { PatKind::Range( - .., Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. } + .., + Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }, ) => return Ok(()), PatKind::Range(..) => {} _ => return Ok(()), } - let mut err = self.struct_span_err( - pat.span, - "the range pattern here has ambiguous interpretation", - ); + let mut err = + self.struct_span_err(pat.span, "the range pattern here has ambiguous interpretation"); err.span_suggestion( pat.span, "add parentheses to clarify the precedence", format!("({})", pprust::pat_to_string(&pat)), // "ambiguous interpretation" implies that we have to be guessing - Applicability::MaybeIncorrect + Applicability::MaybeIncorrect, ); Err(err) } @@ -482,7 +489,8 @@ impl<'a> Parser<'a> { /// Parse a tuple or parenthesis pattern. fn parse_pat_tuple_or_parens(&mut self) -> PResult<'a, PatKind> { - let (fields, trailing_comma) = self.parse_paren_comma_seq(|p| p.parse_pat_with_or_inner())?; + let (fields, trailing_comma) = + self.parse_paren_comma_seq(|p| p.parse_pat_with_or_inner())?; // Here, `(pat,)` is a tuple pattern. // For backward compatibility, `(..)` is a tuple pattern as well. @@ -498,16 +506,16 @@ impl<'a> Parser<'a> { let mut_span = self.prev_span; if self.eat_keyword(kw::Ref) { - return self.recover_mut_ref_ident(mut_span) + return self.recover_mut_ref_ident(mut_span); } self.recover_additional_muts(); // Make sure we don't allow e.g. `let mut $p;` where `$p:pat`. if let token::Interpolated(ref nt) = self.token.kind { - if let token::NtPat(_) = **nt { - self.expected_ident_found().emit(); - } + if let token::NtPat(_) = **nt { + self.expected_ident_found().emit(); + } } // Parse the pattern we hope to be an identifier. @@ -535,7 +543,7 @@ impl<'a> Parser<'a> { mutref_span, "try switching the order", "ref mut".into(), - Applicability::MachineApplicable + Applicability::MachineApplicable, ) .emit(); @@ -552,8 +560,8 @@ impl<'a> Parser<'a> { } fn visit_pat(&mut self, pat: &mut P<Pat>) { - if let PatKind::Ident(BindingMode::ByValue(ref mut m @ Mutability::Not), ..) - = pat.kind + if let PatKind::Ident(BindingMode::ByValue(ref mut m @ Mutability::Not), ..) = + pat.kind { *m = Mutability::Mut; self.0 = true; @@ -605,11 +613,7 @@ impl<'a> Parser<'a> { fn parse_pat_mac_invoc(&mut self, path: Path) -> PResult<'a, PatKind> { self.bump(); let args = self.parse_mac_args()?; - let mac = Mac { - path, - args, - prior_type_ascription: self.last_type_ascription, - }; + let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription }; Ok(PatKind::Mac(mac)) } @@ -624,7 +628,7 @@ impl<'a> Parser<'a> { &mut self, lo: Span, qself: Option<QSelf>, - path: Path + path: Path, ) -> PResult<'a, PatKind> { let (end_kind, form) = match self.token.kind { token::DotDot => (self.excluded_range_end(self.token.span), ".."), @@ -793,10 +797,7 @@ impl<'a> Parser<'a> { // binding mode then we do not end up here, because the lookahead // will direct us over to `parse_enum_variant()`. if self.token == token::OpenDelim(token::Paren) { - return Err(self.span_fatal( - self.prev_span, - "expected identifier, found enum pattern", - )) + return Err(self.span_fatal(self.prev_span, "expected identifier, found enum pattern")); } Ok(PatKind::Ident(binding_mode, ident, sub)) @@ -849,7 +850,7 @@ impl<'a> Parser<'a> { delayed.emit(); } return Err(err); - }, + } }; let lo = self.token.span; @@ -868,7 +869,7 @@ impl<'a> Parser<'a> { let mut etc_sp = self.token.span; self.recover_one_fewer_dotdot(); - self.bump(); // `..` || `...` + self.bump(); // `..` || `...` if self.token == token::CloseDelim(token::Brace) { etc_span = Some(etc_sp); @@ -879,11 +880,14 @@ impl<'a> Parser<'a> { err.span_label(self.token.span, "expected `}`"); let mut comma_sp = None; - if self.token == token::Comma { // Issue #49257 + if self.token == token::Comma { + // Issue #49257 let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span); etc_sp = etc_sp.to(nw_span); - err.span_label(etc_sp, - "`..` must be at the end and cannot have a trailing comma"); + err.span_label( + etc_sp, + "`..` must be at the end and cannot have a trailing comma", + ); comma_sp = Some(self.token.span); self.bump(); ate_comma = true; @@ -961,7 +965,7 @@ impl<'a> Parser<'a> { self.token.span, "to omit remaining fields, use one fewer `.`", "..".to_owned(), - Applicability::MachineApplicable + Applicability::MachineApplicable, ) .emit(); } @@ -993,11 +997,8 @@ impl<'a> Parser<'a> { }; let fieldpat = self.mk_pat_ident(boxed_span.to(hi), bind_type, fieldname); - let subpat = if is_box { - self.mk_pat(lo.to(hi), PatKind::Box(fieldpat)) - } else { - fieldpat - }; + let subpat = + if is_box { self.mk_pat(lo.to(hi), PatKind::Box(fieldpat)) } else { fieldpat }; (subpat, fieldname, true) }; diff --git a/src/librustc_parse/parser/path.rs b/src/librustc_parse/parser/path.rs index a768fdc779e..e6c7d50fb4c 100644 --- a/src/librustc_parse/parser/path.rs +++ b/src/librustc_parse/parser/path.rs @@ -1,14 +1,16 @@ use super::{Parser, TokenType}; use crate::maybe_whole; -use rustc_errors::{PResult, Applicability, pluralize}; -use syntax::ast::{self, QSelf, Path, PathSegment, Ident, ParenthesizedArgs, AngleBracketedArgs}; -use syntax::ast::{AnonConst, GenericArg, AssocTyConstraint, AssocTyConstraintKind, BlockCheckMode}; +use rustc_errors::{pluralize, Applicability, PResult}; +use syntax::ast::{self, AngleBracketedArgs, Ident, ParenthesizedArgs, Path, PathSegment, QSelf}; +use syntax::ast::{ + AnonConst, AssocTyConstraint, AssocTyConstraintKind, BlockCheckMode, GenericArg, +}; use syntax::token::{self, Token}; -use syntax_pos::source_map::{Span, BytePos}; +use syntax_pos::source_map::{BytePos, Span}; use syntax_pos::symbol::{kw, sym}; -use std::mem; use log::debug; +use std::mem; /// Specifies how to parse a path. #[derive(Copy, Clone, PartialEq)] @@ -89,8 +91,8 @@ impl<'a> Parser<'a> { /// `Fn::(Args)` (with disambiguator) pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, Path> { maybe_whole!(self, NtPath, |path| { - if style == PathStyle::Mod && - path.segments.iter().any(|segment| segment.args.is_some()) { + if style == PathStyle::Mod && path.segments.iter().any(|segment| segment.args.is_some()) + { self.diagnostic().span_err(path.span, "unexpected generic arguments in path"); } path @@ -145,51 +147,58 @@ impl<'a> Parser<'a> { let ident = self.parse_path_segment_ident()?; let is_args_start = |token: &Token| match token.kind { - token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) + token::Lt + | token::BinOp(token::Shl) + | token::OpenDelim(token::Paren) | token::LArrow => true, _ => false, }; let check_args_start = |this: &mut Self| { - this.expected_tokens.extend_from_slice( - &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))] - ); + this.expected_tokens.extend_from_slice(&[ + TokenType::Token(token::Lt), + TokenType::Token(token::OpenDelim(token::Paren)), + ]); is_args_start(&this.token) }; - Ok(if style == PathStyle::Type && check_args_start(self) || - style != PathStyle::Mod && self.check(&token::ModSep) - && self.look_ahead(1, |t| is_args_start(t)) { - // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If - // it isn't, then we reset the unmatched angle bracket count as we're about to start - // parsing a new path. - if style == PathStyle::Expr { - self.unmatched_angle_bracket_count = 0; - self.max_angle_bracket_count = 0; - } + Ok( + if style == PathStyle::Type && check_args_start(self) + || style != PathStyle::Mod + && self.check(&token::ModSep) + && self.look_ahead(1, |t| is_args_start(t)) + { + // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If + // it isn't, then we reset the unmatched angle bracket count as we're about to start + // parsing a new path. + if style == PathStyle::Expr { + self.unmatched_angle_bracket_count = 0; + self.max_angle_bracket_count = 0; + } - // Generic arguments are found - `<`, `(`, `::<` or `::(`. - self.eat(&token::ModSep); - let lo = self.token.span; - let args = if self.eat_lt() { - // `<'a, T, A = U>` - let (args, constraints) = - self.parse_generic_args_with_leading_angle_bracket_recovery(style, lo)?; - self.expect_gt()?; - let span = lo.to(self.prev_span); - AngleBracketedArgs { args, constraints, span }.into() + // Generic arguments are found - `<`, `(`, `::<` or `::(`. + self.eat(&token::ModSep); + let lo = self.token.span; + let args = if self.eat_lt() { + // `<'a, T, A = U>` + let (args, constraints) = + self.parse_generic_args_with_leading_angle_bracket_recovery(style, lo)?; + self.expect_gt()?; + let span = lo.to(self.prev_span); + AngleBracketedArgs { args, constraints, span }.into() + } else { + // `(T, U) -> R` + let (inputs, _) = self.parse_paren_comma_seq(|p| p.parse_ty())?; + let span = ident.span.to(self.prev_span); + let output = self.parse_ret_ty(false, false)?; + ParenthesizedArgs { inputs, output, span }.into() + }; + + PathSegment { ident, args, id: ast::DUMMY_NODE_ID } } else { - // `(T, U) -> R` - let (inputs, _) = self.parse_paren_comma_seq(|p| p.parse_ty())?; - let span = ident.span.to(self.prev_span); - let output = self.parse_ret_ty(false, false)?; - ParenthesizedArgs { inputs, output, span }.into() - }; - - PathSegment { ident, args, id: ast::DUMMY_NODE_ID } - } else { - // Generic arguments are not found. - PathSegment::from_ident(ident) - }) + // Generic arguments are not found. + PathSegment::from_ident(ident) + }, + ) } pub(super) fn parse_path_segment_ident(&mut self) -> PResult<'a, Ident> { @@ -288,11 +297,7 @@ impl<'a> Parser<'a> { let is_first_invocation = style == PathStyle::Expr; // Take a snapshot before attempting to parse - we can restore this later. - let snapshot = if is_first_invocation { - Some(self.clone()) - } else { - None - }; + let snapshot = if is_first_invocation { Some(self.clone()) } else { None }; debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)"); match self.parse_generic_args() { @@ -319,9 +324,7 @@ impl<'a> Parser<'a> { } // Make a span over ${unmatched angle bracket count} characters. - let span = lo.with_hi( - lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count) - ); + let span = lo.with_hi(lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)); self.diagnostic() .struct_span_err( span, @@ -343,7 +346,7 @@ impl<'a> Parser<'a> { // Try again without unmatched angle bracket characters. self.parse_generic_args() - }, + } Err(e) => Err(e), } } @@ -370,9 +373,7 @@ impl<'a> Parser<'a> { let lo = self.token.span; let ident = self.parse_ident()?; let kind = if self.eat(&token::Eq) { - AssocTyConstraintKind::Equality { - ty: self.parse_ty()?, - } + AssocTyConstraintKind::Equality { ty: self.parse_ty()? } } else if self.eat(&token::Colon) { AssocTyConstraintKind::Bound { bounds: self.parse_generic_bounds(Some(self.prev_span))?, @@ -388,18 +389,16 @@ impl<'a> Parser<'a> { self.sess.gated_spans.gate(sym::associated_type_bounds, span); } - constraints.push(AssocTyConstraint { - id: ast::DUMMY_NODE_ID, - ident, - kind, - span, - }); + constraints.push(AssocTyConstraint { id: ast::DUMMY_NODE_ID, ident, kind, span }); assoc_ty_constraints.push(span); } else if self.check_const_arg() { // Parse const argument. let expr = if let token::OpenDelim(token::Brace) = self.token.kind { self.parse_block_expr( - None, self.token.span, BlockCheckMode::Default, ast::AttrVec::new() + None, + self.token.span, + BlockCheckMode::Default, + ast::AttrVec::new(), )? } else if self.token.is_ident() { // FIXME(const_generics): to distinguish between idents for types and consts, @@ -415,10 +414,7 @@ impl<'a> Parser<'a> { } else { self.parse_literal_maybe_minus()? }; - let value = AnonConst { - id: ast::DUMMY_NODE_ID, - value: expr, - }; + let value = AnonConst { id: ast::DUMMY_NODE_ID, value: expr }; args.push(GenericArg::Const(value)); misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints); } else if self.check_type() { @@ -426,11 +422,11 @@ impl<'a> Parser<'a> { args.push(GenericArg::Type(self.parse_ty()?)); misplaced_assoc_ty_constraints.append(&mut assoc_ty_constraints); } else { - break + break; } if !self.eat(&token::Comma) { - break + break; } } diff --git a/src/librustc_parse/parser/stmt.rs b/src/librustc_parse/parser/stmt.rs index 42d85e96aef..ed5649310e3 100644 --- a/src/librustc_parse/parser/stmt.rs +++ b/src/librustc_parse/parser/stmt.rs @@ -1,18 +1,18 @@ -use super::{Parser, Restrictions, PrevTokenKind, SemiColonMode, BlockMode}; +use super::diagnostics::Error; use super::expr::LhsExpr; -use super::path::PathStyle; use super::pat::GateOr; -use super::diagnostics::Error; +use super::path::PathStyle; +use super::{BlockMode, Parser, PrevTokenKind, Restrictions, SemiColonMode}; use crate::maybe_whole; use crate::DirectoryOwnership; -use rustc_errors::{PResult, Applicability}; -use syntax::ptr::P; +use rustc_errors::{Applicability, PResult}; use syntax::ast; -use syntax::ast::{DUMMY_NODE_ID, Stmt, StmtKind, Local, Block, BlockCheckMode, Expr, ExprKind}; -use syntax::ast::{AttrVec, Attribute, AttrStyle, VisibilityKind, MacStmtStyle, Mac}; -use syntax::util::classify; +use syntax::ast::{AttrStyle, AttrVec, Attribute, Mac, MacStmtStyle, VisibilityKind}; +use syntax::ast::{Block, BlockCheckMode, Expr, ExprKind, Local, Stmt, StmtKind, DUMMY_NODE_ID}; +use syntax::ptr::P; use syntax::token; +use syntax::util::classify; use syntax_pos::source_map::{respan, Span}; use syntax_pos::symbol::{kw, sym, Symbol}; @@ -39,7 +39,7 @@ impl<'a> Parser<'a> { let lo = self.token.span; if self.eat_keyword(kw::Let) { - return self.parse_local_mk(lo, attrs.into()).map(Some) + return self.parse_local_mk(lo, attrs.into()).map(Some); } if self.is_kw_followed_by_ident(kw::Mut) { return self.recover_stmt_local(lo, attrs.into(), "missing keyword", "let mut"); @@ -115,7 +115,7 @@ impl<'a> Parser<'a> { let kind = StmtKind::Semi(self.mk_expr( lo.to(last_semi), ExprKind::Tup(Vec::new()), - AttrVec::new() + AttrVec::new(), )); return Ok(Some(self.mk_stmt(lo.to(last_semi), kind))); } @@ -143,21 +143,12 @@ impl<'a> Parser<'a> { let delim = args.delim(); let hi = self.prev_span; - let style = if delim == token::Brace { - MacStmtStyle::Braces - } else { - MacStmtStyle::NoBraces - }; + let style = + if delim == token::Brace { MacStmtStyle::Braces } else { MacStmtStyle::NoBraces }; - let mac = Mac { - path, - args, - prior_type_ascription: self.last_type_ascription, - }; + let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription }; - let kind = if delim == token::Brace - || self.token == token::Semi - || self.token == token::Eof + let kind = if delim == token::Brace || self.token == token::Semi || self.token == token::Eof { StmtKind::Mac(P((mac, style, attrs.into()))) } @@ -168,11 +159,17 @@ impl<'a> Parser<'a> { && self.token.can_begin_expr() && match self.token.kind { // These can continue an expression, so we can't stop parsing and warn. - token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) | - token::BinOp(token::Minus) | token::BinOp(token::Star) | - token::BinOp(token::And) | token::BinOp(token::Or) | - token::AndAnd | token::OrOr | - token::DotDot | token::DotDotDot | token::DotDotEq => false, + token::OpenDelim(token::Paren) + | token::OpenDelim(token::Bracket) + | token::BinOp(token::Minus) + | token::BinOp(token::Star) + | token::BinOp(token::And) + | token::BinOp(token::Or) + | token::AndAnd + | token::OrOr + | token::DotDot + | token::DotDotDot + | token::DotDotEq => false, _ => true, } { @@ -202,8 +199,7 @@ impl<'a> Parser<'a> { } fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { - self.token.is_keyword(kw) - && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) + self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) } fn recover_stmt_local( @@ -251,17 +247,19 @@ impl<'a> Parser<'a> { (None, None) }; let init = match (self.parse_initializer(err.is_some()), err) { - (Ok(init), None) => { // init parsed, ty parsed + (Ok(init), None) => { + // init parsed, ty parsed init } - (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error + (Ok(init), Some((_, colon_sp, mut err))) => { + // init parsed, ty error // Could parse the type as if it were the initializer, it is likely there was a // typo in the code: `:` instead of `=`. Add suggestion and emit the error. err.span_suggestion_short( colon_sp, "use `=` if you meant to assign", " =".to_string(), - Applicability::MachineApplicable + Applicability::MachineApplicable, ); err.emit(); // As this was parsed successfully, continue as if the code has been fixed for the @@ -269,7 +267,8 @@ impl<'a> Parser<'a> { // extra noise. init } - (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error + (Err(mut init_err), Some((snapshot, _, ty_err))) => { + // init error, ty error init_err.cancel(); // Couldn't parse the type nor the initializer, only raise the type error and // return to the parser state before parsing the type as the initializer. @@ -277,25 +276,15 @@ impl<'a> Parser<'a> { mem::replace(self, snapshot); return Err(ty_err); } - (Err(err), None) => { // init error, ty parsed + (Err(err), None) => { + // init error, ty parsed // Couldn't parse the initializer and we're not attempting to recover a failed // parse of the type, return the error. return Err(err); } }; - let hi = if self.token == token::Semi { - self.token.span - } else { - self.prev_span - }; - Ok(P(ast::Local { - ty, - pat, - init, - id: DUMMY_NODE_ID, - span: lo.to(hi), - attrs, - })) + let hi = if self.token == token::Semi { self.token.span } else { self.prev_span }; + Ok(P(ast::Local { ty, pat, init, id: DUMMY_NODE_ID, span: lo.to(hi), attrs })) } /// Parses the RHS of a local variable declaration (e.g., '= 14;'). @@ -382,14 +371,13 @@ impl<'a> Parser<'a> { /// Parses a block. Inner attributes are allowed. pub(super) fn parse_inner_attrs_and_block( - &mut self + &mut self, ) -> PResult<'a, (Vec<Attribute>, P<Block>)> { maybe_whole!(self, NtBlock, |x| (Vec::new(), x)); let lo = self.token.span; self.expect(&token::OpenDelim(token::Brace))?; - Ok((self.parse_inner_attributes()?, - self.parse_block_tail(lo, BlockCheckMode::Default)?)) + Ok((self.parse_inner_attributes()?, self.parse_block_tail(lo, BlockCheckMode::Default)?)) } /// Parses the rest of a block expression or function body. @@ -397,7 +385,7 @@ impl<'a> Parser<'a> { pub(super) fn parse_block_tail( &mut self, lo: Span, - s: BlockCheckMode + s: BlockCheckMode, ) -> PResult<'a, P<Block>> { let mut stmts = vec![]; while !self.eat(&token::CloseDelim(token::Brace)) { @@ -423,12 +411,7 @@ impl<'a> Parser<'a> { continue; }; } - Ok(P(ast::Block { - stmts, - id: DUMMY_NODE_ID, - rules: s, - span: lo.to(self.prev_span), - })) + Ok(P(ast::Block { stmts, id: DUMMY_NODE_ID, rules: s, span: lo.to(self.prev_span) })) } /// Parses a statement, including the trailing semicolon. @@ -478,11 +461,14 @@ impl<'a> Parser<'a> { } fn warn_missing_semicolon(&self) { - self.diagnostic().struct_span_warn(self.token.span, { - &format!("expected `;`, found {}", self.this_token_descr()) - }).note({ - "this was erroneously allowed and will become a hard error in a future release" - }).emit(); + self.diagnostic() + .struct_span_warn(self.token.span, { + &format!("expected `;`, found {}", self.this_token_descr()) + }) + .note({ + "this was erroneously allowed and will become a hard error in a future release" + }) + .emit(); } fn mk_stmt(&self, span: Span, kind: StmtKind) -> Stmt { diff --git a/src/librustc_parse/parser/ty.rs b/src/librustc_parse/parser/ty.rs index 58f3a5b3d60..fe3db358acc 100644 --- a/src/librustc_parse/parser/ty.rs +++ b/src/librustc_parse/parser/ty.rs @@ -1,16 +1,20 @@ -use super::{Parser, PathStyle, PrevTokenKind, TokenType}; use super::item::ParamCfg; +use super::{Parser, PathStyle, PrevTokenKind, TokenType}; -use crate::{maybe_whole, maybe_recover_from_interpolated_ty_qpath}; +use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole}; -use rustc_errors::{PResult, Applicability, pluralize}; use rustc_error_codes::*; +use rustc_errors::{pluralize, Applicability, PResult}; +use syntax::ast::{ + self, BareFnTy, FunctionRetTy, GenericParam, Ident, Lifetime, MutTy, Ty, TyKind, +}; +use syntax::ast::{ + GenericBound, GenericBounds, PolyTraitRef, TraitBoundModifier, TraitObjectSyntax, +}; +use syntax::ast::{Mac, Mutability}; use syntax::ptr::P; -use syntax::ast::{self, Ty, TyKind, MutTy, BareFnTy, FunctionRetTy, GenericParam, Lifetime, Ident}; -use syntax::ast::{TraitBoundModifier, TraitObjectSyntax, GenericBound, GenericBounds, PolyTraitRef}; -use syntax::ast::{Mutability, Mac}; -use syntax::token::{self, Token}; use syntax::struct_span_err; +use syntax::token::{self, Token}; use syntax_pos::source_map::Span; use syntax_pos::symbol::kw; @@ -20,8 +24,7 @@ use syntax_pos::symbol::kw; /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes /// that `IDENT` is not the ident of a fn trait. fn can_continue_type_after_non_fn_ident(t: &Token) -> bool { - t == &token::ModSep || t == &token::Lt || - t == &token::BinOp(token::Shl) + t == &token::ModSep || t == &token::Lt || t == &token::BinOp(token::Shl) } impl<'a> Parser<'a> { @@ -168,7 +171,8 @@ impl<'a> Parser<'a> { self.parse_remaining_bounds(Vec::new(), path, lo, true) } TyKind::TraitObject(mut bounds, TraitObjectSyntax::None) - if maybe_bounds && bounds.len() == 1 && !trailing_plus => { + if maybe_bounds && bounds.len() == 1 && !trailing_plus => + { let path = match bounds.remove(0) { GenericBound::Trait(pt, ..) => pt.trait_ref.path, GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"), @@ -176,7 +180,7 @@ impl<'a> Parser<'a> { self.parse_remaining_bounds(Vec::new(), path, lo, true) } // `(TYPE)` - _ => Ok(TyKind::Paren(P(ty))) + _ => Ok(TyKind::Paren(P(ty))), } } else { Ok(TyKind::Tup(ts)) @@ -245,9 +249,9 @@ impl<'a> Parser<'a> { /// Is the current token one of the keywords that signals a bare function type? fn token_is_bare_fn_keyword(&mut self) -> bool { - self.check_keyword(kw::Fn) || - self.check_keyword(kw::Unsafe) || - self.check_keyword(kw::Extern) + self.check_keyword(kw::Fn) + || self.check_keyword(kw::Unsafe) + || self.check_keyword(kw::Extern) } /// Parses a function pointer type (`TyKind::BareFn`). @@ -262,17 +266,9 @@ impl<'a> Parser<'a> { let unsafety = self.parse_unsafety(); let ext = self.parse_extern()?; self.expect_keyword(kw::Fn)?; - let cfg = ParamCfg { - is_self_allowed: false, - is_name_required: |_| false, - }; + let cfg = ParamCfg { is_self_allowed: false, is_name_required: |_| false }; let decl = self.parse_fn_decl(cfg, false)?; - Ok(TyKind::BareFn(P(BareFnTy { - ext, - unsafety, - generic_params, - decl, - }))) + Ok(TyKind::BareFn(P(BareFnTy { ext, unsafety, generic_params, decl }))) } /// Parses an `impl B0 + ... + Bn` type. @@ -361,7 +357,7 @@ impl<'a> Parser<'a> { Err(neg_sp) => negative_bounds.push(neg_sp), } if !allow_plus || !self.eat_plus() { - break + break; } } @@ -391,10 +387,7 @@ impl<'a> Parser<'a> { ) { let negative_bounds_len = negative_bounds.len(); let last_span = *negative_bounds.last().expect("no negative bounds, but still error?"); - let mut err = self.struct_span_err( - negative_bounds, - "negative bounds are not supported", - ); + let mut err = self.struct_span_err(negative_bounds, "negative bounds are not supported"); err.span_label(last_span, "negative bounds are not supported"); if let Some(bound_list) = colon_span { let bound_list = bound_list.to(self.prev_span); @@ -433,11 +426,7 @@ impl<'a> Parser<'a> { } else { self.parse_generic_ty_bound(lo, has_parens, question)? }; - Ok(if is_negative { - Err(anchor_lo.to(self.prev_span)) - } else { - Ok(bound) - }) + Ok(if is_negative { Err(anchor_lo.to(self.prev_span)) } else { Ok(bound) }) } /// Parses a lifetime ("outlives") bound, e.g. `'a`, according to: @@ -474,14 +463,14 @@ impl<'a> Parser<'a> { self.expect(&token::CloseDelim(token::Paren))?; let mut err = self.struct_span_err( lo.to(self.prev_span), - "parenthesized lifetime bounds are not supported" + "parenthesized lifetime bounds are not supported", ); if let Ok(snippet) = self.span_to_snippet(inner_span) { err.span_suggestion_short( lo.to(self.prev_span), "remove the parentheses", snippet.to_owned(), - Applicability::MachineApplicable + Applicability::MachineApplicable, ); } err.emit(); |
