A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(compiler): the subset grows, and a number now says how much
yhh9f91525adf3f
diff --git a/compiler/src/eir.ts b/compiler/src/eir.tsindex afb6614b5..89319d0bd 100644--- a/compiler/src/eir.ts+++ b/compiler/src/eir.ts@@ -51,11 +51,38 @@ export type Place =| { readonly p: 'local'; readonly id: number }| { readonly p: 'field'; readonly base: Place; readonly path: readonly string[] };+export type LogicOp = '&&' | '||';+export type Expr =| { readonly e: 'const'; readonly value: number | boolean; readonly type: EirType }| { readonly e: 'read'; readonly place: Place; readonly type: EirType }| { readonly e: 'bin'; readonly op: BinOp; readonly l: Expr; readonly r: Expr; readonly type: EirType }- | { readonly e: 'neg'; readonly v: Expr; readonly type: EirType };+ | { readonly e: 'neg'; readonly v: Expr; readonly type: EirType }+ | { readonly e: 'not'; readonly v: Expr; readonly type: EirType }+ /** Separate from `bin` because both sides must NOT be evaluated. */+ | { readonly e: 'logic'; readonly op: LogicOp; readonly l: Expr; readonly r: Expr; readonly type: EirType }+ /** `a ? b : c`; like `logic`, only one arm runs. */+ | {+ readonly e: 'select';+ readonly cond: Expr;+ readonly then: Expr;+ readonly otherwise: Expr;+ readonly type: EirType;+ }+ /** An intrinsic call. Only the exactly-specified Math operations (§3.3). */+ | { readonly e: 'call'; readonly fn: MathFn; readonly args: readonly Expr[]; readonly type: EirType };++/**+ * The Math operations ECMAScript specifies EXACTLY, so a backend can compute+ * them without disagreeing with the interpreter. sin/cos/tan/exp/log/pow are+ * implementation-defined and deliberately absent — see frontend.ts.+ */+export const MATH_FNS = {+ abs: 1, floor: 1, ceil: 1, round: 1, trunc: 1, sqrt: 1, sign: 1,+ min: 2, max: 2,+} as const;++export type MathFn = keyof typeof MATH_FNS;export type Stmt =/**@@ -70,7 +97,13 @@ export type Stmt =readonly body: readonly Stmt[];}| { readonly s: 'assign'; readonly target: Place; readonly value: Expr }- | { readonly s: 'let'; readonly id: number; readonly value: Expr };+ | { readonly s: 'let'; readonly id: number; readonly value: Expr }+ | {+ readonly s: 'if';+ readonly cond: Expr;+ readonly then: readonly Stmt[];+ readonly otherwise: readonly Stmt[];+ };/** A local's name and type; the name is for diagnostics and printing only. */export interface Local {@@ -121,8 +154,14 @@ function exprText(e: Expr, locals: ReadonlyMap<number, Local>): string {switch (e.e) {case 'const': return String(e.value);case 'read': return placeName(e.place, locals);- case 'bin': return `(${exprText(e.l, locals)} ${e.op} ${exprText(e.r, locals)})`;+ case 'bin':+ case 'logic': return `(${exprText(e.l, locals)} ${e.op} ${exprText(e.r, locals)})`;case 'neg': return `-${exprText(e.v, locals)}`;+ case 'not': return `!${exprText(e.v, locals)}`;+ case 'select':+ return `(${exprText(e.cond, locals)} ? ${exprText(e.then, locals)} : ${exprText(e.otherwise, locals)})`;+ case 'call':+ return `${e.fn}(${e.args.map((a) => exprText(a, locals)).join(', ')})`;}}@@ -139,6 +178,16 @@ function stmtText(s: Stmt, locals: ReadonlyMap<number, Local>, indent: string):return [`${indent}${placeName(s.target, locals)} = ${exprText(s.value, locals)}`];case 'let':return [`${indent}let ${locals.get(s.id)?.name ?? `%${s.id}`} = ${exprText(s.value, locals)}`];+ case 'if': {+ const out = [`${indent}if ${exprText(s.cond, locals)} {`];+ out.push(...s.then.flatMap((b) => stmtText(b, locals, `${indent} `)));+ if (s.otherwise.length > 0) {+ out.push(`${indent}} else {`);+ out.push(...s.otherwise.flatMap((b) => stmtText(b, locals, `${indent} `)));+ }+ out.push(`${indent}}`);+ return out;+ }}}diff --git a/compiler/src/frontend.ts b/compiler/src/frontend.tsindex d84a26bf9..3fc6726e6 100644--- a/compiler/src/frontend.ts+++ b/compiler/src/frontend.ts@@ -23,7 +23,9 @@ import ts from 'typescript';import {BOOL, ENTITY, F64,type CompShape, type EirModule, type EirSystem, type EirType,- type Expr, type Local, type Place, type QueryArg, type Stmt, type BinOp,+ MATH_FNS,+ type Expr, type Local, type Place, type QueryArg, type Stmt, type BinOp, type LogicOp,+ type MathFn,} from './eir';export interface Diagnostic {@@ -55,6 +57,20 @@ const COMPOUND: ReadonlyMap<ts.SyntaxKind, BinOp> = new Map([[ts.SyntaxKind.AsteriskEqualsToken, '*'], [ts.SyntaxKind.SlashEqualsToken, '/'],] as const);+const LOGIC_OPS: ReadonlyMap<ts.SyntaxKind, LogicOp> = new Map([+ [ts.SyntaxKind.AmpersandAmpersandToken, '&&'],+ [ts.SyntaxKind.BarBarToken, '||'],+] as const);++/**+ * A token's source text WITHOUT touching the node. `getText()` walks parent+ * pointers, which exist only after the program has bound — the same trap that+ * has now caught line numbers, binding resolution and this.+ */+function tokenText(kind: ts.SyntaxKind): string {+ return ts.tokenToString(kind) ?? ts.SyntaxKind[kind];+}+/** Thrown internally to abandon one system; never escapes lowerProgram. */class NotInSubset extends Error {constructor(readonly node: ts.Node, message: string) { super(message); }@@ -63,7 +79,8 @@ class NotInSubset extends Error {class SystemLowerer {private readonly locals: Local[] = [];private next = 0;- private readonly scope = new Map<string, Local>();+ /** A stack, not one map: a `const` in a row loop must not outlive the loop. */+ private readonly scopes: Map<string, Local>[] = [new Map()];constructor(private readonly comps: Map<string, CompShape>,@@ -79,14 +96,21 @@ class SystemLowerer {private define(name: string, type: EirType): Local {const l: Local = { id: this.next++, name, type };this.locals.push(l);- this.scope.set(name, l);+ this.scopes[this.scopes.length - 1]!.set(name, l);return l;}private lookup(node: ts.Node, name: string): Local {- const l = this.scope.get(name);- if (!l) throw new NotInSubset(node, `'${name}' is not a value this system declared`);- return l;+ for (let i = this.scopes.length - 1; i >= 0; i--) {+ const l = this.scopes[i]!.get(name);+ if (l) return l;+ }+ throw new NotInSubset(node, `'${name}' is not a value this system declared`);+ }++ private scoped<T>(fn: () => T): T {+ this.scopes.push(new Map());+ try { return fn(); } finally { this.scopes.pop(); }}/** `[Query(Mut(Transform), Mover), Res(Time)]` -> one param type each. */@@ -147,10 +171,33 @@ class SystemLowerer {private stmt(node: ts.Statement): Stmt[] {if (ts.isForOfStatement(node)) return [this.rowLoop(node)];if (ts.isExpressionStatement(node)) return [this.assignment(node.expression)];- if (ts.isBlock(node)) return node.statements.flatMap((s) => this.stmt(s));+ if (ts.isBlock(node)) return this.scoped(() => node.statements.flatMap((s) => this.stmt(s)));+ if (ts.isVariableStatement(node)) return this.declarations(node);+ if (ts.isIfStatement(node)) return [this.ifStmt(node)];throw new NotInSubset(node, `${ts.SyntaxKind[node.kind]} is not a statement this subset lowers`);}+ /** `const x = expr` — the local takes the initializer's type; there is none to declare. */+ private declarations(node: ts.VariableStatement): Stmt[] {+ return node.declarationList.declarations.map((d) => {+ if (!ts.isIdentifier(d.name)) throw new NotInSubset(d, 'a declaration must bind a plain name');+ if (!d.initializer) throw new NotInSubset(d, 'a local must be initialized where it is declared');+ const value = this.expr(d.initializer);+ if (value.type.k !== 'f64' && value.type.k !== 'bool') {+ throw new NotInSubset(d, `a local cannot hold a ${value.type.k}`);+ }+ return { s: 'let', id: this.define(d.name.text, value.type).id, value } as Stmt;+ });+ }++ private ifStmt(node: ts.IfStatement): Stmt {+ const cond = this.expr(node.expression);+ if (cond.type.k !== 'bool') throw new NotInSubset(node.expression, 'an if condition must be a boolean');+ const then = this.scoped(() => this.stmt(node.thenStatement));+ const otherwise = node.elseStatement ? this.scoped(() => this.stmt(node.elseStatement!)) : [];+ return { s: 'if', cond, then, otherwise };+ }+/** `for (const [e, a, b] of query) { ... }` — the shape a system iterates rows in. */private rowLoop(node: ts.ForOfStatement): Stmt {if (!ts.isIdentifier(node.expression)) {@@ -164,14 +211,22 @@ class SystemLowerer {if (!decl || !decl.name || !ts.isArrayBindingPattern(decl.name)) {throw new NotInSubset(node, 'a row loop must destructure [entity, ...components]');}+ // A destructuring may bind a PREFIX and may elide holes — `[, transform,+ // player]` is what most of the corpus writes. Demanding one name per+ // yielded value refused legal TypeScript for no reason.const elements = decl.name.elements;- if (elements.length !== qt.args.length + 1) {+ if (elements.length > qt.args.length + 1) {throw new NotInSubset(node, `the row binds ${elements.length} names but the query yields ${qt.args.length + 1}`);}let entity: number | null = null;const binds: number[] = [];elements.forEach((el, i) => {+ if (ts.isOmittedExpression(el)) {+ // A hole still occupies its position; the row just does not name it.+ if (i > 0) binds.push(this.define(`_hole${i}`, { k: 'comp', name: qt.args[i - 1]!.comp }).id);+ return;+ }if (!ts.isBindingElement(el) || !ts.isIdentifier(el.name)) {throw new NotInSubset(el, 'a row binding must be a plain name');}@@ -186,10 +241,15 @@ class SystemLowerer {const arg = qt.args[i - 1]!;binds.push(this.define(nm, { k: 'comp', name: arg.comp }).id);});+ // A prefix binding still needs the trailing components bound, because the+ // interpreter and every later pass index binds positionally.+ for (let i = elements.length; i < qt.args.length + 1; i++) {+ binds.push(this.define(`_tail${i}`, { k: 'comp', name: qt.args[i - 1]!.comp }).id);+ }- const body = ts.isBlock(node.statement)+ const body = this.scoped(() => (ts.isBlock(node.statement)? node.statement.statements.flatMap((s) => this.stmt(s))- : this.stmt(node.statement);+ : this.stmt(node.statement)));return { s: 'rowLoop', query: { p: 'local', id: q.id }, entity, binds, body };}@@ -206,7 +266,7 @@ class SystemLowerer {return { s: 'assign', target, value: { e: 'bin', op: compound, l: read, r, type } };}if (node.operatorToken.kind !== ts.SyntaxKind.EqualsToken) {- throw new NotInSubset(node, `'${node.operatorToken.getText()}' is not an assignment this subset lowers`);+ throw new NotInSubset(node, `'${tokenText(node.operatorToken.kind)}' is not an assignment this subset lowers`);}return { s: 'assign', target, value: this.expr(node.right) };}@@ -254,6 +314,34 @@ class SystemLowerer {throw new NotInSubset(node, `'${base.name}' has no fields to read`);}+ /**+ * `Math.abs(x)` and friends. Only the operations ECMAScript specifies to the+ * bit: sin/cos/tan/exp/log/pow are implementation-defined, so a native+ * backend and the interpreter would be free to disagree — and a pixel gate+ * would go red on trig rather than on a bug.+ */+ private mathCall(node: ts.CallExpression): Expr {+ const callee = node.expression;+ if (!ts.isPropertyAccessExpression(callee) || !ts.isIdentifier(callee.expression)+ || callee.expression.text !== 'Math') {+ throw new NotInSubset(node, 'CallExpression is not an expression this subset lowers');+ }+ const fn = callee.name.text as MathFn;+ const arity = (MATH_FNS as Record<string, number | undefined>)[fn];+ if (arity === undefined) {+ throw new NotInSubset(node,+ `Math.${fn} is not exactly specified by ECMAScript, so a compiled build would be free to disagree with the interpreter`);+ }+ if (node.arguments.length !== arity) {+ throw new NotInSubset(node, `Math.${fn} takes ${arity} argument(s), not ${node.arguments.length}`);+ }+ const args = node.arguments.map((a) => this.expr(a));+ for (const a of args) {+ if (a.type.k !== 'f64') throw new NotInSubset(node, `Math.${fn} takes numbers, not a ${a.type.k}`);+ }+ return { e: 'call', fn, args, type: F64 };+ }+private expr(node: ts.Expression): Expr {if (ts.isParenthesizedExpression(node)) return this.expr(node.expression);if (ts.isNumericLiteral(node)) return { e: 'const', value: Number(node.text), type: F64 };@@ -263,15 +351,33 @@ class SystemLowerer {const v = this.expr(node.operand);return { e: 'neg', v, type: v.type };}+ if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.ExclamationToken) {+ return { e: 'not', v: this.expr(node.operand), type: BOOL };+ }if (ts.isBinaryExpression(node)) {+ const logic = LOGIC_OPS.get(node.operatorToken.kind);+ if (logic) {+ return { e: 'logic', op: logic, l: this.expr(node.left), r: this.expr(node.right), type: BOOL };+ }const op = BIN_OPS.get(node.operatorToken.kind);- if (!op) throw new NotInSubset(node, `operator '${node.operatorToken.getText()}' is not in this subset`);+ if (!op) throw new NotInSubset(node, `operator '${tokenText(node.operatorToken.kind)}' is not in this subset`);const l = this.expr(node.left);const r = this.expr(node.right);const type = op === '<' || op === '<=' || op === '>' || op === '>=' || op === '==' || op === '!='? BOOL : F64;return { e: 'bin', op, l, r, type };}+ if (ts.isConditionalExpression(node)) {+ const cond = this.expr(node.condition);+ if (cond.type.k !== 'bool') throw new NotInSubset(node.condition, 'a ternary condition must be a boolean');+ const then = this.expr(node.whenTrue);+ const otherwise = this.expr(node.whenFalse);+ if (then.type.k !== otherwise.type.k) {+ throw new NotInSubset(node, 'the two arms of a ternary must have the same type');+ }+ return { e: 'select', cond, then, otherwise, type: then.type };+ }+ if (ts.isCallExpression(node)) return this.mathCall(node);if (ts.isIdentifier(node) || ts.isPropertyAccessExpression(node)) {return { e: 'read', place: this.place(node), type: this.placeType(node) };}@@ -287,7 +393,13 @@ function componentShape(call: ts.CallExpression): CompShape | null {const fields = new Map<string, EirType>();for (const prop of defaults.properties) {if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) return null;- const init = prop.initializer;+ // `-50` parses as a prefix expression, not a numeric literal. A default+ // of a negative number is ordinary, and refusing it took FixtureClamp+ // out of the corpus for no reason anyone would guess from the message.+ const init = ts.isPrefixUnaryExpression(prop.initializer)+ && prop.initializer.operator === ts.SyntaxKind.MinusToken+ ? prop.initializer.operand+ : prop.initializer;if (ts.isNumericLiteral(init)) fields.set(prop.name.text, F64);else if (init.kind === ts.SyntaxKind.TrueKeyword || init.kind === ts.SyntaxKind.FalseKeyword) {fields.set(prop.name.text, BOOL);diff --git a/compiler/src/interp.ts b/compiler/src/interp.tsindex c5bb17cf7..9f4ea5f8a 100644--- a/compiler/src/interp.ts+++ b/compiler/src/interp.ts@@ -66,6 +66,23 @@ function evalExpr(e: Expr, frame: Frame): number | boolean {case 'const': return e.value;case 'read': return readPlace(e.place, frame) as number | boolean;case 'neg': return -(evalExpr(e.v, frame) as number);+ case 'not': return !(evalExpr(e.v, frame) as boolean);+ case 'select':+ return evalExpr(e.cond, frame) ? evalExpr(e.then, frame) : evalExpr(e.otherwise, frame);+ case 'call': {+ const a = e.args.map((x) => evalExpr(x, frame) as number);+ // The frontend admits only the exactly-specified operations, so+ // deferring to the host's Math is the same answer everywhere.+ const fn = (Math as unknown as Record<string, (...xs: number[]) => number>)[e.fn]!;+ return fn(...a);+ }+ case 'logic': {+ // Short-circuit, which is why this is not a `bin`: `a && b(…)` must+ // not evaluate b when a is false.+ const l = evalExpr(e.l, frame) as boolean;+ if (e.op === '&&') return l ? (evalExpr(e.r, frame) as boolean) : false;+ return l ? true : (evalExpr(e.r, frame) as boolean);+ }case 'bin': {const l = evalExpr(e.l, frame) as number;const r = evalExpr(e.r, frame) as number;@@ -100,6 +117,10 @@ function exec(stmts: readonly Stmt[], frame: Frame, world: EirWorld): void {case 'assign':writePlace(s.target, frame, evalExpr(s.value, frame));break;+ case 'if':+ if (evalExpr(s.cond, frame)) exec(s.then, frame, world);+ else exec(s.otherwise, frame, world);+ break;case 'rowLoop': {const q = readPlace(s.query, frame) as { args: readonly QueryArg[] };for (const entity of matching(world, q.args)) {diff --git a/compiler/src/verify.ts b/compiler/src/verify.tsindex b8061b138..208c1010e 100644--- a/compiler/src/verify.ts+++ b/compiler/src/verify.ts@@ -15,6 +15,7 @@* wrong, not a source file that was outside the subset.*/import {+ MATH_FNS,type CompShape, type EirSystem, type EirType, type Expr, type Local, type Place, type Stmt,typeName,} from './eir';@@ -83,6 +84,37 @@ class Verifier {if (t && t.k !== 'f64') this.fail(`negation of a ${typeName(t)}`);return t;}+ case 'not': {+ const t = this.exprType(e.v);+ if (t && t.k !== 'bool') this.fail(`'!' applied to a ${typeName(t)}`);+ return e.type;+ }+ case 'logic': {+ for (const t of [this.exprType(e.l), this.exprType(e.r)]) {+ if (t && t.k !== 'bool') this.fail(`operator '${e.op}' applied to a ${typeName(t)}`);+ }+ return e.type;+ }+ case 'select': {+ const c = this.exprType(e.cond);+ if (c && c.k !== 'bool') this.fail(`a ternary condition is a ${typeName(c)}`);+ const t = this.exprType(e.then);+ const f = this.exprType(e.otherwise);+ if (t && f && t.k !== f.k) this.fail(`ternary arms are ${typeName(t)} and ${typeName(f)}`);+ return e.type;+ }+ case 'call': {+ const arity = (MATH_FNS as Record<string, number | undefined>)[e.fn];+ if (arity === undefined) this.fail(`'${e.fn}' is not an intrinsic`);+ else if (arity !== e.args.length) {+ this.fail(`${e.fn} called with ${e.args.length} argument(s), not ${arity}`);+ }+ for (const a of e.args) {+ const t = this.exprType(a);+ if (t && t.k !== 'f64') this.fail(`${e.fn} applied to a ${typeName(t)}`);+ }+ return e.type;+ }case 'bin': {const l = this.exprType(e.l);const r = this.exprType(e.r);@@ -112,6 +144,12 @@ class Verifier {}break;}+ case 'if': {+ const c = this.exprType(s.cond);+ if (c && c.k !== 'bool') this.fail(`if condition is a ${typeName(c)}`);+ for (const b of [...s.then, ...s.otherwise]) this.stmt(b);+ break;+ }case 'rowLoop': {const q = this.placeType(s.query);if (!q) break;@@ -148,6 +186,7 @@ class Verifier {for (const s of body) {if (s.s === 'assign' && rootOf(s.target) === id) return true;if (s.s === 'rowLoop' && this.writesTo(s.body, id)) return true;+ if (s.s === 'if' && (this.writesTo(s.then, id) || this.writesTo(s.otherwise, id))) return true;}return false;}diff --git a/compiler/tests/conformance.test.ts b/compiler/tests/conformance.test.tsnew file mode 100644index 000000000..f6b897be0--- /dev/null+++ b/compiler/tests/conformance.test.ts@@ -0,0 +1,198 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file conformance.test.ts+ * @brief Every subset feature run BOTH ways and compared (§8.2).+ *+ * @details move-system.test.ts covers the one shape a shipped system happens to+ * use. This covers what the subset gained after it — locals, if /+ * else-if / else, comparisons, `&&`, `!` — because a feature the+ * frontend lowers but nobody runs both ways is unchecked.+ *+ * The oracle is the fixture itself, imported through the stubbed+ * `esengine` and called with live rows, exactly as move-system does.+ */+import { describe, it, expect } from 'vitest';+import { resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { lowerProgram } from '../src/frontend';+import { verifySystem } from '../src/verify';+import { runSystem, type EirWorld, type Row } from '../src/interp';+import { builtinShapes } from '../src/builtins';+import { printSystem } from '../src/eir';++import { driftSystem, clampSystem } from './fixtures/in-subset';+import type { StubSystem } from './stubs/esengine';++const FIXTURE = resolve(fileURLToPath(new URL('./fixtures/in-subset.ts', import.meta.url)));+const ENTITIES = 48;++function makeWorld(): EirWorld {+ let a = 0x51ed270b >>> 0;+ const rand = (): number => {+ a = (a * 1664525 + 1013904223) >>> 0;+ return (a >>> 8) / 16777216;+ };+ const transforms = new Map<number, Row>();+ const drifts = new Map<number, Row>();+ const entities: number[] = [];+ for (let e = 1; e <= ENTITIES; e++) {+ entities.push(e);+ transforms.set(e, {+ position: { x: (rand() - 0.5) * 260, y: 0, z: 0 },+ rotation: { x: 0, y: 0, z: 0, w: 1 },+ scale: { x: 1, y: 1, z: 1 },+ worldPosition: { x: 0, y: 0, z: 0 },+ worldRotation: { x: 0, y: 0, z: 0, w: 1 },+ worldScale: { x: 1, y: 1, z: 1 },+ });+ // Spread rate across the `> 50` boundary and vary `enabled`, so every+ // branch of the fixture is taken by some entity in every frame.+ drifts.set(e, { rate: rand() * 120, wrap: 100, enabled: e % 4 !== 0 });+ }+ return {+ entities,+ comps: new Map([['Transform', transforms], ['FixtureDrift', drifts]]),+ resources: new Map<string, Row>([['Time', { delta: 1 / 30, elapsed: 0 }]]),+ };+}++function runNative(world: EirWorld): void {+ const sys = driftSystem as unknown as StubSystem;+ const transforms = world.comps.get('Transform')!;+ const drifts = world.comps.get('FixtureDrift')!;+ const query = {+ *[Symbol.iterator]() {+ for (const e of world.entities) {+ if (transforms.has(e) && drifts.has(e)) yield [e, transforms.get(e)!, drifts.get(e)!];+ }+ },+ };+ (sys.fn as unknown as (q: unknown, t: unknown) => void)(query, world.resources.get('Time'));+}++const { module, diagnostics } = lowerProgram([FIXTURE], builtinShapes());+const drift = module.systems.find((s) => s.name === 'FixtureDrift');+const clamp = module.systems.find((s) => s.name === 'FixtureClampSys');++describe('conformance — locals, branches, logic', () => {+ it('compiles', () => {+ expect(diagnostics.filter((d) => d.system === 'FixtureDrift')).toEqual([]);+ expect(drift).toBeDefined();+ expect(verifySystem(drift!, module.comps)).toEqual([]);+ });++ it('reads back with its locals and branches intact', () => {+ expect(printSystem(drift!)).toMatchInlineSnapshot(`+ "system FixtureDrift(query: query<mut Transform, FixtureDrift>, time: res<Time>) {+ rowLoop query -> (_entity, transform, drift) {+ let step = (drift.rate * time.delta)+ let nx = (transform.position.x + step)+ let fast = (drift.rate > 50)+ if (nx > drift.wrap) {+ transform.position.x = (nx - (drift.wrap * 2))+ } else {+ if ((nx < -drift.wrap) && drift.enabled) {+ transform.position.x = (nx + (drift.wrap * 2))+ } else {+ transform.position.x = nx+ }+ }+ if (!fast && drift.enabled) {+ transform.position.y = (transform.position.y + (step * 0.5))+ }+ }+ }"+ `);+ });++ it('agrees with node over 40 frames', () => {+ const byNode = makeWorld();+ const byEir = makeWorld();+ for (let f = 0; f < 40; f++) {+ runNative(byNode);+ runSystem(drift!, byEir);+ }+ expect(byEir.comps.get('Transform')).toEqual(byNode.comps.get('Transform'));+ });++ it('took every branch — an agreement over dead code proves nothing', () => {+ const world = makeWorld();+ const wrapped = new Set<number>();+ const yMoved = new Set<number>();+ for (let f = 0; f < 40; f++) {+ const before = new Map([...world.comps.get('Transform')!].map(+ ([e, r]) => [e, { ...(r['position'] as Record<string, number>) }]));+ runSystem(drift!, world);+ for (const [e, row] of world.comps.get('Transform')!) {+ const p = row['position'] as Record<string, number>;+ const b = before.get(e)!;+ if (Math.abs(p['x']! - b['x']!) > 100) wrapped.add(e);+ if (p['y'] !== b['y']) yMoved.add(e);+ }+ }+ expect(wrapped.size, 'no entity ever hit the wrap branch').toBeGreaterThan(0);+ expect(yMoved.size, 'the !fast && enabled branch never ran').toBeGreaterThan(0);+ // And some entity must have been excluded by `enabled`.+ expect(yMoved.size).toBeLessThan(ENTITIES);+ });+});++describe('conformance — ternaries and exact Math', () => {+ function clampWorld(): EirWorld {+ let a = 0x9e3779b1 >>> 0;+ const rand = (): number => {+ a = (a * 1664525 + 1013904223) >>> 0;+ return (a >>> 8) / 16777216;+ };+ const transforms = new Map<number, Row>();+ const clamps = new Map<number, Row>();+ const entities: number[] = [];+ for (let e = 1; e <= 32; e++) {+ entities.push(e);+ transforms.set(e, { position: { x: (rand() - 0.5) * 160, y: 0, z: 0 } });+ clamps.set(e, { lo: -50, hi: 50, push: 10 + rand() * 60 });+ }+ return {+ entities,+ comps: new Map([['Transform', transforms], ['FixtureClamp', clamps]]),+ resources: new Map<string, Row>([['Time', { delta: 1 / 30 }]]),+ };+ }++ function runClampNative(world: EirWorld): void {+ const sys = clampSystem as unknown as StubSystem;+ const transforms = world.comps.get('Transform')!;+ const clamps = world.comps.get('FixtureClamp')!;+ const query = {+ *[Symbol.iterator]() {+ for (const e of world.entities) yield [e, transforms.get(e)!, clamps.get(e)!];+ },+ };+ (sys.fn as unknown as (q: unknown, t: unknown) => void)(query, world.resources.get('Time'));+ }++ it('compiles and verifies', () => {+ expect(diagnostics.filter((d) => d.system === 'FixtureClampSys').map((d) => d.message)).toEqual([]);+ expect(clamp).toBeDefined();+ expect(verifySystem(clamp!, module.comps)).toEqual([]);+ });++ it('keeps the ternary and the intrinsics in the IR', () => {+ const text = printSystem(clamp!);+ expect(text).toContain('? ');+ expect(text).toContain('min(max(');+ expect(text).toContain('sqrt(abs(');+ });++ it('agrees with node over 40 frames', () => {+ const byNode = clampWorld();+ const byEir = clampWorld();+ for (let f = 0; f < 40; f++) {+ runClampNative(byNode);+ runSystem(clamp!, byEir);+ }+ expect(byEir.comps.get('Transform')).toEqual(byNode.comps.get('Transform'));+ });++});diff --git a/compiler/tests/coverage.test.ts b/compiler/tests/coverage.test.tsnew file mode 100644index 000000000..9231b20f3--- /dev/null+++ b/compiler/tests/coverage.test.ts@@ -0,0 +1,77 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file coverage.test.ts+ * @brief How much of the shipped corpus compiles — a number that may only rise.+ *+ * @details §8.2's coverage gate. Without it the subset can quietly stop growing,+ * or shrink under a refactor, and nothing says so: every other test here+ * passes just as well on a compiler that lowers one system.+ *+ * The floor is committed. Raising it is the point; lowering it needs a+ * reason in the commit message, because it means the corpus lost ground.+ */+import { describe, it, expect } from 'vitest';+import { readdirSync, statSync } from 'node:fs';+import { join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { lowerProgram } from '../src/frontend';+import { verifySystem } from '../src/verify';+import { builtinShapes } from '../src/builtins';++const ROOT = resolve(fileURLToPath(new URL('../..', import.meta.url)));++/**+ * Measured, not aspired to. 3 of 174 is where the subset stands: the remaining+ * blockers are semantic (Commands, GetWorld, EventReader all mutate the world),+ * not syntactic, so the next increment is real work rather than more parsing.+ * Raise this when it grows; see the file header before lowering it.+ */+const FLOOR = 3;++function walk(dir: string, out: string[] = []): string[] {+ for (const name of readdirSync(dir)) {+ const p = join(dir, name);+ if (statSync(p).isDirectory()) walk(p, out);+ else if (p.endsWith('.ts') && !p.endsWith('.d.ts')) out.push(p);+ }+ return out;+}++const files = walk(join(ROOT, 'examples')).filter((f) => f.includes(`${'src'}`));+const { module, diagnostics, seen } = lowerProgram(files, builtinShapes());++describe('AOT coverage over examples/', () => {+ it('found systems to measure', () => {+ expect(files.length).toBeGreaterThan(20);+ expect(seen.length).toBeGreaterThan(20);+ });++ it(`compiles at least ${FLOOR} of the corpus's systems`, () => {+ const verified = module.systems.filter((s) => verifySystem(s, module.comps).length === 0);+ const pct = ((100 * verified.length) / seen.length).toFixed(1);++ // The breakdown is the point of running this: the commonest refusal is+ // the next thing worth lowering.+ const reasons = new Map<string, number>();+ for (const d of diagnostics) {+ const key = d.message.startsWith("'") && d.message.includes('parameter intrinsic')+ ? d.message : d.message.replace(/'[^']*'/g, "'…'");+ reasons.set(key, (reasons.get(key) ?? 0) + 1);+ }+ const top = [...reasons.entries()].sort((a, b) => b[1] - a[1]).slice(0, 8);+ console.log(`\nAOT coverage: ${verified.length}/${seen.length} systems (${pct}%) over ${files.length} files`);+ for (const [why, n] of top) console.log(` ${String(n).padStart(3)}x ${why}`);++ expect(verified.length).toBeGreaterThanOrEqual(FLOOR);+ });++ it('every system that compiles also verifies', () => {+ // A system the frontend accepted but the IR verifier rejects is a+ // frontend bug, not a coverage number — it must never be counted.+ const broken = module.systems+ .map((s) => ({ name: s.name, errors: verifySystem(s, module.comps) }))+ .filter((r) => r.errors.length > 0);+ expect(broken).toEqual([]);+ });+});diff --git a/compiler/tests/fixtures/in-subset.ts b/compiler/tests/fixtures/in-subset.tsnew file mode 100644index 000000000..a410d2163--- /dev/null+++ b/compiler/tests/fixtures/in-subset.ts@@ -0,0 +1,51 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file in-subset.ts+ * @brief A system using everything the subset gained after moveSystem.+ *+ * @details Locals, if / else-if / else, comparisons, && and !. Held against node+ * by conformance.test.ts — a feature the frontend lowers but nobody+ * runs both ways is a feature nobody has checked.+ */+import { defineComponent, defineSystem, Query, Mut, Res, Time, Transform } from 'esengine';++export const Drift = defineComponent('FixtureDrift', { rate: 40, wrap: 100, enabled: true });++export const driftSystem = defineSystem(+ [Query(Mut(Transform), Drift), Res(Time)],+ (query, time) => {+ for (const [_entity, transform, drift] of query) {+ const step = drift.rate * time.delta;+ const nx = transform.position.x + step;+ const fast = drift.rate > 50;+ if (nx > drift.wrap) {+ transform.position.x = nx - drift.wrap * 2;+ } else if (nx < -drift.wrap && drift.enabled) {+ transform.position.x = nx + drift.wrap * 2;+ } else {+ transform.position.x = nx;+ }+ if (!fast && drift.enabled) {+ transform.position.y += step * 0.5;+ }+ }+ },+ { name: 'FixtureDrift' },+);++export const Clamp = defineComponent('FixtureClamp', { lo: -50, hi: 50, push: 30 });++/** Ternaries and the exactly-specified half of Math. */+export const clampSystem = defineSystem(+ [Query(Mut(Transform), Clamp), Res(Time)],+ (query, time) => {+ for (const [, transform, clamp] of query) {+ const dx = clamp.push * time.delta;+ const nx = transform.position.x + (transform.position.x < 0 ? dx : -dx);+ transform.position.x = Math.min(Math.max(nx, clamp.lo), clamp.hi);+ transform.position.y = Math.abs(nx) > 10 ? Math.sqrt(Math.abs(nx)) : 0;+ }+ },+ { name: 'FixtureClampSys' },+);diff --git a/compiler/tests/fixtures/outside-subset.ts b/compiler/tests/fixtures/outside-subset.tsindex 2900a980e..89de05fd2 100644--- a/compiler/tests/fixtures/outside-subset.ts+++ b/compiler/tests/fixtures/outside-subset.ts@@ -11,17 +11,17 @@ import { defineComponent, defineSystem, Query, Mut, Res, Time, Transform } fromexport const Speed = defineComponent('FixtureSpeed', { value: 100 });-/** A branch: no control flow beyond the row loop is lowered yet. */-export const branching = defineSystem(+/** A loop of its own: only the row loop is lowered. */+export const looping = defineSystem([Query(Mut(Transform), Speed)],(query) => {for (const [_e, t, s] of query) {- if (s.value > 0) {- t.position.x += s.value;+ while (t.position.x < s.value) {+ t.position.x += 1;}}},- { name: 'FixtureBranching' },+ { name: 'FixtureLooping' },);/** A field the component does not declare — a typo, caught at compile time. */@@ -35,12 +35,31 @@ export const typoField = defineSystem({ name: 'FixtureTypo' },);+/**+ * A Math operation ECMAScript leaves implementation-defined. Refused on purpose:+ * a native backend and the interpreter would be free to disagree, and a pixel+ * gate would then go red on trig instead of on a bug.+ */+export const trig = defineSystem(+ [Query(Mut(Transform), Speed), Res(Time)],+ (query, time) => {+ for (const [_e, t, s] of query) {+ t.position.x += Math.sin(s.value * time.delta);+ }+ },+ { name: 'FixtureTrig' },+);++function damp(v: number): number {+ return v * 0.5;+}+/** A call: nothing outside the intrinsics is reachable from a compiled system. */export const calling = defineSystem([Query(Mut(Transform), Speed), Res(Time)],(query, time) => {for (const [_e, t, s] of query) {- t.position.x += Math.sin(s.value) * time.delta;+ t.position.x += damp(s.value) * time.delta;}},{ name: 'FixtureCalling' },diff --git a/compiler/tests/subset.test.ts b/compiler/tests/subset.test.tsindex 52aaddf6d..1f40deb24 100644--- a/compiler/tests/subset.test.ts+++ b/compiler/tests/subset.test.ts@@ -26,13 +26,14 @@ const compiled = (system: string) => result.module.systems.some((s) => s.name ==describe('the subset refuses, and says why', () => {it('saw every system in the file, compiled or not', () => {expect(result.seen).toEqual([- 'FixtureBranching', 'FixtureTypo', 'FixtureCalling', 'FixtureWritesReadOnly',+ 'FixtureLooping', 'FixtureTypo', 'FixtureTrig', 'FixtureCalling', 'FixtureWritesReadOnly',]);});it.each([- ['FixtureBranching', /IfStatement is not a statement/],+ ['FixtureLooping', /WhileStatement is not a statement/],['FixtureTypo', /has no field 'valeu'/],+ ['FixtureTrig', /Math\.sin is not exactly specified by ECMAScript/],['FixtureCalling', /CallExpression is not an expression/],])('refuses %s', (name, why) => {const d = diagOf(name);