build.zig 35 KB

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