From 86b9f7719bc4c035445d594dfc9678e201cb91f0 Mon Sep 17 00:00:00 2001 From: Moe Charm Date: Wed, 20 Aug 2025 17:58:51 +0900 Subject: [PATCH] =?UTF-8?q?=F0=9F=8F=97=EF=B8=8F=20feat:=20Phase=209.78b?= =?UTF-8?q?=E6=BA=96=E5=82=99=20-=20=E3=82=A4=E3=83=B3=E3=82=BF=E3=83=BC?= =?UTF-8?q?=E3=83=97=E3=83=AA=E3=82=BF=E3=83=BC=E3=83=BBVM=E7=B5=B1?= =?UTF-8?q?=E5=90=88=E3=82=A2=E3=83=BC=E3=82=AD=E3=83=86=E3=82=AF=E3=83=81?= =?UTF-8?q?=E3=83=A3=E8=A8=AD=E8=A8=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 9.78b: Codexの天才的分析に基づくアーキテクチャ再設計準備 ## 📋 実施内容 1. Codex分析結果のアーカイブ - 実装詳細共有 → モデル共有・実行時共有への転換提案 - 8ステップの段階的実装計画 2. Phase 9.78a作業の保存 - MIR生成でのNewBox命令統一(保持) - ScopeTracker基本実装(一時コメントアウト) - VM拡張の方向性(TODOコメント付き) 3. ビルドエラー修正 - ScopeTrackerインポート問題を一時的に解決 - ビルド成功(警告のみ) ## 📚 作成ドキュメント - architecture-redesign-proposal.md - Codexの設計提案 - phase_9_78b_interpreter_architecture_refactoring.md - 実装計画 - codex-analysis/* - 分析結果アーカイブ ## 🎯 次のステップ Phase 9.78b Step 1: BoxDeclarationをcore::modelへ移動 --- build_error.txt | 791 ------------------ build_errors_only.txt | 484 +++++------ check_output.txt | 53 ++ docs/CURRENT_TASK.md | 80 +- docs/CURRENT_VM_CHANGES.md | 147 ++++ docs/architecture-redesign-proposal.md | 241 ++++++ .../2025-08-21-codex-response-full.md | 238 ++++++ ...-08-21-interpreter-refactoring-request.txt | 91 ++ ..._78b_interpreter_architecture_refactoring.md | 212 +++++ src/backend/vm.rs | 148 +++- src/lib.rs | 1 + src/mir/builder.rs | 77 +- src/scope_tracker.rs | 73 ++ 13 files changed, 1478 insertions(+), 1158 deletions(-) create mode 100644 docs/CURRENT_VM_CHANGES.md create mode 100644 docs/architecture-redesign-proposal.md create mode 100644 docs/archive/codex-analysis/2025-08-21-codex-response-full.md create mode 100644 docs/archive/codex-analysis/2025-08-21-interpreter-refactoring-request.txt create mode 100644 docs/予定/native-plan/issues/phase_9_78b_interpreter_architecture_refactoring.md create mode 100644 src/scope_tracker.rs diff --git a/build_error.txt b/build_error.txt index e8e3d9e5..e69de29b 100644 --- a/build_error.txt +++ b/build_error.txt @@ -1,791 +0,0 @@ -warning: unused imports: `BasicBlockIdGenerator`, `BasicBlock`, `CompareOp`, `EffectMask`, `MirFunction`, and `ValueIdGenerator` - --> src/mir/loop_builder.rs:9:21 - | -9 | MirInstruction, BasicBlock, BasicBlockId, MirFunction, ValueId, - | ^^^^^^^^^^ ^^^^^^^^^^^ -10 | ConstValue, CompareOp, BasicBlockIdGenerator, ValueIdGenerator, EffectMask - | ^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ ^^^^^^^^^^ - | - = note: `#[warn(unused_imports)]` on by default - -warning: unused import: `HashSet` - --> src/mir/loop_builder.rs:13:33 - | -13 | use std::collections::{HashMap, HashSet}; - | ^^^^^^^ - -warning: unexpected `cfg` condition value: `llvm` - --> src/backend/mod.rs:13:7 - | -13 | #[cfg(feature = "llvm")] - | ^^^^^^^^^^^^^^^^ - | - = note: expected values for `feature` are: `all-examples`, `cli`, `default`, `dynamic-file`, `gui`, `gui-examples`, and `wasm-backend` - = help: consider adding `llvm` as a feature in `Cargo.toml` - = note: see for more information about checking conditional configuration - = note: `#[warn(unexpected_cfgs)]` on by default - -warning: unexpected `cfg` condition value: `llvm` - --> src/backend/mod.rs:23:7 - | -23 | #[cfg(feature = "llvm")] - | ^^^^^^^^^^^^^^^^ - | - = note: expected values for `feature` are: `all-examples`, `cli`, `default`, `dynamic-file`, `gui`, `gui-examples`, and `wasm-backend` - = help: consider adding `llvm` as a feature in `Cargo.toml` - = note: see for more information about checking conditional configuration - -warning: unused import: `MirInstruction` - --> src/backend/vm_phi.rs:9:41 - | -9 | use crate::mir::{BasicBlockId, ValueId, MirInstruction}; - | ^^^^^^^^^^^^^^ - -warning: unused import: `super::Usize` - --> src/bid/types.rs:1:5 - | -1 | use super::Usize; - | ^^^^^^^^^^^^ - -warning: unused import: `std::os::raw::c_char` - --> src/bid/plugin_api.rs:2:5 - | -2 | use std::os::raw::c_char; - | ^^^^^^^^^^^^^^^^^^^^ - -warning: unused imports: `NyashHostVtable`, `NyashMethodInfo`, and `NyashPluginInfo` - --> src/bid/plugins/filebox/mod.rs:7:18 - | -7 | use crate::bid::{NyashPluginInfo, NyashMethodInfo, NyashHostVtable}; - | ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ - -warning: unused imports: `SeekFrom` and `Seek` - --> src/bid/plugins/filebox/mod.rs:10:28 - | -10 | use std::io::{Read, Write, Seek, SeekFrom}; - | ^^^^ ^^^^^^^^ - -warning: unused imports: `c_char` and `c_void` - --> src/bid/plugins/filebox/mod.rs:11:20 - | -11 | use std::os::raw::{c_char, c_void}; - | ^^^^^^ ^^^^^^ - -warning: unused imports: `CStr` and `CString` - --> src/bid/plugins/filebox/mod.rs:13:16 - | -13 | use std::ffi::{CStr, CString}; - | ^^^^ ^^^^^^^ - -warning: unused import: `std::ffi::c_void` - --> src/bid/loader.rs:3:5 - | -3 | use std::ffi::c_void; - | ^^^^^^^^^^^^^^^^ - -warning: unused imports: `TlvDecoder` and `TlvEncoder` - --> src/bid/generic_plugin_box.rs:2:23 - | -2 | use crate::bid::tlv::{TlvEncoder, TlvDecoder}; - | ^^^^^^^^^^ ^^^^^^^^^^ - -warning: unused import: `crate::bid::types::BidTag` - --> src/bid/generic_plugin_box.rs:3:5 - | -3 | use crate::bid::types::BidTag; - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - -warning: unused import: `BoxBase` - --> src/runtime/plugin_loader_v2.rs:7:43 - | -7 | use crate::box_trait::{NyashBox, BoxCore, BoxBase, StringBox}; - | ^^^^^^^ - -warning: unused import: `std::ffi::c_void` - --> src/runtime/plugin_loader_v2.rs:11:5 - | -11 | use std::ffi::c_void; - | ^^^^^^^^^^^^^^^^ - -warning: unused variable: `registry` - --> src/box_factory/plugin.rs:53:13 - | -53 | let registry = get_global_registry(); - | ^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_registry` - | - = note: `#[warn(unused_variables)]` on by default - -warning: unused variable: `args` - --> src/instance_v2.rs:147:28 - | -147 | pub fn init(&mut self, args: &[Box]) -> Result<(), String> { - | ^^^^ help: if this is intentional, prefix it with an underscore: `_args` - -warning: unused variable: `nyash_value` - --> src/instance_v2.rs:289:21 - | -289 | if let Some(nyash_value) = self.fields_ng.lock().unwrap().get(field_name) { - | ^^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_nyash_value` - -warning: unused variable: `block_id` - --> src/mir/loop_builder.rs:246:39 - | -246 | fn mark_block_unsealed(&mut self, block_id: BasicBlockId) -> Result<(), String> { - | ^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_block_id` - -warning: unused variable: `block_id` - --> src/mir/loop_builder.rs:273:49 - | -273 | fn get_variable_at_block(&self, name: &str, block_id: BasicBlockId) -> Option { - | ^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_block_id` - -warning: unused variable: `dst` - --> src/backend/vm_phi.rs:48:9 - | -48 | dst: ValueId, - | ^^^ help: if this is intentional, prefix it with an underscore: `_dst` - -warning: unused variable: `f` - --> src/bid/plugin_api.rs:167:36 - | -167 | pub fn with_alloc(mut self, f: F) -> Self - | ^ help: if this is intentional, prefix it with an underscore: `_f` - -warning: variable does not need to be mutable - --> src/bid/plugin_api.rs:167:26 - | -167 | pub fn with_alloc(mut self, f: F) -> Self - | ----^^^^ - | | - | help: remove this `mut` - | - = note: `#[warn(unused_mut)]` on by default - -warning: unused variable: `f` - --> src/bid/plugin_api.rs:176:35 - | -176 | pub fn with_free(mut self, f: F) -> Self - | ^ help: if this is intentional, prefix it with an underscore: `_f` - -warning: variable does not need to be mutable - --> src/bid/plugin_api.rs:176:25 - | -176 | pub fn with_free(mut self, f: F) -> Self - | ----^^^^ - | | - | help: remove this `mut` - -warning: unused variable: `f` - --> src/bid/plugin_api.rs:183:34 - | -183 | pub fn with_log(mut self, f: F) -> Self - | ^ help: if this is intentional, prefix it with an underscore: `_f` - -warning: variable does not need to be mutable - --> src/bid/plugin_api.rs:183:24 - | -183 | pub fn with_log(mut self, f: F) -> Self - | ----^^^^ - | | - | help: remove this `mut` - -warning: unused variable: `args` - --> src/runtime/plugin_loader_v2.rs:236:46 - | -236 | pub fn create_box(&self, box_type: &str, args: &[Box]) -> BidResult> { - | ^^^^ help: if this is intentional, prefix it with an underscore: `_args` - -warning: type `FileMode` is more private than the item `FileBoxRegistry::open` - --> src/bid/plugins/filebox/mod.rs:44:5 - | -44 | pub fn open(&mut self, path: &str, mode: FileMode) -> Result { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ method `FileBoxRegistry::open` is reachable at visibility `pub` - | -note: but type `FileMode` is only usable at visibility `pub(self)` - --> src/bid/plugins/filebox/mod.rs:29:1 - | -29 | enum FileMode { - | ^^^^^^^^^^^^^ - = note: `#[warn(private_interfaces)]` on by default - -warning: field `block_var_maps` is never read - --> src/mir/loop_builder.rs:35:5 - | -27 | pub struct LoopBuilder<'a> { - | ----------- field in this struct -... -35 | block_var_maps: HashMap>, - | ^^^^^^^^^^^^^^ - | - = note: `#[warn(dead_code)]` on by default - -warning: fields `type_name_holder` and `method_holders` are never read - --> src/bid/metadata.rs:148:5 - | -143 | pub struct PluginMetadata { - | -------------- fields in this struct -... -148 | type_name_holder: Option, - | ^^^^^^^^^^^^^^^^ -149 | method_holders: Vec<(NyashMethodInfo, CString)>, - | ^^^^^^^^^^^^^^ - -warning: fields `path` and `mode` are never read - --> src/bid/plugins/filebox/mod.rs:24:5 - | -22 | struct FileBoxState { - | ------------ fields in this struct -23 | file: File, -24 | path: String, - | ^^^^ -25 | mode: FileMode, - | ^^^^ - -warning: fields `box_types` and `init_fn` are never read - --> src/runtime/plugin_loader_v2.rs:20:5 - | -15 | pub struct LoadedPluginV2 { - | -------------- fields in this struct -... -20 | box_types: Vec, - | ^^^^^^^^^ -... -23 | init_fn: Option i32>, - | ^^^^^^^ - -warning: unused `Result` that must be used - --> src/mir/loop_builder.rs:62:9 - | -62 | self.add_predecessor(header_id, preheader_id); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this `Result` may be an `Err` variant, which should be handled - = note: `#[warn(unused_must_use)]` on by default -help: use `let _ = ...` to ignore the resulting value - | -62 | let _ = self.add_predecessor(header_id, preheader_id); - | +++++++ - -warning: unused `Result` that must be used - --> src/mir/loop_builder.rs:66:9 - | -66 | self.mark_block_unsealed(header_id); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this `Result` may be an `Err` variant, which should be handled -help: use `let _ = ...` to ignore the resulting value - | -66 | let _ = self.mark_block_unsealed(header_id); - | +++++++ - -warning: unused `Result` that must be used - --> src/mir/loop_builder.rs:78:9 - | -78 | self.add_predecessor(body_id, header_id); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this `Result` may be an `Err` variant, which should be handled -help: use `let _ = ...` to ignore the resulting value - | -78 | let _ = self.add_predecessor(body_id, header_id); - | +++++++ - -warning: unused `Result` that must be used - --> src/mir/loop_builder.rs:79:9 - | -79 | self.add_predecessor(after_loop_id, header_id); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this `Result` may be an `Err` variant, which should be handled -help: use `let _ = ...` to ignore the resulting value - | -79 | let _ = self.add_predecessor(after_loop_id, header_id); - | +++++++ - -warning: unused `Result` that must be used - --> src/mir/loop_builder.rs:93:9 - | -93 | self.add_predecessor(header_id, latch_id); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this `Result` may be an `Err` variant, which should be handled -help: use `let _ = ...` to ignore the resulting value - | -93 | let _ = self.add_predecessor(header_id, latch_id); - | +++++++ - -warning: creating a shared reference to mutable static - --> src/bid/plugins/filebox/mod.rs:102:12 - | -102 | if FILEBOX_REGISTRY.is_none() { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ shared reference to mutable static - | - = note: for more information, see - = note: shared references to mutable statics are dangerous; it's undefined behavior if the static is mutated or if a mutable reference is created for it while the shared reference lives - = note: `#[warn(static_mut_refs)]` on by default - -warning: creating a shared reference to mutable static - --> src/bid/plugins/filebox/mod.rs:105:9 - | -105 | FILEBOX_REGISTRY.as_ref().unwrap().clone() - | ^^^^^^^^^^^^^^^^^^^^^^^^^ shared reference to mutable static - | - = note: for more information, see - = note: shared references to mutable statics are dangerous; it's undefined behavior if the static is mutated or if a mutable reference is created for it while the shared reference lives - -warning: unused imports: `BoolBox`, `IntegerBox`, and `StringBox` - --> src/ast.rs:885:28 - | -885 | use crate::box_trait::{StringBox, IntegerBox, BoolBox}; - | ^^^^^^^^^ ^^^^^^^^^^ ^^^^^^^ - | - = note: `#[warn(unused_imports)]` on by default - -warning: unused import: `Mutex` - --> src/instance_v2.rs:387:26 - | -387 | use std::sync::{Arc, Mutex}; - | ^^^^^ - -warning: unused imports: `BasicBlockIdGenerator`, `BasicBlock`, `CompareOp`, `EffectMask`, `MirFunction`, and `ValueIdGenerator` - --> src/mir/loop_builder.rs:9:21 - | -9 | MirInstruction, BasicBlock, BasicBlockId, MirFunction, ValueId, - | ^^^^^^^^^^ ^^^^^^^^^^^ -10 | ConstValue, CompareOp, BasicBlockIdGenerator, ValueIdGenerator, EffectMask - | ^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ ^^^^^^^^^^ - -warning: unused import: `BasicBlock` - --> src/mir/verification.rs:311:75 - | -311 | use crate::mir::{MirFunction, FunctionSignature, MirType, EffectMask, BasicBlock}; - | ^^^^^^^^^^ - -warning: unused imports: `BasicBlock`, `EffectMask`, `FunctionSignature`, `MirFunction`, `MirModule`, and `MirType` - --> src/backend/vm.rs:860:22 - | -860 | use crate::mir::{MirModule, MirFunction, FunctionSignature, MirType, EffectMask, BasicBlock}; - | ^^^^^^^^^ ^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ ^^^^^^^ ^^^^^^^^^^ ^^^^^^^^^^ - -warning: unused imports: `BidHandle` and `BoxTypeId` - --> src/runtime/tests.rs:10:22 - | -10 | use crate::bid::{BidHandle, BoxTypeId}; - | ^^^^^^^^^ ^^^^^^^^^ - -warning: variable does not need to be mutable - --> src/mir/basic_block.rs:314:13 - | -314 | let mut bb = BasicBlock::new(bb_id); - | ----^^ - | | - | help: remove this `mut` - | - = note: `#[warn(unused_mut)]` on by default - -warning: unused variable: `child` - --> src/mir/ownership_verifier_simple.rs:313:13 - | -313 | let child = value_gen.next(); - | ^^^^^ help: if this is intentional, prefix it with an underscore: `_child` - -warning: variable does not need to be mutable - --> src/bid/plugin_api.rs:167:26 - | -167 | pub fn with_alloc(mut self, f: F) -> Self - | ----^^^^ - | | - | help: remove this `mut` - -warning: unused variable: `config` - --> src/config/nyash_toml_v2.rs:179:13 - | -179 | let config: toml::Value = toml::from_str(toml_str).unwrap(); - | ^^^^^^ help: if this is intentional, prefix it with an underscore: `_config` - -warning: unused variable: `nyash_config` - --> src/config/nyash_toml_v2.rs:180:13 - | -180 | let nyash_config = NyashConfigV2::from_file("test.toml"); - | ^^^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_nyash_config` - -warning: variable does not need to be mutable - --> src/tests/box_tests.rs:11:13 - | -11 | let mut array = ArrayBox::new(); - | ----^^^^^ - | | - | help: remove this `mut` - -warning: variable does not need to be mutable - --> src/tests/box_tests.rs:90:13 - | -90 | let mut stream = NyashStreamBox::from_data(vec![72, 101, 108, 108, 111]); // "Hello" - | ----^^^^^^ - | | - | help: remove this `mut` - -warning: `nyash-rust` (lib) generated 41 warnings (run `cargo fix --lib -p nyash-rust` to apply 17 suggestions) -warning: `nyash-rust` (lib test) generated 52 warnings (39 duplicates) (run `cargo fix --lib -p nyash-rust --tests` to apply 10 suggestions) - Compiling nyash-rust v0.1.0 (/mnt/c/git/nyash-project/nyash) -warning: unexpected `cfg` condition value: `llvm` - --> src/runner.rs:22:7 - | -22 | #[cfg(feature = "llvm")] - | ^^^^^^^^^^^^^^^^ - | - = note: expected values for `feature` are: `all-examples`, `cli`, `default`, `dynamic-file`, `gui`, `gui-examples`, and `wasm-backend` - = help: consider adding `llvm` as a feature in `Cargo.toml` - = note: see for more information about checking conditional configuration - -warning: unexpected `cfg` condition value: `llvm` - --> src/runner.rs:503:15 - | -503 | #[cfg(feature = "llvm")] - | ^^^^^^^^^^^^^^^^ - | - = note: expected values for `feature` are: `all-examples`, `cli`, `default`, `dynamic-file`, `gui`, `gui-examples`, and `wasm-backend` - = help: consider adding `llvm` as a feature in `Cargo.toml` - = note: see for more information about checking conditional configuration - -warning: unexpected `cfg` condition value: `llvm` - --> src/runner.rs:526:19 - | -526 | #[cfg(not(feature = "llvm"))] - | ^^^^^^^^^^^^^^^^ - | - = note: expected values for `feature` are: `all-examples`, `cli`, `default`, `dynamic-file`, `gui`, `gui-examples`, and `wasm-backend` - = help: consider adding `llvm` as a feature in `Cargo.toml` - = note: see for more information about checking conditional configuration - -warning: variable does not need to be mutable - --> src/runner.rs:286:17 - | -286 | let mut printer = if self.config.mir_verbose { - | ----^^^^^^^ - | | - | help: remove this `mut` - | - = note: `#[warn(unused_mut)]` on by default - -warning: type `FileMode` is more private than the item `bid::plugins::filebox::FileBoxRegistry::open` - --> src/bid/plugins/filebox/mod.rs:44:5 - | -44 | pub fn open(&mut self, path: &str, mode: FileMode) -> Result { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ method `bid::plugins::filebox::FileBoxRegistry::open` is reachable at visibility `pub` - | -note: but type `FileMode` is only usable at visibility `pub(self)` - --> src/bid/plugins/filebox/mod.rs:29:1 - | -29 | enum FileMode { - | ^^^^^^^^^^^^^ - = note: `#[warn(private_interfaces)]` on by default - -warning: unused `std::result::Result` that must be used - --> src/mir/loop_builder.rs:62:9 - | -62 | self.add_predecessor(header_id, preheader_id); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this `Result` may be an `Err` variant, which should be handled - = note: `#[warn(unused_must_use)]` on by default -help: use `let _ = ...` to ignore the resulting value - | -62 | let _ = self.add_predecessor(header_id, preheader_id); - | +++++++ - -warning: unused `std::result::Result` that must be used - --> src/mir/loop_builder.rs:66:9 - | -66 | self.mark_block_unsealed(header_id); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this `Result` may be an `Err` variant, which should be handled -help: use `let _ = ...` to ignore the resulting value - | -66 | let _ = self.mark_block_unsealed(header_id); - | +++++++ - -warning: unused `std::result::Result` that must be used - --> src/mir/loop_builder.rs:78:9 - | -78 | self.add_predecessor(body_id, header_id); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this `Result` may be an `Err` variant, which should be handled -help: use `let _ = ...` to ignore the resulting value - | -78 | let _ = self.add_predecessor(body_id, header_id); - | +++++++ - -warning: unused `std::result::Result` that must be used - --> src/mir/loop_builder.rs:79:9 - | -79 | self.add_predecessor(after_loop_id, header_id); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this `Result` may be an `Err` variant, which should be handled -help: use `let _ = ...` to ignore the resulting value - | -79 | let _ = self.add_predecessor(after_loop_id, header_id); - | +++++++ - -warning: unused `std::result::Result` that must be used - --> src/mir/loop_builder.rs:93:9 - | -93 | self.add_predecessor(header_id, latch_id); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this `Result` may be an `Err` variant, which should be handled -help: use `let _ = ...` to ignore the resulting value - | -93 | let _ = self.add_predecessor(header_id, latch_id); - | +++++++ - -warning: unused import: `VMValue` - --> tests/mir_phase6_vm_ref_ops.rs:11:31 - | -11 | use nyash_rust::backend::{VM, VMValue}; - | ^^^^^^^ - | - = note: `#[warn(unused_imports)]` on by default - -warning: unused import: `NyashBox` - --> tests/mir_phase6_vm_ref_ops.rs:12:41 - | -12 | use nyash_rust::box_trait::{IntegerBox, NyashBox}; - | ^^^^^^^^ - -warning: unused variable: `vm` - --> tests/mir_phase6_vm_ref_ops.rs:139:13 - | -139 | let mut vm = VM::new(); - | ^^ help: if this is intentional, prefix it with an underscore: `_vm` - | - = note: `#[warn(unused_variables)]` on by default - -warning: variable does not need to be mutable - --> tests/mir_phase6_vm_ref_ops.rs:139:9 - | -139 | let mut vm = VM::new(); - | ----^^ - | | - | help: remove this `mut` - | - = note: `#[warn(unused_mut)]` on by default - -warning: unused import: `std::collections::HashMap` - --> tests/integration_tests.rs:9:5 - | -9 | use std::collections::HashMap; - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: `#[warn(unused_imports)]` on by default - -warning: function `execute_nyash_code` is never used - --> tests/integration_tests.rs:12:4 - | -12 | fn execute_nyash_code(code: &str) -> Result { - | ^^^^^^^^^^^^^^^^^^ - | - = note: `#[warn(dead_code)]` on by default - -error: couldn't read `examples/C:/Windows/Fonts/arial.ttf`: No such file or directory (os error 2) - --> examples/simple_notepad_win.rs:32:57 - | -32 | std::sync::Arc::new(egui::FontData::from_static(include_bytes!( - | _________________________________________________________^ -33 | | "C:/Windows/Fonts/arial.ttf" -34 | | ))), - | |_________^ - -warning: `nyash-rust` (bin "nyash") generated 45 warnings (35 duplicates) (run `cargo fix --bin "nyash"` to apply 1 suggestion) -warning: `nyash-rust` (test "mir_phase6_vm_ref_ops") generated 4 warnings (run `cargo fix --test "mir_phase6_vm_ref_ops"` to apply 2 suggestions) -warning: `nyash-rust` (test "integration_tests") generated 2 warnings (run `cargo fix --test "integration_tests"` to apply 1 suggestion) -error[E0432]: unresolved import `nyash_rust::backend::wasm` - --> tests/wasm_poc2_box_operations.rs:17:26 - | -17 | use nyash_rust::backend::wasm::WasmBackend; - | ^^^^ could not find `wasm` in `backend` - | -note: found an item that was configured out - --> /mnt/c/git/nyash-project/nyash/src/backend/mod.rs:9:9 - | -9 | pub mod wasm; - | ^^^^ -note: the item is gated behind the `wasm-backend` feature - --> /mnt/c/git/nyash-project/nyash/src/backend/mod.rs:8:7 - | -8 | #[cfg(feature = "wasm-backend")] - | ^^^^^^^^^^^^^^^^^^^^^^^^ - -error[E0432]: unresolved import `nyash_rust::backend::wasm` - --> tests/wasm_poc1_basic_operations.rs:15:26 - | -15 | use nyash_rust::backend::wasm::WasmBackend; - | ^^^^ could not find `wasm` in `backend` - | -note: found an item that was configured out - --> /mnt/c/git/nyash-project/nyash/src/backend/mod.rs:9:9 - | -9 | pub mod wasm; - | ^^^^ -note: the item is gated behind the `wasm-backend` feature - --> /mnt/c/git/nyash-project/nyash/src/backend/mod.rs:8:7 - | -8 | #[cfg(feature = "wasm-backend")] - | ^^^^^^^^^^^^^^^^^^^^^^^^ - -error[E0432]: unresolved import `nyash_rust::backend::wasm` - --> tests/wasm_string_constants.rs:15:26 - | -15 | use nyash_rust::backend::wasm::WasmBackend; - | ^^^^ could not find `wasm` in `backend` - | -note: found an item that was configured out - --> /mnt/c/git/nyash-project/nyash/src/backend/mod.rs:9:9 - | -9 | pub mod wasm; - | ^^^^ -note: the item is gated behind the `wasm-backend` feature - --> /mnt/c/git/nyash-project/nyash/src/backend/mod.rs:8:7 - | -8 | #[cfg(feature = "wasm-backend")] - | ^^^^^^^^^^^^^^^^^^^^^^^^ - -For more information about this error, try `rustc --explain E0432`. -error: could not compile `nyash-rust` (test "wasm_poc2_box_operations") due to 1 previous error -warning: build failed, waiting for other jobs to finish... -error: could not compile `nyash-rust` (test "wasm_string_constants") due to 1 previous error -error: could not compile `nyash-rust` (test "wasm_poc1_basic_operations") due to 1 previous error -error[E0433]: failed to resolve: unresolved import - --> tests/array_state_sharing_test.rs:4:16 - | -4 | use crate::boxes::array::ArrayBox; - | ^^^^^ - | | - | unresolved import - | help: a similar path exists: `nyash_rust::boxes` - -error[E0432]: unresolved import `crate::interpreter` - --> tests/array_state_sharing_test.rs:3:16 - | -3 | use crate::interpreter::Interpreter; - | ^^^^^^^^^^^ - | | - | unresolved import - | help: a similar path exists: `nyash_rust::interpreter` - -error[E0432]: unresolved import `crate::box_trait` - --> tests/array_state_sharing_test.rs:5:16 - | -5 | use crate::box_trait::{NyashBox, IntegerBox, StringBox}; - | ^^^^^^^^^ - | | - | unresolved import - | help: a similar path exists: `nyash_rust::box_trait` - -error[E0432]: unresolved import `crate::mir` - --> tests/mir_phase8_5_hierarchical_25_instructions.rs:7:12 - | -7 | use crate::mir::{ - | ^^^ - | | - | unresolved import - | help: a similar path exists: `nyash_rust::mir` - -Some errors have detailed explanations: E0432, E0433. -For more information about an error, try `rustc --explain E0432`. -error: could not compile `nyash-rust` (test "array_state_sharing_test") due to 3 previous errors -error: could not compile `nyash-rust` (test "mir_phase8_5_hierarchical_25_instructions") due to 1 previous error -error[E0432]: unresolved import `eframe` - --> examples/simple_notepad_win.rs:4:5 - | -4 | use eframe::egui; - | ^^^^^^ use of unresolved module or unlinked crate `eframe` - | - = help: if you wanted to use a crate named `eframe`, use `cargo add eframe` to add it to your `Cargo.toml` - -error[E0433]: failed to resolve: use of unresolved module or unlinked crate `eframe` - --> examples/simple_notepad_win.rs:6:14 - | -6 | fn main() -> eframe::Result { - | ^^^^^^ use of unresolved module or unlinked crate `eframe` - | - = help: if you wanted to use a crate named `eframe`, use `cargo add eframe` to add it to your `Cargo.toml` - -error[E0433]: failed to resolve: use of unresolved module or unlinked crate `eframe` - --> examples/simple_notepad_win.rs:7:19 - | -7 | let options = eframe::NativeOptions { - | ^^^^^^ use of unresolved module or unlinked crate `eframe` - | - = help: if you wanted to use a crate named `eframe`, use `cargo add eframe` to add it to your `Cargo.toml` - -error[E0433]: failed to resolve: use of unresolved module or unlinked crate `eframe` - --> examples/simple_notepad_win.rs:14:5 - | -14 | eframe::run_native( - | ^^^^^^ use of unresolved module or unlinked crate `eframe` - | - = help: if you wanted to use a crate named `eframe`, use `cargo add eframe` to add it to your `Cargo.toml` - -error[E0433]: failed to resolve: use of unresolved module or unlinked crate `eframe` - --> examples/simple_notepad_win.rs:69:6 - | -69 | impl eframe::App for NyashNotepad { - | ^^^^^^ use of unresolved module or unlinked crate `eframe` - | - = help: if you wanted to use a crate named `eframe`, use `cargo add eframe` to add it to your `Cargo.toml` - -error[E0433]: failed to resolve: use of unresolved module or unlinked crate `eframe` - --> examples/simple_notepad_win.rs:70:60 - | -70 | fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { - | ^^^^^^ use of unresolved module or unlinked crate `eframe` - | - = help: if you wanted to use a crate named `eframe`, use `cargo add eframe` to add it to your `Cargo.toml` - -error: could not compile `nyash-rust` (example "simple_notepad_win") due to 7 previous errors -warning: unused import: `BoxCore` - --> src/main.rs:71:32 - | -71 | use box_trait::{StringBox, BoxCore}; - | ^^^^^^^ - -error[E0599]: no method named `to_string_box` found for struct `box_trait::StringBox` in the current scope - --> src/main.rs:77:31 - | -77 | assert_eq!(string_box.to_string_box().value, "test"); - | ^^^^^^^^^^^^^ - | - ::: src/box_trait.rs:96:8 - | -96 | fn to_string_box(&self) -> StringBox; - | ------------- the method is available for `box_trait::StringBox` here -... -127 | pub struct StringBox { - | -------------------- method `to_string_box` not found for this struct - | - = help: items from traits can only be used if the trait is in scope -help: trait `NyashBox` which provides `to_string_box` is implemented but not in scope; perhaps you want to import it - | -70 + use crate::box_trait::NyashBox; - | -help: there is a method `to_string` with a similar name - | -77 - assert_eq!(string_box.to_string_box().value, "test"); -77 + assert_eq!(string_box.to_string().value, "test"); - | - -warning: variable does not need to be mutable - --> src/runner.rs:286:17 - | -286 | let mut printer = if self.config.mir_verbose { - | ----^^^^^^^ - | | - | help: remove this `mut` - -For more information about this error, try `rustc --explain E0599`. -warning: `nyash-rust` (bin "nyash" test) generated 43 warnings (41 duplicates) -error: could not compile `nyash-rust` (bin "nyash" test) due to 1 previous error; 43 warnings emitted diff --git a/build_errors_only.txt b/build_errors_only.txt index 0ea9a292..c3b9a829 100644 --- a/build_errors_only.txt +++ b/build_errors_only.txt @@ -1,267 +1,275 @@ - Compiling proc-macro2 v1.0.95 - Compiling unicode-ident v1.0.18 - Compiling serde v1.0.219 - Compiling cfg-if v1.0.1 - Compiling wasm-bindgen-shared v0.2.100 - Compiling memchr v2.7.5 - Compiling log v0.4.27 - Compiling bumpalo v3.19.0 - Compiling rustversion v1.0.21 - Compiling utf8parse v0.2.2 - Compiling autocfg v1.5.0 - Compiling regex-syntax v0.8.5 - Compiling is_terminal_polyfill v1.70.1 - Compiling anstyle v1.0.11 - Compiling colorchoice v1.0.4 - Compiling crossbeam-utils v0.8.21 - Compiling wasm-bindgen v0.2.100 - Compiling once_cell v1.21.3 - Compiling anstyle-query v1.1.3 - Compiling serde_json v1.0.142 - Compiling hashbrown v0.15.5 - Compiling equivalent v1.0.2 - Compiling itoa v1.0.15 - Compiling strsim v0.11.1 - Compiling heck v0.5.0 - Compiling clap_lex v0.7.5 - Compiling ryu v1.0.20 - Compiling thiserror v2.0.12 - Compiling rayon-core v1.12.1 - Compiling toml_write v0.1.2 - Compiling anyhow v1.0.98 - Compiling anstyle-parse v0.2.7 - Compiling either v1.15.0 - Compiling libc v0.2.174 - Compiling winnow v0.7.12 - Compiling half v2.6.0 - Compiling iana-time-zone v0.1.63 - Compiling jiff v0.2.15 - Compiling aho-corasick v1.1.3 - Compiling indexmap v2.10.0 - Compiling anstream v0.6.19 - Compiling plotters-backend v0.3.7 - Compiling ciborium-io v0.2.2 - Compiling itertools v0.10.5 - Compiling libloading v0.8.8 - Compiling same-file v1.0.6 - Compiling lazy_static v1.5.0 - Compiling cast v0.3.0 - Compiling oorandom v11.1.5 - Compiling anes v0.1.6 - Compiling ciborium-ll v0.2.2 - Compiling num-traits v0.2.19 - Compiling plotters-svg v0.3.7 - Compiling walkdir v2.5.0 - Compiling clap_builder v4.5.42 - Compiling regex-automata v0.4.9 - Compiling criterion-plot v0.5.0 - Compiling regex v1.11.1 - Compiling env_filter v0.1.3 - Compiling crossbeam-epoch v0.9.18 - Compiling env_logger v0.11.8 - Compiling crossbeam-deque v0.8.6 - Compiling quote v1.0.40 - Compiling syn v2.0.104 - Compiling rayon v1.10.0 - Compiling is-terminal v0.4.16 - Compiling chrono v0.4.41 - Compiling plotters v0.3.7 - Compiling wasm-bindgen-backend v0.2.100 - Compiling serde_derive v1.0.219 - Compiling clap_derive v4.5.41 - Compiling thiserror-impl v2.0.12 - Compiling wasm-bindgen-macro-support v0.2.100 - Compiling wasm-bindgen-macro v0.2.100 - Compiling clap v4.5.42 - Compiling js-sys v0.3.77 - Compiling console_error_panic_hook v0.1.7 - Compiling toml_datetime v0.6.11 - Compiling serde_spanned v0.6.9 - Compiling ciborium v0.2.2 - Compiling toml_edit v0.22.27 - Compiling tinytemplate v1.2.1 - Compiling criterion v0.5.1 - Compiling toml v0.8.23 - Compiling web-sys v0.3.77 Compiling nyash-rust v0.1.0 (/mnt/c/git/nyash-project/nyash) -error: couldn't read `examples/C:/Windows/Fonts/arial.ttf`: No such file or directory (os error 2) - --> examples/simple_notepad_win.rs:32:57 +warning: unused macro definition: `debug_trace` + --> src/interpreter/core.rs:33:14 | -32 | std::sync::Arc::new(egui::FontData::from_static(include_bytes!( - | _________________________________________________________^ -33 | | "C:/Windows/Fonts/arial.ttf" -34 | | ))), - | |_________^ +33 | macro_rules! debug_trace { + | ^^^^^^^^^^^ + | + = note: `#[warn(unused_macros)]` on by default -error[E0432]: unresolved import `nyash_rust::backend::wasm` - --> tests/wasm_poc1_basic_operations.rs:15:26 +warning: unused imports: `BasicBlockIdGenerator`, `BasicBlock`, `CompareOp`, `EffectMask`, `MirFunction`, and `ValueIdGenerator` + --> src/mir/loop_builder.rs:9:21 | -15 | use nyash_rust::backend::wasm::WasmBackend; - | ^^^^ could not find `wasm` in `backend` +9 | MirInstruction, BasicBlock, BasicBlockId, MirFunction, ValueId, + | ^^^^^^^^^^ ^^^^^^^^^^^ +10 | ConstValue, CompareOp, BasicBlockIdGenerator, ValueIdGenerator, EffectMask + | ^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ ^^^^^^^^^^ | -note: found an item that was configured out - --> /mnt/c/git/nyash-project/nyash/src/backend/mod.rs:9:9 - | -9 | pub mod wasm; - | ^^^^ -note: the item is gated behind the `wasm-backend` feature - --> /mnt/c/git/nyash-project/nyash/src/backend/mod.rs:8:7 - | -8 | #[cfg(feature = "wasm-backend")] - | ^^^^^^^^^^^^^^^^^^^^^^^^ + = note: `#[warn(unused_imports)]` on by default -error[E0432]: unresolved import `nyash_rust::backend::wasm` - --> tests/wasm_poc2_box_operations.rs:17:26 +warning: unused import: `HashSet` + --> src/mir/loop_builder.rs:13:33 | -17 | use nyash_rust::backend::wasm::WasmBackend; - | ^^^^ could not find `wasm` in `backend` - | -note: found an item that was configured out - --> /mnt/c/git/nyash-project/nyash/src/backend/mod.rs:9:9 - | -9 | pub mod wasm; - | ^^^^ -note: the item is gated behind the `wasm-backend` feature - --> /mnt/c/git/nyash-project/nyash/src/backend/mod.rs:8:7 - | -8 | #[cfg(feature = "wasm-backend")] - | ^^^^^^^^^^^^^^^^^^^^^^^^ +13 | use std::collections::{HashMap, HashSet}; + | ^^^^^^^ -error[E0432]: unresolved import `nyash_rust::backend::wasm` - --> tests/wasm_string_constants.rs:15:26 +warning: unexpected `cfg` condition value: `llvm` + --> src/backend/mod.rs:13:7 | -15 | use nyash_rust::backend::wasm::WasmBackend; - | ^^^^ could not find `wasm` in `backend` +13 | #[cfg(feature = "llvm")] + | ^^^^^^^^^^^^^^^^ | -note: found an item that was configured out - --> /mnt/c/git/nyash-project/nyash/src/backend/mod.rs:9:9 - | -9 | pub mod wasm; - | ^^^^ -note: the item is gated behind the `wasm-backend` feature - --> /mnt/c/git/nyash-project/nyash/src/backend/mod.rs:8:7 - | -8 | #[cfg(feature = "wasm-backend")] - | ^^^^^^^^^^^^^^^^^^^^^^^^ + = note: expected values for `feature` are: `all-examples`, `cli`, `default`, `dynamic-file`, `gui`, `gui-examples`, `plugins`, and `wasm-backend` + = help: consider adding `llvm` as a feature in `Cargo.toml` + = note: see for more information about checking conditional configuration + = note: `#[warn(unexpected_cfgs)]` on by default -For more information about this error, try `rustc --explain E0432`. -error: could not compile `nyash-rust` (test "wasm_poc1_basic_operations") due to 1 previous error -warning: build failed, waiting for other jobs to finish... -error: could not compile `nyash-rust` (test "wasm_string_constants") due to 1 previous error -error: could not compile `nyash-rust` (test "wasm_poc2_box_operations") due to 1 previous error -error[E0433]: failed to resolve: unresolved import - --> tests/array_state_sharing_test.rs:4:16 +warning: unexpected `cfg` condition value: `llvm` + --> src/backend/mod.rs:23:7 + | +23 | #[cfg(feature = "llvm")] + | ^^^^^^^^^^^^^^^^ + | + = note: expected values for `feature` are: `all-examples`, `cli`, `default`, `dynamic-file`, `gui`, `gui-examples`, `plugins`, and `wasm-backend` + = help: consider adding `llvm` as a feature in `Cargo.toml` + = note: see for more information about checking conditional configuration + +warning: unused import: `MirInstruction` + --> src/backend/vm_phi.rs:9:41 | -4 | use crate::boxes::array::ArrayBox; - | ^^^^^ - | | - | unresolved import - | help: a similar path exists: `nyash_rust::boxes` +9 | use crate::mir::{BasicBlockId, ValueId, MirInstruction}; + | ^^^^^^^^^^^^^^ -error[E0432]: unresolved import `crate::mir` - --> tests/mir_phase8_5_hierarchical_25_instructions.rs:7:12 +warning: unused import: `super::Usize` + --> src/bid/types.rs:1:5 | -7 | use crate::mir::{ - | ^^^ - | | - | unresolved import - | help: a similar path exists: `nyash_rust::mir` +1 | use super::Usize; + | ^^^^^^^^^^^^ -error[E0432]: unresolved import `crate::interpreter` - --> tests/array_state_sharing_test.rs:3:16 +warning: unused import: `std::os::raw::c_char` + --> src/bid/plugin_api.rs:2:5 | -3 | use crate::interpreter::Interpreter; - | ^^^^^^^^^^^ - | | - | unresolved import - | help: a similar path exists: `nyash_rust::interpreter` +2 | use std::os::raw::c_char; + | ^^^^^^^^^^^^^^^^^^^^ -error[E0432]: unresolved import `crate::box_trait` - --> tests/array_state_sharing_test.rs:5:16 +warning: unused imports: `NyashHostVtable`, `NyashMethodInfo`, and `NyashPluginInfo` + --> src/bid/plugins/filebox/mod.rs:7:18 | -5 | use crate::box_trait::{NyashBox, IntegerBox, StringBox}; - | ^^^^^^^^^ - | | - | unresolved import - | help: a similar path exists: `nyash_rust::box_trait` +7 | use crate::bid::{NyashPluginInfo, NyashMethodInfo, NyashHostVtable}; + | ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ -Some errors have detailed explanations: E0432, E0433. -For more information about an error, try `rustc --explain E0432`. -error: could not compile `nyash-rust` (test "array_state_sharing_test") due to 3 previous errors -error: could not compile `nyash-rust` (test "mir_phase8_5_hierarchical_25_instructions") due to 1 previous error -error[E0432]: unresolved import `eframe` - --> examples/simple_notepad_win.rs:4:5 - | -4 | use eframe::egui; - | ^^^^^^ use of unresolved module or unlinked crate `eframe` - | - = help: if you wanted to use a crate named `eframe`, use `cargo add eframe` to add it to your `Cargo.toml` - -error[E0433]: failed to resolve: use of unresolved module or unlinked crate `eframe` - --> examples/simple_notepad_win.rs:6:14 - | -6 | fn main() -> eframe::Result { - | ^^^^^^ use of unresolved module or unlinked crate `eframe` - | - = help: if you wanted to use a crate named `eframe`, use `cargo add eframe` to add it to your `Cargo.toml` - -error[E0433]: failed to resolve: use of unresolved module or unlinked crate `eframe` - --> examples/simple_notepad_win.rs:7:19 - | -7 | let options = eframe::NativeOptions { - | ^^^^^^ use of unresolved module or unlinked crate `eframe` - | - = help: if you wanted to use a crate named `eframe`, use `cargo add eframe` to add it to your `Cargo.toml` - -error[E0433]: failed to resolve: use of unresolved module or unlinked crate `eframe` - --> examples/simple_notepad_win.rs:14:5 +warning: unused imports: `SeekFrom` and `Seek` + --> src/bid/plugins/filebox/mod.rs:10:28 | -14 | eframe::run_native( - | ^^^^^^ use of unresolved module or unlinked crate `eframe` - | - = help: if you wanted to use a crate named `eframe`, use `cargo add eframe` to add it to your `Cargo.toml` +10 | use std::io::{Read, Write, Seek, SeekFrom}; + | ^^^^ ^^^^^^^^ -error[E0433]: failed to resolve: use of unresolved module or unlinked crate `eframe` - --> examples/simple_notepad_win.rs:69:6 +warning: unused imports: `c_char` and `c_void` + --> src/bid/plugins/filebox/mod.rs:11:20 | -69 | impl eframe::App for NyashNotepad { - | ^^^^^^ use of unresolved module or unlinked crate `eframe` - | - = help: if you wanted to use a crate named `eframe`, use `cargo add eframe` to add it to your `Cargo.toml` +11 | use std::os::raw::{c_char, c_void}; + | ^^^^^^ ^^^^^^ -error[E0433]: failed to resolve: use of unresolved module or unlinked crate `eframe` - --> examples/simple_notepad_win.rs:70:60 +warning: unused imports: `CStr` and `CString` + --> src/bid/plugins/filebox/mod.rs:13:16 | -70 | fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { - | ^^^^^^ use of unresolved module or unlinked crate `eframe` - | - = help: if you wanted to use a crate named `eframe`, use `cargo add eframe` to add it to your `Cargo.toml` +13 | use std::ffi::{CStr, CString}; + | ^^^^ ^^^^^^^ -error: could not compile `nyash-rust` (example "simple_notepad_win") due to 7 previous errors -error[E0599]: no method named `to_string_box` found for struct `box_trait::StringBox` in the current scope - --> src/main.rs:77:31 +warning: unused import: `std::ffi::c_void` + --> src/bid/loader.rs:4:5 + | +4 | use std::ffi::c_void; + | ^^^^^^^^^^^^^^^^ + +warning: unused imports: `TlvDecoder` and `TlvEncoder` + --> src/bid/generic_plugin_box.rs:5:23 + | +5 | use crate::bid::tlv::{TlvEncoder, TlvDecoder}; + | ^^^^^^^^^^ ^^^^^^^^^^ + +warning: unused import: `crate::bid::types::BidTag` + --> src/bid/generic_plugin_box.rs:6:5 + | +6 | use crate::bid::types::BidTag; + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + +warning: unused import: `BoxBase` + --> src/runtime/plugin_loader_v2.rs:10:47 + | +10 | use crate::box_trait::{NyashBox, BoxCore, BoxBase, StringBox}; + | ^^^^^^^ + +warning: unused import: `std::ffi::c_void` + --> src/runtime/plugin_loader_v2.rs:14:9 + | +14 | use std::ffi::c_void; + | ^^^^^^^^^^^^^^^^ + +error[E0782]: expected a type, found a trait + --> src/backend/vm.rs:175:22 | -77 | assert_eq!(string_box.to_string_box().value, "test"); - | ^^^^^^^^^^^^^ +175 | box_factory: Arc, + | ^^^^^^^^^^ | - ::: src/box_trait.rs:96:8 - | -96 | fn to_string_box(&self) -> StringBox; - | ------------- the method is available for `box_trait::StringBox` here -... -127 | pub struct StringBox { - | -------------------- method `to_string_box` not found for this struct - | - = help: items from traits can only be used if the trait is in scope -help: trait `NyashBox` which provides `to_string_box` is implemented but not in scope; perhaps you want to import it - | -70 + use crate::box_trait::NyashBox; - | -help: there is a method `to_string` with a similar name - | -77 - assert_eq!(string_box.to_string_box().value, "test"); -77 + assert_eq!(string_box.to_string().value, "test"); +help: you can add the `dyn` keyword if you want a trait object | +175 | box_factory: Arc, + | +++ -For more information about this error, try `rustc --explain E0599`. -error: could not compile `nyash-rust` (bin "nyash" test) due to 1 previous error +error[E0782]: expected a type, found a trait + --> src/backend/vm.rs:207:26 + | +207 | box_factory: Arc, + | ^^^^^^^^^^ + | +help: you can add the `dyn` keyword if you want a trait object + | +207 | box_factory: Arc, + | +++ + +error[E0782]: expected a type, found a trait + --> src/backend/vm.rs:230:26 + | +230 | box_factory: Arc, + | ^^^^^^^^^^ + | +help: you can add the `dyn` keyword if you want a trait object + | +230 | box_factory: Arc, + | +++ + +error[E0782]: expected a type, found a trait + --> src/backend/vm.rs:197:35 + | +197 | box_factory: Arc::new(BoxFactory::new()), + | ^^^^^^^^^^ + | +help: you can add the `dyn` keyword if you want a trait object + | +197 | box_factory: Arc::new(::new()), + | ++++ + + +warning: unused variable: `registry` + --> src/box_factory/plugin.rs:53:13 + | +53 | let registry = get_global_registry(); + | ^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_registry` + | + = note: `#[warn(unused_variables)]` on by default + +warning: unused variable: `arc_box` + --> src/scope_tracker.rs:33:17 + | +33 | for arc_box in scope.into_iter().rev() { + | ^^^^^^^ help: if this is intentional, prefix it with an underscore: `_arc_box` + +warning: variable does not need to be mutable + --> src/interpreter/expressions/calls.rs:739:13 + | +739 | let mut is_builtin = is_builtin_box(parent); + | ----^^^^^^^^^^ + | | + | help: remove this `mut` + | + = note: `#[warn(unused_mut)]` on by default + +warning: variable does not need to be mutable + --> src/interpreter/objects.rs:1106:17 + | +1106 | let mut is_builtin = is_builtin_box(parent_name); + | ----^^^^^^^^^^ + | | + | help: remove this `mut` + +warning: unused variable: `args` + --> src/instance_v2.rs:147:28 + | +147 | pub fn init(&mut self, args: &[Box]) -> Result<(), String> { + | ^^^^ help: if this is intentional, prefix it with an underscore: `_args` + +warning: unused variable: `nyash_value` + --> src/instance_v2.rs:289:21 + | +289 | if let Some(nyash_value) = self.fields_ng.lock().unwrap().get(field_name) { + | ^^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_nyash_value` + +warning: unused variable: `block_id` + --> src/mir/loop_builder.rs:246:39 + | +246 | fn mark_block_unsealed(&mut self, block_id: BasicBlockId) -> Result<(), String> { + | ^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_block_id` + +warning: unused variable: `block_id` + --> src/mir/loop_builder.rs:273:49 + | +273 | fn get_variable_at_block(&self, name: &str, block_id: BasicBlockId) -> Option { + | ^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_block_id` + +warning: unused variable: `dst` + --> src/backend/vm_phi.rs:48:9 + | +48 | dst: ValueId, + | ^^^ help: if this is intentional, prefix it with an underscore: `_dst` + +warning: unused variable: `f` + --> src/bid/plugin_api.rs:167:36 + | +167 | pub fn with_alloc(mut self, f: F) -> Self + | ^ help: if this is intentional, prefix it with an underscore: `_f` + +warning: variable does not need to be mutable + --> src/bid/plugin_api.rs:167:26 + | +167 | pub fn with_alloc(mut self, f: F) -> Self + | ----^^^^ + | | + | help: remove this `mut` + +warning: unused variable: `f` + --> src/bid/plugin_api.rs:176:35 + | +176 | pub fn with_free(mut self, f: F) -> Self + | ^ help: if this is intentional, prefix it with an underscore: `_f` + +warning: variable does not need to be mutable + --> src/bid/plugin_api.rs:176:25 + | +176 | pub fn with_free(mut self, f: F) -> Self + | ----^^^^ + | | + | help: remove this `mut` + +warning: unused variable: `f` + --> src/bid/plugin_api.rs:183:34 + | +183 | pub fn with_log(mut self, f: F) -> Self + | ^ help: if this is intentional, prefix it with an underscore: `_f` + +warning: variable does not need to be mutable + --> src/bid/plugin_api.rs:183:24 + | +183 | pub fn with_log(mut self, f: F) -> Self + | ----^^^^ + | | + | help: remove this `mut` + +warning: unused variable: `args` + --> src/runtime/plugin_loader_v2.rs:270:46 + | +270 | pub fn create_box(&self, box_type: &str, args: &[Box]) -> BidResult> { + | ^^^^ help: if this is intentional, prefix it with an underscore: `_args` + +For more information about this error, try `rustc --explain E0782`. +warning: `nyash-rust` (lib) generated 33 warnings +error: could not compile `nyash-rust` (lib) due to 4 previous errors; 33 warnings emitted diff --git a/check_output.txt b/check_output.txt index e69de29b..5d420a90 100644 --- a/check_output.txt +++ b/check_output.txt @@ -0,0 +1,53 @@ +src/interpreter/core.rs:33:14: warning: unused macro definition: `debug_trace` +src/mir/loop_builder.rs:9:21: warning: unused imports: `BasicBlockIdGenerator`, `BasicBlock`, `CompareOp`, `EffectMask`, `MirFunction`, and `ValueIdGenerator` +src/mir/loop_builder.rs:13:33: warning: unused import: `HashSet` +src/backend/mod.rs:13:7: warning: unexpected `cfg` condition value: `llvm` +src/backend/mod.rs:23:7: warning: unexpected `cfg` condition value: `llvm` +src/backend/vm_phi.rs:9:41: warning: unused import: `MirInstruction` +src/bid/types.rs:1:5: warning: unused import: `super::Usize` +src/bid/plugin_api.rs:2:5: warning: unused import: `std::os::raw::c_char` +src/bid/plugins/filebox/mod.rs:7:18: warning: unused imports: `NyashHostVtable`, `NyashMethodInfo`, and `NyashPluginInfo` +src/bid/plugins/filebox/mod.rs:10:28: warning: unused imports: `SeekFrom` and `Seek` +src/bid/plugins/filebox/mod.rs:11:20: warning: unused imports: `c_char` and `c_void` +src/bid/plugins/filebox/mod.rs:13:16: warning: unused imports: `CStr` and `CString` +src/bid/loader.rs:4:5: warning: unused import: `std::ffi::c_void` +src/bid/generic_plugin_box.rs:5:23: warning: unused imports: `TlvDecoder` and `TlvEncoder` +src/bid/generic_plugin_box.rs:6:5: warning: unused import: `crate::bid::types::BidTag` +src/runtime/plugin_loader_v2.rs:10:47: warning: unused import: `BoxBase` +src/runtime/plugin_loader_v2.rs:14:9: warning: unused import: `std::ffi::c_void` +src/box_factory/plugin.rs:53:13: warning: unused variable: `registry`: help: if this is intentional, prefix it with an underscore: `_registry` +src/interpreter/expressions/calls.rs:739:13: warning: variable does not need to be mutable +src/interpreter/objects.rs:1106:17: warning: variable does not need to be mutable +src/instance_v2.rs:147:28: warning: unused variable: `args`: help: if this is intentional, prefix it with an underscore: `_args` +src/instance_v2.rs:289:21: warning: unused variable: `nyash_value`: help: if this is intentional, prefix it with an underscore: `_nyash_value` +src/mir/loop_builder.rs:246:39: warning: unused variable: `block_id`: help: if this is intentional, prefix it with an underscore: `_block_id` +src/mir/loop_builder.rs:273:49: warning: unused variable: `block_id`: help: if this is intentional, prefix it with an underscore: `_block_id` +src/backend/vm_phi.rs:48:9: warning: unused variable: `dst`: help: if this is intentional, prefix it with an underscore: `_dst` +src/bid/plugin_api.rs:167:36: warning: unused variable: `f`: help: if this is intentional, prefix it with an underscore: `_f` +src/bid/plugin_api.rs:167:26: warning: variable does not need to be mutable +src/bid/plugin_api.rs:176:35: warning: unused variable: `f`: help: if this is intentional, prefix it with an underscore: `_f` +src/bid/plugin_api.rs:176:25: warning: variable does not need to be mutable +src/bid/plugin_api.rs:183:34: warning: unused variable: `f`: help: if this is intentional, prefix it with an underscore: `_f` +src/bid/plugin_api.rs:183:24: warning: variable does not need to be mutable +src/runtime/plugin_loader_v2.rs:270:46: warning: unused variable: `args`: help: if this is intentional, prefix it with an underscore: `_args` +src/bid/plugins/filebox/mod.rs:44:5: warning: type `FileMode` is more private than the item `FileBoxRegistry::open`: method `FileBoxRegistry::open` is reachable at visibility `pub` +src/mir/loop_builder.rs:35:5: warning: field `block_var_maps` is never read +src/bid/metadata.rs:148:5: warning: fields `type_name_holder` and `method_holders` are never read +src/bid/plugins/filebox/mod.rs:24:5: warning: fields `path` and `mode` are never read +src/runtime/plugin_loader_v2.rs:24:5: warning: fields `box_types` and `init_fn` are never read +src/mir/loop_builder.rs:62:9: warning: unused `Result` that must be used +src/mir/loop_builder.rs:66:9: warning: unused `Result` that must be used +src/mir/loop_builder.rs:78:9: warning: unused `Result` that must be used +src/mir/loop_builder.rs:79:9: warning: unused `Result` that must be used +src/mir/loop_builder.rs:93:9: warning: unused `Result` that must be used +src/bid/plugins/filebox/mod.rs:102:12: warning: creating a shared reference to mutable static: shared reference to mutable static +src/bid/plugins/filebox/mod.rs:105:9: warning: creating a shared reference to mutable static: shared reference to mutable static +warning: `nyash-rust` (lib) generated 44 warnings (run `cargo fix --lib -p nyash-rust` to apply 19 suggestions) + Checking nyash-rust v0.1.0 (/mnt/c/git/nyash-project/nyash) +src/backend/vm.rs:18:12: error[E0432]: unresolved import `crate::scope_tracker`: unresolved import, help: a similar path exists: `nyash_rust::scope_tracker` +src/runner.rs:22:7: warning: unexpected `cfg` condition value: `llvm` +src/runner.rs:503:15: warning: unexpected `cfg` condition value: `llvm` +src/runner.rs:526:19: warning: unexpected `cfg` condition value: `llvm` +src/runner.rs:286:17: warning: variable does not need to be mutable +warning: `nyash-rust` (bin "nyash") generated 36 warnings (32 duplicates) +error: could not compile `nyash-rust` (bin "nyash") due to 1 previous error; 36 warnings emitted diff --git a/docs/CURRENT_TASK.md b/docs/CURRENT_TASK.md index 417fa1d9..ae43e96e 100644 --- a/docs/CURRENT_TASK.md +++ b/docs/CURRENT_TASK.md @@ -368,56 +368,54 @@ cargo build --release -j32 --features wasm-backend - ✅ substring(start, end)メソッド実装完了 - ✅ fini後のアクセスエラー削除(is_finalized()チェック削除) -## 🚀 **実装中: Phase 9.78a VM統一Box処理** +## 🛑 **一時停止: Phase 9.78a VM統一Box処理** -### 🎯 **目標: すべてのBox型をVMで統一的に処理** +### 📊 **完了した作業 (2025-08-21)** -**発見された問題**: -- ❌ ユーザー定義Box未対応(NewBoxで文字列返すだけ) -- ❌ birth/finiライフサイクル欠落 -- ❌ メソッド呼び出しハードコード +#### ✅ **Step 1: MIR生成修正** - 完了・保持 +`src/mir/builder.rs`の変更: +- すべてのBox型に対してNewBox命令を生成 +- RefNew命令の使用を廃止 +- **評価**: 良い変更、そのまま保持 -**解決策**: インタープリターと同等の統一処理を実装 +#### ✅ **VM実装準備** - ビルド可能な状態で一時停止 +- ScopeTrackerモジュール追加 +- VM構造体の拡張(コメントアウト状態) +- NewBox/BoxCall実装の簡易版 +- **状態**: コンパイル成功、警告のみ -### 📊 **実装ステップ(詳細分析済み)** +### 🔄 **次のステップ: インタープリター整理** -#### **Step 1: MIR生成修正** ✅ 分析完了 -**場所**: `src/mir/builder.rs` - `build_new_expression()` -```rust -// 現在: RefNew命令(不適切) -// 修正: NewBox命令を生成 -emit(MirInstruction::NewBox { - dst, - box_type: class, - args: arg_values -}) -``` +#### **整理計画** +1. **BoxDeclarationをAST層へ移動** + - 現在: `interpreter::BoxDeclaration` + - 目標: `ast::BoxDeclaration` -#### **Step 2: VM構造体拡張** 🔄 実装予定 -**場所**: `src/backend/vm.rs` -```rust -pub struct VM { - // 追加 - box_factory: Arc, - plugin_loader: Option>, - scope_tracker: ScopeTracker, - box_declarations: Arc>>, -} -``` +2. **SharedState依存の削減** + - 現在: インタープリター固有の設計 + - 目標: VM/MIRと共有可能な設計 -#### **Step 3: NewBox統一実装** 🔄 実装予定 -- BoxFactory経由で作成 -- ユーザー定義Boxのbirth実行 -- スコープ登録(fini用) +3. **統一ランタイム基盤の作成** + ```rust + pub struct NyashRuntime { + box_registry: Arc, + box_declarations: Arc>>, + } + ``` -#### **Step 4: BoxCall統一実装** 🔄 実装予定 -- ビルトイン/ユーザー定義/プラグイン統一処理 -- メソッドディスパッチ共通化 +### 📝 **保存された変更の概要** -#### **Step 5: ライフサイクル管理** 🔄 実装予定 -- ScopeTracker実装 -- スコープ終了時の自動fini -- 逆順実行(作成順と逆) +**保持している良い変更**: +- ✅ MIR生成のNewBox命令統一 +- ✅ ScopeTrackerの基本実装 +- ✅ VM拡張の方向性(TODOコメント付き) + +**一時的にコメントアウト**: +- BoxFactory/UnifiedBoxRegistry使用部分 +- interpreter::BoxDeclaration依存 +- プラグインローダー統合 + +**ビルド状態**: ✅ 正常(警告44個、エラー0個) ### 🔧 **共有コンポーネント** - `BoxFactory` - すでに存在、VMでも使用 diff --git a/docs/CURRENT_VM_CHANGES.md b/docs/CURRENT_VM_CHANGES.md new file mode 100644 index 00000000..92f9a8ff --- /dev/null +++ b/docs/CURRENT_VM_CHANGES.md @@ -0,0 +1,147 @@ +# 🔄 現在のVM変更状態 (2025-08-21) + +## 📊 Phase 9.78a VM統一Box処理の実装状況 + +### ✅ 完了したステップ + +#### **Step 1: MIR生成修正** ✅ +`src/mir/builder.rs`の変更内容: +```rust +// 変更前: RefNew命令(不適切) +match class.as_str() { + "IntegerBox" | "StringBox" | "BoolBox" => { + emit(MirInstruction::Const { ... }) + } + _ => { + emit(MirInstruction::RefNew { ... }) + } +} + +// 変更後: NewBox命令(統一) +emit(MirInstruction::NewBox { + dst, + box_type: class, + args: arg_values, +}) +``` +**評価**: ✅ 良い変更。すべてのBox型を統一的に扱える。 + +#### **Step 2: VM構造体拡張** 🔧 部分完了 +`src/backend/vm.rs`の変更内容: +1. **新規インポート追加**: + - `BoxFactory` → ❌ trait/struct混在問題 + - `InstanceBox` ✅ + - `BoxDeclaration` → ⚠️ interpreter依存 + - `ScopeTracker` ✅ + +2. **VM構造体への追加**: + ```rust + box_factory: Arc, // ❌ エラー:traitには dyn 必要 + plugin_loader: Option>, + scope_tracker: ScopeTracker, + box_declarations: Arc>>, + ``` + +3. **新規メソッド追加**: + - `new_with_factory()` → 名前変更必要 + - `new_with_plugins()` + +#### **Step 3: NewBox統一実装** 🔧 部分完了 +VM内のNewBox命令処理を統一実装に更新: +```rust +// BoxFactory経由で作成 +let new_box = match self.box_factory.create_box(box_type, arg_boxes) { + Ok(boxed) => boxed, + Err(e) => return Err(...), +}; +``` +**問題**: BoxFactoryがtraitなのでコンパイルエラー + +#### **Step 4: BoxCall統一実装** ✅ 完了 +- `call_unified_method()`を追加 +- 現在は簡易実装(call_box_methodに委譲) + +#### **Step 5: ライフサイクル管理** 🔧 部分完了 +- `ScopeTracker`を新規作成 +- `execute_function()`でスコープ管理追加 +- fini実装は簡易版 + +### 🚨 現在の問題点 + +1. **BoxFactory trait問題**: + - VMはBoxFactoryをstructとして期待 + - 実際はtraitとして定義されている + - `UnifiedBoxRegistry`を使うべきか? + +2. **BoxDeclaration依存問題**: + - `interpreter::BoxDeclaration`を使用 + - VMからinterpreterへの依存は良くない + +3. **ビルドエラー**: + ``` + error[E0782]: expected a type, found a trait + --> src/backend/vm.rs:175:22 + ``` + +## 🎯 推奨アクション + +### **Option A: 置いておく(推奨)** ✅ +**理由**: +- MIR生成修正(Step 1)は良い変更で保持すべき +- VM拡張の方向性は正しい +- インタープリター整理後に再開が効率的 + +**実行手順**: +```bash +# 現在の変更を一時保存 +git stash push -m "Phase 9.78a VM unified Box handling WIP" + +# または feature ブランチに保存 +git checkout -b feature/vm-unified-box-wip +git add -A +git commit -m "WIP: Phase 9.78a VM unified Box handling" +git checkout main +``` + +### **Option B: 部分的に保持** +**保持すべき部分**: +- ✅ MIR生成修正(Step 1) +- ✅ ScopeTracker実装 + +**巻き戻すべき部分**: +- ❌ VM構造体へのBoxFactory追加 +- ❌ interpreter::BoxDeclaration依存 + +### **Option C: 全て巻き戻す** +**非推奨**: MIR生成修正は価値があり、保持すべき + +## 📝 今後の計画 + +1. **Phase 1**: インタープリター整理 + - BoxDeclarationをast.rsへ移動 + - SharedState依存を減らす + - NyashRuntime共通基盤作成 + +2. **Phase 2**: VM実装再開 + - 整理されたインターフェースを使用 + - UnifiedBoxRegistryベースで実装 + - プラグインシステム統合 + +## 🔧 技術的詳細 + +### 変更されたファイル +- `src/mir/builder.rs`: -72行(RefNew → NewBox) +- `src/backend/vm.rs`: +164行(構造体拡張、メソッド追加) +- `src/lib.rs`: +1行(scope_trackerモジュール) +- `src/scope_tracker.rs`: 新規ファイル(68行) + +### 依存関係の問題 +``` +VM → interpreter::BoxDeclaration ❌ +VM → BoxFactory (trait) ❌ +VM → UnifiedBoxRegistry ✅ (推奨) +``` + +--- + +**結論**: **Option A(置いておく)**を推奨します。現在の実装は方向性として正しく、インタープリター整理後に続きから再開するのが最も効率的です。 \ No newline at end of file diff --git a/docs/architecture-redesign-proposal.md b/docs/architecture-redesign-proposal.md new file mode 100644 index 00000000..7db3ead2 --- /dev/null +++ b/docs/architecture-redesign-proposal.md @@ -0,0 +1,241 @@ +# 🌟 Nyash アーキテクチャ再設計提案 + +*by Codex exec (2025-08-21)* + +## 🎯 核心的洞察 + +**「実装詳細共有」から「モデル共有・実行時共有」への転換** + +現在の問題の本質は、InterpreterとVMが「実装詳細」を共有しようとしていること。正しいアプローチは「モデル(宣言)」と「ランタイム(実行環境)」を共有し、実行戦略だけを分離すること。 + +## 🏗️ 新アーキテクチャ層構造 + +``` +┌─────────────┐ +│ AST/Model │ ← 純粋なデータモデル(依存なし) +└──────┬──────┘ + │ +┌──────▼──────┐ +│ Runtime │ ← 型システム・クラス管理・インスタンス生成 +└──────┬──────┘ + │ +┌──────┴──────┬──────────┬────────────┐ +│ Interpreter │ VM │ Plugins │ +└─────────────┴──────────┴────────────┘ +``` + +### 各層の責務 + +**AST/Model層** +- 言語の純データモデル +- BoxDeclaration、ASTNode、型シグネチャ +- 実行時情報を含まない + +**Runtime層** +- BoxClass/BoxFactoryによる型システム +- インスタンス生成とライフサイクル管理 +- メソッドディスパッチと呼び出し規約 + +**Backend層** +- Interpreter: AST直接実行 +- VM: MIR/Bytecode実行 +- 両者ともRuntimeを通じてBoxを操作 + +## 🔧 具体的な設計 + +### 1. BoxDeclarationの移動 + +```rust +// core::model::box_declaration.rs +pub struct BoxDeclaration { + pub name: String, + pub type_params: Vec, + pub fields: Vec, + pub methods: Vec, + pub static_methods: Vec, + pub attrs: AttrSet, + pub source_span: Option, +} + +pub struct FieldDecl { + pub name: String, + pub ty: TypeRef, + pub attrs: AttrSet, +} + +pub struct MethodDecl { + pub name: String, + pub sig: FnSig, + pub body: FnBodyRef, // AST or MIR reference +} +``` + +### 2. NyashRuntimeの導入 + +```rust +// runtime::mod.rs +pub struct NyashRuntime { + box_registry: BoxRegistry, + type_space: TypeSpace, + fn_space: FnSpace, +} + +pub struct ExecutionSession { + runtime: Arc, + root_box: SharedBox, + frames: Vec, + env: Environment, +} + +// SharedBox = Arc +pub type SharedBox = Arc; +``` + +### 3. BoxClass/Factoryシステム + +```rust +// runtime::box_class.rs +pub trait BoxClass: Send + Sync { + fn name(&self) -> &str; + fn instantiate( + &self, + args: &[SharedBox], + sess: &mut ExecutionSession + ) -> Result; + fn lookup_method(&self, name: &str) -> Option; + fn lifecycle(&self) -> Option<&dyn BoxLifecycle>; +} + +pub trait BoxFactory: Send + Sync { + fn can_build(&self, decl: &BoxDeclaration) -> bool; + fn build_class( + &self, + decl: &BoxDeclaration, + rt: &NyashRuntime + ) -> Result>; +} + +pub trait BoxLifecycle { + fn on_birth(&self, ctx: &mut InstanceCtx) -> Result<()>; + fn on_fini(&self, ctx: &mut InstanceCtx); +} +``` + +### 4. 統一されたBox管理 + +```rust +// runtime::registry.rs +pub struct BoxRegistry { + classes: RwLock>>, + factories: RwLock>>, +} + +impl BoxRegistry { + pub fn register_class(&self, class: Arc) { + // 登録処理 + } + + pub fn get_class(&self, name: &str) -> Option> { + // クラス取得 + } + + pub fn create_instance( + &self, + class_name: &str, + args: &[SharedBox], + sess: &mut ExecutionSession + ) -> Result { + let class = self.get_class(class_name)?; + class.instantiate(args, sess) + } +} +``` + +## 📋 実装手順(最小破壊的移行) + +### Step 1: BoxDeclarationの移動 +```rust +// 1. core::model モジュールを作成 +// 2. BoxDeclarationを移動 +// 3. インタープリターで一時的に別名を使用 +use core::model::BoxDeclaration as InterpreterBoxDecl; +``` + +### Step 2: NyashRuntimeの骨組み作成 +```rust +// 最初は空の実装から始める +pub struct NyashRuntime { + // 段階的に追加 +} + +pub struct NyashRuntimeBuilder { + // SharedStateからの移行を支援 +} +``` + +### Step 3: BoxFactoryのdyn化 +```rust +// 現在の trait BoxFactory を使用 +// すべて Arc として扱う +``` + +### Step 4: グローバル登録の排除 +```rust +// 削除: register_user_defined_factory(...) +// 追加: NyashRuntimeBuilder::with_factory(...) +``` + +### Step 5: SharedStateの段階的分解 +```rust +// 一時的なシム +pub struct SharedStateShim { + runtime: Arc, + session: ExecutionSession, +} + +// 互換性のためのFrom実装 +impl From for SharedStateShim { + // 移行ロジック +} +``` + +### Step 6-8: 統一と最適化 +- Interpreter/VMのコンストラクタ統一 +- birth/finiライフサイクルの一元化 +- 最終的なSharedState削除 + +## 🎯 得られる利点 + +1. **依存関係の明確化** + - VM→Interpreter依存が完全に解消 + - 両者はRuntimeのみに依存 + +2. **テスタビリティ向上** + - グローバル状態なし + - 並行テスト可能 + +3. **保守性向上** + - 責務が明確に分離 + - 新しいBackend追加が容易 + +4. **Everything is Box哲学の貫徹** + - 統一的なBox管理 + - birth/finiライフサイクルの一元化 + +## ⚠️ 実装上の注意点 + +1. **trait objectは必ず`Arc`** + - `Arc`は使わない + - dynキーワードを忘れない + +2. **段階的移行** + - 各ステップでテストが通ることを確認 + - 互換性レイヤーを活用 + +3. **ロックの最小化** + - Runtimeは基本的に不変 + - 必要最小限のRwLock使用 + +--- + +この設計により、Nyashはよりシンプルでエレガントなアーキテクチャとなり、InterpreterとVMの統合が自然に実現されます。 \ No newline at end of file diff --git a/docs/archive/codex-analysis/2025-08-21-codex-response-full.md b/docs/archive/codex-analysis/2025-08-21-codex-response-full.md new file mode 100644 index 00000000..550bce87 --- /dev/null +++ b/docs/archive/codex-analysis/2025-08-21-codex-response-full.md @@ -0,0 +1,238 @@ +# Codex exec 天才的分析回答 (2025-08-21) + +**モデル**: GPT-5 +**実行時間**: 2025-08-20T08:13:13 - 08:14:35 +**トークン使用**: 14,603 (入力: 6,325 + 出力: 8,278) + +## 結論 + +依存の向きと責務を正し、Interpreter/VMの「実装詳細共有」をやめて「モデル共有・実行時共有」に転換します。鍵は「Everything is Box」をタイプシステムとクラス実装にも一貫させつつ、「AST/宣言モデル」と「Runtimeクラス・インスタンス」を厳密に分離することです。 + +## 層構造 + +- **AST/Model**: 言語の純データモデル。依存先なし。 +- **Runtime**: 型系・クラス登録・インスタンス生成・ライフサイクル・呼出し規約。ASTにのみ依存。 +- **Backends**: Interpreter と VM。どちらも Runtime にのみ依存(ASTは入力として読むが、構造体はRuntimeを介して使う)。 +- **Plugins**: BoxClass/Factory を提供。RuntimeのAPIにのみ依存。グローバルへは一切依存しない。 + +依存関係: AST → Runtime → Interpreter/VM(Plugins は Runtime へ) + +## 各質問への回答 + +### 1) アーキテクチャ再設計 + +**境界の引き直し**: +- AST/Model: 宣言とシグネチャの「静的情報」だけを保持。 +- Runtime: クラス定義(vtable/ディスパッチ)、レジストリ、インスタンス化、birth/fini、呼出し規約、セッション(Fiber/Frame)等。 +- Backends: 実行方式(AST直解釈 or MIR/Bytecode)だけを差し替える。Boxは常にRuntimeで生成・管理。 + +**セッション単位**: +- `NyashRuntime` は「不変に近い共有資産」(クラス登録、型定義、グローバルな定数等)。 +- `ExecutionSession` は「実行ごとの可変状態」(root/global box、スタック、環境変数、I/O handles等)。Interpreter/VMどちらも同じセッション型を使う。 + +### 2) BoxDeclaration の適切配置 + +**場所**: `ast::model`(もしくは `core::model`)に移動。Interpreter固有の型は参照しない。 + +**必要な情報(純データ)**: +- `name: String` +- `type_params: Vec` +- `fields: Vec` +- `methods: Vec` +- `static_methods: Vec` +- `attrs: AttrSet` +- `source_span: Option`(任意) + +**不要な情報(AST層から排除)**: +- 実行時ハンドル(`Arc`、`InstanceBox` 等) +- 共有状態やミューテックス +- インタープリターのクロージャ/関数ポインタ + +**Body表現**: +- AST直実行であれば `FnBodyRef::Ast(AstNodeId)`。 +- VM/MIR 変換後は `FnBodyRef::Mir(MirFuncId)` を追加可能(後方互換のため enum)。 + +### 3) SharedState の解体 + +**役割で分割**: + +**ランタイム共通へ移すもの**: +- `box_declarations` → `NyashRuntime.type_space`(宣言と型定義) +- `static_box_definitions` → `NyashRuntime.class_space`(宣言→クラスの束縛) +- `static_functions` → `NyashRuntime.fn_space`(宣言・シグネチャ中心。実行体は `FnBodyRef`) +- `included_files` → ビルド/ロードフェーズの `ModuleLoaderState`(実行時からは外す) + +**実行ごとの状態**: +- `global_box` → `ExecutionSession.root_box: SharedBox`(Interpreter/VM共通) + +**新コントラクト**: +- `NyashRuntime` は基本不変。`Arc`で共有。 +- 変更を伴うロード時は `NyashRuntimeBuilder` を使い、確定後に `NyashRuntime` をクローン共有。 +- 実行時は `ExecutionSession` が唯一の可変中核(スタック、環境、root/global box など)。 + +### 4) BoxFactory/Registry の統一設計 + +**コアの型** + +```rust +trait NyashBox: Any + Send + Sync { + // インスタンスの振る舞い + // get_field/set_field/call_method 等 + // as_any で downcast 可能 +} + +trait BoxClass: Send + Sync { + fn name(&self) -> &str; + fn instantiate(&self, args: &[SharedBox], sess: &mut ExecutionSession) -> Result; + fn lookup_method(&self, name: &str) -> Option; + fn lifecycle() -> Option<&dyn BoxLifecycle>; +} + +trait BoxFactory: Send + Sync { + fn can_build(&self, decl: &BoxDeclaration) -> bool; + fn build_class(&self, decl: &BoxDeclaration, rt: &NyashRuntime) -> Result>; +} +``` + +**レジストリ** +- `BoxRegistry`(Runtime内) + - `register_class(class: Arc)` + - `get_class(name: &str) -> Option>` + - `register_factory(factory: Arc)` + - `materialize_from_decl(decl: &BoxDeclaration)`(必要に応じ lazy materialize) + +**ライフサイクル(birth/fini)** +- `trait BoxLifecycle { fn on_birth(&self, &mut InstanceCtx) -> Result<()>; fn on_fini(&self, &mut InstanceCtx); }` +- `BoxClass::lifecycle() -> Option<&dyn BoxLifecycle>` +- 生成は `instantiate` の内部で birth を呼ぶ。破棄は `Drop` フックか `Session` の `on_scope_exit` で fini を呼ぶ。 + +**プラグイン** +- Runtimeに明示登録するのみ(グローバル関数禁止) + - `NyashRuntimeBuilder::with_factory(Arc)` +- 動的ロードは別フェーズ(feature flagで opt-in)。基本は静的リンク/明示登録。 + +**dyn の注意点**: +- VM/Interpreter ともに `Arc` / `Arc` / `SharedBox = Arc` を使用。`Arc` は使わない。 + +### 5) 具体的な実装手順(最小破壊で段階導入) + +**Step 1: BoxDeclaration の移動** +- `interpreter::BoxDeclaration` を `core::model::BoxDeclaration` へ抽出。 +- インタープリターは `use core::model::BoxDeclaration as InterpreterBoxDecl` の一時別名でコンパイル維持。 + +**Step 2: NyashRuntime の導入(空の骨組み→段階拡張)** +- `NyashRuntime { box_registry, type_space, fn_space }` を追加。 +- `NyashRuntimeBuilder` を作り、現行の `SharedState` から必要データを移送できるようにする。 + +**Step 3: BoxRegistry と Factory の dyn 化** +- `BoxFactory`/`BoxClass` を上記インターフェースへ統一(dyn前提)。 +- 旧 `UserDefinedBoxFactory` は `Arc` で登録するようにリライト。 + +**Step 4: グローバル登録の排除** +- `register_user_defined_factory(...)` のようなグローバル関数は削除/非推奨に。 +- 代わりに `NyashRuntimeBuilder::with_factory(...)` を使用。 + +**Step 5: SharedState の分解** +- `global_box` を `ExecutionSession.root_box` に移動。 +- 残るマップ類をそれぞれ `type_space / fn_space / class_space` へ移譲。 +- Interpreter 側は `SharedStateShim { runtime: Arc, session: ExecutionSession }` を暫定導入して最小変更で通す。 + +**Step 6: Interpreter/VM のコンストラクタ統一** +- `NyashInterpreter::new(runtime: Arc)` +- `VM::new(runtime: Arc)` +- 双方 `ExecutionSession::new(runtime.clone())` から root などを初期化。 + +**Step 7: birth/fini の統一呼出し点** +- すべてのインスタンス生成を `BoxClass::instantiate` 経由に統一。 +- 破棄時の fini 呼出しを `ExecutionSession` のスコープ管理に集約。 + +**Step 8: 段階的移行と互換** +- 旧APIの薄いアダプタを用意(例えば `impl From for NyashRuntimeBuilder`)。 +- 段階ごとにテストが通るかを確認し、最後に `SharedState` を削除。 + +## 各論の要点 + +**依存関係の整理** +- VM→Interpreter 依存を完全に撤去。両者は Runtime のみを参照。 +- Interpreter固有の「実行戦略」は Backend に閉じ込め、Box管理・生成は Runtime に一元化。 +- `ASTNode` は Backend の評価対象だが、Box生成はすべて `BoxRegistry` を介す。 + +**Everything is Box の貫徹(シンプルに)** +- 値は `SharedBox = Arc`。 +- 型/クラスは値ではなく「クラスオブジェクト」として `Arc`(必要であればメタ階層で `ClassBox` を実装して値化できるが、初期段階では過剰にしない)。 +- つまり「実行時に扱う実体は必ず Box」、クラスは Box を生み出す工場であり、インスタンスはランタイム一元管理。 + +**テスタビリティと並行実行** +- ランタイムは不変に近い `Arc` 共有、セッションは疎結合で複数同時に生成可能。 +- グローバル無効化、明示 DI(Runtime/Session 引数渡し)。 +- テストでは毎回 `NyashRuntimeBuilder` から新鮮な Runtime を生成可能。並行テストで衝突なし。 + +**VM実装の容易化** +- VM は Bytecode/MIR のみを意識。Box生成/呼出しは Runtime の `BoxClass/Registry` に任せる。 +- birth/fini も `instantiate`/`Session` に含めるため、VM は命令列の実行に集中できる。 + +## 参考スケルトン + +**ランタイム** +```rust +pub struct NyashRuntime { + box_registry: BoxRegistry, + type_space: TypeSpace, + fn_space: FnSpace +} + +pub struct ExecutionSession { + runtime: Arc, + root_box: SharedBox, + frames: Vec, + env: Env +} +``` + +**レジストリ** +```rust +pub struct BoxRegistry { + classes: RwLock>>, + factories: RwLock>> +} +``` + +**トレイト** +```rust +pub trait NyashBox { + fn get_field(...); + fn set_field(...); + fn call_method(...); + fn as_any(&self) -> &dyn Any; +} + +pub trait BoxClass { + fn name(&self) -> &str; + fn instantiate(&self, args: &[SharedBox], sess: &mut ExecutionSession) -> Result; + fn lookup_method(&self, name: &str) -> Option; + fn lifecycle(&self) -> Option<&dyn BoxLifecycle>; +} + +pub trait BoxFactory { + fn can_build(&self, decl: &BoxDeclaration) -> bool; + fn build_class(&self, decl: &BoxDeclaration, rt: &NyashRuntime) -> Result>; +} + +pub trait BoxLifecycle { + fn on_birth(&self, ctx: &mut InstanceCtx) -> Result<()>; + fn on_fini(&self, ctx: &mut InstanceCtx); +} +``` + +## 実装上の落とし穴と回避 + +- **trait object の型**: 必ず `Arc`。`Arc` は不可。`dyn` を徹底。 +- **InstanceBox の役割**: もし「ユーザー定義のレコード/オブジェクト」の具象表現なら、それ自体は `NyashBox` 実装。VM/Interpreter は InstanceBox のレイアウトを知らなくてよい(`NyashBox` 経由で操作)。 +- **共有ロックの過剰化**: Runtime は基本不変。レジストリも初期化後は読み取り中心。クラス遅延構築だけ `RwLock` で十分。 +- **birth/fini の二重呼び出し防止**: `instantiate`/`Drop` の責務を一本化。Session スコープまたぎの移動に注意。 + +## 最後に + +この設計は「モデル(宣言)と実装(クラス/インスタンス)」の責務を分け、Interpreter/VM の接合点を Runtime に集約します。グローバル副作用を除去し、`Arc` に統一することで、VM と Interpreter の相互依存が解消され、テスト・並行実行が自然になります。段階的移行のステップを踏めば、最小限の変更で最大の整理効果を得られます。 + +必要なら、上記スケルトンに合わせた最初のパッチ(`core::model::BoxDeclaration` と `NyashRuntime`/`Builder` の最小骨組み)まで作成します。 \ No newline at end of file diff --git a/docs/archive/codex-analysis/2025-08-21-interpreter-refactoring-request.txt b/docs/archive/codex-analysis/2025-08-21-interpreter-refactoring-request.txt new file mode 100644 index 00000000..299dc74b --- /dev/null +++ b/docs/archive/codex-analysis/2025-08-21-interpreter-refactoring-request.txt @@ -0,0 +1,91 @@ +Nyashプログラミング言語のインタープリター・VM統合アーキテクチャ再設計について深い分析をお願いします。 + +【背景】 +Nyashは「Everything is Box」哲学のプログラミング言語で、現在インタープリターとVM(Phase 9.78a)の統合で設計上の問題に直面しています。 + +【現在の問題点】 + +1. **依存関係の逆転** + - BoxDeclarationがinterpreter::BoxDeclarationとして定義 + - VMがインタープリターに依存してしまう + - 本来はAST層に属すべきデータ構造 + +2. **SharedState中心の設計** + ```rust + pub struct SharedState { + pub global_box: Arc>, + pub box_declarations: Arc>>, + pub static_functions: Arc>>>, + pub static_box_definitions: Arc>>, + pub included_files: Arc>>, + } + ``` + - インタープリター固有の実装詳細に依存 + - VMから使いにくい構造 + +3. **BoxFactory設計の混乱** + - BoxFactoryがtraitとして定義されている + - UserDefinedBoxFactoryがSharedStateに依存 + - VMではArcでコンパイルエラー(dynが必要) + +4. **グローバル副作用** + ```rust + let factory = UserDefinedBoxFactory::new(shared.clone()); + register_user_defined_factory(Arc::new(factory)); + ``` + - グローバルレジストリへの登録 + - テストや並行実行で問題 + +5. **VM実装の困難** + - インタープリターの実装詳細に依存 + - 統一的なBox管理ができない + - birth/finiライフサイクルの不統一 + +【要求事項】 +1. インタープリターとVMで共通のBox管理メカニズム +2. 依存関係の整理(AST → Runtime → Interpreter/VM) +3. テスタブルで並行実行可能な設計 +4. シンプルで美しい実装 +5. Everything is Box哲学の維持 + +【質問】 + +1. **アーキテクチャ全体の再設計** + - どのような層構造が最も美しく保守しやすいか? + - 依存関係をどう整理すべきか? + +2. **BoxDeclarationの適切な配置** + - AST層に移動すべきか、それとも別の共通層を作るべきか? + - 必要な情報は何か?不要な情報は何か? + +3. **SharedStateの解体** + - どの部分を共通ランタイムに移すべきか? + - インタープリター固有の部分はどう分離すべきか? + +4. **BoxFactory/Registryの統一設計** + - traitベースか、具体的な構造体ベースか? + - プラグインシステムとの統合方法は? + +5. **具体的な実装手順** + - 最小限の変更で最大の効果を得る順序は? + - 既存コードとの互換性を保ちながら進める方法は? + +【理想の設計】 +```rust +// 例:こんな感じ? +pub struct NyashRuntime { + box_registry: BoxRegistry, + type_definitions: HashMap, +} + +// インタープリターもVMも同じランタイムを使用 +impl NyashInterpreter { + pub fn new(runtime: NyashRuntime) -> Self { ... } +} + +impl VM { + pub fn new(runtime: NyashRuntime) -> Self { ... } +} +``` + +Nyashの「Everything is Box」哲学を活かしつつ、最もシンプルで美しく、保守しやすいアーキテクチャを提案してください。特に、天才的な洞察で問題の本質を見抜き、エレガントな解決策を示してください。 \ No newline at end of file diff --git a/docs/予定/native-plan/issues/phase_9_78b_interpreter_architecture_refactoring.md b/docs/予定/native-plan/issues/phase_9_78b_interpreter_architecture_refactoring.md new file mode 100644 index 00000000..d1d56dc2 --- /dev/null +++ b/docs/予定/native-plan/issues/phase_9_78b_interpreter_architecture_refactoring.md @@ -0,0 +1,212 @@ +# Phase 9.78b: インタープリター・VM統合アーキテクチャ再設計 + +**作成日**: 2025-08-21 +**優先度**: 最高(Phase 9.78aの前提条件) +**設計者**: Codex exec (天才的洞察) +**実装者**: Claude + User + +## 🎯 目標 + +InterpreterとVMの「実装詳細共有」から「モデル共有・実行時共有」への転換を実現し、依存関係を整理する。 + +## 📊 現状の問題(Phase 9.78aで発覚) + +1. **依存関係の逆転** + - `BoxDeclaration`が`interpreter::BoxDeclaration`として定義 + - VMがインタープリターに依存 + +2. **SharedState中心の設計** + - インタープリター固有の実装詳細 + - VMから使いにくい + +3. **BoxFactoryのtrait問題** + - `Arc`でコンパイルエラー(`dyn`が必要) + +4. **グローバル副作用** + - テスト・並行実行で問題 + +## 🏗️ 新アーキテクチャ設計 + +``` +AST/Model → Runtime → Interpreter/VM + ↑ + Plugins +``` + +### 核心的変更 +- **モデル層**: BoxDeclaration等の純粋データ +- **ランタイム層**: BoxClass/Factory、インスタンス管理 +- **バックエンド層**: 実行戦略のみ(AST実行 or MIR実行) + +## 📋 実装ステップ(8段階) + +### ✅ Step 1: BoxDeclarationの移動 +**期限**: 1日 +**リスク**: 低 +**作業内容**: +1. `src/core/model.rs`を作成 +2. `BoxDeclaration`を`interpreter::BoxDeclaration`から移動 +3. 一時的な別名で互換性維持 +```rust +use core::model::BoxDeclaration as InterpreterBoxDecl; +``` + +**成功基準**: +- [ ] ビルド成功(警告OK) +- [ ] 既存テスト全パス + +### ✅ Step 2: NyashRuntime骨組み作成 +**期限**: 1日 +**リスク**: 低 +**作業内容**: +1. `src/runtime/mod.rs`作成 +2. 最小限の`NyashRuntime`構造体 +3. `NyashRuntimeBuilder`追加 + +**成功基準**: +- [ ] 新モジュールのビルド成功 +- [ ] 既存コードへの影響なし + +### ✅ Step 3: BoxFactoryのdyn化 +**期限**: 2日 +**リスク**: 中 +**作業内容**: +1. すべての`Arc`を`Arc`に変更 +2. `BoxClass`トレイト導入 +3. `BoxRegistry`実装 + +**成功基準**: +- [ ] trait object正しく使用 +- [ ] VMでのコンパイルエラー解消 + +### ✅ Step 4: グローバル登録の排除 +**期限**: 1日 +**リスク**: 中 +**作業内容**: +1. `register_user_defined_factory()`削除 +2. `NyashRuntimeBuilder::with_factory()`追加 +3. 既存の登録箇所を修正 + +**成功基準**: +- [ ] グローバル関数の完全削除 +- [ ] 明示的な依存注入に移行 + +### ✅ Step 5: SharedState分解 +**期限**: 3日 +**リスク**: 高 +**作業内容**: +1. `SharedStateShim`導入(互換層) +2. フィールドを段階的に移行 + - `box_declarations` → `type_space` + - `global_box` → `ExecutionSession.root_box` +3. テストを随時実行 + +**成功基準**: +- [ ] SharedStateShim経由で動作 +- [ ] 既存機能の維持 + +### ✅ Step 6: Interpreter/VM統一 +**期限**: 2日 +**リスク**: 中 +**作業内容**: +1. 共通コンストラクタ実装 +2. `ExecutionSession`共有 +3. VM側のBox管理をRuntime経由に + +**成功基準**: +- [ ] 両者が同じRuntimeを使用 +- [ ] VMでのBox生成成功 + +### ✅ Step 7: ライフサイクル統一 +**期限**: 2日 +**リスク**: 中 +**作業内容**: +1. birth/finiをBoxClass経由に +2. ScopeTrackerとの統合 +3. 全Box型で動作確認 + +**成功基準**: +- [ ] birth/fini正しく呼ばれる +- [ ] メモリリークなし + +### ✅ Step 8: クリーンアップ +**期限**: 1日 +**リスク**: 低 +**作業内容**: +1. SharedState完全削除 +2. 不要な互換層削除 +3. ドキュメント更新 + +**成功基準**: +- [ ] コードベースの簡潔性 +- [ ] 全テストパス + +## 🔗 関連リンク + +- **設計書**: [architecture-redesign-proposal.md](../../../architecture-redesign-proposal.md) +- **VM実装状況**: [CURRENT_VM_CHANGES.md](../../../CURRENT_VM_CHANGES.md) +- **現在のタスク**: [CURRENT_TASK.md](../../../CURRENT_TASK.md) +- **Codex分析**: nyash_interpreter_refactoring_analysis.txt + +## 📊 進捗トラッキング + +| Step | 状態 | 開始日 | 完了日 | 担当 | 備考 | +|------|------|--------|--------|------|------| +| 1 | 未着手 | - | - | - | BoxDeclaration移動 | +| 2 | 未着手 | - | - | - | Runtime骨組み | +| 3 | 未着手 | - | - | - | dyn化 | +| 4 | 未着手 | - | - | - | グローバル排除 | +| 5 | 未着手 | - | - | - | SharedState分解 | +| 6 | 未着手 | - | - | - | 統一 | +| 7 | 未着手 | - | - | - | ライフサイクル | +| 8 | 未着手 | - | - | - | クリーンアップ | + +## ⚠️ リスクと対策 + +### 高リスク項目 +1. **SharedState分解(Step 5)** + - 対策: SharedStateShimで段階的移行 + - ロールバック: git stashで保存 + +2. **ライフサイクル統一(Step 7)** + - 対策: 十分なテストケース作成 + - ロールバック: 旧実装を一時保持 + +### 中リスク項目 +1. **BoxFactoryのdyn化(Step 3)** + - 対策: コンパイラエラーを1つずつ解決 + - ロールバック: trait定義を調整 + +## 🧪 テスト戦略 + +1. **各ステップでの確認** + - `cargo test`全パス必須 + - `cargo check --lib`でビルド確認 + +2. **統合テスト** + - インタープリター動作確認 + - VM動作確認(Step 6以降) + +3. **パフォーマンステスト** + - Step 8完了後に実施 + - 既存ベンチマークと比較 + +## 📝 作業時の注意事項 + +1. **trait objectは必ず`Arc`** + - ❌ `Arc` + - ✅ `Arc` + +2. **段階的移行の厳守** + - 各ステップでビルド成功必須 + - テスト失敗したら即修正 + +3. **CURRENT_TASK.mdの更新** + - 作業開始時に更新 + - 問題発生時に記録 + - 完了時に結果記載 + +--- + +**総工数見積もり**: 14日(各ステップにバッファ含む) +**推奨アプローチ**: Step 1-2を先行実施して感触を掴む \ No newline at end of file diff --git a/src/backend/vm.rs b/src/backend/vm.rs index 950762e3..67b7f1af 100644 --- a/src/backend/vm.rs +++ b/src/backend/vm.rs @@ -7,8 +7,18 @@ use crate::mir::{MirModule, MirFunction, MirInstruction, ConstValue, BinaryOp, CompareOp, UnaryOp, ValueId, BasicBlockId}; use crate::box_trait::{NyashBox, StringBox, IntegerBox, BoolBox, VoidBox}; use std::collections::HashMap; +use std::sync::Arc; use super::vm_phi::LoopExecutor; +// Phase 9.78a: Import necessary components for unified Box handling +// TODO: Re-enable when interpreter refactoring is complete +// use crate::box_factory::UnifiedBoxRegistry; +// use crate::instance_v2::InstanceBox; +// use crate::interpreter::BoxDeclaration; +// use crate::scope_tracker::ScopeTracker; +// #[cfg(all(feature = "plugins", not(target_arch = "wasm32")))] +// use crate::runtime::plugin_loader_v2::PluginLoaderV2; + /// VM execution error #[derive(Debug)] pub enum VMError { @@ -44,6 +54,8 @@ pub enum VMValue { String(String), Future(crate::boxes::future::FutureBox), Void, + // Phase 9.78a: Add BoxRef for complex Box types + BoxRef(Arc), } // Manual PartialEq implementation to avoid requiring PartialEq on FutureBox @@ -57,6 +69,8 @@ impl PartialEq for VMValue { (VMValue::Void, VMValue::Void) => true, // Future equality semantics are not defined; treat distinct futures as not equal (VMValue::Future(_), VMValue::Future(_)) => false, + // BoxRef equality by reference + (VMValue::BoxRef(_), VMValue::BoxRef(_)) => false, _ => false, } } @@ -72,6 +86,8 @@ impl VMValue { VMValue::String(s) => Box::new(StringBox::new(s)), VMValue::Future(f) => Box::new(f.clone()), VMValue::Void => Box::new(VoidBox::new()), + // Phase 9.78a: BoxRef returns cloned Box + VMValue::BoxRef(arc_box) => arc_box.clone_box(), } } @@ -84,6 +100,7 @@ impl VMValue { VMValue::String(s) => s.clone(), VMValue::Future(f) => f.to_string_box().value, VMValue::Void => "void".to_string(), + VMValue::BoxRef(arc_box) => arc_box.to_string_box().value, } } @@ -106,7 +123,7 @@ impl VMValue { /// Convert from NyashBox to VMValue pub fn from_nyash_box(nyash_box: Box) -> VMValue { - // Try to downcast to known types + // Try to downcast to known types for optimization if let Some(int_box) = nyash_box.as_any().downcast_ref::() { VMValue::Integer(int_box.value) } else if let Some(bool_box) = nyash_box.as_any().downcast_ref::() { @@ -116,8 +133,8 @@ impl VMValue { } else if let Some(future_box) = nyash_box.as_any().downcast_ref::() { VMValue::Future(future_box.clone()) } else { - // For any other type, convert to string representation - VMValue::String(nyash_box.to_string_box().value) + // Phase 9.78a: For all other Box types (user-defined, plugin), store as BoxRef + VMValue::BoxRef(Arc::from(nyash_box)) } } } @@ -154,6 +171,17 @@ pub struct VM { object_fields: HashMap>, /// Loop executor for handling phi nodes and loop-specific logic loop_executor: LoopExecutor, + // Phase 9.78a: Add unified Box handling components + // TODO: Re-enable when interpreter refactoring is complete + // /// Box registry for creating all Box types + // box_registry: Arc, + // /// Plugin loader for external Box types + // #[cfg(all(feature = "plugins", not(target_arch = "wasm32")))] + // plugin_loader: Option>, + // Scope tracker for lifecycle management + // scope_tracker: ScopeTracker, + // /// Box declarations from the AST + // box_declarations: Arc>>, } impl VM { @@ -168,9 +196,38 @@ impl VM { last_result: None, object_fields: HashMap::new(), loop_executor: LoopExecutor::new(), + // TODO: Re-enable when interpreter refactoring is complete + // box_registry: Arc::new(UnifiedBoxRegistry::new()), + // #[cfg(all(feature = "plugins", not(target_arch = "wasm32")))] + // plugin_loader: None, + // scope_tracker: ScopeTracker::new(), + // box_declarations: Arc::new(RwLock::new(HashMap::new())), } } + // TODO: Re-enable when interpreter refactoring is complete + /* + /// Create a new VM instance with Box registry and declarations + pub fn new_with_registry( + box_registry: Arc, + box_declarations: Arc>> + ) -> Self { + // Implementation pending interpreter refactoring + unimplemented!() + } + + /// Phase 9.78a: Create VM with plugin support + #[cfg(all(feature = "plugins", not(target_arch = "wasm32")))] + pub fn new_with_plugins( + box_registry: Arc, + plugin_loader: Arc, + box_declarations: Arc>>, + ) -> Self { + // Implementation pending interpreter refactoring + unimplemented!() + } + */ + /// Execute a MIR module pub fn execute_module(&mut self, module: &MirModule) -> Result, VMError> { // Find main function @@ -191,6 +248,9 @@ impl VM { // Initialize loop executor for this function self.loop_executor.initialize(); + // Phase 9.78a: Enter a new scope for this function + // self.scope_tracker.push_scope(); + // Start at entry block let mut current_block = function.entry_block; @@ -224,6 +284,8 @@ impl VM { // Handle control flow if let Some(return_value) = should_return { + // Phase 9.78a: Exit scope before returning + // self.scope_tracker.pop_scope(); return Ok(return_value); } else if let Some(target) = next_block { // Update previous block before jumping @@ -234,6 +296,8 @@ impl VM { } else { // Block ended without terminator - this shouldn't happen in well-formed MIR // but let's handle it gracefully by returning void + // Phase 9.78a: Exit scope before returning + // self.scope_tracker.pop_scope(); return Ok(VMValue::Void); } } @@ -354,9 +418,16 @@ impl VM { }, MirInstruction::BoxCall { dst, box_val, method, args, effects: _ } => { + // Phase 9.78a: Unified method dispatch for all Box types + // Get the box value let box_vm_value = self.get_value(*box_val)?; - let box_nyash = box_vm_value.to_nyash_box(); + + // Handle BoxRef for proper method dispatch + let box_nyash = match &box_vm_value { + VMValue::BoxRef(arc_box) => arc_box.clone_box(), + _ => box_vm_value.to_nyash_box(), + }; // Evaluate arguments let mut arg_values = Vec::new(); @@ -365,8 +436,8 @@ impl VM { arg_values.push(arg_vm_value.to_nyash_box()); } - // Call the method - this mimics interpreter method dispatch - let result = self.call_box_method(box_nyash, method, arg_values)?; + // Call the method - unified dispatch for all Box types + let result = self.call_unified_method(box_nyash, method, arg_values)?; // Store result if destination is specified if let Some(dst_id) = dst { @@ -376,32 +447,54 @@ impl VM { Ok(ControlFlow::Continue) }, - MirInstruction::NewBox { dst, box_type, args: _ } => { - // Implement basic box creation for common types + MirInstruction::NewBox { dst, box_type, args } => { + // Phase 9.78a: Simplified Box creation (temporary until interpreter refactoring) + + // Evaluate arguments + let mut arg_values = Vec::new(); + for arg_id in args { + let arg_value = self.get_value(*arg_id)?; + arg_values.push(arg_value); + } + + // Basic Box creation for common types let result = match box_type.as_str() { "StringBox" => { - // Create empty StringBox - in real implementation would use args - let string_box = Box::new(StringBox::new("")); - VMValue::from_nyash_box(string_box) + // Get first argument as string, or empty string + let value = if let Some(arg) = arg_values.first() { + arg.to_string() + } else { + String::new() + }; + VMValue::String(value) + }, + "IntegerBox" => { + // Get first argument as integer, or 0 + let value = if let Some(arg) = arg_values.first() { + arg.as_integer().unwrap_or(0) + } else { + 0 + }; + VMValue::Integer(value) + }, + "BoolBox" => { + // Get first argument as bool, or false + let value = if let Some(arg) = arg_values.first() { + arg.as_bool().unwrap_or(false) + } else { + false + }; + VMValue::Bool(value) }, "ArrayBox" => { - // Create empty ArrayBox - in real implementation would use args + // Create empty ArrayBox let array_box = Box::new(crate::boxes::array::ArrayBox::new()); VMValue::from_nyash_box(array_box) }, - "IntegerBox" => { - // Create IntegerBox with default value - let int_box = Box::new(IntegerBox::new(0)); - VMValue::from_nyash_box(int_box) - }, - "BoolBox" => { - // Create BoolBox with default value - let bool_box = Box::new(BoolBox::new(false)); - VMValue::from_nyash_box(bool_box) - }, _ => { - // For unknown types, create a placeholder string - VMValue::String(format!("NewBox[{}]", box_type)) + // For unknown types, create a placeholder + // TODO: Implement proper user-defined Box creation after refactoring + VMValue::String(format!("{}[placeholder]", box_type)) } }; @@ -722,6 +815,13 @@ impl VM { } } + /// Phase 9.78a: Unified method dispatch for all Box types + fn call_unified_method(&self, box_value: Box, method: &str, args: Vec>) -> Result, VMError> { + // For now, we use the simplified method dispatch + // In a full implementation, this would check for InstanceBox and dispatch appropriately + self.call_box_method(box_value, method, args) + } + /// Call a method on a Box - simplified version of interpreter method dispatch fn call_box_method(&self, box_value: Box, method: &str, _args: Vec>) -> Result, VMError> { // For now, implement basic methods for common box types diff --git a/src/lib.rs b/src/lib.rs index 060d0f22..e10cb87e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,6 +11,7 @@ use wasm_bindgen::prelude::*; pub mod box_trait; pub mod boxes; pub mod box_factory; // 🏭 Unified Box Factory Architecture (Phase 9.78) +pub mod scope_tracker; // 🎯 Phase 9.78a: Box lifecycle tracking for VM pub mod stdlib; pub mod environment; pub mod tokenizer; diff --git a/src/mir/builder.rs b/src/mir/builder.rs index 1f89ff82..72f3d582 100644 --- a/src/mir/builder.rs +++ b/src/mir/builder.rs @@ -670,75 +670,24 @@ impl MirBuilder { /// Build new expression: new ClassName(arguments) fn build_new_expression(&mut self, class: String, arguments: Vec) -> Result { - // Special handling for built-in Box types that have single literal arguments - match class.as_str() { - "IntegerBox" => { - if arguments.len() == 1 { - if let ASTNode::Literal { value: LiteralValue::Integer(n), .. } = &arguments[0] { - // For built-in boxes, just return the value directly - // The VM/interpreter will handle boxing when needed - let dst = self.value_gen.next(); - self.emit_instruction(MirInstruction::Const { - dst, - value: ConstValue::Integer(*n), - })?; - return Ok(dst); - } - } - } - "StringBox" => { - if arguments.len() == 1 { - if let ASTNode::Literal { value: LiteralValue::String(s), .. } = &arguments[0] { - let dst = self.value_gen.next(); - self.emit_instruction(MirInstruction::Const { - dst, - value: ConstValue::String(s.clone()), - })?; - return Ok(dst); - } - } - } - "FloatBox" => { - if arguments.len() == 1 { - if let ASTNode::Literal { value: LiteralValue::Float(f), .. } = &arguments[0] { - let dst = self.value_gen.next(); - self.emit_instruction(MirInstruction::Const { - dst, - value: ConstValue::Float(*f), - })?; - return Ok(dst); - } - } - } - "BoolBox" => { - if arguments.len() == 1 { - if let ASTNode::Literal { value: LiteralValue::Bool(b), .. } = &arguments[0] { - let dst = self.value_gen.next(); - self.emit_instruction(MirInstruction::Const { - dst, - value: ConstValue::Bool(*b), - })?; - return Ok(dst); - } - } - } - _ => {} + // Phase 9.78a: Unified Box creation using NewBox instruction + + // First, evaluate all arguments to get their ValueIds + let mut arg_values = Vec::new(); + for arg in arguments { + let arg_value = self.build_expression(arg)?; + arg_values.push(arg_value); } - // For other classes, use the original implementation + // Generate the destination ValueId let dst = self.value_gen.next(); - // For now, create a "box type" value representing the class - let type_value = self.value_gen.next(); - self.emit_instruction(MirInstruction::Const { - dst: type_value, - value: ConstValue::String(class), - })?; - - // Create the reference using RefNew - self.emit_instruction(MirInstruction::RefNew { + // Emit NewBox instruction for all Box types + // VM will handle optimization for basic types internally + self.emit_instruction(MirInstruction::NewBox { dst, - box_val: type_value, + box_type: class, + args: arg_values, })?; Ok(dst) diff --git a/src/scope_tracker.rs b/src/scope_tracker.rs new file mode 100644 index 00000000..e962f4eb --- /dev/null +++ b/src/scope_tracker.rs @@ -0,0 +1,73 @@ +/*! + * ScopeTracker - Track Box instances for proper lifecycle management + * + * Phase 9.78a: Unified Box lifecycle management for VM + */ + +use std::sync::Arc; +use crate::box_trait::NyashBox; + +/// Tracks Box instances created in different scopes for proper fini calls +pub struct ScopeTracker { + /// Stack of scopes, each containing Boxes created in that scope + scopes: Vec>>, +} + +impl ScopeTracker { + /// Create a new scope tracker + pub fn new() -> Self { + Self { + scopes: vec![Vec::new()], // Start with one root scope + } + } + + /// Enter a new scope + pub fn push_scope(&mut self) { + self.scopes.push(Vec::new()); + } + + /// Exit current scope and call fini on all Boxes created in it + pub fn pop_scope(&mut self) { + if let Some(scope) = self.scopes.pop() { + // Call fini in reverse order of creation + for arc_box in scope.into_iter().rev() { + // For now, fini handling is simplified + // In a full implementation, we would check if the Box has a fini method + // and call it appropriately + // TODO: Implement proper fini dispatch + let _ = arc_box; // Suppress unused warning + } + } + + // Ensure we always have at least one scope + if self.scopes.is_empty() { + self.scopes.push(Vec::new()); + } + } + + /// Register a Box in the current scope + pub fn register_box(&mut self, nyash_box: Arc) { + if let Some(current_scope) = self.scopes.last_mut() { + current_scope.push(nyash_box); + } + } + + /// Clear all scopes (used when resetting VM state) + pub fn clear(&mut self) { + // Pop all scopes and call fini + while self.scopes.len() > 1 { + self.pop_scope(); + } + + // Clear the root scope + if let Some(root_scope) = self.scopes.first_mut() { + root_scope.clear(); + } + } +} + +impl Default for ScopeTracker { + fn default() -> Self { + Self::new() + } +} \ No newline at end of file