sui-spec 0.1.13

Declarative Lisp-authored specs for CppNix-parity behaviors. Rust types are the hard boundary; Lisp forms are the free-middle authoring surface. Both engines (tree-walker + VM) drive the same spec, so they cannot drift.
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
//! L1 AstGraph — the parsed, canonicalized, content-addressed form of
//! a single Nix expression (one `.nix` file or one inline expression).
//!
//! Mirrors `lockfile_graph` to a tee:
//!
//! 1. Parse via rnix exactly once.
//! 2. Walk the rnix typed AST and emit a dense `Vec<AstNode>` keyed by
//!    [`NodeId`] (u32). Every reference between nodes is a `NodeId`,
//!    so the archive is pointer-free.
//! 3. rkyv-archive the graph and BLAKE3 the bytes → cache key for
//!    [`sui_graph_store::GraphKind::Ast`].
//! 4. Cold cost: rnix parse + walk. Warm cost: mmap + cast. The latter
//!    is the budget every eval-cache lookup pays after the first
//!    invocation pays the former.
//!
//! ## Coverage
//!
//! The typed AST covers the 80% of Nix language constructs the rio fleet
//! and nixpkgs hit on the critical path. Constructs we don't model yet
//! land in [`AstNodeKind::Unknown`] with the source text preserved
//! verbatim — forward-compat, never panics. As we add more variants,
//! older blobs keep round-tripping because rkyv appends new variants
//! by tag.
//!
//! Modeled today:
//!
//! * Literals — `Int`, `Float`, `Bool`, `Null`, `Str`, `IndentedStr`,
//!   `Path`
//! * References — `Ident`, `Select` (attrset.a.b with optional fallback)
//! * Containers — `List`, `AttrSet` (`rec` or not), `Inherit` clauses
//! * Bindings — `LetIn`, `With`, `Assert`
//! * Functions — `Lambda` (formal-args destructuring), `Apply`
//! * Control — `IfThenElse`
//! * Operators — `BinOp`, `UnaryOp`, `HasAttr`
//! * Forward-compat — `Unknown { kind, source_text }`
//!
//! ## Determinism
//!
//! Node ids are assigned in **post-order** traversal of the rnix AST:
//! the recursive builder emits each child node before it emits its
//! parent, so the root expression is the **last** node and `root_id`
//! is `(nodes.len() - 1) as u32`. (Unlike `lockfile_graph` whose root
//! is always 0 because the graph is built via BFS from a known root
//! name — for ASTs there's no nameable root, just whatever the source
//! parses to.) Source text in `Unknown` is taken verbatim from the
//! rnix CST so re-parsing it round-trips. The same input source →
//! same node count → same archive bytes → same BLAKE3, end-to-end.
//!
//! ## Behavior contract
//!
//! This module **adds** a typed archive form of Nix expressions. It
//! does not replace the existing rnix → sui-bytecode compilation path
//! (`sui-bytecode/src/compiler.rs`), which remains the only producer of
//! bytecode chunks. The AstGraph is consumed by the L1 substrate (eval
//! cache key derivation, module-graph compiler input, daemon hot
//! cache) — not by the VM directly.

use rkyv::{Archive, Deserialize as RkyvDeserialize, Serialize as RkyvSerialize};
use rnix::ast::{self, AstToken, HasEntry};
use rowan::ast::AstNode;
use serde::{Deserialize, Serialize};
use tatara_lisp::DeriveTataraDomain;

use crate::SpecError;

/// Dense node identifier within an [`AstGraph`].
pub type NodeId = u32;

/// 32-byte BLAKE3 content hash; same shape as
/// `lockfile_graph::CanonicalGraphHash`. Kept duplicated rather than
/// pulled in to keep the module's dependency surface tight.
#[derive(
    DeriveTataraDomain,
    Serialize,
    Deserialize,
    Archive,
    RkyvSerialize,
    RkyvDeserialize,
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Hash,
)]
#[tatara(keyword = "defast-graph-hash")]
#[rkyv(derive(Debug))]
pub struct AstGraphHash {
    pub bytes: [u8; 32],
}

/// Which surface dialect a parsed [`AstGraph`] came from. The IR
/// itself is dialect-agnostic — this discriminator anchors the
/// bidirectional render pipeline + lets transformation passes preserve
/// (or change) the source dialect.
///
/// Sui's stance: both dialects produce the **same** typed IR. The
/// downstream pipeline (eval cache, derivation builder, module-graph
/// compiler, daemon hot cache) never branches on dialect. Only the
/// surface (parse + render) cares.
#[derive(
    Serialize,
    Deserialize,
    Archive,
    RkyvSerialize,
    RkyvDeserialize,
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Hash,
)]
#[rkyv(derive(Debug))]
pub enum SourceDialect {
    /// `.nix` source via the rnix parser. Production today.
    Nix,
    /// `.tlisp` source via the tatara-lisp parser. Queued — the
    /// parser + lowering exist as a typed seam (see
    /// [`AstGraph::from_tlisp_source`]) but the full lowering of every
    /// `AstNodeKind` variant is a focused follow-up ship.
    Tlisp,
    /// A graph stitched together from BOTH dialects (e.g. a `.nix`
    /// flake importing a `.tlisp` module, or a `.tlisp` overlay
    /// transforming a `.nix` config). Rendering this requires keeping
    /// per-node provenance — `AstNodeForm` gains an optional
    /// `dialect_origin` field in a later ship.
    Mixed,
}

/// The AST graph proper. `nodes[0]` is always the root expression.
#[derive(
    DeriveTataraDomain,
    Serialize,
    Deserialize,
    Archive,
    RkyvSerialize,
    RkyvDeserialize,
    Debug,
    Clone,
    PartialEq,
)]
#[tatara(keyword = "defast-graph")]
#[rkyv(derive(Debug))]
pub struct AstGraph {
    /// Which surface dialect this graph was lowered from. Today only
    /// `Nix` is implemented; `Tlisp` is reserved so the typed IR is
    /// stable across the future dialect-lowering work. **The IR
    /// downstream of this field is dialect-agnostic** — every
    /// consumer (eval cache, module-graph compiler, derivation
    /// builder) reads `AstGraph` without knowing which dialect
    /// produced it. Bidirectional rendering (back to `.nix` /
    /// `.tlisp` source text) hangs off this discriminator.
    pub dialect: SourceDialect,
    /// rnix grammar version the source was parsed against. Today this
    /// is locked to the bundled rnix major (0.14). Bumping is a
    /// migration boundary.
    pub grammar_version: u32,
    /// Index of the root expression in [`Self::nodes`]. Today, this is
    /// always `(nodes.len() - 1) as u32` because the builder is
    /// post-order — children are pushed before their parent.
    pub root_id: NodeId,
    /// Dense node table.
    pub nodes: Vec<AstNodeForm>,
    /// BLAKE3 of the rkyv archive bytes. Populated by
    /// [`AstGraph::archive_and_hash`].
    pub canonical_hash: AstGraphHash,
}

/// One AST node in the graph.
#[derive(
    DeriveTataraDomain,
    Serialize,
    Deserialize,
    Archive,
    RkyvSerialize,
    RkyvDeserialize,
    Debug,
    Clone,
    PartialEq,
)]
#[tatara(keyword = "defast-node")]
#[rkyv(derive(Debug))]
pub struct AstNodeForm {
    pub id: NodeId,
    pub kind: AstNodeKind,
}

/// Discriminator for every node variant. Stable IDs by name; append
/// new variants at the bottom of the enum, never reorder (rkyv
/// archive compatibility).
#[derive(
    Serialize,
    Deserialize,
    Archive,
    RkyvSerialize,
    RkyvDeserialize,
    Debug,
    Clone,
    PartialEq,
)]
#[rkyv(derive(Debug))]
pub enum AstNodeKind {
    // ── Literals ──────────────────────────────────────────────────
    Int(i64),
    Float(f64),
    Bool(bool),
    Null,
    /// Quoted string (possibly with interpolation, modeled as a
    /// concatenation of segments).
    Str { segments: Vec<StrSegment> },
    /// `''…''` indented string.
    IndentedStr { segments: Vec<StrSegment> },
    Path(String),

    // ── References ────────────────────────────────────────────────
    Ident(String),
    /// `expr.attr.path` (with optional `or fallback`).
    Select {
        target: NodeId,
        path: Vec<String>,
        fallback: Option<NodeId>,
    },
    /// `expr ? attr.path` — attribute-presence test.
    HasAttr { target: NodeId, path: Vec<String> },

    // ── Containers ────────────────────────────────────────────────
    List(Vec<NodeId>),
    AttrSet {
        recursive: bool,
        entries: Vec<AttrEntry>,
        inherits: Vec<InheritClause>,
    },

    // ── Bindings ──────────────────────────────────────────────────
    LetIn {
        bindings: Vec<AttrEntry>,
        inherits: Vec<InheritClause>,
        body: NodeId,
    },
    With {
        env: NodeId,
        body: NodeId,
    },
    Assert {
        condition: NodeId,
        body: NodeId,
    },

    // ── Functions ─────────────────────────────────────────────────
    Lambda {
        param: LambdaParam,
        body: NodeId,
    },
    Apply {
        function: NodeId,
        argument: NodeId,
    },

    // ── Control ───────────────────────────────────────────────────
    IfThenElse {
        condition: NodeId,
        then_branch: NodeId,
        else_branch: NodeId,
    },

    // ── Operators ─────────────────────────────────────────────────
    BinOp {
        op: BinaryOp,
        left: NodeId,
        right: NodeId,
    },
    UnaryOp {
        op: UnaryOp,
        operand: NodeId,
    },

    // ── Forward-compat ────────────────────────────────────────────
    /// Construct we don't model yet. `source_text` is the verbatim
    /// span from the rnix CST so the underlying meaning is recoverable.
    Unknown {
        kind: String,
        source_text: String,
    },
}

/// One entry in an `AttrSet` or `LetIn` bindings list.
#[derive(
    Serialize,
    Deserialize,
    Archive,
    RkyvSerialize,
    RkyvDeserialize,
    Debug,
    Clone,
    PartialEq,
)]
#[rkyv(derive(Debug))]
pub struct AttrEntry {
    /// Dotted attribute path (`a.b.c` → `["a", "b", "c"]`).
    pub path: Vec<String>,
    pub value: NodeId,
}

/// One `inherit` clause: `inherit (source) attr1 attr2;` or
/// `inherit attr1 attr2;` (source = None).
#[derive(
    Serialize,
    Deserialize,
    Archive,
    RkyvSerialize,
    RkyvDeserialize,
    Debug,
    Clone,
    PartialEq,
    Eq,
)]
#[rkyv(derive(Debug))]
pub struct InheritClause {
    pub source: Option<NodeId>,
    pub attrs: Vec<String>,
}

/// Lambda parameter shape: a bare identifier, or formal-args
/// destructuring, or both (`name @ { … }`).
#[derive(
    Serialize,
    Deserialize,
    Archive,
    RkyvSerialize,
    RkyvDeserialize,
    Debug,
    Clone,
    PartialEq,
)]
#[rkyv(derive(Debug))]
pub enum LambdaParam {
    /// `x:`
    Ident(String),
    /// `{ a, b ? default, ... } [@ name]:`
    Pattern {
        binding_name: Option<String>,
        formals: Vec<Formal>,
        accepts_extra: bool,
    },
}

/// One named formal arg in a destructuring lambda.
#[derive(
    Serialize,
    Deserialize,
    Archive,
    RkyvSerialize,
    RkyvDeserialize,
    Debug,
    Clone,
    PartialEq,
    Eq,
)]
#[rkyv(derive(Debug))]
pub struct Formal {
    pub name: String,
    pub default: Option<NodeId>,
}

/// One segment of a possibly-interpolated string.
#[derive(
    Serialize,
    Deserialize,
    Archive,
    RkyvSerialize,
    RkyvDeserialize,
    Debug,
    Clone,
    PartialEq,
)]
#[rkyv(derive(Debug))]
pub enum StrSegment {
    Literal(String),
    /// `${expr}` interpolation.
    Interpolation(NodeId),
}

/// Binary operator. Tags are stable; appending allowed.
#[derive(
    Serialize,
    Deserialize,
    Archive,
    RkyvSerialize,
    RkyvDeserialize,
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Hash,
)]
#[rkyv(derive(Debug))]
pub enum BinaryOp {
    /// `+`
    Add,
    /// `-`
    Sub,
    /// `*`
    Mul,
    /// `/`
    Div,
    /// `==`
    Eq,
    /// `!=`
    NotEq,
    /// `<`
    Lt,
    /// `<=`
    Le,
    /// `>`
    Gt,
    /// `>=`
    Ge,
    /// `&&`
    And,
    /// `||`
    Or,
    /// `->`
    Implies,
    /// `//`
    Update,
    /// `++`
    Concat,
    /// `|>` (Nix 2.18+) — pipe right: `x |> f` ≡ `f x`.
    PipeRight,
    /// `<|` (Nix 2.18+) — pipe left: `f <| x` ≡ `f x`.
    PipeLeft,
}

/// Unary operator.
#[derive(
    Serialize,
    Deserialize,
    Archive,
    RkyvSerialize,
    RkyvDeserialize,
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Hash,
)]
#[rkyv(derive(Debug))]
pub enum UnaryOp {
    /// `-`
    Neg,
    /// `!`
    Not,
}

/// Errors produced when materializing an [`AstGraph`] from source.
#[derive(Debug, thiserror::Error)]
pub enum AstGraphError {
    #[error("rnix parse error(s): {0}")]
    Parse(String),
    #[error("rnix produced no root expression")]
    NoRoot,
    #[error("rkyv archive of canonical AST graph failed: {0}")]
    Archive(String),
    #[error("{what} (not yet implemented; tracked in the dialect-rendering ship)")]
    Unimplemented { what: &'static str },
}

impl AstGraph {
    /// Parse + canonicalize source text into a typed AST graph.
    ///
    /// # Errors
    ///
    /// - [`AstGraphError::Parse`] if rnix can't parse the source.
    /// - [`AstGraphError::NoRoot`] if the parse succeeds but produces
    ///   an empty root (e.g. comments-only input).
    pub fn from_source(source: &str) -> Result<Self, AstGraphError> {
        let parse = rnix::Root::parse(source);
        if !parse.errors().is_empty() {
            let msg = parse
                .errors()
                .iter()
                .map(|e| e.to_string())
                .collect::<Vec<_>>()
                .join("; ");
            return Err(AstGraphError::Parse(msg));
        }
        let root = parse.tree();
        let expr = root.expr().ok_or(AstGraphError::NoRoot)?;

        let mut builder = Builder::default();
        let root_id = builder.lower_expr(&expr);
        // Builder emits children before parents, so the root is the
        // last node and `root_id == nodes.len() - 1`. Assert that here
        // in debug builds; downstream consumers depend on it.
        debug_assert_eq!(root_id as usize + 1, builder.nodes.len());

        Ok(Self {
            dialect: SourceDialect::Nix,
            grammar_version: RNIX_GRAMMAR_VERSION,
            root_id,
            nodes: builder.nodes,
            canonical_hash: AstGraphHash { bytes: [0u8; 32] },
        })
    }

    /// Parse + lower a tatara-lisp source into the universal IR.
    ///
    /// **Status**: typed seam only. Today this returns an `Unknown`-
    /// kinded root with the source preserved verbatim so callers can
    /// already exercise the dialect-aware downstream pipeline. The
    /// real lowering — mapping each `defast-node` Lisp form to the
    /// matching [`AstNodeKind`] variant — lands in the focused
    /// `.tlisp` dialect ship.
    ///
    /// # Errors
    ///
    /// Always succeeds today (every input is captured as `Unknown`).
    /// Future versions will return [`AstGraphError::Parse`] when the
    /// tatara-lisp reader rejects the input.
    pub fn from_tlisp_source(source: &str) -> Result<Self, AstGraphError> {
        let mut nodes = Vec::with_capacity(1);
        nodes.push(AstNodeForm {
            id: 0,
            kind: AstNodeKind::Unknown {
                kind: "tlisp-source-pending-lowering".to_string(),
                source_text: source.to_string(),
            },
        });
        Ok(Self {
            dialect: SourceDialect::Tlisp,
            grammar_version: TLISP_GRAMMAR_VERSION,
            root_id: 0,
            nodes,
            canonical_hash: AstGraphHash { bytes: [0u8; 32] },
        })
    }

    /// Render this graph back into Nix source text.
    ///
    /// **Status**: API seam only. The renderer that emits canonical
    /// `.nix` syntax for every [`AstNodeKind`] variant lands in the
    /// dialect-rendering ship.
    ///
    /// # Errors
    ///
    /// Always returns [`AstGraphError::Unimplemented`] today.
    pub fn to_nix_source(&self) -> Result<String, AstGraphError> {
        Err(AstGraphError::Unimplemented {
            what: "AstGraph::to_nix_source — queued",
        })
    }

    /// Render this graph as tatara-lisp source text.
    ///
    /// **Status**: API seam only. See [`Self::to_nix_source`].
    ///
    /// # Errors
    ///
    /// Always returns [`AstGraphError::Unimplemented`] today.
    pub fn to_tlisp_source(&self) -> Result<String, AstGraphError> {
        Err(AstGraphError::Unimplemented {
            what: "AstGraph::to_tlisp_source — queued",
        })
    }

    /// Same two-pass shape as `LockfileGraph::archive_and_hash` — the
    /// hash is part of the archive, so it can't be computed before the
    /// archive exists.
    ///
    /// # Errors
    ///
    /// [`AstGraphError::Archive`] if rkyv refuses the graph shape.
    pub fn archive_and_hash(mut self) -> Result<(Self, Vec<u8>), AstGraphError> {
        let initial = rkyv::to_bytes::<rkyv::rancor::Error>(&self)
            .map_err(|e| AstGraphError::Archive(e.to_string()))?;
        let hash = blake3::hash(&initial);
        self.canonical_hash = AstGraphHash { bytes: hash.into() };
        let stamped = rkyv::to_bytes::<rkyv::rancor::Error>(&self)
            .map_err(|e| AstGraphError::Archive(e.to_string()))?;
        Ok((self, stamped.to_vec()))
    }
}

/// Bumped when we change the on-disk graph shape in a way that
/// requires re-parsing source. rkyv handles append-only variant
/// changes natively; this version is for cases like "renamed an
/// existing variant" where blobs need to be invalidated.
pub const RNIX_GRAMMAR_VERSION: u32 = 1;

/// Bumped when the tatara-lisp dialect's lowering schema changes in
/// a way that requires re-parsing. Today: 1 (the stub).
pub const TLISP_GRAMMAR_VERSION: u32 = 1;

// ── Builder ──────────────────────────────────────────────────────

#[derive(Default)]
struct Builder {
    nodes: Vec<AstNodeForm>,
}

impl Builder {
    fn push(&mut self, kind: AstNodeKind) -> NodeId {
        let id = self.nodes.len() as NodeId;
        self.nodes.push(AstNodeForm { id, kind });
        id
    }

    fn unknown(&mut self, expr: &ast::Expr, label: &str) -> NodeId {
        let source_text = expr.syntax().to_string();
        self.push(AstNodeKind::Unknown {
            kind: label.to_string(),
            source_text,
        })
    }

    fn lower_expr(&mut self, expr: &ast::Expr) -> NodeId {
        match expr {
            ast::Expr::Literal(lit) => self.lower_literal(lit),
            ast::Expr::Str(s) => self.lower_str(s, /* indented= */ false),
            ast::Expr::Ident(ident) => {
                let text = ident
                    .ident_token()
                    .map(|t| t.text().to_string())
                    .unwrap_or_default();
                self.push(AstNodeKind::Ident(text))
            }
            // rnix splits the path syntax into four variants depending
            // on whether it's absolute, relative, home-relative, or a
            // <name> search path. Carry the verbatim source text in all
            // four cases; downstream consumers parse it themselves if
            // they need the typed form.
            ast::Expr::PathAbs(p) => {
                let text = p.syntax().to_string();
                self.push(AstNodeKind::Path(text))
            }
            ast::Expr::PathRel(p) => {
                let text = p.syntax().to_string();
                self.push(AstNodeKind::Path(text))
            }
            ast::Expr::PathHome(p) => {
                let text = p.syntax().to_string();
                self.push(AstNodeKind::Path(text))
            }
            ast::Expr::PathSearch(p) => {
                let text = p.syntax().to_string();
                self.push(AstNodeKind::Path(text))
            }
            // `__curPos` — built-in source-position marker.
            ast::Expr::CurPos(c) => {
                let text = c.syntax().to_string();
                self.push(AstNodeKind::Unknown {
                    kind: "cur-pos".to_string(),
                    source_text: text,
                })
            }
            // Pre-2.0 `let { body = …; …; }` syntax. Rare, but rio
            // ships a few nixpkgs pins that contain it.
            ast::Expr::LegacyLet(l) => {
                let text = l.syntax().to_string();
                self.push(AstNodeKind::Unknown {
                    kind: "legacy-let".to_string(),
                    source_text: text,
                })
            }
            // rnix's `Root` is the document wrapper; nested Roots are
            // a parse oddity, but if we see one just dive into its
            // body so the AST stays well-formed.
            ast::Expr::Root(r) => match r.expr() {
                Some(inner) => self.lower_expr(&inner),
                None => self.push(AstNodeKind::Null),
            },
            // Recoverable rnix parse error placeholder. We've already
            // rejected non-empty parse-error lists in `from_source`, so
            // this should only fire for inline-error nodes that
            // upstream couldn't surface as a hard error.
            ast::Expr::Error(e) => {
                let text = e.syntax().to_string();
                self.push(AstNodeKind::Unknown {
                    kind: "parse-error".to_string(),
                    source_text: text,
                })
            }
            ast::Expr::List(list) => {
                let items: Vec<NodeId> = list.items().map(|e| self.lower_expr(&e)).collect();
                self.push(AstNodeKind::List(items))
            }
            ast::Expr::AttrSet(set) => self.lower_attrset(set),
            ast::Expr::LetIn(letin) => self.lower_letin(letin),
            ast::Expr::With(with) => {
                let env = with.namespace().map(|e| self.lower_expr(&e));
                let body = with.body().map(|e| self.lower_expr(&e));
                match (env, body) {
                    (Some(env), Some(body)) => self.push(AstNodeKind::With { env, body }),
                    _ => self.unknown(expr, "with-missing-side"),
                }
            }
            ast::Expr::Assert(assert) => {
                let condition = assert.condition().map(|e| self.lower_expr(&e));
                let body = assert.body().map(|e| self.lower_expr(&e));
                match (condition, body) {
                    (Some(condition), Some(body)) => {
                        self.push(AstNodeKind::Assert { condition, body })
                    }
                    _ => self.unknown(expr, "assert-missing-side"),
                }
            }
            ast::Expr::Lambda(lambda) => self.lower_lambda(lambda),
            ast::Expr::Apply(apply) => {
                let function = apply.lambda().map(|e| self.lower_expr(&e));
                let argument = apply.argument().map(|e| self.lower_expr(&e));
                match (function, argument) {
                    (Some(function), Some(argument)) => self.push(AstNodeKind::Apply {
                        function,
                        argument,
                    }),
                    _ => self.unknown(expr, "apply-missing-side"),
                }
            }
            ast::Expr::IfElse(ifelse) => {
                let condition = ifelse.condition().map(|e| self.lower_expr(&e));
                let then_branch = ifelse.body().map(|e| self.lower_expr(&e));
                let else_branch = ifelse.else_body().map(|e| self.lower_expr(&e));
                match (condition, then_branch, else_branch) {
                    (Some(c), Some(t), Some(e)) => self.push(AstNodeKind::IfThenElse {
                        condition: c,
                        then_branch: t,
                        else_branch: e,
                    }),
                    _ => self.unknown(expr, "if-else-missing-branch"),
                }
            }
            ast::Expr::Select(select) => self.lower_select(select),
            ast::Expr::HasAttr(has) => {
                let target = has.expr().map(|e| self.lower_expr(&e));
                let path = has
                    .attrpath()
                    .map(|p| attrpath_to_strings(&p))
                    .unwrap_or_default();
                match target {
                    Some(target) => self.push(AstNodeKind::HasAttr { target, path }),
                    None => self.unknown(expr, "hasattr-missing-target"),
                }
            }
            ast::Expr::BinOp(binop) => self.lower_binop(binop),
            ast::Expr::UnaryOp(unaryop) => self.lower_unaryop(unaryop),
            ast::Expr::Paren(p) => match p.expr() {
                Some(inner) => self.lower_expr(&inner),
                None => self.unknown(expr, "paren-empty"),
            },
            // Every rnix 0.14 Expr variant is handled above. If a future
            // rnix bump adds a variant we don't know about, the compiler
            // catches the gap as a non-exhaustive match — by design, so
            // we can't silently drop a construct into Unknown.
        }
    }

    fn lower_literal(&mut self, lit: &ast::Literal) -> NodeId {
        match lit.kind() {
            ast::LiteralKind::Integer(t) => {
                let n: i64 = t.value().unwrap_or(0);
                self.push(AstNodeKind::Int(n))
            }
            ast::LiteralKind::Float(t) => {
                let f: f64 = t.value().unwrap_or(0.0);
                self.push(AstNodeKind::Float(f))
            }
            ast::LiteralKind::Uri(t) => {
                // Uris are deprecated in modern Nix; treat as Str.
                self.push(AstNodeKind::Str {
                    segments: vec![StrSegment::Literal(t.syntax().text().to_string())],
                })
            }
        }
    }

    fn lower_str(&mut self, s: &ast::Str, _indented: bool) -> NodeId {
        let mut segments = Vec::new();
        for part in s.normalized_parts() {
            match part {
                ast::InterpolPart::Literal(text) => {
                    segments.push(StrSegment::Literal(text));
                }
                ast::InterpolPart::Interpolation(interp) => {
                    let id = match interp.expr() {
                        Some(expr) => self.lower_expr(&expr),
                        None => {
                            // Empty interpolation: treat as empty string literal.
                            segments.push(StrSegment::Literal(String::new()));
                            continue;
                        }
                    };
                    segments.push(StrSegment::Interpolation(id));
                }
            }
        }
        self.push(AstNodeKind::Str { segments })
    }

    fn lower_attrset(&mut self, set: &ast::AttrSet) -> NodeId {
        let recursive = set.rec_token().is_some();
        let mut entries = Vec::new();
        let mut inherits = Vec::new();
        for entry in set.entries() {
            match entry {
                ast::Entry::AttrpathValue(av) => {
                    let path = av
                        .attrpath()
                        .map(|p| attrpath_to_strings(&p))
                        .unwrap_or_default();
                    let value = av
                        .value()
                        .map(|e| self.lower_expr(&e))
                        .unwrap_or_else(|| self.push(AstNodeKind::Null));
                    entries.push(AttrEntry { path, value });
                }
                ast::Entry::Inherit(inherit) => {
                    let source = inherit.from().and_then(|f| f.expr()).map(|e| self.lower_expr(&e));
                    let attrs: Vec<String> = inherit
                        .attrs()
                        .filter_map(|a| attr_to_string(&a))
                        .collect();
                    inherits.push(InheritClause { source, attrs });
                }
            }
        }
        self.push(AstNodeKind::AttrSet {
            recursive,
            entries,
            inherits,
        })
    }

    fn lower_letin(&mut self, letin: &ast::LetIn) -> NodeId {
        let mut bindings = Vec::new();
        let mut inherits = Vec::new();
        for entry in letin.entries() {
            match entry {
                ast::Entry::AttrpathValue(av) => {
                    let path = av
                        .attrpath()
                        .map(|p| attrpath_to_strings(&p))
                        .unwrap_or_default();
                    let value = av
                        .value()
                        .map(|e| self.lower_expr(&e))
                        .unwrap_or_else(|| self.push(AstNodeKind::Null));
                    bindings.push(AttrEntry { path, value });
                }
                ast::Entry::Inherit(inherit) => {
                    let source = inherit.from().and_then(|f| f.expr()).map(|e| self.lower_expr(&e));
                    let attrs: Vec<String> = inherit
                        .attrs()
                        .filter_map(|a| attr_to_string(&a))
                        .collect();
                    inherits.push(InheritClause { source, attrs });
                }
            }
        }
        let body = letin
            .body()
            .map(|e| self.lower_expr(&e))
            .unwrap_or_else(|| self.push(AstNodeKind::Null));
        self.push(AstNodeKind::LetIn {
            bindings,
            inherits,
            body,
        })
    }

    fn lower_lambda(&mut self, lambda: &ast::Lambda) -> NodeId {
        let param = match lambda.param() {
            Some(ast::Param::IdentParam(ip)) => {
                let name = ip
                    .ident()
                    .and_then(|i| i.ident_token().map(|t| t.text().to_string()))
                    .unwrap_or_default();
                LambdaParam::Ident(name)
            }
            Some(ast::Param::Pattern(pattern)) => {
                let binding_name = pattern
                    .pat_bind()
                    .and_then(|b| b.ident())
                    .and_then(|i| i.ident_token().map(|t| t.text().to_string()));
                let accepts_extra = pattern.ellipsis_token().is_some();
                let mut formals: Vec<Formal> = Vec::new();
                for entry in pattern.pat_entries() {
                    let name = entry
                        .ident()
                        .and_then(|i| i.ident_token().map(|t| t.text().to_string()))
                        .unwrap_or_default();
                    let default = entry.default().map(|e| self.lower_expr(&e));
                    formals.push(Formal { name, default });
                }
                LambdaParam::Pattern {
                    binding_name,
                    formals,
                    accepts_extra,
                }
            }
            None => LambdaParam::Ident(String::new()),
        };
        let body = lambda
            .body()
            .map(|e| self.lower_expr(&e))
            .unwrap_or_else(|| self.push(AstNodeKind::Null));
        self.push(AstNodeKind::Lambda { param, body })
    }

    fn lower_select(&mut self, select: &ast::Select) -> NodeId {
        let target = match select.expr() {
            Some(e) => self.lower_expr(&e),
            None => return self.push(AstNodeKind::Null),
        };
        let path = select
            .attrpath()
            .map(|p| attrpath_to_strings(&p))
            .unwrap_or_default();
        let fallback = select.default_expr().map(|e| self.lower_expr(&e));
        self.push(AstNodeKind::Select {
            target,
            path,
            fallback,
        })
    }

    fn lower_binop(&mut self, binop: &ast::BinOp) -> NodeId {
        let left = binop
            .lhs()
            .map(|e| self.lower_expr(&e))
            .unwrap_or_else(|| self.push(AstNodeKind::Null));
        let right = binop
            .rhs()
            .map(|e| self.lower_expr(&e))
            .unwrap_or_else(|| self.push(AstNodeKind::Null));
        let op = binop
            .operator()
            .map(map_binop)
            .unwrap_or(BinaryOp::Concat);
        self.push(AstNodeKind::BinOp { op, left, right })
    }

    fn lower_unaryop(&mut self, unaryop: &ast::UnaryOp) -> NodeId {
        let operand = unaryop
            .expr()
            .map(|e| self.lower_expr(&e))
            .unwrap_or_else(|| self.push(AstNodeKind::Null));
        let op = match unaryop.operator() {
            Some(ast::UnaryOpKind::Negate) => UnaryOp::Neg,
            Some(ast::UnaryOpKind::Invert) => UnaryOp::Not,
            None => UnaryOp::Neg,
        };
        self.push(AstNodeKind::UnaryOp { op, operand })
    }
}

fn map_binop(op: ast::BinOpKind) -> BinaryOp {
    match op {
        ast::BinOpKind::Add => BinaryOp::Add,
        ast::BinOpKind::Sub => BinaryOp::Sub,
        ast::BinOpKind::Mul => BinaryOp::Mul,
        ast::BinOpKind::Div => BinaryOp::Div,
        ast::BinOpKind::Equal => BinaryOp::Eq,
        ast::BinOpKind::NotEqual => BinaryOp::NotEq,
        ast::BinOpKind::Less => BinaryOp::Lt,
        ast::BinOpKind::LessOrEq => BinaryOp::Le,
        ast::BinOpKind::More => BinaryOp::Gt,
        ast::BinOpKind::MoreOrEq => BinaryOp::Ge,
        ast::BinOpKind::And => BinaryOp::And,
        ast::BinOpKind::Or => BinaryOp::Or,
        ast::BinOpKind::Implication => BinaryOp::Implies,
        ast::BinOpKind::Update => BinaryOp::Update,
        ast::BinOpKind::Concat => BinaryOp::Concat,
        ast::BinOpKind::PipeRight => BinaryOp::PipeRight,
        ast::BinOpKind::PipeLeft => BinaryOp::PipeLeft,
    }
}

fn attrpath_to_strings(path: &ast::Attrpath) -> Vec<String> {
    path.attrs().filter_map(|a| attr_to_string(&a)).collect()
}

fn attr_to_string(attr: &ast::Attr) -> Option<String> {
    match attr {
        ast::Attr::Ident(i) => i.ident_token().map(|t| t.text().to_string()),
        ast::Attr::Dynamic(d) => Some(d.syntax().to_string()),
        ast::Attr::Str(s) => Some(s.syntax().to_string()),
    }
}

// ── Lisp fixtures loader ────────────────────────────────────────

#[derive(DeriveTataraDomain, Serialize, Deserialize, Debug, Clone)]
#[tatara(keyword = "defast-graph-fixture")]
pub struct AstGraphFixture {
    pub name: String,
    pub source: String,
    #[serde(rename = "rootKind")]
    pub root_kind: String,
    #[serde(rename = "nodeCount")]
    pub node_count: u32,
    pub notes: String,
}

pub const CANONICAL_AST_GRAPH_FIXTURES_LISP: &str =
    include_str!("../specs/ast_graph.lisp");

/// Load every authored fixture.
///
/// # Errors
///
/// Fails if the `.lisp` source can't be parsed.
pub fn load_fixtures() -> Result<Vec<AstGraphFixture>, SpecError> {
    crate::loader::load_all::<AstGraphFixture>(CANONICAL_AST_GRAPH_FIXTURES_LISP)
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;

    #[test]
    fn integer_literal_produces_one_node() {
        let g = AstGraph::from_source("42").unwrap();
        assert_eq!(g.nodes.len(), 1);
        assert_eq!(g.root_id, 0);
        matches!(g.nodes[0].kind, AstNodeKind::Int(42));
    }

    #[test]
    fn binop_produces_three_nodes() {
        // BinOp + left + right
        let g = AstGraph::from_source("1 + 2").unwrap();
        assert!(g.nodes.len() >= 3);
        assert!(matches!(
            g.nodes[g.root_id as usize].kind,
            AstNodeKind::BinOp { op: BinaryOp::Add, .. }
        ));
    }

    #[test]
    fn let_in_with_binop_resolves_identifiers() {
        let g = AstGraph::from_source("let x = 1; in x + 2").unwrap();
        assert!(matches!(
            g.nodes[g.root_id as usize].kind,
            AstNodeKind::LetIn { .. }
        ));
        // Must have at least: LetIn + binding(x=Int(1)) + BinOp + Ident(x) + Int(2)
        // The walker emits children before the parent so root is the last node.
        assert!(g.nodes.len() >= 5);
    }

    #[test]
    fn nixos_module_lambda_destructures_formals() {
        let g = AstGraph::from_source(
            "{ config, lib, pkgs, ... }: { networking.hostName = \"rio\"; }",
        )
        .unwrap();
        // Root must be a Lambda with a Pattern parameter.
        let root_kind = &g.nodes[g.root_id as usize].kind;
        match root_kind {
            AstNodeKind::Lambda {
                param: LambdaParam::Pattern { formals, accepts_extra, .. },
                ..
            } => {
                assert!(*accepts_extra);
                let names: Vec<&str> = formals.iter().map(|f| f.name.as_str()).collect();
                assert!(names.contains(&"config"));
                assert!(names.contains(&"lib"));
                assert!(names.contains(&"pkgs"));
            }
            other => panic!("expected Lambda Pattern at root, got {other:?}"),
        }
    }

    #[test]
    fn archive_and_hash_stamps_canonical_hash() {
        let g = AstGraph::from_source("let x = 1; in x + 2").unwrap();
        assert_eq!(g.canonical_hash.bytes, [0u8; 32]);
        let (stamped, bytes) = g.archive_and_hash().unwrap();
        assert_ne!(stamped.canonical_hash.bytes, [0u8; 32]);
        assert!(!bytes.is_empty());
    }

    #[test]
    fn archive_roundtrips_via_rkyv() {
        let g = AstGraph::from_source("let x = 1; in x + 2").unwrap();
        let (_stamped, bytes) = g.clone().archive_and_hash().unwrap();
        let archived =
            rkyv::access::<ArchivedAstGraph, rkyv::rancor::Error>(&bytes).unwrap();
        // Post-order: root is the last node, so root_id == nodes.len() - 1.
        assert_eq!(archived.root_id, (g.nodes.len() - 1) as u32);
        assert_eq!(archived.grammar_version, RNIX_GRAMMAR_VERSION);
        assert_eq!(archived.nodes.len(), g.nodes.len());
    }

    #[test]
    fn archive_is_deterministic_for_same_source() {
        let g1 = AstGraph::from_source("let x = 1; in x + 2").unwrap();
        let g2 = AstGraph::from_source("let x = 1; in x + 2").unwrap();
        let (s1, _) = g1.archive_and_hash().unwrap();
        let (s2, _) = g2.archive_and_hash().unwrap();
        assert_eq!(s1.canonical_hash.bytes, s2.canonical_hash.bytes);
    }

    #[test]
    fn fixtures_load_from_lisp() {
        let fixtures = load_fixtures().unwrap();
        let names: Vec<_> = fixtures.iter().map(|f| f.name.as_str()).collect();
        assert!(names.contains(&"literal-int"));
        assert!(names.contains(&"let-in-with-binop"));
        assert!(names.contains(&"nixos-module-skeleton"));
    }

    #[test]
    fn nix_source_marks_dialect_as_nix() {
        let g = AstGraph::from_source("42").unwrap();
        assert!(matches!(g.dialect, SourceDialect::Nix));
        assert_eq!(g.grammar_version, RNIX_GRAMMAR_VERSION);
    }

    #[test]
    fn tlisp_source_stub_marks_dialect_as_tlisp() {
        let g = AstGraph::from_tlisp_source("(+ 1 2)").unwrap();
        assert!(matches!(g.dialect, SourceDialect::Tlisp));
        assert_eq!(g.grammar_version, TLISP_GRAMMAR_VERSION);
        assert_eq!(g.nodes.len(), 1);
        match &g.nodes[0].kind {
            AstNodeKind::Unknown { kind, source_text } => {
                assert!(kind.contains("tlisp"));
                assert_eq!(source_text, "(+ 1 2)");
            }
            other => panic!("expected Unknown stub, got {other:?}"),
        }
    }

    #[test]
    fn render_seams_return_unimplemented_today() {
        let g = AstGraph::from_source("42").unwrap();
        assert!(matches!(
            g.to_nix_source(),
            Err(AstGraphError::Unimplemented { .. })
        ));
        assert!(matches!(
            g.to_tlisp_source(),
            Err(AstGraphError::Unimplemented { .. })
        ));
    }

    #[test]
    fn unmodeled_construct_lands_in_unknown_with_source() {
        // Reasonably exotic: `or` outside of select context. Even when
        // we add it to the modeled set, the test still passes — the
        // node count grows but the structure doesn't.
        let result = AstGraph::from_source("let a = { foo = 1; }; in a.bar or 0");
        let g = result.unwrap();
        assert!(g.nodes.len() >= 2);
    }
}