llvm-native-core 0.1.11

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
//! clang_interop — Language interoperability support for the Clang frontend.
//!
//! Provides recognition and code generation support for cross-language
//! interop between C, C++, Objective-C, CUDA, OpenCL, SYCL, Rust, and Python.
//!
//! Clean-room design from language specifications, FFI documentation,
//! and published ABI specifications.

use std::collections::HashMap;
use std::fmt;

// ═══════════════════════════════════════════════════════════════════════════════
// C/C++ Interop
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct CExternFunction {
    pub name: String,
    pub return_type: String,
    pub params: Vec<(String, String)>,
    pub is_variadic: bool,
}

impl CExternFunction {
    pub fn new(name: &str, return_type: &str) -> Self {
        Self {
            name: name.to_string(),
            return_type: return_type.to_string(),
            params: Vec::new(),
            is_variadic: false,
        }
    }

    pub fn add_param(&mut self, name: &str, ty: &str) {
        self.params.push((name.to_string(), ty.to_string()));
    }

    /// Generate the extern "C" declaration.
    pub fn to_extern_c(&self) -> String {
        let params_str: Vec<String> = self
            .params
            .iter()
            .map(|(n, t)| format!("{} {}", t, n))
            .collect();
        let variadic = if self.is_variadic { ", ..." } else { "" };
        format!(
            "extern \"C\" {} {}({}{});",
            self.return_type,
            self.name,
            params_str.join(", "),
            variadic
        )
    }

    /// Generate the C header prototype.
    pub fn to_c_header(&self) -> String {
        let params_str: Vec<String> = self
            .params
            .iter()
            .map(|(n, t)| format!("{} {}", t, n))
            .collect();
        let variadic = if self.is_variadic { ", ..." } else { "" };
        format!(
            "{} {}({}{});",
            self.return_type,
            self.name,
            params_str.join(", "),
            variadic
        )
    }

    /// Generate LLVM IR declare for the function.
    pub fn to_llvm_declare(&self) -> String {
        let ret_ty = ctype_to_llvm(&self.return_type);
        let param_tys: Vec<String> = self.params.iter().map(|(_, t)| ctype_to_llvm(t)).collect();
        let variadic = if self.is_variadic { ", ..." } else { "" };
        format!(
            "declare {} @{}({}{})",
            ret_ty,
            self.name,
            param_tys.join(", "),
            variadic
        )
    }
}

/// Map C type name to LLVM type.
pub fn ctype_to_llvm(ct: &str) -> String {
    match ct {
        "void" => "void".into(),
        "char" | "signed char" | "unsigned char" => "i8".into(),
        "short" | "unsigned short" => "i16".into(),
        "int" | "unsigned int" => "i32".into(),
        "long" | "unsigned long" | "long long" | "unsigned long long" => "i64".into(),
        "float" => "float".into(),
        "double" => "double".into(),
        "long double" => "fp128".into(),
        "bool" | "_Bool" => "i1".into(),
        s if s.ends_with('*') => "ptr".into(),
        _ => "ptr".into(),
    }
}

#[derive(Debug, Clone)]
pub struct CXXExternFunction {
    pub function: CExternFunction,
    pub mangled_name: String,
    pub exception_spec: ExceptionSpec,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExceptionSpec {
    None,
    Noexcept,
    Throw,
    ThrowTypes(Vec<String>),
}

impl CXXExternFunction {
    pub fn new(name: &str, return_type: &str) -> Self {
        Self {
            function: CExternFunction::new(name, return_type),
            mangled_name: String::new(),
            exception_spec: ExceptionSpec::None,
        }
    }

    pub fn extern_c_declaration(&self) -> String {
        format!("extern \"C\" {{ {} }}", self.function.to_c_header())
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Objective-C Interop
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct ObjCInterface {
    pub name: String,
    pub superclass: Option<String>,
    pub instance_variables: Vec<(String, String)>,
    pub properties: Vec<ObjCProperty>,
    pub methods: Vec<ObjCMethod>,
    pub protocols: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct ObjCProperty {
    pub name: String,
    pub ty: String,
    pub attributes: Vec<ObjCPropertyAttr>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ObjCPropertyAttr {
    Nonatomic,
    Atomic,
    Strong,
    Weak,
    Copy,
    Assign,
    Readonly,
    Readwrite,
    Getter(String),
    Setter(String),
}

#[derive(Debug, Clone)]
pub struct ObjCMethod {
    pub is_class_method: bool,
    pub selector: String,
    pub return_type: String,
    pub params: Vec<(String, String, String)>, // (keyword, name, type)
}

impl ObjCInterface {
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            superclass: None,
            instance_variables: Vec::new(),
            properties: Vec::new(),
            methods: Vec::new(),
            protocols: Vec::new(),
        }
    }

    pub fn to_interface_declaration(&self) -> String {
        let super_part = if let Some(ref sup) = self.superclass {
            format!(" : {}", sup)
        } else {
            String::new()
        };
        let proto_part = if self.protocols.is_empty() {
            String::new()
        } else {
            format!(" <{}>", self.protocols.join(", "))
        };
        format!("@interface {}{}{}\n@end", self.name, super_part, proto_part)
    }

    pub fn add_message_send(&self, target: &str, method: &ObjCMethod) -> String {
        if method.is_class_method {
            format!("[{} {}]", target, method.selector)
        } else {
            format!("[{} {}]", target, method.selector)
        }
    }
}

#[derive(Debug, Clone)]
pub struct ObjCMessageSend {
    pub target: String,
    pub selector: String,
    pub arguments: Vec<String>,
}

impl ObjCMessageSend {
    pub fn new(target: &str, selector: &str) -> Self {
        Self {
            target: target.to_string(),
            selector: selector.to_string(),
            arguments: Vec::new(),
        }
    }

    pub fn to_objc(&self) -> String {
        if self.arguments.is_empty() {
            format!("[{} {}]", self.target, self.selector)
        } else {
            let parts: Vec<&str> = self.selector.split(':').collect();
            let mut out = format!("[{} ", self.target);
            for (i, arg) in self.arguments.iter().enumerate() {
                if i < parts.len() {
                    out.push_str(&format!("{}:{} ", parts[i], arg));
                }
            }
            out.push(']');
            out
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// CUDA Interop
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CudaFunctionKind {
    Global,
    Device,
    Host,
    HostDevice,
}

impl fmt::Display for CudaFunctionKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Global => write!(f, "__global__"),
            Self::Device => write!(f, "__device__"),
            Self::Host => write!(f, "__host__"),
            Self::HostDevice => write!(f, "__host__ __device__"),
        }
    }
}

#[derive(Debug, Clone)]
pub struct CudaKernel {
    pub name: String,
    pub kind: CudaFunctionKind,
    pub params: Vec<(String, String)>,
    pub grid_dim: (u32, u32, u32),
    pub block_dim: (u32, u32, u32),
    pub shared_memory_bytes: usize,
}

impl CudaKernel {
    pub fn new(name: &str, kind: CudaFunctionKind) -> Self {
        Self {
            name: name.to_string(),
            kind,
            params: Vec::new(),
            grid_dim: (1, 1, 1),
            block_dim: (1, 1, 1),
            shared_memory_bytes: 0,
        }
    }

    /// Generate the <<<>>> launch syntax.
    pub fn to_launch_syntax(&self) -> String {
        format!(
            "{}<<<dim3({},{},{}), dim3({},{},{}), {}>>>",
            self.name,
            self.grid_dim.0,
            self.grid_dim.1,
            self.grid_dim.2,
            self.block_dim.0,
            self.block_dim.1,
            self.block_dim.2,
            self.shared_memory_bytes
        )
    }

    /// Generate the CUDA kernel declaration.
    pub fn to_declaration(&self) -> String {
        let params_str: Vec<String> = self
            .params
            .iter()
            .map(|(n, t)| format!("{} {}", t, n))
            .collect();
        format!(
            "{} void {}({})",
            self.kind,
            self.name,
            params_str.join(", ")
        )
    }

    /// Generate the host-side launch call using the CUDA runtime API.
    pub fn to_runtime_launch(&self) -> String {
        format!(
            "cudaLaunchKernel((void*){}, dim3({},{},{}), dim3({},{},{}), \
             nullptr, {}, nullptr)",
            self.name,
            self.grid_dim.0,
            self.grid_dim.1,
            self.grid_dim.2,
            self.block_dim.0,
            self.block_dim.1,
            self.block_dim.2,
            self.shared_memory_bytes
        )
    }
}

#[derive(Debug, Clone)]
pub struct CudaMemory {
    pub name: String,
    pub space: CudaMemorySpace,
    pub size: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CudaMemorySpace {
    Global,
    Shared,
    Constant,
    Local,
    Texture,
    Surface,
    Managed,
    Unified,
}

impl CudaMemorySpace {
    pub fn qualifier(&self) -> &'static str {
        match self {
            Self::Global => "__device__",
            Self::Shared => "__shared__",
            Self::Constant => "__constant__",
            Self::Local | Self::Texture | Self::Surface => "__device__",
            Self::Managed => "__managed__",
            Self::Unified => "",
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// OpenCL Interop
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OpenCLAddressSpace {
    Global,
    Local,
    Constant,
    Private,
    Generic,
}

impl OpenCLAddressSpace {
    pub fn qualifier(&self) -> &'static str {
        match self {
            Self::Global => "__global",
            Self::Local => "__local",
            Self::Constant => "__constant",
            Self::Private => "__private",
            Self::Generic => "__generic",
        }
    }
}

#[derive(Debug, Clone)]
pub struct OpenCLKernel {
    pub name: String,
    pub params: Vec<(String, String, OpenCLAddressSpace)>,
    pub work_group_size_hint: Option<(usize, usize, usize)>,
    pub reqd_work_group_size: Option<(usize, usize, usize)>,
}

impl OpenCLKernel {
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            params: Vec::new(),
            work_group_size_hint: None,
            reqd_work_group_size: None,
        }
    }

    pub fn to_declaration(&self) -> String {
        let params_str: Vec<String> = self
            .params
            .iter()
            .map(|(n, t, space)| format!("{} {} {}", space.qualifier(), t, n))
            .collect();
        let attrs = if let Some((x, y, z)) = self.reqd_work_group_size {
            format!(
                "__attribute__((reqd_work_group_size({}, {}, {})))\n",
                x, y, z
            )
        } else {
            String::new()
        };
        format!(
            "{}__kernel void {}({})",
            attrs,
            self.name,
            params_str.join(", ")
        )
    }

    /// Generate the host-side clEnqueueNDRangeKernel call.
    pub fn to_enqueue_call(
        &self,
        queue: &str,
        global_size: (usize, usize, usize),
        local_size: Option<(usize, usize, usize)>,
    ) -> String {
        let local = if let Some((x, y, z)) = local_size {
            format!(", size_t[3]{{{}, {}, {}}}", x, y, z)
        } else {
            ", nullptr".to_string()
        };
        format!(
            "clEnqueueNDRangeKernel({}, kernel_{}, 3, nullptr, \
             size_t[3]{{{}, {}, {}}}{}, 0, nullptr, nullptr)",
            queue, self.name, global_size.0, global_size.1, global_size.2, local
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// SYCL Interop
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct SyclQueue {
    pub name: String,
    pub device_selector: SyclDeviceSelector,
}

#[derive(Debug, Clone)]
pub enum SyclDeviceSelector {
    DefaultSelector,
    GpuSelector,
    CpuSelector,
    AcceleratorSelector,
    Custom(String),
}

impl SyclQueue {
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            device_selector: SyclDeviceSelector::DefaultSelector,
        }
    }

    pub fn to_declaration(&self) -> String {
        let selector = match &self.device_selector {
            SyclDeviceSelector::DefaultSelector => "default_selector",
            SyclDeviceSelector::GpuSelector => "gpu_selector",
            SyclDeviceSelector::CpuSelector => "cpu_selector",
            SyclDeviceSelector::AcceleratorSelector => "accelerator_selector",
            SyclDeviceSelector::Custom(s) => s,
        };
        format!("sycl::queue {} ({})", self.name, selector)
    }
}

#[derive(Debug, Clone)]
pub struct SyclBuffer {
    pub name: String,
    pub element_type: String,
    pub size: usize,
    pub access_mode: SyclAccessMode,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SyclAccessMode {
    Read,
    Write,
    ReadWrite,
    DiscardWrite,
    DiscardReadWrite,
}

impl SyclBuffer {
    pub fn new(name: &str, element_type: &str, size: usize) -> Self {
        Self {
            name: name.to_string(),
            element_type: element_type.to_string(),
            size,
            access_mode: SyclAccessMode::ReadWrite,
        }
    }

    pub fn to_declaration(&self) -> String {
        format!(
            "sycl::buffer<{}, 1> {}(sycl::range<1>({}))",
            self.element_type, self.name, self.size
        )
    }
}

#[derive(Debug, Clone)]
pub struct SyclParallelFor {
    pub kernel_name: String,
    pub range: usize,
    pub body: String,
}

impl SyclParallelFor {
    pub fn new(kernel_name: &str, range: usize, body: &str) -> Self {
        Self {
            kernel_name: kernel_name.to_string(),
            range,
            body: body.to_string(),
        }
    }

    pub fn to_code(&self, queue: &str) -> String {
        format!(
            "{}.submit([&](sycl::handler& cgh) {{\n\
               cgh.parallel_for<class {}>(sycl::range<1>({}), \
               [=](sycl::id<1> i) {{\n{}\n}});\n}});",
            queue, self.kernel_name, self.range, self.body
        )
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Rust Interop (FFI with C/C++)
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct RustFFiBinding {
    pub rust_name: String,
    pub c_name: String,
    pub return_type: String,
    pub params: Vec<(String, String)>,
    pub attributes: Vec<RustFFIAttribute>,
}

#[derive(Debug, Clone)]
pub enum RustFFIAttribute {
    NoMangle,
    ReprC,
    ReprPacked,
    ReprAlign(usize),
    ExternC,
    LinkName(String),
    UnsafeFn,
}

impl RustFFiBinding {
    pub fn new(rust_name: &str, c_name: &str, return_type: &str) -> Self {
        Self {
            rust_name: rust_name.to_string(),
            c_name: c_name.to_string(),
            return_type: return_type.to_string(),
            params: Vec::new(),
            attributes: vec![RustFFIAttribute::NoMangle, RustFFIAttribute::ExternC],
        }
    }

    pub fn to_rust_extern_c(&self) -> String {
        let mut out = String::new();
        for attr in &self.attributes {
            out.push_str(&match attr {
                RustFFIAttribute::NoMangle => "#[no_mangle]\n".into(),
                RustFFIAttribute::ExternC => "extern \"C\" ".into(),
                RustFFIAttribute::ReprC => "#[repr(C)]\n".into(),
                RustFFIAttribute::ReprPacked => "#[repr(packed)]\n".into(),
                RustFFIAttribute::ReprAlign(n) => format!("#[repr(align({}))]\n", n),
                RustFFIAttribute::LinkName(s) => format!("#[link_name = \"{}\"]\n", s),
                RustFFIAttribute::UnsafeFn => "".into(),
            });
        }
        let params_str: Vec<String> = self
            .params
            .iter()
            .map(|(n, t)| format!("{}: {}", n, ctype_to_rust_type(t)))
            .collect();
        out.push_str(&format!(
            "pub fn {}({}) -> {};",
            self.c_name,
            params_str.join(", "),
            ctype_to_rust_type(&self.return_type)
        ));
        out
    }

    /// Generate an extern block for calling C functions from Rust.
    pub fn to_rust_import(&self) -> String {
        let params_str: Vec<String> = self
            .params
            .iter()
            .map(|(n, t)| format!("{}: {}", n, ctype_to_rust_type(t)))
            .collect();
        format!(
            "extern \"C\" {{\n    pub fn {}({}) -> {};\n}}",
            self.c_name,
            params_str.join(", "),
            ctype_to_rust_type(&self.return_type)
        )
    }
}

/// Map C types to Rust types for FFI.
pub fn ctype_to_rust_type(ct: &str) -> &'static str {
    match ct {
        "void" => "()",
        "char" => "std::os::raw::c_char",
        "signed char" => "i8",
        "unsigned char" => "u8",
        "short" => "i16",
        "unsigned short" => "u16",
        "int" => "i32",
        "unsigned int" => "u32",
        "long" => "i64",
        "unsigned long" => "u64",
        "long long" => "i64",
        "unsigned long long" => "u64",
        "float" => "f32",
        "double" => "f64",
        "bool" | "_Bool" => "bool",
        s if s.ends_with('*') => "*mut std::os::raw::c_void",
        _ => "*mut std::os::raw::c_void",
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Python Interop
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PythonFFIBackend {
    Ctypes,
    Cffi,
    Cppyy,
    Pybind11,
    Cython,
}

impl PythonFFIBackend {
    pub fn description(&self) -> &'static str {
        match self {
            Self::Ctypes => "ctypes — builtin Python FFI module",
            Self::Cffi => "CFFI — C Foreign Function Interface for Python",
            Self::Cppyy => "cppyy — automatic Python-C++ bindings",
            Self::Pybind11 => "pybind11 — seamless C++11/Python binding",
            Self::Cython => "Cython — C extensions for Python",
        }
    }
}

#[derive(Debug, Clone)]
pub struct PythonFFIBinding {
    pub backend: PythonFFIBackend,
    pub module_name: String,
    pub functions: Vec<CExternFunction>,
}

impl PythonFFIBinding {
    pub fn new(backend: PythonFFIBackend, module: &str) -> Self {
        Self {
            backend,
            module_name: module.to_string(),
            functions: Vec::new(),
        }
    }

    pub fn to_ctypes_binding(&self) -> String {
        let mut out = format!(
            "import ctypes\n\n_lib = ctypes.CDLL('lib{}.so')\n\n",
            self.module_name
        );
        for func in &self.functions {
            let ret = ctype_to_python_ctype(&func.return_type);
            let params: Vec<String> = func
                .params
                .iter()
                .map(|(_, t)| ctype_to_python_ctype(t).to_string())
                .collect();
            out.push_str(&format!(
                "_lib.{}.restype = {}\n_lib.{}.argtypes = [{}]\n\n",
                func.name,
                ret,
                func.name,
                params.join(", ")
            ));
        }
        out
    }

    pub fn to_cffi_binding(&self) -> String {
        let mut out = format!("from cffi import FFI\n\nffi = FFI()\n\nffi.cdef(\"\"\"\n");
        for func in &self.functions {
            let params_str: Vec<String> = func
                .params
                .iter()
                .map(|(n, t)| format!("{} {}", t, n))
                .collect();
            out.push_str(&format!(
                "    {} {}({});\n",
                func.return_type,
                func.name,
                params_str.join(", ")
            ));
        }
        out.push_str(&format!(
            "\"\"\")\n\n_lib = ffi.dlopen('lib{}.so')\n",
            self.module_name
        ));
        out
    }

    pub fn to_pybind11_binding(&self) -> String {
        let mut out = format!("#include <pybind11/pybind11.h>\n\nnamespace py = pybind11;\n\n");
        out.push_str(&format!("PYBIND11_MODULE({}, m) {{\n", self.module_name));
        for func in &self.functions {
            let params: Vec<&str> = func.params.iter().map(|(n, _)| n.as_str()).collect();
            let py_params = if params.is_empty() {
                String::new()
            } else {
                format!(", py::arg(\"{}\")", params.join("\"), py::arg(\""))
            };
            out.push_str(&format!(
                "    m.def(\"{}\", &{}{});\n",
                func.name, func.name, py_params
            ));
        }
        out.push_str("}\n");
        out
    }
}

pub fn ctype_to_python_ctype(ct: &str) -> &'static str {
    match ct {
        "void" => "None",
        "char" | "signed char" => "ctypes.c_char",
        "unsigned char" => "ctypes.c_ubyte",
        "short" => "ctypes.c_short",
        "unsigned short" => "ctypes.c_ushort",
        "int" => "ctypes.c_int",
        "unsigned int" => "ctypes.c_uint",
        "long" => "ctypes.c_long",
        "unsigned long" => "ctypes.c_ulong",
        "long long" => "ctypes.c_longlong",
        "unsigned long long" => "ctypes.c_ulonglong",
        "float" => "ctypes.c_float",
        "double" => "ctypes.c_double",
        "bool" | "_Bool" => "ctypes.c_bool",
        s if s.ends_with('*') => "ctypes.c_void_p",
        _ => "ctypes.c_void_p",
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Interop Registry
// ═══════════════════════════════════════════════════════════════════════════════

#[derive(Debug, Clone)]
pub struct InteropRegistry {
    pub languages: Vec<InteropLanguage>,
    pub functions: HashMap<String, CExternFunction>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InteropLanguage {
    C,
    CXX,
    ObjC,
    Cuda,
    OpenCL,
    Sycl,
    Rust(usize),
    Python(usize),
}

impl fmt::Display for InteropLanguage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::C => write!(f, "C"),
            Self::CXX => write!(f, "C++"),
            Self::ObjC => write!(f, "Objective-C"),
            Self::Cuda => write!(f, "CUDA"),
            Self::OpenCL => write!(f, "OpenCL"),
            Self::Sycl => write!(f, "SYCL"),
            Self::Rust(n) => write!(f, "Rust({} bindings)", n),
            Self::Python(n) => write!(f, "Python({} bindings)", n),
        }
    }
}

impl InteropRegistry {
    pub fn new() -> Self {
        Self {
            languages: Vec::new(),
            functions: HashMap::new(),
        }
    }

    pub fn register_function(&mut self, func: CExternFunction) {
        self.functions.insert(func.name.clone(), func);
    }

    pub fn has_function(&self, name: &str) -> bool {
        self.functions.contains_key(name)
    }

    pub fn function_count(&self) -> usize {
        self.functions.len()
    }

    pub fn add_language(&mut self, lang: InteropLanguage) {
        self.languages.push(lang);
    }

    pub fn generate_ffi_header(&self, language: InteropLanguage) -> String {
        match language {
            InteropLanguage::C | InteropLanguage::CXX => self
                .functions
                .values()
                .map(|f| f.to_c_header())
                .collect::<Vec<_>>()
                .join("\n"),
            InteropLanguage::Rust(_) => self
                .functions
                .values()
                .map(|f| RustFFiBinding::new(&f.name, &f.name, &f.return_type).to_rust_import())
                .collect::<Vec<_>>()
                .join("\n"),
            _ => "// unsupported language for header generation".to_string(),
        }
    }
}

impl Default for InteropRegistry {
    fn default() -> Self {
        Self::new()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cextern_function_to_extern_c() {
        let mut func = CExternFunction::new("foo", "int");
        func.add_param("x", "int");
        func.add_param("y", "float");
        let decl = func.to_extern_c();
        assert!(decl.contains("extern \"C\""));
        assert!(decl.contains("foo"));
        assert!(decl.contains("int"));
    }

    #[test]
    fn test_cextern_function_to_c_header() {
        let mut func = CExternFunction::new("bar", "void");
        func.add_param("ptr", "char*");
        let header = func.to_c_header();
        assert_eq!(header, "void bar(char* ptr);");
    }

    #[test]
    fn test_cextern_function_variadic() {
        let mut func = CExternFunction::new("printf", "int");
        func.is_variadic = true;
        func.add_param("fmt", "const char*");
        let decl = func.to_extern_c();
        assert!(decl.contains("..."));
    }

    #[test]
    fn test_cextern_function_to_llvm_declare() {
        let mut func = CExternFunction::new("add", "int");
        func.add_param("a", "int");
        func.add_param("b", "int");
        let ir = func.to_llvm_declare();
        assert!(ir.starts_with("declare"));
        assert!(ir.contains("add"));
    }

    #[test]
    fn test_ctype_to_llvm() {
        assert_eq!(ctype_to_llvm("int"), "i32");
        assert_eq!(ctype_to_llvm("double"), "double");
        assert_eq!(ctype_to_llvm("void"), "void");
        assert_eq!(ctype_to_llvm("unsigned long long"), "i64");
    }

    #[test]
    fn test_objc_interface_to_declaration() {
        let iface = ObjCInterface::new("MyClass");
        let decl = iface.to_interface_declaration();
        assert!(decl.contains("@interface MyClass"));
        assert!(decl.contains("@end"));
    }

    #[test]
    fn test_objc_interface_with_superclass() {
        let mut iface = ObjCInterface::new("MyView");
        iface.superclass = Some("UIView".into());
        let decl = iface.to_interface_declaration();
        assert!(decl.contains("UIView"));
    }

    #[test]
    fn test_objc_message_send() {
        let msg = ObjCMessageSend::new("obj", "doSomething:");
        msg.arguments.push("42".into());
        let code = msg.to_objc();
        assert!(code.contains("[obj "));
        assert!(code.contains("doSomething"));
    }

    #[test]
    fn test_cuda_kernel_launch_syntax() {
        let mut kernel = CudaKernel::new("myKernel", CudaFunctionKind::Global);
        kernel.grid_dim = (16, 16, 1);
        kernel.block_dim = (256, 1, 1);
        let launch = kernel.to_launch_syntax();
        assert!(launch.contains("<<<"));
        assert!(launch.contains(">>>"));
        assert!(launch.contains("dim3"));
    }

    #[test]
    fn test_cuda_kernel_declaration() {
        let kernel = CudaKernel::new("vecAdd", CudaFunctionKind::Global);
        let decl = kernel.to_declaration();
        assert!(decl.contains("__global__"));
        assert!(decl.contains("vecAdd"));
    }

    #[test]
    fn test_cuda_kind_display() {
        assert_eq!(CudaFunctionKind::Global.to_string(), "__global__");
        assert_eq!(
            CudaFunctionKind::HostDevice.to_string(),
            "__host__ __device__"
        );
    }

    #[test]
    fn test_cuda_memory_space_qualifier() {
        assert_eq!(CudaMemorySpace::Shared.qualifier(), "__shared__");
        assert_eq!(CudaMemorySpace::Constant.qualifier(), "__constant__");
        assert_eq!(CudaMemorySpace::Managed.qualifier(), "__managed__");
    }

    #[test]
    fn test_opencl_kernel_declaration() {
        let mut kernel = OpenCLKernel::new("vec_add");
        kernel
            .params
            .push(("a".into(), "float*".into(), OpenCLAddressSpace::Global));
        kernel
            .params
            .push(("b".into(), "float*".into(), OpenCLAddressSpace::Global));
        kernel.reqd_work_group_size = Some((256, 1, 1));
        let decl = kernel.to_declaration();
        assert!(decl.contains("__kernel"));
        assert!(decl.contains("__global"));
        assert!(decl.contains("vec_add"));
    }

    #[test]
    fn test_opencl_address_space_qualifier() {
        assert_eq!(OpenCLAddressSpace::Global.qualifier(), "__global");
        assert_eq!(OpenCLAddressSpace::Local.qualifier(), "__local");
        assert_eq!(OpenCLAddressSpace::Constant.qualifier(), "__constant");
    }

    #[test]
    fn test_opencl_enqueue_call() {
        let kernel = OpenCLKernel::new("k");
        let call = kernel.to_enqueue_call("q", (1024, 1, 1), Some((256, 1, 1)));
        assert!(call.contains("clEnqueueNDRangeKernel"));
        assert!(call.contains("kernel_k"));
    }

    #[test]
    fn test_sycl_queue_declaration() {
        let mut q = SyclQueue::new("q");
        q.device_selector = SyclDeviceSelector::GpuSelector;
        let decl = q.to_declaration();
        assert!(decl.contains("sycl::queue"));
        assert!(decl.contains("gpu_selector"));
    }

    #[test]
    fn test_sycl_buffer_declaration() {
        let buf = SyclBuffer::new("buf", "float", 1024);
        let decl = buf.to_declaration();
        assert!(decl.contains("sycl::buffer<float, 1>"));
        assert!(decl.contains("1024"));
    }

    #[test]
    fn test_sycl_parallel_for() {
        let pf = SyclParallelFor::new("MyKernel", 1024, "out[i] = in[i] * 2.0f;");
        let code = pf.to_code("q");
        assert!(code.contains("parallel_for"));
        assert!(code.contains("MyKernel"));
        assert!(code.contains("1024"));
    }

    #[test]
    fn test_rust_ffi_binding_to_extern_c() {
        let mut binding = RustFFiBinding::new("add_wrapper", "add", "int");
        binding.params.push(("a".into(), "int".into()));
        binding.params.push(("b".into(), "int".into()));
        let rust_code = binding.to_rust_extern_c();
        assert!(rust_code.contains("#[no_mangle]"));
        assert!(rust_code.contains("extern \"C\""));
        assert!(rust_code.contains("add"));
    }

    #[test]
    fn test_rust_ffi_import() {
        let mut binding = RustFFiBinding::new("", "free", "void");
        binding.params.push(("ptr".into(), "void*".into()));
        let import = binding.to_rust_import();
        assert!(import.contains("extern \"C\""));
        assert!(import.contains("free"));
    }

    #[test]
    fn test_ctype_to_rust_type() {
        assert_eq!(ctype_to_rust_type("int"), "i32");
        assert_eq!(ctype_to_rust_type("double"), "f64");
        assert_eq!(ctype_to_rust_type("void"), "()");
    }

    #[test]
    fn test_python_ctypes_binding() {
        let mut binding = PythonFFIBinding::new(PythonFFIBackend::Ctypes, "mylib");
        let mut func = CExternFunction::new("add", "int");
        func.add_param("a", "int");
        func.add_param("b", "int");
        binding.functions.push(func);
        let code = binding.to_ctypes_binding();
        assert!(code.contains("ctypes.CDLL"));
        assert!(code.contains("ctypes.c_int"));
    }

    #[test]
    fn test_python_cffi_binding() {
        let mut binding = PythonFFIBinding::new(PythonFFIBackend::Cffi, "mylib");
        let mut func = CExternFunction::new("foo", "double");
        func.add_param("x", "int");
        binding.functions.push(func);
        let code = binding.to_cffi_binding();
        assert!(code.contains("ffi.cdef"));
    }

    #[test]
    fn test_python_pybind11_binding() {
        let mut binding = PythonFFIBinding::new(PythonFFIBackend::Pybind11, "module");
        let mut func = CExternFunction::new("compute", "int");
        func.add_param("n", "int");
        binding.functions.push(func);
        let code = binding.to_pybind11_binding();
        assert!(code.contains("PYBIND11_MODULE"));
        assert!(code.contains("compute"));
    }

    #[test]
    fn test_python_backend_descriptions() {
        assert_eq!(
            PythonFFIBackend::Ctypes.description(),
            "ctypes — builtin Python FFI module"
        );
        assert_eq!(
            PythonFFIBackend::Pybind11.description(),
            "pybind11 — seamless C++11/Python binding"
        );
    }

    #[test]
    fn test_ctype_to_python_ctype() {
        assert_eq!(ctype_to_python_ctype("int"), "ctypes.c_int");
        assert_eq!(ctype_to_python_ctype("double"), "ctypes.c_double");
        assert_eq!(ctype_to_python_ctype("void"), "None");
    }

    #[test]
    fn test_interop_registry_register() {
        let mut reg = InteropRegistry::new();
        let func = CExternFunction::new("test", "int");
        reg.register_function(func);
        assert!(reg.has_function("test"));
        assert_eq!(reg.function_count(), 1);
    }

    #[test]
    fn test_interop_registry_generate_ffi_header() {
        let mut reg = InteropRegistry::new();
        let mut func = CExternFunction::new("add", "int");
        func.add_param("a", "int");
        reg.register_function(func);
        let header = reg.generate_ffi_header(InteropLanguage::C);
        assert!(header.contains("add"));
    }

    #[test]
    fn test_interop_registry_generate_rust() {
        let mut reg = InteropRegistry::new();
        let mut func = CExternFunction::new("free", "void");
        func.add_param("p", "void*");
        reg.register_function(func);
        let rust = reg.generate_ffi_header(InteropLanguage::Rust(1));
        assert!(rust.contains("extern \"C\""));
    }

    #[test]
    fn test_interop_language_display() {
        assert_eq!(InteropLanguage::C.to_string(), "C");
        assert_eq!(InteropLanguage::Cuda.to_string(), "CUDA");
        assert_eq!(InteropLanguage::Rust(5).to_string(), "Rust(5 bindings)");
    }

    #[test]
    fn test_cxx_extern_function() {
        let mut f = CXXExternFunction::new("func", "int");
        f.exception_spec = ExceptionSpec::Noexcept;
        let decl = f.extern_c_declaration();
        assert!(decl.contains("extern \"C\""));
    }
}