neo-devpack-solidity 0.22.0

Production-focused Solidity-to-NeoVM compilation system
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
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
pub fn analyse_source(source: &str) -> Result<ContractMetadata, SolidityError> {
    let mut contracts = analyse_all_sources(source)?;
    Ok(contracts.swap_remove(0))
}

pub fn analyse_all_sources(source: &str) -> Result<Vec<ContractMetadata>, SolidityError> {
    fn is_builtin_library_name(name: &str) -> bool {
        matches!(
            name,
            "Runtime" | "abi" | "Storage" | "Syscalls" | "Neo" | "NativeCalls"
        )
    }

    fn normalize_library_for_neo(mut contract: ContractIR) -> ContractIR {
        if !matches!(contract.kind, ContractKind::Library) {
            return contract;
        }

        // Neo N3 libraries are inlined into contracts; treat externally visible
        // library functions as internal helper functions to avoid exposing them
        // through the contract ABI.
        for function in &mut contract.functions {
            if !matches!(function.ty, FunctionTy::Function) {
                continue;
            }
            if matches!(
                function.visibility,
                VisibilityKind::External | VisibilityKind::Public
            ) {
                function.visibility = VisibilityKind::Internal;
            }
        }

        // Keep merged library state as internal implementation detail.
        // Public library constants would otherwise synthesize contract-level
        // getters and create ABI/name collisions in the consuming contract.
        for state in &mut contract.state_variables {
            state.visibility = Some("internal".to_string());
        }

        contract
    }

    fn collect_contract_types(
        contract_map: &std::collections::HashMap<String, ContractIR>,
    ) -> Vec<String> {
        let mut contract_types: Vec<String> = Vec::new();
        let mut seen_contract_types = std::collections::HashSet::new();

        for contract in contract_map.values() {
            let include_as_contract_type = match contract.kind {
                ContractKind::Contract | ContractKind::AbstractContract | ContractKind::Interface => {
                    true
                }
                ContractKind::Library => !is_builtin_library_name(contract.name.as_str()),
            };

            if include_as_contract_type
                && seen_contract_types.insert(contract.name.to_ascii_lowercase())
            {
                contract_types.push(contract.name.clone());
            }
        }

        contract_types
    }

    let mut primary = Vec::new();
    let mut fallback = Vec::new();

    let contracts = parse_source(source)?;
    for contract in contracts {
        if matches!(
            contract.kind,
            ContractKind::Contract | ContractKind::AbstractContract
        ) {
            primary.push(contract);
        } else {
            fallback.push(contract);
        }
    }

    let has_primary = !primary.is_empty();
    let pre_merge_contract_map: std::collections::HashMap<String, ContractIR> = primary
        .iter()
        .chain(fallback.iter())
        .map(|contract| (contract.name.clone(), contract.clone()))
        .collect();
    let contract_types = collect_contract_types(&pre_merge_contract_map);

    let raw_libraries: Vec<ContractIR> = if has_primary {
        fallback
            .iter()
            .filter(|contract| matches!(contract.kind, ContractKind::Library))
            // Built-in helper libraries (Runtime/Storage/Syscalls/Neo) are lowered directly during
            // IR generation. Avoid merging their Solidity bodies into user contracts since they
            // may contain EVM-only stubs or unsupported constructs, and they would bloat bytecode.
            .filter(|contract| !is_builtin_library_name(contract.name.as_str()))
            .cloned()
            .collect()
    } else {
        Vec::new()
    };

    // Validate user libraries before merging. Convert each library to metadata
    // and run the standard validation pipeline to catch library-specific errors
    // (state variables, constructors, external functions) early.
    //
    // Cross-library struct references — e.g. `function executeInitReserve(
    // ConfiguratorInputTypes.InitReserveInput calldata input)` declared in
    // library `ConfiguratorLogic` and referencing a struct from library
    // `ConfiguratorInputTypes` (both shipped in @aave/core-v3) — require that
    // each library's validation pass see the structs declared in its peers.
    // Otherwise `NeoType::from_solidity` can't resolve the qualified type,
    // `param.neo_type` stays `None`, and the external-function check fires a
    // spurious "uses unsupported type" error.
    //
    // We solve this by pre-merging every other library's structs (and enums,
    // for symmetry) into each library's struct table before running its
    // validation. Doing the merge here (instead of at flatten time) keeps the
    // mutation scoped to a clone and means downstream stages still see the
    // original, un-merged library tree.
    let library_struct_pool: Vec<StructIR> = raw_libraries
        .iter()
        .flat_map(|lib| lib.structs.iter().cloned())
        .collect();
    let library_enum_pool: Vec<EnumIR> = raw_libraries
        .iter()
        .flat_map(|lib| lib.enums.iter().cloned())
        .collect();
    for lib in &raw_libraries {
        let mut lib_with_peers = lib.clone();
        for s in &library_struct_pool {
            if !lib_with_peers.structs.iter().any(|own| own.name == s.name) {
                lib_with_peers.structs.push(s.clone());
            }
        }
        for e in &library_enum_pool {
            if !lib_with_peers.enums.iter().any(|own| own.name == e.name) {
                lib_with_peers.enums.push(e.clone());
            }
        }
        // Run normalize first so the validation sees the post-merge
        // semantics — library external functions get converted to internal
        // BEFORE validate enforces "no storage parameter on external
        // functions". Otherwise the validator rejects legitimate library
        // patterns like `EModeLogic.executeSetUserEMode(mapping storage, ...)`
        // (Aave) where the function is `external` in source but operates as
        // an internal helper on Neo (libraries inline into their callers).
        let normalized_lib = normalize_library_for_neo(lib_with_peers);
        let lib_metadata = convert_contract(
            normalized_lib,
            &[],
            &contract_types,
            std::sync::Arc::new(SelectorRegistry::default()),
        );
        let lib_diagnostics = validate_contract(&lib_metadata);
        let lib_errors: Vec<Diagnostic> = lib_diagnostics
            .into_iter()
            .filter(|d| matches!(d.severity, DiagnosticSeverity::Error))
            .collect();
        if !lib_errors.is_empty() {
            let messages: Vec<String> = lib_errors.iter().map(|d| {
                let mut msg = d.message.clone();
                if let Some(suggestion) = &d.suggestion {
                    msg.push_str(&format!("\n  suggestion: {suggestion}"));
                }
                msg
            }).collect();
            return Err(SolidityError::analysis(messages.join("\n")));
        }
    }

    let libraries: Vec<ContractIR> = raw_libraries
        .into_iter()
        .map(normalize_library_for_neo)
        .collect();

    // Task #83 — when a primary contract `A` runs `B b = new B(); b.foo();`
    // the compiler emits a 20-byte zero placeholder for `b` and lowers
    // `b.foo()` as `System.Contract.Call([0;20], "foo", flags, args)`. B's
    // compiled body is a separate artifact, so without help the call would
    // return `Null` and A's return value would silently go empty. Fix:
    // merge every sibling primary's public/external functions that A
    // references via `new X()` into A's own function table (name-preserving,
    // host-wins-on-collision); the runtime then routes the zero-hash call
    // through `self_method_offsets` — see the Task #83 branch in
    // `execution_impl_part2_contract_call.rs`.
    if has_primary {
        let sibling_fn_map: std::collections::HashMap<String, Vec<FunctionIR>> = primary
            .iter()
            .map(|c| {
                (
                    c.name.clone(),
                    c.functions
                        .iter()
                        .filter(|f| {
                            // Include abstract internal function declarations
                            // (body = None) alongside concrete externals.
                            // When sibling-merge pulls in an external body
                            // like `rawFulfillRandomWords` whose body calls
                            // an abstract sibling-internal function (e.g.
                            // VRFConsumerBaseV2's `fulfillRandomWords(uint256,
                            // uint256[])`), the host's IR-lowering pass would
                            // otherwise fail the overload lookup with
                            // "no overload of 'fulfillRandomWords' with 2
                            // argument(s)". Importing the abstract declaration
                            // satisfies the lookup; at runtime the call lands
                            // on an empty stub (RET-only) which is acceptable
                            // for the dead-code paths that typically include
                            // such helpers transitively.
                            let is_abstract_internal = matches!(f.ty, FunctionTy::Function)
                                && f.body.is_none();
                            // Task #126 — include Fallback (and Receive) alongside
                            // ordinary external/public named functions so that a
                            // primary contract whose only entrypoint is
                            // `fallback()` still contributes its dispatcher to
                            // the caller's merged function table when the caller
                            // invokes a method the callee doesn't declare.
                            //
                            // Without this, `try Target(t).nonExistentMethod()`
                            // (where TargetImpl only defines `fallback()`)
                            // would never be able to route through the zero-
                            // placeholder self-offsets path: the fallback entry
                            // simply wouldn't be in the merge set, and the
                            // runtime's unknown-method path would silently
                            // return Null rather than propagating the fallback's
                            // revert back to the caller's catch clause.
                            let is_named_external = matches!(f.ty, FunctionTy::Function)
                                && matches!(
                                    f.visibility,
                                    VisibilityKind::External | VisibilityKind::Public
                                );
                            let is_fallback_like = matches!(
                                f.ty,
                                FunctionTy::Fallback | FunctionTy::Receive
                            );
                            // (We deliberately do NOT include
                            // `is_abstract_internal` here. Including abstract
                            // internal declarations would let merged bodies
                            // reference them, but it also fails the "all
                            // abstract methods implemented" validation since
                            // those functions don't have a body in the host.
                            // We handle the missing-overload case at
                            // IR-lowering time by emitting a runtime trap
                            // instead of a compile error.)
                            let _ = is_abstract_internal;
                            is_named_external || is_fallback_like
                        })
                        .cloned()
                        .collect::<Vec<_>>(),
                )
            })
            .collect();
        // Companion map: every sibling's modifier definitions — INCLUDING
        // modifiers reachable through the sibling's inheritance chain. When
        // sibling functions are merged into a host below, any modifier they
        // apply (`function upgrade(...) public payable virtual onlyOwner`)
        // must still resolve in the host. The host's local `modifier_defs`
        // only sees ITS OWN modifier declarations — so without a parallel
        // merge pass, merged `upgrade`'s `onlyOwner` lookup fails with
        // "unresolved modifier 'onlyOwner' with 0 argument(s)". Repro: OZ
        // TransparentUpgradeableProxy / ProxyAdmin import cycle, where
        // ProxyAdmin's `onlyOwner` lives in its base contract Ownable.
        //
        // Because the sibling's own inheritance flattening hasn't happened
        // yet at this point in the pipeline, we walk each sibling's
        // linearized base chain ourselves and union their modifier
        // definitions per sibling, keyed by (name, arity), preferring
        // bodied modifiers over abstract declarations.
        let sibling_modifier_map: std::collections::HashMap<String, Vec<FunctionIR>> = primary
            .iter()
            .map(|c| {
                let mut seen: std::collections::HashMap<(String, usize), FunctionIR> =
                    std::collections::HashMap::new();
                let mut visit = |contract: &ContractIR| {
                    for f in &contract.functions {
                        if !matches!(f.ty, FunctionTy::Modifier) {
                            continue;
                        }
                        let key = (f.name.clone(), f.parameters.len());
                        match seen.get(&key) {
                            Some(existing) if existing.body.is_some() => {}
                            _ => {
                                seen.insert(key, f.clone());
                            }
                        }
                    }
                };
                visit(c);
                // Try to walk the linearization. If it fails (shouldn't —
                // we already ran it during pre-merge analysis to detect
                // cycles), fall back to direct base inspection.
                if let Ok(chain) =
                    contract_linearization_base_to_derived(&c.name, &pre_merge_contract_map)
                {
                    for ancestor_name in &chain {
                        if ancestor_name == &c.name {
                            continue;
                        }
                        if let Some(ancestor) = pre_merge_contract_map.get(ancestor_name) {
                            visit(ancestor);
                        }
                    }
                }
                (c.name.clone(), seen.into_values().collect::<Vec<_>>())
            })
            .collect();
        // Task #197 — parallel state-variable map. When a sibling's external
        // function body references state variables (e.g. Mock.balanceOf
        // reading `_bal[a]`), merging only the FunctionIR leaves the
        // identifier unresolved in the caller's `state_index_map`, so the
        // variable lowering falls through to the `Integer(0)` placeholder
        // path (src/ir/expressions/variable.rs) and downstream opcodes like
        // SIZE/PICKITEM fault on the wrong StackItem type. The storage key
        // is derived from the state variable's name (see
        // `value_types.rs::compute_state_slot`), so merging Mock's `_bal`
        // into Client lets Client's compiled balanceOf read the same
        // storage slot Mock.mint wrote to.
        let sibling_state_map: std::collections::HashMap<String, Vec<StateVariableIR>> =
            primary
                .iter()
                .map(|c| (c.name.clone(), c.state_variables.clone()))
                .collect();
        // Task #198 — parallel constructor map. For `new Child(x, y)` inside a
        // Parent contract, the compiled Child lives in a separate artifact, so
        // the Parent's runtime invocation of its own `_deploy` never runs the
        // Child constructor. Without executing the ctor body, Child's state
        // variables (`a`, `b`) stay at their zero defaults — and the follow-up
        // `c.a()` / `c.b()` cross-contract calls (routed through sibling-merge
        // self-offsets; Task #83) therefore observe zeros.
        //
        // Fix: expose each sibling's constructor as a regular, internal,
        // name-mangled function (`__ctor__<SiblingName>`) in the caller's
        // merged function table. The `new Child(x, y)` lowering then calls
        // `__ctor__Child(x, y)` in-line, running the ctor body against the
        // already-merged sibling state-variable slots (Task #197). The address
        // return value stays at the 20-byte zero placeholder that Task #83
        // already routes to self-offsets dispatch.
        let sibling_ctor_map: std::collections::HashMap<String, FunctionIR> = primary
            .iter()
            .filter_map(|c| {
                let ctor = c
                    .functions
                    .iter()
                    .find(|f| matches!(f.ty, FunctionTy::Constructor))?;
                Some((c.name.clone(), ctor.clone()))
            })
            .collect();
        let primary_contract_map: std::collections::HashMap<String, ContractIR> = primary
            .iter()
            .map(|c| (c.name.clone(), c.clone()))
            .collect();
        let primary_names: std::collections::HashSet<String> =
            primary.iter().map(|c| c.name.clone()).collect();

        // Task #126 — a primary contract's `fallback()` acts as a universal
        // catch-all dispatcher: every unknown method name falls through to
        // it. For interface-cast routing `Target(t).someMethod()` where
        // `TargetImpl` has only `fallback()` (no named external methods),
        // we must still treat `TargetImpl` as a valid implementor of the
        // `Target` interface so the sibling-merge pass pulls its fallback
        // body into the caller's function table. This mirrors Solidity's
        // own runtime semantics: the ABI dispatcher routes unknown
        // selectors to `fallback()` when present.
        let primary_has_fallback: std::collections::HashSet<String> = primary
            .iter()
            .filter(|c| {
                c.functions
                    .iter()
                    .any(|f| matches!(f.ty, FunctionTy::Fallback))
            })
            .map(|c| c.name.clone())
            .collect();

        // Task #115 — collect interface kind names and their external method
        // sets. An expression like `I(t).getR()` in contract `C` (where `I`
        // is an interface declared in the same source unit) is a
        // cross-contract call routed through an `address`-typed receiver.
        // At runtime the 20-byte zero placeholder triggers self-offsets
        // dispatch (see `handle_contract_call` / Task #83 branch), so the
        // callee method must live in the caller's merged function table.
        // We match the interface to any sibling primary whose public/external
        // method set is a superset of the interface's method names, and
        // include those siblings in the sibling merge below.
        //
        // This mirrors the `new B()` / `B(addr)` / `B public b;` patterns
        // already handled — without this hook, interface-typed dispatch
        // silently returns `Null` (the `invoke_native_contract` fallback for
        // unknown-hash calls), which then blows up inside `r.a` /
        // `r.b` member accesses downstream.
        let interface_methods: std::collections::HashMap<
            String,
            std::collections::HashSet<String>,
        > = pre_merge_contract_map
            .values()
            .filter(|c| matches!(c.kind, ContractKind::Interface))
            .map(|c| {
                (
                    c.name.clone(),
                    c.functions
                        .iter()
                        .filter(|f| {
                            matches!(f.ty, FunctionTy::Function)
                                && matches!(
                                    f.visibility,
                                    VisibilityKind::External | VisibilityKind::Public
                                )
                        })
                        .map(|f| f.name.clone())
                        .collect(),
                )
            })
            .collect();

        // Reverse map: interface name → list of primary contracts whose
        // method set covers the interface's method set. We pre-compute this
        // once so we don't re-walk the primary function tables per function
        // body.
        let primary_method_names: std::collections::HashMap<
            String,
            std::collections::HashSet<String>,
        > = primary
            .iter()
            .map(|c| {
                (
                    c.name.clone(),
                    c.functions
                        .iter()
                        .filter(|f| {
                            matches!(f.ty, FunctionTy::Function)
                                && matches!(
                                    f.visibility,
                                    VisibilityKind::External | VisibilityKind::Public
                                )
                        })
                        .map(|f| f.name.clone())
                        .collect(),
                )
            })
            .collect();

        let interface_impls: std::collections::HashMap<String, Vec<String>> =
            interface_methods
                .iter()
                .map(|(iface_name, iface_method_set)| {
                    let mut impls: Vec<String> = primary_method_names
                        .iter()
                        .filter_map(|(prim_name, prim_set)| {
                            // Task #126 — a primary with a `fallback()` catches
                            // any interface method that isn't explicitly declared,
                            // so it's always a valid implementor for sibling-
                            // merge purposes (at runtime the call routes through
                            // the merged `fallback` entry, which may itself
                            // revert — that revert is what we propagate to the
                            // caller's try/catch).
                            if iface_method_set.is_subset(prim_set)
                                || primary_has_fallback.contains(prim_name)
                            {
                                Some(prim_name.clone())
                            } else {
                                None
                            }
                        })
                        .collect();
                    // Deterministic order → reproducible bytecode offsets.
                    impls.sort();
                    (iface_name.clone(), impls)
                })
                .collect();

        let interface_names: std::collections::HashSet<String> =
            interface_methods.keys().cloned().collect();

        for contract in primary.iter_mut() {
            let mut referenced: std::collections::HashSet<String> =
                std::collections::HashSet::new();
            let mut iface_refs: std::collections::HashSet<String> =
                std::collections::HashSet::new();
            // Task #194 — collect method names statically resolvable from
            // low-level-call payloads like
            // `addr.call(abi.encodeWithSelector(bytes4(keccak256("m(T)"))))`,
            // `addr.call(abi.encodeWithSignature("m(T)", …))`, or
            // `addr.call(abi.encodeCall(Iface.m, …))`. Previously the
            // sibling-merge pass only detected references through `new X()`,
            // `X(addr)` casts, interface casts, and typed params/returns/
            // state-vars. A low-level `.call()` with a constant selector is
            // semantically identical to a typed `X(addr).m(…)` — the
            // compiler routes it through the zero-placeholder
            // `self_method_offsets` dispatch (see Task #83) — but without
            // this scan the target method never lands in the merged table
            // and the call silently returns `Null`.
            let mut low_level_method_refs: std::collections::HashSet<String> =
                std::collections::HashSet::new();
            for function in &contract.functions {
                if let Some(body) = function.body.as_ref() {
                    collect_new_contract_refs(body, &primary_names, &mut referenced);
                    // Task #115 — interface casts `I(expr)` in statements.
                    collect_interface_casts_stmt(body, &interface_names, &mut iface_refs);
                    // Task #194 — low-level calls whose payload encodes a
                    // statically resolvable method name.
                    collect_low_level_call_method_refs_stmt(
                        body,
                        &mut low_level_method_refs,
                    );
                }
                // Task K4 — function params/returns typed as a sibling contract
                // (e.g. `function bounce() external returns (B) {...}`, or
                // `function xfer(C to, ...)`) mean the function is wired to
                // call into the sibling. Merge so self-call routing can see
                // the target method at runtime.
                for p in function.parameters.iter().chain(function.returns.iter()) {
                    if primary_names.contains(&p.ty) {
                        referenced.insert(p.ty.clone());
                    }
                    // Task #115 — also scan for interface-typed parameters.
                    if interface_names.contains(&p.ty) {
                        iface_refs.insert(p.ty.clone());
                    }
                }
            }
            // Task K4 — also scan state-variable types and initializers.
            // `B public b;` means A is wired to call into B via the storage
            // slot without ever going through `new B()`. Without this hook,
            // K4 (cross-contract reentrancy) fails: `b.bounce()` routes
            // through `System.Contract.Call([0;20], "bounce", …)` which then
            // returns `Null` because B wasn't merged.
            for state in &contract.state_variables {
                if primary_names.contains(&state.ty) {
                    referenced.insert(state.ty.clone());
                }
                if interface_names.contains(&state.ty) {
                    iface_refs.insert(state.ty.clone());
                }
                if let Some(init) = state.initializer.as_ref() {
                    collect_new_refs_expr(init, &primary_names, &mut referenced);
                    collect_interface_casts_expr(init, &interface_names, &mut iface_refs);
                    collect_low_level_call_method_refs_expr(
                        init,
                        &mut low_level_method_refs,
                    );
                }
            }
            // Task #115 — expand interface references to the primary contracts
            // that implement them. Multiple primaries may satisfy the same
            // interface; merge all of them so dispatch sees any signature.
            for iface in &iface_refs {
                if let Some(impls) = interface_impls.get(iface) {
                    for prim in impls {
                        if prim != &contract.name {
                            referenced.insert(prim.clone());
                        }
                    }
                }
            }
            // Task #194 — expand low-level-call method references to every
            // sibling primary that declares a method of that name. When
            // multiple siblings satisfy the same name (e.g. both X and Y
            // declare `foo()`), merge all of them so the dispatcher sees the
            // union; which one actually fires at runtime is decided by the
            // caller's address (handled in `handle_contract_call`). We skip
            // the host contract itself — its methods are already visible
            // through normal dispatch.
            if !low_level_method_refs.is_empty() {
                for (prim_name, prim_methods) in &primary_method_names {
                    if prim_name == &contract.name {
                        continue;
                    }
                    if low_level_method_refs
                        .iter()
                        .any(|m| prim_methods.contains(m))
                    {
                        referenced.insert(prim_name.clone());
                    }
                }
            }
            // Task #206 — close over TRANSITIVE sibling references. The
            // zero-hash self-dispatch table is built from the caller
            // artifact's manifest only, so if `Client` references `Middle`
            // and `Middle` references `Target`, the merged `Client`
            // artifact must carry both `wrap` and `fail`. Without this
            // closure, the grandchild call silently falls through
            // `handle_contract_call`'s zero-hash branch and returns `Null`.
            let mut transitive_queue: Vec<String> = referenced.iter().cloned().collect();
            while let Some(sibling_name) = transitive_queue.pop() {
                let Some(sibling_contract) = primary_contract_map.get(&sibling_name) else {
                    continue;
                };
                let transitive_refs = collect_direct_sibling_contract_refs(
                    sibling_contract,
                    &primary_names,
                    &interface_names,
                    &interface_impls,
                    &primary_method_names,
                );
                for transitive in transitive_refs {
                    if transitive == contract.name {
                        continue;
                    }
                    if referenced.insert(transitive.clone()) {
                        transitive_queue.push(transitive);
                    }
                }
            }
            referenced.remove(&contract.name);
            if referenced.is_empty() {
                continue;
            }
            let mut existing_sigs: std::collections::HashSet<(String, usize)> = contract
                .functions
                .iter()
                .map(|f| (f.name.clone(), f.parameters.len()))
                .collect();
            // Deterministic order → reproducible bytecode offsets.
            let mut sibling_names: Vec<String> = referenced.into_iter().collect();
            sibling_names.sort();
            for sibling_name in &sibling_names {
                let Some(sibling_fns) = sibling_fn_map.get(sibling_name) else {
                    continue;
                };
                for sibling_fn in sibling_fns {
                    let sig = (sibling_fn.name.clone(), sibling_fn.parameters.len());
                    if existing_sigs.insert(sig) {
                        contract.functions.push(sibling_fn.clone());
                    }
                }
                // Pull in the sibling's modifier definitions so the merged
                // external bodies can still resolve their `onlyOwner` /
                // `onlyRole` / etc. references when the host's modifier-
                // expansion pass runs. Modifiers don't conflict on plain
                // function-signature equality (different `ty`), so we track
                // them in a small local set keyed on (name, arity).
                if let Some(sibling_modifiers) = sibling_modifier_map.get(sibling_name) {
                    for sibling_mod in sibling_modifiers {
                        let already_present = contract.functions.iter().any(|existing| {
                            matches!(existing.ty, FunctionTy::Modifier)
                                && existing.name == sibling_mod.name
                                && existing.parameters.len() == sibling_mod.parameters.len()
                        });
                        if !already_present {
                            contract.functions.push(sibling_mod.clone());
                        }
                    }
                }
                // Also pull in the sibling's `using` directives. Merged
                // external bodies may rely on contract-scope `using L for T;`
                // declarations declared in the sibling — e.g. Gnosis Safe
                // declares `using SafeMath for uint256;` and its
                // `execTransaction` body calls `gas.max(other)`. When
                // CompatibilityFallbackHandler triggers a sibling-merge of
                // Safe's external methods, the `execTransaction` body needs
                // its `using SafeMath` directive to remain in scope or the
                // IR-lowering pass reports "member-style call '...' requires
                // an explicit `using` directive". We dedup on
                // (target_type, function_names) so reinjected duplicates
                // don't grow the table.
                if let Some(sibling_contract) = pre_merge_contract_map.get(sibling_name) {
                    for directive in &sibling_contract.using_directives {
                        if !contract.using_directives.iter().any(|existing| {
                            existing.target_type == directive.target_type
                                && existing.function_names == directive.function_names
                        }) {
                            contract.using_directives.push(directive.clone());
                        }
                    }
                    for lib_name in &sibling_contract.using_for_libraries {
                        if !contract.using_for_libraries.contains(lib_name) {
                            contract.using_for_libraries.push(lib_name.clone());
                        }
                    }
                    contract.has_using_for_star =
                        contract.has_using_for_star || sibling_contract.has_using_for_star;
                    contract.has_using_function_list = contract.has_using_function_list
                        || sibling_contract.has_using_function_list;
                }
            }

            // Task #197 — merge sibling state variables after their external
            // functions. Without this, a merged stateful method like
            // `Mock.balanceOf` → `return _bal[a]` would resolve `_bal`
            // against the caller's (Client's) `state_index_map`, find no
            // match, and fall through `variable.rs::lower_variable_expression`'s
            // final compatibility arm which pushes `Integer(0)` as a neutral
            // placeholder. Downstream SIZE/PICKITEM opcodes then fault on
            // the scalar, surfacing as "SIZE: unsupported type" at runtime.
            //
            // Storage-key derivation is name-based (see
            // `value_types.rs::compute_state_slot`), so merging Mock's
            // `_bal` into Client produces the same keccak-derived slot
            // that Mock.mint writes to — the cross-contract read lands on
            // the same storage entry. Host-wins-on-collision preserves any
            // state variable the caller already declares.
            let mut existing_state_names: std::collections::HashSet<String> = contract
                .state_variables
                .iter()
                .filter_map(|s| s.name.clone())
                .collect();
            for sibling_name in &sibling_names {
                let Some(sibling_states) = sibling_state_map.get(sibling_name) else {
                    continue;
                };
                for sibling_state in sibling_states {
                    if let Some(name) = sibling_state.name.as_ref() {
                        if existing_state_names.insert(name.clone()) {
                            contract.state_variables.push(sibling_state.clone());
                        } else if let Some(existing) = contract
                            .state_variables
                            .iter()
                            .find(|s| s.name.as_deref() == Some(name.as_str()))
                        {
                            // Storage-soundness guard — slots are derived
                            // from the BARE variable name (`sha256(name)`,
                            // see `storage_key::compute_state_slot`), so a
                            // host/sibling pair declaring the same name with
                            // DIFFERENT types would silently collapse two
                            // semantically distinct lvalues onto one slot
                            // (e.g. a sibling's `mapping(address=>uint256)
                            // _bal` aliasing the host's scalar `uint256
                            // _bal`), miscompiling both. Same-name SAME-type
                            // sharing stays allowed: that is the documented
                            // Task #197 design (merged sibling bodies must
                            // hit the same name-keyed slot).
                            if normalize_state_type_for_merge(&existing.ty)
                                != normalize_state_type_for_merge(&sibling_state.ty)
                            {
                                return Err(SolidityError::analysis(format!(
                                    "state variable '{name}' is declared with conflicting types \
                                     across merged contracts: '{}' in '{}' vs '{}' in '{sibling_name}'. \
                                     Storage slots are derived from the bare variable name, so both \
                                     declarations would silently alias the same storage entry; \
                                     rename one of the variables.",
                                    existing.ty, contract.name, sibling_state.ty
                                )));
                            }
                        }
                    }
                }
            }

            // Task #198 — merge sibling constructors as name-mangled internal
            // regular functions so the caller's `new Child(args)` lowering can
            // invoke the ctor body in-line. Without this, `new Child(x, y)`
            // silently drops its args and the follow-up `c.a()` / `c.b()`
            // reads land on uninitialized storage (all zeros). Re-typing from
            // `Constructor` to `Function` prevents the caller's own `_deploy`
            // prologue from accidentally calling the merged entry at deploy
            // time (constructor_indices is populated by FunctionKind, so
            // Regular entries are skipped there).
            for sibling_name in &sibling_names {
                let Some(sibling_ctor) = sibling_ctor_map.get(sibling_name) else {
                    continue;
                };
                let mangled_name = format!("__ctor__{sibling_name}");
                let sig = (mangled_name.clone(), sibling_ctor.parameters.len());
                if !existing_sigs.insert(sig) {
                    continue;
                }
                let mut cloned = sibling_ctor.clone();
                cloned.name = mangled_name;
                cloned.ty = FunctionTy::Function;
                cloned.visibility = VisibilityKind::Internal;
                // Base-constructor invocations (`base_or_modifiers`) were
                // already resolved by `apply_modifiers_and_base_constructors`
                // in the owning contract's pipeline; clear the residue so the
                // caller's modifier-application pass (which ran before this
                // merge) doesn't re-expand anything.
                cloned.base_or_modifiers.clear();
                contract.functions.push(cloned);
            }
        }
    }

    // Make non-inherited enum/struct namespaces visible across compilation
    // units so expressions like `Enum.Operation.DelegateCall` can resolve even
    // when the defining type lives in another top-level contract/library file.
    if has_primary {
        let shared_type_defs: Vec<(String, Vec<StructIR>, Vec<EnumIR>)> = pre_merge_contract_map
            .values()
            .filter(|contract| {
                !matches!(contract.kind, ContractKind::Library)
                    || !is_builtin_library_name(contract.name.as_str())
            })
            .map(|contract| {
                (
                    contract.name.clone(),
                    contract.structs.clone(),
                    contract.enums.clone(),
                )
            })
            .collect();

        for contract in primary.iter_mut() {
            let mut seen_structs: std::collections::HashSet<String> = contract
                .structs
                .iter()
                .map(|item| item.name.to_ascii_lowercase())
                .collect();
            let mut seen_enums: std::collections::HashSet<String> = contract
                .enums
                .iter()
                .map(|item| item.name.to_ascii_lowercase())
                .collect();

            for (owner_name, structs, enums) in &shared_type_defs {
                if owner_name == &contract.name {
                    continue;
                }
                for item in structs {
                    let key = item.name.to_ascii_lowercase();
                    if seen_structs.insert(key) {
                        contract.structs.push(item.clone());
                    }
                }
                for item in enums {
                    let key = item.name.to_ascii_lowercase();
                    if seen_enums.insert(key) {
                        contract.enums.push(item.clone());
                    }
                }
            }
        }
    }

    // Build a lookup map for inheritance flattening and modifier expansion.
    let contract_map: std::collections::HashMap<String, ContractIR> = primary
        .iter()
        .chain(fallback.iter())
        .map(|contract| (contract.name.clone(), contract.clone()))
        .collect();

    // Task #106 — gather struct fields across all contracts so canonical
    // signatures can expand struct params into their `(field1,field2,...)` tuple
    // form per the EVM ABI spec. Without this, the selector for
    // `f(P memory p)` where `struct P { uint256 a; bool b; }` is computed from
    // `f(P)` — which does not match the Solidity-spec selector for
    // `f((uint256,bool))`.
    let mut struct_fields_map: std::collections::HashMap<
        String,
        Vec<(String, String)>,
    > = std::collections::HashMap::new();
    for contract in contract_map.values() {
        for struct_def in &contract.structs {
            let entries: Vec<(String, String)> = struct_def
                .fields
                .iter()
                .map(|f| (f.name.clone(), f.ty.clone()))
                .collect();
            struct_fields_map
                .entry(struct_def.name.clone())
                .or_insert(entries);
        }
    }

    // Build a shared selector registry so `.selector` expressions can resolve against
    // any contract/interface visible to this compilation unit (including those defined
    // after the primary contract in the same file).
    // Every visible type name (contract/interface/library) — contract-typed
    // params resolve to `address` for ABI canonicalization.
    let registry_contract_types: Vec<String> =
        contract_map.values().map(|c| c.name.clone()).collect();
    let mut type_method_selectors: std::collections::HashMap<
        String,
        std::collections::HashMap<String, Vec<[u8; 4]>>,
    > = std::collections::HashMap::new();
    let mut interface_types: std::collections::HashSet<String> = std::collections::HashSet::new();
    for contract in contract_map.values() {
        if matches!(contract.kind, ContractKind::Interface) {
            interface_types.insert(contract.name.clone());
        }

        // When building selector lookups for `.selector` / `.interfaceId`, include inherited
        // interface methods as part of the derived interface. This matches Solidity behavior
        // and supports patterns like `type(IChild).interfaceId` where `IChild is IParent`.
        let selector_contract = match contract.kind {
            ContractKind::Contract | ContractKind::AbstractContract | ContractKind::Interface => {
                flatten_contract_inheritance(contract.clone(), &contract_map)
                    .map(|(ir, _warnings)| ir)
                    .unwrap_or_else(|_| contract.clone())
            }
            ContractKind::Library => contract.clone(),
        };

        let mut per_type: std::collections::HashMap<String, Vec<[u8; 4]>> =
            std::collections::HashMap::new();

        // Resolve each `.selector` parameter through the SAME canonicalization as
        // the manifest selector (`FunctionMetadata.selector`, built via
        // `NeoType::canonical_abi_type` in convert/functions.rs): structs expand to
        // tuples, enums render as `uint8`, integer widths are explicit. The two
        // paths must produce identical selectors — both drive on-chain dispatch and
        // a contract's `this.f.selector` must match what external callers compute.
        let sel_struct_types: Vec<StructTypeMetadata> = selector_contract
            .structs
            .iter()
            .map(|s| StructTypeMetadata {
                name: s.name.clone(),
                fields: s
                    .fields
                    .iter()
                    .map(|f| NeoStructFieldMetadata {
                        name: f.name.clone(),
                        ty: f.ty.clone(),
                    })
                    .collect(),
            })
            .collect();
        let sel_enum_types: Vec<EnumTypeMetadata> = selector_contract
            .enums
            .iter()
            .map(|e| EnumTypeMetadata {
                name: e.name.clone(),
                variants: e.values.len(),
            })
            .collect();

        for function in &selector_contract.functions {
            if !matches!(function.ty, FunctionTy::Function) {
                continue;
            }

            if !matches!(
                function.visibility,
                VisibilityKind::External | VisibilityKind::Public
            ) {
                continue;
            }

            let param_signatures: Vec<String> = function
                .parameters
                .iter()
                .map(|param| {
                    match NeoType::from_solidity(
                        &param.ty,
                        &sel_struct_types,
                        &sel_enum_types,
                        &registry_contract_types,
                    ) {
                        Ok(neo_type) => neo_type.canonical_abi_type(),
                        // Fall back to the struct-aware string canonicalizer only
                        // when the type cannot be resolved (keeps prior behavior).
                        Err(_) => crate::utils::canonical_param_type_with_structs(
                            &param.ty,
                            &struct_fields_map,
                        ),
                    }
                })
                .collect();
            let selector = compute_function_selector(&function.name, &param_signatures);
            per_type
                .entry(function.name.clone())
                .or_default()
                .push(selector);
        }

        type_method_selectors.insert(contract.name.clone(), per_type);
    }
    let selector_registry = std::sync::Arc::new(SelectorRegistry {
        type_method_selectors,
        interface_types,
    });

    let mut selected = if has_primary { primary } else { fallback };

    if selected.is_empty() {
        return Ok(Vec::new());
    }

    let mut metadatas = Vec::new();
    for contract in selected.drain(..) {
        let (mut flattened, flatten_warnings) =
            flatten_contract_inheritance(contract, &contract_map)?;
        // Merge user-defined libraries AFTER inheritance flattening so the
        // flattener doesn't mistake cloned library helpers for inheritance
        // overrides. The final flattened contract still needs the library
        // helpers/types present before `convert_contract` so direct library
        // calls and `using for` member-style calls lower correctly.
        if has_primary && !libraries.is_empty() {
            for lib in &libraries {
                flattened.functions.extend(lib.functions.clone());
                flattened.state_variables.extend(lib.state_variables.clone());
                flattened.structs.extend(lib.structs.clone());
                flattened.enums.extend(lib.enums.clone());
                // Merge the library's own `using` directives into the host.
                // Library function bodies are inlined verbatim above, so any
                // member-style call resolved by a library-scope `using` (e.g.
                // OZ Strings.sol declares `using SafeCast for *;` then calls
                // `someBool.toUint()` inside its own helpers) must continue to
                // resolve after the body lives inside the host contract.
                // Without this, the IR-lowering pass at
                // `src/ir/expressions/calls/member_calls.rs:432` reports
                // "member-style call '...' requires an explicit `using`
                // directive" for the inlined library code.
                for directive in &lib.using_directives {
                    if !flattened.using_directives.iter().any(|existing| {
                        existing.target_type == directive.target_type
                            && existing.function_names == directive.function_names
                    }) {
                        flattened.using_directives.push(directive.clone());
                    }
                }
                for lib_name in &lib.using_for_libraries {
                    if !flattened.using_for_libraries.contains(lib_name) {
                        flattened.using_for_libraries.push(lib_name.clone());
                    }
                }
                flattened.has_using_for_star =
                    flattened.has_using_for_star || lib.has_using_for_star;
                flattened.has_using_function_list =
                    flattened.has_using_function_list || lib.has_using_function_list;
            }
        }
        apply_modifiers_and_base_constructors(&mut flattened, &contract_map)?;
        let mut metadata = convert_contract(
            flattened,
            &[],
            &contract_types,
            selector_registry.clone(),
        );
        metadata.flatten_warnings = flatten_warnings;
        metadatas.push(metadata);
    }

    Ok(metadatas)
}

/// Task #83 — walk a statement tree collecting every `new X()` target name
/// that matches a known primary contract. Mirrors the ast_scan permissions
/// pass but accumulates matches instead of returning a boolean.
fn collect_new_contract_refs(
    stmt: &Statement,
    primary_names: &std::collections::HashSet<String>,
    sink: &mut std::collections::HashSet<String>,
) {
    stacker::maybe_grow(32 * 1024, 1024 * 1024, || {
        collect_new_contract_refs_inner(stmt, primary_names, sink)
    })
}

fn collect_new_contract_refs_inner(
    stmt: &Statement,
    primary_names: &std::collections::HashSet<String>,
    sink: &mut std::collections::HashSet<String>,
) {
    match stmt {
        Statement::Block { statements, .. } => {
            for s in statements {
                collect_new_contract_refs(s, primary_names, sink);
            }
        }
        Statement::If(_, cond, t, e) => {
            collect_new_refs_expr(cond, primary_names, sink);
            collect_new_contract_refs(t, primary_names, sink);
            if let Some(s) = e {
                collect_new_contract_refs(s, primary_names, sink);
            }
        }
        Statement::While(_, cond, body) | Statement::DoWhile(_, body, cond) => {
            collect_new_refs_expr(cond, primary_names, sink);
            collect_new_contract_refs(body, primary_names, sink);
        }
        Statement::Expression(_, expr) => collect_new_refs_expr(expr, primary_names, sink),
        Statement::VariableDefinition(_, _, Some(expr)) => {
            collect_new_refs_expr(expr, primary_names, sink);
        }
        Statement::VariableDefinition(_, _, None) => {}
        Statement::For(_, i, c, n, b) => {
            if let Some(s) = i {
                collect_new_contract_refs(s, primary_names, sink);
            }
            if let Some(e) = c {
                collect_new_refs_expr(e, primary_names, sink);
            }
            if let Some(e) = n {
                collect_new_refs_expr(e, primary_names, sink);
            }
            if let Some(s) = b {
                collect_new_contract_refs(s, primary_names, sink);
            }
        }
        Statement::Return(_, Some(expr)) | Statement::Emit(_, expr) => {
            collect_new_refs_expr(expr, primary_names, sink);
        }
        Statement::Revert(_, _, args) => {
            for e in args {
                collect_new_refs_expr(e, primary_names, sink);
            }
        }
        Statement::Try(_, expr, returns, clauses) => {
            collect_new_refs_expr(expr, primary_names, sink);
            if let Some((_, b)) = returns {
                collect_new_contract_refs(b, primary_names, sink);
            }
            for c in clauses {
                match c {
                    CatchClause::Simple(_, _, b) | CatchClause::Named(_, _, _, b) => {
                        collect_new_contract_refs(b, primary_names, sink);
                    }
                }
            }
        }
        _ => {}
    }
}

/// Task #115 — statement-level walk that collects every `I(expr).method(...)`
/// interface-cast receiver where `I` is a known interface declared in the
/// same source unit. Mirrors `collect_new_contract_refs` but tracks a
/// different alphabet of names (interface kinds, not primary contracts).
fn collect_interface_casts_stmt(
    stmt: &Statement,
    interface_names: &std::collections::HashSet<String>,
    sink: &mut std::collections::HashSet<String>,
) {
    stacker::maybe_grow(32 * 1024, 1024 * 1024, || {
        collect_interface_casts_stmt_inner(stmt, interface_names, sink)
    })
}

fn collect_interface_casts_stmt_inner(
    stmt: &Statement,
    interface_names: &std::collections::HashSet<String>,
    sink: &mut std::collections::HashSet<String>,
) {
    match stmt {
        Statement::Block { statements, .. } => {
            for s in statements {
                collect_interface_casts_stmt(s, interface_names, sink);
            }
        }
        Statement::If(_, cond, t, e) => {
            collect_interface_casts_expr(cond, interface_names, sink);
            collect_interface_casts_stmt(t, interface_names, sink);
            if let Some(s) = e {
                collect_interface_casts_stmt(s, interface_names, sink);
            }
        }
        Statement::While(_, cond, body) | Statement::DoWhile(_, body, cond) => {
            collect_interface_casts_expr(cond, interface_names, sink);
            collect_interface_casts_stmt(body, interface_names, sink);
        }
        Statement::Expression(_, expr) => {
            collect_interface_casts_expr(expr, interface_names, sink)
        }
        Statement::VariableDefinition(_, _, Some(expr)) => {
            collect_interface_casts_expr(expr, interface_names, sink);
        }
        Statement::VariableDefinition(_, _, None) => {}
        Statement::For(_, i, c, n, b) => {
            if let Some(s) = i {
                collect_interface_casts_stmt(s, interface_names, sink);
            }
            if let Some(e) = c {
                collect_interface_casts_expr(e, interface_names, sink);
            }
            if let Some(e) = n {
                collect_interface_casts_expr(e, interface_names, sink);
            }
            if let Some(s) = b {
                collect_interface_casts_stmt(s, interface_names, sink);
            }
        }
        Statement::Return(_, Some(expr)) | Statement::Emit(_, expr) => {
            collect_interface_casts_expr(expr, interface_names, sink);
        }
        Statement::Revert(_, _, args) => {
            for e in args {
                collect_interface_casts_expr(e, interface_names, sink);
            }
        }
        Statement::Try(_, expr, returns, clauses) => {
            collect_interface_casts_expr(expr, interface_names, sink);
            if let Some((_, b)) = returns {
                collect_interface_casts_stmt(b, interface_names, sink);
            }
            for c in clauses {
                match c {
                    CatchClause::Simple(_, _, b) | CatchClause::Named(_, _, _, b) => {
                        collect_interface_casts_stmt(b, interface_names, sink);
                    }
                }
            }
        }
        _ => {}
    }
}

/// Task #115 — expression-level half of `collect_interface_casts_stmt`.
/// Matches `FunctionCall(Variable(I), _)` where `I` is a known interface
/// name. The parser emits this shape for interface casts like `I(addr)`.
fn collect_interface_casts_expr(
    expr: &Expression,
    interface_names: &std::collections::HashSet<String>,
    sink: &mut std::collections::HashSet<String>,
) {
    stacker::maybe_grow(32 * 1024, 1024 * 1024, || {
        collect_interface_casts_expr_inner(expr, interface_names, sink)
    })
}

fn collect_interface_casts_expr_inner(
    expr: &Expression,
    interface_names: &std::collections::HashSet<String>,
    sink: &mut std::collections::HashSet<String>,
) {
    if let Expression::FunctionCall(_, func, _) = expr {
        if let Expression::Variable(id) = func.as_ref() {
            if interface_names.contains(&id.name) {
                sink.insert(id.name.clone());
            }
        }
    }
    match expr {
        Expression::New(_, i)
        | Expression::Parenthesis(_, i)
        | Expression::MemberAccess(_, i, _)
        | Expression::Delete(_, i) => collect_interface_casts_expr(i, interface_names, sink),
        Expression::FunctionCall(_, func, args) => {
            collect_interface_casts_expr(func, interface_names, sink);
            for a in args {
                collect_interface_casts_expr(a, interface_names, sink);
            }
        }
        // Task #125 — symmetric fix with `collect_new_refs_expr`: the
        // `try-expr { success-block }` lowering parks the call inside a
        // FunctionCallBlock, so interface-cast chains such as
        // `try I(t).getR() returns (R r) { ... } catch ...` would also
        // silently skip the sibling-merge trigger without this arm.
        Expression::FunctionCallBlock(_, call, block) => {
            collect_interface_casts_expr(call, interface_names, sink);
            collect_interface_casts_stmt(block, interface_names, sink);
        }
        Expression::NamedFunctionCall(_, func, args) => {
            collect_interface_casts_expr(func, interface_names, sink);
            for a in args {
                collect_interface_casts_expr(&a.expr, interface_names, sink);
            }
        }
        Expression::ArraySubscript(_, a, b) => {
            collect_interface_casts_expr(a, interface_names, sink);
            if let Some(e) = b {
                collect_interface_casts_expr(e, interface_names, sink);
            }
        }
        Expression::ConditionalOperator(_, c, a, b) => {
            collect_interface_casts_expr(c, interface_names, sink);
            collect_interface_casts_expr(a, interface_names, sink);
            collect_interface_casts_expr(b, interface_names, sink);
        }
        Expression::Assign(_, a, b) => {
            collect_interface_casts_expr(a, interface_names, sink);
            collect_interface_casts_expr(b, interface_names, sink);
        }
        Expression::ArrayLiteral(_, values) => {
            for v in values {
                collect_interface_casts_expr(v, interface_names, sink);
            }
        }
        _ => {}
    }
}

/// Task #83 — expression-level half of `collect_new_contract_refs`. Matches
/// `Expression::New(FunctionCall(Variable(name), _))` and recurses through
/// the usual expression containers.
fn collect_new_refs_expr(
    expr: &Expression,
    primary_names: &std::collections::HashSet<String>,
    sink: &mut std::collections::HashSet<String>,
) {
    stacker::maybe_grow(32 * 1024, 1024 * 1024, || {
        collect_new_refs_expr_inner(expr, primary_names, sink)
    })
}

fn collect_new_refs_expr_inner(
    expr: &Expression,
    primary_names: &std::collections::HashSet<String>,
    sink: &mut std::collections::HashSet<String>,
) {
    if let Expression::New(_, inner) = expr {
        if let Expression::FunctionCall(_, func, _) = inner.as_ref() {
            if let Expression::Variable(id) = func.as_ref() {
                if primary_names.contains(&id.name) {
                    sink.insert(id.name.clone());
                }
            }
        }
    }
    // Task K4 — `B(addr)` cast expressions mean A plans to call into B
    // through an address typed as B. The parser lowers these as
    // `FunctionCall(Variable("B"), [addr])`, identical in shape to a
    // `B.staticCall(addr)` helper, so we match on that before the generic
    // FunctionCall recursion below picks off the args.
    if let Expression::FunctionCall(_, func, _) = expr {
        if let Expression::Variable(id) = func.as_ref() {
            if primary_names.contains(&id.name) {
                sink.insert(id.name.clone());
            }
        }
    }
    match expr {
        Expression::New(_, i)
        | Expression::Parenthesis(_, i)
        | Expression::MemberAccess(_, i, _)
        | Expression::Delete(_, i) => collect_new_refs_expr(i, primary_names, sink),
        Expression::FunctionCall(_, func, args) => {
            collect_new_refs_expr(func, primary_names, sink);
            for a in args {
                collect_new_refs_expr(a, primary_names, sink);
            }
        }
        // Task #125 — `try X { ... } catch ...` parses the leading
        // `try-expr { success-block }` as `FunctionCallBlock(call, block)`
        // on the expression-tree side, so `try Target(t).willRevert() { ... }`
        // arrives here with `call = FunctionCall(MemberAccess(FunctionCall(
        // Variable("Target"), [t]), "willRevert"), [])` wrapped in a
        // FunctionCallBlock. Without this arm the walker's `_ => {}`
        // silently dropped the cast chain, so `Target` never made the
        // sibling-merge `referenced` set and `willRevert` never entered
        // C's `self_method_offsets` table — the runtime's
        // `handle_contract_call` then fell through to `invoke_native_contract`
        // which returned `Null` for the zero-placeholder hash, so the
        // target's `revert("bad")` was never dispatched and the outer
        // try-arm fired with its literal "ok" instead of the expected
        // `catch Error(string)` binding. The success block body is a
        // Statement, not an Expression, so we use the statement walker
        // for it — symmetric with the `Statement::Try` arm above.
        Expression::FunctionCallBlock(_, call, block) => {
            collect_new_refs_expr(call, primary_names, sink);
            collect_new_contract_refs(block, primary_names, sink);
        }
        Expression::NamedFunctionCall(_, func, args) => {
            collect_new_refs_expr(func, primary_names, sink);
            for a in args {
                collect_new_refs_expr(&a.expr, primary_names, sink);
            }
        }
        Expression::ArraySubscript(_, a, b) => {
            collect_new_refs_expr(a, primary_names, sink);
            if let Some(e) = b {
                collect_new_refs_expr(e, primary_names, sink);
            }
        }
        Expression::ConditionalOperator(_, c, a, b) => {
            collect_new_refs_expr(c, primary_names, sink);
            collect_new_refs_expr(a, primary_names, sink);
            collect_new_refs_expr(b, primary_names, sink);
        }
        Expression::Assign(_, a, b) => {
            collect_new_refs_expr(a, primary_names, sink);
            collect_new_refs_expr(b, primary_names, sink);
        }
        Expression::ArrayLiteral(_, values) => {
            for v in values {
                collect_new_refs_expr(v, primary_names, sink);
            }
        }
        _ => {}
    }
}

/// Task #194 — statement walker that collects statically resolvable method
/// names from low-level `addr.call(...)` / `addr.staticcall(...)` payloads.
/// Mirrors the shape of `collect_new_contract_refs` but feeds a different
/// alphabet: plain method names (e.g. `"getValue"`) that the sibling-merge
/// pass later cross-references against every sibling primary's declared
/// method set.
fn collect_low_level_call_method_refs_stmt(
    stmt: &Statement,
    sink: &mut std::collections::HashSet<String>,
) {
    stacker::maybe_grow(32 * 1024, 1024 * 1024, || {
        collect_low_level_call_method_refs_stmt_inner(stmt, sink)
    })
}

fn collect_low_level_call_method_refs_stmt_inner(
    stmt: &Statement,
    sink: &mut std::collections::HashSet<String>,
) {
    match stmt {
        Statement::Block { statements, .. } => {
            for s in statements {
                collect_low_level_call_method_refs_stmt(s, sink);
            }
        }
        Statement::If(_, cond, t, e) => {
            collect_low_level_call_method_refs_expr(cond, sink);
            collect_low_level_call_method_refs_stmt(t, sink);
            if let Some(s) = e {
                collect_low_level_call_method_refs_stmt(s, sink);
            }
        }
        Statement::While(_, cond, body) | Statement::DoWhile(_, body, cond) => {
            collect_low_level_call_method_refs_expr(cond, sink);
            collect_low_level_call_method_refs_stmt(body, sink);
        }
        Statement::Expression(_, expr) => {
            collect_low_level_call_method_refs_expr(expr, sink);
        }
        Statement::VariableDefinition(_, _, Some(expr)) => {
            collect_low_level_call_method_refs_expr(expr, sink);
        }
        Statement::VariableDefinition(_, _, None) => {}
        Statement::For(_, i, c, n, b) => {
            if let Some(s) = i {
                collect_low_level_call_method_refs_stmt(s, sink);
            }
            if let Some(e) = c {
                collect_low_level_call_method_refs_expr(e, sink);
            }
            if let Some(e) = n {
                collect_low_level_call_method_refs_expr(e, sink);
            }
            if let Some(s) = b {
                collect_low_level_call_method_refs_stmt(s, sink);
            }
        }
        Statement::Return(_, Some(expr)) | Statement::Emit(_, expr) => {
            collect_low_level_call_method_refs_expr(expr, sink);
        }
        Statement::Revert(_, _, args) => {
            for e in args {
                collect_low_level_call_method_refs_expr(e, sink);
            }
        }
        Statement::Try(_, expr, returns, clauses) => {
            collect_low_level_call_method_refs_expr(expr, sink);
            if let Some((_, b)) = returns {
                collect_low_level_call_method_refs_stmt(b, sink);
            }
            for c in clauses {
                match c {
                    CatchClause::Simple(_, _, b) | CatchClause::Named(_, _, _, b) => {
                        collect_low_level_call_method_refs_stmt(b, sink);
                    }
                }
            }
        }
        _ => {}
    }
}

/// Task #194 — expression walker that recognises `<receiver>.call(payload)`
/// / `<receiver>.staticcall(payload)` / `<receiver>.delegatecall(payload)`
/// shapes, then peels the `abi.encodeWith{Selector,Signature}` /
/// `abi.encodeCall` wrapper on the payload to extract the Solidity method
/// name when it can be resolved at compile time. The extracted name is
/// later matched against every sibling primary's declared public/external
/// method set.
///
/// Static resolution handles:
///   - `abi.encodeWithSignature("m(T)", …)` — literal signature string,
///     name taken from the pre-`(` fragment.
///   - `abi.encodeWithSelector(bytes4(keccak256("m(T)")))` —
///     compile-time hash of a literal signature string.
///   - `abi.encodeWithSelector(Type.method.selector)` /
///     `abi.encodeCall(Type.method, (…))` — static member-access.
///
/// Runtime-computed selectors (e.g. `abi.encodeWithSelector(someRuntimeSel,
/// …)`) stay unresolved and yield nothing — the compiler's caller-side
/// lowering similarly cannot route those through sibling-merge, so they
/// fall through to the real cross-contract dispatch path.
fn collect_low_level_call_method_refs_expr(
    expr: &Expression,
    sink: &mut std::collections::HashSet<String>,
) {
    stacker::maybe_grow(32 * 1024, 1024 * 1024, || {
        collect_low_level_call_method_refs_expr_inner(expr, sink)
    })
}

fn collect_low_level_call_method_refs_expr_inner(
    expr: &Expression,
    sink: &mut std::collections::HashSet<String>,
) {
    if let Expression::FunctionCall(_, func, args) = expr {
        if args.len() == 1 {
            if let Expression::MemberAccess(_, _recv, member) = func.as_ref() {
                let is_low_level = matches!(
                    member.name.as_str(),
                    "call" | "staticcall" | "delegatecall"
                );
                if is_low_level {
                    if let Some(name) = extract_static_method_name_from_payload(&args[0]) {
                        if !name.trim().is_empty() {
                            sink.insert(name);
                        }
                    }
                }
            }
        }
    }
    match expr {
        Expression::New(_, i)
        | Expression::Parenthesis(_, i)
        | Expression::MemberAccess(_, i, _)
        | Expression::Delete(_, i) => collect_low_level_call_method_refs_expr(i, sink),
        Expression::FunctionCall(_, func, args) => {
            collect_low_level_call_method_refs_expr(func, sink);
            for a in args {
                collect_low_level_call_method_refs_expr(a, sink);
            }
        }
        Expression::FunctionCallBlock(_, call, block) => {
            collect_low_level_call_method_refs_expr(call, sink);
            collect_low_level_call_method_refs_stmt(block, sink);
        }
        Expression::NamedFunctionCall(_, func, args) => {
            collect_low_level_call_method_refs_expr(func, sink);
            for a in args {
                collect_low_level_call_method_refs_expr(&a.expr, sink);
            }
        }
        Expression::ArraySubscript(_, a, b) => {
            collect_low_level_call_method_refs_expr(a, sink);
            if let Some(e) = b {
                collect_low_level_call_method_refs_expr(e, sink);
            }
        }
        Expression::ConditionalOperator(_, c, a, b) => {
            collect_low_level_call_method_refs_expr(c, sink);
            collect_low_level_call_method_refs_expr(a, sink);
            collect_low_level_call_method_refs_expr(b, sink);
        }
        Expression::Assign(_, a, b) => {
            collect_low_level_call_method_refs_expr(a, sink);
            collect_low_level_call_method_refs_expr(b, sink);
        }
        Expression::ArrayLiteral(_, values) => {
            for v in values {
                collect_low_level_call_method_refs_expr(v, sink);
            }
        }
        _ => {}
    }
}

/// Task #194 — peel the `abi.encodeWith{Selector,Signature}` /
/// `abi.encodeCall` wrapper of a low-level call payload to extract the
/// Solidity method name when it is statically resolvable.
fn extract_static_method_name_from_payload(expr: &Expression) -> Option<String> {
    stacker::maybe_grow(32 * 1024, 1024 * 1024, || {
        extract_static_method_name_from_payload_inner(expr)
    })
}

fn extract_static_method_name_from_payload_inner(expr: &Expression) -> Option<String> {
    match expr {
        Expression::Parenthesis(_, inner) => extract_static_method_name_from_payload(inner),
        Expression::FunctionCall(_, func, args) => {
            // `bytes(<inner>)` / `bytes4(<inner>)` / `string(<inner>)` casts
            // are transparent — recurse through them.
            if args.len() == 1 {
                if let Expression::Variable(id) = func.as_ref() {
                    if id.name == "bytes" || id.name == "string" {
                        return extract_static_method_name_from_payload(&args[0]);
                    }
                }
                if matches!(func.as_ref(), Expression::Type(_, _)) {
                    return extract_static_method_name_from_payload(&args[0]);
                }
            }

            let Expression::MemberAccess(_, inner, member) = func.as_ref() else {
                return None;
            };

            if !matches!(inner.as_ref(), Expression::Variable(id) if id.name == "abi") {
                return None;
            }

            match member.name.as_str() {
                "encodeWithSignature" => {
                    let first = args.first()?;
                    let signature = extract_static_signature_string(first)?;
                    let name = signature
                        .split('(')
                        .next()
                        .unwrap_or(signature.as_str())
                        .trim()
                        .to_string();
                    if name.is_empty() {
                        None
                    } else {
                        Some(name)
                    }
                }
                "encodeWithSelector" => {
                    let first = args.first()?;
                    extract_static_selector_method_name(first)
                }
                "encodeCall" => {
                    // `abi.encodeCall(X.method, (…))` — member-access
                    // function reference resolves to the member name.
                    let first = args.first()?;
                    extract_static_encode_call_method_name(first)
                }
                _ => None,
            }
        }
        _ => None,
    }
}

/// Task #194 — analogue of `resolve_selector_method_name` in
/// `ir/build/selectors.rs` that operates on raw `solang_parser::pt`
/// expressions (the analyse pass runs before the IR is built).
fn extract_static_selector_method_name(expr: &Expression) -> Option<String> {
    stacker::maybe_grow(32 * 1024, 1024 * 1024, || {
        extract_static_selector_method_name_inner(expr)
    })
}

fn extract_static_selector_method_name_inner(expr: &Expression) -> Option<String> {
    match expr {
        Expression::Parenthesis(_, inner) => extract_static_selector_method_name(inner),
        Expression::MemberAccess(_, inner, member) => {
            if member.name == "selector" {
                match inner.as_ref() {
                    Expression::MemberAccess(_, _, function_name) => {
                        let name = function_name.name.trim();
                        if name.is_empty() {
                            None
                        } else {
                            Some(name.to_string())
                        }
                    }
                    Expression::Variable(function_name) => {
                        let name = function_name.name.trim();
                        if name.is_empty() {
                            None
                        } else {
                            Some(name.to_string())
                        }
                    }
                    _ => None,
                }
            } else {
                None
            }
        }
        Expression::FunctionCall(_, func, args) => {
            if matches!(func.as_ref(), Expression::Type(_, _)) && args.len() == 1 {
                return extract_static_selector_method_name(&args[0]);
            }
            if let Expression::Variable(id) = func.as_ref() {
                if (id.name == "bytes" || id.name == "string") && args.len() == 1 {
                    return extract_static_selector_method_name(&args[0]);
                }
                if id.name == "keccak256" && args.len() == 1 {
                    let signature = extract_static_signature_string(&args[0])?;
                    let name = signature
                        .split('(')
                        .next()
                        .unwrap_or(signature.as_str())
                        .trim()
                        .to_string();
                    if name.is_empty() {
                        return None;
                    }
                    return Some(name);
                }
            }
            None
        }
        _ => None,
    }
}

/// Task #194 — recognise the function reference argument of
/// `abi.encodeCall(funcRef, tuple)`. Accepts `Type.method`,
/// `instance.method`, or nested member-access chains and returns the
/// outermost member name.
fn extract_static_encode_call_method_name(expr: &Expression) -> Option<String> {
    stacker::maybe_grow(32 * 1024, 1024 * 1024, || {
        extract_static_encode_call_method_name_inner(expr)
    })
}

fn extract_static_encode_call_method_name_inner(expr: &Expression) -> Option<String> {
    match expr {
        Expression::Parenthesis(_, inner) => extract_static_encode_call_method_name(inner),
        Expression::MemberAccess(_, _inner, member) => {
            if member.name == "selector" {
                // `abi.encodeCall(X.method.selector, …)` — uncommon but we
                // can still recover the method name by looking one level up.
                if let Expression::MemberAccess(_, _, function_name) = _inner.as_ref() {
                    let name = function_name.name.trim();
                    if !name.is_empty() {
                        return Some(name.to_string());
                    }
                }
                return None;
            }
            let name = member.name.trim();
            if name.is_empty() {
                None
            } else {
                Some(name.to_string())
            }
        }
        _ => None,
    }
}

/// Task #194 — compile-time constant string extraction. Peels `bytes(…)`
/// / `string(…)` casts and unwraps `Parenthesis` but stops at the first
/// non-literal (e.g. `constant`-stored strings are not read here because
/// the analyse pass doesn't have access to the lowering context yet).
fn extract_static_signature_string(expr: &Expression) -> Option<String> {
    stacker::maybe_grow(32 * 1024, 1024 * 1024, || {
        extract_static_signature_string_inner(expr)
    })
}

fn extract_static_signature_string_inner(expr: &Expression) -> Option<String> {
    match expr {
        Expression::Parenthesis(_, inner) => extract_static_signature_string(inner),
        Expression::StringLiteral(parts) => {
            let mut bytes = Vec::new();
            for part in parts {
                bytes.extend_from_slice(part.string.as_bytes());
            }
            Some(String::from_utf8_lossy(&bytes).to_string())
        }
        Expression::FunctionCall(_, func, args) if args.len() == 1 => match func.as_ref() {
            Expression::Type(_, _) => extract_static_signature_string(&args[0]),
            Expression::Variable(id) if id.name == "bytes" || id.name == "string" => {
                extract_static_signature_string(&args[0])
            }
            _ => None,
        },
        _ => None,
    }
}

/// Task #206 — compute the DIRECT sibling-primary references a contract body
/// introduces. Used by the sibling-merge closure so multi-hop cross-contract
/// call chains pull every reachable primary into the root artifact's
/// self-dispatch table.
fn collect_direct_sibling_contract_refs(
    contract: &ContractIR,
    primary_names: &std::collections::HashSet<String>,
    interface_names: &std::collections::HashSet<String>,
    interface_impls: &std::collections::HashMap<String, Vec<String>>,
    primary_method_names: &std::collections::HashMap<
        String,
        std::collections::HashSet<String>,
    >,
) -> std::collections::HashSet<String> {
    let mut referenced: std::collections::HashSet<String> =
        std::collections::HashSet::new();
    let mut iface_refs: std::collections::HashSet<String> =
        std::collections::HashSet::new();
    let mut low_level_method_refs: std::collections::HashSet<String> =
        std::collections::HashSet::new();

    for function in &contract.functions {
        if let Some(body) = function.body.as_ref() {
            collect_new_contract_refs(body, primary_names, &mut referenced);
            collect_interface_casts_stmt(body, interface_names, &mut iface_refs);
            collect_low_level_call_method_refs_stmt(body, &mut low_level_method_refs);
        }
        for p in function.parameters.iter().chain(function.returns.iter()) {
            if primary_names.contains(&p.ty) {
                referenced.insert(p.ty.clone());
            }
            if interface_names.contains(&p.ty) {
                iface_refs.insert(p.ty.clone());
            }
        }
    }

    for state in &contract.state_variables {
        if primary_names.contains(&state.ty) {
            referenced.insert(state.ty.clone());
        }
        if interface_names.contains(&state.ty) {
            iface_refs.insert(state.ty.clone());
        }
        if let Some(init) = state.initializer.as_ref() {
            collect_new_refs_expr(init, primary_names, &mut referenced);
            collect_interface_casts_expr(init, interface_names, &mut iface_refs);
            collect_low_level_call_method_refs_expr(init, &mut low_level_method_refs);
        }
    }

    for iface in &iface_refs {
        if let Some(impls) = interface_impls.get(iface) {
            for prim in impls {
                if prim != &contract.name {
                    referenced.insert(prim.clone());
                }
            }
        }
    }

    if !low_level_method_refs.is_empty() {
        for (prim_name, prim_methods) in primary_method_names {
            if prim_name == &contract.name {
                continue;
            }
            if low_level_method_refs
                .iter()
                .any(|method| prim_methods.contains(method))
            {
                referenced.insert(prim_name.clone());
            }
        }
    }

    referenced.remove(&contract.name);
    referenced
}

/// Normalize a state-variable type string for the sibling-merge collision
/// check so that equivalent spellings compare equal: whitespace is dropped
/// and the bare `uint`/`int` aliases expand to their canonical 256-bit
/// forms (`uint256[3]` == `uint [3]` == `uint256 [ 3 ]`,
/// `mapping(address=>uint)` == `mapping(address => uint256)`).
fn normalize_state_type_for_merge(ty: &str) -> String {
    let mut out = String::with_capacity(ty.len());
    let mut word = String::new();
    let flush = |word: &mut String, out: &mut String| {
        if word.is_empty() {
            return;
        }
        match word.as_str() {
            "uint" => out.push_str("uint256"),
            "int" => out.push_str("int256"),
            other => out.push_str(other),
        }
        word.clear();
    };
    for ch in ty.chars() {
        if ch.is_alphanumeric() || ch == '_' || ch == '$' {
            word.push(ch);
        } else {
            flush(&mut word, &mut out);
            if !ch.is_whitespace() {
                out.push(ch);
            }
        }
    }
    flush(&mut word, &mut out);
    out
}