build: remove ZiglingStep.eval

Remove the `ZiglingStep.eval` method and the src/ipc.zig source code.
Use `Step.evalZigProcess`, instead. This greatly simplifies the code.

Print the error messages and error bundle in `ZiglingStep.make`, both in
case of error and success.

Additionally, remove the `ZiglingStep.is_testing` field, since it is no
longer necessary.
This commit is contained in:
Manlio Perillo 2023-05-19 15:28:20 +02:00
parent 282c50834a
commit 699f877bd5
2 changed files with 17 additions and 231 deletions

180
build.zig
View file

@ -1,7 +1,6 @@
const std = @import("std"); const std = @import("std");
const builtin = @import("builtin"); const builtin = @import("builtin");
const compat = @import("src/compat.zig"); const compat = @import("src/compat.zig");
const ipc = @import("src/ipc.zig");
const tests = @import("test/tests.zig"); const tests = @import("test/tests.zig");
const Build = compat.Build; const Build = compat.Build;
@ -195,10 +194,6 @@ const ZiglingStep = struct {
work_path: []const u8, work_path: []const u8,
mode: Mode, mode: Mode,
is_testing: bool = false,
result_messages: []const u8 = "",
result_error_bundle: std.zig.ErrorBundle = std.zig.ErrorBundle.empty,
pub fn create( pub fn create(
b: *Build, b: *Build,
exercise: Exercise, exercise: Exercise,
@ -232,6 +227,8 @@ const ZiglingStep = struct {
} }
const exe_path = self.compile(prog_node) catch { const exe_path = self.compile(prog_node) catch {
self.printErrors();
if (self.exercise.hint) |hint| if (self.exercise.hint) |hint|
print("\n{s}Ziglings hint: {s}{s}", .{ bold_text, hint, reset_text }); print("\n{s}Ziglings hint: {s}{s}", .{ bold_text, hint, reset_text });
@ -240,12 +237,17 @@ const ZiglingStep = struct {
}; };
self.run(exe_path, prog_node) catch { self.run(exe_path, prog_node) catch {
self.printErrors();
if (self.exercise.hint) |hint| if (self.exercise.hint) |hint|
print("\n{s}Ziglings hint: {s}{s}", .{ bold_text, hint, reset_text }); print("\n{s}Ziglings hint: {s}{s}", .{ bold_text, hint, reset_text });
self.help(); self.help();
std.os.exit(2); std.os.exit(2);
}; };
// Print possible warning/debug messages.
self.printErrors();
} }
fn run(self: *ZiglingStep, exe_path: []const u8, _: *std.Progress.Node) !void { fn run(self: *ZiglingStep, exe_path: []const u8, _: *std.Progress.Node) !void {
@ -381,153 +383,7 @@ const ZiglingStep = struct {
zig_args.append("--listen=-") catch @panic("OOM"); zig_args.append("--listen=-") catch @panic("OOM");
const argv = zig_args.items; return try self.step.evalZigProcess(zig_args.items, prog_node);
var code: u8 = undefined;
const exe_path = self.eval(argv, &code, prog_node) catch |err| {
self.printErrors();
switch (err) {
error.FileNotFound => {
print("{s}{s}: Unable to spawn the following command: file not found{s}\n", .{
red_text, self.exercise.main_file, reset_text,
});
dumpArgs(argv);
},
error.ExitCodeFailure => {
print("{s}{s}: The following command exited with error code {}:{s}\n", .{
red_text, self.exercise.main_file, code, reset_text,
});
dumpArgs(argv);
},
error.ProcessTerminated => {
print("{s}{s}: The following command terminated unexpectedly:{s}\n", .{
red_text, self.exercise.main_file, reset_text,
});
dumpArgs(argv);
},
error.ZigIPCError => {
// Commenting this out for now. It always shows up when compilation fails.
//print("{s}{s}: The following command failed to communicate the compilation result:{s}\n", .{
// red_text, self.exercise.main_file, reset_text,
//});
//dumpArgs(argv);
},
else => {
print("{s}{s}: Unexpected error: {s}{s}\n", .{
red_text, self.exercise.main_file, @errorName(err), reset_text,
});
dumpArgs(argv);
},
}
return err;
};
self.printErrors();
return exe_path;
}
// Code adapted from `std.Build.execAllowFail and `std.Build.Step.evalZigProcess`.
pub fn eval(
self: *ZiglingStep,
argv: []const []const u8,
out_code: *u8,
prog_node: *std.Progress.Node,
) ![]const u8 {
assert(argv.len != 0);
const b = self.step.owner;
const allocator = b.allocator;
var child = Child.init(argv, allocator);
child.env_map = b.env_map;
child.stdin_behavior = .Pipe;
child.stdout_behavior = .Pipe;
child.stderr_behavior = .Pipe;
try child.spawn();
var poller = std.io.poll(allocator, enum { stdout, stderr }, .{
.stdout = child.stdout.?,
.stderr = child.stderr.?,
});
defer poller.deinit();
try ipc.sendMessage(child.stdin.?, .update);
try ipc.sendMessage(child.stdin.?, .exit);
const Header = std.zig.Server.Message.Header;
var result: ?[]const u8 = null;
var node_name: std.ArrayListUnmanaged(u8) = .{};
defer node_name.deinit(allocator);
var sub_prog_node = prog_node.start("", 0);
defer sub_prog_node.end();
const stdout = poller.fifo(.stdout);
poll: while (true) {
while (stdout.readableLength() < @sizeOf(Header)) {
if (!(try poller.poll())) break :poll;
}
const header = stdout.reader().readStruct(Header) catch unreachable;
while (stdout.readableLength() < header.bytes_len) {
if (!(try poller.poll())) break :poll;
}
const body = stdout.readableSliceOfLen(header.bytes_len);
switch (header.tag) {
.zig_version => {
if (!std.mem.eql(u8, builtin.zig_version_string, body))
return error.ZigVersionMismatch;
},
.error_bundle => {
self.result_error_bundle = try ipc.parseErrorBundle(allocator, body);
},
.progress => {
node_name.clearRetainingCapacity();
try node_name.appendSlice(allocator, body);
sub_prog_node.setName(node_name.items);
},
.emit_bin_path => {
const emit_bin = try ipc.parseEmitBinPath(allocator, body);
result = emit_bin.path;
},
else => {}, // ignore other messages
}
stdout.discard(body.len);
}
const stderr = poller.fifo(.stderr);
if (stderr.readableLength() > 0) {
self.result_messages = try stderr.toOwnedSlice();
}
// Send EOF to stdin.
child.stdin.?.close();
child.stdin = null;
// Keep the errors compatible with std.Build.execAllowFail.
const term = try child.wait();
switch (term) {
.Exited => |code| {
if (code != 0) {
out_code.* = @truncate(u8, code);
return error.ExitCodeFailure;
}
},
.Signal, .Stopped, .Unknown => |code| {
out_code.* = @truncate(u8, code);
return error.ProcessTerminated;
},
}
if (self.is_testing) {
return "ok";
}
return result orelse return error.ZigIPCError;
} }
fn help(self: *ZiglingStep) void { fn help(self: *ZiglingStep) void {
@ -548,27 +404,25 @@ const ZiglingStep = struct {
fn printErrors(self: *ZiglingStep) void { fn printErrors(self: *ZiglingStep) void {
resetLine(); resetLine();
// Print the additional log and verbose messages. // Display error/warning messages.
// TODO: use colors? if (self.step.result_error_msgs.items.len > 0) {
if (self.result_messages.len > 0) print("{s}", .{self.result_messages}); for (self.step.result_error_msgs.items) |msg| {
print("{s}error: {s}{s}\n", .{ red_text, reset_text, msg });
}
}
// Print the compiler errors. // Render compile errors at the bottom of the terminal.
// TODO: use the same ttyconf from the builder. // TODO: use the same ttyconf from the builder.
const ttyconf: std.debug.TTY.Config = if (use_color_escapes) const ttyconf: std.debug.TTY.Config = if (use_color_escapes)
.escape_codes .escape_codes
else else
.no_color; .no_color;
if (self.result_error_bundle.errorMessageCount() > 0) { if (self.step.result_error_bundle.errorMessageCount() > 0) {
self.result_error_bundle.renderToStdErr(.{ .ttyconf = ttyconf }); self.step.result_error_bundle.renderToStdErr(.{ .ttyconf = ttyconf });
} }
} }
}; };
fn dumpArgs(args: []const []const u8) void {
for (args) |arg| print("{s} ", .{arg});
print("\n", .{});
}
/// Clears the entire line and move the cursor to column zero. /// Clears the entire line and move the cursor to column zero.
/// Used for clearing the compiler and build_runner progress messages. /// Used for clearing the compiler and build_runner progress messages.
fn resetLine() void { fn resetLine() void {

View file

@ -1,68 +0,0 @@
/// Client side support for Zig IPC.
const std = @import("std");
const debug = std.debug;
const fs = std.fs;
const mem = std.mem;
const Allocator = mem.Allocator;
const Client = std.zig.Client;
const ErrorBundle = std.zig.ErrorBundle;
const Server = std.zig.Server;
/// This data structure must be kept in sync with zig.Server.Message.EmitBinPath.
const EmitBinPath = struct {
flags: Flags,
path: []const u8,
pub const Flags = Server.Message.EmitBinPath.Flags;
pub fn deinit(self: *EmitBinPath, allocator: Allocator) void {
allocator.free(self.path);
self.* = undefined;
}
};
pub fn parseErrorBundle(allocator: Allocator, data: []const u8) !ErrorBundle {
const EbHdr = Server.Message.ErrorBundle;
const eb_hdr = @ptrCast(*align(1) const EbHdr, data);
const extra_bytes =
data[@sizeOf(EbHdr)..][0 .. @sizeOf(u32) * eb_hdr.extra_len];
const string_bytes =
data[@sizeOf(EbHdr) + extra_bytes.len ..][0..eb_hdr.string_bytes_len];
// TODO: use @ptrCast when the compiler supports it
const unaligned_extra = std.mem.bytesAsSlice(u32, extra_bytes);
const extra_array = try allocator.alloc(u32, unaligned_extra.len);
// TODO: use @memcpy when it supports slices
//
// Don't use the "multi-object for loop" syntax, in
// order to avoid a syntax error with old Zig compilers.
var i: usize = 0;
while (i < extra_array.len) : (i += 1) {
extra_array[i] = unaligned_extra[i];
}
return .{
.string_bytes = try allocator.dupe(u8, string_bytes),
.extra = extra_array,
};
}
pub fn parseEmitBinPath(allocator: Allocator, data: []const u8) !EmitBinPath {
const EbpHdr = Server.Message.EmitBinPath;
const ebp_hdr = @ptrCast(*align(1) const EbpHdr, data);
const path = try allocator.dupe(u8, data[@sizeOf(EbpHdr)..]);
return .{
.flags = ebp_hdr.flags,
.path = path,
};
}
pub fn sendMessage(file: fs.File, tag: Client.Message.Tag) !void {
const header: Client.Message.Header = .{
.tag = tag,
.bytes_len = 0,
};
try file.writeAll(mem.asBytes(&header));
}