fig 4.0.0

Parse, edit, and convert config files while preserving comments. Supports JSON, YAML, TOML, and more.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
//! Languages resolved at runtime: the [`Language`] trait, the node table its
//! `parse` returns, and [`register`], which carries an implementation to the
//! core as a vtable and hands back a [`Format`] that every entry point of
//! this crate then accepts.
//!
//! This is the in-process carrier of the core's runtime-language contract
//! (`docs/proposals/runtime-languages.md`): the same declarations a compiled
//! format makes, as a [`Description`]; the same parse result, as a
//! [`NodeTable`]; the same fragment renderers, as [`Language::render`]. The
//! core validates the description by the rules it holds its own formats to,
//! runs its harness over the `samples` the description declares — each is
//! parsed, printed, reparsed and edited — and only then registers the
//! language. A description that fails either is refused with the reason in
//! [`Error::Language`] and registers nothing.
//!
//! The out-of-process carrier — the same calls as JSON over a child
//! process's stdio — is [`crate::helper`], which serves any [`Language`] to
//! a `fig` binary and is what a helper written against this crate speaks.
//!
//! A registered language lives for the rest of the process: there is no
//! unregistration, and the [`Format`] it returns is valid until exit. Its
//! integer is per process; persist the name and resolve it with
//! [`Format::by_name`].

use std::ffi::{CString, c_void};
use std::os::raw::{c_char, c_int};
use std::panic::{AssertUnwindSafe, catch_unwind};

use crate::ffi;
use crate::{Capabilities, Error, ExtKind, Format, RuntimeFormat, Span};

// ── the description ────────────────────────────────────────────────────────

/// What a language declares: the `Language` declarations of a compiled
/// format, as data. See the core's `manifest.zig` for what each field means
/// to the editor; the doc on each here says what it is, not why.
///
/// This and the structs it holds are plain, constructible records — build
/// them with `..Default::default()` (or [`Description::new`]), since the
/// contract gains fields as the core's does.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Description {
    /// The language's name; also its first dialect's.
    pub name: String,
    /// What it can do. `read` is required.
    pub caps: Capabilities,
    /// How deep a mapping may nest, or `None` for unbounded. `Some(0)` is a
    /// flat format (dotenv), `Some(1)` a root mapping and one level of
    /// sections (INI).
    pub max_mapping_depth: Option<u8>,
    /// Which kinds the format holds natively — what the `$fig` lossless
    /// envelope need not wrap — or `None` for no envelope at all. Requires
    /// `caps.serialize`.
    pub lossless: Option<NativeKinds>,
    /// What the splice engine needs to write this format. Required iff
    /// `caps.edit`.
    pub syntax: Option<Syntax>,
    /// At least one; the first is named after the language.
    pub dialects: Vec<Dialect>,
    /// Small documents in the format's own grammar. Required, and at least
    /// one: registration checks the language against them.
    pub samples: Vec<String>,
    /// Which fragment renderers [`Language::render`] answers. A renderer
    /// declared here and not answered is a failed edit; one answered and not
    /// declared is never called.
    pub renderers: Renderers,
}

impl Description {
    /// A description with `name` and one dialect of the same name; fill the
    /// rest with the builder-style methods or directly.
    pub fn new(name: &str) -> Self {
        Description {
            name: name.to_owned(),
            caps: Capabilities::default(),
            dialects: vec![Dialect::new(name)],
            ..Default::default()
        }
    }
}

impl Default for Capabilities {
    fn default() -> Self {
        Capabilities::new(true, false, false)
    }
}

/// One dialect of a language.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Dialect {
    /// The name every entry point resolves it by.
    pub name: String,
    /// File extensions, without the dot.
    pub extensions: Vec<String>,
    /// How edit text is taken.
    pub splice: Splice,
    /// What `set` writes to a file that does not exist yet; `None` refuses
    /// creation. The empty string means an empty file already parses.
    pub empty_doc_seed: Option<String>,
    /// This dialect's own syntax where it differs from the language's.
    pub syntax: Option<Syntax>,
}

impl Dialect {
    pub fn new(name: &str) -> Self {
        Dialect {
            name: name.to_owned(),
            extensions: Vec::new(),
            splice: Splice::Literal,
            empty_doc_seed: None,
            syntax: None,
        }
    }
}

/// How a dialect takes spliced edit text.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Splice {
    /// As written.
    #[default]
    Literal,
    /// As a JSON string.
    JsonString,
    /// Raw bytes, no quoting.
    Raw,
}

/// Which kinds a format holds natively. One field per [`ExtKind`], plus null.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct NativeKinds {
    pub null: bool,
    pub offset_datetime: bool,
    pub local_datetime: bool,
    pub local_date: bool,
    pub local_time: bool,
    pub enum_literal: bool,
    pub char_literal: bool,
    pub number_special: bool,
    pub plist_date: bool,
    pub plist_data: bool,
}

/// Which renderers a language answers.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Renderers {
    pub value: bool,
    pub entry: bool,
    pub item: bool,
    pub tail: bool,
    pub key: bool,
}

/// The surface syntax the splice engine writes a format with. Every field
/// is the core's `manifest.Syntax` field of the same name.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Syntax {
    pub comments: Comments,
    /// The key/value separator the engine writes, or `None` when it never
    /// writes `key<sep>value` for this format — which requires an `entry`
    /// renderer.
    pub kv_sep: Option<String>,
    pub flow_kv_sep_from_siblings: bool,
    pub flow_map_pad: String,
    pub key_style: KeyStyle,
    /// A byte every key starts with.
    pub key_sigil: Option<u8>,
    pub empty_map_literal: Option<String>,
    pub block_seq_editable: bool,
    pub flow_containers: bool,
    pub indent_unit: String,
    pub seq_item_marker: String,
    pub closed_containers: Option<ClosedContainers>,
    pub single_line_block_mapping: bool,
    pub bare_document_mapping: bool,
    pub flow_map_open: String,
    pub flow_map_close: String,
    pub structural_indent: bool,
    pub section_noun: Option<SectionNoun>,
    pub section_header: Option<SectionHeader>,
    pub merge_key: Option<String>,
}

impl Default for Syntax {
    /// The core's defaults: `#` comments, `: ` separator is NOT assumed (set
    /// `kv_sep`), two-space indent, `- ` items, `{`/`}` flow maps.
    fn default() -> Self {
        Syntax {
            comments: Comments::hash(),
            kv_sep: None,
            flow_kv_sep_from_siblings: false,
            flow_map_pad: String::new(),
            key_style: KeyStyle::Verbatim,
            key_sigil: None,
            empty_map_literal: None,
            block_seq_editable: true,
            flow_containers: true,
            indent_unit: "  ".to_owned(),
            seq_item_marker: "- ".to_owned(),
            closed_containers: None,
            single_line_block_mapping: false,
            bare_document_mapping: true,
            flow_map_open: "{".to_owned(),
            flow_map_close: "}".to_owned(),
            structural_indent: false,
            section_noun: None,
            section_header: None,
            merge_key: None,
        }
    }
}

/// A format's comment surface.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Comments {
    pub style: CommentStyle,
    /// The own-line delimiter, or `None` for a format with no comments.
    pub line: Option<CommentDelimiter>,
    /// The same-line trailing delimiter, or `None` where a marker after a
    /// value is value text.
    pub trailing: Option<CommentDelimiter>,
}

impl Comments {
    /// `#` throughout.
    pub fn hash() -> Self {
        Comments {
            style: CommentStyle::Hash,
            line: Some(CommentDelimiter::open("#")),
            trailing: Some(CommentDelimiter::open("#")),
        }
    }
    /// `//` throughout.
    pub fn slashes() -> Self {
        Comments {
            style: CommentStyle::Slashes,
            line: Some(CommentDelimiter::open("//")),
            trailing: Some(CommentDelimiter::open("//")),
        }
    }
    /// No comment syntax at all.
    pub fn none() -> Self {
        Comments {
            style: CommentStyle::Hash,
            line: None,
            trailing: None,
        }
    }
}

/// Which owned-comment-block scanner walks the format.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum CommentStyle {
    #[default]
    Hash,
    Slashes,
    Semicolon,
    XmlComment,
}

/// How one comment is delimited.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CommentDelimiter {
    pub open: String,
    /// Empty for an unpaired delimiter.
    pub close: String,
    /// Text a comment body may not contain.
    pub forbidden: Option<String>,
}

impl CommentDelimiter {
    pub fn open(open: &str) -> Self {
        CommentDelimiter {
            open: open.to_owned(),
            close: String::new(),
            forbidden: None,
        }
    }
    pub fn pair(open: &str, close: &str) -> Self {
        CommentDelimiter {
            open: open.to_owned(),
            close: close.to_owned(),
            forbidden: None,
        }
    }
}

/// How a logical key renders into the format's key syntax on insert.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum KeyStyle {
    #[default]
    Verbatim,
    JsonQuoted,
    ZonField,
    BareOrQuoted,
}

/// What a section format calls its scattered container.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SectionNoun {
    Table,
    Section,
    Container,
}

/// How a section format spells a header line.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SectionHeader {
    pub open: String,
    pub close: String,
    pub seq_open: Option<String>,
    pub seq_close: Option<String>,
    pub sep: String,
    pub skip_index: bool,
}

/// The self-closing spellings of an empty block container.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ClosedContainers {
    pub map_open: String,
    pub map_close: String,
    pub seq_open: String,
    pub seq_close: String,
}

// ── the node table ─────────────────────────────────────────────────────────

/// What a parse returns and a print receives: one [`NodeRow`] per node in
/// pre-order — row index is node id, a parent precedes its children, a
/// keyvalue is followed by its key row and then its value row — plus four
/// side tables. It is the shape the core's `Document` holds, as values.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct NodeTable {
    pub rows: Vec<NodeRow>,
    pub regions: Vec<RegionRow>,
    pub mentions: Vec<MentionRow>,
    pub comments: Vec<CommentRow>,
    /// The document's tag-handle declarations, in source order. A parse
    /// returns those it read; a print of a whole document — never of a
    /// fragment — receives them back, to re-emit above any tag that uses
    /// one. Empty for a format without directives.
    pub directives: Vec<DirectiveRow>,
}

impl NodeTable {
    pub fn new() -> Self {
        Self::default()
    }

    /// Append a row and return its index — the id a child names as
    /// `parent`.
    pub fn push(&mut self, row: NodeRow) -> u32 {
        self.rows.push(row);
        (self.rows.len() - 1) as u32
    }
}

/// One node.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct NodeRow {
    pub kind: NodeKind,
    /// A format-specific scalar's kind; the row's `kind` is then what
    /// `fig_node_kind` would report (`String`, or `Int` for a char literal).
    pub ext_kind: Option<ExtKind>,
    /// `None` on the root only.
    pub parent: Option<u32>,
    /// Required of every row a parse returns; `None` in a table built for
    /// print, where there is no source.
    pub span: Option<Span>,
    /// A scalar's decoded text; an int or float's lexeme; `true`/`false`
    /// for a bool; an alias's target anchor name; an extended kind's
    /// payload. `None` for a container or a null.
    pub text: Option<String>,
    /// The anchor this row defines, and where the `&name` token is.
    pub anchor: Option<String>,
    pub anchor_span: Option<Span>,
    /// The tag on this row, verbatim, and where it is written.
    pub tag: Option<String>,
    pub tag_span: Option<Span>,
    /// For a block-sequence item: the span of the `-`/`*` introducing it.
    pub marker: Option<Span>,
    /// For a keyvalue: the span of the token separating key from value. A
    /// zero-width span marks a value hanging under a bare key.
    pub sep: Option<Span>,
}

impl NodeRow {
    /// A row of `kind` under `parent` covering `span`, with nothing else.
    pub fn new(kind: NodeKind, parent: Option<u32>, span: Span) -> Self {
        NodeRow {
            kind,
            ext_kind: None,
            parent,
            span: Some(span),
            text: None,
            anchor: None,
            anchor_span: None,
            tag: None,
            tag_span: None,
            marker: None,
            sep: None,
        }
    }

    pub fn with_text(mut self, text: &str) -> Self {
        self.text = Some(text.to_owned());
        self
    }

    pub fn with_sep(mut self, sep: Span) -> Self {
        self.sep = Some(sep);
        self
    }

    pub fn with_marker(mut self, marker: Span) -> Self {
        self.marker = Some(marker);
        self
    }

    pub fn with_anchor(mut self, name: &str, span: Span) -> Self {
        self.anchor = Some(name.to_owned());
        self.anchor_span = Some(span);
        self
    }

    pub fn with_tag(mut self, tag: &str, span: Span) -> Self {
        self.tag = Some(tag.to_owned());
        self.tag_span = Some(span);
        self
    }

    pub fn with_ext_kind(mut self, kind: ExtKind) -> Self {
        self.ext_kind = Some(kind);
        self
    }
}

/// A row's kind: what `fig_node_kind` reports.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NodeKind {
    Null,
    Bool,
    Int,
    Float,
    String,
    Sequence,
    Mapping,
    KeyValue,
    Alias,
}

impl NodeKind {
    pub(crate) fn to_c(self) -> c_int {
        match self {
            NodeKind::Null => 0,
            NodeKind::Bool => 1,
            NodeKind::Int => 2,
            NodeKind::Float => 3,
            NodeKind::String => 4,
            NodeKind::Sequence => 5,
            NodeKind::Mapping => 6,
            NodeKind::KeyValue => 7,
            NodeKind::Alias => 8,
        }
    }

    pub(crate) fn from_c(v: c_int) -> Option<Self> {
        Some(match v {
            0 => NodeKind::Null,
            1 => NodeKind::Bool,
            2 => NodeKind::Int,
            3 => NodeKind::Float,
            4 => NodeKind::String,
            5 => NodeKind::Sequence,
            6 => NodeKind::Mapping,
            7 => NodeKind::KeyValue,
            8 => NodeKind::Alias,
            _ => return None,
        })
    }
}

/// One whole header line of a section node.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RegionRow {
    pub node: u32,
    pub start: usize,
    pub end: usize,
}

/// One place a section node's name is written.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MentionRow {
    pub node: u32,
    pub span: Span,
    pub kind: MentionKind,
}

/// How a mention sits relative to the node's parent.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MentionKind {
    /// A header line of the node's own.
    Header,
    /// On one of the parent's own entry lines.
    Entry,
}

/// One comment bound to a row.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CommentRow {
    pub node: u32,
    pub slot: CommentSlot,
    pub style: CommentForm,
    pub text: String,
}

/// One tag-handle declaration — a YAML `%TAG` directive's handle (`!e!`,
/// or a redefined `!`/`!!`) and the prefix it expands to. A tag spelled
/// with a named handle is legal only in a document that declares it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DirectiveRow {
    pub handle: String,
    pub prefix: String,
}

/// Where a comment sits on its node.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CommentSlot {
    Leading,
    Trailing,
    Dangling,
}

/// A comment's written form.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CommentForm {
    Line,
    Block,
}

/// What a printer outside the core is told of the serialize options.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PrintOptions {
    pub pretty: bool,
    pub strip_comments: bool,
    pub indent: u8,
    pub width: u16,
}

impl Default for PrintOptions {
    fn default() -> Self {
        PrintOptions {
            pretty: true,
            strip_comments: false,
            indent: 2,
            width: 80,
        }
    }
}

// ── the trait ──────────────────────────────────────────────────────────────

/// A failure a language reports: a message, and where in the input for a
/// parse.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LanguageError {
    pub message: String,
    pub byte_offset: Option<usize>,
}

impl LanguageError {
    pub fn new(message: impl Into<String>) -> Self {
        LanguageError {
            message: message.into(),
            byte_offset: None,
        }
    }
    pub fn at(message: impl Into<String>, byte_offset: usize) -> Self {
        LanguageError {
            message: message.into(),
            byte_offset: Some(byte_offset),
        }
    }
}

impl std::fmt::Display for LanguageError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.byte_offset {
            Some(off) => write!(f, "{} (byte offset {off})", self.message),
            None => f.write_str(&self.message),
        }
    }
}

impl std::error::Error for LanguageError {}

/// The five fragment renderers.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Renderer {
    /// Spell a value in place (plist's typed element).
    Value,
    /// Spell a block-mapping entry past its line's indent.
    Entry,
    /// Spell a block-sequence item past its line's indent.
    Item,
    /// Spell what follows a key: the separator and the value, inline or
    /// re-framed as a block. An empty `key` is the document root.
    Tail,
    /// Spell a renamed key in the form the old one allows.
    Key,
}

impl Renderer {
    pub fn name(self) -> &'static str {
        match self {
            Renderer::Value => "value",
            Renderer::Entry => "entry",
            Renderer::Item => "item",
            Renderer::Tail => "tail",
            Renderer::Key => "key",
        }
    }
}

/// What fig's bare-literal rules make of the text a value renderer is
/// handed: `null`, `true`/`false`, a number, a datetime shape, or a
/// string. The core classifies the text once, trimmed of whitespace, by
/// the `.fig` dialect's own rules (`Yes`, `007` and `TRUE` stay strings),
/// and every format's `set` means the same thing by `42`; a renderer
/// spells the kind it is told. A datetime is a string in the node table
/// and its own answer here, since a renderer spells it differently.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Literal {
    Null,
    Bool,
    Int,
    Float,
    Datetime,
    #[default]
    String,
}

impl Literal {
    /// The name on the vtable and the wire: `null`, `bool`, `int`,
    /// `float`, `datetime`, `string`.
    pub fn name(self) -> &'static str {
        match self {
            Literal::Null => "null",
            Literal::Bool => "bool",
            Literal::Int => "int",
            Literal::Float => "float",
            Literal::Datetime => "datetime",
            Literal::String => "string",
        }
    }

    /// The literal named `name`, or `None`.
    pub fn from_name(name: &str) -> Option<Literal> {
        Some(match name {
            "null" => Literal::Null,
            "bool" => Literal::Bool,
            "int" => Literal::Int,
            "float" => Literal::Float,
            "datetime" => Literal::Datetime,
            "string" => Literal::String,
            _ => return None,
        })
    }
}

/// What a renderer is handed. Which fields are set depends on the
/// [`Renderer`]: `value` for all but `Key`, and with it, for `Value`
/// only, `literal`, what fig's bare-literal rules make of that value;
/// `indent` for all but `Value`; `key` for `Entry`, `Tail` and `Key`;
/// `old_key` for `Key`.
///
/// Constructible, like the description structs, so a test of a
/// [`Language`] can call its `render` directly; `Default` is every field
/// empty and `literal` a string, so `RenderArgs { value: b"42", literal:
/// Literal::Int, ..Default::default() }` is the idiom for one renderer's
/// arguments.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct RenderArgs<'a> {
    pub dialect: &'a str,
    pub indent: &'a [u8],
    pub key: &'a [u8],
    pub value: &'a [u8],
    pub literal: Literal,
    pub old_key: &'a [u8],
}

/// A format implemented in Rust, or in anything Rust can call.
///
/// `Send + Sync + 'static` because the core calls it from whichever thread
/// parses, for the life of the process.
pub trait Language: Send + Sync + 'static {
    /// The declarations. Called once, at [`register`].
    fn describe(&self) -> Description;

    /// `input` as the dialect named `dialect`. Every row needs a `span`.
    fn parse(&self, dialect: &str, input: &[u8]) -> Result<NodeTable, LanguageError>;

    /// `table` as bytes in the dialect. Called only when the description
    /// declares `caps.serialize`.
    fn print(
        &self,
        dialect: &str,
        table: &NodeTable,
        options: &PrintOptions,
    ) -> Result<Vec<u8>, LanguageError> {
        let _ = (dialect, table, options);
        Err(LanguageError::new("this language does not print"))
    }

    /// Spell a fragment for the editor. Called only for a renderer the
    /// description declares.
    fn render(&self, which: Renderer, args: RenderArgs<'_>) -> Result<Vec<u8>, LanguageError> {
        let _ = args;
        Err(LanguageError::new(format!(
            "this language does not render {}",
            which.name()
        )))
    }
}

// ── registration ───────────────────────────────────────────────────────────

/// Register `lang` with the core. Returns one [`Format`] per dialect the
/// description declares, in declaration order — the first is the language's
/// own. Refused, with the reason in [`Error::Language`], when the
/// description breaks a rule the core holds its own formats to, when a
/// sample fails to parse, print, reparse to the same tree or take a no-op
/// edit, or when the name is taken.
pub fn register(lang: impl Language) -> Result<Vec<Format>, Error> {
    let desc = lang.describe();
    let dialect_count = desc.dialects.len();
    let reg = Registration::new(Box::new(lang), desc)?;
    // The registration lives for the process: the core keeps `ctx` and the
    // function pointers, and the strings the vtable points to are copied
    // at registration but `ctx` is read on every call.
    let reg: &'static Registration = Box::leak(Box::new(reg));
    let vt = reg.vtable();
    let mut format: c_int = -1;
    let mut err = ffi::FigError::new();
    let status = unsafe { ffi::fig_language_register(&vt, &mut format, &mut err) };
    if status != ffi::FigStatus(ffi::FigStatus::OK) {
        let len = err.message_len.min(err.message.len());
        let message = String::from_utf8_lossy(&err.message[..len]).into_owned();
        if message.is_empty() {
            Error::from_status(status)?;
            return Err(Error::Internal);
        }
        return Err(Error::Language(message));
    }
    Ok((0..dialect_count as c_int)
        .map(|i| Format::Runtime(RuntimeFormat(format + i)))
        .collect())
}

/// Everything the vtable points at, owned for the life of the process, plus
/// the language itself.
struct Registration {
    lang: Box<dyn Language>,
    name: CString,
    caps: u32,
    max_mapping_depth: c_int,
    lossless: Option<Box<ffi::FigNativeKinds>>,
    syntax: Option<Box<CSyntax>>,
    dialects: Vec<ffi::FigDialectDesc>,
    /// What each dialect's pointers reach.
    _dialect_owned: Vec<CDialect>,
    samples: Vec<Vec<u8>>,
    sample_strs: Vec<ffi::FigStr>,
    renderers: Renderers,
}

/// A `FigSyntax` and the strings it points into.
struct CSyntax {
    c: ffi::FigSyntax,
    _strings: Vec<CString>,
}

struct CDialect {
    _name: CString,
    _extensions: Vec<CString>,
    _extension_ptrs: Vec<*const c_char>,
    _seed: Option<CString>,
    _syntax: Option<Box<CSyntax>>,
}

unsafe impl Send for Registration {}
unsafe impl Sync for Registration {}

fn cstr(s: &str) -> Result<CString, Error> {
    CString::new(s)
        .map_err(|_| Error::Language(format!("a declared string contains a NUL byte: {s:?}")))
}

fn opt_ptr(strings: &mut Vec<CString>, s: Option<&str>) -> Result<*const c_char, Error> {
    match s {
        Some(s) => {
            let c = cstr(s)?;
            let p = c.as_ptr();
            strings.push(c);
            Ok(p)
        }
        None => Ok(std::ptr::null()),
    }
}

impl CSyntax {
    fn new(s: &Syntax) -> Result<Box<Self>, Error> {
        let mut strings = Vec::new();
        let delim = |strings: &mut Vec<CString>,
                     d: Option<&CommentDelimiter>|
         -> Result<ffi::FigCommentDelimiter, Error> {
            Ok(match d {
                Some(d) => ffi::FigCommentDelimiter {
                    open: opt_ptr(strings, Some(&d.open))?,
                    close: opt_ptr(strings, Some(&d.close))?,
                    forbidden: opt_ptr(strings, d.forbidden.as_deref())?,
                },
                None => ffi::FigCommentDelimiter {
                    open: std::ptr::null(),
                    close: std::ptr::null(),
                    forbidden: std::ptr::null(),
                },
            })
        };
        let c = ffi::FigSyntax {
            comments: ffi::FigComments {
                style: match s.comments.style {
                    CommentStyle::Hash => 0,
                    CommentStyle::Slashes => 1,
                    CommentStyle::Semicolon => 2,
                    CommentStyle::XmlComment => 3,
                },
                line: delim(&mut strings, s.comments.line.as_ref())?,
                trailing: delim(&mut strings, s.comments.trailing.as_ref())?,
            },
            kv_sep: opt_ptr(&mut strings, s.kv_sep.as_deref())?,
            flow_kv_sep_from_siblings: s.flow_kv_sep_from_siblings,
            flow_map_pad: opt_ptr(&mut strings, Some(&s.flow_map_pad))?,
            key_style: match s.key_style {
                KeyStyle::Verbatim => 0,
                KeyStyle::JsonQuoted => 1,
                KeyStyle::ZonField => 2,
                KeyStyle::BareOrQuoted => 3,
            },
            key_sigil: s.key_sigil.unwrap_or(0),
            empty_map_literal: opt_ptr(&mut strings, s.empty_map_literal.as_deref())?,
            block_seq_editable: s.block_seq_editable,
            flow_containers: s.flow_containers,
            indent_unit: opt_ptr(&mut strings, Some(&s.indent_unit))?,
            seq_item_marker: opt_ptr(&mut strings, Some(&s.seq_item_marker))?,
            closed_containers: match &s.closed_containers {
                Some(c) => ffi::FigClosedContainers {
                    map_open: opt_ptr(&mut strings, Some(&c.map_open))?,
                    map_close: opt_ptr(&mut strings, Some(&c.map_close))?,
                    seq_open: opt_ptr(&mut strings, Some(&c.seq_open))?,
                    seq_close: opt_ptr(&mut strings, Some(&c.seq_close))?,
                },
                None => ffi::FigClosedContainers {
                    map_open: std::ptr::null(),
                    map_close: std::ptr::null(),
                    seq_open: std::ptr::null(),
                    seq_close: std::ptr::null(),
                },
            },
            single_line_block_mapping: s.single_line_block_mapping,
            bare_document_mapping: s.bare_document_mapping,
            flow_map_open: opt_ptr(&mut strings, Some(&s.flow_map_open))?,
            flow_map_close: opt_ptr(&mut strings, Some(&s.flow_map_close))?,
            structural_indent: s.structural_indent,
            section_noun: match s.section_noun {
                None => -1,
                Some(SectionNoun::Table) => 0,
                Some(SectionNoun::Section) => 1,
                Some(SectionNoun::Container) => 2,
            },
            section_header: match &s.section_header {
                Some(h) => ffi::FigSectionHeader {
                    open: opt_ptr(&mut strings, Some(&h.open))?,
                    close: opt_ptr(&mut strings, Some(&h.close))?,
                    seq_open: opt_ptr(&mut strings, h.seq_open.as_deref())?,
                    seq_close: opt_ptr(&mut strings, h.seq_close.as_deref())?,
                    sep: opt_ptr(&mut strings, Some(&h.sep))?,
                    skip_index: h.skip_index,
                },
                None => ffi::FigSectionHeader {
                    open: std::ptr::null(),
                    close: std::ptr::null(),
                    seq_open: std::ptr::null(),
                    seq_close: std::ptr::null(),
                    sep: std::ptr::null(),
                    skip_index: true,
                },
            },
            merge_key: opt_ptr(&mut strings, s.merge_key.as_deref())?,
        };
        Ok(Box::new(CSyntax {
            c,
            _strings: strings,
        }))
    }
}

impl Registration {
    fn new(lang: Box<dyn Language>, desc: Description) -> Result<Self, Error> {
        let name = cstr(&desc.name)?;
        let mut caps = 0u32;
        if desc.caps.read {
            caps |= 1 << 0;
        }
        if desc.caps.edit {
            caps |= 1 << 1;
        }
        if desc.caps.serialize {
            caps |= 1 << 2;
        }
        if desc.caps.references {
            caps |= 1 << 3;
        }
        let lossless = desc.lossless.map(|l| {
            Box::new(ffi::FigNativeKinds {
                null_: l.null,
                offset_datetime: l.offset_datetime,
                local_datetime: l.local_datetime,
                local_date: l.local_date,
                local_time: l.local_time,
                enum_literal: l.enum_literal,
                char_literal: l.char_literal,
                number_special: l.number_special,
                plist_date: l.plist_date,
                plist_data: l.plist_data,
            })
        });
        let syntax = match &desc.syntax {
            Some(s) => Some(CSyntax::new(s)?),
            None => None,
        };
        let mut dialects = Vec::with_capacity(desc.dialects.len());
        let mut owned = Vec::with_capacity(desc.dialects.len());
        for d in &desc.dialects {
            let dname = cstr(&d.name)?;
            let extensions: Vec<CString> = d
                .extensions
                .iter()
                .map(|e| cstr(e))
                .collect::<Result<_, _>>()?;
            let mut extension_ptrs: Vec<*const c_char> =
                extensions.iter().map(|e| e.as_ptr()).collect();
            extension_ptrs.push(std::ptr::null());
            let seed = match &d.empty_doc_seed {
                Some(s) => Some(cstr(s)?),
                None => None,
            };
            let dsyntax = match &d.syntax {
                Some(s) => Some(CSyntax::new(s)?),
                None => None,
            };
            dialects.push(ffi::FigDialectDesc {
                name: dname.as_ptr(),
                extensions: extension_ptrs.as_ptr(),
                splice: match d.splice {
                    Splice::Literal => 0,
                    Splice::JsonString => 1,
                    Splice::Raw => 2,
                },
                empty_doc_seed: seed.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
                syntax: dsyntax
                    .as_ref()
                    .map_or(std::ptr::null(), |s| &s.c as *const _),
            });
            owned.push(CDialect {
                _name: dname,
                _extensions: extensions,
                _extension_ptrs: extension_ptrs,
                _seed: seed,
                _syntax: dsyntax,
            });
        }
        let samples: Vec<Vec<u8>> = desc.samples.iter().map(|s| s.as_bytes().to_vec()).collect();
        let sample_strs = samples
            .iter()
            .map(|s| ffi::FigStr {
                ptr: s.as_ptr(),
                len: s.len(),
            })
            .collect();
        Ok(Registration {
            lang,
            name,
            caps,
            max_mapping_depth: desc
                .max_mapping_depth
                .map_or(ffi::FIG_DEPTH_NONE, c_int::from),
            lossless,
            syntax,
            dialects,
            _dialect_owned: owned,
            samples,
            sample_strs,
            renderers: desc.renderers,
        })
    }

    fn vtable(&'static self) -> ffi::FigLanguageVTable {
        ffi::FigLanguageVTable {
            version: ffi::FIG_LANGUAGE_VTABLE_VERSION,
            ctx: self as *const Registration as *mut c_void,
            name: self.name.as_ptr(),
            caps: self.caps,
            max_mapping_depth: self.max_mapping_depth,
            lossless: self
                .lossless
                .as_ref()
                .map_or(std::ptr::null(), |l| &**l as *const _),
            syntax: self
                .syntax
                .as_ref()
                .map_or(std::ptr::null(), |s| &s.c as *const _),
            dialects: self.dialects.as_ptr(),
            dialect_count: self.dialects.len(),
            samples: self.sample_strs.as_ptr(),
            sample_count: self.samples.len(),
            parse: parse_thunk,
            print: if self.caps & (1 << 2) != 0 {
                Some(print_thunk)
            } else {
                None
            },
            free_table: free_table_thunk,
            free_bytes: free_bytes_thunk,
            render_value: if self.renderers.value {
                Some(render_value_thunk)
            } else {
                None
            },
            render_entry: if self.renderers.entry {
                Some(render_entry_thunk)
            } else {
                None
            },
            render_item: if self.renderers.item {
                Some(render_item_thunk)
            } else {
                None
            },
            render_tail: if self.renderers.tail {
                Some(render_tail_thunk)
            } else {
                None
            },
            render_key: if self.renderers.key {
                Some(render_key_thunk)
            } else {
                None
            },
        }
    }
}

// ── the thunks ─────────────────────────────────────────────────────────────
//
// Each is the C signature over one `Language` method. A panic in the
// language is caught here — unwinding across the C boundary is undefined —
// and reported as a failure with the panic's message.

fn fill_err(err: *mut ffi::FigError, e: &LanguageError) {
    if err.is_null() {
        return;
    }
    let err = unsafe { &mut *err };
    let bytes = e.message.as_bytes();
    let n = bytes.len().min(err.message.len() - 1);
    err.message[..n].copy_from_slice(&bytes[..n]);
    err.message[n] = 0;
    err.message_len = n;
    err.byte_offset = e.byte_offset.unwrap_or(0);
}

fn panic_message(p: Box<dyn std::any::Any + Send>) -> LanguageError {
    let msg = p
        .downcast_ref::<&str>()
        .map(|s| s.to_string())
        .or_else(|| p.downcast_ref::<String>().cloned())
        .unwrap_or_else(|| "panic".to_owned());
    LanguageError::new(format!("the language panicked: {msg}"))
}

unsafe fn reg_of<'a>(ctx: *mut c_void) -> &'a Registration {
    unsafe { &*(ctx as *const Registration) }
}

unsafe fn dialect_of<'a>(dialect: *const c_char) -> &'a str {
    unsafe { std::ffi::CStr::from_ptr(dialect) }
        .to_str()
        .unwrap_or("")
}

fn bytes_of<'a>(s: ffi::FigStr) -> &'a [u8] {
    if s.len == ffi::FIG_LEN_NONE || s.len == 0 || s.ptr.is_null() {
        return &[];
    }
    unsafe { std::slice::from_raw_parts(s.ptr, s.len) }
}

/// A parse result and the C rows built over it, boxed so `owner` can find
/// it again in `free_table`.
struct TableHolder {
    _table: NodeTable,
    rows: Vec<ffi::FigNodeRow>,
    regions: Vec<ffi::FigRegionRow>,
    mentions: Vec<ffi::FigMentionRow>,
    comments: Vec<ffi::FigCommentRow>,
    directives: Vec<ffi::FigDirectiveRow>,
}

fn str_of(s: &Option<String>) -> ffi::FigStr {
    match s {
        Some(s) => ffi::FigStr {
            ptr: s.as_ptr(),
            len: s.len(),
        },
        None => ffi::FigStr::NONE,
    }
}

fn span_of(s: Option<Span>) -> ffi::FigSpan {
    match s {
        Some(s) => ffi::FigSpan {
            start: s.start,
            end: s.end,
        },
        None => ffi::FigSpan::NONE,
    }
}

/// The C table over a Rust one. The C rows point into `table`'s strings,
/// whose heap buffers do not move when the `NodeTable` is moved into the
/// holder.
fn table_to_c(table: NodeTable) -> Box<TableHolder> {
    let rows = table
        .rows
        .iter()
        .map(|r| ffi::FigNodeRow {
            kind: r.kind.to_c(),
            ext_kind: r.ext_kind.map_or(ffi::FIG_EXT_NONE, |k| k.to_c()),
            parent: r.parent.unwrap_or(ffi::FIG_ROW_NONE),
            span: span_of(r.span),
            text: str_of(&r.text),
            anchor: str_of(&r.anchor),
            anchor_span: span_of(r.anchor_span),
            tag: str_of(&r.tag),
            tag_span: span_of(r.tag_span),
            marker: span_of(r.marker),
            sep: span_of(r.sep),
        })
        .collect();
    let regions = table
        .regions
        .iter()
        .map(|r| ffi::FigRegionRow {
            node: r.node,
            start: r.start,
            end: r.end,
        })
        .collect();
    let mentions = table
        .mentions
        .iter()
        .map(|m| ffi::FigMentionRow {
            node: m.node,
            span: span_of(Some(m.span)),
            kind: match m.kind {
                MentionKind::Header => ffi::FIG_MENTION_HEADER,
                MentionKind::Entry => ffi::FIG_MENTION_ENTRY,
            },
        })
        .collect();
    let comments = table
        .comments
        .iter()
        .map(|c| ffi::FigCommentRow {
            node: c.node,
            slot: match c.slot {
                CommentSlot::Leading => ffi::FIG_COMMENT_LEADING,
                CommentSlot::Trailing => ffi::FIG_COMMENT_TRAILING,
                CommentSlot::Dangling => ffi::FIG_COMMENT_DANGLING,
            },
            style: match c.style {
                CommentForm::Line => ffi::FIG_COMMENT_LINE,
                CommentForm::Block => ffi::FIG_COMMENT_BLOCK,
            },
            text: ffi::FigStr {
                ptr: c.text.as_ptr(),
                len: c.text.len(),
            },
        })
        .collect();
    let directives = table
        .directives
        .iter()
        .map(|d| ffi::FigDirectiveRow {
            handle: ffi::FigStr {
                ptr: d.handle.as_ptr(),
                len: d.handle.len(),
            },
            prefix: ffi::FigStr {
                ptr: d.prefix.as_ptr(),
                len: d.prefix.len(),
            },
        })
        .collect();
    Box::new(TableHolder {
        _table: table,
        rows,
        regions,
        mentions,
        comments,
        directives,
    })
}

impl TableHolder {
    fn c_table(&self, owner: *mut c_void) -> ffi::FigNodeTable {
        ffi::FigNodeTable {
            rows: self.rows.as_ptr(),
            row_count: self.rows.len(),
            regions: self.regions.as_ptr(),
            region_count: self.regions.len(),
            mentions: self.mentions.as_ptr(),
            mention_count: self.mentions.len(),
            comments: self.comments.as_ptr(),
            comment_count: self.comments.len(),
            directives: self.directives.as_ptr(),
            directive_count: self.directives.len(),
            owner,
        }
    }
}

/// A Rust table from a C one — what a `print` is handed.
pub(crate) fn table_from_c(t: &ffi::FigNodeTable) -> Result<NodeTable, LanguageError> {
    let text_of = |s: ffi::FigStr| -> Result<Option<String>, LanguageError> {
        if s.len == ffi::FIG_LEN_NONE {
            return Ok(None);
        }
        String::from_utf8(bytes_of(s).to_vec())
            .map(Some)
            .map_err(|_| LanguageError::new("a table string is not UTF-8"))
    };
    let span_of = |s: ffi::FigSpan| -> Option<Span> {
        if s.start == ffi::FIG_OFFSET_NONE {
            None
        } else {
            Some(Span {
                start: s.start,
                end: s.end,
            })
        }
    };
    let rows = if t.rows.is_null() {
        &[][..]
    } else {
        unsafe { std::slice::from_raw_parts(t.rows, t.row_count) }
    };
    let regions = if t.regions.is_null() {
        &[][..]
    } else {
        unsafe { std::slice::from_raw_parts(t.regions, t.region_count) }
    };
    let mentions = if t.mentions.is_null() {
        &[][..]
    } else {
        unsafe { std::slice::from_raw_parts(t.mentions, t.mention_count) }
    };
    let comments = if t.comments.is_null() {
        &[][..]
    } else {
        unsafe { std::slice::from_raw_parts(t.comments, t.comment_count) }
    };
    let directives = if t.directives.is_null() {
        &[][..]
    } else {
        unsafe { std::slice::from_raw_parts(t.directives, t.directive_count) }
    };
    let mut out = NodeTable::new();
    for r in rows {
        out.rows.push(NodeRow {
            kind: NodeKind::from_c(r.kind)
                .ok_or_else(|| LanguageError::new("unknown node kind"))?,
            ext_kind: if r.ext_kind == ffi::FIG_EXT_NONE {
                None
            } else {
                ExtKind::from_c(r.ext_kind)
            },
            parent: if r.parent == ffi::FIG_ROW_NONE {
                None
            } else {
                Some(r.parent)
            },
            span: span_of(r.span),
            text: text_of(r.text)?,
            anchor: text_of(r.anchor)?,
            anchor_span: span_of(r.anchor_span),
            tag: text_of(r.tag)?,
            tag_span: span_of(r.tag_span),
            marker: span_of(r.marker),
            sep: span_of(r.sep),
        });
    }
    for r in regions {
        out.regions.push(RegionRow {
            node: r.node,
            start: r.start,
            end: r.end,
        });
    }
    for m in mentions {
        out.mentions.push(MentionRow {
            node: m.node,
            span: span_of(m.span).ok_or_else(|| LanguageError::new("a mention has no span"))?,
            kind: if m.kind == ffi::FIG_MENTION_ENTRY {
                MentionKind::Entry
            } else {
                MentionKind::Header
            },
        });
    }
    for c in comments {
        out.comments.push(CommentRow {
            node: c.node,
            slot: match c.slot {
                ffi::FIG_COMMENT_TRAILING => CommentSlot::Trailing,
                ffi::FIG_COMMENT_DANGLING => CommentSlot::Dangling,
                _ => CommentSlot::Leading,
            },
            style: if c.style == ffi::FIG_COMMENT_BLOCK {
                CommentForm::Block
            } else {
                CommentForm::Line
            },
            text: text_of(c.text)?.unwrap_or_default(),
        });
    }
    for d in directives {
        out.directives.push(DirectiveRow {
            handle: text_of(d.handle)?
                .ok_or_else(|| LanguageError::new("a directive has no handle"))?,
            prefix: text_of(d.prefix)?
                .ok_or_else(|| LanguageError::new("a directive has no prefix"))?,
        });
    }
    Ok(out)
}

unsafe extern "C" fn parse_thunk(
    ctx: *mut c_void,
    dialect: *const c_char,
    input: ffi::FigStr,
    out: *mut ffi::FigNodeTable,
    err: *mut ffi::FigError,
) -> c_int {
    let reg = unsafe { reg_of(ctx) };
    let dialect = unsafe { dialect_of(dialect) };
    let input = bytes_of(input);
    let result = catch_unwind(AssertUnwindSafe(|| reg.lang.parse(dialect, input)));
    match result {
        Ok(Ok(table)) => {
            let holder = table_to_c(table);
            let owner = Box::into_raw(holder);
            unsafe { *out = (*owner).c_table(owner as *mut c_void) };
            0
        }
        Ok(Err(e)) => {
            fill_err(err, &e);
            ffi::FigStatus::PARSE_ERROR
        }
        Err(p) => {
            fill_err(err, &panic_message(p));
            ffi::FigStatus::INTERNAL_ERROR
        }
    }
}

unsafe extern "C" fn free_table_thunk(_ctx: *mut c_void, table: *mut ffi::FigNodeTable) {
    let owner = unsafe { (*table).owner } as *mut TableHolder;
    if !owner.is_null() {
        drop(unsafe { Box::from_raw(owner) });
    }
}

/// Hand `bytes` to the core as a `FigStr` it will return through
/// `free_bytes`: a boxed slice, whose pointer and length are enough to
/// rebuild it.
fn give_bytes(bytes: Vec<u8>, out: *mut ffi::FigStr) {
    let boxed = bytes.into_boxed_slice();
    let len = boxed.len();
    let ptr = Box::into_raw(boxed) as *const u8;
    unsafe { *out = ffi::FigStr { ptr, len } };
}

unsafe extern "C" fn free_bytes_thunk(_ctx: *mut c_void, bytes: ffi::FigStr) {
    if bytes.ptr.is_null() || bytes.len == ffi::FIG_LEN_NONE {
        return;
    }
    let slice = std::ptr::slice_from_raw_parts_mut(bytes.ptr as *mut u8, bytes.len);
    drop(unsafe { Box::from_raw(slice) });
}

unsafe extern "C" fn print_thunk(
    ctx: *mut c_void,
    dialect: *const c_char,
    table: *const ffi::FigNodeTable,
    options: *const ffi::FigPrintOptions,
    out: *mut ffi::FigStr,
    err: *mut ffi::FigError,
) -> c_int {
    let reg = unsafe { reg_of(ctx) };
    let dialect = unsafe { dialect_of(dialect) };
    let opts = unsafe { &*options };
    let options = PrintOptions {
        pretty: opts.pretty,
        strip_comments: opts.strip_comments,
        indent: opts.indent,
        width: opts.width,
    };
    let result = catch_unwind(AssertUnwindSafe(|| {
        let table = table_from_c(unsafe { &*table })?;
        reg.lang.print(dialect, &table, &options)
    }));
    match result {
        Ok(Ok(bytes)) => {
            give_bytes(bytes, out);
            0
        }
        Ok(Err(e)) => {
            fill_err(err, &e);
            ffi::FigStatus::UNSUPPORTED_FORMAT
        }
        Err(p) => {
            fill_err(err, &panic_message(p));
            ffi::FigStatus::INTERNAL_ERROR
        }
    }
}

fn render_thunk_body(
    ctx: *mut c_void,
    which: Renderer,
    dialect: *const c_char,
    args: RenderArgs<'_>,
    out: *mut ffi::FigStr,
    err: *mut ffi::FigError,
) -> c_int {
    let reg = unsafe { reg_of(ctx) };
    let args = RenderArgs {
        dialect: unsafe { dialect_of(dialect) },
        ..args
    };
    match catch_unwind(AssertUnwindSafe(|| reg.lang.render(which, args))) {
        Ok(Ok(bytes)) => {
            give_bytes(bytes, out);
            0
        }
        Ok(Err(e)) => {
            fill_err(err, &e);
            ffi::FigStatus::UNSUPPORTED_OPERATION
        }
        Err(p) => {
            fill_err(err, &panic_message(p));
            ffi::FigStatus::INTERNAL_ERROR
        }
    }
}

unsafe extern "C" fn render_value_thunk(
    ctx: *mut c_void,
    dialect: *const c_char,
    value: ffi::FigStr,
    literal: *const c_char,
    out: *mut ffi::FigStr,
    err: *mut ffi::FigError,
) -> c_int {
    // A name this crate does not know is a core newer than it; the
    // fallback is what a renderer does with any text it cannot type.
    let literal = Literal::from_name(unsafe { dialect_of(literal) }).unwrap_or_default();
    render_thunk_body(
        ctx,
        Renderer::Value,
        dialect,
        RenderArgs {
            value: bytes_of(value),
            literal,
            ..Default::default()
        },
        out,
        err,
    )
}

unsafe extern "C" fn render_entry_thunk(
    ctx: *mut c_void,
    dialect: *const c_char,
    indent: ffi::FigStr,
    key: ffi::FigStr,
    value: ffi::FigStr,
    out: *mut ffi::FigStr,
    err: *mut ffi::FigError,
) -> c_int {
    render_thunk_body(
        ctx,
        Renderer::Entry,
        dialect,
        RenderArgs {
            indent: bytes_of(indent),
            key: bytes_of(key),
            value: bytes_of(value),
            ..Default::default()
        },
        out,
        err,
    )
}

unsafe extern "C" fn render_item_thunk(
    ctx: *mut c_void,
    dialect: *const c_char,
    indent: ffi::FigStr,
    value: ffi::FigStr,
    out: *mut ffi::FigStr,
    err: *mut ffi::FigError,
) -> c_int {
    render_thunk_body(
        ctx,
        Renderer::Item,
        dialect,
        RenderArgs {
            indent: bytes_of(indent),
            value: bytes_of(value),
            ..Default::default()
        },
        out,
        err,
    )
}

unsafe extern "C" fn render_tail_thunk(
    ctx: *mut c_void,
    dialect: *const c_char,
    indent: ffi::FigStr,
    key: ffi::FigStr,
    value: ffi::FigStr,
    out: *mut ffi::FigStr,
    err: *mut ffi::FigError,
) -> c_int {
    render_thunk_body(
        ctx,
        Renderer::Tail,
        dialect,
        RenderArgs {
            indent: bytes_of(indent),
            key: bytes_of(key),
            value: bytes_of(value),
            ..Default::default()
        },
        out,
        err,
    )
}

unsafe extern "C" fn render_key_thunk(
    ctx: *mut c_void,
    dialect: *const c_char,
    indent: ffi::FigStr,
    key: ffi::FigStr,
    old_key: ffi::FigStr,
    out: *mut ffi::FigStr,
    err: *mut ffi::FigError,
) -> c_int {
    render_thunk_body(
        ctx,
        Renderer::Key,
        dialect,
        RenderArgs {
            indent: bytes_of(indent),
            key: bytes_of(key),
            old_key: bytes_of(old_key),
            ..Default::default()
        },
        out,
        err,
    )
}