Skip to content

Commit

Permalink
Fix checking if newline is needed before else in let-else statement (
Browse files Browse the repository at this point in the history
  • Loading branch information
rhysd committed Sep 6, 2023
1 parent b636723 commit 08b976b
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
10 changes: 9 additions & 1 deletion src/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ impl Rewrite for ast::Local {
false,
)?
};
let let_kw_offset = result.len() - "let ".len();

// 4 = "let ".len()
let pat_shape = shape.offset_left(4)?;
Expand Down Expand Up @@ -127,8 +128,15 @@ impl Rewrite for ast::Local {

if let Some(block) = else_block {
let else_kw_span = init.span.between(block.span);
// Strip attributes and comments to check if newline is needed before the else
// keyword from the initializer part. (#5901)
let init_str = if context.config.version() == Version::Two {
&result[let_kw_offset..]
} else {
result.as_str()
};
let force_newline_else = pat_str.contains('\n')
|| !same_line_else_kw_and_brace(&result, context, else_kw_span, nested_shape);
|| !same_line_else_kw_and_brace(init_str, context, else_kw_span, nested_shape);
let else_kw = rewrite_else_kw_with_comments(
force_newline_else,
true,
Expand Down
13 changes: 13 additions & 0 deletions tests/source/let_else.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,16 @@ fn with_trailing_try_operator() {
// Maybe this is a workaround?
let Ok(Some(next_bucket)) = ranking_rules[cur_ranking_rule_index].next_bucket(ctx, logger, &ranking_rule_universes[cur_ranking_rule_index]) else { return };
}

fn issue5901() {
#[cfg(target_os = "linux")]
let Some(x) = foo() else { return; };

#[cfg(target_os = "linux")]
// Some comments between attributes and let-else statement
let Some(x) = foo() else { return; };

#[cfg(target_os = "linux")]
#[cfg(target_arch = "x86_64")]
let Some(x) = foo() else { return; };
}
19 changes: 19 additions & 0 deletions tests/target/let_else.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,3 +252,22 @@ fn with_trailing_try_operator() {
return;
};
}

fn issue5901() {
#[cfg(target_os = "linux")]
let Some(x) = foo() else {
return;
};

#[cfg(target_os = "linux")]
// Some comments between attributes and let-else statement
let Some(x) = foo() else {
return;
};

#[cfg(target_os = "linux")]
#[cfg(target_arch = "x86_64")]
let Some(x) = foo() else {
return;
};
}

0 comments on commit 08b976b

Please sign in to comment.