openvm_algebra_complex_macros/
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
#![feature(proc_macro_diagnostic)]

extern crate proc_macro;

use openvm_macros_common::MacroArgs;
use proc_macro::TokenStream;
use syn::{
    parse::{Parse, ParseStream},
    parse_macro_input, Expr, ExprPath, Path, Token,
};

/// This macro is used to declare the complex extension fields.
/// Usage:
/// ```rust
/// complex_declare! {
///     Complex1 { mod_type = Mod1 },
///     Complex2 { mod_type = Mod2 },
/// }
/// ```
#[proc_macro]
pub fn complex_declare(input: TokenStream) -> TokenStream {
    let MacroArgs { items } = parse_macro_input!(input as MacroArgs);

    let mut output = Vec::new();

    let span = proc_macro::Span::call_site();

    for item in items.into_iter() {
        let struct_name = item.name.to_string();
        let struct_name = syn::Ident::new(&struct_name, span.into());
        let mut intmod_type: Option<syn::Path> = None;
        for param in item.params {
            match param.name.to_string().as_str() {
                "mod_type" => {
                    if let syn::Expr::Path(ExprPath { path, .. }) = param.value {
                        intmod_type = Some(path)
                    } else {
                        return syn::Error::new_spanned(param.value, "Expected a type")
                            .to_compile_error()
                            .into();
                    }
                }
                _ => {
                    panic!("Unknown parameter {}", param.name);
                }
            }
        }

        let intmod_type = intmod_type.expect("mod_type parameter is required");

        macro_rules! create_extern_func {
            ($name:ident) => {
                let $name = syn::Ident::new(
                    &format!("{}_{}", stringify!($name), struct_name),
                    span.into(),
                );
            };
        }
        create_extern_func!(complex_add_extern_func);
        create_extern_func!(complex_sub_extern_func);
        create_extern_func!(complex_mul_extern_func);
        create_extern_func!(complex_div_extern_func);

        let result = TokenStream::from(quote::quote_spanned! { span.into() =>
            extern "C" {
                fn #complex_add_extern_func(rd: usize, rs1: usize, rs2: usize);
                fn #complex_sub_extern_func(rd: usize, rs1: usize, rs2: usize);
                fn #complex_mul_extern_func(rd: usize, rs1: usize, rs2: usize);
                fn #complex_div_extern_func(rd: usize, rs1: usize, rs2: usize);
            }


            /// Quadratic extension field of `#intmod_type` with irreducible polynomial `X^2 + 1`.
            /// Elements are represented as `c0 + c1 * u` where `u^2 = -1`.
            ///
            /// Memory alignment follows alignment of `#intmod_type`.
            /// Memory layout is concatenation of `c0` and `c1`.
            #[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
            #[repr(C)]
            pub struct #struct_name {
                /// Real coordinate
                pub c0: #intmod_type,
                /// Imaginary coordinate
                pub c1: #intmod_type,
            }

            impl #struct_name {
                pub const fn new(c0: #intmod_type, c1: #intmod_type) -> Self {
                    Self { c0, c1 }
                }
            }

            impl #struct_name {
                // Zero element (i.e. additive identity)
                pub const ZERO: Self = Self::new(<#intmod_type as openvm_algebra_guest::IntMod>::ZERO, <#intmod_type as openvm_algebra_guest::IntMod>::ZERO);

                // One element (i.e. multiplicative identity)
                pub const ONE: Self = Self::new(<#intmod_type as openvm_algebra_guest::IntMod>::ONE, <#intmod_type as openvm_algebra_guest::IntMod>::ZERO);

                pub fn neg_assign(&mut self) {
                    self.c0.neg_assign();
                    self.c1.neg_assign();
                }

                /// Implementation of AddAssign.
                #[inline(always)]
                fn add_assign_impl(&mut self, other: &Self) {
                    #[cfg(not(target_os = "zkvm"))]
                    {
                        self.c0 += &other.c0;
                        self.c1 += &other.c1;
                    }
                    #[cfg(target_os = "zkvm")]
                    {
                        unsafe {
                            #complex_add_extern_func(
                                self as *mut Self as usize,
                                self as *const Self as usize,
                                other as *const Self as usize
                            );
                        }
                    }
                }

                /// Implementation of SubAssign.
                #[inline(always)]
                fn sub_assign_impl(&mut self, other: &Self) {
                    #[cfg(not(target_os = "zkvm"))]
                    {
                        self.c0 -= &other.c0;
                        self.c1 -= &other.c1;
                    }
                    #[cfg(target_os = "zkvm")]
                    {
                        unsafe {
                            #complex_sub_extern_func(
                                self as *mut Self as usize,
                                self as *const Self as usize,
                                other as *const Self as usize
                            );
                        }
                    }
                }

                /// Implementation of MulAssign.
                #[inline(always)]
                fn mul_assign_impl(&mut self, other: &Self) {
                    #[cfg(not(target_os = "zkvm"))]
                    {
                        let (c0, c1) = (&self.c0, &self.c1);
                        let (d0, d1) = (&other.c0, &other.c1);
                        *self = Self::new(
                            c0.clone() * d0 - c1.clone() * d1,
                            c0.clone() * d1 + c1.clone() * d0,
                        );
                    }
                    #[cfg(target_os = "zkvm")]
                    {
                        unsafe {
                            #complex_mul_extern_func(
                                self as *mut Self as usize,
                                self as *const Self as usize,
                                other as *const Self as usize
                            );
                        }
                    }
                }

                /// Implementation of DivAssignUnsafe.
                #[inline(always)]
                fn div_assign_unsafe_impl(&mut self, other: &Self) {
                    #[cfg(not(target_os = "zkvm"))]
                    {
                        let (c0, c1) = (&self.c0, &self.c1);
                        let (d0, d1) = (&other.c0, &other.c1);
                        let denom = <#intmod_type as openvm_algebra_guest::IntMod>::ONE.div_unsafe(d0.square() + d1.square());
                        *self = Self::new(
                            denom.clone() * (c0.clone() * d0 + c1.clone() * d1),
                            denom * &(c1.clone() * d0 - c0.clone() * d1),
                        );
                    }
                    #[cfg(target_os = "zkvm")]
                    {
                        unsafe {
                            #complex_div_extern_func(
                                self as *mut Self as usize,
                                self as *const Self as usize,
                                other as *const Self as usize
                            );
                        }
                    }
                }

                /// Implementation of Add that doesn't cause zkvm to use an additional store.
                fn add_refs_impl(&self, other: &Self) -> Self {
                    #[cfg(not(target_os = "zkvm"))]
                    {
                        let mut res = self.clone();
                        res.add_assign_impl(other);
                        res
                    }
                    #[cfg(target_os = "zkvm")]
                    {
                        let mut uninit: core::mem::MaybeUninit<Self> = core::mem::MaybeUninit::uninit();
                        unsafe {
                            #complex_add_extern_func(
                                uninit.as_mut_ptr() as usize,
                                self as *const Self as usize,
                                other as *const Self as usize
                            );
                        }
                        unsafe { uninit.assume_init() }
                    }
                }

                /// Implementation of Sub that doesn't cause zkvm to use an additional store.
                #[inline(always)]
                fn sub_refs_impl(&self, other: &Self) -> Self {
                    #[cfg(not(target_os = "zkvm"))]
                    {
                        let mut res = self.clone();
                        res.sub_assign_impl(other);
                        res
                    }
                    #[cfg(target_os = "zkvm")]
                    {
                        let mut uninit: core::mem::MaybeUninit<Self> = core::mem::MaybeUninit::uninit();
                        unsafe {
                            #complex_sub_extern_func(
                                uninit.as_mut_ptr() as usize,
                                self as *const Self as usize,
                                other as *const Self as usize
                            );
                        }
                        unsafe { uninit.assume_init() }
                    }
                }

                /// Implementation of Mul that doesn't cause zkvm to use an additional store.
                ///
                /// SAFETY: dst_ptr must be pointer for `&mut Self`.
                /// It will only be written to at the end of the function.
                #[inline(always)]
                unsafe fn mul_refs_impl(&self, other: &Self, dst_ptr: *mut Self) {
                    #[cfg(not(target_os = "zkvm"))]
                    {
                        let mut res = self.clone();
                        res.mul_assign_impl(other);
                        let dst = unsafe { &mut *dst_ptr };
                        *dst = res;
                    }
                    #[cfg(target_os = "zkvm")]
                    {
                        unsafe {
                            #complex_mul_extern_func(
                                dst_ptr as usize,
                                self as *const Self as usize,
                                other as *const Self as usize
                            );
                        }
                    }
                }

                /// Implementation of DivUnsafe that doesn't cause zkvm to use an additional store.
                #[inline(always)]
                fn div_unsafe_refs_impl(&self, other: &Self) -> Self {
                    #[cfg(not(target_os = "zkvm"))]
                    {
                        let mut res = self.clone();
                        res.div_assign_unsafe_impl(other);
                        res
                    }
                    #[cfg(target_os = "zkvm")]
                    {
                        let mut uninit: core::mem::MaybeUninit<Self> = core::mem::MaybeUninit::uninit();
                        unsafe {
                            #complex_div_extern_func(
                                uninit.as_mut_ptr() as usize,
                                self as *const Self as usize,
                                other as *const Self as usize
                            );
                        }
                        unsafe { uninit.assume_init() }
                    }
                }
            }

            impl openvm_algebra_guest::field::ComplexConjugate for #struct_name {
                fn conjugate(self) -> Self {
                    Self {
                        c0: self.c0,
                        c1: -self.c1,
                    }
                }

                fn conjugate_assign(&mut self) {
                    self.c1.neg_assign();
                }
            }

            impl<'a> core::ops::AddAssign<&'a #struct_name> for #struct_name {
                #[inline(always)]
                fn add_assign(&mut self, other: &'a #struct_name) {
                    self.add_assign_impl(other);
                }
            }

            impl core::ops::AddAssign for #struct_name {
                #[inline(always)]
                fn add_assign(&mut self, other: Self) {
                    self.add_assign_impl(&other);
                }
            }

            impl core::ops::Add for #struct_name {
                type Output = Self;
                #[inline(always)]
                fn add(mut self, other: Self) -> Self::Output {
                    self += other;
                    self
                }
            }

            impl<'a> core::ops::Add<&'a #struct_name> for #struct_name {
                type Output = Self;
                #[inline(always)]
                fn add(mut self, other: &'a #struct_name) -> Self::Output {
                    self += other;
                    self
                }
            }

            impl<'a> core::ops::Add<&'a #struct_name> for &#struct_name {
                type Output = #struct_name;
                #[inline(always)]
                fn add(self, other: &'a #struct_name) -> Self::Output {
                    self.add_refs_impl(other)
                }
            }

            impl<'a> core::ops::SubAssign<&'a #struct_name> for #struct_name {
                #[inline(always)]
                fn sub_assign(&mut self, other: &'a #struct_name) {
                    self.sub_assign_impl(other);
                }
            }

            impl core::ops::SubAssign for #struct_name {
                #[inline(always)]
                fn sub_assign(&mut self, other: Self) {
                    self.sub_assign_impl(&other);
                }
            }

            impl core::ops::Sub for #struct_name {
                type Output = Self;
                #[inline(always)]
                fn sub(mut self, other: Self) -> Self::Output {
                    self -= other;
                    self
                }
            }

            impl<'a> core::ops::Sub<&'a #struct_name> for #struct_name {
                type Output = Self;
                #[inline(always)]
                fn sub(mut self, other: &'a #struct_name) -> Self::Output {
                    self -= other;
                    self
                }
            }

            impl<'a> core::ops::Sub<&'a #struct_name> for &#struct_name {
                type Output = #struct_name;
                #[inline(always)]
                fn sub(self, other: &'a #struct_name) -> Self::Output {
                    self.sub_refs_impl(other)
                }
            }

            impl<'a> core::ops::MulAssign<&'a #struct_name> for #struct_name {
                #[inline(always)]
                fn mul_assign(&mut self, other: &'a #struct_name) {
                    self.mul_assign_impl(other);
                }
            }

            impl core::ops::MulAssign for #struct_name {
                #[inline(always)]
                fn mul_assign(&mut self, other: Self) {
                    self.mul_assign_impl(&other);
                }
            }

            impl core::ops::Mul for #struct_name {
                type Output = Self;
                #[inline(always)]
                fn mul(mut self, other: Self) -> Self::Output {
                    self *= other;
                    self
                }
            }

            impl<'a> core::ops::Mul<&'a #struct_name> for #struct_name {
                type Output = Self;
                #[inline(always)]
                fn mul(mut self, other: &'a #struct_name) -> Self::Output {
                    self *= other;
                    self
                }
            }

            impl<'a> core::ops::Mul<&'a #struct_name> for &'a #struct_name {
                type Output = #struct_name;
                #[inline(always)]
                fn mul(self, other: &'a #struct_name) -> Self::Output {
                    let mut uninit: core::mem::MaybeUninit<#struct_name> = core::mem::MaybeUninit::uninit();
                    unsafe {
                        self.mul_refs_impl(other, uninit.as_mut_ptr());
                        uninit.assume_init()
                    }
                }
            }

            impl<'a> openvm_algebra_guest::DivAssignUnsafe<&'a #struct_name> for #struct_name {
                #[inline(always)]
                fn div_assign_unsafe(&mut self, other: &'a #struct_name) {
                    self.div_assign_unsafe_impl(other);
                }
            }

            impl openvm_algebra_guest::DivAssignUnsafe for #struct_name {
                #[inline(always)]
                fn div_assign_unsafe(&mut self, other: Self) {
                    self.div_assign_unsafe_impl(&other);
                }
            }

            impl openvm_algebra_guest::DivUnsafe for #struct_name {
                type Output = Self;
                #[inline(always)]
                fn div_unsafe(mut self, other: Self) -> Self::Output {
                    self = self.div_unsafe_refs_impl(&other);
                    self
                }
            }

            impl<'a> openvm_algebra_guest::DivUnsafe<&'a #struct_name> for #struct_name {
                type Output = Self;
                #[inline(always)]
                fn div_unsafe(mut self, other: &'a #struct_name) -> Self::Output {
                    self = self.div_unsafe_refs_impl(other);
                    self
                }
            }

            impl<'a> openvm_algebra_guest::DivUnsafe<&'a #struct_name> for &#struct_name {
                type Output = #struct_name;
                #[inline(always)]
                fn div_unsafe(self, other: &'a #struct_name) -> Self::Output {
                    self.div_unsafe_refs_impl(other)
                }
            }

            impl<'a> core::iter::Sum<&'a #struct_name> for #struct_name {
                fn sum<I: core::iter::Iterator<Item = &'a #struct_name>>(iter: I) -> Self {
                    iter.fold(Self::ZERO, |acc, x| &acc + x)
                }
            }

            impl core::iter::Sum for #struct_name {
                fn sum<I: core::iter::Iterator<Item = Self>>(iter: I) -> Self {
                    iter.fold(Self::ZERO, |acc, x| &acc + &x)
                }
            }

            impl<'a> core::iter::Product<&'a #struct_name> for #struct_name {
                fn product<I: core::iter::Iterator<Item = &'a #struct_name>>(iter: I) -> Self {
                    iter.fold(Self::ONE, |acc, x| &acc * x)
                }
            }

            impl core::iter::Product for #struct_name {
                fn product<I: core::iter::Iterator<Item = Self>>(iter: I) -> Self {
                    iter.fold(Self::ONE, |acc, x| &acc * &x)
                }
            }

            impl core::ops::Neg for #struct_name {
                type Output = #struct_name;
                fn neg(self) -> Self::Output {
                    Self::ZERO - &self
                }
            }

            impl core::ops::Neg for &#struct_name {
                type Output = #struct_name;
                fn neg(self) -> Self::Output {
                    #struct_name::ZERO - self
                }
            }

            impl core::fmt::Debug for #struct_name {
                fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                    write!(f, "{:?} + {:?} * u", self.c0, self.c1)
                }
            }
        });
        output.push(result);
    }

    TokenStream::from_iter(output)
}

/// This macro is used to initialize the complex extension fields.
/// It must be called after `moduli_init!` is called.
///
/// Usage:
/// ```rust
/// moduli_init!("998244353", "1000000007");
///
/// complex_init!(Complex2 { mod_idx = 1 }, Complex1 { mod_idx = 0 });
/// ```
/// In particular, the order of complex types in the macro doesn't have to match the order of moduli in `moduli_init!`,
/// but they should be accompanied by the `mod_idx` corresponding to the order in the `moduli_init!` macro (not `moduli_declare!`).
#[proc_macro]
pub fn complex_init(input: TokenStream) -> TokenStream {
    let MacroArgs { items } = parse_macro_input!(input as MacroArgs);

    let mut externs = Vec::new();
    let mut setups = Vec::new();
    let mut setup_all_complex_extensions = Vec::new();

    let span = proc_macro::Span::call_site();

    for (complex_idx, item) in items.into_iter().enumerate() {
        let struct_name = item.name.to_string();
        let struct_name = syn::Ident::new(&struct_name, span.into());
        let mut intmod_idx: Option<usize> = None;
        for param in item.params {
            match param.name.to_string().as_str() {
                "mod_idx" => {
                    if let syn::Expr::Lit(syn::ExprLit {
                        lit: syn::Lit::Int(int),
                        ..
                    }) = param.value
                    {
                        intmod_idx = Some(int.base10_parse::<usize>().unwrap());
                    } else {
                        return syn::Error::new_spanned(param.value, "Expected usize")
                            .to_compile_error()
                            .into();
                    }
                }
                _ => {
                    panic!("Unknown parameter {}", param.name);
                }
            }
        }
        let mod_idx = intmod_idx.expect("mod_idx is required");

        println!(
            "[init] complex #{} = {} (mod_idx = {})",
            complex_idx, struct_name, mod_idx
        );

        for op_type in ["add", "sub", "mul", "div"] {
            let func_name = syn::Ident::new(
                &format!("complex_{}_extern_func_{}", op_type, struct_name),
                span.into(),
            );
            let mut chars = op_type.chars().collect::<Vec<_>>();
            chars[0] = chars[0].to_ascii_uppercase();
            let local_opcode = syn::Ident::new(&chars.iter().collect::<String>(), span.into());
            externs.push(quote::quote_spanned! { span.into() =>
                #[no_mangle]
                extern "C" fn #func_name(rd: usize, rs1: usize, rs2: usize) {
                    openvm_platform::custom_insn_r!(
                        openvm_algebra_guest::OPCODE,
                        openvm_algebra_guest::COMPLEX_EXT_FIELD_FUNCT3,
                        openvm_algebra_guest::ComplexExtFieldBaseFunct7::#local_opcode as usize
                            + #mod_idx * (openvm_algebra_guest::ComplexExtFieldBaseFunct7::COMPLEX_EXT_FIELD_MAX_KINDS as usize),
                        rd,
                        rs1,
                        rs2
                    )
                }
            });
        }

        let setup_function =
            syn::Ident::new(&format!("setup_complex_{}", complex_idx), span.into());

        setup_all_complex_extensions.push(quote::quote_spanned! { span.into() =>
            #setup_function();
        });
        setups.push(quote::quote_spanned! { span.into() =>
            #[allow(non_snake_case)]
            pub fn #setup_function() {
                #[cfg(target_os = "zkvm")]
                {
                    let two_modulus_bytes = &openvm_intrinsics_meta_do_not_type_this_by_yourself::two_modular_limbs_list[openvm_intrinsics_meta_do_not_type_this_by_yourself::limb_list_borders[#mod_idx]..openvm_intrinsics_meta_do_not_type_this_by_yourself::limb_list_borders[#mod_idx + 1]];

                    // We are going to use the numeric representation of the `rs2` register to distinguish the chip to setup.
                    // The transpiler will transform this instruction, based on whether `rs2` is `x0` or `x1`, into a `SETUP_ADDSUB` or `SETUP_MULDIV` instruction.
                    let mut uninit: core::mem::MaybeUninit<[u8; openvm_intrinsics_meta_do_not_type_this_by_yourself::limb_list_borders[#mod_idx + 1] - openvm_intrinsics_meta_do_not_type_this_by_yourself::limb_list_borders[#mod_idx]]> = core::mem::MaybeUninit::uninit();
                    openvm_platform::custom_insn_r!(
                        ::openvm_algebra_guest::OPCODE,
                        ::openvm_algebra_guest::COMPLEX_EXT_FIELD_FUNCT3,
                        ::openvm_algebra_guest::ComplexExtFieldBaseFunct7::Setup as usize
                            + #mod_idx
                                * (::openvm_algebra_guest::ComplexExtFieldBaseFunct7::COMPLEX_EXT_FIELD_MAX_KINDS as usize),
                        uninit.as_mut_ptr(),
                        two_modulus_bytes.as_ptr(),
                        "x0" // will be parsed as 0 and therefore transpiled to SETUP_ADDMOD
                    );
                    openvm_platform::custom_insn_r!(
                        ::openvm_algebra_guest::OPCODE,
                        ::openvm_algebra_guest::COMPLEX_EXT_FIELD_FUNCT3,
                        ::openvm_algebra_guest::ComplexExtFieldBaseFunct7::Setup as usize
                            + #mod_idx
                                * (::openvm_algebra_guest::ComplexExtFieldBaseFunct7::COMPLEX_EXT_FIELD_MAX_KINDS as usize),
                        uninit.as_mut_ptr(),
                        two_modulus_bytes.as_ptr(),
                        "x1" // will be parsed as 1 and therefore transpiled to SETUP_MULDIV
                    );
                }
            }
        });
    }

    TokenStream::from(quote::quote_spanned! { span.into() =>
        #[cfg(target_os = "zkvm")]
        mod openvm_intrinsics_ffi_complex {
            #(#externs)*
        }
        #(#setups)*
        pub fn setup_all_complex_extensions() {
            #(#setup_all_complex_extensions)*
        }
    })
}

struct ComplexSimpleItem {
    items: Vec<Path>,
}

impl Parse for ComplexSimpleItem {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let items = input.parse_terminated(<Expr as Parse>::parse, Token![,])?;
        Ok(Self {
            items: items
                .into_iter()
                .map(|e| {
                    if let Expr::Path(p) = e {
                        p.path
                    } else {
                        panic!("expected path");
                    }
                })
                .collect(),
        })
    }
}

#[proc_macro]
pub fn complex_impl_field(input: TokenStream) -> TokenStream {
    let ComplexSimpleItem { items } = parse_macro_input!(input as ComplexSimpleItem);

    let mut output = Vec::new();

    let span = proc_macro::Span::call_site();

    for item in items.into_iter() {
        let str_path = item
            .segments
            .iter()
            .map(|x| x.ident.to_string())
            .collect::<Vec<_>>()
            .join("_");
        let struct_name = syn::Ident::new(&str_path, span.into());

        output.push(quote::quote_spanned! { span.into() =>
            impl openvm_algebra_guest::field::Field for #struct_name {
                type SelfRef<'a>
                    = &'a Self
                where
                    Self: 'a;

                const ZERO: Self = Self::ZERO;
                const ONE: Self = Self::ONE;

                fn double_assign(&mut self) {
                    openvm_algebra_guest::field::Field::double_assign(&mut self.c0);
                    openvm_algebra_guest::field::Field::double_assign(&mut self.c1);
                }

                fn square_assign(&mut self) {
                    unsafe {
                        self.mul_refs_impl(self, self as *const Self as *mut Self);
                    }
                }
            }
        });
    }

    TokenStream::from(quote::quote_spanned! { span.into() =>
        #(#output)*
    })
}