update standalone and incremental tests to new API

This commit is contained in:
Andrew Kelley 2025-07-07 19:33:20 -07:00
parent c873c2eed9
commit d8e26275f2
72 changed files with 347 additions and 892 deletions

View file

@ -374,7 +374,8 @@
<p> <p>
Most of the time, it is more appropriate to write to stderr rather than stdout, and Most of the time, it is more appropriate to write to stderr rather than stdout, and
whether or not the message is successfully written to the stream is irrelevant. whether or not the message is successfully written to the stream is irrelevant.
For this common case, there is a simpler API: Also, formatted printing often comes in handy. For this common case,
there is a simpler API:
</p> </p>
{#code|hello_again.zig#} {#code|hello_again.zig#}

View file

@ -17,7 +17,7 @@ pub fn main() !void {
.maximum = 0.20, .maximum = 0.20,
}; };
const category = threshold.categorize(0.90); const category = threshold.categorize(0.90);
try std.io.getStdOut().writeAll(@tagName(category)); try std.fs.File.stdout().writeAll(@tagName(category));
} }
const std = @import("std"); const std = @import("std");

View file

@ -1,8 +1,7 @@
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
const stdout = std.io.getStdOut().writer(); try std.fs.File.stdout().writeAll("Hello, World!\n");
try stdout.print("Hello, {s}!\n", .{"world"});
} }
// exe=succeed // exe=succeed

View file

@ -1,7 +1,7 @@
const std = @import("std"); const std = @import("std");
pub fn main() void { pub fn main() void {
std.debug.print("Hello, world!\n", .{}); std.debug.print("Hello, {s}!\n", .{"World"});
} }
// exe=succeed // exe=succeed

View file

@ -125,13 +125,12 @@ 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(); const stderr = std.debug.lockStderrWriter(&.{});
defer std.debug.unlockStdErr(); defer std.debug.unlockStderrWriter();
const stderr = std.fs.File.stderr().deprecatedWriter();
self.renderToWriter(args, stderr, config) catch return; self.renderToWriter(args, stderr, config) catch return;
} }
pub fn renderToWriter(self: *Diagnostics, args: []const []const u8, writer: anytype, config: std.io.tty.Config) !void { pub fn renderToWriter(self: *Diagnostics, args: []const []const u8, writer: *std.io.Writer, config: std.io.tty.Config) !void {
for (self.errors.items) |err_details| { for (self.errors.items) |err_details| {
try renderErrorMessage(writer, config, err_details, args); try renderErrorMessage(writer, config, err_details, args);
} }
@ -1403,7 +1402,7 @@ test parsePercent {
try std.testing.expectError(error.InvalidFormat, parsePercent("~1")); try std.testing.expectError(error.InvalidFormat, parsePercent("~1"));
} }
pub fn renderErrorMessage(writer: anytype, config: std.io.tty.Config, err_details: Diagnostics.ErrorDetails, args: []const []const u8) !void { pub fn renderErrorMessage(writer: *std.io.Writer, config: std.io.tty.Config, err_details: Diagnostics.ErrorDetails, args: []const []const u8) !void {
try config.setColor(writer, .dim); try config.setColor(writer, .dim);
try writer.writeAll("<cli>"); try writer.writeAll("<cli>");
try config.setColor(writer, .reset); try config.setColor(writer, .reset);
@ -1481,27 +1480,27 @@ pub fn renderErrorMessage(writer: anytype, config: std.io.tty.Config, err_detail
try writer.writeByte('\n'); try writer.writeByte('\n');
try config.setColor(writer, .green); try config.setColor(writer, .green);
try writer.writeByteNTimes(' ', prefix.len); try writer.splatByteAll(' ', prefix.len);
// Special case for when the option is *only* a prefix (e.g. invalid option: -) // Special case for when the option is *only* a prefix (e.g. invalid option: -)
if (err_details.arg_span.prefix_len == arg_with_name.len) { if (err_details.arg_span.prefix_len == arg_with_name.len) {
try writer.writeByteNTimes('^', err_details.arg_span.prefix_len); try writer.splatByteAll('^', err_details.arg_span.prefix_len);
} else { } else {
try writer.writeByteNTimes('~', err_details.arg_span.prefix_len); try writer.splatByteAll('~', err_details.arg_span.prefix_len);
try writer.writeByteNTimes(' ', err_details.arg_span.name_offset - err_details.arg_span.prefix_len); try writer.splatByteAll(' ', err_details.arg_span.name_offset - err_details.arg_span.prefix_len);
if (!err_details.arg_span.point_at_next_arg and err_details.arg_span.value_offset == 0) { if (!err_details.arg_span.point_at_next_arg and err_details.arg_span.value_offset == 0) {
try writer.writeByte('^'); try writer.writeByte('^');
try writer.writeByteNTimes('~', name_slice.len - 1); try writer.splatByteAll('~', name_slice.len - 1);
} else if (err_details.arg_span.value_offset > 0) { } else if (err_details.arg_span.value_offset > 0) {
try writer.writeByteNTimes('~', err_details.arg_span.value_offset - err_details.arg_span.name_offset); try writer.splatByteAll('~', err_details.arg_span.value_offset - err_details.arg_span.name_offset);
try writer.writeByte('^'); try writer.writeByte('^');
if (err_details.arg_span.value_offset < arg_with_name.len) { if (err_details.arg_span.value_offset < arg_with_name.len) {
try writer.writeByteNTimes('~', arg_with_name.len - err_details.arg_span.value_offset - 1); try writer.splatByteAll('~', arg_with_name.len - err_details.arg_span.value_offset - 1);
} }
} else if (err_details.arg_span.point_at_next_arg) { } else if (err_details.arg_span.point_at_next_arg) {
try writer.writeByteNTimes('~', arg_with_name.len - err_details.arg_span.name_offset + 1); try writer.splatByteAll('~', arg_with_name.len - err_details.arg_span.name_offset + 1);
try writer.writeByte('^'); try writer.writeByte('^');
if (next_arg_len > 0) { if (next_arg_len > 0) {
try writer.writeByteNTimes('~', next_arg_len - 1); try writer.splatByteAll('~', next_arg_len - 1);
} }
} }
} }

View file

@ -62,9 +62,8 @@ 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(); const stderr = std.debug.lockStderrWriter(&.{});
defer std.debug.unlockStdErr(); defer std.debug.unlockStderrWriter();
const stderr = std.fs.File.stderr().deprecatedWriter();
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;
} }
@ -445,7 +444,7 @@ pub const ErrorDetails = struct {
pub fn render(self: ErrorDetails, writer: anytype, source: []const u8, strings: []const []const u8) !void { pub fn render(self: ErrorDetails, writer: anytype, source: []const u8, strings: []const []const u8) !void {
switch (self.err) { switch (self.err) {
.unfinished_string_literal => { .unfinished_string_literal => {
return writer.print("unfinished string literal at '{s}', expected closing '\"'", .{self.fmtToken(source)}); return writer.print("unfinished string literal at '{f}', expected closing '\"'", .{self.fmtToken(source)});
}, },
.string_literal_too_long => { .string_literal_too_long => {
return writer.print("string literal too long (max is currently {} characters)", .{self.extra.number}); return writer.print("string literal too long (max is currently {} characters)", .{self.extra.number});
@ -524,26 +523,26 @@ pub const ErrorDetails = struct {
return writer.print("unsupported code page '{s} (id={})' in #pragma code_page", .{ @tagName(code_page), number }); return writer.print("unsupported code page '{s} (id={})' in #pragma code_page", .{ @tagName(code_page), number });
}, },
.unfinished_raw_data_block => { .unfinished_raw_data_block => {
return writer.print("unfinished raw data block at '{s}', expected closing '}}' or 'END'", .{self.fmtToken(source)}); return writer.print("unfinished raw data block at '{f}', expected closing '}}' or 'END'", .{self.fmtToken(source)});
}, },
.unfinished_string_table_block => { .unfinished_string_table_block => {
return writer.print("unfinished STRINGTABLE block at '{s}', expected closing '}}' or 'END'", .{self.fmtToken(source)}); return writer.print("unfinished STRINGTABLE block at '{f}', expected closing '}}' or 'END'", .{self.fmtToken(source)});
}, },
.expected_token => { .expected_token => {
return writer.print("expected '{s}', got '{s}'", .{ self.extra.expected.nameForErrorDisplay(), self.fmtToken(source) }); return writer.print("expected '{s}', got '{f}'", .{ self.extra.expected.nameForErrorDisplay(), self.fmtToken(source) });
}, },
.expected_something_else => { .expected_something_else => {
try writer.writeAll("expected "); try writer.writeAll("expected ");
try self.extra.expected_types.writeCommaSeparated(writer); try self.extra.expected_types.writeCommaSeparated(writer);
return writer.print("; got '{s}'", .{self.fmtToken(source)}); return writer.print("; got '{f}'", .{self.fmtToken(source)});
}, },
.resource_type_cant_use_raw_data => switch (self.type) { .resource_type_cant_use_raw_data => switch (self.type) {
.err, .warning => try writer.print("expected '<filename>', found '{s}' (resource type '{s}' can't use raw data)", .{ self.fmtToken(source), self.extra.resource.nameForErrorDisplay() }), .err, .warning => try writer.print("expected '<filename>', found '{f}' (resource type '{s}' can't use raw data)", .{ self.fmtToken(source), self.extra.resource.nameForErrorDisplay() }),
.note => try writer.print("if '{s}' is intended to be a filename, it must be specified as a quoted string literal", .{self.fmtToken(source)}), .note => try writer.print("if '{f}' is intended to be a filename, it must be specified as a quoted string literal", .{self.fmtToken(source)}),
.hint => return, .hint => return,
}, },
.id_must_be_ordinal => { .id_must_be_ordinal => {
try writer.print("id of resource type '{s}' must be an ordinal (u16), got '{s}'", .{ self.extra.resource.nameForErrorDisplay(), self.fmtToken(source) }); try writer.print("id of resource type '{s}' must be an ordinal (u16), got '{f}'", .{ self.extra.resource.nameForErrorDisplay(), self.fmtToken(source) });
}, },
.name_or_id_not_allowed => { .name_or_id_not_allowed => {
try writer.print("name or id is not allowed for resource type '{s}'", .{self.extra.resource.nameForErrorDisplay()}); try writer.print("name or id is not allowed for resource type '{s}'", .{self.extra.resource.nameForErrorDisplay()});
@ -559,7 +558,7 @@ pub const ErrorDetails = struct {
try writer.writeAll("ASCII character not equivalent to virtual key code"); try writer.writeAll("ASCII character not equivalent to virtual key code");
}, },
.empty_menu_not_allowed => { .empty_menu_not_allowed => {
try writer.print("empty menu of type '{s}' not allowed", .{self.fmtToken(source)}); try writer.print("empty menu of type '{f}' not allowed", .{self.fmtToken(source)});
}, },
.rc_would_miscompile_version_value_padding => switch (self.type) { .rc_would_miscompile_version_value_padding => switch (self.type) {
.err, .warning => return writer.print("the padding before this quoted string value would be miscompiled by the Win32 RC compiler", .{}), .err, .warning => return writer.print("the padding before this quoted string value would be miscompiled by the Win32 RC compiler", .{}),
@ -624,7 +623,7 @@ pub const ErrorDetails = struct {
.string_already_defined => switch (self.type) { .string_already_defined => switch (self.type) {
.err, .warning => { .err, .warning => {
const language = self.extra.string_and_language.language; const language = self.extra.string_and_language.language;
return writer.print("string with id {d} (0x{X}) already defined for language {}", .{ self.extra.string_and_language.id, self.extra.string_and_language.id, language }); return writer.print("string with id {d} (0x{X}) already defined for language {f}", .{ self.extra.string_and_language.id, self.extra.string_and_language.id, language });
}, },
.note => return writer.print("previous definition of string with id {d} (0x{X}) here", .{ self.extra.string_and_language.id, self.extra.string_and_language.id }), .note => return writer.print("previous definition of string with id {d} (0x{X}) here", .{ self.extra.string_and_language.id, self.extra.string_and_language.id }),
.hint => return, .hint => return,
@ -639,7 +638,7 @@ pub const ErrorDetails = struct {
try writer.print("unable to open file '{s}': {s}", .{ strings[self.extra.file_open_error.filename_string_index], @tagName(self.extra.file_open_error.err) }); try writer.print("unable to open file '{s}': {s}", .{ strings[self.extra.file_open_error.filename_string_index], @tagName(self.extra.file_open_error.err) });
}, },
.invalid_accelerator_key => { .invalid_accelerator_key => {
try writer.print("invalid accelerator key '{s}': {s}", .{ self.fmtToken(source), @tagName(self.extra.accelerator_error.err) }); try writer.print("invalid accelerator key '{f}': {s}", .{ self.fmtToken(source), @tagName(self.extra.accelerator_error.err) });
}, },
.accelerator_type_required => { .accelerator_type_required => {
try writer.writeAll("accelerator type [ASCII or VIRTKEY] required when key is an integer"); try writer.writeAll("accelerator type [ASCII or VIRTKEY] required when key is an integer");
@ -895,7 +894,7 @@ fn cellCount(code_page: SupportedCodePage, source: []const u8, start_index: usiz
const truncated_str = "<...truncated...>"; const truncated_str = "<...truncated...>";
pub fn renderErrorMessage(writer: anytype, tty_config: std.io.tty.Config, cwd: std.fs.Dir, err_details: ErrorDetails, source: []const u8, strings: []const []const u8, source_mappings: ?SourceMappings) !void { pub fn renderErrorMessage(writer: *std.io.Writer, tty_config: std.io.tty.Config, cwd: std.fs.Dir, err_details: ErrorDetails, source: []const u8, strings: []const []const u8, source_mappings: ?SourceMappings) !void {
if (err_details.type == .hint) return; if (err_details.type == .hint) return;
const source_line_start = err_details.token.getLineStartForErrorDisplay(source); const source_line_start = err_details.token.getLineStartForErrorDisplay(source);
@ -978,10 +977,10 @@ pub fn renderErrorMessage(writer: anytype, tty_config: std.io.tty.Config, cwd: s
try tty_config.setColor(writer, .green); try tty_config.setColor(writer, .green);
const num_spaces = truncated_visual_info.point_offset - truncated_visual_info.before_len; const num_spaces = truncated_visual_info.point_offset - truncated_visual_info.before_len;
try writer.writeByteNTimes(' ', num_spaces); try writer.splatByteAll(' ', num_spaces);
try writer.writeByteNTimes('~', truncated_visual_info.before_len); try writer.splatByteAll('~', truncated_visual_info.before_len);
try writer.writeByte('^'); try writer.writeByte('^');
try writer.writeByteNTimes('~', truncated_visual_info.after_len); try writer.splatByteAll('~', truncated_visual_info.after_len);
try writer.writeByte('\n'); try writer.writeByte('\n');
try tty_config.setColor(writer, .reset); try tty_config.setColor(writer, .reset);
@ -1082,7 +1081,7 @@ const CorrespondingLines = struct {
buffered_reader: BufferedReaderType, buffered_reader: BufferedReaderType,
code_page: SupportedCodePage, code_page: SupportedCodePage,
const BufferedReaderType = std.io.BufferedReader(512, std.fs.File.Reader); const BufferedReaderType = std.io.BufferedReader(512, std.fs.File.DeprecatedReader);
pub fn init(cwd: std.fs.Dir, err_details: ErrorDetails, line_for_comparison: []const u8, corresponding_span: SourceMappings.CorrespondingSpan, corresponding_file: []const u8) !CorrespondingLines { pub fn init(cwd: std.fs.Dir, err_details: ErrorDetails, line_for_comparison: []const u8, corresponding_span: SourceMappings.CorrespondingSpan, corresponding_file: []const u8) !CorrespondingLines {
// We don't do line comparison for this error, so don't print the note if the line // We don't do line comparison for this error, so don't print the note if the line

View file

@ -29,7 +29,7 @@ pub fn main() !void {
defer std.process.argsFree(allocator, args); defer std.process.argsFree(allocator, args);
if (args.len < 2) { if (args.len < 2) {
try renderErrorMessage(stderr.deprecatedWriter(), stderr_config, .err, "expected zig lib dir as first argument", .{}); try renderErrorMessage(std.debug.lockStderrWriter(&.{}), stderr_config, .err, "expected zig lib dir as first argument", .{});
std.process.exit(1); std.process.exit(1);
} }
const zig_lib_dir = args[1]; const zig_lib_dir = args[1];
@ -343,7 +343,7 @@ pub fn main() !void {
switch (err) { switch (err) {
error.DuplicateResource => { error.DuplicateResource => {
const duplicate_resource = resources.list.items[cvtres_diagnostics.duplicate_resource]; const duplicate_resource = resources.list.items[cvtres_diagnostics.duplicate_resource];
try error_handler.emitMessage(allocator, .err, "duplicate resource [id: {}, type: {}, language: {}]", .{ try error_handler.emitMessage(allocator, .err, "duplicate resource [id: {f}, type: {f}, language: {f}]", .{
duplicate_resource.name_value, duplicate_resource.name_value,
fmtResourceType(duplicate_resource.type_value), fmtResourceType(duplicate_resource.type_value),
duplicate_resource.language, duplicate_resource.language,
@ -352,7 +352,7 @@ pub fn main() !void {
error.ResourceDataTooLong => { error.ResourceDataTooLong => {
const overflow_resource = resources.list.items[cvtres_diagnostics.duplicate_resource]; const overflow_resource = resources.list.items[cvtres_diagnostics.duplicate_resource];
try error_handler.emitMessage(allocator, .err, "resource has a data length that is too large to be written into a coff section", .{}); try error_handler.emitMessage(allocator, .err, "resource has a data length that is too large to be written into a coff section", .{});
try error_handler.emitMessage(allocator, .note, "the resource with the invalid size is [id: {}, type: {}, language: {}]", .{ try error_handler.emitMessage(allocator, .note, "the resource with the invalid size is [id: {f}, type: {f}, language: {f}]", .{
overflow_resource.name_value, overflow_resource.name_value,
fmtResourceType(overflow_resource.type_value), fmtResourceType(overflow_resource.type_value),
overflow_resource.language, overflow_resource.language,
@ -361,7 +361,7 @@ pub fn main() !void {
error.TotalResourceDataTooLong => { error.TotalResourceDataTooLong => {
const overflow_resource = resources.list.items[cvtres_diagnostics.duplicate_resource]; const overflow_resource = resources.list.items[cvtres_diagnostics.duplicate_resource];
try error_handler.emitMessage(allocator, .err, "total resource data exceeds the maximum of the coff 'size of raw data' field", .{}); try error_handler.emitMessage(allocator, .err, "total resource data exceeds the maximum of the coff 'size of raw data' field", .{});
try error_handler.emitMessage(allocator, .note, "size overflow occurred when attempting to write this resource: [id: {}, type: {}, language: {}]", .{ try error_handler.emitMessage(allocator, .note, "size overflow occurred when attempting to write this resource: [id: {f}, type: {f}, language: {f}]", .{
overflow_resource.name_value, overflow_resource.name_value,
fmtResourceType(overflow_resource.type_value), fmtResourceType(overflow_resource.type_value),
overflow_resource.language, overflow_resource.language,
@ -645,7 +645,9 @@ 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.fs.File.stderr().deprecatedWriter(), self.tty, .err, "{s}\n", .{fail_msg}); const stderr = std.debug.lockStderrWriter(&.{});
defer std.debug.unlockStderrWriter();
try renderErrorMessage(stderr, self.tty, .err, "{s}\n", .{fail_msg});
aro.Diagnostics.render(comp, self.tty); aro.Diagnostics.render(comp, self.tty);
}, },
} }
@ -690,7 +692,9 @@ const ErrorHandler = union(enum) {
try server.serveErrorBundle(error_bundle); try server.serveErrorBundle(error_bundle);
}, },
.tty => { .tty => {
try renderErrorMessage(std.fs.File.stderr().deprecatedWriter(), self.tty, msg_type, format, args); const stderr = std.debug.lockStderrWriter(&.{});
defer std.debug.unlockStderrWriter();
try renderErrorMessage(stderr, self.tty, msg_type, format, args);
}, },
} }
} }

View file

@ -442,7 +442,7 @@ pub const NameOrOrdinal = union(enum) {
pub fn format(self: NameOrOrdinal, w: *std.io.Writer) !void { pub fn format(self: NameOrOrdinal, w: *std.io.Writer) !void {
switch (self) { switch (self) {
.name => |name| { .name => |name| {
try w.print("{s}", .{std.unicode.fmtUtf16Le(name)}); try w.print("{f}", .{std.unicode.fmtUtf16Le(name)});
}, },
.ordinal => |ordinal| { .ordinal => |ordinal| {
try w.print("{d}", .{ordinal}); try w.print("{d}", .{ordinal});
@ -453,7 +453,7 @@ pub const NameOrOrdinal = union(enum) {
fn formatResourceType(self: NameOrOrdinal, w: *std.io.Writer) std.io.Writer.Error!void { fn formatResourceType(self: NameOrOrdinal, w: *std.io.Writer) std.io.Writer.Error!void {
switch (self) { switch (self) {
.name => |name| { .name => |name| {
try w.print("{s}", .{std.unicode.fmtUtf16Le(name)}); try w.print("{f}", .{std.unicode.fmtUtf16Le(name)});
}, },
.ordinal => |ordinal| { .ordinal => |ordinal| {
if (std.enums.tagName(RT, @enumFromInt(ordinal))) |predefined_type_name| { if (std.enums.tagName(RT, @enumFromInt(ordinal))) |predefined_type_name| {

View file

@ -86,7 +86,7 @@ pub const ErrorMessageType = enum { err, warning, note };
/// Used for generic colored errors/warnings/notes, more context-specific error messages /// Used for generic colored errors/warnings/notes, more context-specific error messages
/// are handled elsewhere. /// are handled elsewhere.
pub fn renderErrorMessage(writer: anytype, config: std.io.tty.Config, msg_type: ErrorMessageType, comptime format: []const u8, args: anytype) !void { pub fn renderErrorMessage(writer: *std.io.Writer, config: std.io.tty.Config, msg_type: ErrorMessageType, comptime format: []const u8, args: anytype) !void {
switch (msg_type) { switch (msg_type) {
.err => { .err => {
try config.setColor(writer, .bold); try config.setColor(writer, .bold);

View file

@ -9,7 +9,8 @@ pub const std_options = std.Options{
.logFn = logOverride, .logFn = logOverride,
}; };
var log_file: ?std.fs.File = null; var log_file_buffer: [256]u8 = undefined;
var log_file_writer: ?std.fs.File.Writer = null;
fn logOverride( fn logOverride(
comptime level: std.log.Level, comptime level: std.log.Level,
@ -17,15 +18,17 @@ fn logOverride(
comptime format: []const u8, comptime format: []const u8,
args: anytype, args: anytype,
) void { ) void {
const f = if (log_file) |f| f else f: { const fw = if (log_file_writer) |*f| f else f: {
const f = fuzzer.cache_dir.createFile("tmp/libfuzzer.log", .{}) catch const f = fuzzer.cache_dir.createFile("tmp/libfuzzer.log", .{}) catch
@panic("failed to open fuzzer log file"); @panic("failed to open fuzzer log file");
log_file = f; log_file_writer = f.writer(&log_file_buffer);
break :f f; break :f &log_file_writer.?;
}; };
const prefix1 = comptime level.asText(); const prefix1 = comptime level.asText();
const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): "; const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): ";
f.writer().print(prefix1 ++ prefix2 ++ format ++ "\n", args) catch @panic("failed to write to fuzzer log"); fw.interface.print(prefix1 ++ prefix2 ++ format ++ "\n", args) catch
@panic("failed to write to fuzzer log");
fw.interface.flush() catch @panic("failed to flush fuzzer log");
} }
/// Helps determine run uniqueness in the face of recursion. /// Helps determine run uniqueness in the face of recursion.
@ -226,18 +229,18 @@ const Fuzzer = struct {
.read = true, .read = true,
}) catch |e| switch (e) { }) catch |e| switch (e) {
error.PathAlreadyExists => continue, error.PathAlreadyExists => continue,
else => fatal("unable to create '{}{d}: {s}", .{ f.corpus_directory, i, @errorName(err) }), else => fatal("unable to create '{f}{d}: {s}", .{ f.corpus_directory, i, @errorName(err) }),
}; };
errdefer input_file.close(); errdefer input_file.close();
// Initialize the mmap for the current input. // Initialize the mmap for the current input.
f.input = MemoryMappedList.create(input_file, 0, std.heap.page_size_max) catch |e| { f.input = MemoryMappedList.create(input_file, 0, std.heap.page_size_max) catch |e| {
fatal("unable to init memory map for input at '{}{d}': {s}", .{ fatal("unable to init memory map for input at '{f}{d}': {s}", .{
f.corpus_directory, i, @errorName(e), f.corpus_directory, i, @errorName(e),
}); });
}; };
break; break;
}, },
else => fatal("unable to read '{}{d}': {s}", .{ f.corpus_directory, i, @errorName(err) }), else => fatal("unable to read '{f}{d}': {s}", .{ f.corpus_directory, i, @errorName(err) }),
}; };
errdefer gpa.free(input); errdefer gpa.free(input);
f.corpus.append(gpa, .{ f.corpus.append(gpa, .{
@ -263,7 +266,7 @@ const Fuzzer = struct {
const sub_path = try std.fmt.allocPrint(gpa, "f/{s}", .{f.unit_test_name}); const sub_path = try std.fmt.allocPrint(gpa, "f/{s}", .{f.unit_test_name});
f.corpus_directory = .{ f.corpus_directory = .{
.handle = f.cache_dir.makeOpenPath(sub_path, .{}) catch |err| .handle = f.cache_dir.makeOpenPath(sub_path, .{}) catch |err|
fatal("unable to open corpus directory 'f/{s}': {s}", .{ sub_path, @errorName(err) }), fatal("unable to open corpus directory 'f/{s}': {t}", .{ sub_path, err }),
.path = sub_path, .path = sub_path,
}; };
initNextInput(f); initNextInput(f);

View file

@ -511,7 +511,7 @@ pub const Header = struct {
pub fn read(parse_source: anytype) !Header { pub fn read(parse_source: anytype) !Header {
var hdr_buf: [@sizeOf(Elf64_Ehdr)]u8 align(@alignOf(Elf64_Ehdr)) = undefined; var hdr_buf: [@sizeOf(Elf64_Ehdr)]u8 align(@alignOf(Elf64_Ehdr)) = undefined;
try parse_source.seekableStream().seekTo(0); try parse_source.seekableStream().seekTo(0);
try parse_source.reader().readNoEof(&hdr_buf); try parse_source.deprecatedReader().readNoEof(&hdr_buf);
return Header.parse(&hdr_buf); return Header.parse(&hdr_buf);
} }
@ -586,7 +586,7 @@ pub fn ProgramHeaderIterator(comptime ParseSource: anytype) type {
var phdr: Elf64_Phdr = undefined; var phdr: Elf64_Phdr = undefined;
const offset = self.elf_header.phoff + @sizeOf(@TypeOf(phdr)) * self.index; const offset = self.elf_header.phoff + @sizeOf(@TypeOf(phdr)) * self.index;
try self.parse_source.seekableStream().seekTo(offset); try self.parse_source.seekableStream().seekTo(offset);
try self.parse_source.reader().readNoEof(mem.asBytes(&phdr)); try self.parse_source.deprecatedReader().readNoEof(mem.asBytes(&phdr));
// ELF endianness matches native endianness. // ELF endianness matches native endianness.
if (self.elf_header.endian == native_endian) return phdr; if (self.elf_header.endian == native_endian) return phdr;
@ -599,7 +599,7 @@ pub fn ProgramHeaderIterator(comptime ParseSource: anytype) type {
var phdr: Elf32_Phdr = undefined; var phdr: Elf32_Phdr = undefined;
const offset = self.elf_header.phoff + @sizeOf(@TypeOf(phdr)) * self.index; const offset = self.elf_header.phoff + @sizeOf(@TypeOf(phdr)) * self.index;
try self.parse_source.seekableStream().seekTo(offset); try self.parse_source.seekableStream().seekTo(offset);
try self.parse_source.reader().readNoEof(mem.asBytes(&phdr)); try self.parse_source.deprecatedReader().readNoEof(mem.asBytes(&phdr));
// ELF endianness does NOT match native endianness. // ELF endianness does NOT match native endianness.
if (self.elf_header.endian != native_endian) { if (self.elf_header.endian != native_endian) {
@ -636,7 +636,7 @@ pub fn SectionHeaderIterator(comptime ParseSource: anytype) type {
var shdr: Elf64_Shdr = undefined; var shdr: Elf64_Shdr = undefined;
const offset = self.elf_header.shoff + @sizeOf(@TypeOf(shdr)) * self.index; const offset = self.elf_header.shoff + @sizeOf(@TypeOf(shdr)) * self.index;
try self.parse_source.seekableStream().seekTo(offset); try self.parse_source.seekableStream().seekTo(offset);
try self.parse_source.reader().readNoEof(mem.asBytes(&shdr)); try self.parse_source.deprecatedReader().readNoEof(mem.asBytes(&shdr));
// ELF endianness matches native endianness. // ELF endianness matches native endianness.
if (self.elf_header.endian == native_endian) return shdr; if (self.elf_header.endian == native_endian) return shdr;
@ -649,7 +649,7 @@ pub fn SectionHeaderIterator(comptime ParseSource: anytype) type {
var shdr: Elf32_Shdr = undefined; var shdr: Elf32_Shdr = undefined;
const offset = self.elf_header.shoff + @sizeOf(@TypeOf(shdr)) * self.index; const offset = self.elf_header.shoff + @sizeOf(@TypeOf(shdr)) * self.index;
try self.parse_source.seekableStream().seekTo(offset); try self.parse_source.seekableStream().seekTo(offset);
try self.parse_source.reader().readNoEof(mem.asBytes(&shdr)); try self.parse_source.deprecatedReader().readNoEof(mem.asBytes(&shdr));
// ELF endianness does NOT match native endianness. // ELF endianness does NOT match native endianness.
if (self.elf_header.endian != native_endian) { if (self.elf_header.endian != native_endian) {

View file

@ -705,6 +705,8 @@ pub fn sendFileReading(w: *Writer, file_reader: *File.Reader, limit: Limit) File
return n; return n;
} }
/// Number of bytes logically written is returned. This excludes bytes from
/// `buffer` because they have already been logically written.
pub fn sendFileAll(w: *Writer, file_reader: *File.Reader, limit: Limit) FileAllError!usize { pub fn sendFileAll(w: *Writer, file_reader: *File.Reader, limit: Limit) FileAllError!usize {
var remaining = @intFromEnum(limit); var remaining = @intFromEnum(limit);
while (remaining > 0) { while (remaining > 0) {

View file

@ -2812,9 +2812,8 @@ pub fn unexpectedError(err: Win32Error) UnexpectedError {
buf_wstr.len, buf_wstr.len,
null, null,
); );
std.debug.print("error.Unexpected: GetLastError({}): {}\n", .{ std.debug.print("error.Unexpected: GetLastError({d}): {f}\n", .{
@intFromEnum(err), err, std.unicode.fmtUtf16Le(buf_wstr[0..len]),
std.unicode.fmtUtf16Le(buf_wstr[0..len]),
}); });
std.debug.dumpCurrentStackTrace(@returnAddress()); std.debug.dumpCurrentStackTrace(@returnAddress());
} }

View file

@ -2744,11 +2744,11 @@ test "zig fmt: preserve spacing" {
\\const std = @import("std"); \\const std = @import("std");
\\ \\
\\pub fn main() !void { \\pub fn main() !void {
\\ var stdout_file = std.io.getStdOut; \\ var stdout_file = std.lol.abcd;
\\ var stdout_file = std.io.getStdOut; \\ var stdout_file = std.lol.abcd;
\\ \\
\\ var stdout_file = std.io.getStdOut; \\ var stdout_file = std.lol.abcd;
\\ var stdout_file = std.io.getStdOut; \\ var stdout_file = std.lol.abcd;
\\} \\}
\\ \\
); );

View file

@ -6074,7 +6074,7 @@ fn cmdAstCheck(
const tree = try Ast.parse(arena, source, mode); const tree = try Ast.parse(arena, source, mode);
var stdout_writer = fs.File.stdout().writer(&stdio_buffer); var stdout_writer = fs.File.stdout().writerStreaming(&stdio_buffer);
const stdout_bw = &stdout_writer.interface; const stdout_bw = &stdout_writer.interface;
switch (mode) { switch (mode) {
.zig => { .zig => {
@ -6289,7 +6289,7 @@ fn detectNativeCpuWithLLVM(
} }
fn printCpu(cpu: std.Target.Cpu) !void { fn printCpu(cpu: std.Target.Cpu) !void {
var stdout_writer = fs.File.stdout().writer(&stdio_buffer); var stdout_writer = fs.File.stdout().writerStreaming(&stdio_buffer);
const stdout_bw = &stdout_writer.interface; const stdout_bw = &stdout_writer.interface;
if (cpu.model.llvm_name) |llvm_name| { if (cpu.model.llvm_name) |llvm_name| {
@ -6338,7 +6338,7 @@ fn cmdDumpLlvmInts(
const dl = tm.createTargetDataLayout(); const dl = tm.createTargetDataLayout();
const context = llvm.Context.create(); const context = llvm.Context.create();
var stdout_writer = fs.File.stdout().writer(&stdio_buffer); var stdout_writer = fs.File.stdout().writerStreaming(&stdio_buffer);
const stdout_bw = &stdout_writer.interface; const stdout_bw = &stdout_writer.interface;
for ([_]u16{ 1, 8, 16, 32, 64, 128, 256 }) |bits| { for ([_]u16{ 1, 8, 16, 32, 64, 128, 256 }) |bits| {
const int_type = context.intType(bits); const int_type = context.intType(bits);
@ -6367,7 +6367,7 @@ fn cmdDumpZir(
defer f.close(); defer f.close();
const zir = try Zcu.loadZirCache(arena, f); const zir = try Zcu.loadZirCache(arena, f);
var stdout_writer = fs.File.stdout().writer(&stdio_buffer); var stdout_writer = fs.File.stdout().writerStreaming(&stdio_buffer);
const stdout_bw = &stdout_writer.interface; const stdout_bw = &stdout_writer.interface;
{ {
@ -6453,7 +6453,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 stdout_writer = fs.File.stdout().writer(&stdio_buffer); var stdout_writer = fs.File.stdout().writerStreaming(&stdio_buffer);
const stdout_bw = &stdout_writer.interface; const stdout_bw = &stdout_writer.interface;
{ {
try stdout_bw.print("Instruction mappings:\n", .{}); try stdout_bw.print("Instruction mappings:\n", .{});
@ -6913,7 +6913,7 @@ fn cmdFetch(
const name = switch (save) { const name = switch (save) {
.no => { .no => {
var stdout = fs.File.stdout().writer(&stdio_buffer); var stdout = fs.File.stdout().writerStreaming(&stdio_buffer);
try stdout.interface.print("{s}\n", .{package_hash_slice}); try stdout.interface.print("{s}\n", .{package_hash_slice});
try stdout.interface.flush(); try stdout.interface.flush();
return cleanExit(); return cleanExit();

View file

@ -17,15 +17,6 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
\\} \\}
, "Hello, world!" ++ if (@import("builtin").os.tag == .windows) "\r\n" else "\n"); , "Hello, world!" ++ if (@import("builtin").os.tag == .windows) "\r\n" else "\n");
cases.add("hello world without libc",
\\const io = @import("std").io;
\\
\\pub fn main() void {
\\ const stdout = io.getStdOut().writer();
\\ stdout.print("Hello, world!\n{d:4} {x:3} {c}\n", .{@as(u32, 12), @as(u16, 0x12), @as(u8, 'a')}) catch unreachable;
\\}
, "Hello, world!\n 12 12 a\n");
cases.addC("number literals", cases.addC("number literals",
\\const std = @import("std"); \\const std = @import("std");
\\const builtin = @import("builtin"); \\const builtin = @import("builtin");
@ -158,24 +149,6 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
\\ \\
); );
cases.add("order-independent declarations",
\\const io = @import("std").io;
\\const z = io.stdin_fileno;
\\const x : @TypeOf(y) = 1234;
\\const y : u16 = 5678;
\\pub fn main() void {
\\ var x_local : i32 = print_ok(x);
\\ _ = &x_local;
\\}
\\fn print_ok(val: @TypeOf(x)) @TypeOf(foo) {
\\ _ = val;
\\ const stdout = io.getStdOut().writer();
\\ stdout.print("OK\n", .{}) catch unreachable;
\\ return 0;
\\}
\\const foo : i32 = 0;
, "OK\n");
cases.addC("expose function pointer to C land", cases.addC("expose function pointer to C land",
\\const c = @cImport(@cInclude("stdlib.h")); \\const c = @cImport(@cInclude("stdlib.h"));
\\ \\
@ -236,267 +209,11 @@ pub fn addCases(cases: *tests.CompareOutputContext) void {
\\} \\}
, "3.25\n3\n3.00\n-0.40\n"); , "3.25\n3\n3.00\n-0.40\n");
cases.add("same named methods in incomplete struct", cases.add("valid carriage return example", "const std = @import(\"std\");\r\n" ++ // Testing CRLF line endings are valid
\\const io = @import("std").io;
\\
\\const Foo = struct {
\\ field1: Bar,
\\
\\ fn method(a: *const Foo) bool {
\\ _ = a;
\\ return true;
\\ }
\\};
\\
\\const Bar = struct {
\\ field2: i32,
\\
\\ fn method(b: *const Bar) bool {
\\ _ = b;
\\ return true;
\\ }
\\};
\\
\\pub fn main() void {
\\ const bar = Bar {.field2 = 13,};
\\ const foo = Foo {.field1 = bar,};
\\ const stdout = io.getStdOut().writer();
\\ if (!foo.method()) {
\\ stdout.print("BAD\n", .{}) catch unreachable;
\\ }
\\ if (!bar.method()) {
\\ stdout.print("BAD\n", .{}) catch unreachable;
\\ }
\\ stdout.print("OK\n", .{}) catch unreachable;
\\}
, "OK\n");
cases.add("defer with only fallthrough",
\\const io = @import("std").io;
\\pub fn main() void {
\\ const stdout = io.getStdOut().writer();
\\ stdout.print("before\n", .{}) catch unreachable;
\\ defer stdout.print("defer1\n", .{}) catch unreachable;
\\ defer stdout.print("defer2\n", .{}) catch unreachable;
\\ defer stdout.print("defer3\n", .{}) catch unreachable;
\\ stdout.print("after\n", .{}) catch unreachable;
\\}
, "before\nafter\ndefer3\ndefer2\ndefer1\n");
cases.add("defer with return",
\\const io = @import("std").io;
\\const os = @import("std").os;
\\pub fn main() void {
\\ const stdout = io.getStdOut().writer();
\\ stdout.print("before\n", .{}) catch unreachable;
\\ defer stdout.print("defer1\n", .{}) catch unreachable;
\\ defer stdout.print("defer2\n", .{}) catch unreachable;
\\ var gpa: @import("std").heap.GeneralPurposeAllocator(.{}) = .init;
\\ defer _ = gpa.deinit();
\\ var arena = @import("std").heap.ArenaAllocator.init(gpa.allocator());
\\ defer arena.deinit();
\\ var args_it = @import("std").process.argsWithAllocator(arena.allocator()) catch unreachable;
\\ if (args_it.skip() and !args_it.skip()) return;
\\ defer stdout.print("defer3\n", .{}) catch unreachable;
\\ stdout.print("after\n", .{}) catch unreachable;
\\}
, "before\ndefer2\ndefer1\n");
cases.add("errdefer and it fails",
\\const io = @import("std").io;
\\pub fn main() void {
\\ do_test() catch return;
\\}
\\fn do_test() !void {
\\ const stdout = io.getStdOut().writer();
\\ stdout.print("before\n", .{}) catch unreachable;
\\ defer stdout.print("defer1\n", .{}) catch unreachable;
\\ errdefer stdout.print("deferErr\n", .{}) catch unreachable;
\\ try its_gonna_fail();
\\ defer stdout.print("defer3\n", .{}) catch unreachable;
\\ stdout.print("after\n", .{}) catch unreachable;
\\}
\\fn its_gonna_fail() !void {
\\ return error.IToldYouItWouldFail;
\\}
, "before\ndeferErr\ndefer1\n");
cases.add("errdefer and it passes",
\\const io = @import("std").io;
\\pub fn main() void {
\\ do_test() catch return;
\\}
\\fn do_test() !void {
\\ const stdout = io.getStdOut().writer();
\\ stdout.print("before\n", .{}) catch unreachable;
\\ defer stdout.print("defer1\n", .{}) catch unreachable;
\\ errdefer stdout.print("deferErr\n", .{}) catch unreachable;
\\ try its_gonna_pass();
\\ defer stdout.print("defer3\n", .{}) catch unreachable;
\\ stdout.print("after\n", .{}) catch unreachable;
\\}
\\fn its_gonna_pass() anyerror!void { }
, "before\nafter\ndefer3\ndefer1\n");
cases.addCase(x: {
var tc = cases.create("@embedFile",
\\const foo_txt = @embedFile("foo.txt");
\\const io = @import("std").io;
\\
\\pub fn main() void {
\\ const stdout = io.getStdOut().writer();
\\ stdout.print(foo_txt, .{}) catch unreachable;
\\}
, "1234\nabcd\n");
tc.addSourceFile("foo.txt", "1234\nabcd\n");
break :x tc;
});
cases.addCase(x: {
var tc = cases.create("parsing args",
\\const std = @import("std");
\\const io = std.io;
\\const os = std.os;
\\
\\pub fn main() !void {
\\ var gpa: std.heap.GeneralPurposeAllocator(.{}) = .init;
\\ defer _ = gpa.deinit();
\\ var arena = std.heap.ArenaAllocator.init(gpa.allocator());
\\ defer arena.deinit();
\\ var args_it = try std.process.argsWithAllocator(arena.allocator());
\\ const stdout = io.getStdOut().writer();
\\ var index: usize = 0;
\\ _ = args_it.skip();
\\ while (args_it.next()) |arg| : (index += 1) {
\\ try stdout.print("{}: {s}\n", .{index, arg});
\\ }
\\}
,
\\0: first arg
\\1: 'a' 'b' \
\\2: bare
\\3: ba""re
\\4: "
\\5: last arg
\\
);
tc.setCommandLineArgs(&[_][]const u8{
"first arg",
"'a' 'b' \\",
"bare",
"ba\"\"re",
"\"",
"last arg",
});
break :x tc;
});
cases.addCase(x: {
var tc = cases.create("parsing args new API",
\\const std = @import("std");
\\const io = std.io;
\\const os = std.os;
\\
\\pub fn main() !void {
\\ var gpa: std.heap.GeneralPurposeAllocator(.{}) = .init;
\\ defer _ = gpa.deinit();
\\ var arena = std.heap.ArenaAllocator.init(gpa.allocator());
\\ defer arena.deinit();
\\ var args_it = try std.process.argsWithAllocator(arena.allocator());
\\ const stdout = io.getStdOut().writer();
\\ var index: usize = 0;
\\ _ = args_it.skip();
\\ while (args_it.next()) |arg| : (index += 1) {
\\ try stdout.print("{}: {s}\n", .{index, arg});
\\ }
\\}
,
\\0: first arg
\\1: 'a' 'b' \
\\2: bare
\\3: ba""re
\\4: "
\\5: last arg
\\
);
tc.setCommandLineArgs(&[_][]const u8{
"first arg",
"'a' 'b' \\",
"bare",
"ba\"\"re",
"\"",
"last arg",
});
break :x tc;
});
// It is required to override the log function in order to print to stdout instead of stderr
cases.add("std.log per scope log level override",
\\const std = @import("std");
\\
\\pub const std_options: std.Options = .{
\\ .log_level = .debug,
\\
\\ .log_scope_levels = &.{
\\ .{ .scope = .a, .level = .warn },
\\ .{ .scope = .c, .level = .err },
\\ },
\\ .logFn = log,
\\};
\\
\\const loga = std.log.scoped(.a);
\\const logb = std.log.scoped(.b);
\\const logc = std.log.scoped(.c);
\\
\\pub fn main() !void {
\\ loga.debug("", .{});
\\ logb.debug("", .{});
\\ logc.debug("", .{});
\\
\\ loga.info("", .{});
\\ logb.info("", .{});
\\ logc.info("", .{});
\\
\\ loga.warn("", .{});
\\ logb.warn("", .{});
\\ logc.warn("", .{});
\\
\\ loga.err("", .{});
\\ logb.err("", .{});
\\ logc.err("", .{});
\\}
\\pub fn log(
\\ comptime level: std.log.Level,
\\ comptime scope: @TypeOf(.EnumLiteral),
\\ comptime format: []const u8,
\\ args: anytype,
\\) void {
\\ const level_txt = comptime level.asText();
\\ const prefix2 = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "):";
\\ const stdout = std.io.getStdOut().writer();
\\ nosuspend stdout.print(level_txt ++ prefix2 ++ format ++ "\n", args) catch return;
\\}
,
\\debug(b):
\\info(b):
\\warning(a):
\\warning(b):
\\error(a):
\\error(b):
\\error(c):
\\
);
cases.add("valid carriage return example", "const io = @import(\"std\").io;\r\n" ++ // Testing CRLF line endings are valid
"\r\n" ++ "\r\n" ++
"pub \r fn main() void {\r\n" ++ // Testing isolated carriage return as whitespace is valid "pub \r fn main() void {\r\n" ++ // Testing isolated carriage return as whitespace is valid
" const stdout = io.getStdOut().writer();\r\n" ++ " var file_writer = std.fs.File.stdout().writerStreaming(&.{});\r\n" ++
" const stdout = &file_writer.interface;\r\n" ++
" stdout.print(\\\\A Multiline\r\n" ++ // testing CRLF at end of multiline string line is valid and normalises to \n in the output " stdout.print(\\\\A Multiline\r\n" ++ // testing CRLF at end of multiline string line is valid and normalises to \n in the output
" \\\\String\r\n" ++ " \\\\String\r\n" ++
" , .{}) catch unreachable;\r\n" ++ " , .{}) catch unreachable;\r\n" ++

View file

@ -6,7 +6,7 @@
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(foo); try std.fs.File.stdout().writeAll(foo);
} }
const foo = "good morning\n"; const foo = "good morning\n";
#expect_stdout="good morning\n" #expect_stdout="good morning\n"
@ -15,7 +15,7 @@ const foo = "good morning\n";
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(foo); try std.fs.File.stdout().writeAll(foo);
} }
const foo = "good morning\n"; const foo = "good morning\n";
const bar = "good evening\n"; const bar = "good evening\n";
@ -25,7 +25,7 @@ const bar = "good evening\n";
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(bar); try std.fs.File.stdout().writeAll(bar);
} }
const foo = "good morning\n"; const foo = "good morning\n";
const bar = "good evening\n"; const bar = "good evening\n";
@ -35,17 +35,17 @@ const bar = "good evening\n";
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(qux); try std.fs.File.stdout().writeAll(qux);
} }
const foo = "good morning\n"; const foo = "good morning\n";
const bar = "good evening\n"; const bar = "good evening\n";
#expect_error=main.zig:3:37: error: use of undeclared identifier 'qux' #expect_error=main.zig:3:39: error: use of undeclared identifier 'qux'
#update=add missing declaration #update=add missing declaration
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(qux); try std.fs.File.stdout().writeAll(qux);
} }
const foo = "good morning\n"; const foo = "good morning\n";
const bar = "good evening\n"; const bar = "good evening\n";
@ -56,7 +56,7 @@ const qux = "good night\n";
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(qux); try std.fs.File.stdout().writeAll(qux);
} }
const qux = "good night\n"; const qux = "good night\n";
#expect_stdout="good night\n" #expect_stdout="good night\n"

View file

@ -6,7 +6,7 @@
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(@This().foo); try std.fs.File.stdout().writeAll(@This().foo);
} }
const foo = "good morning\n"; const foo = "good morning\n";
#expect_stdout="good morning\n" #expect_stdout="good morning\n"
@ -15,7 +15,7 @@ const foo = "good morning\n";
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(@This().foo); try std.fs.File.stdout().writeAll(@This().foo);
} }
const foo = "good morning\n"; const foo = "good morning\n";
const bar = "good evening\n"; const bar = "good evening\n";
@ -25,7 +25,7 @@ const bar = "good evening\n";
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(@This().bar); try std.fs.File.stdout().writeAll(@This().bar);
} }
const foo = "good morning\n"; const foo = "good morning\n";
const bar = "good evening\n"; const bar = "good evening\n";
@ -35,18 +35,18 @@ const bar = "good evening\n";
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(@This().qux); try std.fs.File.stdout().writeAll(@This().qux);
} }
const foo = "good morning\n"; const foo = "good morning\n";
const bar = "good evening\n"; const bar = "good evening\n";
#expect_error=main.zig:3:44: error: root source file struct 'main' has no member named 'qux' #expect_error=main.zig:3:46: error: root source file struct 'main' has no member named 'qux'
#expect_error=main.zig:1:1: note: struct declared here #expect_error=main.zig:1:1: note: struct declared here
#update=add missing declaration #update=add missing declaration
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(@This().qux); try std.fs.File.stdout().writeAll(@This().qux);
} }
const foo = "good morning\n"; const foo = "good morning\n";
const bar = "good evening\n"; const bar = "good evening\n";
@ -57,7 +57,7 @@ const qux = "good night\n";
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(@This().qux); try std.fs.File.stdout().writeAll(@This().qux);
} }
const qux = "good night\n"; const qux = "good night\n";
#expect_stdout="good night\n" #expect_stdout="good night\n"

View file

@ -7,7 +7,7 @@
#file=main.zig #file=main.zig
pub fn main() !void { pub fn main() !void {
_ = @import("foo.zig"); _ = @import("foo.zig");
try std.io.getStdOut().writeAll("success\n"); try std.fs.File.stdout().writeAll("success\n");
} }
const std = @import("std"); const std = @import("std");
#file=foo.zig #file=foo.zig
@ -29,7 +29,7 @@ comptime {
#file=main.zig #file=main.zig
pub fn main() !void { pub fn main() !void {
//_ = @import("foo.zig"); //_ = @import("foo.zig");
try std.io.getStdOut().writeAll("success\n"); try std.fs.File.stdout().writeAll("success\n");
} }
const std = @import("std"); const std = @import("std");
#expect_stdout="success\n" #expect_stdout="success\n"

View file

@ -7,7 +7,7 @@
const std = @import("std"); const std = @import("std");
const string = @embedFile("string.txt"); const string = @embedFile("string.txt");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(string); try std.fs.File.stdout().writeAll(string);
} }
#file=string.txt #file=string.txt
Hello, World! Hello, World!
@ -27,7 +27,7 @@ Hello again, World!
const std = @import("std"); const std = @import("std");
const string = @embedFile("string.txt"); const string = @embedFile("string.txt");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll("a hardcoded string\n"); try std.fs.File.stdout().writeAll("a hardcoded string\n");
} }
#expect_stdout="a hardcoded string\n" #expect_stdout="a hardcoded string\n"
@ -36,7 +36,7 @@ pub fn main() !void {
const std = @import("std"); const std = @import("std");
const string = @embedFile("string.txt"); const string = @embedFile("string.txt");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(string); try std.fs.File.stdout().writeAll(string);
} }
#expect_error=main.zig:2:27: error: unable to open 'string.txt': FileNotFound #expect_error=main.zig:2:27: error: unable to open 'string.txt': FileNotFound

View file

@ -14,7 +14,8 @@ const Foo = enum(Tag) {
pub fn main() !void { pub fn main() !void {
var val: Foo = undefined; var val: Foo = undefined;
val = .a; val = .a;
try std.io.getStdOut().writer().print("{s}\n", .{@tagName(val)}); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
try stdout_writer.interface.print("{s}\n", .{@tagName(val)});
} }
const std = @import("std"); const std = @import("std");
#expect_stdout="a\n" #expect_stdout="a\n"
@ -31,7 +32,8 @@ const Foo = enum(Tag) {
pub fn main() !void { pub fn main() !void {
var val: Foo = undefined; var val: Foo = undefined;
val = .a; val = .a;
try std.io.getStdOut().writer().print("{s}\n", .{@tagName(val)}); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
try stdout_writer.interface.print("{s}\n", .{@tagName(val)});
} }
comptime { comptime {
// These can't be true at the same time; analysis should stop as soon as it sees `Foo` // These can't be true at the same time; analysis should stop as soon as it sees `Foo`
@ -53,7 +55,8 @@ const Foo = enum(Tag) {
pub fn main() !void { pub fn main() !void {
var val: Foo = undefined; var val: Foo = undefined;
val = .a; val = .a;
try std.io.getStdOut().writer().print("{s}\n", .{@tagName(val)}); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
try stdout_writer.interface.print("{s}\n", .{@tagName(val)});
} }
const std = @import("std"); const std = @import("std");
#expect_stdout="a\n" #expect_stdout="a\n"

View file

@ -16,7 +16,8 @@ pub fn main() !void {
extern const bar: u32; extern const bar: u32;
}; };
S.foo(); S.foo();
try std.io.getStdOut().writer().print("{}\n", .{S.bar}); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
try stdout_writer.interface.print("{}\n", .{S.bar});
} }
const std = @import("std"); const std = @import("std");
#expect_stdout="123\n" #expect_stdout="123\n"
@ -37,7 +38,8 @@ pub fn main() !void {
extern const other: u32; extern const other: u32;
}; };
S.foo(); S.foo();
try std.io.getStdOut().writer().print("{} {}\n", .{ S.bar, S.other }); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
try stdout_writer.interface.print("{} {}\n", .{ S.bar, S.other });
} }
const std = @import("std"); const std = @import("std");
#expect_error=main.zig:6:5: error: exported symbol collision: foo #expect_error=main.zig:6:5: error: exported symbol collision: foo
@ -59,7 +61,8 @@ pub fn main() !void {
extern const other: u32; extern const other: u32;
}; };
S.foo(); S.foo();
try std.io.getStdOut().writer().print("{} {}\n", .{ S.bar, S.other }); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
try stdout_writer.interface.print("{} {}\n", .{ S.bar, S.other });
} }
const std = @import("std"); const std = @import("std");
#expect_stdout="123 456\n" #expect_stdout="123 456\n"
@ -83,7 +86,8 @@ pub fn main() !void {
extern const other: u32; extern const other: u32;
}; };
S.foo(); S.foo();
try std.io.getStdOut().writer().print("{} {}\n", .{ S.bar, S.other }); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
try stdout_writer.interface.print("{} {}\n", .{ S.bar, S.other });
} }
const std = @import("std"); const std = @import("std");
#expect_stdout="123 456\n" #expect_stdout="123 456\n"
@ -128,7 +132,8 @@ pub fn main() !void {
extern const other: u32; extern const other: u32;
}; };
S.foo(); S.foo();
try std.io.getStdOut().writer().print("{} {}\n", .{ S.bar, S.other }); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
try stdout_writer.interface.print("{} {}\n", .{ S.bar, S.other });
} }
const std = @import("std"); const std = @import("std");
#expect_stdout="123 456\n" #expect_stdout="123 456\n"
@ -152,7 +157,8 @@ pub fn main() !void {
extern const other: u32; extern const other: u32;
}; };
S.foo(); S.foo();
try std.io.getStdOut().writer().print("{} {}\n", .{ S.bar, S.other }); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
try stdout_writer.interface.print("{} {}\n", .{ S.bar, S.other });
} }
const std = @import("std"); const std = @import("std");
#expect_error=main.zig:5:5: error: exported symbol collision: bar #expect_error=main.zig:5:5: error: exported symbol collision: bar

View file

@ -7,7 +7,8 @@ pub fn main() !void {
try foo(123); try foo(123);
} }
fn foo(x: u8) !void { fn foo(x: u8) !void {
return std.io.getStdOut().writer().print("{d}\n", .{x}); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
return stdout_writer.interface.print("{d}\n", .{x});
} }
const std = @import("std"); const std = @import("std");
#expect_stdout="123\n" #expect_stdout="123\n"
@ -18,7 +19,8 @@ pub fn main() !void {
try foo(123); try foo(123);
} }
fn foo(x: i64) !void { fn foo(x: i64) !void {
return std.io.getStdOut().writer().print("{d}\n", .{x}); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
return stdout_writer.interface.print("{d}\n", .{x});
} }
const std = @import("std"); const std = @import("std");
#expect_stdout="123\n" #expect_stdout="123\n"
@ -29,7 +31,8 @@ pub fn main() !void {
try foo(-42); try foo(-42);
} }
fn foo(x: i64) !void { fn foo(x: i64) !void {
return std.io.getStdOut().writer().print("{d}\n", .{x}); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
return stdout_writer.interface.print("{d}\n", .{x});
} }
const std = @import("std"); const std = @import("std");
#expect_stdout="-42\n" #expect_stdout="-42\n"

View file

@ -6,7 +6,7 @@ const std = @import("std");
fn Printer(message: []const u8) type { fn Printer(message: []const u8) type {
return struct { return struct {
fn print() !void { fn print() !void {
try std.io.getStdOut().writeAll(message); try std.fs.File.stdout().writeAll(message);
} }
}; };
} }
@ -22,7 +22,7 @@ const std = @import("std");
fn Printer(message: []const u8) type { fn Printer(message: []const u8) type {
return struct { return struct {
fn print() !void { fn print() !void {
try std.io.getStdOut().writeAll(message); try std.fs.File.stdout().writeAll(message);
} }
}; };
} }

View file

@ -4,7 +4,7 @@
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll("foo\n"); try std.fs.File.stdout().writeAll("foo\n");
} }
#expect_stdout="foo\n" #expect_stdout="foo\n"
#update=change line number #update=change line number
@ -12,6 +12,6 @@ pub fn main() !void {
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll("foo\n"); try std.fs.File.stdout().writeAll("foo\n");
} }
#expect_stdout="foo\n" #expect_stdout="foo\n"

View file

@ -11,7 +11,8 @@ pub fn main() !u8 {
} }
pub const panic = std.debug.FullPanic(myPanic); pub const panic = std.debug.FullPanic(myPanic);
fn myPanic(msg: []const u8, _: ?usize) noreturn { fn myPanic(msg: []const u8, _: ?usize) noreturn {
std.io.getStdOut().writer().print("panic message: {s}\n", .{msg}) catch {}; var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
stdout_writer.interface.print("panic message: {s}\n", .{msg}) catch {};
std.process.exit(0); std.process.exit(0);
} }
const std = @import("std"); const std = @import("std");
@ -27,7 +28,8 @@ pub fn main() !u8 {
} }
pub const panic = std.debug.FullPanic(myPanic); pub const panic = std.debug.FullPanic(myPanic);
fn myPanic(msg: []const u8, _: ?usize) noreturn { fn myPanic(msg: []const u8, _: ?usize) noreturn {
std.io.getStdOut().writer().print("new panic message: {s}\n", .{msg}) catch {}; var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
stdout_writer.interface.print("new panic message: {s}\n", .{msg}) catch {};
std.process.exit(0); std.process.exit(0);
} }
const std = @import("std"); const std = @import("std");
@ -43,7 +45,8 @@ pub fn main() !u8 {
} }
pub const panic = std.debug.FullPanic(myPanicNew); pub const panic = std.debug.FullPanic(myPanicNew);
fn myPanicNew(msg: []const u8, _: ?usize) noreturn { fn myPanicNew(msg: []const u8, _: ?usize) noreturn {
std.io.getStdOut().writer().print("third panic message: {s}\n", .{msg}) catch {}; var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
stdout_writer.interface.print("third panic message: {s}\n", .{msg}) catch {};
std.process.exit(0); std.process.exit(0);
} }
const std = @import("std"); const std = @import("std");

View file

@ -41,7 +41,8 @@ pub const panic = struct {
pub const noreturnReturned = no_panic.noreturnReturned; pub const noreturnReturned = no_panic.noreturnReturned;
}; };
fn myPanic(msg: []const u8, _: ?usize) noreturn { fn myPanic(msg: []const u8, _: ?usize) noreturn {
std.io.getStdOut().writer().print("panic message: {s}\n", .{msg}) catch {}; var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
stdout_writer.interface.print("panic message: {s}\n", .{msg}) catch {};
std.process.exit(0); std.process.exit(0);
} }
const std = @import("std"); const std = @import("std");
@ -87,7 +88,8 @@ pub const panic = struct {
pub const noreturnReturned = no_panic.noreturnReturned; pub const noreturnReturned = no_panic.noreturnReturned;
}; };
fn myPanic(msg: []const u8, _: ?usize) noreturn { fn myPanic(msg: []const u8, _: ?usize) noreturn {
std.io.getStdOut().writer().print("new panic message: {s}\n", .{msg}) catch {}; var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
stdout_writer.interface.print("new panic message: {s}\n", .{msg}) catch {};
std.process.exit(0); std.process.exit(0);
} }
const std = @import("std"); const std = @import("std");
@ -133,7 +135,8 @@ pub const panic = struct {
pub const noreturnReturned = no_panic.noreturnReturned; pub const noreturnReturned = no_panic.noreturnReturned;
}; };
fn myPanicNew(msg: []const u8, _: ?usize) noreturn { fn myPanicNew(msg: []const u8, _: ?usize) noreturn {
std.io.getStdOut().writer().print("third panic message: {s}\n", .{msg}) catch {}; var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
stdout_writer.interface.print("third panic message: {s}\n", .{msg}) catch {};
std.process.exit(0); std.process.exit(0);
} }
const std = @import("std"); const std = @import("std");

View file

@ -8,7 +8,8 @@ pub fn main() !void {
try foo(0x1300); try foo(0x1300);
} }
fn foo(x: u16) !void { fn foo(x: u16) !void {
try std.io.getStdOut().writer().print("0x{x}\n", .{x << 4}); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
try stdout_writer.interface.print("0x{x}\n", .{x << 4});
} }
const std = @import("std"); const std = @import("std");
#expect_stdout="0x3000\n" #expect_stdout="0x3000\n"
@ -18,7 +19,8 @@ pub fn main() !void {
try foo(0x1300); try foo(0x1300);
} }
fn foo(x: u16) !void { fn foo(x: u16) !void {
try std.io.getStdOut().writer().print("0x{x}\n", .{x >> 4}); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
try stdout_writer.interface.print("0x{x}\n", .{x >> 4});
} }
const std = @import("std"); const std = @import("std");
#expect_stdout="0x130\n" #expect_stdout="0x130\n"

View file

@ -10,7 +10,8 @@ pub fn main() !void {
try foo(&val); try foo(&val);
} }
fn foo(val: *const S) !void { fn foo(val: *const S) !void {
try std.io.getStdOut().writer().print( var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
try stdout_writer.interface.print(
"{d} {d}\n", "{d} {d}\n",
.{ val.x, val.y }, .{ val.x, val.y },
); );
@ -26,7 +27,8 @@ pub fn main() !void {
try foo(&val); try foo(&val);
} }
fn foo(val: *const S) !void { fn foo(val: *const S) !void {
try std.io.getStdOut().writer().print( var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
try stdout_writer.interface.print(
"{d} {d}\n", "{d} {d}\n",
.{ val.x, val.y }, .{ val.x, val.y },
); );
@ -42,7 +44,8 @@ pub fn main() !void {
try foo(&val); try foo(&val);
} }
fn foo(val: *const S) !void { fn foo(val: *const S) !void {
try std.io.getStdOut().writer().print( var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
try stdout_writer.interface.print(
"{d} {d}\n", "{d} {d}\n",
.{ val.x, val.y }, .{ val.x, val.y },
); );

View file

@ -7,7 +7,7 @@
const std = @import("std"); const std = @import("std");
const message: []const u8 = @import("message.zon"); const message: []const u8 = @import("message.zon");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(message); try std.fs.File.stdout().writeAll(message);
} }
#file=message.zon #file=message.zon
"Hello, World!\n" "Hello, World!\n"
@ -28,7 +28,7 @@ pub fn main() !void {
const std = @import("std"); const std = @import("std");
const message: []const u8 = @import("message.zon"); const message: []const u8 = @import("message.zon");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll("a hardcoded string\n"); try std.fs.File.stdout().writeAll("a hardcoded string\n");
} }
#expect_error=message.zon:1:1: error: unable to load 'message.zon': FileNotFound #expect_error=message.zon:1:1: error: unable to load 'message.zon': FileNotFound
#expect_error=main.zig:2:37: note: file imported here #expect_error=main.zig:2:37: note: file imported here
@ -43,6 +43,6 @@ pub fn main() !void {
const std = @import("std"); const std = @import("std");
const message: []const u8 = @import("message.zon"); const message: []const u8 = @import("message.zon");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(message); try std.fs.File.stdout().writeAll(message);
} }
#expect_stdout="We're back, World!\n" #expect_stdout="We're back, World!\n"

View file

@ -6,7 +6,7 @@
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(@import("foo.zon").message); try std.fs.File.stdout().writeAll(@import("foo.zon").message);
} }
#file=foo.zon #file=foo.zon
.{ .{

View file

@ -7,7 +7,7 @@
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll("Hello, World!\n"); try std.fs.File.stdout().writeAll("Hello, World!\n");
} }
#expect_stdout="Hello, World!\n" #expect_stdout="Hello, World!\n"
@ -15,7 +15,7 @@ pub fn main() !void {
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll("Hello, World!\n"); try std.fs.File.stdout().writeAll("Hello, World!\n");
@compileLog("this is a log"); @compileLog("this is a log");
} }
#expect_error=main.zig:4:5: error: found compile log statement #expect_error=main.zig:4:5: error: found compile log statement
@ -25,6 +25,6 @@ pub fn main() !void {
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll("Hello, World!\n"); try std.fs.File.stdout().writeAll("Hello, World!\n");
} }
#expect_stdout="Hello, World!\n" #expect_stdout="Hello, World!\n"

View file

@ -9,28 +9,28 @@ pub fn main() !void {
} }
#file=foo.zig #file=foo.zig
pub fn hello() !void { pub fn hello() !void {
try std.io.getStdOut().writeAll("Hello, World!\n"); try std.fs.File.stdout().writeAll("Hello, World!\n");
} }
#expect_error=foo.zig:2:9: error: use of undeclared identifier 'std' #expect_error=foo.zig:2:9: error: use of undeclared identifier 'std'
#update=fix the error #update=fix the error
#file=foo.zig #file=foo.zig
const std = @import("std"); const std = @import("std");
pub fn hello() !void { pub fn hello() !void {
try std.io.getStdOut().writeAll("Hello, World!\n"); try std.fs.File.stdout().writeAll("Hello, World!\n");
} }
#expect_stdout="Hello, World!\n" #expect_stdout="Hello, World!\n"
#update=add new error #update=add new error
#file=foo.zig #file=foo.zig
const std = @import("std"); const std = @import("std");
pub fn hello() !void { pub fn hello() !void {
try std.io.getStdOut().writeAll(hello_str); try std.fs.File.stdout().writeAll(hello_str);
} }
#expect_error=foo.zig:3:37: error: use of undeclared identifier 'hello_str' #expect_error=foo.zig:3:39: error: use of undeclared identifier 'hello_str'
#update=fix the new error #update=fix the new error
#file=foo.zig #file=foo.zig
const std = @import("std"); const std = @import("std");
const hello_str = "Hello, World! Again!\n"; const hello_str = "Hello, World! Again!\n";
pub fn hello() !void { pub fn hello() !void {
try std.io.getStdOut().writeAll(hello_str); try std.fs.File.stdout().writeAll(hello_str);
} }
#expect_stdout="Hello, World! Again!\n" #expect_stdout="Hello, World! Again!\n"

View file

@ -7,7 +7,7 @@ pub fn main() !void {
try foo(); try foo();
} }
fn foo() !void { fn foo() !void {
try std.io.getStdOut().writer().writeAll("Hello, World!\n"); try std.fs.File.stdout().writeAll("Hello, World!\n");
} }
const std = @import("std"); const std = @import("std");
#expect_stdout="Hello, World!\n" #expect_stdout="Hello, World!\n"
@ -18,7 +18,7 @@ pub fn main() !void {
try foo(); try foo();
} }
inline fn foo() !void { inline fn foo() !void {
try std.io.getStdOut().writer().writeAll("Hello, World!\n"); try std.fs.File.stdout().writeAll("Hello, World!\n");
} }
const std = @import("std"); const std = @import("std");
#expect_stdout="Hello, World!\n" #expect_stdout="Hello, World!\n"
@ -29,7 +29,7 @@ pub fn main() !void {
try foo(); try foo();
} }
inline fn foo() !void { inline fn foo() !void {
try std.io.getStdOut().writer().writeAll("Hello, `inline` World!\n"); try std.fs.File.stdout().writeAll("Hello, `inline` World!\n");
} }
const std = @import("std"); const std = @import("std");
#expect_stdout="Hello, `inline` World!\n" #expect_stdout="Hello, `inline` World!\n"

View file

@ -6,13 +6,13 @@
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll("good morning\n"); try std.fs.File.stdout().writeAll("good morning\n");
} }
#expect_stdout="good morning\n" #expect_stdout="good morning\n"
#update=change the string #update=change the string
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll("おはようございます\n"); try std.fs.File.stdout().writeAll("おはようございます\n");
} }
#expect_stdout="おはようございます\n" #expect_stdout="おはようございます\n"

View file

@ -11,7 +11,7 @@ pub fn main() !void {
#file=foo.zig #file=foo.zig
const std = @import("std"); const std = @import("std");
fn hello() !void { fn hello() !void {
try std.io.getStdOut().writeAll("Hello, World!\n"); try std.fs.File.stdout().writeAll("Hello, World!\n");
} }
#expect_error=main.zig:3:12: error: 'hello' is not marked 'pub' #expect_error=main.zig:3:12: error: 'hello' is not marked 'pub'
#expect_error=foo.zig:2:1: note: declared here #expect_error=foo.zig:2:1: note: declared here
@ -20,6 +20,6 @@ fn hello() !void {
#file=foo.zig #file=foo.zig
const std = @import("std"); const std = @import("std");
pub fn hello() !void { pub fn hello() !void {
try std.io.getStdOut().writeAll("Hello, World!\n"); try std.fs.File.stdout().writeAll("Hello, World!\n");
} }
#expect_stdout="Hello, World!\n" #expect_stdout="Hello, World!\n"

View file

@ -7,7 +7,7 @@
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
const str = getStr(); const str = getStr();
try std.io.getStdOut().writeAll(str); try std.fs.File.stdout().writeAll(str);
} }
inline fn getStr() []const u8 { inline fn getStr() []const u8 {
return "foo\n"; return "foo\n";
@ -18,7 +18,7 @@ inline fn getStr() []const u8 {
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
const str = getStr(); const str = getStr();
try std.io.getStdOut().writeAll(str); try std.fs.File.stdout().writeAll(str);
} }
inline fn getStr() []const u8 { inline fn getStr() []const u8 {
return "bar\n"; return "bar\n";

View file

@ -6,23 +6,9 @@
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writer().print("{d} {d}\n", .{ foo(), bar() }); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
try stdout_writer.interface.print("{d} {d}\n", .{ foo(), bar() });
} }
fn foo() u32 {
return @src().line;
}
fn bar() u32 {
return 123;
}
#expect_stdout="6 123\n"
#update=add newline
#file=main.zig
const std = @import("std");
pub fn main() !void {
try std.io.getStdOut().writer().print("{d} {d}\n", .{ foo(), bar() });
}
fn foo() u32 { fn foo() u32 {
return @src().line; return @src().line;
} }
@ -30,3 +16,19 @@ fn bar() u32 {
return 123; return 123;
} }
#expect_stdout="7 123\n" #expect_stdout="7 123\n"
#update=add newline
#file=main.zig
const std = @import("std");
pub fn main() !void {
var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
try stdout_writer.interface.print("{d} {d}\n", .{ foo(), bar() });
}
fn foo() u32 {
return @src().line;
}
fn bar() u32 {
return 123;
}
#expect_stdout="8 123\n"

View file

@ -7,7 +7,7 @@
const std = @import("std"); const std = @import("std");
var some_enum: enum { first, second } = .first; var some_enum: enum { first, second } = .first;
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(@tagName(some_enum)); try std.fs.File.stdout().writeAll(@tagName(some_enum));
} }
#expect_stdout="first" #expect_stdout="first"
#update=no change #update=no change
@ -15,6 +15,6 @@ pub fn main() !void {
const std = @import("std"); const std = @import("std");
var some_enum: enum { first, second } = .first; var some_enum: enum { first, second } = .first;
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(@tagName(some_enum)); try std.fs.File.stdout().writeAll(@tagName(some_enum));
} }
#expect_stdout="first" #expect_stdout="first"

View file

@ -8,7 +8,7 @@ pub fn main() !void {
try foo(false); try foo(false);
} }
fn foo(recurse: bool) !void { fn foo(recurse: bool) !void {
const stdout = std.io.getStdOut().writer(); const stdout = std.fs.File.stdout();
if (recurse) return foo(true); if (recurse) return foo(true);
try stdout.writeAll("non-recursive path\n"); try stdout.writeAll("non-recursive path\n");
} }
@ -21,7 +21,7 @@ pub fn main() !void {
try foo(true); try foo(true);
} }
fn foo(recurse: bool) !void { fn foo(recurse: bool) !void {
const stdout = std.io.getStdOut().writer(); const stdout = std.fs.File.stdout();
if (recurse) return stdout.writeAll("x==1\n"); if (recurse) return stdout.writeAll("x==1\n");
try stdout.writeAll("non-recursive path\n"); try stdout.writeAll("non-recursive path\n");
} }

View file

@ -9,7 +9,8 @@ const MyEnum = enum(u8) {
bar = 2, bar = 2,
}; };
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writer().print("{}\n", .{@intFromEnum(MyEnum.foo)}); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
try stdout_writer.interface.print("{}\n", .{@intFromEnum(MyEnum.foo)});
} }
const std = @import("std"); const std = @import("std");
#expect_stdout="1\n" #expect_stdout="1\n"
@ -20,8 +21,9 @@ const MyEnum = enum(u8) {
bar = 2, bar = 2,
}; };
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writer().print("{}\n", .{@intFromEnum(MyEnum.foo)}); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
try stdout_writer.interface.print("{}\n", .{@intFromEnum(MyEnum.foo)});
} }
const std = @import("std"); const std = @import("std");
#expect_error=main.zig:6:73: error: enum 'main.MyEnum' has no member named 'foo' #expect_error=main.zig:7:69: error: enum 'main.MyEnum' has no member named 'foo'
#expect_error=main.zig:1:16: note: enum declared here #expect_error=main.zig:1:16: note: enum declared here

View file

@ -6,7 +6,7 @@
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(a); try std.fs.File.stdout().writeAll(a);
} }
const a = "Hello, World!\n"; const a = "Hello, World!\n";
#expect_stdout="Hello, World!\n" #expect_stdout="Hello, World!\n"
@ -15,7 +15,7 @@ const a = "Hello, World!\n";
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(a); try std.fs.File.stdout().writeAll(a);
} }
const a = @compileError("bad a"); const a = @compileError("bad a");
#expect_error=main.zig:5:11: error: bad a #expect_error=main.zig:5:11: error: bad a
@ -24,7 +24,7 @@ const a = @compileError("bad a");
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(b); try std.fs.File.stdout().writeAll(b);
} }
const a = @compileError("bad a"); const a = @compileError("bad a");
const b = "Hi there!\n"; const b = "Hi there!\n";
@ -34,7 +34,7 @@ const b = "Hi there!\n";
#file=main.zig #file=main.zig
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll(a); try std.fs.File.stdout().writeAll(a);
} }
const a = "Back to a\n"; const a = "Back to a\n";
const b = @compileError("bad b"); const b = @compileError("bad b");

View file

@ -4,8 +4,11 @@ const std = @import("std");
var buffer: [0x1000000]u64 = [1]u64{0} ** 0x1000000; var buffer: [0x1000000]u64 = [1]u64{0} ** 0x1000000;
pub fn main() anyerror!void { pub fn main() anyerror!void {
var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
buffer[0x10] = 1; buffer[0x10] = 1;
try std.io.getStdOut().writer().print("{d}, {d}, {d}\n", .{
try stdout_writer.interface.print("{d}, {d}, {d}\n", .{
// workaround the dreaded decl_val // workaround the dreaded decl_val
(&buffer)[0], (&buffer)[0],
(&buffer)[0x10], (&buffer)[0x10],

View file

@ -1315,8 +1315,8 @@ fn testGcSectionsZig(b: *Build, opts: Options) *Step {
\\extern var live_var2: i32; \\extern var live_var2: i32;
\\extern fn live_fn2() void; \\extern fn live_fn2() void;
\\pub fn main() void { \\pub fn main() void {
\\ const stdout = std.io.getStdOut(); \\ var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
\\ stdout.deprecatedWriter().print("{d} {d}\n", .{ live_var1, live_var2 }) catch unreachable; \\ stdout_writer.interface.print("{d} {d}\n", .{ live_var1, live_var2 }) catch @panic("fail");
\\ live_fn2(); \\ live_fn2();
\\} \\}
, ,
@ -1357,8 +1357,8 @@ fn testGcSectionsZig(b: *Build, opts: Options) *Step {
\\extern var live_var2: i32; \\extern var live_var2: i32;
\\extern fn live_fn2() void; \\extern fn live_fn2() void;
\\pub fn main() void { \\pub fn main() void {
\\ const stdout = std.io.getStdOut(); \\ var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
\\ stdout.deprecatedWriter().print("{d} {d}\n", .{ live_var1, live_var2 }) catch unreachable; \\ stdout_writer.interface.print("{d} {d}\n", .{ live_var1, live_var2 }) catch @panic("fail");
\\ live_fn2(); \\ live_fn2();
\\} \\}
, ,

View file

@ -710,7 +710,7 @@ fn testHelloZig(b: *Build, opts: Options) *Step {
const exe = addExecutable(b, opts, .{ .name = "main", .zig_source_bytes = const exe = addExecutable(b, opts, .{ .name = "main", .zig_source_bytes =
\\const std = @import("std"); \\const std = @import("std");
\\pub fn main() void { \\pub fn main() void {
\\ std.io.getStdOut().writer().print("Hello world!\n", .{}) catch unreachable; \\ std.fs.File.stdout().writeAll("Hello world!\n") catch @panic("fail");
\\} \\}
}); });
@ -2365,10 +2365,11 @@ fn testTlsZig(b: *Build, opts: Options) *Step {
\\threadlocal var x: i32 = 0; \\threadlocal var x: i32 = 0;
\\threadlocal var y: i32 = -1; \\threadlocal var y: i32 = -1;
\\pub fn main() void { \\pub fn main() void {
\\ std.io.getStdOut().writer().print("{d} {d}\n", .{x, y}) catch unreachable; \\ var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
\\ stdout_writer.interface.print("{d} {d}\n", .{x, y}) catch unreachable;
\\ x -= 1; \\ x -= 1;
\\ y += 1; \\ y += 1;
\\ std.io.getStdOut().writer().print("{d} {d}\n", .{x, y}) catch unreachable; \\ stdout_writer.interface.print("{d} {d}\n", .{x, y}) catch unreachable;
\\} \\}
}); });

View file

@ -3,6 +3,6 @@ const std = @import("std");
extern const foo: u32; extern const foo: u32;
pub fn main() void { pub fn main() void {
const std_out = std.io.getStdOut(); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
std_out.writer().print("Result: {d}", .{foo}) catch {}; stdout_writer.interface.print("Result: {d}", .{foo}) catch {};
} }

View file

@ -84,5 +84,5 @@ pub fn main() !void {
break :got_result try buf.toOwnedSlice(); break :got_result try buf.toOwnedSlice();
}; };
try std.io.getStdOut().writeAll(got); try std.fs.File.stdout().writeAll(got);
} }

View file

@ -27,12 +27,12 @@ fn run(allocator: std.mem.Allocator) !void {
} }
// test stdout pipe; parent verifies // test stdout pipe; parent verifies
try std.io.getStdOut().writer().writeAll("hello from stdout"); try std.fs.File.stdout().writeAll("hello from stdout");
// test stdin pipe from parent // test stdin pipe from parent
const hello_stdin = "hello from stdin"; const hello_stdin = "hello from stdin";
var buf: [hello_stdin.len]u8 = undefined; var buf: [hello_stdin.len]u8 = undefined;
const stdin = std.io.getStdIn().reader(); const stdin: std.fs.File = .stdin();
const n = try stdin.readAll(&buf); const n = try stdin.readAll(&buf);
if (!std.mem.eql(u8, buf[0..n], hello_stdin)) { if (!std.mem.eql(u8, buf[0..n], hello_stdin)) {
testError("stdin: '{s}'; want '{s}'", .{ buf[0..n], hello_stdin }); testError("stdin: '{s}'; want '{s}'", .{ buf[0..n], hello_stdin });
@ -40,7 +40,8 @@ fn run(allocator: std.mem.Allocator) !void {
} }
fn testError(comptime fmt: []const u8, args: anytype) void { fn testError(comptime fmt: []const u8, args: anytype) void {
const stderr = std.io.getStdErr().writer(); var stderr_writer = std.fs.File.stderr().writer(&.{});
const stderr = &stderr_writer.interface;
stderr.print("CHILD TEST ERROR: ", .{}) catch {}; stderr.print("CHILD TEST ERROR: ", .{}) catch {};
stderr.print(fmt, args) catch {}; stderr.print(fmt, args) catch {};
if (fmt[fmt.len - 1] != '\n') { if (fmt[fmt.len - 1] != '\n') {

View file

@ -19,13 +19,13 @@ pub fn main() !void {
child.stderr_behavior = .Inherit; child.stderr_behavior = .Inherit;
try child.spawn(); try child.spawn();
const child_stdin = child.stdin.?; const child_stdin = child.stdin.?;
try child_stdin.writer().writeAll("hello from stdin"); // verified in child try child_stdin.writeAll("hello from stdin"); // verified in child
child_stdin.close(); child_stdin.close();
child.stdin = null; child.stdin = null;
const hello_stdout = "hello from stdout"; const hello_stdout = "hello from stdout";
var buf: [hello_stdout.len]u8 = undefined; var buf: [hello_stdout.len]u8 = undefined;
const n = try child.stdout.?.reader().readAll(&buf); const n = try child.stdout.?.deprecatedReader().readAll(&buf);
if (!std.mem.eql(u8, buf[0..n], hello_stdout)) { if (!std.mem.eql(u8, buf[0..n], hello_stdout)) {
testError("child stdout: '{s}'; want '{s}'", .{ buf[0..n], hello_stdout }); testError("child stdout: '{s}'; want '{s}'", .{ buf[0..n], hello_stdout });
} }
@ -45,7 +45,8 @@ pub fn main() !void {
var parent_test_error = false; var parent_test_error = false;
fn testError(comptime fmt: []const u8, args: anytype) void { fn testError(comptime fmt: []const u8, args: anytype) void {
const stderr = std.io.getStdErr().writer(); var stderr_writer = std.fs.File.stderr().writer(&.{});
const stderr = &stderr_writer.interface;
stderr.print("PARENT TEST ERROR: ", .{}) catch {}; stderr.print("PARENT TEST ERROR: ", .{}) catch {};
stderr.print(fmt, args) catch {}; stderr.print(fmt, args) catch {};
if (fmt[fmt.len - 1] != '\n') { if (fmt[fmt.len - 1] != '\n') {

View file

@ -10,7 +10,7 @@ pub fn main() !void {
std.posix.close(pipe[0]); std.posix.close(pipe[0]);
_ = std.posix.write(pipe[1], "a") catch |err| switch (err) { _ = std.posix.write(pipe[1], "a") catch |err| switch (err) {
error.BrokenPipe => { error.BrokenPipe => {
try std.io.getStdOut().writer().writeAll("BrokenPipe\n"); try std.fs.File.stdout().writeAll("BrokenPipe\n");
std.posix.exit(123); std.posix.exit(123);
}, },
else => |e| return e, else => |e| return e,

View file

@ -1,292 +0,0 @@
const std = @import("std");
const io = std.io;
const mem = std.mem;
const debug = std.debug;
const assert = debug.assert;
const testing = std.testing;
const ArrayList = std.ArrayList;
const maxInt = std.math.maxInt;
const Token = union(enum) {
Word: []const u8,
OpenBrace,
CloseBrace,
Comma,
Eof,
};
var gpa: std.heap.GeneralPurposeAllocator(.{}) = .init;
var global_allocator = gpa.allocator();
fn tokenize(input: []const u8) !ArrayList(Token) {
const State = enum {
Start,
Word,
};
var token_list = ArrayList(Token).init(global_allocator);
errdefer token_list.deinit();
var tok_begin: usize = undefined;
var state = State.Start;
for (input, 0..) |b, i| {
switch (state) {
.Start => switch (b) {
'a'...'z', 'A'...'Z' => {
state = State.Word;
tok_begin = i;
},
'{' => try token_list.append(Token.OpenBrace),
'}' => try token_list.append(Token.CloseBrace),
',' => try token_list.append(Token.Comma),
else => return error.InvalidInput,
},
.Word => switch (b) {
'a'...'z', 'A'...'Z' => {},
'{', '}', ',' => {
try token_list.append(Token{ .Word = input[tok_begin..i] });
switch (b) {
'{' => try token_list.append(Token.OpenBrace),
'}' => try token_list.append(Token.CloseBrace),
',' => try token_list.append(Token.Comma),
else => unreachable,
}
state = State.Start;
},
else => return error.InvalidInput,
},
}
}
switch (state) {
State.Start => {},
State.Word => try token_list.append(Token{ .Word = input[tok_begin..] }),
}
try token_list.append(Token.Eof);
return token_list;
}
const Node = union(enum) {
Scalar: []const u8,
List: ArrayList(Node),
Combine: []Node,
fn deinit(self: Node) void {
switch (self) {
.Scalar => {},
.Combine => |pair| {
pair[0].deinit();
pair[1].deinit();
global_allocator.free(pair);
},
.List => |list| {
for (list.items) |item| {
item.deinit();
}
list.deinit();
},
}
}
};
const ParseError = error{
InvalidInput,
OutOfMemory,
};
fn parse(tokens: *const ArrayList(Token), token_index: *usize) ParseError!Node {
const first_token = tokens.items[token_index.*];
token_index.* += 1;
const result_node = switch (first_token) {
.Word => |word| Node{ .Scalar = word },
.OpenBrace => blk: {
var list = ArrayList(Node).init(global_allocator);
errdefer {
for (list.items) |node| node.deinit();
list.deinit();
}
while (true) {
try list.append(try parse(tokens, token_index));
const token = tokens.items[token_index.*];
token_index.* += 1;
switch (token) {
.CloseBrace => break,
.Comma => continue,
else => return error.InvalidInput,
}
}
break :blk Node{ .List = list };
},
else => return error.InvalidInput,
};
switch (tokens.items[token_index.*]) {
.Word, .OpenBrace => {
const pair = try global_allocator.alloc(Node, 2);
errdefer global_allocator.free(pair);
pair[0] = result_node;
pair[1] = try parse(tokens, token_index);
return Node{ .Combine = pair };
},
else => return result_node,
}
}
fn expandString(input: []const u8, output: *ArrayList(u8)) !void {
const tokens = try tokenize(input);
defer tokens.deinit();
if (tokens.items.len == 1) {
return output.resize(0);
}
var token_index: usize = 0;
const root = try parse(&tokens, &token_index);
defer root.deinit();
const last_token = tokens.items[token_index];
switch (last_token) {
Token.Eof => {},
else => return error.InvalidInput,
}
var result_list = ArrayList(ArrayList(u8)).init(global_allocator);
defer {
for (result_list.items) |*buf| buf.deinit();
result_list.deinit();
}
try expandNode(root, &result_list);
try output.resize(0);
for (result_list.items, 0..) |buf, i| {
if (i != 0) {
try output.append(' ');
}
try output.appendSlice(buf.items);
}
}
const ExpandNodeError = error{OutOfMemory};
fn expandNode(node: Node, output: *ArrayList(ArrayList(u8))) ExpandNodeError!void {
assert(output.items.len == 0);
switch (node) {
.Scalar => |scalar| {
var list = ArrayList(u8).init(global_allocator);
errdefer list.deinit();
try list.appendSlice(scalar);
try output.append(list);
},
.Combine => |pair| {
const a_node = pair[0];
const b_node = pair[1];
var child_list_a = ArrayList(ArrayList(u8)).init(global_allocator);
defer {
for (child_list_a.items) |*buf| buf.deinit();
child_list_a.deinit();
}
try expandNode(a_node, &child_list_a);
var child_list_b = ArrayList(ArrayList(u8)).init(global_allocator);
defer {
for (child_list_b.items) |*buf| buf.deinit();
child_list_b.deinit();
}
try expandNode(b_node, &child_list_b);
for (child_list_a.items) |buf_a| {
for (child_list_b.items) |buf_b| {
var combined_buf = ArrayList(u8).init(global_allocator);
errdefer combined_buf.deinit();
try combined_buf.appendSlice(buf_a.items);
try combined_buf.appendSlice(buf_b.items);
try output.append(combined_buf);
}
}
},
.List => |list| {
for (list.items) |child_node| {
var child_list = ArrayList(ArrayList(u8)).init(global_allocator);
errdefer for (child_list.items) |*buf| buf.deinit();
defer child_list.deinit();
try expandNode(child_node, &child_list);
for (child_list.items) |buf| {
try output.append(buf);
}
}
},
}
}
pub fn main() !void {
defer _ = gpa.deinit();
const stdin_file = io.getStdIn();
const stdout_file = io.getStdOut();
const stdin = try stdin_file.deprecatedReader().readAllAlloc(global_allocator, std.math.maxInt(usize));
defer global_allocator.free(stdin);
var result_buf = ArrayList(u8).init(global_allocator);
defer result_buf.deinit();
try expandString(stdin, &result_buf);
try stdout_file.writeAll(result_buf.items);
}
test "invalid inputs" {
global_allocator = std.testing.allocator;
try expectError("}ABC", error.InvalidInput);
try expectError("{ABC", error.InvalidInput);
try expectError("}{", error.InvalidInput);
try expectError("{}", error.InvalidInput);
try expectError("A,B,C", error.InvalidInput);
try expectError("{A{B,C}", error.InvalidInput);
try expectError("{A,}", error.InvalidInput);
try expectError("\n", error.InvalidInput);
}
fn expectError(test_input: []const u8, expected_err: anyerror) !void {
var output_buf = ArrayList(u8).init(global_allocator);
defer output_buf.deinit();
try testing.expectError(expected_err, expandString(test_input, &output_buf));
}
test "valid inputs" {
global_allocator = std.testing.allocator;
try expectExpansion("{x,y,z}", "x y z");
try expectExpansion("{A,B}{x,y}", "Ax Ay Bx By");
try expectExpansion("{A,B{x,y}}", "A Bx By");
try expectExpansion("{ABC}", "ABC");
try expectExpansion("{A,B,C}", "A B C");
try expectExpansion("ABC", "ABC");
try expectExpansion("", "");
try expectExpansion("{A,B}{C,{x,y}}{g,h}", "ACg ACh Axg Axh Ayg Ayh BCg BCh Bxg Bxh Byg Byh");
try expectExpansion("{A,B}{C,C{x,y}}{g,h}", "ACg ACh ACxg ACxh ACyg ACyh BCg BCh BCxg BCxh BCyg BCyh");
try expectExpansion("{A,B}a", "Aa Ba");
try expectExpansion("{C,{x,y}}", "C x y");
try expectExpansion("z{C,{x,y}}", "zC zx zy");
try expectExpansion("a{b,c{d,e{f,g}}}", "ab acd acef aceg");
try expectExpansion("a{x,y}b", "axb ayb");
try expectExpansion("z{{a,b}}", "za zb");
try expectExpansion("a{b}", "ab");
}
fn expectExpansion(test_input: []const u8, expected_result: []const u8) !void {
var result = ArrayList(u8).init(global_allocator);
defer result.deinit();
expandString(test_input, &result) catch unreachable;
try testing.expectEqualSlices(u8, expected_result, result.items);
}

View file

@ -109,10 +109,6 @@ const cases = [_]Case{
//.{ //.{
// .src_path = "issue_9693/main.zig", // .src_path = "issue_9693/main.zig",
//}, //},
.{
.src_path = "brace_expansion.zig",
.is_test = true,
},
.{ .{
.src_path = "issue_7030.zig", .src_path = "issue_7030.zig",
.target = .{ .target = .{

View file

@ -1,42 +1,42 @@
const std = @import("std"); const std = @import("std");
const io = std.io; const io = std.io;
const process = std.process;
const fs = std.fs; const fs = std.fs;
const mem = std.mem; const mem = std.mem;
const warn = std.log.warn; const warn = std.log.warn;
const fatal = std.process.fatal;
pub fn main() !void { pub fn main() !void {
var arena_instance = std.heap.ArenaAllocator.init(std.heap.page_allocator); var arena_instance = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena_instance.deinit(); defer arena_instance.deinit();
const arena = arena_instance.allocator(); const arena = arena_instance.allocator();
const args = try process.argsAlloc(arena); const args = try std.process.argsAlloc(arena);
const exe = args[0]; const exe = args[0];
var catted_anything = false; var catted_anything = false;
const stdout_file = io.getStdOut(); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
const stdout = &stdout_writer.interface;
var stdin_reader = std.fs.File.stdin().reader(&.{});
const cwd = fs.cwd(); const cwd = fs.cwd();
for (args[1..]) |arg| { for (args[1..]) |arg| {
if (mem.eql(u8, arg, "-")) { if (mem.eql(u8, arg, "-")) {
catted_anything = true; catted_anything = true;
try stdout_file.writeFileAll(io.getStdIn(), .{}); _ = try stdout.sendFileAll(&stdin_reader, .unlimited);
} else if (mem.startsWith(u8, arg, "-")) { } else if (mem.startsWith(u8, arg, "-")) {
return usage(exe); return usage(exe);
} else { } else {
const file = cwd.openFile(arg, .{}) catch |err| { const file = cwd.openFile(arg, .{}) catch |err| fatal("unable to open file: {t}\n", .{err});
warn("Unable to open file: {s}\n", .{@errorName(err)});
return err;
};
defer file.close(); defer file.close();
catted_anything = true; catted_anything = true;
try stdout_file.writeFileAll(file, .{}); var file_reader = file.reader(&.{});
_ = try stdout.sendFileAll(&file_reader, .unlimited);
} }
} }
if (!catted_anything) { if (!catted_anything) {
try stdout_file.writeFileAll(io.getStdIn(), .{}); _ = try stdout.sendFileAll(&stdin_reader, .unlimited);
} }
} }

View file

@ -1,37 +1,35 @@
const builtin = @import("builtin"); const builtin = @import("builtin");
const std = @import("std"); const std = @import("std");
const io = std.io;
const fmt = std.fmt;
pub fn main() !void { pub fn main() !void {
const stdout = io.getStdOut().writer(); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
const stdin = io.getStdIn(); const out = &stdout_writer.interface;
const stdin: std.fs.File = .stdin();
try stdout.print("Welcome to the Guess Number Game in Zig.\n", .{}); try out.writeAll("Welcome to the Guess Number Game in Zig.\n");
const answer = std.crypto.random.intRangeLessThan(u8, 0, 100) + 1; const answer = std.crypto.random.intRangeLessThan(u8, 0, 100) + 1;
while (true) { while (true) {
try stdout.print("\nGuess a number between 1 and 100: ", .{}); try out.writeAll("\nGuess a number between 1 and 100: ");
var line_buf: [20]u8 = undefined; var line_buf: [20]u8 = undefined;
const amt = try stdin.read(&line_buf); const amt = try stdin.read(&line_buf);
if (amt == line_buf.len) { if (amt == line_buf.len) {
try stdout.print("Input too long.\n", .{}); try out.writeAll("Input too long.\n");
continue; continue;
} }
const line = std.mem.trimEnd(u8, line_buf[0..amt], "\r\n"); const line = std.mem.trimEnd(u8, line_buf[0..amt], "\r\n");
const guess = fmt.parseUnsigned(u8, line, 10) catch { const guess = std.fmt.parseUnsigned(u8, line, 10) catch {
try stdout.print("Invalid number.\n", .{}); try out.writeAll("Invalid number.\n");
continue; continue;
}; };
if (guess > answer) { if (guess > answer) {
try stdout.print("Guess lower.\n", .{}); try out.writeAll("Guess lower.\n");
} else if (guess < answer) { } else if (guess < answer) {
try stdout.print("Guess higher.\n", .{}); try out.writeAll("Guess higher.\n");
} else { } else {
try stdout.print("You win!\n", .{}); try out.writeAll("You win!\n");
return; return;
} }
} }

View file

@ -1,5 +1,5 @@
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
try std.io.getStdOut().writeAll("Hello, World!\n"); try std.fs.File.stdout().writeAll("Hello, World!\n");
} }

View file

@ -6,6 +6,7 @@ pub fn main() void {
const Big = @Type(.{ .@"enum" = .{ const Big = @Type(.{ .@"enum" = .{
.tag_type = u16, .tag_type = u16,
.fields = make_fields: { .fields = make_fields: {
@setEvalBranchQuota(500000);
var fields: [1001]std.builtin.Type.EnumField = undefined; var fields: [1001]std.builtin.Type.EnumField = undefined;
for (&fields, 0..) |*field, i| { for (&fields, 0..) |*field, i| {
field.* = .{ .name = std.fmt.comptimePrint("field_{d}", .{i}), .value = i }; field.* = .{ .name = std.fmt.comptimePrint("field_{d}", .{i}), .value = i };

View file

@ -5,7 +5,8 @@ pub fn main() !void {
defer arena_state.deinit(); defer arena_state.deinit();
const arena = arena_state.allocator(); const arena = arena_state.allocator();
const stdout = std.io.getStdOut().writer(); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
const stdout = &stdout_writer.interface;
var args = try std.process.argsAlloc(arena); var args = try std.process.argsAlloc(arena);
for (args[1..], 1..) |arg, i| { for (args[1..], 1..) |arg, i| {
try stdout.writeAll(arg); try stdout.writeAll(arg);

View file

@ -1,6 +1,7 @@
const std = @import("std"); const std = @import("std");
pub fn main() !void { pub fn main() !void {
const stdout = std.io.getStdOut().writer(); var stdout_writer = std.fs.File.stdout().writerStreaming(&.{});
const stdout = &stdout_writer.interface;
try stdout.writeAll("hello from exe\n"); try stdout.writeAll("hello from exe\n");
} }

View file

@ -43,8 +43,7 @@ pub fn main() !void {
while (args_it.next()) |arg| { while (args_it.next()) |arg| {
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(); try fs.File.stdout().writeAll(usage);
try stdout.writeAll(usage);
process.exit(0); process.exit(0);
} else if (mem.eql(u8, arg, "--code-dir")) { } else if (mem.eql(u8, arg, "--code-dir")) {
if (args_it.next()) |param| { if (args_it.next()) |param| {

View file

@ -44,7 +44,7 @@ pub fn main() !void {
while (args_it.next()) |arg| { while (args_it.next()) |arg| {
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 std.io.getStdOut().writeAll(usage); try std.fs.File.stdout().writeAll(usage);
process.exit(0); process.exit(0);
} else if (mem.eql(u8, arg, "-i")) { } else if (mem.eql(u8, arg, "-i")) {
opt_input = args_it.next() orelse fatal("expected parameter after -i", .{}); opt_input = args_it.next() orelse fatal("expected parameter after -i", .{});

View file

@ -48,8 +48,9 @@ pub fn main() !void {
fatal("failed to load coverage file {}: {s}", .{ cov_path, @errorName(err) }); fatal("failed to load coverage file {}: {s}", .{ cov_path, @errorName(err) });
}; };
var bw = std.io.bufferedWriter(std.io.getStdOut().writer()); var stdout_buffer: [4000]u8 = undefined;
const stdout = bw.writer(); var stdout_writer = std.fs.File.stdout().writerStreaming(&stdout_buffer);
const stdout = &stdout_writer.interface;
const header: *SeenPcsHeader = @ptrCast(cov_bytes); const header: *SeenPcsHeader = @ptrCast(cov_bytes);
try stdout.print("{any}\n", .{header.*}); try stdout.print("{any}\n", .{header.*});
@ -83,5 +84,5 @@ pub fn main() !void {
}); });
} }
try bw.flush(); try stdout.flush();
} }

View file

@ -5,6 +5,8 @@ const mem = std.mem;
const process = std.process; const process = std.process;
const assert = std.debug.assert; const assert = std.debug.assert;
const tmpDir = std.testing.tmpDir; const tmpDir = std.testing.tmpDir;
const fatal = std.process.fatal;
const info = std.log.info;
const Allocator = mem.Allocator; const Allocator = mem.Allocator;
const OsTag = std.Target.Os.Tag; const OsTag = std.Target.Os.Tag;
@ -245,19 +247,6 @@ const ArgsIterator = struct {
} }
}; };
fn info(comptime format: []const u8, args: anytype) void {
const msg = std.fmt.allocPrint(gpa, "info: " ++ format ++ "\n", args) catch return;
std.io.getStdOut().writeAll(msg) catch {};
}
fn fatal(comptime format: []const u8, args: anytype) noreturn {
ret: {
const msg = std.fmt.allocPrint(gpa, "fatal: " ++ format ++ "\n", args) catch break :ret;
std.io.getStdErr().writeAll(msg) catch {};
}
std.process.exit(1);
}
const Version = struct { const Version = struct {
major: u16, major: u16,
minor: u8, minor: u8,

View file

@ -1,5 +1,7 @@
const std = @import("std"); const std = @import("std");
const assert = std.debug.assert; const assert = std.debug.assert;
const info = std.log.info;
const fatal = std.process.fatal;
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
@ -13,19 +15,6 @@ const usage =
\\-h, --help Print this help and exit \\-h, --help Print this help and exit
; ;
fn info(comptime format: []const u8, args: anytype) void {
const msg = std.fmt.allocPrint(gpa, "info: " ++ format ++ "\n", args) catch return;
std.io.getStdOut().writeAll(msg) catch {};
}
fn fatal(comptime format: []const u8, args: anytype) noreturn {
ret: {
const msg = std.fmt.allocPrint(gpa, "fatal: " ++ format ++ "\n", args) catch break :ret;
std.io.getStdErr().writeAll(msg) catch {};
}
std.process.exit(1);
}
pub fn main() anyerror!void { pub fn main() anyerror!void {
var arena_allocator = std.heap.ArenaAllocator.init(gpa); var arena_allocator = std.heap.ArenaAllocator.init(gpa);
defer arena_allocator.deinit(); defer arena_allocator.deinit();
@ -58,16 +47,19 @@ pub fn main() anyerror!void {
std.mem.sort([]const u8, paths.items, {}, SortFn.lessThan); std.mem.sort([]const u8, paths.items, {}, SortFn.lessThan);
const stdout = std.io.getStdOut().writer(); var buffer: [2000]u8 = undefined;
try stdout.writeAll("#define _XOPEN_SOURCE\n"); var stdout_writer = std.fs.File.stdout().writerStreaming(&buffer);
const w = &stdout_writer.interface;
try w.writeAll("#define _XOPEN_SOURCE\n");
for (paths.items) |path| { for (paths.items) |path| {
try stdout.print("#include <{s}>\n", .{path}); try w.print("#include <{s}>\n", .{path});
} }
try stdout.writeAll( try w.writeAll(
\\int main(int argc, char **argv) { \\int main(int argc, char **argv) {
\\ return 0; \\ return 0;
\\} \\}
); );
try w.flush();
} }
fn findHeaders( fn findHeaders(

View file

@ -17,8 +17,9 @@ pub fn main() !void {
//const args = try std.process.argsAlloc(arena); //const args = try std.process.argsAlloc(arena);
var bw = std.io.bufferedWriter(std.io.getStdOut().writer()); var stdout_buffer: [2000]u8 = undefined;
const w = bw.writer(); var stdout_writer = std.fs.File.stdout().writerStreaming(&stdout_buffer);
const w = &stdout_writer.interface;
try w.writeAll( try w.writeAll(
\\//! This file is generated by tools/gen_outline_atomics.zig. \\//! This file is generated by tools/gen_outline_atomics.zig.
@ -57,7 +58,7 @@ pub fn main() !void {
try w.writeAll(footer.items); try w.writeAll(footer.items);
try w.writeAll("}\n"); try w.writeAll("}\n");
try bw.flush(); try w.flush();
} }
fn writeFunction( fn writeFunction(

View file

@ -91,9 +91,10 @@ pub fn main() !void {
try readExtRegistry(&exts, a, std.fs.cwd(), args[2]); try readExtRegistry(&exts, a, std.fs.cwd(), args[2]);
var bw = std.io.bufferedWriter(std.io.getStdOut().writer()); var buffer: [4000]u8 = undefined;
try render(bw.writer(), a, core_spec, exts.items); var w = std.fs.File.stdout().writerStreaming(&buffer);
try bw.flush(); try render(&w, a, core_spec, exts.items);
try w.flush();
} }
fn readExtRegistry(exts: *std.ArrayList(Extension), a: Allocator, dir: std.fs.Dir, sub_path: []const u8) !void { fn readExtRegistry(exts: *std.ArrayList(Extension), a: Allocator, dir: std.fs.Dir, sub_path: []const u8) !void {
@ -166,7 +167,7 @@ fn tagPriorityScore(tag: []const u8) usize {
} }
} }
fn render(writer: anytype, a: Allocator, registry: CoreRegistry, extensions: []const Extension) !void { fn render(writer: *std.io.Writer, a: Allocator, registry: CoreRegistry, extensions: []const Extension) !void {
try writer.writeAll( try writer.writeAll(
\\//! This file is auto-generated by tools/gen_spirv_spec.zig. \\//! This file is auto-generated by tools/gen_spirv_spec.zig.
\\ \\
@ -188,15 +189,10 @@ fn render(writer: anytype, a: Allocator, registry: CoreRegistry, extensions: []c
\\ none, \\ none,
\\ _, \\ _,
\\ \\
\\ pub fn format( \\ pub fn format(self: IdResult, writer: *std.io.Writer) std.io.Writer.Error!void {
\\ self: IdResult,
\\ comptime _: []const u8,
\\ _: std.fmt.FormatOptions,
\\ writer: anytype,
\\ ) @TypeOf(writer).Error!void {
\\ switch (self) { \\ switch (self) {
\\ .none => try writer.writeAll("(none)"), \\ .none => try writer.writeAll("(none)"),
\\ else => try writer.print("%{}", .{@intFromEnum(self)}), \\ else => try writer.print("%{d}", .{@intFromEnum(self)}),
\\ } \\ }
\\ } \\ }
\\}; \\};
@ -899,7 +895,8 @@ fn parseHexInt(text: []const u8) !u31 {
} }
fn usageAndExit(arg0: []const u8, code: u8) noreturn { fn usageAndExit(arg0: []const u8, code: u8) noreturn {
std.io.getStdErr().writer().print( const stderr = std.debug.lockStderrWriter(&.{});
stderr.print(
\\Usage: {s} <SPIRV-Headers repository path> <path/to/zig/src/codegen/spirv/extinst.zig.grammar.json> \\Usage: {s} <SPIRV-Headers repository path> <path/to/zig/src/codegen/spirv/extinst.zig.grammar.json>
\\ \\
\\Generates Zig bindings for SPIR-V specifications found in the SPIRV-Headers \\Generates Zig bindings for SPIR-V specifications found in the SPIRV-Headers

View file

@ -333,7 +333,9 @@ pub fn main() !void {
} }
} }
const stdout = std.io.getStdOut().writer(); var stdout_buffer: [2000]u8 = undefined;
var stdout_writer = std.fs.File.stdout().writerStreaming(&stdout_buffer);
const stdout = &stdout_writer.interface;
try stdout.writeAll( try stdout.writeAll(
\\#ifdef PTR64 \\#ifdef PTR64
\\#define WEAK64 .weak \\#define WEAK64 .weak
@ -533,6 +535,8 @@ pub fn main() !void {
.all => {}, .all => {},
.single, .multi, .family, .time32 => try stdout.writeAll("#endif\n"), .single, .multi, .family, .time32 => try stdout.writeAll("#endif\n"),
} }
try stdout.flush();
} }
fn parseElf(parse: Parse, comptime is_64: bool, comptime endian: builtin.Endian) !void { fn parseElf(parse: Parse, comptime is_64: bool, comptime endian: builtin.Endian) !void {

View file

@ -6,7 +6,9 @@ pub fn main() !void {
var gpa: std.heap.GeneralPurposeAllocator(.{}) = .init; var gpa: std.heap.GeneralPurposeAllocator(.{}) = .init;
var allocator = gpa.allocator(); var allocator = gpa.allocator();
var output = std.io.getStdOut().writer(); var stdout_buffer: [2000]u8 = undefined;
var stdout_writer = std.fs.File.stdout().writerStreaming(&stdout_buffer);
const output = &stdout_writer.interface;
try output.writeAll( try output.writeAll(
\\// This file was generated by _generate_JSONTestSuite.zig \\// This file was generated by _generate_JSONTestSuite.zig
\\// These test cases are sourced from: https://github.com/nst/JSONTestSuite \\// These test cases are sourced from: https://github.com/nst/JSONTestSuite
@ -44,6 +46,8 @@ pub fn main() !void {
try writeString(output, contents); try writeString(output, contents);
try output.writeAll(");\n}\n"); try output.writeAll(");\n}\n");
} }
try output.flush();
} }
const i_structure_500_nested_arrays = "[" ** 500 ++ "]" ** 500; const i_structure_500_nested_arrays = "[" ** 500 ++ "]" ** 500;

View file

@ -42,20 +42,23 @@ pub fn main() !void {
const query = try std.Target.Query.parse(.{ .arch_os_abi = args[1] }); const query = try std.Target.Query.parse(.{ .arch_os_abi = args[1] });
const target = try std.zig.system.resolveTargetQuery(query); const target = try std.zig.system.resolveTargetQuery(query);
const stdout = std.io.getStdOut().writer(); var buffer: [2000]u8 = undefined;
var stdout_writer = std.fs.File.stdout().writerStreaming(&buffer);
const w = &stdout_writer.interface;
inline for (@typeInfo(std.Target.CType).@"enum".fields) |field| { inline for (@typeInfo(std.Target.CType).@"enum".fields) |field| {
const c_type: std.Target.CType = @enumFromInt(field.value); const c_type: std.Target.CType = @enumFromInt(field.value);
try stdout.print("_Static_assert(sizeof({0s}) == {1d}, \"sizeof({0s}) == {1d}\");\n", .{ try w.print("_Static_assert(sizeof({0s}) == {1d}, \"sizeof({0s}) == {1d}\");\n", .{
cName(c_type), cName(c_type),
target.cTypeByteSize(c_type), target.cTypeByteSize(c_type),
}); });
try stdout.print("_Static_assert(_Alignof({0s}) == {1d}, \"_Alignof({0s}) == {1d}\");\n", .{ try w.print("_Static_assert(_Alignof({0s}) == {1d}, \"_Alignof({0s}) == {1d}\");\n", .{
cName(c_type), cName(c_type),
target.cTypeAlignment(c_type), target.cTypeAlignment(c_type),
}); });
try stdout.print("_Static_assert(__alignof({0s}) == {1d}, \"__alignof({0s}) == {1d}\");\n\n", .{ try w.print("_Static_assert(__alignof({0s}) == {1d}, \"__alignof({0s}) == {1d}\");\n\n", .{
cName(c_type), cName(c_type),
target.cTypePreferredAlignment(c_type), target.cTypePreferredAlignment(c_type),
}); });
} }
try w.flush();
} }

View file

@ -666,13 +666,16 @@ pub fn main() !void {
const allocator = arena.allocator(); const allocator = arena.allocator();
const args = try std.process.argsAlloc(allocator); const args = try std.process.argsAlloc(allocator);
if (args.len < 3 or mem.eql(u8, args[1], "--help")) if (args.len < 3 or mem.eql(u8, args[1], "--help")) {
usageAndExit(std.io.getStdErr(), args[0], 1); usage(std.debug.lockStderrWriter(&.{}), args[0]) catch std.process.exit(2);
std.process.exit(1);
}
const zig_exe = args[1]; const zig_exe = args[1];
const linux_path = args[2]; const linux_path = args[2];
var buf_out = std.io.bufferedWriter(std.io.getStdOut().writer()); var stdout_buffer: [2000]u8 = undefined;
const writer = buf_out.writer(); var stdout_writer = std.fs.File.stdout().writerStreaming(&stdout_buffer);
const writer = &stdout_writer.interface;
var linux_dir = try std.fs.cwd().openDir(linux_path, .{}); var linux_dir = try std.fs.cwd().openDir(linux_path, .{});
defer linux_dir.close(); defer linux_dir.close();
@ -714,17 +717,16 @@ pub fn main() !void {
} }
} }
try buf_out.flush(); try writer.flush();
} }
fn usageAndExit(file: fs.File, arg0: []const u8, code: u8) noreturn { fn usage(w: *std.io.Writer, arg0: []const u8) std.io.Writer.Error!void {
file.writer().print( try w.print(
\\Usage: {s} /path/to/zig /path/to/linux \\Usage: {s} /path/to/zig /path/to/linux
\\Alternative Usage: zig run /path/to/git/zig/tools/generate_linux_syscalls.zig -- /path/to/zig /path/to/linux \\Alternative Usage: zig run /path/to/git/zig/tools/generate_linux_syscalls.zig -- /path/to/zig /path/to/linux
\\ \\
\\Generates the list of Linux syscalls for each supported cpu arch, using the Linux development tree. \\Generates the list of Linux syscalls for each supported cpu arch, using the Linux development tree.
\\Prints to stdout Zig code which you can use to replace the file lib/std/os/linux/syscalls.zig. \\Prints to stdout Zig code which you can use to replace the file lib/std/os/linux/syscalls.zig.
\\ \\
, .{arg0}) catch std.process.exit(1); , .{arg0});
std.process.exit(code);
} }

View file

@ -634,25 +634,25 @@ pub fn main() anyerror!void {
const allocator = arena.allocator(); const allocator = arena.allocator();
const args = try std.process.argsAlloc(allocator); const args = try std.process.argsAlloc(allocator);
if (args.len <= 1) { var stdout_buffer: [4000]u8 = undefined;
usageAndExit(std.io.getStdErr(), args[0], 1); var stdout_writer = fs.stdout().writerStreaming(&stdout_buffer);
} const stdout = &stdout_writer.interface;
if (args.len <= 1) printUsageAndExit(args[0]);
if (std.mem.eql(u8, args[1], "--help")) { if (std.mem.eql(u8, args[1], "--help")) {
usageAndExit(std.io.getStdOut(), args[0], 0); printUsage(stdout, args[0]) catch std.process.exit(2);
} stdout.flush() catch std.process.exit(2);
if (args.len < 3) { std.process.exit(0);
usageAndExit(std.io.getStdErr(), args[0], 1);
} }
if (args.len < 3) printUsageAndExit(args[0]);
const llvm_tblgen_exe = args[1]; const llvm_tblgen_exe = args[1];
if (std.mem.startsWith(u8, llvm_tblgen_exe, "-")) { if (std.mem.startsWith(u8, llvm_tblgen_exe, "-")) printUsageAndExit(args[0]);
usageAndExit(std.io.getStdErr(), args[0], 1);
}
const llvm_src_root = args[2]; const llvm_src_root = args[2];
if (std.mem.startsWith(u8, llvm_src_root, "-")) { if (std.mem.startsWith(u8, llvm_src_root, "-")) printUsageAndExit(args[0]);
usageAndExit(std.io.getStdErr(), args[0], 1);
}
var llvm_to_zig_cpu_features = std.StringHashMap([]const u8).init(allocator); var llvm_to_zig_cpu_features = std.StringHashMap([]const u8).init(allocator);
@ -719,8 +719,6 @@ pub fn main() anyerror!void {
// "W" and "Wl,". So we sort this list in order of descending priority. // "W" and "Wl,". So we sort this list in order of descending priority.
std.mem.sort(*json.ObjectMap, all_objects.items, {}, objectLessThan); std.mem.sort(*json.ObjectMap, all_objects.items, {}, objectLessThan);
var buffered_stdout = std.io.bufferedWriter(std.io.getStdOut().writer());
const stdout = buffered_stdout.writer();
try stdout.writeAll( try stdout.writeAll(
\\// This file is generated by tools/update_clang_options.zig. \\// This file is generated by tools/update_clang_options.zig.
\\// zig fmt: off \\// zig fmt: off
@ -815,7 +813,7 @@ pub fn main() anyerror!void {
\\ \\
); );
try buffered_stdout.flush(); try stdout.flush();
} }
// TODO we should be able to import clang_options.zig but currently this is problematic because it will // TODO we should be able to import clang_options.zig but currently this is problematic because it will
@ -966,13 +964,17 @@ fn objectLessThan(context: void, a: *json.ObjectMap, b: *json.ObjectMap) bool {
return std.mem.lessThan(u8, a_key, b_key); return std.mem.lessThan(u8, a_key, b_key);
} }
fn usageAndExit(file: fs.File, arg0: []const u8, code: u8) noreturn { fn printUsageAndExit(arg0: []const u8) noreturn {
file.writer().print( printUsage(std.debug.lockStderrWriter(&.{}), arg0) catch std.process.exit(2);
std.process.exit(1);
}
fn printUsage(w: *std.io.Writer, arg0: []const u8) std.io.Writer.Error!void {
try w.print(
\\Usage: {s} /path/to/llvm-tblgen /path/to/git/llvm/llvm-project \\Usage: {s} /path/to/llvm-tblgen /path/to/git/llvm/llvm-project
\\Alternative Usage: zig run /path/to/git/zig/tools/update_clang_options.zig -- /path/to/llvm-tblgen /path/to/git/llvm/llvm-project \\Alternative Usage: zig run /path/to/git/zig/tools/update_clang_options.zig -- /path/to/llvm-tblgen /path/to/git/llvm/llvm-project
\\ \\
\\Prints to stdout Zig code which you can use to replace the file src/clang_options_data.zig. \\Prints to stdout Zig code which you can use to replace the file src/clang_options_data.zig.
\\ \\
, .{arg0}) catch std.process.exit(1); , .{arg0});
std.process.exit(code);
} }

View file

@ -2082,8 +2082,8 @@ fn processOneTarget(job: Job) void {
} }
fn usageAndExit(arg0: []const u8, code: u8) noreturn { fn usageAndExit(arg0: []const u8, code: u8) noreturn {
const stderr = std.io.getStdErr(); const stderr = std.debug.lockStderrWriter(&.{});
stderr.writer().print( stderr.print(
\\Usage: {s} /path/to/llvm-tblgen /path/git/llvm-project /path/git/zig [zig_name filter] \\Usage: {s} /path/to/llvm-tblgen /path/git/llvm-project /path/git/zig [zig_name filter]
\\ \\
\\Updates lib/std/target/<target>.zig from llvm/lib/Target/<Target>/<Target>.td . \\Updates lib/std/target/<target>.zig from llvm/lib/Target/<Target>/<Target>.td .

View file

@ -11,14 +11,10 @@ pub fn main() anyerror!void {
const arena = arena_state.allocator(); const arena = arena_state.allocator();
const args = try std.process.argsAlloc(arena); const args = try std.process.argsAlloc(arena);
if (args.len <= 1) { if (args.len <= 1) printUsageAndExit(args[0]);
usageAndExit(std.io.getStdErr(), args[0], 1);
}
const zig_src_root = args[1]; const zig_src_root = args[1];
if (mem.startsWith(u8, zig_src_root, "-")) { if (mem.startsWith(u8, zig_src_root, "-")) printUsageAndExit(args[0]);
usageAndExit(std.io.getStdErr(), args[0], 1);
}
var zig_src_dir = try fs.cwd().openDir(zig_src_root, .{}); var zig_src_dir = try fs.cwd().openDir(zig_src_root, .{});
defer zig_src_dir.close(); defer zig_src_dir.close();
@ -193,10 +189,14 @@ pub fn main() anyerror!void {
} }
} }
fn usageAndExit(file: fs.File, arg0: []const u8, code: u8) noreturn { fn printUsageAndExit(arg0: []const u8) noreturn {
file.writer().print( printUsage(std.debug.lockStderrWriter(&.{}), arg0) catch std.process.exit(2);
std.process.exit(1);
}
fn printUsage(w: *std.io.Writer, arg0: []const u8) std.io.Writer.Error!void {
return w.print(
\\Usage: {s} /path/git/zig \\Usage: {s} /path/git/zig
\\ \\
, .{arg0}) catch std.process.exit(1); , .{arg0});
std.process.exit(code);
} }