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:
285
docs/reference/execution-backend/mir-26-specification.md
Normal file
285
docs/reference/execution-backend/mir-26-specification.md
Normal file
@ -0,0 +1,285 @@
|
||||
# MIR 26-Instruction Specification
|
||||
|
||||
*Nyash Machine Intermediate Representation - ChatGPT5 Compliant Version*
|
||||
|
||||
## Overview
|
||||
|
||||
This document specifies the official 26-instruction set for Nyash MIR (Machine Intermediate Representation), following the ChatGPT5 specification and AI consensus from the grand meeting.
|
||||
|
||||
## Instruction Set (26 Instructions)
|
||||
|
||||
### Tier-0: Core Instructions (5)
|
||||
|
||||
1. **Const** - Load constant value
|
||||
```mir
|
||||
%dst = const <value>
|
||||
```
|
||||
Effect: pure
|
||||
|
||||
2. **BinOp** - Binary operations (includes arithmetic, logical, comparison)
|
||||
```mir
|
||||
%dst = binop <op> %lhs, %rhs
|
||||
```
|
||||
Effect: pure
|
||||
|
||||
3. **Compare** - Comparison operations
|
||||
```mir
|
||||
%dst = icmp <op> %lhs, %rhs
|
||||
```
|
||||
Effect: pure
|
||||
|
||||
4. **Phi** - SSA phi node
|
||||
```mir
|
||||
%dst = phi [%bb1: %val1], [%bb2: %val2], ...
|
||||
```
|
||||
Effect: pure
|
||||
|
||||
5. **Call** - Function and intrinsic calls
|
||||
```mir
|
||||
%dst = call <func>(%arg1, %arg2, ...)
|
||||
call <func>(%arg1, %arg2, ...)
|
||||
```
|
||||
Effect: context-dependent
|
||||
|
||||
### Tier-0: Control Flow (3)
|
||||
|
||||
6. **Branch** - Conditional branch
|
||||
```mir
|
||||
br %cond, label %then, label %else
|
||||
```
|
||||
Effect: control
|
||||
|
||||
7. **Jump** - Unconditional jump
|
||||
```mir
|
||||
br label %target
|
||||
```
|
||||
Effect: control
|
||||
|
||||
8. **Return** - Return from function
|
||||
```mir
|
||||
ret %value
|
||||
ret void
|
||||
```
|
||||
Effect: control
|
||||
|
||||
### Tier-1: Box Operations (5)
|
||||
|
||||
9. **NewBox** - Create new Box instance
|
||||
```mir
|
||||
%dst = new <BoxType>(%arg1, %arg2, ...)
|
||||
```
|
||||
Effect: mut
|
||||
|
||||
10. **BoxFieldLoad** - Load field from Box
|
||||
```mir
|
||||
%dst = %box.field
|
||||
```
|
||||
Effect: pure
|
||||
|
||||
11. **BoxFieldStore** - Store field to Box
|
||||
```mir
|
||||
%box.field = %value
|
||||
```
|
||||
Effect: mut
|
||||
|
||||
12. **BoxCall** - Call Box method
|
||||
```mir
|
||||
%dst = call %box.method(%arg1, %arg2, ...)
|
||||
```
|
||||
Effect: context-dependent
|
||||
|
||||
13. **ExternCall** - Call external function
|
||||
```mir
|
||||
%dst = extern_call "interface.method"(%arg1, %arg2, ...)
|
||||
```
|
||||
Effect: context-dependent
|
||||
|
||||
### Tier-1: Reference Operations (6)
|
||||
|
||||
14. **RefGet** - Get reference target
|
||||
```mir
|
||||
%dst = ref_get %reference
|
||||
```
|
||||
Effect: pure
|
||||
|
||||
15. **RefSet** - Set reference target
|
||||
```mir
|
||||
ref_set %reference -> %new_target
|
||||
```
|
||||
Effect: mut
|
||||
|
||||
16. **WeakNew** - Create weak reference
|
||||
```mir
|
||||
%dst = weak_new %box
|
||||
```
|
||||
Effect: pure
|
||||
|
||||
17. **WeakLoad** - Load from weak reference
|
||||
```mir
|
||||
%dst = weak_load %weak_ref
|
||||
```
|
||||
Effect: pure
|
||||
|
||||
18. **WeakCheck** - Check if weak reference is alive
|
||||
```mir
|
||||
%dst = weak_check %weak_ref
|
||||
```
|
||||
Effect: pure
|
||||
|
||||
19. **Safepoint** - GC safepoint
|
||||
```mir
|
||||
safepoint
|
||||
```
|
||||
Effect: io
|
||||
|
||||
### Tier-2: Advanced Operations (7)
|
||||
|
||||
20. **Send** - Send message via Bus
|
||||
```mir
|
||||
send %data -> %target
|
||||
```
|
||||
Effect: io
|
||||
|
||||
21. **Recv** - Receive message from Bus
|
||||
```mir
|
||||
%dst = recv %source
|
||||
```
|
||||
Effect: io
|
||||
|
||||
22. **TailCall** - Tail call optimization
|
||||
```mir
|
||||
tail_call %func(%arg1, %arg2, ...)
|
||||
```
|
||||
Effect: control
|
||||
|
||||
23. **Adopt** - Adopt ownership
|
||||
```mir
|
||||
adopt %parent <- %child
|
||||
```
|
||||
Effect: mut
|
||||
|
||||
24. **Release** - Release ownership
|
||||
```mir
|
||||
release %reference
|
||||
```
|
||||
Effect: mut
|
||||
|
||||
25. **MemCopy** - Optimized memory copy
|
||||
```mir
|
||||
memcpy %dst <- %src, %size
|
||||
```
|
||||
Effect: mut
|
||||
|
||||
26. **AtomicFence** - Memory barrier
|
||||
```mir
|
||||
atomic_fence <ordering>
|
||||
```
|
||||
Effect: io
|
||||
|
||||
## Deprecated Instructions (17)
|
||||
|
||||
The following instructions have been removed from the specification:
|
||||
|
||||
1. **UnaryOp** → Use `BinOp` (e.g., `not %x` → `%x xor true`)
|
||||
2. **Load** → Use `BoxFieldLoad`
|
||||
3. **Store** → Use `BoxFieldStore`
|
||||
4. **ArrayGet** → Use `BoxFieldLoad` or `Call @array_get`
|
||||
5. **ArraySet** → Use `BoxFieldStore` or `Call @array_set`
|
||||
6. **Print** → Use `Call @print`
|
||||
7. **Debug** → Use `Call @debug`
|
||||
8. **TypeCheck** → Use `Call @type_check`
|
||||
9. **Cast** → Use `Call @cast`
|
||||
10. **Throw** → Use `Call @throw`
|
||||
11. **Catch** → Use `Call @catch`
|
||||
12. **Copy** → Optimization pass only
|
||||
13. **Nop** → Not needed
|
||||
14. **RefNew** → References handled implicitly
|
||||
15. **BarrierRead** → Use `AtomicFence`
|
||||
16. **BarrierWrite** → Use `AtomicFence`
|
||||
17. **FutureNew/FutureSet/Await** → Use `NewBox` + `BoxCall`
|
||||
|
||||
## Intrinsic Functions
|
||||
|
||||
Standard intrinsic functions available via `Call` instruction:
|
||||
|
||||
- `@print(value)` - Print value to console
|
||||
- `@debug(value, message)` - Debug output
|
||||
- `@type_check(value, type)` - Runtime type check
|
||||
- `@cast(value, type)` - Type cast
|
||||
- `@throw(exception)` - Throw exception
|
||||
- `@catch(type, handler)` - Set exception handler
|
||||
- `@array_get(array, index)` - Array element access
|
||||
- `@array_set(array, index, value)` - Array element update
|
||||
- `@unary_neg(value)` - Unary negation
|
||||
- `@unary_not(value)` - Logical not
|
||||
|
||||
## Effect System
|
||||
|
||||
Each instruction has an associated effect mask:
|
||||
|
||||
- **pure** - No side effects, can be reordered/eliminated
|
||||
- **mut** - Mutates memory, order-dependent
|
||||
- **io** - I/O operations, cannot be eliminated
|
||||
- **control** - Control flow, affects program execution path
|
||||
|
||||
## Migration Guide
|
||||
|
||||
### UnaryOp Migration
|
||||
```mir
|
||||
// Before
|
||||
%dst = neg %x
|
||||
%dst = not %x
|
||||
|
||||
// After
|
||||
%dst = binop sub 0, %x
|
||||
%dst = binop xor %x, true
|
||||
```
|
||||
|
||||
### Load/Store Migration
|
||||
```mir
|
||||
// Before
|
||||
%value = load %ptr
|
||||
store %value -> %ptr
|
||||
|
||||
// After
|
||||
%value = %box.field
|
||||
%box.field = %value
|
||||
```
|
||||
|
||||
### Print Migration
|
||||
```mir
|
||||
// Before
|
||||
print %value
|
||||
|
||||
// After
|
||||
call @print(%value)
|
||||
```
|
||||
|
||||
### Future Operations Migration
|
||||
```mir
|
||||
// Before
|
||||
%future = future_new %value
|
||||
future_set %future = %result
|
||||
%result = await %future
|
||||
|
||||
// After
|
||||
%future = new FutureBox(%value)
|
||||
call %future.set(%result)
|
||||
%result = call %future.await()
|
||||
```
|
||||
|
||||
## Implementation Status
|
||||
|
||||
- ✅ Phase 1: New instruction definitions
|
||||
- ✅ Phase 2: Frontend migration (AST→MIR generation)
|
||||
- ✅ Phase 3: Optimization pass migration
|
||||
- ✅ Phase 4: Backend implementation (VM/WASM)
|
||||
- ✅ Phase 5-1: Deprecated instruction marking
|
||||
- ✅ Phase 5-2: Backend rejection of deprecated instructions
|
||||
- ✅ Phase 5-3: Frontend stops generating deprecated instructions
|
||||
- 🔄 Phase 5-4: Test and documentation updates (in progress)
|
||||
- 📋 Phase 5-5: Final verification and cleanup
|
||||
|
||||
---
|
||||
|
||||
*Last updated: 2025-08-17*
|
||||
254
docs/reference/execution-backend/p2p_spec.md
Normal file
254
docs/reference/execution-backend/p2p_spec.md
Normal file
@ -0,0 +1,254 @@
|
||||
# 🌐 P2PBox完全実装 - AI大会議仕様準拠
|
||||
|
||||
## 📋 Issue概要
|
||||
|
||||
**目標**: NyaMeshP2Pライブラリ実現のためのP2P通信システムを、AI大会議で決定した最新仕様に従って完全実装する
|
||||
|
||||
**重要**: 既存の `src/boxes/intent_box.rs` と `src/boxes/p2p_box.rs` は**古い設計**のため、**完全に作り直し**が必要
|
||||
|
||||
## 🎯 AI大会議決定事項
|
||||
|
||||
### ✅ 採用仕様
|
||||
- **構造化IntentBox**: `name` + `payload` 形式のメッセージBox
|
||||
- **個別送信のみ**: `send(to, message)` 固定API
|
||||
- **明示的デリゲーション**: `from Parent.method()` 統一構文
|
||||
|
||||
### ❌ 除外仕様
|
||||
- **ブロードキャスト**: 安全性のため完全除外(無限ループリスク回避)
|
||||
- **関数オーバーロード**: `send(a)` vs `send(a,b)` 分岐不採用
|
||||
|
||||
## 🏗️ 新アーキテクチャ設計
|
||||
|
||||
```
|
||||
┌─────────────┐ ┌──────────────┐ ┌─────────────┐
|
||||
│ P2PBox │◄──►│ MessageBus │◄──►│ Transport │
|
||||
│ (ユーザーAPI) │ │ (ローカル配送) │ │ (送受信層) │
|
||||
└─────────────┘ └──────────────┘ └─────────────┘
|
||||
▲ ▲ ▲
|
||||
│ │ │
|
||||
┌─────────────┐ ┌──────────────┐ ┌─────────────┐
|
||||
│ IntentBox │ │ ハンドラ管理 │ │ InProcess │
|
||||
│ (構造化MSG) │ │ ノード登録 │ │ WebSocket │
|
||||
└─────────────┘ └──────────────┘ │ WebRTC │
|
||||
└─────────────┘
|
||||
```
|
||||
|
||||
## 📦 段階的実装計画
|
||||
|
||||
### 🎯 **Phase 1: 基盤実装**
|
||||
|
||||
#### **Step 1: IntentBox(構造化メッセージ)**
|
||||
**ファイル**: `src/boxes/intent_box.rs` (完全作り直し)
|
||||
|
||||
```rust
|
||||
// 新しいIntentBox設計
|
||||
pub struct IntentBoxData {
|
||||
pub name: String, // "chat.message", "file.share"等
|
||||
pub payload: serde_json::Value, // 任意のJSON data
|
||||
}
|
||||
pub type IntentBox = Arc<Mutex<IntentBoxData>>;
|
||||
```
|
||||
|
||||
**実装要件**:
|
||||
- Arc<Mutex>統一パターン準拠
|
||||
- BoxCore + NyashBox実装
|
||||
- serde_json::Value使用
|
||||
|
||||
**テストコード**:
|
||||
```nyash
|
||||
// tests/phase2/intent_box_test.nyash
|
||||
local msg = new IntentBox("chat.message", { text: "Hello P2P!" })
|
||||
local console = new ConsoleBox()
|
||||
console.log("Name: " + msg.name) // "chat.message"
|
||||
console.log("Text: " + msg.payload.text) // "Hello P2P!"
|
||||
```
|
||||
|
||||
#### **Step 2: MessageBus(プロセス内シングルトン)**
|
||||
**ファイル**: `src/messaging/message_bus.rs` (新規作成)
|
||||
|
||||
```rust
|
||||
pub struct MessageBusData {
|
||||
nodes: HashMap<String, BusEndpoint>, // ノード登録
|
||||
subscribers: HashMap<String, Vec<IntentHandler>>, // ハンドラー管理
|
||||
}
|
||||
pub type MessageBus = Arc<Mutex<MessageBusData>>;
|
||||
|
||||
impl MessageBusData {
|
||||
pub fn global() -> MessageBus // シングルトンアクセス
|
||||
pub fn register_node(&mut self, id: String, endpoint: BusEndpoint)
|
||||
pub fn route(&self, to: &str, intent: IntentBox) -> Result<(), SendError>
|
||||
}
|
||||
```
|
||||
|
||||
#### **Step 3: Transport trait(送受信抽象化)**
|
||||
**ファイル**: `src/transport/mod.rs` (新規作成)
|
||||
|
||||
```rust
|
||||
pub trait Transport: Send + Sync {
|
||||
fn node_id(&self) -> &str;
|
||||
fn send(&self, to: &str, intent: IntentBox, opts: SendOpts) -> Result<(), SendError>;
|
||||
fn on_receive(&mut self, callback: Box<dyn Fn(IntentEnvelope) + Send + Sync>);
|
||||
}
|
||||
```
|
||||
|
||||
### 🎯 **Phase 2: InProcess実装**
|
||||
|
||||
#### **Step 4: InProcessTransport**
|
||||
**ファイル**: `src/transport/inprocess.rs` (新規作成)
|
||||
|
||||
```rust
|
||||
pub struct InProcessTransport {
|
||||
node_id: String,
|
||||
bus: MessageBus, // MessageBus::global()を使用
|
||||
}
|
||||
|
||||
impl Transport for InProcessTransport {
|
||||
// Bus経由の高速ローカル配送実装
|
||||
}
|
||||
```
|
||||
|
||||
### 🎯 **Phase 3: P2PBox統合**
|
||||
|
||||
#### **Step 5: P2PBox基本実装**
|
||||
**ファイル**: `src/boxes/p2p_box.rs` (完全作り直し)
|
||||
|
||||
```rust
|
||||
pub struct P2PBoxData {
|
||||
node_id: String,
|
||||
transport: Arc<dyn Transport>,
|
||||
bus: MessageBus, // 全P2PBoxで共有
|
||||
}
|
||||
pub type P2PBox = Arc<Mutex<P2PBoxData>>;
|
||||
|
||||
impl P2PBoxData {
|
||||
pub fn new(node_id: String, kind: TransportKind) -> P2PBox
|
||||
pub fn on(&self, intent_name: &str, handler: IntentHandler) -> Result<(), P2PError>
|
||||
pub fn send(&self, to: &str, intent: IntentBox) -> Result<(), SendError>
|
||||
// ブロードキャストメソッドは実装しない
|
||||
}
|
||||
```
|
||||
|
||||
## 🧪 包括的テスト要件
|
||||
|
||||
### **基本動作テスト**
|
||||
**ファイル**: `test_p2p_basic_new.nyash`
|
||||
|
||||
```nyash
|
||||
// 2つのノード作成
|
||||
local node_a = new P2PBox("alice", transport: "inprocess")
|
||||
local node_b = new P2PBox("bob", transport: "inprocess")
|
||||
|
||||
// 受信ハンドラ設定
|
||||
node_b.on("chat.message", function(intent, from) {
|
||||
local console = new ConsoleBox()
|
||||
console.log("From " + from + ": " + intent.payload.text)
|
||||
})
|
||||
|
||||
// メッセージ送信
|
||||
local msg = new IntentBox("chat.message", { text: "Hello P2P!" })
|
||||
node_a.send("bob", msg) // → "From alice: Hello P2P!"
|
||||
```
|
||||
|
||||
### **エラーハンドリングテスト**
|
||||
```nyash
|
||||
// 存在しないノードへの送信
|
||||
local result = node_a.send("nonexistent", msg)
|
||||
// → SendError::NodeNotFound
|
||||
|
||||
// 不正なIntentBox
|
||||
local invalid_msg = "not an IntentBox"
|
||||
local result = node_a.send("bob", invalid_msg)
|
||||
// → 型エラー
|
||||
```
|
||||
|
||||
### **パフォーマンステスト**
|
||||
```nyash
|
||||
// 大量メッセージ送信テスト
|
||||
local start_time = new TimeBox()
|
||||
loop(i < 1000) {
|
||||
local msg = new IntentBox("test.performance", { id: i })
|
||||
node_a.send("bob", msg)
|
||||
i = i + 1
|
||||
}
|
||||
local end_time = new TimeBox()
|
||||
// 実行時間計測
|
||||
```
|
||||
|
||||
## 📁 必要なディレクトリ構成
|
||||
|
||||
```
|
||||
src/
|
||||
├── boxes/
|
||||
│ ├── intent_box.rs # 完全作り直し
|
||||
│ └── p2p_box.rs # 完全作り直し
|
||||
├── messaging/ # 新規作成
|
||||
│ └── message_bus.rs # MessageBus実装
|
||||
└── transport/ # 新規作成
|
||||
├── mod.rs # Transport trait
|
||||
└── inprocess.rs # InProcessTransport
|
||||
```
|
||||
|
||||
## 🔧 実装時の重要注意点
|
||||
|
||||
### **Arc<Mutex>統一パターン厳守**
|
||||
```rust
|
||||
// ✅ 正しい統一パターン
|
||||
pub type IntentBox = Arc<Mutex<IntentBoxData>>;
|
||||
pub type MessageBus = Arc<Mutex<MessageBusData>>;
|
||||
pub type P2PBox = Arc<Mutex<P2PBoxData>>;
|
||||
|
||||
// ❌ 避けるべき
|
||||
pub struct IntentBox { ... } // Arcなし
|
||||
```
|
||||
|
||||
### **BoxCore実装必須**
|
||||
```rust
|
||||
impl BoxCore for IntentBox {
|
||||
fn box_id(&self) -> u64 { self.lock().unwrap().base.id }
|
||||
fn parent_type_id(&self) -> Option<TypeId> { None }
|
||||
fn fmt_box(&self, f: &mut fmt::Formatter) -> fmt::Result { ... }
|
||||
fn as_any(&self) -> &dyn Any { self }
|
||||
fn as_any_mut(&mut self) -> &mut dyn Any { self }
|
||||
}
|
||||
```
|
||||
|
||||
### **エラーハンドリング設計**
|
||||
```rust
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum SendError {
|
||||
NodeNotFound(String), // 宛先ノードが見つからない
|
||||
NetworkError(String), // ネットワークエラー
|
||||
SerializationError(String), // JSON変換エラー
|
||||
BusError(String), // MessageBusエラー
|
||||
}
|
||||
```
|
||||
|
||||
## 🎯 成功の定義
|
||||
|
||||
以下のテストが全て通過すること:
|
||||
|
||||
1. **基本通信**: ノード間でIntentBoxメッセージ送受信
|
||||
2. **ハンドラ登録**: `on()` でイベントリスナー正常動作
|
||||
3. **エラーハンドリング**: 不正な送信先・データで適切エラー
|
||||
4. **パフォーマンス**: 1000メッセージ/秒以上の送信性能
|
||||
5. **メモリ安全性**: valgrind等でメモリリーク検出なし
|
||||
|
||||
## 📚 参考ドキュメント
|
||||
|
||||
- **[P2P_GUIDE.md](docs/P2P_GUIDE.md)** - 設計詳細・使用例
|
||||
- **[CURRENT_TASK.md](CURRENT_TASK.md)** - 実装状況・優先順位
|
||||
- **[ai_conference_overload_decision.md](ai_conference_overload_decision.md)** - AI大会議決定事項
|
||||
- **[docs/reference/override-delegation-syntax.md](docs/reference/override-delegation-syntax.md)** - デリゲーション構文仕様
|
||||
|
||||
## 🚀 実装開始
|
||||
|
||||
**Priority**: High
|
||||
**Assignee**: Copilot
|
||||
**Labels**: enhancement, p2p, breaking-change
|
||||
**Milestone**: P2P Phase 2 Complete
|
||||
|
||||
**最初に取り組むべき**: Step 1 IntentBox の完全作り直し
|
||||
|
||||
---
|
||||
|
||||
🎉 **この実装により、Nyashは本格的なP2P通信システムを持つ現代的プログラミング言語になります!**
|
||||
Reference in New Issue
Block a user