1use logicaffeine_system::fs::{Vfs, VfsResult};
7
8pub async fn seed_examples<V: Vfs>(vfs: &V) -> VfsResult<()> {
12 vfs.create_dir_all("/examples/logic").await?;
14 vfs.create_dir_all("/examples/code").await?;
15 vfs.create_dir_all("/examples/math").await?;
16 vfs.create_dir_all("/examples/hardware").await?;
17 for sub in [
18 "basics",
19 "strings",
20 "types",
21 "collections",
22 "functions",
23 "algorithms",
24 "distributed",
25 "security",
26 "memory",
27 "concurrency",
28 "networking",
29 "crypto",
30 "verification",
31 "projects",
32 "time-and-money",
33 "web",
34 ] {
35 vfs.create_dir_all(&format!("/examples/code/{sub}")).await?;
36 }
37
38 for obsolete in [
41 "toggle.v",
42 "mutex.v",
43 "counter.v",
44 "enable-ready.hw",
45 "start-done.hw",
46 "write-full.hw",
47 ] {
48 let _ = vfs.remove(&format!("/examples/hardware/{obsolete}")).await;
49 }
50
51 for obsolete in [
54 "hello-world2.logos",
55 "fizzbuzz.logos",
56 "fizzbuzz2.logos",
57 "fizzbuzz3.logos",
58 "sum-list.logos",
59 "collections.logos",
60 "fibonacci.logos",
61 "factorial.logos",
62 "prime-check.logos",
63 "bubble-sort.logos",
64 "struct-demo.logos",
65 "error-handling.logos",
66 "types/enums-patterns.logos",
67 "native/tasks.logos",
68 "native/channels.logos",
69 "advanced/refinement.logos",
70 "advanced/assertions.logos",
71 "temporal/durations.logos",
72 ] {
73 let _ = vfs.remove(&format!("/examples/code/{obsolete}")).await;
74 }
75 for empty_dir in ["native", "advanced", "temporal"] {
76 let _ = vfs.remove(&format!("/examples/code/{empty_dir}")).await;
77 }
78
79 let _ = vfs.remove("/examples/logic/trivial-proof.logic").await;
81
82 for spec in seeded_examples() {
83 vfs.write(spec.vfs_path, spec.source.as_bytes()).await?;
84 }
85
86 Ok(())
87}
88
89pub fn seeded_examples() -> impl Iterator<Item = &'static ExampleSpec> {
94 ALL_LOGIC_EXAMPLES
95 .iter()
96 .chain(ALL_CODE_EXAMPLES)
97 .chain(ALL_MATH_EXAMPLES)
98 .chain(ALL_HARDWARE_SPECS)
99}
100
101pub const HARDWARE_EXAMPLES: &[(&str, &str)] = &[
107 (
108 "handshake.hw",
109 "# Handshake\n\
110 # Whenever request is high, acknowledge is high in the same cycle.\n\
111 \n\
112 Always, if request is high, then acknowledge is high.\n",
113 ),
114 (
115 "only-if.hw",
116 "# Grant Only If Requested\n\
117 # A grant never appears in a cycle without a request.\n\
118 \n\
119 Always, grant is high only if request is high.\n",
120 ),
121 (
122 "next-cycle.hw",
123 "# Grant in the Next Cycle\n\
124 # A request is answered with a grant one cycle later.\n\
125 \n\
126 Always, if request is high, then grant is high in the next cycle.\n",
127 ),
128 (
131 "intersection-design.hw",
132 "# Intersection Signal Plan\n\
133 # Five movements and the pairs that cannot go at once; the Studio finds a plan with the\n\
134 # fewest phases that keeps every such pair apart, and certifies no plan needs fewer.\n\
135 \n\
136 Movements: ns-through, ew-through, ns-left, ew-left, pedestrian.\n\
137 ns-through conflicts with ew-through and ew-left.\n\
138 ew-through conflicts with ns-left.\n\
139 ns-left conflicts with ew-left.\n\
140 pedestrian conflicts with ns-through, ew-through, ns-left and ew-left.\n",
141 ),
142 (
144 "t-junction.hw",
145 "# T-Junction Signal Plan\n\
146 # Three movements, every pair of them at odds: each needs a phase of its own.\n\
147 \n\
148 Movements: main-through, side-left, pedestrian.\n\
149 main-through conflicts with side-left.\n\
150 pedestrian conflicts with main-through and side-left.\n",
151 ),
152];
153
154pub const HW_MUTEX: &str = "# Mutual Exclusion\n\
159 # The two grants are never high in the same cycle.\n\
160 \n\
161 Always, not both grant0 is high and grant1 is high.\n";
162
163pub const RTL_EXAMPLES: &[(&str, &str)] = &[
169 (
170 "arbiter.v",
171 r#"// Round-Robin Arbiter
172// Two masters share a bus, and grants are issued in mutually exclusive branches. Proven by
173// k-induction for every request and turn sequence: the masters are never granted together.
174module arbiter(input clk, input r0, input r1);
175 reg g0;
176 reg g1;
177 reg turn;
178 initial begin
179 g0 = 0;
180 g1 = 0;
181 turn = 0;
182 end
183 always @(posedge clk) begin
184 if (r0 && (!r1 || turn == 0)) begin
185 g0 <= 1;
186 g1 <= 0;
187 end else if (r1) begin
188 g0 <= 0;
189 g1 <= 1;
190 end else begin
191 g0 <= 0;
192 g1 <= 0;
193 end
194 turn <= ~turn;
195 end
196 assert property (~(g0 & g1));
197endmodule
198"#,
199 ),
200 (
201 "bad-arbiter.v",
202 r#"// Buggy Arbiter
203// Each request is granted on its own, so when both masters ask in the same cycle, both are
204// granted. BMC finds the violation at step 1: the waveform shows r0 = r1 = 1, then g0 = g1 = 1.
205module bad_arbiter(input clk, input r0, input r1);
206 reg g0;
207 reg g1;
208 initial begin
209 g0 = 0;
210 g1 = 0;
211 end
212 always @(posedge clk) begin
213 if (r0)
214 g0 <= 1;
215 else
216 g0 <= 0;
217 if (r1)
218 g1 <= 1;
219 else
220 g1 <= 0;
221 end
222 assert property (~(g0 & g1));
223endmodule
224"#,
225 ),
226 (
227 "fifo.v",
228 r#"// FIFO Occupancy Counter
229// Depth 8, over free push and pop inputs: it counts up only when not full and down only when
230// not empty. Proven for every push and pop sequence: the count never passes 8, although the
231// 4-bit register could reach 15.
232module fifo(input clk, input push, input pop);
233 reg [3:0] count;
234 initial count = 0;
235 always @(posedge clk)
236 if (push && (count < 4'd8) && !(pop && (count > 4'd0)))
237 count <= count + 1;
238 else if (pop && (count > 4'd0) && !(push && (count < 4'd8)))
239 count <= count - 1;
240 else
241 count <= count;
242 assert property (count <= 4'd8);
243endmodule
244"#,
245 ),
246 (
247 "onehot.v",
248 r#"// One-Hot Ring
249// A 3-state one-hot ring: the rotation a <= c, b <= a, c <= b permutes the state bits.
250// Proven: exactly one of a, b and c is ever high (at least one, and at most one).
251module onehot(input clk);
252 reg a;
253 reg b;
254 reg c;
255 initial begin
256 a = 1;
257 b = 0;
258 c = 0;
259 end
260 always @(posedge clk) begin
261 a <= c;
262 b <= a;
263 c <= b;
264 end
265 assert property ((a | b | c) & ~(a & b) & ~(a & c) & ~(b & c));
266endmodule
267"#,
268 ),
269 (
270 "reset-mirror.v",
271 r#"// Reset Mirror
272// Two registers with the same reset-and-toggle logic over a free reset input. Proven by
273// k-induction for every reset sequence: a and b always stay equal.
274module mirror(input clk, input rst);
275 reg a;
276 reg b;
277 initial begin
278 a = 0;
279 b = 0;
280 end
281 always @(posedge clk) begin
282 if (rst)
283 a <= 0;
284 else
285 a <= ~a;
286 if (rst)
287 b <= 0;
288 else
289 b <= ~b;
290 end
291 assert property (a == b);
292endmodule
293"#,
294 ),
295 (
296 "traffic-safe.v",
297 r#"// Signalized Intersection
298// North-south and east-west through movements, protected left turns (nsl, ewl) and a
299// pedestrian phase, sequenced by a 9-state controller with a per-phase timer. Lights: 0 is
300// red, 1 green, 2 yellow. Proven by k-induction: no two conflicting movements are ever active
301// together, and pedestrians get WALK only while every vehicle movement is red.
302module traffic(input clk);
303 reg [1:0] ns;
304 reg [1:0] ew;
305 reg [1:0] nsl;
306 reg [1:0] ewl;
307 reg ped;
308 reg [3:0] phase;
309 reg [2:0] timer;
310 initial begin
311 ns = 2'd0;
312 ew = 2'd0;
313 nsl = 2'd1;
314 ewl = 2'd0;
315 ped = 1'd0;
316 phase = 4'd0;
317 timer = 3'd1;
318 end
319 always @(posedge clk)
320 if (timer == 3'd0) begin
321 timer <= 3'd1;
322 if (phase == 4'd0) begin
323 phase <= 4'd1;
324 nsl <= 2'd2;
325 ns <= 2'd0;
326 ew <= 2'd0;
327 ewl <= 2'd0;
328 ped <= 1'd0;
329 end else if (phase == 4'd1) begin
330 phase <= 4'd2;
331 nsl <= 2'd0;
332 ns <= 2'd1;
333 ew <= 2'd0;
334 ewl <= 2'd0;
335 ped <= 1'd0;
336 end else if (phase == 4'd2) begin
337 phase <= 4'd3;
338 ns <= 2'd2;
339 nsl <= 2'd0;
340 ew <= 2'd0;
341 ewl <= 2'd0;
342 ped <= 1'd0;
343 end else if (phase == 4'd3) begin
344 phase <= 4'd4;
345 ewl <= 2'd1;
346 ns <= 2'd0;
347 ew <= 2'd0;
348 nsl <= 2'd0;
349 ped <= 1'd0;
350 end else if (phase == 4'd4) begin
351 phase <= 4'd5;
352 ewl <= 2'd2;
353 ns <= 2'd0;
354 ew <= 2'd0;
355 nsl <= 2'd0;
356 ped <= 1'd0;
357 end else if (phase == 4'd5) begin
358 phase <= 4'd6;
359 ewl <= 2'd0;
360 ew <= 2'd1;
361 ns <= 2'd0;
362 nsl <= 2'd0;
363 ped <= 1'd0;
364 end else if (phase == 4'd6) begin
365 phase <= 4'd7;
366 ew <= 2'd2;
367 ns <= 2'd0;
368 nsl <= 2'd0;
369 ewl <= 2'd0;
370 ped <= 1'd0;
371 end else if (phase == 4'd7) begin
372 phase <= 4'd8;
373 ped <= 1'd1;
374 ns <= 2'd0;
375 ew <= 2'd0;
376 nsl <= 2'd0;
377 ewl <= 2'd0;
378 end else begin
379 phase <= 4'd0;
380 nsl <= 2'd1;
381 ns <= 2'd0;
382 ew <= 2'd0;
383 ewl <= 2'd0;
384 ped <= 1'd0;
385 end
386 end else
387 timer <= timer - 1;
388 assert property (~((ns != 2'd0) & (ew != 2'd0))
389 & ~((ped == 1'd1) & ((ns != 2'd0) | (ew != 2'd0) | (nsl != 2'd0) | (ewl != 2'd0))));
390endmodule
391"#,
392 ),
393 (
394 "traffic-crash.v",
395 r#"// Intersection With a Bug
396// The same intersection with one dangerous bug: the pedestrian phase raises WALK but turns
397// north-south green, sending pedestrians into live cross traffic. BMC finds the exact cycle;
398// watch the lights step through the real trace, then flash CONFLICT.
399module traffic(input clk);
400 reg [1:0] ns;
401 reg [1:0] ew;
402 reg [1:0] nsl;
403 reg [1:0] ewl;
404 reg ped;
405 reg [3:0] phase;
406 reg [2:0] timer;
407 initial begin
408 ns = 2'd0;
409 ew = 2'd0;
410 nsl = 2'd1;
411 ewl = 2'd0;
412 ped = 1'd0;
413 phase = 4'd0;
414 timer = 3'd1;
415 end
416 always @(posedge clk)
417 if (timer == 3'd0) begin
418 timer <= 3'd1;
419 if (phase == 4'd0) begin
420 phase <= 4'd1;
421 nsl <= 2'd2;
422 ns <= 2'd0;
423 ew <= 2'd0;
424 ewl <= 2'd0;
425 ped <= 1'd0;
426 end else if (phase == 4'd1) begin
427 phase <= 4'd2;
428 nsl <= 2'd0;
429 ns <= 2'd1;
430 ew <= 2'd0;
431 ewl <= 2'd0;
432 ped <= 1'd0;
433 end else if (phase == 4'd2) begin
434 phase <= 4'd3;
435 ns <= 2'd2;
436 nsl <= 2'd0;
437 ew <= 2'd0;
438 ewl <= 2'd0;
439 ped <= 1'd0;
440 end else if (phase == 4'd3) begin
441 phase <= 4'd4;
442 ewl <= 2'd1;
443 ns <= 2'd0;
444 ew <= 2'd0;
445 nsl <= 2'd0;
446 ped <= 1'd0;
447 end else if (phase == 4'd4) begin
448 phase <= 4'd5;
449 ewl <= 2'd2;
450 ns <= 2'd0;
451 ew <= 2'd0;
452 nsl <= 2'd0;
453 ped <= 1'd0;
454 end else if (phase == 4'd5) begin
455 phase <= 4'd6;
456 ewl <= 2'd0;
457 ew <= 2'd1;
458 ns <= 2'd0;
459 nsl <= 2'd0;
460 ped <= 1'd0;
461 end else if (phase == 4'd6) begin
462 phase <= 4'd7;
463 ew <= 2'd2;
464 ns <= 2'd0;
465 nsl <= 2'd0;
466 ewl <= 2'd0;
467 ped <= 1'd0;
468 end else if (phase == 4'd7) begin
469 phase <= 4'd8;
470 ped <= 1'd1;
471 ns <= 2'd1;
472 ew <= 2'd0;
473 nsl <= 2'd0;
474 ewl <= 2'd0;
475 end else begin
476 phase <= 4'd0;
477 nsl <= 2'd1;
478 ns <= 2'd0;
479 ew <= 2'd0;
480 ewl <= 2'd0;
481 ped <= 1'd0;
482 end
483 end else
484 timer <= timer - 1;
485 assert property (~((ns != 2'd0) & (ew != 2'd0))
486 & ~((ped == 1'd1) & ((ns != 2'd0) | (ew != 2'd0) | (nsl != 2'd0) | (ewl != 2'd0))));
487endmodule
488"#,
489 ),
490 (
491 "queue-jam.v",
492 r#"// Queue That Jams
493// An approach's queue is a counter. It is served only every other cycle while a car arrives
494// every cycle, so demand beats capacity and the queue climbs until it jams. BMC finds the
495// exact cycle it overflows: watch q ramp up in the waveform.
496module flow(input clk);
497 reg [2:0] q;
498 reg phase;
499 initial begin
500 q = 3'd0;
501 phase = 1'd0;
502 end
503 always @(posedge clk) begin
504 phase <= ~phase;
505 if (phase == 1'd1)
506 q <= q + 3'd1;
507 end
508 assert property (q < 3'd7);
509endmodule
510"#,
511 ),
512 (
513 "queue-stable.v",
514 r#"// Queue That Drains
515// The same queue, but service keeps up with demand, so a starting backlog only ever drains.
516// Proven by k-induction never to jam: for all time, not just a bounded window.
517module flow(input clk);
518 reg [2:0] q;
519 initial begin
520 q = 3'd5;
521 end
522 always @(posedge clk)
523 if (q != 3'd0)
524 q <= q - 3'd1;
525 assert property (q < 3'd7);
526endmodule
527"#,
528 ),
529 (
530 "datapath-identity.v",
531 r#"// Datapath Identity
532// The bit-blaster at work: for every 4-bit value of x, x + x equals 2 * x. x starts free (no
533// initial value) and holds, so the proof covers all 16 start values: a datapath identity
534// proven by k-induction, not sampled by simulation.
535module identity(input clk);
536 reg [3:0] x;
537 reg [3:0] a;
538 reg [3:0] b;
539 initial begin
540 a = 0;
541 b = 0;
542 end
543 always @(posedge clk) begin
544 x <= x;
545 a <= x + x;
546 b <= 4'd2 * x;
547 end
548 assert property (a == b);
549endmodule
550"#,
551 ),
552 (
553 "door-interlock.v",
554 r#"// Elevator Door Interlock
555// The door may open only while the car is stopped, and the car may move only while the door
556// is shut. Proven by k-induction for every request sequence: moving and door-open are never
557// true together.
558module interlock(input clk, input req_open, input start);
559 reg moving;
560 reg door;
561 initial begin
562 moving = 0;
563 door = 0;
564 end
565 always @(posedge clk) begin
566 if (start && !door && !req_open)
567 moving <= 1;
568 else if (!start)
569 moving <= 0;
570 if (req_open && !moving && !start)
571 door <= 1;
572 else
573 door <= 0;
574 end
575 assert property (~(moving & door));
576endmodule
577"#,
578 ),
579 (
580 "door-interlock-bug.v",
581 r#"// Interlock With a Dropped Guard
582// The same interlock with one guard dropped: the door answers req_open without checking the
583// car. BMC walks straight to the crash; the waveform shows the car moving with the door open
584// at cycle 2.
585module interlock(input clk, input req_open, input start);
586 reg moving;
587 reg door;
588 initial begin
589 moving = 0;
590 door = 0;
591 end
592 always @(posedge clk) begin
593 if (start && !door && !req_open)
594 moving <= 1;
595 else if (!start)
596 moving <= 0;
597 if (req_open)
598 door <= 1;
599 else
600 door <= 0;
601 end
602 assert property (~(moving & door));
603endmodule
604"#,
605 ),
606];
607
608pub const REGALLOC_EXAMPLES: &[(&str, &str)] = &[
612 (
613 "register-alloc-fits.hw",
614 "# Register Allocation That Fits\n\
615 # A basic block whose live ranges fit in 3 registers. Each line is\n\
616 # `variable: firstInstr-lastInstr`; `registers:` is the physical budget.\n\
617 \n\
618 registers: 3\n\
619 a: 0-4\n\
620 b: 1-3\n\
621 c: 2-6\n\
622 d: 5-9\n\
623 e: 7-10\n",
624 ),
625 (
626 "register-alloc-spill.hw",
627 "# Register Allocation Under Pressure\n\
628 # Four variables are live at once but only 3 registers exist, so the allocator certifies\n\
629 # (by the clique of mutually interfering ranges) that at least one must spill.\n\
630 \n\
631 registers: 3\n\
632 a: 0-6\n\
633 b: 1-7\n\
634 c: 2-8\n\
635 d: 3-9\n",
636 ),
637];
638
639pub const PIGEONHOLE_EXAMPLES: &[(&str, &str)] = &[
644 (
645 "pigeonhole.hw",
646 "# Pigeonhole\n\
647 # N pigeons into N-1 holes is impossible: watch the last pigeon find no home. Our prover\n\
648 # certifies UNSAT in polynomial time (maximum matching and symmetry breaking); every\n\
649 # resolution solver (Kissat, CaDiCaL, Z3) needs exponentially many steps here.\n\
650 \n\
651 pigeons: 6\n",
652 ),
653 (
654 "pigeonhole-12.hw",
655 "# Pigeonhole at 12\n\
656 # PHP(12): far past where Z3 times out, our certified PR proof stays polynomial.\n\
657 \n\
658 pigeons: 12\n",
659 ),
660];
661
662const LOGIC_GARDEN_PATH: &str = r#"# Garden-Path Sentences
669# The classic reduced relatives: "raced past the barn" modifies the horse.
670
671The horse raced past the barn fell.
672The man pushed fell.
673John said Mary ran.
674"#;
675
676const LOGIC_EVENTS_ADVERBS: &str = r#"# Event Semantics and Adverbs
677# Verbs become events; adverbs attach to the event variable, not the subject.
678
679John ran quickly.
680Mary sliced the bread carefully.
681Some dogs bark loudly.
682"#;
683
684const LOGIC_NPI: &str = r#"# Negation and "Any"
685# "any" is licensed by negation and conditionals, and maps to the right quantifier.
686
687John did not see any dogs.
688If any dog barks, John runs.
689No student saw any error.
690"#;
691
692const LOGIC_PLURALS: &str = r#"# Plurals and Collectives
693# Pairing with "respectively", collective sums with "together", reciprocal "each other".
694
695John and Mary helped Tom and Jerry respectively.
696The boys gathered.
697The boys lifted the piano together.
698John and Mary love each other.
699"#;
700
701const LOGIC_COMPARATIVES: &str = r#"# Comparatives and Superlatives
702# Degrees, measure phrases, and the superlative's hidden universal.
703
704John is taller than Bill is.
705John is 2 inches taller than Mary.
706John climbed the highest mountain.
707"#;
708
709const LOGIC_MODALITY: &str = r#"# Modality
710# Necessity ("must") and possibility ("can") under generalized quantifiers like "few birds".
711
712All students must study.
713Few birds can fly.
714Some birds cannot fly.
715"#;
716
717const LOGIC_DONKEY: &str = r#"# Donkey Sentences
718# The classic that breaks naive translation: "it" must reach back inside
719# the relative clause. Discourse representation gets the binding right.
720
721Every farmer who owns a donkey beats it.
722If a farmer owns a donkey, he beats it.
723No farmer who owns a donkey beats it.
724"#;
725
726const LOGIC_INTENSIONALITY: &str = r#"# Seeking Unicorns
727# "seeks a unicorn" does not entail a unicorn exists: the theme stays
728# intensional (^), unlike an ordinary object.
729
730John seeks a unicorn.
731Mary needs a doctor.
732John believes a spy exists.
733"#;
734
735const LOGIC_COUNTERFACTUALS: &str = r#"# Counterfactuals
736# "had studied / would have passed" becomes the Lewis conditional.
737
738If John had studied, he would have passed.
739If the glass had fallen, it would have broken.
740"#;
741
742const LOGIC_NEITHER_NOR: &str = r#"# Neither Nor
745# "Neither A nor B" denies both.
746
747## Theorem: Neither_Nor
748Given: Neither Alice nor Bob is guilty.
749Prove: Bob is not guilty.
750Proof: Auto.
751"#;
752
753const LOGIC_EQUALITY_REWRITE: &str = r#"# Rewriting by Equality
754# Once Alice is Bob, whatever is said of Bob can be said of Alice.
755
756## Theorem: Equality_Rewrite
757Given: Alice is equal to Bob.
758Given: If Alice is happy then Alice is dancing.
759Given: Bob is happy.
760
761Prove: Bob is dancing.
762Proof: Auto.
763"#;
764
765const LOGIC_PRESUPPOSITION: &str = r#"# What Regret Takes for Granted
766# "Mary does not regret lying" still takes it for granted that she lied.
767
768## Theorem: What_Regret_Takes_For_Granted
769Given: Mary does not regret lying.
770Prove: Mary lied.
771Proof: Auto.
772"#;
773
774const LOGIC_GRID_STARTER: &str = r#"# A Mini Logic Grid
775# Two trips, two years, two states: the exactly-one clues leave one answer.
776
777## Theorem: Mini_Grid
778Given: Alpha is a trip.
779Given: Beta is a trip.
780Given: Alpha is not Beta.
781Given: Every trip is in 2003 or in 2004.
782Given: Every trip is in Florida or in Maine.
783Given: Exactly one trip is in 2003.
784Given: Exactly one trip is in Florida.
785Given: Alpha is in 2003.
786Given: Alpha is in Florida.
787
788Prove: Beta is in Maine.
789Proof: Auto.
790"#;
791
792const LOGIC_GRID_QUESTION: &str = r#"# Asking the Puzzle
793# The same grid, asked as a question: the prover names the trip that is in Maine.
794
795## Theorem: Ask_The_Puzzle
796Given: Alpha is a trip.
797Given: Beta is a trip.
798Given: Alpha is not Beta.
799Given: Every trip is in 2003 or in 2004.
800Given: Every trip is in Florida or in Maine.
801Given: Exactly one trip is in 2003.
802Given: Exactly one trip is in Florida.
803Given: Alpha is in 2003.
804Given: Alpha is in Florida.
805
806Prove: Who is in Maine?
807Proof: Auto.
808"#;
809
810const LOGIC_TACTIC_SCRIPT: &str = r#"# A Proof by Hand
811# A labelled premise and a tactic script: take the conjunction apart, then rebuild it.
812
813## Theorem: By_Hand
814Given (h): Bob is happy and Bob is tall.
815Prove: Bob is tall and Bob is happy.
816Proof: cases h. split. assumption. assumption.
817"#;
818
819pub const LOGIC_SIMPLE: &str = r#"# Simple Sentences
820# Plain sentences, each read into first-order logic.
821
822Every cat sleeps.
823Some dogs bark loudly.
824John loves Mary.
825The quick brown fox jumps.
826No student failed.
827"#;
828
829pub const LOGIC_QUANTIFIERS: &str = r#"# Quantifier Scope
830# Two quantifiers in one sentence: which one takes scope over the other.
831
832Every student read a book.
833A professor supervises every student.
834No student failed every exam.
835Some teacher praised every student.
836Every dog chased some cat.
837"#;
838
839const LOGIC_TENSE: &str = r#"# Tense and Aspect
840# Past, perfect, future and progressive, each read onto the event it describes.
841
842John was running.
843Mary has eaten.
844The train will arrive.
845She had been sleeping.
846They have been working.
847"#;
848
849const LOGIC_PROVER: &str = r#"# Socrates Is Mortal
854# The classic syllogism, proved by the kernel-certified prover.
855
856## Theorem: Socrates_Mortality
857Given: All men are mortal.
858Given: Socrates is a man.
859Prove: Socrates is mortal.
860Proof: Auto.
861"#;
862
863const LOGIC_SIMON: &str = r#"# The Simon Logic Grid
870# Four trips, each in a year and a state, with a friend and an activity, and six clues.
871# The prover grounds the puzzle to its finite domain and derives where Beta went.
872
873## Theorem: Simon
874Given: Alpha, Beta, Gamma, and Delta are four different trips.
875Given: 2001, 2002, 2003, and 2004 are four different years.
876Given: Connecticut, Florida, Kentucky, and Maine are four different states.
877Given: Bill, Lillie, Neal, and Yvonne are four different friends.
878Given: Cycling, hunting, kayaking, and skydiving are four different activities.
879Given: Every trip is in 2001 or in 2002 or in 2003 or in 2004.
880Given: Exactly one trip is in 2001.
881Given: Exactly one trip is in 2002.
882Given: Exactly one trip is in 2003.
883Given: Exactly one trip is in 2004.
884Given: Every trip is in Connecticut or in Florida or in Kentucky or in Maine.
885Given: Exactly one trip is in Connecticut.
886Given: Exactly one trip is in Florida.
887Given: Exactly one trip is in Kentucky.
888Given: Exactly one trip is in Maine.
889Given: Every trip is with Bill or with Lillie or with Neal or with Yvonne.
890Given: Exactly one trip is with Bill.
891Given: Exactly one trip is with Lillie.
892Given: Exactly one trip is with Neal.
893Given: Exactly one trip is with Yvonne.
894Given: Every trip is cycling or hunting or kayaking or skydiving.
895Given: Exactly one trip is cycling.
896Given: Exactly one trip is hunting.
897Given: Exactly one trip is kayaking.
898Given: Exactly one trip is skydiving.
899Given: Alpha is in 2001.
900Given: Beta is in 2002.
901Given: Gamma is in 2003.
902Given: Delta is in 2004.
903Given: Of the hunting trip and the 2004 trip, one was with Neal and the other was in Connecticut.
904Given: The Florida trip was the hunting trip.
905Given: Neither the trip with Bill nor the Florida trip is the 2001 trip.
906Given: The trip with Yvonne is not in Kentucky.
907Given: Of the skydiving trip and the Maine trip, one was in 2003 and the other was with Bill.
908Given: The 2003 trip is not the cycling trip.
909
910Prove: Beta is in Florida.
911Proof: Auto.
912"#;
913
914const LOGIC_SYLLOGISM: &str = r#"# A Chain of Syllogisms
915# Two universal premises chained: men are mortal, and mortals are doomed.
916
917## Theorem: Chain_Reasoning
918Given: All men are mortal.
919Given: All mortals are doomed.
920Given: Plato is a man.
921
922Prove: Plato is doomed.
923Proof: Auto.
924"#;
925
926const LOGIC_DISJUNCTIVE: &str = r#"# Disjunctive Syllogism
927# One of two is guilty; ruling one out convicts the other.
928
929## Theorem: Disjunctive_Syllogism
930Given: Either Alice or Bob is guilty.
931Given: Alice is not guilty.
932Prove: Bob is guilty.
933Proof: Auto.
934"#;
935
936const LOGIC_MODUS_TOLLENS: &str = r#"# Modus Tollens
937# Two conditionals, followed backwards from a consequent that did not happen.
938
939## Theorem: Modus_Tollens_Chain
940Given: If the butler did it, he was seen.
941Given: If he was seen, he was caught.
942Given: He was not caught.
943
944Prove: The butler did not do it.
945Proof: Auto.
946"#;
947
948pub const LOGIC_LEIBNIZ: &str = r#"# Leibniz's Law
949# Identical things share their properties: what holds of Clark holds of Superman.
950
951## Theorem: Leibniz_Identity
952Given: Clark is Superman.
953Given: Clark is mortal.
954Prove: Superman is mortal.
955Proof: Auto.
956"#;
957
958pub const LOGIC_BARBER: &str = r#"# The Barber Paradox
959# A barber who shaves exactly the men who do not shave themselves cannot exist.
960
961## Theorem: Barber_Paradox
962Given: The barber is a man.
963Given: The barber shaves all men who do not shave themselves.
964Given: The barber does not shave any man who shaves himself.
965
966Prove: The barber does not exist.
967Proof: Auto.
968"#;
969
970pub const CODE_HELLO: &str = r#"# Hello, LOGOS
975-- A program is numbered sections of English sentences.
976
977## Main
978
979Let greeting be "Hello, LOGOS!".
980Show greeting.
981
982Let x be 10.
983Let y be 20.
984Show "{x} + {y} = {x + y}".
985"#;
986
987const CODE_SYNTAX_FLAVORS: &str = r#"# Many Surfaces, One Meaning
990-- LOGOS accepts several spellings for the same idea. This example
991-- tours the variants; the rest of the catalog sticks to one style.
992
993## Main
994
995Let classic be 20.
996greeting = "bound with the = sign".
997Show greeting.
998Show "Let and = both bind values: {classic}".
999
1000Let n be 15.
1001If n is divisible by 15:
1002 Show "Otherwise If flavor: FizzBuzz".
1003Otherwise If n is divisible by 3:
1004 Show "Otherwise If flavor: Fizz".
1005Otherwise:
1006 Show "Otherwise If flavor: {n}".
1007
1008If n is divisible by 15:
1009 Show "elif flavor: FizzBuzz".
1010elif n is divisible by 3:
1011 Show "elif flavor: Fizz".
1012Else:
1013 Show "elif flavor: {n}".
1014
1015Let mut short_form be 1.
1016Let mutable long_form be 2.
1017Set short_form to short_form + 9.
1018Show "mut and mutable both work: {short_form + long_form}".
1019
1020If n % 5 equals 0 and n is divisible by 5:
1021 Show "symbols and English agree: {n} is divisible by 5".
1022"#;
1023
1024pub const CODE_FIBONACCI: &str = r#"# Fibonacci
1025-- Each number is the sum of the two before it.
1026
1027## Main
1028
1029Let n be 10.
1030Let mutable a be 0.
1031Let mutable b be 1.
1032
1033Show "The first {n} Fibonacci numbers:".
1034
1035Repeat for i from 1 to n:
1036 Show b.
1037 Let next be a + b.
1038 Set a to b.
1039 Set b to next.
1040"#;
1041
1042const CODE_FIZZBUZZ: &str = r#"# FizzBuzz
1043-- The classic: `is divisible by` reads exactly like the rule.
1044
1045## Main
1046
1047Repeat for i from 1 to 20:
1048 If i is divisible by 15:
1049 Show "FizzBuzz".
1050 Otherwise If i is divisible by 3:
1051 Show "Fizz".
1052 Otherwise If i is divisible by 5:
1053 Show "Buzz".
1054 Otherwise:
1055 Show i.
1056"#;
1057
1058const CODE_COLLECTIONS: &str = r#"# Lists
1059-- Lists are 1-indexed: item 1 is the first element.
1060
1061## Main
1062
1063Let mutable numbers be [10, 20, 30, 40, 50].
1064Show "Numbers: {numbers}".
1065
1066Push 60 to numbers.
1067Show "After pushing 60: {numbers}".
1068Show "The list now holds {length(numbers)} items.".
1069
1070Let first be item 1 of numbers.
1071Let last be item 6 of numbers.
1072Show "First: {first}, last: {last}.".
1073
1074Let mutable total be 0.
1075Repeat for n in numbers:
1076 Set total to total + n.
1077Show "Sum of all items: {total}".
1078
1079Pop from numbers into removed.
1080Show "Popped {removed}; {length(numbers)} items remain.".
1081"#;
1082
1083const CODE_FACTORIAL: &str = r#"# Recursion
1084-- A function may call itself, as long as a base case stops it.
1085
1086## To factorial (n: Int) -> Int:
1087 If n <= 1:
1088 Return 1.
1089 Return n * factorial(n - 1).
1090
1091## To fib (n: Int) -> Int:
1092 If n <= 2:
1093 Return 1.
1094 Return fib(n - 1) + fib(n - 2).
1095
1096## Main
1097
1098Show "factorial(5) = {factorial(5)}".
1099Show "factorial(10) = {factorial(10)}".
1100Show "fib(10) = {fib(10)}".
1101"#;
1102
1103const CODE_PRIME: &str = r#"# Prime Check
1104-- Trial division: prime means nothing divides it.
1105
1106## To is_prime (n: Int) -> Bool:
1107 If n <= 1:
1108 Return false.
1109 Let mutable i be 2.
1110 While i * i <= n:
1111 If n is divisible by i:
1112 Return false.
1113 Set i to i + 1.
1114 Return true.
1115
1116## Main
1117
1118Show "Checking 2 through 30:".
1119Repeat for candidate from 2 to 30:
1120 If is_prime(candidate):
1121 Show "{candidate} is prime".
1122"#;
1123
1124const CODE_BUBBLE_SORT: &str = r#"# Bubble Sort
1125-- Each pass bubbles the largest value to the end.
1126-- The `swapped` flag stops early once a pass changes nothing.
1127
1128## Main
1129
1130Let mutable numbers be [64, 34, 25, 12, 22, 11, 90].
1131Show "Before: {numbers}".
1132
1133Let n be length(numbers).
1134Let mutable limit be n - 1.
1135Let mutable swapped be true.
1136While swapped:
1137 Set swapped to false.
1138 Repeat for j from 1 to limit:
1139 Let a be item j of numbers.
1140 Let b be item (j + 1) of numbers.
1141 If a > b:
1142 Set item j of numbers to b.
1143 Set item (j + 1) of numbers to a.
1144 Set swapped to true.
1145 Set limit to limit - 1.
1146
1147Show "After: {numbers}".
1148"#;
1149
1150const CODE_STRUCT: &str = r#"# Structs
1151-- A struct groups named fields; build one with `with`.
1152-- Fields may also be written as: a public name, which is Text.
1153
1154## Definition
1155
1156A Person has:
1157 name: Text.
1158 age: Int.
1159
1160## Main
1161
1162Let alice be a new Person with name "Alice" and age 30.
1163Let bob be a new Person with name "Bob" and age 25.
1164
1165Show "{alice's name} is {alice's age}.".
1166Show "{bob's name} is {bob's age}.".
1167
1168Set alice's age to 31.
1169Show "After a birthday, {alice's name} is {alice's age}.".
1170"#;
1171
1172const CODE_ENUMS: &str = r#"# Enums
1179-- An enum names a closed set of variants; Inspect matches them.
1180
1181## A Color is one of:
1182 A Red.
1183 A Green.
1184 A Blue.
1185
1186## Main
1187
1188Let c be a new Red.
1189Inspect c:
1190 When Red: Show "It's red!".
1191 When Green: Show "It's green!".
1192 When Blue: Show "It's blue!".
1193
1194Let c2 be a new Blue.
1195Inspect c2:
1196 When Red: Show "red".
1197 Otherwise: Show "not red".
1198"#;
1199
1200const CODE_GENERICS: &str = r#"# Generics
1201-- A type can take type parameters, written in brackets.
1202
1203## A Box of [T] has:
1204 contents: T.
1205
1206## A Pair of [A] and [B] has:
1207 first: A.
1208 second: B.
1209
1210## Main
1211
1212Let answer be a new Box of Int with contents 42.
1213Show "The Int box holds {answer's contents}.".
1214
1215Let message be a new Box of Text with contents "hello".
1216Show "The Text box holds {message's contents}.".
1217
1218Let entry be a new Pair of Text and Int with first "score" and second 97.
1219Show "Pair: {entry's first} = {entry's second}.".
1220"#;
1221
1222const CODE_SETS: &str = r#"# Sets
1225-- A set keeps one copy of each value.
1226
1227## Main
1228
1229Let names be a new Set of Text.
1230Add "Alice" to names.
1231Add "Bob" to names.
1232Add "Charlie" to names.
1233Add "Alice" to names.
1234Let count be length of names.
1235Show "After 4 adds (one duplicate): {count} members.".
1236
1237If names contains "Bob":
1238 Show "Bob is in the set.".
1239Remove "Bob" from names.
1240Let remaining be length of names.
1241Show "After removing Bob: {remaining} members.".
1242
1243Let evens be a new Set of Int.
1244Add 2 to evens.
1245Add 4 to evens.
1246Let small be a new Set of Int.
1247Add 1 to small.
1248Add 2 to small.
1249
1250Let both be evens union small.
1251Show "union: {both}".
1252Let shared be evens intersection small.
1253Show "intersection: {shared}".
1254Let rest be evens without small.
1255Show "difference: {rest}".
1256"#;
1257
1258const CODE_MAPS: &str = r#"# Maps
1259-- A map stores values by key; both access forms below are equivalent.
1260
1261## Main
1262
1263Let mutable inventory be a new Map of Text to Int.
1264Set inventory["iron"] to 50.
1265Set inventory["copper"] to 30.
1266Set item "gold" of inventory to 10.
1267
1268Let iron be inventory["iron"].
1269Show "iron count: {iron}".
1270
1271Set inventory["iron"] to 100.
1272Let updated be item "iron" of inventory.
1273Show "after restock: {updated}".
1274
1275Show "Full inventory:".
1276Repeat for (name, count) in inventory:
1277 Show " {name}: {count}".
1278"#;
1279
1280const CODE_HIGHER_ORDER: &str = r#"# Higher-Order Functions
1283-- Functions are values: pass them in, get new ones back.
1284
1285## To twice (f: fn(Int) -> Int) and (x: Int) -> Int:
1286 Return f(f(x)).
1287
1288## To makeAdder (n: Int) -> fn(Int) -> Int:
1289 Return (x: Int) -> x + n.
1290
1291## Main
1292
1293Let double be (x: Int) -> x * 2.
1294Let doubled be double(21).
1295Show "double(21) = {doubled}".
1296
1297Let quadrupled be twice(double, 5).
1298Show "twice(double, 5) = {quadrupled}".
1299
1300Let add10 be makeAdder(10).
1301Let sum be add10(32).
1302Show "makeAdder(10) applied to 32 = {sum}".
1303"#;
1304
1305pub const CODE_CRDT_COUNTERS: &str = r#"# Convergent Counter
1308-- A Shared type's fields are CRDTs: they merge without conflicts.
1309
1310## Definition
1311A Counter is Shared and has:
1312 points: ConvergentCount.
1313
1314## Main
1315Let mutable c be a new Counter.
1316Increase c's points by 10.
1317Increase c's points by 5.
1318Increase c's points by 3.
1319Show "Total points: {c's points}".
1320"#;
1321
1322const CODE_POLICIES: &str = r#"# Policies & Capabilities
1325-- Policy rules read like a security document — and Check enforces them.
1326
1327## Definition
1328A User has:
1329 a name: Text.
1330 a role: Text.
1331
1332A Document has:
1333 an owner: Text.
1334
1335## Policy
1336A User is admin if the user's role equals "admin".
1337A User can edit the Document if:
1338 The user is admin, OR
1339 The user's name equals the document's owner.
1340
1341## Main
1342
1343Let root be a new User with name "Root" and role "admin".
1344Check that root is admin.
1345Show "Admin check passed: Root is admin.".
1346
1347Let alice be a new User with name "Alice" and role "editor".
1348Let doc be a new Document with owner "Alice".
1349Check that alice can edit doc.
1350Show "Capability check passed: Alice can edit her own document.".
1351"#;
1352
1353const CODE_ZONES: &str = r#"# Memory Zones
1356-- A zone is an arena: everything allocated inside is freed at the end.
1357
1358## Main
1359
1360Inside a zone called "Work":
1361 Let x be 42.
1362 Let y be 58.
1363 Show "Sum in zone: {x + y}".
1364
1365Inside a zone called "Buffer" of size 1 MB:
1366 Let value be 100.
1367 Show "Value in the 1 MB zone: {value}".
1368
1369Show "Zones cleaned up!".
1370"#;
1371
1372const CODE_TASKS: &str = r#"# Tasks
1375-- Launch runs a function concurrently; a handle can stop it.
1376
1377## To worker:
1378 Show "worker done".
1379
1380## To greet (name: Text):
1381 Show "Hello from {name}".
1382
1383## Main
1384
1385Launch a task to worker.
1386Show "main continues".
1387
1388Launch a task to greet with "a task".
1389
1390Let handle be Launch a task to worker.
1391Stop handle.
1392Show "second worker stopped".
1393"#;
1394
1395const CODE_CHANNELS: &str = r#"# Pipes
1396-- A pipe carries values between tasks; Send blocks, Try does not.
1397
1398## Main
1399
1400Let ch be a Pipe of Int.
1401Send 42 into ch.
1402Receive x from ch.
1403Show "received: {x}".
1404
1405Try to send 7 into ch.
1406Try to receive y from ch.
1407Show "try-receive got: {y}".
1408"#;
1409
1410const CODE_INTERPOLATION: &str = r#"# String Interpolation
1413-- Any expression can sit in a {hole}; a colon adds a format spec.
1414
1415## Main
1416
1417Let name be "Ada".
1418Let age be 36.
1419Show "{name} is {age}.".
1420Show "Next year she will be {age + 1}.".
1421
1422Let pi be 3.14159.
1423Show "pi to two places: {pi:.2}".
1424
1425Let item be "socks".
1426Show "|{item:>10}|".
1427Show "|{item:<10}|".
1428Show "|{item:^10}|".
1429
1430Let price be 19.99.
1431Show "that will be {price:$}".
1432
1433Let x be 42.
1434Show "debugging: {x=}".
1435Show "literal braces: {{not a hole}}".
1436"#;
1437
1438const CODE_NUMBERS: &str = r#"# Numbers Big & Small
1439-- Ints are exact and grow past 64 bits; Decimals never drift.
1440
1441## Main
1442
1443Let big be 2 ** 100.
1444Show "2 to the 100th = {big}".
1445
1446Let third be 1.0 / 3.0.
1447Show "a third to 4 places: {third:.4}".
1448
1449Let close be 0.1 + 0.2.
1450If close is approximately 0.3:
1451 Show "0.1 + 0.2 is approximately 0.3 (floats drift)".
1452
1453Let exact be decimal("0.1") + decimal("0.2").
1454Show "with Decimal it is exactly {exact}".
1455"#;
1456
1457const CODE_TEXT_BASICS: &str = r#"# Working with Text
1458-- Text is 1-indexed like every LOGOS collection.
1459
1460## Main
1461
1462Let word be "LOGOS".
1463Let letters be length of word.
1464Show "{word} has {letters} letters.".
1465
1466Let first be item 1 of word.
1467Show "It starts with {first}.".
1468
1469If word contains "GO":
1470 Show "There is GO in {word}.".
1471
1472Let greeting be "Hello, " combined with "world!".
1473Show greeting.
1474
1475Let mutable reversed be "".
1476Let mutable i be letters.
1477While i >= 1:
1478 Let c be item i of word.
1479 Set reversed to reversed combined with c.
1480 Set i to i - 1.
1481Show "Reversed: {reversed}".
1482"#;
1483
1484const CODE_FORMATTING: &str = r#"# Formatted Output
1485-- Alignment and currency specs build tidy reports in the string itself.
1486
1487## Main
1488
1489Let header_item be "item".
1490Let header_cost be "cost".
1491Show "{header_item:<10}{header_cost:>8}".
1492
1493Let apples be "apples".
1494Let apples_cost be 1.25.
1495Show "{apples:<10}{apples_cost:>8}".
1496
1497Let bread be "bread".
1498Let bread_cost be 3.5.
1499Show "{bread:<10}{bread_cost:>8}".
1500
1501Let total be apples_cost + bread_cost.
1502Show "total: {total:$}".
1503"#;
1504
1505const CODE_FIND_AND_COUNT: &str = r#"# Scan & Count
1506-- Walk a Text by index to count what you care about.
1507
1508## Main
1509
1510Let sentence be "the cat sat on the mat".
1511Let target be "t".
1512Let mutable count be 0.
1513Let chars be length of sentence.
1514Repeat for i from 1 to chars:
1515 If item i of sentence equals target:
1516 Set count to count + 1.
1517Show "the letter {target} appears {count} times".
1518
1519Let mutable words be 1.
1520Repeat for i from 1 to chars:
1521 If item i of sentence equals " ":
1522 Set words to words + 1.
1523Show "the sentence has {words} words".
1524"#;
1525
1526const CODE_SLICING: &str = r#"# Slices & Copies
1527-- items M through N is an inclusive slice; copy of duplicates.
1528
1529## Main
1530
1531Let scores be [55, 70, 85, 90, 60].
1532Let middle be items 2 through 4 of scores.
1533Show "middle three: {middle}".
1534
1535Let mutable working be copy of scores.
1536Set item 1 of working to 100.
1537Show "edited copy: {working}".
1538Show "original untouched: {scores}".
1539"#;
1540
1541const CODE_TUPLES: &str = r#"# Tuples
1542-- A tuple holds a fixed group of mixed-type values, 1-indexed.
1543
1544## Main
1545
1546Let point be (10, 20).
1547Show "x = {point[1]}, y = {point[2]}".
1548
1549Let city be ("Berlin", 3600000, true).
1550Show "{city[1]} has {city[2]} people".
1551Let slots be length of city.
1552Show "the tuple has {slots} slots".
1553
1554Let mutable capitals be a new Map of Text to Text.
1555Set capitals["Germany"] to "Berlin".
1556Set capitals["France"] to "Paris".
1557Repeat for (country, capital) in capitals:
1558 Show "{capital} is the capital of {country}".
1559"#;
1560
1561const CODE_FILTER_TRANSFORM: &str = r#"# Filter & Transform
1562-- The Repeat + Push pair is LOGOS's map/filter workhorse.
1563
1564## Main
1565
1566Let numbers be [1, 2, 3, 4, 5, 6].
1567
1568Let mutable evens be a new Seq of Int.
1569Repeat for n in numbers:
1570 If n is even:
1571 Push n to evens.
1572Show "evens: {evens}".
1573
1574Let mutable squares be a new Seq of Int.
1575Repeat for n in evens:
1576 Push n * n to squares.
1577Show "their squares: {squares}".
1578
1579Let mutable total be 0.
1580Repeat for n in squares:
1581 Set total to total + n.
1582Show "sum of squares: {total}".
1583"#;
1584
1585const CODE_DATES: &str = r#"# Dates & Moments
1586-- Dates, times of day, spans, and moments are all literal values.
1587
1588## Main
1589
1590Let liftoff be 2026-05-20.
1591Show "liftoff day: {liftoff}".
1592
1593Let prep be liftoff - 3 days.
1594Show "prep starts: {prep}".
1595
1596Let review be liftoff + 2 months.
1597Show "review lands: {review}".
1598
1599Let sprint be 2 weeks and 3 days.
1600Show "sprint length: {sprint}".
1601
1602Let standup be 9:30am.
1603Show "daily standup: {standup}".
1604
1605Let kickoff be 2026-05-20 at 4pm.
1606Show "kickoff moment: {kickoff}".
1607
1608If 9am < noon:
1609 Show "9am is before noon".
1610"#;
1611
1612const CODE_MONEY: &str = r#"# Money
1613-- Decimal keeps cents exact; the :$ spec prints currency.
1614
1615## Main
1616
1617Let latte be decimal("4.50").
1618Let muffin be decimal("3.25").
1619Let subtotal be latte + muffin.
1620Show "subtotal: {subtotal:$}".
1621
1622Let two_rounds be subtotal * 2.
1623Show "two rounds: {two_rounds:$}".
1624
1625Let tip be decimal("1.55").
1626Let total be two_rounds + tip.
1627Show "with tip: {total:$}".
1628
1629Let cents be decimal("0.1") + decimal("0.2").
1630Show "0.1 + 0.2 = {cents} exactly (no float drift)".
1631"#;
1632
1633const CODE_DEFINING: &str = r#"# Defining Functions
1636-- Parameters are named and typed; prepositions read naturally.
1637
1638## To area (width: Int) and (height: Int) -> Int:
1639 Return width * height.
1640
1641## To withdraw (amount: Int) from (balance: Int) -> Int:
1642 Return balance - amount.
1643
1644## To greet (name: Text):
1645 Show "Welcome, {name}!".
1646
1647## Main
1648
1649Let room be area(12, 10).
1650Show "a 12 x 10 room covers {room} square feet".
1651
1652Let left be withdraw(40, 100).
1653Show "balance after withdrawing 40 from 100: {left}".
1654
1655Let guest be "Ada".
1656Give guest to greet.
1657"#;
1658
1659const CODE_CLOSURES: &str = r#"# Closures
1660-- A closure is an unnamed function value; it captures what it uses.
1661
1662## Main
1663
1664Let double be (x: Int) -> x * 2.
1665Let doubled be double(21).
1666Show "double(21) = {doubled}".
1667
1668Let bonus be 100.
1669Let with_bonus be (score: Int) -> score + bonus.
1670Let final_score be with_bonus(42).
1671Show "42 with the captured bonus of {bonus}: {final_score}".
1672
1673Let describe be (n: Int) ->:
1674 If n is even:
1675 Return "{n} is even".
1676 Return "{n} is odd".
1677Let verdict be describe(7).
1678Show verdict.
1679"#;
1680
1681const CODE_UFCS: &str = r#"# Method-Style Calls
1682-- Any function can be called like a method: the receiver is argument one.
1683
1684## To double (x: Int) -> Int:
1685 Return x * 2.
1686
1687## To plus (a: Int) and (b: Int) -> Int:
1688 Return a + b.
1689
1690## Main
1691
1692Let classic be double(5).
1693Show "function style: double(5) = {classic}".
1694
1695Let method be (5).double().
1696Show "method style: (5).double() = {method}".
1697
1698Let chained be (5).double().plus(3).double().
1699Show "chained: (5).double().plus(3).double() = {chained}".
1700"#;
1701
1702const CODE_BYTES_WORDS: &str = r#"# Bits, Bytes & Words
1703-- Word types are fixed-width rings: arithmetic wraps, never traps.
1704
1705## Main
1706
1707Let max32 be word32(4294967295).
1708Let wrapped be max32 + word32(1).
1709Show "4294967295 + 1 wraps to {wrapped}".
1710
1711Let low_bit be word32(1).
1712Let nudged be low_bit shifted left by 4.
1713Show "1 shifted left by 4 = {nudged}".
1714Let back be nudged shifted right by 2.
1715Show "16 shifted right by 2 = {back}".
1716
1717Let bits be count_ones(255).
1718Show "count_ones(255) = {bits}".
1719
1720Let mask be 255 & 170.
1721Show "255 AND 170 = {mask}".
1722Let mixed be 85 | 170.
1723Show "85 OR 170 = {mixed}".
1724Let flipped be 255 ^ 85.
1725Show "255 XOR 85 = {flipped}".
1726
1727Let letter be `A`.
1728Show "a Char literal: {letter}".
1729"#;
1730
1731const CODE_EXACT_NUMBERS: &str = r#"# Exact Arithmetic
1732-- Rationals stay fractions; Decimals keep scale; Complex is built in.
1733
1734## Main
1735
1736Let r: Rational be 1 / 3.
1737Let s: Rational be 1 / 6.
1738Let sum be r + s.
1739Show "1/3 + 1/6 = {sum}".
1740
1741Let precise be decimal("19.99") * 3.
1742Show "19.99 * 3 = {precise} (no float drift)".
1743
1744Let i be complex(0, 1).
1745Let squared be i * i.
1746Show "i * i = {squared}".
1747"#;
1748
1749const CODE_SIEVE: &str = r#"# Sieve of Eratosthenes
1752-- Cross out every multiple; what survives is prime.
1753
1754## Main
1755
1756Let limit be 100.
1757Let mutable is_prime be a new Seq of Bool.
1758Repeat for i from 1 to limit:
1759 Push true to is_prime.
1760
1761Set item 1 of is_prime to false.
1762Let mutable p be 2.
1763While p * p <= limit:
1764 If item p of is_prime:
1765 Let mutable multiple be p * p.
1766 While multiple <= limit:
1767 Set item multiple of is_prime to false.
1768 Set multiple to multiple + p.
1769 Set p to p + 1.
1770
1771Let mutable count be 0.
1772Let mutable largest be 0.
1773Repeat for i from 1 to limit:
1774 If item i of is_prime:
1775 Set count to count + 1.
1776 Set largest to i.
1777Show "{count} primes at or below {limit}".
1778Show "the largest is {largest}".
1779"#;
1780
1781const CODE_BINARY_SEARCH: &str = r#"# Binary Search
1782-- Halve the search space until the target is cornered.
1783
1784## To find_index (target: Int) and (xs: Seq of Int) -> Int:
1785 Let mutable lo be 1.
1786 Let mutable hi be length of xs.
1787 While lo <= hi:
1788 Let mid be (lo + hi) / 2.
1789 Let candidate be item mid of xs.
1790 If candidate equals target:
1791 Return mid.
1792 If candidate < target:
1793 Set lo to mid + 1.
1794 Otherwise:
1795 Set hi to mid - 1.
1796 Return 0.
1797
1798## Main
1799
1800Let ordered be [3, 8, 15, 23, 42, 57, 91].
1801Let hit be find_index(42, ordered).
1802Show "found 42 at position {hit}".
1803Let miss be find_index(50, ordered).
1804If miss equals 0:
1805 Show "50 is not present".
1806"#;
1807
1808const CODE_MERGE_SORT: &str = r#"# Merge Sort
1809-- Split in half, sort each side, merge the fronts.
1810
1811## To merge_sorted (a: Seq of Int) and (b: Seq of Int) -> Seq of Int:
1812 Let mutable merged be a new Seq of Int.
1813 Let mutable i be 1.
1814 Let mutable j be 1.
1815 While i <= length of a and j <= length of b:
1816 Let from_a be item i of a.
1817 Let from_b be item j of b.
1818 If from_a <= from_b:
1819 Push from_a to merged.
1820 Set i to i + 1.
1821 Otherwise:
1822 Push from_b to merged.
1823 Set j to j + 1.
1824 While i <= length of a:
1825 Push item i of a to merged.
1826 Set i to i + 1.
1827 While j <= length of b:
1828 Push item j of b to merged.
1829 Set j to j + 1.
1830 Return merged.
1831
1832## To merge_sort (xs: Seq of Int) -> Seq of Int:
1833 Let n be length of xs.
1834 If n <= 1:
1835 Return xs.
1836 Let half be n / 2.
1837 Let front be items 1 through half of xs.
1838 Let back be items (half + 1) through n of xs.
1839 Let sorted_front be merge_sort(front).
1840 Let sorted_back be merge_sort(back).
1841 Return merge_sorted(sorted_front, sorted_back).
1842
1843## Main
1844
1845Let messy be [38, 27, 43, 3, 9, 82, 10].
1846Let tidy be merge_sort(messy).
1847Show "before: {messy}".
1848Show "after: {tidy}".
1849"#;
1850
1851const CODE_GCD: &str = r#"# Euclid's GCD
1852-- The oldest algorithm in the book, with a termination measure.
1853
1854## To gcd (a: Int) and (b: Int) -> Int:
1855 Let mutable x be a.
1856 Let mutable y be b.
1857 While y > 0 (decreasing y):
1858 Let r be x % y.
1859 Set x to y.
1860 Set y to r.
1861 Return x.
1862
1863## Main
1864
1865Show "gcd(48, 18) = {gcd(48, 18)}".
1866Show "gcd(17, 5) = {gcd(17, 5)}".
1867Show "gcd(100, 75) = {gcd(100, 75)}".
1868"#;
1869
1870const CODE_TWO_SUM: &str = r#"# Two Sum
1871-- One pass with a Set of seen values finds the pair.
1872
1873## Main
1874
1875Let numbers be [2, 7, 11, 15, 3].
1876Let target be 14.
1877Let mutable seen be a new Set of Int.
1878Let mutable found be false.
1879Repeat for n in numbers:
1880 Let complement be target - n.
1881 If seen contains complement and not found:
1882 Show "{complement} + {n} = {target}".
1883 Set found to true.
1884 Add n to seen.
1885If not found:
1886 Show "no pair sums to {target}".
1887"#;
1888
1889const CODE_BFS: &str = r#"# Breadth-First Search
1890-- Explore level by level; the first arrival is the shortest path.
1891
1892## Main
1893
1894Let mutable graph be a new Map of Int to Seq of Int.
1895Set graph[1] to [2, 3].
1896Set graph[2] to [4].
1897Set graph[3] to [4, 5].
1898Set graph[4] to [6].
1899Set graph[5] to [6].
1900Set graph[6] to a new Seq of Int.
1901
1902Let origin be 1.
1903Let goal be 6.
1904Let mutable frontier be [1].
1905Let mutable distance be a new Map of Int to Int.
1906Set distance[1] to 0.
1907
1908While length of frontier > 0:
1909 Let mutable next_frontier be a new Seq of Int.
1910 Repeat for node in frontier:
1911 Repeat for neighbor in graph[node]:
1912 If not (distance contains neighbor):
1913 Set distance[neighbor] to distance[node] + 1.
1914 Push neighbor to next_frontier.
1915 Set frontier to next_frontier.
1916
1917Show "shortest path from {origin} to {goal}: {distance[goal]} hops".
1918"#;
1919
1920const CODE_COLLATZ: &str = r#"# Collatz
1921-- Halve if even; triple and add one if odd. Everyone reaches 1... probably.
1922
1923## Main
1924
1925Let mutable n be 27.
1926Let mutable steps be 0.
1927While n > 1:
1928 If n is even:
1929 Set n to n / 2.
1930 Otherwise:
1931 Set n to 3 * n + 1.
1932 Set steps to steps + 1.
1933Show "27 takes {steps} steps to reach 1".
1934"#;
1935
1936const CODE_SELECT: &str = r#"# Select
1939-- Await the first of races receive arms against a timeout.
1940
1941## Main
1942
1943Let inbox be a Pipe of Int.
1944Send 99 into inbox.
1945Await the first of:
1946 Receive msg from inbox:
1947 Show "first arrival: {msg}".
1948 After 2 seconds:
1949 Show "timed out".
1950
1951Let quiet be a Pipe of Int.
1952Await the first of:
1953 Receive msg from quiet:
1954 Show "got {msg}".
1955 After 1 seconds:
1956 Show "timed out waiting on the quiet pipe".
1957"#;
1958
1959const CODE_CRDT_LWW: &str = r#"# Last-Write-Wins Register
1960-- A LastWriteWins field keeps whichever write happened latest.
1961
1962## Definition
1963A Profile is Shared and has:
1964 status: LastWriteWins of Text.
1965
1966## Main
1967Let mutable me be a new Profile.
1968Set me's status to "online".
1969Show "status: {me's status}".
1970Set me's status to "away".
1971Show "status now: {me's status}".
1972"#;
1973
1974const CODE_CRDT_DIVERGENT: &str = r#"# Divergent Register
1975-- A Divergent field keeps both sides of a conflict until you Resolve it.
1976
1977## Definition
1978A WikiPage is Shared and has:
1979 title: Divergent Text.
1980
1981## Main
1982Let mutable page be a new WikiPage.
1983Set page's title to "Draft".
1984Show "title: {page's title}".
1985Resolve page's title to "Final".
1986Show "resolved title: {page's title}".
1987"#;
1988
1989const CODE_CRDT_SHARED_SET: &str = r#"# Shared Sets
1990-- An add-wins set: when replicas disagree, the add survives the merge.
1991
1992## Definition
1993A Team is Shared and has:
1994 members: a SharedSet of Text.
1995
1996## Main
1997Let mutable local be a new Team.
1998Add "Ada" to local's members.
1999Add "Bob" to local's members.
2000
2001Let mutable remote be a new Team.
2002Add "Bob" to remote's members.
2003Remove "Bob" from remote's members.
2004
2005Merge remote into local.
2006If local's members contains "Bob":
2007 Show "Bob survives: concurrent add wins".
2008Let team_size be length of local's members.
2009Show "team size: {team_size}".
2010"#;
2011
2012const CODE_CRDT_SHARED_SEQUENCE: &str = r#"# Shared Sequences
2013-- Replicated logs: appends from different replicas merge into one order.
2014
2015## Definition
2016A Journal is Shared and has:
2017 lines: a SharedSequence of Text.
2018
2019## Main
2020Let mutable mine be a new Journal.
2021Append "first entry" to mine's lines.
2022Append "second entry" to mine's lines.
2023
2024Let mutable other be a new Journal.
2025Append "remote entry" to other's lines.
2026
2027Merge other into mine.
2028Let total be length of mine's lines.
2029Show "entries after merge: {total}".
2030"#;
2031
2032const CODE_CRDT_SHARED_MAP: &str = r#"# Shared Map
2033-- A key-value CRDT: each key keeps its latest write, and replicas that
2034-- merge converge on the same map.
2035
2036## Definition
2037A Warehouse is Shared and has:
2038 stock: a SharedMap from Text to Int.
2039
2040## Main
2041Let mutable w be a new Warehouse.
2042Set w's stock["wood"] to 50.
2043Set w's stock["stone"] to 30.
2044Show w's stock["wood"].
2045"#;
2046
2047const CODE_CRDT_SYNC: &str = r#"# Network Sync
2048-- Sync joins a CRDT to a gossip topic. In the playground this runs in
2049-- offline single-node mode; compiled programs gossip with real peers.
2050
2051## Definition
2052A Clicks is Shared and has:
2053 total: ConvergentCount.
2054
2055## Main
2056Let mutable c be a new Clicks.
2057Sync c on "global-clicks".
2058Increase c's total by 1.
2059Increase c's total by 2.
2060Show "local clicks: {c's total}".
2061"#;
2062
2063const CODE_HASHES: &str = r#"# Hash Functions
2066-- md5 and sha1 digest byte sequences right in the browser.
2067
2068## Main
2069
2070Let message be text_bytes("abc").
2071Let sha be sha1(message).
2072Let fingerprint be md5(message).
2073
2074Show "sha1 of abc: first bytes {item 1 of sha}, {item 2 of sha}".
2075Show "md5 of abc: first byte {item 1 of fingerprint}".
2076
2077Let sha_len be length of sha.
2078Let md5_len be length of fingerprint.
2079Show "digest lengths: sha1 {sha_len} bytes, md5 {md5_len} bytes".
2080"#;
2081
2082const CODE_CHACHA20: &str = r#"# ChaCha20 in LOGOS
2083-- quarterRound below is stdlib code written in LOGOS itself (crypto.lg),
2084-- running on the RFC 8439 test vector.
2085
2086## Main
2087
2088Let mutable state be a new Seq of Word32.
2089Push word32(286331153) to state.
2090Push word32(16909060) to state.
2091Push word32(2609737539) to state.
2092Push word32(19088743) to state.
2093
2094Let mixed be quarterRound(state, 0, 1, 2, 3).
2095Show "a = {item 1 of mixed}".
2096Show "b = {item 2 of mixed}".
2097Show "c = {item 3 of mixed}".
2098Show "d = {item 4 of mixed}".
2099"#;
2100
2101const CODE_MLKEM: &str = r#"# Post-Quantum ML-KEM
2102-- ML-KEM-768 (FIPS 203): the lattice math is stdlib code written in
2103-- LOGOS (crypto.lg), proven bit-exact against the reference oracle.
2104
2105## Main
2106
2107Let mutable seed be a new Seq of Int.
2108Repeat for i from 1 to 32:
2109 Push i to seed.
2110
2111Let ek be mlkem768Keygen(seed).
2112Let ek_size be length of ek.
2113Show "encapsulation key: {ek_size} bytes".
2114
2115Let mutable msg be a new Seq of Int.
2116Repeat for i from 1 to 32:
2117 Push 42 to msg.
2118Let sealed be mlkem768Encaps(ek, msg).
2119Let sealed_size be length of sealed.
2120Let ct_size be sealed_size - 32.
2121Show "ciphertext: {ct_size} bytes, shared secret: 32 bytes".
2122"#;
2123
2124const CODE_UUID: &str = r#"# UUIDs
2125-- RFC 9562 UUIDs, generated by stdlib code written in LOGOS (uuid.lg).
2126
2127## Main
2128
2129Let dns be uuidParse("6ba7b810-9dad-11d1-80b4-00c04fd430c8").
2130Let stable be uuidV5(dns, "www.example.com").
2131Show "v5 of example.com: {stable}".
2132
2133Let mutable bytes be a new Seq of Int.
2134Repeat for i from 1 to 16:
2135 Push i * 11 to bytes.
2136Let tagged be uuidV4(bytes).
2137Show "v4 from fixed bytes: {tagged}".
2138"#;
2139
2140const CODE_TERMINATION: &str = r#"# Proving Loops Halt
2141-- The (decreasing e) clause names a measure that must shrink every pass.
2142
2143## To halvings (n: Int) -> Int:
2144 Let mutable remaining be n.
2145 Let mutable count be 0.
2146 While remaining > 1 (decreasing remaining):
2147 Set remaining to remaining / 2.
2148 Set count to count + 1.
2149 Return count.
2150
2151## Main
2152
2153Show "1024 halves to 1 in {halvings(1024)} steps".
2154Show "1000000 halves to 1 in {halvings(1000000)} steps".
2155"#;
2156
2157const CODE_CHECK_GATE: &str = r#"# Check vs Assert
2158-- Assert guards logic errors; Check is a security gate that always
2159-- runs and always enforces its policy.
2160
2161## Definition
2162An Account has:
2163 owner: Text.
2164 standing: Text.
2165
2166## Policy
2167An Account is open if the account's standing equals "open".
2168
2169## Main
2170
2171Let acct be a new Account with owner "Ada" and standing "open".
2172Check that acct is open.
2173Show "gate passed: the account is open".
2174
2175Let amount be 40.
2176Assert that amount is greater than 0.
2177Show "withdrawal of {amount} approved for {acct's owner}".
2178"#;
2179
2180const CODE_PROJ_TODO: &str = r#"# Todo List
2183-- Structs, an enum status, and a formatted checklist.
2184
2185## A Status is one of:
2186 An Open.
2187 A Done.
2188
2189## Definition
2190A Task has:
2191 label: Text.
2192 status: Status.
2193
2194## Main
2195
2196Let mutable chores be a new Seq of Task.
2197Let milk be a new Task with label "buy milk" and status a new Open.
2198Push milk to chores.
2199Let writing be a new Task with label "write examples" and status a new Done.
2200Push writing to chores.
2201Let plants be a new Task with label "water plants" and status a new Open.
2202Push plants to chores.
2203
2204Show "TODO:".
2205Let mutable open_count be 0.
2206Repeat for chore in chores:
2207 Inspect chore's status:
2208 When Done: Show " [x] {chore's label}".
2209 When Open:
2210 Show " [ ] {chore's label}".
2211 Set open_count to open_count + 1.
2212Show "{open_count} remaining".
2213"#;
2214
2215const CODE_PROJ_INVENTORY: &str = r#"# Inventory Manager
2216-- Map bookkeeping with a low-stock report.
2217
2218## Main
2219
2220Let mutable stock be a new Map of Text to Int.
2221Set stock["planks"] to 40.
2222Set stock["nails"] to 350.
2223Set stock["hinges"] to 6.
2224Set stock["varnish"] to 2.
2225
2226Set stock["planks"] to stock["planks"] - 12.
2227Set stock["hinges"] to stock["hinges"] - 4.
2228
2229Show "Inventory report:".
2230Repeat for (part, quantity) in stock:
2231 If quantity < 10:
2232 Show " {part}: {quantity} LOW - reorder".
2233 Otherwise:
2234 Show " {part}: {quantity}".
2235"#;
2236
2237const CODE_PROJ_DICE: &str = r#"# Dice Game
2238-- Dice from scratch: a linear congruential generator makes the rolls.
2239-- Same seed, same game — deterministic randomness you can replay.
2240
2241## To next_seed (seed: Int) -> Int:
2242 Return (seed * 1103515245 + 12345) % 2147483648.
2243
2244## Main
2245
2246Let mutable rng be 20260712.
2247Let mutable player be 0.
2248Let mutable rival be 0.
2249
2250Repeat for round in [1, 2, 3]:
2251 Set rng to next_seed(rng).
2252 Let yours be rng % 6 + 1.
2253 Set rng to next_seed(rng).
2254 Let theirs be rng % 6 + 1.
2255 Set player to player + yours.
2256 Set rival to rival + theirs.
2257 Show "round {round}: you rolled {yours}, rival rolled {theirs}".
2258
2259Show "final score - you: {player}, rival: {rival}".
2260If player > rival:
2261 Show "you win!".
2262Otherwise If rival > player:
2263 Show "rival wins!".
2264Otherwise:
2265 Show "a tie!".
2266"#;
2267
2268const CODE_PROJ_WEATHER: &str = r##"# Weather Stats
2269-- Min, max, mean, and an ASCII bar chart from a week of readings.
2270
2271## Main
2272
2273Let readings be [18, 21, 25, 24, 19, 16, 22].
2274Let mutable lowest be 999.
2275Let mutable highest be -999.
2276Let mutable total be 0.
2277Repeat for r in readings:
2278 Set total to total + r.
2279 If r < lowest:
2280 Set lowest to r.
2281 If r > highest:
2282 Set highest to r.
2283Let day_count be length of readings.
2284Let mean be total / day_count.
2285
2286Show "week of readings: {readings}".
2287Show "low {lowest}, high {highest}, average {mean} (rounded down)".
2288Show "chart:".
2289Repeat for r in readings:
2290 Let mutable bar be "".
2291 Let stars be r - 15.
2292 Repeat for s from 1 to stars:
2293 Set bar to bar combined with "#".
2294 Show " {r} {bar}".
2295"##;
2296
2297const CODE_PROJ_LEDGER: &str = r#"# Bank Ledger
2298-- Exact Decimal money and a tidy statement.
2299
2300## Main
2301
2302Let mutable balance be decimal("250.00").
2303Show "opening balance: {balance:$}".
2304
2305Let deposits be [decimal("75.50"), decimal("12.25")].
2306Repeat for d in deposits:
2307 Set balance to balance + d.
2308 Show "deposit {d:$} -> {balance:$}".
2309
2310Let withdrawal be decimal("40.00").
2311Assert that withdrawal <= balance.
2312Set balance to balance - withdrawal.
2313Show "withdrew {withdrawal:$} -> {balance:$}".
2314
2315Show "closing balance: {balance:$}".
2316"#;
2317
2318const CODE_PROJ_CAESAR: &str = r#"# Caesar Cipher
2321-- Shift each letter three places by scanning an alphabet string.
2322
2323## To encode (message: Text) and (shift: Int) -> Text:
2324 Let alphabet be "abcdefghijklmnopqrstuvwxyz".
2325 Let mutable scrambled be "".
2326 Let message_len be length of message.
2327 Repeat for i from 1 to message_len:
2328 Let c be item i of message.
2329 Let mutable found_at be 0.
2330 Repeat for j from 1 to 26:
2331 If item j of alphabet equals c:
2332 Set found_at to j.
2333 If found_at equals 0:
2334 Set scrambled to scrambled combined with c.
2335 Otherwise:
2336 Let moved be (found_at - 1 + shift) % 26 + 1.
2337 Set scrambled to scrambled combined with item moved of alphabet.
2338 Return scrambled.
2339
2340## Main
2341
2342Let secret be encode("hello world", 3).
2343Show "encoded: {secret}".
2344Let restored be encode(secret, 23).
2345Show "decoded: {restored}".
2346"#;
2347
2348const CODE_PROJ_WORDCOUNT: &str = r#"# Word Count
2349-- Count words and characters by scanning the text.
2350
2351## Main
2352
2353Let prose be "the quick brown fox jumps over the lazy dog".
2354Show "text: {prose}".
2355
2356Let chars be length of prose.
2357Let mutable spaces be 0.
2358Repeat for i from 1 to chars:
2359 If item i of prose equals " ":
2360 Set spaces to spaces + 1.
2361Let words be spaces + 1.
2362
2363Show "{chars} characters".
2364Show "{words} words".
2365"#;
2366
2367const CODE_PROJ_MATRIX: &str = r#"# Matrix Multiply
2368-- A Seq of Seq is a matrix; three loops do the classic multiply.
2369
2370## Main
2371
2372Let mutable a be a new Seq of Seq of Int.
2373Push [1, 2] to a.
2374Push [3, 4] to a.
2375Let mutable b be a new Seq of Seq of Int.
2376Push [5, 6] to b.
2377Push [7, 8] to b.
2378
2379Let mutable product be a new Seq of Seq of Int.
2380Repeat for i from 1 to 2:
2381 Let row_a be item i of a.
2382 Let mutable new_row be a new Seq of Int.
2383 Repeat for j from 1 to 2:
2384 Let mutable cell be 0.
2385 Repeat for k from 1 to 2:
2386 Let x be item k of row_a.
2387 Let row_b be item k of b.
2388 Let y be item j of row_b.
2389 Set cell to cell + x * y.
2390 Push cell to new_row.
2391 Push new_row to product.
2392
2393Show "A x B = {product}".
2394"#;
2395
2396const CODE_PROJ_SCHEDULER: &str = r#"# Event Scheduler
2397-- Moments and durations build an ordered agenda.
2398
2399## Main
2400
2401Let kickoff be 2026-06-01 at 9am.
2402Show "kickoff: {kickoff}".
2403Let standup be 2026-06-01 at 9:30am.
2404Show "standup: {standup}".
2405Let review be 2026-06-01 at 4pm.
2406Show "review: {review}".
2407
2408If standup < review:
2409 Show "standup comes before review".
2410
2411Let focus be 2h.
2412Show "each focus block runs {focus}".
2413"#;
2414
2415const CODE_PROJ_VENDING: &str = r#"# Vending Machine
2416-- An enum state machine: coins move it, a purchase resets it.
2417
2418## A MachineState is one of:
2419 An Idle.
2420 A HasCredit with cents Int.
2421
2422## To insert (coins: Int) and (current: MachineState) -> MachineState:
2423 Inspect current:
2424 When Idle: Return a new HasCredit with cents coins.
2425 When HasCredit (c): Return a new HasCredit with cents (c + coins).
2426
2427## Main
2428
2429Let mutable machine be a new Idle.
2430Set machine to insert(50, machine).
2431Set machine to insert(25, machine).
2432
2433Inspect machine:
2434 When Idle: Show "no credit".
2435 When HasCredit (c):
2436 Show "credit: {c} cents".
2437 If c >= 65:
2438 Show "dispensing soda".
2439 Let change be c - 65.
2440 Show "change: {change} cents".
2441
2442Set machine to a new Idle.
2443Show "machine reset".
2444"#;
2445
2446const CODE_PROJ_ADVENTURE: &str = r#"# Tiny Text Adventure
2449-- Rooms live in a Map; a scripted walk drives the story.
2450
2451## Main
2452
2453Let mutable rooms be a new Map of Text to Text.
2454Set rooms["hall"] to "a dusty hall. Doors lead north and east.".
2455Set rooms["library"] to "a quiet library. A key glints on the desk.".
2456Set rooms["cellar"] to "a dark cellar. The exit door is locked.".
2457
2458Let mutable here be "hall".
2459Let mutable has_key be false.
2460
2461Let script be ["north", "take key", "south", "east"].
2462Repeat for command in script:
2463 Show "> {command}".
2464 If command equals "take key":
2465 Set has_key to true.
2466 Show "You found the key!".
2467 Otherwise:
2468 If command equals "north":
2469 Set here to "library".
2470 Otherwise If command equals "south":
2471 Set here to "hall".
2472 Otherwise If command equals "east":
2473 Set here to "cellar".
2474 Let room_desc be rooms[here].
2475 Show "You are in {room_desc}".
2476
2477If has_key:
2478 Show "The key turns. You escape the cellar!".
2479"#;
2480
2481const CODE_PROJ_CHAT: &str = r#"# Chat Room
2482-- Messages drain from the room pipe until a quiet timeout closes it.
2483
2484## Main
2485
2486Let room be a Pipe of Int.
2487Send 101 into room.
2488Send 102 into room.
2489Send 201 into room.
2490
2491Let mutable open_room be true.
2492While open_room:
2493 Await the first of:
2494 Receive msg from room:
2495 If msg < 200:
2496 Show "<alice> message {msg}".
2497 Otherwise:
2498 Show "<bob> message {msg}".
2499 After 1 seconds:
2500 Show "room quiet - closing".
2501 Set open_room to false.
2502"#;
2503
2504const CODE_PROJ_LEADERBOARD: &str = r#"# CRDT Leaderboard
2505-- Three replicas tally independently, then merge into one standings.
2506
2507## Definition
2508A Board is Shared and has:
2509 alice: Tally.
2510 bob: Tally.
2511
2512## Main
2513Let mutable phone be a new Board.
2514Increase phone's alice by 12.
2515Increase phone's bob by 7.
2516
2517Let mutable laptop be a new Board.
2518Increase laptop's alice by 5.
2519Increase laptop's bob by 1.
2520
2521Let mutable tablet be a new Board.
2522Increase tablet's alice by 2.
2523Increase tablet's bob by 10.
2524Decrease tablet's bob by 2.
2525
2526Merge laptop into phone.
2527Merge tablet into phone.
2528
2529Show "standings after merge:".
2530Show " alice: {phone's alice}".
2531Show " bob: {phone's bob}".
2532If phone's alice > phone's bob:
2533 Show "alice leads".
2534Otherwise:
2535 Show "bob leads".
2536"#;
2537
2538const CODE_PROJ_HASHER: &str = r#"# Password Hasher
2539-- Salt the password, hash it, verify by rehashing. (A demo shape —
2540-- real systems use slow KDFs, not one hash round.)
2541
2542## To hash_password (password: Text) and (salt: Text) -> Seq of Int:
2543 Let salted be salt combined with password.
2544 Return sha1(text_bytes(salted)).
2545
2546## To verify (attempt: Text) and (salt: Text) and (expected: Seq of Int) -> Bool:
2547 Let candidate be hash_password(attempt, salt).
2548 Let hash_len be length of expected.
2549 Let mutable matching be true.
2550 Repeat for i from 1 to hash_len:
2551 If item i of candidate is not item i of expected:
2552 Set matching to false.
2553 Return matching.
2554
2555## Main
2556
2557Let stored be hash_password("hunter2", "s4lt").
2558Let stored_len be length of stored.
2559Show "stored digest: {stored_len} bytes".
2560
2561If verify("hunter2", "s4lt", stored):
2562 Show "correct password accepted".
2563If not verify("wrong", "s4lt", stored):
2564 Show "wrong password rejected".
2565"#;
2566
2567const MATH_PRELUDE_TOUR: &str = r#"-- What the kernel already knows
2574-- Every session starts with a typed prelude: naturals, equality,
2575-- logic, and exact integer arithmetic. Check asks for a type;
2576-- Eval computes a value.
2577
2578Check Nat.
2579Check Zero.
2580Check Succ.
2581Check Eq.
2582Check refl.
2583Check True.
2584Check False.
2585Check Not.
2586Eval (add 20 22).
2587Eval (mul 6 7).
2588Eval (le 2 3).
2589"#;
2590
2591const MATH_BIG_ARITHMETIC: &str = r#"-- Exact arithmetic past 2^63
2592-- These products overflow every machine integer. The kernel promotes
2593-- to exact big integers and keeps computing — so `refl` can PROVE an
2594-- equation by pure computation where bit-level tools must bit-blast.
2595
2596Eval (mul 4000000000000000000 4).
2597Eval (add 9000000000000000000 9000000000000000000).
2598Eval (mul 123456789123456789 987654321987654321).
2599
2600Definition big_eq : Eq Int (mul 4000000000000000000 4) (mul 8000000000000000000 2) :=
2601 refl Int (mul 4000000000000000000 4).
2602Check big_eq.
2603"#;
2604
2605const MATH_TERMINATION_WALL: &str = r#"-- The wall is real: the kernel REJECTS recursion it cannot prove
2606-- terminates. Everything below builds up legally — parity, halving —
2607-- until `collatz_len` asks for the length of a Collatz descent.
2608-- Nobody has proven that descent finite. Watch the checker say no.
2609
2610A Decision is either Yes or No.
2611
2612## To negate (d: Decision) -> Decision:
2613 Consider d:
2614 When Yes: Yield No.
2615 When No: Yield Yes.
2616
2617## To check_parity (n: Nat) -> Decision:
2618 Consider n:
2619 When Zero: Yield Yes.
2620 When Succ k: Yield negate(check_parity(k)).
2621
2622## To is_odd (n: Nat) -> Decision:
2623 Yield negate(check_parity(n)).
2624
2625## To halve (n: Nat) -> Nat:
2626 Consider n:
2627 When Zero: Yield Zero.
2628 When Succ k:
2629 Consider is_odd(k):
2630 When Yes: Yield Succ (halve(k)).
2631 When No: Yield halve(k).
2632
2633-- Every definition above is certified total. This one cannot be:
2634-- the recursive call is not on a structurally smaller argument,
2635-- and the kernel refuses the axiom of wishful thinking.
2636
2637## To collatz_len (n: Nat) -> Nat:
2638 Consider n:
2639 When Zero: Yield Zero.
2640 When Succ k: Yield Succ (collatz_len(halve(n))).
2641"#;
2642
2643const MATH_TARSKI: &str = r#"## Theory Tarski
2644
2645Axiom cong_pseudo_reflexivity: for all a b, Cong(a, b, b, a).
2646Axiom cong_inner_transitivity: for all a b c d e f,
2647 if Cong(a, b, c, d) and Cong(a, b, e, f) then Cong(c, d, e, f).
2648Axiom cong_identity: for all a b c, if Cong(a, b, c, c) then a = b.
2649Axiom segment_construction: for all q a b c, there exists x, Bet(q, a, x) and Cong(a, x, b, c).
2650Axiom bet_identity: for all a b, if Bet(a, b, a) then a = b.
2651Axiom pasch: for all a p c b q,
2652 if Bet(a, p, c) and Bet(b, q, c) then there exists x, Bet(p, x, b) and Bet(q, x, a).
2653Axiom five_segment: for all a b c d ap bp cp dp,
2654 if not (a = b) and Bet(a, b, c) and Bet(ap, bp, cp)
2655 and Cong(a, b, ap, bp) and Cong(b, c, bp, cp) and Cong(a, d, ap, dp) and Cong(b, d, bp, dp)
2656 then Cong(c, d, cp, dp).
2657
2658Theorem cong_reflexivity: prove for all a b, Cong(a, b, a, b).
2659Theorem cong_symmetry cites cong_reflexivity:
2660 prove for all a b c d, if Cong(a, b, c, d) then Cong(c, d, a, b).
2661Theorem cong_transitivity cites cong_symmetry:
2662 prove for all a b c d e f, if Cong(a, b, c, d) and Cong(c, d, e, f) then Cong(a, b, e, f).
2663Theorem null_segment_identity: given Cong(P, Q, R, R); prove P = Q.
2664Theorem construct_point: prove there exists x, Bet(Q, A, x) and Cong(A, x, B, C).
2665Theorem cevians_meet: given Bet(A, P, C); given Bet(B, Q, C);
2666 prove there exists x, Bet(P, x, B) and Bet(Q, x, A).
2667Theorem degenerate_betweenness: given Bet(P, Q, P); prove P = Q.
2668Theorem outer_five_segment: given not (A = B); given Bet(A, B, C); given Bet(Ap, Bp, Cp);
2669 given Cong(A, B, Ap, Bp); given Cong(B, C, Bp, Cp); given Cong(A, D, Ap, Dp);
2670 given Cong(B, D, Bp, Dp); prove Cong(C, D, Cp, Dp).
2671"#;
2672
2673pub const MATH_NAT: &str = r#"-- Natural Numbers
2674-- The foundation of arithmetic in type theory
2675
2676-- Define the natural number type
2677Inductive Nat := Zero : Nat | Succ : Nat -> Nat.
2678
2679-- Define some numbers
2680Definition one : Nat := Succ Zero.
2681Definition two : Nat := Succ one.
2682Definition three : Nat := Succ two.
2683
2684-- Check the types
2685Check Zero.
2686Check Succ.
2687Check one.
2688Check two.
2689
2690-- Evaluate expressions
2691Eval three.
2692"#;
2693
2694pub const MATH_BOOL: &str = r#"-- Booleans
2695-- A two-constructor type, checked and evaluated by the kernel, and functions over it.
2696
2697Inductive MyBool := Yes : MyBool | No : MyBool.
2698
2699Check Yes.
2700Check No.
2701Eval Yes.
2702Eval No.
2703
2704Definition id_bool : MyBool -> MyBool := fun b : MyBool => b.
2705
2706Check id_bool.
2707Eval id_bool Yes.
2708Eval id_bool No.
2709"#;
2710
2711const MATH_GODEL: &str = r#"-- Gödel Sentence Construction
2712-- Building the self-referential sentence G
2713
2714-- The Provable predicate: "there exists a derivation concluding s"
2715Definition Provable : Syntax -> Prop :=
2716 fun s : Syntax => Ex Derivation (fun d : Derivation => Eq Syntax (concludes d) s).
2717
2718-- The Gödel template T = "Not(Provable(x))"
2719-- When we apply the diagonal lemma, x becomes the code of T itself
2720Definition T : Syntax := SApp (SName "Not") (SApp (SName "Provable") (SVar 0)).
2721
2722-- The Gödel sentence G = T[code(T)/x]
2723-- G says "I am not provable"
2724Definition G : Syntax := syn_diag T.
2725
2726-- Check our constructions
2727Check Provable.
2728Check T.
2729Check G.
2730
2731-- G has type Syntax (it's a syntactic object)
2732-- But Provable G has type Prop (it's a proposition)
2733Check (Provable G).
2734"#;
2735
2736const MATH_INCOMPLETENESS: &str = r#"-- Gödel's First Incompleteness Theorem
2737-- If LOGOS is consistent, G is not provable
2738
2739-- Setup: Provable predicate
2740Definition Provable : Syntax -> Prop :=
2741 fun s : Syntax => Ex Derivation (fun d : Derivation => Eq Syntax (concludes d) s).
2742
2743-- Consistency: the system cannot prove False
2744Definition Consistent : Prop := Not (Provable (SName "False")).
2745
2746-- The Gödel template and sentence
2747Definition T : Syntax := SApp (SName "Not") (SApp (SName "Provable") (SVar 0)).
2748Definition G : Syntax := syn_diag T.
2749
2750-- THE THEOREM STATEMENT
2751-- "If LOGOS is consistent, then G is not provable"
2752Definition Godel_I : Prop := Consistent -> Not (Provable G).
2753
2754-- Check that our theorem statement is well-typed
2755Check Godel_I.
2756Check Consistent.
2757Check (Provable G).
2758Check (Not (Provable G)).
2759
2760-- This is a proposition (a type in Prop)
2761-- A proof would be a term of this type
2762"#;
2763
2764pub const MATH_PROP_LOGIC: &str = r#"-- Propositional Logic Types
2765-- Encoding logical connectives as types
2766
2767Inductive MyProp :=
2768 PTrue : MyProp
2769 | PFalse : MyProp
2770 | PAnd : MyProp -> MyProp -> MyProp
2771 | POr : MyProp -> MyProp -> MyProp
2772 | PNot : MyProp -> MyProp.
2773
2774-- Some example propositions
2775Definition p1 : MyProp := PTrue.
2776Definition p2 : MyProp := PFalse.
2777Definition p3 : MyProp := PAnd PTrue PTrue.
2778Definition p4 : MyProp := POr PTrue PFalse.
2779Definition p5 : MyProp := PNot PFalse.
2780
2781-- Check and evaluate
2782Check p3.
2783Check p4.
2784Check p5.
2785Eval p3.
2786Eval p4.
2787Eval p5.
2788"#;
2789
2790const MATH_FUNCTIONS: &str = r#"-- Simple Functions
2791-- Lambda calculus basics
2792
2793-- Identity function
2794Definition id : Nat -> Nat := fun x : Nat => x.
2795
2796-- Constant function
2797Definition const_zero : Nat -> Nat := fun x : Nat => Zero.
2798
2799-- Apply successor twice
2800Definition double_succ : Nat -> Nat := fun x : Nat => Succ (Succ x).
2801
2802-- Check types
2803Check id.
2804Check const_zero.
2805Check double_succ.
2806
2807-- Evaluate some applications
2808Definition one : Nat := Succ Zero.
2809Definition two : Nat := Succ one.
2810
2811Eval id one.
2812Eval const_zero two.
2813Eval double_succ one.
2814"#;
2815
2816const MATH_LIST_OPS: &str = r#"-- List Operations
2817-- Polymorphic lists in type theory
2818
2819-- Define a list type (built-in, but showing the structure)
2820Inductive MyList (A : Type) :=
2821 MyNil : MyList A
2822 | MyCons : A -> MyList A -> MyList A.
2823
2824-- Example: a list of natural numbers
2825Definition nat_list : MyList Nat := MyCons Nat Zero (MyCons Nat (Succ Zero) (MyNil Nat)).
2826
2827-- Check the types
2828Check MyNil.
2829Check MyCons.
2830Check nat_list.
2831
2832-- Evaluate
2833Eval nat_list.
2834"#;
2835
2836const MATH_PAIRS: &str = r#"-- Pairs and Products
2837-- Cartesian product types
2838
2839-- A small boolean type to pair with numbers.
2840Inductive MyBool := Yes : MyBool | No : MyBool.
2841
2842Inductive MyPair (A : Type) (B : Type) :=
2843 MkPair : A -> B -> MyPair A B.
2844
2845-- Example pairs
2846Definition nat_bool_pair : MyPair Nat MyBool := MkPair Nat MyBool Zero Yes.
2847Definition nat_nat_pair : MyPair Nat Nat := MkPair Nat Nat Zero (Succ Zero).
2848
2849-- Check types
2850Check MkPair.
2851Check nat_bool_pair.
2852Check nat_nat_pair.
2853
2854-- Evaluate
2855Eval nat_bool_pair.
2856Eval nat_nat_pair.
2857"#;
2858
2859const MATH_CIRCUIT: &str = r#"-- Logic Gates as a Circuit
2860-- Encode the gates formally, then hit the crab Compile button to extract
2861-- runnable Rust. The same code could run in WASM or drive a hardware circuit —
2862-- this is "encode it, extract it, run it".
2863
2864Inductive MyBit := Lo : MyBit | Hi : MyBit.
2865
2866Definition not1 : MyBit -> MyBit := fun a : MyBit =>
2867 match a return (fun _ : MyBit => MyBit) with | Lo => Hi | Hi => Lo.
2868
2869Definition and2 : MyBit -> MyBit -> MyBit := fun a : MyBit => fun b : MyBit =>
2870 match a return (fun _ : MyBit => MyBit) with | Lo => Lo | Hi => b.
2871
2872Definition or2 : MyBit -> MyBit -> MyBit := fun a : MyBit => fun b : MyBit =>
2873 match a return (fun _ : MyBit => MyBit) with | Lo => b | Hi => Hi.
2874
2875-- XOR built from the primitive gates
2876Definition xor2 : MyBit -> MyBit -> MyBit := fun a : MyBit => fun b : MyBit =>
2877 or2 (and2 a (not1 b)) (and2 (not1 a) b).
2878
2879-- Try it: XOR truth table
2880Eval xor2 Lo Hi.
2881Eval xor2 Hi Hi.
2882"#;
2883
2884const MATH_PROPERTY: &str = r#"-- Proven theorems become RUNNABLE Rust property checks.
2885-- Define a function, prove a theorem about it, then hit Compile: the proof turns
2886-- into a `check_*` function over the extracted code that the demo main runs.
2887
2888Inductive Num := Z : Num | S : Num -> Num.
2889
2890Definition add : Num -> Num -> Num := fix rec => fun n : Num => fun m : Num =>
2891 match n return (fun _ : Num => Num) with | Z => m | S k => S (rec k m).
2892
2893Definition one : Num := S Z.
2894
2895-- A proven theorem: adding Z on the left is the identity (true by computation,
2896-- so `refl` proves it). Compile → `fn check_add_zero_l(n) -> bool { add(Z, n) == n }`.
2897Definition add_zero_l : (forall n : Num, Eq Num (add Z n) n) := fun n : Num => refl Num n.
2898
2899Eval add one one.
2900"#;
2901
2902const MATH_COLLATZ: &str = r###"-- ============================================
2903-- THE COLLATZ CONJECTURE (Literate Mode)
2904-- ============================================
2905-- The Collatz sequence: if n is even, n/2; if odd, 3n+1
2906-- Conjecture: All positive integers eventually reach 1
2907-- This is one of mathematics' most famous unsolved problems!
2908--
2909-- This example demonstrates the Literate Specification syntax:
2910-- - "A X is either" for sum types (instead of Inductive)
2911-- - "## To" for functions (instead of Definition)
2912-- - "Consider/When/Yield" for pattern matching (instead of match)
2913-- - Implicit recursion (no explicit "fix")
2914
2915-- ============================================
2916-- TYPE DEFINITIONS
2917-- ============================================
2918
2919-- A Decision represents a binary choice (Yes/No)
2920-- Replaces: Inductive MyBool := Yes : MyBool | No : MyBool.
2921A Decision is either Yes or No.
2922
2923-- ============================================
2924-- BOOLEAN OPERATIONS
2925-- ============================================
2926
2927-- Negate a decision: Yes becomes No, No becomes Yes
2928## To negate (d: Decision) -> Decision:
2929 Consider d:
2930 When Yes: Yield No.
2931 When No: Yield Yes.
2932
2933-- ============================================
2934-- NATURAL NUMBERS (using kernel's Nat)
2935-- ============================================
2936
2937-- Addition: add two natural numbers
2938-- Note: Recursion is implicit - we just call "add" in the body
2939## To add (n: Nat) and (m: Nat) -> Nat:
2940 Consider n:
2941 When Zero: Yield m.
2942 When Succ k: Yield Succ (add(k, m)).
2943
2944-- ============================================
2945-- PARITY CHECKS
2946-- ============================================
2947
2948-- Check if a number is even (Yes) or odd (No)
2949-- isEven(0) = Yes, isEven(n+1) = negate(isEven(n))
2950## To check_parity (n: Nat) -> Decision:
2951 Consider n:
2952 When Zero: Yield Yes.
2953 When Succ k: Yield negate(check_parity(k)).
2954
2955-- Check if a number is odd
2956## To is_odd (n: Nat) -> Decision:
2957 Yield negate(check_parity(n)).
2958
2959-- ============================================
2960-- ARITHMETIC HELPERS
2961-- ============================================
2962
2963-- Half: floor division by 2
2964-- half(0) = 0
2965-- half(n+1) = if odd(n) then 1+half(n) else half(n)
2966## To halve (n: Nat) -> Nat:
2967 Consider n:
2968 When Zero: Yield Zero.
2969 When Succ k:
2970 Consider is_odd(k):
2971 When Yes: Yield Succ (halve(k)).
2972 When No: Yield halve(k).
2973
2974-- Double: 2n = n + n
2975## To double (n: Nat) -> Nat:
2976 Yield add(n, n).
2977
2978-- Triple: 3n = n + 2n
2979## To triple (n: Nat) -> Nat:
2980 Yield add(n, double(n)).
2981
2982-- Multiplication: n * m
2983-- Used for defining 6k + 4
2984## To mul (n: Nat) and (m: Nat) -> Nat:
2985 Consider n:
2986 When Zero: Yield Zero.
2987 When Succ k: Yield add(m, mul(k, m)).
2988
2989-- Useful constants
2990Definition four : Nat := Succ (Succ (Succ (Succ Zero))).
2991Definition five : Nat := Succ (four).
2992Definition six : Nat := Succ (five).
2993Definition sixteen : Nat := double (double four).
2994
2995-- ============================================
2996-- THE COLLATZ STEP
2997-- ============================================
2998
2999-- The Collatz step function:
3000-- if even: n/2
3001-- if odd: 3n+1
3002## To take_collatz_step (n: Nat) -> Nat:
3003 Consider check_parity(n):
3004 When Yes: Yield halve(n).
3005 When No: Yield Succ (triple(n)).
3006
3007-- ============================================
3008-- VERIFICATION
3009-- ============================================
3010
3011Check negate.
3012Check check_parity.
3013Check is_odd.
3014Check halve.
3015Check take_collatz_step.
3016
3017-- Test check_parity: 0=even, 1=odd, 2=even, 3=odd
3018Eval (check_parity Zero).
3019Eval (check_parity (Succ Zero)).
3020Eval (check_parity (Succ (Succ Zero))).
3021Eval (check_parity (Succ (Succ (Succ Zero)))).
3022
3023-- Test halve: halve(4) = 2
3024Eval (halve (Succ (Succ (Succ (Succ Zero))))).
3025
3026-- Test take_collatz_step
3027-- 2 -> 1 (even, so divide by 2)
3028Eval (take_collatz_step (Succ (Succ Zero))).
3029
3030-- 4 -> 2 (even, so divide by 2)
3031Eval (take_collatz_step (Succ (Succ (Succ (Succ Zero))))).
3032
3033-- ============================================
3034-- PART 2: THE LOGICAL ENGINE
3035-- ============================================
3036-- The step function above is the "computational engine" - it runs.
3037-- But to REASON about the Collatz conjecture, we need a "logical engine".
3038--
3039-- Why can't we just write a function that counts steps to 1?
3040-- Because the termination checker cannot verify it always halts!
3041-- The compiler would reject it - that's the "termination wall".
3042--
3043-- Instead, we define a PREDICATE: "n eventually reaches 1"
3044-- This describes the PROPERTY without requiring computation to terminate.
3045
3046-- ============================================
3047-- REACHABILITY PREDICATE
3048-- ============================================
3049-- A proof that 'n' reaches 1 is a tree:
3050-- - Done: n IS 1 (with equality proof)
3051-- - Step: if take_collatz_step(n) reaches 1, so does n
3052
3053Inductive ReachesOne (n : Nat) :=
3054 | Done : Eq Nat n (Succ Zero) -> ReachesOne n
3055 | Step : ReachesOne (take_collatz_step n) -> ReachesOne n.
3056
3057-- ============================================
3058-- CONCRETE PROOFS
3059-- ============================================
3060-- Let's prove specific numbers reach 1 by constructing proof trees.
3061-- This is "running" the conjecture in the type system!
3062
3063-- Proof that 1 reaches 1 (trivial base case)
3064-- Note: Constructors for parameterized inductives take the parameter first
3065Definition one_reaches : ReachesOne (Succ Zero) :=
3066 Done (Succ Zero) (refl Nat (Succ Zero)).
3067
3068-- Proof that 2 reaches 1
3069-- Chain: 2 -> 1 (since 2 is even, take_collatz_step(2) = halve(2) = 1)
3070Definition two_reaches : ReachesOne (Succ (Succ Zero)) :=
3071 Step (Succ (Succ Zero)) (Done (Succ Zero) (refl Nat (Succ Zero))).
3072
3073-- Proof that 4 reaches 1
3074-- Chain: 4 -> 2 -> 1
3075Definition four_reaches : ReachesOne (Succ (Succ (Succ (Succ Zero)))) :=
3076 Step (Succ (Succ (Succ (Succ Zero))))
3077 (Step (Succ (Succ Zero))
3078 (Done (Succ Zero) (refl Nat (Succ Zero)))).
3079
3080-- Proof that 8 reaches 1
3081-- Chain: 8 -> 4 -> 2 -> 1
3082Definition eight_reaches : ReachesOne (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero)))))))) :=
3083 Step (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero))))))))
3084 (Step (Succ (Succ (Succ (Succ Zero))))
3085 (Step (Succ (Succ Zero))
3086 (Done (Succ Zero) (refl Nat (Succ Zero))))).
3087
3088-- Verify the proofs type-check
3089Check one_reaches.
3090Check two_reaches.
3091Check four_reaches.
3092Check eight_reaches.
3093
3094-- ============================================
3095-- THE INVERSE COLLATZ TREE
3096-- ============================================
3097-- A different perspective: instead of proving numbers GO to 1,
3098-- prove numbers COME FROM 1 by reversing the rules.
3099--
3100-- From any n in the tree:
3101-- - 2n is always in the tree (reverse the "even" rule)
3102-- - (n-1)/3 is in the tree if it's a positive odd integer
3103--
3104-- This tree is well-founded, so we CAN do structural induction!
3105
3106Inductive InverseCollatz (n : Nat) :=
3107 | Root : Eq Nat n (Succ Zero) -> InverseCollatz n
3108 | FromDouble : InverseCollatz n -> InverseCollatz (double n)
3109 | FromTripleSucc : InverseCollatz (Succ (triple n)) -> InverseCollatz n.
3110
3111-- ============================================
3112-- STRUCTURAL THEOREMS
3113-- ============================================
3114-- We can prove general facts about the inverse tree.
3115
3116-- Theorem: 1 is in the inverse tree
3117Definition one_in_tree : InverseCollatz (Succ Zero) :=
3118 Root (Succ Zero) (refl Nat (Succ Zero)).
3119
3120-- Theorem: 2 is in the tree (since 2 = double 1)
3121Definition two_in_tree : InverseCollatz (Succ (Succ Zero)) :=
3122 FromDouble (Succ Zero) one_in_tree.
3123
3124-- Theorem: 4 is in the tree (since 4 = double 2)
3125Definition four_in_tree : InverseCollatz (Succ (Succ (Succ (Succ Zero)))) :=
3126 FromDouble (Succ (Succ Zero)) two_in_tree.
3127
3128-- Verify the tree membership proofs
3129Check one_in_tree.
3130Check two_in_tree.
3131Check four_in_tree.
3132
3133-- ============================================
3134-- THEOREM 1: All Powers of Two
3135-- ============================================
3136-- power_of_two computes 2^n: 2^0 = 1, 2^(n+1) = double(2^n)
3137
3138Definition power_of_two : Nat -> Nat :=
3139 fix rec => fun n : Nat =>
3140 match n return Nat with
3141 | Zero => Succ Zero
3142 | Succ k => double (rec k)
3143 end.
3144
3145-- Theorem: All 2^n are in the inverse tree (proof by induction on n)
3146-- Base: 2^0 = 1 is the Root
3147-- Step: If 2^k is in tree, then 2^(k+1) = double(2^k) is in tree via FromDouble
3148Definition all_powers_of_two : forall n : Nat, InverseCollatz (power_of_two n) :=
3149 fix proof => fun n : Nat =>
3150 match n return (fun k : Nat => InverseCollatz (power_of_two k)) with
3151 | Zero => Root (Succ Zero) (refl Nat (Succ Zero))
3152 | Succ k => FromDouble (power_of_two k) (proof k)
3153 end.
3154
3155Check power_of_two.
3156Check all_powers_of_two.
3157
3158-- Verify: power_of_two 3 = 8
3159Eval (power_of_two (Succ (Succ (Succ Zero)))).
3160
3161-- ============================================
3162-- THEOREM 2: Grandchild Growth
3163-- ============================================
3164-- If n is in the tree, then 4n = double(double(n)) is also in the tree
3165-- This shows the tree has "depth" - we can always extend further
3166
3167Definition grandchild_growth : forall n : Nat, InverseCollatz n -> InverseCollatz (double (double n)) :=
3168 fun n : Nat => fun pf : InverseCollatz n =>
3169 FromDouble (double n) (FromDouble n pf).
3170
3171Check grandchild_growth.
3172
3173-- ============================================
3174-- THEOREM 3: Odd Numbers via FromTripleSucc
3175-- ============================================
3176-- 5 is in the tree because 3*5+1 = 16 = 2^4 is in the tree
3177-- This demonstrates the "reverse odd step" rule
3178
3179-- 5 is in tree: FromTripleSucc requires InverseCollatz (Succ (triple 5))
3180-- triple 5 = 15, so Succ (triple 5) = 16 = 2^4
3181Definition five_in_tree : InverseCollatz five :=
3182 FromTripleSucc five (all_powers_of_two four).
3183
3184Check five_in_tree.
3185
3186-- ============================================
3187-- WHAT WE PROVED AND DIDN'T PROVE
3188-- ============================================
3189-- PROVED:
3190-- - Specific numbers (1, 2, 4, 8) reach 1 via ReachesOne
3191-- - All powers of 2 are in the inverse tree (all_powers_of_two)
3192-- - If n is in tree, so is 4n (grandchild_growth)
3193-- - 5 is in the tree via the FromTripleSucc rule (five_in_tree)
3194-- - The inverse tree contains infinitely many numbers
3195--
3196-- DID NOT PROVE:
3197-- - That ALL positive integers reach 1 (the full conjecture)
3198-- - That the inverse tree covers ALL positive integers
3199--
3200-- The full conjecture remains open in mathematics!
3201-- But this demonstrates how proof assistants let us
3202-- verify partial results with absolute certainty.
3203
3204-- ============================================
3205-- PART 3: TOPOLOGY OF THE INVERSE GRAPH
3206-- ============================================
3207-- The inverse Collatz graph has special "skeleton" structure.
3208-- "Skeleton nodes" (junctions) are nodes of the form 6k + 4.
3209-- These are the ONLY nodes that can spawn odd children!
3210--
3211-- Key insight: For (n-1)/3 to be a positive odd integer,
3212-- we need n = 6k + 4 for some k.
3213
3214-- ============================================
3215-- SKELETON PREDICATE
3216-- ============================================
3217-- n is a skeleton node if n = 6k + 4 for some k
3218
3219Inductive IsSkeleton (n : Nat) :=
3220 | Witness : forall k : Nat, Eq Nat n (add (mul six k) four) -> IsSkeleton n.
3221
3222-- ============================================
3223-- ODDNESS PREDICATE
3224-- ============================================
3225-- n is odd if n = 2k + 1 for some k
3226
3227Inductive IsOdd (n : Nat) :=
3228 | OddWitness : forall k : Nat, Eq Nat n (Succ (double k)) -> IsOdd n.
3229
3230Check IsSkeleton.
3231Check IsOdd.
3232
3233-- ============================================
3234-- CONCRETE SKELETON EXAMPLES
3235-- ============================================
3236-- Demonstrate specific skeleton nodes: 4, 10, 16, 22...
3237-- These are the nodes of the form 6k + 4.
3238
3239-- 4 is skeleton: 4 = 6*0 + 4
3240Definition four_is_skeleton : IsSkeleton four :=
3241 Witness four Zero (refl Nat four).
3242
3243Check four_is_skeleton.
3244
3245-- 10 is skeleton: 10 = 6*1 + 4
3246-- First define 10
3247Definition ten : Nat := add six four.
3248
3249Definition ten_is_skeleton : IsSkeleton ten :=
3250 Witness ten (Succ Zero) (refl Nat ten).
3251
3252Check ten_is_skeleton.
3253
3254-- ============================================
3255-- CONCRETE ODD EXAMPLES
3256-- ============================================
3257-- Demonstrate specific odd numbers and their skeleton mappings.
3258
3259-- 1 is odd: 1 = 2*0 + 1
3260Definition one_is_odd : IsOdd (Succ Zero) :=
3261 OddWitness (Succ Zero) Zero (refl Nat (Succ Zero)).
3262
3263Check one_is_odd.
3264
3265-- 3 is odd: 3 = 2*1 + 1
3266Definition three : Nat := Succ (Succ (Succ Zero)).
3267Definition three_is_odd : IsOdd three :=
3268 OddWitness three (Succ Zero) (refl Nat three).
3269
3270Check three_is_odd.
3271
3272-- ============================================
3273-- SKELETON REDUCTION EXAMPLES
3274-- ============================================
3275-- Verify that 3m+1 lands on skeleton nodes for specific odd m.
3276--
3277-- For m=1: 3*1+1 = 4 = 6*0 + 4 (skeleton!)
3278-- For m=3: 3*3+1 = 10 = 6*1 + 4 (skeleton!)
3279
3280-- Verify: take_collatz_step(1) = 4 (since 1 is odd)
3281Eval (take_collatz_step (Succ Zero)).
3282
3283-- Verify: take_collatz_step(3) = 10 (since 3 is odd)
3284Eval (take_collatz_step three).
3285
3286-- ============================================
3287-- THEOREM 5: GREEN HIGHWAY
3288-- ============================================
3289-- Powers of 4 provide an infinite highway of skeleton nodes.
3290--
3291-- Power of four function: 4^n
3292
3293Definition power_of_four : Nat -> Nat :=
3294 fix rec => fun n : Nat =>
3295 match n return Nat with
3296 | Zero => Succ Zero
3297 | Succ k => double (double (rec k))
3298 end.
3299
3300Check power_of_four.
3301
3302-- Verify computations
3303Eval (power_of_four Zero).
3304Eval (power_of_four (Succ Zero)).
3305Eval (power_of_four (Succ (Succ Zero))).
3306Eval (power_of_four (Succ (Succ (Succ Zero)))).
3307
3308-- Base case: 4^1 = 4 is skeleton (6*0 + 4)
3309Definition pow4_1_skeleton : IsSkeleton (power_of_four (Succ Zero)) :=
3310 Witness (power_of_four (Succ Zero)) Zero (refl Nat four).
3311
3312Check pow4_1_skeleton.
3313
3314-- 4^2 = 16 is skeleton: 16 = 6*2 + 4
3315Definition two : Nat := Succ (Succ Zero).
3316Definition pow4_2_skeleton : IsSkeleton (power_of_four (Succ (Succ Zero))) :=
3317 Witness (power_of_four (Succ (Succ Zero))) two (refl Nat sixteen).
3318
3319Check pow4_2_skeleton.
3320
3321-- ============================================
3322-- PART 3 SUMMARY
3323-- ============================================
3324-- We have demonstrated the "Skeleton Network" topology:
3325-- 1. Skeleton nodes are defined by n = 6k + 4 for some k.
3326-- 2. Examples: 4, 10, 16, 22... are all skeleton nodes.
3327-- 3. Odd numbers map to skeleton nodes via 3m+1 (verified for m=1, m=3).
3328-- 4. The Green Highway (4^n) provides skeleton nodes: 4, 16, 64...
3329-- 5. To solve Collatz, we only need to check if the Skeleton is connected.
3330"###;
3331
3332pub const MATH_GODEL_LITERATE: &str = r###"-- Gödel Sentence Construction (Literate Mode)
3337-- Building the self-referential sentence G that says "I am not provable"
3338--
3339-- This example demonstrates the fully Literate meta-logic syntax:
3340-- - "## To be Predicate" for predicate definitions
3341-- - "Let X be Y" for constant definitions
3342-- - "the Name X" for syntax names (maps to SName)
3343-- - "Variable N" for syntax variables (maps to SVar)
3344-- - "Apply(f, x)" for syntax application (maps to SApp)
3345-- - "the diagonalization of T" for diagonal lemma
3346-- - "there exists a d: T such that P" for existential quantification
3347-- - "X equals Y" for equality propositions
3348
3349-- 1. The Provability Predicate
3350-- "s is provable if there exists a derivation d that concludes s"
3351
3352## To be Provable (s: Syntax) -> Prop:
3353 Yield there exists a d: Derivation such that (concludes(d) equals s).
3354
3355-- 2. The Template T
3356-- T encodes "Not(Provable(x))" as syntax
3357
3358Let Not_Name be the Name "Not".
3359Let Provable_Name be the Name "Provable".
3360Let T be Apply(Not_Name, Apply(Provable_Name, Variable 0)).
3361
3362-- 3. The Gödel Sentence G
3363-- G = T[code(T)/x] via the diagonal lemma
3364-- G says "I am not provable"
3365
3366Let G be the diagonalization of T.
3367
3368-- Verification
3369
3370Check Provable.
3371Check T.
3372Check G.
3373Check Provable(G).
3374"###;
3375
3376pub const MATH_INCOMPLETENESS_LITERATE: &str = r###"-- Gödel's First Incompleteness Theorem (Literate Mode)
3377-- "If LOGOS is consistent, then G is not provable"
3378--
3379-- This example demonstrates fully Literate syntax:
3380-- - "## To be Predicate" for predicate definitions
3381-- - "## To be Consistent -> Prop:" for nullary predicates
3382-- - "## Theorem:" blocks with "Statement:"
3383-- - "X implies Y" for logical implication
3384-- - "X equals Y" for equality propositions
3385
3386-- 1. The Provability Predicate
3387
3388## To be Provable (s: Syntax) -> Prop:
3389 Yield there exists a d: Derivation such that (concludes(d) equals s).
3390
3391-- 2. Consistency Definition
3392-- A system is consistent if it cannot prove False
3393
3394Let False_Name be the Name "False".
3395
3396## To be Consistent -> Prop:
3397 Yield Not(Provable(False_Name)).
3398
3399-- 3. The Gödel Sentences
3400
3401Let T be Apply(the Name "Not", Apply(the Name "Provable", Variable 0)).
3402Let G be the diagonalization of T.
3403
3404-- 4. The Theorem Statement
3405
3406## Theorem: Godel_First_Incompleteness
3407 Statement: Consistent implies Not(Provable(G)).
3408
3409-- Verification
3410
3411Check Godel_First_Incompleteness.
3412Check Consistent.
3413Check Provable(G).
3414Check Not(Provable(G)).
3415"###;
3416
3417const MATH_RING: &str = r###"-- The ring Tactic: Polynomial Equality by Normalization
3418-- The ring tactic proves polynomial equalities automatically!
3419-- It works by normalizing both sides to canonical polynomial form
3420-- and checking if they're structurally equal.
3421--
3422-- Supported operations: add, sub, mul (no division)
3423-- This is a decision procedure - it either proves the equality or fails.
3424
3425-- Basic Setup
3426
3427-- Type annotation (for the Eq constructor)
3428Definition T : Syntax := SName "Int".
3429
3430-- Variables using de Bruijn indices
3431Definition x : Syntax := SVar 0.
3432Definition y : Syntax := SVar 1.
3433Definition z : Syntax := SVar 2.
3434
3435-- Example 1: Reflexivity (x = x)
3436
3437Definition refl_goal : Syntax := SApp (SApp (SApp (SName "Eq") T) x) x.
3438Definition refl_proof : Derivation := try_ring refl_goal.
3439Definition refl_result : Syntax := concludes refl_proof.
3440
3441Check refl_proof.
3442Eval refl_result.
3443
3444-- Example 2: Commutativity of Addition (x + y = y + x)
3445
3446Definition add_xy : Syntax := SApp (SApp (SName "add") x) y.
3447Definition add_yx : Syntax := SApp (SApp (SName "add") y) x.
3448Definition comm_add_goal : Syntax := SApp (SApp (SApp (SName "Eq") T) add_xy) add_yx.
3449
3450-- The ring tactic proves this automatically!
3451Definition comm_add_proof : Derivation := try_ring comm_add_goal.
3452Definition comm_add_result : Syntax := concludes comm_add_proof.
3453
3454Check comm_add_proof.
3455Eval comm_add_result.
3456
3457-- Example 3: Commutativity of Multiplication (x * y = y * x)
3458
3459Definition mul_xy : Syntax := SApp (SApp (SName "mul") x) y.
3460Definition mul_yx : Syntax := SApp (SApp (SName "mul") y) x.
3461Definition comm_mul_goal : Syntax := SApp (SApp (SApp (SName "Eq") T) mul_xy) mul_yx.
3462
3463Definition comm_mul_proof : Derivation := try_ring comm_mul_goal.
3464Definition comm_mul_result : Syntax := concludes comm_mul_proof.
3465
3466Check comm_mul_proof.
3467Eval comm_mul_result.
3468
3469-- Example 4: Distributivity (x * (y + z) = x*y + x*z)
3470
3471-- LHS: x * (y + z)
3472Definition y_plus_z : Syntax := SApp (SApp (SName "add") y) z.
3473Definition dist_lhs : Syntax := SApp (SApp (SName "mul") x) y_plus_z.
3474
3475-- RHS: x*y + x*z
3476Definition x_times_y : Syntax := SApp (SApp (SName "mul") x) y.
3477Definition x_times_z : Syntax := SApp (SApp (SName "mul") x) z.
3478Definition dist_rhs : Syntax := SApp (SApp (SName "add") x_times_y) x_times_z.
3479
3480Definition dist_goal : Syntax := SApp (SApp (SApp (SName "Eq") T) dist_lhs) dist_rhs.
3481
3482Definition dist_proof : Derivation := try_ring dist_goal.
3483Definition dist_result : Syntax := concludes dist_proof.
3484
3485Check dist_proof.
3486Eval dist_result.
3487
3488-- Example 5: The Collatz Algebra Step
3489-- The key algebraic identity in Collatz analysis:
3490-- 3(2k+1) + 1 = 6k + 4
3491--
3492-- This proves that applying the Collatz odd step (3n+1)
3493-- to an odd number of the form 2k+1 yields 6k+4.
3494
3495Definition k : Syntax := SVar 0.
3496
3497-- Build LHS: 3 * (2*k + 1) + 1
3498Definition two_k : Syntax := SApp (SApp (SName "mul") (SLit 2)) k.
3499Definition two_k_plus_1 : Syntax := SApp (SApp (SName "add") two_k) (SLit 1).
3500Definition three_times : Syntax := SApp (SApp (SName "mul") (SLit 3)) two_k_plus_1.
3501Definition collatz_lhs : Syntax := SApp (SApp (SName "add") three_times) (SLit 1).
3502
3503-- Build RHS: 6*k + 4
3504Definition six_k : Syntax := SApp (SApp (SName "mul") (SLit 6)) k.
3505Definition collatz_rhs : Syntax := SApp (SApp (SName "add") six_k) (SLit 4).
3506
3507-- The equality goal
3508Definition collatz_goal : Syntax := SApp (SApp (SApp (SName "Eq") T) collatz_lhs) collatz_rhs.
3509
3510-- Ring proves it!
3511Definition collatz_proof : Derivation := try_ring collatz_goal.
3512Definition collatz_result : Syntax := concludes collatz_proof.
3513
3514Check collatz_proof.
3515Eval collatz_result.
3516
3517-- Example 6: Associativity ((x + y) + z = x + (y + z))
3518
3519Definition xy_plus_z : Syntax := SApp (SApp (SName "add") (SApp (SApp (SName "add") x) y)) z.
3520Definition x_plus_yz : Syntax := SApp (SApp (SName "add") x) (SApp (SApp (SName "add") y) z).
3521Definition assoc_goal : Syntax := SApp (SApp (SApp (SName "Eq") T) xy_plus_z) x_plus_yz.
3522
3523Definition assoc_proof : Derivation := try_ring assoc_goal.
3524Definition assoc_result : Syntax := concludes assoc_proof.
3525
3526Check assoc_proof.
3527Eval assoc_result.
3528
3529-- Example 7: Subtraction Cancellation (x - x = 0)
3530
3531Definition x_minus_x : Syntax := SApp (SApp (SName "sub") x) x.
3532Definition zero_lit : Syntax := SLit 0.
3533Definition cancel_goal : Syntax := SApp (SApp (SApp (SName "Eq") T) x_minus_x) zero_lit.
3534
3535Definition cancel_proof : Derivation := try_ring cancel_goal.
3536Definition cancel_result : Syntax := concludes cancel_proof.
3537
3538Check cancel_proof.
3539Eval cancel_result.
3540
3541-- Summary
3542-- The ring tactic is a decision procedure for polynomial ring equalities.
3543-- It handles: constants, variables, addition, subtraction, multiplication.
3544-- It does NOT handle: division, modulo, or non-polynomial operations.
3545--
3546-- Key insight: Both sides are normalized to a canonical polynomial form
3547-- (sum of monomials with sorted variable indices), and compared structurally.
3548-- If they match, the equality is provable. If not, it fails.
3549"###;
3550
3551const MATH_LIA: &str = r###"-- The lia Tactic: Linear Integer Arithmetic
3552-- The lia tactic proves linear inequalities automatically!
3553-- It uses Fourier-Motzkin elimination to decide validity.
3554--
3555-- Supported: Lt (<), Le (<=), Gt (>), Ge (>=)
3556-- Expressions must be LINEAR: constants, variables, c*x (no x*y)
3557
3558-- Basic Setup
3559
3560-- Variables using de Bruijn indices
3561Definition x : Syntax := SVar 0.
3562Definition y : Syntax := SVar 1.
3563Definition z : Syntax := SVar 2.
3564
3565-- Example 1: Reflexivity (x <= x)
3566
3567Definition le_refl_goal : Syntax := SApp (SApp (SName "Le") x) x.
3568Definition le_refl_proof : Derivation := try_lia le_refl_goal.
3569Definition le_refl_result : Syntax := concludes le_refl_proof.
3570
3571Check le_refl_proof.
3572Eval le_refl_result.
3573
3574-- Example 2: Constant Inequality (2 < 5)
3575
3576Definition const_lt_goal : Syntax := SApp (SApp (SName "Lt") (SLit 2)) (SLit 5).
3577Definition const_lt_proof : Derivation := try_lia const_lt_goal.
3578Definition const_lt_result : Syntax := concludes const_lt_proof.
3579
3580Check const_lt_proof.
3581Eval const_lt_result.
3582
3583-- Example 3: Successor (x < x + 1)
3584
3585Definition x_plus_1 : Syntax := SApp (SApp (SName "add") x) (SLit 1).
3586Definition succ_goal : Syntax := SApp (SApp (SName "Lt") x) x_plus_1.
3587Definition succ_proof : Derivation := try_lia succ_goal.
3588Definition succ_result : Syntax := concludes succ_proof.
3589
3590Check succ_proof.
3591Eval succ_result.
3592
3593-- Example 4: Linear Coefficient (2*x <= 2*x)
3594
3595Definition two_x : Syntax := SApp (SApp (SName "mul") (SLit 2)) x.
3596Definition linear_goal : Syntax := SApp (SApp (SName "Le") two_x) two_x.
3597Definition linear_proof : Derivation := try_lia linear_goal.
3598Definition linear_result : Syntax := concludes linear_proof.
3599
3600Check linear_proof.
3601Eval linear_result.
3602
3603-- Example 5: Predecessor (x - 1 < x)
3604
3605Definition x_minus_1 : Syntax := SApp (SApp (SName "sub") x) (SLit 1).
3606Definition pred_goal : Syntax := SApp (SApp (SName "Lt") x_minus_1) x.
3607Definition pred_proof : Derivation := try_lia pred_goal.
3608Definition pred_result : Syntax := concludes pred_proof.
3609
3610Check pred_proof.
3611Eval pred_result.
3612
3613-- Example 6: Equality Bound (5 <= 5)
3614
3615Definition eq_bound_goal : Syntax := SApp (SApp (SName "Le") (SLit 5)) (SLit 5).
3616Definition eq_bound_proof : Derivation := try_lia eq_bound_goal.
3617Definition eq_bound_result : Syntax := concludes eq_bound_proof.
3618
3619Check eq_bound_proof.
3620Eval eq_bound_result.
3621
3622-- Summary
3623-- The lia tactic is a decision procedure for linear integer arithmetic.
3624-- It handles: constants, variables, addition, subtraction, c*x multiplication.
3625-- It does NOT handle: variable * variable (nonlinear), division, modulo.
3626--
3627-- Key insight: Fourier-Motzkin elimination projects out variables one by one,
3628-- combining lower and upper bounds until only constant constraints remain.
3629-- If these are contradictory, the negation is unsatisfiable, proving the goal.
3630"###;
3631
3632const CODE_BASICS_VARIABLES: &str = r#"# Variables and Types
3637-- Let binds a value; the type is inferred from it.
3638
3639## Main
3640
3641Let name be "Alice".
3642Let age be 25.
3643Let is_active be true.
3644Let price be 19.99.
3645
3646Show "{name} is {age}, active: {is_active}".
3647Show "ticket price: {price:$}".
3648
3649Let mutable count be 100.
3650Set count to count * 2.
3651Show "count doubled: {count}".
3652"#;
3653
3654const CODE_BASICS_OPERATORS: &str = r#"# Operators
3655-- Symbols for arithmetic; English or symbols for comparisons.
3656
3657## Main
3658
3659Let a be 10.
3660Let b be 3.
3661
3662Show "{a} + {b} = {a + b}".
3663Show "{a} - {b} = {a - b}".
3664Show "{a} * {b} = {a * b}".
3665Show "{a} / {b} = {a / b}".
3666Show "{a} % {b} = {a % b}".
3667
3668If a is greater than b:
3669 Show "{a} is greater than {b}".
3670If 1 <= a <= 100:
3671 Show "{a} is between 1 and 100 (chained comparison)".
3672If a is between 5 and 15:
3673 Show "{a} is between 5 and 15".
3674If a is even:
3675 Show "{a} is even".
3676If b is odd:
3677 Show "{b} is odd".
3678If a is divisible by 5:
3679 Show "{a} is divisible by 5".
3680
3681Let sunny be true.
3682Let warm be false.
3683Let both be sunny and warm.
3684Let either be sunny or warm.
3685Let flipped be not sunny.
3686Show "sunny and warm: {both}".
3687Show "sunny or warm: {either}".
3688Show "not sunny: {flipped}".
3689"#;
3690
3691const CODE_BASICS_CONTROL_FLOW: &str = r#"# Control Flow
3692-- If chooses, While repeats, Repeat walks a range or a list.
3693
3694## Main
3695
3696Let score be 85.
3697If score is at least 90:
3698 Show "Grade: A".
3699Otherwise If score is at least 80:
3700 Show "Grade: B".
3701Otherwise:
3702 Show "Grade: C or below".
3703
3704Show "Countdown:".
3705Let mutable count be 3.
3706While count >= 1:
3707 Show count.
3708 Set count to count - 1.
3709Show "Blastoff!".
3710
3711Show "First multiple of 7 above 20:".
3712Repeat for n from 21 to 35:
3713 If n is divisible by 7:
3714 Show n.
3715 Break.
3716"#;
3717
3718const CODE_ENUMS_PATTERNS: &str = r#"# Enums with Data
3723-- Variants can carry fields; Inspect binds them by position.
3724
3725## A Shape is one of:
3726 A Circle with radius Int.
3727 A Rectangle with width Int and height Int.
3728
3729## Main
3730
3731Let round be a new Circle with radius 5.
3732Inspect round:
3733 When Circle (r): Show "Circle with radius {r}, area about {3 * r * r}".
3734 When Rectangle (w, h): Show "Rectangle {w} x {h}".
3735
3736Let box be a new Rectangle with width 4 and height 6.
3737Inspect box:
3738 When Circle (r): Show "Circle with radius {r}".
3739 When Rectangle (w, h): Show "Rectangle {w} x {h}, area {w * h}".
3740"#;
3741
3742const CODE_OWNERSHIP: &str = r#"# Memory and Ownership
3747-- Show lends a value; Give moves it; copy of duplicates it.
3748
3749## To display (data: Text):
3750 Show "Viewing: {data}".
3751
3752## To consume (data: Text):
3753 Show "Consumed: {data}".
3754
3755## Main
3756
3757Let profile be "User Profile Data".
3758
3759Show profile to display.
3760Show "Still usable after lending: {profile}".
3761
3762Let duplicate be copy of profile.
3763Give duplicate to consume.
3764
3765Show "Original intact: {profile}".
3766"#;
3767
3768const CODE_CONCURRENCY_PARALLEL: &str = r#"# Parallel Blocks
3773-- Simultaneously runs statements on separate cores.
3774-- Attempt all overlaps async work and joins the results.
3775
3776## Main
3777
3778Simultaneously:
3779 Let squares be 25 * 25.
3780 Let cubes be 9 * 9 * 9.
3781
3782Show "25^2 = {squares}, 9^3 = {cubes}".
3783Show "product: {squares * cubes}".
3784
3785Attempt all of the following:
3786 Let x be 10.
3787 Let y be 20.
3788
3789Show "x + y = {x + y}".
3790"#;
3791
3792pub const CODE_CRDT_TALLY: &str = r#"# Tally
3797-- A Tally counts both ways and still merges cleanly across replicas.
3798
3799## Definition
3800A Score is Shared and has:
3801 points: Tally.
3802
3803## Main
3804Let mutable s be a new Score.
3805Increase s's points by 100.
3806Show "after +100: {s's points}".
3807
3808Decrease s's points by 30.
3809Show "after -30: {s's points}".
3810
3811Increase s's points by 10.
3812Show "final: {s's points}".
3813"#;
3814
3815const CODE_CRDT_MERGE: &str = r#"# Merging Replicas
3816-- Two replicas count independently, then merge without losing anything.
3817
3818## Definition
3819A Stats is Shared and has:
3820 views: ConvergentCount.
3821
3822## Main
3823Let mutable local be a new Stats.
3824Increase local's views by 100.
3825Show "local views: {local's views}".
3826
3827Let mutable remote be a new Stats.
3828Increase remote's views by 50.
3829Show "remote views: {remote's views}".
3830
3831Merge remote into local.
3832Show "after merge: {local's views}".
3833"#;
3834
3835const CODE_NETWORK_SERVER: &str = r#"# P2P Server
3840-- Listen binds a libp2p multiaddr; LAN peers are found via mDNS.
3841-- Live networking needs the compiled runtime: build with `largo build`.
3842
3843## Definition
3844A Message is Portable and has:
3845 content: Text.
3846
3847## Main
3848
3849Listen on "/ip4/0.0.0.0/tcp/8000".
3850Show "Server listening on port 8000".
3851Show "mDNS will auto-discover local peers".
3852"#;
3853
3854const CODE_NETWORK_CLIENT: &str = r#"# P2P Client
3855-- Connect dials a peer; a PeerAgent is a handle for sending to it.
3856-- Live networking needs the compiled runtime: build with `largo build`.
3857
3858## Definition
3859A Greeting is Portable and has:
3860 message: Text.
3861
3862## Main
3863
3864Let server be "/ip4/127.0.0.1/tcp/8000".
3865Connect to server.
3866Show "Connected!".
3867
3868Let remote be a PeerAgent at server.
3869Let msg be a new Greeting with message "Hello, peer!".
3870Send msg to remote.
3871Show "Message sent".
3872"#;
3873
3874const CODE_ERROR_HANDLING: &str = r#"# Outcomes, Not Crashes
3879-- A function that can fail returns an either-type; Inspect handles both arms.
3880
3881## Definition
3882An Outcome is either:
3883 Success (value: Int).
3884 Failure (message: Text).
3885
3886## To checked_divide (a: Int) and (b: Int) -> Outcome:
3887 If b equals 0:
3888 Return a new Failure with message "cannot divide {a} by zero".
3889 Return a new Success with value (a / b).
3890
3891## Main
3892
3893Let good be checked_divide(10, 2).
3894Inspect good:
3895 When Success (v): Show "10 / 2 = {v}".
3896 When Failure (m): Show "error: {m}".
3897
3898Let bad be checked_divide(5, 0).
3899Inspect bad:
3900 When Success (v): Show "5 / 0 = {v}".
3901 When Failure (m): Show "error: {m}".
3902"#;
3903
3904const CODE_ADVANCED_REFINEMENT: &str = r#"# Refinement Types
3909-- A type can carry a constraint; the value must satisfy it.
3910
3911## Main
3912
3913Let positive: Int where it > 0 be 5.
3914Let percentage: Int where it >= 0 and it <= 100 be 85.
3915Let dice: Int where it >= 1 and it <= 6 be 4.
3916
3917Show "positive: {positive}".
3918Show "percentage: {percentage}".
3919Show "dice roll: {dice}".
3920"#;
3921
3922const CODE_ADVANCED_ASSERTIONS: &str = r#"# Assert and Trust
3923-- Assert checks a claim at runtime; Trust records a justified assumption.
3924
3925## To withdraw (amount: Int) from (balance: Int) -> Int:
3926 Assert that amount is greater than 0.
3927 Assert that amount is at most balance.
3928 Return balance - amount.
3929
3930## To process (n: Int) -> Int:
3931 Trust that n is greater than 0 because "caller guarantees positive input".
3932 Return n * 2.
3933
3934## Main
3935
3936Let result be withdraw(50, 100).
3937Show "withdrew 50 from 100, leaving {result}".
3938
3939Let doubled be process(5).
3940Show "process(5) = {doubled}".
3941"#;
3942
3943const CODE_TEMPORAL: &str = r#"# Durations
3948-- Time literals are first-class values with real units.
3949
3950## Main
3951
3952Let blink be 50ns.
3953Let tick be 100us.
3954Let pause be 500ms.
3955Let breath be 1s.
3956Show "blink {blink}, tick {tick}, pause {pause}, breath {breath}".
3957
3958Let total be pause + pause.
3959Show "500ms + 500ms = {total}".
3960
3961If pause < breath:
3962 Show "500ms is less than 1s".
3963
3964Show "Sleeping 200ms...".
3965Sleep 200ms.
3966Show "Awake!".
3967"#;
3968
3969const MATH_CC: &str = r###"-- The cc Tactic: Congruence Closure
3974-- The cc tactic proves equalities over uninterpreted functions!
3975-- It uses the congruence rule: if a = b then f(a) = f(b)
3976--
3977-- Key insight: cc connects arithmetic proofs to function applications.
3978-- While ring proves "1 + 1 = 2", cc proves "f(1 + 1) = f(2)".
3979
3980-- Example 1: Reflexivity (f(x) = f(x))
3981-- Any term equals itself
3982
3983## Theorem: FxRefl
3984 Statement: (Eq (f x) (f x)).
3985 Proof: cc.
3986
3987Check FxRefl.
3988
3989-- Example 2: Nested Reflexivity (f(g(x)) = f(g(x)))
3990
3991## Theorem: FgxRefl
3992 Statement: (Eq (f (g x)) (f (g x))).
3993 Proof: cc.
3994
3995Check FgxRefl.
3996
3997-- Example 3: Congruence (x = y → f(x) = f(y))
3998-- The core congruence rule: equal arguments give equal results
3999
4000## Theorem: Congruence
4001 Statement: (implies (Eq x y) (Eq (f x) (f y))).
4002 Proof: cc.
4003
4004Check Congruence.
4005
4006-- Example 4: Binary Congruence (a = b → add(a,c) = add(b,c))
4007-- Congruence works for multi-argument functions too
4008
4009## Theorem: BinaryCongruence
4010 Statement: (implies (Eq a b) (Eq (add a c) (add b c))).
4011 Proof: cc.
4012
4013Check BinaryCongruence.
4014
4015-- Example 5: Transitivity Chain (a = b → b = c → f(a) = f(c))
4016-- Multiple hypotheses combine via transitivity
4017
4018## Theorem: Transitivity
4019 Statement: (implies (Eq a b) (implies (Eq b c) (Eq (f a) (f c)))).
4020 Proof: cc.
4021
4022Check Transitivity.
4023
4024-- Summary
4025-- The cc tactic proves equalities by:
4026-- 1. Building an E-graph from all subterms
4027-- 2. Merging equivalence classes from hypothesis equalities
4028-- 3. Propagating congruences: if a=b then f(a)=f(b)
4029-- 4. Checking if goal's LHS and RHS are equivalent
4030--
4031-- This completes the trinity of automated tactics:
4032-- - ring: polynomial equalities (normalization)
4033-- - lia: linear inequalities (Fourier-Motzkin)
4034-- - cc: function equalities (congruence closure)
4035"###;
4036
4037const MATH_SIMP: &str = r###"-- The simp Tactic: Term Rewriting
4038-- The simp tactic normalizes goals by applying rewrite rules!
4039-- It unfolds definitions and simplifies arithmetic.
4040--
4041-- Key insight: simp turns complex terms into canonical forms,
4042-- making equalities trivially checkable by reflexivity.
4043
4044-- Example 1: Arithmetic Simplification
4045-- Constant expressions are evaluated
4046
4047## Theorem: TwoPlusThree
4048 Statement: (Eq (add 2 3) 5).
4049 Proof: simp.
4050
4051Check TwoPlusThree.
4052
4053## Theorem: Nested
4054 Statement: (Eq (mul (add 1 1) 3) 6).
4055 Proof: simp.
4056
4057Check Nested.
4058
4059## Theorem: TenMinusFour
4060 Statement: (Eq (sub 10 4) 6).
4061 Proof: simp.
4062
4063Check TenMinusFour.
4064
4065-- Example 2: Definition Unfolding
4066
4067## To double (n: Int) -> Int:
4068 Yield (add n n).
4069
4070## Theorem: DoubleTwo
4071 Statement: (double 2) equals 4.
4072 Proof: simp.
4073
4074Check DoubleTwo.
4075
4076## To quadruple (n: Int) -> Int:
4077 Yield (double (double n)).
4078
4079## Theorem: QuadTwo
4080 Statement: (quadruple 2) equals 8.
4081 Proof: simp.
4082
4083Check QuadTwo.
4084
4085## To zero_fn (n: Int) -> Int:
4086 Yield 0.
4087
4088## Theorem: ZeroFnTest
4089 Statement: (zero_fn 42) equals 0.
4090 Proof: simp.
4091
4092Check ZeroFnTest.
4093
4094-- Example 3: With Hypotheses
4095-- simp uses equalities from hypotheses as rewrite rules
4096
4097## Theorem: SubstSimp
4098 Statement: (implies (Eq Int x 0) (Eq Int (add x 1) 1)).
4099 Proof: simp.
4100
4101Check SubstSimp.
4102
4103## Theorem: TwoHyps
4104 Statement: (implies (Eq Int x 1) (implies (Eq Int y 2) (Eq Int (add x y) 3))).
4105 Proof: simp.
4106
4107Check TwoHyps.
4108
4109-- Example 4: Reflexive Equalities
4110-- simp handles reflexivity for free
4111
4112## Theorem: XEqX
4113 Statement: (Eq x x).
4114 Proof: simp.
4115
4116Check XEqX.
4117
4118## Theorem: FxRefl
4119 Statement: (Eq (f x) (f x)).
4120 Proof: simp.
4121
4122Check FxRefl.
4123
4124-- Summary
4125-- The simp tactic:
4126-- 1. Collects rewrite rules from definitions and hypotheses
4127-- 2. Applies rules bottom-up to both sides of equality
4128-- 3. Evaluates arithmetic on constants
4129-- 4. Checks if simplified terms are equal
4130--
4131-- Combined with ring, lia, and cc, this completes the core
4132-- automated reasoning toolkit!
4133--
4134-- - ring: polynomial equalities (normalization)
4135-- - lia: linear inequalities (Fourier-Motzkin)
4136-- - cc: function equalities (congruence closure)
4137-- - simp: term rewriting (bottom-up simplification)
4138"###;
4139
4140const MATH_OMEGA: &str = r###"-- The omega Tactic: True Integer Arithmetic
4141-- The omega tactic handles LINEAR INTEGER constraints!
4142-- Unlike lia (which uses rationals), omega knows that:
4143-- x > 1 means x >= 2 for integers
4144-- 2x = 3 has NO solution (3 is odd!)
4145--
4146-- This is essential for array bounds, loop indices,
4147-- and anything involving discrete counts.
4148
4149-- Basic Inequalities (same as lia)
4150
4151## Theorem: TwoLessThanFive
4152 Statement: (Lt 2 5).
4153 Proof: omega.
4154
4155Check TwoLessThanFive.
4156
4157## Theorem: XLessThanXPlusOne
4158 Statement: (Lt x (add x 1)).
4159 Proof: omega.
4160
4161Check XLessThanXPlusOne.
4162
4163## Theorem: XLeX
4164 Statement: (Le x x).
4165 Proof: omega.
4166
4167Check XLeX.
4168
4169-- Integer-Specific Reasoning
4170-- These are IMPOSSIBLE with rational-based lia!
4171
4172## Theorem: StrictToNonStrict
4173 Statement: (implies (Gt x 0) (Ge x 1)).
4174 Proof: omega.
4175
4176Check StrictToNonStrict.
4177
4178-- x > 0 in rationals allows x = 0.001
4179-- x > 0 in integers means x >= 1
4180
4181## Theorem: LtConvertsToLe
4182 Statement: (implies (Lt x 5) (Le x 4)).
4183 Proof: omega.
4184
4185Check LtConvertsToLe.
4186
4187-- x < 5 in rationals allows x = 4.999
4188-- x < 5 in integers means x <= 4
4189
4190## Theorem: CoeffBound
4191 Statement: (implies (Le (mul 3 x) 10) (Le x 3)).
4192 Proof: omega.
4193
4194Check CoeffBound.
4195
4196-- 3x <= 10 means x <= floor(10/3) = 3
4197
4198## Theorem: TwoCoefficientBound
4199 Statement: (implies (Le (mul 2 x) 5) (Le x 2)).
4200 Proof: omega.
4201
4202Check TwoCoefficientBound.
4203
4204-- 2x <= 5 means x <= floor(5/2) = 2
4205
4206-- Transitivity and Chains
4207
4208## Theorem: LtTrans
4209 Statement: (implies (Lt x y) (implies (Lt y z) (Lt x z))).
4210 Proof: omega.
4211
4212Check LtTrans.
4213
4214## Theorem: LeTrans
4215 Statement: (implies (Le x y) (implies (Le y z) (Le x z))).
4216 Proof: omega.
4217
4218Check LeTrans.
4219
4220-- Summary
4221-- omega handles integer arithmetic properly:
4222-- 1. Strict-to-nonstrict conversion (x > n -> x >= n+1)
4223-- 2. Floor/ceil rounding in bounds
4224-- 3. Coefficient bounds with floor division
4225-- 4. Variable elimination via the Omega Test
4226--
4227-- Combined with ring, lia, cc, and simp, this completes
4228-- the core automated reasoning toolkit:
4229-- - ring: polynomial equalities (normalization)
4230-- - lia: linear rational inequalities (Fourier-Motzkin)
4231-- - cc: function equalities (congruence closure)
4232-- - simp: term rewriting (bottom-up simplification)
4233-- - omega: true integer arithmetic (Omega Test)
4234"###;
4235
4236pub const MATH_AUTO: &str = r###"-- The auto Tactic: The Infinity Gauntlet
4237-- The auto tactic combines ALL decision procedures!
4238-- It tries each one in sequence until one succeeds:
4239-- 1. True/False (trivial propositions)
4240-- 2. simp (simplification)
4241-- 3. ring (polynomial algebra)
4242-- 4. cc (congruence closure)
4243-- 5. omega (integer arithmetic)
4244-- 6. lia (linear arithmetic)
4245
4246-- Simplification (auto -> simp)
4247
4248## Theorem: TrueIsTrue
4249 Statement: True.
4250 Proof: auto.
4251
4252Check TrueIsTrue.
4253
4254-- Ring Algebra (auto -> ring)
4255
4256## Theorem: AddCommutative
4257 Statement: (add a b) equals (add b a).
4258 Proof: auto.
4259
4260Check AddCommutative.
4261
4262## Theorem: AddAssociative
4263 Statement: (add (add a b) c) equals (add a (add b c)).
4264 Proof: auto.
4265
4266Check AddAssociative.
4267
4268## Theorem: MulDistributes
4269 Statement: (mul a (add b c)) equals (add (mul a b) (mul a c)).
4270 Proof: auto.
4271
4272Check MulDistributes.
4273
4274-- Congruence Closure (auto -> cc)
4275
4276## Theorem: FunctionReflexive
4277 Statement: (Eq (f x) (f x)).
4278 Proof: auto.
4279
4280Check FunctionReflexive.
4281
4282-- Integer Arithmetic (auto -> omega)
4283
4284## Theorem: TwoLessThanFive
4285 Statement: (Lt 2 5).
4286 Proof: auto.
4287
4288Check TwoLessThanFive.
4289
4290## Theorem: StrictToNonStrict
4291 Statement: (implies (Gt x 0) (Ge x 1)).
4292 Proof: auto.
4293
4294Check StrictToNonStrict.
4295
4296## Theorem: XLessThanSucc
4297 Statement: (Lt x (add x 1)).
4298 Proof: auto.
4299
4300Check XLessThanSucc.
4301
4302-- Linear Arithmetic (auto -> lia/omega)
4303
4304## Theorem: LeReflexive
4305 Statement: (Le x x).
4306 Proof: auto.
4307
4308Check LeReflexive.
4309
4310## Theorem: LeTransitive
4311 Statement: (implies (Le x y) (implies (Le y z) (Le x z))).
4312 Proof: auto.
4313
4314Check LeTransitive.
4315
4316-- The Power of auto
4317-- With auto, you don't need to think about
4318-- which tactic to use. Just say:
4319--
4320-- Proof: auto.
4321--
4322-- And the system figures it out!
4323--
4324-- auto combines ALL five stones:
4325-- - ring: polynomial equalities
4326-- - lia: linear rational arithmetic
4327-- - cc: congruence closure
4328-- - simp: simplification
4329-- - omega: true integer arithmetic
4330--
4331-- This is the Infinity Gauntlet of tactics!
4332"###;
4333
4334const MATH_INDUCTION: &str = r###"-- The induction Tactic: The Time Machine
4335-- Structural reasoning for inductive types.
4336-- Works for Nat, Bool, and any user-defined inductive.
4337--
4338-- The induction tactic automatically:
4339-- 1. Looks up constructors for the inductive type
4340-- 2. Generates one subgoal per constructor
4341-- 3. Provides induction hypotheses for recursive cases
4342
4343-- Kernel Infrastructure
4344-- These are the building blocks for induction.
4345
4346-- Check that induction helpers exist
4347Check try_induction.
4348Check induction_base_goal.
4349Check induction_step_goal.
4350Check induction_num_cases.
4351
4352-- Nat Induction Examples
4353-- Nat has 2 constructors: Zero, Succ
4354
4355-- How many constructors does Nat have?
4356Definition nat_cases : Nat := induction_num_cases (SName "Nat").
4357Eval nat_cases.
4358
4359-- The motive: what we're proving (λn:Nat. Le n n)
4360Definition le_motive : Syntax := SLam (SName "Nat") (SApp (SApp (SName "Le") (SVar 0)) (SVar 0)).
4361
4362-- Base case goal: Le Zero Zero
4363Definition base_goal : Syntax := induction_base_goal (SName "Nat") le_motive.
4364Eval base_goal.
4365
4366-- Step case goal: ∀k. P(k) → P(Succ k)
4367Definition step_goal : Syntax := induction_step_goal (SName "Nat") le_motive (Succ Zero).
4368Eval step_goal.
4369
4370-- Bool Induction
4371-- Bool has 2 constructors: true, false
4372
4373-- How many constructors does Bool have?
4374Definition bool_cases : Nat := induction_num_cases (SName "Bool").
4375Eval bool_cases.
4376
4377-- Check the Bool type
4378Check Bool.
4379Check true.
4380Check false.
4381
4382-- Building a Complete Proof
4383-- Let's build an induction proof manually using the kernel.
4384
4385-- Base case: Le Zero Zero (auto can solve this)
4386Definition base_proof : Derivation :=
4387 try_auto (SApp (SApp (SName "Le") (SName "Zero")) (SName "Zero")).
4388Definition base_result : Syntax := concludes base_proof.
4389Eval base_result.
4390
4391-- Step case: use axiom for now (step needs IH)
4392Definition step_proof : Derivation := DAxiom step_goal.
4393
4394-- Combine into full induction proof
4395Definition full_proof : Derivation :=
4396 try_induction (SName "Nat") le_motive (DCase base_proof (DCase step_proof DCaseEnd)).
4397Definition full_result : Syntax := concludes full_proof.
4398Eval full_result.
4399
4400-- Error Handling
4401-- Wrong number of cases should error
4402
4403Definition motive2 : Syntax := SLam (SName "Nat") (SName "True").
4404Definition single_case : Derivation := DAxiom (SName "True").
4405
4406-- Only 1 case for 2-constructor Nat = error
4407Definition bad_proof : Derivation :=
4408 try_induction (SName "Nat") motive2 (DCase single_case DCaseEnd).
4409Definition bad_result : Syntax := concludes bad_proof.
4410Eval bad_result.
4411
4412-- Non-Inductive Types
4413-- Int is not an inductive type
4414
4415Definition int_cases : Nat := induction_num_cases (SName "Int").
4416Eval int_cases.
4417
4418-- Summary
4419-- The induction infrastructure provides:
4420--
4421-- 1. induction_num_cases: Count constructors for a type
4422-- 2. induction_base_goal: Generate base case goal
4423-- 3. induction_step_goal: Generate step case goal
4424-- 4. try_induction: Build DElim from cases
4425--
4426-- This enables generic structural induction on:
4427-- - Nat (Zero, Succ)
4428-- - Bool (true, false)
4429-- - User-defined inductives
4430--
4431-- Bullet-point syntax in literate mode:
4432-- Proof:
4433-- induction n.
4434-- - auto. # Base case
4435-- - auto. # Step case
4436"###;
4437
4438const MATH_HINTS: &str = r###"-- The Hint Database: Teaching auto New Tricks
4439-- Register theorems as hints so auto can use them!
4440--
4441-- The hint system allows you to:
4442-- 1. Prove a theorem once
4443-- 2. Register it with "Attribute: hint."
4444-- 3. Auto will try to use it when other tactics fail
4445
4446-- A Basic Hint
4447
4448-- First, let's define a simple property
4449Definition trivial_true : Syntax := SName "True".
4450
4451-- Prove it (trivially)
4452Definition trivial_proof : Derivation := try_auto trivial_true.
4453
4454-- Verify the proof
4455Eval concludes trivial_proof.
4456
4457-- How Hints Work
4458-- When you write:
4459--
4460-- ## Theorem: my_lemma
4461-- Statement: <some_statement>
4462-- Proof: auto.
4463-- Attribute: hint.
4464--
4465-- The system:
4466-- 1. Proves the theorem
4467-- 2. Registers it in the hint database
4468-- 3. When auto runs later, it checks if any hint matches the goal
4469
4470-- Hint-Aware auto
4471-- Auto tries tactics in this order:
4472-- 1. Trivial (True/False)
4473-- 2. simp (simplification)
4474-- 3. ring (polynomial arithmetic)
4475-- 4. cc (congruence closure)
4476-- 5. omega (integer arithmetic)
4477-- 6. lia (linear arithmetic)
4478-- 7. HINTS (registered theorems) <-- NEW!
4479
4480-- Literate Syntax for Hints
4481-- In literate mode, you can write:
4482--
4483-- ## Theorem: plus_zero_right
4484-- Statement: For all (n: Nat), n + 0 = n.
4485-- Proof:
4486-- induction n.
4487-- - auto.
4488-- - auto.
4489-- Attribute: hint.
4490--
4491-- This registers plus_zero_right as a hint!
4492-- Now any proof with goal "n + 0 = n" can use auto.
4493
4494-- Checking Hints
4495-- You can inspect the hint database via the context.
4496-- Hints are stored as theorem names.
4497
4498Check try_auto.
4499
4500-- Summary
4501-- The hint system extends auto with learned knowledge:
4502--
4503-- 1. Prove theorems normally
4504-- 2. Add "Attribute: hint." to register them
4505-- 3. Auto will try hints when built-in tactics fail
4506--
4507-- This creates a virtuous cycle:
4508-- Prove lemmas → Register as hints → Prove harder theorems
4509"###;
4510
4511const MATH_INVERSION: &str = r###"-- Inversion: The Scalpel
4512-- Derives contradictions by running constructors backwards.
4513--
4514-- If you claim something impossible (like Eq Nat 3 0),
4515-- inversion proves False by showing no constructor can build it.
4516
4517-- Kernel Infrastructure
4518-- These are the building blocks for inversion.
4519
4520-- Check that inversion helpers exist
4521Check try_inversion.
4522Check DInversion.
4523
4524-- Discriminate: Different Constructors
4525-- The Eq type has only one constructor: refl
4526-- refl : Π(A:Type). Π(x:A). Eq A x x
4527--
4528-- refl requires BOTH arguments to be the same!
4529
4530-- Build hypothesis: Eq Nat 3 0 (impossible!)
4531Definition three : Syntax :=
4532 SApp (SName "Succ") (SApp (SName "Succ") (SApp (SName "Succ") (SName "Zero"))).
4533
4534Definition eq_three_zero : Syntax :=
4535 SApp (SApp (SApp (SName "Eq") (SName "Nat")) three) (SName "Zero").
4536
4537-- Try inversion: can refl build Eq Nat 3 0?
4538-- No! refl needs same args, but 3 ≠ 0
4539Definition discriminate_proof : Derivation := try_inversion eq_three_zero.
4540Definition discriminate_result : Syntax := concludes discriminate_proof.
4541Eval discriminate_result.
4542
4543-- Reflexive: The Constructor Can Match
4544-- Eq Nat Zero Zero CAN be built by refl Zero
4545-- So inversion should NOT derive False (returns error)
4546
4547Definition eq_zero_zero : Syntax :=
4548 SApp (SApp (SApp (SName "Eq") (SName "Nat")) (SName "Zero")) (SName "Zero").
4549
4550Definition reflexive_proof : Derivation := try_inversion eq_zero_zero.
4551Definition reflexive_result : Syntax := concludes reflexive_proof.
4552Eval reflexive_result.
4553
4554-- Empty Inductive: False
4555-- False has NO constructors at all.
4556-- Anything of type False is automatically contradictory.
4557
4558Definition false_hyp : Syntax := SName "False".
4559Definition false_proof : Derivation := try_inversion false_hyp.
4560Definition false_result : Syntax := concludes false_proof.
4561Eval false_result.
4562
4563-- Bool Discriminate: true ≠ false
4564-- Eq Bool true false requires refl to make true = false
4565-- But true and false are different constructors!
4566
4567Definition eq_true_false : Syntax :=
4568 SApp (SApp (SApp (SName "Eq") (SName "Bool")) (SName "true")) (SName "false").
4569
4570Definition bool_proof : Derivation := try_inversion eq_true_false.
4571Definition bool_result : Syntax := concludes bool_proof.
4572Eval bool_result.
4573
4574-- Non-Inductive: An Error
4575-- Inversion only works on inductive types.
4576-- Variables or unknown types produce errors.
4577
4578Definition var_hyp : Syntax := SVar 0.
4579Definition var_proof : Derivation := try_inversion var_hyp.
4580Definition var_result : Syntax := concludes var_proof.
4581Eval var_result.
4582
4583-- Summary
4584-- The inversion tactic:
4585--
4586-- 1. Extracts the inductive type from the hypothesis
4587-- 2. Checks if ANY constructor could produce the given args
4588-- 3. If no constructor matches → proves False
4589-- 4. If some constructor matches → returns error
4590--
4591-- Key insight: Inversion is the INVERSE of introduction.
4592-- Introduction builds terms; inversion checks if building is possible.
4593--
4594-- Common uses:
4595-- - Discriminate different constructors (Eq 3 0 → False)
4596-- - Empty inductives (False → False)
4597-- - Proof by contradiction
4598"###;
4599
4600const MATH_OPERATOR: &str = r###"-- The Operator: Manual Control Tactics
4601-- When auto fails, you need precision tools.
4602--
4603-- rewrite - The Sniper: targeted substitution
4604-- destruct - The Fork: case analysis without IH
4605-- apply - The Arrow: backward chaining
4606
4607-- Kernel Infrastructure
4608
4609Check try_rewrite.
4610Check try_rewrite_rev.
4611Check try_destruct.
4612Check try_apply.
4613Check DRewrite.
4614Check DDestruct.
4615Check DApply.
4616
4617-- rewrite: The Sniper
4618-- Given a proof of Eq A x y and a goal containing x,
4619-- rewrite replaces x with y (or vice versa with rewrite_rev).
4620--
4621-- Use case: When you have an equality lemma and need to
4622-- substitute one term for another.
4623
4624-- Example: Given Eq Nat x y, transform goal P(x) to P(y)
4625
4626-- Build equality hypothesis: Eq Nat (SVar 0) (SVar 1)
4627-- This represents "x = y" where x is var 0, y is var 1
4628Definition eq_type : Syntax :=
4629 SApp (SApp (SApp (SName "Eq") (SName "Nat")) (SVar 0)) (SVar 1).
4630
4631-- Create a proof of this equality (as axiom for demo)
4632Definition eq_proof : Derivation := DAxiom eq_type.
4633
4634-- Goal: P(x) = P(SVar 0)
4635Definition goal_px : Syntax := SApp (SName "P") (SVar 0).
4636
4637-- Rewrite: Replace x with y to get P(y)
4638Definition rewritten : Derivation := try_rewrite eq_proof goal_px.
4639Eval (concludes rewritten).
4640
4641-- Reverse rewrite: Given same equality, replace y with x
4642Definition goal_py : Syntax := SApp (SName "P") (SVar 1).
4643Definition rev_rewritten : Derivation := try_rewrite_rev eq_proof goal_py.
4644Eval (concludes rev_rewritten).
4645
4646-- destruct: The Fork
4647-- Case analysis WITHOUT induction hypotheses.
4648--
4649-- For Bool: generates true and false cases
4650-- For Nat: generates Zero case and "forall k. P(Succ k)"
4651-- NOT "forall k. P(k) -> P(Succ k)" (that's induction)
4652--
4653-- Use case: When you need to split on cases but don't need
4654-- the induction hypothesis (enums, finite types).
4655
4656-- Motive: λb:Bool. P(b)
4657Definition bool_motive : Syntax :=
4658 SLam (SName "Bool") (SApp (SName "P") (SVar 0)).
4659
4660-- Case proofs: P(true) and P(false) as axioms
4661Definition case_true : Derivation := DAxiom (SApp (SName "P") (SName "true")).
4662Definition case_false : Derivation := DAxiom (SApp (SName "P") (SName "false")).
4663
4664-- Build case list
4665Definition bool_cases : Derivation := DCase case_true (DCase case_false DCaseEnd).
4666
4667-- Destruct Bool
4668Definition bool_destruct : Derivation :=
4669 try_destruct (SName "Bool") bool_motive bool_cases.
4670Eval (concludes bool_destruct).
4671
4672-- apply: The Arrow
4673-- Manual backward chaining.
4674--
4675-- Given hypothesis H : P → Q and goal Q,
4676-- apply H transforms the goal to P.
4677--
4678-- Given hypothesis H : ∀x. P(x) and goal P(3),
4679-- apply H instantiates the forall.
4680--
4681-- Use case: When auto can't figure out which lemma to use.
4682
4683-- Implication example: H : P → Q, goal: Q
4684Definition impl_type : Syntax := SPi (SName "P") (SName "Q").
4685Definition impl_proof : Derivation := DAxiom impl_type.
4686Definition goal_q : Syntax := SName "Q".
4687
4688-- Apply H to goal Q → new goal P
4689Definition applied_impl : Derivation :=
4690 try_apply (SName "H") impl_proof goal_q.
4691Eval (concludes applied_impl).
4692
4693-- Forall example: H : ∀x:Nat. P(x), goal: P(3)
4694Definition forall_type : Syntax :=
4695 SApp (SName "Forall")
4696 (SLam (SName "Nat") (SApp (SName "P") (SVar 0))).
4697
4698Definition forall_proof : Derivation := DAxiom forall_type.
4699
4700Definition three : Syntax :=
4701 SApp (SName "Succ") (SApp (SName "Succ") (SApp (SName "Succ") (SName "Zero"))).
4702
4703Definition goal_p3 : Syntax := SApp (SName "P") three.
4704
4705-- Apply forall to goal P(3)
4706Definition applied_forall : Derivation :=
4707 try_apply (SName "lemma") forall_proof goal_p3.
4708Eval (concludes applied_forall).
4709
4710-- Summary
4711-- The Operator tactics give you manual control:
4712--
4713-- rewrite eq_proof goal
4714-- - Given Eq A x y, replaces x with y in goal
4715-- - Surgical precision when you have the right equality
4716--
4717-- rewrite_rev eq_proof goal
4718-- - Same but replaces y with x (reverse direction)
4719--
4720-- destruct type motive cases
4721-- - Case analysis without induction hypothesis
4722-- - Simpler than induction for non-recursive proofs
4723--
4724-- apply hyp_name hyp_proof goal
4725-- - Backward chaining: uses hypothesis to transform goal
4726-- - Works with implications (P → Q) and foralls (∀x. P(x))
4727--
4728-- When to use:
4729-- - auto fails on complex goals
4730-- - Need specific control over proof steps
4731-- - Working with explicit equality proofs
4732"###;
4733
4734const MATH_TACTICALS: &str = r###"-- The Strategist: Programmable Proofs
4735--
4736-- Phase 10: Higher-Order Tactic Combinators
4737--
4738-- Tacticals turn proofs into programs. Instead of:
4739-- induction n.
4740-- auto.
4741-- auto.
4742-- auto.
4743--
4744-- Write:
4745-- induction n; repeat auto.
4746--
4747-- One line. Infinite power.
4748
4749-- tact_try: The Safety Net
4750-- tact_try : (Syntax -> Derivation) -> Syntax -> Derivation
4751--
4752-- Attempts a tactic but never fails. If the tactic fails,
4753-- returns the goal unchanged (identity).
4754--
4755-- Use case: "Try to simplify, but don't crash if you can't"
4756
4757-- Reflexive goal - try_refl succeeds
4758Definition goal_refl : Syntax :=
4759 SApp (SApp (SApp (SName "Eq") (SName "Nat"))
4760 (SName "Zero")) (SName "Zero").
4761
4762-- Non-reflexive goal - try_refl would fail
4763Definition goal_hard : Syntax :=
4764 SApp (SApp (SApp (SName "Eq") (SName "Nat"))
4765 (SName "Zero")) (SApp (SName "Succ") (SName "Zero")).
4766
4767-- tact_try always succeeds
4768Definition d_try_easy : Derivation := tact_try try_refl goal_refl.
4769Definition d_try_hard : Derivation := tact_try try_refl goal_hard.
4770
4771-- Easy goal: proves it
4772Eval (concludes d_try_easy).
4773
4774-- Hard goal: returns unchanged (identity) - NOT Error
4775Eval (concludes d_try_hard).
4776
4777-- tact_repeat: The Loop
4778-- tact_repeat : (Syntax -> Derivation) -> Syntax -> Derivation
4779--
4780-- Applies a tactic repeatedly until it fails.
4781-- Returns after the last successful application.
4782--
4783-- Use case: "Keep simplifying until you can't simplify anymore"
4784
4785-- Identity tactic (always succeeds, does nothing)
4786Definition tact_id : Syntax -> Derivation := fun g : Syntax => DAxiom g.
4787
4788-- tact_repeat stops when no progress is made
4789Definition d_repeat : Derivation := tact_repeat tact_id goal_refl.
4790Eval (concludes d_repeat).
4791
4792-- tact_then: The Sequencer (;)
4793-- tact_then : (Syntax -> Derivation) -> (Syntax -> Derivation) -> Syntax -> Derivation
4794--
4795-- Sequence two tactics: apply first, then apply second to result.
4796-- If either fails, the whole thing fails.
4797--
4798-- Use case: "First simplify, then prove by reflexivity"
4799
4800-- Sequence: try (always succeeds) ; refl
4801Definition tact_combo : Syntax -> Derivation :=
4802 tact_then (tact_try tact_fail) try_refl.
4803
4804Definition d_combo : Derivation := tact_combo goal_refl.
4805Eval (concludes d_combo).
4806
4807-- tact_first: The Menu
4808-- tact_first : TTactics -> Syntax -> Derivation
4809--
4810-- Try tactics from a list until one succeeds.
4811-- Returns Error if all fail.
4812--
4813-- TTactics = TList of (Syntax -> Derivation)
4814-- TacCons and TacNil are convenience wrappers
4815
4816-- Build a tactic list: [tact_fail, tact_fail, try_refl]
4817Definition my_tactics : TTactics :=
4818 TacCons tact_fail
4819 (TacCons tact_fail
4820 (TacCons try_refl TacNil)).
4821
4822-- First will skip the failures and use try_refl
4823Definition d_first : Derivation := tact_first my_tactics goal_refl.
4824Eval (concludes d_first).
4825
4826-- All fail case
4827Definition fail_tactics : TTactics := TacCons tact_fail TacNil.
4828Definition d_all_fail : Derivation := tact_first fail_tactics goal_refl.
4829Eval (concludes d_all_fail).
4830
4831-- tact_solve: The Enforcer
4832-- tact_solve : (Syntax -> Derivation) -> Syntax -> Derivation
4833--
4834-- Tactic MUST completely solve the goal.
4835-- If the tactic returns Error, fails.
4836-- If the tactic succeeds, returns its proof.
4837--
4838-- Use case: "Only use this tactic if it finishes the job"
4839
4840-- try_refl completely solves reflexive goals
4841Definition d_solve : Derivation := tact_solve try_refl goal_refl.
4842Eval (concludes d_solve).
4843
4844-- The Nuclear Code
4845-- Combine all tacticals into the ultimate tactic:
4846-- "Try everything we know how to do"
4847
4848Definition nuclear : Syntax -> Derivation :=
4849 tact_first (TacCons try_refl
4850 (TacCons (tact_try try_simp)
4851 (TacCons try_lia
4852 (TacCons try_auto TacNil)))).
4853
4854-- Test it on our reflexive goal
4855Definition d_nuclear : Derivation := nuclear goal_refl.
4856Eval (concludes d_nuclear).
4857
4858-- Combining Tacticals
4859-- Real power: nest them!
4860
4861-- repeat (first [refl, simp]) - keep trying until nothing works
4862Definition solve_trivial : Syntax -> Derivation :=
4863 tact_repeat (tact_first (TacCons try_refl
4864 (TacCons (tact_try try_simp) TacNil))).
4865
4866Definition d_trivial : Derivation := solve_trivial goal_refl.
4867Eval (concludes d_trivial).
4868
4869-- Summary
4870-- tact_try t - Try t, never fail (identity on failure)
4871-- tact_repeat t - Apply t until failure
4872-- tact_then t1 t2 - Sequence: t1 then t2
4873-- tact_first ts - Try list of tactics until one works
4874-- tact_solve t - t must completely prove the goal
4875--
4876-- With tact_orelse from Phase 98:
4877-- tact_orelse t1 t2 - Try t1, if fails try t2
4878-- tact_fail - Always fail
4879--
4880-- These form a complete tactical language for
4881-- programming proofs. God Mode achieved.
4882"###;
4883
4884pub const CODE_WEB_COUNTER: &str = r##"# Counter — a LOGOS page
4895
4896A page owns a URL and mounts itself: no `## Main`, no `Mount`. One click is one TURN —
4897the action runs, the page repaints once.
4898
4899## Page /
4900
4901State:
4902 Let count be 0.
4903
4904Actions:
4905 To bump:
4906 Set count to count + 1.
4907
4908 To reset:
4909 Set count to 0.
4910
4911View:
4912 <h1 id="count">Count: {count}</h1>
4913 <button id="bump" on-click={bump}>+1</button>
4914 <button id="reset" on-click={reset}>reset</button>
4915
4916## Test: each click is one turn
4917
4918Click "#bump".
4919Click "#bump".
4920Expect that the text of "#count" is equal to "Count: 2".
4921Click "#reset".
4922Expect that the text of "#count" is equal to "Count: 0".
4923"##;
4924
4925pub const CODE_WEB_TODO: &str = r##"# To-Do — add, finish, remove
4928
4929`State:` holds an ordinary list of records. Each row is keyed by its id, so removing
4930one leaves the others' elements where they are. `left` is derived: it recomputes
4931whenever `todos` changes.
4932
4933## A Todo has:
4934 an id, which is Int.
4935 a text, which is Text.
4936 a done, which is Bool.
4937
4938## To openCount (todos: Seq of Todo) -> Int:
4939 Let mutable n be 0.
4940 Repeat for t in todos:
4941 If t's done is equal to false:
4942 Set n to n + 1.
4943 Return n.
4944
4945## Page /
4946
4947State:
4948 Let todos be a new Seq of Todo.
4949 Let draft be "".
4950 Let nextId be 1.
4951 Let left always be openCount(todos).
4952
4953Actions:
4954 To add:
4955 If draft is equal to "":
4956 Return.
4957 Push (a new Todo with id nextId and text draft and done false) to todos.
4958 Set nextId to nextId + 1.
4959 Set draft to "".
4960
4961 To toggle (id: Int):
4962 Let mutable next be a new Seq of Todo.
4963 Repeat for t in todos:
4964 If t's id is equal to id:
4965 Push (a new Todo with id t's id and text t's text and done (not t's done)) to next.
4966 Otherwise:
4967 Push t to next.
4968 Set todos to next.
4969
4970 To remove (id: Int):
4971 Let mutable kept be a new Seq of Todo.
4972 Repeat for t in todos:
4973 If t's id is not equal to id:
4974 Push t to kept.
4975 Set todos to kept.
4976
4977View:
4978 <h1>To-Do</h1>
4979 <form id="add" on-submit.prevent={add}>
4980 <input id="draft" type="text" aria-label="New task" bind={draft} placeholder="What needs doing?">
4981 <button type="submit">Add</button>
4982 </form>
4983 <ul>
4984 {for each t in todos, keyed by t's id:}
4985 <li class="todo" class:done={t's done}>
4986 <button id="toggle-{t's id}" on-click={toggle(t's id)}>{t's text}</button>
4987 <button id="remove-{t's id}" on-click={remove(t's id)}>remove</button>
4988 </li>
4989 {else:}
4990 <li class="empty">Nothing to do.</li>
4991 {end}
4992 </ul>
4993 <p id="left">{left} left</p>
4994
4995Style:
4996 .done button:first-child { text-decoration: line-through; opacity: .6; }
4997
4998## Test: todos are added, finished and removed
4999
5000Type "milk" into "#draft".
5001Submit "#add".
5002Type "bread" into "#draft".
5003Submit "#add".
5004Expect that the count of ".todo" is equal to 2.
5005Click "#toggle-1".
5006Expect that the text of "#left" is equal to "1 left".
5007Click "#remove-1".
5008Expect that the count of ".todo" is equal to 1.
5009Expect that the text of "#toggle-2" is equal to "bread".
5010"##;
5011
5012pub const CODE_WEB_FORM: &str = r##"# Form — binding, validation and scoped style
5015
5016`bind={name}` binds an input to a field both ways. `forms.lg` collects what was
5017wrong with a submission, one message per field. `Style:` is scoped to this page, so
5018`.error` cannot collide with anything else on the site.
5019
5020## Page /
5021
5022State:
5023 Let name be "".
5024 Let password be "".
5025 Let errors be a new Seq of FieldError.
5026 Let sent be false.
5027
5028Actions:
5029 To send:
5030 Let mutable e be noErrors().
5031 Set e to checkRequired(e, "name", name).
5032 Set e to checkMinLength(e, "password", password, 8).
5033 Set errors to e.
5034 Set sent to isValid(e).
5035
5036View:
5037 <form id="signup" on-submit.prevent={send}>
5038 <label>Name <input id="name" type="text" bind={name}></label>
5039 <p class="error" id="name-error">{errorFor(errors, "name")}</p>
5040 <label>Password <input id="password" type="password" bind={password}></label>
5041 <p class="error" id="password-error">{errorFor(errors, "password")}</p>
5042 <button type="submit">Sign up</button>
5043 </form>
5044 {if sent:}<p class="greet" id="greet">Welcome, {name}!</p>{end}
5045
5046Style:
5047 .error { color: #b3261e; }
5048 .greet { color: #cc785c; font-weight: 600; }
5049
5050## Test: an empty form names each problem
5051
5052Submit "#signup".
5053Expect that the text of "#name-error" is equal to "This is required.".
5054Expect that the text of "#password-error" is equal to "Use at least 8 characters.".
5055
5056## Test: a complete form is welcomed
5057
5058Type "Ada" into "#name".
5059Type "correct horse" into "#password".
5060Submit "#signup".
5061Expect that the text of "#greet" is equal to "Welcome, Ada!".
5062"##;
5063
5064pub const CODE_WEB_SITE: &str = include_str!("examples/website.logos");
5067
5068#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5070pub enum Mode {
5071 Logic,
5072 Code,
5073 Math,
5074 Hardware,
5075}
5076
5077#[derive(Debug, Clone)]
5080pub enum Expected {
5081 Proves,
5083 DerivationNotCertified,
5088 CompilesToFol(&'static [&'static str]),
5093 OutputContains(&'static [&'static str]),
5097 OutputExact(&'static str),
5101 NativeOnlyCompiles,
5104 WebPage,
5108 KernelAllStatementsOk,
5110 KernelAdmitsAt(&'static str),
5113 TheoryAllVerified,
5116 SvaSynthesizes,
5118 SignalPlanSynthesizes,
5120 RtlProven,
5122 RefutesWithCounterexample,
5124 RegisterAllocFits,
5126 SpillsRequired,
5128 UnsatCertified,
5130}
5131
5132pub struct ExampleSpec {
5135 pub vfs_path: &'static str,
5136 pub mode: Mode,
5137 pub source: &'static str,
5138 pub expected: Expected,
5139}
5140
5141pub const ALL_LOGIC_EXAMPLES: &[ExampleSpec] = &[
5143 ExampleSpec {
5144 vfs_path: "/examples/logic/simple-sentences.logic",
5145 mode: Mode::Logic,
5146 source: LOGIC_SIMPLE,
5147 expected: Expected::CompilesToFol(&["Sleep", "Bark", "Loudly", "Love", "Fail"]),
5148 },
5149 ExampleSpec {
5150 vfs_path: "/examples/logic/quantifiers.logic",
5151 mode: Mode::Logic,
5152 source: LOGIC_QUANTIFIERS,
5153 expected: Expected::CompilesToFol(&["Student", "Book", "Professor", "Exam", "Cat"]),
5154 },
5155 ExampleSpec {
5156 vfs_path: "/examples/logic/tense-aspect.logic",
5157 mode: Mode::Logic,
5158 source: LOGIC_TENSE,
5159 expected: Expected::CompilesToFol(&["Run", "Eat", "Arrive", "Sleep", "Work"]),
5160 },
5161 ExampleSpec {
5162 vfs_path: "/examples/logic/garden-path.logic",
5163 mode: Mode::Logic,
5164 source: LOGIC_GARDEN_PATH,
5165 expected: Expected::CompilesToFol(&["Horse", "Race", "Fall"]),
5166 },
5167 ExampleSpec {
5168 vfs_path: "/examples/logic/events-adverbs.logic",
5169 mode: Mode::Logic,
5170 source: LOGIC_EVENTS_ADVERBS,
5171 expected: Expected::CompilesToFol(&["Quickly", "Carefully", "Loudly"]),
5172 },
5173 ExampleSpec {
5174 vfs_path: "/examples/logic/negation-polarity.logic",
5175 mode: Mode::Logic,
5176 source: LOGIC_NPI,
5177 expected: Expected::CompilesToFol(&["Dog", "Bark", "Error"]),
5178 },
5179 ExampleSpec {
5180 vfs_path: "/examples/logic/plurals-collectives.logic",
5181 mode: Mode::Logic,
5182 source: LOGIC_PLURALS,
5183 expected: Expected::CompilesToFol(&["σBoy", "Gather", "Love"]),
5184 },
5185 ExampleSpec {
5186 vfs_path: "/examples/logic/comparatives.logic",
5187 mode: Mode::Logic,
5188 source: LOGIC_COMPARATIVES,
5189 expected: Expected::CompilesToFol(&["Taller", "2 inches", "Higher"]),
5190 },
5191 ExampleSpec {
5192 vfs_path: "/examples/logic/modality.logic",
5193 mode: Mode::Logic,
5194 source: LOGIC_MODALITY,
5195 expected: Expected::CompilesToFol(&["Student", "FEW", "Bird"]),
5196 },
5197 ExampleSpec {
5198 vfs_path: "/examples/logic/donkey-anaphora.logic",
5199 mode: Mode::Logic,
5200 source: LOGIC_DONKEY,
5201 expected: Expected::CompilesToFol(&["Farmer", "Donkey", "Beat"]),
5202 },
5203 ExampleSpec {
5204 vfs_path: "/examples/logic/intensionality.logic",
5205 mode: Mode::Logic,
5206 source: LOGIC_INTENSIONALITY,
5207 expected: Expected::CompilesToFol(&["Seek", "^Unicorn", "Believe"]),
5208 },
5209 ExampleSpec {
5210 vfs_path: "/examples/logic/counterfactuals.logic",
5211 mode: Mode::Logic,
5212 source: LOGIC_COUNTERFACTUALS,
5213 expected: Expected::CompilesToFol(&["□→", "Study", "Glass"]),
5214 },
5215 ExampleSpec {
5216 vfs_path: "/examples/logic/prover-demo.logic",
5217 mode: Mode::Logic,
5218 source: LOGIC_PROVER,
5219 expected: Expected::Proves,
5220 },
5221 ExampleSpec {
5222 vfs_path: "/examples/logic/simon.logic",
5223 mode: Mode::Logic,
5224 source: LOGIC_SIMON,
5225 expected: Expected::Proves,
5226 },
5227 ExampleSpec {
5228 vfs_path: "/examples/logic/syllogism.logic",
5229 mode: Mode::Logic,
5230 source: LOGIC_SYLLOGISM,
5231 expected: Expected::Proves,
5232 },
5233 ExampleSpec {
5234 vfs_path: "/examples/logic/disjunctive-syllogism.logic",
5235 mode: Mode::Logic,
5236 source: LOGIC_DISJUNCTIVE,
5237 expected: Expected::Proves,
5238 },
5239 ExampleSpec {
5240 vfs_path: "/examples/logic/modus-tollens.logic",
5241 mode: Mode::Logic,
5242 source: LOGIC_MODUS_TOLLENS,
5243 expected: Expected::Proves,
5244 },
5245 ExampleSpec {
5246 vfs_path: "/examples/logic/leibniz-identity.logic",
5247 mode: Mode::Logic,
5248 source: LOGIC_LEIBNIZ,
5249 expected: Expected::Proves,
5250 },
5251 ExampleSpec {
5252 vfs_path: "/examples/logic/neither-nor.logic",
5253 mode: Mode::Logic,
5254 source: LOGIC_NEITHER_NOR,
5255 expected: Expected::Proves,
5256 },
5257 ExampleSpec {
5258 vfs_path: "/examples/logic/equality-rewrite.logic",
5259 mode: Mode::Logic,
5260 source: LOGIC_EQUALITY_REWRITE,
5261 expected: Expected::Proves,
5262 },
5263 ExampleSpec {
5264 vfs_path: "/examples/logic/presupposition.logic",
5265 mode: Mode::Logic,
5266 source: LOGIC_PRESUPPOSITION,
5267 expected: Expected::Proves,
5268 },
5269 ExampleSpec {
5270 vfs_path: "/examples/logic/grid-starter.logic",
5271 mode: Mode::Logic,
5272 source: LOGIC_GRID_STARTER,
5273 expected: Expected::Proves,
5274 },
5275 ExampleSpec {
5276 vfs_path: "/examples/logic/grid-question.logic",
5277 mode: Mode::Logic,
5278 source: LOGIC_GRID_QUESTION,
5279 expected: Expected::Proves,
5280 },
5281 ExampleSpec {
5282 vfs_path: "/examples/logic/tactic-script.logic",
5283 mode: Mode::Logic,
5284 source: LOGIC_TACTIC_SCRIPT,
5285 expected: Expected::Proves,
5286 },
5287 ExampleSpec {
5288 vfs_path: "/examples/logic/barber-paradox.logic",
5289 mode: Mode::Logic,
5290 source: LOGIC_BARBER,
5291 expected: Expected::DerivationNotCertified,
5292 },
5293];
5294
5295pub const ALL_CODE_EXAMPLES: &[ExampleSpec] = &[
5298 ExampleSpec { vfs_path: "/examples/code/hello-world.logos", mode: Mode::Code, source: CODE_HELLO, expected: Expected::OutputExact("Hello, LOGOS!\n10 + 20 = 30") },
5299 ExampleSpec { vfs_path: "/examples/code/basics/fizzbuzz.logos", mode: Mode::Code, source: CODE_FIZZBUZZ, expected: Expected::OutputExact("1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n16\n17\nFizz\n19\nBuzz") },
5300 ExampleSpec { vfs_path: "/examples/code/basics/syntax-flavors.logos", mode: Mode::Code, source: CODE_SYNTAX_FLAVORS, expected: Expected::OutputExact("bound with the = sign\nLet and = both bind values: 20\nOtherwise If flavor: FizzBuzz\nelif flavor: FizzBuzz\nmut and mutable both work: 12\nsymbols and English agree: 15 is divisible by 5") },
5301 ExampleSpec { vfs_path: "/examples/code/basics/interpolation.logos", mode: Mode::Code, source: CODE_INTERPOLATION, expected: Expected::OutputExact("Ada is 36.\nNext year she will be 37.\npi to two places: 3.14\n| socks|\n|socks |\n| socks |\nthat will be $19.99\ndebugging: x=42\nliteral braces: {not a hole}") },
5302 ExampleSpec { vfs_path: "/examples/code/basics/numbers.logos", mode: Mode::Code, source: CODE_NUMBERS, expected: Expected::OutputExact("2 to the 100th = 1267650600228229401496703205376\na third to 4 places: 0.3333\n0.1 + 0.2 is approximately 0.3 (floats drift)\nwith Decimal it is exactly 0.3") },
5303 ExampleSpec { vfs_path: "/examples/code/strings/text-basics.logos", mode: Mode::Code, source: CODE_TEXT_BASICS, expected: Expected::OutputExact("LOGOS has 5 letters.\nIt starts with L.\nThere is GO in LOGOS.\nHello, world!\nReversed: SOGOL") },
5304 ExampleSpec { vfs_path: "/examples/code/strings/formatting.logos", mode: Mode::Code, source: CODE_FORMATTING, expected: Expected::OutputExact("item cost\napples 1.25\nbread 3.5\ntotal: $4.75") },
5305 ExampleSpec { vfs_path: "/examples/code/strings/find-and-count.logos", mode: Mode::Code, source: CODE_FIND_AND_COUNT, expected: Expected::OutputExact("the letter t appears 5 times\nthe sentence has 6 words") },
5306 ExampleSpec { vfs_path: "/examples/code/collections/slicing.logos", mode: Mode::Code, source: CODE_SLICING, expected: Expected::OutputExact("middle three: [70, 85, 90]\nedited copy: [100, 70, 85, 90, 60]\noriginal untouched: [55, 70, 85, 90, 60]") },
5307 ExampleSpec { vfs_path: "/examples/code/collections/tuples.logos", mode: Mode::Code, source: CODE_TUPLES, expected: Expected::OutputExact("x = 10, y = 20\nBerlin has 3600000 people\nthe tuple has 3 slots\nBerlin is the capital of Germany\nParis is the capital of France") },
5308 ExampleSpec { vfs_path: "/examples/code/collections/filter-transform.logos", mode: Mode::Code, source: CODE_FILTER_TRANSFORM, expected: Expected::OutputExact("evens: [2, 4, 6]\ntheir squares: [4, 16, 36]\nsum of squares: 56") },
5309 ExampleSpec { vfs_path: "/examples/code/time-and-money/dates.logos", mode: Mode::Code, source: CODE_DATES, expected: Expected::OutputExact("liftoff day: 2026-05-20\nprep starts: 2026-05-17\nreview lands: 2026-07-20\nsprint length: 17 days\ndaily standup: 09:30:00\nkickoff moment: 2026-05-20 16:00\n9am is before noon") },
5310 ExampleSpec { vfs_path: "/examples/code/time-and-money/money.logos", mode: Mode::Code, source: CODE_MONEY, expected: Expected::OutputExact("subtotal: $7.75\ntwo rounds: $15.50\nwith tip: $17.05\n0.1 + 0.2 = 0.3 exactly (no float drift)") },
5311 ExampleSpec { vfs_path: "/examples/code/algorithms/fibonacci.logos", mode: Mode::Code, source: CODE_FIBONACCI, expected: Expected::OutputExact("The first 10 Fibonacci numbers:\n1\n1\n2\n3\n5\n8\n13\n21\n34\n55") },
5312 ExampleSpec { vfs_path: "/examples/code/algorithms/primes.logos", mode: Mode::Code, source: CODE_PRIME, expected: Expected::OutputExact("Checking 2 through 30:\n2 is prime\n3 is prime\n5 is prime\n7 is prime\n11 is prime\n13 is prime\n17 is prime\n19 is prime\n23 is prime\n29 is prime") },
5313 ExampleSpec { vfs_path: "/examples/code/algorithms/bubble-sort.logos", mode: Mode::Code, source: CODE_BUBBLE_SORT, expected: Expected::OutputExact("Before: [64, 34, 25, 12, 22, 11, 90]\nAfter: [11, 12, 22, 25, 34, 64, 90]") },
5314 ExampleSpec { vfs_path: "/examples/code/algorithms/sieve.logos", mode: Mode::Code, source: CODE_SIEVE, expected: Expected::OutputExact("25 primes at or below 100\nthe largest is 97") },
5315 ExampleSpec { vfs_path: "/examples/code/algorithms/binary-search.logos", mode: Mode::Code, source: CODE_BINARY_SEARCH, expected: Expected::OutputExact("found 42 at position 5\n50 is not present") },
5316 ExampleSpec { vfs_path: "/examples/code/algorithms/merge-sort.logos", mode: Mode::Code, source: CODE_MERGE_SORT, expected: Expected::OutputExact("before: [38, 27, 43, 3, 9, 82, 10]\nafter: [3, 9, 10, 27, 38, 43, 82]") },
5317 ExampleSpec { vfs_path: "/examples/code/algorithms/gcd.logos", mode: Mode::Code, source: CODE_GCD, expected: Expected::OutputExact("gcd(48, 18) = 6\ngcd(17, 5) = 1\ngcd(100, 75) = 25") },
5318 ExampleSpec { vfs_path: "/examples/code/algorithms/two-sum.logos", mode: Mode::Code, source: CODE_TWO_SUM, expected: Expected::OutputExact("11 + 3 = 14") },
5319 ExampleSpec { vfs_path: "/examples/code/algorithms/bfs.logos", mode: Mode::Code, source: CODE_BFS, expected: Expected::OutputExact("shortest path from 1 to 6: 3 hops") },
5320 ExampleSpec { vfs_path: "/examples/code/algorithms/collatz.logos", mode: Mode::Code, source: CODE_COLLATZ, expected: Expected::OutputExact("27 takes 111 steps to reach 1") },
5321 ExampleSpec { vfs_path: "/examples/code/collections/lists.logos", mode: Mode::Code, source: CODE_COLLECTIONS, expected: Expected::OutputExact("Numbers: [10, 20, 30, 40, 50]\nAfter pushing 60: [10, 20, 30, 40, 50, 60]\nThe list now holds 6 items.\nFirst: 10, last: 60.\nSum of all items: 210\nPopped 60; 5 items remain.") },
5322 ExampleSpec { vfs_path: "/examples/code/functions/recursion.logos", mode: Mode::Code, source: CODE_FACTORIAL, expected: Expected::OutputExact("factorial(5) = 120\nfactorial(10) = 3628800\nfib(10) = 55") },
5323 ExampleSpec { vfs_path: "/examples/code/functions/defining.logos", mode: Mode::Code, source: CODE_DEFINING, expected: Expected::OutputExact("a 12 x 10 room covers 120 square feet\nbalance after withdrawing 40 from 100: 60\nWelcome, Ada!") },
5324 ExampleSpec { vfs_path: "/examples/code/functions/closures.logos", mode: Mode::Code, source: CODE_CLOSURES, expected: Expected::OutputExact("double(21) = 42\n42 with the captured bonus of 100: 142\n7 is odd") },
5325 ExampleSpec { vfs_path: "/examples/code/functions/ufcs.logos", mode: Mode::Code, source: CODE_UFCS, expected: Expected::OutputExact("function style: double(5) = 10\nmethod style: (5).double() = 10\nchained: (5).double().plus(3).double() = 26") },
5326 ExampleSpec { vfs_path: "/examples/code/types/bytes-and-words.logos", mode: Mode::Code, source: CODE_BYTES_WORDS, expected: Expected::OutputExact("4294967295 + 1 wraps to 0\n1 shifted left by 4 = 16\n16 shifted right by 2 = 4\ncount_ones(255) = 8\n255 AND 170 = 170\n85 OR 170 = 255\n255 XOR 85 = 170\na Char literal: A") },
5327 ExampleSpec { vfs_path: "/examples/code/types/exact-numbers.logos", mode: Mode::Code, source: CODE_EXACT_NUMBERS, expected: Expected::OutputExact("1/3 + 1/6 = 1/2\n19.99 * 3 = 59.97 (no float drift)\ni * i = -1") },
5328 ExampleSpec { vfs_path: "/examples/code/types/structs.logos", mode: Mode::Code, source: CODE_STRUCT, expected: Expected::OutputExact("Alice is 30.\nBob is 25.\nAfter a birthday, Alice is 31.") },
5329 ExampleSpec { vfs_path: "/examples/code/types/enums.logos", mode: Mode::Code, source: CODE_ENUMS, expected: Expected::OutputExact("It's red!\nnot red") },
5330 ExampleSpec { vfs_path: "/examples/code/types/generics.logos", mode: Mode::Code, source: CODE_GENERICS, expected: Expected::OutputExact("The Int box holds 42.\nThe Text box holds hello.\nPair: score = 97.") },
5331 ExampleSpec { vfs_path: "/examples/code/collections/sets.logos", mode: Mode::Code, source: CODE_SETS, expected: Expected::OutputExact("After 4 adds (one duplicate): 3 members.\nBob is in the set.\nAfter removing Bob: 2 members.\nunion: {2, 4, 1}\nintersection: {2}\ndifference: {4}") },
5332 ExampleSpec { vfs_path: "/examples/code/collections/maps.logos", mode: Mode::Code, source: CODE_MAPS, expected: Expected::OutputExact("iron count: 50\nafter restock: 100\nFull inventory:\n iron: 100\n copper: 30\n gold: 10") },
5333 ExampleSpec { vfs_path: "/examples/code/functions/higher-order.logos", mode: Mode::Code, source: CODE_HIGHER_ORDER, expected: Expected::OutputExact("double(21) = 42\ntwice(double, 5) = 20\nmakeAdder(10) applied to 32 = 42") },
5334 ExampleSpec { vfs_path: "/examples/code/distributed/counters.logos", mode: Mode::Code, source: CODE_CRDT_COUNTERS, expected: Expected::OutputExact("Total points: 18") },
5335 ExampleSpec { vfs_path: "/examples/code/security/policies.logos", mode: Mode::Code, source: CODE_POLICIES, expected: Expected::OutputExact("Admin check passed: Root is admin.\nCapability check passed: Alice can edit her own document.") },
5336 ExampleSpec { vfs_path: "/examples/code/memory/zones.logos", mode: Mode::Code, source: CODE_ZONES, expected: Expected::OutputExact("Sum in zone: 100\nValue in the 1 MB zone: 100\nZones cleaned up!") },
5337 ExampleSpec { vfs_path: "/examples/code/concurrency/tasks.logos", mode: Mode::Code, source: CODE_TASKS, expected: Expected::OutputExact("worker done\nmain continues\nHello from a task\nworker done\nsecond worker stopped") },
5338 ExampleSpec { vfs_path: "/examples/code/concurrency/pipes.logos", mode: Mode::Code, source: CODE_CHANNELS, expected: Expected::OutputExact("received: 42\ntry-receive got: 7") },
5339 ExampleSpec { vfs_path: "/examples/code/concurrency/select.logos", mode: Mode::Code, source: CODE_SELECT, expected: Expected::OutputExact("first arrival: 99\ntimed out waiting on the quiet pipe") },
5340 ExampleSpec { vfs_path: "/examples/code/distributed/last-write-wins.logos", mode: Mode::Code, source: CODE_CRDT_LWW, expected: Expected::OutputExact("status: online\nstatus now: away") },
5341 ExampleSpec { vfs_path: "/examples/code/distributed/divergent.logos", mode: Mode::Code, source: CODE_CRDT_DIVERGENT, expected: Expected::OutputExact("title: Draft\nresolved title: Final") },
5342 ExampleSpec { vfs_path: "/examples/code/distributed/shared-set.logos", mode: Mode::Code, source: CODE_CRDT_SHARED_SET, expected: Expected::OutputExact("Bob survives: concurrent add wins\nteam size: 2") },
5343 ExampleSpec { vfs_path: "/examples/code/distributed/shared-sequence.logos", mode: Mode::Code, source: CODE_CRDT_SHARED_SEQUENCE, expected: Expected::OutputExact("entries after merge: 3") },
5344 ExampleSpec { vfs_path: "/examples/code/distributed/shared-map.logos", mode: Mode::Code, source: CODE_CRDT_SHARED_MAP, expected: Expected::OutputExact("50") },
5345 ExampleSpec { vfs_path: "/examples/code/distributed/sync.logos", mode: Mode::Code, source: CODE_CRDT_SYNC, expected: Expected::OutputExact("local clicks: 3") },
5346 ExampleSpec { vfs_path: "/examples/code/basics/variables.logos", mode: Mode::Code, source: CODE_BASICS_VARIABLES, expected: Expected::OutputExact("Alice is 25, active: true\nticket price: $19.99\ncount doubled: 200") },
5347 ExampleSpec { vfs_path: "/examples/code/basics/operators.logos", mode: Mode::Code, source: CODE_BASICS_OPERATORS, expected: Expected::OutputExact("10 + 3 = 13\n10 - 3 = 7\n10 * 3 = 30\n10 / 3 = 3\n10 % 3 = 1\n10 is greater than 3\n10 is between 1 and 100 (chained comparison)\n10 is between 5 and 15\n10 is even\n3 is odd\n10 is divisible by 5\nsunny and warm: false\nsunny or warm: true\nnot sunny: false") },
5348 ExampleSpec { vfs_path: "/examples/code/basics/control-flow.logos", mode: Mode::Code, source: CODE_BASICS_CONTROL_FLOW, expected: Expected::OutputExact("Grade: B\nCountdown:\n3\n2\n1\nBlastoff!\nFirst multiple of 7 above 20:\n21") },
5349 ExampleSpec { vfs_path: "/examples/code/types/enum-payloads.logos", mode: Mode::Code, source: CODE_ENUMS_PATTERNS, expected: Expected::OutputExact("Circle with radius 5, area about 75\nRectangle 4 x 6, area 24") },
5350 ExampleSpec { vfs_path: "/examples/code/memory/ownership.logos", mode: Mode::Code, source: CODE_OWNERSHIP, expected: Expected::OutputExact("Viewing: User Profile Data\nStill usable after lending: User Profile Data\nConsumed: User Profile Data\nOriginal intact: User Profile Data") },
5351 ExampleSpec { vfs_path: "/examples/code/concurrency/parallel.logos", mode: Mode::Code, source: CODE_CONCURRENCY_PARALLEL, expected: Expected::OutputExact("25^2 = 625, 9^3 = 729\nproduct: 455625\nx + y = 30") },
5352 ExampleSpec { vfs_path: "/examples/code/distributed/tally.logos", mode: Mode::Code, source: CODE_CRDT_TALLY, expected: Expected::OutputExact("after +100: 100\nafter -30: 70\nfinal: 80") },
5353 ExampleSpec { vfs_path: "/examples/code/distributed/merge.logos", mode: Mode::Code, source: CODE_CRDT_MERGE, expected: Expected::OutputExact("local views: 100\nremote views: 50\nafter merge: 150") },
5354 ExampleSpec { vfs_path: "/examples/code/networking/server.logos", mode: Mode::Code, source: CODE_NETWORK_SERVER, expected: Expected::NativeOnlyCompiles },
5355 ExampleSpec { vfs_path: "/examples/code/networking/client.logos", mode: Mode::Code, source: CODE_NETWORK_CLIENT, expected: Expected::NativeOnlyCompiles },
5356 ExampleSpec { vfs_path: "/examples/code/types/option-result.logos", mode: Mode::Code, source: CODE_ERROR_HANDLING, expected: Expected::OutputExact("10 / 2 = 5\nerror: cannot divide 5 by zero") },
5357 ExampleSpec { vfs_path: "/examples/code/verification/refinement.logos", mode: Mode::Code, source: CODE_ADVANCED_REFINEMENT, expected: Expected::OutputExact("positive: 5\npercentage: 85\ndice roll: 4") },
5358 ExampleSpec { vfs_path: "/examples/code/verification/assertions.logos", mode: Mode::Code, source: CODE_ADVANCED_ASSERTIONS, expected: Expected::OutputExact("withdrew 50 from 100, leaving 50\nprocess(5) = 10") },
5359 ExampleSpec { vfs_path: "/examples/code/verification/termination.logos", mode: Mode::Code, source: CODE_TERMINATION, expected: Expected::OutputExact("1024 halves to 1 in 10 steps\n1000000 halves to 1 in 19 steps") },
5360 ExampleSpec { vfs_path: "/examples/code/security/check-gate.logos", mode: Mode::Code, source: CODE_CHECK_GATE, expected: Expected::OutputExact("gate passed: the account is open\nwithdrawal of 40 approved for Ada") },
5361 ExampleSpec { vfs_path: "/examples/code/crypto/hashes.logos", mode: Mode::Code, source: CODE_HASHES, expected: Expected::OutputExact("sha1 of abc: first bytes 169, 153\nmd5 of abc: first byte 144\ndigest lengths: sha1 20 bytes, md5 16 bytes") },
5362 ExampleSpec { vfs_path: "/examples/code/crypto/chacha20.logos", mode: Mode::Code, source: CODE_CHACHA20, expected: Expected::OutputExact("a = 3928658676\nb = 3407673550\nc = 1166100270\nd = 1484899515") },
5363 ExampleSpec { vfs_path: "/examples/code/crypto/ml-kem.logos", mode: Mode::Code, source: CODE_MLKEM, expected: Expected::OutputExact("encapsulation key: 1184 bytes\nciphertext: 1088 bytes, shared secret: 32 bytes") },
5364 ExampleSpec { vfs_path: "/examples/code/crypto/uuid.logos", mode: Mode::Code, source: CODE_UUID, expected: Expected::OutputExact("v5 of example.com: 2ed6657d-e927-568b-95e1-2665a8aea6a2\nv4 from fixed bytes: 0b16212c-3742-4d58-a36e-79848f9aa5b0") },
5365 ExampleSpec { vfs_path: "/examples/code/projects/todo-list.logos", mode: Mode::Code, source: CODE_PROJ_TODO, expected: Expected::OutputExact("TODO:\n [ ] buy milk\n [x] write examples\n [ ] water plants\n2 remaining") },
5366 ExampleSpec { vfs_path: "/examples/code/projects/inventory.logos", mode: Mode::Code, source: CODE_PROJ_INVENTORY, expected: Expected::OutputExact("Inventory report:\n planks: 28\n nails: 350\n hinges: 2 LOW - reorder\n varnish: 2 LOW - reorder") },
5367 ExampleSpec { vfs_path: "/examples/code/projects/dice-game.logos", mode: Mode::Code, source: CODE_PROJ_DICE, expected: Expected::OutputExact("round 1: you rolled 4, rival rolled 1\nround 2: you rolled 6, rival rolled 5\nround 3: you rolled 6, rival rolled 3\nfinal score - you: 16, rival: 9\nyou win!") },
5368 ExampleSpec { vfs_path: "/examples/code/projects/temperature-stats.logos", mode: Mode::Code, source: CODE_PROJ_WEATHER, expected: Expected::OutputExact("week of readings: [18, 21, 25, 24, 19, 16, 22]\nlow 16, high 25, average 20 (rounded down)\nchart:\n 18 ###\n 21 ######\n 25 ##########\n 24 #########\n 19 ####\n 16 #\n 22 #######") },
5369 ExampleSpec { vfs_path: "/examples/code/projects/bank-ledger.logos", mode: Mode::Code, source: CODE_PROJ_LEDGER, expected: Expected::OutputExact("opening balance: $250.00\ndeposit $75.50 -> $325.50\ndeposit $12.25 -> $337.75\nwithdrew $40.00 -> $297.75\nclosing balance: $297.75") },
5370 ExampleSpec { vfs_path: "/examples/code/projects/caesar-cipher.logos", mode: Mode::Code, source: CODE_PROJ_CAESAR, expected: Expected::OutputExact("encoded: khoor zruog\ndecoded: hello world") },
5371 ExampleSpec { vfs_path: "/examples/code/projects/word-count.logos", mode: Mode::Code, source: CODE_PROJ_WORDCOUNT, expected: Expected::OutputExact("text: the quick brown fox jumps over the lazy dog\n43 characters\n9 words") },
5372 ExampleSpec { vfs_path: "/examples/code/projects/matrix-ops.logos", mode: Mode::Code, source: CODE_PROJ_MATRIX, expected: Expected::OutputExact("A x B = [[19, 22], [43, 50]]") },
5373 ExampleSpec { vfs_path: "/examples/code/projects/event-scheduler.logos", mode: Mode::Code, source: CODE_PROJ_SCHEDULER, expected: Expected::OutputExact("kickoff: 2026-06-01 09:00\nstandup: 2026-06-01 09:30\nreview: 2026-06-01 16:00\nstandup comes before review\neach focus block runs 2h") },
5374 ExampleSpec { vfs_path: "/examples/code/projects/vending-machine.logos", mode: Mode::Code, source: CODE_PROJ_VENDING, expected: Expected::OutputExact("credit: 75 cents\ndispensing soda\nchange: 10 cents\nmachine reset") },
5375 ExampleSpec { vfs_path: "/examples/code/projects/text-adventure.logos", mode: Mode::Code, source: CODE_PROJ_ADVENTURE, expected: Expected::OutputExact("> north\nYou are in a quiet library. A key glints on the desk.\n> take key\nYou found the key!\n> south\nYou are in a dusty hall. Doors lead north and east.\n> east\nYou are in a dark cellar. The exit door is locked.\nThe key turns. You escape the cellar!") },
5376 ExampleSpec { vfs_path: "/examples/code/projects/chat-simulation.logos", mode: Mode::Code, source: CODE_PROJ_CHAT, expected: Expected::OutputExact("<alice> message 101\n<alice> message 102\n<bob> message 201\nroom quiet - closing") },
5377 ExampleSpec { vfs_path: "/examples/code/projects/leaderboard.logos", mode: Mode::Code, source: CODE_PROJ_LEADERBOARD, expected: Expected::OutputExact("standings after merge:\n alice: 19\n bob: 16\nalice leads") },
5378 ExampleSpec { vfs_path: "/examples/code/projects/password-hasher.logos", mode: Mode::Code, source: CODE_PROJ_HASHER, expected: Expected::OutputExact("stored digest: 20 bytes\ncorrect password accepted\nwrong password rejected") },
5379 ExampleSpec { vfs_path: "/examples/code/time-and-money/durations.logos", mode: Mode::Code, source: CODE_TEMPORAL, expected: Expected::OutputExact("blink 50ns, tick 100\u{3bc}s, pause 500ms, breath 1s\n500ms + 500ms = 1s\n500ms is less than 1s\nSleeping 200ms...\nAwake!") },
5380 ExampleSpec { vfs_path: "/examples/code/web/counter.logos", mode: Mode::Code, source: CODE_WEB_COUNTER, expected: Expected::WebPage },
5382 ExampleSpec { vfs_path: "/examples/code/web/todo-list.logos", mode: Mode::Code, source: CODE_WEB_TODO, expected: Expected::WebPage },
5383 ExampleSpec { vfs_path: "/examples/code/web/form.logos", mode: Mode::Code, source: CODE_WEB_FORM, expected: Expected::WebPage },
5384 ExampleSpec { vfs_path: "/examples/code/web/website.logos", mode: Mode::Code, source: CODE_WEB_SITE, expected: Expected::WebPage },
5385];
5386
5387pub const ALL_MATH_EXAMPLES: &[ExampleSpec] = &[
5389 ExampleSpec {
5390 vfs_path: "/examples/math/prelude-tour.logos",
5391 mode: Mode::Math,
5392 source: MATH_PRELUDE_TOUR,
5393 expected: Expected::KernelAllStatementsOk,
5394 },
5395 ExampleSpec {
5396 vfs_path: "/examples/math/big-arithmetic.logos",
5397 mode: Mode::Math,
5398 source: MATH_BIG_ARITHMETIC,
5399 expected: Expected::KernelAllStatementsOk,
5400 },
5401 ExampleSpec {
5402 vfs_path: "/examples/math/termination-wall.logos",
5403 mode: Mode::Math,
5404 source: MATH_TERMINATION_WALL,
5405 expected: Expected::KernelAdmitsAt("collatz_len"),
5406 },
5407 ExampleSpec {
5408 vfs_path: "/examples/math/tarski-geometry.logos",
5409 mode: Mode::Math,
5410 source: MATH_TARSKI,
5411 expected: Expected::TheoryAllVerified,
5412 },
5413 ExampleSpec {
5414 vfs_path: "/examples/math/natural-numbers.logos",
5415 mode: Mode::Math,
5416 source: MATH_NAT,
5417 expected: Expected::KernelAllStatementsOk,
5418 },
5419 ExampleSpec {
5420 vfs_path: "/examples/math/boolean-logic.logos",
5421 mode: Mode::Math,
5422 source: MATH_BOOL,
5423 expected: Expected::KernelAllStatementsOk,
5424 },
5425 ExampleSpec {
5426 vfs_path: "/examples/math/godel-sentence.logos",
5427 mode: Mode::Math,
5428 source: MATH_GODEL,
5429 expected: Expected::KernelAllStatementsOk,
5430 },
5431 ExampleSpec {
5432 vfs_path: "/examples/math/incompleteness.logos",
5433 mode: Mode::Math,
5434 source: MATH_INCOMPLETENESS,
5435 expected: Expected::KernelAllStatementsOk,
5436 },
5437 ExampleSpec {
5438 vfs_path: "/examples/math/prop-logic.logos",
5439 mode: Mode::Math,
5440 source: MATH_PROP_LOGIC,
5441 expected: Expected::KernelAllStatementsOk,
5442 },
5443 ExampleSpec {
5444 vfs_path: "/examples/math/functions.logos",
5445 mode: Mode::Math,
5446 source: MATH_FUNCTIONS,
5447 expected: Expected::KernelAllStatementsOk,
5448 },
5449 ExampleSpec {
5450 vfs_path: "/examples/math/list-ops.logos",
5451 mode: Mode::Math,
5452 source: MATH_LIST_OPS,
5453 expected: Expected::KernelAllStatementsOk,
5454 },
5455 ExampleSpec {
5456 vfs_path: "/examples/math/pairs.logos",
5457 mode: Mode::Math,
5458 source: MATH_PAIRS,
5459 expected: Expected::KernelAllStatementsOk,
5460 },
5461 ExampleSpec {
5462 vfs_path: "/examples/math/logic-gates.logos",
5463 mode: Mode::Math,
5464 source: MATH_CIRCUIT,
5465 expected: Expected::KernelAllStatementsOk,
5466 },
5467 ExampleSpec {
5468 vfs_path: "/examples/math/proven-property.logos",
5469 mode: Mode::Math,
5470 source: MATH_PROPERTY,
5471 expected: Expected::KernelAllStatementsOk,
5472 },
5473 ExampleSpec {
5474 vfs_path: "/examples/math/collatz.logos",
5475 mode: Mode::Math,
5476 source: MATH_COLLATZ,
5477 expected: Expected::KernelAllStatementsOk,
5478 },
5479 ExampleSpec {
5480 vfs_path: "/examples/math/godel-literate.logos",
5481 mode: Mode::Math,
5482 source: MATH_GODEL_LITERATE,
5483 expected: Expected::KernelAllStatementsOk,
5484 },
5485 ExampleSpec {
5486 vfs_path: "/examples/math/incompleteness-literate.logos",
5487 mode: Mode::Math,
5488 source: MATH_INCOMPLETENESS_LITERATE,
5489 expected: Expected::KernelAllStatementsOk,
5490 },
5491 ExampleSpec {
5492 vfs_path: "/examples/math/ring-tactic.logos",
5493 mode: Mode::Math,
5494 source: MATH_RING,
5495 expected: Expected::KernelAllStatementsOk,
5496 },
5497 ExampleSpec {
5498 vfs_path: "/examples/math/lia-tactic.logos",
5499 mode: Mode::Math,
5500 source: MATH_LIA,
5501 expected: Expected::KernelAllStatementsOk,
5502 },
5503 ExampleSpec {
5504 vfs_path: "/examples/math/cc-tactic.logos",
5505 mode: Mode::Math,
5506 source: MATH_CC,
5507 expected: Expected::KernelAllStatementsOk,
5508 },
5509 ExampleSpec {
5510 vfs_path: "/examples/math/simp-tactic.logos",
5511 mode: Mode::Math,
5512 source: MATH_SIMP,
5513 expected: Expected::KernelAllStatementsOk,
5514 },
5515 ExampleSpec {
5516 vfs_path: "/examples/math/omega-tactic.logos",
5517 mode: Mode::Math,
5518 source: MATH_OMEGA,
5519 expected: Expected::KernelAllStatementsOk,
5520 },
5521 ExampleSpec {
5522 vfs_path: "/examples/math/auto-tactic.logos",
5523 mode: Mode::Math,
5524 source: MATH_AUTO,
5525 expected: Expected::KernelAllStatementsOk,
5526 },
5527 ExampleSpec {
5528 vfs_path: "/examples/math/induction-tactic.logos",
5529 mode: Mode::Math,
5530 source: MATH_INDUCTION,
5531 expected: Expected::KernelAllStatementsOk,
5532 },
5533 ExampleSpec {
5534 vfs_path: "/examples/math/hints.logos",
5535 mode: Mode::Math,
5536 source: MATH_HINTS,
5537 expected: Expected::KernelAllStatementsOk,
5538 },
5539 ExampleSpec {
5540 vfs_path: "/examples/math/inversion-tactic.logos",
5541 mode: Mode::Math,
5542 source: MATH_INVERSION,
5543 expected: Expected::KernelAllStatementsOk,
5544 },
5545 ExampleSpec {
5546 vfs_path: "/examples/math/operator-tactics.logos",
5547 mode: Mode::Math,
5548 source: MATH_OPERATOR,
5549 expected: Expected::KernelAllStatementsOk,
5550 },
5551 ExampleSpec {
5552 vfs_path: "/examples/math/tacticals.logos",
5553 mode: Mode::Math,
5554 source: MATH_TACTICALS,
5555 expected: Expected::KernelAllStatementsOk,
5556 },
5557];
5558
5559pub const ALL_HARDWARE_SPECS: &[ExampleSpec] = &[
5563 ExampleSpec {
5564 vfs_path: "/examples/hardware/handshake.hw",
5565 mode: Mode::Hardware,
5566 source: HARDWARE_EXAMPLES[0].1,
5567 expected: Expected::SvaSynthesizes,
5568 },
5569 ExampleSpec {
5570 vfs_path: "/examples/hardware/only-if.hw",
5571 mode: Mode::Hardware,
5572 source: HARDWARE_EXAMPLES[1].1,
5573 expected: Expected::SvaSynthesizes,
5574 },
5575 ExampleSpec {
5576 vfs_path: "/examples/hardware/next-cycle.hw",
5577 mode: Mode::Hardware,
5578 source: HARDWARE_EXAMPLES[2].1,
5579 expected: Expected::SvaSynthesizes,
5580 },
5581 ExampleSpec {
5582 vfs_path: "/examples/hardware/mutex.hw",
5583 mode: Mode::Hardware,
5584 source: HW_MUTEX,
5585 expected: Expected::SvaSynthesizes,
5586 },
5587 ExampleSpec {
5588 vfs_path: "/examples/hardware/intersection-design.hw",
5589 mode: Mode::Hardware,
5590 source: HARDWARE_EXAMPLES[3].1,
5591 expected: Expected::SignalPlanSynthesizes,
5592 },
5593 ExampleSpec {
5594 vfs_path: "/examples/hardware/t-junction.hw",
5595 mode: Mode::Hardware,
5596 source: HARDWARE_EXAMPLES[4].1,
5597 expected: Expected::SignalPlanSynthesizes,
5598 },
5599 ExampleSpec {
5600 vfs_path: "/examples/hardware/arbiter.v",
5601 mode: Mode::Hardware,
5602 source: RTL_EXAMPLES[0].1,
5603 expected: Expected::RtlProven,
5604 },
5605 ExampleSpec {
5606 vfs_path: "/examples/hardware/bad-arbiter.v",
5607 mode: Mode::Hardware,
5608 source: RTL_EXAMPLES[1].1,
5609 expected: Expected::RefutesWithCounterexample,
5610 },
5611 ExampleSpec {
5612 vfs_path: "/examples/hardware/fifo.v",
5613 mode: Mode::Hardware,
5614 source: RTL_EXAMPLES[2].1,
5615 expected: Expected::RtlProven,
5616 },
5617 ExampleSpec {
5618 vfs_path: "/examples/hardware/onehot.v",
5619 mode: Mode::Hardware,
5620 source: RTL_EXAMPLES[3].1,
5621 expected: Expected::RtlProven,
5622 },
5623 ExampleSpec {
5624 vfs_path: "/examples/hardware/reset-mirror.v",
5625 mode: Mode::Hardware,
5626 source: RTL_EXAMPLES[4].1,
5627 expected: Expected::RtlProven,
5628 },
5629 ExampleSpec {
5630 vfs_path: "/examples/hardware/traffic-safe.v",
5631 mode: Mode::Hardware,
5632 source: RTL_EXAMPLES[5].1,
5633 expected: Expected::RtlProven,
5634 },
5635 ExampleSpec {
5636 vfs_path: "/examples/hardware/traffic-crash.v",
5637 mode: Mode::Hardware,
5638 source: RTL_EXAMPLES[6].1,
5639 expected: Expected::RefutesWithCounterexample,
5640 },
5641 ExampleSpec {
5642 vfs_path: "/examples/hardware/queue-jam.v",
5643 mode: Mode::Hardware,
5644 source: RTL_EXAMPLES[7].1,
5645 expected: Expected::RefutesWithCounterexample,
5646 },
5647 ExampleSpec {
5648 vfs_path: "/examples/hardware/queue-stable.v",
5649 mode: Mode::Hardware,
5650 source: RTL_EXAMPLES[8].1,
5651 expected: Expected::RtlProven,
5652 },
5653 ExampleSpec {
5654 vfs_path: "/examples/hardware/datapath-identity.v",
5655 mode: Mode::Hardware,
5656 source: RTL_EXAMPLES[9].1,
5657 expected: Expected::RtlProven,
5658 },
5659 ExampleSpec {
5660 vfs_path: "/examples/hardware/door-interlock.v",
5661 mode: Mode::Hardware,
5662 source: RTL_EXAMPLES[10].1,
5663 expected: Expected::RtlProven,
5664 },
5665 ExampleSpec {
5666 vfs_path: "/examples/hardware/door-interlock-bug.v",
5667 mode: Mode::Hardware,
5668 source: RTL_EXAMPLES[11].1,
5669 expected: Expected::RefutesWithCounterexample,
5670 },
5671 ExampleSpec {
5672 vfs_path: "/examples/hardware/register-alloc-fits.hw",
5673 mode: Mode::Hardware,
5674 source: REGALLOC_EXAMPLES[0].1,
5675 expected: Expected::RegisterAllocFits,
5676 },
5677 ExampleSpec {
5678 vfs_path: "/examples/hardware/register-alloc-spill.hw",
5679 mode: Mode::Hardware,
5680 source: REGALLOC_EXAMPLES[1].1,
5681 expected: Expected::SpillsRequired,
5682 },
5683 ExampleSpec {
5684 vfs_path: "/examples/hardware/pigeonhole.hw",
5685 mode: Mode::Hardware,
5686 source: PIGEONHOLE_EXAMPLES[0].1,
5687 expected: Expected::UnsatCertified,
5688 },
5689 ExampleSpec {
5690 vfs_path: "/examples/hardware/pigeonhole-12.hw",
5691 mode: Mode::Hardware,
5692 source: PIGEONHOLE_EXAMPLES[1].1,
5693 expected: Expected::UnsatCertified,
5694 },
5695];
5696
5697const COMPILED_RUNTIME_NEEDS: &[(&str, &str)] = &[
5700 ("/examples/code/networking/server.logos", "Live networking"),
5701 ("/examples/code/networking/client.logos", "Live networking"),
5702];
5703
5704const PLANTED_BUG_FIXES: &[(&str, &str)] = &[
5707 (
5708 "/examples/hardware/bad-arbiter.v",
5709 "/examples/hardware/arbiter.v",
5710 ),
5711 (
5712 "/examples/hardware/traffic-crash.v",
5713 "/examples/hardware/traffic-safe.v",
5714 ),
5715 (
5716 "/examples/hardware/queue-jam.v",
5717 "/examples/hardware/queue-stable.v",
5718 ),
5719 (
5720 "/examples/hardware/door-interlock-bug.v",
5721 "/examples/hardware/door-interlock.v",
5722 ),
5723 (
5724 "/examples/hardware/register-alloc-spill.hw",
5725 "/examples/hardware/register-alloc-fits.hw",
5726 ),
5727];
5728
5729fn row(table: &[(&'static str, &'static str)], path: &str) -> Option<&'static str> {
5730 table
5731 .iter()
5732 .find(|(at, _)| *at == path)
5733 .map(|(_, value)| *value)
5734}
5735
5736pub fn compiled_runtime_needs(path: &str) -> Option<&'static str> {
5739 let spec = ALL_CODE_EXAMPLES
5740 .iter()
5741 .find(|spec| spec.vfs_path == path)?;
5742 if !matches!(spec.expected, Expected::NativeOnlyCompiles) {
5743 return None;
5744 }
5745 row(COMPILED_RUNTIME_NEEDS, path)
5746}
5747
5748pub fn planted_bug_fix(path: &str) -> Option<&'static str> {
5750 let spec = ALL_HARDWARE_SPECS
5751 .iter()
5752 .find(|spec| spec.vfs_path == path)?;
5753 if !matches!(
5754 spec.expected,
5755 Expected::RefutesWithCounterexample | Expected::SpillsRequired
5756 ) {
5757 return None;
5758 }
5759 row(PLANTED_BUG_FIXES, path)
5760}
5761
5762pub fn planted_bug_notice(path: &str) -> Option<String> {
5765 let fixed = planted_bug_fix(path)?;
5766 let name = fixed.rsplit('/').next().unwrap_or(fixed);
5767 Some(format!(
5768 "A planted bug: this design is meant to fail, and the prover shows exactly where. {name} is the same design, fixed."
5769 ))
5770}
5771
5772pub fn compiled_runtime_notice(path: &str) -> Option<String> {
5775 let needs = compiled_runtime_needs(path)?;
5776 Some(format!(
5777 "{needs} needs the compiled runtime. Build it with `largo build`, and Compile shows the Rust it becomes."
5778 ))
5779}
5780
5781#[cfg(test)]
5782#[path = "../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/examples/example_health.rs"]
5783mod example_health;
5784
5785#[cfg(test)]
5786#[path = "../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/examples/compiled_runtime_notice_tests.rs"]
5787mod compiled_runtime_notice_tests;
5788
5789#[cfg(test)]
5790#[path = "../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/examples/planted_bug_tests.rs"]
5791mod planted_bug_tests;