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

+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',
});