Skip to content

Overly aggressive const_fn function pointer check. #83033

Closed
@HindrikStegenga

Description

@HindrikStegenga

I tried this code:

#[derive(Clone, Copy)]
struct Foo {
    sort_idx: usize,
    some_fn: unsafe fn(*mut u8, u16)
}

unsafe fn dummy_fn(_: *mut u8, _: u16) {}


const fn sort_arr<const N: usize>(arr: [Foo; N]) -> [Foo; N] {
    let mut unsorted_arr: [Foo; N] = [Foo {
        sort_idx: 0,
        some_fn: dummy_fn
    }; N];
    
    // My actual need is to construct a array of size N, copy arr into it and sort in place. This part is omitted for brevity.
    
    unsorted_arr
}

fn foo() {

}

I expected to see this happen: explanation
I expected this to work, and just compile.

Instead, this happened: explanation

function pointer casts are not allowed in constant functions
see issue #57563 #57563 for more information
add #![feature(const_fn_fn_ptr_basics)] to the crate

It complains about unable being to assign the fn pointer due to a cast, which makes no sense since a type cast should not be necessary.
Interestingly enough, the following does compile and work fine:

#[derive(Clone, Copy)]
struct Foo {
    sort_idx: usize,
    some_fn: unsafe fn(*mut u8, u16)
}

unsafe fn dummy_fn(_: *mut u8, _: u16) {}

const EMPTY_FOO: Foo = Foo {
    sort_idx: 0,
    some_fn: dummy_fn
};

const fn some_const_fn<const N: usize>(arr: [Foo; N]) -> [Foo; N] {
    let mut unsorted_arr: [Foo; N] = [EMPTY_FOO; N];

    // My actual need is to construct a array of size N, copy arr into it and sort in place. This part is omitted for brevity.

    unsorted_arr
}

Meta

rustc --version --verbose:

rustc 1.51.0-nightly (e38fb306b 2021-01-14)
binary: rustc
commit-hash: e38fb306b7f5e65cca34df2dab1f0db15e1defb4
commit-date: 2021-01-14
host: x86_64-apple-darwin
release: 1.51.0-nightly
LLVM version: 11.0
Backtrace

<backtrace>

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions