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
//! vudo - VUDO Spirit runtime and toolchain
//!
//! A unified CLI for compiling, running, and checking DOL spirits.
//!
//! # Usage
//!
//! ```bash
//! # Run a WASM spirit
//! vudo run counter.wasm
//! vudo run counter.wasm -f add_numbers -a '[3, 4]'
//!
//! # Compile DOL to WASM
//! vudo compile counter.dol -o counter.wasm
//!
//! # Type-check DOL files
//! vudo check counter.dol
//! ```

use clap::{Parser, Subcommand};
use colored::Colorize;
use std::io;
use std::path::PathBuf;
use std::process::ExitCode;

/// VUDO Spirit runtime and toolchain
#[derive(Parser, Debug)]
#[command(name = "vudo")]
#[command(author, version, about = "VUDO Spirit runtime and toolchain")]
#[command(propagate_version = true)]
struct Cli {
    #[command(subcommand)]
    command: Commands,

    /// Enable verbose output
    #[arg(short, long, global = true)]
    verbose: bool,

    /// Suppress non-error output
    #[arg(short, long, global = true)]
    quiet: bool,
}

#[derive(Subcommand, Debug)]
enum Commands {
    /// Run a WASM spirit
    Run(RunArgs),

    /// Compile DOL to WASM
    Compile(CompileArgs),

    /// Type-check DOL files
    Check(CheckArgs),

    /// Start interactive REPL
    Repl(ReplArgs),
}

/// Arguments for the run command
#[derive(Parser, Debug)]
struct RunArgs {
    /// Path to WASM file
    #[arg(required = true)]
    file: PathBuf,

    /// Function to call (default: main or first exported function)
    #[arg(short, long)]
    function: Option<String>,

    /// Arguments as JSON array (e.g., '[3, 4]' or '[1234]')
    #[arg(short, long)]
    args: Option<String>,

    /// Initial memory pages (default: 16 = 1MB)
    #[arg(long, default_value = "16")]
    memory: u32,

    /// Enable execution tracing
    #[arg(long)]
    trace: bool,
}

/// Arguments for the compile command
#[derive(Parser, Debug)]
struct CompileArgs {
    /// Path to DOL file
    #[arg(required = true)]
    file: PathBuf,

    /// Output file (default: <input>.wasm)
    #[arg(short, long)]
    output: Option<PathBuf>,

    /// Enable optimization
    #[arg(long)]
    optimize: bool,

    /// Include debug info in output
    #[arg(long)]
    debug: bool,
}

/// Arguments for the check command
#[derive(Parser, Debug)]
struct CheckArgs {
    /// Files or directories to check
    #[arg(required = true)]
    paths: Vec<PathBuf>,

    /// Treat warnings as errors
    #[arg(long)]
    strict: bool,

    /// Output as JSON
    #[arg(long)]
    json: bool,

    /// Recursively check directories
    #[arg(short, long)]
    recursive: bool,
}

/// Arguments for the repl command
#[derive(Parser, Debug)]
struct ReplArgs {
    /// Load a file on startup
    #[arg(short, long)]
    load: Option<PathBuf>,

    /// Enable tree shaking
    #[arg(long, default_value = "true")]
    tree_shake: bool,

    /// Enable optimization
    #[arg(long)]
    optimize: bool,

    /// Session name
    #[arg(long, default_value = "default")]
    session: String,
}

fn main() -> ExitCode {
    let cli = Cli::parse();

    let result = match cli.command {
        Commands::Run(args) => cmd_run(args, cli.verbose, cli.quiet),
        Commands::Compile(args) => cmd_compile(args, cli.verbose, cli.quiet),
        Commands::Check(args) => cmd_check(args, cli.verbose, cli.quiet),
        Commands::Repl(args) => cmd_repl(args, cli.verbose, cli.quiet),
    };

    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("{}: {}", "error".red(), e);
            ExitCode::FAILURE
        }
    }
}

// =============================================================================
// Run Command
// =============================================================================

#[cfg(feature = "wasm")]
fn cmd_run(args: RunArgs, verbose: bool, quiet: bool) -> Result<(), String> {
    use wasmtime::{Engine, Instance, Module, Store, Val};

    if !args.file.exists() {
        return Err(format!("File not found: {}", args.file.display()));
    }

    if verbose {
        eprintln!("{} {}", "Loading".cyan(), args.file.display());
    }

    // Read WASM bytes
    let wasm_bytes =
        std::fs::read(&args.file).map_err(|e| format!("Failed to read WASM file: {}", e))?;

    if verbose {
        eprintln!("  {} bytes loaded", wasm_bytes.len());
    }

    // Create wasmtime engine and module
    let engine = Engine::default();
    let module =
        Module::new(&engine, &wasm_bytes).map_err(|e| format!("Failed to compile WASM: {}", e))?;

    // Create store with default state
    let mut store = Store::new(&engine, ());

    // Create instance
    let instance = Instance::new(&mut store, &module, &[])
        .map_err(|e| format!("Failed to instantiate WASM: {}", e))?;

    // Find function to call
    let func_name = args.function.as_deref().unwrap_or_else(|| {
        // Try to find main, or use first exported function
        if instance.get_func(&mut store, "main").is_some() {
            "main"
        } else {
            // Get first exported function
            module
                .exports()
                .find(|e| e.ty().func().is_some())
                .map(|e| e.name())
                .unwrap_or("main")
        }
    });

    let func = instance
        .get_func(&mut store, func_name)
        .ok_or_else(|| format!("Function '{}' not found", func_name))?;

    if verbose {
        eprintln!("{} {}()", "Calling".cyan(), func_name);
    }

    // Parse arguments
    let call_args = parse_json_args(&args.args, &func, &store)?;

    // Prepare result storage
    let func_ty = func.ty(&store);
    let mut results: Vec<Val> = func_ty.results().map(|_| Val::I64(0)).collect();

    // Call function
    func.call(&mut store, &call_args, &mut results)
        .map_err(|e| format!("Execution error: {}", e))?;

    // Print results
    if !quiet {
        if results.is_empty() {
            println!("(no return value)");
        } else if results.len() == 1 {
            println!("{}", format_val(&results[0]));
        } else {
            let formatted: Vec<String> = results.iter().map(format_val).collect();
            println!("({})", formatted.join(", "));
        }
    }

    Ok(())
}

#[cfg(feature = "wasm")]
fn parse_json_args(
    args_json: &Option<String>,
    func: &wasmtime::Func,
    store: &wasmtime::Store<()>,
) -> Result<Vec<wasmtime::Val>, String> {
    use wasmtime::{Val, ValType};

    let Some(json_str) = args_json else {
        return Ok(vec![]);
    };

    // Parse JSON array
    let parsed: serde_json::Value =
        serde_json::from_str(json_str).map_err(|e| format!("Invalid JSON arguments: {}", e))?;

    let arr = parsed
        .as_array()
        .ok_or_else(|| "Arguments must be a JSON array".to_string())?;

    let func_ty = func.ty(store);
    let param_types: Vec<_> = func_ty.params().collect();

    if arr.len() != param_types.len() {
        return Err(format!(
            "Expected {} arguments, got {}",
            param_types.len(),
            arr.len()
        ));
    }

    let mut vals = Vec::with_capacity(arr.len());

    for (i, (val, ty)) in arr.iter().zip(param_types.iter()).enumerate() {
        let wasm_val = match ty {
            ValType::I32 => {
                let n = val
                    .as_i64()
                    .ok_or_else(|| format!("Argument {} must be an integer", i))?;
                Val::I32(n as i32)
            }
            ValType::I64 => {
                let n = val
                    .as_i64()
                    .ok_or_else(|| format!("Argument {} must be an integer", i))?;
                Val::I64(n)
            }
            ValType::F32 => {
                let n = val
                    .as_f64()
                    .ok_or_else(|| format!("Argument {} must be a number", i))?;
                Val::F32((n as f32).to_bits())
            }
            ValType::F64 => {
                let n = val
                    .as_f64()
                    .ok_or_else(|| format!("Argument {} must be a number", i))?;
                Val::F64(n.to_bits())
            }
            _ => return Err(format!("Unsupported parameter type at position {}", i)),
        };
        vals.push(wasm_val);
    }

    Ok(vals)
}

#[cfg(feature = "wasm")]
fn format_val(val: &wasmtime::Val) -> String {
    match val {
        wasmtime::Val::I32(n) => n.to_string(),
        wasmtime::Val::I64(n) => n.to_string(),
        wasmtime::Val::F32(bits) => f32::from_bits(*bits).to_string(),
        wasmtime::Val::F64(bits) => f64::from_bits(*bits).to_string(),
        _ => format!("{:?}", val),
    }
}

#[cfg(not(feature = "wasm"))]
fn cmd_run(_args: RunArgs, _verbose: bool, _quiet: bool) -> Result<(), String> {
    Err("WASM feature not enabled. Rebuild with --features wasm".to_string())
}

// =============================================================================
// Compile Command
// =============================================================================

#[cfg(feature = "wasm")]
fn cmd_compile(args: CompileArgs, verbose: bool, quiet: bool) -> Result<(), String> {
    use metadol::parse_dol_file;
    use metadol::wasm::WasmCompiler;

    if !args.file.exists() {
        return Err(format!("File not found: {}", args.file.display()));
    }

    if verbose {
        eprintln!("{} {}", "Compiling".cyan(), args.file.display());
    }

    // Read DOL source
    let source =
        std::fs::read_to_string(&args.file).map_err(|e| format!("Failed to read file: {}", e))?;

    // Parse
    let file = parse_dol_file(&source).map_err(|e| format!("Parse error: {:?}", e))?;

    if verbose {
        eprintln!("  Parsed {} declarations", file.declarations.len());
    }

    // Compile to WASM
    let mut compiler = WasmCompiler::new();
    if args.optimize {
        compiler = compiler.with_optimization(true);
    }

    let wasm_bytes = compiler
        .compile_file(&file)
        .map_err(|e| format!("Compile error: {}", e.message))?;

    if verbose {
        eprintln!("  Generated {} bytes of WASM", wasm_bytes.len());
    }

    // Determine output path
    let output_path = args
        .output
        .unwrap_or_else(|| args.file.with_extension("wasm"));

    // Write output
    std::fs::write(&output_path, &wasm_bytes)
        .map_err(|e| format!("Failed to write output: {}", e))?;

    if !quiet {
        eprintln!(
            "{} {} ({} bytes)",
            "Wrote".green(),
            output_path.display(),
            wasm_bytes.len()
        );
    }

    Ok(())
}

#[cfg(not(feature = "wasm"))]
fn cmd_compile(_args: CompileArgs, _verbose: bool, _quiet: bool) -> Result<(), String> {
    Err("WASM feature not enabled. Rebuild with --features wasm".to_string())
}

// =============================================================================
// Check Command
// =============================================================================

fn cmd_check(args: CheckArgs, verbose: bool, quiet: bool) -> Result<(), String> {
    let files = collect_dol_files(&args.paths, args.recursive);

    if files.is_empty() {
        if !quiet {
            eprintln!("{}: No .dol files found", "warning".yellow());
        }
        return Ok(());
    }

    if verbose {
        eprintln!("Checking {} file(s)...", files.len());
    }

    let mut passed = 0;
    let mut failed = 0;
    let mut errors: Vec<(PathBuf, String)> = Vec::new();

    for path in &files {
        match check_file(path) {
            Ok(()) => {
                passed += 1;
                if verbose {
                    eprintln!("{} {}", "  OK".green(), path.display());
                }
            }
            Err(e) => {
                failed += 1;
                if !args.json {
                    eprintln!("{} {}: {}", "FAIL".red(), path.display(), e);
                }
                errors.push((path.clone(), e));
            }
        }
    }

    if args.json {
        let result = serde_json::json!({
            "passed": passed,
            "failed": failed,
            "errors": errors.iter().map(|(p, e)| {
                serde_json::json!({
                    "file": p.display().to_string(),
                    "error": e
                })
            }).collect::<Vec<_>>()
        });
        println!("{}", serde_json::to_string_pretty(&result).unwrap());
    } else if !quiet {
        eprintln!(
            "\n{} passed, {} failed",
            passed.to_string().green(),
            if failed > 0 {
                failed.to_string().red()
            } else {
                failed.to_string().normal()
            }
        );
    }

    if failed > 0 && args.strict {
        Err(format!("{} file(s) failed type check", failed))
    } else if failed > 0 {
        // Non-strict mode: report but don't fail
        Ok(())
    } else {
        Ok(())
    }
}

fn check_file(path: &PathBuf) -> Result<(), String> {
    let source =
        std::fs::read_to_string(path).map_err(|e| format!("Failed to read file: {}", e))?;

    // Parse the file
    metadol::parse_file(&source).map_err(|e| format!("Parse error: {}", e))?;

    // TODO: Add type checking when typechecker is integrated

    Ok(())
}

// =============================================================================
// REPL Command
// =============================================================================

fn cmd_repl(args: ReplArgs, verbose: bool, _quiet: bool) -> Result<(), String> {
    use metadol::repl::{EvalResult, SessionConfig, SpiritRepl};
    use std::io::{self, BufRead, Write};

    let config = SessionConfig::with_name(&args.session)
        .with_tree_shaking(args.tree_shake)
        .with_optimization(args.optimize);

    let mut repl = SpiritRepl::with_config(config);

    // Load file if specified
    if let Some(path) = &args.load {
        if verbose {
            eprintln!("{} {}", "Loading".cyan(), path.display());
        }
        let source =
            std::fs::read_to_string(path).map_err(|e| format!("Failed to load file: {}", e))?;
        let file =
            metadol::parse_dol_file(&source).map_err(|e| format!("Failed to parse file: {}", e))?;
        for _decl in file.declarations {
            let _ = repl.eval("// loaded from file");
        }
        eprintln!("Loaded {}", path.display());
    }

    // Print banner
    println!("{}", "Spirit REPL v0.8.0".cyan().bold());
    println!(
        "Type {} for help, {} to quit",
        ":help".green(),
        ":quit".green()
    );
    println!();

    let stdin = io::stdin();
    let mut stdout = io::stdout();

    loop {
        // Print prompt
        print!("{} ", "dol>".blue().bold());
        stdout.flush().map_err(|e| e.to_string())?;

        // Read input
        let mut line = String::new();
        if stdin
            .lock()
            .read_line(&mut line)
            .map_err(|e| e.to_string())?
            == 0
        {
            // EOF
            println!();
            break;
        }

        let input = line.trim();

        // Handle multi-line input (for declarations with braces)
        let full_input = if needs_continuation(input) {
            collect_multiline(&stdin, input)?
        } else {
            input.to_string()
        };

        // Evaluate
        match repl.eval(&full_input) {
            Ok(result) => match result {
                EvalResult::Empty => {}
                EvalResult::Quit => {
                    println!("Goodbye!");
                    break;
                }
                EvalResult::Help(text) => println!("{}", text),
                EvalResult::Message(msg) => println!("{}", msg),
                EvalResult::Defined {
                    name,
                    kind,
                    message,
                } => {
                    println!(
                        "{} {} {}: {}",
                        "Defined".green(),
                        kind.cyan(),
                        name.yellow(),
                        message
                    );
                }
                EvalResult::Expression { value, .. } => {
                    println!("= {}", value.yellow());
                }
                EvalResult::TypeInfo(info) => {
                    println!("{}", info.cyan());
                }
                EvalResult::RustCode(code) => {
                    println!("--- Rust ---");
                    println!("{}", code);
                    println!("------------");
                }
                EvalResult::WasmInfo {
                    size_bytes,
                    functions,
                    has_memory,
                } => {
                    println!(
                        "WASM: {} bytes, {} functions, memory: {}",
                        size_bytes, functions, has_memory
                    );
                }
            },
            Err(e) => {
                eprintln!("{}: {}", "Error".red(), e);
            }
        }
    }

    // Print session summary
    if verbose {
        println!(
            "\nSession ended. {} declarations defined.",
            repl.declarations().len()
        );
    }

    Ok(())
}

/// Check if input needs continuation (unclosed braces)
fn needs_continuation(input: &str) -> bool {
    let open_braces = input.matches('{').count();
    let close_braces = input.matches('}').count();
    open_braces > close_braces
}

/// Collect multi-line input until braces are balanced
fn collect_multiline(stdin: &io::Stdin, first_line: &str) -> Result<String, String> {
    use std::io::{BufRead, Write};

    let mut full = first_line.to_string();
    let mut stdout = io::stdout();

    loop {
        print!("{} ", "...".blue());
        stdout.flush().map_err(|e| e.to_string())?;

        let mut line = String::new();
        if stdin
            .lock()
            .read_line(&mut line)
            .map_err(|e| e.to_string())?
            == 0
        {
            break;
        }

        full.push('\n');
        full.push_str(&line);

        let open_braces = full.matches('{').count();
        let close_braces = full.matches('}').count();
        if open_braces <= close_braces {
            break;
        }
    }

    Ok(full)
}

// =============================================================================
// Utilities
// =============================================================================

fn collect_dol_files(paths: &[PathBuf], recursive: bool) -> Vec<PathBuf> {
    let mut files = Vec::new();

    for path in paths {
        if path.is_file() {
            if path.extension().is_some_and(|ext| ext == "dol") {
                files.push(path.clone());
            }
        } else if path.is_dir() {
            if recursive {
                collect_dol_files_recursive(path, &mut files);
            } else {
                if let Ok(entries) = std::fs::read_dir(path) {
                    for entry in entries.flatten() {
                        let p = entry.path();
                        if p.is_file() && p.extension().is_some_and(|ext| ext == "dol") {
                            files.push(p);
                        }
                    }
                }
            }
        }
    }

    files.sort();
    files
}

fn collect_dol_files_recursive(dir: &PathBuf, files: &mut Vec<PathBuf>) {
    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                collect_dol_files_recursive(&path, files);
            } else if path.extension().is_some_and(|ext| ext == "dol") {
                files.push(path);
            }
        }
    }
}

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

    #[test]
    fn test_collect_empty() {
        let files = collect_dol_files(&[], false);
        assert!(files.is_empty());
    }
}