feat: support user-defined functions and classes in Ren'Py python

- Converter: def/return/global/nonlocal, class (inheritance, property,
  staticmethod, classmethod), lambda, *args/**kwargs and call-site unpacking.
  Unsupported dunder methods, generators and unknown decorators are still refused
- Player: closures, super(), instances that survive save/load, isinstance,
  hasattr/getattr/setattr, map/filter/sorted(key=), recursion limit
- audit_ir accepts calls to names, classes and methods the game defines itself;
  unknown renpy.* calls still block the import. Volume/pan/pause/replay calls
  are accepted as presentation-only no-ops; build.* settings are skipped
- Tests: IR fixture compiled from tests/fixtures/classes.py (tests/make_ir.py)
  and run in the interpreter; converter tests updated

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
mrleo1nidandClaude Sonnet 5.5 committed 2026-10-25 12:01:09 +03:00
1 parent 12ec82c7e6
commit 962595c925
12 files changed
+782 -23

No files matched your search

+53 -2
View File
@@ -99,11 +99,60 @@ CALLS |= {"renpy." + method for method in ("play", "notify", "jump", "call", "in
"seen_label", "showing", "get_attributes", "full_restart", "quit", "version")}
CALLS |= {f"renpy.{channel}.{method}" for channel in ("music", "sound")
for method in ("play", "queue", "stop", "get_playing", "is_playing")}
# Presentation-only calls the player accepts and ignores (volume/pan/pause tweaks, replay and
# rollback bookkeeping). They never change the story state.
CALLS |= {f"renpy.{channel}.{method}" for channel in ("music", "sound")
for method in ("set_volume", "set_pause", "set_pan")}
CALLS |= {"renpy.end_replay", "renpy.block_rollback"}
CALLS |= {"map", "filter", "hasattr", "getattr", "setattr", "callable", "super"}
METHODS = set("append extend insert pop remove index count reverse sort clear copy add discard get keys values items setdefault update lower upper capitalize title strip lstrip rstrip startswith endswith replace split join format find isdigit isalpha".split())
def _bound_names(root) -> tuple[set[str], set[str]]:
"""Names the game binds itself and the method names of its classes.
Calling any of them is the game's own code, which the player interprets.
"""
names: set[str] = set()
methods: set[str] = set()
def target(value):
if isinstance(value, dict):
if value.get("k") == "name":
names.add(value["id"])
elif value.get("k") == "tuple":
for item in value["v"]:
target(item)
def visit(value, in_class=False):
if isinstance(value, list):
for item in value:
visit(item, in_class)
elif isinstance(value, dict):
op, kind = value.get("op"), value.get("k")
if op == "def":
(methods if in_class else names).add(value["name"])
names.update(p["n"] for p in value["params"])
elif op == "class":
names.add(value["name"])
elif op in ("set", "aug", "for"):
target(value.get("t"))
elif kind == "lambda":
names.update(p["n"] for p in value["params"])
elif kind == "comp":
target(value.get("t"))
for key, child in value.items():
visit(child, op == "class" and key == "body")
visit(root)
return names, methods
def audit_ir(data) -> None:
"""Reject calls which the browser would otherwise silently replace by None."""
user_names, user_methods = _bound_names([data.modules, data.init_code, data.defaults, data.images])
user_names |= {name for name, _ in data.defaults}
def dotted(value):
if value.get("k") == "name":
return value["id"]
@@ -119,8 +168,10 @@ def audit_ir(data) -> None:
if value.get("k") == "call":
function = value.get("f", {})
name = dotted(function)
if name not in CALLS and not (function.get("k") == "attr" and
function.get("a") in METHODS and not name.startswith(("renpy.", "math.", "random."))):
is_method = (function.get("k") == "attr" and not name.startswith(("renpy.", "math.", "random."))
and (function.get("a") in METHODS or function.get("a") in user_methods
or function.get("a") in user_names))
if name not in CALLS and name not in user_names and not is_method:
data.warn(f"Вызов не поддерживается плеером: {name or 'динамическая функция'}", location)
if value.get("op") in {"jump", "call"} and value.get("target"):
if value["target"] not in labels: