Skip to main content

vm/
cli.rs

1use std::collections::{BTreeMap, BTreeSet};
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    OpCode, Program, ReplLocalBinding, SourceFlavor, SourceMap, SourcePathError, Value, Vm,
11    VmError, VmRecording, VmStatus, builtin_namespace_specs, compile_source_file_with_options,
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!("features: {}", cli_build_feature_summary());
835    println!();
836    println!("Usage:");
837    println!("  {binary_name}                  (defaults to REPL)");
838    println!("  {binary_name} --version");
839    println!("  {binary_name} [source_path]");
840    println!("  {binary_name} fmt [--check] <source_path>");
841    println!("  {binary_name} --repl");
842    println!("  {binary_name} repl");
843    println!("  {binary_name} --emit-vmbc <output.vmbc> [source_path]");
844    println!("  {binary_name} --disasm-vmbc <input.vmbc> [--show-source]");
845    println!("  {binary_name} --record <output.pdr> [source_path]");
846    println!("  {binary_name} --view-record <input.pdr>");
847    println!("  {binary_name} --debug [--stop-on-entry|--no-stop-on-entry] [source_path]");
848    println!("  {binary_name} --debug --tcp <addr> [source_path]");
849    println!(
850        "  {binary_name} [--aot|--aot-load <artifact.pat>] [--aot-save <artifact.pat>] [--aot-dump] [source_path]"
851    );
852    println!(
853        "  {binary_name} [--jit-hot-loop <n>] [--jit-dump|--dump-jit] [--jit-dump-no-code] [--emit-vmbc <output.vmbc>] [source_path]"
854    );
855    println!(
856        "  {binary_name} [--fuel <n>|--epoch-deadline <n>] [--epoch-check-interval <n>] [source_path]"
857    );
858    println!("  {binary_name} debug [--tcp <addr>] [source_path]");
859    println!();
860    println!("Options:");
861    println!("  -V, --version              Show version with git metadata");
862    println!("  -h, --help                 Show this help");
863    println!("      --check                In fmt mode, fail if formatting would change the file");
864}
865
866fn cli_build_features() -> Vec<String> {
867    let mut features = Vec::new();
868    if cfg!(feature = "cranelift-jit") {
869        features.push("cranelift-jit".to_string());
870    }
871    if cfg!(feature = "runtime") {
872        features.push("runtime".to_string());
873    }
874    if CompileSourceFileOptions::default()
875        .module_override_source("stdlib/rss/strings.rss")
876        .is_some()
877    {
878        features.push("stdlibs".to_string());
879    }
880    let modules = builtin_namespace_specs()
881        .iter()
882        .map(|spec| spec.namespace)
883        .collect::<Vec<_>>()
884        .join(", ");
885    features.push(format!("modules={modules}"));
886    features
887}
888
889fn cli_build_feature_summary() -> String {
890    cli_build_features().join(", ")
891}
892
893fn binary_version_text(binary: &str) -> String {
894    let git_tag = option_env!("PD_BUILD_GIT_TAG").unwrap_or("untagged");
895    let git_commit = option_env!("PD_BUILD_GIT_COMMIT").unwrap_or("unknown");
896    let git_dirty = option_env!("PD_BUILD_GIT_DIRTY").unwrap_or("false");
897    let dirty = matches!(git_dirty, "true" | "1" | "yes" | "dirty");
898
899    if dirty {
900        format!("{binary} {git_tag} (dirty commit: {git_commit})")
901    } else {
902        format!("{binary} {git_tag}")
903    }
904}
905
906fn run_repl() -> Result<(), Box<dyn std::error::Error>> {
907    println!("pd-vm REPL (RustScript)");
908    println!("features: {}", cli_build_feature_summary());
909    println!("history: up/down arrows, commands: .help, .quit, .cancel");
910    let mut editor = DefaultEditor::new()?;
911    let mut session = ReplSession::default();
912    let mut pending_input = String::new();
913    loop {
914        let prompt = if pending_input.is_empty() {
915            "pd-vm> "
916        } else {
917            "...> "
918        };
919        match editor.readline(prompt) {
920            Ok(line) => {
921                let trimmed = line.trim();
922                if pending_input.is_empty() {
923                    if trimmed.is_empty() {
924                        continue;
925                    }
926                    if let Some(action) = handle_repl_command(trimmed) {
927                        if action == ReplAction::Break {
928                            break;
929                        }
930                        continue;
931                    }
932                } else if trimmed == ".cancel" {
933                    pending_input.clear();
934                    println!("pending input cleared");
935                    continue;
936                }
937
938                if !pending_input.is_empty() {
939                    pending_input.push('\n');
940                }
941                pending_input.push_str(line.trim_end());
942                if !is_repl_input_complete(&pending_input) {
943                    continue;
944                }
945
946                let snippet = pending_input.trim().to_string();
947                pending_input.clear();
948                if snippet.is_empty() {
949                    continue;
950                }
951
952                let _ = editor.add_history_entry(&snippet);
953                let compiled = match compile_repl_snippet(&snippet, &session.locals) {
954                    Ok(compiled) => compiled,
955                    Err(err) => {
956                        println!("{}", render_repl_compile_error(&snippet, &err));
957                        continue;
958                    }
959                };
960                let moved_by_rebinding =
961                    repl_locals_moved_by_rebinding(&compiled.compiled.program, &session.locals);
962                let no_repl_moves = BTreeSet::new();
963                let mut vm = Vm::new_with_jit_config(
964                    compiled
965                        .compiled
966                        .program
967                        .with_local_count(compiled.compiled.locals),
968                    JitConfig::default(),
969                );
970                configure_cli_vm(&mut vm);
971                let imports = vm.program().imports.clone();
972                if let Err(err) = register_imports(&mut vm, &imports) {
973                    println!("{err}");
974                    continue;
975                }
976                if let Err(err) = seed_repl_vm_locals(&mut vm, &session.locals) {
977                    println!("{}", render_vm_error(&vm, &err));
978                    continue;
979                }
980                loop {
981                    match vm.run() {
982                        Ok(VmStatus::Halted) => {
983                            sync_repl_session(
984                                &vm,
985                                &compiled.bindings,
986                                &moved_by_rebinding,
987                                &mut session,
988                            );
989                            if let Some(value) = vm.stack().last() {
990                                println!("=> {}", format_value(value));
991                            } else {
992                                println!("=> <empty>");
993                            }
994                            break;
995                        }
996                        Ok(VmStatus::Yielded) => continue,
997                        Ok(VmStatus::Waiting(_op_id)) => {
998                            if let Err(err) = vm.wait_for_host_op_blocking() {
999                                sync_repl_session(
1000                                    &vm,
1001                                    &compiled.bindings,
1002                                    &no_repl_moves,
1003                                    &mut session,
1004                                );
1005                                println!("{}", render_vm_error(&vm, &err));
1006                                break;
1007                            }
1008                            continue;
1009                        }
1010                        Err(err) => {
1011                            sync_repl_session(
1012                                &vm,
1013                                &compiled.bindings,
1014                                &no_repl_moves,
1015                                &mut session,
1016                            );
1017                            println!("{}", render_vm_error(&vm, &err));
1018                            break;
1019                        }
1020                    }
1021                }
1022            }
1023            Err(ReadlineError::Interrupted) => {
1024                if pending_input.is_empty() {
1025                    println!("bye");
1026                    break;
1027                }
1028                pending_input.clear();
1029                println!("pending input cleared");
1030            }
1031            Err(ReadlineError::Eof) => {
1032                println!("bye");
1033                break;
1034            }
1035            Err(err) => {
1036                return Err(Box::new(io::Error::other(err.to_string())));
1037            }
1038        }
1039    }
1040    Ok(())
1041}
1042
1043#[derive(Default)]
1044struct ReplSession {
1045    locals: BTreeMap<String, ReplSessionLocal>,
1046}
1047
1048#[derive(Clone, Debug, PartialEq)]
1049struct ReplSessionLocal {
1050    value: Value,
1051    mutable: bool,
1052    schema: Option<crate::compiler::TypeSchema>,
1053    optional: bool,
1054    moved: bool,
1055}
1056
1057fn repl_locals_moved_by_rebinding(
1058    program: &Program,
1059    locals: &BTreeMap<String, ReplSessionLocal>,
1060) -> BTreeSet<String> {
1061    let Some(debug) = program.debug.as_ref() else {
1062        return BTreeSet::new();
1063    };
1064    let persisted_by_slot = locals
1065        .keys()
1066        .filter_map(|name| debug.local_index(name).map(|slot| (slot, name.clone())))
1067        .collect::<BTreeMap<_, _>>();
1068    let mut moved = BTreeSet::new();
1069    let mut ip = 0;
1070
1071    while ip < program.code.len() {
1072        let Ok(opcode) = OpCode::try_from(program.code[ip]) else {
1073            break;
1074        };
1075        if opcode == OpCode::Ldloc
1076            && let (Some(source), Some(OpCode::Stloc), Some(target)) = (
1077                program.code.get(ip + 1).copied(),
1078                program
1079                    .code
1080                    .get(ip + 2)
1081                    .copied()
1082                    .and_then(|byte| OpCode::try_from(byte).ok()),
1083                program.code.get(ip + 3).copied(),
1084            )
1085            && source != target
1086            && let Some(name) = persisted_by_slot.get(&source)
1087        {
1088            moved.insert(name.clone());
1089        }
1090        if opcode == OpCode::Stloc
1091            && let Some(target) = program.code.get(ip + 1).copied()
1092            && let Some(name) = persisted_by_slot.get(&target)
1093        {
1094            moved.remove(name);
1095        }
1096        ip += 1 + opcode.operand_len();
1097    }
1098    moved
1099}
1100
1101fn sync_repl_session(
1102    vm: &Vm,
1103    bindings: &[ReplLocalBinding],
1104    moved_by_rebinding: &BTreeSet<String>,
1105    session: &mut ReplSession,
1106) {
1107    if bindings.is_empty() {
1108        session.locals.clear();
1109        return;
1110    }
1111    let Some(debug) = vm.debug_info() else {
1112        session.locals.clear();
1113        return;
1114    };
1115    let mut next = BTreeMap::new();
1116    for binding in bindings {
1117        let Some(index) = debug.local_index(&binding.name) else {
1118            continue;
1119        };
1120        let Some(value) = vm.locals().get(index as usize) else {
1121            continue;
1122        };
1123        let (schema, optional) = repl_local_schema_from_vm(vm, index as usize, value);
1124        let moved = moved_by_rebinding.contains(&binding.name)
1125            || (!optional
1126                && value == &Value::Null
1127                && matches!(
1128                    schema,
1129                    Some(vm::compiler::TypeSchema::String | vm::compiler::TypeSchema::Bytes)
1130                ));
1131        next.insert(
1132            binding.name.clone(),
1133            ReplSessionLocal {
1134                value: value.clone(),
1135                mutable: binding.mutable,
1136                schema,
1137                optional,
1138                moved,
1139            },
1140        );
1141    }
1142    session.locals = next;
1143}
1144
1145#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1146enum ReplAction {
1147    Continue,
1148    Break,
1149}
1150
1151fn handle_repl_command(line: &str) -> Option<ReplAction> {
1152    match line {
1153        ".quit" | ".exit" => Some(ReplAction::Break),
1154        ".cancel" => {
1155            println!("no pending input");
1156            Some(ReplAction::Continue)
1157        }
1158        ".help" => {
1159            println!("commands:");
1160            println!("  .help      show commands");
1161            println!("  .quit      quit repl");
1162            println!("  .exit      quit repl");
1163            println!("  .cancel    clear pending multiline input");
1164            Some(ReplAction::Continue)
1165        }
1166        _ if line.starts_with('.') => {
1167            println!("unknown command: {line}");
1168            Some(ReplAction::Continue)
1169        }
1170        _ => None,
1171    }
1172}
1173
1174fn compile_repl_snippet(
1175    input: &str,
1176    locals: &BTreeMap<String, ReplSessionLocal>,
1177) -> Result<vm::CompiledReplProgram, vm::SourceError> {
1178    let trimmed = input.trim_end();
1179    let bindings = locals
1180        .iter()
1181        .map(|(name, local)| vm::compiler::ReplLocalState {
1182            binding: ReplLocalBinding {
1183                name: name.clone(),
1184                mutable: local.mutable,
1185                schema: local.schema.clone(),
1186                optional: local.optional,
1187            },
1188            moved: local.moved,
1189        })
1190        .collect::<Vec<_>>();
1191    match vm::compiler::compile_source_for_repl_with_state(trimmed, &bindings) {
1192        Ok(compiled) => Ok(compiled),
1193        Err(first_err) => {
1194            if trimmed.ends_with(';') {
1195                return Err(first_err);
1196            }
1197            let fallback = format!("{trimmed};");
1198            match vm::compiler::compile_source_for_repl_with_state(&fallback, &bindings) {
1199                Ok(compiled) => Ok(compiled),
1200                Err(err @ vm::SourceError::Parse(vm::ParseError { code: Some(_), .. })) => Err(err),
1201                Err(err @ vm::SourceError::Compile(_)) => Err(err),
1202                Err(_) => Err(first_err),
1203            }
1204        }
1205    }
1206}
1207
1208fn seed_repl_vm_locals(
1209    vm: &mut Vm,
1210    locals: &BTreeMap<String, ReplSessionLocal>,
1211) -> Result<(), VmError> {
1212    if locals.is_empty() {
1213        return Ok(());
1214    }
1215    for (name, local) in locals {
1216        let index = {
1217            let Some(debug) = vm.debug_info() else {
1218                return Err(VmError::HostError(
1219                    "repl debug info unavailable while restoring locals".to_string(),
1220                ));
1221            };
1222            debug.local_index(name).ok_or_else(|| {
1223                VmError::HostError(format!("repl local '{name}' missing from compiled snippet"))
1224            })?
1225        };
1226        vm.set_local(index, local.value.clone())?;
1227    }
1228    Ok(())
1229}
1230
1231fn repl_local_schema_from_vm(
1232    vm: &Vm,
1233    index: usize,
1234    value: &Value,
1235) -> (Option<vm::compiler::TypeSchema>, bool) {
1236    let fallback = repl_schema_from_value(value);
1237    let Some(type_map) = vm.program().type_map.as_ref() else {
1238        return (fallback, false);
1239    };
1240    let schema = type_map
1241        .local_schemas
1242        .get(index)
1243        .cloned()
1244        .flatten()
1245        .or_else(|| {
1246            type_map
1247                .local_types
1248                .get(index)
1249                .copied()
1250                .and_then(repl_schema_from_value_type)
1251        })
1252        .or(fallback);
1253    let optional = type_map.optional_slots.get(index).copied().unwrap_or(false);
1254    (schema, optional)
1255}
1256
1257fn repl_schema_from_value(value: &Value) -> Option<vm::compiler::TypeSchema> {
1258    use vm::compiler::TypeSchema;
1259
1260    match value {
1261        Value::Null => Some(TypeSchema::Null),
1262        Value::Int(_) => Some(TypeSchema::Int),
1263        Value::Float(_) => Some(TypeSchema::Float),
1264        Value::Bool(_) => Some(TypeSchema::Bool),
1265        Value::String(_) => Some(TypeSchema::String),
1266        Value::Bytes(_) => Some(TypeSchema::Bytes),
1267        Value::Array(_) => Some(TypeSchema::Array(Box::new(TypeSchema::Unknown))),
1268        Value::Map(_) => Some(TypeSchema::Map(Box::new(TypeSchema::Unknown))),
1269    }
1270}
1271
1272fn repl_schema_from_value_type(value_type: vm::ValueType) -> Option<vm::compiler::TypeSchema> {
1273    use vm::compiler::TypeSchema;
1274
1275    match value_type {
1276        vm::ValueType::Unknown => None,
1277        vm::ValueType::Null => Some(TypeSchema::Null),
1278        vm::ValueType::Int => Some(TypeSchema::Int),
1279        vm::ValueType::Float => Some(TypeSchema::Float),
1280        vm::ValueType::Bool => Some(TypeSchema::Bool),
1281        vm::ValueType::String => Some(TypeSchema::String),
1282        vm::ValueType::Bytes => Some(TypeSchema::Bytes),
1283        vm::ValueType::Array => Some(TypeSchema::Array(Box::new(TypeSchema::Unknown))),
1284        vm::ValueType::Map => Some(TypeSchema::Map(Box::new(TypeSchema::Unknown))),
1285    }
1286}
1287
1288fn is_repl_input_complete(input: &str) -> bool {
1289    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1290    enum Delimiter {
1291        Paren,
1292        Bracket,
1293        Brace,
1294    }
1295
1296    let mut stack: Vec<Delimiter> = Vec::new();
1297    let mut chars = input.chars().peekable();
1298    let mut in_string = false;
1299    let mut escaped = false;
1300    let mut in_line_comment = false;
1301    let mut in_block_comment = false;
1302    let mut code = String::with_capacity(input.len());
1303
1304    while let Some(ch) = chars.next() {
1305        if in_line_comment {
1306            if ch == '\n' {
1307                in_line_comment = false;
1308                code.push('\n');
1309            }
1310            continue;
1311        }
1312        if in_block_comment {
1313            if ch == '*'
1314                && let Some('/') = chars.peek()
1315            {
1316                chars.next();
1317                in_block_comment = false;
1318            }
1319            continue;
1320        }
1321        if in_string {
1322            if escaped {
1323                escaped = false;
1324                continue;
1325            }
1326            match ch {
1327                '\\' => escaped = true,
1328                '"' => {
1329                    in_string = false;
1330                    code.push('"');
1331                }
1332                _ => {}
1333            }
1334            continue;
1335        }
1336
1337        if ch == '/' {
1338            match chars.peek().copied() {
1339                Some('/') => {
1340                    chars.next();
1341                    in_line_comment = true;
1342                    continue;
1343                }
1344                Some('*') => {
1345                    chars.next();
1346                    in_block_comment = true;
1347                    continue;
1348                }
1349                _ => {}
1350            }
1351        }
1352
1353        match ch {
1354            '"' => {
1355                in_string = true;
1356                code.push('"');
1357            }
1358            '(' => {
1359                stack.push(Delimiter::Paren);
1360                code.push(ch);
1361            }
1362            '[' => {
1363                stack.push(Delimiter::Bracket);
1364                code.push(ch);
1365            }
1366            '{' => {
1367                stack.push(Delimiter::Brace);
1368                code.push(ch);
1369            }
1370            ')' => {
1371                if stack.pop() != Some(Delimiter::Paren) {
1372                    return true;
1373                }
1374                code.push(ch);
1375            }
1376            ']' => {
1377                if stack.pop() != Some(Delimiter::Bracket) {
1378                    return true;
1379                }
1380                code.push(ch);
1381            }
1382            '}' => {
1383                if stack.pop() != Some(Delimiter::Brace) {
1384                    return true;
1385                }
1386                code.push(ch);
1387            }
1388            _ => code.push(ch),
1389        }
1390    }
1391
1392    if in_string || in_block_comment || !stack.is_empty() {
1393        return false;
1394    }
1395
1396    let trimmed = code.trim_end();
1397    if trimmed.is_empty() {
1398        return true;
1399    }
1400
1401    const TRAILING_INCOMPLETE_TOKENS: [&str; 18] = [
1402        "=>", "::", "&&", "||", "<=", ">=", "==", "!=", "=", ",", ".", "+", "-", "*", "/", "%",
1403        "!", ":",
1404    ];
1405    !TRAILING_INCOMPLETE_TOKENS
1406        .iter()
1407        .any(|token| trimmed.ends_with(token))
1408}
1409
1410fn render_repl_compile_error(snippet: &str, err: &vm::SourceError) -> String {
1411    match err {
1412        vm::SourceError::Parse(parse) => {
1413            let mut source_map = SourceMap::new();
1414            let source_id = source_map.add_source("<repl>", snippet.to_string());
1415            let parse = parse
1416                .clone()
1417                .with_line_span_from_source(&source_map, source_id);
1418            render_source_error(&source_map, &parse, true)
1419        }
1420        _ => err.to_string(),
1421    }
1422}
1423
1424fn add_one_host_function(_vm: &mut Vm, args: &[Value]) -> Result<CallOutcome, VmError> {
1425    let value = match args.first() {
1426        Some(Value::Int(value)) => *value,
1427        _ => return Err(VmError::TypeMismatch("int")),
1428    };
1429    Ok(CallOutcome::Return(CallReturn::one(Value::Int(value + 1))))
1430}
1431
1432fn echo_host_function(_vm: &mut Vm, args: &[Value]) -> Result<CallOutcome, VmError> {
1433    let value = args.first().cloned().ok_or(VmError::StackUnderflow)?;
1434    Ok(CallOutcome::Return(CallReturn::one(value)))
1435}
1436
1437fn format_value(value: &Value) -> String {
1438    match value {
1439        Value::Null => "null".to_string(),
1440        Value::Int(value) => value.to_string(),
1441        Value::Float(value) => value.to_string(),
1442        Value::Bool(value) => value.to_string(),
1443        Value::String(value) => value.as_str().to_string(),
1444        Value::Bytes(value) => format_bytes(value.as_ref()),
1445        Value::Array(values) => {
1446            let parts = values
1447                .iter()
1448                .map(format_value)
1449                .collect::<Vec<_>>()
1450                .join(", ");
1451            format!("[{parts}]")
1452        }
1453        Value::Map(entries) => {
1454            let parts = entries
1455                .iter()
1456                .map(|(key, value)| format!("{}: {}", format_value(key), format_value(value)))
1457                .collect::<Vec<_>>()
1458                .join(", ");
1459            format!("{{{parts}}}")
1460        }
1461    }
1462}
1463
1464fn format_bytes(bytes: &[u8]) -> String {
1465    let preview_len = bytes.len().min(16);
1466    let mut preview = String::with_capacity(preview_len * 2);
1467    for byte in &bytes[..preview_len] {
1468        preview.push(hex_nibble(byte >> 4));
1469        preview.push(hex_nibble(byte & 0x0F));
1470    }
1471    if bytes.len() > preview_len {
1472        format!("bytes[len={} hex={}..]", bytes.len(), preview)
1473    } else {
1474        format!("bytes[len={} hex={}]", bytes.len(), preview)
1475    }
1476}
1477
1478fn hex_nibble(value: u8) -> char {
1479    match value {
1480        0..=9 => char::from(b'0' + value),
1481        10..=15 => char::from(b'a' + (value - 10)),
1482        _ => unreachable!("hex nibble out of range"),
1483    }
1484}
1485
1486#[cfg(test)]
1487mod tests {
1488    use crate as vm;
1489    use std::collections::BTreeMap;
1490    use std::time::{SystemTime, UNIX_EPOCH};
1491
1492    use super::{
1493        CliConfig, parse_cli_args, prepare_aot_for_cli, register_imports,
1494        try_new_cli_vm_from_standalone_aot,
1495    };
1496    use vm::{
1497        CompileSourceFileOptions, HostImport, OpCode, Program, Value, ValueType, Vm, VmStatus,
1498    };
1499
1500    fn s(value: &str) -> String {
1501        value.to_string()
1502    }
1503
1504    #[test]
1505    fn cli_build_features_report_compiled_capabilities() {
1506        let features = super::cli_build_features();
1507
1508        assert_eq!(
1509            features,
1510            vec![
1511                cfg!(feature = "cranelift-jit").then_some("cranelift-jit".to_string()),
1512                cfg!(feature = "runtime").then_some("runtime".to_string()),
1513                CompileSourceFileOptions::default()
1514                    .module_override_source("stdlib/rss/strings.rss")
1515                    .is_some()
1516                    .then_some("stdlibs".to_string()),
1517                Some("modules=bytes, io, re, json, jit, math".to_string()),
1518            ]
1519            .into_iter()
1520            .flatten()
1521            .collect::<Vec<_>>()
1522        );
1523        assert!(!super::cli_build_feature_summary().contains("enabled"));
1524    }
1525
1526    fn native_aot_supported() -> bool {
1527        (cfg!(target_arch = "x86_64")
1528            && (cfg!(target_os = "windows") || (cfg!(unix) && !cfg!(target_os = "macos"))))
1529            || (cfg!(target_arch = "aarch64")
1530                && (cfg!(target_os = "linux") || cfg!(target_os = "macos")))
1531    }
1532
1533    fn unique_artifact_path() -> std::path::PathBuf {
1534        let mut path = std::env::temp_dir();
1535        let stamp = SystemTime::now()
1536            .duration_since(UNIX_EPOCH)
1537            .expect("system clock should be after unix epoch")
1538            .as_nanos();
1539        path.push(format!("pd-vm-run-aot-{}-{stamp}.pat", std::process::id()));
1540        path
1541    }
1542
1543    fn run_repl_snippet_and_sync(session: &mut super::ReplSession, snippet: &str) -> Vm {
1544        let compiled =
1545            super::compile_repl_snippet(snippet, &session.locals).expect("compile should succeed");
1546        let moved_by_rebinding =
1547            super::repl_locals_moved_by_rebinding(&compiled.compiled.program, &session.locals);
1548        let mut vm = Vm::new(
1549            compiled
1550                .compiled
1551                .program
1552                .with_local_count(compiled.compiled.locals),
1553        );
1554        super::configure_cli_vm(&mut vm);
1555        let imports = vm.program().imports.clone();
1556        super::register_imports(&mut vm, &imports).expect("register should succeed");
1557        super::seed_repl_vm_locals(&mut vm, &session.locals).expect("locals should restore");
1558        loop {
1559            match vm.run().expect("snippet should run") {
1560                VmStatus::Halted => break,
1561                VmStatus::Yielded => continue,
1562                VmStatus::Waiting(_) => vm
1563                    .wait_for_host_op_blocking()
1564                    .expect("snippet should not block"),
1565            }
1566        }
1567        super::sync_repl_session(&vm, &compiled.bindings, &moved_by_rebinding, session);
1568        vm
1569    }
1570
1571    #[test]
1572    fn register_imports_binds_cached_cli_host_registry_plan() {
1573        let imports = vec![
1574            HostImport {
1575                name: "print".to_string(),
1576                arity: 1,
1577                return_type: ValueType::Unknown,
1578            },
1579            HostImport {
1580                name: "echo".to_string(),
1581                arity: 1,
1582                return_type: ValueType::Unknown,
1583            },
1584        ];
1585        let program =
1586            Program::with_imports_and_debug(vec![], vec![OpCode::Ret as u8], imports.clone(), None);
1587
1588        let mut first = Vm::new(program.clone());
1589        register_imports(&mut first, &imports).expect("first vm should bind imports");
1590        assert_eq!(first.bound_function_count(), 2);
1591
1592        let mut second = Vm::new(program);
1593        register_imports(&mut second, &imports).expect("second vm should reuse cached plan");
1594        assert_eq!(second.bound_function_count(), 2);
1595    }
1596
1597    #[test]
1598    fn parse_cli_defaults() {
1599        let cfg = parse_cli_args(&[]).expect("parse should succeed");
1600        assert!(cfg.repl);
1601        assert!(!cfg.debug);
1602        assert!(!cfg.version);
1603        assert!(cfg.tcp_addr.is_none());
1604        assert!(cfg.stop_on_entry);
1605        assert!(!cfg.aot);
1606        assert!(!cfg.aot_dump);
1607        assert!(cfg.aot_save_path.is_none());
1608        assert!(cfg.aot_load_path.is_none());
1609        assert!(!cfg.jit_dump);
1610        assert!(cfg.jit_dump_show_machine_code);
1611        assert!(cfg.jit_hot_loop_threshold.is_none());
1612        assert!(cfg.fuel.is_none());
1613        assert!(cfg.epoch_deadline.is_none());
1614        assert!(cfg.source.is_none());
1615        assert!(cfg.epoch_check_interval.is_none());
1616        assert!(cfg.emit_vmbc_path.is_none());
1617        assert!(cfg.disasm_vmbc_path.is_none());
1618        assert!(!cfg.show_source);
1619        assert!(!cfg.fmt);
1620        assert!(!cfg.fmt_check);
1621    }
1622
1623    #[test]
1624    fn parse_cli_version_flag() {
1625        let cfg = parse_cli_args(&[s("--version")]).expect("parse should succeed");
1626        assert!(cfg.version);
1627        assert!(!cfg.repl);
1628    }
1629
1630    #[test]
1631    fn parse_cli_version_short_flag() {
1632        let cfg = parse_cli_args(&[s("-V")]).expect("parse should succeed");
1633        assert!(cfg.version);
1634        assert!(!cfg.repl);
1635    }
1636
1637    #[test]
1638    fn parse_cli_debug_with_source_and_tcp() {
1639        let cfg = parse_cli_args(&[
1640            s("--debug"),
1641            s("--tcp"),
1642            s("127.0.0.1:9002"),
1643            s("examples/example.lua"),
1644        ])
1645        .expect("parse should succeed");
1646        assert!(cfg.debug);
1647        assert_eq!(cfg.tcp_addr.as_deref(), Some("127.0.0.1:9002"));
1648        assert_eq!(cfg.source.as_deref(), Some("examples/example.lua"));
1649    }
1650
1651    #[test]
1652    fn parse_cli_legacy_debug_command() {
1653        let cfg =
1654            parse_cli_args(&[s("debug"), s("examples/example.rss")]).expect("parse should succeed");
1655        assert!(cfg.debug);
1656        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1657    }
1658
1659    #[test]
1660    fn parse_cli_rejects_multiple_sources() {
1661        let err = parse_cli_args(&[s("a.rss"), s("b.rss")]).expect_err("parse should fail");
1662        assert!(err.contains("multiple source paths"));
1663    }
1664
1665    #[test]
1666    fn parse_cli_jit_flags() {
1667        let cfg = parse_cli_args(&[
1668            s("--jit-hot-loop"),
1669            s("2"),
1670            s("--jit-dump"),
1671            s("--jit-dump-no-code"),
1672            s("examples/example.rss"),
1673        ])
1674        .expect("parse should succeed");
1675        assert_eq!(cfg.jit_hot_loop_threshold, Some(2));
1676        assert!(cfg.jit_dump);
1677        assert!(!cfg.jit_dump_show_machine_code);
1678        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1679    }
1680
1681    #[test]
1682    fn parse_cli_aot_flags() {
1683        let cfg = parse_cli_args(&[
1684            s("--aot"),
1685            s("--aot-dump"),
1686            s("--aot-save"),
1687            s("out/program.pat"),
1688            s("examples/example.rss"),
1689        ])
1690        .expect("parse should succeed");
1691        assert!(cfg.aot);
1692        assert!(cfg.aot_dump);
1693        assert_eq!(cfg.aot_save_path.as_deref(), Some("out/program.pat"));
1694        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1695    }
1696
1697    #[test]
1698    fn parse_cli_aot_load_without_source_path() {
1699        let cfg =
1700            parse_cli_args(&[s("--aot-load"), s("out/program.pat")]).expect("parse should succeed");
1701        assert_eq!(cfg.aot_load_path.as_deref(), Some("out/program.pat"));
1702        assert!(cfg.source.is_none());
1703    }
1704
1705    #[test]
1706    fn parse_cli_rejects_aot_and_load_together() {
1707        let err = parse_cli_args(&[
1708            s("--aot"),
1709            s("--aot-load"),
1710            s("out/program.pat"),
1711            s("examples/example.rss"),
1712        ])
1713        .expect_err("parse should fail");
1714        assert!(err.contains("mutually exclusive"));
1715    }
1716
1717    #[test]
1718    fn parse_cli_debug_rejects_aot_runtime_flags() {
1719        let err = parse_cli_args(&[s("--debug"), s("--aot"), s("examples/example.rss")])
1720            .expect_err("parse should fail");
1721        assert!(err.contains("debug mode"));
1722    }
1723
1724    #[test]
1725    fn parse_cli_dump_jit_alias() {
1726        let cfg = parse_cli_args(&[s("--dump-jit"), s("examples/example.rss")])
1727            .expect("parse should succeed");
1728        assert!(cfg.jit_dump);
1729        assert!(cfg.jit_dump_show_machine_code);
1730        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1731    }
1732
1733    #[test]
1734    fn parse_cli_jit_dump_no_code_requires_dump_flag() {
1735        let err = parse_cli_args(&[s("--jit-dump-no-code"), s("examples/example.rss")])
1736            .expect_err("parse should fail");
1737        assert!(err.contains("requires --jit-dump or --dump-jit"));
1738    }
1739
1740    #[test]
1741    fn parse_cli_fuel_flag() {
1742        let cfg = parse_cli_args(&[s("--fuel"), s("123"), s("examples/example.rss")])
1743            .expect("parse should succeed");
1744        assert_eq!(cfg.fuel, Some(123));
1745        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1746    }
1747
1748    #[test]
1749    fn parse_cli_fuel_requires_value() {
1750        let err = parse_cli_args(&[s("--fuel")]).expect_err("parse should fail");
1751        assert!(err.contains("missing value for --fuel"));
1752    }
1753
1754    #[test]
1755    fn parse_cli_epoch_deadline_flag() {
1756        let cfg = parse_cli_args(&[s("--epoch-deadline"), s("3"), s("examples/example.rss")])
1757            .expect("parse should succeed");
1758        assert_eq!(cfg.epoch_deadline, Some(3));
1759        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1760    }
1761
1762    #[test]
1763    fn parse_cli_rejects_fuel_and_epoch_deadline_together() {
1764        let err = parse_cli_args(&[
1765            s("--fuel"),
1766            s("10"),
1767            s("--epoch-deadline"),
1768            s("3"),
1769            s("examples/example.rss"),
1770        ])
1771        .expect_err("parse should fail");
1772        assert!(err.contains("mutually exclusive"));
1773    }
1774
1775    #[test]
1776    fn parse_cli_emit_vmbc_path() {
1777        let cfg = parse_cli_args(&[
1778            s("--emit-vmbc"),
1779            s("out/program.vmbc"),
1780            s("examples/example.rss"),
1781        ])
1782        .expect("parse should succeed");
1783        assert_eq!(cfg.emit_vmbc_path.as_deref(), Some("out/program.vmbc"));
1784        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1785    }
1786
1787    #[test]
1788    fn parse_cli_emit_vmbc_requires_path() {
1789        let err = parse_cli_args(&[s("--emit-vmbc")]).expect_err("parse should fail");
1790        assert!(err.contains("missing value for --emit-vmbc"));
1791    }
1792
1793    #[test]
1794    fn parse_cli_disasm_vmbc_path() {
1795        let cfg = parse_cli_args(&[
1796            s("--disasm-vmbc"),
1797            s("out/program.vmbc"),
1798            s("--show-source"),
1799        ])
1800        .expect("parse should succeed");
1801        assert_eq!(cfg.disasm_vmbc_path.as_deref(), Some("out/program.vmbc"));
1802        assert!(cfg.show_source);
1803    }
1804
1805    #[test]
1806    fn parse_cli_disasm_requires_path() {
1807        let err = parse_cli_args(&[s("--disasm-vmbc")]).expect_err("parse should fail");
1808        assert!(err.contains("missing value for --disasm-vmbc"));
1809    }
1810
1811    #[test]
1812    fn parse_cli_show_source_requires_disasm() {
1813        let err = parse_cli_args(&[s("--show-source")]).expect_err("parse should fail");
1814        assert!(err.contains("requires --disasm-vmbc"));
1815    }
1816
1817    #[test]
1818    fn parse_cli_disasm_rejects_source_path() {
1819        let err = parse_cli_args(&[
1820            s("--disasm-vmbc"),
1821            s("program.vmbc"),
1822            s("examples/example.rss"),
1823        ])
1824        .expect_err("parse should fail");
1825        assert!(err.contains("does not accept a source path"));
1826    }
1827
1828    #[test]
1829    fn parse_cli_record_path() {
1830        let cfg = parse_cli_args(&[s("--record"), s("out/run.pdr"), s("examples/example.rss")])
1831            .expect("parse should succeed");
1832        assert_eq!(cfg.record_path.as_deref(), Some("out/run.pdr"));
1833        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1834    }
1835
1836    #[test]
1837    fn parse_cli_view_record_path() {
1838        let cfg =
1839            parse_cli_args(&[s("--view-record"), s("out/run.pdr")]).expect("parse should succeed");
1840        assert_eq!(cfg.view_recording_path.as_deref(), Some("out/run.pdr"));
1841        assert!(cfg.source.is_none());
1842    }
1843
1844    #[test]
1845    fn parse_cli_view_record_rejects_fuel() {
1846        let err = parse_cli_args(&[s("--view-record"), s("out/run.pdr"), s("--fuel"), s("10")])
1847            .expect_err("parse should fail");
1848        assert!(err.contains("view-record mode"));
1849    }
1850
1851    #[test]
1852    fn parse_cli_record_rejects_debug() {
1853        let err = parse_cli_args(&[s("--record"), s("run.pdr"), s("--debug")])
1854            .expect_err("parse should fail");
1855        assert!(err.contains("record mode"));
1856    }
1857
1858    #[test]
1859    fn parse_cli_repl_flag() {
1860        let cfg = parse_cli_args(&[s("--repl")]).expect("parse should succeed");
1861        assert!(cfg.repl);
1862    }
1863
1864    #[test]
1865    fn parse_cli_fmt_command() {
1866        let cfg =
1867            parse_cli_args(&[s("fmt"), s("examples/example.rss")]).expect("parse should succeed");
1868        assert!(cfg.fmt);
1869        assert!(!cfg.fmt_check);
1870        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1871    }
1872
1873    #[test]
1874    fn parse_cli_fmt_check_flag() {
1875        let cfg = parse_cli_args(&[s("fmt"), s("--check"), s("examples/example.rss")])
1876            .expect("parse should succeed");
1877        assert!(cfg.fmt);
1878        assert!(cfg.fmt_check);
1879        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1880    }
1881
1882    #[test]
1883    fn parse_cli_fmt_requires_source_path() {
1884        let err = parse_cli_args(&[s("fmt")]).expect_err("parse should fail");
1885        assert!(err.contains("requires a source path"));
1886    }
1887
1888    #[test]
1889    fn parse_cli_check_requires_fmt() {
1890        let err = parse_cli_args(&[s("--check"), s("examples/example.rss")])
1891            .expect_err("parse should fail");
1892        assert!(err.contains("requires fmt mode"));
1893    }
1894
1895    #[test]
1896    fn parse_cli_fmt_rejects_debug_flag() {
1897        let err = parse_cli_args(&[s("fmt"), s("--debug"), s("examples/example.rss")])
1898            .expect_err("parse should fail");
1899        assert!(err.contains("fmt mode"));
1900    }
1901
1902    #[test]
1903    fn parse_cli_repl_legacy_command() {
1904        let cfg = parse_cli_args(&[s("repl")]).expect("parse should succeed");
1905        assert!(cfg.repl);
1906    }
1907
1908    #[test]
1909    fn parse_cli_repl_rejects_source_path() {
1910        let err = parse_cli_args(&[s("--repl"), s("examples/example.rss")])
1911            .expect_err("parse should fail");
1912        assert!(err.contains("does not accept a source path"));
1913    }
1914
1915    #[test]
1916    fn parse_cli_repl_rejects_emit_vmbc() {
1917        let err = parse_cli_args(&[s("--repl"), s("--emit-vmbc"), s("out.vmbc")])
1918            .expect_err("parse should fail");
1919        assert!(err.contains("cannot be combined"));
1920    }
1921
1922    #[test]
1923    fn parse_cli_repl_rejects_fuel() {
1924        let err =
1925            parse_cli_args(&[s("--repl"), s("--fuel"), s("10")]).expect_err("parse should fail");
1926        assert!(err.contains("cannot be combined"));
1927    }
1928
1929    #[test]
1930    fn prepare_cli_aot_can_save_and_reload_artifact() {
1931        if !native_aot_supported() {
1932            return;
1933        }
1934
1935        let program = Program::new(
1936            vec![Value::Int(9)],
1937            vec![OpCode::Ldc as u8, 0, 0, 0, 0, OpCode::Ret as u8],
1938        );
1939        let artifact_path = unique_artifact_path();
1940
1941        let mut save_vm = Vm::new(program.clone());
1942        let save_cfg = CliConfig {
1943            aot_save_path: Some(artifact_path.display().to_string()),
1944            ..CliConfig::default()
1945        };
1946        prepare_aot_for_cli(&mut save_vm, &save_cfg).expect("aot save should succeed");
1947        assert!(save_vm.has_aot_program(), "save path should install aot");
1948
1949        let mut load_vm = Vm::new(program);
1950        let load_cfg = CliConfig {
1951            aot_load_path: Some(artifact_path.display().to_string()),
1952            ..CliConfig::default()
1953        };
1954        prepare_aot_for_cli(&mut load_vm, &load_cfg).expect("aot load should succeed");
1955        assert!(load_vm.has_aot_program(), "load path should install aot");
1956        let status = load_vm.run().expect("loaded aot vm should run");
1957        assert_eq!(status, VmStatus::Halted);
1958        assert_eq!(load_vm.stack(), &[Value::Int(9)]);
1959
1960        std::fs::remove_file(&artifact_path).expect("artifact cleanup should succeed");
1961    }
1962
1963    #[test]
1964    fn standalone_cli_aot_load_without_source_uses_embedded_program() {
1965        if !native_aot_supported() {
1966            return;
1967        }
1968
1969        let program = Program::new(
1970            vec![Value::Int(9)],
1971            vec![OpCode::Ldc as u8, 0, 0, 0, 0, OpCode::Ret as u8],
1972        )
1973        .with_local_count(5);
1974        let artifact_path = unique_artifact_path();
1975
1976        let mut save_vm = Vm::new(program.clone());
1977        let save_cfg = CliConfig {
1978            aot_save_path: Some(artifact_path.display().to_string()),
1979            ..CliConfig::default()
1980        };
1981        prepare_aot_for_cli(&mut save_vm, &save_cfg).expect("aot save should succeed");
1982
1983        let load_cfg = CliConfig {
1984            aot_load_path: Some(artifact_path.display().to_string()),
1985            ..CliConfig::default()
1986        };
1987        let mut loaded_vm = try_new_cli_vm_from_standalone_aot(&load_cfg)
1988            .expect("standalone load should succeed")
1989            .expect("standalone load should create a vm");
1990
1991        assert!(
1992            loaded_vm.has_aot_program(),
1993            "standalone load should install aot"
1994        );
1995        assert_eq!(loaded_vm.program().local_count, 5);
1996
1997        let status = loaded_vm.run().expect("standalone aot vm should run");
1998        assert_eq!(status, VmStatus::Halted);
1999        assert_eq!(loaded_vm.stack(), &[Value::Int(9)]);
2000
2001        std::fs::remove_file(&artifact_path).expect("artifact cleanup should succeed");
2002    }
2003
2004    #[test]
2005    fn repl_compile_falls_back_to_expression_semicolon() {
2006        let compiled =
2007            super::compile_repl_snippet("1 + 2", &BTreeMap::new()).expect("compile should succeed");
2008        assert_eq!(compiled.compiled.locals, 0);
2009    }
2010
2011    #[test]
2012    fn repl_compile_uses_persisted_locals() {
2013        let mut locals = BTreeMap::new();
2014        locals.insert(
2015            "x".to_string(),
2016            super::ReplSessionLocal {
2017                value: Value::Int(41),
2018                mutable: false,
2019                schema: Some(vm::compiler::TypeSchema::Int),
2020                optional: false,
2021                moved: false,
2022            },
2023        );
2024        let compiled =
2025            super::compile_repl_snippet("x + 1", &locals).expect("compile should succeed");
2026        assert!(compiled.compiled.locals >= 1);
2027    }
2028
2029    #[test]
2030    fn repl_session_persists_locals_between_entries() {
2031        let mut session = super::ReplSession::default();
2032        let _ = run_repl_snippet_and_sync(&mut session, "let x = 41;");
2033        assert_eq!(
2034            session.locals.get("x").map(|local| &local.value),
2035            Some(&Value::Int(41))
2036        );
2037
2038        let vm = run_repl_snippet_and_sync(&mut session, "x + 1");
2039        assert_eq!(vm.stack().last(), Some(&Value::Int(42)));
2040    }
2041
2042    #[test]
2043    fn repl_session_preserves_move_state_between_entries() {
2044        let mut session = super::ReplSession::default();
2045        let _ = run_repl_snippet_and_sync(&mut session, "let a = \"payload\";");
2046        let _ = run_repl_snippet_and_sync(&mut session, "let b = a;");
2047
2048        assert_eq!(session.locals.get("a").map(|local| local.moved), Some(true));
2049        assert_eq!(
2050            session.locals.get("b").map(|local| &local.value),
2051            Some(&Value::string("payload"))
2052        );
2053        match super::compile_repl_snippet("a", &session.locals) {
2054            Err(vm::SourceError::Parse(parse)) => {
2055                assert_eq!(parse.code.as_deref(), Some("E_LOCAL_MOVED"));
2056            }
2057            Err(other) => panic!("expected moved-local parse error, got {other}"),
2058            Ok(_) => panic!("expected moved-local parse error, got successful compile"),
2059        }
2060    }
2061
2062    #[test]
2063    fn repl_session_marks_copy_types_moved_after_binding() {
2064        let mut session = super::ReplSession::default();
2065        let _ = run_repl_snippet_and_sync(&mut session, "let a = 1;");
2066        let _ = run_repl_snippet_and_sync(&mut session, "let b = a;");
2067
2068        assert_eq!(session.locals.get("a").map(|local| local.moved), Some(true));
2069        match super::compile_repl_snippet("a", &session.locals) {
2070            Err(vm::SourceError::Parse(parse)) => {
2071                assert_eq!(parse.code.as_deref(), Some("E_LOCAL_MOVED"));
2072            }
2073            Err(other) => panic!("expected moved-local parse error, got {other}"),
2074            Ok(_) => panic!("expected moved-local parse error, got successful compile"),
2075        }
2076    }
2077
2078    #[test]
2079    fn repl_session_marks_all_value_types_moved_after_binding() {
2080        let cases = [
2081            ("null", "let a = null;"),
2082            ("int", "let a = 1;"),
2083            ("float", "let a = 1.5;"),
2084            ("bool", "let a = true;"),
2085            ("string", "let a = \"payload\";"),
2086            ("bytes", "use bytes; let a = bytes::from_hex(\"00ff\");"),
2087            ("array", "let a = [1, 2];"),
2088            ("map", "let a = { key: 1 };"),
2089        ];
2090
2091        for (value_type, initializer) in cases {
2092            let mut session = super::ReplSession::default();
2093            let _ = run_repl_snippet_and_sync(&mut session, initializer);
2094            let _ = run_repl_snippet_and_sync(&mut session, "let b = a;");
2095
2096            assert_eq!(
2097                session.locals.get("a").map(|local| local.moved),
2098                Some(true),
2099                "expected {value_type} local to be moved after rebinding"
2100            );
2101            match super::compile_repl_snippet("a", &session.locals) {
2102                Err(vm::SourceError::Parse(parse)) => {
2103                    assert_eq!(
2104                        parse.code.as_deref(),
2105                        Some("E_LOCAL_MOVED"),
2106                        "expected {value_type} local to reject a later use"
2107                    );
2108                }
2109                Err(other) => {
2110                    panic!("expected moved-local parse error for {value_type}, got {other}")
2111                }
2112                Ok(_) => panic!("expected {value_type} local to reject a later use"),
2113            }
2114        }
2115    }
2116
2117    #[test]
2118    fn repl_session_restores_rebound_copy_local_after_reassignment() {
2119        let mut session = super::ReplSession::default();
2120        let _ = run_repl_snippet_and_sync(&mut session, "let mut a = 1;");
2121        let _ = run_repl_snippet_and_sync(&mut session, "let b = a; a = 2;");
2122        let vm = run_repl_snippet_and_sync(&mut session, "a");
2123
2124        assert_eq!(vm.stack().last(), Some(&Value::Int(2)));
2125        assert_eq!(
2126            session.locals.get("a").map(|local| local.moved),
2127            Some(false)
2128        );
2129    }
2130
2131    #[test]
2132    fn repl_session_persists_mutable_locals_between_entries() {
2133        let mut session = super::ReplSession::default();
2134        let _ = run_repl_snippet_and_sync(&mut session, "let mut x = 1;");
2135        assert_eq!(
2136            session.locals.get("x").map(|local| local.mutable),
2137            Some(true)
2138        );
2139
2140        let _ = run_repl_snippet_and_sync(&mut session, "x = x + 1;");
2141        let vm = run_repl_snippet_and_sync(&mut session, "x");
2142        assert_eq!(vm.stack().last(), Some(&Value::Int(2)));
2143    }
2144
2145    #[test]
2146    fn repl_session_persists_null_between_entries() {
2147        let mut session = super::ReplSession::default();
2148        let _ = run_repl_snippet_and_sync(&mut session, "let x = null;");
2149        assert_eq!(
2150            session.locals.get("x").map(|local| &local.value),
2151            Some(&Value::Null)
2152        );
2153
2154        let vm = run_repl_snippet_and_sync(&mut session, "x");
2155        assert_eq!(vm.stack().last(), Some(&Value::Null));
2156    }
2157
2158    #[test]
2159    fn repl_session_persists_float_between_entries() {
2160        let mut session = super::ReplSession::default();
2161        let _ = run_repl_snippet_and_sync(&mut session, "let x = 1.5;");
2162        assert_eq!(
2163            session.locals.get("x").map(|local| &local.value),
2164            Some(&Value::Float(1.5))
2165        );
2166
2167        let vm = run_repl_snippet_and_sync(&mut session, "x + 0.5");
2168        assert_eq!(vm.stack().last(), Some(&Value::Float(2.0)));
2169    }
2170
2171    #[test]
2172    fn repl_compile_remaps_parse_error_line_numbers() {
2173        let mut locals = BTreeMap::new();
2174        locals.insert(
2175            "x".to_string(),
2176            super::ReplSessionLocal {
2177                value: Value::Int(1),
2178                mutable: false,
2179                schema: Some(vm::compiler::TypeSchema::Int),
2180                optional: false,
2181                moved: false,
2182            },
2183        );
2184        match super::compile_repl_snippet("let y = ;", &locals) {
2185            Err(vm::SourceError::Parse(parse)) => assert_eq!(parse.line, 1),
2186            Err(other) => panic!("expected parse error, got {other}"),
2187            Ok(_) => panic!("expected parse error, got successful compile"),
2188        }
2189    }
2190
2191    #[test]
2192    fn repl_input_complete_for_balanced_match_block() {
2193        let input = "let b = match a {\n    Some(String) => 2,\n    _ => 3,\n};";
2194        assert!(super::is_repl_input_complete(input));
2195    }
2196
2197    #[test]
2198    fn repl_input_incomplete_for_open_brace() {
2199        assert!(!super::is_repl_input_complete("let b = match a {"));
2200    }
2201
2202    #[test]
2203    fn repl_input_incomplete_for_unclosed_string() {
2204        assert!(!super::is_repl_input_complete("let s = \"hello"));
2205    }
2206
2207    #[test]
2208    fn repl_input_incomplete_for_unclosed_block_comment() {
2209        assert!(!super::is_repl_input_complete("let a = 1; /* comment"));
2210    }
2211
2212    #[test]
2213    fn repl_input_ignores_comment_delimiters() {
2214        assert!(super::is_repl_input_complete("// {\nlet a = 1;"));
2215    }
2216
2217    #[test]
2218    fn repl_input_incomplete_for_trailing_operator() {
2219        assert!(!super::is_repl_input_complete("let a = 1 +"));
2220    }
2221}