forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-node-errors.ts
More file actions
178 lines (142 loc) · 5.4 KB
/
Copy pathgenerate-node-errors.ts
File metadata and controls
178 lines (142 loc) · 5.4 KB
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
import path from "node:path";
import NodeErrors from "../jsc/bindings/ErrorCode.ts";
import { writeIfNotChanged } from "./helpers.ts";
const outputDir = process.argv[2];
if (!outputDir) {
throw new Error("Missing output directory");
}
const extra_count = NodeErrors.map(x => x.slice(3))
.filter(x => x.length > 0)
.reduce((ac, cv) => ac + cv.length, 0);
const count = NodeErrors.length + extra_count;
if (count > 1 << 16) {
// increase size of the enums below to have more tags
throw new Error(`NodeError can't fit ${count} codes in a u16`);
}
let enumHeader = ``;
let listHeader = ``;
let zig = ``;
enumHeader = `
// clang-format off
// Generated by: src/codegen/generate-node-errors.ts
// Input: src/jsc/bindings/ErrorCode.ts
#pragma once
#include <cstdint>
namespace Bun {
static constexpr size_t NODE_ERROR_COUNT = ${count};
enum class ErrorCode : uint16_t {
`;
listHeader = `
// clang-format off
// Generated by: src/codegen/generate-node-errors.ts
#pragma once
#include <JavaScriptCore/ErrorType.h>
struct ErrorCodeData {
JSC::ErrorType type;
WTF::ASCIILiteral name;
WTF::ASCIILiteral code;
};
static constexpr ErrorCodeData errors[${count}] = {
`;
zig = `
// Generated by: src/codegen/generate-node-errors.ts
const std = @import("std");
const bun = @import("bun");
const jsc = bun.jsc;
pub fn ErrorBuilder(comptime code: Error, comptime fmt: [:0]const u8, Args: type) type {
return struct {
global: *jsc.JSGlobalObject,
args: Args,
// Throw this error as a JS exception
pub inline fn throw(this: @This()) bun.JSError {
return code.throw(this.global, fmt, this.args);
}
/// Turn this into a JSValue
pub inline fn toJS(this: @This()) jsc.JSValue {
return code.fmt(this.global, fmt, this.args);
}
/// Turn this into a JSPromise that is already rejected.
pub inline fn reject(this: @This()) jsc.JSValue {
return jsc.JSPromise.rejectedPromise(this.global, code.fmt(this.global, fmt, this.args)).toJS();
}
};
}
pub const Error = enum(u16) {
`;
let i = 0;
for (let [code, constructor, name, ...other_constructors] of NodeErrors) {
if (name == null) name = constructor.name;
// it's useful to avoid the prefix, but module not found has a prefixed and unprefixed version
const codeWithoutPrefix = code === "ERR_MODULE_NOT_FOUND" ? code : code.replace(/^ERR_/, "");
enumHeader += ` ${code} = ${i},\n`;
listHeader += ` { JSC::ErrorType::${constructor.name}, "${name}"_s, "${code}"_s },\n`;
zig += ` /// ${name}: ${code} (instanceof ${constructor.name})\n`;
zig += ` ${codeWithoutPrefix} = ${i},\n`;
i++;
for (const con of other_constructors) {
if (con == null) continue;
if (name == null) name = con.name;
enumHeader += ` ${code}_${con.name} = ${i},\n`;
listHeader += ` { JSC::ErrorType::${con.name}, "${con.name}"_s, "${code}"_s },\n`;
zig += ` /// ${name}: ${code} (instanceof ${con.name})\n`;
zig += ` ${codeWithoutPrefix}_${con.name} = ${i},\n`;
i++;
}
}
enumHeader += `
};
} // namespace Bun
`;
listHeader += `
};
`;
zig += `
extern fn Bun__createErrorWithCode(globalThis: *jsc.JSGlobalObject, code: Error, message: *bun.String) jsc.JSValue;
/// Creates an Error object with the given error code.
/// If an error is thrown while creating the Error object, returns that error instead.
/// Derefs the message string.
pub fn toJS(this: Error, globalThis: *jsc.JSGlobalObject, message: *bun.String) jsc.JSValue {
defer message.deref();
return Bun__createErrorWithCode(globalThis, this, message);
}
pub fn fmt(this: Error, globalThis: *jsc.JSGlobalObject, comptime fmt_str: [:0]const u8, args: anytype) jsc.JSValue {
if (comptime std.meta.fieldNames(@TypeOf(args)).len == 0) {
var message = bun.String.static(fmt_str);
return toJS(this, globalThis, &message);
}
var message = bun.handleOom(bun.String.createFormat(fmt_str, args));
return toJS(this, globalThis, &message);
}
pub fn throw(this: Error, globalThis: *jsc.JSGlobalObject, comptime fmt_str: [:0]const u8, args: anytype) bun.JSError {
return globalThis.throwValue(fmt(this, globalThis, fmt_str, args));
}
};
`;
let builtindtsPath = path.join(import.meta.dir, "..", "..", "src", "js", "builtins.d.ts");
let builtindts = await Bun.file(builtindtsPath).text();
let dts = `
// Generated by: src/codegen/generate-node-errors.ts
// Input: src/jsc/bindings/ErrorCode.ts
// Global error code functions for TypeScript
`;
for (const [code, constructor, name, ...other_constructors] of NodeErrors) {
const hasExistingOverride = builtindts.includes(`declare function $${code}`);
if (hasExistingOverride) {
continue;
}
const namedError =
name && name !== constructor.name
? `${constructor.name} & { name: "${name}", code: "${code}" }`
: `${constructor.name} & { code: "${code}" }`;
dts += `
/**
* Construct an {@link ${constructor.name} ${constructor.name}} with the \`"${code}"\` error code.
*
* To override this, update ErrorCode.cpp. To remove this generated type, mention \`"${code}"\` in builtins.d.ts.
*/
declare function $${code}(message: string): ${namedError};\n`;
}
writeIfNotChanged(path.join(outputDir, "ErrorCode+List.h"), enumHeader);
writeIfNotChanged(path.join(outputDir, "ErrorCode+Data.h"), listHeader);
writeIfNotChanged(path.join(outputDir, "ErrorCode.zig"), zig);
writeIfNotChanged(path.join(outputDir, "ErrorCode.d.ts"), dts);