zksecurity / noname

Noname: a programming language to write zkapps
https://zksecurity.github.io/noname/
193 stars 50 forks source link

Support generic struct #212

Open katat opened 3 weeks ago

katat commented 3 weeks ago

Generic struct only can simplify repeated code, but also it is necessary when we want to use struct field to instantiate a generic method.

For example:

struct Uint8 {
    inner: Field,
    bit_len: Field,
}

fn Uint8.new(val: Field) -> Uint8 {
    let bit_len = 8;

    // range check
    let ignore_ = bits::to_bits(bit_len, val);

    return Uint8 {
        inner: val,
        bit_len: bit_len
    };
}

fn Uint8.less_than(self, rhs: Uint8) -> Bool {
    return comparator::less_than(self.bit_len, self.inner, rhs.inner);
}

With support of generic struct, struct Uint8 can be generalized as Uint<bit_len> generic over the size of bit len.

Also the self.bit_len can be treated as a immutable constant so it can be as a constant argument to instantiate a generic function.

mimoo commented 3 weeks ago

Btw constants as field might still be useful. For example, if we want to track the bit number of something and only perform mod reductions or range checks when the bits get too large