build.zig 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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. .main_file = "082_anonymous_structs3.zig",
  400. .output = "\"0\"(bool):true \"1\"(bool):false \"2\"(i32):42 \"3\"(f32):3.14159202e+00",
  401. .hint = "This one is a challenge! But you have everything you need.",
  402. },
  403. .{
  404. .main_file = "083_anonymous_lists.zig",
  405. .output = "I say hello!",
  406. },
  407. .{
  408. .main_file = "084_async.zig",
  409. .output = "foo() A",
  410. .hint = "Read the facts. Use the facts.",
  411. },
  412. .{
  413. .main_file = "085_async2.zig",
  414. .output = "Hello async!",
  415. },
  416. .{
  417. .main_file = "086_async3.zig",
  418. .output = "5 4 3 2 1",
  419. },
  420. };
  421. /// Check the zig version to make sure it can compile the examples properly.
  422. /// This will compile with Zig 0.6.0 and later.
  423. fn checkVersion() bool {
  424. if (!@hasDecl(std.builtin, "zig_version")) {
  425. return false;
  426. }
  427. const version = std.builtin.zig_version;
  428. const order = version.order(needed_version);
  429. return order != .lt;
  430. }
  431. pub fn build(b: *Builder) void {
  432. // Use a comptime branch for the version check.
  433. // If this fails, code after this block is not compiled.
  434. // It is parsed though, so versions of zig from before 0.6.0
  435. // cannot do the version check and will just fail to compile.
  436. // We could fix this by moving the ziglings code to a separate file,
  437. // but 0.5.0 was a long time ago, it is unlikely that anyone who
  438. // attempts these exercises is still using it.
  439. if (comptime !checkVersion()) {
  440. // very old versions of Zig used warn instead of print.
  441. const stderrPrintFn = if (@hasDecl(std.debug, "print")) std.debug.print else std.debug.warn;
  442. stderrPrintFn(
  443. \\ERROR: Sorry, it looks like your version of zig is too old. :-(
  444. \\
  445. \\Ziglings requires development build
  446. \\
  447. \\ {}
  448. \\
  449. \\or higher. Please download a development ("master") build from
  450. \\
  451. \\ https://ziglang.org/download/
  452. \\
  453. \\
  454. , .{needed_version});
  455. std.os.exit(0);
  456. }
  457. use_color_escapes = false;
  458. switch (b.color) {
  459. .on => use_color_escapes = true,
  460. .off => use_color_escapes = false,
  461. .auto => {
  462. if (std.io.getStdErr().supportsAnsiEscapeCodes()) {
  463. use_color_escapes = true;
  464. } else if (std.builtin.os.tag == .windows) {
  465. const w32 = struct {
  466. const WINAPI = std.os.windows.WINAPI;
  467. const DWORD = std.os.windows.DWORD;
  468. const ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004;
  469. const STD_ERROR_HANDLE = @bitCast(DWORD, @as(i32, -12));
  470. extern "kernel32" fn GetStdHandle(id: DWORD) callconv(WINAPI) ?*c_void;
  471. extern "kernel32" fn GetConsoleMode(console: ?*c_void, out_mode: *DWORD) callconv(WINAPI) u32;
  472. extern "kernel32" fn SetConsoleMode(console: ?*c_void, mode: DWORD) callconv(WINAPI) u32;
  473. };
  474. const handle = w32.GetStdHandle(w32.STD_ERROR_HANDLE);
  475. var mode: w32.DWORD = 0;
  476. if (w32.GetConsoleMode(handle, &mode) != 0) {
  477. mode |= w32.ENABLE_VIRTUAL_TERMINAL_PROCESSING;
  478. use_color_escapes = w32.SetConsoleMode(handle, mode) != 0;
  479. }
  480. }
  481. },
  482. }
  483. if (use_color_escapes) {
  484. red_text = "\x1b[31m";
  485. green_text = "\x1b[32m";
  486. bold_text = "\x1b[1m";
  487. reset_text = "\x1b[0m";
  488. }
  489. const header_step = b.addLog(
  490. \\
  491. \\ _ _ _
  492. \\ ___(_) __ _| (_)_ __ __ _ ___
  493. \\ |_ | |/ _' | | | '_ \ / _' / __|
  494. \\ / /| | (_| | | | | | | (_| \__ \
  495. \\ /___|_|\__, |_|_|_| |_|\__, |___/
  496. \\ |___/ |___/
  497. \\
  498. \\
  499. , .{});
  500. const verify_all = b.step("ziglings", "Check all ziglings");
  501. verify_all.dependOn(&header_step.step);
  502. b.default_step = verify_all;
  503. var prev_chain_verify = verify_all;
  504. const use_healed = b.option(bool, "healed", "Run exercises from patches/healed") orelse false;
  505. for (exercises) |ex| {
  506. const base_name = ex.baseName();
  507. const file_path = std.fs.path.join(b.allocator, &[_][]const u8{
  508. if (use_healed) "patches/healed" else "exercises", ex.main_file,
  509. }) catch unreachable;
  510. const build_step = b.addExecutable(base_name, file_path);
  511. build_step.install();
  512. const verify_step = ZiglingStep.create(b, ex, use_healed);
  513. const key = ex.key();
  514. const named_test = b.step(b.fmt("{s}_test", .{key}), b.fmt("Run {s} without checking output", .{ex.main_file}));
  515. const run_step = build_step.run();
  516. named_test.dependOn(&run_step.step);
  517. const named_install = b.step(b.fmt("{s}_install", .{key}), b.fmt("Install {s} to zig-cache/bin", .{ex.main_file}));
  518. named_install.dependOn(&build_step.install_step.?.step);
  519. const named_verify = b.step(key, b.fmt("Check {s} only", .{ex.main_file}));
  520. named_verify.dependOn(&verify_step.step);
  521. const chain_verify = b.allocator.create(Step) catch unreachable;
  522. chain_verify.* = Step.initNoOp(.Custom, b.fmt("chain {s}", .{key}), b.allocator);
  523. chain_verify.dependOn(&verify_step.step);
  524. const named_chain = b.step(b.fmt("{s}_start", .{key}), b.fmt("Check all solutions starting at {s}", .{ex.main_file}));
  525. named_chain.dependOn(&header_step.step);
  526. named_chain.dependOn(chain_verify);
  527. prev_chain_verify.dependOn(chain_verify);
  528. prev_chain_verify = chain_verify;
  529. }
  530. }
  531. var use_color_escapes = false;
  532. var red_text: []const u8 = "";
  533. var green_text: []const u8 = "";
  534. var bold_text: []const u8 = "";
  535. var reset_text: []const u8 = "";
  536. const ZiglingStep = struct {
  537. step: Step,
  538. exercise: Exercise,
  539. builder: *Builder,
  540. use_healed: bool,
  541. pub fn create(builder: *Builder, exercise: Exercise, use_healed: bool) *@This() {
  542. const self = builder.allocator.create(@This()) catch unreachable;
  543. self.* = .{
  544. .step = Step.init(.Custom, exercise.main_file, builder.allocator, make),
  545. .exercise = exercise,
  546. .builder = builder,
  547. .use_healed = use_healed,
  548. };
  549. return self;
  550. }
  551. fn make(step: *Step) anyerror!void {
  552. const self = @fieldParentPtr(@This(), "step", step);
  553. self.makeInternal() catch {
  554. if (self.exercise.hint.len > 0) {
  555. print("\n{s}HINT: {s}{s}", .{ bold_text, self.exercise.hint, reset_text });
  556. }
  557. print("\n{s}Edit exercises/{s} and run this again.{s}", .{ red_text, self.exercise.main_file, reset_text });
  558. 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 });
  559. std.os.exit(0);
  560. };
  561. }
  562. fn makeInternal(self: *@This()) !void {
  563. print("Compiling {s}...\n", .{self.exercise.main_file});
  564. const exe_file = try self.doCompile();
  565. print("Checking {s}...\n", .{self.exercise.main_file});
  566. const cwd = self.builder.build_root;
  567. const argv = [_][]const u8{exe_file};
  568. const child = std.ChildProcess.init(&argv, self.builder.allocator) catch unreachable;
  569. defer child.deinit();
  570. child.cwd = cwd;
  571. child.env_map = self.builder.env_map;
  572. child.stdin_behavior = .Inherit;
  573. if (self.exercise.check_stdout) {
  574. child.stdout_behavior = .Pipe;
  575. child.stderr_behavior = .Inherit;
  576. } else {
  577. child.stdout_behavior = .Inherit;
  578. child.stderr_behavior = .Pipe;
  579. }
  580. child.spawn() catch |err| {
  581. print("{s}Unable to spawn {s}: {s}{s}\n", .{ red_text, argv[0], @errorName(err), reset_text });
  582. return err;
  583. };
  584. // Allow up to 1 MB of stdout capture
  585. const max_output_len = 1 * 1024 * 1024;
  586. const output = if (self.exercise.check_stdout)
  587. try child.stdout.?.reader().readAllAlloc(self.builder.allocator, max_output_len)
  588. else
  589. try child.stderr.?.reader().readAllAlloc(self.builder.allocator, max_output_len);
  590. // at this point stdout is closed, wait for the process to terminate
  591. const term = child.wait() catch |err| {
  592. print("{s}Unable to spawn {s}: {s}{s}\n", .{ red_text, argv[0], @errorName(err), reset_text });
  593. return err;
  594. };
  595. // make sure it exited cleanly.
  596. switch (term) {
  597. .Exited => |code| {
  598. if (code != 0) {
  599. print("{s}{s} exited with error code {d} (expected {d}){s}\n", .{ red_text, self.exercise.main_file, code, 0, reset_text });
  600. return error.BadExitCode;
  601. }
  602. },
  603. else => {
  604. print("{s}{s} terminated unexpectedly{s}\n", .{ red_text, self.exercise.main_file, reset_text });
  605. return error.UnexpectedTermination;
  606. },
  607. }
  608. // validate the output
  609. if (std.mem.indexOf(u8, output, self.exercise.output) == null) {
  610. print(
  611. \\
  612. \\{s}----------- Expected this output -----------{s}
  613. \\{s}
  614. \\{s}----------- but found -----------{s}
  615. \\{s}
  616. \\{s}-----------{s}
  617. \\
  618. , .{ red_text, reset_text, self.exercise.output, red_text, reset_text, output, red_text, reset_text });
  619. return error.InvalidOutput;
  620. }
  621. print("{s}PASSED: {s}{s}\n", .{ green_text, output, reset_text });
  622. }
  623. // The normal compile step calls os.exit, so we can't use it as a library :(
  624. // This is a stripped down copy of std.build.LibExeObjStep.make.
  625. fn doCompile(self: *@This()) ![]const u8 {
  626. const builder = self.builder;
  627. var zig_args = std.ArrayList([]const u8).init(builder.allocator);
  628. defer zig_args.deinit();
  629. zig_args.append(builder.zig_exe) catch unreachable;
  630. zig_args.append("build-exe") catch unreachable;
  631. if (builder.color != .auto) {
  632. zig_args.append("--color") catch unreachable;
  633. zig_args.append(@tagName(builder.color)) catch unreachable;
  634. }
  635. 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;
  636. zig_args.append(builder.pathFromRoot(zig_file)) catch unreachable;
  637. zig_args.append("--cache-dir") catch unreachable;
  638. zig_args.append(builder.pathFromRoot(builder.cache_root)) catch unreachable;
  639. zig_args.append("--enable-cache") catch unreachable;
  640. const argv = zig_args.items;
  641. var code: u8 = undefined;
  642. const output_dir_nl = builder.execAllowFail(argv, &code, .Inherit) catch |err| {
  643. switch (err) {
  644. error.FileNotFound => {
  645. print("{s}{s}: Unable to spawn the following command: file not found{s}\n", .{ red_text, self.exercise.main_file, reset_text });
  646. for (argv) |v| print("{s} ", .{v});
  647. print("\n", .{});
  648. },
  649. error.ExitCodeFailure => {
  650. print("{s}{s}: The following command exited with error code {}:{s}\n", .{ red_text, self.exercise.main_file, code, reset_text });
  651. for (argv) |v| print("{s} ", .{v});
  652. print("\n", .{});
  653. },
  654. error.ProcessTerminated => {
  655. print("{s}{s}: The following command terminated unexpectedly:{s}\n", .{ red_text, self.exercise.main_file, reset_text });
  656. for (argv) |v| print("{s} ", .{v});
  657. print("\n", .{});
  658. },
  659. else => {},
  660. }
  661. return err;
  662. };
  663. const build_output_dir = std.mem.trimRight(u8, output_dir_nl, "\r\n");
  664. const target_info = std.zig.system.NativeTargetInfo.detect(
  665. builder.allocator,
  666. .{},
  667. ) catch unreachable;
  668. const target = target_info.target;
  669. const file_name = std.zig.binNameAlloc(builder.allocator, .{
  670. .root_name = self.exercise.baseName(),
  671. .target = target,
  672. .output_mode = .Exe,
  673. .link_mode = .Static,
  674. .version = null,
  675. }) catch unreachable;
  676. return std.fs.path.join(builder.allocator, &[_][]const u8{
  677. build_output_dir, file_name,
  678. });
  679. }
  680. };