build.zig 25 KB

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