Skip to content

Failed determining slice length at compile time without any runtime conditionals #4736

@sirasistant

Description

@sirasistant

Aim

Compile code like this one:

trait Serialize<N> {
    fn serialize(self) ->[Field; N];
}

struct Point {
    x: Field,
    y: Field,
}

impl Serialize<2> for Point {
    fn serialize(self) -> [Field; 2] {
        [self.x, self.y]
    }
}

fn sum(values: [Field]) -> Field {
    let mut sum = 0;
    for value in values {
        sum = sum + value;
    }
    sum
}

fn main(points: [Point; 3]) -> pub Field {
    let mut serialized_points = &[];
    for point in points {
        serialized_points = serialized_points.append(point.serialize().as_slice());
    }
    sum(serialized_points)
}

Expected Behavior

Should figure out that the length of serialized_points is 6 and compile succesfully

Bug

error: Could not determine loop bound at compile-time
   ┌─ /mnt/user-data/alvaro/constructor/src/main.nr:18:18
   │
18 │     for value in values {
   │                  ------ If attempting to fetch the length of a slice, try converting to an array. Slices only use dynamic lengths.
   │
   = Call stack:
     1. /mnt/user-data/alvaro/constructor/src/main.nr:29:5
     2. /mnt/user-data/alvaro/constructor/src/main.nr:18:18

Aborting due to 1 previous error

Seems like the length is known at the end of the optimization pipeline, since it figures it out if we just return it

fn main(points: [Point; 3]) -> pub Field {
    let mut serialized_points = &[];
    for point in points {
        serialized_points = serialized_points.append(point.serialize().as_slice());
    }
    serialized_points.len() as Field
}

It indeed finds out that the length is 6

After Array Set Optimizations:
acir(inline) fn main f0 {
  b0(v0: [Field, Field; 3]):
    return Field 6
}

To Reproduce

Project Impact

Nice-to-have

Impact Context

No response

Workaround

None

Workaround Description

No response

Additional Context

No response

Installation Method

None

Nargo Version

No response

NoirJS Version

No response

Would you like to submit a PR for this Issue?

None

Support Needs

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions