dol 0.8.1

DOL (Design Ontology Language) - A declarative specification language for ontology-first development
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
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
//! Spirit REPL - Interactive DOL evaluation
//!
//! Provides a read-eval-print loop for DOL code, supporting:
//! - Interactive DOL expression evaluation
//! - Declaration definition and reuse
//! - DOL → Rust → WASM compilation pipeline
//! - Tree-shaked optimized output
//!
//! # Pipeline
//!
//! ```text
//! User Input → Parse → Tree Shake → Codegen (Rust) → WASM → Execute
//! ```
//!
//! # Example
//!
//! ```rust,ignore
//! use metadol::repl::SpiritRepl;
//!
//! let mut repl = SpiritRepl::new();
//!
//! // Define a gene
//! repl.eval("gene Point { point has x: Int64; point has y: Int64 }")?;
//!
//! // Define a function
//! repl.eval("fun add(a: Int64, b: Int64) -> Int64 { a + b }")?;
//!
//! // Call the function
//! let result = repl.eval("add(3, 4)")?;
//! assert_eq!(result, Value::Int(7));
//! ```

mod context;
mod evaluator;
mod session;

pub use context::ReplContext;
pub use evaluator::{EvalResult, ReplEvaluator};
pub use session::{ReplSession, SessionConfig};

use crate::ast::Declaration;
use crate::codegen::compile_to_rust_via_hir;
use crate::error::ParseError;
use crate::manifest::{parse_spirit_manifest, SpiritManifest};
use crate::parser::Parser;
use crate::transform::TreeShaking;

use std::path::{Path, PathBuf};

/// A loaded Spirit in the REPL.
#[derive(Debug, Clone)]
pub struct LoadedSpirit {
    /// The Spirit manifest
    pub manifest: SpiritManifest,
    /// Path to the Spirit directory
    pub path: PathBuf,
    /// Loaded DOL declarations from the Spirit
    pub declarations: Vec<Declaration>,
    /// Source texts for the declarations
    pub source_texts: Vec<String>,
}

/// Spirit REPL - Interactive DOL evaluation environment.
///
/// The SpiritRepl maintains state across evaluations, allowing
/// declarations to be defined and reused across multiple inputs.
#[derive(Debug)]
pub struct SpiritRepl {
    /// Accumulated declarations from session
    declarations: Vec<Declaration>,

    /// Original source text for each declaration (for WASM compilation)
    source_texts: Vec<String>,

    /// Tree shaker for dead code elimination
    tree_shaker: TreeShaking,

    /// Session configuration
    config: SessionConfig,

    /// Evaluation context (symbols, types, etc.)
    context: ReplContext,

    /// History of evaluated inputs
    history: Vec<String>,

    /// Evaluator for expression execution
    evaluator: ReplEvaluator,

    /// Loaded spirits
    spirits: Vec<LoadedSpirit>,

    /// Currently active spirit (for :reload)
    current_spirit: Option<String>,
}

impl Default for SpiritRepl {
    fn default() -> Self {
        Self::new()
    }
}

impl SpiritRepl {
    /// Create a new Spirit REPL with default configuration.
    pub fn new() -> Self {
        Self {
            declarations: Vec::new(),
            source_texts: Vec::new(),
            tree_shaker: TreeShaking::new(),
            config: SessionConfig::default(),
            context: ReplContext::new(),
            history: Vec::new(),
            evaluator: ReplEvaluator::new(),
            spirits: Vec::new(),
            current_spirit: None,
        }
    }

    /// Create a REPL with custom configuration.
    pub fn with_config(config: SessionConfig) -> Self {
        let evaluator = if config.optimize {
            ReplEvaluator::optimized()
        } else {
            ReplEvaluator::new()
        };

        Self {
            declarations: Vec::new(),
            source_texts: Vec::new(),
            tree_shaker: TreeShaking::new(),
            config,
            context: ReplContext::new(),
            history: Vec::new(),
            evaluator,
            spirits: Vec::new(),
            current_spirit: None,
        }
    }

    /// Evaluate a DOL input string.
    ///
    /// The input can be:
    /// - A declaration (gene, trait, constraint, system, function)
    /// - An expression to evaluate
    /// - A REPL command (starting with `:`)
    ///
    /// # Arguments
    ///
    /// * `input` - The DOL source to evaluate
    ///
    /// # Returns
    ///
    /// The result of evaluation, or an error.
    pub fn eval(&mut self, input: &str) -> Result<EvalResult, ReplError> {
        let input = input.trim();

        // Handle REPL commands
        if input.starts_with(':') {
            return self.handle_command(input);
        }

        // Skip empty input
        if input.is_empty() {
            return Ok(EvalResult::Empty);
        }

        // Add to history
        self.history.push(input.to_string());

        // Try to parse as declaration first
        if let Ok(decl) = self.try_parse_declaration(input) {
            return self.process_declaration(decl, input);
        }

        // Try to evaluate as expression
        // Return the expression result or error directly
        self.try_eval_expression(input)
    }

    /// Handle a REPL command (starts with `:`)
    fn handle_command(&mut self, cmd: &str) -> Result<EvalResult, ReplError> {
        let parts: Vec<&str> = cmd.splitn(2, ' ').collect();
        let command = parts[0];
        let args = parts.get(1).map(|s| s.trim());

        match command {
            ":help" | ":h" | ":?" => Ok(EvalResult::Help(HELP_TEXT.to_string())),

            ":quit" | ":q" | ":exit" => Ok(EvalResult::Quit),

            ":clear" | ":reset" => {
                self.declarations.clear();
                self.source_texts.clear();
                self.context = ReplContext::new();
                Ok(EvalResult::Message("Session cleared".to_string()))
            }

            ":list" | ":ls" => {
                let names: Vec<String> = self
                    .declarations
                    .iter()
                    .map(|d| d.name().to_string())
                    .collect();
                if names.is_empty() {
                    Ok(EvalResult::Message("No declarations defined".to_string()))
                } else {
                    Ok(EvalResult::Message(format!(
                        "Declarations:\n  {}",
                        names.join("\n  ")
                    )))
                }
            }

            ":type" | ":t" => {
                if let Some(name) = args {
                    self.show_type(name)
                } else {
                    Err(ReplError::Command("Usage: :type <name>".to_string()))
                }
            }

            ":emit" | ":rust" => {
                // Emit Rust code for current session
                self.emit_rust()
            }

            ":wasm" => {
                // Compile to WASM and show info
                self.compile_wasm_info()
            }

            ":shake" => {
                // Run tree shaking analysis
                self.analyze_tree_shaking()
            }

            ":history" => {
                let hist = self
                    .history
                    .iter()
                    .enumerate()
                    .map(|(i, h)| format!("{}: {}", i + 1, h))
                    .collect::<Vec<_>>()
                    .join("\n");
                Ok(EvalResult::Message(hist))
            }

            ":load" => {
                if let Some(path) = args {
                    self.load_file(path)
                } else {
                    Err(ReplError::Command("Usage: :load <file.dol>".to_string()))
                }
            }

            ":load-spirit" | ":spirit" => {
                if let Some(path) = args {
                    self.load_spirit(path)
                } else {
                    Err(ReplError::Command(
                        "Usage: :load-spirit <path/to/spirit>".to_string(),
                    ))
                }
            }

            ":spirits" => self.list_spirits(),

            ":reload" => self.reload_current_spirit(),

            _ => Err(ReplError::Command(format!("Unknown command: {}", command))),
        }
    }

    /// Try to parse input as a declaration.
    fn try_parse_declaration(&self, input: &str) -> Result<Declaration, ParseError> {
        let mut parser = Parser::new(input);
        parser.parse()
    }

    /// Process a parsed declaration.
    fn process_declaration(
        &mut self,
        decl: Declaration,
        source: &str,
    ) -> Result<EvalResult, ReplError> {
        let name = decl.name().to_string();
        let kind = match &decl {
            Declaration::Gene(_) => "gene",
            Declaration::Trait(_) => "trait",
            Declaration::Constraint(_) => "constraint",
            Declaration::System(_) => "system",
            Declaration::Evolution(_) => "evolution",
            Declaration::Function(_) => "function",
            Declaration::Const(_) => "const",
            Declaration::SexVar(_) => "var",
        };

        // Check if we're redefining
        let existing_idx = self.declarations.iter().position(|d| d.name() == name);
        let redefined = existing_idx.is_some();

        if let Some(idx) = existing_idx {
            // Remove old definition and its source text
            self.declarations.remove(idx);
            if idx < self.source_texts.len() {
                self.source_texts.remove(idx);
            }
        }

        // Add new declaration and its source
        self.declarations.push(decl);
        self.source_texts.push(source.to_string());

        // Update context
        self.context.add_declaration(&name, kind);

        let msg = if redefined {
            format!("Redefined {} {}", kind, name)
        } else {
            format!("Defined {} {}", kind, name)
        };

        Ok(EvalResult::Defined {
            name,
            kind: kind.to_string(),
            message: msg,
        })
    }

    /// Try to evaluate input as an expression.
    ///
    /// Wraps the expression in a function, compiles to WASM, and executes it.
    /// Returns the evaluated result.
    #[cfg(feature = "wasm")]
    fn try_eval_expression(&mut self, input: &str) -> Result<EvalResult, ReplError> {
        use crate::repl::evaluator::EvalError;

        // Get declarations source for context
        let declarations_source = self.build_source();

        // Use the evaluator to compile and execute
        match self.evaluator.eval_expression(input, &declarations_source) {
            Ok(value) => Ok(EvalResult::Expression {
                input: input.to_string(),
                value,
            }),
            Err(e) => {
                // Convert EvalError to ReplError
                let repl_err = match e {
                    EvalError::Parse(msg) => ReplError::Parse(msg),
                    EvalError::Compile(msg) => ReplError::Wasm(msg),
                    EvalError::Runtime(msg) => ReplError::Wasm(format!("Runtime: {}", msg)),
                    EvalError::Feature(msg) => ReplError::Feature(msg),
                };
                Err(repl_err)
            }
        }
    }

    /// Try to evaluate input as an expression (stub when wasm feature not enabled).
    #[cfg(not(feature = "wasm"))]
    fn try_eval_expression(&mut self, input: &str) -> Result<EvalResult, ReplError> {
        // Infer the type for display purposes
        let return_type = self.evaluator.infer_expression_type(input);

        // Wrap expression in a temporary function for parsing validation
        let wrapper = format!(
            r#"
pub fun dolReplEval() -> {} {{
    {}
}}
"#,
            return_type, input
        );

        // Try to parse the wrapper to validate syntax
        let mut parser = Parser::new(&wrapper);
        let _decl = parser
            .parse()
            .map_err(|e| ReplError::Parse(e.to_string()))?;

        // Return message that evaluation requires wasm feature
        Err(ReplError::Feature(
            "Expression evaluation requires the 'wasm' feature. Use `cargo build --features wasm` to enable.".to_string()
        ))
    }

    /// Show type information for a declaration.
    fn show_type(&self, name: &str) -> Result<EvalResult, ReplError> {
        let decl = self
            .declarations
            .iter()
            .find(|d| d.name() == name)
            .ok_or_else(|| ReplError::NotFound(name.to_string()))?;

        let info = match decl {
            Declaration::Gene(g) => {
                let fields: Vec<String> = g
                    .statements
                    .iter()
                    .filter_map(|s| {
                        if let crate::ast::Statement::HasField(f) = s {
                            Some(format!("  {}: {:?}", f.name, f.type_))
                        } else {
                            None
                        }
                    })
                    .collect();
                format!("gene {} {{\n{}\n}}", name, fields.join("\n"))
            }
            Declaration::Function(f) => {
                let params: Vec<String> = f
                    .params
                    .iter()
                    .map(|p| format!("{}: {:?}", p.name, p.type_ann))
                    .collect();
                format!(
                    "fun {}({}) -> {:?}",
                    f.name,
                    params.join(", "),
                    f.return_type
                )
            }
            _ => format!("{} {}", declaration_kind_name(decl), name),
        };

        Ok(EvalResult::TypeInfo(info))
    }

    /// Emit Rust code for the current session.
    fn emit_rust(&self) -> Result<EvalResult, ReplError> {
        if self.declarations.is_empty() {
            return Ok(EvalResult::Message("No declarations to emit".to_string()));
        }

        // Build a DOL source from declarations (simplified)
        // In practice, we'd need to reconstruct the source or keep it
        let source = self.build_source();

        match compile_to_rust_via_hir(&source) {
            Ok(rust_code) => Ok(EvalResult::RustCode(rust_code)),
            Err(e) => Err(ReplError::Codegen(e.to_string())),
        }
    }

    /// Compile to WASM and show information.
    fn compile_wasm_info(&self) -> Result<EvalResult, ReplError> {
        #[cfg(feature = "wasm-compile")]
        {
            use crate::wasm::WasmCompiler;

            if self.declarations.is_empty() {
                return Ok(EvalResult::Message(
                    "No declarations to compile".to_string(),
                ));
            }

            let source = self.build_source();
            let file =
                crate::parse_dol_file(&source).map_err(|e| ReplError::Parse(e.to_string()))?;

            let mut compiler = WasmCompiler::new();
            let wasm_bytes = compiler
                .compile_file(&file)
                .map_err(|e| ReplError::Wasm(e.message))?;

            Ok(EvalResult::WasmInfo {
                size_bytes: wasm_bytes.len(),
                functions: self.count_functions(),
                has_memory: true,
            })
        }

        #[cfg(not(feature = "wasm-compile"))]
        Err(ReplError::Feature(
            "wasm-compile feature not enabled".to_string(),
        ))
    }

    /// Run tree shaking analysis.
    fn analyze_tree_shaking(&mut self) -> Result<EvalResult, ReplError> {
        if self.declarations.is_empty() {
            return Ok(EvalResult::Message(
                "No declarations to analyze".to_string(),
            ));
        }

        let stats = self.tree_shaker.analyze(&self.declarations);
        Ok(EvalResult::Message(stats.to_string()))
    }

    /// Load declarations from a file.
    fn load_file(&mut self, path: &str) -> Result<EvalResult, ReplError> {
        let source = std::fs::read_to_string(path).map_err(|e| ReplError::Io(e.to_string()))?;

        let file = crate::parse_dol_file(&source).map_err(|e| ReplError::Parse(e.to_string()))?;

        let count = file.declarations.len();
        // For file loading, we use the whole source for all declarations
        // since we can't easily extract individual declaration sources
        for decl in file.declarations {
            self.process_declaration(decl, &source)?;
        }

        Ok(EvalResult::Message(format!(
            "Loaded {} declarations from {}",
            count, path
        )))
    }

    /// Load a Spirit from a directory containing Spirit.dol.
    ///
    /// This loads the Spirit manifest and its entry point file.
    fn load_spirit(&mut self, path: &str) -> Result<EvalResult, ReplError> {
        let spirit_path = Path::new(path);

        // Check if path is a directory or a Spirit.dol file
        let (spirit_dir, manifest_path) = if spirit_path.is_dir() {
            (spirit_path.to_path_buf(), spirit_path.join("Spirit.dol"))
        } else if spirit_path
            .file_name()
            .map(|n| n == "Spirit.dol")
            .unwrap_or(false)
        {
            (
                spirit_path.parent().unwrap_or(Path::new(".")).to_path_buf(),
                spirit_path.to_path_buf(),
            )
        } else {
            return Err(ReplError::Command(format!(
                "Expected a Spirit directory or Spirit.dol file, got: {}",
                path
            )));
        };

        // Read and parse the Spirit manifest
        let manifest_source =
            std::fs::read_to_string(&manifest_path).map_err(|e| ReplError::Io(e.to_string()))?;

        let manifest =
            parse_spirit_manifest(&manifest_source).map_err(|e| ReplError::Parse(e.to_string()))?;

        let spirit_name = manifest.name.clone();

        // Check if spirit is already loaded
        if self.spirits.iter().any(|s| s.manifest.name == spirit_name) {
            // Reload the spirit - remove old version first
            self.spirits.retain(|s| s.manifest.name != spirit_name);
        }

        let mut loaded_decls = Vec::new();
        let mut loaded_sources = Vec::new();

        // Load the entry point file (defaults to "lib.dol")
        let entry_path = spirit_dir.join(&manifest.config.entry);
        if entry_path.exists() {
            let entry_source =
                std::fs::read_to_string(&entry_path).map_err(|e| ReplError::Io(e.to_string()))?;

            let file = crate::parse_dol_file(&entry_source)
                .map_err(|e| ReplError::Parse(e.to_string()))?;

            for decl in file.declarations {
                // Add to session declarations too
                let kind = match &decl {
                    Declaration::Gene(_) => "gene",
                    Declaration::Trait(_) => "trait",
                    Declaration::Constraint(_) => "constraint",
                    Declaration::System(_) => "system",
                    Declaration::Evolution(_) => "evolution",
                    Declaration::Function(_) => "function",
                    Declaration::Const(_) => "const",
                    Declaration::SexVar(_) => "var",
                };
                self.context.add_declaration(decl.name(), kind);
                self.declarations.push(decl.clone());
                self.source_texts.push(entry_source.clone());

                loaded_decls.push(decl);
                loaded_sources.push(entry_source.clone());
            }
        }

        // Also load any additional module files based on exports
        // Module names map to src/<name>.dol
        for module_export in &manifest.modules {
            let module_path = spirit_dir
                .join("src")
                .join(format!("{}.dol", module_export.name));
            if module_path.exists() {
                let module_source = std::fs::read_to_string(&module_path)
                    .map_err(|e| ReplError::Io(e.to_string()))?;

                let file = crate::parse_dol_file(&module_source)
                    .map_err(|e| ReplError::Parse(e.to_string()))?;

                for decl in file.declarations {
                    let kind = match &decl {
                        Declaration::Gene(_) => "gene",
                        Declaration::Trait(_) => "trait",
                        Declaration::Constraint(_) => "constraint",
                        Declaration::System(_) => "system",
                        Declaration::Evolution(_) => "evolution",
                        Declaration::Function(_) => "function",
                        Declaration::Const(_) => "const",
                        Declaration::SexVar(_) => "var",
                    };
                    self.context.add_declaration(decl.name(), kind);
                    self.declarations.push(decl.clone());
                    self.source_texts.push(module_source.clone());

                    loaded_decls.push(decl);
                    loaded_sources.push(module_source.clone());
                }
            }
        }

        let decl_count = loaded_decls.len();

        // Store the loaded spirit
        self.spirits.push(LoadedSpirit {
            manifest,
            path: spirit_dir,
            declarations: loaded_decls,
            source_texts: loaded_sources,
        });

        // Set as current spirit
        self.current_spirit = Some(spirit_name.clone());

        Ok(EvalResult::SpiritLoaded {
            name: spirit_name,
            declarations: decl_count,
        })
    }

    /// List all loaded spirits.
    fn list_spirits(&self) -> Result<EvalResult, ReplError> {
        if self.spirits.is_empty() {
            return Ok(EvalResult::Message("No spirits loaded".to_string()));
        }

        let mut output = String::from("Loaded Spirits:\n");
        for spirit in &self.spirits {
            let is_current = self
                .current_spirit
                .as_ref()
                .map(|c| c == &spirit.manifest.name)
                .unwrap_or(false);
            let marker = if is_current { " *" } else { "" };
            output.push_str(&format!(
                "  {} @ {}{}\n    Path: {}\n    Declarations: {}\n",
                spirit.manifest.name,
                spirit.manifest.version,
                marker,
                spirit.path.display(),
                spirit.declarations.len()
            ));
        }

        if self.current_spirit.is_some() {
            output.push_str("\n(* = current spirit)");
        }

        Ok(EvalResult::Message(output))
    }

    /// Reload the currently active spirit.
    fn reload_current_spirit(&mut self) -> Result<EvalResult, ReplError> {
        match &self.current_spirit {
            Some(name) => {
                // Find the spirit's path
                let spirit_path = self
                    .spirits
                    .iter()
                    .find(|s| &s.manifest.name == name)
                    .map(|s| s.path.clone())
                    .ok_or_else(|| ReplError::NotFound(name.clone()))?;

                // Reload it
                self.load_spirit(&spirit_path.to_string_lossy())
            }
            None => Err(ReplError::Command(
                "No spirit loaded. Use :load-spirit <path> first.".to_string(),
            )),
        }
    }

    /// Build DOL source from accumulated declarations.
    fn build_source(&self) -> String {
        // Use the stored original source texts for accurate compilation
        self.source_texts.join("\n\n")
    }

    /// Count functions in declarations.
    #[allow(dead_code)]
    fn count_functions(&self) -> usize {
        self.declarations
            .iter()
            .filter(|d| matches!(d, Declaration::Function(_)))
            .count()
    }

    /// Get the current declarations.
    pub fn declarations(&self) -> &[Declaration] {
        &self.declarations
    }

    /// Get evaluation history.
    pub fn history(&self) -> &[String] {
        &self.history
    }

    /// Get the session configuration.
    pub fn config(&self) -> &SessionConfig {
        &self.config
    }
}

/// REPL error types.
#[derive(Debug, Clone)]
pub enum ReplError {
    /// Parse error
    Parse(String),
    /// Command error
    Command(String),
    /// Declaration not found
    NotFound(String),
    /// Code generation error
    Codegen(String),
    /// WASM compilation error
    Wasm(String),
    /// I/O error
    Io(String),
    /// Feature not available
    Feature(String),
}

impl std::fmt::Display for ReplError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ReplError::Parse(msg) => write!(f, "Parse error: {}", msg),
            ReplError::Command(msg) => write!(f, "Command error: {}", msg),
            ReplError::NotFound(name) => write!(f, "Not found: {}", name),
            ReplError::Codegen(msg) => write!(f, "Codegen error: {}", msg),
            ReplError::Wasm(msg) => write!(f, "WASM error: {}", msg),
            ReplError::Io(msg) => write!(f, "I/O error: {}", msg),
            ReplError::Feature(msg) => write!(f, "Feature error: {}", msg),
        }
    }
}

impl std::error::Error for ReplError {}

/// Help text for the REPL.
const HELP_TEXT: &str = r#"
Spirit REPL - Interactive DOL Environment

Commands:
  :help, :h, :?       Show this help
  :quit, :q, :exit    Exit the REPL
  :clear, :reset      Clear all declarations
  :list, :ls          List defined declarations
  :type <name>        Show type info for a declaration
  :emit, :rust        Emit Rust code for session
  :wasm               Compile to WASM and show info
  :shake              Run tree shaking analysis
  :history            Show input history
  :load <file>        Load declarations from file

Spirit Management:
  :load-spirit <path> Load a Spirit from directory
  :spirits            List loaded Spirits
  :reload             Hot-reload current Spirit

Input Types:
  - Declarations: gene, trait, constraint, system, fun
  - Expressions: arithmetic, function calls (evaluation in progress)

Examples:
  gene Point { point has x: Int64; point has y: Int64 }
  fun add(a: Int64, b: Int64) -> Int64 { a + b }
  :type Point
  :load-spirit ./my-spirit/
  :spirits
  :emit
"#;

/// Helper function to get the kind name of a declaration.
fn declaration_kind_name(decl: &Declaration) -> &'static str {
    match decl {
        Declaration::Gene(_) => "gene",
        Declaration::Trait(_) => "trait",
        Declaration::Constraint(_) => "rule",
        Declaration::System(_) => "system",
        Declaration::Evolution(_) => "evo",
        Declaration::Function(_) => "fun",
        Declaration::Const(_) => "const",
        Declaration::SexVar(_) => "sex var",
    }
}

// Extension trait for Statement to generate DOL string
#[allow(dead_code)]
trait StatementExt {
    fn to_dol_string(&self) -> String;
}

impl StatementExt for crate::ast::Statement {
    fn to_dol_string(&self) -> String {
        match self {
            crate::ast::Statement::Has {
                subject, property, ..
            } => {
                format!("{} has {}", subject, property)
            }
            crate::ast::Statement::HasField(f) => {
                // HasField has: name, type_, default, constraint, span
                format!("has {}: {:?}", f.name, f.type_)
            }
            crate::ast::Statement::Is { subject, state, .. } => {
                format!("{} is {}", subject, state)
            }
            crate::ast::Statement::DerivesFrom {
                subject, origin, ..
            } => {
                format!("{} derives from {}", subject, origin)
            }
            crate::ast::Statement::Requires {
                subject,
                requirement,
                ..
            } => {
                format!("{} requires {}", subject, requirement)
            }
            crate::ast::Statement::Uses { reference, .. } => {
                format!("uses {}", reference)
            }
            crate::ast::Statement::Emits { action, event, .. } => {
                format!("{} emits {}", action, event)
            }
            crate::ast::Statement::Matches {
                subject, target, ..
            } => {
                format!("{} matches {}", subject, target)
            }
            crate::ast::Statement::Never {
                subject, action, ..
            } => {
                format!("{} never {}", subject, action)
            }
            crate::ast::Statement::Quantified {
                quantifier, phrase, ..
            } => {
                format!("{} {}", quantifier, phrase)
            }
            crate::ast::Statement::Function(_) => "// function".to_string(),
        }
    }
}

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

    // ==================== Basic REPL Operations ====================

    #[test]
    fn test_repl_new() {
        let repl = SpiritRepl::new();
        assert!(repl.declarations.is_empty());
        assert!(repl.history.is_empty());
    }

    #[test]
    fn test_repl_default() {
        let repl = SpiritRepl::default();
        assert!(repl.declarations.is_empty());
    }

    #[test]
    fn test_repl_with_config() {
        let config = SessionConfig::with_name("test-session");
        let repl = SpiritRepl::with_config(config);
        assert_eq!(repl.config().name, "test-session");
    }

    // ==================== REPL Commands ====================

    #[test]
    fn test_repl_help_command() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval(":help");
        assert!(matches!(result, Ok(EvalResult::Help(_))));
    }

    #[test]
    fn test_repl_help_short_commands() {
        let mut repl = SpiritRepl::new();
        assert!(matches!(repl.eval(":h"), Ok(EvalResult::Help(_))));
        assert!(matches!(repl.eval(":?"), Ok(EvalResult::Help(_))));
    }

    #[test]
    fn test_repl_quit_command() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval(":quit");
        assert!(matches!(result, Ok(EvalResult::Quit)));
    }

    #[test]
    fn test_repl_quit_aliases() {
        let mut repl = SpiritRepl::new();
        assert!(matches!(repl.eval(":q"), Ok(EvalResult::Quit)));
        assert!(matches!(repl.eval(":exit"), Ok(EvalResult::Quit)));
    }

    #[test]
    fn test_repl_empty_input() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval("");
        assert!(matches!(result, Ok(EvalResult::Empty)));
    }

    #[test]
    fn test_repl_whitespace_input() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval("   \t  \n  ");
        assert!(matches!(result, Ok(EvalResult::Empty)));
    }

    #[test]
    fn test_repl_list_empty() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval(":list");
        match result {
            Ok(EvalResult::Message(msg)) => {
                assert!(msg.contains("No declarations"));
            }
            _ => panic!("Expected message about no declarations"),
        }
    }

    #[test]
    fn test_repl_list_alias() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval(":ls");
        match result {
            Ok(EvalResult::Message(msg)) => {
                assert!(msg.contains("No declarations"));
            }
            _ => panic!("Expected message"),
        }
    }

    #[test]
    fn test_repl_unknown_command() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval(":foobar");
        assert!(matches!(result, Err(ReplError::Command(_))));
    }

    // ==================== Gene Declarations ====================

    #[test]
    fn test_repl_gene_declaration_legacy() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval("gene Point { has x: Int64\n has y: Int64 }");
        match result {
            Ok(EvalResult::Defined { name, kind, .. }) => {
                assert_eq!(name, "Point");
                assert_eq!(kind, "gene");
            }
            Err(e) => panic!("Failed to define gene: {:?}", e),
            _ => panic!("Expected Defined result"),
        }
    }

    #[test]
    fn test_repl_gen_declaration_v080() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval("gen Point { has x: i64\n has y: i64 }");
        match result {
            Ok(EvalResult::Defined { name, kind, .. }) => {
                assert_eq!(name, "Point");
                assert_eq!(kind, "gene");
            }
            Err(e) => panic!("Failed to define gen: {:?}", e),
            _ => panic!("Expected Defined result"),
        }
    }

    #[test]
    fn test_repl_gene_with_float_fields() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval("gen Vector2D { has dx: f64\n has dy: f64 }");
        match result {
            Ok(EvalResult::Defined { name, kind, .. }) => {
                assert_eq!(name, "Vector2D");
                assert_eq!(kind, "gene");
            }
            Err(e) => panic!("Failed to define gene with floats: {:?}", e),
            _ => panic!("Expected Defined result"),
        }
    }

    // ==================== Function Declarations ====================

    #[test]
    fn test_repl_function_declaration() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval("pub fun add(a: i64, b: i64) -> i64 { a + b }");
        match result {
            Ok(EvalResult::Defined { name, kind, .. }) => {
                assert_eq!(name, "add");
                assert_eq!(kind, "function");
            }
            Err(e) => panic!("Failed to define function: {:?}", e),
            _ => panic!("Expected Defined result"),
        }
    }

    #[test]
    fn test_repl_function_without_pub() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval("fun multiply(x: i64, y: i64) -> i64 { x * y }");
        match result {
            Ok(EvalResult::Defined { name, kind, .. }) => {
                assert_eq!(name, "multiply");
                assert_eq!(kind, "function");
            }
            Err(e) => panic!("Failed to define function: {:?}", e),
            _ => panic!("Expected Defined result"),
        }
    }

    #[test]
    fn test_repl_function_with_gene_constructor() {
        let mut repl = SpiritRepl::new();

        // First define a gene
        let _ = repl.eval("gen Point { has x: i64\n has y: i64 }");

        // Then define a function that uses the gene
        let result =
            repl.eval("pub fun create_point() -> i64 { let p = Point { x: 10, y: 20 }\n p.x }");
        match result {
            Ok(EvalResult::Defined { name, kind, .. }) => {
                assert_eq!(name, "create_point");
                assert_eq!(kind, "function");
            }
            Err(e) => panic!("Failed to define function with gene: {:?}", e),
            _ => panic!("Expected Defined result"),
        }
    }

    // ==================== Trait Declarations ====================

    #[test]
    fn test_repl_trait_declaration() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval("trait Addable { has value: i64 }");
        match result {
            Ok(EvalResult::Defined { name, kind, .. }) => {
                assert_eq!(name, "Addable");
                assert_eq!(kind, "trait");
            }
            Err(e) => panic!("Failed to define trait: {:?}", e),
            _ => panic!("Expected Defined result"),
        }
    }

    // ==================== Declaration Management ====================

    #[test]
    fn test_repl_list_declarations() {
        let mut repl = SpiritRepl::new();
        repl.eval("gen Point { has x: i64 }").unwrap();
        repl.eval("gen Circle { has radius: i64 }").unwrap();

        let result = repl.eval(":list");
        match result {
            Ok(EvalResult::Message(msg)) => {
                assert!(msg.contains("Point"));
                assert!(msg.contains("Circle"));
            }
            _ => panic!("Expected message with declarations"),
        }
    }

    #[test]
    fn test_repl_redefinition() {
        let mut repl = SpiritRepl::new();

        // Define Point
        repl.eval("gen Point { has x: i64 }").unwrap();
        assert_eq!(repl.declarations().len(), 1);

        // Redefine Point with different fields
        let result = repl.eval("gen Point { has x: i64\n has y: i64 }");
        match result {
            Ok(EvalResult::Defined { message, .. }) => {
                assert!(message.contains("Redefined"));
            }
            Err(e) => panic!("Failed to redefine: {:?}", e),
            _ => panic!("Expected Defined result"),
        }

        // Still only one declaration
        assert_eq!(repl.declarations().len(), 1);
    }

    #[test]
    fn test_repl_clear() {
        let mut repl = SpiritRepl::new();
        repl.eval("gen Point { has x: i64 }").unwrap();
        repl.eval("gen Circle { has r: i64 }").unwrap();
        assert_eq!(repl.declarations().len(), 2);

        let result = repl.eval(":clear");
        assert!(matches!(result, Ok(EvalResult::Message(_))));
        assert!(repl.declarations().is_empty());
    }

    #[test]
    fn test_repl_reset_alias() {
        let mut repl = SpiritRepl::new();
        repl.eval("gen Point { has x: i64 }").unwrap();

        let result = repl.eval(":reset");
        assert!(matches!(result, Ok(EvalResult::Message(_))));
        assert!(repl.declarations().is_empty());
    }

    // ==================== Type Information ====================

    #[test]
    fn test_repl_type_gene() {
        let mut repl = SpiritRepl::new();
        repl.eval("gen Point { has x: i64\n has y: i64 }").unwrap();

        let result = repl.eval(":type Point");
        match result {
            Ok(EvalResult::TypeInfo(info)) => {
                assert!(info.contains("Point"));
                assert!(info.contains("x"));
                assert!(info.contains("y"));
            }
            Err(e) => panic!("Failed to get type info: {:?}", e),
            _ => panic!("Expected TypeInfo result"),
        }
    }

    #[test]
    fn test_repl_type_function() {
        let mut repl = SpiritRepl::new();
        repl.eval("fun add(a: i64, b: i64) -> i64 { a + b }")
            .unwrap();

        let result = repl.eval(":type add");
        match result {
            Ok(EvalResult::TypeInfo(info)) => {
                assert!(info.contains("add"));
                assert!(info.contains("a"));
                assert!(info.contains("b"));
            }
            Err(e) => panic!("Failed to get type info: {:?}", e),
            _ => panic!("Expected TypeInfo result"),
        }
    }

    #[test]
    fn test_repl_type_alias() {
        let mut repl = SpiritRepl::new();
        repl.eval("gen Point { has x: i64 }").unwrap();

        let result = repl.eval(":t Point");
        assert!(matches!(result, Ok(EvalResult::TypeInfo(_))));
    }

    #[test]
    fn test_repl_type_not_found() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval(":type NonExistent");
        assert!(matches!(result, Err(ReplError::NotFound(_))));
    }

    #[test]
    fn test_repl_type_no_arg() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval(":type");
        assert!(matches!(result, Err(ReplError::Command(_))));
    }

    // ==================== History ====================

    #[test]
    fn test_repl_history() {
        let mut repl = SpiritRepl::new();
        repl.eval("gen Point { has x: i64 }").unwrap();
        repl.eval("gen Circle { has r: i64 }").unwrap();

        assert_eq!(repl.history().len(), 2);
        assert!(repl.history()[0].contains("Point"));
        assert!(repl.history()[1].contains("Circle"));
    }

    #[test]
    fn test_repl_history_command() {
        let mut repl = SpiritRepl::new();
        repl.eval("gen Point { has x: i64 }").unwrap();

        let result = repl.eval(":history");
        match result {
            Ok(EvalResult::Message(msg)) => {
                assert!(msg.contains("Point"));
            }
            _ => panic!("Expected history message"),
        }
    }

    // ==================== Expression Evaluation ====================

    #[test]
    #[cfg(feature = "wasm")]
    fn test_repl_expression_now_supported() {
        let mut repl = SpiritRepl::new();
        // Simple expressions like "1 + 2" are now supported with wasm feature
        let result = repl.eval("1 + 2");
        match result {
            Ok(EvalResult::Expression { value, .. }) => {
                assert_eq!(value, "3");
            }
            other => panic!("Expected Expression result with value 3, got {:?}", other),
        }
    }

    #[test]
    #[cfg(not(feature = "wasm"))]
    fn test_repl_expression_requires_wasm() {
        let mut repl = SpiritRepl::new();
        // Without wasm feature, expression evaluation returns Feature error
        let result = repl.eval("1 + 2");
        assert!(matches!(result, Err(ReplError::Feature(_))));
    }

    #[test]
    fn test_repl_function_as_expression() {
        // For now, define a function and call it via declarations
        let mut repl = SpiritRepl::new();

        // Define a function
        let result = repl.eval("pub fun calculate() -> i64 { 1 + 2 }");
        match result {
            Ok(EvalResult::Defined { name, kind, .. }) => {
                assert_eq!(name, "calculate");
                assert_eq!(kind, "function");
            }
            Err(e) => panic!("Failed to define function: {:?}", e),
            _ => panic!("Expected Defined result"),
        }
    }

    // ==================== Tree Shaking ====================

    #[test]
    fn test_repl_shake_empty() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval(":shake");
        match result {
            Ok(EvalResult::Message(msg)) => {
                assert!(msg.contains("No declarations"));
            }
            _ => panic!("Expected message about no declarations"),
        }
    }

    #[test]
    fn test_repl_shake_with_declarations() {
        let mut repl = SpiritRepl::new();
        repl.eval("gen Point { has x: i64 }").unwrap();
        repl.eval("pub fun test() -> i64 { let p = Point { x: 10 }\n p.x }")
            .unwrap();

        let result = repl.eval(":shake");
        assert!(matches!(result, Ok(EvalResult::Message(_))));
    }

    // ==================== Emit Rust ====================

    #[test]
    fn test_repl_emit_empty() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval(":emit");
        match result {
            Ok(EvalResult::Message(msg)) => {
                assert!(msg.contains("No declarations"));
            }
            _ => panic!("Expected message about no declarations"),
        }
    }

    #[test]
    fn test_repl_emit_alias() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval(":rust");
        match result {
            Ok(EvalResult::Message(msg)) => {
                assert!(msg.contains("No declarations"));
            }
            _ => panic!("Expected message"),
        }
    }

    // ==================== WASM Compilation ====================

    #[cfg(feature = "wasm-compile")]
    #[test]
    fn test_repl_wasm_empty() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval(":wasm");
        match result {
            Ok(EvalResult::Message(msg)) => {
                assert!(msg.contains("No declarations"));
            }
            _ => panic!("Expected message about no declarations"),
        }
    }

    #[cfg(feature = "wasm-compile")]
    #[test]
    fn test_repl_wasm_gene_constructor() {
        let mut repl = SpiritRepl::new();
        repl.eval("gen Point { has x: i64\n has y: i64 }").unwrap();
        repl.eval("pub fun test() -> i64 { let p = Point { x: 10, y: 20 }\n p.x }")
            .unwrap();

        let result = repl.eval(":wasm");
        match result {
            Ok(EvalResult::WasmInfo {
                size_bytes,
                functions,
                has_memory,
            }) => {
                assert!(size_bytes > 0);
                assert!(functions >= 1);
                assert!(has_memory);
            }
            Err(e) => panic!("WASM compilation failed: {:?}", e),
            _ => panic!("Expected WasmInfo result"),
        }
    }

    #[cfg(feature = "wasm-compile")]
    #[test]
    fn test_repl_wasm_float_operations() {
        let mut repl = SpiritRepl::new();
        repl.eval("gen Vector2D { has dx: f64\n has dy: f64 }")
            .unwrap();
        repl.eval(
            "pub fun magnitude() -> f64 { let v = Vector2D { dx: 3.0, dy: 4.0 }\n v.dx + v.dy }",
        )
        .unwrap();

        let result = repl.eval(":wasm");
        match result {
            Ok(EvalResult::WasmInfo { size_bytes, .. }) => {
                assert!(size_bytes > 0);
            }
            Err(e) => panic!("WASM compilation with floats failed: {:?}", e),
            _ => panic!("Expected WasmInfo result"),
        }
    }

    #[cfg(feature = "wasm")]
    #[test]
    fn test_repl_expression_evaluation_integer() {
        let mut repl = SpiritRepl::new();
        // Define a simple function that the expression can use
        repl.eval("pub fun add(a: i64, b: i64) -> i64 { a + b }")
            .unwrap();

        // Evaluate an expression that calls the function
        let result = repl.eval("add(2, 3)");
        match result {
            Ok(EvalResult::Expression { input, value }) => {
                assert_eq!(input, "add(2, 3)");
                assert_eq!(value, "5");
            }
            Err(e) => panic!("Expression evaluation failed: {:?}", e),
            other => panic!("Expected Expression result, got {:?}", other),
        }
    }

    #[cfg(feature = "wasm")]
    #[test]
    fn test_repl_expression_evaluation_literal() {
        let mut repl = SpiritRepl::new();

        // Evaluate a simple literal
        let result = repl.eval("42");
        match result {
            Ok(EvalResult::Expression { input, value }) => {
                assert_eq!(input, "42");
                assert_eq!(value, "42");
            }
            Err(e) => panic!("Literal evaluation failed: {:?}", e),
            other => panic!("Expected Expression result, got {:?}", other),
        }
    }

    #[cfg(feature = "wasm")]
    #[test]
    fn test_repl_expression_evaluation_float() {
        let mut repl = SpiritRepl::new();

        // Evaluate a float expression
        let result = repl.eval("3.14");
        match result {
            Ok(EvalResult::Expression { input, value }) => {
                assert_eq!(input, "3.14");
                assert!(value.starts_with("3.14"));
            }
            Err(e) => panic!("Float evaluation failed: {:?}", e),
            other => panic!("Expected Expression result, got {:?}", other),
        }
    }

    #[cfg(feature = "wasm")]
    #[test]
    fn test_repl_expression_evaluation_arithmetic() {
        let mut repl = SpiritRepl::new();

        // Evaluate arithmetic
        let result = repl.eval("10 + 20 * 2");
        match result {
            Ok(EvalResult::Expression { value, .. }) => {
                assert_eq!(value, "50");
            }
            Err(e) => panic!("Arithmetic evaluation failed: {:?}", e),
            other => panic!("Expected Expression result, got {:?}", other),
        }
    }

    #[cfg(feature = "wasm")]
    #[test]
    fn test_repl_expression_with_gene_field_access() {
        let mut repl = SpiritRepl::new();
        repl.eval("gen Point { has x: i64\n has y: i64 }").unwrap();

        // Define a function that creates and accesses gene field
        // (inline constructor field access requires type inference)
        repl.eval("pub fun getX() -> i64 { let p = Point { x: 100, y: 200 }\n p.x }")
            .unwrap();

        // Evaluate the function call
        let result = repl.eval("getX()");
        match result {
            Ok(EvalResult::Expression { value, .. }) => {
                assert_eq!(value, "100");
            }
            Err(e) => panic!("Gene field access evaluation failed: {:?}", e),
            other => panic!("Expected Expression result, got {:?}", other),
        }
    }

    #[cfg(not(feature = "wasm-compile"))]
    #[test]
    fn test_repl_wasm_feature_disabled() {
        let mut repl = SpiritRepl::new();
        repl.eval("gen Point { has x: i64 }").unwrap();

        let result = repl.eval(":wasm");
        assert!(matches!(result, Err(ReplError::Feature(_))));
    }

    // ==================== Load File ====================

    #[test]
    fn test_repl_load_no_arg() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval(":load");
        assert!(matches!(result, Err(ReplError::Command(_))));
    }

    #[test]
    fn test_repl_load_nonexistent_file() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval(":load /nonexistent/file.dol");
        assert!(matches!(result, Err(ReplError::Io(_))));
    }

    // ==================== Error Types ====================

    #[test]
    fn test_repl_error_display() {
        let err = ReplError::Parse("test error".to_string());
        assert_eq!(format!("{}", err), "Parse error: test error");

        let err = ReplError::NotFound("Point".to_string());
        assert_eq!(format!("{}", err), "Not found: Point");

        let err = ReplError::Command("bad command".to_string());
        assert_eq!(format!("{}", err), "Command error: bad command");

        let err = ReplError::Codegen("gen error".to_string());
        assert_eq!(format!("{}", err), "Codegen error: gen error");

        let err = ReplError::Wasm("wasm error".to_string());
        assert_eq!(format!("{}", err), "WASM error: wasm error");

        let err = ReplError::Io("io error".to_string());
        assert_eq!(format!("{}", err), "I/O error: io error");

        let err = ReplError::Feature("missing".to_string());
        assert_eq!(format!("{}", err), "Feature error: missing");
    }

    // ==================== Public API ====================

    #[test]
    fn test_repl_declarations_accessor() {
        let mut repl = SpiritRepl::new();
        repl.eval("gen Point { has x: i64 }").unwrap();
        repl.eval("gen Circle { has r: i64 }").unwrap();

        let decls = repl.declarations();
        assert_eq!(decls.len(), 2);
    }

    #[test]
    fn test_repl_history_accessor() {
        let mut repl = SpiritRepl::new();
        repl.eval("gen Point { has x: i64 }").unwrap();

        let history = repl.history();
        assert_eq!(history.len(), 1);
    }

    #[test]
    fn test_repl_config_accessor() {
        let config = SessionConfig::with_name("my-session");
        let repl = SpiritRepl::with_config(config);

        assert_eq!(repl.config().name, "my-session");
    }

    // ==================== Spirit Loading ====================

    #[test]
    fn test_repl_spirits_empty() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval(":spirits");
        match result {
            Ok(EvalResult::Message(msg)) => {
                assert!(msg.contains("No spirits loaded"));
            }
            _ => panic!("Expected message about no spirits"),
        }
    }

    #[test]
    fn test_repl_load_spirit_no_arg() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval(":load-spirit");
        assert!(matches!(result, Err(ReplError::Command(_))));
    }

    #[test]
    fn test_repl_load_spirit_nonexistent() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval(":load-spirit /nonexistent/spirit");
        assert!(matches!(
            result,
            Err(ReplError::Command(_)) | Err(ReplError::Io(_))
        ));
    }

    #[test]
    fn test_repl_reload_no_spirit() {
        let mut repl = SpiritRepl::new();
        let result = repl.eval(":reload");
        assert!(matches!(result, Err(ReplError::Command(_))));
    }

    #[test]
    fn test_repl_spirit_alias() {
        let mut repl = SpiritRepl::new();
        // :spirit should work as an alias for :load-spirit
        let result = repl.eval(":spirit");
        assert!(matches!(result, Err(ReplError::Command(_))));
    }

    #[test]
    fn test_loaded_spirit_struct() {
        // Test the LoadedSpirit struct directly
        let manifest_source = r#"
spirit test_spirit @ 1.0.0
docs "A test spirit"
"#;
        let manifest = parse_spirit_manifest(manifest_source).expect("should parse");

        let loaded = LoadedSpirit {
            manifest,
            path: PathBuf::from("/test/path"),
            declarations: Vec::new(),
            source_texts: Vec::new(),
        };

        assert_eq!(loaded.manifest.name, "test_spirit");
        assert_eq!(loaded.path.to_string_lossy(), "/test/path");
    }

    #[test]
    fn test_eval_result_spirit_loaded() {
        let result = EvalResult::SpiritLoaded {
            name: "my-spirit".to_string(),
            declarations: 5,
        };
        assert!(matches!(result, EvalResult::SpiritLoaded { .. }));
    }
}