1use 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
32pub const PAIR_LETTER: char = 'g';
34pub const POINT_LETTER: char = 'x';
36pub const FREE_LETTER: char = 'p';
38
39#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
41pub struct LocosCode {
42 pub id: String,
44 pub letter: char,
46 #[serde(default)]
48 pub open: Option<String>,
49 #[serde(default)]
51 pub close: Option<String>,
52 #[serde(default)]
54 pub free: bool,
55 #[serde(default, skip_serializing_if = "Option::is_none")]
57 pub unpaired: Option<TagKind>,
58}
59
60pub type LocosMap = BTreeMap<String, LocosCode>;
62
63pub fn to_locos_text(inl: &[Inline]) -> (String, LocosMap) {
65 to_locos_text_as(inl, PAIR_LETTER)
66}
67
68pub fn to_locos_text_as(inl: &[Inline], pair_letter: char) -> (String, LocosMap) {
71 convert(inl, pair_letter, pairs(inl), None, None)
72}
73
74pub fn locos_pair_letter(format: &str) -> char {
77 if matches!(format, "docx" | "pptx" | "xlsx") {
78 'r'
79 } else {
80 PAIR_LETTER
81 }
82}
83
84const LOCOS_PAIRS_BY_ID: &[&str] = &["html", "aspx", "erb", "shtml", "jsp", "phtml", "epub", "eml"];
93
94const LOCOS_NUMBERED_BY_ID: &[&str] = &["docx", "pptx", "xlsx"];
100
101pub 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
119const LOCOS_RUN_PAIRS: &[&str] = &["idml", "icml"];
123
124pub 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
136pub 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 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 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
166fn 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
199type 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 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 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 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
286fn pairs(inl: &[Inline]) -> Vec<Option<usize>> {
290 let mut partner = vec![None; inl.len()];
291 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
319fn pairs_by_id(inl: &[Inline]) -> Vec<Option<usize>> {
323 let mut partner = vec![None; inl.len()];
324 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#[derive(Debug, Clone, PartialEq, Eq)]
346pub enum TokenProblem {
347 Stray {
349 at: usize,
351 },
352 Unknown {
354 token: String,
356 },
357 KindMismatch {
360 token: String,
362 },
363}
364
365pub fn from_locos_text(text: &str, map: &LocosMap) -> Vec<Inline> {
368 parse_locos_text(text, map).0
369}
370
371pub fn parse_locos_text(text: &str, map: &LocosMap) -> (Vec<Inline>, Vec<TokenProblem>) {
373 parse_tokens(text, map, false, true)
374}
375
376const LOCOS_DROPS_MISMATCH: &[&str] = &["toml", "js", "rc"];
382
383const LOCOS_NO_FREE_LETTER: &[&str] = &["dxf"];
387
388pub 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
396const 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
406const LOCOS_TYPED_TAGS: &[&str] = &["xliff", "sdlxliff", "mqxliff", "mxliff", "txlf", "txml", "ttx", "xlz", "mqxlz", "sdlppx", "mdx"];
410
411pub fn locos_repairs_tags(format: &str) -> bool {
415 LOCOS_REPAIRS_TAGS.contains(&format)
416}
417
418pub(crate) fn locos_keeps_typed_tags(format: &str) -> bool {
421 LOCOS_TYPED_TAGS.contains(&format)
422}
423
424#[derive(Debug, Clone, PartialEq, Eq)]
427#[non_exhaustive]
428pub enum TagRepair {
429 Repeated {
431 token: String,
433 },
434 StrayClose {
436 token: String,
438 },
439 Unclosed {
441 token: String,
443 },
444 PairAsPoint {
447 token: String,
449 },
450}
451
452pub 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
471fn 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
485fn 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 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 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 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
565pub(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 None if known.contains(id.as_str()) => {}
618 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
694fn 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 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
772pub 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#[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#[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 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 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 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 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 #[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 let (back, problems) = parse_locos_text(&t.replace("r1", "g1"), &map);
929 assert!(problems.is_empty() && back == inl);
930 }
931 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 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 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 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 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 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 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 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 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 let s = vec![
1126 Inline::tag("1", TagKind::Open, "<a>"),
1127 Inline::tag("2", TagKind::Open, "<span>"),
1128 Inline::text(" "),
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} \u{27E6}/g2\u{27E7}", "{f}");
1134 assert_eq!(from_locos_text(&t, &map), s, "{f}");
1135 }
1136 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 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 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 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 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 #[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 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 #[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 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 #[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 (
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 (
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 ("\u{27E6}g1\u{27E7}a\u{27E6}/x1\u{27E7}", vec![open.clone(), Inline::text("a"), close.clone()], vec![]),
1325 ("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 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 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 #[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 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 #[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 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}