rust-lang / rustfmt

Format Rust code
https://rust-lang.github.io/rustfmt/
Apache License 2.0
6.06k stars 892 forks source link

Rustfmt incorrectly adds whitespace inside multiline string literals within macro calls that have curly braces #5283

Open Aiden2207 opened 2 years ago

Aiden2207 commented 2 years ago

Code:

macro_rules! test {
    ($l:literal) => {};
}

fn main() {
    test!{
        "
"};
}

expected output:

macro_rules! test {
    ($l:literal) => {};
}

fn main() {
    test!{
        "
"
    };
}

actual output:

macro_rules! test {
    ($l:literal) => {};
}

fn main() {
    test! {
            "
    "};
}

Rustfmt added an extra indentation to the literal, including inside the string itself. This only occurs when the macro invocation is delimited by curly brackets, it works fine when square or parentheses are used.

ytmimi commented 2 years ago

Thanks for the report! Confirming that I can reproduce this on rustfmt 1.4.38-nightly (63acf900 2022-03-27)

ytmimi commented 2 years ago

I'm pretty sure the error can be tracked down to trim_left_preserve_layout in this match arm:

https://github.com/rust-lang/rustfmt/blob/7d6ca7c35c275ab7a6a50d290babe874cb8e3fc7/src/macros.rs#L326-L334

zeenix commented 11 months ago

Rustfmt added an extra indentation to the literal, including inside the string itself. This only occurs when the macro invocation is delimited by curly brackets, it works fine when square or parentheses are used.

Unfortunately this workaround doesn't work for me with rust-analyzer, as it (or cargo fmt) automatically replace [] and () with {} for me. :(

ytmimi commented 11 months ago

@zeenix can you please post a code snippet of the issue you're seeing so we can more easily investigate this when we have time, thanks!

zeenix commented 11 months ago

@zeenix can you please post a code snippet of the issue you're seeing so we can more easily investigate this when we have time, thanks!

It's in the commit that mentioned this issue: https://github.com/zeenix/endi/commit/868afee95a29293aa3d5aca1a4c6c6d1cc9296d8 . If you split the concat! arguments over multiple lines, you'll reproduce the issue.

ytmimi commented 11 months ago

@zeenix It's possible that your issue is related to this one, but it sounds like you're running into https://github.com/rust-lang/rustfmt/issues/5974

zeenix commented 11 months ago

@zeenix It's possible that your issue is related to this one, but it sounds like you're running into #5974

Ah, you're likely correct. Thanks.