Skip to main content

logicaffeine_web/ui/pages/guide/
content.rs

1//! Embedded guide content for the Programmer's Guide page.
2//!
3//! Contains all 24 sections from work/PROGRAMMERS_LANGUAGE_STARTER.md as Rust constants.
4//! WASM cannot read files at runtime, so we embed the content at compile time.
5
6/// Mode for code examples - determines how "Run" executes them
7#[derive(Clone, Copy, PartialEq, Eq, Debug)]
8pub enum ExampleMode {
9    /// Logic mode: compile to First-Order Logic (FOL)
10    Logic,
11    /// Imperative mode: execute via WASM interpreter
12    Imperative,
13}
14
15/// A code example within a section
16#[derive(Clone, Debug, PartialEq)]
17pub struct CodeExample {
18    pub id: &'static str,
19    pub label: &'static str,
20    pub mode: ExampleMode,
21    pub code: &'static str,
22}
23
24/// A section of the guide
25#[derive(Clone, Debug)]
26pub struct Section {
27    pub id: &'static str,
28    pub number: u8,
29    pub title: &'static str,
30    pub part: &'static str,
31    pub content: &'static str,
32    pub examples: &'static [CodeExample],
33}
34
35/// All guide sections organized by part
36pub const SECTIONS: &[Section] = &[
37    // ============================================================
38    // Part I: Programming in LOGOS (Sections 1-17)
39    // ============================================================
40
41    Section {
42        id: "introduction",
43        number: 1,
44        title: "Introduction",
45        part: "Part I: Programming in LOGOS",
46        content: r#"
47### What is LOGOS?
48
49LOGOS is a programming language where you write code in natural English. Instead of cryptic symbols and arcane syntax, you express your ideas in sentences that read like plain prose—and those sentences compile into efficient, executable programs.
50
51LOGOS has two modes:
52
53| Mode | What It Does | Output |
54|------|--------------|--------|
55| **Imperative Mode** | Write executable programs | Rust code (compiled to native binaries) |
56| **Logic Mode** | Translate English to formal logic | First-Order Logic notation |
57
58This guide focuses primarily on **Imperative Mode**—using LOGOS as a programming language. Part III covers Logic Mode for those interested in formal semantics.
59
60### The Vision
61
62The name LOGOS comes from the Greek λόγος, meaning "word," "reason," and "principle." In LOGOS, these concepts unify:
63
64- **Words** become executable code
65- **Reason** becomes verifiable logic
66- **Principles** become formal proofs
67
68When you write LOGOS, you're not writing comments that describe code—you're writing sentences that *are* the code.
69
70### How to Read This Guide
71
72**If you're new to programming:**
73- Read each section in order
74- Try every example yourself
75- Don't skip ahead—each concept builds on the previous
76
77**If you're an experienced programmer:**
78- Use the Table of Contents to jump to what interests you
79- The Quick Reference section provides rapid lookup
80- The Complete Examples show real-world patterns
81"#,
82        examples: &[],
83    },
84
85    Section {
86        id: "getting-started",
87        number: 2,
88        title: "Getting Started",
89        part: "Part I: Programming in LOGOS",
90        content: r#"
91### Installing largo
92
93Everything on this site runs in your browser — but for real projects you want `largo`,
94the LOGOS build tool, on your machine. One line, no toolchain required:
95
96```bash
97curl -fsSL https://logicaffeine.com/install.sh | sh
98```
99
100On Windows:
101
102```powershell
103powershell -ExecutionPolicy Bypass -c "irm https://logicaffeine.com/install.ps1 | iex"
104```
105
106The installer fetches the prebuilt binary for your platform (Linux/macOS x64 + arm64,
107Windows x64), verifies its SHA-256 checksum, and installs it to `~/.local/bin` — no sudo,
108no shell-config edits. Add `--full` (`sh -s -- --full`) for the build with Z3 verification
109bundled. Then:
110
111```bash
112largo new hello && cd hello && largo run
113```
114
115### Hello World
116
117Every programming journey begins with Hello World. In LOGOS:
118"#,
119        examples: &[
120            CodeExample {
121                id: "hello-world",
122                label: "Hello World",
123                mode: ExampleMode::Imperative,
124                code: r#"## Main
125Show "Hello, World!"."#,
126            },
127            CodeExample {
128                id: "program-structure",
129                label: "Program Structure",
130                mode: ExampleMode::Imperative,
131                code: r#"## Definition
132A Point has:
133    an x: Int.
134    a y: Int.
135
136## To greet (name: Text) -> Text:
137    Return "Hello, " + name + "!".
138
139## Main
140Let p be a new Point with x 10 and y 20.
141Let message be greet("World").
142Show message."#,
143            },
144            CodeExample {
145                id: "first-program",
146                label: "Your First Real Program",
147                mode: ExampleMode::Imperative,
148                code: r#"## Main
149Let name be "Alice".
150Let age be 25.
151Show "Name: " + name.
152Show "Age: " + age."#,
153            },
154        ],
155    },
156
157    Section {
158        id: "variables-and-types",
159        number: 3,
160        title: "Variables and Types",
161        part: "Part I: Programming in LOGOS",
162        content: r#"
163Variables are containers that hold values. In LOGOS, you create and modify variables using natural English sentences.
164
165### Creating Variables
166
167Use `Let` to create a new variable. The word `be` assigns a value to the variable.
168
169### Changing Values
170
171Use `Set` to change an existing variable. The difference between `Let` and `Set`:
172- `Let` creates a *new* variable
173- `Set` modifies an *existing* variable
174
175### Primitive Types
176
177| Type | Description | Examples |
178|------|-------------|----------|
179| `Int` | Whole numbers | `5`, `-10`, `0`, `1000000` |
180| `Bool` | True or false | `true`, `false` |
181| `Text` | Strings of characters | `"Hello"`, `"LOGOS"`, `""` |
182| `Float` / `Real` | Decimal numbers | `3.14`, `-0.5`, `98.6` |
183| `Char` | Single character | see examples below |
184| `Byte` | 8-bit unsigned (0-255) | `42: Byte`, `255: Byte` |
185
186### Characters (Char)
187
188Characters represent single Unicode characters, wrapped in backticks. See the example below.
189
190### Bytes (Byte)
191
192Bytes are 8-bit unsigned integers (0-255), useful for binary data and low-level operations.
193
194### Type Annotations
195
196Usually, LOGOS infers the type from the value you assign. But you can be explicit with `: Type`.
197"#,
198        examples: &[
199            CodeExample {
200                id: "creating-variables",
201                label: "Creating Variables",
202                mode: ExampleMode::Imperative,
203                code: r#"## Main
204Let x be 5.
205Let name be "Bob".
206Let is_active be true.
207Let temperature be 98.6.
208Show x.
209Show name."#,
210            },
211            CodeExample {
212                id: "changing-variables",
213                label: "Changing Variables",
214                mode: ExampleMode::Imperative,
215                code: r#"## Main
216Let x be 5.
217Show x.
218
219Set x to 10.
220Show x.
221
222Set x to x + 1.
223Show x."#,
224            },
225            CodeExample {
226                id: "text-concat",
227                label: "Text Concatenation",
228                mode: ExampleMode::Imperative,
229                code: r#"## Main
230Let first be "Hello".
231Let second be "World".
232Let message be first + ", " + second + "!".
233Show message."#,
234            },
235            CodeExample {
236                id: "char-literals",
237                label: "Character Literals",
238                mode: ExampleMode::Imperative,
239                code: r#"## Main
240Let letter be `a`.
241Let newline be `\n`.
242Let tab be `\t`.
243Let escaped be `\\`.
244Show letter.
245Show "Char type uses backticks"."#,
246            },
247            CodeExample {
248                id: "byte-type",
249                label: "Byte Type",
250                mode: ExampleMode::Imperative,
251                code: r#"## Main
252Let max: Byte be 255.
253Let min: Byte be 0.
254Let mid: Byte be 128.
255Show max.
256Show min.
257Show mid."#,
258            },
259        ],
260    },
261
262    Section {
263        id: "operators",
264        number: 4,
265        title: "Operators and Expressions",
266        part: "Part I: Programming in LOGOS",
267        content: r#"
268Operators let you combine values into expressions. LOGOS supports both symbolic operators (like `+`) and English words (like `plus`).
269
270### Arithmetic
271
272| Operation | Symbol | English |
273|-----------|--------|---------|
274| Addition | `+` | `plus` |
275| Subtraction | `-` | `minus` |
276| Multiplication | `*` | `times` |
277| Division | `/` | `divided by` |
278| Modulo | `%` | `modulo` |
279
280### Comparisons
281
282| Operation | Symbol | English |
283|-----------|--------|---------|
284| Less than | `<` | `is less than` |
285| Greater than | `>` | `is greater than` |
286| Less or equal | `<=` | `is at most` |
287| Greater or equal | `>=` | `is at least` |
288| Equal | `==` | `equals` |
289| Not equal | `!=` | `is not` |
290
291### Logical Operators
292
293| Operation | Keyword | Meaning |
294|-----------|---------|---------|
295| AND | `and` | Both must be true |
296| OR | `or` | At least one must be true |
297| NOT | `not` | Inverts true/false |
298"#,
299        examples: &[
300            CodeExample {
301                id: "arithmetic",
302                label: "Arithmetic Operations",
303                mode: ExampleMode::Imperative,
304                code: r#"## Main
305Let a be 10.
306Let b be 3.
307
308Let sum be a + b.
309Let diff be a - b.
310Let prod be a * b.
311Let quot be a / b.
312Let rem be a % b.
313
314Show "Sum: " + sum.
315Show "Difference: " + diff.
316Show "Product: " + prod.
317Show "Quotient: " + quot.
318Show "Remainder: " + rem."#,
319            },
320            CodeExample {
321                id: "comparisons",
322                label: "Comparisons",
323                mode: ExampleMode::Imperative,
324                code: r#"## Main
325Let x be 5.
326Let y be 10.
327
328Show x is less than y.
329Show x is greater than y.
330Show x equals 5.
331Show x is at most 5.
332Show x is at least 5."#,
333            },
334            CodeExample {
335                id: "logical",
336                label: "Logical Operators",
337                mode: ExampleMode::Imperative,
338                code: r#"## Main
339Let a be true.
340Let b be false.
341
342Show a and b.
343Show a or b.
344Show not a."#,
345            },
346        ],
347    },
348
349    Section {
350        id: "control-flow",
351        number: 5,
352        title: "Control Flow",
353        part: "Part I: Programming in LOGOS",
354        content: r#"
355Control flow determines which code runs and in what order. LOGOS provides conditionals and loops using natural English syntax.
356
357### Conditionals
358
359Use `If` to execute code only when a condition is true. The colon (`:`) after the condition opens an indented block.
360
361### If/Otherwise
362
363Use `Otherwise` to handle the false case.
364
365### While Loops
366
367Use `While` to repeat code as long as a condition is true.
368
369### For-Each Loops
370
371Use `Repeat for` to iterate over collections.
372"#,
373        examples: &[
374            CodeExample {
375                id: "if-otherwise",
376                label: "If/Otherwise",
377                mode: ExampleMode::Imperative,
378                code: r#"## Main
379Let temperature be 72.
380
381If temperature is greater than 80:
382    Show "It's hot!".
383Otherwise:
384    Show "It's comfortable."."#,
385            },
386            CodeExample {
387                id: "while-loop",
388                label: "While Loop",
389                mode: ExampleMode::Imperative,
390                code: r#"## Main
391Let count be 1.
392
393While count is at most 5:
394    Show count.
395    Set count to count + 1."#,
396            },
397            CodeExample {
398                id: "for-each",
399                label: "For-Each Loop",
400                mode: ExampleMode::Imperative,
401                code: r#"## Main
402Let numbers be [1, 2, 3, 4, 5].
403
404Repeat for n in numbers:
405    Show n."#,
406            },
407            CodeExample {
408                id: "grading",
409                label: "Grading Example",
410                mode: ExampleMode::Imperative,
411                code: r#"## Main
412Let score be 85.
413
414If score is at least 90:
415    Show "Grade: A".
416If score is at least 80 and score is less than 90:
417    Show "Grade: B".
418If score is at least 70 and score is less than 80:
419    Show "Grade: C".
420If score is less than 70:
421    Show "Grade: F"."#,
422            },
423        ],
424    },
425
426    Section {
427        id: "functions",
428        number: 6,
429        title: "Functions",
430        part: "Part I: Programming in LOGOS",
431        content: r#"
432Functions are reusable blocks of code. In LOGOS, you define functions using natural English headers that describe what the function does.
433
434### Defining Functions
435
436A function definition starts with `## To` followed by the function name.
437
438### Parameters
439
440Functions can accept parameters—values passed in when the function is called. Use `and` to separate multiple parameters.
441
442### Return Values
443
444Use `-> Type` to specify what the function returns.
445
446### Recursion
447
448Functions can call themselves. This is called recursion. Every recursive function needs:
4491. A **base case** — when to stop recursing
4502. A **recursive case** — calling itself with a "smaller" problem
451"#,
452        examples: &[
453            CodeExample {
454                id: "simple-function",
455                label: "Simple Function",
456                mode: ExampleMode::Imperative,
457                code: r#"## To greet (name: Text):
458    Show "Hello, " + name + "!".
459
460## Main
461greet("Alice").
462greet("Bob")."#,
463            },
464            CodeExample {
465                id: "function-return",
466                label: "Function with Return",
467                mode: ExampleMode::Imperative,
468                code: r#"## To add (a: Int) and (b: Int) -> Int:
469    Return a + b.
470
471## Main
472Let sum be add(3, 5).
473Show sum."#,
474            },
475            CodeExample {
476                id: "factorial",
477                label: "Recursive Factorial",
478                mode: ExampleMode::Imperative,
479                code: r#"## To factorial (n: Int) -> Int:
480    If n is at most 1:
481        Return 1.
482    Return n * factorial(n - 1).
483
484## Main
485Show factorial(5)."#,
486            },
487        ],
488    },
489
490    Section {
491        id: "collections",
492        number: 7,
493        title: "Collections",
494        part: "Part I: Programming in LOGOS",
495        content: r#"
496Collections hold multiple values. LOGOS provides four main collection types:
497
498| Collection | Description | Index Type |
499|------------|-------------|------------|
500| `Seq of T` | Ordered list | Int (1-based) |
501| `Map of K to V` | Key-value pairs | Any key type |
502| `Set of T` | Unique elements | N/A (membership) |
503| `Tuple` | Fixed-size, mixed types | Int (1-based) |
504
505### Creating Lists
506
507Create a list with square brackets, or create an empty list with a type.
508
509### Accessing Elements
510
511LOGOS uses **1-based indexing**. The first element is at position 1, not 0. Why? Because that's how humans count.
512
513### Modifying Collections
514
515- `Push` to add an element to the end
516- `Pop` to remove and get the last element
517- `copy of` to create a deep copy
518
519### Slicing
520
521Extract a portion of a list with `through`. Slicing is **inclusive** on both ends.
522
523### Maps (Dictionaries)
524
525Maps store key-value pairs. Unlike lists which use integer indexing, maps use keys of any type.
526
527**Create a map:**
528`Let prices be a new Map of Text to Int.`
529
530**Access a value by key:**
531`Let cost be prices["iron"].`
532
533**Set a value by key:**
534`Set prices["iron"] to 100.`
535
536Maps are useful for lookups, caches, and associating data without needing a struct.
537
538### Bracket Syntax
539
540Both lists and maps support bracket indexing as an alternative to `item X of`:
541
542| English Style | Bracket Style |
543|---------------|---------------|
544| `item 1 of items` | `items[1]` |
545| `item "iron" of prices` | `prices["iron"]` |
546| `Set item "key" of map to val.` | `Set map["key"] to val.` |
547
548Both compile to the same code—use whichever reads better in context.
549
550### Sets
551
552Sets store unique elements with no duplicates. Unlike lists, sets have no order and no index.
553
554**Create a set:**
555`Let numbers be a new Set of Int.`
556
557**Add elements:**
558`Add 5 to numbers.`
559
560**Remove elements:**
561`Remove 5 from numbers.`
562
563**Check membership:**
564`If numbers contains 5:` or `If 5 in numbers:`
565
566**Set operations:**
567- `a union b` — elements in either set
568- `a intersection b` — elements in both sets
569
570### Tuples
571
572Tuples are fixed-size collections that can hold values of different types. Unlike lists, tuples can mix integers, text, and other types in a single collection.
573
574**Create a tuple:**
575`Let point be (10, 20).`
576`Let record be ("Alice", 25, true).`
577
578**Access elements (1-indexed):**
579`Let x be point[1].` or `Let x be item 1 of point.`
580
581**Get length:**
582`Let size be length of record.`
583
584Tuples are useful for returning multiple values from functions or grouping related but differently-typed data without defining a struct.
585"#,
586        examples: &[
587            CodeExample {
588                id: "creating-lists",
589                label: "Creating Lists",
590                mode: ExampleMode::Imperative,
591                code: r#"## Main
592Let numbers be [1, 2, 3, 4, 5].
593Let names be ["Alice", "Bob", "Charlie"].
594Show numbers.
595Show names."#,
596            },
597            CodeExample {
598                id: "accessing-elements",
599                label: "Accessing Elements (1-indexed)",
600                mode: ExampleMode::Imperative,
601                code: r#"## Main
602Let fruits be ["apple", "banana", "cherry"].
603
604Let first be item 1 of fruits.
605Let second be item 2 of fruits.
606Let third be item 3 of fruits.
607
608Show first.
609Show second.
610Show third."#,
611            },
612            CodeExample {
613                id: "push-pop",
614                label: "Push and Pop",
615                mode: ExampleMode::Imperative,
616                code: r#"## Main
617Let numbers be [1, 2, 3].
618Push 4 to numbers.
619Push 5 to numbers.
620Show numbers.
621
622Pop from numbers into last.
623Show last.
624Show numbers."#,
625            },
626            CodeExample {
627                id: "slicing",
628                label: "Slicing (inclusive, 1-based)",
629                mode: ExampleMode::Imperative,
630                code: r#"## Main
631Let fruits be ["apple", "banana", "cherry", "date"].
632Let middle be items 2 through 3 of fruits.
633Show middle."#,
634            },
635            CodeExample {
636                id: "list-iteration",
637                label: "Iterating and Accumulating",
638                mode: ExampleMode::Imperative,
639                code: r#"## Main
640Let numbers be [10, 20, 30, 40, 50].
641Let total be 0.
642
643Repeat for n in numbers:
644    Set total to total + n.
645
646Show "Total: " + total."#,
647            },
648            CodeExample {
649                id: "map-create",
650                label: "Creating Maps",
651                mode: ExampleMode::Imperative,
652                code: r#"## Main
653Let prices be a new Map of Text to Int.
654Set prices["iron"] to 10.
655Set prices["copper"] to 25.
656Set prices["gold"] to 100.
657Show "Iron: " + prices["iron"].
658Show "Copper: " + prices["copper"].
659Show "Gold: " + prices["gold"]."#,
660            },
661            CodeExample {
662                id: "map-access",
663                label: "Map Access",
664                mode: ExampleMode::Imperative,
665                code: r#"## Main
666Let inventory be a new Map of Text to Int.
667Set inventory["wood"] to 50.
668Set inventory["stone"] to 30.
669
670Let wood_count be inventory["wood"].
671Show "Wood: " + wood_count."#,
672            },
673            CodeExample {
674                id: "map-update",
675                label: "Map Update",
676                mode: ExampleMode::Imperative,
677                code: r#"## Main
678Let scores be a new Map of Text to Int.
679Set scores["Alice"] to 100.
680Show "Initial: " + scores["Alice"].
681
682Set scores["Alice"] to 150.
683Show "Updated: " + scores["Alice"]."#,
684            },
685            CodeExample {
686                id: "bracket-syntax",
687                label: "Bracket Syntax",
688                mode: ExampleMode::Imperative,
689                code: r#"## Main
690Let items be [10, 20, 30].
691Let prices be a new Map of Text to Int.
692
693Set prices["iron"] to 5.
694Set prices["gold"] to 100.
695
696Show items[1].
697Show prices["iron"].
698Set items[2] to 99.
699Show items[2]."#,
700            },
701            CodeExample {
702                id: "set-create",
703                label: "Creating Sets",
704                mode: ExampleMode::Imperative,
705                code: r#"## Main
706Let numbers be a new Set of Int.
707Add 1 to numbers.
708Add 2 to numbers.
709Add 3 to numbers.
710Add 1 to numbers.
711Show numbers."#,
712            },
713            CodeExample {
714                id: "set-contains",
715                label: "Set Membership",
716                mode: ExampleMode::Imperative,
717                code: r#"## Main
718Let primes be a new Set of Int.
719Add 2 to primes.
720Add 3 to primes.
721Add 5 to primes.
722Add 7 to primes.
723
724If primes contains 3:
725    Show "3 is prime".
726If primes contains 4:
727    Show "4 is prime".
728Otherwise:
729    Show "4 is not prime"."#,
730            },
731            CodeExample {
732                id: "set-remove",
733                label: "Adding and Removing",
734                mode: ExampleMode::Imperative,
735                code: r#"## Main
736Let colors be a new Set of Text.
737Add "red" to colors.
738Add "green" to colors.
739Add "blue" to colors.
740Show colors.
741
742Remove "green" from colors.
743Show colors."#,
744            },
745            CodeExample {
746                id: "set-operations",
747                label: "Set Operations",
748                mode: ExampleMode::Imperative,
749                code: r#"## Main
750Let a be a new Set of Int.
751Let b be a new Set of Int.
752
753Add 1 to a. Add 2 to a. Add 3 to a.
754Add 2 to b. Add 3 to b. Add 4 to b.
755
756Let both be a intersection b.
757Let either be a union b.
758Show "Intersection: " + both.
759Show "Union: " + either."#,
760            },
761            CodeExample {
762                id: "tuple-create",
763                label: "Creating Tuples",
764                mode: ExampleMode::Imperative,
765                code: r#"## Main
766Let point be (10, 20).
767Let record be ("Alice", 25, true).
768Show point.
769Show record."#,
770            },
771            CodeExample {
772                id: "tuple-access",
773                label: "Accessing Tuple Elements",
774                mode: ExampleMode::Imperative,
775                code: r#"## Main
776Let data be ("answer", 42).
777Let label be data[1].
778Let value be data[2].
779Show label.
780Show value."#,
781            },
782            CodeExample {
783                id: "tuple-mixed",
784                label: "Mixed-Type Tuples",
785                mode: ExampleMode::Imperative,
786                code: r#"## Main
787Let person be ("Bob", 30, 5.9).
788Show item 1 of person.
789Show item 2 of person.
790Show item 3 of person.
791Show length of person."#,
792            },
793        ],
794    },
795
796    Section {
797        id: "user-types",
798        number: 8,
799        title: "User-Defined Types",
800        part: "Part I: Programming in LOGOS",
801        content: r#"
802Beyond primitive types and collections, LOGOS lets you define your own types to model your problem domain.
803
804### Structs
805
806A struct (structure) groups related values together. Define one in a `## Definition` block using `A [TypeName] has:` syntax.
807
808### Creating Instances
809
810Use `a new [Type] with [fields]` to create instances.
811
812### Accessing Fields
813
814Use `'s` (possessive) to access fields.
815
816### Enums
817
818An enum (enumeration) defines a type that can be one of several variants using `A [TypeName] is either:` syntax.
819
820### Pattern Matching
821
822Use `Inspect` to handle different enum variants with `When` clauses.
823"#,
824        examples: &[
825            CodeExample {
826                id: "struct-basic",
827                label: "Basic Struct",
828                mode: ExampleMode::Imperative,
829                code: r#"## Definition
830A Point has:
831    an x: Int.
832    a y: Int.
833
834## Main
835Let p be a new Point with x 10 and y 20.
836Show p's x.
837Show p's y."#,
838            },
839            CodeExample {
840                id: "struct-person",
841                label: "Person Struct",
842                mode: ExampleMode::Imperative,
843                code: r#"## Definition
844A Person has:
845    a name: Text.
846    an age: Int.
847
848## Main
849Let alice be a new Person with name "Alice" and age 25.
850Show alice's name.
851Show alice's age."#,
852            },
853            CodeExample {
854                id: "enum-direction",
855                label: "Simple Enum",
856                mode: ExampleMode::Imperative,
857                code: r#"## Definition
858A Direction is either:
859    North.
860    South.
861    East.
862    West.
863
864## Main
865Let heading be North.
866Show heading."#,
867            },
868            CodeExample {
869                id: "inspect-when",
870                label: "Pattern Matching (Inspect/When)",
871                mode: ExampleMode::Imperative,
872                code: r#"## Definition
873A Direction is either:
874    North.
875    South.
876    East.
877    West.
878
879## Main
880Let heading be East.
881Inspect heading:
882    When North:
883        Show "Heading north".
884    When South:
885        Show "Heading south".
886    When East:
887        Show "Heading east".
888    When West:
889        Show "Heading west"."#,
890            },
891        ],
892    },
893
894    Section {
895        id: "generics",
896        number: 9,
897        title: "Generics",
898        part: "Part I: Programming in LOGOS",
899        content: r#"
900Generics let you write types and functions that work with any type, not just specific ones.
901
902### Generic Types
903
904Define a generic type with `[T]` in the type name. The `[T]` is a placeholder that gets replaced with a real type when you use it.
905
906### Multiple Type Parameters
907
908You can have multiple type parameters like `[A]` and `[B]`.
909
910### Generic Collections
911
912Collections are generic types. `Seq of Int` is a sequence of integers.
913
914### Nested Generics
915
916You can nest generic types like `Seq of (Seq of Int)` for a matrix.
917"#,
918        examples: &[
919            CodeExample {
920                id: "generic-box",
921                label: "Generic Box",
922                mode: ExampleMode::Imperative,
923                code: r#"## Definition
924A Box of [T] has:
925    a contents: T.
926
927## Main
928Let int_box be a new Box of Int with contents 42.
929Let text_box be a new Box of Text with contents "Hello".
930
931Show int_box's contents.
932Show text_box's contents."#,
933            },
934            CodeExample {
935                id: "generic-pair",
936                label: "Generic Pair",
937                mode: ExampleMode::Imperative,
938                code: r#"## Definition
939A Pair of [A] and [B] has:
940    a first: A.
941    a second: B.
942
943## Main
944Let p be a new Pair of Int and Text with first 1 and second "one".
945Show p's first.
946Show p's second."#,
947            },
948        ],
949    },
950
951    Section {
952        id: "memory-ownership",
953        number: 10,
954        title: "Memory and Ownership",
955        part: "Part I: Programming in LOGOS",
956        content: r#"
957LOGOS provides memory safety through an ownership system expressed in natural English. Instead of cryptic symbols, you use verbs that describe what you're doing with data.
958
959### The Three Verbs
960
961| Verb | Meaning | What Happens |
962|------|---------|--------------|
963| `Give` | Transfer ownership | The original variable can no longer be used |
964| `Show` | Temporary read access | The function can look but not modify |
965| `Let modify` | Temporary write access | The function can change the data |
966
967### Ownership Rules
968
9691. **Single Owner:** Every value has exactly one owner at a time
9702. **Move Semantics:** `Give` transfers ownership—you can't use it after
9713. **Borrow Checking:** References (`Show`) can't outlive the owner
9724. **Exclusive Mutation:** Only one `Let modify` at a time
973
974### Common Patterns
975
976- Copy first, then give
977- Show multiple times (all OK - just reading)
978- Sequential mutation
979
980### The `copy of` Expression
981
982Use `copy of` to create a deep clone of a value. This lets you keep using the original while giving away the copy.
983"#,
984        examples: &[
985            CodeExample {
986                id: "ownership-show",
987                label: "Show (Borrow)",
988                mode: ExampleMode::Imperative,
989                code: r#"## To display (data: Text):
990    Show "Displaying: " + data.
991
992## Main
993Let profile be "User Profile Data".
994Show profile to display.
995Show profile."#,
996            },
997            CodeExample {
998                id: "ownership-give",
999                label: "Give (Move Ownership)",
1000                mode: ExampleMode::Imperative,
1001                code: r#"## To consume (data: Text):
1002    Show "Consumed: " + data.
1003
1004## Main
1005Let message be "Important data".
1006Give message to consume.
1007Show "Message was transferred"."#,
1008            },
1009            CodeExample {
1010                id: "ownership-copy",
1011                label: "Copy Before Giving",
1012                mode: ExampleMode::Imperative,
1013                code: r#"## To process (data: Text):
1014    Show "Processing: " + data.
1015
1016## Main
1017Let original be "Keep this".
1018Let duplicate be copy of original.
1019Give duplicate to process.
1020Show "Original still here: " + original."#,
1021            },
1022        ],
1023    },
1024
1025    Section {
1026        id: "zones",
1027        number: 11,
1028        title: "The Zone System",
1029        part: "Part I: Programming in LOGOS",
1030        content: r#"
1031For high-performance scenarios, LOGOS provides **Zones**—memory regions where allocations are fast and cleanup is instant.
1032
1033### Why Zones?
1034
1035| Operation | Normal Heap | Zone |
1036|-----------|-------------|------|
1037| Allocate | O(log n) | O(1) |
1038| Deallocate individual | O(log n) | N/A |
1039| Free everything | O(n) | O(1) |
1040
1041### The Hotel California Rule
1042
1043**"What happens in the Zone, stays in the Zone."**
1044
1045References to zone-allocated data cannot escape. To get data out of a zone, make an explicit copy.
1046
1047### Zone Configuration
1048
1049**Default size:** 4 KB (4096 bytes) when not specified.
1050
1051**Specifying size:** Use `of size` with units:
1052
1053| Unit | Example | Bytes |
1054|------|---------|-------|
1055| B | `of size 256 B` | 256 |
1056| KB | `of size 64 KB` | 65,536 |
1057| MB | `of size 2 MB` | 2,097,152 |
1058| GB | `of size 1 GB` | 1,073,741,824 |
1059
1060### Zone Types
1061
1062| Zone Type | Syntax | Access | Use Case |
1063|-----------|--------|--------|----------|
1064| Heap | `Inside a zone called "X":` | Read/Write | Temporary data |
1065| Heap (sized) | `Inside a zone called "X" of size 2 MB:` | Read/Write | Large temporary data |
1066| Mapped | `Inside a zone called "X" mapped from "file.bin":` | Read-only | Large file processing |
1067
1068### When to Use Zones
1069
1070Use zones when:
1071- Processing large amounts of temporary data
1072- Performance is critical (games, simulations)
1073- Memory allocation patterns are predictable
1074- You want instant cleanup
1075"#,
1076        examples: &[
1077            CodeExample {
1078                id: "zone-basic",
1079                label: "Basic Zone (4KB default)",
1080                mode: ExampleMode::Imperative,
1081                code: r#"## Main
1082Inside a zone called "WorkSpace":
1083    Let temp_data be [1, 2, 3, 4, 5].
1084    Show temp_data.
1085Show "Zone freed!"."#,
1086            },
1087            CodeExample {
1088                id: "zone-sized-mb",
1089                label: "Zone with Size (MB)",
1090                mode: ExampleMode::Imperative,
1091                code: r#"## Main
1092Inside a zone called "LargeBuffer" of size 2 MB:
1093    Let data be [1, 2, 3, 4, 5].
1094    Show data."#,
1095            },
1096            CodeExample {
1097                id: "zone-sized-kb",
1098                label: "Zone with Size (KB)",
1099                mode: ExampleMode::Imperative,
1100                code: r#"## Main
1101Inside a zone called "SmallArena" of size 64 KB:
1102    Let x be 42.
1103    Let y be 100.
1104    Show x + y."#,
1105            },
1106            CodeExample {
1107                id: "zone-mapped",
1108                label: "Memory-Mapped Zone (Compiled Only)",
1109                mode: ExampleMode::Imperative,
1110                code: r#"## To process_file (path: Text):
1111    Inside a zone called "Data" mapped from path:
1112        Show "Processing: " + path.
1113
1114## Main
1115process_file("config.bin").
1116process_file("assets.bin")."#,
1117            },
1118        ],
1119    },
1120
1121    Section {
1122        id: "concurrency",
1123        number: 12,
1124        title: "Concurrency",
1125        part: "Part I: Programming in LOGOS",
1126        content: r#"
1127LOGOS provides safe concurrency through structured patterns. No data races, no deadlocks.
1128
1129### Concurrent Patterns Overview
1130
1131| Pattern | Syntax | Use For | Compiles To |
1132|---------|--------|---------|-------------|
1133| **Async Join** | `Attempt all of the following:` | Wait for all I/O tasks | tokio::join! |
1134| **Parallel CPU** | `Simultaneously:` | CPU-bound computation | rayon::join / threads |
1135| **Spawn Task** | `Launch a task to...` | Fire-and-forget work | tokio::spawn |
1136| **Channels** | `Pipe of Type` | Message passing | tokio::mpsc |
1137| **Select** | `Await the first of:` | Race operations | tokio::select! |
1138
1139### Attempt All (Async I/O)
1140
1141Use `Attempt all of the following:` for I/O operations that wait on external resources. All operations run concurrently, and the program waits until all complete.
1142
1143Variables declared in concurrent blocks are captured and returned as a tuple.
1144
1145### Simultaneously (Parallel CPU)
1146
1147Use `Simultaneously:` for CPU-intensive work. Computations run in parallel on different CPU cores.
1148
1149- 2 tasks → uses `rayon::join` (work-stealing thread pool)
1150- 3+ tasks → uses `std::thread::spawn` (dedicated threads)
1151
1152### Tasks (Green Threads)
1153
1154Use `Launch a task to...` to spawn a green thread that runs concurrently. For fire-and-forget work, just launch:
1155
1156`Launch a task to process(data).`
1157
1158To control the task later (cancel, await), capture a handle:
1159
1160`Let worker be Launch a task to process(data).`
1161
1162Stop a running task with:
1163
1164`Stop worker.`
1165
1166### Channels (Pipes)
1167
1168Pipes are Go-style channels for message passing between tasks.
1169
1170**Create a channel:**
1171`Let jobs be a new Pipe of Int.`
1172
1173**Send into a channel (blocking):**
1174`Send value into jobs.`
1175
1176**Receive from a channel (blocking):**
1177`Receive item from jobs.`
1178
1179**Non-blocking variants:**
1180`Try to send value into jobs.`
1181`Try to receive item from jobs.`
1182
1183### Select (Racing Operations)
1184
1185Use `Await the first of:` to race multiple operations. The first one to complete wins:
1186
1187```
1188Await the first of:
1189    Receive msg from inbox:
1190        Show msg.
1191    After 5 seconds:
1192        Show "timeout".
1193```
1194
1195**Branch types:**
1196- `Receive var from pipe:` — wait for channel message
1197- `After N seconds:` — timeout branch
1198
1199### Ownership and Concurrency
1200
1201The ownership system prevents data races. Multiple reads are OK, but concurrent writes are prevented.
1202
1203**Note:** Tasks, Pipes, and Select require compilation—they don't run in the browser playground.
1204"#,
1205        examples: &[
1206            CodeExample {
1207                id: "concurrent-async",
1208                label: "Async Concurrent (Attempt All)",
1209                mode: ExampleMode::Imperative,
1210                code: r#"## Main
1211Attempt all of the following:
1212    Let a be 10.
1213    Let b be 20.
1214Show "a = " + a.
1215Show "b = " + b.
1216Show "Sum: " + (a + b)."#,
1217            },
1218            CodeExample {
1219                id: "parallel-cpu",
1220                label: "Parallel CPU (Simultaneously)",
1221                mode: ExampleMode::Imperative,
1222                code: r#"## Main
1223Simultaneously:
1224    Let x be 100.
1225    Let y be 200.
1226Show "x = " + x.
1227Show "y = " + y.
1228Show "Product: " + (x * y)."#,
1229            },
1230            CodeExample {
1231                id: "parallel-three-tasks",
1232                label: "Three Parallel Tasks",
1233                mode: ExampleMode::Imperative,
1234                code: r#"## Main
1235Simultaneously:
1236    Let a be 1.
1237    Let b be 2.
1238    Let c be 3.
1239Show "Sum: " + (a + b + c)."#,
1240            },
1241            CodeExample {
1242                id: "concurrent-in-function",
1243                label: "Concurrency in Functions",
1244                mode: ExampleMode::Imperative,
1245                code: r#"## To compute_parallel -> Int:
1246    Simultaneously:
1247        Let x be 5.
1248        Let y be 10.
1249    Return x + y.
1250
1251## Main
1252Let result be compute_parallel().
1253Show "Result: " + result."#,
1254            },
1255            CodeExample {
1256                id: "launch-task",
1257                label: "Launch Task (Compiled Only)",
1258                mode: ExampleMode::Imperative,
1259                code: r#"## To worker (id: Int):
1260    Show "Worker " + id + " started".
1261
1262## Main
1263Launch a task to worker(1).
1264Launch a task to worker(2).
1265Show "Tasks launched"."#,
1266            },
1267            CodeExample {
1268                id: "task-with-handle",
1269                label: "Task with Handle (Compiled Only)",
1270                mode: ExampleMode::Imperative,
1271                code: r#"## To long_running:
1272    Show "Working...".
1273
1274## Main
1275Let job be Launch a task to long_running.
1276Show "Task spawned".
1277Stop job.
1278Show "Task cancelled"."#,
1279            },
1280            CodeExample {
1281                id: "pipe-send-receive",
1282                label: "Pipe Communication (Compiled Only)",
1283                mode: ExampleMode::Imperative,
1284                code: r#"## Main
1285Let messages be a new Pipe of Int.
1286Send 42 into messages.
1287Send 100 into messages.
1288Receive x from messages.
1289Show "Got: " + x."#,
1290            },
1291            CodeExample {
1292                id: "select-timeout",
1293                label: "Select with Timeout (Compiled Only)",
1294                mode: ExampleMode::Imperative,
1295                code: r#"## Main
1296Let inbox be a new Pipe of Text.
1297
1298Await the first of:
1299    Receive msg from inbox:
1300        Show "Message: " + msg.
1301    After 2 seconds:
1302        Show "No message received"."#,
1303            },
1304        ],
1305    },
1306
1307    Section {
1308        id: "crdt",
1309        number: 13,
1310        title: "Distributed Types (CRDTs)",
1311        part: "Part I: Programming in LOGOS",
1312        content: r#"
1313### What are CRDTs?
1314
1315CRDTs (Conflict-free Replicated Data Types) are data structures that can be replicated across multiple computers and merged without coordination. No matter what order updates arrive, the final state converges to the same result.
1316
1317### Why CRDTs Matter
1318
1319| Challenge | Traditional Approach | CRDT Approach |
1320|-----------|---------------------|---------------|
1321| Network partition | Data loss or conflicts | Automatic merge |
1322| Concurrent edits | Last-write-wins (data loss) | Semantic merge |
1323| Offline support | Sync conflicts | Seamless reconciliation |
1324
1325### Shared Structs
1326
1327Mark a struct as `Shared` to enable automatic merge support. The compiler generates a `merge` method that combines two instances.
1328
1329### Built-in CRDT Types
1330
1331| Type | Description | Operations |
1332|------|-------------|------------|
1333| `ConvergentCount` | Counter that only grows | `Increase` |
1334| `Tally` | Counter that grows and shrinks | `Increase`, `Decrease` |
1335| `LastWriteWins of T` | Register with timestamp-based conflict resolution | `Set` |
1336| `Divergent T` | Register that preserves concurrent values | `Set`, `Resolve` |
1337| `SharedSet of T` | Set with add/remove support | `Add`, `Remove`, `contains` |
1338| `SharedSequence of T` | Ordered list (RGA algorithm) | `Append`, `length of` |
1339| `CollaborativeSequence of T` | Text-optimized sequence (YATA) | `Append`, `length of` |
1340| `SharedMap from K to V` | Key-value CRDT map | `[]` access and assignment |
1341
1342### ConvergentCount
1343
1344A grow-only counter (G-Counter). Multiple replicas can increment independently, and when merged, the total reflects all increments. Useful for view counts, likes, or any monotonically increasing metric.
1345
1346### Tally
1347
1348A bidirectional counter (PN-Counter) that supports both increment and decrement. Unlike ConvergentCount, values can go up and down—even negative. Useful for scores, balances, and temperatures.
1349
1350### LastWriteWins
1351
1352A register that resolves conflicts by timestamp. The most recent write wins. Works with any type: `Text`, `Int`, `Bool`, etc.
1353
1354### Divergent
1355
1356A multi-value register that preserves all concurrent writes instead of silently picking a winner. When replicas write different values concurrently, both are kept until you explicitly `Resolve` the conflict. Useful for collaborative editing where conflicts should be visible.
1357
1358### SharedSet
1359
1360An observed-remove set (OR-Set) that supports both adding and removing elements. By default uses **add-wins** semantics: if one replica adds while another removes, the element stays.
1361
1362**Configuring bias:**
1363- `SharedSet (AddWins) of T` — concurrent add beats remove (default)
1364- `SharedSet (RemoveWins) of T` — concurrent remove beats add
1365
1366### SharedSequence
1367
1368An ordered CRDT list using the RGA (Replicated Growable Array) algorithm. Elements maintain their order across replicas. Useful for ordered lists, chat history, and document lines.
1369
1370### CollaborativeSequence
1371
1372A text-optimized sequence using the YATA algorithm. Better conflict resolution for concurrent insertions at the same position. Ideal for collaborative text editing. Alternative syntax: `SharedSequence (YATA) of T`.
1373
1374### SharedMap
1375
1376A key-value CRDT map (OR-Map). Keys can be added and removed, and values are themselves CRDTs that merge recursively. Alternative syntax: `ORMap from K to V`.
1377
1378### Merge Operations
1379
1380Use `Merge source into target` to combine two CRDT instances. The target is updated in place with the merged state.
1381
1382### Persistence
1383
1384CRDTs can be persisted to disk using the `Persistent` type modifier and `Mount` statement. Data is stored in append-only journal files (`.lsf` format) with automatic compaction.
1385
1386**The Persistent Type:**
1387
1388`Persistent Counter` wraps a Shared struct with journaling. All mutations are durably recorded.
1389
1390**The Mount Statement:**
1391
1392`Mount [variable] at [path].`
1393
1394or
1395
1396`Let x be mounted at "path/to/data.lsf".`
1397
1398This loads existing state from the journal file (if present) or creates a new one. Changes are automatically persisted.
1399
1400### Network Synchronization
1401
1402CRDTs become powerful when synchronized across the network. Use `Sync` to subscribe a variable to a GossipSub topic.
1403
1404**The Sync Statement:**
1405
1406`Sync [variable] on [topic].`
1407
1408- `variable` — A mutable variable containing a Shared struct
1409- `topic` — A string or variable naming the GossipSub topic
1410
1411**What Sync Does:**
14121. Subscribes to the topic for incoming messages
14132. Spawns a background task to merge incoming updates
14143. Broadcasts the full state after any mutation
1415
1416### Persistence + Network
1417
1418For the best of both worlds, combine `Persistent` types with `Sync`. The Distributed runtime ensures:
1419- Local changes are journaled before broadcast
1420- Remote updates are merged and persisted
1421- Data survives restarts
1422
1423**Note:** Programs using `Sync` or `Mount` require compilation—they don't run in the browser playground.
1424"#,
1425        examples: &[
1426            CodeExample {
1427                id: "crdt-basic",
1428                label: "Basic Shared Struct",
1429                mode: ExampleMode::Imperative,
1430                code: r#"## Definition
1431A Counter is Shared and has:
1432    a points, which is ConvergentCount.
1433
1434## Main
1435Let c be a new Counter.
1436Increase c's points by 10.
1437Show c's points."#,
1438            },
1439            CodeExample {
1440                id: "crdt-lww",
1441                label: "Last-Write-Wins Register",
1442                mode: ExampleMode::Imperative,
1443                code: r#"## Definition
1444A Profile is Shared and has:
1445    a name, which is LastWriteWins of Text.
1446    a score, which is LastWriteWins of Int.
1447
1448## Main
1449Let p be a new Profile.
1450Set p's name to "Alice".
1451Set p's score to 100.
1452Show p's name.
1453Show p's score."#,
1454            },
1455            CodeExample {
1456                id: "crdt-merge",
1457                label: "Merging Replicas",
1458                mode: ExampleMode::Imperative,
1459                code: r#"## Definition
1460A Stats is Shared and has:
1461    a views, which is ConvergentCount.
1462
1463## Main
1464Let local be a new Stats.
1465Increase local's views by 100.
1466
1467Let remote be a new Stats.
1468Increase remote's views by 50.
1469
1470Merge remote into local.
1471Show local's views."#,
1472            },
1473            CodeExample {
1474                id: "crdt-sync-counter",
1475                label: "Synced Counter (Compiled Only)",
1476                mode: ExampleMode::Imperative,
1477                code: r#"## Definition
1478A GameScore is Shared and has:
1479    a points, which is ConvergentCount.
1480
1481## Main
1482Let mutable score be a new GameScore.
1483Sync score on "game-leaderboard".
1484Increase score's points by 100.
1485Show score's points."#,
1486            },
1487            CodeExample {
1488                id: "crdt-sync-profile",
1489                label: "Synced Profile (Compiled Only)",
1490                mode: ExampleMode::Imperative,
1491                code: r#"## Definition
1492A Profile is Shared and has:
1493    a name, which is LastWriteWins of Text.
1494    a level, which is ConvergentCount.
1495
1496## Main
1497Let mutable p be a new Profile.
1498Sync p on "player-data".
1499Increase p's level by 1.
1500Show p's level."#,
1501            },
1502            CodeExample {
1503                id: "crdt-persistent",
1504                label: "Persistent Counter (Compiled Only)",
1505                mode: ExampleMode::Imperative,
1506                code: r#"## Definition
1507A Counter is Shared and has:
1508    a value, which is ConvergentCount.
1509
1510## Main
1511Let mutable c: Persistent Counter be mounted at "counter.lsf".
1512Increase c's value by 1.
1513Show c's value."#,
1514            },
1515            CodeExample {
1516                id: "crdt-tally",
1517                label: "Tally (Bidirectional Counter)",
1518                mode: ExampleMode::Imperative,
1519                code: r#"## Definition
1520A Score is Shared and has:
1521    a points, which is a Tally.
1522
1523## Main
1524Let mutable s be a new Score.
1525Increase s's points by 100.
1526Decrease s's points by 30.
1527Show s's points."#,
1528            },
1529            CodeExample {
1530                id: "crdt-divergent",
1531                label: "Divergent (Multi-Value Register)",
1532                mode: ExampleMode::Imperative,
1533                code: r#"## Definition
1534A WikiPage is Shared and has:
1535    a title, which is Divergent Text.
1536
1537## Main
1538Let mutable page be a new WikiPage.
1539Set page's title to "Draft".
1540Show page's title.
1541Resolve page's title to "Final".
1542Show page's title."#,
1543            },
1544            CodeExample {
1545                id: "crdt-sharedset",
1546                label: "SharedSet (Add/Remove Set)",
1547                mode: ExampleMode::Imperative,
1548                code: r#"## Definition
1549A Party is Shared and has:
1550    a guests, which is a SharedSet of Text.
1551
1552## Main
1553Let mutable p be a new Party.
1554Add "Alice" to p's guests.
1555Add "Bob" to p's guests.
1556Remove "Alice" from p's guests.
1557If p's guests contains "Bob":
1558    Show "Bob is invited".
1559Show length of p's guests."#,
1560            },
1561            CodeExample {
1562                id: "crdt-sharedset-bias",
1563                label: "SharedSet with Bias",
1564                mode: ExampleMode::Imperative,
1565                code: r#"## Definition
1566A Moderation is Shared and has:
1567    a tags, which is a SharedSet (AddWins) of Text.
1568    a blocked, which is a SharedSet (RemoveWins) of Text.
1569
1570## Main
1571Let mutable m be a new Moderation.
1572Add "safe" to m's tags.
1573Add "spammer" to m's blocked.
1574Show m's tags.
1575Show m's blocked."#,
1576            },
1577            CodeExample {
1578                id: "crdt-sequence",
1579                label: "SharedSequence (Ordered List)",
1580                mode: ExampleMode::Imperative,
1581                code: r#"## Definition
1582A Document is Shared and has:
1583    a lines, which is a SharedSequence of Text.
1584
1585## Main
1586Let mutable doc be a new Document.
1587Append "Line 1" to doc's lines.
1588Append "Line 2" to doc's lines.
1589Append "Line 3" to doc's lines.
1590Show length of doc's lines."#,
1591            },
1592            CodeExample {
1593                id: "crdt-collaborative",
1594                label: "CollaborativeSequence (Text)",
1595                mode: ExampleMode::Imperative,
1596                code: r#"## Definition
1597A Editor is Shared and has:
1598    a text, which is a CollaborativeSequence of Text.
1599
1600## Main
1601Let mutable e be a new Editor.
1602Append "Hello" to e's text.
1603Append " " to e's text.
1604Append "World" to e's text.
1605Show length of e's text."#,
1606            },
1607            CodeExample {
1608                id: "crdt-sharedmap",
1609                label: "SharedMap (Key-Value CRDT)",
1610                mode: ExampleMode::Imperative,
1611                code: r#"## Definition
1612A Inventory is Shared and has:
1613    an items, which is a SharedMap from Text to Int.
1614
1615## Main
1616Let mutable inv be a new Inventory.
1617Set inv's items["wood"] to 50.
1618Set inv's items["stone"] to 30.
1619Show inv's items["wood"]."#,
1620            },
1621        ],
1622    },
1623
1624    Section {
1625        id: "security",
1626        number: 14,
1627        title: "Policy-Based Security",
1628        part: "Part I: Programming in LOGOS",
1629        content: r#"
1630### Security in Natural Language
1631
1632LOGOS lets you express security policies as natural English sentences. These compile into efficient runtime checks that can never be optimized away.
1633
1634### Policy Blocks
1635
1636Define security rules in `## Policy` blocks. Policies define **predicates** (conditions on a single entity) and **capabilities** (permissions involving multiple entities).
1637
1638### Predicates
1639
1640A predicate is a boolean condition on a subject:
1641
1642`A User is admin if the user's role equals "admin".`
1643
1644This generates a method `is_admin()` on the User type.
1645
1646### Capabilities
1647
1648A capability defines what a subject can do with an object:
1649
1650`A User can publish the Document if the user is admin.`
1651
1652This generates a method `can_publish(&Document)` on the User type.
1653
1654### Check Statements
1655
1656Use `Check` to enforce security at runtime. **Unlike `Assert`, Check statements are mandatory and can never be optimized away.**
1657
1658| Statement | Debug Build | Release Build |
1659|-----------|-------------|---------------|
1660| `Assert` | Runs | Can be optimized out |
1661| `Check` | Runs | **Always runs** |
1662
1663### Policy Composition
1664
1665Policies can use `AND` and `OR` to combine conditions, and can reference other predicates.
1666"#,
1667        examples: &[
1668            CodeExample {
1669                id: "security-predicate",
1670                label: "Simple Predicate",
1671                mode: ExampleMode::Imperative,
1672                code: r#"## Definition
1673A User has:
1674    a role: Text.
1675
1676## Policy
1677A User is admin if the user's role equals "admin".
1678
1679## Main
1680Let u be a new User with role "admin".
1681Check that u is admin.
1682Show "Access granted"."#,
1683            },
1684            CodeExample {
1685                id: "security-capability",
1686                label: "Capability with Object",
1687                mode: ExampleMode::Imperative,
1688                code: r#"## Definition
1689A User has:
1690    a name: Text.
1691    a role: Text.
1692
1693A Document has:
1694    an owner: Text.
1695
1696## Policy
1697A User is admin if the user's role equals "admin".
1698A User can edit the Document if:
1699    The user is admin, OR
1700    The user's name equals the document's owner.
1701
1702## Main
1703Let alice be a new User with name "Alice" and role "editor".
1704Let doc be a new Document with owner "Alice".
1705Check that alice can edit doc.
1706Show "Edit permitted"."#,
1707            },
1708        ],
1709    },
1710
1711    Section {
1712        id: "networking",
1713        number: 15,
1714        title: "P2P Networking",
1715        part: "Part I: Programming in LOGOS",
1716        content: r#"
1717LOGOS includes built-in peer-to-peer networking primitives for building distributed applications.
1718
1719**Note:** Networking features require compilation—they don't run in the browser playground.
1720
1721### Core Concepts
1722
1723| Concept | Description |
1724|---------|-------------|
1725| **Address** | libp2p multiaddr format: `/ip4/127.0.0.1/tcp/8000` |
1726| **Listen** | Bind to an address to accept connections |
1727| **Connect** | Dial a peer at an address |
1728| **PeerAgent** | A handle to a remote peer |
1729| **Send** | Transmit a message to a peer |
1730| **Sync** | Subscribe a CRDT to a GossipSub topic |
1731
1732### Portable Types
1733
1734Messages sent over the network must be **Portable**. Mark your struct with `is Portable` to enable network serialization.
1735
1736### Address Format
1737
1738LOGOS uses libp2p multiaddresses:
1739
1740| Address | Meaning |
1741|---------|---------|
1742| `/ip4/0.0.0.0/tcp/8000` | Listen on all interfaces, port 8000 |
1743| `/ip4/127.0.0.1/tcp/8000` | Localhost only, port 8000 |
1744| `/ip4/192.168.1.5/tcp/8000` | Specific IP address |
1745| `/ip4/0.0.0.0/tcp/0` | Listen on any available port |
1746
1747### Automatic Peer Discovery (mDNS)
1748
1749When you `Listen`, LOGOS automatically enables **mDNS** (multicast DNS) for local network peer discovery. Peers on the same LAN will discover each other without manual configuration.
1750
1751- Works on WiFi networks, local development
1752- No configuration required—just Listen
1753- Peers are auto-connected when discovered
1754
1755### GossipSub (Pub/Sub)
1756
1757The `Sync` statement uses **GossipSub**, a pub/sub protocol for broadcasting messages to topic subscribers:
1758
1759- Topics are strings (e.g., `"game-scores"`, `"player-data"`)
1760- When you mutate a synced variable, the full state broadcasts to all subscribers
1761- Incoming messages are automatically merged in the background
1762- Retry with exponential backoff: 1s, 2s, 4s, 8s, 16s
1763
1764### File Transfer
1765
1766For large file transfers, LOGOS provides **FileSipper**—a chunked transfer protocol:
1767
1768| Component | Description |
1769|-----------|-------------|
1770| **FileSipper** | Zero-copy file chunker (1 MB default chunks) |
1771| **FileManifest** | Describes file: chunk count, SHA256 hashes |
1772| **FileChunk** | Individual chunk with verification hash |
1773
1774This enables resumable transfers over unreliable networks.
1775
1776### Building a P2P Application
1777
17781. Define Portable message types
17792. Listen on an address (server)
17803. Connect to peers (client)
17814. Create PeerAgent handles
17825. Send messages
17836. Use `Sync` for automatic CRDT replication
1784"#,
1785        examples: &[
1786            CodeExample {
1787                id: "network-listen",
1788                label: "Server: Listen for Connections",
1789                mode: ExampleMode::Imperative,
1790                code: r#"## Main
1791Listen on "/ip4/0.0.0.0/tcp/8000".
1792Show "Server listening on port 8000"."#,
1793            },
1794            CodeExample {
1795                id: "network-connect",
1796                label: "Client: Connect to Peer",
1797                mode: ExampleMode::Imperative,
1798                code: r#"## Main
1799Let server_addr be "/ip4/127.0.0.1/tcp/8000".
1800Connect to server_addr.
1801Show "Connected to server"."#,
1802            },
1803            CodeExample {
1804                id: "network-peer-agent",
1805                label: "Creating a Remote Handle",
1806                mode: ExampleMode::Imperative,
1807                code: r#"## Main
1808Let remote be a PeerAgent at "/ip4/127.0.0.1/tcp/8000".
1809Show "Remote peer handle created"."#,
1810            },
1811            CodeExample {
1812                id: "network-send-message",
1813                label: "Sending a Message",
1814                mode: ExampleMode::Imperative,
1815                code: r#"## Definition
1816A Greeting is Portable and has:
1817    a message (Text).
1818
1819## Main
1820Let remote be a PeerAgent at "/ip4/127.0.0.1/tcp/8000".
1821Let msg be a new Greeting with message "Hello, peer!".
1822Show "Sending: " + msg's message.
1823Send msg to remote."#,
1824            },
1825            CodeExample {
1826                id: "network-distributed",
1827                label: "Persistent + Synced (Compiled Only)",
1828                mode: ExampleMode::Imperative,
1829                code: r#"## Definition
1830A Counter is Shared and has:
1831    a value, which is ConvergentCount.
1832
1833## Main
1834Listen on "/ip4/0.0.0.0/tcp/0".
1835Let mutable c: Persistent Counter be mounted at "counter.lsf".
1836Sync c on "shared-counter".
1837Increase c's value by 1.
1838Show c's value."#,
1839            },
1840            CodeExample {
1841                id: "network-mdns",
1842                label: "Automatic Peer Discovery",
1843                mode: ExampleMode::Imperative,
1844                code: r#"## Definition
1845A GameState is Shared and has:
1846    a score, which is ConvergentCount.
1847
1848## Main
1849Listen on "/ip4/0.0.0.0/tcp/0".
1850Show "Listening... mDNS will auto-discover peers".
1851
1852Let mutable state be a new GameState.
1853Sync state on "game-session".
1854Show "Synced to game-session topic"."#,
1855            },
1856            CodeExample {
1857                id: "network-file-transfer",
1858                label: "File Transfer Pattern",
1859                mode: ExampleMode::Imperative,
1860                code: r#"## Definition
1861A FileRequest is Portable and has:
1862    a filename: Text.
1863    a chunk_index: Int.
1864
1865A FileResponse is Portable and has:
1866    a data: Text.
1867    a is_last: Bool.
1868
1869## Main
1870Listen on "/ip4/0.0.0.0/tcp/8000".
1871Show "File server ready".
1872Show "Supports resumable chunked transfers"."#,
1873            },
1874        ],
1875    },
1876
1877    Section {
1878        id: "error-handling",
1879        number: 16,
1880        title: "Error Handling",
1881        part: "Part I: Programming in LOGOS",
1882        content: r#"
1883LOGOS uses **Socratic error messages**—friendly, educational feedback that teaches while it corrects.
1884
1885### The Philosophy
1886
1887Instead of cryptic compiler errors, LOGOS explains:
18881. **What** went wrong
18892. **Where** it happened
18903. **Why** it's a problem
18914. **How** to fix it
1892
1893### The Failure Type
1894
1895Functions that might fail return a `Result`. Use pattern matching to handle success and failure cases.
1896
1897### Error Propagation
1898
1899Errors propagate naturally through return values. Handle them where appropriate.
1900
1901### Defensive Programming
1902
1903Use assertions and guards to prevent errors before they happen.
1904"#,
1905        examples: &[
1906            CodeExample {
1907                id: "defensive-divide",
1908                label: "Safe Division with Guard",
1909                mode: ExampleMode::Imperative,
1910                code: r#"## To safe_divide (a: Int) and (b: Int) -> Int:
1911    If b equals 0:
1912        Show "Error: Cannot divide by zero".
1913        Return 0.
1914    Return a / b.
1915
1916## Main
1917Let result be safe_divide(10, 2).
1918Show "10 / 2 = " + result.
1919Let bad be safe_divide(5, 0).
1920Show "Result after error: " + bad."#,
1921            },
1922            CodeExample {
1923                id: "validation-example",
1924                label: "Input Validation",
1925                mode: ExampleMode::Imperative,
1926                code: r#"## To validate_age (age: Int) -> Bool:
1927    If age is less than 0:
1928        Show "Error: Age cannot be negative".
1929        Return false.
1930    If age is greater than 150:
1931        Show "Error: Age seems unrealistic".
1932        Return false.
1933    Return true.
1934
1935## Main
1936Let valid be validate_age(25).
1937Show "Age 25 valid: " + valid.
1938Let invalid be validate_age(-5).
1939Show "Age -5 valid: " + invalid."#,
1940            },
1941            CodeExample {
1942                id: "result-pattern",
1943                label: "Success/Failure with Pattern Matching",
1944                mode: ExampleMode::Imperative,
1945                code: r#"## Definition
1946An Outcome is either:
1947    Success (value: Int).
1948    Failure (message: Text).
1949
1950## To checked_halve (n: Int) -> Outcome:
1951    If n is less than 0:
1952        Return a new Failure with message "cannot halve a negative".
1953    Return a new Success with value (n / 2).
1954
1955## Main
1956Let good be checked_halve(10).
1957Inspect good:
1958    When Success (v):
1959        Show "Halved: " + v.
1960    When Failure (m):
1961        Show "Error: " + m.
1962
1963Let bad be checked_halve(-4).
1964Inspect bad:
1965    When Success (v):
1966        Show "Halved: " + v.
1967    When Failure (m):
1968        Show "Error: " + m."#,
1969            },
1970        ],
1971    },
1972
1973    Section {
1974        id: "advanced-features",
1975        number: 17,
1976        title: "Advanced Features",
1977        part: "Part I: Programming in LOGOS",
1978        content: r#"
1979### Refinement Types
1980
1981Refinement types add constraints to base types. The constraint is checked at runtime or compile time with Z3.
1982
1983### Assertions
1984
1985Use `Assert` to verify conditions in your code. If the assertion fails, the program stops with an error message.
1986
1987### Trust with Reason
1988
1989Use `Trust` when you know something is true but the compiler can't verify it. The `because` clause documents why you believe the condition holds.
1990
1991### Modules
1992
1993Organize code across multiple files with `Use`.
1994"#,
1995        examples: &[
1996            CodeExample {
1997                id: "refinement-types",
1998                label: "Refinement Types",
1999                mode: ExampleMode::Imperative,
2000                code: r#"## Main
2001Let positive: Int where it > 0 be 5.
2002Let percentage: Int where it >= 0 and it <= 100 be 85.
2003Show positive.
2004Show percentage."#,
2005            },
2006            CodeExample {
2007                id: "assertions",
2008                label: "Assertions",
2009                mode: ExampleMode::Imperative,
2010                code: r#"## To divide_safe (a: Int) and (b: Int) -> Int:
2011    Assert that b is not 0.
2012    Return a / b.
2013
2014## Main
2015Let result be divide_safe(10, 2).
2016Show result."#,
2017            },
2018        ],
2019    },
2020
2021    // ============================================================
2022    // Part II: Project Structure (Sections 18-20)
2023    // ============================================================
2024
2025    Section {
2026        id: "modules",
2027        number: 18,
2028        title: "Modules",
2029        part: "Part II: Project Structure",
2030        content: r#"
2031Organize large programs across multiple files using the module system.
2032
2033### Importing Modules
2034
2035Use `Use` to import a module.
2036
2037### Qualified Access
2038
2039Access module contents with the possessive `'s`.
2040
2041### Creating Modules
2042
2043Each `.md` file is a module. The filename becomes the module name.
2044
2045### Visibility
2046
2047By default, all definitions are public. Mark fields private with no `public` modifier.
2048"#,
2049        examples: &[
2050            CodeExample {
2051                id: "module-import",
2052                label: "Importing Modules (Compiled Only)",
2053                mode: ExampleMode::Imperative,
2054                code: r#"## To square (n: Int) -> Int:
2055    Return n * n.
2056
2057## Main
2058Let x be 5.
2059Let result be square(x).
2060Show "5 squared = " + result."#,
2061            },
2062        ],
2063    },
2064
2065    Section {
2066        id: "cli-largo",
2067        number: 19,
2068        title: "The CLI: largo",
2069        part: "Part II: Project Structure",
2070        content: r#"
2071LOGOS projects are built with `largo`, the LOGOS build tool.
2072
2073### Installing
2074
2075```bash
2076curl -fsSL https://logicaffeine.com/install.sh | sh
2077```
2078
2079Windows: `powershell -ExecutionPolicy Bypass -c "irm https://logicaffeine.com/install.ps1 | iex"`.
2080Prebuilt for Linux/macOS (x64 + arm64) and Windows x64, SHA-256-verified, installed to
2081`~/.local/bin` with no sudo. `--full` bundles Z3 static verification.
2082
2083### Creating a Project
2084
2085| Command | Description |
2086|---------|-------------|
2087| `largo new <name>` | Create a new project in a new directory |
2088| `largo init` | Initialize a project in the current directory |
2089
2090This creates a `Largo.toml` manifest and `src/main.lg` entry point.
2091
2092### Build Commands
2093
2094| Command | Description |
2095|---------|-------------|
2096| `largo build` | Compile the project to a native binary |
2097| `largo build --release` | Compile with optimizations |
2098| `largo run` | Build and run |
2099| `largo run --interpret` | Run on the interpreter—no Rust build, sub-second feedback |
2100| `largo run --release` | Build and run with optimizations |
2101| `largo check` | Type-check without compiling |
2102| `largo verify` | Run Z3 static verification (Pro+ license required) |
2103| `largo build --verify` | Build with verification |
2104| `largo build --target wasm` | Cross-compile to WebAssembly |
2105| `largo opts <file>` | Report which optimizations actually fire |
2106
2107### The Wider Verbs
2108
2109| Command | Description |
2110|---------|-------------|
2111| `largo repl` | Interactive session: imperative statements + English→FOL logic mode |
2112| `largo logic "<sentence>"` | English → First-Order Logic (`--all-readings`, `--format latex`) |
2113| `largo prove [file]` | Kernel-certified theorem proving (`## Theory` / `## Theorem` blocks) |
2114| `largo sat <file.cnf>` | The certified SAT solver (DIMACS in, DRAT proofs out) |
2115| `largo fmt [--check]` | Format sources (the LSP's rules) |
2116| `largo emit <rust\|c\|wasm>` | Print or write the generated code |
2117| `largo doc` | Generate markdown docs from a project's `##` blocks |
2118| `largo add / remove <dep>` | Edit `Largo.toml` dependencies (format-preserving) |
2119| `largo clean` | Remove build artifacts |
2120| `largo completions <shell>` | Shell tab-completion scripts |
2121
2122### Package Registry
2123
2124Publish and manage packages on the LOGOS registry:
2125
2126| Command | Description |
2127|---------|-------------|
2128| `largo login` | Authenticate with the registry |
2129| `largo publish` | Publish your package |
2130| `largo publish --dry-run` | Validate without publishing |
2131| `largo logout` | Log out from the registry |
2132
2133### Project Manifest
2134
2135The `Largo.toml` file defines package metadata and dependencies:
2136
2137```toml
2138[package]
2139name = "myproject"
2140version = "0.1.0"
2141entry = "src/main.lg"
2142
2143[dependencies]
2144```
2145"#,
2146        examples: &[],
2147    },
2148
2149    Section {
2150        id: "stdlib",
2151        number: 20,
2152        title: "Standard Library",
2153        part: "Part II: Project Structure",
2154        content: r#"
2155LOGOS provides built-in functions for common operations.
2156
2157### Currently Available
2158
2159These built-ins work in both the playground and compiled programs:
2160
2161- `Show x.` — Output values to the console
2162- `length of x` — Get the length of a list or text
2163- `format(x)` — Convert any value to text
2164- `abs(n)` — Absolute value of a number
2165- `min(a, b)` — Minimum of two integers
2166- `max(a, b)` — Maximum of two integers
2167
2168### Coming Soon
2169
2170Additional modules are planned for future releases:
2171
2172- **File** — `read`, `write`, `exists` for file operations
2173- **Time** — `now`, `sleep` for timing and delays
2174- **Random** — `randomInt`, `randomFloat`, `choice`
2175- **Env** — Environment variables and command-line arguments
2176
2177These will be available in compiled programs. Some features may have limited support in the browser playground due to WASM constraints.
2178"#,
2179        examples: &[
2180            CodeExample {
2181                id: "stdlib-example",
2182                label: "Standard Library",
2183                mode: ExampleMode::Imperative,
2184                code: r#"## Main
2185Let nums be [5, -3, 8, -1, 4].
2186Let text be "Hello".
2187
2188Show "Built-in functions:".
2189Show "length of nums = " + format(length of nums).
2190Show "length of text = " + format(length of text).
2191Show "abs(-42) = " + format(abs(-42)).
2192Show "min(10, 3) = " + format(min(10, 3)).
2193Show "max(10, 3) = " + format(max(10, 3))."#,
2194            },
2195        ],
2196    },
2197
2198    // ============================================================
2199    // Part III: Logic Mode (Section 21)
2200    // ============================================================
2201
2202    Section {
2203        id: "logic-mode",
2204        number: 21,
2205        title: "Logic Mode",
2206        part: "Part III: Logic Mode",
2207        content: r#"
2208LOGOS can translate English sentences into First-Order Logic (FOL). This is useful for formal verification, knowledge representation, and understanding the logical structure of natural language.
2209
2210### Quantifiers
2211
2212| English | Symbol | Output |
2213|---------|--------|--------|
2214| All X are Y | `∀` | `∀x(X(x) → Y(x))` |
2215| Some X is Y | `∃` | `∃x(X(x) ∧ Y(x))` |
2216| No X is Y | `¬∃` | `¬∃x(X(x) ∧ Y(x))` |
2217
2218### Connectives
2219
2220| English | Symbol |
2221|---------|--------|
2222| and | `∧` |
2223| or | `∨` |
2224| not | `¬` |
2225| if...then | `→` |
2226| if and only if | `↔` |
2227
2228### Modals
2229
2230| English | Symbol |
2231|---------|--------|
2232| can, may, might | `◇` (possibility) |
2233| must | `□` (necessity) |
2234
2235### Tense and Aspect
2236
2237- `PAST(P)` — past tense
2238- `FUT(P)` — future tense
2239- `PROG(P)` — progressive aspect
2240- `PERF(P)` — perfect aspect
2241"#,
2242        examples: &[
2243            CodeExample {
2244                id: "logic-universal",
2245                label: "Universal Quantifier",
2246                mode: ExampleMode::Logic,
2247                code: "All birds fly.",
2248            },
2249            CodeExample {
2250                id: "logic-existential",
2251                label: "Existential Quantifier",
2252                mode: ExampleMode::Logic,
2253                code: "Some cats sleep.",
2254            },
2255            CodeExample {
2256                id: "logic-negative",
2257                label: "Negative Quantifier",
2258                mode: ExampleMode::Logic,
2259                code: "No fish fly.",
2260            },
2261            CodeExample {
2262                id: "logic-conditional",
2263                label: "Conditional",
2264                mode: ExampleMode::Logic,
2265                code: "If John runs, then Mary walks.",
2266            },
2267            CodeExample {
2268                id: "logic-modal",
2269                label: "Modal Operators",
2270                mode: ExampleMode::Logic,
2271                code: "John can swim.",
2272            },
2273        ],
2274    },
2275
2276    // ============================================================
2277    // Part IV: Proofs and Verification (Sections 22-23)
2278    // ============================================================
2279
2280    Section {
2281        id: "assertions-trust",
2282        number: 22,
2283        title: "Assertions and Trust",
2284        part: "Part IV: Proofs and Verification",
2285        content: r#"
2286LOGOS bridges imperative programming with formal verification through assertions and proof statements.
2287
2288### Assert
2289
2290Use `Assert` to verify conditions at runtime. If an assertion fails, the program stops with a clear error message.
2291
2292### Trust with Justification
2293
2294Use `Trust` for conditions the compiler can't verify automatically. The `because` clause is **mandatory**—it documents your reasoning.
2295
2296### Trust Generates Debug Assertions
2297
2298In development builds, `Trust` becomes a `debug_assert!`. In release builds, it generates no code—the trust is assumed.
2299
2300### Auditing Trust Statements
2301
2302Every `Trust` stays a plain `Trust that ... because ...` line in your source—search for `Trust that` to review every assumption, each carrying the `because` justification that documents why it holds.
2303
2304### Proof Blocks (Advanced)
2305
2306For formal verification, use theorem blocks with proofs documented in comments.
2307"#,
2308        examples: &[
2309            CodeExample {
2310                id: "assert-example",
2311                label: "Assert",
2312                mode: ExampleMode::Imperative,
2313                code: r#"## To withdraw (amount: Int) from (balance: Int) -> Int:
2314    Assert that amount is greater than 0.
2315    Assert that amount is at most balance.
2316    Return balance - amount.
2317
2318## Main
2319Let result be withdraw(50, 100).
2320Show result."#,
2321            },
2322            CodeExample {
2323                id: "trust-example",
2324                label: "Trust with Justification",
2325                mode: ExampleMode::Imperative,
2326                code: r#"## To process_positive (n: Int) -> Int:
2327    Trust that n is greater than 0 because "caller guarantees positive input".
2328    Return n * 2.
2329
2330## Main
2331Let result be process_positive(5).
2332Show result."#,
2333            },
2334        ],
2335    },
2336
2337    Section {
2338        id: "z3-verification",
2339        number: 23,
2340        title: "Z3 Static Verification",
2341        part: "Part IV: Proofs and Verification",
2342        content: r#"
2343LOGOS can use the Z3 SMT solver to verify refinement types at compile time.
2344
2345### What is Z3?
2346
2347Z3 is a theorem prover. Instead of checking constraints at runtime, Z3 proves (or disproves) them at compile time.
2348
2349| Approach | When Checked | If Violated |
2350|----------|--------------|-------------|
2351| Runtime assertion | When code runs | Program crashes |
2352| Z3 verification | At compile time | Compilation fails |
2353
2354### Variable Tracking
2355
2356Z3 tracks constraints through variable assignments.
2357
2358### Compound Predicates
2359
2360Multiple constraints can be combined.
2361
2362### Function Preconditions
2363
2364Z3 verifies function contracts.
2365
2366### Enabling Z3 Verification
2367
2368Enable with `largo build --verify` or in `Largo.toml`.
2369
2370### What Z3 Can Prove
2371
2372| Constraint Type | Example | Z3 Support |
2373|-----------------|---------|------------|
2374| Integer bounds | `it > 0`, `it < 100` | Full |
2375| Equality | `it == 5` | Full |
2376| Arithmetic | `it * 2 < 100` | Full |
2377| Boolean logic | `it > 0 and it < 10` | Full |
2378"#,
2379        examples: &[
2380            CodeExample {
2381                id: "z3-refinement",
2382                label: "Z3 Refinement Types",
2383                mode: ExampleMode::Imperative,
2384                code: r#"## Main
2385Let positive: Int where it > 0 be 5.
2386Let bounded: Int where it >= 0 and it <= 100 be 85.
2387Show "Positive: " + positive.
2388Show "Bounded: " + bounded."#,
2389            },
2390        ],
2391    },
2392
2393    // ============================================================
2394    // Part V: Reference (Sections 24-25)
2395    // ============================================================
2396
2397    Section {
2398        id: "complete-examples",
2399        number: 24,
2400        title: "Complete Examples",
2401        part: "Part V: Reference",
2402        content: r#"
2403This section contains complete, runnable programs demonstrating various LOGOS features.
2404
2405### Factorial
2406
2407A classic recursive function.
2408
2409### Fibonacci
2410
2411Recursion combined with a `While` loop to print a sequence.
2412
2413### Filtering a Collection
2414
2415Iterating a list with `Repeat for`, guarding with `If`, and accumulating into a new `Seq`.
2416"#,
2417        examples: &[
2418            CodeExample {
2419                id: "example-factorial",
2420                label: "Factorial",
2421                mode: ExampleMode::Imperative,
2422                code: r#"## To factorial (n: Int) -> Int:
2423    If n is at most 1:
2424        Return 1.
2425    Return n * factorial(n - 1).
2426
2427## Main
2428Let result be factorial(5).
2429Show "5! = " + result."#,
2430            },
2431            CodeExample {
2432                id: "example-fibonacci",
2433                label: "Fibonacci",
2434                mode: ExampleMode::Imperative,
2435                code: r#"## To fib (n: Int) -> Int:
2436    If n is at most 1:
2437        Return n.
2438    Return fib(n - 1) + fib(n - 2).
2439
2440## Main
2441Show "Fibonacci sequence:".
2442Let i be 0.
2443While i is less than 10:
2444    Show fib(i).
2445    Set i to i + 1."#,
2446            },
2447            CodeExample {
2448                id: "example-filter",
2449                label: "Filter Positive Numbers",
2450                mode: ExampleMode::Imperative,
2451                code: r#"## Main
2452Let data be [-2, 5, -1, 8, 3, -4, 7].
2453Let positives be a new Seq of Int.
2454
2455Repeat for n in data:
2456    If n is greater than 0:
2457        Push n to positives.
2458
2459Show "Positives: " + positives."#,
2460            },
2461        ],
2462    },
2463
2464    Section {
2465        id: "quick-reference",
2466        number: 25,
2467        title: "Quick Reference",
2468        part: "Part V: Reference",
2469        content: r#"
2470### Syntax Cheat Sheet
2471
2472**Variables:**
2473- `Let x be 5.` — Create variable
2474- `Set x to 10.` — Change variable
2475- `Let x: Int be 5.` — With type annotation
2476
2477**Control Flow:**
2478- `If condition:` ... `Otherwise:` — Conditional
2479- `While condition:` — While loop
2480- `Repeat for item in items:` — For-each loop
2481- `Return value.` — Return from function
2482
2483**Functions:**
2484- `## To name (param: Type) -> ReturnType:` — Define function
2485
2486**Structs:**
2487- `A TypeName has:` ... — Define struct
2488- `Let x be a new TypeName with field1 value1.` — Create instance
2489- `x's field` — Access field
2490
2491**Enums:**
2492- `A TypeName is either:` ... — Define enum
2493- `Inspect x: When Variant:` ... — Pattern match
2494
2495**Primitive Types:**
2496
2497| Type | Description | Examples |
2498|------|-------------|----------|
2499| `Int` | Whole numbers | `5`, `-10`, `0` |
2500| `Bool` | True or false | `true`, `false` |
2501| `Text` | Strings | `"Hello"`, `""` |
2502| `Float` / `Real` | Decimals | `3.14`, `-0.5` |
2503| `Char` | Single character | backtick syntax |
2504| `Byte` | 8-bit unsigned | `42: Byte`, `255: Byte` |
2505
2506**Lists (Seq):**
2507- `[1, 2, 3]` — List literal
2508- `item 1 of items` or `items[1]` — Access (1-indexed)
2509- `Push value to items.` — Add to end
2510- `length of items` — Get length
2511
2512**Maps:**
2513- `Map of K to V` — Map type (key-value pairs)
2514- `a new Map of Text to Int` — Create empty map
2515- `item "key" of map` or `map["key"]` — Get value by key
2516- `Set item "key" of map to val.` or `Set map["key"] to val.` — Set value
2517
2518**Sets:**
2519- `Set of T` — Set type (unique elements)
2520- `a new Set of Int` — Create empty set
2521- `Add x to set.` — Add element
2522- `Remove x from set.` — Remove element
2523- `set contains x` — Check membership
2524- `a union b` — Elements in either set
2525- `a intersection b` — Elements in both sets
2526
2527**Tuples:**
2528- `(1, "two", 3.0)` — Tuple literal (mixed types allowed)
2529- `t[1]` or `item 1 of t` — Access (1-indexed)
2530- `length of t` — Get tuple size
2531
2532### Ownership Verbs
2533
2534| Verb | Meaning |
2535|------|---------|
2536| `Give x to f.` | Move ownership |
2537| `Show x to f.` | Borrow (read) |
2538| `Let f modify x.` | Mutable borrow |
2539| `copy of x` | Clone |
2540
2541### Zones
2542
2543**Basic syntax:**
2544- `Inside a zone called "Name":` — 4KB default zone
2545- `Inside a zone called "Name" of size 2 MB:` — Sized heap zone
2546- `Inside a zone called "Name" mapped from "file.bin":` — Memory-mapped file
2547
2548**Size units:** B, KB, MB, GB
2549
2550### Concurrency
2551
2552**Async I/O:**
2553- `Attempt all of the following:` — Concurrent async tasks (tokio::join!)
2554
2555**Parallel CPU:**
2556- `Simultaneously:` — Parallel computation (rayon/threads)
2557
2558**Tasks (Compiled Only):**
2559- `Launch a task to f(args).` — Fire-and-forget spawn
2560- `Let h be Launch a task to f(args).` — Spawn with handle
2561- `Stop h.` — Abort a running task
2562
2563**Channels/Pipes (Compiled Only):**
2564- `Let p be a new Pipe of Int.` — Create bounded channel
2565- `Send x into p.` — Blocking send
2566- `Receive x from p.` — Blocking receive
2567- `Try to send/receive` — Non-blocking variants
2568
2569**Select (Compiled Only):**
2570- `Await the first of:` — Race multiple operations
2571- `Receive x from p:` — Channel receive branch
2572- `After N seconds:` — Timeout branch
2573
2574### Distributed Types (CRDTs)
2575
2576**Shared Structs:**
2577- `A Counter is Shared and has:` — CRDT-enabled struct
2578
2579**CRDT Field Types:**
2580- `ConvergentCount` — Grow-only counter (`Increase`)
2581- `Tally` — Bidirectional counter (`Increase`, `Decrease`)
2582- `LastWriteWins of T` — Timestamp-based register (`Set`)
2583- `Divergent T` — Multi-value register (`Set`, `Resolve`)
2584- `SharedSet of T` — Add/remove set (`Add`, `Remove`, `contains`)
2585- `SharedSet (AddWins) of T` — Set where add wins conflicts
2586- `SharedSet (RemoveWins) of T` — Set where remove wins conflicts
2587- `SharedSequence of T` — Ordered list RGA (`Append`)
2588- `CollaborativeSequence of T` — Text-optimized YATA (`Append`)
2589- `SharedSequence (YATA) of T` — Alternate YATA syntax
2590- `SharedMap from K to V` — Key-value CRDT (`[]` access)
2591- `ORMap from K to V` — Alternate map syntax
2592
2593**CRDT Operations:**
2594- `Increase x's field by amount.` — Increment counter
2595- `Decrease x's field by amount.` — Decrement Tally
2596- `Set x's field to value.` — Set register value
2597- `Resolve x's field to value.` — Resolve Divergent conflict
2598- `Add value to x's field.` — Add to SharedSet
2599- `Remove value from x's field.` — Remove from SharedSet
2600- `Append value to x's field.` — Append to sequence
2601- `Merge source into target.` — Combine two CRDT instances
2602
2603**Persistence (Compiled Only):**
2604- `Persistent Counter` — Type with automatic journaling
2605- `Let x be mounted at "data.lsf".` — Load/create persistent CRDT
2606- `Mount x at "path".` — Mount statement for persistence
2607
2608**Network Sync (Compiled Only):**
2609- `Sync mutable_var on "topic".` — Subscribe to GossipSub topic for auto-sync
2610
2611### P2P Networking
2612
2613**Server/Client:**
2614- `Listen on "/ip4/0.0.0.0/tcp/8000".` — Bind to address
2615- `Listen on "/ip4/0.0.0.0/tcp/0".` — Listen on any available port
2616- `Connect to addr.` — Dial a peer
2617- `Let remote be a PeerAgent at addr.` — Create remote handle
2618- `Send msg to remote.` — Transmit message
2619
2620**Portable Types:**
2621- `A Message is Portable and has:` — Network-serializable struct
2622
2623**Automatic Discovery:**
2624- mDNS auto-discovers peers on local network when you Listen
2625- Peers are automatically connected when discovered
2626
2627**GossipSub (via Sync):**
2628- Topics broadcast state changes to all subscribers
2629- Retry with exponential backoff (1s, 2s, 4s, 8s, 16s)
2630
2631**File Transfer:**
2632- FileSipper for chunked transfers (1 MB chunks)
2633- FileManifest with SHA256 hashes for verification
2634- Enables resumable transfers
2635
2636### Security
2637
2638**Policy Blocks:**
2639- `## Policy` — Define security rules
2640- `A User is admin if...` — Define a predicate
2641- `A User can edit the Doc if...` — Define a capability
2642
2643**Security Enforcement:**
2644- `Check that user is admin.` — Mandatory runtime check (never optimized out)
2645- `Assert that x > 0.` — Debug-only assertion (can be optimized out)
2646
2647### Logic Mode Symbols
2648
2649| English | Symbol |
2650|---------|--------|
2651| All | `∀` |
2652| Some | `∃` |
2653| and | `∧` |
2654| or | `∨` |
2655| not | `¬` |
2656| if...then | `→` |
2657| can/may | `◇` |
2658| must | `□` |
2659"#,
2660        examples: &[],
2661    },
2662];
2663
2664/// Get all sections
2665pub fn get_all_sections() -> &'static [Section] {
2666    SECTIONS
2667}
2668
2669/// Get sections by part
2670pub fn get_sections_by_part(part: &str) -> Vec<&'static Section> {
2671    SECTIONS.iter().filter(|s| s.part == part).collect()
2672}
2673
2674/// Get a section by ID
2675pub fn get_section_by_id(id: &str) -> Option<&'static Section> {
2676    SECTIONS.iter().find(|s| s.id == id)
2677}
2678
2679/// Get all unique part names in order
2680pub fn get_parts() -> Vec<&'static str> {
2681    let mut parts = Vec::new();
2682    for section in SECTIONS {
2683        if parts.last() != Some(&section.part) {
2684            parts.push(section.part);
2685        }
2686    }
2687    parts
2688}