Skip to main content

logicaffeine_language/ast/
stmt.rs

1//! Imperative statement AST types for the LOGOS language.
2//!
3//! This module defines statement types for the imperative fragment including:
4//!
5//! - **[`Stmt`]**: Statement variants (let, if, match, while, for, function defs)
6//! - **[`Expr`]**: Imperative expressions (field access, method calls, literals)
7//! - **[`TypeExpr`]**: Type annotations with refinements and generics
8//! - **[`Literal`]**: Literal values (numbers, strings, booleans)
9//! - **[`Block`]**: Statement blocks with optional return expressions
10//!
11//! The imperative AST is used in LOGOS mode for generating executable Rust code.
12
13use super::axiom::{AxiomBlock, TheoryBlock};
14use super::definition::DefinitionBlock;
15use super::logic::LogicExpr;
16use super::theorem::TheoremBlock;
17use crate::token::Span;
18use logicaffeine_base::{Interner, Symbol};
19
20/// Type expression for explicit type annotations.
21///
22/// Represents type syntax like:
23/// - `Int` → Primitive(Int)
24/// - `User` → Named(User)
25/// - `List of Int` → Generic { base: List, params: [Primitive(Int)] }
26/// - `List of List of Int` → Generic { base: List, params: [Generic { base: List, params: [Primitive(Int)] }] }
27/// - `Result of Int and Text` → Generic { base: Result, params: [Primitive(Int), Primitive(Text)] }
28#[derive(Debug, Clone)]
29pub enum TypeExpr<'a> {
30    /// Primitive type: Int, Nat, Text, Bool
31    Primitive(Symbol),
32    /// Named type (user-defined): User, Point
33    Named(Symbol),
34    /// Generic type: List of Int, Option of Text, Result of Int and Text
35    Generic {
36        base: Symbol,
37        params: &'a [TypeExpr<'a>],
38    },
39    /// Anonymous tuple type: `(Int, Int)`, `(Int, Text, Bool)`. A positional heterogeneous product —
40    /// the first-class form of a multiple-return / paired parameter. Resolves to `BoundaryType::Tuple`
41    /// (the same cross-tier classification `Pair`/`Triple` already use) and rides one slot per tier.
42    Tuple(&'a [TypeExpr<'a>]),
43    /// Named record type: `(quotient: Int, remainder: Int)`. A tuple whose positions carry NAMES, so it is
44    /// accessed by field (`r's quotient`) rather than position. Its VALUE is a self-describing struct
45    /// (`RuntimeValue::Struct` with these field names), built by coercing the returned positional tuple —
46    /// so it reuses the entire struct field-access + codegen machinery on every tier. Parallel slices
47    /// (`field_names[i]` : `field_types[i]`) keep the arena allocators simple.
48    Record {
49        field_names: &'a [Symbol],
50        field_types: &'a [TypeExpr<'a>],
51    },
52    /// Function type: fn(A, B) -> C (for higher-order functions)
53    Function {
54        inputs: &'a [TypeExpr<'a>],
55        output: &'a TypeExpr<'a>,
56    },
57    /// Refinement type with predicate constraint.
58    /// Example: `Int where it > 0`
59    Refinement {
60        /// The base type being refined
61        base: &'a TypeExpr<'a>,
62        /// The bound variable (usually "it")
63        var: Symbol,
64        /// The predicate constraint (from Logic Kernel)
65        predicate: &'a LogicExpr<'a>,
66    },
67    /// Persistent storage wrapper type.
68    /// Example: `Persistent Counter`
69    /// Semantics: Wraps a Shared type with journal-backed storage
70    Persistent {
71        /// The inner type (must be a Shared/CRDT type)
72        inner: &'a TypeExpr<'a>,
73    },
74    /// Mutable-parameter marker (Mutable Value Semantics escape hatch).
75    /// Example: `## To addItem (items: mutable Seq of Int):` →
76    /// `Mutable { inner: Generic { List, [Int] } }`.
77    /// Semantics: under value semantics collections pass by value by default; a
78    /// `Mutable` parameter passes by reference so the callee's mutations are
79    /// visible to the caller (the explicit, opt-in form of the void-mutate
80    /// idiom). Carried on the parameter's type so the `(Symbol, &TypeExpr)`
81    /// parameter representation is unchanged. For every purpose other than the
82    /// parameter-passing convention, `Mutable { inner }` behaves as `inner`.
83    Mutable {
84        /// The underlying parameter type.
85        inner: &'a TypeExpr<'a>,
86    },
87}
88
89/// Source for Read statements.
90#[derive(Debug, Clone, Copy)]
91pub enum ReadSource<'a> {
92    /// Read from console (stdin)
93    Console,
94    /// Read from file at given path
95    File(&'a Expr<'a>),
96}
97
98/// Pattern for loop variable binding.
99/// Supports single identifiers and tuple destructuring for Map iteration.
100#[derive(Debug, Clone)]
101pub enum Pattern {
102    /// Single identifier: `Repeat for x in list`
103    Identifier(Symbol),
104    /// Tuple destructuring: `Repeat for (k, v) in map`
105    Tuple(Vec<Symbol>),
106}
107
108/// Binary operation kinds for imperative expressions.
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
110pub enum BinaryOpKind {
111    Add,
112    Subtract,
113    Multiply,
114    /// `a ** b` — exponentiation. Integer power is EXACT (promotes to BigInt on
115    /// overflow); a Float operand uses `powf`; a negative integer exponent is a
116    /// loud error. Binds tighter than `* / %`, right-associative.
117    Pow,
118    Divide,
119    /// EXACT division — the type-directed sibling of [`BinaryOpKind::Divide`].
120    /// `Divide` floors (`7 / 2 → 3`, the integer default); `ExactDivide` keeps the
121    /// quotient exact (`7 / 2 → 7/2`, a `Rational`). The `resolve_divisions` pass
122    /// rewrites `Divide → ExactDivide` only where the result flows into a `Rational`
123    /// context, so existing (floor) code is untouched.
124    ExactDivide,
125    /// `a // b` — FLOOR division, rounding toward negative infinity (`-7 // 2 → -4`).
126    /// Distinct from [`BinaryOpKind::Divide`], which truncates toward zero (`-7 / 2 →
127    /// -3`); the two agree when the operands share a sign. Exact (promotes to BigInt),
128    /// integer-producing, and immune to the `resolve_divisions` Rational rewrite — the
129    /// explicit spelling for "give me the floored integer quotient."
130    FloorDivide,
131    Modulo,
132    Eq,
133    NotEq,
134    Lt,
135    Gt,
136    LtEq,
137    GtEq,
138    // Logical/bitwise operators — type-aware in codegen (&&/|| for Bool, &/| for Int)
139    And,
140    Or,
141    /// String concatenation ("X combined with Y")
142    Concat,
143    /// Sequence concatenation ("A followed by B") — merge two sequences into one.
144    SeqConcat,
145    /// Tolerant float comparison ("a is approximately b") — Python-isclose
146    /// semantics (rel 1e-9, abs floor 1e-12). `==` stays IEEE bit-exact;
147    /// this is the EXPLICIT spelling for near-equality.
148    ApproxEq,
149    /// Bitwise XOR: `x ^ y` (the word `xor` is the English spelling); on
150    /// Sets, symmetric difference.
151    BitXor,
152    /// Bitwise AND: `x & y`; on Sets, intersection.
153    BitAnd,
154    /// Bitwise OR: `x | y`; on Sets, union.
155    BitOr,
156    /// Left shift: "x shifted left by y" → `x << y`
157    Shl,
158    /// Right shift: "x shifted right by y" → `x >> y`
159    Shr,
160}
161
162/// The HTTP method of a [`Stmt::Fetch`].
163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
164pub enum FetchMethod {
165    Get,
166    Post,
167    Put,
168    Patch,
169    Delete,
170    /// `Upload <file> to URL as T, then action.` — a multipart body.
171    Upload,
172}
173
174/// What a component action can do to the page, the browser, storage or a store. Each is a
175/// sentence in the `Actions:` vocabulary; the selector forms take a selector TEXT or an
176/// `Element`.
177#[derive(Debug, Clone)]
178pub enum UiStmt<'a> {
179    /// `Focus SEL.` — put focus on the element AND raise the `focus` event, so a
180    /// `When "#x" is focused:` handler runs. Setting focus without raising it left that handler
181    /// unreachable from any test.
182    Focus {
183        selector: &'a Expr<'a>,
184    },
185    /// `Blur SEL.` — take focus off the element and raise `blur`.
186    ///
187    /// ★ ITS EVENT COULD BE WAITED FOR AND NOT CAUSED. `blurred` is one of the six predicates a
188    /// handler may name, and nothing in the language could make one happen — so a page's
189    /// leave-the-field path (validate on blur, save a draft, close a menu) was unreachable from
190    /// every test in the suite.
191    Blur {
192        selector: &'a Expr<'a>,
193    },
194    /// `Hover SEL.` — raise `mouseover`.
195    ///
196    /// ★ IT WAS ALLOWLISTED WITH NOTHING BEHIND IT: `Hover` appeared in the gate that decides
197    /// whether a sentence may open a UI statement, and `parse_ui_statement` had no branch for it,
198    /// so the word was accepted into the gate and then fell out the bottom as "I expected a
199    /// statement here". Two hand-maintained halves of one table, each complete on its own.
200    Hover {
201        selector: &'a Expr<'a>,
202    },
203    /// `Scroll to SEL.`
204    ScrollTo {
205        selector: &'a Expr<'a>,
206    },
207    /// `Add class C to SEL.`
208    AddClass {
209        class: &'a Expr<'a>,
210        selector: &'a Expr<'a>,
211    },
212    /// `Remove class C from SEL.`
213    RemoveClass {
214        class: &'a Expr<'a>,
215        selector: &'a Expr<'a>,
216    },
217    /// `Select the text in SEL.`
218    SelectText {
219        selector: &'a Expr<'a>,
220    },
221    /// `Copy TEXT to the clipboard.`
222    CopyToClipboard {
223        text: &'a Expr<'a>,
224    },
225    /// `Download BYTES as "name.ext".`
226    Download {
227        bytes: &'a Expr<'a>,
228        name: &'a Expr<'a>,
229    },
230    /// `Navigate to URL.`
231    Navigate {
232        url: &'a Expr<'a>,
233    },
234    /// `Replace the URL with URL.` — history replace, no new entry.
235    ReplaceUrl {
236        url: &'a Expr<'a>,
237    },
238    /// `Go back.`
239    /// `Raise "offline".` — cause a WINDOW event in a test.
240    ///
241    /// ★ ONE DRIVER FOR EVERY EVENT THAT HAPPENS TO THE PAGE RATHER THAN TO AN ELEMENT. Going
242    /// offline, coming back online and the window resizing are not things a page does to itself
243    /// and not things a visitor does to an element, so none of the element verbs can cause one —
244    /// and a trigger no test can cause is a trigger nothing checks. Naming the event as TEXT means
245    /// the next window event needs no new sentence.
246    RaiseWindowEvent {
247        event: &'a Expr<'a>,
248        target: &'a Expr<'a>,
249        value: &'a Expr<'a>,
250    },
251
252    GoBack,
253    /// `Set the title to TEXT.`
254    SetTitle {
255        title: &'a Expr<'a>,
256    },
257    /// `Save VALUE as "key".`
258    Save {
259        value: &'a Expr<'a>,
260        key: &'a Expr<'a>,
261    },
262    /// `Load "key" into FIELD.`
263    Load {
264        key: &'a Expr<'a>,
265        var: Symbol,
266    },
267    /// `Forget "key".`
268    Forget {
269        key: &'a Expr<'a>,
270    },
271    /// `Reload the page.` — every component instance, listener and mounted root goes; browser
272    /// storage stays. What a `persisted` store survives and a local one does not.
273    Reload,
274    /// `Notify MESSAGE [as success|error].`
275    Notify {
276        message: &'a Expr<'a>,
277        tone: Option<Symbol>,
278    },
279    /// `Publish MESSAGE on TOPIC.` — send on a relay topic.
280    ///
281    /// ★ THE OUTBOUND HALF OF A CONSTRUCT THAT SHIPPED WITH ONLY ITS INBOUND HALF.
282    /// `When a message arrives on "t":` subscribes, and nothing in the language could publish —
283    /// so a page could hear a server and never answer it, and two tabs of one app could not talk.
284    /// The relay had the other side complete the whole time (`RelayFrame::Publish` fans out to
285    /// every local subscriber and gossips on to native nodes); what was missing was a sentence.
286    ///
287    /// It delivers to THIS page's own subscribers as well as sending the frame, so a publish
288    /// means one thing wherever the page runs: every handler on the topic hears it exactly once.
289    /// The relay excludes the originating connection, so the local delivery is not a second copy.
290    Publish {
291        message: &'a Expr<'a>,
292        topic: &'a Expr<'a>,
293    },
294    /// `Toggle FIELD.` — a Bool state field.
295    Toggle {
296        field: Symbol,
297    },
298    /// `Call <Store>'s <action> [with a and b].`
299    CallStore {
300        store: Symbol,
301        action: Symbol,
302        args: Vec<&'a Expr<'a>>,
303    },
304    /// `Stop the timer NAME.`
305    StopTimer {
306        name: Symbol,
307    },
308    /// `Start the timer NAME.` — (re)start a named timer from a whole period, its period read from
309    /// its sentence now; a running timer restarts, a stopped one runs again.
310    StartTimer {
311        name: Symbol,
312    },
313    /// `Click SEL.` — fire a click on the element the selector names.
314    Click {
315        selector: &'a Expr<'a>,
316    },
317    /// `Submit SEL.` — submit a form, as a user pressing the button would.
318    Submit {
319        selector: &'a Expr<'a>,
320    },
321    /// `Choose VALUE in SEL.` — pick an option in a `<select>`.
322    ///
323    /// Its own verb because a dropdown is neither typed into nor clicked; without one a test can
324    /// only reach a `<select>` by faking the event some other control raises.
325    Choose {
326        value: &'a Expr<'a>,
327        selector: &'a Expr<'a>,
328    },
329    /// `Press KEY [in SEL].` — a key press, on an element or on the page.
330    Press {
331        key: &'a Expr<'a>,
332        selector: Option<&'a Expr<'a>>,
333    },
334    /// `Type TEXT into SEL.` — type into a bound input, as a user would.
335    TypeInto {
336        text: &'a Expr<'a>,
337        selector: &'a Expr<'a>,
338    },
339    /// `Mount <Component> [at "#sel"].` — create the component's root instance and render it.
340    /// (The legacy indentation dialect keeps its own synthesized-`render` lowering.)
341    Mount {
342        component: Symbol,
343        selector: Option<&'a Expr<'a>>,
344    },
345}
346
347impl<'a> UiStmt<'a> {
348    /// Every expression this statement evaluates — the traversal surface for the analyses.
349    pub fn exprs(&self) -> Vec<&'a Expr<'a>> {
350        match self {
351            UiStmt::Focus { selector }
352            | UiStmt::Blur { selector }
353            | UiStmt::Hover { selector }
354            | UiStmt::ScrollTo { selector }
355            | UiStmt::SelectText { selector } => vec![selector],
356            UiStmt::AddClass { class, selector } | UiStmt::RemoveClass { class, selector } => {
357                vec![class, selector]
358            }
359            UiStmt::CopyToClipboard { text } => vec![text],
360            UiStmt::Download { bytes, name } => vec![bytes, name],
361            UiStmt::Navigate { url } | UiStmt::ReplaceUrl { url } => vec![url],
362            UiStmt::SetTitle { title } => vec![title],
363            UiStmt::RaiseWindowEvent {
364                event,
365                target,
366                value,
367            } => vec![event, target, value],
368            UiStmt::Save { value, key } => vec![value, key],
369            UiStmt::Load { key, .. } => vec![key],
370            UiStmt::Forget { key } => vec![key],
371            UiStmt::Notify { message, .. } => vec![message],
372            UiStmt::Publish { message, topic } => vec![message, topic],
373            UiStmt::CallStore { args, .. } => args.clone(),
374            UiStmt::Click { selector } | UiStmt::Submit { selector } => vec![selector],
375            UiStmt::Choose { value, selector } => vec![value, selector],
376            UiStmt::Press { key, selector } => {
377                let mut v = vec![*key];
378                v.extend(selector.iter().copied());
379                v
380            }
381            UiStmt::TypeInto { text, selector } => vec![text, selector],
382            UiStmt::Mount { selector, .. } => selector.iter().copied().collect(),
383            UiStmt::GoBack
384            | UiStmt::Reload
385            | UiStmt::Toggle { .. }
386            | UiStmt::StopTimer { .. }
387            | UiStmt::StartTimer { .. } => Vec::new(),
388        }
389    }
390
391    /// The binding this statement WRITES, if any (`Load … into x`, `Toggle done`).
392    pub fn writes(&self) -> Option<Symbol> {
393        match self {
394            UiStmt::Load { var, .. } => Some(*var),
395            UiStmt::Toggle { field } => Some(*field),
396            _ => None,
397        }
398    }
399
400    /// Where this statement may be written: driving a page from a `## Main`/`## Test` body,
401    /// inside a component's `Actions:`, or either.
402    pub fn role(&self) -> Role {
403        match self {
404            // Drive-only: `action_verb_tier_lock`'s `NOT_IN_ACTIONS` proves none of these compile
405            // inside `Actions:`, and `page_host::Drive` carries each to a page under test.
406            UiStmt::Mount { .. }
407            | UiStmt::Click { .. }
408            | UiStmt::Submit { .. }
409            | UiStmt::Choose { .. }
410            | UiStmt::Press { .. }
411            | UiStmt::TypeInto { .. }
412            | UiStmt::RaiseWindowEvent { .. } => Role::Drive,
413            // Both: `action_verb_tier_lock`'s `VERBS` proves each compiles inside `Actions:`, and
414            // `page_host::Drive` also carries each to a page under test.
415            UiStmt::Focus { .. }
416            | UiStmt::Blur { .. }
417            | UiStmt::Hover { .. }
418            | UiStmt::Navigate { .. }
419            | UiStmt::Reload => Role::Both,
420            // Action-only: `action_verb_tier_lock`'s `VERBS` proves each compiles inside
421            // `Actions:`, and none is a variant of `page_host::Drive`.
422            UiStmt::ScrollTo { .. }
423            | UiStmt::AddClass { .. }
424            | UiStmt::RemoveClass { .. }
425            | UiStmt::SelectText { .. }
426            | UiStmt::CopyToClipboard { .. }
427            | UiStmt::Download { .. }
428            | UiStmt::ReplaceUrl { .. }
429            | UiStmt::GoBack
430            | UiStmt::SetTitle { .. }
431            | UiStmt::Save { .. }
432            | UiStmt::Load { .. }
433            | UiStmt::Forget { .. }
434            | UiStmt::Notify { .. }
435            | UiStmt::Publish { .. }
436            | UiStmt::Toggle { .. }
437            | UiStmt::CallStore { .. }
438            | UiStmt::StopTimer { .. }
439            | UiStmt::StartTimer { .. } => Role::Action,
440        }
441    }
442}
443
444/// Which position a `UiStmt` may be written in — the partition [`UiStmt::role`] holds to, cross-
445/// checked against `action_verb_tier_lock`'s own census (which verbs compile inside `Actions:`)
446/// and `page_host::Drive` (which verbs carry a `## Main`/`## Test` statement to a page under
447/// test), so the two catalogues cannot silently drift apart.
448#[derive(Clone, Copy, Debug, PartialEq, Eq)]
449pub enum Role {
450    /// A `## Main`/`## Test` driving statement only — never legal inside a component's `Actions:`.
451    Drive,
452    /// Only ever written inside a component's `Actions:` — never a driving statement.
453    Action,
454    /// Legal in either position.
455    Both,
456}
457
458/// Block is a sequence of statements.
459pub type Block<'a> = &'a [Stmt<'a>];
460
461/// A statement's identity: where it lives. Stable for as long as the AST it
462/// was taken from is alive; a statement copied into a new block is a new
463/// identity. Diagnostics use it to name the exact statement a finding is
464/// about, nested ones included.
465#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
466pub struct StmtId(usize);
467
468impl StmtId {
469    pub fn of(stmt: &Stmt<'_>) -> Self {
470        StmtId(stmt as *const Stmt<'_> as usize)
471    }
472}
473
474/// Match arm for pattern matching in Inspect statements.
475#[derive(Debug, Clone)]
476pub struct MatchArm<'a> {
477    pub enum_name: Option<Symbol>,       // The enum type (e.g., Shape)
478    pub variant: Option<Symbol>,         // None = Otherwise (wildcard)
479    pub bindings: Vec<(Symbol, Symbol)>, // (field_name, binding_name)
480    pub body: Block<'a>,
481}
482
483/// Which sealed-world resources a `## Test` may really touch, granted by
484/// capability sentences (`This test may use the real filesystem.`). Everything
485/// defaults to sealed; a granted capability moves the test to the `--live` set.
486#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
487pub struct TestCapabilities {
488    pub filesystem: bool,
489    pub network: bool,
490    pub environment: bool,
491    pub clock: bool,
492}
493
494/// A table-driven test's case fixture: `For each of these cases:` followed by
495/// a markdown pipe table. Columns bind names in the test body's scope; each
496/// data row is a named sub-test.
497#[derive(Debug, Clone)]
498pub struct CaseTable<'a> {
499    pub columns: Vec<Symbol>,
500    pub rows: Vec<Vec<&'a Expr<'a>>>,
501}
502
503/// Where an `Expect output:` snapshot lives: indented in the document, or in
504/// an external golden file (`Expect output as in "golden/report.txt".`).
505#[derive(Debug, Clone, Copy, PartialEq, Eq)]
506pub enum ExpectedOutput {
507    Inline(Symbol),
508    File(Symbol),
509}
510
511/// The domain a property quantifies over (`For all integers a and b:`).
512/// Generation draws from this; shrinking minimizes toward the domain's zero.
513#[derive(Debug, Clone, Copy, PartialEq, Eq)]
514pub enum PropDomain {
515    Integers,
516    Naturals,
517    Booleans,
518}
519
520/// The speech-act category of an observation statement:
521/// audience + retention, not a
522/// numeric level.
523#[derive(Debug, Clone, Copy, PartialEq, Eq)]
524pub enum ObsCategory {
525    /// `Note that …` — for the developer replaying the run; ring-buffered,
526    /// elidable in release.
527    Note,
528    /// `Warn that …` — for the operator; never dropped, never sampled.
529    Warn,
530    /// `Record that …` — the audit/business trail; durable.
531    Record,
532}
533
534/// The wire compression codec a `Send compressed [with <codec>]` selects. The
535/// transpiler maps this to the runtime's wire codec; bare `compressed` = `Deflate`.
536#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
537pub enum CompressionCodec {
538    /// DEFLATE — the balanced default (bare `Send compressed`).
539    Deflate,
540    /// LZ4 — near-memcpy speed, lighter ratio.
541    Lz4,
542    /// Zstandard — the best ratio.
543    Zstd,
544}
545
546/// The wire LAYOUT a `Send` modifier picks — the size↔speed dial the sender chooses for
547/// their link. The transpiler maps this to the runtime's numeric codec. The sender knows
548/// their use case; this lets them express it in one word.
549#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
550pub enum SendLayout {
551    /// `compact` / `small` — smallest wire (LEB128 varint). For a bandwidth-bound link
552    /// (mobile, WAN, metered). This is also the default when no layout word is given.
553    Compact,
554    /// `fast` / `quickly` — fastest decode (fixed-width memcpy, zero parse). For a
555    /// latency-bound / fat link (LAN, datacenter, RDMA).
556    Fast,
557    /// `packed` — varint size with SIMD group-varint decode; the balanced middle.
558    Packed,
559    /// `smallest` / `best` — turn on the per-column compression menu (delta /
560    /// delta-of-delta / frame-of-reference / run-length / dictionary), auto-selecting
561    /// each column's smallest form and never exceeding plain varint. For a
562    /// bandwidth-bound link where CPU is cheap relative to bytes.
563    Smallest,
564    /// `redundant` / `tough` — forward error correction: the message is split into
565    /// Reed-Solomon shards and each is published as its own packet, so a receiver
566    /// reconstructs the exact message from any K even after some are lost. For a lossy
567    /// / one-way link (UDP, multicast, BLE, LoRa) where retransmit is impossible.
568    Redundant,
569}
570
571/// Backing-file source for a memory-mapped zone (`… mapped from <here>`).
572/// `Inside a zone called "D" mapped from "f.bin"` is [`ZoneSource::Literal`];
573/// `… mapped from path` (a runtime `Text` variable) is [`ZoneSource::Variable`].
574#[derive(Debug, Clone, Copy, PartialEq, Eq)]
575pub enum ZoneSource {
576    /// A string-literal path baked into the source.
577    Literal(Symbol),
578    /// A variable holding the path, resolved at runtime.
579    Variable(Symbol),
580}
581
582/// Imperative statement AST (LOGOS §15.0.0).
583///
584/// Stmt is the primary AST node for imperative code blocks like `## Main`
585/// and function bodies. The Assert variant bridges to the Logic Kernel.
586/// Which end of the shared pad this peer draws from, for the PNP one-time-pad tier.
587/// `as initiator` sends on the first directional half; `as responder` sends on the second.
588#[derive(Debug, Clone, Copy, PartialEq, Eq)]
589pub enum SecureRole {
590    /// Draws the send pad from the first directional half (`i2r`).
591    Initiator,
592    /// Draws the send pad from the second directional half (`r2i`).
593    Responder,
594}
595
596/// The `with pad "<path>" as <role>` binding on a `Connect`/`Listen` — activate the PNP one-time-pad
597/// session over the pad file at `pad`, with this peer taking `role`.
598#[derive(Debug, Clone, Copy)]
599pub struct SecurePad<'a> {
600    /// The pad file path (a string-literal or variable expression).
601    pub pad: &'a Expr<'a>,
602    /// Which directional half this peer sends on.
603    pub role: SecureRole,
604}
605
606#[derive(Debug, Clone)]
607pub enum Stmt<'a> {
608    /// Variable binding: `Let x be 5.` or `Let x: Int be 5.`
609    Let {
610        var: Symbol,
611        ty: Option<&'a TypeExpr<'a>>,
612        value: &'a Expr<'a>,
613        mutable: bool,
614    },
615
616    /// Mutation: `Set x to 10.`
617    Set { target: Symbol, value: &'a Expr<'a> },
618
619    /// Reversible register exchange: `Swap x and y.` — the canonical ZERO-GARBAGE reversible
620    /// primitive (`Op::RevSwap`, its own inverse), the first LOGOS surface that emits the abelian
621    /// reversible ISA. Exchanges the two variables' values with no history-tape cost.
622    Swap { a: Symbol, b: Symbol },
623
624    /// Function call as statement: `Call process with data.`
625    Call {
626        function: Symbol,
627        args: Vec<&'a Expr<'a>>,
628    },
629
630    /// Conditional: `If condition: ... Otherwise: ...`
631    If {
632        cond: &'a Expr<'a>,
633        then_block: Block<'a>,
634        else_block: Option<Block<'a>>,
635    },
636
637    /// Loop: `While condition: ...` or `While condition (decreasing expr): ...`
638    While {
639        cond: &'a Expr<'a>,
640        body: Block<'a>,
641        /// Optional decreasing variant for termination proof.
642        decreasing: Option<&'a Expr<'a>>,
643    },
644
645    /// Iteration: `Repeat for x in list: ...` or `Repeat for i from 1 to 10: ...`
646    Repeat {
647        pattern: Pattern, // Changed from `var: Symbol` to support tuple destructuring
648        iterable: &'a Expr<'a>,
649        body: Block<'a>,
650    },
651
652    /// Return: `Return x.` or `Return.`
653    Return { value: Option<&'a Expr<'a>> },
654
655    /// Break: `Break.` — exits the innermost while loop.
656    Break,
657
658    /// Bridge to Logic Kernel: `Assert that P.`
659    Assert { proposition: &'a LogicExpr<'a> },
660
661    /// Documented assertion with justification.
662    /// `Trust that P because "reason".`
663    /// Semantics: Documented runtime check that could be verified statically.
664    Trust {
665        proposition: &'a LogicExpr<'a>,
666        justification: Symbol,
667    },
668
669    /// Runtime assertion with imperative condition.
670    /// `Assert that condition.` (`hard: false` → `debug_assert!`, a development check)
671    /// `Require that condition.` (`hard: true` → `assert!`, an enforced invariant that
672    /// survives release — the form a proven property lowers to).
673    /// `dim` is the physical dimension of a range contract whose literal quantity bounds the
674    /// parser folded to SI magnitudes (`Assume v is between 0.2 volts and 0.7 volts.`) —
675    /// metadata for static consumers (the analog lane); `None` for ordinary conditions.
676    /// `reason` is the `, otherwise <text>` clause: why the contract exists, reported verbatim when
677    /// it breaks and evaluated ONLY then. `None` reports `Assertion failed`.
678    RuntimeAssert {
679        condition: &'a Expr<'a>,
680        hard: bool,
681        dim: Option<logicaffeine_base::dimension::Dimension>,
682        reason: Option<&'a Expr<'a>>,
683    },
684
685    /// `Fail with <reason>.` — raise an error. With no `Result` to return it into and no `Try:`
686    /// region around it, the program stops with `reason` as its report.
687    Fail { reason: &'a Expr<'a> },
688
689    /// Ownership transfer (move): `Give x to processor.`
690    /// Semantics: Move ownership of `object` to `recipient`.
691    Give {
692        object: &'a Expr<'a>,
693        recipient: &'a Expr<'a>,
694    },
695
696    /// Immutable borrow: `Show x to console.`
697    /// Semantics: Immutable borrow of `object` passed to `recipient`.
698    Show {
699        object: &'a Expr<'a>,
700        recipient: &'a Expr<'a>,
701    },
702
703    /// Field mutation: `Set p's x to 10.`
704    SetField {
705        object: &'a Expr<'a>,
706        field: Symbol,
707        value: &'a Expr<'a>,
708    },
709
710    /// Struct definition for codegen.
711    StructDef {
712        name: Symbol,
713        fields: Vec<(Symbol, Symbol, bool)>, // (name, type_name, is_public)
714        is_portable: bool,                   // Derives Serialize/Deserialize
715    },
716
717    /// Function definition.
718    FunctionDef {
719        name: Symbol,
720        /// Generic type parameters: empty for monomorphic functions, e.g. `[T, U]` for polymorphic.
721        generics: Vec<Symbol>,
722        params: Vec<(Symbol, &'a TypeExpr<'a>)>,
723        body: Block<'a>,
724        return_type: Option<&'a TypeExpr<'a>>,
725        is_native: bool,
726        /// Rust path for user-defined native functions (e.g., "reqwest::blocking::get").
727        /// None for system native functions (read, write, etc.) which use map_native_function().
728        native_path: Option<Symbol>,
729        /// Whether this function is exported for FFI (C ABI or WASM).
730        is_exported: bool,
731        /// Export target: None = C ABI (#\[no_mangle\] extern "C"), Some("wasm") = #\[wasm_bindgen\].
732        export_target: Option<Symbol>,
733        /// Per-function optimization config: each `## No <X>` annotation clears
734        /// that optimization's bit (default: all enabled).
735        opt_flags: crate::optimization::OptimizationConfig,
736    },
737
738    /// A `## Test: <prose sentence>` block — an independent test entry point.
739    /// The prose name is the
740    /// test's identity everywhere; duplicates in a module are a parse error.
741    /// Ignored by normal execution; collected by the `largo test` runner.
742    TestDef {
743        /// The prose sentence after the colon, whitespace-normalized.
744        name: Symbol,
745        /// `Skip this test because "<reason>".` — the mandatory reason.
746        skip: Option<Symbol>,
747        /// Capability sentences granting real-world access (sealed by default).
748        capabilities: TestCapabilities,
749        /// `This test may run up to N steps.` — op-budget escalation.
750        budget: Option<u64>,
751        /// `For each of these cases:` + pipe table, when present.
752        cases: Option<CaseTable<'a>>,
753        body: Block<'a>,
754    },
755
756    /// Test-only assertion: `Expect that <condition>.` — records the failure
757    /// and CONTINUES (a test reports every failed expectation, not just the
758    /// first). Refused outside `## Test`/`## Example` blocks.
759    Expect { condition: &'a Expr<'a> },
760
761    /// `Expect this to fail [with "<message>"]:` — the only error-expectation
762    /// form; the test FAILS if the block succeeds.
763    ExpectFail {
764        message: Option<Symbol>,
765        body: Block<'a>,
766    },
767
768    /// `Expect output:` — byte-exact stdout snapshot (in-document or golden file).
769    ExpectOutput { expected: ExpectedOutput },
770
771    /// `Advance time by <duration>.` — moves the sealed world's virtual clock
772    /// (test-only; the statement that makes every timeout test instant).
773    AdvanceTime {
774        /// The advance in milliseconds.
775        millis: &'a Expr<'a>,
776    },
777
778    /// `Given a file "<path>" containing "<content>".` — pre-seeds the sealed
779    /// world's in-memory filesystem (test-only).
780    GivenFile { path: Symbol, content: Symbol },
781
782    /// An observation statement: `Note/Warn/Record that <clause> [with <p> and
783    /// <p>]`. The that-clause is
784    /// captured as the rendered `message`; payloads are the named values that
785    /// travel with the event. Legal anywhere; emission is Wave 7.
786    Observe {
787        category: ObsCategory,
788        /// The that-clause, rendered to text (the event's stable message).
789        message: Symbol,
790        /// Prepositional payloads (`with X and Y`) — name → value expression.
791        payloads: Vec<(Symbol, &'a Expr<'a>)>,
792        /// Deterministic counter-based sampling (`Note once in every N times
793        /// that …`): emit 1-in-N. `None` = always. Sampling is a rendering
794        /// decision, never an evidence decision (replay regenerates the rest).
795        sample: Option<u64>,
796    },
797
798    /// `During <gerund>:` — a lexical trace span (no imperative start/stop, so
799    /// a span can never leak). The body is ordinary code.
800    During {
801        /// The span's name (the gerund phrase or quoted literal), rendered.
802        label: Symbol,
803        body: Block<'a>,
804    },
805
806    /// `For all <domain> <vars> [where <cond>]:` — a property test.
807    /// The runner generates seeded
808    /// cases, binds the vars, runs the body, and shrinks any counterexample.
809    /// Test-only (like `Expect`).
810    ForAll {
811        vars: Vec<Symbol>,
812        domain: PropDomain,
813        /// Optional refinement filter (`where n is greater than 0`).
814        constraint: Option<&'a Expr<'a>>,
815        body: Block<'a>,
816    },
817
818    /// Pattern matching on sum types.
819    Inspect {
820        target: &'a Expr<'a>,
821        arms: Vec<MatchArm<'a>>,
822        has_otherwise: bool, // For exhaustiveness tracking
823    },
824
825    /// Push to collection: `Push x to items.`
826    Push {
827        value: &'a Expr<'a>,
828        collection: &'a Expr<'a>,
829    },
830
831    /// Pop from collection: `Pop from items.` or `Pop from items into y.`
832    Pop {
833        collection: &'a Expr<'a>,
834        into: Option<Symbol>,
835    },
836
837    /// Add to set: `Add x to set.`
838    Add {
839        value: &'a Expr<'a>,
840        collection: &'a Expr<'a>,
841    },
842
843    /// Remove from set: `Remove x from set.`
844    Remove {
845        value: &'a Expr<'a>,
846        collection: &'a Expr<'a>,
847    },
848
849    /// Index assignment: `Set item N of X to Y.`
850    SetIndex {
851        collection: &'a Expr<'a>,
852        index: &'a Expr<'a>,
853        value: &'a Expr<'a>,
854    },
855
856    /// A SCOPE-TRANSPARENT statement sequence — parser-desugar output, never
857    /// written by users. One surface statement can lower to several primitive
858    /// statements (a nested place-write `Set item j of (item i of grid) to v`
859    /// becomes read → copy-on-write element write → write-back; a multi-push
860    /// `Push a, b, c to xs` becomes one Push per element). The body runs in
861    /// the ENCLOSING scope with no block of its own: temporaries inside are
862    /// gensym'd (`__place_*`), so they can never collide with user names, and
863    /// engines that execute blocks with scoping must NOT scope this one.
864    Splice { body: Block<'a> },
865
866    /// A REVERSIBLE / UNCOMPUTE block: `Reversibly:` (alias `Uncompute:`) introducing an
867    /// indented body. Semantically TRANSPARENT — the body runs in the enclosing scope and
868    /// produces byte-identical OUTPUT to the same statements outside the block. The only
869    /// difference is the LOWERING: an IN-PLACE ABELIAN scalar update inside the body compiles
870    /// to the zero-garbage reversible ISA (`Op::RevAdd`/`RevSub`/`RevXor`/`RevNeg`) instead of
871    /// the plain journaling op, so `Vm::run_reverse` can undo the whole region with NO history
872    /// tape (the adiabatic charge-recovery contract). Recognized in-place forms — where `x` is a
873    /// local and `e` provably never observes `x`:
874    /// `Set x to x + e` → `RevAdd`, `Set x to x - e` → `RevSub`,
875    /// `Set x to x xor e` → `RevXor`, `Set x to -x` → `RevNeg`.
876    /// Anything else in the body lowers exactly as it would outside the block.
877    Reversibly { body: Block<'a> },
878
879    /// Memory arena block (Zone).
880    /// "Inside a new zone called 'Scratch':"
881    /// "Inside a zone called 'Buffer' of size 1 MB:"
882    /// "Inside a zone called 'Data' mapped from 'file.bin':"
883    Zone {
884        /// The variable name for the arena handle (e.g., "Scratch")
885        name: Symbol,
886        /// Optional pre-allocated capacity in bytes (Heap zones only)
887        capacity: Option<usize>,
888        /// Optional backing file for memory-mapped zones (literal path or runtime variable)
889        source_file: Option<ZoneSource>,
890        /// The code block executed within this memory context
891        body: Block<'a>,
892    },
893
894    /// Concurrent execution block (async, I/O-bound).
895    /// "Attempt all of the following:"
896    /// Semantics: All tasks run concurrently via tokio::join!
897    /// Best for: network requests, file I/O, waiting operations
898    Concurrent {
899        /// The statements to execute concurrently
900        tasks: Block<'a>,
901    },
902
903    /// Parallel execution block (CPU-bound).
904    /// "Simultaneously:"
905    /// Semantics: True parallelism via rayon::join or thread::spawn
906    /// Best for: computation, data processing, number crunching
907    Parallel {
908        /// The statements to execute in parallel
909        tasks: Block<'a>,
910    },
911
912    /// Read from console or file.
913    /// `Read input from the console.` or `Read data from file "path.txt".`
914    ReadFrom { var: Symbol, source: ReadSource<'a> },
915
916    /// Write to file.
917    /// `Write "content" to file "output.txt".`
918    WriteFile {
919        content: &'a Expr<'a>,
920        path: &'a Expr<'a>,
921    },
922
923    /// Spawn an agent.
924    /// `Spawn a Worker called "w1".`
925    Spawn { agent_type: Symbol, name: Symbol },
926
927    /// Send message to agent.
928    /// `Send Ping to "agent".`, `Send compressed Ping to "agent".`,
929    /// `Send cached Point to "agent".`, or `Send cached compressed Report to "agent".`
930    SendMessage {
931        message: &'a Expr<'a>,
932        destination: &'a Expr<'a>,
933        /// The wire compression codec. `None` for a plain `Send`; `Some(codec)` for
934        /// `Send compressed [with <codec>]` (bare `compressed` = deflate). Kept only
935        /// if it actually shrinks the body.
936        compression: Option<CompressionCodec>,
937        /// `Send cached …` — use the connection's schema dictionary, so a struct
938        /// schema is transmitted once and referenced thereafter (content-addressed,
939        /// footgun-free). `false` for a plain `Send`.
940        cached: bool,
941        /// `Send unchecked …` — drop the wire integrity checksum for the fastest path
942        /// (latency↔safety dial). `false` keeps the default checksum.
943        unchecked: bool,
944        /// `Send fast|compact|packed …` — the wire LAYOUT (size↔speed dial). `None` is
945        /// the default (compact / varint). The sender picks for their link.
946        layout: Option<SendLayout>,
947        /// `Send shared …` — OPT-IN type-id elision: drop struct/enum NAMES off the wire
948        /// (ship a small registry id both ends derive from their shared program type
949        /// defs). Only safe when the receiver runs the same program, so it is OFF by
950        /// default — the default `Send` stays self-describing for any peer / relay.
951        shared: bool,
952        /// `Send computed f …` — COMPUTE-SHIPPING: when the message is a pure single-arg
953        /// function, lower it to a sandboxed generator and ship the COMPUTATION, not data.
954        /// The receiver evaluates it in the bounded sandbox (never arbitrary code). OFF by
955        /// default; a non-lowerable function under `computed` is rejected at send.
956        computed: bool,
957        /// `Send indexed …` (alias `addressable`) — encode a record list in the random-access
958        /// struct-view LAYOUT (row + field offset tables), so the receiver reaches any
959        /// (row, field) in O(1) without decoding the rest — Cap'n Proto's home turf. Composes
960        /// with the other knobs (`compressed`, `cached`, `shared`, `unchecked`). OFF by default
961        /// (the dense columnar form is smaller); opt in when the peer does random field reads.
962        indexed: bool,
963        /// `Send deduped …` — Rc-DEDUP: a subtree the same value reaches more than once ships ONCE
964        /// (the first occurrence) plus a tiny backref for every repeat, and the receiver rebuilds the
965        /// SHARING (one aliased value, not N copies). OFF by default; opt in when the message has
966        /// shared sub-structure (a lookup table referenced by many records, one object aliased
967        /// across the payload). Self-describing by tag, so any peer decodes it.
968        deduped: bool,
969        /// `Send unreliably …` — the transport RELIABILITY dial: an unordered, best-effort
970        /// datagram (may reorder or drop) instead of the reliable, ordered default. The media
971        /// path pairs it with FEC so lossy frames recover without a retransmit stall. `false`
972        /// is the default (reliable, ordered).
973        unreliable: bool,
974    },
975
976    /// Await response from agent.
977    /// `Await response from "agent" into result.`
978    AwaitMessage {
979        source: &'a Expr<'a>,
980        into: Symbol,
981        /// `Await view from …`: hold a received record-list LAZILY (the zero-copy receive —
982        /// decode-on-touch, no rows materialized until a field is read) instead of fully decoding
983        /// it. Ignored for non-record-list shapes, which always decode eagerly.
984        view: bool,
985        /// `Await stream from …`: receive a batch STREAM message and deframe it into a list (the
986        /// values a peer `Stream`ed), rather than a single message.
987        stream: bool,
988    },
989
990    /// Stream a batch of values to a peer in one framed message.
991    /// `Stream readings to "sink".` — frames each element of `values` length-delimited so the
992    /// receiver (`Await stream from …`) deframes them incrementally; one relay publish ships the
993    /// whole batch (Kafka-style streaming that amortizes per-message overhead).
994    StreamMessage {
995        values: &'a Expr<'a>,
996        destination: &'a Expr<'a>,
997    },
998
999    /// Merge CRDT state.
1000    /// `Merge remote into local.` or `Merge remote's field into local's field.`
1001    MergeCrdt {
1002        source: &'a Expr<'a>,
1003        target: &'a Expr<'a>,
1004    },
1005
1006    /// Converge CRDT state by the IDEMPOTENT lattice join — the sibling of [`Stmt::MergeCrdt`].
1007    /// `Converge remote into local.` A bare-`Int` field takes per-field MAX (not ADD), so applying a
1008    /// redelivered state twice equals applying it once; counter/other fields defer to the same rule as
1009    /// `Merge` (already idempotent / last-writer-wins).
1010    JoinCrdt {
1011        source: &'a Expr<'a>,
1012        target: &'a Expr<'a>,
1013    },
1014
1015    /// Increment GCounter.
1016    /// `Increase local's points by 10.`
1017    IncreaseCrdt {
1018        object: &'a Expr<'a>,
1019        field: Symbol,
1020        amount: &'a Expr<'a>,
1021    },
1022
1023    /// Decrement PNCounter (Tally).
1024    /// `Decrease game's score by 5.`
1025    DecreaseCrdt {
1026        object: &'a Expr<'a>,
1027        field: Symbol,
1028        amount: &'a Expr<'a>,
1029    },
1030
1031    /// Append to SharedSequence (RGA).
1032    /// `Append "Hello" to doc's lines.`
1033    AppendToSequence {
1034        sequence: &'a Expr<'a>,
1035        value: &'a Expr<'a>,
1036    },
1037
1038    /// Resolve MVRegister conflicts.
1039    /// `Resolve page's title to "Final".`
1040    ResolveConflict {
1041        object: &'a Expr<'a>,
1042        field: Symbol,
1043        value: &'a Expr<'a>,
1044    },
1045
1046    /// Security check - mandatory runtime guard.
1047    /// `Check that user is admin.`
1048    /// `Check that user can publish the document.`
1049    /// Semantics: NEVER optimized out. Panics if condition is false.
1050    Check {
1051        /// The subject being checked (e.g., "user")
1052        subject: Symbol,
1053        /// The predicate name (e.g., "admin") or action (e.g., "publish")
1054        predicate: Symbol,
1055        /// True if this is a capability check (`can [action]`)
1056        is_capability: bool,
1057        /// For capabilities: the object being acted on (e.g., "document")
1058        object: Option<Symbol>,
1059        /// Original English text for error message
1060        source_text: String,
1061        /// Source location for error reporting
1062        span: crate::token::Span,
1063    },
1064
1065    /// Listen on network address.
1066    /// `Listen on "/ip4/127.0.0.1/tcp/8000".`
1067    /// Semantics: Bind to address, start accepting connections via libp2p
1068    Listen {
1069        address: &'a Expr<'a>,
1070        /// Optional PNP one-time-pad binding: `with pad "<path>" as initiator|responder`.
1071        secure: Option<SecurePad<'a>>,
1072    },
1073
1074    /// Serve HTTP requests on a port with a handler function.
1075    /// `Serve on port 8080 with handleRequest.`
1076    /// Semantics: bind an HTTP server on the port and, per request, invoke the
1077    /// handler (a `Request -> Response` function) and write back its response.
1078    Serve {
1079        port: &'a Expr<'a>,
1080        handler: &'a Expr<'a>,
1081    },
1082
1083    /// Connect to remote peer.
1084    /// `Connect to "/ip4/127.0.0.1/tcp/8000".`
1085    /// Semantics: Dial peer via libp2p
1086    ConnectTo {
1087        address: &'a Expr<'a>,
1088        /// Optional PNP one-time-pad binding: `with pad "<path>" as initiator|responder`.
1089        secure: Option<SecurePad<'a>>,
1090    },
1091
1092    /// Create PeerAgent remote handle.
1093    /// `Let remote be a PeerAgent at "/ip4/127.0.0.1/tcp/8000".`
1094    /// Semantics: Create handle for remote agent communication
1095    LetPeerAgent { var: Symbol, address: &'a Expr<'a> },
1096
1097    /// Sleep for milliseconds.
1098    /// `Sleep 1000.` or `Sleep delay.`
1099    /// Semantics: Pause execution for N milliseconds (async)
1100    Sleep { milliseconds: &'a Expr<'a> },
1101
1102    /// Sync CRDT variable on topic.
1103    /// `Sync x on "topic".`
1104    /// Semantics: Subscribe to GossipSub topic, auto-publish on mutation, auto-merge on receive
1105    Sync { var: Symbol, topic: &'a Expr<'a> },
1106
1107    /// One of the English things a component action DOES: an element verb, navigation,
1108    /// persistence, feedback, a store call, or a timer ([`UiStmt`]). First-class: every tier
1109    /// implements it natively rather than receiving a desugared builtin call.
1110    Ui(UiStmt<'a>),
1111
1112    /// A typed request: `Get URL as T, then action.` / `Post <body> to URL as T, then action.`
1113    /// The completion action receives `Result of T and HttpError` — the decode is derived from
1114    /// `as_type`, and a non-2xx status becomes the `Err` side. No implicit retry.
1115    Fetch {
1116        method: FetchMethod,
1117        url: &'a Expr<'a>,
1118        /// The request body (`Post <body> to …`); `None` for `Get` / `Delete`.
1119        body: Option<&'a Expr<'a>>,
1120        as_type: &'a TypeExpr<'a>,
1121        /// The action the response is delivered to.
1122        then: Symbol,
1123    },
1124
1125    /// `Replay these actions: a, b, c.` — re-run a sequence of the page's actions, in order.
1126    ///
1127    /// The journal's reason for existing: a bug report becomes a test by naming the actions that
1128    /// produced it, and the dev panel's time travel is this with a slider on it. Each one is a
1129    /// REAL TURN — it rolls back if it traps, it is journalled, and the page repaints — because a
1130    /// replay that bypassed the turn machinery would reproduce a different bug from the one being
1131    /// investigated.
1132    Replay { actions: Vec<Symbol> },
1133
1134    /// `Serve fetches with routes.` — answer the page's requests from the program's OWN routes.
1135    ///
1136    /// The full-stack loop with no network: a `Get "/api/todo"` is answered by the matching
1137    /// `## Route`, through the derived encoder on the way out and the derived decoder on the way
1138    /// back. That round trip is the only thing that can catch the two halves of the wire
1139    /// contract drifting apart — a stub answers with whatever the test author typed, which
1140    /// agrees with itself no matter what the encoder does.
1141    ///
1142    /// A DECISION a test makes, never a default: a page whose fetches were silently answered by
1143    /// the local route table would pass tests that a deployed page fails, because in a browser
1144    /// nothing local answers anything.
1145    ServeFetches,
1146
1147    /// `Given that METHOD "/url" answers STATUS with BODY.` — how a test answers a fetch.
1148    ///
1149    /// The sealed-world rule the rest of the suite follows: a page test must not depend on a
1150    /// network, and a page whose data never arrives is a page that proves nothing. Matched by
1151    /// method AND url together, because a stub that answered the wrong request is how a test
1152    /// ends up proving something nobody asked for.
1153    GivenFetch {
1154        method: Symbol,
1155        url: &'a Expr<'a>,
1156        status: &'a Expr<'a>,
1157        body: &'a Expr<'a>,
1158    },
1159
1160    /// An LGX page / component / store / error page — the component model, first-class
1161    /// (see [`crate::ast::component`]). Every tier implements it natively.
1162    ComponentDef(Box<crate::ast::component::ComponentDef<'a>>),
1163
1164    /// `## Directive name (el: Element) and (value: T):` — a custom attribute behavior:
1165    /// `body` runs when the attribute appears on an element and whenever its value changes;
1166    /// `removed` (a `When removed:` block) runs when the element leaves.
1167    DirectiveDef {
1168        name: Symbol,
1169        params: Vec<(Symbol, &'a TypeExpr<'a>)>,
1170        body: Block<'a>,
1171        removed: Option<Block<'a>>,
1172    },
1173
1174    /// `## Route METHOD /path (params) -> T:` — a typed HTTP route.
1175    RouteDef {
1176        method: Symbol,
1177        path: Symbol,
1178        params: Vec<(Symbol, &'a TypeExpr<'a>)>,
1179        return_type: Option<&'a TypeExpr<'a>>,
1180        /// ★ BOXED, AND THE REASON IS THE WHOLE NODE'S SIZE. `RouteBody` is 88 bytes, which made
1181        /// `RouteDef` 144 — the single widest `Stmt` variant, and therefore the size of EVERY `Stmt`.
1182        /// `compiler_stack_safety_lock::ast_nodes_stay_small` holds the node to 128 bytes because the
1183        /// compiler walk keeps many per frame, so widening it multiplies stack use across every tier.
1184        /// A route's body is the rare payload and does not belong inline; `ComponentDef` next door is
1185        /// boxed for the same reason.
1186        body: Box<crate::ast::component::RouteBody<'a>>,
1187        /// Where the route was declared. A `## Route` is refused for reasons the author has to
1188        /// go and look at — a parameter type the path matcher cannot bind, an answer type the
1189        /// derived codecs do not cover — and those refusals had nowhere to point.
1190        span: Span,
1191    },
1192
1193    /// `## Before each request (request: Request) -> Option of Response:` — middleware.
1194    MiddlewareDef {
1195        param: (Symbol, &'a TypeExpr<'a>),
1196        body: Block<'a>,
1197    },
1198
1199    /// `## Redirect /from -> /to.`
1200    RedirectDef { from: Symbol, to: Symbol },
1201
1202    /// Mount persistent CRDT from journal file.
1203    /// `Mount counter at "data/counter.journal".`
1204    /// Semantics: Load or create journal, replay operations to reconstruct state
1205    Mount {
1206        /// The variable name for the mounted value
1207        var: Symbol,
1208        /// The path expression for the journal file
1209        path: &'a Expr<'a>,
1210    },
1211
1212    // =========================================================================
1213    // Go-like Concurrency (Green Threads, Channels, Select)
1214    // =========================================================================
1215    /// Launch a fire-and-forget task (green thread).
1216    /// `Launch a task to process(data).`
1217    /// Semantics: tokio::spawn with no handle capture
1218    LaunchTask {
1219        /// The function to call
1220        function: Symbol,
1221        /// Arguments to pass
1222        args: Vec<&'a Expr<'a>>,
1223    },
1224
1225    /// Launch a task with handle for control.
1226    /// `Let worker be Launch a task to process(data).`
1227    /// Semantics: tokio::spawn returning JoinHandle
1228    LaunchTaskWithHandle {
1229        /// Variable to bind the handle
1230        handle: Symbol,
1231        /// The function to call
1232        function: Symbol,
1233        /// Arguments to pass
1234        args: Vec<&'a Expr<'a>>,
1235    },
1236
1237    /// Create a bounded channel (pipe).
1238    /// `Let jobs be a new Pipe of Int.`
1239    /// Semantics: tokio::sync::mpsc::channel(32)
1240    CreatePipe {
1241        /// Variable for the pipe
1242        var: Symbol,
1243        /// Type of values in the pipe
1244        element_type: Symbol,
1245        /// Optional capacity (defaults to 32)
1246        capacity: Option<u32>,
1247    },
1248
1249    /// Blocking send into pipe.
1250    /// `Send value into pipe.`
1251    /// Semantics: pipe_tx.send(value).await
1252    SendPipe {
1253        /// The value to send
1254        value: &'a Expr<'a>,
1255        /// The pipe to send into
1256        pipe: &'a Expr<'a>,
1257    },
1258
1259    /// Blocking receive from pipe.
1260    /// `Receive x from pipe.`
1261    /// Semantics: let x = pipe_rx.recv().await
1262    ReceivePipe {
1263        /// Variable to bind the received value
1264        var: Symbol,
1265        /// The pipe to receive from
1266        pipe: &'a Expr<'a>,
1267    },
1268
1269    /// Non-blocking send (try).
1270    /// `Try to send value into pipe.`
1271    /// Semantics: pipe_tx.try_send(value) - returns immediately
1272    TrySendPipe {
1273        /// The value to send
1274        value: &'a Expr<'a>,
1275        /// The pipe to send into
1276        pipe: &'a Expr<'a>,
1277        /// Variable to bind the result (true/false)
1278        result: Option<Symbol>,
1279    },
1280
1281    /// Non-blocking receive (try).
1282    /// `Try to receive x from pipe.`
1283    /// Semantics: pipe_rx.try_recv() - returns Option
1284    TryReceivePipe {
1285        /// Variable to bind the received value (if any)
1286        var: Symbol,
1287        /// The pipe to receive from
1288        pipe: &'a Expr<'a>,
1289    },
1290
1291    /// Cancel a spawned task.
1292    /// `Stop worker.`
1293    /// Semantics: handle.abort()
1294    StopTask {
1295        /// The handle to cancel
1296        handle: &'a Expr<'a>,
1297    },
1298
1299    /// Close a channel (pipe).
1300    /// `Close ch.` or `Close the pipe ch.`
1301    /// Semantics: mark the channel closed so pending/future receivers wake with the
1302    /// closed signal (`Op::ChanClose`). Buffered values stay receivable; a later send
1303    /// is the error. The deterministic-scheduler sibling of `Stop` for tasks.
1304    CloseChannel {
1305        /// The channel to close
1306        channel: &'a Expr<'a>,
1307    },
1308
1309    /// Await a spawned task handle's completion.
1310    /// `Await worker.` or `Wait for worker.` (optionally `… into result`).
1311    /// Semantics: park until the task finishes, taking its result (`Op::TaskAwait`).
1312    /// The join sibling of `Stop` (which cancels) — this waits for and observes the
1313    /// child's completion.
1314    AwaitTask {
1315        /// The task handle to join.
1316        handle: &'a Expr<'a>,
1317        /// Optional binding for the task's result (`… into r`); `None` discards it.
1318        result: Option<Symbol>,
1319    },
1320
1321    /// Select on multiple channels/timeouts.
1322    /// `Await the first of:`
1323    ///     `Receive x from ch:`
1324    ///         `...`
1325    ///     `After 5 seconds:`
1326    ///         `...`
1327    /// Semantics: tokio::select! with auto-cancel
1328    Select {
1329        /// The branches to select from
1330        branches: Vec<SelectBranch<'a>>,
1331    },
1332
1333    /// Theorem block.
1334    /// `## Theorem: Name`
1335    /// `Given: Premise.`
1336    /// `Prove: Goal.`
1337    /// `Proof: Auto.`
1338    Theorem(TheoremBlock<'a>),
1339
1340    /// `## Define` block — a vernacular-logic predicate definition (Rung 0a).
1341    /// `x is a bachelor if and only if x is unmarried and x is a man.`
1342    /// Non-executable: like [`Stmt::Theorem`], it is a declaration the proof
1343    /// layer consumes, not code the VM/AOT runs.
1344    Definition(DefinitionBlock<'a>),
1345
1346    /// `## Axiom` block — a named first-order axiom in formal notation. Registers a
1347    /// shared premise for later theorems (the seam for an axiomatic base like Tarski).
1348    Axiom(AxiomBlock),
1349
1350    /// `## Theory` block — a named development grouping formal axioms and theorems.
1351    Theory(TheoryBlock),
1352
1353    /// Escape hatch: embed raw foreign code.
1354    /// `Escape to Rust:` followed by an indented block of raw code.
1355    ///
1356    /// Variables from the enclosing LOGOS scope are available in the
1357    /// escape block as their generated Rust types. The raw code is
1358    /// emitted verbatim inside a `{ ... }` block in the generated Rust.
1359    Escape {
1360        /// Target language ("Rust" for now, forward-compatible with "Python", "WGSL", etc.)
1361        language: Symbol,
1362        /// Raw foreign code, captured verbatim with base indentation stripped.
1363        code: Symbol,
1364        /// Source span covering the entire escape block (header + body).
1365        span: crate::token::Span,
1366    },
1367
1368    /// Dependency declaration from `## Requires` block.
1369    /// The "serde" crate version "1.0" with features "derive".
1370    Require {
1371        crate_name: Symbol,
1372        version: Symbol,
1373        features: Vec<Symbol>,
1374        span: crate::token::Span,
1375    },
1376
1377    /// ★ A RUNTIME FAILURE-SITE MARKER (Wave 3: "runtime failures carry a location") — no `Stmt`
1378    /// variant carries a span (this one included: its OWN payload is an opaque id, not a span), so
1379    /// a trap deep inside an action's body has never been able to say WHERE in the source it
1380    /// happened. This is the fix, and it is a MARKER rather than a span field on every `Stmt`
1381    /// variant on purpose: giving every variant a span is a schema change touching every
1382    /// constructor and every exhaustive match in the workspace for a span most of them never need
1383    /// (a `Let` inside a `## Main` that never fails costs nothing to leave unmarked). A `Site(id)`
1384    /// is inserted as its OWN statement, immediately before the sentence it marks, by
1385    /// `Parser::parse_indented_block` whenever `Parser::site_tracking` names a component and
1386    /// action — so it travels through the ordinary statement pipeline into every backend's own
1387    /// compiled form (bytecode, wasm, C, …) exactly like any other statement, which a parse-time-
1388    /// only side table (`Parser::stmt_spans`) cannot: that table is gone by the time a COMPILED
1389    /// program traps at runtime, and `stmt_spans` covers only top-level statements besides.
1390    ///
1391    /// `id` indexes [`Parser::failure_sites`] (built as each marker is inserted) for the
1392    /// `(file, span, component, action)` it names. Every backend that runs a `Stmt` must accept
1393    /// this variant in an EXPLICIT arm, not a wildcard — this file's own doc history is full of
1394    /// wildcard arms that silently swallowed a case nobody noticed was reachable; a backend with
1395    /// nothing to do here yet says so by name (`Stmt::Site(_) => {}` or equivalent), so the day it
1396    /// DOES need to do something, the compiler — not a bug report — is what tells whoever adds a
1397    /// new backend that this one still needs it. The tree-walker's job with it is the simplest one
1398    /// there is: `current site = id` (`FailureSite`'s own doc comment says why this is enough for a
1399    /// location); every OTHER backend, not yet given a reason to do more, ignores it explicitly and
1400    /// moves on.
1401    ///
1402    /// [`Parser::failure_sites`]: crate::Parser::failure_sites
1403    Site(u32),
1404}
1405
1406/// One entry in [`Parser::failure_sites`] — everything a runtime failure needs to point BACK at
1407/// the sentence a [`Stmt::Site`] marker stood in front of.
1408///
1409/// ★ "CURRENT SITE = n" IS ENOUGH, AND HERE IS WHY. A trap does not need a call stack to be useful
1410/// — LOGOS actions do not recurse into each other's OWN bodies the way a general-purpose language's
1411/// functions do (an action calls another via `Call <Store>'s <action>`, a dispatch through data, not
1412/// a nested nomination-time invocation whose OWN Sites would need distinguishing on a stack) — so
1413/// "which Site did the runtime most recently pass through" already answers "which sentence trapped"
1414/// unambiguously, for the same reason a program counter alone (no full backtrace) already answers it
1415/// in a language with no first-class stack frames to unwind through. A future construct that DOES
1416/// nest one action's failure inside another's turn is exactly the case that would need this
1417/// reconsidered — flagging it here so nobody has to rediscover why a stack was not built.
1418///
1419/// ★ NO `file` FIELD, ON PURPOSE. A `Parser` parses ONE flat token stream and has no concept of
1420/// splicing at all — `loader::apply_prelude_mapped` assembles a user file plus its demand-imported
1421/// stdlib modules into that ONE stream BEFORE the parser ever sees it, and `ui_bridge.rs`'s checked
1422/// seam is what undoes the splice, exactly once, on whatever span leaves the compile pipeline (item
1423/// 10 of this session's own record — the double-mapping bug that fix closed). `span` here is in the
1424/// SAME spliced coordinates every other span this parser hands out is in, for the same reason: a
1425/// second, bespoke translation point for `FailureSite` spans specifically would be exactly the
1426/// double-mapping shape that bug already was. Whoever renders a `FailureSite` for a person translates
1427/// it through the SAME seam every other diagnostic in this pipeline already goes through.
1428///
1429/// [`Parser::failure_sites`]: crate::Parser::failure_sites
1430#[derive(Debug, Clone, Copy)]
1431pub struct FailureSite {
1432    /// Where the marked sentence is, in spliced coordinates — see the field's own note above for
1433    /// why there is no separate `file` to pair it with.
1434    pub span: crate::token::Span,
1435    /// The component (or store, or page) whose action/handler this sentence is written in.
1436    pub component: Symbol,
1437    /// The action or event handler this sentence belongs to — `__e3`-style synthesized names for a
1438    /// `When …:` handler, same as every other place this pipeline names one.
1439    pub action: Symbol,
1440}
1441
1442impl FailureSite {
1443    /// `message` (the runtime error text itself, unchanged) wrapped with WHICH sentence raised it
1444    /// — `component`/`action`, in the author's own words wherever this site can recover them.
1445    /// Deliberately does NOT touch `file:line:col`: `span` is still in spliced coordinates (this
1446    /// struct's own doc comment says why there is no `file` to pair it with), and turning a byte
1447    /// offset into a line/column needs the source text this crate never holds once parsing ends —
1448    /// that translation is `ui_bridge.rs`'s checked seam's job, on the SAME span, same as every
1449    /// other diagnostic; this method only ever supplies the component/action half.
1450    ///
1451    /// An event handler's `action` is a synthesized `__e<n>` (`lgx_lower.rs::action_fn_name`'s own
1452    /// numbering) — never a name the author wrote, so it is named generically ("an event handler")
1453    /// rather than surfaced verbatim. An ordinary `To <name>:` action's own name IS what the author
1454    /// wrote, and is quoted as `` `To <name>` `` to read the same way the section that declares it
1455    /// does.
1456    pub fn render(&self, interner: &Interner, message: &str) -> String {
1457        let component = interner.resolve(self.component);
1458        let action = interner.resolve(self.action);
1459        let is_synthesized_event_name = action
1460            .strip_prefix("__e")
1461            .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()));
1462        let where_ = if is_synthesized_event_name {
1463            format!("an event handler in `{component}`")
1464        } else {
1465            format!("`To {action}` in `{component}`")
1466        };
1467        format!("{where_}: {message}")
1468    }
1469}
1470
1471/// A branch in a Select statement.
1472#[derive(Debug, Clone)]
1473pub enum SelectBranch<'a> {
1474    /// Receive from a pipe: `Receive x from ch:`
1475    Receive {
1476        var: Symbol,
1477        pipe: &'a Expr<'a>,
1478        body: Block<'a>,
1479    },
1480    /// Timeout: `After N seconds:` or `After N milliseconds:`
1481    Timeout {
1482        milliseconds: &'a Expr<'a>,
1483        body: Block<'a>,
1484    },
1485}
1486
1487/// Shared expression type for pure computations (LOGOS §15.0.0).
1488///
1489/// Expr is used by both LogicExpr (as terms) and Stmt (as values).
1490/// These are pure computations without side effects.
1491#[derive(Debug)]
1492pub enum Expr<'a> {
1493    /// Literal value: 42, "hello", true, nothing
1494    Literal(Literal),
1495
1496    /// Variable reference: x
1497    Identifier(Symbol),
1498
1499    /// Binary operation: x plus y
1500    BinaryOp {
1501        op: BinaryOpKind,
1502        left: &'a Expr<'a>,
1503        right: &'a Expr<'a>,
1504    },
1505
1506    /// Unary NOT: "not x" → `!x` (logical for Bool, bitwise for Int)
1507    Not { operand: &'a Expr<'a> },
1508
1509    /// Function call as expression: f(x, y)
1510    Call {
1511        function: Symbol,
1512        args: Vec<&'a Expr<'a>>,
1513    },
1514
1515    /// Dynamic index access: `items at i` (1-indexed).
1516    Index {
1517        collection: &'a Expr<'a>,
1518        index: &'a Expr<'a>,
1519    },
1520
1521    /// Dynamic slice access: `items 1 through mid` (1-indexed, inclusive).
1522    Slice {
1523        collection: &'a Expr<'a>,
1524        start: &'a Expr<'a>,
1525        end: &'a Expr<'a>,
1526    },
1527
1528    /// Copy expression: `copy of slice` → slice.to_vec().
1529    Copy { expr: &'a Expr<'a> },
1530
1531    /// Give expression: `Give x` → transfers ownership, no clone needed.
1532    /// Used in function calls to explicitly move values.
1533    Give { value: &'a Expr<'a> },
1534
1535    /// Length expression: `length of items` → items.len().
1536    Length { collection: &'a Expr<'a> },
1537
1538    /// Set contains: `set contains x` or `x in set`
1539    Contains {
1540        collection: &'a Expr<'a>,
1541        value: &'a Expr<'a>,
1542    },
1543
1544    /// Set union: `a union b`
1545    Union {
1546        left: &'a Expr<'a>,
1547        right: &'a Expr<'a>,
1548    },
1549
1550    /// Set intersection: `a intersection b`
1551    Intersection {
1552        left: &'a Expr<'a>,
1553        right: &'a Expr<'a>,
1554    },
1555
1556    /// Get manifest of a zone.
1557    /// `the manifest of Zone` → FileSipper::from_zone(&zone).manifest()
1558    ManifestOf { zone: &'a Expr<'a> },
1559
1560    /// Get chunk at index from a zone.
1561    /// `the chunk at N in Zone` → FileSipper::from_zone(&zone).get_chunk(N)
1562    ChunkAt {
1563        index: &'a Expr<'a>,
1564        zone: &'a Expr<'a>,
1565    },
1566
1567    /// List literal: [1, 2, 3]
1568    List(Vec<&'a Expr<'a>>),
1569
1570    /// Tuple literal: (1, "hello", true)
1571    Tuple(Vec<&'a Expr<'a>>),
1572
1573    /// Range: 1 to 10 (inclusive)
1574    Range {
1575        start: &'a Expr<'a>,
1576        end: &'a Expr<'a>,
1577    },
1578
1579    /// Field access: `p's x` or `the x of p`.
1580    FieldAccess { object: &'a Expr<'a>, field: Symbol },
1581
1582    /// Constructor: `a new Point` or `a new Point with x 10 and y 20`.
1583    /// Supports generics: `a new Box of Int` and nested types: `a new Seq of (Seq of Int)`
1584    New {
1585        type_name: Symbol,
1586        type_args: Vec<TypeExpr<'a>>, // Empty for non-generic types - now supports nested types
1587        init_fields: Vec<(Symbol, &'a Expr<'a>)>, // Optional field initialization
1588    },
1589
1590    /// Enum variant constructor: `a new Circle with radius 10`.
1591    NewVariant {
1592        enum_name: Symbol,                   // Shape (resolved from registry)
1593        variant: Symbol,                     // Circle
1594        fields: Vec<(Symbol, &'a Expr<'a>)>, // [(radius, 10)]
1595    },
1596
1597    /// Escape hatch expression: raw foreign code that produces a value.
1598    /// Used in expression position: `Let x: Int be Escape to Rust:`
1599    Escape { language: Symbol, code: Symbol },
1600
1601    /// Option Some: `some 30` → Some(30)
1602    OptionSome { value: &'a Expr<'a> },
1603
1604    /// Option None: `none` → None
1605    OptionNone,
1606
1607    /// Pre-allocation capacity hint wrapping an inner value expression.
1608    /// `"" with capacity 100` or `a new Seq of Int with capacity n`
1609    /// Codegen uses with_capacity(); interpreter ignores the hint.
1610    WithCapacity {
1611        value: &'a Expr<'a>,
1612        capacity: &'a Expr<'a>,
1613    },
1614
1615    /// Closure expression: `(params) -> body` or `(params) ->:` block body.
1616    /// Captures variables from the enclosing scope by value (snapshot/clone).
1617    Closure {
1618        params: Vec<(Symbol, &'a TypeExpr<'a>)>,
1619        body: ClosureBody<'a>,
1620        return_type: Option<&'a TypeExpr<'a>>,
1621    },
1622
1623    /// Call an expression that evaluates to a callable value.
1624    /// `f(x)` where `f` is a variable holding a closure, not a named function.
1625    CallExpr {
1626        callee: &'a Expr<'a>,
1627        args: Vec<&'a Expr<'a>>,
1628    },
1629
1630    /// Interpolated string: `"Hello, {name}! Value: {x:.2}"`
1631    InterpolatedString(Vec<StringPart<'a>>),
1632
1633    /// A template literal — the body of a `## To … -> View:` function: a view tree that
1634    /// renders wherever the returned `View` value is placed.
1635    View(Box<crate::ast::view::ViewDef<'a>>),
1636
1637    /// A question about the rendered page: `the text of "#draft"`, `the count of ".row"`.
1638    /// An ordinary expression, so every assertion form already works on it — a page test
1639    /// needs no statements of its own.
1640    Dom(DomQuery<'a>),
1641}
1642
1643/// What `the <thing> of <selector>` asks the page.
1644#[derive(Debug, Clone)]
1645pub enum DomQuery<'a> {
1646    /// `the text of SEL` — the element's text content (its own text plus its descendants').
1647    Text { selector: &'a Expr<'a> },
1648    /// `the count of SEL` — how many elements match.
1649    Count { selector: &'a Expr<'a> },
1650    /// `the value of SEL` — an input's current value.
1651    Value { selector: &'a Expr<'a> },
1652    /// `SEL is visible` — whether anything matches at all.
1653    Visible { selector: &'a Expr<'a> },
1654    /// `SEL is hidden` — the exact complement of `visible`, so an element is always one or the
1655    /// other and a test written with either word is complete.
1656    Hidden { selector: &'a Expr<'a> },
1657    /// `SEL is disabled` — whether the match carries the `disabled` attribute. A PRESENCE, like
1658    /// the render: asking by comparing against the string `"false"` would call an enabled
1659    /// control disabled.
1660    Disabled { selector: &'a Expr<'a> },
1661    /// `SEL is checked` — a checkbox's or radio's LIVE state, which is a property rather than an
1662    /// attribute (see `DomOp::SetChecked`), so this follows a click.
1663    Checked { selector: &'a Expr<'a> },
1664    /// `SEL is focused` — whether the match is the element focus is on.
1665    Focused { selector: &'a Expr<'a> },
1666    /// `the journal` — the ACTIONS that have run, in order, as a `Seq of Text`.
1667    ///
1668    /// A value rather than a bespoke assertion, so `the count of`, `contains` and `item N of`
1669    /// all work on it and the ordinary questions need no journal-specific vocabulary.
1670    Journal,
1671    /// `the journal shows A then B` — did `A` run and `B` run AFTER it?
1672    ///
1673    /// The one question a sequence operation cannot ask without an index-of. "Then" means after,
1674    /// not immediately after: pinning adjacency would break a test every time an unrelated turn
1675    /// appeared between the two it cares about.
1676    JournalShows { first: Symbol, second: Symbol },
1677    /// `the title` — the page title.
1678    Title,
1679    /// `the URL` — the current path.
1680    Url,
1681}
1682
1683impl<'a> DomQuery<'a> {
1684    /// The selector expression, when the query has one.
1685    pub fn selector(&self) -> Option<&'a Expr<'a>> {
1686        match self {
1687            DomQuery::Text { selector }
1688            | DomQuery::Count { selector }
1689            | DomQuery::Value { selector }
1690            | DomQuery::Visible { selector }
1691            | DomQuery::Hidden { selector }
1692            | DomQuery::Disabled { selector }
1693            | DomQuery::Checked { selector }
1694            | DomQuery::Focused { selector } => Some(selector),
1695            DomQuery::Title | DomQuery::Url | DomQuery::Journal | DomQuery::JournalShows { .. } => {
1696                None
1697            }
1698        }
1699    }
1700
1701    /// The English word this query reads as — for messages and shape printers.
1702    pub fn noun(&self) -> &'static str {
1703        match self {
1704            DomQuery::Text { .. } => "text",
1705            DomQuery::Count { .. } => "count",
1706            DomQuery::Value { .. } => "value",
1707            DomQuery::Visible { .. } => "visible",
1708            DomQuery::Hidden { .. } => "hidden",
1709            DomQuery::Disabled { .. } => "disabled",
1710            DomQuery::Checked { .. } => "checked",
1711            DomQuery::Focused { .. } => "focused",
1712            DomQuery::Journal => "journal",
1713            DomQuery::JournalShows { .. } => "journal ordering",
1714            DomQuery::Title => "title",
1715            DomQuery::Url => "URL",
1716        }
1717    }
1718}
1719
1720/// A segment of an interpolated string.
1721#[derive(Debug, Clone)]
1722pub enum StringPart<'a> {
1723    /// Literal text segment
1724    Literal(Symbol),
1725    /// Expression with optional format specifier
1726    Expr {
1727        value: &'a Expr<'a>,
1728        format_spec: Option<Symbol>,
1729        /// Self-documenting debug format: `{var=}` → `"var=42"`
1730        debug: bool,
1731    },
1732}
1733
1734/// Body of a closure expression.
1735#[derive(Debug, Clone)]
1736pub enum ClosureBody<'a> {
1737    /// Single expression: `(n: Int) -> n * 2`
1738    Expression(&'a Expr<'a>),
1739    /// Block of statements: `(n: Int) ->:` followed by indented body
1740    Block(Block<'a>),
1741}
1742
1743/// Literal values in LOGOS.
1744#[derive(Debug, Clone)]
1745pub enum Literal {
1746    /// Integer literal
1747    Number(i64),
1748    /// Float literal
1749    Float(f64),
1750    /// Text literal
1751    Text(Symbol),
1752    /// Boolean literal
1753    Boolean(bool),
1754    /// The nothing literal (unit type)
1755    Nothing,
1756    /// Character literal
1757    Char(char),
1758    /// Duration literal (nanoseconds, signed for negative offsets like "5 minutes early")
1759    Duration(i64),
1760    /// Date literal (days since Unix epoch 1970-01-01)
1761    Date(i32),
1762    /// Moment literal (nanoseconds since Unix epoch)
1763    Moment(i64),
1764    /// Calendar span (months, days) - NOT flattened to seconds
1765    /// Months and days are kept separate because they're incommensurable.
1766    Span { months: i32, days: i32 },
1767    /// Time-of-day literal (nanoseconds from midnight)
1768    /// Range: 0 to 86_399_999_999_999 (just under 24 hours)
1769    Time(i64),
1770}
1771
1772impl PartialEq for Literal {
1773    fn eq(&self, other: &Self) -> bool {
1774        match (self, other) {
1775            (Literal::Number(a), Literal::Number(b)) => a == b,
1776            (Literal::Float(a), Literal::Float(b)) => a.to_bits() == b.to_bits(),
1777            (Literal::Text(a), Literal::Text(b)) => a == b,
1778            (Literal::Boolean(a), Literal::Boolean(b)) => a == b,
1779            (Literal::Nothing, Literal::Nothing) => true,
1780            (Literal::Char(a), Literal::Char(b)) => a == b,
1781            (Literal::Duration(a), Literal::Duration(b)) => a == b,
1782            (Literal::Date(a), Literal::Date(b)) => a == b,
1783            (Literal::Moment(a), Literal::Moment(b)) => a == b,
1784            (
1785                Literal::Span {
1786                    months: m1,
1787                    days: d1,
1788                },
1789                Literal::Span {
1790                    months: m2,
1791                    days: d2,
1792                },
1793            ) => m1 == m2 && d1 == d2,
1794            (Literal::Time(a), Literal::Time(b)) => a == b,
1795            _ => false,
1796        }
1797    }
1798}
1799
1800impl Eq for Literal {}
1801
1802impl std::hash::Hash for Literal {
1803    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1804        std::mem::discriminant(self).hash(state);
1805        match self {
1806            Literal::Number(n) => n.hash(state),
1807            Literal::Float(f) => f.to_bits().hash(state),
1808            Literal::Text(s) => s.hash(state),
1809            Literal::Boolean(b) => b.hash(state),
1810            Literal::Nothing => {}
1811            Literal::Char(c) => c.hash(state),
1812            Literal::Duration(d) => d.hash(state),
1813            Literal::Date(d) => d.hash(state),
1814            Literal::Moment(m) => m.hash(state),
1815            Literal::Span { months, days } => {
1816                months.hash(state);
1817                days.hash(state);
1818            }
1819            Literal::Time(t) => t.hash(state),
1820        }
1821    }
1822}