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
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
//! RIDL intermediate representation.
//!
//! The v2 schema (`proto/ridl/ir/v2/ir.proto`) is compiled from its protobuf
//! source by `build.rs` (protox + prost-build, ADR-0006 decision 3) and
//! exposed as [`v2`]. v2 is the typl surface plus the ridl interaction layer
//! (ridl language reference §3–§14) with exact decimal values — every numeric
//! value is a canonical decimal string, never a floating-point field (ADR-0007
//! decision 9, ADR-0008 decision 12). The v1 schema was removed when its last
//! consumer moved to v2 (task 6 of the E2 plan), mirroring the E1 v0→v1
//! retirement.
pub mod v2 {
//! IR v2 — the typl surface plus the ridl interaction layer (ridl
//! language reference §3–§14) with exact decimal values (ADR-0007
//! decision 9, ADR-0008 decision 12).
include!(concat!(env!("OUT_DIR"), "/ridl.ir.v2.rs"));
// The canonical protobuf JSON serde impls, generated by pbjson-build in
// `build.rs` from the same schema compilation as the types above
// (ADR-0014 decision 14).
//
// The file holds only trait impls, so it sits in a private module to scope
// one lint allowance to generated code: pbjson-build 0.9.0 writes
// `write!(formatter, "…", &FIELDS)`, which clippy 1.98 reports as
// `useless_borrows_in_formatting`. The build script writes the file into
// `OUT_DIR`, so an edit to it does not last and the lint cannot be repaired
// in source. A lint attribute on the `include!` itself is ignored by rustc.
// `expect` rather than `allow`: when the lint no longer fires here, clippy
// reports the expectation as unfulfilled. Then remove this module and
// include the file directly in `v2` again.
#[expect(clippy::useless_borrows_in_formatting)]
mod serde_impls {
use super::*;
include!(concat!(env!("OUT_DIR"), "/ridl.ir.v2.serde.rs"));
}
/// The descriptor pool over the compiled IR schema — the reflection data
/// the prototext encoding needs (ADR-0014 decision 7; since decision 14
/// JSON goes through the pbjson-generated impls and no longer uses the
/// pool). Binary needs none of it.
/// `build.rs` writes the `FileDescriptorSet` to `OUT_DIR` from the same
/// `protox` compilation that generates the types above, so the pool and
/// the types cannot disagree; every `expect` on this path leans on that.
static DESCRIPTOR_POOL: std::sync::LazyLock<prost_reflect::DescriptorPool> =
std::sync::LazyLock::new(|| {
prost_reflect::DescriptorPool::decode(
include_bytes!(concat!(env!("OUT_DIR"), "/ir_descriptor.binpb")).as_slice(),
)
.expect("the embedded descriptor set decodes: build.rs wrote it from the schema compilation that generated these types")
});
/// The descriptor of one root message of the compiled schema, by its
/// full name.
fn descriptor(name: &str) -> prost_reflect::MessageDescriptor {
DESCRIPTOR_POOL
.get_message_by_name(name)
.unwrap_or_else(|| panic!("{name} is declared by the compiled schema"))
}
/// The `Package` message descriptor — the entry point of the prototext
/// encoder and decoder, the one reflection path left in this module.
pub(crate) fn package_descriptor() -> prost_reflect::MessageDescriptor {
descriptor("ridl.ir.v2.Package")
}
/// The `System` message descriptor (`system.proto`), the prototext entry
/// point of the rsdl system layer.
pub(crate) fn system_descriptor() -> prost_reflect::MessageDescriptor {
descriptor("ridl.ir.v2.System")
}
/// The `ridl.codegen.v1.CodegenRequest` message descriptor — the entry
/// point of the request reader that ignores unknown keys.
pub(crate) fn codegen_request_descriptor() -> prost_reflect::MessageDescriptor {
descriptor("ridl.codegen.v1.CodegenRequest")
}
/// The `ridl.codegen.v1.Model` message descriptor — the prototext entry
/// point of the lowered codegen model, from the same pool, because
/// `build.rs` compiles both schemas in one `protox` call.
pub(crate) fn codegen_model_descriptor() -> prost_reflect::MessageDescriptor {
descriptor("ridl.codegen.v1.Model")
}
/// Rebuilds a message as a `DynamicMessage` over its descriptor — the
/// step `prost-reflect` needs before rendering a text encoding.
/// Transcoding goes through the wire encoding, whose decoder enforces
/// prost's fixed recursion limit, so a package whose composite nesting
/// crosses that limit fails here — an input-dependent failure, not
/// schema drift (ADR-0014 decision 12).
fn transcode<M: prost::Message>(
descriptor: prost_reflect::MessageDescriptor,
message: &M,
) -> Result<prost_reflect::DynamicMessage, prost::DecodeError> {
let mut dynamic = prost_reflect::DynamicMessage::new(descriptor);
dynamic.transcode_from(message)?;
Ok(dynamic)
}
/// Derives the synthesized transport identity of an inline `T | E`
/// result union (ADR-0008 decision 4): the enclosing interface name plus
/// the interaction ordinal plus the ordered arm references. The single
/// derivation every consumer — backends and the diff classifier — calls,
/// so the identity stays stable under compatible evolution.
pub fn fallible_transport_identity(
interface: &str,
ordinal: u32,
fallible: &FallibleType,
) -> String {
format!(
"{interface}#{ordinal}:{ok}|{err}",
ok = fallible.ok,
err = fallible.err
)
}
/// The error [`to_json_pretty`] and [`to_text_format`] return. The
/// serialization surface is fallible on purpose (ADR-0014 decisions 12
/// and 14), and the two encodings now fail for different causes, so each
/// carries its own variant — its `Display` names the encoding, so a
/// build requesting several IR emits attributes each failure to its own
/// artifact.
#[derive(Debug)]
pub enum SerializeError {
/// Canonical protobuf JSON (ADR-0014 decision 14): the
/// pbjson-generated `Serialize` impl writes the typed message
/// directly — no transcode, so no message-level recursion limit —
/// and its one error path is an `i32` enum field holding a
/// discriminant outside the schema.
Json(serde_json::Error),
/// Prototext (ADR-0014 decision 12): the transcode into the dynamic
/// message goes through the wire encoding, whose decoder enforces
/// prost's fixed recursion limit, and legal source can nest
/// composites past it.
Text(prost::DecodeError),
}
impl std::fmt::Display for SerializeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Json(source) => write!(
f,
"cannot render the package as canonical protobuf JSON: {source}; the known \
cause is an enum field holding a discriminant outside the schema"
),
Self::Text(source) => write!(
f,
"cannot render the package as prototext: {source}; the known cause \
is composite nesting deeper than the transcoding decoder's recursion limit"
),
}
}
}
impl std::error::Error for SerializeError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Json(source) => Some(source),
Self::Text(source) => Some(source),
}
}
}
/// Renders a package as pretty-printed canonical protobuf JSON — the one
/// dialect every IR surface carries: the `--emit ir-json` artifact, the
/// baselines, and the goldens (ADR-0014 decision 1) — through the
/// pbjson-generated `Serialize` impl (decision 14), byte-identical to
/// what the retired reflection path rendered.
///
/// A field holding its default is emitted rather than skipped (decision
/// 2, `emit_fields()` in `build.rs`); an unset proto3 `optional` field
/// is omitted entirely, never rendered as `null` (the answer to that
/// decision's open item). 64-bit fields render as strings, the canonical
/// mapping JavaScript consumers need (decision 8).
///
/// Still fallible (ADR-0014 decision 14, amending decision 12), but the
/// error path changed rather than survived: the generated impl writes
/// the typed message directly, so the transcode's depth error is gone,
/// and the one error path it has is new — an `i32` enum field holding a
/// discriminant outside the schema, which the retired reflection path
/// serialized successfully as its bare number. The checker never
/// produces one, but the value is data, not schema, so the failure is
/// returned rather than panicked on.
pub fn to_json_pretty(package: &Package) -> Result<String, SerializeError> {
render_json(package)
}
/// Renders a lowered system (`system.proto`, rsdl reference §13) as
/// pretty-printed canonical protobuf JSON — the `<pkg.Name>.system.json`
/// artifact, under the rules of [`to_json_pretty`].
pub fn system_to_json_pretty(system: &System) -> Result<String, SerializeError> {
render_json(system)
}
/// The one JSON writer behind [`to_json_pretty`] and
/// [`system_to_json_pretty`]: the pbjson-generated `Serialize` impl of
/// the message, pretty-printed.
pub(crate) fn render_json<M: serde::Serialize>(message: &M) -> Result<String, SerializeError> {
let mut buf = Vec::new();
let mut serializer = serde_json::Serializer::pretty(&mut buf);
serde::Serialize::serialize(message, &mut serializer).map_err(SerializeError::Json)?;
Ok(String::from_utf8(buf).expect("serde_json emits UTF-8"))
}
/// The nesting ceiling `from_json` enforces, in JSON bracket levels.
///
/// It cannot bind on IR this toolchain produces, and the bound is a
/// measurement rather than a guess. The parser refuses type nesting past
/// 128 levels (FORM-102, `MAX_TYPE_DEPTH` in `ridl-syntax`), and the
/// deepest package that limit admits emits JSON **516 brackets** deep —
/// so 1,000 leaves a factor of 1.9 over anything `ridlc` can write, and
/// the deepest nesting in the corpus is single digits. The figure this
/// comment carried until 2026-09-22, 262 brackets and a factor of 3.8,
/// was the array shape; the tuple shape costs four brackets per source
/// level rather than two and is the one that binds (the IR
/// specification, "The nesting bound").
///
/// It exists for input this toolchain did not write: a hand-edited
/// baseline, or a snapshot from elsewhere. Past the stack ceiling the
/// failure mode is a stack-overflow abort, which no caller can catch, so
/// the cap turns an abort into a diagnostic (ADR-0014 decisions 12
/// and 14).
pub(crate) const MAX_JSON_NESTING: usize = 1_000;
/// The stack `from_json` parses on, in bytes. An explicit size makes the
/// depth that fits a constant of this crate rather than of the ambient
/// stack, which differs between debug and release builds and between
/// platforms — the same input parses everywhere or nowhere.
const JSON_PARSE_STACK: usize = 16 * 1024 * 1024;
/// The maximum bracket nesting of `text`: the largest number of `{` and
/// `[` open at once, with string literals skipped — a bracket inside a
/// string must not count, an escaped quote (`\"`) must not end the
/// string, and an escaped backslash (`\\`) must not disarm the real
/// closing quote after it. Runs before the parse in [`from_json`], so it
/// tolerates input that is not valid JSON; a stray closer never
/// underflows the running depth.
pub(crate) fn max_json_nesting(text: &str) -> usize {
let mut depth = 0usize;
let mut deepest = 0usize;
let mut in_string = false;
let mut escaped = false;
for byte in text.bytes() {
if in_string {
if escaped {
escaped = false;
} else if byte == b'\\' {
escaped = true;
} else if byte == b'"' {
in_string = false;
}
} else {
match byte {
b'"' => in_string = true,
b'{' | b'[' => {
depth += 1;
deepest = deepest.max(depth);
}
b'}' | b']' => depth = depth.saturating_sub(1),
_ => {}
}
}
}
deepest
}
/// Reads a package from canonical protobuf JSON — the inverse of
/// [`to_json_pretty`], through the pbjson-generated `Deserialize` impl
/// (ADR-0014 decision 14). Unknown fields are rejected (the generated
/// deserializer's default; `ignore_unknown_fields()` stays unset in
/// `build.rs`), so a snapshot written against a different schema fails
/// loudly rather than dropping fields silently.
///
/// The generated impl recurses per JSON level, so `serde_json`'s own
/// recursion limit of 128 levels is disabled — it would bind far below
/// this crate's documented ceiling — and two guards replace it
/// (ADR-0014 decision 14):
///
/// - input nesting is measured first and refused past
/// `MAX_JSON_NESTING`, returning a diagnostic where unbounded
/// recursion would eventually abort on a stack overflow no caller can
/// catch;
/// - the parse runs on a thread of `JSON_PARSE_STACK` bytes, so the
/// ceiling behaves identically across build profiles and platforms
/// instead of tracking the ambient stack. On the wasm family there is
/// no such thread — see the branch below — and the cap alone guards
/// the parse.
pub fn from_json(text: &str) -> Result<Package, serde_json::Error> {
read_json(text)
}
/// Reads a lowered system from canonical protobuf JSON — the inverse of
/// [`system_to_json_pretty`], under the rules and guards of
/// [`from_json`].
pub fn system_from_json(text: &str) -> Result<System, serde_json::Error> {
read_json(text)
}
/// The one JSON reader behind [`from_json`] and [`system_from_json`]:
/// the nesting cap, then the parse on its own stack.
pub(crate) fn read_json<M>(text: &str) -> Result<M, serde_json::Error>
where
M: serde::de::DeserializeOwned + Send,
{
check_nesting(text)?;
on_parse_stack(|| parse_json(text))
}
/// Reads a request-shaped message the way [`read_json`] does, except that
/// an object key the schema does not declare is ignored at every nesting
/// level. The same nesting cap and parse stack apply.
///
/// The text is read once into a `serde_json::Value` that keeps only the
/// keys `descriptor` declares at each point (by JSON name or proto name),
/// including inside repeated and map message values, and the value is
/// then read by the generated deserializer of `M`. That reader still
/// rejects what it rejects for the strict path: a value of the wrong
/// type, an unknown enum name, and a field written twice. Only an unknown
/// key is dropped; an unknown enum name is an error, because it changes
/// the meaning of a known field. A value of a `google.protobuf` message
/// is left untouched.
///
/// An error from the second phase, the generated deserializer reading the
/// filtered value, carries no line and column, because the value no longer
/// has a position in the text.
pub(crate) fn read_json_ignoring_unknown<M>(
descriptor: prost_reflect::MessageDescriptor,
text: &str,
) -> Result<M, serde_json::Error>
where
M: serde::de::DeserializeOwned + Send,
{
use serde::de::DeserializeSeed as _;
check_nesting(text)?;
on_parse_stack(|| {
let mut deserializer = serde_json::Deserializer::from_str(text);
deserializer.disable_recursion_limit();
let known = Shape::Message(descriptor).deserialize(&mut deserializer)?;
deserializer.end()?;
serde::Deserialize::deserialize(known)
})
}
/// What a JSON value is expected to be, as far as dropping unknown keys
/// needs to know.
#[derive(Clone)]
enum Shape {
/// A message: an object whose unknown keys are dropped.
Message(prost_reflect::MessageDescriptor),
/// A repeated field: an array of the inner shape.
List(Box<Shape>),
/// A map field: an object whose values have the inner shape.
Map(Box<Shape>),
/// Anything else: kept as read.
Opaque,
}
impl Shape {
/// The shape of the value of one field.
fn of(field: &prost_reflect::FieldDescriptor) -> Shape {
use prost_reflect::Kind;
if field.is_map() {
let Kind::Message(entry) = field.kind() else {
return Shape::Opaque;
};
return Shape::Map(Box::new(Shape::of_kind(
&entry.map_entry_value_field().kind(),
)));
}
let item = Shape::of_kind(&field.kind());
if field.is_list() {
Shape::List(Box::new(item))
} else {
item
}
}
fn of_kind(kind: &prost_reflect::Kind) -> Shape {
match kind {
prost_reflect::Kind::Message(message)
if !message.full_name().starts_with("google.protobuf.") =>
{
Shape::Message(message.clone())
}
_ => Shape::Opaque,
}
}
}
impl<'de> serde::de::DeserializeSeed<'de> for Shape {
type Value = serde_json::Value;
fn deserialize<D: serde::Deserializer<'de>>(
self,
deserializer: D,
) -> Result<Self::Value, D::Error> {
match self {
Shape::Opaque => serde::Deserialize::deserialize(deserializer),
shape => deserializer.deserialize_any(ShapeVisitor(shape)),
}
}
}
struct ShapeVisitor(Shape);
impl<'de> serde::de::Visitor<'de> for ShapeVisitor {
type Value = serde_json::Value;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(match self.0 {
Shape::List(_) => "an array",
_ => "an object",
})
}
// `null` is passed on: the generated reader decides what it means.
fn visit_unit<E>(self) -> Result<Self::Value, E> {
Ok(serde_json::Value::Null)
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(
self,
mut seq: A,
) -> Result<Self::Value, A::Error> {
let Shape::List(item) = self.0 else {
return Err(serde::de::Error::invalid_type(
serde::de::Unexpected::Seq,
&self,
));
};
let mut items = Vec::new();
while let Some(value) = seq.next_element_seed((*item).clone())? {
items.push(value);
}
Ok(serde_json::Value::Array(items))
}
fn visit_map<A: serde::de::MapAccess<'de>>(
self,
mut map: A,
) -> Result<Self::Value, A::Error> {
use serde::de::Error as _;
let mut out = serde_json::Map::new();
match &self.0 {
Shape::Message(descriptor) => {
let mut seen = std::collections::HashSet::new();
while let Some(key) = map.next_key::<String>()? {
let field = descriptor
.get_field_by_json_name(&key)
.or_else(|| descriptor.get_field_by_name(&key));
match field {
Some(field) => {
if !seen.insert(field.number()) {
return Err(A::Error::custom(format!(
"duplicate field `{key}`"
)));
}
let value = map.next_value_seed(Shape::of(&field))?;
out.insert(key, value);
}
None => {
map.next_value::<serde::de::IgnoredAny>()?;
}
}
}
}
Shape::Map(value_shape) => {
while let Some(key) = map.next_key::<String>()? {
let value = map.next_value_seed((**value_shape).clone())?;
if out.insert(key.clone(), value).is_some() {
return Err(A::Error::custom(format!("duplicate key `{key}`")));
}
}
}
Shape::List(_) | Shape::Opaque => {
return Err(A::Error::invalid_type(serde::de::Unexpected::Map, &self));
}
}
Ok(serde_json::Value::Object(out))
}
}
/// Refuses input that nests past `MAX_JSON_NESTING`.
fn check_nesting(text: &str) -> Result<(), serde_json::Error> {
if max_json_nesting(text) > MAX_JSON_NESTING {
return Err(<serde_json::Error as serde::de::Error>::custom(format!(
"the input nests deeper than {MAX_JSON_NESTING} JSON levels, the ceiling this \
reader enforces (ADR-0014 decision 14); real IR nests orders of magnitude \
shallower"
)));
}
Ok(())
}
/// Runs a parse on its own stack of `JSON_PARSE_STACK` bytes, or in line
/// on the wasm family.
fn on_parse_stack<R: Send>(parse: impl FnOnce() -> R + Send) -> R {
if cfg!(target_family = "wasm") {
// The wasm family has no spawnable threads: `spawn_scoped`
// returns `Err(Unsupported)` at run time on
// `wasm32-unknown-unknown`, the `just wasm-check` target, so a
// spawn here would turn every call into a panic. The parse runs
// in line instead, on the caller's stack. What this path loses
// is the deterministic stack — the ceiling is the ambient stack
// — and the `MAX_JSON_NESTING` cap is the guard that matters: it
// is what turns an abort into an error.
parse()
} else {
std::thread::scope(|scope| {
let handle = std::thread::Builder::new()
.stack_size(JSON_PARSE_STACK)
.spawn_scoped(scope, parse)
.expect("the JSON parse thread spawns");
match handle.join() {
Ok(result) => result,
Err(payload) => std::panic::resume_unwind(payload),
}
})
}
}
/// The parse both branches of [`from_json`] share; only the stack that
/// carries it differs. `serde_json`'s own recursion limit is disabled
/// here, so the caller must have applied the `MAX_JSON_NESTING` cap
/// first.
fn parse_json<M: serde::de::DeserializeOwned>(text: &str) -> Result<M, serde_json::Error> {
let mut deserializer = serde_json::Deserializer::from_str(text);
deserializer.disable_recursion_limit();
let message: M = serde::Deserialize::deserialize(&mut deserializer)?;
deserializer.end()?;
Ok(message)
}
/// Renders a package in the protobuf text format — the inspection
/// encoding (ADR-0014 decision 9): emittable, but not a recommended
/// interchange form. Rendered `pretty`, with a field holding its default
/// emitted rather than skipped (decision 2) and message fields printed
/// in schema index order, so the output ordering is deterministic rather
/// than incidental (decision 8).
///
/// Fallible on purpose (ADR-0014 decision 12): the transcode into the
/// dynamic message goes through the wire encoding, and a package whose
/// composite nesting crosses prost's recursion limit fails there. That
/// input is legal source, so the failure is returned rather than
/// panicked on. JSON lost this failure mode when it moved off the
/// transcode (decision 14); prototext keeps it.
pub fn to_text_format(package: &Package) -> Result<String, SerializeError> {
render_text_for(package_descriptor(), package)
}
/// Renders a lowered system in the protobuf text format — the
/// `<pkg.Name>.system.txtpb` artifact, under the rules of
/// [`to_text_format`].
pub fn system_to_text_format(system: &System) -> Result<String, SerializeError> {
render_text_for(system_descriptor(), system)
}
/// The one prototext writer behind [`to_text_format`] and
/// [`system_to_text_format`].
pub(crate) fn render_text_for<M: prost::Message>(
descriptor: prost_reflect::MessageDescriptor,
message: &M,
) -> Result<String, SerializeError> {
let dynamic = transcode(descriptor, message).map_err(SerializeError::Text)?;
Ok(dynamic.to_text_format_with_options(
&prost_reflect::text_format::FormatOptions::new()
.pretty(true)
.skip_default_fields(false)
.print_message_fields_in_index_order(true),
))
}
/// The error [`from_text_format`] returns: the input does not parse as
/// prototext, or the parsed message does not transcode into the
/// generated types. The transcode failure is the read direction of the
/// recursion-limit failure mode (ADR-0014 decision 12) — input-dependent,
/// so it is mapped into this return rather than expected on.
#[cfg(test)]
#[derive(Debug)]
pub(crate) enum TextFormatError {
/// The input is not valid prototext for the `Package` schema.
Parse(prost_reflect::text_format::ParseError),
/// The parsed message cannot be rebuilt as a typed `Package`.
Transcode(prost::DecodeError),
}
#[cfg(test)]
impl std::fmt::Display for TextFormatError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Parse(source) => {
write!(f, "cannot parse the text as an IR package: {source}")
}
Self::Transcode(source) => write!(
f,
"cannot rebuild the parsed prototext as a package: {source}; the known cause \
is composite nesting deeper than the transcoding decoder's recursion limit"
),
}
}
}
#[cfg(test)]
impl std::error::Error for TextFormatError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Parse(source) => Some(source),
Self::Transcode(source) => Some(source),
}
}
}
/// Reads a package from the protobuf text format — the inverse of
/// [`to_text_format`], kept because without it the prototext emit has no
/// round-trip test, and a write path with no read path is untested by
/// construction (ADR-0014 decision 7).
///
/// **Deliberately not public.** `prost-reflect`'s text parser recurses per
/// message level with frames large enough that a debug build exhausts a
/// 2 MiB stack at roughly 45 levels of nesting — *below* prost's recursion
/// limit of 100, so on that path the error return below is unreachable and
/// the process aborts instead. A stack overflow cannot be caught, so the
/// hazard is contained by reach rather than handled: nothing in the
/// toolchain reads prototext, `ridl diff` and `ridl check --baseline`
/// refuse the encoding by name (ADR-0014 decision 5), and this function is
/// compiled only for this crate's tests. The tests that exercise it run on an
/// explicitly sized stack (see `with_sized_stack`). Making it public again
/// means giving it a stack strategy first — driftsys/ridl#218.
///
/// A package whose nesting crosses prost's limit *before* the stack runs
/// out fails in the transcode out of the dynamic message; that failure is
/// mapped into the error return, not expected on (ADR-0014 decision 12).
#[cfg(test)]
pub(crate) fn from_text_format(text: &str) -> Result<Package, TextFormatError> {
parse_text(package_descriptor(), text)
}
/// Reads a lowered system from the protobuf text format — the inverse of
/// [`system_to_text_format`], test-only for the reason
/// [`from_text_format`] states.
#[cfg(test)]
pub(crate) fn system_from_text_format(text: &str) -> Result<System, TextFormatError> {
parse_text(system_descriptor(), text)
}
#[cfg(test)]
fn parse_text<M: prost::Message + Default>(
descriptor: prost_reflect::MessageDescriptor,
text: &str,
) -> Result<M, TextFormatError> {
let dynamic = prost_reflect::DynamicMessage::parse_text_format(descriptor, text)
.map_err(TextFormatError::Parse)?;
dynamic.transcode_to().map_err(TextFormatError::Transcode)
}
/// Encodes a package in the protobuf binary wire format — a derived
/// encoding since ADR-0014 decision 9's 2026-09-22 amendment, whose
/// reader stops 100 message levels below the root where the canonical
/// encoding has no such bound (the IR specification, "The derived
/// encodings"). Binary needs no descriptors: prost's generated encoding
/// is schema-faithful by construction.
pub fn to_binary(package: &Package) -> Vec<u8> {
prost::Message::encode_to_vec(package)
}
/// Decodes a package from the protobuf binary wire format — the inverse
/// of [`to_binary`].
pub fn from_binary(bytes: &[u8]) -> Result<Package, prost::DecodeError> {
prost::Message::decode(bytes)
}
/// Encodes a lowered system in the protobuf binary wire format — the
/// `<pkg.Name>.system.binpb` artifact (ADR-0014 decision 9).
pub fn system_to_binary(system: &System) -> Vec<u8> {
prost::Message::encode_to_vec(system)
}
/// Decodes a lowered system from the protobuf binary wire format — the
/// inverse of [`system_to_binary`].
pub fn system_from_binary(bytes: &[u8]) -> Result<System, prost::DecodeError> {
prost::Message::decode(bytes)
}
/// `pkg.Name` — how a system, a component or a distribution is referred
/// to across the system layer (`system.proto`); a name with no package,
/// the implicit component of a lone service (rsdl §6), is its own
/// qualified name.
fn qualified(package: &str, name: &str) -> String {
if package.is_empty() {
name.to_string()
} else {
format!("{package}.{name}")
}
}
impl System {
/// The system's qualified name, `pkg.Name` — the base name of its
/// artifacts.
pub fn qualified_name(&self) -> String {
qualified(&self.package, &self.name)
}
}
impl Component {
/// The name every reference to this component uses: `pkg.Name` for a
/// declared component, the service's dotted name for an implicit one.
pub fn qualified_name(&self) -> String {
qualified(&self.package, &self.name)
}
}
impl Distribution {
/// The name `Distribution.depends_on` and `Installation.distribution`
/// use.
pub fn qualified_name(&self) -> String {
qualified(&self.package, &self.name)
}
}
/// One interface shape of a package (ridl §14.0): a declared `interface`,
/// or the inline shape of a `service` (§14.5).
///
/// **[`Package::interfaces`] is not the complete set.** A `service`
/// declared with an inline body carries a full [`Interface`] inside its
/// shape list (the single `INLINE` slot, ADR-0015 decision 14), which
/// lives outside `interfaces`; a consumer that walks `interfaces` alone
/// silently misses it. Six defects of exactly that shape were found
/// independently across E2 — observer-stub lowering, both backends'
/// transport identity, `ridl test`'s report, the Rust backend's collision
/// check, and the desk check's span index.
/// [`Package::shapes`] is the one walk that sees both, the way
/// [`fallible_transport_identity`] is the one transport-identity
/// derivation.
///
/// This view is deliberately not a bare `&Interface`, because two of an
/// inline shape's own fields are empty by construction and reading them
/// is what produced two of those six defects:
///
/// - [`Interface::name`] is `""` for an inline shape, so [`Self::name`]
/// carries the **identity** name instead — the interface's own name, or
/// the owning service's dotted global name. That is the name the diff
/// paths, the observer-stub scoping, and both backends' identity fields
/// already use.
/// - [`Interface::visibility`] is `VISIBILITY_UNSPECIFIED` for an inline
/// shape; the owning [`Service`] carries the authoritative one, which
/// [`Self::visibility`] reads.
///
/// The generated *type* name is not derived here on purpose: mangling is
/// language-specific and stays with each backend.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct InterfaceShape<'a> {
/// The name this shape is known by outside the package: an
/// `interface` declaration's own name, or the owning service's dotted
/// global name. Never `Interface::name` for an inline shape.
pub name: &'a str,
/// The interface body — its interactions and its doc envelope.
pub interface: &'a Interface,
/// The owning service, for an inline shape; `None` for a declared
/// `interface`.
pub service: Option<&'a Service>,
}
impl InterfaceShape<'_> {
/// The authoritative visibility of this shape: the owning service's
/// for an inline shape (an inline shape's own field is
/// `VISIBILITY_UNSPECIFIED` by construction), the interface's own
/// otherwise.
pub fn visibility(&self) -> i32 {
match self.service {
Some(service) => service.visibility,
None => self.interface.visibility,
}
}
/// `true` when this shape is the inline body of a `service`.
pub fn is_inline(&self) -> bool {
self.service.is_some()
}
}
impl Package {
/// Every interface shape the package carries — the declared
/// interfaces and the inline shapes of its services. See
/// [`InterfaceShape`] for why walking [`Package::interfaces`] alone is
/// a defect.
///
/// The order is the one every consumer already walked: the declared
/// interfaces in source order, then the services in source order. A
/// shape-list entry that names an interface yields nothing — its
/// target is a declared interface and is already in the sequence, so
/// yielding it again would visit one shape twice; a service composing
/// several interfaces (ADR-0015 decision 12) therefore contributes
/// nothing at all. A tombstone slot names no shape. Only the `INLINE`
/// slot of an inline-form service carries an interface of its own,
/// and that is what this walk yields.
pub fn shapes(&self) -> impl Iterator<Item = InterfaceShape<'_>> {
let named = self.interfaces.iter().map(|interface| InterfaceShape {
name: &interface.name,
interface,
service: None,
});
let inline = self.services.iter().flat_map(|service| {
service
.shapes
.iter()
.filter_map(move |slot| match slot.kind.as_ref()? {
service_shape::Kind::Inline(interface) => Some(InterfaceShape {
name: &service.name,
interface,
service: Some(service),
}),
service_shape::Kind::InterfaceRef(_) => None,
})
});
named.chain(inline)
}
}
/// Every package named by a type reference in `package`.
///
/// A resolved type-reference string is the fully qualified `pkg.Name` for
/// a cross-package reference and the bare `Name` for a same-package one,
/// never an import alias — the canonical form stated in
/// `proto/ridl/ir/v2/ir.proto`, which also enumerates the fields carrying
/// one. **That enumeration and this walk are edited together.** A
/// reference-bearing field added there and not read here makes the package
/// it names invisible to every caller asking what a package depends on.
///
/// Every `oneof` below is matched exhaustively with no wildcard arm, so a
/// variant added later fails to compile here rather than going unread.
pub fn referenced_packages(package: &Package) -> std::collections::BTreeSet<String> {
let mut found = std::collections::BTreeSet::new();
for decl in &package.decls {
walk_decl(decl, &mut found);
}
for interface in &package.interfaces {
for interaction in &interface.interactions {
walk_decl(interaction, &mut found);
}
}
for service in &package.services {
for slot in &service.shapes {
match &slot.kind {
Some(service_shape::Kind::InterfaceRef(reference)) => {
qualifier(reference, &mut found);
}
Some(service_shape::Kind::Inline(interface)) => {
for interaction in &interface.interactions {
walk_decl(interaction, &mut found);
}
}
None => {}
}
}
}
found
}
/// Records the package qualifier of a dotted reference. A bare reference
/// is same-package and contributes nothing.
fn qualifier(reference: &str, found: &mut std::collections::BTreeSet<String>) {
if let Some((package, _)) = reference.rsplit_once('.') {
found.insert(package.to_string());
}
}
/// Records every reference in one declaration — a package-level one or an
/// interaction inside an interface, which share the `Decl` envelope.
fn walk_decl(decl: &Decl, found: &mut std::collections::BTreeSet<String>) {
match &decl.kind {
Some(decl::Kind::TypeDef(type_def)) => walk_type_def(type_def, found),
Some(decl::Kind::ConstDef(const_def)) => {
if let Some(reference) = &const_def.type_ref {
qualifier(reference, found);
}
}
Some(decl::Kind::StructDef(struct_def)) => {
for member in &struct_def.members {
match &member.member {
Some(struct_member::Member::Field(field)) => {
if let Some(field_type) = &field.r#type {
walk_field_type(field_type, found);
}
}
// A tombstone occupies an ordinal and names no type.
Some(struct_member::Member::Reserved(_)) | None => {}
}
}
}
// An enum's variants are integers; it names no type.
Some(decl::Kind::EnumDef(_)) => {}
Some(decl::Kind::EnumSetDef(enum_set)) => {
if let Some(reference) = &enum_set.backing_enum {
qualifier(reference, found);
}
}
Some(decl::Kind::UnionDef(union_def)) => {
for arm in &union_def.arms {
qualifier(&arm.type_ref, found);
}
}
Some(decl::Kind::SignalDef(signal)) => qualifier(&signal.payload, found),
Some(decl::Kind::EventDef(event)) => qualifier(&event.payload, found),
Some(decl::Kind::CommandDef(command)) => {
for param in &command.params {
if let Some(field_type) = ¶m.r#type {
walk_field_type(field_type, found);
}
}
}
Some(decl::Kind::QueryDef(query)) => {
for param in &query.params {
if let Some(field_type) = ¶m.r#type {
walk_field_type(field_type, found);
}
}
if let Some(return_type) = &query.return_type {
walk_return_type(return_type, found);
}
}
Some(decl::Kind::FixedDef(fixed)) => {
if let Some(field_type) = &fixed.payload {
walk_field_type(field_type, found);
}
}
// A tombstone occupies an ordinal and names no type.
Some(decl::Kind::ReservedSlot(_)) | None => {}
}
}
/// The recursive half: a reference is reachable at arbitrary depth through
/// tuples, arrays, maps, inline scalars, and streams.
fn walk_field_type(field_type: &FieldType, found: &mut std::collections::BTreeSet<String>) {
match &field_type.kind {
Some(field_type::Kind::Named(reference)) => qualifier(reference, found),
// A primitive names no package.
Some(field_type::Kind::Primitive(_)) => {}
Some(field_type::Kind::InlineScalar(type_def)) => walk_type_def(type_def, found),
Some(field_type::Kind::Tuple(tuple)) => {
for field in &tuple.fields {
if let Some(inner) = &field.r#type {
walk_field_type(inner, found);
}
}
}
Some(field_type::Kind::Array(array)) => {
if let Some(element) = &array.element {
walk_field_type(element, found);
}
}
Some(field_type::Kind::Map(map)) => {
if let Some(key) = &map.key {
walk_field_type(key, found);
}
if let Some(value) = &map.value {
walk_field_type(value, found);
}
}
Some(field_type::Kind::Stream(stream)) => match &stream.element {
Some(stream_type::Element::Named(reference)) => qualifier(reference, found),
// STRING or BYTES only; names no package.
Some(stream_type::Element::Primitive(_)) | None => {}
},
None => {}
}
}
/// A `TypeDef`'s only reference is the constant a `match` bound names.
fn walk_type_def(type_def: &TypeDef, found: &mut std::collections::BTreeSet<String>) {
if let Some(constraint) = &type_def.constraint
&& let Some(reference) = &constraint.pattern_const
{
qualifier(reference, found);
}
}
fn walk_return_type(return_type: &ReturnType, found: &mut std::collections::BTreeSet<String>) {
match &return_type.kind {
Some(return_type::Kind::Value(field_type)) => walk_field_type(field_type, found),
Some(return_type::Kind::Fallible(fallible)) => {
qualifier(&fallible.ok, found);
qualifier(&fallible.err, found);
}
None => {}
}
}
/// Whether a constraint leaves a generated constructor nothing to check.
///
/// True when no bound, step or pattern is present. A step is an enforced
/// quantization constraint, including when its origin defaults to zero.
///
/// A pattern given by name counts as a pattern: `pattern_const` is read as
/// well as `pattern`, because a pattern constant that did not resolve leaves
/// `pattern` absent while the type still carries a match constraint.
/// `ridl-sem` treats the two fields the same way in its derived-init rule
/// (`init.rs`).
///
/// Because the checker materializes the typl §4.4 default `[0..256]` into
/// `len_min`/`len_max`, every string and bytes type is non-vacuous. In
/// practice this reduces to `boolean`, and `integer`/`float` with no declared
/// range.
pub fn constraint_is_vacuous(constraint: Option<&Constraint>) -> bool {
let Some(c) = constraint else { return true };
c.min.is_none()
&& c.max.is_none()
&& c.step.is_none()
&& c.len_min.is_none()
&& c.len_max.is_none()
&& c.pattern.is_none()
&& c.pattern_const.is_none()
}
}
pub mod catalog_hash;
pub mod codegen;
pub mod name;
pub mod projection;
pub mod rules;
pub mod zero;
#[cfg(test)]
mod v2_round_trip {
use crate::v2;
/// Wraps an interaction kind in the shared `Decl` envelope. Visibility
/// and `is_error` stay unset on interactions (ridl §14.1); the ordinal is
/// the 1-based declaration order across all interactions of the
/// enclosing interface (ridl §11).
fn interaction(name: &str, ordinal: u32, kind: v2::decl::Kind) -> v2::Decl {
v2::Decl {
name: name.to_string(),
visibility: v2::Visibility::Unspecified as i32,
is_error: false,
doc: String::new(),
labels: Vec::new(),
deprecated: None,
ordinal,
kind: Some(kind),
links: Vec::new(),
see: Vec::new(),
since: Vec::new(),
}
}
fn named_type(name: &str) -> v2::FieldType {
v2::FieldType {
optional: false,
kind: Some(v2::field_type::Kind::Named(name.to_string())),
}
}
fn stream_of(element: v2::stream_type::Element) -> v2::FieldType {
v2::FieldType {
optional: false,
kind: Some(v2::field_type::Kind::Stream(v2::StreamType {
element: Some(element),
})),
}
}
/// A representative ridl package: one interface holding all five
/// interaction kinds plus a reserved tombstone (ordinals 1–6, the
/// tombstone counted, ridl §11), a strict-periodic and a defaulted
/// range timing, a fallible query, and two services — a named
/// reference and an inline shape holding a stream query.
fn fixture() -> v2::Package {
// signal speed : Speed @10ms — strict periodic stores the period
// in both bounds (ADR-0008 decision 12).
let speed = v2::SignalDef {
payload: "Speed".to_string(),
declared_init: None,
init: Some(v2::InitValue {
derivable: true,
value: Some("0.0".to_string()),
}),
timing: Some(v2::Timing {
mode: v2::TimingMode::StrictPeriodic as i32,
min_us: Some("10000".to_string()),
max_us: Some("10000".to_string()),
default_applied: false,
}),
};
// event doorOpened : DoorEvent — untimed in source, so the
// configured default range is resolved at compile time (ridl §9.1).
let door_opened = v2::EventDef {
payload: "DoorEvent".to_string(),
timing: Some(v2::Timing {
mode: v2::TimingMode::Range as i32,
min_us: Some("20000".to_string()),
max_us: Some("500000".to_string()),
default_applied: true,
}),
};
// command setTarget(target : Speed) [ require target >= speed ]
let set_target = v2::CommandDef {
params: vec![v2::Param {
name: "target".to_string(),
r#type: Some(named_type("Speed")),
doc: String::new(),
links: Vec::new(),
see: Vec::new(),
since: Vec::new(),
}],
contracts: vec![v2::Contract {
kind: v2::ContractKind::Require as i32,
source: "target >= speed".to_string(),
signal_refs: vec!["speed".to_string()],
param_refs: vec!["target".to_string()],
uses_result: false,
observer_id: "VehicleStatus.setTarget.require[0]".to_string(),
}],
timing: None,
};
// query fetchFaults(page : PageSpec) : FaultPage | DiagError
// [ ensure result.count <= page.limit ]
let fetch_faults = v2::QueryDef {
params: vec![v2::Param {
name: "page".to_string(),
r#type: Some(named_type("PageSpec")),
doc: String::new(),
links: Vec::new(),
see: Vec::new(),
since: Vec::new(),
}],
return_type: Some(v2::ReturnType {
kind: Some(v2::return_type::Kind::Fallible(v2::FallibleType {
ok: "FaultPage".to_string(),
err: "DiagError".to_string(),
})),
}),
contracts: vec![v2::Contract {
kind: v2::ContractKind::Ensure as i32,
source: "result.count <= page.limit".to_string(),
signal_refs: Vec::new(),
param_refs: vec!["page".to_string()],
uses_result: true,
observer_id: "VehicleStatus.fetchFaults.ensure[0]".to_string(),
}],
timing: None,
};
// fixed vin : Vin
let vin = v2::FixedDef {
payload: Some(named_type("Vin")),
};
let vehicle_status = v2::Interface {
name: "VehicleStatus".to_string(),
visibility: v2::Visibility::Public as i32,
doc: "Vehicle status contract".to_string(),
labels: Vec::new(),
deprecated: None,
interactions: vec![
interaction("speed", 1, v2::decl::Kind::SignalDef(speed)),
interaction("doorOpened", 2, v2::decl::Kind::EventDef(door_opened)),
// reserved legacyMode — the tombstone keeps ordinal 3
// occupied in the one interaction sequence (ridl §11).
v2::Decl {
ordinal: 3,
kind: Some(v2::decl::Kind::ReservedSlot(v2::Reserved {
ordinal: 3,
name: Some("legacyMode".to_string()),
value: None,
})),
..interaction("", 3, v2::decl::Kind::ReservedSlot(v2::Reserved::default()))
},
interaction("setTarget", 4, v2::decl::Kind::CommandDef(set_target)),
interaction("fetchFaults", 5, v2::decl::Kind::QueryDef(fetch_faults)),
interaction("vin", 6, v2::decl::Kind::FixedDef(vin)),
],
number: 0,
provisional: false,
links: Vec::new(),
see: Vec::new(),
since: Vec::new(),
};
// query tailLogs(pattern : <string>) : <LogLine> — a stream param
// and a stream return (ridl §12), inside the inline service shape.
let tail_logs = v2::QueryDef {
params: vec![v2::Param {
name: "pattern".to_string(),
r#type: Some(stream_of(v2::stream_type::Element::Primitive(
v2::PrimitiveType::String as i32,
))),
doc: String::new(),
links: Vec::new(),
see: Vec::new(),
since: Vec::new(),
}],
return_type: Some(v2::ReturnType {
kind: Some(v2::return_type::Kind::Value(stream_of(
v2::stream_type::Element::Named("LogLine".to_string()),
))),
}),
contracts: Vec::new(),
timing: None,
};
// service veh.adas.status : VehicleStatus — one named reference in
// the service's set (ADR-0015 decision 12).
let status_service = v2::Service {
name: "veh.adas.status".to_string(),
visibility: v2::Visibility::Public as i32,
doc: String::new(),
labels: Vec::new(),
deprecated: None,
shapes: vec![v2::ServiceShape {
kind: Some(v2::service_shape::Kind::InterfaceRef(
"VehicleStatus".to_string(),
)),
}],
links: Vec::new(),
see: Vec::new(),
since: Vec::new(),
};
// service veh.adas.logs { … } — the inline shape as the one entry,
// Interface.name == "" (ridl §14.5).
let logs_service = v2::Service {
name: "veh.adas.logs".to_string(),
visibility: v2::Visibility::Public as i32,
doc: String::new(),
labels: Vec::new(),
deprecated: None,
shapes: vec![v2::ServiceShape {
kind: Some(v2::service_shape::Kind::Inline(v2::Interface {
name: String::new(),
visibility: v2::Visibility::Unspecified as i32,
doc: String::new(),
labels: Vec::new(),
deprecated: None,
interactions: vec![interaction(
"tailLogs",
1,
v2::decl::Kind::QueryDef(tail_logs),
)],
number: 0,
provisional: false,
links: Vec::new(),
see: Vec::new(),
since: Vec::new(),
})),
}],
links: Vec::new(),
see: Vec::new(),
since: Vec::new(),
};
v2::Package {
name: "veh.adas".to_string(),
// One typl declaration proves the verbatim v1 surface rides
// along unchanged in v2; package-level declarations carry
// ordinal 0.
decls: vec![v2::Decl {
name: "Speed".to_string(),
visibility: v2::Visibility::Public as i32,
is_error: false,
doc: String::new(),
labels: Vec::new(),
deprecated: None,
ordinal: 0,
kind: Some(v2::decl::Kind::TypeDef(v2::TypeDef {
backing: Some(v2::Backing {
kind: Some(v2::backing::Kind::Unit("km/h".to_string())),
}),
constraint: None,
declared_init: None,
init: None,
width: Some(v2::type_def::Width::FloatWidth(v2::FloatWidth::F32 as i32)),
})),
links: Vec::new(),
see: Vec::new(),
since: Vec::new(),
}],
interfaces: vec![vehicle_status],
services: vec![status_service, logs_service],
retired: Vec::new(),
}
}
/// The typl vocabulary surface the interaction fixture does not reach:
/// the boxed `inlineScalar` oneof member, genuine 64-bit integer fields
/// (array and map bounds, length bounds, `Reserved.value`,
/// `EnumValue.value`), a tuple, a map, a union, an enum set, a constant,
/// and a set `deprecated`. A second fixture, so each stays readable; the
/// same round-trip tests drive both.
fn vocabulary_fixture() -> v2::Package {
fn decl(name: &str, kind: v2::decl::Kind) -> v2::Decl {
v2::Decl {
name: name.to_string(),
visibility: v2::Visibility::Public as i32,
is_error: false,
doc: String::new(),
labels: Vec::new(),
deprecated: None,
ordinal: 0,
kind: Some(kind),
links: Vec::new(),
see: Vec::new(),
since: Vec::new(),
}
}
fn field(name: &str, ordinal: u32, field_type: v2::FieldType) -> v2::Field {
v2::Field {
name: name.to_string(),
ordinal,
r#type: Some(field_type),
declared_init: None,
init: None,
doc: String::new(),
labels: Vec::new(),
deprecated: None,
links: Vec::new(),
see: Vec::new(),
since: Vec::new(),
}
}
// const MAX_RETRY : integer = 24
let max_retry = v2::ConstDef {
type_ref: Some("integer".to_string()),
value: "24".to_string(),
regex: None,
};
// enum Gear { PARK = 1 DRIVE = 2 reserved 7 } — the tombstone
// retires the integer value, a genuine int64 field.
let gear = v2::EnumDef {
values: vec![
v2::EnumValue {
name: "PARK".to_string(),
value: 1,
doc: String::new(),
links: Vec::new(),
see: Vec::new(),
since: Vec::new(),
},
v2::EnumValue {
name: "DRIVE".to_string(),
value: 2,
doc: String::new(),
links: Vec::new(),
see: Vec::new(),
since: Vec::new(),
},
],
reserved: vec![v2::Reserved {
ordinal: 0,
name: None,
value: Some(7),
}],
};
// enumset Warnings { LOW_FUEL = 0 ICE_RISK = 33 } — the standalone
// form; bit 33 forces the u64 width and is a genuine int64 value.
let warnings = v2::EnumSetDef {
backing_enum: None,
bits: vec![
v2::EnumValue {
name: "LOW_FUEL".to_string(),
value: 0,
doc: String::new(),
links: Vec::new(),
see: Vec::new(),
since: Vec::new(),
},
v2::EnumValue {
name: "ICE_RISK".to_string(),
value: 33,
doc: String::new(),
links: Vec::new(),
see: Vec::new(),
since: Vec::new(),
},
],
width: v2::IntWidth::U64 as i32,
};
// type PlateText : string [1..86] — character length bounds, two
// genuine uint64 fields behind proto3 `optional`.
let plate_text = v2::TypeDef {
backing: Some(v2::Backing {
kind: Some(v2::backing::Kind::Primitive(
v2::PrimitiveType::String as i32,
)),
}),
constraint: Some(v2::Constraint {
min: None,
max: None,
step: None,
len_min: Some(1),
len_max: Some(86),
pattern: None,
pattern_const: None,
}),
declared_init: None,
init: None,
width: None,
};
// union Sample { speed : Speed gear : Gear }
let sample = v2::UnionDef {
arms: vec![
v2::UnionArm {
name: "speed".to_string(),
ordinal: 1,
type_ref: "Speed".to_string(),
doc: String::new(),
links: Vec::new(),
see: Vec::new(),
since: Vec::new(),
},
v2::UnionArm {
name: "gear".to_string(),
ordinal: 2,
type_ref: "Gear".to_string(),
doc: String::new(),
links: Vec::new(),
see: Vec::new(),
since: Vec::new(),
},
],
is_result: false,
reserved: Vec::new(),
};
// retries : integer [0..24] = 3 — the boxed `inlineScalar` oneof
// member: the committed regression guard for ADR-0014 Open item 2,
// which established that the Rust-side `Box` is invisible to the
// reflection path. The enclosing field carries the init; the nested
// TypeDef's stays unset.
let retries = v2::Field {
declared_init: Some("3".to_string()),
init: Some(v2::InitValue {
derivable: true,
value: Some("3".to_string()),
}),
..field(
"retries",
1,
v2::FieldType {
optional: false,
kind: Some(v2::field_type::Kind::InlineScalar(Box::new(v2::TypeDef {
backing: Some(v2::Backing {
kind: Some(v2::backing::Kind::Primitive(
v2::PrimitiveType::Integer as i32,
)),
}),
constraint: Some(v2::Constraint {
min: Some("0".to_string()),
max: Some("24".to_string()),
step: None,
len_min: None,
len_max: None,
pattern: None,
pattern_const: None,
}),
declared_init: None,
init: None,
width: Some(v2::type_def::Width::IntWidth(v2::IntWidth::U8 as i32)),
}))),
},
)
};
// position : (x : Speed, y : Speed) — an anonymous named-field
// composite (typl §11).
let position = field(
"position",
2,
v2::FieldType {
optional: false,
kind: Some(v2::field_type::Kind::Tuple(v2::TupleType {
fields: vec![
v2::TupleField {
name: "x".to_string(),
r#type: Some(named_type("Speed")),
},
v2::TupleField {
name: "y".to_string(),
r#type: Some(named_type("Speed")),
},
],
})),
},
);
// gears : [Gear; 1..4096] — array bounds are genuine uint64 fields.
let gears = field(
"gears",
3,
v2::FieldType {
optional: false,
kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
element: Some(Box::new(named_type("Gear"))),
min: 1,
max: 4096,
}))),
},
);
// plates : { PlateText -> Gear } [0..53] — map bounds are genuine
// uint64 fields. The field is deprecated, covering the optional
// string on the Field envelope.
let plates = v2::Field {
deprecated: Some("superseded by gears".to_string()),
..field(
"plates",
4,
v2::FieldType {
optional: false,
kind: Some(v2::field_type::Kind::Map(Box::new(v2::MapType {
key: Some(Box::new(named_type("PlateText"))),
value: Some(Box::new(named_type("Gear"))),
min: 0,
max: 53,
}))),
},
)
};
let snapshot = v2::StructDef {
members: [retries, position, gears, plates]
.into_iter()
.map(|field| v2::StructMember {
member: Some(v2::struct_member::Member::Field(Box::new(field))),
})
.collect(),
fixed_layout: false,
};
v2::Package {
name: "veh.vocab".to_string(),
decls: vec![
decl("MAX_RETRY", v2::decl::Kind::ConstDef(max_retry)),
decl("Gear", v2::decl::Kind::EnumDef(gear)),
decl("Warnings", v2::decl::Kind::EnumSetDef(warnings)),
decl("PlateText", v2::decl::Kind::TypeDef(plate_text)),
// The union is deprecated — the optional string on the Decl
// envelope.
v2::Decl {
deprecated: Some("use Snapshot".to_string()),
..decl("Sample", v2::decl::Kind::UnionDef(sample))
},
decl("Snapshot", v2::decl::Kind::StructDef(snapshot)),
],
interfaces: Vec::new(),
services: Vec::new(),
retired: Vec::new(),
}
}
#[test]
fn protobuf_round_trip_preserves_package() {
let package = fixture();
let buf = v2::to_binary(&package);
let decoded = v2::from_binary(buf.as_slice()).expect("decode must succeed");
assert_eq!(package, decoded);
// The vocabulary fixture rides the same round trip.
let vocabulary = vocabulary_fixture();
let decoded_vocabulary =
v2::from_binary(v2::to_binary(&vocabulary).as_slice()).expect("decode must succeed");
assert_eq!(vocabulary, decoded_vocabulary);
let interface = &decoded.interfaces[0];
let ordinals: Vec<u32> = interface.interactions.iter().map(|d| d.ordinal).collect();
assert_eq!(
ordinals,
[1, 2, 3, 4, 5, 6],
"one ordinal sequence, tombstone counted (ridl §11)"
);
let Some(v2::decl::Kind::ReservedSlot(tombstone)) = &interface.interactions[2].kind else {
panic!("ordinal 3 must decode as a reserved tombstone");
};
assert_eq!(tombstone.name.as_deref(), Some("legacyMode"));
let Some(v2::service_shape::Kind::Inline(inline)) = decoded.services[1]
.shapes
.first()
.and_then(|slot| slot.kind.as_ref())
else {
panic!("veh.adas.logs must decode as an inline shape");
};
assert_eq!(inline.name, "", "an inline shape carries no name");
let references: Vec<&str> = decoded.services[0]
.shapes
.iter()
.filter_map(|slot| match &slot.kind {
Some(v2::service_shape::Kind::InterfaceRef(reference)) => Some(reference.as_str()),
_ => None,
})
.collect();
assert_eq!(
references,
["VehicleStatus"],
"a service's set carries its references and nothing else"
);
}
#[test]
fn json_round_trip_preserves_package() {
for package in [fixture(), vocabulary_fixture()] {
let json = v2::to_json_pretty(&package).expect("the fixture serializes as IR JSON");
let decoded = v2::from_json(&json).expect("json deserialization must succeed");
assert_eq!(package, decoded);
}
}
/// The interface identity fields the lock design §9 adds — `number` and
/// `provisional` on every `Interface`, an inline shape included, and the
/// package's `retired` list — ride all three encodings unchanged, and the
/// JSON writes them under their canonical names even when they hold their
/// defaults (ADR-0014 decision 2), so a reader can tell `number` 0 from an
/// absent field only by the schema, never by the text.
#[test]
fn number_provisional_and_retired_round_trip_through_json_text_and_binary() {
let mut package = fixture();
package.interfaces[0].number = 4;
package.interfaces[0].provisional = true;
let Some(v2::service_shape::Kind::Inline(inline)) =
package.services[1].shapes[0].kind.as_mut()
else {
panic!("veh.adas.logs holds an inline shape in slot 1");
};
inline.number = 5;
package.retired = vec![
v2::RetiredInterface {
name: "LaneAssist".to_string(),
number: 2,
},
v2::RetiredInterface {
name: "service:veh.hvac.cabin".to_string(),
number: 3,
},
];
let json = v2::to_json_pretty(&package).expect("the package serializes as IR JSON");
assert_eq!(v2::from_json(&json).expect("the JSON parses back"), package);
let text = v2::to_text_format(&package).expect("the package serializes as prototext");
assert_eq!(
v2::from_text_format(&text).expect("the prototext parses back"),
package
);
assert_eq!(
v2::from_binary(v2::to_binary(&package).as_slice()).expect("the binary decodes"),
package
);
for needle in [
r#""number": 4"#,
r#""provisional": true"#,
r#""number": 5"#,
r#""name": "LaneAssist""#,
r#""name": "service:veh.hvac.cabin""#,
] {
assert!(
json.contains(needle),
"the JSON must carry {needle}, got: {json}"
);
}
// A default holds its place in the text (decision 2): an interface
// that was never numbered writes `0` and `false`, and a package with
// nothing retired writes an empty list.
let unnumbered = v2::to_json_pretty(&fixture()).expect("the fixture serializes as IR JSON");
for needle in [
r#""number": 0"#,
r#""provisional": false"#,
r#""retired": []"#,
] {
assert!(
unnumbered.contains(needle),
"a default field must still be written, expected {needle} in: {unnumbered}"
);
}
}
/// A baseline published before the lock existed carries no `number`, no
/// `provisional` and no `retired` field. It still loads — a missing field
/// reads as its default, which is the `number` 0 the lock design §7 names
/// as the one transition case — while an unknown field is still rejected
/// (`json_parse_rejects_an_unknown_field`).
#[test]
fn a_snapshot_lacking_the_number_fields_still_loads() {
let package = v2::from_json(
r#"{"name": "veh.x", "interfaces": [{"name": "LaneKeeping"}], "services": [{"name": "veh.x.s", "shapes": [{"inline": {"name": ""}}]}]}"#,
)
.expect("a pre-lock snapshot loads");
assert_eq!(package.interfaces[0].number, 0);
assert!(!package.interfaces[0].provisional);
let Some(v2::service_shape::Kind::Inline(inline)) =
package.services[0].shapes[0].kind.as_ref()
else {
panic!("the service holds an inline shape");
};
assert_eq!(inline.number, 0);
assert!(!inline.provisional);
assert_eq!(package.retired, Vec::new());
}
/// The prototext read path (ADR-0014 decision 7): both fixtures survive
/// `to_text_format` then `from_text_format` unchanged. With the binary
/// and JSON round trips above, this is what proves all three encodings
/// carry the same IR.
#[test]
fn text_format_round_trip_preserves_package() {
for package in [fixture(), vocabulary_fixture()] {
let text = v2::to_text_format(&package).expect("the fixture serializes as prototext");
let decoded = v2::from_text_format(&text).expect("prototext parsing must succeed");
assert_eq!(package, decoded);
}
}
/// The prototext options ADR-0014 decision 8 fixes — `pretty`,
/// `skip_default_fields(false)`, `print_message_fields_in_index_order`.
/// Any option set round-trips, which is why the round-trip test above
/// cannot guard them.
///
/// The first two are asserted through a visible consequence. The third is
/// **not guarded here and cannot be on this schema**: every message in
/// `ir.proto` declares its fields in ascending field-number order, and
/// field-number order is also `prost-reflect`'s default, so index order
/// and default order coincide everywhere and dropping the option would
/// change no output. It is set because the schema's ordering is a
/// property of the schema rather than a guarantee, and a message whose
/// declaration order departs from its numbering would otherwise reorder
/// every artifact it appears in.
#[test]
fn text_format_is_pretty_with_defaults_in_index_order() {
let text = v2::to_text_format(&fixture()).expect("the fixture serializes as prototext");
// pretty: nested messages are indented, one field per line.
assert!(
text.contains("\n "),
"pretty printing must indent nested fields, got: {text}"
);
// skip_default_fields(false): a field holding its default is present
// (decision 2 — `ordinal: 0` is read, not inferred from absence).
assert!(
text.contains("is_error: false"),
"a field holding its default must be emitted, got: {text}"
);
// print_message_fields_in_index_order: `name` is field 1 of
// `Package`, so it opens the output.
assert!(
text.starts_with("name:"),
"fields must print in schema index order, got: {text}"
);
}
/// Parses emitted JSON the way ADR-0014 decision 11's conformance test
/// requires: unknown fields rejected, trailing input rejected. Since
/// decision 14 the strict parser is the pbjson-generated `Deserialize`
/// impl, whose default already rejects unknown fields
/// (`ignore_unknown_fields()` stays unset in `build.rs`), so the
/// strictness needs no option to opt into.
fn strict_parse(json: &str) -> v2::Package {
let mut deserializer = serde_json::Deserializer::from_str(json);
let package = <v2::Package as serde::Deserialize>::deserialize(&mut deserializer)
.expect("a strict conformant parser must accept the emitted JSON");
deserializer.end().expect("no trailing input");
package
}
/// The conformance claim of ADR-0014 decision 11: a conformant protobuf
/// JSON parser configured to reject unknown fields accepts the emitted
/// JSON. Re-reading tests that claim itself; asserting on the rendered
/// text would only restate the serializer's behaviour back to itself.
#[test]
fn emitted_json_survives_a_strict_conformant_parse() {
for package in [fixture(), vocabulary_fixture()] {
let json = v2::to_json_pretty(&package).expect("the fixture serializes as IR JSON");
assert_eq!(package, strict_parse(&json));
}
}
#[test]
fn json_renders_timing_bounds_and_fallible_arms_exactly() {
let json = v2::to_json_pretty(&fixture()).expect("the fixture serializes as IR JSON");
// Exactness is visible: timing bounds are exact-decimal microsecond
// strings, never floating-point numbers (ADR-0008 decision 12) —
// under the canonical lowerCamelCase field name (ADR-0014 decision 1).
assert!(
json.contains(r#""minUs": "10000""#),
"the timing bound must be a JSON string, got: {json}"
);
// Both arms of the inline T | E return are visible by name.
assert!(
json.contains(r#""ok": "FaultPage""#),
"the ok arm must render, got: {json}"
);
assert!(
json.contains(r#""err": "DiagError""#),
"the err arm must render, got: {json}"
);
}
/// ADR-0014 decision 8's stringification, tested on genuine 64-bit
/// fields. The timing assertion above proves nothing about it —
/// `Timing.min_us` is `optional string` in the schema — so the claim
/// needs fields whose wire type actually is `uint64` or `int64`.
#[test]
fn json_renders_64_bit_integer_fields_as_strings() {
let json = v2::to_json_pretty(&vocabulary_fixture())
.expect("the vocabulary fixture serializes as IR JSON");
// uint64: the array's upper bound.
assert!(
json.contains(r#""max": "4096""#),
"an array bound must be a JSON string, got: {json}"
);
// uint64 behind proto3 `optional`: the character length bound.
assert!(
json.contains(r#""lenMax": "86""#),
"a length bound must be a JSON string, got: {json}"
);
// int64: the retired enum value and the enum-set bit position.
assert!(
json.contains(r#""value": "7""#),
"a retired enum value must be a JSON string, got: {json}"
);
assert!(
json.contains(r#""value": "33""#),
"an enum-set bit position must be a JSON string, got: {json}"
);
}
#[test]
fn fallible_transport_identity_follows_the_derivation_rule() {
// The ADR-0008 decision 4 rule: interface + interaction ordinal +
// both arm references, in that order.
let fallible = v2::FallibleType {
ok: "FaultPage".to_string(),
err: "DiagError".to_string(),
};
assert_eq!(
v2::fallible_transport_identity("VehicleStatus", 9, &fallible),
"VehicleStatus#9:FaultPage|DiagError"
);
// Derived from the fixture: the fallible query sits at ordinal 5.
let package = fixture();
let interface = &package.interfaces[0];
let query_decl = &interface.interactions[4];
let Some(v2::decl::Kind::QueryDef(query)) = &query_decl.kind else {
panic!("ordinal 5 must be the fallible query");
};
let Some(v2::return_type::Kind::Fallible(arms)) = &query.return_type.as_ref().unwrap().kind
else {
panic!("fetchFaults must return a fallible type");
};
assert_eq!(
v2::fallible_transport_identity(&interface.name, query_decl.ordinal, arms),
"VehicleStatus#5:FaultPage|DiagError"
);
}
/// `Package::shapes` yields the named interfaces first, then the inline
/// shapes of the services — and each shape carries the name it is known by
/// OUTSIDE the package. The fixture's inline shape has `Interface.name ==
/// ""` by construction, so a walk that yielded the interface bare would
/// hand every consumer the empty string; two of the six E2 defects were
/// exactly that.
#[test]
fn shapes_walks_named_interfaces_and_inline_service_shapes() {
let package = fixture();
let walk: Vec<(&str, bool, usize)> = package
.shapes()
.map(|shape| {
(
shape.name,
shape.is_inline(),
shape.interface.interactions.len(),
)
})
.collect();
assert_eq!(
walk,
[("VehicleStatus", false, 6), ("veh.adas.logs", true, 1)],
"the named interface, then the inline shape under the service's \
dotted name",
);
// The fixture's third shape-bearing declaration is `service
// veh.adas.status : VehicleStatus`, which names an interface already in
// the walk. Yielding it too would visit `VehicleStatus` twice.
assert_eq!(package.services.len(), 2, "one reference form, one inline");
assert!(
!package
.shapes()
.any(|shape| shape.name == "veh.adas.status"),
"a service naming an interface contributes no shape of its own",
);
}
/// The owning service is carried because `Service.visibility` is the
/// authoritative one: an inline shape's own field is
/// `VISIBILITY_UNSPECIFIED` by construction, which is not "internal" and
/// not "public".
#[test]
fn shape_visibility_reads_the_owning_service_for_an_inline_shape() {
let package = fixture();
let shapes: Vec<v2::InterfaceShape<'_>> = package.shapes().collect();
let named = shapes[0];
assert!(named.service.is_none());
assert_eq!(named.visibility(), v2::Visibility::Public as i32);
assert_eq!(named.visibility(), named.interface.visibility);
let inline = shapes[1];
assert_eq!(
inline.interface.visibility,
v2::Visibility::Unspecified as i32,
"the trap: an inline shape's own visibility field is unset",
);
assert_eq!(
inline.service.expect("an inline shape has an owner").name,
"veh.adas.logs",
);
assert_eq!(
inline.visibility(),
v2::Visibility::Public as i32,
"the accessor reads the owning service's, never the unset field",
);
}
/// A package with no service at all still walks its interfaces, and a
/// package with neither yields nothing — the emptiness both backends test
/// for before emitting any interaction vocabulary.
#[test]
fn shapes_is_empty_only_when_the_package_declares_no_shape() {
let mut package = fixture();
package.services.clear();
assert_eq!(package.shapes().count(), 1);
package.interfaces.clear();
assert_eq!(package.shapes().count(), 0);
}
/// A dotted reference contributes its qualifier; a bare one contributes
/// nothing. Every recursive path through `walk_field_type` — array
/// element, tuple field, map key, map value, stream element — carries a
/// distinct qualifier, so no path's absence can hide behind another
/// path's presence: deleting any one arm's body changes the expected set
/// this test compares against, rather than leaving it unchanged.
#[test]
fn referenced_packages_finds_qualifiers_at_depth() {
fn named(reference: &str) -> v2::FieldType {
v2::FieldType {
kind: Some(v2::field_type::Kind::Named(reference.to_string())),
..Default::default()
}
}
fn fixed(payload: v2::FieldType) -> v2::decl::Kind {
v2::decl::Kind::FixedDef(v2::FixedDef {
payload: Some(payload),
})
}
let package = v2::Package {
name: "veh.cluster".to_string(),
decls: vec![
v2::Decl {
name: "Local".to_string(),
kind: Some(v2::decl::Kind::SignalDef(v2::SignalDef {
payload: "Speed".to_string(),
..Default::default()
})),
..Default::default()
},
v2::Decl {
name: "Stamped".to_string(),
kind: Some(v2::decl::Kind::SignalDef(v2::SignalDef {
payload: "ridl.std.Timestamp".to_string(),
..Default::default()
})),
..Default::default()
},
v2::Decl {
name: "ArrLabels".to_string(),
kind: Some(fixed(v2::FieldType {
kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
element: Some(Box::new(named("veh.arr.Label"))),
min: 0,
max: 32,
}))),
..Default::default()
})),
..Default::default()
},
v2::Decl {
name: "TupThing".to_string(),
kind: Some(fixed(v2::FieldType {
kind: Some(v2::field_type::Kind::Tuple(v2::TupleType {
fields: vec![v2::TupleField {
name: "x".to_string(),
r#type: Some(named("veh.tup.X")),
}],
})),
..Default::default()
})),
..Default::default()
},
v2::Decl {
name: "MapThing".to_string(),
kind: Some(fixed(v2::FieldType {
kind: Some(v2::field_type::Kind::Map(Box::new(v2::MapType {
key: Some(Box::new(named("veh.key.X"))),
value: Some(Box::new(named("veh.val.X"))),
min: 0,
max: 8,
}))),
..Default::default()
})),
..Default::default()
},
v2::Decl {
name: "StreamThing".to_string(),
kind: Some(fixed(v2::FieldType {
kind: Some(v2::field_type::Kind::Stream(v2::StreamType {
element: Some(v2::stream_type::Element::Named(
"veh.strm.X".to_string(),
)),
})),
..Default::default()
})),
..Default::default()
},
],
..Default::default()
};
let found = v2::referenced_packages(&package);
let expected: std::collections::BTreeSet<String> = [
"ridl.std", "veh.arr", "veh.tup", "veh.key", "veh.val", "veh.strm",
]
.into_iter()
.map(str::to_string)
.collect();
assert_eq!(
found, expected,
"each recursive path must contribute its own distinct qualifier"
);
assert!(
!found.contains("Speed") && !found.contains("veh.cluster"),
"a bare reference contributes no package: {found:?}",
);
}
/// An empty package references nothing — the negative case the emit rule in
/// `ridlc` depends on.
#[test]
fn referenced_packages_is_empty_without_references() {
let package = v2::Package {
name: "veh.solo".to_string(),
..Default::default()
};
assert!(v2::referenced_packages(&package).is_empty());
}
/// Below prost's recursion limit at two message levels per nesting level
/// — the depth ADR-0014 decision 12 measured as round-tripping correctly.
/// Since decision 14 these two constants bound the prototext transcode
/// alone: JSON no longer transcodes and carries its own read-side
/// ceiling, tested separately below.
const NESTING_BELOW_LIMIT: usize = 45;
/// Past the limit today. The tests assert the outcome — an error, never a
/// panic — not the exact threshold, so a prost release that moves the
/// limit moves these constants, not the assertions.
const NESTING_PAST_LIMIT: usize = 60;
/// One declaration whose payload nests `depth` levels of inline arrays —
/// each level costs two message levels on the wire (`FieldType` plus
/// `ArrayType`), the arithmetic ADR-0014 decision 12 records against
/// prost's recursion limit.
fn nested_package(depth: usize) -> v2::Package {
let mut payload = v2::FieldType {
optional: false,
kind: Some(v2::field_type::Kind::Primitive(
v2::PrimitiveType::Integer as i32,
)),
};
for _ in 0..depth {
payload = v2::FieldType {
optional: false,
kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
element: Some(Box::new(payload)),
min: 1,
max: 1,
}))),
};
}
v2::Package {
name: "veh.deep".to_string(),
decls: vec![v2::Decl {
name: "deep".to_string(),
kind: Some(v2::decl::Kind::FixedDef(v2::FixedDef {
payload: Some(payload),
})),
..Default::default()
}],
..Default::default()
}
}
/// One package whose nesting sits exactly `levels` message levels below
/// the `Package` root — the unit the derived binary encoding's bound is
/// stated in (the IR specification, "The derived encodings").
///
/// The chain under a `FixedDef` costs three levels before any nesting
/// (`Decl`, `FixedDef`, the outermost `FieldType`) and two per array level
/// (`ArrayType`, `FieldType`), so an array-only chain reaches the odd
/// depths alone. One tuple level costs three (`FieldType`, `TupleType`,
/// `TupleField`, then the `FieldType` the next level counts), which is what
/// reaches the even depths. Both shapes are what the front end lowers, so
/// neither is a construction the schema would not otherwise see.
fn package_at_message_depth(levels: usize) -> v2::Package {
assert!(levels >= 3, "the chain costs three levels before nesting");
let (arrays, tuple) = if levels % 2 == 1 {
((levels - 3) / 2, false)
} else {
assert!(levels >= 6, "one tuple level costs three");
((levels - 6) / 2, true)
};
let mut payload = v2::FieldType {
optional: false,
kind: Some(v2::field_type::Kind::Primitive(
v2::PrimitiveType::Integer as i32,
)),
};
for _ in 0..arrays {
payload = v2::FieldType {
optional: false,
kind: Some(v2::field_type::Kind::Array(Box::new(v2::ArrayType {
element: Some(Box::new(payload)),
min: 1,
max: 1,
}))),
};
}
if tuple {
payload = v2::FieldType {
optional: false,
kind: Some(v2::field_type::Kind::Tuple(v2::TupleType {
fields: vec![v2::TupleField {
name: "f0".to_string(),
r#type: Some(payload),
}],
})),
};
}
v2::Package {
name: "veh.deep".to_string(),
decls: vec![v2::Decl {
name: "deep".to_string(),
kind: Some(v2::decl::Kind::FixedDef(v2::FixedDef {
payload: Some(payload),
})),
..Default::default()
}],
..Default::default()
}
}
/// The nesting of JSON objects in a canonical artifact, which in the
/// protobuf JSON mapping is the nesting of messages: every message is an
/// object, a repeated field is an array of them, and the schema declares no
/// `map<>` field. The root `Package` object is included, so a caller
/// counting levels *below* the root subtracts one. Brackets inside a string
/// literal do not count.
fn message_nesting(json: &str) -> usize {
let (mut depth, mut max) = (0usize, 0usize);
let (mut in_string, mut escaped) = (false, false);
for byte in json.bytes() {
if in_string {
if escaped {
escaped = false;
} else if byte == b'\\' {
escaped = true;
} else if byte == b'"' {
in_string = false;
}
continue;
}
match byte {
b'"' => in_string = true,
b'{' => {
depth += 1;
max = max.max(depth);
}
b'}' => depth = depth.saturating_sub(1),
_ => {}
}
}
max
}
/// [`package_at_message_depth`] builds what it claims, on both parities.
/// Without this the two bound tests below would pin a depth nobody
/// measured.
#[test]
fn package_at_message_depth_builds_the_depth_it_names() {
with_sized_stack(|| {
for levels in [3, 6, 7, 99, 100, 101] {
let json = v2::to_json_pretty(&package_at_message_depth(levels))
.expect("the writer is unrestricted at these depths");
assert_eq!(
message_nesting(&json) - 1,
levels,
"the chain must nest {levels} message levels below the root"
);
}
});
}
/// The derived binary encoding's bound, stated by the IR specification and
/// pinned here: 100 message levels below the root round-trip.
///
/// `to_binary` writes any depth; it is `from_binary` that stops, at prost's
/// `RECURSION_LIMIT` of 100, decremented once per nested message on decode
/// and not consulted on encode. The test asserts the outcome, not prost's
/// constant: a prost release that moves the limit moves these two tests and
/// the specification's paragraph together.
#[test]
fn binary_round_trip_at_100_message_levels_succeeds() {
let package = package_at_message_depth(100);
let bytes = v2::to_binary(&package);
let decoded = v2::from_binary(&bytes).expect("100 message levels decode");
assert_eq!(package, decoded);
}
/// One level past that bound the binary reader refuses — an error, never a
/// panic — while the canonical encoding carries the same package. This is
/// the asymmetry the specification states as the reason binary is derived
/// rather than canonical (driftsys/ridl#231).
#[test]
fn binary_decode_at_101_message_levels_returns_an_error() {
let package = package_at_message_depth(101);
let bytes = v2::to_binary(&package);
let error = v2::from_binary(&bytes).expect_err("101 message levels must fail, not panic");
assert!(
error.to_string().contains("recursion limit reached"),
"the error must name the limit, got: {error}"
);
let json = v2::to_json_pretty(&package).expect("the canonical encoding has no such bound");
assert_eq!(
package,
v2::from_json(&json).expect("the canonical encoding round-trips the same package")
);
}
/// The write side after ADR-0014 decision 14: the pbjson-generated
/// writer recurses the typed message directly — no transcode, so no
/// message-level recursion limit — and 400 levels of array nesting,
/// roughly eight times the ceiling decision 12 recorded, serialize and
/// round-trip. Run on an explicitly sized stack: the writer recurses on
/// the caller's stack, and debug-build frames at this depth overflow the
/// default test-thread stack (the reader sizes its own thread inside
/// `from_json`).
#[test]
fn json_round_trip_at_400_nested_levels_succeeds() {
with_sized_stack(|| {
let package = nested_package(400);
let json = v2::to_json_pretty(&package).expect("the writer has no message-level limit");
let decoded = v2::from_json(&json).expect("the reader parses within its ceiling");
assert_eq!(package, decoded);
});
}
/// The one error path on the JSON write side (ADR-0014 decision 14),
/// and it is new with the generated impl, not a survivor of the
/// transcode's: an `i32` enum field holding a discriminant outside the
/// schema — data, not depth — which the retired reflection path
/// serialized successfully as its bare number. The checker never
/// produces one, so there is no CLI route to this failure; it is pinned
/// here at the crate surface.
#[test]
fn json_serialization_of_an_out_of_schema_discriminant_returns_an_error() {
let mut package = fixture();
package.decls[0].visibility = 999;
let err = v2::to_json_pretty(&package)
.expect_err("an out-of-schema discriminant must fail, not panic");
let message = err.to_string();
assert!(
message.contains("canonical protobuf JSON"),
"the error must name the encoding that failed, got: {message}"
);
assert!(
message.contains("discriminant outside the schema"),
"the error must name the known cause, got: {message}"
);
}
/// The strictness ADR-0014 decision 11 relies on is the generated
/// deserializer's default: `ignore_unknown_fields()` is the opt-out and
/// stays unset, so a field the schema does not declare is an error,
/// never silently dropped.
#[test]
fn json_parse_rejects_an_unknown_field() {
let error = v2::from_json(r#"{"name": "veh.deep", "notAField": 1}"#)
.expect_err("an unknown field must be rejected");
assert!(
error.to_string().contains("unknown field"),
"the error must name the defect, got: {error}"
);
}
/// A reader narrowing ADR-0014 decision 14 records: the proto3 JSON
/// mapping expects parsers to accept numeric enum values, and the
/// generated deserializer does — within the schema's range. A
/// discriminant outside it (`"visibility": 77`) is rejected, where the
/// retired reflection reader accepted it — and the retired *writer*
/// emitted exactly such a number for an out-of-schema discriminant.
/// Pinned so the narrowing stays a decision rather than an accident: a
/// future mechanism change must confront this test.
#[test]
fn json_parse_rejects_an_out_of_range_numeric_enum_value() {
let with_visibility =
|value: &str| format!(r#"{{"name": "veh.x", "decls": [{{"visibility": {value}}}]}}"#);
v2::from_json(&with_visibility("1"))
.expect("an in-range numeric enum value parses, as the mapping expects");
let error = v2::from_json(&with_visibility("77"))
.expect_err("an out-of-range numeric enum value must be rejected");
assert!(
error.to_string().contains("invalid value: integer `77`"),
"the error must name the value, got: {error}"
);
}
/// A reader narrowing ADR-0014 decision 14 records: the mapping accepts
/// float and exponent notation for integer fields (`"min": 1.0`), and
/// the retired reflection reader did; the generated deserializer
/// rejects both. Pinned for the same reason as the numeric-enum case
/// above.
#[test]
fn json_parse_rejects_a_float_form_integer() {
for spelling in ["1.0", "1e0"] {
let error = v2::from_json(&format!(
r#"{{"name": "veh.x", "decls": [{{"fixedDef": {{"payload": {{"array": {{"min": {spelling}}}}}}}}}]}}"#,
))
.expect_err("a float-form integer must be rejected");
assert!(
error.to_string().contains("did not match any variant"),
"the integer field's deserializer must be the one refusing `{spelling}`, \
got: {error}"
);
}
}
/// A reader narrowing ADR-0014 decision 14 records: `null` for a
/// repeated field (`"decls": null`), which the retired reflection
/// reader read as empty, is rejected. `null` for an optional scalar or
/// message field is still accepted — parity with the retired reader,
/// asserted alongside so the narrowing's edge is pinned from both
/// sides.
#[test]
fn json_parse_rejects_null_for_a_repeated_field() {
let error = v2::from_json(r#"{"name": "veh.x", "decls": null}"#)
.expect_err("null for a repeated field must be rejected");
assert!(
error.to_string().contains("invalid type: null"),
"the error must name the null, got: {error}"
);
v2::from_json(r#"{"name": "veh.x", "decls": [{"deprecated": null}]}"#)
.expect("null for an optional scalar field still parses");
}
/// A reader narrowing ADR-0014 decision 14 records: a duplicate JSON
/// key, which the retired reflection reader resolved last-wins, is
/// rejected.
#[test]
fn json_parse_rejects_a_duplicate_key() {
let error = v2::from_json(r#"{"name": "a", "name": "b"}"#)
.expect_err("a duplicate key must be rejected");
assert!(
error.to_string().contains("duplicate field `name`"),
"the error must name the duplicated field, got: {error}"
);
}
/// The read-side ceiling (ADR-0014 decision 14): nesting past 1,000
/// bracket levels returns an error before the parse begins — a
/// diagnostic, where unbounded recursion would eventually abort on a
/// stack overflow no caller can catch. The input is real writer output:
/// past the ceiling the asymmetry is deliberate — the writer is
/// unrestricted, the reader is not.
#[test]
fn json_parse_past_the_nesting_ceiling_returns_an_error() {
with_sized_stack(|| {
let json = v2::to_json_pretty(&nested_package(500))
.expect("the writer is unrestricted at this depth");
let error = v2::from_json(&json).expect_err("the reader must refuse past its ceiling");
assert!(
error.to_string().contains("1000 JSON levels"),
"the error must name the ceiling, got: {error}"
);
});
}
/// The ceiling is exact: 1,000 open brackets pass the scan and reach the
/// parser — which then rejects the input as not a package — and 1,001 do
/// not. The scan runs before the parse, so the over-ceiling probe needs
/// no valid JSON behind its brackets.
#[test]
fn json_nesting_ceiling_binds_exactly_at_1000() {
let at = v2::from_json(&"[".repeat(1_000)).expect_err("an array is not a package");
assert!(
!at.to_string().contains("JSON levels"),
"at the ceiling the parser, not the scan, must be the one refusing, got: {at}"
);
let past = v2::from_json(&"[".repeat(1_001)).expect_err("past the ceiling, the scan");
assert!(
past.to_string().contains("1000 JSON levels"),
"past the ceiling the error must name it, got: {past}"
);
}
/// The nesting scan behind the ceiling: brackets count only outside
/// string literals, an escaped quote does not end a literal, an escaped
/// backslash does not disarm the real closing quote after it, and a
/// stray closer never underflows the running depth.
#[test]
fn nesting_scan_counts_brackets_outside_string_literals_only() {
// Plain structural nesting counts every open bracket.
assert_eq!(v2::max_json_nesting(r#"{"a": [{"b": []}]}"#), 4);
// Brackets inside a string literal do not count.
assert_eq!(v2::max_json_nesting(r#"{"doc": "{[[[{"}"#), 1);
// An escaped quote does not end the literal, so the brackets after
// it are still inside it.
assert_eq!(v2::max_json_nesting(r#"{"doc": "a\"[[[", "x": []}"#), 2);
// An escaped backslash does not escape the closing quote: the
// literal ends, and the brackets after it count.
assert_eq!(v2::max_json_nesting(r#"{"doc": "a\\", "x": [[]]}"#), 3);
// A stray closer saturates at zero rather than underflowing.
assert_eq!(v2::max_json_nesting("]]]{"), 1);
}
/// The prototext form of [`nested_package`], built by hand for the same
/// reason [`nested_json`] is: past the limit the serializer rejects the
/// package, so its prototext cannot come from [`v2::to_text_format`].
fn nested_text(depth: usize) -> String {
let mut payload = "primitive: PRIMITIVE_TYPE_INTEGER".to_string();
for _ in 0..depth {
payload = format!("array {{ element {{ {payload} }} min: 1 max: 1 }}");
}
format!(
r#"name: "veh.deep" decls {{ name: "deep" fixed_def {{ payload {{ {payload} }} }} }}"#
)
}
/// The prototext write path carries the same recursion-limit failure mode
/// as JSON — both go through the one transcode (ADR-0014 decision 12) —
/// and reports it as an error naming its own encoding, never a panic.
#[test]
fn text_serialization_past_the_nesting_limit_returns_an_error() {
let err = v2::to_text_format(&nested_package(NESTING_PAST_LIMIT))
.expect_err("serialization past the recursion limit must fail, not panic");
let message = err.to_string();
assert!(
message.contains("recursion limit"),
"the error must name the nesting limit as the known cause, got: {message}"
);
assert!(
message.contains("prototext"),
"the error must name the encoding that failed, got: {message}"
);
}
/// Runs `test` on a thread whose stack fits the recursion the test
/// drives on its own thread. Two groups need one. The prototext parser
/// recurses once per message level with debug-build frames large enough
/// that the default 2 MiB test-thread stack overflows near 45 array
/// levels — under prost's own recursion limit, so the depths
/// [`NESTING_BELOW_LIMIT`] and [`NESTING_PAST_LIMIT`] pin are
/// unreachable on that stack; the production paths are unaffected, since
/// the toolchain writes prototext and never parses it (`ridl diff` and
/// the baselines stay `.ir.json`, ADR-0014 decision 5). And the deep
/// JSON tests drive the pbjson-generated writer, which recurses on the
/// caller's stack (ADR-0014 decision 14 — only the reader sizes a
/// thread of its own, inside `from_json`).
fn with_sized_stack(test: impl FnOnce() + Send + 'static) {
let outcome = std::thread::Builder::new()
.stack_size(16 * 1024 * 1024)
.spawn(test)
.expect("spawn the large-stack test thread")
.join();
if let Err(payload) = outcome {
std::panic::resume_unwind(payload);
}
}
/// The read direction: the text-format parser itself has no depth limit,
/// so the failure is the transcode out of the dynamic message, mapped
/// into the error return instead of expected on (ADR-0014 decision 12).
#[test]
fn text_parse_past_the_nesting_limit_returns_an_error() {
with_sized_stack(|| {
let error = v2::from_text_format(&nested_text(NESTING_PAST_LIMIT))
.expect_err("parsing past the recursion limit must fail, not panic");
// Assert *which* stage failed: prost's transcoding decoder says
// "recursion limit reached", and a parse-stage failure would
// render through the `Parse` variant instead.
let message = error.to_string();
assert!(
message.contains("recursion limit reached"),
"the transcode out of the dynamic message must be the failing \
stage, got: {message}"
);
});
}
/// The prototext bound must not tighten silently either: below the limit
/// the package still serializes and round-trips.
#[test]
fn text_round_trip_below_the_nesting_limit_succeeds() {
with_sized_stack(|| {
let package = nested_package(NESTING_BELOW_LIMIT);
let text = v2::to_text_format(&package)
.expect("below the recursion limit, serialization succeeds");
let decoded =
v2::from_text_format(&text).expect("below the recursion limit, parsing succeeds");
assert_eq!(package, decoded);
});
}
}
#[cfg(test)]
mod vacuous_constraint {
use crate::v2;
/// A constraint with every field absent. Each test sets only the field it
/// is about, so no assertion can pass through a neighbouring field.
fn constraint() -> v2::Constraint {
v2::Constraint {
min: None,
max: None,
step: None,
len_min: None,
len_max: None,
pattern: None,
pattern_const: None,
}
}
#[test]
fn an_absent_or_empty_constraint_is_vacuous() {
assert!(v2::constraint_is_vacuous(None));
assert!(v2::constraint_is_vacuous(Some(&constraint())));
}
#[test]
fn a_step_constraint_is_non_vacuous() {
let stepped = v2::Constraint {
step: Some("0.5".to_string()),
..constraint()
};
assert!(!v2::constraint_is_vacuous(Some(&stepped)));
}
/// Every constrained field on its own. A fixture setting a pair — `min`
/// with `max`, or `len_min` with `len_max` — cannot tell a predicate that
/// reads both from one that reads either, so each bound here is one-sided.
/// The paired shapes are pinned separately by
/// [`a_bound_pair_set_together_is_non_vacuous`], which a one-sided fixture
/// cannot do.
#[test]
fn any_single_constrained_field_is_non_vacuous() {
let cases = [
(
"min",
v2::Constraint {
min: Some("0.0".to_string()),
..constraint()
},
),
(
"max",
v2::Constraint {
max: Some("250.0".to_string()),
..constraint()
},
),
(
"len_min",
v2::Constraint {
len_min: Some(1),
..constraint()
},
),
(
"len_max",
v2::Constraint {
len_max: Some(256),
..constraint()
},
),
(
"pattern",
v2::Constraint {
pattern: Some("^[a-z]+$".to_string()),
..constraint()
},
),
(
"pattern_const",
v2::Constraint {
pattern_const: Some("NAME_PATTERN".to_string()),
..constraint()
},
),
];
for (field, case) in cases {
assert!(
!v2::constraint_is_vacuous(Some(&case)),
"`{field}` alone must be non-vacuous"
);
}
}
/// The two shapes the checker actually emits: a declared range, and the
/// typl §4.4 default `[0..256]` every string and bytes type carries.
///
/// A one-sided fixture cannot pin these. A predicate reading each bound as
/// a pair — `(c.min.is_none() == c.max.is_none())` and the same for the
/// length bounds — passes every one-sided case and still reports both
/// shapes below as vacuous, which would drop the range check from every
/// bounded number and every string.
#[test]
fn a_bound_pair_set_together_is_non_vacuous() {
let ranged = v2::Constraint {
min: Some("0.0".to_string()),
max: Some("250.0".to_string()),
..constraint()
};
assert!(!v2::constraint_is_vacuous(Some(&ranged)));
let default_length = v2::Constraint {
len_min: Some(0),
len_max: Some(256),
..constraint()
};
assert!(!v2::constraint_is_vacuous(Some(&default_length)));
}
}
#[cfg(test)]
mod system_round_trip {
use crate::v2;
fn attribute(namespace: &str, key: &str, value: Option<v2::AttributeValue>) -> v2::Attribute {
v2::Attribute {
namespace: namespace.to_string(),
key: key.to_string(),
value,
}
}
fn scalar(text: &str) -> v2::AttributeValue {
v2::AttributeValue {
kind: Some(v2::attribute_value::Kind::Scalar(text.to_string())),
}
}
fn list(items: Vec<v2::AttributeValue>) -> v2::AttributeValue {
v2::AttributeValue {
kind: Some(v2::attribute_value::Kind::List(v2::AttributeList { items })),
}
}
fn interface(catalog: &str, name: &str, inline: bool) -> Option<v2::InterfaceRef> {
Some(v2::InterfaceRef {
catalog: catalog.to_string(),
name: name.to_string(),
inline,
})
}
fn endpoint(component: &str, instance: &str, machine: &str) -> v2::Endpoint {
v2::Endpoint {
component: component.to_string(),
instance: instance.to_string(),
machine: machine.to_string(),
}
}
/// A reduced rsdl reference Appendix A: `Cruise` with two instances
/// offering `veh.adas.cruise` and requiring `LaneAssist`, the implicit
/// component of `veh.diag.access`, one distribution and one deployment.
/// Every message of `system.proto` appears at least once, with every
/// scalar set to a value other than its default — a flag and a nested-list
/// attribute value included — so a round trip that drops a field is
/// caught.
fn doc_link() -> v2::DocLink {
v2::DocLink {
text: "Cruise".to_string(),
offset: 16,
len: 6,
target: "veh.topology.Cruise".to_string(),
}
}
fn fixture() -> v2::System {
let link = v2::Link {
interface: interface("veh.diag", "veh.diag.access", true),
service: "veh.diag.access".to_string(),
consumer: Some(endpoint("veh.topology.Backend", "Unit", "Cloud")),
producer: Some(endpoint("veh.diag.access", "Unit", "AdasHpc")),
crossing: v2::Crossing::OffBoard as i32,
};
v2::System {
name: "Vehicle".to_string(),
package: "veh.topology".to_string(),
labels: vec!["ASIL_B".to_string()],
attributes: vec![attribute("rust", "crate", Some(scalar("\"vehicle\"")))],
members: vec![
v2::MemberLine {
component: "veh.topology.Cruise".to_string(),
attributes: vec![attribute("linux", "pinned", None)],
doc: "Documented, see [Cruise].".to_string(),
links: vec![doc_link()],
see: vec![doc_link()],
since: vec!["1.2".to_string()],
},
v2::MemberLine {
component: "veh.diag.access".to_string(),
attributes: vec![],
doc: "Documented, see [Cruise].".to_string(),
links: vec![doc_link()],
see: vec![doc_link()],
since: vec!["1.2".to_string()],
},
],
components: vec![
v2::Component {
name: "Cruise".to_string(),
package: "veh.topology".to_string(),
implicit: false,
external: true,
instances: vec!["primary".to_string(), "backup".to_string()],
offers: vec![v2::Offer {
service: "veh.adas.cruise".to_string(),
attributes: vec![attribute("someip", "serviceId", Some(scalar("4097")))],
doc: "Documented, see [Cruise].".to_string(),
links: vec![doc_link()],
see: vec![doc_link()],
since: vec!["1.2".to_string()],
}],
requires: vec![v2::Require {
interface: interface("veh.adas", "LaneAssist", false),
service: "veh.adas.lane".to_string(),
producer: "veh.topology.Lane".to_string(),
attributes: vec![attribute(
"linux",
"cpuset",
Some(list(vec![scalar("2"), list(vec![scalar("3")])])),
)],
doc: "Documented, see [Cruise].".to_string(),
links: vec![doc_link()],
see: vec![doc_link()],
since: vec!["1.2".to_string()],
}],
labels: vec!["ASIL_B".to_string()],
attributes: vec![attribute("rust", "crate", None)],
doc: "Documented, see [Cruise].".to_string(),
links: vec![doc_link()],
see: vec![doc_link()],
since: vec!["1.2".to_string()],
},
v2::Component {
name: "veh.diag.access".to_string(),
package: String::new(),
implicit: true,
external: false,
instances: vec!["Unit".to_string()],
offers: vec![v2::Offer {
service: "veh.diag.access".to_string(),
attributes: vec![],
doc: "Documented, see [Cruise].".to_string(),
links: vec![doc_link()],
see: vec![doc_link()],
since: vec!["1.2".to_string()],
}],
requires: vec![],
labels: vec![],
attributes: vec![],
doc: "Documented, see [Cruise].".to_string(),
links: vec![doc_link()],
see: vec![doc_link()],
since: vec!["1.2".to_string()],
},
],
producers: vec![v2::Producer {
service: "veh.adas.cruise".to_string(),
component: "veh.topology.Cruise".to_string(),
instances: vec!["primary".to_string(), "backup".to_string()],
not_yet_realizable: true,
}],
grants: vec![v2::Grant {
component: "veh.topology.Backend".to_string(),
external: true,
regions: vec!["veh.adas".to_string(), "veh.diag".to_string()],
}],
regions: vec![v2::Region {
catalog: "veh.diag".to_string(),
hash: vec![0xab; 32],
interfaces: vec![v2::RegionInterface {
name: "veh.diag.access".to_string(),
inline: true,
number: 2,
provisional: true,
service: "veh.diag.access".to_string(),
}],
}],
distributions: vec![v2::Distribution {
name: "Adas".to_string(),
package: "veh.topology".to_string(),
members: vec![v2::MemberLine {
component: "veh.topology.Cruise".to_string(),
attributes: vec![],
doc: "Documented, see [Cruise].".to_string(),
links: vec![doc_link()],
see: vec![doc_link()],
since: vec!["1.2".to_string()],
}],
depends_on: vec!["veh.topology.Base".to_string()],
labels: vec!["PLATFORM_BUNDLE".to_string()],
attributes: vec![attribute("deb", "section", Some(scalar("net")))],
doc: "Documented, see [Cruise].".to_string(),
links: vec![doc_link()],
see: vec![doc_link()],
since: vec!["1.2".to_string()],
}],
deployments: vec![v2::Deployment {
name: "Production".to_string(),
package: "veh.topology".to_string(),
labels: vec!["FLEET".to_string()],
attributes: vec![attribute("ota", "channel", Some(scalar("stable")))],
machines: vec![v2::Machine {
name: "Cloud".to_string(),
external: true,
labels: vec!["OFF_BOARD".to_string()],
attributes: vec![attribute("net", "zone", Some(scalar("wan")))],
doc: "Documented, see [Cruise].".to_string(),
links: vec![doc_link()],
see: vec![doc_link()],
since: vec!["1.2".to_string()],
}],
placements: vec![v2::Placement {
component: "veh.topology.Cruise".to_string(),
instance: "backup".to_string(),
machine: "Cockpit".to_string(),
attributes: vec![attribute("linux", "cpuset", Some(list(vec![])))],
sizing: Some(v2::Sizing {
depth: Some(4_294_967_295),
slots: Some(65_536),
budget: Some(18_446_744_073_709_551_615),
}),
}],
links: vec![link.clone()],
routes: vec![v2::Route {
catalog: "veh.adas".to_string(),
interface_number: 2,
member_ordinal: 1,
interface: "LaneAssist".to_string(),
member: "active".to_string(),
service: "veh.adas.lane".to_string(),
producers: vec![endpoint("veh.topology.Lane", "Unit", "AdasHpc")],
}],
surface: vec![v2::Surface {
link: Some(link),
direction: v2::SurfaceDirection::ExternalConsumes as i32,
}],
installations: vec![v2::Installation {
distribution: "veh.topology.Adas".to_string(),
machines: vec!["AdasHpc".to_string(), "Cockpit".to_string()],
}],
doc: "Documented, see [Cruise].".to_string(),
doc_links: vec![doc_link()],
see: vec![doc_link()],
since: vec!["1.2".to_string()],
sizing: Some(v2::Sizing {
depth: Some(3),
slots: Some(8),
budget: Some(4096),
}),
}],
doc: "Documented, see [Cruise].".to_string(),
see: vec![doc_link()],
since: vec!["1.2".to_string()],
links: vec![doc_link()],
}
}
#[test]
fn system_binary_round_trip_preserves_system() {
let system = fixture();
let decoded = v2::system_from_binary(v2::system_to_binary(&system).as_slice())
.expect("decode must succeed");
assert_eq!(system, decoded);
}
/// The canonical JSON of the system artifact re-reads through the same
/// strict pbjson-generated impl the package uses (ADR-0014 decisions 11
/// and 14): unknown fields rejected, the catalog hash as base64, enums by
/// name, the nested attribute list intact.
#[test]
fn system_json_round_trip_preserves_system() {
let system = fixture();
let json = v2::system_to_json_pretty(&system).expect("the fixture serializes as JSON");
assert!(
json.contains("\"hash\": \"q6urq6urq6urq6urq6urq6urq6urq6urq6urq6urq6s=\""),
"bytes render as base64, got:\n{json}"
);
assert!(
json.contains("\"crossing\": \"CROSSING_OFF_BOARD\""),
"enums render by name, got:\n{json}"
);
assert!(
json.contains("\"notYetRealizable\": true"),
"fields render in lowerCamelCase, got:\n{json}"
);
assert!(
json.contains("\"budget\": \"18446744073709551615\""),
"a 64-bit value renders as a string, got:\n{json}"
);
assert_eq!(
system,
v2::system_from_json(&json).expect("the JSON parses")
);
assert!(
v2::system_from_json(&json.replacen("\"name\"", "\"nam\"", 1)).is_err(),
"an unknown field is rejected"
);
}
/// An absent `sizing` and an empty one are different on the wire: a plugin
/// reads "nothing declared" and "declared nothing" apart, in the binary and
/// the JSON encodings.
#[test]
fn an_absent_sizing_and_an_empty_one_stay_distinct_through_the_encodings() {
let mut absent = fixture();
absent.deployments[0].sizing = None;
absent.deployments[0].placements[0].sizing = None;
let mut empty = absent.clone();
empty.deployments[0].sizing = Some(v2::Sizing::default());
empty.deployments[0].placements[0].sizing = Some(v2::Sizing::default());
for system in [&absent, &empty] {
let binary = v2::system_from_binary(v2::system_to_binary(system).as_slice())
.expect("decode must succeed");
assert_eq!(system, &binary);
let json = v2::system_to_json_pretty(system).expect("serializes as JSON");
assert_eq!(
system,
&v2::system_from_json(&json).expect("the JSON parses")
);
}
assert_ne!(
v2::system_to_binary(&absent),
v2::system_to_binary(&empty),
"the binary encodings differ"
);
}
#[test]
fn system_text_format_round_trip_preserves_system() {
let system = fixture();
let text = v2::system_to_text_format(&system).expect("the fixture serializes as prototext");
assert!(
text.starts_with("name:"),
"fields print in schema index order, got: {text}"
);
assert_eq!(
system,
v2::system_from_text_format(&text).expect("prototext parsing must succeed")
);
}
/// `pkg.Name` for a declared name; the implicit component of a lone
/// service, which no package declares, is its own qualified name.
#[test]
fn qualified_names_follow_the_one_derivation() {
let system = fixture();
assert_eq!(system.qualified_name(), "veh.topology.Vehicle");
assert_eq!(system.components[0].qualified_name(), "veh.topology.Cruise");
assert_eq!(system.components[1].qualified_name(), "veh.diag.access");
assert_eq!(
system.distributions[0].qualified_name(),
"veh.topology.Adas"
);
}
}