build.zig 36 KB

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