jlrs-macros 0.1.1

jlrs-macros contains the custom derives offered by jlrs.
Documentation
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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TS2;
use quote::quote;
use syn::{self, punctuated::Punctuated, token::Comma, Expr, Lit, Meta, Token, WherePredicate};

#[derive(Default)]
pub struct ClassifiedFields<'a> {
    rs_flag_fields: Vec<&'a syn::Type>,
    rs_align_fields: Vec<&'a syn::Type>,
    rs_union_fields: Vec<&'a syn::Type>,
    rs_non_union_fields: Vec<&'a syn::Type>,
    jl_union_field_idxs: Vec<usize>,
    jl_non_union_field_idxs: Vec<usize>,
}

impl<'a> ClassifiedFields<'a> {
    fn classify<I>(fields_iter: I) -> Self
    where
        I: Iterator<Item = &'a syn::Field> + ExactSizeIterator,
    {
        let mut rs_flag_fields = vec![];
        let mut rs_align_fields = vec![];
        let mut rs_union_fields = vec![];
        let mut rs_non_union_fields = vec![];
        let mut jl_union_field_idxs = vec![];
        let mut jl_non_union_field_idxs = vec![];
        let mut offset = 0;

        'outer: for (idx, field) in fields_iter.enumerate() {
            for attr in &field.attrs {
                match JlrsFieldAttr::parse(attr) {
                    Some(JlrsFieldAttr::BitsUnion) => {
                        rs_union_fields.push(&field.ty);
                        jl_union_field_idxs.push(idx - offset);
                        continue 'outer;
                    }
                    Some(JlrsFieldAttr::BitsUnionAlign) => {
                        rs_align_fields.push(&field.ty);
                        offset += 1;
                        continue 'outer;
                    }
                    Some(JlrsFieldAttr::BitsUnionFlag) => {
                        rs_flag_fields.push(&field.ty);
                        offset += 1;
                        continue 'outer;
                    }
                    _ => (),
                }
            }

            rs_non_union_fields.push(&field.ty);
            jl_non_union_field_idxs.push(idx - offset);
        }

        ClassifiedFields {
            rs_flag_fields,
            rs_align_fields,
            rs_union_fields,
            rs_non_union_fields,
            jl_union_field_idxs,
            jl_non_union_field_idxs,
        }
    }
}

pub struct JlrsTypeAttrs {
    julia_type: Option<String>,
    zst: bool,
}

impl JlrsTypeAttrs {
    fn parse(ast: &syn::DeriveInput) -> Self {
        let mut julia_type: Option<String> = None;
        let mut zst = false;
        for attr in &ast.attrs {
            if attr.path().is_ident("jlrs") {
                let nested = attr
                    .parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)
                    .unwrap();
                for meta in nested {
                    match meta {
                        Meta::Path(path) if path.is_ident("zero_sized_type") => {
                            zst = true;
                        }
                        Meta::NameValue(mnv) if mnv.path.is_ident("julia_type") => {
                            if let Expr::Lit(lit) = mnv.value {
                                if let Lit::Str(s) = lit.lit {
                                    julia_type = Some(s.value());
                                }
                            }
                        }
                        _ => todo!(),
                    }
                }
            }
        }

        JlrsTypeAttrs { julia_type, zst }
    }
}

enum JlrsFieldAttr {
    BitsUnionAlign,
    BitsUnion,
    BitsUnionFlag,
}

impl JlrsFieldAttr {
    pub fn parse(attr: &syn::Attribute) -> Option<Self> {
        if attr.path().is_ident("jlrs") {
            let nested = attr
                .parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)
                .unwrap();
            for meta in nested {
                let Meta::Path(path) = meta else {
                    return None
                };

                if path.is_ident("bits_union") {
                    return Some(JlrsFieldAttr::BitsUnion);
                } else if path.is_ident("bits_union_align") {
                    return Some(JlrsFieldAttr::BitsUnionAlign);
                } else if path.is_ident("bits_union_flag") {
                    return Some(JlrsFieldAttr::BitsUnionFlag);
                }
            }
        }

        None
    }
}

pub fn impl_into_julia(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;
    if !is_repr_c(ast) {
        panic!("IntoJulia can only be derived for types with the attribute #[repr(C)].");
    }

    let mut attrs = JlrsTypeAttrs::parse(ast);
    let jl_type = attrs.julia_type
        .take()
        .expect("IntoJulia can only be derived if the corresponding Julia type is set with #[julia_type = \"Main.MyModule.Submodule.StructType\"]");

    let mut type_it = jl_type.split('.');
    let func: syn::Expr = match type_it.next() {
        Some("Main") => syn::parse_quote! {
            {
                ::jlrs::data::managed::module::Module::main(&global)
            }
        },
        Some("Base") => syn::parse_quote! {
            {
                ::jlrs::data::managed::module::Module::base(&global)
            }
        },
        Some("Core") => syn::parse_quote! {
            {
                ::jlrs::data::managed::module::Module::corr(&global)
            }
        },
        Some(pkg) => syn::parse_quote! {
            {
                let module = ::jlrs::data::managed::module::Module::package_root_module(&global, #pkg);
                match module {
                    Some(module) => module,
                    _ => panic!("Package {} cannot be found", #pkg)
                }
            }
        },
        _ => panic!("IntoJulia can only be derived if the first module of \"julia_type\" is either \"Main\", \"Base\" or \"Core\", or a package name."),
    };

    let mut modules = type_it.collect::<Vec<_>>();
    let ty = modules.pop().expect("IntoJulia can only be derived if the corresponding Julia type is set with #[jlrs(julia_type = \"Main.MyModule.Submodule.StructType\")]");
    let modules_it = modules.iter();
    let modules_it_b = modules_it.clone();

    let into_julia_fn = impl_into_julia_fn(&attrs);

    let into_julia_impl = quote! {
        unsafe impl ::jlrs::convert::into_julia::IntoJulia for #name {
            fn julia_type<'scope, T>(target: T) -> ::jlrs::data::managed::datatype::DataTypeData<'scope, T>
            where
                T: ::jlrs::memory::target::Target<'scope>,
            {
                unsafe {
                    let global = target.unrooted();
                    #func
                        #(
                            .submodule(&global, #modules_it)
                            .expect(&format!("Submodule {} cannot be found", #modules_it_b))
                            .as_managed()
                        )*
                        .global(&global, #ty)
                        .expect(&format!("Type {} cannot be found in module", #ty))
                        .as_value()
                        .cast::<::jlrs::data::managed::datatype::DataType>()
                        .expect("Type is not a DataType")
                        .root(target)
                }
            }

            #into_julia_fn
        }
    };

    into_julia_impl.into()
}

pub fn impl_into_julia_fn(attrs: &JlrsTypeAttrs) -> Option<TS2> {
    if attrs.zst {
        Some(quote! {
            fn into_julia<'target, T>(self, target: T) -> ::jlrs::data::managed::value::ValueData<'target, 'static, T>
            where
                T: ::jlrs::memory::target::Target<'target>,
            {
                let ty = Self::julia_type(&target);
                unsafe {
                    ty.as_managed()
                        .instance()
                        .expect("Instance is undefined")
                        .as_value()
                        .root(target)
                }
            }
        })
    } else {
        None
    }
}

pub fn impl_unbox(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;
    if !is_repr_c(ast) {
        panic!("Unbox can only be derived for types with the attribute #[repr(C)].");
    }

    let generics = &ast.generics;
    let where_clause = match ast.generics.where_clause.as_ref() {
        Some(wc) => {
            let mut wc = wc.clone();
            for generic in generics.type_params() {
                let clause: WherePredicate = syn::parse_quote! {
                    #generic: Clone
                };
                wc.predicates.push(clause)
            }
            wc
        }
        None => {
            let mut predicates = Punctuated::<_, Comma>::new();
            for generic in generics.type_params() {
                let clause: WherePredicate = syn::parse_quote! {
                    #generic: Clone
                };
                predicates.push(clause)
            }

            syn::parse_quote! {
                where #predicates
            }
        }
    };

    let unbox_impl = quote! {
        unsafe impl #generics ::jlrs::convert::unbox::Unbox for #name #generics #where_clause {
            type Output = Self;
        }
    };

    unbox_impl.into()
}

pub fn impl_typecheck(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;
    if !is_repr_c(ast) {
        panic!("Typecheck can only be derived for types with the attribute #[repr(C)].");
    }

    let generics = &ast.generics;
    let where_clause = match ast.generics.where_clause.as_ref() {
        Some(wc) => {
            let mut wc = wc.clone();
            let clause: WherePredicate = syn::parse_quote! {
                Self: ::jlrs::data::layout::valid_layout::ValidLayout
            };
            wc.predicates.push(clause);
            for generic in generics.type_params() {
                let clause: WherePredicate = syn::parse_quote! {
                    #generic: ::jlrs::data::layout::valid_layout::ValidLayout
                };
                wc.predicates.push(clause)
            }
            wc
        }
        None => {
            let mut predicates = Punctuated::<_, Comma>::new();
            let clause: WherePredicate = syn::parse_quote! {
                Self: ::jlrs::data::layout::valid_layout::ValidLayout
            };
            predicates.push(clause);

            for generic in generics.type_params() {
                let clause: WherePredicate = syn::parse_quote! {
                    #generic: ::jlrs::data::layout::valid_layout::ValidLayout
                };
                predicates.push(clause)
            }

            syn::parse_quote! {
                where #predicates
            }
        }
    };

    let typecheck_impl = quote! {
        unsafe impl #generics ::jlrs::data::types::typecheck::Typecheck for #name #generics #where_clause {
            fn typecheck(dt: ::jlrs::data::managed::datatype::DataType) -> bool {
                <Self as ::jlrs::data::layout::valid_layout::ValidLayout>::valid_layout(dt.as_value())
            }
        }
    };

    typecheck_impl.into()
}

pub fn impl_construct_type(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;
    let mut attrs = JlrsTypeAttrs::parse(ast);
    let jl_type = attrs.julia_type
        .take()
        .expect("ConstructType can only be derived if the corresponding Julia type is set with #[julia_type = \"Main.MyModule.Submodule.StructType\"]");

    let mut type_it = jl_type.split('.');
    let func: syn::Expr = match type_it.next() {
        Some("Main") => syn::parse_quote! {
            {
                ::jlrs::data::managed::module::Module::main(&frame)
            }
        },
        Some("Base") => syn::parse_quote! {
            {
                ::jlrs::data::managed::module::Module::base(&frame)
            }
        },
        Some("Core") => syn::parse_quote! {
            {
                ::jlrs::data::managed::module::Module::corr(&frame)
            }
        },
        Some(pkg) => syn::parse_quote! {
            {
                let module = ::jlrs::data::managed::module::Module::package_root_module(&frame, #pkg);
                match module {
                    Some(module) => module,
                    _ => panic!("Package {} cannot be found", #pkg)
                }
            }
        },
        _ => panic!("ConstructType can only be derived if the first module of \"julia_type\" is either \"Main\", \"Base\" or \"Core\", or a package name."),
    };

    let mut modules = type_it.collect::<Vec<_>>();
    let ty = modules.pop().expect("ConstructType can only be derived if the corresponding Julia type is set with #[jlrs(julia_type = \"Main.MyModule.Submodule.StructType\")]");
    let modules_it = modules.iter();
    let modules_it_b = modules_it.clone();
    let modules_it_c = modules_it.clone();
    let modules_it_d = modules_it.clone();

    let generics = &ast.generics;
    let wc = match ast.generics.where_clause.as_ref() {
        Some(wc) => {
            let mut wc = wc.clone();
            for generic in generics.type_params() {
                let clause: WherePredicate = syn::parse_quote! {
                    #generic: ::jlrs::data::types::construct_type::ConstructType
                };
                wc.predicates.push(clause)
            }
            wc
        }
        None => {
            let mut predicates = Punctuated::<_, Comma>::new();
            for generic in generics.type_params() {
                let clause: WherePredicate = syn::parse_quote! {
                    #generic: ::jlrs::data::types::construct_type::ConstructType
                };
                predicates.push(clause)
            }

            syn::parse_quote! {
                where #predicates
            }
        }
    };

    let param_names = ast
        .generics
        .type_params()
        .map(|p| &p.ident)
        .collect::<Vec<_>>();
    let n_generics = param_names.len();
    let param_names = param_names.iter();
    let nth_generic = 0..n_generics;

    let construct_type_impl = quote! {
        unsafe impl #generics ::jlrs::data::types::construct_type::ConstructType for #name #generics #wc {
            fn construct_type<'target, Tgt>(
                target: ::jlrs::memory::target::ExtendedTarget<'target, '_, '_, Tgt>,
            ) -> ::jlrs::data::managed::value::ValueData<'target, 'static, Tgt>
            where
                Tgt: ::jlrs::memory::target::Target<'target>,
            {
                let (target, frame) = target.split();

                frame.scope(|mut frame| {
                    let base_type = unsafe {
                        #func
                        #(
                            .submodule(&frame, #modules_it)
                            .expect(&format!("Submodule {} cannot be found", #modules_it_b))
                            .as_managed()
                        )*
                        .global(&frame, #ty)
                        .expect(&format!("Type {} cannot be found in module", #ty))
                        .as_value()
                    };

                    if base_type.is::<::jlrs::data::managed::datatype::DataType>() {
                        return Ok(base_type.root(target))
                    }

                    let mut types: [Option<::jlrs::data::managed::value::Value>; #n_generics] = [None; #n_generics];
                    #(
                        types[#nth_generic] = Some(<#param_names as ::jlrs::data::types::construct_type::ConstructType>::construct_type(frame.as_extended_target()));
                    )*
                    unsafe {
                        let types = std::mem::transmute::<&[Option<::jlrs::data::managed::value::Value>; #n_generics], &[::jlrs::data::managed::value::Value; #n_generics]>(&types);
                        let applied = base_type
                            .apply_type_unchecked(&mut frame, types);
                        Ok(::jlrs::data::managed::union_all::UnionAll::rewrap(
                            target.into_extended_target(&mut frame),
                            applied.cast_unchecked::<::jlrs::data::managed::datatype::DataType>(),
                        ))
                    }
                }).unwrap()
            }

            fn base_type<'target, Tgt>(
                target: &Tgt
            ) -> Option<::jlrs::data::managed::value::Value<'target, 'static>>
            where
                Tgt: ::jlrs::memory::target::Target<'target>,
            {
                let frame = target;
                let base_type = unsafe {
                    #func
                    #(
                        .submodule(target, #modules_it_c)
                        .expect(&format!("Submodule {} cannot be found", #modules_it_d))
                        .as_managed()
                    )*
                    .global(target, #ty)
                    .expect(&format!("Type {} cannot be found in module", #ty))
                    .as_value()
                };

                Some(base_type)
            }
        }
    };

    construct_type_impl.into()
}

/*
pub fn impl_construct_type(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;
    let mut attrs = JlrsTypeAttrs::parse(ast);
    let jl_type = attrs.julia_type
        .take()
        .expect("ConstructType can only be derived if the corresponding Julia type is set with #[julia_type = \"Main.MyModule.Submodule.StructType\"]");

    let mut type_it = jl_type.split('.');
    let func: syn::Expr = match type_it.next() {
        Some("Main") => syn::parse_quote! {
            {
                ::jlrs::data::managed::module::Module::main(target)
            }
        },
        Some("Base") => syn::parse_quote! {
            {
                ::jlrs::data::managed::module::Module::base(target)
            }
        },
        Some("Core") => syn::parse_quote! {
            {
                ::jlrs::data::managed::module::Module::corr(target)
            }
        },
        Some(pkg) => syn::parse_quote! {
            {
                let module = ::jlrs::data::managed::module::Module::package_root_module(target, #pkg);
                match module {
                    Some(module) => module,
                    _ => panic!("Package {} cannot be found", #pkg)
                }
            }
        },
        _ => panic!("ConstructType can only be derived if the first module of \"julia_type\" is either \"Main\", \"Base\" or \"Core\", or a package name."),
    };

    let mut modules = type_it.collect::<Vec<_>>();
    let ty = modules.pop().expect("ConstructType can only be derived if the corresponding Julia type is set with #[jlrs(julia_type = \"Main.MyModule.Submodule.StructType\")]");
    let modules_it = modules.iter();
    let modules_it_b = modules_it.clone();

    let generics = &ast.generics;
    let wc = match ast.generics.where_clause.as_ref() {
        Some(wc) => {
            let mut wc = wc.clone();
            for generic in generics.type_params() {
                let clause: WherePredicate = syn::parse_quote! {
                    #generic: ::jlrs::convert::construct_type::ConstructType
                };
                wc.predicates.push(clause)
            }
            wc
        }
        None => {
            let mut predicates = Punctuated::<_, Comma>::new();
            for generic in generics.type_params() {
                let clause: WherePredicate = syn::parse_quote! {
                    #generic: ::jlrs::convert::construct_type::ConstructType
                };
                predicates.push(clause)
            }

            syn::parse_quote! {
                where #predicates
            }
        }
    };

    let param_names = ast
        .generics
        .type_params()
        .map(|p| &p.ident)
        .collect::<Vec<_>>();
    let n_generics = param_names.len();
    let param_names = param_names.iter();
    let nth_generic = 0..n_generics;

    let construct_type_impl = quote! {
        unsafe impl #generics ::jlrs::convert::construct_type::ConstructType for #name #generics #wc {
            fn base_type<'target, TARGET>(target: &TARGET) -> ::jlrs::data::managed::value::Value<'target, 'static>
            where
                TARGET: ::jlrs::memory::target::Target<'target>,
            {
                unsafe {
                        #func
                        #(
                            .submodule(target, #modules_it)
                            .expect(&format!("Submodule {} cannot be found", #modules_it_b))
                            .as_managed()
                        )*
                        .global(target, #ty)
                        .expect(&format!("Type {} cannot be found in module", #ty))
                        .as_value()
                }
            }

            fn construct_type<'target, 'current, 'borrow, TARGET>(
                target: ::jlrs::memory::target::ExtendedTarget<'target, '_, '_, TARGET>,
            ) -> ::jlrs::data::managed::datatype::DataTypeData<'target, TARGET>
            where
                TARGET: ::jlrs::memory::target::Target<'target>,
            {
                let (target, frame) = target.split();

                frame.scope(|mut frame| {
                    let base_type = Self::base_type(&frame);
                    if let Ok(ty) = base_type.cast::<::jlrs::data::managed::datatype::DataType>() {
                        Ok(ty.root(target))
                    } else if let Ok(ua) = base_type.cast::<::jlrs::data::managed::union_all::UnionAll>() {
                        let mut types: [Option<::jlrs::data::managed::value::Value>; #n_generics] = [None; #n_generics];
                        #(
                            types[#nth_generic] = Some(<#param_names as ::jlrs::convert::construct_type::ConstructType>::construct_type(frame.as_extended_target()).as_value());
                        )*
                        unsafe {
                            let types = std::mem::transmute::<&[Option<::jlrs::data::managed::value::Value>; #n_generics], &[::jlrs::data::managed::value::Value; #n_generics]>(&types);
                            let applied = ua
                                .apply_types_unchecked(&target, types)
                                .as_value()
                                .cast::<::jlrs::data::managed::datatype::DataType>()
                                .expect("UnionAll is not a DataType after applying generic types")
                                .root(target);

                            Ok(applied)
                        }
                    } else {
                        panic!("Type is neither a DataType or UnionAll")
                    }
                }).unwrap()
            }
        }
    };

    construct_type_impl.into()
}
*/

pub fn impl_valid_layout(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;
    if !is_repr_c(ast) {
        panic!("ValidLayout can only be derived for types with the attribute #[repr(C)].");
    }

    let generics = &ast.generics;
    let where_clause = match ast.generics.where_clause.as_ref() {
        Some(wc) => {
            let mut wc = wc.clone();
            for generic in generics.type_params() {
                let clause: WherePredicate = syn::parse_quote! {
                    #generic: ::jlrs::data::layout::valid_layout::ValidField
                };
                wc.predicates.push(clause)
            }
            wc
        }
        None => {
            let mut predicates = Punctuated::<_, Comma>::new();
            for generic in generics.type_params() {
                let clause: WherePredicate = syn::parse_quote! {
                    #generic: ::jlrs::data::layout::valid_layout::ValidField
                };
                predicates.push(clause)
            }

            syn::parse_quote! {
                where #predicates
            }
        }
    };

    let fields = match &ast.data {
        syn::Data::Struct(s) => &s.fields,
        _ => panic!("ValidLayout can only be derived for structs."),
    };

    let classified_fields = match fields {
        syn::Fields::Named(n) => ClassifiedFields::classify(n.named.iter()),
        syn::Fields::Unit => ClassifiedFields::default(),
        _ => panic!("ValidLayout cannot be derived for tuple structs."),
    };

    let rs_flag_fields = classified_fields.rs_flag_fields.iter();
    let rs_align_fields = classified_fields.rs_align_fields.iter();
    let rs_union_fields = classified_fields.rs_union_fields.iter();
    let rs_non_union_fields = classified_fields.rs_non_union_fields.iter();
    let jl_union_field_idxs = classified_fields.jl_union_field_idxs.iter();
    let jl_non_union_field_idxs = classified_fields.jl_non_union_field_idxs.iter();

    let n_fields = classified_fields.jl_union_field_idxs.len()
        + classified_fields.jl_non_union_field_idxs.len();

    let valid_layout_impl = quote! {
        unsafe impl #generics ::jlrs::data::layout::valid_layout::ValidLayout for #name #generics #where_clause {
            fn valid_layout(v: ::jlrs::data::managed::value::Value) -> bool {
                unsafe {
                    if let Ok(dt) = v.cast::<::jlrs::data::managed::datatype::DataType>() {
                        if dt.n_fields().unwrap() as usize != #n_fields {
                            return false;
                        }

                        let global = v.unrooted_target();
                        let field_types = dt.field_types(global);
                        let field_types_svec = field_types.as_managed();
                        let field_types_data = field_types_svec.data();
                        let field_types = field_types_data.as_slice();

                        #(
                            if !<#rs_non_union_fields as ::jlrs::data::layout::valid_layout::ValidField>::valid_field(field_types[#jl_non_union_field_idxs].unwrap().as_managed()) {
                                return false;
                            }
                        )*

                        #(
                            if let Ok(u) = field_types[#jl_union_field_idxs].unwrap().as_managed().cast::<::jlrs::data::managed::union::Union>() {
                                if !::jlrs::data::layout::union::correct_layout_for::<#rs_align_fields, #rs_union_fields, #rs_flag_fields>(u) {
                                    return false
                                }
                            } else {
                                return false
                            }
                        )*


                        return true;
                    }
                }

                false
            }

            const IS_REF: bool = false;
        }
    };

    valid_layout_impl.into()
}

pub fn impl_valid_field(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;
    if !is_repr_c(ast) {
        panic!("ValidLayout can only be derived for types with the attribute #[repr(C)].");
    }

    let generics = &ast.generics;
    let where_clause = match ast.generics.where_clause.as_ref() {
        Some(wc) => {
            let mut wc = wc.clone();
            for generic in generics.type_params() {
                let clause: WherePredicate = syn::parse_quote! {
                    #generic: ::jlrs::data::layout::valid_layout::ValidField
                };
                wc.predicates.push(clause)
            }
            wc
        }
        None => {
            let mut predicates = Punctuated::<_, Comma>::new();
            for generic in generics.type_params() {
                let clause: WherePredicate = syn::parse_quote! {
                    #generic: ::jlrs::data::layout::valid_layout::ValidField
                };
                predicates.push(clause)
            }

            syn::parse_quote! {
                where #predicates
            }
        }
    };

    let valid_field_impl = quote! {
        unsafe impl #generics ::jlrs::data::layout::valid_layout::ValidField for #name #generics #where_clause {
            fn valid_field(v: ::jlrs::data::managed::value::Value) -> bool {
                <Self as ::jlrs::data::layout::valid_layout::ValidLayout>::valid_layout(v)
            }
        }
    };

    valid_field_impl.into()
}

pub fn impl_ccall_arg(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;
    if !is_repr_c(ast) {
        panic!("ValidLayout can only be derived for types with the attribute #[repr(C)].");
    }

    let generics = &ast.generics;
    let wc = match ast.generics.where_clause.as_ref() {
        Some(wc) => {
            let mut wc = wc.clone();
            for generic in generics.type_params() {
                let clause: WherePredicate = syn::parse_quote! {
                    #generic: ::jlrs::data::types::construct_type::ConstructType
                };
                wc.predicates.push(clause)
            }
            wc
        }
        None => {
            let mut predicates = Punctuated::<_, Comma>::new();
            for generic in generics.type_params() {
                let clause: WherePredicate = syn::parse_quote! {
                    #generic: ::jlrs::data::types::construct_type::ConstructType
                };
                predicates.push(clause)
            }

            syn::parse_quote! {
                where #predicates
            }
        }
    };

    let ccall_arg_impl = quote! {
        unsafe impl #generics ::jlrs::convert::ccall_types::CCallArg for #name #generics #wc {
            type CCallArgType = Self;
            type FunctionArgType = Self;
        }
    };

    ccall_arg_impl.into()
}

pub fn impl_ccall_return(ast: &syn::DeriveInput) -> TokenStream {
    let name = &ast.ident;
    if !is_repr_c(ast) {
        panic!("ValidLayout can only be derived for types with the attribute #[repr(C)].");
    }

    let generics = &ast.generics;
    let wc = match ast.generics.where_clause.as_ref() {
        Some(wc) => {
            let mut wc = wc.clone();
            for generic in generics.type_params() {
                let clause: WherePredicate = syn::parse_quote! {
                    #generic: ::jlrs::data::types::construct_type::ConstructType
                };
                wc.predicates.push(clause)
            }
            wc
        }
        None => {
            let mut predicates = Punctuated::<_, Comma>::new();
            for generic in generics.type_params() {
                let clause: WherePredicate = syn::parse_quote! {
                    #generic: ::jlrs::data::types::construct_type::ConstructType
                };
                predicates.push(clause)
            }

            syn::parse_quote! {
                where #predicates
            }
        }
    };

    let ccall_arg_impl = quote! {
        unsafe impl #generics ::jlrs::convert::ccall_types::CCallReturn for #name #generics #wc {
            type CCallReturnType = Self;
            type FunctionReturnType = Self;
        }
    };

    ccall_arg_impl.into()
}

fn is_repr_c(ast: &syn::DeriveInput) -> bool {
    for attr in &ast.attrs {
        if attr.path().is_ident("repr") {
            let p: Result<syn::Path, _> = attr.parse_args();
            if let Ok(p) = p {
                if p.is_ident("C") {
                    return true;
                }
            }
        }
    }

    false
}