package reason

  1. Overview
  2. Docs
Reason: Syntax & Toolchain for OCaml

Install

dune-project
 Dependency

Authors

Maintainers

Sources

reason-3.17.0.tbz
sha256=82c8819ce9fd215b7e7e2c6501e638e7a904ebe13ab5a1d8eac2679d8cf8a5eb
sha512=64f525d795501602d92174a35232c0791a0d77322c48397497c9ac3c1e0b76b86a89c3c50e057e52a8727d37b579720a0d48fb9fab3835193bb3a4668ded79cd

doc/src/reason/reason_pprint_ast.ml.html

Source file reason_pprint_ast.ml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
(* Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed
   under the MIT license found in the * LICENSE file in the root directory of
   this source tree. * Forked from OCaml, which is provided under the license
   below: * * Xavier Leroy, projet Cristal, INRIA Rocquencourt * * Copyright ©
   1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Inria * *
   Permission is hereby granted, free of charge, to the Licensee obtaining a *
   copy of this software and associated documentation files (the "Software"), *
   to deal in the Software without restriction, including without limitation *
   the rights to use, copy, modify, merge, publish, distribute, sublicense *
   under any license of the Licensee's choice, and/or sell copies of the *
   Software, subject to the following conditions: * * 1. Redistributions of
   source code must retain the above copyright notice * and the following
   disclaimer. * 2. Redistributions in binary form must reproduce the above
   copyright * notice, the following disclaimer in the documentation and/or
   other * materials provided with the distribution. * 3. All advertising
   materials mentioning features or use of the Software * must display the
   following acknowledgement: This product includes all or * parts of the Caml
   system developed by Inria and its contributors. * 4. Other than specified in
   clause 3, neither the name of Inria nor the * names of its contributors may
   be used to endorse or promote products * derived from the Software without
   specific prior written permission. * * Disclaimer * * This software is
   provided by Inria and contributors “as is” and any express * or implied
   warranties, including, but not limited to, the implied * warranties of
   merchantability and fitness for a particular purpose are * disclaimed. in no
   event shall Inria or its contributors be liable for any * direct, indirect,
   incidental, special, exemplary, or consequential damages * (including, but
   not limited to, procurement of substitute goods or * services; loss of use,
   data, or profits; or business interruption) however * caused and on any
   theory of liability, whether in contract, strict * liability, or tort
   (including negligence or otherwise) arising in any way * out of the use of
   this software, even if advised of the possibility of such * damage. * *)

(* TODO more fine-grained precedence pretty-printing *)

module Easy_format = Reason_easy_format
open Ppxlib
open Easy_format
module Comment = Reason_comment
module Layout = Reason_layout
module WhitespaceRegion = Layout.WhitespaceRegion
module Range = Reason_location.Range

let source_map = Layout.source_map

exception NotPossible of string

let commaTrail =
  Layout.SepFinal (",", Reason_syntax_util.TrailingCommaMarker.string)

let commaSep = Layout.Sep ","

type ruleInfoData =
  { reducePrecedence : precedence
  ; shiftPrecedence : precedence
  }

and ruleCategory =
  (* Printing will be parsed with very high precedence, so not much need to
     worry about ensuring it will reduce correctly. In short, you can put
     `FunctionApplication` content anywhere around an infix identifier without
     wrapping in parens. For example `myFunc x y z` or `if x {y} else {z}` The
     layout is kept in list form only to allow for elegant wrapping rules to
     take into consideration the *number* of high precedence parsed items. *)
  | FunctionApplication of Layout.t list
  (* Care should be taken to ensure the rule that caused it to be parsed will
     reduce again on the printed output - context should carefully consider
     wrapping in parens according to the ruleInfoData. *)
  | SpecificInfixPrecedence of ruleInfoData * resolvedRule
  (* Not safe to include anywhere between infix operators without wrapping in
     parens. This describes expressions like `fun x => x` which doesn't fit into
     our simplistic algorithm for printing function applications separated by
     infix.

     It might be possible to include these in between infix, but there are
     tricky rules to determining when these must be guarded by parens (it
     depends highly on context that is hard to reason about). It's so nuanced
     that it's easier just to always wrap them in parens. *)
  | PotentiallyLowPrecedence of Layout.t
  (* Simple means it is clearly one token (such as (anything) or [anything] or
     identifier *)
  | Simple of Layout.t

(* Represents a ruleCategory where the precedence has been resolved. * The
   precedence of a ruleCategory gets resolved in `ensureExpression` or *
   `ensureContainingRule`. The result is either a plain Layout.t (where * parens
   probably have been applied) or an InfixTree containing the operator and * a
   left & right resolvedRule. The latter indicates that the precedence has been
   resolved, * but the actual formatting is deferred to a later stadium. * Think
   `let x = foo |> f |> z |>`, which requires a certain formatting style when *
   things break over multiple lines. *)
and resolvedRule =
  | LayoutNode of Layout.t
  | InfixTree of string * resolvedRule * resolvedRule

and associativity =
  | Right
  | Nonassoc
  | Left

and precedenceEntryType =
  | TokenPrecedence
  | CustomPrecedence

and precedence =
  | Token of string
  | Custom of string

(* Describes the "fixity" of a token, and stores its *printed* representation
   should it be rendered as infix/prefix (This rendering may be different than
   how it is stored in the AST). *)
and tokenFixity =
  (* Such as !simple_expr and ~!simple_expr. These function applications are
     considered *almost* "simple" because they may be allowed anywhere a simple
     expression is accepted, except for when on the left hand side of a
     dot/send. *)
  | AlmostSimplePrefix of string
  | UnaryPlusPrefix of string
  | UnaryMinusPrefix of string
  | UnaryNotPrefix of string
  | UnaryPostfix of string
  | Infix of string
  | Letop of string
  | Andop of string
  | Normal

(* Type which represents a resolvedRule's InfixTree flattened *)
type infixChain =
  | InfixToken of string
  | Layout of Layout.t

(* Helpers for dealing with extension nodes (%expr) *)

let expression_extension_sugar x =
  if x.pexp_attributes != []
  then None
  else
    match x.pexp_desc with
    | Pexp_extension (name, PStr [ { pstr_desc = Pstr_eval (expr, []); _ } ])
      when name.txt <> "mel.obj" ->
      Some (name, expr)
    | _ -> None

let expression_immediate_extension_sugar x =
  match expression_extension_sugar x with
  | None -> None, x
  | Some (name, expr) ->
    (match expr.pexp_desc with
    | Pexp_for _ | Pexp_while _ | Pexp_ifthenelse _
    | Pexp_function (_, _, Pfunction_cases _)
    | Pexp_newtype _ | Pexp_try _ | Pexp_match _ ->
      Some name, expr
    | _ -> None, x)

let expression_not_immediate_extension_sugar x =
  match expression_immediate_extension_sugar x with
  | Some _, _ -> None
  | None, _ -> expression_extension_sugar x

let add_extension_sugar keyword = function
  | None -> keyword
  | Some str -> keyword ^ "%" ^ str.txt

let override = function Override -> "!" | Fresh -> ""

let add_open_extension_sugar ~override:open_override extension =
  let base = "open" in
  match extension, open_override with
  | extension, Fresh -> add_extension_sugar base extension
  | None, Override -> base ^ override open_override
  | Some _, Override ->
    (* need to add a space between `!` and `%foo` otherwise it can't be parsed
       back *)
    add_extension_sugar (base ^ override open_override ^ " ") extension

let string_equal : string -> string -> bool = ( = )

let string_loc_equal : string Asttypes.loc -> string Asttypes.loc -> bool =
 fun l1 l2 -> l1.txt = l2.txt

let longident_same l1 l2 =
  let rec equal l1 l2 =
    match l1, l2 with
    | Lident l1, Lident l2 -> string_equal l1 l2
    | Ldot (path1, l1), Ldot (path2, l2) ->
      equal path1 path2 && string_equal l1 l2
    | Lapply (l11, l12), Lapply (l21, l22) -> equal l11 l21 && equal l12 l22
    | _ -> false
  in
  equal l1.txt l2.txt

(* A variant of List.for_all2 that returns false instead of failing on lists of
   different size *)
let for_all2' pred l1 l2 = try List.for_all2 pred l1 l2 with _ -> false

(* Checks to see if two types are the same modulo the process of varification
   which turns abstract types into type variables of the same name. For example,
   [same_ast_modulo_varification] would consider (a => b) and ('a => 'b) to have
   the same ast. This is useful in recovering syntactic sugar for explicit
   polymorphic types with locally abstract types.

   Does not compare attributes, or extensions intentionally.

   TODO: This has one more issue: We need to compare only accepting t1's type
   variables, to be considered compatible with t2's type constructors - not the
   other way around. *)
let same_ast_modulo_varification_and_extensions t1 t2 =
  let rec loop t1 t2 =
    match t1.ptyp_desc, t2.ptyp_desc with
    (* Importantly, cover the case where type constructors (of the form [a]) are
       converted to type vars of the form ['a]. *)
    | Ptyp_constr ({ txt = Lident s1; _ }, []), Ptyp_var s2 ->
      string_equal s1 s2
    (* Now cover the case where type variables (of the form ['a]) are converted
       to type constructors of the form [a]. *)
    | Ptyp_var s1, Ptyp_constr ({ txt = Lident s2; _ }, []) ->
      string_equal s1 s2
    (* Now cover the typical case *)
    | Ptyp_constr (longident1, lst1), Ptyp_constr (longident2, lst2) ->
      longident_same longident1 longident2 && for_all2' loop lst1 lst2
    | Ptyp_any, Ptyp_any -> true
    | Ptyp_var x1, Ptyp_var x2 -> string_equal x1 x2
    | ( Ptyp_arrow (label1, core_type1, core_type1')
      , Ptyp_arrow (label2, core_type2, core_type2') ) ->
      (match label1, label2 with
        | Nolabel, Nolabel -> true
        | Labelled s1, Labelled s2 -> string_equal s1 s2
        | Optional s1, Optional s2 -> string_equal s1 s2
        | _ -> false)
      && loop core_type1 core_type2
      && loop core_type1' core_type2'
    | Ptyp_tuple lst1, Ptyp_tuple lst2 -> for_all2' loop lst1 lst2
    | Ptyp_object (lst1, o1), Ptyp_object (lst2, o2) ->
      let tester t1 t2 =
        match t1.pof_desc, t2.pof_desc with
        | Otag (s1, t1), Otag (s2, t2) ->
          string_equal s1.txt s2.txt && loop t1 t2
        | Oinherit t1, Oinherit t2 -> loop t1 t2
        | _ -> false
      in
      for_all2' tester lst1 lst2 && o1 = o2
    | Ptyp_class (longident1, lst1), Ptyp_class (longident2, lst2) ->
      longident_same longident1 longident2 && for_all2' loop lst1 lst2
    | Ptyp_alias (core_type1, string1), Ptyp_alias (core_type2, string2) ->
      loop core_type1 core_type2 && string_equal string1.txt string2.txt
    | ( Ptyp_variant (row_field_list1, flag1, lbl_lst_option1)
      , Ptyp_variant (row_field_list2, flag2, lbl_lst_option2) ) ->
      for_all2' rowFieldEqual row_field_list1 row_field_list2
      && flag1 = flag2
      && lbl_lst_option1 = lbl_lst_option2
    | Ptyp_poly (string_lst1, core_type1), Ptyp_poly (string_lst2, core_type2)
      ->
      for_all2' string_loc_equal string_lst1 string_lst2
      && loop core_type1 core_type2
    | Ptyp_package (longident1, lst1), Ptyp_package (longident2, lst2) ->
      longident_same longident1 longident2
      && for_all2' testPackageType lst1 lst2
    | Ptyp_extension (s1, _), Ptyp_extension (s2, _) ->
      string_equal s1.txt s2.txt
    | _ -> false
  and testPackageType (lblLongIdent1, ct1) (lblLongIdent2, ct2) =
    longident_same lblLongIdent1 lblLongIdent2 && loop ct1 ct2
  and rowFieldEqual f1 f2 =
    match f1.prf_desc, f2.prf_desc with
    | Rtag (label1, flag1, lst1), Rtag (label2, flag2, lst2) ->
      string_equal label1.txt label2.txt
      && flag1 = flag2
      && for_all2' loop lst1 lst2
    | Rinherit t1, Rinherit t2 -> loop t1 t2
    | _ -> false
  in
  loop t1 t2

let expandLocation pos ~expand:(startPos, endPos) =
  { pos with
    loc_start =
      { pos.loc_start with
        Lexing.pos_cnum = pos.loc_start.Lexing.pos_cnum + startPos
      }
  ; loc_end =
      { pos.loc_end with
        Lexing.pos_cnum = pos.loc_end.Lexing.pos_cnum + endPos
      }
  }

(* Computes the location of the attribute with the lowest line number * that
   isn't ghost. Useful to determine the start location of an item * in the
   parsetree that has attributes. * If there are no valid attributes, defaults
   to the passed location. * 1| [@attr] --> notice how the "start" is determined
   * 2| let f = ... by the attr on line 1, not the lnum of the `let` *)
let rec firstAttrLoc loc = function
  | ({ attr_name = attrLoc; _ } : Parsetree.attribute) :: attrs ->
    if
      attrLoc.loc.loc_start.pos_lnum < loc.loc_start.pos_lnum
      && not attrLoc.loc.loc_ghost
    then firstAttrLoc attrLoc.loc attrs
    else firstAttrLoc loc attrs
  | [] -> loc

let extractLocationFromValBindList expr vbs =
  let rec extract loc = function
    | x :: xs ->
      let { pvb_expr; _ } = x in
      let loc = { loc with loc_end = pvb_expr.pexp_loc.loc_end } in
      extract loc xs
    | [] -> loc
  in
  let loc =
    match vbs with
    | x :: xs ->
      let { pvb_pat; pvb_expr; _ } = x in
      let loc = { pvb_pat.ppat_loc with loc_end = pvb_expr.pexp_loc.loc_end } in
      extract loc xs
    | [] -> expr.pexp_loc
  in
  { loc with loc_start = expr.pexp_loc.loc_start }

let extractLocValBinding { pvb_pat; pvb_expr; pvb_attributes; _ } =
  let estimatedLoc = firstAttrLoc pvb_pat.ppat_loc pvb_attributes in
  { estimatedLoc with loc_end = pvb_expr.pexp_loc.loc_end }

let extractLocBindingOp { pbop_pat; pbop_exp; _ } =
  let estimatedLoc = firstAttrLoc pbop_pat.ppat_loc [] in
  { estimatedLoc with loc_end = pbop_exp.pexp_loc.loc_end }

let extractLocModuleBinding { pmb_expr; pmb_attributes; _ } =
  let estimatedLoc = firstAttrLoc pmb_expr.pmod_loc pmb_attributes in
  { estimatedLoc with loc_end = pmb_expr.pmod_loc.loc_end }

let extractLocModDecl { pmd_type; pmd_attributes; _ } =
  let estimatedLoc = firstAttrLoc pmd_type.pmty_loc pmd_attributes in
  { estimatedLoc with loc_end = pmd_type.pmty_loc.loc_end }

let rec sequentialIfBlocks x =
  match x with
  | Some { pexp_desc = Pexp_ifthenelse (e1, e2, els); _ } ->
    let nestedIfs, finalExpression = sequentialIfBlocks els in
    (e1, e2) :: nestedIfs, finalExpression
  | Some e -> [], Some e
  | None -> [], None

(* TODO: IDE integration beginning with Vim: * * - Create recovering version of
   parser that creates regions of "unknown" * content in between let sequence
   bindings (anything between semicolons, * really). * - Use Easy_format's
   "style" features to tag each known node. * - Turn those style annotations
   into editor highlight commands. * - Editors have a set of keys that retrigger
   the parsing/rehighlighting * process (typically newline/semi/close-brace). *
   \- On every parsing/rehighlighting, this pretty printer can be used to *
   determine the highlighting of recovered regions, and the editor plugin can *
   relegate highlighting of malformed regions to the editor which mostly does *
   so based on token patterns. * *)

(* @avoidSingleTokenWrapping
 *
 *  +-----------------------------+
 *  |+------+                     |     Another label
 *  || let ( \                    |
 *  ||    a  | Label              |
 *  ||    o  |                    |     The thing to the right of any label must be a
 *  ||    p _+ label RHS          |     list in order for it to wrap correctly. Lists
 *  ||  ): /   v                  |     will wrap if they need to/can. NON-lists will
 *  |+--+ sixteenTuple = echoTuple|(    wrap (indented) even though they're no lists!
 *  +---/ 0,\---------------------+     To prevent a single item from wrapping, make
 *        0,                            an unbreakable list via ensureSingleTokenSticksToLabel.
 *        0
 *      );
 *  In general, the best approach for indenting
 *  let bindings is to keep building up labels from
 *  the "let", always ensuring things that you want
 *  to wrap will either be lists or guarded in
 *  [ensureSingleTokenSticksToLabel].
 *  If you must join several lists together (via =)
 *  (or colon), ensure that joining is done via
 *  [makeList] (which won't break), and that new
 *  list is always appended to the left
 *  hand side of the label. (So that the right hand
 *  side may always be the untouched list that you want
 *  to wrap with aligned closing).
 *  Always make sure rhs of the label are the
 *
 *  Creating nested labels will preserve the original
 *  indent location ("let" in this
 *  case) as long as that nesting is
 *  done on the left hand side of the labels.
 *
 *)

(*  Table 2.1. Precedence and associativity.
 *  Precedence from highest to lowest: From RWOC, modified to include !=
 *  ---------------------------------------
 *
 *  Operator prefix	Associativity
 *  !..., ?..., ~...	                              Prefix
 *  ., .(, .[	-
 *  function application, constructor, assert, lazy	Left associative
 *  -, -.                                           Prefix
 *  **..., lsl, lsr, asr                            Right associative
 *  *..., /..., %..., mod, land, lor, lxor          Left associative
 *  +..., -...                                      Left associative
 *  ::                                              Right associative
 *  @..., ^...                                      Right associative
 *
 *  !=                                              Left associative (INFIXOP0 listed first in lexer)
 *  =..., <..., >..., |..., &..., $...              Left associative (INFIXOP0)
 *  =, <, >                                         Left associative (IN SAME row as INFIXOP0 listed after)
 *
 *  &, &&                                           Right associative
 *  or, ||                                          Right associative
 *  ,                                               -
 *  :=, =                                         	Right associative
 *  if                                              -
 *  ;                                               Right associative
 *
 *
 * Note: It would be much better if &... and |... were in separate precedence
 * groups just as & and | are. This way, we could encourage custom infix
 * operators to use one of the two precedences and no one would be confused as
 * to precedence (leading &, | are intuitive). Two precedence classes for the
 * majority of infix operators is totally sufficient.
 *
 * TODO: Free up the (&) operator from pervasives so it can be reused for
 * something very common such as string concatenation or list appending.
 *
 * let x = tail & head;
 *)

(* "Almost Simple Prefix" function applications parse with the rule:

   `PREFIXOP simple_expr %prec below_DOT_AND_SHARP`, which in turn is almost
   considered a "simple expression" (it's acceptable anywhere a simple
   expression is except in a couple of edge cases.

   "Unary Prefix" function applications parse with the rule:

   `MINUS epxr %prec prec_unary_minus`, which in turn is considered an
   "expression" (not simple). All unary operators are mapped into an identifier
   beginning with "~".

   TODO: Migrate all "almost simple prefix" to "unsary prefix". When `!` becomes
   "not", then it will make more sense that !myFunc (arg) is parsed as !(myFunc
   arg) instead of (!myFunc) arg. *)
let almost_simple_prefix_symbols = [ '!'; '?'; '~' ]

(* Subset of prefix symbols that have special "unary precedence" *)
let unary_minus_prefix_symbols = [ "~-"; "~-." ]
let unary_plus_prefix_symbols = [ "~+"; "~+." ]

let infix_symbols =
  [ '='; '<'; '>'; '@'; '^'; '|'; '&'; '+'; '-'; '*'; '/'; '$'; '%'; '\\'; '#' ]

(* this should match "kwdopchar" from reason_declarative_lexer.mll *)
let special_infix_strings =
  [ "asr"; "land"; "lor"; "lsl"; "lsr"; "lxor"; "mod"; "or"; ":="; "!="; "!==" ]

let updateToken = "="
let sharpOpEqualToken = "#="
let pipeFirstToken = "->"
let requireIndentFor = [ updateToken; ":=" ]
let namedArgSym = "~"

let requireNoSpaceFor tok =
  tok = pipeFirstToken || (tok.[0] = '#' && tok <> "#=")

let funToken = "fun"

let getPrintableUnaryIdent s =
  if
    List.mem s unary_minus_prefix_symbols
    || List.mem s unary_plus_prefix_symbols
  then String.sub s 1 (String.length s - 1)
  else s

(* determines if the string is an infix string. checks backwards, first allowing
   a renaming postfix ("_102") which may have resulted from Pexp -> Texp -> Pexp
   translation, then checking if all the characters in the beginning of the
   string are valid infix characters. *)
let printedStringAndFixity = function
  | s when List.mem s special_infix_strings -> Infix s
  | "^" -> UnaryPostfix "^"
  | s when List.mem s.[0] infix_symbols -> Infix s
  (* Correctness under assumption that unary operators are stored in AST with
     leading "~" *)
  | s
    when List.mem s.[0] almost_simple_prefix_symbols
         && (not (List.mem s special_infix_strings))
         && not (s = "?") ->
    if
      (* What *kind* of prefix fixity? *)
      List.mem s unary_plus_prefix_symbols
    then UnaryPlusPrefix (getPrintableUnaryIdent s)
    else if List.mem s unary_minus_prefix_symbols
    then UnaryMinusPrefix (getPrintableUnaryIdent s)
    else if s = "!"
    then UnaryNotPrefix s
    else AlmostSimplePrefix s
  | s when Reason_syntax_util.is_letop s -> Letop s
  | s when Reason_syntax_util.is_andop s -> Andop s
  | _ -> Normal

(* Also, this doesn't account for != and !== being infixop!!! *)
let isSimplePrefixToken s =
  match printedStringAndFixity s with
  | AlmostSimplePrefix _ | UnaryPostfix "^" -> true
  | _ -> false

(* Convenient bank of information that represents the parser's precedence
   rankings. Each instance describes a precedence table entry. The function
   tests either a token string encountered by the parser, or (in the case of
   `CustomPrecedence`) the string name of a custom rule precedence declared
   using %prec *)
let rules =
  [ [ (TokenPrecedence, fun s -> Left, s = pipeFirstToken)
    ; ( TokenPrecedence
      , fun s -> Left, s.[0] = '#' && s <> sharpOpEqualToken && s <> "#" )
    ; (TokenPrecedence, fun s -> Left, s = ".")
    ; (CustomPrecedence, fun s -> Left, s = "prec_lbracket")
    ]
  ; [ (CustomPrecedence, fun s -> Nonassoc, s = "prec_functionAppl") ]
  ; [ (TokenPrecedence, fun s -> Right, isSimplePrefixToken s) ]
  ; [ (TokenPrecedence, fun s -> Left, s = sharpOpEqualToken) ]
  ; [ (CustomPrecedence, fun s -> Nonassoc, s = "prec_unary") ]
  ; (* Note the special case for "*\*", BARBAR, and LESSMINUS, AMPERSAND(s) *)
    [ (TokenPrecedence, fun s -> Right, s = "**")
    ; ( TokenPrecedence
      , fun s ->
          ( Right
          , String.length s > 1 && s.[0] == '*' && s.[1] == '\\' && s.[2] == '*'
          ) )
    ; (TokenPrecedence, fun s -> Right, s = "lsl")
    ; (TokenPrecedence, fun s -> Right, s = "lsr")
    ; (TokenPrecedence, fun s -> Right, s = "asr")
    ]
  ; [ ( TokenPrecedence
      , fun s -> Left, s.[0] == '*' && (String.length s == 1 || s != "*\\*") )
    ; (TokenPrecedence, fun s -> Left, s.[0] == '/')
    ; (TokenPrecedence, fun s -> Left, s.[0] == '%')
    ; (TokenPrecedence, fun s -> Left, s = "mod")
    ; (TokenPrecedence, fun s -> Left, s = "land")
    ; (TokenPrecedence, fun s -> Left, s = "lor")
    ; (TokenPrecedence, fun s -> Left, s = "lxor")
    ]
  ; [ (* Even though these use the same *tokens* as unary plus/minus at parse
         time, when unparsing infix -/+, the CustomPrecedence rule would be
         incorrect to use, and instead we need a rule that models what infix
         parsing would use - just the regular token precedence without a custom
         precedence. *)
      ( TokenPrecedence
      , fun s ->
          ( Left
          , if String.length s > 1 && s.[0] == '+' && s.[1] == '+'
            then
              (* Explicitly call this out as false because the other ++ case
                 below should have higher *lexing* priority. ++operator_chars*
                 is considered an entirely different token than
                 +(non_plus_operator_chars)* *)
              false
            else s.[0] == '+' ) )
    ; (TokenPrecedence, fun s -> Left, s.[0] == '-' && s <> pipeFirstToken)
    ; (TokenPrecedence, fun s -> Left, s = "!")
    ]
  ; [ (TokenPrecedence, fun s -> Right, s = "::") ]
  ; [ (TokenPrecedence, fun s -> Right, s.[0] == '@')
    ; (TokenPrecedence, fun s -> Right, s.[0] == '^')
    ; ( TokenPrecedence
      , fun s -> Right, String.length s > 1 && s.[0] == '+' && s.[1] == '+' )
    ]
  ; [ ( TokenPrecedence
      , fun s -> Left, s.[0] == '=' && (not (s = "=")) && not (s = "=>") )
    ; (TokenPrecedence, fun s -> Left, s.[0] == '<' && not (s = "<"))
    ; (TokenPrecedence, fun s -> Left, s.[0] == '>' && not (s = ">"))
    ; (TokenPrecedence, fun s -> Left, s = "!=")
    ; (* Not preset in the RWO table! *)
      (TokenPrecedence, fun s -> Left, s = "!==")
    ; (* Not preset in the RWO table! *)
      (TokenPrecedence, fun s -> Left, s = "==")
    ; (TokenPrecedence, fun s -> Left, s = "===")
    ; (TokenPrecedence, fun s -> Left, s = "<")
    ; (TokenPrecedence, fun s -> Left, s = ">")
    ; (TokenPrecedence, fun s -> Left, s.[0] == '|' && not (s = "||"))
    ; ( TokenPrecedence
      , fun s -> Left, s.[0] == '&' && (not (s = "&")) && not (s = "&&") )
    ; (TokenPrecedence, fun s -> Left, s.[0] == '$')
    ]
  ; [ (CustomPrecedence, fun s -> Left, s = funToken) ]
  ; [ (TokenPrecedence, fun s -> Right, s = "&")
    ; (TokenPrecedence, fun s -> Right, s = "&&")
    ]
  ; [ (TokenPrecedence, fun s -> Right, s = "or")
    ; (TokenPrecedence, fun s -> Right, s = "||")
    ]
  ; [ (* The Left shouldn't ever matter in practice. Should never get in a
         situation with two consecutive infix ? - the colon saves us. *)
      (TokenPrecedence, fun s -> Left, s = "?")
    ]
  ; [ (TokenPrecedence, fun s -> Right, s = ":=") ]
  ; [ (TokenPrecedence, fun s -> Right, s = updateToken) ]
  ; (* It's important to account for ternary ":" being lower precedence than
       "?" *)
    [ (TokenPrecedence, fun s -> Right, s = ":") ]
  ; [ (TokenPrecedence, fun s -> Nonassoc, s = "=>") ]
  ]

(* remove all prefixing backslashes, e.g. \=== becomes === *)
let without_prefixed_backslashes str =
  if str = ""
  then str
  else if String.get str 0 = '\\'
  then String.sub str 1 (String.length str - 1)
  else str

let indexOfFirstMatch ~prec lst =
  let rec aux n = function
    | [] -> None
    | [] :: tl -> aux (n + 1) tl
    | ((kind, tester) :: hdTl) :: tl ->
      (match prec, kind with
      | Token str, TokenPrecedence | Custom str, CustomPrecedence ->
        let associativity, foundMatch = tester str in
        if foundMatch then Some (associativity, n) else aux n (hdTl :: tl)
      | _ -> aux n (hdTl :: tl))
  in
  aux 0 lst

(* Assuming it's an infix function application. *)
let precedenceInfo ~prec =
  (* Removes prefixed backslashes in order to do proper conversion *)
  let prec =
    match prec with
    | Token str -> Token (without_prefixed_backslashes str)
    | Custom _ -> prec
  in
  indexOfFirstMatch ~prec rules

let isLeftAssociative ~prec =
  match precedenceInfo ~prec with
  | None -> false
  | Some (Left, _) -> true
  | Some (Right, _) -> false
  | Some (Nonassoc, _) -> false

let isRightAssociative ~prec =
  match precedenceInfo ~prec with
  | None -> false
  | Some (Right, _) -> true
  | Some (Left, _) -> false
  | Some (Nonassoc, _) -> false

let higherPrecedenceThan c1 c2 =
  match precedenceInfo ~prec:c1, precedenceInfo ~prec:c2 with
  | _, None | None, _ ->
    let str1, str2 =
      match c1, c2 with
      | Token s1, Token s2 -> "Token " ^ s1, "Token " ^ s2
      | Token s1, Custom s2 -> "Token " ^ s1, "Custom " ^ s2
      | Custom s1, Token s2 -> "Custom " ^ s1, "Token " ^ s2
      | Custom s1, Custom s2 -> "Custom " ^ s1, "Custom " ^ s2
    in
    raise
      (NotPossible
         ("Cannot determine precedence of two checks " ^ str1 ^ " vs. " ^ str2))
  | Some (_, p1), Some (_, p2) -> p1 < p2

let printedStringAndFixityExpr = function
  | { pexp_desc = Pexp_ident { txt = Lident l; _ }; _ } ->
    printedStringAndFixity l
  | _ -> Normal

(* which identifiers are in fact operators needing parentheses *)
let needs_parens txt =
  match printedStringAndFixity txt with
  | Infix _ -> true
  | UnaryPostfix _ -> true
  | UnaryPlusPrefix _ -> true
  | UnaryMinusPrefix _ -> true
  | UnaryNotPrefix _ -> true
  | AlmostSimplePrefix _ -> true
  | Letop _ -> true
  | Andop _ -> true
  | Normal -> false

(* some infixes need spaces around parens to avoid clashes with comment syntax.
   This isn't needed for comment syntax /* */ *)
let needs_spaces txt = txt.[0] = '*' || txt.[String.length txt - 1] = '*'

let rec orList = function
  (* only consider ((A|B)|C)*)
  | { ppat_desc = Ppat_or (p1, p2); _ } -> orList p1 @ orList p2
  | x -> [ x ]

(* variance encoding: need to sync up with the [parser.mly] *)
let type_variance = function
  | NoVariance -> ""
  | Covariant -> "+"
  | Contravariant -> "-"

let moduleIdent ident = match ident.txt with None -> "_" | Some name -> name

type construct =
  [ `cons of expression list
  | `list of expression list
  | `nil
  | `normal
  | `simple of Longident.t
  | `tuple
  | `btrue
  | `bfalse
  ]

let view_expr x =
  match x.pexp_desc with
  | Pexp_construct ({ txt = Lident "()"; _ }, _) -> `tuple
  | Pexp_construct ({ txt = Lident "true"; _ }, _) -> `btrue
  | Pexp_construct ({ txt = Lident "false"; _ }, _) -> `bfalse
  | Pexp_construct ({ txt = Lident "[]"; _ }, _) -> `nil
  | Pexp_construct ({ txt = Lident "::"; _ }, Some _) ->
    let rec loop exp acc =
      match exp with
      | { pexp_desc = Pexp_construct ({ txt = Lident "[]"; _ }, _); _ } ->
        List.rev acc, true
      | { pexp_desc =
            Pexp_construct
              ( { txt = Lident "::"; _ }
              , Some { pexp_desc = Pexp_tuple [ e1; e2 ]; _ } )
        ; _
        } ->
        loop e2 (e1 :: acc)
      | e -> List.rev (e :: acc), false
    in
    let ls, b = loop x [] in
    if b then `list ls else `cons ls
  | Pexp_construct (x, None) -> `simple x.txt
  | _ -> `normal

let is_simple_list_expr x =
  match view_expr x with `list _ | `cons _ -> true | _ -> false

let is_simple_construct : construct -> bool = function
  | `nil | `tuple | `list _ | `simple _ | `btrue | `bfalse | `cons _ -> true
  | `normal -> false

let uncurriedTable = Hashtbl.create 42

(* Determines if a list of expressions contains a single unit construct * e.g.
   used to check: MyConstructor() -> exprList == [()] * useful to determine if
   MyConstructor(()) should be printed as MyConstructor() * *)
let is_single_unit_construct exprList =
  match exprList with
  | x :: [] ->
    let view = view_expr x in
    (match view with `tuple -> true | _ -> false)
  | _ -> false

let detectTernary l =
  match l with
  | [ { pc_lhs =
          { ppat_desc = Ppat_construct ({ txt = Lident "true"; _ }, _); _ }
      ; pc_guard = None
      ; pc_rhs = ifTrue
      }
    ; { pc_lhs =
          { ppat_desc = Ppat_construct ({ txt = Lident "false"; _ }, _); _ }
      ; pc_guard = None
      ; pc_rhs = ifFalse
      }
    ] ->
    Some (ifTrue, ifFalse)
  | _ -> None

type funcApplicationLabelStyle =
  (* No attaching to the label, but if the entire application fits on one line,
     the entire application will appear next to the label as you 'd expect. *)
  | NeverWrapFinalItem
  (* Attach the first term if there are exactly two terms involved in the
     application.

     let x = firstTerm (secondTerm_1 secondTerm_2) thirdTerm;

     Ideally, we'd be able to attach all but the last argument into the label
     any time all but the last term will fit - and *not* when (attaching all but
     the last term isn't enough to prevent a wrap) - But there's no way to tell
     ahead of time if it would prevent a wrap.

     However, the number two is somewhat convenient. This models the indentation
     that you'd prefer in non-curried syntax languages like JavaScript, where
     application only ever has two terms. *)
  | WrapFinalListyItemIfFewerThan of int

type formatSettings =
  { space : int
  ; (* For curried arguments in function *definitions* only: Number of [space]s
       to offset beyond the [let] keyword. Default 1. *)
    listsRecordsIndent : int
  ; indentWrappedPatternArgs : int
  ; (* Amount to indent in label-like constructs such as wrapped function
       applications, etc - or even record fields. This is not the same concept
       as an indented curried argument list. *)
    indentAfterLabels : int
  ; (* Amount to indent after the opening brace of switch/try.
     * Here's an example of what it would look like w/ [trySwitchIndent = 2]:
     * Sticks the expression to the last item in a sequence in several [X | Y | Z
     * => expr], and forces X, Y, Z to be split onto several lines. (Otherwise,
     * sticking to Z would result in hanging expressions).  TODO: In the first case,
     * it's clear that we want patterns to have an "extra" indentation with matching
     * in a "match". Create extra config param to pass to [self#pattern] for extra
     * indentation in this one case.
     *
     *  switch x {
     *  | TwoCombos
     *      (HeresTwoConstructorArguments x y)
     *      (HeresTwoConstructorArguments a b) =>
     *      ((a + b) + x) + y;
     *  | Short
     *  | AlsoHasARecord a b {x, y} => (
     *      retOne,
     *      retTwo
     *    )
     *  | AlsoHasARecord a b {x, y} =>
     *    callMyFunction
     *      withArg
     *      withArg
     *      withArg
     *      withArg;
     *  }
     *)
    trySwitchIndent : int
  ; (* In the case of two term function application (when flattened), the first
     * term should become part of the label, and the second term should be able to wrap
     * This doesn't effect n != 2.
     *
     *   [true]
     *   let x = reallyShort allFitsOnOneLine;
     *   let x = someFunction {
     *     reallyLongObject: true,
     *     thatWouldntFitOnThe: true,
     *     firstLine: true
     *   };
     *
     *   [false]
     *   let x = reallyShort allFitsOnOneLine;
     *   let x =
     *    someFunction
     *      {
     *        reallyLongObject: true,
     *        thatWouldntFitOnThe: true,
     *        firstLine: true
     *      };
     *)
    funcApplicationLabelStyle : funcApplicationLabelStyle
  ; funcCurriedPatternStyle : funcApplicationLabelStyle
  ; width : int
  ; assumeExplicitArity : bool
  ; constructorLists : string list
  }

let defaultSettings =
  { space = 1
  ; listsRecordsIndent = 2
  ; indentWrappedPatternArgs = 2
  ; indentAfterLabels = 2
  ; trySwitchIndent = 0
  ; funcApplicationLabelStyle = WrapFinalListyItemIfFewerThan 3
  ; (* WrapFinalListyItemIfFewerThan is currently a bad idea for curried
     * arguments: It looks great in some cases:
     *
     *    let myFun (a:int) :(
     *      int,
     *      string
     *    ) => (a, "this is a");
     *
     * But horrible in others:
     *
     *    let myFun
     *        {
     *          myField,
     *          yourField
     *        } :someReturnType => myField + yourField;
     *
     *    let myFun
     *        {            // Curried arg wraps
     *          myField,
     *          yourField
     *        } : (       // But the last is "listy" so it docks
     *      int,          // To the [let].
     *      int,
     *      int
     *    ) => myField + yourField;
     *
     * We probably want some special listy label docking/wrapping mode for
     * curried function bindings.
     *
     *)
    funcCurriedPatternStyle = NeverWrapFinalItem
  ; width = 80
  ; assumeExplicitArity = false
  ; constructorLists = []
  }

let configuredSettings = ref defaultSettings

let configure ~width ~assumeExplicitArity ~constructorLists =
  configuredSettings :=
    { defaultSettings with width; assumeExplicitArity; constructorLists }

let createFormatter () =
  let module Formatter = struct
    let settings = !configuredSettings

    (* How do we make
     * this a label?
     *
     * /---------------------\
     * let myVal = (oneThing, {
     * field: [],
     * anotherField: blah
     * });
     *
     * But in this case, this wider region a label?
     * /------------------------------------------------------\
     * let myVal = callSomeFunc (oneThing, {field: [], anotherField: blah}, {
     * boo: 'hi'
     * });
     *
     * This is difficult. You must form a label from the preorder traversal of every
     * node - except the last encountered in the traversal. An easier heuristic is:
     *
     * - The last argument to a functor application is expanded.
     *
     * React.CreateClass SomeThing {
     * let render {props} => {
     * };
     * }
     *
     * - The last argument to a function application is expanded on the same line.
     * - Only if it's not curried with another invocation.
     * -- Optionally: "only if everything else is an atom"
     * -- Optionally: "only if there are no other args"
     *
     * React.createClass someThing {
     * render: fn x => y,
     * }
     *
     * !!! NOT THIS
     * React.createClass someThing {
     * render: fn x => y,
     * }
     * somethingElse
     *)

    let isArityClear attrs =
      !configuredSettings.assumeExplicitArity
      || List.exists
           (function
             | { attr_name = { txt = "explicit_arity"; _ }; _ } -> true
             | _ -> false)
           attrs

    let default_indent_body = settings.listsRecordsIndent * settings.space

    let makeList
          ?listConfigIfCommentsInterleaved
          ?listConfigIfEolCommentsInterleaved
          ?(break = Layout.Never)
          ?(wrap = "", "")
          ?(inline = true, false)
          ?(sep = Layout.NoSep)
          ?(indent = default_indent_body)
          ?(sepLeft = true)
          ?(preSpace = false)
          ?(postSpace = false)
          ?(pad = false, false)
          lst
      =
      let config =
        { Layout.listConfigIfCommentsInterleaved
        ; listConfigIfEolCommentsInterleaved
        ; break = (if lst = [] then Layout.IfNeed else break)
        ; wrap
        ; inline
        ; sep
        ; indent
        ; sepLeft
        ; preSpace
        ; postSpace
        ; pad
        }
      in
      Layout.Sequence (config, lst)

    let makeAppList = function
      | [ hd ] -> hd
      | l -> makeList ~inline:(true, true) ~postSpace:true ~break:IfNeed l

    let makeTup ?(wrap = "", "") ?(trailComma = true) ?(uncurried = false) l =
      let lwrap, rwrap = wrap in
      let lparen = lwrap ^ if uncurried then "(. " else "(" in
      makeList
        ~wrap:(lparen, ")" ^ rwrap)
        ~sep:(if trailComma then commaTrail else commaSep)
        ~postSpace:true
        ~break:IfNeed
        l

    let ensureSingleTokenSticksToLabel x =
      let listConfigIfCommentsInterleaved cfg =
        let inline = true, true
        and postSpace = true
        and indent = 0 in
        { cfg with Layout.break = Always_rec; postSpace; indent; inline }
      in
      makeList ~listConfigIfCommentsInterleaved [ x ]

    let unbreakLabelFormatter formatter =
      let newFormatter labelTerm term =
        match formatter labelTerm term with
        | Easy_format.Label ((labelTerm, settings), term) ->
          Easy_format.Label
            ((labelTerm, { settings with label_break = `Never }), term)
        | _ -> failwith "not a label"
      in
      newFormatter

    let inlineLabel labelTerm term =
      let settings =
        { label_break = `Never
        ; space_after_label = true
        ; indent_after_label = 0
        ; label_style = Some "inlineLabel"
        }
      in
      Easy_format.Label ((labelTerm, settings), term)

    (* Just for debugging: Set debugWithHtml = true *)
    let debugWithHtml = ref false

    let html_escape_string s =
      let buf = Buffer.create (2 * String.length s) in
      for i = 0 to String.length s - 1 do
        match s.[i] with
        | '&' -> Buffer.add_string buf "&amp;"
        | '<' -> Buffer.add_string buf "&lt;"
        | '>' -> Buffer.add_string buf "&gt;"
        | c -> Buffer.add_char buf c
      done;
      Buffer.contents buf

    let html_escape = `Escape_string html_escape_string

    let html_style =
      [ "atom", { Easy_format.tag_open = "<a>"; tag_close = "</a>" }
      ; "body", { tag_open = "<lb>"; tag_close = "</lb>" }
      ; "list", { tag_open = "<l>"; tag_close = "</l>" }
      ; "op", { tag_open = "<op>"; tag_close = "</op>" }
      ; "cl", { tag_open = "<cl>"; tag_close = "</cl>" }
      ; "sep", { tag_open = "<sep>"; tag_close = "</sep>" }
      ; "label", { tag_open = "<la>"; tag_close = "</la>" }
      ]

    let easyLabel
          ?(break = `Auto)
          ?(space = false)
          ?(indent = settings.indentAfterLabels)
          labelTerm
          term
      =
      let settings =
        { label_break = break
        ; space_after_label = space
        ; indent_after_label = indent
        ; label_style = Some "label"
        }
      in
      Easy_format.Label ((labelTerm, settings), term)

    let label ?break ?space ?indent (labelTerm : Layout.t) (term : Layout.t) =
      Layout.Label (easyLabel ?break ?indent ?space, labelTerm, term)

    let atom ?loc str =
      let style = { Easy_format.atom_style = Some "atomClss" } in
      source_map ?loc (Layout.Easy (Easy_format.Atom (str, style)))

    (** Take x,y,z and n and generate [x, y, z, ...n] *)
    let makeES6List ?wrap:(lwrap, rwrap = "", "") lst last =
      makeList
        ~wrap:(lwrap ^ "[", "]" ^ rwrap)
        ~break:IfNeed
        ~postSpace:true
        ~sep:commaTrail
        (lst @ [ makeList [ atom "..."; last ] ])

    let makeNonIndentedBreakingList lst =
      (* No align closing: So that semis stick to the ends of every break *)
      makeList ~break:Always_rec ~indent:0 ~inline:(true, true) lst

    (* Like a <span> could place with other breakableInline lists without
       upsetting final semicolons *)
    let makeSpacedBreakableInlineList lst =
      makeList ~break:IfNeed ~inline:(true, true) ~postSpace:true lst

    let makeCommaBreakableListSurround opn cls lst =
      makeList ~break:IfNeed ~postSpace:true ~sep:(Sep ",") ~wrap:(opn, cls) lst

    (* TODO: Allow configuration of spacing around colon symbol *)

    let formatPrecedence ?(inline = false) ?(wrap = "(", ")") ?loc formattedTerm
      =
      source_map
        ?loc
        (makeList ~inline:(true, inline) ~wrap ~break:IfNeed [ formattedTerm ])

    let wrap fn term =
      ignore (Format.flush_str_formatter ());
      fn Format.str_formatter term;
      atom (Format.flush_str_formatter ())

    let quoted_ext ?(pct = "%") extension i delim =
      wrap
        (fun ppf () ->
           Format.fprintf
             ppf
             "{%s%s%s%s|%s|%s}"
             pct
             extension.txt
             (if delim != "" then " " else "")
             delim
             i
             delim)
        ()

    (* Don't use `trim` since it kills line return too? *)
    let rec beginsWithStar_ line length idx =
      if idx = length
      then false
      else
        match String.get line idx with
        | '*' -> true
        | '\t' | ' ' -> beginsWithStar_ line length (idx + 1)
        | _ -> false

    let beginsWithStar line = beginsWithStar_ line (String.length line) 0

    let rec numLeadingSpace_ line length idx accum =
      if idx = length
      then accum
      else
        match String.get line idx with
        | '\t' | ' ' -> numLeadingSpace_ line length (idx + 1) (accum + 1)
        | _ -> accum

    let numLeadingSpace line = numLeadingSpace_ line (String.length line) 0 0

    (* Computes the smallest leading spaces for non-empty lines *)
    let smallestLeadingSpaces strs =
      let rec smallestLeadingSpaces curMin strs =
        match strs with
        | [] -> curMin
        | "" :: tl -> smallestLeadingSpaces curMin tl
        | hd :: tl ->
          let leadingSpace = numLeadingSpace hd in
          let nextMin = min curMin leadingSpace in
          smallestLeadingSpaces nextMin tl
      in
      smallestLeadingSpaces 99999 strs

    let rec isSequencey = function
      | Layout.SourceMap (_, sub) -> isSequencey sub
      | Layout.Sequence _ -> true
      | Layout.Label (_, _, _) -> false
      | Layout.Easy (Easy_format.List _) -> true
      | Layout.Easy _ -> false
      | Layout.Whitespace (_, sub) -> isSequencey sub

    let inline ?(preSpace = false) ?(postSpace = false) labelTerm term =
      makeList
        [ labelTerm; term ]
        ~inline:(true, true)
        ~postSpace
        ~preSpace
        ~indent:0
        ~break:Layout.Never

    let breakline labelTerm term =
      makeList
        [ labelTerm; term ]
        ~inline:(true, true)
        ~indent:0
        ~break:Always_rec

    let insertBlankLines n term =
      if n = 0
      then term
      else
        makeList
          ~inline:(true, true)
          ~indent:0
          ~break:Always_rec
          (Array.to_list (Array.make n (atom "")) @ [ term ])

    let string_after s n = String.sub s n (String.length s - n)

    (* This is a special-purpose functions only used by `formatComment_`. Notice
       we skip a char below during usage because we know the comment starts with
       `/*` *)
    let rec lineZeroMeaningfulContent_ line length idx accum =
      if idx = length
      then None
      else
        let ch = String.get line idx in
        if ch = '\t' || ch = ' ' || ch = '*'
        then lineZeroMeaningfulContent_ line length (idx + 1) (accum + 1)
        else Some accum

    let lineZeroMeaningfulContent line =
      lineZeroMeaningfulContent_ line (String.length line) 1 0

    let formatComment_ txt =
      let commLines =
        Reason_syntax_util.split_by
          ~keep_empty:true
          (fun x -> x = '\n')
          (Comment.wrap txt)
      in
      match commLines with
      | [] -> atom ""
      | [ hd ] -> atom hd
      | zero :: one :: tl ->
        let attemptRemoveCount = smallestLeadingSpaces (one :: tl) in
        let leftPad =
          if beginsWithStar one
          then 1
          else
            match lineZeroMeaningfulContent zero with
            | None -> 1
            | Some num -> num + 1
        in
        let padNonOpeningLine s =
          let numLeadingSpaceForThisLine = numLeadingSpace s in
          if String.length s == 0
          then ""
          else
            String.make leftPad ' '
            ^ string_after s (min attemptRemoveCount numLeadingSpaceForThisLine)
        in
        let lines = zero :: List.map padNonOpeningLine (one :: tl) in
        makeList
          ~inline:(true, true)
          ~indent:0
          ~break:Always_rec
          (List.map atom lines)

    let formatComment comment =
      source_map ~loc:(Comment.location comment) (formatComment_ comment)

    let[@tail_mod_cons] rec append ?(space = false) txt = function
      | Layout.SourceMap (loc, sub) ->
        Layout.SourceMap (loc, append ~space txt sub)
      | Sequence (config, l) when snd config.wrap <> "" ->
        let sep = if space then " " else "" in
        Sequence
          ( { config with wrap = fst config.wrap, snd config.wrap ^ sep ^ txt }
          , l )
      | Sequence (config, []) -> Sequence (config, [ atom txt ])
      | Sequence (({ sep = NoSep; _ } as config), l)
      | Sequence (({ sep = Sep ""; _ } as config), l) ->
        let sub = appendSub txt ~space l in
        Sequence (config, sub)
      | Label (formatter, left, right) ->
        Label (formatter, left, append ~space txt right)
      | Whitespace (info, sub) -> Whitespace (info, append ~space txt sub)
      | layout -> (inline [@tailcall false]) ~postSpace:space layout (atom txt)

    and[@tail_mod_cons] appendSub txt ~space layouts =
      match layouts with
      | [] -> []
      | [ layout ] -> [ append ~space txt layout ]
      | layout :: xs -> layout :: appendSub txt ~space xs

    let appendSep spaceBeforeSep sep layout =
      append (if spaceBeforeSep then " " ^ sep else sep) layout

    let rec flattenCommentAndSep ?(spaceBeforeSep = false) ?sepStr = function
      | Layout.SourceMap (loc, sub) ->
        Layout.SourceMap (loc, flattenCommentAndSep ~spaceBeforeSep ?sepStr sub)
      | Layout.Whitespace (info, sub) ->
        Layout.Whitespace
          (info, flattenCommentAndSep ~spaceBeforeSep ?sepStr sub)
      | layout ->
        (match sepStr with
        | None -> layout
        | Some sep -> appendSep spaceBeforeSep sep layout)

    let rec preOrderWalk f layout =
      match f layout with
      | Layout.Sequence (listConfig, sublayouts) ->
        let newSublayouts = List.map (preOrderWalk f) sublayouts in
        Layout.Sequence (listConfig, newSublayouts)
      | Layout.Label (formatter, left, right) ->
        let newLeftLayout = preOrderWalk f left in
        let newRightLayout = preOrderWalk f right in
        Layout.Label (formatter, newLeftLayout, newRightLayout)
      | Layout.SourceMap (loc, sub) -> Layout.SourceMap (loc, preOrderWalk f sub)
      | Layout.Easy _ as layout -> layout
      | Layout.Whitespace (info, sub) ->
        Layout.Whitespace (info, preOrderWalk f sub)

    (** Recursively unbreaks a layout to make sure they stay within the same
        line *)
    let unbreaklayout =
      preOrderWalk (function
        | Layout.Sequence (listConfig, sublayouts) ->
          Layout.Sequence ({ listConfig with break = Layout.Never }, sublayouts)
        | Layout.Label (formatter, left, right) ->
          Layout.Label (unbreakLabelFormatter formatter, left, right)
        | layout -> layout)

    (** [consolidateSeparator layout] walks the [layout], extract separators out
        of each * list and insert them into PrintTree as separated items *)
    let consolidateSeparator l =
      preOrderWalk
        (function
          | Sequence (listConfig, sublayouts)
            when listConfig.sep != NoSep && listConfig.sepLeft ->
            (* TODO: Support !sepLeft, and this should apply to the *first*
               separator if !sepLeft. *)
            let[@tail_mod_cons] rec mapSublayout layouts =
              match listConfig.sep, layouts with
              | NoSep, _ ->
                raise
                  (NotPossible
                     "We already covered this case. This shouldn't happen.")
              | Sep _, [ layout ] -> [ layout ]
              | (SepFinal (sepStr, _) | Sep sepStr), layout :: l2 :: xs ->
                flattenCommentAndSep
                  ~spaceBeforeSep:listConfig.preSpace
                  ~sepStr
                  layout
                :: mapSublayout (l2 :: xs)
              | SepFinal (_, finalSepStr), [ layout ] ->
                [ flattenCommentAndSep
                    ~spaceBeforeSep:listConfig.preSpace
                    ~sepStr:finalSepStr
                    layout
                ]
              | _, [] -> []
            in
            let layoutsWithSepAndComment = mapSublayout sublayouts in
            let sep = Layout.NoSep in
            let preSpace = false in
            Sequence
              ({ listConfig with sep; preSpace }, layoutsWithSepAndComment)
          | layout -> layout)
        l

    (** [insertLinesAboveItems layout] walks the [layout] and insert empty lines
    *)
    let insertLinesAboveItems items =
      preOrderWalk
        (function
          | Whitespace (region, sub) ->
            insertBlankLines (WhitespaceRegion.newlines region) sub
          | layout -> layout)
        items

    let insertCommentIntoWhitespaceRegion comment region subLayout =
      let cl = Comment.location comment in
      let range = WhitespaceRegion.range region in
      (* append the comment to the list of inserted comments in the whitespace
         region *)
      let nextRegion = WhitespaceRegion.addComment region comment in
      let formattedComment = formatComment comment in
      match WhitespaceRegion.comments region with
      (* the comment inserted into the whitespace region is the first in the
         region *)
      | [] ->
        (* 1| let a = 1; * 2| * 3| /* comment at end of whitespace region */ *
           4| let b = 2; *)
        if range.lnum_end = cl.loc_end.pos_lnum
        then
          let subLayout = breakline formattedComment subLayout in
          Layout.Whitespace (nextRegion, subLayout)
          (* 1| let a = 1; * 2| /* comment at start of whitespace region */ * 3|
           * 4| let b = 2;
           *)
        else if range.lnum_start = cl.loc_start.pos_lnum
        then
          let subLayout =
            breakline formattedComment (insertBlankLines 1 subLayout)
          in
          let nextRegion = WhitespaceRegion.modifyNewlines nextRegion 0 in
          Whitespace (nextRegion, subLayout)
          (* 1| let a = 1; * 2| * 3| /* comment floats in whitespace region */ *
             4| * 5| let b = 2; *)
        else
          let subLayout =
            breakline formattedComment (insertBlankLines 1 subLayout)
          in
          Whitespace (nextRegion, subLayout)
      (* The whitespace region contains already inserted comments *)
      | prevComment :: _cs ->
        let pcl = Comment.location prevComment in
        (* check if the comment is attached to the start of the region *)
        let attachedToStartRegion = cl.loc_start.pos_lnum = range.lnum_start in
        let nextRegion =
          (* 1| let a = 1; * 2| /* comment sits on the beginning of the region
           */ * 3| /* previous comment */ * 4| * 5| let b = 2;
           *)
          if attachedToStartRegion
          then
            (* we don't want a newline between `let a = 1` and the `comment sits
             * on the beginning of the region` comment*)
            WhitespaceRegion.modifyNewlines nextRegion 0
            (* 1| let a = 1; * 2| * 3| /* comment isn't located at the beginnin
               of a region*/ * 4| /* previous comment */ * 5| * 6| let b = 2; *)
          else nextRegion
        in
        (* 1| let a = 1; * 2| /* comment */ * 3| --> whitespace between * 4| /*
           previous comment */ * 5| let b = 1; *)
        if Reason_location.hasSpaceBetween pcl cl
        then
          (* pcl.loc_start.pos_lnum - cl.loc_end.pos_lnum > 1 then *)
          let subLayout =
            breakline formattedComment (insertBlankLines 1 subLayout)
          in
          let withComment = Layout.Whitespace (nextRegion, subLayout) in
          withComment
          (* 1| let a = 1; * 2| * 3| /* comment */ | no whitespace between
             `comment` * 4| /* previous comment */ | and `previous comment` * 5|
             let b = 1; *)
        else
          let subLayout = breakline formattedComment subLayout in
          let withComment = Layout.Whitespace (nextRegion, subLayout) in
          withComment

    (** * prependSingleLineComment inserts a single line comment right above
        layout *)
    let rec prependSingleLineComment comment layout =
      match layout with
      | Layout.SourceMap (loc, sub) ->
        Layout.SourceMap (loc, prependSingleLineComment comment sub)
      | Sequence (config, hd :: tl) when config.break = Always_rec ->
        Sequence (config, prependSingleLineComment comment hd :: tl)
      | Whitespace (info, sub) ->
        insertCommentIntoWhitespaceRegion comment info sub
      | layout -> breakline (formatComment comment) layout

    (* breakAncestors break ancestors above node, but not comment attachment
       itself.*)
    let appendComment ~breakAncestors layout comment =
      let text = Comment.wrap comment in
      let layout =
        match layout with
        | Layout.Whitespace (info, sublayout) ->
          Layout.Whitespace
            ( info
            , makeList
                ~break:Layout.Never
                ~postSpace:true
                [ sublayout; atom text ] )
        | layout ->
          makeList ~break:Layout.Never ~postSpace:true [ layout; atom text ]
      in
      if breakAncestors
      then
        makeList
          ~inline:(true, true)
          ~postSpace:false
          ~preSpace:true
          ~indent:0
          ~break:Always_rec
          [ layout ]
      else layout

    (** * [looselyAttachComment layout comment] preorderly walks the layout and
        * find a place where the comment can be loosely attached to *)
    let rec looselyAttachComment ~breakAncestors layout comment =
      let location = Comment.location comment in
      match layout with
      | Layout.SourceMap (loc, sub) ->
        Layout.SourceMap (loc, looselyAttachComment ~breakAncestors sub comment)
      | Layout.Whitespace (info, sub) ->
        Layout.Whitespace
          (info, looselyAttachComment ~breakAncestors sub comment)
      | Easy _ -> inline ~postSpace:true layout (formatComment comment)
      | Sequence (listConfig, subLayouts)
        when List.exists (Layout.contains_location ~location) subLayouts ->
        (* If any of the subLayout strictly contains this comment, recurse into
           to it *)
        let recurse_sublayout layout =
          if Layout.contains_location layout ~location
          then looselyAttachComment ~breakAncestors layout comment
          else layout
        in
        Sequence (listConfig, List.map recurse_sublayout subLayouts)
      | Sequence (listConfig, subLayouts) when subLayouts == [] ->
        (* If there are no subLayouts (empty body), create a Sequence of just
           the comment *)
        Sequence (listConfig, [ formatComment comment ])
      | Sequence (listConfig, subLayouts) ->
        let beforeComment, afterComment =
          Reason_syntax_util.pick_while (Layout.is_before ~location) subLayouts
        in
        let newSubLayout =
          match List.rev beforeComment with
          | [] ->
            Reason_syntax_util.map_first
              (prependSingleLineComment comment)
              afterComment
          | hd :: tl ->
            List.rev_append
              (appendComment ~breakAncestors hd comment :: tl)
              afterComment
        in
        Sequence (listConfig, newSubLayout)
      | Label (formatter, left, right) ->
        let newLeft, newRight =
          match Layout.get_location left, Layout.get_location right with
          | None, None ->
            left, looselyAttachComment ~breakAncestors right comment
          | _, Some loc2 when Reason_syntax_util.location_contains loc2 location
            ->
            left, looselyAttachComment ~breakAncestors right comment
          | Some loc1, _ when Reason_syntax_util.location_contains loc1 location
            ->
            looselyAttachComment ~breakAncestors left comment, right
          | Some loc1, Some _
            when Reason_syntax_util.location_is_before location loc1 ->
            prependSingleLineComment comment left, right
          | Some _, Some loc2
            when Reason_syntax_util.location_is_before location loc2 ->
            left, prependSingleLineComment comment right
          | _ -> left, appendComment ~breakAncestors right comment
        in
        Label (formatter, newLeft, newRight)

    (** * [insertSingleLineComment layout comment] preorderly walks the layout
        and * find a place where the SingleLineComment can be fit into *)
    let rec insertSingleLineComment layout comment =
      let location = Comment.location comment in
      match layout with
      | Layout.SourceMap (loc, sub) ->
        Layout.SourceMap (loc, insertSingleLineComment sub comment)
      | Layout.Whitespace (info, sub) ->
        let range = WhitespaceRegion.range info in
        if Range.containsLoc range location
        then insertCommentIntoWhitespaceRegion comment info sub
        else Layout.Whitespace (info, insertSingleLineComment sub comment)
      | Easy _ -> prependSingleLineComment comment layout
      | Sequence (listConfig, subLayouts) when subLayouts == [] ->
        (* If there are no subLayouts (empty body), create a Sequence of just the
         * comment. We need to be careful when the empty body contains a //-style
         * comment. Example:
         *   let make = () => {
         *     //
         *   };
         * It is clear that the sequence needs to always break here, otherwise
         * we get a parse error: let make = () => { // };
         * The closing brace and semicolon `};` would become part of the comment…
         *)
        let listConfig =
          if Reason_comment.isLineComment comment
          then { listConfig with break = Always_rec }
          else listConfig
        in
        Sequence (listConfig, [ formatComment comment ])
      | Sequence (listConfig, subLayouts) ->
        let beforeComment, afterComment =
          Reason_syntax_util.pick_while (Layout.is_before ~location) subLayouts
        in
        (match afterComment with
        (* Nothing in the list is after comment, attach comment to the statement
           before the comment *)
        | [] ->
          let break sublayout = breakline sublayout (formatComment comment) in
          Sequence (listConfig, Reason_syntax_util.map_last break beforeComment)
        | hd :: tl ->
          let afterComment =
            match Layout.get_location hd with
            | Some loc when Reason_syntax_util.location_contains loc location ->
              insertSingleLineComment hd comment :: tl
            | Some loc ->
              Layout.SourceMap (loc, prependSingleLineComment comment hd) :: tl
            | _ -> prependSingleLineComment comment hd :: tl
          in
          Sequence (listConfig, beforeComment @ afterComment))
      | Label (formatter, left, right) ->
        let leftLoc = Layout.get_location left in
        let rightLoc = Layout.get_location right in
        let newLeft, newRight =
          match leftLoc, rightLoc with
          | None, None -> left, insertSingleLineComment right comment
          | _, Some loc2 when Reason_syntax_util.location_contains loc2 location
            ->
            left, insertSingleLineComment right comment
          | Some loc1, _ when Reason_syntax_util.location_contains loc1 location
            ->
            insertSingleLineComment left comment, right
          | Some loc1, Some _
            when Reason_syntax_util.location_is_before location loc1 ->
            prependSingleLineComment comment left, right
          | Some _, Some loc2
            when Reason_syntax_util.location_is_before location loc2 ->
            left, prependSingleLineComment comment right
          | _ -> left, breakline right (formatComment comment)
        in
        Label (formatter, newLeft, newRight)

    let rec attachCommentToNodeRight layout comment =
      match layout with
      | Layout.Sequence (config, sub) when snd config.wrap <> "" ->
        (* jwalke: This is quite the abuse of the "wrap" config *)
        let lwrap, rwrap = config.wrap in
        let rwrap = rwrap ^ " " ^ Comment.wrap comment in
        Layout.Sequence ({ config with wrap = lwrap, rwrap }, sub)
      | Layout.SourceMap (loc, sub) ->
        Layout.SourceMap (loc, attachCommentToNodeRight sub comment)
      | layout -> inline ~postSpace:true layout (formatComment comment)

    let rec attachCommentToNodeLeft comment layout =
      match layout with
      | Layout.Sequence (config, sub) when snd config.wrap <> "" ->
        let lwrap, rwrap = config.wrap in
        let lwrap = Comment.wrap comment ^ " " ^ lwrap in
        Layout.Sequence ({ config with wrap = lwrap, rwrap }, sub)
      | Layout.SourceMap (loc, sub) ->
        Layout.SourceMap (loc, attachCommentToNodeLeft comment sub)
      | layout -> Layout.Label (inlineLabel, formatComment comment, layout)

    (* [tryPerfectlyAttachComment layout comment] postorderly walk the [layout] and tries
     *  to perfectly attach a comment with a layout node.
     *
     *  Perfectly attach here means a comment's start location is equal to the node's end location
     *  and vice versa.
     *
     *  If the comment can be perfectly attached to any layout node, returns (newLayout, None),
     *  meaning the comment is consumed. Otherwise returns the (unchangedLayout, Some comment),
     *  meaning the comment is not consumed.
     *
     * "perfect attachment" doesn't make sense for end of line comments:
     *
     *       {
     *         x: 0,
     *         y: 0
     *       }
     *
     * One of these will be "perfectly attached" to the zero and the other won't.
     * Why should the comma have such an influence? Trailing commas and semicolons
     * may be inserted or removed, an we need end-of-line comments to never be
     * impacted by that. Therefore, never try to "perfectly" attach EOL comments.
     *)
    let rec tryPerfectlyAttachComment layout = function
      | None -> layout, None
      | Some comment -> perfectlyAttachComment comment layout

    and perfectlyAttachComment comment = function
      | Layout.Sequence (listConfig, subLayouts) ->
        let distributeCommentIntoSubLayouts (i, processed, newComment) layout =
          let layout, newComment =
            tryPerfectlyAttachComment layout newComment
          in
          i + 1, layout :: processed, newComment
        in
        let _, processed, consumed =
          List.fold_left
            distributeCommentIntoSubLayouts
            (0, [], Some comment)
            (List.rev subLayouts)
        in
        Layout.Sequence (listConfig, processed), consumed
      | Layout.Label (labelFormatter, left, right) ->
        let newRight, comment = perfectlyAttachComment comment right in
        let newLeft, comment = tryPerfectlyAttachComment left comment in
        Layout.Label (labelFormatter, newLeft, newRight), comment
      | Layout.SourceMap (loc, subLayout) ->
        let commloc = Comment.location comment in
        if
          loc.loc_end.Lexing.pos_lnum = loc.loc_start.Lexing.pos_lnum
          && commloc.loc_start.Lexing.pos_cnum = loc.loc_end.Lexing.pos_cnum
        then
          ( Layout.SourceMap
              ( loc
              , makeList
                  ~inline:(true, true)
                  ~break:Always
                  [ unbreaklayout (attachCommentToNodeRight subLayout comment) ]
              )
          , None )
        else
          let layout, comment = perfectlyAttachComment comment subLayout in
          (match comment with
          | None -> Layout.SourceMap (loc, layout), None
          | Some comment ->
            if commloc.loc_end.Lexing.pos_cnum = loc.loc_start.Lexing.pos_cnum
            then
              ( Layout.SourceMap (loc, attachCommentToNodeLeft comment layout)
              , None )
            else if
              commloc.loc_start.Lexing.pos_cnum = loc.loc_end.Lexing.pos_cnum
            then
              ( Layout.SourceMap (loc, attachCommentToNodeRight layout comment)
              , None )
            else Layout.SourceMap (loc, layout), Some comment)
      | Whitespace (info, subLayout) ->
        (match perfectlyAttachComment comment subLayout with
        | newLayout, None -> Whitespace (info, newLayout), None
        | newLayout, Some c -> Whitespace (info, newLayout), Some c)
      | layout -> layout, Some comment

    let insertRegularComment layout comment =
      match perfectlyAttachComment comment layout with
      | layout, None -> layout
      | layout, Some _ ->
        looselyAttachComment ~breakAncestors:false layout comment

    let insertEndOfLineComment layout comment =
      looselyAttachComment ~breakAncestors:true layout comment

    let rec partitionComments_ ((singleLines, endOfLines, regulars) as soFar)
      = function
      | [] -> soFar
      | com :: tl ->
        (match Comment.category com with
        | Comment.EndOfLine ->
          partitionComments_ (singleLines, com :: endOfLines, regulars) tl
        | Comment.SingleLine ->
          partitionComments_ (com :: singleLines, endOfLines, regulars) tl
        | Comment.Regular ->
          partitionComments_ (singleLines, endOfLines, com :: regulars) tl)

    let partitionComments comments =
      let singleLines, endOfLines, regulars =
        partitionComments_ ([], [], []) comments
      in
      singleLines, List.rev endOfLines, regulars

    (* * Partition single line comments based on a location into two lists: * -
       one contains the comments before/same height of that location * - the
       other contains the comments after the location *)
    let partitionSingleLineComments loc singleLineComments =
      let before, after =
        List.fold_left
          (fun (before, after) comment ->
             let cl = Comment.location comment in
             let isAfter = loc.loc_end.pos_lnum < cl.loc_start.pos_lnum in
             if isAfter
             then before, comment :: after
             else comment :: before, after)
          ([], [])
          singleLineComments
      in
      List.rev before, after

    (* * appends all [singleLineComments] after the [layout]. * [loc] marks the
       end of [layout] *)
    let appendSingleLineCommentsToEnd loc layout singleLineComments =
      let rec aux prevLoc layout i = function
        | comment :: cs ->
          let loc = Comment.location comment in
          let formattedComment = formatComment comment in
          let commentLayout =
            if Reason_location.hasSpaceBetween loc prevLoc
            then insertBlankLines 1 formattedComment
            else formattedComment
          in
          (* The initial layout breaks ugly with `breakline`, * an inline list
             (that never breaks) fixes this *)
          let newLayout =
            if i == 0
            then
              makeList
                ~inline:(true, true)
                ~break:Never
                [ layout; commentLayout ]
            else breakline layout commentLayout
          in
          aux loc newLayout (i + 1) cs
        | [] -> layout
      in
      aux loc layout 0 singleLineComments

    (* * For simplicity, the formatting of comments happens in two parts in
       context of a source map: * 1) insert the singleLineComments with the
       interleaving algorithm contained in * `insertSingleLineComment` for all
       comments overlapping with the sourcemap. * A `Layout.Whitespace` node
       signals an intent to preserve whitespace here. * 2) SingleLineComments
       after the sourcemap, e.g. at the end of .re/.rei file, * get attached
       with `appendSingleLineCommentsToEnd`. Due to the fact there * aren't any
       real ocaml ast nodes anymore after the sourcemap (end of a * file), the
       printing of the comments can be done in one pass with *
       `appendSingleLineCommentsToEnd`. This is more performant and * simplifies
       the implementation of comment attachment. *)
    let attachSingleLineComments singleLineComments = function
      | Layout.SourceMap (loc, subLayout) ->
        let before, after =
          partitionSingleLineComments loc singleLineComments
        in
        let layout = List.fold_left insertSingleLineComment subLayout before in
        appendSingleLineCommentsToEnd loc layout after
      | layout ->
        List.fold_left insertSingleLineComment layout singleLineComments

    let format_layout ?comments ppf layout =
      let easy =
        match comments with
        | None -> Layout.to_easy_format layout
        | Some comments ->
          let singleLines, endOfLines, regulars = partitionComments comments in
          (* TODO: Stop generating multiple versions of the tree, and instead
             generate one new tree. *)
          (* Layout.dump Format.std_formatter layout; *)
          let layout = List.fold_left insertRegularComment layout regulars in
          let layout = consolidateSeparator layout in
          let layout =
            List.fold_left insertEndOfLineComment layout endOfLines
          in
          (* Layout.dump Format.std_formatter layout; *)
          let layout = attachSingleLineComments singleLines layout in
          (* Layout.dump Format.std_formatter layout; *)
          let layout = insertLinesAboveItems layout in
          let layout = Layout.to_easy_format layout in
          (* Layout.dump_easy Format.std_formatter layout; *)
          layout
      in
      let buf = Buffer.create 1000 in
      let fauxmatter = Format.formatter_of_buffer buf in
      let _ = Format.pp_set_margin fauxmatter settings.width in
      if debugWithHtml.contents
      then Easy_format.Pretty.define_styles fauxmatter html_escape html_style;
      let _ = Easy_format.Pretty.to_formatter fauxmatter easy in
      let trimmed =
        Reason_syntax_util.processLineEndingsAndStarts (Buffer.contents buf)
      in
      Format.fprintf ppf "%s\n" trimmed;
      Format.pp_print_flush ppf ()

    let rev_and_len xs =
      let rec rev_and_len acc len xs =
        match xs with
        | [] -> acc, len
        | x :: xs -> rev_and_len (x :: acc) (len + 1) xs
      in
      rev_and_len [] 0 xs

    let partitionFinalWrapping listTester wrapFinalItemSetting x =
      let rev, len = rev_and_len x in
      match rev, wrapFinalItemSetting with
      | [], _ ->
        raise (NotPossible "shouldnt be partitioning 0 label attachments")
      | _, NeverWrapFinalItem -> None
      | last :: revEverythingButLast, WrapFinalListyItemIfFewerThan max ->
        if (not (listTester last)) || len >= max
        then None
        else Some (List.rev revEverythingButLast, last)

    let semiTerminated term = makeList [ term; atom ";" ]

    (* postSpace is so that when comments are interleaved, we still use spacing
       rules. *)
    let makeLetSequence ?(wrap = "{", "}") letItems =
      makeList
        ~break:Always_rec
        ~inline:(true, false)
        ~wrap
        ~postSpace:true
        ~sep:(SepFinal (";", ";"))
        letItems

    let makeLetSequenceSingleLine ?(wrap = "{", "}") letItems =
      makeList
        ~break:IfNeed
        ~inline:(true, false)
        ~wrap
        ~preSpace:true
        ~postSpace:true
        ~sep:(Sep ";")
        letItems

    (* postSpace is so that when comments are interleaved, we still use spacing
       rules. *)
    let makeUnguardedLetSequence ?(sep = Layout.SepFinal (";", ";")) letItems =
      makeList
        ~break:Always_rec
        ~inline:(true, true)
        ~wrap:("", "")
        ~indent:0
        ~postSpace:true
        ~sep
        letItems

    let formatSimpleAttributed x y =
      makeList
        ~wrap:("(", ")")
        ~break:IfNeed
        ~indent:0
        ~postSpace:true
        (List.concat [ y; [ x ] ])

    let formatAttributed ?(labelBreak = `Auto) x y =
      label
        ~break:labelBreak
        ~indent:0
        ~space:true
        (makeList ~inline:(true, true) ~postSpace:true y)
        x

    (* For when the type constraint should be treated as a separate breakable
       line item itself not docked to some value/pattern label. fun x y :
       retType => blah; *)
    let formatJustTheTypeConstraint typ =
      makeList ~postSpace:false ~sep:(Sep " ") [ atom ":"; typ ]

    let formatTypeConstraint one two =
      label ~space:true (makeList ~postSpace:false [ one; atom ":" ]) two

    let formatJustCoerce optType coerced =
      match optType with
      | None -> makeList ~postSpace:false ~sep:(Sep " ") [ atom ":>"; coerced ]
      | Some typ ->
        label ~space:true (makeList ~postSpace:true [ typ; atom ":>" ]) coerced

    let formatCoerce expr optType coerced =
      match optType with
      | None ->
        label ~space:true (makeList ~postSpace:true [ expr; atom ":>" ]) coerced
      | Some typ ->
        label
          ~space:true
          (makeList
             ~postSpace:true
             [ formatTypeConstraint expr typ; atom ":>" ])
          coerced

    (* Standard function application style indentation - no special wrapping *
       behavior. * * Formats like this: * * let result = * someFunc * (10, 20);
       * * * Instead of this: * * let result = * someFunc ( * 10, * 20 * ); * *
       The outer list wrapping fixes #566: format should break the whole *
       application before breaking arguments. *)
    let formatIndentedApplication headApplicationItem argApplicationItems =
      makeList
        ~inline:(true, true)
        ~postSpace:true
        ~break:IfNeed
        [ label
            ~space:true
            headApplicationItem
            (makeAppList argApplicationItems)
        ]

    (* The loc, is an optional location or the returned app terms *)
    let formatAttachmentApplication
          finalWrapping
          (attachTo : (bool * Layout.t) option)
          (appTermItems, loc)
      =
      let partitioning = finalWrapping appTermItems in
      match partitioning with
      | None ->
        (match appTermItems, attachTo with
        | [], _ -> raise (NotPossible "No app terms")
        | [ hd ], None -> source_map ?loc hd
        | [ hd ], Some (useSpace, toThis) ->
          label ~space:useSpace toThis (source_map ?loc hd)
        | hd :: tl, None -> source_map ?loc (formatIndentedApplication hd tl)
        | hd :: tl, Some (useSpace, toThis) ->
          label
            ~space:useSpace
            toThis
            (source_map ?loc (formatIndentedApplication hd tl)))
      | Some (attachedList, wrappedListy) ->
        (match attachedList, attachTo with
        | [], Some (useSpace, toThis) ->
          label ~space:useSpace toThis (source_map ?loc wrappedListy)
        | [], None ->
          (* Not Sure when this would happen *)
          source_map ?loc wrappedListy
        | _ :: _, Some (useSpace, toThis) ->
          (* TODO: Can't attach location to this - maybe rewrite anyways *)
          let attachedArgs = makeAppList attachedList in
          label
            ~space:useSpace
            toThis
            (label ~space:true attachedArgs wrappedListy)
        | _ :: _, None ->
          (* Args that are "attached to nothing" *)
          let appList = makeAppList attachedList in
          source_map ?loc (label ~space:true appList wrappedListy))

    (* Preprocesses an expression term for the sake of label attachments ([letx
       = expr]or record [field: expr]). Function application should have special
       treatment when placed next to a label. (The invoked function term should
       "stick" to the label in some cases). In others, the invoked function term
       should become a new label for the remaining items to be indented
       under. *)
    let applicationFinalWrapping x =
      partitionFinalWrapping isSequencey settings.funcApplicationLabelStyle x

    let curriedFunctionFinalWrapping x =
      partitionFinalWrapping isSequencey settings.funcCurriedPatternStyle x

    let typeApplicationFinalWrapping typeApplicationItems =
      partitionFinalWrapping
        isSequencey
        settings.funcApplicationLabelStyle
        typeApplicationItems

    let add_raw_identifier_prefix txt =
      let prefix =
        match Hashtbl.find Reason_declarative_lexer.keyword_table txt with
        | _ -> "\\#"
        | exception Not_found -> ""
      in
      prefix ^ txt

    (* add parentheses to binders when they are in fact infix or prefix
       operators *)
    let protectIdentifier txt =
      let needs_parens = needs_parens txt in
      let txt =
        if Reason_syntax_util.is_andop txt || Reason_syntax_util.is_letop txt
        then Reason_syntax_util.compress_letop_identifier txt
        else txt |> add_raw_identifier_prefix
      in
      if not needs_parens
      then atom txt
      else if needs_spaces txt
      then makeList ~wrap:("(", ")") ~pad:(true, true) [ atom txt ]
      else atom ("(" ^ txt ^ ")")

    let protectLongIdentifier longPrefix txt =
      makeList [ longPrefix; atom "."; protectIdentifier txt ]

    let paren b fu ppf x =
      if b then Format.fprintf ppf "(%a)" fu x else fu ppf x

    let constant_string_for_primitive ppf s =
      let hasQuote = try String.index s '"' with Not_found -> -1 in
      let hasNewline = try String.index s '\n' with Not_found -> -1 in
      if hasQuote > -1 || hasNewline > -1
      then Format.fprintf ppf "{|%s|}" s
      else Format.fprintf ppf "%S" s

    let tyvar ppf str = Format.fprintf ppf "'%s" str

    (* In some places parens shouldn't be printed for readability: * e.g.
       Some((-1)) should be printed as Some(-1) * In `1 + (-1)` -1 should be
       wrapped in parens for readability *)
    let constant ?raw_literal ?(parens = true) ppf = function
      | Pconst_char i -> Format.fprintf ppf "%C" i
      | Pconst_string (i, _, None) ->
        (match raw_literal with
        | Some text -> Format.fprintf ppf "\"%s\"" text
        | None ->
          Format.fprintf ppf "\"%s\"" (Reason_syntax_util.escape_string i))
      | Pconst_string (i, _, Some delim) ->
        Format.fprintf ppf "{%s|%s|%s}" delim i delim
      | Pconst_integer (i, None) ->
        paren (parens && i.[0] = '-') (fun ppf -> Format.fprintf ppf "%s") ppf i
      | Pconst_integer (i, Some m) ->
        paren
          (parens && i.[0] = '-')
          (fun ppf (i, m) -> Format.fprintf ppf "%s%c" i m)
          ppf
          (i, m)
      | Pconst_float (i, None) ->
        paren (parens && i.[0] = '-') (fun ppf -> Format.fprintf ppf "%s") ppf i
      | Pconst_float (i, Some m) ->
        paren
          (parens && i.[0] = '-')
          (fun ppf (i, m) -> Format.fprintf ppf "%s%c" i m)
          ppf
          (i, m)

    let is_punned_labelled_pattern_no_attrs p lbl =
      match p.ppat_attributes, p.ppat_desc with
      | _ :: _, _ -> false
      | ( []
        , Ppat_constraint
            ({ ppat_desc = Ppat_var { txt; _ }; ppat_attributes = []; _ }, _) )
      | [], Ppat_var { txt; _ } ->
        txt = lbl
      | _ -> false

    let isLongIdentWithDot = function Ldot _ -> true | _ -> false

    (* Js.t -> useful for Melange syntax sugar: `Js.t({. foo: bar})` -> `{.
       "foo": bar}` *)
    let isJsDotTLongIdent ident =
      match ident with Ldot (Lident "Js", "t") -> true | _ -> false

    let recordRowIsPunned pld =
      let name = pld.pld_name.txt in
      match pld.pld_type with
      | { ptyp_desc =
            Ptyp_constr
              ( { txt; _ }
              , (* don't pun parameterized types, e.g. {tag: tag 'props} *)
                [] )
        ; (* Don't pun types that have attributes attached, e.g. { foo: [@bar]
             foo } *)
          ptyp_attributes = []
        ; _
        }
        when Longident.last_exn txt = name
             (* Don't pun types from other modules, e.g. type bar = {foo:
                Baz.foo}; *)
             && isLongIdentWithDot txt == false ->
        true
      | _ -> false

    let isPunnedJsxArg lbl ident attr =
      (not (isLongIdentWithDot ident.txt))
      && Longident.last_exn ident.txt = lbl
      && attr = []

    let is_unit_pattern x =
      match x.ppat_desc with
      | Ppat_construct ({ txt = Lident "()"; _ }, None) -> true
      | _ -> false

    let is_ident_pattern x =
      match x.ppat_desc with Ppat_var _ -> true | _ -> false

    let is_any_pattern x = x.ppat_desc = Ppat_any

    let is_direct_pattern x =
      x.ppat_attributes == []
      &&
      match x.ppat_desc with
      | Ppat_construct ({ txt = Lident "()"; _ }, None) -> true
      | _ -> false

    let isJSXComponent expr =
      match expr with
      | { pexp_desc = Pexp_apply ({ pexp_desc = Pexp_ident _; _ }, args)
        ; pexp_attributes
        ; _
        }
      | { pexp_desc =
            Pexp_apply ({ pexp_desc = Pexp_letmodule (_, _, _); _ }, args)
        ; pexp_attributes
        ; _
        } ->
        let { Reason_attributes.jsxAttrs; _ } =
          Reason_attributes.partitionAttributes pexp_attributes
        in
        let hasLabelledChildrenLiteral =
          List.exists
            (function Labelled "children", _ -> true | _ -> false)
            args
        in
        let rec hasSingleNonLabelledUnitAndIsAtTheEnd l =
          match l with
          | [] -> false
          | ( Nolabel
            , { pexp_desc = Pexp_construct ({ txt = Lident "()"; _ }, _); _ } )
            :: [] ->
            true
          | (Nolabel, _) :: _ -> false
          | _ :: rest -> hasSingleNonLabelledUnitAndIsAtTheEnd rest
        in
        if
          jsxAttrs != []
          && hasLabelledChildrenLiteral
          && hasSingleNonLabelledUnitAndIsAtTheEnd args
        then true
        else false
      | _ -> false

    (* Some cases require special formatting when there's a function application
     * with a single argument containing some kind of structure with braces/parens/brackets.
     * Example: `foo({a: 1, b: 2})` needs to be formatted as
     *  foo({
     *    a: 1,
     *    b: 2
     *  })
     *  when the line length dictates breaking. Notice how `({` and `})` 'hug'.
     *  Also applies to (poly)variants because they can be seen as a form of "function application".
     *  This function says if a list of expressions fulfills the need to be formatted like
     *  the example above. *)
    let isSingleArgParenApplication = function
      | [ { pexp_attributes = []; pexp_desc = Pexp_record _; _ } ]
      | [ { pexp_attributes = []; pexp_desc = Pexp_tuple _; _ } ]
      | [ { pexp_attributes = []; pexp_desc = Pexp_array _; _ } ]
      | [ { pexp_attributes = []; pexp_desc = Pexp_object _; _ } ] ->
        true
      | [ { pexp_attributes = []; pexp_desc = Pexp_extension (s, _); _ } ]
        when s.txt = "mel.obj" ->
        true
      | [ ({ pexp_attributes = []; _ } as exp) ] when is_simple_list_expr exp ->
        true
      | _ -> false

    (* Determines if the arguments of a constructor pattern match need
     * special printing. If there's one argument & they have some kind of wrapping,
     * they're wrapping need to 'hug' the surrounding parens.
     * Example:
     *  switch x {
     *  | Some({
     *      a,
     *      b,
     *    }) => ()
     *  }
     *
     *  Notice how ({ and }) hug.
     *  This applies for records, arrays, tuples & lists.
     *  See `singleArgParenPattern` for the acutal formatting
     *)
    let isSingleArgParenPattern = function
      | [ { ppat_attributes = []; ppat_desc = Ppat_record _; _ } ]
      | [ { ppat_attributes = []; ppat_desc = Ppat_array _; _ } ]
      | [ { ppat_attributes = []; ppat_desc = Ppat_tuple _; _ } ] ->
        true
      | [ { ppat_attributes = []
          ; ppat_desc = Ppat_construct ({ txt = Lident "::"; _ }, _)
          ; _
          }
        ] ->
        true
      | _ -> false

    (* Flattens a resolvedRule into a list of infixChain nodes. * When foo |> f
       |> z gets parsed, we get the following tree: * |> * / \ * foo |> * / \ *
       f z * To format this recursive tree in a way that allows nice breaking *
       & respects the print-width, we need some kind of flattened * version of
       the above tree. `computeInfixChain` transforms the tree * in a flattened
       version which allows flexible formatting. * E.g. we get * [LayoutNode
       foo; InfixToken |>; LayoutNode f; InfixToken |>; LayoutNode z] *)
    let rec computeInfixChain = function
      | LayoutNode layoutNode -> [ Layout layoutNode ]
      | InfixTree (op, leftResolvedRule, rightResolvedRule) ->
        computeInfixChain leftResolvedRule
        @ [ InfixToken op ]
        @ computeInfixChain rightResolvedRule

    let equalityOperators = [ "!="; "!=="; "==="; "=="; ">="; "<="; "<"; ">" ]

    (* Formats a flattened list of infixChain nodes into a list of layoutNodes *
       which allow smooth line-breaking * e.g. [LayoutNode foo; InfixToken |>;
       LayoutNode f; InfixToken |>; LayoutNode z] * becomes * [ * foo * ; |> f
       --> label * ; |> z --> label * ] * If you make a list out of this items,
       we get smooth line breaking * foo |> f |> z * becomes * foo * |> f * |> z
       * when the print-width forces line breaks. *)
    let formatComputedInfixChain infixChainList =
      let layout_of_group group currentToken =
        (* Represents the `foo` in * foo * |> f * |> z *)
        match group with
        | [] | [ _ ] -> makeList ~inline:(true, true) ~sep:(Sep " ") group
        | _ ->
          (* Basic equality operators require special formatting, we can't give
             it * 'classic' infix operator formatting, otherwise we would get *
             let example = * true * != false * && "a" * == "b" * *)
          if List.mem currentToken equalityOperators
          then
            let hd = List.hd group in
            let tl =
              makeList ~inline:(true, true) ~sep:(Sep " ") (List.tl group)
            in
            makeList
              ~inline:(true, true)
              ~sep:(Sep " ")
              ~break:IfNeed
              [ hd; tl ]
          else if currentToken.[0] = '#'
          then
            let isSharpEqual = currentToken = sharpOpEqualToken in
            makeList ~postSpace:isSharpEqual group
          else
            (* Represents `|> f` in foo |> f * We need a label here to indent
               possible closing parens * on the same height as the infix
               operator * e.g. * >|= ( * fun body => * Printf.sprintf * "okokok"
               uri meth headers body * ) <-- notice how this closing paren is on
               the same height as >|= *)
            label
              ~break:`Never
              ~space:true
              (atom currentToken)
              (List.nth group 1)
      in
      let rec print acc group currentToken l =
        match l with
        | x :: xs ->
          (match x with
          | InfixToken t ->
            (* = or := *)
            if List.mem t requireIndentFor
            then
              let groupNode =
                makeList
                  ~inline:(true, true)
                  ~sep:(Sep " ")
                  (print [] group currentToken [] @ [ atom t ])
              in
              let children =
                makeList
                  ~inline:(true, true)
                  ~preSpace:true
                  ~break:IfNeed
                  (print [] [] t xs)
              in
              print (acc @ [ label ~space:true groupNode children ]) [] t []
              (* Represents:
               * List.map @@
               * List.length
               *
               * Notice how we want the `@@` on the first line.
               * Extra indent puts pressure on the subsequent line lengths
               *)
            else if t = "@@"
            then
              let groupNode =
                makeList ~inline:(true, true) ~sep:(Sep " ") (group @ [ atom t ])
              in
              print (acc @ [ groupNode ]) [] t xs
              (* != !== === == >= <= < > etc *)
            else if List.mem t equalityOperators
            then print acc (print [] group currentToken [] @ [ atom t ]) t xs
            else if requireNoSpaceFor t
            then
              if currentToken = "" || requireNoSpaceFor currentToken
              then print acc (group @ [ atom t ]) t xs
              else
                (* a + b + foo##bar##baz * `foo` needs to be picked from the
                   current group * and inserted into a new one. This way `foo` *
                   gets the special "chained"-printing: * foo##bar##baz. *)
                match List.rev group with
                | hd :: tl ->
                  let acc =
                    acc @ [ layout_of_group (List.rev tl) currentToken ]
                  in
                  print acc [ hd; atom t ] t xs
                | [] -> print acc (group @ [ atom t ]) t xs
            else
              print
                (acc @ [ layout_of_group group currentToken ])
                [ atom t ]
                t
                xs
          | Layout layoutNode ->
            print acc (group @ [ layoutNode ]) currentToken xs)
        | [] ->
          if List.mem currentToken requireIndentFor
          then acc @ group
          else acc @ [ layout_of_group group currentToken ]
      in
      let l = print [] [] "" infixChainList in
      makeList ~inline:(true, true) ~sep:(Sep " ") ~break:IfNeed l

    (** * [groupAndPrint] will print every item in [items] according to the
        function [xf]. * [getLoc] will extract the location from an item. Based
        on the difference * between the location of two items, if there's
        whitespace between the two * (taken possible comments into account),
        items get grouped. * Every group designates a series of layout nodes "in
        need * of whitespace above". A group gets decorated with a Whitespace
        node * containing enough info to interleave whitespace at a later time
        during * printing. *)
    let groupAndPrint ~xf ~getLoc ~comments items =
      let rec group prevLoc curr acc = function
        (* group items *)
        | x :: xs ->
          let item = xf x in
          let loc = getLoc x in
          (* Get the range between the current and previous item * Example: * 1|
             let a = 1; * 2| --> this is the range between the two * 3| let b =
             2; * *)
          let range = Range.makeRangeBetween prevLoc loc in
          (* If there's whitespace interleaved, append the new layout node * to
             a new group, otherwise keep it in the current group. * Takes
             possible comments interleaved into account. * * Example: * 1| let a
             = 1; * 2| * 3| let b = 2; * 4| let c = 3; * `let b = 2` will mark
             the start of a new group * `let c = 3` will be added to the group
             containing `let b = 2` *)
          if Range.containsWhitespace ~range ~comments ()
          then group loc [ range, item ] (List.rev curr :: acc) xs
          else group loc ((range, item) :: curr) acc xs
        (* convert groups into "Layout.Whitespace" *)
        | [] ->
          let groups = List.rev (List.rev curr :: acc) in
          List.mapi
            (fun i group ->
               match group with
               | curr :: xs ->
                 let range, x = curr in
                 (* if this is the first group of all "items", the number of
                  * newlines interleaved should be 0, else we collapse all newlines
                  * to 1.
                  *
                  * Example:
                  * module Abc = {
                  *   let a = 1;
                  *
                  *   let b = 2;
                  * }
                  * `let a = 1` should be wrapped in a `Layout.Whitespace` because a
                  * user might put comments above the `let a = 1`.
                  * e.g.
                  * module Abc = {
                  *   /* comment 1 */
                  *
                  *   /* comment 2 */
                  *   let a = 1;
                  *
                  *  A Whitespace-node will automatically take care of the whitespace
                  *  interleaving between the comments.
                  *)
                 let newlines = if i > 0 then 1 else 0 in
                 let region = WhitespaceRegion.make ~range ~newlines () in
                 let firstLayout = Layout.Whitespace (region, x) in
                 (* the first layout node of every group taks care of the *
                    whitespace above a group*)
                 firstLayout :: List.map snd xs
               | [] -> [])
            groups
      in
      match items with
      | first :: rest ->
        List.concat (group (getLoc first) [] [] (first :: rest))
      | [] -> []

    let printer =
      object (self : 'self)
        val pipe = false
        val semi = false
        val inline_braces = false
        val preserve_braces = true

        (* *Mutable state* in the printer to keep track of all comments * Used
           when whitespace needs to be interleaved. * The printing algorithm
           needs to take the comments into account in between * two items, to
           correctly determine if there's whitespace between two items. * The
           ast doesn't know if there are comments between two items, since *
           comments are store separately. The location diff between two items *
           might indicate whitespace between the two. While in reality there are
           * comments filling that whitespace. The printer needs access to the
           comments * for this reason. * * Example: * 1| let a = 1; * 2| * 3| *
           4| let b = 2; * -> here we can just diff the locations between `let a
           = 1` and `let b = 2` * * 1| let a = 1; * 2| /* a comment */ * 3| /*
           another comment */ * 4| let b = 2; * -> here the location diff will
           result into false info if we don't include * the comments in the
           diffing *)
        val mutable comments = []
        method comments = comments
        method trackComment comment = comments <- comment :: comments

        (* The test and first branch of ternaries must be guarded *)
        method under_pipe = {<pipe = true>}
        method under_semi = {<semi = true>}
        method reset_semi = {<semi = false>}
        method reset_pipe = {<pipe = false>}
        method reset = {<pipe = false; semi = false>}
        method inline_braces = {<inline_braces = true>}
        method dont_preserve_braces = {<preserve_braces = false>}

        method reset_request_braces =
          {<inline_braces = false; preserve_braces = true>}

        method longident =
          function
          | Lident s -> protectIdentifier s
          | Ldot (longPrefix, s) ->
            protectLongIdentifier (self#longident longPrefix) s
          | Lapply (y, s) ->
            makeList [ self#longident y; atom "("; self#longident s; atom ")" ]

        (* This form allows applicative functors. *)
        method longident_class_or_type_loc x = self#longident x.txt

        (* TODO: Fail if observing applicative functors for this form. *)
        method longident_loc (x : Longident.t Location.loc) =
          source_map ~loc:x.loc (self#longident x.txt)

        method constant ?raw_literal ?(parens = true) =
          wrap (constant ?raw_literal ~parens)

        method constant_string_for_primitive =
          wrap constant_string_for_primitive

        method tyvar = wrap tyvar

        (* c ['a,'b] *)
        method class_params_def =
          function [] -> atom "" | l -> makeTup (List.map self#type_param l)

        (* This will fall through to the simple version. *)
        method non_arrowed_core_type x = self#non_arrowed_non_simple_core_type x

        method core_type2 x =
          let { Reason_attributes.stdAttrs; uncurried; _ } =
            Reason_attributes.partitionAttributes x.ptyp_attributes
          in
          let uncurried =
            uncurried
            ||
            try Hashtbl.find uncurriedTable x.ptyp_loc with
            | Not_found -> false
          in
          if stdAttrs != []
          then
            formatAttributed
              (self#non_arrowed_simple_core_type
                 { x with ptyp_attributes = [] })
              (self#attributes stdAttrs)
          else
            let x = if uncurried then { x with ptyp_attributes = [] } else x in
            match x.ptyp_desc with
            | Ptyp_arrow _ ->
              let rec allArrowSegments ?(uncurried = false) acc = function
                | { ptyp_desc = Ptyp_arrow (l, ct1, ct2)
                  ; ptyp_attributes = []
                  ; _
                  } ->
                  allArrowSegments
                    ~uncurried:false
                    ((l, ct1, false || uncurried) :: acc)
                    ct2
                | rhs ->
                  let rhs = self#core_type2 rhs in
                  let is_tuple typ =
                    match typ.ptyp_desc with Ptyp_tuple _ -> true | _ -> false
                  in
                  (match acc with
                  | [ (Nolabel, lhs, uncurried) ] when not (is_tuple lhs) ->
                    let t = self#non_arrowed_simple_core_type lhs in
                    let lhs =
                      if uncurried
                      then makeList ~wrap:("(. ", ")") ~postSpace:true [ t ]
                      else t
                    in
                    lhs, rhs
                  | acc ->
                    let params = List.rev_map self#type_with_label acc in
                    makeCommaBreakableListSurround "(" ")" params, rhs)
              in
              let lhs, rhs = allArrowSegments ~uncurried [] x in
              let normalized =
                makeList
                  ~preSpace:true
                  ~postSpace:true
                  ~inline:(true, true)
                  ~break:IfNeed
                  ~sep:(Sep "=>")
                  [ lhs; rhs ]
              in
              source_map ~loc:x.ptyp_loc normalized
            | Ptyp_poly (sl, ct) ->
              let ct = self#core_type ct in
              let poly =
                match sl with
                | [] -> ct
                | sl ->
                  makeList
                    ~break:IfNeed
                    ~postSpace:true
                    [ makeList
                        [ makeList
                            ~postSpace:true
                            (List.map (fun { txt; _ } -> self#tyvar txt) sl)
                        ; atom "."
                        ]
                    ; ct
                    ]
              in
              source_map ~loc:x.ptyp_loc poly
            | _ -> self#non_arrowed_core_type x

        (* Same as core_type2 but can be aliased *)
        method core_type x =
          let { Reason_attributes.stdAttrs; uncurried; _ } =
            Reason_attributes.partitionAttributes x.ptyp_attributes
          in
          let () =
            if uncurried then Hashtbl.add uncurriedTable x.ptyp_loc true
          in
          if stdAttrs != []
          then
            formatAttributed
              (self#non_arrowed_simple_core_type
                 { x with ptyp_attributes = [] })
              (self#attributes stdAttrs)
          else
            match x.ptyp_desc with
            | Ptyp_alias (ct, s) ->
              source_map
                ~loc:x.ptyp_loc
                (label
                   ~space:true
                   (self#core_type ct)
                   (makeList ~postSpace:true [ atom "as"; atom ("'" ^ s.txt) ]))
            | _ -> self#core_type2 x

        method type_with_label (lbl, c, uncurried) =
          let typ = self#core_type c in
          let t =
            match lbl with
            | Nolabel -> typ
            | Labelled lbl ->
              label ~space:true (atom (namedArgSym ^ lbl ^ ":")) typ
            | Optional lbl ->
              label
                ~space:true
                (atom (namedArgSym ^ lbl ^ ":"))
                (label typ (atom "=?"))
          in
          if uncurried then makeList ~postSpace:true [ atom "."; t ] else t

        method type_param (ct, (a, _)) =
          makeList [ atom (type_variance a); self#core_type ct ]

        (* According to the parse rule [type_declaration], the "type
           declaration"'s * physical location (as indicated by [td.ptype_loc])
           begins with the * identifier and includes the constraints. *)
        method formatOneTypeDef
          prepend
          name
          assignToken
          ({ ptype_params; ptype_kind; ptype_loc; _ } as td) =
          let equalInitiatedSegments, constraints =
            self#type_declaration_binding_segments td
          in
          let formattedTypeParams = List.map self#type_param ptype_params in
          let binding = makeList ~postSpace:true [ prepend; name ] in

          (* /-----------everythingButConstraints-------------- |
             -constraints--\ * /-innerL---|
             ------innerR--------------------------\ * /binding\ /typeparams\
             /--equalInitiatedSegments-\ * type name 'v1 'v1 = foo = private bar
             constraint a = b *)
          let labelWithParams =
            match formattedTypeParams with
            | [] -> binding
            | l -> label binding (makeTup l)
          in
          let everythingButConstraints =
            let nameParamsEquals =
              makeList ~postSpace:true [ labelWithParams; assignToken ]
            in
            match equalInitiatedSegments with
            | [] -> labelWithParams
            | _ :: _ :: _ :: _ ->
              raise (NotPossible "More than two type segments.")
            | hd :: [] ->
              formatAttachmentApplication
                typeApplicationFinalWrapping
                (Some (true, nameParamsEquals))
                (hd, None)
            | [ hd; hd2 ] ->
              let first =
                makeList
                  ~postSpace:true
                  ~break:IfNeed
                  ~inline:(true, true)
                  (hd @ [ atom "=" ])
              in
              (* Because we want a record as a label with the opening brace on the same line
               * and the closing brace indented at the beginning, we can't wrap it in a list here
               * Example:
               * type doubleEqualsRecord =
               *  myRecordWithReallyLongName = {   <- opening brace on the same line
               *    xx: int,
               *    yy: int
               *  };                               <- closing brace indentation
               *)
              let second =
                match ptype_kind with
                | Ptype_record _ -> List.hd hd2
                | _ ->
                  makeList
                    ~postSpace:true
                    ~break:IfNeed
                    ~inline:(true, true)
                    hd2
              in
              label
                ~space:true
                nameParamsEquals
                (label ~space:true first second)
          in
          let everything =
            match constraints with
            | [] -> everythingButConstraints
            | hd :: tl ->
              makeList
                ~break:IfNeed
                ~postSpace:true
                ~indent:0
                ~inline:(true, true)
                (everythingButConstraints :: hd :: tl)
          in
          source_map ~loc:ptype_loc everything

        method formatOneTypeExt prepend name assignToken te =
          let privateAtom = atom "pri" in
          let privatize scope lst =
            match scope with Public -> lst | Private -> privateAtom :: lst
          in
          let equalInitiatedSegments =
            let segments =
              List.map
                self#type_extension_binding_segments
                te.ptyext_constructors
            in
            let privatized_segments = privatize te.ptyext_private segments in
            [ makeList
                ~break:Always_rec
                ~postSpace:true
                ~inline:(true, true)
                privatized_segments
            ]
          in
          let formattedTypeParams = List.map self#type_param te.ptyext_params in
          let binding = makeList ~postSpace:true [ prepend; name ] in
          let labelWithParams =
            match formattedTypeParams with
            | [] -> binding
            | l -> label binding (makeTup l)
          in
          let everything =
            let nameParamsEquals =
              makeList ~postSpace:true [ labelWithParams; assignToken ]
            in
            formatAttachmentApplication
              typeApplicationFinalWrapping
              (Some (true, nameParamsEquals))
              (equalInitiatedSegments, None)
          in
          source_map ~loc:te.ptyext_path.loc everything

        method type_extension_binding_segments
          { pext_kind; pext_loc; pext_attributes; pext_name } =
          let normalize lst =
            match lst with
            | [] -> raise (NotPossible "should not be called")
            | [ hd ] -> hd
            | _ :: _ -> makeList lst
          in
          let add_bar name attrs args =
            let lbl =
              match args with None -> name | Some args -> label name args
            in
            if attrs != []
            then
              label
                ~space:true
                (makeList
                   ~postSpace:true
                   [ atom "|"
                   ; makeList
                       ~postSpace:true
                       ~break:Layout.IfNeed
                       ~inline:(true, true)
                       (self#attributes attrs)
                   ])
                lbl
            else makeList ~postSpace:true [ atom "|"; lbl ]
          in
          let sourceMappedName = atom ~loc:pext_name.loc pext_name.txt in
          let resolved =
            match pext_kind with
            | Pext_decl (_, ctor_args, gadt) ->
              let formattedArgs =
                match ctor_args with
                | Pcstr_tuple [] -> []
                | Pcstr_tuple args ->
                  [ makeTup
                      (List.map self#non_arrowed_non_simple_core_type args)
                  ]
                | Pcstr_record r ->
                  [ self#record_declaration ~wrap:("({", "})") r ]
              in
              let formattedGadt =
                match gadt with
                | None -> None
                | Some x ->
                  Some
                    (makeList
                       [ formatJustTheTypeConstraint (self#core_type x) ])
              in
              formattedArgs, formattedGadt
            (* type bar += Foo = Attr.Foo *)
            | Pext_rebind rebind ->
              let r = self#longident_loc rebind in
              (* we put an empty space before the '=': we don't have access to
                 the fact * that we need a space because of the Pext_rebind
                 later *)
              let prepend = atom " =" in
              [ makeList ~postSpace:true [ prepend; r ] ], None
          in
          (* * The first element of the tuple represents constructor arguments,
             * the second an optional formatted gadt. * * Case 1: No constructor
             arguments, neither a gadt * type attr = ..; * type attr += | Str *
             * Case 2: No constructor arguments, is a gadt * type attr = ..; *
             type attr += | Str :attr * * Case 3: Has Constructor args, not a
             gadt * type attr = ..; * type attr += | Str(string); * type attr +=
             | Point(int, int); * * Case 4: Has Constructor args & is a gadt *
             type attr = ..; * type attr += | Point(int, int) :attr; *)
          let everything =
            match resolved with
            | [], None -> add_bar sourceMappedName pext_attributes None
            | [], Some gadt ->
              add_bar sourceMappedName pext_attributes (Some gadt)
            | ctorArgs, None ->
              add_bar
                sourceMappedName
                pext_attributes
                (Some (normalize ctorArgs))
            | ctorArgs, Some gadt ->
              add_bar
                sourceMappedName
                pext_attributes
                (Some (normalize (ctorArgs @ [ gadt ])))
          in
          source_map ~loc:pext_loc everything

        (* shared by [Pstr_type, Psig_type]*)
        method type_def_list ?(eq_symbol = "=") ?extension rf l =
          (* As oposed to used in type substitution. *)
          let formatOneTypeDefStandard prepend td =
            let itm =
              self#formatOneTypeDef
                prepend
                (atom
                   ~loc:td.ptype_name.loc
                   (add_raw_identifier_prefix td.ptype_name.txt))
                (atom eq_symbol)
                td
            in
            let { Reason_attributes.stdAttrs; docAttrs; _ } =
              Reason_attributes.partitionAttributes
                ~partDoc:true
                td.ptype_attributes
            in
            let layout = self#attach_std_item_attrs stdAttrs itm in
            self#attachDocAttrsToLayout
              ~stdAttrs
              ~docAttrs
              ~loc:td.ptype_loc
              ~layout
              ()
          in

          match l with
          | [] -> raise (NotPossible "asking for type list of nothing")
          | hd :: tl ->
            let first =
              match rf with
              | Recursive ->
                let label = add_extension_sugar "type" extension in
                formatOneTypeDefStandard (atom label) hd
              | Nonrecursive -> formatOneTypeDefStandard (atom "type nonrec") hd
            in
            (match tl with
            (* Exactly one type *)
            | [] -> first
            | _ :: _ as typeList ->
              let items =
                (hd.ptype_loc, first)
                :: List.map
                     (fun ptyp ->
                        ( ptyp.ptype_loc
                        , formatOneTypeDefStandard (atom "and") ptyp ))
                     typeList
              in
              makeList
                ~indent:0
                ~inline:(true, true)
                ~break:Always_rec
                (groupAndPrint
                   ~xf:snd
                   ~getLoc:fst
                   ~comments:self#comments
                   items))

        method type_variant_list lst =
          match lst with
          | [] -> [ atom "|" ]
          | _ -> List.map (fun x -> self#type_variant_leaf x) lst

        method type_variant_leaf
          ?opt_ampersand:(a = false)
          ?polymorphic:(p = false) =
          self#type_variant_leaf1 a p true

        method type_variant_leaf_nobar
          ?opt_ampersand:(a = false)
          ?polymorphic:(p = false) =
          self#type_variant_leaf1 a p false

        (* TODOATTRIBUTES: Attributes on the entire variant leaf are likely *
           not parsed or printed correctly. *)
        method type_variant_leaf1 opt_ampersand polymorphic print_bar x =
          let { pcd_name; pcd_args; pcd_res; pcd_loc; pcd_attributes; _ } = x in
          let { Reason_attributes.stdAttrs; docAttrs; _ } =
            Reason_attributes.partitionAttributes ~partDoc:true pcd_attributes
          in
          let ampersand_helper i arg =
            let ct = self#core_type arg in
            let ct =
              match arg.ptyp_desc with
              | Ptyp_tuple _ -> ct
              | _ -> makeTup [ ct ]
            in
            if i == 0 && not opt_ampersand then ct else label (atom "&") ct
          in
          let args =
            match pcd_args with
            | Pcstr_record r -> [ self#record_declaration ~wrap:("({", "})") r ]
            | Pcstr_tuple [] -> []
            | Pcstr_tuple l when polymorphic -> List.mapi ampersand_helper l
            (* Here's why this works. With the new syntax, all the args, are
               already inside of a safely guarded place like Constructor(here,
               andHere). Compare that to the previous syntax Constructor here
               andHere. In the previous syntax, we needed to require that we
               print "non-arrowed" types for here, and andHere to avoid
               something like Constructor a=>b c=>d. In the new syntax, we don't
               care if here and andHere have unguarded arrow types like a=>b
               because they're safely separated by commas. *)
            | Pcstr_tuple l -> [ makeTup (List.map self#core_type l) ]
          in
          let gadtRes =
            match pcd_res with
            | None -> None
            | Some x -> Some (formatJustTheTypeConstraint (self#core_type x))
          in
          let normalize lst =
            match lst with
            | [] -> raise (NotPossible "should not be called")
            | [ hd ] -> hd
            | _ :: _ ->
              makeList ~inline:(true, true) ~break:IfNeed ~postSpace:true lst
          in
          let add_bar constructor =
            makeList
              ~postSpace:true
              (if print_bar then [ atom "|"; constructor ] else [ constructor ])
          in
          (* In some cases (e.g. inline records) we want the label with bar & the gadt resolution
           * as a list.
           *   | If {
           *       pred: expr bool,
           *       true_branch: expr 'a,
           *       false_branch: expr 'a
           *     }                           ==> end of label
           *     :expr 'a;                   ==> gadt res
           * The label & the gadt res form two separate units combined into a list.
           * This is necessary to properly align the closing '}' on the same height as the 'If'.
           *)
          let add_bar_2 ?gadt name args =
            let lbl = label name args in
            let fullLbl =
              match gadt with
              | Some g -> makeList ~inline:(true, true) ~break:IfNeed [ lbl; g ]
              | None -> lbl
            in
            add_bar fullLbl
          in

          let prefix = if polymorphic then "`" else "" in
          let sourceMappedName =
            atom ~loc:pcd_name.loc (prefix ^ pcd_name.txt)
          in
          let sourceMappedNameWithAttributes =
            let layout =
              match stdAttrs with
              | [] -> sourceMappedName
              | stdAttrs ->
                formatAttributed sourceMappedName (self#attributes stdAttrs)
            in
            match docAttrs with
            | [] -> layout
            | docAttrs ->
              makeList
                ~break:Always
                ~inline:(true, true)
                [ makeList (self#attributes docAttrs); layout ]
          in
          let constructorName =
            makeList ~postSpace:true [ sourceMappedNameWithAttributes ]
          in
          let everything =
            match args, gadtRes with
            | [], None -> add_bar sourceMappedNameWithAttributes
            | [], Some gadt -> add_bar_2 sourceMappedNameWithAttributes gadt
            | _ :: _, None -> add_bar_2 constructorName (normalize args)
            | _ :: _, Some gadt ->
              (match pcd_args with
              | Pcstr_record _ ->
                add_bar_2 ~gadt constructorName (normalize args)
              | _ -> add_bar_2 constructorName ~gadt (normalize args))
          in
          source_map ~loc:pcd_loc everything

        method record_declaration ?(wrap = "{", "}") ?assumeRecordLoc lbls =
          let recordRow pld =
            let hasPunning = recordRowIsPunned pld in
            let name =
              let name = add_raw_identifier_prefix pld.pld_name.txt in
              if hasPunning then [ atom name ] else [ atom name; atom ":" ]
            in
            let name = source_map ~loc:pld.pld_name.loc (makeList name) in
            let withMutable =
              match pld.pld_mutable with
              | Immutable -> name
              | Mutable -> makeList ~postSpace:true [ atom "mutable"; name ]
            in
            let recordRow =
              if hasPunning
              then label withMutable (atom "")
              else label ~space:true withMutable (self#core_type pld.pld_type)
            in
            let recordRow =
              match pld.pld_attributes with
              | [] -> recordRow
              | attrs ->
                let { Reason_attributes.stdAttrs; docAttrs; _ } =
                  Reason_attributes.partitionAttributes ~partDoc:true attrs
                in
                let stdAttrsLayout =
                  makeList
                    ~inline:(true, true)
                    ~postSpace:true
                    (self#attributes stdAttrs)
                in
                let docAttrsLayout =
                  makeList ~inline:(true, true) (self#attributes docAttrs)
                in
                let children =
                  match docAttrs, stdAttrs with
                  | [], [] -> [ recordRow ]
                  | _, [] -> [ docAttrsLayout; recordRow ]
                  | [], _ -> [ stdAttrsLayout; recordRow ]
                  | _, _ -> [ docAttrsLayout; stdAttrsLayout; recordRow ]
                in
                makeList ~inline:(true, true) ~break:Always_rec children
            in
            source_map ~loc:pld.pld_loc recordRow
          in
          let rows = List.map recordRow lbls in
          (* if a record type has more than 1 row, always break *)
          let break =
            match rows with
            | [] | [ _ ] -> Layout.IfNeed
            | _ -> Layout.Always_rec
          in
          source_map
            ?loc:assumeRecordLoc
            (makeList ~wrap ~sep:commaTrail ~postSpace:true ~break rows)

        (* Returns the type declaration partitioned into three segments - one
           suitable for appending to a label, the actual type manifest and the
           list of constraints. *)
        method type_declaration_binding_segments x =
          (* Segments of the type binding (occuring after the type keyword) that
           * should begin with "=". Zero to two total sections.
           * This is just a straightforward reverse mapping from the original parser:
           *  type_kind:
           *      /*empty*/
           *        { (Ptype_abstract, Public, None) }
           *    | EQUAL core_type
           *        { (Ptype_abstract, Public, Some $2) }
           *    | EQUAL PRIVATE core_type
           *        { (Ptype_abstract, Private, Some $3) }
           *    | EQUAL constructor_declarations
           *        { (Ptype_variant(List.rev $2), Public, None) }
           *    | EQUAL PRIVATE constructor_declarations
           *        { (Ptype_variant(List.rev $3), Private, None) }
           *    | EQUAL private_flag BAR constructor_declarations
           *        { (Ptype_variant(List.rev $4), $2, None) }
           *    | EQUAL DOTDOT
           *        { (Ptype_open, Public, None) }
           *    | EQUAL private_flag LBRACE label_declarations opt_comma RBRACE
           *        { (Ptype_record(List.rev $4), $2, None) }
           *    | EQUAL core_type EQUAL private_flag opt_bar constructor_declarations
           *        { (Ptype_variant(List.rev $6), $4, Some $2) }
           *    | EQUAL core_type EQUAL DOTDOT
           *        { (Ptype_open, Public, Some $2) }
           *    | EQUAL core_type EQUAL private_flag LBRACE label_declarations opt_comma RBRACE
           *        { (Ptype_record(List.rev $6), $4, Some $2) }
           *)
          let privateAtom = atom "pri" in
          let privatize scope lst =
            match scope with Public -> lst | Private -> privateAtom :: lst
          in

          let estimateRecordOpenBracePoint () =
            match x.ptype_params with
            | [] -> x.ptype_name.loc.loc_end
            | _ ->
              (fst (List.nth x.ptype_params (List.length x.ptype_params - 1)))
                .ptyp_loc
                .loc_end
          in

          let equalInitiatedSegments =
            match x.ptype_kind, x.ptype_private, x.ptype_manifest with
            (* /*empty*/ {(Ptype_abstract, Public, None)} *)
            | Ptype_abstract, Public, None -> []
            (* EQUAL core_type {(Ptype_abstract, Public, Some _)} *)
            | Ptype_abstract, Public, Some y -> [ [ self#core_type y ] ]
            (* EQUAL PRIVATE core_type {(Ptype_abstract, Private, Some $3)} *)
            | Ptype_abstract, Private, Some y ->
              [ [ privateAtom; self#core_type y ] ]
            (* EQUAL constructor_declarations {(Ptype_variant _., Public, None)} *)
            (* This case is redundant *)
            (* | (Ptype_variant lst, Public, None) -> [ *)
            (*     [makeSpacedBreakableInlineList (List.map type_variant_leaf lst)] *)
            (*   ] *)
            (* EQUAL PRIVATE constructor_declarations {(Ptype_variant _, Private, None)} *)
            | Ptype_variant lst, Private, None ->
              [ [ privateAtom
                ; makeList
                    ~break:IfNeed
                    ~postSpace:true
                    ~inline:(true, true)
                    (self#type_variant_list lst)
                ]
              ]
            (* EQUAL private_flag BAR constructor_declarations {(Ptype_variant
               _, $2, None)} *)
            | Ptype_variant lst, scope, None ->
              [ privatize
                  scope
                  [ makeList
                      ~break:Always_rec
                      ~postSpace:true
                      ~inline:(true, true)
                      (self#type_variant_list lst)
                  ]
              ]
            (* EQUAL DOTDOT {(Ptype_open, Public, None)} *)
            | Ptype_open, Public, None -> [ [ atom ".." ] ]
            | Ptype_open, Private, None -> [ [ privateAtom; atom ".." ] ]
            (* Super confusing how record/variants' manifest is not actually the
               description of the structure. What's in the manifest in that case
               is the *second* EQUALS asignment. *)
            (* EQUAL private_flag LBRACE label_declarations opt_comma RBRACE
               {(Ptype_record _, $2, None)} *)
            | Ptype_record lst, scope, None ->
              let assumeRecordLoc =
                { loc_start = estimateRecordOpenBracePoint ()
                ; loc_end = x.ptype_loc.loc_end
                ; loc_ghost = false
                }
              in
              [ privatize scope [ self#record_declaration ~assumeRecordLoc lst ]
              ]
            (* And now all of the forms involving *TWO* equals *)
            (* Again, super confusing how manifests of variants/records
               represent the structure after the second equals. *)
            (* ================================================*)

            (* EQUAL core_type EQUAL private_flag opt_bar
               constructor_declarations { (Ptype_variant _, _, Some _)} *)
            | Ptype_variant lst, scope, Some mani ->
              [ [ self#core_type mani ]
              ; (let variant =
                   makeList
                     ~break:IfNeed
                     ~postSpace:true
                     ~inline:(true, true)
                     (self#type_variant_list lst)
                 in
                 privatize scope [ variant ])
              ]
            (* EQUAL core_type EQUAL DOTDOT {(Ptype_open, Public, Some $2)} *)
            | Ptype_open, Public, Some mani ->
              [ [ self#core_type mani ]; [ atom ".." ] ]
            (* EQUAL core_type EQUAL private_flag LBRACE label_declarations
               opt_comma RBRACE {(Ptype_record _, $4, Some $2)} *)
            | Ptype_record lst, scope, Some mani ->
              let declaration = self#record_declaration lst in
              let record =
                match scope with
                | Public -> [ declaration ]
                | Private -> [ label ~space:true privateAtom declaration ]
              in
              [ [ self#core_type mani ]; record ]
            (* Everything else is impossible *)
            (* ================================================*)
            | _, _, _ ->
              raise (NotPossible "Encountered impossible type specification")
          in

          let makeConstraint (ct1, ct2, _) =
            let constraintEq =
              makeList
                ~postSpace:true
                [ atom "constraint"; self#core_type ct1; atom "=" ]
            in
            label ~space:true constraintEq (self#core_type ct2)
          in
          let constraints = List.map makeConstraint x.ptype_cstrs in
          equalInitiatedSegments, constraints

        (* "non-arrowed" means "a type where all arrows are inside at least one
           level of parens" * * z => z: not a "non-arrowed" type. * (a, b): a
           "non-arrowed" type. * (z=>z): a "non-arrowed" type because the arrows
           are guarded by parens. * * A "non arrowed, non simple" type would be
           one that is not-arrowed, and also * not "simple". Simple means it is
           "clearly one unit" like (a, b), identifier, * "hello", None. *)
        method non_arrowed_non_simple_core_type x =
          let { Reason_attributes.stdAttrs; _ } =
            Reason_attributes.partitionAttributes x.ptyp_attributes
          in
          if stdAttrs != []
          then
            formatAttributed
              (self#non_arrowed_simple_core_type
                 { x with ptyp_attributes = [] })
              (self#attributes stdAttrs)
          else
            match x.ptyp_desc with
            (* This significantly differs from the standard OCaml
               printer/parser: Type constructors are no longer simple *)
            | _ -> self#non_arrowed_simple_core_type x

        method type_param_list_element =
          function
          | { ptyp_attributes = []; ptyp_desc = Ptyp_package (lid, cstrs); _ }
            ->
            self#typ_package ~mod_prefix:true lid cstrs
          | t -> self#core_type t

        method non_arrowed_simple_core_type x =
          let { Reason_attributes.stdAttrs; _ } =
            Reason_attributes.partitionAttributes x.ptyp_attributes
          in
          if stdAttrs != []
          then
            formatSimpleAttributed
              (self#non_arrowed_simple_core_type
                 { x with ptyp_attributes = [] })
              (self#attributes stdAttrs)
          else
            let result =
              match x.ptyp_desc with
              (*   LPAREN core_type_comma_list RPAREN %prec below_NEWDOT *)
              (*       { match $2 with *)
              (*         | [] -> raise Parse_error *)
              (*         | one::[] -> one *)
              (*         | moreThanOne -> mktyp(Ptyp_tuple(List.rev moreThanOne)) } *)
              | Ptyp_tuple l ->
                makeTup (List.map self#type_param_list_element l)
              | Ptyp_object (l, o) -> self#unparseObject l o
              | Ptyp_package (lid, cstrs) ->
                self#typ_package ~protect:true ~mod_prefix:true lid cstrs
              (*   | QUOTE ident *)
              (*       { mktyp(Ptyp_var $2) } *)
              | Ptyp_var s -> ensureSingleTokenSticksToLabel (self#tyvar s)
              (*   | UNDERSCORE *)
              (*       { mktyp(Ptyp_any) } *)
              | Ptyp_any -> ensureSingleTokenSticksToLabel (atom "_")
              (*   | type_longident *)
              (*       { mktyp(Ptyp_constr(mkrhs $1 1, [])) } *)
              | Ptyp_constr (li, []) ->
                (* [ensureSingleTokenSticksToLabel] loses location information
                   which is important when you are embedded inside a list and
                   comments are to be interleaved around you. Therefore, we wrap
                   the result in the correct [SourceMap]. *)
                source_map
                  ~loc:li.loc
                  (ensureSingleTokenSticksToLabel (self#longident_loc li))
              | Ptyp_constr (li, l) ->
                (match l with
                | [ { ptyp_desc = Ptyp_object ((_ :: _ as l), o); _ } ]
                  when isJsDotTLongIdent li.txt ->
                  (* should have one or more rows, Js.t({..}) should print as Js.t({..})
                   * {..} has a totally different meaning than Js.t({..}) *)
                  self#unparseObject ~withStringKeys:true l o
                | [ { ptyp_desc = Ptyp_object (l, o); _ } ]
                  when not (isJsDotTLongIdent li.txt) ->
                  label
                    (self#longident_loc li)
                    (self#unparseObject ~wrap:("(", ")") l o)
                | [ { ptyp_desc =
                        Ptyp_constr
                          ( lii
                          , [ { ptyp_desc = Ptyp_object ((_ :: _ as ll), o); _ }
                            ] )
                    ; _
                    }
                  ]
                  when isJsDotTLongIdent lii.txt ->
                  label
                    (self#longident_loc li)
                    (self#unparseObject
                       ~withStringKeys:true
                       ~wrap:("(", ")")
                       ll
                       o)
                | _ ->
                  (* small guidance: in `type foo = bar`, we're now at the `bar`
                     part *)

                  (* The single identifier has to be wrapped in a
                     [ensureSingleTokenSticksToLabel] to avoid (@see
                     @avoidSingleTokenWrapping): *)
                  label
                    (self#longident_loc li)
                    (makeTup (List.map self#type_param_list_element l)))
              | Ptyp_variant (l, closed, low) ->
                let pcd_attributes = x.ptyp_attributes in
                let pcd_res = None in
                let variant_helper i rf =
                  match rf.prf_desc with
                  | Rtag (label, opt_ampersand, ctl) ->
                    let label =
                      { label with txt = add_raw_identifier_prefix label.txt }
                    in
                    let pcd_args = Pcstr_tuple ctl in
                    let all_attrs =
                      List.concat [ pcd_attributes; rf.prf_attributes ]
                    in
                    self#type_variant_leaf
                      ~opt_ampersand
                      ~polymorphic:true
                      { pcd_name = label
                      ; pcd_args
                      ; pcd_res
                      ; pcd_loc = label.loc
                      ; pcd_attributes = all_attrs
                      ; pcd_vars = []
                      }
                  | Rinherit ct ->
                    (* '| type' is required if the Rinherit is not the first
                       row_field in the list *)
                    if i = 0
                    then self#core_type ct
                    else
                      makeList ~postSpace:true [ atom "|"; self#core_type ct ]
                in
                let designator, tl =
                  match closed, low with
                  | Closed, None -> "", []
                  | Closed, Some tl -> "<", tl
                  | Open, _ -> ">", []
                in
                let node_list = List.mapi variant_helper l in
                let ll = List.map (fun t -> atom ("`" ^ t)) tl in
                let tag_list =
                  makeList ~postSpace:true ~break:IfNeed (atom ">" :: ll)
                in
                let type_list =
                  if tl != [] then node_list @ [ tag_list ] else node_list
                in
                let break =
                  match type_list with
                  | _ :: _ :: _ -> Layout.Always_rec
                  | [] | _ :: [] -> IfNeed
                in
                makeList
                  ~wrap:("[" ^ designator, "]")
                  ~pad:(true, false)
                  ~postSpace:true
                  ~break
                  type_list
              | Ptyp_class (li, []) ->
                makeList [ atom "#"; self#longident_loc li ]
              | Ptyp_class (li, l) ->
                label
                  (makeList [ atom "#"; self#longident_loc li ])
                  (makeTup (List.map self#core_type l))
              | Ptyp_extension e -> self#extension e
              | Ptyp_arrow (_, _, _) | Ptyp_alias (_, _) | Ptyp_poly (_, _) ->
                makeList ~wrap:("(", ")") ~break:IfNeed [ self#core_type x ]
              | Ptyp_open (m, ct) ->
                label
                  (label (self#longident m.txt) (atom "."))
                  (self#core_type ct)
            in
            source_map ~loc:x.ptyp_loc result
        (* TODO: ensure that we have a form of desugaring that protects *)
        (* when final argument of curried pattern is a type constraint: *)
        (* | COLON non_arrowed_core_type EQUALGREATER expr { mkexp_constraint $4
           (Some $2, None) } *)
        (*                         \----/   \--/
         *                         constraint coerce
         *
         *                         Creates a ghost expression:
         *                         mkexp_constraint | Some t, None -> ghexp(Pexp_constraint(e, t))
         *)

        method pattern_list_split_cons acc =
          function
          | { ppat_desc =
                Ppat_construct
                  ( { txt = Lident "::"; _ }
                  , Some ([], { ppat_desc = Ppat_tuple [ pat1; pat2 ]; _ }) )
            ; _
            } ->
            self#pattern_list_split_cons (pat1 :: acc) pat2
          | p -> List.rev acc, p

        (* Adds parens to the right sub-tree when it is not a single node: * * A
           | B is formatted as A | B * A | (B | C) is formatted as A | (B | C) *
           * Also, adds parens to both sub-trees when both of them * are not a
           single node: * (A | B) | (C | D) is formatted as A | B | (C | D) * A
           | B | (C | D) is formatted as A | B | (C | D) * (A | B) | C is
           formatted as A | B | C * A | B | C is formatted as A | B | C * *)
        method or_pattern p1 p2 =
          let p1_raw, p2_raw = self#pattern p1, self#pattern p2 in
          let left, right =
            match p2.ppat_desc with
            | Ppat_or _ -> p1_raw, formatPrecedence p2_raw
            | _ -> p1_raw, p2_raw
          in
          makeList
            ~break:IfNeed
            ~inline:(true, true)
            ~sep:(Sep "|")
            ~postSpace:true
            ~preSpace:true
            [ left; right ]

        method pattern_with_precedence ?(attrs = []) p =
          let raw_pattern = self#pattern p in
          match p.ppat_desc, attrs with
          | Ppat_or (p1, p2), _ -> formatPrecedence (self#or_pattern p1 p2)
          | Ppat_constraint _, _ | _, _ :: _ ->
            makeList ~wrap:("(", ")") [ raw_pattern ]
          | _, [] -> raw_pattern

        (* Renders level 3 or simpler patterns:
         *
         * Simpler
         * ^   -----------
         * |   1.     [ ], { }, X.{  }, ident, (any-other-pattern-with-parens-around)
         * |   2.     F(args), lazy(foo), [@attr] 1-2
         * |   3.     pat as alias, pat | pat
         * |   4.     1-3 : typ
         * v   ------------
         * Complex
         *
         * Assumes visually rendered attributes have already been rendered.
         *)
        method pattern_at_least_as_simple_as_alias_or_or x =
          let { Reason_attributes.arityAttrs = _; stdAttrs; _ } =
            Reason_attributes.partitionAttributes x.ppat_attributes
          in
          match stdAttrs, x.ppat_desc with
          | [], Ppat_or (p1, p2) -> self#or_pattern p1 p2
          | [], Ppat_alias (p, s) ->
            let pattern_with_precedence = self#pattern_with_precedence p in
            label
              ~space:true
              (source_map ~loc:p.ppat_loc pattern_with_precedence)
              (makeList
                 ~postSpace:true
                 [ atom "as"; source_map ~loc:s.loc (protectIdentifier s.txt) ])
            (* RA*)
          | _ -> self#pattern_at_least_as_simple_as_application x

        (* Formats a pattern that is a least as "simple" as function application
         * style syntax. Produces formatting that is as simple as either 1 or 2.
         *
         * Simpler
         * ^   -----------
         * |   1.     [ ], { }, X.{  }, ident, (any-other-pattern-with-parens-around)
         * |   2.     F(args), lazy(foo), [@attr] 1-2
         * |   3.     pat as alias, pat | pat
         * |   4.     1-3 : typ
         * v   ------------
         * Complex
         *
         *
         * 1. and 2. do not need parens around them in order to apply attributes to
         * them. 3. does need parens around it to apply attributes to the whole
         * pattern.
         *
         * Assumes visually rendered attributes have already been rendered.
         *)
        method pattern_at_least_as_simple_as_application x =
          (* TODOATTRIBUTES: Handle the stdAttrs here *)
          let { Reason_attributes.stdAttrs; arityAttrs; _ } =
            Reason_attributes.partitionAttributes x.ppat_attributes
          in
          let formattedPattern =
            match x.ppat_desc with
            | Ppat_variant (l, Some p) ->
              if arityAttrs != []
              then
                raise
                  (NotPossible
                     "Should never see embedded attributes on poly variant")
              else
                source_map
                  ~loc:x.ppat_loc
                  (self#constructor_pattern
                     (atom ("`" ^ l))
                     p
                     ~polyVariant:true
                     ~arityIsClear:true)
            | Ppat_lazy p ->
              label (atom "lazy") (formatPrecedence (self#simple_pattern p))
            | Ppat_construct
                ({ txt = Lident (("true" | "false") as txt); _ }, None) ->
              atom txt
            | Ppat_construct (({ txt; _ } as li), po)
              when not (txt = Lident "::") ->
              (* FIXME The third field always false *)
              let formattedConstruction =
                match po with
                (* TODO: Check the explicit_arity field on the
                   pattern/constructor attributes to determine if should desugar
                   to an *actual* tuple. *)
                (* | Some ({ *)
                (*   ppat_desc=Ppat_tuple l; *)
                (*   ppat_attributes=[{txt="explicit_arity"; loc}] *)
                (* }) -> *)
                (* label ~space:true (self#longident_loc li)
                   (makeSpacedBreakableInlineList (List.map self#simple_pattern
                   l)) *)
                | Some (_, pattern) ->
                  let arityIsClear = isArityClear arityAttrs in
                  self#constructor_pattern
                    ~arityIsClear
                    (self#longident_loc li)
                    pattern
                | None -> self#longident_loc li
              in
              source_map ~loc:x.ppat_loc formattedConstruction
            | _ -> self#simple_pattern { x with ppat_attributes = arityAttrs }
          in
          if stdAttrs != []
          then formatAttributed formattedPattern (self#attributes stdAttrs)
          else formattedPattern

        (* Format a pattern with no particular requirements of simplicity. For example when
         * formatting a pattern *inside* one tuple position:
         *        |
         *        v
         * let (x : int, foo) = ..
         *
         *
         * Renders level 3 or simpler patterns:
         *
         * Simpler
         * ^   -----------
         * |   1.     [ ], { }, X.{  }, ident, (any-other-pattern-with-parens-around)
         * |   2.     F(args), lazy(foo), [@attr] 1-2
         * |   3.     pat as alias, pat | pat
         * |   4.     1-3 : typ
         * v   ------------
         * Complex
         *
         * Assumes visually rendered attributes have already been rendered.
         *)
        method pattern x =
          let { Reason_attributes.arityAttrs = _; stdAttrs; _ } =
            Reason_attributes.partitionAttributes x.ppat_attributes
          in
          match stdAttrs, x.ppat_desc with
          | [], Ppat_constraint (p, ct) ->
            let pat, typ =
              match p, ct with
              | ( { ppat_desc = Ppat_unpack unpack; _ }
                , { ptyp_desc = Ptyp_package (lid, cstrs); _ } ) ->
                let unpack =
                  match unpack.txt with None -> "_" | Some unpack -> unpack
                in
                ( makeList ~postSpace:true [ atom "module"; atom unpack ]
                , self#typ_package ~mod_prefix:false lid cstrs )
              | _ ->
                (* Have to call pattern_at_least_as_simple_as_alias_or_or
                   because * we don't want to allow *another* nested type
                   annotation without * first adding parens *)
                ( self#pattern_at_least_as_simple_as_alias_or_or p
                , self#core_type ct )
            in
            formatTypeConstraint pat typ
          | _ -> self#pattern_at_least_as_simple_as_alias_or_or x

        method patternList ?(wrap = "", "") pat =
          let pat_list, pat_last = self#pattern_list_split_cons [] pat in
          let pat_list = List.map self#pattern pat_list in
          match pat_last with
          | { ppat_desc = Ppat_construct ({ txt = Lident "[]"; _ }, _); _ } ->
            (* [x,y,z] *)
            let lwrap, rwrap = wrap in
            makeList
              pat_list
              ~break:Layout.IfNeed
              ~sep:commaTrail
              ~postSpace:true
              ~wrap:(lwrap ^ "[", "]" ^ rwrap)
          | _ ->
            (* x::y *)
            makeES6List pat_list (self#pattern pat_last) ~wrap

        (* In some contexts the Ptyp_package needs to be protected by parens, or
           * the `module` keyword needs to be added. * Example: let f = (module
           Add: S.Z, x) => Add.add(x); * It's clear that `S.Z` is a module
           because it constraints the * `module Add` pattern. No need to add
           "module" before `S.Z`. * * Example2: * type t = (module Console); *
           In this case the "module" keyword needs to be printed to indicate *
           usage of a first-class-module. *)
        method typ_package ?(protect = false) ?(mod_prefix = true) lid cstrs =
          let packageIdent =
            let packageIdent = self#longident_loc lid in
            if mod_prefix
            then makeList ~postSpace:true [ atom "module"; packageIdent ]
            else packageIdent
          in
          let unwrapped_layout =
            match cstrs with
            | [] -> packageIdent
            | cstrs ->
              label
                ~space:true
                (makeList ~postSpace:true [ packageIdent; atom "with" ])
                (makeList
                   ~inline:(true, true)
                   ~break:IfNeed
                   ~sep:(Sep " and ")
                   (List.map
                      (fun (s, ct) ->
                         label
                           ~space:true
                           (makeList
                              ~break:IfNeed
                              ~postSpace:true
                              [ atom "type"; self#longident_loc s; atom "=" ])
                           (self#core_type ct))
                      cstrs))
          in
          if protect
          then makeList ~postSpace:true ~wrap:("(", ")") [ unwrapped_layout ]
          else unwrapped_layout

        method simple_pattern x =
          let { Reason_attributes.arityAttrs; stdAttrs; _ } =
            Reason_attributes.partitionAttributes x.ppat_attributes
          in
          if stdAttrs != []
          then
            formatSimpleAttributed
              (self#simple_pattern { x with ppat_attributes = arityAttrs })
              (self#attributes stdAttrs)
          else
            let itm =
              match x.ppat_desc with
              | Ppat_construct
                  ( { loc; txt = Lident (("()" | "[]" | "true" | "false") as x) }
                  , _ ) ->
                (* Patterns' locations might include a leading bar depending on
                   the * context it was parsed in. Therefore, we need to include
                   further * information about the contents of the pattern such
                   as tokens etc, * in order to get comments to be distributed
                   correctly.*)
                atom ~loc x
              | Ppat_construct ({ txt = Lident "::"; _ }, _) ->
                self#patternList x (* LIST PATTERN *)
              | Ppat_construct (li, None) ->
                source_map ~loc:x.ppat_loc (self#longident_loc li)
              | Ppat_any -> atom "_"
              | Ppat_var { loc; txt } ->
                (* To prevent this: * * let oneArgShouldWrapToAlignWith *
                   theFunctionNameBinding => theFunctionNameBinding; * * And
                   instead do: * * let oneArgShouldWrapToAlignWith *
                   theFunctionNameBinding => theFunctionNameBinding; * * We have
                   to do something to the non "listy" patterns. Non listy *
                   patterns don't indent the same amount as listy patterns when
                   docked * to a label. * * If wrapping the non-listy pattern in
                   [ensureSingleTokenSticksToLabel] * you'll get the following
                   (even though it should wrap) * * let
                   oneArgShouldWrapToAlignWith theFunctionNameBinding =>
                   theFunctionNameBinding; *)
                source_map ~loc (protectIdentifier txt)
              | Ppat_array l -> self#patternArray l
              | Ppat_unpack s ->
                let s = match s.txt with None -> "_" | Some s -> s in
                makeList
                  ~wrap:("(", ")")
                  ~break:IfNeed
                  ~postSpace:true
                  [ atom "module"; atom s ]
              | Ppat_open (lid, pat) ->
                (* let someFn Qualified.{ record } = ... *)
                let needsParens =
                  match pat.ppat_desc with
                  | Ppat_exception _ -> true
                  | _ -> false
                in
                let pat = self#simple_pattern pat in
                label
                  (label (self#longident_loc lid) (atom "."))
                  (if needsParens then formatPrecedence pat else pat)
              | Ppat_type li -> makeList [ atom "#"; self#longident_loc li ]
              | Ppat_record (l, closed) -> self#patternRecord l closed
              | Ppat_tuple l -> self#patternTuple l
              | Ppat_constant c ->
                let raw_literal, _ =
                  Reason_attributes.extract_raw_literal x.ppat_attributes
                in
                self#constant ?raw_literal c
              | Ppat_interval (c1, c2) ->
                makeList
                  ~postSpace:true
                  [ self#constant c1; atom ".."; self#constant c2 ]
              | Ppat_variant (l, None) -> makeList [ atom "`"; atom l ]
              | Ppat_constraint _ -> formatPrecedence (self#pattern x)
              | Ppat_lazy p ->
                formatPrecedence
                  (label
                     (atom "lazy")
                     (formatPrecedence (self#simple_pattern p)))
              | Ppat_extension e -> self#extension e
              | Ppat_exception p ->
                (* An exception pattern with an alias should be wrapped in (...)
                   * The rules for what goes to the right of the exception are a
                   little (too) nuanced. * It accepts "non simple" parameters,
                   except in the case of `as`. * Here we consistently apply
                   "simplification" to the exception argument. * Example: * |
                   exception (Sys_error _ as exc) => raise exc * parses
                   correctly while * | Sys_error _ as exc => raise exc * results
                   in incorrect parsing with type error otherwise. *)
                makeList
                  ~postSpace:true
                  [ atom "exception"; self#simple_pattern p ]
              | _ -> formatPrecedence (self#pattern x)
              (* May have a redundant sourcemap *)
            in
            source_map ~loc:x.ppat_loc itm

        method label_exp lbl opt pat =
          let term = self#pattern pat in
          let param =
            match lbl with
            | Nolabel -> term
            | (Labelled lbl | Optional lbl)
              when is_punned_labelled_pattern_no_attrs pat lbl ->
              makeList [ atom namedArgSym; term ]
            | Labelled lbl | Optional lbl ->
              let lblLayout =
                makeList
                  ~sep:(Sep " ")
                  ~break:Layout.Never
                  [ atom (namedArgSym ^ lbl); atom "as" ]
              in
              label lblLayout ~space:true term
          in
          match opt, lbl with
          | None, Optional _ -> makeList [ param; atom "=?" ]
          | None, _ -> param
          | Some o, _ ->
            makeList
              [ param; atom "="; self#unparseProtectedExpr ~forceParens:true o ]

        method access op cls e1 e2 =
          makeList
            [ (* Important that this be not breaking - at least to preserve same
                 behavior as stock desugarer. It might even be required (double
                 check in parser.mly) *)
              e1
            ; atom op
            ; e2
            ; atom cls
            ]

        method simple_get_application x =
          let { Reason_attributes.stdAttrs; jsxAttrs; _ } =
            Reason_attributes.partitionAttributes x.pexp_attributes
          in
          match x.pexp_desc, stdAttrs, jsxAttrs with
          | _, _ :: _, [] -> None (* Has some printed attributes - not simple *)
          | Pexp_apply ({ pexp_desc = Pexp_ident loc; _ }, l), [], _jsx :: _ ->
            (* TODO: Soon, we will allow the final argument to be an identifier
               which represents the entire list. This would be written as
               `<tag>...list</tag>`. If you imagine there being an implicit []
               inside the tag, then it would be consistent with array spread:
               [...list] evaluates to the thing as list. *)
            let hasLabelledChildrenLiteral =
              List.exists
                (function Labelled "children", _ -> true | _ -> false)
                l
            in
            let rec hasSingleNonLabelledUnitAndIsAtTheEnd l =
              match l with
              | [] -> false
              | ( Nolabel
                , { pexp_desc = Pexp_construct ({ txt = Lident "()"; _ }, _)
                  ; _
                  } )
                :: [] ->
                true
              | (Nolabel, _) :: _ -> false
              | _ :: rest -> hasSingleNonLabelledUnitAndIsAtTheEnd rest
            in
            if
              hasLabelledChildrenLiteral
              && hasSingleNonLabelledUnitAndIsAtTheEnd l
            then
              match loc.txt with
              | Ldot (moduleLid, "createElement") ->
                Some
                  (self#formatJSXComponent
                     (String.concat "." (Longident.flatten_exn moduleLid))
                     l)
              | lid ->
                Some
                  (self#formatJSXComponent
                     (String.concat "." (Longident.flatten_exn lid))
                     l)
            else None
          | ( Pexp_apply
                ( { pexp_desc =
                      Pexp_letmodule
                        ( _
                        , ({ pmod_desc = Pmod_apply _; _ } as app)
                        , { pexp_desc = Pexp_ident loc; _ } )
                  ; _
                  }
                , l )
            , []
            , _jsx :: _ ) ->
            (* TODO: Soon, we will allow the final argument to be an identifier
               which represents the entire list. This would be written as
               `<tag>...list</tag>`. If you imagine there being an implicit []
               inside the tag, then it would be consistent with array spread:
               [...list] evaluates to the thing as list. *)
            let rec extract_apps args = function
              | { pmod_desc = Pmod_apply (m1, { pmod_desc = Pmod_ident loc; _ })
                ; _
                } ->
                let arg = String.concat "." (Longident.flatten_exn loc.txt) in
                extract_apps (arg :: args) m1
              | { pmod_desc = Pmod_ident loc; _ } ->
                String.concat "." (Longident.flatten_exn loc.txt) :: args
              | _ ->
                failwith
                  "Functors in JSX tags support only module names as parameters"
            in
            let hasLabelledChildrenLiteral =
              List.exists
                (function Labelled "children", _ -> true | _ -> false)
                l
            in
            let rec hasSingleNonLabelledUnitAndIsAtTheEnd l =
              match l with
              | [] -> false
              | ( Nolabel
                , { pexp_desc = Pexp_construct ({ txt = Lident "()"; _ }, _)
                  ; _
                  } )
                :: [] ->
                true
              | (Nolabel, _) :: _ -> false
              | _ :: rest -> hasSingleNonLabelledUnitAndIsAtTheEnd rest
            in
            if
              hasLabelledChildrenLiteral
              && hasSingleNonLabelledUnitAndIsAtTheEnd l
            then
              match Longident.flatten_exn loc.txt with
              | [] | [ _ ] ->
                Some (self#formatJSXComponent (Longident.last_exn loc.txt) l)
              | _ ->
                if Longident.last_exn loc.txt = "createElement"
                then
                  match extract_apps [] app with
                  | ftor :: args ->
                    let applied = ftor ^ "(" ^ String.concat ", " args ^ ")" in
                    Some
                      (self#formatJSXComponent
                         ~closeComponentName:ftor
                         applied
                         l)
                  | _ -> None
                else None
            else None
          | _ -> None

        method sugar_set_expr_parts e =
          if e.pexp_attributes != []
          then None (* should also check attributes underneath *)
          else
            match e.pexp_desc with
            | Pexp_apply
                ( { pexp_desc =
                      Pexp_ident { txt = Ldot (Lident "Array", "set"); _ }
                  ; _
                  }
                , [ (_, e1); (_, e2); (_, e3) ] ) ->
              let prec = Custom "prec_lbracket" in
              let lhs =
                self#unparseResolvedRule
                  (self#ensureExpression ~reducesOnToken:prec e1)
              in
              Some (self#access "[" "]" lhs (self#unparseExpr e2), e3)
            | Pexp_apply
                ( { pexp_desc =
                      Pexp_ident { txt = Ldot (Lident "String", "set"); _ }
                  ; _
                  }
                , [ (_, e1); (_, e2); (_, e3) ] ) ->
              let prec = Custom "prec_lbracket" in
              let lhs =
                self#unparseResolvedRule
                  (self#ensureExpression ~reducesOnToken:prec e1)
              in
              Some (self#access ".[" "]" lhs (self#unparseExpr e2), e3)
            | Pexp_apply
                ( { pexp_desc =
                      Pexp_ident
                        { txt = Ldot (Ldot (Lident "Bigarray", array), "set")
                        ; _
                        }
                  ; _
                  }
                , label_exprs ) ->
              (match array with
              | "Genarray" ->
                (match label_exprs with
                | [ (_, a); (_, { pexp_desc = Pexp_array ls; _ }); (_, c) ] ->
                  let formattedList = List.map self#unparseExpr ls in
                  let lhs =
                    makeList
                      [ self#simple_enough_to_be_lhs_dot_send a; atom "." ]
                  in
                  let rhs =
                    makeList
                      ~break:IfNeed
                      ~postSpace:true
                      ~sep:commaSep
                      ~wrap:("{", "}")
                      formattedList
                  in
                  Some (label lhs rhs, c)
                | _ -> None)
              | "Array1" | "Array2" | "Array3" ->
                (match label_exprs with
                | (_, a) :: rest ->
                  (match List.rev rest with
                  | (_, v) :: rest ->
                    let args = List.map snd (List.rev rest) in
                    let formattedList = List.map self#unparseExpr args in
                    let lhs =
                      makeList
                        [ self#simple_enough_to_be_lhs_dot_send a; atom "." ]
                    in
                    let rhs =
                      makeList
                        ~break:IfNeed
                        ~postSpace:true
                        ~sep:commaSep
                        ~wrap:("{", "}")
                        formattedList
                    in
                    Some (label lhs rhs, v)
                  | _ -> assert false)
                | _ -> assert false)
              | _ -> None)
            | _ -> None
        (** Detects "sugar expressions" (sugar for array/string setters) and
            returns their separate parts. *)

        (* How would we know not to print the sequence without { }; protecting the let a?
         *
         *                        let a
         *                         |
         *                       sequence
         *                      /        \
         *                let a           print a
         *                alert a
         * let res = {
         *   let a = something();
         *   {                     \
         *     alert(a);           | portion to be parsed as a sequence()
         *     let a = 20;         | The final ; print(a) causes the entire
         *     alert(a);           | portion to be parsed as a sequence()
         *   };                    |
         *   print (a);            /
         * }
         *
         * ******************************************************************
         * Any time the First expression of a sequence is another sequence, or (as in
         * this case) a let, wrapping the first sequence expression in { } is
         * required.
         * ******************************************************************
         *)

        (** TODO: Configure the optional ability to print the *minimum* number
            of parens. It's simply a matter of changing [higherPrecedenceThan]
            to [higherOrEqualPrecedenceThan]. *)

        (* The point of the function is to ensure that
           ~reducesAfterRight:rightExpr will reduce at the proper time when it
           is reparsed, possibly wrapping it in parenthesis if needed. It
           ensures a rule doesn't reduce until *after* `reducesAfterRight` gets
           a chance to reduce. Example: The addition rule which has precedence
           of rightmost token "+", in `x + a * b` should not reduce until after
           the a * b gets a chance to reduce. This function would determine the
           minimum parens to ensure that. *)
        method ensureContainingRule ~withPrecedence ~reducesAfterRight () =
          match self#unparseExprRecurse reducesAfterRight with
          | SpecificInfixPrecedence ({ shiftPrecedence; _ }, rightRecurse) ->
            if higherPrecedenceThan shiftPrecedence withPrecedence
            then rightRecurse
            else if higherPrecedenceThan withPrecedence shiftPrecedence
            then
              LayoutNode
                (formatPrecedence
                   ~loc:reducesAfterRight.pexp_loc
                   (self#unparseResolvedRule rightRecurse))
            else if isRightAssociative ~prec:withPrecedence
            then rightRecurse
            else
              LayoutNode
                (formatPrecedence
                   ~loc:reducesAfterRight.pexp_loc
                   (self#unparseResolvedRule rightRecurse))
          | FunctionApplication itms ->
            let funApplExpr =
              formatAttachmentApplication
                applicationFinalWrapping
                None
                (itms, Some reducesAfterRight.pexp_loc)
            in
            (* Little hack: need to print parens for the `bar` application in
               e.g. `foo->other##(bar(baz))` or `foo->other->(bar(baz))`. *)
            if higherPrecedenceThan withPrecedence (Custom "prec_functionAppl")
            then
              LayoutNode
                (formatPrecedence ~loc:reducesAfterRight.pexp_loc funApplExpr)
            else LayoutNode funApplExpr
          | PotentiallyLowPrecedence itm ->
            LayoutNode (formatPrecedence ~loc:reducesAfterRight.pexp_loc itm)
          | Simple itm -> LayoutNode itm

        method ensureExpression ~reducesOnToken expr =
          match self#unparseExprRecurse expr with
          | SpecificInfixPrecedence ({ reducePrecedence; _ }, leftRecurse) ->
            if higherPrecedenceThan reducePrecedence reducesOnToken
            then leftRecurse
            else if higherPrecedenceThan reducesOnToken reducePrecedence
            then
              LayoutNode
                (formatPrecedence
                   ~loc:expr.pexp_loc
                   (self#unparseResolvedRule leftRecurse))
            else if isLeftAssociative ~prec:reducesOnToken
            then leftRecurse
            else
              LayoutNode
                (formatPrecedence
                   ~loc:expr.pexp_loc
                   (self#unparseResolvedRule leftRecurse))
          | FunctionApplication itms ->
            LayoutNode
              (formatAttachmentApplication
                 applicationFinalWrapping
                 None
                 (itms, Some expr.pexp_loc))
          | PotentiallyLowPrecedence itm ->
            LayoutNode (formatPrecedence ~loc:expr.pexp_loc itm)
          | Simple itm -> LayoutNode itm

        method unparseExpr x =
          match self#unparseExprRecurse x with
          | SpecificInfixPrecedence (_, resolvedRule) ->
            self#unparseResolvedRule resolvedRule
          | FunctionApplication itms ->
            formatAttachmentApplication
              applicationFinalWrapping
              None
              (itms, Some x.pexp_loc)
          | PotentiallyLowPrecedence itm -> itm
          | Simple itm -> itm
        (** Attempts to unparse: The beginning of a more general printing
            algorithm, that determines how to print based on precedence of
            tokens and rules. The end goal is that this should be completely
            auto-generated from the Menhir parsing tables. We could move more
            and more into this function.

            You could always just call self#expression, but `unparseExpr` will
            render infix/prefix/unary/terary fixities in their beautiful forms
            while minimizing parenthesis. *)

        (* This method may not even be needed *)
        method unparseUnattributedExpr x =
          match Reason_attributes.partitionAttributes x.pexp_attributes with
          | { docAttrs = []; stdAttrs = []; _ } -> self#unparseExpr x
          | _ -> makeList ~wrap:("(", ")") [ self#unparseExpr x ]

        (* ensureExpr ensures that the expression is wrapped in parens * e.g. is
           necessary in cases like: * let display = (:message=("hello": string))
           => 1; * but not in cases like: * let f = (a: bool) => 1; * TODO: in
           the future we should probably use the type ruleCategory * to
           'automatically' ensure the validity of a constraint expr with
           parens... *)
        method unparseProtectedExpr ?(forceParens = false) e =
          let itm =
            match e with
            | { pexp_attributes = []; pexp_desc = Pexp_constraint (x, ct); _ }
              ->
              let x = self#unparseExpr x in
              let children =
                [ x; label ~space:true (atom ":") (self#core_type ct) ]
              in
              if forceParens
              then makeList ~wrap:("(", ")") children
              else makeList children
            | { pexp_attributes; pexp_desc = Pexp_constant c; _ } ->
              (* When we have Some(-1) or someFunction(-1, -2), the arguments -1
                 and -2 * pass through this case. In this context they don't
                 need to be wrapped in extra parens * Some((-1)) should be
                 printed as Some(-1). This is in contrast with * 1 + (-1) where
                 we print the parens for readability. *)
              let raw_literal, pexp_attributes =
                Reason_attributes.extract_raw_literal pexp_attributes
              in
              let constant = self#constant ?raw_literal ~parens:forceParens c in
              (match pexp_attributes with
              | [] -> constant
              | attrs ->
                let formattedAttrs =
                  makeSpacedBreakableInlineList
                    (List.map self#item_attribute attrs)
                in
                makeSpacedBreakableInlineList [ formattedAttrs; constant ])
            | { pexp_desc = Pexp_function (_ :: _, _, Pfunction_body _); _ } ->
              self#formatPexpFun e
            | x -> self#unparseExpr x
          in
          source_map ~loc:e.pexp_loc itm

        method simplifyUnparseExpr
          ?(inline = false)
          ?(even_wrap_simple = false)
          ?(wrap = "(", ")")
          x =
          match self#unparseExprRecurse x, even_wrap_simple with
          | SpecificInfixPrecedence (_, itm), _ ->
            formatPrecedence
              ~inline
              ~wrap
              ~loc:x.pexp_loc
              (self#unparseResolvedRule itm)
          | FunctionApplication itms, _ ->
            formatPrecedence
              ~inline
              ~wrap
              ~loc:x.pexp_loc
              (formatAttachmentApplication
                 applicationFinalWrapping
                 None
                 (itms, Some x.pexp_loc))
          | PotentiallyLowPrecedence itm, _ | Simple itm, true ->
            formatPrecedence ~inline ~wrap ~loc:x.pexp_loc itm
          | Simple itm, false -> itm

        method unparseResolvedRule =
          function
          | LayoutNode layoutNode -> layoutNode
          | InfixTree _ as infixTree ->
            formatComputedInfixChain (computeInfixChain infixTree)

        method unparseExprApplicationItems x =
          match self#unparseExprRecurse x with
          | SpecificInfixPrecedence (_, wrappedRule) ->
            let itm = self#unparseResolvedRule wrappedRule in
            [ itm ], Some x.pexp_loc
          | FunctionApplication itms -> itms, Some x.pexp_loc
          | PotentiallyLowPrecedence itm -> [ itm ], Some x.pexp_loc
          | Simple itm -> [ itm ], Some x.pexp_loc

        (* Provides beautiful printing for pipe first sugar: * foo * ->f(a, b) *
           ->g(c, d) *)
        method formatPipeFirst e =
          let module PipeFirstTree = struct
            type exp = Parsetree.expression

            type flatNode =
              | Exp of exp
              | ExpU of exp (* uncurried *)
              | Args of (Asttypes.arg_label * exp) list

            type flatT = flatNode list

            type node =
              { exp : exp
              ; args : (Asttypes.arg_label * exp) list
              ; uncurried : bool
              }

            type t = node list

            let formatNode ?prefix ?(first = false) { exp; args; uncurried } =
              let formatLayout expr =
                let formatted =
                  if first
                  then
                    self#ensureExpression
                      ~reducesOnToken:(Token pipeFirstToken)
                      expr
                  else
                    match expr with
                    (* a->foo(x, _) and a->(foo(x, _)) are equivalent under pipe
                       first * (a->foo)(x, _) is unnatural and desugars to *
                       (__x) => (a |. foo)(x, __x) * Under `->`, it makes more
                       sense to desugar into * a |. (__x => foo(x, __x)) * *
                       Hence we don't need parens in this case. *)
                    | expr when Reason_heuristics.isUnderscoreApplication expr
                      ->
                      LayoutNode (self#unparseExpr expr)
                    | _ ->
                      self#ensureContainingRule
                        ~withPrecedence:(Token pipeFirstToken)
                        ~reducesAfterRight:expr
                        ()
                in
                self#unparseResolvedRule formatted
              in
              let parens =
                match exp.pexp_desc with
                | Pexp_apply (e, _) ->
                  printedStringAndFixityExpr e = UnaryPostfix "^"
                | _ -> false
              in
              let layout =
                match args with
                | [] ->
                  let e = formatLayout exp in
                  (match prefix with Some l -> makeList [ l; e ] | None -> e)
                | args ->
                  let args =
                    List.map
                      (fun (label, arg) ->
                         label, self#process_underscore_application arg)
                      args
                  in
                  let fakeApplExp =
                    let loc_end =
                      match List.rev args with
                      | (_, e) :: _ -> e.pexp_loc.loc_end
                      | _ -> exp.pexp_loc.loc_end
                    in
                    { exp with pexp_loc = { exp.pexp_loc with loc_end } }
                  in
                  makeList
                    (self#formatFunAppl
                       ?prefix
                       ~jsxAttrs:[]
                       ~args
                       ~funExpr:exp
                       ~applicationExpr:fakeApplExp
                       ~uncurried
                       ())
              in
              if parens then formatPrecedence layout else layout
          end
          in
          (* Imagine: foo->f(a, b)->g(c,d) * The corresponding parsetree looks
             more like: * (((foo->f)(a,b))->g)(c, d) * The extra Pexp_apply
             nodes, e.g. (foo->f), result into a * nested/recursive ast which is
             pretty inconvenient in terms of printing. * For printing purposes
             we actually want something more like: * foo->|f(a,b)|->|g(c, d)| *
             in order to provide to following printing: * foo * ->f(a, b) *
             ->g(c, d) * The job of "flatten" is to turn the inconvenient,
             nested ast * (((foo->f)(a,b))->g)(c, d) * into * [Exp foo; Exp f;
             Args [a; b]; Exp g; Args [c; d]] * which can be processed for
             printing purposes. *)
          let rec flatten ?(uncurried = false) acc = function
            | { pexp_desc =
                  Pexp_apply
                    ( { pexp_desc = Pexp_ident { txt = Longident.Lident "|."; _ }
                      ; _
                      }
                    , [ (Nolabel, arg1); (Nolabel, arg2) ] )
              ; _
              } ->
              flatten (PipeFirstTree.Exp arg2 :: acc) arg1
            | { pexp_attributes
              ; pexp_desc =
                  Pexp_apply
                    ( { pexp_desc =
                          Pexp_apply
                            ( { pexp_desc =
                                  Pexp_ident { txt = Longident.Lident "|."; _ }
                              ; _
                              }
                            , [ (Nolabel, arg1); (Nolabel, arg2) ] )
                      ; _
                      }
                    , args )
              ; _
              } as e ->
              let args = PipeFirstTree.Args args in
              (match pexp_attributes with
              | [ { attr_name = { txt = "u" | "bs"; _ }
                  ; attr_payload = PStr []
                  ; _
                  }
                ] ->
                flatten (PipeFirstTree.ExpU arg2 :: args :: acc) arg1
              | [] ->
                (* the uncurried attribute might sit on the Pstr_eval *
                   enclosing the Pexp_apply*)
                if uncurried
                then flatten (PipeFirstTree.ExpU arg2 :: args :: acc) arg1
                else flatten (PipeFirstTree.Exp arg2 :: args :: acc) arg1
              | _ -> PipeFirstTree.Exp e :: acc)
            | { pexp_desc = Pexp_ident { txt = Longident.Lident "|."; _ }; _ }
              ->
              acc
            | arg -> PipeFirstTree.Exp arg :: acc
          in
          (* Given: foo->f(a, b)->g(c, d) * We get the following
             PipeFirstTree.flatNode list: * [Exp foo; Exp f; Args [a; b]; Exp g;
             Args [c; d]] * The job of `parse` is to turn the "flat
             representation" * (a.k.a. PipeFirstTree.flastNode list) into a more
             convenient structure * that allows us to express the segments:
             "foo" "f(a, b)" "g(c, d)". * PipeFirstTree.t expresses those
             segments. * [{exp = foo; args = []}; {exp = f; args = [a; b]}; {exp
             = g; args = [c; d]}] *)
          let rec parse acc = function
            | PipeFirstTree.Exp e :: PipeFirstTree.Args args :: xs ->
              parse
                (PipeFirstTree.{ exp = e; args; uncurried = false } :: acc)
                xs
            | PipeFirstTree.ExpU e :: PipeFirstTree.Args args :: xs ->
              parse
                (PipeFirstTree.{ exp = e; args; uncurried = true } :: acc)
                xs
            | PipeFirstTree.Exp e :: xs ->
              parse
                (PipeFirstTree.{ exp = e; args = []; uncurried = false } :: acc)
                xs
            | _ -> List.rev acc
          in
          (* Given: foo->f(. a,b); * The uncurried attribute doesn't sit on the
             Pexp_apply, but sits on * the top level Pstr_eval. We don't have
             access to top-level context here, * hence the lookup in the global
             uncurriedTable to correctly determine * if we need to print
             uncurried. *)
          let uncurried =
            try Hashtbl.find uncurriedTable e.pexp_loc with Not_found -> false
          in
          (* Turn * foo->f(a, b)->g(c, d) * into * [Exp foo; Exp f; Args [a; b];
             Exp g; Args [c; d]] *)
          let (flatNodes : PipeFirstTree.flatT) = flatten ~uncurried [] e in
          (* Turn * [Exp foo; Exp f; Args [a; b]; Exp g; Args [c; d]] * into *
             [{exp = foo; args = []}; {exp = f; args = [a; b]}; {exp = g; args =
             [c; d]}] *)
          let (pipetree : PipeFirstTree.t) = parse [] flatNodes in
          (* Turn * [{exp = foo; args = []}; {exp = f; args = [a; b]}; {exp = g;
             args = [c; d]}] * into * [foo; ->f(a, b); ->g(c, d)] *)
          let pipeSegments =
            match pipetree with
            (* Special case printing of * foo->bar( * aa, * bb, * ) * * We don't
               want * foo * ->bar( * aa, * bb * ) * * Notice how `foo->bar`
               shouldn't break, it wastes space and is * inconsistent with *
               foo.bar( * aa, * bb, * ) *)
            | [ ({ exp = { pexp_desc = Pexp_ident _; _ }; _ } as hd); last ] ->
              let prefix =
                Some
                  (makeList
                     [ PipeFirstTree.formatNode ~first:true hd; atom "->" ])
              in
              [ PipeFirstTree.formatNode ?prefix last ]
            | hd :: tl ->
              let hd = PipeFirstTree.formatNode ~first:true hd in
              let tl =
                List.map
                  (fun node ->
                     makeList [ atom "->"; PipeFirstTree.formatNode node ])
                  tl
              in
              hd :: tl
            | [] -> []
          in
          (* Provide nice breaking for: [foo; ->f(a, b); ->g(c, d)] * foo *
             ->f(a, b) * ->g(c, d) *)
          makeList ~break:IfNeed ~inline:(true, true) pipeSegments

        (*
         * Replace (__x) => foo(__x) with foo(_)
         *)
        method process_underscore_application x =
          let process_application expr =
            let process_arg (l, e) =
              match e.pexp_desc with
              | Pexp_ident ({ txt = Lident "__x"; _ } as id) ->
                let pexp_desc = Pexp_ident { id with txt = Lident "_" } in
                l, { e with pexp_desc }
              | _ -> l, e
            in
            match expr.pexp_desc with
            | Pexp_apply (e_fun, args) ->
              let pexp_desc = Pexp_apply (e_fun, List.map process_arg args) in
              { expr with pexp_desc }
            | _ -> expr
          in
          match x.pexp_desc with
          | Pexp_function
              ( [ { pparam_desc =
                      Pparam_val
                        ( Nolabel
                        , None
                        , { ppat_desc = Ppat_var { txt = "__x"; _ }; _ } )
                  ; _
                  }
                ]
              , _
              , Pfunction_body ({ pexp_desc = Pexp_apply _; _ } as e) ) ->
            process_application e
          | Pexp_function (params, constraint_, body) ->
            (match body with
            | Pfunction_cases _ -> x
            | Pfunction_body body ->
              let e_processed = self#process_underscore_application body in
              if body == e_processed
              then x
              else
                { x with
                  pexp_desc =
                    Pexp_function
                      (params, constraint_, Pfunction_body e_processed)
                })
          | _ -> x

        method unparseExprRecurse x =
          let x = self#process_underscore_application x in

          (* If there are any attributes, render unary like `(~-) x [@ppx]`, and
             infix like `(+) x y [@attr]` *)
          let { Reason_attributes.arityAttrs
              ; stdAttrs
              ; jsxAttrs
              ; stylisticAttrs
              ; uncurried
              ; _
              }
            =
            Reason_attributes.partitionAttributes
              ~allowUncurry:(Reason_heuristics.bsExprCanBeUncurried x)
              x.pexp_attributes
          in
          let stylisticAttrs =
            Reason_attributes.maybe_remove_stylistic_attrs
              stylisticAttrs
              ~should_preserve:preserve_braces
          in
          let () =
            if uncurried then Hashtbl.add uncurriedTable x.pexp_loc true
          in
          let x =
            { x with
              pexp_attributes =
                stylisticAttrs @ arityAttrs @ stdAttrs @ jsxAttrs
            }
          in
          (* If there's any attributes, recurse without them, then apply them to
             the ends of functions, or simplify infix printings then append. *)
          match stdAttrs, x.pexp_desc with
          | _, Pexp_letop _ ->
            (* `Pexp_letop` is a bit different than `let` bindings because the
               attributes are in `Pexp_letop` rather than the `value_binding`
               type (check https://github.com/ocaml/ocaml/issues/9301 too), so
               we must treat it a bit differently if we want to print the
               attributes inside the braces. *)
            FunctionApplication [ makeLetSequence (self#letList x) ]
          | _ :: _, _ ->
            let withoutVisibleAttrs =
              { x with
                pexp_attributes = stylisticAttrs @ arityAttrs @ jsxAttrs
              }
            in
            let attributesAsList = List.map self#attribute stdAttrs in
            let itms =
              match self#unparseExprRecurse withoutVisibleAttrs with
              | SpecificInfixPrecedence ({ reducePrecedence; _ }, wrappedRule)
                ->
                let itm = self#unparseResolvedRule wrappedRule in
                (match reducePrecedence with
                (* doesn't need wrapping; we know how to parse *)
                | Custom "prec_lbracket" | Token "." -> [ itm ]
                | _ -> [ formatPrecedence ~loc:x.pexp_loc itm ])
              | FunctionApplication itms -> itms
              | PotentiallyLowPrecedence itm ->
                [ formatPrecedence ~loc:x.pexp_loc itm ]
              | Simple itm -> [ itm ]
            in
            FunctionApplication
              [ makeList
                  ~break:IfNeed
                  ~inline:(true, true)
                  ~indent:0
                  ~postSpace:true
                  (List.concat [ attributesAsList; itms ])
              ]
          | [], _ ->
            (match self#simplest_expression x with
            | Some se -> Simple se
            | None ->
              let self = self#reset_request_braces in
              (match x.pexp_desc with
              | Pexp_apply (e, ls) ->
                let ls =
                  List.map
                    (fun (l, expr) ->
                       l, self#process_underscore_application expr)
                    ls
                in
                (match e, ls with
                | e, _ when Reason_heuristics.isPipeFirst e ->
                  let prec = Token pipeFirstToken in
                  SpecificInfixPrecedence
                    ( { reducePrecedence = prec; shiftPrecedence = prec }
                    , LayoutNode (self#formatPipeFirst x) )
                | ( { pexp_desc =
                        Pexp_ident { txt = Ldot (Lident "Array", "get"); _ }
                    ; _
                    }
                  , [ (_, e1); (_, e2) ] ) ->
                  (match e1.pexp_desc with
                  | Pexp_ident { txt = Lident "_"; _ } ->
                    let k = atom "Array.get" in
                    let v =
                      makeList
                        ~postSpace:true
                        ~sep:(Layout.Sep ",")
                        ~wrap:("(", ")")
                        [ atom "_"; self#unparseExpr e2 ]
                    in
                    Simple (label k v)
                  | _ ->
                    let prec = Custom "prec_lbracket" in
                    let lhs =
                      self#unparseResolvedRule
                        (self#ensureExpression ~reducesOnToken:prec e1)
                    in
                    let rhs = self#unparseExpr e2 in
                    SpecificInfixPrecedence
                      ( { reducePrecedence = prec; shiftPrecedence = prec }
                      , LayoutNode (self#access "[" "]" lhs rhs) ))
                | ( { pexp_desc =
                        Pexp_ident { txt = Ldot (Lident "String", "get"); _ }
                    ; _
                    }
                  , [ (_, e1); (_, e2) ] ) ->
                  if Reason_heuristics.isUnderscoreIdent e1
                  then
                    let k = atom "String.get" in
                    let v =
                      makeList
                        ~postSpace:true
                        ~sep:(Layout.Sep ",")
                        ~wrap:("(", ")")
                        [ atom "_"; self#unparseExpr e2 ]
                    in
                    Simple (label k v)
                  else
                    let prec = Custom "prec_lbracket" in
                    let lhs =
                      self#unparseResolvedRule
                        (self#ensureExpression ~reducesOnToken:prec e1)
                    in
                    let rhs = self#unparseExpr e2 in
                    SpecificInfixPrecedence
                      ( { reducePrecedence = prec; shiftPrecedence = prec }
                      , LayoutNode (self#access ".[" "]" lhs rhs) )
                | ( { pexp_desc =
                        Pexp_ident
                          { txt =
                              Ldot (Ldot (Lident "Bigarray", "Genarray"), "get")
                          ; _
                          }
                    ; _
                    }
                  , [ (_, e1); (_, ({ pexp_desc = Pexp_array ls; _ } as e2)) ] )
                  ->
                  if Reason_heuristics.isUnderscoreIdent e1
                  then
                    let k = atom "Bigarray.Genarray.get" in
                    let v =
                      makeList
                        ~postSpace:true
                        ~sep:(Layout.Sep ",")
                        ~wrap:("(", ")")
                        [ atom "_"; self#unparseExpr e2 ]
                    in
                    Simple (label k v)
                  else
                    let formattedList = List.map self#unparseExpr ls in
                    let lhs =
                      makeList
                        [ self#simple_enough_to_be_lhs_dot_send e1; atom "." ]
                    in
                    let rhs =
                      makeList
                        ~break:IfNeed
                        ~postSpace:true
                        ~sep:commaSep
                        ~wrap:("{", "}")
                        formattedList
                    in
                    let prec = Custom "prec_lbracket" in
                    SpecificInfixPrecedence
                      ( { reducePrecedence = prec; shiftPrecedence = prec }
                      , LayoutNode (label lhs rhs) )
                | ( { pexp_desc =
                        Pexp_ident
                          { txt =
                              Ldot
                                ( Ldot
                                    ( Lident "Bigarray"
                                    , (("Array1" | "Array2" | "Array3") as
                                       arrayIdent) )
                                , "get" )
                          ; _
                          }
                    ; _
                    }
                  , (_, e1) :: rest ) ->
                  if Reason_heuristics.isUnderscoreIdent e1
                  then
                    let k = atom ("Bigarray." ^ arrayIdent ^ ".get") in
                    let v =
                      makeList
                        ~postSpace:true
                        ~sep:(Layout.Sep ",")
                        ~wrap:("(", ")")
                        (atom "_"
                        :: List.map (fun (_, e) -> self#unparseExpr e) rest)
                    in
                    Simple (label k v)
                  else
                    let formattedList =
                      List.map self#unparseExpr (List.map snd rest)
                    in
                    let lhs =
                      makeList
                        [ self#simple_enough_to_be_lhs_dot_send e1; atom "." ]
                    in
                    let rhs =
                      makeList
                        ~break:IfNeed
                        ~postSpace:true
                        ~sep:commaSep
                        ~wrap:("{", "}")
                        formattedList
                    in
                    let prec = Custom "prec_lbracket" in
                    SpecificInfixPrecedence
                      ( { reducePrecedence = prec; shiftPrecedence = prec }
                      , LayoutNode (label lhs rhs) )
                | _ ->
                  (match self#sugar_set_expr_parts x with
                  (* Returns None if there's attributes - would render as regular function *)
                  (* Format as if it were an infix function application with identifier "=" *)
                  | Some (simplyFormatedLeftItm, rightExpr) ->
                    let tokenPrec = Token updateToken in
                    let rightItm =
                      self#ensureContainingRule
                        ~withPrecedence:tokenPrec
                        ~reducesAfterRight:rightExpr
                        ()
                    in
                    let leftWithOp =
                      makeList
                        ~postSpace:true
                        [ simplyFormatedLeftItm; atom updateToken ]
                    in
                    let expr =
                      label
                        ~space:true
                        leftWithOp
                        (self#unparseResolvedRule rightItm)
                    in
                    SpecificInfixPrecedence
                      ( { reducePrecedence = tokenPrec
                        ; shiftPrecedence = tokenPrec
                        }
                      , LayoutNode expr )
                  | None ->
                    (match printedStringAndFixityExpr e, ls with
                    (* We must take care not to print two subsequent prefix
                       operators without spaces between them (`! !` could become
                       `!!` which is totally different). *)
                    | AlmostSimplePrefix prefixStr, [ (Nolabel, rightExpr) ] ->
                      let forceSpace =
                        match rightExpr.pexp_desc with
                        | Pexp_apply (ee, _) ->
                          (match printedStringAndFixityExpr ee with
                          | AlmostSimplePrefix _ -> true
                          | _ -> false)
                        | _ -> false
                      in
                      let prec = Token prefixStr in
                      let rightItm =
                        self#unparseResolvedRule
                          (self#ensureContainingRule
                             ~withPrecedence:prec
                             ~reducesAfterRight:rightExpr
                             ())
                      in
                      SpecificInfixPrecedence
                        ( { reducePrecedence = prec; shiftPrecedence = prec }
                        , LayoutNode
                            (label ~space:forceSpace (atom prefixStr) rightItm)
                        )
                    | UnaryPostfix postfixStr, [ (Nolabel, leftExpr) ] ->
                      let forceSpace =
                        match leftExpr.pexp_desc with
                        | Pexp_apply (ee, _) ->
                          (match printedStringAndFixityExpr ee with
                          | UnaryPostfix "^" | AlmostSimplePrefix _ -> true
                          | _ -> false)
                        | _ -> false
                      in
                      let leftItm =
                        match leftExpr.pexp_desc with
                        | Pexp_apply (e, _) ->
                          (match printedStringAndFixityExpr e with
                          | Infix printedIdent
                            when requireNoSpaceFor printedIdent
                                 || Reason_heuristics.isPipeFirst e ->
                            self#unparseExpr leftExpr
                          | _ -> self#simplifyUnparseExpr leftExpr)
                        | Pexp_field _ -> self#unparseExpr leftExpr
                        | _ -> self#simplifyUnparseExpr leftExpr
                      in
                      Simple (label ~space:forceSpace leftItm (atom postfixStr))
                    | ( Infix printedIdent
                      , [ (Nolabel, leftExpr); (Nolabel, rightExpr) ] ) ->
                      let infixToken = Token printedIdent in
                      let rightItm =
                        self#ensureContainingRule
                          ~withPrecedence:infixToken
                          ~reducesAfterRight:rightExpr
                          ()
                      in
                      let leftItm =
                        self#ensureExpression
                          ~reducesOnToken:infixToken
                          leftExpr
                      in
                      (* Left exprs of infix tokens which we don't print spaces
                         for (e.g. `##`) need to be wrapped in parens in the
                         case of postfix `^`. Otherwise, printing will be
                         ambiguous as `^` is also a valid start of an infix
                         operator. *)
                      let formattedLeftItm =
                        match leftItm with
                        | LayoutNode x ->
                          (match leftExpr.pexp_desc with
                          | Pexp_apply (e, _) ->
                            (match printedStringAndFixityExpr e with
                            | UnaryPostfix "^"
                              when requireNoSpaceFor printedIdent ->
                              LayoutNode
                                (formatPrecedence ~loc:leftExpr.pexp_loc x)
                            | _ -> leftItm)
                          | _ -> leftItm)
                        | InfixTree _ -> leftItm
                      in
                      let infixTree =
                        InfixTree (printedIdent, formattedLeftItm, rightItm)
                      in
                      SpecificInfixPrecedence
                        ( { reducePrecedence = infixToken
                          ; shiftPrecedence = infixToken
                          }
                        , infixTree )
                    (* Will be rendered as `(+) a b c` which is parsed with
                       higher precedence than all the other forms unparsed
                       here.*)
                    | UnaryPlusPrefix printedIdent, [ (Nolabel, rightExpr) ] ->
                      let prec = Custom "prec_unary" in
                      let rightItm =
                        self#unparseResolvedRule
                          (self#ensureContainingRule
                             ~withPrecedence:prec
                             ~reducesAfterRight:rightExpr
                             ())
                      in
                      let expr =
                        label ~space:true (atom printedIdent) rightItm
                      in
                      SpecificInfixPrecedence
                        ( { reducePrecedence = prec
                          ; shiftPrecedence = Token printedIdent
                          }
                        , LayoutNode expr )
                    | ( (UnaryMinusPrefix printedIdent as x)
                      , [ (Nolabel, rightExpr) ] )
                    | ( (UnaryNotPrefix printedIdent as x)
                      , [ (Nolabel, rightExpr) ] ) ->
                      let forceSpace =
                        match x with
                        | UnaryMinusPrefix _ -> true
                        | _ ->
                          (match rightExpr.pexp_desc with
                          | Pexp_apply
                              ( { pexp_desc = Pexp_ident { txt = Lident s; _ }
                                ; _
                                }
                              , _ ) ->
                            isSimplePrefixToken s
                          | _ -> false)
                      in
                      let prec = Custom "prec_unary" in
                      let rightItm =
                        self#unparseResolvedRule
                          (self#ensureContainingRule
                             ~withPrecedence:prec
                             ~reducesAfterRight:rightExpr
                             ())
                      in
                      let expr =
                        label ~space:forceSpace (atom printedIdent) rightItm
                      in
                      SpecificInfixPrecedence
                        ( { reducePrecedence = prec
                          ; shiftPrecedence = Token printedIdent
                          }
                        , LayoutNode expr )
                    (* Will need to be rendered in self#expression as (~-) x y
                       z. *)
                    | _, _ ->
                      (* This case will happen when there is something like * *
                         Bar.createElement a::1 b::2 [] [@bla] [@JSX] * * At
                         this point the bla will be stripped (because it's a
                         visible * attribute) but the JSX will still be
                         there. *)

                      (* this case also happens when we have something like: *
                         List.map((a) => a + 1, numbers); * We got two
                         "List.map" as Pexp_ident & a list of arguments: * [`(a)
                         => a + 1`; `numbers`] * * Another possible case is: *
                         describe("App", () => * test("math", () => *
                         Expect.expect(1 + 2) |> toBe(3))); *)
                      let uncurried =
                        try Hashtbl.find uncurriedTable x.pexp_loc with
                        | Not_found -> false
                      in
                      FunctionApplication
                        (self#formatFunAppl
                           ~uncurried
                           ~jsxAttrs
                           ~args:ls
                           ~applicationExpr:x
                           ~funExpr:e
                           ()))))
              | Pexp_field (e, li) ->
                let prec = Token "." in
                let leftItm =
                  self#unparseResolvedRule
                    (self#ensureExpression ~reducesOnToken:prec e)
                in
                let { Reason_attributes.stdAttrs; _ } =
                  Reason_attributes.partitionAttributes e.pexp_attributes
                in
                let formattedLeftItm =
                  if stdAttrs == []
                  then leftItm
                  else formatPrecedence ~loc:e.pexp_loc leftItm
                in
                let layout =
                  label
                    (makeList [ formattedLeftItm; atom "." ])
                    (self#longident_loc li)
                in
                SpecificInfixPrecedence
                  ( { reducePrecedence = prec; shiftPrecedence = prec }
                  , LayoutNode layout )
              | Pexp_construct (li, Some eo)
                when not (is_simple_construct (view_expr x)) ->
                (match view_expr x with
                (* TODO: Explicit arity *)
                | `normal ->
                  let arityIsClear = isArityClear arityAttrs in
                  FunctionApplication
                    [ self#constructor_expression
                        ~arityIsClear
                        stdAttrs
                        (self#longident_loc li)
                        eo
                    ]
                | _ -> assert false)
              | Pexp_variant (l, Some eo) ->
                if arityAttrs != []
                then
                  raise
                    (NotPossible
                       "Should never see embedded attributes on poly variant")
                else
                  FunctionApplication
                    [ self#constructor_expression
                        ~polyVariant:true
                        ~arityIsClear:true
                        stdAttrs
                        (atom ("`" ^ add_raw_identifier_prefix l))
                        eo
                    ]
              (* TODO: Should protect this identifier *)
              | Pexp_setinstvar (s, rightExpr) ->
                let rightItm =
                  self#unparseResolvedRule
                    (self#ensureContainingRule
                       ~withPrecedence:(Token updateToken)
                       ~reducesAfterRight:rightExpr
                       ())
                in
                let expr =
                  label
                    ~space:true
                    (makeList
                       ~postSpace:true
                       [ protectIdentifier s.txt; atom updateToken ])
                    rightItm
                in
                SpecificInfixPrecedence
                  ( { reducePrecedence = Token updateToken
                    ; shiftPrecedence = Token updateToken
                    }
                  , LayoutNode expr )
              | Pexp_setfield (leftExpr, li, rightExpr) ->
                let rightItm =
                  self#unparseResolvedRule
                    (self#ensureContainingRule
                       ~withPrecedence:(Token updateToken)
                       ~reducesAfterRight:rightExpr
                       ())
                in
                let leftItm =
                  self#unparseResolvedRule
                    (self#ensureExpression ~reducesOnToken:(Token ".") leftExpr)
                in
                let leftLbl =
                  label (makeList [ leftItm; atom "." ]) (self#longident_loc li)
                in
                let expr =
                  label
                    ~space:true
                    (makeList ~postSpace:true [ leftLbl; atom updateToken ])
                    rightItm
                in
                SpecificInfixPrecedence
                  ( { reducePrecedence = Token updateToken
                    ; shiftPrecedence = Token updateToken
                    }
                  , LayoutNode expr )
              | Pexp_match (e, l) when detectTernary l != None ->
                (match detectTernary l with
                | None -> raise (Invalid_argument "Impossible")
                | Some (tt, ff) ->
                  let ifTrue = self#reset_request_braces#unparseExpr tt in
                  let testItem =
                    self#unparseResolvedRule
                      (self#reset_request_braces#ensureExpression
                         e
                         ~reducesOnToken:(Token "?"))
                  in
                  let ifFalse =
                    self#unparseResolvedRule
                      (self#reset_request_braces#ensureContainingRule
                         ~withPrecedence:(Token ":")
                         ~reducesAfterRight:ff
                         ())
                  in
                  let trueBranch =
                    label ~space:true ~break:`Never (atom "?") ifTrue
                  in
                  let falseBranch =
                    label ~space:true ~break:`Never (atom ":") ifFalse
                  in
                  let expr =
                    label
                      ~space:true
                      testItem
                      (makeList
                         ~break:IfNeed
                         ~sep:(Sep " ")
                         ~inline:(true, true)
                         [ trueBranch; falseBranch ])
                  in
                  SpecificInfixPrecedence
                    ( { reducePrecedence = Token ":"
                      ; shiftPrecedence = Token "?"
                      }
                    , LayoutNode expr ))
              | _ ->
                (match self#expression_requiring_parens_in_infix x with
                | Some e -> e
                | None ->
                  raise (Invalid_argument "No match for unparsing expression"))))

        method formatNonSequencyExpression ?parent e =
          (* Instead of printing:
           *   let result =  { open Fmt; strf(foo);}
           *
           * We format as:
           *   let result = Fmt.(strf(foo))
           *
           * (Also see https://github.com/facebook/Reason/issues/114)
           *)
          match e.pexp_attributes, e.pexp_desc with
          | [], Pexp_record _ (* syntax sugar for M.{x:1} *)
          | [], Pexp_tuple _ (* syntax sugar for M.(a, b) *)
          | [], Pexp_object { pcstr_fields = []; _ } (* syntax sugar for M.{} *)
          | [], Pexp_construct ({ txt = Lident "::"; _ }, Some _)
          | [], Pexp_construct ({ txt = Lident "[]"; _ }, _)
          | [], Pexp_extension ({ txt = "mel.obj"; _ }, _) ->
            self#simplifyUnparseExpr e (* syntax sugar for M.[x,y] *)
          (* syntax sugar for the rest, wrap with parens to avoid ambiguity.
           * E.g., avoid M.(M2.v) being printed as M.M2.v
           * Or ReasonReact.(<> {string("Test")} </>);
           *)
          | _ ->
            (match parent with
            | Some parent
              when Reason_attributes.has_open_notation_attr
                     parent.pexp_attributes ->
              makeList
                ~break:IfNeed
                ~inline:(true, false)
                ~postSpace:true
                ~wrap:("(", ")")
                ~sep:(SepFinal (";", ""))
                (self#letList e)
            | Some _ | None ->
              makeList ~wrap:("(", ")") ~break:IfNeed [ self#unparseExpr e ])

        (* It's not enough to only check if precedence of an infix left/right is
         * greater than the infix itself. We also should likely pay attention to
         * left/right associativity. So how do we render the minimum number of
         * parenthesis?
         *
         * The intuition is that sequential right associative operators will
         * naturally build up deep trees on the right side (left builds up left-deep
         * trees). So by default, we add parens to model the tree structure that
         * we're rendering except when the parser will *naturally* parse the tree
         * structure that the parens assert.
         *
         * Sequential identical infix operators:
         * ------------------------------------
         * So if we see a nested infix operator of precedence Y, as one side of
         * another infix operator that has the same precedence (Y), that is S
         * associative on the S side of the function application, we don't need to
         * wrap in parens. In more detail:
         *
         * -Add parens around infix binary function application
         *   Exception 1: Unless we are a left-assoc operator of precedence X in the left branch of an operator w/ precedence X.
         *   Exception 2: Unless we are a right-assoc operator of precedence X in the right branch of an operator w/ precedence X.
         *   Exception 3: Unless we are a _any_-assoc X operator in the _any_ branch of an Y operator where X has greater precedence than Y.
         *
         * Note that the exceptions do not specify any special cases for mixing
         * left/right associativity. Precedence is what determines necessity of
         * parens for operators with non-identical precedences. Associativity
         * only determines necessity of parens for identically precedented operators.
         *
         * PLUS is left assoc:
         * - So this one *shouldn't* expand into two consecutive infix +:
         *
         *
         *        [Pexp_apply]
         *          /      \
         *     first +   [Pexp_apply]
         *                  /   \
         *              second + third
         *
         *
         * - This one *should*:
         *
         *                [Pexp_apply]
         *                  /      \
         *       [  Pexp_apply  ] + third
         *          /     \
         *       first +  second
         *
         *
         * COLONCOLON is right assoc, so
         * - This one *should* expand into two consecutive infix ::  :
         *
         *        [Pexp_apply]
         *          /      \
         *     first ::   [Pexp_apply]
         *                  /   \
         *              second :: third
         *
         *
         * - This one *shouldn't*:
         *
         *                [Pexp_apply]
         *                  /      \
         *       [  Pexp_apply  ] :: third
         *          /     \
         *       first ::  second
         *
         *
         * Sequential differing infix operators:
         * ------------------------------------
         *
         * Neither of the following require paren grouping because of rule 3.
         *
         *
         *        [Pexp_apply]
         *          /      \
         *     first  +  [Pexp_apply]
         *                  /   \
         *              second * third
         *
         *
         *                [Pexp_apply]
         *                  /      \
         *        [Pexp_apply  +  third
         *          /     \
         *       first *  second
         *
         *  The previous has nothing to do with the fact that + and * have the same
         *  associativity. Exception 3 applies to the following where :: is right assoc
         *  and + is left. + has higher precedence than ::
         *
         *  - so parens aren't required to group + when it is in a branch of a
         *    lower precedence ::
         *
         *        [Pexp_apply]
         *          /      \
         *     first ::   [Pexp_apply]
         *                  /   \
         *              second + third
         *
         *
         *  - Whereas there is no Exception that applies in this case (Exception 3
         *    doesn't apply) so parens are required around the :: in this case.
         *
         *                [Pexp_apply]
         *                  /      \
         *       [  Pexp_apply  ] + third
         *          /     \
         *       first ::  second
         *)

        method classExpressionToFormattedApplicationItems =
          function
          | { pcl_desc = Pcl_apply (ce, l); _ } ->
            [ label
                (self#simple_class_expr ce)
                (self#label_x_expression_params l)
            ]
          | x -> [ self#class_expr x ]

        method dotdotdotChild expr =
          let self = self#inline_braces in
          match expr with
          | { pexp_desc = Pexp_apply (funExpr, args); _ }
            when printedStringAndFixityExpr funExpr == Normal
                 && Reason_attributes.without_stylistic_attrs
                      expr.pexp_attributes
                    == [] ->
            (match
               self#formatFunAppl
                 ~prefix:(atom "...")
                 ~wrap:("{", "}")
                 ~jsxAttrs:[]
                 ~args
                 ~funExpr
                 ~applicationExpr:expr
                 ()
             with
            | [ x ] -> x
            | xs -> makeList xs)
          | { pexp_desc = Pexp_function (_ :: _, _, Pfunction_body _); _ } ->
            self#formatPexpFun ~prefix:(atom "...") ~wrap:("{", "}") expr
          | _ ->
            (* Currently spreading a list must be wrapped in { }.
             * You can remove the entire even_wrap_simple arg when that is fixed. *)
            let even_wrap_simple =
              match expr with
              | { pexp_desc =
                    Pexp_construct
                      ( { txt = Lident "::"; _ }
                      , Some { pexp_desc = Pexp_tuple _; _ } )
                ; _
                } ->
                not (Reason_attributes.has_jsx_attributes expr.pexp_attributes)
              | _ -> false
            in
            let childLayout =
              self#dont_preserve_braces#simplifyUnparseExpr
                ~even_wrap_simple
                ~wrap:("{", "}")
                expr
            in
            makeList ~break:Never [ atom "..."; childLayout ]

        (* How JSX is formatted/wrapped. We want the attributes to wrap
           independently * of children. * * <xxx * attr1=blah * attr2=foo> *
           child * child * child * </x> * * +-------------------------------+ *
           | left right (list of attrs) | * | / \ / \ | * | <tag | * |
           attr1=blah | * | attr2=foo | * +-------------------------------+ * |
           * | * | * | left right list of children with * | / \ / \ open,close =
           > </tag> * | +---------+ * +--| | > * +---------+ * * </tag> *)
        method formatJSXComponent componentName ?closeComponentName args =
          let self = self#inline_braces in
          let rec processArguments arguments processedAttrs children =
            match arguments with
            | (Labelled "children", { pexp_desc = Pexp_construct (_, None); _ })
              :: tail ->
              processArguments tail processedAttrs None
            | ( Labelled "children"
              , ({ pexp_desc =
                     Pexp_construct
                       ( { txt = Lident "::"; _ }
                       , Some { pexp_desc = Pexp_tuple _; _ } )
                 ; _
                 } as arg) )
              :: tail ->
              (match self#formatJsxChildrenNonSpread arg [] with
              (* Back out of the standard jsx child formatting *)
              | None ->
                processArguments
                  tail
                  processedAttrs
                  (Some [ self#dotdotdotChild arg ])
              | Some chldn -> processArguments tail processedAttrs (Some chldn))
            | (Labelled "children", expr) :: tail ->
              processArguments
                tail
                processedAttrs
                (Some [ self#dotdotdotChild expr ])
            | (Optional lbl, expression) :: tail ->
              let { Reason_attributes.jsxAttrs; stdAttrs; _ } =
                Reason_attributes.partitionAttributes expression.pexp_attributes
              in
              let value_has_jsx = jsxAttrs != [] in
              let nextAttr =
                match expression.pexp_desc with
                | Pexp_ident ident when isPunnedJsxArg lbl ident stdAttrs ->
                  makeList ~break:Layout.Never [ atom "?"; atom lbl ]
                | Pexp_construct _ when value_has_jsx ->
                  label
                    (makeList ~break:Layout.Never [ atom lbl; atom "=?" ])
                    (self#simplifyUnparseExpr ~wrap:("{", "}") expression)
                | _ ->
                  label
                    (makeList ~break:Layout.Never [ atom lbl; atom "=?" ])
                    (self#dont_preserve_braces#simplifyUnparseExpr
                       ~wrap:("{", "}")
                       expression)
              in
              processArguments tail (nextAttr :: processedAttrs) children
            | (Labelled lbl, expression) :: tail ->
              let { Reason_attributes.jsxAttrs; stdAttrs; _ } =
                Reason_attributes.partitionAttributes expression.pexp_attributes
              in
              let value_has_jsx = jsxAttrs != [] in
              let nextAttr =
                match expression.pexp_desc with
                | Pexp_ident ident when isPunnedJsxArg lbl ident stdAttrs ->
                  atom lbl
                | _ when isJSXComponent expression ->
                  label
                    (atom (lbl ^ "="))
                    (makeList
                       ~break:IfNeed
                       ~wrap:("{", "}")
                       [ self#dont_preserve_braces#simplifyUnparseExpr
                           expression
                       ])
                | Pexp_open (me, e)
                  when self#isSeriesOfOpensFollowedByNonSequencyExpression
                         expression ->
                  label
                    (makeList
                       [ atom lbl
                       ; atom "="
                       ; label
                           (self#moduleExpressionToFormattedApplicationItems
                              me.popen_expr)
                           (atom ".")
                       ])
                    (self#formatNonSequencyExpression e)
                | Pexp_apply (({ pexp_desc = Pexp_ident _; _ } as funExpr), args)
                  when printedStringAndFixityExpr funExpr == Normal
                       && Reason_attributes.without_stylistic_attrs
                            expression.pexp_attributes
                          == [] ->
                  let lhs = makeList [ atom lbl; atom "=" ] in
                  (match
                     self#formatFunAppl
                       ~prefix:lhs
                       ~wrap:("{", "}")
                       ~jsxAttrs:[]
                       ~args
                       ~funExpr
                       ~applicationExpr:expression
                       ()
                   with
                  | [ x ] -> x
                  | xs -> makeList xs)
                | Pexp_apply (eFun, _) ->
                  let lhs = makeList [ atom lbl; atom "=" ] in
                  let rhs =
                    match printedStringAndFixityExpr eFun with
                    | Infix str when requireNoSpaceFor str ->
                      self#unparseExpr expression
                    | _ ->
                      self#dont_preserve_braces#simplifyUnparseExpr
                        ~wrap:("{", "}")
                        expression
                  in
                  label lhs rhs
                | Pexp_construct _ when value_has_jsx ->
                  label
                    (makeList [ atom lbl; atom "=" ])
                    (self#simplifyUnparseExpr ~wrap:("{", "}") expression)
                | Pexp_record _ | Pexp_construct _ | Pexp_array _ | Pexp_tuple _
                | Pexp_match _ | Pexp_extension _
                | Pexp_function (_, _, Pfunction_cases _) ->
                  label
                    (makeList [ atom lbl; atom "=" ])
                    (self#dont_preserve_braces#simplifyUnparseExpr
                       ~wrap:("{", "}")
                       expression)
                | Pexp_function (_ :: _, _, Pfunction_body _) ->
                  let propName = makeList [ atom lbl; atom "=" ] in
                  self#formatPexpFun
                    ~wrap:("{", "}")
                    ~prefix:propName
                    expression
                | _ ->
                  makeList
                    [ atom lbl
                    ; atom "="
                    ; self#dont_preserve_braces#simplifyUnparseExpr
                        ~wrap:("{", "}")
                        expression
                    ]
              in
              processArguments tail (nextAttr :: processedAttrs) children
            | [] -> processedAttrs, children
            | _ :: tail -> processArguments tail processedAttrs children
          in
          let reversedAttributes, children = processArguments args [] None in
          match children with
          | None ->
            makeList
              ~break:IfNeed
              ~wrap:("<" ^ componentName, "/>")
              ~pad:(true, true)
              ~inline:(false, false)
              ~postSpace:true
              (List.rev reversedAttributes)
          | Some renderedChildren ->
            let openTagAndAttrs =
              match reversedAttributes with
              | [] -> atom ("<" ^ componentName ^ ">")
              | revAttrHd :: revAttrTl ->
                let finalAttrList =
                  List.rev
                    (makeList ~break:Layout.Never [ revAttrHd; atom ">" ]
                    :: revAttrTl)
                in
                let renderedAttrList =
                  makeList
                    ~inline:(true, true)
                    ~break:IfNeed
                    ~pad:(false, false)
                    ~preSpace:true
                    finalAttrList
                in
                label ~space:true (atom ("<" ^ componentName)) renderedAttrList
            in
            label
              openTagAndAttrs
              (makeList
                 ~wrap:
                   ( ""
                   , "</"
                     ^ (match closeComponentName with
                       | None -> componentName
                       | Some close -> close)
                     ^ ">" )
                 ~inline:(true, false)
                 ~break:IfNeed
                 ~pad:(true, true)
                 ~postSpace:true
                 renderedChildren)

        (* Format Pexp_fun expression: (a, b) => a + b;
         * Example: the `onClick` prop with Pexp_fun in
         *  <div
         *    onClick={(event) => {
         *      Js.log(event);
         *      handleChange(event);
         *    }}
         *  />;
         *
         *  The arguments of the callback (Pexp_fun) should be inlined as much as
         *  possible on the same line as `onClick={`.
         *  Also notice the brace-hugging `}}` at the end.
         *
         *  ~prefix -> prefixes the Pexp_fun layout, example `onClick=`
         *  ~wrap -> wraps the `Pexp_fun` in the tuple passed to wrap, e.g. `{` and
         *  `}` for jsx
         *)
        method formatPexpFun ?(prefix = atom "") ?(wrap = "", "") expression =
          let lwrap, rwrap = wrap in
          let { Reason_attributes.stdAttrs; uncurried; _ } =
            Reason_attributes.partitionAttributes expression.pexp_attributes
          in
          if uncurried then Hashtbl.add uncurriedTable expression.pexp_loc true;

          let args, ret =
            (* omit attributes here, we're formatting them manually *)
            self#curriedPatternsAndReturnVal
              { expression with pexp_attributes = [] }
          in
          (* Format `onClick={` *)
          let propName = makeList ~wrap:("", lwrap) [ prefix ] in
          let argsList =
            let args =
              match args with [ argsList ] -> argsList | args -> makeList args
            in
            match stdAttrs with
            | [] -> args
            | attrs ->
              (* attach attributes to the args of the Pexp_fun: `[@attr]
                 (event)` *)
              let attrList =
                makeList
                  ~inline:(true, true)
                  ~break:IfNeed
                  ~postSpace:true
                  (List.map self#attribute attrs)
              in
              let all = [ attrList; args ] in
              makeList ~break:IfNeed ~inline:(true, true) ~postSpace:true all
          in
          (* Format `onClick={(event)` *)
          let propNameWithArgs = label propName argsList in
          (* Pick constraints: (a, b) :string => ... * :string is the constraint
             here *)
          let return, optConstr =
            match ret.pexp_desc with
            | Pexp_constraint (e, ct) -> e, Some (self#non_arrowed_core_type ct)
            | _ -> ret, None
          in
          let returnExpr, leftWrap =
            match self#letList return with
            | [ x ] ->
              (* Format `handleChange(event)}` or
               *  handleChange(event)
               * }
               *
               * If the closing rwrap is empty, we need it to be inline, otherwise
               * we get a empty newline when the layout breaks:
               * ```
               *  handleChange(event)
               *
               * ```
               * (Notice to nonsense newline)
               *)
              let shouldPreserveBraces =
                self#should_preserve_requested_braces return
              in
              let rwrap = if shouldPreserveBraces then "}" ^ rwrap else rwrap in
              let inlineClosing = rwrap = "" in
              let layout =
                makeList
                  ~break:IfNeed
                  ~inline:(true, inlineClosing)
                  ~wrap:("", rwrap)
                  [ x ]
              in
              layout, if shouldPreserveBraces then "{" else ""
            | xs ->
              (* Format `Js.log(event)` and `handleChange(event)` as
               * {
               *   Js.log(event);
               *   handleChange(event);
               * }}
               *)
              let layout =
                makeList
                  ~break:Always_rec
                  ~sep:(SepFinal (";", ";"))
                  ~wrap:("{", "}" ^ rwrap)
                  xs
              in
              layout, ""
          in
          match optConstr with
          | Some typeConstraint ->
            let upToConstraint =
              label
                ~space:true
                (makeList ~wrap:("", ":") [ propNameWithArgs ])
                typeConstraint
            in
            label
              (makeList ~wrap:("", " => " ^ leftWrap) [ upToConstraint ])
              returnExpr
          | None ->
            label
              (makeList ~wrap:("", " => " ^ leftWrap) [ propNameWithArgs ])
              returnExpr

        (* Creates a list of simple module expressions corresponding to module
           expression or functor application. *)
        method moduleExpressionToFormattedApplicationItems ?(prefix = "") x =
          match x with
          (* are we formatting a functor application with a module structure as arg?
           * YourLib.Make({
           *   type t = int;
           *   type s = string;
           * });
           *
           * We should "hug" the parens here: ({ & }) should stick together.
           *)
          | { pmod_desc =
                Pmod_apply
                  ( ({ pmod_desc = Pmod_ident _; _ } as m1)
                  , ({ pmod_desc = Pmod_structure _; _ } as m2) )
            ; _
            } ->
            let modIdent =
              source_map ~loc:m1.pmod_loc (self#simple_module_expr m1)
            in
            let name =
              if prefix <> ""
              then makeList ~postSpace:true [ atom prefix; modIdent ]
              else modIdent
            in
            let arg =
              source_map ~loc:m2.pmod_loc (self#simple_module_expr ~hug:true m2)
            in
            label name arg
          | _ ->
            let rec extract_apps args = function
              | { pmod_desc = Pmod_apply_unit me; _ } ->
                let head = source_map ~loc:me.pmod_loc (self#module_expr me) in
                label head (makeTup args)
              | { pmod_desc = Pmod_apply (me1, me2); _ } ->
                let arg =
                  source_map ~loc:me2.pmod_loc (self#simple_module_expr me2)
                in
                extract_apps (arg :: args) me1
              | me ->
                let head = source_map ~loc:me.pmod_loc (self#module_expr me) in
                if args == [] then head else label head (makeTup args)
            in
            let functor_application = extract_apps [] x in
            if prefix <> ""
            then makeList ~postSpace:true [ atom prefix; functor_application ]
            else functor_application

        (* Watch out, if you see something like below (sixteenTuple getting put
           on a * newline), yet a paren-wrapped list wouldn't have had an extra
           newlin, you * might need to wrap the single token (sixteenTuple) in
           [ensureSingleTokenSticksToLabel]. * let ( * axx, * oxx, * pxx * ): *
           sixteenTuple = echoTuple ( * 0, * 0, * 0 * ); *)

        method formatSimplePatternBinding
          labelOpener
          layoutPattern
          typeConstraint
          appTerms =
          let letPattern =
            label ~break:`Never ~space:true (atom labelOpener) layoutPattern
          in
          let upUntilEqual =
            match typeConstraint with
            | None -> letPattern
            | Some (tc, `Constraint) -> formatTypeConstraint letPattern tc
            | Some (tc, `Coercion ground) -> formatCoerce letPattern ground tc
          in
          let includingEqual =
            makeList ~postSpace:true [ upUntilEqual; atom "=" ]
          in
          formatAttachmentApplication
            applicationFinalWrapping
            (Some (true, includingEqual))
            appTerms

        (* The [bindingLabel] is either the function name (if let binding) or first
         * arg (if lambda).
         *
         * For defining layout of the following form:
         *
         *     lbl one
         *         two
         *         constraint => {
         *       ...
         *     }
         *
         * If using "=" as the arrow, can also be used for:
         *
         *     met private
         *         myMethod
         *         constraint = fun ...
         *
         *)
        method wrapCurriedFunctionBinding
          ?attachTo
          ~arrow
          ?(sweet = false)
          ?(spaceBeforeArrow = true)
          prefixText
          bindingLabel
          patternList
          returnedAppTerms =
          let allPatterns = bindingLabel :: patternList in
          let partitioning = curriedFunctionFinalWrapping allPatterns in
          let everythingButReturnVal =
            (* Because align_closing is set to false, you get: * * (Brackets[]
               inserted to show boundaries between open/close of pattern list) *
               let[firstThing * secondThing * thirdThing] * * It only wraps to
               indent four by coincidence: If the "opening" token was * longer,
               you'd get: * * letReallyLong[firstThing * secondThing *
               thirdThing] * * For curried let bindings, we stick the arrow in
               the *last* pattern: * let[firstThing * secondThing * thirdThing
               =>] * * But it could have just as easily been the "closing" token
               corresponding to * "let". This works because we have
               [align_closing = false]. The benefit of * shoving it in the last
               pattern, is that we can turn [align_closing = true] * and still
               have the arrow stuck to the last pattern (which is usually what
               we * want) (See modeTwo below). *)
            match partitioning with
            | None when sweet ->
              makeList
                ~pad:(false, spaceBeforeArrow)
                ~wrap:("", arrow)
                ~indent:(settings.space * settings.indentWrappedPatternArgs)
                ~postSpace:true
                ~inline:(true, true)
                ~break:IfNeed
                allPatterns
            | None ->
              (* We want the binding label to break *with* the arguments. Again,
                 there's no apparent way to add additional indenting for the
                 args with this setting. *)

              (* Formats lambdas by treating the first pattern as the *
                 "bindingLabel" which is kind of strange in some cases (when *
                 you only have one arg that wraps)... * * echoTheEchoer ( * fun
                 ( * a, * p * ) => ( * a, * b * ) * * But it makes sense in
                 others (where you have multiple args): * * echoTheEchoer ( *
                 fun ( * a, * p * ) * mySecondArg * myThirdArg => ( * a, * b * )
                 * * Try any other convention for wrapping that first arg and it
                 * won't look as balanced when adding multiple args. *)
              makeList
                ~pad:(true, spaceBeforeArrow)
                ~wrap:(prefixText, arrow)
                ~indent:(settings.space * settings.indentWrappedPatternArgs)
                ~postSpace:true
                ~inline:(true, true)
                ~break:IfNeed
                allPatterns
            | Some (attachedList, wrappedListy) ->
              (* To get *only* the final argument to "break", while not
                 necessarily breaking the prior arguments, we dock everything
                 but the last item to a created label *)
              label
                ~space:true
                (makeList
                   ~pad:(true, spaceBeforeArrow)
                   ~wrap:(prefixText, arrow)
                   ~indent:(settings.space * settings.indentWrappedPatternArgs)
                   ~postSpace:true
                   ~inline:(true, true)
                   ~break:IfNeed
                   attachedList)
                wrappedListy
          in

          let everythingButAppTerms =
            match attachTo with
            | None -> everythingButReturnVal
            | Some toThis -> label ~space:true toThis everythingButReturnVal
          in
          formatAttachmentApplication
            applicationFinalWrapping
            (Some (true, everythingButAppTerms))
            returnedAppTerms

        method leadingCurriedAbstractTypes x =
          let rec argsAndReturn xx =
            match xx.pexp_desc with
            | Pexp_newtype (str, e) ->
              let nextArgs, return = argsAndReturn e in
              str :: nextArgs, return
            | _ -> [], xx.pexp_desc
          in
          argsAndReturn x

        method curriedConstructorPatternsAndReturnVal cl =
          let rec argsAndReturn args = function
            | { pcl_desc = Pcl_fun (label, eo, p, e); pcl_attributes = []; _ }
              ->
              let arg =
                source_map ~loc:p.ppat_loc (self#label_exp label eo p)
              in
              argsAndReturn (arg :: args) e
            | xx ->
              if args == []
              then None, xx
              else Some (makeTup (List.rev args)), xx
          in
          argsAndReturn [] cl

        (* Returns the arguments list (if any, that occur before the =>), and
           the final expression (that is either returned from the function
           (after =>) or that is bound to the value (if there are no arguments,
           and this is just a let pattern binding)). *)
        method curriedPatternsAndReturnVal x =
          let uncurried =
            try Hashtbl.find uncurriedTable x.pexp_loc with Not_found -> false
          in
          let rec extract_args =
            let extract_from_params param =
              match param.pparam_desc with
              | Pparam_val (lbl, eo, pat) -> `Value (lbl, eo, pat)
              | Pparam_newtype newtype -> `Type newtype
            in
            fun xx ->
              let { Reason_attributes.stdAttrs; _ } =
                Reason_attributes.partitionAttributes
                  ~allowUncurry:false
                  xx.pexp_attributes
              in
              if stdAttrs != []
              then [], xx
              else
                match xx.pexp_desc with
                | Pexp_function (params, constraint_, body) ->
                  let vs = List.map extract_from_params params in
                  (match constraint_ with
                  | Some _ -> vs, xx
                  | None ->
                    (match body with
                    | Pfunction_cases _ as c ->
                      vs, { xx with pexp_desc = Pexp_function ([], None, c) }
                    | Pfunction_body e ->
                      let args, ret = extract_args e in
                      vs @ args, ret))
                | Pexp_newtype (newtype, e) ->
                  let args, ret = extract_args e in
                  `Type newtype :: args, ret
                | Pexp_constraint _ -> [], xx
                | _ -> [], xx
          in
          let prepare_arg = function
            | `Value (l, eo, p) ->
              source_map ~loc:p.ppat_loc (self#label_exp l eo p)
            | `Type nt -> atom ("type " ^ nt.txt)
          in
          let single_argument_no_parens p ret =
            if uncurried
            then false
            else
              let isUnitPat = is_unit_pattern p in
              let isAnyPat = is_any_pattern p in
              match ret.pexp_desc with
              (* (event) :ReasonReact.event => {...}
               * The above Pexp_fun with constraint ReasonReact.event requires parens
               * surrounding the single argument `event`.*)
              | Pexp_constraint _ when (not isUnitPat) && not isAnyPat -> false
              | _ -> isUnitPat || isAnyPat || is_ident_pattern p
          in
          match extract_args x with
          | [], ret -> [], ret
          | [ `Value (Nolabel, None, p) ], ret
            when is_unit_pattern p && uncurried ->
            [ atom "(.)" ], ret
          | [ (`Value (Nolabel, None, p) as arg) ], ret
            when single_argument_no_parens p ret ->
            [ prepare_arg arg ], ret
          | args, ret -> [ makeTup ~uncurried (List.map prepare_arg args) ], ret

        (* Returns the (curriedModule, returnStructure) for a functor *)
        method curriedFunctorPatternsAndReturnStruct =
          function
          (* string loc * module_type option * module_expr *)
          | { pmod_desc = Pmod_functor (fp, me2); _ } ->
            let firstOne =
              match fp with
              | Unit -> atom ""
              | Named (s, mt') ->
                let s = moduleIdent s in
                self#module_type (makeList [ atom s; atom ":" ]) mt'
            in
            let functorArgsRecurse, returnStructure =
              self#curriedFunctorPatternsAndReturnStruct me2
            in
            firstOne :: functorArgsRecurse, returnStructure
          | me -> [], me

        method isRenderableAsPolymorphicAbstractTypes
          typeVars
          polyType
          leadingAbstractVars
          nonVarifiedType =
          same_ast_modulo_varification_and_extensions polyType nonVarifiedType
          && for_all2' string_loc_equal typeVars leadingAbstractVars

        (* Reinterpret this as a pattern constraint since we don't currently
           have a * way to disambiguate. There is currently a way to
           disambiguate a parsing * from Ppat_constraint vs. Pexp_constraint.
           Currently (and consistent with * OCaml standard parser):

           * let (x: typ) = blah; * Becomes Ppat_constraint * let x:poly . type
           = blah; * Becomes Ppat_constraint * let x:typ = blah; * Becomes
           Pexp_constraint(ghost) * let x = (blah:typ); * Becomes
           Pexp_constraint(ghost) * * How are double constraints represented? *
           let (x:typ) = (blah:typ); * If currently both constraints are parsed
           into a single Pexp_constraint, * then something must be lost, and how
           could you fail type checking on: * let x:int = (10:string) ?? Answer:
           It probably parses into a nested * Pexp_constraint. * * Proposal: * *
           let (x: typ) = blah; * Becomes Ppat_constraint (still) * let x:poly .
           type = blah; * Becomes Ppat_constraint (still) * let x:typ = blah; *
           Becomes Ppat_constraint * let x = blah:typ; * Becomes Pexp_constraint
           * * * Reasoning: Allows parsing of any of the currently valid ML
           forms, but * combines the two most similar into one form. The only
           lossyness is the * unnecessary parens, which there is already
           precedence for dropping in * expressions. In the existing approach,
           preserving a paren-constrained * expression is *impossible* because
           it becomes pretty printed as * let x:t =.... In the proposal, it is
           not impossible - it is only * impossible to preserve unnecessary
           parenthesis around the let binding. * * The one downside is that
           integrating with existing code that uses [let x = * (blah:typ)] in
           standard OCaml will be parsed as a Pexp_constraint. There * might be
           some lossiness (beyond parens) that occurs in the original OCaml *
           parser. *)

        method locallyAbstractPolymorphicFunctionBinding
          prefixText
          layoutPattern
          funWithNewTypes
          absVars
          bodyType =
          let appTerms = self#unparseExprApplicationItems funWithNewTypes in
          let locallyAbstractTypes = List.map (fun x -> atom x.txt) absVars in
          let typeLayout =
            source_map ~loc:bodyType.ptyp_loc (self#core_type bodyType)
          in
          let polyType =
            label
              ~space:true
              (* TODO: This isn't a correct use of sep! It ruins how * comments
                 are interleaved. *)
              (makeList
                 [ makeList ~sep:(Sep " ") (atom "type" :: locallyAbstractTypes)
                 ; atom "."
                 ])
              typeLayout
          in
          self#formatSimplePatternBinding
            prefixText
            layoutPattern
            (Some (polyType, `Constraint))
            appTerms

        (*  Intelligently switches between:
         *  Curried function binding w/ constraint on return expr:
         *     lbl patt
         *         pattAux
         *         arg
         *         :constraint => {
         *       ...
         *     }
         *
         *  Constrained:
         *     lbl patt
         *         pattAux...
         *         :constraint = {
         *       ...
         *     }
         *)
        method wrappedBinding prefixText ~arrow ?vbct pattern patternAux expr =
          let expr = self#process_underscore_application expr in
          let argsList, return = self#curriedPatternsAndReturnVal expr in
          let patternList =
            match patternAux with
            | [] -> pattern
            | _ :: _ ->
              makeList
                ~postSpace:true
                ~inline:(true, true)
                ~break:IfNeed
                (pattern :: patternAux)
          in
          match argsList, return.pexp_desc with
          | [], Pexp_constraint (e, ct) ->
            assert (vbct = None);
            let typeLayout =
              source_map
                ~loc:ct.ptyp_loc
                (match ct.ptyp_desc with
                | Ptyp_package (li, cstrs) -> self#typ_package li cstrs
                | _ -> self#core_type ct)
            in
            let appTerms = self#unparseExprApplicationItems e in
            self#formatSimplePatternBinding
              prefixText
              patternList
              (Some (typeLayout, `Constraint))
              appTerms
          | [], _ ->
            (* simple let binding, e.g. `let number = 5` *)
            (* let f = (. a, b) => a + b; *)
            let appTerms = self#unparseExprApplicationItems expr in
            self#formatSimplePatternBinding prefixText patternList vbct appTerms
          | _ :: _, _ ->
            let argsWithConstraint, actualReturn =
              self#normalizeFunctionArgsConstraint argsList return
            in
            let fauxArgs = List.concat [ patternAux; argsWithConstraint ] in
            let returnedAppTerms =
              self#unparseExprApplicationItems actualReturn
            in
            (* Attaches the `=` to `f` to recreate javascript function syntax in
             * let f = (a, b) => a + b; *)
            let lbl =
              let pattern =
                match vbct with
                | None -> pattern
                | Some (x, `Constraint) ->
                  label ~indent:0 pattern (formatJustTheTypeConstraint x)
                | Some (x, `Coercion ground) ->
                  label ~indent:0 pattern (formatJustCoerce ground x)
              in
              makeList ~sep:(Sep " ") ~break:Layout.Never [ pattern; atom "=" ]
            in
            self#wrapCurriedFunctionBinding
              prefixText
              ~arrow
              lbl
              fauxArgs
              returnedAppTerms

        (* Similar to the above method. *)
        method wrappedClassBinding prefixText pattern patternAux expr =
          let args, return = self#curriedConstructorPatternsAndReturnVal expr in
          let patternList =
            match patternAux with
            | [] -> pattern
            | _ :: _ ->
              makeList
                ~postSpace:true
                ~inline:(true, true)
                ~break:IfNeed
                (pattern :: patternAux)
          in
          match args, return.pcl_desc with
          | None, Pcl_constraint (e, ct) ->
            let typeLayout =
              source_map ~loc:ct.pcty_loc (self#class_constructor_type ct)
            in
            self#formatSimplePatternBinding
              prefixText
              patternList
              (Some (typeLayout, `Constraint))
              (self#classExpressionToFormattedApplicationItems e, None)
          | None, _ ->
            self#formatSimplePatternBinding
              prefixText
              patternList
              None
              (self#classExpressionToFormattedApplicationItems expr, None)
          | Some args, _ ->
            let argsWithConstraint, actualReturn =
              self#normalizeConstructorArgsConstraint [ args ] return
            in
            let fauxArgs = List.concat [ patternAux; argsWithConstraint ] in
            self#wrapCurriedFunctionBinding
              prefixText
              ~arrow:"="
              pattern
              fauxArgs
              ( self#classExpressionToFormattedApplicationItems actualReturn
              , None )

        (* Attaches doc comments to a layout, with whitespace preserved *
           Example: * /** Doc comment */ * * /* another random comment */ * let
           a = 1; *)
        method attachDocAttrsToLayout
          ~(* all std attributes attached on the ast node backing the layout *)
          (stdAttrs : Parsetree.attributes)
          ~(* all doc comments attached on the ast node backing the layout *)
          (docAttrs : Parsetree.attributes)
          ~(* location of the layout *)
           loc
          ~(* layout to attach the doc comments to *)
           layout
          () =
          (* compute the correct location of layout * Example: * 1| /**
             doc-comment */ * 2| * 3| [@attribute] * 4| let a = 1; * * The
             location might indicate a start of line 4 for the ast-node *
             representing `let a = 1`. The reality is that `[@attribute]` should
             be * included (start of line 3), to represent the correct start
             location * of the whole layout. *)
          let loc =
            match stdAttrs with
            | { attr_name = astLoc; _ } :: _ -> astLoc.loc
            | [] -> loc
          in
          let rec aux prevLoc layout = function
            | ({ attr_name = x; _ } as attr : Parsetree.attribute) :: xs ->
              let newLayout =
                let range = Range.makeRangeBetween x.loc prevLoc in
                let layout =
                  if Range.containsWhitespace ~range ~comments:self#comments ()
                  then
                    let region = WhitespaceRegion.make ~range ~newlines:1 () in
                    Layout.Whitespace (region, layout)
                  else layout
                in
                makeList
                  ~inline:(true, true)
                  ~break:Always
                  [ self#attribute attr; layout ]
              in
              aux x.loc newLayout xs
            | [] -> layout
          in
          aux loc layout (List.rev docAttrs)

        method value_binding
          prefixText
          { pvb_pat; pvb_attributes; pvb_loc; pvb_expr; pvb_constraint } =
          self#binding
            prefixText
            ~attrs:pvb_attributes
            ~loc:pvb_loc
            ~pat:pvb_pat
            ?pvb_constraint
            pvb_expr

        method binding_op prefixText { pbop_pat; pbop_loc; pbop_exp; _ } =
          self#binding
            (Reason_syntax_util.escape_stars_slashes prefixText)
            ~loc:pbop_loc
            ~pat:pbop_pat
            pbop_exp

        method binding prefixText ?(attrs = []) ~loc ~pat ?pvb_constraint expr =
          (* TODO: print attributes *)
          let body =
            let vbct =
              match pvb_constraint with
              | Some (Pvc_constraint { locally_abstract_univars = []; typ }) ->
                Some (self#core_type typ, `Constraint)
              | Some (Pvc_constraint { locally_abstract_univars = vars; typ })
                ->
                Some
                  ( label
                      ~space:true
                      (* TODO: This isn't a correct use of sep! It ruins how *
                         comments are interleaved. *)
                      (makeList
                         [ makeList
                             ~sep:(Sep " ")
                             (atom "type" :: List.map (fun v -> atom v.txt) vars)
                         ; atom "."
                         ])
                      (self#core_type typ)
                  , `Constraint )
              | Some (Pvc_coercion { ground; coercion }) ->
                Some
                  ( self#core_type coercion
                  , `Coercion
                      (match ground with
                      | Some ground -> Some (self#core_type ground)
                      | None -> None) )
              | None -> None
            in
            match pat.ppat_attributes, pat.ppat_desc with
            | [], Ppat_var _ ->
              self#wrappedBinding
                prefixText
                ~arrow:"=>"
                (source_map ~loc:pat.ppat_loc (self#simple_pattern pat))
                ?vbct
                []
                expr
            (* Ppat_constraint is used in bindings of the form * * let
               (inParenVar:typ) = ... * * And in the case of let bindings for
               explicitly polymorphic type * annotations (see parser for more
               details). * * See reason_parser.mly for explanation of how we
               encode the two primary * forms of explicit polymorphic
               annotations in the parse tree, and how * we must recover them
               here. *)
            | [], Ppat_open (lid, { ppat_desc = Ppat_record (l, closed); _ }) ->
              (* Special case handling for:
               *
               * let Foo.{
               *   destruct1,
               *   destruct2,
               *   destruct3,
               *   destruct4,
               *   destruct5,
               * } = bar;
               *)
              let upUntilEqual =
                let pat = self#patternRecord l closed in
                label
                  (label
                     ~space:true
                     (atom prefixText)
                     (label (self#longident_loc lid) (atom ".")))
                  pat
              in
              let appTerms = self#unparseExprApplicationItems expr in
              let includingEqual =
                let vbct =
                  match vbct with
                  | Some (x, `Constraint) -> [ formatJustTheTypeConstraint x ]
                  | Some (x, `Coercion ground) -> [ formatJustCoerce ground x ]
                  | None -> []
                in
                makeList ~postSpace:true ((upUntilEqual :: vbct) @ [ atom "=" ])
              in
              formatAttachmentApplication
                applicationFinalWrapping
                (Some (true, includingEqual))
                appTerms
            | [], Ppat_constraint (p, ty) ->
              (* Locally abstract forall types are *seriously* mangled by the parsing
               * stage, and we have to be very smart about how to recover it.
               *
               *  let df_locallyAbstractFuncAnnotated:
               *    type a b.
               *      a =>
               *      b =>
               *      (inputEchoRecord a, inputEchoRecord b) =
               *    fun (input: a) (input2: b) => (
               *      {inputIs: input},
               *      {inputIs: input2}
               *    );
               *
               * becomes:
               *
               *   let df_locallyAbstractFuncAnnotatedTwo:
               *     'a 'b .
               *     'a => 'b => (inputEchoRecord 'a, inputEchoRecord 'b)
               *    =
               *     fun (type a) (type b) => (
               *       fun (input: a) (input2: b) => ({inputIs: input}, {inputIs:input2}):
               *         a => b => (inputEchoRecord a, inputEchoRecord b)
               *     );
               *)
              let layoutPattern =
                source_map ~loc:pat.ppat_loc (self#simple_pattern p)
              in
              let leadingAbsTypesAndExpr =
                self#leadingCurriedAbstractTypes expr
              in
              (match p.ppat_desc, ty.ptyp_desc, leadingAbsTypesAndExpr with
              | ( Ppat_var _
                , Ptyp_poly (typeVars, varifiedPolyType)
                , ( (_ :: _ as absVars)
                  , Pexp_constraint (funWithNewTypes, nonVarifiedExprType) ) )
                when self#isRenderableAsPolymorphicAbstractTypes
                       typeVars
                       (* If even artificially varified - don't know until
                          returns*)
                       varifiedPolyType
                       absVars
                       nonVarifiedExprType ->
                (* We assume was the case whenever we see this pattern in the *
                   AST, it was because the parser parsed the polymorphic locally
                   * abstract type sugar. * *
                   Ppat_var..Ptyp_poly...Pexp_constraint: * * let x: 'a 'b . 'a
                   => 'b => 'b = * fun (type a) (type b) => * (fun aVal bVal =>
                   bVal : a => b => b); * * We need to be careful not to
                   accidentally detect similar * forms, that cannot be printed
                   as sugar. * * let x: 'a 'b . 'a => 'b => 'b = * fun (type a)
                   (type b) => * (fun aVal bVal => bVal : int => int => int); *
                   * Should *NOT* be formatted as: * * let x: type a b. int =>
                   int => int = fun aVal bVal => bVal; * * The helper function *
                   [same_ast_modulo_varification_and_extensions] was created to
                   * help compare the varified constraint pattern body, and the
                   * non-varified expression constraint type. * * The second
                   requirement that we check before assuming that the * sugar
                   form is correct, is to make sure the list of type vars *
                   corresponds to a leading prefix of the Pexp_newtype
                   variables. *)
                self#locallyAbstractPolymorphicFunctionBinding
                  prefixText
                  layoutPattern
                  funWithNewTypes
                  absVars
                  nonVarifiedExprType
              | _ ->
                let typeLayout, layoutPattern =
                  let typeLayout =
                    source_map ~loc:ty.ptyp_loc (self#core_type ty)
                  in
                  match vbct with
                  | Some _ ->
                    (* nested constraints *)
                    ( vbct
                    , makeList
                        ~wrap:("(", ")")
                        [ layoutPattern
                        ; formatJustTheTypeConstraint typeLayout
                        ] )
                  | None -> Some (typeLayout, `Constraint), layoutPattern
                in
                let appTerms = self#unparseExprApplicationItems expr in
                self#formatSimplePatternBinding
                  prefixText
                  layoutPattern
                  typeLayout
                  appTerms)
            | _ ->
              let layoutPattern =
                source_map
                  ~loc:pat.ppat_loc
                  (match vbct with
                  | Some _ ->
                    self#pattern_with_precedence ~attrs:pat.ppat_attributes pat
                  | None -> self#pattern pat)
              in
              let appTerms = self#unparseExprApplicationItems expr in
              self#formatSimplePatternBinding
                prefixText
                layoutPattern
                vbct
                appTerms
          in
          let { Reason_attributes.stdAttrs; docAttrs; _ } =
            Reason_attributes.partitionAttributes ~partDoc:true attrs
          in
          let body = makeList ~inline:(true, true) [ body ] in
          let layout =
            self#attach_std_item_attrs stdAttrs (source_map ~loc body)
          in
          self#attachDocAttrsToLayout
            ~stdAttrs
            ~docAttrs
            ~loc:pat.ppat_loc
            ~layout
            ()

        (* Ensures that the constraint is formatted properly for sake of
           function binding (formatted without arrows) let x y z :
           no_unguarded_arrows_allowed_here => ret; *)
        method normalizeFunctionArgsConstraint argsList return =
          match return.pexp_desc with
          | Pexp_constraint (e, ct) ->
            let typeLayout =
              source_map
                ~loc:ct.ptyp_loc
                (self#non_arrowed_non_simple_core_type ct)
            in
            ( [ makeList
                  ~break:IfNeed
                  ~inline:(true, true)
                  (argsList @ [ formatJustTheTypeConstraint typeLayout ])
              ]
            , e )
          | _ -> argsList, return

        method normalizeConstructorArgsConstraint argsList return =
          match return.pcl_desc with
          | Pcl_constraint (e, ct) when return.pcl_attributes == [] ->
            let typeLayout =
              source_map
                ~loc:ct.pcty_loc
                (self#non_arrowed_class_constructor_type ct)
            in
            argsList @ [ formatJustTheTypeConstraint typeLayout ], e
          | _ -> argsList, return

        method bindingsLocationRange ?extension l =
          let len = List.length l in
          let fstLoc =
            match extension with
            | Some ({ pexp_loc = { loc_ghost = false; _ }; _ } as ext) ->
              ext.pexp_loc
            | _ -> (List.nth l 0).pvb_loc
          in
          let lstLoc = (List.nth l (len - 1)).pvb_loc in
          { loc_start = fstLoc.loc_start
          ; loc_end = lstLoc.loc_end
          ; loc_ghost = false
          }

        method bindingOpsLocationRange { let_; ands; _ } =
          let fstLoc = let_.pbop_loc in
          let lstLoc =
            match ands with
            | [] -> fstLoc
            | xs ->
              let len = List.length xs in
              (List.nth xs (len - 1)).pbop_loc
          in
          { loc_start = fstLoc.loc_start
          ; loc_end = lstLoc.loc_end
          ; loc_ghost = false
          }

        method bindings ?extension (rf, l) =
          let label = add_extension_sugar "let" extension in
          let label =
            match rf with Nonrecursive -> label | Recursive -> label ^ " rec"
          in
          match l with
          | [ x ] -> self#value_binding label x
          | l ->
            let items =
              List.mapi
                (fun i x ->
                   let loc = extractLocValBinding x in
                   let layout =
                     self#value_binding (if i == 0 then label else "and") x
                   in
                   loc, layout)
                l
            in
            let itemsLayout =
              groupAndPrint
                ~xf:(fun (_, layout) -> layout)
                ~getLoc:(fun (loc, _) -> loc)
                ~comments:self#comments
                items
            in
            makeList
              ~postSpace:true
              ~break:Always
              ~indent:0
              ~inline:(true, true)
              itemsLayout

        method letop_bindings { let_; ands; _ } =
          let label =
            Reason_syntax_util.compress_letop_identifier let_.pbop_op.txt
          in
          let let_item = self#binding_op label let_ in
          match ands with
          | [] -> let_item
          | l ->
            let and_items =
              List.map
                (fun x ->
                   let loc = extractLocBindingOp x in
                   let layout =
                     self#binding_op
                       (Reason_syntax_util.compress_letop_identifier
                          x.pbop_op.txt)
                       x
                   in
                   loc, layout)
                l
            in
            let itemsLayout =
              groupAndPrint
                ~xf:(fun (_, layout) -> layout)
                ~getLoc:(fun (loc, _) -> loc)
                ~comments:self#comments
                ((extractLocBindingOp let_, let_item) :: and_items)
            in
            makeList
              ~postSpace:true
              ~break:Always
              ~indent:0
              ~inline:(true, true)
              itemsLayout

        method pexp_open ~attrs ?extension expr me =
          let openLayout =
            label
              ~space:true
              (atom
                 (add_open_extension_sugar
                    ~override:me.popen_override
                    extension))
              (self#moduleExpressionToFormattedApplicationItems me.popen_expr)
          in
          let attrsOnOpen =
            makeList
              ~inline:(true, true)
              ~postSpace:true
              ~break:Always
              (self#attributes attrs @ [ openLayout ])
          in
          (* Just like the bindings, have to synthesize a location since the *
             Pexp location is parsed (potentially) beginning with the open *
             brace {} in the let sequence. *)
          let layout = source_map ~loc:me.popen_loc attrsOnOpen in
          let loc =
            { me.popen_loc with
              loc_start =
                { me.popen_loc.loc_start with
                  pos_lnum = expr.pexp_loc.loc_start.pos_lnum
                }
            }
          in
          loc, layout

        method letList expr =
          let letModuleBinding ?extension s me =
            let prefixText = add_extension_sugar "module" extension in
            let bindingName = atom ~loc:s.loc (moduleIdent s) in
            let moduleExpr = me in
            let letModuleLayout =
              self#let_module_binding prefixText bindingName moduleExpr
            in
            let letModuleLoc =
              { loc_start = s.loc.loc_start
              ; loc_end = me.pmod_loc.loc_end
              ; loc_ghost = false
              }
            in
            (* Just like the bindings, have to synthesize a location since the
             * Pexp location is parsed (potentially) beginning with the open
             * brace {} in the let sequence. *)
            let layout = source_map ~loc:letModuleLoc letModuleLayout in
            let _, return =
              self#curriedFunctorPatternsAndReturnStruct moduleExpr
            in
            let loc = { letModuleLoc with loc_end = return.pmod_loc.loc_end } in
            loc, layout
          in
          (* Recursively transform a nested ast of "let-items", into a flat *
             list containing the location indicating start/end of the "let-item"
             and * its layout. *)
          let rec processLetList acc expr =
            let { Reason_attributes.stdAttrs
                ; arityAttrs
                ; jsxAttrs
                ; stylisticAttrs
                ; _
                }
              =
              Reason_attributes.partitionAttributes
                ~allowUncurry:false
                expr.pexp_attributes
            in
            match stdAttrs, expr.pexp_desc with
            | [], Pexp_let (rf, l, e) ->
              (* For "letList" bindings, the start/end isn't as simple as with
               * module value bindings. For "let lists", the sequences were formed
               * within braces {}. The parser relocates the first let binding to the
               * first brace. *)
              let bindingsLayout = self#bindings (rf, l) in
              let bindingsLoc = self#bindingsLocationRange l in
              let layout = source_map ~loc:bindingsLoc bindingsLayout in
              processLetList ((bindingsLoc, layout) :: acc) e
            | attrs, Pexp_letop ({ body; _ } as op) ->
              (* For "letList" bindings, the start/end isn't as simple as with
               * module value bindings. For "let lists", the sequences were formed
               * within braces {}. The parser relocates the first let binding to the
               * first brace. *)
              let bindingsLayout = self#letop_bindings op in
              let bindingsLoc = self#bindingOpsLocationRange op in
              let bindingsLayout =
                makeList
                  ~break:IfNeed
                  ~inline:(true, true)
                  ~postSpace:true
                  (self#attributes attrs @ [ bindingsLayout ])
              in
              let layout = source_map ~loc:bindingsLoc bindingsLayout in
              processLetList ((bindingsLoc, layout) :: acc) body
            | attrs, Pexp_open (me, e)
            (* Add this when check to make sure these are handled as regular
               "simple expressions" *)
              when not
                     (self#isSeriesOfOpensFollowedByNonSequencyExpression
                        { expr with pexp_attributes = [] }) ->
              if Reason_attributes.has_open_notation_attr stylisticAttrs
              then
                ( Location.none
                , label
                    (label
                       (self#moduleExpressionToFormattedApplicationItems
                          me.popen_expr)
                       (atom "."))
                    (makeLetSequence ~wrap:("(", ")") (self#letList e)) )
                :: acc
              else
                let loc, layout = self#pexp_open ~attrs expr me in
                processLetList ((loc, layout) :: acc) e
            | [], Pexp_letmodule (s, me, e) ->
              let loc, layout = letModuleBinding s me in
              processLetList ((loc, layout) :: acc) e
            | [], Pexp_letexception (extensionConstructor, expr) ->
              let exc = self#exception_declaration extensionConstructor in
              let layout = source_map ~loc:extensionConstructor.pext_loc exc in
              processLetList
                ((extensionConstructor.pext_loc, layout) :: acc)
                expr
            | [], Pexp_sequence (({ pexp_desc = Pexp_sequence _; _ } as e1), e2)
            | [], Pexp_sequence (({ pexp_desc = Pexp_let _; _ } as e1), e2)
            | [], Pexp_sequence (({ pexp_desc = Pexp_open _; _ } as e1), e2)
            | [], Pexp_sequence (({ pexp_desc = Pexp_letmodule _; _ } as e1), e2)
            | [], Pexp_sequence (e1, e2) ->
              let e1Layout =
                match expression_not_immediate_extension_sugar e1 with
                | Some (extension, e) ->
                  self#attach_std_item_attrs ~extension [] (self#unparseExpr e)
                | None -> self#unparseExpr e1
              in
              let loc = e1.pexp_loc in
              let layout = source_map ~loc e1Layout in
              processLetList ((loc, layout) :: acc) e2
            | _ ->
              let expr =
                { expr with pexp_attributes = arityAttrs @ stdAttrs @ jsxAttrs }
              in
              (match expression_not_immediate_extension_sugar expr with
              | Some
                  ( extension
                  , { pexp_attributes = []; pexp_desc = Pexp_let (rf, l, e); _ }
                  ) ->
                let bindingsLayout = self#bindings ~extension (rf, l) in
                let bindingsLoc =
                  self#bindingsLocationRange ~extension:expr l
                in
                let layout = source_map ~loc:bindingsLoc bindingsLayout in
                processLetList
                  ((extractLocationFromValBindList expr l, layout) :: acc)
                  e
              | Some
                  ( extension
                  , { pexp_attributes = []
                    ; pexp_desc = Pexp_letmodule (s, me, e)
                    ; _
                    } ) ->
                let loc, layout = letModuleBinding ~extension s me in
                processLetList ((loc, layout) :: acc) e
              | Some
                  ( extension
                  , { pexp_attributes = attrs
                    ; pexp_desc = Pexp_open (me, e)
                    ; _
                    } ) ->
                let loc, layout = self#pexp_open ~attrs ~extension expr me in
                processLetList ((loc, layout) :: acc) e
              | Some (extension, e) ->
                let layout =
                  self#attach_std_item_attrs ~extension [] (self#unparseExpr e)
                in
                (expr.pexp_loc, layout) :: acc
              | None ->
                (* Should really do something to prevent infinite loops here.
                   Never allowing a top level call into letList to recurse back
                   to self#unparseExpr- top level calls into letList *must* be
                   one of the special forms above whereas lower level recursive
                   calls may be of any form. *)
                let layout =
                  source_map ~loc:expr.pexp_loc (self#unparseExpr expr)
                in
                (expr.pexp_loc, layout) :: acc)
          in
          let es = processLetList [] expr in
          (* Interleave whitespace between the "let-items" when appropriate *)
          groupAndPrint
            ~xf:(fun (_, layout) -> layout)
            ~getLoc:(fun (loc, _) -> loc)
            ~comments:self#comments
            (List.rev es)

        method constructor_expression
          ?(polyVariant = false)
          ~arityIsClear
          stdAttrs
          ctor
          eo =
          let implicit_arity, arguments =
            match eo.pexp_desc with
            | Pexp_construct ({ txt = Lident "()"; _ }, _) ->
              (* `foo() is a polymorphic variant that contains a single unit
                 construct as expression * This requires special formatting:
                 `foo(()) -> `foo() *)
              false, atom "()"
            (* special printing: MyConstructor(()) -> MyConstructor() *)
            | Pexp_tuple l when is_single_unit_construct l -> false, atom "()"
            | Pexp_tuple l when polyVariant == true ->
              false, self#unparseSequence ~wrap:("(", ")") ~construct:`Tuple l
            | Pexp_tuple l ->
              (* There is no ambiguity when the number of tuple components is 1.
                 We don't need put implicit_arity in that case *)
              (match l with
              | exprList when isSingleArgParenApplication exprList ->
                false, self#singleArgParenApplication exprList
              | _ ->
                not arityIsClear, makeTup (List.map self#unparseProtectedExpr l))
            | _ when isSingleArgParenApplication [ eo ] ->
              false, self#singleArgParenApplication [ eo ]
            | _ -> false, makeTup [ self#unparseProtectedExpr eo ]
          in
          let arguments = source_map ~loc:eo.pexp_loc arguments in
          let construction =
            label
              ctor
              (if isSequencey arguments
               then arguments
               else ensureSingleTokenSticksToLabel arguments)
          in
          let attrs =
            if implicit_arity && not polyVariant
            then
              { attr_name = { txt = "implicit_arity"; loc = eo.pexp_loc }
              ; attr_payload = PStr []
              ; attr_loc = eo.pexp_loc
              }
              :: stdAttrs
            else stdAttrs
          in
          match attrs with
          | [] -> construction
          | _ :: _ -> formatAttributed construction (self#attributes attrs)

        (* TODOATTRIBUTES: Handle stdAttrs here (merge with implicit_arity) *)
        method constructor_pattern ?(polyVariant = false) ~arityIsClear ctor po
            =
          let implicit_arity, arguments =
            match po.ppat_desc with
            (* There is no ambiguity when the number of tuple components is 1.
               We don't need put implicit_arity in that case *)
            | Ppat_tuple (([] | _ :: []) as l) -> false, l
            | Ppat_tuple l -> not arityIsClear, l
            | _ -> false, [ po ]
          in
          let space, arguments =
            match arguments with
            | [ x ] when is_direct_pattern x -> true, self#simple_pattern x
            | xs when isSingleArgParenPattern xs ->
              false, self#singleArgParenPattern xs
            (* Optimize the case when it's a variant holding a shot variable -
               avoid trailing*)
            | [ ({ ppat_desc = Ppat_constant (Pconst_string (s, _, None)); _ }
                 as x)
              ]
            | [ ({ ppat_desc = Ppat_construct ({ txt = Lident s; _ }, None); _ }
                 as x)
              ]
            | [ ({ ppat_desc = Ppat_var { txt = s; _ }; _ } as x) ]
              when Reason_heuristics.singleTokenPatternOmmitTrail s ->
              let layout = makeTup ~trailComma:false [ self#pattern x ] in
              false, source_map ~loc:po.ppat_loc layout
            | [ ({ ppat_desc = Ppat_any; _ } as x) ]
            | [ ({ ppat_desc = Ppat_constant (Pconst_char _); _ } as x) ]
            | [ ({ ppat_desc = Ppat_constant (Pconst_integer _); _ } as x) ] ->
              let layout = makeTup ~trailComma:false [ self#pattern x ] in
              false, source_map ~loc:po.ppat_loc layout
            | xs ->
              let layout = makeTup (List.map self#pattern xs) in
              false, source_map ~loc:po.ppat_loc layout
          in
          let construction = label ~space ctor arguments in
          if implicit_arity && not polyVariant
          then
            formatAttributed
              construction
              (self#attributes
                 [ { attr_name = { txt = "implicit_arity"; loc = po.ppat_loc }
                   ; attr_payload = PStr []
                   ; attr_loc = po.ppat_loc
                   }
                 ])
          else construction

        (* Provides special printing for constructor arguments:
         * iff there's one argument & they have some kind of wrapping,
         * they're wrapping need to 'hug' the surrounding parens.
         * Example:
         *  switch x {
         *  | Some({
         *      a,
         *      b,
         *    }) => ()
         *  }
         *
         *  Notice how ({ and }) hug.
         *  This applies for records, arrays, tuples & lists.
         *  Also see `isSingleArgParenPattern` to determine if this kind of wrapping applies.
         *)
        method singleArgParenPattern =
          function
          | [ { ppat_desc = Ppat_record (l, closed); ppat_loc = loc; _ } ] ->
            source_map ~loc (self#patternRecord ~wrap:("(", ")") l closed)
          | [ { ppat_desc = Ppat_array l; ppat_loc = loc; _ } ] ->
            source_map ~loc (self#patternArray ~wrap:("(", ")") l)
          | [ { ppat_desc = Ppat_tuple l; ppat_loc = loc; _ } ] ->
            source_map ~loc (self#patternTuple ~wrap:("(", ")") l)
          | [ ({ ppat_desc = Ppat_construct ({ txt = Lident "::"; _ }, _)
               ; ppat_loc
               ; _
               } as listPattern)
            ] ->
            source_map
              ~loc:ppat_loc
              (self#patternList ~wrap:("(", ")") listPattern)
          | _ -> assert false

        (* TODO: Similar to tuples, do not print parens around type constraints
           (same for lists) *)
        method patternArray ?(wrap = "", "") l =
          let left, right = wrap in
          let wrap = left ^ "[|", "|]" ^ right in
          makeList
            ~wrap
            ~break:IfNeed
            ~postSpace:true
            ~sep:commaTrail
            (List.map self#pattern l)

        method patternTuple ?(wrap = "", "") l =
          let left, right = wrap in
          let wrap = left ^ "(", ")" ^ right in
          makeList
            ~wrap
            ~sep:commaTrail
            ~postSpace:true
            ~break:IfNeed
            (List.map self#pattern l)

        method patternRecord ?(wrap = "", "") l closed =
          let longident_x_pattern (li, p) =
            match li, p.ppat_desc with
            | { txt = ident; _ }, Ppat_var { txt; _ }
              when Longident.last_exn ident = txt ->
              (* record field punning when destructuring. {x: x, y: y} becomes {x, y} *)
              (* works with module prefix too: {MyModule.x: x, y: y} becomes {MyModule.x, y} *)
              self#longident_loc li
            | ( { txt = ident; _ }
              , Ppat_alias
                  ( { ppat_desc = Ppat_var { txt = ident2; _ }; _ }
                  , { txt = aliasIdent; _ } ) )
              when Longident.last_exn ident = ident2 ->
              (* record field punning when destructuring with renaming. {state:
                 state as prevState} becomes {state as prevState *)
              (* works with module prefix too: {ReasonReact.state: state as
                 prevState} becomes {ReasonReact.state as prevState *)
              makeList
                ~sep:(Sep " ")
                [ self#longident_loc li; atom "as"; atom aliasIdent ]
            | _ ->
              let pattern =
                let formatted = self#pattern p in
                let wrap =
                  match p.ppat_desc with
                  | Ppat_constraint (_, _) -> Some ("(", ")")
                  | _ -> None
                in
                makeList ~inline:(true, true) ?wrap [ formatted ]
              in
              label
                ~space:true
                (makeList [ self#longident_loc li; atom ":" ])
                pattern
          in
          let rows =
            List.map longident_x_pattern l
            @ match closed with Closed -> [] | _ -> [ atom "_" ]
          in
          let left, right = wrap in
          let wrap = left ^ "{", "}" ^ right in
          makeList
            ~wrap
            ~break:IfNeed
            ~sep:commaTrail
            ~pad:(true, true)
            ~postSpace:true
            rows

        method patternFunction ?extension loc l =
          let estimatedFunLocation =
            { loc_start = loc.loc_start
            ; loc_end =
                { loc.loc_start with
                  pos_cnum = loc.loc_start.Lexing.pos_cnum + 3
                }
            ; loc_ghost = false
            }
          in
          makeList
            ~postSpace:true
            ~break:IfNeed
            ~inline:(true, true)
            ~pad:(false, false)
            (atom
               ~loc:estimatedFunLocation
               (add_extension_sugar funToken extension)
            :: self#case_list l)

        method parenthesized_expr ?break expr =
          let result = self#unparseExpr expr in
          match expr.pexp_attributes, expr.pexp_desc with
          | [], (Pexp_tuple _ | Pexp_construct ({ txt = Lident "()"; _ }, None))
            ->
            result
          | _ -> makeList ~wrap:("(", ")") ?break [ self#unparseExpr expr ]

        (* Expressions requiring parens, in most contexts such as separated by
           infix *)
        method expression_requiring_parens_in_infix x =
          let { Reason_attributes.stdAttrs; _ } =
            Reason_attributes.partitionAttributes x.pexp_attributes
          in
          assert (stdAttrs == []);
          (* keep the incoming expression around, an expr with * immediate
             extension sugar might contain less than perfect location * info in
             its children (used for comment interleaving), the expression passed
             to * 'expression_requiring_parens_in_infix' contains the correct
             location *)
          let originalExpr = x in
          let extension, x = expression_immediate_extension_sugar x in
          match x.pexp_desc with
          (* The only reason Pexp_fun must also be wrapped in parens when under
             pipe, is that its => token will be confused with the match token.
             Simple expression will also invoke `#reset`. *)
          | Pexp_function (_, _, Pfunction_cases _) when pipe || semi ->
            None (* Would be rendered as simplest_expression *)
          (* Pexp_function, on the other hand, doesn't need wrapping in parens
             in most cases anymore, since `fun` is not ambiguous anymore (we
             print Pexp_fun as ES6 functions). *)
          | Pexp_function (_, _, Pfunction_cases (cases, loc, _attrs)) ->
            let prec = Custom funToken in
            let expr = self#patternFunction ?extension loc cases in
            Some
              (SpecificInfixPrecedence
                 ( { reducePrecedence = prec; shiftPrecedence = prec }
                 , LayoutNode expr ))
          | _ ->
            (* The Pexp_function cases above don't use location because comment
               printing breaks for them. *)
            let itm =
              match x.pexp_desc with
              | Pexp_function (_ :: _, _, Pfunction_body _) | Pexp_newtype _ ->
                (* let uncurried = *)
                let args, ret = self#curriedPatternsAndReturnVal x in
                (match args with
                | [] -> raise (NotPossible "no arrow args in unparse ")
                | firstArg :: tl ->
                  (* Suboptimal printing of parens: * * something >>= fun x => x
                     \+ 1; * * Will be printed as: * * something >>= (fun x => x
                     \+ 1); * * Because the arrow has lower precedence than >>=,
                     but it wasn't * needed because * * (something >>= fun x) =>
                     x + 1; * * Is not a valid parse. Parens around the `=>`
                     weren't needed to * prevent reducing instead of shifting.
                     To optimize this part, we need * a much deeper encoding of
                     the parse rules to print parens only when * needed, testing
                     which rules will be reduced. It really should be *
                     integrated deeply with Menhir. * * One question is, if it's
                     this difficult to describe when parens are * needed, should
                     we even print them with the minimum amount? We can *
                     instead model everything as "infix" with ranked
                     precedences. *)
                  let retValUnparsed = self#unparseExprApplicationItems ret in
                  Some
                    (self#wrapCurriedFunctionBinding
                       ~sweet:(extension = None)
                       (add_extension_sugar funToken extension)
                       ~arrow:"=>"
                       firstArg
                       tl
                       retValUnparsed))
              | Pexp_try (e, l) ->
                let estimatedBracePoint =
                  { loc_start = e.pexp_loc.loc_end
                  ; loc_end = x.pexp_loc.loc_end
                  ; loc_ghost = false
                  }
                in
                let cases =
                  self#case_list ~allowUnguardedSequenceBodies:true l
                in
                let switchWith =
                  self#dont_preserve_braces#formatSingleArgLabelApplication
                    (atom (add_extension_sugar "try" extension))
                    e
                in
                Some
                  (label
                     ~space:true
                     switchWith
                     (source_map
                        ~loc:estimatedBracePoint
                        (makeList
                           ~indent:settings.trySwitchIndent
                           ~wrap:("{", "}")
                           ~break:Always_rec
                           ~postSpace:true
                           cases)))
              (* These should have already been handled and we should never
                 havgotten this far. *)
              | Pexp_setinstvar _ ->
                raise
                  (Invalid_argument
                     "Cannot handle setinstvar here - call unparseExpr")
              | Pexp_setfield (_, _, _) ->
                raise
                  (Invalid_argument
                     "Cannot handle setfield here - call unparseExpr")
              | Pexp_apply _ ->
                raise
                  (Invalid_argument
                     "Cannot handle apply here - call unparseExpr")
              | Pexp_match (e, l) ->
                let estimatedBracePoint =
                  { loc_start = e.pexp_loc.loc_end
                  ; (* See originalExpr binding, for more info. * It contains
                       the correct location under immediate extension sugar *)
                    loc_end = originalExpr.pexp_loc.loc_end
                  ; loc_ghost = false
                  }
                in
                let cases =
                  self#case_list ~allowUnguardedSequenceBodies:true l
                in
                let switchWith =
                  label
                    ~space:true
                    (atom (add_extension_sugar "switch" extension))
                    (self#parenthesized_expr ~break:IfNeed e)
                in
                let lbl =
                  label
                    ~space:true
                    switchWith
                    (source_map
                       ~loc:estimatedBracePoint
                       (makeList
                          ~indent:settings.trySwitchIndent
                          ~wrap:("{", "}")
                          ~break:Always_rec
                          ~postSpace:true
                          cases))
                in
                Some lbl
              | Pexp_ifthenelse (e1, e2, eo) ->
                let blocks, finalExpression = sequentialIfBlocks eo in
                let rec singleExpression exp =
                  match exp.pexp_desc with
                  | Pexp_ident _ -> true
                  | Pexp_constant _ -> true
                  | Pexp_construct (_, arg) ->
                    (match arg with
                    | None -> true
                    | Some x -> singleExpression x)
                  | _ -> false
                in
                let singleLineIf =
                  singleExpression e1
                  && singleExpression e2
                  &&
                  match eo with
                  | Some expr -> singleExpression expr
                  | None -> true
                in
                let makeLetSequence =
                  if singleLineIf
                  then makeLetSequenceSingleLine
                  else makeLetSequence
                in
                let rec sequence soFar remaining =
                  match remaining, finalExpression with
                  | [], None -> soFar
                  | [], Some e ->
                    let soFarWithElseAppended =
                      makeList ~postSpace:true [ soFar; atom "else" ]
                    in
                    label
                      ~space:true
                      soFarWithElseAppended
                      (source_map
                         ~loc:e.pexp_loc
                         (makeLetSequence (self#letList e)))
                  | hd :: tl, _ ->
                    let e1, e2 = hd in
                    let soFarWithElseIfAppended =
                      label
                        ~space:true
                        (makeList ~postSpace:true [ soFar; atom "else if" ])
                        (makeList ~wrap:("(", ")") [ self#unparseExpr e1 ])
                    in
                    let nextSoFar =
                      label
                        ~space:true
                        soFarWithElseIfAppended
                        (source_map
                           ~loc:e2.pexp_loc
                           (makeLetSequence (self#letList e2)))
                    in
                    sequence nextSoFar tl
                in
                let init =
                  let if_ = atom (add_extension_sugar "if" extension) in
                  let cond = self#parenthesized_expr e1 in
                  label
                    ~space:true
                    (source_map ~loc:e1.pexp_loc (label ~space:true if_ cond))
                    (source_map
                       ~loc:e2.pexp_loc
                       (makeLetSequence (self#letList e2)))
                in
                Some (sequence init blocks)
              | Pexp_while (e1, e2) ->
                let lbl =
                  let while_ = atom (add_extension_sugar "while" extension) in
                  let cond = self#parenthesized_expr e1 in
                  label
                    ~space:true
                    (label ~space:true while_ cond)
                    (source_map
                       ~loc:e2.pexp_loc
                       (makeLetSequence (self#letList e2)))
                in
                Some lbl
              | Pexp_for (s, e1, e2, df, e3) ->
                (*  for longIdentifier in
                 *      (longInit expr) to
                 *      (longEnd expr) {
                 *    print_int longIdentifier;
                 *  };
                 *)
                let identifierIn =
                  makeList ~postSpace:true [ self#pattern s; atom "in" ]
                in
                let dockedToFor =
                  makeList
                    ~break:IfNeed
                    ~postSpace:true
                    ~inline:(true, true)
                    ~wrap:("(", ")")
                    [ identifierIn
                    ; makeList
                        ~postSpace:true
                        [ self#unparseExpr e1; self#direction_flag df ]
                    ; self#unparseExpr e2
                    ]
                in
                let upToBody =
                  makeList
                    ~inline:(true, true)
                    ~postSpace:true
                    [ atom (add_extension_sugar "for" extension); dockedToFor ]
                in
                Some
                  (label
                     ~space:true
                     upToBody
                     (source_map
                        ~loc:e3.pexp_loc
                        (makeLetSequence (self#letList e3))))
              | Pexp_new li ->
                Some
                  (label
                     ~space:true
                     (atom "new")
                     (self#longident_class_or_type_loc li))
              | Pexp_assert e ->
                Some (label (atom "assert") (makeTup [ self#unparseExpr e ]))
              | Pexp_lazy e ->
                Some (self#formatSingleArgLabelApplication (atom "lazy") e)
              | Pexp_poly _ ->
                failwith
                  ("This version of the pretty printer assumes it is \
                    impossible to "
                  ^ "construct a Pexp_poly outside of a method definition - \
                     yet it sees one.")
              | _ -> None
            in
            (match itm with
            | None -> None
            | Some i ->
              Some (PotentiallyLowPrecedence (source_map ~loc:x.pexp_loc i)))

        method potentiallyConstrainedExpr x =
          match x.pexp_desc with
          | Pexp_constraint (e, ct) ->
            formatTypeConstraint (self#unparseExpr e) (self#core_type ct)
          | _ -> self#unparseExpr x

        (* Because the rule BANG simple_expr was given %prec below_DOT_AND_SHARP,
         * !x.y.z will parse as !(x.y.z) and not (!x).y.z.
         *
         *     !x.y.z == !((x.y).z)
         *     !x#y#z == !((x#y)#z)
         *
         * So the intuition is: In general, any simple expression can exist to the
         * left of a `.`, except `BANG simple_expr`, which has special precedence,
         * and must be guarded in this one case.
         *
         * TODO: Instead of special casing this here, we should continue to extend
         * unparseExpr to also unparse simple expressions, (by encoding the
         * rules precedence below_DOT_AND_SHARP).
         *
         * TODO:
         *  Some would even have the prefix application be parsed with lower
         *  precedence function *application*. In the case of !, where ! means not,
         *  it makes a lot of sense because (!identifier)(arg) would be meaningless.
         *
         *  !callTheFunction(1, 2, 3)(andEvenCurriedArgs)
         *
         * Only problem is that it could then not appear anywhere simple expressions
         * would appear.
         *
         * We could make a special case for ! followed by one simple expression, and
         * consider the result simple.
         *
         * Alternatively, we can figure out a way to not require simple expressions
         * in the most common locations such as if/while tests. This is really hard
         * (impossible w/ grammars Menhir supports?)
         *
         * if ! myFunc argOne argTwo {
         *
         * } else {
         *
         * };
         *
         *)
        method simple_enough_to_be_lhs_dot_send x =
          match x.pexp_desc with
          | Pexp_apply (eFun, _) ->
            (match printedStringAndFixityExpr eFun with
            | AlmostSimplePrefix _ | UnaryPlusPrefix _ | UnaryMinusPrefix _
            | UnaryNotPrefix _ | UnaryPostfix _ | Infix _ ->
              self#simplifyUnparseExpr x
            | Letop _ | Andop _ | Normal ->
              if x.pexp_attributes == []
              then
                (* `let a = foo().bar` instead of `let a = (foo()).bar *)
                (* same for foo()##bar, foo()#=bar, etc. *)
                self#unparseExpr x
              else self#simplifyUnparseExpr x)
          | _ -> self#simplifyUnparseExpr x

        method unparseRecord
          ?wrap:(lwrap, rwrap = "", "")
          ?(withStringKeys = false)
          ?(allowPunning = true)
          ?(forceBreak = false)
          l
          eo =
          (* forceBreak is a ref which can be set to always break the record
             rows. * Example, when we have a row which contains a nested record,
             * this ref can be set to true from inside the printing of that row,
             * which forces breaks for the outer record structure. *)
          let forceBreak = ref forceBreak in
          let quote = atom "\"" in
          let maybeQuoteFirstElem fst rest =
            if withStringKeys
            then
              match fst.txt with
              | Lident s -> quote :: atom s :: quote :: rest
              | Ldot _ | Lapply _ -> assert false
            else self#longident_loc fst :: rest
          in
          let makeRow (li, e) shouldPun =
            let totalRowLoc =
              { loc_start = li.Asttypes.loc.loc_start
              ; loc_end = e.pexp_loc.loc_end
              ; loc_ghost = false
              }
            in
            let stdAttrs =
              Reason_attributes.extractStdAttrs e.pexp_attributes
            in
            let theRow =
              match e.pexp_desc, shouldPun, allowPunning with
              (* record value punning. Turns {foo: foo, bar: 1} into {foo, bar: 1} *)
              (* also turns {Foo.bar: bar, baz: 1} into {Foo.bar, baz: 1} *)
              (* don't turn {bar: [@foo] bar, baz: 1} into {bar, baz: 1} *)
              (* don't turn {bar: Foo.bar, baz: 1} into {bar, baz: 1}, naturally *)
              | Pexp_ident { txt = Lident value; _ }, true, true
                when Longident.last_exn li.txt = value && stdAttrs = [] ->
                makeList (maybeQuoteFirstElem li [])
                (* Force breaks for nested records or mel.obj sugar
                 * Example:
                 *  let person = {name: {first: "Bob", last: "Zhmith"}, age: 32};
                 * is a lot less readable than
                 *  let person = {
                 *   "name": {
                 *     "first": "Bob",
                 *     "last": "Zhmith"
                 *   },
                 *  "age": 32
                 *  };
                 *)
              | Pexp_record (recordRows, optionalGadt), _, _ ->
                forceBreak := true;
                let keyWithColon =
                  makeList (maybeQuoteFirstElem li [ atom ":" ])
                in
                let value =
                  self#unparseRecord ~forceBreak:true recordRows optionalGadt
                in
                label ~space:true keyWithColon value
              | Pexp_extension (s, p), _, _ when s.txt = "mel.obj" ->
                forceBreak := true;
                let keyWithColon =
                  makeList (maybeQuoteFirstElem li [ atom ":" ])
                in
                let value =
                  self#formatMelObjExtensionSugar ~forceBreak:true p
                in
                label ~space:true keyWithColon value
              | Pexp_object classStructure, _, _ ->
                forceBreak := true;
                let keyWithColon =
                  makeList (maybeQuoteFirstElem li [ atom ":" ])
                in
                let value =
                  self#classStructure ~forceBreak:true classStructure
                in
                label ~space:true keyWithColon value
              | _ ->
                let argsList, return = self#curriedPatternsAndReturnVal e in
                (match argsList with
                | [] ->
                  let appTerms = self#unparseExprApplicationItems e in
                  let upToColon =
                    makeList (maybeQuoteFirstElem li [ atom ":" ])
                  in
                  formatAttachmentApplication
                    applicationFinalWrapping
                    (Some (true, upToColon))
                    appTerms
                | firstArg :: tl ->
                  let upToColon =
                    makeList (maybeQuoteFirstElem li [ atom ":" ])
                  in
                  let returnedAppTerms =
                    self#unparseExprApplicationItems return
                  in
                  self#wrapCurriedFunctionBinding
                    ~sweet:true
                    ~attachTo:upToColon
                    funToken
                    ~arrow:"=>"
                    firstArg
                    tl
                    returnedAppTerms)
            in
            source_map ~loc:totalRowLoc theRow, totalRowLoc
          in
          let rec getRows l =
            match l with
            | [] -> []
            | hd :: [] -> [ makeRow hd true ]
            | hd :: hd2 :: tl -> makeRow hd true :: getRows (hd2 :: tl)
          in

          let allRows =
            match eo with
            | None ->
              (match l with
              (* No punning (or comma) for records with only a single field.
                 It's ambiguous with an expression in a scope *)
              (* See comment in parser.mly for
                 lbl_expr_list_with_at_least_one_non_punned_field *)
              | [ hd ] -> [ makeRow hd false ]
              | _ -> getRows l)
            (* This case represents a "spread" being present -> {...x, a: 1, b:
               2} *)
            | Some withRecord ->
              let firstRow =
                let row =
                  (* Unclear why "sugar_expr" was special cased hre. *)
                  let appTerms = self#unparseExprApplicationItems withRecord in
                  formatAttachmentApplication
                    applicationFinalWrapping
                    (Some (false, atom "..."))
                    appTerms
                in
                source_map ~loc:withRecord.pexp_loc row, withRecord.pexp_loc
              in
              firstRow :: getRows l
          in
          let break =
            (* if a record has more than 1 row, always break *)
            match !forceBreak, allRows with
            | false, ([] | [ _ ]) -> Layout.IfNeed
            | _ -> Layout.Always_rec
          in
          makeList
            ~wrap:(lwrap ^ "{", "}" ^ rwrap)
            ~break
            ~sep:commaTrail
            ~pad:(true, true)
            ~postSpace:true
            (groupAndPrint ~xf:fst ~getLoc:snd ~comments:self#comments allRows)

        method isSeriesOfOpensFollowedByNonSequencyExpression expr =
          match expr.pexp_attributes, expr.pexp_desc with
          | [], Pexp_let _ -> false
          | [], Pexp_letop _ -> false
          | [], Pexp_sequence _ -> false
          | [], Pexp_letmodule _ -> false
          | ( []
            , Pexp_open
                ( { popen_override
                  ; popen_expr = { pmod_desc = Pmod_ident _; _ }
                  ; _
                  }
                , e ) ) ->
            popen_override == Fresh
            && self#isSeriesOfOpensFollowedByNonSequencyExpression e
          | [], Pexp_open _ -> false
          | [], Pexp_letexception _ -> false
          | [], Pexp_extension ({ txt; _ }, _) -> txt = "mel.obj"
          | _ -> true

        method unparseObject
          ?wrap:(lwrap, rwrap = "", "")
          ?(withStringKeys = false)
          l
          o =
          let core_field_type { pof_desc; pof_attributes; _ } =
            match pof_desc with
            | Otag ({ txt; _ }, ct) ->
              let l = Reason_attributes.extractStdAttrs pof_attributes in
              let row =
                let rowKey =
                  if withStringKeys
                  then makeList ~wrap:("\"", "\"") [ atom txt ]
                  else atom txt
                in
                label
                  ~space:true
                  (makeList ~break:Layout.Never [ rowKey; atom ":" ])
                  (self#core_type ct)
              in
              (match l with
              | [] -> row
              | _ :: _ ->
                makeList
                  ~postSpace:true
                  ~break:IfNeed
                  ~inline:(true, true)
                  (List.concat [ self#attributes pof_attributes; [ row ] ]))
            | Oinherit ct ->
              makeList ~break:Layout.Never [ atom "..."; self#core_type ct ]
          in
          let rows = List.map core_field_type l in
          let openness =
            match o with Closed -> atom "." | Open -> atom ".."
          in
          (* if an object has more than 2 rows, always break for readability *)
          let rows_layout =
            let break, pad_right =
              match rows with
              | [] -> Layout.IfNeed, false
              | [ _ ] -> Layout.IfNeed, true
              | _ -> Layout.Always_rec, true
            in
            makeList
              ~break
              ~inline:(true, true)
              ~postSpace:true
              ~pad:(false, pad_right)
              ~sep:commaTrail
              rows
          in
          makeList
            ~break:Layout.IfNeed
            ~preSpace:(rows != [])
            ~wrap:(lwrap ^ "{", "}" ^ rwrap)
            (openness :: [ rows_layout ])

        method unparseSequence ?(wrap = "", "") ~construct l =
          match construct with
          | `ES6List ->
            let seq, ext =
              match List.rev l with
              | ext :: seq_rev -> List.rev seq_rev, ext
              | [] -> assert false
            in
            makeES6List
              ~wrap
              (List.map self#unparseExpr seq)
              (self#unparseExpr ext)
          | _ ->
            let left, right = wrap in
            let xf, (leftDelim, rightDelim) =
              match construct with
              | `List -> self#unparseExpr, ("[", "]")
              | `Array -> self#unparseExpr, ("[|", "|]")
              | `Tuple -> self#potentiallyConstrainedExpr, ("(", ")")
              | `ES6List -> assert false
            in
            let wrap = left ^ leftDelim, rightDelim ^ right in
            makeList
              ~wrap
              ~sep:commaTrail
              ~break:IfNeed
              ~postSpace:true
              (List.map xf l)

        method formatMelObjExtensionSugar
          ?(wrap = "", "")
          ?(forceBreak = false)
          payload =
          match payload with
          | PStr [ itm ] ->
            (match itm with
            | { pstr_desc =
                  Pstr_eval ({ pexp_desc = Pexp_record (l, eo); _ }, [])
              ; _
              } ->
              self#unparseRecord
                ~forceBreak
                ~wrap
                ~withStringKeys:true
                ~allowPunning:false
                l
                eo
            | { pstr_desc =
                  Pstr_eval
                    ( { pexp_desc =
                          Pexp_extension ({ txt = "mel.obj"; _ }, payload)
                      ; _
                      }
                    , [] )
              ; _
              } ->
              (* some folks write `[%mel.obj [%mel.obj {foo: bar}]]`. This looks
                 improbable but it happens often if you use the sugared version:
                 `[%mel.obj {"foo": bar}]`. We're gonna be lenient here and
                 treat it as if they wanted to just write `{"foo": bar}`.
                 Melange does the same relaxation when parsing mel.obj *)
              self#formatMelObjExtensionSugar ~wrap ~forceBreak payload
            | _ ->
              raise
                (Invalid_argument
                   "mel.obj only accepts a record. You've passed something else"))
          | _ -> assert false

        method should_preserve_requested_braces expr =
          let { Reason_attributes.stylisticAttrs; _ } =
            Reason_attributes.partitionAttributes expr.pexp_attributes
          in
          match expr.pexp_desc with
          | Pexp_ifthenelse _ | Pexp_try _ -> false
          | Pexp_sequence _ ->
            (* `let ... in` should _always_ preserve braces *)
            true
          | _ ->
            preserve_braces
            && Reason_attributes.has_preserve_braces_attrs stylisticAttrs

        method simplest_expression x =
          let { Reason_attributes.stdAttrs
              ; jsxAttrs
              ; stylisticAttrs
              ; arityAttrs
              ; _
              }
            =
            Reason_attributes.partitionAttributes x.pexp_attributes
          in
          let hasJsxAttribute = jsxAttrs != [] in
          if stdAttrs != []
          then None
          else if self#should_preserve_requested_braces x
          then
            let layout =
              makeList
                ~break:(if inline_braces then Always else Always_rec)
                ~inline:(true, inline_braces)
                ~wrap:("{", "}")
                ~postSpace:true
                ~sep:(if inline_braces then Sep ";" else SepFinal (";", ";"))
                (self#letList x)
            in
            Some layout
          else
            let item =
              match x.pexp_desc with
              (* The only reason Pexp_fun must also be wrapped in parens is that
                 its => token will be confused with the match token. *)
              | Pexp_function (_ :: _, _, Pfunction_body _) when pipe || semi ->
                Some (self#reset#simplifyUnparseExpr x)
              | Pexp_function (_, _, Pfunction_cases (cases, loc, _attrs))
                when pipe || semi ->
                Some
                  (formatPrecedence
                     ~loc:x.pexp_loc
                     (self#reset#patternFunction loc cases))
              | Pexp_apply _ ->
                (match self#simple_get_application x with
                (* If it's the simple form of application. *)
                | Some simpleGet -> Some simpleGet
                | None -> None)
              | Pexp_object cs -> Some (self#classStructure cs)
              | Pexp_override l ->
                (* FIXME *)
                let string_x_expression (s, e) =
                  label ~space:true (atom (s.txt ^ ":")) (self#unparseExpr e)
                in
                Some
                  (makeList
                     ~postSpace:true
                     ~wrap:("{<", ">}")
                     ~sep:(Sep ",")
                     (List.map string_x_expression l))
              | Pexp_construct ({ txt = Lident "[]"; _ }, _)
                when hasJsxAttribute ->
                Some (atom "<> </>")
              | Pexp_construct ({ txt = Lident "::"; _ }, Some _)
                when hasJsxAttribute ->
                (match self#formatJsxChildrenNonSpread x [] with
                | None ->
                  (* Back out of the standard jsx child formatting *)
                  (* This is actually not a useful construct to have written:
                   *   <> ... x </>
                   * Is the same as:
                   *   x
                   * There is also a bug in the parser where a space is needed
                   * between <> and ..., but no one would write the ... form of
                   * <> anyways. *)
                  let withoutJsxAttributes =
                    { x with pexp_attributes = stylisticAttrs @ arityAttrs }
                  in
                  self#simplest_expression withoutJsxAttributes
                | Some chldn ->
                  Some
                    (makeList
                       ~break:IfNeed
                       ~inline:(false, false)
                       ~postSpace:true
                       ~wrap:("<>", "</>")
                       ~pad:(true, true)
                       chldn))
              | Pexp_construct _ when is_simple_construct (view_expr x) ->
                Some
                  (match view_expr x with
                  | `nil -> atom "[]"
                  | `tuple -> atom "()"
                  | `btrue -> atom "true"
                  | `bfalse -> atom "false"
                  | `list xs ->
                    (* LIST EXPRESSION *)
                    self#unparseSequence ~construct:`List xs
                  | `cons xs -> self#unparseSequence ~construct:`ES6List xs
                  | `simple x -> self#longident x
                  | _ -> assert false)
              | Pexp_ident li ->
                (* Lone identifiers shouldn't break when to the right of a
                   label *)
                Some (ensureSingleTokenSticksToLabel (self#longident_loc li))
              | Pexp_constant c ->
                (* Constants shouldn't break when to the right of a label *)
                let raw_literal, _ =
                  Reason_attributes.extract_raw_literal x.pexp_attributes
                in
                Some
                  (ensureSingleTokenSticksToLabel
                     (self#constant ?raw_literal c))
              | Pexp_pack me ->
                Some
                  (makeList
                     ~break:IfNeed
                     ~postSpace:true
                     ~wrap:("(", ")")
                     ~inline:(true, true)
                     [ atom "module"; self#module_expr me ])
              | Pexp_tuple l ->
                (* TODO: These may be simple, non-simple, or type constrained
                   non-simple expressions *)
                Some (self#unparseSequence ~construct:`Tuple l)
              | Pexp_constraint (e, ct) ->
                Some
                  (makeList
                     ~break:IfNeed
                     ~wrap:("(", ")")
                     [ formatTypeConstraint
                         (self#unparseExpr e)
                         (self#core_type ct)
                     ])
              | Pexp_coerce (e, cto1, ct) ->
                let optFormattedType =
                  match cto1 with
                  | None -> None
                  | Some typ -> Some (self#core_type typ)
                in
                Some
                  (makeList
                     ~break:IfNeed
                     ~wrap:("(", ")")
                     [ formatCoerce
                         (self#unparseExpr e)
                         optFormattedType
                         (self#core_type ct)
                     ])
              | Pexp_variant (l, None) ->
                Some
                  (ensureSingleTokenSticksToLabel
                     (atom ("`" ^ add_raw_identifier_prefix l)))
              | Pexp_record (l, eo) -> Some (self#unparseRecord l eo)
              | Pexp_array l -> Some (self#unparseSequence ~construct:`Array l)
              | Pexp_let _ | Pexp_sequence _ | Pexp_letmodule _
              | Pexp_letexception _ | Pexp_letop _ ->
                Some (makeLetSequence (self#letList x))
              | Pexp_extension e ->
                (match expression_immediate_extension_sugar x with
                | Some _, _ -> None
                | None, _ ->
                  (match expression_extension_sugar x with
                  | None -> Some (self#extension e)
                  | Some (ext, x') ->
                    (match x'.pexp_desc with
                    | Pexp_let _ | Pexp_letop _ | Pexp_letmodule _ ->
                      Some (makeLetSequence (self#letList x))
                    | Pexp_constant (Pconst_string (i, _, Some delim)) ->
                      let { Reason_attributes.stylisticAttrs; _ } =
                        Reason_attributes.partitionAttributes
                          ~allowUncurry:
                            (Reason_heuristics.bsExprCanBeUncurried x')
                          x'.pexp_attributes
                      in
                      if
                        Reason_attributes.has_quoted_extension_attrs
                          stylisticAttrs
                      then Some (quoted_ext ext i delim)
                      else Some (self#extension e)
                    | _ -> Some (self#extension e))))
              | Pexp_open (me, e) ->
                if self#isSeriesOfOpensFollowedByNonSequencyExpression x
                then
                  Some
                    (label
                       (label
                          (self#moduleExpressionToFormattedApplicationItems
                             me.popen_expr)
                          (atom "."))
                       (self#formatNonSequencyExpression ~parent:x e))
                else Some (makeLetSequence (self#letList x))
              | Pexp_send (e, s) ->
                let needparens =
                  match e.pexp_desc with
                  | Pexp_apply (ee, _) ->
                    (match printedStringAndFixityExpr ee with
                    | UnaryPostfix "^" -> true
                    | _ -> false)
                  | _ -> false
                in
                let lhs = self#simple_enough_to_be_lhs_dot_send e in
                let lhs =
                  if needparens then makeList ~wrap:("(", ")") [ lhs ] else lhs
                in
                Some (label (makeList [ lhs; atom "#" ]) (atom s.txt))
              | Pexp_unreachable -> Some (atom ".")
              | _ -> None
            in
            match item with
            | None -> None
            | Some i -> Some (source_map ~loc:x.pexp_loc i)

        (* Renders jsx children. Returns None if it is not a valid JSX child *
           structure and must be rendered as spread. You cannot render any list
           of * JSX children in Reason unless it is nil-terminated. Otherwise
           you must use * spread. *)
        method formatJsxChildrenNonSpread expr processedRev =
          let formatJsxChild x =
            match x with
            | { pexp_desc = Pexp_apply _; _ } as e ->
              (* Pipe first behaves differently according to the expression on the
               * right. In example (1) below, it's a `SpecificInfixPrecedence`; in
               * (2), however, it's `Simple` and doesn't need to be wrapped in parens.
               *
               * (1). <div> {items->Belt.Array.map(ReasonReact.string)->ReasonReact.array} </div>;
               * (2). <Foo> (title === "" ? [1, 2, 3] : blocks)->Foo.toString </Foo>; *)
              if
                Reason_heuristics.isPipeFirst e
                && not (Reason_heuristics.isPipeFirstWithNonSimpleJSXChild e)
              then self#formatPipeFirst e
              else
                self#inline_braces#simplifyUnparseExpr
                  ~inline:true
                  ~wrap:("{", "}")
                  e
            (* No braces - very simple *)
            | { pexp_desc = Pexp_ident li; _ } -> self#longident_loc li
            | { pexp_desc = Pexp_constant constant; _ } as x ->
              let raw_literal, _ =
                Reason_attributes.extract_raw_literal x.pexp_attributes
              in
              self#constant ?raw_literal constant
            | _ ->
              (* Currently spreading a list, or having a list as a child must be
               * wrapped in { }. You can remove the entire even_wrap_simple arg
               * when that is fixed (there is a conflict in grammar when allowing
               * a [] without {[]} as child. *)
              (* Simple child that has jsx: <hi> </hi> *)
              (* Simple child that doesn't have jsx: "hello" *)
              (* Simple child that doesn't have jsx but is a "::" and requires
                 braces: [a, b] *)
              self#inline_braces#simplifyUnparseExpr
                ~inline:true
                ~wrap:("{", "}")
                x
          in
          match expr with
          | { pexp_desc = Pexp_construct ({ txt = Lident "[]"; _ }, None); _ }
            ->
            (match processedRev with
            | [] -> None
            | _ :: _ -> Some (List.rev processedRev))
          | { pexp_desc =
                Pexp_construct
                  ( { txt = Lident "::"; _ }
                  , Some { pexp_desc = Pexp_tuple [ hd; tl ]; _ } )
            ; _
            } ->
            self#formatJsxChildrenNonSpread
              tl
              (formatJsxChild hd :: processedRev)
          | _ -> None

        method direction_flag =
          function Upto -> atom "to" | Downto -> atom "downto"

        method payload ppxToken ppxId e =
          let wrap = "[" ^ ppxToken ^ ppxId.txt, "]" in
          let wrap_prefix str (x, y) = x ^ str, y in
          let pad = true, false in
          let postSpace = true in
          match e with
          | PStr [] -> atom ("[" ^ ppxToken ^ ppxId.txt ^ "]")
          | PStr [ itm ] ->
            makeList ~break:Layout.IfNeed ~wrap ~pad [ self#structure_item itm ]
          | PStr (_ :: _ as items) ->
            let rows = List.map self#structure_item items in
            makeList
              ~wrap
              ~break:Layout.Always
              ~pad
              ~postSpace
              ~sep:(Layout.Sep ";")
              rows
          | PTyp x ->
            let wrap = wrap_prefix ":" wrap in
            makeList ~wrap ~break:Layout.IfNeed ~pad [ self#core_type x ]
          (* Signatures in attributes were added recently *)
          | PSig [] -> atom ("[" ^ ppxToken ^ ppxId.txt ^ ":]")
          | PSig [ x ] ->
            let wrap = wrap_prefix ":" wrap in
            makeList ~break:Layout.IfNeed ~wrap ~pad [ self#signature_item x ]
          | PSig items ->
            let wrap = wrap_prefix ":" wrap in
            let rows = List.map self#signature_item items in
            makeList
              ~wrap
              ~break:Layout.IfNeed
              ~pad
              ~postSpace
              ~sep:(Layout.Sep ";")
              rows
          | PPat (x, None) ->
            let wrap = wrap_prefix "?" wrap in
            makeList
              ~wrap
              ~break:Layout.IfNeed
              ~pad
              [ self#pattern_at_least_as_simple_as_alias_or_or x ]
          | PPat (x, Some e) ->
            let wrap = wrap_prefix "?" wrap in
            makeList
              ~wrap
              ~break:Layout.IfNeed
              ~pad
              ~postSpace
              [ self#pattern_at_least_as_simple_as_alias_or_or x
              ; label ~space:true (atom "when") (self#unparseExpr e)
              ]

        (* [% ...] *)
        method extension (s, p) =
          match s.txt with
          (* We special case "mel.obj" for now to allow for a nicer interop with
           * Melange. We might be able to generalize to any kind of
           * record looking thing with struct keys. *)
          | "mel.obj" -> self#formatMelObjExtensionSugar p
          | _ -> self#payload "%" s p

        method item_extension (s, e) = self#payload "%%" s e

        (* [@ ...] Simple attributes *)
        method attribute =
          function
          | { attr_name = { Location.txt = "ocaml.doc" | "ocaml.text"; _ }
            ; attr_payload =
                PStr
                  [ { pstr_desc =
                        Pstr_eval
                          ( { pexp_desc =
                                Pexp_constant (Pconst_string (text, _, None))
                            ; _
                            }
                          , _ )
                    ; pstr_loc
                    }
                  ]
            ; _
            } ->
            let break = if text = "" then Layout.IfNeed else Always_rec in
            let text = if text = "" then "/**/" else "/**" ^ text ^ "*/" in
            makeList
              ~inline:(true, true)
              ~postSpace:true
              ~preSpace:true
              ~indent:0
              ~break
              [ atom ~loc:pstr_loc text ]
          | { attr_name; attr_payload; _ } ->
            self#payload "@" attr_name attr_payload

        (* [@@ ... ] Attributes that occur after a major item in a
           structure/class *)
        method item_attribute = self#attribute

        (* [@@ ...] Attributes that occur not *after* an item in some
           structure/class/sig, but rather as their own standalone item. Note
           that syntactic distinction between item_attribute and
           floating_attribute is no longer necessary with Reason. Thank you
           semicolons. *)
        method floating_attribute = self#item_attribute
        method attributes l = List.map self#attribute l

        method attach_std_attrs l toThis =
          let l = Reason_attributes.extractStdAttrs l in
          match l with
          | [] -> toThis
          | _ :: _ ->
            makeList
              ~postSpace:true
              (List.concat [ self#attributes l; [ toThis ] ])

        method attach_std_item_attrs ?(allowUncurry = true) ?extension l toThis
            =
          let attrs = Reason_attributes.partitionAttributes ~allowUncurry l in
          match extension, attrs.stdAttrs with
          | None, [] -> toThis
          | Some id, _ ->
            makeList
              ~wrap:("[%" ^ id.txt, "]")
              ~indent:1
              ~pad:(true, false)
              ~break:Layout.IfNeed
              (List.map self#item_attribute l @ [ toThis ])
          | None, _ ->
            makeList
              ~postSpace:true
              ~indent:0
              ~break:Always
              ~inline:(true, true)
              (List.map self#item_attribute l @ [ toThis ])

        method exception_declaration ed =
          let pcd_name = ed.pext_name in
          let pcd_loc = ed.pext_loc in
          let pcd_attributes = [] in
          let exn_arg =
            match ed.pext_kind with
            | Pext_decl (vars, args, type_opt) ->
              let pcd_args, pcd_res = args, type_opt in
              [ self#type_variant_leaf_nobar
                  { pcd_name
                  ; pcd_args
                  ; pcd_res
                  ; pcd_loc
                  ; pcd_attributes
                  ; pcd_vars = vars
                  }
              ]
            | Pext_rebind id ->
              [ atom pcd_name.txt; atom "="; self#longident_loc id ]
          in
          let { Reason_attributes.stdAttrs; docAttrs; _ } =
            Reason_attributes.partitionAttributes
              ~partDoc:true
              ed.pext_attributes
          in
          let layout =
            self#attach_std_item_attrs
              stdAttrs
              (label
                 ~space:true
                 (atom "exception")
                 (makeList ~postSpace:true ~inline:(true, true) exn_arg))
          in
          self#attachDocAttrsToLayout
            ~stdAttrs
            ~docAttrs
            ~loc:ed.pext_loc
            ~layout
            ()

        (* Note: that override doesn't appear in class_sig_field, but does occur
           in class/object expressions. TODO: TODOATTRIBUTES *)
        method method_sig_flags_for s =
          function
          | Virtual -> [ atom "virtual"; atom s ]
          | Concrete -> [ atom s ]

        method value_type_flags_for s =
          function
          | Virtual, Mutable -> [ atom "virtual"; atom "mutable"; atom s ]
          | Virtual, Immutable -> [ atom "virtual"; atom s ]
          | Concrete, Mutable -> [ atom "mutable"; atom s ]
          | Concrete, Immutable -> [ atom s ]

        method class_sig_field x =
          match x.pctf_desc with
          | Pctf_inherit ct ->
            label ~space:true (atom "inherit") (self#class_constructor_type ct)
          | Pctf_val (s, mf, vf, ct) ->
            let valueFlags = self#value_type_flags_for (s.txt ^ ":") (vf, mf) in
            label
              ~space:true
              (label
                 ~space:true
                 (atom "val")
                 (makeList
                    ~postSpace:true
                    ~inline:(false, true)
                    ~break:IfNeed
                    valueFlags))
              (self#core_type ct)
          | Pctf_method (s, pf, vf, ct) ->
            let methodFlags = self#method_sig_flags_for (s.txt ^ ":") vf in
            let pubOrPrivate =
              match pf with Private -> "pri" | Public -> "pub"
            in
            let m =
              label
                ~space:true
                (label
                   ~space:true
                   (atom pubOrPrivate)
                   (makeList
                      ~postSpace:true
                      ~inline:(false, true)
                      ~break:IfNeed
                      methodFlags))
                (self#core_type ct)
            in
            self#attach_std_item_attrs x.pctf_attributes m
          | Pctf_constraint (ct1, ct2) ->
            label
              ~space:true
              (atom "constraint")
              (label
                 ~space:true
                 (makeList ~postSpace:true [ self#core_type ct1; atom "=" ])
                 (self#core_type ct2))
          | Pctf_attribute a -> self#floating_attribute a
          | Pctf_extension e -> self#item_extension e

        (* * /** doc comment */ (* formattedDocs *) * [@bs.val] [@bs.module
           "react-dom"] (* formattedAttrs *) * external render : reactElement =>
           element => unit = (* frstHalf *) * "render"; (* sndHalf *)

           * To improve the formatting with breaking & indentation: * * consider
           the part before the '=' as a label * * combine that label with '=' in
           a list * * consider the part after the '=' as a list * * combine both
           parts as a label * * format the doc comment with a ~postSpace:true
           (inline, not inline) list * * format the attributes with a
           ~postSpace:true (inline, inline) list * * format everything together
           in a ~postSpace:true (inline, inline) list * for nicer breaking *)
        method primitive_declaration ?extension vd =
          let external_label = add_extension_sugar "external" extension in
          let lblBefore =
            label
              ~space:true
              (makeList
                 [ makeList
                     ~postSpace:true
                     [ atom external_label; protectIdentifier vd.pval_name.txt ]
                 ; atom ":"
                 ])
              (self#core_type vd.pval_type)
          in
          let primDecl =
            match vd.pval_prim with
            | [ "" ] -> lblBefore
            | _ ->
              let frstHalf = makeList ~postSpace:true [ lblBefore; atom "=" ] in
              let sndHalf =
                makeSpacedBreakableInlineList
                  (List.map self#constant_string_for_primitive vd.pval_prim)
              in
              label ~space:true frstHalf sndHalf
          in
          match vd.pval_attributes with
          | [] -> primDecl
          | attrs ->
            let { Reason_attributes.stdAttrs; docAttrs; _ } =
              Reason_attributes.partitionAttributes ~partDoc:true attrs
            in
            let docs = List.map self#item_attribute docAttrs in
            let formattedDocs = makeList ~postSpace:true docs in
            let attrs = List.map self#item_attribute stdAttrs in
            let formattedAttrs = makeSpacedBreakableInlineList attrs in
            let layouts =
              match docAttrs, stdAttrs with
              | [], _ -> [ formattedAttrs; primDecl ]
              | _, [] -> [ formattedDocs; primDecl ]
              | _ -> [ formattedDocs; formattedAttrs; primDecl ]
            in
            makeSpacedBreakableInlineList layouts

        method classTypeSigsAndRest x =
          match x.pcty_desc with
          | Pcty_signature cs ->
            let { pcsig_self = ct; pcsig_fields = l } = cs in
            let instTypeFields = List.map self#class_sig_field l in
            let allItems =
              match ct.ptyp_desc with
              | Ptyp_any -> instTypeFields
              | _ ->
                label ~space:true (atom "as") (self#core_type ct)
                :: instTypeFields
            in
            allItems
          | _ -> [ self#class_instance_type x ]

        method class_instance_type x =
          match x.pcty_desc with
          | Pcty_signature _ | Pcty_open _ ->
            let opens, rest = self#classTypeOpens x in
            let cs = self#classTypeSigsAndRest rest in
            self#attach_std_item_attrs
              ~allowUncurry:false
              x.pcty_attributes
              (makeList
                 ~wrap:("{", "}")
                 ~postSpace:true
                 ~break:Layout.Always_rec
                 (List.map semiTerminated (List.concat [ opens; cs ])))
          | Pcty_constr (li, l) ->
            self#attach_std_attrs
              x.pcty_attributes
              (match l with
              | [] -> self#longident_loc li
              | _ :: _ ->
                label
                  (self#longident_loc li)
                  (makeList
                     ~wrap:("(", ")")
                     ~sep:commaTrail
                     (List.map self#core_type l)))
          | Pcty_extension e ->
            self#attach_std_item_attrs x.pcty_attributes (self#extension e)
          | Pcty_arrow _ ->
            failwith "class_instance_type should not be printed with Pcty_arrow"

        method classTypeOpens x =
          let rec gatherOpens acc opn =
            match opn.pcty_desc with
            | Pcty_open (md, ct) ->
              let li = md.popen_expr in
              gatherOpens
                (source_map
                   ~loc:li.loc
                   (label
                      ~space:true
                      (atom ("open" ^ override md.popen_override))
                      (self#longident_loc li))
                :: acc)
                ct
            | _ -> List.rev acc, opn
          in
          gatherOpens [] x

        method class_declaration_list l =
          let class_declaration
                ?(class_keyword = false)
                ({ pci_params = ls
                 ; pci_name = { txt; _ }
                 ; pci_virt
                 ; pci_loc
                 ; _
                 } as x)
            =
            let firstToken, pattern, patternAux =
              self#class_opening class_keyword txt pci_virt ls
            in
            let classBinding =
              self#wrappedClassBinding firstToken pattern patternAux x.pci_expr
            in
            source_map
              ~loc:pci_loc
              (self#attach_std_item_attrs x.pci_attributes classBinding)
          in
          match l with
          | [] ->
            raise (NotPossible "Class definitions will have at least one item.")
          | x :: rest ->
            makeNonIndentedBreakingList
              (class_declaration ~class_keyword:true x
              :: List.map class_declaration rest)

        (* For use with [class type a = class_instance_type]. Class type
           declarations/definitions declare the types of instances generated by
           class constructors. We have to call self#class_instance_type because
           self#class_constructor_type would add a "new" before the type. TODO:
           TODOATTRIBUTES: *)
        method class_type_declaration_list l =
          let class_type_declaration
                kwd
                ({ pci_params = ls; pci_name; pci_attributes; _ } as x)
            =
            let opener =
              match x.pci_virt with
              | Virtual -> kwd ^ " " ^ "virtual"
              | Concrete -> kwd
            in

            let upToName =
              let name = add_raw_identifier_prefix pci_name.txt in
              if ls == []
              then label ~space:true (atom opener) (atom name)
              else
                label
                  ~space:true
                  (label ~space:true (atom opener) (atom name))
                  (self#class_params_def ls)
            in
            let includingEqual =
              makeList ~postSpace:true [ upToName; atom "=" ]
            in
            let { Reason_attributes.stdAttrs; docAttrs; _ } =
              Reason_attributes.partitionAttributes ~partDoc:true pci_attributes
            in
            let layout =
              self#attach_std_item_attrs stdAttrs
              @@ label
                   ~space:true
                   includingEqual
                   (self#class_instance_type x.pci_expr)
            in
            self#attachDocAttrsToLayout
              ~stdAttrs
              ~docAttrs
              ~loc:pci_name.loc
              ~layout
              ()
          in
          match l with
          | [] ->
            failwith "Should not call class_type_declaration with no classes"
          | [ x ] -> class_type_declaration "class type" x
          | x :: xs ->
            makeList
              ~break:Always_rec
              ~indent:0
              ~inline:(true, true)
              (class_type_declaration "class type" x
              :: List.map (class_type_declaration "and") xs)

        (* Formerly the [class_type] Notice how class_constructor_type doesn't
           have any type attributes - class_instance_type does. TODO: Divide
           into class_constructor_types that allow arrows and ones that
           don't. *)
        method class_constructor_type x =
          match x.pcty_desc with
          | Pcty_arrow _ ->
            let rec allArrowSegments acc = function
              | { pcty_desc = Pcty_arrow (l, ct1, ct2); _ } ->
                allArrowSegments
                  (self#type_with_label (l, ct1, false) :: acc)
                  ct2
              (* This "new" is unfortunate. See reason_parser.mly for
                 details. *)
              | xx -> List.rev acc, self#class_constructor_type xx
            in
            let params, return = allArrowSegments [] x in
            let normalized =
              makeList
                ~break:IfNeed
                ~sep:(Sep "=>")
                ~preSpace:true
                ~postSpace:true
                ~inline:(true, true)
                [ makeCommaBreakableListSurround "(" ")" params; return ]
            in
            source_map ~loc:x.pcty_loc normalized
          | _ ->
            (* Unfortunately, we have to have final components of a
               class_constructor_type be prefixed with the `new` keyword.
               Hopefully this is temporary. *)
            self#class_instance_type x

        method non_arrowed_class_constructor_type x =
          match x.pcty_desc with
          | Pcty_arrow _ ->
            source_map
              ~loc:x.pcty_loc
              (formatPrecedence (self#class_constructor_type x))
          | _ -> self#class_instance_type x

        method class_field x =
          let itm =
            match x.pcf_desc with
            | Pcf_inherit (ovf, ce, so) ->
              let inheritText = "inherit" ^ override ovf in
              let inheritExp = self#class_expr ce in
              label
                ~space:true
                (atom inheritText)
                (match so with
                | None -> inheritExp
                | Some s -> label ~space:true inheritExp (atom ("as " ^ s.txt)))
            | Pcf_val (s, mf, Cfk_concrete (ovf, e)) ->
              let opening =
                match mf with
                | Mutable ->
                  let mutableName = [ atom "mutable"; atom s.txt ] in
                  label
                    ~space:true
                    (atom ("val" ^ override ovf))
                    (makeList
                       ~postSpace:true
                       ~inline:(false, true)
                       ~break:IfNeed
                       mutableName)
                | Immutable ->
                  label ~space:true (atom ("val" ^ override ovf)) (atom s.txt)
              in
              let valExprAndConstraint =
                match e.pexp_desc with
                | Pexp_constraint (ex, ct) ->
                  let openingWithTypeConstraint =
                    formatTypeConstraint opening (self#core_type ct)
                  in
                  label
                    ~space:true
                    (makeList
                       ~postSpace:true
                       [ openingWithTypeConstraint; atom "=" ])
                    (self#unparseExpr ex)
                | _ ->
                  label
                    ~space:true
                    (makeList ~postSpace:true [ opening; atom "=" ])
                    (self#unparseExpr e)
              in
              valExprAndConstraint
            | Pcf_val (s, mf, Cfk_virtual ct) ->
              let opening =
                match mf with
                | Mutable ->
                  let mutableVirtualName =
                    [ atom "mutable"; atom "virtual"; atom s.txt ]
                  in
                  let openingTokens =
                    makeList
                      ~postSpace:true
                      ~inline:(false, true)
                      ~break:IfNeed
                      mutableVirtualName
                  in
                  label ~space:true (atom "val") openingTokens
                | Immutable ->
                  let virtualName = [ atom "virtual"; atom s.txt ] in
                  let openingTokens =
                    makeList
                      ~postSpace:true
                      ~inline:(false, true)
                      ~break:IfNeed
                      virtualName
                  in
                  label ~space:true (atom "val") openingTokens
              in
              formatTypeConstraint opening (self#core_type ct)
            | Pcf_method (s, pf, Cfk_virtual ct) ->
              let opening =
                match pf with
                | Private ->
                  let privateVirtualName = [ atom "virtual"; atom s.txt ] in
                  let openingTokens =
                    makeList
                      ~postSpace:true
                      ~inline:(false, true)
                      ~break:IfNeed
                      privateVirtualName
                  in
                  label ~space:true (atom "pri") openingTokens
                | Public ->
                  let virtualName = [ atom "virtual"; atom s.txt ] in
                  let openingTokens =
                    makeList
                      ~postSpace:true
                      ~inline:(false, true)
                      ~break:IfNeed
                      virtualName
                  in
                  label ~space:true (atom "pub") openingTokens
              in
              formatTypeConstraint opening (self#core_type ct)
            | Pcf_method (s, pf, Cfk_concrete (ovf, e)) ->
              let methodText =
                let postFix = if ovf == Override then "!" else "" in
                match pf with
                | Private -> "pri" ^ postFix
                | Public -> "pub" ^ postFix
              in
              (* Should refactor the binding logic so faking out the AST isn't
                 needed, currently, it includes a ton of nuanced logic around
                 recovering explicitly polymorphic type definitions, and that
                 furthermore, that representation... Actually, let's do it.

                 For some reason, concrete methods are only ever parsed as
                 Pexp_poly. If there *is* no polymorphic function for the
                 method, then the return value of the function is wrapped in a
                 ghost Pexp_poly with [None] for the type vars.*)
              (match e.pexp_desc with
              | Pexp_poly
                  ( { pexp_desc =
                        Pexp_constraint
                          (methodFunWithNewtypes, nonVarifiedExprType)
                    ; _
                    }
                  , Some
                      { ptyp_desc = Ptyp_poly (typeVars, varifiedPolyType); _ }
                  )
                when let leadingAbstractVars, _ =
                       self#leadingCurriedAbstractTypes methodFunWithNewtypes
                     in
                     self#isRenderableAsPolymorphicAbstractTypes
                       typeVars
                       (* If even artificially varified. Don't know until this
                          returns*)
                       varifiedPolyType
                       leadingAbstractVars
                       nonVarifiedExprType ->
                let leadingAbstractVars, _ =
                  self#leadingCurriedAbstractTypes methodFunWithNewtypes
                in
                self#locallyAbstractPolymorphicFunctionBinding
                  methodText
                  (atom s.txt)
                  methodFunWithNewtypes
                  leadingAbstractVars
                  nonVarifiedExprType
              | Pexp_poly (e, Some ct) ->
                self#formatSimplePatternBinding
                  methodText
                  (atom s.txt)
                  (Some
                     ( source_map ~loc:ct.ptyp_loc (self#core_type ct)
                     , `Constraint ))
                  (self#unparseExprApplicationItems e)
              (* This form means that there is no type constraint - it's a
                 strange node name.*)
              | Pexp_poly (e, None) ->
                self#wrappedBinding methodText ~arrow:"=>" (atom s.txt) [] e
              | _ ->
                failwith "Concrete methods should only ever have Pexp_poly.")
            | Pcf_constraint (ct1, ct2) ->
              label
                ~space:true
                (atom "constraint")
                (makeList
                   ~postSpace:true
                   ~inline:(true, false)
                   [ makeList ~postSpace:true [ self#core_type ct1; atom "=" ]
                   ; self#core_type ct2
                   ])
            | Pcf_initializer e ->
              label
                ~space:true
                (atom "initializer")
                (self#simplifyUnparseExpr e)
            | Pcf_attribute a -> self#floating_attribute a
            | Pcf_extension e ->
              (* And don't forget, we still need to print post_item_attributes
                 even for this case *)
              self#item_extension e
          in
          let layout = self#attach_std_attrs x.pcf_attributes itm in
          source_map ~loc:x.pcf_loc layout

        method class_self_pattern_and_structure
          { pcstr_self = p; pcstr_fields = l } =
          let fields = List.map self#class_field l in
          (* Recall that by default self is bound to "this" at parse time. You'd
             have to go out of your way to bind it to "_". *)
          match p.ppat_attributes, p.ppat_desc with
          | [], Ppat_var { txt = "this"; _ } -> fields
          | _ ->
            let field = label ~space:true (atom "as") (self#pattern p) in
            source_map ~loc:p.ppat_loc field :: fields

        method simple_class_expr x =
          let { Reason_attributes.stdAttrs; _ } =
            Reason_attributes.partitionAttributes x.pcl_attributes
          in
          if stdAttrs != []
          then
            formatSimpleAttributed
              (self#simple_class_expr { x with pcl_attributes = [] })
              (self#attributes stdAttrs)
          else
            let itm =
              match x.pcl_desc with
              | Pcl_constraint (ce, ct) ->
                formatTypeConstraint
                  (self#class_expr ce)
                  (self#class_constructor_type ct)
              (* In OCaml, * - In the most recent version of OCaml, when in the
                 top level of a * module, let _ = ... is a PStr_eval. * - When
                 in a function, it is a Pexp_let PPat_any * - When in class
                 pre-member let bindings it is a Pcl_let PPat_any * * Reason
                 normalizes all of these to be simple imperative expressions *
                 with trailing semicolons, *except* in the case of classes
                 because it * will likely introduce a conflict with some
                 proposed syntaxes for * objects. *)
              | Pcl_let _ | Pcl_structure _ | Pcl_open _ ->
                let opens, rest = self#classExprOpens x in
                let rows = self#classExprLetsAndRest rest in
                makeList
                  ~wrap:("{", "}")
                  ~inline:(true, false)
                  ~postSpace:true
                  ~break:Always_rec
                  (List.map semiTerminated (List.concat [ opens; rows ]))
              | Pcl_extension e -> self#extension e
              | _ -> formatPrecedence (self#class_expr x)
            in
            source_map ~loc:x.pcl_loc itm

        method classExprLetsAndRest x =
          match x.pcl_desc with
          | Pcl_structure cs -> self#class_self_pattern_and_structure cs
          | Pcl_let (rf, l, ce) ->
            (* For "letList" bindings, the start/end isn't as simple as with
             * module value bindings. For "let lists", the sequences were formed
             * within braces {}. The parser relocates the first let binding to the
             * first brace. *)
            let binding =
              source_map
                ~loc:(self#bindingsLocationRange l)
                (self#bindings (rf, l))
            in
            binding :: self#classExprLetsAndRest ce
          | Pcl_open (_, ce) -> self#classExprLetsAndRest ce
          | _ -> [ self#class_expr x ]

        method classExprOpens x =
          let rec gatherOpens acc opn =
            match opn.pcl_desc with
            | Pcl_open (md, ce) ->
              let li = md.popen_expr in
              gatherOpens
                (source_map
                   ~loc:li.loc
                   (label
                      ~space:true
                      (atom ("open" ^ override md.popen_override))
                      (self#longident_loc li))
                :: acc)
                ce
            | _ -> List.rev acc, opn
          in
          gatherOpens [] x

        method class_expr x =
          let { Reason_attributes.stdAttrs; _ } =
            Reason_attributes.partitionAttributes x.pcl_attributes
          in
          (* We cannot handle the attributes here. Must handle them in each
             item *)
          if stdAttrs != []
          then
            (* Do not need a "simple" attributes precedence wrapper. *)
            formatAttributed
              (self#simple_class_expr { x with pcl_attributes = [] })
              (self#attributes stdAttrs)
          else
            match x.pcl_desc with
            | Pcl_fun _ ->
              (match self#curriedConstructorPatternsAndReturnVal x with
              | None, _ ->
                (* x just matched Pcl_fun, there is at least one parameter *)
                assert false
              | Some args, e ->
                label
                  ~space:true
                  (makeList
                     ~postSpace:true
                     [ label ~space:true (atom funToken) args; atom "=>" ])
                  (self#class_expr e))
            | Pcl_apply _ ->
              formatAttachmentApplication
                applicationFinalWrapping
                None
                (self#classExpressionToFormattedApplicationItems x, None)
            | Pcl_constr (li, []) ->
              label ~space:true (atom "class") (self#longident_loc li)
            | Pcl_constr (li, l) ->
              label
                (makeList
                   ~postSpace:true
                   [ atom "class"; self#longident_loc li ])
                (makeTup (List.map self#non_arrowed_non_simple_core_type l))
            | Pcl_open _ | Pcl_constraint _ | Pcl_extension _ | Pcl_let _
            | Pcl_structure _ ->
              self#simple_class_expr x

        method classStructure ?(forceBreak = false) ?(wrap = "", "") cs =
          let left, right = wrap in
          let fields_layout = self#class_self_pattern_and_structure cs in
          let pad = match fields_layout with [] -> false | _ :: _ -> true in
          makeList
            ~sep:(Layout.Sep ";")
            ~wrap:(left ^ "{", "}" ^ right)
            ~break:(if forceBreak then Layout.Always else Layout.IfNeed)
            ~postSpace:true
            ~pad:(pad, pad)
            ~inline:(true, false)
            fields_layout

        method signature signatureItems =
          match signatureItems with
          | [] -> atom ""
          | first :: _ as signatureItems ->
            let last =
              match List.rev signatureItems with
              | last :: _ -> last
              | [] -> assert false
            in
            let loc_start = first.psig_loc.loc_start in
            let loc_end = last.psig_loc.loc_end in
            let items =
              groupAndPrint
                ~xf:self#signature_item
                ~getLoc:(fun x -> x.psig_loc)
                ~comments:self#comments
                signatureItems
            in
            source_map
              ~loc:{ loc_start; loc_end; loc_ghost = false }
              (makeList
                 ~postSpace:true
                 ~break:Layout.Always_rec
                 ~indent:0
                 ~inline:(true, false)
                 ~sep:(SepFinal (";", ";"))
                 items)

        method signature_item item : Layout.t =
          match item.psig_desc with
          | Psig_extension ((extension, PSig [ item ]), _attrs) ->
            (match item.psig_desc with
            (* In case of a value or `external`, the extension gets inlined
               `let%private a = 1` *)
            | Psig_value ({ pval_prim = [ _ ]; _ } as vd) ->
              self#primitive_declaration ~extension vd
            | Psig_value vd -> self#val_binding ~extension vd
            | Psig_module pmd -> self#psig_module ~extension pmd
            | Psig_recmodule pmd -> self#psig_recmodule ~extension pmd
            | Psig_open od -> self#psig_open ~extension od
            | Psig_type (rf, l) -> self#type_def_list ~extension rf l
            | Psig_typext te -> self#type_extension ~extension te
            | _ -> self#payload "%%" extension (PSig [ item ]))
          | _ -> self#signature_item' item

        method val_binding ?extension vd =
          let intro = add_extension_sugar "let" extension in
          let { Reason_attributes.stdAttrs; docAttrs; _ } =
            Reason_attributes.partitionAttributes
              ~partDoc:true
              vd.pval_attributes
          in
          let layout =
            self#attach_std_item_attrs
              stdAttrs
              (formatTypeConstraint
                 (label
                    ~space:true
                    (atom intro)
                    (source_map
                       ~loc:vd.pval_name.loc
                       (protectIdentifier vd.pval_name.txt)))
                 (self#core_type vd.pval_type))
          in
          self#attachDocAttrsToLayout
            ~stdAttrs
            ~docAttrs
            ~loc:vd.pval_loc
            ~layout
            ()

        method psig_module ?extension pmd =
          let layout =
            let prefix = add_extension_sugar "module" extension in
            match pmd.pmd_type.pmty_desc with
            | Pmty_alias alias ->
              label
                ~space:true
                (makeList
                   ~postSpace:true
                   [ atom prefix; atom (moduleIdent pmd.pmd_name); atom "=" ])
                (self#longident_loc alias)
            | _ ->
              let letPattern =
                makeList
                  [ makeList
                      ~postSpace:true
                      [ atom prefix; atom (moduleIdent pmd.pmd_name) ]
                  ; atom ":"
                  ]
              in
              self#module_type letPattern pmd.pmd_type
          in
          let { Reason_attributes.stdAttrs; docAttrs; _ } =
            Reason_attributes.partitionAttributes
              ~partDoc:true
              pmd.pmd_attributes
          in
          self#attachDocAttrsToLayout
            ~stdAttrs
            ~docAttrs
            ~loc:pmd.pmd_name.loc
            ~layout:(self#attach_std_item_attrs stdAttrs @@ layout)
            ()

        method psig_recmodule ?extension decls =
          let items =
            List.mapi
              (fun i xx ->
                 let { Reason_attributes.stdAttrs; docAttrs; _ } =
                   Reason_attributes.partitionAttributes
                     ~partDoc:true
                     xx.pmd_attributes
                 in
                 let letPattern =
                   makeList
                     [ makeList
                         ~postSpace:true
                         [ atom
                             (if i == 0
                              then
                                add_extension_sugar "module" extension ^ " rec"
                              else "and")
                         ; atom (moduleIdent xx.pmd_name)
                         ]
                     ; atom ":"
                     ]
                 in
                 let layout =
                   self#attach_std_item_attrs
                     stdAttrs
                     (self#module_type ~space:true letPattern xx.pmd_type)
                 in
                 let layoutWithDocAttrs =
                   self#attachDocAttrsToLayout
                     ~stdAttrs
                     ~docAttrs
                     ~loc:xx.pmd_name.loc
                     ~layout
                     ()
                 in
                 extractLocModDecl xx, layoutWithDocAttrs)
              decls
          in
          makeNonIndentedBreakingList
            (groupAndPrint
               ~xf:(fun (_, layout) -> layout)
               ~getLoc:(fun (loc, _) -> loc)
               ~comments:self#comments
               items)

        method psig_open ?extension od =
          let { Reason_attributes.stdAttrs; docAttrs; _ } =
            Reason_attributes.partitionAttributes
              ~partDoc:true
              od.popen_attributes
          in
          let layout =
            let open_prefix =
              add_open_extension_sugar ~override:od.popen_override extension
            in
            self#attach_std_item_attrs stdAttrs
            @@ label
                 ~space:true
                 (atom open_prefix)
                 (self#longident_loc od.popen_expr)
          in
          self#attachDocAttrsToLayout
            ~stdAttrs
            ~docAttrs
            ~loc:od.popen_expr.loc
            ~layout
            ()

        method modtype x ~delim =
          let name = atom (add_raw_identifier_prefix x.pmtd_name.txt) in
          let main =
            match x.pmtd_type with
            | None -> makeList ~postSpace:true [ atom "module type"; name ]
            | Some mt ->
              let letPattern =
                makeList
                  ~postSpace:true
                  [ atom "module type"; name; atom delim ]
              in
              self#module_type letPattern mt
          in
          let { Reason_attributes.stdAttrs; docAttrs; _ } =
            Reason_attributes.partitionAttributes
              ~partDoc:true
              x.pmtd_attributes
          in
          let layout = self#attach_std_item_attrs stdAttrs main in
          self#attachDocAttrsToLayout
            ~stdAttrs
            ~docAttrs
            ~loc:x.pmtd_name.loc
            ~layout
            ()

        method signature_item' x : Layout.t =
          let item : Layout.t =
            match x.psig_desc with
            | Psig_type (rf, l) -> self#type_def_list rf l
            | Psig_value vd ->
              if vd.pval_prim != []
              then self#primitive_declaration vd
              else self#val_binding vd
            | Psig_typext te -> self#type_extension te
            | Psig_exception ed ->
              self#exception_declaration
                { ed.ptyexn_constructor with
                  pext_attributes =
                    ed.ptyexn_attributes @ ed.ptyexn_constructor.pext_attributes
                }
            | Psig_class l ->
              let class_description
                    ?(class_keyword = false)
                    ({ pci_params = ls; pci_name = { txt; _ }; pci_loc; _ } as x)
                =
                let firstToken, pattern, patternAux =
                  self#class_opening class_keyword txt x.pci_virt ls
                in
                let withColon =
                  self#wrapCurriedFunctionBinding
                    ~arrow:":"
                    ~spaceBeforeArrow:false
                    firstToken
                    pattern
                    patternAux
                    ([ self#class_constructor_type x.pci_expr ], None)
                in
                let { Reason_attributes.stdAttrs; docAttrs; _ } =
                  Reason_attributes.partitionAttributes
                    ~partDoc:true
                    x.pci_attributes
                in
                let layout = self#attach_std_item_attrs stdAttrs withColon in
                source_map
                  ~loc:pci_loc
                  (self#attachDocAttrsToLayout
                     ~stdAttrs
                     ~docAttrs
                     ~loc:x.pci_name.loc
                     ~layout
                     ())
              in
              makeNonIndentedBreakingList
                (match l with
                | [] -> raise (NotPossible "No recursive class bindings")
                | [ x ] -> [ class_description ~class_keyword:true x ]
                | x :: xs ->
                  class_description ~class_keyword:true x
                  :: List.map class_description xs)
            | Psig_module pmd -> self#psig_module pmd
            | Psig_open od -> self#psig_open od
            | Psig_include incl ->
              let { Reason_attributes.stdAttrs; docAttrs; _ } =
                Reason_attributes.partitionAttributes
                  ~partDoc:true
                  incl.pincl_attributes
              in
              let layout =
                self#attach_std_item_attrs stdAttrs
                @@ self#module_type (atom "include") incl.pincl_mod
              in
              self#attachDocAttrsToLayout
                ~stdAttrs
                ~docAttrs
                ~loc:incl.pincl_mod.pmty_loc
                ~layout
                ()
            | Psig_modtype x -> self#modtype x ~delim:"="
            | Psig_class_type l -> self#class_type_declaration_list l
            | Psig_recmodule decls -> self#psig_recmodule decls
            | Psig_attribute a -> self#floating_attribute a
            | Psig_extension ((({ loc; _ }, _) as ext), attrs) ->
              let { Reason_attributes.stdAttrs; docAttrs; _ } =
                Reason_attributes.partitionAttributes ~partDoc:true attrs
              in
              let layout =
                self#attach_std_item_attrs stdAttrs (self#item_extension ext)
              in
              self#attachDocAttrsToLayout ~stdAttrs ~docAttrs ~loc ~layout ()
            | Psig_modsubst { pms_name; pms_manifest; pms_attributes; pms_loc }
              ->
              let name = atom pms_name.txt in
              let main =
                makeList
                  ~postSpace:true
                  [ atom "module"
                  ; name
                  ; atom ":="
                  ; self#longident_loc pms_manifest
                  ]
              in
              let { Reason_attributes.stdAttrs; docAttrs; _ } =
                Reason_attributes.partitionAttributes
                  ~partDoc:true
                  pms_attributes
              in
              let layout = self#attach_std_item_attrs stdAttrs main in
              self#attachDocAttrsToLayout
                ~stdAttrs
                ~docAttrs
                ~loc:pms_loc
                ~layout
                ()
            | Psig_typesubst l -> self#type_def_list ~eq_symbol:":=" Recursive l
            | Psig_modtypesubst x -> self#modtype x ~delim:":="
          in
          source_map ~loc:x.psig_loc item

        method non_arrowed_module_type ?(space = true) letPattern x =
          match x.pmty_desc with
          | Pmty_alias li ->
            label
              ~space
              letPattern
              (formatPrecedence
                 (label ~space:true (atom "module") (self#longident_loc li)))
          | Pmty_typeof me ->
            let labelWithoutFinalWrap =
              label
                ~space:true
                (label
                   ~space:true
                   letPattern
                   (makeList
                      ~inline:(false, false)
                      ~wrap:("(", "")
                      ~postSpace:true
                      [ atom "module type of" ]))
                (self#module_expr me)
            in
            makeList ~wrap:("", ")") [ labelWithoutFinalWrap ]
          | _ -> self#simple_module_type ~space letPattern x

        method simple_module_type ?(space = true) letPattern x =
          match x.pmty_desc with
          | Pmty_ident li -> label ~space letPattern (self#longident_loc li)
          | Pmty_signature s ->
            let items =
              groupAndPrint
                ~xf:self#signature_item
                ~getLoc:(fun x -> x.psig_loc)
                ~comments:self#comments
                s
            in
            let shouldBreakLabel = match s with [] -> `Auto | _ -> `Always in
            label
              ~indent:0
              ~break:shouldBreakLabel
              (makeList
                 [ label
                     ~break:shouldBreakLabel
                     (makeList ~postSpace:true [ letPattern; atom "{" ])
                     (source_map
                        ~loc:x.pmty_loc
                        (makeList
                           ~break:(match s with [] -> IfNeed | _ -> Always)
                           ~inline:(true, true)
                           ~postSpace:true
                           ~sep:(SepFinal (";", ";"))
                           items))
                 ])
              (atom "}")
          | Pmty_extension (s, e) ->
            label ~space letPattern (self#payload "%" s e)
          | _ ->
            makeList
              ~break:IfNeed
              ~wrap:("", ")")
              [ self#module_type
                  ~space:false
                  (makeList ~pad:(false, true) ~wrap:("", "(") [ letPattern ])
                  x
              ]

        method module_type ?(space = true) letPattern x =
          let pmty =
            match x.pmty_desc with
            | Pmty_functor _ ->
              (* The segments that should be separated by arrows. *)
              let rec extract_args args xx =
                match xx.pmty_desc with
                | Pmty_functor (Unit, mt2) -> extract_args (`Unit :: args) mt2
                | Pmty_functor (Named ({ txt = s; _ }, mt1), mt2) ->
                  let arg =
                    match s with
                    | None -> self#module_type ~space:false (atom "") mt1
                    | Some s ->
                      self#module_type
                        ~space
                        (makeList [ atom s; atom ":" ])
                        mt1
                  in
                  extract_args (`Arg arg :: args) mt2
                | _ ->
                  let prepare_arg = function
                    | `Unit -> atom "()"
                    | `Arg x -> x
                  in
                  let args =
                    match args with
                    | [ `Unit ] -> []
                    | _ -> List.rev_map prepare_arg args
                  in
                  args, self#module_type (atom "") xx
              in
              let args, ret = extract_args [] x in
              label
                ~space
                letPattern
                (makeList
                   ~break:IfNeed
                   ~sep:(Sep "=>")
                   ~preSpace:true
                   ~inline:(true, true)
                   [ makeTup args; ret ])
            (* See comments in sugar_parser.mly about why WITH constraints
               aren't "non * arrowed" *)
            | Pmty_with (mt, l) ->
              let modSub atm li2 token =
                makeList
                  ~postSpace:true
                  [ atom "module"; atm; atom token; self#longident_loc li2 ]
              in
              let modtypeSub atm li modtype =
                label
                  (makeList
                     ~break:IfNeed
                     ~sep:(Sep " ")
                     [ atom "module type"; self#longident li; atm ])
                  (self#module_type (atom "") modtype)
              in
              let typeAtom = atom "type" in
              let eqAtom = atom "=" in
              let destrAtom = atom ":=" in
              let with_constraint = function
                | Pwith_type (li, td) ->
                  self#formatOneTypeDef
                    typeAtom
                    (makeList ~preSpace:true [ self#longident_loc li ])
                    eqAtom
                    td
                | Pwith_module (li, li2) ->
                  modSub (self#longident_loc li) li2 "="
                | Pwith_typesubst (_, td) ->
                  self#formatOneTypeDef
                    typeAtom
                    (atom ~loc:td.ptype_name.loc td.ptype_name.txt)
                    destrAtom
                    td
                | Pwith_modsubst (s, li2) ->
                  modSub (self#longident s.txt) li2 ":="
                | Pwith_modtype (s, modtype) -> modtypeSub eqAtom s.txt modtype
                | Pwith_modtypesubst (s, modtype) ->
                  modtypeSub destrAtom s.txt modtype
              in
              (match l with
              | [] -> self#module_type ~space letPattern mt
              | _ ->
                label
                  ~space
                  letPattern
                  (label
                     ~space:true
                     (makeList
                        ~preSpace:true
                        [ self#module_type ~space:false (atom "") mt
                        ; atom "with"
                        ])
                     (makeList
                        ~break:IfNeed
                        ~inline:(true, true)
                        ~sep:(Sep "and")
                        ~postSpace:true
                        ~preSpace:true
                        (List.map with_constraint l))))
            (* Seems like an infinite loop just waiting to happen. *)
            | _ -> self#non_arrowed_module_type ~space letPattern x
          in
          source_map ~loc:x.pmty_loc pmty

        method simple_module_expr ?(hug = false) x =
          match x.pmod_desc with
          | Pmod_unpack e ->
            let exprLayout =
              match e.pexp_desc with
              | Pexp_constraint (e, { ptyp_desc = Ptyp_package (lid, cstrs); _ })
                ->
                formatTypeConstraint
                  (makeList ~postSpace:true [ atom "val"; self#unparseExpr e ])
                  (self#typ_package ~mod_prefix:false lid cstrs)
              | _ -> makeList ~postSpace:true [ atom "val"; self#unparseExpr e ]
            in
            formatPrecedence exprLayout
          | Pmod_ident li ->
            ensureSingleTokenSticksToLabel (self#longident_loc li)
          | Pmod_constraint (unconstrainedRet, mt) ->
            let letPattern =
              makeList [ self#module_expr unconstrainedRet; atom ":" ]
            in
            formatPrecedence (self#module_type letPattern mt)
          | Pmod_structure s ->
            let wrap =
              if hug then if s = [] then "(", ")" else "({", "})" else "{", "}"
            in
            self#structure ~indent:None ~wrap s
          | _ ->
            (* For example, functor application will be wrapped. *)
            formatPrecedence ~wrap:("", "") (self#module_expr x)

        method module_expr x =
          match x.pmod_desc with
          | Pmod_functor _ ->
            let argsList, return =
              self#curriedFunctorPatternsAndReturnStruct x
            in
            (* See #19/20 in syntax.mls - cannot annotate return type at the
               moment. *)
            self#wrapCurriedFunctionBinding
              funToken
              ~sweet:true
              ~arrow:"=>"
              (makeTup argsList)
              []
              ([ self#moduleExpressionToFormattedApplicationItems return ], None)
          | Pmod_apply _ | Pmod_apply_unit _ ->
            self#moduleExpressionToFormattedApplicationItems x
          | Pmod_extension (s, e) -> self#payload "%" s e
          | Pmod_unpack _ | Pmod_ident _ | Pmod_constraint _ | Pmod_structure _
            ->
            self#simple_module_expr x

        method recmodule ?extension decls =
          let items =
            List.mapi
              (fun i xx ->
                 let { Reason_attributes.stdAttrs; docAttrs; _ } =
                   Reason_attributes.partitionAttributes
                     ~partDoc:true
                     xx.pmb_attributes
                 in
                 let layout =
                   self#attach_std_item_attrs stdAttrs
                   @@ self#let_module_binding
                        (if i == 0
                         then add_extension_sugar "module" extension ^ " rec"
                         else "and")
                        (atom (moduleIdent xx.pmb_name))
                        xx.pmb_expr
                 in
                 let layoutWithDocAttrs =
                   self#attachDocAttrsToLayout
                     ~stdAttrs
                     ~docAttrs
                     ~loc:xx.pmb_name.loc
                     ~layout
                     ()
                 in
                 extractLocModuleBinding xx, layoutWithDocAttrs)
              decls
          in
          makeNonIndentedBreakingList
            (groupAndPrint
               ~xf:(fun (_, layout) -> layout)
               ~getLoc:(fun (loc, _) -> loc)
               ~comments:self#comments
               items)

        method pstr_open ?extension od =
          let open_prefix =
            add_open_extension_sugar ~override:od.popen_override extension
          in
          self#attach_std_item_attrs od.popen_attributes
          @@ label
               ~space:true
               (atom open_prefix)
               (self#moduleExpressionToFormattedApplicationItems od.popen_expr)

        method structure ?(indent = Some 0) ?wrap structureItems =
          (* We don't have any way to know if an extension is placed at the top
             level by the parsetree while there's a difference syntactically (%
             for structure_items/expressons and %% for top_level). This small fn
             detects this particular case (structure > structure_item >
             extension > value) and prints with double % *)
          let structure_item item =
            match item.pstr_desc with
            | Pstr_extension ((extension, PStr [ item ]), attrs) ->
              (match item.pstr_desc with
              (* In case of a value or `external`, the extension gets inlined
                 `let%private a = 1` *)
              | Pstr_value (rf, vb_list) ->
                self#bindings ~extension (rf, vb_list)
              | Pstr_primitive vd -> self#primitive_declaration ~extension vd
              | Pstr_module binding ->
                let bindingName =
                  atom ~loc:binding.pmb_name.loc (moduleIdent binding.pmb_name)
                in
                let module_binding =
                  let prefix = add_extension_sugar "module" (Some extension) in
                  self#let_module_binding prefix bindingName binding.pmb_expr
                in
                self#attach_std_item_attrs binding.pmb_attributes module_binding
              | Pstr_recmodule decls -> self#recmodule ~extension decls
              | Pstr_open od -> self#pstr_open ~extension od
              | Pstr_type (rf, l) -> self#type_def_list ~extension rf l
              | Pstr_typext te -> self#type_extension ~extension te
              | Pstr_eval
                  ( ({ pexp_desc =
                         Pexp_constant (Pconst_string (i, _, Some delim))
                     ; pexp_attributes
                     ; _
                     } as expr)
                  , _ ) ->
                let { Reason_attributes.stylisticAttrs; _ } =
                  Reason_attributes.partitionAttributes
                    ~allowUncurry:(Reason_heuristics.bsExprCanBeUncurried expr)
                    pexp_attributes
                in
                if Reason_attributes.has_quoted_extension_attrs stylisticAttrs
                then quoted_ext ~pct:"%%" extension i delim
                else
                  self#attach_std_item_attrs
                    attrs
                    (self#payload "%%" extension (PStr [ item ]))
              | _ ->
                self#attach_std_item_attrs
                  attrs
                  (self#payload "%%" extension (PStr [ item ])))
            | _ -> self#structure_item item
          in
          match structureItems with
          | [] -> makeList ?wrap []
          | first :: _ as structureItems ->
            let last =
              match List.rev structureItems with
              | last :: _ -> last
              | [] -> assert false
            in
            let loc_start = first.pstr_loc.loc_start in
            let loc_end = last.pstr_loc.loc_end in
            let items =
              groupAndPrint
                ~xf:structure_item
                ~getLoc:(fun x -> x.pstr_loc)
                ~comments:self#comments
                structureItems
            in
            source_map
              ~loc:{ loc_start; loc_end; loc_ghost = false }
              (makeList
                 ~postSpace:true
                 ~break:Always_rec
                 ?wrap
                 ?indent
                 ~inline:(true, false)
                 ~sep:(SepFinal (";", ";"))
                 items)

        (* How do modules become parsed? * let module (X: sig) = blah; * Will
           not parse! (Should just make it parse to let [X:sig =]). * let module
           X: sig = blah; * Becomes Pmod_constraint * let module X: sig =
           (blah:sig); * Becomes Pmod_constraint .. Pmod_constraint * let module
           X = blah:typ; * Becomes Pmod_constraint * let module X (Y:y) (Z:z):r
           => Q * Becomes Pmod_functor...=> Pmod_constraint

           * let module X (Y:y) (Z:z):r => (Q:r2) * Probably becomes
           Pmod_functor...=> (Pmod_constraint.. * Pmod_constraint)

           * let (module X) = * Is a *completely* different thing
           (unpacking/packing first class modules). * We should make sure this
           is very well distinguished. * - Just replace all "let module" with a
           new three letter keyword (mod)? * - Reserve let (module X) for
           unpacking first class modules.

           * See the notes about how Ppat_constraint become parsed and attempt
           to unify * those as well. *)

        method let_module_binding prefixText bindingName moduleExpr =
          let { Reason_attributes.stdAttrs; _ } =
            Reason_attributes.partitionAttributes moduleExpr.pmod_attributes
          in
          let argsList, return =
            self#curriedFunctorPatternsAndReturnStruct moduleExpr
          in
          match argsList, return.pmod_desc with
          (* Simple module with type constraint, no functor args. *)
          | [], Pmod_constraint (unconstrainedRetTerm, ct) ->
            let letPattern =
              makeList
                [ makeList ~postSpace:true [ atom prefixText; bindingName ]
                ; atom ":"
                ]
            in
            let typeConstraint = self#module_type letPattern ct in
            let includingEqual =
              makeList ~postSpace:true [ typeConstraint; atom "=" ]
            in
            formatAttachmentApplication
              applicationFinalWrapping
              (Some (true, includingEqual))
              ( [ self#moduleExpressionToFormattedApplicationItems
                    unconstrainedRetTerm
                  |> self#attach_std_item_attrs stdAttrs
                ]
              , None )
          (* Simple module with type no constraint, no functor args. *)
          | [], _ ->
            self#formatSimplePatternBinding
              prefixText
              bindingName
              None
              ( [ self#moduleExpressionToFormattedApplicationItems return
                  |> self#attach_std_item_attrs stdAttrs
                ]
              , None )
          | _, _ ->
            (* A functor *)
            let argsWithConstraint, actualReturn =
              match return.pmod_desc with
              (* A functor with constrained return type: * * let module X = (A)
                 (B) : Ret => ... * *)
              | Pmod_constraint (me, ct) ->
                ( [ makeTup argsList
                  ; self#non_arrowed_module_type (atom ":") ct
                  ]
                , me )
              | _ -> [ makeTup argsList ], return
            in
            self#wrapCurriedFunctionBinding
              prefixText
              ~arrow:"=>"
              (makeList [ bindingName; atom " =" ])
              argsWithConstraint
              ( [ self#moduleExpressionToFormattedApplicationItems actualReturn
                  |> self#attach_std_item_attrs stdAttrs
                ]
              , None )

        method class_opening class_keyword name pci_virt ls =
          let name = add_raw_identifier_prefix name in
          let firstToken = if class_keyword then "class" else "and" in
          match pci_virt, ls with
          (* When no class params, it's a very simple formatting for the *
             opener - no breaking. *)
          | Virtual, [] -> firstToken, atom "virtual", [ atom name ]
          | Concrete, [] -> firstToken, atom name, []
          | Virtual, _ :: _ ->
            firstToken, atom "virtual", [ atom name; self#class_params_def ls ]
          | Concrete, _ :: _ ->
            firstToken, atom name, [ self#class_params_def ls ]

        (* TODO: TODOATTRIBUTES: Structure items don't have attributes, but each
           pstr_desc *)
        method structure_item term =
          let item =
            match term.pstr_desc with
            | Pstr_eval (e, attrs) ->
              let { Reason_attributes.stdAttrs; jsxAttrs; uncurried; _ } =
                Reason_attributes.partitionAttributes attrs
              in
              if uncurried then Hashtbl.add uncurriedTable e.pexp_loc true;
              let layout =
                self#attach_std_item_attrs
                  stdAttrs
                  (self#unparseUnattributedExpr e)
              in
              (* If there was a JSX attribute BUT JSX component wasn't detected,
                 that JSX attribute needs to be pretty printed so it doesn't get
                 lost *)
              (match jsxAttrs with
              | [] -> layout
              | _ :: _ ->
                let jsxAttrNodes = List.map self#attribute jsxAttrs in
                makeList ~sep:(Sep " ") (jsxAttrNodes @ [ layout ]))
            | Pstr_type (_, []) -> assert false
            | Pstr_type (rf, l) -> self#type_def_list rf l
            | Pstr_value (rf, l) -> self#bindings (rf, l)
            | Pstr_typext te -> self#type_extension te
            | Pstr_exception ed ->
              self#exception_declaration
                { ed.ptyexn_constructor with
                  pext_attributes =
                    ed.ptyexn_attributes @ ed.ptyexn_constructor.pext_attributes
                }
            | Pstr_module binding ->
              let bindingName =
                atom ~loc:binding.pmb_name.loc (moduleIdent binding.pmb_name)
              in
              let module_binding =
                self#let_module_binding "module" bindingName binding.pmb_expr
              in
              self#attach_std_item_attrs binding.pmb_attributes module_binding
            | Pstr_open od -> self#pstr_open od
            | Pstr_modtype x ->
              let name = atom (add_raw_identifier_prefix x.pmtd_name.txt) in
              let main =
                match x.pmtd_type with
                | None -> makeList ~postSpace:true [ atom "module type"; name ]
                | Some mt ->
                  let letPattern =
                    makeList
                      ~postSpace:true
                      [ atom "module type"; name; atom "=" ]
                  in
                  self#module_type letPattern mt
              in
              self#attach_std_item_attrs x.pmtd_attributes main
            | Pstr_class l -> self#class_declaration_list l
            | Pstr_class_type l -> self#class_type_declaration_list l
            | Pstr_primitive vd -> self#primitive_declaration vd
            | Pstr_include incl ->
              self#attach_std_item_attrs incl.pincl_attributes
              @@
              (* Kind of a hack *)
              let moduleExpr = incl.pincl_mod in
              self#moduleExpressionToFormattedApplicationItems
                ~prefix:"include"
                moduleExpr
            | Pstr_recmodule decls -> self#recmodule decls
            | Pstr_attribute a -> self#floating_attribute a
            | Pstr_extension (((_extension, PStr []) as extension), attrs) ->
              (* Extension with attributes and without PStr gets printed
                 inline *)
              self#attach_std_attrs attrs (self#item_extension extension)
            | Pstr_extension ((extension, PStr [ item ]), attrs) ->
              (match item.pstr_desc with
              (* In case of a value, the extension gets inlined `let%lwt a =
                 1` *)
              | Pstr_value (rf, l) -> self#bindings ~extension (rf, l)
              | _ ->
                let { Reason_attributes.stdAttrs; docAttrs; _ } =
                  Reason_attributes.partitionAttributes ~partDoc:true attrs
                in
                let item = self#structure_item item in
                let layout =
                  self#attach_std_item_attrs ~extension stdAttrs item
                in
                makeList (List.map self#attribute docAttrs @ [ layout ]))
            | Pstr_extension (e, a) ->
              (* Notice how extensions have attributes - but not every structure
                 item does. *)
              self#attach_std_item_attrs a (self#item_extension e)
          in
          source_map ~loc:term.pstr_loc item

        method type_extension ?extension te =
          let formatOneTypeExtStandard prepend ({ ptyext_path; _ } as te) =
            let name = self#longident_loc ptyext_path in
            let item = self#formatOneTypeExt prepend name (atom "+=") te in
            let { Reason_attributes.stdAttrs; docAttrs; _ } =
              Reason_attributes.partitionAttributes
                ~partDoc:true
                te.ptyext_attributes
            in
            let layout = self#attach_std_item_attrs stdAttrs item in
            self#attachDocAttrsToLayout
              ~stdAttrs
              ~docAttrs
              ~loc:ptyext_path.loc
              ~layout
              ()
          in
          let label = add_extension_sugar "type" extension in
          formatOneTypeExtStandard (atom label) te

        (* [allowUnguardedSequenceBodies] allows sequence expressions {} to the
           right of `=>` to not be guarded in `{}` braces. *)
        method case_list ?(allowUnguardedSequenceBodies = false) l =
          let rec appendLabelToLast items rhs =
            match items with
            | hd :: [] -> label ~indent:0 ~space:true hd rhs :: []
            | hd :: tl -> hd :: appendLabelToLast tl rhs
            | [] -> raise (NotPossible "Cannot append to last of nothing")
          in

          let case_row { pc_lhs; pc_guard; pc_rhs } =
            let theOrs = orList pc_lhs in

            (* match x with *)
            (* | AnotherReallyLongVariantName (_, _, _)   *)
            (* | AnotherReallyLongVariantName2 (_, _, _) when true => { *)

            (* } *)

            (*<sbi><X>match x with</X>   *)
            (*     <Y>everythingElse</Y> *)
            (*</sbi>                     *)

            (*     ............................................................
             * :    each or segment has a spaced list <> that ties its    :
             * : bar "|" to its pattern                                   :
             * ...:..........................................................:.....
             * :  :  each or-patterned match is grouped in SpacedBreakableInline  :
             * :  :                                                          :    :
             * v  v                                                          v    v
             * <sbi><>|<lb><A><>     FirstThingStandalone t =></A></><B>t</B></lb></></sbi>
             * <sbi><>|<C>           AnotherReallyLongVariantName (_, _, _)</C></>
             * ^    <>|<lb><><lb><D>AnotherReallyLongVariantNam2 (_, _, _)</D>             (label the last in or ptn for or and label it again for arrow)
             * :        ^  ^   ^     <E>when true<E></lb> =></><F>{
             * :        :  :   :    </F>}</lb></sbi> ^       ^
             * :        :  :   :            ^     ^   :      :
             * :        :  :   :            :     :   :      :
             * :        :  :   :If there is :a WHERE  :      :
             * :        :  :   :an extra    :label is :      :
             * :        :  :   :inserted bef:ore the  :      :
             * :        :  :   :arrow.      :     :   :      :
             * :        :  :   :............:.....:...:      :
             * :        :  :                :     :          :
             * :        :  :                :     :          :
             * :        :  :                :     :          :
             * :        :  :The left side of:this final label:
             * :        :  :uses a list to  :append the arrow:
             * :        :  :................:.....:..........:
             * :        :                   :     :
             * :        :                   :     :
             * :        :                   :     :
             * :        :Final or segment is:     :
             * :        :wrapped in lbl that:     :
             * :        :partitions pattern :     :
             * :        :and arrow from     :     :
             * :        :expression.        :     :
             * :        :                   :     :
             * :        :...................:     :
             * :     [orsWithWhereAndArrowOnLast] :
             * :                                  :
             * :..................................:
             *             [row]
             *)
            let bar xx = makeList ~postSpace:true [ atom "|"; xx ] in
            let appendWhereAndArrow p =
              match pc_guard with
              | None -> makeList ~postSpace:true [ p; atom "=>" ]
              | Some g ->
                (* when x should break as a whole - extra list added around it
                   to make it break as one *)
                let withWhen =
                  label
                    ~space:true
                    p
                    (makeList
                       ~break:Layout.Never
                       ~inline:(true, true)
                       ~postSpace:true
                       [ label ~space:true (atom "when") (self#unparseExpr g) ])
                in
                makeList
                  ~inline:(true, true)
                  ~postSpace:true
                  [ withWhen; atom "=>" ]
            in
            let rec appendWhereAndArrowToLastOr = function
              | [] -> []
              | hd :: tl ->
                let formattedHd = self#pattern hd in
                let formattedHd =
                  match hd.ppat_desc with
                  | Ppat_constraint _ -> formatPrecedence formattedHd
                  | _ -> formattedHd
                in
                let formattedHd =
                  if tl == []
                  then appendWhereAndArrow formattedHd
                  else formattedHd
                in
                formattedHd :: appendWhereAndArrowToLastOr tl
            in
            let orsWithWhereAndArrowOnLast =
              appendWhereAndArrowToLastOr theOrs
            in
            let rhs =
              if allowUnguardedSequenceBodies
              then
                match self#under_pipe#letList pc_rhs with
                (* TODO: Still render a list with located information here so
                   that comments (eol) are interleaved *)
                | [ hd ] -> hd
                (* In this case, we don't need any additional indentation,
                   because there aren't wrapping {} which would cause zero
                   indentation to look strange. *)
                | lst -> makeUnguardedLetSequence lst
              else self#under_pipe#unparseExpr pc_rhs
            in
            source_map
            (* Fake shift the location to accommodate for the bar, to make sure
             * the wrong comments don't make their way past the next bar. *)
              ~loc:
                (expandLocation
                   ~expand:(0, 0)
                   { loc_start = pc_lhs.ppat_loc.loc_start
                   ; loc_end = pc_rhs.pexp_loc.loc_end
                   ; loc_ghost = false
                   })
              (makeList
                 ~break:Always_rec
                 ~inline:(true, true)
                 (List.map
                    bar
                    (appendLabelToLast orsWithWhereAndArrowOnLast rhs)))
          in
          groupAndPrint
            ~xf:case_row
            ~getLoc:(fun { pc_lhs; pc_rhs; _ } ->
              { pc_lhs.ppat_loc with loc_end = pc_rhs.pexp_loc.loc_end })
            ~comments:self#comments
            l

        (* Formats a list of a single expr param in such a way that the parens of the function or
         * (poly)-variant application and the wrapping of the param stick together when the layout breaks.
         *  Example: `foo({a: 1, b: 2})` needs to be formatted as
         *  foo({
         *    a: 1,
         *    b: 2
         *  })
         *  when the line length dictates breaking. Notice how `({` and `})` 'hug'.
         *  Also see "isSingleArgParenApplication" which determines if
         *  this kind of formatting should happen. *)
        method singleArgParenApplication
          ?(wrap = "", "")
          ?(uncurried = false)
          es =
          let lwrap, rwrap = wrap in
          let lparen = lwrap ^ if uncurried then "(. " else "(" in
          let rparen = ")" ^ rwrap in
          match es with
          | [ { pexp_attributes = []; pexp_desc = Pexp_record (l, eo); _ } ] ->
            self#unparseRecord ~wrap:(lparen, rparen) l eo
          | [ { pexp_attributes = []; pexp_desc = Pexp_tuple l; _ } ] ->
            self#unparseSequence ~wrap:(lparen, rparen) ~construct:`Tuple l
          | [ { pexp_attributes = []; pexp_desc = Pexp_array l; _ } ] ->
            self#unparseSequence ~wrap:(lparen, rparen) ~construct:`Array l
          | [ { pexp_attributes = []; pexp_desc = Pexp_object cs; _ } ] ->
            self#classStructure ~wrap:(lparen, rparen) cs
          | [ { pexp_attributes = []; pexp_desc = Pexp_extension (s, p); _ } ]
            when s.txt = "mel.obj" ->
            self#formatMelObjExtensionSugar ~wrap:(lparen, rparen) p
          | [ ({ pexp_attributes = []; _ } as exp) ]
            when is_simple_list_expr exp ->
            (match view_expr exp with
            | `list xs ->
              self#unparseSequence ~construct:`List ~wrap:(lparen, rparen) xs
            | `cons xs ->
              self#unparseSequence ~construct:`ES6List ~wrap:(lparen, rparen) xs
            | _ -> assert false)
          | _ -> assert false

        method formatSingleArgLabelApplication labelTerm rightExpr =
          let layout_right =
            match rightExpr with
            | { pexp_desc = Pexp_let _; _ } ->
              makeLetSequence ~wrap:("({", "})") (self#letList rightExpr)
            | e when isSingleArgParenApplication [ rightExpr ] ->
              self#singleArgParenApplication [ e ]
            | { pexp_desc = Pexp_construct ({ txt = Lident "()"; _ }, _); _ } ->
              (* special case unit such that we don't end up with double
                 parens *)
              self#simplifyUnparseExpr rightExpr
            | _ -> formatPrecedence (self#unparseExpr rightExpr)
          in
          label labelTerm layout_right

        method label_x_expression_param (l, e) =
          let term = self#unparseProtectedExpr e in
          let param =
            match l, e with
            | Nolabel, _ -> term
            | Labelled lbl, _
              when Reason_heuristics.is_punned_labelled_expression e lbl ->
              makeList [ atom namedArgSym; term ]
            | Optional lbl, _
              when Reason_heuristics.is_punned_labelled_expression e lbl ->
              makeList [ atom namedArgSym; label term (atom "?") ]
            | Labelled lbl, _ -> label (atom (namedArgSym ^ lbl ^ "=")) term
            | Optional lbl, _ -> label (atom (namedArgSym ^ lbl ^ "=?")) term
          in
          source_map ~loc:e.pexp_loc param

        method label_x_expression_params ?wrap ?(uncurried = false) xs =
          match xs with
          (* function applications with unit as only argument should be printed
             differently * e.g. print_newline(()) should be printed as
             print_newline() *)
          | [ ( Nolabel
              , { pexp_attributes = []
                ; pexp_desc = Pexp_construct ({ txt = Lident "()"; _ }, None)
                ; _
                } )
            ] ->
            makeList
              ~break:Never
              ?wrap
              [ (if uncurried then atom "(.)" else atom "()") ]
          (* The following cases provide special formatting when there's only one expr_param that is a tuple/array/list/record etc.
           *  e.g. foo({a: 1, b: 2})
           *  becomes ->
           *  foo({
           *    a: 1,
           *    b: 2,
           *  })
           *  when the line-length indicates breaking.
           *)
          | [ (Nolabel, exp) ] when isSingleArgParenApplication [ exp ] ->
            self#singleArgParenApplication ?wrap ~uncurried [ exp ]
          | params ->
            makeTup
              ?wrap
              ~uncurried
              (List.map self#label_x_expression_param params)

        (* Prefix represents an optional layout. When passed it will be "prefixed" to
         * the funExpr. Example, given `bar(x, y)` with prefix `foo`, we get
         * foobar(x,y). When the arguments break, the closing `)` is nicely aligned
         * on the height of the prefix:
         *  foobar(
         *    x,
         *    y,
         *  )  --> notice how `)` sits on the height of `foo` instead of `bar`
         *
         *  ~wrap -> represents optional "wrapping", might be useful in context of jsx
         *  where braces are required:
         * prop={bar(   -> `{` is formatted before the funExpr
         *   x,
         *   y,
         * )}      -> notice how the closing brace hugs: `)}`
         *)
        method formatFunAppl
          ?(prefix = atom "")
          ?(wrap = "", "")
          ~jsxAttrs
          ~args
          ~funExpr
          ~applicationExpr
          ?(uncurried = false)
          () =
          let leftWrap, rightWrap = wrap in
          let uncurriedApplication = uncurried in
          (* If there was a JSX attribute BUT JSX component wasn't detected,
             that JSX attribute needs to be pretty printed so it doesn't get
             lost *)
          let maybeJSXAttr = List.map self#attribute jsxAttrs in
          let categorizeFunApplArgs args =
            let reverseArgs = List.rev args in
            match reverseArgs with
            | ((_, { pexp_desc = Pexp_function (_ :: _, _, _); _ }) as callback)
              :: args
              when []
                   == List.filter
                        (fun (_, e) ->
                           match e.pexp_desc with
                           | Pexp_function (_ :: _, _, _) -> true
                           | _ -> false)
                        args
                   (* default to normal formatting if there's more than one
                      callback *) ->
              `LastArgIsCallback (callback, List.rev args)
            | _ -> `NormalFunAppl args
          in
          let formattedFunExpr =
            match funExpr.pexp_desc with
            (* pipe first chain or sharpop chain as funExpr, no parens needed,
               we know how to parse *)
            | Pexp_apply ({ pexp_desc = Pexp_ident { txt = Lident s; _ }; _ }, _)
              when requireNoSpaceFor s ->
              self#unparseExpr funExpr
            | Pexp_field _ -> self#unparseExpr funExpr
            | _ -> self#simplifyUnparseExpr funExpr
          in
          let formattedFunExpr =
            makeList [ prefix; atom leftWrap; formattedFunExpr ]
          in
          match categorizeFunApplArgs args with
          | `LastArgIsCallback (callbackArg, args) ->
            (* This is the following case: * Thing.map(foo, bar, baz, (abc, z)
               => * MyModuleBlah.toList(argument) *)
            let argLbl, cb = callbackArg in
            let { Reason_attributes.stdAttrs; uncurried; _ } =
              Reason_attributes.partitionAttributes cb.pexp_attributes
            in
            let cbAttrs = stdAttrs in
            if uncurried then Hashtbl.add uncurriedTable cb.pexp_loc true;
            let cbArgs, retCb =
              self#curriedPatternsAndReturnVal { cb with pexp_attributes = [] }
            in
            let cbArgs =
              if cbAttrs != []
              then
                makeList
                  ~break:IfNeed
                  ~inline:(true, true)
                  ~postSpace:true
                  (List.map self#attribute cbAttrs @ cbArgs)
              else makeList cbArgs
            in
            let retCb, cbArgs =
              match retCb.pexp_desc with
              | Pexp_constraint (a, t) ->
                a, makeList [ cbArgs; atom ": "; self#core_type t ]
              | _ -> retCb, cbArgs
            in
            let theCallbackArg =
              match argLbl with
              | Optional s ->
                makeList ([ atom namedArgSym; atom s; atom "=?" ] @ [ cbArgs ])
              | Labelled s ->
                makeList ([ atom namedArgSym; atom s; atom "=" ] @ [ cbArgs ])
              | Nolabel -> cbArgs
            in
            let theFunc =
              source_map
                ~loc:funExpr.pexp_loc
                (makeList
                   ~wrap:("", if uncurriedApplication then "(." else "(")
                   [ formattedFunExpr ])
            in
            let formattedFunAppl =
              match self#letList retCb with
              | [ x ] ->
                (* force breaks for test assertion style callbacks, e.g. *
                   describe("App", () => test("math", () => Expect.expect(1 + 2)
                   |> toBe(3))); * should always break for readability of the
                   tests: * describe("App", () => * test("math", () => *
                   Expect.expect(1 + 2) |> toBe(3) * ) * ); *)
                let forceBreak =
                  match funExpr.pexp_desc with
                  | Pexp_ident ident
                    when let lastIdent = Longident.last_exn ident.txt in
                         List.mem
                           lastIdent
                           [ "test"; "describe"; "it"; "expect" ] ->
                    true
                  | _ -> false
                in
                let ((leftWrap, rightWrap) as wrap) = "=> ", ")" ^ rightWrap in
                let wrap =
                  if self#should_preserve_requested_braces retCb
                  then leftWrap ^ "{", "}" ^ rightWrap
                  else wrap
                in
                let returnValueCallback =
                  makeList
                    ~break:(if forceBreak then Always else IfNeed)
                    ~wrap
                    [ x ]
                in
                let argsWithCallbackArgs =
                  List.concat
                    [ List.map self#label_x_expression_param args
                    ; [ theCallbackArg ]
                    ]
                in
                let left =
                  label
                    theFunc
                    (makeList
                       ~pad:(uncurriedApplication, false)
                       ~wrap:("", " ")
                       ~break:IfNeed
                       ~inline:(true, true)
                       ~sep:(Sep ",")
                       ~postSpace:true
                       argsWithCallbackArgs)
                in
                label left returnValueCallback
              | xs ->
                let printWidthExceeded =
                  Reason_heuristics.funAppCallbackExceedsWidth
                    ~printWidth:settings.width
                    ~args
                    ~funExpr
                    ()
                in
                if not printWidthExceeded
                then
                  (* Thing.map(foo, bar, baz, (abc, z) =>
                   *   MyModuleBlah.toList(argument)
                   * )
                   *
                   * To get this kind of formatting we need to construct the following tree:
                   * <Label>
                   * <left>Thing.map(foo, bar, baz, (abc, z)</left><right>=>
                   *   MyModuleBlah.toList(argument)
                   * )</right>
                   * </Label>
                   *
                   * where left is
                   * <Label><left>Thing.map(</left></right>foo, bar, baz, (abc, z) </right></Label>
                   *
                   * The <right> part of that label could be a <List> with wrap:("", " ") break:IfNeed inline:(true, true)
                   * with items: "foo", "bar", "baz", "(abc, z)", separated by commas.
                   *
                   * this is also necessary to achieve the following formatting where }) hugs :
                   * test("my test", () => {
                   *   let x = a + b;
                   *   let y = z + c;
                   *   x + y
                   * });
                   *)
                  let ((leftWrap, rightWrap) as wrap) =
                    "=> ", ")" ^ rightWrap
                  in
                  let wrap =
                    match
                      ( self#should_preserve_requested_braces retCb
                      , self#isSeriesOfOpensFollowedByNonSequencyExpression
                          { retCb with pexp_attributes = [] } )
                    with
                    | true, _ | _, false -> leftWrap ^ "{", "}" ^ rightWrap
                    | _ -> wrap
                  in
                  let right =
                    source_map
                      ~loc:retCb.pexp_loc
                      (makeList
                         ~break:Always_rec
                         ~wrap
                         ~sep:(SepFinal (";", ";"))
                         xs)
                  in
                  let argsWithCallbackArgs =
                    List.map self#label_x_expression_param args
                    @ [ theCallbackArg ]
                  in
                  let left =
                    label
                      theFunc
                      (makeList
                         ~wrap:("", " ")
                         ~break:IfNeed
                         ~inline:(true, true)
                         ~sep:(Sep ",")
                         ~postSpace:true
                         argsWithCallbackArgs)
                  in
                  label left right
                else
                  (* Since the heuristic says the line length is exceeded in this case,
                   * we conveniently format everything as
                   * <label><left>Thing.map(</left><right><list>
                   *   foo,
                   *   bar,
                   *   baz,
                   *   <label> <left>(abc) =></left> <right><list> {
                   *     let x = 1;
                   *     let y = 2;
                   *     x + y
                   *   }</list></right></label>
                   * )</list></right></label>
                   *)
                  let args =
                    makeList
                      ~break:Always
                      ~wrap:("", ")" ^ rightWrap)
                      ~sep:commaTrail
                      (List.map self#label_x_expression_param args
                      @ [ label
                            ~space:true
                            (makeList ~wrap:("", " =>") [ theCallbackArg ])
                            (source_map
                               ~loc:retCb.pexp_loc
                               (makeLetSequence xs))
                        ])
                  in
                  (* This will need to be (theFunc, args) *)
                  label theFunc args
            in
            maybeJSXAttr @ [ formattedFunAppl ]
          | `NormalFunAppl args ->
            let theFunc = source_map ~loc:funExpr.pexp_loc formattedFunExpr in
            (* reset here only because [function,match,try,sequence] are lower
               priority *)
            (* The "expression location" might be different than the location of the actual
             * function application because things like surrounding { } expand the
             * parsed location (in body of while loop for example).
             * We recover the most meaningful function application location we can.*)
            let syntheticApplicationLocation, syntheticArgLoc =
              match args with
              | [] -> funExpr.pexp_loc, funExpr.pexp_loc
              | _ :: _ ->
                ( { funExpr.pexp_loc with
                    loc_end = applicationExpr.pexp_loc.loc_end
                  }
                , { funExpr.pexp_loc with
                    loc_start = funExpr.pexp_loc.loc_end
                  ; loc_end = applicationExpr.pexp_loc.loc_end
                  } )
            in
            let theArgs =
              self#reset#label_x_expression_params
                ~wrap:("", rightWrap)
                ~uncurried
                args
            in
            maybeJSXAttr
            @ [ source_map
                  ~loc:syntheticApplicationLocation
                  (label theFunc (source_map ~loc:syntheticArgLoc theArgs))
              ]
      end

    let toplevel_phrase ppf x =
      match x with
      | Ptop_def s -> format_layout ppf (printer#structure s)
      | Ptop_dir _ -> print_string "(* top directives not supported *)"

    let case_list ppf x = List.iter (format_layout ppf) (printer#case_list x)

    (* Convert a Longident to a list of strings. E.g. M.Constructor will be
       ["Constructor"; "M.Constructor"] Also support ".Constructor" to specify
       access without a path. *)
    let longident_for_arity lid =
      let rec toplevel = function
        | Lident s -> [ s ]
        | Ldot (lid, s) ->
          let append_s x = x ^ "." ^ s in
          s :: List.map append_s (toplevel lid)
        | Lapply (_, s) -> toplevel s
      in
      match lid with Lident s -> ("." ^ s) :: toplevel lid | _ -> toplevel lid

    (* add expilcit_arity to a list of attributes *)
    let add_explicit_arity loc attributes =
      { attr_name = { txt = "explicit_arity"; loc }
      ; attr_payload = PStr []
      ; attr_loc = loc
      }
      :: Reason_syntax_util.normalized_attributes "explicit_arity" attributes

    (* explicit_arity_exists check if expilcit_arity exists *)
    let explicit_arity_not_exists attributes =
      not (Reason_syntax_util.attribute_exists "explicit_arity" attributes)

    (* wrap_expr_with_tuple wraps an expression * with tuple as a sole
       argument. *)
    let wrap_expr_with_tuple exp = { exp with pexp_desc = Pexp_tuple [ exp ] }

    (* wrap_pat_with_tuple wraps an pattern * with tuple as a sole argument. *)
    let wrap_pat_with_tuple pat = { pat with ppat_desc = Ppat_tuple [ pat ] }

    (* explicit_arity_constructors is a set of constructors that are known to
       have * multiple arguments * *)

    module StringSet = Stdlib.Set.Make (String)

    let built_in_explicit_arity_constructors =
      [ "Some"; "Assert_failure"; "Match_failure" ]

    let explicit_arity_constructors =
      StringSet.of_list
        (built_in_explicit_arity_constructors
        @ !configuredSettings.constructorLists)

    let preprocessing_mapper =
      let escape_slashes = new Reason_syntax_util.escape_stars_slashes_mapper in
      object
        inherit Ast_traverse.map as super

        method! expression expr =
          let expr =
            match expr with
            | { pexp_desc = Pexp_construct (lid, Some sp)
              ; pexp_loc
              ; pexp_attributes
              ; _
              }
              when List.exists
                     (fun c -> StringSet.mem c explicit_arity_constructors)
                     (longident_for_arity lid.txt)
                   && explicit_arity_not_exists pexp_attributes ->
              { pexp_desc = Pexp_construct (lid, Some (wrap_expr_with_tuple sp))
              ; pexp_loc
              ; pexp_attributes = add_explicit_arity pexp_loc pexp_attributes
              ; pexp_loc_stack = []
              }
            | x -> x
          in
          escape_slashes#expression (super#expression expr)

        method! pattern pat =
          let pat =
            match pat with
            | { ppat_desc = Ppat_construct (lid, Some (x, sp))
              ; ppat_loc
              ; ppat_attributes
              ; _
              }
              when List.exists
                     (fun c -> StringSet.mem c explicit_arity_constructors)
                     (longident_for_arity lid.txt)
                   && explicit_arity_not_exists ppat_attributes ->
              { ppat_desc =
                  Ppat_construct (lid, Some (x, wrap_pat_with_tuple sp))
              ; ppat_loc
              ; ppat_attributes = add_explicit_arity ppat_loc ppat_attributes
              ; ppat_loc_stack = []
              }
            | x -> x
          in
          escape_slashes#pattern (super#pattern pat)
      end

    let ml_to_reason_swap_operator_mapper =
      new Reason_syntax_util.ml_to_reason_swap_operator_mapper

    let preprocessing_mapper f a =
      a |> f ml_to_reason_swap_operator_mapper |> f preprocessing_mapper

    let core_type ppf x =
      format_layout
        ppf
        (printer#core_type
           (preprocessing_mapper Reason_syntax_util.apply_mapper_to_type x))

    let pattern ppf x =
      format_layout
        ppf
        (printer#pattern
           (preprocessing_mapper Reason_syntax_util.apply_mapper_to_pattern x))

    let signature (comments : Comment.t list) ppf x =
      List.iter (fun comment -> printer#trackComment comment) comments;
      format_layout
        ppf
        ~comments
        (printer#signature
           (preprocessing_mapper Reason_syntax_util.apply_mapper_to_signature x))

    let structure (comments : Comment.t list) ppf x =
      List.iter (fun comment -> printer#trackComment comment) comments;
      format_layout
        ppf
        ~comments
        (printer#structure
           (preprocessing_mapper Reason_syntax_util.apply_mapper_to_structure x))

    let expression ppf x =
      format_layout
        ppf
        (printer#unparseExpr
           (preprocessing_mapper Reason_syntax_util.apply_mapper_to_expr x))

    let case_list = case_list
  end
  in
  object
    method core_type = Formatter.core_type
    method pattern = Formatter.pattern
    method signature = Formatter.signature
    method structure = Formatter.structure

    (* For merlin-destruct *)
    method toplevel_phrase = Formatter.toplevel_phrase
    method expression = Formatter.expression
    method case_list = Formatter.case_list
  end
OCaml

Innovation. Community. Security.