noir icon indicating copy to clipboard operation
noir copied to clipboard

Cannot replace struct fields with corrected versions (adding generics)

Open Thunkar opened this issue 5 months ago • 3 comments

Aim

Given

comptime fn storage(s: StructDefinition) {
    let mut new_storage_fields = &[];
    let context_generic = s.add_generic("Context");
    for field in s.fields() {
        let (name, typ) = field;
        let with_context_generic = add_context_generic(typ, context_generic);
        println(with_context_generic);
        new_storage_fields = new_storage_fields.push_back((name,  with_context_generic.as_type()));
    }

    s.set_fields(new_storage_fields);
}

comptime fn add_context_generic(typ: Type, context_generic: Type) -> Quoted {
    assert(
        typ.as_struct().is_some(), "Storage containers must be generic structs of the form `Container<..., Context>`"
    );
    let (def, generics) = typ.as_struct().unwrap();
    let name = def.name();
    let new_generics = generics.pop_back().0.push_back(context_generic).map(|typ: Type| quote{$typ}).join(quote{,});
    quote { $name<$new_generics> }
}

struct Container<Context> {
    field1: u32,
    field2: u64,
}

struct MyContext {}

impl MyContext {
    fn zero(self) -> Field {
        0
    }
}

impl Container<MyContext> {
    fn new(context: MyContext) -> Self {
        let _zero = context.zero();
        Self { field1: 0, field2: 0 }
    }
}

// Storage should have a generic argument <Context> that gets passed down to container
// However this is cumbersome boilerplate that we would like to spare the users from writing
#[storage]
struct Storage {
    state: Container
}

fn main() {
    println("Hello, world!");
}

Expected Behavior

The above example should compile, allowing the injection of the <Context> generic struct to the fields in Storage

Bug

Compiler fails with

error: Container expects 1 generic but 0 were given ┌─ src/main.nr:46:12 │ 46 │ state: Container │ --------- │

More context here: https://github.com/AztecProtocol/aztec-packages/issues/8658

To Reproduce

Workaround

None

Workaround Description

No response

Additional Context

No response

Project Impact

Nice-to-have

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

Thunkar avatar Sep 24 '24 12:09 Thunkar