Skip to content

Compiler should report const fns that it can't evaluate #30887

Closed
@jimblandy

Description

@jimblandy

If I write this:

#![feature(const_fn)]

const X : usize = 2;

const fn f(x: usize) -> usize {
    let mut sum = 0;
    for i in 0..x {
        sum += i;
    }
    sum
}

#[allow(unused_variables)]
fn main() {
    let a : [i32; f(X)];
}

then I get the error message:

<anon>:10:5: 10:8 error: array length constant evaluation error: non-constant path in constant expression [E0250]
<anon>:10     sum
              ^~~
<anon>:10:5: 10:8 help: see the detailed explanation for E0250
<anon>:15:13: 15:24 note: for array length here
<anon>:15     let a : [i32; f(X)];
                      ^~~~~~~~~~~

If I understand correctly, the problem here is that although my f is declared to be a const fn, when the compiler tries evaluating the length of the array type [i32; f(X)], it finds it can't actually evaluate that function call at compile time.

As I understand it, the value of declaring a fn to be const is that it makes the function usable at compile time. When this isn't possible, the error message should blame the function, not the call.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions