Merge branch 'ratfactor:main' into testing

This commit is contained in:
Chris Boesch 2023-05-06 15:29:22 +02:00 committed by GitHub
commit f1368f4f81
7 changed files with 161 additions and 106 deletions

View file

@ -122,11 +122,12 @@ pub fn build(b: *Build) !void {
\\ \\
; ;
const use_healed = b.option(bool, "healed", "Run exercises from patches/healed") orelse false; const healed = b.option(bool, "healed", "Run exercises from patches/healed") orelse false;
const override_healed_path = b.option([]const u8, "healed-path", "Override healed path");
const exno: ?usize = b.option(usize, "n", "Select exercise"); const exno: ?usize = b.option(usize, "n", "Select exercise");
const healed_path = "patches/healed"; const healed_path = if (override_healed_path) |path| path else "patches/healed";
const work_path = if (use_healed) healed_path else "exercises"; const work_path = if (healed) healed_path else "exercises";
const header_step = PrintStep.create(b, logo); const header_step = PrintStep.create(b, logo);
@ -172,7 +173,7 @@ pub fn build(b: *Build) !void {
start_step.dependOn(&prev_step.step); start_step.dependOn(&prev_step.step);
return; return;
} else if (use_healed and false) { } else if (healed and false) {
// Special case when healed by the eowyn script, where we can make the // Special case when healed by the eowyn script, where we can make the
// code more efficient. // code more efficient.
// //

View file

@ -1,18 +1,18 @@
// //
// Oh no! This program is supposed to print "Hello world!" but it needs // Oh no, this is supposed to print "Hello world!" but it needs
// your help! // your help.
// //
// Zig functions are private by default but the main() function
// should be public.
// //
// Zig functions are private by default but the main() function should // A function is made public with the "pub" statement like so:
// be public.
//
// A function is declared public with the "pub" statement like so:
// //
// pub fn foo() void { // pub fn foo() void {
// ... // ...
// } // }
// //
// Try to fix the program and run `ziglings` to see if it works! // Perhaps knowing this well help solve the errors we're getting
// with this little program?
// //
const std = @import("std"); const std = @import("std");

View file

@ -2,9 +2,9 @@
// Help! Evil alien creatures have hidden eggs all over the Earth // Help! Evil alien creatures have hidden eggs all over the Earth
// and they're starting to hatch! // and they're starting to hatch!
// //
// Before you jump into battle, you'll need to know four things: // Before you jump into battle, you'll need to know three things:
// //
// 1. You can attach functions to structs: // 1. You can attach functions to structs (and other "type definitions"):
// //
// const Foo = struct{ // const Foo = struct{
// pub fn hello() void { // pub fn hello() void {
@ -12,31 +12,30 @@
// } // }
// }; // };
// //
// 2. A function that is a member of a struct is a "method" and is // 2. A function that is a member of a struct is "namespaced" within
// called with the "dot syntax" like so: // that struct and is called by specifying the "namespace" and then
// using the "dot syntax":
// //
// Foo.hello(); // Foo.hello();
// //
// 3. The NEAT feature of methods is the special parameter named // 3. The NEAT feature of these functions is that if their first argument
// "self" that takes an instance of that type of struct: // is an instance of the struct (or a pointer to one) then we can use
// the instance as the namespace instead of the type:
// //
// const Bar = struct{ // const Bar = struct{
// number: u32, // pub fn a(self: Bar) void {}
// // pub fn b(this: *Bar, other: u8) void {}
// pub fn printMe(self: Bar) void { // pub fn c(bar: *const Bar) void {}
// std.debug.print("{}\n", .{self.number});
// }
// }; // };
// //
// (Actually, you can name the first parameter anything, but // var bar = Bar{};
// please follow convention and use "self".) // bar.a() // is equivalent to Bar.a(bar)
// bar.b(3) // is equivalent to Bar.b(&bar, 3)
// bar.c() // is equivalent to Bar.c(&bar)
// //
// 4. Now when you call the method on an INSTANCE of that struct // Notice that the name of the parameter doesn't matter. Some use
// with the "dot syntax", the instance will be automatically // self, others use a lowercase version of the type name, but feel
// passed as the "self" parameter: // free to use whatever is most appropriate.
//
// var my_bar = Bar{ .number = 2000 };
// my_bar.printMe(); // prints "2000"
// //
// Okay, you're armed. // Okay, you're armed.
// //

View file

@ -1,10 +1,11 @@
// //
// Zig has support for IEEE-754 floating-point numbers in these // Zig has support for IEEE-754 floating-point numbers in these
// specific sizes: f16, f32, f64, f80, and f128. Floating point // specific sizes: f16, f32, f64, f80, and f128. Floating point
// literals may be written in scientific notation: // literals may be written in the same ways as integers but also
// in scientific notation:
// //
// const a1: f32 = 1200.0; // 1,200 // const a1: f32 = 1200; // 1,200
// const a2: f32 = 1.2e+3; // 1,200 // const a2: f32 = 1.2e+3; // 1,200
// const b1: f32 = -500_000.0; // -500,000 // const b1: f32 = -500_000.0; // -500,000
// const b2: f32 = -5.0e+5; // -500,000 // const b2: f32 = -5.0e+5; // -500,000
// //
@ -22,12 +23,14 @@
// const pi: f16 = 3.1415926535; // rounds to 3.140625 // const pi: f16 = 3.1415926535; // rounds to 3.140625
// const av: f16 = 6.02214076e+23; // Avogadro's inf(inity)! // const av: f16 = 6.02214076e+23; // Avogadro's inf(inity)!
// //
// A float literal has a decimal point. When performing math // When performing math operations with numeric literals, ensure
// operations with numeric literals, ensure the types match. Zig // the types match. Zig does not perform unsafe type coercions
// does not perform unsafe type coercions behind your back: // behind your back:
// //
// var foo: f16 = 13.5 * 5; // ERROR! // var foo: f16 = 5; // NO ERROR
// var foo: f16 = 13.5 * 5.0; // No problem, both are floats //
// var foo: u16 = 5; // A literal of a different type
// var bar: f16 = foo; // ERROR
// //
// Please fix the two float problems with this program and // Please fix the two float problems with this program and
// display the result as a whole number. // display the result as a whole number.

View file

@ -40,7 +40,7 @@
// //
// switch (thing) { // switch (thing) {
// .a => |a| special(a), // .a => |a| special(a),
// inline else |t| => normal(t), // inline else => |t| normal(t),
// } // }
// //
// We can have special handling of some cases and then Zig // We can have special handling of some cases and then Zig

View file

@ -79,19 +79,19 @@ pub fn main() void {
// all about: // all about:
// //
// Let's say you've been tasked with grabbing three glass // Let's say you've been tasked with grabbing three glass
// marbles, three spoons, and three feathers from a bucket. But // marbles, three spoons, and three feathers from a magic bag.
// you can't use your hands to grab them. Instead, you have a // But you can't use your hands to grab them. Instead, you must
// special marble scoop, spoon magnet, and feather tongs to grab // use a marble scoop, spoon magnet, and feather tongs to grab
// each type of object. // each type of object.
// //
// Now, would you rather have: // Now, would you rather the magic bag:
// //
// A. The items layered so you have to pick up one marble, then // A. Grouped the items in clusters so you have to pick up one
// one spoon, then one feather? // marble, then one spoon, then one feather?
// //
// OR // OR
// //
// B. The items separated by type so you can pick up all of the // B. Grouped the items by type so you can pick up all of the
// marbles at once, then all the spoons, then all of the // marbles at once, then all the spoons, then all of the
// feathers? // feathers?
// //
@ -103,14 +103,16 @@ pub fn main() void {
// efficient for modern CPUs. // efficient for modern CPUs.
// //
// Decades of OOP practices have steered people towards grouping // Decades of OOP practices have steered people towards grouping
// different data types together into "objects" with the hope // different data types together into mixed-type "objects" with
// that it would be friendlier to the human mind. But // the intent that these are easier on the human mind.
// data-oriented design groups data in a way that is more // Data-oriented design groups data by type in a way that is
// efficient for the computer. // easier on the computer.
// //
// In Zig terminology, the difference in groupings is sometimes // With clever language design, maybe we can have both.
// known as "Array of Structs" (AoS) versus "Struct of Arrays" //
// (SoA). // In the Zig community, you may see the difference in groupings
// presented with the terms "Array of Structs" (AoS) versus
// "Struct of Arrays" (SoA).
// //
// To envision these two designs in action, imagine an array of // To envision these two designs in action, imagine an array of
// RPG character structs, each containing three different data // RPG character structs, each containing three different data

View file

@ -7,6 +7,7 @@ const fs = std.fs;
const mem = std.mem; const mem = std.mem;
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const Child = std.process.Child;
const Build = std.build; const Build = std.build;
const FileSource = std.Build.FileSource; const FileSource = std.Build.FileSource;
const Reader = fs.File.Reader; const Reader = fs.File.Reader;
@ -18,57 +19,73 @@ const Exercise = root.Exercise;
pub fn addCliTests(b: *std.Build, exercises: []const Exercise) *Step { pub fn addCliTests(b: *std.Build, exercises: []const Exercise) *Step {
const step = b.step("test-cli", "Test the command line interface"); const step = b.step("test-cli", "Test the command line interface");
// We should use a temporary path, but it will make the implementation of
// `build.zig` more complex.
const work_path = "patches/healed";
fs.cwd().makePath(work_path) catch |err| {
return fail(step, "unable to make '{s}': {s}\n", .{ work_path, @errorName(err) });
};
const heal_step = HealStep.create(b, exercises, work_path);
{ {
// Test that `zig build -Dhealed -Dn=n test` selects the nth exercise. // Test that `zig build -Dhealed -Dn=n test` selects the nth exercise.
const case_step = createCase(b, "case-1"); const case_step = createCase(b, "case-1");
var i: usize = 0; const tmp_path = makeTempPath(b) catch |err| {
return fail(step, "unable to make tmp path: {s}\n", .{@errorName(err)});
};
const heal_step = HealStep.create(b, exercises, tmp_path);
for (exercises[0 .. exercises.len - 1]) |ex| { for (exercises[0 .. exercises.len - 1]) |ex| {
i += 1; const n = ex.number();
if (ex.skip) continue; if (ex.skip) continue;
const cmd = b.addSystemCommand( const cmd = b.addSystemCommand(&.{
&.{ b.zig_exe, "build", "-Dhealed", b.fmt("-Dn={}", .{i}), "test" }, b.zig_exe,
); "build",
cmd.setName(b.fmt("zig build -Dhealed -Dn={} test", .{i})); "-Dhealed",
b.fmt("-Dhealed-path={s}", .{tmp_path}),
b.fmt("-Dn={}", .{n}),
"test",
});
cmd.setName(b.fmt("zig build -Dhealed -Dn={} test", .{n}));
cmd.expectExitCode(0); cmd.expectExitCode(0);
if (ex.check_stdout) if (ex.check_stdout) {
expectStdOutMatch(cmd, ex.output) expectStdOutMatch(cmd, ex.output);
else cmd.expectStdErrEqual("");
} else {
expectStdErrMatch(cmd, ex.output); expectStdErrMatch(cmd, ex.output);
cmd.expectStdOutEqual("");
}
cmd.step.dependOn(&heal_step.step); cmd.step.dependOn(&heal_step.step);
case_step.dependOn(&cmd.step); case_step.dependOn(&cmd.step);
} }
step.dependOn(case_step); const cleanup = b.addRemoveDirTree(tmp_path);
cleanup.step.dependOn(case_step);
step.dependOn(&cleanup.step);
} }
{ {
// Test that `zig build -Dhealed -Dn=n test` skips disabled esercises. // Test that `zig build -Dhealed -Dn=n test` skips disabled esercises.
const case_step = createCase(b, "case-2"); const case_step = createCase(b, "case-2");
var i: usize = 0; const tmp_path = makeTempPath(b) catch |err| {
return fail(step, "unable to make tmp path: {s}\n", .{@errorName(err)});
};
const heal_step = HealStep.create(b, exercises, tmp_path);
for (exercises[0 .. exercises.len - 1]) |ex| { for (exercises[0 .. exercises.len - 1]) |ex| {
i += 1; const n = ex.number();
if (!ex.skip) continue; if (!ex.skip) continue;
const cmd = b.addSystemCommand( const cmd = b.addSystemCommand(&.{
&.{ b.zig_exe, "build", "-Dhealed", b.fmt("-Dn={}", .{i}), "test" }, b.zig_exe,
); "build",
cmd.setName(b.fmt("zig build -Dhealed -Dn={} test", .{i})); "-Dhealed",
b.fmt("-Dhealed-path={s}", .{tmp_path}),
b.fmt("-Dn={}", .{n}),
"test",
});
cmd.setName(b.fmt("zig build -Dhealed -Dn={} test", .{n}));
cmd.expectExitCode(0); cmd.expectExitCode(0);
cmd.expectStdOutEqual(""); cmd.expectStdOutEqual("");
expectStdErrMatch(cmd, b.fmt("{s} skipped", .{ex.main_file})); expectStdErrMatch(cmd, b.fmt("{s} skipped", .{ex.main_file}));
@ -78,15 +95,30 @@ pub fn addCliTests(b: *std.Build, exercises: []const Exercise) *Step {
case_step.dependOn(&cmd.step); case_step.dependOn(&cmd.step);
} }
step.dependOn(case_step); const cleanup = b.addRemoveDirTree(tmp_path);
cleanup.step.dependOn(case_step);
step.dependOn(&cleanup.step);
} }
{ {
// Test that `zig build -Dhealed` process all the exercises in order. // Test that `zig build -Dhealed` process all the exercises in order.
const case_step = createCase(b, "case-3"); const case_step = createCase(b, "case-3");
const tmp_path = makeTempPath(b) catch |err| {
return fail(step, "unable to make tmp path: {s}\n", .{@errorName(err)});
};
const heal_step = HealStep.create(b, exercises, tmp_path);
heal_step.step.dependOn(case_step);
// TODO: when an exercise is modified, the cache is not invalidated. // TODO: when an exercise is modified, the cache is not invalidated.
const cmd = b.addSystemCommand(&.{ b.zig_exe, "build", "-Dhealed" }); const cmd = b.addSystemCommand(&.{
b.zig_exe,
"build",
"-Dhealed",
b.fmt("-Dhealed-path={s}", .{tmp_path}),
});
cmd.setName("zig build -Dhealed"); cmd.setName("zig build -Dhealed");
cmd.expectExitCode(0); cmd.expectExitCode(0);
cmd.step.dependOn(&heal_step.step); cmd.step.dependOn(&heal_step.step);
@ -95,9 +127,10 @@ pub fn addCliTests(b: *std.Build, exercises: []const Exercise) *Step {
const verify = CheckStep.create(b, exercises, stderr, true); const verify = CheckStep.create(b, exercises, stderr, true);
verify.step.dependOn(&cmd.step); verify.step.dependOn(&cmd.step);
case_step.dependOn(&verify.step); const cleanup = b.addRemoveDirTree(tmp_path);
cleanup.step.dependOn(&verify.step);
step.dependOn(case_step); step.dependOn(&cleanup.step);
} }
{ {
@ -105,10 +138,22 @@ pub fn addCliTests(b: *std.Build, exercises: []const Exercise) *Step {
// in order. // in order.
const case_step = createCase(b, "case-4"); const case_step = createCase(b, "case-4");
const tmp_path = makeTempPath(b) catch |err| {
return fail(step, "unable to make tmp path: {s}\n", .{@errorName(err)});
};
const heal_step = HealStep.create(b, exercises, tmp_path);
heal_step.step.dependOn(case_step);
// TODO: when an exercise is modified, the cache is not invalidated. // TODO: when an exercise is modified, the cache is not invalidated.
const cmd = b.addSystemCommand( const cmd = b.addSystemCommand(&.{
&.{ b.zig_exe, "build", "-Dhealed", "-Dn=1", "start" }, b.zig_exe,
); "build",
"-Dhealed",
b.fmt("-Dhealed-path={s}", .{tmp_path}),
"-Dn=1",
"start",
});
cmd.setName("zig build -Dhealed -Dn=1 start"); cmd.setName("zig build -Dhealed -Dn=1 start");
cmd.expectExitCode(0); cmd.expectExitCode(0);
cmd.step.dependOn(&heal_step.step); cmd.step.dependOn(&heal_step.step);
@ -117,9 +162,10 @@ pub fn addCliTests(b: *std.Build, exercises: []const Exercise) *Step {
const verify = CheckStep.create(b, exercises, stderr, false); const verify = CheckStep.create(b, exercises, stderr, false);
verify.step.dependOn(&cmd.step); verify.step.dependOn(&cmd.step);
case_step.dependOn(&verify.step); const cleanup = b.addRemoveDirTree(tmp_path);
cleanup.step.dependOn(&verify.step);
step.dependOn(case_step); step.dependOn(&cleanup.step);
} }
{ {
@ -131,18 +177,11 @@ pub fn addCliTests(b: *std.Build, exercises: []const Exercise) *Step {
cmd.expectExitCode(1); cmd.expectExitCode(1);
expectStdErrMatch(cmd, exercises[0].hint); expectStdErrMatch(cmd, exercises[0].hint);
cmd.step.dependOn(&heal_step.step); cmd.step.dependOn(case_step);
case_step.dependOn(&cmd.step); step.dependOn(&cmd.step);
step.dependOn(case_step);
} }
// Don't add the cleanup step, since it may delete work_path while a test
// case is running.
//const cleanup = b.addRemoveDirTree(work_path);
//step.dependOn(&cleanup.step);
return step; return step;
} }
@ -157,7 +196,7 @@ fn createCase(b: *Build, name: []const u8) *Step {
return case_step; return case_step;
} }
// Check the output of `zig build` or `zig build -Dn=1 start`. /// Checks the output of `zig build` or `zig build -Dn=1 start`.
const CheckStep = struct { const CheckStep = struct {
step: Step, step: Step,
exercises: []const Exercise, exercises: []const Exercise,
@ -281,7 +320,7 @@ const CheckStep = struct {
} }
}; };
// A step that will fail. /// Fails with a custom error message.
const FailStep = struct { const FailStep = struct {
step: Step, step: Step,
error_msg: []const u8, error_msg: []const u8,
@ -310,9 +349,9 @@ const FailStep = struct {
} }
}; };
// A variant of `std.Build.Step.fail` that does not return an error so that it /// A variant of `std.Build.Step.fail` that does not return an error so that it
// can be used in the configuration phase. It returns a FailStep, so that the /// can be used in the configuration phase. It returns a FailStep, so that the
// error will be cleanly handled by the build runner. /// error will be cleanly handled by the build runner.
fn fail(step: *Step, comptime format: []const u8, args: anytype) *Step { fn fail(step: *Step, comptime format: []const u8, args: anytype) *Step {
const b = step.owner; const b = step.owner;
@ -322,7 +361,7 @@ fn fail(step: *Step, comptime format: []const u8, args: anytype) *Step {
return step; return step;
} }
// A step that heals exercises. /// Heals the exercises.
const HealStep = struct { const HealStep = struct {
step: Step, step: Step,
exercises: []const Exercise, exercises: []const Exercise,
@ -352,7 +391,7 @@ const HealStep = struct {
} }
}; };
// Heals all the exercises. /// Heals all the exercises.
fn heal(allocator: Allocator, exercises: []const Exercise, work_path: []const u8) !void { fn heal(allocator: Allocator, exercises: []const Exercise, work_path: []const u8) !void {
const join = fs.path.join; const join = fs.path.join;
@ -362,7 +401,6 @@ fn heal(allocator: Allocator, exercises: []const Exercise, work_path: []const u8
for (exercises) |ex| { for (exercises) |ex| {
const name = ex.name(); const name = ex.name();
// Use the POSIX patch variant.
const file = try join(allocator, &.{ exercises_path, ex.main_file }); const file = try join(allocator, &.{ exercises_path, ex.main_file });
const patch = b: { const patch = b: {
const patch_name = try fmt.allocPrint(allocator, "{s}.patch", .{name}); const patch_name = try fmt.allocPrint(allocator, "{s}.patch", .{name});
@ -372,11 +410,23 @@ fn heal(allocator: Allocator, exercises: []const Exercise, work_path: []const u8
const argv = &.{ "patch", "-i", patch, "-o", output, "-s", file }; const argv = &.{ "patch", "-i", patch, "-o", output, "-s", file };
var child = std.process.Child.init(argv, allocator); var child = Child.init(argv, allocator);
_ = try child.spawnAndWait(); _ = try child.spawnAndWait();
} }
} }
/// This function is the same as the one in std.Build.makeTempPath, with the
/// difference that returns an error when the temp path cannot be created.
pub fn makeTempPath(b: *Build) ![]const u8 {
const rand_int = std.crypto.random.int(u64);
const tmp_dir_sub_path = "tmp" ++ fs.path.sep_str ++ Build.hex64(rand_int);
const path = b.cache_root.join(b.allocator, &.{tmp_dir_sub_path}) catch
@panic("OOM");
try b.cache_root.handle.makePath(tmp_dir_sub_path);
return path;
}
// //
// Missing functions from std.Build.RunStep // Missing functions from std.Build.RunStep
// //