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
//! Document attributes (the `:name: value` header entries, plus built-ins).
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::sync::Arc;
/// Semantic formatting generated by substitutions, independent of a backend.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AttributeFormat {
Strong,
Emphasis,
Monospace,
Mark,
Superscript,
Subscript,
/// Unquoted text carrying an id or role (also wraps typographic quotes).
Span,
}
impl AttributeFormat {
pub fn name(self) -> &'static str {
match self {
Self::Strong => "strong",
Self::Emphasis => "emphasis",
Self::Monospace => "monospace",
Self::Mark => "mark",
Self::Superscript => "superscript",
Self::Subscript => "subscript",
Self::Span => "span",
}
}
}
/// Semantic link properties generated by substitutions. Backends choose markup.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct AttributeLink {
/// Fields retain substituted lexical spelling, including entity protection.
pub target: String,
pub id: Option<String>,
pub role: Option<String>,
pub title: Option<String>,
pub window: Option<String>,
pub rel: Option<String>,
}
/// A cross-reference resolved like Ruby's `InlineXrefMacroRx` (the attributes
/// it gives its `:xref` anchor node). In [`AttributePart::OpenXref`] the
/// fields keep their lexical entity protection, like link fields; in
/// [`Inline::CrossReference`](crate::Inline::CrossReference) they are decoded.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Xref {
/// The link target (Ruby's `node.target`): `#id`, `doc.html#id`,
/// `doc.html`, or `#` for the current document.
pub target: String,
/// The id whose reftext or title labels a textless reference; `path#id`
/// or `path` for another document; `None` for the current document
/// (`xref:doc.adoc[]` naming this document or an included one).
pub refid: Option<String>,
/// Another document's output path, with `relfileprefix` and
/// `relfilesuffix` (default `outfilesuffix`) applied. A textless
/// interdocument reference displays it.
pub path: Option<String>,
/// The id within the target document, if any.
pub fragment: Option<String>,
/// The lexical refid of a bare id outside compat mode whose lookup is
/// pending: when the id is unknown, Ruby looks this spelling (with any
/// generated tags) up as a title or reftext (a *natural*
/// cross-reference). Taken once resolution has looked it up.
pub(crate) natural: Option<String>,
/// `role` from the macro's attribute list.
pub role: Option<String>,
/// Link constraints of an interdocument reference (`window`, `opts`).
pub window: Option<String>,
pub rel: Option<String>,
/// `xrefstyle` from the macro's attribute list; otherwise the document
/// attribute at the reference applies.
pub xrefstyle: Option<String>,
/// Index of the attribute definition that generated this reference: Ruby
/// converts it while defining, so its target and label are fixed there
/// (see resolve.rs).
pub(crate) definition: Option<usize>,
/// The macros stage converted this reference at conversion (Ruby's
/// `InlineXrefMacroRx` building its text there): the field's resolution
/// only reports an unknown target. Cleared by that resolution.
pub(crate) resolved: bool,
/// The label nodes the macros stage built for a source-owned textless
/// reference and the field range they were built at (borrowed titles
/// keep their own spans); the field's resolution installs them after the
/// field's spans are restored.
pub(crate) label: Option<(crate::Span, Vec<crate::Inline>)>,
/// The refid's lexical spelling (with the tags earlier substitutions
/// generated) of a node whose fields were decoded: Ruby labels an
/// unknown id with it verbatim (`[refid]`).
pub(crate) spelling: Option<String>,
}
impl Xref {
/// An internal reference to `id` (`#id`).
pub fn to_id(id: impl Into<String>) -> Self {
let id = id.into();
Self {
target: format!("#{id}"),
refid: Some(id.clone()),
fragment: Some(id),
..Default::default()
}
}
/// Apply `f` to every text field (e.g. decoding entity protection).
pub(crate) fn map_fields(&mut self, mut f: impl FnMut(&str) -> String) {
self.map_fields_dyn(&mut f);
}
fn map_fields_dyn(&mut self, f: &mut dyn FnMut(&str) -> String) {
self.target = f(&self.target);
for value in [
&mut self.refid,
&mut self.path,
&mut self.fragment,
&mut self.role,
&mut self.window,
&mut self.rel,
&mut self.xrefstyle,
]
.into_iter()
.flatten()
{
*value = f(value);
}
}
}
/// An inline `image:`/`icon:` macro resolved like Ruby's `InlineImageMacroRx`
/// branch of `sub_macros` (the `:image` inline node it converts). Like link
/// fields, every string keeps its substituted lexical spelling, including
/// entity protection and generated tags (Ruby inserts these values verbatim).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct InlineImage {
/// `icon:` rather than `image:`.
pub icon: bool,
/// The macro target.
pub target: String,
/// The resolved source: an image's web path under `imagesdir`, or an
/// icon's `icon_uri` (`icon` attribute or target plus `icontype`, under
/// `iconsdir`) when icons are images. Empty for text and font icons.
pub src: String,
/// The alt text (explicit, else the target's basename with `_`/`-` as
/// spaces). Ruby's alt is the lexical value, so formatting boundaries and
/// raw entities generated by earlier stages survive as parts.
pub alt: Vec<AttributePart>,
/// An icon's document `icons` mode at the macro: `None` renders the alt
/// text in brackets, `font` an icon font glyph, any other value an image.
pub icons: Option<String>,
/// Named attributes (`width`, `height`, `title`, `link`, `window`,
/// `role`, `float`, `size`, `flip`, `rotate`, …), positional ones under
/// their names (`alt`/`width`/`height`, or `size` for an icon).
pub attributes: BTreeMap<String, String>,
/// `opts`/`options` flags (`nofollow`, `noopener`, …).
pub options: Vec<String>,
/// An SVG embedded below secure mode (`%inline`, `%interactive`).
pub svg: Option<Svg>,
}
/// Ruby's SVG embedding in `convert_image` and `convert_inline_image`, below
/// secure mode, for an image whose target contains `.svg` (or with
/// `format=svg`).
#[derive(Debug, Clone, PartialEq)]
pub enum Svg {
/// `%inline`: the file's contents (Ruby's `read_svg_contents`, lines
/// right-stripped), written with [`crate::inline_svg`]; `None` when
/// unreadable or empty, which shows the alt text.
Inline(Option<String>),
/// `%interactive`: an `<object>` of the image's source, falling back to
/// an `<img>` of `fallback` (the `fallback` attribute's source) or the alt
/// text.
Interactive { fallback: Option<String> },
}
impl InlineImage {
/// The CSS classes of Ruby's wrapping span: the type, then `float` and
/// `role`.
pub fn classes(&self) -> String {
let mut classes = String::from(if self.icon { "icon" } else { "image" });
for key in ["float", "role"] {
if let Some(value) = self.attributes.get(key) {
classes.push(' ');
classes.push_str(value);
}
}
classes
}
/// Apply `f` to every lexical field (e.g. restoring passthrough slots);
/// alt parts keep their kind unless `f` changes their lexical spelling.
pub(crate) fn map_fields(&mut self, mut f: impl FnMut(&str) -> String) {
self.map_fields_dyn(&mut f);
}
fn map_fields_dyn(&mut self, f: &mut dyn FnMut(&str) -> String) {
self.target = f(&self.target);
self.src = f(&self.src);
for value in self.attributes.values_mut() {
*value = f(value);
}
let alt = std::mem::take(&mut self.alt);
for part in alt {
let part = match part {
AttributePart::Text(text) => {
let lexical =
reference_text(std::slice::from_ref(&AttributePart::Text(text.clone())));
let mapped = f(&lexical);
if mapped == lexical {
AttributePart::Text(text)
} else {
AttributePart::Raw(mapped)
}
}
AttributePart::Raw(raw) => AttributePart::Raw(f(&raw)),
part => part.map_metadata(|value| f(value)),
};
push_value(&mut self.alt, part);
}
}
/// Ruby's `convert_inline_image` output, the temporary lexical spelling
/// of later stages.
fn lexical(&self) -> String {
let attr = |key: &str| self.attributes.get(key);
let alt = reference_text(&self.alt);
let sized = || {
let mut out = String::new();
for key in ["width", "height", "title"] {
if let Some(value) = attr(key) {
out.push_str(&format!(" {key}=\"{value}\""));
}
}
out
};
let img = |src: &str| {
format!(
"<img src=\"{src}\" alt=\"{}\"{}>",
alt.replace('"', """),
sized()
)
};
let span_alt = || format!("<span class=\"alt\">{alt}</span>");
let mut out = match (self.icon, self.icons.as_deref()) {
(true, Some("font")) => {
let mut class = format!("fa fa-{}", self.target);
if let Some(size) = attr("size") {
class.push_str(&format!(" fa-{size}"));
}
if let Some(flip) = attr("flip") {
class.push_str(&format!(" fa-flip-{flip}"));
} else if let Some(rotate) = attr("rotate") {
class.push_str(&format!(" fa-rotate-{rotate}"));
}
let title = attr("title")
.map(|title| format!(" title=\"{title}\""))
.unwrap_or_default();
format!("<i class=\"{class}\"{title}></i>")
}
(true, None) => format!("[{alt}]"),
_ => match &self.svg {
Some(Svg::Inline(Some(svg))) => crate::image::inline_svg(
svg,
attr("width").map(String::as_str),
attr("height").map(String::as_str),
),
Some(Svg::Inline(None)) => span_alt(),
Some(Svg::Interactive { fallback }) => format!(
"<object type=\"image/svg+xml\" data=\"{}\"{}>{}</object>",
self.src,
sized(),
fallback.as_deref().map_or_else(span_alt, img)
),
None => img(&self.src),
},
};
if let Some(link) = attr("link") {
let option = |name: &str| self.options.iter().any(|o| o == name);
let mut constraints = String::new();
let rel = option("nofollow").then_some("nofollow");
match attr("window") {
Some(window) => {
constraints.push_str(&format!(" target=\"{window}\""));
if window == "_blank" || option("noopener") {
match rel {
Some(rel) => constraints.push_str(&format!(" rel=\"{rel} noopener\"")),
None => constraints.push_str(" rel=\"noopener\""),
}
}
}
None => {
if let Some(rel) = rel {
constraints.push_str(&format!(" rel=\"{rel}\""));
}
}
}
out = format!("<a class=\"image\" href=\"{link}\"{constraints}>{out}</a>");
}
format!("<span class=\"{}\">{out}</span>", self.classes())
}
}
/// Text and semantic boundaries generated by attribute substitutions.
#[derive(Debug, Clone, PartialEq)]
pub enum AttributePart {
Text(String),
Raw(String),
/// Boundaries stay separate because ordered substitutions may produce
/// overlapping formatting. They do not contribute to the flat text API.
Open(AttributeFormat),
/// Values retain the reference's substituted lexical spelling, including
/// entity protection. `role` preserves significant whitespace and emptiness.
OpenWithAttributes {
format: AttributeFormat,
id: Option<String>,
role: Option<String>,
},
Close(AttributeFormat),
OpenLink(AttributeLink),
CloseLink,
/// A semantic hard line break generated by post replacements.
LineBreak,
/// An inline anchor recognized by the macros stage (Ruby's
/// `InlineAnchorRx`). Its reftext is registry metadata, not content.
Anchor(String),
/// A cross-reference recognized by the macros stage (Ruby's
/// `InlineXrefMacroRx`). Its fields retain the lexical entity protection
/// like link fields. A pair with no label between receives the target's
/// label during conversion.
OpenXref(Xref),
CloseXref,
/// An inline image or icon recognized by the macros stage (Ruby's
/// `InlineImageMacroRx`), an atomic value without flat text.
Image(Box<InlineImage>),
/// A footnote recognized by the macros stage (Ruby's
/// `InlineFootnoteMacroRx`), an atomic value without flat text: its
/// marker shows inline, its content belongs to the document's footnotes.
Footnote(Box<Footnote>),
/// A keyboard, button or menu macro recognized by the macros stage when
/// `experimental` is set (Ruby's `InlineKbdBtnMacroRx`,
/// `InlineMenuMacroRx` and `InlineMenuRx`), an atomic value without
/// flat text.
Ui(Box<UiMacro>),
/// An index term recognized by the macros stage after images (Ruby's
/// `InlineIndextermMacroRx`), an atomic value without flat text. A
/// concealed term has an empty lexical spelling, like Ruby's empty
/// output, so the later stages see the same text as in Ruby.
IndexTerm(Box<IndexTerm>),
/// A protected inline formula extracted before normal substitutions.
Stem(Box<Stem>),
/// A callout mark recognized by a block's callouts substitution (Ruby's
/// `sub_callouts`), an atomic value without flat text.
Callout(Box<InlineCallout>),
}
/// A callout mark at the end of a line of a block with custom substitutions,
/// like Ruby's `:callout` inline node. `icons` is the document `icons` mode at
/// the substitution and `src` the image icon (`icon_uri "callouts/N"`) when
/// icons are images.
#[derive(Debug, Clone, PartialEq)]
pub struct InlineCallout {
pub number: String,
/// The line comment kept before the mark (`// `, `# `, …).
pub guard: Option<String>,
/// The `<!--N-->` form.
pub xml: bool,
/// Ruby's `CO<list>-<n>` id read from the callouts catalog, if any.
pub id: Option<String>,
pub icons: Option<String>,
pub src: String,
}
impl InlineCallout {
/// Ruby's `convert_inline_callout` markup, the lexical spelling later
/// stages see.
fn lexical(&self) -> String {
let n = &self.number;
match self.icons.as_deref() {
Some("font") => format!("<i class=\"conum\" data-value=\"{n}\"></i><b>({n})</b>"),
Some(_) => format!("<img src=\"{}\" alt=\"{n}\">", self.src),
None if self.xml => format!("<!--<b class=\"conum\">({n})</b>-->"),
None => format!(
"{}<b class=\"conum\">({n})</b>",
self.guard.as_deref().unwrap_or_default()
),
}
}
}
/// The notation selected by an inline mathematical macro.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StemStyle {
AsciiMath,
LatexMath,
}
impl StemStyle {
/// Ruby's STEM_TYPE_ALIASES; unknown and unset values use AsciiMath.
pub(crate) fn from_alias(value: Option<&str>) -> Self {
match value {
Some("latexmath" | "latex" | "tex") => Self::LatexMath,
_ => Self::AsciiMath,
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::AsciiMath => "asciimath",
Self::LatexMath => "latexmath",
}
}
/// The inline delimiters used by the HTML5 converter and lexical subs.
pub fn delimiters(self) -> (&'static str, &'static str) {
match self {
Self::AsciiMath => (r"\$", r"\$"),
Self::LatexMath => (r"\(", r"\)"),
}
}
}
/// A formula protected from the outer substitutions. Its parts preserve the
/// requested inner substitutions (special characters by default), without
/// embedding HTML or a particular mathematical typesetter in the AST.
#[derive(Debug, Clone, PartialEq)]
pub struct Stem {
pub style: StemStyle,
pub parts: Vec<AttributePart>,
}
impl Stem {
pub(crate) fn lexical(&self) -> String {
let (open, close) = self.style.delimiters();
format!("{open}{}{close}", reference_text(&self.parts))
}
}
/// One of Ruby's experimental UI macros (its `:kbd`, `:button` and `:menu`
/// inline nodes). Every label keeps the lexical parts of the earlier
/// substitutions, so formatting boundaries and raw entities survive.
#[derive(Debug, Clone, PartialEq)]
pub enum UiMacro {
/// `kbd:[Ctrl+T]`: the keys split at the first `,` or `+` after the
/// first character (a trailing delimiter is itself the last key).
Keyboard { keys: Vec<Vec<AttributePart>> },
/// `btn:[Save]`, whitespace normalized.
Button { label: Vec<AttributePart> },
/// `menu:File[Save]`, `menu:File[Edit > Copy]` or the `"File > Save"`
/// shorthand: the menu, its submenus and the item (none for a bare
/// `menu:File[]` reference). `font` is the document's `icons=font` at the
/// macro, which picks the caret glyph.
Menu {
menu: Vec<AttributePart>,
submenus: Vec<Vec<AttributePart>>,
item: Option<Vec<AttributePart>>,
font: bool,
},
}
impl UiMacro {
/// Every label, in output order (for passthrough restoration).
pub(crate) fn labels_mut(&mut self) -> Vec<&mut Vec<AttributePart>> {
match self {
Self::Keyboard { keys } => keys.iter_mut().collect(),
Self::Button { label } => vec![label],
Self::Menu {
menu,
submenus,
item,
..
} => std::iter::once(menu)
.chain(submenus.iter_mut())
.chain(item.iter_mut())
.collect(),
}
}
/// The HTML caret between menu levels (Ruby's `convert_inline_menu`).
pub fn caret(font: bool) -> &'static str {
if font {
" <i class=\"fa fa-angle-right caret\"></i> "
} else {
" <b class=\"caret\">›</b> "
}
}
/// The markup Ruby's `convert_inline_kbd`/`_button`/`_menu` put around
/// the labels: one more piece than labels (the opening markup, the
/// separators between labels, the closing markup).
pub(crate) fn pieces(&self) -> Vec<String> {
let mut pieces: Vec<String> = Vec::new();
match self {
Self::Keyboard { keys } if keys.len() == 1 => {
pieces.extend(["<kbd>".into(), "</kbd>".into()]);
}
Self::Keyboard { keys } => {
pieces.push("<span class=\"keyseq\"><kbd>".into());
for _ in 1..keys.len() {
pieces.push("</kbd>+<kbd>".into());
}
pieces.push("</kbd></span>".into());
}
Self::Button { .. } => pieces.extend(["<b class=\"button\">".into(), "</b>".into()]),
Self::Menu {
submenus,
item: None,
..
} if submenus.is_empty() => {
pieces.extend(["<b class=\"menuref\">".into(), "</b>".into()]);
}
Self::Menu {
submenus,
item,
font,
..
} => {
let caret = Self::caret(*font);
pieces.push("<span class=\"menuseq\"><b class=\"menu\">".into());
for _ in submenus {
pieces.push(format!("</b>{caret}<b class=\"submenu\">"));
}
if item.is_some() {
pieces.push(format!("</b>{caret}<b class=\"menuitem\">"));
}
pieces.push("</b></span>".into());
}
}
pieces
}
/// Ruby's markup with the lexical labels, the spelling later stages see.
fn lexical(&self) -> String {
let mut labels = self.clone();
let labels = labels.labels_mut();
let mut out = String::new();
for (i, piece) in self.pieces().iter().enumerate() {
out.push_str(piece);
if let Some(label) = labels.get(i) {
out.push_str(&reference_text(label));
}
}
out
}
}
/// An index term, like Ruby's `:indexterm` inline node: a flow term
/// (`((Tigers))`, `indexterm2:[Tigers]`) shows its text in place, a concealed
/// term (`(((Big cats,Tigers)))`, `indexterm:[Big cats,Tigers]`) shows
/// nothing. Values other than the shown text keep their lexical spelling
/// (entity protection included), like Ruby's attributes.
#[derive(Debug, Clone, PartialEq)]
pub struct IndexTerm {
/// A flow term's text after the earlier substitutions (whitespace
/// normalized), as lexical parts; `None` for a concealed term.
pub text: Option<Vec<AttributePart>>,
/// Concealed terms in order; the attribute-list form keeps at most three.
pub terms: Vec<String>,
/// The `see` target (`((Tigers >> Big cats))`).
pub see: Option<String>,
/// The `see-also` targets (`((Tigers &> Lions &> Cats))`, `see-also=`).
pub see_also: Vec<String>,
}
impl IndexTerm {
/// The shown text (for passthrough restoration and nested labels).
pub(crate) fn labels_mut(&mut self) -> Vec<&mut Vec<AttributePart>> {
self.text.iter_mut().collect()
}
}
/// What a footnote macro is (Ruby's footnote `type`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FootnoteKind {
/// `footnote:[text]` or `footnote:id[text]`: registered and numbered.
Definition,
/// `footnote:id[]` (or a repeated id) naming a registered footnote.
Reference,
/// A reference to an unknown id, shown as `[id]`.
Unresolved,
}
/// A footnote macro's semantic value, like Ruby's footnote `Inline`:
/// `index` is the `footnote-number` counter value at the definition (shared
/// by references), `content` the definition's text after the earlier
/// substitutions (whitespace normalized, `\]` unescaped), as lexical parts
/// with semantic boundaries.
#[derive(Debug, Clone, PartialEq)]
pub struct Footnote {
pub kind: FootnoteKind,
pub index: Option<String>,
pub id: Option<String>,
pub content: Vec<AttributePart>,
/// Registration order within its document (definitions only).
pub(crate) sequence: Option<usize>,
}
impl Footnote {
/// Ruby's `convert_inline_footnote` markup, the lexical spelling later
/// stages see.
fn lexical(&self) -> String {
let index = self.index.as_deref().unwrap_or_default();
match self.kind {
FootnoteKind::Definition => {
let id = self
.id
.as_ref()
.map(|id| format!(" id=\"_footnote_{id}\""))
.unwrap_or_default();
format!("<sup class=\"footnote\"{id}>[<a id=\"_footnoteref_{index}\" class=\"footnote\" href=\"#_footnotedef_{index}\" title=\"View footnote.\">{index}</a>]</sup>")
}
FootnoteKind::Reference => format!("<sup class=\"footnoteref\">[<a class=\"footnote\" href=\"#_footnotedef_{index}\" title=\"View footnote.\">{index}</a>]</sup>"),
FootnoteKind::Unresolved => format!(
"<sup class=\"footnoteref red\" title=\"Unresolved footnote reference.\">[{}]</sup>",
self.id.as_deref().unwrap_or_default()
),
}
}
/// The marker's visible text: `[index]`, or `[id]` when unresolved.
pub fn marker(&self) -> String {
match self.kind {
FootnoteKind::Unresolved => format!("[{}]", self.id.as_deref().unwrap_or_default()),
_ => format!("[{}]", self.index.as_deref().unwrap_or_default()),
}
}
}
impl AttributePart {
/// Text content; formatting boundaries contribute an empty string.
pub fn text(&self) -> &str {
match self {
Self::Text(text) | Self::Raw(text) => text,
Self::Open(_)
| Self::OpenWithAttributes { .. }
| Self::Close(_)
| Self::OpenLink(_)
| Self::CloseLink
| Self::LineBreak
| Self::Anchor(_)
| Self::OpenXref(_)
| Self::CloseXref
| Self::Image(_)
| Self::Footnote(_)
| Self::Ui(_)
| Self::IndexTerm(_)
| Self::Stem(_)
| Self::Callout(_) => "",
}
}
pub fn is_raw(&self) -> bool {
matches!(self, Self::Raw(_))
}
pub(crate) fn is_special(&self) -> bool {
!matches!(self, Self::Text(_))
}
pub(crate) fn is_boundary(&self) -> bool {
matches!(
self,
Self::Open(_)
| Self::OpenWithAttributes { .. }
| Self::Close(_)
| Self::OpenLink(_)
| Self::CloseLink
| Self::LineBreak
| Self::Anchor(_)
| Self::OpenXref(_)
| Self::CloseXref
| Self::Image(_)
| Self::Footnote(_)
| Self::Ui(_)
| Self::IndexTerm(_)
| Self::Stem(_)
| Self::Callout(_)
)
}
pub(crate) fn map_metadata(mut self, mut f: impl FnMut(&str) -> String) -> Self {
match &mut self {
Self::OpenWithAttributes { id, role, .. } => {
for value in [id, role].into_iter().flatten() {
*value = f(value);
}
}
Self::Anchor(id) => *id = f(id),
Self::OpenXref(xref) => xref.map_fields(f),
Self::Image(image) => image.map_fields(f),
Self::Footnote(footnote) => {
if let Some(id) = &mut footnote.id {
*id = f(id);
}
}
Self::OpenLink(link) => {
link.target = f(&link.target);
for value in [
&mut link.id,
&mut link.role,
&mut link.title,
&mut link.window,
&mut link.rel,
]
.into_iter()
.flatten()
{
*value = f(value);
}
}
_ => {}
}
self
}
pub(crate) fn with_lexical_attributes(&self, text: &str) -> Option<Self> {
if let Self::OpenLink(link) = self {
let mut body = text.strip_prefix("<a")?.strip_suffix('>')?;
let mut updated = link.clone();
for (key, field) in [
("rel", &mut updated.rel),
("target", &mut updated.window),
("title", &mut updated.title),
("class", &mut updated.role),
("id", &mut updated.id),
] {
if field.is_some() {
let (rest, value) = body.rsplit_once(&format!(" {key}=\""))?;
*field = Some(value.strip_suffix('"')?.to_owned());
body = rest;
}
}
updated.target = body.strip_prefix(" href=\"")?.strip_suffix('"')?.to_owned();
return Some(Self::OpenLink(updated));
}
let Self::OpenWithAttributes { format, id, role } = self else {
return None;
};
let prefix = Self::Open(*format).lexical().into_owned();
let mut body = text
.strip_prefix(prefix.trim_end_matches('>'))?
.strip_suffix('>')?;
let new_role = if role.is_some() {
let (rest, value) = body.rsplit_once(" class=\"")?;
body = rest;
Some(value.strip_suffix('"')?.to_owned())
} else {
None
};
let new_id = if id.is_some() {
let value = body.strip_prefix(" id=\"")?.strip_suffix('"')?;
body = "";
Some(value.to_owned())
} else {
None
};
if !body.is_empty() {
return None;
}
Some(Self::OpenWithAttributes {
format: *format,
id: new_id,
role: new_role,
})
}
/// A temporary reference spelling for ordered stages, never the stored
/// value. Backends render the semantic boundaries themselves.
pub(crate) fn lexical(&self) -> Cow<'_, str> {
use AttributeFormat::*;
Cow::Borrowed(match self {
Self::OpenLink(link) => {
let mut text = format!("<a href=\"{}\"", link.target);
for (key, value) in [
("id", &link.id),
("class", &link.role),
("title", &link.title),
("target", &link.window),
("rel", &link.rel),
] {
if let Some(value) = value {
text.push_str(&format!(" {key}=\"{value}\""));
}
}
text.push('>');
return Cow::Owned(text);
}
Self::CloseLink | Self::CloseXref => "</a>",
Self::OpenXref(xref) => {
let mut text = format!("<a href=\"{}\"", xref.target);
for (key, value) in [
("class", &xref.role),
("target", &xref.window),
("rel", &xref.rel),
] {
if let Some(value) = value {
text.push_str(&format!(" {key}=\"{value}\""));
}
}
text.push('>');
return Cow::Owned(text);
}
Self::LineBreak => "<br>",
Self::Image(image) => return Cow::Owned(image.lexical()),
Self::Footnote(footnote) => return Cow::Owned(footnote.lexical()),
Self::Ui(ui) => return Cow::Owned(ui.lexical()),
Self::Stem(stem) => return Cow::Owned(stem.lexical()),
Self::Callout(callout) => return Cow::Owned(callout.lexical()),
Self::IndexTerm(term) => {
return Cow::Owned(term.text.as_deref().map(reference_text).unwrap_or_default())
}
Self::Anchor(id) => return Cow::Owned(format!("<a id=\"{id}\"></a>")),
Self::OpenWithAttributes { format, id, role } => {
let mut text = Self::Open(*format).lexical().into_owned();
text.pop();
if let Some(id) = id {
text.push_str(&format!(" id=\"{id}\""));
}
if let Some(role) = role {
text.push_str(&format!(" class=\"{role}\""));
}
text.push('>');
return Cow::Owned(text);
}
Self::Open(Strong) => "<strong>",
Self::Close(Strong) => "</strong>",
Self::Open(Emphasis) => "<em>",
Self::Close(Emphasis) => "</em>",
Self::Open(Monospace) => "<code>",
Self::Close(Monospace) => "</code>",
Self::Open(Mark) => "<mark>",
Self::Close(Mark) => "</mark>",
Self::Open(Superscript) => "<sup>",
Self::Close(Superscript) => "</sup>",
Self::Open(Subscript) => "<sub>",
Self::Close(Subscript) => "</sub>",
Self::Open(Span) => "<span>",
Self::Close(Span) => "</span>",
_ => self.text(),
})
}
}
pub(crate) fn push_value(parts: &mut Vec<AttributePart>, part: AttributePart) {
// Keep owned strings when starting a new run; only merging adjacent runs
// needs to copy bytes. Empty semantic boundaries must still survive.
use AttributePart::{Raw, Text};
if matches!(&part, Text(text) | Raw(text) if text.is_empty()) {
return;
}
match (parts.last_mut(), &part) {
(Some(Text(last)), Text(text)) | (Some(Raw(last)), Raw(text)) => last.push_str(text),
_ => parts.push(part),
}
}
pub(crate) fn push_part(parts: &mut Vec<AttributePart>, text: &str, raw: bool) {
if text.is_empty() {
return;
}
match parts.last_mut() {
Some(AttributePart::Raw(last)) if raw => last.push_str(text),
Some(AttributePart::Text(last)) if !raw => last.push_str(text),
_ => parts.push(if raw {
AttributePart::Raw(text.to_owned())
} else {
AttributePart::Text(text.to_owned())
}),
}
}
pub fn parts_text(parts: &[AttributePart]) -> String {
parts.iter().map(AttributePart::text).collect()
}
/// Remove the special-character protection of a lexical metadata value;
/// character references keep their spelling (see
/// [`decode_protection`](crate::entity_references::decode_protection)).
pub(crate) fn decode_special(lexical: &str) -> String {
crate::entity_references::decode_protection(lexical)
}
/// Ordered map of document attributes. `BTreeMap` keeps output deterministic,
/// which matters for snapshot/TCK testing.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Attributes {
// Transient block substitution context, never part of document snapshots
// or the named attribute table. A local option affects p (also in selected
// pass stages), but cannot resolve {hardbreaks-option} in the a stage.
pub(crate) local_hardbreaks: bool,
// Cloning a substitution context or a document snapshot shares the tables.
// Keep them separate so plain writes need not copy semantic parts, and keep
// the transient flag above outside the shared storage.
map: Arc<BTreeMap<String, String>>,
parts: Arc<BTreeMap<String, Vec<AttributePart>>>,
// Entries whose name, value or reference text contains the passthrough
// slot marker U+0096 (`slot_marked`), a function of the tables above.
// While zero, no attribute can collide with a slot prefix.
slot_marked: usize,
}
impl Attributes {
pub(crate) fn hardbreaks(&self) -> bool {
self.local_hardbreaks || self.get("hardbreaks-option").is_some()
}
/// Equal values, ignoring the transient local hardbreaks flag.
pub(crate) fn same_values(&self, other: &Self) -> bool {
self.map == other.map && self.parts == other.parts
}
pub fn new() -> Self {
Self::default()
}
pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) {
let key = key.into().to_lowercase();
self.tracked(&key.clone(), |attributes| {
attributes.set_folded(key, value.into())
});
}
fn set_folded(&mut self, key: String, value: String) {
if self.parts.contains_key(&key) {
Arc::make_mut(&mut self.parts).remove(&key);
}
Arc::make_mut(&mut self.map).insert(key, value);
}
/// Preserve literal/raw parts and formatting through attribute substitutions.
pub fn set_parts(&mut self, key: impl Into<String>, parts: Vec<AttributePart>) {
let key = key.into().to_lowercase();
let mut merged = Vec::new();
for part in parts {
push_value(&mut merged, part);
}
self.tracked(&key.clone(), |attributes| {
attributes.set_folded(key.clone(), parts_text(&merged));
if merged.iter().any(AttributePart::is_special) {
Arc::make_mut(&mut attributes.parts).insert(key, merged);
}
});
}
/// Apply one entry's change and keep `slot_marked` in step with it.
fn tracked<R>(&mut self, key: &str, change: impl FnOnce(&mut Self) -> R) -> R {
let before = self.entry_slot_marked(key);
let result = change(self);
let after = self.entry_slot_marked(key);
self.slot_marked = self.slot_marked + usize::from(after) - usize::from(before);
result
}
// Exact keys: parts belong to the same key as their value (a counter's
// verbatim name included), so entries never depend on each other.
fn entry_slot_marked(&self, key: &str) -> bool {
const MARKER: char = '\u{96}';
self.map.get(key).is_some_and(|value| {
key.contains(MARKER)
|| value.contains(MARKER)
|| self
.parts
.get(key)
.is_some_and(|parts| reference_text(parts).contains(MARKER))
})
}
/// Whether some attribute name, value or reference text contains U+0096,
/// the first character of every passthrough slot prefix. When false, no
/// attribute can contain a prefix and the collision scan can be skipped.
pub(crate) fn may_contain_slot_prefix(&self) -> bool {
self.slot_marked > 0
}
/// Raw/formatting boundaries; absent means the entire value is literal text.
pub fn raw_parts(&self, key: &str) -> Option<&[AttributePart]> {
self.raw_parts_exact(&fold_key(key))
}
// Serialization follows exact iter keys, including case-sensitive counters.
pub(crate) fn raw_parts_exact(&self, key: &str) -> Option<&[AttributePart]> {
self.parts.get(key).map(Vec::as_slice)
}
pub(crate) fn value_parts(&self, key: &str) -> Option<Vec<AttributePart>> {
self.get(key).map(|text| {
self.raw_parts(key)
.map_or_else(|| vec![AttributePart::Text(text.to_owned())], <[_]>::to_vec)
})
}
// Counter names deliberately bypass ordinary case folding (Ruby's counter
// registry uses the supplied name verbatim).
pub(crate) fn counter_value(&self, key: &str) -> Option<String> {
self.map.get(key).map(|v| {
self.parts
.get(key)
.map_or_else(|| v.clone(), |p| reference_text(p))
})
}
pub(crate) fn set_counter(&mut self, key: &str, value: &str) {
self.tracked(key, |attributes| {
Arc::make_mut(&mut attributes.parts)
.insert(key.into(), vec![AttributePart::Raw(value.into())]);
Arc::make_mut(&mut attributes.map).insert(key.into(), value.into());
});
}
pub fn get(&self, key: &str) -> Option<&str> {
self.map.get(fold_key(key).as_ref()).map(String::as_str)
}
pub fn remove(&mut self, key: &str) -> Option<String> {
let key = key.to_lowercase();
self.tracked(&key, |attributes| {
if attributes.parts.contains_key(&key) {
Arc::make_mut(&mut attributes.parts).remove(&key);
}
if attributes.map.contains_key(&key) {
Arc::make_mut(&mut attributes.map).remove(&key)
} else {
None
}
})
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
self.map.iter().map(|(k, v)| (k.as_str(), v.as_str()))
}
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
}
/// Attribute names are case-insensitive; lookups fold the key like `set`,
/// without copying a key that is already lowercase ASCII.
fn fold_key(key: &str) -> std::borrow::Cow<'_, str> {
if key.bytes().all(|b| b.is_ascii() && !b.is_ascii_uppercase()) {
std::borrow::Cow::Borrowed(key)
} else {
std::borrow::Cow::Owned(key.to_lowercase())
}
}
/// The reference compares the protected attribute to unprotected declarations.
/// This temporary lexical view is not stored in the AST or rendered by core.
pub(crate) fn reference_text(parts: &[AttributePart]) -> String {
let mut result = String::new();
for part in parts {
for ch in part.lexical().chars() {
if part.is_special() {
result.push(ch);
} else {
result.push_str(match ch {
'<' => "<",
'>' => ">",
'&' => "&",
_ => {
result.push(ch);
continue;
}
});
}
}
}
result
}
#[cfg(test)]
mod tests {
use super::*;
/// The collision scan `slot_marked` stands in for, over every entry.
fn scanned_slot_marker(attributes: &Attributes) -> bool {
attributes.iter().any(|(name, value)| {
name.contains('\u{96}')
|| value.contains('\u{96}')
|| attributes
.raw_parts(name)
.is_some_and(|p| reference_text(p).contains('\u{96}'))
})
}
#[test]
fn slot_marker_count_follows_every_kind_of_write() {
use AttributePart::{Raw, Text};
fn check(attributes: &Attributes, expected: bool) {
assert_eq!(
attributes.may_contain_slot_prefix(),
expected,
"{attributes:?}"
);
assert_eq!(scanned_slot_marker(attributes), expected);
}
let marked = "a\u{96}b";
let mut attributes = Attributes::new();
check(&attributes, false);
attributes.set("plain", "x");
check(&attributes, false);
attributes.set("Value", marked);
check(&attributes, true);
attributes.set("value", "x");
check(&attributes, false);
attributes.set(marked, "x");
check(&attributes, true);
attributes.remove(marked);
check(&attributes, false);
attributes.set_parts("parts", vec![Raw(marked.into()), Text("t".into())]);
check(&attributes, true);
attributes.set_parts("parts", vec![Raw("r".into())]);
check(&attributes, false);
attributes.set_counter("Count", marked);
check(&attributes, true);
attributes.set_counter("Count", "1");
check(&attributes, false);
attributes.set("value", marked);
attributes.set_parts("parts", vec![Raw(marked.into())]);
let snapshot = attributes.clone();
check(&snapshot, true);
attributes.remove("VALUE");
check(&attributes, true);
attributes.remove("parts");
check(&attributes, false);
check(&snapshot, true);
attributes.remove("missing");
check(&attributes, false);
}
#[test]
fn owned_parts_reuse_strings_and_merge_only_adjacent_equal_kinds() {
let mut text = String::with_capacity(64);
text.push('Ж');
let text_buffer = text.as_ptr();
let raw = "&🙂".to_owned();
let raw_buffer = raw.as_ptr();
let mut parts = Vec::new();
push_value(&mut parts, AttributePart::Text(text));
assert_eq!(parts[0].text().as_ptr(), text_buffer);
push_value(&mut parts, AttributePart::Text("🙂".into()));
assert_eq!(parts[0].text().as_ptr(), text_buffer);
push_value(&mut parts, AttributePart::Raw(String::new()));
push_value(&mut parts, AttributePart::Raw(raw));
assert_eq!(parts[1].text().as_ptr(), raw_buffer);
push_value(&mut parts, AttributePart::Text(String::new()));
push_value(&mut parts, AttributePart::Anchor("target".into()));
push_value(&mut parts, AttributePart::Text("tail".into()));
push_value(&mut parts, AttributePart::LineBreak);
assert_eq!(
parts,
[
AttributePart::Text("Ж🙂".into()),
AttributePart::Raw("&🙂".into()),
AttributePart::Anchor("target".into()),
AttributePart::Text("tail".into()),
AttributePart::LineBreak,
]
);
// Attribute normalization also owns these strings. Installing them
// must not duplicate their buffers, and later writes isolate snapshots.
let mut attributes = Attributes::new();
attributes.set_parts("v", parts);
assert_eq!(
attributes.raw_parts("v").unwrap()[0].text().as_ptr(),
text_buffer
);
assert_eq!(
attributes.raw_parts("v").unwrap()[1].text().as_ptr(),
raw_buffer
);
let snapshot = attributes.clone();
attributes.set("v", "changed");
assert_eq!(snapshot.get("v"), Some("Ж🙂&🙂tail"));
assert_eq!(
snapshot.raw_parts("v").unwrap()[0].text().as_ptr(),
text_buffer
);
assert_eq!(attributes.raw_parts("v"), None);
}
fn formatted() -> Vec<AttributePart> {
vec![
AttributePart::Open(AttributeFormat::Strong),
AttributePart::Text("Ж🙂".into()),
AttributePart::Close(AttributeFormat::Strong),
]
}
#[test]
fn cloned_snapshots_share_tables_but_keep_local_flags_independent() {
let mut original = Attributes::new();
original.set("plain", "before");
original.set_parts("rich", formatted());
let mut snapshot = original.clone();
snapshot.local_hardbreaks = true;
assert!(Arc::ptr_eq(&original.map, &snapshot.map));
assert!(Arc::ptr_eq(&original.parts, &snapshot.parts));
assert!(snapshot.hardbreaks());
assert!(!original.hardbreaks());
assert!(original.same_values(&snapshot));
assert_ne!(original, snapshot);
snapshot.set("PLAIN", "after");
assert!(!Arc::ptr_eq(&original.map, &snapshot.map));
assert!(Arc::ptr_eq(&original.parts, &snapshot.parts));
assert_eq!(original.get("plain"), Some("before"));
assert_eq!(snapshot.get("plain"), Some("after"));
original.set("new", "only original");
assert_eq!(snapshot.get("new"), None);
assert_eq!(snapshot.raw_parts("rich"), Some(formatted().as_slice()));
}
#[test]
fn semantic_writes_and_removals_leave_older_snapshots_intact() {
let mut original = Attributes::new();
original.set_parts("RICH", formatted());
let snapshot = original.clone();
original.set("rich", "plain");
assert_eq!(original.raw_parts("rich"), None);
assert_eq!(snapshot.raw_parts("RICH"), Some(formatted().as_slice()));
assert_eq!(snapshot.get("rich"), Some("Ж🙂"));
let mut changed = snapshot.clone();
changed.set_parts("rich", vec![AttributePart::Raw("&".into())]);
assert_eq!(changed.get("rich"), Some("&"));
assert_eq!(snapshot.raw_parts("rich"), Some(formatted().as_slice()));
assert_eq!(changed.remove("RICH"), Some("&".into()));
assert!(changed.is_empty());
assert_eq!(changed.raw_parts("rich"), None);
let mut unchanged = snapshot.clone();
assert_eq!(unchanged.remove("missing"), None);
assert!(Arc::ptr_eq(&unchanged.map, &snapshot.map));
assert!(Arc::ptr_eq(&unchanged.parts, &snapshot.parts));
assert_eq!(unchanged.remove("rich"), Some("Ж🙂".into()));
assert_eq!(snapshot.get("rich"), Some("Ж🙂"));
assert_eq!(snapshot.raw_parts("rich"), Some(formatted().as_slice()));
}
#[test]
fn counter_writes_preserve_exact_keys_and_snapshot_parts() {
let mut original = Attributes::new();
original.set("N", "ordinary");
original.set_counter("N", "1");
let mut snapshot = original.clone();
snapshot.set_counter("N", "2");
assert_eq!(original.counter_value("N").as_deref(), Some("1"));
assert_eq!(snapshot.counter_value("N").as_deref(), Some("2"));
assert_eq!(snapshot.get("N"), Some("ordinary"));
assert_eq!(
original.raw_parts_exact("N"),
Some([AttributePart::Raw("1".into())].as_slice())
);
assert_eq!(
snapshot.raw_parts_exact("N"),
Some([AttributePart::Raw("2".into())].as_slice())
);
assert_eq!(
snapshot.iter().collect::<Vec<_>>(),
[("N", "2"), ("n", "ordinary")]
);
assert_eq!(snapshot.remove("N"), Some("ordinary".into()));
assert_eq!(original.get("n"), Some("ordinary"));
assert_eq!(snapshot.counter_value("N").as_deref(), Some("2"));
}
}