Skip to main content

bilingua_model/profile/
tokens.rs

1//! Conversion between Bilingua inline codes and the text tokens Localization OS uses.
2//!
3//! LocOS puts inline codes into the text as `\u{27E6}..\u{27E7}` tokens, numbered from 1 in source order, and
4//! keeps the real markup in a side map (`TextUnit.inline_map`). Every Bilingua tag becomes exactly one token:
5//!
6//! | Bilingua tag                  | token       | letter |
7//! |-------------------------------|-------------|--------|
8//! | `Open`                        | `\u{27E6}g1\u{27E7}`   | `g` (or the pair letter you pass, `r` for DOCX runs) |
9//! | `Close` (matches an `Open`)   | `\u{27E6}/g1\u{27E7}`  | same number and letter as its `Open` |
10//! | `Standalone`                  | `\u{27E6}x1\u{27E7}`   | `x`, its order matters |
11//! | `Standalone` with `free`      | `\u{27E6}p1\u{27E7}`   | `p`, may move in the target |
12//! | `Open` or `Close` with no partner, or crossing another pair | `\u{27E6}x1\u{27E7}` | `x`, like LocOS's own begin and end codes (`<bpt>`, `<ept>`, `<it>`) |
13//!
14//! Pairs are matched by id with proper nesting, so the text is always well formed for LocOS's tag checks
15//! (`placeholders_well_formed`): an unclosed open, a close with no open and the inner side of crossed pairs are
16//! point codes whose order matters. One counter numbers every token, so numbers never repeat in a unit.
17//!
18//! The map ([`LocosMap`]) is keyed by the token number as text, like `inline_map`, and holds what is needed to
19//! rebuild the exact tag: its id, its displays and its free flag. The conversion back reads the kind from the
20//! token and the rest from the map, so a translator or model may reorder tokens and the tags still come back.
21//!
22//! Damage is never silent and never loses text: a token that is malformed, or whose number is not in the map,
23//! stays in the text as it is and is reported by [`parse_locos_text`].
24
25use crate::{merge_text, Codes, Inline, TagKind};
26use serde::{Deserialize, Serialize};
27use std::collections::BTreeMap;
28
29const OPEN: char = '\u{27E6}';
30const CLOSE: char = '\u{27E7}';
31
32/// The kind letter for paired codes unless the caller picks another.
33pub const PAIR_LETTER: char = 'g';
34/// The kind letter of a standalone code whose order matters.
35pub const POINT_LETTER: char = 'x';
36/// The kind letter of a standalone code that may move freely (LocOS `FREE_POINT_KIND`).
37pub const FREE_LETTER: char = 'p';
38
39/// What the side map holds for one token number.
40#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
41pub struct LocosCode {
42    /// Bilingua tag id.
43    pub id: String,
44    /// Kind letter used in the token: `g`/`r`/... for a pair, `x` or `p` for a standalone code.
45    pub letter: char,
46    /// Display of the opening (or standalone) tag.
47    #[serde(default)]
48    pub open: Option<String>,
49    /// Display of the closing tag, when the pair has one in the text.
50    #[serde(default)]
51    pub close: Option<String>,
52    /// Standalone code that may move freely.
53    #[serde(default)]
54    pub free: bool,
55    /// For an `x` token that stands for an `Open` or `Close` with no partner: which side it is.
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub unpaired: Option<TagKind>,
58}
59
60/// Token number (as text, from "1") to the tag it stands for.
61pub type LocosMap = BTreeMap<String, LocosCode>;
62
63/// Inline codes as LocOS text with `g` for pairs.
64pub fn to_locos_text(inl: &[Inline]) -> (String, LocosMap) {
65    to_locos_text_as(inl, PAIR_LETTER)
66}
67
68/// Like [`to_locos_text`] with another kind letter for pairs (`r` for DOCX runs). `pair_letter` must be a
69/// lower-case ASCII letter other than `x` and `p`; anything else falls back to `g`.
70pub fn to_locos_text_as(inl: &[Inline], pair_letter: char) -> (String, LocosMap) {
71    convert(inl, pair_letter, pairs(inl), None, None)
72}
73
74/// The pair-token letter a format's LocOS filter uses (the adapter's `_PAIR_LETTER`): `r` for docx and pptx runs
75/// and for the runs of an xlsx text box (LocOS tokenizes those with its PowerPoint filter), else [`PAIR_LETTER`].
76pub fn locos_pair_letter(format: &str) -> char {
77    if matches!(format, "docx" | "pptx" | "xlsx") {
78        'r'
79    } else {
80        PAIR_LETTER
81    }
82}
83
84/// Formats whose LocOS filter writes its own tag tokens into the unit text: every open tag a pair token, every
85/// close the pair token of the nearest open of its id even when pairs cross, and an open with no close a pair
86/// token too (LocOS `html_filter._iter_units`). Their LocOS text is not always well formed for
87/// `placeholders_well_formed`; it is what LocOS stores.
88///
89/// The formats that read their text with the same `_iter_units` do the same: the server pages (a `<span>` whose
90/// end tag sits after a code statement, an `<a>` closed after a block child), the mail HTML parts and the EPUB
91/// content documents.
92const LOCOS_PAIRS_BY_ID: &[&str] = &["html", "aspx", "erb", "shtml", "jsp", "phtml", "epub", "eml"];
93
94/// Formats whose LocOS filter does not number its tokens in reading order, so the tag ids carry LocOS's numbers
95/// ([`to_locos_text_numbered`], the one id-numbering path): DOCX numbers the runs `r1..rN` first and the object
96/// groups from `x<N+1>`; PPTX, and the text boxes of an XLSX workbook (LocOS tokenizes those with its PowerPoint
97/// filter), number the runs first and the breaks and fields after them. XLSX cells carry no tags, so the rule
98/// changes nothing for them. Every other format is numbered by position.
99const LOCOS_NUMBERED_BY_ID: &[&str] = &["docx", "pptx", "xlsx"];
100
101/// A unit's inline codes as the LocOS filter of `format` writes them: the format's pair letter
102/// ([`locos_pair_letter`]), and for the formats whose filter keeps its own tag tokens (`html`) every `Open` a
103/// pair token and every `Close` the closing token of the latest open of its id, crossing or not, an `Open` with
104/// no close a pair token with no closing one; a `Close` with no open stays an `x` token. For the formats whose
105/// tag ids are LocOS's token numbers (`docx`, `pptx`, `xlsx`): [`to_locos_text_numbered`]. Other formats:
106/// [`to_locos_text_as`].
107/// [`from_locos_text`] reads them all back.
108pub fn to_locos_text_for(format: &str, inl: &[Inline]) -> (String, LocosMap) {
109    let letter = locos_pair_letter(format);
110    if LOCOS_PAIRS_BY_ID.contains(&format) {
111        convert(inl, letter, pairs_by_id(inl), None, None)
112    } else if LOCOS_NUMBERED_BY_ID.contains(&format) {
113        to_locos_text_numbered(inl, letter)
114    } else {
115        to_locos_text_as(inl, letter)
116    }
117}
118
119/// Formats whose LocOS filter writes two pair letters (IDML and ICML, `idml_filter._tokenize`): a
120/// CharacterStyleRange is an `r` pair, every other wrap (hyperlink, XML tag, tracked change) a `g` pair. The
121/// Bilingua code of a range is labelled `run`.
122const LOCOS_RUN_PAIRS: &[&str] = &["idml", "icml"];
123
124/// A segment's inline codes as the LocOS filter of `format` writes them, knowing the unit's codes: what
125/// [`to_locos_text_for`] gives, except for IDML and ICML, where a pair whose code is labelled `run` (a
126/// CharacterStyleRange) is an `r` pair (`⟦r1⟧bold⟦/r1⟧`) and every other pair a `g` pair, as LocOS writes them.
127/// [`crate::profile::locos_units`] numbers every segment this way.
128pub fn to_locos_text_coded(format: &str, inl: &[Inline], codes: &Codes) -> (String, LocosMap) {
129    if !LOCOS_RUN_PAIRS.contains(&format) {
130        return to_locos_text_for(format, inl);
131    }
132    let run = |id: &str| codes.get(id).filter(|c| c.label.as_deref() == Some("run")).map(|_| 'r');
133    convert(inl, PAIR_LETTER, pairs(inl), None, Some(&run))
134}
135
136/// Like [`to_locos_text_as`], but each token takes its number from its tag's id when the ids are LocOS's own token
137/// numbers: the formats whose LocOS filter does not number its tokens in reading order (DOCX, PPTX and XLSX text
138/// boxes under the profile, where LocOS numbers the runs `r1..rN` first and the breaks, fields and objects after
139/// them, so a paragraph reads `⟦r1⟧a⟦/r1⟧⟦x3⟧⟦r2⟧b⟦/r2⟧`). The ids are used only when every tag id is a positive decimal number (no sign, no
140/// leading zero) and no number would stand for two tokens; otherwise this is exactly [`to_locos_text_as`]. The
141/// map is keyed by those numbers, so [`from_locos_text`] reads the text back as usual.
142pub fn to_locos_text_numbered(inl: &[Inline], pair_letter: char) -> (String, LocosMap) {
143    let partner = pairs(inl);
144    let mut nums = Vec::new();
145    let mut seen = std::collections::BTreeSet::new();
146    for (pos, i) in inl.iter().enumerate() {
147        let Inline::Tag { id, kind, .. } = i else { continue };
148        // a paired close takes its open's number; every other tag is a token of its own
149        if *kind == TagKind::Close && partner[pos].is_some() {
150            continue;
151        }
152        let ok = !id.is_empty() && id.len() <= 18 && id.bytes().all(|b| b.is_ascii_digit()) && !id.starts_with('0');
153        match id.parse::<usize>() {
154            Ok(n) if ok && seen.insert(n) => nums.push(n),
155            _ => return to_locos_text_as(inl, pair_letter),
156        }
157    }
158    // source text that already looks like a token with one of these numbers: the numbers give way (see `convert`)
159    let reserved = reserved_numbers(inl);
160    if nums.iter().any(|n| reserved.contains(n)) {
161        return to_locos_text_as(inl, pair_letter);
162    }
163    convert(inl, pair_letter, partner, Some(&nums), None)
164}
165
166/// The numbers of token-like text (`⟦x2⟧`, `⟦/g1⟧`, `⟦3⟧`) that the plain text of `inl` already holds. LocOS reads
167/// such text in a source as one of its tokens and drops or moves it on export; here a real code never takes the
168/// number of a look-alike, so [`from_locos_text`] can only read a look-alike as the text it is (it names no code
169/// in the map).
170fn reserved_numbers(inl: &[Inline]) -> std::collections::BTreeSet<usize> {
171    let mut out = std::collections::BTreeSet::new();
172    let mut run = String::new();
173    let flush = |run: &mut String, out: &mut std::collections::BTreeSet<usize>| {
174        let mut rest = run.as_str();
175        while let Some(at) = rest.find(OPEN) {
176            rest = &rest[at..];
177            match scan_token(rest) {
178                Some((len, _, _, num)) => {
179                    if let Ok(n) = num.parse() {
180                        out.insert(n);
181                    }
182                    rest = &rest[len..];
183                }
184                None => rest = &rest[OPEN.len_utf8()..],
185            }
186        }
187        run.clear();
188    };
189    for i in inl {
190        match i {
191            Inline::Text(t) => run.push_str(t),
192            Inline::Tag { .. } => flush(&mut run, &mut out),
193        }
194    }
195    flush(&mut run, &mut out);
196    out
197}
198
199/// The shared body; `nums[k]` is the number of the k-th token (`None`: 1, 2, 3 ... in reading order).
200/// A pair's letter by its tag id, when it is not the format's one ([`to_locos_text_coded`]).
201type PairLetterOf<'a> = &'a dyn Fn(&str) -> Option<char>;
202
203fn convert(inl: &[Inline], pair_letter: char, partner: Vec<Option<usize>>, nums: Option<&[usize]>, letter_of: Option<PairLetterOf>) -> (String, LocosMap) {
204    let pair = if pair_letter.is_ascii_lowercase() && pair_letter != POINT_LETTER && pair_letter != FREE_LETTER {
205        pair_letter
206    } else {
207        PAIR_LETTER
208    };
209    // positional numbers skip the numbers that look-alike text in the source uses
210    let reserved = if nums.is_some() { Default::default() } else { reserved_numbers(inl) };
211    let mut last = 0usize;
212    let mut number = |k: usize| match nums {
213        Some(v) => v.get(k - 1).copied().unwrap_or(k),
214        None => {
215            last += 1;
216            while reserved.contains(&last) {
217                last += 1;
218            }
219            last
220        }
221    };
222    let mut text = String::new();
223    let mut map = LocosMap::new();
224    // token number of each paired Open, by its position in `inl`
225    let mut open_num: BTreeMap<usize, usize> = BTreeMap::new();
226    let mut k = 0usize;
227    for (pos, i) in inl.iter().enumerate() {
228        let (id, kind, display, free) = match i {
229            Inline::Text(t) => {
230                text.push_str(t);
231                continue;
232            }
233            Inline::Tag { id, kind, display, free } => (id, kind, display, free),
234        };
235        let code = |letter, open: Option<&String>, close: Option<&String>, free, unpaired| LocosCode {
236            id: id.clone(),
237            letter,
238            open: open.cloned(),
239            close: close.cloned(),
240            free,
241            unpaired,
242        };
243        match (kind, partner[pos]) {
244            (TagKind::Open, Some(_)) => {
245                k += 1;
246                let n = number(k);
247                open_num.insert(pos, n);
248                let pair = letter_of.and_then(|f| f(id)).unwrap_or(pair);
249                map.insert(n.to_string(), code(pair, Some(display), None, false, None));
250                text.push_str(&format!("{OPEN}{pair}{n}{CLOSE}"));
251            }
252            (TagKind::Close, Some(o)) => {
253                let num = open_num.get(&o).copied().unwrap_or_default();
254                // the close takes its open's letter
255                let mut letter = pair;
256                if let Some(c) = map.get_mut(&num.to_string()) {
257                    c.close = Some(display.clone());
258                    letter = c.letter;
259                }
260                text.push_str(&format!("{OPEN}/{letter}{num}{CLOSE}"));
261            }
262            (TagKind::Open, None) => {
263                k += 1;
264                let n = number(k);
265                map.insert(n.to_string(), code(POINT_LETTER, Some(display), None, false, Some(TagKind::Open)));
266                text.push_str(&format!("{OPEN}{POINT_LETTER}{n}{CLOSE}"));
267            }
268            (TagKind::Close, None) => {
269                k += 1;
270                let n = number(k);
271                map.insert(n.to_string(), code(POINT_LETTER, None, Some(display), false, Some(TagKind::Close)));
272                text.push_str(&format!("{OPEN}{POINT_LETTER}{n}{CLOSE}"));
273            }
274            (TagKind::Standalone, _) => {
275                k += 1;
276                let n = number(k);
277                let letter = if *free { FREE_LETTER } else { POINT_LETTER };
278                map.insert(n.to_string(), code(letter, Some(display), None, *free, None));
279                text.push_str(&format!("{OPEN}{letter}{n}{CLOSE}"));
280            }
281        }
282    }
283    (text, map)
284}
285
286/// For each position in `inl`, the position of its partner when it is an `Open` or `Close` in a properly nested
287/// pair with the same id. A close whose open is not on top of the stack closes it and leaves the opens above it
288/// unpaired; a close whose id is not open at all is unpaired.
289fn pairs(inl: &[Inline]) -> Vec<Option<usize>> {
290    let mut partner = vec![None; inl.len()];
291    // the opens still open, by position; per id, (place on that stack, position) of its opens, the entries the
292    // stack has dropped removed when they come up. A close finds its open without scanning the stack (unmatched
293    // closes over a deep stack were quadratic).
294    let mut stack: Vec<usize> = Vec::new();
295    let mut by_id: BTreeMap<&str, Vec<(usize, usize)>> = BTreeMap::new();
296    for (pos, i) in inl.iter().enumerate() {
297        match i {
298            Inline::Tag { id, kind: TagKind::Open, .. } => {
299                by_id.entry(id.as_str()).or_default().push((stack.len(), pos));
300                stack.push(pos);
301            }
302            Inline::Tag { id, kind: TagKind::Close, .. } => {
303                let Some(opens) = by_id.get_mut(id.as_str()) else { continue };
304                while opens.last().is_some_and(|&(at, o)| stack.get(at) != Some(&o)) {
305                    opens.pop();
306                }
307                if let Some((at, o)) = opens.pop() {
308                    stack.truncate(at);
309                    partner[o] = Some(pos);
310                    partner[pos] = Some(o);
311                }
312            }
313            _ => {}
314        }
315    }
316    partner
317}
318
319/// Like [`pairs`], the way LocOS's HTML filter pairs its tags: a close pairs with the latest open of its id still
320/// open, wherever it is on the stack (pairs may cross); an open never closed is its own partner (a pair token with
321/// no closing one). A close with no open is unpaired.
322fn pairs_by_id(inl: &[Inline]) -> Vec<Option<usize>> {
323    let mut partner = vec![None; inl.len()];
324    // the opens still open, per id: one pass whatever the nesting
325    let mut open: BTreeMap<&str, Vec<usize>> = BTreeMap::new();
326    for (pos, i) in inl.iter().enumerate() {
327        match i {
328            Inline::Tag { id, kind: TagKind::Open, .. } => {
329                partner[pos] = Some(pos);
330                open.entry(id.as_str()).or_default().push(pos);
331            }
332            Inline::Tag { id, kind: TagKind::Close, .. } => {
333                if let Some(o) = open.get_mut(id.as_str()).and_then(Vec::pop) {
334                    partner[o] = Some(pos);
335                    partner[pos] = Some(o);
336                }
337            }
338            _ => {}
339        }
340    }
341    partner
342}
343
344/// What was wrong with a token in LocOS text.
345#[derive(Debug, Clone, PartialEq, Eq)]
346pub enum TokenProblem {
347    /// A `\u{27E6}` or `\u{27E7}` that is not part of a well-formed token. Left in the text.
348    Stray {
349        /// Its byte position.
350        at: usize,
351    },
352    /// A well-formed token whose number is not in the map. Left in the text.
353    Unknown {
354        /// The token.
355        token: String,
356    },
357    /// A token whose kind does not fit the map (a closing token for a standalone code, an `x` token for a pair).
358    /// Left in the text.
359    KindMismatch {
360        /// The token.
361        token: String,
362    },
363}
364
365/// LocOS text back to inline codes. Tokens that cannot be resolved stay in the text; see [`parse_locos_text`]
366/// to find out which.
367pub fn from_locos_text(text: &str, map: &LocosMap) -> Vec<Inline> {
368    parse_locos_text(text, map).0
369}
370
371/// Like [`from_locos_text`], and lists every token that could not be resolved.
372pub fn parse_locos_text(text: &str, map: &LocosMap) -> (Vec<Inline>, Vec<TokenProblem>) {
373    parse_tokens(text, map, false, true)
374}
375
376/// Formats whose LocOS filter drops a token of the wrong kind that names one of the unit's codes (a pair token
377/// `\u{27E6}g1\u{27E7}`, `\u{27E6}/g1\u{27E7}` for a point code), where other formats keep it as text: LocOS
378/// `toml_filter._detokenize`, `js_module_filter._render` and `rc_filter._render_literal` (#814.1, g12; rc: B-SIDE W6
379/// rc-2, a pair token for a point code). A token whose number names no code stays
380/// text in every format.
381const LOCOS_DROPS_MISMATCH: &[&str] = &["toml", "js", "rc"];
382
383/// Formats whose LocOS filter reads only `x` as a point letter: a `p` token naming a point code is not that code
384/// (LocOS `dxf_filter._render` takes `x` and `g` only, B-SIDE W6 dxf-1). It is a [`TokenProblem::KindMismatch`]
385/// left in the text, where the format's writer applies LocOS's rule (DXF drops it).
386const LOCOS_NO_FREE_LETTER: &[&str] = &["dxf"];
387
388/// [`parse_locos_text`] with the token rules of `format`'s LocOS filter: for TOML and JavaScript modules a token of
389/// the wrong kind for a code of the unit is dropped (LocOS writes nothing for it) instead of kept as text; it is
390/// still listed as [`TokenProblem::KindMismatch`]. Every other format reads as [`parse_locos_text`].
391pub fn parse_locos_text_for(format: &str, text: &str, map: &LocosMap) -> (Vec<Inline>, Vec<TokenProblem>) {
392    let (inl, problems, _) = repair_locos_text_for(format, text, map);
393    (inl, problems)
394}
395
396/// Formats whose LocOS writer repairs the tags of a translation instead of refusing it (every CAT XML writer:
397/// `cat_xliff._render` for sdlxliff, mqxliff, mxliff, txlf, txml, ttx and the xlz, mqxlz and Trados package
398/// members, `xliff_filter._rebuild_target` for plain XLIFF). W5: the XML writers do the same (`xml_its` render for
399/// generic XML, DITA and DocBook, `xml_resource_common.render_inner` for Android strings and Java XML properties,
400/// `ttml_filter._render`, `angular_xmb_filter._render` for XMB and XTB): a duplicated token is dropped, a stray close
401/// is dropped, a pair left open is closed. MDX (`mdx_filter._rematerialize`) writes every token as it comes, a
402/// repeated one again. See [`repair_locos_text_for`].
403const LOCOS_REPAIRS_TAGS: &[&str] =
404    &["xliff", "sdlxliff", "mqxliff", "mxliff", "txlf", "txml", "ttx", "xlz", "mqxlz", "sdlppx", "xml", "dita", "docbook", "android", "javaxml", "ttml", "xmb", "xtb", "mdx"];
405
406/// The formats of [`LOCOS_REPAIRS_TAGS`] whose Bilingua writer gets the target with every tag as typed: the CAT
407/// writers port LocOS's render rule and apply it after stripping the target's edges; MDX writes each tag as LocOS
408/// does. The other formats get the repaired target.
409const LOCOS_TYPED_TAGS: &[&str] = &["xliff", "sdlxliff", "mqxliff", "mxliff", "txlf", "txml", "ttx", "xlz", "mqxlz", "sdlppx", "mdx"];
410
411/// True when the LocOS writer of `format` repairs a translation's tags ([`repair_locos_text_for`]) rather than
412/// refusing them: the XLIFF family, TXML, TTX, the XLIFF packages, and since W5 the XML formats (generic XML, DITA,
413/// DocBook, Android strings, Java XML properties, TTML, XMB, XTB) and MDX.
414pub fn locos_repairs_tags(format: &str) -> bool {
415    LOCOS_REPAIRS_TAGS.contains(&format)
416}
417
418/// For a format [`locos_repairs_tags`] lists: true when the target is stored with its tags as typed (the writer
419/// applies LocOS's rule itself), false when it is stored repaired ([`repair_tags`]).
420pub(crate) fn locos_keeps_typed_tags(format: &str) -> bool {
421    LOCOS_TYPED_TAGS.contains(&format)
422}
423
424/// One repair [`repair_locos_text_for`] made to a translation's tokens. The text around a token always stays; only
425/// the token's tag is dropped, or a close added.
426#[derive(Debug, Clone, PartialEq, Eq)]
427#[non_exhaustive]
428pub enum TagRepair {
429    /// A token whose code was already written: dropped (a repeated pair keeps its inner text, without the tags).
430    Repeated {
431        /// The token.
432        token: String,
433    },
434    /// A closing token with no open pair of its number on top (or a closing token for a standalone code): dropped.
435    StrayClose {
436        /// The token.
437        token: String,
438    },
439    /// A pair opened and never closed: closed at the end of the segment.
440    Unclosed {
441        /// The opening token.
442        token: String,
443    },
444    /// A pair code written as a point token (`\u{27E6}x1\u{27E7}` for `\u{27E6}g1\u{27E7}`): written empty, its open
445    /// and close tags side by side.
446    PairAsPoint {
447        /// The token.
448        token: String,
449    },
450}
451
452/// [`parse_locos_text_for`] that also lists the tag repairs. For the formats whose LocOS writer repairs tags
453/// ([`locos_repairs_tags`]: the XLIFF family, TXML, TTX, the XLIFF packages) every token whose number is in the map
454/// becomes its tag whatever its letter (a pair named by a point token becomes its open and close side by side, a
455/// closing token for a standalone code a close of its id), repeated or unbalanced as typed: their Bilingua writers
456/// apply LocOS's rule (`cat_xliff._render`) while writing, after the target's edges are stripped, so the white space
457/// next to a dropped tag comes out as LocOS writes it. The rule: a code is written at most once (a repeated pair
458/// loses its tags, its inner text stays in place; a repeated point is dropped); a closing token that does not close
459/// the pair on top is dropped; a pair still open at the end is closed there; a pair named by a point token is
460/// written empty. Every repair the writer will make is listed, so a caller can show it (LocOS's QA flags the same
461/// target through its placeholder check). A token whose number is not in the map stays text, as everywhere. Other
462/// formats: the plain reading, no repairs.
463pub fn repair_locos_text_for(format: &str, text: &str, map: &LocosMap) -> (Vec<Inline>, Vec<TokenProblem>, Vec<TagRepair>) {
464    if locos_repairs_tags(format) {
465        return parse_tokens_repairing(text, map);
466    }
467    let (inl, problems) = parse_tokens(text, map, LOCOS_DROPS_MISMATCH.contains(&format), !LOCOS_NO_FREE_LETTER.contains(&format));
468    (inl, problems, Vec::new())
469}
470
471/// The tag a point token stands for (a standalone code, or an `Open` or `Close` with no partner).
472fn point_tag(code: &LocosCode) -> Inline {
473    match code.unpaired {
474        Some(TagKind::Close) => Inline::Tag { id: code.id.clone(), kind: TagKind::Close, display: code.close.clone().unwrap_or_default(), free: false },
475        Some(TagKind::Open) => Inline::Tag { id: code.id.clone(), kind: TagKind::Open, display: code.open.clone().unwrap_or_default(), free: false },
476        _ => Inline::Tag { id: code.id.clone(), kind: TagKind::Standalone, display: code.open.clone().unwrap_or_default(), free: code.free },
477    }
478}
479
480fn pair_tag(code: &LocosCode, kind: TagKind) -> Inline {
481    let display = if kind == TagKind::Close { code.close.clone() } else { code.open.clone() };
482    Inline::Tag { id: code.id.clone(), kind, display: display.unwrap_or_default(), free: false }
483}
484
485/// The CAT writers' token rule (`cat_xliff._render`), see [`repair_locos_text_for`]: every token as its tag (nothing
486/// dropped, the writer does that), the problems, and the repairs the writer will make.
487fn parse_tokens_repairing(text: &str, map: &LocosMap) -> (Vec<Inline>, Vec<TokenProblem>, Vec<TagRepair>) {
488    let mut out: Vec<Inline> = Vec::new();
489    let mut problems = Vec::new();
490    let mut repairs = Vec::new();
491    let mut lit = String::new();
492    let mut used: std::collections::BTreeSet<String> = Default::default();
493    // the pairs open now: (number, opening token, written); a pair not written (a repeat) only eats its close
494    let mut stack: Vec<(String, String, bool)> = Vec::new();
495    let mut rest = text;
496    let mut pos = 0usize;
497    while let Some(ch) = rest.chars().next() {
498        let len = ch.len_utf8();
499        if ch == OPEN {
500            if let Some((tok_len, closing, letter, num)) = scan_token(rest) {
501                let token = rest[..tok_len].to_string();
502                rest = &rest[tok_len..];
503                pos += tok_len;
504                let Some(code) = map.get(&num) else {
505                    problems.push(TokenProblem::Unknown { token: token.clone() });
506                    lit.push_str(&token);
507                    continue;
508                };
509                if !lit.is_empty() {
510                    out.push(Inline::Text(std::mem::take(&mut lit)));
511                }
512                let code_point = code.letter == POINT_LETTER || code.letter == FREE_LETTER;
513                let typed_point = letter.is_some_and(|l| l == POINT_LETTER || l == FREE_LETTER);
514                if closing {
515                    // a closing token for a standalone code is a close of its id: the writer drops it
516                    out.push(if code_point {
517                        Inline::Tag { id: code.id.clone(), kind: TagKind::Close, display: code.close.clone().unwrap_or_default(), free: false }
518                    } else {
519                        pair_tag(code, TagKind::Close)
520                    });
521                    if !code_point && stack.last().is_some_and(|f| f.0 == num) {
522                        stack.pop();
523                    } else {
524                        repairs.push(TagRepair::StrayClose { token });
525                    }
526                } else if code_point {
527                    out.push(point_tag(code));
528                    if !used.insert(num) {
529                        repairs.push(TagRepair::Repeated { token });
530                    }
531                } else if typed_point {
532                    // written empty (`cat_xliff._render`): an open and a close side by side read the same way
533                    out.push(pair_tag(code, TagKind::Open));
534                    out.push(pair_tag(code, TagKind::Close));
535                    repairs.push(if used.insert(num) { TagRepair::PairAsPoint { token } } else { TagRepair::Repeated { token } });
536                } else {
537                    out.push(pair_tag(code, TagKind::Open));
538                    let first = used.insert(num.clone());
539                    if !first {
540                        repairs.push(TagRepair::Repeated { token: token.clone() });
541                    }
542                    stack.push((num, token, first));
543                }
544                continue;
545            }
546            problems.push(TokenProblem::Stray { at: pos });
547        } else if ch == CLOSE {
548            problems.push(TokenProblem::Stray { at: pos });
549        }
550        lit.push(ch);
551        rest = &rest[len..];
552        pos += len;
553    }
554    if !lit.is_empty() {
555        out.push(Inline::Text(lit));
556    }
557    for (_, token, written) in stack.into_iter().rev() {
558        if written {
559            repairs.push(TagRepair::Unclosed { token });
560        }
561    }
562    (merge_text(out), problems, repairs)
563}
564
565/// The CAT writers' rule ([`repair_locos_text_for`]) on an inline list, for a target given as tags rather than
566/// LocOS text: each source code is written at most as often as the source has it (a repeated pair loses its tags,
567/// its text stays), a close that does not close the pair on top is dropped, a pair left open is closed at the end.
568/// A tag the source lacks is kept, so the model's check still refuses it. With `points` false a standalone code
569/// is never dropped for being repeated (the formats whose writer writes a repeated placeholder each time).
570pub(crate) fn repair_tags(source: &[Inline], target: Vec<Inline>, points: bool) -> Vec<Inline> {
571    use std::collections::HashMap;
572    let partner = pairs(source);
573    let mut pair_allowed: HashMap<&str, usize> = HashMap::new();
574    let mut point_allowed: HashMap<(&str, TagKind), usize> = HashMap::new();
575    let mut close_display: HashMap<&str, &str> = HashMap::new();
576    for (pos, i) in source.iter().enumerate() {
577        let Inline::Tag { id, kind, display, .. } = i else { continue };
578        match (kind, partner[pos]) {
579            (TagKind::Open, Some(_)) => *pair_allowed.entry(id.as_str()).or_default() += 1,
580            (TagKind::Close, Some(_)) => {
581                close_display.entry(id.as_str()).or_insert(display.as_str());
582            }
583            _ => *point_allowed.entry((id.as_str(), *kind)).or_default() += 1,
584        }
585    }
586    let known: std::collections::HashSet<&str> = source.iter().filter_map(|i| if let Inline::Tag { id, .. } = i { Some(id.as_str()) } else { None }).collect();
587    let mut pair_used: HashMap<String, usize> = HashMap::new();
588    let mut point_used: HashMap<(String, TagKind), usize> = HashMap::new();
589    let mut stack: Vec<(String, bool)> = Vec::new();
590    let mut out = Vec::with_capacity(target.len());
591    for i in target {
592        let Inline::Tag { id, kind, .. } = &i else {
593            out.push(i);
594            continue;
595        };
596        let paired = pair_allowed.get(id.as_str()).copied().unwrap_or(0);
597        match kind {
598            TagKind::Open if paired > 0 => {
599                let n = pair_used.entry(id.clone()).or_default();
600                let write = *n < paired;
601                if write {
602                    *n += 1;
603                }
604                stack.push((id.clone(), write));
605                if write {
606                    out.push(i);
607                }
608            }
609            TagKind::Close if paired > 0 && stack.last().is_some_and(|(top, _)| top == id) => {
610                if let Some((_, true)) = stack.pop() {
611                    out.push(i);
612                }
613            }
614            TagKind::Close if paired > 0 && !point_allowed.contains_key(&(id.as_str(), TagKind::Close)) => {}
615            _ => match point_allowed.get(&(id.as_str(), *kind)) {
616                // a code of the source written as another kind (a close for a standalone code): dropped
617                None if known.contains(id.as_str()) => {}
618                // not a code of the source: kept, the model's check names it
619                None => out.push(i),
620                Some(_) if !points => out.push(i),
621                Some(max) => {
622                    let n = point_used.entry((id.clone(), *kind)).or_default();
623                    if *n < *max {
624                        *n += 1;
625                        out.push(i);
626                    }
627                }
628            },
629        }
630    }
631    for (id, written) in stack.into_iter().rev() {
632        if written {
633            let display = close_display.get(id.as_str()).map(|d| d.to_string()).unwrap_or_default();
634            out.push(Inline::Tag { id, kind: TagKind::Close, display, free: false });
635        }
636    }
637    merge_text(out)
638}
639
640fn parse_tokens(text: &str, map: &LocosMap, drop_mismatch: bool, free_letter: bool) -> (Vec<Inline>, Vec<TokenProblem>) {
641    let mut out: Vec<Inline> = Vec::new();
642    let mut problems = Vec::new();
643    let mut lit = String::new();
644    let mut rest = text;
645    let mut pos = 0usize;
646    while let Some(ch) = rest.chars().next() {
647        let len = ch.len_utf8();
648        if ch == OPEN {
649            if let Some((tok_len, closing, letter, num)) = scan_token(rest) {
650                let token = &rest[..tok_len];
651                let found = if free_letter || letter != Some(FREE_LETTER) {
652                    resolve(map, closing, letter, &num)
653                } else if map.contains_key(num.as_str()) {
654                    Resolved::Mismatch
655                } else {
656                    Resolved::Unknown
657                };
658                match found {
659                    Resolved::Tag(t) => {
660                        if !lit.is_empty() {
661                            out.push(Inline::Text(std::mem::take(&mut lit)));
662                        }
663                        out.push(t);
664                    }
665                    Resolved::Unknown => {
666                        problems.push(TokenProblem::Unknown { token: token.to_string() });
667                        lit.push_str(token);
668                    }
669                    Resolved::Mismatch => {
670                        problems.push(TokenProblem::KindMismatch { token: token.to_string() });
671                        if !drop_mismatch {
672                            lit.push_str(token);
673                        }
674                    }
675                }
676                rest = &rest[tok_len..];
677                pos += tok_len;
678                continue;
679            }
680            problems.push(TokenProblem::Stray { at: pos });
681        } else if ch == CLOSE {
682            problems.push(TokenProblem::Stray { at: pos });
683        }
684        lit.push(ch);
685        rest = &rest[len..];
686        pos += len;
687    }
688    if !lit.is_empty() {
689        out.push(Inline::Text(lit));
690    }
691    (merge_text(out), problems)
692}
693
694/// Reads `OPEN [/] [a-z] digits CLOSE` at the start of `s`: (byte length, is closing, letter, number text).
695fn scan_token(s: &str) -> Option<(usize, bool, Option<char>, String)> {
696    let mut it = s.char_indices();
697    let (_, c) = it.next()?;
698    if c != OPEN {
699        return None;
700    }
701    let mut closing = false;
702    let mut letter = None;
703    let mut num = String::new();
704    for (idx, c) in it {
705        match c {
706            '/' if !closing && letter.is_none() && num.is_empty() => closing = true,
707            c if c.is_ascii_lowercase() && letter.is_none() && num.is_empty() => letter = Some(c),
708            c if c.is_ascii_digit() => num.push(c),
709            CLOSE if !num.is_empty() => return Some((idx + CLOSE.len_utf8(), closing, letter, num)),
710            _ => return None,
711        }
712    }
713    None
714}
715
716enum Resolved {
717    Tag(Inline),
718    Unknown,
719    Mismatch,
720}
721
722fn resolve(map: &LocosMap, closing: bool, letter: Option<char>, num: &str) -> Resolved {
723    let Some(code) = map.get(num) else { return Resolved::Unknown };
724    let is_point = code.letter == POINT_LETTER || code.letter == FREE_LETTER;
725    // The letter in the text may differ from the map's only between x and p (a model may normalise it); a
726    // pair letter must agree, and a closing token never belongs to a standalone code.
727    if is_point {
728        if closing || letter.is_some_and(|l| l != POINT_LETTER && l != FREE_LETTER) {
729            return Resolved::Mismatch;
730        }
731        return Resolved::Tag(match code.unpaired {
732            Some(TagKind::Close) => Inline::Tag {
733                id: code.id.clone(),
734                kind: TagKind::Close,
735                display: code.close.clone().unwrap_or_default(),
736                free: false,
737            },
738            Some(TagKind::Open) => Inline::Tag {
739                id: code.id.clone(),
740                kind: TagKind::Open,
741                display: code.open.clone().unwrap_or_default(),
742                free: false,
743            },
744            _ => Inline::Tag {
745                id: code.id.clone(),
746                kind: TagKind::Standalone,
747                display: code.open.clone().unwrap_or_default(),
748                free: code.free,
749            },
750        });
751    }
752    if letter.is_some_and(|l| l == POINT_LETTER || l == FREE_LETTER) {
753        return Resolved::Mismatch;
754    }
755    if closing {
756        Resolved::Tag(Inline::Tag {
757            id: code.id.clone(),
758            kind: TagKind::Close,
759            display: code.close.clone().unwrap_or_default(),
760            free: false,
761        })
762    } else {
763        Resolved::Tag(Inline::Tag {
764            id: code.id.clone(),
765            kind: TagKind::Open,
766            display: code.open.clone().unwrap_or_default(),
767            free: false,
768        })
769    }
770}
771
772/// True when a placeholder names its argument, so its position in a translation is free: `%1$s`, `%(name)s`,
773/// `{name}`, `{0}`, `{{name}}`, `${name}`. False for markup and for unnumbered placeholders (`%s`, `%d`, `{}`),
774/// whose order is the argument order.
775pub fn is_named_placeholder(s: &str) -> bool {
776    let b = s.as_bytes();
777    match b {
778        [b'{', b'{', ..] => s.ends_with("}}") && s.len() > 4,
779        [b'$', b'{', ..] => s.ends_with('}') && s.len() > 3,
780        [b'{', ..] => {
781            let inner = &s[1..s.len().saturating_sub(1)];
782            s.ends_with('}') && !inner.is_empty() && !inner.starts_with(' ')
783        }
784        [b'%', b'(', ..] => s[2..].contains(')'),
785        [b'%', d, ..] if d.is_ascii_digit() => {
786            let digits = s[1..].bytes().take_while(u8::is_ascii_digit).count();
787            s.as_bytes().get(1 + digits) == Some(&b'$')
788        }
789        _ => false,
790    }
791}
792
793/// Hides the token brackets of literal text from a writer that cuts LocOS text at its tokens (the Office writers
794/// of the LocOS profile). `\u{27E6}` becomes U+E000 U+E001 and U+E000 becomes U+E000 U+E000, so the result holds
795/// no token and [`unescape_literal`] gives back the text byte for byte. Shared by the format crates; not part of
796/// the semver API.
797#[doc(hidden)]
798pub fn escape_literal(s: &str) -> String {
799    if !s.contains([OPEN, LIT_MARK]) {
800        return s.to_string();
801    }
802    let mut out = String::with_capacity(s.len() + 8);
803    for c in s.chars() {
804        match c {
805            OPEN => out.push_str("\u{e000}\u{e001}"),
806            LIT_MARK => out.push_str("\u{e000}\u{e000}"),
807            c => out.push(c),
808        }
809    }
810    out
811}
812
813/// The inverse of [`escape_literal`]. A U+E000 that starts no pair (only text that was not escaped holds one)
814/// stays as it is. Not part of the semver API.
815#[doc(hidden)]
816pub fn unescape_literal(s: &str) -> String {
817    if !s.contains(LIT_MARK) {
818        return s.to_string();
819    }
820    let mut out = String::with_capacity(s.len());
821    let mut it = s.chars().peekable();
822    while let Some(c) = it.next() {
823        if c == LIT_MARK {
824            match it.peek() {
825                Some('\u{e001}') => {
826                    it.next();
827                    out.push(OPEN);
828                    continue;
829                }
830                Some(&LIT_MARK) => {
831                    it.next();
832                }
833                _ => {}
834            }
835        }
836        out.push(c);
837    }
838    out
839}
840
841const LIT_MARK: char = '\u{e000}';
842
843#[cfg(test)]
844mod tests {
845    use super::*;
846    use crate::CodeData;
847
848    #[test]
849    fn literal_escape_round_trips_every_short_string() {
850        // every string of up to six characters over the characters that matter: the escape never holds a token
851        // bracket and always comes back byte for byte
852        let alpha = ['\u{27e6}', '\u{27e7}', '\u{e000}', '\u{e001}', 'x', '1'];
853        let mut cur: Vec<String> = vec![String::new()];
854        for _ in 0..6 {
855            let mut next = Vec::new();
856            for s in &cur {
857                for c in alpha {
858                    let mut t = s.clone();
859                    t.push(c);
860                    let e = escape_literal(&t);
861                    assert!(!e.contains('\u{27e6}'), "{t:?}");
862                    assert_eq!(unescape_literal(&e), t, "{t:?}");
863                    next.push(t);
864                }
865            }
866            cur = next;
867        }
868        // the escape of a concatenation is the concatenation of the escapes, so text cut at a token unescapes
869        // piece by piece
870        assert_eq!(escape_literal("a\u{e000}\u{27e6}x1\u{27e7}\u{e001}"), "a\u{e000}\u{e000}\u{e000}\u{e001}x1\u{27e7}\u{e001}");
871        assert_eq!(unescape_literal("lone \u{e000} mark"), "lone \u{e000} mark");
872    }
873
874    #[test]
875    fn docx_tokens_carry_locos_numbers() {
876        let inl = vec![
877            Inline::tag("1", TagKind::Open, "<w:r>"),
878            Inline::text("a"),
879            Inline::tag("1", TagKind::Close, "</w:r>"),
880            Inline::tag("3", TagKind::Standalone, "object"),
881            Inline::tag("2", TagKind::Open, "<w:r>"),
882            Inline::text("b"),
883            Inline::tag("2", TagKind::Close, "</w:r>"),
884        ];
885        let (t, map) = to_locos_text_for("docx", &inl);
886        assert_eq!(t, "\u{27e6}r1\u{27e7}a\u{27e6}/r1\u{27e7}\u{27e6}x3\u{27e7}\u{27e6}r2\u{27e7}b\u{27e6}/r2\u{27e7}");
887        assert_eq!(from_locos_text(&t, &map), inl);
888        // one id-numbering path for docx, pptx and xlsx text boxes; every other format keeps the positional numbering
889        for f in ["docx", "pptx", "xlsx"] {
890            assert_eq!(to_locos_text_for(f, &inl), to_locos_text_numbered(&inl, 'r'), "{f}");
891        }
892        for f in ["xliff", "html", "po", "markdown", "json", "odt", ""] {
893            assert_eq!(to_locos_text_for(f, &inl).0.matches("\u{27e6}x2\u{27e7}").count(), 1, "{f}");
894        }
895        assert_eq!(to_locos_text_for("xliff", &inl).0, "\u{27e6}g1\u{27e7}a\u{27e6}/g1\u{27e7}\u{27e6}x2\u{27e7}\u{27e6}g3\u{27e7}b\u{27e6}/g3\u{27e7}");
896        // a bare xlsx cell has no tags: the rule changes nothing
897        let cell = vec![Inline::text("Total")];
898        assert_eq!(to_locos_text_for("xlsx", &cell), to_locos_text_as(&cell, 'r'));
899        let dup = vec![Inline::tag("1", TagKind::Standalone, "o"), Inline::tag("1", TagKind::Standalone, "o")];
900        assert_eq!(to_locos_text_for("docx", &dup).0, "\u{27e6}x1\u{27e7}\u{27e6}x2\u{27e7}");
901        let odd = vec![Inline::tag("x", TagKind::Standalone, "o"), Inline::tag("07", TagKind::Standalone, "o")];
902        assert_eq!(to_locos_text_for("docx", &odd).0, "\u{27e6}x1\u{27e7}\u{27e6}x2\u{27e7}");
903    }
904
905    /// W4 idml-1 / icml-1: LocOS writes a CharacterStyleRange as an `r` pair and every other wrap as a `g` pair.
906    #[test]
907    fn idml_and_icml_runs_are_r_pairs() {
908        let inl = vec![
909            Inline::tag("1", TagKind::Open, "<CharacterStyleRange>"),
910            Inline::text("bold "),
911            Inline::tag("2", TagKind::Open, "<HyperlinkTextSource>"),
912            Inline::text("link"),
913            Inline::tag("2", TagKind::Close, "</HyperlinkTextSource>"),
914            Inline::tag("3", TagKind::Standalone, "<Br/>"),
915            Inline::tag("1", TagKind::Close, "</CharacterStyleRange>"),
916        ];
917        let mut codes = Codes::new();
918        codes.insert("1", CodeData::paired("<CharacterStyleRange>", "</CharacterStyleRange>").with_label("run"));
919        codes.insert("2", CodeData::paired("<HyperlinkTextSource>", "</HyperlinkTextSource>").with_label("link"));
920        codes.insert("3", CodeData::standalone("<Br/>").with_label("br"));
921        let want = "\u{27e6}r1\u{27e7}bold \u{27e6}g2\u{27e7}link\u{27e6}/g2\u{27e7}\u{27e6}x3\u{27e7}\u{27e6}/r1\u{27e7}";
922        for f in ["idml", "icml"] {
923            let (t, map) = to_locos_text_coded(f, &inl, &codes);
924            assert_eq!(t, want, "{f}");
925            assert_eq!(map["1"].letter, 'r');
926            assert_eq!(from_locos_text(&t, &map), inl, "{f}");
927            // the reader is lenient about a pair's letter (as before): a run written as `g` is still the run
928            let (back, problems) = parse_locos_text(&t.replace("r1", "g1"), &map);
929            assert!(problems.is_empty() && back == inl);
930        }
931        // other formats ignore the labels; without codes every pair is `g`, as before
932        assert_eq!(to_locos_text_coded("odt", &inl, &codes), to_locos_text_for("odt", &inl));
933        assert_eq!(to_locos_text_coded("idml", &inl, &Codes::new()).0.matches("\u{27e6}g").count(), 2);
934    }
935
936    fn sample() -> Vec<Inline> {
937        vec![
938            Inline::text("Hola "),
939            Inline::tag("1", TagKind::Open, "<b>"),
940            Inline::text("mundo"),
941            Inline::tag("1", TagKind::Close, "</b>"),
942            Inline::text(", "),
943            Inline::free_tag("2", "{name}"),
944            Inline::text(" "),
945            Inline::tag("3", TagKind::Standalone, "%s"),
946            Inline::text("."),
947        ]
948    }
949
950    #[test]
951    fn tokens_follow_the_table() {
952        let (t, map) = to_locos_text(&sample());
953        assert_eq!(t, "Hola \u{27E6}g1\u{27E7}mundo\u{27E6}/g1\u{27E7}, \u{27E6}p2\u{27E7} \u{27E6}x3\u{27E7}.");
954        assert_eq!(map.len(), 3);
955        assert_eq!(map["1"].close.as_deref(), Some("</b>"));
956        assert!(map["2"].free && map["2"].letter == 'p');
957        assert!(!map["3"].free && map["3"].letter == 'x');
958    }
959
960    #[test]
961    fn round_trips() {
962        let s = sample();
963        let (t, map) = to_locos_text(&s);
964        assert_eq!(from_locos_text(&t, &map), s);
965        let (t, map) = to_locos_text_as(&s, 'r');
966        assert!(t.contains("\u{27E6}r1\u{27E7}") && t.contains("\u{27E6}/r1\u{27E7}"));
967        assert_eq!(from_locos_text(&t, &map), s);
968    }
969
970    #[test]
971    fn token_look_alikes_in_the_text_are_text() {
972        // the text says "use ⟦x2⟧ and ⟦g1⟧": no real code may take number 1 or 2
973        let inl = vec![
974            Inline::text("Use \u{27E6}x2\u{27E7} and \u{27E6}g1\u{27E7} "),
975            Inline::tag("a", TagKind::Open, "<b>"),
976            Inline::text("here"),
977            Inline::tag("a", TagKind::Close, "</b>"),
978            Inline::tag("b", TagKind::Standalone, "<br/>"),
979        ];
980        for f in ["xliff", "html", "docx"] {
981            let (t, map) = to_locos_text_for(f, &inl);
982            assert!(!map.contains_key("1") && !map.contains_key("2"), "{f}: {map:?}");
983            assert_eq!(from_locos_text(&t, &map), inl, "{f}: {t}");
984            // a translator keeps the text and moves the code
985            let moved = t.replace("here", "HERE");
986            let back = from_locos_text(&moved, &map);
987            assert!(matches!(&back[0], Inline::Text(x) if x.starts_with("Use \u{27E6}x2\u{27E7} and \u{27E6}g1\u{27E7}")), "{f}");
988        }
989        // numbers with gaps: a translator who swaps the codes gets each tag back by its own number
990        let inl = vec![
991            Inline::text("\u{27E6}x2\u{27E7} "),
992            Inline::tag("1", TagKind::Open, "<b>"),
993            Inline::text("one"),
994            Inline::tag("1", TagKind::Close, "</b>"),
995            Inline::tag("3", TagKind::Standalone, "<br/>"),
996            Inline::text("two"),
997        ];
998        for f in ["html", "docx"] {
999            let (t, map) = to_locos_text_for(f, &inl);
1000            let p = locos_pair_letter(f);
1001            let (n_pair, n_point) = (map.iter().find(|(_, c)| c.id == "1").unwrap().0, map.iter().find(|(_, c)| c.id == "3").unwrap().0);
1002            assert!(!map.contains_key("2"), "{f}: {map:?}");
1003            let swapped = format!("\u{27E6}x2\u{27E7} two\u{27E6}x{n_point}\u{27E7}\u{27E6}{p}{n_pair}\u{27E7}one\u{27E6}/{p}{n_pair}\u{27E7}");
1004            let (back, problems) = parse_locos_text(&swapped, &map);
1005            assert_eq!(problems.len(), 1, "{f}: only the look-alike is unknown: {problems:?} ({t})");
1006            assert_eq!(
1007                back,
1008                vec![
1009                    Inline::text("\u{27E6}x2\u{27E7} two"),
1010                    Inline::tag("3", TagKind::Standalone, "<br/>"),
1011                    Inline::tag("1", TagKind::Open, "<b>"),
1012                    Inline::text("one"),
1013                    Inline::tag("1", TagKind::Close, "</b>"),
1014                ],
1015                "{f}"
1016            );
1017        }
1018        // a letterless look-alike ("⟦1⟧") also keeps its number free
1019        let inl = vec![Inline::text("\u{27E6}1\u{27E7} "), Inline::tag("a", TagKind::Standalone, "<br/>")];
1020        let (t, map) = to_locos_text(&inl);
1021        assert_eq!(t, "\u{27E6}1\u{27E7} \u{27E6}x2\u{27E7}");
1022        assert_eq!(from_locos_text(&t, &map), inl);
1023    }
1024
1025    #[test]
1026    fn bad_pair_letter_falls_back() {
1027        let (t, _) = to_locos_text_as(&sample(), 'x');
1028        assert!(t.contains("\u{27E6}g1\u{27E7}"));
1029        let (t, _) = to_locos_text_as(&sample(), 'G');
1030        assert!(t.contains("\u{27E6}g1\u{27E7}"));
1031    }
1032
1033    #[test]
1034    fn reordered_free_tokens_come_back_by_number() {
1035        let (_, map) = to_locos_text(&[Inline::free_tag("a", "%1$s"), Inline::text(" y "), Inline::free_tag("b", "%2$s")]);
1036        let back = from_locos_text("\u{27E6}p2\u{27E7} \u{27E6}p1\u{27E7}", &map);
1037        assert_eq!(back[0], Inline::free_tag("b", "%2$s"));
1038        assert_eq!(back[2], Inline::free_tag("a", "%1$s"));
1039    }
1040
1041    #[test]
1042    fn unmatched_close_and_open_survive() {
1043        let s = vec![
1044            Inline::tag("9", TagKind::Close, "</i>"),
1045            Inline::text("x"),
1046            Inline::tag("8", TagKind::Open, "<u>"),
1047            Inline::text("y"),
1048        ];
1049        let (t, map) = to_locos_text(&s);
1050        assert_eq!(t, "\u{27E6}x1\u{27E7}x\u{27E6}x2\u{27E7}y");
1051        assert!(well_formed(&t));
1052        assert_eq!(map["1"].unpaired, Some(TagKind::Close));
1053        assert_eq!(from_locos_text(&t, &map), s);
1054        // The map keeps the side through JSON.
1055        let back: LocosMap = serde_json::from_str(&serde_json::to_string(&map).unwrap()).unwrap();
1056        assert_eq!(from_locos_text(&t, &back), s);
1057    }
1058
1059    /// LocOS `placeholders_well_formed`: pairs nest by number, point letters (x, p) never pair.
1060    fn well_formed(t: &str) -> bool {
1061        let mut stack = Vec::new();
1062        for tok in t.split('\u{27E6}').skip(1) {
1063            let tok = tok.split('\u{27E7}').next().unwrap_or_default();
1064            if let Some(rest) = tok.strip_prefix('/') {
1065                let key = rest.trim_start_matches(|c: char| c.is_ascii_lowercase());
1066                if stack.pop() != Some(key.to_string()) {
1067                    return false;
1068                }
1069            } else if !tok.starts_with(['x', 'p']) {
1070                stack.push(tok.trim_start_matches(|c: char| c.is_ascii_lowercase()).to_string());
1071            }
1072        }
1073        stack.is_empty()
1074    }
1075
1076    #[test]
1077    fn crossed_pairs_become_well_formed() {
1078        let s = vec![
1079            Inline::tag("a", TagKind::Open, "<b>"),
1080            Inline::text("1"),
1081            Inline::tag("b", TagKind::Open, "<i>"),
1082            Inline::text("2"),
1083            Inline::tag("a", TagKind::Close, "</b>"),
1084            Inline::text("3"),
1085            Inline::tag("b", TagKind::Close, "</i>"),
1086        ];
1087        let (t, map) = to_locos_text(&s);
1088        assert_eq!(t, "\u{27E6}g1\u{27E7}1\u{27E6}x2\u{27E7}2\u{27E6}/g1\u{27E7}3\u{27E6}x3\u{27E7}");
1089        assert!(well_formed(&t));
1090        assert_eq!(from_locos_text(&t, &map), s);
1091    }
1092
1093    #[test]
1094    fn html_keeps_its_own_tokens() {
1095        // LocOS html_filter: an open with no close is a pair token, crossed pairs keep their numbers
1096        let s = vec![
1097            Inline::tag("1", TagKind::Open, "<a>"),
1098            Inline::text("Hi "),
1099            Inline::tag("2", TagKind::Open, "<b>"),
1100            Inline::text("1"),
1101            Inline::tag("3", TagKind::Open, "<i>"),
1102            Inline::text("2"),
1103            Inline::tag("2", TagKind::Close, "</b>"),
1104            Inline::text("3"),
1105            Inline::tag("3", TagKind::Close, "</i>"),
1106            Inline::tag("4", TagKind::Standalone, "<br>"),
1107            Inline::tag("9", TagKind::Close, "</u>"),
1108        ];
1109        let (t, map) = to_locos_text_for("html", &s);
1110        assert_eq!(
1111            t,
1112            "\u{27E6}g1\u{27E7}Hi \u{27E6}g2\u{27E7}1\u{27E6}g3\u{27E7}2\u{27E6}/g2\u{27E7}3\u{27E6}/g3\u{27E7}\u{27E6}x4\u{27E7}\u{27E6}x5\u{27E7}"
1113        );
1114        assert_eq!(map["1"].letter, 'g');
1115        assert_eq!(map["1"].close, None);
1116        assert_eq!(from_locos_text(&t, &map), s);
1117        // the other formats keep the well-formed conversion, with their pair letter
1118        assert_eq!(to_locos_text_for("md", &s), to_locos_text_as(&s, 'g'));
1119        assert_eq!(to_locos_text_for("docx", &s), to_locos_text_as(&s, 'r'));
1120    }
1121
1122    #[test]
1123    fn html_family_formats_keep_an_open_with_no_close_a_pair_token() {
1124        // `<a><span>&nbsp;</span>` then a block child: the `<a>` closes in a later unit
1125        let s = vec![
1126            Inline::tag("1", TagKind::Open, "<a>"),
1127            Inline::tag("2", TagKind::Open, "<span>"),
1128            Inline::text("&nbsp;"),
1129            Inline::tag("2", TagKind::Close, "</span>"),
1130        ];
1131        for f in ["html", "aspx", "erb", "shtml", "jsp", "phtml", "epub", "eml"] {
1132            let (t, map) = to_locos_text_for(f, &s);
1133            assert_eq!(t, "\u{27E6}g1\u{27E7}\u{27E6}g2\u{27E7}&nbsp;\u{27E6}/g2\u{27E7}", "{f}");
1134            assert_eq!(from_locos_text(&t, &map), s, "{f}");
1135        }
1136        // a format outside the family keeps the well-formed conversion
1137        assert!(to_locos_text_for("md", &s).0.starts_with("\u{27E6}x1\u{27E7}"));
1138    }
1139
1140    #[test]
1141    fn nested_and_repeated_ids() {
1142        let s = vec![
1143            Inline::tag("a", TagKind::Open, "<b>"),
1144            Inline::tag("b", TagKind::Open, "<i>"),
1145            Inline::text("t"),
1146            Inline::tag("b", TagKind::Close, "</i>"),
1147            Inline::tag("a", TagKind::Close, "</b>"),
1148            Inline::tag("a", TagKind::Open, "<b>"),
1149            Inline::text("u"),
1150            Inline::tag("a", TagKind::Close, "</b>"),
1151        ];
1152        let (t, map) = to_locos_text(&s);
1153        assert_eq!(map.len(), 3);
1154        assert!(well_formed(&t));
1155        assert_eq!(from_locos_text(&t, &map), s);
1156    }
1157
1158    #[test]
1159    fn malformed_tokens_stay_as_text_and_are_reported() {
1160        let (_, map) = to_locos_text(&sample());
1161        for bad in [
1162            "a \u{27E6} b",
1163            "a \u{27E7} b",
1164            "\u{27E6}g\u{27E7}",
1165            "\u{27E6}g1",
1166            "\u{27E6}/\u{27E6}g1\u{27E7}",
1167            "\u{27E6}G1\u{27E7}",
1168            "\u{27E6}x1{limit}\u{27E7}",
1169            "\u{27E6}g99\u{27E7}",
1170            "\u{27E6}/x3\u{27E7}",
1171            "\u{27E6}x1\u{27E7}",
1172        ] {
1173            let (inl, problems) = parse_locos_text(bad, &map);
1174            let rebuilt: String = inl
1175                .iter()
1176                .map(|i| match i {
1177                    Inline::Text(t) => t.clone(),
1178                    Inline::Tag { .. } => String::from("#"),
1179                })
1180                .collect();
1181            if bad == "\u{27E6}x1\u{27E7}" {
1182                // x1 is a pair in the map: a point token for a pair is a mismatch.
1183                assert!(problems.iter().any(|p| matches!(p, TokenProblem::KindMismatch { .. })), "{bad}");
1184            } else {
1185                assert!(!problems.is_empty(), "{bad:?} gave no problem");
1186            }
1187            assert!(rebuilt.contains('\u{27E6}') || rebuilt.contains('\u{27E7}') || bad.contains("g1\u{27E7}"), "{bad:?} lost text");
1188        }
1189    }
1190
1191    #[test]
1192    fn text_in_every_language_survives() {
1193        for t in [
1194            "Hello", "Hola", "Bonjour", "Ciao", "Hallo", "Hallo", "Ola", "\u{3053}\u{3093}\u{306b}\u{3061}\u{306f}",
1195            "\u{4f60}\u{597d}", "\u{c548}\u{b155}", "\u{645}\u{631}\u{62d}\u{628}\u{627}",
1196        ] {
1197            let s = vec![Inline::tag("1", TagKind::Open, "<b>"), Inline::text(t), Inline::tag("1", TagKind::Close, "</b>"), Inline::free_tag("2", "{0}")];
1198            let (x, map) = to_locos_text(&s);
1199            assert_eq!(from_locos_text(&x, &map), s);
1200        }
1201    }
1202
1203    #[test]
1204    fn numbered_by_id_like_locos_pptx() {
1205        // LocOS's PPTX numbering: runs r1, r2 first, the break and the field after them
1206        let s = vec![
1207            Inline::tag("1", TagKind::Open, "<a:r>"),
1208            Inline::text("a"),
1209            Inline::tag("1", TagKind::Close, "</a:r>"),
1210            Inline::tag("3", TagKind::Standalone, "<a:br/>"),
1211            Inline::tag("2", TagKind::Open, "<a:r>"),
1212            Inline::text("b"),
1213            Inline::tag("2", TagKind::Close, "</a:r>"),
1214            Inline::tag("4", TagKind::Standalone, "<a:fld/>"),
1215        ];
1216        let (t, map) = to_locos_text_numbered(&s, 'r');
1217        assert_eq!(t, "\u{27E6}r1\u{27E7}a\u{27E6}/r1\u{27E7}\u{27E6}x3\u{27E7}\u{27E6}r2\u{27E7}b\u{27E6}/r2\u{27E7}\u{27E6}x4\u{27E7}");
1218        assert!(well_formed(&t));
1219        assert_eq!(from_locos_text(&t, &map), s);
1220        // ids that are not usable token numbers: reading order, exactly as to_locos_text_as
1221        for bad in [
1222            vec![Inline::tag("a", TagKind::Standalone, "x")],
1223            vec![Inline::tag("0", TagKind::Standalone, "x")],
1224            vec![Inline::tag("01", TagKind::Standalone, "x")],
1225            vec![Inline::tag("+2", TagKind::Standalone, "x")],
1226            vec![Inline::tag("2", TagKind::Standalone, "x"), Inline::tag("2", TagKind::Standalone, "y")],
1227            vec![Inline::tag("9", TagKind::Open, "x"), Inline::tag("9", TagKind::Open, "y")],
1228            vec![Inline::tag("99999999999999999999999", TagKind::Standalone, "x")],
1229        ] {
1230            assert_eq!(to_locos_text_numbered(&bad, 'r'), to_locos_text_as(&bad, 'r'), "{bad:?}");
1231        }
1232        assert_eq!(to_locos_text_numbered(&sample(), 'g'), to_locos_text(&sample()));
1233        assert_eq!(to_locos_text_numbered(&[], 'r'), (String::new(), LocosMap::new()));
1234        // the per-format entry point picks it for pptx
1235        assert_eq!(to_locos_text_for("pptx", &s), (t, map));
1236    }
1237
1238    #[test]
1239    fn empty_and_tagless() {
1240        let (t, m) = to_locos_text(&[]);
1241        assert!(t.is_empty() && m.is_empty());
1242        assert!(from_locos_text("", &m).is_empty());
1243        assert_eq!(from_locos_text("plain", &m), vec![Inline::text("plain")]);
1244    }
1245
1246    #[test]
1247    fn named_placeholders() {
1248        for yes in ["%1$s", "%12$d", "%(name)s", "{name}", "{0}", "{{count}}", "${user}"] {
1249            assert!(is_named_placeholder(yes), "{yes}");
1250        }
1251        for no in ["%s", "%d", "%.2f", "{}", "{ x }", "<b>", "%%", "%5d", "{{}}", "${}", "%(x"] {
1252            assert!(!is_named_placeholder(no), "{no}");
1253        }
1254    }
1255
1256    /// #814.1 (g12): TOML and JS drop a pair token naming a point code; an unknown number stays text; other
1257    /// formats keep the wrong-kind token as text.
1258    #[test]
1259    fn wrong_kind_tokens_are_dropped_for_toml_and_js() {
1260        let src = vec![Inline::text("Reading time "), Inline::tag("1", TagKind::Standalone, "{{ .Count }}"), Inline::text(" min")];
1261        let (_, map) = to_locos_text(&src);
1262        let t = "Lesezeit \u{27E6}x9\u{27E7} \u{27E6}g1\u{27E7}Min\u{27E6}/g1\u{27E7} \u{27E6}x1\u{27E7}";
1263        // rc (B-SIDE W6 rc-2): LocOS `rc_filter._render_literal` drops a pair token for a point code the same way
1264        for f in ["toml", "js", "rc"] {
1265            let (inl, problems) = parse_locos_text_for(f, t, &map);
1266            assert_eq!(
1267                inl,
1268                vec![Inline::text("Lesezeit \u{27E6}x9\u{27E7} Min "), Inline::tag("1", TagKind::Standalone, "{{ .Count }}")],
1269                "{f}"
1270            );
1271            assert_eq!(problems.iter().filter(|p| matches!(p, TokenProblem::KindMismatch { .. })).count(), 2, "{f}");
1272            assert!(problems.contains(&TokenProblem::Unknown { token: "\u{27E6}x9\u{27E7}".into() }), "{f}");
1273        }
1274        let (kept, _) = parse_locos_text_for("json", t, &map);
1275        assert_eq!(kept, parse_locos_text(t, &map).0);
1276        assert!(matches!(&kept[0], Inline::Text(x) if x.contains("\u{27E6}g1\u{27E7}Min")));
1277    }
1278
1279    /// B-SIDE W6 dxf-1: DXF reads only `x` as a point letter; `p` naming a point code is a kind mismatch left in the
1280    /// text (the DXF writer drops it as LocOS does), where every other format reads `p` as the point.
1281    #[test]
1282    fn dxf_does_not_read_p_as_a_point() {
1283        let src = vec![Inline::text("a"), Inline::tag("1", TagKind::Standalone, "%%d")];
1284        let (_, map) = to_locos_text(&src);
1285        let t = "a%\u{27E6}p1\u{27E7}%b\u{27E6}x1\u{27E7}";
1286        let (inl, problems) = parse_locos_text_for("dxf", t, &map);
1287        assert_eq!(inl, vec![Inline::text("a%\u{27E6}p1\u{27E7}%b"), Inline::tag("1", TagKind::Standalone, "%%d")]);
1288        assert_eq!(problems, vec![TokenProblem::KindMismatch { token: "\u{27E6}p1\u{27E7}".into() }]);
1289        // a `p` token naming no code is unknown, as everywhere
1290        let (_, problems) = parse_locos_text_for("dxf", "\u{27E6}p7\u{27E7}", &map);
1291        assert_eq!(problems, vec![TokenProblem::Unknown { token: "\u{27E6}p7\u{27E7}".into() }]);
1292        let (inl, problems) = parse_locos_text_for("txt", t, &map);
1293        assert!(problems.is_empty() && inl.iter().filter(|i| matches!(i, Inline::Tag { .. })).count() == 2);
1294    }
1295
1296    /// B-SIDE 8: the CAT writers' rule (LocOS `cat_xliff._render`): a repeated pair loses its tags and keeps its
1297    /// text, a stray close is dropped, an unclosed pair is closed at the end, a pair named by a point token is
1298    /// written empty, a repeated point is dropped; each repair is listed. Other formats read as before.
1299    #[test]
1300    fn cat_formats_repair_tags_like_locos() {
1301        let open = Inline::tag("1", TagKind::Open, "<g id=\"1\">");
1302        let close = Inline::tag("1", TagKind::Close, "</g>");
1303        let x = Inline::tag("2", TagKind::Standalone, "<x id=\"2\"/>");
1304        let src = vec![Inline::text("Click "), open.clone(), Inline::text("here"), close.clone(), x.clone()];
1305        let (text, map) = to_locos_text(&src);
1306        assert_eq!(text, "Click \u{27E6}g1\u{27E7}here\u{27E6}/g1\u{27E7}\u{27E6}x2\u{27E7}");
1307        let cases: Vec<(&str, Vec<Inline>, Vec<&str>)> = vec![
1308            // verify_filter_roundtrip_509: the second frame loses its tags, its text stays in place
1309            (
1310                "bitte \u{27E6}g1\u{27E7}Klick\u{27E6}/g1\u{27E7} hier \u{27E6}g1\u{27E7}doppelt\u{27E6}/g1\u{27E7} jetzt",
1311                vec![Inline::text("bitte "), open.clone(), Inline::text("Klick"), close.clone(), Inline::text(" hier doppelt jetzt")],
1312                vec!["repeated"],
1313            ),
1314            // verify_cat_xliff_filter 165: an open used again with no close of its own is dropped, the pair closed at the end
1315            (
1316                "\u{27E6}g1\u{27E7}A \u{27E6}x2\u{27E7}B \u{27E6}g1\u{27E7}C",
1317                vec![open.clone(), Inline::text("A "), x.clone(), Inline::text("B C"), close.clone()],
1318                vec!["repeated", "unclosed"],
1319            ),
1320            ("\u{27E6}/g1\u{27E7}Hi \u{27E6}/x2\u{27E7}", vec![Inline::text("Hi ")], vec!["stray_close", "stray_close"]),
1321            ("Hi \u{27E6}x1\u{27E7} you", vec![Inline::text("Hi "), open.clone(), close.clone(), Inline::text(" you")], vec!["pair_as_point"]),
1322            ("\u{27E6}x2\u{27E7}a\u{27E6}x2\u{27E7}b\u{27E6}g2\u{27E7}", vec![x.clone(), Inline::text("ab")], vec!["repeated", "repeated"]),
1323            // the letter does not matter, only the number: a close typed with a point letter closes the pair
1324            ("\u{27E6}g1\u{27E7}a\u{27E6}/x1\u{27E7}", vec![open.clone(), Inline::text("a"), close.clone()], vec![]),
1325            // a number the map lacks stays text
1326            ("a \u{27E6}g9\u{27E7}", vec![Inline::text("a \u{27E6}g9\u{27E7}")], vec![]),
1327        ];
1328        for (t, want, kinds) in cases {
1329            for f in ["sdlxliff", "xliff", "mqxliff", "mxliff", "txlf", "txml", "ttx", "xlz", "mqxlz", "sdlppx"] {
1330                let (inl, _, repairs) = repair_locos_text_for(f, t, &map);
1331                // every token stays a tag (the writer applies the rule); the rule on the inlines gives LocOS's result
1332                assert_eq!(repair_tags(&src, inl.clone(), true), want, "{f}: {t}");
1333                let got: Vec<&str> = repairs
1334                    .iter()
1335                    .map(|r| match r {
1336                        TagRepair::Repeated { .. } => "repeated",
1337                        TagRepair::StrayClose { .. } => "stray_close",
1338                        TagRepair::Unclosed { .. } => "unclosed",
1339                        TagRepair::PairAsPoint { .. } => "pair_as_point",
1340                    })
1341                    .collect();
1342                assert_eq!(got, kinds, "{f}: {t}");
1343                // the inline repair leaves a repaired target as it is
1344                assert_eq!(repair_tags(&src, want.clone(), true), want, "{f}: {t}");
1345                assert_eq!(parse_locos_text_for(f, t, &map).0, inl, "{f}: {t}");
1346            }
1347            let (plain, _, none) = repair_locos_text_for("json", t, &map);
1348            assert!(none.is_empty());
1349            assert_eq!(plain, parse_locos_text(t, &map).0);
1350        }
1351    }
1352
1353    /// The inline repair (a target given as tags): the same rule by id; a source that repeats an id may repeat it
1354    /// as often; an invented tag is kept for the model's check.
1355    #[test]
1356    fn inline_targets_are_repaired_by_id() {
1357        let open = Inline::tag("1", TagKind::Open, "<b>");
1358        let close = Inline::tag("1", TagKind::Close, "</b>");
1359        let src = vec![open.clone(), Inline::text("a"), close.clone()];
1360        let t = vec![open.clone(), Inline::text("x"), close.clone(), open.clone(), Inline::text("y"), close.clone(), close.clone(), open.clone()];
1361        assert_eq!(repair_tags(&src, t, true), vec![open.clone(), Inline::text("x"), close.clone(), Inline::text("y")]);
1362        assert_eq!(repair_tags(&src, vec![open.clone(), Inline::text("z")], true), vec![open.clone(), Inline::text("z"), close.clone()]);
1363        let twice = vec![open.clone(), Inline::text("a"), close.clone(), open.clone(), Inline::text("b"), close.clone()];
1364        assert_eq!(repair_tags(&twice, twice.clone(), true), twice);
1365        let invented = vec![Inline::tag("9", TagKind::Standalone, "<hr/>")];
1366        assert_eq!(repair_tags(&src, invented.clone(), true), invented);
1367    }
1368
1369    /// `pairs` as it was written before the per-id index: a close pairs with the nearest open of its id still on
1370    /// the stack and drops the opens above it.
1371    fn pairs_by_scan(inl: &[Inline]) -> Vec<Option<usize>> {
1372        let mut partner = vec![None; inl.len()];
1373        let mut stack: Vec<(&str, usize)> = Vec::new();
1374        for (pos, i) in inl.iter().enumerate() {
1375            match i {
1376                Inline::Tag { id, kind: TagKind::Open, .. } => stack.push((id.as_str(), pos)),
1377                Inline::Tag { id, kind: TagKind::Close, .. } => {
1378                    if let Some(at) = stack.iter().rposition(|(oid, _)| oid == id) {
1379                        let (_, o) = stack[at];
1380                        stack.truncate(at);
1381                        partner[o] = Some(pos);
1382                        partner[pos] = Some(o);
1383                    }
1384                }
1385                _ => {}
1386            }
1387        }
1388        partner
1389    }
1390
1391    /// Resource limits (security review run 2): tens of thousands of opens followed by as many closes of an id
1392    /// that is not open scanned the whole stack per close. The index pairs exactly as the scan did.
1393    #[test]
1394    fn locos_tokens_of_many_unmatched_closes_are_linear() {
1395        let n = 50_000;
1396        let mut inl: Vec<Inline> = (0..n).map(|k| Inline::tag(format!("a{k}"), TagKind::Open, "")).collect();
1397        inl.extend((0..n).map(|_| Inline::tag("z", TagKind::Close, "")));
1398        let start = std::time::Instant::now();
1399        let (text, _) = to_locos_text(&inl);
1400        assert!(start.elapsed().as_secs() < 10, "took {:?}", start.elapsed());
1401        assert!(!text.is_empty());
1402        // every sequence of up to seven opens and closes over three ids pairs as before
1403        let tags = [("1", TagKind::Open), ("1", TagKind::Close), ("2", TagKind::Open), ("2", TagKind::Close), ("3", TagKind::Open), ("3", TagKind::Close)];
1404        let mut cur: Vec<Vec<Inline>> = vec![Vec::new()];
1405        for _ in 0..7 {
1406            let mut next = Vec::new();
1407            for v in &cur {
1408                for (id, k) in tags {
1409                    let mut w = v.clone();
1410                    w.push(Inline::tag(id, k, ""));
1411                    assert_eq!(pairs(&w), pairs_by_scan(&w), "{w:?}");
1412                    next.push(w);
1413                }
1414            }
1415            cur = next;
1416        }
1417    }
1418}