-
Notifications
You must be signed in to change notification settings - Fork 166
/
Copy pathgen-make-functions-script.ts
308 lines (282 loc) · 10.7 KB
/
gen-make-functions-script.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import generate from "@babel/generator";
import type { ParserOptions } from "@babel/parser";
import { parse } from "@babel/parser";
import * as t from "@babel/types";
import * as fs from "fs";
import * as path from "path";
function main() {
const options: ParserOptions = {
sourceType: "module",
plugins: ["typescript"],
};
const astModule = fs
.readFileSync(path.join(__dirname, "..", "ast.ts"))
.toString();
const astTypeDecls = parse(astModule, options);
const decls = astTypeDecls.program.body
.filter((stmt) => t.isExportNamedDeclaration(stmt))
.map((stmt) => stmt.declaration)
.filter((stmt) => t.isTSTypeAliasDeclaration(stmt));
const declNames = new Set(decls.map((decl) => decl.id.name));
const finalFunctions: { name: string; code: string }[] = [];
// Extract from the declarations all the union types
const unionTypes = decls
.map((decl) => decl.typeAnnotation)
.filter((decl) => t.isTSUnionType(decl));
for (const unionType of unionTypes) {
const subtypes = unionType.types
.filter((typeDecl) => t.isTSTypeReference(typeDecl))
.map((typeDecl) => typeDecl.typeName)
.filter((typeDecl) => t.isIdentifier(typeDecl));
for (const subtype of subtypes) {
const subtypeDecl = decls.find(
(decl) => decl.id.name === subtype.name,
);
if (typeof subtypeDecl === "undefined") {
throw new Error(`${subtype.name} is not declared.`);
}
const subtypeDeclAnnotation = subtypeDecl.typeAnnotation;
if (t.isTSTypeLiteral(subtypeDeclAnnotation)) {
const genFunctions = createMakeAndDummyFunctions(
subtypeDeclAnnotation,
subtypeDecl.id,
declNames,
);
const genFunctionsFiltered = genFunctions.filter((genF) =>
finalFunctions.every((f) => f.name !== genF.name),
);
if (genFunctionsFiltered.length > 0) {
console.log(
`Generated [${genFunctionsFiltered.map((entry) => entry.name).join(", ")}] for ${subtype.name}`,
);
}
finalFunctions.push(...genFunctionsFiltered);
} else if (t.isTSUnionType(subtypeDeclAnnotation)) {
// Do nothing, since it will be processed later.
} else {
// Unexpected type
throw new Error(
`${subtype.name} is not a reference to a type literal or a union type.`,
);
}
}
}
// Create the make factory file
const makeFactoryTemplate = fs
.readFileSync(path.join(__dirname, "make-factory.template"))
.toString();
const functionCodes = finalFunctions
.map((genFun) => genFun.code)
.join("\n\n");
const functionNames = finalFunctions
.map((genFun) => genFun.name)
.join(",\n");
const makeFactoryCode = makeFactoryTemplate
.replace("<FUNCTIONS>", functionCodes)
.replace("<FUNCTION_NAMES>", functionNames);
fs.writeFileSync(path.join(__dirname, "make-factory.ts"), makeFactoryCode);
console.log("Finished.");
}
function createMakeAndDummyFunctions(
decl: t.TSTypeLiteral,
id: t.Identifier,
decls: Set<string>,
): { name: string; code: string }[] {
const astNamespace = "Ast";
const astFactoryObject = "astF";
const createNodeFunName = "createNode";
const emptySrcInfo = "emptySrcInfo";
const rawFieldsArray = decl.members.filter((decl) =>
t.isTSPropertySignature(decl),
);
const generalParams: { id: t.Identifier; type: t.TSType }[] = [];
const paramsWithLiteralTypes: {
id: t.Identifier;
type: t.TSLiteralType;
}[] = [];
// If there is no loc field,
// the makeDummy function cannot be created
const makeDummy = rawFieldsArray.some(
(f) => t.isIdentifier(f.key) && f.key.name === "loc",
);
for (const field of rawFieldsArray) {
if (!t.isIdentifier(field.key)) {
throw new Error(
`Expected identifier in fields, but found ${field.key.type}`,
);
}
const fieldName = field.key.name;
if (fieldName === "id") {
// The id field should not occur as an argument to the function,
// nor as a parameter to createNode
continue;
}
if (field.typeAnnotation) {
const typeAnnotation = field.typeAnnotation.typeAnnotation;
if (t.isTSLiteralType(typeAnnotation)) {
paramsWithLiteralTypes.push({
id: field.key,
type: typeAnnotation,
});
} else {
generalParams.push({ id: field.key, type: typeAnnotation });
}
} else {
throw new Error(
`Expected field ${fieldName} to have a type annotation`,
);
}
}
const makeFunName = `make${id.name}`;
const makeDummyFunName = `makeDummy${id.name}`;
// The params to the make functions do not have fields with literal types
// Also, the dummy function needs to filter the loc parameter
const createParam = (entry: { id: t.Identifier; type: t.TSType }) => {
const newId = t.identifier(`p_${entry.id.name}`);
newId.typeAnnotation = t.tsTypeAnnotation(
qualifyType(astNamespace, entry.type, decls),
);
return newId;
};
const makeFunParamsArray = generalParams.map((entry) => createParam(entry));
const makeDummyFunParamsArray = generalParams
.filter(({ id, type: _ }) => id.name !== "loc")
.map((entry) => createParam(entry));
// The arguments with literal values to the createNode call inside the make functions body
const createNodeLiteralArgs = paramsWithLiteralTypes.map(({ id, type }) =>
t.objectProperty(id, type.literal),
);
// The non-literal arguments to the createNode call inside the make functions body
const createNodeArgsForMake = generalParams.map(({ id, type: _ }) =>
t.objectProperty(id, t.identifier(`p_${id.name}`)),
);
const createNodeArgsForMakeDummy = generalParams.map(({ id, type: _ }) =>
id.name === "loc"
? t.objectProperty(id, t.identifier(emptySrcInfo))
: t.objectProperty(id, t.identifier(`p_${id.name}`)),
);
const funReturnType = t.tsTypeReference(
t.tsQualifiedName(t.identifier(astNamespace), id),
);
// Function to create the function codes
const createFun = (
name: string,
params: t.Identifier[],
createNodeArgs: t.ObjectProperty[],
) => {
const body = t.returnStatement(
t.tsAsExpression(
t.callExpression(
t.memberExpression(
t.identifier(astFactoryObject),
t.identifier(createNodeFunName),
),
[t.objectExpression(createNodeArgs)],
),
funReturnType,
),
);
const funDecl = t.functionDeclaration(
t.identifier(name),
params,
t.blockStatement([body]),
);
funDecl.returnType = t.tsTypeAnnotation(funReturnType);
return funDecl;
};
const makeFun = createFun(makeFunName, makeFunParamsArray, [
...createNodeLiteralArgs,
...createNodeArgsForMake,
]);
const makeDummyFun = createFun(makeDummyFunName, makeDummyFunParamsArray, [
...createNodeLiteralArgs,
...createNodeArgsForMakeDummy,
]);
if (makeDummy) {
return [
{ name: makeFunName, code: generate(makeFun).code },
{ name: makeDummyFunName, code: generate(makeDummyFun).code },
];
} else {
console.log(
`[WARNING] Skipped makeDummy for ${id.name}, because there is no loc field in ${id.name}.`,
);
return [{ name: makeFunName, code: generate(makeFun).code }];
}
}
function qualifyType(
namespace: string,
typ: t.TSType,
decls: Set<string>,
): t.TSType {
switch (typ.type) {
case "TSTypeReference": {
if (t.isIdentifier(typ.typeName)) {
if (decls.has(typ.typeName.name)) {
return t.tsTypeReference(
t.tsQualifiedName(
t.identifier(namespace),
typ.typeName,
),
);
} else {
// Leave the identifier unchanged, but check if it has type parameters
const typRef = t.tsTypeReference(typ.typeName);
if (typ.typeParameters) {
typRef.typeParameters = t.tsTypeParameterInstantiation(
typ.typeParameters.params.map((t) =>
qualifyType(namespace, t, decls),
),
);
}
return typRef;
}
}
// Leave the type as is
return typ;
}
case "TSUnionType": {
return t.tsUnionType(
typ.types.map((t) => qualifyType(namespace, t, decls)),
);
}
case "TSArrayType": {
return t.tsArrayType(
qualifyType(namespace, typ.elementType, decls),
);
}
case "TSTypeOperator": {
const op = t.tsTypeOperator(
qualifyType(namespace, typ.typeAnnotation, decls),
);
op.operator = typ.operator;
return op;
}
case "TSTupleType": {
if (
// Cannot use guard function isTSNamedTupleMember, because compiler cannot deduce the type inside
// the condition if the guard function is used.
typ.elementTypes.every((ty) => ty.type !== "TSNamedTupleMember")
) {
return t.tsTupleType(
typ.elementTypes.map((t) =>
qualifyType(namespace, t, decls),
),
);
} else {
// Currently unsupported
throw new Error(
"TSNamedTupleMember is currently not supported in TSTupleType",
);
}
}
case "TSUndefinedKeyword":
case "TSStringKeyword":
case "TSBooleanKeyword":
case "TSBigIntKeyword":
return typ;
default:
throw new Error(`${typ.type} is not supported`);
}
}
main();