forked from denoland/deno_bindgen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
codegen.ts
283 lines (255 loc) · 7.04 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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
// Copyright 2020-2021 the Deno authors. All rights reserved. MIT license.
import {
createFromBuffer,
GlobalConfiguration,
} from "https://deno.land/x/[email protected]/mod.ts";
import * as Cache from "https://deno.land/x/[email protected]/mod.ts";
Cache.configure({ directory: Cache.options.directory });
const cache = Cache.namespace("deno_bindgen_cli");
const globalConfig: GlobalConfiguration = {
indentWidth: 2,
lineWidth: 80,
};
const file = await cache.cache(
"https://plugins.dprint.dev/typescript-0.57.0.wasm",
);
const tsFormatter = createFromBuffer(await Deno.readFile(file.path));
tsFormatter.setConfig(globalConfig, {
semiColons: "asi",
});
const Type: Record<string, string> = {
void: "null",
i8: "number",
u8: "number",
i16: "number",
u16: "number",
i32: "number",
u32: "number",
i64: "bigint",
u64: "bigint",
usize: "bigint",
isize: "bigint",
f32: "number",
f64: "number",
};
const BufferTypes: Record<string, string> = {
str: "string",
buffer: "Uint8Array",
buffermut: "Uint8Array",
ptr: "Uint8Array",
};
enum Encoder {
JsonStringify = "JSON.stringify",
None = "",
}
const BufferTypeEncoders: Record<keyof typeof BufferTypes, Encoder> = {
str: Encoder.None,
buffer: Encoder.None,
buffermut: Encoder.None,
ptr: Encoder.None,
};
type TypeDef = Record<string, Record<string, string>>;
function resolveType(typeDefs: TypeDef, type: any): string {
const t = typeof type == "string" ? type : type.structenum.ident;
if (Type[t] !== undefined) return Type[t];
if (BufferTypes[t] !== undefined) return BufferTypes[t];
if (Object.keys(typeDefs).find((f) => f == t) !== undefined) {
return t;
}
return "any";
}
function resolveDlopenParameter(typeDefs: TypeDef, type: any): string {
const t = typeof type == "string" ? type : type.structenum.ident;
if (Type[t] !== undefined) return t;
if (t === "buffer" || t === "buffermut") {
return "buffer";
}
if (
BufferTypes[t] !== undefined ||
Object.keys(typeDefs).find((f) => f == t) !== undefined
) {
return "pointer";
}
throw new TypeError(`Type not supported: ${t}`);
}
type Sig = Record<
string,
{
parameters: any[];
result: string;
nonBlocking?: boolean;
}
>;
type Options = {
le?: boolean;
release?: boolean;
};
function isTypeDef(p: any) {
return typeof p !== "string";
}
function isBufferType(p: any) {
return isTypeDef(p) || BufferTypes[p] !== undefined;
}
function needsPointer(p: any) {
return isBufferType(p) && p !== "buffer" && p !== "buffermut";
}
// TODO(@littledivy): factor out options in an interface
export function codegen(
fetchPrefix: string,
name: string,
decl: TypeDef,
typescript: Record<string, string>,
signature: Sig,
options?: Options,
) {
signature = Object.keys(signature)
.sort()
.reduce(
(acc, key) => ({
...acc,
[key]: signature[key],
}),
{},
);
return tsFormatter.formatText(
"bindings.ts",
`import { CachePolicy, prepare } from "https://deno.land/x/[email protected]/plug.ts";
function encode(v: string | Uint8Array): Uint8Array {
if (typeof v !== "string") return v;
return new TextEncoder().encode(v);
}
function decode(v: Uint8Array): string {
return new TextDecoder().decode(v);
}
function readPointer(v: any): Uint8Array {
const ptr = new Deno.UnsafePointerView(v as bigint)
const lengthBe = new Uint8Array(4);
const view = new DataView(lengthBe.buffer);
ptr.copyInto(lengthBe, 0);
const buf = new Uint8Array(view.getUint32(0));
ptr.copyInto(buf, 4)
return buf
}
const url = new URL("${fetchPrefix}", import.meta.url);
let uri = url.toString();
if (!uri.endsWith("/")) uri += "/";
let darwin: string | { aarch64: string; x86_64: string } = uri + "lib${name}.dylib";
if (url.protocol !== "file:") {
// Assume that remote assets follow naming scheme
// for each macOS artifact.
darwin = {
aarch64: uri + "lib${name}_arm64.dylib",
x86_64: uri + "lib${name}.dylib",
}
}
const opts = {
name: "${name}",
urls: {
darwin,
windows: uri + "${name}.dll",
linux: uri + "lib${name}.so",
},
policy: ${!!options?.release ? "undefined" : "CachePolicy.NONE"},
};
const _lib = await prepare(opts, {
${
Object.keys(signature)
.map(
(sig) =>
`${sig}: { parameters: [ ${
signature[sig].parameters
.map((p) => {
const ffiParam = resolveDlopenParameter(decl, p);
// FIXME: Dupe logic here.
return `"${ffiParam}"${isBufferType(p) ? `, "usize"` : ""}`;
})
.join(", ")
} ], result: "${
resolveDlopenParameter(
decl,
signature[sig].result,
)
}", nonblocking: ${String(!!signature[sig].nonBlocking)} }`,
)
.join(", ")
} });
${
Object.keys(decl)
.sort()
.map((def) => typescript[def])
.join("\n")
}
${
Object.keys(signature)
.map((sig) => {
const { parameters, result, nonBlocking } = signature[sig];
return `export function ${sig}(${
parameters
.map((p, i) => `a${i}: ${resolveType(decl, p)}`)
.join(",")
}) {
${
parameters
.map((p, i) =>
isBufferType(p)
? `const a${i}_buf = encode(${
BufferTypeEncoders[p] ?? Encoder.JsonStringify
}(a${i}));`
: null
)
.filter((c) => c !== null)
.join("\n")
}
${
parameters
.map((p, i) =>
// dont get pointer for buffer/buffermut
needsPointer(p)
? `const a${i}_ptr = Deno.UnsafePointer.of(a${i}_buf);`
: null
)
.filter((c) => c !== null)
.join("\n")
}
let rawResult = _lib.symbols.${sig}(${
parameters
.map((p, i) => (isBufferType(p)
? `a${i}_${
needsPointer(p) ? "ptr" : "buf"
}, a${i}_buf.byteLength`
: `a${i}`)
)
.join(", ")
});
${
isBufferType(result)
? nonBlocking
? `const result = rawResult.then(readPointer);`
: `const result = readPointer(rawResult);`
: "const result = rawResult;"
};
${
isTypeDef(result)
? nonBlocking
? `return result.then(r => JSON.parse(decode(r))) as Promise<${
resolveType(
decl,
result,
)
}>;`
: `return JSON.parse(decode(result)) as ${
resolveType(decl, result)
};`
: result == "str"
? nonBlocking
? "return result.then(decode);"
: "return decode(result);"
: "return result;"
};
}`;
})
.join("\n")
}
`,
);
}