feat(tracker): map script types through runner_map

Types follow CMC_RunnerFactory when the snapshot has it, so the shared
variable runner no longer forms a VARIABLE pseudo-type. Base CMC_Runner
verbs are listed once under * and referenced via inherits; type 0 becomes
the @ scope, matched against CodeParser.dispatchSpecialCall.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Patryk Gensch
2026-10-24 18:37:17 +02:00
co-authored by Claude Opus 5.5
parent 5c597a3a52
commit 87fcefa877
3 changed files with 185 additions and 33 deletions
+108 -28
View File
@@ -46,16 +46,55 @@ def code_mask(text: str) -> str:
return JAVA_TOKENS.sub(lambda m: re.sub(r"[^\n]", " ", m.group()), text)
def closing(code: str, start: int) -> int:
def closing(code: str, start: int, pair: str = "()") -> int:
depth = 0
for i in range(start, len(code)):
if code[i] == "(":
if code[i] == pair[0]:
depth += 1
elif code[i] == ")":
elif code[i] == pair[1]:
depth -= 1
if depth == 0:
return i + 1
raise ValueError("Unbalanced MethodSpec registration")
raise ValueError("Unbalanced " + pair)
BUILTINS_SOURCE = "pl/genschu/bloomooemulator/interpreter/parser/CodeParser.java"
BUILTINS_DISPATCH = re.compile(r"\bdispatchSpecialCall\s*\([^)]*\)\s*\{")
CASE_ARM = re.compile(r"\bcase\b([^;{}]*?)->|\bdefault\b\s*->")
def scan_builtins(root: Path, source_root: Path) -> dict | None:
"""`@IF`, `@LOOP`, ... are parsed by CodeParser.dispatchSpecialCall, not registered as
MethodSpec: each `case "NAME", ... ->` arm of its switch is one built-in statement."""
path = source_root / BUILTINS_SOURCE
if not path.is_file():
return None
text = path.read_text(encoding="utf-8")
code = code_mask(text)
head = BUILTINS_DISPATCH.search(code)
if head is None:
return None
switch = code.index("switch", head.end())
body_start = code.index("{", switch)
body_end = closing(code, body_start, "{}")
arms = list(CASE_ARM.finditer(code, body_start, body_end))
methods = {}
for arm, following in zip(arms, arms[1:] + [None]):
if arm.group(1) is None:
continue # default arm: unknown statements are a parse error
end = following.start() if following else body_end
body = text[arm.start():end]
status = "registered"
notes = []
if re.search(r"not (?:yet )?implemented", body, re.I) or "UnsupportedOperationException" in body:
status = "stub_candidate"
notes.append("Heurystyka: wyjątek lub komunikat o braku implementacji; wymaga przeglądu.")
for name in re.findall(r'"([A-Za-z_]+)"', text[arm.start(1):arm.end(1)]):
methods[name.upper()] = {"status": status, "notes": list(notes), "source": {
"path": str(path.relative_to(root)), "line": text.count("\n", 0, arm.start()) + 1,
"owner": "@", "body_sha256": digest(body.encode()), "file_sha256": digest(text.encode())}}
return {"methods": methods, "mapping_notes": [
"Instrukcje @ są rozpoznawane w CodeParser.dispatchSpecialCall, nie przez MethodSpec."]}
def _git(root: Path, *args: str) -> str | None:
@@ -110,6 +149,9 @@ def scan_emulator(root: Path) -> dict:
"owner": name, "body_sha256": digest(body.encode()), "file_sha256": digest(text.encode()),
}}
types[name] = {"methods": methods, "mapping_notes": notes}
builtins = scan_builtins(root, source_root)
if builtins is not None:
types["@"] = builtins
return {"root": str(root), "commit": _git(root, "rev-parse", "HEAD"),
"dirty": bool(_git(root, "status", "--porcelain")),
"source_tree_sha256": tree.hexdigest(), "types": types, "warnings": warnings}
@@ -123,6 +165,44 @@ def owner_name(owner: str) -> str:
return canonical(owner.removeprefix("CMC_"))
BASE_SCOPE = "*"
# getRunner(0) is the runner behind `@IF`, `@LOOP`, ... statements, not an object type.
BUILTIN_SCOPE, BUILTIN_TYPE_ID = "@", 0
def script_owners(snap: Snapshot, owners) -> dict[str, tuple[str, str]]:
"""Script scope -> (method owner, provenance) for one binary.
`runner_map` (CMC_RunnerFactory, Piklib 7.1+/BlooMoo) is the engine's own dispatch table and
wins: several types can share a runner (INTEGER/STRING/... -> Variable). Without it (Piklib
6.1, plugins, older extractions) the C++ class or its name is the best available guess."""
runner_map = snap.raw.get("runner_map") or {}
by_type_id = {e["type_id"]: e["runner"].removesuffix("_Runner") for e in runner_map.get("by_type_id", [])}
mappings = {}
if BUILTIN_TYPE_ID in by_type_id:
mappings[BUILTIN_SCOPE] = (by_type_id[BUILTIN_TYPE_ID], "runner_factory")
for t in snap.types:
name = canonical(t["script_name"])
if t.get("type_id") in by_type_id:
mappings[name] = (by_type_id[t["type_id"]], "runner_factory")
continue
owner, mapping = t.get("cpp_class"), "explicit"
# Known extractor failure: unrelated factory entries all mapped to Behaviour.
if owner == "CMC_Behaviour" and name != "BEHAVIOUR":
owner = None
if not owner:
candidate = [o for o in owners if owner_name(o) == name]
owner, mapping = (candidate[0] if len(candidate) == 1 else None), "inferred"
if owner:
mappings[name] = (owner, mapping)
used = {owner for owner, _ in mappings.values()}
for owner in owners:
# Singletons (SYSTEM, SCENE, ...) and the base scope run without a factory type.
if owner not in used and owner_name(owner) not in mappings:
mappings[owner_name(owner)] = (owner, "inferred")
return mappings
def build_tracker(snapshots: list[Snapshot], emulator: dict, reviews: list[dict] | None = None) -> dict:
"""Join script APIs, keeping every binary and inherited declaration as evidence."""
warnings = list(emulator.get("warnings", []))
@@ -174,39 +254,30 @@ def build_tracker(snapshots: list[Snapshot], emulator: dict, reviews: list[dict]
parents = defaultdict(list)
for edge in snap.method_inheritance:
parents[edge["runner"].removesuffix("_Runner")].append(edge["base_runner"].removesuffix("_Runner"))
mappings = {}
used_owners = set()
mappings = script_owners(snap, owners)
for t in snap.types:
name = canonical(t["script_name"])
row = type_row(name)
owner = t.get("cpp_class")
mapping = "explicit"
row = type_row(canonical(t["script_name"]))
if t.get("cpp_class_provenance"):
row["mapping_notes"].append(t["cpp_class_provenance"])
# Known extractor failure: unrelated factory entries all mapped to Behaviour.
if owner == "CMC_Behaviour" and name != "BEHAVIOUR":
owner = None
if not owner:
candidate = [o for o in owners if owner_name(o) == name]
owner = candidate[0] if len(candidate) == 1 else None
mapping = "inferred"
if owner:
mappings[name] = (owner, mapping)
used_owners.add(owner)
else:
if canonical(t["script_name"]) not in mappings:
row["mapping_notes"].append(f"{snap.binary.get('name', '?')}: typ wykryty, klasa/metody nieustalone.")
for owner in owners:
if owner not in used_owners:
# Includes singleton classes and separate base scopes. Label inference explicitly.
name = owner_name(owner)
if name not in mappings:
mappings[name] = (owner, "inferred")
sharing = defaultdict(set)
for name, (owner, _) in mappings.items():
sharing[owner].add(name)
for name, (owner, mapping) in mappings.items():
if len(sharing[owner]) > 1:
type_row(name)["mapping_notes"].append(
f"Wspólny runner {owner}_Runner z: {', '.join(sorted(sharing[owner] - {name}))}. "
"Rejestracja nie mówi, które metody działają dla tego typu.")
visited = set()
def add(current, inherited=False):
if current in visited:
return
visited.add(current)
if inherited and owner_name(current) == BASE_SCOPE and name != BASE_SCOPE:
# Base verbs (SEND, CLONE, ...) belong to every runner; they are listed once.
type_row(name).setdefault("inherits", []).append(BASE_SCOPE)
return
for m in owners[current]:
row = method_row(name, m["name"].upper())
if len(name_ids[(current, m["name"].upper())]) > 1:
@@ -247,6 +318,11 @@ def build_tracker(snapshots: list[Snapshot], emulator: dict, reviews: list[dict]
if row["source"] is None and method in globals_:
row.update(globals_[method])
row["notes"] = row["notes"] + ["Obsługa przez globalny fallback Variable."]
base_verbs = {m for m, row in rows.get(BASE_SCOPE, {}).get("methods", {}).items() if row["original"]}
for name, t in rows.items():
for method, row in t["methods"].items():
if name != BASE_SCOPE and method in base_verbs and row["source"] and not row["original"]:
row["notes"].append("W oryginale metoda bazowa (*) każdego runnera; emulator rejestruje ją lokalnie.")
# Reviews are declarative, version-controlled assertions; strict anchors prevent
# accidentally making an entire family green based on one stale binary/address.
for review in reviews or []:
@@ -276,6 +352,8 @@ def build_tracker(snapshots: list[Snapshot], emulator: dict, reviews: list[dict]
row["verification"] = "stale"
t["methods"] = sorted(t["methods"].values(), key=lambda m: m["name"])
t["mapping_notes"] = sorted(set(t["mapping_notes"]))
if "inherits" in t:
t["inherits"] = sorted(set(t["inherits"]))
all_rows = [m for t in rows.values() for m in t["methods"]]
return {"schema": "tracker/1", "emulator": {k: v for k, v in emulator.items() if k not in ("types", "warnings")},
"binaries": sorted(binaries, key=lambda b: (b["name"].lower(), b["id"])),
@@ -284,7 +362,9 @@ def build_tracker(snapshots: list[Snapshot], emulator: dict, reviews: list[dict]
"verification": dict(Counter(m["verification"] for m in all_rows))},
"warnings": warnings + ["Brak obserwacji w wariancie oznacza nieustalone, nie brak metody.",
"Rejestracja Java nie dowodzi poprawności. Liczniki obejmują pary typ/metoda, także odziedziczone.",
"Dopasowania klas po nazwie są wnioskowane; zakres * to metody bazowe/globalne."]}
"Typ → runner pochodzi z CMC_RunnerFactory, gdy snapshot ma runner_map; inaczej z nazwy klasy (wnioskowane).",
"Zakres * to metody bazowe CMC_Runner, wspólne dla każdego typu (pole inherits); nie są powielane przy typach.",
"Zakres @ to wbudowane instrukcje @IF/@LOOP/... (runner typu 0)."]}
def validate_review(review: dict) -> None: