build.zig 37 KB

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