feat: add ATL animation timelines and try/raise to the Ren'Py player

Python sandbox
- try/except/else/finally, raise (incl. re-raise), assert, for/while ... else
- Multi-generator and dict comprehensions
- Builtin exception hierarchy; user exceptions subclass it
- Inside try, missing keys/indexes, division by zero, attribute access on None
  and unknown names raise Python exceptions; lookups stay lenient elsewhere
- int()/float() raise ValueError on non-numeric strings

ATL
- converter/atl.py: set/move (linear, ease, easein, easeout), pause, repeat,
  parallel, choice, block, on show/hide and named transforms become a timeline
  shipped as game.json "atl"; Move() becomes a linear slide
- player/atl.ts: timeline runner wired into the renderer; `on hide` plays
  before the picture is removed
- function, time, contains, matrixcolor and expressions still block the import

Tests: exceptions/ATL fixtures and runtime tests, converter ATL tests; README
and ARCHITECTURE 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:11:07 +03:00
1 parent 962595c925
commit ff82d882c0
18 files changed
+1050 -53

No files matched your search

+178 -13
View File
@@ -88,6 +88,39 @@ class PyDescriptor {
export const OBJECT = new PyClass("object", []);
const classRegistry = new Map<string, PyClass>();
/** Builtin exception hierarchy; ``args`` holds the constructor arguments. */
export const BASE_EXCEPTION = new PyClass("BaseException", [OBJECT]);
BASE_EXCEPTION.attrs.set("__init__", (self: PyInstance, ...args: any[]) => {
const last = args[args.length - 1];
self.attrs.args = last && typeof last === "object" && !Array.isArray(last) && Object.hasOwn(last, "__kw")
? args.slice(0, -1) : args;
return null;
});
BASE_EXCEPTION.attrs.set("__str__", (self: PyInstance) => {
const args = self.attrs.args;
return Array.isArray(args) && args.length ? (args.length === 1 ? pyStr(args[0]) : pyStr(args)) : "";
});
for (const method of BASE_EXCEPTION.attrs.values()) method.__method = true;
export const EXCEPTIONS = new Map<string, PyClass>([["BaseException", BASE_EXCEPTION]]);
for (const [name, parent] of [
["Exception", "BaseException"], ["ArithmeticError", "Exception"], ["ZeroDivisionError", "ArithmeticError"],
["OverflowError", "ArithmeticError"], ["AssertionError", "Exception"], ["AttributeError", "Exception"],
["ImportError", "Exception"], ["LookupError", "Exception"], ["IndexError", "LookupError"],
["KeyError", "LookupError"], ["NameError", "Exception"], ["OSError", "Exception"], ["IOError", "OSError"],
["EnvironmentError", "OSError"], ["RuntimeError", "Exception"], ["NotImplementedError", "RuntimeError"],
["RecursionError", "RuntimeError"], ["StopIteration", "Exception"], ["SyntaxError", "Exception"],
["TypeError", "Exception"], ["ValueError", "Exception"], ["UnicodeError", "ValueError"],
] as const) {
EXCEPTIONS.set(name, new PyClass(name, [EXCEPTIONS.get(parent)!]));
}
for (const cls of EXCEPTIONS.values()) classRegistry.set(cls.name, cls);
class PyException extends Error {
constructor(public instance: PyInstance) {
super(`${instance.cls.name}: ${instanceText(instance)}`);
}
}
type FnDef = { name: string; params: any[]; body?: PyStmt[]; expr?: Expr };
type FnCtx = {
vars: Map<string, any>;
@@ -328,6 +361,9 @@ export class Python {
warned = new Set<string>();
fn: FnCtx | null = null;
depth = 0;
/** > 0 while a try block runs: lookups that normally yield None raise Python exceptions. */
strict = 0;
handling: PyInstance[] = [];
constructor(public scope: Scope) {
activePython = this;
@@ -345,6 +381,7 @@ export class Python {
for (let i = this.locals.length - 1; i >= 0; i--)
if (this.locals[i].has(name)) return this.locals[i].get(name);
if (this.scope.has(name)) return this.scope.get(name);
if (this.strict) this.raise("NameError", `имя ${name} не определено`);
this.warnOnce(`неизвестное имя ${name}`);
return null;
}
@@ -368,6 +405,7 @@ export class Python {
}
if (!safeProperty(e.a) || typeof o === "function") return null;
if (o === null || o === undefined) {
if (this.strict) this.raise("AttributeError", `у None нет атрибута ${e.a}`);
this.warnOnce(`атрибут ${e.a} у None`);
return null;
}
@@ -379,8 +417,15 @@ export class Python {
case "sub": {
const o = this.eval(e.o);
const i = this.eval(e.i);
if (o instanceof PyDict) return o.has(i) ? o.get(i) : null;
if (o instanceof PyDict) {
if (this.strict && !o.has(i)) this.raise("KeyError", pyStr(i));
return o.has(i) ? o.get(i) : null;
}
if (!safeProperty(i) || typeof o === "function") return null;
if (this.strict && (Array.isArray(o) || typeof o === "string")) {
const at = index(o.length, i);
if (at < 0 || at >= o.length) this.raise("IndexError", "индекс вне диапазона");
}
if (Array.isArray(o) || typeof o === "string") return o[index(o.length, i)] ?? null;
return o?.[i] ?? null;
}
@@ -390,8 +435,13 @@ export class Python {
const hi = e.hi ? this.eval(e.hi) : undefined;
return o.slice(lo, hi);
}
case "bin":
return binop(e.op, this.eval(e.l), this.eval(e.r));
case "bin": {
const left = this.eval(e.l);
const right = this.eval(e.r);
if (this.strict && right === 0 && (e.op === "/" || e.op === "//" || e.op === "%"))
this.raise("ZeroDivisionError", "деление на ноль");
return binop(e.op, left, right);
}
case "bool": {
let v: any = null;
for (const x of e.v) {
@@ -426,18 +476,30 @@ export class Python {
case "fmt":
return e.v.map((p: any) => (typeof p === "string" ? p : pyStr(this.eval(p)))).join("");
case "comp": {
const gens = e.gens ?? [{ t: e.t, it: e.it, if: e.if }];
const isDict = e.v !== undefined && e.v !== null;
const out: any[] = [];
const dict = new PyDict();
const frame = new Map<string, any>();
this.locals.push(frame);
try {
for (const item of iterate(this.eval(e.it))) {
this.bind(e.t, item, frame);
if (e.if.every((c: Expr) => truthy(this.eval(c)))) out.push(this.eval(e.e));
const run = (level: number) => {
if (level === gens.length) {
if (isDict) dict.set(this.eval(e.e), this.eval(e.v));
else out.push(this.eval(e.e));
return;
}
const gen = gens[level];
for (const item of [...iterate(this.eval(gen.it))]) {
this.bind(gen.t, item, frame);
if (gen.if.every((c: Expr) => truthy(this.eval(c)))) run(level + 1);
}
};
try {
run(0);
} finally {
this.locals.pop();
}
return out;
return isDict ? dict : out;
}
case "lambda": {
const closure = this.fn?.isClassBody ? this.locals.slice(0, this.fn.index) : this.locals.slice();
@@ -530,17 +592,38 @@ export class Python {
case "if":
this.exec(truthy(this.eval(s.c)) ? s.then : s.else);
break;
case "while":
case "while": {
let broke = false;
while (truthy(this.eval(s.c))) {
if (++guard > 100000) throw new Error("бесконечный цикл в python");
if (this.loopBody(s.body)) break;
if (this.loopBody(s.body)) {
broke = true;
break;
}
}
if (!broke && s.else?.length) this.exec(s.else);
break;
case "for":
}
case "for": {
let broke = false;
for (const item of [...iterate(this.eval(s.it))]) {
this.bind(s.t, item);
if (this.loopBody(s.body)) break;
if (this.loopBody(s.body)) {
broke = true;
break;
}
}
if (!broke && s.else?.length) this.exec(s.else);
break;
}
case "try":
this.execTry(s);
break;
case "raise":
this.execRaise(s);
break;
case "assert":
if (!truthy(this.eval(s.c))) this.raise("AssertionError", s.m ? pyStr(this.eval(s.m)) : "");
break;
case "del":
if (s.t.k === "name") {
@@ -577,6 +660,69 @@ export class Python {
}
}
// --- exceptions ---------------------------------------------------------------------
/** Throw a builtin Python exception, e.g. ``raise("KeyError", "x")``. */
raise(name: string, message: string): never {
const cls = EXCEPTIONS.get(name) ?? EXCEPTIONS.get("Exception")!;
throw new PyException(this.instantiate(cls, message === "" ? [] : [message]));
}
private execRaise(s: PyStmt) {
if (!s.v) {
const current = this.handling[this.handling.length - 1];
if (!current) this.raise("RuntimeError", "нет исключения для повторного вызова");
throw new PyException(current);
}
const v = this.eval(s.v);
if (v instanceof PyInstance && v.cls.mro().includes(BASE_EXCEPTION)) throw new PyException(v);
if (v instanceof PyClass && v.mro().includes(BASE_EXCEPTION)) throw new PyException(this.instantiate(v, []));
this.raise("TypeError", "можно вызвать только исключение");
}
/** Python exception for anything thrown while running a try body, or null for control flow. */
private caught(err: unknown): PyInstance | null {
if (err instanceof PyException) return err.instance;
if (err instanceof BreakSignal || err instanceof ContinueSignal || err instanceof ReturnSignal
|| err instanceof JumpSignal) return null;
if (err instanceof TypeError) return this.instantiate(EXCEPTIONS.get("TypeError")!, [err.message]);
if (err instanceof Error) return this.instantiate(EXCEPTIONS.get("RuntimeError")!, [err.message]);
return null;
}
private execTry(s: PyStmt) {
try {
let handled = false;
this.strict++;
try {
this.exec(s.body);
} catch (err) {
this.strict--;
const exception = this.caught(err);
const handler = exception && s.handlers.find((h: any) => {
if (h.types === null) return true;
const kinds = this.eval(h.types);
return (Array.isArray(kinds) ? kinds : [kinds]).some((k: any) =>
k instanceof PyClass && exception.cls.mro().includes(k));
});
if (!exception || !handler) throw err;
handled = true;
if (handler.name) this.bindName(handler.name, exception);
this.handling.push(exception);
try {
this.exec(handler.body);
} finally {
this.handling.pop();
}
return;
}
this.strict--;
if (!handled && s.else?.length) this.exec(s.else);
} finally {
if (s.final?.length) this.exec(s.final);
}
}
// --- functions and classes ---------------------------------------------------------
/** Assign a name in the scope the running code sees: function local, global or enclosing. */
@@ -755,7 +901,7 @@ export class Python {
if (value.kind === "static") return value.fn;
return (...a: any[]) => value.fn(cls, ...a);
}
if (typeof value === "function" && value.__def) return (...a: any[]) => value(self, ...a);
if (typeof value === "function" && (value.__def || value.__method)) return (...a: any[]) => value(self, ...a);
return value;
}
@@ -828,6 +974,25 @@ export function userBuiltins(py: Python): Record<string, any> {
};
const less = (a: any, b: any) => (a < b ? -1 : a > b ? 1 : 0);
return {
...Object.fromEntries(EXCEPTIONS),
int: (x: any = 0, base?: number) => {
if (typeof x === "string") {
const text = x.trim();
const ok = base ? new RegExp(`^[+-]?[0-9a-z]+$`, "i").test(text) : /^[+-]?\d+$/.test(text);
const n = ok ? parseInt(text, base ?? 10) : NaN;
if (Number.isNaN(n)) py.raise("ValueError", `недопустимое значение для int(): '${x}'`);
return n;
}
const n = Math.trunc(Number(x));
if (!Number.isFinite(n)) py.raise("ValueError", "недопустимое значение для int()");
return n;
},
float: (x: any = 0) => {
const n = typeof x === "string" ? Number(x.trim()) : Number(x);
if (Number.isNaN(n) || (typeof x === "string" && x.trim() === ""))
py.raise("ValueError", `недопустимое значение для float(): '${x}'`);
return n;
},
object: OBJECT,
python_object: OBJECT,
NoRollback: OBJECT,