build.zig 30 KB

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