build.zig 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  1. const std = @import("std");
  2. const builtin = @import("builtin");
  3. const compat = @import("src/compat.zig");
  4. const ipc = @import("src/ipc.zig");
  5. const tests = @import("test/tests.zig");
  6. const Build = compat.Build;
  7. const Step = compat.build.Step;
  8. const Child = std.process.Child;
  9. const assert = std.debug.assert;
  10. const print = std.debug.print;
  11. pub const Exercise = struct {
  12. /// main_file must have the format key_name.zig.
  13. /// The key will be used as a shorthand to build
  14. /// just one example.
  15. main_file: []const u8,
  16. /// This is the desired output of the program.
  17. /// A program passes if its output, excluding trailing whitespace, is equal
  18. /// to this string.
  19. output: []const u8,
  20. /// This is an optional hint to give if the program does not succeed.
  21. hint: []const u8 = "",
  22. /// By default, we verify output against stderr.
  23. /// Set this to true to check stdout instead.
  24. check_stdout: bool = false,
  25. /// This exercise makes use of C functions
  26. /// We need to keep track of this, so we compile with libc
  27. C: bool = false,
  28. /// This exercise is not supported by the current Zig compiler.
  29. skip: bool = false,
  30. /// Returns the name of the main file with .zig stripped.
  31. pub fn baseName(self: Exercise) []const u8 {
  32. assert(std.mem.endsWith(u8, self.main_file, ".zig"));
  33. return self.main_file[0 .. self.main_file.len - 4];
  34. }
  35. /// Returns the key of the main file, the string before the '_' with
  36. /// "zero padding" removed.
  37. /// For example, "001_hello.zig" has the key "1".
  38. pub fn key(self: Exercise) []const u8 {
  39. const end_index = std.mem.indexOfScalar(u8, self.main_file, '_');
  40. assert(end_index != null); // main file must be key_description.zig
  41. // remove zero padding by advancing index past '0's
  42. var start_index: usize = 0;
  43. while (self.main_file[start_index] == '0') start_index += 1;
  44. return self.main_file[start_index..end_index.?];
  45. }
  46. /// Returns the exercise key as an integer.
  47. pub fn number(self: Exercise) usize {
  48. return std.fmt.parseInt(usize, self.key(), 10) catch unreachable;
  49. }
  50. };
  51. pub fn build(b: *Build) !void {
  52. if (!compat.is_compatible) compat.die();
  53. if (!validate_exercises()) std.os.exit(1);
  54. use_color_escapes = false;
  55. if (std.io.getStdErr().supportsAnsiEscapeCodes()) {
  56. use_color_escapes = true;
  57. } else if (builtin.os.tag == .windows) {
  58. const w32 = struct {
  59. const WINAPI = std.os.windows.WINAPI;
  60. const DWORD = std.os.windows.DWORD;
  61. const ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004;
  62. const STD_ERROR_HANDLE = @bitCast(DWORD, @as(i32, -12));
  63. extern "kernel32" fn GetStdHandle(id: DWORD) callconv(WINAPI) ?*anyopaque;
  64. extern "kernel32" fn GetConsoleMode(console: ?*anyopaque, out_mode: *DWORD) callconv(WINAPI) u32;
  65. extern "kernel32" fn SetConsoleMode(console: ?*anyopaque, mode: DWORD) callconv(WINAPI) u32;
  66. };
  67. const handle = w32.GetStdHandle(w32.STD_ERROR_HANDLE);
  68. var mode: w32.DWORD = 0;
  69. if (w32.GetConsoleMode(handle, &mode) != 0) {
  70. mode |= w32.ENABLE_VIRTUAL_TERMINAL_PROCESSING;
  71. use_color_escapes = w32.SetConsoleMode(handle, mode) != 0;
  72. }
  73. }
  74. if (use_color_escapes) {
  75. red_text = "\x1b[31m";
  76. green_text = "\x1b[32m";
  77. bold_text = "\x1b[1m";
  78. reset_text = "\x1b[0m";
  79. }
  80. const logo =
  81. \\
  82. \\ _ _ _
  83. \\ ___(_) __ _| (_)_ __ __ _ ___
  84. \\ |_ | |/ _' | | | '_ \ / _' / __|
  85. \\ / /| | (_| | | | | | | (_| \__ \
  86. \\ /___|_|\__, |_|_|_| |_|\__, |___/
  87. \\ |___/ |___/
  88. \\
  89. \\
  90. ;
  91. const use_healed = b.option(bool, "healed", "Run exercises from patches/healed") orelse false;
  92. const exno: ?usize = b.option(usize, "n", "Select exercise");
  93. const header_step = PrintStep.create(b, logo);
  94. if (exno) |n| {
  95. if (n == 0 or n > exercises.len - 1) {
  96. print("unknown exercise number: {}\n", .{n});
  97. std.os.exit(1);
  98. }
  99. const ex = exercises[n - 1];
  100. const base_name = ex.baseName();
  101. const file_path = std.fs.path.join(b.allocator, &[_][]const u8{
  102. if (use_healed) "patches/healed" else "exercises", ex.main_file,
  103. }) catch unreachable;
  104. const build_step = b.addExecutable(.{ .name = base_name, .root_source_file = .{ .path = file_path } });
  105. if (ex.C) {
  106. build_step.linkLibC();
  107. }
  108. b.installArtifact(build_step);
  109. const run_step = b.addRunArtifact(build_step);
  110. const test_step = b.step("test", b.fmt("Run {s} without checking output", .{ex.main_file}));
  111. if (ex.skip) {
  112. const skip_step = SkipStep.create(b, ex);
  113. test_step.dependOn(&skip_step.step);
  114. } else {
  115. test_step.dependOn(&run_step.step);
  116. }
  117. const install_step = b.step("install", b.fmt("Install {s} to prefix path", .{ex.main_file}));
  118. install_step.dependOn(b.getInstallStep());
  119. const uninstall_step = b.step("uninstall", b.fmt("Uninstall {s} from prefix path", .{ex.main_file}));
  120. uninstall_step.dependOn(b.getUninstallStep());
  121. const verify_step = ZiglingStep.create(b, ex, use_healed);
  122. const zigling_step = b.step("zigling", b.fmt("Check the solution of {s}", .{ex.main_file}));
  123. zigling_step.dependOn(&verify_step.step);
  124. b.default_step = zigling_step;
  125. const start_step = b.step("start", b.fmt("Check all solutions starting at {s}", .{ex.main_file}));
  126. var prev_step = verify_step;
  127. for (exercises) |exn| {
  128. const nth = exn.number();
  129. if (nth > n) {
  130. const verify_stepn = ZiglingStep.create(b, exn, use_healed);
  131. verify_stepn.step.dependOn(&prev_step.step);
  132. prev_step = verify_stepn;
  133. }
  134. }
  135. start_step.dependOn(&prev_step.step);
  136. return;
  137. } else if (use_healed and false) {
  138. const test_step = b.step("test", "Test the healed exercises");
  139. b.default_step = test_step;
  140. for (exercises) |ex| {
  141. const base_name = ex.baseName();
  142. const file_path = std.fs.path.join(b.allocator, &[_][]const u8{
  143. "patches/healed", ex.main_file,
  144. }) catch unreachable;
  145. const build_step = b.addExecutable(.{ .name = base_name, .root_source_file = .{ .path = file_path } });
  146. if (ex.C) {
  147. build_step.linkLibC();
  148. }
  149. b.installArtifact(build_step);
  150. const run_step = b.addRunArtifact(build_step);
  151. if (ex.skip) {
  152. const skip_step = SkipStep.create(b, ex);
  153. test_step.dependOn(&skip_step.step);
  154. } else {
  155. test_step.dependOn(&run_step.step);
  156. }
  157. }
  158. return;
  159. }
  160. const ziglings_step = b.step("ziglings", "Check all ziglings");
  161. b.default_step = ziglings_step;
  162. // Don't use the "multi-object for loop" syntax, in order to avoid a syntax
  163. // error with old Zig compilers.
  164. var prev_step = &header_step.step;
  165. for (exercises) |ex| {
  166. const base_name = ex.baseName();
  167. const file_path = std.fs.path.join(b.allocator, &[_][]const u8{
  168. "exercises", ex.main_file,
  169. }) catch unreachable;
  170. const build_step = b.addExecutable(.{ .name = base_name, .root_source_file = .{ .path = file_path } });
  171. b.installArtifact(build_step);
  172. const verify_stepn = ZiglingStep.create(b, ex, use_healed);
  173. verify_stepn.step.dependOn(prev_step);
  174. prev_step = &verify_stepn.step;
  175. }
  176. ziglings_step.dependOn(prev_step);
  177. const test_step = b.step("test", "Run all the tests");
  178. test_step.dependOn(tests.addCliTests(b, &exercises));
  179. }
  180. var use_color_escapes = false;
  181. var red_text: []const u8 = "";
  182. var green_text: []const u8 = "";
  183. var bold_text: []const u8 = "";
  184. var reset_text: []const u8 = "";
  185. const ZiglingStep = struct {
  186. step: Step,
  187. exercise: Exercise,
  188. builder: *Build,
  189. use_healed: bool,
  190. result_messages: []const u8 = "",
  191. result_error_bundle: std.zig.ErrorBundle = std.zig.ErrorBundle.empty,
  192. pub fn create(builder: *Build, exercise: Exercise, use_healed: bool) *@This() {
  193. const self = builder.allocator.create(@This()) catch unreachable;
  194. self.* = .{
  195. .step = Step.init(Step.Options{ .id = .custom, .name = exercise.main_file, .owner = builder, .makeFn = make }),
  196. .exercise = exercise,
  197. .builder = builder,
  198. .use_healed = use_healed,
  199. };
  200. return self;
  201. }
  202. fn make(step: *Step, prog_node: *std.Progress.Node) anyerror!void {
  203. const self = @fieldParentPtr(@This(), "step", step);
  204. if (self.exercise.skip) {
  205. print("Skipping {s}\n\n", .{self.exercise.main_file});
  206. return;
  207. }
  208. self.makeInternal(prog_node) catch {
  209. if (self.exercise.hint.len > 0) {
  210. print("\n{s}HINT: {s}{s}", .{ bold_text, self.exercise.hint, reset_text });
  211. }
  212. print("\n{s}Edit exercises/{s} and run this again.{s}", .{ red_text, self.exercise.main_file, reset_text });
  213. print("\n{s}To continue from this zigling, use this command:{s}\n {s}zig build -Dn={s}{s}\n", .{ red_text, reset_text, bold_text, self.exercise.key(), reset_text });
  214. std.os.exit(1);
  215. };
  216. }
  217. fn makeInternal(self: *@This(), prog_node: *std.Progress.Node) !void {
  218. print("Compiling {s}...\n", .{self.exercise.main_file});
  219. const exe_file = try self.doCompile(prog_node);
  220. resetLine();
  221. print("Checking {s}...\n", .{self.exercise.main_file});
  222. const cwd = self.builder.build_root.path.?;
  223. const argv = [_][]const u8{exe_file};
  224. var child = std.ChildProcess.init(&argv, self.builder.allocator);
  225. child.cwd = cwd;
  226. child.env_map = self.builder.env_map;
  227. child.stdin_behavior = .Inherit;
  228. if (self.exercise.check_stdout) {
  229. child.stdout_behavior = .Pipe;
  230. child.stderr_behavior = .Inherit;
  231. } else {
  232. child.stdout_behavior = .Inherit;
  233. child.stderr_behavior = .Pipe;
  234. }
  235. child.spawn() catch |err| {
  236. print("{s}Unable to spawn {s}: {s}{s}\n", .{ red_text, argv[0], @errorName(err), reset_text });
  237. return err;
  238. };
  239. // Allow up to 1 MB of stdout capture.
  240. const max_output_len = 1 * 1024 * 1024;
  241. const output = if (self.exercise.check_stdout)
  242. try child.stdout.?.reader().readAllAlloc(self.builder.allocator, max_output_len)
  243. else
  244. try child.stderr.?.reader().readAllAlloc(self.builder.allocator, max_output_len);
  245. // At this point stdout is closed, wait for the process to terminate.
  246. const term = child.wait() catch |err| {
  247. print("{s}Unable to spawn {s}: {s}{s}\n", .{ red_text, argv[0], @errorName(err), reset_text });
  248. return err;
  249. };
  250. // Make sure it exited cleanly.
  251. switch (term) {
  252. .Exited => |code| {
  253. if (code != 0) {
  254. print("{s}{s} exited with error code {d} (expected {d}){s}\n", .{ red_text, self.exercise.main_file, code, 0, reset_text });
  255. return error.BadExitCode;
  256. }
  257. },
  258. else => {
  259. print("{s}{s} terminated unexpectedly{s}\n", .{ red_text, self.exercise.main_file, reset_text });
  260. return error.UnexpectedTermination;
  261. },
  262. }
  263. // Validate the output.
  264. const trimOutput = std.mem.trimRight(u8, output, " \r\n");
  265. const trimExerciseOutput = std.mem.trimRight(u8, self.exercise.output, " \r\n");
  266. if (!std.mem.eql(u8, trimOutput, trimExerciseOutput)) {
  267. print(
  268. \\
  269. \\{s}----------- Expected this output -----------{s}
  270. \\"{s}"
  271. \\{s}----------- but found -----------{s}
  272. \\"{s}"
  273. \\{s}-----------{s}
  274. \\
  275. , .{ red_text, reset_text, trimExerciseOutput, red_text, reset_text, trimOutput, red_text, reset_text });
  276. return error.InvalidOutput;
  277. }
  278. print("{s}PASSED:\n{s}{s}\n\n", .{ green_text, trimOutput, reset_text });
  279. }
  280. // The normal compile step calls os.exit, so we can't use it as a library :(
  281. // This is a stripped down copy of std.build.LibExeObjStep.make.
  282. fn doCompile(self: *@This(), prog_node: *std.Progress.Node) ![]const u8 {
  283. const builder = self.builder;
  284. var zig_args = std.ArrayList([]const u8).init(builder.allocator);
  285. defer zig_args.deinit();
  286. zig_args.append(builder.zig_exe) catch unreachable;
  287. zig_args.append("build-exe") catch unreachable;
  288. // Enable C support for exercises that use C functions
  289. if (self.exercise.C) {
  290. zig_args.append("-lc") catch unreachable;
  291. }
  292. const zig_file = std.fs.path.join(builder.allocator, &[_][]const u8{ if (self.use_healed) "patches/healed" else "exercises", self.exercise.main_file }) catch unreachable;
  293. zig_args.append(builder.pathFromRoot(zig_file)) catch unreachable;
  294. zig_args.append("--cache-dir") catch unreachable;
  295. zig_args.append(builder.pathFromRoot(builder.cache_root.path.?)) catch unreachable;
  296. zig_args.append("--listen=-") catch unreachable;
  297. const argv = zig_args.items;
  298. var code: u8 = undefined;
  299. const file_name = self.eval(argv, &code, prog_node) catch |err| {
  300. self.printErrors();
  301. switch (err) {
  302. error.FileNotFound => {
  303. print("{s}{s}: Unable to spawn the following command: file not found{s}\n", .{ red_text, self.exercise.main_file, reset_text });
  304. for (argv) |v| print("{s} ", .{v});
  305. print("\n", .{});
  306. },
  307. error.ExitCodeFailure => {
  308. print("{s}{s}: The following command exited with error code {}:{s}\n", .{ red_text, self.exercise.main_file, code, reset_text });
  309. for (argv) |v| print("{s} ", .{v});
  310. print("\n", .{});
  311. },
  312. error.ProcessTerminated => {
  313. print("{s}{s}: The following command terminated unexpectedly:{s}\n", .{ red_text, self.exercise.main_file, reset_text });
  314. for (argv) |v| print("{s} ", .{v});
  315. print("\n", .{});
  316. },
  317. error.ZigIPCError => {
  318. print("{s}{s}: The following command failed to communicate the compilation result:{s}\n", .{
  319. red_text,
  320. self.exercise.main_file,
  321. reset_text,
  322. });
  323. for (argv) |v| print("{s} ", .{v});
  324. print("\n", .{});
  325. },
  326. else => {},
  327. }
  328. return err;
  329. };
  330. self.printErrors();
  331. return file_name;
  332. }
  333. // Code adapted from `std.Build.execAllowFail and `std.Build.Step.evalZigProcess`.
  334. pub fn eval(
  335. self: *ZiglingStep,
  336. argv: []const []const u8,
  337. out_code: *u8,
  338. prog_node: *std.Progress.Node,
  339. ) ![]const u8 {
  340. assert(argv.len != 0);
  341. const b = self.step.owner;
  342. const allocator = b.allocator;
  343. var child = Child.init(argv, allocator);
  344. child.env_map = b.env_map;
  345. child.stdin_behavior = .Pipe;
  346. child.stdout_behavior = .Pipe;
  347. child.stderr_behavior = .Pipe;
  348. try child.spawn();
  349. var poller = std.io.poll(allocator, enum { stdout, stderr }, .{
  350. .stdout = child.stdout.?,
  351. .stderr = child.stderr.?,
  352. });
  353. defer poller.deinit();
  354. try ipc.sendMessage(child.stdin.?, .update);
  355. try ipc.sendMessage(child.stdin.?, .exit);
  356. const Header = std.zig.Server.Message.Header;
  357. var result: ?[]const u8 = null;
  358. var node_name: std.ArrayListUnmanaged(u8) = .{};
  359. defer node_name.deinit(allocator);
  360. var sub_prog_node = prog_node.start("", 0);
  361. defer sub_prog_node.end();
  362. const stdout = poller.fifo(.stdout);
  363. poll: while (true) {
  364. while (stdout.readableLength() < @sizeOf(Header)) {
  365. if (!(try poller.poll())) break :poll;
  366. }
  367. const header = stdout.reader().readStruct(Header) catch unreachable;
  368. while (stdout.readableLength() < header.bytes_len) {
  369. if (!(try poller.poll())) break :poll;
  370. }
  371. const body = stdout.readableSliceOfLen(header.bytes_len);
  372. switch (header.tag) {
  373. .zig_version => {
  374. if (!std.mem.eql(u8, builtin.zig_version_string, body))
  375. return error.ZigVersionMismatch;
  376. },
  377. .error_bundle => {
  378. self.result_error_bundle = try ipc.parseErrorBundle(allocator, body);
  379. },
  380. .progress => {
  381. node_name.clearRetainingCapacity();
  382. try node_name.appendSlice(allocator, body);
  383. sub_prog_node.setName(node_name.items);
  384. },
  385. .emit_bin_path => {
  386. const emit_bin = try ipc.parseEmitBinPath(allocator, body);
  387. result = emit_bin.path;
  388. },
  389. else => {}, // ignore other messages
  390. }
  391. stdout.discard(body.len);
  392. }
  393. const stderr = poller.fifo(.stderr);
  394. if (stderr.readableLength() > 0) {
  395. self.result_messages = try stderr.toOwnedSlice();
  396. }
  397. // Send EOF to stdin.
  398. child.stdin.?.close();
  399. child.stdin = null;
  400. // Keep the errors compatible with std.Build.execAllowFail.
  401. const term = try child.wait();
  402. switch (term) {
  403. .Exited => |code| {
  404. if (code != 0) {
  405. out_code.* = @truncate(u8, code);
  406. return error.ExitCodeFailure;
  407. }
  408. },
  409. .Signal, .Stopped, .Unknown => |code| {
  410. out_code.* = @truncate(u8, code);
  411. return error.ProcessTerminated;
  412. },
  413. }
  414. return result orelse return error.ZigIPCError;
  415. }
  416. fn printErrors(self: *ZiglingStep) void {
  417. resetLine();
  418. // Print the additional log and verbose messages.
  419. // TODO: use colors?
  420. if (self.result_messages.len > 0) print("{s}", .{self.result_messages});
  421. // Print the compiler errors.
  422. // TODO: use the same ttyconf from the builder.
  423. const ttyconf: std.debug.TTY.Config = if (use_color_escapes)
  424. .escape_codes
  425. else
  426. .no_color;
  427. if (self.result_error_bundle.errorMessageCount() > 0) {
  428. self.result_error_bundle.renderToStdErr(.{ .ttyconf = ttyconf });
  429. }
  430. }
  431. };
  432. // Clear the entire line and move the cursor to column zero.
  433. // Used for clearing the compiler and build_runner progress messages.
  434. fn resetLine() void {
  435. if (use_color_escapes) print("{s}", .{"\x1b[2K\r"});
  436. }
  437. // Print a message to stderr.
  438. const PrintStep = struct {
  439. step: Step,
  440. message: []const u8,
  441. pub fn create(owner: *Build, message: []const u8) *PrintStep {
  442. const self = owner.allocator.create(PrintStep) catch @panic("OOM");
  443. self.* = .{
  444. .step = Step.init(.{
  445. .id = .custom,
  446. .name = "print",
  447. .owner = owner,
  448. .makeFn = make,
  449. }),
  450. .message = message,
  451. };
  452. return self;
  453. }
  454. fn make(step: *Step, prog_node: *std.Progress.Node) !void {
  455. _ = prog_node;
  456. const p = @fieldParentPtr(PrintStep, "step", step);
  457. print("{s}", .{p.message});
  458. }
  459. };
  460. // Skip an exercise.
  461. const SkipStep = struct {
  462. step: Step,
  463. exercise: Exercise,
  464. pub fn create(owner: *Build, exercise: Exercise) *SkipStep {
  465. const self = owner.allocator.create(SkipStep) catch @panic("OOM");
  466. self.* = .{
  467. .step = Step.init(.{
  468. .id = .custom,
  469. .name = owner.fmt("skip {s}", .{exercise.main_file}),
  470. .owner = owner,
  471. .makeFn = make,
  472. }),
  473. .exercise = exercise,
  474. };
  475. return self;
  476. }
  477. fn make(step: *Step, prog_node: *std.Progress.Node) !void {
  478. _ = prog_node;
  479. const p = @fieldParentPtr(SkipStep, "step", step);
  480. if (p.exercise.skip) {
  481. print("{s} skipped\n", .{p.exercise.main_file});
  482. }
  483. }
  484. };
  485. // Check that each exercise number, excluding the last, forms the sequence
  486. // `[1, exercise.len)`.
  487. //
  488. // Additionally check that the output field does not contain trailing whitespace.
  489. fn validate_exercises() bool {
  490. // Don't use the "multi-object for loop" syntax, in order to avoid a syntax
  491. // error with old Zig compilers.
  492. var i: usize = 0;
  493. for (exercises[0 .. exercises.len - 1]) |ex| {
  494. i += 1;
  495. if (ex.number() != i) {
  496. print("exercise {s} has an incorrect number: expected {}, got {s}\n", .{
  497. ex.main_file,
  498. i,
  499. ex.key(),
  500. });
  501. return false;
  502. }
  503. const output = std.mem.trimRight(u8, ex.output, " \r\n");
  504. if (output.len != ex.output.len) {
  505. print("exercise {s} output field has extra trailing whitespace\n", .{
  506. ex.main_file,
  507. });
  508. return false;
  509. }
  510. }
  511. return true;
  512. }
  513. const exercises = [_]Exercise{
  514. .{
  515. .main_file = "001_hello.zig",
  516. .output = "Hello world!",
  517. .hint = "DON'T PANIC!\nRead the error above.\nSee how it has something to do with 'main'?\nOpen up the source file as noted and read the comments.\nYou can do this!",
  518. },
  519. .{
  520. .main_file = "002_std.zig",
  521. .output = "Standard Library.",
  522. },
  523. .{
  524. .main_file = "003_assignment.zig",
  525. .output = "55 314159 -11",
  526. .hint = "There are three mistakes in this one!",
  527. },
  528. .{
  529. .main_file = "004_arrays.zig",
  530. .output = "First: 2, Fourth: 7, Length: 8",
  531. .hint = "There are two things to complete here.",
  532. },
  533. .{
  534. .main_file = "005_arrays2.zig",
  535. .output = "LEET: 1337, Bits: 100110011001",
  536. .hint = "Fill in the two arrays.",
  537. },
  538. .{
  539. .main_file = "006_strings.zig",
  540. .output = "d=d ha ha ha Major Tom",
  541. .hint = "Each '???' needs something filled in.",
  542. },
  543. .{
  544. .main_file = "007_strings2.zig",
  545. .output = "Ziggy played guitar\nJamming good with Andrew Kelley\nAnd the Spiders from Mars",
  546. .hint = "Please fix the lyrics!",
  547. },
  548. .{
  549. .main_file = "008_quiz.zig",
  550. .output = "Program in Zig!",
  551. .hint = "See if you can fix the program!",
  552. },
  553. .{
  554. .main_file = "009_if.zig",
  555. .output = "Foo is 1!",
  556. },
  557. .{
  558. .main_file = "010_if2.zig",
  559. .output = "With the discount, the price is $17.",
  560. },
  561. .{
  562. .main_file = "011_while.zig",
  563. .output = "2 4 8 16 32 64 128 256 512 n=1024",
  564. .hint = "You probably want a 'less than' condition.",
  565. },
  566. .{
  567. .main_file = "012_while2.zig",
  568. .output = "2 4 8 16 32 64 128 256 512 n=1024",
  569. .hint = "It might help to look back at the previous exercise.",
  570. },
  571. .{
  572. .main_file = "013_while3.zig",
  573. .output = "1 2 4 7 8 11 13 14 16 17 19",
  574. },
  575. .{
  576. .main_file = "014_while4.zig",
  577. .output = "n=4",
  578. },
  579. .{
  580. .main_file = "015_for.zig",
  581. .output = "A Dramatic Story: :-) :-) :-( :-| :-) The End.",
  582. },
  583. .{
  584. .main_file = "016_for2.zig",
  585. .output = "The value of bits '1101': 13.",
  586. },
  587. .{
  588. .main_file = "017_quiz2.zig",
  589. .output = "1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16,",
  590. .hint = "This is a famous game!",
  591. },
  592. .{
  593. .main_file = "018_functions.zig",
  594. .output = "Answer to the Ultimate Question: 42",
  595. .hint = "Can you help write the function?",
  596. },
  597. .{
  598. .main_file = "019_functions2.zig",
  599. .output = "Powers of two: 2 4 8 16",
  600. },
  601. .{
  602. .main_file = "020_quiz3.zig",
  603. .output = "32 64 128 256",
  604. .hint = "Unexpected pop quiz! Help!",
  605. },
  606. .{
  607. .main_file = "021_errors.zig",
  608. .output = "2<4. 3<4. 4=4. 5>4. 6>4.",
  609. .hint = "What's the deal with fours?",
  610. },
  611. .{
  612. .main_file = "022_errors2.zig",
  613. .output = "I compiled!",
  614. .hint = "Get the error union type right to allow this to compile.",
  615. },
  616. .{
  617. .main_file = "023_errors3.zig",
  618. .output = "a=64, b=22",
  619. },
  620. .{
  621. .main_file = "024_errors4.zig",
  622. .output = "a=20, b=14, c=10",
  623. },
  624. .{
  625. .main_file = "025_errors5.zig",
  626. .output = "a=0, b=19, c=0",
  627. },
  628. .{
  629. .main_file = "026_hello2.zig",
  630. .output = "Hello world!",
  631. .hint = "Try using a try!",
  632. .check_stdout = true,
  633. },
  634. .{
  635. .main_file = "027_defer.zig",
  636. .output = "One Two",
  637. },
  638. .{
  639. .main_file = "028_defer2.zig",
  640. .output = "(Goat) (Cat) (Dog) (Dog) (Goat) (Unknown) done.",
  641. },
  642. .{
  643. .main_file = "029_errdefer.zig",
  644. .output = "Getting number...got 5. Getting number...failed!",
  645. },
  646. .{
  647. .main_file = "030_switch.zig",
  648. .output = "ZIG?",
  649. },
  650. .{
  651. .main_file = "031_switch2.zig",
  652. .output = "ZIG!",
  653. },
  654. .{
  655. .main_file = "032_unreachable.zig",
  656. .output = "1 2 3 9 8 7",
  657. },
  658. .{
  659. .main_file = "033_iferror.zig",
  660. .output = "2<4. 3<4. 4=4. 5>4. 6>4.",
  661. .hint = "Seriously, what's the deal with fours?",
  662. },
  663. .{
  664. .main_file = "034_quiz4.zig",
  665. .output = "my_num=42",
  666. .hint = "Can you make this work?",
  667. .check_stdout = true,
  668. },
  669. .{
  670. .main_file = "035_enums.zig",
  671. .output = "1 2 3 9 8 7",
  672. .hint = "This problem seems familiar...",
  673. },
  674. .{
  675. .main_file = "036_enums2.zig",
  676. .output = "<p>\n <span style=\"color: #ff0000\">Red</span>\n <span style=\"color: #00ff00\">Green</span>\n <span style=\"color: #0000ff\">Blue</span>\n</p>",
  677. .hint = "I'm feeling blue about this.",
  678. },
  679. .{
  680. .main_file = "037_structs.zig",
  681. .output = "Your wizard has 90 health and 25 gold.",
  682. },
  683. .{
  684. .main_file = "038_structs2.zig",
  685. .output = "Character 1 - G:20 H:100 XP:10\nCharacter 2 - G:10 H:100 XP:20",
  686. },
  687. .{
  688. .main_file = "039_pointers.zig",
  689. .output = "num1: 5, num2: 5",
  690. .hint = "Pointers aren't so bad.",
  691. },
  692. .{
  693. .main_file = "040_pointers2.zig",
  694. .output = "a: 12, b: 12",
  695. },
  696. .{
  697. .main_file = "041_pointers3.zig",
  698. .output = "foo=6, bar=11",
  699. },
  700. .{
  701. .main_file = "042_pointers4.zig",
  702. .output = "num: 5, more_nums: 1 1 5 1",
  703. },
  704. .{
  705. .main_file = "043_pointers5.zig",
  706. .output = "Wizard (G:10 H:100 XP:20)\n Mentor: Wizard (G:10000 H:100 XP:2340)",
  707. },
  708. .{
  709. .main_file = "044_quiz5.zig",
  710. .output = "Elephant A. Elephant B. Elephant C.",
  711. .hint = "Oh no! We forgot Elephant B!",
  712. },
  713. .{
  714. .main_file = "045_optionals.zig",
  715. .output = "The Ultimate Answer: 42.",
  716. },
  717. .{
  718. .main_file = "046_optionals2.zig",
  719. .output = "Elephant A. Elephant B. Elephant C.",
  720. .hint = "Elephants again!",
  721. },
  722. .{
  723. .main_file = "047_methods.zig",
  724. .output = "5 aliens. 4 aliens. 1 aliens. 0 aliens. Earth is saved!",
  725. .hint = "Use the heat ray. And the method!",
  726. },
  727. .{
  728. .main_file = "048_methods2.zig",
  729. .output = "A B C",
  730. .hint = "This just needs one little fix.",
  731. },
  732. .{
  733. .main_file = "049_quiz6.zig",
  734. .output = "A B C Cv Bv Av",
  735. .hint = "Now you're writing Zig!",
  736. },
  737. .{
  738. .main_file = "050_no_value.zig",
  739. .output = "That is not dead which can eternal lie / And with strange aeons even death may die.",
  740. },
  741. .{
  742. .main_file = "051_values.zig",
  743. .output = "1:false!. 2:true!. 3:true!. XP before:0, after:200.",
  744. },
  745. .{
  746. .main_file = "052_slices.zig",
  747. .output = "Hand1: A 4 K 8 \nHand2: 5 2 Q J",
  748. },
  749. .{
  750. .main_file = "053_slices2.zig",
  751. .output = "'all your base are belong to us.' 'for great justice.'",
  752. },
  753. .{
  754. .main_file = "054_manypointers.zig",
  755. .output = "Memory is a resource.",
  756. },
  757. .{
  758. .main_file = "055_unions.zig",
  759. .output = "Insect report! Ant alive is: true. Bee visited 15 flowers.",
  760. },
  761. .{
  762. .main_file = "056_unions2.zig",
  763. .output = "Insect report! Ant alive is: true. Bee visited 16 flowers.",
  764. },
  765. .{
  766. .main_file = "057_unions3.zig",
  767. .output = "Insect report! Ant alive is: true. Bee visited 17 flowers.",
  768. },
  769. .{
  770. .main_file = "058_quiz7.zig",
  771. .output = "Archer's Point--2->Bridge--1->Dogwood Grove--3->Cottage--2->East Pond--1->Fox Pond",
  772. .hint = "This is the biggest program we've seen yet. But you can do it!",
  773. },
  774. .{
  775. .main_file = "059_integers.zig",
  776. .output = "Zig is cool.",
  777. },
  778. .{
  779. .main_file = "060_floats.zig",
  780. .output = "Shuttle liftoff weight: 1995796kg",
  781. },
  782. .{
  783. .main_file = "061_coercions.zig",
  784. .output = "Letter: A",
  785. },
  786. .{
  787. .main_file = "062_loop_expressions.zig",
  788. .output = "Current language: Zig",
  789. .hint = "Surely the current language is 'Zig'!",
  790. },
  791. .{
  792. .main_file = "063_labels.zig",
  793. .output = "Enjoy your Cheesy Chili!",
  794. },
  795. .{
  796. .main_file = "064_builtins.zig",
  797. .output = "1101 + 0101 = 0010 (true). Without overflow: 00010010. Furthermore, 11110000 backwards is 00001111.",
  798. },
  799. .{
  800. .main_file = "065_builtins2.zig",
  801. .output = "A Narcissus loves all Narcissuses. He has room in his heart for: me myself.",
  802. },
  803. .{
  804. .main_file = "066_comptime.zig",
  805. .output = "Immutable: 12345, 987.654; Mutable: 54321, 456.789; Types: comptime_int, comptime_float, u32, f32",
  806. .hint = "It may help to read this one out loud to your favorite stuffed animal until it sinks in completely.",
  807. },
  808. .{
  809. .main_file = "067_comptime2.zig",
  810. .output = "A BB CCC DDDD",
  811. },
  812. .{
  813. .main_file = "068_comptime3.zig",
  814. .output = "Minnow (1:32, 4 x 2)\nShark (1:16, 8 x 5)\nWhale (1:1, 143 x 95)",
  815. },
  816. .{
  817. .main_file = "069_comptime4.zig",
  818. .output = "s1={ 1, 2, 3 }, s2={ 1, 2, 3, 4, 5 }, s3={ 1, 2, 3, 4, 5, 6, 7 }",
  819. },
  820. .{
  821. .main_file = "070_comptime5.zig",
  822. .output = "\"Quack.\" ducky1: true, \"Squeek!\" ducky2: true, ducky3: false",
  823. .hint = "Have you kept the wizard hat on?",
  824. },
  825. .{
  826. .main_file = "071_comptime6.zig",
  827. .output = "Narcissus has room in his heart for: me myself.",
  828. },
  829. .{
  830. .main_file = "072_comptime7.zig",
  831. .output = "26",
  832. },
  833. .{
  834. .main_file = "073_comptime8.zig",
  835. .output = "My llama value is 25.",
  836. },
  837. .{
  838. .main_file = "074_comptime9.zig",
  839. .output = "My llama value is 2.",
  840. },
  841. .{
  842. .main_file = "075_quiz8.zig",
  843. .output = "Archer's Point--2->Bridge--1->Dogwood Grove--3->Cottage--2->East Pond--1->Fox Pond",
  844. .hint = "Roll up those sleeves. You get to WRITE some code for this one.",
  845. },
  846. .{
  847. .main_file = "076_sentinels.zig",
  848. .output = "Array:123056. Many-item pointer:123.",
  849. },
  850. .{
  851. .main_file = "077_sentinels2.zig",
  852. .output = "Weird Data!",
  853. },
  854. .{
  855. .main_file = "078_sentinels3.zig",
  856. .output = "Weird Data!",
  857. },
  858. .{
  859. .main_file = "079_quoted_identifiers.zig",
  860. .output = "Sweet freedom: 55, false.",
  861. .hint = "Help us, Zig Programmer, you're our only hope!",
  862. },
  863. .{
  864. .main_file = "080_anonymous_structs.zig",
  865. .output = "[Circle(i32): 25,70,15] [Circle(f32): 25.2,71.0,15.7]",
  866. },
  867. .{
  868. .main_file = "081_anonymous_structs2.zig",
  869. .output = "x:205 y:187 radius:12",
  870. },
  871. .{
  872. .main_file = "082_anonymous_structs3.zig",
  873. .output = "\"0\"(bool):true \"1\"(bool):false \"2\"(i32):42 \"3\"(f32):3.14159202e+00",
  874. .hint = "This one is a challenge! But you have everything you need.",
  875. },
  876. .{
  877. .main_file = "083_anonymous_lists.zig",
  878. .output = "I say hello!",
  879. },
  880. // Skipped because of https://github.com/ratfactor/ziglings/issues/163
  881. // direct link: https://github.com/ziglang/zig/issues/6025
  882. .{
  883. .main_file = "084_async.zig",
  884. .output = "foo() A",
  885. .hint = "Read the facts. Use the facts.",
  886. .skip = true,
  887. },
  888. .{
  889. .main_file = "085_async2.zig",
  890. .output = "Hello async!",
  891. .skip = true,
  892. },
  893. .{
  894. .main_file = "086_async3.zig",
  895. .output = "5 4 3 2 1",
  896. .skip = true,
  897. },
  898. .{
  899. .main_file = "087_async4.zig",
  900. .output = "1 2 3 4 5",
  901. .skip = true,
  902. },
  903. .{
  904. .main_file = "088_async5.zig",
  905. .output = "Example Title.",
  906. .skip = true,
  907. },
  908. .{
  909. .main_file = "089_async6.zig",
  910. .output = ".com: Example Title, .org: Example Title.",
  911. .skip = true,
  912. },
  913. .{
  914. .main_file = "090_async7.zig",
  915. .output = "beef? BEEF!",
  916. .skip = true,
  917. },
  918. .{
  919. .main_file = "091_async8.zig",
  920. .output = "ABCDEF",
  921. .skip = true,
  922. },
  923. .{
  924. .main_file = "092_interfaces.zig",
  925. .output = "Daily Insect Report:\nAnt is alive.\nBee visited 17 flowers.\nGrasshopper hopped 32 meters.",
  926. },
  927. .{
  928. .main_file = "093_hello_c.zig",
  929. .output = "Hello C from Zig! - C result is 17 chars written.",
  930. .C = true,
  931. },
  932. .{
  933. .main_file = "094_c_math.zig",
  934. .output = "The normalized angle of 765.2 degrees is 45.2 degrees.",
  935. .C = true,
  936. },
  937. .{
  938. .main_file = "095_for3.zig",
  939. .output = "1 2 4 7 8 11 13 14 16 17 19",
  940. },
  941. .{
  942. .main_file = "096_memory_allocation.zig",
  943. .output = "Running Average: 0.30 0.25 0.20 0.18 0.22",
  944. },
  945. .{
  946. .main_file = "097_bit_manipulation.zig",
  947. .output = "x = 0; y = 1",
  948. },
  949. .{
  950. .main_file = "098_bit_manipulation2.zig",
  951. .output = "Is this a pangram? true!",
  952. },
  953. .{
  954. .main_file = "099_formatting.zig",
  955. .output = "\n X | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 \n---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n 1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 \n\n 2 | 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 \n\n 3 | 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 \n\n 4 | 4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 \n\n 5 | 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 \n\n 6 | 6 12 18 24 30 36 42 48 54 60 66 72 78 84 90 \n\n 7 | 7 14 21 28 35 42 49 56 63 70 77 84 91 98 105 \n\n 8 | 8 16 24 32 40 48 56 64 72 80 88 96 104 112 120 \n\n 9 | 9 18 27 36 45 54 63 72 81 90 99 108 117 126 135 \n\n10 | 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 \n\n11 | 11 22 33 44 55 66 77 88 99 110 121 132 143 154 165 \n\n12 | 12 24 36 48 60 72 84 96 108 120 132 144 156 168 180 \n\n13 | 13 26 39 52 65 78 91 104 117 130 143 156 169 182 195 \n\n14 | 14 28 42 56 70 84 98 112 126 140 154 168 182 196 210 \n\n15 | 15 30 45 60 75 90 105 120 135 150 165 180 195 210 225",
  956. },
  957. .{
  958. .main_file = "100_for4.zig",
  959. .output = "Arrays match!",
  960. },
  961. .{
  962. .main_file = "999_the_end.zig",
  963. .output = "\nThis is the end for now!\nWe hope you had fun and were able to learn a lot, so visit us again when the next exercises are available.",
  964. },
  965. };