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
67 changes: 58 additions & 9 deletions src/interscript/isc.py
Original file line number Diff line number Diff line change
Expand Up @@ -726,10 +726,7 @@ def _quoted_string(self) -> str:
elif nxt in {"n", "t", "r", '"', "\\"}:
result += {"n": "\n", "t": "\t", "r": "\r", '"': '"', "\\": "\\"}[nxt]
elif nxt == "U":
# esc_u_lone/esc_uni: the capital form is deliberately
# NOT decoded here (see _unicode_escape) — a literal
# "U"; the digits stay raw text.
result += "U"
result += self._capital_unicode_escape()
else:
# maps#293 (WO20 fuzz): the grammar's escape_sequence
# admits only n r t double-quote backslash uXXXX and
Expand All @@ -745,6 +742,36 @@ def _quoted_string(self) -> str:
result += c
self._error("Unterminated string")

def _capital_unicode_escape(self) -> str:
"""Decode ``\\U`` per the grammar's ordered escape alternatives
(``grammar/isc.parg``): esc_uni = ``"U" (4*8hexd) as unicode``
decodes 4 to 8 hex digits, greedily, to one code point — the
WO19 G6 ruling (BOTH spellings decode; ruby/rs always did, ts
since the gki-bel ``"\\U040E"`` fix). With fewer than 4 hex
digits esc_uni fails and esc_u_lone renders a literal ``"U"``;
the digits then stay raw text (measured on ruby 4/4:
``"\\Uab"`` → ``Uab``). The first 8 hex digits are consumed, so
a 9th remains raw (``"\\U000000410"`` → ``A0``, ruby-verified).

The capital form was previously rendered as a bare ``"U"`` with
the digits as raw text — a stale 0.1.x ts hand-parser parity
note (ts decodes since the G6 fix), which left the three
Belarusian uppercase-Ў rows (gki-bel-2000 / mvd-bel-2008 /
odni-bel-2015: ``sub "\\U040E" "W"-style`` rules) unfired and
diverging from the golden corpus.
"""
start = self._pos
digits = self._src[start : start + 8]
n = 0
while n < len(digits) and digits[n] in "0123456789abcdefABCDEF":
n += 1
if n < 4:
# esc_u_lone: a lone "U"; the raw digits (if any) are
# consumed as ordinary text by the main loop.
return "U"
self._pos = start + n
return chr(int(digits[:n], 16))

def _unicode_escape(self) -> str:
"""Decode ``\\uXXXX`` — the grammar's esc_uni4 (exactly 4 hex
digits, ``grammar/isc.parg``). Any other form (short hex,
Expand All @@ -754,11 +781,10 @@ def _unicode_escape(self) -> str:
fuzz campaign's largest crash class — it fires on note text too,
which shares this scanner).

The capital ``\\U`` form is deliberately NOT decoded by this
parser: the grammar's esc_u_lone branch renders it as a literal
"U" with the digits as raw text — the same deviation ts carries
in its actions.ts (ruby's artifact parser decodes both
spellings; aligning the runtimes is an owner decision).
Unlike ``\\u`` (esc_uni4, exactly 4 — no later alternative can
match a lowercase ``u``, so a short form fails the string
production), the capital ``\\U`` falls back to esc_u_lone with
fewer than 4 hex digits — see ``_capital_unicode_escape``.
"""
slash = self._pos - 2 # the backslash, for the error position
digits = self._src[self._pos : self._pos + 4]
Expand Down Expand Up @@ -1409,6 +1435,20 @@ def isc_to_tree(source: str, filename: str | None = None, on_unsupported: str =
# the document owning the items being expanded — nested `use` items
# resolve against their OWNER, not this document.

# WO18 G7 (py canon): a ruleset declared more than once is a named
# load error — keep-first/last-wins silently hides map bugs and
# makes the executed body declaration-order dependent (ruby
# document_builder raises MapLogicError, ts expand.ts IscLoadError,
# rs builder.rs MapLogicError; spec §6 item 4's load-error surface
# for cycles, extended to duplicate definition). The 0.2.x parser
# rewrite lost the 0.1.0 check — the last def silently won.
seen_rulesets: set[str] = set()
for r in doc["rulesets"]:
if r["name"] in seen_rulesets:
raise UnsupportedConstruct(
f'ruleset "{r["name"]}" declared more than once in {doc["systemCode"]}'
)
seen_rulesets.add(r["name"])
doc_rulesets = {r["name"]: r["body"] for r in doc["rulesets"]}

def _owner_rulesets(target: str) -> tuple[str, dict, dict]:
Expand All @@ -1427,6 +1467,15 @@ def _owner_rulesets(target: str) -> tuple[str, dict, dict]:
f"use: cannot resolve dependency {target!r} (needed for its rulesets)"
)
dep_doc = _dep_doc_cached(str(path), path)
# Same G7 check as the loading document: the trio validate every
# document they build, dependency docs included.
dep_seen: set[str] = set()
for r in dep_doc["rulesets"]:
if r["name"] in dep_seen:
raise UnsupportedConstruct(
f'ruleset "{r["name"]}" declared more than once in {dep_doc["systemCode"]}'
)
dep_seen.add(r["name"])
dep_rulesets = {r["name"]: r["body"] for r in dep_doc["rulesets"]}
dep_dep_aliases = {
d["aliasName"]: d["target"] for d in dep_doc["dependencies"] if d.get("aliasName")
Expand Down
48 changes: 35 additions & 13 deletions tests/test_isc.py
Original file line number Diff line number Diff line change
Expand Up @@ -511,20 +511,42 @@ def test_valid_escape_still_decodes():
assert rule["from"] == {"type": "string", "value": "é"}


def test_capital_escape_stays_literal_u():
"""Capital \\U is NOT decoded by this parser: the grammar's esc_u_lone
branch renders a literal "U" and the digits stay raw text (the ts
hand-parser parity deviation in actions.ts; ruby's artifact parser
decodes both spellings — cross-runtime alignment is an owner
decision). Malformed \\U therefore never raises; it must also never
crash (#44's adjacent shape)."""
def test_capital_escape_decodes_and_falls_back():
"""Capital \\U follows the grammar's ordered alternatives: esc_uni
decodes 4..8 hex digits (greedy) to one code point; with fewer than
4 hex digits esc_u_lone renders a literal "U" and the digits stay
raw text. Both spellings decode — the WO19 G6 ruling (ruby/rs
always decoded; ts since the gki-bel "\\U040E" fix).

The capital form was previously rendered as a bare "U" with the
digits as raw text (a stale 0.1.x ts hand-parser parity note), so
the three Belarusian uppercase-Ў rows (gki-bel-2000 / mvd-bel-2008
/ odni-bel-2015, `sub "\\U040E" "W"-style`) never fired and
diverged from the rs golden corpus.

Edge shapes are ruby-measured (4/4 with this parser):
"\\U00000041" → "A"; "\\U000000410" → "A0" (first 8 hex consumed,
the 9th stays raw); "\\U00e9" → "é"; "\\Uab" → "Uab". Malformed
capital forms never raise (#44's adjacent shape).
"""
system = 'system "x" { stage main { sub %s "X" } }'
doc = _parse_only(system % '"\\UZZZZ"')
rule = doc["stages"][0]["body"][0]["rule"]
assert rule["from"] == {"type": "string", "value": "UZZZZ"}
doc = _parse_only(system % '"\\U00E"')
rule = doc["stages"][0]["body"][0]["rule"]
assert rule["from"] == {"type": "string", "value": "U00E"}

def from_value(literal):
doc = _parse_only(system % literal)
return doc["stages"][0]["body"][0]["rule"]["from"]["value"]

# esc_uni: 4..8 hex digits decode, both hex casings
assert from_value('"\\U040E"') == "Ў"
assert from_value('"\\U045E"') == "ў"
assert from_value('"\\U00e9"') == "é"
assert from_value('"\\U00000041"') == "A"
# greedy 8-hex cap: a 9th hex digit stays raw text
assert from_value('"\\U000000410"') == "A0"
# esc_u_lone fallback: fewer than 4 hex digits — literal "U",
# digits raw, and never a raise
assert from_value('"\\Uab"') == "Uab"
assert from_value('"\\U00E"') == "U00E"
assert from_value('"\\UZZZZ"') == "UZZZZ"


# --- maps#293 (WO20 fuzz): the parse accept/reject boundary must match
Expand Down
59 changes: 44 additions & 15 deletions tests/test_wf1.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,43 @@ def test_use_cycle_and_unknown_ruleset_are_named_load_errors():
_parse(unknown)


def test_duplicate_ruleset_declaration_is_a_named_load_error():
"""WO18 G7 (py canon): `ruleset a` declared twice is a named load
error — keep-first (ruby/ts) and last-wins/merge (rs pre-fix, py
0.2.x) silently hide map bugs and make the executed body
declaration-order dependent. ruby (MapLogicError), ts (IscLoadError)
and rs (MapLogicError) reject; the 0.2.x parser rewrite lost the
0.1.0 check. Spec §6 item 4's load-error surface for cycles,
extended to duplicate definition (maps docs/parity G7)."""
block_use = (
'system "x" {\n'
"ruleset a {\n"
" sequence { sub \"x\" \"1\" }\n"
"}\n"
"ruleset a {\n"
" sequence { sub \"z\" \"3\" }\n"
"}\n"
"stage main {\n"
" sequence { use a }\n"
"}\n"
"}\n"
)
stage_use = (
'system "x" {\n'
"ruleset a {\n"
" parallel { sub \"x\" \"1\" }\n"
"}\n"
"ruleset a {\n"
" parallel { sub \"z\" \"3\" }\n"
"}\n"
"stage main { use a }\n"
"}\n"
)
for src in (block_use, stage_use):
with pytest.raises(UnsupportedConstruct, match='ruleset "a" declared more than once'):
_parse(src)


@corpus
def test_thai_maps_load_and_splice_the_dependency_ruleset():
"""alalc-tha-2011 and bgnpcgn-tha-2002 failed at `parallel` before:
Expand Down Expand Up @@ -339,23 +376,17 @@ def test_full_corpus_parses():
@corpus_and_golden
def test_golden_corpus_replay():
"""tests/golden/isc-wf0.jsonl (the rs golden corpus, 16,322 rows over
453 maps) replays byte-identically.

KNOWN PRE-EXISTING EXCLUSION (execution-level, NOT a parse gap):
the three Belarusian maps' uppercase-Ў rows — ruby derives the
uppercase rule from the `sub "ў" "ŭ"`-style row, py does not fire it
(3 rows across gki-bel-2000 / mvd-bel-2008 / odni-bel-2015; the maps
load on both sides and already diverged before this fix). Tracked
outside #47.
453 maps) replays byte-identically, with no exclusions.

The former exclusion (all rows of gki-bel-2000 / mvd-bel-2008 /
odni-bel-2015) is gone: the capital-``\\U`` escape now decodes
4..8 hex digits (esc_uni, the WO19 G6 ruling both spellings
decode), so the three maps' uppercase-Ў rules fire and the corpus
converges 16,322/16,322.
"""
import interscript

interscript.add_load_path(str(LIBS))
excluded = {
"gki-bel-Cyrl-Latn-2000",
"mvd-bel-Cyrl-Latn-2008",
"odni-bel-Cyrl-Latn-2015",
}
rows = [
json.loads(line)
for line in GOLDEN.read_text(encoding="utf-8").splitlines()
Expand All @@ -364,8 +395,6 @@ def test_golden_corpus_replay():
engines: dict[str, Engine] = {}
mismatches = []
for row in rows:
if row["map"] in excluded:
continue
engine = engines.get(row["map"])
if engine is None:
engines[row["map"]] = engine = interscript.load_map(row["map"])
Expand Down
Loading