Skip to content

Fix idempotency issue when using empty statements in simple blocks #4771

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: rustfmt-2.0.0-rc.2
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions src/formatting/closures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use crate::formatting::{
rewrite::{Rewrite, RewriteContext},
shape::Shape,
source_map::SpanUtils,
utils::{last_line_width, left_most_sub_expr, stmt_expr, NodeIdExt},
utils::{last_line_width, left_most_sub_expr, stmt_expr, NodeIdExt, StmtsExt},
};

// This module is pretty messy because of the rules around closures and blocks:
Expand Down Expand Up @@ -140,7 +140,7 @@ fn get_inner_expr<'a>(
if !needs_block(block, prefix, context) {
// block.stmts.len() == 1 except with `|| {{}}`;
// https://github.com/rust-lang/rustfmt/issues/3844
if let Some(expr) = block.stmts.first().and_then(stmt_expr) {
if let Some(expr) = block.stmts.find_non_empty().and_then(stmt_expr) {
return get_inner_expr(expr, prefix, context);
}
}
Expand All @@ -151,12 +151,18 @@ fn get_inner_expr<'a>(

// Figure out if a block is necessary.
fn needs_block(block: &ast::Block, prefix: &str, context: &RewriteContext<'_>) -> bool {
let has_attributes = block.stmts.first().map_or(false, |first_stmt| {
let has_attributes = block.stmts.find_non_empty().map_or(false, |first_stmt| {
!get_attrs_from_stmt(first_stmt).is_empty()
});

let mut non_empty_stmts = block
.stmts
.iter()
.filter(|stmt| !matches!(stmt.kind, ast::StmtKind::Empty));
non_empty_stmts.next();

is_unsafe_block(block)
|| block.stmts.len() > 1
|| non_empty_stmts.next().is_some()
|| has_attributes
|| block_contains_comment(context, block)
|| prefix.contains('\n')
Expand Down Expand Up @@ -390,7 +396,7 @@ pub(crate) fn rewrite_last_closure(
&& !context.inside_macro()
&& is_simple_block(context, block, Some(&body.attrs)) =>
{
stmt_expr(&block.stmts[0]).unwrap_or(body)
stmt_expr(block.stmts.find_non_empty().unwrap()).unwrap_or(body)
}
_ => body,
};
Expand Down
22 changes: 16 additions & 6 deletions src/formatting/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use crate::formatting::{
utils::{
colon_spaces, contains_skip, count_newlines, first_line_ends_with, inner_attributes,
last_line_extendable, last_line_width, mk_sp, outer_attributes, semicolon_for_expr,
unicode_str_width, wrap_str,
unicode_str_width, wrap_str, StmtsExt,
},
vertical::rewrite_with_alignment,
visitor::FmtVisitor,
Expand Down Expand Up @@ -557,7 +557,11 @@ fn rewrite_single_line_block(
) -> Option<String> {
if is_simple_block(context, block, attrs) {
let expr_shape = shape.offset_left(last_line_width(prefix))?;
let expr_str = block.stmts[0].rewrite(context, expr_shape)?;
let expr_str = block
.stmts
.find_non_empty()
.unwrap()
.rewrite(context, expr_shape)?;
let label_str = rewrite_label(label);
let result = format!("{}{}{{ {} }}", prefix, label_str, expr_str);
if result.len() <= shape.width && !result.contains('\n') {
Expand Down Expand Up @@ -826,11 +830,11 @@ impl<'a> ControlFlow<'a> {
}

let new_width = width.checked_sub(pat_expr_str.len() + fixed_cost)?;
let expr = &self.block.stmts[0];
let expr = self.block.stmts.find_non_empty().unwrap();
let if_str = expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;

let new_width = new_width.checked_sub(if_str.len())?;
let else_expr = &else_node.stmts[0];
let else_expr = else_node.stmts.find_non_empty().unwrap();
let else_str = else_expr.rewrite(context, Shape::legacy(new_width, Indent::empty()))?;

if if_str.contains('\n') || else_str.contains('\n') {
Expand Down Expand Up @@ -1182,8 +1186,14 @@ pub(crate) fn is_simple_block(
block: &ast::Block,
attrs: Option<&[ast::Attribute]>,
) -> bool {
block.stmts.len() == 1
&& stmt_is_expr(&block.stmts[0])
let mut non_empty_stmts = block
.stmts
.iter()
.filter(|stmt| !matches!(stmt.kind, ast::StmtKind::Empty));
let first = non_empty_stmts.next();
first.is_some()
&& non_empty_stmts.next().is_none()
&& stmt_is_expr(first.unwrap())
&& !block_contains_comment(context, block)
&& attrs.map_or(true, |a| a.is_empty())
}
Expand Down
2 changes: 1 addition & 1 deletion src/formatting/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,7 @@ impl<'a> FmtVisitor<'a> {
return None;
}

let res = Stmt::from_ast_node(block.stmts.first()?, true)
let res = Stmt::from_ast_node(block.stmts.find_non_empty()?, true)
.rewrite(&self.get_context(), self.shape())?;

let width = self.block_indent.width() + fn_str.len() + res.len() + 5;
Expand Down
5 changes: 3 additions & 2 deletions src/formatting/matches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use crate::formatting::{
utils::{
contains_skip, extra_offset, first_line_width, inner_attributes, last_line_extendable,
mk_sp, mk_sp_lo_plus_one, semicolon_for_expr, trimmed_last_line_width, unicode_str_width,
StmtsExt,
},
};

Expand Down Expand Up @@ -312,7 +313,7 @@ fn block_can_be_flattened<'a>(
&& is_simple_block(context, block, Some(&expr.attrs))
// Don't flatten a block containing a macro invocation,
// since it may expand to a statement
&& !stmt_is_expr_mac(&block.stmts[0]) =>
&& !stmt_is_expr_mac(block.stmts.find_non_empty().unwrap()) =>
{
Some(&*block)
}
Expand All @@ -332,7 +333,7 @@ fn flatten_arm_body<'a>(
|expr| !context.config.force_multiline_blocks() && can_flatten_block_around_this(expr);

if let Some(ref block) = block_can_be_flattened(context, body) {
if let ast::StmtKind::Expr(ref expr) = block.stmts[0].kind {
if let ast::StmtKind::Expr(ref expr) = block.stmts.find_non_empty().unwrap().kind {
if let ast::ExprKind::Block(..) = expr.kind {
if expr.attrs.is_empty() {
flatten_arm_body(context, expr, None)
Expand Down
11 changes: 11 additions & 0 deletions src/formatting/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -837,6 +837,17 @@ pub(crate) fn format_code_block(
})
}

pub(crate) trait StmtsExt {
fn find_non_empty(&self) -> Option<&ast::Stmt>;
}

impl StmtsExt for Vec<ast::Stmt> {
fn find_non_empty(&self) -> Option<&ast::Stmt> {
self.iter()
.find(|stmt| !matches!(stmt.kind, ast::StmtKind::Empty))
}
}

#[cfg(test)]
mod test {
use super::*;
Expand Down
43 changes: 43 additions & 0 deletions tests/source/issue-4748.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
fn foo(x: Option<i32>) -> i32 {
match y {
Some(y) => {
;
;
y
}
None => 0,
}
}

fn foo(x: Option<i32>) -> i32 {
match y {
Some(y) => {
y
}
None => 0,
}
}

fn foo(){

foo.find(|y| {
;
;
x
});
}

fn foo() {
foo.find(|y| { x });
}

fn foo(){
try {
;
;
;
;
y
}
}

25 changes: 25 additions & 0 deletions tests/target/issue-4748.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
fn foo(x: Option<i32>) -> i32 {
match y {
Some(y) => y,
None => 0,
}
}

fn foo(x: Option<i32>) -> i32 {
match y {
Some(y) => y,
None => 0,
}
}

fn foo() {
foo.find(|y| x);
}

fn foo() {
foo.find(|y| x);
}

fn foo() {
try { y }
}