build.zig 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. const std = @import("std");
  2. const Builder = std.build.Builder;
  3. const Step = std.build.Step;
  4. const assert = std.debug.assert;
  5. const print = std.debug.print;
  6. const Exercise = struct {
  7. /// main_file must have the format key_name.zig.
  8. /// The key will be used as a shorthand to build
  9. /// just one example.
  10. main_file: []const u8,
  11. /// This is the desired output of the program.
  12. /// A program passes if its output ends with this string.
  13. output: []const u8,
  14. /// This is an optional hint to give if the program does not succeed.
  15. hint: []const u8 = "",
  16. /// By default, we verify output against stderr.
  17. /// Set this to true to check stdout instead.
  18. check_stdout: bool = false,
  19. /// Returns the name of the main file with .zig stripped.
  20. pub fn baseName(self: Exercise) []const u8 {
  21. assert(std.mem.endsWith(u8, self.main_file, ".zig"));
  22. return self.main_file[0 .. self.main_file.len - 4];
  23. }
  24. /// Returns the key of the main file, which is the text before the _.
  25. /// For example, "01_hello.zig" has the key "01".
  26. pub fn key(self: Exercise) []const u8 {
  27. const end_index = std.mem.indexOfScalar(u8, self.main_file, '_');
  28. assert(end_index != null); // main file must be key_description.zig
  29. return self.main_file[0..end_index.?];
  30. }
  31. };
  32. const exercises = [_]Exercise{
  33. .{
  34. .main_file = "01_hello.zig",
  35. .output = "Hello world",
  36. .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!",
  37. },
  38. .{
  39. .main_file = "02_std.zig",
  40. .output = "Standard Library",
  41. },
  42. .{
  43. .main_file = "03_assignment.zig",
  44. .output = "55 314159 -11",
  45. .hint = "There are three mistakes in this one!",
  46. },
  47. .{
  48. .main_file = "04_arrays.zig",
  49. .output = "Fourth: 7, Length: 8",
  50. .hint = "There are two things to complete here.",
  51. },
  52. .{
  53. .main_file = "05_arrays2.zig",
  54. .output = "LEET: 1337, Bits: 100110011001",
  55. .hint = "Fill in the two arrays.",
  56. },
  57. .{
  58. .main_file = "06_strings.zig",
  59. .output = "d=d ha ha ha Major Tom",
  60. .hint = "Each '???' needs something filled in.",
  61. },
  62. .{
  63. .main_file = "07_strings2.zig",
  64. .output = "Ziggy",
  65. .hint = "Please fix the lyrics!",
  66. },
  67. .{
  68. .main_file = "08_quiz.zig",
  69. .output = "Program in Zig",
  70. .hint = "See if you can fix the program!",
  71. },
  72. .{
  73. .main_file = "09_if.zig",
  74. .output = "Foo is 1!",
  75. },
  76. .{
  77. .main_file = "10_if2.zig",
  78. .output = "price is $17",
  79. },
  80. .{
  81. .main_file = "11_while.zig",
  82. .output = "n=1024",
  83. .hint = "You probably want a 'less than' condition.",
  84. },
  85. .{
  86. .main_file = "12_while2.zig",
  87. .output = "n=1024",
  88. .hint = "It might help to look back at the previous exercise.",
  89. },
  90. .{
  91. .main_file = "13_while3.zig",
  92. .output = "1 2 4 7 8 11 13 14 16 17 19",
  93. },
  94. .{
  95. .main_file = "14_while4.zig",
  96. .output = "n=4",
  97. },
  98. .{
  99. .main_file = "15_for.zig",
  100. .output = "A Dramatic Story: :-) :-) :-( :-| :-) The End.",
  101. },
  102. .{
  103. .main_file = "16_for2.zig",
  104. .output = "13",
  105. },
  106. .{
  107. .main_file = "17_quiz2.zig",
  108. .output = "8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16",
  109. .hint = "This is a famous game!",
  110. },
  111. .{
  112. .main_file = "18_functions.zig",
  113. .output = "Question: 42",
  114. .hint = "Can you help write the function?",
  115. },
  116. .{
  117. .main_file = "19_functions2.zig",
  118. .output = "2 4 8 16",
  119. },
  120. .{
  121. .main_file = "20_quiz3.zig",
  122. .output = "32 64 128 256",
  123. .hint = "Unexpected pop quiz! Help!",
  124. },
  125. .{
  126. .main_file = "21_errors.zig",
  127. .output = "2<4. 3<4. 4=4. 5>4. 6>4.",
  128. .hint = "What's the deal with fours?",
  129. },
  130. .{
  131. .main_file = "22_errors2.zig",
  132. .output = "I compiled",
  133. .hint = "Get the error union type right to allow this to compile.",
  134. },
  135. .{
  136. .main_file = "23_errors3.zig",
  137. .output = "a=64, b=22",
  138. },
  139. .{
  140. .main_file = "24_errors4.zig",
  141. .output = "a=20, b=14, c=10",
  142. },
  143. .{
  144. .main_file = "25_errors5.zig",
  145. .output = "a=0, b=19, c=0",
  146. },
  147. .{
  148. .main_file = "26_hello2.zig",
  149. .output = "Hello world",
  150. .hint = "Try using a try!",
  151. .check_stdout = true,
  152. },
  153. .{
  154. .main_file = "27_defer.zig",
  155. .output = "One Two",
  156. },
  157. .{
  158. .main_file = "28_defer2.zig",
  159. .output = "(Goat) (Cat) (Dog) (Dog) (Goat) (Unknown) done.",
  160. },
  161. .{
  162. .main_file = "29_errdefer.zig",
  163. .output = "Getting number...got 5. Getting number...failed!",
  164. },
  165. .{
  166. .main_file = "30_switch.zig",
  167. .output = "ZIG?",
  168. },
  169. .{
  170. .main_file = "31_switch2.zig",
  171. .output = "ZIG!",
  172. },
  173. .{
  174. .main_file = "32_unreachable.zig",
  175. .output = "1 2 3 9 8 7",
  176. },
  177. .{
  178. .main_file = "33_iferror.zig",
  179. .output = "2<4. 3<4. 4=4. 5>4. 6>4.",
  180. .hint = "Seriously, what's the deal with fours?",
  181. },
  182. .{
  183. .main_file = "34_quiz4.zig",
  184. .output = "my_num=42",
  185. .hint = "Can you make this work?",
  186. .check_stdout = true,
  187. },
  188. .{
  189. .main_file = "35_enums.zig",
  190. .output = "1 2 3 9 8 7",
  191. .hint = "This problem seems familiar...",
  192. },
  193. .{
  194. .main_file = "36_enums2.zig",
  195. .output = "#0000ff",
  196. .hint = "I'm feeling blue about this.",
  197. },
  198. .{
  199. .main_file = "37_structs.zig",
  200. .output = "Your wizard has 90 health and 25 gold.",
  201. },
  202. .{
  203. .main_file = "38_structs2.zig",
  204. .output = "Character 2 - G:10 H:100 XP:20",
  205. },
  206. .{
  207. .main_file = "39_pointers.zig",
  208. .output = "num1: 5, num2: 5",
  209. .hint = "Pointers aren't so bad.",
  210. },
  211. .{
  212. .main_file = "40_pointers2.zig",
  213. .output = "a: 12, b: 12",
  214. },
  215. .{
  216. .main_file = "41_pointers3.zig",
  217. .output = "foo=6, bar=11",
  218. },
  219. .{
  220. .main_file = "42_pointers4.zig",
  221. .output = "num: 5, more_nums: 1 1 5 1",
  222. },
  223. .{
  224. .main_file = "43_pointers5.zig",
  225. .output = "Wizard (G:10 H:100 XP:20)",
  226. },
  227. .{
  228. .main_file = "44_quiz5.zig",
  229. .output = "Elephant A. Elephant B. Elephant C.",
  230. .hint = "Oh no! We forgot Elephant B!",
  231. },
  232. .{
  233. .main_file = "45_optionals.zig",
  234. .output = "The Ultimate Answer: 42.",
  235. },
  236. .{
  237. .main_file = "46_optionals2.zig",
  238. .output = "Elephant A. Elephant B. Elephant C.",
  239. .hint = "Elephants again!",
  240. },
  241. .{
  242. .main_file = "47_methods.zig",
  243. .output = "5 aliens. 4 aliens. 1 aliens. 0 aliens. Earth is saved!",
  244. .hint = "Use the heat ray. And the method!",
  245. },
  246. .{
  247. .main_file = "48_methods2.zig",
  248. .output = "A B C",
  249. .hint = "This just needs one little fix.",
  250. },
  251. .{
  252. .main_file = "49_quiz6.zig",
  253. .output = "A B C Cv Bv Av",
  254. .hint = "Now you're writting Zig!",
  255. },
  256. .{
  257. .main_file = "50_no_value.zig",
  258. .output = "That is not dead which can eternal lie / And with strange aeons even death may die.",
  259. },
  260. // 51 pass-by-value and const fn params
  261. // 52 slices!
  262. };
  263. /// Check the zig version to make sure it can compile the examples properly.
  264. /// This will compile with Zig 0.6.0 and later.
  265. fn checkVersion() bool {
  266. if (!@hasDecl(std.builtin, "zig_version")) {
  267. return false;
  268. }
  269. const needed_version = std.SemanticVersion.parse("0.8.0-dev.1065") catch unreachable;
  270. const version = std.builtin.zig_version;
  271. const order = version.order(needed_version);
  272. return order != .lt;
  273. }
  274. pub fn build(b: *Builder) void {
  275. // Use a comptime branch for the version check.
  276. // If this fails, code after this block is not compiled.
  277. // It is parsed though, so versions of zig from before 0.6.0
  278. // cannot do the version check and will just fail to compile.
  279. // We could fix this by moving the ziglings code to a separate file,
  280. // but 0.5.0 was a long time ago, it is unlikely that anyone who
  281. // attempts these exercises is still using it.
  282. if (comptime !checkVersion()) {
  283. // very old versions of Zig used warn instead of print.
  284. const stderrPrintFn = if (@hasDecl(std.debug, "print")) std.debug.print else std.debug.warn;
  285. stderrPrintFn(
  286. \\ERROR: Sorry, it looks like your version of zig is too old. :-(
  287. \\
  288. \\Ziglings requires development build
  289. \\
  290. \\ 0.8.0-dev.1065
  291. \\
  292. \\or higher. Please download a development ("master") build from
  293. \\https://ziglang.org/download/
  294. \\
  295. , .{});
  296. std.os.exit(0);
  297. }
  298. use_color_escapes = false;
  299. switch (b.color) {
  300. .on => use_color_escapes = true,
  301. .off => use_color_escapes = false,
  302. .auto => {
  303. if (std.io.getStdErr().supportsAnsiEscapeCodes()) {
  304. use_color_escapes = true;
  305. } else if (std.builtin.os.tag == .windows) {
  306. const w32 = struct {
  307. const WINAPI = std.os.windows.WINAPI;
  308. const DWORD = std.os.windows.DWORD;
  309. const ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004;
  310. const STD_ERROR_HANDLE = @bitCast(DWORD, @as(i32, -12));
  311. extern "kernel32" fn GetStdHandle(id: DWORD) callconv(WINAPI) ?*c_void;
  312. extern "kernel32" fn GetConsoleMode(console: ?*c_void, out_mode: *DWORD) callconv(WINAPI) u32;
  313. extern "kernel32" fn SetConsoleMode(console: ?*c_void, mode: DWORD) callconv(WINAPI) u32;
  314. };
  315. const handle = w32.GetStdHandle(w32.STD_ERROR_HANDLE);
  316. var mode: w32.DWORD = 0;
  317. if (w32.GetConsoleMode(handle, &mode) != 0) {
  318. mode |= w32.ENABLE_VIRTUAL_TERMINAL_PROCESSING;
  319. use_color_escapes = w32.SetConsoleMode(handle, mode) != 0;
  320. }
  321. }
  322. },
  323. }
  324. if (use_color_escapes) {
  325. red_text = "\x1b[31m";
  326. green_text = "\x1b[32m";
  327. bold_text = "\x1b[1m";
  328. reset_text = "\x1b[0m";
  329. }
  330. const header_step = b.addLog(
  331. \\
  332. \\ _ _ _
  333. \\ ___(_) __ _| (_)_ __ __ _ ___
  334. \\ |_ | |/ _' | | | '_ \ / _' / __|
  335. \\ / /| | (_| | | | | | | (_| \__ \
  336. \\ /___|_|\__, |_|_|_| |_|\__, |___/
  337. \\ |___/ |___/
  338. \\
  339. \\
  340. , .{});
  341. const verify_all = b.step("ziglings", "Check all ziglings");
  342. verify_all.dependOn(&header_step.step);
  343. b.default_step = verify_all;
  344. var prev_chain_verify = verify_all;
  345. const use_healed = b.option(bool, "healed", "Run exercises from patches/healed") orelse false;
  346. for (exercises) |ex| {
  347. const base_name = ex.baseName();
  348. const file_path = std.fs.path.join(b.allocator, &[_][]const u8{
  349. if (use_healed) "patches/healed" else "exercises", ex.main_file,
  350. }) catch unreachable;
  351. const build_step = b.addExecutable(base_name, file_path);
  352. build_step.install();
  353. const verify_step = ZiglingStep.create(b, ex, use_healed);
  354. const key = ex.key();
  355. const named_test = b.step(b.fmt("{s}_test", .{key}), b.fmt("Run {s} without checking output", .{ex.main_file}));
  356. const run_step = build_step.run();
  357. named_test.dependOn(&run_step.step);
  358. const named_install = b.step(b.fmt("{s}_install", .{key}), b.fmt("Install {s} to zig-cache/bin", .{ex.main_file}));
  359. named_install.dependOn(&build_step.install_step.?.step);
  360. const named_verify = b.step(key, b.fmt("Check {s} only", .{ex.main_file}));
  361. named_verify.dependOn(&verify_step.step);
  362. const chain_verify = b.allocator.create(Step) catch unreachable;
  363. chain_verify.* = Step.initNoOp(.Custom, b.fmt("chain {s}", .{key}), b.allocator);
  364. chain_verify.dependOn(&verify_step.step);
  365. const named_chain = b.step(b.fmt("{s}_start", .{key}), b.fmt("Check all solutions starting at {s}", .{ex.main_file}));
  366. named_chain.dependOn(&header_step.step);
  367. named_chain.dependOn(chain_verify);
  368. prev_chain_verify.dependOn(chain_verify);
  369. prev_chain_verify = chain_verify;
  370. }
  371. }
  372. var use_color_escapes = false;
  373. var red_text: []const u8 = "";
  374. var green_text: []const u8 = "";
  375. var bold_text: []const u8 = "";
  376. var reset_text: []const u8 = "";
  377. const ZiglingStep = struct {
  378. step: Step,
  379. exercise: Exercise,
  380. builder: *Builder,
  381. use_healed: bool,
  382. pub fn create(builder: *Builder, exercise: Exercise, use_healed: bool) *@This() {
  383. const self = builder.allocator.create(@This()) catch unreachable;
  384. self.* = .{
  385. .step = Step.init(.Custom, exercise.main_file, builder.allocator, make),
  386. .exercise = exercise,
  387. .builder = builder,
  388. .use_healed = use_healed,
  389. };
  390. return self;
  391. }
  392. fn make(step: *Step) anyerror!void {
  393. const self = @fieldParentPtr(@This(), "step", step);
  394. self.makeInternal() catch {
  395. if (self.exercise.hint.len > 0) {
  396. print("\n{s}HINT: {s}{s}", .{ bold_text, self.exercise.hint, reset_text });
  397. }
  398. print("\n{s}Edit exercises/{s} and run this again.{s}", .{ red_text, self.exercise.main_file, reset_text });
  399. print("\n{s}To continue from this zigling, use this command:{s}\n {s}zig build {s}{s}\n", .{ red_text, reset_text, bold_text, self.exercise.key(), reset_text });
  400. std.os.exit(0);
  401. };
  402. }
  403. fn makeInternal(self: *@This()) !void {
  404. print("Compiling {s}...\n", .{self.exercise.main_file});
  405. const exe_file = try self.doCompile();
  406. print("Checking {s}...\n", .{self.exercise.main_file});
  407. const cwd = self.builder.build_root;
  408. const argv = [_][]const u8{exe_file};
  409. const child = std.ChildProcess.init(&argv, self.builder.allocator) catch unreachable;
  410. defer child.deinit();
  411. child.cwd = cwd;
  412. child.env_map = self.builder.env_map;
  413. child.stdin_behavior = .Inherit;
  414. if (self.exercise.check_stdout) {
  415. child.stdout_behavior = .Pipe;
  416. child.stderr_behavior = .Inherit;
  417. } else {
  418. child.stdout_behavior = .Inherit;
  419. child.stderr_behavior = .Pipe;
  420. }
  421. child.spawn() catch |err| {
  422. print("{s}Unable to spawn {s}: {s}{s}\n", .{ red_text, argv[0], @errorName(err), reset_text });
  423. return err;
  424. };
  425. // Allow up to 1 MB of stdout capture
  426. const max_output_len = 1 * 1024 * 1024;
  427. const output = if (self.exercise.check_stdout)
  428. try child.stdout.?.reader().readAllAlloc(self.builder.allocator, max_output_len)
  429. else
  430. try child.stderr.?.reader().readAllAlloc(self.builder.allocator, max_output_len);
  431. // at this point stdout is closed, wait for the process to terminate
  432. const term = child.wait() catch |err| {
  433. print("{s}Unable to spawn {s}: {s}{s}\n", .{ red_text, argv[0], @errorName(err), reset_text });
  434. return err;
  435. };
  436. // make sure it exited cleanly.
  437. switch (term) {
  438. .Exited => |code| {
  439. if (code != 0) {
  440. print("{s}{s} exited with error code {d} (expected {d}){s}\n", .{ red_text, self.exercise.main_file, code, 0, reset_text });
  441. return error.BadExitCode;
  442. }
  443. },
  444. else => {
  445. print("{s}{s} terminated unexpectedly{s}\n", .{ red_text, self.exercise.main_file, reset_text });
  446. return error.UnexpectedTermination;
  447. },
  448. }
  449. // validate the output
  450. if (std.mem.indexOf(u8, output, self.exercise.output) == null) {
  451. print(
  452. \\
  453. \\{s}----------- Expected this output -----------{s}
  454. \\{s}
  455. \\{s}----------- but found -----------{s}
  456. \\{s}
  457. \\{s}-----------{s}
  458. \\
  459. , .{ red_text, reset_text, self.exercise.output, red_text, reset_text, output, red_text, reset_text });
  460. return error.InvalidOutput;
  461. }
  462. print("{s}PASSED: {s}{s}\n", .{ green_text, output, reset_text });
  463. }
  464. // The normal compile step calls os.exit, so we can't use it as a library :(
  465. // This is a stripped down copy of std.build.LibExeObjStep.make.
  466. fn doCompile(self: *@This()) ![]const u8 {
  467. const builder = self.builder;
  468. var zig_args = std.ArrayList([]const u8).init(builder.allocator);
  469. defer zig_args.deinit();
  470. zig_args.append(builder.zig_exe) catch unreachable;
  471. zig_args.append("build-exe") catch unreachable;
  472. if (builder.color != .auto) {
  473. zig_args.append("--color") catch unreachable;
  474. zig_args.append(@tagName(builder.color)) catch unreachable;
  475. }
  476. const zig_file = std.fs.path.join(builder.allocator, &[_][]const u8{
  477. if (self.use_healed) "patches/healed" else "exercises", self.exercise.main_file }) catch unreachable;
  478. zig_args.append(builder.pathFromRoot(zig_file)) catch unreachable;
  479. zig_args.append("--cache-dir") catch unreachable;
  480. zig_args.append(builder.pathFromRoot(builder.cache_root)) catch unreachable;
  481. zig_args.append("--enable-cache") catch unreachable;
  482. const argv = zig_args.items;
  483. var code: u8 = undefined;
  484. const output_dir_nl = builder.execAllowFail(argv, &code, .Inherit) catch |err| {
  485. switch (err) {
  486. error.FileNotFound => {
  487. print("{s}{s}: Unable to spawn the following command: file not found{s}\n", .{ red_text, self.exercise.main_file, reset_text });
  488. for (argv) |v| print("{s} ", .{v});
  489. print("\n", .{});
  490. },
  491. error.ExitCodeFailure => {
  492. print("{s}{s}: The following command exited with error code {}:{s}\n", .{ red_text, self.exercise.main_file, code, reset_text });
  493. for (argv) |v| print("{s} ", .{v});
  494. print("\n", .{});
  495. },
  496. error.ProcessTerminated => {
  497. print("{s}{s}: The following command terminated unexpectedly:{s}\n", .{ red_text, self.exercise.main_file, reset_text });
  498. for (argv) |v| print("{s} ", .{v});
  499. print("\n", .{});
  500. },
  501. else => {},
  502. }
  503. return err;
  504. };
  505. const build_output_dir = std.mem.trimRight(u8, output_dir_nl, "\r\n");
  506. const target_info = std.zig.system.NativeTargetInfo.detect(
  507. builder.allocator,
  508. .{},
  509. ) catch unreachable;
  510. const target = target_info.target;
  511. const file_name = std.zig.binNameAlloc(builder.allocator, .{
  512. .root_name = self.exercise.baseName(),
  513. .target = target,
  514. .output_mode = .Exe,
  515. .link_mode = .Static,
  516. .version = null,
  517. }) catch unreachable;
  518. return std.fs.path.join(builder.allocator, &[_][]const u8{
  519. build_output_dir, file_name,
  520. });
  521. }
  522. };