diff --git a/src/bun.js/ConsoleObject.zig b/src/bun.js/ConsoleObject.zig index 4c02d210dd..cafa239b12 100644 --- a/src/bun.js/ConsoleObject.zig +++ b/src/bun.js/ConsoleObject.zig @@ -3,7 +3,6 @@ const bun = @import("root").bun; const JSC = bun.JSC; const Output = bun.Output; const ConsoleObject = @This(); -const Shimmer = @import("./bindings/shimmer.zig").Shimmer; const String = bun.String; const JSGlobalObject = JSC.JSGlobalObject; const JSValue = JSC.JSValue; @@ -20,11 +19,6 @@ const default_allocator = bun.default_allocator; const JestPrettyFormat = @import("./test/pretty_format.zig").JestPrettyFormat; const JSPromise = JSC.JSPromise; const EventType = JSC.EventType; -pub const shim = Shimmer("Bun", "ConsoleObject", @This()); -pub const Type = *anyopaque; -pub const name = "Bun::ConsoleObject"; -pub const include = "\"ConsoleObject.h\""; -pub const namespace = shim.namespace; const Counter = std.AutoHashMapUnmanaged(u64, u32); @@ -79,8 +73,7 @@ threadlocal var stdout_lock_count: u16 = 0; /// https://console.spec.whatwg.org/#formatter pub fn messageWithTypeAndLevel( - //console_: ConsoleObject.Type, - ctype: ConsoleObject.Type, + ctype: *ConsoleObject, message_type: MessageType, //message_level: u32, level: MessageLevel, @@ -94,8 +87,8 @@ pub fn messageWithTypeAndLevel( }; } fn messageWithTypeAndLevel_( - //console_: ConsoleObject.Type, - _: ConsoleObject.Type, + //console_: *ConsoleObject, + _: *ConsoleObject, message_type: MessageType, //message_level: u32, level: MessageLevel, @@ -1759,7 +1752,7 @@ pub const Formatter = struct { formatter: *ConsoleObject.Formatter, writer: Writer, count: usize = 0, - pub fn forEach(_: [*c]JSC.VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void { + pub fn forEach(_: *JSC.VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void { var this: *@This() = bun.cast(*@This(), ctx orelse return); if (this.formatter.failed) return; if (single_line and this.count > 0) { @@ -1833,7 +1826,7 @@ pub const Formatter = struct { formatter: *ConsoleObject.Formatter, writer: Writer, is_first: bool = true, - pub fn forEach(_: [*c]JSC.VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void { + pub fn forEach(_: *JSC.VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void { var this: *@This() = bun.cast(*@This(), ctx orelse return); if (this.formatter.failed) return; if (single_line) { @@ -3506,7 +3499,7 @@ pub const Formatter = struct { pub fn count( // console - _: ConsoleObject.Type, + _: *ConsoleObject, // global globalThis: *JSGlobalObject, // chars @@ -3532,7 +3525,7 @@ pub fn count( } pub fn countReset( // console - _: ConsoleObject.Type, + _: *ConsoleObject, // global globalThis: *JSGlobalObject, // chars @@ -3554,7 +3547,7 @@ threadlocal var pending_time_logs_loaded = false; pub fn time( // console - _: ConsoleObject.Type, + _: *ConsoleObject, // global _: *JSGlobalObject, chars: [*]const u8, @@ -3574,7 +3567,7 @@ pub fn time( } pub fn timeEnd( // console - _: ConsoleObject.Type, + _: *ConsoleObject, // global _: *JSGlobalObject, chars: [*]const u8, @@ -3600,7 +3593,7 @@ pub fn timeEnd( pub fn timeLog( // console - _: ConsoleObject.Type, + _: *ConsoleObject, // global global: *JSGlobalObject, // chars @@ -3652,7 +3645,7 @@ pub fn timeLog( } pub fn profile( // console - _: ConsoleObject.Type, + _: *ConsoleObject, // global _: *JSGlobalObject, // chars @@ -3662,7 +3655,7 @@ pub fn profile( ) callconv(JSC.conv) void {} pub fn profileEnd( // console - _: ConsoleObject.Type, + _: *ConsoleObject, // global _: *JSGlobalObject, // chars @@ -3672,7 +3665,7 @@ pub fn profileEnd( ) callconv(JSC.conv) void {} pub fn takeHeapSnapshot( // console - _: ConsoleObject.Type, + _: *ConsoleObject, // global globalThis: *JSGlobalObject, // chars @@ -3686,7 +3679,7 @@ pub fn takeHeapSnapshot( } pub fn timeStamp( // console - _: ConsoleObject.Type, + _: *ConsoleObject, // global _: *JSGlobalObject, // args @@ -3694,7 +3687,7 @@ pub fn timeStamp( ) callconv(JSC.conv) void {} pub fn record( // console - _: ConsoleObject.Type, + _: *ConsoleObject, // global _: *JSGlobalObject, // args @@ -3702,7 +3695,7 @@ pub fn record( ) callconv(JSC.conv) void {} pub fn recordEnd( // console - _: ConsoleObject.Type, + _: *ConsoleObject, // global _: *JSGlobalObject, // args @@ -3710,7 +3703,7 @@ pub fn recordEnd( ) callconv(JSC.conv) void {} pub fn screenshot( // console - _: ConsoleObject.Type, + _: *ConsoleObject, // global _: *JSGlobalObject, // args @@ -3718,17 +3711,17 @@ pub fn screenshot( ) callconv(JSC.conv) void {} comptime { - @export(&messageWithTypeAndLevel, .{ .name = shim.symbolName("messageWithTypeAndLevel") }); - @export(&count, .{ .name = shim.symbolName("count") }); - @export(&countReset, .{ .name = shim.symbolName("countReset") }); - @export(&time, .{ .name = shim.symbolName("time") }); - @export(&timeLog, .{ .name = shim.symbolName("timeLog") }); - @export(&timeEnd, .{ .name = shim.symbolName("timeEnd") }); - @export(&profile, .{ .name = shim.symbolName("profile") }); - @export(&profileEnd, .{ .name = shim.symbolName("profileEnd") }); - @export(&takeHeapSnapshot, .{ .name = shim.symbolName("takeHeapSnapshot") }); - @export(&timeStamp, .{ .name = shim.symbolName("timeStamp") }); - @export(&record, .{ .name = shim.symbolName("record") }); - @export(&recordEnd, .{ .name = shim.symbolName("recordEnd") }); - @export(&screenshot, .{ .name = shim.symbolName("screenshot") }); + @export(&messageWithTypeAndLevel, .{ .name = "Bun__ConsoleObject__messageWithTypeAndLevel" }); + @export(&count, .{ .name = "Bun__ConsoleObject__count" }); + @export(&countReset, .{ .name = "Bun__ConsoleObject__countReset" }); + @export(&time, .{ .name = "Bun__ConsoleObject__time" }); + @export(&timeLog, .{ .name = "Bun__ConsoleObject__timeLog" }); + @export(&timeEnd, .{ .name = "Bun__ConsoleObject__timeEnd" }); + @export(&profile, .{ .name = "Bun__ConsoleObject__profile" }); + @export(&profileEnd, .{ .name = "Bun__ConsoleObject__profileEnd" }); + @export(&takeHeapSnapshot, .{ .name = "Bun__ConsoleObject__takeHeapSnapshot" }); + @export(&timeStamp, .{ .name = "Bun__ConsoleObject__timeStamp" }); + @export(&record, .{ .name = "Bun__ConsoleObject__record" }); + @export(&recordEnd, .{ .name = "Bun__ConsoleObject__recordEnd" }); + @export(&screenshot, .{ .name = "Bun__ConsoleObject__screenshot" }); } diff --git a/src/bun.js/api/Timer.zig b/src/bun.js/api/Timer.zig index b8eb7e657a..ddacbcf984 100644 --- a/src/bun.js/api/Timer.zig +++ b/src/bun.js/api/Timer.zig @@ -516,27 +516,14 @@ pub const All = struct { return JSValue.jsUndefined(); } - const Shimmer = @import("../bindings/shimmer.zig").Shimmer; - - pub const shim = Shimmer("Bun", "Timer", @This()); - pub const name = "Bun__Timer"; - pub const include = ""; - pub const namespace = shim.namespace; - - pub const Export = shim.exportFunctions(.{ - .setImmediate = setImmediate, - .setTimeout = setTimeout, - .setInterval = setInterval, - .clearImmediate = clearImmediate, - .clearTimeout = clearTimeout, - .clearInterval = clearInterval, - .getNextID = getNextID, - }); - comptime { - for (Export) |e| { - @export(&@field(e.Parent, e.local_name), .{ .name = e.symbol_name }); - } + @export(&setImmediate, .{ .name = "Bun__Timer__setImmediate" }); + @export(&setTimeout, .{ .name = "Bun__Timer__setTimeout" }); + @export(&setInterval, .{ .name = "Bun__Timer__setInterval" }); + @export(&clearImmediate, .{ .name = "Bun__Timer__clearImmediate" }); + @export(&clearTimeout, .{ .name = "Bun__Timer__clearTimeout" }); + @export(&clearInterval, .{ .name = "Bun__Timer__clearInterval" }); + @export(&getNextID, .{ .name = "Bun__Timer__getNextID" }); } }; diff --git a/src/bun.js/api/ffi.zig b/src/bun.js/api/ffi.zig index 61b878bfda..d4dfbea81e 100644 --- a/src/bun.js/api/ffi.zig +++ b/src/bun.js/api/ffi.zig @@ -2365,12 +2365,12 @@ const CompilerRT = struct { UINT64_TO_JSVALUE: *const fn (arg0: *JSC.JSGlobalObject, arg1: u64) callconv(.C) JSC.JSValue, bun_call: *const @TypeOf(JSC.C.JSObjectCallAsFunction), }; - const headers = @import("../bindings/headers.zig"); + const headers = JSValue.exposed_to_ffi; var workaround: MyFunctionSStructWorkAround = .{ - .JSVALUE_TO_INT64 = headers.JSC__JSValue__toInt64, - .JSVALUE_TO_UINT64 = headers.JSC__JSValue__toUInt64NoTruncate, - .INT64_TO_JSVALUE = headers.JSC__JSValue__fromInt64NoTruncate, - .UINT64_TO_JSVALUE = headers.JSC__JSValue__fromUInt64NoTruncate, + .JSVALUE_TO_INT64 = headers.JSVALUE_TO_INT64, + .JSVALUE_TO_UINT64 = headers.JSVALUE_TO_UINT64, + .INT64_TO_JSVALUE = headers.INT64_TO_JSVALUE, + .UINT64_TO_JSVALUE = headers.UINT64_TO_JSVALUE, .bun_call = &JSC.C.JSObjectCallAsFunction, }; @@ -2420,10 +2420,6 @@ const CompilerRT = struct { state.addSymbol("JSVALUE_TO_INT64_SLOW", workaround.JSVALUE_TO_INT64) catch unreachable; state.addSymbol("JSVALUE_TO_UINT64_SLOW", workaround.JSVALUE_TO_UINT64) catch unreachable; - std.mem.doNotOptimizeAway(headers.JSC__JSValue__toUInt64NoTruncate); - std.mem.doNotOptimizeAway(headers.JSC__JSValue__toInt64); - std.mem.doNotOptimizeAway(headers.JSC__JSValue__fromInt64NoTruncate); - std.mem.doNotOptimizeAway(headers.JSC__JSValue__fromUInt64NoTruncate); state.addSymbol("INT64_TO_JSVALUE_SLOW", workaround.INT64_TO_JSVALUE) catch unreachable; state.addSymbol("UINT64_TO_JSVALUE_SLOW", workaround.UINT64_TO_JSVALUE) catch unreachable; } diff --git a/src/bun.js/api/server.zig b/src/bun.js/api/server.zig index 51a0ace195..8927c6c9f7 100644 --- a/src/bun.js/api/server.zig +++ b/src/bun.js/api/server.zig @@ -2174,9 +2174,6 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp // It costs about 655,632 bytes. pub const RequestContextStackAllocator = bun.HiveArray(RequestContext, if (bun.heap_breakdown.enabled) 0 else 2048).Fallback; - pub const name = "HTTPRequestContext" ++ (if (debug_mode) "Debug" else "") ++ (if (ThisServer.ssl_enabled) "TLS" else ""); - pub const shim = JSC.Shimmer("Bun", name, @This()); - server: ?*ThisServer, resp: ?*App.Response, /// thread-local default heap allocator @@ -4541,22 +4538,16 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp return false; } - pub const Export = shim.exportFunctions(.{ - .onResolve = onResolve, - .onReject = onReject, - .onResolveStream = onResolveStream, - .onRejectStream = onRejectStream, - }); - comptime { + const export_prefix = "Bun__HTTPRequestContext" ++ (if (debug_mode) "Debug" else "") ++ (if (ThisServer.ssl_enabled) "TLS" else ""); const jsonResolve = JSC.toJSHostFunction(onResolve); - @export(&jsonResolve, .{ .name = Export[0].symbol_name }); + @export(&jsonResolve, .{ .name = export_prefix ++ "__onResolve" }); const jsonReject = JSC.toJSHostFunction(onReject); - @export(&jsonReject, .{ .name = Export[1].symbol_name }); + @export(&jsonReject, .{ .name = export_prefix ++ "__onReject" }); const jsonResolveStream = JSC.toJSHostFunction(onResolveStream); - @export(&jsonResolveStream, .{ .name = Export[2].symbol_name }); + @export(&jsonResolveStream, .{ .name = export_prefix ++ "__onResolveStream" }); const jsonRejectStream = JSC.toJSHostFunction(onRejectStream); - @export(&jsonRejectStream, .{ .name = Export[3].symbol_name }); + @export(&jsonRejectStream, .{ .name = export_prefix ++ "__onRejectStream" }); } }; } diff --git a/src/bun.js/base.zig b/src/bun.js/base.zig index 9e3f42eec9..66b2889d3e 100644 --- a/src/bun.js/base.zig +++ b/src/bun.js/base.zig @@ -978,8 +978,6 @@ pub fn DOMCall( pub const is_dom_call = true; const Slowpath = @field(Container, functionName); const SlowpathType = @TypeOf(@field(Container, functionName)); - pub const shim = JSC.Shimmer(className, functionName, @This()); - pub const name = class_name ++ "__" ++ functionName; // Zig doesn't support @frameAddress(1) // so we have to add a small wrapper fujnction @@ -995,18 +993,18 @@ pub fn DOMCall( pub const fastpath = @field(Container, functionName ++ "WithoutTypeChecks"); pub const Fastpath = @TypeOf(fastpath); pub const Arguments = std.meta.ArgsTuple(Fastpath); + const PutFnType = *const fn (globalObject: *JSC.JSGlobalObject, value: JSC.JSValue) callconv(.c) void; + const put_fn = @extern(PutFnType, .{ .name = className ++ "__" ++ functionName ++ "__put" }); pub fn put(globalObject: *JSC.JSGlobalObject, value: JSC.JSValue) void { - shim.cppFn("put", .{ globalObject, value }); + put_fn(globalObject, value); } pub const effect = dom_effect; - pub const Extern = [_][]const u8{"put"}; - comptime { - @export(&slowpath, .{ .name = shim.symbolName("slowpath") }); - @export(&fastpath, .{ .name = shim.symbolName("fastpath") }); + @export(&slowpath, .{ .name = className ++ "__" ++ functionName ++ "__slowpath" }); + @export(&fastpath, .{ .name = className ++ "__" ++ functionName ++ "__fastpath" }); } }; } diff --git a/src/bun.js/bindings/BunProcess.cpp b/src/bun.js/bindings/BunProcess.cpp index 23af270a91..f78dc8d2bf 100644 --- a/src/bun.js/bindings/BunProcess.cpp +++ b/src/bun.js/bindings/BunProcess.cpp @@ -448,10 +448,34 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionDlopen, (JSC::JSGlobalObject * globalOb #if OS(WINDOWS) DWORD errorId = GetLastError(); LPWSTR messageBuffer = nullptr; - size_t size = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, errorId, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&messageBuffer, 0, NULL); - WTF::String msg = makeString("LoadLibrary failed: "_s, WTF::StringView(std::span { (UCHAR*)messageBuffer, size })); - LocalFree(messageBuffer); + DWORD charCount = FormatMessageW( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, // Prevents automatic line breaks + NULL, // No source needed when using FORMAT_MESSAGE_FROM_SYSTEM + errorId, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language + (LPWSTR)&messageBuffer, // Buffer will be allocated by the function + 0, // Minimum size to allocate - 0 means "determine size automatically" + NULL // No arguments since we're using FORMAT_MESSAGE_IGNORE_INSERTS + ); + + WTF::StringBuilder errorBuilder; + errorBuilder.append("LoadLibrary failed: "_s); + if (messageBuffer && charCount > 0) { + // Trim trailing whitespace, carriage returns, and newlines that FormatMessageW often includes + while (charCount > 0 && (messageBuffer[charCount - 1] == L'\r' || messageBuffer[charCount - 1] == L'\n' || messageBuffer[charCount - 1] == L' ')) + charCount--; + + // Create a span of the wide characters + auto wideCharSpan = std::span(reinterpret_cast(messageBuffer), charCount); + errorBuilder.append(WTF::StringView(wideCharSpan)); + } else { + errorBuilder.append("error code "_s); + errorBuilder.append(WTF::String::number(errorId)); + } + + WTF::String msg = errorBuilder.toString(); + if (messageBuffer) + LocalFree(messageBuffer); // Free the buffer allocated by FormatMessageW #else WTF::String msg = WTF::String::fromUTF8(dlerror()); #endif diff --git a/src/bun.js/bindings/CustomGetterSetter.zig b/src/bun.js/bindings/CustomGetterSetter.zig index 7a423a3bfc..b0484f7641 100644 --- a/src/bun.js/bindings/CustomGetterSetter.zig +++ b/src/bun.js/bindings/CustomGetterSetter.zig @@ -2,19 +2,14 @@ const std = @import("std"); const bun = @import("root").bun; const JSC = bun.JSC; -pub const CustomGetterSetter = extern struct { - pub const shim = JSC.Shimmer("JSC", "CustomGetterSetter", @This()); - bytes: shim.Bytes, - const cppFn = shim.cppFn; - pub const include = "JavaScriptCore/CustomGetterSetter.h"; - pub const name = "JSC::CustomGetterSetter"; - pub const namespace = "JSC"; - +pub const CustomGetterSetter = opaque { pub fn isGetterNull(this: *CustomGetterSetter) bool { - return shim.cppFn("isGetterNull", .{this}); + return JSC__CustomGetterSetter__isGetterNull(this); } pub fn isSetterNull(this: *CustomGetterSetter) bool { - return shim.cppFn("isSetterNull", .{this}); + return JSC__CustomGetterSetter__isSetterNull(this); } + extern fn JSC__CustomGetterSetter__isGetterNull(this: *CustomGetterSetter) bool; + extern fn JSC__CustomGetterSetter__isSetterNull(this: *CustomGetterSetter) bool; }; diff --git a/src/bun.js/bindings/DOMFormData.zig b/src/bun.js/bindings/DOMFormData.zig index 1e553f52bb..0a658b8c60 100644 --- a/src/bun.js/bindings/DOMFormData.zig +++ b/src/bun.js/bindings/DOMFormData.zig @@ -127,13 +127,4 @@ pub const DOMFormData = opaque { JSC.markBinding(@src()); DOMFormData__forEach(this, ctx, Wrap.forEachWrapper); } - - pub const Extern = [_][]const u8{ - "create", - "fromJS", - "append", - "appendBlob", - "count", - "createFromURLQuery", - }; }; diff --git a/src/bun.js/bindings/Errorable.zig b/src/bun.js/bindings/Errorable.zig index c9cb446ba5..a1aac13d03 100644 --- a/src/bun.js/bindings/Errorable.zig +++ b/src/bun.js/bindings/Errorable.zig @@ -8,7 +8,6 @@ pub fn Errorable(comptime Type: type) type { return extern struct { result: Result, success: bool, - pub const name = "Errorable" ++ typeBaseName(@typeName(Type)); pub const Result = extern union { value: Type, @@ -31,7 +30,6 @@ pub fn Errorable(comptime Type: type) type { return @This(){ .result = .{ .value = val }, .success = true }; } - threadlocal var err_buf: [4096]u8 = undefined; pub fn err(code: anyerror, ptr: *anyopaque) @This() { return @This(){ .result = .{ diff --git a/src/bun.js/bindings/GetterSetter.zig b/src/bun.js/bindings/GetterSetter.zig index 551ecf1c4b..71b4ffb52d 100644 --- a/src/bun.js/bindings/GetterSetter.zig +++ b/src/bun.js/bindings/GetterSetter.zig @@ -2,19 +2,14 @@ const std = @import("std"); const bun = @import("root").bun; const JSC = bun.JSC; -pub const GetterSetter = extern struct { - pub const shim = JSC.Shimmer("JSC", "GetterSetter", @This()); - bytes: shim.Bytes, - const cppFn = shim.cppFn; - pub const include = "JavaScriptCore/GetterSetter.h"; - pub const name = "JSC::GetterSetter"; - pub const namespace = "JSC"; - +pub const GetterSetter = opaque { pub fn isGetterNull(this: *GetterSetter) bool { - return shim.cppFn("isGetterNull", .{this}); + return JSC__GetterSetter__isGetterNull(this); } pub fn isSetterNull(this: *GetterSetter) bool { - return shim.cppFn("isSetterNull", .{this}); + return JSC__GetterSetter__isSetterNull(this); } + extern fn JSC__GetterSetter__isGetterNull(this: *GetterSetter) bool; + extern fn JSC__GetterSetter__isSetterNull(this: *GetterSetter) bool; }; diff --git a/src/bun.js/bindings/JSCell.zig b/src/bun.js/bindings/JSCell.zig index 4ef936fd97..ee6cb89c30 100644 --- a/src/bun.js/bindings/JSCell.zig +++ b/src/bun.js/bindings/JSCell.zig @@ -6,20 +6,11 @@ const JSGlobalObject = JSC.JSGlobalObject; const GetterSetter = @import("GetterSetter.zig").GetterSetter; const CustomGetterSetter = @import("CustomGetterSetter.zig").CustomGetterSetter; -pub const JSCell = extern struct { - pub const shim = JSC.Shimmer("JSC", "JSCell", @This()); - bytes: shim.Bytes, - const cppFn = shim.cppFn; - pub const include = "JavaScriptCore/JSCell.h"; - pub const name = "JSC::JSCell"; - pub const namespace = "JSC"; - - const CellType = enum(u8) { _ }; - +pub const JSCell = opaque { /// Statically cast a cell to a JSObject. Returns null for non-objects. /// Use `toObject` to mutate non-objects into objects. pub fn getObject(this: *JSCell) ?*JSC.JSObject { - return shim.cppFn("getObject", .{this}); + return JSC__JSCell__getObject(this); } /// Convert a cell to a JSObject. @@ -27,21 +18,17 @@ pub const JSCell = extern struct { /// Statically casts cells that are already objects, otherwise mutates them /// into objects. pub fn toObject(this: *JSCell, global: *JSC.JSGlobalObject) *JSC.JSObject { - return shim.cppFn("toObject", .{ this, global }); + return JSC__JSCell__toObject(this, global); } pub fn getType(this: *JSCell) u8 { - return shim.cppFn("getType", .{ - this, - }); + return JSC__JSCell__getType(this); } pub fn toJS(this: *JSCell) JSC.JSValue { return JSC.JSValue.fromCell(this); } - pub const Extern = [_][]const u8{ "getObject", "getType" }; - pub fn getGetterSetter(this: *JSCell) *GetterSetter { if (comptime bun.Environment.allow_assert) { bun.assert(JSValue.fromCell(this).isGetterSetter()); @@ -55,4 +42,8 @@ pub const JSCell = extern struct { } return @as(*CustomGetterSetter, @ptrCast(@alignCast(this))); } + + extern fn JSC__JSCell__getObject(this: *JSCell) *JSC.JSObject; + extern fn JSC__JSCell__toObject(this: *JSCell, *JSGlobalObject) *JSC.JSObject; + extern fn JSC__JSCell__getType(this: *JSCell) u8; }; diff --git a/src/bun.js/bindings/JSFunction.zig b/src/bun.js/bindings/JSFunction.zig index 9418e9659f..ae1363d08a 100644 --- a/src/bun.js/bindings/JSFunction.zig +++ b/src/bun.js/bindings/JSFunction.zig @@ -3,21 +3,13 @@ const bun = @import("root").bun; const string = bun.string; const Output = bun.Output; const JSC = bun.JSC; -const Shimmer = JSC.Shimmer; const JSHostFunctionType = JSC.JSHostFunctionType; const ZigString = JSC.ZigString; const String = bun.String; const JSGlobalObject = JSC.JSGlobalObject; const JSValue = JSC.JSValue; -pub const JSFunction = extern struct { - pub const shim = Shimmer("JSC", "JSFunction", @This()); - bytes: shim.Bytes, - const cppFn = shim.cppFn; - pub const include = "JavaScriptCore/JSFunction.h"; - pub const name = "JSC::JSFunction"; - pub const namespace = "JSC"; - +pub const JSFunction = opaque { const ImplementationVisibility = enum(u8) { public, private, @@ -67,8 +59,9 @@ pub const JSFunction = extern struct { ); } + pub extern fn JSC__JSFunction__optimizeSoon(value: JSValue) void; pub fn optimizeSoon(value: JSValue) void { - cppFn("optimizeSoon", .{value}); + JSC__JSFunction__optimizeSoon(value); } extern fn JSC__JSFunction__getSourceCode(value: JSValue, out: *ZigString) bool; @@ -77,12 +70,4 @@ pub const JSFunction = extern struct { var str: ZigString = undefined; return if (JSC__JSFunction__getSourceCode(value, &str)) bun.String.init(str) else null; } - - pub const Extern = [_][]const u8{ - "fromString", - "getName", - "displayName", - "calculatedDisplayName", - "optimizeSoon", - }; }; diff --git a/src/bun.js/bindings/JSModuleLoader.zig b/src/bun.js/bindings/JSModuleLoader.zig index 1d0da923f0..eb419b8990 100644 --- a/src/bun.js/bindings/JSModuleLoader.zig +++ b/src/bun.js/bindings/JSModuleLoader.zig @@ -5,16 +5,20 @@ const JSC = bun.JSC; const JSValue = JSC.JSValue; const JSGlobalObject = JSC.JSGlobalObject; const JSInternalPromise = @import("JSInternalPromise.zig").JSInternalPromise; -const Shimmer = JSC.Shimmer; const String = bun.String; -pub const JSModuleLoader = extern struct { - pub const shim = Shimmer("JSC", "JSModuleLoader", @This()); - bytes: shim.Bytes, - const cppFn = shim.cppFn; - pub const include = "JavaScriptCore/JSModuleLoader.h"; - pub const name = "JSC::JSModuleLoader"; - pub const namespace = "JSC"; +pub const JSModuleLoader = opaque { + extern fn JSC__JSModuleLoader__evaluate( + globalObject: *JSGlobalObject, + sourceCodePtr: [*]const u8, + sourceCodeLen: usize, + originUrlPtr: [*]const u8, + originUrlLen: usize, + referrerUrlPtr: [*]const u8, + referrerUrlLen: usize, + thisValue: JSValue, + exception: [*]JSValue, + ) JSValue; pub fn evaluate( globalObject: *JSGlobalObject, @@ -27,7 +31,7 @@ pub const JSModuleLoader = extern struct { thisValue: JSValue, exception: [*]JSValue, ) JSValue { - return shim.cppFn("evaluate", .{ + return JSC__JSModuleLoader__evaluate( globalObject, sourceCodePtr, sourceCodeLen, @@ -37,7 +41,7 @@ pub const JSModuleLoader = extern struct { referrerUrlLen, thisValue, exception, - }); + ); } extern fn JSC__JSModuleLoader__loadAndEvaluateModule(arg0: *JSGlobalObject, arg1: ?*const String) *JSInternalPromise; pub fn loadAndEvaluateModule(globalObject: *JSGlobalObject, module_name: ?*const bun.String) ?*JSInternalPromise { @@ -48,15 +52,4 @@ pub const JSModuleLoader = extern struct { pub fn import(globalObject: *JSGlobalObject, module_name: *const bun.String) *JSInternalPromise { return JSModuleLoader__import(globalObject, module_name); } - - // pub fn dependencyKeysIfEvaluated(this: *JSModuleLoader, globalObject: *JSGlobalObject, moduleRecord: *JSModuleRecord) *JSValue { - // return shim.cppFn("dependencyKeysIfEvaluated", .{ this, globalObject, moduleRecord }); - // } - - pub const Extern = [_][]const u8{ - "evaluate", - "loadAndEvaluateModule", - "importModule", - "checkSyntax", - }; }; diff --git a/src/bun.js/bindings/JSObject.zig b/src/bun.js/bindings/JSObject.zig index d7956ec1d0..7a54c780ce 100644 --- a/src/bun.js/bindings/JSObject.zig +++ b/src/bun.js/bindings/JSObject.zig @@ -1,14 +1,16 @@ const std = @import("std"); const bun = @import("root").bun; const JSC = bun.JSC; -const Shimmer = JSC.Shimmer; const JSValue = JSC.JSValue; const JSGlobalObject = JSC.JSGlobalObject; const ZigString = JSC.ZigString; -pub const JSObject = extern struct { - pub const shim = Shimmer("JSC", "JSObject", @This()); - const cppFn = shim.cppFn; +pub const JSObject = opaque { + extern fn JSC__JSObject__getIndex(this: JSValue, globalThis: *JSGlobalObject, i: u32) JSValue; + extern fn JSC__JSObject__putRecord(this: *JSObject, global: *JSGlobalObject, key: *ZigString, values: [*]ZigString, len: usize) void; + extern fn Bun__JSObject__getCodePropertyVMInquiry(global: *JSGlobalObject, obj: *JSObject) JSValue; + extern fn JSC__createStructure(global: *JSC.JSGlobalObject, owner: *JSC.JSCell, length: u32, names: [*]ExternColumnIdentifier) JSC.JSValue; + extern fn JSC__JSObject__create(global_object: *JSGlobalObject, length: usize, ctx: *anyopaque, initializer: InitializeCallback) JSValue; pub fn toJS(obj: *JSObject) JSValue { return JSValue.fromCell(obj); @@ -84,8 +86,6 @@ pub const JSObject = extern struct { } } - extern fn JSC__createStructure(*JSC.JSGlobalObject, *JSC.JSCell, u32, names: [*]ExternColumnIdentifier) JSC.JSValue; - pub const ExternColumnIdentifier = extern struct { tag: u8 = 0, value: extern union { @@ -112,7 +112,6 @@ pub const JSObject = extern struct { } const InitializeCallback = *const fn (ctx: *anyopaque, obj: *JSObject, global: *JSGlobalObject) callconv(.C) void; - extern fn JSC__JSObject__create(global_object: *JSGlobalObject, length: usize, ctx: *anyopaque, initializer: InitializeCallback) JSValue; pub fn Initializer(comptime Ctx: type, comptime func: fn (*Ctx, obj: *JSObject, global: *JSGlobalObject) void) type { return struct { @@ -128,19 +127,13 @@ pub const JSObject = extern struct { } pub fn getIndex(this: JSValue, globalThis: *JSGlobalObject, i: u32) JSValue { - return cppFn("getIndex", .{ - this, - globalThis, - i, - }); + return JSC__JSObject__getIndex(this, globalThis, i); } pub fn putRecord(this: *JSObject, global: *JSGlobalObject, key: *ZigString, values: []ZigString) void { - return cppFn("putRecord", .{ this, global, key, values.ptr, values.len }); + return JSC__JSObject__putRecord(this, global, key, values.ptr, values.len); } - extern fn Bun__JSObject__getCodePropertyVMInquiry(*JSGlobalObject, *JSObject) JSValue; - /// This will not call getters or be observable from JavaScript. pub fn getCodePropertyVMInquiry(obj: *JSObject, global: *JSGlobalObject) ?JSValue { const v = Bun__JSObject__getCodePropertyVMInquiry(global, obj); diff --git a/src/bun.js/bindings/JSString.zig b/src/bun.js/bindings/JSString.zig index 3ca0fe2387..729aa2620f 100644 --- a/src/bun.js/bindings/JSString.zig +++ b/src/bun.js/bindings/JSString.zig @@ -7,24 +7,24 @@ const JSObject = @import("JSObject.zig").JSObject; const ZigString = @import("ZigString.zig").ZigString; const JSError = bun.JSError; -pub const JSString = extern struct { - pub const shim = JSC.Shimmer("JSC", "JSString", @This()); - bytes: shim.Bytes, - const cppFn = shim.cppFn; - pub const include = "JavaScriptCore/JSString.h"; - pub const name = "JSC::JSString"; - pub const namespace = "JSC"; +pub const JSString = opaque { + extern fn JSC__JSString__toObject(this: *JSString, global: *JSGlobalObject) ?*JSObject; + extern fn JSC__JSString__toZigString(this: *JSString, global: *JSGlobalObject, zig_str: *JSC.ZigString) void; + extern fn JSC__JSString__eql(this: *const JSString, global: *JSGlobalObject, other: *JSString) bool; + extern fn JSC__JSString__iterator(this: *JSString, globalObject: *JSGlobalObject, iter: *anyopaque) void; + extern fn JSC__JSString__length(this: *const JSString) usize; + extern fn JSC__JSString__is8Bit(this: *const JSString) bool; pub fn toJS(str: *JSString) JSValue { return JSValue.fromCell(str); } pub fn toObject(this: *JSString, global: *JSGlobalObject) ?*JSObject { - return shim.cppFn("toObject", .{ this, global }); + return JSC__JSString__toObject(this, global); } pub fn toZigString(this: *JSString, global: *JSGlobalObject, zig_str: *JSC.ZigString) void { - return shim.cppFn("toZigString", .{ this, global, zig_str }); + return JSC__JSString__toZigString(this, global, zig_str); } pub fn ensureStillAlive(this: *JSString) void { @@ -71,23 +71,19 @@ pub const JSString = extern struct { } pub fn eql(this: *const JSString, global: *JSGlobalObject, other: *JSString) bool { - return shim.cppFn("eql", .{ this, global, other }); + return JSC__JSString__eql(this, global, other); } pub fn iterator(this: *JSString, globalObject: *JSGlobalObject, iter: *anyopaque) void { - return shim.cppFn("iterator", .{ this, globalObject, iter }); + return JSC__JSString__iterator(this, globalObject, iter); } pub fn length(this: *const JSString) usize { - return shim.cppFn("length", .{ - this, - }); + return JSC__JSString__length(this); } pub fn is8Bit(this: *const JSString) bool { - return shim.cppFn("is8Bit", .{ - this, - }); + return JSC__JSString__is8Bit(this); } pub const JStringIteratorAppend8Callback = *const fn (*Iterator, [*]const u8, u32) callconv(.C) void; @@ -102,6 +98,4 @@ pub const JSString = extern struct { write8: ?JStringIteratorWrite8Callback, write16: ?JStringIteratorWrite16Callback, }; - - pub const Extern = [_][]const u8{ "toZigString", "iterator", "toObject", "eql", "value", "length", "is8Bit", "createFromOwnedString", "createFromString" }; }; diff --git a/src/bun.js/bindings/JSValue.zig b/src/bun.js/bindings/JSValue.zig index 9a284f1f71..c08bfb492a 100644 --- a/src/bun.js/bindings/JSValue.zig +++ b/src/bun.js/bindings/JSValue.zig @@ -38,14 +38,7 @@ pub const JSValue = enum(i64) { return if (val != .zero) val else JSError.JSError; } - pub const shim = Shimmer("JSC", "JSValue", @This()); pub const is_pointer = false; - - const cppFn = shim.cppFn; - - pub const include = "JavaScriptCore/JSValue.h"; - pub const name = "JSC::JSValue"; - pub const namespace = "JSC"; pub const JSType = enum(u8) { Cell = 0, Structure = 1, @@ -406,12 +399,14 @@ pub const JSValue = enum(i64) { return @as(JSValue, @enumFromInt(@as(i64, @bitCast(@intFromPtr(ptr))))); } + extern fn JSC__JSValue__coerceToInt32(this: JSValue, globalThis: *JSC.JSGlobalObject) i32; pub fn coerceToInt32(this: JSValue, globalThis: *JSC.JSGlobalObject) i32 { - return cppFn("coerceToInt32", .{ this, globalThis }); + return JSC__JSValue__coerceToInt32(this, globalThis); } + extern fn JSC__JSValue__coerceToInt64(this: JSValue, globalThis: *JSC.JSGlobalObject) i64; pub fn coerceToInt64(this: JSValue, globalThis: *JSC.JSGlobalObject) i64 { - return cppFn("coerceToInt64", .{ this, globalThis }); + return JSC__JSValue__coerceToInt64(this, globalThis); } pub fn getIndex(this: JSValue, globalThis: *JSGlobalObject, i: u32) JSValue { @@ -438,9 +433,9 @@ pub const JSValue = enum(i64) { is_private_symbol: bool, ) callconv(.C) void; - pub extern fn JSC__JSValue__forEachPropertyNonIndexed(JSValue0: JSValue, arg1: *JSGlobalObject, arg2: ?*anyopaque, ArgFn3: ?*const fn (*JSGlobalObject, ?*anyopaque, *ZigString, JSValue, bool, bool) callconv(.C) void) void; - pub extern fn JSC__JSValue__forEachProperty(JSValue0: JSValue, arg1: *JSGlobalObject, arg2: ?*anyopaque, ArgFn3: ?*const fn (*JSGlobalObject, ?*anyopaque, *ZigString, JSValue, bool, bool) callconv(.C) void) void; - pub extern fn JSC__JSValue__forEachPropertyOrdered(JSValue0: JSValue, arg1: *JSGlobalObject, arg2: ?*anyopaque, ArgFn3: ?*const fn (*JSGlobalObject, ?*anyopaque, *ZigString, JSValue, bool, bool) callconv(.C) void) void; + extern fn JSC__JSValue__forEachPropertyNonIndexed(JSValue0: JSValue, arg1: *JSGlobalObject, arg2: ?*anyopaque, ArgFn3: ?*const fn (*JSGlobalObject, ?*anyopaque, *ZigString, JSValue, bool, bool) callconv(.C) void) void; + extern fn JSC__JSValue__forEachProperty(JSValue0: JSValue, arg1: *JSGlobalObject, arg2: ?*anyopaque, ArgFn3: ?*const fn (*JSGlobalObject, ?*anyopaque, *ZigString, JSValue, bool, bool) callconv(.C) void) void; + extern fn JSC__JSValue__forEachPropertyOrdered(JSValue0: JSValue, arg1: *JSGlobalObject, arg2: ?*anyopaque, ArgFn3: ?*const fn (*JSGlobalObject, ?*anyopaque, *ZigString, JSValue, bool, bool) callconv(.C) void) void; pub fn forEachPropertyNonIndexed( this: JSValue, @@ -469,15 +464,16 @@ pub const JSValue = enum(i64) { JSC__JSValue__forEachPropertyOrdered(this, globalObject, ctx, callback); } + extern fn JSC__JSValue__coerceToDouble(this: JSValue, globalObject: *JSC.JSGlobalObject) f64; /// Prefer toNumber over this function to /// - Match the underlying JSC api name /// - Match the underlying specification /// - Catch exceptions pub fn coerceToDouble(this: JSValue, globalObject: *JSC.JSGlobalObject) f64 { - return cppFn("coerceToDouble", .{ this, globalObject }); + return JSC__JSValue__coerceToDouble(this, globalObject); } - pub extern fn Bun__JSValue__toNumber(value: JSValue, global: *JSGlobalObject, had_error: *bool) f64; + extern fn Bun__JSValue__toNumber(value: JSValue, global: *JSGlobalObject, had_error: *bool) f64; /// Perform the ToNumber abstract operation, coercing a value to a number. /// Equivalent to `+value` @@ -583,11 +579,12 @@ pub const JSValue = enum(i64) { return JSC.Error.ERR_SOCKET_BAD_PORT.throw(global, "Invalid port number", .{}); } + extern fn JSC__JSValue__isInstanceOf(this: JSValue, global: *JSGlobalObject, constructor: JSValue) bool; pub fn isInstanceOf(this: JSValue, global: *JSGlobalObject, constructor: JSValue) bool { if (!this.isCell()) return false; - return cppFn("isInstanceOf", .{ this, global, constructor }); + return JSC__JSValue__isInstanceOf(this, global, constructor); } pub fn callWithGlobalThis(this: JSValue, globalThis: *JSGlobalObject, args: []const JSC.JSValue) !JSC.JSValue { @@ -636,13 +633,13 @@ pub const JSValue = enum(i64) { else => @compileError("needs more copy paste"), } } - + extern fn JSC__JSValue__jsType(this: JSValue) JSType; /// The value cannot be empty. Check `!this.isEmpty()` before calling this function pub fn jsType( this: JSValue, ) JSType { bun.assert(this != .zero); - return cppFn("jsType", .{this}); + return JSC__JSValue__jsType(this); } pub fn jsTypeLoose( @@ -666,22 +663,24 @@ pub const JSValue = enum(i64) { pub fn createEmptyObjectWithNullPrototype(global: *JSGlobalObject) JSValue { return JSC__JSValue__createEmptyObjectWithNullPrototype(global); } - + extern fn JSC__JSValue__createEmptyObject(global: *JSGlobalObject, len: usize) JSValue; /// Creates a new empty object, with Object as its prototype pub fn createEmptyObject(global: *JSGlobalObject, len: usize) JSValue { - return cppFn("createEmptyObject", .{ global, len }); + return JSC__JSValue__createEmptyObject(global, len); } + extern fn JSC__JSValue__createEmptyArray(global: *JSGlobalObject, len: usize) JSValue; pub fn createEmptyArray(global: *JSGlobalObject, len: usize) JSValue { - return cppFn("createEmptyArray", .{ global, len }); + return JSC__JSValue__createEmptyArray(global, len); } + extern fn JSC__JSValue__putRecord(value: JSValue, global: *JSGlobalObject, key: *ZigString, values_array: [*]ZigString, values_len: usize) void; pub fn putRecord(value: JSValue, global: *JSGlobalObject, key: *ZigString, values_array: [*]ZigString, values_len: usize) void { - return cppFn("putRecord", .{ value, global, key, values_array, values_len }); + return JSC__JSValue__putRecord(value, global, key, values_array, values_len); } - + extern fn JSC__JSValue__put(value: JSValue, global: *JSGlobalObject, key: *const ZigString, result: JSC.JSValue) void; pub fn putZigString(value: JSValue, global: *JSGlobalObject, key: *const ZigString, result: JSC.JSValue) void { - @import("./headers.zig").JSC__JSValue__put(value, global, key, result); + JSC__JSValue__put(value, global, key, result); } extern "c" fn JSC__JSValue__putBunString(value: JSValue, global: *JSGlobalObject, key: *const bun.String, result: JSC.JSValue) void; @@ -712,22 +711,22 @@ pub const JSValue = enum(i64) { @compileError("Unsupported key type in put(). Expected ZigString or bun.String, got " ++ @typeName(Key)); } } - - /// Note: key can't be numeric (if so, use putMayBeIndex instead) extern fn JSC__JSValue__putMayBeIndex(target: JSValue, globalObject: *JSGlobalObject, key: *const String, value: JSC.JSValue) void; - + /// Note: key can't be numeric (if so, use putMayBeIndex instead) /// Same as `.put` but accepts both non-numeric and numeric keys. /// Prefer to use `.put` if the key is guaranteed to be non-numeric (e.g. known at comptime) pub inline fn putMayBeIndex(this: JSValue, globalObject: *JSGlobalObject, key: *const String, value: JSValue) void { JSC__JSValue__putMayBeIndex(this, globalObject, key, value); } + extern fn JSC__JSValue__putIndex(value: JSValue, globalObject: *JSGlobalObject, i: u32, out: JSValue) void; pub fn putIndex(value: JSValue, globalObject: *JSGlobalObject, i: u32, out: JSValue) void { - cppFn("putIndex", .{ value, globalObject, i, out }); + JSC__JSValue__putIndex(value, globalObject, i, out); } + extern fn JSC__JSValue__push(value: JSValue, globalObject: *JSGlobalObject, out: JSValue) void; pub fn push(value: JSValue, globalObject: *JSGlobalObject, out: JSValue) void { - cppFn("push", .{ value, globalObject, out }); + JSC__JSValue__push(value, globalObject, out); } extern fn JSC__JSValue__toISOString(*JSC.JSGlobalObject, JSC.JSValue, *[28]u8) c_int; @@ -851,30 +850,38 @@ pub const JSValue = enum(i64) { JSC.C.JSValueUnprotect(JSC.VirtualMachine.get().global, this.asObjectRef()); } + extern fn JSC__JSValue__JSONValueFromString( + global: *JSGlobalObject, + str: [*]const u8, + len: usize, + ascii: bool, + ) JSValue; pub fn JSONValueFromString( global: *JSGlobalObject, str: [*]const u8, len: usize, ascii: bool, ) JSValue { - return cppFn("JSONValueFromString", .{ global, str, len, ascii }); + return JSC__JSValue__JSONValueFromString(global, str, len, ascii); } - + extern fn JSC__JSValue__createObject2(global: *JSGlobalObject, key1: *const ZigString, key2: *const ZigString, value1: JSValue, value2: JSValue) JSValue; /// Create an object with exactly two properties pub fn createObject2(global: *JSGlobalObject, key1: *const ZigString, key2: *const ZigString, value1: JSValue, value2: JSValue) JSValue { - return cppFn("createObject2", .{ global, key1, key2, value1, value2 }); + return JSC__JSValue__createObject2(global, key1, key2, value1, value2); } pub fn asPromisePtr(this: JSValue, comptime T: type) *T { return asPtr(this, T); } + extern fn JSC__JSValue__createRopeString(this: JSValue, rhs: JSValue, globalThis: *JSC.JSGlobalObject) JSValue; pub fn createRopeString(this: JSValue, rhs: JSValue, globalThis: *JSC.JSGlobalObject) JSValue { - return cppFn("createRopeString", .{ this, rhs, globalThis }); + return JSC__JSValue__createRopeString(this, rhs, globalThis); } + extern fn JSC__JSValue__getErrorsProperty(this: JSValue, globalObject: *JSGlobalObject) JSValue; pub fn getErrorsProperty(this: JSValue, globalObject: *JSGlobalObject) JSValue { - return cppFn("getErrorsProperty", .{ this, globalObject }); + return JSC__JSValue__getErrorsProperty(this, globalObject); } pub fn createBufferFromLength(globalObject: *JSGlobalObject, len: usize) JSValue { @@ -921,9 +928,10 @@ pub const JSValue = enum(i64) { } } + extern fn JSC__JSValue__createUninitializedUint8Array(globalObject: *JSGlobalObject, len: usize) JSValue; pub fn createUninitializedUint8Array(globalObject: *JSGlobalObject, len: usize) JSValue { JSC.markBinding(@src()); - return shim.cppFn("createUninitializedUint8Array", .{ globalObject, len }); + return JSC__JSValue__createUninitializedUint8Array(globalObject, len); } pub fn createBufferWithCtx(globalObject: *JSGlobalObject, slice: []u8, ptr: ?*anyopaque, func: JSC.C.JSTypedArrayBytesDeallocator) JSValue { @@ -955,8 +963,9 @@ pub const JSValue = enum(i64) { }; } + extern fn JSC__JSValue__createInternalPromise(globalObject: *JSGlobalObject) JSValue; pub fn createInternalPromise(globalObject: *JSGlobalObject) JSValue { - return cppFn("createInternalPromise", .{globalObject}); + return JSC__JSValue__createInternalPromise(globalObject); } extern fn JSC__JSValue__asInternalPromise(JSValue0: JSValue) ?*JSInternalPromise; @@ -990,16 +999,19 @@ pub const JSValue = enum(i64) { return null; } + extern fn JSC__JSValue__jsBoolean(i: bool) JSValue; pub inline fn jsBoolean(i: bool) JSValue { - return cppFn("jsBoolean", .{i}); + return JSC__JSValue__jsBoolean(i); } + extern fn JSC__JSValue__jsDoubleNumber(i: f64) JSValue; pub fn jsDoubleNumber(i: f64) JSValue { - return cppFn("jsDoubleNumber", .{i}); + return JSC__JSValue__jsDoubleNumber(i); } + extern fn JSC__JSValue__jsEmptyString(globalThis: *JSGlobalObject) JSValue; pub inline fn jsEmptyString(globalThis: *JSGlobalObject) JSValue { - return cppFn("jsEmptyString", .{globalThis}); + return JSC__JSValue__jsEmptyString(globalThis); } pub inline fn jsNull() JSValue { @@ -1010,8 +1022,9 @@ pub const JSValue = enum(i64) { return jsNumberWithType(@TypeOf(number), number); } + extern fn JSC__JSValue__jsTDZValue() JSValue; pub inline fn jsTDZValue() JSValue { - return cppFn("jsTDZValue", .{}); + return JSC__JSValue__jsTDZValue(); } pub inline fn jsUndefined() JSValue { @@ -1066,33 +1079,36 @@ pub const JSValue = enum(i64) { return String.init(buf.slice()).toJS(globalThis); } + extern fn JSC__JSValue__fromEntries(globalThis: *JSGlobalObject, keys_array: [*c]ZigString, values_array: [*c]ZigString, strings_count: usize, clone: bool) JSValue; pub fn fromEntries(globalThis: *JSGlobalObject, keys_array: [*c]ZigString, values_array: [*c]ZigString, strings_count: usize, clone: bool) JSValue { - return cppFn("fromEntries", .{ + return JSC__JSValue__fromEntries( globalThis, keys_array, values_array, strings_count, clone, - }); + ); } + extern fn JSC__JSValue__keys(globalThis: *JSGlobalObject, value: JSValue) JSValue; pub fn keys(value: JSValue, globalThis: *JSGlobalObject) JSValue { - return cppFn("keys", .{ + return JSC__JSValue__keys( globalThis, value, - }); + ); } + extern fn JSC__JSValue__values(globalThis: *JSGlobalObject, value: JSValue) JSValue; /// This is `Object.values`. /// `value` is assumed to be not empty, undefined, or null. pub fn values(value: JSValue, globalThis: *JSGlobalObject) JSValue { if (comptime bun.Environment.allow_assert) { bun.assert(!value.isEmptyOrUndefinedOrNull()); } - return cppFn("values", .{ + return JSC__JSValue__values( globalThis, value, - }); + ); } extern "c" fn JSC__JSValue__hasOwnPropertyValue(JSValue, *JSGlobalObject, JSValue) bool; @@ -1109,11 +1125,13 @@ pub const JSValue = enum(i64) { pub fn jsNumberFromDouble(i: f64) JSValue { return FFI.DOUBLE_TO_JSVALUE(i).asJSValue; } + extern fn JSC__JSValue__jsNumberFromChar(i: u8) JSValue; pub fn jsNumberFromChar(i: u8) JSValue { - return cppFn("jsNumberFromChar", .{i}); + return JSC__JSValue__jsNumberFromChar(i); } + extern fn JSC__JSValue__jsNumberFromU16(i: u16) JSValue; pub fn jsNumberFromU16(i: u16) JSValue { - return cppFn("jsNumberFromU16", .{i}); + return JSC__JSValue__jsNumberFromU16(i); } pub fn jsNumberFromInt32(i: i32) JSValue { return FFI.INT32_TO_JSVALUE(i).asJSValue; @@ -1167,6 +1185,8 @@ pub const JSValue = enum(i64) { return coerceJSValueDoubleTruncatingT(i64, this.asNumber()); } + extern fn JSC__JSValue__toInt64(this: JSValue) i64; + /// Decimal values are truncated without rounding. /// `-Infinity` and `NaN` coerce to -minInt(64) /// `Infinity` coerces to maxInt(64) @@ -1179,7 +1199,7 @@ pub const JSValue = enum(i64) { return this.coerceDoubleTruncatingIntoInt64(); } - return cppFn("toInt64", .{this}); + return JSC__JSValue__toInt64(this); } pub const ComparisonResult = enum(u8) { @@ -1190,11 +1210,12 @@ pub const JSValue = enum(i64) { invalid_comparison, }; + extern fn JSC__JSValue__asBigIntCompare(this: JSValue, global: *JSGlobalObject, other: JSValue) ComparisonResult; pub fn asBigIntCompare(this: JSValue, global: *JSGlobalObject, other: JSValue) ComparisonResult { if (!this.isBigInt() or (!other.isBigInt() and !other.isNumber())) { return .invalid_comparison; } - return cppFn("asBigIntCompare", .{ this, global, other }); + return JSC__JSValue__asBigIntCompare(this, global, other); } pub inline fn isUndefined(this: JSValue) bool { @@ -1218,11 +1239,13 @@ pub const JSValue = enum(i64) { pub fn isBoolean(this: JSValue) bool { return this == .true or this == .false; } + extern fn JSC__JSValue__isAnyInt(this: JSValue) bool; pub fn isAnyInt(this: JSValue) bool { - return cppFn("isAnyInt", .{this}); + return JSC__JSValue__isAnyInt(this); } + extern fn JSC__JSValue__isUInt32AsAnyInt(this: JSValue) bool; pub fn isUInt32AsAnyInt(this: JSValue) bool { - return cppFn("isUInt32AsAnyInt", .{this}); + return JSC__JSValue__isUInt32AsAnyInt(this); } pub fn asEncoded(this: JSValue) FFI.EncodedJSValue { @@ -1237,8 +1260,9 @@ pub const JSValue = enum(i64) { return FFI.JSVALUE_IS_INT32(.{ .asJSValue = this }); } + extern fn JSC__JSValue__isInt32AsAnyInt(this: JSValue) bool; pub fn isInt32AsAnyInt(this: JSValue) bool { - return cppFn("isInt32AsAnyInt", .{this}); + return JSC__JSValue__isInt32AsAnyInt(this); } pub fn isNumber(this: JSValue) bool { @@ -1264,15 +1288,17 @@ pub const JSValue = enum(i64) { return this.jsType() == JSType.ErrorInstance; } + extern fn JSC__JSValue__isAnyError(this: JSValue) bool; pub fn isAnyError(this: JSValue) bool { if (!this.isCell()) return false; - return cppFn("isAnyError", .{this}); + return JSC__JSValue__isAnyError(this); } + extern fn JSC__JSValue__toError_(this: JSValue) JSValue; pub fn toError_(this: JSValue) JSValue { - return cppFn("toError_", .{this}); + return JSC__JSValue__toError_(this); } pub fn toError(this: JSValue) ?JSValue { @@ -1314,26 +1340,33 @@ pub const JSValue = enum(i64) { return jsType(this).isStringObjectLike(); } + extern fn JSC__JSValue__isBigInt(this: JSValue) bool; pub fn isBigInt(this: JSValue) bool { - return cppFn("isBigInt", .{this}); + return JSC__JSValue__isBigInt(this); } + extern fn JSC__JSValue__isHeapBigInt(this: JSValue) bool; pub fn isHeapBigInt(this: JSValue) bool { - return cppFn("isHeapBigInt", .{this}); + return JSC__JSValue__isHeapBigInt(this); } + extern fn JSC__JSValue__isBigInt32(this: JSValue) bool; pub fn isBigInt32(this: JSValue) bool { - return cppFn("isBigInt32", .{this}); + return JSC__JSValue__isBigInt32(this); } + extern fn JSC__JSValue__isSymbol(this: JSValue) bool; pub fn isSymbol(this: JSValue) bool { - return cppFn("isSymbol", .{this}); + return JSC__JSValue__isSymbol(this); } + extern fn JSC__JSValue__isPrimitive(this: JSValue) bool; pub fn isPrimitive(this: JSValue) bool { - return cppFn("isPrimitive", .{this}); + return JSC__JSValue__isPrimitive(this); } + extern fn JSC__JSValue__isGetterSetter(this: JSValue) bool; pub fn isGetterSetter(this: JSValue) bool { - return cppFn("isGetterSetter", .{this}); + return JSC__JSValue__isGetterSetter(this); } + extern fn JSC__JSValue__isCustomGetterSetter(this: JSValue) bool; pub fn isCustomGetterSetter(this: JSValue) bool { - return cppFn("isCustomGetterSetter", .{this}); + return JSC__JSValue__isCustomGetterSetter(this); } pub inline fn isObject(this: JSValue) bool { return this.isCell() and this.jsType().isObject(); @@ -1355,21 +1388,24 @@ pub const JSValue = enum(i64) { return this.jsType().isObject() and keys(this, globalObject).getLength(globalObject) == 0; } + extern fn JSC__JSValue__isClass(this: JSValue, global: *JSGlobalObject) bool; pub fn isClass(this: JSValue, global: *JSGlobalObject) bool { - return cppFn("isClass", .{ this, global }); + return JSC__JSValue__isClass(this, global); } + extern fn JSC__JSValue__isConstructor(this: JSValue) bool; pub fn isConstructor(this: JSValue) bool { if (!this.isCell()) return false; - return cppFn("isConstructor", .{this}); + return JSC__JSValue__isConstructor(this); } + extern fn JSC__JSValue__getNameProperty(this: JSValue, global: *JSGlobalObject, ret: *ZigString) void; pub fn getNameProperty(this: JSValue, global: *JSGlobalObject, ret: *ZigString) void { if (this.isEmptyOrUndefinedOrNull()) { return; } - cppFn("getNameProperty", .{ this, global, ret }); + JSC__JSValue__getNameProperty(this, global, ret); } extern fn JSC__JSValue__getName(JSC.JSValue, *JSC.JSGlobalObject, *bun.String) void; @@ -1379,8 +1415,9 @@ pub const JSValue = enum(i64) { return ret; } + extern fn JSC__JSValue__getClassName(this: JSValue, global: *JSGlobalObject, ret: *ZigString) void; pub fn getClassName(this: JSValue, global: *JSGlobalObject, ret: *ZigString) void { - cppFn("getClassName", .{ this, global, ret }); + JSC__JSValue__getClassName(this, global, ret); } pub inline fn isCell(this: JSValue) bool { @@ -1394,13 +1431,18 @@ pub const JSValue = enum(i64) { return JSC.ZigString.init(slice_).withEncoding().toJS(globalObject); } - /// Calling this on a non-cell is safety-checked undefined behavior. + extern fn JSC__JSValue__asCell(this: JSValue) *JSCell; pub fn asCell(this: JSValue) *JSCell { // NOTE: asCell already asserts this, but since we're crossing an FFI // boundary, that assertion is opaque to the Zig compiler. By asserting // it twice we let Zig possibly optimize out other checks. bun.unsafeAssert(this.isCell()); - return cppFn("asCell", .{this}); + return JSC__JSValue__asCell(this); + } + + extern fn JSC__JSValue__isCallable(this: JSValue) bool; + pub fn isCallable(this: JSValue) bool { + return JSC__JSValue__isCallable(this); } /// Statically cast a value to a cell. Returns `null` for non-cells. @@ -1408,26 +1450,25 @@ pub const JSValue = enum(i64) { return if (this.isCell()) this.asCell() else null; } - pub fn isCallable(this: JSValue) bool { - return cppFn("isCallable", .{this}); - } - + extern fn JSC__JSValue__isException(this: JSValue, vm: *VM) bool; pub fn isException(this: JSValue, vm: *VM) bool { - return cppFn("isException", .{ this, vm }); + return JSC__JSValue__isException(this, vm); } + extern fn JSC__JSValue__isTerminationException(this: JSValue, vm: *VM) bool; pub fn isTerminationException(this: JSValue, vm: *VM) bool { - return cppFn("isTerminationException", .{ this, vm }); + return JSC__JSValue__isTerminationException(this, vm); } + extern fn JSC__JSValue__toZigException(this: JSValue, global: *JSGlobalObject, exception: *ZigException) void; pub fn toZigException(this: JSValue, global: *JSGlobalObject, exception: *ZigException) void { - return cppFn("toZigException", .{ this, global, exception }); + return JSC__JSValue__toZigException(this, global, exception); } + extern fn JSC__JSValue__toZigString(this: JSValue, out: *ZigString, global: *JSGlobalObject) void; pub fn toZigString(this: JSValue, out: *ZigString, global: *JSGlobalObject) error{JSError}!void { - const str = cppFn("toZigString", .{ this, out, global }); + JSC__JSValue__toZigString(this, out, global); if (global.hasException()) return error.JSError; - return str; } /// Increments the reference count, you must call `.deref()` or it will leak memory. @@ -1435,14 +1476,17 @@ pub const JSValue = enum(i64) { return bun.String.fromJS2(this, globalObject); } + extern fn JSC__JSValue__toMatch(this: JSValue, global: *JSGlobalObject, other: JSValue) bool; + /// this: RegExp value /// other: string value pub fn toMatch(this: JSValue, global: *JSGlobalObject, other: JSValue) bool { - return cppFn("toMatch", .{ this, global, other }); + return JSC__JSValue__toMatch(this, global, other); } + extern fn JSC__JSValue__asArrayBuffer_(this: JSValue, global: *JSGlobalObject, out: *ArrayBuffer) bool; pub fn asArrayBuffer_(this: JSValue, global: *JSGlobalObject, out: *ArrayBuffer) bool { - return cppFn("asArrayBuffer_", .{ this, global, out }); + return JSC__JSValue__asArrayBuffer_(this, global, out); } pub fn asArrayBuffer(this: JSValue, global: *JSGlobalObject) ?ArrayBuffer { @@ -1461,30 +1505,30 @@ pub const JSValue = enum(i64) { return null; } - + extern fn JSC__JSValue__fromInt64NoTruncate(globalObject: *JSGlobalObject, i: i64) JSValue; /// This always returns a JS BigInt pub fn fromInt64NoTruncate(globalObject: *JSGlobalObject, i: i64) JSValue { - return cppFn("fromInt64NoTruncate", .{ globalObject, i }); + return JSC__JSValue__fromInt64NoTruncate(globalObject, i); } + extern fn JSC__JSValue__fromUInt64NoTruncate(globalObject: *JSGlobalObject, i: u64) JSValue; /// This always returns a JS BigInt pub fn fromUInt64NoTruncate(globalObject: *JSGlobalObject, i: u64) JSValue { - return cppFn("fromUInt64NoTruncate", .{ globalObject, i }); + return JSC__JSValue__fromUInt64NoTruncate(globalObject, i); } - + extern fn JSC__JSValue__fromTimevalNoTruncate(globalObject: *JSGlobalObject, nsec: i64, sec: i64) JSValue; /// This always returns a JS BigInt using std.posix.timeval from std.posix.rusage pub fn fromTimevalNoTruncate(globalObject: *JSGlobalObject, nsec: i64, sec: i64) JSValue { - return cppFn("fromTimevalNoTruncate", .{ globalObject, nsec, sec }); + return JSC__JSValue__fromTimevalNoTruncate(globalObject, nsec, sec); } - + extern fn JSC__JSValue__bigIntSum(globalObject: *JSGlobalObject, a: JSValue, b: JSValue) JSValue; /// Sums two JS BigInts pub fn bigIntSum(globalObject: *JSGlobalObject, a: JSValue, b: JSValue) JSValue { - return cppFn("bigIntSum", .{ globalObject, a, b }); + return JSC__JSValue__bigIntSum(globalObject, a, b); } + extern fn JSC__JSValue__toUInt64NoTruncate(this: JSValue) u64; pub fn toUInt64NoTruncate(this: JSValue) u64 { - return cppFn("toUInt64NoTruncate", .{ - this, - }); + return JSC__JSValue__toUInt64NoTruncate(this); } /// Deprecated: replace with 'toBunString' @@ -1512,17 +1556,19 @@ pub const JSValue = enum(i64) { } // On exception, this returns the empty string. + extern fn JSC__JSValue__toString(this: JSValue, globalThis: *JSGlobalObject) *JSString; pub fn toString(this: JSValue, globalThis: *JSGlobalObject) *JSString { - return cppFn("toString", .{ this, globalThis }); + return JSC__JSValue__toString(this, globalThis); } + extern fn JSC__JSValue__jsonStringify(this: JSValue, globalThis: *JSGlobalObject, indent: u32, out: *bun.String) void; pub fn jsonStringify(this: JSValue, globalThis: *JSGlobalObject, indent: u32, out: *bun.String) void { - return cppFn("jsonStringify", .{ this, globalThis, indent, out }); + return JSC__JSValue__jsonStringify(this, globalThis, indent, out); } - + extern fn JSC__JSValue__toStringOrNull(this: JSValue, globalThis: *JSGlobalObject) ?*JSString; /// On exception, this returns null, to make exception checks clearer. pub fn toStringOrNull(this: JSValue, globalThis: *JSGlobalObject) ?*JSString { - return cppFn("toStringOrNull", .{ this, globalThis }); + return JSC__JSValue__toStringOrNull(this, globalThis); } /// Call `toString()` on the JSValue and clone the result. @@ -1573,8 +1619,9 @@ pub const JSValue = enum(i64) { /// /// For values that are already objects, this is effectively a reinterpret /// cast. + extern fn JSC__JSValue__toObject(this: JSValue, globalThis: *JSGlobalObject) *JSObject; pub fn toObject(this: JSValue, globalThis: *JSGlobalObject) *JSObject { - return cppFn("toObject", .{ this, globalThis }); + return JSC__JSValue__toObject(this, globalThis); } /// Statically cast a value to a JSObject. @@ -1584,16 +1631,19 @@ pub const JSValue = enum(i64) { return if (this.isObject()) this.uncheckedPtrCast(JSObject) else null; } + extern fn JSC__JSValue__getPrototype(this: JSValue, globalObject: *JSGlobalObject) JSValue; pub fn getPrototype(this: JSValue, globalObject: *JSGlobalObject) JSValue { - return cppFn("getPrototype", .{ this, globalObject }); + return JSC__JSValue__getPrototype(this, globalObject); } + extern fn JSC__JSValue__eqlValue(this: JSValue, other: JSValue) bool; pub fn eqlValue(this: JSValue, other: JSValue) bool { - return cppFn("eqlValue", .{ this, other }); + return JSC__JSValue__eqlValue(this, other); } + extern fn JSC__JSValue__eqlCell(this: JSValue, other: *JSCell) bool; pub fn eqlCell(this: JSValue, other: *JSCell) bool { - return cppFn("eqlCell", .{ this, other }); + return JSC__JSValue__eqlCell(this, other); } pub const BuiltinName = enum(u8) { @@ -1682,34 +1732,40 @@ pub const JSValue = enum(i64) { return result; } + extern fn JSC__JSValue__fastGetDirect_(this: JSValue, global: *JSGlobalObject, builtin_name: u8) JSValue; pub fn fastGetDirect_(this: JSValue, global: *JSGlobalObject, builtin_name: u8) JSValue { - return cppFn("fastGetDirect_", .{ this, global, builtin_name }); + return JSC__JSValue__fastGetDirect_(this, global, builtin_name); } extern fn JSC__JSValue__getIfPropertyExistsImpl(target: JSValue, global: *JSGlobalObject, ptr: [*]const u8, len: u32) JSValue; + extern fn JSC__JSValue__getIfPropertyExistsFromPath(this: JSValue, global: *JSGlobalObject, path: JSValue) JSValue; pub fn getIfPropertyExistsFromPath(this: JSValue, global: *JSGlobalObject, path: JSValue) JSValue { - return cppFn("getIfPropertyExistsFromPath", .{ this, global, path }); + return JSC__JSValue__getIfPropertyExistsFromPath(this, global, path); } + extern fn JSC__JSValue__getSymbolDescription(this: JSValue, global: *JSGlobalObject, str: *ZigString) void; pub fn getSymbolDescription(this: JSValue, global: *JSGlobalObject, str: *ZigString) void { - cppFn("getSymbolDescription", .{ this, global, str }); + JSC__JSValue__getSymbolDescription(this, global, str); } + extern fn JSC__JSValue__symbolFor(global: *JSGlobalObject, str: *ZigString) JSValue; pub fn symbolFor(global: *JSGlobalObject, str: *ZigString) JSValue { - return cppFn("symbolFor", .{ global, str }); + return JSC__JSValue__symbolFor(global, str); } + extern fn JSC__JSValue__symbolKeyFor(this: JSValue, global: *JSGlobalObject, str: *ZigString) bool; pub fn symbolKeyFor(this: JSValue, global: *JSGlobalObject, str: *ZigString) bool { - return cppFn("symbolKeyFor", .{ this, global, str }); + return JSC__JSValue__symbolKeyFor(this, global, str); } + extern fn JSC__JSValue___then(this: JSValue, global: *JSGlobalObject, ctx: JSValue, resolve: JSC.JSHostFunctionPtr, reject: JSC.JSHostFunctionPtr) void; pub fn _then(this: JSValue, global: *JSGlobalObject, ctx: JSValue, resolve: JSNativeFn, reject: JSNativeFn) void { - return cppFn("_then", .{ this, global, ctx, toJSHostFunction(resolve), toJSHostFunction(reject) }); + return JSC__JSValue___then(this, global, ctx, toJSHostFunction(resolve), toJSHostFunction(reject)); } - pub fn _then2(this: JSValue, global: *JSGlobalObject, ctx: JSValue, resolve: JSHostFunctionType, reject: JSHostFunctionType) void { - return cppFn("_then", .{ this, global, ctx, resolve, reject }); + pub fn _then2(this: JSValue, global: *JSGlobalObject, ctx: JSValue, resolve: JSC.JSHostFunctionPtr, reject: JSC.JSHostFunctionPtr) void { + return JSC__JSValue___then(this, global, ctx, resolve, reject); } pub fn then(this: JSValue, global: *JSGlobalObject, ctx: ?*anyopaque, resolve: JSNativeFn, reject: JSNativeFn) void { @@ -2095,61 +2151,62 @@ pub const JSValue = enum(i64) { /// Alias for getIfPropertyExists pub const getIfPropertyExists = get; + extern fn JSC__JSValue__createTypeError(message: *const ZigString, code: *const ZigString, global: *JSGlobalObject) JSValue; pub fn createTypeError(message: *const ZigString, code: *const ZigString, global: *JSGlobalObject) JSValue { - return cppFn("createTypeError", .{ message, code, global }); + return JSC__JSValue__createTypeError(message, code, global); } + extern fn JSC__JSValue__createRangeError(message: *const ZigString, code: *const ZigString, global: *JSGlobalObject) JSValue; pub fn createRangeError(message: *const ZigString, code: *const ZigString, global: *JSGlobalObject) JSValue { - return cppFn("createRangeError", .{ message, code, global }); + return JSC__JSValue__createRangeError(message, code, global); } + extern fn JSC__JSValue__isSameValue(this: JSValue, other: JSValue, global: *JSGlobalObject) bool; + /// Object.is() /// /// This algorithm differs from the IsStrictlyEqual Algorithm by treating all NaN values as equivalent and by differentiating +0𝔽 from -0𝔽. /// https://tc39.es/ecma262/#sec-samevalue pub fn isSameValue(this: JSValue, other: JSValue, global: *JSGlobalObject) bool { - return @intFromEnum(this) == @intFromEnum(other) or cppFn("isSameValue", .{ this, other, global }); + return @intFromEnum(this) == @intFromEnum(other) or JSC__JSValue__isSameValue(this, other, global); } + extern fn JSC__JSValue__deepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) bool; pub fn deepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) JSError!bool { - // JSC__JSValue__deepEquals - const result = cppFn("deepEquals", .{ this, other, global }); + const result = JSC__JSValue__deepEquals(this, other, global); if (global.hasException()) return error.JSError; return result; } - + extern fn JSC__JSValue__jestDeepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) bool; /// same as `JSValue.deepEquals`, but with jest asymmetric matchers enabled pub fn jestDeepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) JSError!bool { - const result = cppFn("jestDeepEquals", .{ this, other, global }); + const result = JSC__JSValue__jestDeepEquals(this, other, global); if (global.hasException()) return error.JSError; return result; } + extern fn JSC__JSValue__strictDeepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) bool; pub fn strictDeepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) JSError!bool { - // JSC__JSValue__strictDeepEquals - const result = cppFn("strictDeepEquals", .{ this, other, global }); + const result = JSC__JSValue__strictDeepEquals(this, other, global); if (global.hasException()) return error.JSError; return result; } - + extern fn JSC__JSValue__jestStrictDeepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) bool; /// same as `JSValue.strictDeepEquals`, but with jest asymmetric matchers enabled pub fn jestStrictDeepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) JSError!bool { - // JSC__JSValue__jestStrictDeepEquals - const result = cppFn("jestStrictDeepEquals", .{ this, other, global }); + const result = JSC__JSValue__jestStrictDeepEquals(this, other, global); if (global.hasException()) return error.JSError; return result; } - + extern fn JSC__JSValue__deepMatch(this: JSValue, subset: JSValue, global: *JSGlobalObject, replace_props_with_asymmetric_matchers: bool) bool; /// NOTE: can throw. Check for exceptions. pub fn deepMatch(this: JSValue, subset: JSValue, global: *JSGlobalObject, replace_props_with_asymmetric_matchers: bool) bool { - // JSC__JSValue__deepMatch - return cppFn("deepMatch", .{ this, subset, global, replace_props_with_asymmetric_matchers }); + return JSC__JSValue__deepMatch(this, subset, global, replace_props_with_asymmetric_matchers); } - + extern fn JSC__JSValue__jestDeepMatch(this: JSValue, subset: JSValue, global: *JSGlobalObject, replace_props_with_asymmetric_matchers: bool) bool; /// same as `JSValue.deepMatch`, but with jest asymmetric matchers enabled pub fn jestDeepMatch(this: JSValue, subset: JSValue, global: *JSGlobalObject, replace_props_with_asymmetric_matchers: bool) bool { - // JSC__JSValue__jestDeepMatch - return cppFn("jestDeepMatch", .{ this, subset, global, replace_props_with_asymmetric_matchers }); + return JSC__JSValue__jestDeepMatch(this, subset, global, replace_props_with_asymmetric_matchers); } pub const DiffMethod = enum(u8) { @@ -2175,17 +2232,16 @@ pub const JSValue = enum(i64) { /// - Does not increment ref count /// - Make sure `this` stays on the stack. If you're method chaining, you may need to call `this.ensureStillAlive()`. pub fn asString(this: JSValue) *JSString { - return cppFn("asString", .{ - this, - }); + return JSC__JSValue__asString(this); } + extern fn JSC__JSValue__asString(this: JSValue) *JSString; + + extern fn JSC__JSValue__getUnixTimestamp(this: JSValue) f64; /// Get the internal number of the `JSC::DateInstance` object /// Returns NaN if the value is not a `JSC::DateInstance` (`Date` in JS) pub fn getUnixTimestamp(this: JSValue) f64 { - return cppFn("getUnixTimestamp", .{ - this, - }); + return JSC__JSValue__getUnixTimestamp(this); } extern fn JSC__JSValue__getUTCTimestamp(globalObject: *JSC.JSGlobalObject, this: JSValue) f64; @@ -2245,6 +2301,7 @@ pub const JSValue = enum(i64) { return null; } + extern fn JSC__JSValue__asNumber(this: JSValue) f64; pub fn asNumber(this: JSValue) f64 { if (this.isInt32()) { return @as(f64, @floatFromInt(this.asInt32())); @@ -2261,9 +2318,7 @@ pub const JSValue = enum(i64) { return if (asBoolean(this)) 1.0 else 0.0; } - return cppFn("asNumber", .{ - this, - }); + return JSC__JSValue__asNumber(this); } pub fn asDouble(this: JSValue) f64 { @@ -2286,10 +2341,10 @@ pub const JSValue = enum(i64) { pub fn fromPtr(addr: anytype) JSValue { return fromPtrAddress(@intFromPtr(addr)); } - + extern fn JSC__JSValue__toBoolean(this: JSValue) bool; /// Equivalent to the `!!` operator pub fn toBoolean(this: JSValue) bool { - return this != .zero and cppFn("toBoolean", .{this}); + return this != .zero and JSC__JSValue__toBoolean(this); } pub fn asBoolean(this: JSValue) bool { @@ -2308,6 +2363,7 @@ pub const JSValue = enum(i64) { return coerceJSValueDoubleTruncatingTT(i52, i64, this.asNumber()); } + extern fn JSC__JSValue__toInt32(this: JSValue) i32; pub fn toInt32(this: JSValue) i32 { if (this.isInt32()) { return asInt32(this); @@ -2323,9 +2379,7 @@ pub const JSValue = enum(i64) { } // TODO: this shouldn't be reachable. - return cppFn("toInt32", .{ - this, - }); + return JSC__JSValue__toInt32(this); } pub fn asInt32(this: JSValue) i32 { @@ -2392,27 +2446,27 @@ pub const JSValue = enum(i64) { return @as(u64, @intFromFloat(@max(@min(len, std.math.maxInt(i52)), 0))); } + extern fn JSC__JSValue__getLengthIfPropertyExistsInternal(this: JSValue, globalThis: *JSGlobalObject) f64; /// Do not use this directly! /// /// If the property does not exist, this function will return max(f64) instead of 0. pub fn getLengthIfPropertyExistsInternal(this: JSValue, globalThis: *JSGlobalObject) f64 { - return cppFn("getLengthIfPropertyExistsInternal", .{ - this, - globalThis, - }); + return JSC__JSValue__getLengthIfPropertyExistsInternal(this, globalThis); } + extern fn JSC__JSValue__isAggregateError(this: JSValue, globalObject: *JSGlobalObject) bool; pub fn isAggregateError(this: JSValue, globalObject: *JSGlobalObject) bool { - return cppFn("isAggregateError", .{ this, globalObject }); + return JSC__JSValue__isAggregateError(this, globalObject); } + extern fn JSC__JSValue__forEach(this: JSValue, globalObject: *JSGlobalObject, ctx: ?*anyopaque, callback: *const fn (vm: *VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void) void; pub fn forEach( this: JSValue, globalObject: *JSGlobalObject, ctx: ?*anyopaque, callback: *const fn (vm: *VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void, ) void { - return cppFn("forEach", .{ this, globalObject, ctx, callback }); + return JSC__JSValue__forEach(this, globalObject, ctx, callback); } /// Same as `forEach` but accepts a typed context struct without need for @ptrCasts @@ -2423,18 +2477,17 @@ pub const JSValue = enum(i64) { callback: *const fn (vm: *VM, globalObject: *JSGlobalObject, ctx: @TypeOf(ctx), nextValue: JSValue) callconv(.C) void, ) void { const func = @as(*const fn (vm: *VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void, @ptrCast(callback)); - return cppFn("forEach", .{ this, globalObject, ctx, func }); + return JSC__JSValue__forEach(this, globalObject, ctx, func); } + extern fn JSC__JSValue__isIterable(this: JSValue, globalObject: *JSGlobalObject) bool; pub fn isIterable(this: JSValue, globalObject: *JSGlobalObject) bool { - return cppFn("isIterable", .{ - this, - globalObject, - }); + return JSC__JSValue__isIterable(this, globalObject); } + extern fn JSC__JSValue__stringIncludes(this: JSValue, globalObject: *JSGlobalObject, other: JSValue) bool; pub fn stringIncludes(this: JSValue, globalObject: *JSGlobalObject, other: JSValue) bool { - return cppFn("stringIncludes", .{ this, globalObject, other }); + return JSC__JSValue__stringIncludes(this, globalObject, other); } // TODO: remove this (no replacement) @@ -2481,122 +2534,6 @@ pub const JSValue = enum(i64) { return @alignCast(@ptrCast(value.asEncoded().asPtr)); } - pub const Extern = [_][]const u8{ - "_then", - "asArrayBuffer_", - "asBigIntCompare", - "asCell", - "asInternalPromise", - "asNumber", - "asPromise", - "asString", - "coerceToDouble", - "coerceToInt32", - "coerceToInt64", - "createEmptyArray", - "createEmptyObject", - "createInternalPromise", - "createObject2", - "createRangeError", - "createRopeString", - "createStringArray", - "createTypeError", - "createUninitializedUint8Array", - "deepEquals", - "eqlCell", - "eqlValue", - "fastGetDirect_", - "fastGet_", - "forEach", - "forEachProperty", - "forEachPropertyOrdered", - "fromEntries", - "fromInt64NoTruncate", - "fromUInt64NoTruncate", - "getClassName", - "getDirect", - "getErrorsProperty", - "getIfExists", - "getIfPropertyExistsFromPath", - "getIfPropertyExistsImpl", - "getLengthIfPropertyExistsInternal", - "getNameProperty", - "getPropertyByPropertyName", - "getPropertyNames", - "getPrototype", - "getStaticProperty", - "getSymbolDescription", - "getUnixTimestamp", - "hasProperty", - "hasOwnProperty", - "isAggregateError", - "isAnyError", - "isAnyInt", - "isBigInt", - "isBigInt32", - "isBoolean", - "isCallable", - "isClass", - "isCustomGetterSetter", - "isError", - "isException", - "isGetterSetter", - "isHeapBigInt", - "isInt32", - "isInt32AsAnyInt", - "isIterable", - "isNumber", - "isObject", - "isPrimitive", - "isSameValue", - "isSymbol", - "isTerminationException", - "isUInt32AsAnyInt", - "jsBoolean", - "jsDoubleNumber", - "jsNull", - "jsNumberFromChar", - "jsNumberFromDouble", - "jsNumberFromInt64", - "jsNumberFromU16", - "jsTDZValue", - "jsType", - "jsUndefined", - "jsonStringify", - "keys", - "values", - "kind_", - "parseJSON", - "put", - "putDirect", - "putIndex", - "push", - "putRecord", - "strictDeepEquals", - "symbolFor", - "symbolKeyFor", - "toBoolean", - "toError_", - "toInt32", - "toInt64", - "toObject", - "toPropertyKeyValue", - "toString", - "toStringOrNull", - "toUInt64NoTruncate", - "toWTFString", - "toZigException", - "toZigString", - "toMatch", - "isConstructor", - "isInstanceOf", - "stringIncludes", - "deepMatch", - "jestDeepEquals", - "jestStrictDeepEquals", - "jestDeepMatch", - }; - /// For any callback JSValue created in JS that you will not call *immediately*, you must wrap it /// in an AsyncContextFrame with this function. This allows AsyncLocalStorage to work by /// snapshotting it's state and restoring it when called. @@ -2670,6 +2607,13 @@ pub const JSValue = enum(i64) { if (!JSC__JSValue__getClassInfoName(this, &out.ptr, &out.len)) return null; return out; } + + pub const exposed_to_ffi = struct { + pub const JSVALUE_TO_INT64 = JSValue.JSC__JSValue__toInt64; + pub const JSVALUE_TO_UINT64 = JSValue.JSC__JSValue__toUInt64NoTruncate; + pub const INT64_TO_JSVALUE = JSValue.JSC__JSValue__fromInt64NoTruncate; + pub const UINT64_TO_JSVALUE = JSValue.JSC__JSValue__fromUInt64NoTruncate; + }; }; pub const JSValueReprInt = JSC.JSValueReprInt; @@ -2702,7 +2646,6 @@ const JSCell = JSC.JSCell; const Exports = @import("./exports.zig"); const JSNativeFn = JSC.JSNativeFn; -const Shimmer = JSC.Shimmer; const AnyPromise = JSC.AnyPromise; const DOMURL = JSC.DOMURL; const JestPrettyFormat = @import("../test/pretty_format.zig").JestPrettyFormat; diff --git a/src/bun.js/bindings/LoadLibrary.zig b/src/bun.js/bindings/LoadLibrary.zig deleted file mode 100644 index 2411141978..0000000000 --- a/src/bun.js/bindings/LoadLibrary.zig +++ /dev/null @@ -1,29 +0,0 @@ -const bun = @import("root").bun; -const Environment = bun.Environment; - -/// Returns null on error. Use windows API to lookup the actual error. -/// The reason this function is in zig is so that we can use our own utf16-conversion functions. -/// -/// Using characters16() does not seem to always have the sentinel. or something else -/// broke when I just used it. Not sure. ... but this works! -pub export fn Bun__LoadLibraryBunString(str: *bun.String) ?*anyopaque { - if (comptime !Environment.isWindows) { - unreachable; - } - - var buf: bun.WPathBuffer = undefined; - const data = switch (str.encoding()) { - .utf8 => bun.strings.convertUTF8toUTF16InBuffer(&buf, str.utf8()), - .utf16 => brk: { - @memcpy(buf[0..str.length()], str.utf16()); - break :brk buf[0..str.length()]; - }, - .latin1 => brk: { - bun.strings.copyU8IntoU16(&buf, str.latin1()); - break :brk buf[0..str.length()]; - }, - }; - buf[data.len] = 0; - const LOAD_WITH_ALTERED_SEARCH_PATH = 0x00000008; - return bun.windows.LoadLibraryExW(buf[0..data.len :0].ptr, null, LOAD_WITH_ALTERED_SEARCH_PATH); -} diff --git a/src/bun.js/bindings/Process.zig b/src/bun.js/bindings/Process.zig index e985f6a5eb..0e93ff0e64 100644 --- a/src/bun.js/bindings/Process.zig +++ b/src/bun.js/bindings/Process.zig @@ -1,15 +1,5 @@ -const bun = @import("root").bun; -const JSC = bun.JSC; -const JSGlobalObject = JSC.JSGlobalObject; -const JSValue = JSC.JSValue; -const ZigString = JSC.ZigString; -const Shimmer = @import("./shimmer.zig").Shimmer; - /// Process information and control APIs -pub const Process = extern struct { - pub const shim = Shimmer("Bun", "Process", @This()); - pub const name = "Process"; - pub const namespace = shim.namespace; +pub const Process = opaque { var title_mutex = bun.Mutex{}; pub fn getTitle(_: *JSGlobalObject, title: *ZigString) callconv(.C) void { @@ -36,45 +26,21 @@ pub const Process = extern struct { pub const getExecPath = JSC.Node.Process.getExecPath; pub const getExecArgv = JSC.Node.Process.getExecArgv; - pub const Export = shim.exportFunctions(.{ - .getTitle = getTitle, - .setTitle = setTitle, - .getArgv = getArgv, - .getCwd = getCwd, - .setCwd = setCwd, - .exit = exit, - .getArgv0 = getArgv0, - .getExecPath = getExecPath, - .getExecArgv = getExecArgv, - }); - comptime { - @export(&getTitle, .{ - .name = Export[0].symbol_name, - }); - @export(&setTitle, .{ - .name = Export[1].symbol_name, - }); - @export(&getArgv, .{ - .name = Export[2].symbol_name, - }); - @export(&getCwd, .{ - .name = Export[3].symbol_name, - }); - @export(&setCwd, .{ - .name = Export[4].symbol_name, - }); - @export(&exit, .{ - .name = Export[5].symbol_name, - }); - @export(&getArgv0, .{ - .name = Export[6].symbol_name, - }); - @export(&getExecPath, .{ - .name = Export[7].symbol_name, - }); - @export(&getExecArgv, .{ - .name = Export[8].symbol_name, - }); + @export(&getTitle, .{ .name = "Bun__Process__getTitle" }); + @export(&setTitle, .{ .name = "Bun__Process__setTitle" }); + @export(&getArgv, .{ .name = "Bun__Process__getArgv" }); + @export(&getCwd, .{ .name = "Bun__Process__getCwd" }); + @export(&setCwd, .{ .name = "Bun__Process__setCwd" }); + @export(&exit, .{ .name = "Bun__Process__exit" }); + @export(&getArgv0, .{ .name = "Bun__Process__getArgv0" }); + @export(&getExecPath, .{ .name = "Bun__Process__getExecPath" }); + @export(&getExecArgv, .{ .name = "Bun__Process__getExecArgv" }); } }; + +const bun = @import("root").bun; +const JSC = bun.JSC; +const JSGlobalObject = JSC.JSGlobalObject; +const JSValue = JSC.JSValue; +const ZigString = JSC.ZigString; diff --git a/src/bun.js/bindings/ResolvedSource.zig b/src/bun.js/bindings/ResolvedSource.zig index eacf5193c4..ed35ac3fc1 100644 --- a/src/bun.js/bindings/ResolvedSource.zig +++ b/src/bun.js/bindings/ResolvedSource.zig @@ -1,13 +1,8 @@ const bun = @import("root").bun; const JSC = bun.JSC; -const Shimmer = @import("./shimmer.zig").Shimmer; const JSValue = JSC.JSValue; pub const ResolvedSource = extern struct { - pub const shim = Shimmer("Zig", "ResolvedSource", @This()); - pub const name = "ResolvedSource"; - pub const namespace = shim.namespace; - /// Specifier's lifetime is the caller from C++ /// https://github.com/oven-sh/bun/issues/9521 specifier: bun.String = bun.String.empty, diff --git a/src/bun.js/bindings/ShimReferences.zig b/src/bun.js/bindings/ShimReferences.zig deleted file mode 100644 index 8049de701c..0000000000 --- a/src/bun.js/bindings/ShimReferences.zig +++ /dev/null @@ -1,74 +0,0 @@ -const bun = @import("root").bun; -const JSC = bun.JSC; -const NodePath = JSC.Node.Path; -const WebSocketHTTPClient = JSC.WebSocketHTTPClient; -const WebSocketHTTPSClient = JSC.WebSocketHTTPSClient; -const WebSocketClient = JSC.WebSocketClient; -const WebSocketClientTLS = JSC.WebSocketClientTLS; - -const JSArrayBufferSink = JSC.JSArrayBufferSink; -const JSHTTPResponseSink = JSC.JSHTTPResponseSink; -const JSHTTPSResponseSink = JSC.JSHTTPSResponseSink; -const JSNetworkSink = JSC.JSNetworkSink; -const JSFileSink = JSC.JSFileSink; -const HTTPServerRequestContext = JSC.HTTPServerRequestContext; -const HTTPSSLServerRequestContext = JSC.HTTPSSLServerRequestContext; -const HTTPDebugServerRequestContext = JSC.HTTPDebugServerRequestContext; -const HTTPDebugSSLServerRequestContext = JSC.HTTPDebugSSLServerRequestContext; -const BodyValueBuffererContext = JSC.BodyValueBuffererContext; -const TestScope = JSC.TestScope; -const Process = JSC.Process; -const Environment = bun.Environment; -const Mimalloc = bun.Mimalloc; -const ZigString = JSC.ZigString; -const std = @import("std"); - -export fn ZigString__free(raw: [*]const u8, len: usize, allocator_: ?*anyopaque) void { - var allocator: std.mem.Allocator = @as(*std.mem.Allocator, @ptrCast(@alignCast(allocator_ orelse return))).*; - var ptr = ZigString.init(raw[0..len]).slice().ptr; - if (comptime Environment.allow_assert) { - bun.assert(Mimalloc.mi_is_in_heap_region(ptr)); - } - const str = ptr[0..len]; - - allocator.free(str); -} - -export fn ZigString__free_global(ptr: [*]const u8, len: usize) void { - const untagged = @as(*anyopaque, @ptrFromInt(@intFromPtr(ZigString.init(ptr[0..len]).slice().ptr))); - if (comptime Environment.allow_assert) { - bun.assert(Mimalloc.mi_is_in_heap_region(ptr)); - } - // we must untag the string pointer - Mimalloc.mi_free(untagged); -} - -pub fn addShimReferences() void { - WebSocketHTTPClient.shim.ref(); - WebSocketHTTPSClient.shim.ref(); - WebSocketClient.shim.ref(); - WebSocketClientTLS.shim.ref(); - - HTTPServerRequestContext.shim.ref(); - HTTPSSLServerRequestContext.shim.ref(); - HTTPDebugServerRequestContext.shim.ref(); - HTTPDebugSSLServerRequestContext.shim.ref(); - - _ = Process.getTitle; - _ = Process.setTitle; - NodePath.shim.ref(); - JSArrayBufferSink.shim.ref(); - JSHTTPResponseSink.shim.ref(); - JSHTTPSResponseSink.shim.ref(); - JSNetworkSink.shim.ref(); - JSFileSink.shim.ref(); - JSFileSink.shim.ref(); - _ = &ZigString__free; - _ = &ZigString__free_global; - - TestScope.shim.ref(); - BodyValueBuffererContext.shim.ref(); - - _ = @import("LoadLibrary.zig").Bun__LoadLibraryBunString; - _ = &JSC.NodeModuleModule__findPath; -} diff --git a/src/bun.js/bindings/SystemError.zig b/src/bun.js/bindings/SystemError.zig index d8ed86cd16..34b9fa57c9 100644 --- a/src/bun.js/bindings/SystemError.zig +++ b/src/bun.js/bindings/SystemError.zig @@ -24,10 +24,8 @@ pub const SystemError = extern struct { }; } - pub const shim = JSC.Shimmer("", "SystemError", @This()); - - pub const name = "SystemError"; - pub const namespace = ""; + extern fn SystemError__toErrorInstance(this: *const SystemError, global: *JSGlobalObject) JSValue; + extern fn SystemError__toErrorInstanceWithInfoObject(this: *const SystemError, global: *JSC.JSGlobalObject) JSValue; pub fn getErrno(this: *const SystemError) bun.C.E { // The inverse in bun.sys.Error.toSystemError() @@ -55,7 +53,7 @@ pub const SystemError = extern struct { pub fn toErrorInstance(this: *const SystemError, global: *JSGlobalObject) JSValue { defer this.deref(); - return shim.cppFn("toErrorInstance", .{ this, global }); + return SystemError__toErrorInstance(this, global); } /// This constructs the ERR_SYSTEM_ERROR error object, which has an `info` @@ -82,7 +80,6 @@ pub const SystemError = extern struct { return SystemError__toErrorInstanceWithInfoObject(this, global); } - extern fn SystemError__toErrorInstanceWithInfoObject(*const SystemError, *JSC.JSGlobalObject) JSValue; pub fn format(self: SystemError, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { if (!self.path.isEmpty()) { @@ -117,8 +114,4 @@ pub const SystemError = extern struct { ), } } - - pub const Extern = [_][]const u8{ - "toErrorInstance", - }; }; diff --git a/src/bun.js/bindings/VM.zig b/src/bun.js/bindings/VM.zig index 13bb82ce7f..91507bf1d8 100644 --- a/src/bun.js/bindings/VM.zig +++ b/src/bun.js/bindings/VM.zig @@ -3,42 +3,37 @@ const bun = @import("root").bun; const JSC = bun.JSC; const JSGlobalObject = JSC.JSGlobalObject; const JSValue = JSC.JSValue; -const Shimmer = JSC.Shimmer; - -pub const VM = extern struct { - pub const shim = Shimmer("JSC", "VM", @This()); - bytes: shim.Bytes, - - const cppFn = shim.cppFn; - - pub const include = "JavaScriptCore/VM.h"; - pub const name = "JSC::VM"; - pub const namespace = "JSC"; +pub const VM = opaque { pub const HeapType = enum(u8) { SmallHeap = 0, LargeHeap = 1, }; + extern fn JSC__VM__create(heap_type: u8) *VM; pub fn create(heap_type: HeapType) *VM { - return cppFn("create", .{@intFromEnum(heap_type)}); + return JSC__VM__create(@intFromEnum(heap_type)); } + extern fn JSC__VM__deinit(vm: *VM, global_object: *JSGlobalObject) void; pub fn deinit(vm: *VM, global_object: *JSGlobalObject) void { - return cppFn("deinit", .{ vm, global_object }); + return JSC__VM__deinit(vm, global_object); } + extern fn JSC__VM__setControlFlowProfiler(vm: *VM, enabled: bool) void; pub fn setControlFlowProfiler(vm: *VM, enabled: bool) void { - return cppFn("setControlFlowProfiler", .{ vm, enabled }); + return JSC__VM__setControlFlowProfiler(vm, enabled); } + extern fn JSC__VM__isJITEnabled() bool; pub fn isJITEnabled() bool { - return cppFn("isJITEnabled", .{}); + return JSC__VM__isJITEnabled(); } /// deprecated in favor of getAPILock to avoid an annoying callback wrapper + extern fn JSC__VM__holdAPILock(this: *VM, ctx: ?*anyopaque, callback: *const fn (ctx: ?*anyopaque) callconv(.C) void) void; pub fn holdAPILock(this: *VM, ctx: ?*anyopaque, callback: *const fn (ctx: ?*anyopaque) callconv(.C) void) void { - cppFn("holdAPILock", .{ this, ctx, callback }); + JSC__VM__holdAPILock(this, ctx, callback); } extern fn JSC__VM__getAPILock(vm: *VM) void; @@ -57,8 +52,9 @@ pub const VM = extern struct { } }; + extern fn JSC__VM__deferGC(this: *VM, ctx: ?*anyopaque, callback: *const fn (ctx: ?*anyopaque) callconv(.C) void) void; pub fn deferGC(this: *VM, ctx: ?*anyopaque, callback: *const fn (ctx: ?*anyopaque) callconv(.C) void) void { - cppFn("deferGC", .{ this, ctx, callback }); + JSC__VM__deferGC(this, ctx, callback); } extern fn JSC__VM__reportExtraMemory(*VM, usize) void; pub fn reportExtraMemory(this: *VM, size: usize) void { @@ -66,152 +62,132 @@ pub const VM = extern struct { JSC__VM__reportExtraMemory(this, size); } + extern fn JSC__VM__deleteAllCode(vm: *VM, global_object: *JSGlobalObject) void; pub fn deleteAllCode( vm: *VM, global_object: *JSGlobalObject, ) void { - return cppFn("deleteAllCode", .{ vm, global_object }); + return JSC__VM__deleteAllCode(vm, global_object); } + extern fn JSC__VM__whenIdle(vm: *VM, callback: *const fn (...) callconv(.C) void) void; pub fn whenIdle( vm: *VM, callback: *const fn (...) callconv(.C) void, ) void { - return cppFn("whenIdle", .{ vm, callback }); + return JSC__VM__whenIdle(vm, callback); } + extern fn JSC__VM__shrinkFootprint(vm: *VM) void; pub fn shrinkFootprint( vm: *VM, ) void { - return cppFn("shrinkFootprint", .{ - vm, - }); + return JSC__VM__shrinkFootprint(vm); } + extern fn JSC__VM__runGC(vm: *VM, sync: bool) usize; pub fn runGC(vm: *VM, sync: bool) usize { - return cppFn("runGC", .{ - vm, - sync, - }); + return JSC__VM__runGC(vm, sync); } + extern fn JSC__VM__heapSize(vm: *VM) usize; pub fn heapSize(vm: *VM) usize { - return cppFn("heapSize", .{ - vm, - }); + return JSC__VM__heapSize(vm); } + extern fn JSC__VM__collectAsync(vm: *VM) void; pub fn collectAsync(vm: *VM) void { - return cppFn("collectAsync", .{ - vm, - }); + return JSC__VM__collectAsync(vm); } + extern fn JSC__VM__setExecutionForbidden(vm: *VM, forbidden: bool) void; pub fn setExecutionForbidden(vm: *VM, forbidden: bool) void { - cppFn("setExecutionForbidden", .{ vm, forbidden }); + JSC__VM__setExecutionForbidden(vm, forbidden); } + extern fn JSC__VM__setExecutionTimeLimit(vm: *VM, timeout: f64) void; pub fn setExecutionTimeLimit(vm: *VM, timeout: f64) void { - return cppFn("setExecutionTimeLimit", .{ vm, timeout }); + return JSC__VM__setExecutionTimeLimit(vm, timeout); } + extern fn JSC__VM__clearExecutionTimeLimit(vm: *VM) void; pub fn clearExecutionTimeLimit(vm: *VM) void { - return cppFn("clearExecutionTimeLimit", .{vm}); + return JSC__VM__clearExecutionTimeLimit(vm); } + extern fn JSC__VM__executionForbidden(vm: *VM) bool; pub fn executionForbidden(vm: *VM) bool { - return cppFn("executionForbidden", .{ - vm, - }); + return JSC__VM__executionForbidden(vm); } // These four functions fire VM traps. To understand what that means, see VMTraps.h for a giant explainer. // These may be called concurrently from another thread. + extern fn JSC__VM__notifyNeedTermination(vm: *VM) void; + /// Fires NeedTermination Trap. Thread safe. See JSC's "VMTraps.h" for explaination on traps. pub fn notifyNeedTermination(vm: *VM) void { - cppFn("notifyNeedTermination", .{vm}); + JSC__VM__notifyNeedTermination(vm); } + + extern fn JSC__VM__notifyNeedWatchdogCheck(vm: *VM) void; + /// Fires NeedWatchdogCheck Trap. Thread safe. See JSC's "VMTraps.h" for explaination on traps. pub fn notifyNeedWatchdogCheck(vm: *VM) void { - cppFn("notifyNeedWatchdogCheck", .{vm}); + JSC__VM__notifyNeedWatchdogCheck(vm); } + + extern fn JSC__VM__notifyNeedDebuggerBreak(vm: *VM) void; + /// Fires NeedDebuggerBreak Trap. Thread safe. See JSC's "VMTraps.h" for explaination on traps. pub fn notifyNeedDebuggerBreak(vm: *VM) void { - cppFn("notifyNeedDebuggerBreak", .{vm}); + JSC__VM__notifyNeedDebuggerBreak(vm); } + + extern fn JSC__VM__notifyNeedShellTimeoutCheck(vm: *VM) void; + /// Fires NeedShellTimeoutCheck Trap. Thread safe. See JSC's "VMTraps.h" for explaination on traps. pub fn notifyNeedShellTimeoutCheck(vm: *VM) void { - cppFn("notifyNeedShellTimeoutCheck", .{vm}); + JSC__VM__notifyNeedShellTimeoutCheck(vm); } + extern fn JSC__VM__isEntered(vm: *VM) bool; pub fn isEntered(vm: *VM) bool { - return cppFn("isEntered", .{ - vm, - }); + return JSC__VM__isEntered(vm); } - // manual extern to workaround shimmer limitation - // shimmer doesnt let you change the return type or make it non-pub extern fn JSC__VM__throwError(*VM, *JSGlobalObject, JSValue) void; pub fn throwError(vm: *VM, global_object: *JSGlobalObject, value: JSValue) void { JSC__VM__throwError(vm, global_object, value); } + extern fn JSC__VM__releaseWeakRefs(vm: *VM) void; pub fn releaseWeakRefs(vm: *VM) void { - return cppFn("releaseWeakRefs", .{vm}); + return JSC__VM__releaseWeakRefs(vm); } + extern fn JSC__VM__drainMicrotasks(vm: *VM) void; pub fn drainMicrotasks( vm: *VM, ) void { - return cppFn("drainMicrotasks", .{ - vm, - }); + return JSC__VM__drainMicrotasks(vm); } + extern fn JSC__VM__externalMemorySize(vm: *VM) usize; pub fn externalMemorySize(vm: *VM) usize { - return cppFn("externalMemorySize", .{vm}); + return JSC__VM__externalMemorySize(vm); } + extern fn JSC__VM__blockBytesAllocated(vm: *VM) usize; + /// `RESOURCE_USAGE` build option in JavaScriptCore is required for this function /// This is faster than checking the heap size pub fn blockBytesAllocated(vm: *VM) usize { - return cppFn("blockBytesAllocated", .{vm}); + return JSC__VM__blockBytesAllocated(vm); } + extern fn JSC__VM__performOpportunisticallyScheduledTasks(vm: *VM, until: f64) void; pub fn performOpportunisticallyScheduledTasks(vm: *VM, until: f64) void { - cppFn("performOpportunisticallyScheduledTasks", .{ vm, until }); + JSC__VM__performOpportunisticallyScheduledTasks(vm, until); } - - pub const Extern = [_][]const u8{ - "setControlFlowProfiler", - "collectAsync", - "externalMemorySize", - "blockBytesAllocated", - "heapSize", - "releaseWeakRefs", - "throwError", - "deferGC", - "holdAPILock", - "runGC", - "generateHeapSnapshot", - "isJITEnabled", - "deleteAllCode", - "create", - "deinit", - "setExecutionForbidden", - "executionForbidden", - "isEntered", - "throwError", - "drainMicrotasks", - "whenIdle", - "shrinkFootprint", - "setExecutionTimeLimit", - "clearExecutionTimeLimit", - "notifyNeedTermination", - "notifyNeedWatchdogCheck", - "notifyNeedDebuggerBreak", - "notifyNeedShellTimeoutCheck", - }; }; diff --git a/src/bun.js/bindings/ZigErrorType.zig b/src/bun.js/bindings/ZigErrorType.zig index 960391dee6..8559dda282 100644 --- a/src/bun.js/bindings/ZigErrorType.zig +++ b/src/bun.js/bindings/ZigErrorType.zig @@ -1,11 +1,6 @@ -const Shimmer = @import("./shimmer.zig").Shimmer; -const ErrorCode = @import("ErrorCode.zig").ErrorCode; - pub const ZigErrorType = extern struct { - pub const shim = Shimmer("Zig", "ErrorType", @This()); - pub const name = "ErrorType"; - pub const namespace = shim.namespace; - code: ErrorCode, ptr: ?*anyopaque, }; + +const ErrorCode = @import("ErrorCode.zig").ErrorCode; diff --git a/src/bun.js/bindings/ZigGlobalObject.zig b/src/bun.js/bindings/ZigGlobalObject.zig index 2c3569d5d1..73fabdadb7 100644 --- a/src/bun.js/bindings/ZigGlobalObject.zig +++ b/src/bun.js/bindings/ZigGlobalObject.zig @@ -1,6 +1,5 @@ const bun = @import("root").bun; const JSC = bun.JSC; -const Shimmer = @import("./shimmer.zig").Shimmer; const JSGlobalObject = JSC.JSGlobalObject; const ZigString = JSC.ZigString; const String = bun.String; @@ -12,15 +11,8 @@ const ErrorableString = JSC.ErrorableString; const NewGlobalObject = JSC.NewGlobalObject; /// Global object for Zig JavaScript environment -pub const ZigGlobalObject = extern struct { - pub const shim = Shimmer("Zig", "GlobalObject", @This()); - bytes: shim.Bytes, - pub const Type = *anyopaque; - pub const name = "Zig::GlobalObject"; - pub const include = "\"ZigGlobalObject.h\""; - pub const namespace = shim.namespace; - pub const Interface: type = NewGlobalObject(JSC.VirtualMachine); - +pub const ZigGlobalObject = opaque { + const interface = NewGlobalObject(JSC.VirtualMachine); pub fn create( vm: *JSC.VirtualMachine, console: *anyopaque, @@ -30,7 +22,7 @@ pub const ZigGlobalObject = extern struct { worker_ptr: ?*anyopaque, ) *JSGlobalObject { vm.eventLoop().ensureWaker(); - const global = shim.cppFn("create", .{ console, context_id, mini_mode, eval_mode, worker_ptr }); + const global = Zig__GlobalObject__create(console, context_id, mini_mode, eval_mode, worker_ptr); // JSC might mess with the stack size. bun.StackCheck.configureThread(); @@ -39,55 +31,54 @@ pub const ZigGlobalObject = extern struct { } pub fn getModuleRegistryMap(global: *JSGlobalObject) *anyopaque { - return shim.cppFn("getModuleRegistryMap", .{global}); + return Zig__GlobalObject__getModuleRegistryMap(global); } pub fn resetModuleRegistryMap(global: *JSGlobalObject, map: *anyopaque) bool { - return shim.cppFn("resetModuleRegistryMap", .{ global, map }); + return Zig__GlobalObject__resetModuleRegistryMap(global, map); } + extern fn Zig__GlobalObject__create( + console: *anyopaque, + context_id: i32, + mini_mode: bool, + eval_mode: bool, + worker_ptr: ?*anyopaque, + ) *JSGlobalObject; + + extern fn Zig__GlobalObject__getModuleRegistryMap(global: *JSGlobalObject) *anyopaque; + extern fn Zig__GlobalObject__resetModuleRegistryMap(global: *JSGlobalObject, map: *anyopaque) bool; + pub fn import(global: *JSGlobalObject, specifier: *bun.String, source: *bun.String) callconv(.C) ErrorableString { JSC.markBinding(@src()); - - return @call(bun.callmod_inline, Interface.import, .{ global, specifier, source }); + return @call(bun.callmod_inline, interface.import, .{ global, specifier, source }); } + pub fn resolve(res: *ErrorableString, global: *JSGlobalObject, specifier: *bun.String, source: *bun.String, query: *ZigString) callconv(.C) void { JSC.markBinding(@src()); - @call(bun.callmod_inline, Interface.resolve, .{ res, global, specifier, source, query }); + @call(bun.callmod_inline, interface.resolve, .{ res, global, specifier, source, query }); } pub fn promiseRejectionTracker(global: *JSGlobalObject, promise: *JSPromise, rejection: JSPromiseRejectionOperation) callconv(.C) JSValue { JSC.markBinding(@src()); - return @call(bun.callmod_inline, Interface.promiseRejectionTracker, .{ global, promise, rejection }); + return @call(bun.callmod_inline, interface.promiseRejectionTracker, .{ global, promise, rejection }); } pub fn reportUncaughtException(global: *JSGlobalObject, exception: *Exception) callconv(.C) JSValue { JSC.markBinding(@src()); - return @call(bun.callmod_inline, Interface.reportUncaughtException, .{ global, exception }); + return @call(bun.callmod_inline, interface.reportUncaughtException, .{ global, exception }); } pub fn onCrash() callconv(.C) void { JSC.markBinding(@src()); - return @call(bun.callmod_inline, Interface.onCrash, .{}); + return @call(bun.callmod_inline, interface.onCrash, .{}); } - pub const Export = shim.exportFunctions( - .{ - .import = import, - .resolve = resolve, - .promiseRejectionTracker = promiseRejectionTracker, - .reportUncaughtException = reportUncaughtException, - .onCrash = onCrash, - }, - ); - - pub const Extern = [_][]const u8{ "create", "getModuleRegistryMap", "resetModuleRegistryMap" }; - comptime { - @export(&import, .{ .name = Export[0].symbol_name }); - @export(&resolve, .{ .name = Export[1].symbol_name }); - @export(&promiseRejectionTracker, .{ .name = Export[2].symbol_name }); - @export(&reportUncaughtException, .{ .name = Export[3].symbol_name }); - @export(&onCrash, .{ .name = Export[4].symbol_name }); + @export(&import, .{ .name = "Zig__GlobalObject__import" }); + @export(&resolve, .{ .name = "Zig__GlobalObject__resolve" }); + @export(&promiseRejectionTracker, .{ .name = "Zig__GlobalObject__promiseRejectionTracker" }); + @export(&reportUncaughtException, .{ .name = "Zig__GlobalObject__reportUncaughtException" }); + @export(&onCrash, .{ .name = "Zig__GlobalObject__onCrash" }); } }; diff --git a/src/bun.js/bindings/ZigString.zig b/src/bun.js/bindings/ZigString.zig index 04db088aa3..344545e88c 100644 --- a/src/bun.js/bindings/ZigString.zig +++ b/src/bun.js/bindings/ZigString.zig @@ -5,7 +5,6 @@ const Output = bun.Output; const strings = bun.strings; const JSC = bun.JSC; const String = bun.String; -const Shimmer = JSC.Shimmer; const NullableAllocator = bun.NullableAllocator; const MutableString = bun.MutableString; const OOM = bun.OOM; @@ -13,6 +12,8 @@ const JSGlobalObject = JSC.JSGlobalObject; const JSValue = JSC.JSValue; const JSString = @import("JSString.zig").JSString; const C_API = bun.JSC.C; +const Environment = bun.Environment; +const Mimalloc = bun.Mimalloc; /// Prefer using bun.String instead of ZigString in new code. pub const ZigString = extern struct { @@ -307,8 +308,6 @@ pub const ZigString = extern struct { @compileError("Not implemented yet for latin1"); } - pub const shim = Shimmer("", "ZigString", @This()); - pub inline fn length(this: ZigString) usize { return this.len; } @@ -455,9 +454,6 @@ pub const ZigString = extern struct { } }; - pub const name = "ZigString"; - pub const namespace = ""; - pub inline fn is16Bit(this: *const ZigString) bool { return (@intFromPtr(this._unsafe_ptr_do_not_use) & (1 << 63)) != 0; } @@ -550,8 +546,9 @@ pub const ZigString = extern struct { return GithubActionFormatter{ .text = this }; } + extern fn ZigString__toAtomicValue(this: *const ZigString, globalThis: *JSC.JSGlobalObject) JSValue; pub fn toAtomicValue(this: *const ZigString, globalThis: *JSC.JSGlobalObject) JSValue { - return shim.cppFn("toAtomicValue", .{ this, globalThis }); + return ZigString__toAtomicValue(this, globalThis); } pub fn initUTF16(items: []const u16) ZigString { @@ -597,13 +594,14 @@ pub const ZigString = extern struct { } } + extern fn ZigString__toExternalU16(ptr: [*]const u16, len: usize, global: *JSGlobalObject) JSValue; pub fn toExternalU16(ptr: [*]const u16, len: usize, global: *JSGlobalObject) JSValue { if (len > String.max_length()) { bun.default_allocator.free(ptr[0..len]); global.ERR_STRING_TOO_LONG("Cannot create a string longer than 2^32-1 characters", .{}).throw() catch {}; // TODO: propagate? return .zero; } - return shim.cppFn("toExternalU16", .{ ptr, len, global }); + return ZigString__toExternalU16(ptr, len, global); } pub fn isUTF8(this: ZigString) bool { @@ -782,6 +780,7 @@ pub const ZigString = extern struct { } } + extern fn ZigString__toExternalValue(this: *const ZigString, global: *JSGlobalObject) JSValue; pub fn toExternalValue(this: *const ZigString, global: *JSGlobalObject) JSValue { this.assertGlobal(); if (this.len > String.max_length()) { @@ -789,17 +788,28 @@ pub const ZigString = extern struct { global.ERR_STRING_TOO_LONG("Cannot create a string longer than 2^32-1 characters", .{}).throw() catch {}; // TODO: propagate? return .zero; } - return shim.cppFn("toExternalValue", .{ this, global }); + return ZigString__toExternalValue(this, global); } + extern fn ZigString__toExternalValueWithCallback( + this: *const ZigString, + global: *JSGlobalObject, + callback: *const fn (ctx: ?*anyopaque, ptr: ?*anyopaque, len: usize) callconv(.C) void, + ) JSValue; pub fn toExternalValueWithCallback( this: *const ZigString, global: *JSGlobalObject, callback: *const fn (ctx: ?*anyopaque, ptr: ?*anyopaque, len: usize) callconv(.C) void, ) JSValue { - return shim.cppFn("toExternalValueWithCallback", .{ this, global, callback }); + return ZigString__toExternalValueWithCallback(this, global, callback); } + extern fn ZigString__external( + this: *const ZigString, + global: *JSGlobalObject, + ctx: ?*anyopaque, + callback: *const fn (ctx: ?*anyopaque, ptr: ?*anyopaque, len: usize) callconv(.C) void, + ) JSValue; pub fn external( this: *const ZigString, global: *JSGlobalObject, @@ -812,12 +822,13 @@ pub const ZigString = extern struct { return .zero; } - return shim.cppFn("external", .{ this, global, ctx, callback }); + return ZigString__external(this, global, ctx, callback); } + extern fn ZigString__to16BitValue(this: *const ZigString, global: *JSGlobalObject) JSValue; pub fn to16BitValue(this: *const ZigString, global: *JSGlobalObject) JSValue { this.assertGlobal(); - return shim.cppFn("to16BitValue", .{ this, global }); + return ZigString__to16BitValue(this, global); } pub fn withEncoding(this: *const ZigString) ZigString { @@ -837,37 +848,48 @@ pub const ZigString = extern struct { C_API.JSStringCreateStatic(untagged(this._unsafe_ptr_do_not_use), this.len); } + extern fn ZigString__toErrorInstance(this: *const ZigString, global: *JSGlobalObject) JSValue; pub fn toErrorInstance(this: *const ZigString, global: *JSGlobalObject) JSValue { - return shim.cppFn("toErrorInstance", .{ this, global }); + return ZigString__toErrorInstance(this, global); } + extern fn ZigString__toTypeErrorInstance(this: *const ZigString, global: *JSGlobalObject) JSValue; pub fn toTypeErrorInstance(this: *const ZigString, global: *JSGlobalObject) JSValue { - return shim.cppFn("toTypeErrorInstance", .{ this, global }); + return ZigString__toTypeErrorInstance(this, global); } + extern fn ZigString__toSyntaxErrorInstance(this: *const ZigString, global: *JSGlobalObject) JSValue; pub fn toSyntaxErrorInstance(this: *const ZigString, global: *JSGlobalObject) JSValue { - return shim.cppFn("toSyntaxErrorInstance", .{ this, global }); + return ZigString__toSyntaxErrorInstance(this, global); } + extern fn ZigString__toRangeErrorInstance(this: *const ZigString, global: *JSGlobalObject) JSValue; pub fn toRangeErrorInstance(this: *const ZigString, global: *JSGlobalObject) JSValue { - return shim.cppFn("toRangeErrorInstance", .{ this, global }); + return ZigString__toRangeErrorInstance(this, global); } - - pub const Extern = [_][]const u8{ - "toAtomicValue", - "toExternalValue", - "to16BitValue", - "toErrorInstance", - "toExternalU16", - "toExternalValueWithCallback", - "external", - "toTypeErrorInstance", - "toSyntaxErrorInstance", - "toRangeErrorInstance", - }; }; pub const StringPointer = struct { offset: usize = 0, length: usize = 0, }; + +export fn ZigString__free(raw: [*]const u8, len: usize, allocator_: ?*anyopaque) void { + var allocator: std.mem.Allocator = @as(*std.mem.Allocator, @ptrCast(@alignCast(allocator_ orelse return))).*; + var ptr = ZigString.init(raw[0..len]).slice().ptr; + if (comptime Environment.allow_assert) { + bun.assert(Mimalloc.mi_is_in_heap_region(ptr)); + } + const str = ptr[0..len]; + + allocator.free(str); +} + +export fn ZigString__freeGlobal(ptr: [*]const u8, len: usize) void { + const untagged = @as(*anyopaque, @ptrFromInt(@intFromPtr(ZigString.init(ptr[0..len]).slice().ptr))); + if (comptime Environment.allow_assert) { + bun.assert(Mimalloc.mi_is_in_heap_region(ptr)); + } + // we must untag the string pointer + Mimalloc.mi_free(untagged); +} diff --git a/src/bun.js/bindings/bindings.zig b/src/bun.js/bindings/bindings.zig index 615bd9e041..51f1841af0 100644 --- a/src/bun.js/bindings/bindings.zig +++ b/src/bun.js/bindings/bindings.zig @@ -12,7 +12,7 @@ const ZigException = Exports.ZigException; const ZigStackTrace = Exports.ZigStackTrace; const ArrayBuffer = @import("../base.zig").ArrayBuffer; const JSC = bun.JSC; -const Shimmer = JSC.Shimmer; + const FFI = @import("./FFI.zig"); const NullableAllocator = bun.NullableAllocator; const MutableString = bun.MutableString; @@ -424,8 +424,39 @@ pub fn initialize(eval_mode: bool) void { ); } +/// Returns null on error. Use windows API to lookup the actual error. +/// The reason this function is in zig is so that we can use our own utf16-conversion functions. +/// +/// Using characters16() does not seem to always have the sentinel. or something else +/// broke when I just used it. Not sure. ... but this works! +fn @"windows process.dlopen"(str: *bun.String) callconv(.C) ?*anyopaque { + if (comptime !bun.Environment.isWindows) { + unreachable; + } + + var buf: bun.WPathBuffer = undefined; + const data = switch (str.encoding()) { + .utf8 => bun.strings.convertUTF8toUTF16InBuffer(&buf, str.utf8()), + .utf16 => brk: { + @memcpy(buf[0..str.length()], str.utf16()); + break :brk buf[0..str.length()]; + }, + .latin1 => brk: { + bun.strings.copyU8IntoU16(&buf, str.latin1()); + break :brk buf[0..str.length()]; + }, + }; + buf[data.len] = 0; + const LOAD_WITH_ALTERED_SEARCH_PATH = 0x00000008; + return bun.windows.LoadLibraryExW(buf[0..data.len :0].ptr, null, LOAD_WITH_ALTERED_SEARCH_PATH); +} + comptime { // this file is gennerated, but cant be placed in the build/debug/codegen folder // because zig will complain about outside-of-module stuff _ = @import("./GeneratedJS2Native.zig"); + + if (bun.Environment.isWindows) { + @export(&@"windows process.dlopen", .{ .name = "Bun__LoadLibraryBunString" }); + } } diff --git a/src/bun.js/bindings/exports.zig b/src/bun.js/bindings/exports.zig index 6bf7aa3b8a..382570442f 100644 --- a/src/bun.js/bindings/exports.zig +++ b/src/bun.js/bindings/exports.zig @@ -31,6 +31,13 @@ pub const WebSocketHTTPSClient = @import("../../http/websocket_http_client.zig") pub const WebSocketClient = @import("../../http/websocket_http_client.zig").WebSocketClient; pub const WebSocketClientTLS = @import("../../http/websocket_http_client.zig").WebSocketClientTLS; +comptime { + WebSocketClient.exportAll(); + WebSocketClientTLS.exportAll(); + WebSocketHTTPClient.exportAll(); + WebSocketHTTPSClient.exportAll(); +} + // Re-export the Errorable type and common instances pub const Errorable = @import("Errorable.zig").Errorable; pub const ResolvedSource = @import("ResolvedSource.zig").ResolvedSource; @@ -44,6 +51,10 @@ pub const ZigStackFrameCode = @import("ZigStackFrameCode.zig").ZigStackFrameCode // Re-export Process pub const Process = @import("Process.zig").Process; +comptime { + _ = Process.getTitle; + _ = Process.setTitle; +} // Re-export stack trace related types pub const ZigStackTrace = @import("ZigStackTrace.zig").ZigStackTrace; @@ -66,12 +77,3 @@ pub const HTTPDebugServerRequestContext = JSC.API.DebugHTTPServer.RequestContext pub const HTTPDebugSSLServerRequestContext = JSC.API.DebugHTTPSServer.RequestContext; pub const BodyValueBuffererContext = JSC.WebCore.BodyValueBufferer; pub const TestScope = @import("../test/jest.zig").TestScope; - -// Reference all the shims -comptime { - @import("ShimReferences.zig").addShimReferences(); -} - -// Re-export LoadLibrary and NodeModuleModule -pub const Bun__LoadLibraryBunString = @import("LoadLibrary.zig").Bun__LoadLibraryBunString; -pub const NodeModuleModule__findPath = @import("NodeModuleModule.zig").NodeModuleModule__findPath; diff --git a/src/bun.js/bindings/header-gen.zig b/src/bun.js/bindings/header-gen.zig deleted file mode 100644 index 14a8eac7b7..0000000000 --- a/src/bun.js/bindings/header-gen.zig +++ /dev/null @@ -1,1088 +0,0 @@ -const std = @import("std"); -const Dir = std.fs.Dir; -const FnMeta = std.builtin.Type.Fn; -const FnDecl = std.builtin.Type.Declaration.Data.FnDecl; -const StructMeta = std.builtin.Type.Struct; -const EnumMeta = std.builtin.Type.Enum; -const UnionMeta = std.builtin.Type.Union; -const warn = std.debug.warn; -const StaticExport = @import("./static_export.zig"); -const typeBaseName = @import("../../meta.zig").typeBaseName; -const bun = @import("root").bun; -const TypeNameMap = bun.StringHashMap([]const u8); - -fn isCppObject(comptime Type: type) bool { - return switch (@typeInfo(Type)) { - .Struct, .Union, .Opaque => true, - .Enum => @hasDecl(Type, "Type"), - else => false, - }; -} - -const ENABLE_REWRITE_RETURN = false; - -pub fn cTypeLabel(comptime Type: type) ?[]const u8 { - return switch (comptime Type) { - *c_char => "char*", - [*c]u8, *const c_char => "const char*", - c_char => "char", - *void => "void", - bool => "bool", - usize => "size_t", - isize => "int", - u8 => "unsigned char", - u16 => "uint16_t", - u32 => "uint32_t", - u64 => "uint64_t", - i8 => "int8_t", - i16 => "int16_t", - i24 => "int24_t", - i32 => "int32_t", - i64 => "int64_t", - f64 => "double", - f32 => "float", - *anyopaque => "void*", - *const anyopaque => "const void*", - [*c]bool, [*]bool => "bool*", - [*c]usize, [*]usize => "size_t*", - [*c]isize, [*]isize => "int*", - [*]u8 => "unsigned char*", - [*c]u16, [*]u16 => "uint16_t*", - [*c]u32, [*]u32 => "uint32_t*", - [*c]u64, [*]u64 => "uint64_t*", - [*c]i8, [*]i8 => "int8_t*", - [*c]i16, [*]i16 => "int16_t*", - [*c]i32, [*]i32 => "int32_t*", - [*c]i64, [*]i64 => "int64_t*", - [*c]const bool, [*]const bool => "const bool*", - [*c]const usize, [*]const usize => "const size_t*", - [*c]const isize, [*]const isize => "const int*", - [*c]const u8, [*]const u8 => "const unsigned char*", - [*c]const u16, [*]const u16 => "const uint16_t*", - [*c]const u32, [*]const u32 => "const uint32_t*", - [*c]const u64, [*]const u64 => "const uint64_t*", - [*c]const i8, [*]const i8 => "const int8_t*", - [*c]const i16, [*]const i16 => "const int16_t*", - [*c]const i32, [*]const i32 => "const int32_t*", - [*c]const i64, [*]const i64 => "const int64_t*", - else => null, - }; -} - -var buffer = std.ArrayList(u8).init(std.heap.c_allocator); -var writer = buffer.writer(); -var impl_buffer = std.ArrayList(u8).init(std.heap.c_allocator); -var impl_writer = impl_buffer.writer(); -var bufset = std.BufSet.init(std.heap.c_allocator); -var type_names = TypeNameMap.init(std.heap.c_allocator); -var opaque_types = std.BufSet.init(std.heap.c_allocator); -var size_map = bun.StringHashMap(u32).init(std.heap.c_allocator); -var align_map = bun.StringHashMap(u29).init(std.heap.c_allocator); - -pub const C_Generator = struct { - filebase: []const u8, - - direction: Direction = .export_cpp, - const Self = @This(); - - pub const Direction = enum { - export_cpp, - export_zig, - }; - - pub fn init(comptime src_file: []const u8, comptime Writer: type, _: Writer) Self { - const res = Self{ .filebase = src_file }; - - return res; - } - - pub fn deinit(_: *const Self) void { - // self.file.writeAll("\n/**** ****/\n\n") catch unreachable; - } - - pub fn gen_func( - self: *Self, - comptime name: []const u8, - comptime func: anytype, - comptime meta: FnMeta, - comptime _: []const []const u8, - comptime rewrite_return: bool, - ) void { - switch (comptime meta.calling_convention) { - .Naked => self.write("__attribute__((naked)) "), - .Stdcall => self.write("__attribute__((stdcall)) "), - .Fastcall => self.write("__attribute__((fastcall)) "), - .Thiscall => self.write("__attribute__((thiscall)) "), - else => {}, - } - - switch (self.direction) { - .export_cpp => self.write("CPP_DECL "), - .export_zig => self.write("ZIG_DECL "), - } - - const return_type: type = comptime if (@TypeOf(func.return_type) == ?type) - (func.return_type orelse void) - else - func.return_type; - - if (comptime rewrite_return) { - self.writeType(void); - } else { - self.writeType(comptime return_type); - } - - self.write(" " ++ name ++ "("); - - if (comptime rewrite_return) { - self.writeType(comptime return_type); - self.write("_buf ret_value"); - - if (comptime meta.args.len > 0) { - self.write(", "); - } - } - - comptime var nonnull = std.BoundedArray(u8, 32).init(0) catch unreachable; - - inline for (meta.params, 0..) |arg, i| { - const ArgType = comptime arg.type.?; - - switch (comptime @typeInfo(ArgType)) { - .Fn => { - self.gen_closure(comptime arg.type.?, comptime std.fmt.comptimePrint(" ArgFn{d}", .{i})); - comptime nonnull.append(i) catch unreachable; - }, - else => |info| { - if (comptime info == .pointer and @typeInfo(info.pointer.child) == .Fn) { - self.gen_closure(comptime info.pointer.child, comptime std.fmt.comptimePrint(" ArgFn{d}", .{i})); - comptime nonnull.append(i) catch unreachable; - } else { - self.writeType(comptime arg.type.?); - - switch (@typeInfo(ArgType)) { - .Enum => { - self.write(comptime std.fmt.comptimePrint(" {s}{d}", .{ typeBaseName(@typeName(ArgType)), i })); - }, - - else => { - self.write(comptime std.fmt.comptimePrint(" arg{d}", .{i})); - }, - } - } - }, - } - - // if (comptime func.arg_names.len > 0 and func.arg_names.len > i) { - // self.write(comptime arg_names[i]); - // } else { - - //TODO: Figure out how to get arg names; for now just do arg0..argN - if (i != meta.params.len - 1) - self.write(", "); - } - - self.write(")"); - // we don't handle nonnull due to MSVC not supporting it. - defer self.write(";\n"); - // const ReturnTypeInfo: std.builtin.Type = comptime @typeInfo(func.return_type); - // switch (comptime ReturnTypeInfo) { - // .pointer => |Pointer| { - // self.write(" __attribute__((returns_nonnull))"); - // }, - // .Optional => |Optional| {}, - // else => {}, - // } - } - - pub fn gen_closure( - self: *Self, - comptime Function: type, - comptime name: []const u8, - ) void { - const func: std.builtin.Type.Fn = @typeInfo(Function).Fn; - self.writeType(func.return_type orelse void); - self.write("(*" ++ name ++ ")("); - inline for (func.params, 0..) |arg, i| { - self.writeType(arg.type.?); - // if (comptime func.arg_names.len > 0 and func.arg_names.len > i) { - // self.write(comptime arg_names[i]); - // } else { - const ArgType = arg.type.?; - if (@typeInfo(ArgType) == .Enum) { - self.write(comptime std.fmt.comptimePrint(" {s}{d}", .{ typeBaseName(@typeName(ArgType)), i })); - } else { - self.write(comptime std.fmt.comptimePrint(" arg{d}", .{i})); - } - // } - - //TODO: Figure out how to get arg names; for now just do arg0..argN - if (i != func.params.len - 1) - self.write(", "); - } - - self.write(")"); - // const ReturnTypeInfo: std.builtin.Type = comptime @typeInfo(func.return_type); - // switch (comptime ReturnTypeInfo) { - // .pointer => |Pointer| { - // self.write(" __attribute__((returns_nonnull))"); - // }, - // .Optional => |Optional| {}, - // else => {}, - // } - } - - pub fn gen_struct( - self: *Self, - comptime name: []const u8, - comptime meta: StructMeta, - comptime static_types: anytype, - ) void { - self.write("typedef struct "); - - if (meta.layout == .Packed) - self.write("__attribute__((__packed__)) "); - - self.write(name ++ " {\n"); - - inline for (meta.fields) |field| { - self.write(" "); - - const info = @typeInfo(field.type); - - if (info == .Array) { - const PrintType = comptime brk: { - for (static_types) |static_type| { - if (static_type.Type == info.Array.child) { - break :brk static_type.Type; - } - } - - break :brk info.Array.child; - }; - self.writeType(PrintType); - } else { - const PrintType = comptime brk: { - for (static_types) |static_type| { - if (static_type.Type == field.type) { - break :brk static_type.Type; - } - } - - break :brk field.type; - }; - self.writeType(PrintType); - } - - self.write(" " ++ field.name); - - if (info == .Array) { - writer.print("[{}]", .{info.Array.len}) catch unreachable; - } - - self.write(";\n"); - } - self.write("} " ++ name ++ ";\n\n"); - } - - pub fn gen_enum( - self: *Self, - comptime name: []const u8, - comptime meta: EnumMeta, - ) void { - self.write("enum " ++ name ++ " {\n"); - - comptime var last = 0; - inline for (meta.fields, 0..) |field, i| { - self.write(" " ++ field.name); - - // if field value is unexpected/custom, manually define it - if ((i == 0 and field.value != 0) or (i > 0 and field.value > last + 1)) { - writer.print(" = {}", .{field.value}) catch unreachable; - } - - self.write(",\n"); - - last = field.value; - } - - self.write("};\n\n"); - } - - pub fn gen_union( - _: *Self, - comptime _: []const u8, - comptime _: UnionMeta, - comptime _: anytype, - ) void { - @compileError("Not implemented"); - // self.write("typedef union "); - - // self.write(name ++ " {\n"); - - // inline for (meta.fields) |field, i| { - // self.write(" "); - - // self.writeType(comptime FieldType); - - // self.write(" " ++ field.name ++ ";\n"); - // } - // self.write("} " ++ name ++ ";\n\n"); - } - - fn writeType( - self: *Self, - comptime T: type, - ) void { - const TT = comptime brk: { - var Type = T; - if (@typeInfo(Type) == .Optional) { - const OtherType = std.meta.Child(Type); - if (@typeInfo(OtherType) == .Fn) { - Type = OtherType; - } - } - if (@typeInfo(Type) == .pointer and !std.meta.isManyItemPtr(Type)) { - Type = @typeInfo(Type).pointer.child; - } - - break :brk Type; - }; - - if (comptime (isCppObject(TT)) and @hasDecl(TT, "name")) { - if (@typeInfo(T) == .pointer or (@hasDecl(TT, "Type") and (@TypeOf(TT.Type) == type and @typeInfo(TT.Type) == .pointer))) { - if (@hasDecl(TT, "is_pointer") and !TT.is_pointer) {} else if (@typeInfo(T).pointer.is_const) { - write(self, "const "); - } - } - - const _formatted_name = comptime brk: { - var original: [TT.name.len]u8 = undefined; - _ = std.mem.replace(u8, TT.name, ":", "_", &original); - break :brk original; - }; - const formatted_name = comptime _formatted_name[0..]; - - if (@hasDecl(TT, "is_pointer") and !TT.is_pointer) { - if (@TypeOf(TT.Type) == type) { - if (cTypeLabel(TT.Type)) |label| { - type_names.put(comptime label, formatted_name) catch unreachable; - if (@typeInfo(TT) == .Struct and @hasField(TT, "bytes")) { - size_map.put(comptime formatted_name, @as(u32, TT.shim.byte_size)) catch unreachable; - align_map.put(comptime formatted_name, @as(u29, TT.shim.align_size)) catch unreachable; - } else if (@typeInfo(TT) == .Opaque) { - opaque_types.insert(comptime label) catch unreachable; - } - } - } else { - type_names.put(comptime TT.name, formatted_name) catch unreachable; - if (@typeInfo(TT) == .Struct and @hasField(TT, "bytes")) { - size_map.put(comptime formatted_name, @as(u32, TT.shim.byte_size)) catch unreachable; - align_map.put(comptime formatted_name, @as(u29, TT.shim.align_size)) catch unreachable; - } else if (@typeInfo(TT) == .Opaque) { - opaque_types.insert(comptime TT.name) catch unreachable; - } - } - } else { - type_names.put(comptime TT.name, formatted_name) catch unreachable; - if (@typeInfo(TT) == .Struct and @hasField(TT, "bytes")) { - size_map.put(comptime formatted_name, @as(u32, TT.shim.byte_size)) catch unreachable; - align_map.put(comptime formatted_name, @as(u29, TT.shim.align_size)) catch unreachable; - } else if (@typeInfo(TT) == .Opaque) { - opaque_types.insert(comptime TT.name) catch unreachable; - } - } - - if (TT == T and @hasField(T, "bytes")) { - write(self, comptime "b" ++ formatted_name); - } else { - write(self, comptime formatted_name); - } - - if (@typeInfo(T) == .pointer or (@hasDecl(TT, "Type") and (@TypeOf(TT.Type) == type and @typeInfo(TT.Type) == .pointer))) { - if (@hasDecl(TT, "is_pointer") and !TT.is_pointer) {} else { - write(self, "*"); - } - } - return; - } - - if (comptime cTypeLabel(T)) |label| { - self.write(comptime label); - } else { - const meta = @typeInfo(T); - switch (meta) { - .pointer => |Pointer| { - const child = Pointer.child; - // if (childmeta == .Struct and childmeta.Struct.layout != .Extern) { - // self.write("void"); - // } else { - self.writeType(child); - // } - self.write("*"); - }, - .Optional => self.writeType(meta.Optional.child), - .Array => @compileError("Handle goofy looking C Arrays in the calling function"), - .Enum => |Enum| { - self.writeType(Enum.tag_type); - }, - else => { - return self.write(comptime typeBaseName(@typeName(T))); - }, - } - } - } - - fn write(_: *Self, comptime str: []const u8) void { - _ = writer.write(str) catch {}; - } -}; - -const builtin = @import("builtin"); -const TypeInfo = builtin.TypeInfo; -const Declaration = TypeInfo.Declaration; - -const GeneratorInterface = struct { - fn init() void {} - fn deinit() void {} - fn gen_func() void {} - fn gen_struct() void {} - fn gen_enum() void {} - fn gen_union() void {} -}; - -fn validateGenerator(comptime Generator: type) void { - comptime { - const interface = @typeInfo(GeneratorInterface).Struct.decls; - - for (interface) |decl| { - if (@hasDecl(Generator, decl.name) == false) { - @compileError("Generator: '" ++ - @typeName(Generator) ++ - "' is missing function: " ++ - decl.name); - } - } - } -} - -const NamedStruct = struct { - name: []const u8, - Type: type, -}; - -pub fn getCStruct(comptime T: type) ?NamedStruct { - if (!std.meta.isContainer(T) or - (std.meta.isSingleItemPtr(T) and - !std.meta.isContainer(std.meta.Child(T)))) - { - return null; - } - - inline for (std.meta.declarations(T)) |decl| { - if (std.mem.eql(u8, decl.name, "Type")) { - switch (decl.data) { - .Type => { - return NamedStruct{ .Type = T, .name = comptime typeBaseName(@typeName(T)) }; - }, - else => {}, - } - } - } - - return null; -} - -var thenables = std.ArrayListUnmanaged([]const u8){}; -pub fn HeaderGen(comptime first_import: type, comptime second_import: type, comptime fname: []const u8) type { - return struct { - source_file: []const u8 = fname, - gen: C_Generator = undefined, - - const Self = @This(); - - pub fn init() Self { - return Self{}; - } - - pub fn startFile( - comptime _: Self, - comptime Type: type, - comptime _: []const u8, - file: anytype, - other: std.fs.File, - ) void { - if (@hasDecl(Type, "include")) { - comptime var new_name = std.mem.zeroes([Type.include.len]u8); - - comptime { - _ = std.mem.replace(u8, Type.include, "/", "_", &new_name); - _ = std.mem.replace(u8, &new_name, ".", "_", &new_name); - _ = std.mem.replace(u8, &new_name, "<", "_", &new_name); - _ = std.mem.replace(u8, &new_name, ">", "_", &new_name); - _ = std.mem.replace(u8, &new_name, "\"", "_", &new_name); - } - file.writeAll("\n#pragma mark - " ++ Type.name ++ "\n\n") catch unreachable; - - if (@hasDecl(Type, "include")) { - other.writer().print( - \\ - \\#ifndef INCLUDED_{s} - \\#define INCLUDED_{s} - \\#include "{s}" - \\#endif - \\ - \\extern "C" const size_t {s} = sizeof({s}); - \\extern "C" const size_t {s} = alignof({s}); - \\ - , - .{ new_name, new_name, Type.include, Type.shim.size_of_symbol, Type.name, Type.shim.align_of_symbol, Type.name }, - ) catch unreachable; - } - } - } - - pub fn processStaticExport(comptime _: Self, _: anytype, gen: *C_Generator, comptime static_export: StaticExport) void { - const fn_meta = comptime @typeInfo(static_export.Type).Fn; - const DeclData = @typeInfo(@TypeOf(@field(static_export.Parent, static_export.local_name))); - - gen.gen_func( - comptime static_export.symbol_name, - DeclData.Fn, - comptime fn_meta, - comptime std.mem.zeroes([]const []const u8), - false, - ); - } - - pub fn processThenable(comptime _: Self, _: anytype, comptime static_export: StaticExport) void { - thenables.append(std.heap.c_allocator, comptime static_export.symbol_name) catch unreachable; - } - - pub fn processDecl( - comptime _: Self, - _: anytype, - gen: *C_Generator, - comptime ParentType: type, - comptime _: std.builtin.Type.Declaration, - comptime name: []const u8, - comptime prefix: []const u8, - ) void { - const DeclData = @typeInfo(@TypeOf(@field(ParentType, name))); - - switch (comptime DeclData) { - .Type => |Type| { - switch (@typeInfo(Type)) { - .Enum => |Enum| { - gen.gen_enum( - prefix ++ "__" ++ name, - Enum, - ); - }, - - .Fn => |func| { - // if (func.) { - // blocked by https://github.com/ziglang/zig/issues/8259 - gen.gen_func( - comptime prefix ++ "__" ++ name, - comptime func, - comptime func, - comptime &.{}, - false, // comptime ENABLE_REWRITE_RETURN and @typeInfo(fn_meta.return_type) == .Struct, - ); - }, - else => {}, - } - }, - .Fn => |func| { - // if (func.) { - // blocked by https://github.com/ziglang/zig/issues/8259 - gen.gen_func( - comptime prefix ++ "__" ++ name, - comptime func, - comptime func, - comptime &.{}, - comptime ENABLE_REWRITE_RETURN and @typeInfo(func.return_type) == .Struct, - ); - }, - else => {}, - } - } - - pub fn exec(comptime self: Self, file: std.fs.File, impl: std.fs.File, generated: std.fs.File) void { - const Generator = C_Generator; - validateGenerator(Generator); - var file_writer = file.writer(); - file_writer.writeAll("// clang-format off\n" ++ - \\//-- GENERATED FILE. Do not edit -- - \\// - \\// To regenerate this file, run: - \\// - \\// make headers - \\// - \\//-- GENERATED FILE. Do not edit -- - \\ - ) catch unreachable; - file.writeAll( - \\#pragma once - \\ - \\#include - \\#include - \\#include - \\ - \\#ifdef __cplusplus - \\ #define AUTO_EXTERN_C extern "C" - \\ #ifdef WIN32 - \\ #define AUTO_EXTERN_C_ZIG extern "C" - \\ #else - \\ #define AUTO_EXTERN_C_ZIG extern "C" __attribute__((weak)) - \\ #endif - \\#else - \\ #define AUTO_EXTERN_C - \\ #define AUTO_EXTERN_C_ZIG __attribute__((weak)) - \\#endif - \\#define ZIG_DECL AUTO_EXTERN_C_ZIG - \\#define CPP_DECL AUTO_EXTERN_C - \\#define CPP_SIZE AUTO_EXTERN_C - \\ - \\#ifndef __cplusplus - \\typedef void* JSClassRef; - \\#endif - \\ - \\#ifdef __cplusplus - \\#include "root.h" - \\#include - \\#endif - \\#include "headers-handwritten.h" - \\ - ) catch {}; - - impl.writer().writeAll("// clang-format off\n" ++ - \\//-- GENERATED FILE. Do not edit -- - \\// - \\// To regenerate this file, run: - \\// - \\// make headers - \\// - \\//-- GENERATED FILE. Do not edit -- - \\ - ) catch unreachable; - impl.writer().writeAll( - \\#pragma once - \\ - \\#include - \\#include - \\#include - \\ - \\#include "root.h" - \\ - ) catch {}; - - var impl_second_buffer = std.ArrayList(u8).init(std.heap.c_allocator); - var impl_second_writer = impl_second_buffer.writer(); - - var impl_third_buffer = std.ArrayList(u8).init(std.heap.c_allocator); - var impl_third_writer = impl_third_buffer.writer(); - - var impl_fourth_buffer = std.ArrayList(u8).init(std.heap.c_allocator); - var impl_fourth_writer = impl_fourth_buffer.writer(); - - // var lazy_function_definitions_writer = lazy_function_definitions_buffer.writer(); - - var dom_buffer = std.ArrayList(u8).init(std.heap.c_allocator); - var dom_writer = dom_buffer.writer(); - - // inline for (import.all_static_externs) |static_extern, i| { - // const Type = static_extern.Type; - // var gen = C_Generator.init(static_extern.name, @TypeOf(writer), writer); - // defer gen.deinit(); - - // switch (@typeInfo(Type)) { - // .Enum => |Enum| { - // gen.gen_enum( - // static_extern.name, - // Enum, - // ); - // }, - // .Union => |Union| { - // gen.gen_union(static_extern.name, Union, import.all_static_externs); - // }, - // .Struct => |Struct| { - // gen.gen_struct(static_extern.name, Struct, import.all_static_externs); - // }, - // else => {}, - // } - // } - - var to_get_sizes: usize = 0; - - const exclude_from_cpp = comptime [_][]const u8{ "ZigString", "ZigException" }; - - const TypesToCheck: []type = comptime brk: { - var all_types: [100]type = undefined; - all_types[0] = first_import; - all_types[1] = second_import; - var counter: usize = 2; - inline for (first_import.DOMCalls) |Type_| { - const Type = if (@typeInfo(@TypeOf(Type_)) == .pointer) - @typeInfo(@TypeOf(Type_)).pointer.child - else - @TypeOf(Type_); - - inline for (bun.meta.fieldNames(Type)) |static_function_name| { - const static_function = @field(Type_, static_function_name); - all_types[counter] = static_function; - counter += 1; - } - } - - break :brk all_types[0..counter]; - }; - - inline for (first_import.DOMCalls) |Type_| { - const Type = if (@typeInfo(@TypeOf(Type_)) == .pointer) - @typeInfo(@TypeOf(Type_)).pointer.child - else - @TypeOf(Type_); - - inline for (comptime bun.meta.fieldNames(Type)) |static_function_name| { - const static_function = comptime @field(Type_, static_function_name); - if (comptime @TypeOf(static_function) == type and @hasDecl(static_function, "is_dom_call")) { - dom_writer.writeAll("\n\n") catch unreachable; - static_function.printGenerateDOMJITSignature(@TypeOf(&dom_writer), &dom_writer) catch unreachable; - dom_writer.writeAll("\n\n") catch unreachable; - } - } - } - - inline for (TypesToCheck) |BaseType| { - const all_decls = comptime std.meta.declarations(BaseType); - inline for (all_decls) |_decls| { - // if (comptime _decls.is_pub) { - @setEvalBranchQuota(99999); - const Type = @field(BaseType, _decls.name); - if (@TypeOf(Type) == type) { - const TypeTypeInfo: std.builtin.Type = @typeInfo(@field(BaseType, _decls.name)); - const is_container_type = switch (TypeTypeInfo) { - .Opaque, .Struct, .Enum => true, - else => false, - }; - - if (is_container_type and (@hasDecl(Type, "Extern") or @hasDecl(Type, "Export") or @hasDecl(Type, "lazy_static_functions"))) { - const identifier = comptime std.fmt.comptimePrint("{s}_{s}", .{ Type.shim.name, Type.shim.namespace }); - if (!bufset.contains(identifier)) { - self.startFile( - Type, - Type.shim.name, - writer, - impl, - ); - - bufset.insert(identifier) catch unreachable; - - var gen = C_Generator.init(Type.name, @TypeOf(writer), writer); - defer gen.deinit(); - - if (@hasDecl(Type, "Extern")) { - if (comptime !(std.mem.eql(u8, Type.name, exclude_from_cpp[0]) or std.mem.eql(u8, Type.name, exclude_from_cpp[1]))) { - if (to_get_sizes > 0) { - impl_second_writer.writeAll(", ") catch unreachable; - impl_third_writer.writeAll(", ") catch unreachable; - impl_fourth_writer.writeAll(", ") catch unreachable; - } - } - - const formatted_name = comptime brk: { - var original: [Type.name.len]u8 = undefined; - _ = std.mem.replace(u8, Type.name, ":", "_", &original); - break :brk original; - }; - - if (comptime !(std.mem.eql(u8, Type.name, exclude_from_cpp[0]) or std.mem.eql(u8, Type.name, exclude_from_cpp[1]))) { - impl_third_writer.print("sizeof({s})", .{comptime Type.name}) catch unreachable; - impl_fourth_writer.print("alignof({s})", .{comptime Type.name}) catch unreachable; - impl_second_writer.print("\"{s}\"", .{formatted_name}) catch unreachable; - to_get_sizes += 1; - } - const ExternList = comptime brk: { - const Sorder = struct { - pub fn lessThan(_: @This(), lhs: []const u8, rhs: []const u8) bool { - return std.ascii.orderIgnoreCase(lhs, rhs) == std.math.Order.lt; - } - }; - var extern_list = Type.Extern; - std.sort.block([]const u8, &extern_list, Sorder{}, Sorder.lessThan); - break :brk extern_list; - }; - // impl_writer.print(" #include {s}\n", .{Type.include}) catch unreachable; - inline for (&ExternList) |extern_decl| { - if (@hasDecl(Type, extern_decl)) { - const normalized_name = comptime brk: { - var _normalized_name: [Type.name.len]u8 = undefined; - _ = std.mem.replace(u8, Type.name, ":", "_", &_normalized_name); - break :brk _normalized_name; - }; - - processDecl( - self, - writer, - &gen, - Type, - comptime std.meta.declarationInfo(Type, extern_decl), - comptime extern_decl, - &normalized_name, - ); - } - } - } - - if (@hasDecl(Type, "Export")) { - const ExportList = comptime brk: { - const SortContext = struct { - data: []StaticExport, - pub fn lessThan(comptime ctx: @This(), comptime lhs: usize, comptime rhs: usize) bool { - return std.ascii.orderIgnoreCase(ctx.data[lhs].symbol_name, ctx.data[rhs].symbol_name) == std.math.Order.lt; - } - pub fn swap(comptime ctx: @This(), comptime lhs: usize, comptime rhs: usize) void { - const tmp = ctx.data[lhs]; - ctx.data[lhs] = ctx.data[rhs]; - ctx.data[rhs] = tmp; - } - }; - var extern_list = Type.Export; - std.sort.insertionContext(0, extern_list.len, SortContext{ - .data = &extern_list, - }); - break :brk extern_list; - }; - - gen.direction = C_Generator.Direction.export_zig; - if (ExportList.len > 0) { - gen.write("\n#ifdef __cplusplus\n\n"); - inline for (ExportList) |static_export| { - processStaticExport( - self, - file, - &gen, - comptime static_export, - ); - } - gen.write("\n#endif\n"); - } - } - - // if (@hasDecl(Type, "lazy_static_functions")) { - // const ExportLIst = comptime brk: { - // const Sorder = struct { - // pub fn lessThan(_: @This(), comptime lhs: StaticExport, comptime rhs: StaticExport) bool { - // return std.ascii.orderIgnoreCase(lhs.symbol_name, rhs.symbol_name) == std.math.Order.lt; - // } - // }; - // var extern_list = Type.lazy_static_functions; - // std.sort.block(StaticExport, &extern_list, Sorder{}, Sorder.lessThan); - // break :brk extern_list; - // }; - - // gen.direction = C_Generator.Direction.export_zig; - // if (ExportLIst.len > 0) { - // lazy_function_definitions_writer.writeAll("\n#pragma mark ") catch unreachable; - // lazy_function_definitions_writer.writeAll(Type.shim.name) catch unreachable; - // lazy_function_definitions_writer.writeAll("\n\n") catch unreachable; - - // inline for (ExportLIst) |static_export| { - // const exp: StaticExport = static_export; - // lazy_function_definitions_writer.print(" JSC::LazyProperty m_{s};", .{exp.symbol_name}) catch unreachable; - // lazy_function_definitions_writer.writeAll("\n") catch unreachable; - - // lazy_function_definitions_writer.print( - // " Zig::JSFFIFunction* get__{s}(Zig::GlobalObject *globalObject) {{ return m_{s}.getInitializedOnMainThread(globalObject); }}", - // .{ exp.symbol_name, exp.symbol_name }, - // ) catch unreachable; - // lazy_function_definitions_writer.writeAll("\n") catch unreachable; - - // const impl_format = - // \\ - // \\ m_{s}.initLater( - // \\ [](const JSC::LazyProperty::Initializer& init) {{ - // \\ WTF::String functionName = WTF::String("{s}"_s); - // \\ Zig::JSFFIFunction* function = Zig::JSFFIFunction::create( - // \\ init.vm, - // \\ init.owner, - // \\ 1, - // \\ functionName, - // \\ {s}, - // \\ JSC::NoIntrinsic, - // \\ {s} - // \\ ); - // \\ init.set(function); - // \\ }}); - // \\ - // ; - - // lazy_functions_buffer_writer.print( - // impl_format, - // .{ - // exp.symbol_name, - // exp.local_name, - // exp.symbol_name, - // exp.symbol_name, - // }, - // ) catch unreachable; - - // lazy_function_visitor_writer.print( - // \\ this->m_{s}.visit(visitor); - // \\ - // , - // .{exp.symbol_name}, - // ) catch unreachable; - // } - // gen.write("\n"); - // } - // } - } - } - } - // } - } - } - - impl.writer().print("\nconst size_t sizes[{d}] = {{", .{to_get_sizes}) catch unreachable; - impl.writeAll(impl_third_buffer.items) catch unreachable; - impl.writeAll("};\n") catch unreachable; - impl.writer().print("\nconst char* names[{d}] = {{", .{to_get_sizes}) catch unreachable; - impl.writeAll(impl_second_buffer.items) catch unreachable; - impl.writeAll("};\n") catch unreachable; - impl.writer().print("\nconst size_t aligns[{d}] = {{", .{to_get_sizes}) catch unreachable; - impl.writeAll(impl_fourth_buffer.items) catch unreachable; - impl.writeAll("};\n") catch unreachable; - var iter = type_names.iterator(); - - generated.writer().print( - \\ #include "root.h" - \\ #include "headers.h" - \\ - \\ #include - \\ #include "DOMJITIDLConvert.h" - \\ #include "DOMJITIDLType.h" - \\ #include "DOMJITIDLTypeFilter.h" - \\ #include "DOMJITHelpers.h" - \\ #include - \\ - \\ #include "JSDOMConvertBufferSource.h" - \\ - \\ using namespace JSC; - \\ using namespace WebCore; - \\ - \\ - \\ /* -- BEGIN DOMCall DEFINITIONS -- */ - \\ {s} - \\ /* -- END DOMCall DEFINITIONS-- */ - \\ - \\ - , .{ - dom_buffer.items, - }) catch unreachable; - - const NamespaceMap = bun.StringArrayHashMap(std.BufMap); - var namespaces = NamespaceMap.init(std.heap.c_allocator); - - var size_iter = size_map.iterator(); - while (size_iter.next()) |size| { - file_writer.print(" typedef struct b{s} {{ unsigned char bytes[{d}]; }} b{s};\n", .{ - size.key_ptr.*, - // align_map.get(size.key_ptr.*).?, - size.value_ptr.*, - size.key_ptr.*, - }) catch unreachable; - - file_writer.print(" typedef char* b{s}_buf;\n", .{ - size.key_ptr.*, - }) catch unreachable; - } - - file_writer.writeAll("\n#ifndef __cplusplus\n") catch unreachable; - while (iter.next()) |entry| { - const key = entry.key_ptr.*; - const value = entry.value_ptr.*; - if (std.mem.indexOfScalar(u8, entry.key_ptr.*, ':')) |namespace_start| { - const namespace = entry.key_ptr.*[0..namespace_start]; - - if (opaque_types.contains(entry.key_ptr.*)) { - file_writer.print(" typedef struct {s} {s}; // {s}\n", .{ - value, - value, - key, - }) catch unreachable; - } else { - file_writer.print(" typedef b{s} {s}; // {s}\n", .{ - value, - value, - key, - }) catch unreachable; - } - - if (!namespaces.contains(namespace)) { - namespaces.put(namespace, std.BufMap.init(std.heap.c_allocator)) catch unreachable; - } - const class = key[namespace_start + 2 ..]; - namespaces.getPtr(namespace).?.put(class, value) catch unreachable; - } else { - file_writer.print(" typedef {s} {s};\n", .{ - key, - value, - }) catch unreachable; - - impl_writer.print(" typedef {s} {s};\n", .{ - key, - value, - }) catch unreachable; - } - } - - file_writer.writeAll("\n#endif\n") catch unreachable; - - file_writer.writeAll("\n#ifdef __cplusplus\n") catch unreachable; - - iter = type_names.iterator(); - var namespace_iter = namespaces.iterator(); - while (namespace_iter.next()) |map| { - file_writer.print(" namespace {s} {{\n", .{map.key_ptr.*}) catch unreachable; - var classes = map.value_ptr.iterator(); - while (classes.next()) |class| { - file_writer.print(" class {s};\n", .{class.key_ptr.*}) catch unreachable; - } - file_writer.writeAll(" }\n") catch unreachable; - } - - file_writer.writeAll("\n") catch unreachable; - - file_writer.writeAll(impl_buffer.items) catch unreachable; - - iter = type_names.iterator(); - namespace_iter = namespaces.iterator(); - while (namespace_iter.next()) |map| { - var classes = map.value_ptr.iterator(); - while (classes.next()) |class| { - file_writer.print(" using {s} = {s}::{s};\n", .{ - class.value_ptr.*, - map.key_ptr.*, - class.key_ptr.*, - }) catch unreachable; - } - } - - file_writer.writeAll("\n#endif\n\n") catch unreachable; - - file.writeAll(buffer.items) catch unreachable; - - // processDecls( - // self, - // file, - // import, - // "Bindings", - // ); - } - }; -} diff --git a/src/bun.js/bindings/headers-handwritten.h b/src/bun.js/bindings/headers-handwritten.h index 37f17850fb..a81d3f193c 100644 --- a/src/bun.js/bindings/headers-handwritten.h +++ b/src/bun.js/bindings/headers-handwritten.h @@ -379,7 +379,7 @@ extern "C" const char* Bun__versions_usockets; extern "C" const char* Bun__version_sha; -extern "C" void ZigString__free_global(const unsigned char* ptr, size_t len); +extern "C" void ZigString__freeGlobal(const unsigned char* ptr, size_t len); extern "C" size_t Bun__encoding__writeLatin1(const unsigned char* ptr, size_t len, unsigned char* to, size_t other_len, Encoding encoding); extern "C" size_t Bun__encoding__writeUTF16(const UChar* ptr, size_t len, unsigned char* to, size_t other_len, Encoding encoding); diff --git a/src/bun.js/bindings/headers-replacements.zig b/src/bun.js/bindings/headers-replacements.zig deleted file mode 100644 index cfe6142c88..0000000000 --- a/src/bun.js/bindings/headers-replacements.zig +++ /dev/null @@ -1,67 +0,0 @@ -const bindings = bun.JSC; -pub const struct_JSC__CallFrame = bindings.CallFrame; -pub const struct_JSC__StringPrototype = bindings.StringPrototype; -pub const struct_JSC__SetIteratorPrototype = bindings.SetIteratorPrototype; -pub const struct_JSC__RegExpPrototype = bindings.RegExpPrototype; -pub const struct_JSC__ObjectPrototype = bindings.ObjectPrototype; -pub const struct_JSC__MapIteratorPrototype = bindings.MapIteratorPrototype; -pub const struct_JSC__JSPromisePrototype = bindings.JSPromisePrototype; -pub const struct_JSC__IteratorPrototype = bindings.IteratorPrototype; -pub const struct_JSC__GeneratorPrototype = bindings.GeneratorPrototype; -pub const struct_JSC__GeneratorFunctionPrototype = bindings.GeneratorFunctionPrototype; -pub const struct_JSC__FunctionPrototype = bindings.FunctionPrototype; -pub const struct_JSC__BigIntPrototype = bindings.BigIntPrototype; -pub const struct_JSC__AsyncIteratorPrototype = bindings.AsyncIteratorPrototype; -pub const struct_JSC__AsyncGeneratorPrototype = bindings.AsyncGeneratorPrototype; -pub const struct_JSC__AsyncGeneratorFunctionPrototype = bindings.AsyncGeneratorFunctionPrototype; -pub const struct_JSC__AsyncFunctionPrototype = bindings.AsyncFunctionPrototype; -pub const struct_JSC__ArrayPrototype = bindings.ArrayPrototype; - -pub const struct_JSC__ArrayIteratorPrototype = bindings.ArrayIteratorPrototype; -pub const bWTF__URL = bindings.URL; -pub const bWTF__StringView = bindings.StringView; -pub const bWTF__StringImpl = bindings.StringImpl; -pub const bWTF__String = bindings.String; -pub const bWTF__ExternalStringImpl = bindings.ExternalStringImpl; -pub const bJSC__VM = bindings.VM; -pub const bJSC__SourceOrigin = bindings.SourceOrigin; -pub const bJSC__SourceCode = bindings.SourceCode; -pub const bJSC__PropertyName = bindings.PropertyName; -pub const bJSC__JSString = bindings.JSString; -pub const bJSC__JSPromise = bindings.JSPromise; -pub const bJSC__JSObject = bindings.JSObject; -pub const bJSC__JSModuleRecord = bindings.JSModuleRecord; -pub const bJSC__JSModuleLoader = bindings.JSModuleLoader; -pub const bJSC__JSLock = bindings.JSLock; -pub const bJSC__JSInternalPromise = bindings.JSInternalPromise; -pub const bJSC__JSGlobalObject = bindings.JSGlobalObject; -pub const bJSC__JSFunction = bindings.JSFunction; -pub const bJSC__JSCell = bindings.JSCell; -pub const bJSC__Identifier = bindings.Identifier; -pub const bJSC__Exception = bindings.Exception; -pub const bJSC__CallFrame = bindings.CallFrame; -pub const bInspector__ScriptArguments = bindings.ScriptArguments; -pub const JSC__JSValue = bindings.JSValue; - -// Inlined types -pub const ZigString = bindings.ZigString; -pub const ZigException = bindings.ZigException; -pub const ResolvedSource = bindings.ResolvedSource; -pub const ZigStackTrace = bindings.ZigStackTrace; -pub const struct_Zig__JSMicrotaskCallback = bindings.Microtask; -pub const bZig__JSMicrotaskCallback = struct_Zig__JSMicrotaskCallback; -pub const SystemError = bindings.SystemError; -const JSClassRef = bindings.C.JSClassRef; -pub const Bun__Readable = bindings.NodeReadableStream; -pub const Bun__Writable = bindings.NodeWritableStream; -pub const Bun__ArrayBuffer = bindings.ArrayBuffer; -pub const struct_WebCore__DOMURL = bindings.DOMURL; -pub const struct_WebCore__FetchHeaders = bindings.FetchHeaders; -pub const StringPointer = @import("../../api/schema.zig").Api.StringPointer; -pub const struct_VirtualMachine = bindings.VirtualMachine; -pub const ArrayBufferSink = @import("../webcore/streams.zig").ArrayBufferSink; -pub const WebSocketHTTPClient = bindings.WebSocketHTTPClient; -pub const WebSocketHTTPSClient = bindings.WebSocketHTTPSClient; -pub const WebSocketClient = bindings.WebSocketClient; -pub const WebSocketClientTLS = bindings.WebSocketClientTLS; -pub const BunString = bun.String; diff --git a/src/bun.js/bindings/helpers.h b/src/bun.js/bindings/helpers.h index 47188d9a77..3abaa526b0 100644 --- a/src/bun.js/bindings/helpers.h +++ b/src/bun.js/bindings/helpers.h @@ -72,7 +72,7 @@ static void free_global_string(void* str, void* ptr, unsigned len) if (ptr == nullptr) return; - ZigString__free_global(reinterpret_cast(ptr), len); + ZigString__freeGlobal(reinterpret_cast(ptr), len); } // Switching to AtomString doesn't yield a perf benefit because we're recreating it each time. diff --git a/src/bun.js/bindings/shimmer.zig b/src/bun.js/bindings/shimmer.zig deleted file mode 100644 index 4b306e2d01..0000000000 --- a/src/bun.js/bindings/shimmer.zig +++ /dev/null @@ -1,211 +0,0 @@ -const std = @import("std"); -const bun = @import("root").bun; -const StaticExport = @import("./static_export.zig"); -const Sizes = @import("./sizes.zig"); -const headers = @import("./headers.zig"); - -fn isNullableType(comptime Type: type) bool { - return @typeInfo(Type) == .optional or (@typeInfo(Type) == .pointer and @typeInfo(Type).pointer.is_allowzero); -} - -const log = @import("../../output.zig").scoped(.CPP, true); -pub fn Shimmer(comptime _namespace: []const u8, comptime _name: []const u8, comptime Parent: type) type { - return struct { - pub const namespace = _namespace; - pub const name = _name; - - pub fn assertJSFunction(comptime funcs: anytype) void { - inline for (funcs) |func| { - if (@typeInfo(@TypeOf(func)) != .@"fn") { - @compileError("Expected " ++ @typeName(Parent) ++ "." ++ @typeName(func) ++ " to be a function but received " ++ @tagName(@typeInfo(@TypeOf(func)))); - } - } - } - - pub fn ref() void { - if (comptime @hasDecl(Parent, "Export")) { - inline for (Parent.Export) |exp| { - _ = exp; - } - } - - if (comptime @hasDecl(Parent, "Extern")) { - inline for (Parent.Extern) |exp| { - _ = @field(Parent, exp); - } - } - } - - // fn toCppType(comptime FromType: type) type { - // var NewReturnType = FromType; - - // if (NewReturnType == anyopaque) { - // return FromType; - // } - - // var ReturnTypeInfo: std.builtin.Type = @typeInfo(FromType); - - // if (ReturnTypeInfo == .pointer and NewReturnType != *anyopaque) { - // NewReturnType = ReturnTypeInfo.pointer.child; - // ReturnTypeInfo = @typeInfo(NewReturnType); - // } - - // switch (ReturnTypeInfo) { - // .Union, - // .Struct, - // .@"enum", - // => { - // if (@hasDecl(ReturnTypeInfo., "Type")) { - // return NewReturnType; - // } - // }, - // else => {}, - // } - - // return FromType; - // } - pub const align_of_symbol = std.fmt.comptimePrint("{s}__{s}_object_align_", .{ namespace, name }); - pub const size_of_symbol = std.fmt.comptimePrint("{s}__{s}_object_size_", .{ namespace, name }); - const align_symbol = std.fmt.comptimePrint("{s}__{s}_align", .{ namespace, name }); - - pub const byte_size = brk: { - const identifier = std.fmt.comptimePrint("{s}__{s}", .{ namespace, name }); - if (@hasDecl(Sizes, identifier)) { - break :brk @field(Sizes, identifier); - } else { - break :brk 0; - } - }; - - pub const align_size = brk: { - const identifier = std.fmt.comptimePrint("{s}__{s}_align", .{ namespace, name }); - if (@hasDecl(Sizes, identifier)) { - break :brk @field(Sizes, identifier); - } else { - break :brk 0; - } - }; - pub const Bytes = if (byte_size > 16) [byte_size]u8 else std.meta.Int(.unsigned, byte_size * 8); - - pub const Return = struct { - pub const Type = Parent; - pub const is_return = true; - }; - - fn pointerChild(comptime Type: type) type { - if (@typeInfo(Type) == .pointer) { - return @typeInfo(Type).pointer.child_type; - } - - return Type; - } - - pub fn symbolName(comptime typeName: []const u8) []const u8 { - if (comptime namespace.len > 0) { - return comptime std.fmt.comptimePrint("{s}__{s}__{s}", .{ namespace, name, typeName }); - } else { - return comptime std.fmt.comptimePrint("{s}__{s}", .{ name, typeName }); - } - } - - pub fn exportFunctions(comptime Functions: anytype) [std.meta.fieldNames(@TypeOf(Functions)).len]StaticExport { - const FunctionsType = @TypeOf(Functions); - return comptime brk: { - var functions: [std.meta.fieldNames(FunctionsType).len]StaticExport = undefined; - for (std.meta.fieldNames(FunctionsType), 0..) |fn_name, i| { - const Function = @TypeOf(@field(Functions, fn_name)); - if (@typeInfo(Function) != .@"fn") { - @compileError("Expected " ++ @typeName(Parent) ++ "." ++ @typeName(Function) ++ " to be a function but received " ++ @tagName(@typeInfo(Function))); - } - const Fn: std.builtin.Type.Fn = @typeInfo(Function).@"fn"; - if (Function == bun.JSC.JSHostFunctionTypeWithCCallConvForAssertions and bun.JSC.conv != .C) { - @compileError("Expected " ++ bun.meta.typeName(Function) ++ " to have a JSC.conv Calling Convention."); - } else if (Function == bun.JSC.JSHostFunctionType) { - // - } else if (Function == bun.JSC.JSHostZigFunction) { - // - } else if (std.meta.activeTag(Fn.calling_convention) != std.meta.activeTag(std.builtin.CallingConvention.c)) { - @compileError("Expected " ++ @typeName(Parent) ++ "." ++ @typeName(Function) ++ " to have a C Calling Convention."); - } - - const export_name = symbolName(fn_name); - functions[i] = StaticExport{ - .Type = Function, - .symbol_name = export_name, - .local_name = fn_name, - .Parent = Parent, - }; - } - - break :brk functions; - }; - } - - pub fn thenables(comptime Functions: anytype) [std.meta.fieldNames(@TypeOf(Functions)).len * 2]StaticExport { - const FunctionsType = @TypeOf(Functions); - return comptime brk: { - var functions: [std.meta.fieldNames(FunctionsType).len * 2]StaticExport = undefined; - var j: usize = 0; - for (Functions) |thenable| { - for ([_][]const u8{ "resolve", "reject" }) |fn_name| { - const Function = @TypeOf(@field(thenable, fn_name)); - if (@typeInfo(Function) != .@"fn") { - @compileError("Expected " ++ @typeName(Parent) ++ "." ++ @typeName(Function) ++ " to be a function but received " ++ @tagName(@typeInfo(Function))); - } - const Fn: std.builtin.Type.@"fn" = @typeInfo(Function).@"fn"; - if (Fn.calling_convention != .C) { - @compileError("Expected " ++ @typeName(Parent) ++ "." ++ @typeName(Function) ++ " to have a C Calling Convention."); - } - - const export_name = symbolName(fn_name); - functions[j] = StaticExport{ - .Type = Function, - .symbol_name = export_name, - .local_name = fn_name, - .Parent = thenable, - }; - j += 1; - } - } - - break :brk functions; - }; - } - - pub inline fn matchNullable(comptime ExpectedReturnType: type, comptime ExternReturnType: type, value: ExternReturnType) ExpectedReturnType { - if (comptime isNullableType(ExpectedReturnType) != isNullableType(ExternReturnType)) { - return value.?; - } else if (comptime (@typeInfo(ExpectedReturnType) == .@"enum") and (@typeInfo(ExternReturnType) != .@"enum")) { - return @as(ExpectedReturnType, @enumFromInt(value)); - } else { - return value; - } - } - - pub inline fn cppFn(comptime typeName: []const u8, args: anytype) (ret: { - @setEvalBranchQuota(99999); - if (!@hasDecl(Parent, typeName)) { - @compileError(@typeName(Parent) ++ " is missing cppFn: " ++ typeName); - } - break :ret @typeInfo(@TypeOf(@field(Parent, typeName))).@"fn".return_type.?; - }) { - log(comptime name ++ "__" ++ typeName, .{}); - @setEvalBranchQuota(99999); - { - const Fn = comptime @field(headers, symbolName(typeName)); - if (@typeInfo(@TypeOf(Fn)).@"fn".params.len > 0) - return matchNullable( - comptime @typeInfo(@TypeOf(@field(Parent, typeName))).@"fn".return_type.?, - comptime @typeInfo(@TypeOf(Fn)).@"fn".return_type.?, - @call(.auto, Fn, args), - ); - - return matchNullable( - comptime @typeInfo(@TypeOf(@field(Parent, typeName))).@"fn".return_type.?, - comptime @typeInfo(@TypeOf(Fn)).@"fn".return_type.?, - Fn(), - ); - } - } - }; -} diff --git a/src/bun.js/javascript.zig b/src/bun.js/javascript.zig index d704a5a00a..9c3925912b 100644 --- a/src/bun.js/javascript.zig +++ b/src/bun.js/javascript.zig @@ -3311,13 +3311,13 @@ pub const VirtualMachine = struct { current_exception_list: ?*ExceptionList = null, formatter: *ConsoleObject.Formatter, - pub fn iteratorWithColor(_vm: [*c]VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void { - iterator(_vm, globalObject, nextValue, ctx.?, true); + pub fn iteratorWithColor(vm: *VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void { + iterator(vm, globalObject, nextValue, ctx.?, true); } - pub fn iteratorWithOutColor(_vm: [*c]VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void { - iterator(_vm, globalObject, nextValue, ctx.?, false); + pub fn iteratorWithOutColor(vm: *VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void { + iterator(vm, globalObject, nextValue, ctx.?, false); } - inline fn iterator(_: [*c]VM, _: *JSGlobalObject, nextValue: JSValue, ctx: ?*anyopaque, comptime color: bool) void { + inline fn iterator(_: *VM, _: *JSGlobalObject, nextValue: JSValue, ctx: ?*anyopaque, comptime color: bool) void { const this_ = @as(*@This(), @ptrFromInt(@intFromPtr(ctx))); VirtualMachine.get().printErrorlikeObject(nextValue, null, this_.current_exception_list, this_.formatter, Writer, this_.writer, color, allow_side_effects); } diff --git a/src/bun.js/node/path.zig b/src/bun.js/node/path.zig index 289aa383f6..a6d0231d92 100644 --- a/src/bun.js/node/path.zig +++ b/src/bun.js/node/path.zig @@ -106,11 +106,6 @@ pub fn PATH_SIZE(comptime T: type) usize { return if (T == u16) PATH_MIN_WIDE else bun.MAX_PATH_BYTES; } -const Shimmer = @import("../bindings/shimmer.zig").Shimmer; -pub const shim = Shimmer("Bun", "Path", @This()); -pub const name = "Bun__Path"; -pub const include = "Path.h"; -pub const namespace = shim.namespace; pub const sep_posix = CHAR_FORWARD_SLASH; pub const sep_windows = CHAR_BACKWARD_SLASH; pub const sep_str_posix = CHAR_STR_FORWARD_SLASH; @@ -477,10 +472,6 @@ pub fn basename(globalObject: *JSC.JSGlobalObject, isWindows: bool, args_ptr: [* return basenameJS_T(u8, globalObject, isWindows, pathZSlice.slice(), if (suffixZSlice) |_s| _s.slice() else null); } -pub fn create(globalObject: *JSC.JSGlobalObject, isWindows: bool) callconv(JSC.conv) JSC.JSValue { - return shim.cppFn("create", .{ globalObject, isWindows }); -} - /// Based on Node v21.6.1 path.posix.dirname: /// https://github.com/nodejs/node/blob/6ae20aa63de78294b18d5015481485b7cd8fbb60/lib/path.js#L1278 pub fn dirnamePosixT(comptime T: type, path: []const T) []const T { @@ -731,8 +722,8 @@ pub fn extnamePosixT(comptime T: type, path: []const T) []const T { (preDotState != null and _preDotState == 0) or // The (right-most) trimmed path component is exactly '..' (_preDotState == 1 and - _startDot == _end - 1 and - _startDot == startPart + 1)) + _startDot == _end - 1 and + _startDot == startPart + 1)) { return &.{}; } @@ -820,8 +811,8 @@ pub fn extnameWindowsT(comptime T: type, path: []const T) []const T { (preDotState != null and _preDotState == 0) or // The (right-most) trimmed path component is exactly '..' (_preDotState == 1 and - _startDot == _end - 1 and - _startDot == startPart + 1)) + _startDot == _end - 1 and + _startDot == startPart + 1)) { return &.{}; } @@ -1031,9 +1022,9 @@ pub fn isAbsoluteWindowsT(comptime T: type, path: []const T) bool { return isSepWindowsT(T, byte0) or // Possible device root (len > 2 and - isWindowsDeviceRootT(T, byte0) and - path[1] == CHAR_COLON and - isSepWindowsT(T, path[2])); + isWindowsDeviceRootT(T, byte0) and + path[1] == CHAR_COLON and + isSepWindowsT(T, path[2])); } pub fn isAbsolutePosixZigString(pathZStr: JSC.ZigString) bool { @@ -1297,9 +1288,9 @@ fn normalizeStringT(comptime T: type, path: []const T, allowAboveRoot: bool, sep const len = path.len; const isSepT = if (platform == .posix) - isSepPosixT - else - isSepWindowsT; + isSepPosixT + else + isSepWindowsT; var bufOffset: usize = 0; var bufSize: usize = 0; @@ -1777,8 +1768,8 @@ pub fn parsePosixT(comptime T: type, path: []const T) PathParsed(T) { (preDotState != null and _preDotState == 0) or // The (right-most) trimmed path component is exactly '..' (_preDotState == 1 and - _startDot == _end - 1 and - _startDot == startPart + 1)) + _startDot == _end - 1 and + _startDot == startPart + 1)) { _name = path[start.._end]; base = _name; @@ -1961,8 +1952,8 @@ pub fn parseWindowsT(comptime T: type, path: []const T) PathParsed(T) { (preDotState != null and _preDotState == 0) or // The (right-most) trimmed path component is exactly '..' (_preDotState == 1 and - _startDot == _end - 1 and - _startDot == startPart + 1)) + _startDot == _end - 1 and + _startDot == startPart + 1)) { // Prefix with _ to avoid shadowing the identifier in the outer scope. _name = path[startPart.._end]; @@ -2584,7 +2575,7 @@ pub fn resolveWindowsT(comptime T: type, paths: []const []const T, buf: []T, buf // StringPrototypeCharCodeAt(path, 2) === CHAR_BACKWARD_SLASH)) { if (envPath == null or (path[2] == CHAR_BACKWARD_SLASH and - !eqlIgnoreCaseT(T, path[0..2], resolvedDevice))) + !eqlIgnoreCaseT(T, path[0..2], resolvedDevice))) { // Translated from the following JS code: // path = `${resolvedDevice}\\`; @@ -2973,8 +2964,6 @@ pub fn toNamespacedPath(globalObject: *JSC.JSGlobalObject, isWindows: bool, args return toNamespacedPathJS_T(u8, globalObject, allocator, isWindows, pathZSlice.slice()); } -pub const Extern = [_][]const u8{"create"}; - comptime { @export(&Path.basename, .{ .name = "Bun__Path__basename" }); @export(&Path.dirname, .{ .name = "Bun__Path__dirname" }); diff --git a/src/bun.js/node/types.zig b/src/bun.js/node/types.zig index 5cea7a38df..ca139469a7 100644 --- a/src/bun.js/node/types.zig +++ b/src/bun.js/node/types.zig @@ -18,7 +18,6 @@ const Fs = @import("../../fs.zig"); const IdentityContext = @import("../../identity_context.zig").IdentityContext; const JSC = bun.JSC; const Mode = bun.Mode; -const Shimmer = @import("../bindings/shimmer.zig").Shimmer; const Syscall = bun.sys; const URL = @import("../../url.zig").URL; const Value = std.json.Value; diff --git a/src/bun.js/test/jest.zig b/src/bun.js/test/jest.zig index ba0f1df9c2..46fe23233f 100644 --- a/src/bun.js/test/jest.zig +++ b/src/bun.js/test/jest.zig @@ -788,14 +788,12 @@ pub const TestScope = struct { .{ .pass = expect.active_test_expectation_counter.actual }; } - pub const name = "TestScope"; - pub const shim = JSC.Shimmer("Bun", name, @This()); comptime { @export(&jsOnResolve, .{ - .name = shim.symbolName("onResolve"), + .name = "Bun__TestScope__onResolve", }); @export(&jsOnReject, .{ - .name = shim.symbolName("onReject"), + .name = "Bun__TestScope__onReject", }); } }; diff --git a/src/bun.js/test/pretty_format.zig b/src/bun.js/test/pretty_format.zig index 33e5ebd7df..a7975549dd 100644 --- a/src/bun.js/test/pretty_format.zig +++ b/src/bun.js/test/pretty_format.zig @@ -676,7 +676,7 @@ pub const JestPrettyFormat = struct { return struct { formatter: *JestPrettyFormat.Formatter, writer: Writer, - pub fn forEach(_: [*c]JSC.VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void { + pub fn forEach(_: *JSC.VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void { var this: *@This() = bun.cast(*@This(), ctx orelse return); if (this.formatter.failed) return; const key = JSC.JSObject.getIndex(nextValue, globalObject, 0); @@ -712,7 +712,7 @@ pub const JestPrettyFormat = struct { return struct { formatter: *JestPrettyFormat.Formatter, writer: Writer, - pub fn forEach(_: [*c]JSC.VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void { + pub fn forEach(_: *JSC.VM, globalObject: *JSGlobalObject, ctx: ?*anyopaque, nextValue: JSValue) callconv(.C) void { var this: *@This() = bun.cast(*@This(), ctx orelse return); if (this.formatter.failed) return; this.formatter.writeIndent(Writer, this.writer) catch return; diff --git a/src/bun.js/webcore/blob.zig b/src/bun.js/webcore/blob.zig index 7ae295211b..3d9a3b91ec 100644 --- a/src/bun.js/webcore/blob.zig +++ b/src/bun.js/webcore/blob.zig @@ -4100,7 +4100,6 @@ pub const Blob = struct { } }; - pub const shim = JSC.Shimmer("Bun", "FileStreamWrapper", @This()); pub fn onFileStreamResolveRequestStream(globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame) bun.JSError!JSC.JSValue { var args = callframe.arguments_old(2); var this = args.ptr[args.len - 1].asPromisePtr(FileStreamWrapper); @@ -4132,16 +4131,13 @@ pub const Blob = struct { } return .undefined; } - pub const Export = shim.exportFunctions(.{ - .onResolveRequestStream = onFileStreamResolveRequestStream, - .onRejectRequestStream = onFileStreamRejectRequestStream, - }); comptime { const jsonResolveRequestStream = JSC.toJSHostFunction(onFileStreamResolveRequestStream); - @export(&jsonResolveRequestStream, .{ .name = Export[0].symbol_name }); + @export(&jsonResolveRequestStream, .{ .name = "Bun__FileStreamWrapper__onResolveRequestStream" }); const jsonRejectRequestStream = JSC.toJSHostFunction(onFileStreamRejectRequestStream); - @export(&jsonRejectRequestStream, .{ .name = Export[1].symbol_name }); + @export(&jsonRejectRequestStream, .{ .name = "Bun__FileStreamWrapper__onRejectRequestStream" }); } + pub fn pipeReadableStreamToBlob(this: *Blob, globalThis: *JSC.JSGlobalObject, readable_stream: JSC.WebCore.ReadableStream, extra_options: ?JSValue) JSC.JSValue { var store = this.store orelse { return JSC.JSPromise.rejectedPromiseValue(globalThis, globalThis.createErrorInstance("Blob is detached", .{})); diff --git a/src/bun.js/webcore/body.zig b/src/bun.js/webcore/body.zig index 3771bbf741..b48011f7da 100644 --- a/src/bun.js/webcore/body.zig +++ b/src/bun.js/webcore/body.zig @@ -1356,7 +1356,7 @@ pub fn BodyMixin(comptime Type: type) type { if (value.* == .Locked) { if (value.Locked.action != .none or ((this_value != .zero and value.Locked.isDisturbed(Type, globalObject, this_value)) or - (this_value == .zero and value.Locked.readable.isDisturbed(globalObject)))) + (this_value == .zero and value.Locked.readable.isDisturbed(globalObject)))) { return handleBodyAlreadyUsed(globalObject); } @@ -1724,21 +1724,11 @@ pub const BodyValueBufferer = struct { } } - pub const shim = JSC.Shimmer("Bun", "BodyValueBufferer", @This()); - pub const name = "Bun__BodyValueBufferer"; - pub const include = ""; - pub const namespace = shim.namespace; - - pub const Export = shim.exportFunctions(.{ - .onResolveStream = onResolveStream, - .onRejectStream = onRejectStream, - }); - comptime { const jsonResolveStream = JSC.toJSHostFunction(onResolveStream); - @export(&jsonResolveStream, .{ .name = Export[0].symbol_name }); + @export(&jsonResolveStream, .{ .name = "Bun__BodyValueBufferer__onResolveStream" }); const jsonRejectStream = JSC.toJSHostFunction(onRejectStream); - @export(&jsonRejectStream, .{ .name = Export[1].symbol_name }); + @export(&jsonRejectStream, .{ .name = "Bun__BodyValueBufferer__onRejectStream" }); } }; diff --git a/src/bun.js/webcore/response.zig b/src/bun.js/webcore/response.zig index 0b27ce768e..49c44c04f7 100644 --- a/src/bun.js/webcore/response.zig +++ b/src/bun.js/webcore/response.zig @@ -1171,17 +1171,11 @@ pub const Fetch = struct { this.abortListener(err); return JSValue.jsUndefined(); } - pub const shim = JSC.Shimmer("Bun", "FetchTasklet", @This()); - - pub const Export = shim.exportFunctions(.{ - .onResolveRequestStream = onResolveRequestStream, - .onRejectRequestStream = onRejectRequestStream, - }); comptime { const jsonResolveRequestStream = JSC.toJSHostFunction(onResolveRequestStream); - @export(&jsonResolveRequestStream, .{ .name = Export[0].symbol_name }); + @export(&jsonResolveRequestStream, .{ .name = "Bun__FetchTasklet__onResolveRequestStream" }); const jsonRejectRequestStream = JSC.toJSHostFunction(onRejectRequestStream); - @export(&jsonRejectRequestStream, .{ .name = Export[1].symbol_name }); + @export(&jsonRejectRequestStream, .{ .name = "Bun__FetchTasklet__onRejectRequestStream" }); } pub fn startRequestStream(this: *FetchTasklet) void { diff --git a/src/bun.js/webcore/streams.zig b/src/bun.js/webcore/streams.zig index 08aeac61e9..9cbf8fe9cb 100644 --- a/src/bun.js/webcore/streams.zig +++ b/src/bun.js/webcore/streams.zig @@ -1630,9 +1630,6 @@ pub fn NewJSSink(comptime SinkType: type, comptime abi_name: []const u8) type { const ThisSink = @This(); - pub const shim = JSC.Shimmer("", abi_name, @This()); - pub const name = abi_name; - // This attaches it to JS pub const SinkSignal = extern struct { cpp: JSValue, @@ -1658,34 +1655,53 @@ pub fn NewJSSink(comptime SinkType: type, comptime abi_name: []const u8) type { return @sizeOf(ThisSink) + SinkType.memoryCost(&this.sink); } - pub fn onClose(ptr: JSValue, reason: JSValue) callconv(.C) void { - JSC.markBinding(@src()); + const AssignToStreamFn = *const fn (*JSGlobalObject, JSValue, *anyopaque, **anyopaque) callconv(.C) JSValue; + const OnCloseFn = *const fn (JSValue, JSValue) callconv(.C) void; + const OnReadyFn = *const fn (JSValue, JSValue, JSValue) callconv(.C) void; + const OnStartFn = *const fn (JSValue, *JSGlobalObject) callconv(.C) void; + const CreateObjectFn = *const fn (*JSGlobalObject, *anyopaque, usize) callconv(.C) JSValue; + const SetDestroyCallbackFn = *const fn (JSValue, usize) callconv(.C) void; + const DetachPtrFn = *const fn (JSValue) callconv(.C) void; - return shim.cppFn("onClose", .{ ptr, reason }); + const assignToStreamExtern = @extern(AssignToStreamFn, .{ .name = abi_name ++ "__assignToStream" }); + const onCloseExtern = @extern(OnCloseFn, .{ .name = abi_name ++ "__onClose" }); + const onReadyExtern = @extern(OnReadyFn, .{ .name = abi_name ++ "__onReady" }); + const onStartExtern = @extern(OnStartFn, .{ .name = abi_name ++ "__onStart" }); + const createObjectExtern = @extern(CreateObjectFn, .{ .name = abi_name ++ "__createObject" }); + const setDestroyCallbackExtern = @extern(SetDestroyCallbackFn, .{ .name = abi_name ++ "__setDestroyCallback" }); + const detachPtrExtern = @extern(DetachPtrFn, .{ .name = abi_name ++ "__detachPtr" }); + + pub fn assignToStream(globalThis: *JSGlobalObject, stream: JSValue, ptr: *anyopaque, jsvalue_ptr: **anyopaque) JSValue { + return assignToStreamExtern(globalThis, stream, ptr, jsvalue_ptr); } - pub fn onReady(ptr: JSValue, amount: JSValue, offset: JSValue) callconv(.C) void { + pub fn onClose(ptr: JSValue, reason: JSValue) void { JSC.markBinding(@src()); - - return shim.cppFn("onReady", .{ ptr, amount, offset }); + return onCloseExtern(ptr, reason); } - pub fn onStart(ptr: JSValue, globalThis: *JSGlobalObject) callconv(.C) void { + pub fn onReady(ptr: JSValue, amount: JSValue, offset: JSValue) void { JSC.markBinding(@src()); - - return shim.cppFn("onStart", .{ ptr, globalThis }); + return onReadyExtern(ptr, amount, offset); } - pub fn createObject(globalThis: *JSGlobalObject, object: *anyopaque, destructor: usize) callconv(.C) JSValue { + pub fn onStart(ptr: JSValue, globalThis: *JSGlobalObject) void { JSC.markBinding(@src()); + return onStartExtern(ptr, globalThis); + } - return shim.cppFn("createObject", .{ globalThis, object, destructor }); + pub fn createObject(globalThis: *JSGlobalObject, object: *anyopaque, destructor: usize) JSValue { + JSC.markBinding(@src()); + return createObjectExtern(globalThis, object, destructor); } pub fn setDestroyCallback(value: JSValue, callback: usize) void { JSC.markBinding(@src()); + return setDestroyCallbackExtern(value, callback); + } - return shim.cppFn("setDestroyCallback", .{ value, callback }); + pub fn detachPtr(ptr: JSValue) void { + return detachPtrExtern(ptr); } pub fn construct(globalThis: *JSGlobalObject, _: *JSC.CallFrame) bun.JSError!JSC.JSValue { @@ -1729,10 +1745,6 @@ pub fn NewJSSink(comptime SinkType: type, comptime abi_name: []const u8) type { detachPtr(value); } - pub fn detachPtr(ptr: JSValue) callconv(.C) void { - shim.cppFn("detachPtr", .{ptr}); - } - // The code generator encodes two distinct failure types using 0 and 1 const FromJSResult = enum(usize) { /// The sink has been closed and the wrapped type is freed. @@ -1972,10 +1984,6 @@ pub fn NewJSSink(comptime SinkType: type, comptime abi_name: []const u8) type { return this.sink.endFromJS(globalThis).toJS(globalThis); } - pub fn assignToStream(globalThis: *JSGlobalObject, stream: JSValue, ptr: *anyopaque, jsvalue_ptr: **anyopaque) JSValue { - return shim.cppFn("assignToStream", .{ globalThis, stream, ptr, jsvalue_ptr }); - } - pub fn updateRef(ptr: *anyopaque, value: bool) callconv(.C) void { JSC.markBinding(@src()); var this = bun.cast(*ThisSink, ptr); @@ -1998,28 +2006,18 @@ pub fn NewJSSink(comptime SinkType: type, comptime abi_name: []const u8) type { } comptime { - @export(&finalize, .{ .name = shim.symbolName("finalize") }); - @export(&jsWrite, .{ .name = shim.symbolName("write") }); - @export(&jsGetInternalFd, .{ .name = shim.symbolName("getInternalFd") }); - @export(&close, .{ .name = shim.symbolName("close") }); - @export(&jsFlush, .{ .name = shim.symbolName("flush") }); - @export(&jsStart, .{ .name = shim.symbolName("start") }); - @export(&jsEnd, .{ .name = shim.symbolName("end") }); - @export(&jsConstruct, .{ .name = shim.symbolName("construct") }); - @export(&endWithSink, .{ .name = shim.symbolName("endWithSink") }); - @export(&updateRef, .{ .name = shim.symbolName("updateRef") }); - @export(&memoryCost, .{ .name = shim.symbolName("memoryCost") }); - - shim.assertJSFunction(.{ - write, - close, - flush, - start, - end, - }); + @export(&finalize, .{ .name = abi_name ++ "__finalize" }); + @export(&jsWrite, .{ .name = abi_name ++ "__write" }); + @export(&jsGetInternalFd, .{ .name = abi_name ++ "__getInternalFd" }); + @export(&close, .{ .name = abi_name ++ "__close" }); + @export(&jsFlush, .{ .name = abi_name ++ "__flush" }); + @export(&jsStart, .{ .name = abi_name ++ "__start" }); + @export(&jsEnd, .{ .name = abi_name ++ "__end" }); + @export(&jsConstruct, .{ .name = abi_name ++ "__construct" }); + @export(&endWithSink, .{ .name = abi_name ++ "__endWithSink" }); + @export(&updateRef, .{ .name = abi_name ++ "__updateRef" }); + @export(&memoryCost, .{ .name = abi_name ++ "__memoryCost" }); } - - pub const Extern = [_][]const u8{ "createObject", "fromJS", "assignToStream", "onReady", "onClose", "detachPtr" }; }; } diff --git a/src/cli/outdated_command.zig b/src/cli/outdated_command.zig index 985de0dd5f..012cb1ea7d 100644 --- a/src/cli/outdated_command.zig +++ b/src/cli/outdated_command.zig @@ -40,12 +40,10 @@ pub const OutdatedCommand = struct { }; defer ctx.allocator.free(original_cwd); - return switch (manager.options.log_level) { - inline else => |log_level| outdated(ctx, original_cwd, manager, log_level), - }; + try outdated(ctx, original_cwd, manager); } - fn outdated(ctx: Command.Context, original_cwd: string, manager: *PackageManager, comptime log_level: PackageManager.Options.LogLevel) !void { + fn outdated(ctx: Command.Context, original_cwd: string, manager: *PackageManager) !void { const load_lockfile_result = manager.lockfile.loadFromCwd( manager, manager.allocator, @@ -55,13 +53,13 @@ pub const OutdatedCommand = struct { manager.lockfile = switch (load_lockfile_result) { .not_found => { - if (log_level != .silent) { + if (manager.options.log_level != .silent) { Output.errGeneric("missing lockfile, nothing outdated", .{}); } Global.crash(); }, .err => |cause| { - if (log_level != .silent) { + if (manager.options.log_level != .silent) { switch (cause.step) { .open_file => Output.errGeneric("failed to open lockfile: {s}", .{ @errorName(cause.value), @@ -99,14 +97,14 @@ pub const OutdatedCommand = struct { ) catch bun.outOfMemory(); defer bun.default_allocator.free(workspace_pkg_ids); - try updateManifestsIfNecessary(manager, log_level, workspace_pkg_ids); + try updateManifestsIfNecessary(manager, workspace_pkg_ids); try printOutdatedInfoTable(manager, workspace_pkg_ids, true, enable_ansi_colors); } else { // just the current workspace const root_pkg_id = manager.root_package_id.get(manager.lockfile, manager.workspace_name_hash); if (root_pkg_id == invalid_package_id) return; - try updateManifestsIfNecessary(manager, log_level, &.{root_pkg_id}); + try updateManifestsIfNecessary(manager, &.{root_pkg_id}); try printOutdatedInfoTable(manager, &.{root_pkg_id}, false, enable_ansi_colors); } }, @@ -332,13 +330,13 @@ pub const OutdatedCommand = struct { const package_name_len = package_name.len + if (dep.behavior.dev) - " (dev)".len - else if (dep.behavior.peer) - " (peer)".len - else if (dep.behavior.optional) - " (optional)".len - else - 0; + " (dev)".len + else if (dep.behavior.peer) + " (peer)".len + else if (dep.behavior.optional) + " (optional)".len + else + 0; if (package_name_len > max_name) max_name = package_name_len; @@ -521,9 +519,9 @@ pub const OutdatedCommand = struct { fn updateManifestsIfNecessary( manager: *PackageManager, - comptime log_level: PackageManager.Options.LogLevel, workspace_pkg_ids: []const PackageID, ) !void { + const log_level = manager.options.log_level; const lockfile = manager.lockfile; const resolutions = lockfile.buffers.resolutions.items; const dependencies = lockfile.buffers.dependencies.items; @@ -616,7 +614,7 @@ pub const OutdatedCommand = struct { .manifests_only = true, }, true, - log_level, + closure.manager.options.log_level, ) catch |err| { closure.err = err; return true; @@ -630,7 +628,7 @@ pub const OutdatedCommand = struct { var run_closure: RunClosure = .{ .manager = manager }; manager.sleepUntil(&run_closure, &RunClosure.isDone); - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { manager.endProgressBar(); Output.flush(); } diff --git a/src/cli/pack_command.zig b/src/cli/pack_command.zig index ccdca7f939..fc15583bcb 100644 --- a/src/cli/pack_command.zig +++ b/src/cli/pack_command.zig @@ -144,37 +144,33 @@ pub const PackCommand = struct { }, }; - switch (manager.options.log_level) { - inline else => |log_level| { - // var arena = std.heap.ArenaAllocator.init(ctx.allocator); - // defer arena.deinit(); + // var arena = std.heap.ArenaAllocator.init(ctx.allocator); + // defer arena.deinit(); - // if (manager.options.filter_patterns.len > 0) { - // // TODO: --filter - // // loop, convert, find matching workspaces, then pack each - // return; - // } + // if (manager.options.filter_patterns.len > 0) { + // // TODO: --filter + // // loop, convert, find matching workspaces, then pack each + // return; + // } - // just pack the current workspace - pack(&pack_ctx, manager.original_package_json_path, log_level, false) catch |err| { - switch (err) { - error.OutOfMemory => bun.outOfMemory(), - error.MissingPackageName, error.MissingPackageVersion => { - Output.errGeneric("package.json must have `name` and `version` fields", .{}); - Global.crash(); - }, - error.InvalidPackageName, error.InvalidPackageVersion => { - Output.errGeneric("package.json `name` and `version` fields must be non-empty strings", .{}); - Global.crash(); - }, - error.MissingPackageJSON => { - Output.errGeneric("failed to find a package.json in: \"{s}\"", .{manager.original_package_json_path}); - Global.crash(); - }, - } - }; - }, - } + // just pack the current workspace + pack(&pack_ctx, manager.original_package_json_path, false) catch |err| { + switch (err) { + error.OutOfMemory => bun.outOfMemory(), + error.MissingPackageName, error.MissingPackageVersion => { + Output.errGeneric("package.json must have `name` and `version` fields", .{}); + Global.crash(); + }, + error.InvalidPackageName, error.InvalidPackageVersion => { + Output.errGeneric("package.json `name` and `version` fields must be non-empty strings", .{}); + Global.crash(); + }, + error.MissingPackageJSON => { + Output.errGeneric("failed to find a package.json in: \"{s}\"", .{manager.original_package_json_path}); + Global.crash(); + }, + } + }; } pub fn exec(ctx: Command.Context) !void { @@ -272,7 +268,7 @@ pub const PackCommand = struct { allocator: std.mem.Allocator, includes: []const Pattern, root_dir: std.fs.Dir, - comptime log_level: LogLevel, + log_level: LogLevel, ) OOM!PackQueue { var pack_queue = PackQueue.init(allocator, {}); @@ -384,7 +380,7 @@ pub const PackCommand = struct { root_dir_info: DirInfo, pack_queue: *PackQueue, maybe_dedupe: ?*bun.StringHashMap(void), - comptime log_level: LogLevel, + log_level: LogLevel, ) OOM!void { var dirs: std.ArrayListUnmanaged(DirInfo) = .{}; defer dirs.deinit(allocator); @@ -430,7 +426,7 @@ pub const PackCommand = struct { } if (isExcluded(entry, entry_subpath, dir_depth, ignores.items)) |used_pattern_info| { - if (comptime log_level.isVerbose()) { + if (log_level.isVerbose()) { const pattern, const kind = used_pattern_info; Output.prettyln("ignore [{s}:{s}] {s}{s}", .{ @tagName(kind), @@ -503,7 +499,7 @@ pub const PackCommand = struct { fn iterateBundledDeps( ctx: *Context, root_dir: std.fs.Dir, - comptime log_level: LogLevel, + log_level: LogLevel, ) OOM!PackQueue { var bundled_pack_queue = PackQueue.init(ctx.allocator, {}); if (ctx.bundled_deps.items.len == 0) return bundled_pack_queue; @@ -643,7 +639,7 @@ pub const PackCommand = struct { bundled_pack_queue: *PackQueue, dedupe: *bun.StringHashMap(void), additional_bundled_deps: *std.ArrayListUnmanaged(DirInfo), - comptime log_level: LogLevel, + log_level: LogLevel, ) OOM!void { ctx.stats.bundled_deps += 1; @@ -737,7 +733,7 @@ pub const PackCommand = struct { } if (isExcluded(entry, entry_subpath, dir_depth, &.{})) |used_pattern_info| { - if (comptime log_level.isVerbose()) { + if (log_level.isVerbose()) { const pattern, const kind = used_pattern_info; Output.prettyln("ignore [{s}:{s}] {s}{s}", .{ @tagName(kind), @@ -773,7 +769,7 @@ pub const PackCommand = struct { fn iterateProjectTree( allocator: std.mem.Allocator, root_dir: std.fs.Dir, - comptime log_level: LogLevel, + log_level: LogLevel, ) OOM!PackQueue { var pack_queue = PackQueue.init(allocator, {}); @@ -835,7 +831,7 @@ pub const PackCommand = struct { } if (isExcluded(entry, entry_subpath, dir_depth, ignores.items)) |used_pattern_info| { - if (comptime log_level.isVerbose()) { + if (log_level.isVerbose()) { const pattern, const kind = used_pattern_info; Output.prettyln("ignore [{s}:{s}] {s}{s}", .{ @tagName(kind), @@ -1140,10 +1136,10 @@ pub const PackCommand = struct { pub fn pack( ctx: *Context, abs_package_json_path: stringZ, - comptime log_level: LogLevel, comptime for_publish: bool, ) PackError(for_publish)!if (for_publish) Publish.Context(true) else void { const manager = ctx.manager; + const log_level = manager.options.log_level; const json = switch (manager.workspace_package_json_cache.getWithPath(manager.allocator, manager.log, abs_package_json_path, .{ .guess_indentation = true, })) { @@ -1569,20 +1565,21 @@ pub const PackCommand = struct { var entry = Archive.Entry.new2(archive); { - var progress: if (log_level == .silent) void else Progress = if (comptime log_level == .silent) {} else .{}; - var node = if (comptime log_level == .silent) {} else node: { + var progress: Progress = undefined; + var node: *Progress.Node = undefined; + if (log_level.showProgress()) { + progress = .{}; progress.supports_ansi_escape_codes = Output.enable_ansi_colors; - var node: *Progress.Node = progress.start("", pack_queue.count() + bundled_pack_queue.count() + 1); + node = progress.start("", pack_queue.count() + bundled_pack_queue.count() + 1); node.unit = " files"; - break :node node; - }; - defer if (comptime log_level != .silent) node.end(); + } + defer if (log_level.showProgress()) node.end(); entry = try archivePackageJSON(ctx, archive, entry, root_dir, edited_package_json); - if (comptime log_level != .silent) node.completeOne(); + if (log_level.showProgress()) node.completeOne(); while (pack_queue.removeOrNull()) |pathname| { - defer if (comptime log_level != .silent) node.completeOne(); + defer if (log_level.showProgress()) node.completeOne(); const file = bun.sys.openat(bun.toFD(root_dir.fd), pathname, bun.O.RDONLY, 0).unwrap() catch |err| { Output.err(err, "failed to open file: \"{s}\"", .{pathname}); @@ -1618,7 +1615,7 @@ pub const PackCommand = struct { } while (bundled_pack_queue.removeOrNull()) |pathname| { - defer if (comptime log_level != .silent) node.completeOne(); + defer if (log_level.showProgress()) node.completeOne(); const file = File.openat(root_dir, pathname, bun.O.RDONLY, 0).unwrap() catch |err| { Output.err(err, "failed to open file: \"{s}\"", .{pathname}); diff --git a/src/cli/pm_trusted_command.zig b/src/cli/pm_trusted_command.zig index 762df8f752..4c25c1bd9a 100644 --- a/src/cli/pm_trusted_command.zig +++ b/src/cli/pm_trusted_command.zig @@ -339,15 +339,12 @@ pub const TrustCommand = struct { const output_in_foreground = false; const optional = false; - switch (pm.options.log_level) { - inline else => |log_level| try pm.spawnPackageLifecycleScripts( - ctx, - info.scripts_list, - optional, - log_level, - output_in_foreground, - ), - } + try pm.spawnPackageLifecycleScripts( + ctx, + info.scripts_list, + optional, + output_in_foreground, + ); if (pm.options.log_level.showProgress()) { scripts_node.activate(); diff --git a/src/cli/publish_command.zig b/src/cli/publish_command.zig index 9e0d93ff63..d6fefedc2a 100644 --- a/src/cli/publish_command.zig +++ b/src/cli/publish_command.zig @@ -320,9 +320,7 @@ pub const PublishCommand = struct { }, }; - return switch (manager.options.log_level) { - inline else => |log_level| Pack.pack(&pack_ctx, manager.original_package_json_path, log_level, true), - }; + return Pack.pack(&pack_ctx, manager.original_package_json_path, true); } }; } diff --git a/src/http/websocket_http_client.zig b/src/http/websocket_http_client.zig index 9ae8b136c6..c2dedf4d61 100644 --- a/src/http/websocket_http_client.zig +++ b/src/http/websocket_http_client.zig @@ -223,9 +223,6 @@ pub fn NewHTTPUpgradeClient(comptime ssl: bool) type { const State = enum { initializing, reading, failed }; - pub const name = if (ssl) "WebSocketHTTPSClient" else "WebSocketHTTPClient"; - - pub const shim = JSC.Shimmer("Bun", name, @This()); pub usingnamespace bun.NewRefCounted(@This(), deinit, null); const HTTPClient = @This(); @@ -705,26 +702,22 @@ pub fn NewHTTPUpgradeClient(comptime ssl: bool) type { } } - pub const Export = shim.exportFunctions(.{ - .connect = connect, - .cancel = cancel, - .register = register, - .memoryCost = memoryCost, - }); - - comptime { - @export(&connect, .{ - .name = Export[0].symbol_name, - }); - @export(&cancel, .{ - .name = Export[1].symbol_name, - }); - @export(®ister, .{ - .name = Export[2].symbol_name, - }); - @export(&memoryCost, .{ - .name = Export[3].symbol_name, - }); + pub fn exportAll() void { + comptime { + const name = if (ssl) "WebSocketHTTPSClient" else "WebSocketHTTPClient"; + @export(&connect, .{ + .name = "Bun__" ++ name ++ "__connect", + }); + @export(&cancel, .{ + .name = "Bun__" ++ name ++ "__cancel", + }); + @export(®ister, .{ + .name = "Bun__" ++ name ++ "__register", + }); + @export(&memoryCost, .{ + .name = "Bun__" ++ name ++ "__memoryCost", + }); + } } }; } @@ -1025,9 +1018,6 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { event_loop: *JSC.EventLoop = undefined, ref_count: u32 = 1, - pub const name = if (ssl) "WebSocketClientTLS" else "WebSocketClient"; - - pub const shim = JSC.Shimmer("Bun", name, @This()); const stack_frame_size = 1024; const WebSocket = @This(); @@ -1994,27 +1984,18 @@ pub fn NewWebSocketClient(comptime ssl: bool) type { // This is under-estimated a little, as we don't include usockets context. return cost; } - - pub const Export = shim.exportFunctions(.{ - .writeBinaryData = writeBinaryData, - .writeString = writeString, - .close = close, - .cancel = cancel, - .register = register, - .init = init, - .finalize = finalize, - .memoryCost = memoryCost, - }); - - comptime { - @export(&writeBinaryData, .{ .name = Export[0].symbol_name }); - @export(&writeString, .{ .name = Export[1].symbol_name }); - @export(&close, .{ .name = Export[2].symbol_name }); - @export(&cancel, .{ .name = Export[3].symbol_name }); - @export(®ister, .{ .name = Export[4].symbol_name }); - @export(&init, .{ .name = Export[5].symbol_name }); - @export(&finalize, .{ .name = Export[6].symbol_name }); - @export(&memoryCost, .{ .name = Export[7].symbol_name }); + pub fn exportAll() void { + comptime { + const name = if (ssl) "WebSocketClientTLS" else "WebSocketClient"; + @export(&cancel, .{ .name = "Bun__" ++ name ++ "__cancel" }); + @export(&close, .{ .name = "Bun__" ++ name ++ "__close" }); + @export(&finalize, .{ .name = "Bun__" ++ name ++ "__finalize" }); + @export(&init, .{ .name = "Bun__" ++ name ++ "__init" }); + @export(&memoryCost, .{ .name = "Bun__" ++ name ++ "__memoryCost" }); + @export(®ister, .{ .name = "Bun__" ++ name ++ "__register" }); + @export(&writeBinaryData, .{ .name = "Bun__" ++ name ++ "__writeBinaryData" }); + @export(&writeString, .{ .name = "Bun__" ++ name ++ "__writeString" }); + } } }; } diff --git a/src/install/install.zig b/src/install/install.zig index 8cf3d63649..f213118008 100644 --- a/src/install/install.zig +++ b/src/install/install.zig @@ -2820,7 +2820,8 @@ pub const PackageManager = struct { } }; - pub fn reportSlowLifecycleScripts(this: *PackageManager, log_level: Options.LogLevel) void { + pub fn reportSlowLifecycleScripts(this: *PackageManager) void { + const log_level = this.options.log_level; if (log_level == .silent) return; if (bun.getRuntimeFeatureFlag("BUN_DISABLE_SLOW_LIFECYCLE_SCRIPT_LOGGING")) { return; @@ -3213,7 +3214,7 @@ pub const PackageManager = struct { } fn hasNoMorePendingLifecycleScripts(this: *PackageManager) bool { - this.reportSlowLifecycleScripts(this.options.log_level); + this.reportSlowLifecycleScripts(); return this.pending_lifecycle_script_tasks.load(.monotonic) == 0; } @@ -3227,7 +3228,7 @@ pub const PackageManager = struct { } pub fn sleep(this: *PackageManager) void { - this.reportSlowLifecycleScripts(this.options.log_level); + this.reportSlowLifecycleScripts(); Output.flush(); this.event_loop.tick(this, hasNoMorePendingLifecycleScripts); } @@ -3291,60 +3292,56 @@ pub const PackageManager = struct { invalid_package_id => brk: { this.drainDependencyList(); - switch (this.options.log_level) { - inline else => |log_levela| { - const Closure = struct { - // https://github.com/ziglang/zig/issues/19586 - pub fn issue_19586_workaround(comptime log_level: Options.LogLevel) type { - return struct { - err: ?anyerror = null, - manager: *PackageManager, - pub fn isDone(closure: *@This()) bool { - const manager = closure.manager; - if (manager.pendingTaskCount() > 0) { - manager.runTasks( - void, - {}, - .{ - .onExtract = {}, - .onResolve = {}, - .onPackageManifestError = {}, - .onPackageDownloadError = {}, - }, - false, - log_level, - ) catch |err| { - closure.err = err; - return true; - }; + const Closure = struct { + // https://github.com/ziglang/zig/issues/19586 + pub fn issue_19586_workaround() type { + return struct { + err: ?anyerror = null, + manager: *PackageManager, + pub fn isDone(closure: *@This()) bool { + const manager = closure.manager; + if (manager.pendingTaskCount() > 0) { + manager.runTasks( + void, + {}, + .{ + .onExtract = {}, + .onResolve = {}, + .onPackageManifestError = {}, + .onPackageDownloadError = {}, + }, + false, + manager.options.log_level, + ) catch |err| { + closure.err = err; + return true; + }; - if (PackageManager.verbose_install and manager.pendingTaskCount() > 0) { - if (PackageManager.hasEnoughTimePassedBetweenWaitingMessages()) Output.prettyErrorln("[PackageManager] waiting for {d} tasks\n", .{closure.manager.pendingTaskCount()}); - } - } - - return manager.pendingTaskCount() == 0; + if (PackageManager.verbose_install and manager.pendingTaskCount() > 0) { + if (PackageManager.hasEnoughTimePassedBetweenWaitingMessages()) Output.prettyErrorln("[PackageManager] waiting for {d} tasks\n", .{closure.manager.pendingTaskCount()}); } - }; + } + + return manager.pendingTaskCount() == 0; } - }.issue_19586_workaround(log_levela); + }; + } + }.issue_19586_workaround(); - if (comptime log_levela.showProgress()) { - this.startProgressBarIfNone(); - } + if (this.options.log_level.showProgress()) { + this.startProgressBarIfNone(); + } - var closure = Closure{ .manager = this }; - this.sleepUntil(&closure, &Closure.isDone); + var closure = Closure{ .manager = this }; + this.sleepUntil(&closure, &Closure.isDone); - if (comptime log_levela.showProgress()) { - this.endProgressBar(); - Output.flush(); - } + if (this.options.log_level.showProgress()) { + this.endProgressBar(); + Output.flush(); + } - if (closure.err) |err| { - return .{ .failure = err }; - } - }, + if (closure.err) |err| { + return .{ .failure = err }; } break :brk this.lockfile.buffers.resolutions.items[dep_id]; @@ -6104,7 +6101,7 @@ pub const PackageManager = struct { dep_id: DependencyID, resolution: *const Resolution, data: *const ExtractData, - comptime log_level: Options.LogLevel, + log_level: Options.LogLevel, ) ?Lockfile.Package { switch (resolution.tag) { .git, .github => { @@ -6132,7 +6129,7 @@ pub const PackageManager = struct { &resolver, Features.npm, ) catch |err| { - if (comptime log_level != .silent) { + if (log_level != .silent) { const string_buf = manager.lockfile.buffers.string_bytes.items; Output.err(err, "failed to parse package.json for {}", .{ resolution.fmtURL(string_buf), @@ -6216,7 +6213,7 @@ pub const PackageManager = struct { &resolver, Features.npm, ) catch |err| { - if (comptime log_level != .silent) { + if (log_level != .silent) { const string_buf = manager.lockfile.buffers.string_bytes.items; Output.prettyErrorln("error: expected package.json in {any} to be a JSON file: {s}\n", .{ resolution.fmtURL(string_buf), @@ -6260,7 +6257,7 @@ pub const PackageManager = struct { manager.log, manager.allocator, ) catch |err| { - if (comptime log_level != .silent) { + if (log_level != .silent) { const string_buf = manager.lockfile.buffers.string_bytes.items; Output.prettyErrorln("error: expected package.json in {any} to be a JSON file: {s}\n", .{ resolution.fmtURL(string_buf), @@ -6319,7 +6316,7 @@ pub const PackageManager = struct { extract_ctx: ExtractCompletionContext, comptime callbacks: anytype, install_peer: bool, - comptime log_level: Options.LogLevel, + log_level: Options.LogLevel, ) anyerror!void { var has_updated_this_run = false; var has_network_error = false; @@ -6329,7 +6326,7 @@ pub const PackageManager = struct { defer { manager.drainDependencyList(); - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { manager.startProgressBarIfNone(); if (@hasField(@TypeOf(callbacks), "progress_bar") and callbacks.progress_bar == true) { @@ -6394,7 +6391,7 @@ pub const PackageManager = struct { switch (task.callback) { .package_manifest => |*manifest_req| { const name = manifest_req.name; - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { if (!has_updated_this_run) { manager.setNodeName(manager.downloads_node.?, name.slice(), ProgressStrings.download_emoji, true); has_updated_this_run = true; @@ -6532,7 +6529,7 @@ pub const PackageManager = struct { continue; } - if (comptime log_level.isVerbose()) { + if (log_level.isVerbose()) { Output.prettyError(" ", .{}); Output.printElapsed(@as(f64, @floatFromInt(task.unsafe_http_client.elapsed)) / std.time.ns_per_ms); Output.prettyError("\nDownloaded {s} versions\n", .{name.slice()}); @@ -6737,14 +6734,14 @@ pub const PackageManager = struct { continue; } - if (comptime log_level.isVerbose()) { + if (log_level.isVerbose()) { Output.prettyError(" ", .{}); Output.printElapsed(@as(f64, @floatCast(@as(f64, @floatFromInt(task.unsafe_http_client.elapsed)) / std.time.ns_per_ms))); Output.prettyError(" Downloaded {s} tarball\n", .{extract.name.slice()}); Output.flush(); } - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { if (!has_updated_this_run) { manager.setNodeName(manager.downloads_node.?, extract.name.slice(), ProgressStrings.extract_emoji, true); has_updated_this_run = true; @@ -6811,7 +6808,7 @@ pub const PackageManager = struct { try manager.processDependencyList(dependency_list, ExtractCompletionContext, extract_ctx, callbacks, install_peer); - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { if (!has_updated_this_run) { manager.setNodeName(manager.downloads_node.?, manifest.name(), ProgressStrings.download_emoji, true); has_updated_this_run = true; @@ -6937,10 +6934,10 @@ pub const PackageManager = struct { if (comptime @TypeOf(callbacks.onExtract) != void and ExtractCompletionContext != *PackageInstaller) { // handled *PackageInstaller above - callbacks.onExtract(extract_ctx, dependency_id, &task.data.extract, comptime log_level); + callbacks.onExtract(extract_ctx, dependency_id, &task.data.extract, log_level); } - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { if (!has_updated_this_run) { manager.setNodeName(manager.downloads_node.?, alias, ProgressStrings.extract_emoji, true); has_updated_this_run = true; @@ -6965,7 +6962,7 @@ pub const PackageManager = struct { err, url, ); - } else if (comptime log_level != .silent) { + } else if (log_level != .silent) { manager.log.addErrorFmt( null, logger.Loc.Empty, @@ -7024,7 +7021,7 @@ pub const PackageManager = struct { try manager.processDependencyList(dependency_list, ExtractCompletionContext, extract_ctx, callbacks, install_peer); } - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { if (!has_updated_this_run) { manager.setNodeName(manager.downloads_node.?, name, ProgressStrings.download_emoji, true); has_updated_this_run = true; @@ -7109,12 +7106,12 @@ pub const PackageManager = struct { extract_ctx, git_checkout.dependency_id, &task.data.git_checkout, - comptime log_level, + log_level, ); } } - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { if (!has_updated_this_run) { manager.setNodeName(manager.downloads_node.?, alias.slice(), ProgressStrings.download_emoji, true); has_updated_this_run = true; @@ -9458,9 +9455,7 @@ pub const PackageManager = struct { Global.exit(0); } else { // bun link lodash - switch (manager.options.log_level) { - inline else => |log_level| try manager.updatePackageJSONAndInstallWithManager(ctx, original_cwd, log_level), - } + try manager.updatePackageJSONAndInstallWithManager(ctx, original_cwd); } } @@ -10641,9 +10636,7 @@ pub const PackageManager = struct { } } - switch (manager.options.log_level) { - inline else => |log_level| try manager.updatePackageJSONAndInstallWithManager(ctx, original_cwd, log_level), - } + try manager.updatePackageJSONAndInstallWithManager(ctx, original_cwd); if (manager.options.patch_features == .patch) { try manager.preparePatch(); @@ -10774,7 +10767,6 @@ pub const PackageManager = struct { manager: *PackageManager, ctx: Command.Context, original_cwd: string, - comptime log_level: Options.LogLevel, ) !void { var update_requests = UpdateRequest.Array.initCapacity(manager.allocator, 64) catch bun.outOfMemory(); defer update_requests.deinit(manager.allocator); @@ -10805,7 +10797,6 @@ pub const PackageManager = struct { original_cwd, manager.options.positionals[1..], &update_requests, - log_level, ); } @@ -10815,7 +10806,6 @@ pub const PackageManager = struct { original_cwd: string, positionals: []const string, update_requests: *UpdateRequest.Array, - comptime log_level: Options.LogLevel, ) !void { var updates: []UpdateRequest = if (manager.subcommand == .@"patch-commit" or manager.subcommand == .patch) &[_]UpdateRequest{} @@ -10826,7 +10816,6 @@ pub const PackageManager = struct { &updates, manager.subcommand, original_cwd, - log_level, ); } fn updatePackageJSONAndInstallWithManagerWithUpdates( @@ -10835,10 +10824,10 @@ pub const PackageManager = struct { updates: *[]UpdateRequest, subcommand: Subcommand, original_cwd: string, - comptime log_level: Options.LogLevel, ) !void { + const log_level = manager.options.log_level; if (manager.log.errors > 0) { - if (comptime log_level != .silent) { + if (log_level != .silent) { manager.log.print(Output.errorWriter()) catch {}; } Global.crash(); @@ -11109,7 +11098,7 @@ pub const PackageManager = struct { break :brk .{ root_package_json.source.contents, root_package_json_path_buf[0..root_package_json_path.len :0] }; }; - try manager.installWithManager(ctx, root_package_json_source, original_cwd, log_level); + try manager.installWithManager(ctx, root_package_json_source, original_cwd); if (subcommand == .update or subcommand == .add or subcommand == .link) { for (updates.*) |request| { @@ -11810,7 +11799,7 @@ pub const PackageManager = struct { fn doPatchCommit( manager: *PackageManager, pathbuf: *bun.PathBuffer, - comptime log_level: Options.LogLevel, + log_level: Options.LogLevel, ) !?PatchCommitResult { var folder_path_buf: bun.PathBuffer = undefined; var lockfile: *Lockfile = try manager.allocator.create(Lockfile); @@ -12395,9 +12384,7 @@ pub const PackageManager = struct { Output.prettyln("bun add v" ++ Global.package_json_version_with_sha ++ "\n", .{}); Output.flush(); } - return switch (manager.options.log_level) { - inline else => |log_level| manager.updatePackageJSONAndInstallWithManager(ctx, original_cwd, log_level), - }; + return manager.updatePackageJSONAndInstallWithManager(ctx, original_cwd); } if (manager.options.shouldPrintCommandName()) { @@ -12413,9 +12400,7 @@ pub const PackageManager = struct { return; }; - try switch (manager.options.log_level) { - inline else => |log_level| manager.installWithManager(ctx, package_json_contents, original_cwd, log_level), - }; + try manager.installWithManager(ctx, package_json_contents, original_cwd); if (manager.any_failed_to_install) { Global.exit(1); @@ -12636,7 +12621,7 @@ pub const PackageManager = struct { tree_id: Lockfile.Tree.Id, maybe_destination_dir: ?*LazyPackageDestinationDir, comptime should_install_packages: bool, - comptime log_level: Options.LogLevel, + log_level: Options.LogLevel, ) void { if (comptime Environment.allow_assert) { bun.assertWithLocation(tree_id != Lockfile.Tree.invalid_id, @src()); @@ -12753,7 +12738,7 @@ pub const PackageManager = struct { } } - pub fn linkRemainingBins(this: *PackageInstaller, comptime log_level: Options.LogLevel) void { + pub fn linkRemainingBins(this: *PackageInstaller, log_level: Options.LogLevel) void { var depth_buf: Lockfile.Tree.DepthBuf = undefined; var node_modules_rel_path_buf: bun.PathBuffer = undefined; @memcpy(node_modules_rel_path_buf[0.."node_modules".len], "node_modules"); @@ -12793,7 +12778,7 @@ pub const PackageManager = struct { } } - pub fn runAvailableScripts(this: *PackageInstaller, comptime log_level: Options.LogLevel) void { + pub fn runAvailableScripts(this: *PackageInstaller, log_level: Options.LogLevel) void { var i: usize = this.pending_lifecycle_scripts.items.len; while (i > 0) { i -= 1; @@ -12808,14 +12793,13 @@ pub const PackageManager = struct { this.command_ctx, entry.list, optional, - log_level, output_in_foreground, ) catch |err| { - if (comptime log_level != .silent) { + if (log_level != .silent) { const fmt = "\nerror: failed to spawn life-cycle scripts for {s}: {s}\n"; const args = .{ name, @errorName(err) }; - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { switch (Output.enable_ansi_colors) { inline else => |enable_ansi_colors| { this.progress.log(comptime Output.prettyFmt(fmt, enable_ansi_colors), args); @@ -12837,7 +12821,7 @@ pub const PackageManager = struct { } } - pub fn installAvailablePackages(this: *PackageInstaller, comptime log_level: Options.LogLevel, comptime force: bool) void { + pub fn installAvailablePackages(this: *PackageInstaller, log_level: Options.LogLevel, comptime force: bool) void { const prev_node_modules = this.node_modules; defer this.node_modules = prev_node_modules; const prev_tree_id = this.current_tree_id; @@ -12882,7 +12866,7 @@ pub const PackageManager = struct { } } - pub fn completeRemainingScripts(this: *PackageInstaller, comptime log_level: Options.LogLevel) void { + pub fn completeRemainingScripts(this: *PackageInstaller, log_level: Options.LogLevel) void { for (this.pending_lifecycle_scripts.items) |entry| { const package_name = entry.list.package_name; while (LifecycleScriptSubprocess.alive_count.load(.monotonic) >= this.manager.options.max_concurrent_lifecycle_scripts) { @@ -12891,12 +12875,12 @@ pub const PackageManager = struct { const optional = entry.optional; const output_in_foreground = false; - this.manager.spawnPackageLifecycleScripts(this.command_ctx, entry.list, optional, log_level, output_in_foreground) catch |err| { - if (comptime log_level != .silent) { + this.manager.spawnPackageLifecycleScripts(this.command_ctx, entry.list, optional, output_in_foreground) catch |err| { + if (log_level != .silent) { const fmt = "\nerror: failed to spawn life-cycle scripts for {s}: {s}\n"; const args = .{ package_name, @errorName(err) }; - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { switch (Output.enable_ansi_colors) { inline else => |enable_ansi_colors| { this.progress.log(comptime Output.prettyFmt(fmt, enable_ansi_colors), args); @@ -12917,9 +12901,9 @@ pub const PackageManager = struct { } while (this.manager.pending_lifecycle_script_tasks.load(.monotonic) > 0) { - this.manager.reportSlowLifecycleScripts(log_level); + this.manager.reportSlowLifecycleScripts(); - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { if (this.manager.scripts_node) |scripts_node| { scripts_node.activate(); this.manager.progress.refresh(); @@ -12989,7 +12973,7 @@ pub const PackageManager = struct { this: *PackageInstaller, dependency_id: DependencyID, data: *const ExtractData, - comptime log_level: Options.LogLevel, + log_level: Options.LogLevel, ) void { const package_id = this.lockfile.buffers.resolutions.items[dependency_id]; const name = this.names[package_id]; @@ -13018,7 +13002,7 @@ pub const PackageManager = struct { this: *PackageInstaller, name: String, task_id: Task.Id.Type, - comptime log_level: Options.LogLevel, + log_level: Options.LogLevel, ) bool { if (this.manager.task_queue.fetchRemove(task_id)) |removed| { var callbacks = removed.value; @@ -13068,7 +13052,7 @@ pub const PackageManager = struct { package_id: PackageID, resolution_tag: Resolution.Tag, node_modules_folder: *LazyPackageDestinationDir, - comptime log_level: Options.LogLevel, + log_level: Options.LogLevel, ) usize { if (comptime Environment.allow_assert) { bun.assertWithLocation(resolution_tag != .root, @src()); @@ -13092,7 +13076,7 @@ pub const PackageManager = struct { node_modules_folder, alias, ) catch |err| { - if (comptime log_level != .silent) { + if (log_level != .silent) { Output.errGeneric("failed to fill lifecycle scripts for {s}: {s}", .{ alias, @errorName(err), @@ -13153,7 +13137,7 @@ pub const PackageManager = struct { this: *PackageInstaller, dependency_id: DependencyID, package_id: PackageID, - comptime log_level: Options.LogLevel, + log_level: Options.LogLevel, pkg_name: String, resolution: *const Resolution, @@ -13311,11 +13295,11 @@ pub const PackageManager = struct { }, .symlink => { const directory = this.manager.globalLinkDir() catch |err| { - if (comptime log_level != .silent) { + if (log_level != .silent) { const fmt = "\nerror: unable to access global directory while installing {s}: {s}\n"; const args = .{ pkg_name.slice(this.lockfile.buffers.string_bytes.items), @errorName(err) }; - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { switch (Output.enable_ansi_colors) { inline else => |enable_ansi_colors| { this.progress.log(comptime Output.prettyFmt(fmt, enable_ansi_colors), args); @@ -13561,7 +13545,7 @@ pub const PackageManager = struct { this.summary.success += @as(u32, @intFromBool(!is_duplicate)); this.successfully_installed.set(package_id); - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { this.node.completeOne(); } @@ -13613,7 +13597,7 @@ pub const PackageManager = struct { log_level, ); if (count > 0) { - if (comptime log_level.isVerbose()) { + if (log_level.isVerbose()) { Output.prettyError("Blocked {d} scripts for: {s}@{}\n", .{ count, alias.slice(this.lockfile.buffers.string_bytes.items), @@ -13770,7 +13754,7 @@ pub const PackageManager = struct { this: *PackageInstaller, pkg_has_patch: bool, comptime is_pending_package_install: bool, - comptime log_level: Options.LogLevel, + log_level: Options.LogLevel, ) void { this.summary.fail += 1; if (!pkg_has_patch) this.incrementTreeInstallCount(this.current_tree_id, null, !is_pending_package_install, log_level); @@ -13780,7 +13764,7 @@ pub const PackageManager = struct { fn enqueueLifecycleScripts( this: *PackageInstaller, folder_name: string, - comptime log_level: Options.LogLevel, + log_level: Options.LogLevel, node_modules_folder: *LazyPackageDestinationDir, package_id: PackageID, optional: bool, @@ -13795,11 +13779,11 @@ pub const PackageManager = struct { folder_name, resolution, ) catch |err| { - if (comptime log_level != .silent) { + if (log_level != .silent) { const fmt = "\nerror: failed to enqueue lifecycle scripts for {s}: {s}\n"; const args = .{ folder_name, @errorName(err) }; - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { switch (Output.enable_ansi_colors) { inline else => |enable_ansi_colors| { this.progress.log(comptime Output.prettyFmt(fmt, enable_ansi_colors), args); @@ -13847,7 +13831,7 @@ pub const PackageManager = struct { pub fn installPackage( this: *PackageInstaller, dep_id: DependencyID, - comptime log_level: Options.LogLevel, + log_level: Options.LogLevel, ) void { const package_id = this.lockfile.buffers.resolutions.items[dep_id]; @@ -14058,7 +14042,7 @@ pub const PackageManager = struct { ctx: Command.Context, workspace_filters: []const WorkspaceFilter, install_root_dependencies: bool, - comptime log_level: PackageManager.Options.LogLevel, + log_level: PackageManager.Options.LogLevel, ) !PackageInstall.Summary { const original_trees = this.lockfile.buffers.trees; const original_tree_dep_ids = this.lockfile.buffers.hoisted_dependencies; @@ -14077,7 +14061,7 @@ pub const PackageManager = struct { const options = &this.options; var progress = &this.progress; - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { progress.supports_ansi_escape_codes = Output.enable_ansi_colors_stderr; root_node = progress.start("", 0); download_node = root_node.start(ProgressStrings.download(), 0); @@ -14089,7 +14073,7 @@ pub const PackageManager = struct { } defer { - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { progress.root.end(); progress.* = .{}; } @@ -14297,7 +14281,7 @@ pub const PackageManager = struct { while (remaining.len > unroll_count) { comptime var i: usize = 0; inline while (i < unroll_count) : (i += 1) { - installer.installPackage(remaining[i], comptime log_level); + installer.installPackage(remaining[i], log_level); } remaining = remaining[unroll_count..]; @@ -14320,7 +14304,7 @@ pub const PackageManager = struct { if (!installer.options.do.install_packages) return error.InstallFailed; } this.tickLifecycleScripts(); - this.reportSlowLifecycleScripts(log_level); + this.reportSlowLifecycleScripts(); } for (remaining) |dependency_id| { @@ -14343,7 +14327,7 @@ pub const PackageManager = struct { if (!installer.options.do.install_packages) return error.InstallFailed; this.tickLifecycleScripts(); - this.reportSlowLifecycleScripts(log_level); + this.reportSlowLifecycleScripts(); } while (this.pendingTaskCount() > 0 and installer.options.do.install_packages) { @@ -14353,6 +14337,7 @@ pub const PackageManager = struct { manager: *PackageManager, pub fn isDone(closure: *@This()) bool { + const pm = closure.manager; closure.manager.runTasks( *PackageInstaller, closure.installer, @@ -14364,7 +14349,7 @@ pub const PackageManager = struct { .onPackageDownloadError = {}, }, true, - log_level, + pm.options.log_level, ) catch |err| { closure.err = err; }; @@ -14373,7 +14358,7 @@ pub const PackageManager = struct { return true; } - closure.manager.reportSlowLifecycleScripts(log_level); + closure.manager.reportSlowLifecycleScripts(); if (PackageManager.verbose_install and closure.manager.pendingTaskCount() > 0) { const pending_task_count = closure.manager.pendingTaskCount(); @@ -14401,7 +14386,7 @@ pub const PackageManager = struct { } } else { this.tickLifecycleScripts(); - this.reportSlowLifecycleScripts(log_level); + this.reportSlowLifecycleScripts(); } for (installer.trees) |tree| { @@ -14413,7 +14398,7 @@ pub const PackageManager = struct { } this.finished_installing.store(true, .monotonic); - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { scripts_node.activate(); } @@ -14427,12 +14412,12 @@ pub const PackageManager = struct { installer.completeRemainingScripts(log_level); while (this.pending_lifecycle_script_tasks.load(.monotonic) > 0) { - this.reportSlowLifecycleScripts(log_level); + this.reportSlowLifecycleScripts(); this.sleep(); } - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { scripts_node.end(); } } @@ -14529,8 +14514,8 @@ pub const PackageManager = struct { ctx: Command.Context, root_package_json_contents: string, original_cwd: string, - comptime log_level: Options.LogLevel, ) !void { + const log_level = manager.options.log_level; // Start resolving DNS for the default registry immediately. if (manager.options.scope.url.hostname.len > 0) { @@ -14980,7 +14965,7 @@ pub const PackageManager = struct { .progress_bar = true, }, check_peers, - log_level, + this.options.log_level, ) catch |err| { closure.err = err; return true; @@ -15035,9 +15020,9 @@ pub const PackageManager = struct { try waitForPeers(manager); - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { manager.endProgressBar(); - } else if (comptime log_level != .silent) { + } else if (log_level != .silent) { Output.prettyErrorln("Resolved, downloaded and extracted [{d}]", .{manager.total_tasks}); Output.flush(); } @@ -15153,7 +15138,7 @@ pub const PackageManager = struct { } } - if (comptime log_level != .silent) { + if (log_level != .silent) { Output.prettyErrorln("error: lockfile had changes, but lockfile is frozen", .{}); Output.note("try re-running without --frozen-lockfile and commit the updated lockfile", .{}); } @@ -15250,7 +15235,7 @@ pub const PackageManager = struct { ); } - if (comptime log_level != .silent) { + if (log_level != .silent) { try manager.log.print(Output.errorWriter()); } if (had_errors_before_cleaning_lockfile or manager.log.hasErrors()) Global.crash(); @@ -15293,17 +15278,17 @@ pub const PackageManager = struct { if (manager.options.do.save_yarn_lock) { var node: *Progress.Node = undefined; - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { manager.progress.supports_ansi_escape_codes = Output.enable_ansi_colors_stderr; node = manager.progress.start("Saving yarn.lock", 0); manager.progress.refresh(); - } else if (comptime log_level != .silent) { + } else if (log_level != .silent) { Output.prettyErrorln("Saved yarn.lock", .{}); Output.flush(); } try manager.writeYarnLock(); - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { node.completeOne(); manager.progress.refresh(); manager.progress.root.end(); @@ -15317,7 +15302,7 @@ pub const PackageManager = struct { bun.assert(scripts.total > 0); } - if (comptime log_level != .silent) { + if (log_level != .silent) { Output.printError("\n", .{}); Output.flush(); } @@ -15325,17 +15310,17 @@ pub const PackageManager = struct { // have finished, and lockfiles have been saved const optional = false; const output_in_foreground = true; - try manager.spawnPackageLifecycleScripts(ctx, scripts, optional, log_level, output_in_foreground); + try manager.spawnPackageLifecycleScripts(ctx, scripts, optional, output_in_foreground); while (manager.pending_lifecycle_script_tasks.load(.monotonic) > 0) { - manager.reportSlowLifecycleScripts(log_level); + manager.reportSlowLifecycleScripts(); manager.sleep(); } } } - if (comptime log_level != .silent) { + if (log_level != .silent) { try manager.printInstallSummary(ctx, &install_summary, did_meta_hash_change, log_level); } @@ -15351,7 +15336,7 @@ pub const PackageManager = struct { ctx: Command.Context, install_summary: *const PackageInstall.Summary, did_meta_hash_change: bool, - comptime log_level: Options.LogLevel, + log_level: Options.LogLevel, ) !void { var printed_timestamp = false; if (this.options.do.summary) { @@ -15554,7 +15539,7 @@ pub const PackageManager = struct { } } - pub fn verifyResolutions(this: *PackageManager, comptime log_level: PackageManager.Options.LogLevel) void { + pub fn verifyResolutions(this: *PackageManager, log_level: PackageManager.Options.LogLevel) void { const lockfile = this.lockfile; const resolutions_lists: []const Lockfile.DependencyIDSlice = lockfile.packages.items(.resolutions); const dependency_lists: []const Lockfile.DependencySlice = lockfile.packages.items(.dependencies); @@ -15606,9 +15591,9 @@ pub const PackageManager = struct { ctx: Command.Context, list: Lockfile.Package.Scripts.List, optional: bool, - comptime log_level: PackageManager.Options.LogLevel, - comptime foreground: bool, + foreground: bool, ) !void { + const log_level = this.options.log_level; var any_scripts = false; for (list.items) |maybe_item| { if (maybe_item != null) { diff --git a/src/install/lifecycle_script_runner.zig b/src/install/lifecycle_script_runner.zig index 0ba772b9df..6c56425b40 100644 --- a/src/install/lifecycle_script_runner.zig +++ b/src/install/lifecycle_script_runner.zig @@ -485,8 +485,8 @@ pub const LifecycleScriptSubprocess = struct { list: Lockfile.Package.Scripts.List, envp: [:null]?[*:0]const u8, optional: bool, - comptime log_level: PackageManager.Options.LogLevel, - comptime foreground: bool, + log_level: PackageManager.Options.LogLevel, + foreground: bool, ) !void { var lifecycle_subprocess = LifecycleScriptSubprocess.new(.{ .manager = manager, @@ -497,7 +497,7 @@ pub const LifecycleScriptSubprocess = struct { .optional = optional, }); - if (comptime log_level.isVerbose()) { + if (log_level.isVerbose()) { Output.prettyErrorln("[Scripts] Starting scripts for \"{s}\"", .{ list.package_name, }); diff --git a/src/install/lockfile.zig b/src/install/lockfile.zig index b344c12518..02b75d3e43 100644 --- a/src/install/lockfile.zig +++ b/src/install/lockfile.zig @@ -1148,7 +1148,7 @@ pub fn maybeCloneFilteringRootPackages( manager: *PackageManager, features: Features, exact_versions: bool, - comptime log_level: PackageManager.Options.LogLevel, + log_level: PackageManager.Options.LogLevel, ) !*Lockfile { const old_packages = old.packages.slice(); const old_dependencies_lists = old_packages.items(.dependencies); @@ -1273,7 +1273,7 @@ pub fn clean( manager: *PackageManager, updates: []PackageManager.UpdateRequest, exact_versions: bool, - comptime log_level: PackageManager.Options.LogLevel, + log_level: PackageManager.Options.LogLevel, ) !*Lockfile { // This is wasteful, but we rarely log anything so it's fine. var log = logger.Log.init(bun.default_allocator); @@ -1344,9 +1344,12 @@ pub fn cleanWithLogger( updates: []PackageManager.UpdateRequest, log: *logger.Log, exact_versions: bool, - comptime log_level: PackageManager.Options.LogLevel, + log_level: PackageManager.Options.LogLevel, ) !*Lockfile { - var timer: if (log_level.isVerbose()) std.time.Timer else void = if (comptime log_level.isVerbose()) try std.time.Timer.start(); + var timer: std.time.Timer = undefined; + if (log_level.isVerbose()) { + timer = try std.time.Timer.start(); + } const old_trusted_dependencies = old.trusted_dependencies; const old_scripts = old.scripts; @@ -1519,7 +1522,7 @@ pub fn cleanWithLogger( } } - if (comptime log_level.isVerbose()) { + if (log_level.isVerbose()) { Output.prettyErrorln("Clean lockfile: {d} packages -> {d} packages in {}\n", .{ old.packages.len, new.packages.len, @@ -2061,7 +2064,7 @@ pub const Printer = struct { comptime Writer: type, writer: Writer, comptime enable_ansi_colors: bool, - comptime log_level: PackageManager.Options.LogLevel, + log_level: PackageManager.Options.LogLevel, ) !void { try writer.writeAll("\n"); const allocator = this.lockfile.allocator; @@ -2083,7 +2086,7 @@ pub const Printer = struct { var had_printed_new_install = false; if (this.successfully_installed) |*installed| { - if (comptime log_level.isVerbose()) { + if (log_level.isVerbose()) { var workspaces_to_print: std.ArrayListUnmanaged(DependencyID) = .{}; defer workspaces_to_print.deinit(allocator); diff --git a/src/install/patch_install.zig b/src/install/patch_install.zig index d4c4fdd60b..1688b99139 100644 --- a/src/install/patch_install.zig +++ b/src/install/patch_install.zig @@ -141,7 +141,7 @@ pub const PatchTask = struct { pub fn runFromMainThread( this: *PatchTask, manager: *PackageManager, - comptime log_level: PackageManager.Options.LogLevel, + log_level: PackageManager.Options.LogLevel, ) !void { debug("runFromThreadMainThread {s}", .{@tagName(this.callback)}); defer { @@ -165,7 +165,7 @@ pub const PatchTask = struct { fn runFromMainThreadCalcHash( this: *PatchTask, manager: *PackageManager, - comptime log_level: PackageManager.Options.LogLevel, + log_level: PackageManager.Options.LogLevel, ) !void { // TODO only works for npm package // need to switch on version.tag and handle each case appropriately @@ -173,7 +173,7 @@ pub const PatchTask = struct { const hash = calc_hash.result orelse { const fmt = "\n\nErrors occured while calculating hash for {s}:\n\n"; const args = .{this.callback.calc_hash.patchfile_path}; - if (comptime log_level.showProgress()) { + if (log_level.showProgress()) { Output.prettyWithPrinterFn(fmt, args, Progress.log, &manager.progress); } else { Output.prettyErrorln( diff --git a/src/jsc.zig b/src/jsc.zig index cf32b33131..2f3b7b94cf 100644 --- a/src/jsc.zig +++ b/src/jsc.zig @@ -8,7 +8,6 @@ pub usingnamespace @import("./bun.js/module_loader.zig"); pub const Debugger = @import("./bun.js/bindings/Debugger.zig").Debugger; pub const napi = @import("./napi/napi.zig"); pub const RareData = @import("./bun.js/rare_data.zig"); -pub const Shimmer = @import("./bun.js/bindings/shimmer.zig").Shimmer; pub const C = @import("./bun.js/javascript_core_c_api.zig"); pub const WebCore = @import("./bun.js/webcore.zig"); pub const BuildMessage = @import("./bun.js/BuildMessage.zig").BuildMessage; diff --git a/src/s3/client.zig b/src/s3/client.zig index 09912e67fd..0ebf5efcaa 100644 --- a/src/s3/client.zig +++ b/src/s3/client.zig @@ -272,17 +272,11 @@ pub fn onUploadStreamRejectRequestStream(globalThis: *JSC.JSGlobalObject, callfr return .undefined; } -pub const shim = JSC.Shimmer("Bun", "S3UploadStream", @This()); - -pub const Export = shim.exportFunctions(.{ - .onResolveRequestStream = onUploadStreamResolveRequestStream, - .onRejectRequestStream = onUploadStreamRejectRequestStream, -}); comptime { const jsonResolveRequestStream = JSC.toJSHostFunction(onUploadStreamResolveRequestStream); - @export(&jsonResolveRequestStream, .{ .name = Export[0].symbol_name }); + @export(&jsonResolveRequestStream, .{ .name = "Bun__S3UploadStream__onResolveRequestStream" }); const jsonRejectRequestStream = JSC.toJSHostFunction(onUploadStreamRejectRequestStream); - @export(&jsonRejectRequestStream, .{ .name = Export[1].symbol_name }); + @export(&jsonRejectRequestStream, .{ .name = "Bun__S3UploadStream__onRejectRequestStream" }); } /// consumes the readable stream and upload to s3 diff --git a/test/internal/ban-words.test.ts b/test/internal/ban-words.test.ts index e296661bb4..3ec5f14faf 100644 --- a/test/internal/ban-words.test.ts +++ b/test/internal/ban-words.test.ts @@ -27,7 +27,7 @@ const words: Record "alloc.ptr !=": { reason: "The std.mem.Allocator context pointer can be undefined, which makes this comparison undefined behavior" }, "== alloc.ptr": { reason: "The std.mem.Allocator context pointer can be undefined, which makes this comparison undefined behavior" }, "!= alloc.ptr": { reason: "The std.mem.Allocator context pointer can be undefined, which makes this comparison undefined behavior" }, - [String.raw`: [a-zA-Z0-9_\.\*\?\[\]\(\)]+ = undefined,`]: { reason: "Do not default a struct field to undefined", limit: 250, regex: true }, + [String.raw`: [a-zA-Z0-9_\.\*\?\[\]\(\)]+ = undefined,`]: { reason: "Do not default a struct field to undefined", limit: 249, regex: true }, }; const words_keys = [...Object.keys(words)];