Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 33 additions & 2 deletions interscript-py/src/interscript/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,10 @@ def _execute_sub_rule(rule: SubRule, ctx: ExecutionContext) -> None:
def _resolve_template(template: str, m: regex.Match) -> str:
"""Resolve `$1`, `$2`, ... capture references in a replacement
template. `$'`/`` $` ``/`$$` are NOT interpreted (literal), matching
the TS runtime. Out-of-range references resolve to the whole match.
the TS runtime. Ruby gsub semantics (rs ``decode_replacement``
parity): a reference whose group did not participate — or does not
exist in the pattern at all (reversed rules re-reference groups
their reversed pattern lost) — inserts the EMPTY string.
"""

def repl(tmpl_match: regex.Match) -> str:
Expand All @@ -207,7 +210,7 @@ def repl(tmpl_match: regex.Match) -> str:
group = m.group(idx)
except IndexError:
group = None
return group if group is not None else m.group(0)
return group if group is not None else ""

return regex.sub(r"\$(\d+)", repl, template)

Expand Down Expand Up @@ -252,6 +255,18 @@ def _execute_funcall(rule: FuncallRule, ctx: ExecutionContext) -> None:
# ---------------------------------------------------------------------------


def _backref_without_group(pattern: str) -> bool:
"""Does this rule pattern carry a `\\N` backreference to a capture
group the pattern itself does not define? Machine-generated rule
patterns only: capture groups open with `(` not followed by `?`
(lookarounds and `(?:` are not capture groups). Such a rule can
never match (rs match_item fails a ref on an unparticipated group),
so a megaregexp pass drops it instead of failing the combined
compile (WO20 reverse-golden bgnpcgn-zho)."""
group_count = len(regex.findall(r"\((?!\?)", pattern))
return any(int(n) > group_count for n in regex.findall(r"\\(\d+)", pattern))


def _tree_compatible(rule: SubRule, ctx: ExecutionContext) -> bool:
return (
rule.before is None
Expand Down Expand Up @@ -327,6 +342,22 @@ def sort_key(pair: tuple[int, SubRule]):
after = compile_item(r.after, ctx, True).re if r.after else ""
not_before = compile_item(r.not_before, ctx, True).re if r.not_before else ""
not_after = compile_item(r.not_after, ctx, True).re if r.not_after else ""
# A from-pattern backreference to a group the pattern does
# not itself define (reversed rules re-reference capture
# groups their reversal hoisted away — the WO20
# reverse-golden bgnpcgn-zho family) can never match: rs
# `match_item` fails the ref on an unparticipated group,
# and the combined alternation would refuse to compile.
# Drop the rule, mirroring the rs never-matches semantics.
full = (
(f"(?<={before})" if before else "")
+ (f"(?<!{not_before})" if not_before else "")
+ src
+ (f"(?={after})" if after else "")
+ (f"(?!{not_after})" if not_after else "")
)
if _backref_without_group(full):
continue
compiled.append((r, src, before, after, not_before, not_after))
# §5.2 at pattern level: identical compiled `from` source under a
# guard-applicable rule shadows the unguarded one.
Expand Down
10 changes: 8 additions & 2 deletions interscript-py/src/interscript/items.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,12 +171,18 @@ def compile_item(
)
if kind == "repeat":
assert isinstance(item, RepeatItem)
inner = compile_item(item.item, ctx).re
inner = compile_item(item.item, ctx)
if item.max is None:
quant = "*" if item.min == 0 else "+"
else:
quant = f"{{{item.min},{item.max}}}"
return _compiled(f"(?:{inner}){quant}", "")
# Replacement-position collapse mirrors Ruby `Repeat#nth_string`
# (= data.nth_string): a maybe/some contributes its inner data's
# string, not the quantifier and not an empty string. The
# empty-literal reading dropped the restored segment on reversed
# rules whose `to` carries a maybe (the WO20 reverse-golden
# bgnpcgn-ara-1956 / hin-Deva / odni-ara / yaghoubi families).
return _compiled(f"(?:{inner.re}){quant}", inner.literal)
if kind == "stage_ref":
# Stage references are handled by the executor, not by item
# compilation.
Expand Down
39 changes: 33 additions & 6 deletions interscript-py/src/interscript/stdlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,28 @@ def _sub(m: regex.Match) -> str:
return rule.replace(m.group(0), captures[start : start + n])
return m.group(0)

return mega.sub(_sub, text)
# Ruby gsub scan semantics: attempt the megaregexp at every position
# INCLUDING the end, and after a zero-width match skip one character
# (ruby cannot loop an empty match). Python's regex.sub continues at
# the SAME position after an empty match — the next alternative then
# also fires there, double-inserting where ruby inserts once (the
# WO20 reverse-golden bgnpcgn-prs/pus family). Mirrors rs
# `apply_parallel`'s megaregexp loop.
parts: list[str] = []
copied = 0 # text[:copied] already emitted
pos = 0
n = len(text)
while pos <= n:
m = mega.match(text, pos)
if m is not None:
parts.append(text[copied : m.start()])
parts.append(_sub(m))
copied = m.end()
pos = max(m.end(), pos + 1)
else:
pos += 1
parts.append(text[copied:])
return "".join(parts)


# ---------------------------------------------------------------------------
Expand All @@ -170,14 +191,20 @@ def upcase(text: str, opts: dict | None = None) -> str:

def title_case(text: str, opts: dict | None = None) -> str:
"""`Interscript::Stdlib::Functions.title_case` / rs `title_case`
parity: upcase the FIRST character of the string, then the
parity: upcase the first character of each LINE, then the
character following each word separator. Other characters are
untouched (ruby `gsub(/^(.)/)` + `gsub(/#{sep}(.)/)` — notably NOT
full per-word title-casing)."""
untouched (ruby `gsub(/^(.)/)` + `gsub(/#{sep}(.)/)` — ruby `^` is
line-anchored, so `gsub(/^(.)/)` upcases the head of every line;
the string-head-only reading deviated from the ruby ground truth on
reversed-downcase runs — the WO20 reverse-golden
un-ell-Grek-Latn-1987-phonetic family)."""
sep = (opts or {}).get("wordSeparator", " ")
chars = list(text)
if chars:
chars[0] = chars[0].upper()
at_line_start = True
for k, c in enumerate(chars):
if at_line_start and c != "\n":
chars[k] = c.upper()
at_line_start = c == "\n"
if sep == "":
return "".join(chars)
sep_chars = list(sep)
Expand Down
11 changes: 9 additions & 2 deletions interscript-py/tests/test_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,13 +95,20 @@ def test_captures(self):
m = make_map([stage("main", [rule])])
assert execute_stage(m, "main", "ab ab") == "aa aa"

def test_capture_out_of_range_resolves_to_match(self):
def test_capture_out_of_range_inserts_empty(self):
# rs `decode_replacement` / ruby gsub parity: a `$N` reference
# whose group did not participate — or does not exist in the
# pattern at all — inserts the EMPTY string, never the whole
# match. Reversed rules re-reference capture groups their
# reversal hoisted away (the WO20 reverse-golden hin-Deva
# family), so the whole-match fallback there deleted nothing
# and diverged from the rs golden.
rule = SubRule(
from_=StringItem(value="a"),
to=CaptureRefItem(id=3),
)
m = make_map([stage("main", [rule])])
assert execute_stage(m, "main", "ab") == "ab"
assert execute_stage(m, "main", "ab") == "b"


class TestParallel:
Expand Down
55 changes: 43 additions & 12 deletions interscript-py/tests/test_golden_reverse.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,15 +69,7 @@ def resolve_dependency(target: str):
resolve_dependency=resolve_dependency,
)
compiled = {stem: isc_to_compiled_map(doc) for stem, doc in docs.items()}

class _Resolver:
"""MapResolver over the in-memory corpus (the MapLoader protocol:
.load(system_code))."""

def load(self, system_code: str):
return compiled[system_code]

return compiled, _Resolver()
return compiled


@pytest.mark.skipif(
Expand All @@ -91,7 +83,46 @@ def test_golden_reverse_capture_additivity() -> None:
if line.strip()
]
assert rows, "reverse golden file has no rows"
compiled, resolver = _build_corpus()
compiled = _build_corpus()

# rs reverse_document reverses the dependency CLOSURE with the
# parent (ruby Dependency#reverse parity). The compiled IR carries
# dependency names, not documents, so the replay must serve
# reversed dependency maps to the run rules — Runtime.reverse's
# _ReversedDependencyResolver flow. Replaying reverse_map against
# forward deps made every run-carrying reverse doc execute the
# FORWARD dependency stage (the WO20 91-map identity-output family:
# alalc-rus-2012's "Azov" etc.).
reversed_closure: dict[str, tuple[object, dict[str, object]]] = {}

def _reversed_closure(name: str) -> tuple[object, dict[str, object]]:
if name in reversed_closure:
return reversed_closure[name]
map_ = compiled[name]
revs: dict[str, object] = {}

def collect(m: object) -> None:
for dep in m.dependencies: # type: ignore[union-attr]
if dep in revs:
continue
dep_map = compiled[dep]
revs[dep] = reverse_map(dep_map)
collect(dep_map)

collect(map_)
entry = (reverse_map(map_), revs)
reversed_closure[name] = entry
return entry

class _ReversedResolver:
"""Serves reversed dependency documents under their forward
names (run rules reference the forward names)."""

def __init__(self, revs: dict[str, object]) -> None:
self._revs = revs

def load(self, system_code: str):
return self._revs[system_code]

deltas: list[str] = []
failed_maps: set[str] = set()
Expand All @@ -103,8 +134,8 @@ def test_golden_reverse_capture_additivity() -> None:
got = "null"
else:
try:
reversed_map = reverse_map(compiled_map)
got = execute_stage(reversed_map, "main", row["src"], resolver)
reversed_map, revs = _reversed_closure(map_id)
got = execute_stage(reversed_map, "main", row["src"], _ReversedResolver(revs))
except Exception: # noqa: BLE001 — mirror the rs/ts/ruby gates
got = "null"
checked += 1
Expand Down
Loading