This commit is contained in:
手瓜一十雪 committed 2026-10-24 17:28:58 +08:00
1 parent 8e28bca775
commit 1172a6bd3d
100 files changed
+8305 -6025

No files matched your search

-420
View File
@@ -1,420 +0,0 @@
import ts from 'typescript';
import {
WireType,
PRIMITIVE_TYPE_MAP,
type ProtobufMessage,
type MessageRegistry,
type GenericProtobufTemplate,
} from './types.js';
import {
collectInterface,
collectGenericInterface,
collectConcreteFieldGenericTypeArgs,
} from './collector.js';
import { monomorphizeTypeNode } from './monomorphizer.js';
import {
createImportedTypeNameResolver,
getCallableName,
typeNodeToMangledName,
registerSyntheticTypeSourceFile,
resolveSourceFileForTypeNode,
} from './utils.js';
import type { ImportedDefinitions, WrapperBinding } from './import-resolver.js';
import {
collectProtobufImportBindings,
matchProtobufCallSite,
type CanonicalProtobufFn,
} from './callsite.js';
import { buildDependencyRegistry } from './dependency-graph.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
}
export interface ResolvedCallSiteRecord extends CallSiteRecord {
typeName: string;
}
export interface AnalysisResult {
registry: MessageRegistry;
callSites: CallSiteRecord[];
sourceFile: ts.SourceFile;
}
export interface UsedRegistryResult {
registry: MessageRegistry;
roots: Set<string>;
callSites: ResolvedCallSiteRecord[];
}
/**
* Analyze TypeScript source in a **single parse + single walk**.
*
* One walk handles both:
* - Collecting concrete + generic interfaces
* - Recording protobuf_encode/decode call-sites
*
* Then post-processes: monomorphize → resolve wire types → topo sort.
*/
export function analyze(
code: string,
filePath: string,
imported?: ImportedDefinitions,
): AnalysisResult {
const sf = ts.createSourceFile(filePath, code, ts.ScriptTarget.Latest, true);
const concrete: ProtobufMessage[] = [];
const templates = new Map<string, GenericProtobufTemplate>();
const mono = new Map<string, ProtobufMessage>();
const callSites: CallSiteRecord[] = [];
const deferredTypeArgs: ts.TypeNode[] = [];
const importBindings = collectProtobufImportBindings(sf);
const resolveImportedTypeName = createImportedTypeNameResolver(sf);
const wrapperBindings = imported?.wrapperBindings ?? new Map<string, WrapperBinding>();
// Seed with imported definitions
if (imported) {
concrete.push(...imported.concrete);
for (const [k, v] of imported.templates) {
templates.set(k, v);
}
}
// Stack of generic-function type-param scopes. When visiting a
// `protobuf_encode/decode<X>` call whose type arg references one of
// these (e.g. `protobuf_encode<OidbBase<T>>(env)` inside
// `function encodeOidbEnv<T>(...)`), we MUST skip monomorphization —
// the type arg only resolves once the wrapper itself is instantiated
// at a downstream call site, and that case is handled separately by
// the wrapper-binding path in `matchForwardedProtobufFn`. Without
// this skip, the analyzer would happily mint a literal `OidbBase__T`
// registry entry with a `body.typeName = 'T'` field, which the
// wire-type guard then trips on.
const enclosingTypeParamStack: Set<string>[] = [];
function typeArgReferencesEnclosingParam(typeArg: ts.TypeNode): boolean {
if (enclosingTypeParamStack.length === 0) {
return false;
}
let found = false;
function check(n: ts.Node): void {
if (found) {
return;
}
if (ts.isTypeReferenceNode(n) && ts.isIdentifier(n.typeName)) {
const name = n.typeName.text;
for (const scope of enclosingTypeParamStack) {
if (scope.has(name)) {
found = true;
return;
}
}
}
ts.forEachChild(n, check);
}
check(typeArg);
return found;
}
function nodeIntroducesTypeParams(
n: ts.Node,
): readonly ts.TypeParameterDeclaration[] | undefined {
if (ts.isFunctionDeclaration(n)) {
return n.typeParameters;
}
if (ts.isFunctionExpression(n)) {
return n.typeParameters;
}
if (ts.isArrowFunction(n)) {
return n.typeParameters;
}
if (ts.isMethodDeclaration(n)) {
return n.typeParameters;
}
return undefined;
}
// ── single walk ─────────────────────────────────────────────────────
ts.forEachChild(sf, function visit(node) {
const introduced = nodeIntroducesTypeParams(node);
const pushedScope = !!(introduced && introduced.length);
if (pushedScope) {
enclosingTypeParamStack.push(new Set(introduced!.map((p) => p.name.text)));
}
try {
if (ts.isInterfaceDeclaration(node)) {
if (node.typeParameters?.length) {
const tpl = collectGenericInterface(node, sf, resolveImportedTypeName);
if (tpl) {
templates.set(tpl.name, tpl);
}
} else {
const msg = collectInterface(node, sf, resolveImportedTypeName);
if (msg) {
concrete.push(msg);
}
// Queue any generic-instantiated type-args appearing as field types
// (e.g. `wrapped: pb<5, Wrapper<uint_32>>`) for monomorphization.
// The call-site queue only sees the outer concrete type, so without
// this the nested instantiation would never reach the registry.
for (const ta of collectConcreteFieldGenericTypeArgs(
node,
resolveImportedTypeName,
)) {
deferredTypeArgs.push(ta);
}
}
}
if (ts.isCallExpression(node)) {
const cs = matchProtobufCallSite(node, sf, importBindings, {
allowLegacyUnboundCanonical: true,
});
if (cs) {
if (!typeArgReferencesEnclosingParam(cs.firstTypeArg)) {
deferredTypeArgs.push(cs.firstTypeArg);
callSites.push(cs);
}
// else: this call sits inside a generic wrapper definition; the
// wrapper-binding path will materialise concrete codecs at each
// downstream call site instead.
} else if (
node.typeArguments?.length &&
getCallableName(node.expression) &&
wrapperBindings.has(getCallableName(node.expression)!)
) {
const binding = wrapperBindings.get(getCallableName(node.expression)!)!;
const firstTypeArg = instantiateWrapperTypePattern(
binding,
node.typeArguments,
sf,
);
if (!firstTypeArg) {
ts.forEachChild(node, visit);
return;
}
const exprStart = node.expression.getStart(sf);
const lc = sf.getLineAndCharacterOfPosition(exprStart);
deferredTypeArgs.push(firstTypeArg);
callSites.push({
fnName: binding.fnName,
exprStart,
typeArgsEnd: node.typeArguments.end + 1,
firstTypeArg,
line: lc.line + 1,
column: lc.character + 1,
});
}
}
ts.forEachChild(node, visit);
} finally {
if (pushedScope) {
enclosingTypeParamStack.pop();
}
}
});
// ── post-walk: monomorphize deferred type args ──────────────────────
for (const typeArg of deferredTypeArgs) {
const typeSf = resolveSourceFileForTypeNode(typeArg, sf);
const typeResolver = createImportedTypeNameResolver(typeSf);
monomorphizeTypeNode(typeArg, typeSf, templates, mono, typeResolver);
}
for (const m of mono.values()) {
concrete.push(m);
}
// ── resolve wire types ──────────────────────────────────────────────
// Anything that doesn't resolve to a primitive or a registered message is
// a type-tracking miss — historically these leaked the placeholder
// `WireType.Varint` into codegen and corrupted the wire format silently.
// Throw loudly instead so future analyzer gaps surface immediately.
const names = new Set(concrete.map((m) => m.name));
for (const msg of concrete) {
for (const f of msg.fields) {
const prim = PRIMITIVE_TYPE_MAP[f.typeName];
if (prim) {
f.wireType = prim.wireType;
f.isMessage = false;
} else if (names.has(f.typeName)) {
f.wireType = WireType.LengthDelim;
f.isMessage = true;
} else {
throw new Error(
`Cannot resolve protobuf field type "${f.typeName}" on message "${msg.name}" ` +
`(field "${f.name}", field number ${f.fieldNumber}). The analyzer did not produce ` +
`a primitive or registered message for this type. Common causes: union / intersection / ` +
`mapped / conditional types, TypeScript utility types (Partial<T>, Pick<T>, …), ` +
`qualified names (ns.Type), or a missing import.`,
);
}
}
}
return { registry: topoSort(concrete), callSites, sourceFile: sf };
}
/**
* Backward-compatible wrapper: returns only the MessageRegistry.
* Uses the same single-walk analysis internally.
*/
export function analyzeSource(
code: string,
filePath: string,
imported?: ImportedDefinitions,
): MessageRegistry {
return analyze(code, filePath, imported).registry;
}
/**
* Build a minimal message registry by collecting only call-site root types and
* their transitive message dependencies.
*/
export function selectUsedRegistry(
registry: MessageRegistry,
callSites: CallSiteRecord[],
sourceFile: ts.SourceFile,
): UsedRegistryResult {
const roots = new Set<string>();
const resolved: ResolvedCallSiteRecord[] = [];
for (const cs of callSites) {
const typeSf = resolveSourceFileForTypeNode(cs.firstTypeArg, sourceFile);
const typeName = typeNodeToMangledName(
cs.firstTypeArg,
typeSf,
createImportedTypeNameResolver(typeSf),
);
if (!registry.has(typeName)) {
continue;
}
roots.add(typeName);
resolved.push({ ...cs, typeName });
}
if (roots.size === 0) {
return { registry: new Map(), roots, callSites: resolved };
}
return {
registry: buildDependencyRegistry(registry, roots),
roots,
callSites: resolved,
};
}
// ── topological sort ──────────────────────────────────────────────────
function topoSort(messages: ProtobufMessage[]): MessageRegistry {
const map = new Map(messages.map((m) => [m.name, m]));
const deps = new Map(
messages.map((m) => [
m.name,
new Set(m.fields.filter((f) => map.has(f.typeName)).map((f) => f.typeName)),
]),
);
const sorted: ProtobufMessage[] = [];
const visited = new Set<string>();
const visiting = new Set<string>();
function dfs(name: string): void {
if (visited.has(name)) {
return;
}
if (visiting.has(name)) {
throw new Error(`Circular dependency: ${name}`);
}
visiting.add(name);
for (const d of deps.get(name) || []) {
dfs(d);
}
visiting.delete(name);
visited.add(name);
sorted.push(map.get(name)!);
}
for (const m of messages) {
dfs(m.name);
}
return new Map(sorted.map((m) => [m.name, m]));
}
-141
View File
@@ -1,141 +0,0 @@
import ts from 'typescript';
export type CanonicalProtobufFn = 'protobuf_encode' | 'protobuf_decode';
const CANONICAL = new Set<CanonicalProtobufFn>(['protobuf_encode', 'protobuf_decode']);
const PROTOBUF_RUNTIME_MODULES = new Set(['@snowluma/proton']);
export interface ProtobufImportBindings {
identifierToCanonical: Map<string, CanonicalProtobufFn>;
namespaceAliases: Set<string>;
blockedLegacyCanonical: Set<CanonicalProtobufFn>;
hasRuntimeImport: boolean;
}
export interface ProtobufCallSite {
fnName: CanonicalProtobufFn;
exprStart: number;
typeArgsEnd: number;
firstTypeArg: ts.TypeNode;
line: number;
column: number;
}
export function collectProtobufImportBindings(sf: ts.SourceFile): ProtobufImportBindings {
const identifierToCanonical = new Map<string, CanonicalProtobufFn>();
const namespaceAliases = new Set<string>();
const blockedLegacyCanonical = new Set<CanonicalProtobufFn>();
let hasRuntimeImport = false;
for (const stmt of sf.statements) {
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) {
continue;
}
if (!ts.isStringLiteral(stmt.moduleSpecifier)) {
continue;
}
const fromRuntime = PROTOBUF_RUNTIME_MODULES.has(stmt.moduleSpecifier.text);
if (fromRuntime) {
hasRuntimeImport = true;
}
const bindings = stmt.importClause.namedBindings;
const defaultImport = stmt.importClause.name?.text;
if (defaultImport && CANONICAL.has(defaultImport as CanonicalProtobufFn) && !fromRuntime) {
blockedLegacyCanonical.add(defaultImport as CanonicalProtobufFn);
}
if (!bindings) {
continue;
}
if (ts.isNamedImports(bindings)) {
for (const el of bindings.elements) {
const imported = (el.propertyName ?? el.name).text;
if (fromRuntime && CANONICAL.has(imported as CanonicalProtobufFn)) {
identifierToCanonical.set(el.name.text, imported as CanonicalProtobufFn);
continue;
}
if (CANONICAL.has(el.name.text as CanonicalProtobufFn)) {
blockedLegacyCanonical.add(el.name.text as CanonicalProtobufFn);
}
}
continue;
}
if (fromRuntime && ts.isNamespaceImport(bindings)) {
namespaceAliases.add(bindings.name.text);
} else if (CANONICAL.has(bindings.name.text as CanonicalProtobufFn)) {
blockedLegacyCanonical.add(bindings.name.text as CanonicalProtobufFn);
}
}
return { identifierToCanonical, namespaceAliases, blockedLegacyCanonical, hasRuntimeImport };
}
interface MatchOptions {
allowLegacyUnboundCanonical?: boolean;
}
export function matchProtobufCallSite(
node: ts.CallExpression,
sf: ts.SourceFile,
bindings: ProtobufImportBindings,
options?: MatchOptions,
): ProtobufCallSite | null {
const ta = node.typeArguments;
if (!ta?.length) {
return null;
}
const expr = node.expression;
const allowLegacy = options?.allowLegacyUnboundCanonical === true;
let fnName: CanonicalProtobufFn | null = null;
let exprStart = expr.getStart(sf);
if (ts.isIdentifier(expr)) {
fnName = bindings.identifierToCanonical.get(expr.text) ?? null;
if (
!fnName &&
allowLegacy &&
!bindings.hasRuntimeImport &&
CANONICAL.has(expr.text as CanonicalProtobufFn) &&
!bindings.blockedLegacyCanonical.has(expr.text as CanonicalProtobufFn)
) {
fnName = expr.text as CanonicalProtobufFn;
}
} else if (ts.isPropertyAccessExpression(expr) && ts.isIdentifier(expr.expression)) {
if (
bindings.namespaceAliases.has(expr.expression.text) &&
CANONICAL.has(expr.name.text as CanonicalProtobufFn)
) {
fnName = expr.name.text as CanonicalProtobufFn;
exprStart = expr.getStart(sf);
}
}
if (!fnName) {
return null;
}
const lc = sf.getLineAndCharacterOfPosition(exprStart);
return {
fnName,
exprStart,
typeArgsEnd: ta.end + 1,
firstTypeArg: ta[0],
line: lc.line + 1,
column: lc.character + 1,
};
}
-244
View File
@@ -1,244 +0,0 @@
import ts from 'typescript';
import {
WireType,
PB_MARKER,
PB_REPEATED_MARKER,
PB_OPTIONAL_MARKER,
type ProtobufField,
type ProtobufMessage,
type GenericProtobufTemplate,
type GenericFieldTemplate,
} from './types.js';
import {
isKeywordTypeNode,
typeNodeToMangledName,
type ImportedTypeNameResolver,
} from './utils.js';
function identityImportedTypeName(name: string): string {
return name;
}
/**
* Yield generic-instantiated type-arg nodes appearing as field types on a
* **concrete** (non-generic) interface — e.g. `wrapped: pb<5, Wrapper<uint_32>>`
* yields the `Wrapper<uint_32>` node so the analyzer can enqueue it for
* monomorphization. (The call-site-driven queue only sees the outer concrete
* type; nested generic instantiations on its fields would otherwise be missed.)
*/
export function* collectConcreteFieldGenericTypeArgs(
node: ts.InterfaceDeclaration,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): IterableIterator<ts.TypeNode> {
if (node.typeParameters?.length) {
return;
}
for (const m of node.members) {
if (!ts.isPropertySignature(m) || !m.type) {
continue;
}
const parsed = parsePbTypeRef(m, resolveImportedTypeName);
if (!parsed) {
continue;
}
const ta = parsed.typeArgNode;
if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) {
yield ta;
}
}
}
/** Collect a concrete (non-generic) interface with pb<>/pb_repeated<> fields. */
export function collectInterface(
node: ts.InterfaceDeclaration,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): ProtobufMessage | null {
const fields: ProtobufField[] = [];
for (const m of node.members) {
if (!ts.isPropertySignature(m) || !m.type) {
continue;
}
const f = extractField(m, sf, resolveImportedTypeName);
if (f) {
fields.push(f);
}
}
// Register interfaces that are EXPLICITLY empty (`interface X {}`) as
// zero-field proto messages — proto3 wire format allows them and
// downstream code routinely uses them for "this OIDB call has no
// meaningful response body" placeholders. Interfaces that have
// members but no pb-marked fields are NOT proto messages — they
// belong to regular TS types and must stay unregistered to avoid
// polluting the registry.
if (fields.length === 0 && node.members.length > 0) {
return null;
}
return { name: node.name.text, fields };
}
/** Collect a generic interface template. */
export function collectGenericInterface(
node: ts.InterfaceDeclaration,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): GenericProtobufTemplate | null {
const typeParams = node.typeParameters!.map((p) => p.name.text);
const tpSet = new Set(typeParams);
const fields: GenericFieldTemplate[] = [];
for (const m of node.members) {
if (!ts.isPropertySignature(m) || !m.type) {
continue;
}
const f = extractGenericField(m, sf, tpSet, resolveImportedTypeName);
if (f) {
fields.push(f);
}
}
return fields.length ? { name: node.name.text, typeParams, fields } : null;
}
// ── helpers ───────────────────────────────────────────────────────────
function parsePbTypeRef(
member: ts.PropertySignature,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): { marker: string; fieldNumber: number; typeArgNode: ts.TypeNode } | null {
const t = member.type!;
if (!ts.isTypeReferenceNode(t) || !ts.isIdentifier(t.typeName)) {
return null;
}
// Resolve the marker name through aliased imports so `import { pb as P }`
// / `import { pb_repeated as PR }` still match the marker constants.
const marker = resolveImportedTypeName(t.typeName.text);
if (marker !== PB_MARKER && marker !== PB_REPEATED_MARKER && marker !== PB_OPTIONAL_MARKER) {
return null;
}
const ta = t.typeArguments;
if (!ta || ta.length !== 2) {
return null;
}
const fnNode = ta[0];
if (!ts.isLiteralTypeNode(fnNode) || !ts.isNumericLiteral(fnNode.literal)) {
return null;
}
return { marker, fieldNumber: Number(fnNode.literal.text), typeArgNode: ta[1] };
}
function resolveTypeName(
node: ts.TypeNode,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver,
): string | null {
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) {
// Generic instantiations (e.g. `Wrapper<uint_32>`) must resolve to the
// mangled name produced by monomorphization so wire-type resolution can
// find the message in the registry. Without this the field would carry
// the bare identifier `"Wrapper"` and never link to `Wrapper__uint_32`.
if (node.typeArguments && node.typeArguments.length > 0) {
return typeNodeToMangledName(node, sf, resolveImportedTypeName);
}
return resolveImportedTypeName(node.typeName.text);
}
if (isKeywordTypeNode(node)) {
return node.getText(sf);
}
return null;
}
function extractField(
member: ts.PropertySignature,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver,
): ProtobufField | null {
const parsed = parsePbTypeRef(member, resolveImportedTypeName);
if (!parsed) {
return null;
}
const typeName = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName);
if (!typeName || !ts.isIdentifier(member.name)) {
return null;
}
return {
name: (member.name as ts.Identifier).text,
fieldNumber: parsed.fieldNumber,
typeName,
wireType: WireType.Varint, // placeholder
isMessage: false, // placeholder
isOptional: member.questionToken != null,
isRepeated: parsed.marker === PB_REPEATED_MARKER,
explicitPresence: parsed.marker === PB_OPTIONAL_MARKER,
};
}
function extractGenericField(
member: ts.PropertySignature,
sf: ts.SourceFile,
tpSet: Set<string>,
resolveImportedTypeName: ImportedTypeNameResolver,
): GenericFieldTemplate | null {
const parsed = parsePbTypeRef(member, resolveImportedTypeName);
if (!parsed) {
return null;
}
const raw = resolveTypeName(parsed.typeArgNode, sf, resolveImportedTypeName);
if (!raw || !ts.isIdentifier(member.name)) {
return null;
}
const result: GenericFieldTemplate = {
name: (member.name as ts.Identifier).text,
fieldNumber: parsed.fieldNumber,
rawTypeName: tpSet.has(raw) ? raw : resolveImportedTypeName(raw),
isTypeParam: tpSet.has(raw),
isOptional: member.questionToken != null,
isRepeated: parsed.marker === PB_REPEATED_MARKER,
explicitPresence: parsed.marker === PB_OPTIONAL_MARKER,
};
// If the field's type-arg is itself a generic instantiation (`Wrapper<U>`,
// where U is a type param of the enclosing template), capture the original
// source text so monomorphization can substitute U and re-instantiate the
// inner generic. Without this the field's `rawTypeName` would stay at the
// unsubstituted `'Wrapper__U'` form and the substituted instantiation
// would never reach the registry.
const ta = parsed.typeArgNode;
if (ts.isTypeReferenceNode(ta) && ta.typeArguments && ta.typeArguments.length > 0) {
result.genericTypeArgText = ta.getText(sf);
result.genericTypeArgSourceFilePath = sf.fileName;
}
return result;
}
File diff suppressed because it is too large. Load diff
-173
View File
@@ -1,173 +0,0 @@
import ts from 'typescript';
import {
WireType,
type ProtobufField,
type ProtobufMessage,
type GenericProtobufTemplate,
} from './types.js';
import {
isKeywordTypeNode,
createImportedTypeNameResolver,
resolveSourceFileForTypeNode,
type ImportedTypeNameResolver,
typeNodeToMangledName,
} from './utils.js';
function identityImportedTypeName(name: string): string {
return name;
}
/** Resolved value for a single template type parameter. */
interface ResolvedTypeArg {
/** Mangled-name form used when substituting into a `rawTypeName` slot
* for an `isTypeParam` field. */
mangled: string;
/** Original TypeScript source text — used when re-substituting into a
* field's `genericTypeArgText` so the substituted text remains parseable. */
text: string;
}
/**
* Recursively monomorphize a generic type instantiation into concrete ProtobufMessages.
* E.g. `Wrapper<Wrapper<string>>` → creates `Wrapper__string` and `Wrapper__Wrapper__string`.
* Returns the mangled name of the concrete type, or null if it cannot be resolved.
*/
export function monomorphizeTypeNode(
typeNode: ts.TypeNode,
sf: ts.SourceFile,
templates: Map<string, GenericProtobufTemplate>,
out: Map<string, ProtobufMessage>,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): string | null {
if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) {
return null;
}
const baseName = resolveImportedTypeName(typeNode.typeName.text);
const typeArgs = typeNode.typeArguments;
if (!typeArgs || typeArgs.length === 0) {
return baseName;
} // already concrete
const tpl = templates.get(baseName);
if (!tpl || typeArgs.length !== tpl.typeParams.length) {
return null;
}
const mangledName = typeNodeToMangledName(typeNode, sf, resolveImportedTypeName);
if (out.has(mangledName)) {
return mangledName;
} // already done
// Resolve each type parameter → both mangled name AND source text.
const paramMap = new Map<string, ResolvedTypeArg>();
for (let i = 0; i < tpl.typeParams.length; i++) {
const resolved = resolveTypeArg(typeArgs[i], sf, templates, out, resolveImportedTypeName);
if (!resolved) {
return null;
}
paramMap.set(tpl.typeParams[i], resolved);
}
// Substitute type params in template fields.
const fields: ProtobufField[] = tpl.fields.map((f) => {
if (f.genericTypeArgText) {
// Field type is an inner generic instantiation referencing template
// type params (e.g. `pb<N, Wrapper<U>>`). Substitute the params into
// the captured text, re-parse, and re-monomorphize so the resulting
// concrete instantiation (`Wrapper<uint_32>`) lands in `out`.
let substituted = f.genericTypeArgText;
for (const [paramName, value] of paramMap) {
substituted = substituted.replace(
new RegExp(`\\b${paramName}\\b`, 'g'),
value.text,
);
}
const innerSfPath = f.genericTypeArgSourceFilePath ?? sf.fileName;
const innerSf = ts.createSourceFile(
innerSfPath,
`type __X = ${substituted};`,
ts.ScriptTarget.Latest,
true,
);
const stmt = innerSf.statements[0];
let resolvedTypeName: string | null = null;
if (ts.isTypeAliasDeclaration(stmt)) {
const innerResolver = createImportedTypeNameResolver(innerSf);
resolvedTypeName = monomorphizeTypeNode(
stmt.type,
innerSf,
templates,
out,
innerResolver,
);
}
return {
name: f.name,
fieldNumber: f.fieldNumber,
typeName: resolvedTypeName ?? f.rawTypeName,
wireType: WireType.Varint,
isMessage: false,
isOptional: f.isOptional,
isRepeated: f.isRepeated,
explicitPresence: f.explicitPresence,
};
}
return {
name: f.name,
fieldNumber: f.fieldNumber,
typeName: f.isTypeParam
? (paramMap.get(f.rawTypeName)?.mangled ?? f.rawTypeName)
: f.rawTypeName,
wireType: WireType.Varint,
isMessage: false,
isOptional: f.isOptional,
isRepeated: f.isRepeated,
explicitPresence: f.explicitPresence,
};
});
out.set(mangledName, { name: mangledName, fields });
return mangledName;
}
function resolveTypeArg(
node: ts.TypeNode,
sf: ts.SourceFile,
templates: Map<string, GenericProtobufTemplate>,
out: Map<string, ProtobufMessage>,
resolveImportedTypeName: ImportedTypeNameResolver,
): ResolvedTypeArg | null {
const effectiveSf = resolveSourceFileForTypeNode(node, sf);
// Try recursive monomorphization first (handles nested generics).
const mono = monomorphizeTypeNode(node, effectiveSf, templates, out, resolveImportedTypeName);
if (mono) {
return { mangled: mono, text: node.getText(effectiveSf) };
}
// Keyword type (string, number, …)
if (isKeywordTypeNode(node)) {
const text = node.getText(effectiveSf);
return { mangled: text, text };
}
// Simple identifier (uint_32, SomeMsg, …)
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && !node.typeArguments) {
const name = resolveImportedTypeName(node.typeName.text);
return { mangled: name, text: name };
}
return null;
}
-83
View File
@@ -1,83 +0,0 @@
export enum WireType {
Varint = 0,
Bit64 = 1,
LengthDelim = 2,
Bit32 = 5,
}
export interface ProtobufField {
name: string;
fieldNumber: number;
typeName: string;
wireType: WireType;
isMessage: boolean;
isOptional: boolean;
isRepeated: boolean;
/**
* Explicit presence (proto3 `optional`), set only by the `pb_optional<>`
* marker. When true, a scalar field serialises even at its zero/default
* value. Distinct from `isOptional` (which merely tracks the TS `?` and is
* true for almost every field) — the encoder keys off THIS flag, never
* `isOptional`, so existing `pb<>` fields are unaffected.
*/
explicitPresence: boolean;
}
export interface ProtobufMessage {
name: string;
fields: ProtobufField[];
}
/** Generic interface template, e.g. `interface Wrapper<T> { val: pb<1, T>; }` */
export interface GenericProtobufTemplate {
name: string;
typeParams: string[];
fields: GenericFieldTemplate[];
}
export interface GenericFieldTemplate {
name: string;
fieldNumber: number;
rawTypeName: string;
isTypeParam: boolean;
isOptional: boolean;
isRepeated: boolean;
/** Explicit presence (proto3 `optional`); see ProtobufField.explicitPresence. */
explicitPresence: boolean;
/**
* For fields whose type-arg is itself a generic instantiation
* (e.g. `wrapped: pb<5, Wrapper<U>>` where `U` is a template type
* parameter), the original type-arg source text. At monomorphization
* time the substituted text is re-parsed and re-instantiated so
* `Wrapper<uint_32>` ends up in the registry under its mangled name.
*/
genericTypeArgText?: string;
/** Source-file path captured alongside `genericTypeArgText`, used as
* the synthetic file name when re-parsing the substituted text. */
genericTypeArgSourceFilePath?: string;
}
export type MessageRegistry = Map<string, ProtobufMessage>;
export const PRIMITIVE_TYPE_MAP: Record<string, { wireType: WireType; defaultValue: string }> = {
uint_32: { wireType: WireType.Varint, defaultValue: '0' },
int_32: { wireType: WireType.Varint, defaultValue: '0' },
uint_64: { wireType: WireType.Varint, defaultValue: '0' },
int_64: { wireType: WireType.Varint, defaultValue: '0' },
sint_32: { wireType: WireType.Varint, defaultValue: '0' },
sint_64: { wireType: WireType.Varint, defaultValue: '0' },
bool: { wireType: WireType.Varint, defaultValue: 'false' },
string: { wireType: WireType.LengthDelim, defaultValue: '""' },
bytes: { wireType: WireType.LengthDelim, defaultValue: 'new Uint8Array(0)' },
float: { wireType: WireType.Bit32, defaultValue: '0' },
double: { wireType: WireType.Bit64, defaultValue: '0' },
fixed_32: { wireType: WireType.Bit32, defaultValue: '0' },
fixed_64: { wireType: WireType.Bit64, defaultValue: '0' },
sfixed_32: { wireType: WireType.Bit32, defaultValue: '0' },
sfixed_64: { wireType: WireType.Bit64, defaultValue: '0' },
};
/** Marker identifiers recognised in type references */
export const PB_MARKER = 'pb';
export const PB_REPEATED_MARKER = 'pb_repeated';
export const PB_OPTIONAL_MARKER = 'pb_optional';
-115
View File
@@ -1,115 +0,0 @@
import ts from 'typescript';
export type ImportedTypeNameResolver = (name: string) => string;
export function getCallableName(expr: ts.Expression): string | null {
if (ts.isIdentifier(expr)) {
return expr.text;
}
if (ts.isPropertyAccessExpression(expr)) {
return expr.name.text;
}
return null;
}
function identityImportedTypeName(name: string): string {
return name;
}
// Synthetic type-arg nodes (produced by wrapper-binding instantiation) live in
// their own SourceFile, not in the caller's. Anyone that needs to read text or
// resolve imports against such a node must use the registered SF; otherwise
// `node.getText(callerSf)` reads garbage from the wrong buffer.
const syntheticTypeSourceFiles = new WeakMap<ts.TypeNode, ts.SourceFile>();
export function registerSyntheticTypeSourceFile(node: ts.TypeNode, sf: ts.SourceFile): void {
syntheticTypeSourceFiles.set(node, sf);
}
export function resolveSourceFileForTypeNode(
node: ts.TypeNode,
fallback: ts.SourceFile,
): ts.SourceFile {
return syntheticTypeSourceFiles.get(node) ?? fallback;
}
// TS 5.9+ removed ts.isKeywordTypeNode — manual kind-based check
const KEYWORD_TYPE_KINDS = new Set([
ts.SyntaxKind.StringKeyword,
ts.SyntaxKind.NumberKeyword,
ts.SyntaxKind.BooleanKeyword,
ts.SyntaxKind.AnyKeyword,
ts.SyntaxKind.VoidKeyword,
ts.SyntaxKind.UndefinedKeyword,
ts.SyntaxKind.NullKeyword,
ts.SyntaxKind.NeverKeyword,
ts.SyntaxKind.UnknownKeyword,
ts.SyntaxKind.BigIntKeyword,
ts.SyntaxKind.SymbolKeyword,
ts.SyntaxKind.ObjectKeyword,
]);
export function isKeywordTypeNode(node: ts.Node): boolean {
return KEYWORD_TYPE_KINDS.has(node.kind);
}
export function createImportedTypeNameResolver(sf: ts.SourceFile): ImportedTypeNameResolver {
const localToImported = new Map<string, string>();
for (const stmt of sf.statements) {
if (!ts.isImportDeclaration(stmt) || !stmt.importClause) {
continue;
}
const bindings = stmt.importClause.namedBindings;
if (!bindings || !ts.isNamedImports(bindings)) {
continue;
}
for (const el of bindings.elements) {
localToImported.set(el.name.text, (el.propertyName ?? el.name).text);
}
}
return (name: string) => localToImported.get(name) ?? name;
}
/**
* Deterministic mangled name for a type node.
* `Foo` → `Foo`
* `Foo<string>` → `Foo__string`
* `Foo<Bar<uint_32>>` → `Foo__Bar__uint_32`
*
* If `typeNode` is a synthetic node produced by wrapper-binding instantiation,
* its registered source file is used automatically so `getText()` returns
* the substituted type text rather than garbage from `sf`.
*/
export function typeNodeToMangledName(
typeNode: ts.TypeNode,
sf: ts.SourceFile,
resolveImportedTypeName: ImportedTypeNameResolver = identityImportedTypeName,
): string {
const effectiveSf = resolveSourceFileForTypeNode(typeNode, sf);
if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) {
const base = resolveImportedTypeName(typeNode.typeName.text);
if (typeNode.typeArguments && typeNode.typeArguments.length > 0) {
const args = typeNode.typeArguments.map((a) =>
typeNodeToMangledName(a, effectiveSf, resolveImportedTypeName),
);
return base + '__' + args.join('__');
}
return base;
}
if (isKeywordTypeNode(typeNode)) {
return typeNode.getText(effectiveSf);
}
return typeNode.getText(effectiveSf);
}
+13
View File
@@ -0,0 +1,13 @@
export const buffers = `let __pool;
let __poolOffset = 0;
function __allocate(size) {
if (size > 4096) return new Uint8Array(size);
let buffer = __pool;
if (!buffer || __poolOffset + size > buffer.length) {
buffer = __pool = new Uint8Array(8192);
__poolOffset = 0;
}
const start = __poolOffset;
__poolOffset += size;
return buffer.subarray(start, start + size);
}`;
+146 -125
View File
@@ -3,84 +3,118 @@ import {
PRIMITIVE_TYPE_MAP,
type ProtobufField,
type ProtobufMessage,
type MessageRegistry,
} from '../ast/types.js';
} from '../codegen/model.js';
function tagValue(field: ProtobufField): number {
const wireType =
field.isMessage || field.typeName === 'string' || field.typeName === 'bytes'
? WireType.LengthDelim
: field.wireType;
function tagValue(field: ProtobufField, wireType = field.wireType): number {
return ((field.fieldNumber << 3) | wireType) >>> 0;
}
/** Emit inline varint decode, storing result in `varName`. */
function varintDec(varName: string, ind: string): string {
/** Read the low 32 bits, consuming sign-extended int32 varints without shift wraparound. */
function varintDec(
varName: string,
ind: string,
end = 'end',
maxBytes = 10,
truthy = false,
checkInitial = true,
): string {
const lastShift = (maxBytes - 1) * 7;
const lastByte = maxBytes === 5 ? 0x0f : 0x01;
return [
`${ind}const [${varName}, ${varName}_offset] = __readVarint32(data, offset, end);`,
`${ind}offset = ${varName}_offset;`,
...(checkInitial
? [`${ind}if (offset >= ${end}) throw new Error('Truncated protobuf varint');`]
: []),
`${ind}let ${varName} = data[offset++];`,
`${ind}if (${varName} & 0x80) {`,
`${ind} let _s = 7, _b;`,
`${ind} ${varName} &= 0x7f;`,
`${ind} do {`,
`${ind} if (offset >= ${end}) throw new Error('Truncated protobuf varint');`,
`${ind} _b = data[offset++];`,
`${ind} if (_s === ${lastShift} && _b > ${lastByte}) throw new Error('Invalid protobuf varint');`,
truthy
? `${ind} ${varName} |= _b & 0x7f;`
: `${ind} if (_s < 32) ${varName} |= (_b & 0x7f) << _s;`,
`${ind} _s += 7;`,
`${ind} } while (_b & 0x80);`,
`${ind} ${varName} >>>= 0;`,
`${ind}}`,
].join('\n');
}
function varintDec64(varName: string, ind: string): string {
function varintDec64(varName: string, ind: string, end: string): string {
return [
`${ind}const [${varName}, ${varName}_offset] = __readVarint64(data, offset, end);`,
`${ind}offset = ${varName}_offset;`,
`${ind}let _lo = 0, _hi = 0, _s = 0, _b;`,
`${ind}do {`,
`${ind} if (offset >= ${end}) throw new Error('Truncated protobuf varint');`,
`${ind} _b = data[offset++];`,
`${ind} if (_s === 63 && _b > 1) throw new Error('Invalid protobuf varint');`,
`${ind} if (_s < 28) _lo |= (_b & 0x7f) << _s;`,
`${ind} else if (_s === 28) { _lo |= (_b & 0x7f) << 28; _hi = (_b & 0x7f) >>> 4; }`,
`${ind} else _hi |= (_b & 0x7f) << (_s - 32);`,
`${ind} _s += 7;`,
`${ind}} while (_b & 0x80);`,
`${ind}const ${varName} = _hi === 0 ? BigInt(_lo >>> 0) : BigInt(_lo >>> 0) | (BigInt(_hi >>> 0) << 32n);`,
].join('\n');
}
function varintDec32Value(varName: string, ind: string): string {
return [
`${ind}const [${varName}, ${varName}_offset] = __readVarint32Value(data, offset, end);`,
`${ind}offset = ${varName}_offset;`,
].join('\n');
function checkLength(length: string | number, ind: string, end: string): string {
return `${ind}if (offset + ${length} > ${end}) throw new Error('Truncated protobuf field');`;
}
function isVarint64(typeName: string): boolean {
return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64';
}
function isFixed64BigInt(typeName: string): boolean {
return typeName === 'fixed_64' || typeName === 'sfixed_64';
}
const INLINE_SKIP = ` offset = __skipUnknownField(data, offset, end, wireType, _tag >>> 3);`;
export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry): string {
export function generateDecoder(msg: ProtobufMessage): string {
const locals = msg.fields.map((field, index) => {
const keyword = field.isRepeated ? 'const' : 'let';
return ` ${keyword} _f${index} = ${getDefault(field)};`;
});
const result = msg.fields.map((field, index) => `${field.name}: _f${index}`).join(', ');
const result = msg.fields
.map(
(field, index) =>
`${field.name === '__proto__' ? '["__proto__"]' : JSON.stringify(field.name)}: _f${index}`,
)
.join(', ');
const L = [
const lines = [
`function protobuf_decode_${msg.name}(data, offset = 0, end = data.length) {`,
` if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(end) || offset < 0 || end < offset || end > data.length) {`,
` throw new Error('protobuf decoder bounds are invalid');`,
` }`,
` if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(end) || offset < 0 || end > data.length || offset > end) throw new Error('Invalid protobuf bounds');`,
...locals,
` let _unknownFields = null;`,
` let _unknownFieldsByKey = null;`,
` let _unknownTotalOccurrences = 0;`,
` let _unknownOmittedOccurrences = 0;`,
` let _unknownOmittedByteLength = 0;`,
` while (offset < end) {`,
` const _fieldStart = offset;`,
` const [_tag, _tagOffset] = __readVarint32(data, offset, end);`,
` offset = _tagOffset;`,
` if ((_tag >>> 3) === 0) throw new Error('protobuf field number 0 is invalid');`,
varintDec('_tag', ' ', 'end', 5, false, false),
` if ((_tag >>> 3) === 0) throw new Error('Invalid protobuf field number');`,
` switch (_tag) {`,
];
msg.fields.forEach((field, index) => {
L.push(decodeField(field, index));
lines.push(` case ${tagValue(field)}: {`);
lines.push(...decodeValue(field, index, ' ', 'end'));
lines.push(` break;`, ` }`);
if (field.isRepeated && !field.isMessage && field.wireType !== WireType.LengthDelim) {
lines.push(
` case ${tagValue(field, WireType.LengthDelim)}: {`,
varintDec('_len', ' ', 'end', 5),
checkLength('_len', ' ', 'end'),
` const _packedEnd = offset + _len;`,
` while (offset < _packedEnd) {`,
...decodeValue(field, index, ' ', '_packedEnd'),
` }`,
` break;`,
` }`,
);
}
});
L.push(
lines.push(
` default: {`,
` const _unknownStart = offset;`,
` const wireType = _tag & 0x7;`,
INLINE_SKIP,
` offset = __skipUnknownField(data, offset, end, wireType, _tag >>> 3);`,
` const _unknownFieldNumber = _tag >>> 3;`,
` const _unknownByteLength = offset - _unknownStart;`,
` const _unknownKey = (_unknownFieldNumber * 8) + wireType;`,
@@ -102,10 +136,10 @@ export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry
` _unknownOmittedOccurrences++;`,
` _unknownOmittedByteLength += _unknownByteLength;`,
` }`,
` break;`,
` }`,
` }`,
` if (offset <= _fieldStart || offset > end) throw new Error('protobuf decoder made invalid progress');`,
` }`,
` const _result = { ${result} };`,
` if (_unknownTotalOccurrences > 0) Object.defineProperty(`,
@@ -124,96 +158,83 @@ export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry
` return _result;`,
`}`,
);
return L.join('\n');
return lines.join('\n');
}
function decodeField(field: ProtobufField, index: number): string {
/** Shared by ordinary fields and packed repeated payloads. */
function decodeValue(field: ProtobufField, index: number, ind: string, end: string): string[] {
const { typeName, wireType, isMessage, isRepeated } = field;
const I = ' ';
const local = `_f${index}`;
const assign = (expr: string) =>
isRepeated ? `${I}${local}.push(${expr});` : `${I}${local} = ${expr};`;
isRepeated ? `${ind}${local}.push(${expr});` : `${ind}${local} = ${expr};`;
const lines: string[] = [];
const L: string[] = [` case ${tagValue(field)}: {`];
if (isMessage) {
L.push(varintDec('_len', I));
L.push(`${I}const _end = __checkedEnd(offset, _len, end);`);
L.push(assign(`protobuf_decode_${typeName}(data, offset, _end)`));
L.push(`${I}offset = _end;`);
} else if (typeName === 'string') {
L.push(varintDec('_len', I));
L.push(`${I}const _end = __checkedEnd(offset, _len, end);`);
L.push(assign(`__td.decode(data.subarray(offset, _end))`));
L.push(`${I}offset = _end;`);
} else if (typeName === 'bytes') {
L.push(varintDec('_len', I));
L.push(`${I}const _end = __checkedEnd(offset, _len, end);`);
L.push(assign(`data.slice(offset, _end)`));
L.push(`${I}offset = _end;`);
} else if (typeName === 'bool') {
L.push(varintDec('_val', I));
L.push(assign(`_val !== 0`));
} else if (isVarint64(typeName)) {
L.push(varintDec64('_val', I));
if (typeName === 'uint_64') {
L.push(assign(`_val`));
} else if (typeName === 'int_64') {
L.push(assign(`BigInt.asIntN(64, _val)`));
} else {
L.push(assign(`__zigZagDecode64(_val)`));
}
} else if (typeName === 'int_32') {
// Protobuf encodes negative int32 values as a sign-extended 10-byte
// varint. Read the full uint64 representation, then keep its signed low
// 32 bits.
L.push(varintDec64('_val', I));
L.push(assign(`Number(BigInt.asIntN(32, _val))`));
} else if (typeName === 'sint_32') {
L.push(varintDec('_val', I));
L.push(assign(`(_val >>> 1) ^ -(_val & 1)`));
} else if (wireType === WireType.Varint) {
L.push(varintDec32Value('_val', I));
L.push(assign(`_val >>> 0`));
} else if (typeName === 'float') {
L.push(`${I}if (end - offset < 4) throw new Error('protobuf truncated float field');`);
L.push(assign(`__readFloat32(data, offset)`));
L.push(`${I}offset += 4;`);
} else if (wireType === WireType.Bit32) {
L.push(`${I}if (end - offset < 4) throw new Error('protobuf truncated fixed32 field');`);
L.push(
assign(
`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`,
),
);
L.push(`${I}offset += 4;`);
} else if (typeName === 'double') {
L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated double field');`);
L.push(assign(`__readFloat64(data, offset)`));
L.push(`${I}offset += 8;`);
} else if (isFixed64BigInt(typeName)) {
L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated fixed64 field');`);
if (typeName === 'fixed_64') {
L.push(assign(`__readFixed64(data, offset)`));
} else {
L.push(assign(`BigInt.asIntN(64, __readFixed64(data, offset))`));
}
L.push(`${I}offset += 8;`);
} else if (wireType === WireType.Bit64) {
L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated fixed64 field');`);
L.push(
assign(
`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`,
),
);
L.push(`${I}offset += 8;`);
if (wireType === WireType.Bit32) {
lines.push(checkLength(4, ind, end));
}
L.push(`${I}break;`, ` }`);
return L.join('\n');
if (wireType === WireType.Bit64) {
lines.push(checkLength(8, ind, end));
}
if (isMessage || typeName === 'string' || typeName === 'bytes') {
lines.push(varintDec('_len', ind, end, 5), checkLength('_len', ind, end));
if (isMessage) {
lines.push(assign(`protobuf_decode_${typeName}(data, offset, offset + _len)`));
} else if (typeName === 'string') {
lines.push(
assign(
`_len <= 32 ? __utf8Read(data, offset, offset + _len) : __utf8ReadLong(data, offset, offset + _len)`,
),
);
} else {
lines.push(assign(`data.slice(offset, offset + _len)`));
}
lines.push(`${ind}offset += _len;`);
} else if (typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64') {
lines.push(varintDec64('_val', ind, end));
const value =
typeName === 'uint_64'
? '_val'
: typeName === 'int_64'
? 'BigInt.asIntN(64, _val)'
: '__zigZagDecode64(_val)';
lines.push(assign(value));
} else if (wireType === WireType.Varint) {
lines.push(varintDec('_val', ind, end, 10, typeName === 'bool'));
const value =
typeName === 'bool'
? '_val !== 0'
: typeName === 'sint_32'
? '(_val >>> 1) ^ -(_val & 1)'
: typeName === 'int_32'
? '_val | 0'
: '_val';
lines.push(assign(value));
} else if (typeName === 'float') {
lines.push(assign('__readFloat32(data, offset)'), `${ind}offset += 4;`);
} else if (wireType === WireType.Bit32) {
const value =
'(data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24))';
lines.push(
assign(typeName === 'fixed_32' ? `${value} >>> 0` : value),
`${ind}offset += 4;`,
);
} else if (typeName === 'double') {
lines.push(assign('__readFloat64(data, offset)'), `${ind}offset += 8;`);
} else if (typeName === 'fixed_64' || typeName === 'sfixed_64') {
const value =
typeName === 'fixed_64'
? '__readFixed64(data, offset)'
: 'BigInt.asIntN(64, __readFixed64(data, offset))';
lines.push(assign(value), `${ind}offset += 8;`);
} else {
throw new Error(`Unsupported protobuf field type: ${typeName}`);
}
return lines;
}
function getDefault(field: ProtobufField): string {
@@ -1,4 +1,4 @@
import type { MessageRegistry } from './types.js';
import type { MessageRegistry } from './model.js';
export function collectDependencyClosure(
registry: MessageRegistry,
@@ -32,26 +32,3 @@ export function collectDependencyClosure(
return selected;
}
export function pickRegistrySubset(
registry: MessageRegistry,
selectedNames: Set<string>,
): MessageRegistry {
const subset: MessageRegistry = new Map();
for (const [name, msg] of registry) {
if (selectedNames.has(name)) {
subset.set(name, msg);
}
}
return subset;
}
export function buildDependencyRegistry(
registry: MessageRegistry,
roots: Iterable<string>,
): MessageRegistry {
const selected = collectDependencyClosure(registry, roots);
return pickRegistrySubset(registry, selected);
}
+39 -833
View File
@@ -1,845 +1,51 @@
import {
WireType,
type ProtobufField,
type ProtobufMessage,
type MessageRegistry,
} from '../ast/types.js';
import type { ProtobufMessage } from './model.js';
import { fieldBlock } from './fields.js';
/**
* Pre-compute tag bytes at codegen time.
* Field 1 + Varint(0) -> [0x08], Field 1 + LenDelim(2) -> [0x0a], etc.
*/
function computeTagBytes(fieldNumber: number, wireType: number): number[] {
let value = ((fieldNumber << 3) | wireType) >>> 0;
const bytes: number[] = [];
while (value > 0x7f) {
bytes.push((value & 0x7f) | 0x80);
value >>>= 7;
}
bytes.push(value & 0x7f);
return bytes;
}
function writeTag(fieldNumber: number, wireType: number, ind: string): string {
return computeTagBytes(fieldNumber, wireType)
.map((byte) => `${ind}buf[offset++] = ${byte};`)
.join('\n');
}
function varintSize(varName: string, ind: string): string {
return `${ind}size += ${varName} < 0x80 ? 1 : ${varName} < 0x4000 ? 2 : ${varName} < 0x200000 ? 3 : ${varName} < 0x10000000 ? 4 : 5;`;
}
function writeVarint(expr: string, ind: string): string {
export function generateEncoderHelpers(message: ProtobufMessage): string {
const blocks = message.fields.map((field, index) => fieldBlock(field, index, true));
return [
`${ind}let _v = ${expr};`,
`${ind}if (_v < 0x80) {`,
`${ind} buf[offset++] = _v;`,
`${ind}} else if (_v < 0x4000) {`,
`${ind} buf[offset++] = (_v & 0x7f) | 0x80;`,
`${ind} buf[offset++] = _v >>> 7;`,
`${ind}} else if (_v < 0x200000) {`,
`${ind} buf[offset++] = (_v & 0x7f) | 0x80;`,
`${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`,
`${ind} buf[offset++] = _v >>> 14;`,
`${ind}} else if (_v < 0x10000000) {`,
`${ind} buf[offset++] = (_v & 0x7f) | 0x80;`,
`${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`,
`${ind} buf[offset++] = ((_v >>> 14) & 0x7f) | 0x80;`,
`${ind} buf[offset++] = _v >>> 21;`,
`${ind}} else {`,
`${ind} buf[offset++] = (_v & 0x7f) | 0x80;`,
`${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`,
`${ind} buf[offset++] = ((_v >>> 14) & 0x7f) | 0x80;`,
`${ind} buf[offset++] = ((_v >>> 21) & 0x7f) | 0x80;`,
`${ind} buf[offset++] = _v >>> 28;`,
`${ind}}`,
`function __size_${message.name}(obj, sizes) {`,
' let size = 0;',
...blocks.flatMap((block) => block.declare),
...blocks.flatMap((block) => block.size),
' return size;',
'}',
`function __write_${message.name}(obj, buf, offset, sizes) {`,
...blocks.flatMap((block) => block.declare),
...blocks.flatMap((block) => block.write),
' return offset;',
'}',
].join('\n');
}
function isVarint64(typeName: string): boolean {
return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64';
}
export function generateEncoder(message: ProtobufMessage, pooled = false): string {
const allocation = pooled
? ' const buf = size <= 64 ? new Uint8Array(size) : __allocate(size);'
: ' const buf = new Uint8Array(size);';
function isFixed64BigInt(typeName: string): boolean {
return typeName === 'fixed_64' || typeName === 'sfixed_64';
}
function bigintVarintExpr(typeName: string, expr: string): string {
if (typeName === 'uint_64') {
return `BigInt.asUintN(64, ${expr})`;
if (message.fields.some((field) => field.isMessage)) {
return [
`function protobuf_encode_${message.name}(obj) {`,
' const sizes = [1];',
...(pooled
? [` const size = __size_${message.name}(obj, sizes);`, allocation]
: [` const buf = new Uint8Array(__size_${message.name}(obj, sizes));`]),
` __write_${message.name}(obj, buf, 0, sizes);`,
' return buf;',
'}',
].join('\n');
}
if (typeName === 'int_64') {
return `BigInt.asUintN(64, ${expr})`;
}
return `__zigZagEncode64(${expr})`;
}
interface EncoderBlock {
declare: string[];
size: string[];
write: string[];
}
export function generateEncoder(msg: ProtobufMessage, _registry: MessageRegistry): string {
const blocks = msg.fields.map((field, index) =>
field.isRepeated ? buildRepeatedBlock(field, index) : buildSingularBlock(field, index),
);
const L = [
`function protobuf_encode_${msg.name}(obj) {`,
` let size = 0;`,
const blocks = message.fields.map((field, index) => fieldBlock(field, index, false));
return [
`function protobuf_encode_${message.name}(obj) {`,
' let size = 0;',
...blocks.flatMap((block) => block.declare),
...blocks.flatMap((block) => block.size),
` const buf = new Uint8Array(size);`,
` let offset = 0;`,
allocation,
' let offset = 0;',
...blocks.flatMap((block) => block.write),
` return buf;`,
`}`,
];
return L.join('\n');
}
function buildSingularBlock(field: ProtobufField, index: number): EncoderBlock {
const { name, fieldNumber, typeName, wireType, isMessage } = field;
// `pb_optional<>` scalar → serialise even at the zero value (proto3 explicit
// presence). Message fields already emit on `!= null`, so they stay on the
// default path; only scalars need the dedicated guard. Every `pb<>` /
// `pb_repeated<>` field has `explicitPresence === false` and so takes the
// untouched branches below — their generated code is byte-for-byte unchanged.
if (field.explicitPresence && !isMessage) {
return buildExplicitPresenceScalarBlock(field, index);
}
const valueVar = `_f${index}`;
const cacheVar = `_c${index}`;
const tagLength = computeTagBytes(
fieldNumber,
isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType,
).length;
if (isMessage) {
return {
declare: [` const ${valueVar} = obj.${name};`, ` let ${cacheVar};`],
size: [
` if (${valueVar} != null) {`,
` ${cacheVar} = protobuf_encode_${typeName}(${valueVar});`,
` const _len = ${cacheVar}.length;`,
` size += ${tagLength};`,
varintSize('_len', ' '),
` size += _len;`,
` }`,
],
write: [
` if (${valueVar} != null) {`,
` const _data = ${cacheVar};`,
writeTag(fieldNumber, 2, ' '),
` const _len = _data.length;`,
writeVarint('_len', ' '),
` buf.set(_data, offset);`,
` offset += _len;`,
` }`,
],
};
}
if (typeName === 'string') {
return {
declare: [` const ${valueVar} = obj.${name};`, ` let ${cacheVar};`],
size: [
` if (${valueVar} != null && ${valueVar} !== "") {`,
` ${cacheVar} = __utf8Len(${valueVar});`,
` const _len = ${cacheVar};`,
` size += ${tagLength};`,
varintSize('_len', ' '),
` size += _len;`,
` }`,
],
write: [
` if (${valueVar} != null && ${valueVar} !== "") {`,
writeTag(fieldNumber, 2, ' '),
` const _len = ${cacheVar};`,
writeVarint('_len', ' '),
` offset = __utf8Write(buf, offset, ${valueVar});`,
` }`,
],
};
}
if (typeName === 'bytes') {
return {
declare: [` const ${valueVar} = obj.${name};`],
size: [
` if (${valueVar} != null && ${valueVar}.length > 0) {`,
` const _len = ${valueVar}.length;`,
` size += ${tagLength};`,
varintSize('_len', ' '),
` size += _len;`,
` }`,
],
write: [
` if (${valueVar} != null && ${valueVar}.length > 0) {`,
writeTag(fieldNumber, 2, ' '),
` const _len = ${valueVar}.length;`,
writeVarint('_len', ' '),
` buf.set(${valueVar}, offset);`,
` offset += _len;`,
` }`,
],
};
}
if (typeName === 'bool') {
return {
declare: [` const ${valueVar} = obj.${name};`],
size: [` if (${valueVar} === true) size += ${tagLength + 1};`],
write: [
` if (${valueVar} === true) {`,
writeTag(fieldNumber, 0, ' '),
` buf[offset++] = 1;`,
` }`,
],
};
}
if (isVarint64(typeName)) {
const bigintExpr = bigintVarintExpr(typeName, valueVar);
return {
declare: [` const ${valueVar} = obj.${name};`],
size: [
` if (${valueVar} != null && ${valueVar} !== 0n) {`,
` const _val = ${bigintExpr};`,
` size += ${tagLength};`,
` size += __varint64Size(_val);`,
` }`,
],
write: [
` if (${valueVar} != null && ${valueVar} !== 0n) {`,
` const _val = ${bigintExpr};`,
writeTag(fieldNumber, 0, ' '),
` offset = __writeVarint64(buf, offset, _val);`,
` }`,
],
};
}
if (typeName === 'sint_32') {
return {
declare: [` const ${valueVar} = obj.${name};`],
size: [
` if (${valueVar} != null && ${valueVar} !== 0) {`,
` const _val = ((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0;`,
` size += ${tagLength};`,
varintSize('_val', ' '),
` }`,
],
write: [
` if (${valueVar} != null && ${valueVar} !== 0) {`,
writeTag(fieldNumber, 0, ' '),
writeVarint(`((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0`, ' '),
` }`,
],
};
}
if (wireType === WireType.Varint) {
return {
declare: [` const ${valueVar} = obj.${name};`],
size: [
` if (${valueVar} != null && ${valueVar} !== 0) {`,
` const _val = ${valueVar} >>> 0;`,
` size += ${tagLength};`,
varintSize('_val', ' '),
` }`,
],
write: [
` if (${valueVar} != null && ${valueVar} !== 0) {`,
writeTag(fieldNumber, 0, ' '),
writeVarint(`${valueVar} >>> 0`, ' '),
` }`,
],
};
}
if (typeName === 'float') {
return {
declare: [` const ${valueVar} = obj.${name};`],
size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 4};`],
write: [
` if (${valueVar} != null && ${valueVar} !== 0) {`,
writeTag(fieldNumber, 5, ' '),
` offset = __writeFloat32(buf, offset, ${valueVar});`,
` }`,
],
};
}
if (wireType === WireType.Bit32) {
return {
declare: [` const ${valueVar} = obj.${name};`],
size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 4};`],
write: [
` if (${valueVar} != null && ${valueVar} !== 0) {`,
writeTag(fieldNumber, 5, ' '),
` const _val = ${valueVar};`,
` buf[offset++] = _val & 0xff;`,
` buf[offset++] = (_val >> 8) & 0xff;`,
` buf[offset++] = (_val >> 16) & 0xff;`,
` buf[offset++] = (_val >> 24) & 0xff;`,
` }`,
],
};
}
if (typeName === 'double') {
return {
declare: [` const ${valueVar} = obj.${name};`],
size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 8};`],
write: [
` if (${valueVar} != null && ${valueVar} !== 0) {`,
writeTag(fieldNumber, 1, ' '),
` offset = __writeFloat64(buf, offset, ${valueVar});`,
` }`,
],
};
}
if (isFixed64BigInt(typeName)) {
return {
declare: [` const ${valueVar} = obj.${name};`],
size: [` if (${valueVar} != null && ${valueVar} !== 0n) size += ${tagLength + 8};`],
write: [
` if (${valueVar} != null && ${valueVar} !== 0n) {`,
writeTag(fieldNumber, 1, ' '),
` offset = __writeFixed64(buf, offset, ${valueVar});`,
` }`,
],
};
}
if (wireType === WireType.Bit64) {
return {
declare: [` const ${valueVar} = obj.${name};`],
size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 8};`],
write: [
` if (${valueVar} != null && ${valueVar} !== 0) {`,
writeTag(fieldNumber, 1, ' '),
` const _val = ${valueVar};`,
` buf[offset++] = _val & 0xff;`,
` buf[offset++] = (_val >> 8) & 0xff;`,
` buf[offset++] = (_val >> 16) & 0xff;`,
` buf[offset++] = (_val >> 24) & 0xff;`,
` buf[offset++] = 0;`,
` buf[offset++] = 0;`,
` buf[offset++] = 0;`,
` buf[offset++] = 0;`,
` }`,
],
};
}
return { declare: [], size: [], write: [] };
}
/**
* Encoder block for a singular scalar field marked `pb_optional<>` (proto3
* explicit presence). Identical to the default scalar paths EXCEPT the guard
* is `!= null` instead of `!= null && !== <default>`, so the field — and a
* `bool`'s real value — is written even when zero/false/empty. Reached only
* when `field.explicitPresence === true`, so default `pb<>` fields never run
* this code.
*/
function buildExplicitPresenceScalarBlock(field: ProtobufField, index: number): EncoderBlock {
const { name, fieldNumber, typeName, wireType } = field;
const valueVar = `_f${index}`;
const cacheVar = `_c${index}`;
const isLenDelim = typeName === 'string' || typeName === 'bytes';
const tagLength = computeTagBytes(fieldNumber, isLenDelim ? 2 : wireType).length;
const declareVal = ` const ${valueVar} = obj.${name};`;
const present = `${valueVar} != null`;
if (typeName === 'string') {
return {
declare: [declareVal, ` let ${cacheVar};`],
size: [
` if (${present}) {`,
` ${cacheVar} = __utf8Len(${valueVar});`,
` const _len = ${cacheVar};`,
` size += ${tagLength};`,
varintSize('_len', ' '),
` size += _len;`,
` }`,
],
write: [
` if (${present}) {`,
writeTag(fieldNumber, 2, ' '),
` const _len = ${cacheVar};`,
writeVarint('_len', ' '),
` offset = __utf8Write(buf, offset, ${valueVar});`,
` }`,
],
};
}
if (typeName === 'bytes') {
return {
declare: [declareVal],
size: [
` if (${present}) {`,
` const _len = ${valueVar}.length;`,
` size += ${tagLength};`,
varintSize('_len', ' '),
` size += _len;`,
` }`,
],
write: [
` if (${present}) {`,
writeTag(fieldNumber, 2, ' '),
` const _len = ${valueVar}.length;`,
writeVarint('_len', ' '),
` buf.set(${valueVar}, offset);`,
` offset += _len;`,
` }`,
],
};
}
if (typeName === 'bool') {
return {
declare: [declareVal],
size: [` if (${present}) size += ${tagLength + 1};`],
write: [
` if (${present}) {`,
writeTag(fieldNumber, 0, ' '),
` buf[offset++] = ${valueVar} ? 1 : 0;`,
` }`,
],
};
}
if (isVarint64(typeName)) {
const bigintExpr = bigintVarintExpr(typeName, valueVar);
return {
declare: [declareVal],
size: [
` if (${present}) {`,
` const _val = ${bigintExpr};`,
` size += ${tagLength};`,
` size += __varint64Size(_val);`,
` }`,
],
write: [
` if (${present}) {`,
` const _val = ${bigintExpr};`,
writeTag(fieldNumber, 0, ' '),
` offset = __writeVarint64(buf, offset, _val);`,
` }`,
],
};
}
if (typeName === 'sint_32') {
return {
declare: [declareVal],
size: [
` if (${present}) {`,
` const _val = ((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0;`,
` size += ${tagLength};`,
varintSize('_val', ' '),
` }`,
],
write: [
` if (${present}) {`,
writeTag(fieldNumber, 0, ' '),
writeVarint(`((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0`, ' '),
` }`,
],
};
}
if (wireType === WireType.Varint) {
return {
declare: [declareVal],
size: [
` if (${present}) {`,
` const _val = ${valueVar} >>> 0;`,
` size += ${tagLength};`,
varintSize('_val', ' '),
` }`,
],
write: [
` if (${present}) {`,
writeTag(fieldNumber, 0, ' '),
writeVarint(`${valueVar} >>> 0`, ' '),
` }`,
],
};
}
if (typeName === 'float') {
return {
declare: [declareVal],
size: [` if (${present}) size += ${tagLength + 4};`],
write: [
` if (${present}) {`,
writeTag(fieldNumber, 5, ' '),
` offset = __writeFloat32(buf, offset, ${valueVar});`,
` }`,
],
};
}
if (wireType === WireType.Bit32) {
return {
declare: [declareVal],
size: [` if (${present}) size += ${tagLength + 4};`],
write: [
` if (${present}) {`,
writeTag(fieldNumber, 5, ' '),
` const _val = ${valueVar};`,
` buf[offset++] = _val & 0xff;`,
` buf[offset++] = (_val >> 8) & 0xff;`,
` buf[offset++] = (_val >> 16) & 0xff;`,
` buf[offset++] = (_val >> 24) & 0xff;`,
` }`,
],
};
}
if (typeName === 'double') {
return {
declare: [declareVal],
size: [` if (${present}) size += ${tagLength + 8};`],
write: [
` if (${present}) {`,
writeTag(fieldNumber, 1, ' '),
` offset = __writeFloat64(buf, offset, ${valueVar});`,
` }`,
],
};
}
if (isFixed64BigInt(typeName)) {
return {
declare: [declareVal],
size: [` if (${present}) size += ${tagLength + 8};`],
write: [
` if (${present}) {`,
writeTag(fieldNumber, 1, ' '),
` offset = __writeFixed64(buf, offset, ${valueVar});`,
` }`,
],
};
}
if (wireType === WireType.Bit64) {
return {
declare: [declareVal],
size: [` if (${present}) size += ${tagLength + 8};`],
write: [
` if (${present}) {`,
writeTag(fieldNumber, 1, ' '),
` const _val = ${valueVar};`,
` buf[offset++] = _val & 0xff;`,
` buf[offset++] = (_val >> 8) & 0xff;`,
` buf[offset++] = (_val >> 16) & 0xff;`,
` buf[offset++] = (_val >> 24) & 0xff;`,
` buf[offset++] = 0;`,
` buf[offset++] = 0;`,
` buf[offset++] = 0;`,
` buf[offset++] = 0;`,
` }`,
],
};
}
return { declare: [], size: [], write: [] };
}
function buildRepeatedBlock(field: ProtobufField, index: number): EncoderBlock {
const { name, fieldNumber, typeName, wireType, isMessage } = field;
const arrayVar = `_f${index}`;
const cacheVar = `_c${index}`;
const tagWireType = isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType;
const tagLength = computeTagBytes(fieldNumber, tagWireType).length;
if (isMessage) {
return {
declare: [` const ${arrayVar} = obj.${name};`, ` let ${cacheVar};`],
size: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` ${cacheVar} = new Array(${arrayVar}.length);`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
` const _data = protobuf_encode_${typeName}(${arrayVar}[_i]);`,
` ${cacheVar}[_i] = _data;`,
` const _len = _data.length;`,
` size += ${tagLength};`,
varintSize('_len', ' '),
` size += _len;`,
` }`,
` }`,
],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
` const _data = ${cacheVar}[_i];`,
writeTag(fieldNumber, 2, ' '),
` const _len = _data.length;`,
writeVarint('_len', ' '),
` buf.set(_data, offset);`,
` offset += _len;`,
` }`,
` }`,
],
};
}
if (typeName === 'string') {
return {
declare: [` const ${arrayVar} = obj.${name};`, ` let ${cacheVar};`],
size: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` ${cacheVar} = new Array(${arrayVar}.length);`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
` const _len = __utf8Len(${arrayVar}[_i]);`,
` ${cacheVar}[_i] = _len;`,
` size += ${tagLength};`,
varintSize('_len', ' '),
` size += _len;`,
` }`,
` }`,
],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
` const _len = ${cacheVar}[_i];`,
writeTag(fieldNumber, 2, ' '),
writeVarint('_len', ' '),
` offset = __utf8Write(buf, offset, ${arrayVar}[_i]);`,
` }`,
` }`,
],
};
}
if (typeName === 'bytes') {
return {
declare: [` const ${arrayVar} = obj.${name};`],
size: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
` const _data = ${arrayVar}[_i];`,
` const _len = _data.length;`,
` size += ${tagLength};`,
varintSize('_len', ' '),
` size += _len;`,
` }`,
` }`,
],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
` const _data = ${arrayVar}[_i];`,
writeTag(fieldNumber, 2, ' '),
` const _len = _data.length;`,
writeVarint('_len', ' '),
` buf.set(_data, offset);`,
` offset += _len;`,
` }`,
` }`,
],
};
}
if (typeName === 'bool') {
return {
declare: [` const ${arrayVar} = obj.${name};`],
size: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 1};`,
],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
writeTag(fieldNumber, 0, ' '),
` buf[offset++] = ${arrayVar}[_i] ? 1 : 0;`,
` }`,
` }`,
],
};
}
if (isVarint64(typeName)) {
const bigintExpr = bigintVarintExpr(typeName, `${arrayVar}[_i]`);
return {
declare: [` const ${arrayVar} = obj.${name};`],
size: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
` const _val = ${bigintExpr};`,
` size += ${tagLength};`,
` size += __varint64Size(_val);`,
` }`,
` }`,
],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
` const _val = ${bigintExpr};`,
writeTag(fieldNumber, 0, ' '),
` offset = __writeVarint64(buf, offset, _val);`,
` }`,
` }`,
],
};
}
if (typeName === 'sint_32') {
return {
declare: [` const ${arrayVar} = obj.${name};`],
size: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
` const _val = ((${arrayVar}[_i] << 1) ^ (${arrayVar}[_i] >> 31)) >>> 0;`,
` size += ${tagLength};`,
varintSize('_val', ' '),
` }`,
` }`,
],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
writeTag(fieldNumber, 0, ' '),
writeVarint(`((${arrayVar}[_i] << 1) ^ (${arrayVar}[_i] >> 31)) >>> 0`, ' '),
` }`,
` }`,
],
};
}
if (wireType === WireType.Varint) {
return {
declare: [` const ${arrayVar} = obj.${name};`],
size: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
` const _val = ${arrayVar}[_i] >>> 0;`,
` size += ${tagLength};`,
varintSize('_val', ' '),
` }`,
` }`,
],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
writeTag(fieldNumber, 0, ' '),
writeVarint(`${arrayVar}[_i] >>> 0`, ' '),
` }`,
` }`,
],
};
}
if (typeName === 'float') {
return {
declare: [` const ${arrayVar} = obj.${name};`],
size: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 4};`,
],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
writeTag(fieldNumber, 5, ' '),
` offset = __writeFloat32(buf, offset, ${arrayVar}[_i]);`,
` }`,
` }`,
],
};
}
if (wireType === WireType.Bit32) {
return {
declare: [` const ${arrayVar} = obj.${name};`],
size: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 4};`,
],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
writeTag(fieldNumber, 5, ' '),
` const _val = ${arrayVar}[_i];`,
` buf[offset++] = _val & 0xff;`,
` buf[offset++] = (_val >> 8) & 0xff;`,
` buf[offset++] = (_val >> 16) & 0xff;`,
` buf[offset++] = (_val >> 24) & 0xff;`,
` }`,
` }`,
],
};
}
if (typeName === 'double') {
return {
declare: [` const ${arrayVar} = obj.${name};`],
size: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`,
],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
writeTag(fieldNumber, 1, ' '),
` offset = __writeFloat64(buf, offset, ${arrayVar}[_i]);`,
` }`,
` }`,
],
};
}
if (isFixed64BigInt(typeName)) {
return {
declare: [` const ${arrayVar} = obj.${name};`],
size: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`,
],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
writeTag(fieldNumber, 1, ' '),
` offset = __writeFixed64(buf, offset, ${arrayVar}[_i]);`,
` }`,
` }`,
],
};
}
if (wireType === WireType.Bit64) {
return {
declare: [` const ${arrayVar} = obj.${name};`],
size: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`,
],
write: [
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
writeTag(fieldNumber, 1, ' '),
` const _val = ${arrayVar}[_i];`,
` buf[offset++] = _val & 0xff;`,
` buf[offset++] = (_val >> 8) & 0xff;`,
` buf[offset++] = (_val >> 16) & 0xff;`,
` buf[offset++] = (_val >> 24) & 0xff;`,
` buf[offset++] = 0;`,
` buf[offset++] = 0;`,
` buf[offset++] = 0;`,
` buf[offset++] = 0;`,
` }`,
` }`,
],
};
}
return { declare: [], size: [], write: [] };
' return buf;',
'}',
].join('\n');
}
+141
View File
@@ -0,0 +1,141 @@
import { WireType, type ProtobufField } from './model.js';
import { computeTagBytes, varintSize, writeTag, writeVarint } from './write.js';
export interface FieldBlock {
declare: string[];
size: string[];
write: string[];
}
export function fieldBlock(field: ProtobufField, index: number, shared: boolean): FieldBlock {
const { fieldNumber, wireType, typeName, isRepeated, isMessage } = field;
const variable = `_f${index}`;
const item = isRepeated ? `${variable}[_i]` : variable;
const cached = `_c${index}`;
const slot = isRepeated ? `${cached}[_i]` : cached;
const indent = isRepeated ? ' ' : ' ';
const tag = computeTagBytes(fieldNumber, wireType).length;
const condition = isRepeated
? `${variable} != null && ${variable}.length > 0`
: presence(field, variable);
const start = [` if (${condition}) {`];
const loop = isRepeated ? [` for (let _i = 0; _i < ${variable}.length; _i++) {`] : [];
const end = [...(isRepeated ? [' }'] : []), ' }'];
const declare = [` const ${variable} = obj[${JSON.stringify(field.name)}];`];
const setup: string[] = [];
const size: string[] = [];
const write: string[] = [writeTag(fieldNumber, wireType, indent)];
const emit = (lines: string[]) => lines.map((line) => indent + line);
if (wireType === WireType.LengthDelim) {
if (isMessage) {
size.push(
...emit([
'const _slot = sizes.length;',
'sizes.push(0);',
`const _len = __size_${typeName}(${item}, sizes);`,
'sizes[_slot] = _len;',
]),
);
write.push(...emit(['const _len = sizes[sizes[0]++];']));
} else if (typeName === 'string') {
if (shared) {
size.push(...emit([`const _len = __utf8Len(${item});`, 'sizes.push(_len);']));
write.push(...emit(['const _len = sizes[sizes[0]++];']));
} else {
declare.push(` let ${cached};`);
if (isRepeated) {
setup.push(` ${cached} = new Array(${variable}.length);`);
}
size.push(...emit([`const _len = __utf8Len(${item});`, `${slot} = _len;`]));
write.push(...emit([`const _len = ${slot};`]));
}
} else {
size.push(...emit([`const _len = ${item}.length;`]));
write.push(...emit([`const _len = ${item}.length;`]));
}
size.push(...emit([`size += ${tag} + _len;`]), varintSize('_len', indent));
write.push(
writeVarint('_len', indent),
...emit(
isMessage
? [`offset = __write_${typeName}(${item}, buf, offset, sizes);`]
: typeName === 'string'
? [
`offset = _len >= 128 ? __utf8WriteLong(buf, offset, ${item}) : _len === ${item}.length ? __asciiWrite(buf, offset, ${item}) : __utf8Write(buf, offset, ${item});`,
]
: [`buf.set(${item}, offset);`, 'offset += _len;'],
),
);
} else if (typeName === 'bool') {
size.push(...emit([`size += ${tag + 1};`]));
write.push(...emit([`buf[offset++] = ${item} ? 1 : 0;`]));
} else if (wireType === WireType.Varint) {
if (typeName.endsWith('_64')) {
const normalized =
typeName === 'sint_64'
? `__zigZagEncode64(${item})`
: `BigInt.asUintN(64, ${item})`;
size.push(...emit([`size += ${tag} + __varint64Size(${normalized});`]));
write.push(...emit([`offset = __writeVarint64(buf, offset, ${normalized});`]));
} else {
// Preserve QQ's established five-byte negative int32 encoding. Decoders
// also accept the canonical sign-extended ten-byte representation.
const normalized =
typeName === 'sint_32'
? `((${item} << 1) ^ (${item} >> 31)) >>> 0`
: `${item} >>> 0`;
size.push(
...emit([`const _val = ${normalized};`, `size += ${tag};`]),
varintSize('_val', indent),
);
write.push(writeVarint(normalized, indent));
}
} else {
size.push(...emit([`size += ${tag + (wireType === WireType.Bit32 ? 4 : 8)};`]));
if (typeName === 'float' || typeName === 'double') {
write.push(
...emit([
`offset = __writeFloat${typeName === 'float' ? 32 : 64}(buf, offset, ${item});`,
]),
);
} else if (wireType === WireType.Bit64) {
write.push(...emit([`offset = __writeFixed64(buf, offset, ${item});`]));
} else {
write.push(
...emit([
`const _val = ${item};`,
...[0, 8, 16, 24].map((shift) => `buf[offset++] = (_val >>> ${shift}) & 0xff;`),
]),
);
}
}
return {
declare,
size: [...start, ...setup, ...loop, ...size, ...end],
write: [...start, ...loop, ...write, ...end],
};
}
function presence(field: ProtobufField, value: string): string {
// TypeScript optionality controls missing decoded values, not wire presence.
if (field.explicitPresence || field.isMessage) {
return `${value} != null`;
}
if (field.typeName === 'bool') {
return `${value} === true`;
}
if (field.typeName === 'bytes') {
return `${value} != null && ${value}.length > 0`;
}
const empty = field.typeName === 'string' ? '""' : field.typeName.endsWith('_64') ? '0n' : '0';
return `${value} != null && ${value} !== ${empty}`;
}
+84 -236
View File
@@ -1,251 +1,99 @@
import type { MessageRegistry } from '../ast/types.js';
import { generateEncoder } from './encoder.js';
import { WireType, type MessageRegistry, type ProtobufMessage } from './model.js';
import { generateEncoder, generateEncoderHelpers } from './encoder.js';
import { generateDecoder } from './decoder.js';
import { collectDependencyClosure } from '../codegen/dependencies.js';
/** Shared preamble: UTF-8 string helpers plus TextDecoder for decode. */
const CODEGEN_PREAMBLE = `const __td = new TextDecoder();
const __scratch = new DataView(new ArrayBuffer(8));
function __utf8Len(value) {
let length = 0;
for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i);
if (code < 0x80) {
length++;
continue;
}
if (code < 0x800) {
length += 2;
continue;
}
if ((code & 0xfc00) === 0xd800) {
if (i + 1 < value.length) {
const next = value.charCodeAt(i + 1);
if ((next & 0xfc00) === 0xdc00) {
length += 4;
i++;
continue;
}
}
length += 3;
continue;
}
if ((code & 0xfc00) === 0xdc00) {
length += 3;
continue;
}
length += 3;
}
return length;
}
function __utf8Write(buf, offset, value) {
for (let i = 0; i < value.length; i++) {
let code = value.charCodeAt(i);
if (code < 0x80) {
buf[offset++] = code;
continue;
}
if (code < 0x800) {
buf[offset++] = 0xc0 | (code >> 6);
buf[offset++] = 0x80 | (code & 0x3f);
continue;
}
if ((code & 0xfc00) === 0xd800) {
if (i + 1 < value.length) {
const next = value.charCodeAt(i + 1);
if ((next & 0xfc00) === 0xdc00) {
const point = ((code - 0xd800) << 10) + (next - 0xdc00) + 0x10000;
buf[offset++] = 0xf0 | (point >> 18);
buf[offset++] = 0x80 | ((point >> 12) & 0x3f);
buf[offset++] = 0x80 | ((point >> 6) & 0x3f);
buf[offset++] = 0x80 | (point & 0x3f);
i++;
continue;
}
}
code = 0xfffd;
} else if ((code & 0xfc00) === 0xdc00) {
code = 0xfffd;
}
buf[offset++] = 0xe0 | (code >> 12);
buf[offset++] = 0x80 | ((code >> 6) & 0x3f);
buf[offset++] = 0x80 | (code & 0x3f);
}
return offset;
}
function __varint64Size(value) {
let size = 1;
while (value > 0x7fn) {
value >>= 7n;
size++;
}
return size;
}
function __writeVarint64(buf, offset, value) {
while (value > 0x7fn) {
buf[offset++] = Number((value & 0x7fn) | 0x80n);
value >>= 7n;
}
buf[offset++] = Number(value);
return offset;
}
function __zigZagEncode64(value) {
value = BigInt.asIntN(64, value);
return BigInt.asUintN(64, (value << 1n) ^ (value >> 63n));
}
function __zigZagDecode64(value) {
return BigInt.asIntN(64, (value >> 1n) ^ -(value & 1n));
}
function __readVarint32(data, offset, end) {
let value = 0;
for (let i = 0; i < 5; i++) {
if (offset >= end) throw new Error('protobuf truncated uint32 varint');
const byte = data[offset++];
if (i === 4 && (byte & 0xf0) !== 0) throw new Error('protobuf uint32 varint overflow');
value += (byte & 0x7f) * (2 ** (i * 7));
if ((byte & 0x80) === 0) return [value >>> 0, offset];
}
throw new Error('protobuf uint32 varint overflow');
}
function __readVarint64(data, offset, end) {
let value = 0n;
for (let i = 0; i < 10; i++) {
if (offset >= end) throw new Error('protobuf truncated uint64 varint');
const byte = data[offset++];
if (i === 9 && byte > 1) throw new Error('protobuf uint64 varint overflow');
value |= BigInt(byte & 0x7f) << BigInt(i * 7);
if ((byte & 0x80) === 0) return [value, offset];
}
throw new Error('protobuf uint64 varint overflow');
}
function __readVarint32Value(data, offset, end) {
const [value, next] = __readVarint64(data, offset, end);
// QQ-compatible protobuf runtimes consume a complete, well-formed uint32
// value varint and retain its low 32 bits. Keep tags and lengths on
// __readVarint32 so malformed framing still fails before it affects bounds.
return [Number(BigInt.asUintN(32, value)), next];
}
function __skipVarint(data, offset, end) {
for (let i = 0; i < 10; i++) {
if (offset >= end) throw new Error('protobuf truncated varint');
const byte = data[offset++];
if (i === 9 && byte > 1) throw new Error('protobuf varint overflow');
if ((byte & 0x80) === 0) return offset;
}
throw new Error('protobuf varint overflow');
}
function __checkedEnd(offset, length, end) {
if (length > end - offset) throw new Error('protobuf length-delimited field exceeds parent bounds');
return offset + length;
}
function __skipUnknownField(data, offset, end, wireType, fieldNumber, depth = 0) {
if (depth > 64) throw new Error('protobuf group nesting exceeds 64');
if (wireType === 0) return __skipVarint(data, offset, end);
if (wireType === 1) {
if (end - offset < 8) throw new Error('protobuf truncated fixed64 field');
return offset + 8;
}
if (wireType === 2) {
const [length, next] = __readVarint32(data, offset, end);
return __checkedEnd(next, length, end);
}
if (wireType === 3) {
while (offset < end) {
const [tag, next] = __readVarint32(data, offset, end);
offset = next;
const nestedField = tag >>> 3;
const nestedWire = tag & 0x7;
if (nestedField === 0) throw new Error('protobuf field number 0 is invalid');
if (nestedWire === 4) {
if (nestedField !== fieldNumber) throw new Error('protobuf mismatched end-group tag');
return offset;
}
offset = __skipUnknownField(data, offset, end, nestedWire, nestedField, depth + 1);
}
throw new Error('protobuf unterminated group');
}
if (wireType === 4) throw new Error('protobuf unexpected end-group tag');
if (wireType === 5) {
if (end - offset < 4) throw new Error('protobuf truncated fixed32 field');
return offset + 4;
}
throw new Error('protobuf invalid wire type ' + wireType);
}
function __writeFloat32(buf, offset, value) {
__scratch.setFloat32(0, value, true);
buf[offset++] = __scratch.getUint8(0);
buf[offset++] = __scratch.getUint8(1);
buf[offset++] = __scratch.getUint8(2);
buf[offset++] = __scratch.getUint8(3);
return offset;
}
function __readFloat32(data, offset) {
__scratch.setUint8(0, data[offset]);
__scratch.setUint8(1, data[offset + 1]);
__scratch.setUint8(2, data[offset + 2]);
__scratch.setUint8(3, data[offset + 3]);
return __scratch.getFloat32(0, true);
}
function __writeFloat64(buf, offset, value) {
__scratch.setFloat64(0, value, true);
buf[offset++] = __scratch.getUint8(0);
buf[offset++] = __scratch.getUint8(1);
buf[offset++] = __scratch.getUint8(2);
buf[offset++] = __scratch.getUint8(3);
buf[offset++] = __scratch.getUint8(4);
buf[offset++] = __scratch.getUint8(5);
buf[offset++] = __scratch.getUint8(6);
buf[offset++] = __scratch.getUint8(7);
return offset;
}
function __readFloat64(data, offset) {
__scratch.setUint8(0, data[offset]);
__scratch.setUint8(1, data[offset + 1]);
__scratch.setUint8(2, data[offset + 2]);
__scratch.setUint8(3, data[offset + 3]);
__scratch.setUint8(4, data[offset + 4]);
__scratch.setUint8(5, data[offset + 5]);
__scratch.setUint8(6, data[offset + 6]);
__scratch.setUint8(7, data[offset + 7]);
return __scratch.getFloat64(0, true);
}
function __writeFixed64(buf, offset, value) {
value = BigInt.asUintN(64, value);
buf[offset++] = Number(value & 0xffn);
buf[offset++] = Number((value >> 8n) & 0xffn);
buf[offset++] = Number((value >> 16n) & 0xffn);
buf[offset++] = Number((value >> 24n) & 0xffn);
buf[offset++] = Number((value >> 32n) & 0xffn);
buf[offset++] = Number((value >> 40n) & 0xffn);
buf[offset++] = Number((value >> 48n) & 0xffn);
buf[offset++] = Number((value >> 56n) & 0xffn);
return offset;
}
function __readFixed64(data, offset) {
return BigInt(data[offset])
| (BigInt(data[offset + 1]) << 8n)
| (BigInt(data[offset + 2]) << 16n)
| (BigInt(data[offset + 3]) << 24n)
| (BigInt(data[offset + 4]) << 32n)
| (BigInt(data[offset + 5]) << 40n)
| (BigInt(data[offset + 6]) << 48n)
| (BigInt(data[offset + 7]) << 56n);
}`;
import { helpers } from './helpers.js';
/**
* Generate fully self-contained encode/decode source code.
* No runtime imports needed — all wire-format logic is inlined.
*/
export function generateCode(registry: MessageRegistry): string {
export interface CodegenOptions {
encodeRoots?: Iterable<string>;
decodeRoots?: Iterable<string>;
}
export function generateCode(registry: MessageRegistry, options: CodegenOptions = {}): string {
if (registry.size === 0) {
return '';
}
const parts: string[] = [CODEGEN_PREAMBLE];
const encodeRoots = new Set(options.encodeRoots ?? registry.keys());
const decodeNames = collectDependencyClosure(registry, options.decodeRoots ?? registry.keys());
const nestedRoots = [...encodeRoots].filter((name) =>
registry.get(name)?.fields.some((field) => field.isMessage),
);
const encoderHelpers = collectDependencyClosure(registry, nestedRoots);
const bounds = new Map<string, number>();
for (const msg of registry.values()) {
parts.push(generateEncoder(msg, registry));
parts.push(generateDecoder(msg, registry));
function sizeBound(message: ProtobufMessage): number {
const cached = bounds.get(message.name);
if (cached !== undefined) {
return cached;
}
bounds.set(message.name, Infinity);
let size = 0;
for (const field of message.fields) {
if (field.isRepeated || (!field.isMessage && field.wireType === WireType.LengthDelim)) {
return Infinity;
}
// A scalar needs at most 5 tag bytes and 10 payload bytes.
size += 16;
if (field.isMessage) {
size += sizeBound(registry.get(field.typeName)!);
}
if (size > 64) {
return Infinity;
}
}
bounds.set(message.name, size);
return size;
}
return parts.join('\n');
const parts: string[] = [];
for (const msg of registry.values()) {
if (encodeRoots.has(msg.name)) {
parts.push(generateEncoder(msg, sizeBound(msg) > 64));
}
if (encoderHelpers.has(msg.name)) {
parts.push(generateEncoderHelpers(msg));
}
if (decodeNames.has(msg.name)) {
parts.push(generateDecoder(msg));
}
}
const body = parts.join('\n');
const selected = new Set<string>();
function include(text: string): void {
for (const match of text.matchAll(/\b__\w+/g)) {
const name = match[0];
if (selected.has(name) || !helpers.has(name)) {
continue;
}
selected.add(name);
include(helpers.get(name)!);
}
}
include(body);
return [...helpers]
.filter(([name]) => selected.has(name))
.map(([, text]) => text)
.concat(body)
.join('\n');
}
+98
View File
@@ -0,0 +1,98 @@
import { utf8 } from './utf8.js';
import { unknownFields } from './unknown.js';
import { buffers } from './buffer.js';
const CODEGEN_PREAMBLE = `${utf8}
${buffers}
${unknownFields}
const __scratch = new DataView(new ArrayBuffer(8));
function __varint64Size(value) {
if (value < 0x80n) return 1;
const hi = Number(value >> 32n);
const bits = hi ? 64 - Math.clz32(hi) : 32 - Math.clz32(Number(value));
return ((bits + 6) / 7) | 0;
}
function __writeVarint64(buf, offset, value) {
let lo = Number(value & 0xffffffffn) >>> 0;
let hi = Number(value >> 32n) >>> 0;
while (hi || lo > 0x7f) {
buf[offset++] = (lo & 0x7f) | 0x80;
lo = ((lo >>> 7) | (hi << 25)) >>> 0;
hi >>>= 7;
}
buf[offset++] = lo;
return offset;
}
function __zigZagEncode64(value) {
value = BigInt.asIntN(64, value);
return BigInt.asUintN(64, (value << 1n) ^ (value >> 63n));
}
function __zigZagDecode64(value) {
return BigInt.asIntN(64, (value >> 1n) ^ -(value & 1n));
}
function __writeFloat32(buf, offset, value) {
__scratch.setFloat32(0, value, true);
buf[offset++] = __scratch.getUint8(0);
buf[offset++] = __scratch.getUint8(1);
buf[offset++] = __scratch.getUint8(2);
buf[offset++] = __scratch.getUint8(3);
return offset;
}
function __readFloat32(data, offset) {
__scratch.setUint8(0, data[offset]);
__scratch.setUint8(1, data[offset + 1]);
__scratch.setUint8(2, data[offset + 2]);
__scratch.setUint8(3, data[offset + 3]);
return __scratch.getFloat32(0, true);
}
function __writeFloat64(buf, offset, value) {
__scratch.setFloat64(0, value, true);
buf[offset++] = __scratch.getUint8(0);
buf[offset++] = __scratch.getUint8(1);
buf[offset++] = __scratch.getUint8(2);
buf[offset++] = __scratch.getUint8(3);
buf[offset++] = __scratch.getUint8(4);
buf[offset++] = __scratch.getUint8(5);
buf[offset++] = __scratch.getUint8(6);
buf[offset++] = __scratch.getUint8(7);
return offset;
}
function __readFloat64(data, offset) {
__scratch.setUint8(0, data[offset]);
__scratch.setUint8(1, data[offset + 1]);
__scratch.setUint8(2, data[offset + 2]);
__scratch.setUint8(3, data[offset + 3]);
__scratch.setUint8(4, data[offset + 4]);
__scratch.setUint8(5, data[offset + 5]);
__scratch.setUint8(6, data[offset + 6]);
__scratch.setUint8(7, data[offset + 7]);
return __scratch.getFloat64(0, true);
}
function __writeFixed64(buf, offset, value) {
value = BigInt.asUintN(64, value);
const lo = Number(value & 0xffffffffn), hi = Number(value >> 32n);
buf[offset++] = lo;
buf[offset++] = lo >>> 8;
buf[offset++] = lo >>> 16;
buf[offset++] = lo >>> 24;
buf[offset++] = hi;
buf[offset++] = hi >>> 8;
buf[offset++] = hi >>> 16;
buf[offset++] = hi >>> 24;
return offset;
}
function __readFixed64(data, offset) {
const lo = (data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)) >>> 0;
const hi = (data[offset + 4] | (data[offset + 5] << 8) | (data[offset + 6] << 16) | (data[offset + 7] << 24)) >>> 0;
return BigInt(lo) | (BigInt(hi) << 32n);
}`;
export const helpers = new Map<string, string>();
const helperStarts = [...CODEGEN_PREAMBLE.matchAll(/^(?:function|const|let) (__\w+)/gm)];
for (let i = 0; i < helperStarts.length; i++) {
helpers.set(
helperStarts[i][1],
CODEGEN_PREAMBLE.slice(helperStarts[i].index, helperStarts[i + 1]?.index).trim(),
);
}
+42
View File
@@ -0,0 +1,42 @@
export enum WireType {
Varint = 0,
Bit64 = 1,
LengthDelim = 2,
Bit32 = 5,
}
export interface ProtobufField {
name: string;
fieldNumber: number;
typeName: string;
wireType: WireType;
isMessage: boolean;
isOptional: boolean;
isRepeated: boolean;
explicitPresence?: boolean;
}
export interface ProtobufMessage {
name: string;
fields: ProtobufField[];
}
export type MessageRegistry = Map<string, ProtobufMessage>;
export const PRIMITIVE_TYPE_MAP: Record<string, { wireType: WireType; defaultValue: string }> = {
uint_32: { wireType: WireType.Varint, defaultValue: '0' },
int_32: { wireType: WireType.Varint, defaultValue: '0' },
uint_64: { wireType: WireType.Varint, defaultValue: '0n' },
int_64: { wireType: WireType.Varint, defaultValue: '0n' },
sint_32: { wireType: WireType.Varint, defaultValue: '0' },
sint_64: { wireType: WireType.Varint, defaultValue: '0n' },
bool: { wireType: WireType.Varint, defaultValue: 'false' },
string: { wireType: WireType.LengthDelim, defaultValue: '""' },
bytes: { wireType: WireType.LengthDelim, defaultValue: 'new Uint8Array(0)' },
float: { wireType: WireType.Bit32, defaultValue: '0' },
double: { wireType: WireType.Bit64, defaultValue: '0' },
fixed_32: { wireType: WireType.Bit32, defaultValue: '0' },
fixed_64: { wireType: WireType.Bit64, defaultValue: '0n' },
sfixed_32: { wireType: WireType.Bit32, defaultValue: '0' },
sfixed_64: { wireType: WireType.Bit64, defaultValue: '0n' },
};
+60
View File
@@ -0,0 +1,60 @@
// Bound unknown fields and groups to the current message frame.
export const unknownFields = `
function __readVarint32(data, offset, end) {
let value = 0;
for (let i = 0; i < 5; i++) {
if (offset >= end) throw new Error('protobuf truncated uint32 varint');
const byte = data[offset++];
if (i === 4 && (byte & 0xf0) !== 0) throw new Error('protobuf uint32 varint overflow');
value += (byte & 0x7f) * (2 ** (i * 7));
if ((byte & 0x80) === 0) return [value >>> 0, offset];
}
throw new Error('protobuf uint32 varint overflow');
}
function __skipVarint(data, offset, end) {
for (let i = 0; i < 10; i++) {
if (offset >= end) throw new Error('protobuf truncated varint');
const byte = data[offset++];
if (i === 9 && byte > 1) throw new Error('protobuf varint overflow');
if ((byte & 0x80) === 0) return offset;
}
throw new Error('protobuf varint overflow');
}
function __checkedEnd(offset, length, end) {
if (length > end - offset) throw new Error('protobuf length-delimited field exceeds parent bounds');
return offset + length;
}
function __skipUnknownField(data, offset, end, wireType, fieldNumber, depth = 0) {
if (depth > 64) throw new Error('protobuf group nesting exceeds 64');
if (wireType === 0) return __skipVarint(data, offset, end);
if (wireType === 1) {
if (end - offset < 8) throw new Error('protobuf truncated fixed64 field');
return offset + 8;
}
if (wireType === 2) {
const [length, next] = __readVarint32(data, offset, end);
return __checkedEnd(next, length, end);
}
if (wireType === 3) {
while (offset < end) {
const [tag, next] = __readVarint32(data, offset, end);
offset = next;
const nestedField = tag >>> 3;
const nestedWire = tag & 0x7;
if (nestedField === 0) throw new Error('protobuf field number 0 is invalid');
if (nestedWire === 4) {
if (nestedField !== fieldNumber) throw new Error('protobuf mismatched end-group tag');
return offset;
}
offset = __skipUnknownField(data, offset, end, nestedWire, nestedField, depth + 1);
}
throw new Error('protobuf unterminated group');
}
if (wireType === 4) throw new Error('protobuf unexpected end-group tag');
if (wireType === 5) {
if (end - offset < 4) throw new Error('protobuf truncated fixed32 field');
return offset + 4;
}
throw new Error('protobuf invalid wire type ' + wireType);
}
`;
+159
View File
@@ -0,0 +1,159 @@
export const utf8 = `const __td = new TextDecoder();
const __te = new TextEncoder();
const __nonAscii = /[^\\x00-\\x7f]/;
let __utf8Scratch;
const __tdStrict = new TextDecoder('utf-8', { fatal: true });
function __utf8LenLong(value) {
const buffer = __utf8Scratch ??= new Uint8Array(4096);
let length = 0;
for (;;) {
const result = __te.encodeInto(value, buffer);
length += result.written;
if (result.read === value.length) return length;
value = value.slice(result.read);
}
}
function __utf8Len(value) {
if (value.length >= 32) return __utf8LenLong(value);
if (value.length >= 8 && value.charCodeAt(0) < 0x80 && !__nonAscii.test(value)) return value.length;
let length = 0;
for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i);
if (code < 0x80) {
length++;
continue;
}
if (code < 0x800) {
length += 2;
continue;
}
if ((code & 0xfc00) === 0xd800) {
if (i + 1 < value.length) {
const next = value.charCodeAt(i + 1);
if ((next & 0xfc00) === 0xdc00) {
length += 4;
i++;
continue;
}
}
length += 3;
continue;
}
if ((code & 0xfc00) === 0xdc00) {
length += 3;
continue;
}
length += 3;
}
return length;
}
function __utf8Write(buf, offset, value) {
for (let i = 0; i < value.length; i++) {
let code = value.charCodeAt(i);
if (code < 0x80) {
buf[offset++] = code;
continue;
}
if (code < 0x800) {
buf[offset++] = 0xc0 | (code >> 6);
buf[offset++] = 0x80 | (code & 0x3f);
continue;
}
if ((code & 0xfc00) === 0xd800) {
if (i + 1 < value.length) {
const next = value.charCodeAt(i + 1);
if ((next & 0xfc00) === 0xdc00) {
const point = ((code - 0xd800) << 10) + (next - 0xdc00) + 0x10000;
buf[offset++] = 0xf0 | (point >> 18);
buf[offset++] = 0x80 | ((point >> 12) & 0x3f);
buf[offset++] = 0x80 | ((point >> 6) & 0x3f);
buf[offset++] = 0x80 | (point & 0x3f);
i++;
continue;
}
}
code = 0xfffd;
} else if ((code & 0xfc00) === 0xdc00) {
code = 0xfffd;
}
buf[offset++] = 0xe0 | (code >> 12);
buf[offset++] = 0x80 | ((code >> 6) & 0x3f);
buf[offset++] = 0x80 | (code & 0x3f);
}
return offset;
}
function __utf8WriteLong(buf, offset, value) {
return offset + __te.encodeInto(value, buf.subarray(offset)).written;
}
function __asciiWrite(buf, offset, value) {
let i = 0;
for (; i + 7 < value.length; i += 8) {
buf[offset++] = value.charCodeAt(i);
buf[offset++] = value.charCodeAt(i + 1);
buf[offset++] = value.charCodeAt(i + 2);
buf[offset++] = value.charCodeAt(i + 3);
buf[offset++] = value.charCodeAt(i + 4);
buf[offset++] = value.charCodeAt(i + 5);
buf[offset++] = value.charCodeAt(i + 6);
buf[offset++] = value.charCodeAt(i + 7);
}
for (; i < value.length; i++) buf[offset++] = value.charCodeAt(i);
return offset;
}
function __utf8ReadLong(data, start, end) {
const bytes = data.subarray(start, end);
if (end - start < 128) return __td.decode(bytes);
try {
return __tdStrict.decode(bytes);
} catch {
return __td.decode(bytes);
}
}
function __utf8Read(data, start, end) {
let value = '', offset = start;
while (offset + 7 < end) {
const a = data[offset], b = data[offset + 1], c = data[offset + 2], d = data[offset + 3];
const e = data[offset + 4], f = data[offset + 5], g = data[offset + 6], h = data[offset + 7];
if ((a | b | c | d | e | f | g | h) & 0x80) break;
value += String.fromCharCode(a, b, c, d, e, f, g, h);
offset += 8;
}
if (offset + 3 < end) {
const a = data[offset], b = data[offset + 1], c = data[offset + 2], d = data[offset + 3];
if (!((a | b | c | d) & 0x80)) {
value += String.fromCharCode(a, b, c, d);
offset += 4;
}
}
while (offset < end) {
const a = data[offset++];
if (a < 0x80) {
value += String.fromCharCode(a);
} else if (a >= 0xc2 && a < 0xe0 && offset < end) {
const b = data[offset++];
if ((b & 0xc0) !== 0x80) return __td.decode(data.subarray(start, end));
value += String.fromCharCode(((a & 0x1f) << 6) | (b & 0x3f));
} else if (a >= 0xe0 && a < 0xf0 && offset + 1 < end) {
const b = data[offset++], c = data[offset++];
if ((b & 0xc0) !== 0x80 || (c & 0xc0) !== 0x80 ||
(a === 0xe0 && b < 0xa0) || (a === 0xed && b >= 0xa0)) {
return __td.decode(data.subarray(start, end));
}
const code = ((a & 0x0f) << 12) | ((b & 0x3f) << 6) | (c & 0x3f);
// Match TextDecoder's handling of a leading BOM.
if (code !== 0xfeff || offset !== start + 3) value += String.fromCharCode(code);
} else if (a >= 0xf0 && a < 0xf5 && offset + 2 < end) {
const b = data[offset++], c = data[offset++], d = data[offset++];
if ((b & 0xc0) !== 0x80 || (c & 0xc0) !== 0x80 || (d & 0xc0) !== 0x80 ||
(a === 0xf0 && b < 0x90) || (a === 0xf4 && b >= 0x90)) {
return __td.decode(data.subarray(start, end));
}
const code = (((a & 7) << 18) | ((b & 0x3f) << 12) | ((c & 0x3f) << 6) | (d & 0x3f)) - 0x10000;
value += String.fromCharCode(0xd800 | (code >>> 10), 0xdc00 | (code & 0x3ff));
} else {
return __td.decode(data.subarray(start, end));
}
}
return value;
}
`;
+56
View File
@@ -0,0 +1,56 @@
export function computeTagBytes(fieldNumber: number, wireType: number): number[] {
let value = ((fieldNumber << 3) | wireType) >>> 0;
const bytes: number[] = [];
while (value > 0x7f) {
bytes.push((value & 0x7f) | 0x80);
value >>>= 7;
}
bytes.push(value & 0x7f);
return bytes;
}
export function writeTag(fieldNumber: number, wireType: number, ind: string): string {
return computeTagBytes(fieldNumber, wireType)
.map((byte) => `${ind}buf[offset++] = ${byte};`)
.join('\n');
}
export function varintSize(varName: string, ind: string, signed = false): string {
const negativeSize = signed ? `${varName} < 0 ? 10 : ` : '';
return `${ind}size += ${negativeSize}${varName} < 0x80 ? 1 : ${varName} < 0x4000 ? 2 : ${varName} < 0x200000 ? 3 : ${varName} < 0x10000000 ? 4 : 5;`;
}
export function writeVarint(expr: string, ind: string, signed = false): string {
return [
`${ind}let _v = ${expr};`,
...(signed
? [
`${ind}if (_v < 0) {`,
`${ind} offset = __writeVarint64(buf, offset, BigInt.asUintN(64, BigInt(_v)));`,
]
: []),
`${ind}${signed ? '} else if' : 'if'} (_v < 0x80) {`,
`${ind} buf[offset++] = _v;`,
`${ind}} else if (_v < 0x4000) {`,
`${ind} buf[offset++] = (_v & 0x7f) | 0x80;`,
`${ind} buf[offset++] = _v >>> 7;`,
`${ind}} else if (_v < 0x200000) {`,
`${ind} buf[offset++] = (_v & 0x7f) | 0x80;`,
`${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`,
`${ind} buf[offset++] = _v >>> 14;`,
`${ind}} else if (_v < 0x10000000) {`,
`${ind} buf[offset++] = (_v & 0x7f) | 0x80;`,
`${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`,
`${ind} buf[offset++] = ((_v >>> 14) & 0x7f) | 0x80;`,
`${ind} buf[offset++] = _v >>> 21;`,
`${ind}} else {`,
`${ind} buf[offset++] = (_v & 0x7f) | 0x80;`,
`${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`,
`${ind} buf[offset++] = ((_v >>> 14) & 0x7f) | 0x80;`,
`${ind} buf[offset++] = ((_v >>> 21) & 0x7f) | 0x80;`,
`${ind} buf[offset++] = _v >>> 28;`,
`${ind}}`,
].join('\n');
}
+559
View File
@@ -0,0 +1,559 @@
import { unique } from './edits.js';
import { Callbacks, mentionsGeneric } from './callbacks.js';
import ts from 'typescript';
import { packageName } from '../package.js';
import { SourceContext, fail, runtimeImportName } from '../source/context.js';
import { SchemaResolver } from '../schema/resolver.js';
import type { TypeEnvironment, TypeValue } from '../schema/types.js';
import {
callable,
constructorOf,
type Owner,
type Plan,
type Requirement,
type Site,
} from './model.js';
import { CallTargets } from './targets.js';
export class CallAnalysis {
readonly plans = new Map<Owner, Plan>();
readonly sites = new Map<ts.SourceFile, Site[]>();
readonly targets: CallTargets;
readonly callbacks = new Callbacks(this);
private readonly runtimePlans = new Map<string, Plan>();
constructor(
readonly context: SourceContext,
readonly resolver: SchemaResolver,
) {
this.targets = new CallTargets(context, resolver, this);
}
runtimePlan(fn: Requirement['fn']): Plan {
let plan = this.runtimePlans.get(fn);
if (!plan) {
const source = ts.createSourceFile(
`${fn}.internal.ts`,
`function ${fn}<T>(value: T) {}`,
ts.ScriptTarget.Latest,
true,
);
plan = this.plan(source.statements[0] as ts.FunctionDeclaration);
plan.runtime = fn;
const type = plan.env.get('T')!;
const requirement = { key: `${fn}:${type.key}`, fn, type, node: plan.node };
plan.requirements.set(requirement.key, requirement);
this.runtimePlans.set(fn, plan);
}
return plan;
}
scan(source: ts.SourceFile): void {
if (this.sites.has(source)) {
return;
}
const sites: Site[] = [];
this.sites.set(source, sites);
if (source.isDeclarationFile) {
return;
}
for (const statement of source.statements) {
if (
(!ts.isImportDeclaration(statement) && !ts.isExportDeclaration(statement)) ||
!statement.moduleSpecifier ||
!ts.isStringLiteral(statement.moduleSpecifier)
) {
continue;
}
const imported = this.context.module(statement.moduleSpecifier.text, source);
if (
imported &&
!imported.isDeclarationFile &&
!imported.fileName.includes('/node_modules/')
) {
this.scan(imported);
}
}
let env: TypeEnvironment = new Map();
let owner: Plan | undefined;
const visit = (node: ts.Node): void => {
this.callbacks.record(node);
if (
ts.isTypeNode(node) ||
ts.isInterfaceDeclaration(node) ||
ts.isImportDeclaration(node) ||
ts.isExportDeclaration(node)
) {
return;
}
const outerEnv = env;
const outerOwner = owner;
if (ts.isClassDeclaration(node)) {
this.plan(node);
}
if ((callable(node) || ts.isClassDeclaration(node)) && node.typeParameters?.length) {
owner = this.plan(node);
env = owner.env;
}
if (ts.isCallExpression(node) || ts.isNewExpression(node)) {
let fn = ts.isCallExpression(node)
? this.protobufFunction(node.expression, source)
: undefined;
const target = fn ? undefined : this.targets.target(node.expression, source, env);
if (!fn && ts.isCallExpression(node) && target) {
fn = this.plan(target.node).runtime;
}
if (fn) {
const typeNode =
node.typeArguments?.[0] ??
(fn === 'protobuf_encode' && node.arguments?.[0]
? this.targets.infer(node.arguments[0], source)
: undefined);
if (!typeNode) {
fail(
node,
'Cannot infer protobuf schema; supply an explicit type argument.',
);
}
const type = this.resolver.type(typeNode, typeNode.getSourceFile(), env);
const direct: Requirement = { key: `${fn}:${type.key}`, fn, type, node };
if (type.dynamic && owner) {
owner.requirements.set(direct.key, direct);
}
sites.push({ node, owner, direct });
} else {
if (target) {
const plan = this.plan(target.node);
sites.push({
node,
owner,
target: plan,
bindings: target.bindings,
typeArgs: node.typeArguments,
env,
});
this.scan(target.node.getSourceFile());
}
}
}
ts.forEachChild(node, visit);
env = outerEnv;
owner = outerOwner;
};
visit(source);
}
propagate(): void {
const consumers = new Map<
Plan,
{ owner?: Plan; bindings: () => Map<string, TypeValue> }[]
>();
const connect = (
target: Plan,
owner: Plan | undefined,
bindings: () => Map<string, TypeValue>,
) => {
const list = consumers.get(target) ?? [];
list.push({ owner, bindings });
consumers.set(target, list);
};
for (const sites of this.sites.values()) {
for (const site of sites) {
if (site.target) {
connect(site.target, site.owner, () => this.bindings(site));
}
}
}
for (const adapter of this.callbacks.connections()) {
connect(adapter.target, adapter.owner, adapter.bindings);
}
for (const plan of this.plans.values()) {
if (plan.base) {
connect(plan.base.plan, plan, () => plan.base!.bindings);
}
}
const queue = [...this.plans.values()].flatMap((plan) =>
[...plan.requirements.values()].map((requirement) => ({ plan, requirement })),
);
for (let index = 0; index < queue.length; index++) {
const { plan, requirement } = queue[index];
for (const consumer of consumers.get(plan) ?? []) {
const instantiated = this.instantiate(requirement, consumer.bindings());
const owner = consumer.owner;
if (
!instantiated.type.dynamic ||
!owner ||
owner.requirements.has(instantiated.key)
) {
continue;
}
if (owner.requirements.size >= 128) {
fail(owner.node, 'Generic codec expansion does not converge.');
}
owner.requirements.set(instantiated.key, instantiated);
queue.push({ plan: owner, requirement: instantiated });
}
}
}
instantiate(req: Requirement, bindings: Map<string, TypeValue>): Requirement {
const type = this.resolver.substitute(req.type, bindings);
return { ...req, type, key: `${req.fn}:${type.key}` };
}
bindings(site: Site, partial = false): Map<string, TypeValue> {
if (!site.bound) {
const plan = site.target!;
// Ordinary calls cannot contribute generic codec bindings. Resolving
// their parameter types would treat unrelated application data as schemas.
if (plan.env.size === 0 && !plan.base) {
site.bound = true;
return site.bindings!;
}
if (!site.typeArgs?.length) {
this.parameters(plan.node)?.forEach((param, index) => {
const argument = site.node.arguments?.[index];
const actual =
argument && this.targets.infer(argument, site.node.getSourceFile());
if (
param.type &&
actual &&
mentionsGeneric(param.type, this.environment(param)) &&
!this.targets.signature(param.type, plan.env)
) {
// Matching generic containers expose their arguments directly;
// unrelated members need not be expanded as protobuf schemas.
const pattern = param.type;
if (
ts.isTypeReferenceNode(pattern) &&
ts.isTypeReferenceNode(actual) &&
pattern.typeArguments?.length &&
pattern.typeArguments.length === actual.typeArguments?.length &&
this.context.typeName(pattern.typeName, pattern.getSourceFile())
?.node &&
this.context.typeName(pattern.typeName, pattern.getSourceFile())
?.node ===
this.context.typeName(actual.typeName, actual.getSourceFile())?.node
) {
pattern.typeArguments.forEach((type, i) =>
this.unify(
this.resolver.type(
type,
type.getSourceFile(),
this.environment(param),
),
partial
? this.resolver.lazy(
actual.typeArguments![i],
actual.getSourceFile(),
site.env!,
)
: this.resolver.type(
actual.typeArguments![i],
actual.getSourceFile(),
site.env,
),
site.bindings!,
site.node,
),
);
return;
}
this.unify(
this.resolver.type(
param.type,
param.getSourceFile(),
this.environment(param),
),
this.resolver.type(actual, actual.getSourceFile(), site.env),
site.bindings!,
site.node,
);
}
});
const bases: NonNullable<Plan['base']>[] = [];
for (let base = plan.base; base; base = base.plan.base) {
bases.push(base);
}
for (const base of bases.reverse()) {
for (const [key, pattern] of base.bindings) {
const actual = site.bindings!.get(key);
if (actual) {
this.unify(pattern, actual, site.bindings!, site.node);
}
}
}
}
const local = this.targets.environment({ node: plan.node, bindings: site.bindings! });
for (let i = 0; i < (plan.node.typeParameters?.length ?? 0); i++) {
const param = plan.node.typeParameters![i];
const key = plan.env.get(param.name.text)!.key;
const arg = site.typeArgs?.[i];
const actual =
site.bindings!.get(key) ??
(arg
? partial
? this.resolver.lazy(arg, arg.getSourceFile(), site.env!)
: this.resolver.type(arg, arg.getSourceFile(), site.env!)
: param.default
? this.resolver.type(param.default, param.getSourceFile(), local)
: undefined);
if (!actual && partial) {
continue;
}
if (!actual) {
fail(
site.node,
`Cannot infer ${param.name.text}; supply an explicit generic argument.`,
);
}
site.bindings!.set(key, actual);
local.set(param.name.text, actual);
}
site.bound = !partial;
}
return site.bindings!;
}
unify(
pattern: TypeValue,
actual: TypeValue,
bindings: Map<string, TypeValue>,
node: ts.Node,
seen = new Set<string>(),
): void {
const key = `${pattern.key}:${actual.key}`;
if (seen.has(key)) {
return;
}
seen.add(key);
if (pattern.kind === 'parameter') {
const previous = bindings.get(pattern.key);
if (previous && previous.key !== actual.key) {
fail(
node,
`Conflicting inference for ${pattern.name}; supply an explicit type argument.`,
);
}
bindings.set(pattern.key, actual);
} else if (
pattern.application &&
actual.application &&
pattern.application.declaration === actual.application.declaration
) {
pattern.application.arguments.forEach((type, index) =>
this.unify(type, actual.application!.arguments[index], bindings, node, seen),
);
} else if (pattern.fields && actual.fields) {
for (const [name, property] of pattern.fields) {
const field = actual.fields.get(name);
if (field) {
this.unify(property.type, field.type, bindings, node, seen);
}
}
} else if (
pattern.values &&
actual.values &&
pattern.values.length === actual.values.length
) {
pattern.values.forEach((type, index) =>
this.unify(type, actual.values![index], bindings, node, seen),
);
}
}
owner(node: ts.Node): Owner | undefined {
for (let parent = node.parent; parent; parent = parent.parent) {
if (
(callable(parent) || ts.isClassDeclaration(parent)) &&
parent.typeParameters?.length
) {
return parent;
}
}
return;
}
environment(node: ts.Node): TypeEnvironment {
const owners: Owner[] = [];
for (let parent: ts.Node | undefined = node; parent; parent = parent.parent) {
if (
(callable(parent) || ts.isClassDeclaration(parent)) &&
parent.typeParameters?.length
) {
owners.push(parent);
}
}
const env: TypeEnvironment = new Map();
for (const owner of owners.reverse()) {
for (const param of owner.typeParameters!) {
env.set(param.name.text, this.resolver.parameter(param.name.text, owner));
}
}
return env;
}
plan(node: Owner): Plan {
let plan = this.plans.get(node);
if (!plan) {
plan = { node, env: this.environment(node), requirements: new Map(), names: new Map() };
this.plans.set(node, plan);
if (ts.isClassDeclaration(node)) {
const heritage = node.heritageClauses?.find(
(clause) => clause.token === ts.SyntaxKind.ExtendsKeyword,
)?.types[0];
if (heritage) {
const target = this.targets.target(
heritage.expression,
node.getSourceFile(),
plan.env,
);
if (target && ts.isClassDeclaration(target.node)) {
const base = this.plan(target.node);
for (
let ancestor: Plan | undefined = base;
ancestor;
ancestor = ancestor.base?.plan
) {
if (ancestor === plan) {
fail(heritage, 'Circular class inheritance.');
}
}
const args = this.resolver.arguments(
target.node.typeParameters,
heritage.typeArguments,
node.getSourceFile(),
plan.env,
target.node,
);
const bindings = new Map<string, TypeValue>();
for (const [name, type] of args) {
bindings.set(base.env.get(name)!.key, type);
}
plan.base = { plan: base, bindings };
this.scan(target.node.getSourceFile());
}
}
}
}
return plan;
}
protobufFunction(
expression: ts.Expression,
source: ts.SourceFile,
): Requirement['fn'] | undefined {
let name: string | undefined;
if (ts.isIdentifier(expression)) {
const declaration = this.context.lookup(expression.text, expression, source);
name = declaration ? runtimeImportName(declaration.node) : undefined;
} else if (
ts.isPropertyAccessExpression(expression) &&
ts.isIdentifier(expression.expression)
) {
const declaration = this.context.lookup(expression.expression.text, expression, source);
if (
declaration &&
ts.isNamespaceImport(declaration.node) &&
(declaration.node.parent.parent.moduleSpecifier as ts.StringLiteral).text ===
packageName
) {
name = expression.name.text;
}
}
return name === 'protobuf_encode' || name === 'protobuf_decode' ? name : undefined;
}
parameters(node: Owner): readonly ts.ParameterDeclaration[] | undefined {
const parameters = ts.isClassDeclaration(node)
? (constructorOf(node)?.parameters ??
(this.plan(node).base ? this.parameters(this.plan(node).base!.plan.node) : undefined))
: node.parameters;
return parameters?.filter(
(param) => !ts.isIdentifier(param.name) || param.name.text !== 'this',
);
}
parameterName(plan: Plan, key: string): string {
let name = plan.names.get(key);
if (!name) {
name = unique(
plan.node.getSourceFile(),
`__pb_codec_${plan.node.pos}_${plan.names.size}`.replace(/-/g, '_'),
);
plan.names.set(key, name);
}
return name;
}
}
@@ -0,0 +1,169 @@
import ts from 'typescript';
import { fail } from '../source/context.js';
import type { TypeEnvironment } from '../schema/types.js';
import { memberType, type Signature } from './signatures.js';
import { callable } from './model.js';
import type { CallAnalysis } from './analysis.js';
interface Expected {
type: ts.TypeNode;
env: TypeEnvironment;
}
export class CallbackTypes {
constructor(private readonly graph: CallAnalysis) {}
context(
node: ts.Expression,
env: TypeEnvironment,
): { signature?: Signature; types?: ts.TypeNode[] } | undefined {
const expected = this.expected(node, env);
const signature = expected && this.graph.targets.signature(expected.type, expected.env);
if (signature) {
return { signature };
}
const parent = node.parent;
if (
ts.isCallExpression(parent) &&
parent.arguments[0] === node &&
ts.isPropertyAccessExpression(parent.expression) &&
['map', 'forEach', 'flatMap', 'filter', 'find', 'some', 'every'].includes(
parent.expression.name.text,
)
) {
const array = this.graph.targets.infer(
parent.expression.expression,
node.getSourceFile(),
);
const element = array && this.element(array);
if (element) {
return { types: [element] };
}
}
return;
}
private expected(node: ts.Node, env: TypeEnvironment): Expected | undefined {
const graph = this.graph;
let child = node;
if (
ts.isPropertyAccessExpression(child.parent) &&
child.parent.name.text === 'bind' &&
ts.isCallExpression(child.parent.parent)
) {
child = child.parent.parent;
}
while (
ts.isParenthesizedExpression(child.parent) ||
ts.isConditionalExpression(child.parent)
) {
child = child.parent;
}
const parent = child.parent;
if (
(ts.isVariableDeclaration(parent) ||
ts.isParameter(parent) ||
ts.isPropertyDeclaration(parent) ||
ts.isAsExpression(parent) ||
ts.isSatisfiesExpression(parent)) &&
parent.type
) {
return { type: parent.type, env };
}
if (
ts.isBinaryExpression(parent) &&
parent.right === child &&
parent.operatorToken.kind === ts.SyntaxKind.EqualsToken
) {
const type = graph.targets.infer(parent.left, node.getSourceFile());
if (type) {
return { type, env };
}
}
if (
(ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent)) &&
ts.isObjectLiteralExpression(parent.parent)
) {
const object = this.expected(parent.parent, env);
return (
object &&
memberType(
object.type,
parent.name.getText().replace(/^['"]|['"]$/g, ''),
object.env,
graph.context,
graph.resolver,
)
);
}
if (ts.isArrayLiteralExpression(parent)) {
const array = this.expected(parent, env);
const type = array && this.element(array.type);
return type && array ? { type, env: array.env } : undefined;
}
if (ts.isReturnStatement(parent) || (ts.isArrowFunction(parent) && parent.body === child)) {
for (let fn: ts.Node | undefined = parent; fn; fn = fn.parent) {
if (callable(fn)) {
return fn.type ? { type: fn.type, env } : undefined;
}
}
}
if (ts.isCallExpression(parent)) {
const index = parent.arguments.indexOf(child as ts.Expression);
const site = graph.sites
.get(node.getSourceFile())
?.find((site) => site.node === parent);
const parameter = site?.target && graph.parameters(site.target.node)?.[index];
if (site?.target && parameter?.type) {
const bindings = graph.bindings(site, true);
const local = new Map(
[...site.target.env].map(([name, value]) => [
name,
graph.resolver.substitute(value, bindings),
]),
);
const signature = graph.targets.signature(parameter.type, local);
if (
signature?.node.typeParameters?.length &&
(site.target.node.getSourceFile().isDeclarationFile ||
(ts.isFunctionDeclaration(site.target.node) && !site.target.node.body))
) {
fail(
node,
'Polymorphic callbacks require the receiving implementation to participate in the build.',
);
}
return { type: parameter.type, env: local };
}
}
return;
}
private element(type: ts.TypeNode): ts.TypeNode | undefined {
return ts.isArrayTypeNode(type)
? type.elementType
: ts.isTypeReferenceNode(type) &&
['Array', 'ReadonlyArray'].includes(type.typeName.getText())
? type.typeArguments?.[0]
: undefined;
}
}
+323
View File
@@ -0,0 +1,323 @@
import ts from 'typescript';
import { fail } from '../source/context.js';
import type { TypeEnvironment, TypeValue } from '../schema/types.js';
import type { CallAnalysis } from './analysis.js';
import { callable, type Plan, type Requirement, type Edit } from './model.js';
import { codecIndex, unique } from './edits.js';
import { CallbackTypes } from './callback-types.js';
interface Adapter {
node: ts.Expression;
target: Plan;
bindings: Map<string, TypeValue>;
owner?: Plan;
signature?: Plan;
}
export class Callbacks {
readonly adapters = new Map<ts.Expression, Adapter>();
private readonly candidates: ts.Expression[] = [];
private cursor = 0;
private readonly types: CallbackTypes;
constructor(private readonly graph: CallAnalysis) {
this.types = new CallbackTypes(graph);
}
record(node: ts.Node): void {
switch (node.kind) {
case ts.SyntaxKind.ExpressionWithTypeArguments:
if (!ts.isHeritageClause(node.parent)) {
this.candidates.push(node as ts.ExpressionWithTypeArguments);
}
break;
case ts.SyntaxKind.VariableDeclaration:
case ts.SyntaxKind.Parameter:
case ts.SyntaxKind.PropertyDeclaration:
case ts.SyntaxKind.PropertyAssignment:
this.candidate((node as ts.VariableDeclaration).initializer);
break;
case ts.SyntaxKind.CallExpression:
for (const argument of (node as ts.CallExpression).arguments) {
this.candidate(argument);
}
break;
case ts.SyntaxKind.ArrayLiteralExpression:
for (const element of (node as ts.ArrayLiteralExpression).elements) {
this.candidate(element);
}
break;
case ts.SyntaxKind.ShorthandPropertyAssignment:
this.candidate((node as ts.ShorthandPropertyAssignment).name);
break;
case ts.SyntaxKind.ReturnStatement:
case ts.SyntaxKind.ParenthesizedExpression:
case ts.SyntaxKind.AsExpression:
case ts.SyntaxKind.SatisfiesExpression:
this.candidate((node as ts.ReturnStatement).expression);
break;
case ts.SyntaxKind.ConditionalExpression: {
const expression = node as ts.ConditionalExpression;
this.candidate(expression.whenTrue);
this.candidate(expression.whenFalse);
break;
}
case ts.SyntaxKind.BinaryExpression: {
const expression = node as ts.BinaryExpression;
if (expression.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
this.candidate(expression.right);
}
break;
}
case ts.SyntaxKind.PropertyAccessExpression: {
const expression = node as ts.PropertyAccessExpression;
if (expression.name.text === 'bind') {
this.candidate(expression.expression);
}
}
}
}
private candidate(node: ts.Expression | undefined): void {
if (
node &&
(ts.isIdentifier(node) ||
ts.isPropertyAccessExpression(node) ||
ts.isElementAccessExpression(node) ||
callable(node))
) {
this.candidates.push(node);
}
}
collect(): void {
while (this.cursor < this.candidates.length) {
this.add(this.candidates[this.cursor++]);
}
}
private add(node: ts.Expression): void {
const graph = this.graph;
const env = graph.environment(node);
const explicit = ts.isExpressionWithTypeArguments(node) ? node : undefined;
const target = graph.targets.target(
explicit?.expression ?? node,
node.getSourceFile(),
env,
);
if (!target || ts.isClassDeclaration(target.node)) {
return;
}
const plan = graph.plan(target.node);
if (!plan.node.typeParameters?.length) {
return;
}
graph.scan(plan.node.getSourceFile());
const ownerNode = graph.owner(node);
const adapter: Adapter = {
node,
target: plan,
bindings: new Map(target.bindings),
owner: ownerNode ? graph.plan(ownerNode) : undefined,
};
if (explicit) {
const args = graph.resolver.arguments(
plan.node.typeParameters,
explicit.typeArguments,
node.getSourceFile(),
env,
plan.node,
);
for (const [name, type] of args) {
adapter.bindings.set(plan.env.get(name)!.key, type);
}
} else {
const context = this.types.context(node, env);
if (!context) {
return;
}
const signature = context.signature;
const local = new Map(signature?.env ?? env);
if (signature?.node.typeParameters?.length) {
adapter.signature = graph.plan(signature.node);
for (const param of signature.node.typeParameters) {
local.set(param.name.text, adapter.signature.env.get(param.name.text)!);
}
}
const parameters = graph.parameters(plan.node) ?? [];
const actual =
context.types ?? graph.parameters(signature!.node)!.map((param) => param.type);
parameters.forEach((param, index) => {
if (
param.type &&
actual[index] &&
plan.runtime !== 'protobuf_decode' &&
mentionsGeneric(param.type, plan.env)
) {
graph.unify(
graph.resolver.type(param.type, param.getSourceFile(), plan.env),
graph.resolver.type(actual[index]!, actual[index]!.getSourceFile(), local),
adapter.bindings,
node,
);
}
});
if (plan.runtime === 'protobuf_decode' && signature) {
adapter.bindings.set(
plan.env.get('T')!.key,
graph.resolver.type(
signature.node.type!,
signature.node.getSourceFile(),
local,
),
);
}
for (const parameter of plan.node.typeParameters ?? []) {
const key = plan.env.get(parameter.name.text)!.key;
if (!adapter.bindings.has(key) && parameter.default) {
adapter.bindings.set(
key,
graph.resolver.type(parameter.default, parameter.getSourceFile(), env),
);
}
}
}
this.adapters.set(node, adapter);
}
connections(): { target: Plan; owner?: Plan; bindings: () => Map<string, TypeValue> }[] {
return [...this.adapters.values()].map((adapter) => ({
target: adapter.target,
owner: adapter.signature ?? adapter.owner,
bindings: () => adapter.bindings,
}));
}
emit(
source: ts.SourceFile,
reference: (req: Requirement, owner?: Plan) => string,
edits: Edit[],
): void {
for (const adapter of this.adapters.values()) {
if (adapter.node.getSourceFile() !== source || !adapter.target.requirements.size) {
continue;
}
const { target, signature, node } = adapter;
if (target === signature) {
continue;
}
const requirements = [...target.requirements.values()].map((req) =>
this.graph.instantiate(req, adapter.bindings),
);
for (const req of requirements) {
if (
[...target.env.values()].some(
(type) => type.dynamic && req.type.key === type.key,
)
) {
fail(
node,
'Cannot infer callback schema; annotate its parameter type or supply type arguments.',
);
}
}
const codecs = requirements.map((req) => reference(req, signature ?? adapter.owner));
if (target.runtime && !signature) {
const text =
target.runtime === 'protobuf_decode'
? `(bytes => ${codecs[0]}(bytes))`
: codecs[0];
edits.push({ start: node.getStart(source), end: node.end, text });
continue;
}
const params = this.graph.parameters(target.node) ?? [];
const count = params.findIndex((param) => !!param.dotDotDotToken);
const arity = count < 0 ? params.length : count;
const signatureParams = signature && this.graph.parameters(signature.node)!;
const signatureRest =
signatureParams?.findIndex((param) => !!param.dotDotDotToken) ?? -1;
const incomingArity = signatureParams
? signatureRest < 0
? signatureParams.length
: signatureRest
: arity;
const prefix = unique(source, '__pb_callback');
const args = Array.from(
{ length: Math.max(arity, incomingArity) },
(_, index) => `${prefix}_${index}`,
);
const hidden = signature
? [...signature.requirements.keys()].map((key) =>
this.graph.parameterName(signature, key),
)
: [];
const incoming = args.map((name, index) =>
params[index]?.initializer ? `${name} = undefined` : name,
);
incoming.splice(incomingArity, 0, ...hidden.map((name) => `${name} = undefined`));
if (count >= 0) {
incoming.push(`...${prefix}_rest`);
}
const index = codecIndex(params);
const forwarded = [...args.slice(0, index), ...codecs, ...args.slice(index, arity)];
if (count >= 0) {
forwarded.push(...args.slice(arity), `...${prefix}_rest`);
}
const call = target.runtime
? `${codecs[0]}(${args[0]})`
: `${prefix}_fn.call(this, ${forwarded.join(', ')})`;
const property = ts.isShorthandPropertyAssignment(node.parent)
? node.getText(source) + ': '
: '';
edits.push({
start: node.getStart(source),
end: node.getStart(source),
text: `${property}((${prefix}_fn) => function(${incoming.join(', ')}) { return ${call}; })(`,
});
edits.push({ start: node.end, end: node.end, text: ')', order: -1 });
}
}
}
export function mentionsGeneric(node: ts.Node, env: TypeEnvironment): boolean {
if (ts.isIdentifier(node) && env.get(node.text)?.dynamic) {
return true;
}
return ts.forEachChild(node, (child) => mentionsGeneric(child, env)) ?? false;
}
+326
View File
@@ -0,0 +1,326 @@
import { codecIndex, insertArguments, insertParameters, unique } from './edits.js';
import ts from 'typescript';
import { SourceContext, fail } from '../source/context.js';
import { SchemaResolver } from '../schema/resolver.js';
import { generateCode } from '../codegen/generator.js';
import { constructorOf, type Plan, type Requirement, type Edit } from './model.js';
import { CallAnalysis } from './analysis.js';
import { validateSource } from './validate.js';
/** Generic calls receive generated codec functions, preserving the original body and closure. */
export class ProtobufCompiler {
readonly context = new SourceContext();
private resolver = new SchemaResolver(this.context);
private graph = new CallAnalysis(this.context, this.resolver);
private output = new Map<string, { source: string; code: string | null }>();
private entries = new Set<string>();
clear(): void {
this.reset();
this.entries.clear();
}
private reset(): void {
this.context.clear();
this.output.clear();
this.resolver = new SchemaResolver(this.context);
this.graph = new CallAnalysis(this.context, this.resolver);
}
prepare(files: Iterable<string>): void {
for (const file of files) {
this.entries.add(file);
}
try {
for (const file of this.entries) {
this.graph.scan(this.context.source(file));
}
this.graph.callbacks.collect();
this.graph.propagate();
} catch (error) {
this.reset();
throw error;
}
}
compile(code: string, file: string): string | null {
try {
return this.transform(code, file);
} catch (error) {
this.reset();
throw error;
}
}
private transform(code: string, file: string): string | null {
const cached = this.output.get(file);
if (cached?.source === code) {
return cached.code;
}
const revision = this.context.revision;
const source = this.context.source(file, code);
if (!this.graph.sites.size && this.entries.size) {
this.prepare(this.entries);
}
if (cached || this.context.revision !== revision) {
const entries = [...this.entries];
this.clear();
this.context.files.set(source.fileName, source);
this.prepare(entries);
}
this.graph.scan(source);
this.graph.callbacks.collect();
this.graph.propagate();
validateSource(this.graph, source);
const edits: Edit[] = [];
const encodeRoots = new Set<string>();
const decodeRoots = new Set<string>();
const reference = (requirement: Requirement, owner?: Plan, constructor = false): string => {
if (requirement.type.dynamic) {
if (!owner) {
fail(
requirement.node,
'Unresolved generic codec outside a generic function or class.',
);
}
const name = this.graph.parameterName(owner, requirement.key);
return ts.isClassDeclaration(owner.node) && !constructor ? `this.#${name}` : name;
}
const name = this.resolver.message(requirement.type, requirement.node);
(requirement.fn === 'protobuf_encode' ? encodeRoots : decodeRoots).add(name);
return `${requirement.fn}_${name}`;
};
for (const site of this.graph.sites.get(source) ?? []) {
let constructor = false;
for (
let parent: ts.Node | undefined = site.node;
parent && parent !== site.owner?.node;
parent = parent.parent
) {
if (ts.isConstructorDeclaration(parent)) {
constructor = true;
break;
}
}
if (site.direct) {
edits.push({
start: site.node.expression.getStart(source),
end: site.node.typeArguments
? site.node.typeArguments.end + 1
: site.node.expression.end,
text: reference(site.direct, site.owner, constructor),
});
} else if (site.target?.requirements.size) {
const args = [...site.target.requirements.values()].map((req) =>
reference(
this.graph.instantiate(req, this.graph.bindings(site)),
site.owner,
constructor,
),
);
insertArguments(
site.node,
this.graph.parameters(site.target.node),
args,
edits,
source,
);
}
}
this.graph.callbacks.emit(source, reference, edits);
for (const plan of this.graph.plans.values()) {
if (
ts.isTypeNode(plan.node) ||
ts.isCallSignatureDeclaration(plan.node) ||
plan.node.getSourceFile() !== source ||
(plan.requirements.size === 0 && !plan.base?.plan.requirements.size)
) {
continue;
}
const names = [...plan.requirements.keys()].map((key) =>
this.graph.parameterName(plan, key),
);
if (ts.isClassDeclaration(plan.node)) {
const constructor = constructorOf(plan.node);
const assignments = names.map((name) => `this.#${name} = ${name};`).join('\n');
if (names.length) {
edits.push({
start: plan.node.members.pos,
end: plan.node.members.pos,
text: '\n' + names.map((name) => `#${name};`).join('\n') + '\n',
});
}
if (constructor?.body) {
if (names.length) {
insertParameters(constructor.parameters, names, edits, source);
}
const superStatement = constructor.body.statements.find(
(statement) =>
ts.isExpressionStatement(statement) &&
ts.isCallExpression(statement.expression) &&
statement.expression.expression.kind === ts.SyntaxKind.SuperKeyword,
);
if (plan.base && !superStatement) {
fail(
constructor,
'Generic derived constructors require a top-level super(...) call.',
);
}
const position = superStatement?.end ?? constructor.body.getStart(source) + 1;
edits.push({ start: position, end: position, text: assignments });
} else if (plan.base) {
const inherited = this.graph.parameters(plan.base.plan.node);
const count = codecIndex(inherited);
const argsName = unique(source, '__pb_constructor_args');
const locals = names
.map((name, i) => `const ${name} = ${argsName}[${count + i}];`)
.join('\n');
const codecs = [...plan.base.plan.requirements.values()].map((req) =>
reference(this.graph.instantiate(req, plan.base!.bindings), plan, true),
);
const forwarded = [
`...${argsName}.slice(0, ${count})`,
...codecs,
`...${argsName}.slice(${count + names.length})`,
];
edits.push({
start: plan.node.members.pos,
end: plan.node.members.pos,
text: `\nconstructor(...${argsName}) { ${locals}\nsuper(${forwarded.join(', ')});\n${assignments} }\n`,
});
} else {
edits.push({
start: plan.node.members.pos,
end: plan.node.members.pos,
text: `\nconstructor(${names.map((name) => name + ' = undefined').join(', ')}) { ${assignments} }\n`,
});
}
} else {
insertParameters(plan.node.parameters, names, edits, source);
}
}
if (!edits.length) {
this.output.set(file, { source: code, code: null });
return null;
}
edits.sort((a, b) => a.start - b.start || (a.order ?? 0) - (b.order ?? 0) || a.end - b.end);
const parts: string[] = [];
let offset = 0;
for (const edit of edits) {
if (edit.start < offset) {
throw new Error('Overlapping protobuf compiler edits.');
}
offset = edit.end;
}
let generated = generateCode(this.resolver.registry, {
encodeRoots,
decodeRoots,
});
// Keep generated identifiers out of the user's namespace, including helper names.
const prefix = unique(source, '__pb_generated_');
const generatedNames = new Set(
[
...generated.matchAll(
/\b(?:function|const|let)\s+((?:protobuf_(?:encode|decode)_|__)[\p{ID_Continue}$]+)/gu,
),
].map((match) => match[1]),
);
const hasCollision = [...generatedNames].some((name) => source.text.includes(name));
const renamed = (text: string): string => {
if (!hasCollision) {
return text;
}
const scanner = ts.createScanner(
ts.ScriptTarget.Latest,
false,
ts.LanguageVariant.Standard,
text,
);
const chunks: string[] = [];
let position = 0;
for (
let token = scanner.scan();
token !== ts.SyntaxKind.EndOfFileToken;
token = scanner.scan()
) {
if (
token !== ts.SyntaxKind.Identifier ||
!generatedNames.has(scanner.getTokenText())
) {
continue;
}
chunks.push(
text.slice(position, scanner.getTokenPos()),
prefix + scanner.getTokenText(),
);
position = scanner.getTextPos();
}
return chunks.join('') + text.slice(position);
};
generated = renamed(generated);
// Rename only inserted codec references, never arbitrary source strings or user identifiers.
for (const edit of edits) {
edit.text = renamed(edit.text);
}
parts.length = 0;
offset = 0;
for (const edit of edits) {
parts.push(code.slice(offset, edit.start), edit.text);
offset = edit.end;
}
parts.push(code.slice(offset));
const rewritten = parts.join('');
let preambleAt = code.startsWith('#!') ? code.indexOf('\n') + 1 : 0;
for (const statement of source.statements) {
if (!ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression)) {
break;
}
preambleAt = statement.end;
}
const transformed =
rewritten.slice(0, preambleAt) + '\n' + generated + '\n' + rewritten.slice(preambleAt);
this.output.set(file, { source: code, code: transformed });
return transformed;
}
}
+80
View File
@@ -0,0 +1,80 @@
import ts from 'typescript';
import type { Edit, Site } from './model.js';
export function unique(source: ts.SourceFile, base: string): string {
while (source.text.includes(base)) {
base += '_';
}
return base;
}
export function codecIndex(params: readonly ts.ParameterDeclaration[] = []): number {
const index = params.findIndex((param) => !!param.initializer || !!param.dotDotDotToken);
return index < 0 ? params.length : index;
}
export function insertParameters(
params: ts.NodeArray<ts.ParameterDeclaration>,
names: string[],
edits: Edit[],
source: ts.SourceFile,
): void {
names = names.map((name) => name + ' = undefined');
const index = codecIndex(params);
if (index < params.length) {
edits.push({
start: params[index].getStart(source),
end: params[index].getStart(source),
text: names.join(', ') + ', ',
});
} else {
edits.push({
start: params.end,
end: params.end,
text: (params.length && !params.hasTrailingComma ? ', ' : '') + names.join(', '),
});
}
}
export function insertArguments(
node: Site['node'],
params: readonly ts.ParameterDeclaration[] | undefined,
args: string[],
edits: Edit[],
source: ts.SourceFile,
): void {
const index = codecIndex(params);
const actual = node.arguments;
if (actual?.some(ts.isSpreadElement)) {
const values = unique(source, '__pb_arguments');
edits.push({
start: actual[0].getStart(source),
end: actual[0].getStart(source),
text: `...((${values}) => { while (${values}.length < ${index}) ${values}.push(undefined); ${values}.splice(${index}, 0, ${args.join(', ')}); return ${values}; })([`,
});
edits.push({ start: actual.end, end: actual.end, text: '])', order: 1 });
return;
}
const missing = Math.max(0, index - (actual?.length ?? 0));
const text = [...Array(missing).fill('undefined'), ...args].join(', ');
if (!actual) {
edits.push({ start: node.end, end: node.end, text: `(${text})` });
} else if (actual.length > index) {
edits.push({
start: actual[index].getStart(source),
end: actual[index].getStart(source),
text: text + ', ',
});
} else {
edits.push({
start: actual.end,
end: actual.end,
text: (actual.length && !actual.hasTrailingComma ? ', ' : '') + text,
});
}
}
+99
View File
@@ -0,0 +1,99 @@
import ts from 'typescript';
import type { TypeEnvironment, TypeValue } from '../schema/types.js';
export type Callable =
| ts.FunctionDeclaration
| ts.FunctionExpression
| ts.ArrowFunction
| ts.MethodDeclaration
| ts.FunctionTypeNode
| ts.CallSignatureDeclaration;
export type Owner = Callable | ts.ClassDeclaration;
export interface Requirement {
key: string;
fn: 'protobuf_encode' | 'protobuf_decode';
type: TypeValue;
node: ts.Node;
}
export interface Plan {
runtime?: Requirement['fn'];
node: Owner;
env: TypeEnvironment;
requirements: Map<string, Requirement>;
names: Map<string, string>;
base?: { plan: Plan; bindings: Map<string, TypeValue> };
}
export interface Target {
node: Owner;
bindings: Map<string, TypeValue>;
}
export interface Site {
node: ts.CallExpression | ts.NewExpression;
owner?: Plan;
direct?: Requirement;
target?: Plan;
bindings?: Map<string, TypeValue>;
typeArgs?: readonly ts.TypeNode[];
env?: TypeEnvironment;
bound?: boolean;
}
export interface Edit {
order?: number;
start: number;
end: number;
text: string;
}
export function callable(node: ts.Node): node is Callable {
switch (node.kind) {
case ts.SyntaxKind.FunctionDeclaration:
case ts.SyntaxKind.FunctionExpression:
case ts.SyntaxKind.ArrowFunction:
case ts.SyntaxKind.MethodDeclaration:
case ts.SyntaxKind.FunctionType:
case ts.SyntaxKind.CallSignature:
return true;
default:
return false;
}
}
export function constructorOf(node: ts.ClassDeclaration): ts.ConstructorDeclaration | undefined {
return node.members.find(
(member): member is ts.ConstructorDeclaration =>
ts.isConstructorDeclaration(member) && !!member.body,
);
}
export function memberName(name: ts.PropertyName): string | undefined {
if (ts.isIdentifier(name) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) {
return name.text;
}
if (
ts.isComputedPropertyName(name) &&
(ts.isStringLiteralLike(name.expression) || ts.isNumericLiteral(name.expression))
) {
return name.expression.text;
}
return;
}
export function access(
expression: ts.Expression,
): { receiver: ts.Expression; name: string } | undefined {
if (ts.isPropertyAccessExpression(expression)) {
return { receiver: expression.expression, name: expression.name.text };
}
if (
ts.isElementAccessExpression(expression) &&
(ts.isStringLiteralLike(expression.argumentExpression) ||
ts.isNumericLiteral(expression.argumentExpression))
) {
return { receiver: expression.expression, name: expression.argumentExpression.text };
}
return;
}
+404
View File
@@ -0,0 +1,404 @@
import ts from 'typescript';
import { fail } from '../source/context.js';
import type { TypeEnvironment } from '../schema/types.js';
import {
access,
callable,
constructorOf,
memberName,
type Callable,
type Target,
} from './model.js';
import type { CallTargets } from './targets.js';
interface Receiver {
node: ts.ClassDeclaration | ts.ObjectLiteralExpression;
bindings: Target['bindings'];
env: TypeEnvironment;
}
type Returning = Callable | ts.GetAccessorDeclaration;
export class Receivers {
private readonly returns = new WeakMap<Returning, ts.Expression[]>();
constructor(private readonly targets: CallTargets) {}
resolve(
expression: ts.Expression,
source: ts.SourceFile,
env: TypeEnvironment,
seen = new Set<ts.Node>(),
): Receiver | undefined {
if (seen.has(expression)) {
return;
}
seen.add(expression);
const { context } = this.targets;
if (
ts.isParenthesizedExpression(expression) ||
ts.isNonNullExpression(expression) ||
ts.isSatisfiesExpression(expression)
) {
return this.resolve(expression.expression, source, env, seen);
}
if (ts.isAsExpression(expression) || ts.isTypeAssertionExpression(expression)) {
return (
this.annotation(expression.type, env, seen) ??
this.resolve(expression.expression, source, env, seen)
);
}
if (ts.isObjectLiteralExpression(expression)) {
return { node: expression, env, bindings: new Map() };
}
if (expression.kind === ts.SyntaxKind.ThisKeyword) {
for (let parent = expression.parent; parent; parent = parent.parent) {
if (ts.isClassDeclaration(parent)) {
const target = this.targets.capture(
expression,
{ node: parent, bindings: new Map() },
env,
);
return {
node: parent,
bindings: target.bindings,
env: this.targets.environment(target),
};
}
}
}
if (ts.isIdentifier(expression)) {
const declaration = context.lookup(expression.text, expression, source)?.node;
if (declaration && ts.isClassDeclaration(declaration)) {
return {
node: declaration,
bindings: new Map(),
env: this.targets.graph.plan(declaration).env,
};
}
if (
declaration &&
(ts.isVariableDeclaration(declaration) || ts.isParameter(declaration))
) {
const annotated = declaration.type && this.annotation(declaration.type, env, seen);
if (annotated) {
return annotated;
}
if (declaration.initializer) {
return this.resolve(
declaration.initializer,
declaration.getSourceFile(),
env,
seen,
);
}
}
}
const property = access(expression);
if (property) {
const receiver = this.resolve(property.receiver, source, env, seen);
const member = receiver && this.member(receiver, property.name);
if (!member) {
return;
}
const node = member.node;
if ('type' in node && node.type) {
const annotated = this.annotation(node.type, member.env, seen);
if (annotated) {
return annotated;
}
}
if (ts.isGetAccessorDeclaration(node)) {
return this.returned(node, member.env, seen, expression);
}
if ('initializer' in node && node.initializer) {
return this.resolve(node.initializer, node.getSourceFile(), member.env, seen);
}
if (ts.isShorthandPropertyAssignment(node)) {
return this.resolve(node.name, node.getSourceFile(), member.env, seen);
}
}
if (ts.isNewExpression(expression) || ts.isCallExpression(expression)) {
const target = this.targets.target(expression.expression, source, env, seen);
if (!target) {
return;
}
const specialized = this.targets.specialize(expression, target, env);
const local = this.targets.environment(specialized);
if (ts.isNewExpression(expression)) {
return ts.isClassDeclaration(target.node)
? { node: target.node, bindings: specialized.bindings, env: local }
: undefined;
}
if (!callable(target.node)) {
return;
}
const annotated = target.node.type && this.annotation(target.node.type, local, seen);
return annotated || this.returned(target.node, local, seen, expression);
}
if (ts.isConditionalExpression(expression)) {
return this.merge([expression.whenTrue, expression.whenFalse], env, seen, expression);
}
return;
}
member(
receiver: Receiver,
name: string,
):
| {
node: ts.ClassElement | ts.ObjectLiteralElementLike | ts.ParameterDeclaration;
bindings: Target['bindings'];
env: TypeEnvironment;
}
| undefined {
const { graph, resolver } = this.targets;
let node = receiver.node;
const bindings = new Map(receiver.bindings);
for (;;) {
const members = ts.isClassDeclaration(node) ? node.members : node.properties;
const member =
members.find(
(member) =>
member.name &&
memberName(member.name) === name &&
(!ts.isMethodDeclaration(member) || !!member.body),
) ??
(ts.isClassDeclaration(node)
? constructorOf(node)?.parameters.find(
(param) =>
ts.isIdentifier(param.name) &&
param.name.text === name &&
param.modifiers?.length,
)
: undefined);
if (member) {
const env = ts.isClassDeclaration(node)
? this.targets.environment({ node, bindings })
: receiver.env;
return { node: member, bindings, env };
}
const base = ts.isClassDeclaration(node) && graph.plan(node).base;
if (!base || !ts.isClassDeclaration(base.plan.node)) {
return;
}
for (const [key, type] of base.bindings) {
bindings.set(key, resolver.substitute(type, bindings));
}
node = base.plan.node;
}
}
private annotation(
type: ts.TypeNode,
env: TypeEnvironment,
seen: Set<ts.Node>,
): Receiver | undefined {
if (seen.has(type)) {
return;
}
seen.add(type);
if (ts.isParenthesizedTypeNode(type)) {
return this.annotation(type.type, env, seen);
}
if (ts.isUnionTypeNode(type)) {
const types = type.types.filter(
(item) =>
item.kind !== ts.SyntaxKind.UndefinedKeyword &&
!(
ts.isLiteralTypeNode(item) &&
item.literal.kind === ts.SyntaxKind.NullKeyword
),
);
if (types.length === 1) {
return this.annotation(types[0], env, seen);
}
return;
}
if (!ts.isTypeReferenceNode(type)) {
return;
}
const { context, resolver, graph } = this.targets;
const ref = context.typeName(type.typeName, type.getSourceFile());
if (!ref || (!ts.isClassDeclaration(ref.node) && !ts.isTypeAliasDeclaration(ref.node))) {
return;
}
if (ts.isTypeAliasDeclaration(ref.node) && !this.classShape(ref.node.type)) {
return;
}
const args = resolver.arguments(
ref.node.typeParameters,
type.typeArguments,
type.getSourceFile(),
env,
ref.node,
);
if (ts.isTypeAliasDeclaration(ref.node)) {
return this.annotation(ref.node.type, new Map([...env, ...args]), seen);
}
const plan = graph.plan(ref.node);
const target = this.targets.capture(
type,
{
node: ref.node,
bindings: new Map([...args].map(([name, type]) => [plan.env.get(name)!.key, type])),
},
env,
);
return { node: ref.node, bindings: target.bindings, env: this.targets.environment(target) };
}
private classShape(type: ts.TypeNode, seen = new Set<ts.Node>()): boolean {
if (seen.has(type)) {
return false;
}
seen.add(type);
if (ts.isParenthesizedTypeNode(type)) {
return this.classShape(type.type, seen);
}
if (ts.isUnionTypeNode(type)) {
return type.types.some((member) => this.classShape(member, seen));
}
if (!ts.isTypeReferenceNode(type)) {
return false;
}
const node = this.targets.context.typeName(type.typeName, type.getSourceFile())?.node;
return (
!!node &&
(ts.isClassDeclaration(node) ||
(ts.isTypeAliasDeclaration(node) && this.classShape(node.type, seen)))
);
}
private returned(
node: Returning,
env: TypeEnvironment,
seen: Set<ts.Node>,
origin: ts.Node,
): Receiver | undefined {
const cached = this.returns.get(node);
if (cached) {
return this.merge(cached, env, seen, origin);
}
const expressions: ts.Expression[] = [];
if ('body' in node && node.body) {
if (ts.isBlock(node.body)) {
const visit = (child: ts.Node): void => {
if (ts.isFunctionLike(child) || ts.isClassDeclaration(child)) {
return;
}
if (ts.isReturnStatement(child)) {
if (child.expression) {
expressions.push(child.expression);
}
} else {
ts.forEachChild(child, visit);
}
};
visit(node.body);
} else {
expressions.push(node.body);
}
}
this.returns.set(node, expressions);
return this.merge(expressions, env, seen, origin);
}
private merge(
expressions: ts.Expression[],
env: TypeEnvironment,
seen: Set<ts.Node>,
origin: ts.Node,
): Receiver | undefined {
let result: Receiver | undefined;
for (const expression of expressions) {
const next = this.resolve(expression, expression.getSourceFile(), env, new Set(seen));
if (!next) {
return;
}
if (
result &&
(result.node !== next.node ||
[...result.env].some(([name, type]) => next.env.get(name)?.key !== type.key))
) {
// Data objects returned by ordinary functions need no codec
// specialization, even when their branches have different shapes.
if (
ts.isObjectLiteralExpression(result.node) &&
ts.isObjectLiteralExpression(next.node) &&
![...result.node.properties, ...next.node.properties].some(
(member) =>
callable(member) ||
(ts.isPropertyAssignment(member) && callable(member.initializer)),
)
) {
return;
}
fail(origin, 'Receiver branches must resolve to the same specialization.');
}
result = next;
}
return result;
}
}
+212
View File
@@ -0,0 +1,212 @@
import ts from 'typescript';
import type { SourceContext } from '../source/context.js';
import type { SchemaResolver } from '../schema/resolver.js';
import type { TypeEnvironment } from '../schema/types.js';
export interface Signature {
node: ts.FunctionTypeNode | ts.CallSignatureDeclaration;
env: TypeEnvironment;
}
export function memberType(
type: ts.TypeNode,
name: string,
env: TypeEnvironment,
context: SourceContext,
resolver: SchemaResolver,
seen = new Set<ts.Node>(),
): { type: ts.TypeNode; env: TypeEnvironment } | undefined {
if (seen.has(type)) {
return;
}
seen.add(type);
if (ts.isTypeLiteralNode(type)) {
const member = type.members.find(
(member) =>
member.name &&
(ts.isIdentifier(member.name) || ts.isStringLiteral(member.name)) &&
member.name.text === name,
);
return member && ts.isPropertySignature(member) && member.type
? { type: member.type, env }
: undefined;
}
if (ts.isTypeReferenceNode(type)) {
const ref = context.typeName(type.typeName, type.getSourceFile());
if (
!ref ||
(!ts.isTypeAliasDeclaration(ref.node) && !ts.isInterfaceDeclaration(ref.node))
) {
return;
}
if (ts.isTypeAliasDeclaration(ref.node) && !memberShape(ref.node.type, name, context)) {
return;
}
const local = new Map([
...env,
...resolver.arguments(
ref.node.typeParameters,
type.typeArguments,
type.getSourceFile(),
env,
ref.node,
true,
),
]);
if (ts.isTypeAliasDeclaration(ref.node)) {
return memberType(ref.node.type, name, local, context, resolver, seen);
}
const member = ref.node.members.find(
(member) => member.name?.getText(ref.source).replace(/^['"]|['"]$/g, '') === name,
);
return member && ts.isPropertySignature(member) && member.type
? { type: member.type, env: local }
: undefined;
}
return;
}
export function resolveSignature(
type: ts.TypeNode,
env: TypeEnvironment,
context: SourceContext,
resolver: SchemaResolver,
seen = new Set<ts.Node>(),
): Signature | undefined {
if (seen.has(type)) {
return;
}
seen.add(type);
if (ts.isParenthesizedTypeNode(type)) {
return resolveSignature(type.type, env, context, resolver, seen);
}
if (ts.isFunctionTypeNode(type)) {
return { node: type, env };
}
if (ts.isTypeLiteralNode(type)) {
const signatures = type.members.filter(ts.isCallSignatureDeclaration);
if (signatures.length === 1) {
return { node: signatures[0], env };
}
}
if (ts.isTypeReferenceNode(type)) {
const ref = context.typeName(type.typeName, type.getSourceFile());
if (!ref) {
return;
}
const node = ref.node;
if (!ts.isTypeAliasDeclaration(node) && !ts.isInterfaceDeclaration(node)) {
return;
}
if (!callableShape(type, context)) {
return;
}
const local = new Map([
...env,
...resolver.arguments(
node.typeParameters,
type.typeArguments,
type.getSourceFile(),
env,
node,
true,
),
]);
return ts.isTypeAliasDeclaration(node)
? resolveSignature(node.type, local, context, resolver, seen)
: { node: node.members.find(ts.isCallSignatureDeclaration)!, env: local };
}
return;
}
export function callableShape(
type: ts.TypeNode,
context: SourceContext,
seen = new Set<ts.Node>(),
): boolean {
if (seen.has(type)) {
return false;
}
seen.add(type);
if (ts.isFunctionTypeNode(type)) {
return true;
}
if (ts.isParenthesizedTypeNode(type)) {
return callableShape(type.type, context, seen);
}
if (ts.isTypeLiteralNode(type)) {
return type.members.filter(ts.isCallSignatureDeclaration).length === 1;
}
if (!ts.isTypeReferenceNode(type)) {
return false;
}
const node = context.typeName(type.typeName, type.getSourceFile())?.node;
return (
!!node &&
(ts.isTypeAliasDeclaration(node)
? callableShape(node.type, context, seen)
: ts.isInterfaceDeclaration(node) &&
node.members.filter(ts.isCallSignatureDeclaration).length === 1)
);
}
function memberShape(
type: ts.TypeNode,
name: string,
context: SourceContext,
seen = new Set<ts.Node>(),
): boolean {
if (seen.has(type)) {
return false;
}
seen.add(type);
if (ts.isTypeLiteralNode(type)) {
return type.members.some(
(member) => member.name?.getText().replace(/^['"]|['"]$/g, '') === name,
);
}
if (!ts.isTypeReferenceNode(type)) {
return false;
}
const node = context.typeName(type.typeName, type.getSourceFile())?.node;
return (
!!node &&
(ts.isTypeAliasDeclaration(node)
? memberShape(node.type, name, context, seen)
: ts.isInterfaceDeclaration(node) &&
node.members.some(
(member) => member.name?.getText().replace(/^['"]|['"]$/g, '') === name,
))
);
}
+345
View File
@@ -0,0 +1,345 @@
import ts from 'typescript';
import { packageName } from '../package.js';
import { SourceContext, runtimeImportName, type DeclarationRef } from '../source/context.js';
import { SchemaResolver } from '../schema/resolver.js';
import type { TypeEnvironment, TypeValue } from '../schema/types.js';
import { access, callable, type Plan, type Target, type Requirement, type Site } from './model.js';
import { Receivers } from './receivers.js';
import { callableShape, memberType, resolveSignature, type Signature } from './signatures.js';
interface Plans {
environment(node: ts.Node): TypeEnvironment;
plan(node: Target['node']): Plan;
runtimePlan(fn: Requirement['fn']): Plan;
bindings(site: Site, partial?: boolean): Map<string, TypeValue>;
}
export class CallTargets {
private readonly receivers = new Receivers(this);
constructor(
readonly context: SourceContext,
readonly resolver: SchemaResolver,
readonly graph: Plans,
) {}
signature(type: ts.TypeNode, env: TypeEnvironment) {
return resolveSignature(type, env, this.context, this.resolver);
}
signatureTarget(signature: Signature): Target {
const plan = this.graph.plan(signature.node);
return {
node: signature.node,
bindings: new Map(
[...signature.env].flatMap(([name, type]) => {
if (signature.node.typeParameters?.some((param) => param.name.text === name)) {
return [];
}
const parameter = plan.env.get(name);
return parameter ? [[parameter.key, type] as const] : [];
}),
),
};
}
target(
expression: ts.Expression,
source: ts.SourceFile,
env: TypeEnvironment,
seen = new Set<ts.Node>(),
): Target | undefined {
if (seen.has(expression)) {
return;
}
seen.add(expression);
if (callable(expression)) {
return { node: expression, bindings: new Map() };
}
if (ts.isCallExpression(expression)) {
const factory = this.target(expression.expression, source, env, seen);
if (
factory &&
callable(factory.node) &&
factory.node.type &&
callableShape(factory.node.type, this.context)
) {
const local = this.environment(this.specialize(expression, factory, env));
const signature = this.signature(factory.node.type, local);
if (signature) {
return this.signatureTarget(signature);
}
}
return;
}
if (
ts.isParenthesizedExpression(expression) ||
ts.isAsExpression(expression) ||
ts.isNonNullExpression(expression)
) {
return this.target(expression.expression, source, env, seen);
}
if (expression.kind === ts.SyntaxKind.SuperKeyword) {
for (let parent: ts.Node | undefined = expression; parent; parent = parent.parent) {
if (ts.isClassDeclaration(parent)) {
const base = this.graph.plan(parent).base;
return base
? { node: base.plan.node, bindings: new Map(base.bindings) }
: undefined;
}
}
}
let ref: DeclarationRef | undefined;
const property = access(expression);
if (ts.isIdentifier(expression)) {
ref = this.context.lookup(expression.text, expression, source);
} else if (property) {
let receiver: ts.Expression = property.receiver;
while (ts.isParenthesizedExpression(receiver)) {
receiver = receiver.expression;
}
const declaration = ts.isIdentifier(receiver)
? this.context.lookup(receiver.text, receiver, source)?.node
: undefined;
if (
declaration &&
(ts.isVariableDeclaration(declaration) || ts.isParameter(declaration)) &&
declaration.type
) {
const member = memberType(
declaration.type,
property.name,
env,
this.context,
this.resolver,
);
const signature = member && this.signature(member.type, member.env);
if (signature) {
return this.signatureTarget(signature);
}
}
if (declaration && ts.isNamespaceImport(declaration)) {
const specifier = (declaration.parent.parent.moduleSpecifier as ts.StringLiteral)
.text;
if (
specifier === packageName &&
(property.name === 'protobuf_encode' || property.name === 'protobuf_decode')
) {
return {
node: this.graph.runtimePlan(property.name).node,
bindings: new Map(),
};
}
const module = this.context.module(specifier, declaration.getSourceFile());
ref = module ? this.context.exported(property.name, module) : undefined;
} else {
const value = this.receivers.resolve(receiver, source, env, seen);
const member = value && this.receivers.member(value, property.name);
if (member) {
if (callable(member.node)) {
return { node: member.node, bindings: member.bindings };
}
if ('initializer' in member.node && member.node.initializer) {
const target = this.target(
member.node.initializer,
member.node.getSourceFile(),
member.env,
seen,
);
if (target) {
return {
node: target.node,
bindings: new Map([...member.bindings, ...target.bindings]),
};
}
}
if (ts.isShorthandPropertyAssignment(member.node)) {
return this.target(
member.node.name,
member.node.getSourceFile(),
member.env,
seen,
);
}
}
}
}
if (!ref) {
return;
}
// Ambient library declarations have no body in which to thread codecs.
// Their unrelated generic arguments must not enter schema inference.
if (ref.source.isDeclarationFile) {
return;
}
const runtime = runtimeImportName(ref.node);
if (runtime === 'protobuf_encode' || runtime === 'protobuf_decode') {
return { node: this.graph.runtimePlan(runtime).node, bindings: new Map() };
}
if ((ts.isParameter(ref.node) || ts.isVariableDeclaration(ref.node)) && ref.node.type) {
const signature = this.signature(ref.node.type, env);
if (signature) {
return this.signatureTarget(signature);
}
}
if (
ts.isBindingElement(ref.node) &&
ts.isObjectBindingPattern(ref.node.parent) &&
(ts.isVariableDeclaration(ref.node.parent.parent) ||
ts.isParameter(ref.node.parent.parent))
) {
const declaration = ref.node.parent.parent;
const initializer = declaration.initializer;
const name = ref.node.propertyName ?? ref.node.name;
if (declaration.type && (ts.isIdentifier(name) || ts.isStringLiteral(name))) {
const property = memberType(
declaration.type,
name.text,
env,
this.context,
this.resolver,
);
const signature = property && this.signature(property.type, property.env);
if (signature) {
return this.signatureTarget(signature);
}
}
if (initializer && (ts.isIdentifier(name) || ts.isStringLiteral(name))) {
return this.target(
ts.factory.createPropertyAccessExpression(initializer, name.text),
ref.source,
env,
seen,
);
}
}
if (callable(ref.node) || ts.isClassDeclaration(ref.node)) {
return { node: ref.node, bindings: new Map() };
}
if (ts.isVariableDeclaration(ref.node) && ref.node.initializer) {
if (callable(ref.node.initializer)) {
return { node: ref.node.initializer, bindings: new Map() };
}
return this.target(ref.node.initializer, ref.source, env, seen);
}
return;
}
specialize(
node: ts.CallExpression | ts.NewExpression,
target: Target,
env: TypeEnvironment,
): Target {
return {
node: target.node,
bindings: this.graph.bindings(
{
node,
target: this.graph.plan(target.node),
bindings: this.capture(node, target, env).bindings,
typeArgs: node.typeArguments,
env,
},
true,
),
};
}
capture(node: ts.Node, target: Target, env: TypeEnvironment): Target {
const bindings = new Map(target.bindings);
const lexical = this.graph.environment(node);
for (const [name, type] of this.graph.plan(target.node).env) {
if (
!bindings.has(type.key) &&
!target.node.typeParameters?.some((param) => param.name.text === name) &&
lexical.get(name)?.key === type.key &&
env.has(name)
) {
bindings.set(type.key, env.get(name)!);
}
}
return { node: target.node, bindings };
}
environment(target: Target): TypeEnvironment {
return new Map(
[...this.graph.plan(target.node).env].map(([name, type]) => [
name,
this.resolver.substitute(type, target.bindings),
]),
);
}
infer(
expression: ts.Expression,
source: ts.SourceFile,
seen = new Set<ts.Node>(),
): ts.TypeNode | undefined {
if (seen.has(expression)) {
return;
}
seen.add(expression);
if (
ts.isAsExpression(expression) ||
ts.isTypeAssertionExpression(expression) ||
ts.isSatisfiesExpression(expression)
) {
return expression.type;
}
if (ts.isIdentifier(expression)) {
const ref = this.context.lookup(expression.text, expression, source);
if (ref && (ts.isVariableDeclaration(ref.node) || ts.isParameter(ref.node))) {
if (ref.node.type) {
return ref.node.type;
}
if (ref.node.initializer) {
return this.infer(ref.node.initializer, ref.source, seen);
}
}
}
return;
}
}
+140
View File
@@ -0,0 +1,140 @@
import ts from 'typescript';
import { fail } from '../source/context.js';
import { callable } from './model.js';
import type { CallAnalysis } from './analysis.js';
export function validateSource(graph: CallAnalysis, source: ts.SourceFile): void {
if (![...graph.plans.values()].some((plan) => plan.requirements.size)) {
return;
}
const visit = (node: ts.Node): void => {
if (ts.isExpressionWithTypeArguments(node) && !ts.isHeritageClause(node.parent)) {
const target = graph.targets.target(node.expression, source, graph.environment(node));
if (
target &&
graph.plan(target.node).requirements.size &&
!graph.callbacks.adapters.has(node)
) {
fail(node, 'Generic function values require an explicitly typed arrow adapter.');
}
}
if (ts.isTypeNode(node) || ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
return;
}
if (ts.isIdentifier(node) && node.text === 'arguments') {
const owner = graph.owner(node);
if (owner && graph.plan(owner).requirements.size) {
fail(
node,
'Generic codec functions cannot reflect on arguments; use named or rest parameters.',
);
}
}
if (
(ts.isIdentifier(node) ||
ts.isPropertyAccessExpression(node) ||
ts.isElementAccessExpression(node) ||
ts.isArrowFunction(node) ||
ts.isFunctionExpression(node)) &&
isValuePosition(node)
) {
const target = graph.targets.target(node, source, graph.environment(node));
const owner = target && graph.owner(target.node);
if (
target &&
!graph.callbacks.adapters.has(node) &&
!ts.isClassDeclaration(target.node) &&
(graph.plan(target.node).requirements.size ||
(ts.isMethodDeclaration(target.node) &&
owner &&
graph.plan(owner).requirements.size))
) {
fail(
node,
'Cannot infer callback schema; annotate the callback type or supply concrete type arguments.',
);
}
}
if (
(ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) &&
ts.isVariableDeclaration(node.parent) &&
node.parent.initializer === node
) {
const target = graph.targets.target(node, source, graph.environment(node));
const owner = target && graph.owner(target.node);
if (
target &&
ts.isMethodDeclaration(target.node) &&
!target.node.typeParameters?.length &&
owner &&
ts.isClassDeclaration(owner) &&
graph.plan(owner).requirements.size
) {
fail(
node,
'Instance codec methods require their receiver; use an arrow adapter instead of detaching the method.',
);
}
}
ts.forEachChild(node, visit);
};
visit(source);
for (const site of graph.sites.get(source) ?? []) {
if (!site.direct?.type.dynamic || !site.owner || !ts.isClassDeclaration(site.owner.node)) {
continue;
}
for (
let parent = site.node.parent;
parent && parent !== site.owner.node;
parent = parent.parent
) {
if (callable(parent) || ts.isConstructorDeclaration(parent)) {
break;
}
if (ts.isPropertyDeclaration(parent)) {
fail(
site.node,
'Move generic codec calls from class field initializers into the constructor body.',
);
}
}
}
}
function isValuePosition(node: ts.Expression): boolean {
let value: ts.Node = node;
while (
ts.isParenthesizedExpression(value.parent) ||
ts.isAsExpression(value.parent) ||
ts.isSatisfiesExpression(value.parent)
) {
value = value.parent;
}
const parent = value.parent;
return (
(ts.isCallExpression(parent) && parent.expression !== value) ||
ts.isReturnStatement(parent) ||
ts.isShorthandPropertyAssignment(parent) ||
ts.isArrayLiteralExpression(parent) ||
(ts.isPropertyAssignment(parent) && parent.initializer === value) ||
(ts.isBinaryExpression(parent) &&
parent.right === value &&
parent.operatorToken.kind === ts.SyntaxKind.EqualsToken)
);
}
+50 -116
View File
@@ -1,140 +1,74 @@
import type { Plugin } from 'vite';
import {
analyze,
analyzeSource,
selectUsedRegistry,
typeNodeToMangledName,
} from './ast/analyzer.js';
import { generateCode } from './codegen/generator.js';
import { applyReplacements, replaceCallSites } from './transform/replacer.js';
import type { MessageRegistry } from './ast/types.js';
import { resolveImports, type ParsedFileEntry } from './ast/import-resolver.js';
import { createRuntimeMap, type RuntimeMapCallSite } from './runtime-map.js';
import type { Plugin, ResolvedConfig } from 'vite';
import { ProtobufCompiler } from './compiler/compiler.js';
import { buildEntries } from './source/entries.js';
import { packageName } from './package.js';
export interface ProtobufRuntimeMapPluginOptions {
enabled?: boolean;
fileName?: string;
}
export default function protobufVitePlugin(): Plugin {
const compiler = new ProtobufCompiler();
const transformedFiles = new Set<string>();
let config: ResolvedConfig | undefined;
let needsPreparation = true;
export interface ProtobufVitePluginOptions {
runtimeMap?: ProtobufRuntimeMapPluginOptions;
}
interface RuntimeMapFileEntry {
messages: MessageRegistry;
callSites: RuntimeMapCallSite[];
}
export default function protobufVitePlugin(options: ProtobufVitePluginOptions = {}): Plugin {
const fileCache = new Map<string, ParsedFileEntry>();
const runtimeMapByFile = new Map<string, RuntimeMapFileEntry>();
const runtimeMapEnabled = options.runtimeMap?.enabled === true;
const runtimeMapFileName = options.runtimeMap?.fileName ?? 'snowluma-proton.runtime-map.json';
const invalidate = () => {
compiler.clear();
needsPreparation = true;
};
return {
name: 'vite-plugin-protobuf',
name: `${packageName}:vite`,
enforce: 'pre',
configResolved(resolved) {
config = resolved;
},
buildStart() {
invalidate();
transformedFiles.clear();
},
watchChange() {
invalidate();
},
transform(code, id) {
const cleanId = id.split('?')[0];
if (!cleanId.endsWith('.ts') || cleanId.endsWith('.d.ts')) {
if (!/\.[cm]?tsx?$/.test(cleanId) || /\.d\.[cm]?ts$/.test(cleanId)) {
return null;
}
const imported = resolveImports(code, cleanId, fileCache);
const { registry, callSites, sourceFile } = analyze(code, cleanId, imported);
if (needsPreparation) {
if (config) {
compiler.prepare(buildEntries(config));
}
if (registry.size === 0 && callSites.length === 0) {
return null;
needsPreparation = false;
}
const used = selectUsedRegistry(registry, callSites, sourceFile);
const transformed = compiler.compile(code, cleanId);
if (used.registry.size === 0) {
runtimeMapByFile.delete(cleanId);
return null;
if (transformed !== null) {
transformedFiles.add(cleanId);
for (const dependency of compiler.context.files.keys()) {
this.addWatchFile?.(dependency);
}
}
if (runtimeMapEnabled) {
runtimeMapByFile.set(cleanId, {
messages: used.registry,
callSites: used.callSites.map((cs) => ({
file: cleanId,
line: cs.line,
column: cs.column,
fnName: cs.fnName as RuntimeMapCallSite['fnName'],
typeName: cs.typeName,
})),
return transformed === null ? null : { code: transformed, map: null };
},
handleHotUpdate({ file, server }) {
if (/\.[cm]?tsx?$/.test(file)) {
invalidate();
return [...transformedFiles].flatMap((id) => {
const module = server.moduleGraph.getModuleById(id);
return module ? [module] : [];
});
}
const generatedCode = generateCode(used.registry);
const { transformedCode, hasReplacements } = applyReplacements(
code,
sourceFile,
callSites,
used.registry,
);
if (!hasReplacements && generatedCode === '') {
return null;
}
return { code: generatedCode + '\n' + transformedCode, map: null };
},
handleHotUpdate({ file }) {
if (file.endsWith('.ts')) {
fileCache.delete(file);
runtimeMapByFile.delete(file);
}
},
generateBundle() {
if (!runtimeMapEnabled) {
return;
}
const mergedMessages: MessageRegistry = new Map();
const mergedCallSites: RuntimeMapCallSite[] = [];
for (const entry of runtimeMapByFile.values()) {
for (const [name, msg] of entry.messages) {
mergedMessages.set(name, msg);
}
mergedCallSites.push(...entry.callSites);
}
if (mergedMessages.size === 0 || mergedCallSites.length === 0) {
return;
}
const runtimeMap = createRuntimeMap({
messages: mergedMessages,
callSites: mergedCallSites,
});
this.emitFile({
type: 'asset',
fileName: runtimeMapFileName,
source: JSON.stringify(runtimeMap, null, 2),
});
return;
},
};
}
export {
analyze,
analyzeSource,
generateCode,
replaceCallSites,
applyReplacements,
typeNodeToMangledName,
resolveImports,
selectUsedRegistry,
createRuntimeMap,
};
export type { ProtobufRuntimeMap, RuntimeMapCallSite } from './runtime-map.js';
+1
View File
@@ -0,0 +1 @@
export { name as packageName } from '../package.json';
-78
View File
@@ -1,78 +0,0 @@
import type { MessageRegistry, ProtobufField, ProtobufMessage } from './ast/types.js';
export type RuntimeMapFnName = 'protobuf_encode' | 'protobuf_decode';
export interface RuntimeMapCallSite {
file: string;
line: number;
column: number;
fnName: RuntimeMapFnName;
typeName: string;
}
export interface ProtobufRuntimeMap {
version: 1;
messages: ProtobufMessage[];
callSites: RuntimeMapCallSite[];
}
function cloneField(field: ProtobufField): ProtobufField {
return {
name: field.name,
fieldNumber: field.fieldNumber,
typeName: field.typeName,
wireType: field.wireType,
isMessage: field.isMessage,
isOptional: field.isOptional,
isRepeated: field.isRepeated,
explicitPresence: field.explicitPresence ?? false,
};
}
function cloneMessage(msg: ProtobufMessage): ProtobufMessage {
return {
name: msg.name,
fields: msg.fields.map(cloneField),
};
}
export function registryToRuntimeMapMessages(registry: MessageRegistry): ProtobufMessage[] {
return [...registry.values()].map(cloneMessage);
}
export function runtimeMapToRegistry(map: ProtobufRuntimeMap): MessageRegistry {
const registry: MessageRegistry = new Map();
for (const msg of map.messages) {
registry.set(msg.name, cloneMessage(msg));
}
return registry;
}
export function normalizeRuntimeMapPath(filePath: string): string {
const noQuery = filePath.replace(/[?#].*$/, '');
return noQuery.replace(/\\/g, '/').replace(/^file:\/\//, '');
}
export function createRuntimeMap(map: {
messages: MessageRegistry;
callSites: RuntimeMapCallSite[];
}): ProtobufRuntimeMap {
const dedupedCallSites = new Map<string, RuntimeMapCallSite>();
for (const cs of map.callSites) {
const normalized = {
...cs,
file: normalizeRuntimeMapPath(cs.file),
};
const key = `${normalized.file}:${normalized.line}:${normalized.column}:${normalized.fnName}:${normalized.typeName}`;
dedupedCallSites.set(key, normalized);
}
return {
version: 1,
messages: registryToRuntimeMapMessages(map.messages),
callSites: [...dedupedCallSites.values()],
};
}
+14 -282
View File
@@ -1,16 +1,18 @@
import { buildDependencyRegistry } from './ast/dependency-graph.js';
import type { MessageRegistry } from './ast/types.js';
import { generateCode } from './codegen/generator.js';
import {
normalizeRuntimeMapPath,
runtimeMapToRegistry,
type ProtobufRuntimeMap,
type RuntimeMapCallSite,
type RuntimeMapFnName,
} from './runtime-map.js';
import { packageName } from './package.js';
type DynamicEncode = (params: unknown) => Uint8Array;
type DynamicDecode = (data: Uint8Array) => unknown;
function uncompiled(operation: string): never {
throw new Error(
`${operation}<T>() was not transformed by the ${packageName} Vite plugin. Add the plugin from ${packageName}/vite to your build.`,
);
}
export function protobuf_encode<T>(_value: T): Uint8Array {
return uncompiled('protobuf_encode');
}
export function protobuf_decode<T>(_bytes: Uint8Array): T {
return uncompiled('protobuf_decode');
}
export interface ProtobufUnknownField {
fieldNumber: number;
@@ -65,273 +67,3 @@ export function protobuf_getUnknownFieldMetadata(value: unknown): ProtobufUnknow
omittedByteLength: candidate.omittedByteLength ?? 0,
};
}
interface DynamicTypeFns {
encode?: DynamicEncode;
decode?: DynamicDecode;
}
interface StackFrame {
file: string;
line: number;
column: number;
}
const DYNAMIC_MISS = Symbol('snowluma-proton-dynamic-miss');
let runtimeMapFallback: ProtobufRuntimeMap | null = null;
let runtimeMapRegistry: MessageRegistry | null = null;
let runtimeMapCallSites: RuntimeMapCallSite[] = [];
const dynamicTypeCache = new Map<string, DynamicTypeFns>();
/**
* Enable dynamic runtime fallback from a pre-collected map file.
* This is disabled by default.
*/
export function protobuf_enableRuntimeMapFallback(map: ProtobufRuntimeMap): void {
runtimeMapFallback = map;
runtimeMapRegistry = runtimeMapToRegistry(map);
runtimeMapCallSites = map.callSites.map((cs) => ({
...cs,
file: normalizeRuntimeMapPath(cs.file),
}));
dynamicTypeCache.clear();
}
/** Disable dynamic runtime fallback and clear all generated function caches. */
export function protobuf_disableRuntimeMapFallback(): void {
runtimeMapFallback = null;
runtimeMapRegistry = null;
runtimeMapCallSites = [];
dynamicTypeCache.clear();
}
export function protobuf_encode<T>(_params: T): Uint8Array {
const dynamic = tryDynamicInvoke('protobuf_encode', _params);
if (dynamic !== DYNAMIC_MISS) {
return dynamic as Uint8Array;
}
throw new Error(
'protobuf_encode<T>() was not transformed by the @snowluma/proton Vite plugin. ' +
'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.',
);
}
export function protobuf_decode<T>(_data: Uint8Array): T {
const dynamic = tryDynamicInvoke('protobuf_decode', _data);
if (dynamic !== DYNAMIC_MISS) {
return dynamic as T;
}
throw new Error(
'protobuf_decode<T>() was not transformed by the @snowluma/proton Vite plugin. ' +
'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.',
);
}
function tryDynamicInvoke(fnName: RuntimeMapFnName, payload: unknown): unknown {
if (!runtimeMapFallback || runtimeMapFallback.version !== 1 || !runtimeMapRegistry) {
return DYNAMIC_MISS;
}
const caller = getFirstUserFrame();
if (!caller) {
return DYNAMIC_MISS;
}
const callSite = resolveCallSite(fnName, caller);
if (!callSite) {
return DYNAMIC_MISS;
}
const typeFns = ensureTypeFunctions(callSite.typeName);
if (!typeFns) {
return DYNAMIC_MISS;
}
const fn = fnName === 'protobuf_encode' ? typeFns.encode : typeFns.decode;
if (typeof fn !== 'function') {
return DYNAMIC_MISS;
}
return fn(payload as never);
}
function ensureTypeFunctions(typeName: string): DynamicTypeFns | null {
const cached = dynamicTypeCache.get(typeName);
if (cached) {
return cached;
}
if (!runtimeMapRegistry || !runtimeMapRegistry.has(typeName)) {
return null;
}
const subset = buildDependencyRegistry(runtimeMapRegistry, [typeName]);
if (subset.size === 0) {
return null;
}
const generated = generateCode(subset);
if (!generated) {
return null;
}
const factory = new Function(
`${generated}\nreturn {\n` +
` encode: typeof protobuf_encode_${typeName} === 'function' ? protobuf_encode_${typeName} : undefined,\n` +
` decode: typeof protobuf_decode_${typeName} === 'function' ? protobuf_decode_${typeName} : undefined,\n` +
`};`,
) as () => DynamicTypeFns;
const compiled = factory();
dynamicTypeCache.set(typeName, compiled);
return compiled;
}
function resolveCallSite(fnName: RuntimeMapFnName, caller: StackFrame): RuntimeMapCallSite | null {
const callerFile = normalizeRuntimeMapPath(caller.file);
const candidates = runtimeMapCallSites.filter(
(cs) =>
cs.fnName === fnName && cs.line === caller.line && pathsLikelySame(callerFile, cs.file),
);
if (candidates.length === 0) {
return null;
}
if (candidates.length === 1) {
return candidates[0];
}
let best = candidates[0];
let bestDistance = Math.abs(best.column - caller.column);
for (let i = 1; i < candidates.length; i++) {
const dist = Math.abs(candidates[i].column - caller.column);
if (dist < bestDistance) {
best = candidates[i];
bestDistance = dist;
}
}
return best;
}
function getFirstUserFrame(): StackFrame | null {
const err = new Error();
if (!err.stack) {
return null;
}
const lines = err.stack.split('\n').slice(1);
for (const raw of lines) {
const frame = parseStackLine(raw);
if (!frame) {
continue;
}
const file = normalizeRuntimeMapPath(frame.file);
if (isRuntimeInternalFile(file)) {
continue;
}
return {
file,
line: frame.line,
column: frame.column,
};
}
return null;
}
function parseStackLine(line: string): StackFrame | null {
const trimmed = line.trim();
if (!trimmed) {
return null;
}
let location = trimmed;
const atPrefix = 'at ';
if (location.startsWith(atPrefix)) {
location = location.slice(atPrefix.length).trim();
}
const openParen = location.lastIndexOf('(');
if (openParen >= 0 && location.endsWith(')')) {
location = location.slice(openParen + 1, -1);
}
const lastColon = location.lastIndexOf(':');
if (lastColon < 0) {
return null;
}
const secondLastColon = location.lastIndexOf(':', lastColon - 1);
if (secondLastColon < 0) {
return null;
}
const file = location.slice(0, secondLastColon);
const linePart = location.slice(secondLastColon + 1, lastColon);
const colPart = location.slice(lastColon + 1);
const parsedLine = Number(linePart);
const parsedCol = Number(colPart);
if (!Number.isFinite(parsedLine) || !Number.isFinite(parsedCol)) {
return null;
}
return {
file,
line: parsedLine,
column: parsedCol,
};
}
function isRuntimeInternalFile(file: string): boolean {
return (
file.endsWith('/runtime.ts') ||
file.endsWith('/runtime.js') ||
file.includes('/dist/runtime.js')
);
}
function pathsLikelySame(a: string, b: string): boolean {
if (a === b) {
return true;
}
const aBase = basename(a);
const bBase = basename(b);
return aBase !== '' && aBase === bBase;
}
function basename(file: string): string {
const normalized = normalizeRuntimeMapPath(file);
const idx = normalized.lastIndexOf('/');
return idx >= 0 ? normalized.slice(idx + 1) : normalized;
}
+143
View File
@@ -0,0 +1,143 @@
import type ts from 'typescript';
import { fail } from '../source/context.js';
import {
PRIMITIVE_TYPE_MAP,
WireType,
type MessageRegistry,
type ProtobufField,
} from '../codegen/model.js';
import type { TypeValue } from './types.js';
export class MessageBuilder {
readonly registry: MessageRegistry = new Map();
private readonly messageNames = new Map<string, string>();
private readonly nameOwners = new Map<string, string>();
build(type: TypeValue, node: ts.Node): string {
if (type.dynamic) {
fail(
node,
`Cannot statically resolve protobuf type ${type.name}. Supply concrete generic arguments at its call site.`,
);
}
if (type.kind !== 'object' || !type.fields) {
fail(node, `Expected a protobuf message, received ${type.name}.`);
}
const cached = this.messageNames.get(type.key);
if (cached) {
return cached;
}
let name = type.name.replace(/[^\p{ID_Continue}$]/gu, '_');
if (!/^[\p{ID_Start}_$]/u.test(name)) {
name = '_' + name;
}
if (this.nameOwners.has(name) && this.nameOwners.get(name) !== type.key) {
let hash = 2166136261;
for (const char of type.key) {
hash = Math.imul(hash ^ char.charCodeAt(0), 16777619);
}
name += '_' + (hash >>> 0).toString(36);
}
this.nameOwners.set(name, type.key);
this.messageNames.set(type.key, name);
const fields: ProtobufField[] = [];
this.registry.set(name, { name, fields });
const numbers = new Set<number>();
for (const [fieldName, property] of type.fields) {
let marker = property.type;
let optional = property.optional;
if (marker.kind === 'union') {
optional ||= marker.values!.some((item) => item.kind === 'null');
const members = marker.values!.filter((item) => item.kind !== 'null');
if (members.length !== 1) {
fail(property.node, `Ambiguous protobuf union on field ${fieldName}.`);
}
marker = members[0];
}
if (marker.kind !== 'marker') {
fail(
property.node,
`Field ${fieldName} must use pb<N, T>, pb_optional<N, T> or pb_repeated<N, T>.`,
);
}
const number = marker.fieldNumber!;
if (
!Number.isInteger(number) ||
number < 1 ||
number > 536870911 ||
(number >= 19000 && number <= 19999)
) {
fail(property.node, `Invalid or reserved protobuf field number ${number}.`);
}
if (numbers.has(number)) {
fail(property.node, `Duplicate protobuf field number ${number}.`);
}
numbers.add(number);
let payload = marker.values![0];
if (payload.kind === 'marker') {
payload = payload.values![0];
}
if (payload.kind === 'union') {
optional ||= payload.values!.some((item) => item.kind === 'null');
const members = payload.values!.filter((item) => item.kind !== 'null');
if (members.length !== 1) {
fail(property.node, `Ambiguous protobuf union on field ${fieldName}.`);
}
payload = members[0];
}
const repeated = marker.repeated || payload.kind === 'array';
if (payload.kind === 'array') {
payload = payload.values![0];
}
const isMessage = payload.kind === 'object';
const typeName = isMessage ? this.build(payload, property.node) : payload.name;
const primitive = PRIMITIVE_TYPE_MAP[typeName];
if (!isMessage && !primitive) {
fail(
property.node,
`Unsupported protobuf field type ${typeName}. Use an explicit protobuf scalar type.`,
);
}
fields.push({
name: fieldName,
fieldNumber: number,
typeName,
wireType: isMessage ? WireType.LengthDelim : primitive.wireType,
isMessage,
isRepeated: !!repeated,
isOptional: optional,
explicitPresence: marker.explicitPresence,
});
}
fields.sort((a, b) => a.fieldNumber - b.fieldNumber);
return name;
}
}
+249
View File
@@ -0,0 +1,249 @@
import ts from 'typescript';
import { fail, type DeclarationRef } from '../source/context.js';
import type { SchemaResolver } from './resolver.js';
import { value, type TypeEnvironment, type TypeValue } from './types.js';
export class ObjectTypes {
private readonly types = new Map<string, TypeValue>();
private readonly aliases = new Set<string>();
private readonly concrete = new WeakMap<ts.Node, TypeValue>();
private readonly bases = new Set<string>();
constructor(private readonly resolver: SchemaResolver) {}
declaration(
ref: DeclarationRef,
args: readonly ts.TypeNode[],
caller: ts.SourceFile,
env: TypeEnvironment,
origin: ts.TypeNode,
heritage = false,
): TypeValue {
const node = ref.node;
if (
!ts.isInterfaceDeclaration(node) &&
!ts.isTypeAliasDeclaration(node) &&
!ts.isClassDeclaration(node)
) {
fail(origin, 'Expected an interface, type alias or class schema.');
}
const concrete = !node.typeParameters?.length && ts.isSourceFile(node.parent);
const previous = concrete && this.concrete.get(node);
if (previous && heritage && this.bases.has(previous.key)) {
fail(origin, 'Circular schema inheritance.');
}
if (previous) {
return previous;
}
const local = this.resolver.arguments(node.typeParameters, args, caller, env, node);
for (let scope = node.parent; scope; scope = scope.parent) {
if (!ts.isFunctionLike(scope) && !ts.isClassDeclaration(scope)) {
continue;
}
for (const parameter of scope.typeParameters ?? []) {
const name = parameter.name.text;
if (!local.has(name)) {
local.set(name, env.get(name) ?? this.resolver.parameter(name, scope));
}
}
}
const parameters = [...local.values()];
const key = `${ref.source.fileName}:${node.pos}<${parameters.map((type) => type.key).join(',')}>`;
if (heritage && this.bases.has(key)) {
fail(origin, 'Circular schema inheritance.');
}
if (heritage && this.bases.size >= 128) {
fail(origin, 'Schema inheritance exceeds 128 levels.');
}
const cached = this.types.get(key);
if (cached) {
return cached;
}
if (ts.isTypeAliasDeclaration(node)) {
if (ts.isTypeLiteralNode(node.type)) {
const result = this.object(
node.name.text + parameters.map((type) => '__' + type.name).join(''),
key,
);
result.origin = { node: origin, source: caller, env: new Map(env) };
if (parameters.length) {
result.application = { declaration: node, arguments: parameters };
}
this.types.set(key, result);
if (concrete) {
this.concrete.set(node, result);
}
return this.members(node.type.members, result, ref.source, local);
}
if (this.aliases.has(key)) {
fail(node, 'Circular type alias.');
}
this.aliases.add(key);
try {
const result = this.resolver.type(node.type, ref.source, local);
this.types.set(key, result);
if (concrete) {
this.concrete.set(node, result);
}
return result;
} finally {
this.aliases.delete(key);
}
}
const name =
(node.name?.text ?? 'Default') + parameters.map((type) => '__' + type.name).join('');
const result = this.object(name, key);
result.dynamic = parameters.some((type) => type.dynamic);
if (parameters.length) {
result.application = { declaration: node, arguments: parameters };
}
result.origin = { node: origin, source: caller, env: new Map(env) };
this.types.set(key, result);
if (concrete) {
this.concrete.set(node, result);
}
this.bases.add(key);
try {
for (const clause of node.heritageClauses ?? []) {
if (clause.token !== ts.SyntaxKind.ExtendsKeyword) {
continue;
}
for (const base of clause.types) {
const declaration = this.resolver.context.reference(
base.expression,
ref.source,
true,
);
if (!declaration) {
fail(base, 'Unresolved base schema.');
}
this.merge(
result,
this.declaration(
declaration,
base.typeArguments ?? [],
ref.source,
local,
origin,
true,
),
base,
);
}
}
} finally {
this.bases.delete(key);
}
return this.members(node.members, result, ref.source, local);
}
members(
members: ts.NodeArray<ts.TypeElement | ts.ClassElement>,
result: TypeValue,
source: ts.SourceFile,
env: TypeEnvironment,
): TypeValue {
const fields = members.flatMap<ts.TypeElement | ts.ClassElement | ts.ParameterDeclaration>(
(member) =>
ts.isConstructorDeclaration(member)
? member.parameters.filter((parameter) =>
parameter.modifiers?.some((modifier) =>
[
ts.SyntaxKind.PublicKeyword,
ts.SyntaxKind.PrivateKeyword,
ts.SyntaxKind.ProtectedKeyword,
ts.SyntaxKind.ReadonlyKeyword,
].includes(modifier.kind),
),
)
: [member],
);
for (const member of fields) {
if (
!ts.isPropertySignature(member) &&
!ts.isPropertyDeclaration(member) &&
!ts.isParameter(member)
) {
continue;
}
if (
member.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.StaticKeyword)
) {
continue;
}
if (!member.type || !member.name || ts.isComputedPropertyName(member.name)) {
fail(member, 'Schema fields require static names and explicit field markers.');
}
const name =
ts.isIdentifier(member.name) ||
ts.isStringLiteral(member.name) ||
ts.isNumericLiteral(member.name)
? member.name.text
: fail(member, 'Unsupported field name.');
const type = this.resolver.type(member.type, source, env);
result.fields!.set(name, { type, optional: !!member.questionToken, node: member });
result.dynamic ||= type.dynamic;
}
return result;
}
merge(target: TypeValue, source: TypeValue, node: ts.Node): void {
if (!source.fields) {
fail(node, 'Schema intersections and bases must be object types.');
}
for (const [name, property] of source.fields) {
const existing = target.fields!.get(name);
if (existing && existing.type.key !== property.type.key) {
fail(node, `Conflicting inherited field ${name}.`);
}
target.fields!.set(name, property);
}
target.dynamic ||= source.dynamic;
}
object(name: string, key: string): TypeValue {
return { ...value('object', name, key), fields: new Map() };
}
}
+246
View File
@@ -0,0 +1,246 @@
import ts from 'typescript';
import { fail } from '../source/context.js';
import type { SchemaResolver } from './resolver.js';
import { assignable } from './relations.js';
import { value, type TypeEnvironment, type TypeValue } from './types.js';
const utilities = new Set([
'Promise',
'Awaited',
'ReturnType',
'Parameters',
'InstanceType',
'ConstructorParameters',
'Extract',
'Exclude',
'Uppercase',
'Lowercase',
'Capitalize',
'Uncapitalize',
]);
function container(kind: TypeValue['kind'], values: TypeValue[]): TypeValue {
return {
kind,
values,
key: `${kind}<${values.map((type) => type.key)}>`,
name: kind,
dynamic: values.some((type) => type.dynamic),
};
}
export function resolveOperator(
node: ts.TypeNode,
source: ts.SourceFile,
env: TypeEnvironment,
resolver: SchemaResolver,
): TypeValue | undefined {
if (
ts.isTypeReferenceNode(node) &&
(!ts.isIdentifier(node.typeName) || !utilities.has(node.typeName.text))
) {
return;
}
const resolve = (type: ts.TypeNode) => resolver.type(type, type.getSourceFile(), env);
if (ts.isInferTypeNode(node)) {
return value('inference', node.typeParameter.name.text);
}
if (ts.isTupleTypeNode(node)) {
return container(
'tuple',
node.elements.map((type) => resolve(ts.isNamedTupleMember(type) ? type.type : type)),
);
}
if (ts.isOptionalTypeNode(node)) {
return container('union', [resolve(node.type), value('null', 'undefined')]);
}
if (ts.isRestTypeNode(node)) {
return resolve(node.type);
}
if (ts.isFunctionTypeNode(node) || ts.isConstructorTypeNode(node)) {
const local = new Map(env);
for (const param of node.typeParameters ?? []) {
local.set(param.name.text, resolver.parameter(param.name.text, node));
}
const parameters = node.parameters.filter(
(param) => !ts.isIdentifier(param.name) || param.name.text !== 'this',
);
return container(ts.isFunctionTypeNode(node) ? 'function' : 'constructor', [
container(
'tuple',
parameters.map((param) =>
param.type
? resolver.type(param.type, source, local)
: value('primitive', 'unknown'),
),
),
resolver.type(node.type, source, local),
]);
}
if (ts.isTypeQueryNode(node)) {
const ref = ts.isIdentifier(node.exprName)
? resolver.context.lookup(node.exprName.text, node.exprName, source)
: resolver.context.typeName(node.exprName, source);
const declaration = ref?.node;
if (declaration && (ts.isVariableDeclaration(declaration) || ts.isParameter(declaration))) {
if (declaration.type) {
return resolve(declaration.type);
}
const initializer = declaration.initializer;
if (
initializer &&
(ts.isAsExpression(initializer) || ts.isSatisfiesExpression(initializer))
) {
return resolve(initializer.type);
}
}
if (declaration && ts.isFunctionDeclaration(declaration) && declaration.type) {
return container('function', [
container(
'tuple',
declaration.parameters.map((param) =>
param.type ? resolve(param.type) : value('primitive', 'unknown'),
),
),
resolve(declaration.type),
]);
}
fail(
node,
'Type queries used in schemas require an explicit variable or function return annotation.',
);
}
if (ts.isTemplateLiteralTypeNode(node)) {
let strings = [node.head.text];
for (const span of node.templateSpans) {
const type = resolve(span.type);
if (type.dynamic) {
return resolver.defer(node, source, env);
}
const options = type.kind === 'union' ? type.values! : [type];
if (options.some((type) => type.kind !== 'literal')) {
fail(node, 'Template schema keys require literal types.');
}
strings = strings.flatMap((prefix) =>
options.map((type) => prefix + type.name + span.literal.text),
);
if (strings.length > 128) {
fail(node, 'Template type expansion exceeds 128 keys.');
}
}
const literals = strings.map((text) => value('literal', text, JSON.stringify(text)));
return literals.length === 1 ? literals[0] : container('union', literals);
}
if (!ts.isTypeReferenceNode(node) || !ts.isIdentifier(node.typeName)) {
return;
}
const name = node.typeName.text;
if (!utilities.has(name) || resolver.context.typeName(node.typeName, source)) {
return;
}
const args = node.typeArguments;
if (!args?.length) {
fail(node, `${name} requires a type argument.`);
}
const operand = resolve(args[0]);
if (name === 'Promise') {
return container('promise', [operand]);
}
if (operand.dynamic) {
return resolver.defer(node, source, env);
}
if (name === 'Awaited') {
const unwrap = (type: TypeValue): TypeValue =>
type.kind === 'promise'
? unwrap(type.values![0])
: type.kind === 'union'
? container('union', type.values!.map(unwrap))
: type;
return unwrap(operand);
}
if (['ReturnType', 'Parameters', 'InstanceType', 'ConstructorParameters'].includes(name)) {
const expected =
name === 'InstanceType' || name === 'ConstructorParameters'
? 'constructor'
: 'function';
if (operand.kind !== expected) {
fail(node, `${name} requires a ${expected} type.`);
}
return operand.values![name.endsWith('Parameters') ? 0 : 1];
}
if (name === 'Extract' || name === 'Exclude') {
if (!args[1]) {
fail(node, `${name} requires two type arguments.`);
}
const constraint = resolve(args[1]);
if (constraint.dynamic) {
return resolver.defer(node, source, env);
}
const selected = (operand.kind === 'union' ? operand.values! : [operand]).filter(
(type) => assignable(type, constraint) === (name === 'Extract'),
);
return selected.length === 0
? value('primitive', 'never')
: selected.length === 1
? selected[0]
: container('union', selected);
}
const transform = (type: TypeValue): TypeValue => {
if (type.kind !== 'literal' || !/^["']/.test(type.key)) {
fail(node, `${name} requires literal string keys.`);
}
const text =
name === 'Uppercase'
? type.name.toUpperCase()
: name === 'Lowercase'
? type.name.toLowerCase()
: (name === 'Capitalize'
? (type.name[0] ?? '').toUpperCase()
: (type.name[0] ?? '').toLowerCase()) + type.name.slice(1);
return value('literal', text, JSON.stringify(text));
};
return operand.kind === 'union'
? container('union', operand.values!.map(transform))
: transform(operand);
}
+137
View File
@@ -0,0 +1,137 @@
import type { TypeValue } from './types.js';
export function assignable(
source: TypeValue,
target: TypeValue,
seen = new Set<string>(),
): boolean {
if (
source.key === target.key ||
target.name === 'unknown' ||
target.name === 'any' ||
source.name === 'never'
) {
return true;
}
if (target.name === 'object') {
return (
!!source.fields ||
['array', 'tuple', 'function', 'constructor', 'promise'].includes(source.kind)
);
}
const key = `${source.key}:${target.key}`;
if (seen.has(key)) {
return true;
}
seen.add(key);
if (source.kind === 'marker') {
return assignable(source.values![0], target, seen);
}
if (target.kind === 'marker') {
return assignable(source, target.values![0], seen);
}
if (source.kind === 'union') {
return source.values!.every((type) => assignable(type, target, new Set(seen)));
}
if (target.kind === 'union') {
return target.values!.some((type) => assignable(source, type, new Set(seen)));
}
if (source.kind === target.kind && source.values && target.values) {
return (
source.values.length === target.values.length &&
source.values.every((type, index) => assignable(type, target.values![index], seen))
);
}
if (source.fields && target.fields) {
return [...target.fields].every(([name, field]) => {
const actual = source.fields!.get(name);
return actual
? (field.optional || !actual.optional) && assignable(actual.type, field.type, seen)
: field.optional;
});
}
if (target.kind === 'primitive' && source.kind === 'literal') {
return target.name === 'string'
? /^["']/.test(source.key)
: target.name === 'number'
? !Number.isNaN(Number(source.name))
: target.name === 'bool' && /^(true|false)$/.test(source.name);
}
if (target.name === 'number') {
return /^(?:u?int_32|sint_32|s?fixed_32|float|double)$/.test(source.name);
}
if (target.name === 'bigint') {
return /^(?:u?int_64|sint_64|s?fixed_64)$/.test(source.name);
}
return false;
}
export function matchInferred(
source: TypeValue,
pattern: TypeValue,
inferred: Map<string, TypeValue>,
seen = new Set<string>(),
): boolean {
if (pattern.kind === 'inference') {
const previous = inferred.get(pattern.name);
if (previous && previous.key !== source.key) {
return false;
}
inferred.set(pattern.name, source);
return true;
}
const key = `${source.key}:${pattern.key}`;
if (seen.has(key)) {
return true;
}
seen.add(key);
if (source.kind === 'function' && pattern.kind === 'function') {
const args = pattern.values![0].values!;
const variadicAny =
args.length === 1 && args[0].kind === 'array' && args[0].values![0].name === 'any';
return (
(variadicAny || matchInferred(source.values![0], pattern.values![0], inferred, seen)) &&
matchInferred(source.values![1], pattern.values![1], inferred, seen)
);
}
if (source.fields && pattern.fields) {
return [...pattern.fields].every(([name, property]) => {
const actual = source.fields!.get(name);
return actual
? matchInferred(actual.type, property.type, inferred, seen)
: property.optional;
});
}
if (source.kind === pattern.kind && source.values && pattern.values) {
return (
source.values.length === pattern.values.length &&
source.values.every((type, index) =>
matchInferred(type, pattern.values![index], inferred, seen),
)
);
}
return assignable(source, pattern);
}
+600
View File
@@ -0,0 +1,600 @@
import { packageName } from '../package.js';
import ts from 'typescript';
import { SourceContext, fail, runtimeImportName } from '../source/context.js';
import { PRIMITIVE_TYPE_MAP } from '../codegen/model.js';
import { value, type TypeEnvironment, type TypeValue } from './types.js';
import { MessageBuilder } from './message.js';
import { matchInferred } from './relations.js';
import { resolveOperator } from './operators.js';
import { ObjectTypes } from './objects.js';
const primitiveNames = new Set(Object.keys(PRIMITIVE_TYPE_MAP));
/** Lazily resolves only types reached by codec calls; no project-wide type checker. */
export class SchemaResolver {
private readonly messages = new MessageBuilder();
readonly registry = this.messages.registry;
private readonly objects = new ObjectTypes(this);
private depth = 0;
private readonly resolvedLazy = new WeakMap<TypeValue, TypeValue>();
constructor(readonly context: SourceContext) {}
parameter(name: string, owner: ts.Node): TypeValue {
return value('parameter', name, `${owner.getSourceFile().fileName}:${owner.pos}:${name}`);
}
substitute(type: TypeValue, bindings: Map<string, TypeValue>): TypeValue {
if (type.kind === 'lazy') {
const { node, source, env } = type.origin!;
return this.lazy(
node,
source,
new Map([...env].map(([name, val]) => [name, this.substitute(val, bindings)])),
);
}
if (!type.dynamic) {
return type;
}
if (type.kind === 'parameter') {
return bindings.get(type.key) ?? type;
}
if (type.origin) {
const { node, source, env } = type.origin;
return this.type(
node,
source,
new Map([...env].map(([name, val]) => [name, this.substitute(val, bindings)])),
);
}
return type;
}
type(
node: ts.TypeNode,
source = node.getSourceFile(),
env: TypeEnvironment = new Map(),
): TypeValue {
if (++this.depth > 128) {
this.depth--;
return fail(
node,
'Type expansion exceeds 128 levels (possibly an expanding recursive generic).',
);
}
try {
const result = this.resolve(node, source, env);
if (result.dynamic && result.kind !== 'parameter' && !result.origin) {
result.origin = { node, source, env: new Map(env) };
}
return result;
} finally {
this.depth--;
}
}
arguments(
params: readonly ts.TypeParameterDeclaration[] | undefined,
args: readonly ts.TypeNode[] | undefined,
source: ts.SourceFile,
outer: TypeEnvironment,
declaration: ts.Node,
lazy = false,
): TypeEnvironment {
const result = new Map<string, TypeValue>();
if ((args?.length ?? 0) > (params?.length ?? 0)) {
fail(declaration, 'Too many generic type arguments.');
}
for (let i = 0; i < (params?.length ?? 0); i++) {
const param = params![i];
const arg = args?.[i];
const resolved = arg
? lazy
? this.lazy(arg, source, outer)
: this.type(arg, source, outer)
: param.default
? lazy
? this.lazy(param.default, declaration.getSourceFile(), result)
: this.type(param.default, declaration.getSourceFile(), result)
: undefined;
if (!resolved) {
fail(declaration, `Missing concrete type argument for ${param.name.text}.`);
}
result.set(param.name.text, resolved);
}
return result;
}
message(type: TypeValue, node: ts.Node): string {
return this.messages.build(this.materialize(type), node);
}
/** Receiver discovery carries application types without expanding them until
* a protobuf requirement actually consumes the binding. */
lazy(node: ts.TypeNode, source: ts.SourceFile, env: TypeEnvironment): TypeValue {
if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) {
const bound = env.get(node.typeName.text);
if (bound) {
return bound;
}
if (primitiveNames.has(node.typeName.text)) {
return this.type(node, source, env);
}
}
const mentionsParameter = (child: ts.Node): boolean =>
(ts.isIdentifier(child) && env.get(child.text)?.dynamic === true) ||
(ts.forEachChild(child, mentionsParameter) ?? false);
return {
...value(
'lazy',
node.getText(source),
`lazy:${source.fileName}:${node.getText(source)}<${[...env.values()].map((v) => v.key)}>`,
),
dynamic: mentionsParameter(node),
origin: { node, source, env: new Map(env) },
};
}
private materialize(type: TypeValue): TypeValue {
if (type.kind !== 'lazy') {
return type;
}
const cached = this.resolvedLazy.get(type);
if (cached) {
return cached;
}
const { node, source, env } = type.origin!;
const resolved = this.type(node, source, env);
this.resolvedLazy.set(type, resolved);
return resolved;
}
private resolve(node: ts.TypeNode, source: ts.SourceFile, env: TypeEnvironment): TypeValue {
if (ts.isTypeReferenceNode(node)) {
return this.reference(node, source, env);
}
const operator = resolveOperator(node, source, env, this);
if (operator) {
return operator;
}
if (ts.isParenthesizedTypeNode(node)) {
return this.type(node.type, source, env);
}
if (node.kind === ts.SyntaxKind.StringKeyword) {
return value('primitive', 'string');
}
if (node.kind === ts.SyntaxKind.BooleanKeyword) {
return value('primitive', 'bool');
}
if (
[
ts.SyntaxKind.ObjectKeyword,
ts.SyntaxKind.NumberKeyword,
ts.SyntaxKind.BigIntKeyword,
ts.SyntaxKind.AnyKeyword,
ts.SyntaxKind.UnknownKeyword,
ts.SyntaxKind.NeverKeyword,
].includes(node.kind)
) {
return value('primitive', node.getText(source));
}
if (
node.kind === ts.SyntaxKind.UndefinedKeyword ||
node.kind === ts.SyntaxKind.VoidKeyword
) {
return value('null', 'undefined');
}
if (ts.isLiteralTypeNode(node)) {
if (node.literal.kind === ts.SyntaxKind.NullKeyword) {
return value('null', 'null');
}
if (ts.isStringLiteral(node.literal)) {
return value('literal', node.literal.text, JSON.stringify(node.literal.text));
}
return value('literal', node.literal.getText(source));
}
if (ts.isArrayTypeNode(node)) {
return this.container(
'array',
[this.type(node.elementType, source, env)],
node,
source,
env,
);
}
if (ts.isUnionTypeNode(node)) {
const members = [
...new Map(
node.types
.flatMap((item) => {
const type = this.type(item, source, env);
return type.kind === 'union' ? type.values! : [type];
})
.map((item) => [item.key, item]),
).values(),
];
return members.length === 1
? members[0]
: this.container('union', members, node, source, env);
}
if (ts.isIntersectionTypeNode(node)) {
const members = node.types.map((item) => this.type(item, source, env));
if (members.some((item) => item.dynamic && item.kind !== 'object')) {
return this.defer(node, source, env);
}
const result = this.objects.object(
'Intersection',
members.map((item) => item.key).join('&'),
);
for (const member of members) {
this.objects.merge(result, member, node);
}
return result;
}
if (ts.isTypeLiteralNode(node)) {
return this.objects.members(
node.members,
this.objects.object(
'Anonymous',
`${source.fileName}:${node.pos}<${[...env.values()].map((type) => type.key)}>`,
),
source,
env,
);
}
if (ts.isTypeOperatorNode(node)) {
const operand = this.type(node.type, source, env);
if (node.operator === ts.SyntaxKind.ReadonlyKeyword) {
return operand;
}
if (operand.dynamic && !operand.fields) {
return this.defer(node, source, env);
}
if (node.operator === ts.SyntaxKind.KeyOfKeyword && operand.fields) {
return this.container(
'union',
[...operand.fields.keys()].map((key) =>
value('literal', key, JSON.stringify(key)),
),
node,
source,
env,
);
}
}
if (ts.isIndexedAccessTypeNode(node)) {
const object = this.type(node.objectType, source, env);
const index = this.type(node.indexType, source, env);
if (object.dynamic || index.dynamic) {
return this.defer(node, source, env);
}
const keys = index.kind === 'union' ? index.values! : [index];
const values = keys.map(
(key) =>
object.fields?.get(key.name)?.type ??
(object.kind === 'tuple'
? object.values?.[Number(key.name)]
: object.kind === 'array'
? object.values?.[0]
: undefined) ??
fail(node, `Unknown indexed property ${key.name}.`),
);
return values.length === 1
? values[0]
: this.container('union', values, node, source, env);
}
if (ts.isConditionalTypeNode(node)) {
const check = this.type(node.checkType, source, env);
const constraint = this.type(node.extendsType, source, env);
if (check.dynamic || constraint.dynamic) {
return this.defer(node, source, env);
}
if (
check.kind === 'union' &&
ts.isTypeReferenceNode(node.checkType) &&
ts.isIdentifier(node.checkType.typeName) &&
env.has(node.checkType.typeName.text)
) {
const results = check.values!.map((type) =>
this.type(
node,
source,
new Map(env).set(
(node.checkType as ts.TypeReferenceNode).typeName.getText(source),
type,
),
),
);
const distinct = [...new Map(results.map((type) => [type.key, type])).values()];
return distinct.length === 1
? distinct[0]
: this.container('union', distinct, node, source, env);
}
const inferred = new Map<string, TypeValue>();
const matches = matchInferred(check, constraint, inferred);
return this.type(
matches ? node.trueType : node.falseType,
source,
new Map([...env, ...inferred]),
);
}
if (ts.isMappedTypeNode(node) && node.type && node.typeParameter.constraint) {
const keys = this.type(node.typeParameter.constraint, source, env);
if (keys.dynamic) {
return this.defer(node, source, env);
}
const result = this.objects.object(
'Mapped',
`${source.fileName}:${node.pos}<${[...env.values()].map((v) => v.key)}>`,
);
for (const key of keys.kind === 'union' ? keys.values! : [keys]) {
const local = new Map(env).set(node.typeParameter.name.text, key);
const remapped = node.nameType ? this.type(node.nameType, source, local) : key;
if (remapped.name === 'never') {
continue;
}
const inherited = ts.isIndexedAccessTypeNode(node.type)
? (this.type(node.type.objectType, source, local).fields?.get(key.name)
?.optional ?? false)
: false;
const optional = node.questionToken
? node.questionToken.kind !== ts.SyntaxKind.MinusToken
: inherited;
for (const name of remapped.kind === 'union' ? remapped.values! : [remapped]) {
result.fields!.set(name.name, {
type: this.type(node.type, source, local),
optional,
node,
});
}
}
return result;
}
fail(node, `Unsupported or ambiguous type expression ${node.getText(source)}.`);
}
private reference(
node: ts.TypeReferenceNode,
source: ts.SourceFile,
env: TypeEnvironment,
): TypeValue {
const simple = ts.isIdentifier(node.typeName) ? node.typeName.text : undefined;
if (simple && env.has(simple)) {
return this.materialize(env.get(simple)!);
}
const operator = resolveOperator(node, source, env, this);
if (operator) {
return operator;
}
const ref = this.context.typeName(node.typeName, source);
let name = simple
? (ref && runtimeImportName(ref.node)) || simple
: node.typeName.getText(source);
if (ts.isQualifiedName(node.typeName) && ts.isIdentifier(node.typeName.left)) {
const namespace = this.context.lookup(node.typeName.left.text, node, source, true);
if (
namespace &&
ts.isNamespaceImport(namespace.node) &&
(namespace.node.parent.parent.moduleSpecifier as ts.StringLiteral).text ===
packageName
) {
name = node.typeName.right.text;
}
}
const args = node.typeArguments ?? [];
if (
ref &&
(ts.isImportSpecifier(ref.node) || ts.isImportClause(ref.node)) &&
!runtimeImportName(ref.node)
) {
fail(node, `Unresolved imported type ${name}.`);
}
if (
ref &&
!runtimeImportName(ref.node) &&
!ts.isImportSpecifier(ref.node) &&
!ts.isNamespaceImport(ref.node)
) {
return this.objects.declaration(ref, args, source, env, node);
}
if (primitiveNames.has(name)) {
return value('primitive', name);
}
if (name === 'pb' || name === 'pb_repeated' || name === 'pb_optional') {
if (args.length !== 2) {
fail(node, `${name} requires a field number and a field type.`);
}
const fieldNumber = this.type(args[0], source, env);
const payload = this.type(args[1], source, env);
const marker = this.container('marker', [payload], node, source, env);
return {
...marker,
key: `${name}:${marker.key}:${fieldNumber.key}`,
dynamic: fieldNumber.dynamic || marker.dynamic,
fieldNumber: Number(fieldNumber.name),
repeated: name === 'pb_repeated',
explicitPresence: name === 'pb_optional',
};
}
if (name === 'Array' || name === 'ReadonlyArray') {
return this.container('array', [this.type(args[0], source, env)], node, source, env);
}
if (['Partial', 'Required', 'Readonly', 'Pick', 'Omit', 'NonNullable'].includes(name)) {
const operand = this.type(args[0], source, env);
if (operand.dynamic) {
return this.defer(node, source, env);
}
if (name === 'Readonly') {
return operand;
}
if (name === 'NonNullable') {
const members =
operand.kind === 'union'
? operand.values!.filter((item) => item.kind !== 'null')
: [operand];
return members.length === 1
? members[0]
: this.container('union', members, node, source, env);
}
if (!operand.fields) {
fail(node, `${name} requires an object type.`);
}
const keys = args[1] ? this.type(args[1], source, env) : undefined;
const selected = new Set(
keys ? (keys.kind === 'union' ? keys.values! : [keys]).map((key) => key.name) : [],
);
if (name === 'Pick') {
for (const key of selected) {
if (!operand.fields.has(key)) {
fail(node, `Unknown Pick property ${key}.`);
}
}
}
const result = this.objects.object(
`${name}__${operand.name}`,
`${name}<${operand.key},${keys?.key ?? ''}>`,
);
for (const [key, property] of operand.fields) {
if (
(name === 'Pick' && !selected.has(key)) ||
(name === 'Omit' && selected.has(key))
) {
continue;
}
result.fields!.set(key, {
...property,
optional: name === 'Partial' || (name !== 'Required' && property.optional),
});
}
return result;
}
if (ref) {
return this.objects.declaration(ref, args, source, env, node);
}
fail(node, `Unresolved type ${name}.`);
}
defer(node: ts.TypeNode, source: ts.SourceFile, env: TypeEnvironment): TypeValue {
return {
...value(
'deferred',
node.getText(source),
`${source.fileName}:${node.pos}<${[...env.values()].map((v) => v.key)}>`,
),
dynamic: true,
origin: { node, source, env: new Map(env) },
};
}
private container(
kind: TypeValue['kind'],
values: TypeValue[],
node: ts.TypeNode,
source: ts.SourceFile,
env: TypeEnvironment,
): TypeValue {
if (kind === 'union') {
values = values.filter((type) => type.name !== 'never');
if (!values.length) {
return value('primitive', 'never');
}
if (values.length === 1) {
return values[0];
}
}
return {
kind,
name: values.map((type) => type.name).join('__'),
key: `${kind}<${JSON.stringify(values.map((type) => type.key))}>`,
values,
dynamic: values.some((type) => type.dynamic),
origin: { node, source, env: new Map(env) },
};
}
}
+38
View File
@@ -0,0 +1,38 @@
import type ts from 'typescript';
export interface TypeValue {
kind:
| 'primitive'
| 'literal'
| 'null'
| 'parameter'
| 'object'
| 'marker'
| 'union'
| 'array'
| 'tuple'
| 'function'
| 'constructor'
| 'promise'
| 'inference'
| 'lazy'
| 'deferred';
key: string;
name: string;
dynamic: boolean;
fields?: Map<string, { type: TypeValue; optional: boolean; node: ts.Node }>;
values?: TypeValue[];
fieldNumber?: number;
repeated?: boolean;
explicitPresence?: boolean;
origin?: { node: ts.TypeNode; source: ts.SourceFile; env: TypeEnvironment };
application?: { declaration: ts.Declaration; arguments: TypeValue[] };
}
export type TypeEnvironment = Map<string, TypeValue>;
export const value = (kind: TypeValue['kind'], name: string, key = name): TypeValue => ({
kind,
key,
name,
dynamic: kind === 'parameter',
});
+423
View File
@@ -0,0 +1,423 @@
import { packageName } from '../package.js';
import ts from 'typescript';
import { readFileSync, statSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
export interface DeclarationRef {
node: ts.Declaration;
source: ts.SourceFile;
}
export function runtimeImportName(node: ts.Declaration): string | undefined {
const declaration = ts.isImportSpecifier(node)
? node.parent.parent.parent
: ts.isExportSpecifier(node)
? node.parent.parent
: undefined;
if (
declaration?.moduleSpecifier &&
ts.isStringLiteral(declaration.moduleSpecifier) &&
declaration.moduleSpecifier.text === packageName
) {
return (
(node as ts.ImportSpecifier | ts.ExportSpecifier).propertyName?.text ??
(node as ts.ImportSpecifier | ts.ExportSpecifier).name.text
);
}
return;
}
const extensions = ['.ts', '.tsx', '.mts', '.cts', '/index.ts', '/index.tsx'];
export const normalizePath = (path: string): string => resolve(path).replace(/\\/g, '/');
/** One parse per source revision, shared by schema and generic-call analysis. */
export class SourceContext {
readonly files = new Map<string, ts.SourceFile>();
revision = 0;
private readonly modules = new Map<string, string | null>();
private readonly names = new WeakMap<ts.Node, Map<string, ts.Declaration>>();
private readonly typeNames = new WeakMap<ts.Node, Map<string, ts.Declaration>>();
private readonly options = new Map<string, ts.CompilerOptions>();
clear(): void {
this.files.clear();
this.modules.clear();
this.options.clear();
}
source(path: string, code?: string): ts.SourceFile {
const key = normalizePath(path);
const cached = this.files.get(key);
if (cached && (code === undefined || cached.text === code)) {
return cached;
}
if (cached) {
this.revision++;
}
const source = ts.createSourceFile(
key,
code ?? readFileSync(key, 'utf8'),
ts.ScriptTarget.Latest,
true,
);
this.files.set(key, source);
return source;
}
module(specifier: string, source: ts.SourceFile): ts.SourceFile | undefined {
if (specifier === packageName) {
return;
}
const key = `${source.fileName}:${specifier}`;
let path = this.modules.get(key);
if (path === undefined) {
if (specifier.startsWith('.')) {
const base = normalizePath(resolve(dirname(source.fileName), specifier));
const stem = base.replace(/\.(?:mjs|cjs|js)$/, '');
path =
[base, ...extensions.map((ext) => stem + ext)].find((candidate) => {
try {
return statSync(candidate).isFile();
} catch {
return false;
}
}) ?? null;
} else {
const directory = dirname(source.fileName);
let options = this.options.get(directory);
if (!options) {
const config = ts.findConfigFile(directory, ts.sys.fileExists);
options = config ? this.options.get(config) : undefined;
options ??= config
? ts.parseJsonConfigFileContent(
ts.readConfigFile(config, ts.sys.readFile).config,
{ ...ts.sys, readDirectory: () => [] },
dirname(config),
).options
: {};
if (config) {
this.options.set(config, options);
}
this.options.set(directory, options);
}
path =
ts.resolveModuleName(specifier, source.fileName, options, ts.sys).resolvedModule
?.resolvedFileName ?? null;
}
this.modules.set(key, path);
}
return path ? this.source(path) : undefined;
}
lookup(
name: string,
location: ts.Node,
source = location.getSourceFile(),
typeOnly = false,
): DeclarationRef | undefined {
for (let scope: ts.Node | undefined = location; scope; scope = scope.parent) {
if (!typeOnly && ts.isFunctionLike(scope)) {
const parameter = scope.parameters.find(
(param) => ts.isIdentifier(param.name) && param.name.text === name,
);
if (parameter) {
return { node: parameter, source };
}
for (const param of scope.parameters) {
if (!ts.isObjectBindingPattern(param.name)) {
continue;
}
const element = param.name.elements.find(
(element) => ts.isIdentifier(element.name) && element.name.text === name,
);
if (element) {
return { node: element, source };
}
}
}
if (!ts.isSourceFile(scope) && !ts.isBlock(scope) && !ts.isModuleBlock(scope)) {
continue;
}
const declaration = this.declarations(scope, typeOnly).get(name);
if (declaration) {
return this.follow(declaration, source, new Set(), typeOnly);
}
}
const declaration = this.declarations(source, typeOnly).get(name);
return declaration ? this.follow(declaration, source, new Set(), typeOnly) : undefined;
}
typeName(name: ts.EntityName, source: ts.SourceFile): DeclarationRef | undefined {
return this.reference(name, source, true);
}
reference(
name: ts.EntityName | ts.Expression,
source: ts.SourceFile,
typeOnly = false,
): DeclarationRef | undefined {
if (ts.isIdentifier(name)) {
return this.lookup(name.text, name, source, typeOnly);
}
if (!ts.isQualifiedName(name) && !ts.isPropertyAccessExpression(name)) {
return;
}
const left = this.reference(
ts.isQualifiedName(name) ? name.left : name.expression,
source,
typeOnly,
);
const right = ts.isQualifiedName(name) ? name.right : name.name;
if (!left) {
return;
}
if (ts.isNamespaceImport(left.node)) {
const declaration = left.node.parent.parent;
const imported = this.module(
(declaration.moduleSpecifier as ts.StringLiteral).text,
left.source,
);
return imported ? this.exported(right.text, imported, new Set(), typeOnly) : undefined;
}
if (
ts.isModuleDeclaration(left.node) &&
left.node.body &&
ts.isModuleBlock(left.node.body)
) {
const declaration = this.declarations(left.node.body, typeOnly).get(right.text);
return declaration ? { node: declaration, source: left.source } : undefined;
}
return;
}
private declarations(
scope: ts.SourceFile | ts.Block | ts.ModuleBlock,
typeOnly = false,
): Map<string, ts.Declaration> {
const cache = typeOnly ? this.typeNames : this.names;
let names = cache.get(scope);
if (names) {
return names;
}
names = new Map();
for (const statement of scope.statements) {
if (ts.isVariableStatement(statement)) {
if (typeOnly) {
continue;
}
for (const declaration of statement.declarationList.declarations) {
if (ts.isIdentifier(declaration.name)) {
names.set(declaration.name.text, declaration);
} else if (ts.isObjectBindingPattern(declaration.name)) {
for (const element of declaration.name.elements) {
if (ts.isIdentifier(element.name)) {
names.set(element.name.text, element);
}
}
}
}
} else if (ts.isImportDeclaration(statement)) {
const clause = statement.importClause;
if (clause?.name) {
names.set(clause.name.text, clause);
}
const bindings = clause?.namedBindings;
if (bindings && ts.isNamedImports(bindings)) {
for (const binding of bindings.elements) {
names.set(binding.name.text, binding);
}
} else if (bindings) {
names.set(bindings.name.text, bindings);
}
} else if (
'name' in statement &&
statement.name &&
ts.isIdentifier(statement.name as ts.Node)
) {
if (typeOnly && ts.isFunctionDeclaration(statement)) {
continue;
}
if (
!typeOnly &&
(ts.isTypeAliasDeclaration(statement) || ts.isInterfaceDeclaration(statement))
) {
continue;
}
names.set(
(statement.name as ts.Identifier).text,
statement as unknown as ts.Declaration,
);
}
}
cache.set(scope, names);
return names;
}
private follow(
node: ts.Declaration,
source: ts.SourceFile,
seen: Set<ts.Node>,
typeOnly = false,
): DeclarationRef | undefined {
if (seen.has(node)) {
return;
}
seen.add(node);
if (ts.isImportSpecifier(node)) {
const declaration = node.parent.parent.parent;
const imported = this.module(
(declaration.moduleSpecifier as ts.StringLiteral).text,
source,
);
if (imported) {
return this.exported(
(node.propertyName ?? node.name).text,
imported,
seen,
typeOnly,
);
}
} else if (ts.isImportClause(node)) {
const imported = this.module(
(node.parent.moduleSpecifier as ts.StringLiteral).text,
source,
);
if (imported) {
return this.exported('default', imported, seen, typeOnly);
}
}
return { node, source };
}
exported(
name: string,
source: ts.SourceFile,
seen = new Set<ts.Node>(),
typeOnly = false,
): DeclarationRef | undefined {
const local = this.declarations(source, typeOnly).get(name);
if (local) {
return this.follow(local, source, seen, typeOnly);
}
for (const statement of source.statements) {
if (name === 'default') {
if (
(ts.isClassDeclaration(statement) ||
ts.isFunctionDeclaration(statement) ||
ts.isInterfaceDeclaration(statement)) &&
statement.modifiers?.some(
(modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword,
)
) {
return { node: statement, source };
}
if (ts.isExportAssignment(statement) && ts.isIdentifier(statement.expression)) {
return this.lookup(
statement.expression.text,
statement.expression,
source,
typeOnly,
);
}
}
if (!ts.isExportDeclaration(statement) || seen.has(statement)) {
continue;
}
seen.add(statement);
const imported =
statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier)
? this.module(statement.moduleSpecifier.text, source)
: source;
if (!imported) {
if (statement.exportClause && ts.isNamedExports(statement.exportClause)) {
const element = statement.exportClause.elements.find(
(element) => element.name.text === name,
);
if (element && runtimeImportName(element)) {
return { node: element, source };
}
}
continue;
}
if (!statement.exportClause) {
const ref = this.exported(name, imported, seen, typeOnly);
if (ref) {
return ref;
}
} else if (ts.isNamedExports(statement.exportClause)) {
const element = statement.exportClause.elements.find((el) => el.name.text === name);
if (element) {
return this.exported(
(element.propertyName ?? element.name).text,
imported,
seen,
typeOnly,
);
}
}
}
return;
}
}
export function fail(node: ts.Node, message: string): never {
const source = node.getSourceFile();
const position = source.getLineAndCharacterOfPosition(node.getStart(source));
throw new Error(
`[${packageName}] ${source.fileName}:${position.line + 1}:${position.character + 1}: ${message}`,
);
}
+43
View File
@@ -0,0 +1,43 @@
import { existsSync, readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import type { ResolvedConfig } from 'vite';
export function buildEntries(config: ResolvedConfig): string[] {
const input =
config.build.rolldownOptions.input ??
(config.build.lib && config.build.lib.entry) ??
'index.html';
const files =
typeof input === 'string' ? [input] : Array.isArray(input) ? input : Object.values(input);
return files.flatMap((file) => {
const path = resolve(config.root, file);
if (!existsSync(path)) {
return [];
}
if (/\.[cm]?[jt]sx?$/.test(path)) {
return [path];
}
if (!path.endsWith('.html')) {
return [];
}
return [
...readFileSync(path, 'utf8').matchAll(
/<script\b[^>]*\bsrc\s*=\s*["']([^"']+)["'][^>]*>/gi,
),
].flatMap(([, src]) => {
if (/^(?:[a-z]+:)?\/\//i.test(src)) {
return [];
}
const entry = resolve(
src.startsWith('/') ? config.root : resolve(path, '..'),
src.replace(/^\//, '').split('?')[0],
);
return /\.[cm]?[jt]sx?$/.test(entry) && existsSync(entry) ? [entry] : [];
});
});
}
-79
View File
@@ -1,79 +0,0 @@
import type { MessageRegistry } from '../ast/types.js';
import type { CallSiteRecord } from '../ast/analyzer.js';
import { createImportedTypeNameResolver, typeNodeToMangledName } from '../ast/utils.js';
import { collectProtobufImportBindings, matchProtobufCallSite } from '../ast/callsite.js';
import ts from 'typescript';
interface TextEdit {
start: number;
end: number;
replacement: string;
}
/**
* Apply replacements using pre-recorded call-sites from analyze().
* No parsing or AST walking — just position-based string edits.
*/
export function applyReplacements(
code: string,
sf: ts.SourceFile,
callSites: CallSiteRecord[],
registry: MessageRegistry,
): { transformedCode: string; hasReplacements: boolean } {
const edits: TextEdit[] = [];
const resolveImportedTypeName = createImportedTypeNameResolver(sf);
for (const cs of callSites) {
const mangled = typeNodeToMangledName(cs.firstTypeArg, sf, resolveImportedTypeName);
if (registry.has(mangled)) {
edits.push({
start: cs.exprStart,
end: cs.typeArgsEnd,
replacement: `${cs.fnName}_${mangled}`,
});
}
}
if (!edits.length) {
return { transformedCode: code, hasReplacements: false };
}
edits.sort((a, b) => b.start - a.start);
let result = code;
for (const ed of edits) {
result = result.slice(0, ed.start) + ed.replacement + result.slice(ed.end);
}
return { transformedCode: result, hasReplacements: true };
}
/**
* Backward-compatible: parses + walks on its own.
* Prefer applyReplacements() with pre-recorded call-sites from analyze().
*/
export function replaceCallSites(
code: string,
registry: MessageRegistry,
): { transformedCode: string; hasReplacements: boolean } {
const sf = ts.createSourceFile('input.ts', code, ts.ScriptTarget.Latest, true);
const callSites: CallSiteRecord[] = [];
const importBindings = collectProtobufImportBindings(sf);
ts.forEachChild(sf, function visit(node) {
if (ts.isCallExpression(node)) {
const cs = matchProtobufCallSite(node, sf, importBindings, {
allowLegacyUnboundCanonical: true,
});
if (cs) {
callSites.push(cs);
}
}
ts.forEachChild(node, visit);
});
return applyReplacements(code, sf, callSites, registry);
}