chore(fmt): add legacy stubs and strip trailing whitespace to unblock cargo fmt

This commit is contained in:
Selfhosting Dev
2025-09-17 07:43:07 +09:00
parent fcf8ce1f3c
commit adbb0201a9
385 changed files with 35622 additions and 15004 deletions

View File

@ -1,6 +1,6 @@
use super::super::NyashRunner;
#[cfg(feature = "cranelift-jit")]
use std::{process::Command, process};
use std::{process, process::Command};
impl NyashRunner {
/// Execute AOT compilation mode (split)
@ -11,7 +11,16 @@ impl NyashRunner {
let status = if cfg!(target_os = "windows") {
// Use PowerShell helper; falls back to bash if available inside the script
Command::new("powershell")
.args(["-ExecutionPolicy","Bypass","-File","tools/build_aot.ps1","-Input", filename, "-Out", &format!("{}.exe", output)])
.args([
"-ExecutionPolicy",
"Bypass",
"-File",
"tools/build_aot.ps1",
"-Input",
filename,
"-Out",
&format!("{}.exe", output),
])
.status()
} else {
Command::new("bash")
@ -20,15 +29,24 @@ impl NyashRunner {
};
match status {
Ok(s) if s.success() => {
println!("✅ AOT compilation successful!\nExecutable written to: {}", output);
println!(
"✅ AOT compilation successful!\nExecutable written to: {}",
output
);
}
Ok(s) => {
eprintln!("❌ AOT compilation failed (exit={} ). See logs above.", s.code().unwrap_or(-1));
eprintln!(
"❌ AOT compilation failed (exit={} ). See logs above.",
s.code().unwrap_or(-1)
);
process::exit(1);
}
Err(e) => {
eprintln!("❌ Failed to invoke build_aot.sh: {}", e);
eprintln!("Hint: ensure bash is available, or run: bash tools/build_aot.sh {} -o {}", filename, output);
eprintln!(
"Hint: ensure bash is available, or run: bash tools/build_aot.sh {} -o {}",
filename, output
);
process::exit(1);
}
}

View File

@ -1,10 +1,15 @@
use super::super::NyashRunner;
use nyash_rust::{parser::NyashParser, interpreter::NyashInterpreter, mir::MirCompiler, backend::VM};
use nyash_rust::{
backend::VM, interpreter::NyashInterpreter, mir::MirCompiler, parser::NyashParser,
};
impl NyashRunner {
/// Execute benchmark mode (split)
pub(crate) fn execute_benchmark_mode(&self) {
println!("🏁 Running benchmark mode with {} iterations", self.config.iterations);
println!(
"🏁 Running benchmark mode with {} iterations",
self.config.iterations
);
// Tests: some run on all backends, some are JIT+f64 only
// Third element indicates JIT+f64 only (skip VM/Interpreter)
let tests: Vec<(&str, &str, bool)> = vec![
@ -63,14 +68,21 @@ impl NyashRunner {
println!("\n====================================");
println!("🧪 Test: {}", name);
if jit_f64_only {
println!("(JIT+f64 only) Skipping VM/Interpreter; requires --features cranelift-jit");
println!(
"(JIT+f64 only) Skipping VM/Interpreter; requires --features cranelift-jit"
);
// Warmup JIT
let warmup = (self.config.iterations / 10).max(1);
self.bench_jit(code, warmup);
// Measured
let jit_time = self.bench_jit(code, self.config.iterations);
println!("\n📊 Performance Summary [{}]:", name);
println!(" JIT f64 ops: {} iters in {:?} ({:.2} ops/sec)", self.config.iterations, jit_time, self.config.iterations as f64 / jit_time.as_secs_f64());
println!(
" JIT f64 ops: {} iters in {:?} ({:.2} ops/sec)",
self.config.iterations,
jit_time,
self.config.iterations as f64 / jit_time.as_secs_f64()
);
} else {
// Quick correctness check across modes (golden): Interpreter vs VM vs VM+JIT
if let Err(e) = self.verify_outputs_match(code) {
@ -93,8 +105,28 @@ impl NyashRunner {
let vm_vs_interp = interpreter_time.as_secs_f64() / vm_time.as_secs_f64();
let jit_vs_vm = vm_time.as_secs_f64() / jit_time.as_secs_f64();
println!("\n📊 Performance Summary [{}]:", name);
println!(" VM is {:.2}x {} than Interpreter", if vm_vs_interp > 1.0 { vm_vs_interp } else { 1.0 / vm_vs_interp }, if vm_vs_interp > 1.0 { "faster" } else { "slower" });
println!(" JIT is {:.2}x {} than VM (note: compile cost included)", if jit_vs_vm > 1.0 { jit_vs_vm } else { 1.0 / jit_vs_vm }, if jit_vs_vm > 1.0 { "faster" } else { "slower" });
println!(
" VM is {:.2}x {} than Interpreter",
if vm_vs_interp > 1.0 {
vm_vs_interp
} else {
1.0 / vm_vs_interp
},
if vm_vs_interp > 1.0 {
"faster"
} else {
"slower"
}
);
println!(
" JIT is {:.2}x {} than VM (note: compile cost included)",
if jit_vs_vm > 1.0 {
jit_vs_vm
} else {
1.0 / jit_vs_vm
},
if jit_vs_vm > 1.0 { "faster" } else { "slower" }
);
}
}
}
@ -110,7 +142,12 @@ impl NyashRunner {
}
}
let elapsed = start.elapsed();
println!(" ⚡ Interpreter: {} iters in {:?} ({:.2} ops/sec)", iters, elapsed, iters as f64 / elapsed.as_secs_f64());
println!(
" ⚡ Interpreter: {} iters in {:?} ({:.2} ops/sec)",
iters,
elapsed,
iters as f64 / elapsed.as_secs_f64()
);
elapsed
}
@ -126,7 +163,12 @@ impl NyashRunner {
}
}
let elapsed = start.elapsed();
println!(" 🚀 VM: {} iters in {:?} ({:.2} ops/sec)", iters, elapsed, iters as f64 / elapsed.as_secs_f64());
println!(
" 🚀 VM: {} iters in {:?} ({:.2} ops/sec)",
iters,
elapsed,
iters as f64 / elapsed.as_secs_f64()
);
elapsed
}
@ -134,8 +176,12 @@ impl NyashRunner {
// Force JIT mode for this run
std::env::set_var("NYASH_JIT_EXEC", "1");
std::env::set_var("NYASH_JIT_THRESHOLD", "1");
if self.config.jit_stats { std::env::set_var("NYASH_JIT_STATS", "1"); }
if self.config.jit_stats_json { std::env::set_var("NYASH_JIT_STATS_JSON", "1"); }
if self.config.jit_stats {
std::env::set_var("NYASH_JIT_STATS", "1");
}
if self.config.jit_stats_json {
std::env::set_var("NYASH_JIT_STATS_JSON", "1");
}
let start = std::time::Instant::now();
for _ in 0..iters {
if let Ok(ast) = NyashParser::parse_from_string(code) {
@ -147,7 +193,12 @@ impl NyashRunner {
}
}
let elapsed = start.elapsed();
println!(" 🔥 JIT: {} iters in {:?} ({:.2} ops/sec)", iters, elapsed, iters as f64 / elapsed.as_secs_f64());
println!(
" 🔥 JIT: {} iters in {:?} ({:.2} ops/sec)",
iters,
elapsed,
iters as f64 / elapsed.as_secs_f64()
);
elapsed
}
@ -155,22 +206,28 @@ impl NyashRunner {
fn verify_outputs_match(&self, code: &str) -> Result<(), String> {
// VM
let vm_out = {
let ast = NyashParser::parse_from_string(code).map_err(|e| format!("vm parse: {}", e))?;
let ast =
NyashParser::parse_from_string(code).map_err(|e| format!("vm parse: {}", e))?;
let mut mc = MirCompiler::new();
let cr = mc.compile(ast).map_err(|e| format!("vm compile: {}", e))?;
let mut vm = VM::new();
let out = vm.execute_module(&cr.module).map_err(|e| format!("vm exec: {}", e))?;
let out = vm
.execute_module(&cr.module)
.map_err(|e| format!("vm exec: {}", e))?;
out.to_string_box().value
};
// VM+JIT
let jit_out = {
std::env::set_var("NYASH_JIT_EXEC", "1");
std::env::set_var("NYASH_JIT_THRESHOLD", "1");
let ast = NyashParser::parse_from_string(code).map_err(|e| format!("jit parse: {}", e))?;
let ast =
NyashParser::parse_from_string(code).map_err(|e| format!("jit parse: {}", e))?;
let mut mc = MirCompiler::new();
let cr = mc.compile(ast).map_err(|e| format!("jit compile: {}", e))?;
let mut vm = VM::new();
let out = vm.execute_module(&cr.module).map_err(|e| format!("jit exec: {}", e))?;
let out = vm
.execute_module(&cr.module)
.map_err(|e| format!("jit exec: {}", e))?;
out.to_string_box().value
};
if vm_out != jit_out {

View File

@ -1,7 +1,7 @@
use crate::parser::NyashParser;
use crate::interpreter::NyashInterpreter;
use crate::runner_plugin_init;
use crate::parser::NyashParser;
use crate::runner::pipeline::{resolve_using_target, UsingContext};
use crate::runner_plugin_init;
use std::{fs, process};
/// Execute Nyash file with interpreter
@ -22,11 +22,11 @@ pub fn execute_nyash_file(filename: &str, debug_fuel: Option<usize>) {
println!("📝 File contents:\n{}", code);
println!("\n🚀 Parsing and executing...\n");
// Test: immediate file creation (use relative path to avoid sandbox issues)
std::fs::create_dir_all("development/debug_hang_issue").ok();
std::fs::write("development/debug_hang_issue/test.txt", "START").ok();
// Optional: using pre-processing (strip lines and register modules)
let enable_using = std::env::var("NYASH_ENABLE_USING").ok().as_deref() == Some("1");
let mut code_ref: std::borrow::Cow<'_, str> = std::borrow::Cow::Borrowed(&code);
@ -39,13 +39,25 @@ pub fn execute_nyash_file(filename: &str, debug_fuel: Option<usize>) {
let rest0 = t.strip_prefix("using ").unwrap().trim();
let rest0 = rest0.strip_suffix(';').unwrap_or(rest0).trim();
let (target, alias) = if let Some(pos) = rest0.find(" as ") {
(rest0[..pos].trim().to_string(), Some(rest0[pos+4..].trim().to_string()))
} else { (rest0.to_string(), None) };
let is_path = target.starts_with('"') || target.starts_with("./") || target.starts_with('/') || target.ends_with(".nyash");
(
rest0[..pos].trim().to_string(),
Some(rest0[pos + 4..].trim().to_string()),
)
} else {
(rest0.to_string(), None)
};
let is_path = target.starts_with('"')
|| target.starts_with("./")
|| target.starts_with('/')
|| target.ends_with(".nyash");
if is_path {
let path = target.trim_matches('"').to_string();
let name = alias.clone().unwrap_or_else(|| {
std::path::Path::new(&path).file_stem().and_then(|s| s.to_str()).unwrap_or("module").to_string()
std::path::Path::new(&path)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("module")
.to_string()
});
used_names.push((name, Some(path)));
} else {
@ -57,7 +69,11 @@ pub fn execute_nyash_file(filename: &str, debug_fuel: Option<usize>) {
out.push('\n');
}
// Resolve and register
let using_ctx = UsingContext { using_paths: vec!["apps".into(), "lib".into(), ".".into()], pending_modules: vec![], aliases: std::collections::HashMap::new() };
let using_ctx = UsingContext {
using_paths: vec!["apps".into(), "lib".into(), ".".into()],
pending_modules: vec![],
aliases: std::collections::HashMap::new(),
};
let strict = std::env::var("NYASH_USING_STRICT").ok().as_deref() == Some("1");
let verbose = std::env::var("NYASH_CLI_VERBOSE").ok().as_deref() == Some("1");
let ctx_dir = std::path::Path::new(filename).parent();
@ -66,12 +82,24 @@ pub fn execute_nyash_file(filename: &str, debug_fuel: Option<usize>) {
let sb = crate::box_trait::StringBox::new(path);
crate::runtime::modules_registry::set(ns_or_alias, Box::new(sb));
} else {
match resolve_using_target(&ns_or_alias, false, &using_ctx.pending_modules, &using_ctx.using_paths, &using_ctx.aliases, ctx_dir, strict, verbose) {
match resolve_using_target(
&ns_or_alias,
false,
&using_ctx.pending_modules,
&using_ctx.using_paths,
&using_ctx.aliases,
ctx_dir,
strict,
verbose,
) {
Ok(value) => {
let sb = crate::box_trait::StringBox::new(value);
crate::runtime::modules_registry::set(ns_or_alias, Box::new(sb));
}
Err(e) => { eprintln!("❌ using: {}", e); std::process::exit(1); }
Err(e) => {
eprintln!("❌ using: {}", e);
std::process::exit(1);
}
}
}
}
@ -84,30 +112,30 @@ pub fn execute_nyash_file(filename: &str, debug_fuel: Option<usize>) {
Ok(ast) => {
eprintln!("🔍 DEBUG: Parse completed, AST created");
ast
},
}
Err(e) => {
eprintln!("❌ Parse error: {}", e);
process::exit(1);
}
};
eprintln!("🔍 DEBUG: About to print parse success message...");
println!("✅ Parse successful!");
eprintln!("🔍 DEBUG: Parse success message printed");
// Debug log file write
if let Ok(mut file) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open("development/debug_hang_issue/debug_trace.log")
.open("development/debug_hang_issue/debug_trace.log")
{
use std::io::Write;
let _ = writeln!(file, "=== MAIN: Parse successful ===");
let _ = file.flush();
}
eprintln!("🔍 DEBUG: Creating interpreter...");
// Execute the AST
let mut interpreter = NyashInterpreter::new();
eprintln!("🔍 DEBUG: Starting execution...");
@ -116,9 +144,12 @@ pub fn execute_nyash_file(filename: &str, debug_fuel: Option<usize>) {
println!("✅ Execution completed successfully!");
println!("Result: {}", result.to_string_box().value);
// Structured concurrency: best-effort join of spawned tasks at program end
let join_ms: u64 = std::env::var("NYASH_JOIN_ALL_MS").ok().and_then(|s| s.parse().ok()).unwrap_or(2000);
let join_ms: u64 = std::env::var("NYASH_JOIN_ALL_MS")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(2000);
crate::runtime::global_hooks::join_all_registered_futures(join_ms);
},
}
Err(e) => {
// Use enhanced error reporting with source context
eprintln!("❌ Runtime error:\n{}", e.detailed_message(Some(&code)));

View File

@ -1,6 +1,9 @@
use super::super::NyashRunner;
use nyash_rust::{parser::NyashParser, mir::{MirCompiler, MirInstruction}};
use nyash_rust::mir::passes::method_id_inject::inject_method_ids;
use nyash_rust::{
mir::{MirCompiler, MirInstruction},
parser::NyashParser,
};
use std::{fs, process};
impl NyashRunner {
@ -12,20 +15,29 @@ impl NyashRunner {
// Read the file
let code = match fs::read_to_string(filename) {
Ok(content) => content,
Err(e) => { eprintln!("❌ Error reading file {}: {}", filename, e); process::exit(1); }
Err(e) => {
eprintln!("❌ Error reading file {}: {}", filename, e);
process::exit(1);
}
};
// Parse to AST
let ast = match NyashParser::parse_from_string(&code) {
Ok(ast) => ast,
Err(e) => { eprintln!("❌ Parse error: {}", e); process::exit(1); }
Err(e) => {
eprintln!("❌ Parse error: {}", e);
process::exit(1);
}
};
// Compile to MIR
let mut mir_compiler = MirCompiler::new();
let compile_result = match mir_compiler.compile(ast) {
Ok(result) => result,
Err(e) => { eprintln!("❌ MIR compilation error: {}", e); process::exit(1); }
Err(e) => {
eprintln!("❌ MIR compilation error: {}", e);
process::exit(1);
}
};
println!("📊 MIR Module compiled successfully!");
@ -46,7 +58,9 @@ impl NyashRunner {
// Harness path (optional): if NYASH_LLVM_USE_HARNESS=1, try Python/llvmlite first.
let use_harness = crate::config::env::llvm_use_harness();
if use_harness {
if let Some(parent) = std::path::Path::new(&_out_path).parent() { let _ = std::fs::create_dir_all(parent); }
if let Some(parent) = std::path::Path::new(&_out_path).parent() {
let _ = std::fs::create_dir_all(parent);
}
let py = which::which("python3").ok();
if let Some(py3) = py {
let harness = std::path::Path::new("tools/llvmlite_harness.py");
@ -55,34 +69,61 @@ impl NyashRunner {
let tmp_dir = std::path::Path::new("tmp");
let _ = std::fs::create_dir_all(tmp_dir);
let mir_json_path = tmp_dir.join("nyash_harness_mir.json");
if let Err(e) = crate::runner::mir_json_emit::emit_mir_json_for_harness(&module, &mir_json_path) {
if let Err(e) = crate::runner::mir_json_emit::emit_mir_json_for_harness(
&module,
&mir_json_path,
) {
eprintln!("❌ MIR JSON emit error: {}", e);
process::exit(1);
}
if std::env::var("NYASH_CLI_VERBOSE").ok().as_deref() == Some("1") {
eprintln!("[Runner/LLVM] using llvmlite harness → {} (mir={})", _out_path, mir_json_path.display());
eprintln!(
"[Runner/LLVM] using llvmlite harness → {} (mir={})",
_out_path,
mir_json_path.display()
);
}
// 2) Run harness with --in/--out失敗時は即エラー
let status = std::process::Command::new(py3)
.args([harness.to_string_lossy().as_ref(), "--in", &mir_json_path.display().to_string(), "--out", &_out_path])
.status().map_err(|e| format!("spawn harness: {}", e)).unwrap();
.args([
harness.to_string_lossy().as_ref(),
"--in",
&mir_json_path.display().to_string(),
"--out",
&_out_path,
])
.status()
.map_err(|e| format!("spawn harness: {}", e))
.unwrap();
if !status.success() {
eprintln!("❌ llvmlite harness failed (status={})", status.code().unwrap_or(-1));
eprintln!(
"❌ llvmlite harness failed (status={})",
status.code().unwrap_or(-1)
);
process::exit(1);
}
// Verify
match std::fs::metadata(&_out_path) {
Ok(meta) if meta.len() > 0 => {
if std::env::var("NYASH_CLI_VERBOSE").ok().as_deref() == Some("1") {
eprintln!("[LLVM] object emitted by harness: {} ({} bytes)", _out_path, meta.len());
}
return;
}
_ => {
eprintln!("❌ harness output not found or empty: {}", _out_path);
process::exit(1);
match std::fs::metadata(&_out_path) {
Ok(meta) if meta.len() > 0 => {
if std::env::var("NYASH_CLI_VERBOSE").ok().as_deref()
== Some("1")
{
eprintln!(
"[LLVM] object emitted by harness: {} ({} bytes)",
_out_path,
meta.len()
);
}
return;
}
_ => {
eprintln!(
"❌ harness output not found or empty: {}",
_out_path
);
process::exit(1);
}
}
} else {
eprintln!("❌ harness script not found: {}", harness.display());
process::exit(1);
@ -99,11 +140,18 @@ impl NyashRunner {
process::exit(1);
}
if std::env::var("NYASH_CLI_VERBOSE").ok().as_deref() == Some("1") {
eprintln!("[LLVM] object emitted: {} ({} bytes)", _out_path, meta.len());
eprintln!(
"[LLVM] object emitted: {} ({} bytes)",
_out_path,
meta.len()
);
}
}
Err(e) => {
eprintln!("❌ harness output not found after emit: {} ({})", _out_path, e);
eprintln!(
"❌ harness output not found after emit: {} ({})",
_out_path, e
);
process::exit(1);
}
}
@ -117,7 +165,13 @@ impl NyashRunner {
let _ = std::fs::create_dir_all(parent);
}
if std::env::var("NYASH_CLI_VERBOSE").ok().as_deref() == Some("1") {
eprintln!("[Runner/LLVM] emitting object to {} (cwd={})", _out_path, std::env::current_dir().map(|p| p.display().to_string()).unwrap_or_default());
eprintln!(
"[Runner/LLVM] emitting object to {} (cwd={})",
_out_path,
std::env::current_dir()
.map(|p| p.display().to_string())
.unwrap_or_default()
);
}
if let Err(e) = llvm_compile_to_object(&module, &_out_path) {
eprintln!("❌ LLVM object emit error: {}", e);
@ -126,10 +180,17 @@ impl NyashRunner {
match std::fs::metadata(&_out_path) {
Ok(meta) if meta.len() > 0 => {
if std::env::var("NYASH_CLI_VERBOSE").ok().as_deref() == Some("1") {
eprintln!("[LLVM] object emitted: {} ({} bytes)", _out_path, meta.len());
eprintln!(
"[LLVM] object emitted: {} ({} bytes)",
_out_path,
meta.len()
);
}
}
_ => { eprintln!("❌ LLVM object not found or empty: {}", _out_path); process::exit(1); }
_ => {
eprintln!("❌ LLVM object not found or empty: {}", _out_path);
process::exit(1);
}
}
return;
}
@ -156,8 +217,11 @@ impl NyashRunner {
println!("✅ LLVM execution completed (non-integer result)!");
println!("📊 Result: {}", result.to_string_box().value);
}
},
Err(e) => { eprintln!("❌ LLVM execution error: {}", e); process::exit(1); }
}
Err(e) => {
eprintln!("❌ LLVM execution error: {}", e);
process::exit(1);
}
}
}
#[cfg(all(not(feature = "llvm-inkwell-legacy")))]
@ -168,8 +232,14 @@ impl NyashRunner {
for (_bid, block) in &main_func.blocks {
for inst in &block.instructions {
match inst {
MirInstruction::Return { value: Some(_) } => { println!("✅ Mock exit code: 42"); process::exit(42); }
MirInstruction::Return { value: None } => { println!("✅ Mock exit code: 0"); process::exit(0); }
MirInstruction::Return { value: Some(_) } => {
println!("✅ Mock exit code: 42");
process::exit(42);
}
MirInstruction::Return { value: None } => {
println!("✅ Mock exit code: 0");
process::exit(0);
}
_ => {}
}
}

View File

@ -1,5 +1,8 @@
use super::super::NyashRunner;
use nyash_rust::{parser::NyashParser, mir::{MirCompiler, MirPrinter}};
use nyash_rust::{
mir::{MirCompiler, MirPrinter},
parser::NyashParser,
};
use std::{fs, process};
impl NyashRunner {
@ -8,20 +11,29 @@ impl NyashRunner {
// Read the file
let code = match fs::read_to_string(filename) {
Ok(content) => content,
Err(e) => { eprintln!("❌ Error reading file {}: {}", filename, e); process::exit(1); }
Err(e) => {
eprintln!("❌ Error reading file {}: {}", filename, e);
process::exit(1);
}
};
// Parse to AST
let ast = match NyashParser::parse_from_string(&code) {
Ok(ast) => ast,
Err(e) => { eprintln!("❌ Parse error: {}", e); process::exit(1); }
Err(e) => {
eprintln!("❌ Parse error: {}", e);
process::exit(1);
}
};
// Compile to MIR (opt passes configurable)
let mut mir_compiler = MirCompiler::with_options(!self.config.no_optimize);
let compile_result = match mir_compiler.compile(ast) {
Ok(result) => result,
Err(e) => { eprintln!("❌ MIR compilation error: {}", e); process::exit(1); }
Err(e) => {
eprintln!("❌ MIR compilation error: {}", e);
process::exit(1);
}
};
// Verify MIR if requested
@ -31,7 +43,9 @@ impl NyashRunner {
Ok(()) => println!("✅ MIR verification passed!"),
Err(errors) => {
eprintln!("❌ MIR verification failed:");
for error in errors { eprintln!("{}", error); }
for error in errors {
eprintln!("{}", error);
}
process::exit(1);
}
}
@ -39,11 +53,16 @@ impl NyashRunner {
// Dump MIR if requested
if self.config.dump_mir {
let mut printer = if self.config.mir_verbose { MirPrinter::verbose() } else { MirPrinter::new() };
if self.config.mir_verbose_effects { printer.set_show_effects_inline(true); }
let mut printer = if self.config.mir_verbose {
MirPrinter::verbose()
} else {
MirPrinter::new()
};
if self.config.mir_verbose_effects {
printer.set_show_effects_inline(true);
}
println!("🚀 MIR Output for {}:", filename);
println!("{}", printer.print_module(&compile_result.module));
}
}
}

View File

@ -1,8 +1,8 @@
pub mod bench;
pub mod interpreter;
pub mod llvm;
pub mod mir;
pub mod vm;
pub mod llvm;
pub mod bench;
#[cfg(feature = "cranelift-jit")]
pub mod aot;

View File

@ -1,7 +1,16 @@
use super::super::NyashRunner;
use nyash_rust::{parser::NyashParser, mir::MirCompiler, backend::VM, runtime::{NyashRuntime, NyashRuntimeBuilder}, ast::ASTNode, core::model::BoxDeclaration as CoreBoxDecl, interpreter::SharedState, box_factory::user_defined::UserDefinedBoxFactory};
use std::{fs, process};
use nyash_rust::{
ast::ASTNode,
backend::VM,
box_factory::user_defined::UserDefinedBoxFactory,
core::model::BoxDeclaration as CoreBoxDecl,
interpreter::SharedState,
mir::MirCompiler,
parser::NyashParser,
runtime::{NyashRuntime, NyashRuntimeBuilder},
};
use std::sync::Arc;
use std::{fs, process};
impl NyashRunner {
/// Execute VM mode (split)
@ -18,7 +27,9 @@ impl NyashRunner {
// Init plugin host from nyash.toml if not yet loaded
let need_init = {
let host = nyash_rust::runtime::get_global_plugin_host();
host.read().map(|h| h.config_ref().is_none()).unwrap_or(true)
host.read()
.map(|h| h.config_ref().is_none())
.unwrap_or(true)
};
if need_init {
let _ = nyash_rust::runtime::init_global_plugin_host("nyash.toml");
@ -29,16 +40,29 @@ impl NyashRunner {
std::env::set_var("NYASH_USE_PLUGIN_BUILTINS", "1");
}
// Build stable override list
let mut override_types: Vec<String> = if let Ok(list) = std::env::var("NYASH_PLUGIN_OVERRIDE_TYPES") {
list.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()
} else { vec![] };
let mut override_types: Vec<String> =
if let Ok(list) = std::env::var("NYASH_PLUGIN_OVERRIDE_TYPES") {
list.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect()
} else {
vec![]
};
for t in [
"FileBox", "TOMLBox", // IO/config
"ConsoleBox", "StringBox", "IntegerBox", // core value-ish
"ArrayBox", "MapBox", // collections
"MathBox", "TimeBox" // math/time helpers
"FileBox",
"TOMLBox", // IO/config
"ConsoleBox",
"StringBox",
"IntegerBox", // core value-ish
"ArrayBox",
"MapBox", // collections
"MathBox",
"TimeBox", // math/time helpers
] {
if !override_types.iter().any(|x| x == t) { override_types.push(t.to_string()); }
if !override_types.iter().any(|x| x == t) {
override_types.push(t.to_string());
}
}
std::env::set_var("NYASH_PLUGIN_OVERRIDE_TYPES", override_types.join(","));
@ -46,11 +70,23 @@ impl NyashRunner {
if std::env::var("NYASH_VM_PLUGIN_STRICT").ok().as_deref() == Some("1") {
let v2 = nyash_rust::runtime::get_global_registry();
let mut missing: Vec<String> = Vec::new();
for t in ["FileBox","ConsoleBox","ArrayBox","MapBox","StringBox","IntegerBox"] {
if v2.get_provider(t).is_none() { missing.push(t.to_string()); }
for t in [
"FileBox",
"ConsoleBox",
"ArrayBox",
"MapBox",
"StringBox",
"IntegerBox",
] {
if v2.get_provider(t).is_none() {
missing.push(t.to_string());
}
}
if !missing.is_empty() {
eprintln!("❌ VM plugin-first strict: missing providers for: {:?}", missing);
eprintln!(
"❌ VM plugin-first strict: missing providers for: {:?}",
missing
);
std::process::exit(1);
}
}
@ -59,13 +95,19 @@ impl NyashRunner {
// Read the file
let code = match fs::read_to_string(filename) {
Ok(content) => content,
Err(e) => { eprintln!("❌ Error reading file {}: {}", filename, e); process::exit(1); }
Err(e) => {
eprintln!("❌ Error reading file {}: {}", filename, e);
process::exit(1);
}
};
// Parse to AST
let ast = match NyashParser::parse_from_string(&code) {
Ok(ast) => ast,
Err(e) => { eprintln!("❌ Parse error: {}", e); process::exit(1); }
Err(e) => {
eprintln!("❌ Parse error: {}", e);
process::exit(1);
}
};
// Prepare runtime and collect Box declarations for VM user-defined types
@ -80,7 +122,9 @@ impl NyashRunner {
let mut shared = SharedState::new();
shared.box_declarations = rt.box_declarations.clone();
let udf = Arc::new(UserDefinedBoxFactory::new(shared));
if let Ok(mut reg) = rt.box_registry.lock() { reg.register(udf); }
if let Ok(mut reg) = rt.box_registry.lock() {
reg.register(udf);
}
rt
};
@ -88,20 +132,30 @@ impl NyashRunner {
let mut mir_compiler = MirCompiler::with_options(!self.config.no_optimize);
let compile_result = match mir_compiler.compile(ast) {
Ok(result) => result,
Err(e) => { eprintln!("❌ MIR compilation error: {}", e); process::exit(1); }
Err(e) => {
eprintln!("❌ MIR compilation error: {}", e);
process::exit(1);
}
};
// Optional: demo scheduling hook
if std::env::var("NYASH_SCHED_DEMO").ok().as_deref() == Some("1") {
if let Some(s) = &runtime.scheduler {
// Immediate task
s.spawn("demo-immediate", Box::new(|| {
println!("[SCHED] immediate task ran at safepoint");
}));
s.spawn(
"demo-immediate",
Box::new(|| {
println!("[SCHED] immediate task ran at safepoint");
}),
);
// Delayed task
s.spawn_after(0, "demo-delayed", Box::new(|| {
println!("[SCHED] delayed task ran at safepoint");
}));
s.spawn_after(
0,
"demo-delayed",
Box::new(|| {
println!("[SCHED] delayed task ran at safepoint");
}),
);
}
}
@ -130,17 +184,28 @@ impl NyashRunner {
let tmp_dir = std::path::Path::new("tmp");
let _ = std::fs::create_dir_all(tmp_dir);
let mir_json_path = tmp_dir.join("nyash_pyvm_mir.json");
if let Err(e) = crate::runner::mir_json_emit::emit_mir_json_for_harness(&module_vm, &mir_json_path) {
if let Err(e) = crate::runner::mir_json_emit::emit_mir_json_for_harness(
&module_vm,
&mir_json_path,
) {
eprintln!("❌ PyVM MIR JSON emit error: {}", e);
process::exit(1);
}
if std::env::var("NYASH_CLI_VERBOSE").ok().as_deref() == Some("1") {
eprintln!("[Runner/VM] using PyVM → {} (mir={})", filename, mir_json_path.display());
eprintln!(
"[Runner/VM] using PyVM → {} (mir={})",
filename,
mir_json_path.display()
);
}
// Determine entry function hint (prefer Main.main if present)
let entry = if module_vm.functions.contains_key("Main.main") {
"Main.main"
} else if module_vm.functions.contains_key("main") { "main" } else { "Main.main" };
} else if module_vm.functions.contains_key("main") {
"main"
} else {
"Main.main"
};
// Spawn runner
let status = std::process::Command::new(py3)
.args([
@ -178,20 +243,24 @@ impl NyashRunner {
let mut vm = VM::with_runtime(runtime);
match vm.execute_module(&module_vm) {
Ok(result) => {
if !quiet_pipe { println!("✅ VM execution completed successfully!"); }
if !quiet_pipe {
println!("✅ VM execution completed successfully!");
}
// Pretty-print with coercions for plugin-backed values
// Prefer MIR signature when available, but fall back to runtime coercions to keep VM/JIT consistent.
let (ety, sval) = if let Some(func) = compile_result.module.functions.get("main") {
use nyash_rust::mir::MirType;
use nyash_rust::box_trait::{IntegerBox, BoolBox, StringBox};
use nyash_rust::box_trait::{BoolBox, IntegerBox, StringBox};
use nyash_rust::boxes::FloatBox;
use nyash_rust::mir::MirType;
match &func.signature.return_type {
MirType::Float => {
if let Some(fb) = result.as_any().downcast_ref::<FloatBox>() {
("Float", format!("{}", fb.value))
} else if let Some(ib) = result.as_any().downcast_ref::<IntegerBox>() {
("Float", format!("{}", ib.value as f64))
} else if let Some(s) = nyash_rust::runtime::semantics::coerce_to_string(result.as_ref()) {
} else if let Some(s) =
nyash_rust::runtime::semantics::coerce_to_string(result.as_ref())
{
("String", s)
} else {
(result.type_name(), result.to_string_box().value)
@ -200,7 +269,9 @@ impl NyashRunner {
MirType::Integer => {
if let Some(ib) = result.as_any().downcast_ref::<IntegerBox>() {
("Integer", ib.value.to_string())
} else if let Some(i) = nyash_rust::runtime::semantics::coerce_to_i64(result.as_ref()) {
} else if let Some(i) =
nyash_rust::runtime::semantics::coerce_to_i64(result.as_ref())
{
("Integer", i.to_string())
} else {
(result.type_name(), result.to_string_box().value)
@ -218,50 +289,72 @@ impl NyashRunner {
MirType::String => {
if let Some(sb) = result.as_any().downcast_ref::<StringBox>() {
("String", sb.value.clone())
} else if let Some(s) = nyash_rust::runtime::semantics::coerce_to_string(result.as_ref()) {
} else if let Some(s) =
nyash_rust::runtime::semantics::coerce_to_string(result.as_ref())
{
("String", s)
} else {
(result.type_name(), result.to_string_box().value)
}
}
_ => {
if let Some(i) = nyash_rust::runtime::semantics::coerce_to_i64(result.as_ref()) {
if let Some(i) =
nyash_rust::runtime::semantics::coerce_to_i64(result.as_ref())
{
("Integer", i.to_string())
} else if let Some(s) = nyash_rust::runtime::semantics::coerce_to_string(result.as_ref()) {
} else if let Some(s) =
nyash_rust::runtime::semantics::coerce_to_string(result.as_ref())
{
("String", s)
} else { (result.type_name(), result.to_string_box().value) }
} else {
(result.type_name(), result.to_string_box().value)
}
}
}
} else {
if let Some(i) = nyash_rust::runtime::semantics::coerce_to_i64(result.as_ref()) {
if let Some(i) = nyash_rust::runtime::semantics::coerce_to_i64(result.as_ref())
{
("Integer", i.to_string())
} else if let Some(s) = nyash_rust::runtime::semantics::coerce_to_string(result.as_ref()) {
} else if let Some(s) =
nyash_rust::runtime::semantics::coerce_to_string(result.as_ref())
{
("String", s)
} else { (result.type_name(), result.to_string_box().value) }
} else {
(result.type_name(), result.to_string_box().value)
}
};
if !quiet_pipe {
println!("ResultType(MIR): {}", ety);
println!("Result: {}", sval);
}
},
Err(e) => { eprintln!("❌ VM execution error: {}", e); process::exit(1); }
}
Err(e) => {
eprintln!("❌ VM execution error: {}", e);
process::exit(1);
}
}
}
/// Collect Box declarations from AST and register into runtime
pub(crate) fn collect_box_declarations(&self, ast: &ASTNode, runtime: &NyashRuntime) {
fn resolve_include_path(filename: &str) -> String {
if filename.starts_with("./") || filename.starts_with("../") { return filename.to_string(); }
if filename.starts_with("./") || filename.starts_with("../") {
return filename.to_string();
}
let parts: Vec<&str> = filename.splitn(2, '/').collect();
if parts.len() == 2 {
let root = parts[0]; let rest = parts[1];
let root = parts[0];
let rest = parts[1];
let cfg_path = "nyash.toml";
if let Ok(toml_str) = std::fs::read_to_string(cfg_path) {
if let Ok(toml_val) = toml::from_str::<toml::Value>(&toml_str) {
if let Some(include) = toml_val.get("include") {
if let Some(roots) = include.get("roots").and_then(|v| v.as_table()) {
if let Some(base) = roots.get(root).and_then(|v| v.as_str()) {
let mut b = base.to_string(); if !b.ends_with('/') && !b.ends_with('\\') { b.push('/'); }
let mut b = base.to_string();
if !b.ends_with('/') && !b.ends_with('\\') {
b.push('/');
}
return format!("{}{}", b, rest);
}
}
@ -274,10 +367,23 @@ impl NyashRunner {
use std::collections::HashSet;
fn walk_with_state(node: &ASTNode, runtime: &NyashRuntime, stack: &mut Vec<String>, visited: &mut HashSet<String>) {
fn walk_with_state(
node: &ASTNode,
runtime: &NyashRuntime,
stack: &mut Vec<String>,
visited: &mut HashSet<String>,
) {
match node {
ASTNode::Program { statements, .. } => { for st in statements { walk_with_state(st, runtime, stack, visited); } }
ASTNode::FunctionDeclaration { body, .. } => { for st in body { walk_with_state(st, runtime, stack, visited); } }
ASTNode::Program { statements, .. } => {
for st in statements {
walk_with_state(st, runtime, stack, visited);
}
}
ASTNode::FunctionDeclaration { body, .. } => {
for st in body {
walk_with_state(st, runtime, stack, visited);
}
}
ASTNode::Include { filename, .. } => {
let mut path = resolve_include_path(filename);
if std::path::Path::new(&path).is_dir() {
@ -305,42 +411,139 @@ impl NyashRunner {
stack.pop();
}
ASTNode::Assignment { target, value, .. } => {
walk_with_state(target, runtime, stack, visited); walk_with_state(value, runtime, stack, visited);
walk_with_state(target, runtime, stack, visited);
walk_with_state(value, runtime, stack, visited);
}
ASTNode::Return { value, .. } => { if let Some(v) = value { walk_with_state(v, runtime, stack, visited); } }
ASTNode::Print { expression, .. } => { walk_with_state(expression, runtime, stack, visited); }
ASTNode::If { condition, then_body, else_body, .. } => {
ASTNode::Return { value, .. } => {
if let Some(v) = value {
walk_with_state(v, runtime, stack, visited);
}
}
ASTNode::Print { expression, .. } => {
walk_with_state(expression, runtime, stack, visited);
}
ASTNode::If {
condition,
then_body,
else_body,
..
} => {
walk_with_state(condition, runtime, stack, visited);
for st in then_body { walk_with_state(st, runtime, stack, visited); }
if let Some(eb) = else_body { for st in eb { walk_with_state(st, runtime, stack, visited); } }
for st in then_body {
walk_with_state(st, runtime, stack, visited);
}
if let Some(eb) = else_body {
for st in eb {
walk_with_state(st, runtime, stack, visited);
}
}
}
ASTNode::Loop { condition, body, .. } => {
walk_with_state(condition, runtime, stack, visited); for st in body { walk_with_state(st, runtime, stack, visited); }
ASTNode::Loop {
condition, body, ..
} => {
walk_with_state(condition, runtime, stack, visited);
for st in body {
walk_with_state(st, runtime, stack, visited);
}
}
ASTNode::TryCatch { try_body, catch_clauses, finally_body, .. } => {
for st in try_body { walk_with_state(st, runtime, stack, visited); }
for cc in catch_clauses { for st in &cc.body { walk_with_state(st, runtime, stack, visited); } }
if let Some(fb) = finally_body { for st in fb { walk_with_state(st, runtime, stack, visited); } }
ASTNode::TryCatch {
try_body,
catch_clauses,
finally_body,
..
} => {
for st in try_body {
walk_with_state(st, runtime, stack, visited);
}
for cc in catch_clauses {
for st in &cc.body {
walk_with_state(st, runtime, stack, visited);
}
}
if let Some(fb) = finally_body {
for st in fb {
walk_with_state(st, runtime, stack, visited);
}
}
}
ASTNode::Throw { expression, .. } => {
walk_with_state(expression, runtime, stack, visited);
}
ASTNode::Throw { expression, .. } => { walk_with_state(expression, runtime, stack, visited); }
ASTNode::Local { initial_values, .. } => {
for iv in initial_values { if let Some(v) = iv { walk_with_state(v, runtime, stack, visited); } }
for iv in initial_values {
if let Some(v) = iv {
walk_with_state(v, runtime, stack, visited);
}
}
}
ASTNode::Outbox { initial_values, .. } => {
for iv in initial_values { if let Some(v) = iv { walk_with_state(v, runtime, stack, visited); } }
for iv in initial_values {
if let Some(v) = iv {
walk_with_state(v, runtime, stack, visited);
}
}
}
ASTNode::FunctionCall { arguments, .. } => { for a in arguments { walk_with_state(a, runtime, stack, visited); } }
ASTNode::MethodCall { object, arguments, .. } => { walk_with_state(object, runtime, stack, visited); for a in arguments { walk_with_state(a, runtime, stack, visited); } }
ASTNode::FieldAccess { object, .. } => { walk_with_state(object, runtime, stack, visited); }
ASTNode::New { arguments, .. } => { for a in arguments { walk_with_state(a, runtime, stack, visited); } }
ASTNode::BinaryOp { left, right, .. } => { walk_with_state(left, runtime, stack, visited); walk_with_state(right, runtime, stack, visited); }
ASTNode::UnaryOp { operand, .. } => { walk_with_state(operand, runtime, stack, visited); }
ASTNode::AwaitExpression { expression, .. } => { walk_with_state(expression, runtime, stack, visited); }
ASTNode::Arrow { sender, receiver, .. } => { walk_with_state(sender, runtime, stack, visited); walk_with_state(receiver, runtime, stack, visited); }
ASTNode::Nowait { expression, .. } => { walk_with_state(expression, runtime, stack, visited); }
ASTNode::BoxDeclaration { name, fields, public_fields, private_fields, methods, constructors, init_fields, weak_fields, is_interface, extends, implements, type_parameters, .. } => {
for (_mname, mnode) in methods { walk_with_state(mnode, runtime, stack, visited); }
for (_ckey, cnode) in constructors { walk_with_state(cnode, runtime, stack, visited); }
ASTNode::FunctionCall { arguments, .. } => {
for a in arguments {
walk_with_state(a, runtime, stack, visited);
}
}
ASTNode::MethodCall {
object, arguments, ..
} => {
walk_with_state(object, runtime, stack, visited);
for a in arguments {
walk_with_state(a, runtime, stack, visited);
}
}
ASTNode::FieldAccess { object, .. } => {
walk_with_state(object, runtime, stack, visited);
}
ASTNode::New { arguments, .. } => {
for a in arguments {
walk_with_state(a, runtime, stack, visited);
}
}
ASTNode::BinaryOp { left, right, .. } => {
walk_with_state(left, runtime, stack, visited);
walk_with_state(right, runtime, stack, visited);
}
ASTNode::UnaryOp { operand, .. } => {
walk_with_state(operand, runtime, stack, visited);
}
ASTNode::AwaitExpression { expression, .. } => {
walk_with_state(expression, runtime, stack, visited);
}
ASTNode::Arrow {
sender, receiver, ..
} => {
walk_with_state(sender, runtime, stack, visited);
walk_with_state(receiver, runtime, stack, visited);
}
ASTNode::Nowait { expression, .. } => {
walk_with_state(expression, runtime, stack, visited);
}
ASTNode::BoxDeclaration {
name,
fields,
public_fields,
private_fields,
methods,
constructors,
init_fields,
weak_fields,
is_interface,
extends,
implements,
type_parameters,
..
} => {
for (_mname, mnode) in methods {
walk_with_state(mnode, runtime, stack, visited);
}
for (_ckey, cnode) in constructors {
walk_with_state(cnode, runtime, stack, visited);
}
let decl = CoreBoxDecl {
name: name.clone(),
fields: fields.clone(),
@ -355,7 +558,9 @@ impl NyashRunner {
implements: implements.clone(),
type_parameters: type_parameters.clone(),
};
if let Ok(mut map) = runtime.box_declarations.write() { map.insert(name.clone(), decl); }
if let Ok(mut map) = runtime.box_declarations.write() {
map.insert(name.clone(), decl);
}
}
_ => {}
}