build.zig 25 KB

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