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

preparing to rearrange std.io namespace into an interface

how to upgrade:

std.io.getStdIn() -> std.fs.File.stdin()
std.io.getStdOut() -> std.fs.File.stdout()
std.io.getStdErr() -> std.fs.File.stderr()
This commit is contained in:
Andrew Kelley 2025-06-28 06:59:11 -07:00
parent 7c42517151
commit 0b3f0124dc
46 changed files with 175 additions and 222 deletions

View File

@ -541,7 +541,7 @@ const MsgWriter = struct {
fn init(config: std.io.tty.Config) MsgWriter { fn init(config: std.io.tty.Config) MsgWriter {
std.debug.lockStdErr(); std.debug.lockStdErr();
return .{ return .{
.w = std.io.bufferedWriter(std.io.getStdErr().writer()), .w = std.io.bufferedWriter(std.fs.File.stderr().writer()),
.config = config, .config = config,
}; };
} }

View File

@ -519,7 +519,7 @@ fn option(arg: []const u8, name: []const u8) ?[]const u8 {
fn addSource(d: *Driver, path: []const u8) !Source { fn addSource(d: *Driver, path: []const u8) !Source {
if (mem.eql(u8, "-", path)) { if (mem.eql(u8, "-", path)) {
const stdin = std.io.getStdIn().reader(); const stdin = std.fs.File.stdin().reader();
const input = try stdin.readAllAlloc(d.comp.gpa, std.math.maxInt(u32)); const input = try stdin.readAllAlloc(d.comp.gpa, std.math.maxInt(u32));
defer d.comp.gpa.free(input); defer d.comp.gpa.free(input);
return d.comp.addSourceFromBuffer("<stdin>", input); return d.comp.addSourceFromBuffer("<stdin>", input);
@ -541,7 +541,7 @@ pub fn fatal(d: *Driver, comptime fmt: []const u8, args: anytype) error{ FatalEr
} }
pub fn renderErrors(d: *Driver) void { pub fn renderErrors(d: *Driver) void {
Diagnostics.render(d.comp, d.detectConfig(std.io.getStdErr())); Diagnostics.render(d.comp, d.detectConfig(std.fs.File.stderr()));
} }
pub fn detectConfig(d: *Driver, file: std.fs.File) std.io.tty.Config { pub fn detectConfig(d: *Driver, file: std.fs.File) std.io.tty.Config {
@ -591,7 +591,7 @@ pub fn main(d: *Driver, tc: *Toolchain, args: []const []const u8, comptime fast_
var macro_buf = std.ArrayList(u8).init(d.comp.gpa); var macro_buf = std.ArrayList(u8).init(d.comp.gpa);
defer macro_buf.deinit(); defer macro_buf.deinit();
const std_out = std.io.getStdOut().writer(); const std_out = std.fs.File.stdout().writer();
if (try parseArgs(d, std_out, macro_buf.writer(), args)) return; if (try parseArgs(d, std_out, macro_buf.writer(), args)) return;
const linking = !(d.only_preprocess or d.only_syntax or d.only_compile or d.only_preprocess_and_compile); const linking = !(d.only_preprocess or d.only_syntax or d.only_compile or d.only_preprocess_and_compile);
@ -686,7 +686,7 @@ fn processSource(
std.fs.cwd().createFile(some, .{}) catch |er| std.fs.cwd().createFile(some, .{}) catch |er|
return d.fatal("unable to create output file '{s}': {s}", .{ some, errorDescription(er) }) return d.fatal("unable to create output file '{s}': {s}", .{ some, errorDescription(er) })
else else
std.io.getStdOut(); std.fs.File.stdout();
defer if (d.output_name != null) file.close(); defer if (d.output_name != null) file.close();
var buf_w = std.io.bufferedWriter(file.writer()); var buf_w = std.io.bufferedWriter(file.writer());
@ -704,7 +704,7 @@ fn processSource(
defer tree.deinit(); defer tree.deinit();
if (d.verbose_ast) { if (d.verbose_ast) {
const stdout = std.io.getStdOut(); const stdout = std.fs.File.stdout();
var buf_writer = std.io.bufferedWriter(stdout.writer()); var buf_writer = std.io.bufferedWriter(stdout.writer());
tree.dump(d.detectConfig(stdout), buf_writer.writer()) catch {}; tree.dump(d.detectConfig(stdout), buf_writer.writer()) catch {};
buf_writer.flush() catch {}; buf_writer.flush() catch {};
@ -734,7 +734,7 @@ fn processSource(
defer ir.deinit(d.comp.gpa); defer ir.deinit(d.comp.gpa);
if (d.verbose_ir) { if (d.verbose_ir) {
const stdout = std.io.getStdOut(); const stdout = std.fs.File.stdout();
var buf_writer = std.io.bufferedWriter(stdout.writer()); var buf_writer = std.io.bufferedWriter(stdout.writer());
ir.dump(d.comp.gpa, d.detectConfig(stdout), buf_writer.writer()) catch {}; ir.dump(d.comp.gpa, d.detectConfig(stdout), buf_writer.writer()) catch {};
buf_writer.flush() catch {}; buf_writer.flush() catch {};
@ -806,7 +806,7 @@ fn processSource(
} }
fn dumpLinkerArgs(items: []const []const u8) !void { fn dumpLinkerArgs(items: []const []const u8) !void {
const stdout = std.io.getStdOut().writer(); const stdout = std.fs.File.stdout().writer();
for (items, 0..) |item, i| { for (items, 0..) |item, i| {
if (i > 0) try stdout.writeByte(' '); if (i > 0) try stdout.writeByte(' ');
try stdout.print("\"{}\"", .{std.zig.fmtEscapes(item)}); try stdout.print("\"{}\"", .{std.zig.fmtEscapes(item)});

View File

@ -811,7 +811,7 @@ fn verboseLog(pp: *Preprocessor, raw: RawToken, comptime fmt: []const u8, args:
const source = pp.comp.getSource(raw.source); const source = pp.comp.getSource(raw.source);
const line_col = source.lineCol(.{ .id = raw.source, .line = raw.line, .byte_offset = raw.start }); const line_col = source.lineCol(.{ .id = raw.source, .line = raw.line, .byte_offset = raw.start });
const stderr = std.io.getStdErr().writer(); const stderr = std.fs.File.stderr().writer();
var buf_writer = std.io.bufferedWriter(stderr); var buf_writer = std.io.bufferedWriter(stderr);
const writer = buf_writer.writer(); const writer = buf_writer.writer();
defer buf_writer.flush() catch {}; defer buf_writer.flush() catch {};

View File

@ -1781,7 +1781,7 @@ test "Macro matching" {
fn renderErrorsAndExit(comp: *aro.Compilation) noreturn { fn renderErrorsAndExit(comp: *aro.Compilation) noreturn {
defer std.process.exit(1); defer std.process.exit(1);
var writer = aro.Diagnostics.defaultMsgWriter(std.io.tty.detectConfig(std.io.getStdErr())); var writer = aro.Diagnostics.defaultMsgWriter(std.io.tty.detectConfig(std.fs.File.stderr()));
defer writer.deinit(); // writer deinit must run *before* exit so that stderr is flushed defer writer.deinit(); // writer deinit must run *before* exit so that stderr is flushed
var saw_error = false; var saw_error = false;
@ -1824,6 +1824,6 @@ pub fn main() !void {
defer tree.deinit(gpa); defer tree.deinit(gpa);
const formatted = try tree.render(arena); const formatted = try tree.render(arena);
try std.io.getStdOut().writeAll(formatted); try std.fs.File.stdout().writeAll(formatted);
return std.process.cleanExit(); return std.process.cleanExit();
} }

View File

@ -330,7 +330,7 @@ pub fn main() !void {
} }
} }
const stderr = std.io.getStdErr(); const stderr = std.fs.File.stderr();
const ttyconf = get_tty_conf(color, stderr); const ttyconf = get_tty_conf(color, stderr);
switch (ttyconf) { switch (ttyconf) {
.no_color => try graph.env_map.put("NO_COLOR", "1"), .no_color => try graph.env_map.put("NO_COLOR", "1"),
@ -378,7 +378,7 @@ pub fn main() !void {
validateSystemLibraryOptions(builder); validateSystemLibraryOptions(builder);
const stdout_writer = io.getStdOut().writer(); const stdout_writer = std.fs.File.stdout().writer();
if (help_menu) if (help_menu)
return usage(builder, stdout_writer); return usage(builder, stdout_writer);

View File

@ -40,7 +40,7 @@ pub fn main() !void {
const arg = args[i]; const arg = args[i];
if (mem.startsWith(u8, arg, "-")) { if (mem.startsWith(u8, arg, "-")) {
if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) { if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {
const stdout = std.io.getStdOut().writer(); const stdout = std.fs.File.stdout().writer();
try stdout.writeAll(usage_libc); try stdout.writeAll(usage_libc);
return std.process.cleanExit(); return std.process.cleanExit();
} else if (mem.eql(u8, arg, "-target")) { } else if (mem.eql(u8, arg, "-target")) {
@ -97,7 +97,7 @@ pub fn main() !void {
fatal("no include dirs detected for target {s}", .{zig_target}); fatal("no include dirs detected for target {s}", .{zig_target});
} }
var bw = std.io.bufferedWriter(std.io.getStdOut().writer()); var bw = std.io.bufferedWriter(std.fs.File.stdout().writer());
var writer = bw.writer(); var writer = bw.writer();
for (libc_dirs.libc_include_dir_list) |include_dir| { for (libc_dirs.libc_include_dir_list) |include_dir| {
try writer.writeAll(include_dir); try writer.writeAll(include_dir);
@ -125,7 +125,7 @@ pub fn main() !void {
}; };
defer libc.deinit(gpa); defer libc.deinit(gpa);
var bw = std.io.bufferedWriter(std.io.getStdOut().writer()); var bw = std.io.bufferedWriter(std.fs.File.stdout().writer());
try libc.render(bw.writer()); try libc.render(bw.writer());
try bw.flush(); try bw.flush();
} }

View File

@ -54,7 +54,7 @@ fn cmdObjCopy(
fatal("unexpected positional argument: '{s}'", .{arg}); fatal("unexpected positional argument: '{s}'", .{arg});
} }
} else if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) { } else if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {
return std.io.getStdOut().writeAll(usage); return std.fs.File.stdout().writeAll(usage);
} else if (mem.eql(u8, arg, "-O") or mem.eql(u8, arg, "--output-target")) { } else if (mem.eql(u8, arg, "-O") or mem.eql(u8, arg, "--output-target")) {
i += 1; i += 1;
if (i >= args.len) fatal("expected another argument after '{s}'", .{arg}); if (i >= args.len) fatal("expected another argument after '{s}'", .{arg});
@ -227,8 +227,8 @@ fn cmdObjCopy(
if (listen) { if (listen) {
var server = try Server.init(.{ var server = try Server.init(.{
.gpa = gpa, .gpa = gpa,
.in = std.io.getStdIn(), .in = .stdin(),
.out = std.io.getStdOut(), .out = .stdout(),
.zig_version = builtin.zig_version_string, .zig_version = builtin.zig_version_string,
}); });
defer server.deinit(); defer server.deinit();

View File

@ -68,7 +68,7 @@ pub fn main() !void {
const arg = args[i]; const arg = args[i];
if (mem.startsWith(u8, arg, "-")) { if (mem.startsWith(u8, arg, "-")) {
if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) { if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {
const stdout = std.io.getStdOut().writer(); const stdout = std.fs.File.stdout().writer();
try stdout.writeAll(usage); try stdout.writeAll(usage);
return std.process.cleanExit(); return std.process.cleanExit();
} else if (mem.eql(u8, arg, "--")) { } else if (mem.eql(u8, arg, "--")) {

View File

@ -127,7 +127,7 @@ pub const Diagnostics = struct {
pub fn renderToStdErr(self: *Diagnostics, args: []const []const u8, config: std.io.tty.Config) void { pub fn renderToStdErr(self: *Diagnostics, args: []const []const u8, config: std.io.tty.Config) void {
std.debug.lockStdErr(); std.debug.lockStdErr();
defer std.debug.unlockStdErr(); defer std.debug.unlockStdErr();
const stderr = std.io.getStdErr().writer(); const stderr = std.fs.File.stderr().writer();
self.renderToWriter(args, stderr, config) catch return; self.renderToWriter(args, stderr, config) catch return;
} }

View File

@ -63,14 +63,14 @@ pub const Diagnostics = struct {
pub fn renderToStdErr(self: *Diagnostics, cwd: std.fs.Dir, source: []const u8, tty_config: std.io.tty.Config, source_mappings: ?SourceMappings) void { pub fn renderToStdErr(self: *Diagnostics, cwd: std.fs.Dir, source: []const u8, tty_config: std.io.tty.Config, source_mappings: ?SourceMappings) void {
std.debug.lockStdErr(); std.debug.lockStdErr();
defer std.debug.unlockStdErr(); defer std.debug.unlockStdErr();
const stderr = std.io.getStdErr().writer(); const stderr = std.fs.File.stderr().writer();
for (self.errors.items) |err_details| { for (self.errors.items) |err_details| {
renderErrorMessage(stderr, tty_config, cwd, err_details, source, self.strings.items, source_mappings) catch return; renderErrorMessage(stderr, tty_config, cwd, err_details, source, self.strings.items, source_mappings) catch return;
} }
} }
pub fn renderToStdErrDetectTTY(self: *Diagnostics, cwd: std.fs.Dir, source: []const u8, source_mappings: ?SourceMappings) void { pub fn renderToStdErrDetectTTY(self: *Diagnostics, cwd: std.fs.Dir, source: []const u8, source_mappings: ?SourceMappings) void {
const tty_config = std.io.tty.detectConfig(std.io.getStdErr()); const tty_config = std.io.tty.detectConfig(std.fs.File.stderr());
return self.renderToStdErr(cwd, source, tty_config, source_mappings); return self.renderToStdErr(cwd, source, tty_config, source_mappings);
} }

View File

@ -22,7 +22,7 @@ pub fn main() !void {
defer arena_state.deinit(); defer arena_state.deinit();
const arena = arena_state.allocator(); const arena = arena_state.allocator();
const stderr = std.io.getStdErr(); const stderr = std.fs.File.stderr();
const stderr_config = std.io.tty.detectConfig(stderr); const stderr_config = std.io.tty.detectConfig(stderr);
const args = try std.process.argsAlloc(allocator); const args = try std.process.argsAlloc(allocator);
@ -44,7 +44,7 @@ pub fn main() !void {
var error_handler: ErrorHandler = switch (zig_integration) { var error_handler: ErrorHandler = switch (zig_integration) {
true => .{ true => .{
.server = .{ .server = .{
.out = std.io.getStdOut(), .out = std.fs.File.stdout(),
.in = undefined, // won't be receiving messages .in = undefined, // won't be receiving messages
.receive_fifo = undefined, // won't be receiving messages .receive_fifo = undefined, // won't be receiving messages
}, },
@ -81,7 +81,7 @@ pub fn main() !void {
defer options.deinit(); defer options.deinit();
if (options.print_help_and_exit) { if (options.print_help_and_exit) {
const stdout = std.io.getStdOut(); const stdout = std.fs.File.stdout();
try cli.writeUsage(stdout.writer(), "zig rc"); try cli.writeUsage(stdout.writer(), "zig rc");
return; return;
} }
@ -89,7 +89,7 @@ pub fn main() !void {
// Don't allow verbose when integrating with Zig via stdout // Don't allow verbose when integrating with Zig via stdout
options.verbose = false; options.verbose = false;
const stdout_writer = std.io.getStdOut().writer(); const stdout_writer = std.fs.File.stdout().writer();
if (options.verbose) { if (options.verbose) {
try options.dumpVerbose(stdout_writer); try options.dumpVerbose(stdout_writer);
try stdout_writer.writeByte('\n'); try stdout_writer.writeByte('\n');
@ -645,7 +645,7 @@ const ErrorHandler = union(enum) {
}, },
.tty => { .tty => {
// extra newline to separate this line from the aro errors // extra newline to separate this line from the aro errors
try renderErrorMessage(std.io.getStdErr().writer(), self.tty, .err, "{s}\n", .{fail_msg}); try renderErrorMessage(std.fs.File.stderr().writer(), self.tty, .err, "{s}\n", .{fail_msg});
aro.Diagnostics.render(comp, self.tty); aro.Diagnostics.render(comp, self.tty);
}, },
} }
@ -690,7 +690,7 @@ const ErrorHandler = union(enum) {
try server.serveErrorBundle(error_bundle); try server.serveErrorBundle(error_bundle);
}, },
.tty => { .tty => {
try renderErrorMessage(std.io.getStdErr().writer(), self.tty, msg_type, format, args); try renderErrorMessage(std.fs.File.stderr().writer(), self.tty, msg_type, format, args);
}, },
} }
} }

View File

@ -7,7 +7,7 @@ const assert = std.debug.assert;
const Cache = std.Build.Cache; const Cache = std.Build.Cache;
fn usage() noreturn { fn usage() noreturn {
io.getStdOut().writeAll( std.fs.File.stdout().writeAll(
\\Usage: zig std [options] \\Usage: zig std [options]
\\ \\
\\Options: \\Options:
@ -63,7 +63,7 @@ pub fn main() !void {
var http_server = try address.listen(.{}); var http_server = try address.listen(.{});
const port = http_server.listen_address.in.getPort(); const port = http_server.listen_address.in.getPort();
const url_with_newline = try std.fmt.allocPrint(arena, "http://127.0.0.1:{d}/\n", .{port}); const url_with_newline = try std.fmt.allocPrint(arena, "http://127.0.0.1:{d}/\n", .{port});
std.io.getStdOut().writeAll(url_with_newline) catch {}; std.fs.File.stdout().writeAll(url_with_newline) catch {};
if (should_open_browser) { if (should_open_browser) {
openBrowserTab(gpa, url_with_newline[0 .. url_with_newline.len - 1 :'\n']) catch |err| { openBrowserTab(gpa, url_with_newline[0 .. url_with_newline.len - 1 :'\n']) catch |err| {
std.log.err("unable to open browser: {s}", .{@errorName(err)}); std.log.err("unable to open browser: {s}", .{@errorName(err)});

View File

@ -69,8 +69,8 @@ fn mainServer() !void {
@disableInstrumentation(); @disableInstrumentation();
var server = try std.zig.Server.init(.{ var server = try std.zig.Server.init(.{
.gpa = fba.allocator(), .gpa = fba.allocator(),
.in = std.io.getStdIn(), .in = .stdin(),
.out = std.io.getStdOut(), .out = .stdout(),
.zig_version = builtin.zig_version_string, .zig_version = builtin.zig_version_string,
}); });
defer server.deinit(); defer server.deinit();
@ -191,7 +191,7 @@ fn mainTerminal() void {
.root_name = "Test", .root_name = "Test",
.estimated_total_items = test_fn_list.len, .estimated_total_items = test_fn_list.len,
}); });
const have_tty = std.io.getStdErr().isTty(); const have_tty = std.fs.File.stderr().isTty();
var async_frame_buffer: []align(builtin.target.stackAlignment()) u8 = undefined; var async_frame_buffer: []align(builtin.target.stackAlignment()) u8 = undefined;
// TODO this is on the next line (using `undefined` above) because otherwise zig incorrectly // TODO this is on the next line (using `undefined` above) because otherwise zig incorrectly
@ -301,7 +301,7 @@ pub fn mainSimple() anyerror!void {
var failed: u64 = 0; var failed: u64 = 0;
// we don't want to bring in File and Writer if the backend doesn't support it // we don't want to bring in File and Writer if the backend doesn't support it
const stderr = if (comptime enable_print) std.io.getStdErr() else {}; const stderr = if (comptime enable_print) std.fs.File.stderr() else {};
for (builtin.test_functions) |test_fn| { for (builtin.test_functions) |test_fn| {
if (test_fn.func()) |_| { if (test_fn.func()) |_| {

View File

@ -145,7 +145,7 @@ fn mainImpl() !void {
var parser = try Parser.init(gpa); var parser = try Parser.init(gpa);
defer parser.deinit(); defer parser.deinit();
var stdin_buf = std.io.bufferedReader(std.io.getStdIn().reader()); var stdin_buf = std.io.bufferedReader(std.fs.File.stdin().reader());
var line_buf = std.ArrayList(u8).init(gpa); var line_buf = std.ArrayList(u8).init(gpa);
defer line_buf.deinit(); defer line_buf.deinit();
while (stdin_buf.reader().streamUntilDelimiter(line_buf.writer(), '\n', null)) { while (stdin_buf.reader().streamUntilDelimiter(line_buf.writer(), '\n', null)) {
@ -160,7 +160,7 @@ fn mainImpl() !void {
var doc = try parser.endInput(); var doc = try parser.endInput();
defer doc.deinit(gpa); defer doc.deinit(gpa);
var stdout_buf = std.io.bufferedWriter(std.io.getStdOut().writer()); var stdout_buf = std.io.bufferedWriter(std.fs.File.stdout().writer());
try doc.render(stdout_buf.writer()); try doc.render(stdout_buf.writer());
try stdout_buf.flush(); try stdout_buf.flush();
} }

View File

@ -5,7 +5,7 @@ pub fn bufferedPrint() !void {
// Stdout is for the actual output of your application, for example if you // Stdout is for the actual output of your application, for example if you
// are implementing gzip, then only the compressed bytes should be sent to // are implementing gzip, then only the compressed bytes should be sent to
// stdout, not any debugging messages. // stdout, not any debugging messages.
const stdout_file = std.io.getStdOut().writer(); const stdout_file = std.fs.File.stdout().writer();
// Buffering can improve performance significantly in print-heavy programs. // Buffering can improve performance significantly in print-heavy programs.
var bw = std.io.bufferedWriter(stdout_file); var bw = std.io.bufferedWriter(stdout_file);
const stdout = bw.writer(); const stdout = bw.writer();

View File

@ -2467,7 +2467,7 @@ pub const GeneratedFile = struct {
pub fn getPath2(gen: GeneratedFile, src_builder: *Build, asking_step: ?*Step) []const u8 { pub fn getPath2(gen: GeneratedFile, src_builder: *Build, asking_step: ?*Step) []const u8 {
return gen.path orelse { return gen.path orelse {
std.debug.lockStdErr(); std.debug.lockStdErr();
const stderr = std.io.getStdErr(); const stderr = std.fs.File.stderr();
dumpBadGetPathHelp(gen.step, stderr, src_builder, asking_step) catch {}; dumpBadGetPathHelp(gen.step, stderr, src_builder, asking_step) catch {};
std.debug.unlockStdErr(); std.debug.unlockStdErr();
@panic("misconfigured build script"); @panic("misconfigured build script");
@ -2677,7 +2677,7 @@ pub const LazyPath = union(enum) {
.root_dir = Cache.Directory.cwd(), .root_dir = Cache.Directory.cwd(),
.sub_path = gen.file.path orelse { .sub_path = gen.file.path orelse {
std.debug.lockStdErr(); std.debug.lockStdErr();
const stderr = std.io.getStdErr(); const stderr: fs.File = .stderr();
dumpBadGetPathHelp(gen.file.step, stderr, src_builder, asking_step) catch {}; dumpBadGetPathHelp(gen.file.step, stderr, src_builder, asking_step) catch {};
std.debug.unlockStdErr(); std.debug.unlockStdErr();
@panic("misconfigured build script"); @panic("misconfigured build script");
@ -2769,7 +2769,7 @@ fn dumpBadDirnameHelp(
debug.lockStdErr(); debug.lockStdErr();
defer debug.unlockStdErr(); defer debug.unlockStdErr();
const stderr = io.getStdErr(); const stderr: fs.File = .stderr();
const w = stderr.writer(); const w = stderr.writer();
try w.print(msg, args); try w.print(msg, args);

View File

@ -1072,7 +1072,7 @@ fn depTokenizer(input: []const u8, expect: []const u8) !void {
return; return;
} }
const out = std.io.getStdErr().writer(); const out = std.fs.File.stderr().writer();
try out.writeAll("\n"); try out.writeAll("\n");
try printSection(out, "<<<< input", input); try printSection(out, "<<<< input", input);

View File

@ -112,7 +112,7 @@ fn rebuildTestsWorkerRun(run: *Step.Run, ttyconf: std.io.tty.Config, parent_prog
fn rebuildTestsWorkerRunFallible(run: *Step.Run, ttyconf: std.io.tty.Config, parent_prog_node: std.Progress.Node) !void { fn rebuildTestsWorkerRunFallible(run: *Step.Run, ttyconf: std.io.tty.Config, parent_prog_node: std.Progress.Node) !void {
const gpa = run.step.owner.allocator; const gpa = run.step.owner.allocator;
const stderr = std.io.getStdErr(); const stderr = std.fs.File.stderr();
const compile = run.producer.?; const compile = run.producer.?;
const prog_node = parent_prog_node.start(compile.step.name, 0); const prog_node = parent_prog_node.start(compile.step.name, 0);
@ -152,7 +152,7 @@ fn fuzzWorkerRun(
run.rerunInFuzzMode(web_server, unit_test_index, prog_node) catch |err| switch (err) { run.rerunInFuzzMode(web_server, unit_test_index, prog_node) catch |err| switch (err) {
error.MakeFailed => { error.MakeFailed => {
const stderr = std.io.getStdErr(); const stderr = std.fs.File.stderr();
std.debug.lockStdErr(); std.debug.lockStdErr();
defer std.debug.unlockStdErr(); defer std.debug.unlockStdErr();
build_runner.printErrorMessages(gpa, &run.step, .{ .ttyconf = ttyconf }, stderr, false) catch {}; build_runner.printErrorMessages(gpa, &run.step, .{ .ttyconf = ttyconf }, stderr, false) catch {};

View File

@ -1018,7 +1018,7 @@ fn getGeneratedFilePath(compile: *Compile, comptime tag_name: []const u8, asking
const generated_file = maybe_path orelse { const generated_file = maybe_path orelse {
std.debug.lockStdErr(); std.debug.lockStdErr();
const stderr = std.io.getStdErr(); const stderr: fs.File = .stderr();
std.Build.dumpBadGetPathHelp(&compile.step, stderr, compile.step.owner, asking_step) catch {}; std.Build.dumpBadGetPathHelp(&compile.step, stderr, compile.step.owner, asking_step) catch {};
@ -1027,7 +1027,7 @@ fn getGeneratedFilePath(compile: *Compile, comptime tag_name: []const u8, asking
const path = generated_file.path orelse { const path = generated_file.path orelse {
std.debug.lockStdErr(); std.debug.lockStdErr();
const stderr = std.io.getStdErr(); const stderr: fs.File = .stderr();
std.Build.dumpBadGetPathHelp(&compile.step, stderr, compile.step.owner, asking_step) catch {}; std.Build.dumpBadGetPathHelp(&compile.step, stderr, compile.step.owner, asking_step) catch {};

View File

@ -451,7 +451,7 @@ pub fn start(options: Options) Node {
if (options.disable_printing) { if (options.disable_printing) {
return Node.none; return Node.none;
} }
const stderr = std.io.getStdErr(); const stderr: std.fs.File = .stderr();
global_progress.terminal = stderr; global_progress.terminal = stderr;
if (stderr.getOrEnableAnsiEscapeSupport()) { if (stderr.getOrEnableAnsiEscapeSupport()) {
global_progress.terminal_mode = .ansi_escape_codes; global_progress.terminal_mode = .ansi_escape_codes;

View File

@ -122,7 +122,7 @@ fn mode(comptime x: comptime_int) comptime_int {
} }
pub fn main() !void { pub fn main() !void {
const stdout = std.io.getStdOut().writer(); const stdout = std.fs.File.stdout().writer();
var buffer: [1024]u8 = undefined; var buffer: [1024]u8 = undefined;
var fixed = std.heap.FixedBufferAllocator.init(buffer[0..]); var fixed = std.heap.FixedBufferAllocator.init(buffer[0..]);

View File

@ -51,7 +51,7 @@ pub const StackTrace = struct {
const debug_info = std.debug.getSelfDebugInfo() catch |err| { const debug_info = std.debug.getSelfDebugInfo() catch |err| {
return writer.print("\nUnable to print stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}); return writer.print("\nUnable to print stack trace: Unable to open debug info: {s}\n", .{@errorName(err)});
}; };
const tty_config = std.io.tty.detectConfig(std.io.getStdErr()); const tty_config = std.io.tty.detectConfig(std.fs.File.stderr());
try writer.writeAll("\n"); try writer.writeAll("\n");
std.debug.writeStackTrace(self, writer, debug_info, tty_config) catch |err| { std.debug.writeStackTrace(self, writer, debug_info, tty_config) catch |err| {
try writer.print("Unable to print stack trace: {s}\n", .{@errorName(err)}); try writer.print("Unable to print stack trace: {s}\n", .{@errorName(err)});

View File

@ -458,7 +458,7 @@ fn mode(comptime x: comptime_int) comptime_int {
} }
pub fn main() !void { pub fn main() !void {
const stdout = std.io.getStdOut().writer(); const stdout = std.fs.File.stdout().writer();
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit(); defer arena.deinit();

View File

@ -209,7 +209,7 @@ pub fn unlockStdErr() void {
pub fn print(comptime fmt: []const u8, args: anytype) void { pub fn print(comptime fmt: []const u8, args: anytype) void {
lockStdErr(); lockStdErr();
defer unlockStdErr(); defer unlockStdErr();
const stderr = io.getStdErr().writer(); const stderr = fs.File.stderr().writer();
nosuspend stderr.print(fmt, args) catch return; nosuspend stderr.print(fmt, args) catch return;
} }
@ -239,7 +239,7 @@ pub fn dumpHex(bytes: []const u8) void {
/// Prints a hexadecimal view of the bytes, unbuffered, returning any error that occurs. /// Prints a hexadecimal view of the bytes, unbuffered, returning any error that occurs.
pub fn dumpHexFallible(bytes: []const u8) !void { pub fn dumpHexFallible(bytes: []const u8) !void {
const stderr = std.io.getStdErr(); const stderr: fs.File = .stderr();
const ttyconf = std.io.tty.detectConfig(stderr); const ttyconf = std.io.tty.detectConfig(stderr);
const writer = stderr.writer(); const writer = stderr.writer();
try dumpHexInternal(bytes, ttyconf, writer); try dumpHexInternal(bytes, ttyconf, writer);
@ -318,12 +318,12 @@ pub fn dumpCurrentStackTrace(start_addr: ?usize) void {
nosuspend { nosuspend {
if (builtin.target.cpu.arch.isWasm()) { if (builtin.target.cpu.arch.isWasm()) {
if (native_os == .wasi) { if (native_os == .wasi) {
const stderr = io.getStdErr().writer(); const stderr = fs.File.stderr().writer();
stderr.print("Unable to dump stack trace: not implemented for Wasm\n", .{}) catch return; stderr.print("Unable to dump stack trace: not implemented for Wasm\n", .{}) catch return;
} }
return; return;
} }
const stderr = io.getStdErr().writer(); const stderr = fs.File.stderr().writer();
if (builtin.strip_debug_info) { if (builtin.strip_debug_info) {
stderr.print("Unable to dump stack trace: debug info stripped\n", .{}) catch return; stderr.print("Unable to dump stack trace: debug info stripped\n", .{}) catch return;
return; return;
@ -332,7 +332,7 @@ pub fn dumpCurrentStackTrace(start_addr: ?usize) void {
stderr.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}) catch return; stderr.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}) catch return;
return; return;
}; };
writeCurrentStackTrace(stderr, debug_info, io.tty.detectConfig(io.getStdErr()), start_addr) catch |err| { writeCurrentStackTrace(stderr, debug_info, io.tty.detectConfig(fs.File.stderr()), start_addr) catch |err| {
stderr.print("Unable to dump stack trace: {s}\n", .{@errorName(err)}) catch return; stderr.print("Unable to dump stack trace: {s}\n", .{@errorName(err)}) catch return;
return; return;
}; };
@ -406,12 +406,12 @@ pub fn dumpStackTraceFromBase(context: *ThreadContext) void {
nosuspend { nosuspend {
if (builtin.target.cpu.arch.isWasm()) { if (builtin.target.cpu.arch.isWasm()) {
if (native_os == .wasi) { if (native_os == .wasi) {
const stderr = io.getStdErr().writer(); const stderr = fs.File.stderr().writer();
stderr.print("Unable to dump stack trace: not implemented for Wasm\n", .{}) catch return; stderr.print("Unable to dump stack trace: not implemented for Wasm\n", .{}) catch return;
} }
return; return;
} }
const stderr = io.getStdErr().writer(); const stderr = fs.File.stderr().writer();
if (builtin.strip_debug_info) { if (builtin.strip_debug_info) {
stderr.print("Unable to dump stack trace: debug info stripped\n", .{}) catch return; stderr.print("Unable to dump stack trace: debug info stripped\n", .{}) catch return;
return; return;
@ -420,7 +420,7 @@ pub fn dumpStackTraceFromBase(context: *ThreadContext) void {
stderr.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}) catch return; stderr.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}) catch return;
return; return;
}; };
const tty_config = io.tty.detectConfig(io.getStdErr()); const tty_config = io.tty.detectConfig(fs.File.stderr());
if (native_os == .windows) { if (native_os == .windows) {
// On x86_64 and aarch64, the stack will be unwound using RtlVirtualUnwind using the context // On x86_64 and aarch64, the stack will be unwound using RtlVirtualUnwind using the context
// provided by the exception handler. On x86, RtlVirtualUnwind doesn't exist. Instead, a new backtrace // provided by the exception handler. On x86, RtlVirtualUnwind doesn't exist. Instead, a new backtrace
@ -510,12 +510,12 @@ pub fn dumpStackTrace(stack_trace: std.builtin.StackTrace) void {
nosuspend { nosuspend {
if (builtin.target.cpu.arch.isWasm()) { if (builtin.target.cpu.arch.isWasm()) {
if (native_os == .wasi) { if (native_os == .wasi) {
const stderr = io.getStdErr().writer(); const stderr = fs.File.stderr().writer();
stderr.print("Unable to dump stack trace: not implemented for Wasm\n", .{}) catch return; stderr.print("Unable to dump stack trace: not implemented for Wasm\n", .{}) catch return;
} }
return; return;
} }
const stderr = io.getStdErr().writer(); const stderr = fs.File.stderr().writer();
if (builtin.strip_debug_info) { if (builtin.strip_debug_info) {
stderr.print("Unable to dump stack trace: debug info stripped\n", .{}) catch return; stderr.print("Unable to dump stack trace: debug info stripped\n", .{}) catch return;
return; return;
@ -524,7 +524,7 @@ pub fn dumpStackTrace(stack_trace: std.builtin.StackTrace) void {
stderr.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}) catch return; stderr.print("Unable to dump stack trace: Unable to open debug info: {s}\n", .{@errorName(err)}) catch return;
return; return;
}; };
writeStackTrace(stack_trace, stderr, debug_info, io.tty.detectConfig(io.getStdErr())) catch |err| { writeStackTrace(stack_trace, stderr, debug_info, io.tty.detectConfig(fs.File.stderr())) catch |err| {
stderr.print("Unable to dump stack trace: {s}\n", .{@errorName(err)}) catch return; stderr.print("Unable to dump stack trace: {s}\n", .{@errorName(err)}) catch return;
return; return;
}; };
@ -678,7 +678,7 @@ pub fn defaultPanic(
lockStdErr(); lockStdErr();
defer unlockStdErr(); defer unlockStdErr();
const stderr = io.getStdErr().writer(); const stderr = fs.File.stderr().writer();
if (builtin.single_threaded) { if (builtin.single_threaded) {
stderr.print("panic: ", .{}) catch posix.abort(); stderr.print("panic: ", .{}) catch posix.abort();
} else { } else {
@ -699,7 +699,7 @@ pub fn defaultPanic(
// A panic happened while trying to print a previous panic message. // A panic happened while trying to print a previous panic message.
// We're still holding the mutex but that's fine as we're going to // We're still holding the mutex but that's fine as we're going to
// call abort(). // call abort().
io.getStdErr().writeAll("aborting due to recursive panic\n") catch {}; fs.File.stderr().writeAll("aborting due to recursive panic\n") catch {};
}, },
else => {}, // Panicked while printing the recursive panic message. else => {}, // Panicked while printing the recursive panic message.
}; };
@ -1461,7 +1461,7 @@ fn handleSegfaultPosix(sig: i32, info: *const posix.siginfo_t, ctx_ptr: ?*anyopa
} }
fn dumpSegfaultInfoPosix(sig: i32, code: i32, addr: usize, ctx_ptr: ?*anyopaque) void { fn dumpSegfaultInfoPosix(sig: i32, code: i32, addr: usize, ctx_ptr: ?*anyopaque) void {
const stderr = io.getStdErr().writer(); const stderr = fs.File.stderr().writer();
_ = switch (sig) { _ = switch (sig) {
posix.SIG.SEGV => if (native_arch == .x86_64 and native_os == .linux and code == 128) // SI_KERNEL posix.SIG.SEGV => if (native_arch == .x86_64 and native_os == .linux and code == 128) // SI_KERNEL
// x86_64 doesn't have a full 64-bit virtual address space. // x86_64 doesn't have a full 64-bit virtual address space.
@ -1549,7 +1549,7 @@ fn handleSegfaultWindowsExtra(info: *windows.EXCEPTION_POINTERS, msg: u8, label:
}, },
1 => { 1 => {
panic_stage = 2; panic_stage = 2;
io.getStdErr().writeAll("aborting due to recursive panic\n") catch {}; fs.File.stderr().writeAll("aborting due to recursive panic\n") catch {};
}, },
else => {}, else => {},
}; };
@ -1557,7 +1557,7 @@ fn handleSegfaultWindowsExtra(info: *windows.EXCEPTION_POINTERS, msg: u8, label:
} }
fn dumpSegfaultInfoWindows(info: *windows.EXCEPTION_POINTERS, msg: u8, label: ?[]const u8) void { fn dumpSegfaultInfoWindows(info: *windows.EXCEPTION_POINTERS, msg: u8, label: ?[]const u8) void {
const stderr = io.getStdErr().writer(); const stderr = fs.File.stderr().writer();
_ = switch (msg) { _ = switch (msg) {
0 => stderr.print("{s}\n", .{label.?}), 0 => stderr.print("{s}\n", .{label.?}),
1 => stderr.print("Segmentation fault at address 0x{x}\n", .{info.ExceptionRecord.ExceptionInformation[1]}), 1 => stderr.print("Segmentation fault at address 0x{x}\n", .{info.ExceptionRecord.ExceptionInformation[1]}),
@ -1591,7 +1591,7 @@ test "manage resources correctly" {
const writer = std.io.null_writer; const writer = std.io.null_writer;
var di = try SelfInfo.open(testing.allocator); var di = try SelfInfo.open(testing.allocator);
defer di.deinit(); defer di.deinit();
try printSourceAtAddress(&di, writer, showMyTrace(), io.tty.detectConfig(std.io.getStdErr())); try printSourceAtAddress(&di, writer, showMyTrace(), io.tty.detectConfig(std.fs.File.stderr()));
} }
noinline fn showMyTrace() usize { noinline fn showMyTrace() usize {
@ -1657,8 +1657,8 @@ pub fn ConfigurableTrace(comptime size: usize, comptime stack_frame_count: usize
pub fn dump(t: @This()) void { pub fn dump(t: @This()) void {
if (!enabled) return; if (!enabled) return;
const tty_config = io.tty.detectConfig(std.io.getStdErr()); const tty_config = io.tty.detectConfig(std.fs.File.stderr());
const stderr = io.getStdErr().writer(); const stderr = fs.File.stderr().writer();
const end = @min(t.index, size); const end = @min(t.index, size);
const debug_info = getSelfDebugInfo() catch |err| { const debug_info = getSelfDebugInfo() catch |err| {
stderr.print( stderr.print(

View File

@ -15,7 +15,7 @@ pub fn call(msg: []const u8, ra: ?usize) noreturn {
@branchHint(.cold); @branchHint(.cold);
_ = ra; _ = ra;
std.debug.lockStdErr(); std.debug.lockStdErr();
const stderr = std.io.getStdErr(); const stderr: std.fs.File = .stderr();
stderr.writeAll(msg) catch {}; stderr.writeAll(msg) catch {};
@trap(); @trap();
} }

View File

@ -346,7 +346,7 @@ fn mode(comptime x: comptime_int) comptime_int {
} }
pub fn main() !void { pub fn main() !void {
const stdout = std.io.getStdOut().writer(); const stdout = std.fs.File.stdout().writer();
var buffer: [1024]u8 = undefined; var buffer: [1024]u8 = undefined;
var fixed = std.heap.FixedBufferAllocator.init(buffer[0..]); var fixed = std.heap.FixedBufferAllocator.init(buffer[0..]);

View File

@ -77,54 +77,6 @@ pub const Limit = enum(usize) {
pub const Reader = @import("io/Reader.zig"); pub const Reader = @import("io/Reader.zig");
pub const Writer = @import("io/Writer.zig"); pub const Writer = @import("io/Writer.zig");
fn getStdOutHandle() posix.fd_t {
if (is_windows) {
return windows.peb().ProcessParameters.hStdOutput;
}
if (@hasDecl(root, "os") and @hasDecl(root.os, "io") and @hasDecl(root.os.io, "getStdOutHandle")) {
return root.os.io.getStdOutHandle();
}
return posix.STDOUT_FILENO;
}
pub fn getStdOut() File {
return .{ .handle = getStdOutHandle() };
}
fn getStdErrHandle() posix.fd_t {
if (is_windows) {
return windows.peb().ProcessParameters.hStdError;
}
if (@hasDecl(root, "os") and @hasDecl(root.os, "io") and @hasDecl(root.os.io, "getStdErrHandle")) {
return root.os.io.getStdErrHandle();
}
return posix.STDERR_FILENO;
}
pub fn getStdErr() File {
return .{ .handle = getStdErrHandle() };
}
fn getStdInHandle() posix.fd_t {
if (is_windows) {
return windows.peb().ProcessParameters.hStdInput;
}
if (@hasDecl(root, "os") and @hasDecl(root.os, "io") and @hasDecl(root.os.io, "getStdInHandle")) {
return root.os.io.getStdInHandle();
}
return posix.STDIN_FILENO;
}
pub fn getStdIn() File {
return .{ .handle = getStdInHandle() };
}
/// Deprecated in favor of `Reader`. /// Deprecated in favor of `Reader`.
pub fn GenericReader( pub fn GenericReader(
comptime Context: type, comptime Context: type,

View File

@ -56,7 +56,7 @@ pub const Value = union(enum) {
std.debug.lockStdErr(); std.debug.lockStdErr();
defer std.debug.unlockStdErr(); defer std.debug.unlockStdErr();
const stderr = std.io.getStdErr().writer(); const stderr = std.fs.File.stderr().writer();
stringify(self, .{}, stderr) catch return; stringify(self, .{}, stderr) catch return;
} }

View File

@ -47,7 +47,7 @@
//! // Print the message to stderr, silently ignoring any errors //! // Print the message to stderr, silently ignoring any errors
//! std.debug.lockStdErr(); //! std.debug.lockStdErr();
//! defer std.debug.unlockStdErr(); //! defer std.debug.unlockStdErr();
//! const stderr = std.io.getStdErr().writer(); //! const stderr = std.fs.File.stderr().writer();
//! nosuspend stderr.print(prefix ++ format ++ "\n", args) catch return; //! nosuspend stderr.print(prefix ++ format ++ "\n", args) catch return;
//! } //! }
//! //!
@ -148,7 +148,7 @@ pub fn defaultLog(
) void { ) void {
const level_txt = comptime message_level.asText(); const level_txt = comptime message_level.asText();
const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): "; const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";
const stderr = std.io.getStdErr().writer(); const stderr = std.fs.File.stderr().writer();
var bw = std.io.bufferedWriter(stderr); var bw = std.io.bufferedWriter(stderr);
const writer = bw.writer(); const writer = bw.writer();

View File

@ -390,7 +390,7 @@ pub fn expectEqualSlices(comptime T: type, expected: []const T, actual: []const
const actual_window = actual[window_start..@min(actual.len, window_start + max_window_size)]; const actual_window = actual[window_start..@min(actual.len, window_start + max_window_size)];
const actual_truncated = window_start + actual_window.len < actual.len; const actual_truncated = window_start + actual_window.len < actual.len;
const stderr = std.io.getStdErr(); const stderr: std.fs.File = .stderr();
const ttyconf = std.io.tty.detectConfig(stderr); const ttyconf = std.io.tty.detectConfig(stderr);
var differ = if (T == u8) BytesDiffer{ var differ = if (T == u8) BytesDiffer{
.expected = expected_window, .expected = expected_window,

View File

@ -39,7 +39,7 @@ fn benchmarkCodepointCount(buf: []const u8) !ResultCount {
} }
pub fn main() !void { pub fn main() !void {
const stdout = std.io.getStdOut().writer(); const stdout = std.fs.File.stdout().writer();
try stdout.print("short ASCII strings\n", .{}); try stdout.print("short ASCII strings\n", .{});
{ {

View File

@ -48,7 +48,7 @@ pub const Color = enum {
pub fn get_tty_conf(color: Color) std.io.tty.Config { pub fn get_tty_conf(color: Color) std.io.tty.Config {
return switch (color) { return switch (color) {
.auto => std.io.tty.detectConfig(std.io.getStdErr()), .auto => std.io.tty.detectConfig(std.fs.File.stderr()),
.on => .escape_codes, .on => .escape_codes,
.off => .no_color, .off => .no_color,
}; };

View File

@ -7,6 +7,11 @@
//! empty, it means there are no errors. This special encoding exists so that //! empty, it means there are no errors. This special encoding exists so that
//! heap allocation is not needed in the common case of no errors. //! heap allocation is not needed in the common case of no errors.
const std = @import("std");
const ErrorBundle = @This();
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
string_bytes: []const u8, string_bytes: []const u8,
/// The first thing in this array is an `ErrorMessageList`. /// The first thing in this array is an `ErrorMessageList`.
extra: []const u32, extra: []const u32,
@ -159,7 +164,7 @@ pub const RenderOptions = struct {
pub fn renderToStdErr(eb: ErrorBundle, options: RenderOptions) void { pub fn renderToStdErr(eb: ErrorBundle, options: RenderOptions) void {
std.debug.lockStdErr(); std.debug.lockStdErr();
defer std.debug.unlockStdErr(); defer std.debug.unlockStdErr();
const stderr = std.io.getStdErr(); const stderr: std.fs.File = .stderr();
return renderToWriter(eb, options, stderr.writer()) catch return; return renderToWriter(eb, options, stderr.writer()) catch return;
} }
@ -305,11 +310,6 @@ fn writeMsg(eb: ErrorBundle, err_msg: ErrorMessage, stderr: anytype, indent: usi
} }
} }
const std = @import("std");
const ErrorBundle = @This();
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
pub const Wip = struct { pub const Wip = struct {
gpa: Allocator, gpa: Allocator,
string_bytes: std.ArrayListUnmanaged(u8), string_bytes: std.ArrayListUnmanaged(u8),

View File

@ -9493,7 +9493,8 @@ pub fn asmValue(
} }
pub fn dump(self: *Builder) void { pub fn dump(self: *Builder) void {
self.print(std.io.getStdErr().writer()) catch {}; const stderr: std.fs.File = .stderr();
self.print(stderr.writer()) catch {};
} }
pub fn printToFile(self: *Builder, path: []const u8) Allocator.Error!bool { pub fn printToFile(self: *Builder, path: []const u8) Allocator.Error!bool {

View File

@ -1,3 +1,9 @@
const std = @import("std");
const mem = std.mem;
const print = std.debug.print;
const io = std.io;
const maxInt = std.math.maxInt;
test "zig fmt: remove extra whitespace at start and end of file with comment between" { test "zig fmt: remove extra whitespace at start and end of file with comment between" {
try testTransform( try testTransform(
\\ \\
@ -6315,16 +6321,10 @@ test "ampersand" {
, &.{}); , &.{});
} }
const std = @import("std");
const mem = std.mem;
const print = std.debug.print;
const io = std.io;
const maxInt = std.math.maxInt;
var fixed_buffer_mem: [100 * 1024]u8 = undefined; var fixed_buffer_mem: [100 * 1024]u8 = undefined;
fn testParse(source: [:0]const u8, allocator: mem.Allocator, anything_changed: *bool) ![]u8 { fn testParse(source: [:0]const u8, allocator: mem.Allocator, anything_changed: *bool) ![]u8 {
const stderr = io.getStdErr().writer(); const stderr = std.fs.File.stderr().writer();
var tree = try std.zig.Ast.parse(allocator, source, .zig); var tree = try std.zig.Ast.parse(allocator, source, .zig);
defer tree.deinit(allocator); defer tree.deinit(allocator);

View File

@ -22,7 +22,7 @@ pub fn main() !void {
const bytes_per_sec_float = @as(f64, @floatFromInt(source.len * iterations)) / elapsed_s; const bytes_per_sec_float = @as(f64, @floatFromInt(source.len * iterations)) / elapsed_s;
const bytes_per_sec = @as(u64, @intFromFloat(@floor(bytes_per_sec_float))); const bytes_per_sec = @as(u64, @intFromFloat(@floor(bytes_per_sec_float)));
var stdout_file = std.io.getStdOut(); var stdout_file: std.fs.File = .stdout();
const stdout = stdout_file.writer(); const stdout = stdout_file.writer();
try stdout.print("parsing speed: {:.2}/s, {:.2} used \n", .{ try stdout.print("parsing speed: {:.2}/s, {:.2} used \n", .{
fmtIntSizeBin(bytes_per_sec), fmtIntSizeBin(bytes_per_sec),

View File

@ -73,11 +73,11 @@ pub fn writeInst(
} }
pub fn dump(air: Air, pt: Zcu.PerThread, liveness: ?Air.Liveness) void { pub fn dump(air: Air, pt: Zcu.PerThread, liveness: ?Air.Liveness) void {
air.write(std.io.getStdErr().writer(), pt, liveness); air.write(std.fs.File.stderr().writer(), pt, liveness);
} }
pub fn dumpInst(air: Air, inst: Air.Inst.Index, pt: Zcu.PerThread, liveness: ?Air.Liveness) void { pub fn dumpInst(air: Air, inst: Air.Inst.Index, pt: Zcu.PerThread, liveness: ?Air.Liveness) void {
air.writeInst(std.io.getStdErr().writer(), inst, pt, liveness); air.writeInst(std.fs.File.stderr().writer(), inst, pt, liveness);
} }
const Writer = struct { const Writer = struct {

View File

@ -1875,7 +1875,7 @@ pub fn create(gpa: Allocator, arena: Allocator, options: CreateOptions) !*Compil
if (options.root_mod.resolved_target.llvm_cpu_features) |cf| print: { if (options.root_mod.resolved_target.llvm_cpu_features) |cf| print: {
std.debug.lockStdErr(); std.debug.lockStdErr();
defer std.debug.unlockStdErr(); defer std.debug.unlockStdErr();
const stderr = std.io.getStdErr().writer(); const stderr = std.fs.File.stderr().writer();
nosuspend { nosuspend {
stderr.print("compilation: {s}\n", .{options.root_name}) catch break :print; stderr.print("compilation: {s}\n", .{options.root_name}) catch break :print;
stderr.print(" target: {s}\n", .{try target.zigTriple(arena)}) catch break :print; stderr.print(" target: {s}\n", .{try target.zigTriple(arena)}) catch break :print;
@ -3932,7 +3932,7 @@ pub fn getAllErrorsAlloc(comp: *Compilation) !ErrorBundle {
// This AU is referenced and has a transitive compile error, meaning it referenced something with a compile error. // This AU is referenced and has a transitive compile error, meaning it referenced something with a compile error.
// However, we haven't reported any such error. // However, we haven't reported any such error.
// This is a compiler bug. // This is a compiler bug.
const stderr = std.io.getStdErr().writer(); const stderr = std.fs.File.stderr().writer();
try stderr.writeAll("referenced transitive analysis errors, but none actually emitted\n"); try stderr.writeAll("referenced transitive analysis errors, but none actually emitted\n");
try stderr.print("{} [transitive failure]\n", .{zcu.fmtAnalUnit(failed_unit)}); try stderr.print("{} [transitive failure]\n", .{zcu.fmtAnalUnit(failed_unit)});
while (ref) |r| { while (ref) |r| {
@ -7214,7 +7214,7 @@ pub fn lockAndSetMiscFailure(
pub fn dump_argv(argv: []const []const u8) void { pub fn dump_argv(argv: []const []const u8) void {
std.debug.lockStdErr(); std.debug.lockStdErr();
defer std.debug.unlockStdErr(); defer std.debug.unlockStdErr();
const stderr = std.io.getStdErr().writer(); const stderr = std.fs.File.stderr().writer();
for (argv[0 .. argv.len - 1]) |arg| { for (argv[0 .. argv.len - 1]) |arg| {
nosuspend stderr.print("{s} ", .{arg}) catch return; nosuspend stderr.print("{s} ", .{arg}) catch return;
} }

View File

@ -11259,7 +11259,7 @@ fn dumpStatsFallible(ip: *const InternPool, arena: Allocator) anyerror!void {
} }
fn dumpAllFallible(ip: *const InternPool) anyerror!void { fn dumpAllFallible(ip: *const InternPool) anyerror!void {
var bw = std.io.bufferedWriter(std.io.getStdErr().writer()); var bw = std.io.bufferedWriter(std.fs.File.stderr().writer());
const w = bw.writer(); const w = bw.writer();
for (ip.locals, 0..) |*local, tid| { for (ip.locals, 0..) |*local, tid| {
const items = local.shared.items.view(); const items = local.shared.items.view();
@ -11369,7 +11369,7 @@ pub fn dumpGenericInstancesFallible(ip: *const InternPool, allocator: Allocator)
defer arena_allocator.deinit(); defer arena_allocator.deinit();
const arena = arena_allocator.allocator(); const arena = arena_allocator.allocator();
var bw = std.io.bufferedWriter(std.io.getStdErr().writer()); var bw = std.io.bufferedWriter(std.fs.File.stderr().writer());
const w = bw.writer(); const w = bw.writer();
var instances: std.AutoArrayHashMapUnmanaged(Index, std.ArrayListUnmanaged(Index)) = .empty; var instances: std.AutoArrayHashMapUnmanaged(Index, std.ArrayListUnmanaged(Index)) = .empty;

View File

@ -27,6 +27,22 @@
//! All of this must be done with only referring to the state inside this struct //! All of this must be done with only referring to the state inside this struct
//! because this work will be done in a dedicated thread. //! because this work will be done in a dedicated thread.
const builtin = @import("builtin");
const std = @import("std");
const fs = std.fs;
const assert = std.debug.assert;
const ascii = std.ascii;
const Allocator = std.mem.Allocator;
const Cache = std.Build.Cache;
const ThreadPool = std.Thread.Pool;
const WaitGroup = std.Thread.WaitGroup;
const Fetch = @This();
const git = @import("Fetch/git.zig");
const Package = @import("../Package.zig");
const Manifest = Package.Manifest;
const ErrorBundle = std.zig.ErrorBundle;
const native_os = builtin.os.tag;
arena: std.heap.ArenaAllocator, arena: std.heap.ArenaAllocator,
location: Location, location: Location,
location_tok: std.zig.Ast.TokenIndex, location_tok: std.zig.Ast.TokenIndex,
@ -1638,7 +1654,7 @@ fn computeHash(f: *Fetch, pkg_path: Cache.Path, filter: Filter) RunError!Compute
} }
fn dumpHashInfo(all_files: []const *const HashedFile) !void { fn dumpHashInfo(all_files: []const *const HashedFile) !void {
const stdout = std.io.getStdOut(); const stdout: std.fs.File = .stdout();
var bw = std.io.bufferedWriter(stdout.writer()); var bw = std.io.bufferedWriter(stdout.writer());
const w = bw.writer(); const w = bw.writer();
@ -1817,28 +1833,6 @@ pub fn depDigest(pkg_root: Cache.Path, cache_root: Cache.Directory, dep: Manifes
} }
} }
const builtin = @import("builtin");
const std = @import("std");
const fs = std.fs;
const assert = std.debug.assert;
const ascii = std.ascii;
const Allocator = std.mem.Allocator;
const Cache = std.Build.Cache;
const ThreadPool = std.Thread.Pool;
const WaitGroup = std.Thread.WaitGroup;
const Fetch = @This();
const git = @import("Fetch/git.zig");
const Package = @import("../Package.zig");
const Manifest = Package.Manifest;
const ErrorBundle = std.zig.ErrorBundle;
const native_os = builtin.os.tag;
test {
_ = Filter;
_ = FileType;
_ = UnpackResult;
}
// Detects executable header: ELF or Macho-O magic header or shebang line. // Detects executable header: ELF or Macho-O magic header or shebang line.
const FileHeader = struct { const FileHeader = struct {
header: [4]u8 = undefined, header: [4]u8 = undefined,
@ -2437,3 +2431,9 @@ const TestFetchBuilder = struct {
try std.testing.expectEqualStrings(msg, al.items); try std.testing.expectEqualStrings(msg, al.items);
} }
}; };
test {
_ = Filter;
_ = FileType;
_ = UnpackResult;
}

View File

@ -4378,7 +4378,7 @@ fn runCodegenInner(pt: Zcu.PerThread, func_index: InternPool.Index, air: *Air) e
if (build_options.enable_debug_extensions and comp.verbose_air) { if (build_options.enable_debug_extensions and comp.verbose_air) {
std.debug.lockStdErr(); std.debug.lockStdErr();
defer std.debug.unlockStdErr(); defer std.debug.unlockStdErr();
const stderr = std.io.getStdErr().writer(); const stderr = std.fs.File.stderr().writer();
stderr.print("# Begin Function AIR: {}:\n", .{fqn.fmt(ip)}) catch {}; stderr.print("# Begin Function AIR: {}:\n", .{fqn.fmt(ip)}) catch {};
air.write(stderr, pt, liveness); air.write(stderr, pt, liveness);
stderr.print("# End Function AIR: {}\n\n", .{fqn.fmt(ip)}) catch {}; stderr.print("# End Function AIR: {}\n\n", .{fqn.fmt(ip)}) catch {};

View File

@ -80,7 +80,7 @@ fn dumpStatusReport() !void {
var fba = std.heap.FixedBufferAllocator.init(&crash_heap); var fba = std.heap.FixedBufferAllocator.init(&crash_heap);
const allocator = fba.allocator(); const allocator = fba.allocator();
const stderr = io.getStdErr().writer(); const stderr = std.fs.File.stderr().writer();
const block: *Sema.Block = anal.block; const block: *Sema.Block = anal.block;
const zcu = anal.sema.pt.zcu; const zcu = anal.sema.pt.zcu;
@ -271,7 +271,7 @@ const StackContext = union(enum) {
debug.dumpStackTraceFromBase(context); debug.dumpStackTraceFromBase(context);
}, },
.not_supported => { .not_supported => {
const stderr = io.getStdErr().writer(); const stderr = std.fs.File.stderr().writer();
stderr.writeAll("Stack trace not supported on this platform.\n") catch {}; stderr.writeAll("Stack trace not supported on this platform.\n") catch {};
}, },
} }
@ -379,7 +379,7 @@ const PanicSwitch = struct {
state.recover_stage = .release_mutex; state.recover_stage = .release_mutex;
const stderr = io.getStdErr().writer(); const stderr = std.fs.File.stderr().writer();
if (builtin.single_threaded) { if (builtin.single_threaded) {
stderr.print("panic: ", .{}) catch goTo(releaseMutex, .{state}); stderr.print("panic: ", .{}) catch goTo(releaseMutex, .{state});
} else { } else {
@ -406,7 +406,7 @@ const PanicSwitch = struct {
recover(state, trace, stack, msg); recover(state, trace, stack, msg);
state.recover_stage = .release_mutex; state.recover_stage = .release_mutex;
const stderr = io.getStdErr().writer(); const stderr = std.fs.File.stderr().writer();
stderr.writeAll("\nOriginal Error:\n") catch {}; stderr.writeAll("\nOriginal Error:\n") catch {};
goTo(reportStack, .{state}); goTo(reportStack, .{state});
} }
@ -477,7 +477,7 @@ const PanicSwitch = struct {
recover(state, trace, stack, msg); recover(state, trace, stack, msg);
state.recover_stage = .silent_abort; state.recover_stage = .silent_abort;
const stderr = io.getStdErr().writer(); const stderr = std.fs.File.stderr().writer();
stderr.writeAll("Aborting...\n") catch {}; stderr.writeAll("Aborting...\n") catch {};
goTo(abort, .{}); goTo(abort, .{});
} }
@ -505,7 +505,7 @@ const PanicSwitch = struct {
// lower the verbosity, and restore it at the end if we don't panic. // lower the verbosity, and restore it at the end if we don't panic.
state.recover_verbosity = .message_only; state.recover_verbosity = .message_only;
const stderr = io.getStdErr().writer(); const stderr = std.fs.File.stderr().writer();
stderr.writeAll("\nPanicked during a panic: ") catch {}; stderr.writeAll("\nPanicked during a panic: ") catch {};
stderr.writeAll(msg) catch {}; stderr.writeAll(msg) catch {};
stderr.writeAll("\nInner panic stack:\n") catch {}; stderr.writeAll("\nInner panic stack:\n") catch {};
@ -519,7 +519,7 @@ const PanicSwitch = struct {
.message_only => { .message_only => {
state.recover_verbosity = .silent; state.recover_verbosity = .silent;
const stderr = io.getStdErr().writer(); const stderr = std.fs.File.stderr().writer();
stderr.writeAll("\nPanicked while dumping inner panic stack: ") catch {}; stderr.writeAll("\nPanicked while dumping inner panic stack: ") catch {};
stderr.writeAll(msg) catch {}; stderr.writeAll(msg) catch {};
stderr.writeAll("\n") catch {}; stderr.writeAll("\n") catch {};

View File

@ -1,3 +1,11 @@
const std = @import("std");
const mem = std.mem;
const fs = std.fs;
const process = std.process;
const Allocator = std.mem.Allocator;
const Color = std.zig.Color;
const fatal = std.process.fatal;
const usage_fmt = const usage_fmt =
\\Usage: zig fmt [file]... \\Usage: zig fmt [file]...
\\ \\
@ -52,7 +60,7 @@ pub fn run(
const arg = args[i]; const arg = args[i];
if (mem.startsWith(u8, arg, "-")) { if (mem.startsWith(u8, arg, "-")) {
if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) { if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {
const stdout = std.io.getStdOut().writer(); const stdout = std.fs.File.stdout().writer();
try stdout.writeAll(usage_fmt); try stdout.writeAll(usage_fmt);
return process.cleanExit(); return process.cleanExit();
} else if (mem.eql(u8, arg, "--color")) { } else if (mem.eql(u8, arg, "--color")) {
@ -93,7 +101,7 @@ pub fn run(
fatal("cannot use --stdin with positional arguments", .{}); fatal("cannot use --stdin with positional arguments", .{});
} }
const stdin = std.io.getStdIn(); const stdin: fs.File = .stdin();
const source_code = std.zig.readSourceFileToEndAlloc(gpa, stdin, null) catch |err| { const source_code = std.zig.readSourceFileToEndAlloc(gpa, stdin, null) catch |err| {
fatal("unable to read stdin: {}", .{err}); fatal("unable to read stdin: {}", .{err});
}; };
@ -146,7 +154,7 @@ pub fn run(
process.exit(code); process.exit(code);
} }
return std.io.getStdOut().writeAll(formatted); return std.fs.File.stdout().writeAll(formatted);
} }
if (input_files.items.len == 0) { if (input_files.items.len == 0) {
@ -363,7 +371,7 @@ fn fmtPathFile(
return; return;
if (check_mode) { if (check_mode) {
const stdout = std.io.getStdOut().writer(); const stdout = std.fs.File.stdout().writer();
try stdout.print("{s}\n", .{file_path}); try stdout.print("{s}\n", .{file_path});
fmt.any_error = true; fmt.any_error = true;
} else { } else {
@ -372,15 +380,7 @@ fn fmtPathFile(
try af.file.writeAll(fmt.out_buffer.items); try af.file.writeAll(fmt.out_buffer.items);
try af.finish(); try af.finish();
const stdout = std.io.getStdOut().writer(); const stdout = std.fs.File.stdout().writer();
try stdout.print("{s}\n", .{file_path}); try stdout.print("{s}\n", .{file_path});
} }
} }
const std = @import("std");
const mem = std.mem;
const fs = std.fs;
const process = std.process;
const Allocator = std.mem.Allocator;
const Color = std.zig.Color;
const fatal = std.process.fatal;

View File

@ -306,7 +306,7 @@ pub fn buildImportLib(comp: *Compilation, lib_name: []const u8) !void {
if (comp.verbose_cc) print: { if (comp.verbose_cc) print: {
std.debug.lockStdErr(); std.debug.lockStdErr();
defer std.debug.unlockStdErr(); defer std.debug.unlockStdErr();
const stderr = std.io.getStdErr().writer(); const stderr = std.fs.File.stderr().writer();
nosuspend stderr.print("def file: {s}\n", .{def_file_path}) catch break :print; nosuspend stderr.print("def file: {s}\n", .{def_file_path}) catch break :print;
nosuspend stderr.print("include dir: {s}\n", .{include_dir}) catch break :print; nosuspend stderr.print("include dir: {s}\n", .{include_dir}) catch break :print;
nosuspend stderr.print("output path: {s}\n", .{def_final_path}) catch break :print; nosuspend stderr.print("output path: {s}\n", .{def_final_path}) catch break :print;
@ -326,7 +326,7 @@ pub fn buildImportLib(comp: *Compilation, lib_name: []const u8) !void {
for (aro_comp.diagnostics.list.items) |diagnostic| { for (aro_comp.diagnostics.list.items) |diagnostic| {
if (diagnostic.kind == .@"fatal error" or diagnostic.kind == .@"error") { if (diagnostic.kind == .@"fatal error" or diagnostic.kind == .@"error") {
aro.Diagnostics.render(&aro_comp, std.io.tty.detectConfig(std.io.getStdErr())); aro.Diagnostics.render(&aro_comp, std.io.tty.detectConfig(std.fs.File.stderr()));
return error.AroPreprocessorFailed; return error.AroPreprocessorFailed;
} }
} }

View File

@ -163,7 +163,7 @@ fn prune(elf_file: *Elf) void {
} }
pub fn dumpPrunedAtoms(elf_file: *Elf) !void { pub fn dumpPrunedAtoms(elf_file: *Elf) !void {
const stderr = std.io.getStdErr().writer(); const stderr = std.fs.File.stderr().writer();
for (elf_file.objects.items) |index| { for (elf_file.objects.items) |index| {
const file = elf_file.file(index).?; const file = elf_file.file(index).?;
for (file.atoms()) |atom_index| { for (file.atoms()) |atom_index| {

View File

@ -340,11 +340,11 @@ fn mainArgs(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
} else if (mem.eql(u8, cmd, "targets")) { } else if (mem.eql(u8, cmd, "targets")) {
dev.check(.targets_command); dev.check(.targets_command);
const host = std.zig.resolveTargetQueryOrFatal(.{}); const host = std.zig.resolveTargetQueryOrFatal(.{});
const stdout = io.getStdOut().writer(); const stdout = fs.File.stdout().writer();
return @import("print_targets.zig").cmdTargets(arena, cmd_args, stdout, &host); return @import("print_targets.zig").cmdTargets(arena, cmd_args, stdout, &host);
} else if (mem.eql(u8, cmd, "version")) { } else if (mem.eql(u8, cmd, "version")) {
dev.check(.version_command); dev.check(.version_command);
try std.io.getStdOut().writeAll(build_options.version ++ "\n"); try fs.File.stdout().writeAll(build_options.version ++ "\n");
// Check libc++ linkage to make sure Zig was built correctly, but only // Check libc++ linkage to make sure Zig was built correctly, but only
// for "env" and "version" to avoid affecting the startup time for // for "env" and "version" to avoid affecting the startup time for
// build-critical commands (check takes about ~10 μs) // build-critical commands (check takes about ~10 μs)
@ -352,7 +352,7 @@ fn mainArgs(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
} else if (mem.eql(u8, cmd, "env")) { } else if (mem.eql(u8, cmd, "env")) {
dev.check(.env_command); dev.check(.env_command);
verifyLibcxxCorrectlyLinked(); verifyLibcxxCorrectlyLinked();
return @import("print_env.zig").cmdEnv(arena, cmd_args, io.getStdOut().writer()); return @import("print_env.zig").cmdEnv(arena, cmd_args, fs.File.stdout().writer());
} else if (mem.eql(u8, cmd, "reduce")) { } else if (mem.eql(u8, cmd, "reduce")) {
return jitCmd(gpa, arena, cmd_args, .{ return jitCmd(gpa, arena, cmd_args, .{
.cmd_name = "reduce", .cmd_name = "reduce",
@ -360,10 +360,10 @@ fn mainArgs(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
}); });
} else if (mem.eql(u8, cmd, "zen")) { } else if (mem.eql(u8, cmd, "zen")) {
dev.check(.zen_command); dev.check(.zen_command);
return io.getStdOut().writeAll(info_zen); return fs.File.stdout().writeAll(info_zen);
} else if (mem.eql(u8, cmd, "help") or mem.eql(u8, cmd, "-h") or mem.eql(u8, cmd, "--help")) { } else if (mem.eql(u8, cmd, "help") or mem.eql(u8, cmd, "-h") or mem.eql(u8, cmd, "--help")) {
dev.check(.help_command); dev.check(.help_command);
return io.getStdOut().writeAll(usage); return fs.File.stdout().writeAll(usage);
} else if (mem.eql(u8, cmd, "ast-check")) { } else if (mem.eql(u8, cmd, "ast-check")) {
return cmdAstCheck(arena, cmd_args); return cmdAstCheck(arena, cmd_args);
} else if (mem.eql(u8, cmd, "detect-cpu")) { } else if (mem.eql(u8, cmd, "detect-cpu")) {
@ -1038,7 +1038,7 @@ fn buildOutputType(
}; };
} else if (mem.startsWith(u8, arg, "-")) { } else if (mem.startsWith(u8, arg, "-")) {
if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) { if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {
try io.getStdOut().writeAll(usage_build_generic); try fs.File.stdout().writeAll(usage_build_generic);
return cleanExit(); return cleanExit();
} else if (mem.eql(u8, arg, "--")) { } else if (mem.eql(u8, arg, "--")) {
if (arg_mode == .run) { if (arg_mode == .run) {
@ -2766,9 +2766,9 @@ fn buildOutputType(
} else if (mem.eql(u8, arg, "-V")) { } else if (mem.eql(u8, arg, "-V")) {
warn("ignoring request for supported emulations: unimplemented", .{}); warn("ignoring request for supported emulations: unimplemented", .{});
} else if (mem.eql(u8, arg, "-v")) { } else if (mem.eql(u8, arg, "-v")) {
try std.io.getStdOut().writeAll("zig ld " ++ build_options.version ++ "\n"); try fs.File.stdout().writeAll("zig ld " ++ build_options.version ++ "\n");
} else if (mem.eql(u8, arg, "--version")) { } else if (mem.eql(u8, arg, "--version")) {
try std.io.getStdOut().writeAll("zig ld " ++ build_options.version ++ "\n"); try fs.File.stdout().writeAll("zig ld " ++ build_options.version ++ "\n");
process.exit(0); process.exit(0);
} else { } else {
fatal("unsupported linker arg: {s}", .{arg}); fatal("unsupported linker arg: {s}", .{arg});
@ -3328,7 +3328,7 @@ fn buildOutputType(
var hasher = Cache.Hasher.init("0123456789abcdef"); var hasher = Cache.Hasher.init("0123456789abcdef");
var w = io.multiWriter(.{ f.writer(), hasher.writer() }); var w = io.multiWriter(.{ f.writer(), hasher.writer() });
var fifo = std.fifo.LinearFifo(u8, .{ .Static = 4096 }).init(); var fifo = std.fifo.LinearFifo(u8, .{ .Static = 4096 }).init();
try fifo.pump(io.getStdIn().reader(), w.writer()); try fifo.pump(fs.File.stdin().reader(), w.writer());
var bin_digest: Cache.BinDigest = undefined; var bin_digest: Cache.BinDigest = undefined;
hasher.final(&bin_digest); hasher.final(&bin_digest);
@ -3546,15 +3546,15 @@ fn buildOutputType(
if (show_builtin) { if (show_builtin) {
const builtin_opts = comp.root_mod.getBuiltinOptions(comp.config); const builtin_opts = comp.root_mod.getBuiltinOptions(comp.config);
const source = try builtin_opts.generate(arena); const source = try builtin_opts.generate(arena);
return std.io.getStdOut().writeAll(source); return fs.File.stdout().writeAll(source);
} }
switch (listen) { switch (listen) {
.none => {}, .none => {},
.stdio => { .stdio => {
try serve( try serve(
comp, comp,
std.io.getStdIn(), .stdin(),
std.io.getStdOut(), .stdout(),
test_exec_args.items, test_exec_args.items,
self_exe_path, self_exe_path,
arg_mode, arg_mode,
@ -4606,7 +4606,7 @@ fn cmdTranslateC(
fatal("unable to open cached translated zig file '{s}{s}{s}': {s}", .{ path, fs.path.sep_str, out_zig_path, @errorName(err) }); fatal("unable to open cached translated zig file '{s}{s}{s}': {s}", .{ path, fs.path.sep_str, out_zig_path, @errorName(err) });
}; };
defer zig_file.close(); defer zig_file.close();
try io.getStdOut().writeFileAll(zig_file, .{}); try fs.File.stdout().writeFileAll(zig_file, .{});
return cleanExit(); return cleanExit();
} }
} }
@ -4636,7 +4636,7 @@ fn cmdInit(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
if (mem.eql(u8, arg, "-s") or mem.eql(u8, arg, "--strip")) { if (mem.eql(u8, arg, "-s") or mem.eql(u8, arg, "--strip")) {
strip = true; strip = true;
} else if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) { } else if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {
try io.getStdOut().writeAll(usage_init); try fs.File.stdout().writeAll(usage_init);
return cleanExit(); return cleanExit();
} else { } else {
fatal("unrecognized parameter: '{s}'", .{arg}); fatal("unrecognized parameter: '{s}'", .{arg});
@ -5482,7 +5482,7 @@ fn jitCmd(
if (options.server) { if (options.server) {
var server = std.zig.Server{ var server = std.zig.Server{
.out = std.io.getStdOut(), .out = fs.File.stdout(),
.in = undefined, // won't be receiving messages .in = undefined, // won't be receiving messages
.receive_fifo = undefined, // won't be receiving messages .receive_fifo = undefined, // won't be receiving messages
}; };
@ -6015,7 +6015,7 @@ fn cmdAstCheck(
const arg = args[i]; const arg = args[i];
if (mem.startsWith(u8, arg, "-")) { if (mem.startsWith(u8, arg, "-")) {
if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) { if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {
try io.getStdOut().writeAll(usage_ast_check); try fs.File.stdout().writeAll(usage_ast_check);
return cleanExit(); return cleanExit();
} else if (mem.eql(u8, arg, "-t")) { } else if (mem.eql(u8, arg, "-t")) {
want_output_text = true; want_output_text = true;
@ -6046,7 +6046,7 @@ fn cmdAstCheck(
break :file fs.cwd().openFile(p, .{}) catch |err| { break :file fs.cwd().openFile(p, .{}) catch |err| {
fatal("unable to open file '{s}' for ast-check: {s}", .{ display_path, @errorName(err) }); fatal("unable to open file '{s}' for ast-check: {s}", .{ display_path, @errorName(err) });
}; };
} else io.getStdIn(); } else fs.File.stdin();
defer if (zig_source_path != null) f.close(); defer if (zig_source_path != null) f.close();
break :s std.zig.readSourceFileToEndAlloc(arena, f, null) catch |err| { break :s std.zig.readSourceFileToEndAlloc(arena, f, null) catch |err| {
fatal("unable to load file '{s}' for ast-check: {s}", .{ display_path, @errorName(err) }); fatal("unable to load file '{s}' for ast-check: {s}", .{ display_path, @errorName(err) });
@ -6107,7 +6107,7 @@ fn cmdAstCheck(
const extra_bytes = zir.extra.len * @sizeOf(u32); const extra_bytes = zir.extra.len * @sizeOf(u32);
const total_bytes = @sizeOf(Zir) + instruction_bytes + extra_bytes + const total_bytes = @sizeOf(Zir) + instruction_bytes + extra_bytes +
zir.string_bytes.len * @sizeOf(u8); zir.string_bytes.len * @sizeOf(u8);
const stdout = io.getStdOut(); const stdout = fs.File.stdout();
const fmtIntSizeBin = std.fmt.fmtIntSizeBin; const fmtIntSizeBin = std.fmt.fmtIntSizeBin;
// zig fmt: off // zig fmt: off
try stdout.writer().print( try stdout.writer().print(
@ -6131,7 +6131,7 @@ fn cmdAstCheck(
// zig fmt: on // zig fmt: on
} }
try @import("print_zir.zig").renderAsTextToFile(arena, tree, zir, io.getStdOut()); try @import("print_zir.zig").renderAsTextToFile(arena, tree, zir, fs.File.stdout());
if (zir.hasCompileErrors()) { if (zir.hasCompileErrors()) {
process.exit(1); process.exit(1);
@ -6158,7 +6158,7 @@ fn cmdAstCheck(
fatal("-t option only available in builds of zig with debug extensions", .{}); fatal("-t option only available in builds of zig with debug extensions", .{});
} }
try @import("print_zoir.zig").renderToFile(zoir, arena, io.getStdOut()); try @import("print_zoir.zig").renderToFile(zoir, arena, fs.File.stdout());
return cleanExit(); return cleanExit();
}, },
} }
@ -6186,7 +6186,7 @@ fn cmdDetectCpu(args: []const []const u8) !void {
const arg = args[i]; const arg = args[i];
if (mem.startsWith(u8, arg, "-")) { if (mem.startsWith(u8, arg, "-")) {
if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) { if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {
const stdout = io.getStdOut().writer(); const stdout = fs.File.stdout().writer();
try stdout.writeAll(detect_cpu_usage); try stdout.writeAll(detect_cpu_usage);
return cleanExit(); return cleanExit();
} else if (mem.eql(u8, arg, "--llvm")) { } else if (mem.eql(u8, arg, "--llvm")) {
@ -6279,7 +6279,7 @@ fn detectNativeCpuWithLLVM(
} }
fn printCpu(cpu: std.Target.Cpu) !void { fn printCpu(cpu: std.Target.Cpu) !void {
var bw = io.bufferedWriter(io.getStdOut().writer()); var bw = io.bufferedWriter(fs.File.stdout().writer());
const stdout = bw.writer(); const stdout = bw.writer();
if (cpu.model.llvm_name) |llvm_name| { if (cpu.model.llvm_name) |llvm_name| {
@ -6328,7 +6328,7 @@ fn cmdDumpLlvmInts(
const dl = tm.createTargetDataLayout(); const dl = tm.createTargetDataLayout();
const context = llvm.Context.create(); const context = llvm.Context.create();
var bw = io.bufferedWriter(io.getStdOut().writer()); var bw = io.bufferedWriter(fs.File.stdout().writer());
const stdout = bw.writer(); const stdout = bw.writer();
for ([_]u16{ 1, 8, 16, 32, 64, 128, 256 }) |bits| { for ([_]u16{ 1, 8, 16, 32, 64, 128, 256 }) |bits| {
@ -6368,7 +6368,7 @@ fn cmdDumpZir(
const extra_bytes = zir.extra.len * @sizeOf(u32); const extra_bytes = zir.extra.len * @sizeOf(u32);
const total_bytes = @sizeOf(Zir) + instruction_bytes + extra_bytes + const total_bytes = @sizeOf(Zir) + instruction_bytes + extra_bytes +
zir.string_bytes.len * @sizeOf(u8); zir.string_bytes.len * @sizeOf(u8);
const stdout = io.getStdOut(); const stdout = fs.File.stdout();
const fmtIntSizeBin = std.fmt.fmtIntSizeBin; const fmtIntSizeBin = std.fmt.fmtIntSizeBin;
// zig fmt: off // zig fmt: off
try stdout.writer().print( try stdout.writer().print(
@ -6386,7 +6386,7 @@ fn cmdDumpZir(
// zig fmt: on // zig fmt: on
} }
return @import("print_zir.zig").renderAsTextToFile(arena, null, zir, io.getStdOut()); return @import("print_zir.zig").renderAsTextToFile(arena, null, zir, fs.File.stdout());
} }
/// This is only enabled for debug builds. /// This is only enabled for debug builds.
@ -6444,7 +6444,7 @@ fn cmdChangelist(
var inst_map: std.AutoHashMapUnmanaged(Zir.Inst.Index, Zir.Inst.Index) = .empty; var inst_map: std.AutoHashMapUnmanaged(Zir.Inst.Index, Zir.Inst.Index) = .empty;
try Zcu.mapOldZirToNew(arena, old_zir, new_zir, &inst_map); try Zcu.mapOldZirToNew(arena, old_zir, new_zir, &inst_map);
var bw = io.bufferedWriter(io.getStdOut().writer()); var bw = io.bufferedWriter(fs.File.stdout().writer());
const stdout = bw.writer(); const stdout = bw.writer();
{ {
try stdout.print("Instruction mappings:\n", .{}); try stdout.print("Instruction mappings:\n", .{});
@ -6794,7 +6794,7 @@ fn cmdFetch(
const arg = args[i]; const arg = args[i];
if (mem.startsWith(u8, arg, "-")) { if (mem.startsWith(u8, arg, "-")) {
if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) { if (mem.eql(u8, arg, "-h") or mem.eql(u8, arg, "--help")) {
const stdout = io.getStdOut().writer(); const stdout = fs.File.stdout().writer();
try stdout.writeAll(usage_fetch); try stdout.writeAll(usage_fetch);
return cleanExit(); return cleanExit();
} else if (mem.eql(u8, arg, "--global-cache-dir")) { } else if (mem.eql(u8, arg, "--global-cache-dir")) {
@ -6908,7 +6908,7 @@ fn cmdFetch(
const name = switch (save) { const name = switch (save) {
.no => { .no => {
try io.getStdOut().writer().print("{s}\n", .{package_hash_slice}); try fs.File.stdout().writer().print("{s}\n", .{package_hash_slice});
return cleanExit(); return cleanExit();
}, },
.yes, .exact => |name| name: { .yes, .exact => |name| name: {