|
| 1 | +"""Executor for parsed Interscript maps. |
| 2 | +
|
| 3 | +Semantics follow interscript-ruby for the covered op set: |
| 4 | +- parallel { sub a, b }: ONE pass over the text; at each position the |
| 5 | + longest matching pattern wins. Uppercase source characters map to |
| 6 | + uppercased results (я->ya implies Я->YA). |
| 7 | +- subst /pat/, res: regex substitution ($1 backreferences converted). |
| 8 | +- run "map": apply another map's stages to the whole text. |
| 9 | +- compose/decompose: NFC/NFD. downcase/upcase/titlecase: Unicode casing. |
| 10 | +
|
| 11 | +Unsupported constructs raise ExecutionError (on_unsupported="raise", |
| 12 | +default) or are skipped and recorded (on_unsupported="skip"). |
| 13 | +""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import re |
| 18 | +import unicodedata |
| 19 | + |
| 20 | +from .expr import expr_to_literal, expr_to_regex, is_plain_string |
| 21 | + |
| 22 | + |
| 23 | +class ExecutionError(ValueError): |
| 24 | + """The map uses a construct this engine does not implement yet.""" |
| 25 | + |
| 26 | + |
| 27 | +def _compile_parallel(subs: list[dict]) -> tuple[re.Pattern[str], dict[str, str], dict[str, str]]: |
| 28 | + """Compile one parallel group: longest-pattern-first alternation |
| 29 | + with a named group per sub; lookaround guards for before:/after:. |
| 30 | + Plain-string patterns additionally feed the casing maps.""" |
| 31 | + indexed = [] |
| 32 | + anchor_results: dict[str, str] = {} |
| 33 | + n = len(subs) |
| 34 | + for i, sub in enumerate(subs): |
| 35 | + pat = expr_to_regex(sub["pattern"]) |
| 36 | + full = pat |
| 37 | + if sub.get("before"): |
| 38 | + full = "(?<=" + expr_to_regex(sub["before"]) + ")" + full |
| 39 | + if sub.get("after"): |
| 40 | + full = full + "(?=" + expr_to_regex(sub["after"]) + ")" |
| 41 | + indexed.append((pat, full, f"s{i}")) |
| 42 | + if is_plain_string(sub["pattern"]) and not sub.get("before") and not sub.get("after"): |
| 43 | + src = expr_to_literal(sub["pattern"]) |
| 44 | + if src.upper() != src: |
| 45 | + anchor_results[f"a{i}"] = expr_to_literal(sub["result"]) |
| 46 | + indexed.append((re.escape(src.upper()), re.escape(src.upper()), f"a{i}")) |
| 47 | + indexed.sort(key=lambda t: -len(t[0])) |
| 48 | + combined = "|".join(f"(?P<{name}>{full})" for _, full, name in indexed) |
| 49 | + pattern = re.compile(combined) if indexed else re.compile(r"(?!)") |
| 50 | + |
| 51 | + results = {f"s{i}": expr_to_literal(sub["result"]) for i, sub in enumerate(subs)} |
| 52 | + results.update(anchor_results) |
| 53 | + casing_map: dict[str, str] = {} |
| 54 | + upper_dst: dict[str, str] = {} |
| 55 | + for sub in subs: |
| 56 | + if is_plain_string(sub["pattern"]) and not sub.get("before") and not sub.get("after"): |
| 57 | + src = expr_to_literal(sub["pattern"]) |
| 58 | + dst = expr_to_literal(sub["result"]) |
| 59 | + casing_map[src] = dst |
| 60 | + if src.upper() != src: |
| 61 | + upper_dst[src.upper()] = dst |
| 62 | + return pattern, {"casing": casing_map, "upper": upper_dst, "results": results}, {} |
| 63 | + |
| 64 | + |
| 65 | +class Engine: |
| 66 | + def __init__(self, tree: dict, loader=None, on_unsupported: str = "raise") -> None: |
| 67 | + self.tree = tree |
| 68 | + self.metadata = tree.get("metadata", {}) |
| 69 | + self._loader = loader |
| 70 | + self.on_unsupported = on_unsupported |
| 71 | + self.skipped_unsupported: list[str] = [] |
| 72 | + self._compiled: re.Pattern[str] | None = None |
| 73 | + self._compiled_map: dict[str, str] = {} |
| 74 | + self._group_results: dict[str, str] = {} |
| 75 | + self._compiled_source: int | None = None |
| 76 | + |
| 77 | + def transliterate(self, text: str) -> str: |
| 78 | + for stage in self.tree.get("stages", []): |
| 79 | + text = self._run_stage(stage, text) |
| 80 | + return text |
| 81 | + |
| 82 | + def _run_stage(self, stage: dict, text: str) -> str: |
| 83 | + for child in stage.get("children", []): |
| 84 | + text = self._run_op(child, text) |
| 85 | + return text |
| 86 | + |
| 87 | + def _group_repl(self, m: re.Match[str], text: str) -> str: |
| 88 | + name = m.lastgroup if m.lastgroup else "" |
| 89 | + if name in self._group_results: |
| 90 | + result = self._group_results[name] |
| 91 | + tok = m.group(0) |
| 92 | + if result != result.upper() and tok == tok.upper() and tok != tok.lower(): |
| 93 | + ws, we = m.start(), m.end() |
| 94 | + while ws > 0 and text[ws - 1].isalpha(): |
| 95 | + ws -= 1 |
| 96 | + while we < len(text) and text[we].isalpha(): |
| 97 | + we += 1 |
| 98 | + if text[ws:we].isupper(): |
| 99 | + return result.upper() |
| 100 | + return result |
| 101 | + return self._parallel_repl(m, text) |
| 102 | + |
| 103 | + def _parallel_repl(self, m: re.Match[str], text: str) -> str: |
| 104 | + tok = m.group(0) |
| 105 | + dst = self._compiled_map.get(tok) or self._upper_dst.get(tok) |
| 106 | + if dst is None: |
| 107 | + return tok |
| 108 | + # interscript-ruby casing convention: inside an ALL-CAPS source |
| 109 | + # word, a fully-uppercase source token uppercases its result |
| 110 | + # (Я -> Ya normally, YA inside БЯГА). |
| 111 | + if dst != dst.upper() and tok == tok.upper() and tok != tok.lower(): |
| 112 | + ws, we = m.start(), m.end() |
| 113 | + while ws > 0 and text[ws - 1].isalpha(): |
| 114 | + ws -= 1 |
| 115 | + while we < len(text) and text[we].isalpha(): |
| 116 | + we += 1 |
| 117 | + if text[ws:we].isupper(): |
| 118 | + return dst.upper() |
| 119 | + return dst |
| 120 | + |
| 121 | + def _run_op(self, op: dict, text: str) -> str: |
| 122 | + kind = op.get("kind") |
| 123 | + if kind == "parallel": |
| 124 | + if self._compiled is None or self._compiled_source != id(op): |
| 125 | + pattern, maps, _ = _compile_parallel(op["subs"]) |
| 126 | + self._compiled = pattern |
| 127 | + self._compiled_map = maps["casing"] |
| 128 | + self._upper_dst = maps["upper"] |
| 129 | + self._group_results = maps["results"] |
| 130 | + self._compiled_source = id(op) |
| 131 | + return self._compiled.sub(lambda m: self._group_repl(m, text), text) |
| 132 | + if kind == "subst": |
| 133 | + flags = re.IGNORECASE if op.get("ignore_case") else 0 |
| 134 | + pattern = re.compile(op["pattern"], flags) |
| 135 | + result = re.sub(r"\$(\d)", r"\\\1", op["result"]) |
| 136 | + return pattern.sub(result, text) |
| 137 | + if kind == "run": |
| 138 | + target = op["map"] |
| 139 | + if target.startswith("map."): |
| 140 | + # dotted dependency reference: map.<alias>.stage.<name> |
| 141 | + alias = target.split(".")[1] |
| 142 | + deps = { |
| 143 | + d.get("alias") or d["name"]: d["name"] |
| 144 | + for d in self.tree.get("dependencies", []) |
| 145 | + if isinstance(d, dict) |
| 146 | + } |
| 147 | + if alias not in deps: |
| 148 | + raise ExecutionError(f"run {target!r}: unknown dependency alias") |
| 149 | + target = deps[alias] |
| 150 | + if self._loader is None: |
| 151 | + raise ExecutionError(f"run {op['map']!r}: no map loader configured") |
| 152 | + return self._loader(target).transliterate(text) |
| 153 | + if kind == "downcase": |
| 154 | + return text.lower() |
| 155 | + if kind == "upcase": |
| 156 | + return text.upper() |
| 157 | + if kind == "titlecase": |
| 158 | + return text.title() |
| 159 | + if kind == "compose": |
| 160 | + return unicodedata.normalize("NFC", text) |
| 161 | + if kind == "decompose": |
| 162 | + return unicodedata.normalize("NFD", text) |
| 163 | + what = op.get("what", kind) |
| 164 | + if self.on_unsupported == "skip": |
| 165 | + self.skipped_unsupported.append(str(what)) |
| 166 | + return text |
| 167 | + raise ExecutionError(f"unsupported construct: {what!r}") |
0 commit comments