build.zig 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  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. // When changing this version, be sure to also update README.md in two places:
  7. // 1) Getting Started
  8. // 2) Version Changes
  9. const needed_version = std.SemanticVersion.parse("0.8.0-dev.1983") catch unreachable;
  10. const Exercise = struct {
  11. /// main_file must have the format key_name.zig.
  12. /// The key will be used as a shorthand to build
  13. /// just one example.
  14. main_file: []const u8,
  15. /// This is the desired output of the program.
  16. /// A program passes if its output ends with this string.
  17. output: []const u8,
  18. /// This is an optional hint to give if the program does not succeed.
  19. hint: []const u8 = "",
  20. /// By default, we verify output against stderr.
  21. /// Set this to true to check stdout instead.
  22. check_stdout: bool = false,
  23. /// Returns the name of the main file with .zig stripped.
  24. pub fn baseName(self: Exercise) []const u8 {
  25. assert(std.mem.endsWith(u8, self.main_file, ".zig"));
  26. return self.main_file[0 .. self.main_file.len - 4];
  27. }
  28. /// Returns the key of the main file, the string before the '_' with
  29. /// "zero padding" removed.
  30. /// For example, "001_hello.zig" has the key "1".
  31. pub fn key(self: Exercise) []const u8 {
  32. const end_index = std.mem.indexOfScalar(u8, self.main_file, '_');
  33. assert(end_index != null); // main file must be key_description.zig
  34. // remove zero padding by advancing index past '0's
  35. var start_index: usize = 0;
  36. while (self.main_file[start_index] == '0') start_index += 1;
  37. return self.main_file[start_index..end_index.?];
  38. }
  39. };
  40. const exercises = [_]Exercise{
  41. .{
  42. .main_file = "001_hello.zig",
  43. .output = "Hello world",
  44. .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!",
  45. },
  46. .{
  47. .main_file = "002_std.zig",
  48. .output = "Standard Library",
  49. },
  50. .{
  51. .main_file = "003_assignment.zig",
  52. .output = "55 314159 -11",
  53. .hint = "There are three mistakes in this one!",
  54. },
  55. .{
  56. .main_file = "004_arrays.zig",
  57. .output = "Fourth: 7, Length: 8",
  58. .hint = "There are two things to complete here.",
  59. },
  60. .{
  61. .main_file = "005_arrays2.zig",
  62. .output = "LEET: 1337, Bits: 100110011001",
  63. .hint = "Fill in the two arrays.",
  64. },
  65. .{
  66. .main_file = "006_strings.zig",
  67. .output = "d=d ha ha ha Major Tom",
  68. .hint = "Each '???' needs something filled in.",
  69. },
  70. .{
  71. .main_file = "007_strings2.zig",
  72. .output = "Ziggy played guitar\nJamming good with Andrew Kelley\nAnd the Spiders from Mars",
  73. .hint = "Please fix the lyrics!",
  74. },
  75. .{
  76. .main_file = "008_quiz.zig",
  77. .output = "Program in Zig!",
  78. .hint = "See if you can fix the program!",
  79. },
  80. .{
  81. .main_file = "009_if.zig",
  82. .output = "Foo is 1!",
  83. },
  84. .{
  85. .main_file = "010_if2.zig",
  86. .output = "With the discount, the price is $17.",
  87. },
  88. .{
  89. .main_file = "011_while.zig",
  90. .output = "2 4 8 16 32 64 128 256 512 n=1024",
  91. .hint = "You probably want a 'less than' condition.",
  92. },
  93. .{
  94. .main_file = "012_while2.zig",
  95. .output = "2 4 8 16 32 64 128 256 512 n=1024",
  96. .hint = "It might help to look back at the previous exercise.",
  97. },
  98. .{
  99. .main_file = "013_while3.zig",
  100. .output = "1 2 4 7 8 11 13 14 16 17 19",
  101. },
  102. .{
  103. .main_file = "014_while4.zig",
  104. .output = "n=4",
  105. },
  106. .{
  107. .main_file = "015_for.zig",
  108. .output = "A Dramatic Story: :-) :-) :-( :-| :-) The End.",
  109. },
  110. .{
  111. .main_file = "016_for2.zig",
  112. .output = "13",
  113. },
  114. .{
  115. .main_file = "017_quiz2.zig",
  116. .output = "1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16,",
  117. .hint = "This is a famous game!",
  118. },
  119. .{
  120. .main_file = "018_functions.zig",
  121. .output = "Answer to the Ultimate Question: 42",
  122. .hint = "Can you help write the function?",
  123. },
  124. .{
  125. .main_file = "019_functions2.zig",
  126. .output = "2 4 8 16",
  127. },
  128. .{
  129. .main_file = "020_quiz3.zig",
  130. .output = "32 64 128 256",
  131. .hint = "Unexpected pop quiz! Help!",
  132. },
  133. .{
  134. .main_file = "021_errors.zig",
  135. .output = "2<4. 3<4. 4=4. 5>4. 6>4.",
  136. .hint = "What's the deal with fours?",
  137. },
  138. .{
  139. .main_file = "022_errors2.zig",
  140. .output = "I compiled",
  141. .hint = "Get the error union type right to allow this to compile.",
  142. },
  143. .{
  144. .main_file = "023_errors3.zig",
  145. .output = "a=64, b=22",
  146. },
  147. .{
  148. .main_file = "024_errors4.zig",
  149. .output = "a=20, b=14, c=10",
  150. },
  151. .{
  152. .main_file = "025_errors5.zig",
  153. .output = "a=0, b=19, c=0",
  154. },
  155. .{
  156. .main_file = "026_hello2.zig",
  157. .output = "Hello world!",
  158. .hint = "Try using a try!",
  159. .check_stdout = true,
  160. },
  161. .{
  162. .main_file = "027_defer.zig",
  163. .output = "One Two",
  164. },
  165. .{
  166. .main_file = "028_defer2.zig",
  167. .output = "(Goat) (Cat) (Dog) (Dog) (Goat) (Unknown) done.",
  168. },
  169. .{
  170. .main_file = "029_errdefer.zig",
  171. .output = "Getting number...got 5. Getting number...failed!",
  172. },
  173. .{
  174. .main_file = "030_switch.zig",
  175. .output = "ZIG?",
  176. },
  177. .{
  178. .main_file = "031_switch2.zig",
  179. .output = "ZIG!",
  180. },
  181. .{
  182. .main_file = "032_unreachable.zig",
  183. .output = "1 2 3 9 8 7",
  184. },
  185. .{
  186. .main_file = "033_iferror.zig",
  187. .output = "2<4. 3<4. 4=4. 5>4. 6>4.",
  188. .hint = "Seriously, what's the deal with fours?",
  189. },
  190. .{
  191. .main_file = "034_quiz4.zig",
  192. .output = "my_num=42",
  193. .hint = "Can you make this work?",
  194. .check_stdout = true,
  195. },
  196. .{
  197. .main_file = "035_enums.zig",
  198. .output = "1 2 3 9 8 7",
  199. .hint = "This problem seems familiar...",
  200. },
  201. .{
  202. .main_file = "036_enums2.zig",
  203. .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>",
  204. .hint = "I'm feeling blue about this.",
  205. },
  206. .{
  207. .main_file = "037_structs.zig",
  208. .output = "Your wizard has 90 health and 25 gold.",
  209. },
  210. .{
  211. .main_file = "038_structs2.zig",
  212. .output = "Character 1 - G:20 H:100 XP:10\nCharacter 2 - G:10 H:100 XP:20",
  213. },
  214. .{
  215. .main_file = "039_pointers.zig",
  216. .output = "num1: 5, num2: 5",
  217. .hint = "Pointers aren't so bad.",
  218. },
  219. .{
  220. .main_file = "040_pointers2.zig",
  221. .output = "a: 12, b: 12",
  222. },
  223. .{
  224. .main_file = "041_pointers3.zig",
  225. .output = "foo=6, bar=11",
  226. },
  227. .{
  228. .main_file = "042_pointers4.zig",
  229. .output = "num: 5, more_nums: 1 1 5 1",
  230. },
  231. .{
  232. .main_file = "043_pointers5.zig",
  233. .output = "Wizard (G:10 H:100 XP:20)",
  234. },
  235. .{
  236. .main_file = "044_quiz5.zig",
  237. .output = "Elephant A. Elephant B. Elephant C.",
  238. .hint = "Oh no! We forgot Elephant B!",
  239. },
  240. .{
  241. .main_file = "045_optionals.zig",
  242. .output = "The Ultimate Answer: 42.",
  243. },
  244. .{
  245. .main_file = "046_optionals2.zig",
  246. .output = "Elephant A. Elephant B. Elephant C.",
  247. .hint = "Elephants again!",
  248. },
  249. .{
  250. .main_file = "047_methods.zig",
  251. .output = "5 aliens. 4 aliens. 1 aliens. 0 aliens. Earth is saved!",
  252. .hint = "Use the heat ray. And the method!",
  253. },
  254. .{
  255. .main_file = "048_methods2.zig",
  256. .output = "A B C",
  257. .hint = "This just needs one little fix.",
  258. },
  259. .{
  260. .main_file = "049_quiz6.zig",
  261. .output = "A B C Cv Bv Av",
  262. .hint = "Now you're writing Zig!",
  263. },
  264. .{
  265. .main_file = "050_no_value.zig",
  266. .output = "That is not dead which can eternal lie / And with strange aeons even death may die.",
  267. },
  268. .{
  269. .main_file = "051_values.zig",
  270. .output = "1:false!. 2:true!. 3:true!. XP before:0, after:200.",
  271. },
  272. .{
  273. .main_file = "052_slices.zig",
  274. .output = "Hand1: A 4 K 8 Hand2: 5 2 Q J",
  275. },
  276. .{
  277. .main_file = "053_slices2.zig",
  278. .output = "'all your base are belong to us.' 'for great justice.'",
  279. },
  280. .{
  281. .main_file = "054_manypointers.zig",
  282. .output = "Memory is a resource.",
  283. },
  284. .{
  285. .main_file = "055_unions.zig",
  286. .output = "Insect report! Ant alive is: true. Bee visited 15 flowers.",
  287. },
  288. .{
  289. .main_file = "056_unions2.zig",
  290. .output = "Insect report! Ant alive is: true. Bee visited 16 flowers.",
  291. },
  292. .{
  293. .main_file = "057_unions3.zig",
  294. .output = "Insect report! Ant alive is: true. Bee visited 17 flowers.",
  295. },
  296. .{
  297. .main_file = "058_quiz7.zig",
  298. .output = "Archer's Point--2->Bridge--1->Dogwood Grove--3->Cottage--2->East Pond--1->Fox Pond",
  299. .hint = "This is the biggest program we've seen yet. But you can do it!"
  300. },
  301. .{
  302. .main_file = "059_integers.zig",
  303. .output = "Zig is cool.",
  304. },
  305. .{
  306. .main_file = "060_floats.zig",
  307. .output = "Shuttle liftoff weight: 1995796kg",
  308. },
  309. .{
  310. .main_file = "061_coercions.zig",
  311. .output = "Letter: A",
  312. },
  313. .{
  314. .main_file = "062_loop_expressions.zig",
  315. .output = "Current language: Zig",
  316. .hint = "Surely the current language is 'Zig'!",
  317. },
  318. .{
  319. .main_file = "063_labels.zig",
  320. .output = "Enjoy your Cheesy Chili!",
  321. },
  322. .{
  323. .main_file = "064_builtins.zig",
  324. .output = "1101 + 0101 = 0010 (true). Furthermore, 11110000 backwards is 00001111.",
  325. },
  326. .{
  327. .main_file = "065_builtins2.zig",
  328. .output = "A Narcissus loves all Narcissuses. He has room in his heart for: me myself.",
  329. },
  330. .{
  331. .main_file = "066_comptime.zig",
  332. .output = "Immutable: 12345, 987.654; Mutable: 54321, 456.789; Types: comptime_int, comptime_float, u32, f32",
  333. .hint = "It may help to read this one out loud to your favorite stuffed animal until it sinks in completely."
  334. },
  335. .{
  336. .main_file = "067_comptime2.zig",
  337. .output = "A BB CCC DDDD",
  338. },
  339. .{
  340. .main_file = "068_comptime3.zig",
  341. .output = "Minnow (1:32, 4 x 2)\nShark (1:16, 8 x 5)\nWhale (1:1, 143 x 95)\n",
  342. },
  343. .{
  344. .main_file = "069_comptime4.zig",
  345. .output = "s1={ 1, 2, 3 }, s2={ 1, 2, 3, 4, 5 }, s3={ 1, 2, 3, 4, 5, 6, 7 }",
  346. },
  347. .{
  348. .main_file = "070_comptime5.zig",
  349. .output = "\"Quack.\" ducky1: true, \"Squeek!\" ducky2: true, ducky3: false",
  350. .hint = "Have you kept the wizard hat on?",
  351. },
  352. .{
  353. .main_file = "071_comptime6.zig",
  354. .output = "Narcissus has room in his heart for: me myself.",
  355. },
  356. .{
  357. .main_file = "072_comptime7.zig",
  358. .output = "26",
  359. },
  360. .{
  361. .main_file = "073_comptime8.zig",
  362. .output = "My llama value is 25.",
  363. },
  364. .{
  365. .main_file = "074_comptime9.zig",
  366. .output = "My llama value is 2.",
  367. },
  368. .{
  369. .main_file = "075_quiz8.zig",
  370. .output = "Archer's Point--2->Bridge--1->Dogwood Grove--3->Cottage--2->East Pond--1->Fox Pond",
  371. .hint = "Roll up those sleeves. You get to WRITE some code for this one.",
  372. },
  373. .{
  374. .main_file = "076_sentinels.zig",
  375. .output = "Array:123056. Many-item pointer:123.",
  376. },
  377. .{
  378. .main_file = "077_sentinels2.zig",
  379. .output = "Weird Data!",
  380. },
  381. .{
  382. .main_file = "078_sentinels3.zig",
  383. .output = "Weird Data!",
  384. },
  385. .{
  386. .main_file = "079_quoted_identifiers.zig",
  387. .output = "Sweet freedom: 55, false.",
  388. .hint = "Help us, Zig Programmer, you're our only hope!",
  389. },
  390. .{
  391. .main_file = "080_anonymous_structs.zig",
  392. .output = "[Circle(i32): 25,70,15] [Circle(f32): 25.2,71.0,15.7]",
  393. },
  394. .{
  395. .main_file = "081_anonymous_structs2.zig",
  396. .output = "x:205 y:187 radius:12",
  397. },
  398. };
  399. /// Check the zig version to make sure it can compile the examples properly.
  400. /// This will compile with Zig 0.6.0 and later.
  401. fn checkVersion() bool {
  402. if (!@hasDecl(std.builtin, "zig_version")) {
  403. return false;
  404. }
  405. const version = std.builtin.zig_version;
  406. const order = version.order(needed_version);
  407. return order != .lt;
  408. }
  409. pub fn build(b: *Builder) void {
  410. // Use a comptime branch for the version check.
  411. // If this fails, code after this block is not compiled.
  412. // It is parsed though, so versions of zig from before 0.6.0
  413. // cannot do the version check and will just fail to compile.
  414. // We could fix this by moving the ziglings code to a separate file,
  415. // but 0.5.0 was a long time ago, it is unlikely that anyone who
  416. // attempts these exercises is still using it.
  417. if (comptime !checkVersion()) {
  418. // very old versions of Zig used warn instead of print.
  419. const stderrPrintFn = if (@hasDecl(std.debug, "print")) std.debug.print else std.debug.warn;
  420. stderrPrintFn(
  421. \\ERROR: Sorry, it looks like your version of zig is too old. :-(
  422. \\
  423. \\Ziglings requires development build
  424. \\
  425. \\ {}
  426. \\
  427. \\or higher. Please download a development ("master") build from
  428. \\
  429. \\ https://ziglang.org/download/
  430. \\
  431. \\
  432. , .{needed_version});
  433. std.os.exit(0);
  434. }
  435. use_color_escapes = false;
  436. switch (b.color) {
  437. .on => use_color_escapes = true,
  438. .off => use_color_escapes = false,
  439. .auto => {
  440. if (std.io.getStdErr().supportsAnsiEscapeCodes()) {
  441. use_color_escapes = true;
  442. } else if (std.builtin.os.tag == .windows) {
  443. const w32 = struct {
  444. const WINAPI = std.os.windows.WINAPI;
  445. const DWORD = std.os.windows.DWORD;
  446. const ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004;
  447. const STD_ERROR_HANDLE = @bitCast(DWORD, @as(i32, -12));
  448. extern "kernel32" fn GetStdHandle(id: DWORD) callconv(WINAPI) ?*c_void;
  449. extern "kernel32" fn GetConsoleMode(console: ?*c_void, out_mode: *DWORD) callconv(WINAPI) u32;
  450. extern "kernel32" fn SetConsoleMode(console: ?*c_void, mode: DWORD) callconv(WINAPI) u32;
  451. };
  452. const handle = w32.GetStdHandle(w32.STD_ERROR_HANDLE);
  453. var mode: w32.DWORD = 0;
  454. if (w32.GetConsoleMode(handle, &mode) != 0) {
  455. mode |= w32.ENABLE_VIRTUAL_TERMINAL_PROCESSING;
  456. use_color_escapes = w32.SetConsoleMode(handle, mode) != 0;
  457. }
  458. }
  459. },
  460. }
  461. if (use_color_escapes) {
  462. red_text = "\x1b[31m";
  463. green_text = "\x1b[32m";
  464. bold_text = "\x1b[1m";
  465. reset_text = "\x1b[0m";
  466. }
  467. const header_step = b.addLog(
  468. \\
  469. \\ _ _ _
  470. \\ ___(_) __ _| (_)_ __ __ _ ___
  471. \\ |_ | |/ _' | | | '_ \ / _' / __|
  472. \\ / /| | (_| | | | | | | (_| \__ \
  473. \\ /___|_|\__, |_|_|_| |_|\__, |___/
  474. \\ |___/ |___/
  475. \\
  476. \\
  477. , .{});
  478. const verify_all = b.step("ziglings", "Check all ziglings");
  479. verify_all.dependOn(&header_step.step);
  480. b.default_step = verify_all;
  481. var prev_chain_verify = verify_all;
  482. const use_healed = b.option(bool, "healed", "Run exercises from patches/healed") orelse false;
  483. for (exercises) |ex| {
  484. const base_name = ex.baseName();
  485. const file_path = std.fs.path.join(b.allocator, &[_][]const u8{
  486. if (use_healed) "patches/healed" else "exercises", ex.main_file,
  487. }) catch unreachable;
  488. const build_step = b.addExecutable(base_name, file_path);
  489. build_step.install();
  490. const verify_step = ZiglingStep.create(b, ex, use_healed);
  491. const key = ex.key();
  492. const named_test = b.step(b.fmt("{s}_test", .{key}), b.fmt("Run {s} without checking output", .{ex.main_file}));
  493. const run_step = build_step.run();
  494. named_test.dependOn(&run_step.step);
  495. const named_install = b.step(b.fmt("{s}_install", .{key}), b.fmt("Install {s} to zig-cache/bin", .{ex.main_file}));
  496. named_install.dependOn(&build_step.install_step.?.step);
  497. const named_verify = b.step(key, b.fmt("Check {s} only", .{ex.main_file}));
  498. named_verify.dependOn(&verify_step.step);
  499. const chain_verify = b.allocator.create(Step) catch unreachable;
  500. chain_verify.* = Step.initNoOp(.Custom, b.fmt("chain {s}", .{key}), b.allocator);
  501. chain_verify.dependOn(&verify_step.step);
  502. const named_chain = b.step(b.fmt("{s}_start", .{key}), b.fmt("Check all solutions starting at {s}", .{ex.main_file}));
  503. named_chain.dependOn(&header_step.step);
  504. named_chain.dependOn(chain_verify);
  505. prev_chain_verify.dependOn(chain_verify);
  506. prev_chain_verify = chain_verify;
  507. }
  508. }
  509. var use_color_escapes = false;
  510. var red_text: []const u8 = "";
  511. var green_text: []const u8 = "";
  512. var bold_text: []const u8 = "";
  513. var reset_text: []const u8 = "";
  514. const ZiglingStep = struct {
  515. step: Step,
  516. exercise: Exercise,
  517. builder: *Builder,
  518. use_healed: bool,
  519. pub fn create(builder: *Builder, exercise: Exercise, use_healed: bool) *@This() {
  520. const self = builder.allocator.create(@This()) catch unreachable;
  521. self.* = .{
  522. .step = Step.init(.Custom, exercise.main_file, builder.allocator, make),
  523. .exercise = exercise,
  524. .builder = builder,
  525. .use_healed = use_healed,
  526. };
  527. return self;
  528. }
  529. fn make(step: *Step) anyerror!void {
  530. const self = @fieldParentPtr(@This(), "step", step);
  531. self.makeInternal() catch {
  532. if (self.exercise.hint.len > 0) {
  533. print("\n{s}HINT: {s}{s}", .{ bold_text, self.exercise.hint, reset_text });
  534. }
  535. print("\n{s}Edit exercises/{s} and run this again.{s}", .{ red_text, self.exercise.main_file, reset_text });
  536. 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 });
  537. std.os.exit(0);
  538. };
  539. }
  540. fn makeInternal(self: *@This()) !void {
  541. print("Compiling {s}...\n", .{self.exercise.main_file});
  542. const exe_file = try self.doCompile();
  543. print("Checking {s}...\n", .{self.exercise.main_file});
  544. const cwd = self.builder.build_root;
  545. const argv = [_][]const u8{exe_file};
  546. const child = std.ChildProcess.init(&argv, self.builder.allocator) catch unreachable;
  547. defer child.deinit();
  548. child.cwd = cwd;
  549. child.env_map = self.builder.env_map;
  550. child.stdin_behavior = .Inherit;
  551. if (self.exercise.check_stdout) {
  552. child.stdout_behavior = .Pipe;
  553. child.stderr_behavior = .Inherit;
  554. } else {
  555. child.stdout_behavior = .Inherit;
  556. child.stderr_behavior = .Pipe;
  557. }
  558. child.spawn() catch |err| {
  559. print("{s}Unable to spawn {s}: {s}{s}\n", .{ red_text, argv[0], @errorName(err), reset_text });
  560. return err;
  561. };
  562. // Allow up to 1 MB of stdout capture
  563. const max_output_len = 1 * 1024 * 1024;
  564. const output = if (self.exercise.check_stdout)
  565. try child.stdout.?.reader().readAllAlloc(self.builder.allocator, max_output_len)
  566. else
  567. try child.stderr.?.reader().readAllAlloc(self.builder.allocator, max_output_len);
  568. // at this point stdout is closed, wait for the process to terminate
  569. const term = child.wait() catch |err| {
  570. print("{s}Unable to spawn {s}: {s}{s}\n", .{ red_text, argv[0], @errorName(err), reset_text });
  571. return err;
  572. };
  573. // make sure it exited cleanly.
  574. switch (term) {
  575. .Exited => |code| {
  576. if (code != 0) {
  577. print("{s}{s} exited with error code {d} (expected {d}){s}\n", .{ red_text, self.exercise.main_file, code, 0, reset_text });
  578. return error.BadExitCode;
  579. }
  580. },
  581. else => {
  582. print("{s}{s} terminated unexpectedly{s}\n", .{ red_text, self.exercise.main_file, reset_text });
  583. return error.UnexpectedTermination;
  584. },
  585. }
  586. // validate the output
  587. if (std.mem.indexOf(u8, output, self.exercise.output) == null) {
  588. print(
  589. \\
  590. \\{s}----------- Expected this output -----------{s}
  591. \\{s}
  592. \\{s}----------- but found -----------{s}
  593. \\{s}
  594. \\{s}-----------{s}
  595. \\
  596. , .{ red_text, reset_text, self.exercise.output, red_text, reset_text, output, red_text, reset_text });
  597. return error.InvalidOutput;
  598. }
  599. print("{s}PASSED: {s}{s}\n", .{ green_text, output, reset_text });
  600. }
  601. // The normal compile step calls os.exit, so we can't use it as a library :(
  602. // This is a stripped down copy of std.build.LibExeObjStep.make.
  603. fn doCompile(self: *@This()) ![]const u8 {
  604. const builder = self.builder;
  605. var zig_args = std.ArrayList([]const u8).init(builder.allocator);
  606. defer zig_args.deinit();
  607. zig_args.append(builder.zig_exe) catch unreachable;
  608. zig_args.append("build-exe") catch unreachable;
  609. if (builder.color != .auto) {
  610. zig_args.append("--color") catch unreachable;
  611. zig_args.append(@tagName(builder.color)) catch unreachable;
  612. }
  613. const zig_file = std.fs.path.join(builder.allocator, &[_][]const u8{ if (self.use_healed) "patches/healed" else "exercises", self.exercise.main_file }) catch unreachable;
  614. zig_args.append(builder.pathFromRoot(zig_file)) catch unreachable;
  615. zig_args.append("--cache-dir") catch unreachable;
  616. zig_args.append(builder.pathFromRoot(builder.cache_root)) catch unreachable;
  617. zig_args.append("--enable-cache") catch unreachable;
  618. const argv = zig_args.items;
  619. var code: u8 = undefined;
  620. const output_dir_nl = builder.execAllowFail(argv, &code, .Inherit) catch |err| {
  621. switch (err) {
  622. error.FileNotFound => {
  623. print("{s}{s}: Unable to spawn the following command: file not found{s}\n", .{ red_text, self.exercise.main_file, reset_text });
  624. for (argv) |v| print("{s} ", .{v});
  625. print("\n", .{});
  626. },
  627. error.ExitCodeFailure => {
  628. print("{s}{s}: The following command exited with error code {}:{s}\n", .{ red_text, self.exercise.main_file, code, reset_text });
  629. for (argv) |v| print("{s} ", .{v});
  630. print("\n", .{});
  631. },
  632. error.ProcessTerminated => {
  633. print("{s}{s}: The following command terminated unexpectedly:{s}\n", .{ red_text, self.exercise.main_file, reset_text });
  634. for (argv) |v| print("{s} ", .{v});
  635. print("\n", .{});
  636. },
  637. else => {},
  638. }
  639. return err;
  640. };
  641. const build_output_dir = std.mem.trimRight(u8, output_dir_nl, "\r\n");
  642. const target_info = std.zig.system.NativeTargetInfo.detect(
  643. builder.allocator,
  644. .{},
  645. ) catch unreachable;
  646. const target = target_info.target;
  647. const file_name = std.zig.binNameAlloc(builder.allocator, .{
  648. .root_name = self.exercise.baseName(),
  649. .target = target,
  650. .output_mode = .Exe,
  651. .link_mode = .Static,
  652. .version = null,
  653. }) catch unreachable;
  654. return std.fs.path.join(builder.allocator, &[_][]const u8{
  655. build_output_dir, file_name,
  656. });
  657. }
  658. };