rust-lang / rust-lang/rustfmt

Trailing spaces removed when formatting `&str` over `max_width`

Open
#4,608 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-whitespace C-bug only-with-option
Dominant language
Rust
Stars
7k
Forks
1.1k
Avg merge
2d 13h
Merged PRs (30d)
24

Description

When there is a &str with trailing spaces that exceeds the max_width rustfmt formats in a way that removes trailing spaces, resulting in different output.

Settings

format_strings = true
max_width = 30
tab_spaces = 1

Description

Note: Line numbers have been added and spaces are replaced with · for clarity.

When trying to format a line like:

1| ··"457890123456789012345678··"

, rustfmt will suggest a new line of:

1| ··"457890123456789012345678·\
2| ····"

If you attempt to add back the space that was removed:

1| ··"457890123456789012345678··\
2| ····"

rustfmt again, suggests removing the space:

1| ··"457890123456789012345678·\
2| ····"

To Reproduce

Also see a minimal, reproducible example.

src/main.rs

fn main() {
 let a = vec![
  // single-line
  "457890123456789012345678  ",
  // multi-line
  "457890123456789012345678  \
    ",
 ];
 assert_eq!(a[0].len(), 26);
 assert_eq!(a[1].len(), 26);
}
  • Run cargo run to see that code runs successfully
  • Run cargo +nightly fmt --all -- --emit files
  • Run cargo run to see that the code fails

The &strs that are created should both have a length of 26.

Expected behavior

Overall, I wouldn't expect rustfmt to change the values of the &strs, though I'm not sure how exactly this should be handled.

Meta

Rust version: 1.50.0-nightly

rustfmt versions:

  • 1.4.29-nightly (70ce182 2020-12-04) from crates.io
  • 1.4.30-nightly (acd9486 2020-12-20) from GitHub releases
  • master (367a874d04abfb2269ff1ea1974f06640546b7c5)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the reproducible example in src/main.rs and run cargo +nightly fmt --all -- --emit files, then cargo run to confirm the changed string value. Investigate rustfmt's handling of format_strings and max_width for the shown trailing-space case. Done means formatting preserves both &str values at length 26 and the example continues to run successfully.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.