Skip to content

Commit

Permalink
[autofix.ci] apply automated fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
autofix-ci[bot] committed Jan 14, 2024
1 parent 1baf79c commit deb72c4
Show file tree
Hide file tree
Showing 11 changed files with 120 additions and 136 deletions.
26 changes: 14 additions & 12 deletions src/codegen/bundle-functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,10 @@ async function processFileSplit(filename: string): Promise<{ functions: BundledB
// do not allow the bundler to rename a symbol to $
($);
$$capture_start$$(${fn.async ? "async " : ""}${useThis
? `function(${fn.params.join(",")})`
: `${fn.params.length === 1 ? fn.params[0] : `(${fn.params.join(",")})`}=>`
$$capture_start$$(${fn.async ? "async " : ""}${
useThis
? `function(${fn.params.join(",")})`
: `${fn.params.length === 1 ? fn.params[0] : `(${fn.params.join(",")})`}=>`
} {${fn.source}}).$$capture_end$$;
`,
);
Expand All @@ -198,11 +199,11 @@ $$capture_start$$(${fn.async ? "async " : ""}${useThis
(fn.directives.sloppy
? captured
: captured.replace(
/function\s*\(.*?\)\s*{/,
'$&"use strict";' +
(usesDebug ? createLogClientJS("BUILTINS", fn.name) : "") +
(usesAssert ? createAssertClientJS(fn.name) : ""),
)
/function\s*\(.*?\)\s*{/,
'$&"use strict";' +
(usesDebug ? createLogClientJS("BUILTINS", fn.name) : "") +
(usesAssert ? createAssertClientJS(fn.name) : ""),
)
)
.replace(/^\((async )?function\(/, "($1function (")
.replace(/__intrinsic__/g, "@") + "\n";
Expand All @@ -221,8 +222,8 @@ $$capture_start$$(${fn.async ? "async " : ""}${useThis
overriddenName: fn.directives.getter
? `"get ${fn.name}"_s`
: fn.directives.overriddenName
? `"${fn.directives.overriddenName}"_s`
: "ASCIILiteral()",
? `"${fn.directives.overriddenName}"_s`
: "ASCIILiteral()",
});
}

Expand Down Expand Up @@ -281,8 +282,9 @@ for (const { basename, functions } of files) {
const name = `${lowerBasename}${cap(fn.name)}Code`;
bundledCPP += `// ${fn.name}
const JSC::ConstructAbility s_${name}ConstructAbility = JSC::ConstructAbility::${fn.constructAbility};
const JSC::InlineAttribute s_${name}InlineAttribute = JSC::InlineAttribute::${fn.directives.alwaysInline ? "Always" : "None"
};
const JSC::InlineAttribute s_${name}InlineAttribute = JSC::InlineAttribute::${
fn.directives.alwaysInline ? "Always" : "None"
};
const JSC::ConstructorKind s_${name}ConstructorKind = JSC::ConstructorKind::${fn.constructKind};
const JSC::ImplementationVisibility s_${name}ImplementationVisibility = JSC::ImplementationVisibility::${fn.visibility};
const int s_${name}Length = ${fn.source.length};
Expand Down
73 changes: 34 additions & 39 deletions src/codegen/bundle-modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ const {
// work, so i have lot of debug logs that blow up the console because not sure what is going on.
// that is also the reason for using `retry` when theoretically writing a file the first time
// should actually write the file.
const verbose = Bun.env.VERBOSE ? console.log : () => { };
const verbose = Bun.env.VERBOSE ? console.log : () => {};
async function retry(n, fn) {
var err;
while (n > 0) {
Expand Down Expand Up @@ -88,12 +88,12 @@ for (let i = 0; i < moduleList.length; i++) {

const processed = sliceSourceCode(
"{" +
input
.replace(
/\bimport(\s*type)?\s*(\{[^}]*\}|(\*\s*as)?\s[a-zA-Z0-9_$]+)\s*from\s*['"][^'"]+['"]/g,
stmt => (importStatements.push(stmt), ""),
)
.replace(/export\s*{\s*}\s*;/g, ""),
input
.replace(
/\bimport(\s*type)?\s*(\{[^}]*\}|(\*\s*as)?\s[a-zA-Z0-9_$]+)\s*from\s*['"][^'"]+['"]/g,
stmt => (importStatements.push(stmt), ""),
)
.replace(/export\s*{\s*}\s*;/g, ""),
true,
x => requireTransformer(x, moduleList[i]),
);
Expand Down Expand Up @@ -237,13 +237,13 @@ for (const entrypoint of bundledEntryPoints) {
captured = captured.replace(
/function\s*\(.*?\)\s*{/,
'$&"use strict";' +
(usesDebug
? createLogClientJS(
file_path.replace(".js", ""),
idToPublicSpecifierOrEnumName(file_path).replace(/^node:|^bun:/, ""),
)
: "") +
(usesAssert ? createAssertClientJS(idToPublicSpecifierOrEnumName(file_path).replace(/^node:|^bun:/, "")) : ""),
(usesDebug
? createLogClientJS(
file_path.replace(".js", ""),
idToPublicSpecifierOrEnumName(file_path).replace(/^node:|^bun:/, ""),
)
: "") +
(usesAssert ? createAssertClientJS(idToPublicSpecifierOrEnumName(file_path).replace(/^node:|^bun:/, "")) : ""),
);
const outputPath = path.join(JS_DIR, file_path);
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
Expand Down Expand Up @@ -286,11 +286,12 @@ writeIfNotChanged(
// actually use this enum but it's probably a good thing to include.
writeIfNotChanged(
path.join(CODEGEN_DIR, "InternalModuleRegistry+enum.h"),
`${moduleList
.map((id, n) => {
return `${idToEnumName(id)} = ${n},`;
})
.join("\n") + "\n"
`${
moduleList
.map((id, n) => {
return `${idToEnumName(id)} = ${n},`;
})
.join("\n") + "\n"
}
`,
);
Expand All @@ -304,16 +305,16 @@ JSValue InternalModuleRegistry::createInternalModuleById(JSGlobalObject* globalO
switch (id) {
// JS internal modules
${moduleList
.map((id, n) => {
return `case Field::${idToEnumName(id)}: {
.map((id, n) => {
return `case Field::${idToEnumName(id)}: {
INTERNAL_MODULE_REGISTRY_GENERATE(globalObject, vm, "${idToPublicSpecifierOrEnumName(id)}"_s, ${JSON.stringify(
id.replace(/\.[mc]?[tj]s$/, ".js"),
)}_s, InternalModuleRegistryConstants::${idToEnumName(id)}Code, "builtin://${id
.replace(/\.[mc]?[tj]s$/, "")
.replace(/[^a-zA-Z0-9]+/g, "/")}"_s);
id.replace(/\.[mc]?[tj]s$/, ".js"),
)}_s, InternalModuleRegistryConstants::${idToEnumName(id)}Code, "builtin://${id
.replace(/\.[mc]?[tj]s$/, "")
.replace(/[^a-zA-Z0-9]+/g, "/")}"_s);
}`;
})
.join("\n ")}
})
.join("\n ")}
default: {
__builtin_unreachable();
}
Expand Down Expand Up @@ -373,8 +374,8 @@ pub const ResolvedSourceTag = enum(u32) {
${moduleList.map((id, n) => ` @"${idToPublicSpecifierOrEnumName(id)}" = ${(1 << 9) | n},`).join("\n")}
// Native modules run through a different system using ESM registry.
${Object.entries(nativeModuleIds)
.map(([id, n]) => ` @"${id}" = ${(1 << 10) | n},`)
.join("\n")}
.map(([id, n]) => ` @"${id}" = ${(1 << 10) | n},`)
.join("\n")}
};
`,
);
Expand All @@ -400,8 +401,8 @@ ${moduleList.map((id, n) => ` ${idToEnumName(id)} = ${(1 << 9) | n},`).join("
// They also have bit 10 set to differentiate them from JS builtins.
NativeModuleFlag = (1 << 10) | (1 << 9),
${Object.entries(nativeModuleEnumToId)
.map(([id, n]) => ` ${id} = ${(1 << 10) | n},`)
.join("\n")}
.map(([id, n]) => ` ${id} = ${(1 << 10) | n},`)
.join("\n")}
};
`,
Expand All @@ -415,16 +416,10 @@ writeIfNotChanged(
.join("\n") + "\n",
);

writeIfNotChanged(
path.join(CODEGEN_DIR, "GeneratedJS2Native.h"),
getJS2NativeCPP(),
);
writeIfNotChanged(path.join(CODEGEN_DIR, "GeneratedJS2Native.h"), getJS2NativeCPP());

// zig will complain if this file is outside of the module
const js2nativeZigPath = path.join(import.meta.dir, "../bun.js/bindings/GeneratedJS2Native.zig");
writeIfNotChanged(
js2nativeZigPath,
getJS2NativeZig(js2nativeZigPath),
);
writeIfNotChanged(js2nativeZigPath, getJS2NativeZig(js2nativeZigPath));

mark("Generate Code");
6 changes: 4 additions & 2 deletions src/codegen/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ export function readdirRecursiveWithExclusionsAndExtensionsSync(
const fullPath = path.join(dir, entry.name);
return entry.isDirectory()
? readdirRecursiveWithExclusionsAndExtensionsSync(fullPath, exclusions, exts)
: exts.includes(path.extname(fullPath)) ? fullPath : [];
: exts.includes(path.extname(fullPath))
? fullPath
: [];
});
}
}
38 changes: 15 additions & 23 deletions src/codegen/js2native-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,24 +19,17 @@ type NativeCallType = "zig" | "cpp";
const nativeCalls: NativeCall[] = [];

const sourceFiles = readdirRecursiveWithExclusionsAndExtensionsSync(
path.join(import.meta.dir, '../'),
[
'deps',
'node_modules',
'WebKit',
],
[
'.cpp',
'.zig',
],
path.join(import.meta.dir, "../"),
["deps", "node_modules", "WebKit"],
[".cpp", ".zig"],
);

function resolveNativeFileId(call_type: NativeCallType, filename: string) {
if (!filename.endsWith("." + call_type)) {
throw new Error(`Expected filename for $${call_type} to have .${call_type} extension`);
}

const resolved = sourceFiles.find(file => file.endsWith('/' + filename));
const resolved = sourceFiles.find(file => file.endsWith("/" + filename));
if (!resolved) {
throw new Error(`Could not find file ${filename} in $${call_type} call`);
}
Expand Down Expand Up @@ -78,14 +71,13 @@ function cppPointer(call: NativeCall) {
}

export function getJS2NativeCPP() {
const files = [...new Set(nativeCalls.filter(x => x.type === 'cpp').map(x => x.filename))];
const files = [...new Set(nativeCalls.filter(x => x.type === "cpp").map(x => x.filename))];

return [
`#pragma once`,
...files
.map(filename => `#include ${JSON.stringify(filename.replace(/.cpp$/, '.h'))}`),
...files.map(filename => `#include ${JSON.stringify(filename.replace(/.cpp$/, ".h"))}`),
...nativeCalls
.filter(x => x.type === 'zig')
.filter(x => x.type === "zig")
.map(call => `extern "C" JSC::EncodedJSValue ${symbol(call)}(Zig::GlobalObject*);`),
"typedef JSC::JSValue (*JS2NativeFunction)(Zig::GlobalObject*);",
"static JS2NativeFunction js2nativePointers[] = {",
Expand All @@ -100,16 +92,16 @@ export function getJS2NativeZig(gs2NativeZigPath: string) {
`const JSC = @import("root").bun.JSC;`,
// `const JSC = bun.JSC;`,
...nativeCalls
.filter(x => x.type === 'zig')
.filter(x => x.type === "zig")
.flatMap(call => [
`export fn ${symbol(call)}(global: *JSC.JSGlobalObject) JSC.JSValue {`,
` return @import(${JSON.stringify(path.relative(path.dirname(gs2NativeZigPath), call.filename))}).${call.symbol}(global);`,
'}',
` return @import(${JSON.stringify(path.relative(path.dirname(gs2NativeZigPath), call.filename))}).${
call.symbol
}(global);`,
"}",
]),
'comptime {',
...nativeCalls
.filter(x => x.type === 'zig')
.flatMap(call => ` _ = &${symbol(call)};`),
'}',
"comptime {",
...nativeCalls.filter(x => x.type === "zig").flatMap(call => ` _ = &${symbol(call)};`),
"}",
].join("\n");
}
37 changes: 15 additions & 22 deletions src/codegen/replacements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,42 +155,35 @@ export function applyReplacements(src: string, length: number) {
}
return [
slice.slice(0, match.index) +
"(IS_BUN_DEVELOPMENT?$assert(" +
checkSlice.result.slice(1, -1) +
"," +
JSON.stringify(
checkSlice.result
.slice(1, -1)
.replace(/__intrinsic__/g, "$")
.trim(),
) +
extraArgs +
"):void 0)",
"(IS_BUN_DEVELOPMENT?$assert(" +
checkSlice.result.slice(1, -1) +
"," +
JSON.stringify(
checkSlice.result
.slice(1, -1)
.replace(/__intrinsic__/g, "$")
.trim(),
) +
extraArgs +
"):void 0)",
rest2,
true,
];
} else if (name == 'zig' || name == 'cpp') {
} else if (name == "zig" || name == "cpp") {
const inner = sliceSourceCode(rest, true);
let args;
try {
args = JSON.parse('[' + inner.result.slice(1, -1).replaceAll("'", "\"") + ']');
args = JSON.parse("[" + inner.result.slice(1, -1).replaceAll("'", '"') + "]");
} catch {
throw new Error(`Call is not known at bundle-time: '$${name}${inner.result}'`);
}
if (args.length != 2
|| typeof args[0] !== 'string'
|| typeof args[1] !== 'string'
) {
if (args.length != 2 || typeof args[0] !== "string" || typeof args[1] !== "string") {
throw new Error(`$${name} takes two string arguments, but got '$${name}${inner.result}'`);
}

const id = registerNativeCall(name, args[0], args[1]);

return [
slice.slice(0, match.index) + "__intrinsic__native(" + id + ")",
inner.rest,
true,
];
return [slice.slice(0, match.index) + "__intrinsic__native(" + id + ")", inner.rest, true];
}
}
return [slice, rest, false];
Expand Down
6 changes: 3 additions & 3 deletions src/js/bun/sqlite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ class Database {
}

if (!SQL) {
SQL = $cpp('JSSQLStatement.cpp', 'WebCore::createJSSQLStatementConstructor');
SQL = $cpp("JSSQLStatement.cpp", "WebCore::createJSSQLStatementConstructor");
}

this.#handle = SQL.open(anonymous ? ":memory:" : filename, flags);
Expand Down Expand Up @@ -245,7 +245,7 @@ class Database {

static #deserialize(serialized, isReadOnly = false) {
if (!SQL) {
SQL = $cpp('JSSQLStatement.cpp', 'WebCore::createJSSQLStatementConstructor');
SQL = $cpp("JSSQLStatement.cpp", "WebCore::createJSSQLStatementConstructor");
}

return SQL.deserialize(serialized, isReadOnly);
Expand All @@ -257,7 +257,7 @@ class Database {

static setCustomSQLite(path) {
if (!SQL) {
SQL = $cpp('JSSQLStatement.cpp', 'WebCore::createJSSQLStatementConstructor');
SQL = $cpp("JSSQLStatement.cpp", "WebCore::createJSSQLStatementConstructor");
}

return SQL.setCustomSQLite(path);
Expand Down
5 changes: 1 addition & 4 deletions src/js/node/async_hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,7 @@
// each key is an AsyncLocalStorage object and the value is the associated value. There are a ton of
// calls to $assert which will verify this invariant (only during bun-debug)
//
const [
cleanupLater,
setAsyncHooksEnabled,
] = $cpp('AsyncHooksBinding.cpp', 'Bun::createAsyncHooksBinding');
const [cleanupLater, setAsyncHooksEnabled] = $cpp("AsyncHooksBinding.cpp", "Bun::createAsyncHooksBinding");

// Only run during debug
function assertValidAsyncContextArray(array: unknown): array is ReadonlyArray<any> | undefined {
Expand Down

0 comments on commit deb72c4

Please sign in to comment.