Extract wrapper binding logic to wrapper-binding.ts

Move instantiateWrapperTypePattern and the WrapperBinding type into a new wrapper-binding.ts module and register it for reuse. Update analyzer.ts and import-resolver.ts to import the function/type from the new module and simplify call-site/type-root collection logic (use entrySourceFile and a cached callable name). Also update README: add ast-helpers.ts and wrapper-binding.ts to the file list and bump test count in the example.
This commit is contained in:
手瓜一十雪 committed 2026-05-25 11:34:37 +08:00
1 parent bed48bbe46
commit 40c51bcd02
4 files changed
+78 -93

No files matched your search

+3 -1
View File
@@ -266,7 +266,7 @@ qualified names (ns.Type), or a missing import.
```bash
pnpm --filter @snowluma/proton build # 打包 src/index.ts → dist/index.js
pnpm --filter @snowluma/proton test # 运行 vitest (95 个测试)
pnpm --filter @snowluma/proton test # 运行 vitest (107 个测试)
pnpm --filter @snowluma/proton typecheck # 运行 tsc --noEmit
```
@@ -281,6 +281,8 @@ src/
monomorphizer.ts 泛型实例化 → 具体 ProtobufMessage
import-resolver.ts 跨文件定义 + 包装器解析
callsite.ts 匹配 protobuf_encode/decode 调用
ast-helpers.ts 共享 AST 小工具 + 快速预检
wrapper-binding.ts 包装器绑定类型 + 类型模板实例化
static-wrapper.ts 静态方法包装器检测 (AST)
utils.ts 名称解析 + 虚拟 SF 追踪
dependency-graph.ts 拓扑排序 + 可达性
+4 -35
View File
@@ -7,57 +7,26 @@ import {
} from './callsite.js';
import { collectConcreteFieldGenericTypeArgs, collectGenericInterface, collectInterface } from './collector.js';
import { buildDependencyRegistry } from './dependency-graph.js';
import type { ImportedDefinitions, WrapperBinding } from './import-resolver.js';
import type { ImportedDefinitions } from './import-resolver.js';
import { monomorphizeTypeNode } from './monomorphizer.js';
import { PRIMITIVE_TYPE_MAP, WireType, type GenericProtobufTemplate, type MessageRegistry, type ProtobufMessage } from './types.js';
import {
createImportedTypeNameResolver,
registerSyntheticTypeSourceFile,
resolveSourceFileForTypeNode,
typeNodeToMangledName,
} from './utils.js';
import { instantiateWrapperTypePattern, type WrapperBinding } from './wrapper-binding.js';
export { typeNodeToMangledName } from './utils.js';
function instantiateWrapperTypePattern(
binding: WrapperBinding,
callerTypeArgs: ts.NodeArray<ts.TypeNode>,
sf: ts.SourceFile,
): ts.TypeNode | null {
if (!binding.typePattern || !binding.typeParamNames?.length) return callerTypeArgs[binding.typeArgIndex] ?? null;
let text = binding.typePattern;
for (let i = 0; i < binding.typeParamNames.length; i++) {
const arg = callerTypeArgs[i];
if (!arg) return null;
text = text.replace(new RegExp(`\\b${binding.typeParamNames[i]}\\b`, 'g'), arg.getText(sf));
}
// Parse the substituted type pattern into a fresh source file whose
// `fileName` is the binding's origin (so subsequent import resolution can
// find the right module) AND whose `text` contains the substituted source
// (so `getText()` on the resulting TypeNode returns the actual type, not
// garbage from an empty-text companion file).
const parsed = ts.createSourceFile(
binding.sourceFilePath ?? sf.fileName,
`type __T = ${text};`,
ts.ScriptTarget.Latest,
true,
);
const stmt = parsed.statements[0];
if (!ts.isTypeAliasDeclaration(stmt)) return null;
registerSyntheticTypeSourceFile(stmt.type, parsed);
return stmt.type;
}
/** A recorded call-site for later replacement. */
export interface CallSiteRecord {
fnName: CanonicalProtobufFn;
exprStart: number; // position of identifier start
typeArgsEnd: number; // position after closing '>'
firstTypeArg: ts.TypeNode; // the type argument node
line: number; // 1-based line for runtime map lookup
column: number; // 1-based column for runtime map lookup
line: number; // 1-based source position for diagnostics
column: number; // 1-based source position for diagnostics
}
export interface ResolvedCallSiteRecord extends CallSiteRecord {
+20 -57
View File
@@ -1,18 +1,13 @@
import { existsSync, readFileSync } from 'fs';
import { dirname, resolve } from 'path';
import ts from 'typescript';
import { collectProtobufImportBindings, matchProtobufCallSite, type CanonicalProtobufFn } from './callsite.js';
import { getCallableName } from './ast-helpers.js';
import { collectProtobufImportBindings, matchProtobufCallSite } from './callsite.js';
import { collectGenericInterface, collectInterface } from './collector.js';
import { PRIMITIVE_TYPE_MAP, type GenericProtobufTemplate, type ProtobufMessage } from './types.js';
import { createImportedTypeNameResolver, isKeywordTypeNode, type ImportedTypeNameResolver } from './utils.js';
export interface WrapperBinding {
fnName: CanonicalProtobufFn;
typeArgIndex: number;
typePattern?: string;
typeParamNames?: string[];
sourceFilePath?: string;
}
import { instantiateWrapperTypePattern, type WrapperBinding } from './wrapper-binding.js';
export type { WrapperBinding } from './wrapper-binding.js';
export interface ParsedFileEntry {
filePath: string;
@@ -36,8 +31,6 @@ interface ImportClause {
specifier: string;
}
import { getCallableName } from './ast-helpers.js';
/** Extract all named imports from the source file (both type and value imports). */
function extractImports(sf: ts.SourceFile): ImportClause[] {
const result: ImportClause[] = [];
@@ -274,26 +267,6 @@ function firstTypeParameterIndex(typeNode: ts.TypeNode, typeParamIndexes: Map<st
return index;
}
function instantiateWrapperTypePattern(
binding: WrapperBinding,
callerTypeArgs: ts.NodeArray<ts.TypeNode>,
sf: ts.SourceFile,
): ts.TypeNode | null {
if (!binding.typePattern || !binding.typeParamNames?.length) return callerTypeArgs[binding.typeArgIndex] ?? null;
let text = binding.typePattern;
for (let i = 0; i < binding.typeParamNames.length; i++) {
const arg = callerTypeArgs[i];
if (!arg) return null;
text = text.replace(new RegExp(`\\b${binding.typeParamNames[i]}\\b`, 'g'), arg.getText(sf));
}
const parsed = ts.createSourceFile('wrapper-type.ts', `type __T = ${text};`, ts.ScriptTarget.Latest, true);
const stmt = parsed.statements[0];
if (!ts.isTypeAliasDeclaration(stmt)) return null;
return stmt.type;
}
function matchForwardedKnownWrapper(
body: ts.ConciseBody | ts.Block | undefined,
typeParams: readonly ts.TypeParameterDeclaration[] | undefined,
@@ -712,39 +685,29 @@ export function resolveImports(
}
}
const rootTypeNodes: RootTypeNode[] = collectCallRootTypeNodes(ts.createSourceFile(entryPath, code, ts.ScriptTarget.Latest, true))
.map(typeNode => ({ typeNode, from: entry }));
const entrySourceFile = ts.createSourceFile(entryPath, code, ts.ScriptTarget.Latest, true);
const rootTypeNodes: RootTypeNode[] = collectCallRootTypeNodes(entrySourceFile)
.map(typeNode => ({ typeNode, from: entry }));
const wrapperBindings = collectWrapperBindings(entry, entrySourceFile);
ts.forEachChild(entrySourceFile, function visit(node) {
if (
ts.isCallExpression(node) &&
node.typeArguments?.length &&
getCallableName(node.expression) &&
(
wrapperBindings.has(getCallableName(node.expression)!) ||
(
ts.isPropertyAccessExpression(node.expression) &&
ts.isIdentifier(node.expression.expression) &&
importedObjectWrapperMembers.get(node.expression.expression.text)?.has(node.expression.name.text)
)
)
) {
const binding = wrapperBindings.get(getCallableName(node.expression)!) ?? (
if (ts.isCallExpression(node) && node.typeArguments?.length) {
const callableName = getCallableName(node.expression);
const binding = callableName ? wrapperBindings.get(callableName) ?? (
ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression)
? importedObjectWrapperMembers.get(node.expression.expression.text)?.get(node.expression.name.text)
: undefined
);
if (!binding) return;
const typeArg = instantiateWrapperTypePattern(binding, node.typeArguments, entrySourceFile);
if (typeArg) rootTypeNodes.push({
typeNode: typeArg,
from: binding.typePattern && binding.sourceFilePath ? getEntry(binding.sourceFilePath) : entry,
});
if (binding.typePattern) {
for (const callerTypeArg of node.typeArguments) {
rootTypeNodes.push({ typeNode: callerTypeArg, from: entry });
) : undefined;
if (binding) {
const typeArg = instantiateWrapperTypePattern(binding, node.typeArguments, entrySourceFile);
if (typeArg) rootTypeNodes.push({
typeNode: typeArg,
from: binding.typePattern && binding.sourceFilePath ? getEntry(binding.sourceFilePath) : entry,
});
if (binding.typePattern) {
for (const callerTypeArg of node.typeArguments) {
rootTypeNodes.push({ typeNode: callerTypeArg, from: entry });
}
}
}
}
@@ -0,0 +1,51 @@
import ts from 'typescript';
import { registerSyntheticTypeSourceFile } from './utils.js';
import type { CanonicalProtobufFn } from './callsite.js';
export interface WrapperBinding {
fnName: CanonicalProtobufFn;
typeArgIndex: number;
typePattern?: string;
typeParamNames?: string[];
sourceFilePath?: string;
}
/** Instantiate the concrete encoded/decoded type behind a wrapper binding.
*
* Wrapper binding discovery records either:
* - a direct forwarded type-argument index (`protobuf_encode<T>`), or
* - a structural type pattern that must be substituted at the call site
* (`encode<T>(x: Wrapper<T>)` → `Wrapper<Concrete>`).
*
* The parsed synthetic type is registered with its synthetic SourceFile so
* downstream `typeNodeToMangledName()` / import resolution can read the
* substituted text from the correct backing file instead of from the caller's
* original source text.
*/
export function instantiateWrapperTypePattern(
binding: WrapperBinding,
callerTypeArgs: ts.NodeArray<ts.TypeNode>,
sf: ts.SourceFile,
): ts.TypeNode | null {
if (!binding.typePattern || !binding.typeParamNames?.length) {
return callerTypeArgs[binding.typeArgIndex] ?? null;
}
let text = binding.typePattern;
for (let i = 0; i < binding.typeParamNames.length; i++) {
const arg = callerTypeArgs[i];
if (!arg) return null;
text = text.replace(new RegExp(`\\b${binding.typeParamNames[i]}\\b`, 'g'), arg.getText(sf));
}
const parsed = ts.createSourceFile(
binding.sourceFilePath ?? sf.fileName,
`type __T = ${text};`,
ts.ScriptTarget.Latest,
true,
);
const stmt = parsed.statements[0];
if (!ts.isTypeAliasDeclaration(stmt)) return null;
registerSyntheticTypeSourceFile(stmt.type, parsed);
return stmt.type;
}