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
fix(aot): a system belongs to its project, and Math's constants are values
esengine578c7e463da7
diff --git a/compiler/src/eir.ts b/compiler/src/eir.tsindex 5fce76a46..5356964c7 100644--- a/compiler/src/eir.ts+++ b/compiler/src/eir.ts@@ -92,6 +92,15 @@ export type CallTarget =* them without disagreeing with the interpreter. sin/cos/tan/exp/log/pow are* implementation-defined and deliberately absent — see frontend.ts.*/+/**+ * The Math CONSTANTS, which ECMAScript pins to an exact double each — unlike+ * `Math.sin`, whose result it leaves to the implementation. Folded rather than+ * loaded, and safe to fold because the value is the same number everywhere.+ */+export const MATH_CONSTS: readonly string[] = [+ 'E', 'LN10', 'LN2', 'LOG10E', 'LOG2E', 'PI', 'SQRT1_2', 'SQRT2',+];+export const MATH_FNS = {abs: 1, floor: 1, ceil: 1, round: 1, trunc: 1, sqrt: 1, sign: 1,min: 2, max: 2,diff --git a/compiler/src/frontend.ts b/compiler/src/frontend.tsindex 83cd5dae7..0d4f7a0e5 100644--- a/compiler/src/frontend.ts+++ b/compiler/src/frontend.ts@@ -30,7 +30,7 @@ import { resourceMethodBit } from '../../sdk/src/ecs/resourceShapes';import {BOOL, ENTITY, F64, HOST_ENC,type CompShape, type EirModule, type EirSystem, type EirType,- MATH_FNS,+ MATH_CONSTS, MATH_FNS,type FieldSpec, type EirFn, type Expr, type Local, type Place, type QueryArg, type Stmt, type BinOp, type LogicOp,type MathFn,} from './eir';@@ -665,6 +665,11 @@ class SystemLowerer {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;+ // `Math.PI` is a value the spec pins exactly, so it folds like any other+ // literal — the same double on both sides, unlike `Math.sin`.+ if (cur.text === 'Math' && path.length === 1 && MATH_CONSTS.includes(path[0]!)) {+ return { e: 'const', value: (Math as unknown as Record<string, number>)[path[0]!]!, type: F64 };+ }const v = this.constAt(cur.text, path);if (v === null || typeof v === 'object') return null;return typeof v === 'boolean'diff --git a/compiler/tests/coverage.test.ts b/compiler/tests/coverage.test.tsindex a284340cf..c4d5e21a5 100644--- a/compiler/tests/coverage.test.ts+++ b/compiler/tests/coverage.test.ts@@ -50,9 +50,9 @@ import { builtinShapes } from '../src/builtins';const ROOT = resolve(fileURLToPath(new URL('../..', import.meta.url)));/** Per-frame systems only. See the file header before lowering these. */-const FRAME_FLOOR = 12;+const FRAME_FLOOR = 13;/** Per-frame systems the contract could take once the pending work is done. */-const CEILING_FLOOR = 75;+const CEILING_FLOOR = 85;function walk(dir: string, out: string[] = []): string[] {for (const name of readdirSync(dir)) {@@ -80,14 +80,27 @@ function byProject(all: readonly string[]): Map<string, string[]> {}const projects = byProject(files);-const results = [...projects.values()].map((fs) => lowerProgram(fs, builtinShapes()));-const seen = results.flatMap((r) => r.seen);-const diagnostics = results.flatMap((r) => r.diagnostics);-const systemBindings = new Map(results.flatMap((r) => [...r.systemBindings]));-const verifiedNames = new Set(results.flatMap(- (r) => r.module.systems.filter((s) => verifySystem(s, r.module.comps, r.module.fns).length === 0).map((s) => s.name)));-const unverified = results.flatMap((r) => r.module.systems- .map((s) => ({ name: s.name, errors: verifySystem(s, r.module.comps, r.module.fns) }))+const results = [...projects.entries()].map(([project, fs]) => ({+ project, lowered: lowerProgram(fs, builtinShapes()),+}));++/**+ * A system is identified by its PROJECT and its name, never by the name alone.+ * Two projects both call a system `MoveSystem`, and counting by name merges+ * them: one project's compiling would have reported the other's as compiled+ * too. The same shape as the two different `Health` components, one layer up.+ */+const key = (project: string, name: string): string => `${project}::${name}`;++const seen = results.flatMap(({ project, lowered }) => lowered.seen.map((n) => key(project, n)));+const diagnostics = results.flatMap(({ project, lowered }) => lowered.diagnostics.map((d) => ({+ ...d, system: d.system === undefined ? undefined : key(project, d.system),+})));+const verifiedNames = new Set(results.flatMap(({ project, lowered }) => lowered.module.systems+ .filter((s) => verifySystem(s, lowered.module.comps, lowered.module.fns).length === 0)+ .map((s) => key(project, s.name))));+const unverified = results.flatMap(({ project, lowered }) => lowered.module.systems+ .map((s) => ({ name: key(project, s.name), errors: verifySystem(s, lowered.module.comps, lowered.module.fns) })).filter((x) => x.errors.length > 0));const SCHEDULED = /addSystemToSchedule\s*\(\s*Schedule\.\w+\s*,\s*(\w+)\s*\)/g;@@ -100,10 +113,14 @@ const BARE_ADD = /\baddSystem\s*\(\s*(\w+)\s*\)/g;*/function perFrameSystems(): Set<string> {const frame = new Set<string>();- for (const f of files.filter((p) => p.endsWith('main.ts'))) {- const src = readFileSync(f, 'utf8');- for (const re of [SCHEDULED, BARE_ADD]) {- for (const m of src.matchAll(re)) frame.add(systemBindings.get(m[1]!) ?? m[1]!);+ for (const { project, lowered } of results) {+ for (const f of projects.get(project)!.filter((p) => p.endsWith('main.ts'))) {+ const src = readFileSync(f, 'utf8');+ for (const re of [SCHEDULED, BARE_ADD]) {+ for (const m of src.matchAll(re)) {+ frame.add(key(project, lowered.systemBindings.get(m[1]!) ?? m[1]!));+ }+ }}}return frame;@@ -117,6 +134,23 @@ describe('AOT coverage over examples/', () => {expect(seen.length).toBeGreaterThan(20);});+ it('counts a system per project, because two projects share a system name', () => {+ const projectsByName = new Map<string, Set<string>>();+ for (const { project, lowered } of results) {+ for (const n of lowered.seen) {+ if (!projectsByName.has(n)) projectsByName.set(n, new Set());+ projectsByName.get(n)!.add(project);+ }+ }+ const shared = [...projectsByName].filter(([, ps]) => ps.size > 1);+ // Without a duplicate in the corpus the distinction is untested, and+ // counting by name alone would pass while merging two systems into one.+ expect(shared.length).toBeGreaterThan(0);+ for (const [name, ps] of shared) {+ for (const project of ps) expect(seen).toContain(key(project, name));+ }+ });+it('no project declares one component name twice', () => {// Across projects the same name is fine and expected; within one it is a// shape nobody can pin down.@@ -204,7 +238,7 @@ describe('AOT coverage over examples/', () => {* It is the number that can be 100% and STAY 100%.*/describe('systems the corpus promises to compile', () => {- const promised = results.flatMap((r) => r.required);+ const promised = results.flatMap(({ project, lowered }) => lowered.required.map((n) => key(project, n)));it('finds the marker in the corpus at all', () => {// At zero this whole block asserts nothing, which is the failure a gate@@ -214,7 +248,7 @@ describe('systems the corpus promises to compile', () => {});it('keeps every one of them', () => {- expect(results.flatMap((r) => brokenPromises(r))).toEqual([]);+ expect(results.flatMap(({ lowered }) => brokenPromises(lowered))).toEqual([]);});it('and each also verifies, not merely lowers', () => {diff --git a/compiler/tests/fixtures/in-subset.ts b/compiler/tests/fixtures/in-subset.tsindex 2d5ce9783..a1663abe0 100644--- a/compiler/tests/fixtures/in-subset.ts+++ b/compiler/tests/fixtures/in-subset.ts@@ -59,7 +59,9 @@ 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;+ // `Math.PI` folds like a module constant does, and for the same+ // reason: the spec pins it to one double. `Math.sin` does not.+ const step = drift.rate * time.delta * TUNING.damping * (Math.PI / Math.SQRT2);const nx = transform.position.x + step * (drift.enabled ? TUNING.boost : 1);transform.position.x = nx > WRAP ? nx - WRAP * 2 : nx;if (drift.enabled) {