tatara-lisp 0.3.48

Homoiconic S-expression reader + macroexpander — the pleme-io Lisp authoring surface, hermetic-build standalone
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
//! Generic Lisp-to-type compiler — drives `#[derive(TataraDomain)]` types.
//!
//! This module used to contain a 1200-line hand-rolled compiler for a single
//! domain (ProcessSpec). The derive macro now handles every typed domain
//! uniformly, so this file shrinks to a thin pipeline: read → macroexpand →
//! dispatch to derive-generated `compile_from_args`.
//!
//! Two entry points:
//!   - `compile_typed::<T>(src)` — every `(T::KEYWORD :k v …)` form becomes
//!     one `T`. Returns `Vec<T>`.
//!   - `compile_named::<T>(src)` — every `(T::KEYWORD NAME :k v …)` form
//!     (positional name after keyword) becomes one `NamedDefinition<T>`.
//!     This is the shape used by ProcessSpec / `(defpoint name …)`.

use crate::ast::Sexp;
use crate::domain::TataraDomain;
use crate::error::{LispError, Result};
use crate::macro_expand::Expander;
use crate::reader::read;

/// Typed-keyword dispatchers on the `Expander` surface — the
/// `T: TataraDomain`-shaped sibling family of
/// [`Expander::expand_and_collect_calls_to`] (from-forms posture) and
/// [`Expander::expand_source_and_collect_calls_to`] (from-source posture).
///
/// The family is closed across TWO axes: input posture (from-forms +
/// from-source) × form shape (typed bare-kwargs + named NAME-then-kwargs).
/// Each cell is ONE typed method on `Expander`, binding `(T::KEYWORD,
/// projection-for-T)` at the type level through `T`:
///
/// |              | typed bare-kwargs            | named NAME-then-kwargs        |
/// |--------------|------------------------------|-------------------------------|
/// | from-forms   | [`expand_to_typed`](Self::expand_to_typed)   | [`expand_to_named`](Self::expand_to_named)   |
/// | from-source  | [`expand_source_to_typed`](Self::expand_source_to_typed) | [`expand_source_to_named`](Self::expand_source_to_named) |
///
/// The from-source row composes `crate::reader::read` with its from-forms
/// row sibling — `read(src)? + <expander>.expand_to_typed::<T>(forms)` —
/// so the typed-pair `(T::KEYWORD, projection-for-T)` is bound in ONE
/// place per form shape (the from-forms row), and the from-source row
/// inherits the binding through delegation. A regression that mis-pairs
/// `T::KEYWORD` with `U::compile_from_args` (where `T != U`) is
/// structurally impossible at any site: the type parameter binds both
/// substitutions together inside ONE method body per form shape.
impl Expander {
    /// Macroexpand + project every `(T::KEYWORD :k v …)` form in `forms`
    /// into a typed `T` — the from-forms posture of the typed bare-kwargs
    /// dispatcher family, sibling of [`Self::expand_to_named`].
    ///
    /// Composes [`Self::expand_and_collect_calls_to`] with `T::KEYWORD`
    /// as the keyword filter and `T::compile_from_args` as the per-form
    /// projection — the two-arg `(keyword, projection)` discipline bound
    /// at the type level through `T` inside ONE method body.
    ///
    /// Sibling of [`Self::expand_source_to_typed`] — that method stacks
    /// a `crate::reader::read` step on top of this one, projecting source
    /// text through the SAME typed-pair primitive. Consumers that have
    /// already parsed their forms (macro-expanded subforms, `Sexp`
    /// loaded from disk, a REPL's already-read top-level buffer) bind
    /// to this method; consumers that consume source text directly bind
    /// to the from-source sibling.
    ///
    /// Theory anchor: THEORY.md §VI.1 — generation over composition;
    /// the typed-pair `(T::KEYWORD, T::compile_from_args)` is bound in
    /// ONE place per form shape (this method) — the from-source sibling
    /// inherits the binding through delegation rather than re-deriving
    /// it at its own call site. THEORY.md §II.1 invariant 1 — typed
    /// entry; the typed-keyword filter paired with `T::compile_from_args`
    /// IS the from-forms typed-entry-batch gate, named on the `Expander`
    /// surface. THEORY.md §II.1 invariant 2 — free middle; the from-forms
    /// posture and the from-source posture route through the SAME typed
    /// primitive, so a regression that drifts ONE posture's pairing
    /// from the other becomes structurally impossible.
    ///
    /// Frontier inspiration: MLIR's `Region::walk<Op>(callback)` —
    /// every typed rewriter binds to a region walker that composes the
    /// typed kind filter with the per-op visitor; the substrate's
    /// `expand_to_typed::<T>` is the typed-pair peer on the `&[Sexp]`
    /// algebra, with `T: TataraDomain` standing in for MLIR's `Op` type
    /// witness.
    pub fn expand_to_typed<T: TataraDomain>(&mut self, forms: Vec<Sexp>) -> Result<Vec<T>> {
        self.expand_and_collect_calls_to(forms, T::KEYWORD, T::compile_from_args)
    }

    /// Macroexpand + project every `(T::KEYWORD NAME :k v …)` form in
    /// `forms` into a typed [`NamedDefinition<T>`] — the from-forms posture
    /// of the named NAME-then-kwargs dispatcher family, sibling of
    /// [`Self::expand_to_typed`].
    ///
    /// Routes through the named constant-keyword primitive
    /// [`Self::expand_and_collect_named_calls_to`] (which itself routes
    /// through the named typed-decoded classifier primitive
    /// [`Self::expand_and_collect_named_calls_to_any`] via a constant-
    /// classifier decoder) with `T::KEYWORD` as the keyword filter and
    /// a per-form `(name, spec_args) -> Result<NamedDefinition<T>>`
    /// projection that composes `T::compile_from_args` with the
    /// `NamedDefinition { name: name.to_string(), spec }` packaging.
    /// Post-lift the typed (this method, `T::KEYWORD`-baked) and
    /// untyped (the runtime-keyword sibling
    /// [`Self::expand_and_collect_named_calls_to`]) constant-keyword
    /// named cells route through the SAME composition point on the
    /// `Expander` surface, mirroring how `expand_and_collect_calls_to`
    /// (bare × constant-keyword × untyped) routes through
    /// `expand_and_collect_calls_to_any` (bare × classifier) — the
    /// `split_name_slot` composition lives at ONE site
    /// (`expand_and_collect_named_calls_to_any` body) for the entire
    /// named cell, with `crate::compile::named_form_projection`
    /// remaining a slice-side primitive for callers that have a
    /// single rest tail.
    ///
    /// The named-form structural rejection chain (`NamedFormMissingName`
    /// for the missing NAME slot, `NamedFormNonSymbolName` for the
    /// non-symbol NAME slot, `T::compile_from_args`'s typed-entry kwargs
    /// gate) fires identically across all consumers of the named
    /// dispatcher family — fresh / preloaded × from-forms / from-source
    /// × constant / classifier — because every consumer routes through
    /// the SAME `expand_and_collect_named_calls_to_any` composition that
    /// composes `split_name_slot` with the per-form projection.
    ///
    /// Sibling of [`Self::expand_to_typed`] — both methods route
    /// through their constant-keyword Expander primitive sibling
    /// ([`Self::expand_and_collect_calls_to`] for the bare-kwargs row,
    /// [`Self::expand_and_collect_named_calls_to`] for the named row),
    /// each binding the per-form projection that fits its typed entry
    /// shape. Together with their from-source siblings they close the
    /// typed-from-`Expander` family.
    ///
    /// Theory anchor: see [`Self::expand_to_typed`] — the named sibling
    /// shares the same lift posture, threading the NAME-then-kwargs
    /// projection through `T` AND routing through the named
    /// constant-keyword primitive (rather than the bare-kwargs one
    /// with `named_form_projection::<T>` doing the NAME extraction
    /// inside the projection). THEORY.md §VI.1 — generation over
    /// composition; the named-form `split_name_slot` composition lives
    /// at ONE site post-lift rather than at TWO sites (the bare-kwargs
    /// path through `named_form_projection<T>` AND the classifier path
    /// through the `_any` primitive).
    pub fn expand_to_named<T: TataraDomain>(
        &mut self,
        forms: Vec<Sexp>,
    ) -> Result<Vec<NamedDefinition<T>>> {
        self.expand_and_collect_named_calls_to(forms, T::KEYWORD, |name, spec_args| {
            let spec = T::compile_from_args(spec_args)?;
            Ok(NamedDefinition {
                name: name.to_string(),
                spec,
            })
        })
    }

    /// Read + macroexpand + project every `(T::KEYWORD :k v …)` form in
    /// `src` into a typed `T` — the from-source posture of the typed
    /// bare-kwargs dispatcher family, sibling of
    /// [`Self::expand_source_to_named`].
    ///
    /// Composes [`crate::reader::read`] with [`Self::expand_to_typed`] —
    /// the typed-pair `(T::KEYWORD, T::compile_from_args)` is bound in
    /// ONE place (the from-forms row), and this from-source sibling
    /// inherits the binding through delegation. The expander posture
    /// (fresh [`Expander::new()`](crate::macro_expand::Expander::new)
    /// for one-shot typed compilation, preloaded
    /// [`self.preloaded.clone()`](crate::compiler_spec::RealizedCompiler)
    /// for compilation inside a CompilerSpec's macro library) is the
    /// caller's choice — this method binds the read step and dispatches
    /// on whichever `Expander` value the caller materialized.
    ///
    /// `?`-routing through `read` preserves the structural ordering of
    /// the rejection chain end-to-end: a reader error (lexer / parser /
    /// unbalanced-paren / unterminated-string) short-circuits BEFORE
    /// `expand_to_typed` runs; the from-forms posture's pipeline
    /// (`expand_program → iter_calls_to → map → collect`) fires
    /// afterwards exactly as it does for direct from-forms callers.
    pub fn expand_source_to_typed<T: TataraDomain>(&mut self, src: &str) -> Result<Vec<T>> {
        let forms = crate::reader::read(src)?;
        self.expand_to_typed::<T>(forms)
    }

    /// Read + macroexpand + project every `(T::KEYWORD NAME :k v …)` form
    /// in `src` into a typed [`NamedDefinition<T>`] — the from-source
    /// posture of the named NAME-then-kwargs dispatcher family, sibling
    /// of [`Self::expand_source_to_typed`].
    ///
    /// Composes [`crate::reader::read`] with [`Self::expand_to_named`] —
    /// the typed-pair `(T::KEYWORD, named_form_projection::<T>)` is bound
    /// in ONE place (the from-forms row), and this from-source sibling
    /// inherits the binding through delegation. Together with the three
    /// other cells of the family ([`Self::expand_to_typed`],
    /// [`Self::expand_to_named`], [`Self::expand_source_to_typed`]) it
    /// closes the typed-from-`Expander` surface across both input
    /// postures and both form shapes.
    pub fn expand_source_to_named<T: TataraDomain>(
        &mut self,
        src: &str,
    ) -> Result<Vec<NamedDefinition<T>>> {
        let forms = crate::reader::read(src)?;
        self.expand_to_named::<T>(forms)
    }
}

/// A typed definition with a positional name — e.g., `(defpoint NAME …)` →
/// `NamedDefinition<ProcessSpec> { name, spec }`.
#[derive(Debug, Clone)]
pub struct NamedDefinition<T> {
    pub name: String,
    pub spec: T,
}

/// Back-compat alias — the old `Definition` type was `NamedDefinition<ProcessSpec>`.
pub type Definition<T> = NamedDefinition<T>;

/// Compile every `(T::KEYWORD :k v …)` form in an **already-macroexpanded**
/// slice into `T` — the third input posture of the typed bare-kwargs family,
/// below from-source ([`compile_typed`]) and from-forms
/// ([`Expander::expand_to_typed`]).
///
/// The posture the family was missing, and the absence had teeth. Every
/// other cell either reads (`&str` → lex + parse) or expands (`Vec<Sexp>` →
/// a fresh [`Expander`] + a full `expand_program` walk), so a consumer that
/// wants **N typed domains out of ONE document** had no cell to bind to: its
/// only option was to call a reading or expanding entry point once per
/// domain, re-lexing and re-expanding the whole document N times and
/// discarding all but one keyword's worth of the result each pass. frost's
/// rc loader did exactly that — 24 `compile_typed` calls over the same
/// 1358-form source, 32,592 form expansions to keep 1358, each pass paying a
/// cold [`Expander`] macro cache. That is not a frost defect; it is this
/// table's empty cell, and it is closed here.
///
/// Takes `&[Sexp]` rather than `Vec<Sexp>` precisely because the multi-domain
/// caller is the point: the expanded document is read once and **borrowed**
/// by every projection, so N domains cost N cheap keyword filters over one
/// slice instead of N clones (or N re-expansions) of the document.
///
/// **Contract — `forms` must already be macroexpanded.** This function does
/// no expansion, by design: a `(defmacro …)`-generated `(T::KEYWORD …)` form
/// is invisible to it unless the caller ran [`Expander::expand_program`]
/// first. Callers that hold raw reader output want
/// [`Expander::expand_to_typed`]; callers that hold source text want
/// [`compile_typed`], which is now a composition of read + expand + THIS
/// primitive rather than an inline re-derivation of the filter.
/// [`Expander::expand_to_typed`] reaches the same projection through the
/// untyped constant-keyword layer (`expand_and_collect_calls_to` →
/// `expand_and_collect_calls_to_any` → `expand_program` +
/// [`crate::ast::iter_calls_to_any`]), so all three postures bottom out on
/// the same slice-side filter even though the from-forms cell keeps its
/// route through the untyped primitive.
///
/// Rejection is fail-fast and positional: the first form whose args
/// `T::compile_from_args` rejects short-circuits the whole call with that
/// form's typed error, identical to every other cell in the family.
/// Non-matching forms — a different keyword, an atom, a list whose head is
/// not a symbol — are skipped silently, matching the soft-projection posture
/// of [`crate::ast::iter_calls_to`] this composes.
///
/// Theory anchor: THEORY.md §II.1 invariant 2 — free middle. The middle of
/// the pipeline (read → expand → project) is now decomposed at every joint,
/// so a consumer binds at the joint its input actually sits on rather than
/// re-entering from the top and paying the prefix again.
pub fn compile_typed_from_expanded<T: TataraDomain>(forms: &[Sexp]) -> Result<Vec<T>> {
    crate::ast::iter_calls_to(forms, T::KEYWORD)
        .map(T::compile_from_args)
        .collect()
}

/// Read + macroexpand + compile every `(T::KEYWORD :k v …)` form into `T`.
///
/// The from-source cell of the typed bare-kwargs family: composes
/// [`crate::reader::read`] and a fresh [`Expander`]'s `expand_program` with
/// [`compile_typed_from_expanded`], which owns the typed projection.
pub fn compile_typed<T: TataraDomain>(src: &str) -> Result<Vec<T>> {
    let forms = read(src)?;
    let mut exp = Expander::new();
    let expanded = exp.expand_program(forms)?;
    compile_typed_from_expanded::<T>(&expanded)
}

/// Read + macroexpand + compile every `(T::KEYWORD NAME :k v …)` form into
/// `NamedDefinition<T>`. The positional `NAME` is captured separately from
/// the `:kw v` arguments that feed `compile_from_args`.
pub fn compile_named<T: TataraDomain>(src: &str) -> Result<Vec<NamedDefinition<T>>> {
    compile_named_from_forms::<T>(read(src)?)
}

/// Same as `compile_named` but operates on already-parsed forms. Useful when
/// the caller has done its own reading (e.g., from a string, a Sexp loaded
/// from disk, a macro-expanded subform).
pub fn compile_named_from_forms<T: TataraDomain>(
    forms: Vec<Sexp>,
) -> Result<Vec<NamedDefinition<T>>> {
    let mut exp = Expander::new();
    let expanded = exp.expand_program(forms)?;
    let mut out = Vec::new();
    for form in &expanded {
        let Some(list) = form.as_list() else { continue };
        if list.first().and_then(|s| s.as_symbol()) != Some(T::KEYWORD) {
            continue;
        }
        if list.len() < 2 {
            return Err(LispError::Compile {
                form: T::KEYWORD.to_string(),
                message: format!("expected ({} NAME …)", T::KEYWORD),
            });
        }
        let name = list[1]
            .as_symbol_or_string()
            .ok_or_else(|| LispError::Compile {
                form: T::KEYWORD.to_string(),
                message: "positional NAME must be a symbol or string".into(),
            })?
            .to_string();
        let spec = T::compile_from_args(&list[2..])?;
        out.push(NamedDefinition { name, spec });
    }
    Ok(out)
}

/// Split a `(<keyword> NAME …)` form's argument tail into the NAME slot
/// projection and the remaining argument tail — the named-form arity +
/// NAME-shape gate lifted out of `named_form_projection`'s inline body
/// into ONE public primitive on the substrate's `&[Sexp]` algebra,
/// independent of any `T: TataraDomain` typed-entry follow-up.
///
/// Composes the two-step structural rejection chain — `rest.split_first()`
/// arity gate → `as_symbol_or_string()` NAME-shape gate — yielding the
/// borrowed `(&'a str, &'a [Sexp])` pair on success: the NAME slot's
/// canonical symbol-or-string projection (sourced from
/// [`Sexp::as_symbol_or_string`], which accepts BOTH `(defcompiler
/// my-compiler …)` symbol-author and `(defcompiler "quoted-compiler"
/// …)` string-author surfaces) alongside the spec args tail (`&rest[1..]`,
/// the empty slice for a singleton like `(defcompiler my-compiler)`).
/// Both projections borrow from `rest` verbatim — no copy, no
/// allocation, same lifetime as [`Sexp::as_symbol_or_string`]'s tail —
/// so a consumer that wants to use the NAME slot as a lookup key (a
/// REPL completion that resolves a partial NAME against a registry, an
/// LSP that surfaces a tooltip for the NAME at hover, a
/// `tatara-check` diagnostic that quotes the NAME in its rendered
/// message) reaches the borrowed projection directly. Consumers that
/// need owned ownership (`NamedDefinition.name: String`,
/// JSON-serialized payloads, channel-bounded message bodies)
/// `.to_string()` themselves — pushing the clone to the consumer
/// boundary means the substrate primitive does NOT force a clone the
/// consumer doesn't need.
///
/// Before this lift the same two-step gate was welded INSIDE
/// `named_form_projection`'s body, immediately followed by the typed-
/// entry `T::compile_from_args` call. The pre-lift body had ONE
/// consumer (every named-form dispatcher in the matrix routed through
/// `named_form_projection::<T>` directly, which welded the gate with
/// the typed-domain compose). After this lift the gate is composable:
/// `named_form_projection` is now a 2-line composition of this
/// primitive with `T::compile_from_args`, and ANY consumer that wants
/// the named-form NAME extraction WITHOUT the typed-domain compose
/// binds to ONE primitive rather than re-deriving the
/// `split_first()` arity gate + `as_symbol_or_string()` shape gate +
/// `LispError::NamedFormMissingName` / `LispError::NamedFormNonSymbolName`
/// emission triple inline at its own call site.
///
/// `keyword: &'static str` is the canonical operator-position label
/// the named-form structural rejection variants
/// ([`LispError::NamedFormMissingName.keyword`],
/// [`LispError::NamedFormNonSymbolName.keyword`]) carry as `&'static
/// str` slots. Threading the `&'static` constraint through this
/// helper's parameter pins the same compile-time guarantee at the
/// boundary — a typo in the keyword can never drift into the
/// diagnostic at runtime, same posture as `MissingHeadSymbol.keyword`,
/// `HeadMismatch.keyword`, `TypeMismatch.expected`, and the
/// `Defmacro*.head` family. The pre-lift call sites bound the keyword
/// via `T::KEYWORD` (the typed-domain witness's canonical label); the
/// post-lift signature admits ANY `&'static str`, so a classifier
/// consumer that decodes the head to a typed kind whose label is
/// `&'static` (e.g. a `ClosedSet` implementor's `T::label()` or a
/// hand-rolled `&'static str` lookup) binds to ONE primitive without
/// requiring a `T: TataraDomain` witness.
///
/// Sibling of [`crate::ast::iter_calls_to`] /
/// [`crate::ast::iter_calls_to_any`] on the slice-side `&[Sexp]`
/// algebra — those primitives filter forms by keyword / classifier,
/// this primitive splits an already-filtered form's argument tail
/// into NAME + spec args. Together with [`Sexp::as_call`] /
/// [`Sexp::as_call_to`] / [`Sexp::as_call_to_any`] on the per-form
/// algebra, the substrate's named-form authoring surface decomposes
/// into ONE chain of named primitives the consumer composes per
/// call-site posture, instead of a four-step inline pipeline.
///
/// The future change that benefits: a `compile_named_any` family —
/// the (named NAME-then-kwargs × typed-decoded classifier) cell the
/// substrate's typed-dispatcher matrix leaves open today. A
/// classifier-NAME consumer composes
/// `expand_and_collect_calls_to_any(forms, decode_kind, |kind, args|
/// { let (name, spec_args) = split_name_slot(args, kind.label())?;
/// project(kind, name, spec_args) })` — the named-form gate is
/// COMPOSED in, not re-derived inline. A future named-classifier
/// primitive on `Expander` (a hypothetical
/// `expand_and_collect_named_calls_to_any`) would land as 3 lines on
/// top of `expand_and_collect_calls_to_any` + this primitive, without
/// re-deriving the gate.
///
/// Theory anchor: THEORY.md §VI.1 — generation over composition; the
/// named-form arity + NAME-shape gate is a NAMED primitive on the
/// `&[Sexp]` algebra, NOT a re-derived inline pipeline at every
/// named-form consumer site. The typed-domain compose (the
/// `T::compile_from_args` step inside `named_form_projection`)
/// follows AS A COMPOSITION of THIS primitive + the typed-entry gate,
/// not as a re-derivation of either. THEORY.md §II.1 invariant 2 —
/// free middle; both the typed-domain consumer
/// (`named_form_projection<T>`) AND any future classifier-NAME
/// consumer route through ONE gate body, so a regression in the gate
/// (a future debug-mode logger, span-aware borrow walker,
/// instrumentation that records every NAME-slot rejection for
/// telemetry) lands at ONE site the entire named-form authoring
/// surface inherits. THEORY.md §V.1 — knowable platform; the
/// named-form gate becomes a discoverable primitive on the
/// substrate's `&[Sexp]` algebra rather than an implementation
/// detail buried inside the typed-domain composition.
///
/// Frontier inspiration: Tree-sitter's `query` matched-set + capture
/// binding — a typed pattern exposes named CAPTURES that the
/// consumer references by binding; the NAME slot of a
/// `(<keyword> NAME …)` form is the substrate's typed peer of the
/// capture, exposed as a borrowed `&str` slot the caller composes
/// into its typed projection. Racket's `syntax-parse`
/// `(~datum keyword) name:id arg ...` matches the NAME slot through
/// the `name:id` capture binder and the consumer references it
/// downstream; `split_name_slot` is the unstructured-Rust peer with
/// the typed structural rejection chain (`NamedFormMissingName`,
/// `NamedFormNonSymbolName`) preserved across the boundary.
pub fn split_name_slot<'a>(
    rest: &'a [Sexp],
    keyword: &'static str,
) -> Result<(&'a str, &'a [Sexp])> {
    let (name_form, spec_args) = rest
        .split_first()
        .ok_or(LispError::NamedFormMissingName { keyword })?;
    let name =
        name_form
            .as_symbol_or_string()
            .ok_or_else(|| LispError::NamedFormNonSymbolName {
                keyword,
                got: name_form.shape(),
            })?;
    Ok((name, spec_args))
}

#[cfg(test)]
mod compile_typed_from_expanded_tests {
    use super::*;
    use crate::reader::read;
    use serde::Serialize;
    use tatara_lisp_derive::TataraDomain as DeriveTataraDomain;

    #[derive(DeriveTataraDomain, Serialize, Debug, PartialEq)]
    #[tatara(keyword = "defamostra-alfa")]
    struct AlfaSpec {
        name: String,
        value: String,
    }

    #[derive(DeriveTataraDomain, Serialize, Debug, PartialEq)]
    #[tatara(keyword = "defamostra-beta")]
    struct BetaSpec {
        name: String,
        value: String,
    }

    const MIXED: &str = r#"
        (defamostra-alfa :name "ll" :value "ls -la")
        (defamostra-beta :name "EDITOR" :value "nvim")
        (defamostra-alfa :name "gs" :value "git status")
        42
        (not-a-known-form :name "x")
    "#;

    fn expand(src: &str) -> Vec<Sexp> {
        let mut exp = Expander::new();
        exp.expand_program(read(src).unwrap()).unwrap()
    }

    /// The projection itself: only `T::KEYWORD` forms, in source order,
    /// with every other shape (a different keyword, a bare atom, an
    /// unknown head) skipped rather than erroring.
    #[test]
    fn projects_only_the_matching_keyword_in_source_order() {
        let expanded = expand(MIXED);
        let aliases: Vec<AlfaSpec> = compile_typed_from_expanded(&expanded).unwrap();
        assert_eq!(
            aliases,
            vec![
                AlfaSpec {
                    name: "ll".into(),
                    value: "ls -la".into()
                },
                AlfaSpec {
                    name: "gs".into(),
                    value: "git status".into()
                },
            ]
        );
        let envs: Vec<BetaSpec> = compile_typed_from_expanded(&expanded).unwrap();
        assert_eq!(
            envs,
            vec![BetaSpec {
                name: "EDITOR".into(),
                value: "nvim".into()
            }]
        );
    }

    /// The equivalence receipt that makes the new posture a safe
    /// substitution for a caller migrating off `compile_typed`: for a
    /// document already run through `read` + `expand_program`, both
    /// entry points yield the identical `Vec<T>`. If this ever diverges,
    /// every consumer that switched postures silently applies a
    /// different set of forms.
    #[test]
    fn agrees_with_compile_typed_on_the_same_document() {
        let expanded = expand(MIXED);

        let from_expanded: Vec<AlfaSpec> = compile_typed_from_expanded(&expanded).unwrap();
        let from_source: Vec<AlfaSpec> = compile_typed(MIXED).unwrap();
        assert_eq!(from_expanded, from_source);

        let from_expanded: Vec<BetaSpec> = compile_typed_from_expanded(&expanded).unwrap();
        let from_source: Vec<BetaSpec> = compile_typed(MIXED).unwrap();
        assert_eq!(from_expanded, from_source);
    }

    /// The documented contract, proved rather than asserted in prose:
    /// this posture does NOT expand. A macro-generated form is invisible
    /// to it when handed raw reader output, and visible once the caller
    /// has run `expand_program` — which is exactly the discipline a
    /// migrating consumer has to keep.
    #[test]
    fn does_not_expand_macros_itself_but_sees_them_once_expanded() {
        let src = r#"
            (defmacro alias-pair (a b)
              `(defamostra-alfa :name ,a :value ,b))
            (alias-pair "ll" "ls -la")
        "#;

        let raw = read(src).unwrap();
        let unexpanded: Vec<AlfaSpec> = compile_typed_from_expanded(&raw).unwrap();
        assert!(
            unexpanded.is_empty(),
            "the from-expanded posture must not macroexpand; got {unexpanded:?}"
        );

        let expanded = expand(src);
        let after: Vec<AlfaSpec> = compile_typed_from_expanded(&expanded).unwrap();
        assert_eq!(
            after,
            vec![AlfaSpec {
                name: "ll".into(),
                value: "ls -la".into()
            }],
            "an expanded macro call must project like a hand-written form"
        );
    }

    /// Rejection is fail-fast: a malformed matching form short-circuits
    /// with its own typed error rather than being skipped.
    #[test]
    fn a_malformed_matching_form_is_rejected_not_skipped() {
        let expanded = expand(r#"(defamostra-alfa :name "ll" :nonsense "boom")"#);
        let err = compile_typed_from_expanded::<AlfaSpec>(&expanded).unwrap_err();
        assert!(
            format!("{err}").contains("nonsense"),
            "the diagnostic must name the offending kwarg, got: {err}"
        );
    }
}