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
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
use crate::openapi::{Discriminator, OpenApiSpec, Schema, SchemaType as OpenApiSchemaType};
use crate::{GeneratorError, Result};
use serde_json::Value;
use std::collections::{BTreeMap, HashSet};
use std::path::Path;
#[derive(Debug, Clone)]
pub struct SchemaAnalysis {
/// All schemas indexed by name
pub schemas: BTreeMap<String, AnalyzedSchema>,
/// Dependency graph for generation ordering
pub dependencies: DependencyGraph,
/// Detected patterns and transformations
pub patterns: DetectedPatterns,
/// OpenAPI operations and their request/response schemas
pub operations: BTreeMap<String, OperationInfo>,
}
#[derive(Debug, Clone)]
pub struct AnalyzedSchema {
pub name: String,
pub original: Value,
pub schema_type: SchemaType,
pub dependencies: HashSet<String>,
pub nullable: bool,
pub description: Option<String>,
pub default: Option<serde_json::Value>,
}
#[derive(Debug, Clone)]
pub enum SchemaType {
/// Simple primitive type
Primitive { rust_type: String },
/// Object with properties
Object {
properties: BTreeMap<String, PropertyInfo>,
required: HashSet<String>,
additional_properties: bool,
},
/// Discriminated union (oneOf + discriminator)
DiscriminatedUnion {
discriminator_field: String,
variants: Vec<UnionVariant>,
},
/// Simple union (anyOf without discriminator)
Union { variants: Vec<SchemaRef> },
/// Array type
Array { item_type: Box<SchemaType> },
/// String enum
StringEnum { values: Vec<String> },
/// Extensible enum with known values and custom variant
ExtensibleEnum { known_values: Vec<String> },
/// Schema composition (allOf)
Composition { schemas: Vec<SchemaRef> },
/// Reference to another schema
Reference { target: String },
}
#[derive(Debug, Clone)]
pub struct PropertyInfo {
pub schema_type: SchemaType,
pub nullable: bool,
pub description: Option<String>,
pub default: Option<serde_json::Value>,
pub serde_attrs: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct UnionVariant {
pub rust_name: String,
pub type_name: String,
pub discriminator_value: String,
pub schema_ref: String,
}
#[derive(Debug, Clone)]
pub struct SchemaRef {
pub target: String,
pub nullable: bool,
}
#[derive(Debug, Clone)]
pub struct DependencyGraph {
pub edges: BTreeMap<String, HashSet<String>>,
/// Set of schemas that have recursive dependencies
pub recursive_schemas: HashSet<String>,
}
#[derive(Debug, Clone)]
pub struct DetectedPatterns {
/// Schemas that should use tagged enums (discriminated unions)
pub tagged_enum_schemas: HashSet<String>,
/// Schemas that should use untagged enums (simple unions)
pub untagged_enum_schemas: HashSet<String>,
/// Auto-detected type mappings for discriminated unions
pub type_mappings: BTreeMap<String, BTreeMap<String, String>>,
}
/// Information about an OpenAPI operation
#[derive(Debug, Clone, serde::Serialize)]
pub struct OperationInfo {
/// Operation ID
pub operation_id: String,
/// HTTP method (GET, POST, etc.)
pub method: String,
/// Path template
pub path: String,
/// Short summary from OpenAPI spec
pub summary: Option<String>,
/// Longer description from OpenAPI spec
pub description: Option<String>,
/// Request body content type and schema (if any)
pub request_body: Option<RequestBodyContent>,
/// Response schemas by status code
pub response_schemas: BTreeMap<String, String>,
/// Parameters (path, query, header)
pub parameters: Vec<ParameterInfo>,
/// Whether this operation supports streaming
pub supports_streaming: bool,
/// Stream parameter name if applicable
pub stream_parameter: Option<String>,
}
/// Content type and schema for a request body
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "kind")]
pub enum RequestBodyContent {
Json { schema_name: String },
FormUrlEncoded { schema_name: String },
Multipart,
OctetStream,
TextPlain,
}
impl RequestBodyContent {
/// Get the schema name if this content type has one
pub fn schema_name(&self) -> Option<&str> {
match self {
Self::Json { schema_name } | Self::FormUrlEncoded { schema_name } => Some(schema_name),
_ => None,
}
}
}
/// Information about an operation parameter
#[derive(Debug, Clone, serde::Serialize)]
pub struct ParameterInfo {
/// Parameter name
pub name: String,
/// Parameter location (path, query, header, cookie)
pub location: String,
/// Whether the parameter is required
pub required: bool,
/// Schema reference for the parameter type
pub schema_ref: Option<String>,
/// Rust type for this parameter
pub rust_type: String,
/// Description from OpenAPI spec
pub description: Option<String>,
}
impl Default for DependencyGraph {
fn default() -> Self {
Self::new()
}
}
impl DependencyGraph {
pub fn new() -> Self {
Self {
edges: BTreeMap::new(),
recursive_schemas: HashSet::new(),
}
}
pub fn add_dependency(&mut self, from: String, to: String) {
self.edges.entry(from).or_default().insert(to);
}
/// Get topological sort order for generation
pub fn topological_sort(&mut self) -> Result<Vec<String>> {
// First, detect and handle recursive dependencies
self.detect_recursive_schemas();
// Create a temporary graph without self-referencing edges for sorting
let mut temp_edges = self.edges.clone();
for (schema, deps) in &mut temp_edges {
deps.remove(schema); // Remove self-references
}
let mut visited = HashSet::new();
let mut temp_visited = HashSet::new();
let mut result = Vec::new();
// Visit all nodes using the temporary graph in sorted order for deterministic output
let mut all_nodes: Vec<_> = temp_edges.keys().collect();
all_nodes.sort();
for node in all_nodes {
if !visited.contains(node) {
self.visit_node_recursive(
node,
&temp_edges,
&mut visited,
&mut temp_visited,
&mut result,
)?;
}
}
result.reverse();
Ok(result)
}
fn detect_recursive_schemas(&mut self) {
for (schema, deps) in &self.edges {
if deps.contains(schema) {
// Direct self-reference
self.recursive_schemas.insert(schema.clone());
} else {
// Check for indirect cycles
if self.has_cycle_from(schema, schema, &mut HashSet::new()) {
self.recursive_schemas.insert(schema.clone());
}
}
}
// Also detect mutual recursion (like GraphNode <-> GraphEdge)
for (schema, deps) in &self.edges {
for dep in deps {
if let Some(dep_deps) = self.edges.get(dep) {
if dep_deps.contains(schema) {
// Mutual recursion detected
self.recursive_schemas.insert(schema.clone());
self.recursive_schemas.insert(dep.clone());
}
}
}
}
}
fn has_cycle_from(&self, start: &str, current: &str, visited: &mut HashSet<String>) -> bool {
if visited.contains(current) {
return false; // Already checked this path
}
visited.insert(current.to_string());
if let Some(deps) = self.edges.get(current) {
for dep in deps {
if dep == start {
return true; // Found cycle back to start
}
if self.has_cycle_from(start, dep, visited) {
return true;
}
}
}
false
}
#[allow(clippy::only_used_in_recursion)]
fn visit_node_recursive(
&self,
node: &str,
temp_edges: &BTreeMap<String, HashSet<String>>,
visited: &mut HashSet<String>,
temp_visited: &mut HashSet<String>,
result: &mut Vec<String>,
) -> Result<()> {
if temp_visited.contains(node) {
// This should not happen with cycle-free temp graph, but just in case
return Ok(());
}
if visited.contains(node) {
return Ok(());
}
temp_visited.insert(node.to_string());
if let Some(dependencies) = temp_edges.get(node) {
// Sort dependencies for deterministic topological order
let mut sorted_deps: Vec<_> = dependencies.iter().collect();
sorted_deps.sort();
for dep in sorted_deps {
self.visit_node_recursive(dep, temp_edges, visited, temp_visited, result)?;
}
}
temp_visited.remove(node);
visited.insert(node.to_string());
result.push(node.to_string());
Ok(())
}
}
/// Merge schema extension files into the main OpenAPI specification
/// Uses simple recursive JSON object merging
pub fn merge_schema_extensions(
main_spec: Value,
extension_paths: &[impl AsRef<Path>],
) -> Result<Value> {
let mut result = main_spec;
for path in extension_paths {
let extension = load_extension_file(path.as_ref())?;
result = merge_json_objects_with_replacements(result, extension)?;
}
Ok(result)
}
/// Load an extension file and parse as JSON
fn load_extension_file(path: &Path) -> Result<Value> {
let content = std::fs::read_to_string(path).map_err(|e| GeneratorError::FileError {
message: format!("Failed to read file {}: {}", path.display(), e),
})?;
serde_json::from_str(&content).map_err(GeneratorError::ParseError)
}
/// Merge JSON objects with explicit replacement support
fn merge_json_objects_with_replacements(main: Value, extension: Value) -> Result<Value> {
// Extract replacement rules from the extension
let replacements = extract_replacement_rules(&extension);
// Perform the merge with replacement awareness
Ok(merge_json_objects_with_rules(
main,
extension,
&replacements,
))
}
/// Extract x-replacements rules from extension
fn extract_replacement_rules(
extension: &Value,
) -> std::collections::HashMap<String, (String, String)> {
let mut rules = std::collections::HashMap::new();
if let Some(x_replacements) = extension.get("x-replacements") {
if let Some(x_replacements_obj) = x_replacements.as_object() {
for (schema_name, replacement_rule) in x_replacements_obj {
if let Some(rule_obj) = replacement_rule.as_object() {
if let (Some(replace), Some(with)) = (
rule_obj.get("replace").and_then(|v| v.as_str()),
rule_obj.get("with").and_then(|v| v.as_str()),
) {
rules.insert(schema_name.clone(), (replace.to_string(), with.to_string()));
// println!("📋 Replacement rule: In {}, replace {} with {}", schema_name, replace, with);
}
}
}
}
}
rules
}
/// Check if a variant should be replaced based on explicit replacement rules
fn should_replace_variant(
schema_name: &str,
extension_refs: &[String],
replacements: &std::collections::HashMap<String, (String, String)>,
) -> bool {
// Check all replacement rules
for (replace_schema, with_schema) in replacements.values() {
if schema_name == replace_schema {
// This schema should be replaced - check if the replacement schema is in extensions
let replacement_exists = extension_refs.iter().any(|ext_ref| {
let ext_schema_name = ext_ref.split('/').next_back().unwrap_or("");
ext_schema_name == with_schema
});
if replacement_exists {
return true;
}
}
}
// Fallback to exact name match for complete replacement
extension_refs.iter().any(|ext_ref| {
let ext_schema_name = ext_ref.split('/').next_back().unwrap_or("");
schema_name == ext_schema_name
})
}
/// Recursively merge two JSON values with replacement rules
/// Objects are merged by combining properties
/// Arrays are merged by concatenating
/// Primitives in the extension override the main value
fn merge_json_objects_with_rules(
main: Value,
extension: Value,
replacements: &std::collections::HashMap<String, (String, String)>,
) -> Value {
match (main, extension) {
// Both objects - merge properties
(Value::Object(mut main_obj), Value::Object(ext_obj)) => {
// Special handling for schema objects with oneOf/anyOf variants.
// Detect which keyword the MAIN spec uses so we preserve it after merging.
let main_union_keyword = if main_obj.contains_key("oneOf") {
Some("oneOf")
} else if main_obj.contains_key("anyOf") {
Some("anyOf")
} else {
None
};
if let (Some(main_variants), Some(ext_variants)) = (
extract_schema_variants(&Value::Object(main_obj.clone())),
extract_schema_variants(&Value::Object(ext_obj.clone())),
) {
let union_key = main_union_keyword.unwrap_or("oneOf");
println!(
"🔍 Merging union schemas ({union_key}): {} main variants, {} extension variants",
main_variants.len(),
ext_variants.len()
);
// Merge the variant arrays, preserving the original union keyword
// First, collect main variants, but filter out any that will be replaced by extension
let mut merged_variants = Vec::new();
let extension_refs: Vec<String> = ext_variants
.iter()
.filter_map(|v| v.get("$ref").and_then(|r| r.as_str()))
.map(|s| s.to_string())
.collect();
// Add main variants that aren't being replaced
for main_variant in main_variants {
if let Some(main_ref) = main_variant.get("$ref").and_then(|r| r.as_str()) {
// Check if this main variant should be replaced by an extension variant
let schema_name = main_ref.split('/').next_back().unwrap_or("");
let should_replace =
should_replace_variant(schema_name, &extension_refs, replacements);
if should_replace {
println!("🔄 REPLACING {} (explicit rule)", schema_name);
}
if !should_replace {
merged_variants.push(main_variant);
}
} else {
// Keep non-ref variants
merged_variants.push(main_variant);
}
}
// Add all extension variants
for ext_variant in ext_variants {
merged_variants.push(ext_variant);
}
// Remove old oneOf/anyOf keys and add merged variants under the original keyword
main_obj.remove("oneOf");
main_obj.remove("anyOf");
main_obj.insert(union_key.to_string(), Value::Array(merged_variants));
// Merge other properties normally
for (key, ext_value) in ext_obj {
if key != "oneOf" && key != "anyOf" {
match main_obj.get(&key) {
Some(main_value) => {
let merged_value = merge_json_objects_with_rules(
main_value.clone(),
ext_value,
replacements,
);
main_obj.insert(key, merged_value);
}
None => {
main_obj.insert(key, ext_value);
}
}
}
}
return Value::Object(main_obj);
}
// Normal object merging
for (key, ext_value) in ext_obj {
match main_obj.get(&key) {
Some(main_value) => {
// Key exists in both - recursively merge
let merged_value = merge_json_objects_with_rules(
main_value.clone(),
ext_value,
replacements,
);
main_obj.insert(key, merged_value);
}
None => {
// Key only in extension - add it
main_obj.insert(key, ext_value);
}
}
}
Value::Object(main_obj)
}
// Both arrays - concatenate
(Value::Array(mut main_arr), Value::Array(ext_arr)) => {
main_arr.extend(ext_arr);
Value::Array(main_arr)
}
// Extension overrides main for all other cases
(_, extension) => extension,
}
}
/// Extract schema variants from oneOf or anyOf properties
fn extract_schema_variants(obj: &Value) -> Option<Vec<Value>> {
if let Value::Object(map) = obj {
if let Some(Value::Array(variants)) = map.get("oneOf") {
return Some(variants.clone());
}
if let Some(Value::Array(variants)) = map.get("anyOf") {
return Some(variants.clone());
}
}
None
}
pub struct SchemaAnalyzer {
schemas: BTreeMap<String, Schema>,
resolved_cache: BTreeMap<String, AnalyzedSchema>,
openapi_spec: Value,
current_schema_name: Option<String>,
component_parameters: BTreeMap<String, crate::openapi::Parameter>,
}
impl SchemaAnalyzer {
pub fn new(openapi_spec: Value) -> Result<Self> {
let spec: OpenApiSpec =
serde_json::from_value(openapi_spec.clone()).map_err(GeneratorError::ParseError)?;
let schemas = Self::extract_schemas(&spec)?;
let component_parameters = spec
.components
.as_ref()
.and_then(|c| c.parameters.as_ref())
.cloned()
.unwrap_or_default();
Ok(Self {
schemas,
resolved_cache: BTreeMap::new(),
openapi_spec,
current_schema_name: None,
component_parameters,
})
}
/// Create a new analyzer with schema extensions merged in
pub fn new_with_extensions(
openapi_spec: Value,
extension_paths: &[std::path::PathBuf],
) -> Result<Self> {
let merged_spec = merge_schema_extensions(openapi_spec, extension_paths)?;
Self::new(merged_spec)
}
/// Generate a context-aware name for inline types, arrays, and variants
/// This provides better naming than generic names like UnionArray1, InlineVariant2, etc.
fn generate_context_aware_name(
&self,
base_context: &str,
type_hint: &str,
index: usize,
schema: Option<&Schema>,
) -> String {
// First, try to infer a better name from the schema structure
if let Some(schema) = schema {
// For arrays, check if we can derive name from items
if type_hint == "Array"
&& matches!(schema.schema_type(), Some(OpenApiSchemaType::Array))
{
if let Some(items_schema) = &schema.details().items {
// Check for specific item types
if let Some(item_type) = items_schema.schema_type() {
match item_type {
OpenApiSchemaType::Object => {
return format!("{base_context}ItemArray");
}
OpenApiSchemaType::String => {
return format!("{base_context}StringArray");
}
_ => {}
}
}
}
}
}
// Generate context-aware name based on type hint
match type_hint {
"Array" => {
// For arrays, always use context name instead of generic numbering
format!("{base_context}Array")
}
"Variant" | "InlineVariant" => {
// For variants, include index only if > 0 to keep first variant clean
if index == 0 {
format!("{base_context}{type_hint}")
} else {
format!("{}{}{}", base_context, type_hint, index + 1)
}
}
_ => {
// Default case
format!("{base_context}{type_hint}{index}")
}
}
}
/// Convert a string to PascalCase, handling underscores and hyphens
fn to_pascal_case(&self, s: &str) -> String {
s.split(['_', '-'])
.filter(|part| !part.is_empty())
.map(|part| {
let mut chars = part.chars();
match chars.next() {
None => String::new(),
Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
}
})
.collect()
}
fn extract_schemas(spec: &OpenApiSpec) -> Result<BTreeMap<String, Schema>> {
let schemas = spec
.components
.as_ref()
.and_then(|c| c.schemas.as_ref())
.ok_or_else(|| {
GeneratorError::InvalidSchema("No schemas found in OpenAPI spec".to_string())
})?;
// Convert BTreeMap to BTreeMap for deterministic iteration order
Ok(schemas
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect())
}
pub fn analyze(&mut self) -> Result<SchemaAnalysis> {
let mut analysis = SchemaAnalysis {
schemas: BTreeMap::new(),
dependencies: DependencyGraph::new(),
patterns: DetectedPatterns {
tagged_enum_schemas: HashSet::new(),
untagged_enum_schemas: HashSet::new(),
type_mappings: BTreeMap::new(),
},
operations: BTreeMap::new(),
};
// First pass: detect patterns
self.detect_patterns(&mut analysis.patterns)?;
// Second pass: analyze each schema
let schema_names: Vec<String> = self.schemas.keys().cloned().collect();
for schema_name in schema_names {
let analyzed = self.analyze_schema(&schema_name)?;
// Build dependency graph
for dep in &analyzed.dependencies {
analysis
.dependencies
.add_dependency(schema_name.clone(), dep.clone());
}
analysis.schemas.insert(schema_name, analyzed);
}
// Third pass: include any inline schemas that were generated during analysis
// BTreeMap maintains sorted order, so iteration is deterministic
for (inline_name, inline_schema) in &self.resolved_cache {
if !analysis.schemas.contains_key(inline_name) {
// Add the inline schema first
analysis
.schemas
.insert(inline_name.clone(), inline_schema.clone());
// Build dependency graph for inline schema's own dependencies
for dep in &inline_schema.dependencies {
analysis
.dependencies
.add_dependency(inline_name.clone(), dep.clone());
}
// Check if any existing schemas depend on this inline schema
// We need to check ALL schemas, not just the ones already in analysis.schemas,
// because parent schemas might have been analyzed but their dependencies
// on inline schemas might not have been added to the dependency graph yet
let mut schemas_to_update = Vec::new();
for (schema_name, schema) in &analysis.schemas {
// Skip self-reference
if schema_name == inline_name {
continue;
}
if schema.dependencies.contains(inline_name) {
// The parent schema depends on this inline schema
schemas_to_update.push(schema_name.clone());
}
}
// Add the dependencies to the graph
for schema_name in schemas_to_update {
analysis
.dependencies
.add_dependency(schema_name, inline_name.clone());
}
}
}
// Fourth pass: analyze OpenAPI operations
self.analyze_operations(&mut analysis)?;
// Fifth pass: include any inline schemas generated during operation analysis
// (e.g., inline response types)
for (inline_name, inline_schema) in &self.resolved_cache {
if !analysis.schemas.contains_key(inline_name) {
analysis
.schemas
.insert(inline_name.clone(), inline_schema.clone());
// Build dependency graph for inline schema's dependencies
for dep in &inline_schema.dependencies {
analysis
.dependencies
.add_dependency(inline_name.clone(), dep.clone());
}
}
}
Ok(analysis)
}
fn detect_patterns(&self, patterns: &mut DetectedPatterns) -> Result<()> {
for (schema_name, schema) in &self.schemas {
// Detect discriminated unions
if self.is_discriminated_union(schema) {
patterns.tagged_enum_schemas.insert(schema_name.clone());
// Extract type mappings for this union
if let Some(mappings) = self.extract_type_mappings(schema)? {
patterns.type_mappings.insert(schema_name.clone(), mappings);
}
}
// Detect simple unions
else if self.is_simple_union(schema) {
patterns.untagged_enum_schemas.insert(schema_name.clone());
}
}
Ok(())
}
fn is_discriminated_union(&self, schema: &Schema) -> bool {
// Check for explicit discriminator
if schema.is_discriminated_union() {
return true;
}
// Auto-detect from union patterns with any common const field
if let Some(variants) = schema.union_variants() {
return variants.len() > 2 && self.detect_discriminator_field(variants).is_some();
}
false
}
fn all_variants_have_const_field(&self, variants: &[Schema], field_name: &str) -> bool {
variants.iter().all(|variant| {
if let Some(ref_str) = variant.reference() {
// $ref variant: resolve and check the referenced schema
if let Some(schema_name) = self.extract_schema_name(ref_str) {
if let Some(schema) = self.schemas.get(schema_name) {
return self.has_const_discriminator_field(schema, field_name);
}
}
} else {
// Inline variant: check properties directly
return self.has_const_discriminator_field(variant, field_name);
}
false
})
}
/// Scan all variants to find any common property that has a const/single-enum value
/// across all variants. Returns the field name if found.
/// Prioritizes "type" if it matches (most common convention).
fn detect_discriminator_field(&self, variants: &[Schema]) -> Option<String> {
if variants.is_empty() {
return None;
}
// Collect candidate field names from the first variant
let first_variant = &variants[0];
let first_schema = if let Some(ref_str) = first_variant.reference() {
let schema_name = self.extract_schema_name(ref_str)?;
self.schemas.get(schema_name)?
} else {
first_variant
};
let properties = first_schema.details().properties.as_ref()?;
let mut candidates: Vec<String> = Vec::new();
for (field_name, field_schema) in properties {
let details = field_schema.details();
let is_const = details.const_value.is_some()
|| details.enum_values.as_ref().is_some_and(|v| v.len() == 1)
|| details.extra.contains_key("const");
if is_const {
candidates.push(field_name.clone());
}
}
if candidates.is_empty() {
return None;
}
// Prioritize "type" if it's among candidates
candidates.sort_by(|a, b| {
if a == "type" {
std::cmp::Ordering::Less
} else if b == "type" {
std::cmp::Ordering::Greater
} else {
a.cmp(b)
}
});
// Check each candidate against all variants
for candidate in &candidates {
if self.all_variants_have_const_field(variants, candidate) {
return Some(candidate.clone());
}
}
None
}
fn has_const_discriminator_field(&self, schema: &Schema, field_name: &str) -> bool {
if let Some(properties) = &schema.details().properties {
if let Some(field) = properties.get(field_name) {
// Check for const value (OpenAPI 3.1 style)
if field.details().const_value.is_some() {
return true;
}
// Check if it's an enum field with a single value
if let Some(enum_vals) = &field.details().enum_values {
return enum_vals.len() == 1;
}
// Fallback: check extra fields for const
return field.details().extra.contains_key("const");
}
}
false
}
fn is_simple_union(&self, schema: &Schema) -> bool {
if let Some(variants) = schema.union_variants() {
// Simple union: multiple types but not nullable pattern
if variants.len() > 1 && !schema.is_nullable_pattern() {
let has_refs = variants.iter().any(|v| v.is_reference());
return has_refs;
}
}
false
}
fn extract_type_mappings(&self, schema: &Schema) -> Result<Option<BTreeMap<String, String>>> {
let variants = schema.union_variants().ok_or_else(|| {
GeneratorError::InvalidSchema("No variants found for discriminated union".to_string())
})?;
// Get the discriminator field name from the schema
let discriminator_field = if let Some(discriminator) = schema.discriminator() {
discriminator.property_name.clone()
} else if let Some(detected) = self.detect_discriminator_field(variants) {
detected
} else {
"type".to_string() // fallback to "type" for auto-detected discriminated unions
};
let mut mappings = BTreeMap::new();
for variant in variants {
if let Some(ref_str) = variant.reference() {
if let Some(type_name) = self.extract_schema_name(ref_str) {
if let Some(variant_schema) = self.schemas.get(type_name) {
if let Some(discriminator_value) = self
.extract_discriminator_value_for_field(
variant_schema,
&discriminator_field,
)
{
mappings.insert(type_name.to_string(), discriminator_value);
}
}
}
}
}
if mappings.is_empty() {
Ok(None)
} else {
Ok(Some(mappings))
}
}
#[allow(dead_code)]
fn extract_discriminator_value(&self, schema: &Schema) -> Option<String> {
self.extract_discriminator_value_for_field(schema, "type")
}
fn extract_discriminator_value_for_field(
&self,
schema: &Schema,
field_name: &str,
) -> Option<String> {
if let Some(properties) = &schema.details().properties {
if let Some(type_field) = properties.get(field_name) {
// Check for const value first (highest priority)
if let Some(const_value) = &type_field.details().const_value {
if let Some(value) = const_value.as_str() {
return Some(value.to_string());
}
}
// Check for enum with single value
if let Some(enum_values) = &type_field.details().enum_values {
if enum_values.len() == 1 {
return enum_values[0].as_str().map(|s| s.to_string());
}
}
// Check for const value in extra fields
if let Some(const_value) = type_field.details().extra.get("const") {
return const_value.as_str().map(|s| s.to_string());
}
// Check for x-stainless-const with default value
if let Some(stainless_const) = type_field.details().extra.get("x-stainless-const") {
if stainless_const.as_bool() == Some(true) {
if let Some(default_value) = &type_field.details().default {
if let Some(value) = default_value.as_str() {
return Some(value.to_string());
}
}
}
}
}
}
None
}
fn get_any_reference<'a>(&self, schema: &'a Schema) -> Option<&'a str> {
schema.reference().or_else(|| schema.recursive_reference())
}
fn extract_schema_name<'a>(&self, ref_str: &'a str) -> Option<&'a str> {
if ref_str == "#" {
return None; // Special case for self-reference
}
let parts: Vec<&str> = ref_str.split('/').collect();
// Standard pattern: #/components/schemas/{SchemaName}[/deeper/path]
// parts[0]="#", parts[1]="components", parts[2]="schemas", parts[3]="SchemaName"
if parts.len() >= 4 && parts[0] == "#" && parts[2] == "schemas" {
return Some(parts[3]);
}
// Fallback for other ref patterns: use last segment,
// but only if it looks like a schema name (not a bare number)
let last = parts.last()?;
if last.is_empty() || last.chars().all(|c| c.is_ascii_digit()) {
None
} else {
Some(last)
}
}
fn analyze_schema(&mut self, schema_name: &str) -> Result<AnalyzedSchema> {
// Check cache first
if let Some(cached) = self.resolved_cache.get(schema_name) {
return Ok(cached.clone());
}
// Set current schema name for context
self.current_schema_name = Some(schema_name.to_string());
let schema = self
.schemas
.get(schema_name)
.ok_or_else(|| GeneratorError::UnresolvedReference(schema_name.to_string()))?
.clone();
// Prevent infinite recursion with placeholder
self.resolved_cache.insert(
schema_name.to_string(),
AnalyzedSchema {
name: schema_name.to_string(),
original: serde_json::to_value(&schema).unwrap_or(Value::Null),
schema_type: SchemaType::Reference {
target: "placeholder".to_string(),
},
dependencies: HashSet::new(),
nullable: false,
description: None,
default: None,
},
);
let analyzed = self.analyze_schema_value(&schema, schema_name)?;
// Update cache with real result
self.resolved_cache
.insert(schema_name.to_string(), analyzed.clone());
Ok(analyzed)
}
fn analyze_schema_value(
&mut self,
schema: &Schema,
schema_name: &str,
) -> Result<AnalyzedSchema> {
let details = schema.details();
let description = details.description.clone();
let nullable = details.is_nullable();
let mut dependencies = HashSet::new();
let schema_type = match schema {
Schema::Reference { reference, .. } => {
let target = self
.extract_schema_name(reference)
.ok_or_else(|| GeneratorError::UnresolvedReference(reference.to_string()))?
.to_string();
dependencies.insert(target.clone());
SchemaType::Reference { target }
}
Schema::RecursiveRef { recursive_ref, .. } => {
// Handle recursive references
if recursive_ref == "#" {
// Self-reference to the current schema
dependencies.insert(schema_name.to_string());
SchemaType::Reference {
target: schema_name.to_string(),
}
} else {
// Handle other recursive reference patterns
let target = self
.extract_schema_name(recursive_ref)
.unwrap_or(schema_name)
.to_string();
dependencies.insert(target.clone());
SchemaType::Reference { target }
}
}
Schema::Typed { schema_type, .. } => {
match schema_type {
OpenApiSchemaType::String => {
if let Some(values) = details.string_enum_values() {
SchemaType::StringEnum { values }
} else {
SchemaType::Primitive {
rust_type: "String".to_string(),
}
}
}
OpenApiSchemaType::Integer => {
let rust_type =
self.get_number_rust_type(OpenApiSchemaType::Integer, details);
SchemaType::Primitive { rust_type }
}
OpenApiSchemaType::Number => {
let rust_type =
self.get_number_rust_type(OpenApiSchemaType::Number, details);
SchemaType::Primitive { rust_type }
}
OpenApiSchemaType::Boolean => SchemaType::Primitive {
rust_type: "bool".to_string(),
},
OpenApiSchemaType::Array => {
// Analyze array item type
self.analyze_array_schema(schema, schema_name, &mut dependencies)?
}
OpenApiSchemaType::Object => {
// Check if this is a dynamic JSON object
if self.should_use_dynamic_json(schema) {
SchemaType::Primitive {
rust_type: "serde_json::Value".to_string(),
}
} else {
// Analyze object properties
self.analyze_object_schema(schema, &mut dependencies)?
}
}
_ => SchemaType::Primitive {
rust_type: "serde_json::Value".to_string(),
},
}
}
Schema::AnyOf {
any_of,
discriminator,
..
} => {
// Handle anyOf patterns (nullable vs flexible union vs discriminated)
self.analyze_anyof_union(
any_of,
discriminator.as_ref(),
&mut dependencies,
schema_name,
)?
}
Schema::OneOf {
one_of,
discriminator,
..
} => {
// Handle oneOf discriminated unions
self.analyze_oneof_union(
one_of,
discriminator.as_ref(),
schema_name,
&mut dependencies,
)?
}
Schema::AllOf { all_of, .. } => {
// Handle allOf composition (schema inheritance)
self.analyze_allof_composition(all_of, &mut dependencies)?
}
Schema::Untyped { .. } => {
// Try to infer type from structure
if let Some(inferred) = schema.inferred_type() {
match inferred {
OpenApiSchemaType::Object => {
if self.should_use_dynamic_json(schema) {
SchemaType::Primitive {
rust_type: "serde_json::Value".to_string(),
}
} else {
self.analyze_object_schema(schema, &mut dependencies)?
}
}
OpenApiSchemaType::String if details.is_string_enum() => {
SchemaType::StringEnum {
values: details.string_enum_values().unwrap_or_default(),
}
}
_ => SchemaType::Primitive {
rust_type: "serde_json::Value".to_string(),
},
}
} else {
SchemaType::Primitive {
rust_type: "serde_json::Value".to_string(),
}
}
}
};
Ok(AnalyzedSchema {
name: schema_name.to_string(),
original: serde_json::to_value(schema).unwrap_or(Value::Null), // Convert back to Value for now
schema_type,
dependencies,
nullable,
description,
default: details.default.clone(),
})
}
fn analyze_object_schema(
&mut self,
schema: &Schema,
dependencies: &mut HashSet<String>,
) -> Result<SchemaType> {
let details = schema.details();
let properties = &details.properties;
let required = details
.required
.as_ref()
.map(|req| req.iter().cloned().collect::<HashSet<String>>())
.unwrap_or_default();
let mut property_info = BTreeMap::new();
if let Some(props) = properties {
for (prop_name, prop_schema) in props {
// Check if this property is a union that needs a named type
let prop_type = if let Schema::AnyOf { any_of, .. } = prop_schema {
// First check if this should be a dynamic JSON pattern
if self.should_use_dynamic_json(prop_schema) {
// This is a dynamic JSON pattern, use serde_json::Value directly
SchemaType::Primitive {
rust_type: "serde_json::Value".to_string(),
}
} else {
// This is an anyOf union in a property - create a named union type
// Use the current schema name as context to make the union name unique
let context_name = self
.current_schema_name
.clone()
.unwrap_or_else(|| "Unknown".to_string());
// Generate a name based on both the schema and property name
let prop_pascal = self.to_pascal_case(prop_name);
let union_type_name = format!("{context_name}{prop_pascal}");
// Analyze the union
let union_schema_type = self.analyze_anyof_union(
any_of,
prop_schema.discriminator(),
dependencies,
&union_type_name,
)?;
// Store the union as a named schema
self.resolved_cache.insert(
union_type_name.clone(),
AnalyzedSchema {
name: union_type_name.clone(),
original: serde_json::to_value(prop_schema).unwrap_or(Value::Null),
schema_type: union_schema_type,
dependencies: HashSet::new(),
nullable: false,
description: prop_schema.details().description.clone(),
default: None,
},
);
// Return a reference to the named union type
dependencies.insert(union_type_name.clone());
SchemaType::Reference {
target: union_type_name,
}
}
} else if let Schema::OneOf {
one_of,
discriminator,
..
} = prop_schema
{
// Handle oneOf discriminated unions in properties
// Generate a name based on the property name
let context_name = self
.current_schema_name
.clone()
.unwrap_or_else(|| "Unknown".to_string());
let prop_pascal = self.to_pascal_case(prop_name);
let union_type_name = format!("{context_name}{prop_pascal}");
// Analyze the discriminated union
let union_schema_type = self.analyze_oneof_union(
one_of,
discriminator.as_ref(),
&union_type_name,
dependencies,
)?;
// Store the union as a named schema
self.resolved_cache.insert(
union_type_name.clone(),
AnalyzedSchema {
name: union_type_name.clone(),
original: serde_json::to_value(prop_schema).unwrap_or(Value::Null),
schema_type: union_schema_type,
dependencies: HashSet::new(),
nullable: false,
description: prop_schema.details().description.clone(),
default: None,
},
);
// Return a reference to the named union type
dependencies.insert(union_type_name.clone());
SchemaType::Reference {
target: union_type_name,
}
} else {
// Regular property schema analysis - pass property name for context
self.analyze_property_schema_with_context(
prop_schema,
Some(prop_name),
dependencies,
)?
};
let prop_details = prop_schema.details();
// Check for both explicit nullable and anyOf nullable patterns
let prop_nullable = prop_details.is_nullable() || prop_schema.is_nullable_pattern();
let prop_description = prop_details.description.clone();
let prop_default = prop_details.default.clone();
property_info.insert(
prop_name.clone(),
PropertyInfo {
schema_type: prop_type,
nullable: prop_nullable,
description: prop_description,
default: prop_default,
serde_attrs: Vec::new(),
},
);
}
}
// Check additionalProperties setting
let additional_properties = match &details.additional_properties {
Some(crate::openapi::AdditionalProperties::Boolean(true)) => true,
Some(crate::openapi::AdditionalProperties::Boolean(false)) => false,
Some(crate::openapi::AdditionalProperties::Schema(_)) => {
// For now, treat schema-based additionalProperties as true
// TODO: Could analyze the schema to determine the value type
true
}
None => false, // Default is false if not specified
};
Ok(SchemaType::Object {
properties: property_info,
required,
additional_properties,
})
}
fn analyze_property_schema_with_context(
&mut self,
schema: &Schema,
property_name: Option<&str>,
dependencies: &mut HashSet<String>,
) -> Result<SchemaType> {
if let Some(ref_str) = self.get_any_reference(schema) {
let target = if ref_str == "#" {
// $recursiveRef: "#" - need to find the schema with $recursiveAnchor: true
self.find_recursive_anchor_schema()
.unwrap_or_else(|| "UnknownRecursive".to_string())
} else {
self.extract_schema_name(ref_str)
.ok_or_else(|| GeneratorError::UnresolvedReference(ref_str.to_string()))?
.to_string()
};
dependencies.insert(target.clone());
return Ok(SchemaType::Reference { target });
}
if let Some(schema_type) = schema.schema_type() {
match schema_type {
OpenApiSchemaType::String => {
// Check if this string type has enum values
if let Some(enum_values) = schema.details().string_enum_values() {
// This is an inline enum in a property - create a named enum type
// Use the current schema name as context to make the enum name unique
let context_name = self
.current_schema_name
.clone()
.unwrap_or_else(|| "Unknown".to_string());
// Generate a candidate name based on both the schema and property context.
let primary_name = if let Some(prop_name) = property_name {
// We have property name context - use it for a unique name
let prop_pascal = self.to_pascal_case(prop_name);
format!("{context_name}{prop_pascal}")
} else {
// No property name context - generate a unique name using enum values
// Use the first enum value to help make the name unique
let suffix = if !enum_values.is_empty() {
let first_value = self.to_pascal_case(&enum_values[0]);
format!("{first_value}Enum")
} else {
"StringEnum".to_string()
};
format!("{context_name}{suffix}")
};
// Resolve a name that either matches an existing same-valued
// enum (dedup) or doesn't collide with a different one.
//
// Two distinct inline enums can land on the same primary
// candidate when a parent schema has a property like
// `type` that recurs at multiple nesting levels — e.g.
// Latitude.sh's `plan_data.type = ["plans"]` (the
// JSON-API resource type) and
// `plan_data.attributes.specs.drives[].type =
// ["SSD","HDD","NVME"]` both want to become
// `PlanDataType`. We must NOT silently overwrite the
// first registration: that breaks deserialization
// because both fields end up referencing whichever
// enum was processed last.
//
// Disambiguation strategy: append the PascalCase first
// enum value (`PlanDataTypeNVME` vs `PlanDataTypePlans`)
// and, if that's also claimed with different values,
// fall back to a numeric `_2`, `_3`, … suffix.
fn matches_values(existing: &AnalyzedSchema, values: &[String]) -> bool {
matches!(
&existing.schema_type,
SchemaType::StringEnum { values: existing_values }
if existing_values == values
)
}
let mut enum_type_name = primary_name.clone();
let mut should_insert = match self.resolved_cache.get(&enum_type_name) {
None => true,
Some(existing) if matches_values(existing, &enum_values) => false,
Some(_) => {
// Collision with different values — try a
// value-suffixed name first.
let suffix = enum_values
.first()
.map(|v| self.to_pascal_case(v))
.unwrap_or_else(|| "Variant".to_string());
let candidate = format!("{primary_name}{suffix}");
let resolved = match self.resolved_cache.get(&candidate) {
None => Some((candidate.clone(), true)),
Some(existing) if matches_values(existing, &enum_values) => {
Some((candidate.clone(), false))
}
Some(_) => {
// Walk a numeric suffix until we find
// a slot that's free or matches.
let mut found = None;
for n in 2..1000 {
let numbered = format!("{candidate}_{n}");
match self.resolved_cache.get(&numbered) {
None => {
found = Some((numbered, true));
break;
}
Some(existing)
if matches_values(existing, &enum_values) =>
{
found = Some((numbered, false));
break;
}
Some(_) => continue,
}
}
found
}
};
let (resolved_name, insert) = resolved.unwrap_or((candidate, true));
enum_type_name = resolved_name;
insert
}
};
// Store the enum as a named schema if this is the
// first time we've seen this exact (name, values) pair.
if should_insert {
self.resolved_cache.insert(
enum_type_name.clone(),
AnalyzedSchema {
name: enum_type_name.clone(),
original: serde_json::to_value(schema).unwrap_or(Value::Null),
schema_type: SchemaType::StringEnum {
values: enum_values,
},
dependencies: HashSet::new(),
nullable: false,
description: schema.details().description.clone(),
default: schema.details().default.clone(),
},
);
// Silence unused-write warnings when the value
// is not consulted again on this path.
let _ = &mut should_insert;
}
// Return a reference to the named enum type
dependencies.insert(enum_type_name.clone());
return Ok(SchemaType::Reference {
target: enum_type_name,
});
} else {
return Ok(SchemaType::Primitive {
rust_type: "String".to_string(),
});
}
}
OpenApiSchemaType::Integer | OpenApiSchemaType::Number => {
let details = schema.details();
let rust_type = self.get_number_rust_type(schema_type.clone(), details);
return Ok(SchemaType::Primitive { rust_type });
}
OpenApiSchemaType::Boolean => {
return Ok(SchemaType::Primitive {
rust_type: "bool".to_string(),
});
}
OpenApiSchemaType::Array => {
// Analyze array property with context
let context_name = if let Some(prop_name) = property_name {
// Use property name for context
let prop_pascal = self.to_pascal_case(prop_name);
format!(
"{}{}",
self.current_schema_name.as_deref().unwrap_or("Unknown"),
prop_pascal
)
} else {
// Fallback to generic name
"ArrayItem".to_string()
};
return self.analyze_array_schema(schema, &context_name, dependencies);
}
OpenApiSchemaType::Object => {
// Check if this is a dynamic JSON object
if self.should_use_dynamic_json(schema) {
return Ok(SchemaType::Primitive {
rust_type: "serde_json::Value".to_string(),
});
}
// Inline object in property - create a named schema for it
let object_type_name = if let Some(prop_name) = property_name {
// Use property name for context
let prop_pascal = self.to_pascal_case(prop_name);
format!(
"{}{}",
self.current_schema_name.as_deref().unwrap_or("Unknown"),
prop_pascal
)
} else {
// Fallback to generic name
format!(
"{}Object",
self.current_schema_name.as_deref().unwrap_or("Unknown")
)
};
// Analyze the object schema
let object_type = self.analyze_object_schema(schema, dependencies)?;
// Create an analyzed schema for the inline object
let inline_schema = AnalyzedSchema {
name: object_type_name.clone(),
original: serde_json::to_value(schema).unwrap_or(Value::Null),
schema_type: object_type,
dependencies: dependencies.clone(),
nullable: false,
description: schema.details().description.clone(),
default: None,
};
// Add the inline object as a named schema
self.resolved_cache
.insert(object_type_name.clone(), inline_schema);
dependencies.insert(object_type_name.clone());
// Return a reference to the named schema
return Ok(SchemaType::Reference {
target: object_type_name,
});
}
_ => {
return Ok(SchemaType::Primitive {
rust_type: "serde_json::Value".to_string(),
});
}
}
}
// Handle nullable patterns
if schema.is_nullable_pattern() {
if let Some(non_null) = schema.non_null_variant() {
return self.analyze_property_schema_with_context(
non_null,
property_name,
dependencies,
);
}
}
// Check if this should be dynamic JSON before further analysis
if self.should_use_dynamic_json(schema) {
return Ok(SchemaType::Primitive {
rust_type: "serde_json::Value".to_string(),
});
}
// Handle allOf composition patterns
if let Schema::AllOf { all_of, .. } = schema {
return self.analyze_allof_composition(all_of, dependencies);
}
// Handle union patterns (anyOf/oneOf) that weren't caught earlier
if let Some(variants) = schema.union_variants() {
match variants.len().cmp(&1) {
std::cmp::Ordering::Equal => {
// Single variant - analyze it directly
return self.analyze_property_schema_with_context(
&variants[0],
property_name,
dependencies,
);
}
std::cmp::Ordering::Greater => {
// Multiple variants - try to analyze as a union
// Generate a context-aware name for the union type
let union_name = if let Some(prop_name) = property_name {
// We have property context - create a proper union name
let prop_pascal = self.to_pascal_case(prop_name);
format!(
"{}{}",
self.current_schema_name.as_deref().unwrap_or(""),
prop_pascal
)
} else {
"UnionType".to_string()
};
// Check if this is a oneOf or anyOf
if let Schema::OneOf {
one_of,
discriminator,
..
} = schema
{
// This is a oneOf - analyze it properly with potential discriminator
let oneof_result = self.analyze_oneof_union(
one_of,
discriminator.as_ref(),
&union_name,
dependencies,
)?;
// If we got a union type (not discriminated), we need to store it as a named type
if let SchemaType::Union {
variants: _union_variants,
} = &oneof_result
{
// Store the union as a named type in resolved_cache
self.resolved_cache.insert(
union_name.clone(),
AnalyzedSchema {
name: union_name.clone(),
original: serde_json::to_value(schema).unwrap_or(Value::Null),
schema_type: oneof_result.clone(),
dependencies: dependencies.clone(),
nullable: false,
description: schema.details().description.clone(),
default: None,
},
);
// Return a reference to the named union type
dependencies.insert(union_name.clone());
return Ok(SchemaType::Reference { target: union_name });
}
return Ok(oneof_result);
} else if let Schema::AnyOf {
any_of,
discriminator,
..
} = schema
{
// This is anyOf - use existing logic with discriminator support
let union_analysis = self.analyze_anyof_union(
any_of,
discriminator.as_ref(),
dependencies,
&union_name,
)?;
return Ok(union_analysis);
} else {
// This shouldn't happen, but handle gracefully
// Create a simple union from variants
let mut union_variants = Vec::new();
for variant in variants {
if let Some(ref_str) = variant.reference() {
if let Some(target) = self.extract_schema_name(ref_str) {
dependencies.insert(target.to_string());
union_variants.push(SchemaRef {
target: target.to_string(),
nullable: false,
});
}
}
}
return Ok(SchemaType::Union {
variants: union_variants,
});
}
}
std::cmp::Ordering::Less => {}
}
}
// Handle untyped schemas by trying to infer from structure
if let Some(inferred_type) = schema.inferred_type() {
match inferred_type {
OpenApiSchemaType::Object => {
// Double-check for dynamic JSON pattern even for inferred objects
if self.should_use_dynamic_json(schema) {
return Ok(SchemaType::Primitive {
rust_type: "serde_json::Value".to_string(),
});
}
return self.analyze_object_schema(schema, dependencies);
}
OpenApiSchemaType::Array => {
let context_name = if let Some(prop_name) = property_name {
// Use property name for context
let prop_pascal = self.to_pascal_case(prop_name);
format!(
"{}{}",
self.current_schema_name.as_deref().unwrap_or("Unknown"),
prop_pascal
)
} else {
// Fallback to generic name
"ArrayItem".to_string()
};
return self.analyze_array_schema(schema, &context_name, dependencies);
}
OpenApiSchemaType::String => {
if let Some(enum_values) = schema.details().string_enum_values() {
return Ok(SchemaType::StringEnum {
values: enum_values,
});
} else {
return Ok(SchemaType::Primitive {
rust_type: "String".to_string(),
});
}
}
_ => {
// Handle other inferred types
let rust_type = self.openapi_type_to_rust_type(inferred_type, schema.details());
return Ok(SchemaType::Primitive { rust_type });
}
}
}
Ok(SchemaType::Primitive {
rust_type: "serde_json::Value".to_string(),
})
}
fn analyze_allof_composition(
&mut self,
all_of_schemas: &[Schema],
dependencies: &mut HashSet<String>,
) -> Result<SchemaType> {
// Special case: if allOf contains only a single reference, treat it as a direct type alias
// This handles patterns like: "allOf": [{"$ref": "#/components/schemas/Usage"}]
if all_of_schemas.len() == 1 {
if let Schema::Reference { reference, .. } = &all_of_schemas[0] {
if let Some(target) = self.extract_schema_name(reference) {
dependencies.insert(target.to_string());
return Ok(SchemaType::Reference {
target: target.to_string(),
});
}
}
}
// AllOf represents schema composition - merge all schemas into one
let mut merged_properties = BTreeMap::new();
let mut merged_required = HashSet::new();
let mut descriptions = Vec::new();
// Save the current schema context to restore it when analyzing properties
let current_context = self.current_schema_name.clone();
for schema in all_of_schemas {
match schema {
Schema::Reference { reference, .. } => {
// Add dependency on referenced schema
if let Some(target) = self.extract_schema_name(reference) {
dependencies.insert(target.to_string());
// First ensure the referenced schema is analyzed
let analyzed_ref = self.analyze_schema(target)?;
// Now merge the analyzed schema's properties
match &analyzed_ref.schema_type {
SchemaType::Object {
properties,
required,
..
} => {
// Merge properties from the analyzed schema
for (prop_name, prop_info) in properties {
merged_properties.insert(prop_name.clone(), prop_info.clone());
}
// Merge required fields
for req in required {
merged_required.insert(req.clone());
}
}
_ => {
// If the referenced schema is not an object, fall back to raw merge
if let Some(ref_schema) = self.schemas.get(target).cloned() {
self.merge_schema_into_properties(
&ref_schema,
&mut merged_properties,
&mut merged_required,
dependencies,
)?;
}
}
}
}
}
Schema::Typed {
schema_type: OpenApiSchemaType::Object,
..
}
| Schema::Untyped { .. } => {
// Restore the original context when analyzing inline properties
let saved_context = self.current_schema_name.clone();
self.current_schema_name = current_context.clone();
// Merge object properties directly
self.merge_schema_into_properties(
schema,
&mut merged_properties,
&mut merged_required,
dependencies,
)?;
// Restore the previous context
self.current_schema_name = saved_context;
}
_ => {
// For non-object typed schemas in allOf, try to merge them as well
// This handles cases like allOf with enum or string constraints
self.merge_schema_into_properties(
schema,
&mut merged_properties,
&mut merged_required,
dependencies,
)?;
}
}
// Collect descriptions
if let Some(desc) = &schema.details().description {
descriptions.push(desc.clone());
}
}
// If we successfully merged properties, return an object
if !merged_properties.is_empty() {
Ok(SchemaType::Object {
properties: merged_properties,
required: merged_required,
additional_properties: false,
})
} else {
// Fall back to composition if we couldn't merge
Ok(SchemaType::Composition {
schemas: all_of_schemas
.iter()
.filter_map(|s| {
if let Some(ref_str) = s.reference() {
if let Some(target) = self.extract_schema_name(ref_str) {
dependencies.insert(target.to_string());
Some(SchemaRef {
target: target.to_string(),
nullable: false,
})
} else {
None
}
} else {
None
}
})
.collect(),
})
}
}
fn merge_schema_into_properties(
&mut self,
schema: &Schema,
merged_properties: &mut BTreeMap<String, PropertyInfo>,
merged_required: &mut HashSet<String>,
dependencies: &mut HashSet<String>,
) -> Result<()> {
let details = schema.details();
// Merge properties
if let Some(properties) = &details.properties {
for (prop_name, prop_schema) in properties {
let prop_type = self.analyze_property_schema_with_context(
prop_schema,
Some(prop_name),
dependencies,
)?;
let prop_details = prop_schema.details();
merged_properties.insert(
prop_name.clone(),
PropertyInfo {
schema_type: prop_type,
nullable: prop_details.is_nullable(),
description: prop_details.description.clone(),
default: prop_details.default.clone(),
serde_attrs: Vec::new(),
},
);
}
}
// Merge required fields
if let Some(required) = &details.required {
for field in required {
merged_required.insert(field.clone());
}
}
Ok(())
}
fn analyze_oneof_union(
&mut self,
one_of_schemas: &[Schema],
discriminator: Option<&crate::openapi::Discriminator>,
parent_name: &str,
dependencies: &mut HashSet<String>,
) -> Result<SchemaType> {
// Pattern: nullable [Type, null] — return the non-null type directly.
// The nullable bit is recorded at the property level via is_nullable_pattern().
if one_of_schemas.len() == 2 {
let null_count = one_of_schemas
.iter()
.filter(|s| matches!(s.schema_type(), Some(OpenApiSchemaType::Null)))
.count();
if null_count == 1 {
if let Some(non_null) = one_of_schemas
.iter()
.find(|s| !matches!(s.schema_type(), Some(OpenApiSchemaType::Null)))
{
return self
.analyze_schema_value(non_null, parent_name)
.map(|a| a.schema_type);
}
}
}
// If there's no discriminator, we should create an untagged union
if discriminator.is_none() {
// Handle untagged unions (oneOf without discriminator)
return self.analyze_untagged_oneof_union(one_of_schemas, parent_name, dependencies);
}
// This is a discriminated union
let discriminator_field = discriminator
.ok_or_else(|| {
GeneratorError::InvalidDiscriminator(
"expected discriminator after guard check".to_string(),
)
})?
.property_name
.clone();
let mut variants = Vec::new();
let mut used_variant_names = std::collections::HashSet::new();
for variant_schema in one_of_schemas {
// Check if this is a direct reference, recursive reference, or an allOf wrapper with a reference
let ref_info = if let Some(ref_str) = variant_schema.reference() {
Some((ref_str, false))
} else if let Some(recursive_ref) = variant_schema.recursive_reference() {
Some((recursive_ref, true))
} else if let Schema::AllOf { all_of, .. } = variant_schema {
// Check if this is an allOf with a single reference
if all_of.len() == 1 {
if let Some(ref_str) = all_of[0].reference() {
Some((ref_str, false))
} else {
all_of[0]
.recursive_reference()
.map(|recursive_ref| (recursive_ref, true))
}
} else {
None
}
} else {
None
};
if let Some((ref_str, is_recursive)) = ref_info {
let schema_name = if is_recursive && ref_str == "#" {
// Handle recursive reference to the schema with recursiveAnchor
self.find_recursive_anchor_schema()
.or_else(|| self.current_schema_name.clone())
.unwrap_or_else(|| "CompoundFilter".to_string())
} else {
self.extract_schema_name(ref_str)
.map(|s| s.to_string())
.unwrap_or_else(|| "UnknownRef".to_string())
};
if !schema_name.is_empty() {
dependencies.insert(schema_name.clone());
// Determine discriminator value with priority order:
// 1. Explicit mapping in discriminator
// 2. Extract from referenced schema
// 3. Generate from schema name
let discriminator_value = if let Some(disc) = discriminator {
if let Some(mappings) = &disc.mapping {
// Find the mapping key that points to this schema reference
// Mapping format is: "discriminator_value" -> "#/components/schemas/SchemaName"
mappings
.iter()
.find(|(_, target_ref)| {
// Check if this mapping target matches our reference
target_ref.as_str() == ref_str
|| self
.extract_schema_name(target_ref)
.map(|s| s.to_string())
== Some(schema_name.clone())
})
.map(|(key, _)| key.clone())
.unwrap_or_else(|| {
self.fallback_discriminator_value_for_field(
&schema_name,
&discriminator_field,
)
})
} else {
self.fallback_discriminator_value_for_field(
&schema_name,
&discriminator_field,
)
}
} else {
self.fallback_discriminator_value_for_field(
&schema_name,
&discriminator_field,
)
};
// Generate Rust-friendly variant name and ensure uniqueness
let base_name = self.to_rust_variant_name(&schema_name);
let rust_name =
self.ensure_unique_variant_name(base_name, &mut used_variant_names);
// Use the discriminator value as-is from the schema
let final_discriminator_value = discriminator_value;
variants.push(UnionVariant {
rust_name,
type_name: schema_name,
discriminator_value: final_discriminator_value,
schema_ref: ref_str.to_string(),
});
}
} else {
// Handle inline schemas in oneOf
let variant_index = variants.len();
let inline_type_name =
self.generate_inline_type_name(variant_schema, variant_index);
// Try to extract discriminator value from inline schema
let discriminator_value = if let Some(disc) = discriminator {
if let Some(mappings) = &disc.mapping {
// Look for mapping that points to this inline variant by index
mappings
.iter()
.find(|(_, target_ref)| {
target_ref.contains(&format!("variant_{variant_index}"))
})
.map(|(key, _)| key.clone())
.unwrap_or_else(|| {
self.extract_inline_discriminator_value(
variant_schema,
&discriminator_field,
variant_index,
)
})
} else {
self.extract_inline_discriminator_value(
variant_schema,
&discriminator_field,
variant_index,
)
}
} else {
self.extract_inline_discriminator_value(
variant_schema,
&discriminator_field,
variant_index,
)
};
// Generate Rust-friendly variant name based on discriminator or fallback to generic
let base_name = if discriminator_value.starts_with("variant_") {
format!("Variant{variant_index}")
} else {
// Convert discriminator value to a meaningful Rust variant name
let clean_name = self.discriminator_to_variant_name(&discriminator_value);
self.to_rust_variant_name(&clean_name)
};
let rust_name = self.ensure_unique_variant_name(base_name, &mut used_variant_names);
// Use the discriminator value as-is from the schema
let final_discriminator_value = discriminator_value;
variants.push(UnionVariant {
rust_name,
type_name: inline_type_name.clone(),
discriminator_value: final_discriminator_value,
schema_ref: format!("inline_{variant_index}"),
});
// Store inline schema for later analysis and generation
self.add_inline_schema(&inline_type_name, variant_schema, dependencies)?;
}
}
if variants.is_empty() {
// If we couldn't create a discriminated union, fall back to an untagged union
// This handles cases where oneOf contains references or inline schemas without proper discriminators
let mut union_variants = Vec::new();
for (variant_index, variant_schema) in one_of_schemas.iter().enumerate() {
// First check if it's a reference or recursive reference
if let Some(ref_str) = variant_schema.reference() {
if let Some(schema_name) = self.extract_schema_name(ref_str) {
dependencies.insert(schema_name.to_string());
union_variants.push(SchemaRef {
target: schema_name.to_string(),
nullable: false,
});
}
} else if let Some(recursive_ref) = variant_schema.recursive_reference() {
let schema_name = if recursive_ref == "#" {
// Handle recursive reference to the schema with recursiveAnchor
self.find_recursive_anchor_schema()
.or_else(|| self.current_schema_name.clone())
.unwrap_or_else(|| "CompoundFilter".to_string())
} else {
self.extract_schema_name(recursive_ref)
.map(|s| s.to_string())
.unwrap_or_else(|| "RecursiveType".to_string())
};
dependencies.insert(schema_name.clone());
union_variants.push(SchemaRef {
target: schema_name,
nullable: false,
});
} else {
// Handle inline schemas by creating type aliases or using primitive types directly
let inline_name = self.generate_context_aware_name(
parent_name,
"InlineVariant",
variant_index,
Some(variant_schema),
);
let analyzed = self.analyze_schema_value(variant_schema, &inline_name)?;
let variant_type = analyzed.schema_type;
// Add dependencies from the analyzed schema
for dep in &analyzed.dependencies {
dependencies.insert(dep.clone());
}
match &variant_type {
// For primitive types, we can use them directly in the union
SchemaType::Primitive { rust_type } => {
union_variants.push(SchemaRef {
target: rust_type.clone(),
nullable: false,
});
}
// For arrays, check if we can determine the item type
SchemaType::Array { item_type } => {
match item_type.as_ref() {
SchemaType::Primitive { rust_type } => {
let type_name = format!("Vec<{rust_type}>");
union_variants.push(SchemaRef {
target: type_name,
nullable: false,
});
}
SchemaType::Reference { target } => {
let type_name = format!("Vec<{target}>");
union_variants.push(SchemaRef {
target: type_name,
nullable: false,
});
}
_ => {
// For other array types, create an inline type
let inline_type_name = self.generate_context_aware_name(
parent_name,
"Variant",
variant_index,
None,
);
self.add_inline_schema(
&inline_type_name,
variant_schema,
dependencies,
)?;
union_variants.push(SchemaRef {
target: inline_type_name,
nullable: false,
});
}
}
}
// For reference types, use the reference target directly
SchemaType::Reference { target } => {
union_variants.push(SchemaRef {
target: target.clone(),
nullable: false,
});
}
// For other complex types, create an inline type
_ => {
let inline_type_name =
format!("{}Variant{}", parent_name, variant_index + 1);
self.add_inline_schema(
&inline_type_name,
variant_schema,
dependencies,
)?;
union_variants.push(SchemaRef {
target: inline_type_name,
nullable: false,
});
}
}
}
}
if !union_variants.is_empty() {
return Ok(SchemaType::Union {
variants: union_variants,
});
}
// Only fall back to serde_json::Value if we truly can't analyze the union
return Ok(SchemaType::Primitive {
rust_type: "serde_json::Value".to_string(),
});
}
Ok(SchemaType::DiscriminatedUnion {
discriminator_field,
variants,
})
}
fn analyze_untagged_oneof_union(
&mut self,
one_of_schemas: &[Schema],
parent_name: &str,
dependencies: &mut HashSet<String>,
) -> Result<SchemaType> {
// Drop {"type": "null"} variants. They mean "may be null" and are surfaced
// as Option<T> at the property level — including them here produces a junk
// `SerdeJsonValue(serde_json::Value)` variant.
let filtered: Vec<&Schema> = one_of_schemas
.iter()
.filter(|s| !matches!(s.schema_type(), Some(OpenApiSchemaType::Null)))
.collect();
// If filtering leaves a single variant, return its analyzed type directly.
if filtered.len() == 1 {
return self
.analyze_schema_value(filtered[0], parent_name)
.map(|a| a.schema_type);
}
let mut union_variants = Vec::new();
for (variant_index, variant_schema) in filtered.iter().copied().enumerate() {
// First check if it's a reference or recursive reference
if let Some(ref_str) = variant_schema.reference() {
if let Some(schema_name) = self.extract_schema_name(ref_str) {
dependencies.insert(schema_name.to_string());
union_variants.push(SchemaRef {
target: schema_name.to_string(),
nullable: false,
});
}
} else if let Some(recursive_ref) = variant_schema.recursive_reference() {
let schema_name = if recursive_ref == "#" {
// Handle recursive reference to the schema with recursiveAnchor
self.find_recursive_anchor_schema()
.or_else(|| self.current_schema_name.clone())
.unwrap_or_else(|| "CompoundFilter".to_string())
} else {
self.extract_schema_name(recursive_ref)
.map(|s| s.to_string())
.unwrap_or_else(|| "RecursiveType".to_string())
};
dependencies.insert(schema_name.clone());
union_variants.push(SchemaRef {
target: schema_name,
nullable: false,
});
} else {
// Handle inline schemas by creating type aliases or using primitive types directly
let inline_name = self.generate_context_aware_name(
parent_name,
"InlineVariant",
variant_index,
Some(variant_schema),
);
let analyzed = self.analyze_schema_value(variant_schema, &inline_name)?;
let variant_type = analyzed.schema_type;
// Add dependencies from the analyzed schema
for dep in &analyzed.dependencies {
dependencies.insert(dep.clone());
}
match &variant_type {
// For primitive types, we can use them directly in the union
SchemaType::Primitive { rust_type } => {
union_variants.push(SchemaRef {
target: rust_type.clone(),
nullable: false,
});
}
// For arrays, check if we can determine the item type
SchemaType::Array { item_type } => {
match item_type.as_ref() {
SchemaType::Primitive { rust_type } => {
let type_name = format!("Vec<{rust_type}>");
union_variants.push(SchemaRef {
target: type_name,
nullable: false,
});
}
SchemaType::Reference { target } => {
let type_name = format!("Vec<{target}>");
union_variants.push(SchemaRef {
target: type_name,
nullable: false,
});
}
// Handle arrays of arrays (e.g., Vec<Vec<i64>>)
SchemaType::Array {
item_type: inner_item_type,
} => {
match inner_item_type.as_ref() {
SchemaType::Primitive { rust_type } => {
let type_name = format!("Vec<Vec<{rust_type}>>");
union_variants.push(SchemaRef {
target: type_name,
nullable: false,
});
}
SchemaType::Reference { target } => {
let type_name = format!("Vec<Vec<{target}>>");
union_variants.push(SchemaRef {
target: type_name,
nullable: false,
});
}
_ => {
// For deeper nesting, create an inline type
let inline_type_name = self.generate_context_aware_name(
parent_name,
"Variant",
variant_index,
None,
);
self.add_inline_schema(
&inline_type_name,
variant_schema,
dependencies,
)?;
union_variants.push(SchemaRef {
target: inline_type_name,
nullable: false,
});
}
}
}
_ => {
// For other array types, create an inline type
let inline_type_name = self.generate_context_aware_name(
parent_name,
"Variant",
variant_index,
None,
);
self.add_inline_schema(
&inline_type_name,
variant_schema,
dependencies,
)?;
union_variants.push(SchemaRef {
target: inline_type_name,
nullable: false,
});
}
}
}
// For reference types, use the reference target directly
SchemaType::Reference { target } => {
union_variants.push(SchemaRef {
target: target.clone(),
nullable: false,
});
}
// For other complex types, create an inline type
_ => {
let inline_type_name = self.generate_context_aware_name(
parent_name,
"Variant",
variant_index,
None,
);
self.add_inline_schema(&inline_type_name, variant_schema, dependencies)?;
union_variants.push(SchemaRef {
target: inline_type_name,
nullable: false,
});
}
}
}
}
if !union_variants.is_empty() {
return Ok(SchemaType::Union {
variants: union_variants,
});
}
// Only fall back to serde_json::Value if we truly can't analyze the union
Ok(SchemaType::Primitive {
rust_type: "serde_json::Value".to_string(),
})
}
fn add_inline_schema(
&mut self,
type_name: &str,
schema: &Schema,
dependencies: &mut HashSet<String>,
) -> Result<()> {
// For primitive types, we need to ensure they are stored as type aliases
if let Some(schema_type) = schema.schema_type() {
match schema_type {
OpenApiSchemaType::String
| OpenApiSchemaType::Integer
| OpenApiSchemaType::Number
| OpenApiSchemaType::Boolean => {
let rust_type =
self.openapi_type_to_rust_type(schema_type.clone(), schema.details());
// Store as a type alias
self.resolved_cache.insert(
type_name.to_string(),
AnalyzedSchema {
name: type_name.to_string(),
original: serde_json::to_value(schema).unwrap_or(Value::Null),
schema_type: SchemaType::Primitive { rust_type },
dependencies: HashSet::new(),
nullable: false,
description: schema.details().description.clone(),
default: None,
},
);
return Ok(());
}
_ => {}
}
}
// For non-primitive types, analyze the inline schema and add it to our collection
// Set current_schema_name so nested inline properties (enums, unions, objects)
// get named with the correct parent context instead of inheriting a stale name
let previous_schema_name = self.current_schema_name.take();
self.current_schema_name = Some(type_name.to_string());
let analyzed = self.analyze_schema_value(schema, type_name)?;
self.current_schema_name = previous_schema_name;
// Add to resolved cache so it can be generated
self.resolved_cache.insert(type_name.to_string(), analyzed);
// Add dependencies
if let Some(cached) = self.resolved_cache.get(type_name) {
for dep in &cached.dependencies {
dependencies.insert(dep.clone());
}
}
Ok(())
}
fn extract_inline_discriminator_value(
&self,
schema: &Schema,
discriminator_field: &str,
variant_index: usize,
) -> String {
// Try to extract discriminator value from inline schema properties
if let Some(properties) = &schema.details().properties {
if let Some(discriminator_prop) = properties.get(discriminator_field) {
// Check for enum with single value
if let Some(enum_values) = &discriminator_prop.details().enum_values {
if enum_values.len() == 1 {
if let Some(value) = enum_values[0].as_str() {
return value.to_string();
}
}
}
// Check for const value in extra fields
if let Some(const_value) = discriminator_prop.details().extra.get("const") {
if let Some(value) = const_value.as_str() {
return value.to_string();
}
}
// Check for const value in the discriminator_prop.details().const_value
if let Some(const_value) = &discriminator_prop.details().const_value {
if let Some(value) = const_value.as_str() {
return value.to_string();
}
}
}
}
// Try to infer from schema structure and properties
if let Some(inferred_name) = self.infer_variant_name_from_structure(schema, variant_index) {
return inferred_name;
}
// Fall back to generic variant name
format!("variant_{variant_index}")
}
fn infer_variant_name_from_structure(
&self,
schema: &Schema,
_variant_index: usize,
) -> Option<String> {
let details = schema.details();
// Strategy 1: Look for unique property combinations that suggest the variant type
if let Some(properties) = &details.properties {
// Common patterns for content blocks
if properties.contains_key("text") && properties.len() <= 3 {
return Some("text".to_string());
}
if properties.contains_key("image") || properties.contains_key("source") {
return Some("image".to_string());
}
if properties.contains_key("document") {
return Some("document".to_string());
}
if properties.contains_key("tool_use_id") || properties.contains_key("tool_result") {
return Some("tool_result".to_string());
}
if properties.contains_key("content") && properties.contains_key("is_error") {
return Some("tool_result".to_string());
}
if properties.contains_key("partial_json") {
return Some("partial_json".to_string());
}
// Strategy 2: Look for properties that hint at the variant purpose
let property_names: Vec<&String> = properties.keys().collect();
// Try to find the most descriptive property name
for prop_name in &property_names {
if prop_name.contains("result") {
return Some("result".to_string());
}
if prop_name.contains("error") {
return Some("error".to_string());
}
if prop_name.contains("content") && property_names.len() <= 2 {
return Some("content".to_string());
}
}
// Strategy 3: Use the most significant unique property
let significant_props = property_names
.iter()
.filter(|&name| !["type", "id", "cache_control"].contains(&name.as_str()))
.collect::<Vec<_>>();
if significant_props.len() == 1 {
return Some((*significant_props[0]).clone());
}
}
// Strategy 4: Look at description for hints
if let Some(description) = &details.description {
let desc_lower = description.to_lowercase();
if desc_lower.contains("text") && desc_lower.len() < 100 {
return Some("text".to_string());
}
if desc_lower.contains("image") {
return Some("image".to_string());
}
if desc_lower.contains("document") {
return Some("document".to_string());
}
if desc_lower.contains("tool") && desc_lower.contains("result") {
return Some("tool_result".to_string());
}
}
None
}
fn discriminator_to_variant_name(&self, discriminator: &str) -> String {
// Convert discriminator values to PascalCase variant names using general rules
if discriminator.is_empty() {
return "Variant".to_string();
}
let mut result = String::new();
let mut next_upper = true;
for c in discriminator.chars() {
match c {
'a'..='z' => {
if next_upper {
result.push(c.to_ascii_uppercase());
next_upper = false;
} else {
result.push(c);
}
}
'A'..='Z' => {
result.push(c);
next_upper = false;
}
'0'..='9' => {
result.push(c);
next_upper = false;
}
'_' | '-' | '.' | ' ' | '/' | '\\' => {
// Word separators - next char should be uppercase
next_upper = true;
}
_ => {
// Other special characters - treat as word boundary
next_upper = true;
}
}
}
// Ensure it starts with a letter
if result.is_empty() || result.chars().next().is_some_and(|c| c.is_ascii_digit()) {
result = format!("Variant{result}");
}
result
}
fn ensure_unique_variant_name(
&self,
base_name: String,
used_names: &mut std::collections::HashSet<String>,
) -> String {
let mut candidate = base_name.clone();
let mut counter = 1;
while used_names.contains(&candidate) {
counter += 1;
candidate = format!("{base_name}{counter}");
}
used_names.insert(candidate.clone());
candidate
}
fn generate_inline_type_name(&self, schema: &Schema, variant_index: usize) -> String {
// Try to generate a meaningful name for inline schemas
if let Some(meaningful_name) = self.infer_type_name_from_structure(schema) {
return meaningful_name;
}
// Fallback to context-aware name
let context = self.current_schema_name.as_deref().unwrap_or("Inline");
self.generate_context_aware_name(context, "Variant", variant_index, Some(schema))
}
fn infer_type_name_from_structure(&self, schema: &Schema) -> Option<String> {
let details = schema.details();
// Strategy 1: Use description if it's short and descriptive
if let Some(description) = &details.description {
if let Some(name_from_desc) = self.extract_type_name_from_description(description) {
return Some(name_from_desc);
}
}
// Strategy 2: Use the most significant property name as the type identifier
if let Some(properties) = &details.properties {
if let Some(name_from_props) = self.extract_type_name_from_properties(properties) {
return Some(format!("{name_from_props}Block"));
}
}
None
}
fn extract_type_name_from_description(&self, description: &str) -> Option<String> {
// Only use descriptions that are short and likely to be type identifiers
if description.len() > 100 || description.contains('\n') {
return None;
}
// Extract the first meaningful word(s) from the description
let words: Vec<&str> = description
.split_whitespace()
.take(2) // Only take first 2 words to avoid long names
.filter(|word| {
let w = word.to_lowercase();
word.len() > 2
&& ![
"the", "and", "for", "with", "that", "this", "are", "can", "will", "was",
]
.contains(&w.as_str())
})
.collect();
if words.is_empty() {
return None;
}
// Convert to PascalCase using our existing logic
let combined = words.join("_");
let pascal_name = self.discriminator_to_variant_name(&combined);
// Add suffix if it doesn't already have one
if !pascal_name.ends_with("Content")
&& !pascal_name.ends_with("Block")
&& !pascal_name.ends_with("Type")
{
Some(format!("{pascal_name}Content"))
} else {
Some(pascal_name)
}
}
fn extract_type_name_from_properties(
&self,
properties: &std::collections::BTreeMap<String, crate::openapi::Schema>,
) -> Option<String> {
// Get property names, excluding common structural properties
let significant_props: Vec<&String> = properties
.keys()
.filter(|name| !["type", "id", "cache_control"].contains(&name.as_str()))
.collect();
if significant_props.is_empty() {
return None;
}
// Strategy 1: If there's only one significant property, use it
if significant_props.len() == 1 {
let prop_name = significant_props[0];
return Some(self.discriminator_to_variant_name(prop_name));
}
// Strategy 2: Use the first property alphabetically for consistency
// This provides deterministic naming without hardcoded preferences
let mut sorted_props = significant_props.clone();
sorted_props.sort();
if let Some(first_prop) = sorted_props.first() {
return Some(self.discriminator_to_variant_name(first_prop));
}
None
}
fn openapi_type_to_rust_type(
&self,
openapi_type: OpenApiSchemaType,
details: &crate::openapi::SchemaDetails,
) -> String {
match openapi_type {
OpenApiSchemaType::String => "String".to_string(),
OpenApiSchemaType::Integer => self.get_number_rust_type(openapi_type, details),
OpenApiSchemaType::Number => self.get_number_rust_type(openapi_type, details),
OpenApiSchemaType::Boolean => "bool".to_string(),
OpenApiSchemaType::Array => "Vec<serde_json::Value>".to_string(), // Fallback for arrays without items
OpenApiSchemaType::Object => "serde_json::Value".to_string(), // Fallback for untyped objects
OpenApiSchemaType::Null => "()".to_string(), // Null type
}
}
#[allow(dead_code)]
fn fallback_discriminator_value(&self, schema_name: &str) -> String {
self.fallback_discriminator_value_for_field(schema_name, "type")
}
fn fallback_discriminator_value_for_field(
&self,
schema_name: &str,
field_name: &str,
) -> String {
// Try to extract from referenced schema first
if let Some(ref_schema) = self.schemas.get(schema_name) {
if let Some(extracted) =
self.extract_discriminator_value_for_field(ref_schema, field_name)
{
return extracted;
}
}
// Fall back to generating from name
self.generate_discriminator_value_from_name(schema_name)
}
fn generate_discriminator_value_from_name(&self, schema_name: &str) -> String {
// Convert schema names like "ResponseCreatedEvent" to "response.created"
let mut result = String::new();
let mut chars = schema_name.chars().peekable();
let mut first = true;
while let Some(c) = chars.next() {
if c.is_uppercase()
&& !first
&& chars
.peek()
.map(|&next| next.is_lowercase())
.unwrap_or(false)
{
result.push('.');
}
result.push(c.to_ascii_lowercase());
first = false;
}
// Remove common suffixes
if result.ends_with("event") {
result = result[..result.len() - 5].to_string();
}
// Add "response." prefix if it looks like a response event
if schema_name.starts_with("Response") && !result.starts_with("response.") {
result = format!("response.{}", result.trim_start_matches("response"));
}
result
}
fn to_rust_variant_name(&self, schema_name: &str) -> String {
// Convert "ResponseCreatedEvent" to "Created", "UserStatus" to "UserStatus", etc.
let mut name = schema_name;
// Remove common prefixes for cleaner variant names
if name.starts_with("Response") && name.len() > 8 {
name = &name[8..]; // Remove "Response"
}
// Remove common suffixes
if name.ends_with("Event") && name.len() > 5 {
name = &name[..name.len() - 5]; // Remove "Event"
}
// Trim leading and trailing underscores
name = name.trim_matches('_');
// Convert underscores to camel case using our existing function
if name.is_empty() {
schema_name.to_string()
} else {
// Use discriminator_to_variant_name to properly handle underscores
self.discriminator_to_variant_name(name)
}
}
fn analyze_array_schema(
&mut self,
schema: &Schema,
parent_schema_name: &str,
dependencies: &mut HashSet<String>,
) -> Result<SchemaType> {
let details = schema.details();
// Check if items field is present
if let Some(items_schema) = &details.items {
// Analyze the item type
let item_type = match items_schema.as_ref() {
Schema::Reference { reference, .. } => {
// Array of referenced types
let target = self
.extract_schema_name(reference)
.ok_or_else(|| GeneratorError::UnresolvedReference(reference.to_string()))?
.to_string();
dependencies.insert(target.clone());
SchemaType::Reference { target }
}
Schema::RecursiveRef { recursive_ref, .. } => {
// Array of recursive references
if recursive_ref == "#" {
// Self-reference to the current schema
let target = self
.find_recursive_anchor_schema()
.unwrap_or_else(|| parent_schema_name.to_string());
dependencies.insert(target.clone());
SchemaType::Reference { target }
} else {
let target = self
.extract_schema_name(recursive_ref)
.unwrap_or("RecursiveType")
.to_string();
dependencies.insert(target.clone());
SchemaType::Reference { target }
}
}
Schema::Typed { schema_type, .. } => {
// Array of primitive types
match schema_type {
OpenApiSchemaType::String => SchemaType::Primitive {
rust_type: "String".to_string(),
},
OpenApiSchemaType::Integer | OpenApiSchemaType::Number => {
let details = items_schema.details();
let rust_type = self.get_number_rust_type(schema_type.clone(), details);
SchemaType::Primitive { rust_type }
}
OpenApiSchemaType::Boolean => SchemaType::Primitive {
rust_type: "bool".to_string(),
},
OpenApiSchemaType::Object => {
// Inline object in array - create a named schema for it
let object_type_name = format!("{parent_schema_name}Item");
// Analyze the object schema
let object_type =
self.analyze_object_schema(items_schema, dependencies)?;
// Create an analyzed schema for the inline object
let inline_schema = AnalyzedSchema {
name: object_type_name.clone(),
original: serde_json::to_value(items_schema).unwrap_or(Value::Null),
schema_type: object_type,
dependencies: dependencies.clone(),
nullable: false,
description: items_schema.details().description.clone(),
default: None,
};
// Add the inline object as a named schema
self.resolved_cache
.insert(object_type_name.clone(), inline_schema);
dependencies.insert(object_type_name.clone());
// Return a reference to the named schema
SchemaType::Reference {
target: object_type_name,
}
}
OpenApiSchemaType::Array => {
// Array of arrays - recursively analyze
self.analyze_array_schema(
items_schema,
parent_schema_name,
dependencies,
)?
}
_ => SchemaType::Primitive {
rust_type: "serde_json::Value".to_string(),
},
}
}
Schema::OneOf { .. } | Schema::AnyOf { .. } => {
// Union types in arrays - analyze recursively
let analyzed = self.analyze_schema_value(items_schema, "ArrayItem")?;
// If we got a discriminated union or union, we need to create a separate schema for it
match &analyzed.schema_type {
SchemaType::DiscriminatedUnion { .. } | SchemaType::Union { .. } => {
// Generate a unique name for the union schema based on the parent context
// Use the parent context directly to maintain consistent naming
let union_name = format!("{parent_schema_name}ItemUnion");
// Create a new analyzed schema with the correct name
let mut union_schema = analyzed;
union_schema.name = union_name.clone();
// Add the union as a separate schema
self.resolved_cache.insert(union_name.clone(), union_schema);
// Add dependency
dependencies.insert(union_name.clone());
// Return a reference to the union schema
SchemaType::Reference { target: union_name }
}
_ => analyzed.schema_type,
}
}
Schema::Untyped { .. } => {
// Try to infer the type
if let Some(inferred) = items_schema.inferred_type() {
match inferred {
OpenApiSchemaType::Object => {
// Inline object in array - create a named schema for it
let object_type_name = format!("{parent_schema_name}Item");
// Analyze the object schema
let object_type =
self.analyze_object_schema(items_schema, dependencies)?;
// Create an analyzed schema for the inline object
let inline_schema = AnalyzedSchema {
name: object_type_name.clone(),
original: serde_json::to_value(items_schema)
.unwrap_or(Value::Null),
schema_type: object_type,
dependencies: dependencies.clone(),
nullable: false,
description: items_schema.details().description.clone(),
default: None,
};
// Add the inline object as a named schema
self.resolved_cache
.insert(object_type_name.clone(), inline_schema);
dependencies.insert(object_type_name.clone());
// Return a reference to the named schema
SchemaType::Reference {
target: object_type_name,
}
}
OpenApiSchemaType::String => SchemaType::Primitive {
rust_type: "String".to_string(),
},
OpenApiSchemaType::Integer | OpenApiSchemaType::Number => {
let details = items_schema.details();
let rust_type = self.get_number_rust_type(inferred, details);
SchemaType::Primitive { rust_type }
}
OpenApiSchemaType::Boolean => SchemaType::Primitive {
rust_type: "bool".to_string(),
},
_ => SchemaType::Primitive {
rust_type: "serde_json::Value".to_string(),
},
}
} else {
SchemaType::Primitive {
rust_type: "serde_json::Value".to_string(),
}
}
}
_ => SchemaType::Primitive {
rust_type: "serde_json::Value".to_string(),
},
};
Ok(SchemaType::Array {
item_type: Box::new(item_type),
})
} else {
// No items specified, fall back to generic array
Ok(SchemaType::Primitive {
rust_type: "Vec<serde_json::Value>".to_string(),
})
}
}
fn get_number_rust_type(
&self,
schema_type: OpenApiSchemaType,
details: &crate::openapi::SchemaDetails,
) -> String {
match schema_type {
OpenApiSchemaType::Integer => {
// Check format field for integer types
match details.format.as_deref() {
Some("int32") => "i32".to_string(),
Some("int64") => "i64".to_string(),
_ => "i64".to_string(), // Default for integer
}
}
OpenApiSchemaType::Number => {
// Check format field for number types
match details.format.as_deref() {
Some("float") => "f32".to_string(),
Some("double") => "f64".to_string(),
_ => "f64".to_string(), // Default for number
}
}
_ => "serde_json::Value".to_string(), // Fallback
}
}
fn analyze_anyof_union(
&mut self,
any_of_schemas: &[Schema],
discriminator: Option<&Discriminator>,
dependencies: &mut HashSet<String>,
context_name: &str,
) -> Result<SchemaType> {
// Drop {"type": "null"} variants. Nullability is surfaced as Option<T>
// at the property level via is_nullable_pattern(); leaving the null
// variant in here would produce a phantom `()` or `serde_json::Value`
// type alias that the generator can't render.
let filtered_owned: Vec<Schema>;
let any_of_schemas: &[Schema] = if any_of_schemas
.iter()
.any(|s| matches!(s.schema_type(), Some(OpenApiSchemaType::Null)))
{
filtered_owned = any_of_schemas
.iter()
.filter(|s| !matches!(s.schema_type(), Some(OpenApiSchemaType::Null)))
.cloned()
.collect();
if filtered_owned.is_empty() {
return Ok(SchemaType::Primitive {
rust_type: "serde_json::Value".to_string(),
});
}
if filtered_owned.len() == 1 {
return self
.analyze_schema_value(&filtered_owned[0], context_name)
.map(|a| a.schema_type);
}
&filtered_owned
} else {
any_of_schemas
};
// Pattern 2: Multiple complex types or mixed primitive/complex = flexible union
let has_refs = any_of_schemas.iter().any(|s| s.is_reference());
let has_objects = any_of_schemas.iter().any(|s| {
matches!(s.schema_type(), Some(OpenApiSchemaType::Object))
|| s.inferred_type() == Some(OpenApiSchemaType::Object)
});
let has_arrays = any_of_schemas
.iter()
.any(|s| matches!(s.schema_type(), Some(OpenApiSchemaType::Array)));
// Handle mixed primitive and complex types (like string + array of objects)
// Skip this pattern if all schemas are strings or const values (handle in pattern 3)
let all_string_like = any_of_schemas.iter().all(|s| {
matches!(s.schema_type(), Some(OpenApiSchemaType::String))
|| s.details().const_value.is_some()
});
if (has_refs || has_objects || has_arrays || any_of_schemas.len() > 1) && !all_string_like {
// Check if this is a discriminated union
if let Some(disc) = discriminator {
// This is a discriminated anyOf union, analyze it the same way as oneOf
return self.analyze_oneof_union(
any_of_schemas,
Some(disc),
context_name,
dependencies,
);
}
// Auto-detect implicit discriminator from const fields across all variants
if let Some(disc_field) = self.detect_discriminator_field(any_of_schemas) {
return self.analyze_oneof_union(
any_of_schemas,
Some(&Discriminator {
property_name: disc_field,
mapping: None,
extra: BTreeMap::new(),
}),
context_name,
dependencies,
);
}
// Create an untagged union for flexible matching
let mut variants = Vec::new();
for schema in any_of_schemas {
if let Some(ref_str) = schema.reference() {
if let Some(target) = self.extract_schema_name(ref_str) {
dependencies.insert(target.to_string());
variants.push(SchemaRef {
target: target.to_string(),
nullable: false,
});
}
} else if matches!(schema.schema_type(), Some(OpenApiSchemaType::Object))
|| schema.inferred_type() == Some(OpenApiSchemaType::Object)
{
// Generate inline object type for anyOf union
let inline_index = variants.len();
let inline_type_name = self.generate_inline_type_name(schema, inline_index);
// Store inline schema for later analysis and generation
self.add_inline_schema(&inline_type_name, schema, dependencies)?;
variants.push(SchemaRef {
target: inline_type_name,
nullable: false,
});
} else if matches!(schema.schema_type(), Some(OpenApiSchemaType::Array)) {
// Handle array types in unions by creating a type alias
let array_type =
self.analyze_array_schema(schema, context_name, dependencies)?;
// Create a unique name for this array type in the union
let array_type_name = if let Some(items_schema) = &schema.details().items {
if let Some(ref_str) = items_schema.reference() {
if let Some(item_type_name) = self.extract_schema_name(ref_str) {
dependencies.insert(item_type_name.to_string());
format!("{item_type_name}Array")
} else {
self.generate_context_aware_name(
context_name,
"Array",
variants.len(),
Some(schema),
)
}
} else {
self.generate_context_aware_name(
context_name,
"Array",
variants.len(),
Some(schema),
)
}
} else {
self.generate_context_aware_name(
context_name,
"Array",
variants.len(),
Some(schema),
)
};
// Store the array as a type alias
self.resolved_cache.insert(
array_type_name.clone(),
AnalyzedSchema {
name: array_type_name.clone(),
original: serde_json::to_value(schema).unwrap_or(Value::Null),
schema_type: array_type,
dependencies: HashSet::new(),
nullable: false,
description: Some("Array variant in union".to_string()),
default: None,
},
);
// Add array type as a dependency
dependencies.insert(array_type_name.clone());
variants.push(SchemaRef {
target: array_type_name,
nullable: false,
});
} else if let Some(schema_type) = schema.schema_type() {
// Handle primitive types by creating type aliases for consistency
let inline_index = variants.len();
// Generate a better name for primitive types
let inline_type_name = match schema_type {
OpenApiSchemaType::String => {
// For string types, check if we can infer a better name from context
// If this is the first variant and it's a string, use a simple name
if inline_index == 0 {
format!("{context_name}String")
} else {
format!("{context_name}StringVariant{inline_index}")
}
}
OpenApiSchemaType::Number => {
if inline_index == 0 {
format!("{context_name}Number")
} else {
format!("{context_name}NumberVariant{inline_index}")
}
}
OpenApiSchemaType::Integer => {
if inline_index == 0 {
format!("{context_name}Integer")
} else {
format!("{context_name}IntegerVariant{inline_index}")
}
}
OpenApiSchemaType::Boolean => {
if inline_index == 0 {
format!("{context_name}Boolean")
} else {
format!("{context_name}BooleanVariant{inline_index}")
}
}
_ => format!("{context_name}Variant{inline_index}"),
};
let rust_type =
self.openapi_type_to_rust_type(schema_type.clone(), schema.details());
// Store as a type alias
self.resolved_cache.insert(
inline_type_name.clone(),
AnalyzedSchema {
name: inline_type_name.clone(),
original: serde_json::to_value(schema).unwrap_or(Value::Null),
schema_type: SchemaType::Primitive { rust_type },
dependencies: HashSet::new(),
nullable: false,
description: schema.details().description.clone(),
default: None,
},
);
// Add inline type as a dependency
dependencies.insert(inline_type_name.clone());
variants.push(SchemaRef {
target: inline_type_name,
nullable: false,
});
}
}
if !variants.is_empty() {
return Ok(SchemaType::Union { variants });
}
}
// Pattern 3: String enum pattern (mix of "type": "string" and const values)
let all_strings = any_of_schemas.iter().all(|schema| {
matches!(schema.schema_type(), Some(OpenApiSchemaType::String))
|| schema.details().const_value.is_some()
});
if all_strings {
// Collect all constant values as enum variants
let mut enum_values = Vec::new();
let mut has_open_string = false;
for schema in any_of_schemas {
if let Some(const_val) = &schema.details().const_value {
if let Some(const_str) = const_val.as_str() {
enum_values.push(const_str.to_string());
}
} else if matches!(schema.schema_type(), Some(OpenApiSchemaType::String)) {
has_open_string = true;
}
}
if !enum_values.is_empty() {
if has_open_string {
// Has both constants and open string - create an extensible enum
// This generates an enum with known variants plus a Custom(String) variant
return Ok(SchemaType::ExtensibleEnum {
known_values: enum_values,
});
} else {
// All constants - create string enum
return Ok(SchemaType::StringEnum {
values: enum_values,
});
}
}
}
// Pattern 4: Mixed primitives = fall back to serde_json::Value
Ok(SchemaType::Primitive {
rust_type: "serde_json::Value".to_string(),
})
}
/// Find the schema with $recursiveAnchor: true for resolving $recursiveRef: "#"
fn find_recursive_anchor_schema(&self) -> Option<String> {
// Search through all schemas to find one with $recursiveAnchor: true
for (schema_name, schema) in &self.schemas {
let details = schema.details();
if details.recursive_anchor == Some(true) {
return Some(schema_name.clone());
}
}
// If no schema has $recursiveAnchor: true, this might be an older spec
// In that case, $recursiveRef: "#" typically refers to the root schema
// For now, return None to indicate we couldn't resolve it
None
}
/// Detect if a schema should use serde_json::Value for dynamic JSON
/// Based on structural patterns identified in real-world APIs
fn should_use_dynamic_json(&self, schema: &Schema) -> bool {
// Pattern 1: anyOf with [object, null] where object has no properties
if let Schema::AnyOf { any_of, .. } = schema {
if any_of.len() == 2 {
let has_null = any_of
.iter()
.any(|s| matches!(s.schema_type(), Some(OpenApiSchemaType::Null)));
let has_empty_object = any_of.iter().any(|s| self.is_dynamic_object_pattern(s));
if has_null && has_empty_object {
return true;
}
}
}
// Pattern 2: Direct empty object pattern
self.is_dynamic_object_pattern(schema)
}
/// Check if a schema represents a dynamic object pattern
fn is_dynamic_object_pattern(&self, schema: &Schema) -> bool {
// Must be object type or untyped with object inference
let is_object = match schema.schema_type() {
Some(OpenApiSchemaType::Object) => true,
None => schema.inferred_type() == Some(OpenApiSchemaType::Object),
_ => false,
};
if !is_object {
return false;
}
let details = schema.details();
// If it has explicit additionalProperties, it should remain as a typed object
// that will be generated as BTreeMap<String, serde_json::Value> or similar
if self.has_explicit_additional_properties(schema) {
return false;
}
// Pattern 1: Object with no properties at all (and no additionalProperties)
let no_properties = details
.properties
.as_ref()
.map(|props| props.is_empty())
.unwrap_or(true);
if no_properties {
// Check for constraints that would make this a structured type
let has_structural_constraints =
// Has required fields (other than just 'type')
details.required.as_ref()
.map(|req| req.iter().any(|r| r != "type"))
.unwrap_or(false)
// Has pattern-based property definitions
|| details.extra.contains_key("patternProperties")
// Has property name schema
|| details.extra.contains_key("propertyNames")
// Has min/max property constraints
|| details.extra.contains_key("minProperties")
|| details.extra.contains_key("maxProperties")
// Has specific property dependencies
|| details.extra.contains_key("dependencies")
// Has conditional schemas
|| details.extra.contains_key("if")
|| details.extra.contains_key("then")
|| details.extra.contains_key("else");
return !has_structural_constraints;
}
false
}
/// Check if this is an object that explicitly allows arbitrary additional properties
fn has_explicit_additional_properties(&self, schema: &Schema) -> bool {
let details = schema.details();
// Check if additionalProperties is explicitly set to true or a schema
matches!(
&details.additional_properties,
Some(crate::openapi::AdditionalProperties::Boolean(true))
| Some(crate::openapi::AdditionalProperties::Schema(_))
)
}
/// Analyze OpenAPI operations to extract request/response schemas
fn analyze_operations(&mut self, analysis: &mut SchemaAnalysis) -> Result<()> {
let spec: crate::openapi::OpenApiSpec = serde_json::from_value(self.openapi_spec.clone())
.map_err(GeneratorError::ParseError)?;
if let Some(paths) = &spec.paths {
for (path, path_item) in paths {
for (method, operation) in path_item.operations() {
// Generate operation ID if missing
let operation_id = operation
.operation_id
.clone()
.unwrap_or_else(|| Self::generate_operation_id(method, path));
let op_info = self.analyze_single_operation(
&operation_id,
method,
path,
operation,
path_item.parameters.as_ref(),
analysis,
)?;
analysis.operations.insert(operation_id, op_info);
}
}
}
Ok(())
}
/// Generate an operation ID from method and path when not provided
/// Converts paths like "/v0/servers/{serverId}" + "get" to "getV0ServersServerId"
fn generate_operation_id(method: &str, path: &str) -> String {
// Start with the HTTP method in lowercase
let mut operation_id = method.to_lowercase();
// Process the path: remove leading slash, split by /, convert to camelCase
let path_parts: Vec<&str> = path.trim_start_matches('/').split('/').collect();
for part in path_parts {
if part.is_empty() {
continue;
}
// Handle path parameters: {serverId} -> ServerId
let cleaned_part = if part.starts_with('{') && part.ends_with('}') {
&part[1..part.len() - 1]
} else {
part
};
// Convert to PascalCase and append
let pascal_case_part = cleaned_part
.split(&['-', '_'][..])
.map(|s| {
let mut chars = s.chars();
match chars.next() {
None => String::new(),
Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
}
})
.collect::<String>();
operation_id.push_str(&pascal_case_part);
}
operation_id
}
/// Analyze a single OpenAPI operation
fn analyze_single_operation(
&mut self,
operation_id: &str,
method: &str,
path: &str,
operation: &crate::openapi::Operation,
path_item_parameters: Option<&Vec<crate::openapi::Parameter>>,
_analysis: &mut SchemaAnalysis,
) -> Result<OperationInfo> {
let mut op_info = OperationInfo {
operation_id: operation_id.to_string(),
method: method.to_uppercase(),
path: path.to_string(),
summary: operation.summary.clone(),
description: operation.description.clone(),
request_body: None,
response_schemas: BTreeMap::new(),
parameters: Vec::new(),
supports_streaming: false, // Will be determined by StreamingConfig, not spec
stream_parameter: None, // Will be determined by StreamingConfig, not spec
};
// Extract request body schema with content-type awareness
if let Some(request_body) = &operation.request_body
&& let Some((content_type, maybe_schema)) = request_body.best_content()
{
use crate::openapi::{is_form_urlencoded_media_type, is_json_media_type};
op_info.request_body = if is_json_media_type(content_type) {
maybe_schema
.map(|s| {
self.resolve_or_inline_schema(s, operation_id, "Request")
.map(|name| RequestBodyContent::Json { schema_name: name })
})
.transpose()?
} else if is_form_urlencoded_media_type(content_type) {
maybe_schema
.map(|s| {
self.resolve_or_inline_schema(s, operation_id, "Request")
.map(|name| RequestBodyContent::FormUrlEncoded { schema_name: name })
})
.transpose()?
} else {
match content_type {
"multipart/form-data" => Some(RequestBodyContent::Multipart),
"application/octet-stream" => Some(RequestBodyContent::OctetStream),
"text/plain" => Some(RequestBodyContent::TextPlain),
_ => None,
}
};
}
// Extract response schemas
if let Some(responses) = &operation.responses {
for (status_code, response) in responses {
if let Some(schema) = response.json_schema() {
if let Some(schema_ref) = schema.reference() {
// Named schema reference
if let Some(schema_name) = self.extract_schema_name(schema_ref) {
op_info
.response_schemas
.insert(status_code.clone(), schema_name.to_string());
}
} else {
// Inline schema - generate a synthetic type name and analyze it
let synthetic_name =
self.generate_inline_response_type_name(operation_id, status_code);
// Use the existing inline schema infrastructure
let mut deps = HashSet::new();
self.add_inline_schema(&synthetic_name, schema, &mut deps)?;
op_info
.response_schemas
.insert(status_code.clone(), synthetic_name);
}
}
}
}
// Extract parameters (operation-level first, then merge path-item-level)
if let Some(parameters) = &operation.parameters {
for param in parameters {
let resolved = self.resolve_parameter(param);
if let Some(param_info) = self.analyze_parameter(&resolved)? {
op_info.parameters.push(param_info);
}
}
}
// Merge path-item-level parameters (operation params take precedence per OpenAPI spec)
if let Some(path_params) = path_item_parameters {
let existing_keys: std::collections::HashSet<(String, String)> = op_info
.parameters
.iter()
.map(|p| (p.name.clone(), p.location.clone()))
.collect();
for param in path_params {
let resolved = self.resolve_parameter(param);
if let Some(param_info) = self.analyze_parameter(&resolved)? {
if !existing_keys
.contains(&(param_info.name.clone(), param_info.location.clone()))
{
op_info.parameters.push(param_info);
}
}
}
}
Ok(op_info)
}
/// Generate a type name for an inline response schema.
///
/// 200 (the canonical success status) keeps the unsuffixed `{Op}Response`
/// name so simple specs and existing snapshots are unchanged. Every other
/// status code is disambiguated by suffix so that multi-response operations
/// (e.g. 200 + 400) don't collide in the schema registry — see issue #8.
fn generate_inline_response_type_name(&self, operation_id: &str, status_code: &str) -> String {
use heck::ToPascalCase;
let base_name = operation_id.replace('.', "_").to_pascal_case();
let suffix = Self::status_code_suffix(status_code);
format!("{}Response{}", base_name, suffix)
}
/// Map an OpenAPI status code key to a suffix for generated type names.
///
/// "200" → "" (unchanged, the dominant case)
/// "201", "400", "404" → "201", "400", "404"
/// "default" → "Default"
/// "4XX" / "4xx" → "4xx" (lowercased range form)
fn status_code_suffix(status_code: &str) -> String {
match status_code {
"" | "200" => String::new(),
"default" | "Default" => "Default".to_string(),
other if other.chars().all(|c| c.is_ascii_digit()) => other.to_string(),
other => other.to_ascii_lowercase(),
}
}
/// Generate a type name for an inline request body schema
fn generate_inline_request_type_name(&self, operation_id: &str) -> String {
use heck::ToPascalCase;
// Convert operation_id to PascalCase and append Request
// e.g., "session.prompt" -> "SessionPromptRequest"
// e.g., "pty.create" -> "PtyCreateRequest"
let base_name = operation_id.replace('.', "_").to_pascal_case();
format!("{}Request", base_name)
}
/// Resolve a schema reference to a name, or inline it with a synthetic name.
/// `suffix` controls the generated name (e.g. "Request" or "Response").
fn resolve_or_inline_schema(
&mut self,
schema: &crate::openapi::Schema,
operation_id: &str,
suffix: &str,
) -> Result<String> {
if let Some(schema_ref) = schema.reference()
&& let Some(schema_name) = self.extract_schema_name(schema_ref)
{
return Ok(schema_name.to_string());
}
// Inline schema - generate a synthetic type name and analyze it
let synthetic_name = if suffix == "Request" {
self.generate_inline_request_type_name(operation_id)
} else {
self.generate_inline_response_type_name(operation_id, "")
};
let mut deps = HashSet::new();
self.add_inline_schema(&synthetic_name, schema, &mut deps)?;
Ok(synthetic_name)
}
/// Resolve a parameter reference ($ref) to the actual parameter definition.
/// Returns the resolved parameter, or the original if it's not a reference.
fn resolve_parameter<'a>(
&'a self,
param: &'a crate::openapi::Parameter,
) -> std::borrow::Cow<'a, crate::openapi::Parameter> {
if let Some(ref_str) = param.extra.get("$ref").and_then(|v| v.as_str()) {
if let Some(param_name) = ref_str.strip_prefix("#/components/parameters/") {
if let Some(resolved) = self.component_parameters.get(param_name) {
return std::borrow::Cow::Borrowed(resolved);
}
}
}
std::borrow::Cow::Borrowed(param)
}
/// Analyze a parameter
fn analyze_parameter(
&self,
param: &crate::openapi::Parameter,
) -> Result<Option<ParameterInfo>> {
let name = param.name.as_deref().unwrap_or("");
let location = param.location.as_deref().unwrap_or("");
let required = param.required.unwrap_or(false);
let mut rust_type = "String".to_string();
let mut schema_ref = None;
if let Some(schema) = ¶m.schema {
if let Some(ref_str) = schema.reference() {
schema_ref = self.extract_schema_name(ref_str).map(|s| s.to_string());
} else if let Some(schema_type) = schema.schema_type() {
rust_type = match schema_type {
crate::openapi::SchemaType::Boolean => "bool",
crate::openapi::SchemaType::Integer => "i64",
crate::openapi::SchemaType::Number => "f64",
crate::openapi::SchemaType::String => "String",
_ => "String",
}
.to_string();
}
}
Ok(Some(ParameterInfo {
name: name.to_string(),
location: location.to_string(),
required,
schema_ref,
rust_type,
description: param.description.clone(),
}))
}
}