build.zig 37 KB

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