From 75d09a89a83937e4006ff840ff6c30917b082545 Mon Sep 17 00:00:00 2001 From: Moe Charm Date: Sun, 17 Aug 2025 17:31:46 +0900 Subject: [PATCH] feat(phase-9.75g-0): Start BID-FFI type-first implementation strategy - Create comprehensive type definitions for all future features - Adopt FFI ABI v0 compliance with platform-aware pointers (usize) - Implement 8-byte alignment for cross-platform compatibility - Design single entry point: nyash_plugin_invoke - Target Linux x86-64 for initial implementation - Use unimplemented!() for gradual feature addition Key decisions from AI review: - Pointer width: platform-dependent (not fixed 32-bit) - Early addition of Option/Result types - Clear ownership rules for strings/arrays - Extensible BoxHeader with magic number Phase 9.75g-0: Build it simple, make it work, then extend! --- docs/CURRENT_TASK.md | 948 ++---------------- ...d_ffi_integration_discussion_2025-08-17.md | 92 ++ .../issues/bid_ai_meeting_2025-08-17.md | 137 +++ .../bid_ffi_ai_final_review_2025-08-17.md | 147 +++ ...phase_9_75g_0_revised_type_first_approach.md | 278 +++++ ...9_75g_0_simplified_bid_ffi_implementation.md | 176 ++++ .../issues/phase_9_75g_bid_ffi_abi_alignment.md | 352 +++++++ .../phase_9_75g_bid_integration_architecture.md | 590 +++++++++++ dump.txt | 13 + local_tests/bid_design_consultation.txt | 73 ++ local_tests/bid_ffi_final_review.txt | 80 ++ local_tests/mir_output.txt | 15 + local_tests/trace_mir_gen.nyash | 6 + 13 files changed, 2039 insertions(+), 868 deletions(-) create mode 100644 docs/archive/bid_ffi_integration_discussion_2025-08-17.md create mode 100644 docs/予定/native-plan/issues/bid_ai_meeting_2025-08-17.md create mode 100644 docs/予定/native-plan/issues/bid_ffi_ai_final_review_2025-08-17.md create mode 100644 docs/予定/native-plan/issues/phase_9_75g_0_revised_type_first_approach.md create mode 100644 docs/予定/native-plan/issues/phase_9_75g_0_simplified_bid_ffi_implementation.md create mode 100644 docs/予定/native-plan/issues/phase_9_75g_bid_ffi_abi_alignment.md create mode 100644 docs/予定/native-plan/issues/phase_9_75g_bid_integration_architecture.md create mode 100644 dump.txt create mode 100644 local_tests/bid_design_consultation.txt create mode 100644 local_tests/bid_ffi_final_review.txt create mode 100644 local_tests/mir_output.txt create mode 100644 local_tests/trace_mir_gen.nyash diff --git a/docs/CURRENT_TASK.md b/docs/CURRENT_TASK.md index 560e1657..87f71de5 100644 --- a/docs/CURRENT_TASK.md +++ b/docs/CURRENT_TASK.md @@ -1,874 +1,86 @@ -# 🎯 現在のタスク (2025-08-17 MIR 35→26命令削減プロジェクト 完了!🎉) +# 🎯 現在のタスク (2025-08-17) -## 🎉 **完了: MIR 35→26命令削減プロジェクト** +## 🚀 **現在進行中: Phase 9.75g-0 型定義ファースト BID-FFI実装** -### 📊 **驚異的達成** -- **削減前**: 35命令実装(175%膨張) -- **削減後**: 26命令(ChatGPT5仕様完全準拠)✅ -- **予定期間**: 5週間 -- **実際の期間**: **1日(24時間)で完了!** 🚀 -- **達成率**: 100%(RefNew表示問題を除く) +**目的**: FFI ABI v0準拠のシンプルで動くプラグインシステム構築 +**戦略**: 型定義は全部最初に、実装は段階的に(unimplemented!活用) +**期間**: 1週間(2025-08-17〜2025-08-24) +**詳細**: +- [phase_9_75g_0_revised_type_first_approach.md](../予定/native-plan/issues/phase_9_75g_0_revised_type_first_approach.md) +- [bid_ffi_ai_final_review_2025-08-17.md](../予定/native-plan/issues/bid_ffi_ai_final_review_2025-08-17.md) -### 🎯 **Phase 1実装目標** -```rust -// 新命令実装 (10個) -BoxFieldLoad { dst: ValueId, box_val: ValueId, field: String } -BoxFieldStore { box_val: ValueId, field: String, value: ValueId } -WeakCheck { dst: ValueId, weak_ref: ValueId } -Send { data: ValueId, target: ValueId } -Recv { dst: ValueId, source: ValueId } -TailCall, Adopt, Release, MemCopy, AtomicFence +### 🎯 今週の実装計画 +- **Day 1**: 全型定義(BidType, Transport, Effect, Error) +- **Day 2**: プラグインローダー(dlopen/dlsym) +- **Day 3**: 文字列処理(UTF-8, 所有権) +- **Day 4**: FileBox最小実装 +- **Day 5**: エラー処理とOption/Result +- **Day 6-7**: ドキュメント・CI・仕上げ + +### 🔑 技術的決定事項 +- ポインタ: `usize`(プラットフォーム依存) +- アライメント: 8バイト境界 +- 単一エントリーポイント: `nyash_plugin_invoke` +- ターゲット: Linux x86-64限定 + +## ✅ **完了済み主要成果** + +### **MIR 35→26命令削減** (2025-08-17) +- 実装期間: 1日(予定5週間の5%) +- 成果: 26命令体系確立、全バックエンド対応 +- 詳細: [mir-26-specification.md](../説明書/reference/mir-26-specification.md) + +### **Phase 9.75 RwLock変換** (完了) +- Arc → Arc全Box型変換 +- 性能改善達成 + +### **Phase 9.75e using nyashstd** (完了) +- 標準ライブラリ統合 +- リテラル自動変換実装 + +### **Phase 9.75j 警告削減** (完了) +- 106個→0個(100%削減) + +## 🔮 **次期優先タスク** + +1. **Phase 8.6: VM性能改善**(緊急) + - 問題: VMがインタープリターより0.9倍遅い + - 目標: 2倍以上高速化 + - 詳細: [phase_8_6_vm_performance_improvement.md](../予定/native-plan/issues/phase_8_6_vm_performance_improvement.md) + +2. **Phase 9: JIT実装** + - VM改善後の次ステップ + +3. **Phase 10: LLVM Direct AOT** + - 目標: 100-1000倍高速化 + - 期間: 4-6ヶ月 + +## 📊 **プロジェクト統計** + +- **実行モード**: インタープリター/VM/WASM/AOT(開発中) +- **Box型数**: 16種類(すべてRwLock統一) +- **MIR命令数**: 26(最適化済み) +- **ビルド時間**: 2分以上(改善中) + +## 🔧 **開発ガイドライン** + +### クイックリファレンス +- [CLAUDE.md](../CLAUDE.md) - 開発者向けガイド +- [copilot_issues.txt](../予定/native-plan/copilot_issues.txt) - Phase順開発計画 +- [syntax-cheatsheet.md](../quick-reference/syntax-cheatsheet.md) - 構文早見表 + +### テスト実行 +```bash +# リリースビルド(推奨) +cargo build --release -j32 + +# 実行 +./target/release/nyash program.nyash + +# ベンチマーク +./target/release/nyash --benchmark --iterations 100 ``` -### ✅ **Phase 1完了: 10新命令実装成功!** - -### ✅ **Phase 2完了: フロントエンド移行 100%達成!** (2025-08-17) - -#### **実装完了項目** -- **✅ UnaryOp → Call @unary_op**: 単項演算子をintrinsic呼び出しに変換完了 -- **✅ Print → Call @print**: print文をintrinsic呼び出しに変換完了 -- **✅ FutureNew → NewBox**: Future生成をNewBox実装に変換完了 -- **✅ Await → BoxCall**: await式をBoxCall実装に変換完了 -- **✅ Throw/Catch → Call intrinsic**: 例外処理をCall基盤に変換完了 -- **✅ VM intrinsicサポート**: VM backend で intrinsic 関数実行機能追加完了 -- **✅ ビルド成功**: エラー0個・warnings 8個のみ(関連性なし) - -#### **変換された命令** -```rust -// 変換前(旧MIR) -UnaryOp { dst, op: Neg, operand } -Print { value } -FutureNew { dst, value } -Await { dst, future } -Throw { exception } -Catch { exception_type, exception_value, handler_bb } - -// 変換後(新MIR) -Call { dst, func: "@unary_neg", args: [operand] } -Call { dst: None, func: "@print", args: [value] } -NewBox { dst, box_type: "FutureBox", args: [value] } -BoxCall { dst, box_val: future, method: "await", args: [] } -Call { dst: None, func: "@throw", args: [exception] } -Call { dst, func: "@set_exception_handler", args: [type, handler] } -``` - -#### **Phase 2達成度: 100%完了** -**AST→MIR生成が新形式のみに完全移行!** -- **✅ 構造体定義**: instruction.rsに全10命令定義完了 -- **✅ エフェクト実装**: effects()メソッド対応完了 -- **✅ 値処理**: dst_value()・used_values()対応完了 -- **✅ 表示**: Display・MIRプリンター対応完了 -- **✅ VM仮実装**: todo!()で構文チェック完了 -- **✅ ビルド成功**: エラー0個・warnings 7個のみ - -### ✅ **AST→MIR Builder対応完了!** -- **✅ フィールドアクセス変換**: `RefGet` → `BoxFieldLoad`に変更完了 -- **✅ フィールド代入変換**: `RefSet` → `BoxFieldStore`に変更完了 -- **✅ ビルド成功**: エラー0個・warnings 7個のみ - -### ✅ **VM基本実装完了!** -- **✅ BoxFieldLoad/Store**: フィールドアクセス基本実装完了 -- **✅ WeakCheck**: weak参照生存確認実装完了 -- **✅ Send/Recv**: Bus通信基本実装完了 -- **✅ TailCall**: 末尾呼び出し最適化基本実装完了 -- **✅ Adopt/Release**: 所有権操作基本実装完了 -- **✅ MemCopy/AtomicFence**: メモリ操作基本実装完了 -- **✅ ビルド成功**: エラー0個・warnings 7個のみ - -### 🎉 **Phase 1完全実装成功!** -- **✅ WASMバックエンド対応**: 全10新命令のWASMコードジェン実装完了 -- **✅ BoxFieldLoad/Store**: WASMメモリアクセス実装完了 -- **✅ WeakCheck/Send/Recv**: WASM基本実装完了 -- **✅ TailCall/Adopt/Release**: WASM最適化基盤実装完了 -- **✅ MemCopy/AtomicFence**: WASMメモリ操作実装完了 -- **✅ ビルド成功**: エラー0個・warnings 7個のみ - -### 🎯 **Phase 1達成度: 100%完了** -**35→26命令削減プロジェクト Phase 1 完全成功!** - -## ✅ **Phase 3完了: 最適化パス移行** (2025-08-17) - -### ✅ **Phase 4完了: バックエンド対応** (2025-08-17) - -## 🚀 **現在進行中: Phase 5 旧命令削除・クリーンアップ** (2025-08-17) - -### ✅ **Phase 5-1完了: 削除対象17命令にdeprecatedマーク付与** -- 17個の削除対象命令に`#[deprecated]`アトリビュート追加 -- 移行ガイダンスメッセージ付与 - -### ✅ **Phase 5-2完了: バックエンドから削除対象命令の実装削除** -- VM: 全17命令を拒否、適切なエラーメッセージ -- WASM: 全17命令を拒否、移行ガイダンス付き - -### ✅ **Phase 5-3完了: フロントエンドから削除対象命令の生成停止** -- MIRビルダーでRefNewをNewBoxに置き換え -- 不要なConst生成削除 -- 引数処理の改善 - -### ✅ **Phase 5-4完了: テストとドキュメント更新** -- ✅ MIR 26命令仕様書作成: `docs/説明書/reference/mir-26-specification.md` -- ✅ CURRENT_TASK.md更新: Phase 5進捗反映 -- ✅ テストファイル更新: mir_phase7_async_ops.rs, mir_phase6_vm_ref_ops.rs修正 -- ✅ 不要テスト削除: wasm_poc2_box_operations.rsアーカイブ - -### ✅ **Phase 5-5完了: 最終検証とクリーンアップ** -- ✅ 全バックエンドでの26命令動作確認 -- ✅ ライブラリビルド成功(deprecated警告のみ) -- ✅ 基本プログラムの実行確認 -- ⚠️ RefNew表示問題を将来タスクとして記録 - -### 🎉 **プロジェクト完了統計** -- **削減命令数**: 9命令(25.7%削減) -- **実装期間**: 1日(予定の5%の期間) -- **成功率**: 95%(RefNew表示問題を除く) -- **コード品質**: 向上(統一アーキテクチャ達成) - -## 🚀 **Phase 9.75f: BID統合プラグインアーキテクチャ革命** (将来実装) - -### 🎯 **Phase 9.75f-BID: 汎用プラグインシステム実装** (優先度: 🔥最高) - -#### **🌟 革命的発見: FFI-ABI仕様との完全統合可能性** -**Gemini先生評価**: "極めて健全かつ先進的" - LLVM・WASM Component Modelレベルの設計 - -#### **現状の限界と解決策** -```rust -// ❌ 現在の問題: インタープリター専用 -trait PluginLoader: Send + Sync { - fn create_box(&self, box_type: &str, args: &[ASTNode]) -> Result, RuntimeError>; - // ^^^^^^^^ AST依存でVM/WASM/AOTで使用不可 -} - -// ✅ BID統合後: 全バックエンド対応 -trait BidPluginLoader: Send + Sync { - fn create_box(&self, box_type: &str, args: &[MirValue]) -> Result; - // ^^^^^^^^^ MirValue統一で全バックエンド対応! -} -``` - -#### **🎯 統一BIDアーキテクチャ設計** -```yaml -# nyash-math.bid.yaml - 1つの定義で全バックエンド対応! -version: 0 -interfaces: - - name: nyash.math - box: MathBox - methods: - - name: sqrt - params: [ {f64: value} ] - returns: f64 - effect: pure # 🔥 最適化可能! -``` - -```rust -// ストラテジーパターンによる統一実装 -trait BackendStrategy { - fn generate_extern_call(&mut self, call: &ExternCall) -> Result; -} - -struct InterpreterStrategy; // C ABI + dlsym -struct WasmStrategy; // (import ...) + call命令 -struct VmStrategy; // 関数ポインタ呼び出し -struct AotLlvmStrategy; // declare + call命令 -``` - -#### **🚀 Gemini推奨6段階実装ステップ** - -##### **Step 1: BIDパーサ+FFIレジストリ実装** (60分) -- `bid.yaml`パーサー実装 -- FFI関数シグネチャレジストリ生成 -- 型検証・エラーハンドリング基盤 - -##### **Step 2: インタープリターブリッジ対応** (45分) -- `MirInstruction::ExternCall`解釈ロジック追加 -- 既存ローダーとの共存実装 -- `console.log`等の基本関数で動作確認 - -##### **Step 3: 既存プラグインBID化** (90分) -- FileBox/Math系をBID YAML定義に変換 -- C ABI関数のBIDメタデータ追加 -- 既存機能の完全互換確認 - -##### **Step 4: WASMバックエンド実装** (120分) -- BID→WASM import宣言生成 -- ホスト側importObject自動生成 -- ブラウザー環境動作確認 - -##### **Step 5: VM/AOTバックエンド実装** (将来実装) -- VM: 関数ポインタテーブル経由呼び出し -- AOT: LLVM IR外部宣言生成 - -##### **Step 6: Effect System最適化** (将来実装) -- `pure`関数の共通部分式除去 -- `mut`/`io`の順序保持最適化 - -#### **🎉 革命的期待効果** -- **開発効率**: 1つのBID定義で全バックエンド自動対応 -- **パフォーマンス**: Effect Systemによる従来不可能な最適化 -- **拡張性**: プラグイン追加が全環境で自動展開 -- **汎用性**: ブラウザー/ネイティブ/サーバー統一API - -## 🚨 **緊急優先: MIR 26命令削減プロジェクト** (2025-08-17) - -### **重大発見: 実装膨張問題** -- **現状**: 35命令実装(175%膨張) -- **目標**: 26命令(ChatGPT5 + AI大会議仕様) -- **Gemini評価**: 削減戦略「極めて健全」「断行推奨」 - -#### **削減対象9命令** -``` -削除: UnaryOp, Load, Store, TypeCheck, Cast, Copy, ArrayGet, ArraySet, - Debug, Print, Nop, Throw, Catch, RefNew, BarrierRead, BarrierWrite, - FutureNew, FutureSet, Await - -統合: → BoxFieldLoad/BoxFieldStore, AtomicFence -intrinsic化: → Call(@array_get, ...), Call(@print, ...) -``` - -#### **🎉 MIR削減プロジェクト準備完了 (2025-08-17)** - -### **✅ 完了済み作業** -- **26命令仕様書**: ChatGPT5設計完全準拠 -- **緊急Issue作成**: 5週間詳細実装計画 -- **詳細分析完了**: 35→26命令の完全マッピング -- **Gemini評価**: 「極めて健全」「断行推奨」確定 - -### **📋 削減概要** -``` -削除: 17命令 (UnaryOp, Load/Store, Print/Debug, 配列操作等) -追加: 10命令 (BoxFieldLoad/Store, WeakCheck, Send/Recv等) -統合: intrinsic化によるCall統一 (@print, @array_get等) -効果: 複雑性制御・保守性向上・JIT/AOT基盤確立 -``` - -### **🚀 実装スケジュール** -``` -Phase 1 (8/18-8/24): 新命令実装・共存システム -Phase 2 (8/25-8/31): フロントエンド移行 -Phase 3 (9/1-9/7): 最適化パス更新 -Phase 4 (9/8-9/14): バックエンド対応 -Phase 5 (9/15-9/21): 完了・クリーンアップ -``` - -#### **次のアクション**: **Phase 1実装開始** 🔥 - -#### **📊 技術的妥当性評価結果** -- ✅ **MIR ExternCall統合**: 技術的実現可能 -- ✅ **既存ローダー互換性**: 段階移行で問題なし -- ✅ **バックエンド実装複雑度**: 管理可能レベル -- ✅ **Effect System最適化**: 段階的実装で十分実現可能 - -#### **💎 Gemini先生最終提言採用** -**リソース所有権拡張**: 将来のBID v1で `own`, `borrow` 概念導入予定 -→ FFI境界越えのメモリ安全性を静的保証 - -### 📋 **全体ロードマップ更新** -1. **🔥 Phase 9.75f-BID**: BID統合プラグインシステム ← **現在ここ** -2. **Phase 9.75f-3**: 基本型動的化実験(BID基盤活用) -3. **Phase 10**: LLVM AOT準備(BID Effect System活用) -4. **Phase 11**: リソース所有権システム(BID v1) - -## ✅ **Phase 9.77完了: WASM緊急復旧作業完了!** - -### ✅ **Task 1.1完了: BoxCall命令実装** -- **BoxCall実装**: toString(), print(), equals(), clone(), log()メソッド完全実装 ✅ -- **codegen.rs修正**: generate_box_call関数とヘルパー関数5個追加 ✅ -- **パターンマッチ追加**: MirInstruction::BoxCall対応 ✅ -- **ビルド成功**: コンパイルエラーなし ✅ - -### ✅ **Task 1.2完了: wasmtimeバージョン統一 + RuntimeImports** -- **wasmtime更新**: 18.0 → 35.0.0 完了 ✅ -- **RuntimeImports追加**: box_to_string, box_print, box_equals, box_clone 実装済み ✅ -- **ビルド成功**: バージョン互換性問題解決 ✅ - -### ✅ **Task 1.3完了: WASM出力UTF-8エラー修正(Copilot解決!)** -**問題**: 「Generated WASM is not valid UTF-8」エラー -**原因**: WASMバイナリをUTF-8文字列として扱っていた - -**Copilotの修正**: -```rust -// Before (broken) -let wasm_code = wasm_backend.compile_module(compile_result.module)?; -let output_str = std::str::from_utf8(&wasm_code)?; - -// After (fixed) -let wat_text = wasm_backend.compile_to_wat(compile_result.module)?; -let output_str = wat_text; -``` - -**結果**: WAT(テキスト形式)を直接出力することで解決 ✅ - -### 🎉 **Phase 9.77成果まとめ** -- ✅ BoxCall命令完全実装 -- ✅ wasmtime 35.0.0対応 -- ✅ UTF-8エラー解決(手動でCopilot修正を適用) -- ✅ WASM基本機能復旧(リリースビルドで動作確認) -- ✅ WATファイル生成成功: `local result = 42` → 正常なWAT出力 - -### 📋 **残課題** -- ⚠️ デバッグビルドでのWASMエラー(別のバグの可能性) -- 🔄 git pullでのマージコンフリクト(expressions.rsモジュール分割と衝突) - -### 🚀 **次のステップ** -1. **デバッグビルドエラー調査**: なぜデバッグビルドで失敗するか -2. **WASM実行テスト**: 生成されたWATファイルの実行確認 -3. **Phase 10準備**: LLVM Direct AOT実装へ - -## 🎉 **Phase 9.75j完了: 警告削減100%達成!** - -### ✅ **Phase 9.75j - 100% 完了** -- **警告完全削減**: 106個→0個の警告削減(100%改善達成!) ✅ -- **unused変数修正**: すべてのunused variable警告を修正 ✅ -- **dead_code対応**: 適切な#[allow(dead_code)]アノテーション追加 ✅ -- **コードベースクリーン化**: 完全にwarning-freeなコードベース実現 ✅ - -### 🌟 **実装成果 - 驚異的改善** -``` -Before: 106 warnings (build時に大量警告出力) -After: 0 warnings (完全クリーン!) -改善率: 100% warning削減達成 -``` - -## 🎉 **Phase 9.75e完了: using nyashstd実装完全成功!** - -### ✅ **Phase 9.75e - 100% 完了** -- **using文実装**: USINGトークン・パーサー・AST完全実装 ✅ -- **BuiltinStdlib基盤**: 組み込み標準ライブラリ基盤作成 ✅ -- **stdlib統合完了**: `crate::stdlib` import問題解決、ビルド成功 ✅ -- **全機能動作確認**: string.create(), string.upper(), integer.create(), bool.create(), array.create(), console.log() 全て動作確認 ✅ - -### 🌟 **実装成果 - 完全動作確認済み** -```nyash -using nyashstd - -// ✅ 実際に動作テスト済み -local result = string.create("Hello World") // → "Hello World" -local upper = string.upper(result) // → "HELLO WORLD" -local number = integer.create(42) // → 42 -local flag = bool.create(true) // → true -local arr = array.create() // → [] -console.log("✅ using nyashstd test completed!") // ✅ 出力成功 -``` - -## 🎉 **Phase 9.75g完了: expressions.rsモジュール化 100%成功!** - -### ✅ **Phase 9.75g - 100% 完了** -- **expressions.rsモジュール化**: 1457行の巨大ファイルを7つの専門モジュールに分割 ✅ -- **operators.rs**: 二項演算・単項演算処理 (334行) ✅ -- **method_dispatch.rs**: メソッド呼び出しディスパッチ (456行) ✅ -- **field_access.rs**: フィールドアクセス処理 (126行) ✅ -- **delegation.rs**: from呼び出し・デリゲーション (325行) ✅ -- **async_ops.rs**: await式処理 (16行) ✅ -- **utils.rs**: ユーティリティ関数 (34行) ✅ -- **expressions.rs**: メインディスパッチャー (179行) ✅ -- **機能保持テスト**: using nyashstd完全動作確認 ✅ - -### 🌟 **実装成果 - 単一責任原則による劇的改善** -``` -Before: expressions.rs (1457行の巨大ファイル) -After: 7つの専門モジュール + メインディスパッチャー -``` - -**効果**: -- 🎯 **保守性向上**: 機能別分離で変更影響の局所化 -- 🚀 **開発効率向上**: 目的別ファイルでの迅速な作業 -- 🧹 **コード品質向上**: 単一責任原則の徹底 -- ✅ **機能保持**: 既存機能100%動作確認済み - -## 🎉 **Phase 9.75h完了!** - 文字列リテラル自動変換 & nyashstd拡張 **100%成功!** - -### **✅ 実装完了: 文字列リテラル自動変換(革命的ユーザビリティ向上)** - -**成果**: Everything is Box哲学 + ユーザーフレンドリー性の完全両立 -**実装**: パーサーレベルで全リテラルをBox自動変換システム完成 - -### **🌟 実現された自動変換システム** -```nyash -// 🎉 新しい書き方 - 自動変換完全実装済み! -local text = "Hello" // ✅ StringBox::new("Hello")に自動変換 -local name = "Alice" // ✅ StringBox::new("Alice")に自動変換 -local age = 30 // ✅ IntegerBox::new(30)に自動変換 -local active = true // ✅ BoolBox::new(true)に自動変換 -local pi = 3.14159 // ✅ FloatBox::new(3.14159)に自動変換 - -// Everything is Box哲学維持 + 書きやすさ革命達成! -``` - -### **🎯 実装詳細 - 100%完了** -1. **✅ パーサー修正完了**: `src/parser/expressions.rs` リテラル解析時にBox生成AST自動挿入 -2. **✅ 全型対応完了**: String/Integer/Bool/Float全リテラル自動変換 -3. **✅ 互換性保証**: 既存の明示的Box生成も継続サポート -4. **✅ nyashstd連携**: 標準ライブラリとの完全協調動作確認済み - -### **🚀 動作確認テスト完了** -```nyash -using nyashstd -local name = "Nyash" // 自動StringBox変換 -local year = 2025 // 自動IntegerBox変換 -local upper = string.upper(name) // nyashstd完全連携 -console.log("🚀 " + upper + " " + year.toString() + " Ready!") -// 出力: "🚀 NYASH 2025 Ready!" ✅ -``` - -## 🚨 **緊急実装タスク (Priority High)** -**GitHub Issue**: Phase 8.9実装 -**ドキュメント**: [phase_8_9_birth_unified_system_copilot_proof.md](docs/予定/native-plan/issues/phase_8_9_birth_unified_system_copilot_proof.md) - -### **🎯 Copilot委託タスク(手抜き対策済み)** -1. **透明化システム完全削除** - `from StringBox(content)` エラー化 -2. **明示的birth()構文強制** - `from StringBox.birth(content)` 必須化 -3. **weak参照修正** - fini後の自動null化 -4. **包括テストケース** - 手抜き検出用5段階テスト - -## 🎉 **Phase 9.75i 完了報告** (2025-08-16 19:15) - -### **本日の成果** -1. **match_tokenバグ修正完了** - パーサーの根幹バグを解決 -2. **birth()コンストラクタキー不一致修正** - パーサー/インタープリター同期 -3. **static boxメソッド呼び出し実装** - ProxyServer.main()等の静的メソッド対応 -4. **3つのCopilotアプリ全て動作確認** - Nyashの実用性を実証 - -### **修正したバグ一覧** -- ✅ match_token関数の内容比較バグ(discriminant問題) -- ✅ birth/init/packコンストラクタのキー形式不一致 -- ✅ static boxメソッド呼び出し未実装 -- ✅ BufferBox/SocketBoxの存在確認 - -## 🚨 **緊急バグ発見: birth()コンストラクタのキー不一致** (2025-08-16 18:30) - -### **🐛 新たに発見された重大バグ: birth()コンストラクタが動作しない** -**影響範囲**: birth()を使用する全てのコンストラクタ(引数付き) -**症状**: birth(args)を定義しても「No constructor found」エラーが発生 - -### **🔍 バグ詳細** -**パーサー(box_definition.rs)**: -```rust -// Line 381: コンストラクタを"birth"として保存 -constructors.insert(field_or_method, constructor); // field_or_method = "birth" -``` - -**インタープリター(objects.rs)**: -```rust -// コンストラクタを"birth/引数数"で検索 -let birth_key = format!("birth/{}", arguments.len()); -if let Some(constructor) = final_box_decl.constructors.get(&birth_key) { -``` - -**問題**: パーサーは"birth"で保存、インタープリターは"birth/1"で検索→不一致でエラー - -### **🎯 修正方針** -1. パーサー側で保存時に"birth/引数数"形式に変更 -2. init, pack も同様に修正が必要 -3. 既存テストの確認が必要 - -## 🚨 **緊急バグ修正: match_token関数の重大な不具合** (2025-08-16) - -### **🐛 発見された重大バグ: パーサーのmatch_token関数** -**影響範囲**: パーサー全体のトークン比較処理 -**症状**: birth()統一システムで正常なメソッドがBox名コンストラクタと誤認識される - -### **🔍 バグ詳細** -```rust -// src/parser/common.rs の match_token関数 -fn match_token(&self, token_type: &TokenType) -> bool { - std::mem::discriminant(&self.current_token().token_type) == - std::mem::discriminant(token_type) -} -``` - -**問題**: `std::mem::discriminant`は列挙型のバリアントのみ比較し、内容を比較しない -- `TokenType::IDENTIFIER("LifeBox")` と `TokenType::IDENTIFIER("getInfo")` が同一と判定される -- Box名チェックが誤動作し、通常のメソッドをコンストラクタと誤認識 - -### **🎯 修正方針決定 (2025-08-16)** -**調査結果**: match_tokenの使用は99%が演算子トークン(値なし)で問題なし -**問題箇所**: box_definition.rs line 387の1箇所のみ -**修正方針**: match_token関数は変更せず、問題箇所を直接修正 - -### **✅ 修正内容** -```rust -// box_definition.rs line 387の修正 -// 修正前(バグあり) -if self.match_token(&TokenType::IDENTIFIER(name.clone())) && self.peek_token() == &TokenType::LPAREN { - -// 修正後(完全比較) -if let TokenType::IDENTIFIER(id) = &self.current_token().token_type { - if id == &name && self.peek_token() == &TokenType::LPAREN { - // Box名コンストラクタエラー処理 - } -} -``` - -## 🚀 **現在進行中: Phase 9.75i** - match_tokenバグ修正 & Copilotアプリ移植 - -### **✅ 完了: match_token関数修正** -**修正内容**: box_definition.rs line 387の完全内容比較実装 -**成果**: birth()統一システム正常動作確認 - -### **✅ 完了: static boxメソッド呼び出しバグ修正** (2025-08-16 19:00) -**修正内容**: execute_method_callにstatic boxメソッドチェック追加 -**成果**: TestStatic.main(), TestStatic.greet()正常動作確認 - -### **✅ 完了: appsディレクトリの3つのアプリ動作確認** (2025-08-16 19:15) - -**場所**: `C:\git\nyash-project\nyash\apps` -**目的**: Copilotが作成した3つのアプリケーションをNyashで実行可能にする -**重要性**: Nyash実用性の実証・リテラル自動変換の実戦テスト - -**進捗状況**: -- ✅ Chip-8エミュレーター: 動作確認済み(weak参照テスト成功) -- ✅ Kiloエディター: birth()修正で動作確認済み(リテラル自動変換対応) -- ✅ Tinyプロキシ: ProxyServer.main()正常起動確認(ゼロコピー機能実装済み) - -**成果**: -- 全3アプリケーションがNyashで正常動作 -- static boxメソッド呼び出し機能の実用性を実証 -- BufferBox/SocketBoxの実装確認 -- ゼロコピー検出機能(is_shared_with/share_reference)の動作確認 - -### **📋 実装手順** -1. **match_tokenバグ修正**: 完全な内容比較の実装 -2. **全機能テスト実施**: パーサー修正の影響確認 -3. **アプリケーション調査**: 3つのアプリの内容・依存関係を確認 -4. **文法適合**: 新しいリテラル自動変換に対応 -5. **機能テスト**: 各アプリの動作確認 -6. **問題修正**: 発見された問題の解決 - -### **✅ 完了済み条件** -- ✅ 透明化システム実装済み -- ✅ 明示的birth()構文実装済み -- ✅ weak参照ライフサイクル修正済み -- ✅ リテラル自動変換システム完成 -- ✅ nyashstd標準ライブラリ統合完成 - -## 📦 **移植対象アプリケーション** -1. **🌐 Tinyproxy** - ゼロコピー判定機能実証(HTTPプロキシサーバー) -2. **🎮 Chip-8エミュレーター** - fini伝播・weak参照実戦テスト -3. **✏️ kilo テキストエディター** - 「うっかり全体コピー」検出機能 - -### 🛠️ **新API要件(実装予定)** -- **ゼロコピー判定**: `BufferBox.is_shared_with()`, `share_reference()` -- **fini伝播システム**: 依存オブジェクト自動クリーンアップ -- **weak参照**: `WeakBox.is_alive()`, 循環参照防止 -- **メモリ効率監視**: `Box.memory_footprint()`, リアルタイム警告 - -## 📈 **完了済みPhase要約** -- **Phase 8**: MIR/WASM基盤構築、13.5倍高速化実証 ✅ -- **Phase 9**: AOT WASM実装、ExternCall基盤 ✅ -- **Phase 9.75**: Arc→RwLock全変換完了 ✅ -- **Phase 9.75e**: using nyashstd実装完全成功 ✅ **← NEW!** - -## 🔮 **今後のロードマップ** -- **Phase 9.75g**: expressions.rsモジュール化完了 ✅ **← NEW!** -- **Phase 9.75h**: 文字列リテラル自動変換実装 ← **現在ここ** -- **Phase 9.5**: HTTPサーバー実用テスト(2週間) -- **Phase 10**: LLVM Direct AOT(4-6ヶ月、1000倍高速化目標) - -## 📊 **主要実績** -- **Box統一アーキテクチャ**: Arc二重ロック問題を根本解決 -- **実行性能**: WASM 13.5倍、VM 20.4倍高速化達成 -- **Everything is Box哲学**: 全11個のBox型でRwLock統一完了 -- **標準ライブラリ**: using nyashstd完全実装 ✅ **← NEW!** - -## 🔥 **実装優先度** - -### **🚨 Critical (即時実装)** -1. **文字列リテラル自動変換** - パーサー修正(1時間) -2. **整数/真偽値リテラル自動変換** - 統一実装(30分) -3. **nyashstd拡張テスト** - 自動変換動作確認(15分) - -### **⚡ High (今週中)** -4. **ビルトインBox判定システム** - is_builtin_box()実装 -5. **pack透明化解決** - from BuiltinBox()自動変換 -6. **統合テスト作成** - 透明化動作確認 - -### **📝 Medium (来週)** -7. **エラーメッセージ改善** - pack隠蔽、birth中心メッセージ -8. **ドキュメント更新** - CLAUDE.md文字列リテラル自動変換反映 -9. **既存テスト見直し** - pack直接呼び出し削除 - -### **🔮 Future (今後の予定)** -10. **FFI/ABI統合** - ExternBox経由外部API(Phase 11予定) -11. **動的ライブラリ読み込み** - 外部ライブラリBox化(Phase 12予定) -12. **BID自動生成** - YAML→実装自動化(Phase 13予定) - -## 🚀 **Phase 8.8: pack透明化システム実装準備完了** - -### **✅ 完了事項 (2025-08-15)** -1. **birth()実装完了** - コンストラクタ統一構文実装 ✅ -2. **ドキュメント矛盾修正完了** - pack機能正しい定義確立 ✅ -3. **pack透明化イシュー作成完了** - Copilot実装仕様書完成 ✅ -4. **using nyashstd実装完了** - 標準ライブラリアクセス実現 ✅ **← NEW!** - -### **🎯 次のアクション (Phase 9.75h)** -**優先順位1**: 文字列リテラル自動変換実装 -**優先順位2**: Copilot pack透明化システム実装依頼 - -#### **文字列リテラル自動変換実装内容** -1. **パーサー修正** - string literal → StringBox自動変換 -2. **整数リテラル対応** - integer literal → IntegerBox自動変換 -3. **真偽値リテラル対応** - boolean literal → BoolBox自動変換 -4. **型推論システム基盤** - Everything is Box + 使いやすさ - -#### **完了条件** -- リテラル自動変換動作確認 -- 既存機能継続動作 -- Everything is Box哲学維持 -- ユーザビリティ大幅向上 - -## 🔮 **次のステップ** - -### **Phase 9.75j**: 残りのバグ修正とコード品質向上 -1. **警告の削減** - 現在106個のwarningを削減 -2. **テストスイート整備** - local_testsの自動テスト化 -3. **ドキュメント更新** - 最新の修正を反映 - -### **Phase 10準備**: LLVM Direct AOT実装準備 -- MIR命令セット最適化 -- AOTバックエンド設計 -- パフォーマンステスト基盤 - --- -**現在状況**: 🚀 **Phase 9.75f ビルトインBox動的ライブラリ分離実装中!** -**最終更新**: 2025-08-17 06:30 - -## 🔥 **Phase 9.75f: 緊急ビルド時間改善(Option C段階的実装)** - -### 🎯 **動的ライブラリ化によるビルド革命** -- **現状**: 16個のビルトインBox静的リンク → 2分以上のビルド -- **目標**: コア2MB + 動的ライブラリ → 15秒ビルド - -### 📋 **Option C: 段階的移行戦略** -1. **[9.75f-1]**: FileBox動的化(即実装) - - 詳細: [phase_9_75f_1_filebox_dynamic.md](docs/予定/native-plan/issues/phase_9_75f_1_filebox_dynamic.md) - - libnyash_file.so作成、C ABI実装 - - 目標: 15秒のビルド時間短縮 - -2. **[9.75f-2]**: Math/Time系動的化(今週中) - - 詳細: [phase_9_75f_2_math_time_dynamic.md](docs/予定/native-plan/issues/phase_9_75f_2_math_time_dynamic.md) - - 統合プラグイン(Math, Random, Time) - - 目標: さらに30秒短縮 - -3. **[9.75f-3]**: 基本型実験(将来) - - 詳細: [phase_9_75f_3_core_types_experiment.md](docs/予定/native-plan/issues/phase_9_75f_3_core_types_experiment.md) - - --dynamic-all フラグで完全動的化 - - 目標: 5秒ビルド(実験的) - -### ✅ **完了タスク** -- FFI-ABI file実装テスト(削除済み) -- Gemini先生への相談・アドバイス取得 -- FileBox実装確認(存在・利用可能) -- Option C実装計画策定 - -### 🚀 **現在の作業: 9.75f-1 FileBox動的化** - -#### ✅ **完了タスク** -1. **workspace構成準備** - Cargo.toml設定、プラグインディレクトリ作成 ✅ -2. **FileBoxプラグイン作成** - nyash-fileクレート実装 ✅ -3. **C ABI関数実装** - nyash_file_open/read/write/exists/free完全実装 ✅ -4. **プラグインローダー実装** - FileBoxProxy + PluginLoader完成 ✅ -5. **インタープリター統合** - 動的FileBox作成パス実装 ✅ - -#### ✅ **解決済み: 変数型変換バグ(根本原因特定・修正完了)** -- **原因**: FileBoxProxyの`share_box()`メソッドが`VoidBox::new()`を返していた -- **修正内容**: - - ✅ FileBoxProxy.share_box()修正: 自分自身の複製を返すように変更 - - ✅ FileBoxProxy.clone_box()修正: 正しいインスタンス複製実装 - - ✅ toString()メソッド追加: execute_file_proxy_methodに実装 -- **テスト結果**: - - ✅ 修正前: `type_name: VoidBox` → `Object is NOT FileBoxProxy` - - ✅ 修正後: `type_name: FileBox` → `Object is FileBoxProxy, calling execute_file_proxy_method` - -#### 📊 **ビルド時間改善実績** -- **プラグイン単体ビルド**: 2.86秒(98%改善!) -- **メインビルド**: 2分以上(変わらず) -- **目標**: 動的ロードで15秒以下のメインビルド実現 - -## 🌐 **WASM研究メモ** - -### **実行フロー: MIR → WAT → WASM** -``` -Nyashソースコード - ↓ (Parser/AST) -MIR (中間表現) - ↓ (WasmCodegen) -WAT (WebAssembly Text形式) - ↓ (wabt::wat2wasm) -WASM (バイナリ形式) -``` - -### **現在の実装状況** -- ✅ **console.log()**: ConsoleBox経由で動作 -- ❌ **canvas操作**: ExternCall定義はあるが、canvasオブジェクトが未実装 -- ✅ **WAT生成**: UTF-8エラー修正済み、正常に出力 - -### **Canvas実装の選択肢** - -#### **Option 1: CanvasBox実装(推奨)** -```nyash -// ConsoleBoxと同様のアプローチ -local canvas = new CanvasBox("canvas_id", 800, 600) -canvas.fillRect(10, 10, 100, 50, "#FF0000") -canvas.fillText("Hello", 50, 100, "#000000", "20px Arial") -``` - -**メリット**: -- Everything is Box哲学に合致 -- 既存のBoxパターンと一貫性 -- 型安全性の確保 - -#### **Option 2: グローバルcanvasオブジェクト** -```nyash -// MIRビルダーで特別扱い -canvas.fillRect(10, 10, 100, 50, 255, 0, 0, 255) -``` - -**メリット**: -- JavaScriptのCanvas APIに近い -- 実装が簡単 - -**デメリット**: -- Everything is Box哲学から逸脱 -- 特殊ケースの増加 - -#### **Option 3: 標準ライブラリ拡張** -```nyash -using nyashstd - -canvas.create("myCanvas", 800, 600) -canvas.fillRect(10, 10, 100, 50) -``` - -**メリット**: -- 名前空間で整理 -- 拡張性が高い - -### **次のステップ** -1. CanvasBox実装の設計 -2. ExternCall統合 -3. WASMブラウザー実行環境の構築 - -## 🔧 **Parser リファクタリング完了報告** - -### ✅ **全ステップ完了 (100%)** -- **Phase 9.75g**: expressions.rsモジュール化 100%完了 ✅ -- **Parser Step 1**: common.rs作成(ユーティリティトレイト) ✅ -- **Parser Step 2**: expressions.rs(既存)の整理 ✅ -- **Parser Step 3**: declarations/モジュール作成 ✅ - - box_definition.rs (628行) - - static_box.rs (290行) - - dependency_helpers.rs (144行) -- **Parser Step 4**: items/モジュール作成 ✅ - - global_vars.rs (33行) - - functions.rs (79行) - - static_items.rs (117行) -- **Parser Step 5**: 最終クリーンアップ・ドキュメント更新 ✅ - -### 📊 **最終成果** -``` -parser/ -├── mod.rs (1530行 → 227行) 🎯 85%削減! -├── common.rs (121行) -├── expressions.rs (555行) -├── statements.rs (488行) -├── declarations/ -│ ├── mod.rs (15行) -│ ├── box_definition.rs (628行) -│ ├── static_box.rs (290行) -│ └── dependency_helpers.rs (144行) -└── items/ - ├── mod.rs (17行) - ├── global_vars.rs (33行) - ├── functions.rs (79行) - └── static_items.rs (117行) -``` - -### 🌟 **達成内容** -- **保守性向上**: 機能別モジュール分離で変更影響の局所化 -- **開発効率向上**: 目的別ファイルで迅速な作業可能 -- **コード品質向上**: 単一責任原則の徹底 -- **可読性向上**: 関連コードが論理的にグループ化 - -## 🚀 **次期リファクタリング計画** - -### **🎯 対象ファイル(優先順位順)** - -1. **src/interpreter/expressions.rs (1457行)** - - **分割案**: operators.rs, calls.rs, access.rs, builtins.rs - - **予想削減率**: 70-80% - - **優先度**: 🔥 最高(最大のファイル) - -2. **src/mir/builder.rs (1109行)** - - **分割案**: expressions.rs, statements.rs, variables.rs - - **予想削減率**: 60-70% - - **優先度**: ⚡ 高 - -3. **src/interpreter/objects.rs (1105行)** - - **分割案**: instances.rs, prototypes.rs, utils.rs - - **予想削減率**: 50-60% - - **優先度**: ⚡ 高 - -4. **src/ast.rs (1006行)** - - **分割案**: expressions.rs, statements.rs, literals.rs, common.rs - - **予想削減率**: 70-80% - - **優先度**: 📝 中 - -5. **src/box_trait.rs (923行)** - - **分割案**: 型別モジュール(string.rs, integer.rs, array.rs等) - - **予想削減率**: 70-80% - - **優先度**: 📝 中 - -### **🔧 現在の作業** -**interpreter/expressions.rs** のモジュール分割を開始予定 - -## 🔍 **pack透明化システム調査報告** (2025-08-16) - -### **🌟 調査結果: pack透明化の実装詳細** - -**結論**: packメソッドは実際にはRustコードに存在せず、完全に透明化されている! - -### **📋 実装の仕組み** - -1. **ビルトインBoxには`pack`メソッドが存在しない** - - StringBox, IntegerBox等のRust実装を確認 - - packメソッドは一切定義されていない - - 代わりに`new()`メソッドのみ実装 - -2. **`new StringBox("hello")` の動作** - ```rust - // interpreter/objects.rs の execute_new() 内 - "StringBox" => { - let string_box = Box::new(StringBox::new(string_value)); - return Ok(string_box); - } - ``` - - 直接`StringBox::new()`を呼び出し - -3. **`from StringBox.birth(content)` の動作** - ```rust - // interpreter/delegation.rs の execute_builtin_birth_method() 内 - "StringBox" => { - let string_box = StringBox::new(content); - Ok(Box::new(VoidBox::new())) // 初期化成功を示すvoid返却 - } - ``` - - 内部で同じく`StringBox::new()`を呼び出し - - ユーザーには`birth()`として見える - -### **🎯 透明化の実現方法** - -1. **パーサーレベル**: packキーワードは解析されるが、ビルトインBoxでは使用されない -2. **デリゲーションシステム**: `from BuiltinBox.birth()` が内部で適切な初期化を行う -3. **ユーザー視点**: packの存在を意識する必要がない - birth()統一構文のみ使用 - -### **✅ 設計の利点** - -- **一貫性**: ユーザー定義Box・ビルトインBox問わず`birth()`で統一 -- **シンプル**: 内部実装(pack)と外部インターフェース(birth)の分離 -- **拡張性**: 将来的にpack処理が必要になっても透明性を維持可能 - -### **💡 重要な発見** - -`is_builtin_box()`関数とBUILTIN_BOXESリストが透明化の鍵: -- ビルトインBox判定により、適切な初期化パスへ振り分け -- ユーザー定義Boxとは異なる処理経路を通る -- しかし外部インターフェースは統一されている \ No newline at end of file +**最終更新**: 2025-08-17 21:30 +**次回レビュー**: 2025-08-20(Day 3完了時) \ No newline at end of file diff --git a/docs/archive/bid_ffi_integration_discussion_2025-08-17.md b/docs/archive/bid_ffi_integration_discussion_2025-08-17.md new file mode 100644 index 00000000..61c583d8 --- /dev/null +++ b/docs/archive/bid_ffi_integration_discussion_2025-08-17.md @@ -0,0 +1,92 @@ +# BID-FFI統合議論アーカイブ (2025-08-17) + +## 概要 +Phase 9.75g BID(Box Interface Definition)とFFI ABI v0の統合について、設計の簡素化と段階的実装を検討した記録。 + +## 議論の流れ + +### 1. 問題提起 +- FFI ABI v0仕様(`ffi-abi-specification.md`)を確認 +- Phase 9.75g BIDが野心的すぎて複雑との懸念 +- 両者の統合による簡素化を提案 + +### 2. 主要な発見 + +#### FFI ABI v0の良い点 +- シンプルで実績がある +- 型システムが完備(i32, i64, f32, f64, bool, string, array) +- メモリモデルが明確(32ビットポインタ、4バイトアライメント) +- Effect systemが4種類で明確(pure/mut/io/control) + +#### BIDの問題点 +- 型が不完全(i32, f32欠落) +- Transport層が野心的すぎる(grpc/rest/python_bridge等) +- 実装の複雑さが高い + +### 3. C ABIの説明 +ユーザーからの質問「C ABIって何?」に対して: +- C言語のバイナリレベルでの約束事 +- どの言語からでも同じ方法で関数を呼べる仕組み +- 高速(直接マシンコード呼び出し) +- 安定(何十年も使われている標準) + +### 4. 統合計画の作成 +`phase_9_75g_bid_ffi_abi_alignment.md`として以下を提案: +- Phase 9.75g-0: FFI ABI v0準拠(1週間) +- 型システムの統一 +- メモリモデルの明確化 +- 段階的実装(C ABI → gRPC/REST → 言語ブリッジ) + +### 5. AI大会議での最終レビュー + +#### Gemini先生の評価 +- 全体的に優れた計画 +- Simple Firstの原則を支持 +- 段階的実装は現実的 + +#### ChatGPT先生の技術的指摘 +1. **ポインタサイズ**: 32ビット固定は危険 → `usize`推奨 +2. **アライメント**: 4バイト不十分 → 8バイト推奨 +3. **型追加**: Option/Result型を最初から +4. **API設計**: 単一invoke関数で拡張性確保 +5. **所有権**: 明文化が必須 + +### 6. 重要な技術修正 + +```rust +// ❌ 当初の案 +ptr: i32 // 32ビット固定 +alignment: 4 // 4バイト + +// ✅ 修正案 +ptr: usize // プラットフォーム依存 +alignment: 8 // 8バイト保証 + +// Boxヘッダー改善案(ChatGPT) +#[repr(C)] +pub struct BoxHeader { + magic: u32, // "NYBX" + abi_major: u16, // バージョン管理 + abi_minor: u16, + type_id: u32, + flags: u32, // 将来のatomic等 + ref_count: u32, + field_count: u16, + reserved: u16, // 8バイトアライメント +} +``` + +### 7. NyaMeshとの関連 +- 当初の野心的なTransport設計はNyaMesh(P2Pライブラリ)でやろうとしていたことに似ている +- Phase 4でP2P追加は価値ありとAIも評価 + +## 結論 +- FFI ABI v0準拠で始める(シンプル・実績あり) +- ChatGPTの技術的指摘を反映(ポインタ幅、アライメント、所有権) +- 段階的に拡張(C ABI → ネットワーク → P2P) +- 「最初は簡単に動かして、拡張できる方式」の実現 + +## 次のステップ +1. AIレビューのフィードバックを適用 +2. 実装計画をissueとして作成 +3. Linux x86-64限定で1週間スプリント開始 \ No newline at end of file diff --git a/docs/予定/native-plan/issues/bid_ai_meeting_2025-08-17.md b/docs/予定/native-plan/issues/bid_ai_meeting_2025-08-17.md new file mode 100644 index 00000000..8f9d5d5b --- /dev/null +++ b/docs/予定/native-plan/issues/bid_ai_meeting_2025-08-17.md @@ -0,0 +1,137 @@ +# BID設計 AI大会議記録 (2025-08-17) + +## 参加者 +- Gemini先生 +- ChatGPT先生(GPT-5) +- Claude(司会・まとめ) + +## 議題 +Nyashプログラミング言語のBID(Box Interface Definition)設計について + +## Gemini先生の回答 + +### 1. 複雑性について +**回答:** 過度な複雑性とは思いません。むしろ、Rustのトレイトを用いた抽象化は、このようなシナリオで非常にうまく機能します。 + +**推奨アプローチ:** +1. `UniversalConnector` トレイトのAPIを設計します。 +2. **最初の具体的な実装として `DynamicLibraryConnector` のみを実装します。** +3. 他のコネクター(`GrpcConnector` など)は、構造体だけ定義しておくか、`todo!()` マクロで未実装を示す形にしておきます。 + +### 2. 型システムについて +**回答:** `MirValue`(Nyashの内部値表現)のような中間表現に一度変換するアプローチは、FFIやRPCにおいて非常に現実的かつ一般的な解決策です。 + +**推奨アプローチ:** +1. **サポートする型を限定することから始めます。** まずは数値、文字列、真偽値、そして「ハンドル(不透明ポインタやID)」のような基本的な型に絞ります。 +2. 複雑な型(Nyashのオブジェクトや配列など)は、シリアライズ(JSONやMessagePackなど)して文字列やバイト配列として渡す、というルールを設けることも有効です。 + +### 3. 性能について +**結論として、`UniversalConnector` トレイトによる抽象化自体の性能への影響は軽微です。** パフォーマンスが重要な場合は、一度の呼び出しで多くの作業を行うような粒度の大きいAPI(例: `process_batch(data)`) をBIDで定義することが効果的です。 + +### 4. エラー処理について +**回答:** はい、可能です。これは統一抽象化レイヤーの大きな利点の一つです。Rustの `enum` を使って統一的なエラー型を定義することを強く推奨します。 + +```rust +#[derive(Debug, thiserror::Error)] +pub enum BidError { + #[error("Transport layer error: {0}")] + Transport(#[from] Box), + #[error("Interface error: {0}")] + Interface(String), + #[error("Connection setup failed: {0}")] + Connection(String), + #[error("Remote execution error: {0}")] + Remote(String), +} +``` + +### 5. 段階的実装について +**回答:** 提案されている実装順序は非常に合理的で、リスクを最小限に抑えつつ着実に進められる優れたロードマップです。 + +### 6. 既存システムとの比較について +**BIDの独自価値は、「Everything is a Box」というNyashのコア哲学を、言語の境界を越えて外部世界にまで拡張する点**に尽きます。 + +### 7. セキュリティについて +**回答:** **現段階では過剰設計の可能性が高いです。** + +**推奨アプローチ:** +1. **今は実装しない。** +2. ただし、将来の拡張ポイントとしてBID定義に `permissions` のようなオプショナルなセクションを設けることだけは念頭に置いておくと良いでしょう。 + +### まとめ +**最適なバランスを取るための鍵は、「抽象(インターフェース)と具象(実装)の分離」です。** + +## ChatGPT先生の回答 + +### 結論と全体方針 +- **二層化コア:** BIDは「型/意味」レイヤー、コネクタは「バインディング/トランスポート」レイヤーに厳密分離 +- **最小中核の固定化:** まずC ABI動的ライブラリ+同期単発呼び出し(unary)+最小型集合+統一エラーの4点を固める +- **コード生成前提:** YAML BIDからRust/他言語のスタブ/スケルトンを自動生成 +- **場所透過の現実解:** API設計で「粗粒度・バッチ・ストリーミング」を促す + +### Transport/Connectorの設計 +- **二経路最適化:** + - 同一プロセス(C ABI/`*.so`): 直関数ポインタ呼び出し(ゼロコピー)=最速経路 + - 遠隔/ブリッジ: 仕様化した「カノニカルエンコーディング(NCE)」で`invoke` + +### 型システム(MirValueの現実解) +- **最小型集合:** `bool`, `i32/i64`, `f64`, `string(utf8)`, `bytes`, `list`, `map`, `record{...}`, `variant{...}`, `option`, `result`, `resource`(ハンドル), `opaque` +- **Resource/Handle:** `resource`のように"ホスト所有でクローズを要する"型を明示 + +### 性能指針 +- **ホットパス確保:** C ABI経路は関数ポインタ直叩き(`#[repr(C)]` vtable) +- **N回呼び出し禁止:** tight loop/粒度の細かいRPCは不可 +- **バッチ/ストリーミング:** 将来の`client_stream/server_stream/bidi`を型で表現 + +### エラー処理(統一モデル) +- **BoxErrorコア:** `code(u32)`, `category(enum)`, `transport(enum)`, `message`, `data(optional record)`, `retryable(bool)`, `idempotent_safe(bool)` + +### YAML BIDの拡張例 +```yaml +version: 1 +transport: + type: dynamic_library + location: ./libnyash_file.so + +interfaces: + - namespace: nyash + name: file + uuid: "c1b9...-..." # 安定ID + version: "1.0.0" + types: + - name: Handle + type: resource + methods: + - name: open + shape: unary + params: + - { name: path, type: string } + - { name: mode, type: string } + returns: { type: resource } + effects: [fs, io] + errors: [NotFound, Permission, Invalid] + idempotent: false +``` + +### 既存システムとの比較 +- **WASM Component Model (WIT):** 強力なIDL/型・言語間互換が成熟。Nyashは「同プロセスC ABI最速+後でWASM追加」を差別化軸に +- **gRPC(Protobuf):** ネットワークRPCの王道。Nyashは"ハンドルと効果"の第一級概念で優位 +- **COM/CORBA:** 位置透過・IFace/VTable思想は近いが、現代的DX/ツールが乏しい + +### セキュリティ指針 +- **ケーパビリティ必須(段階導入):** メソッド/リソース単位の権限をBIDで宣言 +- **信頼境界で実行形態を変える:** + - 信頼済み: C ABI `*.so`(最速) + - 準信頼/第三者: 別プロセス+gRPC/REST + - 非信頼: WASMサンドボックス + +## 共通見解まとめ + +1. **抽象化は適切** - UniversalConnectorトレイトは良い設計 +2. **MirValue統一は現実的** - 型変換は各Connector実装が担当 +3. **性能への影響は軽微** - 抽象化レイヤー自体のオーバーヘッドは無視できる +4. **段階的実装が鍵** - Phase 1: C ABI動的ライブラリのみ +5. **セキュリティは後回し** - 現段階では過剰設計 + +## 結論 +BIDの設計は健全で将来性がある。シンプルに始めて段階的に拡張する方針で進める。 \ No newline at end of file diff --git a/docs/予定/native-plan/issues/bid_ffi_ai_final_review_2025-08-17.md b/docs/予定/native-plan/issues/bid_ffi_ai_final_review_2025-08-17.md new file mode 100644 index 00000000..f2b8de40 --- /dev/null +++ b/docs/予定/native-plan/issues/bid_ffi_ai_final_review_2025-08-17.md @@ -0,0 +1,147 @@ +# BID-FFI統合計画 AI最終レビュー結果 (2025-08-17) + +## 参加者 +- Gemini先生(部分的 - メモリ不足でクラッシュ) +- ChatGPT先生(GPT-5) +- Claude(まとめ) + +## 🎯 総評 + +### Gemini先生 +> 全体として、この統合計画は非常に優れています。「Simple First」の原則に基づき、実績のあるFFI ABI v0を基盤とすることで、リスクを大幅に低減しつつ、将来の拡張性も確保されています。 + +### ChatGPT先生 +> 方向性は概ね妥当ですが、メモリモデルとBoxヘッダ、文字列/配列の所有権、エラーモデル、将来拡張の型とディスパッチ契約に数点の修正提案があります。 + +## 🔧 重要な修正提案 + +### 1. **ポインタサイズとアライメント** 🚨 + +**問題**: 32ビットポインタ固定は非現実的 + +**ChatGPT提案**: +```rust +// ❌ 現在の案 +ptr: i32 // 32ビット固定 + +// ✅ 修正案 +ptr: usize // プラットフォームポインタ幅 +// WASMでは32ビット、ネイティブでは64ビット +``` + +**アライメント**: +- ❌ 4バイト固定 → x86_64でf64が破綻する可能性 +- ✅ **8バイト境界保証**を推奨 + +### 2. **型システムの追加提案** 📦 + +**ChatGPT提案**: Phase 1から以下を追加 +```rust +pub enum BidType { + // 既存の型... + + // エラーと欠損表現(Phase 1から) + Optional(Box), // Option + Result(Box, Box), // Result +} +``` + +理由: エラーと欠損表現が楽になる + +### 3. **単一invoke関数方式** 🎯 + +**ChatGPT提案**: シンボル乱立を避ける +```rust +// 単一ディスパッチ関数(将来gRPC/RESTへ写せる) +extern "C" fn ny_invoke( + func_id: u32, + args_ptr: *const u8, + args_len: usize, + out_ptr: *mut u8, + out_len: *mut usize +) -> NyStatus +``` + +### 4. **所有権の明確化** 📝 + +**ChatGPT強調**: 文字列・配列の所有権ルール + +```rust +// 入力: 呼び出し側所有(借用、呼び出し中のみ有効) +// 出力: calleeがhost_allocで確保、callerがhost_freeで解放 + +// アロケータAPI +extern "C" { + fn host_alloc(size: usize, align: usize) -> *mut u8; + fn host_free(ptr: *mut u8, size: usize, align: usize); +} +``` + +### 5. **Boxヘッダーの改善** 🏗️ + +**ChatGPT提案**: 将来拡張を考慮 +```rust +#[repr(C)] +pub struct BoxHeader { + magic: u32, // "NYBX" + abi_major: u16, // バージョン管理 + abi_minor: u16, + type_id: u32, + flags: u32, // 将来のatomic等 + ref_count: u32, + field_count: u16, + reserved: u16, // 8バイトアライメント +} +``` + +## ✅ 両AIの共通見解 + +1. **FFI ABI v0準拠は適切** + - Gemini: 「極めて適切」 + - ChatGPT: 「賢明」 + +2. **段階的実装は現実的** + - Phase 1でC ABIのみは正解 + - vtable後回しも妥当 + +3. **1週間での実装は可能** + - ただし範囲を明確に限定すること + +## 📋 修正版1週間計画(ChatGPT提案) + +- **Day 1**: 仕様文書とヘッダ定義、`ny_invoke`契約確定 +- **Day 2**: Rustローダー(dlopen/dlsym)実装 +- **Day 3**: 文字列/配列マーシャリングと所有権テスト +- **Day 4**: サンプルプラグイン2種、e2eテスト +- **Day 5**: Boxヘッダ実装(8Bアライメント) +- **Day 6**: ドキュメント整備とCI +- **Day 7**: 予備日(Linux整備/微修正) + +## 🎯 結論と推奨事項 + +### 必須の修正 +1. ポインタ幅を`usize`に変更 +2. アライメントを8バイトに変更 +3. Option/Result型を最初から追加 +4. 所有権ルールを明文化 +5. 単一invoke関数方式を採用 + +### 実装順序 +1. **ターゲット**: Linux x86-64に限定(Windows/macOSは後続) +2. **スコープ**: スカラ+string/array、同期呼び出し、単一スレッド +3. **テスト**: 加算・echoサンプル+統合テスト + +### NyaMeshとの整合性 +- ChatGPT: 「TransportTypeにP2P追加は価値あり(Phase 4以降)」 +- 場所透過性の設計は適切 + +## 🚀 アクションアイテム + +1. **仕様修正**: ポインタ幅とアライメントの変更 +2. **型追加**: Option/Result型の早期導入 +3. **API設計**: 単一invoke関数と所有権ルール +4. **実装開始**: Linux x86-64限定で1週間スプリント + +--- + +**まとめ**: 両AIとも基本的な方向性を支持。ChatGPTの具体的な技術提案(ポインタ幅、アライメント、所有権)を取り入れることで、より堅実な実装が可能になる。 \ No newline at end of file diff --git a/docs/予定/native-plan/issues/phase_9_75g_0_revised_type_first_approach.md b/docs/予定/native-plan/issues/phase_9_75g_0_revised_type_first_approach.md new file mode 100644 index 00000000..11b03c9b --- /dev/null +++ b/docs/予定/native-plan/issues/phase_9_75g_0_revised_type_first_approach.md @@ -0,0 +1,278 @@ +# Phase 9.75g-0 改訂版: 型定義ファースト戦略 + +## 🎯 基本方針:型は全部、実装は段階的 + +**ユーザーの賢い指摘**:構造体の定義を最初に全部やっておけば、ビルドは楽になる! + +## 📦 Phase 1で定義する全ての型(実装は後でOK) + +```rust +// src/bid/types.rs - 全ての型を最初に定義! + +#[derive(Clone, Debug, PartialEq)] +pub enum BidType { + // === 基本型(Phase 1で実装) === + Bool, + I32, + I64, + F32, + F64, + String, // (ptr: usize, len: usize) + Bytes, // (ptr: usize, len: usize) + + // === 複合型(定義だけ、実装はPhase 2) === + Array(Box), // 配列 + List(Box), // 可変長リスト + Map(Box, Box), // キーバリューマップ + Tuple(Vec), // タプル + Record(Vec<(String, BidType)>), // 名前付きフィールド + Variant(Vec<(String, Option)>), // 列挙型 + + // === 特殊型(定義だけ、実装はPhase 2) === + Option(Box), // null許容 + Result(Box, Box), // エラー型 + Handle(String), // 不透明ハンドル + Void, // 戻り値なし + + // === 非同期型(定義だけ、実装はPhase 3) === + Future(Box), // 非同期結果 + Stream(Box), // ストリーム + + // === 拡張用(定義だけ) === + Opaque(String), // 不透明型 + Extension(String, Box), // 拡張用 +} + +// Transport層も全部定義(実装は段階的) +#[derive(Clone, Debug)] +pub enum TransportType { + // Phase 1で実装 + DynamicLibrary, + + // Phase 2で実装(定義だけ先に) + Grpc, + Rest, + WebSocket, + + // Phase 3で実装(定義だけ先に) + WasmComponent, + PythonBridge, + + // Phase 4で実装(定義だけ先に) + P2P, // NyaMesh統合 + Quantum, // 量子コンピュータ(夢) +} + +// Effect定義も完全版 +#[derive(Clone, Debug, PartialEq)] +pub enum Effect { + Pure, // 副作用なし + Mut, // 状態変更 + Io, // I/O操作 + Control, // 制御フロー + + // 将来の拡張(定義だけ) + Async, // 非同期 + Parallel, // 並列実行可 + Network, // ネットワーク + Gpu, // GPU使用 +} + +// エラー型も完全定義 +#[derive(Debug, thiserror::Error)] +pub enum BidError { + // Phase 1で実装 + #[error("Transport error: {0}")] + Transport(String), + + #[error("Type mismatch: expected {expected}, got {actual}")] + TypeMismatch { expected: String, actual: String }, + + // Phase 2で実装(定義だけ先に) + #[error("Network error: {0}")] + Network(String), + + #[error("Serialization error: {0}")] + Serialization(String), + + // Phase 3で実装(定義だけ先に) + #[error("Async error: {0}")] + Async(String), + + #[error("Language bridge error: {0}")] + LanguageBridge(String), + + // エラーカテゴリ(完全定義) + #[error("{category} error: {message}")] + Categorized { + category: ErrorCategory, + message: String, + retryable: bool, + details: Option, + }, +} + +#[derive(Debug, Clone)] +pub enum ErrorCategory { + Invalid, + NotFound, + Conflict, + Unavailable, + Timeout, + Cancelled, + Internal, + Permission, + Resource, + // 将来の拡張 + Quantum, +} + +// UniversalConnectorも完全インターフェース +pub trait UniversalConnector: Send + Sync { + fn connect(&self, bid: &BidDefinition) -> Result, BidError>; + fn supported_transport(&self) -> TransportType; + + // Phase 2で実装(デフォルト実装で逃げる) + fn handshake(&self) -> Result { + Ok(HandshakeInfo::default()) + } + + fn describe(&self) -> Result, BidError> { + Ok(vec![]) + } + + // Phase 3で実装 + fn async_connect(&self, bid: &BidDefinition) -> Result, BidError> { + unimplemented!("Async not supported yet") + } +} + +// Connection trait も完全版 +pub trait Connection: Send + Sync { + // Phase 1で実装 + fn invoke(&self, method: &str, args: &[BidValue]) -> Result; + + // Phase 2で実装(デフォルト実装) + fn invoke_async(&self, method: &str, args: &[BidValue]) -> Result { + unimplemented!("Async not supported") + } + + fn stream(&self, method: &str, args: &[BidValue]) -> Result { + unimplemented!("Streaming not supported") + } + + // Phase 3で実装 + fn batch(&self, calls: Vec<(String, Vec)>) -> Result, BidError> { + unimplemented!("Batch not supported") + } +} + +// 実装用のマクロ(Phase 1では基本型のみ実装) +impl BidType { + pub fn to_wasm_types(&self) -> Vec { + match self { + // Phase 1: これらは実装 + BidType::Bool => vec![WasmType::I32], + BidType::I32 => vec![WasmType::I32], + BidType::I64 => vec![WasmType::I64], + BidType::F32 => vec![WasmType::F32], + BidType::F64 => vec![WasmType::F64], + BidType::String => vec![WasmType::I32, WasmType::I32], + + // Phase 2以降: とりあえずpanic + _ => unimplemented!("Type {:?} not implemented yet", self), + } + } +} +``` + +## 🎯 この戦略のメリット + +1. **ビルドエラーなし** - 型は全部あるのでコンパイル通る +2. **API安定** - 最初から完全なAPIが見える +3. **段階的実装** - `unimplemented!()` から順次実装 +4. **将来の拡張が楽** - 構造体変更不要 + +## 📅 実装スケジュール + +### Phase 1(1週間) +```rust +// 実装するもの +- 基本型(Bool, I32, I64, F32, F64, String) +- DynamicLibraryコネクター +- 同期invoke()のみ +- Linux x86-64のみ + +// 実装しないもの(unimplemented!) +- 複合型(Array, Map等) +- 非同期処理 +- ネットワーク +``` + +### Phase 2(2週間後) +```rust +// 追加実装 +- Array, List, Map型 +- Option, Result型 +- エラー処理の充実 +``` + +### Phase 3(1ヶ月後) +```rust +// 非同期対応 +- Future, Stream型 +- async_connect, invoke_async +- WasmComponent対応 +``` + +### Phase 4(将来) +```rust +// 拡張機能 +- P2P(NyaMesh統合) +- 量子コンピュータ(?) +``` + +## 📝 実装例(Phase 1) + +```rust +// src/bid/connectors/dynamic_library.rs + +impl UniversalConnector for DynamicLibraryConnector { + fn connect(&self, bid: &BidDefinition) -> Result, BidError> { + // Phase 1: 実装する + let lib = unsafe { libloading::Library::new(&bid.transport.location)? }; + Ok(Box::new(DynamicLibraryConnection { lib })) + } + + fn supported_transport(&self) -> TransportType { + TransportType::DynamicLibrary + } + + // Phase 2以降: デフォルト実装のまま +} + +impl Connection for DynamicLibraryConnection { + fn invoke(&self, method: &str, args: &[BidValue]) -> Result { + // Phase 1: 基本型のみ実装 + match args[0] { + BidValue::I32(n) => { /* 実装 */ }, + BidValue::String(s) => { /* 実装 */ }, + + // Phase 2以降 + BidValue::Array(_) => unimplemented!("Array not supported yet"), + BidValue::Future(_) => unimplemented!("Future not supported yet"), + } + } +} +``` + +## ✨ まとめ + +**構造体は最初に全部定義、実装は段階的に** - これでビルドエラーなしで、APIも安定! + +ユーザーの「深く考えて」の結果:この方が絶対に楽です。将来Array型を追加するときも、構造体はもうあるので実装を書くだけ! + +--- + +**改訂日**: 2025-08-17 +**改訂理由**: 型定義ファースト戦略の採用 \ No newline at end of file diff --git a/docs/予定/native-plan/issues/phase_9_75g_0_simplified_bid_ffi_implementation.md b/docs/予定/native-plan/issues/phase_9_75g_0_simplified_bid_ffi_implementation.md new file mode 100644 index 00000000..2443d116 --- /dev/null +++ b/docs/予定/native-plan/issues/phase_9_75g_0_simplified_bid_ffi_implementation.md @@ -0,0 +1,176 @@ +# Phase 9.75g-0: 簡素化BID-FFI実装計画 + +## 🎯 目的 +FFI ABI v0準拠の**シンプルで動く**プラグインシステムを1週間で実装する。 + +## 🌟 設計方針:シンプル第一 + +### 複雑さの回避 +- ❌ 過度な抽象化(gRPC/REST/P2P等は後回し) +- ❌ 完璧な型システム(必要最小限から開始) +- ✅ **動くものを最速で作る** +- ✅ **拡張可能な基盤を作る** + +### 技術的決定事項 + +```rust +// 1. ポインタとアライメント(AIレビュー反映) +pub type Ptr = usize; // プラットフォーム依存 +pub const ALIGNMENT: usize = 8; // 8バイト境界 + +// 2. 最小限の型セット +pub enum BidType { + // 基本型(必須) + Bool, + I32, + I64, + F32, + F64, + String, // (ptr: usize, len: usize) + + // 早期追加(ChatGPT推奨) + Option(Box), + Result(Box, Box), + + // Phase 2以降 + // Array, Map, Future等 +} + +// 3. シンプルなBoxヘッダー(大きくてもOK) +#[repr(C, align(8))] +pub struct BoxHeader { + magic: u32, // "NYBX" (0x5859424E) + version: u16, // 1 + _pad: u16, // アライメント用 + type_id: u32, + ref_count: u32, // 非atomic(Phase 1) +} + +// 4. 単一エントリーポイント(ChatGPT推奨) +#[no_mangle] +extern "C" fn nyash_plugin_invoke( + method_id: u32, + args_ptr: *const u8, + args_len: usize, + result_ptr: *mut u8, + result_len: *mut usize, +) -> i32 { // 0=成功, 非0=エラー + // 実装 +} +``` + +## 📋 1週間の実装計画 + +### Day 1: 基礎定義 +- [ ] `src/bid/types.rs` - 最小型システム +- [ ] `src/bid/header.rs` - Boxヘッダー定義 +- [ ] テスト: アライメント検証 + +### Day 2: プラグインローダー +- [ ] `src/bid/loader.rs` - dlopen/dlsym +- [ ] 最小限のサンプルプラグイン(加算関数) +- [ ] テスト: ロード成功/失敗 + +### Day 3: 文字列処理 +- [ ] UTF-8文字列の受け渡し実装 +- [ ] 所有権ルール明文化 +- [ ] テスト: 日本語/絵文字/空文字列 + +### Day 4: 統合実装 +- [ ] FileBoxの最小実装(open/read/close) +- [ ] インタープリターとの接続 +- [ ] テスト: ファイル操作e2e + +### Day 5: エラー処理 +- [ ] エラーコード体系 +- [ ] Option/Result型の実装 +- [ ] テスト: 各種エラーケース + +### Day 6-7: ドキュメント・仕上げ +- [ ] 使い方ドキュメント +- [ ] Linux x86-64でのCI設定 +- [ ] 予備日(問題対応) + +## 🛠️ 実装の簡素化ポイント + +### 1. Transport層の簡素化 +```rust +// Phase 1: これだけ! +pub enum Transport { + DynamicLibrary(PathBuf), +} + +// 将来の拡張を予約(実装しない) +// Grpc(String), +// Rest(Url), +// P2P(PeerId), +``` + +### 2. 所有権の単純ルール +```rust +// 入力: 呼び出し側が所有(借用) +// 出力: プラグインがallocate、呼び出し側がfree + +extern "C" { + fn nyash_alloc(size: usize) -> *mut u8; + fn nyash_free(ptr: *mut u8); +} +``` + +### 3. バージョニングの簡素化 +```yaml +# BID定義(最小限) +version: 1 +plugin: + name: nyash-file + version: "0.1.0" + +methods: + - id: 1 + name: open + params: [string, string] + returns: i32 +``` + +## ✅ 成功基準 + +### 必須 +- [ ] Linux x86-64で動作 +- [ ] FileBoxプラグインが動く +- [ ] 文字列の受け渡しが正しい +- [ ] メモリリークなし + +### あれば良い +- [ ] Windows対応の準備 +- [ ] 性能測定 +- [ ] 複数プラグイン同時ロード + +## 🚀 この設計の利点 + +1. **シンプル**: 必要最小限の機能のみ +2. **実用的**: 1週間で確実に動く +3. **拡張可能**: 将来の機能追加が容易 +4. **保守可能**: Rust中級者が理解できる + +## ⚠️ 意図的に省略したもの + +- vtable(動的ディスパッチ) +- 非同期処理 +- ネットワーク対応 +- 複雑な型(Array, Map等) +- マルチスレッド対応 + +これらは**動くものができてから**Phase 2以降で追加します。 + +## 📝 まとめ + +「structが大きくても問題ない」というユーザーの言葉通り、Boxヘッダーは拡張性を考慮して余裕を持たせています。複雑さを避けつつ、確実に動くものを作ることに集中します。 + +**キーワード**: Simple, Practical, Extensible + +--- + +**作成日**: 2025-08-17 +**優先度**: 🔥 最高(Phase 9.75g-1の前提) +**期間**: 1週間 +**ターゲット**: Linux x86-64 \ No newline at end of file diff --git a/docs/予定/native-plan/issues/phase_9_75g_bid_ffi_abi_alignment.md b/docs/予定/native-plan/issues/phase_9_75g_bid_ffi_abi_alignment.md new file mode 100644 index 00000000..e30e21e2 --- /dev/null +++ b/docs/予定/native-plan/issues/phase_9_75g_bid_ffi_abi_alignment.md @@ -0,0 +1,352 @@ +# Phase 9.75g-0: BID-FFI ABI v0 統合仕様 + +## 🎯 概要 + +**目的**: BID(Box Interface Definition)をFFI ABI v0仕様に準拠させ、シンプルで実用的な実装を実現する + +**背景**: +- FFI ABI v0は既に確立された明確な仕様 +- BID Phase 9.75gは野心的だが過度に複雑 +- 両者の良い部分を統合し、段階的実装を可能にする + +**期間**: 1週間(Phase 9.75g-1の前に実施) + +## 📊 FFI ABI v0とBIDの差異分析 + +### 型システムの比較 + +| 項目 | FFI ABI v0 | BID (現在) | 統合案 | +|------|------------|------------|---------| +| 整数型 | i32, i64 | i64のみ | **i32, i64** | +| 浮動小数点 | f32, f64 | f64のみ | **f32, f64** | +| 文字列 | (ptr:i32, len:i32) | string(曖昧) | **string: (ptr:i32, len:i32)** | +| 配列 | array(T): (ptr, len) | 将来拡張 | **array(T): (ptr:i32, len:i32)** | +| 真偽値 | i32 (0/1) | bool | **bool: i32表現** | +| ハンドル | boxref: i32 | handle(String) | **handle: i32** | + +### メモリモデルの統一 + +```rust +// FFI ABI v0準拠のメモリレイアウト +pub struct MemoryLayout { + // ポインタサイズ: WASM MVPは32ビット + pointer_size: 32, + + // アライメント: 4バイト推奨 + alignment: 4, + + // エンディアン: リトルエンディアン + endianness: LittleEndian, + + // 文字列: UTF-8、NUL終端不要 + string_encoding: UTF8, +} +``` + +## 🛠️ 実装計画 + +### Phase 9.75g-0: FFI ABI v0準拠(新規・1週間) + +#### Day 1-2: 型システム統合 + +```rust +// src/bid/types.rs - FFI ABI v0準拠版 +#[derive(Clone, Debug, PartialEq)] +pub enum BidType { + // === 基本型(FFI ABI v0準拠) === + Bool, // i32 (0=false, 1=true) + I32, // 32ビット符号付き整数 + I64, // 64ビット符号付き整数 + F32, // IEEE 754 単精度 + F64, // IEEE 754 倍精度 + + // === 複合型 === + String, // UTF-8 (ptr:i32, len:i32) + Bytes, // バイナリ (ptr:i32, len:i32) + Array(Box), // 配列 (ptr:i32, len:i32) + + // === 特殊型 === + Handle(String), // 不透明ハンドル(i32) + Void, // 戻り値なし + + // === Phase 2以降 === + List(Box), + Map(Box, Box), + Optional(Box), + Result(Box, Box), +} + +impl BidType { + /// FFI ABI v0でのWASM表現を返す + pub fn to_wasm_types(&self) -> Vec { + match self { + BidType::Bool => vec![WasmType::I32], + BidType::I32 => vec![WasmType::I32], + BidType::I64 => vec![WasmType::I64], + BidType::F32 => vec![WasmType::F32], + BidType::F64 => vec![WasmType::F64], + BidType::String => vec![WasmType::I32, WasmType::I32], // ptr, len + BidType::Bytes => vec![WasmType::I32, WasmType::I32], // ptr, len + BidType::Array(_) => vec![WasmType::I32, WasmType::I32], // ptr, len + BidType::Handle(_) => vec![WasmType::I32], + BidType::Void => vec![], + _ => panic!("Phase 2型は未実装"), + } + } + + /// MirTypeとの相互変換 + pub fn from_mir_type(mir_type: &MirType) -> Self { + match mir_type { + MirType::Integer => BidType::I64, // Nyashのデフォルト + MirType::Float => BidType::F64, // Nyashのデフォルト + MirType::String => BidType::String, + MirType::Bool => BidType::Bool, + MirType::Box(name) => BidType::Handle(name.clone()), + _ => panic!("未対応のMirType: {:?}", mir_type), + } + } +} +``` + +#### Day 3: Effect System統合 + +```rust +// src/bid/effects.rs - FFI ABI v0準拠 +#[derive(Clone, Debug, PartialEq)] +pub enum Effect { + /// 純粋関数:再順序化可能、メモ化可能 + Pure, + + /// 可変状態:同一リソースへの操作順序を保持 + Mut, + + /// I/O操作:プログラム順序を厳密に保持 + Io, + + /// 制御フロー:CFGに影響(break, continue, return等) + Control, +} + +impl Effect { + /// MIR EffectMaskとの変換 + pub fn to_mir_effects(&self) -> EffectMask { + match self { + Effect::Pure => EffectMask::empty(), + Effect::Mut => EffectMask::MUT, + Effect::Io => EffectMask::IO, + Effect::Control => EffectMask::CONTROL, + } + } +} +``` + +#### Day 4: Box Layout標準化 + +```rust +// src/bid/layout.rs - FFI ABI v0準拠のBoxレイアウト +#[repr(C)] +pub struct BoxHeader { + type_id: i32, // Box型識別子 + ref_count: i32, // 参照カウント(Arc実装用) + field_count: i32, // フィールド数 +} + +#[repr(C)] +pub struct StringBoxLayout { + header: BoxHeader, + data_ptr: i32, // UTF-8データへのポインタ + length: i32, // 文字列長(バイト数) +} + +// レイアウト検証関数 +pub fn validate_alignment(ptr: *const u8) -> bool { + (ptr as usize) % 4 == 0 // 4バイトアライメント +} +``` + +#### Day 5: BID YAML仕様の調整 + +```yaml +# FFI ABI v0準拠のBID定義 +version: 0 # FFI ABI v0準拠を明示 + +# メモリモデル宣言(オプション、デフォルトはFFI ABI v0) +memory: + pointer_size: 32 + alignment: 4 + endianness: little + +# トランスポート層(Phase 1はシンプルに) +transport: + type: dynamic_library + location: ./libnyash_file.so + # 将来の拡張を予約 + future_transports: [grpc, rest, wasm, python_bridge] + +interfaces: + - namespace: nyash + name: file + version: "1.0.0" + + # 型定義(FFI ABI v0準拠) + types: + - name: FileHandle + type: handle + + methods: + - name: open + params: + - { name: path, type: string } # (ptr:i32, len:i32) + - { name: mode, type: string } # (ptr:i32, len:i32) + returns: { type: FileHandle } # i32 + effect: io + + - name: read + params: + - { name: handle, type: FileHandle } # i32 + - { name: size, type: i32 } # 32ビット整数 + returns: { type: bytes } # (ptr:i32, len:i32) + effect: io + + - name: write + params: + - { name: handle, type: FileHandle } # i32 + - { name: data, type: bytes } # (ptr:i32, len:i32) + returns: { type: i32 } # 書き込みバイト数 + effect: io + + - name: close + params: + - { name: handle, type: FileHandle } # i32 + returns: { type: void } + effect: io +``` + +### Phase 9.75g-1: 調整版実装(1週間) + +#### 簡素化されたUniversalConnector + +```rust +// src/bid/connector.rs - シンプル版 +pub trait UniversalConnector: Send + Sync { + /// Phase 1: dynamic_libraryのみサポート + fn connect(&self, bid: &BidDefinition) -> Result, BidError>; + + fn supported_transport(&self) -> TransportType { + TransportType::DynamicLibrary // Phase 1固定 + } +} + +// 将来の拡張ポイントを明示 +#[derive(Debug, Clone)] +pub enum TransportType { + DynamicLibrary, // Phase 1 + #[allow(dead_code)] + Grpc, // Phase 2 + #[allow(dead_code)] + Rest, // Phase 2 + #[allow(dead_code)] + WasmComponent, // Phase 3 + #[allow(dead_code)] + PythonBridge, // Phase 3 +} +``` + +#### C ABI関数シグネチャ生成 + +```rust +// src/bid/codegen/c_abi.rs +impl Method { + /// FFI ABI v0準拠のC関数シグネチャを生成 + pub fn to_c_signature(&self) -> String { + let mut params = Vec::new(); + + for param in &self.params { + match ¶m.param_type { + BidType::String => { + params.push(format!("const char* {}_ptr", param.name)); + params.push(format!("int32_t {}_len", param.name)); + } + BidType::Array(_) => { + params.push(format!("const void* {}_ptr", param.name)); + params.push(format!("int32_t {}_len", param.name)); + } + BidType::I32 => params.push(format!("int32_t {}", param.name)), + BidType::I64 => params.push(format!("int64_t {}", param.name)), + BidType::F32 => params.push(format!("float {}", param.name)), + BidType::F64 => params.push(format!("double {}", param.name)), + BidType::Bool => params.push(format!("int32_t {}", param.name)), + BidType::Handle(_) => params.push(format!("int32_t {}", param.name)), + _ => panic!("未対応の型"), + } + } + + let return_type = match &self.returns { + Some(BidType::Void) | None => "void", + Some(BidType::I32) => "int32_t", + Some(BidType::I64) => "int64_t", + Some(BidType::F32) => "float", + Some(BidType::F64) => "double", + Some(BidType::Handle(_)) => "int32_t", + _ => panic!("複合戻り値は未対応"), + }; + + format!("{} nyash_{}({})", return_type, self.name, params.join(", ")) + } +} +``` + +## 📊 成功基準 + +### Phase 9.75g-0完了時 +- [ ] FFI ABI v0の全型をBidTypeでサポート +- [ ] メモリレイアウトの明確な定義 +- [ ] Effect systemの4種類実装 +- [ ] Box layout標準の確立 +- [ ] C ABI関数シグネチャの自動生成 + +### 互換性保証 +- [ ] 既存のFileBoxがFFI ABI v0準拠で動作 +- [ ] WASM/VM/LLVMすべてで同じ型表現 +- [ ] 文字列の(ptr, len)表現が統一 + +## 🔧 実装上の注意点 + +### 1. 後方互換性の維持 +```rust +// 既存のBID定義も動作するように +if bid.version == 0 { + // FFI ABI v0準拠モード +} else { + // 将来の拡張モード +} +``` + +### 2. エラーメッセージの改善 +```rust +// 型不一致時の親切なエラー +BidError::TypeMismatch { + expected: "string (ptr:i32, len:i32)", + actual: "string (単一値)", + hint: "FFI ABI v0では文字列は(ptr, len)ペアで渡す必要があります", +} +``` + +### 3. デバッグ支援 +```rust +// BID定義の検証ツール +nyash-bid validate --ffi-abi-v0 file.bid.yaml +``` + +## 🎯 期待される成果 + +1. **明確な仕様**: FFI ABI v0準拠で曖昧さを排除 +2. **実装の簡素化**: 複雑なvtableを後回しにして基本に集中 +3. **相互運用性**: WASM/VM/LLVM/ネイティブで統一的な型表現 +4. **段階的拡張**: 基礎が固まってから高度な機能を追加 + +--- + +**作成日**: 2025-08-17 +**作成者**: Claude +**優先度**: 🔥 最高(Phase 9.75g-1の前提条件) \ No newline at end of file diff --git a/docs/予定/native-plan/issues/phase_9_75g_bid_integration_architecture.md b/docs/予定/native-plan/issues/phase_9_75g_bid_integration_architecture.md new file mode 100644 index 00000000..f3cce357 --- /dev/null +++ b/docs/予定/native-plan/issues/phase_9_75g_bid_integration_architecture.md @@ -0,0 +1,590 @@ +# Phase 9.75g: BID統合プラグインアーキテクチャ実装計画 + +## 🎯 概要 + +**目的**: ビルトインBox動的ライブラリ化とBID(Box Interface Definition)統合により、全バックエンド(インタープリター/VM/WASM/AOT)で統一的に使えるプラグインシステムを構築する。 + +**期間**: 2週間(段階的実装) + +**優先度**: 🔥 最高(VM性能改善の基盤にもなる) + +## 🌟 設計哲学(AI大会議の結論を反映) + +### 二層化アーキテクチャ +``` +┌─────────────────────────────────────────┐ +│ Nyashコード(不変) │ +├─────────────────────────────────────────┤ +│ BID層(インターフェース定義) │ +│ - 型定義、メソッドシグネチャ │ +│ - エフェクト、エラー仕様 │ +├─────────────────────────────────────────┤ +│ Connector層(実装・トランスポート) │ +│ - DynamicLibrary (.so/.dll) │ +│ - REST/gRPC(将来) │ +│ - Language Bridge(将来) │ +└─────────────────────────────────────────┘ +``` + +### 設計原則 +1. **段階的実装**: 完璧を求めず、動くものから始める +2. **最小型集合**: i64, f64, string, bool, handle から開始 +3. **コード生成**: 手書きコードを最小化、型安全性確保 +4. **粗粒度API**: tight loopを避ける設計指針 + +## 📋 実装フェーズ + +### Phase 9.75g-1: BID基盤実装(3日) + +#### 1.1 BIDパーサー実装(Day 1) +```rust +// src/bid/parser.rs +pub struct BidDefinition { + pub version: u32, + pub transport: Transport, + pub interfaces: Vec, +} + +pub struct Interface { + pub namespace: String, + pub name: String, + pub version: String, + pub methods: Vec, +} + +pub struct Method { + pub name: String, + pub params: Vec, + pub returns: Option, + pub effects: Vec, +} + +// YAMLパーサー(serde_yaml使用) +pub fn parse_bid(yaml_content: &str) -> Result { + // 実装 +} +``` + +#### 1.2 統一型システム(Day 1) +```rust +// src/bid/types.rs +#[derive(Clone, Debug)] +pub enum BidType { + // 基本型(Phase 1) + Bool, + I32, + I64, + F64, + String, + Bytes, + Handle(String), // resource + + // 将来の拡張用 + List(Box), + Map(Box, Box), + Optional(Box), + Result(Box, Box), +} + +// MirValueとの相互変換 +impl BidType { + pub fn to_mir_type(&self) -> MirType { + match self { + BidType::I64 => MirType::Integer, + BidType::F64 => MirType::Float, + BidType::String => MirType::String, + BidType::Bool => MirType::Bool, + BidType::Handle(name) => MirType::Box(name.clone()), + _ => todo!("Phase 2で実装") + } + } +} +``` + +#### 1.3 UniversalConnectorトレイト(Day 2) +```rust +// src/bid/connector.rs +pub trait UniversalConnector: Send + Sync { + /// BID定義から接続を確立 + fn connect(&self, bid: &BidDefinition) -> Result, BidError>; + + /// サポートするトランスポートタイプ + fn supported_transport(&self) -> TransportType; +} + +pub trait Connection: Send + Sync { + /// インターフェースのvtableを取得(高速パス用) + fn get_vtable(&self, interface: &str) -> Option; + + /// 汎用呼び出し(リモート/ブリッジ用) + fn invoke(&self, + interface: &str, + method: &str, + args: &[BidValue] + ) -> Result; +} +``` + +#### 1.4 統一エラーモデル(Day 2) +```rust +// src/bid/error.rs +use thiserror::Error; + +#[derive(Error, Debug)] +pub enum BidError { + #[error("Transport error: {0}")] + Transport(String), + + #[error("Interface error in {interface}: {message}")] + Interface { interface: String, message: String }, + + #[error("Method not found: {interface}.{method}")] + MethodNotFound { interface: String, method: String }, + + #[error("Type mismatch: expected {expected}, got {actual}")] + TypeMismatch { expected: String, actual: String }, + + #[error("Remote execution error: {0}")] + Remote(String), + + // カテゴリー別エラー(ChatGPT提案) + #[error("{category} error: {message}")] + Categorized { + category: ErrorCategory, + message: String, + retryable: bool, + }, +} + +#[derive(Debug)] +pub enum ErrorCategory { + Invalid, + NotFound, + Conflict, + Unavailable, + Timeout, + Cancelled, + Internal, + Permission, + Resource, +} +``` + +### Phase 9.75g-2: C ABI動的ライブラリConnector(3日) + +#### 2.1 DynamicLibraryConnector実装(Day 3) +```rust +// src/bid/connectors/dynamic_library.rs +pub struct DynamicLibraryConnector { + library_cache: Mutex>>, +} + +impl UniversalConnector for DynamicLibraryConnector { + fn connect(&self, bid: &BidDefinition) -> Result, BidError> { + let path = &bid.transport.location; + + // ライブラリをロード + let library = unsafe { + Library::new(path) + .map_err(|e| BidError::Transport(format!("Failed to load {}: {}", path, e)))? + }; + + // バージョンチェック + let version_fn: Symbol u32> = unsafe { + library.get(b"nyash_bid_version\0")? + }; + + let version = unsafe { version_fn() }; + if version != bid.version { + return Err(BidError::Transport(format!( + "Version mismatch: expected {}, got {}", + bid.version, version + ))); + } + + Ok(Box::new(DynamicLibraryConnection { + library: Arc::new(library), + bid: bid.clone(), + })) + } +} +``` + +#### 2.2 高速vtableパス(Day 4) +```rust +// src/bid/vtable.rs +#[repr(C)] +pub struct InterfaceVTable { + pub version: u32, + pub interface_id: [u8; 16], // UUID + pub method_count: u32, + pub methods: *const MethodEntry, +} + +#[repr(C)] +pub struct MethodEntry { + pub name: *const c_char, + pub function: *const c_void, + pub param_count: u32, + pub param_types: *const BidTypeId, + pub return_type: BidTypeId, +} + +// 使用例(FileBox) +impl DynamicLibraryConnection { + fn get_vtable(&self, interface: &str) -> Option { + // シンボル名: nyash_{interface}_vtable + let symbol_name = format!("nyash_{}_vtable\0", interface); + + let vtable_ptr: Symbol<*const InterfaceVTable> = unsafe { + self.library.get(symbol_name.as_bytes()).ok()? + }; + + Some(unsafe { (*vtable_ptr).clone() }) + } +} +``` + +#### 2.3 FileBoxプラグイン移植(Day 5) +```rust +// plugins/nyash-file/src/lib.rs +use nyash_bid::*; + +// C ABI関数 +#[no_mangle] +pub extern "C" fn nyash_bid_version() -> u32 { + 1 +} + +#[no_mangle] +pub static NYASH_FILE_VTABLE: InterfaceVTable = InterfaceVTable { + version: 1, + interface_id: *b"nyash.file.v1.0\0", + method_count: 4, + methods: &FILE_METHODS as *const _, +}; + +static FILE_METHODS: [MethodEntry; 4] = [ + MethodEntry { + name: b"open\0" as *const _ as *const c_char, + function: nyash_file_open as *const _, + param_count: 2, + param_types: &[BidTypeId::String, BidTypeId::String] as *const _, + return_type: BidTypeId::Handle, + }, + // read, write, close... +]; + +// 実装 +#[no_mangle] +pub extern "C" fn nyash_file_open( + path: *const c_char, + mode: *const c_char, +) -> *mut FileHandle { + // 既存のFileBox実装を再利用 +} +``` + +### Phase 9.75g-3: インタープリター統合(2日) + +#### 3.1 BIDローダー統合(Day 6) +```rust +// src/interpreter/bid_loader.rs +pub struct BidPluginLoader { + connectors: HashMap>, + connections: HashMap>, +} + +impl BidPluginLoader { + pub fn new() -> Self { + let mut connectors = HashMap::new(); + + // Phase 1: 動的ライブラリのみ + connectors.insert( + TransportType::DynamicLibrary, + Box::new(DynamicLibraryConnector::new()), + ); + + Self { + connectors, + connections: HashMap::new(), + } + } + + pub fn load_bid(&mut self, yaml_path: &str) -> Result<(), BidError> { + let content = fs::read_to_string(yaml_path)?; + let bid = parse_bid(&content)?; + + // 適切なコネクターを選択 + let connector = self.connectors + .get(&bid.transport.transport_type) + .ok_or_else(|| BidError::Transport( + format!("Unsupported transport: {:?}", bid.transport.transport_type) + ))?; + + // 接続を確立 + let connection = connector.connect(&bid)?; + + // インターフェースごとに登録 + for interface in &bid.interfaces { + let key = format!("{}.{}", interface.namespace, interface.name); + self.connections.insert(key, connection.clone()); + } + + Ok(()) + } +} +``` + +#### 3.2 既存コードとの互換性層(Day 7) +```rust +// src/interpreter/objects.rs の修正 +impl NyashInterpreter { + fn execute_new(&mut self, class: &str, args: Vec>) + -> Result, RuntimeError> + { + // 既存のビルトインBox処理 + if is_builtin_box(class) { + // 従来の処理... + } + + // BIDプラグインチェック + if let Some(connection) = self.bid_loader.get_connection(class) { + // BID経由で作成 + let bid_args: Vec = args.iter() + .map(|arg| nyash_to_bid_value(arg)) + .collect::>()?; + + let result = connection.invoke(class, "new", &bid_args)?; + + return Ok(bid_to_nyash_box(result)?); + } + + // ユーザー定義Box + // 従来の処理... + } +} +``` + +### Phase 9.75g-4: MIR/VM統合(3日) + +#### 4.1 ExternCall命令とBID統合(Day 8) +```rust +// src/mir/builder.rs の修正 +impl MirBuilder { + fn build_method_call(&mut self, object: ASTNode, method: String, args: Vec) + -> Result + { + // オブジェクトの型を解析 + let obj_type = self.infer_type(&object)?; + + // BIDプラグインメソッドかチェック + if let Some(bid_interface) = self.bid_registry.get_interface(&obj_type) { + // ExternCall命令を生成 + let dst = self.value_gen.next(); + self.emit_instruction(MirInstruction::ExternCall { + dst: Some(dst), + iface_name: bid_interface.name.clone(), + method_name: method, + args: arg_values, + effects: bid_interface.get_method_effects(&method), + })?; + + return Ok(dst); + } + + // 通常のBoxCall + // 従来の処理... + } +} +``` + +#### 4.2 VM実行時BID呼び出し(Day 9) +```rust +// src/backend/vm.rs の修正 +impl VM { + fn execute_extern_call(&mut self, + dst: Option, + iface: &str, + method: &str, + args: &[ValueId], + effects: &EffectMask, + ) -> Result<(), VMError> { + // BID接続を取得 + let connection = self.bid_loader + .get_connection(iface) + .ok_or_else(|| VMError::InterfaceNotFound(iface.to_string()))?; + + // 引数をBidValueに変換 + let bid_args: Vec = args.iter() + .map(|id| self.vm_to_bid_value(*id)) + .collect::>()?; + + // 高速パスチェック(vtable利用可能か) + if let Some(vtable) = connection.get_vtable(iface) { + // 直接関数ポインタ呼び出し(最速) + let result = unsafe { + call_vtable_method(&vtable, method, &bid_args)? + }; + + if let Some(dst_id) = dst { + self.set_value(dst_id, bid_to_vm_value(result)?); + } + } else { + // 汎用invoke経路(リモート対応) + let result = connection.invoke(iface, method, &bid_args)?; + + if let Some(dst_id) = dst { + self.set_value(dst_id, bid_to_vm_value(result)?); + } + } + + Ok(()) + } +} +``` + +### Phase 9.75g-5: コード生成ツール(2日) + +#### 5.1 BIDからRustスタブ生成(Day 10) +```bash +# CLIツール +nyash-bid-gen --input file.bid.yaml --output src/generated/ +``` + +生成されるコード例: +```rust +// src/generated/nyash_file.rs +pub struct FileBoxClient { + connection: Arc, +} + +impl FileBoxClient { + pub fn open(&self, path: &str, mode: &str) -> Result { + let args = vec![ + BidValue::String(path.to_string()), + BidValue::String(mode.to_string()), + ]; + + let result = self.connection.invoke("nyash.file", "open", &args)?; + + match result { + BidValue::Handle(h) => Ok(FileHandle(h)), + _ => Err(BidError::TypeMismatch { + expected: "handle".to_string(), + actual: format!("{:?}", result), + }), + } + } +} +``` + +#### 5.2 プラグイン側スケルトン生成(Day 11) +```rust +// 生成されるプラグイン側のスケルトン +pub trait FileBoxImpl { + fn open(&self, path: &str, mode: &str) -> Result; + fn read(&self, handle: &FileHandle, size: usize) -> Result, FileError>; + fn write(&self, handle: &FileHandle, data: &[u8]) -> Result; + fn close(&self, handle: FileHandle) -> Result<(), FileError>; +} + +// C ABIラッパーも自動生成 +#[no_mangle] +pub extern "C" fn nyash_file_open( + path: *const c_char, + mode: *const c_char, +) -> *mut c_void { + // 実装への橋渡し +} +``` + +## 📊 テスト計画 + +### 統合テスト(Day 12) +```nyash +// test_bid_integration.nyash +using nyashstd + +// BIDプラグインのロード +bid.load("plugins/file.bid.yaml") + +// 通常のNyashコードで使用(透過的) +local file = new FileBox("test.txt", "w") +file.write("Hello from BID!") +file.close() + +// 性能測定 +local timer = new TimerBox() +timer.start() + +local i = 0 +loop(i < 1000) { + local f = new FileBox("bench.txt", "r") + f.read(1024) + f.close() + i = i + 1 +} + +timer.stop() +console.log("1000 file operations: " + timer.elapsed() + "ms") +``` + +### ベンチマーク目標 +- C ABI直接呼び出し: < 100ns オーバーヘッド +- 型変換コスト: < 50ns(基本型) +- メモリ効率: 既存実装と同等以下 + +## 🎯 成功基準 + +### Phase 9.75g完了時 +- [ ] BIDパーサー・型システム・エラーモデル完成 +- [ ] DynamicLibraryConnector完全動作 +- [ ] FileBoxがBID経由で動作 +- [ ] インタープリター/VM/WASMすべてで同じBIDが使える +- [ ] コード生成ツール基本機能 +- [ ] 性能目標達成(< 100ns オーバーヘッド) + +### 将来の拡張準備 +- [ ] Transport抽象化の拡張ポイント確保 +- [ ] ストリーミング/非同期の設計考慮 +- [ ] セキュリティ拡張ポイント予約 + +## 🔧 実装の鍵 + +### 1. 段階的アプローチ +- 完璧を求めない +- 動くものから始める +- フィードバックを早く得る + +### 2. 既存資産の活用 +- FileBoxProxyの実装を再利用 +- 既存のプラグインローダーと共存 + +### 3. 性能最優先 +- C ABI高速パスを最初に実装 +- 型変換を最小化 +- ゼロコピーを目指す + +### 4. 開発者体験 +- コード生成で型安全性 +- エラーメッセージの充実 +- デバッグ支援機能 + +## 📅 マイルストーン + +- **Week 1**: BID基盤 + C ABIコネクター + FileBox移植 +- **Week 2**: インタープリター/VM統合 + コード生成 + テスト + +## 🚀 期待される成果 + +1. **統一プラグインシステム**: 全バックエンドで同じプラグインが動く +2. **ビルド時間改善**: 動的ライブラリ化で2分→15秒 +3. **将来の拡張性**: REST/gRPC/Python等への道筋 +4. **VM性能改善の基盤**: BID経由のプロファイリング・最適化 + +--- + +**作成**: 2025-08-17 +**作成者**: Claude (AI大会議の結論を統合) +**優先度**: 🔥 最高(VM性能改善の前提) \ No newline at end of file diff --git a/dump.txt b/dump.txt new file mode 100644 index 00000000..0e9b2a07 --- /dev/null +++ b/dump.txt @@ -0,0 +1,13 @@ +🚀 Nyash MIR Compiler - Processing file: local_tests/test_simple_string.nyash 🚀 +🚀 MIR Output for local_tests/test_simple_string.nyash: +; MIR Module: main + +define void @main() { +bb0: + 0: safepoint + 1: %0 = const "Hello" + 2: %1 = ref_new %0 + 3: ret %1 +} + + diff --git a/local_tests/bid_design_consultation.txt b/local_tests/bid_design_consultation.txt new file mode 100644 index 00000000..ac83a9d3 --- /dev/null +++ b/local_tests/bid_design_consultation.txt @@ -0,0 +1,73 @@ +Nyashプログラミング言語のBID(Box Interface Definition)設計についてご相談です。 + +【背景】 +Nyashは「Everything is Box」哲学のプログラミング言語で、現在Phase 9.75fでビルトインBoxの動的ライブラリ化とBID統合プラグインアーキテクチャを実装中です。 + +【現在の設計案】 +1. 基本BID定義(YAML形式) +```yaml +version: 1 +transport: + type: dynamic_library # 将来: grpc, rest, wasm, python_bridge等 + location: ./libnyash_file.so + +interfaces: + - name: nyash.file + box: FileBox + methods: + - name: open + params: [{string: path}, {string: mode}] + returns: handle + effect: io +``` + +2. 統一接続層(Rust実装) +```rust +trait UniversalConnector { + fn connect(&self, bid: &BidDefinition) -> Result; +} + +// 各種コネクター実装 +struct DynamicLibraryConnector; // C ABI/.so +struct GrpcConnector; // リモートサービス +struct PythonBridgeConnector; // Python統合 +``` + +3. 将来の接続先 +- 他言語ライブラリ(Python/JS/Go/Java) +- リモートサービス(REST/GraphQL/gRPC) +- システムリソース(GPU/DB/MQ) +- 未来技術(量子コンピューター等) + +【設計の狙い】 +- Protocol Agnostic: トランスポート層を抽象化 +- Location Transparent: ローカル/リモート透過的 +- Future Proof: 新技術追加が容易 +- Nyashコード不変: どんなバックエンドでも同じコード + +【懸念点と質問】 +1. **複雑性**: Transport抽象化は過度に複雑でしょうか?最初はC ABIのみに絞るべき? + +2. **型システム**: MirValueでの統一は現実的?各バックエンドの型差異をどう吸収? + +3. **性能**: 抽象化レイヤーのオーバーヘッドは許容範囲?特にタイトループでの呼び出し。 + +4. **エラー処理**: 異なるトランスポート(ローカル/ネットワーク)のエラーを統一的に扱える? + +5. **段階的実装**: 以下の順序は妥当? + - Phase 1: C ABI動的ライブラリのみ + - Phase 2: REST/gRPC追加 + - Phase 3: 言語ブリッジ(Python等) + - Phase 4: 汎用化 + +6. **既存システムとの比較**: + - WASM Component Model + - gRPC + - COM/CORBA + これらと比較してBIDの独自価値は? + +7. **セキュリティ**: Capability-based securityは必要?それとも過剰設計? + +実装者(Rust中級者)が理解・保守できる範囲で、将来の拡張性を確保する最適なバランスはどこでしょうか? + +プログラミング言語設計とFFI/プラグインシステムの専門的観点から、アドバイスをお願いします。 \ No newline at end of file diff --git a/local_tests/bid_ffi_final_review.txt b/local_tests/bid_ffi_final_review.txt new file mode 100644 index 00000000..e0490f3b --- /dev/null +++ b/local_tests/bid_ffi_final_review.txt @@ -0,0 +1,80 @@ +Nyashプログラミング言語のBID-FFI ABI v0統合計画について、最終レビューをお願いします。 + +【背景】 +- Phase 9.75g BID(Box Interface Definition)が野心的すぎて複雑 +- 既存のFFI ABI v0仕様はシンプルで実績がある +- 両者を統合し、段階的に実装可能な設計にしたい + +【統合計画の要点】 + +1. **Phase 9.75g-0: FFI ABI v0準拠(1週間)** + - 型システム完全化:i32, i64, f32, f64, bool, string, array(T) + - メモリモデル明確化:32ビットポインタ、4バイトアライメント + - Effect system:pure/mut/io/controlの4種類 + - Box layout標準化:[type_id:i32][ref_count:i32][field_count:i32] + +2. **実装の簡素化戦略** + ```rust + // Phase 1: C ABIのみ + pub enum TransportType { + DynamicLibrary, // 最初はこれだけ + #[allow(dead_code)] + Grpc, // Phase 2で追加 + Rest, // Phase 2で追加 + WasmComponent, // Phase 3で追加 + } + ``` + +3. **文字列・配列の統一表現** + ```rust + // FFI ABI v0準拠 + BidType::String => vec![WasmType::I32, WasmType::I32], // (ptr, len) + BidType::Array(_) => vec![WasmType::I32, WasmType::I32], // (ptr, len) + ``` + +4. **段階的拡張パス** + - Phase 1: ローカルC ABI(.so/.dll)のみ + - Phase 2: ネットワーク対応(gRPC/REST) + - Phase 3: 言語ブリッジ(Python等) + - Phase 4: 未来技術対応(量子等) + +【設計原則】 +- **Simple First**: 動くものを最速で作る +- **FFI ABI v0互換**: 実績ある仕様に準拠 +- **拡張可能**: TransportTypeで将来対応を予約 +- **Everything is Box**: Nyash哲学を維持 + +【質問】 + +1. **FFI ABI v0準拠は適切か?** + - 型システムの統合方針は妥当か? + - メモリモデル(32ビット、4バイトアライメント)は現実的か? + - WASMとネイティブの両対応は可能か? + +2. **段階的実装は現実的か?** + - Phase 1でC ABIのみに絞るのは賢明か? + - vtableを後回しにして基本型のみから始めるのは? + - 1週間でFFI ABI v0準拠は達成可能か? + +3. **拡張性は確保されているか?** + - UniversalConnectorトレイトは将来のgRPC/REST対応に十分か? + - BidTypeは将来の複雑な型(Future/Stream等)に対応できるか? + - エラーモデルは異なるトランスポートに対応可能か? + +4. **実装の落とし穴は?** + - 文字列の(ptr, len)表現で注意すべき点は? + - Box layoutのプラットフォーム依存性は? + - 既存のNyashコードとの互換性維持は? + +5. **NyaMesh(P2Pライブラリ)との整合性** + - 将来P2P通信もBIDで統一できるか? + - TransportTypeにP2Pを追加する価値は? + - 場所透過性の設計は適切か? + +【期待する成果】 +- 1週間で動くC ABIプラグインシステム +- WASM/VM/LLVMすべてで同じBIDが使える +- 将来のネットワーク対応への明確な道筋 +- Everything is Box哲学の技術的実現 + +実装者(Rust中級者)が理解でき、確実に動作し、将来拡張可能な設計になっているか、専門的観点からレビューをお願いします。 \ No newline at end of file diff --git a/local_tests/mir_output.txt b/local_tests/mir_output.txt new file mode 100644 index 00000000..dc26e786 --- /dev/null +++ b/local_tests/mir_output.txt @@ -0,0 +1,15 @@ +🚀 Nyash MIR Compiler - Processing file: local_tests/test_simple_string.nyash 🚀 +🔍 build_new_expression: class=StringBox, arguments=[Literal { value: String("Hello"), span: Span { start: 0, end: 0, line: 1, column: 1 } }] +🔍 build_new_expression: StringBox with literal string: "Hello" +🚀 MIR Output for local_tests/test_simple_string.nyash: +; MIR Module: main + +define void @main() { +bb0: + 0: safepoint + 1: %0 = const "Hello" + 2: %1 = ref_new %0 + 3: ret %1 +} + + diff --git a/local_tests/trace_mir_gen.nyash b/local_tests/trace_mir_gen.nyash new file mode 100644 index 00000000..3076e2ce --- /dev/null +++ b/local_tests/trace_mir_gen.nyash @@ -0,0 +1,6 @@ +// Trace MIR generation +static box Main { + main() { + print("Hello") + } +} \ No newline at end of file