Source file output.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
(*ZZZZ
Should use string_as for comments
*)

open Wax_utils.Colors
open Ast

let indent_level = 4

(* Target line width for Wax output, matching the Rust Style Guide's default
   ([max_width = 100]); WebAssembly text output keeps the printer's own default.
   Passed at every [Printer.run] that renders a Wax module to a real
   formatter. *)
let width = 100

(*** Printer primitives ***)

let get_theme use_color = if use_color then wax_theme else no_color

type 'info ctx = {
  base : Wax_utils.Styled_printer.t;
  (* Extract a source location from a node's annotation, to look its trivia up.
     [fun _ -> None] when printing typed ASTs for diagnostics (no trivia). *)
  locate : 'info -> location option;
}

let print_styled pp style ?(len = None) text =
  Wax_utils.Styled_printer.print_styled pp.base style ~len text

let box pp ?indent f = Wax_utils.Printer.box pp.base.printer ?indent f
let hvbox pp ?indent f = Wax_utils.Printer.hvbox pp.base.printer ?indent f
let hbox pp f = Wax_utils.Printer.hbox pp.base.printer f
let indent pp i f = Wax_utils.Printer.indent pp.base.printer i f
let space pp () = Wax_utils.Printer.space pp.base.printer ()
let cut pp () = Wax_utils.Printer.cut pp.base.printer ()
let newline pp () = Wax_utils.Printer.newline pp.base.printer ()
let punctuation pp s = print_styled pp Punctuation s
let operator pp s = print_styled pp Operator s

(* A declaration terminator [;], held past a deferred trailing comment so it
   sits before the comment ([const x = v; // c]) rather than dangling on its own
   line after it — as the block-statement [;] and list [,] separators already
   do. *)
let semicolon pp =
  Wax_utils.Printer.with_held_eol pp.base.printer (fun () -> punctuation pp ";")

let identifier pp s =
  print_styled pp Identifier ~len:(Some (Wax_utils.Unicode.terminal_width s)) s

let constant pp s = print_styled pp Constant s
let keyword pp s = print_styled pp Keyword s
let type_ pp s = print_styled pp Type s
let string pp ?len s = print_styled pp String ?len s
let attribute pp s = print_styled pp Attribute s

(* Branch-hinting proposal: the [#[likely]]/[#[unlikely]] prefix on a hinted
   conditional branch. *)
let branch_hint_attr pp likely =
  attribute pp (if likely then "#[likely]" else "#[unlikely]");
  space pp ()

(* Comment preservation: emit the trivia (comments, blank lines) the lexer
   collected, looked up by AST-node location. The rendering logic is shared with
   the WebAssembly printer in [Wax_utils.Trivia]. *)

let print_trivia pp lst = Wax_utils.Styled_printer.print_trivia pp.base lst

let get_trivia pp (loc : location option) =
  Wax_utils.Styled_printer.get_trivia pp.base loc

let atomic_node pp (loc : location option) f =
  Wax_utils.Styled_printer.atomic_node pp.base loc f

let with_style ctx style f =
  Wax_utils.Styled_printer.with_style ctx.base style f

let list ?(sep = space) f pp l =
  match l with
  | [] -> ()
  | [ x ] -> f pp x
  | x :: xs ->
      f pp x;
      List.iter
        (fun x ->
          sep pp ();
          f pp x)
        xs

let list_commasep f pp l =
  list
    ~sep:(fun pp () ->
      (* Hold any deferred trailing comment so the comma prints on the comment's
         line, ahead of it. *)
      Wax_utils.Printer.with_held_eol pp.base.printer (fun () ->
          punctuation pp ",");
      space pp ())
    f pp l

(* A trailing comma after the last element of [l], emitted only when the
   enclosing box wraps across lines (rustfmt style). Skipped when the last
   element carries a trailing comment: a comma there would push the comment off
   the element and change where it re-attaches on a reparse (breaking
   idempotence), so the comment-less last element keeps its layout. *)
let trailing_comma pp l =
  if l <> [] && not (Wax_utils.Printer.has_pending_eol pp.base.printer) then
    Wax_utils.Printer.if_broken pp.base.printer (fun () -> punctuation pp ",")

let list_commasep_trailing f pp l =
  list_commasep f pp l;
  trailing_comma pp l

let print_paren_list f pp l =
  punctuation pp "(";
  box pp (fun () -> list_commasep f pp l);
  punctuation pp ")"

(* A Rust-style parenthesised list: it stays on one line if it fits, otherwise
   [(] keeps the preceding token company and the elements break one per line,
   indented one level, with the closing [)] back at the opening column — never
   the Lisp-like [(] on its own line. The caller's enclosing [hvbox] makes the
   choice all-or-nothing. *)
let print_arg_list f pp l =
  punctuation pp "(";
  (match l with
  | [] -> ()
  | _ ->
      indent pp indent_level (fun () ->
          cut pp ();
          list_commasep_trailing f pp l);
      cut pp ());
  punctuation pp ")"

(*** Type printing ***)

let heaptype pp (t : heaptype) =
  match heaptype_keyword t with
  | Some kw -> type_ pp kw
  | None -> (
      match t with Type s | Exact s -> type_ pp s.desc | _ -> assert false)

let reftype pp { nullable; typ } =
  (* The [!] exact marker sits between the [&]/[&?] sigil and the type name. *)
  punctuation pp
    (match (nullable, typ) with
    | true, Exact _ -> "&?!"
    | false, Exact _ -> "&!"
    | true, _ -> "&?"
    | false, _ -> "&");
  heaptype pp typ

let rec valtype pp t =
  match t with
  | I32 -> type_ pp "i32"
  | I64 -> type_ pp "i64"
  | F32 -> type_ pp "f32"
  | F64 -> type_ pp "f64"
  | V128 -> type_ pp "v128"
  | Ref t -> reftype pp t

and tuple always_paren pp l =
  match l with
  | [ t ] when not always_paren -> valtype pp t
  | _ -> print_paren_list valtype pp l

let simple_pat pp p =
  match p with
  | Some x ->
      (* Anchor at the identifier's own location, so a comment trailing the name
         (e.g. before a parameter's [: type]) attaches to it. *)
      atomic_node pp (Some x.info) (fun () -> identifier pp x.desc)
  | None -> operator pp "_"

let print_key_value pp key val_printer value =
  box pp ~indent:indent_level (fun () ->
      identifier pp key;
      punctuation pp ":";
      space pp ();
      val_printer pp value)

let print_typed_pat pp (pat, opt_typ) =
  box pp ~indent:indent_level (fun () ->
      simple_pat pp pat;
      Option.iter
        (fun t ->
          punctuation pp ":";
          space pp ();
          valtype pp t)
        opt_typ)

let raw_functype pp { params; results } =
  print_arg_list
    (fun pp p ->
      let id, t = p.desc in
      (* Anchor trivia at the whole parameter, so a trailing comment attaches to
         it — named or not. *)
      atomic_node pp (Some p.info) (fun () ->
          match id with
          | None -> valtype pp t
          | Some _ -> print_typed_pat pp (id, Some t)))
    pp (Array.to_list params);
  if results <> [||] then
    (* Keep [-> Ret] glued to the closing [)] so the parameter list, not the
       arrow, is what breaks when the signature overflows. *)
    hbox pp (fun () ->
        space pp ();
        operator pp "->";
        space pp ();
        tuple false pp (Array.to_list results))

let functype pp ty =
  box pp ~indent:indent_level (fun () ->
      keyword pp "fn";
      raw_functype pp ty)

let blocktype pp typ =
  match typ with
  | { params = [||]; results = [| ty |] } -> valtype pp ty
  | _ -> box pp ~indent:indent_level (fun () -> raw_functype pp typ)

let packedtype pp t = type_ pp (match t with I8 -> "i8" | I16 -> "i16")

let storagetype pp t =
  match t with Value t -> valtype pp t | Packed t -> packedtype pp t

(* The bare name of a numeric-literal type suffix ([1i32] -> ["i32"]). *)
let suffix_string : Ast.storagetype -> string = function
  | Packed I8 -> "i8"
  | Packed I16 -> "i16"
  | Value I32 -> "i32"
  | Value I64 -> "i64"
  | Value F32 -> "f32"
  | Value F64 -> "f64"
  | Value (V128 | Ref _) -> assert false

let muttype t pp { mut; typ } =
  if mut then
    box pp ~indent:indent_level (fun () ->
        keyword pp "mut";
        space pp ();
        t pp typ)
  else t pp typ

let fieldtype = muttype storagetype

let comptype pp (t : comptype) =
  match t with
  | Func t -> functype pp t
  | Struct l ->
      (* The opening brace is printed in [subtype] *)
      indent pp indent_level (fun () ->
          space pp ();
          list_commasep
            (fun pp field ->
              (* A leading [..] inherits the supertype's fields; the parser puts
                 it first, so it prints as the first comma-separated item. *)
              if Ast.is_splice_field field then punctuation pp ".."
              else
                let nm, t = field.desc in
                (* Look the field's trivia up by its own location, so a trailing
                   comment attaches to the whole field. *)
                atomic_node pp (Some field.info) (fun () ->
                    print_key_value pp nm.desc fieldtype t))
            pp (Array.to_list l));
      space pp ();
      punctuation pp "}"
  | Array t ->
      punctuation pp "[";
      box pp (fun () -> fieldtype pp t);
      punctuation pp "]"
  | Cont s ->
      type_ pp "cont";
      space pp ();
      type_ pp s.desc

let subtype pp field =
  let nm, { typ; supertype; final; descriptor; describes } = field.desc in
  atomic_node pp (Some field.info) @@ fun () ->
  hvbox pp (fun () ->
      let is_struct = match typ with Struct _ -> true | _ -> false in
      box pp (fun () ->
          keyword pp "type";
          space pp ();
          identifier pp nm.desc;
          (match supertype with
          | Some supertype ->
              punctuation pp ":";
              space pp ();
              identifier pp supertype.desc
          | None -> ());
          space pp ();
          punctuation pp "=";
          if not final then (
            space pp ();
            keyword pp "open");
          (* custom-descriptors clauses, between [open] and the body. *)
          let clause kw = function
            | Some (id : ident) ->
                space pp ();
                keyword pp kw;
                space pp ();
                identifier pp id.desc
            | None -> ()
          in
          clause "describes" describes;
          clause "descriptor" descriptor;
          if is_struct then (
            space pp ();
            punctuation pp "{"));
      space pp ();
      comptype pp typ;
      punctuation pp ";")

let rectype pp t =
  match Array.to_list t with
  | [ t ] -> subtype pp t
  | l ->
      hvbox pp (fun () ->
          box pp (fun () ->
              keyword pp "rec";
              space pp ();
              punctuation pp "{");
          indent pp indent_level (fun () ->
              space pp ();
              list ~sep:space subtype pp l);
          space pp ();
          punctuation pp "}")

(*** Operators and precedence ***)

let binop op =
  match op with
  | Add -> "+"
  | Sub -> "-"
  | Mul -> "*"
  | Div None -> "/"
  | Div (Some Signed) -> "/s"
  | Div (Some Unsigned) -> "/u"
  | Rem Signed -> "%s"
  | Rem Unsigned -> "%u"
  | And -> "&"
  | Or -> "|"
  | Xor -> "^"
  | Shl -> "<<"
  | Shr Signed -> ">>s"
  | Shr Unsigned -> ">>u"
  | Eq -> "=="
  | Ne -> "!="
  | Lt None -> "<"
  | Lt (Some Signed) -> "<s"
  | Lt (Some Unsigned) -> "<u"
  | Gt None -> ">"
  | Gt (Some Signed) -> ">s"
  | Gt (Some Unsigned) -> ">u"
  | Le None -> "<="
  | Le (Some Signed) -> "<=s"
  | Le (Some Unsigned) -> "<=u"
  | Ge None -> ">="
  | Ge (Some Signed) -> ">=s"
  | Ge (Some Unsigned) -> ">=u"

let unop op = match op with Neg -> "-" | Pos -> "+" | Not -> "!"

type prec =
  | Instruction
  | Branch
  | Assignement
  | Select
  | Comparison
  | LogicalOr
  | LogicalXor
  | LogicalAnd
  | Shift
  | Addition
  | Multiplication
  | Cast
  | UnaryPrefix
  | UnaryPostfix
  | CallAndFieldAccess
  | Atom

let parentheses expected actual pp g =
  if expected > actual then (
    punctuation pp "(";
    box pp (fun () ->
        g ();
        (* Hold the closing [)] past a trailing comment on the last inner token,
           so it hugs the expression ([(c == 108) // 'l']) instead of being
           pushed onto its own line after the comment — as [;] and [,] do. *)
        Wax_utils.Printer.with_held_eol pp.base.printer (fun () ->
            punctuation pp ")")))
  else g ()

let prec_op op =
  (* out, left, right *)
  match op with
  | Add | Sub -> (Addition, Addition, Multiplication)
  | Mul | Div _ | Rem _ -> (Multiplication, Multiplication, Cast)
  | And -> (LogicalAnd, LogicalAnd, Shift)
  | Or -> (LogicalOr, LogicalOr, LogicalXor)
  | Xor -> (LogicalXor, LogicalXor, LogicalAnd)
  | Shl | Shr _ -> (Shift, Shift, Addition)
  | Gt _ | Lt _ | Ge _ | Le _ | Eq | Ne -> (Comparison, LogicalOr, LogicalOr)

(*** Instruction-printing helpers ***)

let block_label pp label =
  Option.iter
    (fun label ->
      identifier pp "'";
      identifier pp label.desc;
      punctuation pp ":";
      space pp ())
    label

let need_blocktype bt = bt.params <> [||] || bt.results <> [||]

let casttype pp ty =
  match ty with
  | Valtype ty -> valtype pp ty
  | Functype { nullable; sign } ->
      punctuation pp (if nullable then "&?" else "&");
      functype pp sign
  | Signedtype { typ; signage; strict } ->
      type_ pp (Ast.format_signed_type typ signage strict)

let branch_instr instr pp name label i =
  box pp ~indent:indent_level (fun () ->
      keyword pp name;
      space pp ();
      identifier pp "'";
      identifier pp label.desc;
      Option.iter
        (fun i ->
          space pp ();
          instr Branch pp i)
        i)

let branch_ref_instr instr pp name label ty i =
  box pp ~indent:indent_level (fun () ->
      keyword pp name;
      space pp ();
      identifier pp "'";
      identifier pp label.desc;
      space pp ();
      reftype pp ty;
      space pp ();
      instr Branch pp i)

(* [ [?]descriptor(d) ] — the target-spec of the custom-descriptors instructions
   ([ref.cast_desc_eq], [br_on_cast_desc_eq], [struct.new_desc]). The target type
   is recovered from [d]'s descriptor type, so only the operand is written; a
   leading [?] marks a nullable result. The [( )] delimit [d] so it may be any
   expression with no precedence clash. *)
let descriptor_operand instr pp ?(nullable = false) d =
  if nullable then punctuation pp "?";
  keyword pp "descriptor";
  punctuation pp "(";
  box pp (fun () -> instr Instruction pp d);
  punctuation pp ")"

(* As [branch_ref_instr], for the custom-descriptors [br_on_cast_desc_eq] /
   [_fail]: the [[?]descriptor(d)] target-spec precedes the value, so the value
   is the sole trailing operand and prints at [Branch] like the plain form. *)
let branch_ref_desc_instr instr pp name label nullable i d =
  box pp ~indent:indent_level (fun () ->
      keyword pp name;
      space pp ();
      identifier pp "'";
      identifier pp label.desc;
      space pp ();
      descriptor_operand instr pp ~nullable d;
      space pp ();
      instr Branch pp i)

let call_instr instr pp ?prefix i l =
  hvbox pp (fun () ->
      (* Keep an optional prefix ([become]/[return]) and the callee glued to the
         opening [(]: only the argument list may break. *)
      hbox pp (fun () ->
          Option.iter
            (fun s ->
              keyword pp s;
              space pp ())
            prefix;
          instr CallAndFieldAccess pp i);
      print_arg_list (instr Instruction) pp l)

(* All but the last element ([] if empty) — the non-receiver operands of a
   stack-switching method call. *)
let drop_last l = match List.rev l with [] -> [] | _ :: r -> List.rev r

(* A continuation constructor [T::new(f)] / [T::bind(args…, c)]: the [T::]
   namespace constructs a [&T]; the type is always explicit (it is the
   namespace itself). *)
let cont_construct_instr instr pp ct member l =
  box pp ~indent:indent_level (fun () ->
      hbox pp (fun () ->
          identifier pp ct.desc;
          operator pp "::";
          identifier pp member);
      print_arg_list (instr Instruction) pp l)

let print_on_clauses pp handlers =
  punctuation pp "[";
  box pp (fun () ->
      list_commasep
        (fun pp clause ->
          match clause with
          | OnLabel (tag, label) ->
              identifier pp tag.desc;
              space pp ();
              punctuation pp "->";
              space pp ();
              identifier pp "'";
              identifier pp label.desc
          | OnSwitch tag ->
              identifier pp tag.desc;
              space pp ();
              punctuation pp "->";
              space pp ();
              keyword pp "switch")
        pp handlers);
  punctuation pp "]"

(* A stack-switching method call [recv.meth(args…) on [handlers]]. The receiver
   is the LAST operand of [l] — Wasm stack order: it compiles last, exactly as
   call_ref's callee does — and prints first, as the method receiver. [args]
   renders the parenthesised argument list (closures, so [resume_throw]'s
   [tag(payload)] and [switch]'s [tag: t] need no AST form). *)
let cont_method_instr instr pp meth l ~args ~handlers =
  box pp ~indent:indent_level (fun () ->
      hvbox pp (fun () ->
          hbox pp (fun () ->
              (match List.rev l with
              | recv :: _ -> instr CallAndFieldAccess pp recv
              | [] -> operator pp "_" (* ill-formed operand list: recovery *));
              punctuation pp ".";
              identifier pp meth);
          print_arg_list (fun pp g -> g pp) pp args);
      match handlers with
      | [] -> ()
      | _ :: _ ->
          space pp ();
          keyword pp "on";
          space pp ();
          print_on_clauses pp handlers)

let print_container pp ~opening ~closing ?(indent = 0) opt_type f =
  hvbox pp ~indent (fun () ->
      box pp (fun () ->
          punctuation pp opening;
          Option.iter
            (fun t ->
              identifier pp t.desc;
              punctuation pp "|")
            opt_type);
      f ();
      punctuation pp closing)

let struct_instr pp nm f =
  print_container pp ~opening:"{" ~closing:"}" ~indent:0 nm (fun () ->
      indent pp indent_level (fun () ->
          space pp ();
          f ());
      space pp ())

(* As [struct_instr] but with a leading [descriptor(d)] target-spec instead of a
   type name (the custom-descriptors [struct.new_desc] / [struct.new_default_desc];
   the struct type is recovered from [d]). [print_desc] renders the operand. *)
let struct_desc_instr pp print_desc f =
  hvbox pp ~indent:0 (fun () ->
      box pp (fun () ->
          punctuation pp "{";
          space pp ();
          print_desc ();
          punctuation pp "|");
      indent pp indent_level (fun () ->
          space pp ();
          f ());
      space pp ();
      punctuation pp "}")

let array_instr pp nm f =
  (* Indent the elements one level and break before the closing [\]] at the
     array's own column (like [struct_instr]), so a wrapped array reads
     [\[t|]/elem,/.../elem,/]\]] with [\]] dedented — not hugging the last
     element as [elem,\]]. *)
  print_container pp ~opening:"[" ~closing:"]" ~indent:0 nm (fun () ->
      indent pp indent_level (fun () ->
          cut pp ();
          f ());
      cut pp ())

let rec get_prec (i : _ Ast.instr) =
  match i.desc with
  (* Branch-hinting proposal: the hint is a transparent prefix; the wrapped
     branch drives precedence, block-ness, and layout. *)
  | Hinted (_, i) -> get_prec i
  | Block _ | Loop _ | While _ | If _ | Try _ | TryCatch _ | TryTable _
  | If_annotation _ | Dispatch _ | Match _ ->
      Atom
  | Unreachable | Nop | Hole | Null | Get _ | Path _ | Char _ | String _ | Int _
  | Float _ | Struct _ | StructDefault _ | StructDesc _ | StructDefaultDesc _
  | Array _ | ArrayDefault _ | ArrayFixed _ | ArraySegment _ | ArrayGet _
  | ArraySet _ | Sequence _ ->
      Atom
  | Set _ | Tee _ -> Assignement
  | Call _ | TailCall _ -> CallAndFieldAccess
  | ContNew _ | ContBind _ | Suspend _ | Switch _ -> CallAndFieldAccess
  (* A resume-family instruction with handlers carries its postfix [on] clause,
     which binds like [as]/[is]. *)
  | Resume (_, h, _) | ResumeThrow (_, _, h, _) | ResumeThrowRef (_, h, _) ->
      if h = [] then CallAndFieldAccess else Cast
  | On _ -> Cast
  | Cast _ | CastDesc _ | Test _ -> Cast
  | NonNull _ -> UnaryPostfix
  | UnOp _ -> UnaryPrefix
  | StructGet _ | StructSet _ | GetDescriptor _ -> CallAndFieldAccess
  | BinOp (op, _, _) ->
      let out, _, _ = prec_op op.desc in
      out
  | Let _ | Labelled _ -> Instruction
  | Br _ | Br_if _ | Br_table _ | Br_on_null _ | Br_on_non_null _ | Br_on_cast _
  | Br_on_cast_fail _ | Br_on_cast_desc_eq _ | Br_on_cast_desc_eq_fail _
  | Throw _ | ThrowRef _ | Return _ ->
      Branch
  | Select _ -> Select

let rec is_block (i : _ Ast.instr) =
  match i.desc with
  | Hinted (_, i) -> is_block i
  | Block _ | Loop _ | While _ | If _ | Try _ | TryCatch _ | TryTable _
  | If_annotation _ | Dispatch _ | Match _ ->
      true
  | Call _ | Unreachable | Nop | Hole | Null | Get _ | Path _ | Set _ | Tee _
  | TailCall _ | Char _ | String _ | Int _ | Float _ | Cast _ | CastDesc _
  | Test _ | NonNull _ | Struct _ | StructDefault _ | StructDesc _
  | StructDefaultDesc _ | StructGet _ | GetDescriptor _ | StructSet _ | Array _
  | ArrayDefault _ | ArrayFixed _ | ArraySegment _ | ArrayGet _ | ArraySet _
  | BinOp _ | UnOp _ | Let _ | Br _ | Br_if _ | Br_table _ | Br_on_null _
  | Br_on_non_null _ | Br_on_cast _ | Br_on_cast_fail _ | Br_on_cast_desc_eq _
  | Br_on_cast_desc_eq_fail _ | Throw _ | ThrowRef _ | ContNew _ | ContBind _
  | Suspend _ | Resume _ | ResumeThrow _ | ResumeThrowRef _ | Switch _ | On _
  | Return _ | Sequence _ | Select _ | Labelled _ ->
      false

let rec starts_with_block_prec prec (i : 'a Ast.instr) =
  let actual = get_prec i in
  if prec > actual then false
  else
    match i.desc with
    | Hinted (_, i) -> starts_with_block_prec prec i
    | Block _ | Loop _ | While _ | If _ | Try _ | TryCatch _ | TryTable _
    | If_annotation _ | Dispatch _ | Match _ ->
        true
    | Call (i, _) | ArrayGet (i, _) | ArraySet (i, _, _) ->
        starts_with_block_prec CallAndFieldAccess i
    | Cast (i, _) | CastDesc (i, _, _) | Test (i, _) ->
        starts_with_block_prec Cast i
    | NonNull i -> starts_with_block_prec UnaryPostfix i
    | UnOp (_, i) -> starts_with_block_prec UnaryPrefix i
    | StructGet (i, _) | StructSet (i, _, _) | GetDescriptor i ->
        starts_with_block_prec CallAndFieldAccess i
    | BinOp (op, i, _) ->
        let _, left, _ = prec_op op.desc in
        starts_with_block_prec left i
    | Select (i, _, _) -> starts_with_block_prec Select i
    | On (i, _) -> starts_with_block_prec Cast i
    (* The method-form stack-switching instructions print their receiver — the
       last operand — first. *)
    | Resume (_, _, l)
    | ResumeThrow (_, _, _, l)
    | ResumeThrowRef (_, _, l)
    | Switch (_, _, l) -> (
        match List.rev l with
        | recv :: _ -> starts_with_block_prec CallAndFieldAccess recv
        | [] -> false)
    | Unreachable | Nop | Hole | Null | Get _ | Path _ | Set _ | Tee _
    | TailCall _ | Char _ | String _ | Int _ | Float _ | Struct _
    | StructDefault _ | StructDesc _ | StructDefaultDesc _ | Array _
    | ArrayDefault _ | ArrayFixed _ | ArraySegment _ | Let _ | Br _ | Br_if _
    | Br_table _ | Br_on_null _ | Br_on_non_null _ | Br_on_cast _
    | Br_on_cast_fail _ | Br_on_cast_desc_eq _ | Br_on_cast_desc_eq_fail _
    | Throw _ | ThrowRef _ | ContNew _ | ContBind _ | Suspend _ | Return _
    | Sequence _ | Labelled _ ->
        false

let starts_with_block i = starts_with_block_prec Instruction i

let array_element_precedence nm first i =
  if nm = None && first then
    match i.desc with
    | BinOp ({ desc = Or; _ }, { desc = Get _; _ }, _) -> Atom
    | _ -> Instruction
  else Instruction

let cond_op_string (op : Wax_wasm.Ast.cmp_op) =
  match op with
  | Eq -> "="
  | Ne -> "!="
  | Lt -> "<"
  | Gt -> ">"
  | Le -> "<="
  | Ge -> ">="

let rec cond_to_string (c : Wax_wasm.Ast.cond) =
  match c with
  | Cond_var v -> v.desc
  | Cond_string s -> Printf.sprintf "%S" s.desc
  | Cond_version (a, b, c) -> Printf.sprintf "(%d, %d, %d)" a b c
  | Cond_cmp (op, a, b) ->
      Printf.sprintf "%s %s %s" (cond_to_string a) (cond_op_string op)
        (cond_to_string b)
  | Cond_and l -> Printf.sprintf "all(%s)" (cond_list l)
  | Cond_or l -> Printf.sprintf "any(%s)" (cond_list l)
  | Cond_not c -> Printf.sprintf "not(%s)" (cond_to_string c)

and cond_list l = String.concat ", " (List.map cond_to_string l)

(* The comma-separated case labels of a [br_table]/[dispatch] bracket, ending
   in [else <default>]; printed inside a fill box so they pack and wrap. *)
let label_seq pp cases default =
  List.iter
    (fun (l : Ast.ident) ->
      identifier pp "'";
      identifier pp l.desc;
      punctuation pp ",";
      space pp ())
    cases;
  box pp (fun () ->
      keyword pp "else";
      space pp ();
      identifier pp "'";
      identifier pp default.desc)

(* Print [<before>[ <labels> else <default> ]<after>], shared by [br_table] and
   [dispatch]. On one line when it fits; otherwise [<before>[] stays on the line,
   the labels are filled and indented, and []<after>] is dedented to the box's
   column:
     <before>[
         <labels …>
         … else <default>
     ]<after>
   [after] (e.g. the [dispatch] body's [{]) is glued to the []]. *)
let bracketed_labels pp ~before ?(after = fun () -> ()) cases default =
  hvbox pp ~indent:0 (fun () ->
      hbox pp (fun () ->
          before ();
          punctuation pp "[");
      indent pp indent_level (fun () ->
          space pp ();
          box pp (fun () -> label_seq pp cases default));
      space pp ();
      hbox pp (fun () ->
          punctuation pp "]";
          after ()))

let match_pattern pp (pat : Ast.match_pattern) =
  match pat with
  | MatchCast (bind, rt) ->
      Option.iter
        (fun x ->
          identifier pp x.desc;
          punctuation pp ":";
          space pp ())
        bind;
      reftype pp rt
  | MatchNull -> keyword pp "null"

(*** The instruction printer ***)

let rec instr prec pp (i : _ instr) =
  atomic_node pp (pp.locate i.info) @@ fun () ->
  parentheses prec (get_prec i) pp @@ fun () ->
  match i.desc with
  | Block { label; typ; block = l } ->
      (* A plain block is always introduced by [do] (a bare or labelled [{ … }]
         also parses, but [do] is the canonical form we emit). *)
      block pp label (Some "do") typ l
  | If_annotation { cond; then_body; else_body } ->
      let branch body =
        space pp ();
        punctuation pp "{";
        let after = located_block_contents pp body in
        close_block pp after
      in
      hvbox pp (fun () ->
          attribute pp (Printf.sprintf "#[if(%s)]" (cond_to_string cond));
          branch then_body;
          Option.iter
            (fun b ->
              newline pp ();
              attribute pp "#[else]";
              branch b)
            else_body)
  | Loop { label; typ; block = l } -> block pp label (Some "loop") typ l
  | While { label; cond; step; block = l } ->
      hvbox pp (fun () ->
          box pp (fun () ->
              block_label pp label;
              keyword pp "while";
              indent pp indent_level (fun () ->
                  space pp ();
                  instr Instruction pp cond;
                  (* Zig-style continue-expression: [: (step)] after the cond. *)
                  match step with
                  | None -> ()
                  | Some s ->
                      space pp ();
                      punctuation pp ":";
                      space pp ();
                      punctuation pp "(";
                      instr Instruction pp s;
                      punctuation pp ")");
              space pp ();
              punctuation pp "{");
          let after = located_block_contents pp l in
          close_block pp after)
  | If { label; typ; cond; if_block; else_block } ->
      hvbox pp (fun () ->
          box pp (fun () ->
              block_label pp label;
              keyword pp "if";
              indent pp indent_level (fun () ->
                  space pp ();
                  instr Instruction pp cond;
                  if need_blocktype typ then (
                    space pp ();
                    box pp ~indent:indent_level (fun () ->
                        punctuation pp "=>";
                        space pp ();
                        blocktype pp typ)));
              space pp ();
              punctuation pp "{");
          let if_after = located_block_contents pp if_block in
          match else_block with
          | Some else_block ->
              hvbox pp (fun () ->
                  box pp (fun () ->
                      punctuation pp "}";
                      print_trivia pp if_after;
                      space pp ();
                      keyword pp "else";
                      space pp ();
                      punctuation pp "{");
                  let else_after = located_block_contents pp else_block in
                  close_block pp else_after)
          | None -> close_block pp if_after)
  | TryCatch { label; typ; block = l; arms } ->
      hvbox pp (fun () ->
          box pp (fun () ->
              block_label pp label;
              keyword pp "try";
              space pp ();
              if need_blocktype typ then (
                blocktype pp typ;
                space pp ());
              punctuation pp "{");
          let block_after = located_block_contents pp l in
          hvbox pp (fun () ->
              box pp (fun () ->
                  punctuation pp "}";
                  print_trivia pp block_after;
                  space pp ();
                  keyword pp "catch";
                  space pp ();
                  punctuation pp "{");
              indent pp indent_level (fun () ->
                  List.iter
                    (fun arm ->
                      space pp ();
                      hvbox pp (fun () ->
                          box pp (fun () ->
                              (match arm.arm_tag with
                              | Some tag -> identifier pp tag.desc
                              | None -> operator pp "_");
                              space pp ();
                              if arm.arm_ref then (
                                operator pp "&";
                                space pp ());
                              punctuation pp "=>";
                              space pp ();
                              punctuation pp "{");
                          let after = located_block_contents pp arm.arm_body in
                          close_block pp after))
                    arms);
              (* The break before the closing [}] must sit outside the [indent]
                 above so it lands at the catch block's own column, not the
                 arms' deeper indent. *)
              space pp ();
              punctuation pp "}"))
  | Try { label; typ; block = l; catches; catch_all } ->
      hvbox pp (fun () ->
          box pp (fun () ->
              block_label pp label;
              keyword pp "try_legacy";
              space pp ();
              if need_blocktype typ then (
                blocktype pp typ;
                space pp ());
              punctuation pp "{");
          let block_after = located_block_contents pp l in
          hvbox pp (fun () ->
              box pp (fun () ->
                  punctuation pp "}";
                  print_trivia pp block_after;
                  space pp ();
                  keyword pp "catch";
                  space pp ();
                  punctuation pp "{");
              indent pp indent_level (fun () ->
                  List.iter
                    (fun (tag, block) ->
                      space pp ();
                      hvbox pp (fun () ->
                          box pp (fun () ->
                              identifier pp tag.desc;
                              space pp ();
                              punctuation pp "=>";
                              space pp ();
                              punctuation pp "{");
                          let after = located_block_contents pp block in
                          close_block pp after))
                    catches;
                  Option.iter
                    (fun block ->
                      space pp ();
                      hvbox pp (fun () ->
                          box pp (fun () ->
                              operator pp "_";
                              space pp ();
                              punctuation pp "=>";
                              space pp ();
                              punctuation pp "{");
                          let after = located_block_contents pp block in
                          close_block pp after))
                    catch_all);
              (* The break before the closing [}] must sit outside the [indent]
                 above so it lands at the catch block's own column, not the
                 handlers' deeper indent. *)
              space pp ();
              punctuation pp "}"))
  | TryTable { label; typ = bt; block = l; catches } ->
      hvbox pp (fun () ->
          box pp (fun () ->
              block_label pp label;
              keyword pp "try";
              space pp ();
              if need_blocktype bt then (
                blocktype pp bt;
                space pp ());
              punctuation pp "{");
          let block_after = located_block_contents pp l in
          hvbox pp (fun () ->
              box pp (fun () ->
                  punctuation pp "}";
                  print_trivia pp block_after;
                  space pp ();
                  keyword pp "catch";
                  space pp ();
                  punctuation pp "[");
              indent pp indent_level (fun () ->
                  let last = List.length catches - 1 in
                  List.iteri
                    (fun i catch ->
                      space pp ();
                      box pp (fun () ->
                          match catch with
                          | Catch (tag, label) ->
                              identifier pp tag.desc;
                              space pp ();
                              punctuation pp "->";
                              space pp ();
                              identifier pp "'";
                              identifier pp label.desc;
                              if i < last then punctuation pp ","
                          | CatchRef (tag, label) ->
                              identifier pp tag.desc;
                              space pp ();
                              operator pp "&";
                              space pp ();
                              punctuation pp "->";
                              space pp ();
                              identifier pp "'";
                              identifier pp label.desc;
                              if i < last then punctuation pp ","
                          | CatchAll label ->
                              operator pp "_";
                              space pp ();
                              punctuation pp "->";
                              space pp ();
                              identifier pp "'";
                              identifier pp label.desc;
                              if i < last then punctuation pp ","
                          | CatchAllRef label ->
                              operator pp "_";
                              space pp ();
                              operator pp "&";
                              space pp ();
                              punctuation pp "->";
                              space pp ();
                              identifier pp "'";
                              identifier pp label.desc;
                              if i < last then punctuation pp ","))
                    catches);
              (* Break before the closing [\]] so a wrapped handler list dedents
                 it to the [try]'s column rather than hugging the last handler. *)
              cut pp ();
              punctuation pp "]"))
  | Unreachable -> keyword pp "unreachable"
  | Nop -> operator pp "nop"
  | Hole -> operator pp "_"
  | Get x -> identifier pp x.desc
  | Path (x, y) ->
      identifier pp x.desc;
      operator pp "::";
      identifier pp y.desc
  | Set (x, op, i) ->
      box pp ~indent:indent_level (fun () ->
          identifier pp x.desc;
          space pp ();
          (* [x op= e] for a compound assignment; a plain [=] otherwise. *)
          operator pp
            (match op with None -> "=" | Some o -> binop o.desc ^ "=");
          space pp ();
          instr Instruction pp i)
  | Tee (x, i) ->
      box pp ~indent:indent_level (fun () ->
          identifier pp x.desc;
          space pp ();
          operator pp ":=";
          space pp ();
          instr Instruction pp i)
  | Call (i, l) -> call_instr instr pp i l
  | TailCall (i, l) -> call_instr instr pp ~prefix:"become" i l
  | Labelled (l, i) -> print_key_value pp l.desc (instr Instruction) i
  | Char c ->
      let n = Uchar.utf_8_byte_length c in
      let b = Bytes.create n in
      ignore (Bytes.set_utf_8_uchar b 0 c);
      let len, s =
        Wax_utils.Unicode.escape_string ~hex_prefix:"x" (Bytes.to_string b)
      in
      string pp "\'";
      string pp ~len:(Some len) s;
      string pp "\'"
  | String (t, s) ->
      Option.iter
        (fun t ->
          type_ pp t.desc;
          operator pp "#")
        t;
      let len, s = Wax_utils.Unicode.escape_string ~hex_prefix:"x" s in
      string pp "\"";
      string pp ~len:(Some len) s;
      string pp "\""
  | Int s | Float s -> constant pp s
  | Cast (i, t) ->
      box pp ~indent:indent_level (fun () ->
          instr Cast pp i;
          space pp ();
          box pp (fun () ->
              keyword pp "as";
              space pp ();
              casttype pp t))
  | CastDesc (i, nullable, d) ->
      box pp ~indent:indent_level (fun () ->
          instr Cast pp i;
          space pp ();
          box pp (fun () ->
              keyword pp "as";
              space pp ();
              descriptor_operand instr pp ~nullable d))
  | NonNull i ->
      instr UnaryPostfix pp i;
      operator pp "!"
  | Test (i, t) ->
      box pp ~indent:indent_level (fun () ->
          instr Cast pp i;
          space pp ();
          box pp (fun () ->
              keyword pp "is";
              space pp ();
              reftype pp t))
  | Struct (nm, l) ->
      struct_instr pp nm (fun () -> list_commasep_trailing struct_field_kv pp l)
  | StructDefault nm -> struct_instr pp nm (fun () -> punctuation pp "..")
  | StructDesc (d, l) ->
      struct_desc_instr pp
        (fun () -> descriptor_operand instr pp d)
        (fun () -> list_commasep_trailing struct_field_kv pp l)
  | StructDefaultDesc d ->
      struct_desc_instr pp
        (fun () -> descriptor_operand instr pp d)
        (fun () -> punctuation pp "..")
  | StructGet (i, s) ->
      field_receiver pp i;
      operator pp ".";
      identifier pp s.desc
  | GetDescriptor i ->
      field_receiver pp i;
      operator pp ".";
      keyword pp "descriptor"
  | StructSet (i, s, i') ->
      box pp ~indent:indent_level (fun () ->
          field_receiver pp i;
          operator pp ".";
          identifier pp s.desc;
          space pp ();
          operator pp "=";
          space pp ();
          instr Instruction pp i')
  | Array (nm, i, n) ->
      array_instr pp nm (fun () ->
          instr (array_element_precedence nm true i) pp i;
          punctuation pp ";";
          space pp ();
          instr Instruction pp n)
  | ArrayDefault (nm, n) ->
      array_instr pp nm (fun () ->
          punctuation pp "..;";
          space pp ();
          instr Instruction pp n)
  | ArrayFixed (nm, l) ->
      array_instr pp nm (fun () ->
          list_commasep_trailing
            (fun ctx (first, i) ->
              instr (array_element_precedence nm first i) ctx i)
            pp
            (List.mapi (fun n i -> (n = 0, i)) l))
  | ArraySegment (nm, d, off, len) ->
      hvbox pp ~indent:0 (fun () ->
          box pp (fun () ->
              punctuation pp "[";
              Option.iter
                (fun t ->
                  identifier pp t.desc;
                  punctuation pp "|")
                nm;
              space pp ();
              identifier pp d.desc;
              space pp ();
              operator pp "@");
          indent pp indent_level (fun () ->
              space pp ();
              instr Instruction pp off);
          punctuation pp ";";
          indent pp indent_level (fun () ->
              space pp ();
              instr Instruction pp len);
          cut pp ();
          punctuation pp "]")
  | ArrayGet (i1, i2) ->
      box pp ~indent:indent_level (fun () ->
          instr CallAndFieldAccess pp i1;
          cut pp ();
          box pp (fun () ->
              operator pp "[";
              instr Instruction pp i2;
              operator pp "]"))
  | ArraySet (i1, i2, i3) ->
      box pp ~indent:indent_level (fun () ->
          instr CallAndFieldAccess pp i1;
          cut pp ();
          box pp (fun () ->
              operator pp "[";
              instr Instruction pp i2;
              operator pp "]");
          space pp ();
          operator pp "=";
          space pp ();
          instr Instruction pp i3)
  | BinOp (op, i, i') ->
      let _, left, right = prec_op op.desc in
      (* The [precedence] lint (see [Typing.lint_precedence]) flags a shift mixed
         with arithmetic, or a comparison with a bitwise operator, written
         without parentheses — precedence alone would not require them. Emit them
         anyway around such an operand (by demanding an [Atom] there) so
         re-printed / decompiled Wax stays quiet under the lint. The confusion
         table is shared with the lint ({!Ast_utils.confusing_precedence}). *)
      let operand_prec default (child : _ instr) =
        match child.desc with
        | BinOp (child_op, _, _)
          when Ast_utils.confusing_precedence
                 (Ast_utils.binop_kind op.desc)
                 (Ast_utils.binop_kind child_op.desc) ->
            Atom
        | _ -> default
      in
      box pp ~indent:indent_level (fun () ->
          instr (operand_prec left i) pp i;
          (* Break *before* the operator (rustfmt style: a wrapped operator
             leads its continuation line), so only the space ahead of it may
             break; the space after it is a plain, non-breaking blank. The
             operator carries its own location, so a comment between the left
             operand and it attaches to the operand, ahead of the break. *)
          space pp ();
          atomic_node pp (Some op.info) (fun () -> operator pp (binop op.desc));
          Wax_utils.Printer.string pp.base.printer " ";
          instr (operand_prec right i') pp i')
  | UnOp (op, i) ->
      atomic_node pp (Some op.info) (fun () -> operator pp (unop op.desc));
      instr UnaryPrefix pp i
  | Let ([ (None, typ) ], Some i) ->
      (* An anonymous binding is a discarded value: printed [_ = e] (or, when a
         width annotation is load-bearing, [_: t = e]) — without [let], since
         nothing is bound. Mirrors the [Set] layout. *)
      box pp ~indent:indent_level (fun () ->
          hbox pp (fun () ->
              operator pp "_";
              Option.iter
                (fun t ->
                  punctuation pp ":";
                  space pp ();
                  valtype pp t)
                typ;
              space pp ();
              operator pp "=");
          space pp ();
          instr Instruction pp i)
  | Let (l, i) ->
      box pp ~indent:indent_level (fun () ->
          (* Keep [let pat =] together as one unit: when the value breaks the
             line after [=], without this box the outer box would also split
             [let]/[pat]/[=] across lines. *)
          hbox pp (fun () ->
              keyword pp "let";
              space pp ();
              (match l with
              | [ p ] -> print_typed_pat pp p
              | l -> print_paren_list print_typed_pat pp l);
              if Option.is_some i then (
                space pp ();
                keyword pp "="));
          Option.iter
            (fun i ->
              space pp ();
              instr Instruction pp i)
            i)
  | Br (label, i) -> branch_instr instr pp "br" label i
  | Br_if (label, i) -> branch_instr instr pp "br_if" label (Some i)
  | Br_on_null (label, i) -> branch_instr instr pp "br_on_null" label (Some i)
  | Br_on_non_null (label, i) ->
      branch_instr instr pp "br_on_non_null" label (Some i)
  | Br_on_cast (label, ty, i) ->
      branch_ref_instr instr pp "br_on_cast" label ty i
  | Br_on_cast_fail (label, ty, i) ->
      branch_ref_instr instr pp "br_on_cast_fail" label ty i
  | Br_on_cast_desc_eq (label, nullable, i, d) ->
      branch_ref_desc_instr instr pp "br_on_cast" label nullable i d
  | Br_on_cast_desc_eq_fail (label, nullable, i, d) ->
      branch_ref_desc_instr instr pp "br_on_cast_fail" label nullable i d
  (* Branch-hinting proposal: [#[likely]] / [#[unlikely]] prefixing the wrapped
     conditional branch. The attribute is a bare prefix so the branch keeps its own
     layout (and stays on the same line: [#[likely] if …]). *)
  | Hinted (h, inner) ->
      branch_hint_attr pp h;
      instr prec pp inner
  | Br_table (labels, i) ->
      let default, cases =
        match List.rev labels with
        | default :: rev_cases -> (default, List.rev rev_cases)
        | [] -> assert false
      in
      box pp ~indent:indent_level (fun () ->
          bracketed_labels pp
            ~before:(fun () ->
              keyword pp "br_table";
              space pp ())
            cases default;
          space pp ();
          instr Branch pp i)
  | Dispatch { index; cases; default; arms } ->
      hvbox pp (fun () ->
          (* Head: [dispatch <index> [ <labels> else <default> ] {], laid out on
             one line or, when too wide, as
                 dispatch <index> [
                     <labels, filled and indented>
                 ] {
             with the [']'] dedented to the [dispatch] column (see
             [bracketed_labels]). *)
          bracketed_labels pp
            ~before:(fun () ->
              keyword pp "dispatch";
              space pp ();
              (* Parenthesise a non-atomic index: the following '[' would
                 otherwise bind to the index's last atom as an array access. *)
              instr Atom pp index;
              space pp ())
            ~after:(fun () ->
              space pp ();
              punctuation pp "{")
            cases default;
          if arms <> [] then (
            indent pp indent_level (fun () ->
                List.iter
                  (fun (l, body) ->
                    newline pp ();
                    block pp (Some l) None
                      { params = [||]; results = [||] }
                      body)
                  arms);
            newline pp ());
          punctuation pp "}")
  | Match { scrutinee; arms; default } ->
      let arm pat_printer body =
        newline pp ();
        hvbox pp (fun () ->
            box pp (fun () ->
                pat_printer ();
                space pp ();
                punctuation pp "=>";
                space pp ();
                punctuation pp "{");
            let after = located_block_contents pp body in
            close_block pp after)
      in
      hvbox pp (fun () ->
          box pp (fun () ->
              keyword pp "match";
              space pp ();
              (* Parenthesise a non-atomic scrutinee: the following '{' would
                 otherwise read as a struct/block continuation. *)
              instr Atom pp scrutinee;
              space pp ();
              punctuation pp "{");
          indent pp indent_level (fun () ->
              List.iter
                (fun (pat, body) -> arm (fun () -> match_pattern pp pat) body)
                arms;
              (* The default arm is compulsory, so always print it. *)
              arm (fun () -> operator pp "_") default);
          newline pp ();
          punctuation pp "}")
  | Return i ->
      box pp ~indent:indent_level (fun () ->
          keyword pp "return";
          Option.iter
            (fun i ->
              space pp ();
              instr Branch pp i)
            i)
  | Throw (tag, args) ->
      (* Call-like: [throw tag(x, y)]. *)
      hvbox pp (fun () ->
          hbox pp (fun () ->
              keyword pp "throw";
              space pp ();
              identifier pp tag.desc);
          print_arg_list (instr Instruction) pp args)
  | ThrowRef i ->
      box pp ~indent:indent_level (fun () ->
          keyword pp "throw_ref";
          space pp ();
          instr Branch pp i)
  | ContNew (ct, i) -> cont_construct_instr instr pp ct "new" [ i ]
  (* The source continuation type is inferred from the last operand's static
     type, so only the destination — the namespace — is written. *)
  | ContBind (_, dst, l) -> cont_construct_instr instr pp dst "bind" l
  | Suspend (tag, l) ->
      box pp ~indent:indent_level (fun () ->
          keyword pp "suspend";
          space pp ();
          identifier pp tag.desc;
          cut pp ();
          print_paren_list (instr Instruction) pp l)
  (* The type immediate of the resume family and [switch] is inferred from the
     receiver's static type, so it is not written. *)
  | Resume (_, handlers, l) ->
      cont_method_instr instr pp "resume" l
        ~args:(List.map (fun a pp -> instr Instruction pp a) (drop_last l))
        ~handlers
  | ResumeThrow (_, tag, handlers, l) ->
      (* The tag is invoked with its payload, [c.resume_throw(exc(p))], exactly
         as [throw exc(p)] spells it. *)
      cont_method_instr instr pp "resume_throw" l
        ~args:
          [
            (fun pp ->
              box pp ~indent:indent_level (fun () ->
                  identifier pp tag.desc;
                  print_arg_list (instr Instruction) pp (drop_last l)));
          ]
        ~handlers
  | ResumeThrowRef (_, handlers, l) ->
      cont_method_instr instr pp "resume_throw_ref" l
        ~args:(List.map (fun a pp -> instr Instruction pp a) (drop_last l))
        ~handlers
  | Switch (_, tag, l) ->
      cont_method_instr instr pp "switch" l
        ~args:
          (List.map (fun a pp -> instr Instruction pp a) (drop_last l)
          @ [
              (fun pp ->
                print_key_value pp "tag"
                  (fun pp (t : ident) -> identifier pp t.desc)
                  tag);
            ])
        ~handlers:[]
  | On (i, handlers) ->
      box pp ~indent:indent_level (fun () ->
          instr Cast pp i;
          space pp ();
          keyword pp "on";
          space pp ();
          print_on_clauses pp handlers)
  | Sequence l -> print_paren_list (instr Instruction) pp l
  | Select (i1, i2, i3) ->
      box pp ~indent:indent_level (fun () ->
          instr Comparison pp i1;
          cut pp ();
          operator pp "?";
          instr Assignement pp i2;
          cut pp ();
          operator pp ":";
          instr Assignement pp i3)
  | Null -> keyword pp "null"

(* A struct-literal field. A punned field ([None], written [{x}]) prints as the
   bare name; an explicit field prints as [name: value]. *)
and struct_field_kv pp (nm, i) =
  match i with
  | None -> identifier pp nm.desc
  | Some i -> print_key_value pp nm.desc (instr Instruction) i

and field_receiver pp i =
  (* A bare numeric literal receiver would be misparsed: [0.foo] lexes [0.]
     as a float, so parenthesize it. *)
  match i.desc with
  | Int _ | Float _ ->
      punctuation pp "(";
      box pp (fun () ->
          instr Instruction pp i;
          punctuation pp ")")
  | _ -> instr CallAndFieldAccess pp i

and block pp label kind bt (l : (_ instr list, location) annotated) =
  hvbox pp (fun () ->
      box pp (fun () ->
          block_label pp label;
          Option.iter
            (fun kind ->
              keyword pp kind;
              space pp ())
            kind;
          if need_blocktype bt then (
            blocktype pp bt;
            space pp ());
          punctuation pp "{");
      let after = located_block_contents pp l in
      close_block pp after)

and deliminated_instr pp (i : _ instr) =
  if is_block i then instr Instruction pp i
  else (
    instr (if starts_with_block i then Atom else Instruction) pp i;
    (* Hold any deferred trailing comment so the [;] prints on the statement's
       line, ahead of the comment ([expr; // c] rather than [expr // c] then a
       lone [;] on the next line). *)
    Wax_utils.Printer.with_held_eol pp.base.printer (fun () ->
        punctuation pp ";"))

and block_contents pp (l : _ instr list) =
  (* A non-empty block always breaks across lines (rustfmt never keeps a block
     body on one line), so every separator here is a hard [newline]; the
     enclosing box then lays the body out vertically. An empty block stays
     [{}]. *)
  if l <> [] then (
    indent pp indent_level (fun () ->
        List.iter
          (fun i ->
            newline pp ();
            deliminated_instr pp i)
          l);
    newline pp ())

(* Print the contents of a brace-delimited block, looking the block's own
   location up so a comment opening the clause attaches here rather than to the
   condition, and so an own-line comment trailing the last statement ([within]
   the block's span) renders *inside* the block at the statement indentation.
   [before] precedes the body; [within] closes it. The block's [after] (comments
   past the closing [}]) is *returned*, not printed, so the caller can emit it on
   the far side of the [}] — mirroring the WAT printer, where [within] prints
   before the closing [)] and [after] after it. *)
and located_block_contents pp (b : (_ instr list, location) annotated) =
  let assoc = get_trivia pp (Some b.info) in
  print_trivia pp assoc.before;
  if b.desc <> [] || assoc.within <> [] then (
    indent pp indent_level (fun () ->
        List.iter
          (fun i ->
            newline pp ();
            deliminated_instr pp i)
          b.desc;
        print_trivia pp assoc.within);
    newline pp ());
  assoc.after

(* Emit a block's closing [}] followed by the trailing comments [located_block_contents]
   returned, so a comment anchored past the [}] renders after it (and, before an
   [else]/[catch] continuation, back between the [}] and that keyword — where it
   was written). *)
and close_block pp after =
  punctuation pp "}";
  print_trivia pp after

(*** Declarations, attributes, and module fields ***)

let fundecl ?(exact = false) ~tag pp (name, typ, sign) =
  (* The whole signature is one all-or-nothing group anchored at the [fn]
     column: [fn name] stays glued (its own [hbox]) and so does [-> Ret], so the
     only thing that can break — when [fn name(params) -> Ret] overflows — is
     the parameter list, which then lays out one parameter per line. *)
  hvbox pp (fun () ->
      hbox pp (fun () ->
          keyword pp (if tag then "tag" else "fn");
          space pp ();
          identifier pp name.desc;
          (* An exact declaration with an inline signature marks the name
             ([fn f!(…)]); with a named type the marker hugs the type
             ([fn f: !t]). *)
          if exact && Option.is_none typ then punctuation pp "!";
          Option.iter
            (fun typ ->
              punctuation pp ":";
              space pp ();
              if exact then punctuation pp "!";
              identifier pp typ.desc;
              space pp ())
            typ);
      Option.iter (fun ty -> raw_functype pp ty) sign)

let print_attribute_gen open_ pp (name, i, guard) =
  box pp ~indent:indent_level (fun () ->
      attribute pp open_;
      attribute pp name;
      (match i with
      | None -> ()
      | Some i ->
          space pp ();
          attribute pp "=";
          space pp ();
          with_style pp Attribute (fun () -> instr Instruction pp i));
      (* A per-attribute guard, [#[export = "n", if(<cond>)]]. *)
      (match guard with
      | None -> ()
      | Some c ->
          attribute pp ",";
          space pp ();
          attribute pp (Printf.sprintf "if(%s)" (cond_to_string c.desc)));
      attribute pp "]")

let print_attribute pp a = print_attribute_gen "#[" pp a

(* Module-level inner attribute: [#![module = "name"]]. *)
let print_inner_attribute pp a = print_attribute_gen "#![" pp a

(* Separate attributes at this (enclosing) level rather than with a trailing
   space inside each attribute's box: a break between them then lands at the
   enclosing box's indentation, so stacked attributes stay aligned instead of
   each indenting relative to the previous one's box. *)
let print_attributes pp attributes =
  List.iteri
    (fun i a ->
      if i > 0 then space pp ();
      print_attribute pp a)
    attributes

let print_attr_prefix pp attributes_list content_fn =
  hvbox pp (fun () ->
      if attributes_list <> [] then (
        print_attributes pp attributes_list;
        newline pp ());
      content_fn ())

let print_data_bytes pp s =
  let len, s = Wax_utils.Unicode.escape_string ~hex_prefix:"x" s in
  string pp "\"";
  string pp ~len:(Some len) s;
  string pp "\""

let vec_shape_name : Wax_utils.V128.shape -> string = function
  | I8x16 -> "i8x16"
  | I16x8 -> "i16x8"
  | I32x4 -> "i32x4"
  | I64x2 -> "i64x2"
  | F32x4 -> "f32x4"
  | F64x2 -> "f64x2"

(* A data numeric run [[head: e1, e2, …]]: kept in one indented box so it lays
   out inline when it fits and, when it overflows, breaks after the [:] with its
   values indented under the [[] rather than splitting the run head. Laid out
   exactly like an array literal (see [array_instr]): inline when it fits;
   otherwise one value per line with a trailing comma and the [\]] dedented on
   its own line — differing only in the [type:] head (vs an array's [type|]). *)
let print_run pp head print_elem elems =
  hvbox pp ~indent:0 (fun () ->
      box pp (fun () ->
          punctuation pp "[";
          type_ pp head;
          punctuation pp ":");
      indent pp indent_level (fun () ->
          space pp ();
          list_commasep_trailing print_elem pp elems);
      cut pp ();
      punctuation pp "]")

(* One lane group of a [v128] run: [i32x4(1, 2, 3, 4)]. *)
let print_v128_group pp (v : (Wax_utils.V128.t, _) Ast.annotated) =
  type_ pp (vec_shape_name v.desc.shape);
  punctuation pp "(";
  box pp (fun () ->
      list_commasep (fun pp c -> constant pp c) pp v.desc.components);
  punctuation pp ")"

(* A data segment's contents: constant elements (string literals, numeric runs
   [[i16: …]], [v128] runs) concatenated with [++]. Only called for a
   non-empty segment; an empty one omits the [= …] entirely (see callers). *)
let print_data_elem pp = function
  | Ast.Data_string s -> print_data_bytes pp s
  | Ast.Data_run (st, values) ->
      print_run pp (suffix_string st)
        (fun pp (v : (string, _) Ast.annotated) -> constant pp v.desc)
        values
  | Ast.Data_v128 vs -> print_run pp "v128" print_v128_group vs

let print_data_init pp init =
  box pp ~indent:indent_level (fun () ->
      match init with
      | [] -> ()
      | first :: rest ->
          print_data_elem pp first;
          List.iter
            (fun e ->
              (* Fold like a binary operator (see [BinOp]): break *before*
                 [++], which then leads its continuation line; the space after
                 it never breaks. *)
              space pp ();
              operator pp "++";
              Wax_utils.Printer.string pp.base.printer " ";
              print_data_elem pp e)
            rest)

let print_data_name pp n =
  match n with
  | Some (n : ident) -> identifier pp n.desc
  | None -> punctuation pp "_"

let simple_inline_instr (i : _ Ast.instr) =
  match i.desc with
  | Get _ | Path _ | Char _ | String _ | Int _ | Float _ -> true
  | _ -> false

let print_square_instr ?(leading_space = false) pp i =
  if simple_inline_instr i then (
    if leading_space then space pp ();
    punctuation pp "[";
    instr Instruction pp i;
    punctuation pp "]")
  else (
    if leading_space then
      hbox pp (fun () ->
          space pp ();
          punctuation pp "[")
    else punctuation pp "[";
    indent pp indent_level (fun () ->
        newline pp ();
        instr Instruction pp i);
    newline pp ();
    punctuation pp "]")

let print_square_instr_list ?(multiline = false) pp l =
  if not multiline then (
    punctuation pp "[";
    box pp (fun () -> list_commasep (fun pp i -> instr Instruction pp i) pp l);
    punctuation pp "]")
  else (
    punctuation pp "[";
    indent pp indent_level (fun () ->
        newline pp ();
        list_commasep (fun pp i -> instr Instruction pp i) pp l);
    newline pp ();
    punctuation pp "]")

let print_offset_brackets pp off = print_square_instr ~leading_space:true pp off

let print_targeted_offset pp target off =
  hbox pp (fun () ->
      space pp ();
      operator pp "@";
      space pp ();
      identifier pp target.desc);
  print_offset_brackets pp off

let print_eq_square_instr_list pp l =
  hbox pp (fun () ->
      space pp ();
      punctuation pp "=";
      space pp ());
  print_square_instr_list ~multiline:(List.length l > 3) pp l

let print_memdata pp (d : _ Ast.memdata) =
  box pp ~indent:indent_level (fun () ->
      hbox pp (fun () ->
          keyword pp "data";
          space pp ();
          print_data_name pp d.data_name;
          space pp ();
          operator pp "@");
      print_offset_brackets pp d.offset;
      if d.init <> [] then (
        hbox pp (fun () ->
            space pp ();
            punctuation pp "=");
        space pp ();
        print_data_init pp d.init);
      punctuation pp ";")

let print_limits pp limits =
  Option.iter
    (fun (mi, ma) ->
      space pp ();
      punctuation pp "[";
      constant pp (Wax_utils.Uint64.to_string mi);
      Option.iter
        (fun m ->
          punctuation pp ",";
          space pp ();
          constant pp (Wax_utils.Uint64.to_string m))
        ma;
      punctuation pp "]")
    limits

(* Print one entry of an [import "module" { ... }] block: its attributes and an
   [#[import = "name"]] override (when it is imported under a name other than
   its own), then the declaration itself. *)
let print_import_decl pp (decl : Ast.import_decl) =
  print_attr_prefix pp decl.attributes (fun () ->
      box pp (fun () ->
          (match decl.kind with
          | Import_func { typ; sign; exact } ->
              fundecl ~exact ~tag:false pp (decl.id, typ, sign)
          | Import_tag { typ; sign } -> fundecl ~tag:true pp (decl.id, typ, sign)
          | Import_global { mut; typ } ->
              keyword pp (if mut then "let" else "const");
              space pp ();
              identifier pp decl.id.desc;
              punctuation pp ":";
              space pp ();
              valtype pp typ
          | Import_memory { address_type; limits; page_size_log2; shared } ->
              keyword pp "memory";
              space pp ();
              identifier pp decl.id.desc;
              punctuation pp ":";
              space pp ();
              keyword pp
                (match address_type with `I32 -> "i32" | `I64 -> "i64");
              print_limits pp limits;
              Option.iter
                (fun p ->
                  space pp ();
                  keyword pp "pagesize";
                  space pp ();
                  constant pp (Int64.to_string (Int64.shift_left 1L p)))
                page_size_log2;
              if shared then (
                space pp ();
                keyword pp "shared")
          | Import_table { address_type; reftype = rt; limits } ->
              keyword pp "table";
              space pp ();
              identifier pp decl.id.desc;
              punctuation pp ":";
              space pp ();
              (match address_type with
              | `I32 -> ()
              | `I64 ->
                  keyword pp "i64";
                  space pp ());
              reftype pp rt;
              print_limits pp limits);
          semicolon pp))

let rec modulefield pp field =
  atomic_node pp (Some field.info) @@ fun () ->
  match field.desc with
  | Type t -> rectype pp t
  | Module_annotation attrs ->
      hvbox pp (fun () ->
          List.iteri
            (fun i a ->
              if i > 0 then space pp ();
              print_inner_attribute pp a)
            attrs)
  | Func { name; typ; sign; body = label, body; attributes = a } ->
      print_attr_prefix pp a (fun () ->
          hvbox pp (fun () ->
              box pp (fun () ->
                  fundecl ~tag:false pp (name, typ, sign);
                  (* Glue the opening [{] to the signature so [fundecl] counts
                     it when deciding whether to break the parameter list;
                     otherwise a signature one or two columns too long leaves
                     [{] stranded on its own line instead. *)
                  hbox pp (fun () ->
                      space pp ();
                      block_label pp label;
                      punctuation pp "{"));
              block_contents pp body;
              punctuation pp "}"))
  | Global { name; mut; typ; def; attributes = a } ->
      print_attr_prefix pp a (fun () ->
          box pp ~indent:indent_level (fun () ->
              keyword pp (if mut then "let" else "const");
              space pp ();
              identifier pp name.desc;
              Option.iter
                (fun t ->
                  punctuation pp ":";
                  space pp ();
                  valtype pp t)
                typ;
              space pp ();
              punctuation pp "=";
              space pp ();
              instr Instruction pp def;
              semicolon pp))
  | Tag { name; typ; sign; attributes = a } ->
      print_attr_prefix pp a (fun () ->
          box pp (fun () ->
              fundecl ~tag:true pp (name, typ, sign);
              semicolon pp))
  | Memory
      {
        name;
        address_type;
        limits;
        page_size_log2;
        shared;
        data;
        attributes = a;
      } ->
      print_attr_prefix pp a (fun () ->
          hvbox pp (fun () ->
              box pp (fun () ->
                  keyword pp "memory";
                  space pp ();
                  identifier pp name.desc;
                  punctuation pp ":";
                  space pp ();
                  keyword pp
                    (match address_type with `I32 -> "i32" | `I64 -> "i64");
                  Option.iter
                    (fun (mi, ma) ->
                      space pp ();
                      punctuation pp "[";
                      constant pp (Wax_utils.Uint64.to_string mi);
                      Option.iter
                        (fun m ->
                          punctuation pp ",";
                          space pp ();
                          constant pp (Wax_utils.Uint64.to_string m))
                        ma;
                      punctuation pp "]")
                    limits;
                  Option.iter
                    (fun p ->
                      space pp ();
                      keyword pp "pagesize";
                      space pp ();
                      constant pp (Int64.to_string (Int64.shift_left 1L p)))
                    page_size_log2;
                  if shared then (
                    space pp ();
                    keyword pp "shared"));
              match data with
              | [] -> semicolon pp
              | _ ->
                  hbox pp (fun () ->
                      space pp ();
                      punctuation pp "{");
                  indent pp indent_level (fun () ->
                      List.iter
                        (fun d ->
                          space pp ();
                          print_memdata pp d)
                        data);
                  space pp ();
                  punctuation pp "}"))
  | Data { name; mode; init; attributes = a } ->
      print_attr_prefix pp a (fun () ->
          box pp ~indent:indent_level (fun () ->
              hbox pp (fun () ->
                  keyword pp "data";
                  space pp ();
                  print_data_name pp name);
              (match mode with
              | Passive -> ()
              | Active (mem, off) -> print_targeted_offset pp mem off);
              if init <> [] then (
                hbox pp (fun () ->
                    space pp ();
                    punctuation pp "=");
                space pp ();
                print_data_init pp init);
              semicolon pp))
  | Table { name; address_type; reftype = rt; limits; init; attributes = a } ->
      print_attr_prefix pp a (fun () ->
          box pp ~indent:indent_level (fun () ->
              hbox pp (fun () ->
                  keyword pp "table";
                  space pp ();
                  identifier pp name.desc;
                  punctuation pp ":";
                  space pp ();
                  (match address_type with
                  | `I32 -> ()
                  | `I64 ->
                      keyword pp "i64";
                      space pp ());
                  reftype pp rt;
                  Option.iter
                    (fun (mi, ma) ->
                      space pp ();
                      punctuation pp "[";
                      constant pp (Wax_utils.Uint64.to_string mi);
                      Option.iter
                        (fun m ->
                          punctuation pp ",";
                          space pp ();
                          constant pp (Wax_utils.Uint64.to_string m))
                        ma;
                      punctuation pp "]")
                    limits);
              Option.iter
                (fun e ->
                  hbox pp (fun () ->
                      space pp ();
                      punctuation pp "=");
                  space pp ();
                  instr Instruction pp e)
                init;
              semicolon pp))
  | Elem { name; reftype = rt; mode; init; attributes = a } ->
      print_attr_prefix pp a (fun () ->
          box pp ~indent:indent_level (fun () ->
              hbox pp (fun () ->
                  keyword pp "elem";
                  space pp ();
                  identifier pp name.desc;
                  punctuation pp ":";
                  space pp ();
                  reftype pp rt);
              (match mode with
              | EPassive -> ()
              | EActive (tab, off) -> print_targeted_offset pp tab off);
              print_eq_square_instr_list pp init;
              semicolon pp))
  | Import { module_; decl } ->
      box pp (fun () ->
          keyword pp "import";
          space pp ();
          print_data_bytes pp module_.desc;
          space pp ();
          print_import_decl pp decl.desc)
  | Import_group { module_; decls } ->
      hvbox pp (fun () ->
          box pp (fun () ->
              keyword pp "import";
              space pp ();
              print_data_bytes pp module_.desc;
              space pp ();
              punctuation pp "{");
          (* Like any brace-delimited block (see [block_contents]), a non-empty
             import group always lays its declarations out vertically, one per
             line; an empty group stays [{}]. *)
          if decls <> [] then (
            indent pp indent_level (fun () ->
                List.iter
                  (fun d ->
                    newline pp ();
                    print_import_decl pp d.desc)
                  decls);
            newline pp ());
          punctuation pp "}")
  | Conditional { cond; then_fields; else_fields } ->
      (* Braces are mandatory; a branch is a located field list. Like a block
         body (see [located_block_contents]), a non-empty branch always breaks
         across lines — hard [newline]s, so the [{] and each field land on their
         own line even for a short branch — and an own-line comment trailing its
         last field renders inside it. *)
      let branch b =
        space pp ();
        punctuation pp "{";
        let assoc = get_trivia pp (Some b.info) in
        print_trivia pp assoc.before;
        if b.desc <> [] || assoc.within <> [] then (
          indent pp indent_level (fun () ->
              List.iter
                (fun f ->
                  newline pp ();
                  modulefield pp f)
                b.desc;
              print_trivia pp assoc.within);
          newline pp ());
        close_block pp assoc.after
      in
      hvbox pp (fun () ->
          attribute pp (Printf.sprintf "#[if(%s)]" (cond_to_string cond));
          branch then_fields;
          Option.iter
            (fun e ->
              newline pp ();
              attribute pp "#[else]";
              branch e)
            else_fields)

(*** Entry points ***)

let module_ ?(color = Auto) ?out_channel ?(tail = []) ?collect printer ~trivia
    (l : location module_) =
  (* [collect] marks the dry trivia-collection traversal; time the real emit
     only, so a single "output" timing is reported. *)
  Wax_utils.Debug.timed_if (collect = None) "output" @@ fun () ->
  let use_color = should_use_color ~color ~out_channel in
  let theme = get_theme use_color in
  let pp =
    {
      base = Wax_utils.Styled_printer.create ~printer ~theme ?collect ~trivia ();
      locate = (fun l -> Some l);
    }
  in
  hvbox pp (fun () -> list ~sep:space modulefield pp l);
  (* Trailing comments owned by no node. Drop trailing blank lines so the file
     does not end with spurious blank lines. *)
  let tail = Wax_utils.Trivia.drop_trailing_blank_lines tail in
  print_trivia pp tail

(* Context for printing AST fragments in diagnostics: no trivia, no location
   lookup, colour decided from [stderr]. *)
let diagnostic_ctx printer =
  let use_color = should_use_color ~color:Auto ~out_channel:(Some stderr) in
  let theme = get_theme use_color in
  {
    base =
      Wax_utils.Styled_printer.create ~printer ~theme ~trivia:(Hashtbl.create 0)
        ();
    locate = (fun _ -> None);
  }

(* Render an AST fragment into a caller-supplied styled printer — used to embed a
   type in a diagnostic [Message], so it shares the message's colour theme and
   width (unlike [diagnostic_ctx], which sniffs [stderr]). No trivia, no location
   lookup. Defined before the [Printer.t]-taking entries below shadow [valtype]
   / [comptype] with the diagnostic-context wrappers. *)
let styled_ctx base = { base; locate = (fun _ -> None) }
let valtype_styled base i = valtype (styled_ctx base) i
let comptype_styled base i = comptype (styled_ctx base) i
let instr printer i = instr Instruction (diagnostic_ctx printer) i
let valtype printer i = valtype (diagnostic_ctx printer) i
let comptype printer i = comptype (diagnostic_ctx printer) i
let storagetype printer i = storagetype (diagnostic_ctx printer) i
let fieldtype printer i = fieldtype (diagnostic_ctx printer) i
let subtype printer field = subtype (diagnostic_ctx printer) field