Skip to main content

vm/
cli.rs

1use std::collections::BTreeMap;
2use std::io;
3use std::path::{Path, PathBuf};
4use std::sync::OnceLock;
5
6use crate as vm;
7
8use crate::{
9    CallOutcome, CallReturn, CompileSourceFileOptions, Debugger, DisassembleOptions, JitConfig,
10    Program, ReplLocalBinding, SourceFlavor, SourceMap, SourcePathError, Value, Vm, VmError,
11    VmRecording, VmStatus, compile_source_file_with_options, compile_source_for_repl_with_locals,
12    disassemble_vmbc_with_options, encode_program, format_source_with_flavor_and_options,
13    render_source_error, render_vm_error, replay_recording_stdio,
14};
15use crate::{HostFunctionRegistry, HostImport};
16use rustyline::DefaultEditor;
17use rustyline::error::ReadlineError;
18
19pub struct CliRuntime {
20    pub binary_name: &'static str,
21    pub default_source: &'static str,
22    pub compile_options: fn() -> CompileSourceFileOptions,
23}
24
25impl Default for CliRuntime {
26    fn default() -> Self {
27        Self {
28            binary_name: "pd-vm-run",
29            default_source: "examples/example.rss",
30            compile_options: CompileSourceFileOptions::default,
31        }
32    }
33}
34
35#[derive(Debug, Clone, PartialEq, Eq)]
36struct CliConfig {
37    source: Option<String>,
38    emit_vmbc_path: Option<String>,
39    epoch_check_interval: Option<u32>,
40    disasm_vmbc_path: Option<String>,
41    record_path: Option<String>,
42    view_recording_path: Option<String>,
43    show_source: bool,
44    fmt: bool,
45    fmt_check: bool,
46    repl: bool,
47    debug: bool,
48    tcp_addr: Option<String>,
49    stop_on_entry: bool,
50    aot: bool,
51    aot_dump: bool,
52    aot_save_path: Option<String>,
53    aot_load_path: Option<String>,
54    jit_dump: bool,
55    jit_dump_show_machine_code: bool,
56    jit_hot_loop_threshold: Option<u32>,
57    fuel: Option<u64>,
58    epoch_deadline: Option<u64>,
59    help: bool,
60    version: bool,
61}
62
63impl Default for CliConfig {
64    fn default() -> Self {
65        Self {
66            source: None,
67            emit_vmbc_path: None,
68            epoch_check_interval: None,
69            disasm_vmbc_path: None,
70            record_path: None,
71            view_recording_path: None,
72            show_source: false,
73            fmt: false,
74            fmt_check: false,
75            repl: false,
76            debug: false,
77            tcp_addr: None,
78            stop_on_entry: true,
79            aot: false,
80            aot_dump: false,
81            aot_save_path: None,
82            aot_load_path: None,
83            jit_dump: false,
84            jit_dump_show_machine_code: true,
85            jit_hot_loop_threshold: None,
86            fuel: None,
87            epoch_deadline: None,
88            help: false,
89            version: false,
90        }
91    }
92}
93
94pub fn main(runtime: CliRuntime) -> Result<(), Box<dyn std::error::Error>> {
95    if let Err(err) = run_main(&runtime) {
96        eprintln!("{err}");
97        std::process::exit(1);
98    }
99    Ok(())
100}
101
102fn run_main(runtime: &CliRuntime) -> Result<(), Box<dyn std::error::Error>> {
103    let args: Vec<String> = std::env::args().skip(1).collect();
104    let cli = parse_cli_args(&args).map_err(io::Error::other)?;
105    if cli.version {
106        println!("{}", binary_version_text(runtime.binary_name));
107        return Ok(());
108    }
109    if cli.help {
110        print_usage(runtime.binary_name);
111        return Ok(());
112    }
113    if cli.fmt {
114        return run_fmt(&cli, runtime);
115    }
116    if cli.repl {
117        return run_repl();
118    }
119    if let Some(input_path) = cli.disasm_vmbc_path.as_ref() {
120        let bytes = std::fs::read(input_path)?;
121        let listing = disassemble_vmbc_with_options(
122            &bytes,
123            DisassembleOptions {
124                show_source: cli.show_source,
125            },
126        )?;
127        print!("{listing}");
128        return Ok(());
129    }
130    if let Some(recording_path) = cli.view_recording_path.as_ref() {
131        let recording = VmRecording::load_from_file(recording_path)?;
132        replay_recording_stdio(&recording);
133        return Ok(());
134    }
135
136    if let Some(mut vm) = try_new_cli_vm_from_standalone_aot(&cli)? {
137        if let Some(output_path) = cli.emit_vmbc_path.as_ref() {
138            let encoded = encode_program(vm.program())?;
139            std::fs::write(output_path, &encoded)?;
140            println!("wrote {} bytes to {}", encoded.len(), output_path);
141            return Ok(());
142        }
143
144        apply_runtime_flags(&mut vm, &cli)?;
145        run_vm_loop(&mut vm, None, cli.fuel)?;
146        if cli.aot_dump {
147            println!("{}", vm.dump_aot_info());
148        }
149        if cli.jit_dump {
150            println!(
151                "{}",
152                vm.dump_jit_info_with_machine_code(cli.jit_dump_show_machine_code)
153            );
154        }
155        return Ok(());
156    }
157
158    let source_path = resolve_source_path(cli.source.as_deref(), runtime.default_source)?;
159    let compiled = compile_source_file_with_options(&source_path, (runtime.compile_options)())
160        .map_err(|err| io::Error::other(render_source_path_error(&source_path, &err)))?;
161    if let Some(output_path) = cli.emit_vmbc_path.as_ref() {
162        let encoded = encode_program(&compiled.program)?;
163        std::fs::write(output_path, &encoded)?;
164        println!("wrote {} bytes to {}", encoded.len(), output_path);
165        return Ok(());
166    }
167    let recording_program = cli.record_path.as_ref().map(|_| compiled.program.clone());
168    let mut vm = new_cli_vm(compiled.program.with_local_count(compiled.locals), &cli);
169    apply_runtime_flags(&mut vm, &cli)?;
170    let imports = vm.program().imports.clone();
171    register_imports(&mut vm, &imports)?;
172    prepare_aot_for_cli(&mut vm, &cli)?;
173
174    if let Some(record_path) = cli.record_path.as_ref() {
175        let program = recording_program.expect("recording mode should clone program");
176        let mut debugger = Debugger::with_recording(program);
177        run_vm_loop(&mut vm, Some(&mut debugger), cli.fuel)?;
178        let recording = debugger
179            .take_recording()
180            .ok_or_else(|| io::Error::other("recording state unavailable"))?;
181        recording.save_to_file(record_path)?;
182        println!(
183            "recording saved to {} (frames={})",
184            record_path,
185            recording.frames.len()
186        );
187        return Ok(());
188    }
189
190    let mut debugger = if cli.debug {
191        let mut debugger = if let Some(addr) = &cli.tcp_addr {
192            println!("[debug] tcp debugger listening on {addr}");
193            Debugger::with_tcp(addr)?
194        } else {
195            Debugger::new()
196        };
197        if cli.stop_on_entry {
198            debugger.stop_on_entry();
199        }
200        Some(debugger)
201    } else {
202        None
203    };
204
205    run_vm_loop(&mut vm, debugger.as_mut(), cli.fuel)?;
206    if cli.aot_dump {
207        println!("{}", vm.dump_aot_info());
208    }
209    if cli.jit_dump {
210        println!(
211            "{}",
212            vm.dump_jit_info_with_machine_code(cli.jit_dump_show_machine_code)
213        );
214    }
215    Ok(())
216}
217
218fn try_new_cli_vm_from_standalone_aot(cli: &CliConfig) -> Result<Option<Vm>, io::Error> {
219    let Some(path) = cli.aot_load_path.as_deref() else {
220        return Ok(None);
221    };
222    if cli.source.is_some() {
223        return Ok(None);
224    }
225
226    let mut vm = Vm::new_from_aot_artifact_file_with_jit_config(path, cli_jit_config(cli))
227        .map_err(io::Error::other)?;
228    configure_cli_vm(&mut vm);
229    let imports = vm.program().imports.clone();
230    register_imports(&mut vm, &imports)?;
231
232    if let Some(save_path) = cli.aot_save_path.as_deref() {
233        vm.save_aot_artifact_to_file(save_path)
234            .map_err(io::Error::other)?;
235    }
236
237    Ok(Some(vm))
238}
239
240fn apply_runtime_flags(vm: &mut Vm, cli: &CliConfig) -> Result<(), io::Error> {
241    vm.set_jit_native_bridge_stats_enabled(cli.jit_dump);
242    if let Some(interval) = cli.epoch_check_interval {
243        vm.set_epoch_check_interval(interval)
244            .map_err(|err| io::Error::other(render_vm_error(vm, &err)))?;
245    }
246    if let Some(fuel) = cli.fuel {
247        vm.set_fuel(fuel);
248    }
249    if let Some(deadline) = cli.epoch_deadline {
250        vm.set_epoch_deadline(deadline)
251            .map_err(|err| io::Error::other(render_vm_error(vm, &err)))?;
252    }
253    Ok(())
254}
255
256fn prepare_aot_for_cli(vm: &mut Vm, cli: &CliConfig) -> Result<(), io::Error> {
257    if let Some(path) = cli.aot_load_path.as_deref() {
258        vm.load_aot_artifact_from_file(path)
259            .map_err(io::Error::other)?;
260    } else if cli.aot || cli.aot_save_path.is_some() {
261        vm.compile_aot()
262            .map_err(|err| io::Error::other(render_vm_error(vm, &err)))?;
263    }
264
265    if let Some(path) = cli.aot_save_path.as_deref() {
266        vm.save_aot_artifact_to_file(path)
267            .map_err(io::Error::other)?;
268    }
269    Ok(())
270}
271
272fn run_vm_loop(
273    vm: &mut Vm,
274    mut debugger: Option<&mut Debugger>,
275    fuel_recharge: Option<u64>,
276) -> Result<(), io::Error> {
277    loop {
278        let status = if let Some(active_debugger) = debugger.as_deref_mut() {
279            vm.run_with_debugger(active_debugger)
280                .map_err(|err| io::Error::other(render_vm_error(vm, &err)))?
281        } else {
282            vm.run()
283                .map_err(|err| io::Error::other(render_vm_error(vm, &err)))?
284        };
285        match status {
286            VmStatus::Halted => {
287                println!("vm halted");
288                println!("stack: {:?}", vm.stack());
289                return Ok(());
290            }
291            VmStatus::Yielded => match vm.last_yield_reason() {
292                Some(vm::VmYieldReason::Fuel)
293                    if fuel_recharge.is_some() && vm.get_fuel() == Some(0) =>
294                {
295                    let recharge = fuel_recharge.unwrap_or(0);
296                    if recharge > 0 {
297                        vm.recharge_fuel(recharge)
298                            .map_err(|err| io::Error::other(render_vm_error(vm, &err)))?;
299                        println!("vm yielded, recharged {recharge} fuel, resuming...");
300                    } else {
301                        println!("vm yielded, resuming...");
302                    }
303                }
304                Some(vm::VmYieldReason::Epoch) => {
305                    let deadline = vm
306                        .epoch_deadline()
307                        .map(|value| value.to_string())
308                        .unwrap_or_else(|| "disabled".to_string());
309                    println!(
310                        "vm yielded at epoch deadline (current={}, deadline={deadline})",
311                        vm.current_epoch()
312                    );
313                    return Ok(());
314                }
315                _ => {
316                    println!("vm yielded, resuming...");
317                }
318            },
319            VmStatus::Waiting(_op_id) => {
320                vm.wait_for_host_op_blocking()
321                    .map_err(|err| io::Error::other(render_vm_error(vm, &err)))?;
322            }
323        }
324    }
325}
326
327fn render_source_path_error(source_path: &Path, err: &SourcePathError) -> String {
328    match err {
329        SourcePathError::Source(vm::SourceError::Parse(parse)) => {
330            let source = std::fs::read_to_string(source_path).unwrap_or_default();
331            let mut source_map = SourceMap::new();
332            let source_id = source_map.add_source(source_path.display().to_string(), source);
333            let parse = parse
334                .clone()
335                .with_line_span_from_source(&source_map, source_id);
336            render_source_error(&source_map, &parse, true)
337        }
338        SourcePathError::Source(vm::SourceError::Compile(compile)) => {
339            let render_path = compile
340                .source_name()
341                .map(Path::new)
342                .filter(|path| path.exists())
343                .unwrap_or(source_path);
344            let source = std::fs::read_to_string(render_path).unwrap_or_default();
345            let mut source_map = SourceMap::new();
346            source_map.add_source(render_path.display().to_string(), source);
347            vm::render_compile_error(&source_map, compile, true)
348        }
349        SourcePathError::InvalidImportSyntax {
350            path,
351            line,
352            message,
353        } => {
354            let source = std::fs::read_to_string(path).unwrap_or_default();
355            let mut source_map = SourceMap::new();
356            let source_id = source_map.add_source(path.display().to_string(), source);
357            let parse = vm::ParseError::at_line(*line, message.clone())
358                .with_line_span_from_source(&source_map, source_id);
359            render_source_error(&source_map, &parse, true)
360        }
361        _ => err.to_string(),
362    }
363}
364
365fn render_format_path_error(source_path: &Path, source: &str, err: &vm::FormatError) -> String {
366    match err {
367        vm::FormatError::Parse(parse) => {
368            let mut source_map = SourceMap::new();
369            let source_id =
370                source_map.add_source(source_path.display().to_string(), source.to_string());
371            let parse = parse
372                .clone()
373                .with_line_span_from_source(&source_map, source_id);
374            render_source_error(&source_map, &parse, true)
375        }
376        vm::FormatError::UnsupportedFlavor(_) => err.to_string(),
377    }
378}
379
380fn run_fmt(cli: &CliConfig, runtime: &CliRuntime) -> Result<(), Box<dyn std::error::Error>> {
381    let source_arg = cli
382        .source
383        .as_deref()
384        .ok_or_else(|| io::Error::other("fmt mode requires a source path"))?;
385    let source_path = resolve_source_path(Some(source_arg), runtime.default_source)?;
386    let flavor = source_flavor_from_path(&source_path)?;
387    let source = std::fs::read_to_string(&source_path)?;
388    let options = (runtime.compile_options)();
389    let formatted = format_source_with_flavor_and_options(&source, flavor, &options)
390        .map_err(|err| io::Error::other(render_format_path_error(&source_path, &source, &err)))?;
391
392    if cli.fmt_check {
393        if formatted == source {
394            return Ok(());
395        }
396        return Err(Box::new(io::Error::other(format!(
397            "would reformat {}",
398            source_path.display()
399        ))));
400    }
401
402    if formatted == source {
403        println!("already formatted {}", source_path.display());
404        return Ok(());
405    }
406
407    std::fs::write(&source_path, formatted)?;
408    println!("formatted {}", source_path.display());
409    Ok(())
410}
411
412fn parse_cli_args(args: &[String]) -> Result<CliConfig, String> {
413    let mut cfg = CliConfig::default();
414    if args.is_empty() {
415        cfg.repl = true;
416        return Ok(cfg);
417    }
418    if args
419        .iter()
420        .any(|arg| matches!(arg.as_str(), "-V" | "--version"))
421    {
422        cfg.version = true;
423        return Ok(cfg);
424    }
425    let mut index = 0usize;
426
427    if let Some(first) = args.first()
428        && first == "debug"
429    {
430        cfg.debug = true;
431        index = 1;
432    } else if let Some(first) = args.first()
433        && first == "repl"
434    {
435        cfg.repl = true;
436        index = 1;
437    } else if let Some(first) = args.first()
438        && first == "fmt"
439    {
440        cfg.fmt = true;
441        index = 1;
442    }
443
444    while index < args.len() {
445        match args[index].as_str() {
446            "-h" | "--help" => {
447                cfg.help = true;
448                index += 1;
449            }
450            "--debug" => {
451                cfg.debug = true;
452                index += 1;
453            }
454            "--tcp" => {
455                cfg.debug = true;
456                let addr = args
457                    .get(index + 1)
458                    .ok_or_else(|| "missing value for --tcp".to_string())?
459                    .clone();
460                cfg.tcp_addr = Some(addr);
461                index += 2;
462            }
463            "--stop-on-entry" => {
464                cfg.debug = true;
465                cfg.stop_on_entry = true;
466                index += 1;
467            }
468            "--no-stop-on-entry" => {
469                cfg.debug = true;
470                cfg.stop_on_entry = false;
471                index += 1;
472            }
473            "--aot" => {
474                cfg.aot = true;
475                index += 1;
476            }
477            "--aot-dump" => {
478                cfg.aot_dump = true;
479                index += 1;
480            }
481            "--aot-save" => {
482                let path = args
483                    .get(index + 1)
484                    .ok_or_else(|| "missing value for --aot-save".to_string())?;
485                cfg.aot_save_path = Some(path.clone());
486                index += 2;
487            }
488            "--aot-load" => {
489                let path = args
490                    .get(index + 1)
491                    .ok_or_else(|| "missing value for --aot-load".to_string())?;
492                cfg.aot_load_path = Some(path.clone());
493                index += 2;
494            }
495            "--jit-dump" | "--dump-jit" => {
496                cfg.jit_dump = true;
497                index += 1;
498            }
499            "--jit-dump-no-code" => {
500                cfg.jit_dump_show_machine_code = false;
501                index += 1;
502            }
503            "--jit-hot-loop" => {
504                let raw = args
505                    .get(index + 1)
506                    .ok_or_else(|| "missing value for --jit-hot-loop".to_string())?;
507                let value = raw
508                    .parse::<u32>()
509                    .map_err(|_| format!("invalid --jit-hot-loop value '{raw}'"))?;
510                cfg.jit_hot_loop_threshold = Some(value);
511                index += 2;
512            }
513            "--fuel" => {
514                let raw = args
515                    .get(index + 1)
516                    .ok_or_else(|| "missing value for --fuel".to_string())?;
517                let value = raw
518                    .parse::<u64>()
519                    .map_err(|_| format!("invalid --fuel value '{raw}'"))?;
520                cfg.fuel = Some(value);
521                index += 2;
522            }
523            "--epoch-deadline" => {
524                let raw = args
525                    .get(index + 1)
526                    .ok_or_else(|| "missing value for --epoch-deadline".to_string())?;
527                let value = raw
528                    .parse::<u64>()
529                    .map_err(|_| format!("invalid --epoch-deadline value '{raw}'"))?;
530                cfg.epoch_deadline = Some(value);
531                index += 2;
532            }
533            "--emit-vmbc" => {
534                let path = args
535                    .get(index + 1)
536                    .ok_or_else(|| "missing value for --emit-vmbc".to_string())?;
537                cfg.emit_vmbc_path = Some(path.clone());
538                index += 2;
539            }
540            "--epoch-check-interval" => {
541                let raw = args
542                    .get(index + 1)
543                    .ok_or_else(|| "missing value for --epoch-check-interval".to_string())?;
544                cfg.epoch_check_interval = Some(parse_cli_u32_flag("--epoch-check-interval", raw)?);
545                index += 2;
546            }
547            "--disasm-vmbc" => {
548                let path = args
549                    .get(index + 1)
550                    .ok_or_else(|| "missing value for --disasm-vmbc".to_string())?;
551                cfg.disasm_vmbc_path = Some(path.clone());
552                index += 2;
553            }
554            value if value.starts_with("--epoch-check-interval=") => {
555                let raw = value.trim_start_matches("--epoch-check-interval=");
556                cfg.epoch_check_interval = Some(parse_cli_u32_flag("--epoch-check-interval", raw)?);
557                index += 1;
558            }
559            "--record" => {
560                let path = args
561                    .get(index + 1)
562                    .ok_or_else(|| "missing value for --record".to_string())?;
563                cfg.record_path = Some(path.clone());
564                index += 2;
565            }
566            "--view-record" => {
567                let path = args
568                    .get(index + 1)
569                    .ok_or_else(|| "missing value for --view-record".to_string())?;
570                cfg.view_recording_path = Some(path.clone());
571                index += 2;
572            }
573            "--show-source" => {
574                cfg.show_source = true;
575                index += 1;
576            }
577            "--check" => {
578                cfg.fmt_check = true;
579                index += 1;
580            }
581            "--repl" => {
582                cfg.repl = true;
583                index += 1;
584            }
585            value if value.starts_with('-') => {
586                return Err(format!("unknown flag '{value}'"));
587            }
588            path => {
589                if cfg.source.is_some() {
590                    return Err("multiple source paths provided".to_string());
591                }
592                cfg.source = Some(path.to_string());
593                index += 1;
594            }
595        }
596    }
597
598    if !cfg.jit_dump_show_machine_code && !cfg.jit_dump {
599        return Err("--jit-dump-no-code requires --jit-dump or --dump-jit".to_string());
600    }
601    if cfg.fmt_check && !cfg.fmt {
602        return Err("--check requires fmt mode".to_string());
603    }
604    if cfg.fuel.is_some() && cfg.epoch_deadline.is_some() {
605        return Err("--fuel and --epoch-deadline are mutually exclusive".to_string());
606    }
607    if cfg.fuel.is_some() && cfg.epoch_check_interval.is_some() {
608        return Err("--fuel cannot be combined with --epoch-check-interval".to_string());
609    }
610    if cfg.aot && cfg.aot_load_path.is_some() {
611        return Err("--aot and --aot-load are mutually exclusive".to_string());
612    }
613
614    if cfg.repl {
615        if cfg.source.is_some() {
616            return Err("repl mode does not accept a source path".to_string());
617        }
618        if cfg.debug
619            || cfg.aot
620            || cfg.aot_dump
621            || cfg.aot_save_path.is_some()
622            || cfg.aot_load_path.is_some()
623            || cfg.tcp_addr.is_some()
624            || cfg.jit_dump
625            || cfg.jit_hot_loop_threshold.is_some()
626            || cfg.fuel.is_some()
627            || cfg.epoch_deadline.is_some()
628            || cfg.epoch_check_interval.is_some()
629            || cfg.emit_vmbc_path.is_some()
630            || cfg.disasm_vmbc_path.is_some()
631            || cfg.record_path.is_some()
632            || cfg.view_recording_path.is_some()
633        {
634            return Err(
635                "repl mode cannot be combined with debug/aot/jit/fuel/epoch/emit/disasm runtime flags"
636                    .to_string(),
637            );
638        }
639    }
640    if cfg.disasm_vmbc_path.is_some() {
641        if cfg.source.is_some() {
642            return Err("disasm mode does not accept a source path".to_string());
643        }
644        if cfg.repl
645            || cfg.debug
646            || cfg.aot
647            || cfg.aot_dump
648            || cfg.aot_save_path.is_some()
649            || cfg.aot_load_path.is_some()
650            || cfg.tcp_addr.is_some()
651            || cfg.jit_dump
652            || cfg.jit_hot_loop_threshold.is_some()
653            || cfg.fuel.is_some()
654            || cfg.epoch_deadline.is_some()
655            || cfg.epoch_check_interval.is_some()
656            || cfg.emit_vmbc_path.is_some()
657            || cfg.record_path.is_some()
658            || cfg.view_recording_path.is_some()
659        {
660            return Err(
661                "disasm mode cannot be combined with repl/debug/aot/jit/fuel/epoch/emit runtime flags"
662                    .to_string(),
663            );
664        }
665    } else if cfg.show_source {
666        return Err("--show-source requires --disasm-vmbc".to_string());
667    }
668
669    if cfg.fmt {
670        if cfg.source.is_none() && !cfg.help {
671            return Err("fmt mode requires a source path".to_string());
672        }
673        if cfg.repl
674            || cfg.debug
675            || cfg.aot
676            || cfg.aot_dump
677            || cfg.aot_save_path.is_some()
678            || cfg.aot_load_path.is_some()
679            || cfg.tcp_addr.is_some()
680            || cfg.jit_dump
681            || cfg.jit_hot_loop_threshold.is_some()
682            || cfg.fuel.is_some()
683            || cfg.epoch_deadline.is_some()
684            || cfg.epoch_check_interval.is_some()
685            || cfg.emit_vmbc_path.is_some()
686            || cfg.disasm_vmbc_path.is_some()
687            || cfg.record_path.is_some()
688            || cfg.view_recording_path.is_some()
689            || cfg.show_source
690        {
691            return Err(
692                "fmt mode cannot be combined with repl/debug/aot/jit/fuel/epoch/emit/disasm/record flags"
693                    .to_string(),
694            );
695        }
696    }
697
698    if cfg.debug
699        && (cfg.aot || cfg.aot_dump || cfg.aot_save_path.is_some() || cfg.aot_load_path.is_some())
700    {
701        return Err("debug mode cannot be combined with aot runtime flags".to_string());
702    }
703
704    if cfg.epoch_check_interval.is_some() && cfg.epoch_deadline.is_none() && !cfg.debug {
705        return Err("--epoch-check-interval requires --epoch-deadline or --debug".to_string());
706    }
707    if cfg.record_path.is_some()
708        && (cfg.debug
709            || cfg.aot
710            || cfg.aot_dump
711            || cfg.aot_save_path.is_some()
712            || cfg.aot_load_path.is_some()
713            || cfg.tcp_addr.is_some()
714            || cfg.jit_dump
715            || cfg.jit_hot_loop_threshold.is_some()
716            || cfg.emit_vmbc_path.is_some()
717            || cfg.disasm_vmbc_path.is_some()
718            || cfg.view_recording_path.is_some()
719            || cfg.show_source)
720    {
721        return Err(
722            "record mode cannot be combined with debug/aot/jit/emit/disasm/view-record flags"
723                .to_string(),
724        );
725    }
726    if cfg.view_recording_path.is_some()
727        && (cfg.source.is_some()
728            || cfg.debug
729            || cfg.aot
730            || cfg.aot_dump
731            || cfg.aot_save_path.is_some()
732            || cfg.aot_load_path.is_some()
733            || cfg.tcp_addr.is_some()
734            || cfg.jit_dump
735            || cfg.jit_hot_loop_threshold.is_some()
736            || cfg.fuel.is_some()
737            || cfg.epoch_deadline.is_some()
738            || cfg.epoch_check_interval.is_some()
739            || cfg.emit_vmbc_path.is_some()
740            || cfg.disasm_vmbc_path.is_some()
741            || cfg.record_path.is_some()
742            || cfg.show_source)
743    {
744        return Err(
745            "view-record mode cannot be combined with source/debug/aot/jit/fuel/epoch/emit/disasm flags"
746                .to_string(),
747        );
748    }
749
750    Ok(cfg)
751}
752
753fn resolve_source_path(arg: Option<&str>, default_source: &str) -> Result<PathBuf, io::Error> {
754    let rel = arg.unwrap_or(default_source);
755    let provided = PathBuf::from(rel);
756    if provided.is_absolute() {
757        return Ok(provided);
758    }
759
760    let cwd_path = std::env::current_dir()?.join(&provided);
761    if cwd_path.exists() {
762        return Ok(cwd_path);
763    }
764
765    Ok(Path::new(env!("CARGO_MANIFEST_DIR")).join(provided))
766}
767
768fn source_flavor_from_path(path: &Path) -> Result<SourceFlavor, io::Error> {
769    let ext = path
770        .extension()
771        .and_then(|value| value.to_str())
772        .ok_or_else(|| io::Error::other(SourcePathError::MissingExtension))?;
773    SourceFlavor::from_extension(ext)
774        .ok_or_else(|| io::Error::other(SourcePathError::UnsupportedExtension(ext.to_string())))
775}
776
777fn parse_cli_u32_flag(flag: &str, raw: &str) -> Result<u32, String> {
778    raw.parse::<u32>()
779        .map_err(|_| format!("invalid {flag} value '{raw}'"))
780}
781
782fn register_imports(vm: &mut Vm, imports: &[HostImport]) -> Result<(), io::Error> {
783    for import in imports {
784        if import.name.starts_with("http::") {
785            return Err(io::Error::other(format!(
786                "host function '{}' requires pd-edge runtime context",
787                import.name,
788            )));
789        }
790    }
791    if imports.is_empty() {
792        return Ok(());
793    }
794    let plan = cli_host_registry()
795        .prepare_shared_plan(imports)
796        .map_err(|err| io::Error::other(render_vm_error(vm, &err)))?;
797    cli_host_registry()
798        .bind_vm_with_plan(vm, &plan)
799        .map_err(|err| io::Error::other(render_vm_error(vm, &err)))?;
800    Ok(())
801}
802
803fn new_cli_vm(program: Program, cli: &CliConfig) -> Vm {
804    let mut vm = Vm::new_with_jit_config(program, cli_jit_config(cli));
805    configure_cli_vm(&mut vm);
806    vm
807}
808
809fn cli_jit_config(cli: &CliConfig) -> JitConfig {
810    let mut jit_config = JitConfig::default();
811    if let Some(hot_loop_threshold) = cli.jit_hot_loop_threshold {
812        jit_config.hot_loop_threshold = hot_loop_threshold;
813    }
814    jit_config
815}
816
817fn configure_cli_vm(vm: &mut Vm) {
818    vm.set_runtime_print_sink(|rendered| {
819        print!("{rendered}");
820    });
821}
822
823fn cli_host_registry() -> &'static HostFunctionRegistry {
824    static REGISTRY: OnceLock<HostFunctionRegistry> = OnceLock::new();
825    REGISTRY.get_or_init(|| {
826        let mut registry = HostFunctionRegistry::new();
827        registry.register_static("add_one", 1, add_one_host_function);
828        registry.register_static("echo", 1, echo_host_function);
829        registry
830    })
831}
832
833fn print_usage(binary_name: &str) {
834    println!("Usage:");
835    println!("  {binary_name}                  (defaults to REPL)");
836    println!("  {binary_name} --version");
837    println!("  {binary_name} [source_path]");
838    println!("  {binary_name} fmt [--check] <source_path>");
839    println!("  {binary_name} --repl");
840    println!("  {binary_name} repl");
841    println!("  {binary_name} --emit-vmbc <output.vmbc> [source_path]");
842    println!("  {binary_name} --disasm-vmbc <input.vmbc> [--show-source]");
843    println!("  {binary_name} --record <output.pdr> [source_path]");
844    println!("  {binary_name} --view-record <input.pdr>");
845    println!("  {binary_name} --debug [--stop-on-entry|--no-stop-on-entry] [source_path]");
846    println!("  {binary_name} --debug --tcp <addr> [source_path]");
847    println!(
848        "  {binary_name} [--aot|--aot-load <artifact.pat>] [--aot-save <artifact.pat>] [--aot-dump] [source_path]"
849    );
850    println!(
851        "  {binary_name} [--jit-hot-loop <n>] [--jit-dump|--dump-jit] [--jit-dump-no-code] [--emit-vmbc <output.vmbc>] [source_path]"
852    );
853    println!(
854        "  {binary_name} [--fuel <n>|--epoch-deadline <n>] [--epoch-check-interval <n>] [source_path]"
855    );
856    println!("  {binary_name} debug [--tcp <addr>] [source_path]");
857    println!();
858    println!("Options:");
859    println!("  -V, --version              Show version with git metadata");
860    println!("  -h, --help                 Show this help");
861    println!("      --check                In fmt mode, fail if formatting would change the file");
862}
863
864fn binary_version_text(binary: &str) -> String {
865    let git_tag = option_env!("PD_BUILD_GIT_TAG").unwrap_or("untagged");
866    let git_commit = option_env!("PD_BUILD_GIT_COMMIT").unwrap_or("unknown");
867    let git_dirty = option_env!("PD_BUILD_GIT_DIRTY").unwrap_or("false");
868    let dirty = matches!(git_dirty, "true" | "1" | "yes" | "dirty");
869
870    if dirty {
871        format!("{binary} {git_tag} (dirty commit: {git_commit})")
872    } else {
873        format!("{binary} {git_tag}")
874    }
875}
876
877fn run_repl() -> Result<(), Box<dyn std::error::Error>> {
878    println!("pd-vm REPL (RustScript)");
879    println!("history: up/down arrows, commands: .help, .quit, .cancel");
880    println!("state: locals persist across entries");
881    let mut editor = DefaultEditor::new()?;
882    let mut session = ReplSession::default();
883    let mut pending_input = String::new();
884    loop {
885        let prompt = if pending_input.is_empty() {
886            "pd-vm> "
887        } else {
888            "...> "
889        };
890        match editor.readline(prompt) {
891            Ok(line) => {
892                let trimmed = line.trim();
893                if pending_input.is_empty() {
894                    if trimmed.is_empty() {
895                        continue;
896                    }
897                    if let Some(action) = handle_repl_command(trimmed) {
898                        if action == ReplAction::Break {
899                            break;
900                        }
901                        continue;
902                    }
903                } else if trimmed == ".cancel" {
904                    pending_input.clear();
905                    println!("pending input cleared");
906                    continue;
907                }
908
909                if !pending_input.is_empty() {
910                    pending_input.push('\n');
911                }
912                pending_input.push_str(line.trim_end());
913                if !is_repl_input_complete(&pending_input) {
914                    continue;
915                }
916
917                let snippet = pending_input.trim().to_string();
918                pending_input.clear();
919                if snippet.is_empty() {
920                    continue;
921                }
922
923                let _ = editor.add_history_entry(&snippet);
924                let compiled = match compile_repl_snippet(&snippet, &session.locals) {
925                    Ok(compiled) => compiled,
926                    Err(err) => {
927                        println!("{}", render_repl_compile_error(&snippet, &err));
928                        continue;
929                    }
930                };
931                let mut vm = Vm::new_with_jit_config(
932                    compiled
933                        .compiled
934                        .program
935                        .with_local_count(compiled.compiled.locals),
936                    JitConfig::default(),
937                );
938                configure_cli_vm(&mut vm);
939                let imports = vm.program().imports.clone();
940                if let Err(err) = register_imports(&mut vm, &imports) {
941                    println!("{err}");
942                    continue;
943                }
944                if let Err(err) = seed_repl_vm_locals(&mut vm, &session.locals) {
945                    println!("{}", render_vm_error(&vm, &err));
946                    continue;
947                }
948                loop {
949                    match vm.run() {
950                        Ok(VmStatus::Halted) => {
951                            sync_repl_session(&vm, &compiled.bindings, &mut session);
952                            if let Some(value) = vm.stack().last() {
953                                println!("=> {}", format_value(value));
954                            } else {
955                                println!("=> <empty>");
956                            }
957                            break;
958                        }
959                        Ok(VmStatus::Yielded) => continue,
960                        Ok(VmStatus::Waiting(_op_id)) => {
961                            if let Err(err) = vm.wait_for_host_op_blocking() {
962                                sync_repl_session(&vm, &compiled.bindings, &mut session);
963                                println!("{}", render_vm_error(&vm, &err));
964                                break;
965                            }
966                            continue;
967                        }
968                        Err(err) => {
969                            sync_repl_session(&vm, &compiled.bindings, &mut session);
970                            println!("{}", render_vm_error(&vm, &err));
971                            break;
972                        }
973                    }
974                }
975            }
976            Err(ReadlineError::Interrupted) => {
977                if pending_input.is_empty() {
978                    println!("bye");
979                    break;
980                }
981                pending_input.clear();
982                println!("pending input cleared");
983            }
984            Err(ReadlineError::Eof) => {
985                println!("bye");
986                break;
987            }
988            Err(err) => {
989                return Err(Box::new(io::Error::other(err.to_string())));
990            }
991        }
992    }
993    Ok(())
994}
995
996#[derive(Default)]
997struct ReplSession {
998    locals: BTreeMap<String, ReplSessionLocal>,
999}
1000
1001#[derive(Clone, Debug, PartialEq)]
1002struct ReplSessionLocal {
1003    value: Value,
1004    mutable: bool,
1005    schema: Option<crate::compiler::TypeSchema>,
1006    optional: bool,
1007}
1008
1009fn sync_repl_session(vm: &Vm, bindings: &[ReplLocalBinding], session: &mut ReplSession) {
1010    if bindings.is_empty() {
1011        session.locals.clear();
1012        return;
1013    }
1014    let Some(debug) = vm.debug_info() else {
1015        session.locals.clear();
1016        return;
1017    };
1018    let mut next = BTreeMap::new();
1019    for binding in bindings {
1020        let Some(index) = debug.local_index(&binding.name) else {
1021            continue;
1022        };
1023        let Some(value) = vm.locals().get(index as usize) else {
1024            continue;
1025        };
1026        let (schema, optional) = repl_local_schema_from_vm(vm, index as usize, value);
1027        next.insert(
1028            binding.name.clone(),
1029            ReplSessionLocal {
1030                value: value.clone(),
1031                mutable: binding.mutable,
1032                schema,
1033                optional,
1034            },
1035        );
1036    }
1037    session.locals = next;
1038}
1039
1040#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1041enum ReplAction {
1042    Continue,
1043    Break,
1044}
1045
1046fn handle_repl_command(line: &str) -> Option<ReplAction> {
1047    match line {
1048        ".quit" | ".exit" => Some(ReplAction::Break),
1049        ".cancel" => {
1050            println!("no pending input");
1051            Some(ReplAction::Continue)
1052        }
1053        ".help" => {
1054            println!("commands:");
1055            println!("  .help      show commands");
1056            println!("  .quit      quit repl");
1057            println!("  .exit      quit repl");
1058            println!("  .cancel    clear pending multiline input");
1059            Some(ReplAction::Continue)
1060        }
1061        _ if line.starts_with('.') => {
1062            println!("unknown command: {line}");
1063            Some(ReplAction::Continue)
1064        }
1065        _ => None,
1066    }
1067}
1068
1069fn compile_repl_snippet(
1070    input: &str,
1071    locals: &BTreeMap<String, ReplSessionLocal>,
1072) -> Result<vm::CompiledReplProgram, vm::SourceError> {
1073    let trimmed = input.trim_end();
1074    let bindings = locals
1075        .iter()
1076        .map(|(name, local)| ReplLocalBinding {
1077            name: name.clone(),
1078            mutable: local.mutable,
1079            schema: local.schema.clone(),
1080            optional: local.optional,
1081        })
1082        .collect::<Vec<_>>();
1083    match compile_source_for_repl_with_locals(trimmed, &bindings) {
1084        Ok(compiled) => Ok(compiled),
1085        Err(first_err) => {
1086            if trimmed.ends_with(';') {
1087                return Err(first_err);
1088            }
1089            let fallback = format!("{trimmed};");
1090            compile_source_for_repl_with_locals(&fallback, &bindings).map_err(|_| first_err)
1091        }
1092    }
1093}
1094
1095fn seed_repl_vm_locals(
1096    vm: &mut Vm,
1097    locals: &BTreeMap<String, ReplSessionLocal>,
1098) -> Result<(), VmError> {
1099    if locals.is_empty() {
1100        return Ok(());
1101    }
1102    for (name, local) in locals {
1103        let index = {
1104            let Some(debug) = vm.debug_info() else {
1105                return Err(VmError::HostError(
1106                    "repl debug info unavailable while restoring locals".to_string(),
1107                ));
1108            };
1109            debug.local_index(name).ok_or_else(|| {
1110                VmError::HostError(format!("repl local '{name}' missing from compiled snippet"))
1111            })?
1112        };
1113        vm.set_local(index, local.value.clone())?;
1114    }
1115    Ok(())
1116}
1117
1118fn repl_local_schema_from_vm(
1119    vm: &Vm,
1120    index: usize,
1121    value: &Value,
1122) -> (Option<vm::compiler::TypeSchema>, bool) {
1123    let fallback = repl_schema_from_value(value);
1124    let Some(type_map) = vm.program().type_map.as_ref() else {
1125        return (fallback, false);
1126    };
1127    let schema = type_map
1128        .local_schemas
1129        .get(index)
1130        .cloned()
1131        .flatten()
1132        .or_else(|| {
1133            type_map
1134                .local_types
1135                .get(index)
1136                .copied()
1137                .and_then(repl_schema_from_value_type)
1138        })
1139        .or(fallback);
1140    let optional = type_map.optional_slots.get(index).copied().unwrap_or(false);
1141    (schema, optional)
1142}
1143
1144fn repl_schema_from_value(value: &Value) -> Option<vm::compiler::TypeSchema> {
1145    use vm::compiler::TypeSchema;
1146
1147    match value {
1148        Value::Null => Some(TypeSchema::Null),
1149        Value::Int(_) => Some(TypeSchema::Int),
1150        Value::Float(_) => Some(TypeSchema::Float),
1151        Value::Bool(_) => Some(TypeSchema::Bool),
1152        Value::String(_) => Some(TypeSchema::String),
1153        Value::Bytes(_) => Some(TypeSchema::Bytes),
1154        Value::Array(_) => Some(TypeSchema::Array(Box::new(TypeSchema::Unknown))),
1155        Value::Map(_) => Some(TypeSchema::Map(Box::new(TypeSchema::Unknown))),
1156    }
1157}
1158
1159fn repl_schema_from_value_type(value_type: vm::ValueType) -> Option<vm::compiler::TypeSchema> {
1160    use vm::compiler::TypeSchema;
1161
1162    match value_type {
1163        vm::ValueType::Unknown => None,
1164        vm::ValueType::Null => Some(TypeSchema::Null),
1165        vm::ValueType::Int => Some(TypeSchema::Int),
1166        vm::ValueType::Float => Some(TypeSchema::Float),
1167        vm::ValueType::Bool => Some(TypeSchema::Bool),
1168        vm::ValueType::String => Some(TypeSchema::String),
1169        vm::ValueType::Bytes => Some(TypeSchema::Bytes),
1170        vm::ValueType::Array => Some(TypeSchema::Array(Box::new(TypeSchema::Unknown))),
1171        vm::ValueType::Map => Some(TypeSchema::Map(Box::new(TypeSchema::Unknown))),
1172    }
1173}
1174
1175fn is_repl_input_complete(input: &str) -> bool {
1176    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1177    enum Delimiter {
1178        Paren,
1179        Bracket,
1180        Brace,
1181    }
1182
1183    let mut stack: Vec<Delimiter> = Vec::new();
1184    let mut chars = input.chars().peekable();
1185    let mut in_string = false;
1186    let mut escaped = false;
1187    let mut in_line_comment = false;
1188    let mut in_block_comment = false;
1189    let mut code = String::with_capacity(input.len());
1190
1191    while let Some(ch) = chars.next() {
1192        if in_line_comment {
1193            if ch == '\n' {
1194                in_line_comment = false;
1195                code.push('\n');
1196            }
1197            continue;
1198        }
1199        if in_block_comment {
1200            if ch == '*'
1201                && let Some('/') = chars.peek()
1202            {
1203                chars.next();
1204                in_block_comment = false;
1205            }
1206            continue;
1207        }
1208        if in_string {
1209            if escaped {
1210                escaped = false;
1211                continue;
1212            }
1213            match ch {
1214                '\\' => escaped = true,
1215                '"' => {
1216                    in_string = false;
1217                    code.push('"');
1218                }
1219                _ => {}
1220            }
1221            continue;
1222        }
1223
1224        if ch == '/' {
1225            match chars.peek().copied() {
1226                Some('/') => {
1227                    chars.next();
1228                    in_line_comment = true;
1229                    continue;
1230                }
1231                Some('*') => {
1232                    chars.next();
1233                    in_block_comment = true;
1234                    continue;
1235                }
1236                _ => {}
1237            }
1238        }
1239
1240        match ch {
1241            '"' => {
1242                in_string = true;
1243                code.push('"');
1244            }
1245            '(' => {
1246                stack.push(Delimiter::Paren);
1247                code.push(ch);
1248            }
1249            '[' => {
1250                stack.push(Delimiter::Bracket);
1251                code.push(ch);
1252            }
1253            '{' => {
1254                stack.push(Delimiter::Brace);
1255                code.push(ch);
1256            }
1257            ')' => {
1258                if stack.pop() != Some(Delimiter::Paren) {
1259                    return true;
1260                }
1261                code.push(ch);
1262            }
1263            ']' => {
1264                if stack.pop() != Some(Delimiter::Bracket) {
1265                    return true;
1266                }
1267                code.push(ch);
1268            }
1269            '}' => {
1270                if stack.pop() != Some(Delimiter::Brace) {
1271                    return true;
1272                }
1273                code.push(ch);
1274            }
1275            _ => code.push(ch),
1276        }
1277    }
1278
1279    if in_string || in_block_comment || !stack.is_empty() {
1280        return false;
1281    }
1282
1283    let trimmed = code.trim_end();
1284    if trimmed.is_empty() {
1285        return true;
1286    }
1287
1288    const TRAILING_INCOMPLETE_TOKENS: [&str; 18] = [
1289        "=>", "::", "&&", "||", "<=", ">=", "==", "!=", "=", ",", ".", "+", "-", "*", "/", "%",
1290        "!", ":",
1291    ];
1292    !TRAILING_INCOMPLETE_TOKENS
1293        .iter()
1294        .any(|token| trimmed.ends_with(token))
1295}
1296
1297fn render_repl_compile_error(snippet: &str, err: &vm::SourceError) -> String {
1298    match err {
1299        vm::SourceError::Parse(parse) => {
1300            let mut source_map = SourceMap::new();
1301            let source_id = source_map.add_source("<repl>", snippet.to_string());
1302            let parse = parse
1303                .clone()
1304                .with_line_span_from_source(&source_map, source_id);
1305            render_source_error(&source_map, &parse, true)
1306        }
1307        _ => err.to_string(),
1308    }
1309}
1310
1311fn add_one_host_function(_vm: &mut Vm, args: &[Value]) -> Result<CallOutcome, VmError> {
1312    let value = match args.first() {
1313        Some(Value::Int(value)) => *value,
1314        _ => return Err(VmError::TypeMismatch("int")),
1315    };
1316    Ok(CallOutcome::Return(CallReturn::one(Value::Int(value + 1))))
1317}
1318
1319fn echo_host_function(_vm: &mut Vm, args: &[Value]) -> Result<CallOutcome, VmError> {
1320    let value = args.first().cloned().ok_or(VmError::StackUnderflow)?;
1321    Ok(CallOutcome::Return(CallReturn::one(value)))
1322}
1323
1324fn format_value(value: &Value) -> String {
1325    match value {
1326        Value::Null => "null".to_string(),
1327        Value::Int(value) => value.to_string(),
1328        Value::Float(value) => value.to_string(),
1329        Value::Bool(value) => value.to_string(),
1330        Value::String(value) => value.as_str().to_string(),
1331        Value::Bytes(value) => format_bytes(value.as_ref()),
1332        Value::Array(values) => {
1333            let parts = values
1334                .iter()
1335                .map(format_value)
1336                .collect::<Vec<_>>()
1337                .join(", ");
1338            format!("[{parts}]")
1339        }
1340        Value::Map(entries) => {
1341            let parts = entries
1342                .iter()
1343                .map(|(key, value)| format!("{}: {}", format_value(key), format_value(value)))
1344                .collect::<Vec<_>>()
1345                .join(", ");
1346            format!("{{{parts}}}")
1347        }
1348    }
1349}
1350
1351fn format_bytes(bytes: &[u8]) -> String {
1352    let preview_len = bytes.len().min(16);
1353    let mut preview = String::with_capacity(preview_len * 2);
1354    for byte in &bytes[..preview_len] {
1355        preview.push(hex_nibble(byte >> 4));
1356        preview.push(hex_nibble(byte & 0x0F));
1357    }
1358    if bytes.len() > preview_len {
1359        format!("bytes[len={} hex={}..]", bytes.len(), preview)
1360    } else {
1361        format!("bytes[len={} hex={}]", bytes.len(), preview)
1362    }
1363}
1364
1365fn hex_nibble(value: u8) -> char {
1366    match value {
1367        0..=9 => char::from(b'0' + value),
1368        10..=15 => char::from(b'a' + (value - 10)),
1369        _ => unreachable!("hex nibble out of range"),
1370    }
1371}
1372
1373#[cfg(test)]
1374mod tests {
1375    use crate as vm;
1376    use std::collections::BTreeMap;
1377    use std::time::{SystemTime, UNIX_EPOCH};
1378
1379    use super::{
1380        CliConfig, parse_cli_args, prepare_aot_for_cli, register_imports,
1381        try_new_cli_vm_from_standalone_aot,
1382    };
1383    use vm::{HostImport, OpCode, Program, Value, ValueType, Vm, VmStatus};
1384
1385    fn s(value: &str) -> String {
1386        value.to_string()
1387    }
1388
1389    fn native_aot_supported() -> bool {
1390        (cfg!(target_arch = "x86_64")
1391            && (cfg!(target_os = "windows") || (cfg!(unix) && !cfg!(target_os = "macos"))))
1392            || (cfg!(target_arch = "aarch64")
1393                && (cfg!(target_os = "linux") || cfg!(target_os = "macos")))
1394    }
1395
1396    fn unique_artifact_path() -> std::path::PathBuf {
1397        let mut path = std::env::temp_dir();
1398        let stamp = SystemTime::now()
1399            .duration_since(UNIX_EPOCH)
1400            .expect("system clock should be after unix epoch")
1401            .as_nanos();
1402        path.push(format!("pd-vm-run-aot-{}-{stamp}.pat", std::process::id()));
1403        path
1404    }
1405
1406    fn run_repl_snippet_and_sync(session: &mut super::ReplSession, snippet: &str) -> Vm {
1407        let compiled =
1408            super::compile_repl_snippet(snippet, &session.locals).expect("compile should succeed");
1409        let mut vm = Vm::new(
1410            compiled
1411                .compiled
1412                .program
1413                .with_local_count(compiled.compiled.locals),
1414        );
1415        super::configure_cli_vm(&mut vm);
1416        let imports = vm.program().imports.clone();
1417        super::register_imports(&mut vm, &imports).expect("register should succeed");
1418        super::seed_repl_vm_locals(&mut vm, &session.locals).expect("locals should restore");
1419        loop {
1420            match vm.run().expect("snippet should run") {
1421                VmStatus::Halted => break,
1422                VmStatus::Yielded => continue,
1423                VmStatus::Waiting(_) => vm
1424                    .wait_for_host_op_blocking()
1425                    .expect("snippet should not block"),
1426            }
1427        }
1428        super::sync_repl_session(&vm, &compiled.bindings, session);
1429        vm
1430    }
1431
1432    #[test]
1433    fn register_imports_binds_cached_cli_host_registry_plan() {
1434        let imports = vec![
1435            HostImport {
1436                name: "print".to_string(),
1437                arity: 1,
1438                return_type: ValueType::Unknown,
1439            },
1440            HostImport {
1441                name: "echo".to_string(),
1442                arity: 1,
1443                return_type: ValueType::Unknown,
1444            },
1445        ];
1446        let program =
1447            Program::with_imports_and_debug(vec![], vec![OpCode::Ret as u8], imports.clone(), None);
1448
1449        let mut first = Vm::new(program.clone());
1450        register_imports(&mut first, &imports).expect("first vm should bind imports");
1451        assert_eq!(first.bound_function_count(), 2);
1452
1453        let mut second = Vm::new(program);
1454        register_imports(&mut second, &imports).expect("second vm should reuse cached plan");
1455        assert_eq!(second.bound_function_count(), 2);
1456    }
1457
1458    #[test]
1459    fn parse_cli_defaults() {
1460        let cfg = parse_cli_args(&[]).expect("parse should succeed");
1461        assert!(cfg.repl);
1462        assert!(!cfg.debug);
1463        assert!(!cfg.version);
1464        assert!(cfg.tcp_addr.is_none());
1465        assert!(cfg.stop_on_entry);
1466        assert!(!cfg.aot);
1467        assert!(!cfg.aot_dump);
1468        assert!(cfg.aot_save_path.is_none());
1469        assert!(cfg.aot_load_path.is_none());
1470        assert!(!cfg.jit_dump);
1471        assert!(cfg.jit_dump_show_machine_code);
1472        assert!(cfg.jit_hot_loop_threshold.is_none());
1473        assert!(cfg.fuel.is_none());
1474        assert!(cfg.epoch_deadline.is_none());
1475        assert!(cfg.source.is_none());
1476        assert!(cfg.epoch_check_interval.is_none());
1477        assert!(cfg.emit_vmbc_path.is_none());
1478        assert!(cfg.disasm_vmbc_path.is_none());
1479        assert!(!cfg.show_source);
1480        assert!(!cfg.fmt);
1481        assert!(!cfg.fmt_check);
1482    }
1483
1484    #[test]
1485    fn parse_cli_version_flag() {
1486        let cfg = parse_cli_args(&[s("--version")]).expect("parse should succeed");
1487        assert!(cfg.version);
1488        assert!(!cfg.repl);
1489    }
1490
1491    #[test]
1492    fn parse_cli_version_short_flag() {
1493        let cfg = parse_cli_args(&[s("-V")]).expect("parse should succeed");
1494        assert!(cfg.version);
1495        assert!(!cfg.repl);
1496    }
1497
1498    #[test]
1499    fn parse_cli_debug_with_source_and_tcp() {
1500        let cfg = parse_cli_args(&[
1501            s("--debug"),
1502            s("--tcp"),
1503            s("127.0.0.1:9002"),
1504            s("examples/example.lua"),
1505        ])
1506        .expect("parse should succeed");
1507        assert!(cfg.debug);
1508        assert_eq!(cfg.tcp_addr.as_deref(), Some("127.0.0.1:9002"));
1509        assert_eq!(cfg.source.as_deref(), Some("examples/example.lua"));
1510    }
1511
1512    #[test]
1513    fn parse_cli_legacy_debug_command() {
1514        let cfg =
1515            parse_cli_args(&[s("debug"), s("examples/example.rss")]).expect("parse should succeed");
1516        assert!(cfg.debug);
1517        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1518    }
1519
1520    #[test]
1521    fn parse_cli_rejects_multiple_sources() {
1522        let err = parse_cli_args(&[s("a.rss"), s("b.rss")]).expect_err("parse should fail");
1523        assert!(err.contains("multiple source paths"));
1524    }
1525
1526    #[test]
1527    fn parse_cli_jit_flags() {
1528        let cfg = parse_cli_args(&[
1529            s("--jit-hot-loop"),
1530            s("2"),
1531            s("--jit-dump"),
1532            s("--jit-dump-no-code"),
1533            s("examples/example.rss"),
1534        ])
1535        .expect("parse should succeed");
1536        assert_eq!(cfg.jit_hot_loop_threshold, Some(2));
1537        assert!(cfg.jit_dump);
1538        assert!(!cfg.jit_dump_show_machine_code);
1539        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1540    }
1541
1542    #[test]
1543    fn parse_cli_aot_flags() {
1544        let cfg = parse_cli_args(&[
1545            s("--aot"),
1546            s("--aot-dump"),
1547            s("--aot-save"),
1548            s("out/program.pat"),
1549            s("examples/example.rss"),
1550        ])
1551        .expect("parse should succeed");
1552        assert!(cfg.aot);
1553        assert!(cfg.aot_dump);
1554        assert_eq!(cfg.aot_save_path.as_deref(), Some("out/program.pat"));
1555        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1556    }
1557
1558    #[test]
1559    fn parse_cli_aot_load_without_source_path() {
1560        let cfg =
1561            parse_cli_args(&[s("--aot-load"), s("out/program.pat")]).expect("parse should succeed");
1562        assert_eq!(cfg.aot_load_path.as_deref(), Some("out/program.pat"));
1563        assert!(cfg.source.is_none());
1564    }
1565
1566    #[test]
1567    fn parse_cli_rejects_aot_and_load_together() {
1568        let err = parse_cli_args(&[
1569            s("--aot"),
1570            s("--aot-load"),
1571            s("out/program.pat"),
1572            s("examples/example.rss"),
1573        ])
1574        .expect_err("parse should fail");
1575        assert!(err.contains("mutually exclusive"));
1576    }
1577
1578    #[test]
1579    fn parse_cli_debug_rejects_aot_runtime_flags() {
1580        let err = parse_cli_args(&[s("--debug"), s("--aot"), s("examples/example.rss")])
1581            .expect_err("parse should fail");
1582        assert!(err.contains("debug mode"));
1583    }
1584
1585    #[test]
1586    fn parse_cli_dump_jit_alias() {
1587        let cfg = parse_cli_args(&[s("--dump-jit"), s("examples/example.rss")])
1588            .expect("parse should succeed");
1589        assert!(cfg.jit_dump);
1590        assert!(cfg.jit_dump_show_machine_code);
1591        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1592    }
1593
1594    #[test]
1595    fn parse_cli_jit_dump_no_code_requires_dump_flag() {
1596        let err = parse_cli_args(&[s("--jit-dump-no-code"), s("examples/example.rss")])
1597            .expect_err("parse should fail");
1598        assert!(err.contains("requires --jit-dump or --dump-jit"));
1599    }
1600
1601    #[test]
1602    fn parse_cli_fuel_flag() {
1603        let cfg = parse_cli_args(&[s("--fuel"), s("123"), s("examples/example.rss")])
1604            .expect("parse should succeed");
1605        assert_eq!(cfg.fuel, Some(123));
1606        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1607    }
1608
1609    #[test]
1610    fn parse_cli_fuel_requires_value() {
1611        let err = parse_cli_args(&[s("--fuel")]).expect_err("parse should fail");
1612        assert!(err.contains("missing value for --fuel"));
1613    }
1614
1615    #[test]
1616    fn parse_cli_epoch_deadline_flag() {
1617        let cfg = parse_cli_args(&[s("--epoch-deadline"), s("3"), s("examples/example.rss")])
1618            .expect("parse should succeed");
1619        assert_eq!(cfg.epoch_deadline, Some(3));
1620        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1621    }
1622
1623    #[test]
1624    fn parse_cli_rejects_fuel_and_epoch_deadline_together() {
1625        let err = parse_cli_args(&[
1626            s("--fuel"),
1627            s("10"),
1628            s("--epoch-deadline"),
1629            s("3"),
1630            s("examples/example.rss"),
1631        ])
1632        .expect_err("parse should fail");
1633        assert!(err.contains("mutually exclusive"));
1634    }
1635
1636    #[test]
1637    fn parse_cli_emit_vmbc_path() {
1638        let cfg = parse_cli_args(&[
1639            s("--emit-vmbc"),
1640            s("out/program.vmbc"),
1641            s("examples/example.rss"),
1642        ])
1643        .expect("parse should succeed");
1644        assert_eq!(cfg.emit_vmbc_path.as_deref(), Some("out/program.vmbc"));
1645        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1646    }
1647
1648    #[test]
1649    fn parse_cli_emit_vmbc_requires_path() {
1650        let err = parse_cli_args(&[s("--emit-vmbc")]).expect_err("parse should fail");
1651        assert!(err.contains("missing value for --emit-vmbc"));
1652    }
1653
1654    #[test]
1655    fn parse_cli_disasm_vmbc_path() {
1656        let cfg = parse_cli_args(&[
1657            s("--disasm-vmbc"),
1658            s("out/program.vmbc"),
1659            s("--show-source"),
1660        ])
1661        .expect("parse should succeed");
1662        assert_eq!(cfg.disasm_vmbc_path.as_deref(), Some("out/program.vmbc"));
1663        assert!(cfg.show_source);
1664    }
1665
1666    #[test]
1667    fn parse_cli_disasm_requires_path() {
1668        let err = parse_cli_args(&[s("--disasm-vmbc")]).expect_err("parse should fail");
1669        assert!(err.contains("missing value for --disasm-vmbc"));
1670    }
1671
1672    #[test]
1673    fn parse_cli_show_source_requires_disasm() {
1674        let err = parse_cli_args(&[s("--show-source")]).expect_err("parse should fail");
1675        assert!(err.contains("requires --disasm-vmbc"));
1676    }
1677
1678    #[test]
1679    fn parse_cli_disasm_rejects_source_path() {
1680        let err = parse_cli_args(&[
1681            s("--disasm-vmbc"),
1682            s("program.vmbc"),
1683            s("examples/example.rss"),
1684        ])
1685        .expect_err("parse should fail");
1686        assert!(err.contains("does not accept a source path"));
1687    }
1688
1689    #[test]
1690    fn parse_cli_record_path() {
1691        let cfg = parse_cli_args(&[s("--record"), s("out/run.pdr"), s("examples/example.rss")])
1692            .expect("parse should succeed");
1693        assert_eq!(cfg.record_path.as_deref(), Some("out/run.pdr"));
1694        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1695    }
1696
1697    #[test]
1698    fn parse_cli_view_record_path() {
1699        let cfg =
1700            parse_cli_args(&[s("--view-record"), s("out/run.pdr")]).expect("parse should succeed");
1701        assert_eq!(cfg.view_recording_path.as_deref(), Some("out/run.pdr"));
1702        assert!(cfg.source.is_none());
1703    }
1704
1705    #[test]
1706    fn parse_cli_view_record_rejects_fuel() {
1707        let err = parse_cli_args(&[s("--view-record"), s("out/run.pdr"), s("--fuel"), s("10")])
1708            .expect_err("parse should fail");
1709        assert!(err.contains("view-record mode"));
1710    }
1711
1712    #[test]
1713    fn parse_cli_record_rejects_debug() {
1714        let err = parse_cli_args(&[s("--record"), s("run.pdr"), s("--debug")])
1715            .expect_err("parse should fail");
1716        assert!(err.contains("record mode"));
1717    }
1718
1719    #[test]
1720    fn parse_cli_repl_flag() {
1721        let cfg = parse_cli_args(&[s("--repl")]).expect("parse should succeed");
1722        assert!(cfg.repl);
1723    }
1724
1725    #[test]
1726    fn parse_cli_fmt_command() {
1727        let cfg =
1728            parse_cli_args(&[s("fmt"), s("examples/example.rss")]).expect("parse should succeed");
1729        assert!(cfg.fmt);
1730        assert!(!cfg.fmt_check);
1731        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1732    }
1733
1734    #[test]
1735    fn parse_cli_fmt_check_flag() {
1736        let cfg = parse_cli_args(&[s("fmt"), s("--check"), s("examples/example.rss")])
1737            .expect("parse should succeed");
1738        assert!(cfg.fmt);
1739        assert!(cfg.fmt_check);
1740        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1741    }
1742
1743    #[test]
1744    fn parse_cli_fmt_requires_source_path() {
1745        let err = parse_cli_args(&[s("fmt")]).expect_err("parse should fail");
1746        assert!(err.contains("requires a source path"));
1747    }
1748
1749    #[test]
1750    fn parse_cli_check_requires_fmt() {
1751        let err = parse_cli_args(&[s("--check"), s("examples/example.rss")])
1752            .expect_err("parse should fail");
1753        assert!(err.contains("requires fmt mode"));
1754    }
1755
1756    #[test]
1757    fn parse_cli_fmt_rejects_debug_flag() {
1758        let err = parse_cli_args(&[s("fmt"), s("--debug"), s("examples/example.rss")])
1759            .expect_err("parse should fail");
1760        assert!(err.contains("fmt mode"));
1761    }
1762
1763    #[test]
1764    fn parse_cli_repl_legacy_command() {
1765        let cfg = parse_cli_args(&[s("repl")]).expect("parse should succeed");
1766        assert!(cfg.repl);
1767    }
1768
1769    #[test]
1770    fn parse_cli_repl_rejects_source_path() {
1771        let err = parse_cli_args(&[s("--repl"), s("examples/example.rss")])
1772            .expect_err("parse should fail");
1773        assert!(err.contains("does not accept a source path"));
1774    }
1775
1776    #[test]
1777    fn parse_cli_repl_rejects_emit_vmbc() {
1778        let err = parse_cli_args(&[s("--repl"), s("--emit-vmbc"), s("out.vmbc")])
1779            .expect_err("parse should fail");
1780        assert!(err.contains("cannot be combined"));
1781    }
1782
1783    #[test]
1784    fn parse_cli_repl_rejects_fuel() {
1785        let err =
1786            parse_cli_args(&[s("--repl"), s("--fuel"), s("10")]).expect_err("parse should fail");
1787        assert!(err.contains("cannot be combined"));
1788    }
1789
1790    #[test]
1791    fn prepare_cli_aot_can_save_and_reload_artifact() {
1792        if !native_aot_supported() {
1793            return;
1794        }
1795
1796        let program = Program::new(
1797            vec![Value::Int(9)],
1798            vec![OpCode::Ldc as u8, 0, 0, 0, 0, OpCode::Ret as u8],
1799        );
1800        let artifact_path = unique_artifact_path();
1801
1802        let mut save_vm = Vm::new(program.clone());
1803        let save_cfg = CliConfig {
1804            aot_save_path: Some(artifact_path.display().to_string()),
1805            ..CliConfig::default()
1806        };
1807        prepare_aot_for_cli(&mut save_vm, &save_cfg).expect("aot save should succeed");
1808        assert!(save_vm.has_aot_program(), "save path should install aot");
1809
1810        let mut load_vm = Vm::new(program);
1811        let load_cfg = CliConfig {
1812            aot_load_path: Some(artifact_path.display().to_string()),
1813            ..CliConfig::default()
1814        };
1815        prepare_aot_for_cli(&mut load_vm, &load_cfg).expect("aot load should succeed");
1816        assert!(load_vm.has_aot_program(), "load path should install aot");
1817        let status = load_vm.run().expect("loaded aot vm should run");
1818        assert_eq!(status, VmStatus::Halted);
1819        assert_eq!(load_vm.stack(), &[Value::Int(9)]);
1820
1821        std::fs::remove_file(&artifact_path).expect("artifact cleanup should succeed");
1822    }
1823
1824    #[test]
1825    fn standalone_cli_aot_load_without_source_uses_embedded_program() {
1826        if !native_aot_supported() {
1827            return;
1828        }
1829
1830        let program = Program::new(
1831            vec![Value::Int(9)],
1832            vec![OpCode::Ldc as u8, 0, 0, 0, 0, OpCode::Ret as u8],
1833        )
1834        .with_local_count(5);
1835        let artifact_path = unique_artifact_path();
1836
1837        let mut save_vm = Vm::new(program.clone());
1838        let save_cfg = CliConfig {
1839            aot_save_path: Some(artifact_path.display().to_string()),
1840            ..CliConfig::default()
1841        };
1842        prepare_aot_for_cli(&mut save_vm, &save_cfg).expect("aot save should succeed");
1843
1844        let load_cfg = CliConfig {
1845            aot_load_path: Some(artifact_path.display().to_string()),
1846            ..CliConfig::default()
1847        };
1848        let mut loaded_vm = try_new_cli_vm_from_standalone_aot(&load_cfg)
1849            .expect("standalone load should succeed")
1850            .expect("standalone load should create a vm");
1851
1852        assert!(
1853            loaded_vm.has_aot_program(),
1854            "standalone load should install aot"
1855        );
1856        assert_eq!(loaded_vm.program().local_count, 5);
1857
1858        let status = loaded_vm.run().expect("standalone aot vm should run");
1859        assert_eq!(status, VmStatus::Halted);
1860        assert_eq!(loaded_vm.stack(), &[Value::Int(9)]);
1861
1862        std::fs::remove_file(&artifact_path).expect("artifact cleanup should succeed");
1863    }
1864
1865    #[test]
1866    fn repl_compile_falls_back_to_expression_semicolon() {
1867        let compiled =
1868            super::compile_repl_snippet("1 + 2", &BTreeMap::new()).expect("compile should succeed");
1869        assert_eq!(compiled.compiled.locals, 0);
1870    }
1871
1872    #[test]
1873    fn repl_compile_uses_persisted_locals() {
1874        let mut locals = BTreeMap::new();
1875        locals.insert(
1876            "x".to_string(),
1877            super::ReplSessionLocal {
1878                value: Value::Int(41),
1879                mutable: false,
1880                schema: Some(vm::compiler::TypeSchema::Int),
1881                optional: false,
1882            },
1883        );
1884        let compiled =
1885            super::compile_repl_snippet("x + 1", &locals).expect("compile should succeed");
1886        assert!(compiled.compiled.locals >= 1);
1887    }
1888
1889    #[test]
1890    fn repl_session_persists_locals_between_entries() {
1891        let mut session = super::ReplSession::default();
1892        let _ = run_repl_snippet_and_sync(&mut session, "let x = 41;");
1893        assert_eq!(
1894            session.locals.get("x").map(|local| &local.value),
1895            Some(&Value::Int(41))
1896        );
1897
1898        let vm = run_repl_snippet_and_sync(&mut session, "x + 1");
1899        assert_eq!(vm.stack().last(), Some(&Value::Int(42)));
1900    }
1901
1902    #[test]
1903    fn repl_session_persists_mutable_locals_between_entries() {
1904        let mut session = super::ReplSession::default();
1905        let _ = run_repl_snippet_and_sync(&mut session, "let mut x = 1;");
1906        assert_eq!(
1907            session.locals.get("x").map(|local| local.mutable),
1908            Some(true)
1909        );
1910
1911        let _ = run_repl_snippet_and_sync(&mut session, "x = x + 1;");
1912        let vm = run_repl_snippet_and_sync(&mut session, "x");
1913        assert_eq!(vm.stack().last(), Some(&Value::Int(2)));
1914    }
1915
1916    #[test]
1917    fn repl_session_persists_null_between_entries() {
1918        let mut session = super::ReplSession::default();
1919        let _ = run_repl_snippet_and_sync(&mut session, "let x = null;");
1920        assert_eq!(
1921            session.locals.get("x").map(|local| &local.value),
1922            Some(&Value::Null)
1923        );
1924
1925        let vm = run_repl_snippet_and_sync(&mut session, "x");
1926        assert_eq!(vm.stack().last(), Some(&Value::Null));
1927    }
1928
1929    #[test]
1930    fn repl_session_persists_float_between_entries() {
1931        let mut session = super::ReplSession::default();
1932        let _ = run_repl_snippet_and_sync(&mut session, "let x = 1.5;");
1933        assert_eq!(
1934            session.locals.get("x").map(|local| &local.value),
1935            Some(&Value::Float(1.5))
1936        );
1937
1938        let vm = run_repl_snippet_and_sync(&mut session, "x + 0.5");
1939        assert_eq!(vm.stack().last(), Some(&Value::Float(2.0)));
1940    }
1941
1942    #[test]
1943    fn repl_compile_remaps_parse_error_line_numbers() {
1944        let mut locals = BTreeMap::new();
1945        locals.insert(
1946            "x".to_string(),
1947            super::ReplSessionLocal {
1948                value: Value::Int(1),
1949                mutable: false,
1950                schema: Some(vm::compiler::TypeSchema::Int),
1951                optional: false,
1952            },
1953        );
1954        match super::compile_repl_snippet("let y = ;", &locals) {
1955            Err(vm::SourceError::Parse(parse)) => assert_eq!(parse.line, 1),
1956            Err(other) => panic!("expected parse error, got {other}"),
1957            Ok(_) => panic!("expected parse error, got successful compile"),
1958        }
1959    }
1960
1961    #[test]
1962    fn repl_input_complete_for_balanced_match_block() {
1963        let input = "let b = match a {\n    Some(String) => 2,\n    _ => 3,\n};";
1964        assert!(super::is_repl_input_complete(input));
1965    }
1966
1967    #[test]
1968    fn repl_input_incomplete_for_open_brace() {
1969        assert!(!super::is_repl_input_complete("let b = match a {"));
1970    }
1971
1972    #[test]
1973    fn repl_input_incomplete_for_unclosed_string() {
1974        assert!(!super::is_repl_input_complete("let s = \"hello"));
1975    }
1976
1977    #[test]
1978    fn repl_input_incomplete_for_unclosed_block_comment() {
1979        assert!(!super::is_repl_input_complete("let a = 1; /* comment"));
1980    }
1981
1982    #[test]
1983    fn repl_input_ignores_comment_delimiters() {
1984        assert!(super::is_repl_input_complete("// {\nlet a = 1;"));
1985    }
1986
1987    #[test]
1988    fn repl_input_incomplete_for_trailing_operator() {
1989        assert!(!super::is_repl_input_complete("let a = 1 +"));
1990    }
1991}