build.zig 28 KB

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