build.zig 37 KB

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