Skip to content

implement single_line_let_else_max_width #5790

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

Merged
Merged
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
77 changes: 77 additions & 0 deletions Configurations.md
Original file line number Diff line number Diff line change
Expand Up @@ -2392,6 +2392,78 @@ By default this option is set as a percentage of [`max_width`](#max_width) provi

See also [`max_width`](#max_width) and [`use_small_heuristics`](#use_small_heuristics)

## `single_line_let_else_max_width`

Maximum line length for single line let-else statements.
See the [let-else statement section of the Rust Style Guide](https://github.com/rust-lang/rust/blob/master/src/doc/style-guide/src/statements.md#else-blocks-let-else-statements) for more details on when a let-else statement may be written on a single line.
A value of `0` (zero) means the divergent `else` block will always be formatted over multiple lines.
Note this occurs when `use_small_heuristics` is set to `Off`.

By default this option is set as a percentage of [`max_width`](#max_width) provided by [`use_small_heuristics`](#use_small_heuristics), but a value set directly for `single_line_let_else_max_width` will take precedence.

- **Default value**: `50`
- **Possible values**: any positive integer that is less than or equal to the value specified for [`max_width`](#max_width)
- **Stable**: Yes

#### `50` (default):

```rust
fn main() {
let Some(w) = opt else { return Ok(()) };

let Some(x) = opt else { return };

let Some(y) = opt else {
return;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's remove the semicolon here.

in this context we want to demonstrate snippets that are eligible for single line based on all other rules, so that whether they are wrapped is solely dependent upon length and the value of the config option. the semis are load bearing though which means the snippets would always have to be wrapped regardless

Suggested change
return;
return

Copy link
Contributor Author

@ytmimi ytmimi Jun 27, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately I can't remove the ;. The configuration_snippet_tests would fail without it since rustfmt will add the ; by default.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sometimes I forget that we can't readily utilize other config options (e.g. trailing_semicolon) in these snippets.

I also don't recall whether we've discussed this before, but I think having the ability to specify additional options in the snippets (perhaps similar to what we do in the system&idempotence tests?) would be helpful

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the idea has briefly come up before. It's a change that I'd really like to see! I think it'll also be very helpful if we need to demonstrate formatting differences between version (and eventually style_edition)

};

let Some(z) = some_very_very_very_very_long_name else {
return;
};
}
```

#### `0`:

```rust
fn main() {
let Some(w) = opt else {
return Ok(());
};

let Some(x) = opt else {
return;
};

let Some(y) = opt else {
return;
};

let Some(z) = some_very_very_very_very_long_name else {
return;
};
}
```

#### `100`:

```rust
fn main() {
let Some(w) = opt else { return Ok(()) };

let Some(x) = opt else { return };

let Some(y) = opt else {
return;
};

let Some(z) = some_very_very_very_very_long_name else { return };
}
```

See also [`max_width`](#max_width) and [`use_small_heuristics`](#use_small_heuristics)


## `space_after_colon`

Leave a space after the colon.
Expand Down Expand Up @@ -2804,6 +2876,7 @@ The ratios are:
* [`array_width`](#array_width) - `60%`
* [`chain_width`](#chain_width) - `60%`
* [`single_line_if_else_max_width`](#single_line_if_else_max_width) - `50%`
* [`single_line_let_else_max_width`](#single_line_let_else_max_width) - `50%`

For example when `max_width` is set to `100`, the width settings are:
* `fn_call_width=60`
Expand All @@ -2813,6 +2886,7 @@ For example when `max_width` is set to `100`, the width settings are:
* `array_width=60`
* `chain_width=60`
* `single_line_if_else_max_width=50`
* `single_line_let_else_max_width=50`

and when `max_width` is set to `200`:
* `fn_call_width=120`
Expand All @@ -2822,6 +2896,7 @@ and when `max_width` is set to `200`:
* `array_width=120`
* `chain_width=120`
* `single_line_if_else_max_width=100`
* `single_line_let_else_max_width=100`

```rust
enum Lorem {
Expand Down Expand Up @@ -2891,6 +2966,7 @@ So if `max_width` is set to `200`, then all the width settings are also set to `
* `array_width=200`
* `chain_width=200`
* `single_line_if_else_max_width=200`
* `single_line_let_else_max_width=200`

```rust
enum Lorem {
Expand Down Expand Up @@ -2918,6 +2994,7 @@ See also:
* [`array_width`](#array_width)
* [`chain_width`](#chain_width)
* [`single_line_if_else_max_width`](#single_line_if_else_max_width)
* [`single_line_let_else_max_width`](#single_line_let_else_max_width)

## `use_try_shorthand`

Expand Down
10 changes: 10 additions & 0 deletions src/config/config_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ macro_rules! create_config {
| "use_small_heuristics"
| "fn_call_width"
| "single_line_if_else_max_width"
| "single_line_let_else_max_width"
| "attr_fn_like_width"
| "struct_lit_width"
| "struct_variant_width"
Expand Down Expand Up @@ -269,6 +270,7 @@ macro_rules! create_config {
| "use_small_heuristics"
| "fn_call_width"
| "single_line_if_else_max_width"
| "single_line_let_else_max_width"
| "attr_fn_like_width"
| "struct_lit_width"
| "struct_variant_width"
Expand Down Expand Up @@ -407,6 +409,14 @@ macro_rules! create_config {
"single_line_if_else_max_width",
);
self.single_line_if_else_max_width.2 = single_line_if_else_max_width;

let single_line_let_else_max_width = get_width_value(
self.was_set().single_line_let_else_max_width(),
self.single_line_let_else_max_width.2,
heuristics.single_line_let_else_max_width,
"single_line_let_else_max_width",
);
self.single_line_let_else_max_width.2 = single_line_let_else_max_width;
}

fn set_heuristics(&mut self) {
Expand Down
7 changes: 7 additions & 0 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ create_config! {
chain_width: usize, 60, true, "Maximum length of a chain to fit on a single line.";
single_line_if_else_max_width: usize, 50, true, "Maximum line length for single line if-else \
expressions. A value of zero means always break if-else expressions.";
single_line_let_else_max_width: usize, 50, true, "Maximum line length for single line \
let-else statements. A value of zero means always format the divergent `else` block \
over multiple lines.";

// Comments. macros, and strings
wrap_comments: bool, false, false, "Break comments to fit on the line";
Expand Down Expand Up @@ -473,6 +476,9 @@ mod test {
chain_width: usize, 60, true, "Maximum length of a chain to fit on a single line.";
single_line_if_else_max_width: usize, 50, true, "Maximum line length for single \
line if-else expressions. A value of zero means always break if-else expressions.";
single_line_let_else_max_width: usize, 50, false, "Maximum line length for single \
line let-else statements. A value of zero means always format the divergent \
`else` block over multiple lines.";

// Options that are used by the tests
stable_option: bool, false, true, "A stable option";
Expand Down Expand Up @@ -619,6 +625,7 @@ struct_variant_width = 35
array_width = 60
chain_width = 60
single_line_if_else_max_width = 50
single_line_let_else_max_width = 50
wrap_comments = false
format_code_in_doc_comments = false
doc_comment_code_block_width = 100
Expand Down
6 changes: 6 additions & 0 deletions src/config/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,9 @@ pub struct WidthHeuristics {
// Maximum line length for single line if-else expressions. A value
// of zero means always break if-else expressions.
pub(crate) single_line_if_else_max_width: usize,
// Maximum line length for single line let-else statements. A value of zero means
// always format the divergent `else` block over multiple lines.
pub(crate) single_line_let_else_max_width: usize,
}

impl fmt::Display for WidthHeuristics {
Expand All @@ -255,6 +258,7 @@ impl WidthHeuristics {
array_width: usize::max_value(),
chain_width: usize::max_value(),
single_line_if_else_max_width: 0,
single_line_let_else_max_width: 0,
}
}

Expand All @@ -267,6 +271,7 @@ impl WidthHeuristics {
array_width: max_width,
chain_width: max_width,
single_line_if_else_max_width: max_width,
single_line_let_else_max_width: max_width,
}
}

Expand All @@ -288,6 +293,7 @@ impl WidthHeuristics {
array_width: (60.0 * max_width_ratio).round() as usize,
chain_width: (60.0 * max_width_ratio).round() as usize,
single_line_if_else_max_width: (50.0 * max_width_ratio).round() as usize,
single_line_let_else_max_width: (50.0 * max_width_ratio).round() as usize,
}
}
}
Expand Down
32 changes: 23 additions & 9 deletions src/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,8 @@ impl Rewrite for ast::Local {

if let Some(block) = else_block {
let else_kw_span = init.span.between(block.span);
let force_newline_else =
!same_line_else_kw_and_brace(&result, context, else_kw_span, nested_shape);
let force_newline_else = pat_str.contains('\n')
|| !same_line_else_kw_and_brace(&result, context, else_kw_span, nested_shape);
let else_kw = rewrite_else_kw_with_comments(
force_newline_else,
true,
Expand All @@ -138,17 +138,31 @@ impl Rewrite for ast::Local {
);
result.push_str(&else_kw);

let allow_single_line = allow_single_line_let_else_block(&result, block);
// At this point we've written `let {pat} = {expr} else' into the buffer, and we
// want to calculate up front if there's room to write the divergent block on the
// same line. The available space varies based on indentation so we clamp the width
// on the smaller of `shape.width` and `single_line_let_else_max_width`.
let max_width =
std::cmp::min(shape.width, context.config.single_line_let_else_max_width());

// If available_space hits zero we know for sure this will be a multi-lined block
let available_space = max_width.saturating_sub(result.len());

let allow_single_line = !force_newline_else
&& available_space > 0
&& allow_single_line_let_else_block(&result, block);

let mut rw_else_block =
rewrite_let_else_block(block, allow_single_line, context, shape)?;

if allow_single_line && !rw_else_block.contains('\n') {
let available_space = shape.width.saturating_sub(result.len());
if available_space <= rw_else_block.len() {
// writing this on one line would exceed the available width
rw_else_block = rewrite_let_else_block(block, false, context, shape)?;
}
let single_line_else = !rw_else_block.contains('\n');
// +1 for the trailing `;`
let else_block_exceeds_width = rw_else_block.len() + 1 > available_space;

if allow_single_line && single_line_else && else_block_exceeds_width {
// writing this on one line would exceed the available width
// so rewrite the else block over multiple lines.
rw_else_block = rewrite_let_else_block(block, false, context, shape)?;
Comment on lines +145 to +165
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I concur with some of the earlier discussions on this that the high level theme of limit derivation, checking if a formatted version can fit within that limit, else format over multiple lines, feels like a potentially recurrent pattern that could be encapsulated in some manner that lends itself to reuse.

However, even if so, that's the type of internal change we could make afterwards with no impact on resultant behavior so I'd also agree that should be punted to a hypothetical future iteration.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

great! appreciate you sharing your thoughts on that!

}

result.push_str(&rw_else_block);
Expand Down
40 changes: 40 additions & 0 deletions tests/source/configs/single_line_let_else_max_width/100.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// rustfmt-single_line_let_else_max_width: 100

fn main() {
let Some(a) = opt else {};

let Some(b) = opt else { return };

let Some(c) = opt else {
return
};

let Some(c) = opt else {
// a comment should always force the block to be multi-lined
return
};

let Some(c) = opt else { /* a comment should always force the block to be multi-lined */ return };

let Some(d) = some_very_very_very_very_long_name else { return };

let Expr::Slice(ast::ExprSlice { lower, upper, step, range: _ }) = slice.as_ref() else {
return
};

let Some((base_place, current)) = self.lower_expr_as_place(current, *base, true)? else {
return Ok(None)
};

let Some(doc_attr) = variant.attrs.iter().find(|attr| attr.path().is_ident("doc")) else {
return Err(Error::new(variant.span(), r#"expected a doc comment"#))
};

let Some((base_place, current)) = self.lower_expr_as_place(current, *base, true) else {
return Ok(None)
};

let Stmt::Expr(Expr::Call(ExprCall { args: some_args, .. }), _) = last_stmt else {
return Err(Error::new(last_stmt.span(), "expected last expression to be `Some(match (..) { .. })`"))
};
}
40 changes: 40 additions & 0 deletions tests/source/configs/single_line_let_else_max_width/50.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// rustfmt-single_line_let_else_max_width: 50

fn main() {
let Some(a) = opt else {};

let Some(b) = opt else { return };

let Some(c) = opt else {
return
};

let Some(c) = opt else {
// a comment should always force the block to be multi-lined
return
};

let Some(c) = opt else { /* a comment should always force the block to be multi-lined */ return };

let Some(d) = some_very_very_very_very_long_name else { return };

let Expr::Slice(ast::ExprSlice { lower, upper, step, range: _ }) = slice.as_ref() else {
return
};

let Some((base_place, current)) = self.lower_expr_as_place(current, *base, true)? else {
return Ok(None)
};

let Some(doc_attr) = variant.attrs.iter().find(|attr| attr.path().is_ident("doc")) else {
return Err(Error::new(variant.span(), r#"expected a doc comment"#))
};

let Some((base_place, current)) = self.lower_expr_as_place(current, *base, true) else {
return Ok(None)
};

let Stmt::Expr(Expr::Call(ExprCall { args: some_args, .. }), _) = last_stmt else {
return Err(Error::new(last_stmt.span(), "expected last expression to be `Some(match (..) { .. })`"))
};
}
40 changes: 40 additions & 0 deletions tests/source/configs/single_line_let_else_max_width/zero.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// rustfmt-single_line_let_else_max_width: 0

fn main() {
let Some(a) = opt else {};

let Some(b) = opt else { return };

let Some(c) = opt else {
return
};

let Some(c) = opt else {
// a comment should always force the block to be multi-lined
return
};

let Some(c) = opt else { /* a comment should always force the block to be multi-lined */ return };

let Some(d) = some_very_very_very_very_long_name else { return };

let Expr::Slice(ast::ExprSlice { lower, upper, step, range: _ }) = slice.as_ref() else {
return
};

let Some((base_place, current)) = self.lower_expr_as_place(current, *base, true)? else {
return Ok(None)
};

let Some(doc_attr) = variant.attrs.iter().find(|attr| attr.path().is_ident("doc")) else {
return Err(Error::new(variant.span(), r#"expected a doc comment"#))
};

let Some((base_place, current)) = self.lower_expr_as_place(current, *base, true) else {
return Ok(None)
};

let Stmt::Expr(Expr::Call(ExprCall { args: some_args, .. }), _) = last_stmt else {
return Err(Error::new(last_stmt.span(), "expected last expression to be `Some(match (..) { .. })`"))
};
}
10 changes: 10 additions & 0 deletions tests/source/configs/use_small_heuristics/default.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,13 @@ fn main() {
sit
};
}

fn format_let_else() {
let Some(a) = opt else {};

let Some(b) = opt else { return };

let Some(c) = opt else { return };

let Some(d) = some_very_very_very_very_long_name else { return };
}
Loading