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, disassemble_vmbc_with_options,
12    encode_program, format_source_with_flavor_and_options, render_source_error, render_vm_error,
13    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    moved: bool,
1008}
1009
1010fn sync_repl_session(vm: &Vm, bindings: &[ReplLocalBinding], session: &mut ReplSession) {
1011    if bindings.is_empty() {
1012        session.locals.clear();
1013        return;
1014    }
1015    let Some(debug) = vm.debug_info() else {
1016        session.locals.clear();
1017        return;
1018    };
1019    let mut next = BTreeMap::new();
1020    for binding in bindings {
1021        let Some(index) = debug.local_index(&binding.name) else {
1022            continue;
1023        };
1024        let Some(value) = vm.locals().get(index as usize) else {
1025            continue;
1026        };
1027        let (schema, optional) = repl_local_schema_from_vm(vm, index as usize, value);
1028        let moved = !optional
1029            && value == &Value::Null
1030            && matches!(
1031                schema,
1032                Some(vm::compiler::TypeSchema::String | vm::compiler::TypeSchema::Bytes)
1033            );
1034        next.insert(
1035            binding.name.clone(),
1036            ReplSessionLocal {
1037                value: value.clone(),
1038                mutable: binding.mutable,
1039                schema,
1040                optional,
1041                moved,
1042            },
1043        );
1044    }
1045    session.locals = next;
1046}
1047
1048#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1049enum ReplAction {
1050    Continue,
1051    Break,
1052}
1053
1054fn handle_repl_command(line: &str) -> Option<ReplAction> {
1055    match line {
1056        ".quit" | ".exit" => Some(ReplAction::Break),
1057        ".cancel" => {
1058            println!("no pending input");
1059            Some(ReplAction::Continue)
1060        }
1061        ".help" => {
1062            println!("commands:");
1063            println!("  .help      show commands");
1064            println!("  .quit      quit repl");
1065            println!("  .exit      quit repl");
1066            println!("  .cancel    clear pending multiline input");
1067            Some(ReplAction::Continue)
1068        }
1069        _ if line.starts_with('.') => {
1070            println!("unknown command: {line}");
1071            Some(ReplAction::Continue)
1072        }
1073        _ => None,
1074    }
1075}
1076
1077fn compile_repl_snippet(
1078    input: &str,
1079    locals: &BTreeMap<String, ReplSessionLocal>,
1080) -> Result<vm::CompiledReplProgram, vm::SourceError> {
1081    let trimmed = input.trim_end();
1082    let bindings = locals
1083        .iter()
1084        .map(|(name, local)| vm::compiler::ReplLocalState {
1085            binding: ReplLocalBinding {
1086                name: name.clone(),
1087                mutable: local.mutable,
1088                schema: local.schema.clone(),
1089                optional: local.optional,
1090            },
1091            moved: local.moved,
1092        })
1093        .collect::<Vec<_>>();
1094    match vm::compiler::compile_source_for_repl_with_state(trimmed, &bindings) {
1095        Ok(compiled) => Ok(compiled),
1096        Err(first_err) => {
1097            if trimmed.ends_with(';') {
1098                return Err(first_err);
1099            }
1100            let fallback = format!("{trimmed};");
1101            match vm::compiler::compile_source_for_repl_with_state(&fallback, &bindings) {
1102                Ok(compiled) => Ok(compiled),
1103                Err(err @ vm::SourceError::Parse(vm::ParseError { code: Some(_), .. })) => Err(err),
1104                Err(err @ vm::SourceError::Compile(_)) => Err(err),
1105                Err(_) => Err(first_err),
1106            }
1107        }
1108    }
1109}
1110
1111fn seed_repl_vm_locals(
1112    vm: &mut Vm,
1113    locals: &BTreeMap<String, ReplSessionLocal>,
1114) -> Result<(), VmError> {
1115    if locals.is_empty() {
1116        return Ok(());
1117    }
1118    for (name, local) in locals {
1119        let index = {
1120            let Some(debug) = vm.debug_info() else {
1121                return Err(VmError::HostError(
1122                    "repl debug info unavailable while restoring locals".to_string(),
1123                ));
1124            };
1125            debug.local_index(name).ok_or_else(|| {
1126                VmError::HostError(format!("repl local '{name}' missing from compiled snippet"))
1127            })?
1128        };
1129        vm.set_local(index, local.value.clone())?;
1130    }
1131    Ok(())
1132}
1133
1134fn repl_local_schema_from_vm(
1135    vm: &Vm,
1136    index: usize,
1137    value: &Value,
1138) -> (Option<vm::compiler::TypeSchema>, bool) {
1139    let fallback = repl_schema_from_value(value);
1140    let Some(type_map) = vm.program().type_map.as_ref() else {
1141        return (fallback, false);
1142    };
1143    let schema = type_map
1144        .local_schemas
1145        .get(index)
1146        .cloned()
1147        .flatten()
1148        .or_else(|| {
1149            type_map
1150                .local_types
1151                .get(index)
1152                .copied()
1153                .and_then(repl_schema_from_value_type)
1154        })
1155        .or(fallback);
1156    let optional = type_map.optional_slots.get(index).copied().unwrap_or(false);
1157    (schema, optional)
1158}
1159
1160fn repl_schema_from_value(value: &Value) -> Option<vm::compiler::TypeSchema> {
1161    use vm::compiler::TypeSchema;
1162
1163    match value {
1164        Value::Null => Some(TypeSchema::Null),
1165        Value::Int(_) => Some(TypeSchema::Int),
1166        Value::Float(_) => Some(TypeSchema::Float),
1167        Value::Bool(_) => Some(TypeSchema::Bool),
1168        Value::String(_) => Some(TypeSchema::String),
1169        Value::Bytes(_) => Some(TypeSchema::Bytes),
1170        Value::Array(_) => Some(TypeSchema::Array(Box::new(TypeSchema::Unknown))),
1171        Value::Map(_) => Some(TypeSchema::Map(Box::new(TypeSchema::Unknown))),
1172    }
1173}
1174
1175fn repl_schema_from_value_type(value_type: vm::ValueType) -> Option<vm::compiler::TypeSchema> {
1176    use vm::compiler::TypeSchema;
1177
1178    match value_type {
1179        vm::ValueType::Unknown => None,
1180        vm::ValueType::Null => Some(TypeSchema::Null),
1181        vm::ValueType::Int => Some(TypeSchema::Int),
1182        vm::ValueType::Float => Some(TypeSchema::Float),
1183        vm::ValueType::Bool => Some(TypeSchema::Bool),
1184        vm::ValueType::String => Some(TypeSchema::String),
1185        vm::ValueType::Bytes => Some(TypeSchema::Bytes),
1186        vm::ValueType::Array => Some(TypeSchema::Array(Box::new(TypeSchema::Unknown))),
1187        vm::ValueType::Map => Some(TypeSchema::Map(Box::new(TypeSchema::Unknown))),
1188    }
1189}
1190
1191fn is_repl_input_complete(input: &str) -> bool {
1192    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
1193    enum Delimiter {
1194        Paren,
1195        Bracket,
1196        Brace,
1197    }
1198
1199    let mut stack: Vec<Delimiter> = Vec::new();
1200    let mut chars = input.chars().peekable();
1201    let mut in_string = false;
1202    let mut escaped = false;
1203    let mut in_line_comment = false;
1204    let mut in_block_comment = false;
1205    let mut code = String::with_capacity(input.len());
1206
1207    while let Some(ch) = chars.next() {
1208        if in_line_comment {
1209            if ch == '\n' {
1210                in_line_comment = false;
1211                code.push('\n');
1212            }
1213            continue;
1214        }
1215        if in_block_comment {
1216            if ch == '*'
1217                && let Some('/') = chars.peek()
1218            {
1219                chars.next();
1220                in_block_comment = false;
1221            }
1222            continue;
1223        }
1224        if in_string {
1225            if escaped {
1226                escaped = false;
1227                continue;
1228            }
1229            match ch {
1230                '\\' => escaped = true,
1231                '"' => {
1232                    in_string = false;
1233                    code.push('"');
1234                }
1235                _ => {}
1236            }
1237            continue;
1238        }
1239
1240        if ch == '/' {
1241            match chars.peek().copied() {
1242                Some('/') => {
1243                    chars.next();
1244                    in_line_comment = true;
1245                    continue;
1246                }
1247                Some('*') => {
1248                    chars.next();
1249                    in_block_comment = true;
1250                    continue;
1251                }
1252                _ => {}
1253            }
1254        }
1255
1256        match ch {
1257            '"' => {
1258                in_string = true;
1259                code.push('"');
1260            }
1261            '(' => {
1262                stack.push(Delimiter::Paren);
1263                code.push(ch);
1264            }
1265            '[' => {
1266                stack.push(Delimiter::Bracket);
1267                code.push(ch);
1268            }
1269            '{' => {
1270                stack.push(Delimiter::Brace);
1271                code.push(ch);
1272            }
1273            ')' => {
1274                if stack.pop() != Some(Delimiter::Paren) {
1275                    return true;
1276                }
1277                code.push(ch);
1278            }
1279            ']' => {
1280                if stack.pop() != Some(Delimiter::Bracket) {
1281                    return true;
1282                }
1283                code.push(ch);
1284            }
1285            '}' => {
1286                if stack.pop() != Some(Delimiter::Brace) {
1287                    return true;
1288                }
1289                code.push(ch);
1290            }
1291            _ => code.push(ch),
1292        }
1293    }
1294
1295    if in_string || in_block_comment || !stack.is_empty() {
1296        return false;
1297    }
1298
1299    let trimmed = code.trim_end();
1300    if trimmed.is_empty() {
1301        return true;
1302    }
1303
1304    const TRAILING_INCOMPLETE_TOKENS: [&str; 18] = [
1305        "=>", "::", "&&", "||", "<=", ">=", "==", "!=", "=", ",", ".", "+", "-", "*", "/", "%",
1306        "!", ":",
1307    ];
1308    !TRAILING_INCOMPLETE_TOKENS
1309        .iter()
1310        .any(|token| trimmed.ends_with(token))
1311}
1312
1313fn render_repl_compile_error(snippet: &str, err: &vm::SourceError) -> String {
1314    match err {
1315        vm::SourceError::Parse(parse) => {
1316            let mut source_map = SourceMap::new();
1317            let source_id = source_map.add_source("<repl>", snippet.to_string());
1318            let parse = parse
1319                .clone()
1320                .with_line_span_from_source(&source_map, source_id);
1321            render_source_error(&source_map, &parse, true)
1322        }
1323        _ => err.to_string(),
1324    }
1325}
1326
1327fn add_one_host_function(_vm: &mut Vm, args: &[Value]) -> Result<CallOutcome, VmError> {
1328    let value = match args.first() {
1329        Some(Value::Int(value)) => *value,
1330        _ => return Err(VmError::TypeMismatch("int")),
1331    };
1332    Ok(CallOutcome::Return(CallReturn::one(Value::Int(value + 1))))
1333}
1334
1335fn echo_host_function(_vm: &mut Vm, args: &[Value]) -> Result<CallOutcome, VmError> {
1336    let value = args.first().cloned().ok_or(VmError::StackUnderflow)?;
1337    Ok(CallOutcome::Return(CallReturn::one(value)))
1338}
1339
1340fn format_value(value: &Value) -> String {
1341    match value {
1342        Value::Null => "null".to_string(),
1343        Value::Int(value) => value.to_string(),
1344        Value::Float(value) => value.to_string(),
1345        Value::Bool(value) => value.to_string(),
1346        Value::String(value) => value.as_str().to_string(),
1347        Value::Bytes(value) => format_bytes(value.as_ref()),
1348        Value::Array(values) => {
1349            let parts = values
1350                .iter()
1351                .map(format_value)
1352                .collect::<Vec<_>>()
1353                .join(", ");
1354            format!("[{parts}]")
1355        }
1356        Value::Map(entries) => {
1357            let parts = entries
1358                .iter()
1359                .map(|(key, value)| format!("{}: {}", format_value(key), format_value(value)))
1360                .collect::<Vec<_>>()
1361                .join(", ");
1362            format!("{{{parts}}}")
1363        }
1364    }
1365}
1366
1367fn format_bytes(bytes: &[u8]) -> String {
1368    let preview_len = bytes.len().min(16);
1369    let mut preview = String::with_capacity(preview_len * 2);
1370    for byte in &bytes[..preview_len] {
1371        preview.push(hex_nibble(byte >> 4));
1372        preview.push(hex_nibble(byte & 0x0F));
1373    }
1374    if bytes.len() > preview_len {
1375        format!("bytes[len={} hex={}..]", bytes.len(), preview)
1376    } else {
1377        format!("bytes[len={} hex={}]", bytes.len(), preview)
1378    }
1379}
1380
1381fn hex_nibble(value: u8) -> char {
1382    match value {
1383        0..=9 => char::from(b'0' + value),
1384        10..=15 => char::from(b'a' + (value - 10)),
1385        _ => unreachable!("hex nibble out of range"),
1386    }
1387}
1388
1389#[cfg(test)]
1390mod tests {
1391    use crate as vm;
1392    use std::collections::BTreeMap;
1393    use std::time::{SystemTime, UNIX_EPOCH};
1394
1395    use super::{
1396        CliConfig, parse_cli_args, prepare_aot_for_cli, register_imports,
1397        try_new_cli_vm_from_standalone_aot,
1398    };
1399    use vm::{HostImport, OpCode, Program, Value, ValueType, Vm, VmStatus};
1400
1401    fn s(value: &str) -> String {
1402        value.to_string()
1403    }
1404
1405    fn native_aot_supported() -> bool {
1406        (cfg!(target_arch = "x86_64")
1407            && (cfg!(target_os = "windows") || (cfg!(unix) && !cfg!(target_os = "macos"))))
1408            || (cfg!(target_arch = "aarch64")
1409                && (cfg!(target_os = "linux") || cfg!(target_os = "macos")))
1410    }
1411
1412    fn unique_artifact_path() -> std::path::PathBuf {
1413        let mut path = std::env::temp_dir();
1414        let stamp = SystemTime::now()
1415            .duration_since(UNIX_EPOCH)
1416            .expect("system clock should be after unix epoch")
1417            .as_nanos();
1418        path.push(format!("pd-vm-run-aot-{}-{stamp}.pat", std::process::id()));
1419        path
1420    }
1421
1422    fn run_repl_snippet_and_sync(session: &mut super::ReplSession, snippet: &str) -> Vm {
1423        let compiled =
1424            super::compile_repl_snippet(snippet, &session.locals).expect("compile should succeed");
1425        let mut vm = Vm::new(
1426            compiled
1427                .compiled
1428                .program
1429                .with_local_count(compiled.compiled.locals),
1430        );
1431        super::configure_cli_vm(&mut vm);
1432        let imports = vm.program().imports.clone();
1433        super::register_imports(&mut vm, &imports).expect("register should succeed");
1434        super::seed_repl_vm_locals(&mut vm, &session.locals).expect("locals should restore");
1435        loop {
1436            match vm.run().expect("snippet should run") {
1437                VmStatus::Halted => break,
1438                VmStatus::Yielded => continue,
1439                VmStatus::Waiting(_) => vm
1440                    .wait_for_host_op_blocking()
1441                    .expect("snippet should not block"),
1442            }
1443        }
1444        super::sync_repl_session(&vm, &compiled.bindings, session);
1445        vm
1446    }
1447
1448    #[test]
1449    fn register_imports_binds_cached_cli_host_registry_plan() {
1450        let imports = vec![
1451            HostImport {
1452                name: "print".to_string(),
1453                arity: 1,
1454                return_type: ValueType::Unknown,
1455            },
1456            HostImport {
1457                name: "echo".to_string(),
1458                arity: 1,
1459                return_type: ValueType::Unknown,
1460            },
1461        ];
1462        let program =
1463            Program::with_imports_and_debug(vec![], vec![OpCode::Ret as u8], imports.clone(), None);
1464
1465        let mut first = Vm::new(program.clone());
1466        register_imports(&mut first, &imports).expect("first vm should bind imports");
1467        assert_eq!(first.bound_function_count(), 2);
1468
1469        let mut second = Vm::new(program);
1470        register_imports(&mut second, &imports).expect("second vm should reuse cached plan");
1471        assert_eq!(second.bound_function_count(), 2);
1472    }
1473
1474    #[test]
1475    fn parse_cli_defaults() {
1476        let cfg = parse_cli_args(&[]).expect("parse should succeed");
1477        assert!(cfg.repl);
1478        assert!(!cfg.debug);
1479        assert!(!cfg.version);
1480        assert!(cfg.tcp_addr.is_none());
1481        assert!(cfg.stop_on_entry);
1482        assert!(!cfg.aot);
1483        assert!(!cfg.aot_dump);
1484        assert!(cfg.aot_save_path.is_none());
1485        assert!(cfg.aot_load_path.is_none());
1486        assert!(!cfg.jit_dump);
1487        assert!(cfg.jit_dump_show_machine_code);
1488        assert!(cfg.jit_hot_loop_threshold.is_none());
1489        assert!(cfg.fuel.is_none());
1490        assert!(cfg.epoch_deadline.is_none());
1491        assert!(cfg.source.is_none());
1492        assert!(cfg.epoch_check_interval.is_none());
1493        assert!(cfg.emit_vmbc_path.is_none());
1494        assert!(cfg.disasm_vmbc_path.is_none());
1495        assert!(!cfg.show_source);
1496        assert!(!cfg.fmt);
1497        assert!(!cfg.fmt_check);
1498    }
1499
1500    #[test]
1501    fn parse_cli_version_flag() {
1502        let cfg = parse_cli_args(&[s("--version")]).expect("parse should succeed");
1503        assert!(cfg.version);
1504        assert!(!cfg.repl);
1505    }
1506
1507    #[test]
1508    fn parse_cli_version_short_flag() {
1509        let cfg = parse_cli_args(&[s("-V")]).expect("parse should succeed");
1510        assert!(cfg.version);
1511        assert!(!cfg.repl);
1512    }
1513
1514    #[test]
1515    fn parse_cli_debug_with_source_and_tcp() {
1516        let cfg = parse_cli_args(&[
1517            s("--debug"),
1518            s("--tcp"),
1519            s("127.0.0.1:9002"),
1520            s("examples/example.lua"),
1521        ])
1522        .expect("parse should succeed");
1523        assert!(cfg.debug);
1524        assert_eq!(cfg.tcp_addr.as_deref(), Some("127.0.0.1:9002"));
1525        assert_eq!(cfg.source.as_deref(), Some("examples/example.lua"));
1526    }
1527
1528    #[test]
1529    fn parse_cli_legacy_debug_command() {
1530        let cfg =
1531            parse_cli_args(&[s("debug"), s("examples/example.rss")]).expect("parse should succeed");
1532        assert!(cfg.debug);
1533        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1534    }
1535
1536    #[test]
1537    fn parse_cli_rejects_multiple_sources() {
1538        let err = parse_cli_args(&[s("a.rss"), s("b.rss")]).expect_err("parse should fail");
1539        assert!(err.contains("multiple source paths"));
1540    }
1541
1542    #[test]
1543    fn parse_cli_jit_flags() {
1544        let cfg = parse_cli_args(&[
1545            s("--jit-hot-loop"),
1546            s("2"),
1547            s("--jit-dump"),
1548            s("--jit-dump-no-code"),
1549            s("examples/example.rss"),
1550        ])
1551        .expect("parse should succeed");
1552        assert_eq!(cfg.jit_hot_loop_threshold, Some(2));
1553        assert!(cfg.jit_dump);
1554        assert!(!cfg.jit_dump_show_machine_code);
1555        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1556    }
1557
1558    #[test]
1559    fn parse_cli_aot_flags() {
1560        let cfg = parse_cli_args(&[
1561            s("--aot"),
1562            s("--aot-dump"),
1563            s("--aot-save"),
1564            s("out/program.pat"),
1565            s("examples/example.rss"),
1566        ])
1567        .expect("parse should succeed");
1568        assert!(cfg.aot);
1569        assert!(cfg.aot_dump);
1570        assert_eq!(cfg.aot_save_path.as_deref(), Some("out/program.pat"));
1571        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1572    }
1573
1574    #[test]
1575    fn parse_cli_aot_load_without_source_path() {
1576        let cfg =
1577            parse_cli_args(&[s("--aot-load"), s("out/program.pat")]).expect("parse should succeed");
1578        assert_eq!(cfg.aot_load_path.as_deref(), Some("out/program.pat"));
1579        assert!(cfg.source.is_none());
1580    }
1581
1582    #[test]
1583    fn parse_cli_rejects_aot_and_load_together() {
1584        let err = parse_cli_args(&[
1585            s("--aot"),
1586            s("--aot-load"),
1587            s("out/program.pat"),
1588            s("examples/example.rss"),
1589        ])
1590        .expect_err("parse should fail");
1591        assert!(err.contains("mutually exclusive"));
1592    }
1593
1594    #[test]
1595    fn parse_cli_debug_rejects_aot_runtime_flags() {
1596        let err = parse_cli_args(&[s("--debug"), s("--aot"), s("examples/example.rss")])
1597            .expect_err("parse should fail");
1598        assert!(err.contains("debug mode"));
1599    }
1600
1601    #[test]
1602    fn parse_cli_dump_jit_alias() {
1603        let cfg = parse_cli_args(&[s("--dump-jit"), s("examples/example.rss")])
1604            .expect("parse should succeed");
1605        assert!(cfg.jit_dump);
1606        assert!(cfg.jit_dump_show_machine_code);
1607        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1608    }
1609
1610    #[test]
1611    fn parse_cli_jit_dump_no_code_requires_dump_flag() {
1612        let err = parse_cli_args(&[s("--jit-dump-no-code"), s("examples/example.rss")])
1613            .expect_err("parse should fail");
1614        assert!(err.contains("requires --jit-dump or --dump-jit"));
1615    }
1616
1617    #[test]
1618    fn parse_cli_fuel_flag() {
1619        let cfg = parse_cli_args(&[s("--fuel"), s("123"), s("examples/example.rss")])
1620            .expect("parse should succeed");
1621        assert_eq!(cfg.fuel, Some(123));
1622        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1623    }
1624
1625    #[test]
1626    fn parse_cli_fuel_requires_value() {
1627        let err = parse_cli_args(&[s("--fuel")]).expect_err("parse should fail");
1628        assert!(err.contains("missing value for --fuel"));
1629    }
1630
1631    #[test]
1632    fn parse_cli_epoch_deadline_flag() {
1633        let cfg = parse_cli_args(&[s("--epoch-deadline"), s("3"), s("examples/example.rss")])
1634            .expect("parse should succeed");
1635        assert_eq!(cfg.epoch_deadline, Some(3));
1636        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1637    }
1638
1639    #[test]
1640    fn parse_cli_rejects_fuel_and_epoch_deadline_together() {
1641        let err = parse_cli_args(&[
1642            s("--fuel"),
1643            s("10"),
1644            s("--epoch-deadline"),
1645            s("3"),
1646            s("examples/example.rss"),
1647        ])
1648        .expect_err("parse should fail");
1649        assert!(err.contains("mutually exclusive"));
1650    }
1651
1652    #[test]
1653    fn parse_cli_emit_vmbc_path() {
1654        let cfg = parse_cli_args(&[
1655            s("--emit-vmbc"),
1656            s("out/program.vmbc"),
1657            s("examples/example.rss"),
1658        ])
1659        .expect("parse should succeed");
1660        assert_eq!(cfg.emit_vmbc_path.as_deref(), Some("out/program.vmbc"));
1661        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1662    }
1663
1664    #[test]
1665    fn parse_cli_emit_vmbc_requires_path() {
1666        let err = parse_cli_args(&[s("--emit-vmbc")]).expect_err("parse should fail");
1667        assert!(err.contains("missing value for --emit-vmbc"));
1668    }
1669
1670    #[test]
1671    fn parse_cli_disasm_vmbc_path() {
1672        let cfg = parse_cli_args(&[
1673            s("--disasm-vmbc"),
1674            s("out/program.vmbc"),
1675            s("--show-source"),
1676        ])
1677        .expect("parse should succeed");
1678        assert_eq!(cfg.disasm_vmbc_path.as_deref(), Some("out/program.vmbc"));
1679        assert!(cfg.show_source);
1680    }
1681
1682    #[test]
1683    fn parse_cli_disasm_requires_path() {
1684        let err = parse_cli_args(&[s("--disasm-vmbc")]).expect_err("parse should fail");
1685        assert!(err.contains("missing value for --disasm-vmbc"));
1686    }
1687
1688    #[test]
1689    fn parse_cli_show_source_requires_disasm() {
1690        let err = parse_cli_args(&[s("--show-source")]).expect_err("parse should fail");
1691        assert!(err.contains("requires --disasm-vmbc"));
1692    }
1693
1694    #[test]
1695    fn parse_cli_disasm_rejects_source_path() {
1696        let err = parse_cli_args(&[
1697            s("--disasm-vmbc"),
1698            s("program.vmbc"),
1699            s("examples/example.rss"),
1700        ])
1701        .expect_err("parse should fail");
1702        assert!(err.contains("does not accept a source path"));
1703    }
1704
1705    #[test]
1706    fn parse_cli_record_path() {
1707        let cfg = parse_cli_args(&[s("--record"), s("out/run.pdr"), s("examples/example.rss")])
1708            .expect("parse should succeed");
1709        assert_eq!(cfg.record_path.as_deref(), Some("out/run.pdr"));
1710        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1711    }
1712
1713    #[test]
1714    fn parse_cli_view_record_path() {
1715        let cfg =
1716            parse_cli_args(&[s("--view-record"), s("out/run.pdr")]).expect("parse should succeed");
1717        assert_eq!(cfg.view_recording_path.as_deref(), Some("out/run.pdr"));
1718        assert!(cfg.source.is_none());
1719    }
1720
1721    #[test]
1722    fn parse_cli_view_record_rejects_fuel() {
1723        let err = parse_cli_args(&[s("--view-record"), s("out/run.pdr"), s("--fuel"), s("10")])
1724            .expect_err("parse should fail");
1725        assert!(err.contains("view-record mode"));
1726    }
1727
1728    #[test]
1729    fn parse_cli_record_rejects_debug() {
1730        let err = parse_cli_args(&[s("--record"), s("run.pdr"), s("--debug")])
1731            .expect_err("parse should fail");
1732        assert!(err.contains("record mode"));
1733    }
1734
1735    #[test]
1736    fn parse_cli_repl_flag() {
1737        let cfg = parse_cli_args(&[s("--repl")]).expect("parse should succeed");
1738        assert!(cfg.repl);
1739    }
1740
1741    #[test]
1742    fn parse_cli_fmt_command() {
1743        let cfg =
1744            parse_cli_args(&[s("fmt"), s("examples/example.rss")]).expect("parse should succeed");
1745        assert!(cfg.fmt);
1746        assert!(!cfg.fmt_check);
1747        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1748    }
1749
1750    #[test]
1751    fn parse_cli_fmt_check_flag() {
1752        let cfg = parse_cli_args(&[s("fmt"), s("--check"), s("examples/example.rss")])
1753            .expect("parse should succeed");
1754        assert!(cfg.fmt);
1755        assert!(cfg.fmt_check);
1756        assert_eq!(cfg.source.as_deref(), Some("examples/example.rss"));
1757    }
1758
1759    #[test]
1760    fn parse_cli_fmt_requires_source_path() {
1761        let err = parse_cli_args(&[s("fmt")]).expect_err("parse should fail");
1762        assert!(err.contains("requires a source path"));
1763    }
1764
1765    #[test]
1766    fn parse_cli_check_requires_fmt() {
1767        let err = parse_cli_args(&[s("--check"), s("examples/example.rss")])
1768            .expect_err("parse should fail");
1769        assert!(err.contains("requires fmt mode"));
1770    }
1771
1772    #[test]
1773    fn parse_cli_fmt_rejects_debug_flag() {
1774        let err = parse_cli_args(&[s("fmt"), s("--debug"), s("examples/example.rss")])
1775            .expect_err("parse should fail");
1776        assert!(err.contains("fmt mode"));
1777    }
1778
1779    #[test]
1780    fn parse_cli_repl_legacy_command() {
1781        let cfg = parse_cli_args(&[s("repl")]).expect("parse should succeed");
1782        assert!(cfg.repl);
1783    }
1784
1785    #[test]
1786    fn parse_cli_repl_rejects_source_path() {
1787        let err = parse_cli_args(&[s("--repl"), s("examples/example.rss")])
1788            .expect_err("parse should fail");
1789        assert!(err.contains("does not accept a source path"));
1790    }
1791
1792    #[test]
1793    fn parse_cli_repl_rejects_emit_vmbc() {
1794        let err = parse_cli_args(&[s("--repl"), s("--emit-vmbc"), s("out.vmbc")])
1795            .expect_err("parse should fail");
1796        assert!(err.contains("cannot be combined"));
1797    }
1798
1799    #[test]
1800    fn parse_cli_repl_rejects_fuel() {
1801        let err =
1802            parse_cli_args(&[s("--repl"), s("--fuel"), s("10")]).expect_err("parse should fail");
1803        assert!(err.contains("cannot be combined"));
1804    }
1805
1806    #[test]
1807    fn prepare_cli_aot_can_save_and_reload_artifact() {
1808        if !native_aot_supported() {
1809            return;
1810        }
1811
1812        let program = Program::new(
1813            vec![Value::Int(9)],
1814            vec![OpCode::Ldc as u8, 0, 0, 0, 0, OpCode::Ret as u8],
1815        );
1816        let artifact_path = unique_artifact_path();
1817
1818        let mut save_vm = Vm::new(program.clone());
1819        let save_cfg = CliConfig {
1820            aot_save_path: Some(artifact_path.display().to_string()),
1821            ..CliConfig::default()
1822        };
1823        prepare_aot_for_cli(&mut save_vm, &save_cfg).expect("aot save should succeed");
1824        assert!(save_vm.has_aot_program(), "save path should install aot");
1825
1826        let mut load_vm = Vm::new(program);
1827        let load_cfg = CliConfig {
1828            aot_load_path: Some(artifact_path.display().to_string()),
1829            ..CliConfig::default()
1830        };
1831        prepare_aot_for_cli(&mut load_vm, &load_cfg).expect("aot load should succeed");
1832        assert!(load_vm.has_aot_program(), "load path should install aot");
1833        let status = load_vm.run().expect("loaded aot vm should run");
1834        assert_eq!(status, VmStatus::Halted);
1835        assert_eq!(load_vm.stack(), &[Value::Int(9)]);
1836
1837        std::fs::remove_file(&artifact_path).expect("artifact cleanup should succeed");
1838    }
1839
1840    #[test]
1841    fn standalone_cli_aot_load_without_source_uses_embedded_program() {
1842        if !native_aot_supported() {
1843            return;
1844        }
1845
1846        let program = Program::new(
1847            vec![Value::Int(9)],
1848            vec![OpCode::Ldc as u8, 0, 0, 0, 0, OpCode::Ret as u8],
1849        )
1850        .with_local_count(5);
1851        let artifact_path = unique_artifact_path();
1852
1853        let mut save_vm = Vm::new(program.clone());
1854        let save_cfg = CliConfig {
1855            aot_save_path: Some(artifact_path.display().to_string()),
1856            ..CliConfig::default()
1857        };
1858        prepare_aot_for_cli(&mut save_vm, &save_cfg).expect("aot save should succeed");
1859
1860        let load_cfg = CliConfig {
1861            aot_load_path: Some(artifact_path.display().to_string()),
1862            ..CliConfig::default()
1863        };
1864        let mut loaded_vm = try_new_cli_vm_from_standalone_aot(&load_cfg)
1865            .expect("standalone load should succeed")
1866            .expect("standalone load should create a vm");
1867
1868        assert!(
1869            loaded_vm.has_aot_program(),
1870            "standalone load should install aot"
1871        );
1872        assert_eq!(loaded_vm.program().local_count, 5);
1873
1874        let status = loaded_vm.run().expect("standalone aot vm should run");
1875        assert_eq!(status, VmStatus::Halted);
1876        assert_eq!(loaded_vm.stack(), &[Value::Int(9)]);
1877
1878        std::fs::remove_file(&artifact_path).expect("artifact cleanup should succeed");
1879    }
1880
1881    #[test]
1882    fn repl_compile_falls_back_to_expression_semicolon() {
1883        let compiled =
1884            super::compile_repl_snippet("1 + 2", &BTreeMap::new()).expect("compile should succeed");
1885        assert_eq!(compiled.compiled.locals, 0);
1886    }
1887
1888    #[test]
1889    fn repl_compile_uses_persisted_locals() {
1890        let mut locals = BTreeMap::new();
1891        locals.insert(
1892            "x".to_string(),
1893            super::ReplSessionLocal {
1894                value: Value::Int(41),
1895                mutable: false,
1896                schema: Some(vm::compiler::TypeSchema::Int),
1897                optional: false,
1898                moved: false,
1899            },
1900        );
1901        let compiled =
1902            super::compile_repl_snippet("x + 1", &locals).expect("compile should succeed");
1903        assert!(compiled.compiled.locals >= 1);
1904    }
1905
1906    #[test]
1907    fn repl_session_persists_locals_between_entries() {
1908        let mut session = super::ReplSession::default();
1909        let _ = run_repl_snippet_and_sync(&mut session, "let x = 41;");
1910        assert_eq!(
1911            session.locals.get("x").map(|local| &local.value),
1912            Some(&Value::Int(41))
1913        );
1914
1915        let vm = run_repl_snippet_and_sync(&mut session, "x + 1");
1916        assert_eq!(vm.stack().last(), Some(&Value::Int(42)));
1917    }
1918
1919    #[test]
1920    fn repl_session_preserves_move_state_between_entries() {
1921        let mut session = super::ReplSession::default();
1922        let _ = run_repl_snippet_and_sync(&mut session, "let a = \"payload\";");
1923        let _ = run_repl_snippet_and_sync(&mut session, "let b = a;");
1924
1925        assert_eq!(session.locals.get("a").map(|local| local.moved), Some(true));
1926        assert_eq!(
1927            session.locals.get("b").map(|local| &local.value),
1928            Some(&Value::string("payload"))
1929        );
1930        match super::compile_repl_snippet("a", &session.locals) {
1931            Err(vm::SourceError::Parse(parse)) => {
1932                assert_eq!(parse.code.as_deref(), Some("E_LOCAL_MOVED"));
1933            }
1934            Err(other) => panic!("expected moved-local parse error, got {other}"),
1935            Ok(_) => panic!("expected moved-local parse error, got successful compile"),
1936        }
1937    }
1938
1939    #[test]
1940    fn repl_session_keeps_copy_types_available_after_binding() {
1941        let mut session = super::ReplSession::default();
1942        let _ = run_repl_snippet_and_sync(&mut session, "let a = 1;");
1943        let _ = run_repl_snippet_and_sync(&mut session, "let b = a;");
1944        let vm = run_repl_snippet_and_sync(&mut session, "a");
1945
1946        assert_eq!(vm.stack().last(), Some(&Value::Int(1)));
1947        assert_eq!(
1948            session.locals.get("a").map(|local| local.moved),
1949            Some(false)
1950        );
1951    }
1952
1953    #[test]
1954    fn repl_session_persists_mutable_locals_between_entries() {
1955        let mut session = super::ReplSession::default();
1956        let _ = run_repl_snippet_and_sync(&mut session, "let mut x = 1;");
1957        assert_eq!(
1958            session.locals.get("x").map(|local| local.mutable),
1959            Some(true)
1960        );
1961
1962        let _ = run_repl_snippet_and_sync(&mut session, "x = x + 1;");
1963        let vm = run_repl_snippet_and_sync(&mut session, "x");
1964        assert_eq!(vm.stack().last(), Some(&Value::Int(2)));
1965    }
1966
1967    #[test]
1968    fn repl_session_persists_null_between_entries() {
1969        let mut session = super::ReplSession::default();
1970        let _ = run_repl_snippet_and_sync(&mut session, "let x = null;");
1971        assert_eq!(
1972            session.locals.get("x").map(|local| &local.value),
1973            Some(&Value::Null)
1974        );
1975
1976        let vm = run_repl_snippet_and_sync(&mut session, "x");
1977        assert_eq!(vm.stack().last(), Some(&Value::Null));
1978    }
1979
1980    #[test]
1981    fn repl_session_persists_float_between_entries() {
1982        let mut session = super::ReplSession::default();
1983        let _ = run_repl_snippet_and_sync(&mut session, "let x = 1.5;");
1984        assert_eq!(
1985            session.locals.get("x").map(|local| &local.value),
1986            Some(&Value::Float(1.5))
1987        );
1988
1989        let vm = run_repl_snippet_and_sync(&mut session, "x + 0.5");
1990        assert_eq!(vm.stack().last(), Some(&Value::Float(2.0)));
1991    }
1992
1993    #[test]
1994    fn repl_compile_remaps_parse_error_line_numbers() {
1995        let mut locals = BTreeMap::new();
1996        locals.insert(
1997            "x".to_string(),
1998            super::ReplSessionLocal {
1999                value: Value::Int(1),
2000                mutable: false,
2001                schema: Some(vm::compiler::TypeSchema::Int),
2002                optional: false,
2003                moved: false,
2004            },
2005        );
2006        match super::compile_repl_snippet("let y = ;", &locals) {
2007            Err(vm::SourceError::Parse(parse)) => assert_eq!(parse.line, 1),
2008            Err(other) => panic!("expected parse error, got {other}"),
2009            Ok(_) => panic!("expected parse error, got successful compile"),
2010        }
2011    }
2012
2013    #[test]
2014    fn repl_input_complete_for_balanced_match_block() {
2015        let input = "let b = match a {\n    Some(String) => 2,\n    _ => 3,\n};";
2016        assert!(super::is_repl_input_complete(input));
2017    }
2018
2019    #[test]
2020    fn repl_input_incomplete_for_open_brace() {
2021        assert!(!super::is_repl_input_complete("let b = match a {"));
2022    }
2023
2024    #[test]
2025    fn repl_input_incomplete_for_unclosed_string() {
2026        assert!(!super::is_repl_input_complete("let s = \"hello"));
2027    }
2028
2029    #[test]
2030    fn repl_input_incomplete_for_unclosed_block_comment() {
2031        assert!(!super::is_repl_input_complete("let a = 1; /* comment"));
2032    }
2033
2034    #[test]
2035    fn repl_input_ignores_comment_delimiters() {
2036        assert!(super::is_repl_input_complete("// {\nlet a = 1;"));
2037    }
2038
2039    #[test]
2040    fn repl_input_incomplete_for_trailing_operator() {
2041        assert!(!super::is_repl_input_complete("let a = 1 +"));
2042    }
2043}