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, CodeData, 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: &BTreeMap<String, CodeData>) -> (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    let mut stack: Vec<(&str, usize)> = Vec::new();
292    for (pos, i) in inl.iter().enumerate() {
293        match i {
294            Inline::Tag { id, kind: TagKind::Open, .. } => stack.push((id.as_str(), pos)),
295            Inline::Tag { id, kind: TagKind::Close, .. } => {
296                if let Some(at) = stack.iter().rposition(|(oid, _)| oid == id) {
297                    let (_, o) = stack[at];
298                    stack.truncate(at);
299                    partner[o] = Some(pos);
300                    partner[pos] = Some(o);
301                }
302            }
303            _ => {}
304        }
305    }
306    partner
307}
308
309/// Like [`pairs`], the way LocOS's HTML filter pairs its tags: a close pairs with the latest open of its id still
310/// open, wherever it is on the stack (pairs may cross); an open never closed is its own partner (a pair token with
311/// no closing one). A close with no open is unpaired.
312fn pairs_by_id(inl: &[Inline]) -> Vec<Option<usize>> {
313    let mut partner = vec![None; inl.len()];
314    // the opens still open, per id: one pass whatever the nesting
315    let mut open: BTreeMap<&str, Vec<usize>> = BTreeMap::new();
316    for (pos, i) in inl.iter().enumerate() {
317        match i {
318            Inline::Tag { id, kind: TagKind::Open, .. } => {
319                partner[pos] = Some(pos);
320                open.entry(id.as_str()).or_default().push(pos);
321            }
322            Inline::Tag { id, kind: TagKind::Close, .. } => {
323                if let Some(o) = open.get_mut(id.as_str()).and_then(Vec::pop) {
324                    partner[o] = Some(pos);
325                    partner[pos] = Some(o);
326                }
327            }
328            _ => {}
329        }
330    }
331    partner
332}
333
334/// What was wrong with a token in LocOS text.
335#[derive(Debug, Clone, PartialEq, Eq)]
336pub enum TokenProblem {
337    /// A `\u{27E6}` or `\u{27E7}` that is not part of a well-formed token. Left in the text.
338    Stray {
339        /// Its byte position.
340        at: usize,
341    },
342    /// A well-formed token whose number is not in the map. Left in the text.
343    Unknown {
344        /// The token.
345        token: String,
346    },
347    /// A token whose kind does not fit the map (a closing token for a standalone code, an `x` token for a pair).
348    /// Left in the text.
349    KindMismatch {
350        /// The token.
351        token: String,
352    },
353}
354
355/// LocOS text back to inline codes. Tokens that cannot be resolved stay in the text; see [`parse_locos_text`]
356/// to find out which.
357pub fn from_locos_text(text: &str, map: &LocosMap) -> Vec<Inline> {
358    parse_locos_text(text, map).0
359}
360
361/// Like [`from_locos_text`], and lists every token that could not be resolved.
362pub fn parse_locos_text(text: &str, map: &LocosMap) -> (Vec<Inline>, Vec<TokenProblem>) {
363    parse_tokens(text, map, false, true)
364}
365
366/// Formats whose LocOS filter drops a token of the wrong kind that names one of the unit's codes (a pair token
367/// `\u{27E6}g1\u{27E7}`, `\u{27E6}/g1\u{27E7}` for a point code), where other formats keep it as text: LocOS
368/// `toml_filter._detokenize`, `js_module_filter._render` and `rc_filter._render_literal` (#814.1, g12; rc: B-SIDE W6
369/// rc-2, a pair token for a point code). A token whose number names no code stays
370/// text in every format.
371const LOCOS_DROPS_MISMATCH: &[&str] = &["toml", "js", "rc"];
372
373/// Formats whose LocOS filter reads only `x` as a point letter: a `p` token naming a point code is not that code
374/// (LocOS `dxf_filter._render` takes `x` and `g` only, B-SIDE W6 dxf-1). It is a [`TokenProblem::KindMismatch`]
375/// left in the text, where the format's writer applies LocOS's rule (DXF drops it).
376const LOCOS_NO_FREE_LETTER: &[&str] = &["dxf"];
377
378/// [`parse_locos_text`] with the token rules of `format`'s LocOS filter: for TOML and JavaScript modules a token of
379/// the wrong kind for a code of the unit is dropped (LocOS writes nothing for it) instead of kept as text; it is
380/// still listed as [`TokenProblem::KindMismatch`]. Every other format reads as [`parse_locos_text`].
381pub fn parse_locos_text_for(format: &str, text: &str, map: &LocosMap) -> (Vec<Inline>, Vec<TokenProblem>) {
382    let (inl, problems, _) = repair_locos_text_for(format, text, map);
383    (inl, problems)
384}
385
386/// Formats whose LocOS writer repairs the tags of a translation instead of refusing it (every CAT XML writer:
387/// `cat_xliff._render` for sdlxliff, mqxliff, mxliff, txlf, txml, ttx and the xlz, mqxlz and Trados package
388/// members, `xliff_filter._rebuild_target` for plain XLIFF). W5: the XML writers do the same (`xml_its` render for
389/// generic XML, DITA and DocBook, `xml_resource_common.render_inner` for Android strings and Java XML properties,
390/// `ttml_filter._render`, `angular_xmb_filter._render` for XMB and XTB): a duplicated token is dropped, a stray close
391/// is dropped, a pair left open is closed. MDX (`mdx_filter._rematerialize`) writes every token as it comes, a
392/// repeated one again. See [`repair_locos_text_for`].
393const LOCOS_REPAIRS_TAGS: &[&str] =
394    &["xliff", "sdlxliff", "mqxliff", "mxliff", "txlf", "txml", "ttx", "xlz", "mqxlz", "sdlppx", "xml", "dita", "docbook", "android", "javaxml", "ttml", "xmb", "xtb", "mdx"];
395
396/// The formats of [`LOCOS_REPAIRS_TAGS`] whose Bilingua writer gets the target with every tag as typed: the CAT
397/// writers port LocOS's render rule and apply it after stripping the target's edges; MDX writes each tag as LocOS
398/// does. The other formats get the repaired target.
399const LOCOS_TYPED_TAGS: &[&str] = &["xliff", "sdlxliff", "mqxliff", "mxliff", "txlf", "txml", "ttx", "xlz", "mqxlz", "sdlppx", "mdx"];
400
401/// True when the LocOS writer of `format` repairs a translation's tags ([`repair_locos_text_for`]) rather than
402/// refusing them: the XLIFF family, TXML, TTX, the XLIFF packages, and since W5 the XML formats (generic XML, DITA,
403/// DocBook, Android strings, Java XML properties, TTML, XMB, XTB) and MDX.
404pub fn locos_repairs_tags(format: &str) -> bool {
405    LOCOS_REPAIRS_TAGS.contains(&format)
406}
407
408/// For a format [`locos_repairs_tags`] lists: true when the target is stored with its tags as typed (the writer
409/// applies LocOS's rule itself), false when it is stored repaired ([`repair_tags`]).
410pub(crate) fn locos_keeps_typed_tags(format: &str) -> bool {
411    LOCOS_TYPED_TAGS.contains(&format)
412}
413
414/// One repair [`repair_locos_text_for`] made to a translation's tokens. The text around a token always stays; only
415/// the token's tag is dropped, or a close added.
416#[derive(Debug, Clone, PartialEq, Eq)]
417#[non_exhaustive]
418pub enum TagRepair {
419    /// A token whose code was already written: dropped (a repeated pair keeps its inner text, without the tags).
420    Repeated {
421        /// The token.
422        token: String,
423    },
424    /// A closing token with no open pair of its number on top (or a closing token for a standalone code): dropped.
425    StrayClose {
426        /// The token.
427        token: String,
428    },
429    /// A pair opened and never closed: closed at the end of the segment.
430    Unclosed {
431        /// The opening token.
432        token: String,
433    },
434    /// A pair code written as a point token (`\u{27E6}x1\u{27E7}` for `\u{27E6}g1\u{27E7}`): written empty, its open
435    /// and close tags side by side.
436    PairAsPoint {
437        /// The token.
438        token: String,
439    },
440}
441
442/// [`parse_locos_text_for`] that also lists the tag repairs. For the formats whose LocOS writer repairs tags
443/// ([`locos_repairs_tags`]: the XLIFF family, TXML, TTX, the XLIFF packages) every token whose number is in the map
444/// becomes its tag whatever its letter (a pair named by a point token becomes its open and close side by side, a
445/// closing token for a standalone code a close of its id), repeated or unbalanced as typed: their Bilingua writers
446/// apply LocOS's rule (`cat_xliff._render`) while writing, after the target's edges are stripped, so the white space
447/// next to a dropped tag comes out as LocOS writes it. The rule: a code is written at most once (a repeated pair
448/// loses its tags, its inner text stays in place; a repeated point is dropped); a closing token that does not close
449/// the pair on top is dropped; a pair still open at the end is closed there; a pair named by a point token is
450/// written empty. Every repair the writer will make is listed, so a caller can show it (LocOS's QA flags the same
451/// target through its placeholder check). A token whose number is not in the map stays text, as everywhere. Other
452/// formats: the plain reading, no repairs.
453pub fn repair_locos_text_for(format: &str, text: &str, map: &LocosMap) -> (Vec<Inline>, Vec<TokenProblem>, Vec<TagRepair>) {
454    if locos_repairs_tags(format) {
455        return parse_tokens_repairing(text, map);
456    }
457    let (inl, problems) = parse_tokens(text, map, LOCOS_DROPS_MISMATCH.contains(&format), !LOCOS_NO_FREE_LETTER.contains(&format));
458    (inl, problems, Vec::new())
459}
460
461/// The tag a point token stands for (a standalone code, or an `Open` or `Close` with no partner).
462fn point_tag(code: &LocosCode) -> Inline {
463    match code.unpaired {
464        Some(TagKind::Close) => Inline::Tag { id: code.id.clone(), kind: TagKind::Close, display: code.close.clone().unwrap_or_default(), free: false },
465        Some(TagKind::Open) => Inline::Tag { id: code.id.clone(), kind: TagKind::Open, display: code.open.clone().unwrap_or_default(), free: false },
466        _ => Inline::Tag { id: code.id.clone(), kind: TagKind::Standalone, display: code.open.clone().unwrap_or_default(), free: code.free },
467    }
468}
469
470fn pair_tag(code: &LocosCode, kind: TagKind) -> Inline {
471    let display = if kind == TagKind::Close { code.close.clone() } else { code.open.clone() };
472    Inline::Tag { id: code.id.clone(), kind, display: display.unwrap_or_default(), free: false }
473}
474
475/// The CAT writers' token rule (`cat_xliff._render`), see [`repair_locos_text_for`]: every token as its tag (nothing
476/// dropped, the writer does that), the problems, and the repairs the writer will make.
477fn parse_tokens_repairing(text: &str, map: &LocosMap) -> (Vec<Inline>, Vec<TokenProblem>, Vec<TagRepair>) {
478    let mut out: Vec<Inline> = Vec::new();
479    let mut problems = Vec::new();
480    let mut repairs = Vec::new();
481    let mut lit = String::new();
482    let mut used: std::collections::BTreeSet<String> = Default::default();
483    // the pairs open now: (number, opening token, written); a pair not written (a repeat) only eats its close
484    let mut stack: Vec<(String, String, bool)> = Vec::new();
485    let mut rest = text;
486    let mut pos = 0usize;
487    while let Some(ch) = rest.chars().next() {
488        let len = ch.len_utf8();
489        if ch == OPEN {
490            if let Some((tok_len, closing, letter, num)) = scan_token(rest) {
491                let token = rest[..tok_len].to_string();
492                rest = &rest[tok_len..];
493                pos += tok_len;
494                let Some(code) = map.get(&num) else {
495                    problems.push(TokenProblem::Unknown { token: token.clone() });
496                    lit.push_str(&token);
497                    continue;
498                };
499                if !lit.is_empty() {
500                    out.push(Inline::Text(std::mem::take(&mut lit)));
501                }
502                let code_point = code.letter == POINT_LETTER || code.letter == FREE_LETTER;
503                let typed_point = letter.is_some_and(|l| l == POINT_LETTER || l == FREE_LETTER);
504                if closing {
505                    // a closing token for a standalone code is a close of its id: the writer drops it
506                    out.push(if code_point {
507                        Inline::Tag { id: code.id.clone(), kind: TagKind::Close, display: code.close.clone().unwrap_or_default(), free: false }
508                    } else {
509                        pair_tag(code, TagKind::Close)
510                    });
511                    if !code_point && stack.last().is_some_and(|f| f.0 == num) {
512                        stack.pop();
513                    } else {
514                        repairs.push(TagRepair::StrayClose { token });
515                    }
516                } else if code_point {
517                    out.push(point_tag(code));
518                    if !used.insert(num) {
519                        repairs.push(TagRepair::Repeated { token });
520                    }
521                } else if typed_point {
522                    // written empty (`cat_xliff._render`): an open and a close side by side read the same way
523                    out.push(pair_tag(code, TagKind::Open));
524                    out.push(pair_tag(code, TagKind::Close));
525                    repairs.push(if used.insert(num) { TagRepair::PairAsPoint { token } } else { TagRepair::Repeated { token } });
526                } else {
527                    out.push(pair_tag(code, TagKind::Open));
528                    let first = used.insert(num.clone());
529                    if !first {
530                        repairs.push(TagRepair::Repeated { token: token.clone() });
531                    }
532                    stack.push((num, token, first));
533                }
534                continue;
535            }
536            problems.push(TokenProblem::Stray { at: pos });
537        } else if ch == CLOSE {
538            problems.push(TokenProblem::Stray { at: pos });
539        }
540        lit.push(ch);
541        rest = &rest[len..];
542        pos += len;
543    }
544    if !lit.is_empty() {
545        out.push(Inline::Text(lit));
546    }
547    for (_, token, written) in stack.into_iter().rev() {
548        if written {
549            repairs.push(TagRepair::Unclosed { token });
550        }
551    }
552    (merge_text(out), problems, repairs)
553}
554
555/// The CAT writers' rule ([`repair_locos_text_for`]) on an inline list, for a target given as tags rather than
556/// LocOS text: each source code is written at most as often as the source has it (a repeated pair loses its tags,
557/// its text stays), a close that does not close the pair on top is dropped, a pair left open is closed at the end.
558/// A tag the source lacks is kept, so the model's check still refuses it. With `points` false a standalone code
559/// is never dropped for being repeated (the formats whose writer writes a repeated placeholder each time).
560pub(crate) fn repair_tags(source: &[Inline], target: Vec<Inline>, points: bool) -> Vec<Inline> {
561    use std::collections::HashMap;
562    let partner = pairs(source);
563    let mut pair_allowed: HashMap<&str, usize> = HashMap::new();
564    let mut point_allowed: HashMap<(&str, TagKind), usize> = HashMap::new();
565    let mut close_display: HashMap<&str, &str> = HashMap::new();
566    for (pos, i) in source.iter().enumerate() {
567        let Inline::Tag { id, kind, display, .. } = i else { continue };
568        match (kind, partner[pos]) {
569            (TagKind::Open, Some(_)) => *pair_allowed.entry(id.as_str()).or_default() += 1,
570            (TagKind::Close, Some(_)) => {
571                close_display.entry(id.as_str()).or_insert(display.as_str());
572            }
573            _ => *point_allowed.entry((id.as_str(), *kind)).or_default() += 1,
574        }
575    }
576    let known: std::collections::HashSet<&str> = source.iter().filter_map(|i| if let Inline::Tag { id, .. } = i { Some(id.as_str()) } else { None }).collect();
577    let mut pair_used: HashMap<String, usize> = HashMap::new();
578    let mut point_used: HashMap<(String, TagKind), usize> = HashMap::new();
579    let mut stack: Vec<(String, bool)> = Vec::new();
580    let mut out = Vec::with_capacity(target.len());
581    for i in target {
582        let Inline::Tag { id, kind, .. } = &i else {
583            out.push(i);
584            continue;
585        };
586        let paired = pair_allowed.get(id.as_str()).copied().unwrap_or(0);
587        match kind {
588            TagKind::Open if paired > 0 => {
589                let n = pair_used.entry(id.clone()).or_default();
590                let write = *n < paired;
591                if write {
592                    *n += 1;
593                }
594                stack.push((id.clone(), write));
595                if write {
596                    out.push(i);
597                }
598            }
599            TagKind::Close if paired > 0 && stack.last().is_some_and(|(top, _)| top == id) => {
600                if let Some((_, true)) = stack.pop() {
601                    out.push(i);
602                }
603            }
604            TagKind::Close if paired > 0 && !point_allowed.contains_key(&(id.as_str(), TagKind::Close)) => {}
605            _ => match point_allowed.get(&(id.as_str(), *kind)) {
606                // a code of the source written as another kind (a close for a standalone code): dropped
607                None if known.contains(id.as_str()) => {}
608                // not a code of the source: kept, the model's check names it
609                None => out.push(i),
610                Some(_) if !points => out.push(i),
611                Some(max) => {
612                    let n = point_used.entry((id.clone(), *kind)).or_default();
613                    if *n < *max {
614                        *n += 1;
615                        out.push(i);
616                    }
617                }
618            },
619        }
620    }
621    for (id, written) in stack.into_iter().rev() {
622        if written {
623            let display = close_display.get(id.as_str()).map(|d| d.to_string()).unwrap_or_default();
624            out.push(Inline::Tag { id, kind: TagKind::Close, display, free: false });
625        }
626    }
627    merge_text(out)
628}
629
630fn parse_tokens(text: &str, map: &LocosMap, drop_mismatch: bool, free_letter: bool) -> (Vec<Inline>, Vec<TokenProblem>) {
631    let mut out: Vec<Inline> = Vec::new();
632    let mut problems = Vec::new();
633    let mut lit = String::new();
634    let mut rest = text;
635    let mut pos = 0usize;
636    while let Some(ch) = rest.chars().next() {
637        let len = ch.len_utf8();
638        if ch == OPEN {
639            if let Some((tok_len, closing, letter, num)) = scan_token(rest) {
640                let token = &rest[..tok_len];
641                let found = if free_letter || letter != Some(FREE_LETTER) {
642                    resolve(map, closing, letter, &num)
643                } else if map.contains_key(num.as_str()) {
644                    Resolved::Mismatch
645                } else {
646                    Resolved::Unknown
647                };
648                match found {
649                    Resolved::Tag(t) => {
650                        if !lit.is_empty() {
651                            out.push(Inline::Text(std::mem::take(&mut lit)));
652                        }
653                        out.push(t);
654                    }
655                    Resolved::Unknown => {
656                        problems.push(TokenProblem::Unknown { token: token.to_string() });
657                        lit.push_str(token);
658                    }
659                    Resolved::Mismatch => {
660                        problems.push(TokenProblem::KindMismatch { token: token.to_string() });
661                        if !drop_mismatch {
662                            lit.push_str(token);
663                        }
664                    }
665                }
666                rest = &rest[tok_len..];
667                pos += tok_len;
668                continue;
669            }
670            problems.push(TokenProblem::Stray { at: pos });
671        } else if ch == CLOSE {
672            problems.push(TokenProblem::Stray { at: pos });
673        }
674        lit.push(ch);
675        rest = &rest[len..];
676        pos += len;
677    }
678    if !lit.is_empty() {
679        out.push(Inline::Text(lit));
680    }
681    (merge_text(out), problems)
682}
683
684/// Reads `OPEN [/] [a-z] digits CLOSE` at the start of `s`: (byte length, is closing, letter, number text).
685fn scan_token(s: &str) -> Option<(usize, bool, Option<char>, String)> {
686    let mut it = s.char_indices();
687    let (_, c) = it.next()?;
688    if c != OPEN {
689        return None;
690    }
691    let mut closing = false;
692    let mut letter = None;
693    let mut num = String::new();
694    for (idx, c) in it {
695        match c {
696            '/' if !closing && letter.is_none() && num.is_empty() => closing = true,
697            c if c.is_ascii_lowercase() && letter.is_none() && num.is_empty() => letter = Some(c),
698            c if c.is_ascii_digit() => num.push(c),
699            CLOSE if !num.is_empty() => return Some((idx + CLOSE.len_utf8(), closing, letter, num)),
700            _ => return None,
701        }
702    }
703    None
704}
705
706enum Resolved {
707    Tag(Inline),
708    Unknown,
709    Mismatch,
710}
711
712fn resolve(map: &LocosMap, closing: bool, letter: Option<char>, num: &str) -> Resolved {
713    let Some(code) = map.get(num) else { return Resolved::Unknown };
714    let is_point = code.letter == POINT_LETTER || code.letter == FREE_LETTER;
715    // The letter in the text may differ from the map's only between x and p (a model may normalise it); a
716    // pair letter must agree, and a closing token never belongs to a standalone code.
717    if is_point {
718        if closing || letter.is_some_and(|l| l != POINT_LETTER && l != FREE_LETTER) {
719            return Resolved::Mismatch;
720        }
721        return Resolved::Tag(match code.unpaired {
722            Some(TagKind::Close) => Inline::Tag {
723                id: code.id.clone(),
724                kind: TagKind::Close,
725                display: code.close.clone().unwrap_or_default(),
726                free: false,
727            },
728            Some(TagKind::Open) => Inline::Tag {
729                id: code.id.clone(),
730                kind: TagKind::Open,
731                display: code.open.clone().unwrap_or_default(),
732                free: false,
733            },
734            _ => Inline::Tag {
735                id: code.id.clone(),
736                kind: TagKind::Standalone,
737                display: code.open.clone().unwrap_or_default(),
738                free: code.free,
739            },
740        });
741    }
742    if letter.is_some_and(|l| l == POINT_LETTER || l == FREE_LETTER) {
743        return Resolved::Mismatch;
744    }
745    if closing {
746        Resolved::Tag(Inline::Tag {
747            id: code.id.clone(),
748            kind: TagKind::Close,
749            display: code.close.clone().unwrap_or_default(),
750            free: false,
751        })
752    } else {
753        Resolved::Tag(Inline::Tag {
754            id: code.id.clone(),
755            kind: TagKind::Open,
756            display: code.open.clone().unwrap_or_default(),
757            free: false,
758        })
759    }
760}
761
762/// True when a placeholder names its argument, so its position in a translation is free: `%1$s`, `%(name)s`,
763/// `{name}`, `{0}`, `{{name}}`, `${name}`. False for markup and for unnumbered placeholders (`%s`, `%d`, `{}`),
764/// whose order is the argument order.
765pub fn is_named_placeholder(s: &str) -> bool {
766    let b = s.as_bytes();
767    match b {
768        [b'{', b'{', ..] => s.ends_with("}}") && s.len() > 4,
769        [b'$', b'{', ..] => s.ends_with('}') && s.len() > 3,
770        [b'{', ..] => {
771            let inner = &s[1..s.len().saturating_sub(1)];
772            s.ends_with('}') && !inner.is_empty() && !inner.starts_with(' ')
773        }
774        [b'%', b'(', ..] => s[2..].contains(')'),
775        [b'%', d, ..] if d.is_ascii_digit() => {
776            let digits = s[1..].bytes().take_while(u8::is_ascii_digit).count();
777            s.as_bytes().get(1 + digits) == Some(&b'$')
778        }
779        _ => false,
780    }
781}
782
783/// Hides the token brackets of literal text from a writer that cuts LocOS text at its tokens (the Office writers
784/// of the LocOS profile). `\u{27E6}` becomes U+E000 U+E001 and U+E000 becomes U+E000 U+E000, so the result holds
785/// no token and [`unescape_literal`] gives back the text byte for byte. Shared by the format crates; not part of
786/// the semver API.
787#[doc(hidden)]
788pub fn escape_literal(s: &str) -> String {
789    if !s.contains([OPEN, LIT_MARK]) {
790        return s.to_string();
791    }
792    let mut out = String::with_capacity(s.len() + 8);
793    for c in s.chars() {
794        match c {
795            OPEN => out.push_str("\u{e000}\u{e001}"),
796            LIT_MARK => out.push_str("\u{e000}\u{e000}"),
797            c => out.push(c),
798        }
799    }
800    out
801}
802
803/// The inverse of [`escape_literal`]. A U+E000 that starts no pair (only text that was not escaped holds one)
804/// stays as it is. Not part of the semver API.
805#[doc(hidden)]
806pub fn unescape_literal(s: &str) -> String {
807    if !s.contains(LIT_MARK) {
808        return s.to_string();
809    }
810    let mut out = String::with_capacity(s.len());
811    let mut it = s.chars().peekable();
812    while let Some(c) = it.next() {
813        if c == LIT_MARK {
814            match it.peek() {
815                Some('\u{e001}') => {
816                    it.next();
817                    out.push(OPEN);
818                    continue;
819                }
820                Some(&LIT_MARK) => {
821                    it.next();
822                }
823                _ => {}
824            }
825        }
826        out.push(c);
827    }
828    out
829}
830
831const LIT_MARK: char = '\u{e000}';
832
833#[cfg(test)]
834mod tests {
835    use super::*;
836
837    #[test]
838    fn literal_escape_round_trips_every_short_string() {
839        // every string of up to six characters over the characters that matter: the escape never holds a token
840        // bracket and always comes back byte for byte
841        let alpha = ['\u{27e6}', '\u{27e7}', '\u{e000}', '\u{e001}', 'x', '1'];
842        let mut cur: Vec<String> = vec![String::new()];
843        for _ in 0..6 {
844            let mut next = Vec::new();
845            for s in &cur {
846                for c in alpha {
847                    let mut t = s.clone();
848                    t.push(c);
849                    let e = escape_literal(&t);
850                    assert!(!e.contains('\u{27e6}'), "{t:?}");
851                    assert_eq!(unescape_literal(&e), t, "{t:?}");
852                    next.push(t);
853                }
854            }
855            cur = next;
856        }
857        // the escape of a concatenation is the concatenation of the escapes, so text cut at a token unescapes
858        // piece by piece
859        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}");
860        assert_eq!(unescape_literal("lone \u{e000} mark"), "lone \u{e000} mark");
861    }
862
863    #[test]
864    fn docx_tokens_carry_locos_numbers() {
865        let inl = vec![
866            Inline::tag("1", TagKind::Open, "<w:r>"),
867            Inline::text("a"),
868            Inline::tag("1", TagKind::Close, "</w:r>"),
869            Inline::tag("3", TagKind::Standalone, "object"),
870            Inline::tag("2", TagKind::Open, "<w:r>"),
871            Inline::text("b"),
872            Inline::tag("2", TagKind::Close, "</w:r>"),
873        ];
874        let (t, map) = to_locos_text_for("docx", &inl);
875        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}");
876        assert_eq!(from_locos_text(&t, &map), inl);
877        // one id-numbering path for docx, pptx and xlsx text boxes; every other format keeps the positional numbering
878        for f in ["docx", "pptx", "xlsx"] {
879            assert_eq!(to_locos_text_for(f, &inl), to_locos_text_numbered(&inl, 'r'), "{f}");
880        }
881        for f in ["xliff", "html", "po", "markdown", "json", "odt", ""] {
882            assert_eq!(to_locos_text_for(f, &inl).0.matches("\u{27e6}x2\u{27e7}").count(), 1, "{f}");
883        }
884        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}");
885        // a bare xlsx cell has no tags: the rule changes nothing
886        let cell = vec![Inline::text("Total")];
887        assert_eq!(to_locos_text_for("xlsx", &cell), to_locos_text_as(&cell, 'r'));
888        let dup = vec![Inline::tag("1", TagKind::Standalone, "o"), Inline::tag("1", TagKind::Standalone, "o")];
889        assert_eq!(to_locos_text_for("docx", &dup).0, "\u{27e6}x1\u{27e7}\u{27e6}x2\u{27e7}");
890        let odd = vec![Inline::tag("x", TagKind::Standalone, "o"), Inline::tag("07", TagKind::Standalone, "o")];
891        assert_eq!(to_locos_text_for("docx", &odd).0, "\u{27e6}x1\u{27e7}\u{27e6}x2\u{27e7}");
892    }
893
894    /// W4 idml-1 / icml-1: LocOS writes a CharacterStyleRange as an `r` pair and every other wrap as a `g` pair.
895    #[test]
896    fn idml_and_icml_runs_are_r_pairs() {
897        let inl = vec![
898            Inline::tag("1", TagKind::Open, "<CharacterStyleRange>"),
899            Inline::text("bold "),
900            Inline::tag("2", TagKind::Open, "<HyperlinkTextSource>"),
901            Inline::text("link"),
902            Inline::tag("2", TagKind::Close, "</HyperlinkTextSource>"),
903            Inline::tag("3", TagKind::Standalone, "<Br/>"),
904            Inline::tag("1", TagKind::Close, "</CharacterStyleRange>"),
905        ];
906        let mut codes = BTreeMap::new();
907        codes.insert("1".to_string(), CodeData::paired("<CharacterStyleRange>", "</CharacterStyleRange>").with_label("run"));
908        codes.insert("2".to_string(), CodeData::paired("<HyperlinkTextSource>", "</HyperlinkTextSource>").with_label("link"));
909        codes.insert("3".to_string(), CodeData::standalone("<Br/>").with_label("br"));
910        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}";
911        for f in ["idml", "icml"] {
912            let (t, map) = to_locos_text_coded(f, &inl, &codes);
913            assert_eq!(t, want, "{f}");
914            assert_eq!(map["1"].letter, 'r');
915            assert_eq!(from_locos_text(&t, &map), inl, "{f}");
916            // the reader is lenient about a pair's letter (as before): a run written as `g` is still the run
917            let (back, problems) = parse_locos_text(&t.replace("r1", "g1"), &map);
918            assert!(problems.is_empty() && back == inl);
919        }
920        // other formats ignore the labels; without codes every pair is `g`, as before
921        assert_eq!(to_locos_text_coded("odt", &inl, &codes), to_locos_text_for("odt", &inl));
922        assert_eq!(to_locos_text_coded("idml", &inl, &BTreeMap::new()).0.matches("\u{27e6}g").count(), 2);
923    }
924
925    fn sample() -> Vec<Inline> {
926        vec![
927            Inline::text("Hola "),
928            Inline::tag("1", TagKind::Open, "<b>"),
929            Inline::text("mundo"),
930            Inline::tag("1", TagKind::Close, "</b>"),
931            Inline::text(", "),
932            Inline::free_tag("2", "{name}"),
933            Inline::text(" "),
934            Inline::tag("3", TagKind::Standalone, "%s"),
935            Inline::text("."),
936        ]
937    }
938
939    #[test]
940    fn tokens_follow_the_table() {
941        let (t, map) = to_locos_text(&sample());
942        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}.");
943        assert_eq!(map.len(), 3);
944        assert_eq!(map["1"].close.as_deref(), Some("</b>"));
945        assert!(map["2"].free && map["2"].letter == 'p');
946        assert!(!map["3"].free && map["3"].letter == 'x');
947    }
948
949    #[test]
950    fn round_trips() {
951        let s = sample();
952        let (t, map) = to_locos_text(&s);
953        assert_eq!(from_locos_text(&t, &map), s);
954        let (t, map) = to_locos_text_as(&s, 'r');
955        assert!(t.contains("\u{27E6}r1\u{27E7}") && t.contains("\u{27E6}/r1\u{27E7}"));
956        assert_eq!(from_locos_text(&t, &map), s);
957    }
958
959    #[test]
960    fn token_look_alikes_in_the_text_are_text() {
961        // the text says "use ⟦x2⟧ and ⟦g1⟧": no real code may take number 1 or 2
962        let inl = vec![
963            Inline::text("Use \u{27E6}x2\u{27E7} and \u{27E6}g1\u{27E7} "),
964            Inline::tag("a", TagKind::Open, "<b>"),
965            Inline::text("here"),
966            Inline::tag("a", TagKind::Close, "</b>"),
967            Inline::tag("b", TagKind::Standalone, "<br/>"),
968        ];
969        for f in ["xliff", "html", "docx"] {
970            let (t, map) = to_locos_text_for(f, &inl);
971            assert!(!map.contains_key("1") && !map.contains_key("2"), "{f}: {map:?}");
972            assert_eq!(from_locos_text(&t, &map), inl, "{f}: {t}");
973            // a translator keeps the text and moves the code
974            let moved = t.replace("here", "HERE");
975            let back = from_locos_text(&moved, &map);
976            assert!(matches!(&back[0], Inline::Text(x) if x.starts_with("Use \u{27E6}x2\u{27E7} and \u{27E6}g1\u{27E7}")), "{f}");
977        }
978        // numbers with gaps: a translator who swaps the codes gets each tag back by its own number
979        let inl = vec![
980            Inline::text("\u{27E6}x2\u{27E7} "),
981            Inline::tag("1", TagKind::Open, "<b>"),
982            Inline::text("one"),
983            Inline::tag("1", TagKind::Close, "</b>"),
984            Inline::tag("3", TagKind::Standalone, "<br/>"),
985            Inline::text("two"),
986        ];
987        for f in ["html", "docx"] {
988            let (t, map) = to_locos_text_for(f, &inl);
989            let p = locos_pair_letter(f);
990            let (n_pair, n_point) = (map.iter().find(|(_, c)| c.id == "1").unwrap().0, map.iter().find(|(_, c)| c.id == "3").unwrap().0);
991            assert!(!map.contains_key("2"), "{f}: {map:?}");
992            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}");
993            let (back, problems) = parse_locos_text(&swapped, &map);
994            assert_eq!(problems.len(), 1, "{f}: only the look-alike is unknown: {problems:?} ({t})");
995            assert_eq!(
996                back,
997                vec![
998                    Inline::text("\u{27E6}x2\u{27E7} two"),
999                    Inline::tag("3", TagKind::Standalone, "<br/>"),
1000                    Inline::tag("1", TagKind::Open, "<b>"),
1001                    Inline::text("one"),
1002                    Inline::tag("1", TagKind::Close, "</b>"),
1003                ],
1004                "{f}"
1005            );
1006        }
1007        // a letterless look-alike ("⟦1⟧") also keeps its number free
1008        let inl = vec![Inline::text("\u{27E6}1\u{27E7} "), Inline::tag("a", TagKind::Standalone, "<br/>")];
1009        let (t, map) = to_locos_text(&inl);
1010        assert_eq!(t, "\u{27E6}1\u{27E7} \u{27E6}x2\u{27E7}");
1011        assert_eq!(from_locos_text(&t, &map), inl);
1012    }
1013
1014    #[test]
1015    fn bad_pair_letter_falls_back() {
1016        let (t, _) = to_locos_text_as(&sample(), 'x');
1017        assert!(t.contains("\u{27E6}g1\u{27E7}"));
1018        let (t, _) = to_locos_text_as(&sample(), 'G');
1019        assert!(t.contains("\u{27E6}g1\u{27E7}"));
1020    }
1021
1022    #[test]
1023    fn reordered_free_tokens_come_back_by_number() {
1024        let (_, map) = to_locos_text(&[Inline::free_tag("a", "%1$s"), Inline::text(" y "), Inline::free_tag("b", "%2$s")]);
1025        let back = from_locos_text("\u{27E6}p2\u{27E7} \u{27E6}p1\u{27E7}", &map);
1026        assert_eq!(back[0], Inline::free_tag("b", "%2$s"));
1027        assert_eq!(back[2], Inline::free_tag("a", "%1$s"));
1028    }
1029
1030    #[test]
1031    fn unmatched_close_and_open_survive() {
1032        let s = vec![
1033            Inline::tag("9", TagKind::Close, "</i>"),
1034            Inline::text("x"),
1035            Inline::tag("8", TagKind::Open, "<u>"),
1036            Inline::text("y"),
1037        ];
1038        let (t, map) = to_locos_text(&s);
1039        assert_eq!(t, "\u{27E6}x1\u{27E7}x\u{27E6}x2\u{27E7}y");
1040        assert!(well_formed(&t));
1041        assert_eq!(map["1"].unpaired, Some(TagKind::Close));
1042        assert_eq!(from_locos_text(&t, &map), s);
1043        // The map keeps the side through JSON.
1044        let back: LocosMap = serde_json::from_str(&serde_json::to_string(&map).unwrap()).unwrap();
1045        assert_eq!(from_locos_text(&t, &back), s);
1046    }
1047
1048    /// LocOS `placeholders_well_formed`: pairs nest by number, point letters (x, p) never pair.
1049    fn well_formed(t: &str) -> bool {
1050        let mut stack = Vec::new();
1051        for tok in t.split('\u{27E6}').skip(1) {
1052            let tok = tok.split('\u{27E7}').next().unwrap_or_default();
1053            if let Some(rest) = tok.strip_prefix('/') {
1054                let key = rest.trim_start_matches(|c: char| c.is_ascii_lowercase());
1055                if stack.pop() != Some(key.to_string()) {
1056                    return false;
1057                }
1058            } else if !tok.starts_with(['x', 'p']) {
1059                stack.push(tok.trim_start_matches(|c: char| c.is_ascii_lowercase()).to_string());
1060            }
1061        }
1062        stack.is_empty()
1063    }
1064
1065    #[test]
1066    fn crossed_pairs_become_well_formed() {
1067        let s = vec![
1068            Inline::tag("a", TagKind::Open, "<b>"),
1069            Inline::text("1"),
1070            Inline::tag("b", TagKind::Open, "<i>"),
1071            Inline::text("2"),
1072            Inline::tag("a", TagKind::Close, "</b>"),
1073            Inline::text("3"),
1074            Inline::tag("b", TagKind::Close, "</i>"),
1075        ];
1076        let (t, map) = to_locos_text(&s);
1077        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}");
1078        assert!(well_formed(&t));
1079        assert_eq!(from_locos_text(&t, &map), s);
1080    }
1081
1082    #[test]
1083    fn html_keeps_its_own_tokens() {
1084        // LocOS html_filter: an open with no close is a pair token, crossed pairs keep their numbers
1085        let s = vec![
1086            Inline::tag("1", TagKind::Open, "<a>"),
1087            Inline::text("Hi "),
1088            Inline::tag("2", TagKind::Open, "<b>"),
1089            Inline::text("1"),
1090            Inline::tag("3", TagKind::Open, "<i>"),
1091            Inline::text("2"),
1092            Inline::tag("2", TagKind::Close, "</b>"),
1093            Inline::text("3"),
1094            Inline::tag("3", TagKind::Close, "</i>"),
1095            Inline::tag("4", TagKind::Standalone, "<br>"),
1096            Inline::tag("9", TagKind::Close, "</u>"),
1097        ];
1098        let (t, map) = to_locos_text_for("html", &s);
1099        assert_eq!(
1100            t,
1101            "\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}"
1102        );
1103        assert_eq!(map["1"].letter, 'g');
1104        assert_eq!(map["1"].close, None);
1105        assert_eq!(from_locos_text(&t, &map), s);
1106        // the other formats keep the well-formed conversion, with their pair letter
1107        assert_eq!(to_locos_text_for("md", &s), to_locos_text_as(&s, 'g'));
1108        assert_eq!(to_locos_text_for("docx", &s), to_locos_text_as(&s, 'r'));
1109    }
1110
1111    #[test]
1112    fn html_family_formats_keep_an_open_with_no_close_a_pair_token() {
1113        // `<a><span>&nbsp;</span>` then a block child: the `<a>` closes in a later unit
1114        let s = vec![
1115            Inline::tag("1", TagKind::Open, "<a>"),
1116            Inline::tag("2", TagKind::Open, "<span>"),
1117            Inline::text("&nbsp;"),
1118            Inline::tag("2", TagKind::Close, "</span>"),
1119        ];
1120        for f in ["html", "aspx", "erb", "shtml", "jsp", "phtml", "epub", "eml"] {
1121            let (t, map) = to_locos_text_for(f, &s);
1122            assert_eq!(t, "\u{27E6}g1\u{27E7}\u{27E6}g2\u{27E7}&nbsp;\u{27E6}/g2\u{27E7}", "{f}");
1123            assert_eq!(from_locos_text(&t, &map), s, "{f}");
1124        }
1125        // a format outside the family keeps the well-formed conversion
1126        assert!(to_locos_text_for("md", &s).0.starts_with("\u{27E6}x1\u{27E7}"));
1127    }
1128
1129    #[test]
1130    fn nested_and_repeated_ids() {
1131        let s = vec![
1132            Inline::tag("a", TagKind::Open, "<b>"),
1133            Inline::tag("b", TagKind::Open, "<i>"),
1134            Inline::text("t"),
1135            Inline::tag("b", TagKind::Close, "</i>"),
1136            Inline::tag("a", TagKind::Close, "</b>"),
1137            Inline::tag("a", TagKind::Open, "<b>"),
1138            Inline::text("u"),
1139            Inline::tag("a", TagKind::Close, "</b>"),
1140        ];
1141        let (t, map) = to_locos_text(&s);
1142        assert_eq!(map.len(), 3);
1143        assert!(well_formed(&t));
1144        assert_eq!(from_locos_text(&t, &map), s);
1145    }
1146
1147    #[test]
1148    fn malformed_tokens_stay_as_text_and_are_reported() {
1149        let (_, map) = to_locos_text(&sample());
1150        for bad in [
1151            "a \u{27E6} b",
1152            "a \u{27E7} b",
1153            "\u{27E6}g\u{27E7}",
1154            "\u{27E6}g1",
1155            "\u{27E6}/\u{27E6}g1\u{27E7}",
1156            "\u{27E6}G1\u{27E7}",
1157            "\u{27E6}x1{limit}\u{27E7}",
1158            "\u{27E6}g99\u{27E7}",
1159            "\u{27E6}/x3\u{27E7}",
1160            "\u{27E6}x1\u{27E7}",
1161        ] {
1162            let (inl, problems) = parse_locos_text(bad, &map);
1163            let rebuilt: String = inl
1164                .iter()
1165                .map(|i| match i {
1166                    Inline::Text(t) => t.clone(),
1167                    Inline::Tag { .. } => String::from("#"),
1168                })
1169                .collect();
1170            if bad == "\u{27E6}x1\u{27E7}" {
1171                // x1 is a pair in the map: a point token for a pair is a mismatch.
1172                assert!(problems.iter().any(|p| matches!(p, TokenProblem::KindMismatch { .. })), "{bad}");
1173            } else {
1174                assert!(!problems.is_empty(), "{bad:?} gave no problem");
1175            }
1176            assert!(rebuilt.contains('\u{27E6}') || rebuilt.contains('\u{27E7}') || bad.contains("g1\u{27E7}"), "{bad:?} lost text");
1177        }
1178    }
1179
1180    #[test]
1181    fn text_in_every_language_survives() {
1182        for t in [
1183            "Hello", "Hola", "Bonjour", "Ciao", "Hallo", "Hallo", "Ola", "\u{3053}\u{3093}\u{306b}\u{3061}\u{306f}",
1184            "\u{4f60}\u{597d}", "\u{c548}\u{b155}", "\u{645}\u{631}\u{62d}\u{628}\u{627}",
1185        ] {
1186            let s = vec![Inline::tag("1", TagKind::Open, "<b>"), Inline::text(t), Inline::tag("1", TagKind::Close, "</b>"), Inline::free_tag("2", "{0}")];
1187            let (x, map) = to_locos_text(&s);
1188            assert_eq!(from_locos_text(&x, &map), s);
1189        }
1190    }
1191
1192    #[test]
1193    fn numbered_by_id_like_locos_pptx() {
1194        // LocOS's PPTX numbering: runs r1, r2 first, the break and the field after them
1195        let s = vec![
1196            Inline::tag("1", TagKind::Open, "<a:r>"),
1197            Inline::text("a"),
1198            Inline::tag("1", TagKind::Close, "</a:r>"),
1199            Inline::tag("3", TagKind::Standalone, "<a:br/>"),
1200            Inline::tag("2", TagKind::Open, "<a:r>"),
1201            Inline::text("b"),
1202            Inline::tag("2", TagKind::Close, "</a:r>"),
1203            Inline::tag("4", TagKind::Standalone, "<a:fld/>"),
1204        ];
1205        let (t, map) = to_locos_text_numbered(&s, 'r');
1206        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}");
1207        assert!(well_formed(&t));
1208        assert_eq!(from_locos_text(&t, &map), s);
1209        // ids that are not usable token numbers: reading order, exactly as to_locos_text_as
1210        for bad in [
1211            vec![Inline::tag("a", TagKind::Standalone, "x")],
1212            vec![Inline::tag("0", TagKind::Standalone, "x")],
1213            vec![Inline::tag("01", TagKind::Standalone, "x")],
1214            vec![Inline::tag("+2", TagKind::Standalone, "x")],
1215            vec![Inline::tag("2", TagKind::Standalone, "x"), Inline::tag("2", TagKind::Standalone, "y")],
1216            vec![Inline::tag("9", TagKind::Open, "x"), Inline::tag("9", TagKind::Open, "y")],
1217            vec![Inline::tag("99999999999999999999999", TagKind::Standalone, "x")],
1218        ] {
1219            assert_eq!(to_locos_text_numbered(&bad, 'r'), to_locos_text_as(&bad, 'r'), "{bad:?}");
1220        }
1221        assert_eq!(to_locos_text_numbered(&sample(), 'g'), to_locos_text(&sample()));
1222        assert_eq!(to_locos_text_numbered(&[], 'r'), (String::new(), LocosMap::new()));
1223        // the per-format entry point picks it for pptx
1224        assert_eq!(to_locos_text_for("pptx", &s), (t, map));
1225    }
1226
1227    #[test]
1228    fn empty_and_tagless() {
1229        let (t, m) = to_locos_text(&[]);
1230        assert!(t.is_empty() && m.is_empty());
1231        assert!(from_locos_text("", &m).is_empty());
1232        assert_eq!(from_locos_text("plain", &m), vec![Inline::text("plain")]);
1233    }
1234
1235    #[test]
1236    fn named_placeholders() {
1237        for yes in ["%1$s", "%12$d", "%(name)s", "{name}", "{0}", "{{count}}", "${user}"] {
1238            assert!(is_named_placeholder(yes), "{yes}");
1239        }
1240        for no in ["%s", "%d", "%.2f", "{}", "{ x }", "<b>", "%%", "%5d", "{{}}", "${}", "%(x"] {
1241            assert!(!is_named_placeholder(no), "{no}");
1242        }
1243    }
1244
1245    /// #814.1 (g12): TOML and JS drop a pair token naming a point code; an unknown number stays text; other
1246    /// formats keep the wrong-kind token as text.
1247    #[test]
1248    fn wrong_kind_tokens_are_dropped_for_toml_and_js() {
1249        let src = vec![Inline::text("Reading time "), Inline::tag("1", TagKind::Standalone, "{{ .Count }}"), Inline::text(" min")];
1250        let (_, map) = to_locos_text(&src);
1251        let t = "Lesezeit \u{27E6}x9\u{27E7} \u{27E6}g1\u{27E7}Min\u{27E6}/g1\u{27E7} \u{27E6}x1\u{27E7}";
1252        // rc (B-SIDE W6 rc-2): LocOS `rc_filter._render_literal` drops a pair token for a point code the same way
1253        for f in ["toml", "js", "rc"] {
1254            let (inl, problems) = parse_locos_text_for(f, t, &map);
1255            assert_eq!(
1256                inl,
1257                vec![Inline::text("Lesezeit \u{27E6}x9\u{27E7} Min "), Inline::tag("1", TagKind::Standalone, "{{ .Count }}")],
1258                "{f}"
1259            );
1260            assert_eq!(problems.iter().filter(|p| matches!(p, TokenProblem::KindMismatch { .. })).count(), 2, "{f}");
1261            assert!(problems.contains(&TokenProblem::Unknown { token: "\u{27E6}x9\u{27E7}".into() }), "{f}");
1262        }
1263        let (kept, _) = parse_locos_text_for("json", t, &map);
1264        assert_eq!(kept, parse_locos_text(t, &map).0);
1265        assert!(matches!(&kept[0], Inline::Text(x) if x.contains("\u{27E6}g1\u{27E7}Min")));
1266    }
1267
1268    /// 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
1269    /// text (the DXF writer drops it as LocOS does), where every other format reads `p` as the point.
1270    #[test]
1271    fn dxf_does_not_read_p_as_a_point() {
1272        let src = vec![Inline::text("a"), Inline::tag("1", TagKind::Standalone, "%%d")];
1273        let (_, map) = to_locos_text(&src);
1274        let t = "a%\u{27E6}p1\u{27E7}%b\u{27E6}x1\u{27E7}";
1275        let (inl, problems) = parse_locos_text_for("dxf", t, &map);
1276        assert_eq!(inl, vec![Inline::text("a%\u{27E6}p1\u{27E7}%b"), Inline::tag("1", TagKind::Standalone, "%%d")]);
1277        assert_eq!(problems, vec![TokenProblem::KindMismatch { token: "\u{27E6}p1\u{27E7}".into() }]);
1278        // a `p` token naming no code is unknown, as everywhere
1279        let (_, problems) = parse_locos_text_for("dxf", "\u{27E6}p7\u{27E7}", &map);
1280        assert_eq!(problems, vec![TokenProblem::Unknown { token: "\u{27E6}p7\u{27E7}".into() }]);
1281        let (inl, problems) = parse_locos_text_for("txt", t, &map);
1282        assert!(problems.is_empty() && inl.iter().filter(|i| matches!(i, Inline::Tag { .. })).count() == 2);
1283    }
1284
1285    /// B-SIDE 8: the CAT writers' rule (LocOS `cat_xliff._render`): a repeated pair loses its tags and keeps its
1286    /// text, a stray close is dropped, an unclosed pair is closed at the end, a pair named by a point token is
1287    /// written empty, a repeated point is dropped; each repair is listed. Other formats read as before.
1288    #[test]
1289    fn cat_formats_repair_tags_like_locos() {
1290        let open = Inline::tag("1", TagKind::Open, "<g id=\"1\">");
1291        let close = Inline::tag("1", TagKind::Close, "</g>");
1292        let x = Inline::tag("2", TagKind::Standalone, "<x id=\"2\"/>");
1293        let src = vec![Inline::text("Click "), open.clone(), Inline::text("here"), close.clone(), x.clone()];
1294        let (text, map) = to_locos_text(&src);
1295        assert_eq!(text, "Click \u{27E6}g1\u{27E7}here\u{27E6}/g1\u{27E7}\u{27E6}x2\u{27E7}");
1296        let cases: Vec<(&str, Vec<Inline>, Vec<&str>)> = vec![
1297            // verify_filter_roundtrip_509: the second frame loses its tags, its text stays in place
1298            (
1299                "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",
1300                vec![Inline::text("bitte "), open.clone(), Inline::text("Klick"), close.clone(), Inline::text(" hier doppelt jetzt")],
1301                vec!["repeated"],
1302            ),
1303            // verify_cat_xliff_filter 165: an open used again with no close of its own is dropped, the pair closed at the end
1304            (
1305                "\u{27E6}g1\u{27E7}A \u{27E6}x2\u{27E7}B \u{27E6}g1\u{27E7}C",
1306                vec![open.clone(), Inline::text("A "), x.clone(), Inline::text("B C"), close.clone()],
1307                vec!["repeated", "unclosed"],
1308            ),
1309            ("\u{27E6}/g1\u{27E7}Hi \u{27E6}/x2\u{27E7}", vec![Inline::text("Hi ")], vec!["stray_close", "stray_close"]),
1310            ("Hi \u{27E6}x1\u{27E7} you", vec![Inline::text("Hi "), open.clone(), close.clone(), Inline::text(" you")], vec!["pair_as_point"]),
1311            ("\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"]),
1312            // the letter does not matter, only the number: a close typed with a point letter closes the pair
1313            ("\u{27E6}g1\u{27E7}a\u{27E6}/x1\u{27E7}", vec![open.clone(), Inline::text("a"), close.clone()], vec![]),
1314            // a number the map lacks stays text
1315            ("a \u{27E6}g9\u{27E7}", vec![Inline::text("a \u{27E6}g9\u{27E7}")], vec![]),
1316        ];
1317        for (t, want, kinds) in cases {
1318            for f in ["sdlxliff", "xliff", "mqxliff", "mxliff", "txlf", "txml", "ttx", "xlz", "mqxlz", "sdlppx"] {
1319                let (inl, _, repairs) = repair_locos_text_for(f, t, &map);
1320                // every token stays a tag (the writer applies the rule); the rule on the inlines gives LocOS's result
1321                assert_eq!(repair_tags(&src, inl.clone(), true), want, "{f}: {t}");
1322                let got: Vec<&str> = repairs
1323                    .iter()
1324                    .map(|r| match r {
1325                        TagRepair::Repeated { .. } => "repeated",
1326                        TagRepair::StrayClose { .. } => "stray_close",
1327                        TagRepair::Unclosed { .. } => "unclosed",
1328                        TagRepair::PairAsPoint { .. } => "pair_as_point",
1329                    })
1330                    .collect();
1331                assert_eq!(got, kinds, "{f}: {t}");
1332                // the inline repair leaves a repaired target as it is
1333                assert_eq!(repair_tags(&src, want.clone(), true), want, "{f}: {t}");
1334                assert_eq!(parse_locos_text_for(f, t, &map).0, inl, "{f}: {t}");
1335            }
1336            let (plain, _, none) = repair_locos_text_for("json", t, &map);
1337            assert!(none.is_empty());
1338            assert_eq!(plain, parse_locos_text(t, &map).0);
1339        }
1340    }
1341
1342    /// The inline repair (a target given as tags): the same rule by id; a source that repeats an id may repeat it
1343    /// as often; an invented tag is kept for the model's check.
1344    #[test]
1345    fn inline_targets_are_repaired_by_id() {
1346        let open = Inline::tag("1", TagKind::Open, "<b>");
1347        let close = Inline::tag("1", TagKind::Close, "</b>");
1348        let src = vec![open.clone(), Inline::text("a"), close.clone()];
1349        let t = vec![open.clone(), Inline::text("x"), close.clone(), open.clone(), Inline::text("y"), close.clone(), close.clone(), open.clone()];
1350        assert_eq!(repair_tags(&src, t, true), vec![open.clone(), Inline::text("x"), close.clone(), Inline::text("y")]);
1351        assert_eq!(repair_tags(&src, vec![open.clone(), Inline::text("z")], true), vec![open.clone(), Inline::text("z"), close.clone()]);
1352        let twice = vec![open.clone(), Inline::text("a"), close.clone(), open.clone(), Inline::text("b"), close.clone()];
1353        assert_eq!(repair_tags(&twice, twice.clone(), true), twice);
1354        let invented = vec![Inline::tag("9", TagKind::Standalone, "<hr/>")];
1355        assert_eq!(repair_tags(&src, invented.clone(), true), invented);
1356    }
1357}