build.zig 27 KB

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