-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathcodegen.ts
262 lines (213 loc) · 7.33 KB
/
codegen.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
import { MolType, ParseResult } from "./type";
import { Grammar as NearleyGrammar, Parser as NearleyParser } from "nearley";
import { circularIterator } from "./circularIterator";
// eslint-disable-next-line @typescript-eslint/no-var-requires
const grammar = require("./grammar/mol.js");
export type Options = {
/**
* an import statement to prepend to the generated code, used to import and override <br/>
* e.g. `"import { Uint32, Uint64 } from './customized'"` to override the default `Uint32` and `Uint64` types
*/
prepend?: string;
formatObjectKeys?: (key: string, molType: MolType) => string;
};
function id<T>(value: T): T {
return value;
}
export function scanCustomizedTypes(prepend: string): string[] {
if (!prepend) return [];
const matched = prepend.match(/(?<={)([^}]+)(?=})/g);
if (!matched) return [];
// parse the override import statements to get the items
return matched.flatMap((item) =>
item
.split(",")
.map((x) => x.trim())
.filter(Boolean)
);
}
export function codegenReturnWithElements(
schema: string,
options: Options = {}
): ParseResult {
const parser = new NearleyParser(NearleyGrammar.fromCompiled(grammar));
parser.feed(schema);
// the items that don't need to be generated
const importedModules: string[] = scanCustomizedTypes(options.prepend || "");
const molTypes = prepareMolTypes(
parser.results[0].filter(Boolean),
importedModules
);
const typeNames: Array<string> = [];
const codecs = molTypes
.map((molType) => {
if (importedModules.includes(molType.name)) return "";
typeNames.push(molType.name);
if (molType.type === "array") {
if (molType.item === "byte") {
return `export const ${molType.name} = createFallbackFixedBytesCodec(${molType.item_count});`;
}
return `export const ${molType.name} = array(${molType.item}, ${molType.item_count});`;
}
if (molType.type === "vector") {
if (molType.item === "byte") {
return `export const ${molType.name} = fallbackBytesCodec;`;
}
return `export const ${molType.name} = vector(${molType.item});`;
}
if (molType.type === "option") {
return `export const ${molType.name} = option(${molType.item});`;
}
const formatObjectKey = (str: string) =>
(options.formatObjectKeys || id)(str, molType);
if (molType.type === "struct") {
const fields = molType.fields
.map((field) => ` ${formatObjectKey(field.name)}: ${field.type}`)
.join(",\n");
const keys = molType.fields
.map((field) => `'${formatObjectKey(field.name)}'`)
.join(", ");
return `export const ${molType.name} = struct({\n${fields}\n}, [${keys}]);`;
}
if (molType.type === "table") {
const fields = molType.fields
.map((field) => ` ${formatObjectKey(field.name)}: ${field.type}`)
.join(",\n");
const keys = molType.fields
.map((field) => `'${formatObjectKey(field.name)}'`)
.join(", ");
return `export const ${molType.name} = table({\n${fields}\n}, [${keys}]);`;
}
if (molType.type === "union") {
if (Array.isArray(molType.items[0])) {
const items = molType.items as [string, number][];
const fields = items
.map(([itemName]) => ` ${formatObjectKey(itemName)}`)
.join(",\n");
const keys = items
.map(([itemName, key]) => `'${formatObjectKey(itemName)}': ${key}`)
.join(", ");
return `export const ${molType.name} = union({\n${fields}\n}, {${keys}});`;
}
if (typeof molType.items[0] === "string") {
const items = (molType.items as string[]).map((itemName) =>
formatObjectKey(itemName)
);
const fields = items.map((itemName) => ` ${itemName}`).join(",\n");
const keys = items.map((itemName) => `'${itemName}'`).join(", ");
return `export const ${molType.name} = union({\n${fields}\n}, [${keys}]);`;
}
}
})
.filter(Boolean)
.join("\n\n");
const code = `// This file is generated by @ckb-lumos/molecule, please do not modify it manually.
/* eslint-disable */
import { bytes, createBytesCodec, createFixedBytesCodec, molecule } from "@ckb-lumos/codec";
${options.prepend || ""}
const { array, vector, union, option, struct, table } = molecule;
const fallbackBytesCodec = createBytesCodec({
pack: bytes.bytify,
unpack: bytes.hexify,
});
function createFallbackFixedBytesCodec(byteLength: number) {
return createFixedBytesCodec({
pack: bytes.bytify,
unpack: bytes.hexify,
byteLength,
});
}
const byte = createFallbackFixedBytesCodec(1);
${codecs}
`;
const result: ParseResult = {
code,
elements: typeNames,
};
return result;
}
export function codegen(schema: string, options: Options = {}): string {
return codegenReturnWithElements(schema, options).code;
}
// sort molecule types by their dependencies, to make sure the known types can be used in the front
function prepareMolTypes(
types: MolType[],
importedTypes: string[] = []
): MolType[] {
// check if the molecule definition can be parsed
function checkCanParse(molType: MolType): boolean {
if (availableTypes.has(molType.name)) {
return true;
}
const layoutType = molType.type;
switch (layoutType) {
case "array":
case "vector":
case "option": {
if (!availableTypes.has(molType.item)) {
return false;
}
availableTypes.add(molType.name);
return true;
}
case "struct":
case "table": {
const fieldsAreKnown = molType.fields.every((field) =>
availableTypes.has(field.type)
);
if (!fieldsAreKnown) {
return false;
}
availableTypes.add(molType.name);
return true;
}
case "union": {
const itemsAreKnown = molType.items.every((item) =>
Array.isArray(item)
? availableTypes.has(item[0])
: availableTypes.has(item)
);
if (!itemsAreKnown) {
return false;
}
availableTypes.add(molType.name);
return true;
}
default: {
throw new Error(`Unknown molecule layout ${layoutType}`);
}
}
}
// temp set to store the known types
const availableTypes = new Set(importedTypes.concat("byte"));
const sortedTypes: MolType[] = [];
const iterator = circularIterator(types);
// the worst case is that the known types are at the end of the list,
// therefore, the max scan times is the sum of 1 to n
// sigma(n) = n * (n + 1) / 2
const maxScanTimes = ((1 + types.length) * types.length) / 2;
let scanTimes = 0;
while (iterator.current() != null && scanTimes < maxScanTimes) {
scanTimes++;
const molType = iterator.current()!;
if (checkCanParse(molType)) {
sortedTypes.push(molType);
availableTypes.add(molType.name);
iterator.removeAndNext();
continue;
}
iterator.next();
}
if (scanTimes >= maxScanTimes) {
const unknownTypes = types
.filter((type) => !availableTypes.has(type.name))
.map((type) => type.name)
.join(", ");
if (unknownTypes) {
throw new Error(
`Circular dependency or unknown type found in ${unknownTypes}`
);
}
}
return sortedTypes;
}