build.zig 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  1. const std = @import("std");
  2. const builtin = @import("builtin");
  3. const tests = @import("test/tests.zig");
  4. const Build = std.Build;
  5. const CompileStep = Build.CompileStep;
  6. const Step = Build.Step;
  7. const Child = std.process.Child;
  8. const assert = std.debug.assert;
  9. const join = std.fs.path.join;
  10. const print = std.debug.print;
  11. // When changing this version, be sure to also update README.md in two places:
  12. // 1) Getting Started
  13. // 2) Version Changes
  14. comptime {
  15. const required_zig = "0.15.0-dev.1380";
  16. const current_zig = builtin.zig_version;
  17. const min_zig = std.SemanticVersion.parse(required_zig) catch unreachable;
  18. if (current_zig.order(min_zig) == .lt) {
  19. const error_message =
  20. \\Sorry, it looks like your version of zig is too old. :-(
  21. \\
  22. \\Ziglings requires development build
  23. \\
  24. \\{}
  25. \\
  26. \\or higher.
  27. \\
  28. \\Please download a development ("master") build from
  29. \\
  30. \\https://ziglang.org/download/
  31. \\
  32. \\
  33. ;
  34. @compileError(std.fmt.comptimePrint(error_message, .{min_zig}));
  35. }
  36. }
  37. const Kind = enum {
  38. /// Run the artifact as a normal executable.
  39. exe,
  40. /// Run the artifact as a test.
  41. @"test",
  42. };
  43. pub const Exercise = struct {
  44. /// main_file must have the format key_name.zig.
  45. /// The key will be used as a shorthand to build just one example.
  46. main_file: []const u8,
  47. /// This is the desired output of the program.
  48. /// A program passes if its output, excluding trailing whitespace, is equal
  49. /// to this string.
  50. output: []const u8,
  51. /// This is an optional hint to give if the program does not succeed.
  52. hint: ?[]const u8 = null,
  53. /// By default, we verify output against stderr.
  54. /// Set this to true to check stdout instead.
  55. check_stdout: bool = false,
  56. /// This exercise makes use of C functions.
  57. /// We need to keep track of this, so we compile with libc.
  58. link_libc: bool = false,
  59. /// This exercise kind.
  60. kind: Kind = .exe,
  61. /// This exercise is not supported by the current Zig compiler.
  62. skip: bool = false,
  63. /// Returns the name of the main file with .zig stripped.
  64. pub fn name(self: Exercise) []const u8 {
  65. return std.fs.path.stem(self.main_file);
  66. }
  67. /// Returns the key of the main file, the string before the '_' with
  68. /// "zero padding" removed.
  69. /// For example, "001_hello.zig" has the key "1".
  70. pub fn key(self: Exercise) []const u8 {
  71. // Main file must be key_description.zig.
  72. const end_index = std.mem.indexOfScalar(u8, self.main_file, '_') orelse
  73. unreachable;
  74. // Remove zero padding by advancing index past '0's.
  75. var start_index: usize = 0;
  76. while (self.main_file[start_index] == '0') start_index += 1;
  77. return self.main_file[start_index..end_index];
  78. }
  79. /// Returns the exercise key as an integer.
  80. pub fn number(self: Exercise) usize {
  81. return std.fmt.parseInt(usize, self.key(), 10) catch unreachable;
  82. }
  83. };
  84. /// Build mode.
  85. const Mode = enum {
  86. /// Normal build mode: `zig build`
  87. normal,
  88. /// Named build mode: `zig build -Dn=n`
  89. named,
  90. /// Random build mode: `zig build -Drandom`
  91. random,
  92. };
  93. pub const logo =
  94. \\ _ _ _
  95. \\ ___(_) __ _| (_)_ __ __ _ ___
  96. \\ |_ | |/ _' | | | '_ \ / _' / __|
  97. \\ / /| | (_| | | | | | | (_| \__ \
  98. \\ /___|_|\__, |_|_|_| |_|\__, |___/
  99. \\ |___/ |___/
  100. \\
  101. \\ "Look out! Broken programs below!"
  102. \\
  103. \\
  104. ;
  105. const progress_filename = ".progress.txt";
  106. pub fn build(b: *Build) !void {
  107. if (!validate_exercises()) std.process.exit(2);
  108. use_color_escapes = false;
  109. if (std.fs.File.stderr().supportsAnsiEscapeCodes()) {
  110. use_color_escapes = true;
  111. } else if (builtin.os.tag == .windows) {
  112. const w32 = struct {
  113. const DWORD = std.os.windows.DWORD;
  114. const ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004;
  115. const STD_ERROR_HANDLE: DWORD = @bitCast(@as(i32, -12));
  116. const GetStdHandle = std.os.windows.kernel32.GetStdHandle;
  117. const GetConsoleMode = std.os.windows.kernel32.GetConsoleMode;
  118. const SetConsoleMode = std.os.windows.kernel32.SetConsoleMode;
  119. };
  120. const handle = w32.GetStdHandle(w32.STD_ERROR_HANDLE).?;
  121. var mode: w32.DWORD = 0;
  122. if (w32.GetConsoleMode(handle, &mode) != 0) {
  123. mode |= w32.ENABLE_VIRTUAL_TERMINAL_PROCESSING;
  124. use_color_escapes = w32.SetConsoleMode(handle, mode) != 0;
  125. }
  126. }
  127. if (use_color_escapes) {
  128. red_text = "\x1b[31m";
  129. red_bold_text = "\x1b[31;1m";
  130. red_dim_text = "\x1b[31;2m";
  131. green_text = "\x1b[32m";
  132. bold_text = "\x1b[1m";
  133. reset_text = "\x1b[0m";
  134. }
  135. // Remove the standard install and uninstall steps.
  136. b.top_level_steps = .{};
  137. const healed = b.option(bool, "healed", "Run exercises from patches/healed") orelse
  138. false;
  139. const override_healed_path = b.option([]const u8, "healed-path", "Override healed path");
  140. const exno: ?usize = b.option(usize, "n", "Select exercise");
  141. const rand: ?bool = b.option(bool, "random", "Select random exercise");
  142. const start: ?usize = b.option(usize, "s", "Start at exercise");
  143. const reset: ?bool = b.option(bool, "reset", "Reset exercise progress");
  144. const sep = std.fs.path.sep_str;
  145. const healed_path = if (override_healed_path) |path|
  146. path
  147. else
  148. "patches" ++ sep ++ "healed";
  149. const work_path = if (healed) healed_path else "exercises";
  150. const header_step = PrintStep.create(b, logo);
  151. if (exno) |n| {
  152. // Named build mode: verifies a single exercise.
  153. if (n == 0 or n > exercises.len - 1) {
  154. print("unknown exercise number: {}\n", .{n});
  155. std.process.exit(2);
  156. }
  157. const ex = exercises[n - 1];
  158. const zigling_step = b.step(
  159. "zigling",
  160. b.fmt("Check the solution of {s}", .{ex.main_file}),
  161. );
  162. b.default_step = zigling_step;
  163. zigling_step.dependOn(&header_step.step);
  164. const verify_step = ZiglingStep.create(b, ex, work_path, .named);
  165. verify_step.step.dependOn(&header_step.step);
  166. zigling_step.dependOn(&verify_step.step);
  167. return;
  168. }
  169. if (rand) |_| {
  170. // Random build mode: verifies one random exercise.
  171. // like for 'exno' but chooses a random exercise number.
  172. print("work in progress: check a random exercise\n", .{});
  173. var prng = std.Random.DefaultPrng.init(blk: {
  174. var seed: u64 = undefined;
  175. try std.posix.getrandom(std.mem.asBytes(&seed));
  176. break :blk seed;
  177. });
  178. const rnd = prng.random();
  179. const ex = exercises[rnd.intRangeLessThan(usize, 0, exercises.len)];
  180. print("random exercise: {s}\n", .{ex.main_file});
  181. const zigling_step = b.step(
  182. "random",
  183. b.fmt("Check the solution of {s}", .{ex.main_file}),
  184. );
  185. b.default_step = zigling_step;
  186. zigling_step.dependOn(&header_step.step);
  187. const verify_step = ZiglingStep.create(b, ex, work_path, .random);
  188. verify_step.step.dependOn(&header_step.step);
  189. zigling_step.dependOn(&verify_step.step);
  190. return;
  191. }
  192. if (start) |s| {
  193. if (s == 0 or s > exercises.len - 1) {
  194. print("unknown exercise number: {}\n", .{s});
  195. std.process.exit(2);
  196. }
  197. const first = exercises[s - 1];
  198. const ziglings_step = b.step("ziglings", b.fmt("Check ziglings starting with {s}", .{first.main_file}));
  199. b.default_step = ziglings_step;
  200. var prev_step = &header_step.step;
  201. for (exercises[(s - 1)..]) |ex| {
  202. const verify_stepn = ZiglingStep.create(b, ex, work_path, .normal);
  203. verify_stepn.step.dependOn(prev_step);
  204. prev_step = &verify_stepn.step;
  205. }
  206. ziglings_step.dependOn(prev_step);
  207. return;
  208. }
  209. if (reset) |_| {
  210. std.fs.cwd().deleteFile(progress_filename) catch |err| {
  211. switch (err) {
  212. std.fs.Dir.DeleteFileError.FileNotFound => {},
  213. else => {
  214. print("Unable to remove progress file, Error: {}\n", .{err});
  215. return err;
  216. },
  217. }
  218. };
  219. print("Progress reset, {s} removed.\n", .{progress_filename});
  220. std.process.exit(0);
  221. }
  222. // Normal build mode: verifies all exercises according to the recommended
  223. // order.
  224. const ziglings_step = b.step("ziglings", "Check all ziglings");
  225. b.default_step = ziglings_step;
  226. var prev_step = &header_step.step;
  227. var starting_exercise: u32 = 0;
  228. if (std.fs.cwd().openFile(progress_filename, .{})) |progress_file| {
  229. defer progress_file.close();
  230. const progress_file_size = try progress_file.getEndPos();
  231. var gpa = std.heap.GeneralPurposeAllocator(.{}){};
  232. defer _ = gpa.deinit();
  233. const allocator = gpa.allocator();
  234. const contents = try progress_file.readToEndAlloc(allocator, progress_file_size);
  235. defer allocator.free(contents);
  236. starting_exercise = try std.fmt.parseInt(u32, contents, 10);
  237. } else |err| {
  238. switch (err) {
  239. std.fs.File.OpenError.FileNotFound => {
  240. // This is fine, may be the first time tests are run or progress have been reset
  241. },
  242. else => {
  243. print("Unable to open {s}: {}\n", .{ progress_filename, err });
  244. return err;
  245. },
  246. }
  247. }
  248. for (exercises) |ex| {
  249. if (starting_exercise < ex.number()) {
  250. const verify_stepn = ZiglingStep.create(b, ex, work_path, .normal);
  251. verify_stepn.step.dependOn(prev_step);
  252. prev_step = &verify_stepn.step;
  253. }
  254. }
  255. ziglings_step.dependOn(prev_step);
  256. const test_step = b.step("test", "Run all the tests");
  257. test_step.dependOn(tests.addCliTests(b, &exercises));
  258. }
  259. var use_color_escapes = false;
  260. var red_text: []const u8 = "";
  261. var red_bold_text: []const u8 = "";
  262. var red_dim_text: []const u8 = "";
  263. var green_text: []const u8 = "";
  264. var bold_text: []const u8 = "";
  265. var reset_text: []const u8 = "";
  266. const ZiglingStep = struct {
  267. step: Step,
  268. exercise: Exercise,
  269. work_path: []const u8,
  270. mode: Mode,
  271. pub fn create(
  272. b: *Build,
  273. exercise: Exercise,
  274. work_path: []const u8,
  275. mode: Mode,
  276. ) *ZiglingStep {
  277. const self = b.allocator.create(ZiglingStep) catch @panic("OOM");
  278. self.* = .{
  279. .step = Step.init(.{
  280. .id = .custom,
  281. .name = exercise.main_file,
  282. .owner = b,
  283. .makeFn = make,
  284. }),
  285. .exercise = exercise,
  286. .work_path = work_path,
  287. .mode = mode,
  288. };
  289. return self;
  290. }
  291. fn make(step: *Step, options: Step.MakeOptions) !void {
  292. // NOTE: Using exit code 2 will prevent the Zig compiler to print the message:
  293. // "error: the following build command failed with exit code 1:..."
  294. const self: *ZiglingStep = @alignCast(@fieldParentPtr("step", step));
  295. if (self.exercise.skip) {
  296. print("Skipping {s}\n\n", .{self.exercise.main_file});
  297. return;
  298. }
  299. const exe_path = self.compile(options.progress_node) catch {
  300. self.printErrors();
  301. if (self.exercise.hint) |hint|
  302. print("\n{s}Ziglings hint: {s}{s}", .{ bold_text, hint, reset_text });
  303. self.help();
  304. std.process.exit(2);
  305. };
  306. self.run(exe_path, options.progress_node) catch {
  307. self.printErrors();
  308. if (self.exercise.hint) |hint|
  309. print("\n{s}Ziglings hint: {s}{s}", .{ bold_text, hint, reset_text });
  310. self.help();
  311. std.process.exit(2);
  312. };
  313. // Print possible warning/debug messages.
  314. self.printErrors();
  315. }
  316. fn run(self: *ZiglingStep, exe_path: []const u8, _: std.Progress.Node) !void {
  317. resetLine();
  318. print("Checking: {s}\n", .{self.exercise.main_file});
  319. const b = self.step.owner;
  320. // Allow up to 1 MB of stdout capture.
  321. const max_output_bytes = 1 * 1024 * 1024;
  322. const result = Child.run(.{
  323. .allocator = b.allocator,
  324. .argv = &.{exe_path},
  325. .cwd = b.build_root.path.?,
  326. .cwd_dir = b.build_root.handle,
  327. .max_output_bytes = max_output_bytes,
  328. }) catch |err| {
  329. return self.step.fail("unable to spawn {s}: {s}", .{
  330. exe_path, @errorName(err),
  331. });
  332. };
  333. switch (self.exercise.kind) {
  334. .exe => return self.check_output(result),
  335. .@"test" => return self.check_test(result),
  336. }
  337. }
  338. fn check_output(self: *ZiglingStep, result: Child.RunResult) !void {
  339. const b = self.step.owner;
  340. // Make sure it exited cleanly.
  341. switch (result.term) {
  342. .Exited => |code| {
  343. if (code != 0) {
  344. return self.step.fail("{s} exited with error code {d} (expected {})", .{
  345. self.exercise.main_file, code, 0,
  346. });
  347. }
  348. },
  349. else => {
  350. return self.step.fail("{s} terminated unexpectedly", .{
  351. self.exercise.main_file,
  352. });
  353. },
  354. }
  355. const raw_output = if (self.exercise.check_stdout)
  356. result.stdout
  357. else
  358. result.stderr;
  359. // Validate the output.
  360. // NOTE: exercise.output can never contain a CR character.
  361. // See https://ziglang.org/documentation/master/#Source-Encoding.
  362. const output = trimLines(b.allocator, raw_output) catch @panic("OOM");
  363. const exercise_output = self.exercise.output;
  364. if (!std.mem.eql(u8, output, self.exercise.output)) {
  365. const red = red_bold_text;
  366. const reset = reset_text;
  367. // Override the coloring applied by the printError method.
  368. // NOTE: the first red and the last reset are not necessary, they
  369. // are here only for alignment.
  370. return self.step.fail(
  371. \\
  372. \\{s}========= expected this output: =========={s}
  373. \\{s}
  374. \\{s}========= but found: ====================={s}
  375. \\{s}
  376. \\{s}=========================================={s}
  377. , .{ red, reset, exercise_output, red, reset, output, red, reset });
  378. }
  379. const progress = try std.fmt.allocPrint(b.allocator, "{d}", .{self.exercise.number()});
  380. defer b.allocator.free(progress);
  381. const file = try std.fs.cwd().createFile(
  382. progress_filename,
  383. .{ .read = true, .truncate = true },
  384. );
  385. defer file.close();
  386. try file.writeAll(progress);
  387. try file.sync();
  388. print("{s}PASSED:\n{s}{s}\n\n", .{ green_text, output, reset_text });
  389. }
  390. fn check_test(self: *ZiglingStep, result: Child.RunResult) !void {
  391. switch (result.term) {
  392. .Exited => |code| {
  393. if (code != 0) {
  394. // The test failed.
  395. const stderr = std.mem.trimRight(u8, result.stderr, " \r\n");
  396. return self.step.fail("\n{s}", .{stderr});
  397. }
  398. },
  399. else => {
  400. return self.step.fail("{s} terminated unexpectedly", .{
  401. self.exercise.main_file,
  402. });
  403. },
  404. }
  405. print("{s}PASSED{s}\n\n", .{ green_text, reset_text });
  406. }
  407. fn compile(self: *ZiglingStep, prog_node: std.Progress.Node) ![]const u8 {
  408. print("Compiling: {s}\n", .{self.exercise.main_file});
  409. const b = self.step.owner;
  410. const exercise_path = self.exercise.main_file;
  411. const path = join(b.allocator, &.{ self.work_path, exercise_path }) catch
  412. @panic("OOM");
  413. var zig_args = std.ArrayList([]const u8).init(b.allocator);
  414. defer zig_args.deinit();
  415. zig_args.append(b.graph.zig_exe) catch @panic("OOM");
  416. const cmd = switch (self.exercise.kind) {
  417. .exe => "build-exe",
  418. .@"test" => "test",
  419. };
  420. zig_args.append(cmd) catch @panic("OOM");
  421. // Enable C support for exercises that use C functions.
  422. if (self.exercise.link_libc) {
  423. zig_args.append("-lc") catch @panic("OOM");
  424. }
  425. zig_args.append(b.pathFromRoot(path)) catch @panic("OOM");
  426. zig_args.append("--cache-dir") catch @panic("OOM");
  427. zig_args.append(b.pathFromRoot(b.cache_root.path.?)) catch @panic("OOM");
  428. zig_args.append("--listen=-") catch @panic("OOM");
  429. //
  430. // NOTE: After many changes in zig build system, we need to create the cache path manually.
  431. // See https://github.com/ziglang/zig/pull/21115
  432. // Maybe there is a better way (in the future).
  433. const exe_dir = try self.step.evalZigProcess(zig_args.items, prog_node, false, null, b.allocator);
  434. const exe_name = switch (self.exercise.kind) {
  435. .exe => self.exercise.name(),
  436. .@"test" => "test",
  437. };
  438. const sep = std.fs.path.sep_str;
  439. const root_path = exe_dir.?.root_dir.path.?;
  440. const sub_path = exe_dir.?.subPathOrDot();
  441. const exe_path = b.fmt("{s}{s}{s}{s}{s}", .{ root_path, sep, sub_path, sep, exe_name });
  442. return exe_path;
  443. }
  444. fn help(self: *ZiglingStep) void {
  445. const b = self.step.owner;
  446. const key = self.exercise.key();
  447. const path = self.exercise.main_file;
  448. const cmd = switch (self.mode) {
  449. .normal => "zig build",
  450. .named => b.fmt("zig build -Dn={s}", .{key}),
  451. .random => "zig build -Drandom",
  452. };
  453. print("\n{s}Edit exercises/{s} and run '{s}' again.{s}\n", .{
  454. red_bold_text, path, cmd, reset_text,
  455. });
  456. }
  457. fn printErrors(self: *ZiglingStep) void {
  458. resetLine();
  459. // Display error/warning messages.
  460. if (self.step.result_error_msgs.items.len > 0) {
  461. for (self.step.result_error_msgs.items) |msg| {
  462. print("{s}error: {s}{s}{s}{s}\n", .{
  463. red_bold_text, reset_text, red_dim_text, msg, reset_text,
  464. });
  465. }
  466. }
  467. // Render compile errors at the bottom of the terminal.
  468. // TODO: use the same ttyconf from the builder.
  469. const ttyconf: std.io.tty.Config = if (use_color_escapes)
  470. .escape_codes
  471. else
  472. .no_color;
  473. if (self.step.result_error_bundle.errorMessageCount() > 0) {
  474. self.step.result_error_bundle.renderToStdErr(.{ .ttyconf = ttyconf });
  475. }
  476. }
  477. };
  478. /// Clears the entire line and move the cursor to column zero.
  479. /// Used for clearing the compiler and build_runner progress messages.
  480. fn resetLine() void {
  481. if (use_color_escapes) print("{s}", .{"\x1b[2K\r"});
  482. }
  483. /// Removes trailing whitespace for each line in buf, also ensuring that there
  484. /// are no trailing LF characters at the end.
  485. pub fn trimLines(allocator: std.mem.Allocator, buf: []const u8) ![]const u8 {
  486. var list = try std.ArrayList(u8).initCapacity(allocator, buf.len);
  487. var iter = std.mem.splitSequence(u8, buf, " \n");
  488. while (iter.next()) |line| {
  489. // TODO: trimming CR characters is probably not necessary.
  490. const data = std.mem.trimRight(u8, line, " \r");
  491. try list.appendSlice(data);
  492. try list.append('\n');
  493. }
  494. const result = try list.toOwnedSlice(); // TODO: probably not necessary
  495. // Remove the trailing LF character, that is always present in the exercise
  496. // output.
  497. return std.mem.trimRight(u8, result, "\n");
  498. }
  499. /// Prints a message to stderr.
  500. const PrintStep = struct {
  501. step: Step,
  502. message: []const u8,
  503. pub fn create(owner: *Build, message: []const u8) *PrintStep {
  504. const self = owner.allocator.create(PrintStep) catch @panic("OOM");
  505. self.* = .{
  506. .step = Step.init(.{
  507. .id = .custom,
  508. .name = "print",
  509. .owner = owner,
  510. .makeFn = make,
  511. }),
  512. .message = message,
  513. };
  514. return self;
  515. }
  516. fn make(step: *Step, _: Step.MakeOptions) !void {
  517. const self: *PrintStep = @alignCast(@fieldParentPtr("step", step));
  518. print("{s}", .{self.message});
  519. }
  520. };
  521. /// Checks that each exercise number, excluding the last, forms the sequence
  522. /// `[1, exercise.len)`.
  523. ///
  524. /// Additionally check that the output field lines doesn't have trailing whitespace.
  525. fn validate_exercises() bool {
  526. // Don't use the "multi-object for loop" syntax, in order to avoid a syntax
  527. // error with old Zig compilers.
  528. var i: usize = 0;
  529. for (exercises[0..]) |ex| {
  530. const exno = ex.number();
  531. const last = 999;
  532. i += 1;
  533. if (exno != i and exno != last) {
  534. print("exercise {s} has an incorrect number: expected {}, got {s}\n", .{
  535. ex.main_file, i, ex.key(),
  536. });
  537. return false;
  538. }
  539. var iter = std.mem.splitScalar(u8, ex.output, '\n');
  540. while (iter.next()) |line| {
  541. const output = std.mem.trimRight(u8, line, " \r");
  542. if (output.len != line.len) {
  543. print("exercise {s} output field lines have trailing whitespace\n", .{
  544. ex.main_file,
  545. });
  546. return false;
  547. }
  548. }
  549. if (!std.mem.endsWith(u8, ex.main_file, ".zig")) {
  550. print("exercise {s} is not a zig source file\n", .{ex.main_file});
  551. return false;
  552. }
  553. }
  554. return true;
  555. }
  556. const exercises = [_]Exercise{
  557. .{
  558. .main_file = "001_hello.zig",
  559. .output = "Hello world!",
  560. .hint =
  561. \\DON'T PANIC!
  562. \\Read the compiler messages above. (Something about 'main'?)
  563. \\Open up the source file as noted below and read the comments.
  564. \\
  565. \\(Hints like these will occasionally show up, but for the
  566. \\most part, you'll be taking directions from the Zig
  567. \\compiler itself.)
  568. \\
  569. ,
  570. },
  571. .{
  572. .main_file = "002_std.zig",
  573. .output = "Standard Library.",
  574. },
  575. .{
  576. .main_file = "003_assignment.zig",
  577. .output = "55 314159 -11",
  578. .hint = "There are three mistakes in this one!",
  579. },
  580. .{
  581. .main_file = "004_arrays.zig",
  582. .output = "First: 2, Fourth: 7, Length: 8",
  583. .hint = "There are two things to complete here.",
  584. },
  585. .{
  586. .main_file = "005_arrays2.zig",
  587. .output = "LEET: 1337, Bits: 100110011001",
  588. .hint = "Fill in the two arrays.",
  589. },
  590. .{
  591. .main_file = "006_strings.zig",
  592. .output = "d=d ha ha ha Major Tom",
  593. .hint = "Each '???' needs something filled in.",
  594. },
  595. .{
  596. .main_file = "007_strings2.zig",
  597. .output =
  598. \\Ziggy played guitar
  599. \\Jamming good with Andrew Kelley
  600. \\And the Spiders from Mars
  601. ,
  602. .hint = "Please fix the lyrics!",
  603. },
  604. .{
  605. .main_file = "008_quiz.zig",
  606. .output = "Program in Zig!",
  607. .hint = "See if you can fix the program!",
  608. },
  609. .{
  610. .main_file = "009_if.zig",
  611. .output = "Foo is 1!",
  612. },
  613. .{
  614. .main_file = "010_if2.zig",
  615. .output = "With the discount, the price is $17.",
  616. },
  617. .{
  618. .main_file = "011_while.zig",
  619. .output = "2 4 8 16 32 64 128 256 512 n=1024",
  620. .hint = "You probably want a 'less than' condition.",
  621. },
  622. .{
  623. .main_file = "012_while2.zig",
  624. .output = "2 4 8 16 32 64 128 256 512 n=1024",
  625. .hint = "It might help to look back at the previous exercise.",
  626. },
  627. .{
  628. .main_file = "013_while3.zig",
  629. .output = "1 2 4 7 8 11 13 14 16 17 19",
  630. },
  631. .{
  632. .main_file = "014_while4.zig",
  633. .output = "n=4",
  634. },
  635. .{
  636. .main_file = "015_for.zig",
  637. .output = "A Dramatic Story: :-) :-) :-( :-| :-) The End.",
  638. },
  639. .{
  640. .main_file = "016_for2.zig",
  641. .output = "The value of bits '1101': 13.",
  642. },
  643. .{
  644. .main_file = "017_quiz2.zig",
  645. .output = "1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16,",
  646. .hint = "This is a famous game!",
  647. },
  648. .{
  649. .main_file = "018_functions.zig",
  650. .output = "Answer to the Ultimate Question: 42",
  651. .hint = "Can you help write the function?",
  652. },
  653. .{
  654. .main_file = "019_functions2.zig",
  655. .output = "Powers of two: 2 4 8 16",
  656. },
  657. .{
  658. .main_file = "020_quiz3.zig",
  659. .output = "32 64 128 256",
  660. .hint = "Unexpected pop quiz! Help!",
  661. },
  662. .{
  663. .main_file = "021_errors.zig",
  664. .output = "2<4. 3<4. 4=4. 5>4. 6>4.",
  665. .hint = "What's the deal with fours?",
  666. },
  667. .{
  668. .main_file = "022_errors2.zig",
  669. .output = "I compiled!",
  670. .hint = "Get the error union type right to allow this to compile.",
  671. },
  672. .{
  673. .main_file = "023_errors3.zig",
  674. .output = "a=64, b=22",
  675. },
  676. .{
  677. .main_file = "024_errors4.zig",
  678. .output = "a=20, b=14, c=10",
  679. },
  680. .{
  681. .main_file = "025_errors5.zig",
  682. .output = "a=0, b=19, c=0",
  683. },
  684. .{
  685. .main_file = "026_hello2.zig",
  686. .output = "Hello world!",
  687. .hint = "Try using a try!",
  688. .check_stdout = true,
  689. },
  690. .{
  691. .main_file = "027_defer.zig",
  692. .output = "One Two",
  693. },
  694. .{
  695. .main_file = "028_defer2.zig",
  696. .output = "(Goat) (Cat) (Dog) (Dog) (Goat) (Unknown) done.",
  697. },
  698. .{
  699. .main_file = "029_errdefer.zig",
  700. .output = "Getting number...got 5. Getting number...failed!",
  701. },
  702. .{
  703. .main_file = "030_switch.zig",
  704. .output = "ZIG?",
  705. },
  706. .{
  707. .main_file = "031_switch2.zig",
  708. .output = "ZIG!",
  709. },
  710. .{
  711. .main_file = "032_unreachable.zig",
  712. .output = "1 2 3 9 8 7",
  713. },
  714. .{
  715. .main_file = "033_iferror.zig",
  716. .output = "2<4. 3<4. 4=4. 5>4. 6>4.",
  717. .hint = "Seriously, what's the deal with fours?",
  718. },
  719. .{
  720. .main_file = "034_quiz4.zig",
  721. .output = "my_num=42",
  722. .hint = "Can you make this work?",
  723. .check_stdout = true,
  724. },
  725. .{
  726. .main_file = "035_enums.zig",
  727. .output = "1 2 3 9 8 7",
  728. .hint = "This problem seems familiar...",
  729. },
  730. .{
  731. .main_file = "036_enums2.zig",
  732. .output =
  733. \\<p>
  734. \\ <span style="color: #ff0000">Red</span>
  735. \\ <span style="color: #00ff00">Green</span>
  736. \\ <span style="color: #0000ff">Blue</span>
  737. \\</p>
  738. ,
  739. .hint = "I'm feeling blue about this.",
  740. },
  741. .{
  742. .main_file = "037_structs.zig",
  743. .output = "Your wizard has 90 health and 25 gold.",
  744. },
  745. .{
  746. .main_file = "038_structs2.zig",
  747. .output =
  748. \\Character 1 - G:20 H:100 XP:10
  749. \\Character 2 - G:10 H:100 XP:20
  750. ,
  751. },
  752. .{
  753. .main_file = "039_pointers.zig",
  754. .output = "num1: 5, num2: 5",
  755. .hint = "Pointers aren't so bad.",
  756. },
  757. .{
  758. .main_file = "040_pointers2.zig",
  759. .output = "a: 12, b: 12",
  760. },
  761. .{
  762. .main_file = "041_pointers3.zig",
  763. .output = "foo=6, bar=11",
  764. },
  765. .{
  766. .main_file = "042_pointers4.zig",
  767. .output = "num: 5, more_nums: 1 1 5 1",
  768. },
  769. .{
  770. .main_file = "043_pointers5.zig",
  771. .output =
  772. \\Wizard (G:10 H:100 XP:20)
  773. \\ Mentor: Wizard (G:10000 H:100 XP:2340)
  774. ,
  775. },
  776. .{
  777. .main_file = "044_quiz5.zig",
  778. .output = "Elephant A. Elephant B. Elephant C.",
  779. .hint = "Oh no! We forgot Elephant B!",
  780. },
  781. .{
  782. .main_file = "045_optionals.zig",
  783. .output = "The Ultimate Answer: 42.",
  784. },
  785. .{
  786. .main_file = "046_optionals2.zig",
  787. .output = "Elephant A. Elephant B. Elephant C.",
  788. .hint = "Elephants again!",
  789. },
  790. .{
  791. .main_file = "047_methods.zig",
  792. .output = "5 aliens. 4 aliens. 1 aliens. 0 aliens. Earth is saved!",
  793. .hint = "Use the heat ray. And the method!",
  794. },
  795. .{
  796. .main_file = "048_methods2.zig",
  797. .output = "A B C",
  798. .hint = "This just needs one little fix.",
  799. },
  800. .{
  801. .main_file = "049_quiz6.zig",
  802. .output = "A B C Cv Bv Av",
  803. .hint = "Now you're writing Zig!",
  804. },
  805. .{
  806. .main_file = "050_no_value.zig",
  807. .output = "That is not dead which can eternal lie / And with strange aeons even death may die.",
  808. },
  809. .{
  810. .main_file = "051_values.zig",
  811. .output = "1:false!. 2:true!. 3:true!. XP before:0, after:200.",
  812. },
  813. .{
  814. .main_file = "052_slices.zig",
  815. .output =
  816. \\Hand1: A 4 K 8
  817. \\Hand2: 5 2 Q J
  818. ,
  819. },
  820. .{
  821. .main_file = "053_slices2.zig",
  822. .output = "'all your base are belong to us.' 'for great justice.'",
  823. },
  824. .{
  825. .main_file = "054_manypointers.zig",
  826. .output = "Memory is a resource.",
  827. },
  828. .{
  829. .main_file = "055_unions.zig",
  830. .output = "Insect report! Ant alive is: true. Bee visited 15 flowers.",
  831. },
  832. .{
  833. .main_file = "056_unions2.zig",
  834. .output = "Insect report! Ant alive is: true. Bee visited 16 flowers.",
  835. },
  836. .{
  837. .main_file = "057_unions3.zig",
  838. .output = "Insect report! Ant alive is: true. Bee visited 17 flowers.",
  839. },
  840. .{
  841. .main_file = "058_quiz7.zig",
  842. .output = "Archer's Point--2->Bridge--1->Dogwood Grove--3->Cottage--2->East Pond--1->Fox Pond",
  843. .hint = "This is the biggest program we've seen yet. But you can do it!",
  844. },
  845. .{
  846. .main_file = "059_integers.zig",
  847. .output = "Zig is cool.",
  848. },
  849. .{
  850. .main_file = "060_floats.zig",
  851. .output = "Shuttle liftoff weight: 2032 metric tons",
  852. },
  853. .{
  854. .main_file = "061_coercions.zig",
  855. .output = "Letter: A",
  856. },
  857. .{
  858. .main_file = "062_loop_expressions.zig",
  859. .output = "Current language: Zig",
  860. .hint = "Surely the current language is 'Zig'!",
  861. },
  862. .{
  863. .main_file = "063_labels.zig",
  864. .output = "Enjoy your Cheesy Chili!",
  865. },
  866. .{
  867. .main_file = "064_builtins.zig",
  868. .output = "1101 + 0101 = 0010 (true). Without overflow: 00010010. Furthermore, 11110000 backwards is 00001111.",
  869. },
  870. .{
  871. .main_file = "065_builtins2.zig",
  872. .output = "A Narcissus loves all Narcissuses. He has room in his heart for: me myself.",
  873. },
  874. .{
  875. .main_file = "066_comptime.zig",
  876. .output = "Immutable: 12345, 987.654; Mutable: 54321, 456.789; Types: comptime_int, comptime_float, u32, f32",
  877. .hint = "It may help to read this one out loud to your favorite stuffed animal until it sinks in completely.",
  878. },
  879. .{
  880. .main_file = "067_comptime2.zig",
  881. .output = "A BB CCC DDDD",
  882. },
  883. .{
  884. .main_file = "068_comptime3.zig",
  885. .output =
  886. \\Minnow (1:32, 4 x 2)
  887. \\Shark (1:16, 8 x 5)
  888. \\Whale (1:1, 143 x 95)
  889. ,
  890. },
  891. .{
  892. .main_file = "069_comptime4.zig",
  893. .output = "s1={ 1, 2, 3 }, s2={ 1, 2, 3, 4, 5 }, s3={ 1, 2, 3, 4, 5, 6, 7 }",
  894. },
  895. .{
  896. .main_file = "070_comptime5.zig",
  897. .output =
  898. \\"Quack." ducky1: true, "Squeek!" ducky2: true, ducky3: false
  899. ,
  900. .hint = "Have you kept the wizard hat on?",
  901. },
  902. .{
  903. .main_file = "071_comptime6.zig",
  904. .output = "Narcissus has room in his heart for: me myself.",
  905. },
  906. .{
  907. .main_file = "072_comptime7.zig",
  908. .output = "26",
  909. },
  910. .{
  911. .main_file = "073_comptime8.zig",
  912. .output = "My llama value is 25.",
  913. },
  914. .{
  915. .main_file = "074_comptime9.zig",
  916. .output = "My llama value is 2.",
  917. .skip = true,
  918. },
  919. .{
  920. .main_file = "075_quiz8.zig",
  921. .output = "Archer's Point--2->Bridge--1->Dogwood Grove--3->Cottage--2->East Pond--1->Fox Pond",
  922. .hint = "Roll up those sleeves. You get to WRITE some code for this one.",
  923. },
  924. .{
  925. .main_file = "076_sentinels.zig",
  926. .output = "Array:123056. Many-item pointer:123.",
  927. },
  928. .{
  929. .main_file = "077_sentinels2.zig",
  930. .output = "Weird Data!",
  931. },
  932. .{
  933. .main_file = "078_sentinels3.zig",
  934. .output = "Weird Data!",
  935. },
  936. .{
  937. .main_file = "079_quoted_identifiers.zig",
  938. .output = "Sweet freedom: 55, false.",
  939. .hint = "Help us, Zig Programmer, you're our only hope!",
  940. },
  941. .{
  942. .main_file = "080_anonymous_structs.zig",
  943. .output = "[Circle(i32): 25,70,15] [Circle(f32): 25.2,71.0,15.7]",
  944. },
  945. .{
  946. .main_file = "081_anonymous_structs2.zig",
  947. .output = "x:205 y:187 radius:12",
  948. },
  949. .{
  950. .main_file = "082_anonymous_structs3.zig",
  951. .output =
  952. \\"0"(bool):true "1"(bool):false "2"(i32):42 "3"(f32):3.141592
  953. ,
  954. .hint = "This one is a challenge! But you have everything you need.",
  955. },
  956. .{
  957. .main_file = "083_anonymous_lists.zig",
  958. .output = "I say hello!",
  959. },
  960. // Skipped because of https://github.com/ratfactor/ziglings/issues/163
  961. // direct link: https://github.com/ziglang/zig/issues/6025
  962. .{
  963. .main_file = "084_async.zig",
  964. .output = "foo() A",
  965. .hint = "Read the facts. Use the facts.",
  966. .skip = true,
  967. },
  968. .{
  969. .main_file = "085_async2.zig",
  970. .output = "Hello async!",
  971. .skip = true,
  972. },
  973. .{
  974. .main_file = "086_async3.zig",
  975. .output = "5 4 3 2 1",
  976. .skip = true,
  977. },
  978. .{
  979. .main_file = "087_async4.zig",
  980. .output = "1 2 3 4 5",
  981. .skip = true,
  982. },
  983. .{
  984. .main_file = "088_async5.zig",
  985. .output = "Example Title.",
  986. .skip = true,
  987. },
  988. .{
  989. .main_file = "089_async6.zig",
  990. .output = ".com: Example Title, .org: Example Title.",
  991. .skip = true,
  992. },
  993. .{
  994. .main_file = "090_async7.zig",
  995. .output = "beef? BEEF!",
  996. .skip = true,
  997. },
  998. .{
  999. .main_file = "091_async8.zig",
  1000. .output = "ABCDEF",
  1001. .skip = true,
  1002. },
  1003. .{
  1004. .main_file = "092_interfaces.zig",
  1005. .output =
  1006. \\Daily Insect Report:
  1007. \\Ant is alive.
  1008. \\Bee visited 17 flowers.
  1009. \\Grasshopper hopped 32 meters.
  1010. ,
  1011. },
  1012. .{
  1013. .main_file = "093_hello_c.zig",
  1014. .output = "Hello C from Zig! - C result is 17 chars written.",
  1015. .link_libc = true,
  1016. },
  1017. .{
  1018. .main_file = "094_c_math.zig",
  1019. .output = "The normalized angle of 765.2 degrees is 45.2 degrees.",
  1020. .link_libc = true,
  1021. },
  1022. .{
  1023. .main_file = "095_for3.zig",
  1024. .output = "1 2 4 7 8 11 13 14 16 17 19",
  1025. },
  1026. .{
  1027. .main_file = "096_memory_allocation.zig",
  1028. .output = "Running Average: 0.30 0.25 0.20 0.18 0.22",
  1029. },
  1030. .{
  1031. .main_file = "097_bit_manipulation.zig",
  1032. .output = "x = 1011; y = 1101",
  1033. },
  1034. .{
  1035. .main_file = "098_bit_manipulation2.zig",
  1036. .output = "Is this a pangram? true!",
  1037. },
  1038. .{
  1039. .main_file = "099_formatting.zig",
  1040. .output =
  1041. \\
  1042. \\ X | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  1043. \\---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
  1044. \\ 1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  1045. \\
  1046. \\ 2 | 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30
  1047. \\
  1048. \\ 3 | 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45
  1049. \\
  1050. \\ 4 | 4 8 12 16 20 24 28 32 36 40 44 48 52 56 60
  1051. \\
  1052. \\ 5 | 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75
  1053. \\
  1054. \\ 6 | 6 12 18 24 30 36 42 48 54 60 66 72 78 84 90
  1055. \\
  1056. \\ 7 | 7 14 21 28 35 42 49 56 63 70 77 84 91 98 105
  1057. \\
  1058. \\ 8 | 8 16 24 32 40 48 56 64 72 80 88 96 104 112 120
  1059. \\
  1060. \\ 9 | 9 18 27 36 45 54 63 72 81 90 99 108 117 126 135
  1061. \\
  1062. \\10 | 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150
  1063. \\
  1064. \\11 | 11 22 33 44 55 66 77 88 99 110 121 132 143 154 165
  1065. \\
  1066. \\12 | 12 24 36 48 60 72 84 96 108 120 132 144 156 168 180
  1067. \\
  1068. \\13 | 13 26 39 52 65 78 91 104 117 130 143 156 169 182 195
  1069. \\
  1070. \\14 | 14 28 42 56 70 84 98 112 126 140 154 168 182 196 210
  1071. \\
  1072. \\15 | 15 30 45 60 75 90 105 120 135 150 165 180 195 210 225
  1073. ,
  1074. },
  1075. .{
  1076. .main_file = "100_for4.zig",
  1077. .output = "Arrays match!",
  1078. },
  1079. .{
  1080. .main_file = "101_for5.zig",
  1081. .output =
  1082. \\1. Wizard (Gold: 25, XP: 40)
  1083. \\2. Bard (Gold: 11, XP: 17)
  1084. \\3. Bard (Gold: 5, XP: 55)
  1085. \\4. Warrior (Gold: 7392, XP: 21)
  1086. ,
  1087. },
  1088. .{
  1089. .main_file = "102_testing.zig",
  1090. .output = "",
  1091. .kind = .@"test",
  1092. },
  1093. .{
  1094. .main_file = "103_tokenization.zig",
  1095. .output =
  1096. \\My
  1097. \\name
  1098. \\is
  1099. \\Ozymandias
  1100. \\King
  1101. \\of
  1102. \\Kings
  1103. \\Look
  1104. \\on
  1105. \\my
  1106. \\Works
  1107. \\ye
  1108. \\Mighty
  1109. \\and
  1110. \\despair
  1111. \\This little poem has 15 words!
  1112. ,
  1113. },
  1114. .{
  1115. .main_file = "104_threading.zig",
  1116. .output =
  1117. \\Starting work...
  1118. \\thread 1: started.
  1119. \\thread 2: started.
  1120. \\thread 3: started.
  1121. \\Some weird stuff, after starting the threads.
  1122. \\thread 2: finished.
  1123. \\thread 1: finished.
  1124. \\thread 3: finished.
  1125. \\Zig is cool!
  1126. ,
  1127. },
  1128. .{
  1129. .main_file = "105_threading2.zig",
  1130. .output = "PI ≈ 3.14159265",
  1131. },
  1132. .{
  1133. .main_file = "106_files.zig",
  1134. .output = "Successfully wrote 18 bytes.",
  1135. },
  1136. .{
  1137. .main_file = "107_files2.zig",
  1138. .output =
  1139. \\AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
  1140. \\Successfully Read 18 bytes: It's zigling time!
  1141. ,
  1142. },
  1143. .{
  1144. .main_file = "108_labeled_switch.zig",
  1145. .output = "The pull request has been merged.",
  1146. },
  1147. .{
  1148. .main_file = "109_vectors.zig",
  1149. .output =
  1150. \\Max difference (old fn): 0.014
  1151. \\Max difference (new fn): 0.014
  1152. ,
  1153. },
  1154. .{ .main_file = "110_quiz9.zig", .output =
  1155. \\Toggle pins with XOR on PORTB
  1156. \\-----------------------------
  1157. \\ 1100 // (initial state of PORTB)
  1158. \\^ 0101 // (bitmask)
  1159. \\= 1001
  1160. \\
  1161. \\ 1100 // (initial state of PORTB)
  1162. \\^ 0011 // (bitmask)
  1163. \\= 1111
  1164. \\
  1165. \\Set pins with OR on PORTB
  1166. \\-------------------------
  1167. \\ 1001 // (initial state of PORTB)
  1168. \\| 0100 // (bitmask)
  1169. \\= 1101
  1170. \\
  1171. \\ 1001 // (reset state)
  1172. \\| 0100 // (bitmask)
  1173. \\= 1101
  1174. \\
  1175. \\Clear pins with AND and NOT on PORTB
  1176. \\------------------------------------
  1177. \\ 1110 // (initial state of PORTB)
  1178. \\& 1011 // (bitmask)
  1179. \\= 1010
  1180. \\
  1181. \\ 0111 // (reset state)
  1182. \\& 1110 // (bitmask)
  1183. \\= 0110
  1184. },
  1185. .{
  1186. .main_file = "999_the_end.zig",
  1187. .output =
  1188. \\
  1189. \\This is the end for now!
  1190. \\We hope you had fun and were able to learn a lot, so visit us again when the next exercises are available.
  1191. ,
  1192. },
  1193. };