From 1b07005d913fd454cd21e89fbde003d4785f272b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=89=8B=E7=93=9C=E4=B8=80=E5=8D=81=E9=9B=AA?= Date: Tue, 26 May 2026 20:53:32 +0800 Subject: [PATCH] Unify protobuf helpers and tidy comments Export and centralize small utility helpers and remove duplicate implementations: identityImportedTypeName was exported from utils, and isVarint64/isFixed64BigInt were added to types and imported into encoder/decoder. Minor import reorders and formatting cleanups across collector, monomorphizer, import-resolver, static-wrapper, subclass-override and file-pipeline. Comments and JSDoc were tightened for clarity; behavior remains the same but common logic is now deduplicated and easier to maintain. --- packages/proton/src/ast/collector.ts | 23 +++++------ packages/proton/src/ast/import-resolver.ts | 41 +++---------------- packages/proton/src/ast/monomorphizer.ts | 23 +++++------ packages/proton/src/ast/static-wrapper.ts | 22 ++-------- packages/proton/src/ast/types.ts | 8 ++++ packages/proton/src/ast/utils.ts | 2 +- packages/proton/src/codegen/decoder.ts | 10 +---- packages/proton/src/codegen/encoder.ts | 16 ++------ .../proton/src/codegen/subclass-override.ts | 19 ++------- .../proton/src/typecheck/file-pipeline.ts | 25 +++-------- 10 files changed, 51 insertions(+), 138 deletions(-) diff --git a/packages/proton/src/ast/collector.ts b/packages/proton/src/ast/collector.ts index 6955b308..9a9cc1aa 100644 --- a/packages/proton/src/ast/collector.ts +++ b/packages/proton/src/ast/collector.ts @@ -1,15 +1,12 @@ import ts from 'typescript'; import { - WireType, PB_MARKER, PB_REPEATED_MARKER, + WireType, + type GenericFieldTemplate, + type GenericProtobufTemplate, 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; -} +import { identityImportedTypeName, isKeywordTypeNode, typeNodeToMangledName, type ImportedTypeNameResolver } from './utils.js'; /** * Yield generic-instantiated type-arg nodes appearing as field types on a @@ -150,12 +147,12 @@ function extractGenericField( isOptional: member.questionToken != null, isRepeated: parsed.marker === PB_REPEATED_MARKER, }; - // If the field's type-arg is itself a generic instantiation (`Wrapper`, - // 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. + // If the field's type-arg is itself a generic instantiation (`Wrapper`, + // 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); diff --git a/packages/proton/src/ast/import-resolver.ts b/packages/proton/src/ast/import-resolver.ts index 132d1e6b..1a518531 100644 --- a/packages/proton/src/ast/import-resolver.ts +++ b/packages/proton/src/ast/import-resolver.ts @@ -140,44 +140,14 @@ function getBareModuleResolutionCache(): ts.ModuleResolutionCache { return bareModuleResolutionCache; } -/** - * Resolve a module specifier (relative OR bare) to an absolute `.ts` - * source-file path. Returns `null` if the resolution lands on something - * proton can't consume (a `.d.ts` declaration, a `.js` build artifact, - * or just not-found). - * - * Two code paths: - * - * - **Relative** (`./foo`, `../bar`): direct file-existence probe. - * Same behavior as before — fast, no TS dependency. Preserved - * verbatim so that the common case (cross-file imports inside a - * single package) is unaffected by the new bare-specifier logic. - * - * - **Bare** (`@scope/pkg`, `pkg-name`, `~alias`): delegate to - * TypeScript's module resolution so monorepo workspaces / npm - * packages / tsconfig paths / package.json `exports` all just work. - * Required to support proto definitions that live in a separate - * workspace package — e.g. moving `bridge/proto/proton/*.ts` into a - * dedicated `@snowluma/proto-defs` package while keeping the call - * sites in `@snowluma/core`. - * - * We deliberately require the resolved file to be `.ts` (not - * `.d.ts`): proton collects `pb<…>` field tags by walking interface - * AST nodes, and a hand-written `.d.ts` *would* work too — but the - * typical `dist/index.d.ts` strips away the `pb<>` type arguments - * proton needs. Asking proto-definition packages to ship source - * `.ts` (the same model `@snowluma/proton` itself uses) avoids that - * footgun entirely. - */ +/** Resolve a specifier (relative or bare) to an absolute `.ts` source path. + * Returns `null` for non-.ts files (`.d.ts`, `.js`) or unresolved paths. + * Relative specifiers use direct file probing; bare specifiers use TS bundler + * resolution so workspaces, path aliases, and `package.json` exports work. + * Only `.ts` source is accepted — `.d.ts` strips the `pb<>` type arguments. */ function resolveModulePath(specifier: string, importerPath: string): string | null { if (specifier.startsWith('.')) { - // ── Relative path branch (preserved verbatim from the pre-bare- - // specifier implementation; existing callers depend on its - // exact behavior, including the .ts-only filter). ── const base = resolve(dirname(importerPath), specifier); - - // Try exact path (e.g., './types.ts') - if (existsSync(base) && !base.endsWith('.ts') === false) return base; if (base.endsWith('.ts') && existsSync(base)) return base; // Try appending .ts @@ -191,7 +161,6 @@ function resolveModulePath(specifier: string, importerPath: string): string | nu return null; } - // ── Bare specifier branch ── const result = ts.resolveModuleName( specifier, importerPath, diff --git a/packages/proton/src/ast/monomorphizer.ts b/packages/proton/src/ast/monomorphizer.ts index 29d9e47b..03194759 100644 --- a/packages/proton/src/ast/monomorphizer.ts +++ b/packages/proton/src/ast/monomorphizer.ts @@ -1,25 +1,22 @@ import ts from 'typescript'; -import { WireType, type ProtobufField, type ProtobufMessage, type GenericProtobufTemplate } from './types.js'; +import { WireType, type GenericProtobufTemplate, type ProtobufField, type ProtobufMessage } from './types.js'; import { - isKeywordTypeNode, createImportedTypeNameResolver, + identityImportedTypeName, + isKeywordTypeNode, resolveSourceFileForTypeNode, - type ImportedTypeNameResolver, typeNodeToMangledName, + type ImportedTypeNameResolver, } 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; + /** 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; } /** diff --git a/packages/proton/src/ast/static-wrapper.ts b/packages/proton/src/ast/static-wrapper.ts index dfc6cb91..0e288128 100644 --- a/packages/proton/src/ast/static-wrapper.ts +++ b/packages/proton/src/ast/static-wrapper.ts @@ -3,10 +3,8 @@ import { getMethodName, isStaticMethod } from './ast-helpers.js'; import { collectProtobufImportBindings, matchProtobufCallSite, type CanonicalProtobufFn, type ProtobufImportBindings } from './callsite.js'; /** - * Static-method wrapper detection. - * - * A "wrapper" here is the abstract half of the pattern that motivates the - * whole feature: + * Static-method wrapper detection. Detects abstract static methods that + * forward a type parameter into `protobuf_encode`/`protobuf_decode`, e.g.: * * ```ts * abstract class PacketTransformer { @@ -16,21 +14,7 @@ import { collectProtobufImportBindings, matchProtobufCallSite, type CanonicalPro * } * ``` * - * The method itself can never run at the user's call site because `R` is - * erased at runtime. Proton's job is to walk every subclass of such a base, - * resolve `R` per subclass via TypeChecker, and emit a per-subclass override - * with a concrete codec inlined. - * - * This module only handles the AST-side detection — what the method looks - * like and which type parameter it pipes into protobuf_encode/decode. The - * subclass resolution + codegen lives in `typecheck/subclass-wrapper.ts` - * because both steps need a TypeChecker. - * - * The detector is intentionally name-agnostic: it doesn't care that the - * method is called `encode`, that the sibling is `serialize`, or that the - * base is `PacketTransformer`. It only looks at the structural pattern, - * which keeps it usable for user-defined variants (decode side, RPC chains, - * etc.) without further configuration. + * Subclass resolution and codegen live in `typecheck/subclass-wrapper.ts`. */ /** A single `protobuf_encode(...)` / `protobuf_decode(...)` call inside diff --git a/packages/proton/src/ast/types.ts b/packages/proton/src/ast/types.ts index 37f80ea2..f51e353c 100644 --- a/packages/proton/src/ast/types.ts +++ b/packages/proton/src/ast/types.ts @@ -70,3 +70,11 @@ export const PRIMITIVE_TYPE_MAP: Record string; -function identityImportedTypeName(name: string): string { +export function identityImportedTypeName(name: string): string { return name; } diff --git a/packages/proton/src/codegen/decoder.ts b/packages/proton/src/codegen/decoder.ts index 9b8477d2..312d54ad 100644 --- a/packages/proton/src/codegen/decoder.ts +++ b/packages/proton/src/codegen/decoder.ts @@ -1,4 +1,4 @@ -import { WireType, PRIMITIVE_TYPE_MAP, type ProtobufField, type ProtobufMessage, type MessageRegistry } from '../ast/types.js'; +import { PRIMITIVE_TYPE_MAP, WireType, isFixed64BigInt, isVarint64, type MessageRegistry, type ProtobufField, type ProtobufMessage } from '../ast/types.js'; function tagValue(field: ProtobufField): number { const wireType = field.isMessage || field.typeName === 'string' || field.typeName === 'bytes' @@ -26,14 +26,6 @@ function varintDec64(varName: string, ind: string): string { ].join('\n'); } -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 = [ ` const wireType = _tag & 0x7;`, ` if (wireType === 0) { while (data[offset] & 0x80) offset++; offset++; }`, diff --git a/packages/proton/src/codegen/encoder.ts b/packages/proton/src/codegen/encoder.ts index cc89efc4..16c4bd8d 100644 --- a/packages/proton/src/codegen/encoder.ts +++ b/packages/proton/src/codegen/encoder.ts @@ -1,4 +1,4 @@ -import { WireType, type ProtobufField, type ProtobufMessage, type MessageRegistry } from '../ast/types.js'; +import { WireType, isFixed64BigInt, isVarint64, type MessageRegistry, type ProtobufField, type ProtobufMessage } from '../ast/types.js'; /** * Pre-compute tag bytes at codegen time. @@ -52,14 +52,6 @@ function writeVarint(expr: string, ind: string): string { ].join('\n'); } -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'; -} - function bigintVarintExpr(typeName: string, expr: string): string { if (typeName === 'uint_64') return `BigInt.asUintN(64, ${expr})`; if (typeName === 'int_64') return `BigInt.asUintN(64, ${expr})`; @@ -67,9 +59,9 @@ function bigintVarintExpr(typeName: string, expr: string): string { } interface EncoderBlock { - declare: string[]; - size: string[]; - write: string[]; + declare: string[]; + size: string[]; + write: string[]; } export function generateEncoder(msg: ProtobufMessage, _registry: MessageRegistry): string { diff --git a/packages/proton/src/codegen/subclass-override.ts b/packages/proton/src/codegen/subclass-override.ts index 8318b6ac..e8fcbf0f 100644 --- a/packages/proton/src/codegen/subclass-override.ts +++ b/packages/proton/src/codegen/subclass-override.ts @@ -2,25 +2,14 @@ import ts from 'typescript'; import type { ResolvedSubclassWrapper } from '../typecheck/subclass-wrapper.js'; /** - * Per-subclass override code generation. - * - * The abstract base class's static method body is copied verbatim, with - * every `protobuf_encode` / `protobuf_decode` occurrence rewritten to - * the concrete `protobuf_encode_${typeName}` / `protobuf_decode_${typeName}` - * identifier. The result is assigned onto the subclass: + * Per-subclass override code generation. Copies the wrapper body verbatim, + * rewrites every `protobuf_encode/decode` to the concrete form, and emits: * * ```ts - * Sub.encode = function (ctx, params) { … rewritten body … }; + * Sub.encode = function (ctx, params) { … }; * ``` * - * Output language: - * The generated text is appended into the subclass's own (already-TS) - * transform result. Anything TS-only inside the body (`as never`, return- - * type annotations on local vars, etc.) survives intact and is dropped - * downstream by the same TS-to-JS step that already handles the rest of - * the user file. We avoid running our own transpilation step here both - * because it adds latency and because re-transpiling once Vite is about - * to do it again would generate duplicate work for every transform. + * Output is TS-flavoured (not transpiled) — Vite handles the TS-to-JS pass. */ export interface SubclassOverrideRenderResult { diff --git a/packages/proton/src/typecheck/file-pipeline.ts b/packages/proton/src/typecheck/file-pipeline.ts index eaa7e7cc..6458f574 100644 --- a/packages/proton/src/typecheck/file-pipeline.ts +++ b/packages/proton/src/typecheck/file-pipeline.ts @@ -14,22 +14,7 @@ export interface SubclassOverrideInsertion { code: string; } -/** - * Plugin-facing entry point for the subclass-wrapper feature. - * - * Pulls the file's TypeChecker (lazily — returns null and short-circuits - * if no tsconfig is reachable), walks every class declaration in the - * file's program-side SourceFile, runs the subclass resolver against each, - * and returns both the resolved wrappers and the extra root type names - * that the analyzer pipeline needs to drag into the codec registry. - * - * The function is intentionally side-effect free: caching of the Program - * lives in `program-cache.ts`, and the override text is materialised by - * `renderSubclassOverride`. Each call gets a fresh `WrapperLookupCache` - * because the underlying detect call is memoised per ClassDeclaration — - * the cache only matters across the iterations of a single file's - * subclasses (which is exactly what we do here). - */ +/** Result returned by `runSubclassWrapperPipeline`. */ export interface SubclassWrapperPipelineResult { /** All resolved subclass overrides reachable from this file. Empty when * TypeChecker is unavailable, when no class in the file extends a @@ -46,6 +31,9 @@ export interface SubclassWrapperPipelineResult { insertions: SubclassOverrideInsertion[]; } +/** Lazily retrieves the TypeChecker (returns empty result when no tsconfig is + * reachable), resolves inherited wrapper overrides for every class in the file, + * and returns resolved wrappers, extra codec roots, and insertion points. */ export function runSubclassWrapperPipeline(filePath: string): SubclassWrapperPipelineResult { const empty: SubclassWrapperPipelineResult = { resolvedWrappers: [], @@ -62,10 +50,7 @@ export function runSubclassWrapperPipeline(filePath: string): SubclassWrapperPip const cache = new WrapperLookupCache(); const allResolved: ResolvedSubclassWrapper[] = []; const extraRoots = new Set(); - // Group rendered overrides per subclass so encode + decode + ... for the - // same class land in one contiguous block right after the class body. - // Otherwise the plugin would have to apply multiple identical-position - // edits and worry about ordering. + // Group per subclass so encode + decode + ... land in one contiguous block. const perSubclass = new Map(); for (const stmt of sf.statements) {