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 module-level literal is a value, not a load
yhh3fd140c7daa4
diff --git a/compiler/src/frontend.ts b/compiler/src/frontend.tsindex 85241deaf..054c873f9 100644--- a/compiler/src/frontend.ts+++ b/compiler/src/frontend.ts@@ -84,6 +84,35 @@ function tokenText(kind: ts.SyntaxKind): string {*/const COMMAND_RECORDS: Record<string, number | undefined> = { despawn: 1 };+/**+ * A module-level `const` the compiler can read at compile time: a literal, or a+ * record of them. `WORLD_HALF_W` and `FOLLOW.damping` are values, not storage,+ * so a system reading one gets a constant rather than a load.+ */+export type ConstValue = number | boolean | { readonly [k: string]: ConstValue };++/** `const X = 800` / `const F = { damping: 5 }` -> a value, or null if not literal. */+function constValue(node: ts.Expression): ConstValue | null {+ if (ts.isNumericLiteral(node)) return Number(node.text);+ if (node.kind === ts.SyntaxKind.TrueKeyword) return true;+ if (node.kind === ts.SyntaxKind.FalseKeyword) return false;+ if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.MinusToken) {+ const inner = constValue(node.operand);+ return typeof inner === 'number' ? -inner : null;+ }+ if (ts.isObjectLiteralExpression(node)) {+ const out: Record<string, ConstValue> = {};+ for (const prop of node.properties) {+ if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name)) return null;+ const v = constValue(prop.initializer);+ if (v === null) return null;+ out[prop.name.text] = v;+ }+ return out;+ }+ return null;+}+/** Thrown internally to abandon one system; never escapes lowerProgram. */class NotInSubset extends Error {constructor(readonly node: ts.Node, message: string) { super(message); }@@ -100,8 +129,22 @@ class SystemLowerer {/** `const Speed = defineComponent('FixtureSpeed', …)` — a query names the* BINDING, and the shape is filed under the declared name. */private readonly bindings: ReadonlyMap<string, string>,+ /** Module-level literals, folded where they are read. */+ private readonly consts: ReadonlyMap<string, ConstValue>,) {}+ /** The constant a dotted path names, or null when the root is not one. */+ private constAt(root: string, path: readonly string[]): ConstValue | null {+ let cur = this.consts.get(root);+ if (cur === undefined) return null;+ for (const key of path) {+ if (cur === null || typeof cur !== 'object') return null;+ cur = (cur as Record<string, ConstValue>)[key];+ if (cur === undefined) return null;+ }+ return cur;+ }+private compName(binding: string): string {return this.bindings.get(binding) ?? binding;}@@ -319,7 +362,12 @@ class SystemLowerer {/** A place is a local, or a dotted path from one. Nothing else is addressable. */private place(node: ts.Expression): Place {- if (ts.isIdentifier(node)) return { p: 'local', id: this.lookup(node, node.text).id };+ if (ts.isIdentifier(node)) {+ if (this.consts.has(node.text) && !this.scopes.some((sc) => sc.has(node.text))) {+ throw new NotInSubset(node, `'${node.text}' is a constant and cannot be assigned`);+ }+ return { p: 'local', id: this.lookup(node, node.text).id };+ }if (!ts.isPropertyAccessExpression(node)) {throw new NotInSubset(node, 'only a name or a dotted path can be read or assigned here');}@@ -330,6 +378,9 @@ class SystemLowerer {cur = cur.expression;}if (!ts.isIdentifier(cur)) throw new NotInSubset(node, 'a dotted path must start at a declared name');+ if (this.consts.has(cur.text) && !this.scopes.some((sc) => sc.has(cur.text))) {+ throw new NotInSubset(node, `'${cur.text}' is a constant and cannot be assigned`);+ }return { p: 'field', base: { p: 'local', id: this.lookup(cur, cur.text).id }, path };}@@ -388,6 +439,24 @@ class SystemLowerer {return { e: 'call', fn, args, type: F64 };}+ /** A read of a module-level constant becomes the value, not a load. */+ private foldConst(node: ts.Expression): Expr | null {+ const path: string[] = [];+ let cur: ts.Expression = node;+ while (ts.isPropertyAccessExpression(cur)) {+ path.unshift(cur.name.text);+ cur = cur.expression;+ }+ if (!ts.isIdentifier(cur)) return null;+ // A local of the same name shadows the module constant, as it does in TS.+ if (this.scopes.some((sc) => sc.has(cur.text))) return null;+ const v = this.constAt(cur.text, path);+ if (v === null || typeof v === 'object') return null;+ return typeof v === 'boolean'+ ? { e: 'const', value: v, type: BOOL }+ : { e: 'const', value: v, 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 };@@ -425,6 +494,8 @@ class SystemLowerer {}if (ts.isCallExpression(node)) return this.mathCall(node);if (ts.isIdentifier(node) || ts.isPropertyAccessExpression(node)) {+ const folded = this.foldConst(node);+ 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`);@@ -495,6 +566,7 @@ export function lowerProgram(files: readonly string[], builtins: ReadonlyMap<str// things; move.ts happens to use one word for both, which is why this was// missing until a fixture used two.const bindings = new Map<string, string>();+ const consts = new Map<string, ConstValue>();const systems: EirSystem[] = [];const diagnostics: Diagnostic[] = [];const seen: string[] = [];@@ -522,7 +594,16 @@ export function lowerProgram(files: readonly string[], builtins: ReadonlyMap<strts.forEachChild(sf, (c) => go(c, null));};- // Components first: a system in one file names a component declared in another.+ // Constants and components first: a system in one file names both from another.+ for (const sf of sources) {+ walkTop(sf, (node, binding) => {+ // The declaration's own name, not the binding walkTop passes DOWN to+ // an initializer: at the declaration node itself that is still null.+ if (!ts.isVariableDeclaration(node) || !ts.isIdentifier(node.name) || !node.initializer) return;+ const v = constValue(node.initializer);+ if (v !== null) consts.set(node.name.text, v);+ });+ }for (const sf of sources) {walkTop(sf, (node, binding) => {if (!ts.isCallExpression(node) || !ts.isIdentifier(node.expression)) return;@@ -561,7 +642,7 @@ export function lowerProgram(files: readonly string[], builtins: ReadonlyMap<strif (!params || !fn || !ts.isArrowFunction(fn)) {throw new NotInSubset(node, 'defineSystem takes a parameter array and an arrow function');}- systems.push(new SystemLowerer(comps, bindings).lower(name, params, fn));+ systems.push(new SystemLowerer(comps, bindings, consts).lower(name, params, fn));} catch (e) {if (!(e instanceof NotInSubset)) throw e;diagnostics.push({diff --git a/compiler/tests/conformance.test.ts b/compiler/tests/conformance.test.tsindex f6b897be0..e43e06d60 100644--- a/compiler/tests/conformance.test.ts+++ b/compiler/tests/conformance.test.ts@@ -21,7 +21,7 @@ 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 { driftSystem, clampSystem, tunedSystem } from './fixtures/in-subset';import type { StubSystem } from './stubs/esengine';const FIXTURE = resolve(fileURLToPath(new URL('./fixtures/in-subset.ts', import.meta.url)));@@ -74,6 +74,7 @@ function runNative(world: EirWorld): void {const { module, diagnostics } = lowerProgram([FIXTURE], builtinShapes());const drift = module.systems.find((s) => s.name === 'FixtureDrift');const clamp = module.systems.find((s) => s.name === 'FixtureClampSys');+const tuned = module.systems.find((s) => s.name === 'FixtureTuned');describe('conformance — locals, branches, logic', () => {it('compiles', () => {@@ -196,3 +197,51 @@ describe('conformance — ternaries and exact Math', () => {});});++describe('conformance — module constants', () => {+ function runTunedNative(world: EirWorld): void {+ const sys = tunedSystem 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'));+ }++ it('compiles and verifies', () => {+ expect(diagnostics.filter((d) => d.system === 'FixtureTuned').map((d) => d.message)).toEqual([]);+ expect(tuned).toBeDefined();+ expect(verifySystem(tuned!, module.comps)).toEqual([]);+ });++ it('folds the constants rather than loading them', () => {+ const text = printSystem(tuned!);+ // The values, not the names: WRAP is 120 and TUNING.damping is 0.9.+ expect(text).toContain('120');+ expect(text).toContain('0.9');+ expect(text).not.toContain('WRAP)');+ expect(text).not.toContain('TUNING');+ });++ it('lets a local shadow a module constant', () => {+ // Inside the if, WRAP is a local; folding that ignored scope would print+ // the module value 120 in its place.+ expect(printSystem(tuned!)).toContain('let WRAP = drift.rate');+ expect(printSystem(tuned!)).toContain('(WRAP > 100)');+ });++ it('agrees with node over 40 frames', () => {+ const byNode = makeWorld();+ const byEir = makeWorld();+ for (let f = 0; f < 40; f++) {+ runTunedNative(byNode);+ runSystem(tuned!, byEir);+ }+ expect(byEir.comps.get('Transform')).toEqual(byNode.comps.get('Transform'));+ });+});diff --git a/compiler/tests/coverage.test.ts b/compiler/tests/coverage.test.tsindex 31f820035..71f016678 100644--- a/compiler/tests/coverage.test.ts+++ b/compiler/tests/coverage.test.ts@@ -32,7 +32,7 @@ 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. */-const FRAME_FLOOR = 6;+const FRAME_FLOOR = 9;function walk(dir: string, out: string[] = []): string[] {for (const name of readdirSync(dir)) {diff --git a/compiler/tests/fixtures/in-subset.ts b/compiler/tests/fixtures/in-subset.tsindex a410d2163..263250846 100644--- a/compiler/tests/fixtures/in-subset.ts+++ b/compiler/tests/fixtures/in-subset.ts@@ -49,3 +49,26 @@ export const clampSystem = defineSystem(},{ name: 'FixtureClampSys' },);++// Module-level literals: values, not storage. A system reading one gets a+// constant folded in, and a local of the same name must still shadow it.+const WRAP = 120;+const TUNING = { damping: 0.9, boost: 2 };++export const tunedSystem = defineSystem(+ [Query(Mut(Transform), Drift), Res(Time)],+ (query, time) => {+ for (const [, transform, drift] of query) {+ const step = drift.rate * time.delta * TUNING.damping;+ const nx = transform.position.x + step * (drift.enabled ? TUNING.boost : 1);+ transform.position.x = nx > WRAP ? nx - WRAP * 2 : nx;+ if (drift.enabled) {+ // Genuinely shadows the module constant: a read of WRAP in here+ // must be the local, not 120.+ const WRAP = drift.rate;+ transform.position.y = WRAP > 100 ? 1 : 0;+ }+ }+ },+ { name: 'FixtureTuned' },+);diff --git a/compiler/tests/fixtures/outside-subset.ts b/compiler/tests/fixtures/outside-subset.tsindex 89de05fd2..1adf3ff3d 100644--- a/compiler/tests/fixtures/outside-subset.ts+++ b/compiler/tests/fixtures/outside-subset.ts@@ -75,3 +75,17 @@ export const writesReadOnly = defineSystem(},{ name: 'FixtureWritesReadOnly' },);++const LIMIT = 42;++/** Assigning to a module constant: it is a value, not storage. */+export const writesConst = defineSystem(+ [Query(Mut(Transform), Speed)],+ (query) => {+ for (const [_e, t, s] of query) {+ t.position.x = LIMIT + s.value;+ LIMIT.foo = 1;+ }+ },+ { name: 'FixtureWritesConst' },+);diff --git a/compiler/tests/subset.test.ts b/compiler/tests/subset.test.tsindex 1f40deb24..e14b7afda 100644--- a/compiler/tests/subset.test.ts+++ b/compiler/tests/subset.test.ts@@ -26,7 +26,8 @@ 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([- 'FixtureLooping', 'FixtureTypo', 'FixtureTrig', 'FixtureCalling', 'FixtureWritesReadOnly',+ 'FixtureLooping', 'FixtureTypo', 'FixtureTrig', 'FixtureCalling',+ 'FixtureWritesReadOnly', 'FixtureWritesConst',]);});@@ -35,6 +36,7 @@ describe('the subset refuses, and says why', () => {['FixtureTypo', /has no field 'valeu'/],['FixtureTrig', /Math\.sin is not exactly specified by ECMAScript/],['FixtureCalling', /CallExpression is not an expression/],+ ['FixtureWritesConst', /'LIMIT' is a constant and cannot be assigned/],])('refuses %s', (name, why) => {const d = diagOf(name);expect(d, `${name} compiled when it should not have`).toBeDefined();