openvm_circuit_derive/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
extern crate alloc;
extern crate proc_macro;

use itertools::{multiunzip, Itertools};
use proc_macro::{Span, TokenStream};
use quote::{quote, ToTokens};
use syn::{punctuated::Punctuated, Data, Fields, GenericParam, Ident, Meta, Token};

#[proc_macro_derive(InstructionExecutor)]
pub fn instruction_executor_derive(input: TokenStream) -> TokenStream {
    let ast: syn::DeriveInput = syn::parse(input).unwrap();

    let name = &ast.ident;
    let generics = &ast.generics;
    let (impl_generics, ty_generics, _) = generics.split_for_impl();

    match &ast.data {
        Data::Struct(inner) => {
            // Check if the struct has only one unnamed field
            let inner_ty = match &inner.fields {
                Fields::Unnamed(fields) => {
                    if fields.unnamed.len() != 1 {
                        panic!("Only one unnamed field is supported");
                    }
                    fields.unnamed.first().unwrap().ty.clone()
                }
                _ => panic!("Only unnamed fields are supported"),
            };
            // Use full path ::openvm_circuit... so it can be used either within or outside the vm crate.
            // Assume F is already generic of the field.
            let mut new_generics = generics.clone();
            let where_clause = new_generics.make_where_clause();
            where_clause.predicates.push(
                syn::parse_quote! { #inner_ty: ::openvm_circuit::arch::InstructionExecutor<F> },
            );
            quote! {
                impl #impl_generics ::openvm_circuit::arch::InstructionExecutor<F> for #name #ty_generics #where_clause {
                    fn execute(
                        &mut self,
                        instruction: ::openvm_circuit::arch::instructions::instruction::Instruction<F>,
                        from_state: ::openvm_circuit::arch::ExecutionState<u32>,
                    ) -> ::openvm_circuit::arch::Result<::openvm_circuit::arch::ExecutionState<u32>> {
                        self.0.execute(instruction, from_state)
                    }

                    fn get_opcode_name(&self, opcode: usize) -> String {
                        self.0.get_opcode_name(opcode)
                    }
                }
            }
            .into()
        }
        Data::Enum(e) => {
            let variants = e
                .variants
                .iter()
                .map(|variant| {
                    let variant_name = &variant.ident;

                    let mut fields = variant.fields.iter();
                    let field = fields.next().unwrap();
                    assert!(fields.next().is_none(), "Only one field is supported");
                    (variant_name, field)
                })
                .collect::<Vec<_>>();
            let first_ty_generic = ast
                .generics
                .params
                .first()
                .and_then(|param| match param {
                    GenericParam::Type(type_param) => Some(&type_param.ident),
                    _ => None,
                })
                .expect("First generic must be type for Field");
            // Use full path ::openvm_circuit... so it can be used either within or outside the vm crate.
            // Assume F is already generic of the field.
            let (execute_arms, get_opcode_name_arms): (Vec<_>, Vec<_>) =
                multiunzip(variants.iter().map(|(variant_name, field)| {
                    let field_ty = &field.ty;
                    let execute_arm = quote! {
                        #name::#variant_name(x) => <#field_ty as ::openvm_circuit::arch::InstructionExecutor<#first_ty_generic>>::execute(x, instruction, from_state)
                    };
                    let get_opcode_name_arm = quote! {
                        #name::#variant_name(x) => <#field_ty as ::openvm_circuit::arch::InstructionExecutor<#first_ty_generic>>::get_opcode_name(x, opcode)
                    };

                    (execute_arm, get_opcode_name_arm)
                }));
            quote! {
                impl #impl_generics ::openvm_circuit::arch::InstructionExecutor<#first_ty_generic> for #name #ty_generics {
                    fn execute(
                        &mut self,
                        instruction: ::openvm_circuit::arch::instructions::instruction::Instruction<#first_ty_generic>,
                        from_state: ::openvm_circuit::arch::ExecutionState<u32>,
                    ) -> ::openvm_circuit::arch::Result<::openvm_circuit::arch::ExecutionState<u32>> {
                        match self {
                            #(#execute_arms,)*
                        }
                    }

                    fn get_opcode_name(&self, opcode: usize) -> String {
                        match self {
                            #(#get_opcode_name_arms,)*
                        }
                    }
                }
            }
            .into()
        }
        Data::Union(_) => unimplemented!("Unions are not supported"),
    }
}

/// Derives `AnyEnum` trait on an enum type.
/// By default an enum arm will just return `self` as `&dyn Any`.
///
/// Use the `#[any_enum]` field attribute to specify that the
/// arm itself implements `AnyEnum` and should call the inner `as_any_kind` method.
#[proc_macro_derive(AnyEnum, attributes(any_enum))]
pub fn any_enum_derive(input: TokenStream) -> TokenStream {
    let ast: syn::DeriveInput = syn::parse(input).unwrap();

    let name = &ast.ident;
    let generics = &ast.generics;
    let (impl_generics, ty_generics, _) = generics.split_for_impl();

    match &ast.data {
        Data::Enum(e) => {
            let variants = e
                .variants
                .iter()
                .map(|variant| {
                    let variant_name = &variant.ident;

                    // Check if the variant has #[any_enum] attribute
                    let is_enum = variant
                        .attrs
                        .iter()
                        .any(|attr| attr.path().is_ident("any_enum"));
                    let mut fields = variant.fields.iter();
                    let field = fields.next().unwrap();
                    assert!(fields.next().is_none(), "Only one field is supported");
                    (variant_name, field, is_enum)
                })
                .collect::<Vec<_>>();
            let (arms, arms_mut): (Vec<_>, Vec<_>) =
                variants.iter().map(|(variant_name, field, is_enum)| {
                    let field_ty = &field.ty;

                    if *is_enum {
                        // Call the inner trait impl
                        (quote! {
                            #name::#variant_name(x) => <#field_ty as ::openvm_circuit::arch::AnyEnum>::as_any_kind(x)
                        },
                        quote! {
                            #name::#variant_name(x) => <#field_ty as ::openvm_circuit::arch::AnyEnum>::as_any_kind_mut(x)
                        })
                    } else {
                        (quote! {
                            #name::#variant_name(x) => x
                        },
                        quote! {
                            #name::#variant_name(x) => x
                        })
                    }
                }).unzip();
            quote! {
                impl #impl_generics ::openvm_circuit::arch::AnyEnum for #name #ty_generics {
                    fn as_any_kind(&self) -> &dyn std::any::Any {
                        match self {
                            #(#arms,)*
                        }
                    }

                    fn as_any_kind_mut(&mut self) -> &mut dyn std::any::Any {
                        match self {
                            #(#arms_mut,)*
                        }
                    }
                }
            }
            .into()
        }
        _ => syn::Error::new(name.span(), "Only enums are supported")
            .to_compile_error()
            .into(),
    }
}

// VmConfig derive macro

#[proc_macro_derive(VmConfig, attributes(system, extension))]
pub fn vm_generic_config_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let ast = syn::parse_macro_input!(input as syn::DeriveInput);
    let name = &ast.ident;

    let gen_name_with_uppercase_idents = |ident: &Ident| {
        let mut name = ident.to_string().chars().collect::<Vec<_>>();
        assert!(name[0].is_lowercase(), "Field name must not be capitalized");
        let res_lower = Ident::new(&name.iter().collect::<String>(), Span::call_site().into());
        name[0] = name[0].to_ascii_uppercase();
        let res_upper = Ident::new(&name.iter().collect::<String>(), Span::call_site().into());
        (res_lower, res_upper)
    };

    match &ast.data {
        syn::Data::Struct(inner) => {
            let fields = match &inner.fields {
                Fields::Named(named) => named.named.iter().collect(),
                Fields::Unnamed(_) => {
                    return syn::Error::new(name.span(), "Only named fields are supported")
                        .to_compile_error()
                        .into();
                }
                Fields::Unit => vec![],
            };

            let system = fields
                .iter()
                .filter(|f| f.attrs.iter().any(|attr| attr.path().is_ident("system")))
                .exactly_one()
                .expect("Exactly one field must have #[system] attribute");
            let (system_name, system_name_upper) =
                gen_name_with_uppercase_idents(&system.ident.clone().unwrap());

            let extensions = fields
                .iter()
                .filter(|f| f.attrs.iter().any(|attr| attr.path().is_ident("extension")))
                .cloned()
                .collect::<Vec<_>>();

            let mut executor_enum_fields = Vec::new();
            let mut periphery_enum_fields = Vec::new();
            let mut create_chip_complex = Vec::new();
            for &e in extensions.iter() {
                let (field_name, field_name_upper) =
                    gen_name_with_uppercase_idents(&e.ident.clone().unwrap());
                // TRACKING ISSUE:
                // We cannot just use <e.ty.to_token_stream() as VmExtension<F>>::Executor because of this: <https://github.com/rust-lang/rust/issues/85576>
                let mut executor_name = Ident::new(
                    &format!("{}Executor", e.ty.to_token_stream()),
                    Span::call_site().into(),
                );
                let mut periphery_name = Ident::new(
                    &format!("{}Periphery", e.ty.to_token_stream()),
                    Span::call_site().into(),
                );
                if let Some(attr) = e
                    .attrs
                    .iter()
                    .find(|attr| attr.path().is_ident("extension"))
                {
                    match attr.meta {
                        Meta::Path(_) => {}
                        Meta::NameValue(_) => {
                            return syn::Error::new(
                                name.span(),
                                "Only `#[extension]` or `#[extension(...)] formats are supported",
                            )
                            .to_compile_error()
                            .into()
                        }
                        _ => {
                            let nested = attr
                                .parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)
                                .unwrap();
                            for meta in nested {
                                match meta {
                                    Meta::NameValue(nv) => {
                                        if nv.path.is_ident("executor") {
                                            executor_name = Ident::new(
                                                &nv.value.to_token_stream().to_string(),
                                                Span::call_site().into(),
                                            );
                                            Ok(())
                                        } else if nv.path.is_ident("periphery") {
                                            periphery_name = Ident::new(
                                                &nv.value.to_token_stream().to_string(),
                                                Span::call_site().into(),
                                            );
                                            Ok(())
                                        } else {
                                            Err("only executor and periphery keys are supported")
                                        }
                                    }
                                    _ => Err("only name = value format is supported"),
                                }
                                .expect("wrong attributes format");
                            }
                        }
                    }
                };
                executor_enum_fields.push(quote! {
                    #[any_enum]
                    #field_name_upper(#executor_name<F>),
                });
                periphery_enum_fields.push(quote! {
                    #[any_enum]
                    #field_name_upper(#periphery_name<F>),
                });
                create_chip_complex.push(quote! {
                    let complex: VmChipComplex<F, Self::Executor, Self::Periphery> = complex.extend(&self.#field_name)?;
                });
            }

            let executor_type = Ident::new(&format!("{}Executor", name), name.span());
            let periphery_type = Ident::new(&format!("{}Periphery", name), name.span());
            TokenStream::from(quote! {
                #[derive(ChipUsageGetter, Chip, InstructionExecutor, From, AnyEnum)]
                pub enum #executor_type<F: PrimeField32> {
                    #[any_enum]
                    #system_name_upper(SystemExecutor<F>),
                    #(#executor_enum_fields)*
                }

                #[derive(ChipUsageGetter, Chip, From, AnyEnum)]
                pub enum #periphery_type<F: PrimeField32> {
                    #[any_enum]
                    #system_name_upper(SystemPeriphery<F>),
                    #(#periphery_enum_fields)*
                }

                impl<F: PrimeField32> VmConfig<F> for #name {
                    type Executor = #executor_type<F>;
                    type Periphery = #periphery_type<F>;

                    fn system(&self) -> &SystemConfig {
                        &self.#system_name
                    }
                    fn system_mut(&mut self) -> &mut SystemConfig {
                        &mut self.#system_name
                    }

                    fn create_chip_complex(
                        &self,
                    ) -> Result<VmChipComplex<F, Self::Executor, Self::Periphery>, VmInventoryError> {
                        let complex = self.#system_name.create_chip_complex()?;
                        #(#create_chip_complex)*
                        Ok(complex)
                    }
                }
            })
        }
        _ => syn::Error::new(name.span(), "Only structs are supported")
            .to_compile_error()
            .into(),
    }
}