Skip to main content

logicaffeine_language/
teach.rs

1//! The lesson table for LOGOS constructs: every lesson a surface shows
2//! (LSP hover, completion documentation, the REPL's `:explain`) comes from
3//! this table, so the editor and the terminal always teach the same thing.
4//!
5//! A [`ConstructDoc`] is complete by construction: the type has no optional
6//! teaching fields, so an entry cannot exist without a plain-English
7//! sentence, a runnable example, and a socratic question or tip. The
8//! `doc_for` match is wildcard-free (the `token_class` idiom): adding a
9//! `TokenType` variant does not compile until someone decides whether it
10//! deserves a lesson — the decision lives here, next to the enum, not in an
11//! editor plugin. `doc_for_block` is total: every `##` block type teaches.
12
13use crate::token::{BlockType, TokenType};
14
15/// A complete lesson for one construct. Every field is required by the TYPE —
16/// an entry cannot exist without a plain sentence, a runnable example, and a
17/// socratic question or tip. Clear-and-easy is structural, not aspirational.
18pub struct ConstructDoc {
19    /// The construct's display name ("Give", "Main", "Seq").
20    pub name: &'static str,
21    /// ONE plain sentence: what it does. Kept under 90 characters by the
22    /// teach lock — if it needs more, the rest belongs in the question/tip.
23    pub what: &'static str,
24    /// A runnable snippet (code-block body, no fences). Must lex.
25    pub example: &'static str,
26    /// The socratic seat: a guiding question (contains `?`) or an explicit
27    /// `Tip:` — it leads the reader to the next insight, never just restates.
28    pub question_or_tip: &'static str,
29    /// A LOGOS_QUICKGUIDE.md heading slug for "read more", when one fits.
30    pub guide_anchor: Option<&'static str>,
31}
32
33const fn lesson(
34    name: &'static str,
35    what: &'static str,
36    example: &'static str,
37    question_or_tip: &'static str,
38    guide_anchor: Option<&'static str>,
39) -> ConstructDoc {
40    ConstructDoc {
41        name,
42        what,
43        example,
44        question_or_tip,
45        guide_anchor,
46    }
47}
48
49// ---------------------------------------------------------------------------
50// Statement keywords
51// ---------------------------------------------------------------------------
52
53static LET: ConstructDoc = lesson(
54    "Let",
55    "Declares a new variable.",
56    "Let x be 5.\nLet name: Text be \"Alice\".",
57    "Will the value change later? Then declare it `Let mutable x be 5.` — plain `Let` is immutable.",
58    Some("2-variables--mutation"),
59);
60
61static SET_KW: ConstructDoc = lesson(
62    "Set",
63    "Updates an existing mutable variable.",
64    "Set x to 10.",
65    "Was `x` declared with `Let mutable`? Only mutable bindings can be `Set`.",
66    Some("2-variables--mutation"),
67);
68
69static SWAP_KW: ConstructDoc = lesson(
70    "Swap",
71    "Exchanges two variables' values — the zero-garbage REVERSIBLE primitive (its own inverse).",
72    "Swap x and y.",
73    "Are both `x` and `y` defined? Swap runs backward with no history — it reverses at the Landauer floor.",
74    Some("2-variables--mutation"),
75);
76
77static RETURN: ConstructDoc = lesson(
78    "Return",
79    "Hands a value back from the current function.",
80    "Return x.",
81    "Does the value's type match the function's declared `-> Type`? `Return.` alone returns nothing.",
82    Some("6-control-flow"),
83);
84
85static IF: ConstructDoc = lesson(
86    "If",
87    "Runs a block only when its condition holds.",
88    "If x > 0:\n    Show x.\nOtherwise:\n    Show 0.",
89    "What should happen when the condition is false — nothing, an `Otherwise:` branch, or an `elif`?",
90    Some("6-control-flow"),
91);
92
93static WHILE: ConstructDoc = lesson(
94    "While",
95    "Repeats a block as long as its condition stays true.",
96    "While x > 0:\n    Set x to x - 1.",
97    "Does the body change the condition? A body that never does loops forever — `(decreasing e)` proves termination.",
98    Some("6-control-flow"),
99);
100
101static REPEAT: ConstructDoc = lesson(
102    "Repeat",
103    "Walks a collection, binding each element in turn.",
104    "Repeat for item in items:\n    Show item.",
105    "Need positions instead of elements? Count with `for i from 1 to n:` — LOGOS is 1-based.",
106    Some("5-collections"),
107);
108
109static SHOW: ConstructDoc = lesson(
110    "Show",
111    "Displays a value while only borrowing it — you keep ownership.",
112    "Show x.",
113    "Need the value afterward? `Show` lends; `Give` transfers — pick by who owns it next.",
114    Some("13-output"),
115);
116
117static GIVE: ConstructDoc = lesson(
118    "Give",
119    "Transfers ownership of a value to a new owner.",
120    "Give x to processor.",
121    "Who should own this value afterward — you, or the receiver? Keep it by giving `a copy of x`.",
122    Some("13-output"),
123);
124
125static PUSH: ConstructDoc = lesson(
126    "Push",
127    "Appends a value to the end of a sequence.",
128    "Push 5 to items.",
129    "Tip: `Push` grows a Seq by one; for Sets use `Add v to s.` — sets have no order to push onto.",
130    Some("5-collections"),
131);
132
133static INSPECT: ConstructDoc = lesson(
134    "Inspect",
135    "Pattern-matches a value, running one branch per variant.",
136    "Inspect shape:\n    When Circle (r):\n        Show r.\n    Otherwise:\n        Show \"other\".",
137    "Is every variant handled? `Otherwise:` catches the rest — or list each `When` and let the checker verify.",
138    Some("6-control-flow"),
139);
140
141static CALL: ConstructDoc = lesson(
142    "Call",
143    "Invokes a function as a statement.",
144    "Call process with data.",
145    "Tip: in expressions call directly — `add(3, 7)`; `Call f with a and b.` is the statement form.",
146    Some("7-functions--closures"),
147);
148
149static NEW: ConstructDoc = lesson(
150    "New",
151    "Creates a struct or variant instance with named field values.",
152    "Let p be a new Point with x 10 and y 20.",
153    "Tip: fields are set by name — `with x 10 and y 20` — so argument order never bites.",
154    Some("8-structs-enums--field-access"),
155);
156
157static ESCAPE: ConstructDoc = lesson(
158    "Escape",
159    "Embeds raw foreign code, skipping every LOGOS checker.",
160    "Escape to Rust:\n    println!(\"hello\");",
161    "Could plain LOGOS express this? Escaped code is invisible to the ownership and type checkers.",
162    None,
163);
164
165static CHECK: ConstructDoc = lesson(
166    "Check",
167    "Enforces a security capability at runtime — a mandatory gate.",
168    "Check that balance is at least amount.",
169    "What may this code path do, and who says so? `## Policy` blocks define the capabilities.",
170    Some("10-contracts-refinement-assert-trust-check"),
171);
172
173static POP: ConstructDoc = lesson(
174    "Pop",
175    "Removes the last element of a sequence.",
176    "Pop from xs.\nPop from xs into y.",
177    "Need the popped value? `Pop from xs into y.` binds it; plain `Pop` discards it.",
178    Some("5-collections"),
179);
180
181static ADD: ConstructDoc = lesson(
182    "Add",
183    "Inserts a value into a set.",
184    "Add v to s.",
185    "Tip: sets keep one of each value — adding a duplicate changes nothing, and order is not kept.",
186    Some("5-collections"),
187);
188
189static REMOVE: ConstructDoc = lesson(
190    "Remove",
191    "Deletes a value from a set, or every item of a list that matches a condition.",
192    "Remove v from s.\nRemove every t from todos where t's done.",
193    "Tip: removing a value that isn't present is a quiet no-op — test `s contains v` when it matters.",
194    Some("5-collections"),
195);
196
197static BREAK: ConstructDoc = lesson(
198    "Break",
199    "Exits the innermost loop immediately.",
200    "While true:\n    Break.",
201    "Which loop should stop? `Break.` only leaves the innermost one.",
202    Some("6-control-flow"),
203);
204
205static ASSERT: ConstructDoc = lesson(
206    "Assert",
207    "Checks a condition at runtime, failing loudly when it is false.",
208    "Assert that x is equal to 42.",
209    "Is this a debugging aid or a security rule? Debug checks `Assert`; mandatory gates use `Check`.",
210    Some("10-contracts-refinement-assert-trust-check"),
211);
212
213static TRUST: ConstructDoc = lesson(
214    "Trust",
215    "States a justified assumption, carrying its reason.",
216    "Trust that x is greater than 0 because \"set to 10\".",
217    "Why is this safe? The `because` reason is required — future readers hold you to it.",
218    Some("10-contracts-refinement-assert-trust-check"),
219);
220
221static INCREASE: ConstructDoc = lesson(
222    "Increase",
223    "Grows a shared CRDT counter field — merges without conflicts.",
224    "Increase c's points by 10.",
225    "Tip: `Increase` is for `Shared` CRDT fields; plain integers update with `Set i to i + 1.`",
226    Some("12-distributed-crdt-concurrency-networking-zones"),
227);
228
229static DECREASE: ConstructDoc = lesson(
230    "Decrease",
231    "Shrinks a shared CRDT counter field — merges without conflicts.",
232    "Decrease g's score by 30.",
233    "Tip: `Decrease` is for `Shared` CRDT fields; plain integers update with `Set i to i - 1.`",
234    Some("12-distributed-crdt-concurrency-networking-zones"),
235);
236
237static SPAWN: ConstructDoc = lesson(
238    "Spawn",
239    "Starts an agent — an independent concurrent actor.",
240    "Spawn an EchoAgent called \"echo\".",
241    "How will you reach it later? The `called \"name\"` handle is how messages find the agent.",
242    Some("12-distributed-crdt-concurrency-networking-zones"),
243);
244
245static MOUNT: ConstructDoc = lesson(
246    "Mount",
247    "Brings a component into the document, or a CRDT onto a journal file.",
248    "Mount App at \"#root\".\nMount counter at \"data/counter.journal\".",
249    "What is being mounted — a component or a CRDT? A component paints and runs its load handlers once (`Mount App.` takes the whole document); a CRDT loads its journal and writes every later change back to it.",
250    None,
251);
252
253static MERGE: ConstructDoc = lesson(
254    "Merge",
255    "Folds one CRDT replica into another without conflicts.",
256    "Merge remote into local.",
257    "Tip: merge order never matters — replicas converge to the same state either way.",
258    Some("12-distributed-crdt-concurrency-networking-zones"),
259);
260
261static CONVERGE: ConstructDoc = lesson(
262    "Converge",
263    "Joins one CRDT replica into another by the idempotent lattice join.",
264    "Converge remote into local.",
265    "Tip: unlike Merge (which adds bare-Int fields), Converge takes their MAX — applying it twice equals once.",
266    Some("12-distributed-crdt-concurrency-networking-zones"),
267);
268
269// ---------------------------------------------------------------------------
270// Block headers
271// ---------------------------------------------------------------------------
272
273static BLOCK_MAIN: ConstructDoc = lesson(
274    "Main",
275    "The program's entry point — statements here run top to bottom.",
276    "## Main\nShow \"Hello, World!\".",
277    "Tip: one `## Main` per program; everything else is definitions it can call.",
278    Some("1-program-structure"),
279);
280
281static BLOCK_FUNCTION: ConstructDoc = lesson(
282    "To",
283    "Defines a function; parameters and return type live in the header.",
284    "## To add (a: Int, b: Int) -> Int:\n    Return a + b.",
285    "What does it give back? `-> Type` declares it; omit the arrow for a procedure.",
286    Some("7-functions--closures"),
287);
288
289static BLOCK_COMPONENT: ConstructDoc = lesson(
290    "Component",
291    "A piece of a page: its own State, the Actions that may change it, and the View it renders.",
292    "## Component Counter\nState:\n    Let count be 0.\nActions:\n    To add:\n        Set count to count + 1.\nView:\n    <button on-click={add}>{count}</button>",
293    "What state does it own, and what does its view read? Each instance keeps its own record, so placing it twice places two independent counters.",
294    Some("7-functions--closures"),
295);
296
297static BLOCK_THEOREM: ConstructDoc = lesson(
298    "Theorem",
299    "Declares a proposition to be proved.",
300    "## Theorem: Socrates\nGiven: All men are mortal. Socrates is a man.\nProve: Socrates is mortal.\nProof: Auto.",
301    "What structure does the claim have — universal, implication, equality? The proof strategy follows it.",
302    Some("1-program-structure"),
303);
304
305static BLOCK_PROOF: ConstructDoc = lesson(
306    "Proof",
307    "Holds the proof steps for the theorem above it.",
308    "Proof: Auto.",
309    "Stuck? Start with `Auto.` — the prover reports what it can and cannot discharge.",
310    None,
311);
312
313static BLOCK_DEFINITION: ConstructDoc = lesson(
314    "Definition",
315    "Introduces new terminology for later sentences to use.",
316    "## Definition: A bachelor is an unmarried man.",
317    "Tip: `## Definition` explains terms; executable data shapes live in `## A ... has:` blocks.",
318    None,
319);
320
321static BLOCK_DEFINE: ConstructDoc = lesson(
322    "Define",
323    "Mints a predicate the prover can unfold by definition.",
324    "## Define: A number is tiny if it is less than 10.",
325    "Tip: proofs may unfold this exactly — the prover substitutes the body for the name.",
326    None,
327);
328
329static BLOCK_AXIOM: ConstructDoc = lesson(
330    "Axiom",
331    "Declares a named formal axiom as a shared premise.",
332    "## Axiom cong_refl: for all a b, Cong(a,b,b,a).",
333    "Tip: axioms are believed, not proved — keep them few and inspectable.",
334    None,
335);
336
337static BLOCK_THEORY: ConstructDoc = lesson(
338    "Theory",
339    "Names a development grouping the axioms and theorems after it.",
340    "## Theory Tarski",
341    "Tip: a theory bundles `## Axiom`s with the `## Theorem`s proved from them.",
342    None,
343);
344
345static BLOCK_TYPEDEF: ConstructDoc = lesson(
346    "TypeDef",
347    "Defines a struct or enum type in English.",
348    "## A Point has:\n    An x: Int.\n    A y: Int.",
349    "One thing with fields, or one of several shapes? `has:` makes a struct; `is one of:` an enum.",
350    Some("8-structs-enums--field-access"),
351);
352
353static BLOCK_POLICY: ConstructDoc = lesson(
354    "Policy",
355    "Defines the security rules that `Check` statements enforce.",
356    "## Policy\nUsers can read public files.",
357    "Who may do what? Policies name capabilities; `Check that ...` gates on them.",
358    Some("10-contracts-refinement-assert-trust-check"),
359);
360
361static BLOCK_LOGIC: ConstructDoc = lesson(
362    "Logic",
363    "Holds direct logical notation instead of English.",
364    "## Logic\nforall x. Man(x) -> Mortal(x)",
365    "Tip: use it when symbols say it better — English and notation share one prover.",
366    None,
367);
368
369static BLOCK_EXAMPLE: ConstructDoc = lesson(
370    "Example",
371    "Shows an illustrative example the compiler treats as documentation.",
372    "## Example\nShow 42.",
373    "Tip: examples read as prose — the highlighter fades them so code stands out.",
374    None,
375);
376
377static BLOCK_NOTE: ConstructDoc = lesson(
378    "Note",
379    "Documentation prose the compiler skips and the highlighter fades.",
380    "## Note\nThis module parses dates.",
381    "Tip: a `## Note` right above a definition becomes that definition's documentation.",
382    None,
383);
384
385static BLOCK_REQUIRES: ConstructDoc = lesson(
386    "Requires",
387    "Declares external crate dependencies for escaped code.",
388    "## Requires\nserde",
389    "Tip: only `Escape` blocks need this — pure LOGOS programs never do.",
390    None,
391);
392
393static BLOCK_HARDWARE: ConstructDoc = lesson(
394    "Hardware",
395    "Declares hardware signals for verification.",
396    "## Hardware\nclk is a signal.",
397    "What are the inputs and state bits? Properties below verify against exactly these signals.",
398    None,
399);
400
401static BLOCK_PROPERTY: ConstructDoc = lesson(
402    "Property",
403    "States temporal assertions about hardware signals.",
404    "## Property\nThe counter is eventually zero.",
405    "Always or eventually? Temporal words carry the meaning — the prover checks every cycle.",
406    None,
407);
408
409static BLOCK_TEST: ConstructDoc = lesson(
410    "Test",
411    "Declares an independent test named by its prose; the body checks with `Expect that`.",
412    "## Test: Addition carries correctly\nLet x be 1 plus 1.\nExpect that x is 2.",
413    "What should be true when this test ends? Say it with `Expect that` — every expectation is checked, and failures report together.",
414    None,
415);
416
417static BLOCK_PAGE: ConstructDoc = lesson(
418    "Page",
419    "A page component served at a URL path; its State, Actions, View and Style follow.",
420    "## Page /todos\nState:\n    Let count be 0.\nView:\n    <p>{count}</p>",
421    "Which URL should reach this page, and what must it learn from that URL? `## Page /todos/:id (id: Int)` binds a path parameter.",
422    None,
423);
424
425static BLOCK_STORE: ConstructDoc = lesson(
426    "Store",
427    "Shared state plus the only actions that may change it, usable from many components.",
428    "## Store Session\nState:\n    Let name be \"guest\".\nActions:\n    To login (who: Text):\n        Set name to who.",
429    "Which components need this state? Each writes `Use Session.` and reads `Session's name`; only the store's own actions change it.",
430    None,
431);
432
433static BLOCK_SESSION: ConstructDoc = lesson(
434    "Session",
435    "The fields a visitor's session carries between requests, held in one signed cookie.",
436    "## Session\n    a user, which is Text.\n\n## Route POST /login (name: Text) -> Response:\n    Set the session's user to name.\n    Return redirectTo(\"/\").",
437    "What must this visitor still be true of on their NEXT request? Only that belongs in a session — it rides in a cookie, so keep it small and never secret.",
438    None,
439);
440
441static BLOCK_DIRECTIVE: ConstructDoc = lesson(
442    "Directive",
443    "A custom attribute: code that runs on an element when the attribute appears or changes.",
444    "## Directive tooltip (el: Element) and (text: Text):\n    Set the attribute \"title\" of el to text.",
445    "What should the element do when this value changes? Write it once here and use `tooltip={…}` on any element.",
446    None,
447);
448
449static BLOCK_ROUTE: ConstructDoc = lesson(
450    "Route",
451    "A typed HTTP route: method, path with `:params`, typed inputs, and a JSON return value.",
452    "## Route GET /api/todos/:id (id: Int) -> Result of Todo and HttpError:\n    Return findTodo(id).",
453    "What does the client receive on success, and which status when the id is unknown? A `Result` return names both.",
454    None,
455);
456
457static BLOCK_MIDDLEWARE: ConstructDoc = lesson(
458    "Before each request",
459    "Runs before every route; return `some(response)` to answer early or `none` to pass.",
460    "## Before each request (request: Request) -> Option of Response:\n    Return none.",
461    "Which requests must never reach a handler? Answer them here with `some(unauthorized())`.",
462    None,
463);
464
465static BLOCK_REDIRECT: ConstructDoc = lesson(
466    "Redirect",
467    "Sends an old path permanently to a new one.",
468    "## Redirect /old-todos -> /todos.",
469    "Tip: a redirect keeps old links alive when a page moves — the browser lands on the new path.",
470    None,
471);
472
473static BLOCK_ERROR_PAGE: ConstructDoc = lesson(
474    "Error page",
475    "The view served for an HTTP error status.",
476    "## Error page 404\nView:\n    <h1>Nothing here</h1>",
477    "What helps a lost visitor most — a search box, the home link, or both? This view is theirs.",
478    None,
479);
480
481static EXPECT_STMT: ConstructDoc = lesson(
482    "Expect",
483    "A test expectation: checks a condition, records any failure, and keeps going.",
484    "Expect that the balance is at least 0.",
485    "Is this a test observation or a runtime guard? `Expect that` lives in tests; in ordinary code use `Require that`.",
486    None,
487);
488
489static ADVANCE_STMT: ConstructDoc = lesson(
490    "Advance",
491    "Moves a test's virtual clock forward instantly — no real waiting.",
492    "Advance time by 3 seconds.",
493    "Tip: tests never wait — the clock is sealed and virtual, so a timeout test finishes in microseconds.",
494    None,
495);
496
497static SKIP_STMT: ConstructDoc = lesson(
498    "Skip",
499    "Skips a test loudly: the reason is mandatory and every skip counts as a debt.",
500    "Skip this test because \"the flag has not shipped\".",
501    "Why is this test off? The reason travels with the skip, and the budget for skips only shrinks.",
502    None,
503);
504
505static NOTE_STMT: ConstructDoc = lesson(
506    "Note",
507    "Records a developer observation — structured, replayable, elidable in release.",
508    "Note that the cache missed with the key.",
509    "Who reads this? `Note` is for you replaying the run; `Warn` is for the operator; `Record` is the audit trail.",
510    None,
511);
512
513static WARN_STMT: ConstructDoc = lesson(
514    "Warn",
515    "Records an operator warning — never dropped, never sampled.",
516    "Warn that the retry limit was reached with the attempts.",
517    "Is this for the operator or the developer? A `Warn` always ships and always survives.",
518    None,
519);
520
521static RECORD_STMT: ConstructDoc = lesson(
522    "Record",
523    "Records a durable audit or business event.",
524    "Record that the payment settled with the amount and the customer.",
525    "Does this belong in the permanent trail? `Record` is the audit surface; `Note` is ephemeral.",
526    None,
527);
528
529static DURING_STMT: ConstructDoc = lesson(
530    "During",
531    "Opens a trace span over a block — no start/stop, so a span can never leak.",
532    "During parsing the file:\n    Let ast be the parse of text.",
533    "What work does this block do? The span is named by the doing, and it closes with the block.",
534    None,
535);
536
537static BLOCK_NO: ConstructDoc = lesson(
538    "No",
539    "Turns one optimization off for the code that follows.",
540    "## No Memo",
541    "Tip: use it to pin a benchmark or dodge a pathological case — semantics never change.",
542    None,
543);
544
545static BLOCK_TIER: ConstructDoc = lesson(
546    "Tier",
547    "Pins the hotness tier at which an optimization runs.",
548    "## Tier Memo eager",
549    "Tip: `eager`, `t1`–`t3`, or `never` — this tunes WHEN the optimizer fires, not correctness.",
550    None,
551);
552
553static BLOCK_REQUIRE: ConstructDoc = lesson(
554    "Require",
555    "Demands an optimization fires; if it can't, the compile fails (inverse of `## No`).",
556    "## Require memo",
557    "Tip: depend on an optimization on purpose (e.g. `## Require closedform`) so losing it becomes a loud error, not a silent slowdown.",
558    None,
559);
560
561static BLOCK_SUSPECTED_TYPO: ConstructDoc = lesson(
562    "Unknown header",
563    "An unknown header that looks like a typo of a real one.",
564    "## Mian",
565    "Did you mean the suggested header? Unknown `##` headers otherwise read as prose.",
566    None,
567);
568
569// ---------------------------------------------------------------------------
570// Primitive and built-in generic types
571// ---------------------------------------------------------------------------
572
573static TY_INT: ConstructDoc = lesson(
574    "Int",
575    "A whole number.",
576    "Let n: Int be 42.",
577    "Tip: `/` divides and `%` takes the remainder — `x is divisible by n` reads best in conditions.",
578    Some("3-arithmetic-comparison-logic-bitwise"),
579);
580
581static TY_NAT: ConstructDoc = lesson(
582    "Nat",
583    "A whole number that can never be negative.",
584    "Let count: Nat be 0.",
585    "Can this value ever go below zero? If subtraction might take it there, use Int instead.",
586    None,
587);
588
589static TY_TEXT: ConstructDoc = lesson(
590    "Text",
591    "A string of characters.",
592    "Let name: Text be \"Alice\".",
593    "Tip: build strings by interpolation — `\"Hello, {name}!\"` — or `a combined with b`.",
594    Some("4-strings"),
595);
596
597static TY_BOOL: ConstructDoc = lesson(
598    "Bool",
599    "Either true or false.",
600    "Let ready: Bool be true.",
601    "Tip: `and`/`or`/`not` short-circuit and return Bool; 0 and empty collections count as false.",
602    Some("3-arithmetic-comparison-logic-bitwise"),
603);
604
605static TY_FLOAT: ConstructDoc = lesson(
606    "Float",
607    "A floating-point number for fractional values.",
608    "Let pi: Float be 3.14159.",
609    "Tip: floats round — format output with `\"{pi:.2}\"`, and avoid them for money.",
610    Some("3-arithmetic-comparison-logic-bitwise"),
611);
612
613static TY_UNIT: ConstructDoc = lesson(
614    "Unit",
615    "The empty value — what procedures return.",
616    "## To greet (name: Text):\n    Show name.",
617    "Tip: you rarely write Unit; a function without `-> Type` returns it implicitly.",
618    None,
619);
620
621static TY_CHAR: ConstructDoc = lesson(
622    "Char",
623    "A single character.",
624    "Let c: Char be 'a'.",
625    "Tip: Text is a sequence of Chars — one Char is the unit you get when you walk it.",
626    None,
627);
628
629static TY_BYTE: ConstructDoc = lesson(
630    "Byte",
631    "A single byte — a whole number from 0 to 255.",
632    "Let b: Byte be 255.",
633    "Tip: bytes are the unit of binary data; whole numbers past 255 need Int.",
634    None,
635);
636
637static TY_LIST: ConstructDoc = lesson(
638    "List",
639    "An ordered, growable collection (another name for Seq).",
640    "Let xs be a new List of Int.",
641    "Tip: `[1, 2, 3]` is the literal form; `Push` appends; indexing is 1-based.",
642    Some("5-collections"),
643);
644
645static TY_SEQ: ConstructDoc = lesson(
646    "Seq",
647    "An ordered, growable collection — the canonical list type.",
648    "Let xs: Seq of Int be [1, 2, 3].",
649    "Tip: `item 1 of xs` is the FIRST element — LOGOS indexing is 1-based.",
650    Some("5-collections"),
651);
652
653static TY_MAP: ConstructDoc = lesson(
654    "Map",
655    "A dictionary from keys to values.",
656    "Let m be a new Map of Text to Int.\nSet m at \"a\" to 1.",
657    "Tip: read with `item k of m` and write with `Set m at k to v.`",
658    Some("5-collections"),
659);
660
661static TY_SET: ConstructDoc = lesson(
662    "Set",
663    "An unordered collection holding each value once.",
664    "Let s be a new Set of Int.\nAdd 3 to s.",
665    "Tip: on sets `&`/`|`/`^` are intersection/union/symmetric-difference; `a without b` subtracts.",
666    Some("5-collections"),
667);
668
669static TY_OPTION: ConstructDoc = lesson(
670    "Option",
671    "A value that is either present or absent.",
672    "Let maybe be some 30.\nInspect maybe:\n    When OptionSome (v):\n        Show v.\n    When OptionNone:\n        Show \"nothing\".",
673    "What happens when the value is absent? `Inspect` makes you answer both ways.",
674    Some("9-options--pattern-matching"),
675);
676
677static TY_RESULT: ConstructDoc = lesson(
678    "Result",
679    "A success value or an error value — one or the other.",
680    "## To native read (path: Text) -> Result of Text and Text",
681    "Which side is which? `Result of Ok and Err` — handle both with `Inspect`.",
682    None,
683);
684
685/// Every lesson, for parity ratchets and the REPL's suggestion list.
686// ---------------------------------------------------------------------------
687// Comparisons: one lesson per meaning, whichever way it is written. A program
688// says `<` or `is less than`, `==` or `is equal to`, and the hover, completion
689// and `:explain` answer the same for both (the user, 2026-11-01).
690// ---------------------------------------------------------------------------
691
692static LESS_THAN: ConstructDoc = lesson(
693    "Less than",
694    "True when the left value is smaller than the right, written `<` or `is less than`.",
695    "If n is less than 2:\n    Show n.",
696    "Should an equal pair count too? Then write `is at most` (`<=`).",
697    Some("3-arithmetic-comparison-logic-bitwise"),
698);
699
700static GREATER_THAN: ConstructDoc = lesson(
701    "Greater than",
702    "True when the left value is larger than the right, written `>` or `is greater than`.",
703    "If balance is greater than 0:\n    Show balance.",
704    "Should an equal pair count too? Then write `is at least` (`>=`).",
705    Some("3-arithmetic-comparison-logic-bitwise"),
706);
707
708static AT_MOST: ConstructDoc = lesson(
709    "At most",
710    "True when the left is smaller than or equal to the right, written `<=` or `is at most`.",
711    "Require that amount is at most balance.",
712    "Tip: `is less than or equal to` reads the same way, and so does `<=`.",
713    Some("3-arithmetic-comparison-logic-bitwise"),
714);
715
716static AT_LEAST: ConstructDoc = lesson(
717    "At least",
718    "True when the left is larger than or equal to the right, written `>=` or `is at least`.",
719    "Require that amount is at least 1.",
720    "Tip: `is greater than or equal to` reads the same way, and so does `>=`.",
721    Some("3-arithmetic-comparison-logic-bitwise"),
722);
723
724static EQUAL: ConstructDoc = lesson(
725    "Equal",
726    "True when both sides hold the same value, written `==`, `is equal to` or `equals`.",
727    "If answer is equal to 42:\n    Show \"right\".",
728    "A test or an assignment? `Set x to 5.` assigns; `x == 5` only compares.",
729    Some("3-arithmetic-comparison-logic-bitwise"),
730);
731
732static NOT_EQUAL: ConstructDoc = lesson(
733    "Not equal",
734    "True when the two sides differ, written `!=` or `is not equal to`.",
735    "If guess is not equal to secret:\n    Show \"try again\".",
736    "Tip: `not (x == y)` means the same thing, and reads worse.",
737    Some("3-arithmetic-comparison-logic-bitwise"),
738);
739
740// ---------------------------------------------------------------------------
741// Arithmetic and connectives, by symbol or by word (DAT-106).
742// ---------------------------------------------------------------------------
743
744static PLUS_OP: ConstructDoc = lesson(
745    "Plus",
746    "Adds two numbers, written `+` or `plus`.",
747    "Let total be price + tax.\nSet count to count plus 1.",
748    "Adding two Texts? `+` joins them end to end.",
749    Some("3-arithmetic-comparison-logic-bitwise"),
750);
751
752static MINUS_OP: ConstructDoc = lesson(
753    "Minus",
754    "Takes the right number from the left, written `-` or `minus`.",
755    "Let change be paid - price.",
756    "Tip: `Decrease x by 1.` says `Set x to x - 1.` in one word.",
757    Some("3-arithmetic-comparison-logic-bitwise"),
758);
759
760static TIMES_OP: ConstructDoc = lesson(
761    "Times",
762    "Multiplies two numbers, written `*` or `times`.",
763    "Let area be width * height.",
764    "Need a power? `**` raises: `2 ** 10` is 1024.",
765    Some("3-arithmetic-comparison-logic-bitwise"),
766);
767
768static DIVIDE_OP: ConstructDoc = lesson(
769    "Divide",
770    "Divides the left number by the right, written `/`.",
771    "Let half be total / 2.",
772    "Tip: `//` keeps the whole part and `%` the remainder.",
773    Some("3-arithmetic-comparison-logic-bitwise"),
774);
775
776static REMAINDER_OP: ConstructDoc = lesson(
777    "Remainder",
778    "The remainder of the left divided by the right, written `%`.",
779    "If n % 2 is equal to 0:\n    Show \"even\".",
780    "Checking a factor? `n is divisible by 7` reads better than `n % 7 is equal to 0`.",
781    Some("3-arithmetic-comparison-logic-bitwise"),
782);
783
784
785static AND: ConstructDoc = lesson(
786    "And",
787    "True when both sides are true, written `and`.",
788    "If x is greater than 0 and x is less than 10:\n    Show x.",
789    "Tip: group a mixed test with parentheses, as in `(a or b) and c`.",
790    Some("3-arithmetic-comparison-logic-bitwise"),
791);
792
793static OR: ConstructDoc = lesson(
794    "Or",
795    "True when either side is true, written `or`.",
796    "If day is equal to \"Sat\" or day is equal to \"Sun\":\n    Show \"weekend\".",
797    "Tip: `or` is true when both sides are true as well.",
798    Some("3-arithmetic-comparison-logic-bitwise"),
799);
800
801static NOT: ConstructDoc = lesson(
802    "Not",
803    "Flips a truth value, written `not`.",
804    "If not done:\n    Show \"still going\".",
805    "Tip: `is not equal to` reads better than `not (a is equal to b)`.",
806    Some("3-arithmetic-comparison-logic-bitwise"),
807);
808
809pub static ALL_DOCS: &[&ConstructDoc] = &[
810    // arithmetic and connectives
811    &PLUS_OP,
812    &MINUS_OP,
813    &TIMES_OP,
814    &DIVIDE_OP,
815    &REMAINDER_OP,
816    &AND,
817    &OR,
818    &NOT,
819    // comparisons
820    &LESS_THAN,
821    &GREATER_THAN,
822    &AT_MOST,
823    &AT_LEAST,
824    &EQUAL,
825    &NOT_EQUAL,
826    // keywords
827    &LET,
828    &SET_KW,
829    &SWAP_KW,
830    &RETURN,
831    &IF,
832    &WHILE,
833    &REPEAT,
834    &SHOW,
835    &GIVE,
836    &PUSH,
837    &INSPECT,
838    &CALL,
839    &NEW,
840    &ESCAPE,
841    &CHECK,
842    &POP,
843    &ADD,
844    &REMOVE,
845    &BREAK,
846    &ASSERT,
847    &TRUST,
848    &INCREASE,
849    &DECREASE,
850    &SPAWN,
851    &MERGE,
852    &CONVERGE,
853    &MOUNT,
854    &EXPECT_STMT,
855    &ADVANCE_STMT,
856    &SKIP_STMT,
857    &NOTE_STMT,
858    &WARN_STMT,
859    &RECORD_STMT,
860    &DURING_STMT,
861    // block headers
862    &BLOCK_MAIN,
863    &BLOCK_FUNCTION,
864    &BLOCK_COMPONENT,
865    &BLOCK_THEOREM,
866    &BLOCK_PROOF,
867    &BLOCK_DEFINITION,
868    &BLOCK_DEFINE,
869    &BLOCK_AXIOM,
870    &BLOCK_THEORY,
871    &BLOCK_TYPEDEF,
872    &BLOCK_POLICY,
873    &BLOCK_LOGIC,
874    &BLOCK_EXAMPLE,
875    &BLOCK_NOTE,
876    &BLOCK_REQUIRES,
877    &BLOCK_HARDWARE,
878    &BLOCK_PROPERTY,
879    &BLOCK_NO,
880    &BLOCK_TIER,
881    &BLOCK_REQUIRE,
882    &BLOCK_SUSPECTED_TYPO,
883    &BLOCK_TEST,
884    &BLOCK_PAGE,
885    &BLOCK_STORE,
886    &BLOCK_SESSION,
887    &BLOCK_DIRECTIVE,
888    &BLOCK_ROUTE,
889    &BLOCK_MIDDLEWARE,
890    &BLOCK_REDIRECT,
891    &BLOCK_ERROR_PAGE,
892    // types
893    &TY_INT,
894    &TY_NAT,
895    &TY_TEXT,
896    &TY_BOOL,
897    &TY_FLOAT,
898    &TY_UNIT,
899    &TY_CHAR,
900    &TY_BYTE,
901    &TY_LIST,
902    &TY_SEQ,
903    &TY_MAP,
904    &TY_SET,
905    &TY_OPTION,
906    &TY_RESULT,
907];
908
909/// The lesson for a statement keyword, when the token deserves one.
910///
911/// Wildcard-free: a new `TokenType` variant does not compile until someone
912/// decides whether it teaches (a lesson arm) or not (the grouped `None` arm).
913pub fn doc_for(kind: &TokenType) -> Option<&'static ConstructDoc> {
914    match kind {
915        // Comparisons, by symbol or by the English the lexer folds into one token.
916        TokenType::Lt => Some(&LESS_THAN),
917        TokenType::Gt => Some(&GREATER_THAN),
918        TokenType::LtEq => Some(&AT_MOST),
919        TokenType::GtEq => Some(&AT_LEAST),
920        TokenType::EqEq | TokenType::Identity | TokenType::Equals => Some(&EQUAL),
921        TokenType::NotEq => Some(&NOT_EQUAL),
922        TokenType::Plus => Some(&PLUS_OP),
923        TokenType::Minus => Some(&MINUS_OP),
924        TokenType::Star => Some(&TIMES_OP),
925        TokenType::Slash => Some(&DIVIDE_OP),
926        TokenType::Percent => Some(&REMAINDER_OP),
927        TokenType::And => Some(&AND),
928        TokenType::Or => Some(&OR),
929        TokenType::Not => Some(&NOT),
930        TokenType::Let => Some(&LET),
931        TokenType::Set => Some(&SET_KW),
932        TokenType::Swap => Some(&SWAP_KW),
933        TokenType::Return => Some(&RETURN),
934        TokenType::If => Some(&IF),
935        TokenType::While => Some(&WHILE),
936        TokenType::Repeat => Some(&REPEAT),
937        TokenType::Show => Some(&SHOW),
938        TokenType::Give => Some(&GIVE),
939        TokenType::Push => Some(&PUSH),
940        TokenType::Inspect => Some(&INSPECT),
941        TokenType::Call => Some(&CALL),
942        TokenType::New => Some(&NEW),
943        TokenType::Escape => Some(&ESCAPE),
944        TokenType::Expect => Some(&EXPECT_STMT),
945        TokenType::Advance => Some(&ADVANCE_STMT),
946        TokenType::Skip => Some(&SKIP_STMT),
947        TokenType::Note => Some(&NOTE_STMT),
948        TokenType::Warn => Some(&WARN_STMT),
949        TokenType::Record => Some(&RECORD_STMT),
950        TokenType::During => Some(&DURING_STMT),
951        TokenType::Check => Some(&CHECK),
952        TokenType::Pop => Some(&POP),
953        TokenType::Add => Some(&ADD),
954        TokenType::Remove => Some(&REMOVE),
955        TokenType::Break => Some(&BREAK),
956        TokenType::Assert => Some(&ASSERT),
957        TokenType::Trust => Some(&TRUST),
958        TokenType::Increase => Some(&INCREASE),
959        TokenType::Decrease => Some(&DECREASE),
960        TokenType::Spawn => Some(&SPAWN),
961        TokenType::Mount => Some(&MOUNT),
962        TokenType::Merge => Some(&MERGE),
963        TokenType::Converge => Some(&CONVERGE),
964
965        // No lesson (yet): block headers teach through `doc_for_block`;
966        // everything else is either structural, symbolic, or a word whose
967        // meaning the sentence around it carries.
968        TokenType::BlockHeader { .. }
969        | TokenType::All
970        | TokenType::No
971        | TokenType::Some
972        | TokenType::Any
973        | TokenType::Both
974        | TokenType::Most
975        | TokenType::Few
976        | TokenType::Many
977        | TokenType::Cardinal(_)
978        | TokenType::AtLeast(_)
979        | TokenType::AtMost(_)
980        | TokenType::InfinitelyMany
981        | TokenType::FinitelyMany
982        | TokenType::AllButFinitelyMany
983        | TokenType::InfinitelyOften
984        | TokenType::Anything
985        | TokenType::Anyone
986        | TokenType::Nothing
987        | TokenType::Nobody
988        | TokenType::NoOne
989        | TokenType::Nowhere
990        | TokenType::Ever
991        | TokenType::Never
992        | TokenType::Then
993        | TokenType::Iff
994        | TokenType::Because
995        | TokenType::Although
996        | TokenType::Until
997        | TokenType::Release
998        | TokenType::WeakUntil
999        | TokenType::Implies
1000        | TokenType::Must
1001        | TokenType::Shall
1002        | TokenType::Should
1003        | TokenType::Can
1004        | TokenType::May
1005        | TokenType::Cannot
1006        | TokenType::Would
1007        | TokenType::Could
1008        | TokenType::Might
1009        | TokenType::Had
1010        | TokenType::Be
1011        | TokenType::For
1012        | TokenType::In
1013        | TokenType::From
1014        | TokenType::Require
1015        | TokenType::Requires
1016        | TokenType::Ensures
1017        | TokenType::Otherwise
1018        | TokenType::Else
1019        | TokenType::Elif
1020        | TokenType::Either
1021        | TokenType::Native
1022        | TokenType::EscapeBlock(_)
1023        | TokenType::RawBlock { .. }
1024        | TokenType::Given
1025        | TokenType::Prove
1026        | TokenType::Auto
1027        | TokenType::Read
1028        | TokenType::Write
1029        | TokenType::Console
1030        | TokenType::File
1031        | TokenType::Copy
1032        | TokenType::Through
1033        | TokenType::Length
1034        | TokenType::At
1035        | TokenType::Contains
1036        | TokenType::Union
1037        | TokenType::Intersection
1038        | TokenType::Inside
1039        | TokenType::Zone
1040        | TokenType::Called
1041        | TokenType::Size
1042        | TokenType::Mapped
1043        | TokenType::Attempt
1044        | TokenType::Following
1045        | TokenType::Simultaneously
1046        | TokenType::Send
1047        | TokenType::Await
1048        | TokenType::Portable
1049        | TokenType::Manifest
1050        | TokenType::Chunk
1051        | TokenType::Shared
1052        | TokenType::Tally
1053        | TokenType::SharedSet
1054        | TokenType::SharedSequence
1055        | TokenType::CollaborativeSequence
1056        | TokenType::SharedMap
1057        | TokenType::Divergent
1058        | TokenType::Append
1059        | TokenType::Resolve
1060        | TokenType::RemoveWins
1061        | TokenType::AddWins
1062        | TokenType::YATA
1063        | TokenType::Values
1064        | TokenType::Listen
1065        | TokenType::NetConnect
1066        | TokenType::Sleep
1067        | TokenType::Sync
1068        | TokenType::Persistent
1069        | TokenType::Combined
1070        | TokenType::Followed
1071        | TokenType::Launch
1072        | TokenType::Task
1073        | TokenType::Pipe
1074        | TokenType::Receive
1075        | TokenType::Stop
1076        | TokenType::Try
1077        | TokenType::Into
1078        | TokenType::First
1079        | TokenType::After
1080        | TokenType::Colon
1081        | TokenType::Indent
1082        | TokenType::Dedent
1083        | TokenType::Newline
1084        | TokenType::Noun(_)
1085        | TokenType::Adjective(_)
1086        | TokenType::NonIntersectiveAdjective(_)
1087        | TokenType::Adverb(_)
1088        | TokenType::ScopalAdverb(_)
1089        | TokenType::TemporalAdverb(_)
1090        | TokenType::Verb { .. }
1091        | TokenType::ProperName(_)
1092        | TokenType::Ambiguous { .. }
1093        | TokenType::Performative(_)
1094        | TokenType::Exclamation
1095        | TokenType::Article(_)
1096        | TokenType::Auxiliary(_)
1097        | TokenType::Is
1098        | TokenType::Are
1099        | TokenType::Was
1100        | TokenType::Were
1101        | TokenType::That
1102        | TokenType::Who
1103        | TokenType::What
1104        | TokenType::Where
1105        | TokenType::Whose
1106        | TokenType::When
1107        | TokenType::Why
1108        | TokenType::Does
1109        | TokenType::Do
1110        | TokenType::Reflexive
1111        | TokenType::Reciprocal
1112        | TokenType::Respectively
1113        | TokenType::Pronoun { .. }
1114        | TokenType::Preposition(_)
1115        | TokenType::Particle(_)
1116        | TokenType::Comparative(_)
1117        | TokenType::Superlative(_)
1118        | TokenType::Than
1119        | TokenType::To
1120        | TokenType::PresupTrigger(_)
1121        | TokenType::Focus(_)
1122        | TokenType::Measure(_)
1123        | TokenType::Number(_)
1124        | TokenType::MoneyLiteral { .. }
1125        | TokenType::DurationLiteral { .. }
1126        | TokenType::DateLiteral { .. }
1127        | TokenType::TimeLiteral { .. }
1128        | TokenType::CalendarUnit(_)
1129        | TokenType::Ago
1130        | TokenType::Hence
1131        | TokenType::Before
1132        | TokenType::StringLiteral(_)
1133        | TokenType::InterpolatedString(_)
1134        | TokenType::CharLiteral(_)
1135        | TokenType::Item
1136        | TokenType::Items
1137        | TokenType::Possessive
1138        | TokenType::LParen
1139        | TokenType::RParen
1140        | TokenType::LBracket
1141        | TokenType::RBracket
1142        | TokenType::LBrace
1143        | TokenType::Amp
1144        | TokenType::VBar
1145        | TokenType::Tilde
1146        | TokenType::Caret
1147        | TokenType::RBrace
1148        | TokenType::Comma
1149        | TokenType::Period
1150        | TokenType::Dot
1151        | TokenType::Xor
1152        | TokenType::Shifted
1153        | TokenType::PlusEq
1154        | TokenType::MinusEq
1155        | TokenType::StarEq
1156        | TokenType::SlashEq
1157        | TokenType::PercentEq
1158        | TokenType::StarStar
1159        | TokenType::SlashSlash
1160        | TokenType::Arrow
1161        | TokenType::Assign
1162        | TokenType::Mut
1163        | TokenType::Identifier
1164        | TokenType::EOF => None,
1165    }
1166}
1167
1168/// The lesson for a `##` block header. TOTAL — every block type teaches, and
1169/// a new `BlockType` variant does not compile until it gets a lesson.
1170pub fn doc_for_block(block: &BlockType) -> &'static ConstructDoc {
1171    match block {
1172        BlockType::SuspectedTypo { .. } => &BLOCK_SUSPECTED_TYPO,
1173        BlockType::Theorem => &BLOCK_THEOREM,
1174        BlockType::Main => &BLOCK_MAIN,
1175        BlockType::Definition => &BLOCK_DEFINITION,
1176        BlockType::Define => &BLOCK_DEFINE,
1177        BlockType::Axiom => &BLOCK_AXIOM,
1178        BlockType::Theory => &BLOCK_THEORY,
1179        BlockType::Proof => &BLOCK_PROOF,
1180        BlockType::Example => &BLOCK_EXAMPLE,
1181        BlockType::Logic => &BLOCK_LOGIC,
1182        BlockType::Note => &BLOCK_NOTE,
1183        BlockType::Function => &BLOCK_FUNCTION,
1184        BlockType::Component => &BLOCK_COMPONENT,
1185        BlockType::TypeDef => &BLOCK_TYPEDEF,
1186        BlockType::Policy => &BLOCK_POLICY,
1187        BlockType::Requires => &BLOCK_REQUIRES,
1188        BlockType::Hardware => &BLOCK_HARDWARE,
1189        BlockType::Property => &BLOCK_PROPERTY,
1190        BlockType::No => &BLOCK_NO,
1191        BlockType::Tier => &BLOCK_TIER,
1192        BlockType::Require => &BLOCK_REQUIRE,
1193        BlockType::Test { .. } => &BLOCK_TEST,
1194        BlockType::Page { .. } => &BLOCK_PAGE,
1195        BlockType::Store => &BLOCK_STORE,
1196        BlockType::Session => &BLOCK_SESSION,
1197        BlockType::Directive => &BLOCK_DIRECTIVE,
1198        BlockType::Route { .. } => &BLOCK_ROUTE,
1199        BlockType::Middleware => &BLOCK_MIDDLEWARE,
1200        BlockType::Redirect { .. } => &BLOCK_REDIRECT,
1201        BlockType::ErrorPage { .. } => &BLOCK_ERROR_PAGE,
1202    }
1203}
1204
1205/// The lesson for a primitive or built-in generic type name.
1206pub fn doc_for_primitive(name: &str) -> Option<&'static ConstructDoc> {
1207    match name {
1208        "Int" => Some(&TY_INT),
1209        "Nat" => Some(&TY_NAT),
1210        "Text" => Some(&TY_TEXT),
1211        "Bool" => Some(&TY_BOOL),
1212        "Float" => Some(&TY_FLOAT),
1213        "Unit" => Some(&TY_UNIT),
1214        "Char" => Some(&TY_CHAR),
1215        "Byte" => Some(&TY_BYTE),
1216        "List" => Some(&TY_LIST),
1217        "Seq" => Some(&TY_SEQ),
1218        "Map" => Some(&TY_MAP),
1219        "Set" => Some(&TY_SET),
1220        "Option" => Some(&TY_OPTION),
1221        "Result" => Some(&TY_RESULT),
1222        _ => None,
1223    }
1224}
1225
1226// ---------------------------------------------------------------------------
1227// Literate-doc extraction — the prose → documentation pipeline
1228// ---------------------------------------------------------------------------
1229
1230/// One documented definition pulled from a literate LOGOS module.
1231pub struct LiterateDoc {
1232    /// The defined name (`read`, `Point`).
1233    pub name: String,
1234    /// The full `##` header line, verbatim.
1235    pub signature: String,
1236    /// The body of the `## Note` block directly above the header, when one
1237    /// exists. Notes are the ONLY per-definition doc carrier — bare prose
1238    /// between sections is not literate LOGOS.
1239    pub doc: Option<String>,
1240}
1241
1242/// The module-level documentation: the prose between the `# Title` line and
1243/// the first `##` section (the region the lexer skips).
1244pub fn module_doc(source: &str) -> Option<String> {
1245    let first_section = if source.starts_with("## ") {
1246        0
1247    } else {
1248        source.find("\n## ").map(|i| i + 1).unwrap_or(source.len())
1249    };
1250    let prose: Vec<&str> = source[..first_section]
1251        .lines()
1252        .map(str::trim)
1253        .filter(|l| !l.is_empty() && !l.starts_with('#'))
1254        .collect();
1255    (!prose.is_empty()).then(|| prose.join("\n"))
1256}
1257
1258/// The documentation for the `##` header starting at `header_start`: the body
1259/// of a `## Note` block IMMEDIATELY above it (the nearest preceding header
1260/// must be the Note — any other header in between means no doc).
1261pub fn doc_for_header_at(source: &str, header_start: usize) -> Option<String> {
1262    let head = source.get(..header_start)?;
1263    let mut nearest_header: Option<usize> = None;
1264    let mut offset = 0;
1265    for line in head.split_inclusive('\n') {
1266        if line.trim_start().starts_with("## ") {
1267            nearest_header = Some(offset);
1268        }
1269        offset += line.len();
1270    }
1271    let note_start = nearest_header?;
1272    let note_line_end = note_start + head[note_start..].find('\n')?;
1273    if head[note_start..note_line_end].trim() != "## Note" {
1274        return None;
1275    }
1276    let body = head[note_line_end + 1..].trim();
1277    (!body.is_empty()).then(|| body.to_string())
1278}
1279
1280/// Every `## To …` / `## A … ` definition in a literate module, with its
1281/// `## Note` documentation attached where one sits directly above. Types
1282/// declared inside a `## Definition` body inherit the block's Note.
1283pub fn extract_literate_docs(source: &str) -> Vec<LiterateDoc> {
1284    let mut docs = Vec::new();
1285    let mut offset = 0;
1286    let mut definition_doc: Option<Option<String>> = None;
1287    for line in source.split_inclusive('\n') {
1288        let header = line.trim_end().trim_start();
1289        if header.starts_with("## ") && header != "## Note" {
1290            // `## Note` is an attachment to the NEXT definition, not a section
1291            // change — it must not end the `## Definition` block it sits in.
1292            definition_doc = (header == "## Definition").then(|| doc_for_header_at(source, offset));
1293        }
1294        if let Some(name) = literate_definition_name(header) {
1295            docs.push(LiterateDoc {
1296                name,
1297                signature: header.to_string(),
1298                doc: doc_for_header_at(source, offset),
1299            });
1300        } else if let Some(block_doc) = &definition_doc {
1301            if let Some(name) = definition_body_type_name(header) {
1302                docs.push(LiterateDoc {
1303                    name,
1304                    signature: header.to_string(),
1305                    // A note directly above the declaration wins; the block's
1306                    // own doc is the fallback.
1307                    doc: doc_for_header_at(source, offset).or_else(|| block_doc.clone()),
1308                });
1309            }
1310        }
1311        offset += line.len();
1312    }
1313    docs
1314}
1315
1316/// The type a `## Definition` BODY line declares: `A <Name> has …` /
1317/// `A <Name> is …` (mirrors the loader's type-header rule).
1318fn definition_body_type_name(line: &str) -> Option<String> {
1319    let rest = line
1320        .strip_prefix("A ")
1321        .or_else(|| line.strip_prefix("An "))?;
1322    let word = rest
1323        .split(|c: char| c == '(' || c == '.' || c.is_whitespace())
1324        .next()?;
1325    if !word.chars().next().is_some_and(|c| c.is_ascii_uppercase()) {
1326        return None;
1327    }
1328    let tail = rest[word.len()..].trim_start();
1329    (tail.starts_with("has") || tail.starts_with("is") || tail.starts_with("of"))
1330        .then(|| word.to_string())
1331}
1332
1333/// The name a `##` definition header defines, mirroring the loader's
1334/// trigger-name rules: `## To [native|private]… <name>` and `## A/An [private] <TypeName> …`.
1335/// Modifiers come in any order; a parameterless header's trailing `:` is not part of the name.
1336fn literate_definition_name(header: &str) -> Option<String> {
1337    if let Some(mut rest) = header.strip_prefix("## To ") {
1338        while let Some(r) = rest
1339            .strip_prefix("native ")
1340            .or_else(|| rest.strip_prefix("private "))
1341        {
1342            rest = r;
1343        }
1344        let name = rest
1345            .split(|c: char| c == '(' || c == ':' || c.is_whitespace())
1346            .next()?;
1347        return (!name.is_empty()).then(|| name.to_string());
1348    }
1349    let rest = header
1350        .strip_prefix("## A ")
1351        .or_else(|| header.strip_prefix("## An "))?;
1352    let rest = rest.strip_prefix("private ").unwrap_or(rest);
1353    let word = rest
1354        .split(|c: char| c == '(' || c == '.' || c == ':' || c.is_whitespace())
1355        .next()?;
1356    word.chars()
1357        .next()
1358        .is_some_and(|c| c.is_ascii_uppercase())
1359        .then(|| word.to_string())
1360}
1361
1362/// Every lesson whose name matches the word, case-insensitively — a word can
1363/// name more than one construct (`Set` the statement, `Set` the type), and an
1364/// honest teacher shows both.
1365pub fn docs_for_word(word: &str) -> Vec<&'static ConstructDoc> {
1366    ALL_DOCS
1367        .iter()
1368        .filter(|doc| doc.name.eq_ignore_ascii_case(word))
1369        .copied()
1370        .collect()
1371}
1372
1373/// The first lesson whose name matches the word, case-insensitively.
1374pub fn doc_for_word(word: &str) -> Option<&'static ConstructDoc> {
1375    docs_for_word(word).into_iter().next()
1376}
1377
1378/// The comparison a run of English tokens spells, read around the token at `at`: `is less than`,
1379/// `greater than or equal to`, `at least`, `is equal to`, `not equal to`, `equals`. The lexer
1380/// hands most of these to the parser one word at a time (`less` is a comparative, `than` is
1381/// `than`), so no single token carries the meaning; this reads the words the parser reads. Gives
1382/// the lesson and the span of the whole phrase, for a hover to cover and an editor to colour.
1383pub fn doc_for_phrase(source: &str, tokens: &[crate::token::Token], at: usize) -> Option<(&'static ConstructDoc, logicaffeine_base::Span)> {
1384    use logicaffeine_base::Span;
1385    let token = tokens.get(at)?;
1386    // The words of the tokens around `at`, each with the token it came from (a token can hold
1387    // several words: `is equal to` is one token, `at least three` another).
1388    let lo = at.saturating_sub(5);
1389    let hi = (at + 6).min(tokens.len());
1390    let mut words: Vec<(String, usize)> = Vec::new();
1391    for (i, t) in tokens.iter().enumerate().take(hi).skip(lo) {
1392        let text = source.get(t.span.start..t.span.end).unwrap_or("");
1393        for w in text.split_whitespace() {
1394            words.push((w.to_ascii_lowercase(), i));
1395        }
1396    }
1397    const PHRASES: &[(&[&str], &ConstructDoc)] = &[
1398        (&["less", "than", "or", "equal", "to"], &AT_MOST),
1399        (&["greater", "than", "or", "equal", "to"], &AT_LEAST),
1400        (&["not", "equal", "to"], &NOT_EQUAL),
1401        (&["is", "equal", "to"], &EQUAL),
1402        (&["is", "identical", "to"], &EQUAL),
1403        (&["less", "than"], &LESS_THAN),
1404        (&["fewer", "than"], &LESS_THAN),
1405        (&["greater", "than"], &GREATER_THAN),
1406        (&["at", "least"], &AT_LEAST),
1407        (&["at", "most"], &AT_MOST),
1408        (&["equal", "to"], &EQUAL),
1409        (&["equals"], &EQUAL),
1410        (&["divisible", "by"], &REMAINDER_OP),
1411    ];
1412    // `plus`, `minus` and `times` are operators only between two operands (`Repeat 3 times:` counts
1413    // repetitions); the parser reads them the same way, as `check_op_word` does.
1414    const ARITHMETIC_WORDS: &[(&str, &ConstructDoc)] = &[("plus", &PLUS_OP), ("minus", &MINUS_OP), ("times", &TIMES_OP)];
1415    let operand = |t: &crate::token::Token| {
1416        matches!(
1417            t.kind,
1418            TokenType::Number(_)
1419                | TokenType::Identifier
1420                | TokenType::ProperName(_)
1421                | TokenType::Noun(_)
1422                | TokenType::RParen
1423                | TokenType::LParen
1424                | TokenType::StringLiteral(_)
1425        )
1426    };
1427    let text = source.get(token.span.start..token.span.end).unwrap_or("").to_ascii_lowercase();
1428    if let Some((_, doc)) = ARITHMETIC_WORDS.iter().find(|(w, _)| *w == text) {
1429        let before = at.checked_sub(1).and_then(|i| tokens.get(i)).is_some_and(operand);
1430        let after = tokens.get(at + 1).is_some_and(operand);
1431        if before && after {
1432            return Some((doc, Span::new(token.span.start, token.span.end)));
1433        }
1434    }
1435    // Longest phrase first, so `less than or equal to` is not read as `less than`.
1436    for (phrase, doc) in PHRASES {
1437        for start in 0..words.len() {
1438            let end = start + phrase.len();
1439            if end > words.len() {
1440                break;
1441            }
1442            if words[start..end].iter().zip(phrase.iter()).all(|((w, _), p)| w == p) {
1443                let covers = words[start..end].iter().any(|(_, i)| *i == at);
1444                // `equal to` inside `not equal to` is the longer phrase, found first; a bare
1445                // `equal to` preceded by `not` never gets here.
1446                if covers {
1447                    let first = words[start].1;
1448                    let last = words[end - 1].1;
1449                    return Some((doc, Span::new(tokens[first].span.start, tokens[last].span.end)));
1450                }
1451            }
1452        }
1453    }
1454    None
1455}