Remove dead code from js_printer (#18619)

This commit is contained in:
Jarred Sumner
2025-03-29 04:46:23 -07:00
committed by GitHub
parent 358a1db422
commit fee911194a
6 changed files with 74 additions and 189 deletions

View File

@@ -5,8 +5,14 @@ extern const jsc_llint_begin: u8;
extern const jsc_llint_end: u8;
/// allocated using bun.default_allocator. when called from lldb, it is never freed.
pub export fn dumpBtjsTrace() [*:0]const u8 {
if (@import("builtin").mode != .Debug) return "dumpBtjsTrace is disabled in release builds";
if (comptime bun.Environment.isDebug) {
return dumpBtjsTraceDebugImpl();
}
return "btjs is disabled in release builds";
}
fn dumpBtjsTraceDebugImpl() [*:0]const u8 {
var result_writer = std.ArrayList(u8).init(bun.default_allocator);
const w = result_writer.writer();
@@ -63,7 +69,8 @@ pub export fn dumpBtjsTrace() [*:0]const u8 {
}).ptr);
}
pub fn printSourceAtAddress(debug_info: *std.debug.SelfInfo, out_stream: anytype, address: usize, tty_config: std.io.tty.Config, fp: usize) !void {
fn printSourceAtAddress(debug_info: *std.debug.SelfInfo, out_stream: anytype, address: usize, tty_config: std.io.tty.Config, fp: usize) !void {
if (!bun.Environment.isDebug) unreachable;
const module = debug_info.getModuleForAddress(address) catch |err| switch (err) {
error.MissingDebugInfo, error.InvalidDebugInfo => return printUnknownSource(debug_info, out_stream, address, tty_config),
else => return err,
@@ -114,6 +121,7 @@ pub fn printSourceAtAddress(debug_info: *std.debug.SelfInfo, out_stream: anytype
}
fn printUnknownSource(debug_info: *std.debug.SelfInfo, out_stream: anytype, address: usize, tty_config: std.io.tty.Config) !void {
if (!bun.Environment.isDebug) unreachable;
const module_name = debug_info.getModuleNameForAddress(address);
return printLineInfo(
out_stream,
@@ -136,6 +144,8 @@ fn printLineInfo(
comptime printLineFromFile: anytype,
do_llint: bool,
) !void {
if (!bun.Environment.isDebug) unreachable;
nosuspend {
try tty_config.setColor(out_stream, .bold);
@@ -176,6 +186,8 @@ fn printLineInfo(
}
fn printLineFromFileAnyOs(out_stream: anytype, source_location: std.debug.SourceLocation) !void {
if (!bun.Environment.isDebug) unreachable;
// Need this to always block even in async I/O mode, because this could potentially
// be called from e.g. the event loop code crashing.
var f = try std.fs.cwd().openFile(source_location.file_name, .{});
@@ -230,6 +242,7 @@ fn printLineFromFileAnyOs(out_stream: anytype, source_location: std.debug.Source
}
fn printLastUnwindError(it: *std.debug.StackIterator, debug_info: *std.debug.SelfInfo, out_stream: anytype, tty_config: std.io.tty.Config) void {
if (!bun.Environment.isDebug) unreachable;
if (!std.debug.have_ucontext) return;
if (it.getLastError()) |unwind_error| {
printUnwindError(debug_info, out_stream, unwind_error.address, unwind_error.err, tty_config) catch {};
@@ -237,6 +250,8 @@ fn printLastUnwindError(it: *std.debug.StackIterator, debug_info: *std.debug.Sel
}
fn printUnwindError(debug_info: *std.debug.SelfInfo, out_stream: anytype, address: usize, err: std.debug.UnwindError, tty_config: std.io.tty.Config) !void {
if (!bun.Environment.isDebug) unreachable;
const module_name = debug_info.getModuleNameForAddress(address) orelse "???";
try tty_config.setColor(out_stream, .dim);
if (err == error.MissingDebugInfo) {

View File

@@ -1429,23 +1429,35 @@ pub const CreateCommand = struct {
package_json_expr.data.e_object.properties = js_ast.G.Property.List.init(package_json_expr.data.e_object.properties.ptr[0..property_i]);
}
const package_json_writer = JSPrinter.NewFileWriter(package_json_file.?);
const file = package_json_file.?;
const written = JSPrinter.printJSON(@TypeOf(package_json_writer), package_json_writer, package_json_expr, &source, .{ .mangled_props = null }) catch |err| {
var buffer_writer = try JSPrinter.BufferWriter.init(bun.default_allocator);
buffer_writer.append_newline = true;
var package_json_writer = JSPrinter.BufferPrinter.init(buffer_writer);
_ = JSPrinter.printJSON(
@TypeOf(&package_json_writer),
&package_json_writer,
package_json_expr,
&source,
.{ .mangled_props = null },
) catch |err| {
Output.prettyErrorln("package.json failed to write due to error {s}", .{@errorName(err)});
package_json_file = null;
break :process_package_json;
};
const fd = bun.toFD(file);
const written = package_json_writer.ctx.getWritten();
bun.sys.File.writeAll(.{ .handle = fd }, written).unwrap() catch |err| {
Output.prettyErrorln("package.json failed to write due to error {s}", .{@errorName(err)});
package_json_file = null;
break :process_package_json;
};
bun.sys.ftruncate(fd, @intCast(written.len)).unwrap() catch |err| {
Output.prettyErrorln("package.json failed to write due to error {s}", .{@errorName(err)});
package_json_file = null;
break :process_package_json;
};
std.posix.ftruncate(package_json_file.?.handle, written + 1) catch {};
// if (!create_options.skip_install) {
// if (needs.bun_bun_for_nextjs) {
// try postinstall_tasks.append(ctx.allocator, InjectionPrefill.bun_bun_for_nextjs_task);
// } else if (bun_bun_for_react_scripts) {
// try postinstall_tasks.append(ctx.allocator, try std.fmt.allocPrint(ctx.allocator, "bun bun {s}", .{create_react_app_entry_point_path}));
// }
// }
}
}

View File

@@ -757,14 +757,15 @@ pub const InitCommand = struct {
}
write_package_json: {
if (package_json_file == null) {
package_json_file = try std.fs.cwd().createFileZ("package.json", .{});
}
const package_json_writer = JSPrinter.NewFileWriter(package_json_file.?);
var file = package_json_file orelse try std.fs.cwd().createFileZ("package.json", .{});
defer file.close();
var buffer_writer = try JSPrinter.BufferWriter.init(bun.default_allocator);
buffer_writer.append_newline = true;
var package_json_writer = JSPrinter.BufferPrinter.init(buffer_writer);
const written = JSPrinter.printJSON(
@TypeOf(package_json_writer),
package_json_writer,
_ = JSPrinter.printJSON(
@TypeOf(&package_json_writer),
&package_json_writer,
js_ast.Expr{ .data = .{ .e_object = fields.object }, .loc = logger.Loc.Empty },
&logger.Source.initEmptyFile("package.json"),
.{ .mangled_props = null },
@@ -773,9 +774,18 @@ pub const InitCommand = struct {
package_json_file = null;
break :write_package_json;
};
std.posix.ftruncate(package_json_file.?.handle, written + 1) catch {};
package_json_file.?.close();
const fd = bun.toFD(file);
const written = package_json_writer.ctx.getWritten();
bun.sys.File.writeAll(.{ .handle = fd }, written).unwrap() catch |err| {
Output.prettyErrorln("package.json failed to write due to error {s}", .{@errorName(err)});
package_json_file = null;
break :write_package_json;
};
bun.sys.ftruncate(fd, @intCast(written.len)).unwrap() catch |err| {
Output.prettyErrorln("package.json failed to write due to error {s}", .{@errorName(err)});
package_json_file = null;
break :write_package_json;
};
}
if (steps.write_gitignore) {

View File

@@ -54,8 +54,6 @@ const last_low_surrogate = 0xDFFF;
const CodepointIterator = @import("./string_immutable.zig").UnsignedCodepointIterator;
const assert = bun.assert;
threadlocal var imported_module_ids_list: std.ArrayList(u32) = undefined;
threadlocal var imported_module_ids_list_unset: bool = true;
const ImportRecord = bun.ImportRecord;
const SourceMap = @import("./sourcemap/sourcemap.zig");
@@ -687,7 +685,6 @@ fn NewPrinter(
writer: Writer,
has_printed_bundled_import_statement: bool = false,
imported_module_ids: std.ArrayList(u32),
renamer: rename.Renamer,
prev_stmt_tag: Stmt.Tag = .s_empty,
@@ -5243,18 +5240,10 @@ fn NewPrinter(
renamer: bun.renamer.Renamer,
source_map_builder: SourceMap.Chunk.Builder,
) Printer {
if (imported_module_ids_list_unset) {
imported_module_ids_list = std.ArrayList(u32).init(default_allocator);
imported_module_ids_list_unset = false;
}
imported_module_ids_list.clearRetainingCapacity();
var printer = Printer{
.import_records = import_records,
.options = opts,
.writer = writer,
.imported_module_ids = imported_module_ids_list,
.renamer = renamer,
.source_map_builder = source_map_builder,
};
@@ -5553,128 +5542,6 @@ pub const DirectWriter = struct {
pub const Error = std.posix.WriteError;
};
// Unbuffered 653ms
// Buffered 65k 47ms
// Buffered 16k 43ms
// Buffered 4k 55ms
const FileWriterInternal = struct {
file: std.fs.File,
last_bytes: [2]u8 = [_]u8{ 0, 0 },
threadlocal var buffer: MutableString = undefined;
threadlocal var has_loaded_buffer: bool = false;
pub fn getBuffer() *MutableString {
buffer.reset();
return &buffer;
}
pub fn getMutableBuffer(_: *FileWriterInternal) *MutableString {
return &buffer;
}
pub fn init(file: std.fs.File) FileWriterInternal {
if (!has_loaded_buffer) {
buffer = MutableString.init(default_allocator, 0) catch unreachable;
has_loaded_buffer = true;
}
buffer.reset();
return FileWriterInternal{
.file = file,
};
}
pub fn writeByte(this: *FileWriterInternal, byte: u8) anyerror!usize {
try buffer.appendChar(byte);
this.last_bytes = .{ this.last_bytes[1], byte };
return 1;
}
pub fn writeAll(this: *FileWriterInternal, bytes: anytype) anyerror!usize {
try buffer.append(bytes);
if (bytes.len >= 2) {
this.last_bytes = bytes[bytes.len - 2 ..][0..2].*;
} else if (bytes.len >= 1) {
this.last_bytes = .{ this.last_bytes[1], bytes[bytes.len - 1] };
}
return bytes.len;
}
pub fn slice(_: *@This()) string {
return buffer.list.items;
}
pub fn getLastByte(this: *const FileWriterInternal) u8 {
return this.last_bytes[1];
}
pub fn getLastLastByte(this: *const FileWriterInternal) u8 {
return this.last_bytes[0];
}
pub fn reserveNext(_: *FileWriterInternal, count: u64) anyerror![*]u8 {
try buffer.growIfNeeded(count);
return @as([*]u8, @ptrCast(&buffer.list.items.ptr[buffer.list.items.len]));
}
pub fn advanceBy(this: *FileWriterInternal, count: u64) void {
if (comptime Environment.isDebug) bun.assert(buffer.list.items.len + count <= buffer.list.capacity);
buffer.list.items = buffer.list.items.ptr[0 .. buffer.list.items.len + count];
if (count >= 2) {
this.last_bytes = buffer.list.items[buffer.list.items.len - 2 ..][0..2].*;
} else if (count >= 1) {
this.last_bytes = .{ this.last_bytes[1], buffer.list.items[buffer.list.items.len - 1] };
}
}
pub fn done(
ctx: *FileWriterInternal,
) anyerror!void {
defer buffer.reset();
const result_ = buffer.slice();
var result = result_;
while (result.len > 0) {
switch (result.len) {
0...4096 => {
const written = try ctx.file.write(result);
if (written == 0 or result.len - written == 0) return;
result = result[written..];
},
else => {
const first = result.ptr[0 .. result.len / 3];
const second = result[first.len..][0..first.len];
const remain = first.len + second.len;
const third: []const u8 = result[remain..];
var vecs = [_]std.posix.iovec_const{
.{
.base = first.ptr,
.len = first.len,
},
.{
.base = second.ptr,
.len = second.len,
},
.{
.base = third.ptr,
.len = third.len,
},
};
const written = try std.posix.writev(ctx.file.handle, vecs[0..@as(usize, if (third.len > 0) 3 else 2)]);
if (written == 0 or result.len - written == 0) return;
result = result[written..];
},
}
}
}
pub fn flush(
_: *FileWriterInternal,
) anyerror!void {}
};
pub const BufferWriter = struct {
buffer: MutableString = undefined,
written: []u8 = &[_]u8{},
@@ -5801,19 +5668,6 @@ pub const BufferPrinter = NewWriter(
BufferWriter.reserveNext,
BufferWriter.advanceBy,
);
pub const FileWriter = NewWriter(
FileWriterInternal,
FileWriterInternal.writeByte,
FileWriterInternal.writeAll,
FileWriterInternal.getLastByte,
FileWriterInternal.getLastLastByte,
FileWriterInternal.reserveNext,
FileWriterInternal.advanceBy,
);
pub fn NewFileWriter(file: std.fs.File) FileWriter {
const internal = FileWriterInternal.init(file);
return FileWriter.init(internal);
}
pub const Format = enum {
esm,
@@ -5976,9 +5830,6 @@ pub fn printAst(
var bin_stack_heap = std.heap.stackFallback(1024, bun.default_allocator);
printer.binary_expression_stack = std.ArrayList(PrinterType.BinaryExpressionVisitor).init(bin_stack_heap.get());
defer printer.binary_expression_stack.clearAndFree();
defer {
imported_module_ids_list = printer.imported_module_ids;
}
if (!opts.bundling and
tree.uses_require_ref and
@@ -6172,9 +6023,6 @@ pub fn printWithWriterAndPlatform(
defer printer.temporary_bindings.deinit(bun.default_allocator);
defer writer.* = printer.writer.*;
defer {
imported_module_ids_list = printer.imported_module_ids;
}
if (opts.module_type == .internal_bake_dev and !source.index.isRuntime()) {
printer.printDevServerModule(source, &ast, &parts[0]);
@@ -6252,9 +6100,6 @@ pub fn printCommonJS(
var bin_stack_heap = std.heap.stackFallback(1024, bun.default_allocator);
printer.binary_expression_stack = std.ArrayList(PrinterType.BinaryExpressionVisitor).init(bin_stack_heap.get());
defer printer.binary_expression_stack.clearAndFree();
defer {
imported_module_ids_list = printer.imported_module_ids;
}
for (tree.parts.slice()) |part| {
for (part.stmts) |stmt| {

View File

@@ -2316,11 +2316,20 @@ pub fn readlinkat(fd: bun.FileDescriptor, in: [:0]const u8, buf: []u8) Maybe([:0
pub fn ftruncate(fd: bun.FileDescriptor, size: isize) Maybe(void) {
if (comptime Environment.isWindows) {
if (kernel32.SetFileValidData(fd.cast(), size) == 0) {
return Maybe(void).errnoSysFd(0, .ftruncate, fd) orelse Maybe(void).success;
}
var io_status_block: std.os.windows.IO_STATUS_BLOCK = undefined;
var eof_info = std.os.windows.FILE_END_OF_FILE_INFORMATION{
.EndOfFile = @bitCast(size),
};
return Maybe(void).success;
const rc = windows.ntdll.NtSetInformationFile(
fd.cast(),
&io_status_block,
&eof_info,
@sizeOf(std.os.windows.FILE_END_OF_FILE_INFORMATION),
.FileEndOfFileInformation,
);
return Maybe(void).errnoSysFd(rc, .ftruncate, fd) orelse Maybe(void).success;
}
return while (true) {

View File

@@ -93,12 +93,6 @@ pub extern "kernel32" fn GetFileInformationByHandle(
lpFileInformation: *windows.BY_HANDLE_FILE_INFORMATION,
) callconv(windows.WINAPI) BOOL;
/// https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-setfilevaliddata
pub extern "kernel32" fn SetFileValidData(
hFile: win32.HANDLE,
validDataLength: c_longlong,
) callconv(windows.WINAPI) win32.BOOL;
pub extern "kernel32" fn CommandLineToArgvW(
lpCmdLine: win32.LPCWSTR,
pNumArgs: *c_int,