tabnas-xml 0.7.20

XML 1.0 grammar plugin for the tabnas parsing engine, with namespaces and entities
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
/* Copyright (c) 2021-2026 Richard Rodger and other contributors, MIT License */

// The engine's error carries a code, position, hint and a formatted
// report, so it is large by design and `Result<_, TabnasError>` trips
// clippy's `result_large_err`. The engine allows the lint at its own crate
// root for the same reason; boxing here would make `parse` return a
// different shape from `Tabnas::parse` and from the other two ports.
#![allow(clippy::result_large_err)]

//! The XML grammar plugin for the `tabnas` parsing engine.
//!
//! Parses XML text into a tree of elements: attributes, mixed content,
//! namespaces, entities (the five predefined plus numeric character
//! references, custom entities, and DOCTYPE `<!ENTITY>` declarations),
//! CDATA sections, comments, processing instructions and DOCTYPE
//! declarations (including `<!ATTLIST>` attribute defaults and
//! `xml:space` / `xml:lang` inheritance).
//!
//! ```
//! let value = tabnas_xml::parse(r#"<greeting lang="en">Hi <b>world</b></greeting>"#)?;
//! assert_eq!(
//!     value.to_string(),
//!     r#"{"name":"greeting","localName":"greeting","attributes":{"lang":"en"},"children":["Hi ",{"name":"b","localName":"b","attributes":{},"children":["world"]}]}"#
//! );
//! # Ok::<(), tabnas_xml::XmlError>(())
//! ```
//!
//! [`make`], [`make_with`] and [`parse`] install the plugin on the bare
//! engine, as `new Tabnas().use(Xml)` does in the canonical plugin and as
//! Go's C library does with `tabnas.Make()`. In the default pure-XML mode
//! the XML rules are the whole grammar, so nothing else is needed. Embed
//! mode (`embed: true`) is the exception. It splices XML into the value
//! rule of the relaxed-JSON jsonic grammar so an XML element can appear
//! wherever a jsonic value can, so it needs a parser that already carries
//! that grammar: install [`plugin`] or [`xml`] on a jsonic parser
//! (`tabnas_jsonic::make()`, from the `tabnas-jsonic` crate), as the
//! canonical plugin is installed after `use(jsonic)`. This crate does not
//! depend on jsonic.
//!
//! TypeScript is canonical: `ts/src/xml.ts` defines behaviour, option
//! names and defaults, and `xml-grammar.jsonic` at the repository root
//! defines the rule chain, embedded below as JSON. The shared fixtures in
//! `test/spec/*.tsv` are the parity contract across TypeScript, Go and
//! Rust.

use std::cell::RefCell;
use std::rc::Rc;
use std::sync::{Arc, OnceLock};

use indexmap::IndexMap;
use tabnas::{
    Context, LexMatcher, Options, Plugin, PluginError, Rule, Tabnas, Token, Value, TIN_CM, TIN_LN,
    TIN_SP,
};

mod bom;
mod entity;
mod lex;
mod namespace;

pub use bom::{decode_bom, strip_bom};

/// This crate's version. It MUST equal `ts/package.json` "version": the
/// release orchestrator rewrites both, and `tests/version_test.rs` fails
/// the build if they drift. Mirrors `VERSION` in `ts/src/xml.ts` and
/// `const VERSION` in `go/xml.go`.
pub const VERSION: &str = "0.7.20";

/// The README's Rust examples run as doctests, so a stale one fails the
/// gate rather than misleading the reader. Its `toml` and `bash` fences
/// are skipped; rustdoc runs only the `rust` ones.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_examples {}

/// The error a failed parse produces, re-exported so callers need not
/// depend on the engine crate directly.
pub use tabnas::TabnasError as XmlError;

// --- BEGIN EMBEDDED xml-grammar.jsonic ---
/// The grammar, as the JSON that `xml-grammar.jsonic` at the repository
/// root parses to. The TypeScript plugin embeds the same JSON, written by
/// `ts/embed-grammar.js`; this crate carries it by hand, so it needs no
/// jsonic to read it, and `tests/xml_test.rs` holds the two to the same
/// value.
pub const GRAMMAR_TEXT: &str = r##"
{
  "rule": {
    "xml": {
      "open": [
        {
          "s": "#ZZ"
        },
        {
          "s": "#TX",
          "r": "xml",
          "a": "@doc-text-open"
        },
        {
          "p": "element",
          "c": "@no-root-yet"
        }
      ],
      "close": [
        {
          "s": "#ZZ",
          "a": "@xml-end",
          "g": "end"
        },
        {
          "s": "#TX",
          "r": "xml",
          "a": "@doc-text-close",
          "g": "comma"
        }
      ]
    },
    "element": {
      "open": [
        {
          "s": "#XSC",
          "a": "@element-selfclose",
          "u": {
            "selfclose": 1
          }
        },
        {
          "s": "#XOP",
          "p": "head",
          "a": "@element-open"
        }
      ],
      "close": [
        {
          "c": "@element-is-selfclosed"
        },
        {
          "s": "#XCL",
          "a": "@element-close",
          "g": "close"
        }
      ]
    },
    "head": {
      "close": [
        {
          "r": "content"
        }
      ]
    },
    "content": {
      "open": [
        {
          "p": "children",
          "u": {
            "key": "children"
          }
        }
      ],
      "close": [
        {
          "a": "@content-close"
        }
      ]
    },
    "children": {
      "open": [
        {
          "p": "child"
        }
      ]
    },
    "child": {
      "open": [
        {
          "s": "#XCL",
          "b": 1
        },
        {
          "s": "#TX",
          "a": "@child-text"
        },
        {
          "s": "#XOP",
          "b": 1,
          "p": "element"
        },
        {
          "s": "#XSC",
          "b": 1,
          "p": "element"
        }
      ],
      "close": [
        {
          "s": "#XCL",
          "b": 1,
          "g": "close"
        },
        {
          "r": "child"
        }
      ]
    }
  }
}"##;
// --- END EMBEDDED xml-grammar.jsonic ---

/// The name the plugin registers under, and so the namespace of its
/// plugin options.
const PLUGIN_NAME: &str = "xml";

/// What [`xml`] returns when embed mode is asked of a host that is not a
/// jsonic host (see [`jsonic_host`]). Embed mode splices XML into jsonic's
/// `val` rule; on any other host it would parse documents wrongly or to
/// nothing, so the plugin refuses to install instead. The same words as
/// the TypeScript and Go plugins.
const EMBED_NEEDS_JSONIC: &str = "xml: embed mode needs a jsonic host: install the xml plugin \
     on a jsonic engine (tabnas_jsonic::make(), then use_plugin(tabnas_xml::plugin(), ...))";

/// Whether `parser` is a jsonic host: whether its `val` rule is jsonic's.
///
/// jsonic tags its relaxed alternates on `val` (implicit maps and lists,
/// path dives, implicit nulls) with the group `jsonic`, in all three
/// ports. Group tags are the engine's public handle on alternates: the
/// `rule.include` and `rule.exclude` options select by them, and that is
/// how the strict-JSON hosts shed jsonic's alternates (`tabnas_json` and
/// jsonic's own `make_json` set `include` to `json`). So the test is a
/// `val` alternate in that group which those two options leave enabled.
/// This engine applies them when it parses rather than to the rule, so
/// jsonic's `make_json` still carries the alternates it disables, and the
/// options have to be read here. The bare engine has no `val`, and no
/// other tabnas grammar tags an alternate `jsonic`. `jsonicHost` in
/// `ts/src/xml.ts` and `go/xml.go` make the same test.
fn jsonic_host(parser: &Tabnas) -> bool {
    let Some(val) = parser.rules.get("val") else {
        return false;
    };
    let tags = |list: &str| -> Vec<String> {
        list.split(',')
            .map(str::trim)
            .filter(|tag| !tag.is_empty())
            .map(str::to_string)
            .collect()
    };
    let include = tags(&parser.options.rule.include);
    let exclude = tags(&parser.options.rule.exclude);
    val.open.iter().chain(&val.close).any(|alt| {
        let groups = tags(&alt.g);
        groups.iter().any(|tag| tag == "jsonic")
            && (include.is_empty() || groups.iter().any(|tag| include.contains(tag)))
            && !groups.iter().any(|tag| exclude.contains(tag))
    })
}

// The function references the grammar names, registered on the instance
// before the document is installed. The three lifecycle hooks are wired by
// name to their rule and phase when the rule is installed.
const XML_BC: &str = "@xml-bc";
const CHILDREN_BO: &str = "@children-bo";
const CHILD_BC: &str = "@child-bc";
const XML_END: &str = "@xml-end";
const NO_ROOT_YET: &str = "@no-root-yet";
const DOC_TEXT_OPEN: &str = "@doc-text-open";
const DOC_TEXT_CLOSE: &str = "@doc-text-close";
const ELEMENT_OPEN: &str = "@element-open";
const ELEMENT_SELFCLOSE: &str = "@element-selfclose";
const ELEMENT_CLOSE: &str = "@element-close";
const CONTENT_CLOSE: &str = "@content-close";
const CHILD_TEXT: &str = "@child-text";
const ELEMENT_IS_SELFCLOSED: &str = "@element-is-selfclosed";

// State the references keep, and where. The keys are the canonical
// plugin's, so a caller inspecting a rule or the context sees what it sees
// in TypeScript.
/// `Context::u`: the document's value while the white space after the root
/// element is read (`@doc-text-close`), until the document's last rule
/// closes (`@xml-end`).
const ROOT: &str = "xmlRoot";
/// `Context::u`: the first namespace violation of the current resolution
/// (see [`start_element`]).
const NS_ERROR: &str = "xmlNsError";
/// A rule's `k` bag (keep props, copied to every rule pushed or replaced
/// below, never up): the namespace scope an element's content inherits.
const SCOPE: &str = "xmlScope";
/// An element rule's `u` (scratch for that one rule): the members an
/// element with content carries after `children`, which its close appends.
const FIELDS: &str = "fields";

/// Plugin options. [`Default`] is the canonical default set: namespaces
/// resolved, entities decoded, no custom entities, undeclared entities an
/// error, unbound prefixes accepted, pure-XML mode.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct XmlOptions {
    /// Resolve namespaces: annotate elements with `prefix`, `localName`
    /// and `namespace`. Default: true.
    pub namespaces: bool,
    /// Decode the five predefined entities and numeric character
    /// references in character data. Default: true.
    pub entities: bool,
    /// Additional named entities beyond the five predefined ones.
    pub custom_entities: IndexMap<String, String>,
    /// Enforce XML 1.0 4.1: every named entity reference must resolve to
    /// a declared entity (predefined, custom, or a DOCTYPE `<!ENTITY>`
    /// declaration). Default: true. When off, a reference to an unknown
    /// name is left as it is in the output.
    pub strict_entities: bool,
    /// Enforce the Namespaces in XML 1.0 rule that every prefix on an
    /// element or attribute name be bound by an in-scope `xmlns:prefix`
    /// declaration. Default: false. XML 1.0 well-formedness and
    /// Namespaces in XML are separate specifications: `<a><foo:b/></a>`
    /// is well-formed XML, merely not namespace-well-formed, so an
    /// unbound prefix is reported only when this is on. Either way the
    /// element keeps its `prefix` and `localName`; an unbound prefix
    /// leaves `namespace` unset.
    pub strict_namespaces: bool,
    /// Embed mode. When false (the default) the parser is configured for
    /// pure-XML input: `xml` becomes the start rule, the JSON structural
    /// tokens are dropped and every non-XML lexer is switched off. When
    /// true the jsonic grammar stays in place and an alternate is added
    /// to its `val` rule so a literal element (`<tag>...</tag>` or
    /// `<tag/>`) appears wherever jsonic expects a value. That needs a
    /// parser that carries the jsonic grammar: install [`plugin`] on
    /// `tabnas_jsonic::make()`. On any other host [`xml`] returns an
    /// error and [`make_with`] panics.
    pub embed: bool,
}

impl Default for XmlOptions {
    fn default() -> Self {
        XmlOptions {
            namespaces: true,
            entities: true,
            custom_entities: IndexMap::new(),
            strict_entities: true,
            strict_namespaces: false,
            embed: false,
        }
    }
}

impl XmlOptions {
    /// Read an option bag the way `ts/src/xml.ts` reads it: each field on
    /// its own terms (`namespaces !== false`, `embed === true`, and so
    /// on), so one field of the wrong type leaves only that field at its
    /// default. The bag is the JSON shape a fixture's `opts` column
    /// carries and the shape [`plugin`] receives.
    pub fn from_value(value: &Value) -> Self {
        let bag = value.to_json();
        let field = |name: &str| bag.get(name);
        let not_false = |name: &str| field(name) != Some(&serde_json::Value::Bool(false));
        let is_true = |name: &str| field(name) == Some(&serde_json::Value::Bool(true));
        // Read the replacements from the engine value, not from the JSON
        // projection: `to_json` spells `undefined`, `NaN` and an infinity
        // all three `null`, and the canonical coercion tells them apart.
        let custom_entities = custom_entities(value);
        XmlOptions {
            namespaces: not_false("namespaces"),
            entities: not_false("entities"),
            custom_entities,
            strict_entities: not_false("strictEntities"),
            strict_namespaces: is_true("strictNamespaces"),
            embed: is_true("embed"),
        }
    }

    /// The option bag, with the canonical camel-case keys.
    pub fn to_value(&self) -> Value {
        let mut custom = IndexMap::new();
        for (name, text) in &self.custom_entities {
            custom.insert(name.clone(), Value::String(text.clone()));
        }
        let mut bag = IndexMap::new();
        bag.insert("namespaces".to_string(), Value::Bool(self.namespaces));
        bag.insert("entities".to_string(), Value::Bool(self.entities));
        bag.insert("customEntities".to_string(), Value::object(custom));
        bag.insert(
            "strictEntities".to_string(),
            Value::Bool(self.strict_entities),
        );
        bag.insert(
            "strictNamespaces".to_string(),
            Value::Bool(self.strict_namespaces),
        );
        bag.insert("embed".to_string(), Value::Bool(self.embed));
        Value::object(bag)
    }
}

/// The `customEntities` replacements of a loose option bag.
///
/// The canonical plugin hands each replacement straight back from the
/// `String.prototype.replace` callback in `buildEntityDecoder`, so
/// JavaScript coerces it with `ToString`: an object becomes
/// `[object Object]`, an array joins its elements with commas, and a
/// number spells itself the way `Number::toString` does. [`js_string`]
/// is that coercion.
///
/// `undefined` is the one value the callback never coerces: the guard
/// there is `undefined !== baseEntities[ref]`, so the name counts as
/// declared (no `undeclared_entity`) while the reference is left in the
/// text exactly as written. The replacement text recorded here is that
/// verbatim reference, which reads back identically. The one input where
/// the two part company is a name that a DOCTYPE internal subset also
/// declares: the canonical decoder falls through to the DTD value, while
/// this map answers first. A `String` replacement cannot express "no
/// replacement", and [`XmlOptions::custom_entities`] is a map of them.
fn custom_entities(bag: &Value) -> IndexMap<String, String> {
    // A bag built by the engine's plugin merge is an `Object`; one handed
    // in from a parse result may still be the `MapRef` the parse built,
    // and every other field here reads that shape through `to_json`.
    let fields = match bag {
        Value::Object(fields) => &**fields,
        Value::MapRef(map) => &map.value,
        _ => return IndexMap::new(),
    };
    let entries = match fields.get("customEntities") {
        Some(Value::Object(entries)) => &**entries,
        Some(Value::MapRef(map)) => &map.value,
        _ => return IndexMap::new(),
    };
    entries
        .iter()
        .map(|(name, replacement)| {
            let text = match replacement {
                Value::String(text) => text.clone(),
                Value::Text(text) => text.string.clone(),
                Value::Undefined => format!("&{name};"),
                other => js_string(other),
            };
            (name.clone(), text)
        })
        .collect()
}

/// `String(value)` as JavaScript spells it.
///
/// Ported from the same helper in the yaml and csv crates. An array
/// joins its elements with commas, rendering `null` and `undefined` as
/// nothing at all (`Array.prototype.join`), and any object is the bare
/// `[object Object]`, since a value parsed out of an option bag carries
/// no `toString` of its own.
fn js_string(value: &Value) -> String {
    match value {
        Value::Undefined => "undefined".to_string(),
        Value::Null => "null".to_string(),
        Value::Bool(flag) => flag.to_string(),
        Value::Number(number) => js_number_to_string(*number),
        Value::String(text) => text.clone(),
        Value::Text(text) => text.string.clone(),
        Value::Array(items) => items
            .iter()
            .map(|item| match item {
                Value::Undefined | Value::Null => String::new(),
                other => js_string(other),
            })
            .collect::<Vec<_>>()
            .join(","),
        Value::ListRef(list) => js_string(&Value::array(list.value.clone())),
        Value::Object(_) | Value::MapRef(_) => "[object Object]".to_string(),
    }
}

/// `String(number)` as JavaScript spells it (ECMA-262 6.1.6.1.20): the
/// shortest digit string that reads back as the same double, in plain
/// decimal while the decimal point stays inside `(-6, 21]` and in
/// exponent form outside it.
///
/// Rust's own formatting differs in three ways that reach a replacement
/// text: it keeps the sign of negative zero, it never switches to
/// exponent form, and a large integral float prints its exact binary
/// value rather than its shortest round-tripping digits. Ported from
/// `js_number_to_string` in the csv and yaml crates.
fn js_number_to_string(number: f64) -> String {
    if number.is_nan() {
        return "NaN".to_string();
    }
    // Catches -0.0 as well: JavaScript spells both zeros "0".
    if number == 0.0 {
        return "0".to_string();
    }
    if number < 0.0 {
        return format!("-{}", js_number_to_string(-number));
    }
    if number.is_infinite() {
        return "Infinity".to_string();
    }

    // The specification wants the shortest digit string `s` that round
    // trips (length `k`), and `n`, the position of the decimal point
    // relative to it. Rust's `{:e}` yields digits of exactly that length.
    let shortest = format!("{number:e}");
    let shortest_k = shortest
        .split_once('e')
        .map(|(mantissa, _)| mantissa.chars().filter(char::is_ascii_digit).count())
        .expect("a finite f64 always formats with an exponent");

    // Re-render to that same length to settle a tie. Where two digit
    // strings of length `k` are equally close to `number`, the
    // specification takes the one ending in an even digit; Rust's
    // shortest form does not, but its exactly-rounded fixed-precision
    // form does.
    let exponential = format!("{:.*e}", shortest_k - 1, number);
    let (mantissa, exponent) = exponential
        .split_once('e')
        .expect("a finite f64 always formats with an exponent");
    // Rounding can leave trailing zeros (and, on a carry, one digit too
    // many); dropping them keeps `s` shortest, which is what `k` means.
    let digits = mantissa
        .chars()
        .filter(|digit| *digit != '.')
        .collect::<String>();
    let digits = digits.trim_end_matches('0');
    let digits = if digits.is_empty() { "0" } else { digits };
    let k = digits.len() as i32;
    let n = exponent
        .parse::<i32>()
        .expect("a formatted exponent is an integer")
        + 1;

    // The four cases of the specification, in its order. The range bounds
    // are `k <= n <= 21`, `0 < n <= 21` and `-6 < n <= 0`.
    if (k..=21).contains(&n) {
        // Integral, with n - k trailing zeros to restore.
        let mut text = digits.to_string();
        text.push_str(&"0".repeat((n - k) as usize));
        text
    } else if (1..=21).contains(&n) {
        let point = n as usize;
        format!("{}.{}", &digits[..point], &digits[point..])
    } else if (-5..=0).contains(&n) {
        format!("0.{}{}", "0".repeat(-n as usize), digits)
    } else {
        // Exponent form. `n - 1` is never 0 here, so the sign is never "+0".
        let sign = if n - 1 < 0 { '-' } else { '+' };
        let power = (n - 1).abs();
        if k == 1 {
            format!("{digits}e{sign}{power}")
        } else {
            format!("{}.{}e{sign}{power}", &digits[..1], &digits[1..])
        }
    }
}

// ---------------------------------------------------------------------------
// Node helpers
// ---------------------------------------------------------------------------

/// Assign a rule's node: the Rust spelling of TypeScript `r.node = v`.
///
/// A pushed or replaced rule SHARES its parent's node cell, so writing
/// through `rule.node.borrow_mut()` would overwrite the parent's node too.
/// Assigning installs a fresh cell instead; the `content` and `child`
/// rules an element pushes then share THAT cell, which is what lets them
/// append to the element's children in place.
fn set_node(rule: &mut Rule, value: Value) {
    rule.node = Rc::new(RefCell::new(value));
}

fn flag(rule: &Rule, name: &str) -> bool {
    matches!(rule.u.get(name), Some(Value::Bool(true)))
}

fn token_string(token: Option<&Token>) -> Option<String> {
    match token.map(|token| &token.val) {
        Some(Value::String(text)) => Some(text.clone()),
        _ => None,
    }
}

/// The name and the attributes (with the DOCTYPE defaults filled in, as
/// the lexer applies them when it reads the start tag) an open or
/// self-closing tag token carries.
fn tag_of(token: Option<&Token>) -> (String, IndexMap<String, Value>) {
    let (name, attributes) = match token.map(|token| &token.val) {
        Some(Value::Object(tag)) => {
            let name = match tag.get("name") {
                Some(Value::String(name)) => name.clone(),
                _ => String::new(),
            };
            let attributes = match tag.get("attributes") {
                Some(Value::Object(attributes)) => (**attributes).clone(),
                _ => IndexMap::new(),
            };
            (name, attributes)
        }
        _ => (String::new(), IndexMap::new()),
    };
    (name, attributes)
}

/// An element's node, made when its start tag is read (`xml-grammar.jsonic`
/// gives the order the rules build an element in): `name`, `localName`,
/// `attributes`, then, for a self-closing element, an empty `children` and
/// the members that follow it. An element with content keeps those members
/// in its rule's `u` for its close to append after `children`.
///
/// Namespaces are resolved here, against the scope the element inherits
/// (see `namespace`). The scope descends in the rule's `k` bag, so an
/// element whose rule inherits none starts a resolution: the document's
/// root element, or an XML literal in embed mode. The first violation of a
/// resolution is kept in `Context::u`, the elements after it are left
/// unresolved, and `@xml-bc` fails the document with it, where the walk of
/// the finished tree used to run; embed mode ignores it, as it did.
fn start_element(
    rule: &mut Rule,
    context: &mut Context,
    selfclose: bool,
    namespaces: bool,
    strict: bool,
) {
    let (name, attributes) = tag_of(rule.o0());
    let mut local_name = name.clone();
    let mut fields = IndexMap::new();
    if namespaces {
        let inherited = rule.k.get(SCOPE).map(namespace::Scope::from_value);
        if inherited.is_none() {
            context
                .u
                .insert(NS_ERROR.to_string(), Value::String(String::new()));
        }
        let stopped =
            matches!(context.u.get(NS_ERROR), Some(Value::String(code)) if !code.is_empty());
        let mut scope = None;
        if !stopped {
            let resolved = namespace::resolve_element(
                &name,
                &attributes,
                inherited.as_ref().unwrap_or(&namespace::Scope::root()),
                strict,
            );
            local_name = resolved.local_name;
            fields = resolved.fields;
            match resolved.code {
                Some(code) => {
                    context
                        .u
                        .insert(NS_ERROR.to_string(), Value::String(code.to_string()));
                }
                None => scope = resolved.scope,
            }
        }
        // A changed scope descends from here; an unchanged one already
        // came down in `k`. A resolution's first element always records
        // one, so its content is never taken for another resolution.
        if scope.is_some() || inherited.is_none() {
            let scope = scope.unwrap_or_else(namespace::Scope::root);
            rule.k_mut().insert(SCOPE.to_string(), scope.to_value());
        }
    }
    let mut element = IndexMap::new();
    element.insert("name".to_string(), Value::String(name));
    element.insert("localName".to_string(), Value::String(local_name));
    element.insert("attributes".to_string(), Value::object(attributes));
    if selfclose {
        element.insert("children".to_string(), Value::array(Vec::new()));
        element.extend(fields);
    } else {
        rule.u_mut()
            .insert(FIELDS.to_string(), Value::object(fields));
    }
    set_node(rule, Value::object(element));
}

/// XML 1.0 2.1 [1] `document ::= prolog element Misc*`: at document level
/// only Misc (comments, PIs, white space) may appear, so character data
/// before or after the root element is not well-formed. Comments, PIs and
/// the DOCTYPE arrive as `#XIG` and are ignored by the token set, so the
/// only document-level token to police is `#TX`.
///
/// The token policed here is one of the few this plugin does not mint:
/// outside the root element the matcher claims nothing, so the engine's
/// own text matcher cuts it, and its column has not been through
/// [`lex::discount_bom`] yet.
fn check_doc_text(token: Option<&Token>, context: &Context) -> Option<Token> {
    let token = token?;
    let Value::String(text) = &token.val else {
        return None;
    };
    if text
        .bytes()
        .all(|byte| matches!(byte, b' ' | b'\t' | b'\n' | b'\r'))
    {
        return None;
    }
    let mut bad = token.clone();
    lex::discount_bom(context, &mut bad.site);
    bad.bad("text_at_top_level");
    Some(bad)
}

// ---------------------------------------------------------------------------
// The plugin
// ---------------------------------------------------------------------------

/// Install the XML grammar on `parser`: the port of the `Xml` plugin
/// function.
///
/// In pure mode the parser is reconfigured for XML alone: `xml` becomes
/// the start rule, the JSON structural tokens and every non-XML lexer are
/// switched off, and any jsonic value rules are removed, so the parser
/// carries the six XML rules whether it started as the bare engine (as
/// [`make`] arranges) or as a jsonic parser. In embed mode, on a jsonic
/// parser, the jsonic grammar stays and XML elements become values.
/// Installation is idempotent: an instance that already carries the
/// `xml` rule is left alone.
///
/// # Errors
///
/// Embed mode on a parser whose `val` rule is not jsonic's, the bare
/// engine and the strict-JSON parsers among them, is refused with a
/// [`PluginError`] that starts `xml: embed mode needs a jsonic host`, and
/// nothing is installed.
///
/// ```
/// let mut parser = tabnas::Tabnas::new();
/// tabnas_xml::xml(&mut parser, &tabnas_xml::XmlOptions::default())?;
/// assert_eq!(
///     parser.parse("<a x='1'/>")?.to_string(),
///     r#"{"name":"a","localName":"a","attributes":{"x":"1"},"children":[]}"#
/// );
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn xml(parser: &mut Tabnas, options: &XmlOptions) -> Result<(), PluginError> {
    if parser.rules.contains_key("xml") {
        return Ok(());
    }
    if options.embed && !jsonic_host(parser) {
        return Err(PluginError(EMBED_NEEDS_JSONIC.to_string()));
    }
    let embed = options.embed;
    let namespaces = options.namespaces;
    let strict_namespaces = options.strict_namespaces;

    // Reserve the XML tokens so they have stable identities before the
    // grammar references them; the matcher closes over them.
    let tokens = lex::Tokens {
        xig: parser.token("#XIG"),
        xop: parser.token("#XOP"),
        xcl: parser.token("#XCL"),
        xsc: parser.token("#XSC"),
    };
    let state = Arc::new(lex::MatcherState {
        decoder: entity::EntityDecoder::new(&options.custom_entities),
        entities: options.entities,
        strict: options.strict_entities,
        tokens,
    });
    let matcher = lex::matcher(state);

    parser.set_options(|o: &mut Options| {
        // The custom matcher runs first, ahead of every engine matcher.
        o.lex.matchers.insert(
            "xmltag".to_string(),
            LexMatcher {
                name: "xmltag".to_string(),
                order: 100_000.0,
                matcher: None,
                imperative: Some(matcher),
                factory: None,
            },
        );
        o.lex.empty_result = Value::Undefined;
        // Terminate jsonic text at `<` so a tag start is never absorbed
        // into a text run.
        o.ender = vec!["<".to_string()];

        if !embed {
            // Pure XML mode: the jsonic value grammar is unreachable and
            // every lexer other than the tag matcher is quiescent. No
            // `text.modify` hook: while the root element is open the tag
            // matcher emits the text tokens itself, and the engine's text
            // matcher only sees white space before and after the root.
            o.rule.start = "xml".to_string();
            o.rule.exclude = "jsonic,imp".to_string();
            for name in ["#OB", "#CB", "#OS", "#CS", "#CL", "#CA"] {
                o.fixed.tokens.shift_remove(name);
            }
            o.number.lex = false;
            o.value.lex = false;
            o.string.lex = false;
            o.comment.lex = false;
            o.space.lex = false;
            o.line.lex = false;
            // XML 1.0 2.1: a well-formed document has exactly ONE document
            // element. Input that parses to no value at all (a prolog on
            // its own, a lone comment, white space) satisfies every other
            // rule and then yields nothing, which a caller cannot tell
            // from a successful parse of nothing. It is the
            // well-formedness error it is. Both spellings of "no value"
            // are listed: which one a no-value parse lands on depends on
            // whether the start rule ran at all.
            o.result.fail = vec![Value::Undefined, Value::Null];
            // ...and the same rule makes empty input ill-formed. The
            // engine short-circuits `""` before the rule loop, so
            // `result.fail` never sees it; `lex.empty` governs that path.
            o.lex.empty = false;
        }

        // Drop `#XIG` (comments, PIs, DOCTYPE) with the default ignored
        // tokens. In pure mode the space, line and comment tokens are
        // never produced, but listing them is harmless.
        o.token_set.insert(
            "IGNORE".to_string(),
            vec![TIN_SP, TIN_LN, TIN_CM, tokens.xig],
        );

        // Error templates and hints, in both modes. A template
        // interpolates `{key}` against the failing token's details.
        for (code, message) in ERROR_MESSAGES {
            o.error.insert((*code).to_string(), (*message).to_string());
        }
        for (code, hint) in ERROR_HINTS {
            o.hint.insert((*code).to_string(), (*hint).to_string());
        }
    })?;

    register_refs(parser, namespaces, strict_namespaces);

    parser
        .grammar_json(GRAMMAR_TEXT)
        .map_err(|error| PluginError(format!("xml: apply grammar: {error}")))?;

    if embed {
        // Splice XML literals into the jsonic `val` rule: on `#XOP` or
        // `#XSC`, push `element`, backtracking by one so `element.open`
        // reads the same token and dispatches. A bare alternate list is
        // prepended, as the canonical `rs.open([...])` prepends.
        let splice = serde_json::json!({
            "rule": {
                "val": {
                    "open": [
                        { "s": "#XOP", "b": 1, "p": "element", "g": "xml" },
                        { "s": "#XSC", "b": 1, "p": "element", "g": "xml" },
                    ],
                },
            },
        });
        let splice = tabnas::GrammarSpec::from_value(splice)
            .map_err(|error| PluginError(format!("xml: embed grammar: {error}")))?;
        parser
            .grammar(&splice)
            .map_err(|error| PluginError(format!("xml: embed grammar: {error}")))?;
    } else {
        // Pure XML mode: the `xml` start rule reaches only the XML rules,
        // so jsonic's value rules are dead. Remove them, so the parser
        // (and a railroad diagram of it) carries only the rules XML uses.
        for name in ["val", "map", "list", "pair", "elem"] {
            parser.remove_rule(name);
        }
    }

    // The nesting limit is the lexer's (see `lex::DEPTH_LIMIT`), not a
    // budget: a caller's `parse_budget` replaces the budget in place, and
    // would take a limit kept there with it.
    Ok(())
}

/// Register every function reference the grammar names.
fn register_refs(parser: &mut Tabnas, namespaces: bool, strict_namespaces: bool) {
    // The root element is done, on the `xml` rule's child: it is the
    // document's value from here, on the start rule's cell, where a plugin
    // layered on this one (feed) reads it and replaces it with what it
    // makes of the tree. Mark the root as seen so `@no-root-yet` refuses a
    // second one, and fail the document with the first namespace violation
    // its elements met.
    parser.state_action_with_next_ref(XML_BC, move |rule, context, _next, _out| {
        if rule.child_node.is_undefined() {
            return Ok(None);
        }
        // The start rule's cell IS the document node, so it is written in
        // place; `root.node = r.child.node` in the canonical grammar, which
        // writes it before it reports a namespace violation, as this does.
        *rule.node.borrow_mut() = rule.child_node.clone();
        context.u.insert("rootSeen".to_string(), Value::Bool(true));
        if namespaces {
            if let Some(Value::String(code)) = context.u.get(NS_ERROR) {
                if !code.is_empty() {
                    // The canonical writes `ctx.t0.bad(nsErr)` here. The
                    // root is done at DOCUMENT CLOSE, where no token is
                    // current, so the canonical's `t0` is the no-token
                    // sentinel, and its report lands at the start of the
                    // source (row 1, column 1). Marking the same sentinel
                    // keeps the failure inside the engine's error
                    // machinery, which is what renders the template
                    // registered for `code`. An `ActionError` here would
                    // bypass that and hand the caller a literal stand-in
                    // message instead.
                    let code = code.clone();
                    let mut token = context.t0().cloned().unwrap_or_else(Token::no_token);
                    token.bad(&code);
                    return Ok(Some(token));
                }
            }
        }
        Ok(None)
    });

    // The document's last rule closes: a value set aside while the white
    // space after the root was read is the result again. The start rule's
    // cell IS the document node, shared by the rules that replace the start
    // rule, so it is written in place.
    parser.action_with_context(XML_END, |rule, context| {
        if let Some(value) = context.u.shift_remove(ROOT) {
            *rule.node.borrow_mut() = value;
        }
        Ok(())
    });

    // Only let `xml` push an `element` while the document has produced
    // no root (XML 1.0 2.1).
    parser.alt_condition(NO_ROOT_YET, |_rule, context| {
        !matches!(context.u.get("rootSeen"), Some(Value::Bool(true)))
    });

    parser.action_with_match_ref(DOC_TEXT_OPEN, |rule, context, _matched| {
        Ok(check_doc_text(rule.o0(), context))
    });
    // White space after the root element. This rule is replaced to read
    // what follows (`r: xml`), and the rule replacing it shares this
    // rule's cell, so the document's value is set aside until the last
    // rule closes (`@xml-end`): no rule that starts after the root element
    // is done is handed the finished document as its node.
    parser.action_with_match_ref(DOC_TEXT_CLOSE, |rule, context, _matched| {
        if let Some(bad) = check_doc_text(rule.c0(), context) {
            return Ok(Some(bad));
        }
        let value = std::mem::replace(&mut *rule.node.borrow_mut(), Value::Undefined);
        if !value.is_undefined() {
            context.u.insert(ROOT.to_string(), value);
        }
        Ok(None)
    });

    parser.action_with_context(ELEMENT_OPEN, move |rule, context| {
        start_element(rule, context, false, namespaces, strict_namespaces);
        Ok(())
    });
    parser.action_with_context(ELEMENT_SELFCLOSE, move |rule, context| {
        start_element(rule, context, true, namespaces, strict_namespaces);
        Ok(())
    });

    // The close tag must name the open tag. The offending close tag
    // itself is marked (not the lookahead token) so the caret lands on
    // `</b>`, and the two names ride on the token as details, which is
    // where the `{openname}` / `{closename}` placeholders resolve from.
    // Then the members that follow `children` are appended, in order.
    parser.action_with_match_ref(ELEMENT_CLOSE, |rule, _context, _matched| {
        let open_name = match &*rule.node.borrow() {
            Value::Object(element) => match element.get("name") {
                Some(Value::String(name)) => name.clone(),
                _ => String::new(),
            },
            _ => String::new(),
        };
        let close_name = token_string(rule.c0()).unwrap_or_default();
        if open_name == close_name {
            if let Some(Value::Object(fields)) = rule.u.get(FIELDS).cloned() {
                if let Some(element) = rule.node.borrow_mut().as_object_mut() {
                    for (key, value) in fields.iter() {
                        element.insert(key.clone(), value.clone());
                    }
                }
            }
            return Ok(None);
        }
        let Some(mut token) = rule.c0().cloned() else {
            return Ok(None);
        };
        token.bad_with_details(
            "xml_mismatched_tag",
            [
                ("openname".to_string(), Value::String(open_name)),
                ("closename".to_string(), Value::String(close_name)),
            ],
        );
        Ok(Some(token))
    });

    // The list is done: it is the element's `children`.
    parser.action_with_context(CONTENT_CLOSE, |rule, _context| {
        let children = rule.child_node.clone();
        if let Some(element) = rule.node.borrow_mut().as_object_mut() {
            element.insert("children".to_string(), children);
        }
        Ok(())
    });

    // The list of an element's children, in a cell of its own. The first
    // child is pushed with it and shares it, and so do the children that
    // replace the first, so the last of them hands the list back to this
    // rule, whose cell it is, and the rule above it, `content`, takes a
    // handle on the list only when this rule closes. Until then the list
    // has one owner, so a reader of the rule events that empties it in
    // place as it streams (tabnas-transduce's pruning) empties the list
    // the element stores, not a copy.
    parser.state_action_ref(CHILDREN_BO, |rule, _context| {
        set_node(rule, Value::array(Vec::new()));
        Ok(())
    });

    parser.action_with_context(CHILD_TEXT, |rule, _context| {
        let text = rule
            .o0()
            .map_or(Value::Undefined, |token| token.val.clone());
        if let Some(list) = rule.node.borrow_mut().as_array_mut() {
            list.push(text);
        }
        rule.u_mut().insert("done".to_string(), Value::Bool(true));
        Ok(())
    });

    parser.state_action_ref(CHILD_BC, |rule, _context| {
        if flag(rule, "done") || rule.child_node.is_undefined() {
            return Ok(());
        }
        let child = rule.child_node.clone();
        if let Some(list) = rule.node.borrow_mut().as_array_mut() {
            list.push(child);
        }
        Ok(())
    });

    parser.alt_condition(
        ELEMENT_IS_SELFCLOSED,
        |rule, _context| matches!(rule.u.get("selfclose"), Some(Value::Number(n)) if *n == 1.0),
    );
}

/// The plugin form of [`xml`], for [`Tabnas::use_plugin`]. Options are
/// read from the plugin option bag with [`XmlOptions::from_value`];
/// installed this way the grammar is re-applied to derived instances, as
/// every native plugin is.
///
/// ```
/// let mut parser = tabnas::Tabnas::new();
/// parser.use_plugin(tabnas_xml::plugin(), None)?;
/// assert_eq!(
///     parser.parse("<a>&amp;</a>")?.to_string(),
///     r#"{"name":"a","localName":"a","attributes":{},"children":["&"]}"#
/// );
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn plugin() -> Plugin {
    Plugin::new(PLUGIN_NAME, |parser, options| {
        xml(parser, &XmlOptions::from_value(options))
    })
    .with_defaults(XmlOptions::default().to_value())
}

/// Build an XML parser with caller options: the engine, then this
/// plugin, the `make(options)` of the canonical plugin (`new
/// Tabnas().use(Xml, options)`) and the `Make(options)` of the Go port.
///
/// The parser reads a source from a reader a window at a time
/// ([`Tabnas::parse_reader`], admin ADR-30) rather than whole: its tokens
/// are the `xmltag` matcher's and the engine's own, and the matcher reads
/// the source only through the lexer's window, reading it on where a
/// construct runs past the window's end, so the parser declares
/// `lex.window`. The option is set here, on the parser this crate makes
/// whole, and not in [`xml`] or [`plugin`], which other grammars install
/// beneath matchers of their own (feed) and embed mode installs on a
/// jsonic parser.
///
/// Infallible for every option but one: the grammar documents are fixed
/// literals, so any other failure here is a bug in this crate rather than
/// anything a caller did.
///
/// # Panics
///
/// When `options.embed` is true. The engine carries no grammar of its
/// own, so embed mode has no jsonic document to embed XML in, and a
/// parser built anyway would parse every document to nothing. For embed
/// mode, install [`plugin`] on a jsonic parser (`tabnas_jsonic::make()`)
/// instead.
///
/// ```
/// let parser = tabnas_xml::make_with(&tabnas_xml::XmlOptions {
///     strict_entities: false,
///     ..Default::default()
/// });
/// assert_eq!(
///     parser.parse("<a>&nope;</a>")?.to_string(),
///     r#"{"name":"a","localName":"a","attributes":{},"children":["&nope;"]}"#
/// );
/// # Ok::<(), tabnas_xml::XmlError>(())
/// ```
pub fn make_with(options: &XmlOptions) -> Tabnas {
    let mut parser = Tabnas::new();
    if let Err(error) = parser.use_plugin(plugin(), Some(options.to_value())) {
        // Embed mode, refused by `xml` on the bare engine; or a bug here.
        panic!("tabnas_xml::make_with: {error}");
    }
    parser
        .set_options(|options| options.lex.window = true)
        .expect("lex.window sets");
    parser
}

/// Build an XML parser with the default options.
///
/// Reuse the result: building the grammar dominates a parse.
///
/// ```
/// let parser = tabnas_xml::make();
/// assert_eq!(
///     parser.parse("<a><b/></a>")?.to_string(),
///     r#"{"name":"a","localName":"a","attributes":{},"children":[{"name":"b","localName":"b","attributes":{},"children":[]}]}"#
/// );
/// assert_eq!(parser.parse("<a></b>").unwrap_err().code, "xml_mismatched_tag");
/// # Ok::<(), tabnas_xml::XmlError>(())
/// ```
pub fn make() -> Tabnas {
    make_with(&XmlOptions::default())
}

/// Parse an XML document with the shared default parser.
///
/// The engine is built once, on first use, and reused after that; reuse
/// is safe because [`Tabnas::parse`] takes `&self` and builds a fresh
/// parse context per call, and `Tabnas` is `Send + Sync`. Use [`make`] or
/// [`make_with`] when the parser needs configuring.
///
/// ```
/// let value = tabnas_xml::parse("<a>Tom &amp; Jerry</a>")?;
/// assert_eq!(
///     value.to_string(),
///     r#"{"name":"a","localName":"a","attributes":{},"children":["Tom & Jerry"]}"#
/// );
/// assert_eq!(tabnas_xml::parse("<a/>junk").unwrap_err().code, "text_at_top_level");
/// # Ok::<(), tabnas_xml::XmlError>(())
/// ```
pub fn parse(src: &str) -> Result<Value, XmlError> {
    static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
    DEFAULT.get_or_init(make).parse(src)
}

/// One optional alchemy translation source and its explicit entry point.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TranslationPart {
    /// The definition a host calls after linking the source.
    pub entry: &'static str,
    /// The source text, or `None` for an entry supplied by alchemy.
    pub source: Option<&'static str>,
}

/// The package-local structural translation interface.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TranslationParts {
    /// The complete `tabnas.plugin.json` text.
    pub manifest: &'static str,
    /// An optional lift from the grammar's events to its first read shape.
    pub lift: Option<TranslationPart>,
    /// An optional embedding of a plain tree in the format's schema, with its reverse.
    pub embed: Option<TranslationPart>,
    /// An optional render from the write shape to text.
    pub render: Option<TranslationPart>,
    /// An optional transducer: the format's JSON events from its parser's
    /// rule passes, for a host that reads parser events.
    pub transduce: Option<TranslationPart>,
}

const TRANSLATION: TranslationParts = TranslationParts {
    manifest: include_str!("../translate/manifest.json"),
    lift: None,
    embed: Some(TranslationPart {
        entry: "xml-embed",
        source: Some(include_str!("../translate/embed.alc")),
    }),
    render: Some(TranslationPart {
        entry: "xml-render",
        source: Some(include_str!("../translate/render.alc")),
    }),
    transduce: Some(TranslationPart {
        entry: "xml-transduce",
        source: Some(include_str!("../translate/transduce.alc")),
    }),
};

/// Return XML's immutable translation parts.
#[must_use]
pub const fn translate() -> Option<TranslationParts> {
    Some(TRANSLATION)
}

/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
/// it. Its `translate` object is what a host that translates reads: the
/// shape XML is read as and written from (`tree`), the root it takes
/// (`any`), the schema of the tree its events carry (`xml-element`), the
/// files that hold the embedding of a plain tree in that schema and the
/// render, the sentences that say what the render does not keep and how
/// a plain tree is written, and the file that holds the transducer part
/// (`transduce`), the document's JSON events from the grammar's rule
/// passes under its default options, through which a host that reads
/// parser events reads a document. The crate embeds its own copies,
/// `translate/manifest.json` and `translate/transduce.alc`, since a
/// packaged crate holds nothing outside `rs/`; `tests/translate_test.rs`
/// holds each copy to its file.
///
/// ```
/// assert!(tabnas_xml::manifest_text().contains("\"translate\""));
/// ```
pub fn manifest_text() -> &'static str {
    TRANSLATION.manifest
}

/// XML's render, `alchemy/render.alc`, the file the manifest's
/// `translate.render` names: a library of alchemy definitions, with no
/// `export`, whose entry point `xml-render` writes an element tree's
/// events, the shape this reader builds, as one XML document, and
/// refuses any other tree, and one holding a text, an attribute value
/// or a name no XML document can hold. A host links it with its own
/// program. The crate embeds its own copy, `translate/render.alc`, held
/// to the file as the manifest's is.
///
/// ```
/// assert!(tabnas_xml::render_text().contains("def xml-render [input]"));
/// ```
pub fn render_text() -> &'static str {
    match TRANSLATION.render {
        Some(part) => part.source.unwrap_or_default(),
        None => "",
    }
}

/// The error templates, interpolated against the failing token's
/// details. Kept identical to `ts/src/xml.ts`. `$name` is not a
/// placeholder syntax the engine understands, so it is never used here.
const ERROR_MESSAGES: &[(&str, &str)] = &[
    (
        "xml_mismatched_tag",
        "closing tag </{closename}> does not match opening tag <{openname}>",
    ),
    ("xml_invalid_tag", "invalid tag: {src}"),
    ("unterminated_comment", "unterminated comment: {src}"),
    ("unterminated_cdata", "unterminated CDATA section: {src}"),
    (
        "unterminated_pi",
        "unterminated processing instruction: {src}",
    ),
    (
        "unterminated_doctype",
        "unterminated DOCTYPE declaration: {src}",
    ),
    ("comment_double_dash", "comment body cannot contain \"--\""),
    (
        "cdata_terminator_in_text",
        "character data cannot contain \"]]>\"",
    ),
    (
        "pi_target_invalid",
        "processing instruction target is missing or invalid",
    ),
    (
        "lt_in_attr_value",
        "\"<\" is not allowed in an attribute value",
    ),
    (
        "bad_entity_ref",
        "malformed entity reference (need &name; or &#NNN; or &#xHHH;)",
    ),
    ("duplicate_attribute", "duplicate attribute name in tag"),
    ("invalid_xml_char", "illegal control character in XML data"),
    (
        "reserved_namespace",
        "invalid use of a reserved namespace prefix or URI",
    ),
    (
        "unbound_prefix",
        "element or attribute uses an undeclared namespace prefix",
    ),
    (
        "invalid_namespace_uri",
        "namespace name cannot contain white space",
    ),
    ("undeclared_entity", "reference to undeclared entity"),
    (
        "unparsed_entity_ref",
        "reference to an unparsed (NDATA) entity",
    ),
    (
        "external_entity_in_attr",
        "attribute value cannot reference an external entity",
    ),
    (
        "text_at_top_level",
        "character data is not allowed outside the root element",
    ),
];

/// The hint for each error code. Kept identical to `ts/src/xml.ts`.
const ERROR_HINTS: &[(&str, &str)] = &[
    (
        "xml_mismatched_tag",
        "Each opening tag must be paired with a matching closing tag.\nExpected </{openname}> but found </{closename}>.",
    ),
    ("xml_invalid_tag", "The tag syntax is not valid XML."),
    (
        "unterminated_comment",
        "The comment starting at this position has no closing \"-->\".",
    ),
    (
        "unterminated_cdata",
        "The CDATA section starting at this position has no closing \"]]>\".",
    ),
    (
        "unterminated_pi",
        "The processing instruction starting at this position has no closing \"?>\".",
    ),
    (
        "unterminated_doctype",
        "The DOCTYPE declaration starting at this position has no closing \">\".",
    ),
    (
        "comment_double_dash",
        "XML 1.0 disallows \"--\" inside a comment body.",
    ),
    (
        "cdata_terminator_in_text",
        "The literal \"]]>\" must only appear as the end of a CDATA section.",
    ),
    (
        "pi_target_invalid",
        "A processing instruction must start with a Name; the XML declaration <?xml...?> is the special case.",
    ),
    (
        "lt_in_attr_value",
        "Use the entity reference &lt; to include \"<\" in an attribute value.",
    ),
    (
        "bad_entity_ref",
        "Replace literal \"&\" with &amp;, or terminate the entity reference with \";\".",
    ),
    (
        "duplicate_attribute",
        "Each attribute name in an open tag must be unique.",
    ),
    (
        "invalid_xml_char",
        "Only #x9, #xA, #xD and code points >= #x20 are legal XML characters.",
    ),
    (
        "reserved_namespace",
        "The \"xml\" prefix is fixed to http://www.w3.org/XML/1998/namespace; the \"xmlns\" prefix cannot be redeclared, and neither URI may be bound to any other prefix or as the default namespace.",
    ),
    (
        "unbound_prefix",
        "Declare the prefix with xmlns:prefix=\"...\" on this element or one of its ancestors.",
    ),
    (
        "invalid_namespace_uri",
        "A namespace name is a URI reference, and a URI reference cannot contain white space; note that a line break inside the declaration becomes a space under attribute-value normalisation.",
    ),
    (
        "undeclared_entity",
        "Declare the entity in the DOCTYPE internal subset, add it to the customEntities option, or set strictEntities: false to allow unresolved references through.",
    ),
    (
        "unparsed_entity_ref",
        "XML 1.0 \u{a7}4.1 (WFC: Parsed Entity) \u{2014} an entity declared with an NDATA notation is unparsed, and its name may only appear as the value of an ENTITY-typed attribute, never in an entity reference.",
    ),
    (
        "external_entity_in_attr",
        "XML 1.0 \u{a7}4.1 (WFC: No External Entity References) \u{2014} an attribute value may not reference an entity whose replacement text lives in an external file.",
    ),
    (
        "text_at_top_level",
        "An XML document is \"prolog element Misc*\": outside the single root element only comments, processing instructions and white space may appear.",
    ),
];