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
test(sdk): binding-surface handshake pins parameter counts - RC1 function surface closes by handshake, not generation
yhhc6194ae88865
diff --git a/docs/REARCHITECTURE.md b/docs/REARCHITECTURE.mdindex b43149cda..facd77120 100644--- a/docs/REARCHITECTURE.md+++ b/docs/REARCHITECTURE.md@@ -121,7 +121,7 @@- **EHT 路径健壮性**:修复了 `--ts-output sdk/src` 会静默跳过 `component.generated.ts` / ptrLayouts / ptrAccessors 的潜在 bug(之前它们只在非默认 `--ts-output sdk` 下才重新生成)。现在标准构建会让全部生成的 TS 保持同步。- **边界测试可在仓库内运行**:`sdk/tests/helpers/loadWasm.ts` 成为 WASM 路径单一来源(`$ESENGINE_WASM_DIR` → `build/wasm/web` → 旧 `desktop/public/wasm`),8 个集成测试文件不再各自硬编码不存在的 `desktop/public/wasm`。- 验证:SDK typecheck 通过;2012 个测试通过(含 3 个新握手测试,证明 mismatch 在非 strict 下也致命);EHT 幂等。**待补**:C++ 侧 `static_assert` + `getAbiLayoutHash` 的实际编译验证需要 emsdk(随 CI web 构建门禁一起闭环)。-- **函数绑定面握手(2026-07-08)**:病灶所述"`ESEngineModule` 接口是手工镜像、与 `bindings/*.cpp` 的真实导出无任何交叉校验"的收口第一步——新增 `sdk/tests/binding-surface.test.ts`(`cpp-contract.test.ts` 同款测试期握手,随 SDK vitest 进 push 门禁):解析 `WebSDKEntry.cpp`/`TilemapBindings.cpp` 的全部 `emscripten::function` 注册与 `wasm.ts` `ESEngineModule` / `tilemapAPI.ts` `TilemapModule` 声明面,**双向存在性断言**(幽灵声明与未镜像绑定都 RED),另对 embind class 面(`ResourceManager`/`EstellaContext`)逐方法双向对齐。首跑即抓到 16 处存量漂移并已全部对齐:幽灵 `getSpineBounds`+`SpineBounds`(spine 迁侧模块后 C++ 函数仍在但从未注册,TS 声明悬空)、未镜像的 `renderer_setDeltaTime` 与 12 个 `tiled_getObject*`、`CppResourceManager` 缺 3 个 refcount getter。**后续(Phase 1)**:EHT 从注册点生成 TS 接口(删手工镜像本体);顺带清点 C++ 侧已不再注册的死绑定函数(如 `renderer_setDeltaTime` 零消费者、`RendererBindings.hpp` 的旧 spine_* 家族)。+- **函数绑定面握手(2026-07-08)**:病灶所述"`ESEngineModule` 接口是手工镜像、与 `bindings/*.cpp` 的真实导出无任何交叉校验"的收口第一步——新增 `sdk/tests/binding-surface.test.ts`(`cpp-contract.test.ts` 同款测试期握手,随 SDK vitest 进 push 门禁):解析 `WebSDKEntry.cpp`/`TilemapBindings.cpp` 的全部 `emscripten::function` 注册与 `wasm.ts` `ESEngineModule` / `tilemapAPI.ts` `TilemapModule` 声明面,**双向存在性断言**(幽灵声明与未镜像绑定都 RED),另对 embind class 面(`ResourceManager`/`EstellaContext`)逐方法双向对齐。首跑即抓到 16 处存量漂移并已全部对齐:幽灵 `getSpineBounds`+`SpineBounds`(spine 迁侧模块后 C++ 函数仍在但从未注册,TS 声明悬空)、未镜像的 `renderer_setDeltaTime` 与 12 个 `tiled_getObject*`、`CppResourceManager` 缺 3 个 refcount getter。同日三个后续切片全部落地:① **侧模块入守卫**(`346065a9`)——physics(4 文件 96 个 `EMSCRIPTEN_KEEPALIVE` C 导出 vs `PhysicsWasmModule`)、spine(原始 `_spine_*` 成员 ∪ `cw('name',…)` cwrap 表 vs 40 个 KEEPALIVE,抓到未镜像的 `spine_setClippingEnabled`)、basis(TS vs CMake `EXPORTED_FUNCTIONS`,链接期已对 C++ 校验,补上 TS↔CMake 这条边);② **死绑定退役**(`bc4bc423`,wasm 重建 + sprite 像素 verify PASS)——`renderer_setDeltaTime` 整条通道(注册/定义/`EngineState.delta_time` 字段写后无人读/TS 声明)与 `RendererBindings.hpp` 的旧 spine_* 声明家族(`SpineBounds`+9 个无定义无调用者的裸声明)删除;③ **签名元数握手**——逐函数钉参数个数(TS 类型运行时擦除,元数漂移的声明会让所有调用点编译通过、只在路径被执行时爆炸;现在测试期 RED),覆盖主模块注册(含 lambda/`select_overload`)、`ResourceManager` class 面(embind 丢实例参,TS 元数 = C++ 元数−1)、physics/spine(raw + cwrap argTypes 长度)/basis,另有解析器自检用例防"空转假绿"。**拍板:本轨道以握手收口,不做 EHT 生成**——存在性 + 元数已双向钉死、embind/cwrap 在调用期校验值类别,生成反而把手写接口的富类型(结构化返回值、JSDoc)退化为贫类型(与"不生成 defineBuiltin"同构决策);已知接受的残余 = TS 形参名与 C++ 不一致这类无自动化可查的语义漂移。**至此根因 1-5 的全部病灶字面收口。**### RC4 身份 — ✅ 已落地并**编译+运行验证**- `core/Types.hpp`:单一全局 `getTypeId<T>()` 计数器拆为**按域独立**的计数器。新增域标签 `ComponentDomain/EventDomain/ServiceDomain/ResourceDomain` 与具名 helper `componentTypeId/eventTypeId/serviceTypeId/resourceTypeId`(各自 0 起、密集)。移除共享的 `getTypeId`/`nextTypeId`。diff --git a/sdk/tests/binding-surface.test.ts b/sdk/tests/binding-surface.test.tsindex c7b219764..b6a68ab37 100644--- a/sdk/tests/binding-surface.test.ts+++ b/sdk/tests/binding-surface.test.ts@@ -65,36 +65,100 @@ function parseFunctionRegistrations(cppSource: string): Set<string> {}/**- * Method names of one `emscripten::class_<T>("Name")` registration chain:- * every `.function("name", ...)` between the class_ head and the chain's- * terminating `;` (the chain itself contains no semicolons).+ * Method registrations of one `emscripten::class_<T>("Name")` chain: every+ * `.function("name", &target)` between the class_ head and the chain's+ * terminating `;` (the chain itself contains no semicolons), mapped to the+ * target's last identifier.*/-function parseClassRegistration(cppSource: string, className: string): Set<string> {+function parseClassRegistration(cppSource: string, className: string): Map<string, string> {const src = stripComments(cppSource);const head = src.indexOf(`("${className}")`);if (head < 0) throw new Error(`embind class_ registration '${className}' not found`);const end = src.indexOf(';', head);const chain = src.slice(head, end);- const out = new Set<string>();- const re = /\.function\(\s*"(\w+)"/g;- for (let m = re.exec(chain); m; m = re.exec(chain)) out.add(m[1]);+ const out = new Map<string, string>();+ const re = /\.function\(\s*"(\w+)"\s*,\s*[^&]*&([\w:]+)/g;+ for (let m = re.exec(chain); m; m = re.exec(chain)) {+ const parts = m[2].split('::');+ out.set(m[1], parts[parts.length - 1]);+ }return out;}/**- * All `EMSCRIPTEN_KEEPALIVE` C-export names in a file: the identifier right- * before the parameter list that follows each annotation.+ * All `EMSCRIPTEN_KEEPALIVE` C exports in a file: the identifier right before+ * the parameter list that follows each annotation, with parameter count.*/-function parseKeepaliveExports(cppSource: string): Set<string> {+function parseKeepaliveSigs(cppSource: string): Map<string, number> {const src = stripComments(cppSource);- const out = new Set<string>();+ const out = new Map<string, number>();const re = /EMSCRIPTEN_KEEPALIVE\b/g;for (let m = re.exec(src); m; m = re.exec(src)) {const paren = src.indexOf('(', m.index);if (paren < 0) continue;const tokens = src.slice(m.index + m[0].length, paren).match(/\w+/g);if (!tokens?.length) throw new Error(`EMSCRIPTEN_KEEPALIVE with no function name at offset ${m.index}`);- out.add(tokens[tokens.length - 1]);+ out.set(tokens[tokens.length - 1], countParams(src, paren));+ }+ return out;+}++function parseKeepaliveExports(cppSource: string): Set<string> {+ return new Set(parseKeepaliveSigs(cppSource).keys());+}++/** Count the top-level parameters of a parenthesized list starting at `open`. */+function countParams(src: string, open: number): number {+ let depth = 0;+ let commas = 0;+ let sawToken = false;+ for (let i = open; i < src.length; i++) {+ const ch = src[i];+ if (ch === '(' || ch === '{' || ch === '[') depth++;+ else if (ch === ')' || ch === '}' || ch === ']') {+ depth--;+ if (depth === 0) return sawToken ? commas + 1 : 0;+ } else if (ch === ',' && depth === 1) commas++;+ else if (depth === 1 && /\S/.test(ch)) sawToken = true;+ }+ throw new Error(`unbalanced parameter list at offset ${open}`);+}++/**+ * Every plausible arity of `symbol` in the pooled C++ sources: each+ * `symbol(...)` occurrence (declaration, definition, or call — argument+ * counts equal parameter counts, these bindings have no default arguments)+ * contributes its top-level comma count.+ */+function cppArities(pooled: string, symbol: string): Set<number> {+ const out = new Set<number>();+ const re = new RegExp(`\\b${symbol}\\s*\\(`, 'g');+ for (let m = re.exec(pooled); m; m = re.exec(pooled)) {+ out.add(countParams(pooled, m.index + m[0].length - 1));+ }+ return out;+}++interface Registration {+ name: string;+ /** last identifier of the bound `&esengine::...` target; null for lambdas */+ symbol: string | null;+ /** lambda registrations carry their arity directly */+ lambdaArity: number | null;+}++/** `emscripten::function("name", &esengine::sym | +[](...){...})` entries. */+function parseRegistrationTargets(cppSource: string): Registration[] {+ const src = stripComments(cppSource);+ const out: Registration[] = [];+ const re = /emscripten::function\(\s*"(\w+)"\s*,\s*(&[\w:]+|\+?\[\]\s*\()/g;+ for (let m = re.exec(src); m; m = re.exec(src)) {+ if (m[2].startsWith('&')) {+ const parts = m[2].slice(1).split('::');+ out.push({ name: m[1], symbol: parts[parts.length - 1], lambdaArity: null });+ } else {+ out.push({ name: m[1], symbol: null, lambdaArity: countParams(src, m.index + m[0].length - 1) });+ }}return out;}@@ -117,40 +181,65 @@ function parseExportedFunctions(cmakeSource: string, marker: string): Set<string// =============================================================================/**- * Call-signature member names (`name(...)` / `name?(...)`) declared at the top- * level of `interface <name> { ... }`. Property members (`HEAPU8: ...`,- * `Registry: new () => ...`) and members of nested object types (`GL: {...}`,- * inline return-type literals) are excluded by tracking brace depth.+ * Call-signature members (`name(...)` / `name?(...)`) declared at the top+ * level of `interface <name> { ... }`, with their parameter counts. Property+ * members (`HEAPU8: ...`, `Registry: new () => ...`) and members of nested+ * object types (`GL: {...}`, inline return-type literals) are excluded: a+ * member must sit at brace depth 0 of the body and start after `;`/`{`/`}`.*/-function parseInterfaceMethods(tsSource: string, interfaceName: string): Set<string> {+function parseInterfaceMethodSigs(tsSource: string, interfaceName: string): Map<string, number> {const src = stripComments(tsSource);const head = new RegExp(`interface\\s+${interfaceName}\\s*\\{`).exec(src);if (!head) throw new Error(`TS interface '${interfaceName}' not found`);- const out = new Set<string>();+ const start = head.index + head[0].length;let depth = 1;- const body = src.slice(head.index + head[0].length);- for (const line of body.split('\n')) {- if (depth === 1) {- const m = /^\s*(\w+)\s*\??\(/.exec(line);- if (m) out.add(m[1]);- }- for (const ch of line) {- if (ch === '{') depth++;- else if (ch === '}' && --depth === 0) return out;+ let end = -1;+ for (let i = start; i < src.length; i++) {+ const ch = src[i];+ if (ch === '{') depth++;+ else if (ch === '}' && --depth === 0) { end = i; break; }+ }+ if (end < 0) throw new Error(`TS interface '${interfaceName}': unterminated body`);+ const body = src.slice(start, end);+ const out = new Map<string, number>();+ const memberRe = /(\w+)\s*\??\(/g;+ for (let m = memberRe.exec(body); m; m = memberRe.exec(body)) {+ let braces = 0;+ for (let i = 0; i < m.index; i++) {+ if (body[i] === '{') braces++;+ else if (body[i] === '}') braces--;}+ if (braces !== 0) continue;+ let j = m.index - 1;+ while (j >= 0 && /\s/.test(body[j])) j--;+ if (j >= 0 && !';{}'.includes(body[j])) continue;+ out.set(m[1], countParams(body, m.index + m[0].length - 1));}- throw new Error(`TS interface '${interfaceName}': unterminated body`);+ return out;}-/** `cw('name', ...)` / `cwrap('name', ...)` call-site literals in a TS file. */-function parseCwrapNames(tsSource: string): Set<string> {+function parseInterfaceMethods(tsSource: string, interfaceName: string): Set<string> {+ return new Set(parseInterfaceMethodSigs(tsSource, interfaceName).keys());+}++/**+ * `cw('name', ret, [argTypes])` / `cwrap(...)` call-site literals in a TS+ * file, mapped to their argTypes count (the arity the wrapper calls with).+ */+function parseCwrapSigs(tsSource: string): Map<string, number> {const src = stripComments(tsSource);- const out = new Set<string>();- const re = /\bcw(?:rap)?\(\s*['"](\w+)['"]/g;- for (let m = re.exec(src); m; m = re.exec(src)) out.add(m[1]);+ const out = new Map<string, number>();+ const re = /\bcw(?:rap)?\(\s*['"](\w+)['"]\s*,\s*(?:null|'[^']*'|"[^"]*")\s*,\s*\[([^\]]*)\]/g;+ for (let m = re.exec(src); m; m = re.exec(src)) {+ out.set(m[1], m[2].trim() ? m[2].split(',').length : 0);+ }return out;}+function parseCwrapNames(tsSource: string): Set<string> {+ return new Set(parseCwrapSigs(tsSource).keys());+}+const sorted = (s: Iterable<string>): string[] => [...s].sort();const missingFrom = (names: Iterable<string>, universe: Set<string>): string[] =>sorted([...names].filter((n) => !universe.has(n)));@@ -270,13 +359,142 @@ describe('WASM binding surface: embind class methods', () => {it('CppResourceManager mirrors class_<ResourceManager> exactly', () => {const cpp = parseClassRegistration(webSdkEntry, 'ResourceManager');const ts = parseInterfaceMethods(wasmTs, 'CppResourceManager');- expect(sorted(ts)).toEqual(sorted(cpp));+ expect(sorted(ts)).toEqual(sorted(cpp.keys()));});it('CppEngineContext mirrors class_<EstellaContext> exactly (embind-implicit delete aside)', () => {const cpp = parseClassRegistration(webSdkEntry, 'EstellaContext');const ts = parseInterfaceMethods(wasmTs, 'CppEngineContext');ts.delete('delete'); // added by embind on every class instance, never registered- expect(sorted(ts)).toEqual(sorted(cpp));+ expect(sorted(ts)).toEqual(sorted(cpp.keys()));+ });+});++// =============================================================================+// Signature arity handshake+// =============================================================================+// Existence drift is pinned above; this pins the parameter COUNT of every+// mirrored function. TS types are erased at runtime, so an arity-drifted+// declaration compiles every SDK call site happily and only explodes when the+// path is exercised — this catches it at test time instead. Types stay+// hand-written (the TS mirror is deliberately richer than what generation+// from C++ could produce); embind/cwrap check value kinds at call time.++const pooledModuleCpp = [+ 'bindings/WebSDKEntry.cpp',+ 'bindings/TilemapBindings.cpp',+ 'bindings/RendererBindings.hpp',+ 'bindings/RendererBindings.cpp',+ 'bindings/ResourceManagerBindings.hpp',+ 'bindings/ResourceManagerBindings.cpp',+ 'bindings/GeometryBindings.hpp',+ 'bindings/GeometryBindings.cpp',+ 'bindings/ImmediateDrawBindings.hpp',+ 'bindings/ImmediateDrawBindings.cpp',+ 'bindings/PostProcessBindings.hpp',+ 'bindings/PostProcessBindings.cpp',+].map((f) => stripComments(read(resolve(CPP, f)))).join('\n');++function expectArities(label: string, tsSigs: Map<string, number>, cppSigs: Map<string, number>): void {+ const problems: string[] = [];+ for (const [name, tsArity] of tsSigs) {+ if (SIDE_RUNTIME.has(name)) continue;+ const cppArity = cppSigs.get(name.replace(/^_/, ''));+ if (cppArity == null) continue; // existence guard covers missing exports+ if (cppArity !== tsArity) problems.push(`${name}: TS declares ${tsArity} params, C++ has ${cppArity}`);+ }+ expect(problems, `${label}:\n${problems.join('\n')}`).toEqual([]);+}++describe('WASM binding surface: signature arity handshake', () => {+ it('parser self-check: known signatures parse to their real arities', () => {+ // Guards the guard: if a parser regresses into returning empty/zero+ // sets, every comparison above it would pass vacuously.+ expect(parseInterfaceMethodSigs(wasmTs, 'ESEngineModule').get('draw_line')).toBe(9);+ expect(parseInterfaceMethodSigs(wasmTs, 'ESEngineModule').get('renderer_end')).toBe(0);+ expect(cppArities(pooledModuleCpp, 'draw_line')).toContain(9);+ expect(parseKeepaliveSigs(read(resolve(CPP, 'bindings/PhysicsModuleEntry.cpp'))).get('physics_step')).toBe(1);+ expect(parseCwrapSigs(read(resolve(SDK, 'spine/SpineModuleLoader.ts'))).get('spine_setSkin')).toBe(2);+ });++ it('every hand-registered module function has a matching TS parameter count', () => {+ const regs = [+ ...parseRegistrationTargets(webSdkEntry),+ ...parseRegistrationTargets(tilemapBindings),+ ];+ const declarations = [+ ['wasm.ts', parseInterfaceMethodSigs(wasmTs, 'ESEngineModule')],+ ['tilemapAPI.ts', parseInterfaceMethodSigs(tilemapApiTs, 'TilemapModule')],+ ] as const;+ const problems: string[] = [];+ for (const reg of regs) {+ const candidates = reg.lambdaArity != null+ ? new Set([reg.lambdaArity])+ : cppArities(pooledModuleCpp, reg.symbol!);+ if (candidates.size === 0) {+ problems.push(`${reg.name}: no C++ prototype found for '${reg.symbol}' — extend the source pool`);+ continue;+ }+ for (const [file, sigs] of declarations) {+ const tsArity = sigs.get(reg.name);+ if (tsArity == null) continue; // existence guard covers+ if (!candidates.has(tsArity)) {+ problems.push(`${reg.name} (${file}): TS declares ${tsArity} params, C++ has ${sorted(+ [...candidates].map(String),+ ).join('/')}`);+ }+ }+ }+ expect(problems, problems.join('\n')).toEqual([]);+ });++ it('CppResourceManager parameter counts match (embind drops the instance param)', () => {+ const chain = parseClassRegistration(webSdkEntry, 'ResourceManager');+ const ts = parseInterfaceMethodSigs(wasmTs, 'CppResourceManager');+ const problems: string[] = [];+ for (const [name, sym] of chain) {+ const tsArity = ts.get(name);+ if (tsArity == null) continue;+ const candidates = cppArities(pooledModuleCpp, sym);+ if (candidates.size === 0) {+ problems.push(`${name}: no C++ prototype found for '${sym}'`);+ } else if (![...candidates].some((c) => c - 1 === tsArity)) {+ problems.push(`${name}: TS declares ${tsArity} params, C++ has ${sorted(+ [...candidates].map((c) => String(c - 1)),+ ).join('/')} after the instance param`);+ }+ }+ expect(problems, problems.join('\n')).toEqual([]);+ });++ it('physics: parameter counts match', () => {+ const cpp = new Map(+ ['PhysicsModuleEntry.cpp', 'PhysicsShapes.cpp', 'PhysicsJoints.cpp', 'PhysicsQueries.cpp']+ .flatMap((f) => [...parseKeepaliveSigs(read(resolve(CPP, 'bindings', f)))]),+ );+ const ts = parseInterfaceMethodSigs(read(resolve(SDK, 'physics/PhysicsModuleLoader.ts')), 'PhysicsWasmModule');+ expectArities('physics', ts, cpp);+ });++ it('spine: raw members and the cwrap table both match', () => {+ const loaderTs = read(resolve(SDK, 'spine/SpineModuleLoader.ts'));+ const cpp = parseKeepaliveSigs(read(resolve(CPP, 'bindings/SpineModuleEntry.cpp')));+ expectArities('spine raw members', parseInterfaceMethodSigs(loaderTs, 'SpineWasmModule'), cpp);+ expectArities('spine cwrap table', parseCwrapSigs(loaderTs), cpp);+ });++ it('basis: parameter counts match', () => {+ const src = stripComments(read(resolve(CPP, 'bindings/BasisModuleEntry.cpp')));+ const ts = parseInterfaceMethodSigs(read(resolve(SDK, 'asset/basisTranscoder.ts')), 'BasisWasmModule');+ const problems: string[] = [];+ for (const [name, tsArity] of ts) {+ if (SIDE_RUNTIME.has(name)) continue;+ const candidates = cppArities(src, name.replace(/^_/, ''));+ if (candidates.size === 0) problems.push(`${name}: no C++ definition found`);+ else if (!candidates.has(tsArity)) {+ problems.push(`${name}: TS declares ${tsArity} params, C++ has ${sorted([...candidates].map(String)).join('/')}`);+ }+ }+ expect(problems, problems.join('\n')).toEqual([]);});});