refactor: Gemini/ChatGPT collaborative refactoring + build fixes

Major changes:
- Split runner module: 1358→580 lines (via Gemini)
- Create new modules: dispatch.rs, selfhost.rs, pipeline.rs, pipe_io.rs
- Fix build errors from incomplete method migrations
- Add warning to CLAUDE.md about JIT/Cranelift not working
- Create interpreter.rs mode module
- Refactor loop builder into separate module

Build status:
-  Executable builds successfully
-  Basic execution works (tested with print)
- ⚠️ 106 warnings remain (to be cleaned up next)
- ⚠️ execute_mir_mode still in mod.rs (needs further migration)

Note: ChatGPT correctly fixed runner.execute_mir_mode() calls
that I incorrectly changed to super::modes::mir::

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Selfhosting Dev
2025-09-16 03:54:44 +09:00
parent f9bd13f4e4
commit 40db299bab
22 changed files with 425 additions and 613 deletions

View File

@ -0,0 +1,70 @@
use crate::parser::NyashParser;
use crate::interpreter::NyashInterpreter;
use std::{fs, process};
/// Execute Nyash file with interpreter
pub fn execute_nyash_file(filename: &str, debug_fuel: Option<usize>) {
// 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);
}
};
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();
// Parse the code with debug fuel limit
eprintln!("🔍 DEBUG: Starting parse with fuel: {:?}...", debug_fuel);
let ast = match NyashParser::parse_from_string_with_fuel(&code, debug_fuel) {
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")
{
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...");
match interpreter.execute(ast) {
Ok(result) => {
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);
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)));
process::exit(1);
}
}
}

View File

@ -1,5 +1,5 @@
use super::super::NyashRunner;
use nyash_rust::{parser::NyashParser, mir::{MirCompiler, MirInstruction}, box_trait::IntegerBox};
use nyash_rust::{parser::NyashParser, mir::{MirCompiler, MirInstruction}};
use nyash_rust::mir::passes::method_id_inject::inject_method_ids;
use std::{fs, process};
@ -40,13 +40,13 @@ impl NyashRunner {
}
// If explicit object path is requested, emit object only
if let Ok(out_path) = std::env::var("NYASH_LLVM_OBJ_OUT") {
if let Ok(_out_path) = std::env::var("NYASH_LLVM_OBJ_OUT") {
#[cfg(feature = "llvm-harness")]
{
// Harness path (optional): if NYASH_LLVM_USE_HARNESS=1, try Python/llvmlite first.
let use_harness = std::env::var("NYASH_LLVM_USE_HARNESS").ok().as_deref() == Some("1");
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");
@ -60,29 +60,29 @@ impl NyashRunner {
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])
.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));
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());
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);
}
return;
}
_ => {
eprintln!("❌ harness output not found or empty: {}", out_path);
process::exit(1);
}
}
} else {
eprintln!("❌ harness script not found: {}", harness.display());
process::exit(1);
@ -92,18 +92,18 @@ impl NyashRunner {
process::exit(1);
}
// Verify object presence and size (>0)
match std::fs::metadata(&out_path) {
match std::fs::metadata(&_out_path) {
Ok(meta) => {
if meta.len() == 0 {
eprintln!("❌ harness object is empty: {}", out_path);
eprintln!("❌ harness object is empty: {}", _out_path);
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);
}
}
@ -113,23 +113,23 @@ impl NyashRunner {
{
use nyash_rust::backend::llvm_compile_to_object;
// Ensure parent directory exists for the object file
if let Some(parent) = std::path::Path::new(&out_path).parent() {
if let Some(parent) = std::path::Path::new(&_out_path).parent() {
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) {
if let Err(e) = llvm_compile_to_object(&module, &_out_path) {
eprintln!("❌ LLVM object emit error: {}", e);
process::exit(1);
}
match std::fs::metadata(&out_path) {
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;
}

View File

@ -1,12 +1,5 @@
pub mod interpreter;
pub mod mir;
pub mod mir_interpreter;
pub mod vm;
pub mod llvm;
pub mod bench;
pub mod common;
#[cfg(feature = "wasm-backend")]
pub mod wasm;
#[cfg(feature = "cranelift-jit")]
pub mod aot;
#[cfg(feature = "cranelift-jit")]
pub mod cranelift;

View File

@ -107,7 +107,7 @@ impl NyashRunner {
// Optional: dump MIR for diagnostics
if std::env::var("NYASH_VM_DUMP_MIR").ok().as_deref() == Some("1") {
let mut p = nyash_rust::mir::MirPrinter::new();
let p = nyash_rust::mir::MirPrinter::new();
eprintln!("{}", p.print_module(&compile_result.module));
}