Skip to content

Formatting causes syntax error when indexing into return value of long unsafe block within a closure #4965

Open
@kgnlp

Description

@kgnlp

In rare cases, inserting braces around the body of a closure containing an unsafe block followed by indexing seems to cause a syntax error.
Here is a minimal example for reproducing this behavior:

unsafe fn very_long_unsafe_function(vec: &Vec<usize>) -> &Vec<usize> {
    vec
}

fn long_outer_function<'a, F>(index: usize, function: F) -> &'a usize
where
    F: Fn(usize) -> &'a usize,
{
    function(index)
}

fn main() {
    let vec = vec![1, 2, 3, 4];
    // Line which will be split up and reformatted by rust-fmt - compiles and runs without issues
    let output: Vec<_> = vec![0, 0, 1, 1, 2, 2].iter().map(|&index| long_outer_function(index, |index| &unsafe { very_long_unsafe_function(&vec) }[index])).collect();
    println!("{:?}", output);
}

Here is the formatted output using version 1.4.37-nightly (2021-08-25 0afc208)

unsafe fn very_long_unsafe_function(vec: &Vec<usize>) -> &Vec<usize> {
    vec
}

fn long_outer_function<'a, F>(index: usize, function: F) -> &'a usize
where
    F: Fn(usize) -> &'a usize,
{
    function(index)
}

fn main() {
    let vec = vec![1, 2, 3, 4];
    let output: Vec<_> = vec![0, 0, 1, 1, 2, 2]
        .iter()
        // Rust format inserts braces around the bodies of both closures, breaking the inner closure
        .map(|&index| {
            long_outer_function(index, |index| {
                &unsafe { very_long_unsafe_function(&vec) }[index]
            })
        })
        .collect();
    println!("{:?}", output);
}

This results in the following syntax error:

error: expected one of `.`, `;`, `?`, `}`, or an operator, found `[`
  --> src/main.rs:18:60
   |
18 |                 &unsafe { very_long_unsafe_function(&vec) }[index]
   |                                                            ^ expected one of `.`, `;`, `?`, `}`, or an operator

Example code on the playground for reference: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=46a316d108e9686e425ee72b8bb4957e

Metadata

Metadata

Assignees

No one assigned

    Labels

    a-closuresbugPanic, non-idempotency, invalid code, etc.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions