build.zig 27 KB

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