authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-04-04 19:26:50-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-07-01 16:35:26-07:00
log890a02c3456dce7242aa65e5093b31f9d8a417bc
tree2720536bb22c61b9405344cdcb85abcc862ffb07
parent6c48aad991f64f7e5bb92af498cc4cbddca9895e

std.io: move getStdIn, getStdOut, getStdErr functions to fs.File

preparing to rearrange std.io namespace into an interface

36 files changed, 183 insertions(+), 203 deletions(-)

lib/compiler/test_runner.zig+3-3
...@@ -69,8 +69,8 @@ fn mainServer() !void {...@@ -69,8 +69,8 @@ fn mainServer() !void {
69 @disableInstrumentation();69 @disableInstrumentation();
70 var server = try std.zig.Server.init(.{70 var server = try std.zig.Server.init(.{
71 .gpa = fba.allocator(),71 .gpa = fba.allocator(),
72 .in = std.io.getStdIn(),72 .in = .stdin(),
73 .out = std.io.getStdOut(),73 .out = .stdout(),
74 .zig_version = builtin.zig_version_string,74 .zig_version = builtin.zig_version_string,
75 });75 });
76 defer server.deinit();76 defer server.deinit();
...@@ -191,7 +191,7 @@ fn mainTerminal() void {...@@ -191,7 +191,7 @@ fn mainTerminal() void {
191 .root_name = "Test",191 .root_name = "Test",
192 .estimated_total_items = test_fn_list.len,192 .estimated_total_items = test_fn_list.len,
193 });193 });
194 const have_tty = std.io.getStdErr().isTty();194 const have_tty = std.fs.File.stderr().isTty();
195195
196 var async_frame_buffer: []align(builtin.target.stackAlignment()) u8 = undefined;196 var async_frame_buffer: []align(builtin.target.stackAlignment()) u8 = undefined;
197 // TODO this is on the next line (using `undefined` above) because otherwise zig incorrectly197 // TODO this is on the next line (using `undefined` above) because otherwise zig incorrectly
lib/std/Build.zig+3-3
...@@ -2677,7 +2677,7 @@ pub const LazyPath = union(enum) {...@@ -2677,7 +2677,7 @@ pub const LazyPath = union(enum) {
2677 .root_dir = Cache.Directory.cwd(),2677 .root_dir = Cache.Directory.cwd(),
2678 .sub_path = gen.file.path orelse {2678 .sub_path = gen.file.path orelse {
2679 std.debug.lockStdErr();2679 std.debug.lockStdErr();
2680 const stderr = std.io.getStdErr();2680 const stderr: fs.File = .stderr();
2681 dumpBadGetPathHelp(gen.file.step, stderr, src_builder, asking_step) catch {};2681 dumpBadGetPathHelp(gen.file.step, stderr, src_builder, asking_step) catch {};
2682 std.debug.unlockStdErr();2682 std.debug.unlockStdErr();
2683 @panic("misconfigured build script");2683 @panic("misconfigured build script");
...@@ -2766,11 +2766,11 @@ fn dumpBadDirnameHelp(...@@ -2766,11 +2766,11 @@ fn dumpBadDirnameHelp(
2766 comptime msg: []const u8,2766 comptime msg: []const u8,
2767 args: anytype,2767 args: anytype,
2768) anyerror!void {2768) anyerror!void {
2769 var buffered_writer = debug.lockStdErr2();2769 var buffered_writer = debug.lockStdErr2(&.{});
2770 defer debug.unlockStdErr();2770 defer debug.unlockStdErr();
2771 const w = &buffered_writer;2771 const w = &buffered_writer;
27722772
2773 const stderr = io.getStdErr();2773 const stderr: fs.File = .stderr();
2774 try w.print(msg, args);2774 try w.print(msg, args);
27752775
2776 const tty_config = std.io.tty.detectConfig(stderr);2776 const tty_config = std.io.tty.detectConfig(stderr);
lib/std/Build/Fuzz.zig+2-2
...@@ -124,7 +124,7 @@ fn rebuildTestsWorkerRunFallible(run: *Step.Run, ttyconf: std.io.tty.Config, par...@@ -124,7 +124,7 @@ fn rebuildTestsWorkerRunFallible(run: *Step.Run, ttyconf: std.io.tty.Config, par
124 const show_stderr = compile.step.result_stderr.len > 0;124 const show_stderr = compile.step.result_stderr.len > 0;
125125
126 if (show_error_msgs or show_compile_errors or show_stderr) {126 if (show_error_msgs or show_compile_errors or show_stderr) {
127 var bw = std.debug.lockStdErr2();127 var bw = std.debug.lockStdErr2(&.{});
128 defer std.debug.unlockStdErr();128 defer std.debug.unlockStdErr();
129 build_runner.printErrorMessages(gpa, &compile.step, .{ .ttyconf = ttyconf }, &bw, false) catch {};129 build_runner.printErrorMessages(gpa, &compile.step, .{ .ttyconf = ttyconf }, &bw, false) catch {};
130 }130 }
...@@ -151,7 +151,7 @@ fn fuzzWorkerRun(...@@ -151,7 +151,7 @@ fn fuzzWorkerRun(
151151
152 run.rerunInFuzzMode(web_server, unit_test_index, prog_node) catch |err| switch (err) {152 run.rerunInFuzzMode(web_server, unit_test_index, prog_node) catch |err| switch (err) {
153 error.MakeFailed => {153 error.MakeFailed => {
154 var bw = std.debug.lockStdErr2();154 var bw = std.debug.lockStdErr2(&.{});
155 defer std.debug.unlockStdErr();155 defer std.debug.unlockStdErr();
156 build_runner.printErrorMessages(gpa, &run.step, .{ .ttyconf = ttyconf }, &bw, false) catch {};156 build_runner.printErrorMessages(gpa, &run.step, .{ .ttyconf = ttyconf }, &bw, false) catch {};
157 return;157 return;
lib/std/Build/Step/Compile.zig+2-2
...@@ -1018,7 +1018,7 @@ fn getGeneratedFilePath(compile: *Compile, comptime tag_name: []const u8, asking...@@ -1018,7 +1018,7 @@ fn getGeneratedFilePath(compile: *Compile, comptime tag_name: []const u8, asking
10181018
1019 const generated_file = maybe_path orelse {1019 const generated_file = maybe_path orelse {
1020 std.debug.lockStdErr();1020 std.debug.lockStdErr();
1021 const stderr = std.io.getStdErr();1021 const stderr: fs.File = .stderr();
10221022
1023 std.Build.dumpBadGetPathHelp(&compile.step, stderr, compile.step.owner, asking_step) catch {};1023 std.Build.dumpBadGetPathHelp(&compile.step, stderr, compile.step.owner, asking_step) catch {};
10241024
...@@ -1027,7 +1027,7 @@ fn getGeneratedFilePath(compile: *Compile, comptime tag_name: []const u8, asking...@@ -1027,7 +1027,7 @@ fn getGeneratedFilePath(compile: *Compile, comptime tag_name: []const u8, asking
10271027
1028 const path = generated_file.path orelse {1028 const path = generated_file.path orelse {
1029 std.debug.lockStdErr();1029 std.debug.lockStdErr();
1030 const stderr = std.io.getStdErr();1030 const stderr: fs.File = .stderr();
10311031
1032 std.Build.dumpBadGetPathHelp(&compile.step, stderr, compile.step.owner, asking_step) catch {};1032 std.Build.dumpBadGetPathHelp(&compile.step, stderr, compile.step.owner, asking_step) catch {};
10331033
lib/std/Progress.zig+1-1
...@@ -451,7 +451,7 @@ pub fn start(options: Options) Node {...@@ -451,7 +451,7 @@ pub fn start(options: Options) Node {
451 if (options.disable_printing) {451 if (options.disable_printing) {
452 return Node.none;452 return Node.none;
453 }453 }
454 const stderr = std.io.getStdErr();454 const stderr: std.fs.File = .stderr();
455 global_progress.terminal = stderr;455 global_progress.terminal = stderr;
456 if (stderr.getOrEnableAnsiEscapeSupport()) {456 if (stderr.getOrEnableAnsiEscapeSupport()) {
457 global_progress.terminal_mode = .ansi_escape_codes;457 global_progress.terminal_mode = .ansi_escape_codes;
lib/std/Random/benchmark.zig+1-1
...@@ -122,7 +122,7 @@ fn mode(comptime x: comptime_int) comptime_int {...@@ -122,7 +122,7 @@ fn mode(comptime x: comptime_int) comptime_int {
122}122}
123123
124pub fn main() !void {124pub fn main() !void {
125 const stdout = std.io.getStdOut().writer();125 const stdout = std.fs.File.stdout().writer();
126126
127 var buffer: [1024]u8 = undefined;127 var buffer: [1024]u8 = undefined;
128 var fixed = std.heap.FixedBufferAllocator.init(buffer[0..]);128 var fixed = std.heap.FixedBufferAllocator.init(buffer[0..]);
lib/std/builtin.zig+1-1
...@@ -51,7 +51,7 @@ pub const StackTrace = struct {...@@ -51,7 +51,7 @@ pub const StackTrace = struct {
51 const debug_info = std.debug.getSelfDebugInfo() catch |err| {51 const debug_info = std.debug.getSelfDebugInfo() catch |err| {
52 return writer.print("\nUnable to print stack trace: Unable to open debug info: {s}\n", .{@errorName(err)});52 return writer.print("\nUnable to print stack trace: Unable to open debug info: {s}\n", .{@errorName(err)});
53 };53 };
54 const tty_config = std.io.tty.detectConfig(std.io.getStdErr());54 const tty_config = std.io.tty.detectConfig(.stderr());
55 try writer.writeAll("\n");55 try writer.writeAll("\n");
56 std.debug.writeStackTrace(self, writer, debug_info, tty_config) catch |err| {56 std.debug.writeStackTrace(self, writer, debug_info, tty_config) catch |err| {
57 try writer.print("Unable to print stack trace: {s}\n", .{@errorName(err)});57 try writer.print("Unable to print stack trace: {s}\n", .{@errorName(err)});
lib/std/crypto/benchmark.zig+1-1
...@@ -458,7 +458,7 @@ fn mode(comptime x: comptime_int) comptime_int {...@@ -458,7 +458,7 @@ fn mode(comptime x: comptime_int) comptime_int {
458}458}
459459
460pub fn main() !void {460pub fn main() !void {
461 const stdout = std.io.getStdOut().writer();461 const stdout = std.fs.File.stdout().writer();
462462
463 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);463 var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
464 defer arena.deinit();464 defer arena.deinit();
lib/std/debug.zig+23-23
...@@ -210,15 +210,15 @@ pub fn unlockStdErr() void {...@@ -210,15 +210,15 @@ pub fn unlockStdErr() void {
210///210///
211/// Returns a `std.io.BufferedWriter` with empty buffer, meaning that it is211/// Returns a `std.io.BufferedWriter` with empty buffer, meaning that it is
212/// in fact unbuffered and does not need to be flushed.212/// in fact unbuffered and does not need to be flushed.
213pub fn lockStdErr2() std.io.BufferedWriter {213pub fn lockStdErr2(buffer: []u8) std.io.BufferedWriter {
214 std.Progress.lockStdErr();214 std.Progress.lockStdErr();
215 return io.getStdErr().writer().unbuffered();215 return std.fs.File.stderr().writer().buffered(buffer);
216}216}
217217
218/// Print to stderr, unbuffered, and silently returning on failure. Intended218/// Print to stderr, unbuffered, and silently returning on failure. Intended
219/// for use in "printf debugging." Use `std.log` functions for proper logging.219/// for use in "printf debugging." Use `std.log` functions for proper logging.
220pub fn print(comptime fmt: []const u8, args: anytype) void {220pub fn print(comptime fmt: []const u8, args: anytype) void {
221 var bw = lockStdErr2();221 var bw = lockStdErr2(&.{});
222 defer unlockStdErr();222 defer unlockStdErr();
223 nosuspend bw.print(fmt, args) catch return;223 nosuspend bw.print(fmt, args) catch return;
224}224}
...@@ -242,9 +242,9 @@ pub fn getSelfDebugInfo() !*SelfInfo {...@@ -242,9 +242,9 @@ pub fn getSelfDebugInfo() !*SelfInfo {
242/// Tries to print a hexadecimal view of the bytes, unbuffered, and ignores any error returned.242/// Tries to print a hexadecimal view of the bytes, unbuffered, and ignores any error returned.
243/// Obtains the stderr mutex while dumping.243/// Obtains the stderr mutex while dumping.
244pub fn dumpHex(bytes: []const u8) void {244pub fn dumpHex(bytes: []const u8) void {
245 var bw = lockStdErr2();245 var bw = lockStdErr2(&.{});
246 defer unlockStdErr();246 defer unlockStdErr();
247 const ttyconf = std.io.tty.detectConfig(std.io.getStdErr());247 const ttyconf = std.io.tty.detectConfig(.stderr());
248 dumpHexFallible(&bw, ttyconf, bytes) catch {};248 dumpHexFallible(&bw, ttyconf, bytes) catch {};
249}249}
250250
...@@ -320,7 +320,7 @@ test dumpHexFallible {...@@ -320,7 +320,7 @@ test dumpHexFallible {
320320
321/// Tries to print the current stack trace to stderr, unbuffered, and ignores any error returned.321/// Tries to print the current stack trace to stderr, unbuffered, and ignores any error returned.
322pub fn dumpCurrentStackTrace(start_addr: ?usize) void {322pub fn dumpCurrentStackTrace(start_addr: ?usize) void {
323 var stderr = lockStdErr2();323 var stderr = lockStdErr2(&.{});
324 defer unlockStdErr();324 defer unlockStdErr();
325 nosuspend dumpCurrentStackTraceToWriter(start_addr, &stderr) catch return;325 nosuspend dumpCurrentStackTraceToWriter(start_addr, &stderr) catch return;
326}326}
...@@ -341,7 +341,7 @@ pub fn dumpCurrentStackTraceToWriter(start_addr: ?usize, writer: *std.io.Buffere...@@ -341,7 +341,7 @@ pub fn dumpCurrentStackTraceToWriter(start_addr: ?usize, writer: *std.io.Buffere
341 try writer.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)});341 try writer.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)});
342 return;342 return;
343 };343 };
344 writeCurrentStackTrace(writer, debug_info, io.tty.detectConfig(io.getStdErr()), start_addr) catch |err| {344 writeCurrentStackTrace(writer, debug_info, io.tty.detectConfig(.stderr()), start_addr) catch |err| {
345 try writer.print("Unable to dump stack trace: {s}\n", .{@errorName(err)});345 try writer.print("Unable to dump stack trace: {s}\n", .{@errorName(err)});
346 return;346 return;
347 };347 };
...@@ -426,7 +426,7 @@ pub fn dumpStackTraceFromBase(context: *ThreadContext, stderr: *std.io.BufferedW...@@ -426,7 +426,7 @@ pub fn dumpStackTraceFromBase(context: *ThreadContext, stderr: *std.io.BufferedW
426 stderr.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}) catch return;426 stderr.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}) catch return;
427 return;427 return;
428 };428 };
429 const tty_config = io.tty.detectConfig(io.getStdErr());429 const tty_config = io.tty.detectConfig(.stderr());
430 if (native_os == .windows) {430 if (native_os == .windows) {
431 // On x86_64 and aarch64, the stack will be unwound using RtlVirtualUnwind using the context431 // On x86_64 and aarch64, the stack will be unwound using RtlVirtualUnwind using the context
432 // provided by the exception handler. On x86, RtlVirtualUnwind doesn't exist. Instead, a new backtrace432 // provided by the exception handler. On x86, RtlVirtualUnwind doesn't exist. Instead, a new backtrace
...@@ -516,13 +516,13 @@ pub fn dumpStackTrace(stack_trace: std.builtin.StackTrace) void {...@@ -516,13 +516,13 @@ pub fn dumpStackTrace(stack_trace: std.builtin.StackTrace) void {
516 nosuspend {516 nosuspend {
517 if (builtin.target.cpu.arch.isWasm()) {517 if (builtin.target.cpu.arch.isWasm()) {
518 if (native_os == .wasi) {518 if (native_os == .wasi) {
519 var stderr = lockStdErr2();519 var stderr = lockStdErr2(&.{});
520 defer unlockStdErr();520 defer unlockStdErr();
521 stderr.writeAll("Unable to dump stack trace: not implemented for Wasm\n") catch return;521 stderr.writeAll("Unable to dump stack trace: not implemented for Wasm\n") catch return;
522 }522 }
523 return;523 return;
524 }524 }
525 var stderr = lockStdErr2();525 var stderr = lockStdErr2(&.{});
526 defer unlockStdErr();526 defer unlockStdErr();
527 if (builtin.strip_debug_info) {527 if (builtin.strip_debug_info) {
528 stderr.writeAll("Unable to dump stack trace: debug info stripped\n") catch return;528 stderr.writeAll("Unable to dump stack trace: debug info stripped\n") catch return;
...@@ -532,7 +532,7 @@ pub fn dumpStackTrace(stack_trace: std.builtin.StackTrace) void {...@@ -532,7 +532,7 @@ pub fn dumpStackTrace(stack_trace: std.builtin.StackTrace) void {
532 stderr.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}) catch return;532 stderr.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}) catch return;
533 return;533 return;
534 };534 };
535 writeStackTrace(stack_trace, &stderr, debug_info, io.tty.detectConfig(io.getStdErr())) catch |err| {535 writeStackTrace(stack_trace, &stderr, debug_info, io.tty.detectConfig(.stderr())) catch |err| {
536 stderr.print("Unable to dump stack trace: {s}\n", .{@errorName(err)}) catch return;536 stderr.print("Unable to dump stack trace: {s}\n", .{@errorName(err)}) catch return;
537 return;537 return;
538 };538 };
...@@ -683,7 +683,7 @@ pub fn defaultPanic(...@@ -683,7 +683,7 @@ pub fn defaultPanic(
683 _ = panicking.fetchAdd(1, .seq_cst);683 _ = panicking.fetchAdd(1, .seq_cst);
684684
685 {685 {
686 var stderr = lockStdErr2();686 var stderr = lockStdErr2(&.{});
687 defer unlockStdErr();687 defer unlockStdErr();
688688
689 if (builtin.single_threaded) {689 if (builtin.single_threaded) {
...@@ -706,7 +706,7 @@ pub fn defaultPanic(...@@ -706,7 +706,7 @@ pub fn defaultPanic(
706 // A panic happened while trying to print a previous panic message.706 // A panic happened while trying to print a previous panic message.
707 // We're still holding the mutex but that's fine as we're going to707 // We're still holding the mutex but that's fine as we're going to
708 // call abort().708 // call abort().
709 io.getStdErr().writeAll("aborting due to recursive panic\n") catch {};709 fs.File.stderr().writeAll("aborting due to recursive panic\n") catch {};
710 },710 },
711 else => {}, // Panicked while printing the recursive panic message.711 else => {}, // Panicked while printing the recursive panic message.
712 };712 };
...@@ -1468,7 +1468,8 @@ fn handleSegfaultPosix(sig: i32, info: *const posix.siginfo_t, ctx_ptr: ?*anyopa...@@ -1468,7 +1468,8 @@ fn handleSegfaultPosix(sig: i32, info: *const posix.siginfo_t, ctx_ptr: ?*anyopa
1468}1468}
14691469
1470fn dumpSegfaultInfoPosix(sig: i32, code: i32, addr: usize, ctx_ptr: ?*anyopaque) void {1470fn dumpSegfaultInfoPosix(sig: i32, code: i32, addr: usize, ctx_ptr: ?*anyopaque) void {
1471 var stderr = io.getStdErr().writer().unbuffered();1471 var stderr = lockStdErr2(&.{});
1472 defer unlockStdErr();
1472 _ = switch (sig) {1473 _ = switch (sig) {
1473 posix.SIG.SEGV => if (native_arch == .x86_64 and native_os == .linux and code == 128) // SI_KERNEL1474 posix.SIG.SEGV => if (native_arch == .x86_64 and native_os == .linux and code == 128) // SI_KERNEL
1474 // x86_64 doesn't have a full 64-bit virtual address space.1475 // x86_64 doesn't have a full 64-bit virtual address space.
...@@ -1546,25 +1547,24 @@ fn handleSegfaultWindowsExtra(info: *windows.EXCEPTION_POINTERS, msg: u8, label:...@@ -1546,25 +1547,24 @@ fn handleSegfaultWindowsExtra(info: *windows.EXCEPTION_POINTERS, msg: u8, label:
1546 _ = panicking.fetchAdd(1, .seq_cst);1547 _ = panicking.fetchAdd(1, .seq_cst);
15471548
1548 {1549 {
1549 lockStdErr();1550 var stderr = lockStdErr2(&.{});
1550 defer unlockStdErr();1551 defer unlockStdErr();
15511552
1552 dumpSegfaultInfoWindows(info, msg, label);1553 dumpSegfaultInfoWindows(info, msg, label, &stderr);
1553 }1554 }
15541555
1555 waitForOtherThreadToFinishPanicking();1556 waitForOtherThreadToFinishPanicking();
1556 },1557 },
1557 1 => {1558 1 => {
1558 panic_stage = 2;1559 panic_stage = 2;
1559 io.getStdErr().writeAll("aborting due to recursive panic\n") catch {};1560 fs.File.stderr().writeAll("aborting due to recursive panic\n") catch {};
1560 },1561 },
1561 else => {},1562 else => {},
1562 };1563 };
1563 posix.abort();1564 posix.abort();
1564}1565}
15651566
1566fn dumpSegfaultInfoWindows(info: *windows.EXCEPTION_POINTERS, msg: u8, label: ?[]const u8) void {1567fn dumpSegfaultInfoWindows(info: *windows.EXCEPTION_POINTERS, msg: u8, label: ?[]const u8, stderr: *std.io.BufferedWriter) void {
1567 var stderr = io.getStdErr().writer().unbuffered();
1568 _ = switch (msg) {1568 _ = switch (msg) {
1569 0 => stderr.print("{s}\n", .{label.?}),1569 0 => stderr.print("{s}\n", .{label.?}),
1570 1 => stderr.print("Segmentation fault at address 0x{x}\n", .{info.ExceptionRecord.ExceptionInformation[1]}),1570 1 => stderr.print("Segmentation fault at address 0x{x}\n", .{info.ExceptionRecord.ExceptionInformation[1]}),
...@@ -1572,7 +1572,7 @@ fn dumpSegfaultInfoWindows(info: *windows.EXCEPTION_POINTERS, msg: u8, label: ?[...@@ -1572,7 +1572,7 @@ fn dumpSegfaultInfoWindows(info: *windows.EXCEPTION_POINTERS, msg: u8, label: ?[
1572 else => unreachable,1572 else => unreachable,
1573 } catch posix.abort();1573 } catch posix.abort();
15741574
1575 dumpStackTraceFromBase(info.ContextRecord, &stderr);1575 dumpStackTraceFromBase(info.ContextRecord, stderr);
1576}1576}
15771577
1578pub fn dumpStackPointerAddr(prefix: []const u8) void {1578pub fn dumpStackPointerAddr(prefix: []const u8) void {
...@@ -1598,7 +1598,7 @@ test "manage resources correctly" {...@@ -1598,7 +1598,7 @@ test "manage resources correctly" {
1598 const writer = std.io.null_writer;1598 const writer = std.io.null_writer;
1599 var di = try SelfInfo.open(testing.allocator);1599 var di = try SelfInfo.open(testing.allocator);
1600 defer di.deinit();1600 defer di.deinit();
1601 try printSourceAtAddress(&di, writer, showMyTrace(), io.tty.detectConfig(std.io.getStdErr()));1601 try printSourceAtAddress(&di, writer, showMyTrace(), io.tty.detectConfig(.stderr()));
1602}1602}
16031603
1604noinline fn showMyTrace() usize {1604noinline fn showMyTrace() usize {
...@@ -1664,8 +1664,8 @@ pub fn ConfigurableTrace(comptime size: usize, comptime stack_frame_count: usize...@@ -1664,8 +1664,8 @@ pub fn ConfigurableTrace(comptime size: usize, comptime stack_frame_count: usize
1664 pub fn dump(t: @This()) void {1664 pub fn dump(t: @This()) void {
1665 if (!enabled) return;1665 if (!enabled) return;
16661666
1667 const tty_config = io.tty.detectConfig(std.io.getStdErr());1667 const tty_config = io.tty.detectConfig(.stderr());
1668 var stderr = lockStdErr2();1668 var stderr = lockStdErr2(&.{});
1669 defer unlockStdErr();1669 defer unlockStdErr();
1670 const end = @min(t.index, size);1670 const end = @min(t.index, size);
1671 const debug_info = getSelfDebugInfo() catch |err| {1671 const debug_info = getSelfDebugInfo() catch |err| {
lib/std/debug/simple_panic.zig+1-1
...@@ -15,7 +15,7 @@ pub fn call(msg: []const u8, ra: ?usize) noreturn {...@@ -15,7 +15,7 @@ pub fn call(msg: []const u8, ra: ?usize) noreturn {
15 @branchHint(.cold);15 @branchHint(.cold);
16 _ = ra;16 _ = ra;
17 std.debug.lockStdErr();17 std.debug.lockStdErr();
18 const stderr = std.io.getStdErr();18 const stderr: std.fs.File = .stderr();
19 stderr.writeAll(msg) catch {};19 stderr.writeAll(msg) catch {};
20 @trap();20 @trap();
21}21}
lib/std/fs/File.zig+12
...@@ -168,6 +168,18 @@ pub const CreateFlags = struct {...@@ -168,6 +168,18 @@ pub const CreateFlags = struct {
168 mode: Mode = default_mode,168 mode: Mode = default_mode,
169};169};
170170
171pub fn stdout() File {
172 return .{ .handle = if (is_windows) windows.peb().ProcessParameters.hStdOutput else posix.STDOUT_FILENO };
173}
174
175pub fn stderr() File {
176 return .{ .handle = if (is_windows) windows.peb().ProcessParameters.hStdError else posix.STDERR_FILENO };
177}
178
179pub fn stdin() File {
180 return .{ .handle = if (is_windows) windows.peb().ProcessParameters.hStdInput else posix.STDIN_FILENO };
181}
182
171/// Upon success, the stream is in an uninitialized state. To continue using it,183/// Upon success, the stream is in an uninitialized state. To continue using it,
172/// you must use the open() function.184/// you must use the open() function.
173pub fn close(self: File) void {185pub fn close(self: File) void {
lib/std/hash/benchmark.zig+1-1
...@@ -346,7 +346,7 @@ fn mode(comptime x: comptime_int) comptime_int {...@@ -346,7 +346,7 @@ fn mode(comptime x: comptime_int) comptime_int {
346}346}
347347
348pub fn main() !void {348pub fn main() !void {
349 const stdout = std.io.getStdOut().writer();349 const stdout = std.fs.File.stdout().writer().unbuffered();
350350
351 var buffer: [1024]u8 = undefined;351 var buffer: [1024]u8 = undefined;
352 var fixed = std.heap.FixedBufferAllocator.init(buffer[0..]);352 var fixed = std.heap.FixedBufferAllocator.init(buffer[0..]);
lib/std/io.zig-48
...@@ -14,54 +14,6 @@ const File = std.fs.File;...@@ -14,54 +14,6 @@ const File = std.fs.File;
14const Allocator = std.mem.Allocator;14const Allocator = std.mem.Allocator;
15const Alignment = std.mem.Alignment;15const Alignment = std.mem.Alignment;
1616
17fn getStdOutHandle() posix.fd_t {
18 if (is_windows) {
19 return windows.peb().ProcessParameters.hStdOutput;
20 }
21
22 if (@hasDecl(root, "os") and @hasDecl(root.os, "io") and @hasDecl(root.os.io, "getStdOutHandle")) {
23 return root.os.io.getStdOutHandle();
24 }
25
26 return posix.STDOUT_FILENO;
27}
28
29pub fn getStdOut() File {
30 return .{ .handle = getStdOutHandle() };
31}
32
33fn getStdErrHandle() posix.fd_t {
34 if (is_windows) {
35 return windows.peb().ProcessParameters.hStdError;
36 }
37
38 if (@hasDecl(root, "os") and @hasDecl(root.os, "io") and @hasDecl(root.os.io, "getStdErrHandle")) {
39 return root.os.io.getStdErrHandle();
40 }
41
42 return posix.STDERR_FILENO;
43}
44
45pub fn getStdErr() File {
46 return .{ .handle = getStdErrHandle() };
47}
48
49fn getStdInHandle() posix.fd_t {
50 if (is_windows) {
51 return windows.peb().ProcessParameters.hStdInput;
52 }
53
54 if (@hasDecl(root, "os") and @hasDecl(root.os, "io") and @hasDecl(root.os.io, "getStdInHandle")) {
55 return root.os.io.getStdInHandle();
56 }
57
58 return posix.STDIN_FILENO;
59}
60
61pub fn getStdIn() File {
62 return .{ .handle = getStdInHandle() };
63}
64
65pub const Reader = @import("io/Reader.zig");17pub const Reader = @import("io/Reader.zig");
66pub const Writer = @import("io/Writer.zig");18pub const Writer = @import("io/Writer.zig");
6719
lib/std/io/BufferedReader.zig+2-2
...@@ -421,9 +421,9 @@ pub fn takeByte(br: *BufferedReader) anyerror!u8 {...@@ -421,9 +421,9 @@ pub fn takeByte(br: *BufferedReader) anyerror!u8 {
421 return buffer[seek];421 return buffer[seek];
422}422}
423423
424/// Same as `readByte` except the returned byte is signed.424/// Same as `takeByte` except the returned byte is signed.
425pub fn takeByteSigned(br: *BufferedReader) anyerror!i8 {425pub fn takeByteSigned(br: *BufferedReader) anyerror!i8 {
426 return @bitCast(try br.readByte());426 return @bitCast(try br.takeByte());
427}427}
428428
429/// Asserts the buffer was initialized with a capacity at least `@sizeOf(T)`.429/// Asserts the buffer was initialized with a capacity at least `@sizeOf(T)`.
lib/std/io/Reader.zig+23-7
...@@ -2,7 +2,7 @@ const std = @import("../std.zig");...@@ -2,7 +2,7 @@ const std = @import("../std.zig");
2const Reader = @This();2const Reader = @This();
3const assert = std.debug.assert;3const assert = std.debug.assert;
44
5context: *anyopaque,5context: ?*anyopaque,
6vtable: *const VTable,6vtable: *const VTable,
77
8pub const VTable = struct {8pub const VTable = struct {
...@@ -19,8 +19,8 @@ pub const VTable = struct {...@@ -19,8 +19,8 @@ pub const VTable = struct {
19 ///19 ///
20 /// If this is `null` it is equivalent to always returning20 /// If this is `null` it is equivalent to always returning
21 /// `error.Unseekable`.21 /// `error.Unseekable`.
22 posRead: ?*const fn (ctx: *anyopaque, bw: *std.io.BufferedWriter, limit: Limit, offset: u64) anyerror!Status,22 posRead: ?*const fn (ctx: ?*anyopaque, bw: *std.io.BufferedWriter, limit: Limit, offset: u64) Result,
23 posReadVec: ?*const fn (ctx: *anyopaque, data: []const []u8, offset: u64) anyerror!Status,23 posReadVec: ?*const fn (ctx: ?*anyopaque, data: []const []u8, offset: u64) VecResult,
2424
25 /// Writes bytes from the internally tracked stream position to `bw`, or25 /// Writes bytes from the internally tracked stream position to `bw`, or
26 /// returns `error.Unstreamable`, indicating `posRead` should be used26 /// returns `error.Unstreamable`, indicating `posRead` should be used
...@@ -37,14 +37,30 @@ pub const VTable = struct {...@@ -37,14 +37,30 @@ pub const VTable = struct {
37 ///37 ///
38 /// If this is `null` it is equivalent to always returning38 /// If this is `null` it is equivalent to always returning
39 /// `error.Unstreamable`.39 /// `error.Unstreamable`.
40 streamRead: ?*const fn (ctx: *anyopaque, bw: *std.io.BufferedWriter, limit: Limit) anyerror!Status,40 streamRead: ?*const fn (ctx: ?*anyopaque, bw: *std.io.BufferedWriter, limit: Limit) Result,
41 streamReadVec: ?*const fn (ctx: *anyopaque, data: []const []u8) anyerror!Status,41 streamReadVec: ?*const fn (ctx: ?*anyopaque, data: []const []u8) VecResult,
42};42};
4343
44pub const Len = @Type(.{ .int = .{ .signedness = .unsigned, .bits = @bitSizeOf(usize) - 1 } });44pub const Len = @Type(.{ .int = .{ .signedness = .unsigned, .bits = @bitSizeOf(usize) - 1 } });
4545
46pub const Status = packed struct(usize) {46pub const VecResult = struct {
47 /// Number of bytes that were written to `writer`.47 /// Even when a failure occurs, `Effect.written` may be nonzero, and
48 /// `Effect.end` may be true.
49 failure: anyerror!void,
50 effect: VecEffect,
51};
52
53pub const Result = struct {
54 /// Even when a failure occurs, `Effect.written` may be nonzero, and
55 /// `Effect.end` may be true.
56 failure: anyerror!void,
57 write_effect: Effect,
58 read_effect: Effect,
59};
60
61pub const Effect = packed struct(usize) {
62 /// Number of bytes that were read from the reader or written to the
63 /// writer.
48 len: Len,64 len: Len,
49 /// Indicates end of stream.65 /// Indicates end of stream.
50 end: bool,66 end: bool,
lib/std/io/Writer.zig+18-2
...@@ -17,7 +17,7 @@ pub const VTable = struct {...@@ -17,7 +17,7 @@ pub const VTable = struct {
17 /// Number of bytes returned may be zero, which does not mean17 /// Number of bytes returned may be zero, which does not mean
18 /// end-of-stream. A subsequent call may return nonzero, or may signal end18 /// end-of-stream. A subsequent call may return nonzero, or may signal end
19 /// of stream via an error.19 /// of stream via an error.
20 writeSplat: *const fn (ctx: *anyopaque, data: []const []const u8, splat: usize) anyerror!usize,20 writeSplat: *const fn (ctx: *anyopaque, data: []const []const u8, splat: usize) Result,
2121
22 /// Writes contents from an open file. `headers` are written first, then `len`22 /// Writes contents from an open file. `headers` are written first, then `len`
23 /// bytes of `file` starting from `offset`, then `trailers`.23 /// bytes of `file` starting from `offset`, then `trailers`.
...@@ -38,7 +38,23 @@ pub const VTable = struct {...@@ -38,7 +38,23 @@ pub const VTable = struct {
38 /// zero, they can be forwarded directly to `VTable.writev`.38 /// zero, they can be forwarded directly to `VTable.writev`.
39 headers_and_trailers: []const []const u8,39 headers_and_trailers: []const []const u8,
40 headers_len: usize,40 headers_len: usize,
41 ) anyerror!usize,41 ) Result,
42};
43
44pub const Len = @Type(.{ .int = .{ .signedness = .unsigned, .bits = @bitSizeOf(usize) - 1 } });
45
46pub const Result = struct {
47 /// Even when a failure occurs, `Effect.written` may be nonzero, and
48 /// `Effect.end` may be true.
49 failure: anyerror!void,
50 effect: Effect,
51};
52
53pub const Effect = packed struct(usize) {
54 /// Number of bytes that were written to `writer`.
55 len: Len,
56 /// Indicates end of stream.
57 end: bool,
42};58};
4359
44pub const Offset = enum(u64) {60pub const Offset = enum(u64) {
lib/std/json/dynamic.zig+1-1
...@@ -51,7 +51,7 @@ pub const Value = union(enum) {...@@ -51,7 +51,7 @@ pub const Value = union(enum) {
51 }51 }
5252
53 pub fn dump(v: Value) void {53 pub fn dump(v: Value) void {
54 var bw = std.debug.lockStdErr2();54 var bw = std.debug.lockStdErr2(&.{});
55 defer std.debug.unlockStdErr();55 defer std.debug.unlockStdErr();
5656
57 json.Stringify.value(v, .{}, &bw) catch return;57 json.Stringify.value(v, .{}, &bw) catch return;
lib/std/log.zig+2-6
...@@ -47,7 +47,7 @@...@@ -47,7 +47,7 @@
47//! // Print the message to stderr, silently ignoring any errors47//! // Print the message to stderr, silently ignoring any errors
48//! std.debug.lockStdErr();48//! std.debug.lockStdErr();
49//! defer std.debug.unlockStdErr();49//! defer std.debug.unlockStdErr();
50//! const stderr = std.io.getStdErr().writer();50//! const stderr = std.fs.File.stderr().writer();
51//! nosuspend stderr.print(prefix ++ format ++ "\n", args) catch return;51//! nosuspend stderr.print(prefix ++ format ++ "\n", args) catch return;
52//! }52//! }
53//!53//!
...@@ -149,11 +149,7 @@ pub fn defaultLog(...@@ -149,11 +149,7 @@ pub fn defaultLog(
149 const level_txt = comptime message_level.asText();149 const level_txt = comptime message_level.asText();
150 const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";150 const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";
151 var buffer: [1024]u8 = undefined;151 var buffer: [1024]u8 = undefined;
152 var bw: std.io.BufferedWriter = .{152 var bw: std.io.BufferedWriter = std.debug.lockStdErr2(&buffer);
153 .unbuffered_writer = std.io.getStdErr().writer(),
154 .buffer = &buffer,
155 };
156 std.debug.lockStdErr();
157 defer std.debug.unlockStdErr();153 defer std.debug.unlockStdErr();
158 nosuspend {154 nosuspend {
159 bw.print(level_txt ++ prefix2 ++ format ++ "\n", args) catch return;155 bw.print(level_txt ++ prefix2 ++ format ++ "\n", args) catch return;
lib/std/testing.zig+2-2
...@@ -390,9 +390,9 @@ pub fn expectEqualSlices(comptime T: type, expected: []const T, actual: []const...@@ -390,9 +390,9 @@ pub fn expectEqualSlices(comptime T: type, expected: []const T, actual: []const
390 const actual_window = actual[window_start..@min(actual.len, window_start + max_window_size)];390 const actual_window = actual[window_start..@min(actual.len, window_start + max_window_size)];
391 const actual_truncated = window_start + actual_window.len < actual.len;391 const actual_truncated = window_start + actual_window.len < actual.len;
392392
393 var bw = std.debug.lockStdErr2();393 var bw = std.debug.lockStdErr2(&.{});
394 defer std.debug.unlockStdErr();394 defer std.debug.unlockStdErr();
395 const ttyconf = std.io.tty.detectConfig(std.io.getStdErr());395 const ttyconf = std.io.tty.detectConfig(.stderr());
396 var differ = if (T == u8) BytesDiffer{396 var differ = if (T == u8) BytesDiffer{
397 .expected = expected_window,397 .expected = expected_window,
398 .actual = actual_window,398 .actual = actual_window,
lib/std/unicode/throughput_test.zig+1-1
...@@ -39,7 +39,7 @@ fn benchmarkCodepointCount(buf: []const u8) !ResultCount {...@@ -39,7 +39,7 @@ fn benchmarkCodepointCount(buf: []const u8) !ResultCount {
39}39}
4040
41pub fn main() !void {41pub fn main() !void {
42 const stdout = std.io.getStdOut().writer();42 const stdout = std.fs.File.stdout().writer();
4343
44 try stdout.print("short ASCII strings\n", .{});44 try stdout.print("short ASCII strings\n", .{});
45 {45 {
lib/std/zig.zig+1-1
...@@ -48,7 +48,7 @@ pub const Color = enum {...@@ -48,7 +48,7 @@ pub const Color = enum {
4848
49 pub fn get_tty_conf(color: Color) std.io.tty.Config {49 pub fn get_tty_conf(color: Color) std.io.tty.Config {
50 return switch (color) {50 return switch (color) {
51 .auto => std.io.tty.detectConfig(std.io.getStdErr()),51 .auto => std.io.tty.detectConfig(.stderr()),
52 .on => .escape_codes,52 .on => .escape_codes,
53 .off => .no_color,53 .off => .no_color,
54 };54 };
lib/std/zig/ErrorBundle.zig+2-6
...@@ -157,13 +157,9 @@ pub const RenderOptions = struct {...@@ -157,13 +157,9 @@ pub const RenderOptions = struct {
157};157};
158158
159pub fn renderToStdErr(eb: ErrorBundle, options: RenderOptions) void {159pub fn renderToStdErr(eb: ErrorBundle, options: RenderOptions) void {
160 std.debug.lockStdErr();
161 defer std.debug.unlockStdErr();
162 var buffer: [256]u8 = undefined;160 var buffer: [256]u8 = undefined;
163 var bw: std.io.BufferedWriter = .{161 var bw = std.debug.lockStdErr2(&buffer);
164 .unbuffered_writer = std.io.getStdErr().writer(),162 defer std.debug.unlockStdErr();
165 .buffer = &buffer,
166 };
167 renderToWriter(eb, options, &bw) catch return;163 renderToWriter(eb, options, &bw) catch return;
168 bw.flush() catch return;164 bw.flush() catch return;
169}165}
lib/std/zig/llvm/Builder.zig+3-2
...@@ -9493,7 +9493,8 @@ pub fn asmValue(...@@ -9493,7 +9493,8 @@ pub fn asmValue(
9493}9493}
94949494
9495pub fn dump(self: *Builder) void {9495pub fn dump(self: *Builder) void {
9496 self.print(std.io.getStdErr().writer()) catch {};9496 const stderr: std.fs.File = .stderr();
9497 self.print(stderr.writer().unbuffered()) catch {};
9497}9498}
94989499
9499pub fn printToFile(self: *Builder, path: []const u8) Allocator.Error!bool {9500pub fn printToFile(self: *Builder, path: []const u8) Allocator.Error!bool {
...@@ -9509,7 +9510,7 @@ pub fn printToFile(self: *Builder, path: []const u8) Allocator.Error!bool {...@@ -9509,7 +9510,7 @@ pub fn printToFile(self: *Builder, path: []const u8) Allocator.Error!bool {
9509 return true;9510 return true;
9510}9511}
95119512
9512pub fn print(self: *Builder, writer: anytype) (@TypeOf(writer).Error || Allocator.Error)!void {9513pub fn print(self: *Builder, writer: *std.io.BufferedWriter) (@TypeOf(writer).Error || Allocator.Error)!void {
9513 var bw = std.io.bufferedWriter(writer);9514 var bw = std.io.bufferedWriter(writer);
9514 try self.printUnbuffered(bw.writer());9515 try self.printUnbuffered(bw.writer());
9515 try bw.flush();9516 try bw.flush();
lib/std/zig/parser_test.zig+8-7
...@@ -6463,24 +6463,25 @@ const maxInt = std.math.maxInt;...@@ -6463,24 +6463,25 @@ const maxInt = std.math.maxInt;
6463var fixed_buffer_mem: [100 * 1024]u8 = undefined;6463var fixed_buffer_mem: [100 * 1024]u8 = undefined;
64646464
6465fn testParse(source: [:0]const u8, allocator: mem.Allocator, anything_changed: *bool) ![]u8 {6465fn testParse(source: [:0]const u8, allocator: mem.Allocator, anything_changed: *bool) ![]u8 {
6466 const stderr = io.getStdErr().writer();6466 const stderr: std.fs.File = .stderr();
6467 const stderr_writer = stderr.writer().unbuffered();
64676468
6468 var tree = try std.zig.Ast.parse(allocator, source, .zig);6469 var tree = try std.zig.Ast.parse(allocator, source, .zig);
6469 defer tree.deinit(allocator);6470 defer tree.deinit(allocator);
64706471
6471 for (tree.errors) |parse_error| {6472 for (tree.errors) |parse_error| {
6472 const loc = tree.tokenLocation(0, parse_error.token);6473 const loc = tree.tokenLocation(0, parse_error.token);
6473 try stderr.print("(memory buffer):{d}:{d}: error: ", .{ loc.line + 1, loc.column + 1 });6474 try stderr_writer.print("(memory buffer):{d}:{d}: error: ", .{ loc.line + 1, loc.column + 1 });
6474 try tree.renderError(parse_error, stderr);6475 try tree.renderError(parse_error, stderr_writer);
6475 try stderr.print("\n{s}\n", .{source[loc.line_start..loc.line_end]});6476 try stderr_writer.print("\n{s}\n", .{source[loc.line_start..loc.line_end]});
6476 {6477 {
6477 var i: usize = 0;6478 var i: usize = 0;
6478 while (i < loc.column) : (i += 1) {6479 while (i < loc.column) : (i += 1) {
6479 try stderr.writeAll(" ");6480 try stderr_writer.writeAll(" ");
6480 }6481 }
6481 try stderr.writeAll("^");6482 try stderr_writer.writeAll("^");
6482 }6483 }
6483 try stderr.writeAll("\n");6484 try stderr_writer.writeAll("\n");
6484 }6485 }
6485 if (tree.errors.len != 0) {6486 if (tree.errors.len != 0) {
6486 return error.ParseError;6487 return error.ParseError;
lib/std/zig/perf_test.zig+1-1
...@@ -22,7 +22,7 @@ pub fn main() !void {...@@ -22,7 +22,7 @@ pub fn main() !void {
22 const bytes_per_sec_float = @as(f64, @floatFromInt(source.len * iterations)) / elapsed_s;22 const bytes_per_sec_float = @as(f64, @floatFromInt(source.len * iterations)) / elapsed_s;
23 const bytes_per_sec = @as(u64, @intFromFloat(@floor(bytes_per_sec_float)));23 const bytes_per_sec = @as(u64, @intFromFloat(@floor(bytes_per_sec_float)));
2424
25 var stdout_file = std.io.getStdOut();25 var stdout_file: std.fs.File = .stdout();
26 const stdout = stdout_file.writer();26 const stdout = stdout_file.writer();
27 try stdout.print("parsing speed: {:.2}/s, {:.2} used \n", .{27 try stdout.print("parsing speed: {:.2}/s, {:.2} used \n", .{
28 fmtIntSizeBin(bytes_per_sec),28 fmtIntSizeBin(bytes_per_sec),
src/Air/print.zig+2-2
...@@ -72,13 +72,13 @@ pub fn writeInst(...@@ -72,13 +72,13 @@ pub fn writeInst(
72}72}
7373
74pub fn dump(air: Air, pt: Zcu.PerThread, liveness: ?Air.Liveness) void {74pub fn dump(air: Air, pt: Zcu.PerThread, liveness: ?Air.Liveness) void {
75 var bw = std.debug.lockStdErr2();75 var bw = std.debug.lockStdErr2(&.{});
76 defer std.debug.unlockStdErr();76 defer std.debug.unlockStdErr();
77 air.write(&bw, pt, liveness);77 air.write(&bw, pt, liveness);
78}78}
7979
80pub fn dumpInst(air: Air, inst: Air.Inst.Index, pt: Zcu.PerThread, liveness: ?Air.Liveness) void {80pub fn dumpInst(air: Air, inst: Air.Inst.Index, pt: Zcu.PerThread, liveness: ?Air.Liveness) void {
81 var bw = std.debug.lockStdErr2();81 var bw = std.debug.lockStdErr2(&.{});
82 defer std.debug.unlockStdErr();82 defer std.debug.unlockStdErr();
83 air.writeInst(&bw, inst, pt, liveness);83 air.writeInst(&bw, inst, pt, liveness);
84}84}
src/Compilation.zig+9-7
...@@ -1880,7 +1880,7 @@ pub fn create(gpa: Allocator, arena: Allocator, options: CreateOptions) !*Compil...@@ -1880,7 +1880,7 @@ pub fn create(gpa: Allocator, arena: Allocator, options: CreateOptions) !*Compil
18801880
1881 if (options.verbose_llvm_cpu_features) {1881 if (options.verbose_llvm_cpu_features) {
1882 if (options.root_mod.resolved_target.llvm_cpu_features) |cf| print: {1882 if (options.root_mod.resolved_target.llvm_cpu_features) |cf| print: {
1883 var stderr = std.debug.lockStdErr2();1883 var stderr = std.debug.lockStdErr2(&.{});
1884 defer std.debug.unlockStdErr();1884 defer std.debug.unlockStdErr();
1885 nosuspend {1885 nosuspend {
1886 stderr.print("compilation: {s}\n", .{options.root_name}) catch break :print;1886 stderr.print("compilation: {s}\n", .{options.root_name}) catch break :print;
...@@ -3942,7 +3942,8 @@ pub fn getAllErrorsAlloc(comp: *Compilation) !ErrorBundle {...@@ -3942,7 +3942,8 @@ pub fn getAllErrorsAlloc(comp: *Compilation) !ErrorBundle {
3942 // This AU is referenced and has a transitive compile error, meaning it referenced something with a compile error.3942 // This AU is referenced and has a transitive compile error, meaning it referenced something with a compile error.
3943 // However, we haven't reported any such error.3943 // However, we haven't reported any such error.
3944 // This is a compiler bug.3944 // This is a compiler bug.
3945 const stderr = std.io.getStdErr().writer();3945 var stderr = std.debug.lockStdErr2(&.{});
3946 defer std.debug.unlockStdErr();
3946 try stderr.writeAll("referenced transitive analysis errors, but none actually emitted\n");3947 try stderr.writeAll("referenced transitive analysis errors, but none actually emitted\n");
3947 try stderr.print("{} [transitive failure]\n", .{zcu.fmtAnalUnit(failed_unit)});3948 try stderr.print("{} [transitive failure]\n", .{zcu.fmtAnalUnit(failed_unit)});
3948 while (ref) |r| {3949 while (ref) |r| {
...@@ -7222,13 +7223,14 @@ pub fn lockAndSetMiscFailure(...@@ -7222,13 +7223,14 @@ pub fn lockAndSetMiscFailure(
7222}7223}
72237224
7224pub fn dump_argv(argv: []const []const u8) void {7225pub fn dump_argv(argv: []const []const u8) void {
7225 std.debug.lockStdErr();7226 var stderr = std.debug.lockStdErr2(&.{});
7226 defer std.debug.unlockStdErr();7227 defer std.debug.unlockStdErr();
7227 const stderr = std.io.getStdErr().writer();7228 nosuspend {
7228 for (argv[0 .. argv.len - 1]) |arg| {7229 for (argv[0 .. argv.len - 1]) |arg| {
7229 nosuspend stderr.print("{s} ", .{arg}) catch return;7230 stderr.print("{s} ", .{arg}) catch return;
7231 }
7232 stderr.print("{s}\n", .{argv[argv.len - 1]}) catch {};
7230 }7233 }
7231 nosuspend stderr.print("{s}\n", .{argv[argv.len - 1]}) catch {};
7232}7234}
72337235
7234pub fn getZigBackend(comp: Compilation) std.builtin.CompilerBackend {7236pub fn getZigBackend(comp: Compilation) std.builtin.CompilerBackend {
src/InternPool.zig+17-15
...@@ -11267,8 +11267,9 @@ fn dumpStatsFallible(ip: *const InternPool, arena: Allocator) anyerror!void {...@@ -11267,8 +11267,9 @@ fn dumpStatsFallible(ip: *const InternPool, arena: Allocator) anyerror!void {
11267}11267}
1126811268
11269fn dumpAllFallible(ip: *const InternPool) anyerror!void {11269fn dumpAllFallible(ip: *const InternPool) anyerror!void {
11270 var bw = std.io.bufferedWriter(std.io.getStdErr().writer());11270 var buffer: [4096]u8 = undefined;
11271 const w = bw.writer();11271 var bw = std.debug.lockStdErr2(&buffer);
11272 defer std.debug.unlockStdErr();
11272 for (ip.locals, 0..) |*local, tid| {11273 for (ip.locals, 0..) |*local, tid| {
11273 const items = local.shared.items.view();11274 const items = local.shared.items.view();
11274 for (11275 for (
...@@ -11277,12 +11278,12 @@ fn dumpAllFallible(ip: *const InternPool) anyerror!void {...@@ -11277,12 +11278,12 @@ fn dumpAllFallible(ip: *const InternPool) anyerror!void {
11277 0..,11278 0..,
11278 ) |tag, data, index| {11279 ) |tag, data, index| {
11279 const i = Index.Unwrapped.wrap(.{ .tid = @enumFromInt(tid), .index = @intCast(index) }, ip);11280 const i = Index.Unwrapped.wrap(.{ .tid = @enumFromInt(tid), .index = @intCast(index) }, ip);
11280 try w.print("${d} = {s}(", .{ i, @tagName(tag) });11281 try bw.print("${d} = {s}(", .{ i, @tagName(tag) });
11281 switch (tag) {11282 switch (tag) {
11282 .removed => {},11283 .removed => {},
1128311284
11284 .simple_type => try w.print("{s}", .{@tagName(@as(SimpleType, @enumFromInt(@intFromEnum(i))))}),11285 .simple_type => try bw.print("{s}", .{@tagName(@as(SimpleType, @enumFromInt(@intFromEnum(i))))}),
11285 .simple_value => try w.print("{s}", .{@tagName(@as(SimpleValue, @enumFromInt(@intFromEnum(i))))}),11286 .simple_value => try bw.print("{s}", .{@tagName(@as(SimpleValue, @enumFromInt(@intFromEnum(i))))}),
1128611287
11287 .type_int_signed,11288 .type_int_signed,
11288 .type_int_unsigned,11289 .type_int_unsigned,
...@@ -11355,14 +11356,14 @@ fn dumpAllFallible(ip: *const InternPool) anyerror!void {...@@ -11355,14 +11356,14 @@ fn dumpAllFallible(ip: *const InternPool) anyerror!void {
11355 .func_coerced,11356 .func_coerced,
11356 .union_value,11357 .union_value,
11357 .memoized_call,11358 .memoized_call,
11358 => try w.print("{d}", .{data}),11359 => try bw.print("{d}", .{data}),
1135911360
11360 .opt_null,11361 .opt_null,
11361 .type_slice,11362 .type_slice,
11362 .only_possible_value,11363 .only_possible_value,
11363 => try w.print("${d}", .{data}),11364 => try bw.print("${d}", .{data}),
11364 }11365 }
11365 try w.writeAll(")\n");11366 try bw.writeAll(")\n");
11366 }11367 }
11367 }11368 }
11368 try bw.flush();11369 try bw.flush();
...@@ -11377,9 +11378,6 @@ pub fn dumpGenericInstancesFallible(ip: *const InternPool, allocator: Allocator)...@@ -11377,9 +11378,6 @@ pub fn dumpGenericInstancesFallible(ip: *const InternPool, allocator: Allocator)
11377 defer arena_allocator.deinit();11378 defer arena_allocator.deinit();
11378 const arena = arena_allocator.allocator();11379 const arena = arena_allocator.allocator();
1137911380
11380 var bw = std.io.bufferedWriter(std.io.getStdErr().writer());
11381 const w = bw.writer();
11382
11383 var instances: std.AutoArrayHashMapUnmanaged(Index, std.ArrayListUnmanaged(Index)) = .empty;11381 var instances: std.AutoArrayHashMapUnmanaged(Index, std.ArrayListUnmanaged(Index)) = .empty;
11384 for (ip.locals, 0..) |*local, tid| {11382 for (ip.locals, 0..) |*local, tid| {
11385 const items = local.shared.items.view().slice();11383 const items = local.shared.items.view().slice();
...@@ -11402,6 +11400,10 @@ pub fn dumpGenericInstancesFallible(ip: *const InternPool, allocator: Allocator)...@@ -11402,6 +11400,10 @@ pub fn dumpGenericInstancesFallible(ip: *const InternPool, allocator: Allocator)
11402 }11400 }
11403 }11401 }
1140411402
11403 var buffer: [4096]u8 = undefined;
11404 var bw = std.debug.lockStdErr2(&buffer);
11405 defer std.debug.unlockStdErr();
11406
11405 const SortContext = struct {11407 const SortContext = struct {
11406 values: []std.ArrayListUnmanaged(Index),11408 values: []std.ArrayListUnmanaged(Index),
11407 pub fn lessThan(ctx: @This(), a_index: usize, b_index: usize) bool {11409 pub fn lessThan(ctx: @This(), a_index: usize, b_index: usize) bool {
...@@ -11413,19 +11415,19 @@ pub fn dumpGenericInstancesFallible(ip: *const InternPool, allocator: Allocator)...@@ -11413,19 +11415,19 @@ pub fn dumpGenericInstancesFallible(ip: *const InternPool, allocator: Allocator)
11413 var it = instances.iterator();11415 var it = instances.iterator();
11414 while (it.next()) |entry| {11416 while (it.next()) |entry| {
11415 const generic_fn_owner_nav = ip.getNav(ip.funcDeclInfo(entry.key_ptr.*).owner_nav);11417 const generic_fn_owner_nav = ip.getNav(ip.funcDeclInfo(entry.key_ptr.*).owner_nav);
11416 try w.print("{} ({}): \n", .{ generic_fn_owner_nav.name.fmt(ip), entry.value_ptr.items.len });11418 try bw.print("{} ({}): \n", .{ generic_fn_owner_nav.name.fmt(ip), entry.value_ptr.items.len });
11417 for (entry.value_ptr.items) |index| {11419 for (entry.value_ptr.items) |index| {
11418 const unwrapped_index = index.unwrap(ip);11420 const unwrapped_index = index.unwrap(ip);
11419 const func = ip.extraFuncInstance(unwrapped_index.tid, unwrapped_index.getExtra(ip), unwrapped_index.getData(ip));11421 const func = ip.extraFuncInstance(unwrapped_index.tid, unwrapped_index.getExtra(ip), unwrapped_index.getData(ip));
11420 const owner_nav = ip.getNav(func.owner_nav);11422 const owner_nav = ip.getNav(func.owner_nav);
11421 try w.print(" {}: (", .{owner_nav.name.fmt(ip)});11423 try bw.print(" {}: (", .{owner_nav.name.fmt(ip)});
11422 for (func.comptime_args.get(ip)) |arg| {11424 for (func.comptime_args.get(ip)) |arg| {
11423 if (arg != .none) {11425 if (arg != .none) {
11424 const key = ip.indexToKey(arg);11426 const key = ip.indexToKey(arg);
11425 try w.print(" {} ", .{key});11427 try bw.print(" {} ", .{key});
11426 }11428 }
11427 }11429 }
11428 try w.writeAll(")\n");11430 try bw.writeAll(")\n");
11429 }11431 }
11430 }11432 }
1143111433
src/Package/Fetch.zig+1-4
...@@ -1643,10 +1643,7 @@ fn computeHash(f: *Fetch, pkg_path: Cache.Path, filter: Filter) RunError!Compute...@@ -1643,10 +1643,7 @@ fn computeHash(f: *Fetch, pkg_path: Cache.Path, filter: Filter) RunError!Compute
16431643
1644fn dumpHashInfo(all_files: []const *const HashedFile) !void {1644fn dumpHashInfo(all_files: []const *const HashedFile) !void {
1645 var buffer: [4096]u8 = undefined;1645 var buffer: [4096]u8 = undefined;
1646 var bw: std.io.BufferedWriter = .{1646 var bw: std.io.BufferedWriter = std.fs.File.stdout().writer().buffered(&buffer);
1647 .unbuffered_writer = std.io.getStdOut().writer(),
1648 .buffer = &buffer,
1649 };
1650 for (all_files) |hashed_file| {1647 for (all_files) |hashed_file| {
1651 try bw.print("{s}: {x}: {s}\n", .{1648 try bw.print("{s}: {x}: {s}\n", .{
1652 @tagName(hashed_file.kind), &hashed_file.hash, hashed_file.normalized_path,1649 @tagName(hashed_file.kind), &hashed_file.hash, hashed_file.normalized_path,
src/crash_report.zig+7-8
...@@ -80,7 +80,7 @@ fn dumpStatusReport() !void {...@@ -80,7 +80,7 @@ fn dumpStatusReport() !void {
80 var fba = std.heap.FixedBufferAllocator.init(&crash_heap);80 var fba = std.heap.FixedBufferAllocator.init(&crash_heap);
81 const allocator = fba.allocator();81 const allocator = fba.allocator();
8282
83 const stderr = io.getStdErr().writer();83 const stderr = std.fs.File.stderr.writer().unbuffered();
84 const block: *Sema.Block = anal.block;84 const block: *Sema.Block = anal.block;
85 const zcu = anal.sema.pt.zcu;85 const zcu = anal.sema.pt.zcu;
8686
...@@ -271,8 +271,7 @@ const StackContext = union(enum) {...@@ -271,8 +271,7 @@ const StackContext = union(enum) {
271 debug.dumpStackTraceFromBase(context);271 debug.dumpStackTraceFromBase(context);
272 },272 },
273 .not_supported => {273 .not_supported => {
274 const stderr = io.getStdErr().writer();274 std.fs.File.stderr().writeAll("Stack trace not supported on this platform.\n") catch {};
275 stderr.writeAll("Stack trace not supported on this platform.\n") catch {};
276 },275 },
277 }276 }
278 }277 }
...@@ -379,7 +378,7 @@ const PanicSwitch = struct {...@@ -379,7 +378,7 @@ const PanicSwitch = struct {
379378
380 state.recover_stage = .release_mutex;379 state.recover_stage = .release_mutex;
381380
382 const stderr = io.getStdErr().writer();381 const stderr = std.fs.File.stderr().writer().unbuffered();
383 if (builtin.single_threaded) {382 if (builtin.single_threaded) {
384 stderr.print("panic: ", .{}) catch goTo(releaseMutex, .{state});383 stderr.print("panic: ", .{}) catch goTo(releaseMutex, .{state});
385 } else {384 } else {
...@@ -406,7 +405,7 @@ const PanicSwitch = struct {...@@ -406,7 +405,7 @@ const PanicSwitch = struct {
406 recover(state, trace, stack, msg);405 recover(state, trace, stack, msg);
407406
408 state.recover_stage = .release_mutex;407 state.recover_stage = .release_mutex;
409 const stderr = io.getStdErr().writer();408 const stderr = std.fs.File.stderr().writer().unbuffered();
410 stderr.writeAll("\nOriginal Error:\n") catch {};409 stderr.writeAll("\nOriginal Error:\n") catch {};
411 goTo(reportStack, .{state});410 goTo(reportStack, .{state});
412 }411 }
...@@ -477,7 +476,7 @@ const PanicSwitch = struct {...@@ -477,7 +476,7 @@ const PanicSwitch = struct {
477 recover(state, trace, stack, msg);476 recover(state, trace, stack, msg);
478477
479 state.recover_stage = .silent_abort;478 state.recover_stage = .silent_abort;
480 const stderr = io.getStdErr().writer();479 var stderr = std.fs.File.stderr().writer().unbuffered();
481 stderr.writeAll("Aborting...\n") catch {};480 stderr.writeAll("Aborting...\n") catch {};
482 goTo(abort, .{});481 goTo(abort, .{});
483 }482 }
...@@ -505,7 +504,7 @@ const PanicSwitch = struct {...@@ -505,7 +504,7 @@ const PanicSwitch = struct {
505 // lower the verbosity, and restore it at the end if we don't panic.504 // lower the verbosity, and restore it at the end if we don't panic.
506 state.recover_verbosity = .message_only;505 state.recover_verbosity = .message_only;
507506
508 const stderr = io.getStdErr().writer();507 var stderr = std.fs.File.stderr().writer().unbuffered();
509 stderr.writeAll("\nPanicked during a panic: ") catch {};508 stderr.writeAll("\nPanicked during a panic: ") catch {};
510 stderr.writeAll(msg) catch {};509 stderr.writeAll(msg) catch {};
511 stderr.writeAll("\nInner panic stack:\n") catch {};510 stderr.writeAll("\nInner panic stack:\n") catch {};
...@@ -519,7 +518,7 @@ const PanicSwitch = struct {...@@ -519,7 +518,7 @@ const PanicSwitch = struct {
519 .message_only => {518 .message_only => {
520 state.recover_verbosity = .silent;519 state.recover_verbosity = .silent;
521520
522 const stderr = io.getStdErr().writer();521 var stderr = std.fs.File.stderr().writer().unbuffered();
523 stderr.writeAll("\nPanicked while dumping inner panic stack: ") catch {};522 stderr.writeAll("\nPanicked while dumping inner panic stack: ") catch {};
524 stderr.writeAll(msg) catch {};523 stderr.writeAll(msg) catch {};
525 stderr.writeAll("\n") catch {};524 stderr.writeAll("\n") catch {};
src/fmt.zig+4-8
...@@ -49,7 +49,7 @@ pub fn run(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {...@@ -49,7 +49,7 @@ pub fn run(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
49 const arg = args[i];49 const arg = args[i];
50 if (mem.startsWith(u8, arg, "-")) {50 if (mem.startsWith(u8, arg, "-")) {
51 if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {51 if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {
52 try std.io.getStdOut().writeAll(usage_fmt);52 try std.fs.File.stdout().writeAll(usage_fmt);
53 return process.cleanExit();53 return process.cleanExit();
54 } else if (mem.eql(u8, arg, "--color")) {54 } else if (mem.eql(u8, arg, "--color")) {
55 if (i + 1 >= args.len) {55 if (i + 1 >= args.len) {
...@@ -89,8 +89,7 @@ pub fn run(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {...@@ -89,8 +89,7 @@ pub fn run(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
89 fatal("cannot use --stdin with positional arguments", .{});89 fatal("cannot use --stdin with positional arguments", .{});
90 }90 }
9191
92 const stdin = std.io.getStdIn();92 const source_code = std.zig.readSourceFileToEndAlloc(gpa, .stdin(), null) catch |err| {
93 const source_code = std.zig.readSourceFileToEndAlloc(gpa, stdin, null) catch |err| {
94 fatal("unable to read stdin: {}", .{err});93 fatal("unable to read stdin: {}", .{err});
95 };94 };
96 defer gpa.free(source_code);95 defer gpa.free(source_code);
...@@ -145,7 +144,7 @@ pub fn run(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {...@@ -145,7 +144,7 @@ pub fn run(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
145 process.exit(code);144 process.exit(code);
146 }145 }
147146
148 return std.io.getStdOut().writeAll(formatted);147 return std.fs.File.stdout().writeAll(formatted);
149 }148 }
150149
151 if (input_files.items.len == 0) {150 if (input_files.items.len == 0) {
...@@ -153,10 +152,7 @@ pub fn run(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {...@@ -153,10 +152,7 @@ pub fn run(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
153 }152 }
154153
155 var stdout_buffer: [4096]u8 = undefined;154 var stdout_buffer: [4096]u8 = undefined;
156 var stdout: std.io.BufferedWriter = .{155 var stdout: std.io.BufferedWriter = std.fs.File.stdout().writer().buffered(&stdout_buffer);
157 .buffer = &stdout_buffer,
158 .unbuffered_writer = std.io.getStdOut().writer(),
159 };
160156
161 var fmt: Fmt = .{157 var fmt: Fmt = .{
162 .gpa = gpa,158 .gpa = gpa,
src/libs/mingw.zig+2-2
...@@ -304,7 +304,7 @@ pub fn buildImportLib(comp: *Compilation, lib_name: []const u8) !void {...@@ -304,7 +304,7 @@ pub fn buildImportLib(comp: *Compilation, lib_name: []const u8) !void {
304 const include_dir = try comp.dirs.zig_lib.join(arena, &.{ "libc", "mingw", "def-include" });304 const include_dir = try comp.dirs.zig_lib.join(arena, &.{ "libc", "mingw", "def-include" });
305305
306 if (comp.verbose_cc) print: {306 if (comp.verbose_cc) print: {
307 var stderr = std.debug.lockStdErr2();307 var stderr = std.debug.lockStdErr2(&.{});
308 defer std.debug.unlockStdErr();308 defer std.debug.unlockStdErr();
309 nosuspend stderr.print("def file: {s}\n", .{def_file_path}) catch break :print;309 nosuspend stderr.print("def file: {s}\n", .{def_file_path}) catch break :print;
310 nosuspend stderr.print("include dir: {s}\n", .{include_dir}) catch break :print;310 nosuspend stderr.print("include dir: {s}\n", .{include_dir}) catch break :print;
...@@ -325,7 +325,7 @@ pub fn buildImportLib(comp: *Compilation, lib_name: []const u8) !void {...@@ -325,7 +325,7 @@ pub fn buildImportLib(comp: *Compilation, lib_name: []const u8) !void {
325325
326 for (aro_comp.diagnostics.list.items) |diagnostic| {326 for (aro_comp.diagnostics.list.items) |diagnostic| {
327 if (diagnostic.kind == .@"fatal error" or diagnostic.kind == .@"error") {327 if (diagnostic.kind == .@"fatal error" or diagnostic.kind == .@"error") {
328 aro.Diagnostics.render(&aro_comp, std.io.tty.detectConfig(std.io.getStdErr()));328 aro.Diagnostics.render(&aro_comp, std.io.tty.detectConfig(.stderr()));
329 return error.AroPreprocessorFailed;329 return error.AroPreprocessorFailed;
330 }330 }
331 }331 }
src/link/Elf/gc.zig+2-2
...@@ -163,13 +163,13 @@ fn prune(elf_file: *Elf) void {...@@ -163,13 +163,13 @@ fn prune(elf_file: *Elf) void {
163}163}
164164
165pub fn dumpPrunedAtoms(elf_file: *Elf) !void {165pub fn dumpPrunedAtoms(elf_file: *Elf) !void {
166 const stderr = std.io.getStdErr().writer();166 var stderr = std.debug.lockStdErr2(&.{});
167 defer std.debug.unlockStdErr();
167 for (elf_file.objects.items) |index| {168 for (elf_file.objects.items) |index| {
168 const file = elf_file.file(index).?;169 const file = elf_file.file(index).?;
169 for (file.atoms()) |atom_index| {170 for (file.atoms()) |atom_index| {
170 const atom = file.atom(atom_index) orelse continue;171 const atom = file.atom(atom_index) orelse continue;
171 if (!atom.alive)172 if (!atom.alive)
172 // TODO should we simply print to stderr?
173 try stderr.print("link: removing unused section '{s}' in file '{}'\n", .{173 try stderr.print("link: removing unused section '{s}' in file '{}'\n", .{
174 atom.name(elf_file),174 atom.name(elf_file),
175 atom.file(elf_file).?.fmtPath(),175 atom.file(elf_file).?.fmtPath(),
src/main.zig+22-22
...@@ -344,7 +344,7 @@ fn mainArgs(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {...@@ -344,7 +344,7 @@ fn mainArgs(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
344 return @import("print_targets.zig").cmdTargets(arena, cmd_args);344 return @import("print_targets.zig").cmdTargets(arena, cmd_args);
345 } else if (mem.eql(u8, cmd, "version")) {345 } else if (mem.eql(u8, cmd, "version")) {
346 dev.check(.version_command);346 dev.check(.version_command);
347 try std.io.getStdOut().writeAll(build_options.version ++ "\n");347 try fs.File.stdout().writeAll(build_options.version ++ "\n");
348 // Check libc++ linkage to make sure Zig was built correctly, but only348 // Check libc++ linkage to make sure Zig was built correctly, but only
349 // for "env" and "version" to avoid affecting the startup time for349 // for "env" and "version" to avoid affecting the startup time for
350 // build-critical commands (check takes about ~10 μs)350 // build-critical commands (check takes about ~10 μs)
...@@ -360,10 +360,10 @@ fn mainArgs(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {...@@ -360,10 +360,10 @@ fn mainArgs(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
360 });360 });
361 } else if (mem.eql(u8, cmd, "zen")) {361 } else if (mem.eql(u8, cmd, "zen")) {
362 dev.check(.zen_command);362 dev.check(.zen_command);
363 return io.getStdOut().writeAll(info_zen);363 return fs.File.stdout().writeAll(info_zen);
364 } else if (mem.eql(u8, cmd, "help") or mem.eql(u8, cmd, "-h") or mem.eql(u8, cmd, "--help")) {364 } else if (mem.eql(u8, cmd, "help") or mem.eql(u8, cmd, "-h") or mem.eql(u8, cmd, "--help")) {
365 dev.check(.help_command);365 dev.check(.help_command);
366 return io.getStdOut().writeAll(usage);366 return fs.File.stdout().writeAll(usage);
367 } else if (mem.eql(u8, cmd, "ast-check")) {367 } else if (mem.eql(u8, cmd, "ast-check")) {
368 return cmdAstCheck(arena, cmd_args);368 return cmdAstCheck(arena, cmd_args);
369 } else if (mem.eql(u8, cmd, "detect-cpu")) {369 } else if (mem.eql(u8, cmd, "detect-cpu")) {
...@@ -1040,7 +1040,7 @@ fn buildOutputType(...@@ -1040,7 +1040,7 @@ fn buildOutputType(
1040 };1040 };
1041 } else if (mem.startsWith(u8, arg, "-")) {1041 } else if (mem.startsWith(u8, arg, "-")) {
1042 if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {1042 if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {
1043 try io.getStdOut().writeAll(usage_build_generic);1043 try fs.File.stdout().writeAll(usage_build_generic);
1044 return cleanExit();1044 return cleanExit();
1045 } else if (mem.eql(u8, arg, "--")) {1045 } else if (mem.eql(u8, arg, "--")) {
1046 if (arg_mode == .run) {1046 if (arg_mode == .run) {
...@@ -2768,9 +2768,9 @@ fn buildOutputType(...@@ -2768,9 +2768,9 @@ fn buildOutputType(
2768 } else if (mem.eql(u8, arg, "-V")) {2768 } else if (mem.eql(u8, arg, "-V")) {
2769 warn("ignoring request for supported emulations: unimplemented", .{});2769 warn("ignoring request for supported emulations: unimplemented", .{});
2770 } else if (mem.eql(u8, arg, "-v")) {2770 } else if (mem.eql(u8, arg, "-v")) {
2771 try std.io.getStdOut().writeAll("zig ld " ++ build_options.version ++ "\n");2771 try fs.File.stdout().writeAll("zig ld " ++ build_options.version ++ "\n");
2772 } else if (mem.eql(u8, arg, "--version")) {2772 } else if (mem.eql(u8, arg, "--version")) {
2773 try std.io.getStdOut().writeAll("zig ld " ++ build_options.version ++ "\n");2773 try fs.File.stdout().writeAll("zig ld " ++ build_options.version ++ "\n");
2774 process.exit(0);2774 process.exit(0);
2775 } else {2775 } else {
2776 fatal("unsupported linker arg: {s}", .{arg});2776 fatal("unsupported linker arg: {s}", .{arg});
...@@ -3330,7 +3330,7 @@ fn buildOutputType(...@@ -3330,7 +3330,7 @@ fn buildOutputType(
3330 var hasher = Cache.Hasher.init("0123456789abcdef");3330 var hasher = Cache.Hasher.init("0123456789abcdef");
3331 var w = io.multiWriter(.{ f.writer(), hasher.writer() });3331 var w = io.multiWriter(.{ f.writer(), hasher.writer() });
3332 var fifo = std.fifo.LinearFifo(u8, .{ .Static = 4096 }).init();3332 var fifo = std.fifo.LinearFifo(u8, .{ .Static = 4096 }).init();
3333 try fifo.pump(io.getStdIn().reader(), w.writer());3333 try fifo.pump(fs.File.stdin().reader().unbuffered(), w.writer().unbuffered());
33343334
3335 var bin_digest: Cache.BinDigest = undefined;3335 var bin_digest: Cache.BinDigest = undefined;
3336 hasher.final(&bin_digest);3336 hasher.final(&bin_digest);
...@@ -3548,15 +3548,15 @@ fn buildOutputType(...@@ -3548,15 +3548,15 @@ fn buildOutputType(
3548 if (show_builtin) {3548 if (show_builtin) {
3549 const builtin_opts = comp.root_mod.getBuiltinOptions(comp.config);3549 const builtin_opts = comp.root_mod.getBuiltinOptions(comp.config);
3550 const source = try builtin_opts.generate(arena);3550 const source = try builtin_opts.generate(arena);
3551 return std.io.getStdOut().writeAll(source);3551 return fs.File.stdout().writeAll(source);
3552 }3552 }
3553 switch (listen) {3553 switch (listen) {
3554 .none => {},3554 .none => {},
3555 .stdio => {3555 .stdio => {
3556 try serve(3556 try serve(
3557 comp,3557 comp,
3558 std.io.getStdIn(),3558 fs.File.stdin(),
3559 std.io.getStdOut(),3559 fs.File.stdout(),
3560 test_exec_args.items,3560 test_exec_args.items,
3561 self_exe_path,3561 self_exe_path,
3562 arg_mode,3562 arg_mode,
...@@ -4618,7 +4618,7 @@ fn cmdTranslateC(...@@ -4618,7 +4618,7 @@ fn cmdTranslateC(
4618 fatal("unable to open cached translated zig file '{s}{s}{s}': {s}", .{ path, fs.path.sep_str, out_zig_path, @errorName(err) });4618 fatal("unable to open cached translated zig file '{s}{s}{s}': {s}", .{ path, fs.path.sep_str, out_zig_path, @errorName(err) });
4619 };4619 };
4620 defer zig_file.close();4620 defer zig_file.close();
4621 try io.getStdOut().writeFileAll(zig_file, .{});4621 try fs.File.stdout().writeFileAll(zig_file, .{});
4622 return cleanExit();4622 return cleanExit();
4623 }4623 }
4624}4624}
...@@ -4648,7 +4648,7 @@ fn cmdInit(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {...@@ -4648,7 +4648,7 @@ fn cmdInit(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
4648 if (mem.eql(u8, arg, "-s") or mem.eql(u8, arg, "--strip")) {4648 if (mem.eql(u8, arg, "-s") or mem.eql(u8, arg, "--strip")) {
4649 strip = true;4649 strip = true;
4650 } else if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {4650 } else if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {
4651 try io.getStdOut().writeAll(usage_init);4651 try fs.File.stdout().writeAll(usage_init);
4652 return cleanExit();4652 return cleanExit();
4653 } else {4653 } else {
4654 fatal("unrecognized parameter: '{s}'", .{arg});4654 fatal("unrecognized parameter: '{s}'", .{arg});
...@@ -5478,7 +5478,7 @@ fn jitCmd(...@@ -5478,7 +5478,7 @@ fn jitCmd(
54785478
5479 if (options.server) {5479 if (options.server) {
5480 var server = std.zig.Server{5480 var server = std.zig.Server{
5481 .out = std.io.getStdOut(),5481 .out = fs.File.stdout(),
5482 .in = undefined, // won't be receiving messages5482 .in = undefined, // won't be receiving messages
5483 .receive_fifo = undefined, // won't be receiving messages5483 .receive_fifo = undefined, // won't be receiving messages
5484 };5484 };
...@@ -6011,7 +6011,7 @@ fn cmdAstCheck(...@@ -6011,7 +6011,7 @@ fn cmdAstCheck(
6011 const arg = args[i];6011 const arg = args[i];
6012 if (mem.startsWith(u8, arg, "-")) {6012 if (mem.startsWith(u8, arg, "-")) {
6013 if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {6013 if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {
6014 try io.getStdOut().writeAll(usage_ast_check);6014 try fs.File.stdout().writeAll(usage_ast_check);
6015 return cleanExit();6015 return cleanExit();
6016 } else if (mem.eql(u8, arg, "-t")) {6016 } else if (mem.eql(u8, arg, "-t")) {
6017 want_output_text = true;6017 want_output_text = true;
...@@ -6062,7 +6062,7 @@ fn cmdAstCheck(...@@ -6062,7 +6062,7 @@ fn cmdAstCheck(
6062 const tree = try Ast.parse(arena, source, mode);6062 const tree = try Ast.parse(arena, source, mode);
60636063
6064 var bw: std.io.BufferedWriter = .{6064 var bw: std.io.BufferedWriter = .{
6065 .unbuffered_writer = io.getStdOut().writer(),6065 .unbuffered_writer = fs.File.stdout().writer(),
6066 .buffer = &stdout_buffer,6066 .buffer = &stdout_buffer,
6067 };6067 };
60686068
...@@ -6187,7 +6187,7 @@ fn cmdDetectCpu(args: []const []const u8) !void {...@@ -6187,7 +6187,7 @@ fn cmdDetectCpu(args: []const []const u8) !void {
6187 const arg = args[i];6187 const arg = args[i];
6188 if (mem.startsWith(u8, arg, "-")) {6188 if (mem.startsWith(u8, arg, "-")) {
6189 if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {6189 if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {
6190 const stdout = io.getStdOut().writer();6190 const stdout = fs.File.stdout().writer();
6191 try stdout.writeAll(detect_cpu_usage);6191 try stdout.writeAll(detect_cpu_usage);
6192 return cleanExit();6192 return cleanExit();
6193 } else if (mem.eql(u8, arg, "--llvm")) {6193 } else if (mem.eql(u8, arg, "--llvm")) {
...@@ -6281,7 +6281,7 @@ fn detectNativeCpuWithLLVM(...@@ -6281,7 +6281,7 @@ fn detectNativeCpuWithLLVM(
62816281
6282fn printCpu(cpu: std.Target.Cpu) !void {6282fn printCpu(cpu: std.Target.Cpu) !void {
6283 var bw: std.io.BufferedWriter = .{6283 var bw: std.io.BufferedWriter = .{
6284 .unbuffered_writer = io.getStdOut().writer(),6284 .unbuffered_writer = fs.File.stdout().writer(),
6285 .buffer = &stdout_buffer,6285 .buffer = &stdout_buffer,
6286 };6286 };
62876287
...@@ -6331,7 +6331,7 @@ fn cmdDumpLlvmInts(...@@ -6331,7 +6331,7 @@ fn cmdDumpLlvmInts(
6331 const dl = tm.createTargetDataLayout();6331 const dl = tm.createTargetDataLayout();
6332 const context = llvm.Context.create();6332 const context = llvm.Context.create();
63336333
6334 var bw = io.bufferedWriter(io.getStdOut().writer());6334 var bw = io.bufferedWriter(fs.File.stdout().writer());
6335 const stdout = bw.writer();6335 const stdout = bw.writer();
63366336
6337 for ([_]u16{ 1, 8, 16, 32, 64, 128, 256 }) |bits| {6337 for ([_]u16{ 1, 8, 16, 32, 64, 128, 256 }) |bits| {
...@@ -6364,7 +6364,7 @@ fn cmdDumpZir(...@@ -6364,7 +6364,7 @@ fn cmdDumpZir(
6364 const zir = try Zcu.loadZirCache(arena, f);6364 const zir = try Zcu.loadZirCache(arena, f);
63656365
6366 var bw: std.io.BufferedWriter = .{6366 var bw: std.io.BufferedWriter = .{
6367 .unbuffered_writer = io.getStdOut().writer(),6367 .unbuffered_writer = fs.File.stdout().writer(),
6368 .buffer = &stdout_buffer,6368 .buffer = &stdout_buffer,
6369 };6369 };
63706370
...@@ -6452,7 +6452,7 @@ fn cmdChangelist(...@@ -6452,7 +6452,7 @@ fn cmdChangelist(
6452 try Zcu.mapOldZirToNew(arena, old_zir, new_zir, &inst_map);6452 try Zcu.mapOldZirToNew(arena, old_zir, new_zir, &inst_map);
64536453
6454 var bw: std.io.BufferedWriter = .{6454 var bw: std.io.BufferedWriter = .{
6455 .unbuffered_writer = io.getStdOut().writer(),6455 .unbuffered_writer = fs.File.stdout().writer(),
6456 .buffer = &stdout_buffer,6456 .buffer = &stdout_buffer,
6457 };6457 };
6458 {6458 {
...@@ -6800,7 +6800,7 @@ fn cmdFetch(...@@ -6800,7 +6800,7 @@ fn cmdFetch(
6800 const arg = args[i];6800 const arg = args[i];
6801 if (mem.startsWith(u8, arg, "-")) {6801 if (mem.startsWith(u8, arg, "-")) {
6802 if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {6802 if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {
6803 const stdout = io.getStdOut().writer();6803 const stdout = fs.File.stdout().writer();
6804 try stdout.writeAll(usage_fetch);6804 try stdout.writeAll(usage_fetch);
6805 return cleanExit();6805 return cleanExit();
6806 } else if (mem.eql(u8, arg, "--global-cache-dir")) {6806 } else if (mem.eql(u8, arg, "--global-cache-dir")) {
...@@ -6914,7 +6914,7 @@ fn cmdFetch(...@@ -6914,7 +6914,7 @@ fn cmdFetch(
69146914
6915 const name = switch (save) {6915 const name = switch (save) {
6916 .no => {6916 .no => {
6917 try io.getStdOut().writer().print("{s}\n", .{package_hash_slice});6917 try fs.File.stdout().writer().print("{s}\n", .{package_hash_slice});
6918 return cleanExit();6918 return cleanExit();
6919 },6919 },
6920 .yes, .exact => |name| name: {6920 .yes, .exact => |name| name: {
src/print_env.zig+1-4
...@@ -22,10 +22,7 @@ pub fn cmdEnv(arena: Allocator, args: []const []const u8) !void {...@@ -22,10 +22,7 @@ pub fn cmdEnv(arena: Allocator, args: []const []const u8) !void {
22 const triple = try host.zigTriple(arena);22 const triple = try host.zigTriple(arena);
2323
24 var buffer: [1024]u8 = undefined;24 var buffer: [1024]u8 = undefined;
25 var bw: std.io.BufferedWriter = .{25 var bw: std.io.BufferedWriter = std.fs.File.stdout().writer().buffered(&buffer);
26 .buffer = &buffer,
27 .unbuffered_writer = std.io.getStdOut().writer(),
28 };
29 var jws: std.json.Stringify = .{ .writer = &bw, .options = .{ .whitespace = .indent_1 } };26 var jws: std.json.Stringify = .{ .writer = &bw, .options = .{ .whitespace = .indent_1 } };
3027
31 try jws.beginObject();28 try jws.beginObject();
src/print_targets.zig+1-4
...@@ -15,10 +15,7 @@ pub fn cmdTargets(arena: Allocator, args: []const []const u8) anyerror!void {...@@ -15,10 +15,7 @@ pub fn cmdTargets(arena: Allocator, args: []const []const u8) anyerror!void {
15 _ = args;15 _ = args;
16 const host = std.zig.resolveTargetQueryOrFatal(.{});16 const host = std.zig.resolveTargetQueryOrFatal(.{});
17 var buffer: [1024]u8 = undefined;17 var buffer: [1024]u8 = undefined;
18 var bw: std.io.BufferedWriter = .{18 var bw = fs.File.stdout().writer().buffered(&buffer);
19 .unbuffered_writer = io.getStdOut().writer(),
20 .buffer = &buffer,
21 };
22 try print(arena, &bw, host);19 try print(arena, &bw, host);
23 try bw.flush();20 try bw.flush();
24}21}