Files
SnowLuma/packages/proton/src/transform/replacer.ts
T
DrSmoothl 194165f49d feat(proton): add @snowluma/proton — compile-time protobuf DSL
Vendors SnowLuma/protobuf-dsl into the monorepo as @snowluma/proton, with
edge-case fixes applied on top of the upstream source. Reference copy of
the unmodified upstream is kept under dev/protobuf-dsl/.

Edge cases fixed (each with a regression test):
  - Aliased pb / pb_repeated marker imports (`import { pb as P }`)
    — collector now resolves the marker name through the import resolver
  - Concrete interface with a generic-instantiated message field
    (`wrapped: pb<5, Wrapper<uint_32>>`) — field typeName now resolves
    to the mangled form, and the inner instantiation is queued for
    monomorphization
  - Generic template with a generic-instantiated field
    (`interface Outer<U> { x: pb<5, Wrapper<U>> }`) — the inner
    instantiation is now re-substituted and re-monomorphized at outer
    instantiation time
  - Wrapper-binding synthetic SourceFile was empty-text — getText()
    returned garbage, breaking mangled name computation downstream
  - Cross-file forwarded wrappers (chain → imported base) were not
    detected — parseFileForDefinitions now resolves imports recursively
    (value imports only, with cycle protection)
  - matchForwardedKnownWrapper did not propagate typePattern — chain
    treated <X> as the encoded type instead of Wrapper<X>
  - Synthetic-SF WeakMap was private to analyzer.ts — replacer could
    not see it. Moved to utils.ts so typeNodeToMangledName picks it up
    automatically.

Defensive guard: any field whose typeName resolves to neither a primitive
nor a known message now throws at analyze() time, instead of silently
leaking the WireType.Varint placeholder into codegen.

95/95 tests pass; tsc --noEmit clean.
2026-05-19 08:19:13 +08:00

62 lines
2.2 KiB
TypeScript

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);
}