build.zig 36 KB

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