feat(plugin): Fix plugin BoxRef return and Box argument support

- Fixed deadlock in FileBox plugin copyFrom implementation (single lock)
- Added TLV Handle (tag=8) parsing in calls.rs for returned BoxRefs
- Improved plugin loader with config path consistency and detailed logging
- Fixed loader routing for proper Handle type_id/fini_method_id resolution
- Added detailed logging for TLV encoding/decoding in plugin_loader_v2

Test docs/examples/plugin_boxref_return.nyash now works correctly:
- cloneSelf() returns FileBox Handle properly
- copyFrom(Box) accepts plugin Box arguments
- Both FileBox instances close and fini correctly

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

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Moe Charm
2025-08-21 00:41:26 +09:00
parent af32896574
commit cc2a820af7
274 changed files with 7244 additions and 4608 deletions

View File

@ -0,0 +1,53 @@
# 🎯 CURRENT TASK - 2025年8月20日
## 📊 現在の状況
### ✅ 完了したタスク
1. **ドキュメント再編成** - 完全完了!
- 283ファイル → 4大カテゴリに整理
- Phaseファイルも統合済み
- 説明書/予定フォルダ削除済み
2. **プラグインBox基本実装** (Phase 9.78c)
- FileBoxプラグイン実装済み
- インタープリター経由の呼び出し成功
- 基本的な引数/戻り値サポート追加ChatGPT5による
### 🚧 現在の課題
1. **Bashコマンドエラー問題**
- docs整理で現在のディレクトリが削除された影響
- セッション再起動が必要かも
2. **E2Eテスト状況**tests/e2e_plugin_filebox.rs
- インタープリターテスト: ✅ 成功FileBox.close()が"ok"を返す)
- デリゲーションテスト: ❓ 未実装の可能性
- VMテスト: ❌ 失敗VMはまだプラグインBox未対応
### 🎯 次のタスク (Phase 9.78b)
#### Step 3: BoxFactory dyn化優先度: 高)
- 現在: `HashMap<String, Box<dyn Fn() -> Arc<dyn NyashBox>>>`
- 目標: `HashMap<String, Arc<dyn BoxFactory>>`
- 利点: プラグインBoxもVMで統一処理可能
#### Step 4: グローバル排除
- `get_global_registry()``runtime.registry`
- `get_global_loader_v2()``runtime.plugin_loader`
#### Step 5: SharedState分解
- 巨大なSharedState構造体を分割
- Box管理、メソッド管理、スコープ管理を分離
### 📝 メモ
- ChatGPT5がプラグインBoxメソッド呼び出しに引数/戻り値サポートを追加
- TLV (Type-Length-Value) エンコーディングで引数をプラグインに渡す実装
- Rustの借用チェッカーとの格闘の跡が見られる複数回の修正
### 🔧 推奨アクション
1. セッション再起動してBashコマンドを復活
2. ビルド実行: `cargo build --release -j32`
3. E2Eテスト実行: `cargo test e2e_plugin_filebox --features plugins -- --show-output`
4. VMプラグイン統合の実装開始Phase 9.78b Step 3
---
最終更新: 2025年8月20日 22:45

View File

@ -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<BoxFactory>, // ❌ エラーtraitには dyn 必要
plugin_loader: Option<Arc<PluginLoaderV2>>,
scope_tracker: ScopeTracker,
box_declarations: Arc<RwLock<HashMap<String, BoxDeclaration>>>,
```
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置いておく**を推奨します。現在の実装は方向性として正しく、インタープリター整理後に続きから再開するのが最も効率的です。

View File

@ -0,0 +1,82 @@
# Phase 9.78e: Dynamic Method Dispatch Implementation Summary
## 🎯 Overview
Phase 9.78e aimed to implement dynamic method dispatch through the `call_method` trait method to unify method calling across all Box types.
## ✅ Completed Tasks
### 1. **NyashBox Trait Enhancement**
- Added `call_method` to the NyashBox trait in `src/box_trait.rs`
- Default implementation returns `MethodNotFound` error
- Signature: `fn call_method(&mut self, method_name: &str, args: Vec<NyashValue>) -> Result<NyashValue, RuntimeError>`
### 2. **StringBox Implementation**
- Implemented `call_method` in `src/boxes/string_box.rs`
- Supports all StringBox methods:
- `type_name()`, `equals()`, `length()`
- `concat()`, `split()`, `toUpperCase()`, `toLowerCase()`
- `trim()`, `indexOf()`, `replace()`, `charAt()`, `substring()`
- Includes argument validation and proper error handling
### 3. **InstanceBox Implementation**
- Implemented `call_method` in `src/instance_v2.rs` with delegation pattern:
1. First checks user-defined methods
2. Delegates to inner box for builtin methods
3. Handles InstanceBox-specific methods (`getField`, `setField`, `hasMethod`)
- Enables transparent method calls on wrapped builtin boxes
### 4. **Error Type Updates**
- Added new RuntimeError variants:
- `MethodNotFound { method_name: String, type_name: String }`
- `FieldNotFound { field_name: String, class_name: String }`
### 5. **Interpreter Integration (Partial)**
- Added call_method integration in `src/interpreter/expressions/calls.rs`
- Implemented type conversion logic for Box<dyn NyashBox> to NyashValue
- Added debug output for tracking method dispatch flow
## 🚧 Challenges Encountered
### 1. **Type Conversion Complexity**
- Converting between `Box<dyn NyashBox>`, `Arc<Mutex<dyn NyashBox>>`, and `NyashValue`
- Current workaround: Direct type-based conversion for basic types
### 2. **Binary Compilation Issues**
- Several unrelated compilation errors in the binary prevent full testing
- Library builds successfully with call_method implementation
### 3. **Architecture Considerations**
- The current Box/NyashValue dual system creates friction
- Future consideration: Unified value representation system
## 📋 Test Results
- Basic StringBox creation and string operations work correctly
- Method calls currently fall back to legacy dispatch system
- Call_method infrastructure is in place but needs full integration
## 🔮 Next Steps
### Immediate Tasks:
1. Fix binary compilation errors to enable full testing
2. Complete NyashValue/Box type conversion helpers
3. Implement call_method for remaining builtin Box types
### Long-term Improvements:
1. Consider unified value representation to simplify type conversions
2. Optimize method dispatch performance
3. Add comprehensive test coverage for all Box types
## 💡 Key Insights
- The delegation pattern in InstanceBox successfully enables method calls on wrapped boxes
- Dynamic dispatch through call_method provides a clean abstraction for method calling
- Type conversion between the Box trait system and NyashValue remains a key challenge
## 📝 Code Locations
- Trait definition: `src/box_trait.rs:124-130`
- StringBox impl: `src/boxes/string_box.rs:160-313`
- InstanceBox impl: `src/instance_v2.rs:197-263`
- Interpreter integration: `src/interpreter/expressions/calls.rs:230-288`
---
*Phase 9.78e establishes the foundation for unified method dispatch across all Nyash Box types, with the core infrastructure successfully implemented and ready for expanded integration.*