diff --git a/build.zig b/build.zig index ce8624f7e5..57ae78893b 100644 --- a/build.zig +++ b/build.zig @@ -429,7 +429,7 @@ pub fn addBunObject(b: *Build, opts: *BunBuildOptions) *Compile { .name = if (opts.optimize == .Debug) "bun-debug" else "bun", .root_source_file = switch (opts.os) { .wasm => b.path("root_wasm.zig"), - else => b.path("root.zig"), + else => b.path("src/main.zig"), // else => b.path("root_css.zig"), }, .target = opts.target, @@ -519,16 +519,6 @@ fn exists(path: []const u8) bool { fn addInternalPackages(b: *Build, obj: *Compile, opts: *BunBuildOptions) void { const os = opts.os; - const io_path = switch (os) { - .mac => "src/io/io_darwin.zig", - .linux => "src/io/io_linux.zig", - .windows => "src/io/io_windows.zig", - else => "src/io/io_stub.zig", - }; - obj.root_module.addAnonymousImport("async_io", .{ - .root_source_file = b.path(io_path), - }); - const zlib_internal_path = switch (os) { .windows => "src/deps/zlib.win32.zig", .linux, .mac => "src/deps/zlib.posix.zig", @@ -598,6 +588,15 @@ fn addInternalPackages(b: *Build, obj: *Compile, opts: *BunBuildOptions) void { }); } } + inline for (.{ + .{ .import = "completions-bash", .file = b.path("completions/bun.bash") }, + .{ .import = "completions-zsh", .file = b.path("completions/bun.zsh") }, + .{ .import = "completions-fish", .file = b.path("completions/bun.fish") }, + }) |entry| { + obj.root_module.addAnonymousImport(entry.import, .{ + .root_source_file = entry.file, + }); + } if (os == .windows) { obj.root_module.addAnonymousImport("bun_shim_impl.exe", .{ diff --git a/cmake/targets/BuildBun.cmake b/cmake/targets/BuildBun.cmake index 2e7df7b43a..aafc09f309 100644 --- a/cmake/targets/BuildBun.cmake +++ b/cmake/targets/BuildBun.cmake @@ -526,8 +526,7 @@ file(GLOB_RECURSE BUN_ZIG_SOURCES ${CONFIGURE_DEPENDS} list(APPEND BUN_ZIG_SOURCES ${CWD}/build.zig - ${CWD}/root.zig - ${CWD}/root_wasm.zig + ${CWD}/src/main.zig ${BUN_BINDGEN_ZIG_OUTPUTS} ) diff --git a/misctools/machbench.zig b/misctools/machbench.zig index d664788eab..8a5f20d494 100644 --- a/misctools/machbench.zig +++ b/misctools/machbench.zig @@ -35,7 +35,7 @@ fn spamMe(count: usize) void { while (i < count) : (i += 1) { waker.wake() catch unreachable; } - Output.prettyErrorln("[EVFILT_MACHPORT] Sent {any}", .{bun.fmt.fmtDuration(timer.read())}); + Output.prettyErrorln("[EVFILT_MACHPORT] Sent {any}", .{std.fmt.fmtDuration(timer.read())}); } const thread_count = 1; pub fn machMain(runs: usize) anyerror!void { @@ -67,7 +67,7 @@ pub fn machMain(runs: usize) anyerror!void { elapsed += timer.read(); } - Output.prettyErrorln("[EVFILT_MACHPORT] Recv {any}", .{bun.fmt.fmtDuration(elapsed)}); + Output.prettyErrorln("[EVFILT_MACHPORT] Recv {any}", .{std.fmt.fmtDuration(elapsed)}); } var user_waker: bun.Async.UserFilterWaker = undefined; @@ -80,7 +80,7 @@ fn spamMeUserFilter(count: usize) void { user_waker.wake() catch unreachable; } - Output.prettyErrorln("[EVFILT_USER] Sent {any}", .{bun.fmt.fmtDuration(timer.read())}); + Output.prettyErrorln("[EVFILT_USER] Sent {any}", .{std.fmt.fmtDuration(timer.read())}); } pub fn userMain(runs: usize) anyerror!void { defer Output.flush(); @@ -111,7 +111,7 @@ pub fn userMain(runs: usize) anyerror!void { elapsed += timer.read(); } - Output.prettyErrorln("[EVFILT_USER] Recv {any}", .{bun.fmt.fmtDuration(elapsed)}); + Output.prettyErrorln("[EVFILT_USER] Recv {any}", .{std.fmt.fmtDuration(elapsed)}); Output.flush(); } diff --git a/root.zig b/root.zig deleted file mode 100644 index b0d7360c0e..0000000000 --- a/root.zig +++ /dev/null @@ -1,31 +0,0 @@ -pub usingnamespace @import("./src/main.zig"); - -/// These functions are used throughout Bun's codebase. -pub const bun = @import("./src/bun.zig"); - -pub const completions = struct { - pub const bash = @embedFile("./completions/bun.bash"); - pub const zsh = @embedFile("./completions/bun.zsh"); - pub const fish = @embedFile("./completions/bun.fish"); -}; - -pub const JavaScriptCore = @import("./src/jsc.zig"); -pub const C = @import("./src/c.zig"); - -// -- Zig Standard Library Additions -- -pub fn copyForwards(comptime T: type, dest: []T, source: []const T) void { - if (source.len == 0) { - return; - } - bun.copy(T, dest[0..source.len], source); -} -pub fn copyBackwards(comptime T: type, dest: []T, source: []const T) void { - if (source.len == 0) { - return; - } - bun.copy(T, dest[0..source.len], source); -} -pub fn eqlBytes(src: []const u8, dest: []const u8) bool { - return bun.C.memcmp(src.ptr, dest.ptr, src.len) == 0; -} -// -- End Zig Standard Library Additions -- diff --git a/root_wasm.zig b/root_wasm.zig deleted file mode 100644 index a136835f2b..0000000000 --- a/root_wasm.zig +++ /dev/null @@ -1,15 +0,0 @@ -pub usingnamespace @import("src/main_wasm.zig"); - -pub const bun = @import("src/bun.zig"); - -pub const completions = struct {}; -pub const JavaScriptCore = struct { - pub fn markBinding(_: @import("std").builtin.SourceLocation) void { - unreachable; - } - - pub const ZigString = struct {}; -}; - -pub const C = struct {}; -pub const build_options = @import("build_options"); diff --git a/src/async/posix_event_loop.zig b/src/async/posix_event_loop.zig index 7ee6c5d31d..59c6a5d4b5 100644 --- a/src/async/posix_event_loop.zig +++ b/src/async/posix_event_loop.zig @@ -1095,7 +1095,111 @@ pub const FilePoll = struct { } }; -pub const Waker = bun.AsyncIO.Waker; +pub const Waker = switch (Environment.os) { + .mac => KEventWaker, + .linux => LinuxWaker, + else => @compileError(unreachable), +}; + +pub const LinuxWaker = struct { + fd: bun.FileDescriptor, + + pub fn init() !Waker { + return initWithFileDescriptor(bun.toFD(try std.posix.eventfd(0, 0))); + } + + pub fn getFd(this: *const Waker) bun.FileDescriptor { + return this.fd; + } + + pub fn initWithFileDescriptor(fd: bun.FileDescriptor) Waker { + return Waker{ .fd = fd }; + } + + pub fn wait(this: Waker) void { + var bytes: usize = 0; + _ = std.posix.read(this.fd.cast(), @as(*[8]u8, @ptrCast(&bytes))) catch 0; + } + + pub fn wake(this: *const Waker) void { + var bytes: usize = 1; + _ = std.posix.write( + this.fd.cast(), + @as(*[8]u8, @ptrCast(&bytes)), + ) catch 0; + } +}; + +pub const KEventWaker = struct { + kq: std.posix.fd_t, + machport: *anyopaque = undefined, + machport_buf: []u8 = &.{}, + has_pending_wake: bool = false, + + const zeroed = std.mem.zeroes([16]Kevent64); + + const Kevent64 = std.posix.system.kevent64_s; + + pub fn wake(this: *Waker) void { + bun.JSC.markBinding(@src()); + + if (io_darwin_schedule_wakeup(this.machport)) { + this.has_pending_wake = false; + return; + } + this.has_pending_wake = true; + } + + pub fn getFd(this: *const Waker) bun.FileDescriptor { + return bun.toFD(this.kq); + } + + pub fn wait(this: Waker) void { + bun.JSC.markBinding(@src()); + var events = zeroed; + + _ = std.posix.system.kevent64( + this.kq, + &events, + 0, + &events, + events.len, + 0, + null, + ); + } + + extern fn io_darwin_create_machport( + *anyopaque, + std.posix.fd_t, + *anyopaque, + usize, + ) ?*anyopaque; + + extern fn io_darwin_schedule_wakeup(*anyopaque) bool; + + pub fn init() !Waker { + return initWithFileDescriptor(bun.default_allocator, try std.posix.kqueue()); + } + + pub fn initWithFileDescriptor(allocator: std.mem.Allocator, kq: i32) !Waker { + bun.JSC.markBinding(@src()); + bun.assert(kq > -1); + const machport_buf = try allocator.alloc(u8, 1024); + const machport = io_darwin_create_machport( + machport_buf.ptr, + kq, + machport_buf.ptr, + 1024, + ) orelse return error.MachportCreationFailed; + + return Waker{ + .kq = kq, + .machport = machport, + .machport_buf = machport_buf, + }; + } +}; pub const Closer = struct { fd: bun.FileDescriptor, diff --git a/src/bake/FrameworkRouter.zig b/src/bake/FrameworkRouter.zig index f8f4a3bfb0..dc20ca4cd3 100644 --- a/src/bake/FrameworkRouter.zig +++ b/src/bake/FrameworkRouter.zig @@ -1081,7 +1081,8 @@ fn scanInner( /// creation. A production-grade JS api would be able to re-use objects. pub const JSFrameworkRouter = struct { pub const codegen = JSC.Codegen.JSFrameworkFileSystemRouter; - pub usingnamespace codegen; + pub const toJS = codegen.toJS; + pub const fromJS = codegen.fromJS; files: std.ArrayListUnmanaged(bun.String), router: FrameworkRouter, diff --git a/src/bun.js/ConsoleObject.zig b/src/bun.js/ConsoleObject.zig index b78c9afe7d..b184fe3bce 100644 --- a/src/bun.js/ConsoleObject.zig +++ b/src/bun.js/ConsoleObject.zig @@ -1541,7 +1541,7 @@ pub const Formatter = struct { 1; this.addForNewLine(digits); } else { - this.addForNewLine(bun.fmt.count("{d}", .{int})); + this.addForNewLine(std.fmt.count("{d}", .{int})); } writer.print("{d}", .{int}); }, @@ -1576,7 +1576,7 @@ pub const Formatter = struct { const abs = @abs(converted); if (abs < max_before_e_notation and abs >= min_before_e_notation) { - this.addForNewLine(bun.fmt.count("{d}", .{converted})); + this.addForNewLine(std.fmt.count("{d}", .{converted})); writer.print("{d}", .{converted}); } else if (std.math.isNan(converted)) { this.addForNewLine("NaN".len); @@ -2165,7 +2165,7 @@ pub const Formatter = struct { 1; this.addForNewLine(digits); } else { - this.addForNewLine(bun.fmt.count("{d}", .{int})); + this.addForNewLine(std.fmt.count("{d}", .{int})); } writer.print(comptime Output.prettyFmt("{d}", enable_ansi_colors), .{int}); }, diff --git a/src/bun.js/RuntimeTranspilerCache.zig b/src/bun.js/RuntimeTranspilerCache.zig index 3eac90cbf6..d754282eef 100644 --- a/src/bun.js/RuntimeTranspilerCache.zig +++ b/src/bun.js/RuntimeTranspilerCache.zig @@ -366,7 +366,7 @@ pub const RuntimeTranspilerCache = struct { ) !usize { const fmt_name = if (comptime bun.Environment.allow_assert) "{any}.debug.pile" else "{any}.pile"; - const printed = try std.fmt.bufPrint(buf, fmt_name, .{bun.fmt.fmtSliceHexLower(std.mem.asBytes(&input_hash))}); + const printed = try std.fmt.bufPrint(buf, fmt_name, .{std.fmt.fmtSliceHexLower(std.mem.asBytes(&input_hash))}); return printed.len; } diff --git a/src/bun.js/event_loop.zig b/src/bun.js/event_loop.zig index 1b8d98eef4..0c19f08a2f 100644 --- a/src/bun.js/event_loop.zig +++ b/src/bun.js/event_loop.zig @@ -1499,7 +1499,7 @@ pub const EventLoop = struct { loop.tickWithTimeout(if (ctx.timer.getTimeout(×pec, ctx)) ×pec else null); if (comptime Environment.isDebug) { - log("tick {}, timeout: {}", .{ bun.fmt.fmtDuration(event_loop_sleep_timer.read()), bun.fmt.fmtDuration(timespec.ns()) }); + log("tick {}, timeout: {}", .{ std.fmt.fmtDuration(event_loop_sleep_timer.read()), std.fmt.fmtDuration(timespec.ns()) }); } } else { loop.tickWithoutIdle(); diff --git a/src/bun.js/javascript.zig b/src/bun.js/javascript.zig index bf847630fb..351a6b285e 100644 --- a/src/bun.js/javascript.zig +++ b/src/bun.js/javascript.zig @@ -19,14 +19,14 @@ const IdentityContext = @import("../identity_context.zig").IdentityContext; const Fs = @import("../fs.zig"); const Resolver = @import("../resolver/resolver.zig"); const ast = @import("../import_record.zig"); -const MacroEntryPoint = bun.transpiler.MacroEntryPoint; +const MacroEntryPoint = bun.transpiler.EntryPoints.MacroEntryPoint; const ParseResult = bun.transpiler.ParseResult; const logger = bun.logger; const Api = @import("../api/schema.zig").Api; const options = @import("../options.zig"); const Transpiler = bun.Transpiler; const PluginRunner = bun.transpiler.PluginRunner; -const ServerEntryPoint = bun.transpiler.ServerEntryPoint; +const ServerEntryPoint = bun.transpiler.EntryPoints.ServerEntryPoint; const js_printer = bun.js_printer; const js_parser = bun.js_parser; const js_ast = bun.JSAst; @@ -1300,14 +1300,6 @@ pub const VirtualMachine = struct { this.pending_internal_promise = this.reloadEntryPoint(this.main) catch @panic("Failed to reload"); } - pub fn io(this: *VirtualMachine) *bun.AsyncIO { - if (this.io_ == null) { - this.io_ = bun.AsyncIO.init(this) catch @panic("Failed to initialize AsyncIO"); - } - - return &this.io_.?; - } - pub inline fn nodeFS(this: *VirtualMachine) *Node.NodeFS { return this.node_fs orelse brk: { this.node_fs = bun.default_allocator.create(Node.NodeFS) catch unreachable; @@ -1646,7 +1638,7 @@ pub const VirtualMachine = struct { this.eventLoop().autoTickActive(); if (comptime Environment.enable_logs) - log("waited: {}", .{bun.fmt.fmtDuration(@intCast(@as(i64, @truncate(std.time.nanoTimestamp() - bun.CLI.start_time))))}); + log("waited: {}", .{std.fmt.fmtDuration(@intCast(@as(i64, @truncate(std.time.nanoTimestamp() - bun.CLI.start_time))))}); }, .shortly => { // Handle .incrementRefConcurrently @@ -1661,7 +1653,7 @@ pub const VirtualMachine = struct { this.uwsLoop().tickWithTimeout(&deadline); if (comptime Environment.enable_logs) - log("waited: {}", .{bun.fmt.fmtDuration(@intCast(@as(i64, @truncate(std.time.nanoTimestamp() - bun.CLI.start_time))))}); + log("waited: {}", .{std.fmt.fmtDuration(@intCast(@as(i64, @truncate(std.time.nanoTimestamp() - bun.CLI.start_time))))}); const elapsed = bun.timespec.now(); if (elapsed.order(&deadline) != .lt) { diff --git a/src/bun.js/module_loader.zig b/src/bun.js/module_loader.zig index 1d3b0b8b03..6a85888f89 100644 --- a/src/bun.js/module_loader.zig +++ b/src/bun.js/module_loader.zig @@ -18,7 +18,7 @@ const IdentityContext = @import("../identity_context.zig").IdentityContext; const Fs = @import("../fs.zig"); const Resolver = @import("../resolver/resolver.zig"); const ast = @import("../import_record.zig"); -const MacroEntryPoint = bun.transpiler.MacroEntryPoint; +const MacroEntryPoint = bun.transpiler.EntryPoints.MacroEntryPoint; const ParseResult = bun.transpiler.ParseResult; const logger = bun.logger; const Api = @import("../api/schema.zig").Api; diff --git a/src/bun.js/node/buffer.zig b/src/bun.js/node/buffer.zig index 0bccfa0b9d..175fa9a6b6 100644 --- a/src/bun.js/node/buffer.zig +++ b/src/bun.js/node/buffer.zig @@ -1,3 +1,4 @@ +const std = @import("std"); const bun = @import("root").bun; const JSC = bun.JSC; const Encoder = JSC.WebCore.Encoder; @@ -58,7 +59,7 @@ pub const BufferVectorized = struct { inline 4, 8, 16 => |n| if (comptime Environment.isMac) { const pattern = buf[0..n]; buf = buf[pattern.len..]; - @field(bun.C, bun.fmt.comptimePrint("memset_pattern{d}", .{n}))(buf.ptr, pattern.ptr, buf.len); + @field(bun.C, std.fmt.comptimePrint("memset_pattern{d}", .{n}))(buf.ptr, pattern.ptr, buf.len); return true; }, else => {}, diff --git a/src/bun.js/test/pretty_format.zig b/src/bun.js/test/pretty_format.zig index 5d7fd28884..f5317d5d87 100644 --- a/src/bun.js/test/pretty_format.zig +++ b/src/bun.js/test/pretty_format.zig @@ -1049,7 +1049,7 @@ pub const JestPrettyFormat = struct { 1; this.addForNewLine(digits); } else { - this.addForNewLine(bun.fmt.count("{d}", .{int})); + this.addForNewLine(std.fmt.count("{d}", .{int})); } writer.print(comptime Output.prettyFmt("{d}", enable_ansi_colors), .{int}); }, diff --git a/src/bun.zig b/src/bun.zig index 84adbe0963..10e295855f 100644 --- a/src/bun.zig +++ b/src/bun.zig @@ -102,7 +102,7 @@ pub const JSOOM = OOM || JSError; pub const detectCI = @import("./ci_info.zig").detectCI; -pub const C = @import("root").C; +pub const C = @import("c.zig"); pub const sha = @import("./sha.zig"); pub const FeatureFlags = @import("feature_flags.zig"); pub const meta = @import("./meta.zig"); @@ -138,11 +138,7 @@ pub const Bitflags = @import("./bitflags.zig").Bitflags; pub const css = @import("./css/css_parser.zig"); pub const validators = @import("./bun.js/node/util/validators.zig"); -pub const shell = struct { - pub usingnamespace @import("./shell/shell.zig"); - pub const ShellSubprocess = @import("./shell/subproc.zig").ShellSubprocess; - // pub const ShellSubprocessMini = @import("./shell/subproc.zig").ShellSubprocessMini; -}; +pub const shell = @import("./shell/shell.zig"); pub const Output = @import("./output.zig"); pub const Global = @import("./Global.zig"); @@ -728,7 +724,11 @@ pub const http = @import("./http.zig"); pub const Analytics = @import("./analytics/analytics_thread.zig"); -pub usingnamespace @import("./tagged_pointer.zig"); +const tagged_pointer = @import("./tagged_pointer.zig"); +pub const TagTypeEnumWithTypeMap = tagged_pointer.TagTypeEnumWithTypeMap; +pub const TaggedPointer = tagged_pointer.TaggedPointer; +pub const TaggedPointerUnion = tagged_pointer.TaggedPointerUnion; +pub const TypeMap = tagged_pointer.TypeMap; pub fn onceUnsafe(comptime function: anytype, comptime ReturnType: type) ReturnType { const Result = struct { @@ -789,8 +789,7 @@ pub const invalid_fd: FileDescriptor = FDImpl.invalid.encode(); pub const simdutf = @import("./bun.js/bindings/bun-simdutf.zig"); -pub const JSC = @import("root").JavaScriptCore; -pub const AsyncIO = @import("async_io"); +pub const JSC = @import("jsc.zig"); pub const logger = @import("./logger.zig"); pub const ThreadPool = @import("./thread_pool.zig"); @@ -1464,7 +1463,7 @@ pub fn getFdPathW(fd_: anytype, buf: *WPathBuffer) ![]u16 { @panic("TODO unsupported platform for getFdPathW"); } -fn lenSliceTo(ptr: anytype, comptime end: meta.Elem(@TypeOf(ptr))) usize { +fn lenSliceTo(ptr: anytype, comptime end: std.meta.Elem(@TypeOf(ptr))) usize { switch (@typeInfo(@TypeOf(ptr))) { .pointer => |ptr_info| switch (ptr_info.size) { .one => switch (@typeInfo(ptr_info.child)) { @@ -1508,7 +1507,7 @@ fn lenSliceTo(ptr: anytype, comptime end: meta.Elem(@TypeOf(ptr))) usize { } /// Helper for the return type of sliceTo() -fn SliceTo(comptime T: type, comptime end: meta.Elem(T)) type { +fn SliceTo(comptime T: type, comptime end: std.meta.Elem(T)) type { switch (@typeInfo(T)) { .optional => |optional_info| { return ?SliceTo(optional_info.child, end); @@ -1568,7 +1567,7 @@ fn SliceTo(comptime T: type, comptime end: meta.Elem(T)) type { /// resulting slice is also sentinel terminated. /// Pointer properties such as mutability and alignment are preserved. /// C pointers are assumed to be non-null. -pub fn sliceTo(ptr: anytype, comptime end: meta.Elem(@TypeOf(ptr))) SliceTo(@TypeOf(ptr), end) { +pub fn sliceTo(ptr: anytype, comptime end: std.meta.Elem(@TypeOf(ptr))) SliceTo(@TypeOf(ptr), end) { if (@typeInfo(@TypeOf(ptr)) == .optional) { const non_null = ptr orelse return null; return sliceTo(non_null, end); diff --git a/src/bundler/bundle_v2.zig b/src/bundler/bundle_v2.zig index d198c33681..9f8ba3453e 100644 --- a/src/bundler/bundle_v2.zig +++ b/src/bundler/bundle_v2.zig @@ -101,7 +101,7 @@ const URL = @import("../url.zig").URL; const Linker = linker.Linker; const Resolver = _resolver.Resolver; const TOML = @import("../toml/toml_parser.zig").TOML; -const EntryPoints = @import("./entry_points.zig"); +const EntryPoints = bun.transpiler.EntryPoints; const Dependency = js_ast.Dependency; const JSAst = js_ast.BundledAst; const Loader = options.Loader; diff --git a/src/cli/pack_command.zig b/src/cli/pack_command.zig index b23e5ebaaf..2ef32b4c3e 100644 --- a/src/cli/pack_command.zig +++ b/src/cli/pack_command.zig @@ -71,7 +71,7 @@ pub const PackCommand = struct { if (log_level != .silent) { Output.prettyln("\nTotal files: {d}", .{stats.total_files}); if (maybe_shasum) |shasum| { - Output.prettyln("Shasum: {s}", .{bun.fmt.bytesToHex(shasum, .lower)}); + Output.prettyln("Shasum: {s}", .{std.fmt.bytesToHex(shasum, .lower)}); } if (maybe_integrity) |integrity| { Output.prettyln("Integrity: {}", .{bun.fmt.integrity(integrity, .short)}); @@ -2405,7 +2405,7 @@ pub const bindings = struct { defer sha1.deinit(); sha1.update(tarball); sha1.final(&sha1_digest); - const shasum_str = String.createFormat("{s}", .{bun.fmt.bytesToHex(sha1_digest, .lower)}) catch bun.outOfMemory(); + const shasum_str = String.createFormat("{s}", .{std.fmt.bytesToHex(sha1_digest, .lower)}) catch bun.outOfMemory(); var sha512_digest: sha.SHA512.Digest = undefined; var sha512 = sha.SHA512.init(); diff --git a/src/cli/publish_command.zig b/src/cli/publish_command.zig index 43ff1eaabc..59755decd8 100644 --- a/src/cli/publish_command.zig +++ b/src/cli/publish_command.zig @@ -801,7 +801,7 @@ pub const PublishCommand = struct { const nanoseconds = nanoseconds: { if (res.headers.get("retry-after")) |retry| default: { const trimmed = strings.trim(retry, &strings.whitespace_chars); - const seconds = bun.fmt.parseInt(u32, trimmed, 10) catch break :default; + const seconds = std.fmt.parseInt(u32, trimmed, 10) catch break :default; break :nanoseconds seconds * std.time.ns_per_s; } @@ -890,7 +890,7 @@ pub const PublishCommand = struct { // TODO: npm version try json.setString(allocator, "_npmVersion", "10.8.3"); try json.setString(allocator, "integrity", integrity_fmt); - try json.setString(allocator, "shasum", try std.fmt.allocPrint(allocator, "{s}", .{bun.fmt.bytesToHex(shasum, .lower)})); + try json.setString(allocator, "shasum", try std.fmt.allocPrint(allocator, "{s}", .{std.fmt.bytesToHex(shasum, .lower)})); var dist_props = try allocator.alloc(G.Property, 3); dist_props[0] = .{ @@ -913,7 +913,7 @@ pub const PublishCommand = struct { ), .value = Expr.init( E.String, - .{ .data = try std.fmt.allocPrint(allocator, "{s}", .{bun.fmt.bytesToHex(shasum, .lower)}) }, + .{ .data = try std.fmt.allocPrint(allocator, "{s}", .{std.fmt.bytesToHex(shasum, .lower)}) }, logger.Loc.Empty, ), }; @@ -926,7 +926,7 @@ pub const PublishCommand = struct { .value = Expr.init( E.String, .{ - .data = try bun.fmt.allocPrint(allocator, "http://{s}/{s}/-/{}", .{ + .data = try std.fmt.allocPrint(allocator, "http://{s}/{s}/-/{}", .{ // always use replace https with http // https://github.com/npm/cli/blob/9281ebf8e428d40450ad75ba61bc6f040b3bf896/workspaces/libnpmpublish/lib/publish.js#L120 strings.withoutTrailingSlash(strings.withoutPrefixComptime(registry.url.href, "https://")), @@ -1156,7 +1156,7 @@ pub const PublishCommand = struct { while (iter.next().unwrap() catch null) |entry| { const name, const subpath = name_and_subpath: { const name = entry.name.slice(); - const join = try bun.fmt.allocPrintZ(allocator, "{s}{s}{s}", .{ + const join = try std.fmt.allocPrintZ(allocator, "{s}{s}{s}", .{ dir_subpath, // only using posix separators if (dir_subpath.len == 0) "" else std.fs.path.sep_str_posix, diff --git a/src/cli/shell_completions.zig b/src/cli/shell_completions.zig index 4df3eb70b8..7468104997 100644 --- a/src/cli/shell_completions.zig +++ b/src/cli/shell_completions.zig @@ -17,15 +17,15 @@ pub const Shell = enum { fish, pwsh, - const bash_completions = @import("root").completions.bash; - const zsh_completions = @import("root").completions.zsh; - const fish_completions = @import("root").completions.fish; + const bash_completions = @embedFile("completions-bash"); + const zsh_completions = @embedFile("completions-zsh"); + const fish_completions = @embedFile("completions-fish"); pub fn completions(this: Shell) []const u8 { return switch (this) { - .bash => bun.asByteSlice(bash_completions), - .zsh => bun.asByteSlice(zsh_completions), - .fish => bun.asByteSlice(fish_completions), + .bash => bash_completions, + .zsh => zsh_completions, + .fish => fish_completions, else => "", }; } diff --git a/src/cli/test_command.zig b/src/cli/test_command.zig index 244083f4a8..a62068c386 100644 --- a/src/cli/test_command.zig +++ b/src/cli/test_command.zig @@ -42,7 +42,8 @@ const jest = JSC.Jest; const TestRunner = JSC.Jest.TestRunner; const Snapshots = JSC.Snapshot.Snapshots; const Test = TestRunner.Test; -const CodeCoverageReport = bun.sourcemap.CodeCoverageReport; +const coverage = bun.sourcemap.coverage; +const CodeCoverageReport = coverage.Report; const uws = bun.uws; fn escapeXml(str: string, writer: anytype) !void { @@ -721,9 +722,9 @@ pub const CommandLineReporter = struct { return; } - var map = bun.sourcemap.ByteRangeMapping.map orelse return; + var map = coverage.ByteRangeMapping.map orelse return; var iter = map.valueIterator(); - var byte_ranges = try std.ArrayList(bun.sourcemap.ByteRangeMapping).initCapacity(bun.default_allocator, map.count()); + var byte_ranges = try std.ArrayList(bun.sourcemap.coverage.ByteRangeMapping).initCapacity(bun.default_allocator, map.count()); while (iter.next()) |entry| { byte_ranges.appendAssumeCapacity(entry.*); @@ -733,13 +734,24 @@ pub const CommandLineReporter = struct { return; } - std.sort.pdq(bun.sourcemap.ByteRangeMapping, byte_ranges.items, void{}, bun.sourcemap.ByteRangeMapping.isLessThan); + std.sort.pdq( + bun.sourcemap.coverage.ByteRangeMapping, + byte_ranges.items, + {}, + bun.sourcemap.coverage.ByteRangeMapping.isLessThan, + ); try this.printCodeCoverage(vm, opts, byte_ranges.items, reporters, enable_ansi_colors); } - pub fn printCodeCoverage(this: *CommandLineReporter, vm: *JSC.VirtualMachine, opts: *TestCommand.CodeCoverageOptions, byte_ranges: []bun.sourcemap.ByteRangeMapping, comptime reporters: TestCommand.Reporters, comptime enable_ansi_colors: bool) !void { - _ = this; // autofix + pub fn printCodeCoverage( + _: *CommandLineReporter, + vm: *JSC.VirtualMachine, + opts: *TestCommand.CodeCoverageOptions, + byte_ranges: []bun.sourcemap.coverage.ByteRangeMapping, + comptime reporters: TestCommand.Reporters, + comptime enable_ansi_colors: bool, + ) !void { const trace = bun.tracy.traceNamed(@src(), comptime brk: { if (reporters.text and reporters.lcov) { break :brk "TestCommand.printCodeCoverageLCovAndText"; @@ -795,7 +807,7 @@ pub const CommandLineReporter = struct { var console_buffer_buffer = console_buffer.bufferedWriter(); var console_writer = console_buffer_buffer.writer(); - var avg = bun.sourcemap.CoverageFraction{ + var avg = bun.sourcemap.coverage.Fraction{ .functions = 0.0, .lines = 0.0, .stmts = 0.0, @@ -823,7 +835,7 @@ pub const CommandLineReporter = struct { var base64_bytes: [8]u8 = undefined; var shortname_buf: [512]u8 = undefined; bun.rand(&base64_bytes); - const tmpname = std.fmt.bufPrintZ(&shortname_buf, ".lcov.info.{s}.tmp", .{bun.fmt.fmtSliceHexLower(&base64_bytes)}) catch unreachable; + const tmpname = std.fmt.bufPrintZ(&shortname_buf, ".lcov.info.{s}.tmp", .{std.fmt.fmtSliceHexLower(&base64_bytes)}) catch unreachable; const path = bun.path.joinAbsStringBufZ(relative_dir, &lcov_name_buf, &.{ opts.reports_directory, tmpname }, .auto); const file = bun.sys.File.openat( std.fs.cwd(), @@ -1155,7 +1167,7 @@ pub const TestCommand = struct { skip_test_files: bool = !Environment.allow_assert, reporters: Reporters = .{ .text = true, .lcov = false }, reports_directory: string = "coverage", - fractions: bun.sourcemap.CoverageFraction = .{}, + fractions: bun.sourcemap.coverage.Fraction = .{}, ignore_sourcemap: bool = false, enabled: bool = false, fail_on_low_coverage: bool = false, @@ -1380,8 +1392,7 @@ pub const TestCommand = struct { const write_snapshots_success = try jest.Jest.runner.?.snapshots.writeInlineSnapshots(); try jest.Jest.runner.?.snapshots.writeSnapshotFile(); - var coverage = ctx.test_options.coverage; - + var coverage_options = ctx.test_options.coverage; if (reporter.summary.pass > 20) { if (reporter.summary.skip > 0) { Output.prettyError("\n{d} tests skipped:\n", .{reporter.summary.skip}); @@ -1466,12 +1477,12 @@ pub const TestCommand = struct { } else { Output.prettyError("\n", .{}); - if (coverage.enabled) { + if (coverage_options.enabled) { switch (Output.enable_ansi_colors_stderr) { - inline else => |colors| switch (coverage.reporters.text) { - inline else => |console| switch (coverage.reporters.lcov) { + inline else => |colors| switch (coverage_options.reporters.text) { + inline else => |console| switch (coverage_options.reporters.lcov) { inline else => |lcov| { - try reporter.generateCodeCoverage(vm, &coverage, .{ .text = console, .lcov = lcov }, colors); + try reporter.generateCodeCoverage(vm, &coverage_options, .{ .text = console, .lcov = lcov }, colors); }, }, }, @@ -1568,7 +1579,7 @@ pub const TestCommand = struct { vm.runWithAPILock(JSC.VirtualMachine, vm, runEventLoopForWatch); } - if (reporter.summary.fail > 0 or (coverage.enabled and coverage.fractions.failing and coverage.fail_on_low_coverage) or !write_snapshots_success) { + if (reporter.summary.fail > 0 or (coverage_options.enabled and coverage_options.fractions.failing and coverage_options.fail_on_low_coverage) or !write_snapshots_success) { Global.exit(1); } else if (reporter.jest.unhandled_errors_between_tests > 0) { Global.exit(reporter.jest.unhandled_errors_between_tests); diff --git a/src/css/properties/border.zig b/src/css/properties/border.zig index 71a2137065..aff3d92ad6 100644 --- a/src/css/properties/border.zig +++ b/src/css/properties/border.zig @@ -479,7 +479,7 @@ pub const BorderInlineWidth = struct { }; pub fn ImplFallbacks(comptime T: type) type { - const field_names = bun.meta.fieldNames(T); + const field_names = std.meta.fieldNames(T); return struct { pub fn getFallbacks(this: *T, allocator: std.mem.Allocator, targets: css.Targets) css.SmallList(T, 2) { const ColorFallbackKind = css.css_values.color.ColorFallbackKind; diff --git a/src/darwin_c.zig b/src/darwin_c.zig index c2d36a4648..c042bca553 100644 --- a/src/darwin_c.zig +++ b/src/darwin_c.zig @@ -562,129 +562,125 @@ pub fn get_release(buf: []u8) []const u8 { return bun.sliceTo(buf, 0); } -const IO_CTL_RELATED = struct { - pub const IOCPARM_MASK = @as(c_int, 0x1fff); - pub inline fn IOCPARM_LEN(x: anytype) @TypeOf((x >> @as(c_int, 16)) & IOCPARM_MASK) { - return (x >> @as(c_int, 16)) & IOCPARM_MASK; - } - pub inline fn IOCBASECMD(x: anytype) @TypeOf(x & ~(IOCPARM_MASK << @as(c_int, 16))) { - return x & ~(IOCPARM_MASK << @as(c_int, 16)); - } - pub inline fn IOCGROUP(x: anytype) @TypeOf((x >> @as(c_int, 8)) & @as(c_int, 0xff)) { - return (x >> @as(c_int, 8)) & @as(c_int, 0xff); - } - pub const IOCPARM_MAX = IOCPARM_MASK + @as(c_int, 1); - pub const IOC_VOID = @import("std").zig.c_translation.cast(u32, @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x20000000, .hex)); - pub const IOC_OUT = @import("std").zig.c_translation.cast(u32, @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x40000000, .hex)); - pub const IOC_IN = @import("std").zig.c_translation.cast(u32, @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x80000000, .hex)); - pub const IOC_INOUT = IOC_IN | IOC_OUT; - pub const IOC_DIRMASK = @import("std").zig.c_translation.cast(u32, @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xe0000000, .hex)); - pub inline fn _IOC(inout: anytype, group: anytype, num: anytype, len: anytype) @TypeOf(((inout | ((len & IOCPARM_MASK) << @as(c_int, 16))) | (group << @as(c_int, 8))) | num) { - return ((inout | ((len & IOCPARM_MASK) << @as(c_int, 16))) | (group << @as(c_int, 8))) | num; - } - pub inline fn _IO(g: anytype, n: anytype) @TypeOf(_IOC(IOC_VOID, g, n, @as(c_int, 0))) { - return _IOC(IOC_VOID, g, n, @as(c_int, 0)); - } - pub inline fn _IOR(g: anytype, n: anytype, t: anytype) @TypeOf(_IOC(IOC_OUT, g, n, @import("std").zig.c_translation.sizeof(t))) { - return _IOC(IOC_OUT, g, n, @import("std").zig.c_translation.sizeof(t)); - } - pub inline fn _IOW(g: anytype, n: anytype, t: anytype) @TypeOf(_IOC(IOC_IN, g, n, @import("std").zig.c_translation.sizeof(t))) { - return _IOC(IOC_IN, g, n, @import("std").zig.c_translation.sizeof(t)); - } - pub inline fn _IOWR(g: anytype, n: anytype, t: anytype) @TypeOf(_IOC(IOC_INOUT, g, n, @import("std").zig.c_translation.sizeof(t))) { - return _IOC(IOC_INOUT, g, n, @import("std").zig.c_translation.sizeof(t)); - } - pub const TIOCMODG = _IOR('t', @as(c_int, 3), c_int); - pub const TIOCMODS = _IOW('t', @as(c_int, 4), c_int); - pub const TIOCM_LE = @as(c_int, 0o001); - pub const TIOCM_DTR = @as(c_int, 0o002); - pub const TIOCM_RTS = @as(c_int, 0o004); - pub const TIOCM_ST = @as(c_int, 0o010); - pub const TIOCM_SR = @as(c_int, 0o020); - pub const TIOCM_CTS = @as(c_int, 0o040); - pub const TIOCM_CAR = @as(c_int, 0o100); - pub const TIOCM_CD = TIOCM_CAR; - pub const TIOCM_RNG = @as(c_int, 0o200); - pub const TIOCM_RI = TIOCM_RNG; - pub const TIOCM_DSR = @as(c_int, 0o400); - pub const TIOCEXCL = _IO('t', @as(c_int, 13)); - pub const TIOCNXCL = _IO('t', @as(c_int, 14)); - pub const TIOCFLUSH = _IOW('t', @as(c_int, 16), c_int); - pub const TIOCGETD = _IOR('t', @as(c_int, 26), c_int); - pub const TIOCSETD = _IOW('t', @as(c_int, 27), c_int); - pub const TIOCIXON = _IO('t', @as(c_int, 129)); - pub const TIOCIXOFF = _IO('t', @as(c_int, 128)); - pub const TIOCSBRK = _IO('t', @as(c_int, 123)); - pub const TIOCCBRK = _IO('t', @as(c_int, 122)); - pub const TIOCSDTR = _IO('t', @as(c_int, 121)); - pub const TIOCCDTR = _IO('t', @as(c_int, 120)); - pub const TIOCGPGRP = _IOR('t', @as(c_int, 119), c_int); - pub const TIOCSPGRP = _IOW('t', @as(c_int, 118), c_int); - pub const TIOCOUTQ = _IOR('t', @as(c_int, 115), c_int); - pub const TIOCSTI = _IOW('t', @as(c_int, 114), u8); - pub const TIOCNOTTY = _IO('t', @as(c_int, 113)); - pub const TIOCPKT = _IOW('t', @as(c_int, 112), c_int); - pub const TIOCPKT_DATA = @as(c_int, 0x00); - pub const TIOCPKT_FLUSHREAD = @as(c_int, 0x01); - pub const TIOCPKT_FLUSHWRITE = @as(c_int, 0x02); - pub const TIOCPKT_STOP = @as(c_int, 0x04); - pub const TIOCPKT_START = @as(c_int, 0x08); - pub const TIOCPKT_NOSTOP = @as(c_int, 0x10); - pub const TIOCPKT_DOSTOP = @as(c_int, 0x20); - pub const TIOCPKT_IOCTL = @as(c_int, 0x40); - pub const TIOCSTOP = _IO('t', @as(c_int, 111)); - pub const TIOCSTART = _IO('t', @as(c_int, 110)); - pub const TIOCMSET = _IOW('t', @as(c_int, 109), c_int); - pub const TIOCMBIS = _IOW('t', @as(c_int, 108), c_int); - pub const TIOCMBIC = _IOW('t', @as(c_int, 107), c_int); - pub const TIOCMGET = _IOR('t', @as(c_int, 106), c_int); - // pub const TIOCGWINSZ = _IOR('t', @as(c_int, 104), struct_winsize); - // pub const TIOCSWINSZ = _IOW('t', @as(c_int, 103), struct_winsize); - pub const TIOCUCNTL = _IOW('t', @as(c_int, 102), c_int); - pub const TIOCSTAT = _IO('t', @as(c_int, 101)); - pub inline fn UIOCCMD(n: anytype) @TypeOf(_IO('u', n)) { - return _IO('u', n); - } - pub const TIOCSCONS = _IO('t', @as(c_int, 99)); - pub const TIOCCONS = _IOW('t', @as(c_int, 98), c_int); - pub const TIOCSCTTY = _IO('t', @as(c_int, 97)); - pub const TIOCEXT = _IOW('t', @as(c_int, 96), c_int); - pub const TIOCSIG = _IO('t', @as(c_int, 95)); - pub const TIOCDRAIN = _IO('t', @as(c_int, 94)); - pub const TIOCMSDTRWAIT = _IOW('t', @as(c_int, 91), c_int); - pub const TIOCMGDTRWAIT = _IOR('t', @as(c_int, 90), c_int); - pub const TIOCSDRAINWAIT = _IOW('t', @as(c_int, 87), c_int); - pub const TIOCGDRAINWAIT = _IOR('t', @as(c_int, 86), c_int); - pub const TIOCDSIMICROCODE = _IO('t', @as(c_int, 85)); - pub const TIOCPTYGRANT = _IO('t', @as(c_int, 84)); - pub const TIOCPTYGNAME = _IOC(IOC_OUT, 't', @as(c_int, 83), @as(c_int, 128)); - pub const TIOCPTYUNLK = _IO('t', @as(c_int, 82)); - pub const TTYDISC = @as(c_int, 0); - pub const TABLDISC = @as(c_int, 3); - pub const SLIPDISC = @as(c_int, 4); - pub const PPPDISC = @as(c_int, 5); - // pub const TIOCGSIZE = TIOCGWINSZ; - // pub const TIOCSSIZE = TIOCSWINSZ; - pub const FIOCLEX = _IO('f', @as(c_int, 1)); - pub const FIONCLEX = _IO('f', @as(c_int, 2)); - pub const FIONREAD = _IOR('f', @as(c_int, 127), c_int); - pub const FIONBIO = _IOW('f', @as(c_int, 126), c_int); - pub const FIOASYNC = _IOW('f', @as(c_int, 125), c_int); - pub const FIOSETOWN = _IOW('f', @as(c_int, 124), c_int); - pub const FIOGETOWN = _IOR('f', @as(c_int, 123), c_int); - pub const FIODTYPE = _IOR('f', @as(c_int, 122), c_int); - pub const SIOCSHIWAT = _IOW('s', @as(c_int, 0), c_int); - pub const SIOCGHIWAT = _IOR('s', @as(c_int, 1), c_int); - pub const SIOCSLOWAT = _IOW('s', @as(c_int, 2), c_int); - pub const SIOCGLOWAT = _IOR('s', @as(c_int, 3), c_int); - pub const SIOCATMARK = _IOR('s', @as(c_int, 7), c_int); - pub const SIOCSPGRP = _IOW('s', @as(c_int, 8), c_int); - pub const SIOCGPGRP = _IOR('s', @as(c_int, 9), c_int); - // pub const SIOCSETVLAN = SIOCSIFVLAN; - // pub const SIOCGETVLAN = SIOCGIFVLAN; -}; - -pub usingnamespace IO_CTL_RELATED; +pub const IOCPARM_MASK = @as(c_int, 0x1fff); +pub inline fn IOCPARM_LEN(x: anytype) @TypeOf((x >> @as(c_int, 16)) & IOCPARM_MASK) { + return (x >> @as(c_int, 16)) & IOCPARM_MASK; +} +pub inline fn IOCBASECMD(x: anytype) @TypeOf(x & ~(IOCPARM_MASK << @as(c_int, 16))) { + return x & ~(IOCPARM_MASK << @as(c_int, 16)); +} +pub inline fn IOCGROUP(x: anytype) @TypeOf((x >> @as(c_int, 8)) & @as(c_int, 0xff)) { + return (x >> @as(c_int, 8)) & @as(c_int, 0xff); +} +pub const IOCPARM_MAX = IOCPARM_MASK + @as(c_int, 1); +pub const IOC_VOID = @import("std").zig.c_translation.cast(u32, @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x20000000, .hex)); +pub const IOC_OUT = @import("std").zig.c_translation.cast(u32, @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x40000000, .hex)); +pub const IOC_IN = @import("std").zig.c_translation.cast(u32, @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x80000000, .hex)); +pub const IOC_INOUT = IOC_IN | IOC_OUT; +pub const IOC_DIRMASK = @import("std").zig.c_translation.cast(u32, @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xe0000000, .hex)); +pub inline fn _IOC(inout: anytype, group: anytype, num: anytype, len: anytype) @TypeOf(((inout | ((len & IOCPARM_MASK) << @as(c_int, 16))) | (group << @as(c_int, 8))) | num) { + return ((inout | ((len & IOCPARM_MASK) << @as(c_int, 16))) | (group << @as(c_int, 8))) | num; +} +pub inline fn _IO(g: anytype, n: anytype) @TypeOf(_IOC(IOC_VOID, g, n, @as(c_int, 0))) { + return _IOC(IOC_VOID, g, n, @as(c_int, 0)); +} +pub inline fn _IOR(g: anytype, n: anytype, t: anytype) @TypeOf(_IOC(IOC_OUT, g, n, @import("std").zig.c_translation.sizeof(t))) { + return _IOC(IOC_OUT, g, n, @import("std").zig.c_translation.sizeof(t)); +} +pub inline fn _IOW(g: anytype, n: anytype, t: anytype) @TypeOf(_IOC(IOC_IN, g, n, @import("std").zig.c_translation.sizeof(t))) { + return _IOC(IOC_IN, g, n, @import("std").zig.c_translation.sizeof(t)); +} +pub inline fn _IOWR(g: anytype, n: anytype, t: anytype) @TypeOf(_IOC(IOC_INOUT, g, n, @import("std").zig.c_translation.sizeof(t))) { + return _IOC(IOC_INOUT, g, n, @import("std").zig.c_translation.sizeof(t)); +} +pub const TIOCMODG = _IOR('t', @as(c_int, 3), c_int); +pub const TIOCMODS = _IOW('t', @as(c_int, 4), c_int); +pub const TIOCM_LE = @as(c_int, 0o001); +pub const TIOCM_DTR = @as(c_int, 0o002); +pub const TIOCM_RTS = @as(c_int, 0o004); +pub const TIOCM_ST = @as(c_int, 0o010); +pub const TIOCM_SR = @as(c_int, 0o020); +pub const TIOCM_CTS = @as(c_int, 0o040); +pub const TIOCM_CAR = @as(c_int, 0o100); +pub const TIOCM_CD = TIOCM_CAR; +pub const TIOCM_RNG = @as(c_int, 0o200); +pub const TIOCM_RI = TIOCM_RNG; +pub const TIOCM_DSR = @as(c_int, 0o400); +pub const TIOCEXCL = _IO('t', @as(c_int, 13)); +pub const TIOCNXCL = _IO('t', @as(c_int, 14)); +pub const TIOCFLUSH = _IOW('t', @as(c_int, 16), c_int); +pub const TIOCGETD = _IOR('t', @as(c_int, 26), c_int); +pub const TIOCSETD = _IOW('t', @as(c_int, 27), c_int); +pub const TIOCIXON = _IO('t', @as(c_int, 129)); +pub const TIOCIXOFF = _IO('t', @as(c_int, 128)); +pub const TIOCSBRK = _IO('t', @as(c_int, 123)); +pub const TIOCCBRK = _IO('t', @as(c_int, 122)); +pub const TIOCSDTR = _IO('t', @as(c_int, 121)); +pub const TIOCCDTR = _IO('t', @as(c_int, 120)); +pub const TIOCGPGRP = _IOR('t', @as(c_int, 119), c_int); +pub const TIOCSPGRP = _IOW('t', @as(c_int, 118), c_int); +pub const TIOCOUTQ = _IOR('t', @as(c_int, 115), c_int); +pub const TIOCSTI = _IOW('t', @as(c_int, 114), u8); +pub const TIOCNOTTY = _IO('t', @as(c_int, 113)); +pub const TIOCPKT = _IOW('t', @as(c_int, 112), c_int); +pub const TIOCPKT_DATA = @as(c_int, 0x00); +pub const TIOCPKT_FLUSHREAD = @as(c_int, 0x01); +pub const TIOCPKT_FLUSHWRITE = @as(c_int, 0x02); +pub const TIOCPKT_STOP = @as(c_int, 0x04); +pub const TIOCPKT_START = @as(c_int, 0x08); +pub const TIOCPKT_NOSTOP = @as(c_int, 0x10); +pub const TIOCPKT_DOSTOP = @as(c_int, 0x20); +pub const TIOCPKT_IOCTL = @as(c_int, 0x40); +pub const TIOCSTOP = _IO('t', @as(c_int, 111)); +pub const TIOCSTART = _IO('t', @as(c_int, 110)); +pub const TIOCMSET = _IOW('t', @as(c_int, 109), c_int); +pub const TIOCMBIS = _IOW('t', @as(c_int, 108), c_int); +pub const TIOCMBIC = _IOW('t', @as(c_int, 107), c_int); +pub const TIOCMGET = _IOR('t', @as(c_int, 106), c_int); +// pub const TIOCGWINSZ = _IOR('t', @as(c_int, 104), struct_winsize); +// pub const TIOCSWINSZ = _IOW('t', @as(c_int, 103), struct_winsize); +pub const TIOCUCNTL = _IOW('t', @as(c_int, 102), c_int); +pub const TIOCSTAT = _IO('t', @as(c_int, 101)); +pub inline fn UIOCCMD(n: anytype) @TypeOf(_IO('u', n)) { + return _IO('u', n); +} +pub const TIOCSCONS = _IO('t', @as(c_int, 99)); +pub const TIOCCONS = _IOW('t', @as(c_int, 98), c_int); +pub const TIOCSCTTY = _IO('t', @as(c_int, 97)); +pub const TIOCEXT = _IOW('t', @as(c_int, 96), c_int); +pub const TIOCSIG = _IO('t', @as(c_int, 95)); +pub const TIOCDRAIN = _IO('t', @as(c_int, 94)); +pub const TIOCMSDTRWAIT = _IOW('t', @as(c_int, 91), c_int); +pub const TIOCMGDTRWAIT = _IOR('t', @as(c_int, 90), c_int); +pub const TIOCSDRAINWAIT = _IOW('t', @as(c_int, 87), c_int); +pub const TIOCGDRAINWAIT = _IOR('t', @as(c_int, 86), c_int); +pub const TIOCDSIMICROCODE = _IO('t', @as(c_int, 85)); +pub const TIOCPTYGRANT = _IO('t', @as(c_int, 84)); +pub const TIOCPTYGNAME = _IOC(IOC_OUT, 't', @as(c_int, 83), @as(c_int, 128)); +pub const TIOCPTYUNLK = _IO('t', @as(c_int, 82)); +pub const TTYDISC = @as(c_int, 0); +pub const TABLDISC = @as(c_int, 3); +pub const SLIPDISC = @as(c_int, 4); +pub const PPPDISC = @as(c_int, 5); +// pub const TIOCGSIZE = TIOCGWINSZ; +// pub const TIOCSSIZE = TIOCSWINSZ; +pub const FIOCLEX = _IO('f', @as(c_int, 1)); +pub const FIONCLEX = _IO('f', @as(c_int, 2)); +pub const FIONREAD = _IOR('f', @as(c_int, 127), c_int); +pub const FIONBIO = _IOW('f', @as(c_int, 126), c_int); +pub const FIOASYNC = _IOW('f', @as(c_int, 125), c_int); +pub const FIOSETOWN = _IOW('f', @as(c_int, 124), c_int); +pub const FIOGETOWN = _IOR('f', @as(c_int, 123), c_int); +pub const FIODTYPE = _IOR('f', @as(c_int, 122), c_int); +pub const SIOCSHIWAT = _IOW('s', @as(c_int, 0), c_int); +pub const SIOCGHIWAT = _IOR('s', @as(c_int, 1), c_int); +pub const SIOCSLOWAT = _IOW('s', @as(c_int, 2), c_int); +pub const SIOCGLOWAT = _IOR('s', @as(c_int, 3), c_int); +pub const SIOCATMARK = _IOR('s', @as(c_int, 7), c_int); +pub const SIOCSPGRP = _IOW('s', @as(c_int, 8), c_int); +pub const SIOCGPGRP = _IOR('s', @as(c_int, 9), c_int); +// pub const SIOCSETVLAN = SIOCSIFVLAN; +// pub const SIOCGETVLAN = SIOCGIFVLAN; // As of Zig v0.11.0-dev.1393+38eebf3c4, ifaddrs.h is not included in the headers pub const ifaddrs = extern struct { diff --git a/src/deps/libuv.zig b/src/deps/libuv.zig index 336b5720d7..8a6dbe7252 100644 --- a/src/deps/libuv.zig +++ b/src/deps/libuv.zig @@ -2248,19 +2248,18 @@ pub fn socketpair(stdio_flag_1: uv_stdio_flags, stdio_flag_2: uv_stdio_flags) Ma return .{ .result = pair }; } -pub usingnamespace struct { - pub fn pipe(stdio_flag_1: uv_stdio_flags, stdio_flag_2: uv_stdio_flags) Maybe([2]*anyopaque) { - var pair: [2]uv_file = undefined; - // https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-socket - const SOCK_STREAM = 1; - if (uv_socketpair(0, SOCK_STREAM, &pair, stdio_flag_1, stdio_flag_2).toError(.open)) |err| { - return .{ .err = err }; - } +pub fn pipe(stdio_flag_1: uv_stdio_flags, stdio_flag_2: uv_stdio_flags) Maybe([2]*anyopaque) { + var pair: [2]uv_file = undefined; + // https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-socket + const SOCK_STREAM = 1; - return .{ .result = pair }; + if (uv_socketpair(0, SOCK_STREAM, &pair, stdio_flag_1, stdio_flag_2).toError(.open)) |err| { + return .{ .err = err }; } -}; + + return .{ .result = pair }; +} const union_unnamed_463 = extern union { stream: *uv_stream_t, diff --git a/src/fmt.zig b/src/fmt.zig index 2720f0b6f9..447928ebd2 100644 --- a/src/fmt.zig +++ b/src/fmt.zig @@ -9,8 +9,6 @@ const fmt = std.fmt; const Environment = bun.Environment; const sha = bun.sha; -pub usingnamespace std.fmt; - pub const TableSymbols = struct { enable_ansi_colors: bool, diff --git a/src/fs.zig b/src/fs.zig index a0b5344df5..09efbbd4e2 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -537,7 +537,7 @@ pub const FileSystem = struct { .windows => win_tempdir_cache orelse { const value = bun.getenvZ("TEMP") orelse bun.getenvZ("TMP") orelse brk: { if (bun.getenvZ("SystemRoot") orelse bun.getenvZ("windir")) |windir| { - break :brk bun.fmt.allocPrint( + break :brk std.fmt.allocPrint( bun.default_allocator, "{s}\\Temp", .{strings.withoutTrailingSlash(windir)}, @@ -554,7 +554,7 @@ pub const FileSystem = struct { var tmp_buf: bun.PathBuffer = undefined; const cwd = std.posix.getcwd(&tmp_buf) catch @panic("Failed to get cwd for platformTempDir"); const root = bun.path.windowsFilesystemRoot(cwd); - break :brk bun.fmt.allocPrint( + break :brk std.fmt.allocPrint( bun.default_allocator, "{s}\\Windows\\Temp", .{strings.withoutTrailingSlash(root)}, diff --git a/src/http.zig b/src/http.zig index 6eb64576ac..e028730b65 100644 --- a/src/http.zig +++ b/src/http.zig @@ -2833,7 +2833,7 @@ pub const AsyncHTTP = struct { this.client.deinit(); var threadlocal_http: *ThreadlocalAsyncHTTP = @fieldParentPtr("async_http", async_http); defer threadlocal_http.destroy(); - log("onAsyncHTTPCallback: {any}", .{bun.fmt.fmtDuration(this.elapsed)}); + log("onAsyncHTTPCallback: {any}", .{std.fmt.fmtDuration(this.elapsed)}); callback.function(callback.ctx, async_http, result); } diff --git a/src/install/bun.lock.zig b/src/install/bun.lock.zig index 80e7702f77..729f8d2dfe 100644 --- a/src/install/bun.lock.zig +++ b/src/install/bun.lock.zig @@ -295,7 +295,7 @@ pub const Stringifier = struct { const dep = deps_buf[dep_id]; // clobber, there isn't data - try pkg_map.put(try bun.fmt.allocPrint(allocator, "{s}{s}{s}", .{ + try pkg_map.put(try std.fmt.allocPrint(allocator, "{s}{s}{s}", .{ node.relative_path, if (node.depth == 0) "" else "/", dep.name.slice(buf), @@ -1904,7 +1904,7 @@ pub fn parseIntoBinaryLockfile( const dep = &lockfile.buffers.dependencies.items[dep_id]; const dep_name = dep.name.slice(lockfile.buffers.string_bytes.items); - const workspace_node_modules = bun.fmt.bufPrint(&path_buf, "{s}/{s}", .{ workspace_name, dep_name }) catch { + const workspace_node_modules = std.fmt.bufPrint(&path_buf, "{s}/{s}", .{ workspace_name, dep_name }) catch { try log.addErrorFmt(source, root_pkg_exr.loc, allocator, "Workspace and dependency name too long: '{s}/{s}'", .{ workspace_name, dep_name }); return error.InvalidPackageInfo; }; diff --git a/src/install/extract_tarball.zig b/src/install/extract_tarball.zig index ef78639e45..0278611a5d 100644 --- a/src/install/extract_tarball.zig +++ b/src/install/extract_tarball.zig @@ -231,7 +231,7 @@ fn extract(this: *const ExtractTarball, tgz_bytes: []const u8) !Install.ExtractD if (PackageManager.verbose_install) { const decompressing_ended_at: u64 = bun.getRoughTickCount().ns(); const elapsed = decompressing_ended_at - time_started_for_verbose_logs; - Output.prettyErrorln("[{s}] Extract {s} (decompressed {} tgz file in {})", .{ name, tmpname, bun.fmt.size(tgz_bytes.len, .{}), bun.fmt.fmtDuration(elapsed) }); + Output.prettyErrorln("[{s}] Extract {s} (decompressed {} tgz file in {})", .{ name, tmpname, bun.fmt.size(tgz_bytes.len, .{}), std.fmt.fmtDuration(elapsed) }); } switch (this.resolution.tag) { @@ -293,7 +293,7 @@ fn extract(this: *const ExtractTarball, tgz_bytes: []const u8) !Install.ExtractD if (PackageManager.verbose_install) { const elapsed = bun.getRoughTickCount().ns() - time_started_for_verbose_logs; - Output.prettyErrorln("[{s}] Extracted to {s} ({})", .{ name, tmpname, bun.fmt.fmtDuration(elapsed) }); + Output.prettyErrorln("[{s}] Extracted to {s} ({})", .{ name, tmpname, std.fmt.fmtDuration(elapsed) }); Output.flush(); } } diff --git a/src/install/install.zig b/src/install/install.zig index ce8ad53dae..997ed8348d 100644 --- a/src/install/install.zig +++ b/src/install/install.zig @@ -3773,7 +3773,7 @@ pub const PackageManager = struct { try PATH.appendSlice(this.node_gyp_tempdir_name); try this.env.map.put("PATH", PATH.items); - const npm_config_node_gyp = try bun.fmt.bufPrint(&path_buf, "{s}{s}{s}{s}{s}", .{ + const npm_config_node_gyp = try std.fmt.bufPrint(&path_buf, "{s}{s}{s}{s}{s}", .{ strings.withoutTrailingSlash(this.temp_dir_name), std.fs.path.sep_str, strings.withoutTrailingSlash(this.node_gyp_tempdir_name), diff --git a/src/install/lockfile.zig b/src/install/lockfile.zig index 4d97df2737..c4c06cae11 100644 --- a/src/install/lockfile.zig +++ b/src/install/lockfile.zig @@ -2549,9 +2549,9 @@ pub fn saveToDisk(this: *Lockfile, load_result: *const LoadResult, options: *con var base64_bytes: [8]u8 = undefined; bun.rand(&base64_bytes); const tmpname = if (save_format == .text) - std.fmt.bufPrintZ(&tmpname_buf, ".lock-{s}.tmp", .{bun.fmt.fmtSliceHexLower(&base64_bytes)}) catch unreachable + std.fmt.bufPrintZ(&tmpname_buf, ".lock-{s}.tmp", .{std.fmt.fmtSliceHexLower(&base64_bytes)}) catch unreachable else - std.fmt.bufPrintZ(&tmpname_buf, ".lockb-{s}.tmp", .{bun.fmt.fmtSliceHexLower(&base64_bytes)}) catch unreachable; + std.fmt.bufPrintZ(&tmpname_buf, ".lockb-{s}.tmp", .{std.fmt.fmtSliceHexLower(&base64_bytes)}) catch unreachable; const file = switch (File.openat(std.fs.cwd(), tmpname, bun.O.CREAT | bun.O.WRONLY, 0o777)) { .err => |err| { diff --git a/src/io/io_darwin.zig b/src/io/io_darwin.zig deleted file mode 100644 index 71fb60d661..0000000000 --- a/src/io/io_darwin.zig +++ /dev/null @@ -1,211 +0,0 @@ -const std = @import("std"); -const os = struct { - pub usingnamespace std.posix; - pub const EINTR = 4; - pub const EAGAIN = 35; - pub const EBADF = 9; - pub const ECONNRESET = 54; - pub const EFAULT = 14; - pub const EINVAL = 22; - pub const EIO = 5; - pub const EISDIR = 21; - pub const ENOBUFS = 55; - pub const ENOMEM = 12; - pub const ENXIO = 6; - pub const EOVERFLOW = 84; - pub const ESPIPE = 29; -}; - -const socket_t = os.socket_t; -const sockaddr = darwin.sockaddr; -const socklen_t = darwin.socklen_t; -pub const system = darwin; - -const fd_t = os.fd_t; - -const mem = std.mem; -const assert = bun.assert; -const c = std.c; -const bun = @import("root").bun; -pub const darwin = struct { - pub usingnamespace c; - pub extern "c" fn @"recvfrom$NOCANCEL"(sockfd: c.fd_t, noalias buf: *anyopaque, len: usize, flags: u32, noalias src_addr: ?*c.sockaddr, noalias addrlen: ?*c.socklen_t) isize; - pub extern "c" fn @"sendto$NOCANCEL"(sockfd: c.fd_t, buf: *const anyopaque, len: usize, flags: u32, dest_addr: ?*const c.sockaddr, addrlen: c.socklen_t) isize; - pub extern "c" fn @"fcntl$NOCANCEL"(fd: c.fd_t, cmd: c_int, ...) c_int; - // pub extern "c" fn @"sendmsg$NOCANCEL"(sockfd: c.fd_t, msg: *const std.x.os.Socket.Message, flags: c_int) isize; - // pub extern "c" fn @"recvmsg$NOCANCEL"(sockfd: c.fd_t, msg: *std.x.os.Socket.Message, flags: c_int) isize; - pub extern "c" fn @"connect$NOCANCEL"(sockfd: c.fd_t, sock_addr: *const c.sockaddr, addrlen: c.socklen_t) c_int; - pub extern "c" fn @"accept$NOCANCEL"(sockfd: c.fd_t, noalias addr: ?*c.sockaddr, noalias addrlen: ?*c.socklen_t) c_int; - pub extern "c" fn @"accept4$NOCANCEL"(sockfd: c.fd_t, noalias addr: ?*c.sockaddr, noalias addrlen: ?*c.socklen_t, flags: c_uint) c_int; - pub extern "c" fn @"open$NOCANCEL"(path: [*:0]const u8, oflag: c_uint, ...) c_int; - // https://opensource.apple.com/source/xnu/xnu-7195.81.3/libsyscall/wrappers/open-base.c - pub extern "c" fn @"openat$NOCANCEL"(fd: c.fd_t, path: [*:0]const u8, oflag: c_uint, ...) c_int; - pub extern "c" fn @"read$NOCANCEL"(fd: c.fd_t, buf: [*]u8, nbyte: usize) isize; - pub extern "c" fn @"pread$NOCANCEL"(fd: c.fd_t, buf: [*]u8, nbyte: usize, offset: c.off_t) isize; - pub extern "c" fn @"preadv$NOCANCEL"(fd: c.fd_t, uf: [*]std.posix.iovec, count: i32, offset: c.off_t) isize; - pub extern "c" fn @"readv$NOCANCEL"(fd: c.fd_t, uf: [*]std.posix.iovec, count: i32) isize; - pub extern "c" fn @"write$NOCANCEL"(fd: c.fd_t, buf: [*]const u8, nbyte: usize) isize; - pub extern "c" fn @"writev$NOCANCEL"(fd: c.fd_t, buf: [*]const std.posix.iovec_const, count: i32) isize; - pub extern "c" fn @"pwritev$NOCANCEL"(fd: c.fd_t, buf: [*]const std.posix.iovec_const, count: i32, offset: c.off_t) isize; -}; -const IO = @This(); - -pub fn init(_: u12, _: u32, waker: Waker) !IO { - return IO{ - .waker = waker, - }; -} -const Kevent64 = std.posix.system.kevent64_s; -pub const Waker = struct { - kq: os.fd_t, - machport: *anyopaque = undefined, - machport_buf: []u8 = &.{}, - has_pending_wake: bool = false, - - const zeroed = std.mem.zeroes([16]Kevent64); - - pub fn wake(this: *Waker) void { - bun.JSC.markBinding(@src()); - - if (io_darwin_schedule_wakeup(this.machport)) { - this.has_pending_wake = false; - return; - } - this.has_pending_wake = true; - } - - pub fn getFd(this: *const Waker) bun.FileDescriptor { - return bun.toFD(this.kq); - } - - pub fn wait(this: Waker) void { - bun.JSC.markBinding(@src()); - var events = zeroed; - - _ = std.posix.system.kevent64( - this.kq, - &events, - 0, - &events, - events.len, - 0, - null, - ); - } - - extern fn io_darwin_create_machport( - *anyopaque, - os.fd_t, - *anyopaque, - usize, - ) ?*anyopaque; - - extern fn io_darwin_schedule_wakeup( - *anyopaque, - ) bool; - - pub fn init() !Waker { - return initWithFileDescriptor(bun.default_allocator, try std.posix.kqueue()); - } - - pub fn initWithFileDescriptor(allocator: std.mem.Allocator, kq: i32) !Waker { - bun.JSC.markBinding(@src()); - assert(kq > -1); - const machport_buf = try allocator.alloc(u8, 1024); - const machport = io_darwin_create_machport( - machport_buf.ptr, - kq, - machport_buf.ptr, - 1024, - ) orelse return error.MachportCreationFailed; - - return Waker{ - .kq = kq, - .machport = machport, - .machport_buf = machport_buf, - }; - } -}; - -// pub const UserFilterWaker = struct { -// kq: os.fd_t, -// ident: u64 = undefined, - -// pub fn wake(this: UserFilterWaker) !void { -// bun.JSC.markBinding(@src()); -// var events = zeroed; -// events[0].ident = this.ident; -// events[0].filter = c.EVFILT_USER; -// events[0].data = 0; -// events[0].fflags = c.NOTE_TRIGGER; -// events[0].udata = 0; -// const errno = std.posix.system.kevent64( -// this.kq, -// &events, -// 1, -// &events, -// events.len, -// 0, -// null, -// ); - -// if (errno < 0) { -// return asError(bun.C.getErrno(errno)); -// } -// } - -// const zeroed = std.mem.zeroes([16]Kevent64); - -// pub fn wait(this: UserFilterWaker) !u64 { -// var events = zeroed; -// events[0].ident = 123; -// events[0].filter = c.EVFILT_USER; -// events[0].flags = c.EV_ADD | c.EV_ENABLE; -// events[0].data = 0; -// events[0].udata = 0; - -// const errno = std.posix.system.kevent64( -// this.kq, -// &events, -// 1, -// &events, -// events.len, -// 0, -// null, -// ); -// if (errno < 0) { -// return asError(bun.C.getErrno(errno)); -// } - -// return @as(u64, @intCast(errno)); -// } - -// pub fn init(_: std.mem.Allocator) !UserFilterWaker { -// const kq = try os.kqueue(); -// assert(kq > -1); - -// var events = [1]Kevent64{std.mem.zeroes(Kevent64)}; -// events[0].ident = 123; -// events[0].filter = c.EVFILT_USER; -// events[0].flags = c.EV_ADD | c.EV_ENABLE; -// events[0].data = 0; -// events[0].udata = 0; -// var timespec = default_timespec; -// const errno = std.posix.system.kevent64( -// kq, -// &events, -// 1, -// &events, -// @as(c_int, @intCast(events.len)), -// 0, -// ×pec, -// ); - -// bun.assert(errno == 0); - -// return UserFilterWaker{ -// .kq = kq, -// .ident = 123, -// }; -// } -// }; diff --git a/src/io/io_linux.zig b/src/io/io_linux.zig deleted file mode 100644 index 4b95ceb34c..0000000000 --- a/src/io/io_linux.zig +++ /dev/null @@ -1,173 +0,0 @@ -const std = @import("std"); -const assert = bun.assert; -const Platform = bun.analytics.GenerateHeader.GeneratePlatform; -const os = struct { - pub usingnamespace std.posix; - pub const EPERM = 1; - pub const ENOENT = 2; - pub const ESRCH = 3; - pub const EINTR = 4; - pub const EIO = 5; - pub const ENXIO = 6; - pub const E2BIG = 7; - pub const ENOEXEC = 8; - pub const EBADF = 9; - pub const ECHILD = 10; - pub const EAGAIN = 11; - pub const ENOMEM = 12; - pub const EACCES = 13; - pub const EFAULT = 14; - pub const ENOTBLK = 15; - pub const EBUSY = 16; - pub const EEXIST = 17; - pub const EXDEV = 18; - pub const ENODEV = 19; - pub const ENOTDIR = 20; - pub const EISDIR = 21; - pub const EINVAL = 22; - pub const ENFILE = 23; - pub const EMFILE = 24; - pub const ENOTTY = 25; - pub const ETXTBSY = 26; - pub const EFBIG = 27; - pub const ENOSPC = 28; - pub const ESPIPE = 29; - pub const EROFS = 30; - pub const EMLINK = 31; - pub const EPIPE = 32; - pub const EDOM = 33; - pub const ERANGE = 34; - pub const EDEADLK = 35; - pub const ENAMETOOLONG = 36; - pub const ENOLCK = 37; - pub const ENOSYS = 38; - pub const ENOTEMPTY = 39; - pub const ELOOP = 40; - pub const EWOULDBLOCK = 41; - pub const ENOMSG = 42; - pub const EIDRM = 43; - pub const ECHRNG = 44; - pub const EL2NSYNC = 45; - pub const EL3HLT = 46; - pub const EL3RST = 47; - pub const ELNRNG = 48; - pub const EUNATCH = 49; - pub const ENOCSI = 50; - pub const EL2HLT = 51; - pub const EBADE = 52; - pub const EBADR = 53; - pub const EXFULL = 54; - pub const ENOANO = 55; - pub const EBADRQC = 56; - pub const EBADSLT = 57; - pub const EDEADLOCK = 58; - pub const EBFONT = 59; - pub const ENOSTR = 60; - pub const ENODATA = 61; - pub const ETIME = 62; - pub const ENOSR = 63; - pub const ENONET = 64; - pub const ENOPKG = 65; - pub const EREMOTE = 66; - pub const ENOLINK = 67; - pub const EADV = 68; - pub const ESRMNT = 69; - pub const ECOMM = 70; - pub const EPROTO = 71; - pub const EMULTIHOP = 72; - pub const EDOTDOT = 73; - pub const EBADMSG = 74; - pub const EOVERFLOW = 75; - pub const ENOTUNIQ = 76; - pub const EBADFD = 77; - pub const EREMCHG = 78; - pub const ELIBACC = 79; - pub const ELIBBAD = 80; - pub const ELIBSCN = 81; - pub const ELIBMAX = 82; - pub const ELIBEXEC = 83; - pub const EILSEQ = 84; - pub const ERESTART = 85; - pub const ESTRPIPE = 86; - pub const EUSERS = 87; - pub const ENOTSOCK = 88; - pub const EDESTADDRREQ = 89; - pub const EMSGSIZE = 90; - pub const EPROTOTYPE = 91; - pub const ENOPROTOOPT = 92; - pub const EPROTONOSUPPORT = 93; - pub const ESOCKTNOSUPPORT = 94; - /// For Linux, EOPNOTSUPP is the real value - /// but it's ~the same and is incompatible across operating systems - /// https://lists.gnu.org/archive/html/bug-glibc/2002-08/msg00017.html - pub const ENOTSUP = 95; - pub const EOPNOTSUPP = ENOTSUP; - pub const EPFNOSUPPORT = 96; - pub const EAFNOSUPPORT = 97; - pub const EADDRINUSE = 98; - pub const EADDRNOTAVAIL = 99; - pub const ENETDOWN = 100; - pub const ENETUNREACH = 101; - pub const ENETRESET = 102; - pub const ECONNABORTED = 103; - pub const ECONNRESET = 104; - pub const ENOBUFS = 105; - pub const EISCONN = 106; - pub const ENOTCONN = 107; - pub const ESHUTDOWN = 108; - pub const ETOOMANYREFS = 109; - pub const ETIMEDOUT = 110; - pub const ECONNREFUSED = 111; - pub const EHOSTDOWN = 112; - pub const EHOSTUNREACH = 113; - pub const EALREADY = 114; - pub const EINPROGRESS = 115; - pub const ESTALE = 116; - pub const EUCLEAN = 117; - pub const ENOTNAM = 118; - pub const ENAVAIL = 119; - pub const EISNAM = 120; - pub const EREMOTEIO = 121; - pub const EDQUOT = 122; - pub const ENOMEDIUM = 123; - pub const EMEDIUMTYPE = 124; - pub const ECANCELED = 125; - pub const ENOKEY = 126; - pub const EKEYEXPIRED = 127; - pub const EKEYREVOKED = 128; - pub const EKEYREJECTED = 129; - pub const EOWNERDEAD = 130; - pub const ENOTRECOVERABLE = 131; - pub const ERFKILL = 132; - pub const EHWPOISON = 133; -}; - -const bun = @import("root").bun; -pub const Waker = struct { - fd: bun.FileDescriptor, - - pub fn init() !Waker { - return initWithFileDescriptor(bun.toFD(try std.posix.eventfd(0, 0))); - } - - pub fn getFd(this: *const Waker) bun.FileDescriptor { - return this.fd; - } - - pub fn initWithFileDescriptor(fd: bun.FileDescriptor) Waker { - return Waker{ .fd = fd }; - } - - pub fn wait(this: Waker) void { - var bytes: usize = 0; - _ = std.posix.read(this.fd.cast(), @as(*[8]u8, @ptrCast(&bytes))) catch 0; - } - - pub fn wake(this: *const Waker) void { - var bytes: usize = 1; - _ = std.posix.write( - this.fd.cast(), - @as(*[8]u8, @ptrCast(&bytes)), - ) catch 0; - } -}; diff --git a/src/io/io_stub.zig b/src/io/io_stub.zig deleted file mode 100644 index b1f6d3f579..0000000000 --- a/src/io/io_stub.zig +++ /dev/null @@ -1,11 +0,0 @@ -const std = @import("std"); -const IO = struct { - buffer: i32 = 0, -}; - -pub fn init(_: anytype, _: anytype) anyerror!void {} - -pub var global: IO = undefined; -pub var global_loaded: bool = false; - -fn buffer_limit(_: usize) usize {} diff --git a/src/io/io_windows.zig b/src/io/io_windows.zig deleted file mode 100644 index b684d1b2c7..0000000000 --- a/src/io/io_windows.zig +++ /dev/null @@ -1,3 +0,0 @@ -pub fn init() *@This() { - @panic("ahahhhahahhahahha AsyncIO/io_windows.zig was deleted"); -} diff --git a/src/js_ast.zig b/src/js_ast.zig index 38105e0090..c7093970a8 100644 --- a/src/js_ast.zig +++ b/src/js_ast.zig @@ -7896,7 +7896,7 @@ pub const Macro = struct { const js = @import("./bun.js/javascript_core_c_api.zig"); const Zig = @import("./bun.js/bindings/exports.zig"); const Transpiler = bun.Transpiler; - const MacroEntryPoint = bun.transpiler.MacroEntryPoint; + const MacroEntryPoint = bun.transpiler.EntryPoints.MacroEntryPoint; const MacroRemap = @import("./resolver/package_json.zig").MacroMap; pub const MacroRemapEntry = @import("./resolver/package_json.zig").MacroImportReplacementMap; diff --git a/src/linear_fifo.zig b/src/linear_fifo.zig index 685d0c9aa3..62f8f24e03 100644 --- a/src/linear_fifo.zig +++ b/src/linear_fifo.zig @@ -54,39 +54,39 @@ pub fn LinearFifo( // returned a slice into a copy on the stack const SliceSelfArg = if (buffer_type == .Static) *Self else Self; - pub usingnamespace switch (buffer_type) { - .Static => struct { - pub fn init() Self { - return .{ - .allocator = {}, - .buf = undefined, - .head = 0, - .count = 0, - }; - } - }, - .Slice => struct { - pub fn init(buf: []T) Self { - return .{ - .allocator = {}, - .buf = buf, - .head = 0, - .count = 0, - }; - } - }, - .Dynamic => struct { - pub fn init(allocator: Allocator) Self { - return .{ - .allocator = allocator, - .buf = &[_]T{}, - .head = 0, - .count = 0, - }; - } - }, + pub const init = switch (buffer_type) { + .Static => initStatic, + .Slice => initSlice, + .Dynamic => initDynamic, }; + fn initStatic() Self { + return .{ + .allocator = {}, + .buf = undefined, + .head = 0, + .count = 0, + }; + } + + fn initSlice(buf: []T) Self { + return .{ + .allocator = {}, + .buf = buf, + .head = 0, + .count = 0, + }; + } + + fn initDynamic(allocator: Allocator) Self { + return .{ + .allocator = allocator, + .buf = &[_]T{}, + .head = 0, + .count = 0, + }; + } + pub fn deinit(self: Self) void { if (buffer_type == .Dynamic) self.allocator.free(self.buf); } diff --git a/src/main.zig b/src/main.zig index 5dfc2f2bac..63d0a6fee2 100644 --- a/src/main.zig +++ b/src/main.zig @@ -1,6 +1,6 @@ const std = @import("std"); const builtin = @import("builtin"); -const bun = @import("root").bun; +pub const bun = @import("./bun.zig"); const Output = bun.Output; const Environment = bun.Environment; @@ -16,8 +16,10 @@ comptime { } extern fn bun_warn_avx_missing(url: [*:0]const u8) void; + pub extern "c" var _environ: ?*anyopaque; pub extern "c" var environ: ?*anyopaque; + pub fn main() void { bun.crash_handler.init(); @@ -62,3 +64,21 @@ pub fn main() void { pub export fn Bun__panic(msg: [*]const u8, len: usize) noreturn { Output.panic("{s}", .{msg[0..len]}); } + +// -- Zig Standard Library Additions -- +pub fn copyForwards(comptime T: type, dest: []T, source: []const T) void { + if (source.len == 0) { + return; + } + bun.copy(T, dest[0..source.len], source); +} +pub fn copyBackwards(comptime T: type, dest: []T, source: []const T) void { + if (source.len == 0) { + return; + } + bun.copy(T, dest[0..source.len], source); +} +pub fn eqlBytes(src: []const u8, dest: []const u8) bool { + return bun.C.memcmp(src.ptr, dest.ptr, src.len) == 0; +} +// -- End Zig Standard Library Additions -- diff --git a/src/meta.zig b/src/meta.zig index 3b29f33bb0..95573ec620 100644 --- a/src/meta.zig +++ b/src/meta.zig @@ -1,8 +1,6 @@ const std = @import("std"); const bun = @import("root").bun; -pub usingnamespace std.meta; - pub fn OptionalChild(comptime T: type) type { const tyinfo = @typeInfo(T); if (tyinfo != .pointer) @compileError("OptionalChild(T) requires that T be a pointer to an optional type."); diff --git a/src/s3/credentials.zig b/src/s3/credentials.zig index a8701f3353..b0cd832a56 100644 --- a/src/s3/credentials.zig +++ b/src/s3/credentials.zig @@ -674,7 +674,7 @@ pub const S3Credentials = struct { var sha_digest = std.mem.zeroes(bun.sha.SHA256.Digest); bun.sha.SHA256.hash(canonical, &sha_digest, JSC.VirtualMachine.get().rareData().boringEngine()); - const signValue = try std.fmt.bufPrint(&tmp_buffer, "AWS4-HMAC-SHA256\n{s}\n{s}/{s}/{s}/aws4_request\n{s}", .{ amz_date, amz_day, region, service_name, bun.fmt.bytesToHex(sha_digest[0..bun.sha.SHA256.digest], .lower) }); + const signValue = try std.fmt.bufPrint(&tmp_buffer, "AWS4-HMAC-SHA256\n{s}\n{s}/{s}/{s}/aws4_request\n{s}", .{ amz_date, amz_day, region, service_name, std.fmt.bytesToHex(sha_digest[0..bun.sha.SHA256.digest], .lower) }); const signature = bun.hmac.generate(sigDateRegionServiceReq, signValue, .sha256, &hmac_sig_service) orelse return error.FailedToGenerateSignature; @@ -684,13 +684,13 @@ pub const S3Credentials = struct { break :brk try std.fmt.allocPrint( bun.default_allocator, "{s}://{s}{s}?X-Amz-Acl={s}&x-amz-storage-class={s}&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential={s}%2F{s}%2F{s}%2F{s}%2Faws4_request&X-Amz-Date={s}&X-Amz-Expires={}&X-Amz-Security-Token={s}&X-Amz-SignedHeaders=host&X-Amz-Signature={s}", - .{ protocol, host, normalizedPath, acl_value, storage_class_value, this.accessKeyId, amz_day, region, service_name, amz_date, expires, token, bun.fmt.bytesToHex(signature[0..DIGESTED_HMAC_256_LEN], .lower) }, + .{ protocol, host, normalizedPath, acl_value, storage_class_value, this.accessKeyId, amz_day, region, service_name, amz_date, expires, token, std.fmt.bytesToHex(signature[0..DIGESTED_HMAC_256_LEN], .lower) }, ); } else { break :brk try std.fmt.allocPrint( bun.default_allocator, "{s}://{s}{s}?X-Amz-Acl={s}&x-amz-storage-class={s}&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential={s}%2F{s}%2F{s}%2F{s}%2Faws4_request&X-Amz-Date={s}&X-Amz-Expires={}&X-Amz-SignedHeaders=host&X-Amz-Signature={s}", - .{ protocol, host, normalizedPath, acl_value, storage_class_value, this.accessKeyId, amz_day, region, service_name, amz_date, expires, bun.fmt.bytesToHex(signature[0..DIGESTED_HMAC_256_LEN], .lower) }, + .{ protocol, host, normalizedPath, acl_value, storage_class_value, this.accessKeyId, amz_day, region, service_name, amz_date, expires, std.fmt.bytesToHex(signature[0..DIGESTED_HMAC_256_LEN], .lower) }, ); } } else { @@ -698,13 +698,13 @@ pub const S3Credentials = struct { break :brk try std.fmt.allocPrint( bun.default_allocator, "{s}://{s}{s}?x-amz-storage-class={s}&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential={s}%2F{s}%2F{s}%2F{s}%2Faws4_request&X-Amz-Date={s}&X-Amz-Expires={}&X-Amz-Security-Token={s}&X-Amz-SignedHeaders=host&X-Amz-Signature={s}", - .{ protocol, host, normalizedPath, storage_class_value, this.accessKeyId, amz_day, region, service_name, amz_date, expires, token, bun.fmt.bytesToHex(signature[0..DIGESTED_HMAC_256_LEN], .lower) }, + .{ protocol, host, normalizedPath, storage_class_value, this.accessKeyId, amz_day, region, service_name, amz_date, expires, token, std.fmt.bytesToHex(signature[0..DIGESTED_HMAC_256_LEN], .lower) }, ); } else { break :brk try std.fmt.allocPrint( bun.default_allocator, "{s}://{s}{s}?x-amz-storage-class={s}&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential={s}%2F{s}%2F{s}%2F{s}%2Faws4_request&X-Amz-Date={s}&X-Amz-Expires={}&X-Amz-SignedHeaders=host&X-Amz-Signature={s}", - .{ protocol, host, normalizedPath, storage_class_value, this.accessKeyId, amz_day, region, service_name, amz_date, expires, bun.fmt.bytesToHex(signature[0..DIGESTED_HMAC_256_LEN], .lower) }, + .{ protocol, host, normalizedPath, storage_class_value, this.accessKeyId, amz_day, region, service_name, amz_date, expires, std.fmt.bytesToHex(signature[0..DIGESTED_HMAC_256_LEN], .lower) }, ); } } @@ -714,13 +714,13 @@ pub const S3Credentials = struct { break :brk try std.fmt.allocPrint( bun.default_allocator, "{s}://{s}{s}?X-Amz-Acl={s}&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential={s}%2F{s}%2F{s}%2F{s}%2Faws4_request&X-Amz-Date={s}&X-Amz-Expires={}&X-Amz-Security-Token={s}&X-Amz-SignedHeaders=host&X-Amz-Signature={s}", - .{ protocol, host, normalizedPath, acl_value, this.accessKeyId, amz_day, region, service_name, amz_date, expires, token, bun.fmt.bytesToHex(signature[0..DIGESTED_HMAC_256_LEN], .lower) }, + .{ protocol, host, normalizedPath, acl_value, this.accessKeyId, amz_day, region, service_name, amz_date, expires, token, std.fmt.bytesToHex(signature[0..DIGESTED_HMAC_256_LEN], .lower) }, ); } else { break :brk try std.fmt.allocPrint( bun.default_allocator, "{s}://{s}{s}?X-Amz-Acl={s}&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential={s}%2F{s}%2F{s}%2F{s}%2Faws4_request&X-Amz-Date={s}&X-Amz-Expires={}&X-Amz-SignedHeaders=host&X-Amz-Signature={s}", - .{ protocol, host, normalizedPath, acl_value, this.accessKeyId, amz_day, region, service_name, amz_date, expires, bun.fmt.bytesToHex(signature[0..DIGESTED_HMAC_256_LEN], .lower) }, + .{ protocol, host, normalizedPath, acl_value, this.accessKeyId, amz_day, region, service_name, amz_date, expires, std.fmt.bytesToHex(signature[0..DIGESTED_HMAC_256_LEN], .lower) }, ); } } else { @@ -728,13 +728,13 @@ pub const S3Credentials = struct { break :brk try std.fmt.allocPrint( bun.default_allocator, "{s}://{s}{s}?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential={s}%2F{s}%2F{s}%2F{s}%2Faws4_request&X-Amz-Date={s}&X-Amz-Expires={}&X-Amz-Security-Token={s}&X-Amz-SignedHeaders=host&X-Amz-Signature={s}", - .{ protocol, host, normalizedPath, this.accessKeyId, amz_day, region, service_name, amz_date, expires, token, bun.fmt.bytesToHex(signature[0..DIGESTED_HMAC_256_LEN], .lower) }, + .{ protocol, host, normalizedPath, this.accessKeyId, amz_day, region, service_name, amz_date, expires, token, std.fmt.bytesToHex(signature[0..DIGESTED_HMAC_256_LEN], .lower) }, ); } else { break :brk try std.fmt.allocPrint( bun.default_allocator, "{s}://{s}{s}?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential={s}%2F{s}%2F{s}%2F{s}%2Faws4_request&X-Amz-Date={s}&X-Amz-Expires={}&X-Amz-SignedHeaders=host&X-Amz-Signature={s}", - .{ protocol, host, normalizedPath, this.accessKeyId, amz_day, region, service_name, amz_date, expires, bun.fmt.bytesToHex(signature[0..DIGESTED_HMAC_256_LEN], .lower) }, + .{ protocol, host, normalizedPath, this.accessKeyId, amz_day, region, service_name, amz_date, expires, std.fmt.bytesToHex(signature[0..DIGESTED_HMAC_256_LEN], .lower) }, ); } } @@ -808,14 +808,14 @@ pub const S3Credentials = struct { var sha_digest = std.mem.zeroes(bun.sha.SHA256.Digest); bun.sha.SHA256.hash(canonical, &sha_digest, JSC.VirtualMachine.get().rareData().boringEngine()); - const signValue = try std.fmt.bufPrint(&tmp_buffer, "AWS4-HMAC-SHA256\n{s}\n{s}/{s}/{s}/aws4_request\n{s}", .{ amz_date, amz_day, region, service_name, bun.fmt.bytesToHex(sha_digest[0..bun.sha.SHA256.digest], .lower) }); + const signValue = try std.fmt.bufPrint(&tmp_buffer, "AWS4-HMAC-SHA256\n{s}\n{s}/{s}/{s}/aws4_request\n{s}", .{ amz_date, amz_day, region, service_name, std.fmt.bytesToHex(sha_digest[0..bun.sha.SHA256.digest], .lower) }); const signature = bun.hmac.generate(sigDateRegionServiceReq, signValue, .sha256, &hmac_sig_service) orelse return error.FailedToGenerateSignature; break :brk try std.fmt.allocPrint( bun.default_allocator, "AWS4-HMAC-SHA256 Credential={s}/{s}/{s}/{s}/aws4_request, SignedHeaders={s}, Signature={s}", - .{ this.accessKeyId, amz_day, region, service_name, signed_headers, bun.fmt.bytesToHex(signature[0..DIGESTED_HMAC_256_LEN], .lower) }, + .{ this.accessKeyId, amz_day, region, service_name, signed_headers, std.fmt.bytesToHex(signature[0..DIGESTED_HMAC_256_LEN], .lower) }, ); } }; diff --git a/src/shell/interpreter.zig b/src/shell/interpreter.zig index d2a08a3f4d..4d27d4cb4a 100644 --- a/src/shell/interpreter.zig +++ b/src/shell/interpreter.zig @@ -10149,13 +10149,13 @@ pub const Interpreter = struct { } const maybe1 = iter.next().?; - const int1 = bun.fmt.parseFloat(f32, bun.sliceTo(maybe1, 0)) catch return this.fail("seq: invalid argument\n"); + const int1 = std.fmt.parseFloat(f32, bun.sliceTo(maybe1, 0)) catch return this.fail("seq: invalid argument\n"); this._end = int1; if (this._start > this._end) this.increment = -1; const maybe2 = iter.next(); if (maybe2 == null) return this.do(); - const int2 = bun.fmt.parseFloat(f32, bun.sliceTo(maybe2.?, 0)) catch return this.fail("seq: invalid argument\n"); + const int2 = std.fmt.parseFloat(f32, bun.sliceTo(maybe2.?, 0)) catch return this.fail("seq: invalid argument\n"); this._start = int1; this._end = int2; if (this._start < this._end) this.increment = 1; @@ -10163,7 +10163,7 @@ pub const Interpreter = struct { const maybe3 = iter.next(); if (maybe3 == null) return this.do(); - const int3 = bun.fmt.parseFloat(f32, bun.sliceTo(maybe3.?, 0)) catch return this.fail("seq: invalid argument\n"); + const int3 = std.fmt.parseFloat(f32, bun.sliceTo(maybe3.?, 0)) catch return this.fail("seq: invalid argument\n"); this._start = int1; this.increment = int2; this._end = int3; diff --git a/src/shell/shell.zig b/src/shell/shell.zig index ce13900af1..20ebf2f86a 100644 --- a/src/shell/shell.zig +++ b/src/shell/shell.zig @@ -4458,3 +4458,5 @@ pub const TestingAPIs = struct { }; const assert = bun.assert; + +pub const ShellSubprocess = @import("subproc.zig").ShellSubprocess; diff --git a/src/sourcemap/CodeCoverage.zig b/src/sourcemap/CodeCoverage.zig index 2075f1d4c9..dad0903f87 100644 --- a/src/sourcemap/CodeCoverage.zig +++ b/src/sourcemap/CodeCoverage.zig @@ -21,7 +21,7 @@ const prettyFmt = Output.prettyFmt; /// We use two bitsets since the typical size will be decently small, /// bitsets are simple and bitsets are relatively fast to construct and query /// -pub const CodeCoverageReport = struct { +pub const Report = struct { source_url: bun.JSC.ZigString.Slice, executable_lines: Bitset, lines_which_have_executed: Bitset, @@ -32,7 +32,7 @@ pub const CodeCoverageReport = struct { stmts: std.ArrayListUnmanaged(Block), total_lines: u32 = 0, - pub fn linesCoverageFraction(this: *const CodeCoverageReport) f64 { + pub fn linesCoverageFraction(this: *const Report) f64 { var intersected = this.executable_lines.clone(bun.default_allocator) catch bun.outOfMemory(); defer intersected.deinit(bun.default_allocator); intersected.setIntersection(this.lines_which_have_executed); @@ -47,7 +47,7 @@ pub const CodeCoverageReport = struct { return (intersected_count / total_count); } - pub fn stmtsCoverageFraction(this: *const CodeCoverageReport) f64 { + pub fn stmtsCoverageFraction(this: *const Report) f64 { const total_count: f64 = @floatFromInt(this.stmts.items.len); if (total_count == 0) { @@ -57,7 +57,7 @@ pub const CodeCoverageReport = struct { return ((@as(f64, @floatFromInt(this.stmts_which_have_executed.count()))) / (total_count)); } - pub fn functionCoverageFraction(this: *const CodeCoverageReport) f64 { + pub fn functionCoverageFraction(this: *const Report) f64 { const total_count: f64 = @floatFromInt(this.functions.items.len); if (total_count == 0) { return 1.0; @@ -69,8 +69,8 @@ pub const CodeCoverageReport = struct { pub fn writeFormatWithValues( filename: []const u8, max_filename_length: usize, - vals: CoverageFraction, - failing: CoverageFraction, + vals: Fraction, + failing: Fraction, failed: bool, writer: anytype, indent_name: bool, @@ -124,9 +124,9 @@ pub const CodeCoverageReport = struct { } pub fn writeFormat( - report: *const CodeCoverageReport, + report: *const Report, max_filename_length: usize, - fraction: *CoverageFraction, + fraction: *Fraction, base_path: []const u8, writer: anytype, comptime enable_colors: bool, @@ -216,7 +216,7 @@ pub const CodeCoverageReport = struct { pub const Lcov = struct { pub fn writeFormat( - report: *const CodeCoverageReport, + report: *const Report, base_path: []const u8, writer: anytype, ) !void { @@ -268,7 +268,7 @@ pub const CodeCoverageReport = struct { } }; - pub fn deinit(this: *CodeCoverageReport, allocator: std.mem.Allocator) void { + pub fn deinit(this: *Report, allocator: std.mem.Allocator) void { this.executable_lines.deinit(allocator); this.lines_which_have_executed.deinit(allocator); this.line_hits.deinitWithAllocator(allocator); @@ -295,7 +295,7 @@ pub const CodeCoverageReport = struct { const Generator = struct { allocator: std.mem.Allocator, byte_range_mapping: *ByteRangeMapping, - result: *?CodeCoverageReport, + result: *?Report, pub fn do( this: *@This(), @@ -329,11 +329,11 @@ pub const CodeCoverageReport = struct { allocator: std.mem.Allocator, byte_range_mapping: *ByteRangeMapping, ignore_sourcemap_: bool, - ) ?CodeCoverageReport { + ) ?Report { bun.JSC.markBinding(@src()); const vm = globalThis.vm(); - var result: ?CodeCoverageReport = null; + var result: ?Report = null; var generator = Generator{ .result = &result, @@ -418,7 +418,7 @@ pub const ByteRangeMapping = struct { blocks: []const BasicBlockRange, function_blocks: []const BasicBlockRange, ignore_sourcemap: bool, - ) !CodeCoverageReport { + ) !Report { const line_starts = this.line_offset_table.items(.byte_offset_to_start_of_line); var executable_lines: Bitset = Bitset{}; @@ -677,14 +677,14 @@ pub const ByteRangeMapping = struct { }; defer report.deinit(bun.default_allocator); - var coverage_fraction = CoverageFraction{}; + var coverage_fraction = Fraction{}; var mutable_str = bun.MutableString.initEmpty(bun.default_allocator); defer mutable_str.deinit(); var buffered_writer = mutable_str.bufferedWriter(); var writer = buffered_writer.writer(); - CodeCoverageReport.Text.writeFormat(&report, source_url.utf8ByteLength(), &coverage_fraction, "", &writer, false) catch { + Report.Text.writeFormat(&report, source_url.utf8ByteLength(), &coverage_fraction, "", &writer, false) catch { return globalThis.throwOutOfMemoryValue(); }; @@ -713,7 +713,7 @@ comptime { } } -pub const CoverageFraction = struct { +pub const Fraction = struct { functions: f64 = 0.9, lines: f64 = 0.9, diff --git a/src/sourcemap/sourcemap.zig b/src/sourcemap/sourcemap.zig index bca26ab6ac..ac9c365241 100644 --- a/src/sourcemap/sourcemap.zig +++ b/src/sourcemap/sourcemap.zig @@ -1962,4 +1962,4 @@ pub const DebugIDFormatter = struct { const assert = bun.assert; -pub usingnamespace @import("./CodeCoverage.zig"); +pub const coverage = @import("./CodeCoverage.zig"); diff --git a/src/sql/postgres.zig b/src/sql/postgres.zig index eda2a906da..4d206ed461 100644 --- a/src/sql/postgres.zig +++ b/src/sql/postgres.zig @@ -2684,7 +2684,7 @@ pub const PostgresSQLConnection = struct { switch (arrayType) { .int8_array => { if (bigint) { - try array.append(bun.default_allocator, DataCell{ .tag = .int8, .value = .{ .int8 = bun.fmt.parseInt(i64, element, 0) catch return error.UnsupportedArrayFormat } }); + try array.append(bun.default_allocator, DataCell{ .tag = .int8, .value = .{ .int8 = std.fmt.parseInt(i64, element, 0) catch return error.UnsupportedArrayFormat } }); } else { try array.append(bun.default_allocator, DataCell{ .tag = .string, .value = .{ .string = if (element.len > 0) bun.String.createUTF8(element).value.WTFStringImpl else null }, .free_value = 1 }); } @@ -2692,12 +2692,12 @@ pub const PostgresSQLConnection = struct { continue; }, .cid_array, .xid_array, .oid_array => { - try array.append(bun.default_allocator, DataCell{ .tag = .uint4, .value = .{ .uint4 = bun.fmt.parseInt(u32, element, 0) catch 0 } }); + try array.append(bun.default_allocator, DataCell{ .tag = .uint4, .value = .{ .uint4 = std.fmt.parseInt(u32, element, 0) catch 0 } }); slice = trySlice(slice, current_idx); continue; }, else => { - const value = bun.fmt.parseInt(i32, element, 0) catch return error.UnsupportedArrayFormat; + const value = std.fmt.parseInt(i32, element, 0) catch return error.UnsupportedArrayFormat; try array.append(bun.default_allocator, DataCell{ .tag = .int4, .value = .{ .int4 = @intCast(value) } }); slice = trySlice(slice, current_idx); @@ -2794,28 +2794,28 @@ pub const PostgresSQLConnection = struct { if (binary) { return DataCell{ .tag = .int4, .value = .{ .int4 = try parseBinary(.int2, i16, bytes) } }; } else { - return DataCell{ .tag = .int4, .value = .{ .int4 = bun.fmt.parseInt(i32, bytes, 0) catch 0 } }; + return DataCell{ .tag = .int4, .value = .{ .int4 = std.fmt.parseInt(i32, bytes, 0) catch 0 } }; } }, .cid, .xid, .oid => { if (binary) { return DataCell{ .tag = .uint4, .value = .{ .uint4 = try parseBinary(.oid, u32, bytes) } }; } else { - return DataCell{ .tag = .uint4, .value = .{ .uint4 = bun.fmt.parseInt(u32, bytes, 0) catch 0 } }; + return DataCell{ .tag = .uint4, .value = .{ .uint4 = std.fmt.parseInt(u32, bytes, 0) catch 0 } }; } }, .int4 => { if (binary) { return DataCell{ .tag = .int4, .value = .{ .int4 = try parseBinary(.int4, i32, bytes) } }; } else { - return DataCell{ .tag = .int4, .value = .{ .int4 = bun.fmt.parseInt(i32, bytes, 0) catch 0 } }; + return DataCell{ .tag = .int4, .value = .{ .int4 = std.fmt.parseInt(i32, bytes, 0) catch 0 } }; } }, // postgres when reading bigint as int8 it returns a string unless type: { bigint: postgres.BigInt is set .int8 => { if (bigint) { // .int8 is a 64-bit integer always string - return DataCell{ .tag = .int8, .value = .{ .int8 = bun.fmt.parseInt(i64, bytes, 0) catch 0 } }; + return DataCell{ .tag = .int8, .value = .{ .int8 = std.fmt.parseInt(i64, bytes, 0) catch 0 } }; } else { return DataCell{ .tag = .string, .value = .{ .string = if (bytes.len > 0) bun.String.createUTF8(bytes).value.WTFStringImpl else null }, .free_value = 1 }; } @@ -4123,7 +4123,7 @@ const Signature = struct { return error.InvalidQueryBinding; } // max u64 length is 20, max prepared_statement_name length is 63 - const prepared_statement_name = try bun.fmt.allocPrint(bun.default_allocator, "P{s}${d}", .{ name.items[0..@min(40, name.items.len)], prepared_statement_id }); + const prepared_statement_name = try std.fmt.allocPrint(bun.default_allocator, "P{s}${d}", .{ name.items[0..@min(40, name.items.len)], prepared_statement_id }); return Signature{ .prepared_statement_name = prepared_statement_name, diff --git a/src/string_mutable.zig b/src/string_mutable.zig index 6b3b08aa4c..6e01507ada 100644 --- a/src/string_mutable.zig +++ b/src/string_mutable.zig @@ -224,7 +224,7 @@ pub const MutableString = struct { try self.list.ensureUnusedCapacity(self.allocator, count); const old = self.list.items.len; self.list.items.len += count; - bun.assert(count == bun.fmt.formatIntBuf(self.list.items.ptr[old .. old + count], int, 10, .lower, .{})); + bun.assert(count == std.fmt.formatIntBuf(self.list.items.ptr[old .. old + count], int, 10, .lower, .{})); } pub inline fn appendAssumeCapacity(self: *MutableString, char: []const u8) void { diff --git a/src/sys.zig b/src/sys.zig index 7221d32973..a52db013ef 100644 --- a/src/sys.zig +++ b/src/sys.zig @@ -37,14 +37,34 @@ pub const syslog = log; pub const syscall = switch (Environment.os) { .linux => std.os.linux, - - // This is actually libc on MacOS // We don't directly use the Darwin syscall interface. - .mac => bun.AsyncIO.system, - + .mac => std.c, else => @compileError("not implemented"), }; +/// Non-cancellable verisons of various libc functions are undocumented +const darwin_nocancel = struct { + const c = std.c; + pub extern "c" fn @"recvfrom$NOCANCEL"(sockfd: c.fd_t, noalias buf: *anyopaque, len: usize, flags: u32, noalias src_addr: ?*c.sockaddr, noalias addrlen: ?*c.socklen_t) isize; + pub extern "c" fn @"sendto$NOCANCEL"(sockfd: c.fd_t, buf: *const anyopaque, len: usize, flags: u32, dest_addr: ?*const c.sockaddr, addrlen: c.socklen_t) isize; + pub extern "c" fn @"fcntl$NOCANCEL"(fd: c.fd_t, cmd: c_int, ...) c_int; + // pub extern "c" fn @"sendmsg$NOCANCEL"(sockfd: c.fd_t, msg: *const std.x.os.Socket.Message, flags: c_int) isize; + // pub extern "c" fn @"recvmsg$NOCANCEL"(sockfd: c.fd_t, msg: *std.x.os.Socket.Message, flags: c_int) isize; + pub extern "c" fn @"connect$NOCANCEL"(sockfd: c.fd_t, sock_addr: *const c.sockaddr, addrlen: c.socklen_t) c_int; + pub extern "c" fn @"accept$NOCANCEL"(sockfd: c.fd_t, noalias addr: ?*c.sockaddr, noalias addrlen: ?*c.socklen_t) c_int; + pub extern "c" fn @"accept4$NOCANCEL"(sockfd: c.fd_t, noalias addr: ?*c.sockaddr, noalias addrlen: ?*c.socklen_t, flags: c_uint) c_int; + pub extern "c" fn @"open$NOCANCEL"(path: [*:0]const u8, oflag: c_uint, ...) c_int; + // https://opensource.apple.com/source/xnu/xnu-7195.81.3/libsyscall/wrappers/open-base.c + pub extern "c" fn @"openat$NOCANCEL"(fd: c.fd_t, path: [*:0]const u8, oflag: c_uint, ...) c_int; + pub extern "c" fn @"read$NOCANCEL"(fd: c.fd_t, buf: [*]u8, nbyte: usize) isize; + pub extern "c" fn @"pread$NOCANCEL"(fd: c.fd_t, buf: [*]u8, nbyte: usize, offset: c.off_t) isize; + pub extern "c" fn @"preadv$NOCANCEL"(fd: c.fd_t, uf: [*]std.posix.iovec, count: i32, offset: c.off_t) isize; + pub extern "c" fn @"readv$NOCANCEL"(fd: c.fd_t, uf: [*]std.posix.iovec, count: i32) isize; + pub extern "c" fn @"write$NOCANCEL"(fd: c.fd_t, buf: [*]const u8, nbyte: usize) isize; + pub extern "c" fn @"writev$NOCANCEL"(fd: c.fd_t, buf: [*]const std.posix.iovec_const, count: i32) isize; + pub extern "c" fn @"pwritev$NOCANCEL"(fd: c.fd_t, buf: [*]const std.posix.iovec_const, count: i32, offset: c.off_t) isize; +}; + fn toPackedO(number: anytype) std.posix.O { return @bitCast(number); } @@ -1671,7 +1691,7 @@ pub fn openatWindowsA( pub fn openatOSPath(dirfd: bun.FileDescriptor, file_path: bun.OSPathSliceZ, flags: i32, perm: bun.Mode) Maybe(bun.FileDescriptor) { if (comptime Environment.isMac) { // https://opensource.apple.com/source/xnu/xnu-7195.81.3/libsyscall/wrappers/open-base.c - const rc = syscall.@"openat$NOCANCEL"(dirfd.cast(), file_path.ptr, @bitCast(bun.O.toPacked(flags)), perm); + const rc = darwin_nocancel.@"openat$NOCANCEL"(dirfd.cast(), file_path.ptr, @bitCast(bun.O.toPacked(flags)), perm); if (comptime Environment.allow_assert) log("openat({}, {s}, {d}) = {d}", .{ dirfd, bun.sliceTo(file_path, 0), flags, rc }); @@ -1822,7 +1842,7 @@ pub fn write(fd: bun.FileDescriptor, bytes: []const u8) Maybe(usize) { return switch (Environment.os) { .mac => { - const rc = syscall.@"write$NOCANCEL"(fd.cast(), bytes.ptr, adjusted_len); + const rc = darwin_nocancel.@"write$NOCANCEL"(fd.cast(), bytes.ptr, adjusted_len); log("write({}, {d}) = {d} ({})", .{ fd, adjusted_len, rc, debug_timer }); if (Maybe(usize).errnoSysFd(rc, .write, fd)) |err| { @@ -2022,31 +2042,31 @@ pub fn preadv(fd: bun.FileDescriptor, buffers: []std.posix.iovec, position: isiz const preadv_sym = if (builtin.os.tag == .linux and builtin.link_libc) std.os.linux.preadv else if (builtin.os.tag.isDarwin()) - syscall.@"preadv$NOCANCEL" + darwin_nocancel.@"preadv$NOCANCEL" else syscall.preadv; const readv_sym = if (builtin.os.tag == .linux and builtin.link_libc) std.os.linux.readv else if (builtin.os.tag.isDarwin()) - syscall.@"readv$NOCANCEL" + darwin_nocancel.@"readv$NOCANCEL" else syscall.readv; const pwritev_sym = if (builtin.os.tag == .linux and builtin.link_libc) std.os.linux.pwritev else if (builtin.os.tag.isDarwin()) - syscall.@"pwritev$NOCANCEL" + darwin_nocancel.@"pwritev$NOCANCEL" else syscall.pwritev; const writev_sym = if (builtin.os.tag.isDarwin()) - syscall.@"writev$NOCANCEL" + darwin_nocancel.@"writev$NOCANCEL" else syscall.writev; const pread_sym = if (builtin.os.tag.isDarwin()) - syscall.@"pread$NOCANCEL" + darwin_nocancel.@"pread$NOCANCEL" else syscall.pread; @@ -2108,7 +2128,7 @@ pub fn read(fd: bun.FileDescriptor, buf: []u8) Maybe(usize) { const adjusted_len = @min(buf.len, max_count); return switch (Environment.os) { .mac => { - const rc = syscall.@"read$NOCANCEL"(fd.cast(), buf.ptr, adjusted_len); + const rc = darwin_nocancel.@"read$NOCANCEL"(fd.cast(), buf.ptr, adjusted_len); if (Maybe(usize).errnoSysFd(rc, .read, fd)) |err| { log("read({}, {d}) = {s} ({any})", .{ fd, adjusted_len, err.err.name(), debug_timer }); @@ -2174,7 +2194,7 @@ pub fn recv(fd: bun.FileDescriptor, buf: []u8, flag: u32) Maybe(usize) { } if (comptime Environment.isMac) { - const rc = syscall.@"recvfrom$NOCANCEL"(fd.cast(), buf.ptr, adjusted_len, flag, null, null); + const rc = darwin_nocancel.@"recvfrom$NOCANCEL"(fd.cast(), buf.ptr, adjusted_len, flag, null, null); if (Maybe(usize).errnoSysFd(rc, .recv, fd)) |err| { log("recv({}, {d}) = {s} {}", .{ fd, adjusted_len, err.err.name(), debug_timer }); @@ -2205,7 +2225,7 @@ pub fn sendNonBlock(fd: bun.FileDescriptor, buf: []const u8) Maybe(usize) { pub fn send(fd: bun.FileDescriptor, buf: []const u8, flag: u32) Maybe(usize) { if (comptime Environment.isMac) { - const rc = syscall.@"sendto$NOCANCEL"(fd.cast(), buf.ptr, buf.len, flag, null, 0); + const rc = darwin_nocancel.@"sendto$NOCANCEL"(fd.cast(), buf.ptr, buf.len, flag, null, 0); if (Maybe(usize).errnoSysFd(rc, .send, fd)) |err| { syslog("send({}, {d}) = {s}", .{ fd, buf.len, err.err.name() }); diff --git a/src/transpiler.zig b/src/transpiler.zig index acaf18b638..c58cabbc2f 100644 --- a/src/transpiler.zig +++ b/src/transpiler.zig @@ -56,9 +56,9 @@ const DataURL = @import("./resolver/data_url.zig").DataURL; pub const MacroJSValueType = JSC.JSValue; const default_macro_js_value = JSC.JSValue.zero; -const EntryPoints = @import("./bundler/entry_points.zig"); +pub const EntryPoints = @import("./bundler/entry_points.zig"); const SystemTimer = @import("./system_timer.zig").Timer; -pub usingnamespace EntryPoints; + pub const ParseResult = struct { source: logger.Source, loader: options.Loader,