lehit 0.2.0

Embeddable Lehit language frontend and Cranelift JIT runtime
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
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
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
//! Declarative integration model for modules, types, and functions supplied by
//! a Rust host.
//!
//! Lehit source contracts remain authoritative. Native registration metadata
//! describes physical Rust ABI details and is checked against the semantic and
//! physical facts currently represented by those contracts before a pointer is
//! installed. Validation is not yet exhaustive for every nested layout/register
//! class; native integration is a trusted-host API.
//!
//! See [`crate::guides::native_registration`] for a complete tested workflow and
//! [`crate::guides::safety`] for ABI, lifetime, unwind, and allocator contracts.

use std::{any::Any, collections::HashMap, error::Error, fmt, sync::Arc};

use crate::{
    runtime::{NativeAbi, NativePassMode, NativeTypeKind, NativeTypeLayout},
    semantic::{AccessPath, ModuleGraph, metadata::PrimitiveType},
};

/// A declarative library assembled in Rust before it is loaded into a runtime.
///
/// Map keys are script file paths. References between declarations use
/// [`AccessPath`] so they can be resolved to semantic ids by the target runtime.
#[derive(Default, Clone)]
pub struct RustLib {
    /// Source modules keyed by canonical paths such as `native://math.lt`.
    pub scripts: HashMap<String, Script>,
}

/// One source module and the declarations supplied for it by Rust.
#[derive(Default, Clone)]
pub struct Script {
    /// Authoritative Lehit declarations and script function bodies.
    pub content: String,
    /// Rust-provided top-level functions keyed by source contract name.
    pub functions: HashMap<String, Function>,
    /// Rust-provided trait metadata keyed by source contract name.
    pub traits: HashMap<String, Trait>,
    /// Rust-provided type metadata keyed by source contract name.
    pub types: HashMap<String, Type>,
    /// Physical native layouts keyed by source contract name.
    pub native_types: HashMap<String, NativeTypeRegistration>,
}

/// A function declaration whose type paths are resolved when the library is
/// converted into a semantic model.
#[derive(Clone)]
pub struct Function {
    pub pub_visible: bool,
    pub exported: bool,
    pub self_argument: Option<SelfArgument>,
    pub arguments: Vec<FunctionArgument>,
    pub return_value_type: Option<RustTypeRef>,
    pub body: FunctionBody,
}

#[derive(Debug, Clone)]
pub struct SelfArgument {
    pub kind: SelfArgumentKind,
    pub value_type: RustTypeRef,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SelfArgumentKind {
    Owned {
        mutable: bool,
    },
    Reference {
        lifetime: Option<String>,
        mutable: bool,
    },
}

#[derive(Debug, Clone)]
pub struct FunctionArgument {
    pub ident: String,
    pub value_type: RustTypeRef,
}

/// Function implementation metadata stored in a Rust-provided module.
///
/// The current runtime installs [`FunctionBody::Native`] pointers. Script
/// bodies are parsed from [`Script::content`]; the other variants are
/// experimental representations and are not a stable execution contract.
#[derive(Clone)]
pub enum FunctionBody {
    /// Script-language code. This can be either the complete function body or
    /// another representation understood by the semantic loader.
    Script(String),
    /// Backend IR compiled directly by the runtime.
    Ir(String),
    /// A Rust callback invoked by the runtime without compilation.
    External(ExternalFunction),
    /// Direct native ABI entry point. It is installed only after the Rust
    /// metadata has been checked against the Lehit function contract.
    Native(NativeFunction),
}

/// Builds the semantic half of a typed native function registration.
///
/// The [`NativeFunction`] supplies the physical Rust ABI while this builder
/// supplies names and Lehit-visible types. The workspace validates both halves
/// against the source contract before installing the function pointer.
pub struct NativeFunctionRegistrationBuilder<'a> {
    functions: &'a mut HashMap<String, Function>,
    name: String,
    function: Function,
}

impl<'a> NativeFunctionRegistrationBuilder<'a> {
    fn new(
        functions: &'a mut HashMap<String, Function>,
        name: impl Into<String>,
        native: NativeFunction,
    ) -> Self {
        Self {
            functions,
            name: name.into(),
            function: Function {
                pub_visible: false,
                exported: false,
                self_argument: None,
                arguments: Vec::new(),
                return_value_type: None,
                body: FunctionBody::Native(native),
            },
        }
    }

    pub fn public(mut self) -> Self {
        self.function.pub_visible = true;
        self
    }

    pub fn exported(mut self) -> Self {
        self.function.exported = true;
        self
    }

    pub fn argument(mut self, ident: impl Into<String>, value_type: RustTypeRef) -> Self {
        self.function.arguments.push(FunctionArgument {
            ident: ident.into(),
            value_type,
        });
        self
    }

    pub fn returns(mut self, value_type: RustTypeRef) -> Self {
        self.function.return_value_type = Some(value_type);
        self
    }

    pub fn owned_receiver(mut self, value_type: RustTypeRef, mutable: bool) -> Self {
        self.function.self_argument = Some(SelfArgument {
            kind: SelfArgumentKind::Owned { mutable },
            value_type,
        });
        self
    }

    pub fn shared_receiver(mut self, value_type: RustTypeRef) -> Self {
        self.function.self_argument = Some(SelfArgument {
            kind: SelfArgumentKind::Reference {
                lifetime: None,
                mutable: false,
            },
            value_type,
        });
        self
    }

    pub fn mutable_receiver(mut self, value_type: RustTypeRef) -> Self {
        self.function.self_argument = Some(SelfArgument {
            kind: SelfArgumentKind::Reference {
                lifetime: None,
                mutable: true,
            },
            value_type,
        });
        self
    }

    pub fn finish(self) -> &'a mut Function {
        self.functions.insert(self.name.clone(), self.function);
        self.functions
            .get_mut(&self.name)
            .expect("native function was inserted above")
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NativeEntrypointAbi {
    Rust,
    LehitIndirect,
}

/// Trusted native function pointer and optional physical signature metadata.
///
/// Construct through the typed `from_rust_fn*` helpers whenever possible. All
/// constructors are unsafe because pointer lifetime, ABI and unwind behavior
/// cannot be proven by the runtime.
#[derive(Debug, Clone)]
pub struct NativeFunction {
    symbol: String,
    address: usize,
    abi: NativeEntrypointAbi,
    signature: Option<NativeFunctionSignature>,
}

/// Physical Rust ABI signature used to validate a native entry point.
#[derive(Debug, Clone, Default)]
pub struct NativeFunctionSignature {
    arguments: Vec<NativeFunctionArgumentLayout>,
    argument_pass_modes: Vec<NativePassMode>,
    return_type: Option<&'static NativeTypeLayout>,
    return_pass_mode: Option<NativePassMode>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NativeFunctionArgumentLayout {
    Owned(&'static NativeTypeLayout),
    SharedBorrow(&'static NativeTypeLayout),
    MutableBorrow(&'static NativeTypeLayout),
}

impl NativeFunctionArgumentLayout {
    pub fn layout(self) -> &'static NativeTypeLayout {
        match self {
            Self::Owned(layout) | Self::SharedBorrow(layout) | Self::MutableBorrow(layout) => {
                layout
            }
        }
    }
}

impl NativeFunctionSignature {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn argument<T: NativeAbi>(mut self) -> Self {
        self.arguments
            .push(NativeFunctionArgumentLayout::Owned(T::native_layout()));
        self.argument_pass_modes.push(T::native_pass_mode());
        self
    }

    pub fn shared_argument<T: NativeAbi>(mut self) -> Self {
        self.arguments
            .push(NativeFunctionArgumentLayout::SharedBorrow(
                T::native_layout(),
            ));
        self.argument_pass_modes.push(T::native_pass_mode());
        self
    }

    pub fn mutable_argument<T: NativeAbi>(mut self) -> Self {
        self.arguments
            .push(NativeFunctionArgumentLayout::MutableBorrow(
                T::native_layout(),
            ));
        self.argument_pass_modes.push(T::native_pass_mode());
        self
    }

    pub fn returns<T: NativeAbi>(mut self) -> Self {
        self.return_type = Some(T::native_layout());
        self.return_pass_mode = Some(T::native_pass_mode());
        self
    }

    pub fn arguments(&self) -> &[NativeFunctionArgumentLayout] {
        &self.arguments
    }

    pub fn argument_pass_modes(&self) -> &[NativePassMode] {
        &self.argument_pass_modes
    }

    pub fn return_type(&self) -> Option<&'static NativeTypeLayout> {
        self.return_type
    }

    pub fn return_pass_mode(&self) -> Option<&NativePassMode> {
        self.return_pass_mode.as_ref()
    }
}

impl NativeFunction {
    /// # Safety
    ///
    /// `address` must point to a function with the exact ABI described by the
    /// surrounding `Function` metadata and must remain valid while the RustLib
    /// compilation unit is installed. The function must not unwind across the
    /// Lehit/JIT boundary; it must catch all Rust panics before returning.
    pub unsafe fn new(symbol: impl Into<String>, address: *const ()) -> Self {
        Self {
            symbol: symbol.into(),
            address: address as usize,
            abi: NativeEntrypointAbi::Rust,
            signature: None,
        }
    }

    /// Registers a raw Rust entrypoint together with the physical layouts of
    /// its owned arguments and return value. The descriptor is validated
    /// against the concrete Lehit signature before the pointer is installed.
    ///
    /// # Safety
    ///
    /// `address` must still point to the described Rust function and must not
    /// unwind across the JIT boundary.
    pub unsafe fn new_typed(
        symbol: impl Into<String>,
        address: *const (),
        signature: NativeFunctionSignature,
    ) -> Self {
        Self {
            symbol: symbol.into(),
            address: address as usize,
            abi: NativeEntrypointAbi::Rust,
            signature: Some(signature),
        }
    }

    /// Registers a zero-copy aggregate entrypoint that already uses Lehit's
    /// indirect ABI (`out_ptr`, followed by pointers for owned aggregates).
    ///
    /// # Safety
    ///
    /// The pointer must exactly match the lowered Lehit signature and all
    /// pointed-to values must use the registered byte-for-byte layout. The
    /// function must not unwind across the Lehit/JIT boundary.
    pub unsafe fn new_lehit_indirect(symbol: impl Into<String>, address: *const ()) -> Self {
        Self {
            symbol: symbol.into(),
            address: address as usize,
            abi: NativeEntrypointAbi::LehitIndirect,
            signature: None,
        }
    }

    /// Creates a typed Rust-ABI entrypoint directly from a function pointer.
    ///
    /// # Safety
    ///
    /// The function and every referenced symbol must remain valid while the
    /// RustLib unit is installed, and the function must not unwind across the
    /// JIT boundary.
    pub unsafe fn from_rust_fn0<R: NativeAbi>(
        symbol: impl Into<String>,
        function: fn() -> R,
    ) -> Self {
        unsafe {
            Self::new_typed(
                symbol,
                function as *const (),
                NativeFunctionSignature::new().returns::<R>(),
            )
        }
    }

    /// Typed zero-argument Rust function with no return value.
    ///
    /// # Safety
    ///
    /// The function must remain valid and must not unwind across the boundary.
    pub unsafe fn from_rust_fn0_void(symbol: impl Into<String>, function: fn()) -> Self {
        unsafe {
            Self::new_typed(
                symbol,
                function as *const (),
                NativeFunctionSignature::new(),
            )
        }
    }

    pub unsafe fn from_rust_fn1_ref<T: NativeAbi, R: NativeAbi>(
        symbol: impl Into<String>,
        function: for<'a> fn(&'a T) -> R,
    ) -> Self {
        unsafe {
            Self::new_typed(
                symbol,
                function as *const (),
                NativeFunctionSignature::new()
                    .shared_argument::<T>()
                    .returns::<R>(),
            )
        }
    }

    pub unsafe fn from_rust_fn1_mut<T: NativeAbi, R: NativeAbi>(
        symbol: impl Into<String>,
        function: for<'a> fn(&'a mut T) -> R,
    ) -> Self {
        unsafe {
            Self::new_typed(
                symbol,
                function as *const (),
                NativeFunctionSignature::new()
                    .mutable_argument::<T>()
                    .returns::<R>(),
            )
        }
    }

    pub unsafe fn from_rust_fn1_ref_void<T: NativeAbi>(
        symbol: impl Into<String>,
        function: for<'a> fn(&'a T),
    ) -> Self {
        unsafe {
            Self::new_typed(
                symbol,
                function as *const (),
                NativeFunctionSignature::new().shared_argument::<T>(),
            )
        }
    }

    pub unsafe fn from_rust_fn1_mut_void<T: NativeAbi>(
        symbol: impl Into<String>,
        function: for<'a> fn(&'a mut T),
    ) -> Self {
        unsafe {
            Self::new_typed(
                symbol,
                function as *const (),
                NativeFunctionSignature::new().mutable_argument::<T>(),
            )
        }
    }

    pub unsafe fn from_rust_fn2_ref_owned<T: NativeAbi, U: NativeAbi, R: NativeAbi>(
        symbol: impl Into<String>,
        function: for<'a> fn(&'a T, U) -> R,
    ) -> Self {
        unsafe {
            Self::new_typed(
                symbol,
                function as *const (),
                NativeFunctionSignature::new()
                    .shared_argument::<T>()
                    .argument::<U>()
                    .returns::<R>(),
            )
        }
    }

    pub unsafe fn from_rust_fn2_mut_owned<T: NativeAbi, U: NativeAbi, R: NativeAbi>(
        symbol: impl Into<String>,
        function: for<'a> fn(&'a mut T, U) -> R,
    ) -> Self {
        unsafe {
            Self::new_typed(
                symbol,
                function as *const (),
                NativeFunctionSignature::new()
                    .mutable_argument::<T>()
                    .argument::<U>()
                    .returns::<R>(),
            )
        }
    }

    pub unsafe fn from_rust_fn2_ref_owned_void<T: NativeAbi, U: NativeAbi>(
        symbol: impl Into<String>,
        function: for<'a> fn(&'a T, U),
    ) -> Self {
        unsafe {
            Self::new_typed(
                symbol,
                function as *const (),
                NativeFunctionSignature::new()
                    .shared_argument::<T>()
                    .argument::<U>(),
            )
        }
    }

    pub unsafe fn from_rust_fn2_mut_owned_void<T: NativeAbi, U: NativeAbi>(
        symbol: impl Into<String>,
        function: for<'a> fn(&'a mut T, U),
    ) -> Self {
        unsafe {
            Self::new_typed(
                symbol,
                function as *const (),
                NativeFunctionSignature::new()
                    .mutable_argument::<T>()
                    .argument::<U>(),
            )
        }
    }

    pub unsafe fn from_rust_method_ref<T: NativeAbi, U: NativeAbi, R: NativeAbi>(
        symbol: impl Into<String>,
        method: for<'a> fn(&'a T, U) -> R,
    ) -> Self {
        unsafe { Self::from_rust_fn2_ref_owned(symbol, method) }
    }

    pub unsafe fn from_rust_method_mut<T: NativeAbi, U: NativeAbi, R: NativeAbi>(
        symbol: impl Into<String>,
        method: for<'a> fn(&'a mut T, U) -> R,
    ) -> Self {
        unsafe { Self::from_rust_fn2_mut_owned(symbol, method) }
    }

    pub unsafe fn from_rust_method_ref_void<T: NativeAbi, U: NativeAbi>(
        symbol: impl Into<String>,
        method: for<'a> fn(&'a T, U),
    ) -> Self {
        unsafe { Self::from_rust_fn2_ref_owned_void(symbol, method) }
    }

    pub unsafe fn from_rust_method_mut_void<T: NativeAbi, U: NativeAbi>(
        symbol: impl Into<String>,
        method: for<'a> fn(&'a mut T, U),
    ) -> Self {
        unsafe { Self::from_rust_fn2_mut_owned_void(symbol, method) }
    }

    pub fn abi(&self) -> NativeEntrypointAbi {
        self.abi
    }

    pub fn symbol(&self) -> &str {
        &self.symbol
    }

    pub fn signature(&self) -> Option<&NativeFunctionSignature> {
        self.signature.as_ref()
    }

    pub fn address(&self) -> *const u8 {
        self.address as *const u8
    }
}

macro_rules! typed_native_function_helpers {
    ($returning:ident, $void:ident, $(($type:ident, $value:ident)),+ $(,)?) => {
        impl NativeFunction {
            /// Creates a typed Rust-ABI function pointer descriptor.
            ///
            /// # Safety
            ///
            /// The function must remain valid and must not unwind across the
            /// JIT boundary.
            pub unsafe fn $returning<$($type: NativeAbi,)+ R: NativeAbi>(
                symbol: impl Into<String>,
                function: fn($($type),+) -> R,
            ) -> Self {
                let signature = NativeFunctionSignature::new()
                    $(.argument::<$type>())+
                    .returns::<R>();
                unsafe { Self::new_typed(symbol, function as *const (), signature) }
            }

            /// Creates a typed Rust-ABI function pointer descriptor without a
            /// return slot.
            ///
            /// # Safety
            ///
            /// The function must remain valid and must not unwind across the
            /// JIT boundary.
            pub unsafe fn $void<$($type: NativeAbi),+>(
                symbol: impl Into<String>,
                function: fn($($type),+),
            ) -> Self {
                let signature = NativeFunctionSignature::new()
                    $(.argument::<$type>())+;
                unsafe { Self::new_typed(symbol, function as *const (), signature) }
            }
        }
    };
}

typed_native_function_helpers!(from_rust_fn1, from_rust_fn1_void, (A, a));
typed_native_function_helpers!(from_rust_fn2, from_rust_fn2_void, (A, a), (B, b));
typed_native_function_helpers!(from_rust_fn3, from_rust_fn3_void, (A, a), (B, b), (C, c));
typed_native_function_helpers!(
    from_rust_fn4,
    from_rust_fn4_void,
    (A, a),
    (B, b),
    (C, c),
    (D, d)
);

/// A thread-safe, cloneable native function registered by a Rust library.
pub type ExternalFunction =
    Arc<dyn Fn(&mut ExternalCallContext) -> ExternalFunctionResult + Send + Sync + 'static>;

/// Wraps a safe Rust callback and converts panics into an external-call error.
///
/// Unlike raw [`NativeFunction`] entrypoints, callbacks created here cannot
/// unwind across the runtime boundary.
pub fn external_function<F>(function: F) -> ExternalFunction
where
    F: Fn(&mut ExternalCallContext) -> ExternalFunctionResult + Send + Sync + 'static,
{
    Arc::new(move |context| {
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| function(context))).unwrap_or_else(
            |payload| {
                let message = payload
                    .downcast_ref::<&str>()
                    .copied()
                    .or_else(|| payload.downcast_ref::<String>().map(String::as_str))
                    .unwrap_or("Rust callback panicked");
                Err(ExternalFunctionError::new(message))
            },
        )
    })
}

/// Type-erased call data exchanged with an external Rust function.
///
/// The runtime is responsible for validating values against the function's
/// declared signature before invoking the callback.
#[derive(Default)]
pub struct ExternalCallContext {
    pub arguments: Vec<ExternalValue>,
    pub return_value: Option<ExternalValue>,
}

impl ExternalCallContext {
    pub fn new(arguments: Vec<ExternalValue>) -> Self {
        Self {
            arguments,
            return_value: None,
        }
    }

    pub fn argument<T: Any + Send + Sync>(&self, index: usize) -> Option<&T> {
        self.arguments.get(index)?.downcast_ref()
    }

    pub fn argument_mut<T: Any + Send + Sync>(&mut self, index: usize) -> Option<&mut T> {
        self.arguments.get_mut(index)?.downcast_mut()
    }

    pub fn set_return_value<T: Any + Send + Sync>(&mut self, value: T) {
        self.return_value = Some(Box::new(value));
    }
}

pub type ExternalValue = Box<dyn Any + Send + Sync>;
pub type ExternalFunctionResult = Result<(), ExternalFunctionError>;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExternalFunctionError {
    pub message: String,
}

impl ExternalFunctionError {
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }
}

impl fmt::Display for ExternalFunctionError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl Error for ExternalFunctionError {}

/// A trait/contract declaration. Function keys are local names within the
/// trait, while `supers` are globally resolvable paths.
#[derive(Default, Clone)]
pub struct Trait {
    pub pub_visible: bool,
    pub supers: Vec<AccessPath>,
    pub functions: HashMap<String, Function>,
}

#[derive(Debug, Clone)]
pub struct RustFieldRegistration {
    pub index: u32,
    pub ident: String,
    pub value_type: RustTypeRef,
    pub pub_visible: bool,
}

/// Builder for the fields of a Rust structure that are deliberately exposed to
/// Lehit. Field indices refer to entries in [`NativeTypeLayout`]; fields omitted
/// here remain opaque even though they still contribute to the physical layout.
#[derive(Debug, Clone, Default)]
pub struct RustStructureFields {
    fields: Vec<RustFieldRegistration>,
}

impl RustStructureFields {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn field(
        mut self,
        index: u32,
        ident: impl Into<String>,
        value_type: RustTypeRef,
        pub_visible: bool,
    ) -> Self {
        self.fields.push(RustFieldRegistration {
            index,
            ident: ident.into(),
            value_type,
            pub_visible,
        });
        self
    }

    pub fn public_field(
        self,
        index: u32,
        ident: impl Into<String>,
        value_type: RustTypeRef,
    ) -> Self {
        self.field(index, ident, value_type, true)
    }

    pub fn private_field(
        self,
        index: u32,
        ident: impl Into<String>,
        value_type: RustTypeRef,
    ) -> Self {
        self.field(index, ident, value_type, false)
    }

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

    pub fn is_empty(&self) -> bool {
        self.fields.is_empty()
    }
}

impl From<Vec<RustFieldRegistration>> for RustStructureFields {
    fn from(fields: Vec<RustFieldRegistration>) -> Self {
        Self { fields }
    }
}

impl From<RustStructureFields> for Vec<RustFieldRegistration> {
    fn from(fields: RustStructureFields) -> Self {
        fields.fields
    }
}

impl IntoIterator for RustStructureFields {
    type Item = RustFieldRegistration;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.fields.into_iter()
    }
}

/// Structured unresolved type used by Rust registration metadata. Unlike the
/// legacy `ValueType::allocations`, nesting, named lifetimes, and pointer
/// mutability are explicit and cannot be interpreted in two different orders.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RustTypeRef {
    Named(AccessPath),
    Reference {
        lifetime: Option<String>,
        mutable: bool,
        target: Box<RustTypeRef>,
    },
    Pointer {
        mutable: bool,
        target: Box<RustTypeRef>,
    },
}

#[derive(Debug, Clone)]
pub struct NativeTypeRegistration {
    pub layout: &'static NativeTypeLayout,
    pub pass_mode: NativePassMode,
    /// Only fields deliberately exposed to Lehit. Native private fields may be
    /// omitted and remain opaque while still contributing to size/alignment.
    pub exported_fields: Vec<RustFieldRegistration>,
    /// Explicit semantic variants for a native enum. Physical tags and niches
    /// remain entirely defined by `layout`.
    pub exported_variants: Vec<RustEnumVariantRegistration>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RustEnumVariantRegistration {
    pub index: u32,
    pub ident: String,
    pub value_type: Option<RustTypeRef>,
}

impl RustEnumVariantRegistration {
    pub fn unit(index: u32, ident: impl Into<String>) -> Self {
        Self {
            index,
            ident: ident.into(),
            value_type: None,
        }
    }

    pub fn payload(index: u32, ident: impl Into<String>, value_type: RustTypeRef) -> Self {
        Self {
            index,
            ident: ident.into(),
            value_type: Some(value_type),
        }
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RustEnumVariants {
    variants: Vec<RustEnumVariantRegistration>,
}

impl RustEnumVariants {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn unit(mut self, index: u32, ident: impl Into<String>) -> Self {
        self.variants
            .push(RustEnumVariantRegistration::unit(index, ident));
        self
    }

    pub fn payload(
        mut self,
        index: u32,
        ident: impl Into<String>,
        value_type: RustTypeRef,
    ) -> Self {
        self.variants.push(RustEnumVariantRegistration::payload(
            index, ident, value_type,
        ));
        self
    }
}

impl IntoIterator for RustEnumVariants {
    type Item = RustEnumVariantRegistration;
    type IntoIter = std::vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.variants.into_iter()
    }
}

#[derive(Debug, Clone)]
pub enum NativeLehitRegistration {
    Structure {
        name: String,
        pub_visible: bool,
        fields: RustStructureFields,
    },
    Enum {
        name: String,
        pub_visible: bool,
        variants: RustEnumVariants,
    },
}

/// Derive-facing description of the Lehit surface exported by a native type.
///
/// Implementations normally come from a proc macro. Physical layout remains
/// provided independently by the unsafe [`NativeAbi`] implementation.
pub trait NativeRegistration: NativeAbi {
    fn lehit_registration() -> NativeLehitRegistration;
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RustTypeRegistrationError {
    UnsupportedNativeKind,
    DuplicateFieldIndex(u32),
    UnknownNativeFieldIndex(u32),
    UnknownLehitFieldType {
        field: String,
        module: String,
        path: String,
    },
    MissingTypeContract {
        type_: String,
    },
    MissingExportedField {
        type_: String,
        field: String,
    },
    UnregisteredContractField {
        type_: String,
        field: String,
    },
    FieldVisibilityMismatch {
        type_: String,
        field: String,
    },
    FieldTypeMismatch {
        type_: String,
        field: String,
    },
    MissingExportedVariant {
        module: String,
        type_: String,
        variant: String,
        type_span: crate::parsing::Span,
    },
    UnregisteredContractVariant {
        module: String,
        type_: String,
        variant: String,
        type_span: crate::parsing::Span,
        variant_span: crate::parsing::Span,
    },
    VariantPayloadTypeMismatch {
        module: String,
        type_: String,
        variant: String,
        type_span: crate::parsing::Span,
        variant_span: crate::parsing::Span,
    },
}

impl fmt::Display for RustTypeRegistrationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnsupportedNativeKind => formatter.write_str(
                "native layout kind does not match the requested Lehit registration kind",
            ),
            Self::DuplicateFieldIndex(index) => write!(
                formatter,
                "native field index {index} is exported more than once"
            ),
            Self::UnknownNativeFieldIndex(index) => {
                write!(formatter, "native layout has no field index {index}")
            }
            Self::UnknownLehitFieldType {
                field,
                module,
                path,
            } => write!(
                formatter,
                "exported Rust field `{field}` references missing Lehit type `{module}::{path}`"
            ),
            Self::MissingTypeContract { type_ } => {
                write!(
                    formatter,
                    "native Rust type `{type_}` has no Lehit source contract"
                )
            }
            Self::MissingExportedField { type_, field } => write!(
                formatter,
                "native type `{type_}` exports `{field}`, but its Lehit contract does not"
            ),
            Self::UnregisteredContractField { type_, field } => write!(
                formatter,
                "Lehit contract for native type `{type_}` exposes unregistered field `{field}`"
            ),
            Self::FieldVisibilityMismatch { type_, field } => write!(
                formatter,
                "visibility of `{type_}.{field}` differs between Rust metadata and Lehit contract"
            ),
            Self::FieldTypeMismatch { type_, field } => write!(
                formatter,
                "type of `{type_}.{field}` differs between Rust metadata and Lehit contract"
            ),
            Self::MissingExportedVariant { type_, variant, .. } => write!(
                formatter,
                "native enum `{type_}` exports variant `{variant}`, but its Lehit contract does not"
            ),
            Self::UnregisteredContractVariant { type_, variant, .. } => write!(
                formatter,
                "Lehit contract for native enum `{type_}` exposes unregistered variant `{variant}`"
            ),
            Self::VariantPayloadTypeMismatch { type_, variant, .. } => write!(
                formatter,
                "payload type of `{type_}::{variant}` differs between Rust metadata and Lehit contract"
            ),
        }
    }
}

impl Error for RustTypeRegistrationError {}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RustFunctionRegistrationError {
    MissingContract {
        function: String,
    },
    VisibilityMismatch {
        function: String,
    },
    ReceiverMismatch {
        function: String,
    },
    ArgumentCountMismatch {
        function: String,
        rust: usize,
        lehit: usize,
    },
    ArgumentNameMismatch {
        function: String,
        index: usize,
        rust: String,
        lehit: String,
    },
    ArgumentTypeMismatch {
        function: String,
        index: usize,
    },
    ReturnTypeMismatch {
        function: String,
    },
    InvalidTypeMetadata {
        function: String,
    },
    NativeSignatureCountMismatch {
        function: String,
        rust: usize,
        lehit: usize,
    },
    NativeArgumentLayoutMismatch {
        function: String,
        index: usize,
    },
    NativeReturnLayoutMismatch {
        function: String,
    },
}

impl fmt::Display for RustFunctionRegistrationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingContract { function } => write!(
                formatter,
                "Rust function `{function}` has no Lehit contract"
            ),
            Self::VisibilityMismatch { function } => write!(
                formatter,
                "visibility of Rust function `{function}` differs from its Lehit contract"
            ),
            Self::ReceiverMismatch { function } => write!(
                formatter,
                "receiver of Rust function `{function}` differs from its Lehit contract"
            ),
            Self::ArgumentCountMismatch {
                function,
                rust,
                lehit,
            } => write!(
                formatter,
                "Rust function `{function}` has {rust} arguments, Lehit contract has {lehit}"
            ),
            Self::ArgumentNameMismatch {
                function,
                index,
                rust,
                lehit,
            } => write!(
                formatter,
                "argument {index} of `{function}` is `{rust}` in Rust metadata and `{lehit}` in Lehit"
            ),
            Self::ArgumentTypeMismatch { function, index } => write!(
                formatter,
                "argument {index} type of Rust function `{function}` differs from its Lehit contract"
            ),
            Self::ReturnTypeMismatch { function } => write!(
                formatter,
                "return type of Rust function `{function}` differs from its Lehit contract"
            ),
            Self::InvalidTypeMetadata { function } => write!(
                formatter,
                "Rust function `{function}` contains unresolved type metadata"
            ),
            Self::NativeSignatureCountMismatch {
                function,
                rust,
                lehit,
            } => write!(
                formatter,
                "typed native function `{function}` describes {rust} arguments, Lehit contract has {lehit}"
            ),
            Self::NativeArgumentLayoutMismatch { function, index } => write!(
                formatter,
                "physical layout of argument {index} of native function `{function}` differs from its Lehit contract"
            ),
            Self::NativeReturnLayoutMismatch { function } => write!(
                formatter,
                "physical return layout of native function `{function}` differs from its Lehit contract"
            ),
        }
    }
}

impl Error for RustFunctionRegistrationError {}

impl Script {
    /// Starts registration of a direct native function in this module.
    pub fn native_function(
        &mut self,
        name: impl Into<String>,
        native: NativeFunction,
    ) -> NativeFunctionRegistrationBuilder<'_> {
        NativeFunctionRegistrationBuilder::new(&mut self.functions, name, native)
    }

    pub fn register_native<T: NativeRegistration>(
        &mut self,
    ) -> Result<&mut Type, RustTypeRegistrationError> {
        match T::lehit_registration() {
            NativeLehitRegistration::Structure {
                name,
                pub_visible,
                fields,
            } => self.register_type::<T>(name, pub_visible, fields),
            NativeLehitRegistration::Enum {
                name,
                pub_visible,
                variants,
            } => self.register_enum_type::<T>(name, pub_visible, variants),
        }
    }

    pub fn register_type<T: NativeAbi>(
        &mut self,
        name: impl Into<String>,
        pub_visible: bool,
        exported_fields: impl IntoIterator<Item = RustFieldRegistration>,
    ) -> Result<&mut Type, RustTypeRegistrationError> {
        let name = name.into();
        let exported_fields = exported_fields.into_iter().collect::<Vec<_>>();
        let layout = T::native_layout();
        let NativeTypeKind::Structure {
            fields: native_fields,
        } = &layout.kind
        else {
            return Err(RustTypeRegistrationError::UnsupportedNativeKind);
        };
        let mut seen = std::collections::HashSet::new();
        let mut fields = Vec::with_capacity(exported_fields.len());
        for field in &exported_fields {
            if !seen.insert(field.index) {
                return Err(RustTypeRegistrationError::DuplicateFieldIndex(field.index));
            }
            let native = native_fields
                .iter()
                .find(|native| native.index == field.index)
                .ok_or(RustTypeRegistrationError::UnknownNativeFieldIndex(
                    field.index,
                ))?;
            fields.push(StructureField {
                offset: native.offset,
                ident: field.ident.clone(),
                value_type: field.value_type.clone(),
                pub_visible: field.pub_visible,
            });
        }
        self.native_types.insert(
            name.clone(),
            NativeTypeRegistration {
                layout,
                pass_mode: T::native_pass_mode(),
                exported_fields,
                exported_variants: Vec::new(),
            },
        );
        self.types.insert(
            name.clone(),
            Type {
                pub_visible,
                layout: TypeLayout::Structure(StructureType {
                    size: layout.size,
                    align: layout.align,
                    fields,
                }),
                functions: HashMap::new(),
                trait_implementations: HashMap::new(),
            },
        );
        Ok(self.types.get_mut(&name).expect("type was inserted above"))
    }

    pub fn register_enum_type<T: NativeAbi>(
        &mut self,
        name: impl Into<String>,
        pub_visible: bool,
        exported_variants: impl IntoIterator<Item = RustEnumVariantRegistration>,
    ) -> Result<&mut Type, RustTypeRegistrationError> {
        let name = name.into();
        let exported_variants = exported_variants.into_iter().collect::<Vec<_>>();
        let layout = T::native_layout();
        let NativeTypeKind::Enum(native_enum) = &layout.kind else {
            return Err(RustTypeRegistrationError::UnsupportedNativeKind);
        };
        let mut seen = std::collections::HashSet::new();
        let mut variants = Vec::with_capacity(exported_variants.len());
        for variant in &exported_variants {
            if !seen.insert(variant.index) {
                return Err(RustTypeRegistrationError::DuplicateFieldIndex(
                    variant.index,
                ));
            }
            if !native_enum
                .variants
                .iter()
                .any(|native| native.index == variant.index)
            {
                return Err(RustTypeRegistrationError::UnknownNativeFieldIndex(
                    variant.index,
                ));
            }
            variants.push(EnumVariant {
                index: variant.index as usize,
                ident: variant.ident.clone(),
                value_type: variant.value_type.clone(),
            });
        }
        self.native_types.insert(
            name.clone(),
            NativeTypeRegistration {
                layout,
                pass_mode: T::native_pass_mode(),
                exported_fields: Vec::new(),
                exported_variants,
            },
        );
        self.types.insert(
            name.clone(),
            Type {
                pub_visible,
                layout: TypeLayout::Enum(EnumType {
                    size: layout.size,
                    align: layout.align,
                    variants,
                }),
                functions: HashMap::new(),
                trait_implementations: HashMap::new(),
            },
        );
        Ok(self.types.get_mut(&name).expect("type was inserted above"))
    }

    pub fn validate_registered_field_types(
        &self,
        graph: &ModuleGraph,
    ) -> Result<(), Vec<RustTypeRegistrationError>> {
        let mut errors = Vec::new();
        for registration in self.native_types.values() {
            for (name, type_) in registration
                .exported_fields
                .iter()
                .map(|field| (field.ident.as_str(), Some(&field.value_type)))
                .chain(
                    registration
                        .exported_variants
                        .iter()
                        .map(|variant| (variant.ident.as_str(), variant.value_type.as_ref())),
                )
            {
                let Some(type_) = type_ else {
                    continue;
                };
                let mut paths = Vec::new();
                collect_registered_type_paths(type_, &mut paths);
                for path in paths {
                    if graph.resolve(&path.file_path, &path.local_access).is_err() {
                        errors.push(RustTypeRegistrationError::UnknownLehitFieldType {
                            field: name.to_owned(),
                            module: path.file_path.clone(),
                            path: path.local_access.clone(),
                        });
                    }
                }
            }
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

fn collect_registered_type_paths<'a>(type_: &'a RustTypeRef, paths: &mut Vec<&'a AccessPath>) {
    match type_ {
        RustTypeRef::Named(path) => {
            paths.push(path);
            for generic in &path.generics {
                collect_access_path_paths(generic, paths);
            }
        }
        RustTypeRef::Reference { target, .. } | RustTypeRef::Pointer { target, .. } => {
            collect_registered_type_paths(target, paths)
        }
    }
}

fn collect_access_path_paths<'a>(path: &'a AccessPath, paths: &mut Vec<&'a AccessPath>) {
    paths.push(path);
    for generic in &path.generics {
        collect_access_path_paths(generic, paths);
    }
}

/// A named type declaration and its methods/trait implementations.
#[derive(Clone)]
pub struct Type {
    pub pub_visible: bool,
    pub layout: TypeLayout,
    pub functions: HashMap<String, Function>,
    pub trait_implementations: HashMap<AccessPath, TraitImplementation>,
}

impl Type {
    /// Starts registration of a direct native inherent method.
    pub fn native_method(
        &mut self,
        name: impl Into<String>,
        native: NativeFunction,
    ) -> NativeFunctionRegistrationBuilder<'_> {
        NativeFunctionRegistrationBuilder::new(&mut self.functions, name, native)
    }
}

#[derive(Default, Clone)]
pub struct TraitImplementation {
    pub functions: HashMap<String, Function>,
}

/// Unresolved counterpart of semantic `TypeLayoutMetadata`.
#[derive(Debug, Clone)]
pub enum TypeLayout {
    Primitive(PrimitiveType),
    Structure(StructureType),
    Enum(EnumType),
    Tuple(TupleType),
    Function(FunctionType),
}

#[derive(Debug, Clone)]
pub struct StructureType {
    pub size: usize,
    pub align: usize,
    pub fields: Vec<StructureField>,
}

#[derive(Debug, Clone)]
pub struct StructureField {
    pub offset: usize,
    pub ident: String,
    pub value_type: RustTypeRef,
    pub pub_visible: bool,
}

#[derive(Debug, Clone)]
pub struct EnumType {
    pub size: usize,
    pub align: usize,
    pub variants: Vec<EnumVariant>,
}

#[derive(Debug, Clone)]
pub struct EnumVariant {
    pub index: usize,
    pub ident: String,
    pub value_type: Option<RustTypeRef>,
}

#[derive(Debug, Clone)]
pub struct TupleType {
    pub items: Vec<RustTypeRef>,
}

#[derive(Debug, Clone)]
pub struct FunctionType {
    pub arguments: Vec<RustTypeRef>,
    pub return_value_type: Option<RustTypeRef>,
}

#[cfg(test)]
mod tests {
    use std::sync::OnceLock;

    use super::*;
    use crate::{
        core_lib,
        parsing::{SourceFile, parse_file},
        runtime::{NativeEnumLayout, NativeEnumVariant, NativeTypeLayout},
        semantic::DeclarationIndex,
    };

    #[derive(crate::LehitRegistration)]
    #[lehit(name = "NativePair", public)]
    struct NativePair {
        #[lehit(index = 0, public)]
        exposed: i32,
        private: i32,
    }

    #[derive(crate::LehitRegistration)]
    #[lehit(name = "NativeChoice", public)]
    #[repr(u8)]
    enum NativeChoice {
        #[lehit(index = 0)]
        Empty,
        #[lehit(index = 1)]
        Value(i32),
    }

    // SAFETY: repr(u8) fixes the direct discriminant representation. The
    // payload offset is tied to this concrete target layout.
    unsafe impl NativeAbi for NativeChoice {
        fn native_layout() -> &'static NativeTypeLayout {
            static LAYOUT: OnceLock<NativeTypeLayout> = OnceLock::new();
            LAYOUT.get_or_init(|| {
                NativeTypeLayout::enum_type::<NativeChoice>(NativeEnumLayout::direct(
                    vec![
                        NativeEnumVariant::unit(0),
                        NativeEnumVariant::payload(1, i32::native_layout(), 4),
                    ],
                    0,
                    8,
                    false,
                    vec![0, 1],
                ))
            })
        }
    }

    fn i32_value_type() -> RustTypeRef {
        RustTypeRef::Named(AccessPath {
            file_path: core_lib::PRIMITIVE_MODULE_FILE_PATH.into(),
            local_access: "i32".into(),
            generics: Vec::new(),
        })
    }

    #[test]
    fn registers_native_enum_variants_separately_from_physical_tags() {
        let _empty = NativeChoice::Empty;
        let NativeChoice::Value(payload) = NativeChoice::Value(7) else {
            unreachable!()
        };
        assert_eq!(payload, 7);
        let mut script = Script::default();
        script.register_native::<NativeChoice>().unwrap();
        let TypeLayout::Enum(enum_) = &script.types["NativeChoice"].layout else {
            panic!("registered native enum expected")
        };
        assert_eq!(enum_.variants.len(), 2);
        assert_eq!(enum_.variants[0].ident, "Empty");
        assert_eq!(enum_.variants[1].ident, "Value");
        assert_eq!(
            script.native_types["NativeChoice"].exported_variants.len(),
            2
        );
    }

    #[test]
    fn rust_function_pointer_helpers_derive_physical_signatures() {
        fn combine(first: u32, second: u64) -> u64 {
            u64::from(first) + second
        }
        fn consume(_: u8, _: u16, _: u32, _: u64) {}
        fn read(value: &u32) -> u32 {
            *value
        }
        fn clear(value: &mut u32) {
            *value = 0;
        }
        fn read_add(value: &u32, extra: u16) -> u64 {
            u64::from(*value) + u64::from(extra)
        }
        fn mutate_add(value: &mut u32, extra: u16) {
            *value += u32::from(extra);
        }

        let returning = unsafe { NativeFunction::from_rust_fn2("combine", combine) };
        let signature = returning.signature().unwrap();
        assert_eq!(signature.arguments().len(), 2);
        assert_eq!(
            signature.arguments()[0].layout().rust_type_id,
            std::any::TypeId::of::<u32>()
        );
        assert_eq!(
            signature.arguments()[1].layout().rust_type_id,
            std::any::TypeId::of::<u64>()
        );
        assert_eq!(
            signature.return_type().unwrap().rust_type_id,
            std::any::TypeId::of::<u64>()
        );

        let void = unsafe { NativeFunction::from_rust_fn4_void("consume", consume) };
        assert_eq!(void.signature().unwrap().arguments().len(), 4);
        assert!(void.signature().unwrap().return_type().is_none());

        let shared = unsafe { NativeFunction::from_rust_fn1_ref("read", read) };
        assert!(matches!(
            shared.signature().unwrap().arguments(),
            [NativeFunctionArgumentLayout::SharedBorrow(layout)]
                if layout.rust_type_id == std::any::TypeId::of::<u32>()
        ));
        let mutable = unsafe { NativeFunction::from_rust_fn1_mut_void("clear", clear) };
        assert!(matches!(
            mutable.signature().unwrap().arguments(),
            [NativeFunctionArgumentLayout::MutableBorrow(layout)]
                if layout.rust_type_id == std::any::TypeId::of::<u32>()
        ));

        let mixed = unsafe { NativeFunction::from_rust_fn2_ref_owned("read_add", read_add) };
        assert!(matches!(
            mixed.signature().unwrap().arguments(),
            [
                NativeFunctionArgumentLayout::SharedBorrow(_),
                NativeFunctionArgumentLayout::Owned(layout),
            ] if layout.rust_type_id == std::any::TypeId::of::<u16>()
        ));
        let mixed_void =
            unsafe { NativeFunction::from_rust_fn2_mut_owned_void("mutate_add", mutate_add) };
        assert!(matches!(
            mixed_void.signature().unwrap().arguments(),
            [
                NativeFunctionArgumentLayout::MutableBorrow(_),
                NativeFunctionArgumentLayout::Owned(_),
            ]
        ));
        assert!(mixed_void.signature().unwrap().return_type().is_none());
    }

    #[test]
    fn native_registration_builder_assembles_functions_and_methods() {
        fn identity(value: i32) -> i32 {
            value
        }
        fn add(pair: &mut NativePair, amount: i32) -> i32 {
            pair.exposed += amount;
            pair.exposed
        }

        let i32_type = i32_value_type();
        let pair_type = RustTypeRef::Named(AccessPath {
            file_path: "native://builder.lt".into(),
            local_access: "NativePair".into(),
            generics: Vec::new(),
        });
        let mut script = Script::default();
        let identity_native = unsafe { NativeFunction::from_rust_fn1("identity", identity) };
        script
            .native_function("identity", identity_native)
            .public()
            .exported()
            .argument("value", i32_type.clone())
            .returns(i32_type.clone())
            .finish();

        let identity = &script.functions["identity"];
        assert!(identity.pub_visible);
        assert!(identity.exported);
        assert_eq!(identity.arguments[0].ident, "value");
        assert!(matches!(identity.body, FunctionBody::Native(_)));

        let type_ = script.register_native::<NativePair>().unwrap();
        let add_native = unsafe { NativeFunction::from_rust_method_mut("add", add) };
        type_
            .native_method("add", add_native)
            .mutable_receiver(pair_type.clone())
            .argument("amount", i32_type.clone())
            .returns(i32_type)
            .finish();

        let add = &script.types["NativePair"].functions["add"];
        assert!(matches!(
            add.self_argument,
            Some(SelfArgument {
                kind: SelfArgumentKind::Reference { mutable: true, .. },
                ..
            })
        ));
        assert_eq!(add.self_argument.as_ref().unwrap().value_type, pair_type);
        assert_eq!(add.arguments[0].ident, "amount");
    }

    #[test]
    fn safe_external_function_converts_panics_into_errors() {
        let callback = external_function(|_| panic!("native callback failed"));
        let mut context = ExternalCallContext::default();
        let error = callback(&mut context).unwrap_err();
        assert_eq!(error.message, "native callback failed");
    }

    #[test]
    fn registers_only_explicitly_exported_native_fields() {
        let mut script = Script::default();
        script.register_native::<NativePair>().unwrap();

        let TypeLayout::Structure(layout) = &script.types["NativePair"].layout else {
            panic!("registered native structure expected")
        };
        assert_eq!(layout.size, std::mem::size_of::<NativePair>());
        assert_eq!(layout.fields.len(), 1);
        assert_eq!(layout.fields[0].ident, "exposed");

        let parsed = parse_file(SourceFile {
            path: core_lib::PRIMITIVE_MODULE_FILE_PATH,
            text: core_lib::PRIMITIVE_MODULE_FILE_CONTENT,
        })
        .unwrap();
        let mut graph = ModuleGraph::default();
        graph
            .insert(
                core_lib::PRIMITIVE_MODULE_FILE_PATH,
                DeclarationIndex::collect(&parsed).unwrap(),
            )
            .unwrap();
        script.validate_registered_field_types(&graph).unwrap();
    }

    #[test]
    fn rejects_an_exported_field_whose_type_is_absent_from_lehit() {
        let mut script = Script::default();
        let RustTypeRef::Named(mut missing_path) = i32_value_type() else {
            unreachable!()
        };
        missing_path.local_access = "Missing".into();
        let missing = RustTypeRef::Named(missing_path);
        script
            .register_type::<NativePair>(
                "NativePair",
                true,
                vec![RustFieldRegistration {
                    index: 0,
                    ident: "exposed".into(),
                    value_type: missing,
                    pub_visible: true,
                }],
            )
            .unwrap();
        let graph = ModuleGraph::default();
        assert!(matches!(
            script.validate_registered_field_types(&graph),
            Err(errors) if matches!(errors.as_slice(), [RustTypeRegistrationError::UnknownLehitFieldType { .. }])
        ));
    }
}