Skip to content

lazy const evaluation incompatible with const fn #29928

Closed
@oli-obk

Description

@oli-obk

The following code fails to compile

#![feature(const_fn)]
const fn f(x: usize) -> A {
    A { field: x }
}
struct A {
    field: usize,
}
fn main() {
    let _ = [0; f(5).field];
}

The problem is that the A { field: x } expression is lazily evaluated. So we evaluate it when we access field in f(5).field. But now we already lost the function argument x since we are no longer evaluating the const fn. When we try to access x in the const evaluator it bails out with non-const expr. The easy fix would be to evaluate everything eagerly (as it is done in trans/consts). But then we get breaking changes left and right.

Example: the following is legal (see #28189):

struct S<T>(T) where [T; (||{}, 1).1]: Copy;                                    
fn main() {}

But we don't support closures. In fact, you can write arbitrary expression that typecheck and they will compile:

unsafe fn bla() -> i32 { 5 }
struct S<T>(T) where [T; (unsafe { bla() }, 1).1]: Copy;                                    
fn main() {}

So we can't make the const evaluator eager without introducing breaking changes.

  1. As a remedy we can make it eager, but report errors lazily: const_eval evaluates everything eagerly, but stores a Result<ConstVal, ConstEvalErr> instead of a ConstVal wherever we currently allow lazy evaluation.
  2. As an alternative someone pushes the eager const evaluator I implemented through crater and we go with the breaking change (yay?).
  3. Another alternative is to make const fn lazy, too. So we just pass in the expression that generated the function argument, instead of evaluating the function argument. Then we do the same for structs and tuples, so instead of just lazily storing the expression that generates them, we also store the expressions of their fields.
    • imo this is not a nice solution, and probably the most complex implementation-wise

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions