build.zig 31 KB

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