dlang / project-ideas

Collection of impactful projects in the D ecosystem
36 stars 12 forks source link

Better CTFE support for std.bigint #94

Open saxbophone opened 1 year ago

saxbophone commented 1 year ago

Description

Certain cases of constructing BigInt values at compile time are prone to failure, consider the following test case:

@safe unittest
{
    template Product(ulong value)
    {
        immutable BigInt Product = value;
    }
    template Product(ulong value, values...)
    {
        immutable BigInt Product = Product!value * Product!values;
    }
    immutable BigInt[3] factors = [BigInt(ulong.max), BigInt(ulong.max - 1), BigInt(ulong.max - 2)];
    immutable BigInt expected_result = factors[0] * factors[1] * factors[2]; // no problem here

    // currently, compilation error on this next line:
    immutable BigInt actual_result = Product!(ulong.max, ulong.max - 1, ulong.max - 2);
    assert(actual_result == expected_result);
}

Note that this failure occurs specifically when the BigInt is constructed in this template-recursive way, the same value could in this case be constructed with regular inline multiplication.

What are rough milestones of this project?

TBD

How does this project help the D community?

Being able to use BigInt values in template-recursive/variadic ways like these adds greater flexibility and purpose to the standard library. For the original use case I have for this, it would allow one to get the product of an arbitrary number of variables that are known at compile time (but might be subject to change due to the variables being sourced from a template, type trait, or other generic construct).
Being able to do this at compile time provides an optimisation opportunity by not requiring the re-calculation of large values that could be derived at compile-time.
This has applications in functionality such as reflection-based serialisation, arithmetic coding, number base conversion and generally anything which is "generally arbitrary but guaranteed fixed at the time of compilation".

Recommended skills

TBD

(If applicable, e.g. GSoC/SAoC)

What can students expect to get out of doing this project?

TBD

Point of Contact

TBD

References