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): a refusal now says whether it is permanent or pending
yhhdc5fc83715b4
diff --git a/compiler/src/frontend.ts b/compiler/src/frontend.tsindex 033bffd96..340e63482 100644--- a/compiler/src/frontend.ts+++ b/compiler/src/frontend.ts@@ -38,6 +38,7 @@ export interface Diagnostic {readonly file: string;readonly line: number;readonly message: string;+ readonly kind: RefusalKind;/** The system this killed, when the failure happened inside one. */readonly system?: string;}@@ -126,9 +127,20 @@ function annotatedType(node: ts.TypeNode): EirType | null {return null;}+/**+ * `permanent` = the contract has no place for it (REARCH_AOT_ABI.md §4), not a+ * todo. `pending` = the contract admits it, nobody lowered it yet. Default is+ * `pending`; every `permanent` below names what is missing.+ */+export type RefusalKind = 'permanent' | 'pending';+/** Thrown internally to abandon one system; never escapes lowerProgram. */class NotInSubset extends Error {- constructor(readonly node: ts.Node, message: string) { super(message); }+ constructor(+ readonly node: ts.Node,+ message: string,+ readonly kind: RefusalKind = 'pending',+ ) { super(message); }}class SystemLowerer {@@ -206,11 +218,23 @@ class SystemLowerer {return l;}+ /** The local a name binds to, or null — for a caller that wants to ask, not throw. */+ private tryLookup(name: string): Local | null {+ for (let i = this.scopes.length - 1; i >= 0; i--) {+ const l = this.scopes[i]!.get(name);+ if (l) return l;+ }+ return null;+ }+private lookup(node: ts.Node, name: string): Local {for (let i = this.scopes.length - 1; i >= 0; i--) {const l = this.scopes[i]!.get(name);if (l) return l;}+ // Some of these are heap values (an array, a class) and some are not —+ // a numeric enum member is a compile-time constant nobody folds yet. The+ // default stands: claiming it cannot be done needs a reason.throw new NotInSubset(node, `'${name}' is not a value this system declared`);}@@ -238,7 +262,13 @@ class SystemLowerer {if (el.arguments.length !== 0) throw new NotInSubset(el, 'Commands() takes no arguments');return { k: 'channel', name: 'Commands' } as EirType;}- if (kind !== 'Query') throw new NotInSubset(el, `'${kind}' is not a parameter intrinsic`);+ if (kind !== 'Query') {+ // GetWorld hands over the whole World — arbitrary access, the one+ // thing a closed contract cannot have. The rest are parameters+ // nobody has lowered yet.+ throw new NotInSubset(el, `'${kind}' is not a parameter intrinsic`,+ kind === 'GetWorld' ? 'permanent' : 'pending');+ }const args: QueryArg[] = el.arguments.map((a) => this.queryArg(a));return { k: 'query', args } as EirType;});@@ -297,7 +327,9 @@ class SystemLowerer {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}`);+ // A component or query is a reference, and the contract has no+ // reference values — only memory it was handed, and numbers.+ throw new NotInSubset(d, `a local cannot hold a ${value.type.k}`, 'permanent');}return { s: 'let', id: this.define(d.name.text, value.type).id, value } as Stmt;});@@ -494,13 +526,25 @@ class SystemLowerer {}if (!ts.isPropertyAccessExpression(callee) || !ts.isIdentifier(callee.expression)|| callee.expression.text !== 'Math') {- throw new NotInSubset(node, 'CallExpression is not an expression this subset lowers');+ // A method on a RESOURCE is pending: §2.3 says a service should be+ // memory, so `input.isKeyDown('KeyW')` is a bit at a known offset.+ // On anything else it needs an object model, which there is none of.+ const recv = ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression)+ ? this.tryLookup(callee.expression.text)+ : null;+ if (recv && recv.type.k === 'res') {+ throw new NotInSubset(node,+ `${recv.name}.${(callee as ts.PropertyAccessExpression).name.text}(…) is a resource method`+ + ' — the contract wants it read as memory, and nothing lowers it yet');+ }+ throw new NotInSubset(node, 'CallExpression is not an expression this subset lowers', 'permanent');}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`);+ `Math.${fn} is not exactly specified by ECMAScript, so a compiled build would be free to disagree with the interpreter`,+ 'permanent');}if (node.arguments.length !== arity) {throw new NotInSubset(node, `Math.${fn} takes ${arity} argument(s), not ${node.arguments.length}`);@@ -571,7 +615,9 @@ class SystemLowerer {if (folded) return folded;return { e: 'read', place: this.place(node), type: this.placeType(node) };}- throw new NotInSubset(node, `${ts.SyntaxKind[node.kind]} is not an expression this subset lowers`);+ // String, array, object, new, await: each needs a heap, and the contract+ // has no allocation (docs/REARCH_AOT_ABI.md §3).+ throw new NotInSubset(node, `${ts.SyntaxKind[node.kind]} is not an expression this subset lowers`, 'permanent');}}@@ -693,6 +739,7 @@ export function lowerProgram(files: readonly string[], builtins: ReadonlyMap<strif (!shape) {diagnostics.push({file: sf.fileName, line: lineOf(sf, node),+ kind: 'permanent',message: 'defineComponent needs a string literal name and an object literal of literal defaults',});return;@@ -700,7 +747,7 @@ export function lowerProgram(files: readonly string[], builtins: ReadonlyMap<strconst existing = comps.get(shape.name);if (existing && !sameShape(existing, shape)) {diagnostics.push({- file: sf.fileName, line: lineOf(sf, node),+ file: sf.fileName, line: lineOf(sf, node), kind: 'permanent',message: `component '${shape.name}' is already declared with a different shape`+ ` — one program cannot hold two`,});@@ -754,7 +801,7 @@ export function lowerProgram(files: readonly string[], builtins: ReadonlyMap<str} catch (e) {if (!(e instanceof NotInSubset)) throw e;diagnostics.push({- file: sf.fileName, line: lineOf(sf, e.node), message: e.message, system: name,+ file: sf.fileName, line: lineOf(sf, e.node), message: e.message, kind: e.kind, system: name,});}});diff --git a/compiler/tests/coverage.test.ts b/compiler/tests/coverage.test.tsindex f45330d43..8bdb7bbbc 100644--- a/compiler/tests/coverage.test.ts+++ b/compiler/tests/coverage.test.ts@@ -18,8 +18,13 @@* different components both named 'Health' and silently gave one* project the other's shape.*- * The floor is committed. Raising it is the point; lowering it needs a- * reason in the commit message, because the corpus lost ground.+ * It also reports the CEILING: how much of the corpus the contract could+ * ever take, counting a system as reachable when every refusal against+ * it is `pending` rather than `permanent`. That number is what says the+ * remaining work is a finite list rather than an open hunt.+ *+ * The floors are committed. Raising them is the point; lowering one+ * needs a reason in the commit message, because the corpus lost ground.*/import { describe, it, expect } from 'vitest';import { readFileSync, readdirSync, statSync } from 'node:fs';@@ -31,8 +36,10 @@ import { builtinShapes } from '../src/builtins';const ROOT = resolve(fileURLToPath(new URL('../..', import.meta.url)));-/** Per-frame systems only. See the file header before lowering this. */+/** Per-frame systems only. See the file header before lowering these. */const FRAME_FLOOR = 9;+/** Per-frame systems the contract could take once the pending work is done. */+const CEILING_FLOOR = 88;function walk(dir: string, out: string[] = []): string[] {for (const name of readdirSync(dir)) {@@ -110,6 +117,39 @@ describe('AOT coverage over examples/', () => {expect(perFrame.size).toBeLessThan(seen.length);});+ it('reports the contract ceiling, not just today', () => {+ const permanentlyOut = new Set(+ diagnostics.filter((d) => d.kind === 'permanent' && d.system).map((d) => d.system!));+ const reachable = seen.filter((n) => !permanentlyOut.has(n));+ const reachableFrame = reachable.filter((n) => perFrame.has(n));+ const seenFrame = seen.filter((n) => perFrame.has(n));+ const pct = (n: number, d: number) => ((100 * n) / d).toFixed(1);+ console.log([+ '',+ `contract ceiling, per-frame : ${reachableFrame.length}/${seenFrame.length}`+ + ` (${pct(reachableFrame.length, seenFrame.length)}%) <- reachable, pending work only`,+ `permanently out, per-frame : ${seenFrame.length - reachableFrame.length}`+ + ' <- needs something the contract does not have',+ ].join('\n'));+ const why = new Map<string, number>();+ for (const d of diagnostics) {+ if (d.kind !== 'permanent' || !d.system || !perFrame.has(d.system)) continue;+ const key = d.message.replace(/'[^']*'/g, "'…'").slice(0, 64);+ why.set(key, (why.get(key) ?? 0) + 1);+ }+ for (const [k, n] of [...why.entries()].sort((a, b) => b[1] - a[1]).slice(0, 6)) {+ console.log(` ${String(n).padStart(3)}x ${k}`);+ }+ expect(reachableFrame.length).toBeGreaterThanOrEqual(CEILING_FLOOR);+ // A ceiling equal to the corpus would mean nothing was ever classified+ // permanent, which would make the split decorative.+ expect(reachableFrame.length).toBeLessThan(seenFrame.length);+ });++ it('every refusal says whether it is permanent or pending', () => {+ expect(diagnostics.every((d) => d.kind === 'permanent' || d.kind === 'pending')).toBe(true);+ });+it(`compiles at least ${FRAME_FLOOR} of the per-frame systems`, () => {const verified = [...verifiedNames];const verifiedFrame = verified.filter((n) => perFrame.has(n));