Skip to content

Rust has only-const callable functions thanks to PMEs #18

@lcnr

Description

@lcnr
#[expect(unconditional_recursion)]
const fn codegen_diverge<T>() {
    codegen_diverge::<(T,)>();
}

const fn only_const_callable() -> usize {
    if false {
        codegen_diverge::<()>();
    }
    
    2
}

const OK: usize = only_const_callable();

fn main() {
    println!("{}", OK);
    println!("{}", const { only_const_callable() });
    // println!("{}", only_const_callable()); // error
}

We only actually recursively instantiate codegen_diverge during mono item collection. This means using only_const_callable at runtime results in a post monomophization error. CTFE lazily instantiates functions on demand so it never overflows.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions