noir-lang / noir

Noir is a domain specific language for zero knowledge proofs
https://noir-lang.org
Apache License 2.0
878 stars 190 forks source link

Underflow in arithmetic generics leads to compiler crash #5798

Closed jfecher closed 1 month ago

jfecher commented 2 months ago

Aim

fn main() {
    let x: [Field; 1] = [1];
    foo(x);
}

fn foo<let N: u32>(_a: [Field; N]) -> [Field; N - 2] {
    std::mem::zeroed()
}

Expected Behavior

A type error that N - 2 fails to unify with 0 - 2

Bug

memory allocation of 618475290480 bytes failed
[1]    18606 IOT instruction (core dumped)  nargo e --arithmetic-generics

To Reproduce

1. 2. 3. 4.

Workaround

None

Workaround Description

No response

Additional Context

No response

Project Impact

None

Blocker Context

No response

Nargo Version

No response

NoirJS Version

No response

Proving Backend Tooling & Version

No response

Would you like to submit a PR for this Issue?

None

Support Needs

No response

jfecher commented 2 months ago

Related: I'm not sure how we'd handle code like the following which externally appears to accept any N but internally would underflow for N < 2:

fn main() {
    let x: [Field; 1] = [1];
    seems_fine(x);
}

fn seems_fine<let N: u32>(a: [Field; N]) -> [Field; N] {
    add2(sub2(a))
}

fn sub2<let N: u32>(a: [Field; N]) -> [Field; N - 2] {
    let mut result = [0; N - 2];
    for i in 0 .. result.len() {
        result[i] = a[i];
    }
    result
}

fn add2<let N: u32>(a: [Field; N]) -> [Field; N + 2] {
    let mut result = [0; N + 2];
    for i in 0 .. a.len() {
        result[i] = a[i];
    }
    result
}

I think we'd need to allow this during type checking but error during monomorphization

jfecher commented 1 month ago

This has since been fixed. We now issue an error:

error: Could not determine array length `(1 - 2)`