feat
This commit is contained in:
1 parent
8e28bca775
commit
1172a6bd3d
100 files changed
+8305
-6025
No files matched your search
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
))
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user