Skip to content

Commit c29843c

Browse files
authored
Cache type conversions (#83)
1 parent c7ee86f commit c29843c

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

type-generation/src/astToIR.ts

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -532,6 +532,7 @@ export class Converter {
532532
convertedSet: Set<string>;
533533
extraTopLevels: TopLevelIR[];
534534
nameContext: string[] | undefined;
535+
typeMap: Map<number, TypeIR>;
535536

536537
constructor() {
537538
this.ifaceTypeParamConstraints = new Map();
@@ -540,6 +541,7 @@ export class Converter {
540541
this.convertedSet = new Set(BUILTIN_NAMES);
541542
this.extraTopLevels = [];
542543
this.nameContext = undefined;
544+
this.typeMap = new Map();
543545
}
544546

545547
pushNameContext(ctx: string): void {
@@ -689,6 +691,20 @@ export class Converter {
689691
return { kind: "other", nodeKind, location };
690692
}
691693

694+
lookupTypeIR(node: TypeNode): TypeIR | undefined {
695+
const t = node.getType();
696+
// @ts-expect-error
697+
const id = t.compilerType.id;
698+
return this.typeMap.get(id);
699+
}
700+
701+
cacheTypeIR(node: TypeNode, ir: TypeIR): void {
702+
const t = node.getType();
703+
// @ts-expect-error
704+
const id = t.compilerType.id;
705+
this.typeMap.set(id, ir);
706+
}
707+
692708
maybeSyntheticTypeToIR(node: TypeNode): TypeIR | undefined {
693709
if (!this.nameContext) {
694710
return undefined;
@@ -697,7 +713,13 @@ export class Converter {
697713
if (!typeRoot) {
698714
return undefined;
699715
}
700-
return new SyntheticTypeConverter(this).classifiedTypeToIr(typeRoot);
716+
const lookup = this.lookupTypeIR(node);
717+
if (lookup) {
718+
return lookup;
719+
}
720+
const res = new SyntheticTypeConverter(this).classifiedTypeToIr(typeRoot);
721+
this.cacheTypeIR(node, res);
722+
return res;
701723
}
702724

703725
typeToIR(

type-generation/tests/a.test.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1883,6 +1883,21 @@ describe("emit", () => {
18831883
`).trim(),
18841884
);
18851885
});
1886+
it("Repeated type operator", () => {
1887+
const res = emitFile(`
1888+
interface V { x: string; };
1889+
declare function f(a: Partial<V>, b: Partial<V>): vod;
1890+
`);
1891+
assert.strictEqual(
1892+
removeTypeIgnores(res.slice(1).join("\n\n")),
1893+
dedent(`
1894+
def f(a: f__Sig0__a__Partial__V_iface, b: f__Sig0__a__Partial__V_iface, /) -> vod_iface: ...
1895+
1896+
class f__Sig0__a__Partial__V_iface(Protocol):
1897+
x: str | None = ...
1898+
`).trim(),
1899+
);
1900+
});
18861901
});
18871902
it("named tuple", () => {
18881903
const res = emitFile(`

0 commit comments

Comments
 (0)