earthsci-ast 0.6.0

Rust implementation of EarthSciML Abstract Syntax Tree Format
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
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
//! Display formatting implementations for ESM expressions, models, and files
//!
//! This module implements `std::fmt::Display` and other formatting functions
//! for expressions with Unicode mathematical notation, chemical subscripts,
//! LaTeX output, and summary displays for models and reaction systems.

use crate::types::*;
use std::fmt;

// Element table - periodic table symbols for chemical subscript detection
const ELEMENTS: &[&str; 118] = &[
    "H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", "Al", "Si", "P", "S", "Cl",
    "Ar", "K", "Ca", "Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge", "As",
    "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb", "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "Cd", "In",
    "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "La", "Ce", "Pr", "Nd", "Pm", "Sm", "Eu", "Gd", "Tb",
    "Dy", "Ho", "Er", "Tm", "Yb", "Lu", "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au", "Hg", "Tl",
    "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "Ac", "Th", "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk",
    "Cf", "Es", "Fm", "Md", "No", "Lr", "Rf", "Db", "Sg", "Bh", "Hs", "Mt", "Ds", "Rg", "Cn", "Nh",
    "Fl", "Mc", "Lv", "Ts", "Og",
];

// Unicode subscript digits
const UNICODE_SUBSCRIPTS: [char; 10] = ['₀', '₁', '₂', '₃', '₄', '₅', '₆', '₇', '₈', '₉'];

// Unicode superscript digits
const UNICODE_SUPERSCRIPTS: [char; 10] = ['⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹'];

// Operator precedence levels (higher = tighter binding): the esm-spec §4.1.1
// table, identical to `op_precedence` in parse_expression.rs. Comparisons and
// `and`/`or` carry their real levels so the generic rule parenthesizes them
// under arithmetic: `(a <= b) * (c < d)`, never `a <= b * c < d`.
const PRECEDENCE: &[(&str, i32)] = &[
    ("or", 1),
    ("and", 2),
    ("==", 3),
    ("!=", 3),
    ("=", 3),
    ("<", 3),
    (">", 3),
    ("<=", 3),
    (">=", 3),
    ("+", 4),
    ("-", 4),
    ("*", 5),
    ("/", 5),
    ("not", 6),
    ("^", 7),
];

/// Operators whose same-op RIGHT operand needs no parentheses: the parser
/// re-flattens `a + (b + c)` into one n-ary node. Every other same-level right
/// operand keeps its parentheses (`a * (b / c)`, `a == (b < c)`, `a^(b^c)`),
/// because the parser groups same-level operators to the LEFT. Mirrors
/// `ASSOCIATIVE_OPS` in pretty-print.ts.
const ASSOCIATIVE_OPS: &[&str] = &["+", "*", "and", "or"];

/// The `parent_prec` a unary-minus operand renders at: the ADDITIVE level, so
/// a `+`/binary-`-` child (and anything looser: comparisons, `and`, `or`) is
/// parenthesized and a `*`/`/`/`^` child is not. It mirrors the parser's
/// `UMINUS_MIN` (parse_expression.rs), which reads a unary-minus operand at
/// multiplicative precedence — print `-(a + b)` without the parentheses and it
/// reads back as `(-a) + b`, a different expression. `-a * b` and `-a^2` need
/// none. Mirrors `UMINUS_OPERAND_MIN` in pretty-print.ts.
const UMINUS_OPERAND_PARENT_PREC: i32 = 4;

/// Render operand `arg` of the infix operator `op` (precedence `op_prec`).
/// A LEFT operand is parenthesized only when it binds strictly looser; a RIGHT
/// operand (for an n-ary `+ * and or`, every argument after the first) also
/// when it sits at the SAME level, unless it is the very same associative
/// operator. The one exception is LaTeX, where a binary `\frac` operand of `*`
/// is self-delimiting and is never wrapped.
fn render_operand(op: &str, op_prec: i32, arg: &Expr, is_right: bool, fmt: Fmt) -> String {
    if !is_right {
        return render_at(arg, fmt, op_prec - 1);
    }
    let bare = match arg {
        Expr::Operator(n) => {
            (n.op == op && ASSOCIATIVE_OPS.contains(&op))
                || (fmt == Fmt::Latex && op == "*" && n.op == "/" && n.args.len() == 2)
        }
        _ => true,
    };
    render_at(arg, fmt, if bare { op_prec - 1 } else { op_prec })
}

/// Whether a unary-minus operand needs parentheses that the precedence table
/// cannot express: a `-` directly before a numeric literal is part of the
/// literal, so `-(2^2)` printed as `-2^2` reads back as `(-2)^2`; the base is
/// the leftmost leaf of the operand, reached through `*` / `/`.
fn starts_with_literal_power(expr: &Expr) -> bool {
    let Expr::Operator(n) = expr else {
        return false;
    };
    match n.op.as_str() {
        "^" => matches!(
            n.args.first(),
            Some(Expr::Integer(_)) | Some(Expr::Number(_))
        ),
        "*" | "/" => n.args.first().is_some_and(starts_with_literal_power),
        _ => false,
    }
}

/// Get operator precedence (higher means tighter binding)
fn get_precedence(op: &str) -> i32 {
    for (operator, prec) in PRECEDENCE {
        if operator == &op {
            return *prec;
        }
    }
    0 // Default for unknown operators
}

/// The ONE canonical Greek-letter table; every derived lookup below
/// ([`greek_name_to_char`], [`greek_char_to_name`], [`greek_to_latex`]) reads
/// it, mirroring `GREEK_TABLE` in pretty-print.ts. Each row is
/// `(spelled ascii name, lowercase Unicode char, capital-has-distinct-LaTeX)`:
/// the flagged capitals render as a `\Gamma`-style command when SPELLED
/// (`"Gamma"`); the rest look like Latin capitals and carry none. Uppercase
/// Unicode chars appear in NO view — every backend passes them through
/// unchanged — and the name↔char views are lowercase-only, both deliberate
/// (they preserve each backend's prior behavior, and match pretty-print.ts).
const GREEK_TABLE: &[(&str, char, bool)] = &[
    ("alpha", 'α', false),
    ("beta", 'β', false),
    ("gamma", 'γ', true),
    ("delta", 'δ', true),
    ("epsilon", 'ε', false),
    ("zeta", 'ζ', false),
    ("eta", 'η', false),
    ("theta", 'θ', true),
    ("iota", 'ι', false),
    ("kappa", 'κ', false),
    ("lambda", 'λ', true),
    ("mu", 'μ', false),
    ("nu", 'ν', false),
    ("xi", 'ξ', true),
    ("omicron", 'ο', false),
    ("pi", 'π', true),
    ("rho", 'ρ', false),
    ("sigma", 'σ', true),
    ("tau", 'τ', false),
    ("upsilon", 'υ', true),
    ("phi", 'φ', true),
    ("chi", 'χ', false),
    ("psi", 'ψ', true),
    ("omega", 'ω', true),
];

/// The Unicode symbol for a spelled lowercase Greek-letter name
/// (`"pi"` → `'π'`), for the Unicode backend.
fn greek_name_to_char(name: &str) -> Option<char> {
    GREEK_TABLE
        .iter()
        .find(|(n, _, _)| *n == name)
        .map(|&(_, c, _)| c)
}

/// The spelled name of a lowercase Greek Unicode char (`'π'` → `"pi"`), for
/// the ASCII backend.
fn greek_char_to_name(c: char) -> Option<&'static str> {
    GREEK_TABLE
        .iter()
        .find(|&&(_, ch, _)| ch == c)
        .map(|&(n, _, _)| n)
}

/// Convert a string with chemical subscripts and Greek letters to Unicode
fn format_chemical_subscripts(s: &str) -> String {
    // A name that is exactly a spelled Greek letter becomes its symbol.
    if let Some(c) = greek_name_to_char(s) {
        return c.to_string();
    }

    // Peel a trailing ionic charge (`Ca2+`, `SO4-2`) so its magnitude renders
    // as a SUPERSCRIPT (`Ca²⁺`, `SO₄²⁻`) rather than an atom-count subscript.
    let (body, charge) = split_charge(s);

    let mut result = String::new();
    let chars: Vec<char> = body.chars().collect();
    let mut i = 0;

    while i < chars.len() {
        let ch = chars[i];

        if ch.is_alphabetic() {
            // Try to match 2-letter element symbol first
            if i + 1 < chars.len() {
                let two_letter = format!("{}{}", ch, chars[i + 1]);
                if ELEMENTS.contains(&two_letter.as_str()) {
                    result.push_str(&two_letter);
                    i += 2;

                    // Convert following digits to subscripts
                    while i < chars.len() && chars[i].is_ascii_digit() {
                        let digit = chars[i].to_digit(10).unwrap();
                        result.push(UNICODE_SUBSCRIPTS[digit as usize]);
                        i += 1;
                    }
                    continue;
                }
            }

            // Try 1-letter element symbol
            if ELEMENTS.contains(&ch.to_string().as_str()) {
                result.push(ch);
                i += 1;

                // Convert following digits to subscripts
                while i < chars.len() && chars[i].is_ascii_digit() {
                    let digit = chars[i].to_digit(10).unwrap();
                    result.push(UNICODE_SUBSCRIPTS[digit as usize]);
                    i += 1;
                }
                continue;
            }

            // Not an element symbol, just add the character
            result.push(ch);
            i += 1;
        } else {
            // A group-count after a closing bracket subscripts too (`Ca(OH)2`
            // → `Ca(OH)₂`); every other non-element character is copied as-is.
            result.push(ch);
            i += 1;
            if ch == ')' || ch == ']' {
                while i < chars.len() && chars[i].is_ascii_digit() {
                    let digit = chars[i].to_digit(10).unwrap();
                    result.push(UNICODE_SUBSCRIPTS[digit as usize]);
                    i += 1;
                }
            }
        }
    }

    result.push_str(&to_superscript_str(&charge));
    result
}

/// Split off a trailing ionic charge suffix, returning `(body, charge)` where
/// `charge` is the raw magnitude-then-sign string (`"2+"`, `"2-"`) — the caller
/// renders it as a superscript (Unicode `²⁺` via `to_superscript_str`, or LaTeX
/// `^{2+}`). Empty `charge` when no sign is present or the remaining body is not
/// a chemical formula, so ordinary identifiers are untouched. Input `2+` and
/// `-2` after a chemical body both normalize to `"2+"` / `"2-"`.
fn split_charge(s: &str) -> (&str, String) {
    let last = match s.chars().last() {
        Some(c) => c,
        None => return (s, String::new()),
    };
    // digits-then-sign, e.g. "Ca2+"
    if last == '+' || last == '-' {
        let without_sign = &s[..s.len() - 1];
        let mag: String = without_sign
            .chars()
            .rev()
            .take_while(|c| c.is_ascii_digit())
            .collect::<Vec<_>>()
            .into_iter()
            .rev()
            .collect();
        let body = &without_sign[..without_sign.len() - mag.len()];
        if !mag.is_empty() && is_chemical_formula(body) {
            return (body, format!("{mag}{last}"));
        }
    }
    // sign-then-digits, e.g. "SO4-2"
    if last.is_ascii_digit() {
        let mag: String = s
            .chars()
            .rev()
            .take_while(|c| c.is_ascii_digit())
            .collect::<Vec<_>>()
            .into_iter()
            .rev()
            .collect();
        let before = &s[..s.len() - mag.len()];
        if let Some(sign) = before.chars().last()
            && (sign == '+' || sign == '-')
        {
            let body = &before[..before.len() - 1];
            if is_chemical_formula(body) {
                return (body, format!("{mag}{sign}"));
            }
        }
    }
    (s, String::new())
}

/// Backend-independent pieces of a formatted floating-point number.
///
/// The Unicode, LaTeX, and ASCII printers previously each hand-rolled the
/// 0.0 special case, integer collapse, trailing-zero trimming, and
/// scientific-notation cutoffs — with slightly divergent orderings. They now
/// share `format_display_float` and differ only in how they render the
/// exponent (Unicode superscripts, LaTeX `\times 10^{...}`, ASCII `e`).
enum FloatParts {
    /// Rendered verbatim in every backend (e.g. "0", "42", "3.15").
    Plain(String),
    /// Scientific notation, e.g. mantissa "1.8" with exponent "-12". The
    /// mantissa always carries at least one decimal digit ("1" -> "1.0") and
    /// the exponent has no leading `+` (matching tests/display goldens).
    Scientific { mantissa: String, exponent: String },
    /// `+inf` (`false`) / `-inf` (`true`).
    Inf(bool),
    /// Not-a-number.
    NaN,
}

// Scientific-notation cutoffs (esm-spec §6.1 / RENDERING_CONTRACT.md "Number
// formatting"): a nonzero magnitude below the min or at/above the max renders
// in scientific notation, in EVERY backend and for integers alike.
const SCI_NOTATION_MIN: f64 = 0.01;
const SCI_NOTATION_MAX: f64 = 10000.0;

/// Shared float-formatting core for all three expression printers. Integer and
/// float leaves both flow through here so a magnitude like `15000` renders as
/// `1.5×10⁴` regardless of which JSON token produced it.
fn format_display_float(n: f64) -> FloatParts {
    if n.is_nan() {
        return FloatParts::NaN;
    }
    if n.is_infinite() {
        return FloatParts::Inf(n < 0.0);
    }
    // Zero prints as a bare "0" (never "0.0"), in every backend.
    if n == 0.0 {
        return FloatParts::Plain("0".to_string());
    }

    let abs_n = n.abs();
    if !(SCI_NOTATION_MIN..SCI_NOTATION_MAX).contains(&abs_n) {
        // The shortest round-tripping mantissa with no precision loss (e.g.
        // 0.009999 -> "9.999e-3") and an exponent with no leading `+`, matching
        // the normative number-formatting contract. See `shortest_sci` for why
        // it is not plain `{:e}`.
        let sci = shortest_sci(n);
        if let Some(e_pos) = sci.find('e') {
            let mut mantissa = sci[..e_pos].to_string();
            // Ensure at least one decimal place: "1" -> "1.0", "8.64" stays.
            if !mantissa.contains('.') {
                mantissa.push_str(".0");
            }
            return FloatParts::Scientific {
                mantissa,
                exponent: sci[e_pos + 1..].to_string(),
            };
        }
        return FloatParts::Plain(sci);
    }

    // Integers in normal range display without a decimal point.
    if n.fract() == 0.0 {
        return FloatParts::Plain(format!("{}", n as i64));
    }

    // In-range fractional value: shortest round-tripping decimal, no rounding,
    // printed at that many fraction digits so a tie breaks to even (see
    // `shortest_sci`).
    let (digits, exp) = shortest_digit_count(n);
    let frac = usize::try_from(digits as i64 - 1 - exp).unwrap_or(0);
    FloatParts::Plain(format!("{n:.frac$}"))
}

/// The significant-digit count and decimal exponent of the shortest decimal
/// that round-trips `n` (finite, non-zero), read off Rust's `{:e}`.
fn shortest_digit_count(n: f64) -> (usize, i64) {
    let s = format!("{n:e}");
    let e_pos = s.find('e').expect("`{:e}` always has an exponent");
    let digits = s[..e_pos].trim_start_matches('-').replace('.', "").len();
    let exp = s[e_pos + 1..]
        .parse()
        .expect("`{:e}` exponent is an integer");
    (digits, exp)
}

/// `n` in scientific notation with the shortest round-tripping mantissa.
///
/// `{:e}` finds the right digit COUNT, but when the float lies exactly halfway
/// between two candidates of that length (844280270821319.2 is stored as
/// …319.25) it rounds the last digit up, while every other binding — and
/// JavaScript's and Python's own float printing — breaks the tie to even
/// (`8.442802708213192e14`). Re-printing at that precision uses exact decimal
/// conversion, which rounds half to even, so all five bindings agree digit for
/// digit.
fn shortest_sci(n: f64) -> String {
    let (digits, _) = shortest_digit_count(n);
    let prec = digits - 1;
    format!("{n:.prec$e}")
}

/// Replace a leading ASCII hyphen with the Unicode U+2212 MINUS SIGN (used by
/// the Unicode number printer for both the mantissa and plain values).
fn unicode_minus(s: String) -> String {
    match s.strip_prefix('-') {
        Some(rest) => format!("−{rest}"),
        None => s,
    }
}

/// Unicode number rendering (U+2212 minus, superscript exponent, `∞`/`NaN`).
fn format_number_unicode(n: f64) -> String {
    match format_display_float(n) {
        FloatParts::Plain(s) => unicode_minus(s),
        FloatParts::Scientific { mantissa, exponent } => {
            format!(
                "{}×10{}",
                unicode_minus(mantissa),
                to_superscript_str(&exponent)
            )
        }
        FloatParts::Inf(neg) => if neg { "−∞" } else { "∞" }.to_string(),
        FloatParts::NaN => "NaN".to_string(),
    }
}

/// LaTeX number rendering (`\times 10^{…}`, `\infty`/`\text{NaN}`).
fn format_number_latex(n: f64) -> String {
    match format_display_float(n) {
        FloatParts::Plain(s) => s,
        FloatParts::Scientific { mantissa, exponent } => {
            format!("{mantissa} \\times 10^{{{exponent}}}")
        }
        FloatParts::Inf(neg) => if neg { "-\\infty" } else { "\\infty" }.to_string(),
        FloatParts::NaN => "\\text{NaN}".to_string(),
    }
}

/// ASCII number rendering (`mantissa e exp`, no `+` on a positive exponent).
fn format_number_ascii(n: f64) -> String {
    match format_display_float(n) {
        FloatParts::Plain(s) => s,
        FloatParts::Scientific { mantissa, exponent } => format!("{mantissa}e{exponent}"),
        FloatParts::Inf(neg) => if neg { "-inf" } else { "inf" }.to_string(),
        FloatParts::NaN => "NaN".to_string(),
    }
}

/// Render a non-finite value carried as a JSON *string* token (`"Infinity"`,
/// `"-Infinity"`, `"NaN"`) — JSON cannot encode these as numbers, so the corpus
/// smuggles them through as variable names. Returns `None` for any ordinary
/// identifier. See RENDERING_CONTRACT.md "Number formatting".
fn nonfinite_string(name: &str, fmt: Fmt) -> Option<String> {
    let n = match name {
        "Infinity" => f64::INFINITY,
        "-Infinity" => f64::NEG_INFINITY,
        "NaN" => f64::NAN,
        _ => return None,
    };
    Some(match fmt {
        Fmt::Unicode => format_number_unicode(n),
        Fmt::Latex => format_number_latex(n),
        Fmt::Ascii => format_number_ascii(n),
    })
}

impl fmt::Display for Expr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_unicode())
    }
}

impl Expr {
    /// Convert expression to Unicode mathematical notation
    pub fn to_unicode(&self) -> String {
        self.to_unicode_with_precedence(0)
    }

    fn to_unicode_with_precedence(&self, parent_prec: i32) -> String {
        match self {
            // Integers and floats share one formatter so a large-magnitude
            // integer (e.g. 15000) renders as scientific `1.5×10⁴` too.
            Expr::Number(n) => format_number_unicode(*n),
            Expr::Integer(n) => format_number_unicode(*n as f64),
            Expr::Variable(name) => nonfinite_string(name, Fmt::Unicode)
                .unwrap_or_else(|| format_chemical_subscripts(name)),
            Expr::Operator(node) => format_operator(node, Fmt::Unicode, parent_prec),
        }
    }
}

/// Render a call-shaped form `op_symbol(arg1, arg2, ...)`.
///
/// Dozens of match arms and every `_` fallback across the three printers
/// previously hand-rolled this exact shape; they share this helper instead.
/// `render` supplies the backend-specific argument rendering (typically at
/// precedence 0, since the parentheses already delimit the arguments).
fn call_form(op_symbol: &str, args: &[Expr], render: impl Fn(&Expr) -> String) -> String {
    format!(
        "{}({})",
        op_symbol,
        args.iter().map(render).collect::<Vec<_>>().join(", ")
    )
}

/// Select the backend-specific spelling of a symbol that differs only by text
/// (`·`/`\cdot`/`*`, `≥`/`\geq`/`>=`, …). The symbol table that lets the three
/// operator printers share one traversal.
fn pick(fmt: Fmt, unicode: &'static str, latex: &'static str, ascii: &'static str) -> &'static str {
    match fmt {
        Fmt::Unicode => unicode,
        Fmt::Latex => latex,
        Fmt::Ascii => ascii,
    }
}

/// Render a binary comparison `a SYM b` (left operand at the strictly-looser
/// level, right operand under the same-level rule of [`render_operand`]), or
/// fall back to a call form at any other arity. `infix`/`call` are the
/// already-selected backend symbols.
fn comparison_or_call(
    op: &str,
    op_prec: i32,
    args: &[Expr],
    infix: &str,
    call: &str,
    fmt: Fmt,
) -> String {
    if args.len() == 2 {
        format!(
            "{} {} {}",
            render_operand(op, op_prec, &args[0], false, fmt),
            infix,
            render_operand(op, op_prec, &args[1], true, fmt)
        )
    } else {
        call_form(call, args, |a| render_at(a, fmt, 0))
    }
}

/// Render an n-ary infix chain `a SEP b SEP c`: every argument after the first
/// is a RIGHT operand (see [`render_operand`]), so `k * (a / b) * c`.
fn infix_chain(op: &str, op_prec: i32, args: &[Expr], sep: &str, fmt: Fmt) -> String {
    args.iter()
        .enumerate()
        .map(|(i, a)| render_operand(op, op_prec, a, i > 0, fmt))
        .collect::<Vec<_>>()
        .join(sep)
}

/// The three text-rendering backends. Shared by the structural / array-query
/// op renderer so it can produce all three formats from one code path (the
/// scalar-op dispatch keeps three separate functions for readability).
#[derive(Clone, Copy, PartialEq, Eq)]
enum Fmt {
    Unicode,
    Latex,
    Ascii,
}

/// Render a sub-expression in the requested backend at outer precedence.
fn render_fmt(expr: &Expr, fmt: Fmt) -> String {
    match fmt {
        Fmt::Unicode => to_unicode(expr),
        Fmt::Latex => to_latex(expr),
        Fmt::Ascii => to_ascii(expr),
    }
}

/// Render an operator node as a scalar expression in the requested backend
/// (used by `broadcast`, which renders identically to its elementwise `fn`).
fn render_operator(node: &ExpressionNode, fmt: Fmt) -> String {
    format_operator(node, fmt, 0)
}

/// Escape LaTeX-special underscores in a bare operator / identifier name.
fn latex_name(name: &str) -> String {
    name.replace('_', "\\_")
}

/// The integer value of an exponent literal, if it is one (used to pick
/// Unicode-superscript rendering for `x^n`).
fn integer_exponent(e: &Expr) -> Option<i64> {
    match e {
        Expr::Integer(n) => Some(*n),
        Expr::Number(n) if n.fract() == 0.0 => Some(*n as i64),
        _ => None,
    }
}

/// Convert a decimal integer string to Unicode superscript characters.
fn to_superscript_str(s: &str) -> String {
    s.chars()
        .map(|c| match c {
            '0'..='9' => UNICODE_SUPERSCRIPTS[c.to_digit(10).unwrap() as usize],
            '-' => '⁻',
            '+' => '⁺',
            other => other,
        })
        .collect()
}

/// Replace Unicode Greek characters with their ASCII names (e.g. `θ` → `theta`)
/// for the ASCII backend. Non-Greek characters pass through unchanged.
fn greek_to_ascii(s: &str) -> String {
    let mut out = String::new();
    for c in s.chars() {
        match greek_char_to_name(c) {
            Some(name) => out.push_str(name),
            None => out.push(c),
        }
    }
    out
}

/// LaTeX command for a variable name that is exactly a Greek letter, given
/// either as a spelled name (`"phi"`) or a single Unicode character (`"θ"`).
/// The capitals with a distinct LaTeX command are recognized SPELLED only
/// (`"Phi"` → `\Phi`); the rest, and every uppercase Unicode char, return
/// `None` — as does any non-Greek identifier.
fn greek_to_latex(name: &str) -> Option<String> {
    for &(n, c, capital_has_latex) in GREEK_TABLE {
        // A lowercase letter, spelled either way (`"phi"` or `"φ"`).
        if name == n || name.chars().eq(std::iter::once(c)) {
            return Some(format!("\\{n}"));
        }
        // Its spelled capital (`"Phi"`), when the capital has its own command.
        let initial = n.chars().next().expect("table names are non-empty");
        if capital_has_latex && name.strip_prefix(initial.to_ascii_uppercase()) == Some(&n[1..]) {
            return Some(format!("\\{name}"));
        }
    }
    None
}

/// The raw identifier string carried by a leaf expression (used by `enum`,
/// whose members are bare `Type`/`Member` names, not rendered sub-expressions).
fn expr_raw_string(e: &Expr) -> String {
    match e {
        Expr::Variable(s) => s.clone(),
        Expr::Integer(n) => n.to_string(),
        Expr::Number(n) => n.to_string(),
        Expr::Operator(node) => node.op.clone(),
    }
}

/// Parenthesize a sub-expression only when it is an operator node (used by
/// `index` / `transpose`, whose base is bracketed rather than call-wrapped).
fn wrap_if_op(expr: &Expr, fmt: Fmt) -> String {
    let s = render_fmt(expr, fmt);
    if matches!(expr, Expr::Operator(_)) {
        format!("({s})")
    } else {
        s
    }
}

/// Render a sub-expression at a specific parent precedence in the given backend.
fn render_at(expr: &Expr, fmt: Fmt, prec: i32) -> String {
    match fmt {
        Fmt::Unicode => expr.to_unicode_with_precedence(prec),
        Fmt::Latex => to_latex_prec(expr, prec),
        Fmt::Ascii => to_ascii_prec(expr, prec),
    }
}

/// A binary `+` whose right operand is a unary minus renders as a subtraction
/// (`a + (−b)` → `a − b`); returns the rendered string when this applies.
fn sum_as_difference(args: &[Expr], op_prec: i32, fmt: Fmt) -> Option<String> {
    if args.len() != 2 {
        return None;
    }
    let Expr::Operator(n) = &args[1] else {
        return None;
    };
    if n.op != "-" || n.args.len() != 1 {
        return None;
    }
    let minus = if fmt == Fmt::Unicode { "−" } else { "-" };
    Some(format!(
        "{} {minus} {}",
        render_at(&args[0], fmt, op_prec - 1),
        render_at(&n.args[0], fmt, op_prec)
    ))
}

/// True when a LaTeX product has a direct operand that is a variable NAME
/// already carrying a command backslash (e.g. `\mathrm{O_3}`); such products
/// render by juxtaposition (a space) rather than with `\cdot`. Mirrors the
/// `latexSep` decision in pretty-print.ts.
fn latex_mul_juxtapose(args: &[Expr]) -> bool {
    args.iter()
        .any(|a| matches!(a, Expr::Variable(v) if v.contains('\\')))
}

/// Render one `makearray` region bound. An integer prints PLAIN (`10000`, never
/// `1.0e4`) — it is an index, not a measured quantity — while an unfolded bound
/// expression renders like any other sub-expression. Mirrors `formatBound` in
/// pretty-print.ts.
fn format_region_bound(bound: &crate::types::RegionBound, fmt: Fmt) -> String {
    match bound {
        crate::types::RegionBound::Int(i) => i.to_string(),
        crate::types::RegionBound::Expr(Expr::Integer(i)) => i.to_string(),
        crate::types::RegionBound::Expr(e) => render_fmt(e, fmt),
    }
}

/// Render a `const` node's literal JSON value (scalar number or nested array).
/// Integer JSON tokens print as plain integers (so `const 0` is `0`, not
/// `0.0`); float tokens use the backend's number formatting.
fn format_const_value(value: &serde_json::Value, fmt: Fmt) -> String {
    match value {
        serde_json::Value::Array(arr) => {
            let inner = arr
                .iter()
                .map(|v| format_const_value(v, fmt))
                .collect::<Vec<_>>()
                .join(", ");
            format!("[{inner}]")
        }
        serde_json::Value::Number(num) => {
            if let Some(i) = num.as_i64() {
                i.to_string()
            } else if let Some(u) = num.as_u64() {
                u.to_string()
            } else if let Some(f) = num.as_f64() {
                format_number_fmt(f, fmt)
            } else {
                num.to_string()
            }
        }
        serde_json::Value::String(s) => s.clone(),
        serde_json::Value::Bool(b) => b.to_string(),
        other => other.to_string(),
    }
}

/// Stringify a scalar JSON value (e.g. a `table_lookup` `output` selector).
fn json_scalar_string(v: &serde_json::Value) -> String {
    match v {
        serde_json::Value::String(s) => s.clone(),
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::Bool(b) => b.to_string(),
        other => other.to_string(),
    }
}

/// Big-operator symbol for a `faq` reduction (semiring supersedes the
/// bare `reduce`). See tests/display/RENDERING_CONTRACT.md.
fn aggregate_symbol(semiring: Option<&str>, reduce: &str, fmt: Fmt) -> &'static str {
    enum Fam {
        Plus,
        Times,
        Max,
        Min,
        Bool,
    }
    let fam = if let Some(sr) = semiring {
        match sr {
            "max_product" | "max_sum" => Fam::Max,
            "min_sum" => Fam::Min,
            "bool_and_or" => Fam::Bool,
            _ => Fam::Plus,
        }
    } else {
        match reduce {
            "*" => Fam::Times,
            "max" => Fam::Max,
            "min" => Fam::Min,
            _ => Fam::Plus,
        }
    };
    let (u, l, a) = match fam {
        Fam::Plus => ("Σ", "\\sum", "sum"),
        Fam::Times => ("Π", "\\prod", "prod"),
        Fam::Max => ("max", "\\max", "max"),
        Fam::Min => ("min", "\\min", "min"),
        Fam::Bool => ("⋁", "\\bigvee", "any"),
    };
    match fmt {
        Fmt::Unicode => u,
        Fmt::Latex => l,
        Fmt::Ascii => a,
    }
}

/// Render one range entry (`[a,b]` → `a:b`, index-set ref → `name(of…)`).
fn format_range_spec(rng: &RangeSpec) -> String {
    match rng {
        RangeSpec::Interval(iv) => format!("{}:{}", iv[0], iv[1]),
        RangeSpec::Strided(iv) => format!("{}:{}:{}", iv[0], iv[1], iv[2]),
        RangeSpec::IndexSetRef { from, of } => match of {
            Some(of) if !of.is_empty() => format!("{}({})", from, of.join(", ")),
            _ => from.clone(),
        },
        RangeSpec::RaggedDyn { offsets, of } => format!("{}({})", offsets, of.join(", ")),
        RangeSpec::DerivedDyn { from_faq } => from_faq.clone(),
    }
}

/// Render the ` where {…}` range clause shared by aggregate and argmin/argmax
/// (keys sorted for determinism).
fn format_ranges_clause(ranges: &std::collections::HashMap<String, RangeSpec>, fmt: Fmt) -> String {
    let in_sym = match fmt {
        Fmt::Latex => " \\in ",
        Fmt::Unicode => "∈",
        Fmt::Ascii => " in ",
    };
    let mut keys: Vec<&String> = ranges.keys().collect();
    keys.sort();
    let parts = keys
        .iter()
        .map(|k| format!("{}{}{}", k, in_sym, format_range_spec(&ranges[*k])))
        .collect::<Vec<_>>()
        .join(", ");
    match fmt {
        Fmt::Latex => format!(" \\text{{ where }} \\{{{parts}\\}}"),
        _ => format!(" where {{{parts}}}"),
    }
}

/// Render the ` join(…)` clause shared by `faq` and `argmin`/`argmax`, or `""`
/// when there is none. Clauses are joined `; `. An equality clause lists its
/// key-column pairs `l=r` and then, when present, the self-join side assignment
/// `syms=[left, right]`; an overlap clause is the keyword call
/// `overlap(src=[…], tgt=[…])` with `, eps=E` whenever `eps` is present
/// (including `0`). Mirrors `formatJoinClause` in pretty-print.ts.
fn format_join_clause(join: Option<&[JoinClause]>, fmt: Fmt) -> String {
    let Some(join) = join.filter(|j| !j.is_empty()) else {
        return String::new();
    };
    let clauses = join
        .iter()
        .map(|c| {
            if let Some(ov) = &c.overlap {
                let eps = match ov.eps {
                    Some(e) => format!(", eps={}", format_number_fmt(e, fmt)),
                    None => String::new(),
                };
                return format!(
                    "overlap(src=[{}], tgt=[{}]{eps})",
                    ov.src_env.join(", "),
                    ov.tgt_env.join(", ")
                );
            }
            let mut parts: Vec<String> =
                c.on.iter().map(|p| format!("{}={}", p[0], p[1])).collect();
            if let Some(syms) = &c.syms {
                parts.push(format!("syms=[{}]", syms.join(", ")));
            }
            parts.join(", ")
        })
        .collect::<Vec<_>>()
        .join("; ");
    format!(" join({clauses})")
}

/// A float in the backend's number formatting.
fn format_number_fmt(n: f64, fmt: Fmt) -> String {
    match fmt {
        Fmt::Unicode => format_number_unicode(n),
        Fmt::Latex => format_number_latex(n),
        Fmt::Ascii => format_number_ascii(n),
    }
}

/// Render a `faq` node per tests/display/RENDERING_CONTRACT.md §aggregate.
fn format_aggregate(node: &ExpressionNode, fmt: Fmt) -> String {
    let out_idx = node
        .output_idx
        .as_ref()
        .map(|v| v.join(", "))
        .unwrap_or_default();
    let expr_str = node
        .expr
        .as_deref()
        .map(|e| render_fmt(e, fmt))
        .unwrap_or_default();
    let semiring = node.semiring.as_deref();
    let reduce = node.reduce.as_deref().unwrap_or("+");
    let sym = aggregate_symbol(semiring, reduce, fmt);
    let idx_part = if fmt == Fmt::Latex {
        format!("_{{{out_idx}}}")
    } else {
        format!("[{out_idx}]")
    };
    let mut out = format!("{sym}{idx_part} ({expr_str})");
    if let Some(ranges) = &node.ranges
        && !ranges.is_empty()
    {
        out.push_str(&format_ranges_clause(ranges, fmt));
    }
    out.push_str(&format_join_clause(node.join.as_deref(), fmt));
    if let Some(filter) = node.filter.as_deref() {
        out.push_str(&format!(" if {}", render_fmt(filter, fmt)));
    }
    if node.distinct == Some(true) {
        out.push_str(" distinct");
    }
    if let Some(key) = node.key.as_deref() {
        out.push_str(&format!(" key={}", render_fmt(key, fmt)));
    }
    // `id` is a bare-name clause rather than part of the `[…]` suffix so it adds
    // no new bracket ambiguity with `table_lookup`'s `name[axis=…]` surface.
    if let Some(id) = node.id.as_deref() {
        out.push_str(&format!(" id={id}"));
    }
    if let Some(sr) = semiring
        && sr != "sum_product"
    {
        out.push_str(&format!(" [semiring={sr}]"));
    }
    out
}

/// Render an `argmin` / `argmax` arg-witness node.
fn format_arg_witness(node: &ExpressionNode, fmt: Fmt) -> String {
    let arg = node.arg.as_deref().unwrap_or("");
    let expr_str = node
        .expr
        .as_deref()
        .map(|e| render_fmt(e, fmt))
        .unwrap_or_default();
    let idx_part = if fmt == Fmt::Latex {
        format!("_{{{arg}}}")
    } else {
        format!("[{arg}]")
    };
    let name = if fmt == Fmt::Latex {
        format!("\\mathrm{{{}}}", node.op)
    } else {
        node.op.clone()
    };
    let mut out = format!("{name}{idx_part} ({expr_str})");
    if let Some(ranges) = &node.ranges
        && !ranges.is_empty()
    {
        out.push_str(&format_ranges_clause(ranges, fmt));
    }
    out.push_str(&format_join_clause(node.join.as_deref(), fmt));
    if let Some(filter) = node.filter.as_deref() {
        out.push_str(&format!(" if {}", render_fmt(filter, fmt)));
    }
    if let Some(id) = node.id.as_deref() {
        out.push_str(&format!(" id={id}"));
    }
    out
}

/// Render the closed-core structural / array-query ops (esm-spec §4.2), whose
/// defining data lives in fields OTHER than `args`, plus `integral`. Returns a
/// fully-formatted string, or `None` for ops handled by the scalar-op dispatch
/// (arithmetic, elementary functions, comparisons, `D`, `Pre`, …) or by the
/// generic fallback (open-tier sugar `grad`/`div`/`laplacian`, unknown user
/// ops). Mirrors `formatStructuralOp` in pretty-print.ts.
fn format_structural_op(node: &ExpressionNode, fmt: Fmt) -> Option<String> {
    let op = node.op.as_str();
    let args = node.args.as_slice();
    let eq = if fmt == Fmt::Latex { " = " } else { "=" };

    match op {
        "const" => Some(format_const_value(
            node.value.as_ref().unwrap_or(&serde_json::Value::Null),
            fmt,
        )),

        "true" | "false" => Some(op.to_string()),

        "fn" => {
            let name = node.name.as_deref().unwrap_or("");
            let inner = args
                .iter()
                .map(|a| render_fmt(a, fmt))
                .collect::<Vec<_>>()
                .join(", ");
            Some(match fmt {
                Fmt::Latex => format!("\\mathrm{{{}}}({})", latex_name(name), inner),
                _ => format!("{name}({inner})"),
            })
        }

        "enum" => {
            let a0 = args.first().map(expr_raw_string).unwrap_or_default();
            let a1 = args.get(1).map(expr_raw_string).unwrap_or_default();
            let label = format!("{a0}.{a1}");
            Some(match fmt {
                Fmt::Latex => format!("\\mathrm{{{}}}", latex_name(&label)),
                _ => label,
            })
        }

        "index" => {
            if args.is_empty() {
                return None;
            }
            let idx = args[1..]
                .iter()
                .map(|a| render_fmt(a, fmt))
                .collect::<Vec<_>>()
                .join(", ");
            Some(format!("{}[{}]", wrap_if_op(&args[0], fmt), idx))
        }

        "broadcast" => {
            let fn_name = node.broadcast_fn.as_deref()?;
            let synth = ExpressionNode {
                op: fn_name.to_string(),
                args: node.args.clone(),
                ..Default::default()
            };
            Some(render_operator(&synth, fmt))
        }

        "integral" => {
            if args.is_empty() {
                return None;
            }
            let f = render_fmt(&args[0], fmt);
            let v = node.int_var.as_deref().unwrap_or("x");
            let lo = node
                .lower
                .as_deref()
                .map(|e| render_fmt(e, fmt))
                .unwrap_or_default();
            let hi = node
                .upper
                .as_deref()
                .map(|e| render_fmt(e, fmt))
                .unwrap_or_default();
            Some(match fmt {
                Fmt::Latex => format!("\\int_{{{lo}}}^{{{hi}}} {f} \\, d{v}"),
                Fmt::Unicode => format!("∫[{lo}, {hi}] {f} d{v}"),
                Fmt::Ascii => format!("integral({f}, {v}, {lo}, {hi})"),
            })
        }

        "table_lookup" => {
            let table = node.table.as_deref().unwrap_or("");
            let bindings = node
                .axes
                .as_ref()
                .map(|axes| {
                    let mut keys: Vec<&String> = axes.keys().collect();
                    keys.sort();
                    keys.iter()
                        .map(|k| format!("{}{}{}", k, eq, render_fmt(&axes[*k], fmt)))
                        .collect::<Vec<_>>()
                        .join(", ")
                })
                .unwrap_or_default();
            let out_str = match &node.output {
                Some(v) if !v.is_null() => format!(":{}", json_scalar_string(v)),
                _ => String::new(),
            };
            let name = if fmt == Fmt::Latex {
                format!("\\mathrm{{{}}}", latex_name(table))
            } else {
                table.to_string()
            };
            Some(format!("{name}[{bindings}]{out_str}"))
        }

        "apply_expression_template" => {
            let name = node.name.as_deref().unwrap_or("");
            let inner = node
                .bindings
                .as_ref()
                .map(|b| {
                    let mut keys: Vec<&String> = b.keys().collect();
                    keys.sort();
                    keys.iter()
                        .map(|k| format!("{}{}{}", k, eq, render_fmt(&b[*k], fmt)))
                        .collect::<Vec<_>>()
                        .join(", ")
                })
                .unwrap_or_default();
            Some(match fmt {
                Fmt::Latex => format!(
                    "\\mathrm{{{}}}\\langle {} \\rangle",
                    latex_name(name),
                    inner
                ),
                Fmt::Unicode => format!("{name}⟨{inner}⟩"),
                Fmt::Ascii => format!("{name}<{inner}>"),
            })
        }

        "makearray" => {
            let values = node.values.as_ref();
            let parts = node
                .regions
                .as_ref()
                .map(|regions| {
                    regions
                        .iter()
                        .enumerate()
                        .map(|(i, region)| {
                            let reg_str = region
                                .iter()
                                .map(|dim| {
                                    format!(
                                        "{}:{}",
                                        format_region_bound(&dim[0], fmt),
                                        format_region_bound(&dim[1], fmt)
                                    )
                                })
                                .collect::<Vec<_>>()
                                .join(", ");
                            let val = values
                                .and_then(|vs| vs.get(i))
                                .map(|v| render_fmt(v, fmt))
                                .unwrap_or_else(|| "?".to_string());
                            format!("[{reg_str}] = {val}")
                        })
                        .collect::<Vec<_>>()
                        .join(", ")
                })
                .unwrap_or_default();
            let name = if fmt == Fmt::Latex {
                "\\mathrm{makearray}"
            } else {
                "makearray"
            };
            Some(format!("{name}({parts})"))
        }

        "reshape" => {
            if args.is_empty() {
                return None;
            }
            let shape = node
                .shape
                .as_ref()
                .map(|s| {
                    s.iter()
                        .map(|x| x.to_string())
                        .collect::<Vec<_>>()
                        .join(", ")
                })
                .unwrap_or_default();
            let name = if fmt == Fmt::Latex {
                "\\mathrm{reshape}"
            } else {
                "reshape"
            };
            Some(format!(
                "{}({}, [{}])",
                name,
                render_fmt(&args[0], fmt),
                shape
            ))
        }

        "transpose" => {
            if args.is_empty() {
                return None;
            }
            if let Some(perm) = &node.perm
                && !perm.is_empty()
            {
                let p = perm
                    .iter()
                    .map(|x| x.to_string())
                    .collect::<Vec<_>>()
                    .join(", ");
                let name = if fmt == Fmt::Latex {
                    "\\mathrm{transpose}"
                } else {
                    "transpose"
                };
                return Some(format!("{}({}, [{}])", name, render_fmt(&args[0], fmt), p));
            }
            let a = wrap_if_op(&args[0], fmt);
            Some(match fmt {
                Fmt::Latex => format!("{a}^{{T}}"),
                Fmt::Unicode => format!("{a}ᵀ"),
                Fmt::Ascii => format!("transpose({})", render_fmt(&args[0], fmt)),
            })
        }

        "concat" => {
            let inner = args
                .iter()
                .map(|a| render_fmt(a, fmt))
                .collect::<Vec<_>>()
                .join(", ");
            let name = if fmt == Fmt::Latex {
                "\\mathrm{concat}"
            } else {
                "concat"
            };
            let axis = node.axis.unwrap_or(0);
            Some(format!("{name}({inner}, axis={axis})"))
        }

        "intersect_polygon" | "polygon_intersection_area" => {
            let inner = args
                .iter()
                .map(|a| render_fmt(a, fmt))
                .collect::<Vec<_>>()
                .join(", ");
            let name = if fmt == Fmt::Latex {
                format!("\\mathrm{{{}}}", latex_name(op))
            } else {
                op.to_string()
            };
            let manifold = node.manifold.as_deref().unwrap_or("");
            // `id` (RFC §6.1 node identity) is emitted as a trailing named
            // argument when present, so a node addressable as a derived index
            // set's `from_faq` referent survives the text round-trip. Absent
            // `id` prints exactly as before.
            let id_part = match node.id.as_deref() {
                Some(id) => format!(", id={id}"),
                None => String::new(),
            };
            Some(format!("{name}({inner}, manifold={manifold}{id_part})"))
        }

        // The documentary `label` is a trailing named argument, like
        // `intersect_polygon`'s `manifold=`; an unlabeled skolem is a plain
        // call (the generic fallback).
        "skolem" => {
            let label = node.label.as_deref()?;
            let inner = args
                .iter()
                .map(|a| render_fmt(a, fmt))
                .collect::<Vec<_>>()
                .join(", ");
            let name = if fmt == Fmt::Latex {
                "\\mathrm{skolem}"
            } else {
                "skolem"
            };
            Some(format!("{name}({inner}, label={label})"))
        }

        "faq" => Some(format_aggregate(node, fmt)),

        "argmin" | "argmax" => Some(format_arg_witness(node, fmt)),

        _ => None,
    }
}

/// Render a scalar operator node (arithmetic, comparisons, boolean ops,
/// elementary functions, `D`, `Pre`, and the generic call fallback) in the
/// requested backend. The three backends share one traversal and per-op symbol
/// table (`pick`); only genuinely shape-divergent ops keep a per-`fmt` leaf:
/// LaTeX `\frac`/`\begin{cases}`/`\exp`/juxtaposition-multiplication, and the
/// Unicode integer-exponent superscripts and `⌊⌋`/`⌈⌉`/`|·|`/`√` delimiters.
/// Mirrors the `format_structural_op` unification for closed-core ops.
fn format_operator(node: &ExpressionNode, fmt: Fmt, parent_prec: i32) -> String {
    // Closed-core structural / array-query ops (and `integral`) render from
    // their non-`args` fields and are never parenthesized by precedence.
    if let Some(s) = format_structural_op(node, fmt) {
        return s;
    }

    let op = node.op.as_str();
    let args = node.args.as_slice();
    let wrt = &node.wrt;
    let op_prec = get_precedence(op);
    let needs_parens = op_prec > 0 && op_prec <= parent_prec;
    // Renders an argument at precedence 0 (used inside delimited contexts).
    let r0 = |arg: &Expr| render_at(arg, fmt, 0);

    // `\frac{...}{...}` groups its OWN operands visually, so the numerator and
    // denominator render at precedence 0 — but the fraction still takes
    // parentheses from its PARENT when precedence demands them, exactly as the
    // reference printer does (`(\frac{b}{c})^{d}`). Returning early here without
    // consulting `needs_parens` silently dropped them.
    if fmt == Fmt::Latex && op == "/" && args.len() == 2 {
        let frac = format!("\\frac{{{}}}{{{}}}", r0(&args[0]), r0(&args[1]));
        return if needs_parens {
            format!("({frac})")
        } else {
            frac
        };
    }

    let result = match op {
        "+" => {
            if let Some(s) = sum_as_difference(args, op_prec, fmt) {
                s
            } else if args.len() >= 2 {
                infix_chain(op, op_prec, args, " + ", fmt)
            } else {
                call_form("+", args, r0)
            }
        }
        "-" => {
            let minus = pick(fmt, "−", "-", "-");
            if args.len() == 1 {
                // A unary-minus operand renders at the ADDITIVE level, so a sum
                // or difference keeps its parentheses (`−(a + b)`) while a
                // product or power does not (`−a · b`, `−a^2`) — exactly the
                // operands the parser re-absorbs. See
                // `UMINUS_OPERAND_PARENT_PREC`.
                let operand = render_at(&args[0], fmt, UMINUS_OPERAND_PARENT_PREC);
                if starts_with_literal_power(&args[0]) {
                    format!("{minus}({operand})")
                } else {
                    format!("{minus}{operand}")
                }
            } else if args.len() == 2 {
                // Left-associative and NON-associative on the right: the right
                // operand renders at `op_prec` — a child at the SAME precedence
                // keeps its parentheses (`a − (b − c)`), while one that binds
                // TIGHTER does not (`a − b · c`, not `a − (b · c)`). Rendering
                // it at `op_prec + 1` over-parenthesized every product /
                // quotient / power, diverging from the reference printer
                // (pretty-print.ts `needsParentheses`).
                format!(
                    "{} {minus} {}",
                    render_at(&args[0], fmt, op_prec - 1),
                    render_at(&args[1], fmt, op_prec)
                )
            } else {
                call_form(minus, args, r0)
            }
        }
        "*" => {
            if args.len() >= 2 {
                // A LaTeX product of already-typeset factors uses implicit
                // juxtaposition; the other backends use their explicit symbol.
                let sep: &str = match fmt {
                    Fmt::Unicode => "·",
                    Fmt::Ascii => " * ",
                    Fmt::Latex if latex_mul_juxtapose(args) => " ",
                    Fmt::Latex => " \\cdot ",
                };
                infix_chain(op, op_prec, args, sep, fmt)
            } else {
                call_form(pick(fmt, "·", "\\cdot", "*"), args, r0)
            }
        }
        "/" => {
            // Binary LaTeX `/` is handled by the `\frac` early return above.
            if args.len() == 2 {
                // The left operand of a left-associative `/` only needs parens
                // when it binds *strictly* looser (op_prec - 1), so `a·b/c`
                // stays unparenthesized while `(a + b)/c` does not.
                format!(
                    "{}{}{}",
                    render_at(&args[0], fmt, op_prec - 1),
                    pick(fmt, "/", "/", " / "),
                    render_at(&args[1], fmt, op_prec)
                )
            } else {
                call_form(pick(fmt, "÷", "\\div", "/"), args, r0)
            }
        }
        "^" => {
            if args.len() == 2 {
                match fmt {
                    // Integer exponents render as Unicode superscripts.
                    Fmt::Unicode => match integer_exponent(&args[1]) {
                        Some(n) => format!(
                            "{}{}",
                            render_at(&args[0], fmt, op_prec),
                            to_superscript_str(&n.to_string())
                        ),
                        None => format!(
                            "{}^{}",
                            render_at(&args[0], fmt, op_prec),
                            render_at(&args[1], fmt, op_prec)
                        ),
                    },
                    // The exponent sits inside `^{...}`, which groups visually,
                    // so it renders at precedence 0.
                    Fmt::Latex => {
                        format!("{}^{{{}}}", render_at(&args[0], fmt, op_prec), r0(&args[1]))
                    }
                    Fmt::Ascii => format!(
                        "{}^{}",
                        render_at(&args[0], fmt, op_prec),
                        render_at(&args[1], fmt, op_prec)
                    ),
                }
            } else {
                call_form("^", args, r0)
            }
        }
        "D" => {
            // Derivative operator; the operand is parenthesized when it is an
            // operator node (`∂(x + y)/∂t`, never `∂x + y/∂t`).
            //
            // An ABSENT `wrt` means `t` (esm-spec §4.2), so it renders exactly
            // as the explicit spelling does. Requiring `Some(_)` here printed
            // `D(x)` for a node Julia, Python and TypeScript all print as
            // `∂x/∂t` (EarthSciAST#407).
            let wrt_default = wrt
                .as_deref()
                .unwrap_or(crate::op_registry::STRUCTURAL_DERIVATIVE_WRT);
            if let [arg] = args {
                let wrt_var = wrt_default;
                match fmt {
                    Fmt::Unicode => format!(
                        "∂{}/∂{}",
                        wrap_if_op(arg, fmt),
                        format_chemical_subscripts(wrt_var)
                    ),
                    Fmt::Latex => format!(
                        "\\frac{{\\partial {}}}{{\\partial {}}}",
                        wrap_if_op(arg, fmt),
                        wrt_var
                    ),
                    // ASCII fraction form `D(operand)/Dt`.
                    Fmt::Ascii => format!("D({})/D{wrt_var}", r0(arg)),
                }
            } else {
                call_form("D", args, r0)
            }
        }
        ">" => comparison_or_call(op, op_prec, args, ">", ">", fmt),
        "<" => comparison_or_call(op, op_prec, args, "<", "<", fmt),
        ">=" => comparison_or_call(
            op,
            op_prec,
            args,
            pick(fmt, "≥", "\\geq", ">="),
            pick(fmt, ">=", "\\geq", ">="),
            fmt,
        ),
        "<=" => comparison_or_call(
            op,
            op_prec,
            args,
            pick(fmt, "≤", "\\leq", "<="),
            pick(fmt, "<=", "\\leq", "<="),
            fmt,
        ),
        "=" | "==" => comparison_or_call(
            op,
            op_prec,
            args,
            pick(fmt, "=", "=", "=="),
            pick(fmt, "=", "=", "=="),
            fmt,
        ),
        "!=" => comparison_or_call(
            op,
            op_prec,
            args,
            pick(fmt, "≠", "\\neq", "!="),
            pick(fmt, "!=", "\\neq", "!="),
            fmt,
        ),
        "and" => {
            if args.len() >= 2 {
                infix_chain(
                    op,
                    op_prec,
                    args,
                    pick(fmt, " ∧ ", " \\land ", " and "),
                    fmt,
                )
            } else {
                call_form(pick(fmt, "and", "\\land", "and"), args, r0)
            }
        }
        "or" => {
            if args.len() >= 2 {
                infix_chain(op, op_prec, args, pick(fmt, " ∨ ", " \\lor ", " or "), fmt)
            } else {
                call_form(pick(fmt, "or", "\\lor", "or"), args, r0)
            }
        }
        "not" => {
            if args.len() == 1 {
                // Parenthesize a complex operand (`¬(x == 0)`).
                let prefix = pick(fmt, "¬", "\\neg ", "not ");
                if matches!(&args[0], Expr::Operator(_)) {
                    format!("{prefix}({})", r0(&args[0]))
                } else {
                    format!("{prefix}{}", r0(&args[0]))
                }
            } else {
                call_form(pick(fmt, "not", "\\neg", "not"), args, r0)
            }
        }
        "exp" => match fmt {
            // LaTeX wraps a compound argument in `\left(…\right)`.
            Fmt::Latex => {
                if let [arg] = args {
                    if matches!(arg, Expr::Operator(_)) {
                        format!("\\exp\\left({}\\right)", r0(arg))
                    } else {
                        format!("\\exp({})", r0(arg))
                    }
                } else {
                    call_form("\\exp", args, r0)
                }
            }
            _ => call_form("exp", args, r0),
        },
        "ifelse" => match fmt {
            Fmt::Latex if args.len() == 3 => format!(
                "\\begin{{cases}} {} & \\text{{if }} {} \\\\ {} & \\text{{otherwise}} \\end{{cases}}",
                r0(&args[1]),
                r0(&args[0]),
                r0(&args[2])
            ),
            Fmt::Latex => call_form("\\mathrm{ifelse}", args, r0),
            _ => call_form("ifelse", args, r0),
        },
        "log" => {
            if args.len() == 1 {
                call_form(pick(fmt, "ln", "\\ln", "log"), args, r0)
            } else {
                call_form(pick(fmt, "log", "\\log", "log"), args, r0)
            }
        }
        "log10" => {
            let sym = if args.len() == 1 {
                pick(fmt, "log₁₀", "\\log_{10}", "log10")
            } else {
                pick(fmt, "log10", "\\log_{10}", "log10")
            };
            call_form(sym, args, r0)
        }
        "sqrt" => match fmt {
            Fmt::Unicode => {
                if let [arg] = args {
                    // Parenthesize a compound radicand for clarity.
                    if matches!(arg, Expr::Operator(_)) {
                        format!("√({})", r0(arg))
                    } else {
                        format!("√{}", r0(arg))
                    }
                } else {
                    call_form("sqrt", args, r0)
                }
            }
            Fmt::Latex => format!(
                "\\sqrt{{{}}}",
                args.iter().map(&r0).collect::<Vec<_>>().join(", ")
            ),
            Fmt::Ascii => call_form("sqrt", args, r0),
        },
        "asin" => {
            let sym = if args.len() == 1 {
                pick(fmt, "arcsin", "\\arcsin", "asin")
            } else {
                pick(fmt, "asin", "\\arcsin", "asin")
            };
            call_form(sym, args, r0)
        }
        "acos" => {
            let sym = if args.len() == 1 {
                pick(fmt, "arccos", "\\arccos", "acos")
            } else {
                pick(fmt, "acos", "\\arccos", "acos")
            };
            call_form(sym, args, r0)
        }
        "atan" => {
            let sym = if args.len() == 1 {
                pick(fmt, "arctan", "\\arctan", "atan")
            } else {
                pick(fmt, "atan", "\\arctan", "atan")
            };
            call_form(sym, args, r0)
        }
        "abs" => match fmt {
            Fmt::Unicode => {
                if args.len() == 1 {
                    format!("|{}|", r0(&args[0]))
                } else {
                    call_form("abs", args, r0)
                }
            }
            Fmt::Latex => format!("|{}|", args.iter().map(&r0).collect::<Vec<_>>().join(", ")),
            Fmt::Ascii => call_form("abs", args, r0),
        },
        "sign" => call_form(pick(fmt, "sgn", "\\mathrm{sgn}", "sign"), args, r0),
        "floor" => match fmt {
            Fmt::Unicode => {
                if args.len() == 1 {
                    format!("⌊{}⌋", r0(&args[0]))
                } else {
                    call_form("floor", args, r0)
                }
            }
            Fmt::Latex => format!(
                "\\lfloor {} \\rfloor",
                args.iter().map(&r0).collect::<Vec<_>>().join(", ")
            ),
            Fmt::Ascii => call_form("floor", args, r0),
        },
        "ceil" => match fmt {
            Fmt::Unicode => {
                if args.len() == 1 {
                    format!("⌈{}⌉", r0(&args[0]))
                } else {
                    call_form("ceil", args, r0)
                }
            }
            Fmt::Latex => format!(
                "\\lceil {} \\rceil",
                args.iter().map(&r0).collect::<Vec<_>>().join(", ")
            ),
            Fmt::Ascii => call_form("ceil", args, r0),
        },
        "asinh" => {
            let sym = if args.len() == 1 {
                pick(fmt, "sinh⁻¹", "\\sinh^{-1}", "asinh")
            } else {
                pick(fmt, "asinh", "\\sinh^{-1}", "asinh")
            };
            call_form(sym, args, r0)
        }
        "acosh" => {
            let sym = if args.len() == 1 {
                pick(fmt, "cosh⁻¹", "\\cosh^{-1}", "acosh")
            } else {
                pick(fmt, "acosh", "\\cosh^{-1}", "acosh")
            };
            call_form(sym, args, r0)
        }
        "atanh" => {
            let sym = if args.len() == 1 {
                pick(fmt, "tanh⁻¹", "\\tanh^{-1}", "atanh")
            } else {
                pick(fmt, "atanh", "\\tanh^{-1}", "atanh")
            };
            call_form(sym, args, r0)
        }
        "min" => call_form(pick(fmt, "min", "\\min", "min"), args, r0),
        "max" => call_form(pick(fmt, "max", "\\max", "max"), args, r0),
        "atan2" => call_form(pick(fmt, "atan2", "\\mathrm{atan2}", "atan2"), args, r0),
        "sin" | "cos" | "tan" | "sinh" | "cosh" | "tanh" => {
            // LaTeX prefixes a backslash (`\sin`); the others use the bare name.
            let latex = format!("\\{op}");
            call_form(
                if fmt == Fmt::Latex {
                    latex.as_str()
                } else {
                    op
                },
                args,
                r0,
            )
        }
        // `Pre` renders as a call form, matching the cross-language contract.
        "Pre" => call_form(pick(fmt, "Pre", "\\mathrm{Pre}", "Pre"), args, r0),
        // Generic fallback: open-tier sugar (grad/div/laplacian) and any
        // unknown user op. LaTeX wraps in `\mathrm{…}`, escaping underscores.
        _ => {
            let latex = format!("\\mathrm{{{}}}", latex_name(op));
            call_form(
                if fmt == Fmt::Latex {
                    latex.as_str()
                } else {
                    op
                },
                args,
                r0,
            )
        }
    };

    if needs_parens {
        format!("({result})")
    } else {
        result
    }
}

/// The domain the three text renderers accept: expressions AND containers.
///
/// API_SPEC.md §8 item 18 requires [`to_unicode`] / [`to_latex`] /
/// [`to_ascii`] to accept the full domain in every binding — this binding
/// accepted [`Expr`] only. The domain mirrors Python's
/// `Expr | Equation | Model | ReactionSystem | EsmFile`.
///
/// Container renderings are the esm-spec §6.3 SUMMARIES and are
/// format-independent, exactly as Python's `_format_*_summary` helpers are
/// (they take a `format_type` and ignore it). Only the expression and
/// equation renderings differ per format.
pub trait TextRenderable {
    /// Unicode mathematical notation.
    fn render_unicode(&self) -> String;
    /// LaTeX notation.
    fn render_latex(&self) -> String;
    /// Plain-ASCII notation.
    fn render_ascii(&self) -> String;
}

impl TextRenderable for Expr {
    fn render_unicode(&self) -> String {
        self.to_unicode()
    }
    fn render_latex(&self) -> String {
        to_latex_prec(self, 0)
    }
    fn render_ascii(&self) -> String {
        to_ascii_prec(self, 0)
    }
}

impl TextRenderable for Equation {
    fn render_unicode(&self) -> String {
        format!(
            "{} = {}",
            self.lhs.render_unicode(),
            self.rhs.render_unicode()
        )
    }
    fn render_latex(&self) -> String {
        format!("{} = {}", self.lhs.render_latex(), self.rhs.render_latex())
    }
    fn render_ascii(&self) -> String {
        format!("{} = {}", self.lhs.render_ascii(), self.rhs.render_ascii())
    }
}

/// Container summaries: the same §6.3 summary in all three formats, which is
/// what the peer bindings do (their summary helpers accept a format and never
/// branch on it). Rendered by the type's own `Display`, so the text is the one
/// already pinned by `tests/display/model_summary.json`.
macro_rules! summary_renderable {
    ($t:ty) => {
        impl TextRenderable for $t {
            fn render_unicode(&self) -> String {
                self.to_string()
            }
            fn render_latex(&self) -> String {
                self.to_string()
            }
            fn render_ascii(&self) -> String {
                self.to_string()
            }
        }
    };
}

summary_renderable!(Model);
summary_renderable!(ReactionSystem);
summary_renderable!(EsmFile);

/// Render `target` as Unicode mathematical notation.
///
/// Accepts the full display domain (API_SPEC.md §8 item 18): an [`Expr`], an
/// [`Equation`], or a [`Model`] / [`ReactionSystem`] / [`EsmFile`] summary.
pub fn to_unicode<T: TextRenderable + ?Sized>(target: &T) -> String {
    target.render_unicode()
}

/// Render `target` as LaTeX. See [`to_unicode`] for the accepted domain.
pub fn to_latex<T: TextRenderable + ?Sized>(target: &T) -> String {
    target.render_latex()
}

/// LaTeX rendering with the parent operator's precedence threaded through.
///
/// The LaTeX printer previously ignored precedence entirely, so `(a+b)*c`
/// rendered as the mathematically wrong `a + b \cdot c`; it now applies the
/// same parenthesization rule as the reference Unicode printer.
fn to_latex_prec(expr: &Expr, parent_prec: i32) -> String {
    match expr {
        Expr::Integer(n) => format_number_latex(*n as f64),
        Expr::Number(n) => format_number_latex(*n),
        Expr::Variable(name) => {
            nonfinite_string(name, Fmt::Latex).unwrap_or_else(|| format_variable_latex(name))
        }
        Expr::Operator(node) => format_operator(node, Fmt::Latex, parent_prec),
    }
}

fn format_variable_latex(name: &str) -> String {
    // A name that is already LaTeX passes through verbatim.
    if is_preformatted_latex(name) {
        return name.to_string();
    }
    // A variable that is exactly a Greek letter renders as its LaTeX command.
    if let Some(cmd) = greek_to_latex(name) {
        return cmd;
    }
    format_chemical_latex(name)
}

/// True when a variable NAME is already hand-written LaTeX and must be emitted
/// verbatim (mirrors `isPreformattedLatex` in pretty-print.ts): a `\mathrm{…}`
/// atom, a bare command like `\theta` (a backslash with no brace), or a subscript
/// atom like `k_{NO_O3}` (braces without a leading `\command{…}`). A braced
/// `\command{…}` such as `\mathbf{v}` is NOT pre-formatted — it still takes the
/// generic `\mathrm{…}` wrap.
fn is_preformatted_latex(v: &str) -> bool {
    if v.starts_with("\\mathrm{") {
        return true;
    }
    if v.contains('\\') {
        return !v.contains('{');
    }
    v.contains('{') || v.contains('}')
}

/// True when `variable` (underscores ignored) is PURELY a chemical formula: at
/// least one element symbol and no non-element letters. Uses the same greedy
/// 2-char-before-1-char element tokenizer as `scanElements` in pretty-print.ts.
fn has_element_pattern(variable: &str) -> bool {
    let chars: Vec<char> = variable.chars().filter(|&c| c != '_').collect();
    let mut has_element = false;
    let mut i = 0;
    while i < chars.len() {
        let mut sym_len = 0;
        if i + 1 < chars.len() {
            let two: String = [chars[i], chars[i + 1]].iter().collect();
            if ELEMENTS.contains(&two.as_str()) {
                sym_len = 2;
            }
        }
        if sym_len == 0 && ELEMENTS.contains(&chars[i].to_string().as_str()) {
            sym_len = 1;
        }
        if sym_len > 0 {
            has_element = true;
            i += sym_len;
            while i < chars.len() && chars[i].is_ascii_digit() {
                i += 1;
            }
        } else {
            // A non-element letter means this is not a pure chemical formula.
            if chars[i].is_ascii_alphabetic() {
                return false;
            }
            i += 1;
        }
    }
    has_element
}

/// Convert every digit run in a formula to a LaTeX subscript (`H2O` → `H_2O`,
/// `C12` → `C_{12}`), WITHOUT the `\mathrm{}` wrapper.
fn latex_chemical_inner(formula: &str) -> String {
    let chars: Vec<char> = formula.chars().collect();
    let mut out = String::new();
    let mut i = 0;
    while i < chars.len() {
        if chars[i].is_ascii_digit() {
            let mut digits = String::new();
            while i < chars.len() && chars[i].is_ascii_digit() {
                digits.push(chars[i]);
                i += 1;
            }
            if digits.chars().count() == 1 {
                out.push('_');
                out.push_str(&digits);
            } else {
                out.push_str(&format!("_{{{digits}}}"));
            }
        } else {
            out.push(chars[i]);
            i += 1;
        }
    }
    out
}

/// Peel one leading `\mathrm{` and one trailing `}` (independently).
fn strip_outer_mathrm(s: &str) -> String {
    let inner = s.strip_prefix("\\mathrm{").unwrap_or(s);
    inner.strip_suffix('}').unwrap_or(inner).to_string()
}

/// Split a variable into a non-element prefix + element-bearing suffix
/// (`jNO2` → `("j","NO2")`, `k_NO_O3` → `("k","NO_O3")`), or `None`.
fn get_chemical_suffix(variable: &str) -> Option<(String, String)> {
    if variable.contains('_') {
        let parts: Vec<&str> = variable.split('_').collect();
        if parts.len() == 2 && has_element_pattern(parts[1]) && !has_element_pattern(parts[0]) {
            return Some((parts[0].to_string(), parts[1].to_string()));
        }
        if parts.len() == 3 {
            let suffix = parts[1..].join("_");
            if has_element_pattern(&suffix) && !has_element_pattern(parts[0]) {
                return Some((parts[0].to_string(), suffix));
            }
        }
    }
    let chars: Vec<char> = variable.chars().collect();
    for i in 1..chars.len() {
        let prefix: String = chars[..i].iter().collect();
        let suffix: String = chars[i..].iter().collect();
        if has_element_pattern(&suffix) && !has_element_pattern(&prefix) {
            return Some((prefix, suffix));
        }
    }
    None
}

/// Inner content of an element-bearing suffix embedded in a larger variable's
/// subscript (the text INSIDE the enclosing `\mathrm{...}`).
fn format_chemical_suffix_inner(variable: &str) -> String {
    if get_chemical_suffix(variable).is_some() {
        return strip_outer_mathrm(&format_chemical_latex(variable));
    }
    if ELEMENTS.contains(&variable) && !variable.chars().any(|c| c.is_ascii_digit()) {
        return variable.to_string();
    }
    latex_chemical_inner(variable)
}

/// Match a single-letter-then-digits variable (`x1`, `T298`) → `(letter, digits)`.
fn single_letter_digits(name: &str) -> Option<(String, String)> {
    let chars: Vec<char> = name.chars().collect();
    if chars.len() >= 2
        && chars[0].is_ascii_alphabetic()
        && chars[1..].iter().all(|c| c.is_ascii_digit())
    {
        return Some((chars[0].to_string(), chars[1..].iter().collect()));
    }
    None
}

fn is_chemical_formula(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }

    // Check if starts with an element symbol (uppercase letter)
    let first_char = s.chars().next().unwrap();
    if !first_char.is_ascii_uppercase() {
        return false;
    }

    // Try to find a matching element symbol at the start
    if s.len() >= 2 {
        let two_letter = &s[..2];
        if ELEMENTS.contains(&two_letter) {
            return true;
        }
    }

    let one_letter = &s[..1];
    ELEMENTS.contains(&one_letter)
}

/// LaTeX chemical/variable subscript formatting (mirrors `formatChemicalLatex`
/// in pretty-print.ts). Greek and raw-LaTeX names are handled by the caller.
fn format_chemical_latex(variable: &str) -> String {
    // A trailing ionic charge is a superscript, not a subscript
    // (`Ca2+` → `Ca^{2+}`, `SO4-2` → `\mathrm{SO_4}^{2-}`).
    let (charge_body, charge) = split_charge(variable);
    if !charge.is_empty() {
        return format!("{}^{{{charge}}}", format_chemical_latex(charge_body));
    }

    // Mixed variable: non-element prefix + element-bearing suffix.
    if let Some((prefix, suffix)) = get_chemical_suffix(variable) {
        let prefix_multi = prefix.chars().count() > 1;
        if suffix.contains('_') {
            let segments: Vec<&str> = suffix.split('_').collect();
            // Split into per-segment subscripts when the first segment is a
            // complete formula (ends in a digit) or the prefix is multi-char;
            // otherwise the whole suffix stays one `\mathrm{...}` block.
            let should_split = segments[0]
                .chars()
                .last()
                .is_some_and(|c| c.is_ascii_digit())
                || prefix_multi;
            if should_split {
                let mut result = if prefix_multi {
                    format!("\\mathrm{{{prefix}}}")
                } else {
                    prefix.clone()
                };
                for seg in &segments {
                    if has_element_pattern(seg) {
                        result.push_str(&format!("_{{\\mathrm{{{}}}}}", latex_chemical_inner(seg)));
                    } else {
                        result.push_str(&format!("_\\mathrm{{{seg}}}"));
                    }
                }
                return result;
            }
        }
        let inner = format_chemical_suffix_inner(&suffix);
        let formatted_prefix = if prefix_multi {
            format!("\\mathrm{{{prefix}}}")
        } else {
            prefix
        };
        return format!("{formatted_prefix}_{{\\mathrm{{{inner}}}}}");
    }

    if has_element_pattern(variable) {
        // A bare element symbol without digits (e.g. "C", "Ca") is a variable.
        if ELEMENTS.contains(&variable) && !variable.chars().any(|c| c.is_ascii_digit()) {
            return variable.to_string();
        }
        // Pure chemical formula: digit runs → subscripts, wrapped in `\mathrm`.
        return format!("\\mathrm{{{}}}", latex_chemical_inner(variable));
    }

    // Regular (non-chemical) variable.
    if let Some((letter, digits)) = single_letter_digits(variable) {
        return if digits.chars().count() == 1 {
            format!("{letter}_{digits}")
        } else {
            format!("{letter}_{{{digits}}}")
        };
    }
    if variable.chars().count() == 1 {
        return variable.to_string();
    }
    if variable.contains('_') {
        let parts: Vec<&str> = variable.split('_').collect();
        if parts.iter().any(|p| has_element_pattern(p)) {
            let base = parts[0];
            let mut result =
                if base.chars().count() == 1 && base.chars().all(|c| c.is_ascii_alphabetic()) {
                    base.to_string()
                } else if has_element_pattern(base) {
                    format_chemical_latex(base)
                } else {
                    format!("\\mathrm{{{base}}}")
                };
            for part in &parts[1..] {
                if has_element_pattern(part) {
                    result.push_str(&format!("_{{\\mathrm{{{}}}}}", latex_chemical_inner(part)));
                } else {
                    result.push_str(&format!("_\\mathrm{{{part}}}"));
                }
            }
            return result;
        }
        // No chemical segment → plain multi-word variable, underscores escaped.
        return format!("\\mathrm{{{}}}", variable.replace('_', "\\_"));
    }
    // A symbol with no lowercase letters (e.g. "RT", "-E") is a math variable,
    // not a descriptive name — leave it italic instead of wrapping in `\mathrm`.
    if !variable.chars().any(|c| c.is_ascii_lowercase()) {
        return variable.to_string();
    }
    format!("\\mathrm{{{variable}}}")
}

/// Render `target` as plain ASCII. See [`to_unicode`] for the accepted domain.
pub fn to_ascii<T: TextRenderable + ?Sized>(target: &T) -> String {
    target.render_ascii()
}

/// ASCII rendering with the parent operator's precedence threaded through.
///
/// The ASCII printer previously ignored precedence entirely, so `(a+b)*c`
/// rendered as the mathematically wrong `a + b * c`; it now applies the
/// same parenthesization rule as the reference Unicode printer.
fn to_ascii_prec(expr: &Expr, parent_prec: i32) -> String {
    match expr {
        Expr::Integer(n) => format_number_ascii(*n as f64),
        Expr::Number(n) => format_number_ascii(*n),
        // ASCII spells Greek characters out by name (e.g. `θ` → `theta`).
        Expr::Variable(name) => {
            nonfinite_string(name, Fmt::Ascii).unwrap_or_else(|| greek_to_ascii(name))
        }
        Expr::Operator(node) => format_operator(node, Fmt::Ascii, parent_prec),
    }
}

impl fmt::Display for Model {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = self.name.as_deref().unwrap_or("Unnamed");
        let param_count = self
            .variables
            .iter()
            .filter(|(_, v)| matches!(v.var_type, VariableType::Parameter))
            .count();
        let eq_count = self.equations.len();

        writeln!(
            f,
            "    {} ({} parameters, {} equation{})",
            name,
            param_count,
            eq_count,
            if eq_count == 1 { "" } else { "s" }
        )?;

        // Display equations
        for eq in &self.equations {
            writeln!(f, "      {} = {}", eq.lhs, eq.rhs)?;
        }

        Ok(())
    }
}

impl fmt::Display for ReactionSystem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let species_count = self.species.len();

        // Count parameters
        let param_count = self.parameters.len();

        let reaction_count = self.reactions.len();

        writeln!(
            f,
            "    ReactionSystem ({} species, {} parameters, {} reaction{})",
            species_count,
            param_count,
            reaction_count,
            if reaction_count == 1 { "" } else { "s" }
        )?;

        // Display reactions
        for (i, reaction) in self.reactions.iter().enumerate() {
            let default_name = format!("R{}", i + 1);
            let reaction_name = reaction
                .id
                .as_deref()
                .or(reaction.name.as_deref())
                .unwrap_or(&default_name);

            // Format substrates
            let substrates = reaction
                .substrates
                .iter()
                .flatten()
                .map(|s| {
                    if s.coefficient == 1.0 {
                        format_chemical_subscripts(&s.species)
                    } else {
                        format!(
                            "{}·{}",
                            format_number_unicode(s.coefficient),
                            format_chemical_subscripts(&s.species)
                        )
                    }
                })
                .collect::<Vec<_>>()
                .join(" + ");

            // Format products
            let products = reaction
                .products
                .iter()
                .flatten()
                .map(|p| {
                    if p.coefficient == 1.0 {
                        format_chemical_subscripts(&p.species)
                    } else {
                        format!(
                            "{}·{}",
                            format_number_unicode(p.coefficient),
                            format_chemical_subscripts(&p.species)
                        )
                    }
                })
                .collect::<Vec<_>>()
                .join(" + ");

            writeln!(
                f,
                "      {}: {} → {}    rate: {}",
                reaction_name, substrates, products, reaction.rate
            )?;
        }

        Ok(())
    }
}

impl fmt::Display for EsmFile {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = self.metadata.name.as_deref().unwrap_or("Unnamed");
        let description = self.metadata.description.as_deref().unwrap_or("");
        let authors = self
            .metadata
            .authors
            .as_ref()
            .map(|a| a.join(", "))
            .unwrap_or_else(|| "Unknown".to_string());

        writeln!(f, "ESM v{}: {}", self.esm, name)?;
        if !description.is_empty() {
            writeln!(f, "  \"{description}\"")?;
        }
        writeln!(f, "  Authors: {authors}")?;
        writeln!(f)?;

        // Display reaction systems
        if let Some(ref reaction_systems) = self.reaction_systems
            && !reaction_systems.is_empty()
        {
            writeln!(f, "  Reaction Systems:")?;
            for system in reaction_systems.values() {
                write!(f, "{system}")?;
                writeln!(f)?;
            }
        }

        // Display models
        if let Some(ref models) = self.models
            && !models.is_empty()
        {
            writeln!(f, "  Models:")?;
            for model in models.values() {
                write!(f, "{model}")?;
                writeln!(f)?;
            }
        }

        // Display data sources. From esm 1.0.0 a source exposes no variables of
        // its own — the consuming parameter names it — so what is worth showing
        // is where it reads from and whether it is time-varying.
        if let Some(ref data_sources) = self.data_sources
            && !data_sources.is_empty()
        {
            writeln!(f, "  Data Sources:")?;
            for (name, source) in data_sources {
                let kind = match source.kind {
                    crate::DataSourceKind::Grid => "grid",
                    crate::DataSourceKind::Points => "points",
                    crate::DataSourceKind::Static => "static",
                };
                writeln!(
                    f,
                    "    {}: [{}] {}{}",
                    name,
                    kind,
                    source.source.url_template,
                    if source.temporal.is_some() {
                        " (temporal)"
                    } else {
                        ""
                    },
                )?;
            }
            writeln!(f)?;
        }

        // Display coupling
        if let Some(ref coupling) = self.coupling
            && !coupling.is_empty()
        {
            writeln!(f, "  Coupling:")?;
            for (i, entry) in coupling.iter().enumerate() {
                match entry {
                    CouplingEntry::OperatorCompose { systems, .. } => {
                        if systems.len() >= 2 {
                            writeln!(
                                f,
                                "    {}. operator_compose: {} + {}",
                                i + 1,
                                systems[0],
                                systems[1]
                            )?;
                        }
                    }
                    CouplingEntry::VariableMap { from, to, .. } => {
                        writeln!(f, "    {}. variable_map: {} → {}", i + 1, from, to)?;
                    }
                    _ => {
                        writeln!(f, "    {}. {:?}", i + 1, entry)?;
                    }
                }
            }
            writeln!(f)?;
        }

        // Display domain information (EsmFile.domain is the single shared domain)
        if let Some(ref domain) = self.domain {
            write!(f, "  Domain: ")?;

            let mut domain_parts = Vec::new();
            if domain.temporal.is_some() {
                domain_parts.push("temporal".to_string());
            }

            if domain_parts.is_empty() {
                writeln!(f, "[Domain information]")?;
            } else {
                writeln!(f, "{}", domain_parts.join(", "))?;
            }
        }

        Ok(())
    }
}

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

    #[test]
    fn test_chemical_subscripts() {
        assert_eq!(format_chemical_subscripts("O3"), "O₃");
        assert_eq!(format_chemical_subscripts("NO2"), "NO₂");
        assert_eq!(format_chemical_subscripts("CH4"), "CH₄");
        assert_eq!(format_chemical_subscripts("C2H6"), "C₂H₆");
        assert_eq!(format_chemical_subscripts("H2O2"), "H₂O₂");
    }

    #[test]
    fn test_number_formatting_unicode() {
        assert_eq!(format_number_unicode(42.0), "42");
        assert_eq!(format_number_unicode(3.15), "3.15");
        // Mantissa is full-precision (no forced trailing zero): 1.8, not 1.80.
        assert_eq!(format_number_unicode(1.8e-12), "1.8×10⁻¹²");
        assert_eq!(format_number_unicode(2.46e19), "2.46×10¹⁹");

        // Zero prints as a bare "0" (never "0.0") in every backend.
        assert_eq!(format_number_unicode(0.0), "0");
        assert_eq!(format_number_unicode(-0.0), "0");

        // Other integers display without a decimal point; Unicode uses U+2212.
        assert_eq!(format_number_unicode(1.0), "1");
        assert_eq!(format_number_unicode(-1.0), "−1");
    }

    #[test]
    fn test_zero_formatting_all_formats() {
        // Zero renders as a bare "0" in every backend (RENDERING_CONTRACT.md).
        let zero_expr = Expr::Number(0.0);
        let one_expr = Expr::Number(1.0);
        let neg_zero_expr = Expr::Number(-0.0);

        // Unicode formatting
        assert_eq!(to_unicode(&zero_expr), "0");
        assert_eq!(to_unicode(&neg_zero_expr), "0");
        assert_eq!(to_unicode(&one_expr), "1");

        // LaTeX formatting
        assert_eq!(to_latex(&zero_expr), "0");
        assert_eq!(to_latex(&neg_zero_expr), "0");
        assert_eq!(to_latex(&one_expr), "1");

        // ASCII formatting
        assert_eq!(to_ascii(&zero_expr), "0");
        assert_eq!(to_ascii(&neg_zero_expr), "0");
        assert_eq!(to_ascii(&one_expr), "1");
    }

    /// The unified Greek table and its three derived views, pinned: the 24
    /// letters in canonical order, name↔char round-trips, the 11 capitals
    /// with a distinct LaTeX command, and the deliberate asymmetries — the
    /// Latin-looking capitals carry no command, and uppercase Unicode chars
    /// pass through every backend unchanged.
    #[test]
    fn the_greek_table_drives_all_three_views() {
        let names: Vec<&str> = GREEK_TABLE.iter().map(|&(n, _, _)| n).collect();
        assert_eq!(
            names,
            [
                "alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta", "theta", "iota",
                "kappa", "lambda", "mu", "nu", "xi", "omicron", "pi", "rho", "sigma", "tau",
                "upsilon", "phi", "chi", "psi", "omega",
            ]
        );
        for &(n, c, _) in GREEK_TABLE {
            assert_eq!(greek_name_to_char(n), Some(c), "name → char for {n}");
            assert_eq!(greek_char_to_name(c), Some(n), "char → name for {c}");
            assert_eq!(greek_to_latex(n).unwrap(), format!("\\{n}"));
            assert_eq!(greek_to_latex(&c.to_string()).unwrap(), format!("\\{n}"));
        }
        let capitals: Vec<&str> = GREEK_TABLE
            .iter()
            .filter(|&&(_, _, cap)| cap)
            .map(|&(n, _, _)| n)
            .collect();
        assert_eq!(
            capitals,
            [
                "gamma", "delta", "theta", "lambda", "xi", "pi", "sigma", "upsilon", "phi", "psi",
                "omega",
            ]
        );
        assert_eq!(greek_to_latex("Theta").as_deref(), Some("\\Theta"));
        assert_eq!(greek_to_latex("Omega").as_deref(), Some("\\Omega"));
        // A capital that looks like a Latin letter has no LaTeX command, an
        // uppercase Unicode char is recognized nowhere, and neither the
        // all-caps nor a non-Greek spelling is a Greek name.
        for miss in ["Alpha", "Δ", "GAMMA", "Deltas", "x"] {
            assert_eq!(greek_to_latex(miss), None, "{miss} must not match");
        }
        assert_eq!(greek_to_ascii("θ_Δx"), "theta_Δx");
        assert_eq!(format_chemical_subscripts("Delta"), "Delta");
    }

    #[test]
    fn test_scientific_all_backends() {
        // Full-precision mantissa, U+2212 minus / `\times` / `e`, no `+` sign.
        assert_eq!(format_number_unicode(1.8e-12), "1.8×10⁻¹²");
        assert_eq!(format_number_unicode(2.46e19), "2.46×10¹⁹");
        assert_eq!(format_number_latex(1.8e-12), "1.8 \\times 10^{-12}");
        assert_eq!(format_number_ascii(1.8e-12), "1.8e-12");
        // Non-finite values render as symbols, never stringified.
        assert_eq!(format_number_unicode(f64::INFINITY), "∞");
        assert_eq!(format_number_latex(f64::NEG_INFINITY), "-\\infty");
        assert_eq!(format_number_ascii(f64::NAN), "NaN");
    }

    #[test]
    fn test_expr_display() {
        let expr = Expr::Variable("O3".to_string());
        assert_eq!(format!("{expr}"), "O₃");

        let expr = Expr::Number(1.8e-12);
        assert_eq!(format!("{expr}"), "1.8×10⁻¹²");
    }

    #[test]
    fn test_operator_precedence() {
        let add = Expr::operator(ExpressionNode {
            op: "+".to_string(),
            args: vec![
                Expr::operator(ExpressionNode {
                    op: "*".to_string(),
                    args: vec![
                        Expr::Variable("a".to_string()),
                        Expr::Variable("b".to_string()),
                    ],
                    wrt: None,
                    dim: None,
                    ..Default::default()
                }),
                Expr::Variable("c".to_string()),
            ],
            wrt: None,
            dim: None,
            ..Default::default()
        });
        assert_eq!(format!("{add}"), "a·b + c");

        let mul = Expr::operator(ExpressionNode {
            op: "*".to_string(),
            args: vec![
                Expr::operator(ExpressionNode {
                    op: "+".to_string(),
                    args: vec![
                        Expr::Variable("a".to_string()),
                        Expr::Variable("b".to_string()),
                    ],
                    wrt: None,
                    dim: None,
                    ..Default::default()
                }),
                Expr::Variable("c".to_string()),
            ],
            wrt: None,
            dim: None,
            ..Default::default()
        });
        assert_eq!(format!("{mul}"), "(a + b)·c");
    }

    #[test]
    fn test_model_summary_display() {
        // Create minimal ESM file for testing display
        let metadata = Metadata {
            name: Some("TestModel".to_string()),
            description: Some("Test description".to_string()),
            authors: Some(vec!["Test Author".to_string()]),
            ..Default::default()
        };

        // Create a simple reaction system
        let mut parameters = IndexMap::new();
        parameters.insert(
            "k1".to_string(),
            Parameter {
                default: Some(1.8e-12),
                units: Some("cm3/molec/s".to_string()),
                description: Some("Rate constant".to_string()),
                ..Default::default()
            },
        );

        let reactions = vec![Reaction {
            id: Some("R1".to_string()),
            name: Some("R1".to_string()),
            substrates: Some(vec![StoichiometricEntry {
                species: "A".to_string(),
                coefficient: 1.0,
            }]),
            products: Some(vec![StoichiometricEntry {
                species: "B".to_string(),
                coefficient: 1.0,
            }]),
            rate: Expr::Variable("k1".to_string()),
            reference: None,
        }];

        let mut species = IndexMap::new();
        species.insert(
            "A".to_string(),
            Species {
                default: Some(1e-9),
                units: Some("molec/cm3".to_string()),
                description: None,
                constant: None,
                ..Default::default()
            },
        );
        species.insert(
            "B".to_string(),
            Species {
                default: Some(0.0),
                units: Some("molec/cm3".to_string()),
                description: None,
                constant: None,
                ..Default::default()
            },
        );

        let reaction_system = ReactionSystem {
            species,
            parameters,
            reactions,
            ..Default::default()
        };

        let mut reaction_systems = IndexMap::new();
        reaction_systems.insert("TestReactions".to_string(), reaction_system);

        // Create ESM file
        let esm_file = EsmFile {
            esm: "0.1.0".to_string(),
            metadata,
            reaction_systems: Some(reaction_systems),
            ..Default::default()
        };

        // Test the display output
        let output = format!("{esm_file}");

        // Check key components are present in the expected format
        assert!(output.contains("ESM v0.1.0: TestModel"));
        assert!(output.contains("\"Test description\""));
        assert!(output.contains("Authors: Test Author"));
        assert!(output.contains("Reaction Systems:"));
        assert!(output.contains("(2 species, 1 parameters, 1 reaction)"));
        assert!(output.contains("R1: A → B    rate: k1"));

        // API_SPEC.md §8 item 18: the three renderers accept CONTAINERS, not
        // just expressions. A container renders its §6.3 summary, the same
        // text in all three formats (the peer bindings' summary helpers take
        // a format and ignore it).
        assert_eq!(to_unicode(&esm_file), output);
        assert_eq!(to_latex(&esm_file), output);
        assert_eq!(to_ascii(&esm_file), output);

        let rs = &esm_file.reaction_systems.as_ref().unwrap()["TestReactions"];
        assert_eq!(to_unicode(rs), rs.to_string());
        assert_eq!(to_ascii(rs), rs.to_string());
    }

    /// §8 item 18: an `Equation` renders as `lhs = rhs` in each format, the
    /// shape Python and TypeScript already produce.
    #[test]
    fn equations_render_in_all_three_formats() {
        let eq = Equation {
            lhs: Expr::Variable("alpha".to_string()),
            rhs: Expr::operator(ExpressionNode {
                op: "*".to_string(),
                args: vec![Expr::Variable("beta".to_string()), Expr::Number(2.0)],
                ..Default::default()
            }),
            ..Default::default()
        };
        assert_eq!(to_unicode(&eq), "α = β·2");
        assert_eq!(to_ascii(&eq), "alpha = beta * 2");
        assert_eq!(to_latex(&eq), "\\alpha = \\beta \\cdot 2");
    }

    #[test]
    fn test_pre_operator_formatting() {
        use crate::types::*;

        // Test Unicode formatting for Pre operator with x⁻ notation
        let pre_expr = Expr::operator(ExpressionNode {
            op: "Pre".to_string(),
            args: vec![Expr::Variable("x".to_string())],
            wrt: None,
            dim: None,
            ..Default::default()
        });

        // `Pre` renders as a call form (cross-language rendering contract).
        assert_eq!(to_unicode(&pre_expr), "Pre(x)");
        assert_eq!(to_latex(&pre_expr), "\\mathrm{Pre}(x)");
        assert_eq!(to_ascii(&pre_expr), "Pre(x)");

        // Test with complex expression as argument
        let complex_pre = Expr::operator(ExpressionNode {
            op: "Pre".to_string(),
            args: vec![Expr::operator(ExpressionNode {
                op: "+".to_string(),
                args: vec![
                    Expr::Variable("a".to_string()),
                    Expr::Variable("b".to_string()),
                ],
                wrt: None,
                dim: None,
                ..Default::default()
            })],
            wrt: None,
            dim: None,
            ..Default::default()
        });

        assert_eq!(to_unicode(&complex_pre), "Pre(a + b)");
        assert_eq!(to_latex(&complex_pre), "\\mathrm{Pre}(a + b)");
        assert_eq!(to_ascii(&complex_pre), "Pre(a + b)");

        // Test with multiple arguments (should fall back to Pre(...) format)
        let multi_arg_pre = Expr::operator(ExpressionNode {
            op: "Pre".to_string(),
            args: vec![
                Expr::Variable("x".to_string()),
                Expr::Variable("y".to_string()),
            ],
            wrt: None,
            dim: None,
            ..Default::default()
        });

        assert_eq!(to_unicode(&multi_arg_pre), "Pre(x, y)");
        assert_eq!(to_latex(&multi_arg_pre), "\\mathrm{Pre}(x, y)");
        assert_eq!(to_ascii(&multi_arg_pre), "Pre(x, y)");
    }

    /// Build an operator node for the precedence tests below.
    fn op_node(op: &str, args: Vec<Expr>) -> Expr {
        Expr::operator(ExpressionNode {
            op: op.to_string(),
            args,
            wrt: None,
            dim: None,
            ..Default::default()
        })
    }

    fn var(name: &str) -> Expr {
        Expr::Variable(name.to_string())
    }

    #[test]
    fn test_precedence_parens_all_printers() {
        // Regression test: the LaTeX and ASCII printers previously ignored
        // precedence, so (a + b) * c rendered as the mathematically wrong
        // `a + b \cdot c` / `a + b * c`.
        let mul = op_node("*", vec![op_node("+", vec![var("a"), var("b")]), var("c")]);
        assert_eq!(to_unicode(&mul), "(a + b)·c");
        assert_eq!(to_latex(&mul), "(a + b) \\cdot c");
        assert_eq!(to_ascii(&mul), "(a + b) * c");

        // No spurious parentheses when precedence already binds correctly.
        let add = op_node("+", vec![var("a"), op_node("*", vec![var("b"), var("c")])]);
        assert_eq!(to_unicode(&add), "a + b·c");
        assert_eq!(to_latex(&add), "a + b \\cdot c");
        assert_eq!(to_ascii(&add), "a + b * c");

        // Left-associative subtraction: the right operand keeps parentheses.
        let sub = op_node("-", vec![var("a"), op_node("-", vec![var("b"), var("c")])]);
        assert_eq!(to_unicode(&sub), "a − (b − c)");
        assert_eq!(to_latex(&sub), "a - (b - c)");
        assert_eq!(to_ascii(&sub), "a - (b - c)");

        // Powers parenthesize a lower-precedence base in every backend
        // (`{a + b}^{2}` would typeset as `a + b²` in LaTeX).
        let pow = op_node(
            "^",
            vec![op_node("+", vec![var("a"), var("b")]), Expr::Number(2.0)],
        );
        assert_eq!(to_unicode(&pow), "(a + b)²");
        assert_eq!(to_latex(&pow), "(a + b)^{2}");
        assert_eq!(to_ascii(&pow), "(a + b)^2");

        // A same-precedence RIGHT operand keeps its parentheses unless it is
        // the same associative op: `a * b / c` reads back as `(a * b) / c`, so
        // `a * (b / c)` must print its parentheses. LaTeX `\frac` is
        // self-delimiting and stays bare (RENDERING_CONTRACT.md).
        let frac_mul = op_node("*", vec![var("a"), op_node("/", vec![var("b"), var("c")])]);
        assert_eq!(to_unicode(&frac_mul), "a·(b/c)");
        assert_eq!(to_latex(&frac_mul), "a \\cdot \\frac{b}{c}");
        assert_eq!(to_ascii(&frac_mul), "a * (b / c)");

        // Comparisons and `and`/`or` bind looser than arithmetic, so as
        // arithmetic operands they are parenthesized.
        let ind = op_node(
            "*",
            vec![
                op_node("<=", vec![var("a"), var("b")]),
                op_node("<", vec![var("c"), var("d")]),
            ],
        );
        assert_eq!(to_ascii(&ind), "(a <= b) * (c < d)");
        let lt_plus = op_node("+", vec![op_node("<", vec![var("a"), var("b")]), var("c")]);
        assert_eq!(to_ascii(&lt_plus), "(a < b) + c");
        let and_mul = op_node(
            "*",
            vec![op_node("and", vec![var("a"), var("b")]), var("c")],
        );
        assert_eq!(to_ascii(&and_mul), "(a and b) * c");
        // ...but a comparison inside `and` needs none, and an n-ary `and`
        // renders infix.
        let and3 = op_node(
            "and",
            vec![
                op_node("<=", vec![var("a"), var("b")]),
                op_node("<", vec![var("b"), var("c")]),
                op_node("<", vec![var("c"), var("d")]),
            ],
        );
        assert_eq!(to_ascii(&and3), "a <= b and b < c and c < d");
        assert_eq!(to_unicode(&and3), "a ≤ b ∧ b < c ∧ c < d");
        let eq_lt = op_node("==", vec![var("a"), op_node("<", vec![var("b"), var("c")])]);
        assert_eq!(to_ascii(&eq_lt), "a == (b < c)");
        // A unary-minus operand that is a comparison is wrapped exactly once.
        let neg_lt = op_node("-", vec![op_node("<", vec![var("a"), var("b")])]);
        assert_eq!(to_ascii(&neg_lt), "-(a < b)");
        let neg_sum = op_node("-", vec![op_node("+", vec![var("a"), var("b")])]);
        assert_eq!(to_ascii(&neg_sum), "-(a + b)");
        let neg_prod = op_node("-", vec![op_node("*", vec![var("a"), var("b")])]);
        assert_eq!(to_ascii(&neg_prod), "-a * b");
    }

    #[test]
    fn test_scientific_notation_unified_across_printers() {
        // All three printers share one float-formatting core. LaTeX and
        // ASCII previously collapsed large integral floats (e.g. 2.46e19)
        // into long digit strings instead of scientific notation.
        let large = Expr::Number(2.46e19);
        assert_eq!(to_unicode(&large), "2.46×10¹⁹");
        assert_eq!(to_latex(&large), "2.46 \\times 10^{19}");
        assert_eq!(to_ascii(&large), "2.46e19");

        let small = Expr::Number(1.8e-12);
        assert_eq!(to_unicode(&small), "1.8×10⁻¹²");
        assert_eq!(to_latex(&small), "1.8 \\times 10^{-12}");
        assert_eq!(to_ascii(&small), "1.8e-12");

        // A large-magnitude *integer* leaf uses scientific notation too.
        let big_int = Expr::Integer(15000);
        assert_eq!(to_unicode(&big_int), "1.5×10⁴");
        assert_eq!(to_ascii(&big_int), "1.5e4");
    }

    /// Byte-for-byte guard for the unified `format_operator` path: exercises
    /// every per-`fmt` symbol-table entry and every shape-divergent leaf
    /// (LaTeX `\frac`/`\begin{cases}`/`\exp`/juxtaposition, Unicode
    /// superscripts and `⌊⌋`/`⌈⌉`/`|·|`/`√`, the three `D` forms, and the
    /// infix-vs-call symbol split for `≥`/`≤`/`≠`) across all three backends.
    #[test]
    fn test_operator_matrix_all_backends() {
        fn opn(op: &str, args: Vec<Expr>) -> Expr {
            Expr::operator(ExpressionNode {
                op: op.to_string(),
                args,
                ..Default::default()
            })
        }
        fn dop(wrt: &str, arg: Expr) -> Expr {
            Expr::operator(ExpressionNode {
                op: "D".to_string(),
                args: vec![arg],
                wrt: Some(wrt.to_string()),
                ..Default::default()
            })
        }
        let a = || var("a");
        let b = || var("b");
        let c = || var("c");
        let ab = || opn("+", vec![a(), b()]);
        // (node, unicode, latex, ascii) — expected values captured from the
        // three pre-unification printers, so any drift fails loudly.
        let chk = |e: Expr, u: &str, l: &str, s: &str| {
            assert_eq!(to_unicode(&e), u, "unicode");
            assert_eq!(to_latex(&e), l, "latex");
            assert_eq!(to_ascii(&e), s, "ascii");
        };

        // multiplication (·/juxtaposition/*) and precedence parens
        chk(opn("*", vec![a(), b()]), "a·b", r"a \cdot b", "a * b");
        chk(
            opn("*", vec![ab(), c()]),
            "(a + b)·c",
            r"(a + b) \cdot c",
            "(a + b) * c",
        );
        chk(
            opn("*", vec![var("\\mathrm{O_3}"), var("\\mathrm{N_2}")]),
            r"\mathrm{O_3}·\mathrm{N_2}",
            r"\mathrm{O_3} \mathrm{N_2}",
            r"\mathrm{O_3} * \mathrm{N_2}",
        );
        // division (`\frac` is the LaTeX shape-divergent leaf)
        chk(opn("/", vec![a(), b()]), "a/b", r"\frac{a}{b}", "a / b");
        chk(
            opn("/", vec![ab(), c()]),
            "(a + b)/c",
            r"\frac{a + b}{c}",
            "(a + b) / c",
        );
        // A same-precedence `/` RIGHT operand of `*` keeps its parentheses in
        // the inline backends (`a * b / c` reads back as `(a * b) / c`);
        // LaTeX `\frac` is self-delimiting and stays bare.
        chk(
            opn("*", vec![a(), opn("/", vec![b(), c()])]),
            "a·(b/c)",
            r"a \cdot \frac{b}{c}",
            "a * (b / c)",
        );
        // powers: LaTeX braces, Unicode integer superscripts
        chk(opn("^", vec![a(), b()]), "a^b", r"a^{b}", "a^b");
        chk(opn("^", vec![a(), Expr::Integer(2)]), "a²", r"a^{2}", "a^2");
        chk(
            opn("^", vec![a(), Expr::Number(2.0)]),
            "a²",
            r"a^{2}",
            "a^2",
        );
        chk(
            opn("^", vec![a(), Expr::Number(2.5)]),
            "a^2.5",
            r"a^{2.5}",
            "a^2.5",
        );
        chk(
            opn("^", vec![ab(), Expr::Integer(2)]),
            "(a + b)²",
            r"(a + b)^{2}",
            "(a + b)^2",
        );
        chk(
            opn("^", vec![a(), Expr::Integer(-3)]),
            "a⁻³",
            r"a^{-3}",
            "a^-3",
        );
        // subtraction: Unicode U+2212 minus, right-operand parens, `+(-b)` sugar
        chk(opn("-", vec![a()]), "−a", "-a", "-a");
        chk(
            opn("-", vec![a(), opn("-", vec![b(), c()])]),
            "a − (b − c)",
            "a - (b - c)",
            "a - (b - c)",
        );
        chk(
            opn("+", vec![a(), opn("-", vec![b()])]),
            "a − b",
            "a - b",
            "a - b",
        );
        // derivative: three divergent forms + call fallback
        chk(
            dop("t", a()),
            "∂a/∂t",
            r"\frac{\partial a}{\partial t}",
            "D(a)/Dt",
        );
        chk(
            dop("t", ab()),
            "∂(a + b)/∂t",
            r"\frac{\partial (a + b)}{\partial t}",
            "D(a + b)/Dt",
        );
        // A `D` with NO `wrt` is the structural time derivative in its short
        // spelling (esm-spec §4.2: an absent `wrt` MEANS `t`), so it renders
        // exactly as `dop("t", …)` above does. This row used to expect the bare
        // call form `D(a)` — what Rust and Go printed while Julia, Python and
        // TypeScript printed `∂a/∂t` (issue #407).
        chk(
            opn("D", vec![a()]),
            "∂a/∂t",
            r"\frac{\partial a}{\partial t}",
            "D(a)/Dt",
        );
        // Arity, not a missing `wrt`, is what falls back to the call form.
        chk(opn("D", vec![a(), b()]), "D(a, b)", "D(a, b)", "D(a, b)");
        // comparisons: infix symbol AND the call-form symbol (they diverge)
        chk(opn(">", vec![a(), b()]), "a > b", "a > b", "a > b");
        chk(opn(">=", vec![a(), b()]), "a ≥ b", r"a \geq b", "a >= b");
        chk(opn(">=", vec![a()]), ">=(a)", r"\geq(a)", ">=(a)");
        chk(opn("<=", vec![a(), b()]), "a ≤ b", r"a \leq b", "a <= b");
        chk(opn("=", vec![a(), b()]), "a = b", "a = b", "a == b");
        chk(opn("==", vec![a()]), "=(a)", "=(a)", "==(a)");
        chk(opn("!=", vec![a(), b()]), "a ≠ b", r"a \neq b", "a != b");
        chk(opn("!=", vec![a()]), "!=(a)", r"\neq(a)", "!=(a)");
        // boolean ops
        chk(opn("and", vec![a(), b()]), "a ∧ b", r"a \land b", "a and b");
        chk(opn("or", vec![a(), b()]), "a ∨ b", r"a \lor b", "a or b");
        chk(opn("not", vec![a()]), "¬a", r"\neg a", "not a");
        chk(
            opn("not", vec![opn("==", vec![a(), b()])]),
            "¬(a = b)",
            r"\neg (a = b)",
            "not (a == b)",
        );
        chk(
            opn("not", vec![a(), b()]),
            "not(a, b)",
            r"\neg(a, b)",
            "not(a, b)",
        );
        // elementary functions: unicode name vs LaTeX command vs bare ASCII
        chk(opn("log", vec![a()]), "ln(a)", r"\ln(a)", "log(a)");
        chk(
            opn("log", vec![a(), b()]),
            "log(a, b)",
            r"\log(a, b)",
            "log(a, b)",
        );
        chk(
            opn("log10", vec![a()]),
            "log₁₀(a)",
            r"\log_{10}(a)",
            "log10(a)",
        );
        chk(
            opn("log10", vec![a(), b()]),
            "log10(a, b)",
            r"\log_{10}(a, b)",
            "log10(a, b)",
        );
        chk(opn("sqrt", vec![a()]), "√a", r"\sqrt{a}", "sqrt(a)");
        chk(
            opn("sqrt", vec![a(), b()]),
            "sqrt(a, b)",
            r"\sqrt{a, b}",
            "sqrt(a, b)",
        );
        chk(
            opn("sqrt", vec![ab()]),
            "√(a + b)",
            r"\sqrt{a + b}",
            "sqrt(a + b)",
        );
        chk(
            opn("asin", vec![a()]),
            "arcsin(a)",
            r"\arcsin(a)",
            "asin(a)",
        );
        chk(opn("abs", vec![a()]), "|a|", "|a|", "abs(a)");
        chk(
            opn("abs", vec![a(), b()]),
            "abs(a, b)",
            "|a, b|",
            "abs(a, b)",
        );
        chk(
            opn("sign", vec![a()]),
            "sgn(a)",
            r"\mathrm{sgn}(a)",
            "sign(a)",
        );
        chk(
            opn("floor", vec![a()]),
            "⌊a⌋",
            r"\lfloor a \rfloor",
            "floor(a)",
        );
        chk(
            opn("floor", vec![a(), b()]),
            "floor(a, b)",
            r"\lfloor a, b \rfloor",
            "floor(a, b)",
        );
        chk(opn("ceil", vec![a()]), "⌈a⌉", r"\lceil a \rceil", "ceil(a)");
        chk(
            opn("asinh", vec![a()]),
            "sinh⁻¹(a)",
            r"\sinh^{-1}(a)",
            "asinh(a)",
        );
        chk(opn("exp", vec![a()]), "exp(a)", r"\exp(a)", "exp(a)");
        chk(
            opn("exp", vec![ab()]),
            "exp(a + b)",
            r"\exp\left(a + b\right)",
            "exp(a + b)",
        );
        chk(opn("min", vec![a()]), "min(a)", r"\min(a)", "min(a)");
        chk(
            opn("atan2", vec![a()]),
            "atan2(a)",
            r"\mathrm{atan2}(a)",
            "atan2(a)",
        );
        chk(opn("sin", vec![a()]), "sin(a)", r"\sin(a)", "sin(a)");
        chk(
            opn("Pre", vec![a()]),
            "Pre(a)",
            r"\mathrm{Pre}(a)",
            "Pre(a)",
        );
        // ifelse: LaTeX `\begin{cases}` leaf vs the call fallback everywhere else
        chk(
            opn("ifelse", vec![a(), b(), c()]),
            "ifelse(a, b, c)",
            r"\begin{cases} b & \text{if } a \\ c & \text{otherwise} \end{cases}",
            "ifelse(a, b, c)",
        );
        chk(
            opn("ifelse", vec![a(), b()]),
            "ifelse(a, b)",
            r"\mathrm{ifelse}(a, b)",
            "ifelse(a, b)",
        );
        // unknown ops: generic fallback + LaTeX underscore escaping
        chk(
            opn("grad", vec![a()]),
            "grad(a)",
            r"\mathrm{grad}(a)",
            "grad(a)",
        );
        chk(
            opn("my_op", vec![a(), b()]),
            "my_op(a, b)",
            r"\mathrm{my\_op}(a, b)",
            "my_op(a, b)",
        );
    }
}