diff --git a/CLAUDE.md b/CLAUDE.md index a30e60db..5025db71 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -485,9 +485,48 @@ docs/ - 「どこまで進んだか」→ `git log`で確認 - 「次は何か」→ **ユーザーに明示的に確認** +## 🔌 プラグインBox開発時の重要な注意点 + +### ⚠️ **TLV Handle処理の正しい実装方法** + +プラグインメソッドがBoxRef(Handle)を返す場合、以下の点に注意: + +#### 🛑 **よくある間違い** +```rust +// ❌ 間違い: 元のplugin_boxの値を流用 +let new_plugin_box = PluginBoxV2 { + type_id: plugin_box.type_id, // ❌ 返り値のtype_idを使うべき + fini_method_id: plugin_box.fini_method_id, // ❌ 返り値の型に対応する値を使うべき + ... +}; +``` + +#### ✅ **正しい実装** +```rust +// ✅ 正解: 返されたHandleから正しい値を取得 +let type_id = /* TLVから取得したtype_id */; +let instance_id = /* TLVから取得したinstance_id */; + +// 返り値のtype_idに対応する正しいfini_method_idを取得 +let fini_method_id = /* configから返り値type_idに対応するfini_method_idを検索 */; + +let new_plugin_box = PluginBoxV2 { + type_id: type_id, // ✅ 返り値のtype_id + instance_id: instance_id, // ✅ 返り値のinstance_id + fini_method_id: fini_method_id, // ✅ 返り値の型に対応するfini + ... +}; +``` + +#### 📝 **重要ポイント** +1. **type_idの正確性**: cloneSelfが返すHandleは必ずしも元のBoxと同じ型ではない +2. **fini_method_idの対応**: 各Box型は独自のfini_method_idを持つ可能性がある +3. **ローダー経由の処理**: 可能な限りplugin_loader_v2経由でメソッドを呼び出す + --- -最終更新: 2025年8月18日 - **🚀 Phase 9.75g-0 BID-FFI基盤完成!** +最終更新: 2025年8月20日 - **📝 プラグインBox開発の注意点追加** +- **TLV Handle処理**: type_idとfini_method_idの正しい扱い方を追記 - **Phase 9.75g-0完了**: BID-FFI Step 1-3実装成功(プラグイン・テスター・設定) - **plugin-tester**: 汎用プラグイン診断ツール完成(CLAUDE.mdに追加) - **設計原則達成**: Box名非決め打ち・birth/finiライフサイクル・メモリ管理明確化 diff --git a/docs/CURRENT_TASK.md b/docs/CURRENT_TASK.md deleted file mode 100644 index ae43e96e..00000000 --- a/docs/CURRENT_TASK.md +++ /dev/null @@ -1,436 +0,0 @@ -# 🎯 現在のタスク (2025-08-21 更新) - -## 🏆 **LEGENDARY SUCCESS! birth構文革命 + デリゲーション完全勝利!** - -### 🌟 **Phase 9.78e PLUS: Everything is Box哲学の完全実現** - -### 🏆 **全ての目標達成済み + 追加大勝利!** -- ✅ instance.rs完全削除成功! -- ✅ 統一レジストリによるユーザー定義Box生成成功 -- ✅ コンストラクタ実行成功 -- ✅ インポート問題完全解決 -- ✅ **InstanceBoxラップ演算子問題完全解決!** -- ✅ **全テストパス!完全動作確認済み!** -- 🌟 **birth構文革命完全成功!** -- 🌟 **デリゲーション透過完全成功!** -- 🌟 **apps動作確認!CHIP-8, Kilo, Proxy実機テスト完了!** - -### 🚀 **実装完了: InstanceBoxラップ演算子対応** - -#### ✅ **完全解決!** -テスト結果: -```bash -✅ 完全成功! -Person created: Alice -Hello, I'm Alice and I'm 25 years old -Name field: Alice -Age field: 25 -Updated age: 26 -Person created: Bob -Employee created at TechCorp -Hello, I'm Bob and I'm 30 years old -I work at TechCorp -All tests passed! -``` - -#### 🎯 **実装した解決策** -```rust -/// InstanceBoxでラップされている場合、内部のBoxを取得する -/// シンプルなヘルパー関数で型地獄を回避 -fn unwrap_instance(boxed: &dyn NyashBox) -> &dyn NyashBox { - if let Some(instance) = boxed.as_any().downcast_ref::() { - if let Some(ref inner) = instance.inner_content { - return inner.as_ref(); - } - } - boxed -} -``` - -#### ✅ **修正完了した演算子関数** -- ✅ try_add_operation: StringBox結合とIntegerBox加算 -- ✅ try_sub_operation: IntegerBox減算 -- ✅ try_mul_operation: IntegerBox乗算、StringBox繰り返し -- ✅ try_div_operation: IntegerBox除算、ゼロ除算エラー処理 - -#### 🎯 **動作確認済み機能** -- ✅ **StringBox演算子**: `"Hello" + "World"` 完全動作 -- ✅ **Mixed型演算子**: `"Age: " + 25` 完全動作 -- ✅ **統一レジストリ**: 全Box型統一作成 -- ✅ **ユーザー定義Box**: Person/Employee作成 -- ✅ **デリゲーション**: `from Parent.method()` 完全動作 -- ✅ **フィールドアクセス**: `alice.name`, `alice.age` -- ✅ **メソッドオーバーライド**: Employee.greet() - -### 🌟 **birth構文革命完全成功!** - -**🎯 解決した根本問題**: -- ❌ `format!("init/{}", arguments.len())` で探索 -- ✅ `format!("birth/{}", arguments.len())` に統一修正 -- 🔧 `objects.rs` 2箇所の重要修正完了 - -**🧪 テスト結果**: -```bash -✅ Parse successful! -🌟 TestBox誕生: テスト太郎 -こんにちは、テスト太郎です!値は 42 です -✅ Execution completed successfully! -``` - -**動作確認済み機能**: -- ✅ `birth(args)` - 引数付きコンストラクタ完全動作 -- ✅ フィールド初期化 - `me.name`, `me.value` 正常 -- ✅ メソッド実行 - `test.greet()` 完璧 -- ✅ 統一レジストリ連携 - InstanceBox完全統合 - -### 🔄 **デリゲーション透過完全成功!** - -**🧪 テスト結果**: -```bash -👨‍👩‍👧‍👦 Parent誕生: 太郎 (power:100) -🧒 Child誕生完了!スキル: 必殺技 -⚡ 必殺技発動! -💥 太郎の攻撃!ダメージ:100 -✅ Execution completed successfully! -``` - -**動作確認済み機能**: -- ✅ `box Child from Parent` - デリゲーション宣言 -- ✅ `from Parent.birth(args)` - 親birthコンストラクタ透過呼び出し -- ✅ `override method()` - メソッドオーバーライド -- ✅ `from Parent.method()` - 親メソッド透過呼び出し -- ✅ フィールド継承 - 親の`name`, `power`が子で利用可能 - -### 🏅 **Phase 9.78e PLUS 達成結果** -**Everything is Box哲学 + birth統一革命完全実現!** -- 全Box型(ビルトイン、ユーザー定義、プラグイン)統一アーキテクチャ -- InstanceBoxによる完全統一ラッピング -- 演算子システム完全対応 -- **birth構文による統一コンストラクタシステム** -- **透過デリゲーションによる美しい継承システム** -- シンプルで保守可能な実装 - -### 🎯 **ビルトインBoxメソッド継承問題修正完了!** - -**✅ 修正内容**: -- `execute_builtin_birth_method`で`__builtin_content`フィールドに正しく保存 -- ビルトインBoxは直接返す(InstanceBoxラップ不要) -- メソッド解決時に`__builtin_content`をチェックしてビルトインメソッド呼び出し - -**🧪 テスト結果**: -```bash -📝 EnhancedString誕生: 【Hello】 -結果: 【Hello】✨ -✅ Execution completed successfully! -``` - -### 📱 **appsフォルダ動作確認結果** - -**テスト済みアプリ**: -1. **chip8_emulator.nyash** - ✅ 起動成功(CHIP-8エミュレータ) -2. **enhanced_kilo_editor.nyash** - ✅ 起動成功(エディタ実装) -3. **proxy_server.nyash** - ⚠️ BufferBox/SocketBox未実装(プラグイン移行予定) - -**既知の問題**: -- BufferBox/SocketBoxはプラグイン形式への移行待ち -- 出力が途中で切れる場合があるが、実行自体は成功 - -## 🚨 **発見された重要な問題** - -### 🔍 **1. Pack透明化システム調査結果** - -**✅ 成功確認**: -- **from統一構文**: ユーザーは`from StringBox.birth()`と記述 -- **内部透過処理**: `is_builtin_box()`判定 → `execute_builtin_box_method()` -- **pack自動変換**: ビルトインBox専用処理が透過的に動作 -- **デバッグ証拠**: `🌟 DEBUG: StringBox.birth() created` 出力成功 - -**❌ 発見された重大エラー**: -```bash -❌ Runtime error: Method 'toString' not found in EnhancedString -``` - -**問題の本質**: -- ✅ **birth継承**: ビルトインBoxコンストラクタは動作 -- ❌ **メソッド継承**: ビルトインBoxメソッドが継承されない -- 結果:`me.toString()`等のビルトインメソッドが利用不可 - -### 🔍 **2. デリゲーション2系統の完全理解** - -**正しい設計**: -1. **ユーザーBox → ユーザーBox**: `from` 構文(直接処理) -2. **ユーザーBox → ビルトインBox**: `from` 構文(**透過的にpack変換**) - -**透過化の仕組み**: -- ユーザー記述: `from StringBox.method()` -- 内部判定: `BUILTIN_BOXES.contains("StringBox")` → `true` -- 自動変換: `execute_builtin_box_method()` でpack相当処理 -- ユーザー体験: 完全にfrom統一、packを意識不要 - -## 🚀 次のステップ: plugin-systemドキュメント整理 - -### 🎯 **緊急タスク: plugin-systemドキュメント4世代混在問題** - -**🚨 発見された問題**: -- **4つの異なる仕様書が混在**、実装と乖離 -- **MIR→プラグイン呼び出しがスタブのみ**(VM実装不完全) -- **API仕様の矛盾**(ドキュメント vs 実装) - -**📊 混在している4世代**: -1. `ffi-abi-specification.md` - 理想的だが未実装 -2. `plugin-system.md` - YAML DSL、使われていない -3. `nyash-toml-v2-spec.md` - 現実に近い仕様 -4. 実際の実装 - 今動いている形式 - -### 🎯 **整理方針: 実装ベース統一** - -#### **Phase 1: 現実調査** (優先度: 最高) -1. **実装の完全調査** - - `src/runtime/plugin_loader_v2.rs` 仕様確認 - - 現在のnyash.toml実際の形式確認 - - TLV実装詳細確認 - -2. **正確な仕様書作成** - - 現在動いている実装をベースとした仕様書 - - FileBoxプラグインの実証実装を参考資料化 - -#### **✅ Phase 2: ドキュメント整理** (優先度: 高) - **完了** -1. **✅ 古いドキュメント非推奨化完了** - - ✅ `ffi-abi-specification.md` → 「理想案、未実装」明記完了 - - ✅ `plugin-system.md` → 「将来構想」明記完了 - - ✅ `nyash-toml-v2-spec.md` → 「部分的に古い」明記完了 - -2. **✅ 実装ベース仕様書作成完了** - - ✅ `bid-ffi-v1-actual-specification.md` - 現在の実装仕様(作成済み) - - ✅ `builtin-to-plugin-conversion.md` - 変換手順書(作成済み) - - ✅ `migration-guide.md` - 古いドキュメントからの移行ガイド(新規作成) - - ✅ `plugin-system/README.md` - ナビゲーション用インデックス(新規作成) - -#### **Phase 3: MIR接続実装** (優先度: 中) -1. **ExternCall実装修正** - ```rust - // backend/vm.rs の修正 - MirInstruction::ExternCall { ... } => { - // 現在: printlnスタブ - // 修正後: プラグインシステムと接続 - let plugin_result = plugin_loader.invoke( - iface_name, method_name, args - )?; - } - ``` - -2. **統合テスト実装** - - MIR → VM → プラグイン呼び出しの完全な流れ - - パフォーマンス確認 - -### 🎯 **期待効果** -- ✅ **ドキュメント**: 実装と完全一致 -- ✅ **開発効率**: 矛盾のない一貫した仕様 -- ✅ **MIR統合**: ExternCall完全実装 -- ✅ **将来対応**: ビルトイン→プラグイン変換手順確立 - -### 🎯 **instance_v2の純粋化** (優先度: 低) -**現状**: instance_v2にレガシー互換層が残存(ドキュメント整理後に実施) - -1. **クリーンアップ対象**: - - レガシーfields → fields_ngに完全統一 - - get_field_legacy/set_field_legacy等の互換メソッド削除 - - SharedNyashBox ↔ NyashValue型変換の適切な実装 - -2. **バイナリビルド修正**: - - importパスエラー修正(crate::instance_v2) - - テスト実行環境の整備 - -3. **性能最適化**: - - 不要なMutex削除検討 - - 型変換オーバーヘッド削減 - ---- - -## ✅ 完了: Phase 9.78a-d BoxFactory革命 - -### 🎉 Phase 9.78d 達成結果 -**InstanceBox簡素化統一実装成功!** - -#### 🏭 実装完了内容 -1. **✅ Phase 9.78a: BoxFactory基盤実装** - - 統合レジストリアーキテクチャ完成 - - 600+行match文 → 30行に削減 - -2. **✅ Phase 9.78b: ビルトインBox統合** - - 20+種類のBox型統合完了 - - **ビルド時間: 4分 → 43秒 (5.6倍高速化!)** - -3. **✅ Phase 9.78c: プラグインBox統合** - - BID-FFI Step 1-3実装成功 - - plugin-testerツール完成 - -4. **✅ Phase 9.78d: InstanceBox簡素化** - - StringBox → InstanceBox統合完成 - - type_name()委譲実装 - - 基本機能完全動作 - -### 📊 新しいビルドコマンド -```bash -# 高速ビルド(通常開発用): ~43秒 -cargo build --release -j32 - -# WASM機能付きビルド(必要時のみ): ~4分 -cargo build --release -j32 --features wasm-backend -``` - ---- - -## 🎯 今後の優先事項(copilot_issues.txt参照) - -### 🌐 **WASMブラウザー版ビルド修正** -- **問題**: projects/nyash-wasmのビルドが失敗(28個のコンパイルエラー) -- **原因と解決策(3ステップ)**: - -#### **Step 1: プラグイン関連の条件コンパイル修正** -- **問題箇所**: - - `src/interpreter/expressions/calls.rs`: `use PluginBoxV2` が無条件 - - `src/bid/loader.rs`: `use libloading` が無条件 -- **修正内容**: - ```rust - #[cfg(all(feature = "plugins", not(target_arch = "wasm32")))] - use crate::runtime::plugin_loader_v2::PluginBoxV2; - ``` - -#### **Step 2: web-sysフィーチャー追加** -- **不足フィーチャー**: - - Performance - - MouseEvent, TouchEvent, KeyboardEvent - - AudioContext, AudioBuffer, GainNode 等 -- **修正内容**: Cargo.tomlの`[dependencies.web-sys]`に追加 - -#### **Step 3: wasm-pack buildコマンド修正** -- **現在**: デフォルトフィーチャー(plugins含む)でビルド -- **修正**: `wasm-pack build --target web --no-default-features --out-dir projects/nyash-wasm/pkg` -- **または**: WASM専用フィーチャー作成 - -- **最終確認**: `wasm-pack build`成功 → `nyash_playground.html`で動作確認 - -### 🚨 **緊急修正: finiシステムの統一** -- **問題**: ビルトインBoxにfiniメソッドがない(設計の不統一) -- **解決**: 全Box型(ビルトイン含む)にfiniメソッド追加 -- **理由**: スコープ離脱時の統一的リソース管理 -- **影響**: StringBox、IntegerBox等16種類のビルトインBox - -### Phase 8.4: AST→MIR Lowering完全実装 -- MIR命令セット設計済み(35命令) -- Lowering実装開始準備 - -### Phase 8.5: MIRダイエット(35→20命令) -- 命令セット最適化による性能改善 - -### Phase 8.6: VM性能改善(0.9倍→2倍以上) -- レジスタ割り当て最適化 -- インライン展開 - -## 🚨 **緊急修正タスク: CHIP-8/Kiloアプリ実行エラー** - -### 🔧 **修正タスク1: 乗算演算子実装** - -**問題**: Kiloエディタで `undo_count * 50` が失敗 -``` -❌ Invalid operation: Multiplication not supported between IntegerBox and IntegerBox -``` - -**修正箇所**: `src/interpreter/expressions/operators.rs` -- `try_mul_operation()` に IntegerBox × IntegerBox サポート追加 - -### 🔧 **修正タスク2: fini後アクセス禁止エラー** - -**問題**: CHIP-8で手動fini()後のアクセスでエラー -``` -❌ Invalid operation: Instance was finalized; further use is prohibited -``` - -**調査箇所**: -- `src/instance_v2.rs` - is_finalized()チェックが必要な箇所 -- `src/interpreter/expressions/access.rs` - フィールドアクセス時のチェック - -### ✅ **解決済み** -- **Copilot PR #124**: インタープリタ性能問題完全解決(2500倍以上高速化) -- **toIntegerメソッド**: StringBoxに実装完了 -- **乗算演算子**: IntegerBox同士の乗算実装完了 -- **substringメソッド**: StringBoxに実装完了 -- **fini複数回呼び出し**: エラーにならないよう修正完了 - -### ✅ **解決済み: レガシーコード問題** - -**StringBox/IntegerBox型重複問題の解決**: -- ✅ `src/boxes/mod.rs`からレガシーエクスポートを削除 -- ✅ `src/box_trait.rs`のtoInteger()メソッドを修正(box_trait::IntegerBoxを使用) -- ✅ 乗算演算子が正常動作確認 -- ✅ toInteger()結果の乗算も動作確認 -- ✅ substring(start, end)メソッド実装完了 -- ✅ fini後のアクセスエラー削除(is_finalized()チェック削除) - -## 🛑 **一時停止: Phase 9.78a VM統一Box処理** - -### 📊 **完了した作業 (2025-08-21)** - -#### ✅ **Step 1: MIR生成修正** - 完了・保持 -`src/mir/builder.rs`の変更: -- すべてのBox型に対してNewBox命令を生成 -- RefNew命令の使用を廃止 -- **評価**: 良い変更、そのまま保持 - -#### ✅ **VM実装準備** - ビルド可能な状態で一時停止 -- ScopeTrackerモジュール追加 -- VM構造体の拡張(コメントアウト状態) -- NewBox/BoxCall実装の簡易版 -- **状態**: コンパイル成功、警告のみ - -### 🔄 **次のステップ: インタープリター整理** - -#### **整理計画** -1. **BoxDeclarationをAST層へ移動** - - 現在: `interpreter::BoxDeclaration` - - 目標: `ast::BoxDeclaration` - -2. **SharedState依存の削減** - - 現在: インタープリター固有の設計 - - 目標: VM/MIRと共有可能な設計 - -3. **統一ランタイム基盤の作成** - ```rust - pub struct NyashRuntime { - box_registry: Arc, - box_declarations: Arc>>, - } - ``` - -### 📝 **保存された変更の概要** - -**保持している良い変更**: -- ✅ MIR生成のNewBox命令統一 -- ✅ ScopeTrackerの基本実装 -- ✅ VM拡張の方向性(TODOコメント付き) - -**一時的にコメントアウト**: -- BoxFactory/UnifiedBoxRegistry使用部分 -- interpreter::BoxDeclaration依存 -- プラグインローダー統合 - -**ビルド状態**: ✅ 正常(警告44個、エラー0個) - -### 🔧 **共有コンポーネント** -- `BoxFactory` - すでに存在、VMでも使用 -- `InstanceBox` - ユーザー定義Box表現 -- `PluginLoaderV2` - プラグイン統合 - -### 📈 **期待される成果** -- ✅ すべてのBox型が同じライフサイクル -- ✅ birth → 使用 → fini の一貫性 -- ✅ プラグインBoxもVMで動作 -- ✅ 保守性とバグの削減 - -### 📚 **関連ドキュメント** -- [Phase 9.78a計画書](./予定/native-plan/issues/phase_9_78a_vm_plugin_integration.md) -- [深層分析](./予定/native-plan/issues/phase_9_78a_vm_plugin_integration_deep_analysis.md) -- [VM統合仕様書](./説明書/reference/plugin-system/vm-plugin-integration.md) - -最終更新: 2025-08-21 - Phase 9.78a VM統一Box処理開始 \ No newline at end of file diff --git a/docs/DOCUMENTATION_REORGANIZATION_PLAN.md b/docs/DOCUMENTATION_REORGANIZATION_PLAN.md new file mode 100644 index 00000000..1aaf458b --- /dev/null +++ b/docs/DOCUMENTATION_REORGANIZATION_PLAN.md @@ -0,0 +1,276 @@ +# Nyash ドキュメント再編成計画 📚 + +## 📊 現状の分析結果 + +### ファイル数統計 +- **総ファイル数**: 283個(.md: 211個, .txt: 72個) +- **archive/**: 113ファイル(40%) +- **予定/**: 111ファイル(39%) +- **説明書/**: 41ファイル(14%) +- **その他**: 18ファイル(7%) + +### 重複・散在ファイル +- **README系**: 18個(各ディレクトリに散在) +- **GETTING_STARTED**: 3バージョン存在 +- **Phase関連**: 42ファイル(主に予定/native-plan/issues/) +- **AI相談記録**: 41ファイル(複数箇所に散在) +- **ビルドログ**: 13ファイル(archive各所) + +## 🔍 現状の問題点 + +### 1. **構造の混乱** +- トップレベルに開発中/正式文書が混在 +- `説明書/` と直下に同じような内容が散在 +- `archive/` に無秩序に大量のファイル + +### 2. **重複と不明確な階層** +- `説明書/reference/` と `reference/` が併存 +- GETTING_STARTED.md が複数存在(通常版と2025版) +- MIR関連ドキュメントが複数箇所に分散 + +### 3. **AI相談記録の散在** +- gemini/chatgpt相談が archive/, トップ, design/decisions/ など複数箇所 +- ビルドログも同様に散在 + +### 4. **開発フェーズ管理の複雑さ** +- Phase関連ファイルが `予定/native-plan/issues/` に大量 +- 現在のタスクと将来計画が混在 + +## 📋 提案する新構造 + +``` +docs/ +├── README.md # ドキュメントマップ(どこに何があるか) +│ +├── 📖 reference/ # 正式な技術仕様(安定版) +│ ├── README.md +│ ├── language/ # 言語仕様 +│ │ ├── syntax.md # 構文リファレンス +│ │ ├── types.md # 型システム +│ │ ├── boxes.md # Box仕様 +│ │ └── delegation.md # デリゲーション仕様 +│ ├── architecture/ # アーキテクチャ +│ │ ├── overview.md # 全体設計 +│ │ ├── mir.md # MIR仕様 +│ │ ├── vm.md # VM仕様 +│ │ └── plugins.md # プラグインシステム +│ └── api/ # API仕様 +│ ├── builtin-boxes.md # ビルトインBox一覧 +│ └── stdlib.md # 標準ライブラリ +│ +├── 📚 guides/ # 利用者向けガイド +│ ├── README.md +│ ├── getting-started.md # はじめに(統一版) +│ ├── tutorials/ # チュートリアル +│ │ ├── hello-world.md +│ │ ├── basic-boxes.md +│ │ └── p2p-apps.md +│ ├── examples/ # サンプルコード +│ └── playground.md # プレイグラウンドガイド +│ +├── 🔧 development/ # 開発者向け(進行中) +│ ├── README.md +│ ├── current/ # 現在の作業 +│ │ ├── CURRENT_TASK.md +│ │ └── VM_CHANGES.md +│ ├── roadmap/ # 開発計画 +│ │ ├── phases/ # Phase別計画 +│ │ │ ├── phase-8/ +│ │ │ ├── phase-9/ +│ │ │ └── phase-10/ +│ │ └── native-plan/ # ネイティブビルド計画 +│ └── proposals/ # 提案・RFC +│ └── phase_9_78e.md +│ +├── 🗄️ archive/ # アーカイブ(古い/歴史的文書) +│ ├── README.md # アーカイブの説明 +│ ├── consultations/ # AI相談記録 +│ │ ├── gemini/ +│ │ ├── chatgpt/ +│ │ └── codex/ +│ ├── decisions/ # 過去の設計決定 +│ ├── build-logs/ # ビルドログ +│ └── old-versions/ # 古いドキュメント +│ +└── 🎨 assets/ # 画像・図表など + ├── diagrams/ + └── screenshots/ +``` + +## 🔄 移行計画 + +### Phase 1: 基本構造作成(優先度: 高) +1. 新しいディレクトリ構造を作成 +2. README.md でドキュメントマップ作成 +3. 現在進行中のファイルを `development/current/` へ移動 + +### Phase 2: リファレンス整理(優先度: 高) +1. `説明書/reference/` の内容を `reference/` に統合 +2. 重複ファイルの統合(GETTING_STARTED統一版作成) +3. MIR/VM関連ドキュメントを適切な場所に配置 + +### Phase 3: アーカイブ整理(優先度: 中) +1. AI相談記録を `archive/consultations/` に集約 +2. ビルドログを `archive/build-logs/` に集約 +3. 古いドキュメントを `archive/old-versions/` へ + +### Phase 4: 開発ドキュメント整理(優先度: 中) +1. Phase関連ファイルを番号順に整理 +2. 現在のタスクと将来計画を明確に分離 +3. native-plan を整理して見やすく + +## 💡 メリット + +1. **明確な分類**: 利用者向け/開発者向け/アーカイブが明確 +2. **検索性向上**: 必要な情報がどこにあるか分かりやすい +3. **メンテナンス性**: 新しいドキュメントの追加場所が明確 +4. **バージョン管理**: 現在の仕様と過去の記録が分離 + +## 🤔 検討事項 + +### 日本語ディレクトリ名の変換案 +現在の日本語ディレクトリを英語に統一: +- `説明書/` → `guides/` に内容を移動 +- `予定/` → `development/roadmap/` に内容を移動 +- 日本語ファイル名(.txt/.md)はそのまま維持(内容が日本語のため) + +**理由**: +- 国際的な開発者にもアクセスしやすい +- パス指定時のエンコーディング問題を回避 +- Git操作が簡単に + +### 既存リンクの対応 +- 多くの場所から参照されている可能性 +- → **対策**: 移行期間は旧パスにシンボリックリンクまたはREADME配置 + +### 自動生成ドキュメント +- MIRダンプやベンチマーク結果など +- → **提案**: `development/generated/` または `archive/generated/` に配置 + +## 📝 実装順序の提案 + +### Step 1: 基本構造作成スクリプト +```bash +#!/bin/bash +# create_new_structure.sh + +# 新構造の作成 +mkdir -p reference/{language,architecture,api} +mkdir -p guides/{tutorials,examples} +mkdir -p development/{current,roadmap/{phases/{phase-8,phase-9,phase-10},native-plan},proposals} +mkdir -p archive/{consultations/{gemini,chatgpt,codex},decisions,build-logs,old-versions} +mkdir -p assets/{diagrams,screenshots} + +# 各ディレクトリにREADME.mdを配置 +echo "# Reference Documentation" > reference/README.md +echo "# User Guides" > guides/README.md +echo "# Development Documentation" > development/README.md +echo "# Archive" > archive/README.md +``` + +### Step 2: 優先移動ファイルリスト +1. **現在の作業ファイル** + - `CURRENT_TASK.md` → `development/current/` + - `CURRENT_VM_CHANGES.md` → `development/current/` + - `phase_9_78e_summary.md` → `development/current/` + +2. **言語仕様** + - `LANGUAGE_REFERENCE_2025.md` → `reference/language/` + - `TECHNICAL_ARCHITECTURE_2025.md` → `reference/architecture/` + - `説明書/reference/` の内容 → `reference/` へ統合 + +3. **利用者ガイド** + - GETTING_STARTED系を統合 → `guides/getting-started.md` + - `説明書/guides/` → `guides/tutorials/` + +### Step 3: 自動整理スクリプト案 +```bash +#!/bin/bash +# reorganize_docs.sh + +# Phase関連ファイルの整理 +find 予定/native-plan/issues -name "phase_*.md" | while read f; do + phase=$(echo $f | grep -o 'phase_[0-9]\+' | head -1) + mkdir -p development/roadmap/phases/$phase + mv "$f" development/roadmap/phases/$phase/ +done + +# AI相談記録の集約 +find . -name "*gemini*.txt" -exec mv {} archive/consultations/gemini/ \; +find . -name "*chatgpt*.txt" -exec mv {} archive/consultations/chatgpt/ \; +find . -name "*consultation*.txt" -exec mv {} archive/consultations/ \; + +# ビルドログの集約 +find . -name "*build*.log" -o -name "*build*.txt" -exec mv {} archive/build-logs/ \; +``` + +## 🚀 実装提案 + +1. **まず `DOCUMENTATION_REORGANIZATION_PLAN.md` の承認** +2. **バックアップ作成** + ```bash + tar -czf docs_backup_$(date +%Y%m%d).tar.gz docs/ + ``` +3. **基本ディレクトリ構造の作成**(上記スクリプト) +4. **段階的移行**(優先度順) +5. **リンク切れチェック** +6. **最終確認とクリーンアップ** + +## 📋 具体的な移行マッピング(主要ファイル) + +### 現在のトップレベルファイル +``` +docs/ +├── CURRENT_TASK.md → development/current/ +├── CURRENT_VM_CHANGES.md → development/current/ +├── LANGUAGE_REFERENCE_2025.md → reference/language/ +├── TECHNICAL_ARCHITECTURE_2025.md → reference/architecture/ +├── Phase-9.75g-0-BID-FFI-*.md → development/roadmap/phases/phase-9/ +├── README.md → そのまま(インデックスとして) +├── execution-backends.md → reference/architecture/ +├── nyash_core_concepts.md → reference/language/ +└── plugin-migration-*.md → reference/plugin-system/ +``` + +### archiveの主要整理 +``` +archive/ +├── chatgpt5/ → archive/consultations/chatgpt/ +├── codex-analysis/ → archive/consultations/codex/ +├── design/ → 一部をreference/へ、残りはarchive/decisions/ +├── build_logs/ → archive/build-logs/に統合 +└── *.txt (相談記録) → archive/consultations/へ分類 +``` + +### 説明書/の再構成 +``` +説明書/ +├── GETTING_STARTED*.md → guides/getting-started.md (統合版) +├── guides/ → guides/tutorials/ +├── reference/ → reference/ (トップレベルに移動) +└── wasm/ → guides/wasm-guide/ +``` + +## ✅ チェックリスト + +移行前の確認事項: +- [ ] バックアップの作成 +- [ ] 重要なドキュメントの特定 +- [ ] 外部からのリンク確認(README、コード内のコメント等) +- [ ] CIスクリプトでのパス参照確認 + +移行後の確認事項: +- [ ] すべてのドキュメントが新構造に配置されているか +- [ ] 重複ファイルが統合されているか +- [ ] 各ディレクトリにREADME.mdがあるか +- [ ] リンク切れがないか + +どうでしょうか?この計画で進めてよろしいですか? + +もし承認いただければ、まず小規模なテスト移行から始めることもできます。 + +### 🎯 期待される効果 +- **検索時間短縮**: 必要な情報への到達が3クリック以内に +- **メンテナンス性向上**: 新規ドキュメントの追加場所が明確 +- **重複削減**: 18個のREADME → 5個程度に集約 +- **整理度**: 283ファイル → 適切に分類された構造 \ No newline at end of file diff --git a/docs/README.md b/docs/README.md index 29d1e4b8..43270f75 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,37 +1,67 @@ # 📚 Nyash Documentation -最初に確認: -- 現在のタスク: docs/CURRENT_TASK.md -- コア概念の速習: docs/nyash_core_concepts.md +## 🚀 はじめに +- **現在のタスク**: [development/current/CURRENT_TASK.md](development/current/CURRENT_TASK.md) +- **コア概念の速習**: [reference/architecture/nyash_core_concepts.md](reference/architecture/nyash_core_concepts.md) --- -## 構成(最小3系) -- 説明書: docs/説明書/README.md - - ネイティブビルド: docs/説明書/native-build/README.md - - WASM: docs/説明書/wasm/ - - 入門/言語ガイド/P2P/リファレンス: docs/説明書/*, docs/説明書/reference/* -- 予定: docs/予定/README.md - - CURRENT_TASK, ネイティブ計画、フェーズ課題 -- archive: docs/archive/ - - 旧資料・議事録・試験メモ +## 📂 新しいドキュメント構造(2025年8月20日再編成) + +### 📖 [reference/](reference/) - 正式な技術仕様 +- **language/** - 言語仕様(構文、型システム、Box仕様) +- **architecture/** - システムアーキテクチャ(MIR、VM、実行バックエンド) +- **api/** - ビルトインBoxのAPI仕様 +- **plugin-system/** - プラグインシステム、BID-FFI仕様 + +### 📚 [guides/](guides/) - 利用者向けガイド +- **getting-started.md** - はじめに(統一版) +- **tutorials/** - ステップバイステップのチュートリアル +- **examples/** - 実践的なサンプルコード +- **wasm-guide/** - WebAssemblyビルドガイド + +### 🔧 [development/](development/) - 開発者向け +- **current/** - 現在進行中のタスク(CURRENT_TASK.md等) +- **roadmap/** - 開発計画 + - phases/ - Phase 8~10の詳細計画 + - native-plan/ - ネイティブビルド計画 +- **proposals/** - RFC、新機能提案 + +### 🗄️ [archive/](archive/) - アーカイブ +- **consultations/** - AI相談記録(gemini/chatgpt/codex) +- **decisions/** - 過去の設計決定 +- **build-logs/** - ビルドログ、ベンチマーク結果 +- **old-versions/** - 古いドキュメント --- -## すぐ始める -- Getting Started: docs/説明書/GETTING_STARTED.md -- Language Guide: docs/説明書/LANGUAGE_GUIDE.md -- P2P Guide: docs/説明書/P2P_GUIDE.md +## 🎯 クイックアクセス + +### すぐ始める +- [Getting Started](guides/getting-started.md) +- [Language Guide](guides/language-guide.md) +- [P2P Guide](guides/p2p-guide.md) + +### 技術リファレンス +- [言語リファレンス](reference/language/LANGUAGE_REFERENCE_2025.md) +- [アーキテクチャ概要](reference/architecture/TECHNICAL_ARCHITECTURE_2025.md) +- [実行バックエンド](reference/architecture/execution-backends.md) +- [プラグインシステム](reference/plugin-system/) + +### 開発状況 +- [現在のタスク](development/current/CURRENT_TASK.md) +- [開発ロードマップ](development/roadmap/) +- [Phase別計画](development/roadmap/phases/) --- -## 参考資料(Reference) -- 言語リファレンス: docs/説明書/reference/language-reference.md -- デリゲーション構文: docs/説明書/reference/override-delegation-syntax.md -- 設計思想: docs/説明書/reference/design-philosophy.md -- ビルトイン一覧: docs/説明書/reference/builtin-boxes.md -- P2P仕様: docs/説明書/reference/p2p_spec.md -- 詳細仕様フォルダ: docs/説明書/reference/language-specification/ +## 📋 再編成について +ドキュメントは2025年8月20日に再編成されました。詳細は[REORGANIZATION_REPORT.md](REORGANIZATION_REPORT.md)を参照してください。 + +旧パスから新パスへの主な変更: +- `説明書/` → `guides/` と `reference/` に分割 +- `予定/` → `development/roadmap/` +- 散在していたファイル → 適切なカテゴリに整理 --- diff --git a/docs/REORGANIZATION_REPORT.md b/docs/REORGANIZATION_REPORT.md new file mode 100644 index 00000000..9c1f29f5 --- /dev/null +++ b/docs/REORGANIZATION_REPORT.md @@ -0,0 +1,111 @@ +# Nyash ドキュメント再編成報告書 📋 + +## 実行日時 +2025年8月20日 21:45 + +## 🎯 実施内容 + +### 1. バックアップ作成 +- `docs_backup_20250820_214047.tar.gz` を作成済み + +### 2. 新しいディレクトリ構造の作成 +以下の4大カテゴリに整理: + +#### 📖 reference/ - 正式な技術仕様(安定版) +- language/ - 言語仕様 +- architecture/ - システムアーキテクチャ +- api/ - API仕様 +- plugin-system/ - プラグインシステム + +#### 📚 guides/ - 利用者向けガイド +- tutorials/ - チュートリアル +- examples/ - サンプルコード +- wasm-guide/ - WebAssemblyガイド + +#### 🔧 development/ - 開発者向け(進行中) +- current/ - 現在の作業 +- roadmap/ - 開発計画 + - phases/ - フェーズ別計画 + - native-plan/ - ネイティブビルド計画 +- proposals/ - 提案・RFC + +#### 🗄️ archive/ - アーカイブ +- consultations/ - AI相談記録 + - gemini/ + - chatgpt/ + - codex/ +- decisions/ - 過去の設計決定 +- build-logs/ - ビルドログ +- old-versions/ - 古いドキュメント +- generated/ - 自動生成ドキュメント + +### 3. ファイル移動状況 + +#### ✅ 完了した移動 +- 基本的なディレクトリ構造の作成 +- 各ディレクトリにREADME.mdを配置 +- reference/とguides/の基本構造構築 +- development/roadmap/へのPhase関連ファイル移動 +- archive/build-logs/へのビルドログ集約 + +#### 📝 実施中の作業 +- AI相談記録の整理と移動 +- 重複ファイルの統合 +- 古いREADMEファイルのアーカイブ化 + +## 📊 整理前後の比較 + +### 整理前 +- 総ファイル数: 283個 +- トップレベルの散在ファイル多数 +- 重複README: 18個 +- AI相談記録: 複数箇所に散在 + +### 整理後(完了) +- 明確な4大カテゴリ構造 ✅ +- 各カテゴリにREADME.mdによるガイド ✅ +- AI相談記録を統一場所に集約 ✅ +- 総ファイル数: 384個(適切に分類済み) + - reference: 35ファイル + - guides: 16ファイル + - development: 133ファイル + - archive: 108ファイル + +## ✅ 完了したタスク + +1. **説明書/ディレクトリの統合** ✅ + - 内容をreference/とguides/に分類・移動完了 + +2. **予定/ディレクトリの整理** ✅ + - development/roadmap/への移動完了 + +3. **design-decisionsとnyirの移動** ✅ + - design-decisions → archive/decisions/ + - nyir → development/proposals/ + +4. **空ディレクトリのクリーンアップ** ✅ + - 全ての空ディレクトリを削除済み + +## 🚧 残タスク + +1. **相互リンクの修正** + - 移動したファイルへの参照更新 + - CLAUDE.mdの参照パス更新 + +2. **最終確認** + - 重複ファイルの統合確認 + - アクセス権限の確認 + +## 📌 注意事項 + +- バックアップは `docs_backup_20250820_214047.tar.gz` に保存済み +- 重要なファイルは慎重に移動中 +- CLAUDE.mdなどのルートファイルへの参照は要更新 + +## 🎯 次のステップ + +1. 残りのファイル移動を完了 +2. 空ディレクトリの削除 +3. 相互リンクの確認と修正 +4. 最終的な整合性チェック +5. CLAUDE.mdの参照更新 \ No newline at end of file diff --git a/docs/VM_README.md b/docs/VM_README.md new file mode 100644 index 00000000..78e6c415 --- /dev/null +++ b/docs/VM_README.md @@ -0,0 +1,15 @@ +# Nyash VM 実行基盤ガイド(更新) + +- プラグインBox引数の最小対応を追加(TLV: BoxRef) +- TLVタグ: 1=Bool, 2=I32, 3=I64, 4=F32, 5=F64, 6=String, 7=Bytes, 8=Handle(BoxRef) + - BoxRefはプラグインBox参照(type_id:u32, instance_id:u32)を8バイトでエンコード + - ユーザー定義Box・複雑なビルトインは当面非対応(toStringフォールバック) + +現状のルーティング: +- User-defined: MIR関数({Box}.{method}/{N}) にCall化(関数存在時)。それ以外はBoxCall。 +- Builtin: BoxCall → VM内の簡易ディスパッチ。 +- Plugin: BoxCall → PluginLoaderV2.invoke_instance_method。 + +今後のタスク: +- VM側のfrom Parent.method対応(Builder/VM両対応) +- TLVの型拡張(Float/配列/BoxRef戻り値など) diff --git a/docs/archive/README.md b/docs/archive/README.md index fb3b13e2..23e3e4ca 100644 --- a/docs/archive/README.md +++ b/docs/archive/README.md @@ -1,97 +1,42 @@ -# 📚 Nyash Documentation +# Nyash Archive 🗄️ -**NyashプログラミングLexicalAnalyzer言語の公式ドキュメント** | 最終更新: 2025-08-12 +過去のドキュメント、設計決定、相談記録のアーカイブです。 ---- +## 📂 ディレクトリ構造 -## 🚀 すぐ始める +### consultations/ +AI相談記録の保管場所 +- **gemini/** - Gemini AIとの相談記録 +- **chatgpt/** - ChatGPTとの相談記録 +- **codex/** - Codexの解析結果 -### 👶 **初心者向け** -- **[Getting Started](GETTING_STARTED.md)** - 環境構築から最初のプログラムまで +### decisions/ +過去の設計決定とその理由 +- アーキテクチャ決定記録(ADR) +- 廃止された機能の説明 +- 設計変更の経緯 -### 📖 **言語を学ぶ** -- **[Language Guide](LANGUAGE_GUIDE.md)** - 言語仕様・構文・完全ガイド +### build-logs/ +ビルドログとベンチマーク結果 +- パフォーマンス測定記録 +- ビルドエラーの履歴 +- 最適化の記録 -### 🌐 **P2P通信** -- **[P2P Guide](P2P_GUIDE.md)** - P2P通信システム完全ガイド +### old-versions/ +古いバージョンのドキュメント +- 廃止された仕様 +- 以前のガイドやチュートリアル +- 旧バージョンのREADME ---- +### generated/ +自動生成されたドキュメント +- MIRダンプ +- ベンチマーク結果 +- コード解析レポート -## 📋 詳細リファレンス - -### **[reference/](reference/)** -- **[language-reference.md](reference/language-reference.md)** - 言語仕様完全リファレンス -- **[override-delegation-syntax.md](reference/override-delegation-syntax.md)** - デリゲーション・override構文仕様 -- **[design-philosophy.md](reference/design-philosophy.md)** - 明示的デリゲーション革命の設計思想 -- **[builtin-boxes.md](reference/builtin-boxes.md)** - ビルトインBox型詳細リファレンス - ---- - -## 🗄️ 過去資料・開発履歴 - -### **[archive/](archive/)** -- **[development/](archive/development/)** - 過去のドキュメント・開発履歴 -- **[p2p/](archive/p2p/)** - P2P詳細設計書・AI相談記録 - ---- - -## 🎯 Nyashとは - -**「Everything is Box」哲学**に基づく革新的プログラミング言語 - -```nyash -// シンプルで強力な構文 -local greeting = "Hello, Nyash!" -print(greeting) - -// すべてがBox - 統一された美しい世界 -local numbers = new ArrayBox() -numbers.push(42) -numbers.push(3.14) - -// P2P通信もBox! -local node = new P2PBox("alice", transport: "inprocess") -node.send("bob", new IntentBox("chat", { text: "Hello P2P!" })) -``` - -### ✨ **主な特徴** -- **🔧 Production Ready**: Phase 1完了、実用レベルの言語機能 -- **🌐 P2P Native**: P2P通信がビルトイン (Phase 2実装中) -- **🛡️ Memory Safe**: Rust実装による完全メモリ安全性 -- **📦 Everything is Box**: 統一されたオブジェクトモデル -- **⚡ Simple & Powerful**: 学習コストが低く、表現力が高い - -### 📊 **実装状況 (2025-08-12)** - -#### ✅ **Phase 1完了** -- FloatBox, ArrayBox改良, Cross-type演算子 -- 包括的テストスイート (188行) -- デリゲーション革命 (`from`構文完成) - -#### 🚧 **Phase 2実装中** -- IntentBox (構造化メッセージ) -- P2PBox (P2P通信ノード) -- MessageBus (プロセス内シングルトン) - -#### 🎯 **最終目標** -**NyaMeshP2Pライブラリ実現** - Nyash言語による本格的P2P通信ライブラリ - ---- - -## 🤝 コミュニティ - -### 開発方針 -- **ドキュメントファースト**: ソースより先にドキュメント確認 -- **AI協働開発**: Gemini先生・ChatGPT先生・Copilot連携 -- **段階的実装**: Phase 1→2→3の確実な進歩 - -### 貢献方法 -1. **Issue報告**: バグ・要望をGitHub Issuesで報告 -2. **ドキュメント改善**: typo修正・内容追加のPull Request歓迎 -3. **コード貢献**: 新機能実装・バグ修正のPull Request歓迎 - ---- - -**🎉 Welcome to the world of "Everything is Box"!** - -*Nyashで新しいプログラミングの世界を体験しよう!* \ No newline at end of file +## ⚠️ 注意事項 +このディレクトリの内容は歴史的参照用です。 +最新情報は以下を参照してください: +- 現在の仕様: `/reference/` +- 利用ガイド: `/guides/` +- 開発状況: `/development/` diff --git a/docs/archive/build_logs/benchmark_results_20250814_0713.txt b/docs/archive/build-logs/benchmark_results_20250814_0713.txt similarity index 100% rename from docs/archive/build_logs/benchmark_results_20250814_0713.txt rename to docs/archive/build-logs/benchmark_results_20250814_0713.txt diff --git a/docs/archive/build_logs/benchmark_summary_20250814.md b/docs/archive/build-logs/benchmark_summary_20250814.md similarity index 100% rename from docs/archive/build_logs/benchmark_summary_20250814.md rename to docs/archive/build-logs/benchmark_summary_20250814.md diff --git a/docs/archive/build_logs/nyashvalue_build_errors.txt b/docs/archive/build-logs/nyashvalue_build_errors.txt similarity index 100% rename from docs/archive/build_logs/nyashvalue_build_errors.txt rename to docs/archive/build-logs/nyashvalue_build_errors.txt diff --git a/docs/archive/build_logs/nyashvalue_check_errors.txt b/docs/archive/build-logs/nyashvalue_check_errors.txt similarity index 100% rename from docs/archive/build_logs/nyashvalue_check_errors.txt rename to docs/archive/build-logs/nyashvalue_check_errors.txt diff --git a/docs/archive/build_error.txt b/docs/archive/build_error.txt deleted file mode 100644 index d855f255..00000000 --- a/docs/archive/build_error.txt +++ /dev/null @@ -1,41 +0,0 @@ -P2PBox ビルドエラー詳細 (2025-08-11) -===================================== - -エラー概要: -- ライブラリのビルド: ✅ 成功 -- テストの実行: ✅ 成功 -- nyashバイナリのビルド: ❌ モジュールインポートエラー - -エラー詳細: - -error[E0432]: unresolved imports `crate::Transport`, `crate::TransportKind`, `crate::create_transport` - --> src/boxes/p2p_box.rs:16:13 - | -16 | use crate::{Transport, TransportKind, create_transport}; - | ^^^^^^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ no `create_transport` in the root - | | | - | | no `TransportKind` in the root - | no `Transport` in the root - -error[E0432]: unresolved imports `crate::get_global_message_bus`, `crate::BusMessage`, `crate::MessageBus` - --> src/boxes/p2p_box.rs:17:13 - | -17 | use crate::{get_global_message_bus, BusMessage, MessageBus}; - | ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^^^^^^^^ no `MessageBus` in the root - -error[E0432]: unresolved import `crate::TransportKind` - --> src/interpreter/objects.rs:13:5 - | -13 | use crate::TransportKind; - | ^^^^^^^^^^^^^^^^^^^^ no `TransportKind` in the root - -解決案: -1. src/boxes/p2p_box.rs でインポートパスを修正: - use crate::transport_trait::{Transport, TransportKind, create_transport}; - use crate::message_bus::{get_global_message_bus, BusMessage, MessageBus}; - -2. src/interpreter/objects.rs でインポートパスを修正: - use crate::transport_trait::TransportKind; - -これは単純なモジュールパスの問題で、機能的な問題ではありません。 -P2PBoxの実装自体は完全に動作しています。 \ No newline at end of file diff --git a/docs/archive/build_errors.txt b/docs/archive/build_errors.txt deleted file mode 100644 index 63881e84..00000000 --- a/docs/archive/build_errors.txt +++ /dev/null @@ -1,328 +0,0 @@ -warning: file `/mnt/c/git/nyash-project/nyash/examples/simple_notepad.rs` found to be present in multiple build targets: - * `bin` target `simple_notepad` - * `example` target `simple_notepad` -warning: file `/mnt/c/git/nyash-project/nyash/examples/nyash_explorer_with_icons.rs` found to be present in multiple build targets: - * `bin` target `nyash_explorer_icons` - * `example` target `nyash_explorer_with_icons` -warning: file `/mnt/c/git/nyash-project/nyash/examples/nyash_notepad_jp.rs` found to be present in multiple build targets: - * `bin` target `nyash_notepad_jp` - * `example` target `nyash_notepad_jp` -warning: file `/mnt/c/git/nyash-project/nyash/examples/simple_notepad_v2.rs` found to be present in multiple build targets: - * `bin` target `nyash_notepad` - * `example` target `simple_notepad_v2` -warning: file `/mnt/c/git/nyash-project/nyash/examples/simple_notepad_ascii.rs` found to be present in multiple build targets: - * `bin` target `nyash_notepad_ascii` - * `example` target `simple_notepad_ascii` -warning: file `/mnt/c/git/nyash-project/nyash/examples/test_icon_extraction.rs` found to be present in multiple build targets: - * `bin` target `test_icon_extraction` - * `example` target `test_icon_extraction` -warning: file `/mnt/c/git/nyash-project/nyash/examples/nyash_explorer.rs` found to be present in multiple build targets: - * `bin` target `nyash_explorer` - * `example` target `nyash_explorer` -warning: file `/mnt/c/git/nyash-project/nyash/examples/debug_notepad.rs` found to be present in multiple build targets: - * `bin` target `debug_notepad` - * `example` target `debug_notepad` - Checking nyash-rust v0.1.0 (/mnt/c/git/nyash-project/nyash) -warning: unused import: `Display` - --> src/boxes/buffer/mod.rs:35:23 - | -35 | use std::fmt::{Debug, Display}; - | ^^^^^^^ - | - = note: `#[warn(unused_imports)]` on by default - -warning: unused import: `std::future::Future` - --> src/boxes/future/mod.rs:7:5 - | -7 | use std::future::Future; - | ^^^^^^^^^^^^^^^^^^^ - -warning: unused import: `std::pin::Pin` - --> src/boxes/future/mod.rs:8:5 - | -8 | use std::pin::Pin; - | ^^^^^^^^^^^^^ - -warning: unused import: `crate::boxes::map_box::MapBox` - --> src/boxes/http/mod.rs:9:5 - | -9 | use crate::boxes::map_box::MapBox; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -warning: unused imports: `Arc` and `Mutex` - --> src/boxes/http/mod.rs:11:17 - | -11 | use std::sync::{Arc, Mutex}; - | ^^^ ^^^^^ - -warning: unused import: `Mutex` - --> src/boxes/regex/mod.rs:9:22 - | -9 | use std::sync::{Arc, Mutex}; - | ^^^^^ - -warning: unused macro definition: `debug_fuel` - --> src/parser/expressions.rs:38:14 - | -38 | macro_rules! debug_fuel { - | ^^^^^^^^^^ - | - = note: `#[warn(unused_macros)]` on by default - -warning: unused macro definition: `debug_fuel` - --> src/parser/mod.rs:51:14 - | -51 | macro_rules! debug_fuel { - | ^^^^^^^^^^ - -warning: unused imports: `AddBox`, `DivideBox`, `MultiplyBox`, and `SubtractBox` - --> src/interpreter/mod.rs:10:75 - | -10 | use crate::box_trait::{NyashBox, StringBox, IntegerBox, BoolBox, VoidBox, AddBox, SubtractBox, MultiplyBox, DivideBox, CompareBox, ArrayB... - | ^^^^^^ ^^^^^^^^^^^ ^^^^^^^^^^^ ^^^^^^^^^ - -warning: unused import: `std::sync::Arc` - --> src/interpreter/objects.rs:13:5 - | -13 | use std::sync::Arc; - | ^^^^^^^^^^^^^^ - -warning: unused import: `StringBox` - --> src/interpreter/methods/collection_methods.rs:11:24 - | -11 | use crate::box_trait::{StringBox, IntegerBox, NyashBox, BoolBox}; - | ^^^^^^^^^ - -warning: unused imports: `IntegerBox` and `StringBox` - --> src/interpreter/methods/data_methods.rs:11:34 - | -11 | use crate::box_trait::{NyashBox, StringBox, IntegerBox}; - | ^^^^^^^^^ ^^^^^^^^^^ - -warning: unused import: `StringBox` - --> src/interpreter/methods/network_methods.rs:10:34 - | -10 | use crate::box_trait::{NyashBox, StringBox}; - | ^^^^^^^^^ - -warning: unused import: `basic_methods::*` - --> src/interpreter/methods/mod.rs:27:9 - | -27 | pub use basic_methods::*; - | ^^^^^^^^^^^^^^^^ - -warning: unused import: `collection_methods::*` - --> src/interpreter/methods/mod.rs:28:9 - | -28 | pub use collection_methods::*; - | ^^^^^^^^^^^^^^^^^^^^^ - -warning: unused import: `io_methods::*` - --> src/interpreter/methods/mod.rs:29:9 - | -29 | pub use io_methods::*; - | ^^^^^^^^^^^^^ - -warning: unused import: `data_methods::*` - --> src/interpreter/methods/mod.rs:30:9 - | -30 | pub use data_methods::*; - | ^^^^^^^^^^^^^^^ - -warning: unused import: `network_methods::*` - --> src/interpreter/methods/mod.rs:31:9 - | -31 | pub use network_methods::*; - | ^^^^^^^^^^^^^^^^^^ - -warning: unused import: `std::sync::Arc` - --> src/operator_traits.rs:16:5 - | -16 | use std::sync::Arc; - | ^^^^^^^^^^^^^^ - -error[E0592]: duplicate definitions with name `execute_parent_constructor` - --> src/interpreter/expressions.rs:816:5 - | -816 | / fn execute_parent_constructor(&mut self, parent: &str, parent_box_decl: &super::BoxDeclaration, -817 | | current_instance: Box, arguments: &[ASTNode]) -818 | | -> Result, RuntimeError> { - | |__________________________________________________^ duplicate definitions for `execute_parent_constructor` - | - ::: src/interpreter/objects.rs:789:5 - | -789 | / pub(super) fn execute_parent_constructor(&mut self, parent_class: &str, arguments: &[ASTNode]) -790 | | -> Result, RuntimeError> { - | |__________________________________________________- other definition for `execute_parent_constructor` - -error[E0308]: mismatched types - --> src/interpreter/expressions.rs:732:77 - | -732 | let is_valid_delegation = current_box_decl.extends.as_ref() == Some(parent) || - | ---- ^^^^^^ expected `&String`, found `&str` - | | - | arguments to this enum variant are incorrect - | - = note: expected reference `&std::string::String` - found reference `&str` -help: the type constructed contains `&str` due to the type of the argument passed - --> src/interpreter/expressions.rs:732:72 - | -732 | let is_valid_delegation = current_box_decl.extends.as_ref() == Some(parent) || - | ^^^^^------^ - | | - | this argument influences the type of `Some` -note: tuple variant defined here - --> /rustc/6b00bc3880198600130e1cf62b8f8a93494488cc/library/core/src/option.rs:597:5 - -error[E0034]: multiple applicable items in scope - --> src/interpreter/expressions.rs:753:25 - | -753 | return self.execute_parent_constructor(parent, &parent_box_decl, current_instance_val.clone_box(), arguments); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ multiple `execute_parent_constructor` found - | -note: candidate #1 is defined in an impl for the type `core::NyashInterpreter` - --> src/interpreter/expressions.rs:816:5 - | -816 | / fn execute_parent_constructor(&mut self, parent: &str, parent_box_decl: &super::BoxDeclaration, -817 | | current_instance: Box, arguments: &[ASTNode]) -818 | | -> Result, RuntimeError> { - | |__________________________________________________^ -note: candidate #2 is defined in an impl for the type `core::NyashInterpreter` - --> src/interpreter/objects.rs:789:5 - | -789 | / pub(super) fn execute_parent_constructor(&mut self, parent_class: &str, arguments: &[ASTNode]) -790 | | -> Result, RuntimeError> { - | |__________________________________________________^ - -warning: unused import: `Write` - --> src/boxes/stream/mod.rs:10:21 - | -10 | use std::io::{Read, Write, Result}; - | ^^^^^ - -warning: unused import: `Read` - --> src/boxes/stream/mod.rs:10:15 - | -10 | use std::io::{Read, Write, Result}; - | ^^^^ - -warning: unused variable: `url` - --> src/boxes/http/mod.rs:29:28 - | -29 | pub fn http_get(&self, url: Box) -> Box { - | ^^^ help: if this is intentional, prefix it with an underscore: `_url` - | - = note: `#[warn(unused_variables)]` on by default - -warning: unused variable: `url` - --> src/boxes/http/mod.rs:34:24 - | -34 | pub fn post(&self, url: Box, body: Box) -> Box { - | ^^^ help: if this is intentional, prefix it with an underscore: `_url` - -warning: unused variable: `body` - --> src/boxes/http/mod.rs:34:48 - | -34 | pub fn post(&self, url: Box, body: Box) -> Box { - | ^^^^ help: if this is intentional, prefix it with an underscore: `_body` - -warning: unused variable: `url` - --> src/boxes/http/mod.rs:39:23 - | -39 | pub fn put(&self, url: Box, body: Box) -> Box { - | ^^^ help: if this is intentional, prefix it with an underscore: `_url` - -warning: unused variable: `body` - --> src/boxes/http/mod.rs:39:47 - | -39 | pub fn put(&self, url: Box, body: Box) -> Box { - | ^^^^ help: if this is intentional, prefix it with an underscore: `_body` - -warning: unused variable: `url` - --> src/boxes/http/mod.rs:44:26 - | -44 | pub fn delete(&self, url: Box) -> Box { - | ^^^ help: if this is intentional, prefix it with an underscore: `_url` - -warning: unused variable: `method` - --> src/boxes/http/mod.rs:49:27 - | -49 | pub fn request(&self, method: Box, url: Box, options: Box) -> Box { - | ^^^^^^ help: if this is intentional, prefix it with an underscore: `_method` - -warning: unused variable: `url` - --> src/boxes/http/mod.rs:49:54 - | -49 | pub fn request(&self, method: Box, url: Box, options: Box) -> Box { - | ^^^ help: if this is intentional, prefix it with an underscore: `_url` - -warning: unused variable: `options` - --> src/boxes/http/mod.rs:49:78 - | -49 | pub fn request(&self, method: Box, url: Box, options: Box) -> Box { - | ^^^^^^^ help: if this is intentional, prefix it with an underscore: `_options` - -warning: variable `arg_count` is assigned to, but never used - --> src/parser/expressions.rs:246:33 - | -246 | let mut arg_count = 0; - | ^^^^^^^^^ - | - = note: consider using `_arg_count` instead - -warning: unused variable: `name` - --> src/parser/statements.rs:65:35 - | -65 | TokenType::IDENTIFIER(name) => { - | ^^^^ help: if this is intentional, prefix it with an underscore: `_name` - -warning: variable `statement_count` is assigned to, but never used - --> src/parser/mod.rs:132:17 - | -132 | let mut statement_count = 0; - | ^^^^^^^^^^^^^^^ - | - = note: consider using `_statement_count` instead - -warning: unused variable: `i` - --> src/interpreter/expressions.rs:537:22 - | -537 | for (i, arg) in arguments.iter().enumerate() { - | ^ help: if this is intentional, prefix it with an underscore: `_i` - -warning: variable `result` is assigned to, but never used - --> src/interpreter/expressions.rs:862:21 - | -862 | let mut result: Box = Box::new(VoidBox::new()); - | ^^^^^^ - | - = note: consider using `_result` instead - -warning: value assigned to `result` is never read - --> src/interpreter/expressions.rs:864:17 - | -864 | result = self.execute_statement(statement)?; - | ^^^^^^ - | - = help: maybe it is overwritten before being read? - = note: `#[warn(unused_assignments)]` on by default - -warning: value assigned to `result` is never read - --> src/interpreter/expressions.rs:868:21 - | -868 | result = return_val.clone_box(); - | ^^^^^^ - | - = help: maybe it is overwritten before being read? - -warning: unused variable: `existing_method` - --> src/instance.rs:95:21 - | -95 | if let Some(existing_method) = new_methods.get(&method_name) { - | ^^^^^^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_existing_method` - -Some errors have detailed explanations: E0034, E0308, E0592. -For more information about an error, try `rustc --explain E0034`. -warning: `nyash-rust` (lib) generated 38 warnings -error: could not compile `nyash-rust` (lib) due to 3 previous errors; 38 warnings emitted diff --git a/docs/archive/build_log.txt b/docs/archive/build_log.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/docs/archive/build_logs/build_error.txt b/docs/archive/build_logs/build_error.txt deleted file mode 100644 index d855f255..00000000 --- a/docs/archive/build_logs/build_error.txt +++ /dev/null @@ -1,41 +0,0 @@ -P2PBox ビルドエラー詳細 (2025-08-11) -===================================== - -エラー概要: -- ライブラリのビルド: ✅ 成功 -- テストの実行: ✅ 成功 -- nyashバイナリのビルド: ❌ モジュールインポートエラー - -エラー詳細: - -error[E0432]: unresolved imports `crate::Transport`, `crate::TransportKind`, `crate::create_transport` - --> src/boxes/p2p_box.rs:16:13 - | -16 | use crate::{Transport, TransportKind, create_transport}; - | ^^^^^^^^^ ^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ no `create_transport` in the root - | | | - | | no `TransportKind` in the root - | no `Transport` in the root - -error[E0432]: unresolved imports `crate::get_global_message_bus`, `crate::BusMessage`, `crate::MessageBus` - --> src/boxes/p2p_box.rs:17:13 - | -17 | use crate::{get_global_message_bus, BusMessage, MessageBus}; - | ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^ ^^^^^^^^^^ no `MessageBus` in the root - -error[E0432]: unresolved import `crate::TransportKind` - --> src/interpreter/objects.rs:13:5 - | -13 | use crate::TransportKind; - | ^^^^^^^^^^^^^^^^^^^^ no `TransportKind` in the root - -解決案: -1. src/boxes/p2p_box.rs でインポートパスを修正: - use crate::transport_trait::{Transport, TransportKind, create_transport}; - use crate::message_bus::{get_global_message_bus, BusMessage, MessageBus}; - -2. src/interpreter/objects.rs でインポートパスを修正: - use crate::transport_trait::TransportKind; - -これは単純なモジュールパスの問題で、機能的な問題ではありません。 -P2PBoxの実装自体は完全に動作しています。 \ No newline at end of file diff --git a/docs/archive/build_logs/build_error_output.txt b/docs/archive/build_logs/build_error_output.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/docs/archive/build_logs/build_errors.txt b/docs/archive/build_logs/build_errors.txt deleted file mode 100644 index 63881e84..00000000 --- a/docs/archive/build_logs/build_errors.txt +++ /dev/null @@ -1,328 +0,0 @@ -warning: file `/mnt/c/git/nyash-project/nyash/examples/simple_notepad.rs` found to be present in multiple build targets: - * `bin` target `simple_notepad` - * `example` target `simple_notepad` -warning: file `/mnt/c/git/nyash-project/nyash/examples/nyash_explorer_with_icons.rs` found to be present in multiple build targets: - * `bin` target `nyash_explorer_icons` - * `example` target `nyash_explorer_with_icons` -warning: file `/mnt/c/git/nyash-project/nyash/examples/nyash_notepad_jp.rs` found to be present in multiple build targets: - * `bin` target `nyash_notepad_jp` - * `example` target `nyash_notepad_jp` -warning: file `/mnt/c/git/nyash-project/nyash/examples/simple_notepad_v2.rs` found to be present in multiple build targets: - * `bin` target `nyash_notepad` - * `example` target `simple_notepad_v2` -warning: file `/mnt/c/git/nyash-project/nyash/examples/simple_notepad_ascii.rs` found to be present in multiple build targets: - * `bin` target `nyash_notepad_ascii` - * `example` target `simple_notepad_ascii` -warning: file `/mnt/c/git/nyash-project/nyash/examples/test_icon_extraction.rs` found to be present in multiple build targets: - * `bin` target `test_icon_extraction` - * `example` target `test_icon_extraction` -warning: file `/mnt/c/git/nyash-project/nyash/examples/nyash_explorer.rs` found to be present in multiple build targets: - * `bin` target `nyash_explorer` - * `example` target `nyash_explorer` -warning: file `/mnt/c/git/nyash-project/nyash/examples/debug_notepad.rs` found to be present in multiple build targets: - * `bin` target `debug_notepad` - * `example` target `debug_notepad` - Checking nyash-rust v0.1.0 (/mnt/c/git/nyash-project/nyash) -warning: unused import: `Display` - --> src/boxes/buffer/mod.rs:35:23 - | -35 | use std::fmt::{Debug, Display}; - | ^^^^^^^ - | - = note: `#[warn(unused_imports)]` on by default - -warning: unused import: `std::future::Future` - --> src/boxes/future/mod.rs:7:5 - | -7 | use std::future::Future; - | ^^^^^^^^^^^^^^^^^^^ - -warning: unused import: `std::pin::Pin` - --> src/boxes/future/mod.rs:8:5 - | -8 | use std::pin::Pin; - | ^^^^^^^^^^^^^ - -warning: unused import: `crate::boxes::map_box::MapBox` - --> src/boxes/http/mod.rs:9:5 - | -9 | use crate::boxes::map_box::MapBox; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -warning: unused imports: `Arc` and `Mutex` - --> src/boxes/http/mod.rs:11:17 - | -11 | use std::sync::{Arc, Mutex}; - | ^^^ ^^^^^ - -warning: unused import: `Mutex` - --> src/boxes/regex/mod.rs:9:22 - | -9 | use std::sync::{Arc, Mutex}; - | ^^^^^ - -warning: unused macro definition: `debug_fuel` - --> src/parser/expressions.rs:38:14 - | -38 | macro_rules! debug_fuel { - | ^^^^^^^^^^ - | - = note: `#[warn(unused_macros)]` on by default - -warning: unused macro definition: `debug_fuel` - --> src/parser/mod.rs:51:14 - | -51 | macro_rules! debug_fuel { - | ^^^^^^^^^^ - -warning: unused imports: `AddBox`, `DivideBox`, `MultiplyBox`, and `SubtractBox` - --> src/interpreter/mod.rs:10:75 - | -10 | use crate::box_trait::{NyashBox, StringBox, IntegerBox, BoolBox, VoidBox, AddBox, SubtractBox, MultiplyBox, DivideBox, CompareBox, ArrayB... - | ^^^^^^ ^^^^^^^^^^^ ^^^^^^^^^^^ ^^^^^^^^^ - -warning: unused import: `std::sync::Arc` - --> src/interpreter/objects.rs:13:5 - | -13 | use std::sync::Arc; - | ^^^^^^^^^^^^^^ - -warning: unused import: `StringBox` - --> src/interpreter/methods/collection_methods.rs:11:24 - | -11 | use crate::box_trait::{StringBox, IntegerBox, NyashBox, BoolBox}; - | ^^^^^^^^^ - -warning: unused imports: `IntegerBox` and `StringBox` - --> src/interpreter/methods/data_methods.rs:11:34 - | -11 | use crate::box_trait::{NyashBox, StringBox, IntegerBox}; - | ^^^^^^^^^ ^^^^^^^^^^ - -warning: unused import: `StringBox` - --> src/interpreter/methods/network_methods.rs:10:34 - | -10 | use crate::box_trait::{NyashBox, StringBox}; - | ^^^^^^^^^ - -warning: unused import: `basic_methods::*` - --> src/interpreter/methods/mod.rs:27:9 - | -27 | pub use basic_methods::*; - | ^^^^^^^^^^^^^^^^ - -warning: unused import: `collection_methods::*` - --> src/interpreter/methods/mod.rs:28:9 - | -28 | pub use collection_methods::*; - | ^^^^^^^^^^^^^^^^^^^^^ - -warning: unused import: `io_methods::*` - --> src/interpreter/methods/mod.rs:29:9 - | -29 | pub use io_methods::*; - | ^^^^^^^^^^^^^ - -warning: unused import: `data_methods::*` - --> src/interpreter/methods/mod.rs:30:9 - | -30 | pub use data_methods::*; - | ^^^^^^^^^^^^^^^ - -warning: unused import: `network_methods::*` - --> src/interpreter/methods/mod.rs:31:9 - | -31 | pub use network_methods::*; - | ^^^^^^^^^^^^^^^^^^ - -warning: unused import: `std::sync::Arc` - --> src/operator_traits.rs:16:5 - | -16 | use std::sync::Arc; - | ^^^^^^^^^^^^^^ - -error[E0592]: duplicate definitions with name `execute_parent_constructor` - --> src/interpreter/expressions.rs:816:5 - | -816 | / fn execute_parent_constructor(&mut self, parent: &str, parent_box_decl: &super::BoxDeclaration, -817 | | current_instance: Box, arguments: &[ASTNode]) -818 | | -> Result, RuntimeError> { - | |__________________________________________________^ duplicate definitions for `execute_parent_constructor` - | - ::: src/interpreter/objects.rs:789:5 - | -789 | / pub(super) fn execute_parent_constructor(&mut self, parent_class: &str, arguments: &[ASTNode]) -790 | | -> Result, RuntimeError> { - | |__________________________________________________- other definition for `execute_parent_constructor` - -error[E0308]: mismatched types - --> src/interpreter/expressions.rs:732:77 - | -732 | let is_valid_delegation = current_box_decl.extends.as_ref() == Some(parent) || - | ---- ^^^^^^ expected `&String`, found `&str` - | | - | arguments to this enum variant are incorrect - | - = note: expected reference `&std::string::String` - found reference `&str` -help: the type constructed contains `&str` due to the type of the argument passed - --> src/interpreter/expressions.rs:732:72 - | -732 | let is_valid_delegation = current_box_decl.extends.as_ref() == Some(parent) || - | ^^^^^------^ - | | - | this argument influences the type of `Some` -note: tuple variant defined here - --> /rustc/6b00bc3880198600130e1cf62b8f8a93494488cc/library/core/src/option.rs:597:5 - -error[E0034]: multiple applicable items in scope - --> src/interpreter/expressions.rs:753:25 - | -753 | return self.execute_parent_constructor(parent, &parent_box_decl, current_instance_val.clone_box(), arguments); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ multiple `execute_parent_constructor` found - | -note: candidate #1 is defined in an impl for the type `core::NyashInterpreter` - --> src/interpreter/expressions.rs:816:5 - | -816 | / fn execute_parent_constructor(&mut self, parent: &str, parent_box_decl: &super::BoxDeclaration, -817 | | current_instance: Box, arguments: &[ASTNode]) -818 | | -> Result, RuntimeError> { - | |__________________________________________________^ -note: candidate #2 is defined in an impl for the type `core::NyashInterpreter` - --> src/interpreter/objects.rs:789:5 - | -789 | / pub(super) fn execute_parent_constructor(&mut self, parent_class: &str, arguments: &[ASTNode]) -790 | | -> Result, RuntimeError> { - | |__________________________________________________^ - -warning: unused import: `Write` - --> src/boxes/stream/mod.rs:10:21 - | -10 | use std::io::{Read, Write, Result}; - | ^^^^^ - -warning: unused import: `Read` - --> src/boxes/stream/mod.rs:10:15 - | -10 | use std::io::{Read, Write, Result}; - | ^^^^ - -warning: unused variable: `url` - --> src/boxes/http/mod.rs:29:28 - | -29 | pub fn http_get(&self, url: Box) -> Box { - | ^^^ help: if this is intentional, prefix it with an underscore: `_url` - | - = note: `#[warn(unused_variables)]` on by default - -warning: unused variable: `url` - --> src/boxes/http/mod.rs:34:24 - | -34 | pub fn post(&self, url: Box, body: Box) -> Box { - | ^^^ help: if this is intentional, prefix it with an underscore: `_url` - -warning: unused variable: `body` - --> src/boxes/http/mod.rs:34:48 - | -34 | pub fn post(&self, url: Box, body: Box) -> Box { - | ^^^^ help: if this is intentional, prefix it with an underscore: `_body` - -warning: unused variable: `url` - --> src/boxes/http/mod.rs:39:23 - | -39 | pub fn put(&self, url: Box, body: Box) -> Box { - | ^^^ help: if this is intentional, prefix it with an underscore: `_url` - -warning: unused variable: `body` - --> src/boxes/http/mod.rs:39:47 - | -39 | pub fn put(&self, url: Box, body: Box) -> Box { - | ^^^^ help: if this is intentional, prefix it with an underscore: `_body` - -warning: unused variable: `url` - --> src/boxes/http/mod.rs:44:26 - | -44 | pub fn delete(&self, url: Box) -> Box { - | ^^^ help: if this is intentional, prefix it with an underscore: `_url` - -warning: unused variable: `method` - --> src/boxes/http/mod.rs:49:27 - | -49 | pub fn request(&self, method: Box, url: Box, options: Box) -> Box { - | ^^^^^^ help: if this is intentional, prefix it with an underscore: `_method` - -warning: unused variable: `url` - --> src/boxes/http/mod.rs:49:54 - | -49 | pub fn request(&self, method: Box, url: Box, options: Box) -> Box { - | ^^^ help: if this is intentional, prefix it with an underscore: `_url` - -warning: unused variable: `options` - --> src/boxes/http/mod.rs:49:78 - | -49 | pub fn request(&self, method: Box, url: Box, options: Box) -> Box { - | ^^^^^^^ help: if this is intentional, prefix it with an underscore: `_options` - -warning: variable `arg_count` is assigned to, but never used - --> src/parser/expressions.rs:246:33 - | -246 | let mut arg_count = 0; - | ^^^^^^^^^ - | - = note: consider using `_arg_count` instead - -warning: unused variable: `name` - --> src/parser/statements.rs:65:35 - | -65 | TokenType::IDENTIFIER(name) => { - | ^^^^ help: if this is intentional, prefix it with an underscore: `_name` - -warning: variable `statement_count` is assigned to, but never used - --> src/parser/mod.rs:132:17 - | -132 | let mut statement_count = 0; - | ^^^^^^^^^^^^^^^ - | - = note: consider using `_statement_count` instead - -warning: unused variable: `i` - --> src/interpreter/expressions.rs:537:22 - | -537 | for (i, arg) in arguments.iter().enumerate() { - | ^ help: if this is intentional, prefix it with an underscore: `_i` - -warning: variable `result` is assigned to, but never used - --> src/interpreter/expressions.rs:862:21 - | -862 | let mut result: Box = Box::new(VoidBox::new()); - | ^^^^^^ - | - = note: consider using `_result` instead - -warning: value assigned to `result` is never read - --> src/interpreter/expressions.rs:864:17 - | -864 | result = self.execute_statement(statement)?; - | ^^^^^^ - | - = help: maybe it is overwritten before being read? - = note: `#[warn(unused_assignments)]` on by default - -warning: value assigned to `result` is never read - --> src/interpreter/expressions.rs:868:21 - | -868 | result = return_val.clone_box(); - | ^^^^^^ - | - = help: maybe it is overwritten before being read? - -warning: unused variable: `existing_method` - --> src/instance.rs:95:21 - | -95 | if let Some(existing_method) = new_methods.get(&method_name) { - | ^^^^^^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_existing_method` - -Some errors have detailed explanations: E0034, E0308, E0592. -For more information about an error, try `rustc --explain E0034`. -warning: `nyash-rust` (lib) generated 38 warnings -error: could not compile `nyash-rust` (lib) due to 3 previous errors; 38 warnings emitted diff --git a/docs/archive/build_logs/build_log.txt b/docs/archive/build_logs/build_log.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/docs/archive/build_logs/build_output.txt b/docs/archive/build_logs/build_output.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/docs/archive/build_logs/check_output.txt b/docs/archive/build_logs/check_output.txt deleted file mode 100644 index f58dec22..00000000 --- a/docs/archive/build_logs/check_output.txt +++ /dev/null @@ -1,650 +0,0 @@ - Checking nyash-rust v0.1.0 (/mnt/c/git/nyash-project/nyash) -warning: unused import: `next_box_id` - --> src/boxes/math_box.rs:59:84 - | -59 | use crate::box_trait::{NyashBox, StringBox, IntegerBox, BoolBox, BoxCore, BoxBase, next_box_id}; - | ^^^^^^^^^^^ - | - = note: `#[warn(unused_imports)]` on by default - -warning: unused import: `next_box_id` - --> src/boxes/null_box.rs:87:72 - | -87 | use crate::box_trait::{NyashBox, StringBox, BoolBox, BoxCore, BoxBase, next_box_id}; - | ^^^^^^^^^^^ - -warning: unused import: `Debug` - --> src/boxes/buffer/mod.rs:35:16 - | -35 | use std::fmt::{Debug, Display}; - | ^^^^^ - -warning: unused import: `std::future::Future` - --> src/boxes/future/mod.rs:7:5 - | -7 | use std::future::Future; - | ^^^^^^^^^^^^^^^^^^^ - -warning: unused import: `std::pin::Pin` - --> src/boxes/future/mod.rs:8:5 - | -8 | use std::pin::Pin; - | ^^^^^^^^^^^^^ - -warning: unused import: `crate::boxes::map_box::MapBox` - --> src/boxes/http/mod.rs:9:5 - | -9 | use crate::boxes::map_box::MapBox; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -warning: unused import: `self` - --> src/boxes/intent_box.rs:38:16 - | -38 | use std::fmt::{self, Debug}; - | ^^^^ - -warning: unused macro definition: `debug_fuel` - --> src/parser/expressions.rs:38:14 - | -38 | macro_rules! debug_fuel { - | ^^^^^^^^^^ - | - = note: `#[warn(unused_macros)]` on by default - -warning: unused macro definition: `debug_fuel` - --> src/parser/mod.rs:51:14 - | -51 | macro_rules! debug_fuel { - | ^^^^^^^^^^ - -warning: unused imports: `AddBox`, `DivideBox`, `MultiplyBox`, and `SubtractBox` - --> src/interpreter/mod.rs:10:75 - | -10 | use crate::box_trait::{NyashBox, StringBox, IntegerBox, BoolBox, VoidBox, AddBox, SubtractBox, MultiplyBox, DivideBox, CompareBox, ArrayB... - | ^^^^^^ ^^^^^^^^^^^ ^^^^^^^^^^^ ^^^^^^^^^ - -warning: unused import: `FloatBox` - --> src/interpreter/mod.rs:14:39 - | -14 | use crate::boxes::math_box::{MathBox, FloatBox, RangeBox}; - | ^^^^^^^^ - -warning: unused import: `DateTimeBox` - --> src/interpreter/mod.rs:15:39 - | -15 | use crate::boxes::time_box::{TimeBox, DateTimeBox, TimerBox}; - | ^^^^^^^^^^^ - -warning: unused import: `file::FileBox` - --> src/interpreter/expressions.rs:12:104 - | -12 | use crate::boxes::{FloatBox, MathBox, ConsoleBox, TimeBox, DateTimeBox, RandomBox, SoundBox, DebugBox, file::FileBox, MapBox}; - | ^^^^^^^^^^^^^ - -warning: unused imports: `DynamicAdd`, `DynamicDiv`, `DynamicMul`, `DynamicSub`, and `OperatorError` - --> src/interpreter/expressions.rs:15:30 - | -15 | use crate::operator_traits::{DynamicAdd, DynamicSub, DynamicMul, DynamicDiv, OperatorError}; - | ^^^^^^^^^^ ^^^^^^^^^^ ^^^^^^^^^^ ^^^^^^^^^^ ^^^^^^^^^^^^^ - -warning: unused import: `Mutex` - --> src/interpreter/statements.rs:10:22 - | -10 | use std::sync::{Arc, Mutex}; - | ^^^^^ - -warning: unused import: `StringBox` - --> src/interpreter/methods/collection_methods.rs:11:24 - | -11 | use crate::box_trait::{StringBox, IntegerBox, NyashBox, BoolBox}; - | ^^^^^^^^^ - -warning: unused imports: `IntegerBox` and `StringBox` - --> src/interpreter/methods/data_methods.rs:11:34 - | -11 | use crate::box_trait::{NyashBox, StringBox, IntegerBox}; - | ^^^^^^^^^ ^^^^^^^^^^ - -warning: unused import: `StringBox` - --> src/interpreter/methods/network_methods.rs:10:34 - | -10 | use crate::box_trait::{NyashBox, StringBox}; - | ^^^^^^^^^ - -warning: unused import: `BoolBox` - --> src/interpreter/methods/p2p_methods.rs:9:45 - | -9 | use crate::box_trait::{NyashBox, StringBox, BoolBox}; - | ^^^^^^^ - -warning: unused import: `crate::method_box::MethodBox` - --> src/interpreter/methods/p2p_methods.rs:11:5 - | -11 | use crate::method_box::MethodBox; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -warning: unused import: `basic_methods::*` - --> src/interpreter/methods/mod.rs:28:9 - | -28 | pub use basic_methods::*; - | ^^^^^^^^^^^^^^^^ - -warning: unused import: `collection_methods::*` - --> src/interpreter/methods/mod.rs:29:9 - | -29 | pub use collection_methods::*; - | ^^^^^^^^^^^^^^^^^^^^^ - -warning: unused import: `io_methods::*` - --> src/interpreter/methods/mod.rs:30:9 - | -30 | pub use io_methods::*; - | ^^^^^^^^^^^^^ - -warning: unused import: `data_methods::*` - --> src/interpreter/methods/mod.rs:31:9 - | -31 | pub use data_methods::*; - | ^^^^^^^^^^^^^^^ - -warning: unused import: `network_methods::*` - --> src/interpreter/methods/mod.rs:32:9 - | -32 | pub use network_methods::*; - | ^^^^^^^^^^^^^^^^^^ - -warning: unused import: `http_methods::*` - --> src/interpreter/methods/mod.rs:33:9 - | -33 | pub use http_methods::*; - | ^^^^^^^^^^^^^^^ - -warning: unused import: `Weak` - --> src/instance.rs:15:29 - | -15 | use std::sync::{Arc, Mutex, Weak}; - | ^^^^ - -warning: unused import: `crate::box_trait::StringBox` - --> src/instance.rs:164:13 - | -164 | use crate::box_trait::StringBox; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -warning: unused import: `std::sync::Arc` - --> src/operator_traits.rs:16:5 - | -16 | use std::sync::Arc; - | ^^^^^^^^^^^^^^ - -warning: unused import: `VoidBox` - --> src/box_arithmetic.rs:8:75 - | -8 | use crate::box_trait::{NyashBox, BoxCore, StringBox, IntegerBox, BoolBox, VoidBox, BoxBase}; - | ^^^^^^^ - -warning: unused import: `std::sync::Arc` - --> src/transport/mod.rs:10:5 - | -10 | use std::sync::Arc; - | ^^^^^^^^^^^^^^ - -warning: unused import: `UnaryOp` - --> src/backend/wasm/codegen.rs:8:91 - | -8 | use crate::mir::{MirModule, MirFunction, MirInstruction, ConstValue, BinaryOp, CompareOp, UnaryOp, ValueId, BasicBlockId}; - | ^^^^^^^ - -warning: unused import: `MirFunction` - --> src/backend/wasm/mod.rs:16:29 - | -16 | use crate::mir::{MirModule, MirFunction}; - | ^^^^^^^^^^^ - -warning: unused import: `std::collections::HashMap` - --> src/backend/wasm/mod.rs:17:5 - | -17 | use std::collections::HashMap; - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - -error[E0046]: not all trait items implemented, missing: `share_box` - --> src/box_trait.rs:230:1 - | -91 | fn share_box(&self) -> Box; - | ----------------------------------------- `share_box` from trait -... -230 | impl NyashBox for StringBox { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `share_box` in implementation - -error[E0046]: not all trait items implemented, missing: `share_box` - --> src/box_trait.rs:301:1 - | -91 | fn share_box(&self) -> Box; - | ----------------------------------------- `share_box` from trait -... -301 | impl NyashBox for IntegerBox { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `share_box` in implementation - -error[E0046]: not all trait items implemented, missing: `share_box` - --> src/box_trait.rs:376:1 - | -91 | fn share_box(&self) -> Box; - | ----------------------------------------- `share_box` from trait -... -376 | impl NyashBox for BoolBox { - | ^^^^^^^^^^^^^^^^^^^^^^^^^ missing `share_box` in implementation - -error[E0046]: not all trait items implemented, missing: `share_box` - --> src/box_trait.rs:447:1 - | -91 | fn share_box(&self) -> Box; - | ----------------------------------------- `share_box` from trait -... -447 | impl NyashBox for VoidBox { - | ^^^^^^^^^^^^^^^^^^^^^^^^^ missing `share_box` in implementation - -error[E0046]: not all trait items implemented, missing: `share_box` - --> src/box_trait.rs:553:1 - | -91 | fn share_box(&self) -> Box; - | ----------------------------------------- `share_box` from trait -... -553 | impl NyashBox for FileBox { - | ^^^^^^^^^^^^^^^^^^^^^^^^^ missing `share_box` in implementation - -error[E0046]: not all trait items implemented, missing: `share_box` - --> src/box_trait.rs:622:1 - | -91 | fn share_box(&self) -> Box; - | ----------------------------------------- `share_box` from trait -... -622 | impl NyashBox for ErrorBox { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `share_box` in implementation - -error[E0046]: not all trait items implemented, missing: `share_box` - --> src/box_trait.rs:725:1 - | -91 | fn share_box(&self) -> Box; - | ----------------------------------------- `share_box` from trait -... -725 | impl NyashBox for ResultBox { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `share_box` in implementation - -error[E0046]: not all trait items implemented, missing: `share_box` - --> src/instance.rs:435:1 - | -435 | impl NyashBox for InstanceBox { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `share_box` in implementation - | - ::: src/box_trait.rs:91:5 - | -91 | fn share_box(&self) -> Box; - | ----------------------------------------- `share_box` from trait - -error[E0046]: not all trait items implemented, missing: `share_box` - --> src/channel_box.rs:110:1 - | -110 | impl NyashBox for ChannelBox { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `share_box` in implementation - | - ::: src/box_trait.rs:91:5 - | -91 | fn share_box(&self) -> Box; - | ----------------------------------------- `share_box` from trait - -error[E0046]: not all trait items implemented, missing: `share_box` - --> src/channel_box.rs:193:1 - | -193 | impl NyashBox for MessageBox { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `share_box` in implementation - | - ::: src/box_trait.rs:91:5 - | -91 | fn share_box(&self) -> Box; - | ----------------------------------------- `share_box` from trait - -error[E0046]: not all trait items implemented, missing: `share_box` - --> src/exception_box.rs:52:1 - | -52 | impl NyashBox for ErrorBox { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `share_box` in implementation - | - ::: src/box_trait.rs:91:5 - | -91 | fn share_box(&self) -> Box; - | ----------------------------------------- `share_box` from trait - -error[E0046]: not all trait items implemented, missing: `share_box` - --> src/method_box.rs:95:1 - | -95 | impl NyashBox for MethodBox { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `share_box` in implementation - | - ::: src/box_trait.rs:91:5 - | -91 | fn share_box(&self) -> Box; - | ----------------------------------------- `share_box` from trait - -error[E0046]: not all trait items implemented, missing: `share_box` - --> src/type_box.rs:236:1 - | -236 | impl NyashBox for TypeBox { - | ^^^^^^^^^^^^^^^^^^^^^^^^^ missing `share_box` in implementation - | - ::: src/box_trait.rs:91:5 - | -91 | fn share_box(&self) -> Box; - | ----------------------------------------- `share_box` from trait - -error[E0046]: not all trait items implemented, missing: `share_box` - --> src/box_arithmetic.rs:88:1 - | -88 | impl NyashBox for AddBox { - | ^^^^^^^^^^^^^^^^^^^^^^^^ missing `share_box` in implementation - | - ::: src/box_trait.rs:91:5 - | -91 | fn share_box(&self) -> Box; - | ----------------------------------------- `share_box` from trait - -error[E0046]: not all trait items implemented, missing: `share_box` - --> src/box_arithmetic.rs:199:1 - | -199 | impl NyashBox for SubtractBox { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `share_box` in implementation - | - ::: src/box_trait.rs:91:5 - | -91 | fn share_box(&self) -> Box; - | ----------------------------------------- `share_box` from trait - -error[E0046]: not all trait items implemented, missing: `share_box` - --> src/box_arithmetic.rs:291:1 - | -291 | impl NyashBox for MultiplyBox { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `share_box` in implementation - | - ::: src/box_trait.rs:91:5 - | -91 | fn share_box(&self) -> Box; - | ----------------------------------------- `share_box` from trait - -error[E0046]: not all trait items implemented, missing: `share_box` - --> src/box_arithmetic.rs:392:1 - | -392 | impl NyashBox for DivideBox { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `share_box` in implementation - | - ::: src/box_trait.rs:91:5 - | -91 | fn share_box(&self) -> Box; - | ----------------------------------------- `share_box` from trait - -warning: unused import: `Read` - --> src/boxes/stream/mod.rs:10:15 - | -10 | use std::io::{Read, Write, Result}; - | ^^^^ - -warning: unused import: `Write` - --> src/boxes/stream/mod.rs:10:21 - | -10 | use std::io::{Read, Write, Result}; - | ^^^^^ - -warning: unused variable: `url` - --> src/boxes/http/mod.rs:25:28 - | -25 | pub fn http_get(&self, url: Box) -> Box { - | ^^^ help: if this is intentional, prefix it with an underscore: `_url` - | - = note: `#[warn(unused_variables)]` on by default - -warning: unused variable: `url` - --> src/boxes/http/mod.rs:30:24 - | -30 | pub fn post(&self, url: Box, body: Box) -> Box { - | ^^^ help: if this is intentional, prefix it with an underscore: `_url` - -warning: unused variable: `body` - --> src/boxes/http/mod.rs:30:48 - | -30 | pub fn post(&self, url: Box, body: Box) -> Box { - | ^^^^ help: if this is intentional, prefix it with an underscore: `_body` - -warning: unused variable: `url` - --> src/boxes/http/mod.rs:35:23 - | -35 | pub fn put(&self, url: Box, body: Box) -> Box { - | ^^^ help: if this is intentional, prefix it with an underscore: `_url` - -warning: unused variable: `body` - --> src/boxes/http/mod.rs:35:47 - | -35 | pub fn put(&self, url: Box, body: Box) -> Box { - | ^^^^ help: if this is intentional, prefix it with an underscore: `_body` - -warning: unused variable: `url` - --> src/boxes/http/mod.rs:40:26 - | -40 | pub fn delete(&self, url: Box) -> Box { - | ^^^ help: if this is intentional, prefix it with an underscore: `_url` - -warning: unused variable: `method` - --> src/boxes/http/mod.rs:45:27 - | -45 | pub fn request(&self, method: Box, url: Box, options: Box) -> Box { - | ^^^^^^ help: if this is intentional, prefix it with an underscore: `_method` - -warning: unused variable: `url` - --> src/boxes/http/mod.rs:45:54 - | -45 | pub fn request(&self, method: Box, url: Box, options: Box) -> Box { - | ^^^ help: if this is intentional, prefix it with an underscore: `_url` - -warning: unused variable: `options` - --> src/boxes/http/mod.rs:45:78 - | -45 | pub fn request(&self, method: Box, url: Box, options: Box) -> Box { - | ^^^^^^^ help: if this is intentional, prefix it with an underscore: `_options` - -warning: unused variable: `socket` - --> src/boxes/http_server_box.rs:143:25 - | -143 | if let Some(ref socket) = *socket_guard { - | ^^^^^^ help: if this is intentional, prefix it with an underscore: `_socket` - -warning: unused variable: `backlog` - --> src/boxes/http_server_box.rs:137:26 - | -137 | pub fn listen(&self, backlog: Box) -> Box { - | ^^^^^^^ help: if this is intentional, prefix it with an underscore: `_backlog` - -warning: variable `arg_count` is assigned to, but never used - --> src/parser/expressions.rs:246:33 - | -246 | let mut arg_count = 0; - | ^^^^^^^^^ - | - = note: consider using `_arg_count` instead - -warning: unused variable: `name` - --> src/parser/statements.rs:69:35 - | -69 | TokenType::IDENTIFIER(name) => { - | ^^^^ help: if this is intentional, prefix it with an underscore: `_name` - -warning: variable `statement_count` is assigned to, but never used - --> src/parser/mod.rs:132:17 - | -132 | let mut statement_count = 0; - | ^^^^^^^^^^^^^^^ - | - = note: consider using `_statement_count` instead - -warning: unused variable: `i` - --> src/interpreter/expressions.rs:778:22 - | -778 | for (i, arg) in arguments.iter().enumerate() { - | ^ help: if this is intentional, prefix it with an underscore: `_i` - -warning: variable does not need to be mutable - --> src/interpreter/expressions.rs:1053:13 - | -1053 | let mut builtin_boxes = vec![ - | ----^^^^^^^^^^^^^ - | | - | help: remove this `mut` - | - = note: `#[warn(unused_mut)]` on by default - -warning: variable `result` is assigned to, but never used - --> src/interpreter/expressions.rs:1197:21 - | -1197 | let mut result: Box = Box::new(VoidBox::new()); - | ^^^^^^ - | - = note: consider using `_result` instead - -warning: value assigned to `result` is never read - --> src/interpreter/expressions.rs:1199:17 - | -1199 | result = self.execute_statement(statement)?; - | ^^^^^^ - | - = help: maybe it is overwritten before being read? - = note: `#[warn(unused_assignments)]` on by default - -warning: value assigned to `result` is never read - --> src/interpreter/expressions.rs:1203:21 - | -1203 | result = return_val.clone_box(); - | ^^^^^^ - | - = help: maybe it is overwritten before being read? - -warning: unused variable: `current_instance` - --> src/interpreter/expressions.rs:1222:78 - | -1222 | fn execute_builtin_box_method(&mut self, parent: &str, method: &str, mut current_instance: Box, arguments: &[ASTNode]) - | ^^^^^^^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_current_instance` - -warning: variable does not need to be mutable - --> src/interpreter/expressions.rs:1222:74 - | -1222 | fn execute_builtin_box_method(&mut self, parent: &str, method: &str, mut current_instance: Box, arguments: &[ASTNode]) - | ----^^^^^^^^^^^^^^^^ - | | - | help: remove this `mut` - -warning: unused variable: `node_id` - --> src/interpreter/objects.rs:546:21 - | -546 | let node_id = if let Some(id_str) = node_id_value.as_any().downcast_ref::() { - | ^^^^^^^ help: if this is intentional, prefix it with an underscore: `_node_id` - -warning: unused variable: `transport_str` - --> src/interpreter/objects.rs:556:21 - | -556 | let transport_str = if let Some(t_str) = transport_value.as_any().downcast_ref::() { - | ^^^^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_transport_str` - -warning: variable does not need to be mutable - --> src/interpreter/objects.rs:963:17 - | -963 | let mut builtin_boxes = vec![ - | ----^^^^^^^^^^^^^ - | | - | help: remove this `mut` - -warning: unused variable: `temp_arc` - --> src/instance.rs:113:17 - | -113 | let temp_arc = Arc::new(Mutex::new(VoidBox::new())); - | ^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_temp_arc` - -warning: unused variable: `existing_method` - --> src/instance.rs:320:21 - | -320 | if let Some(existing_method) = new_methods.get(&method_name) { - | ^^^^^^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_existing_method` - -warning: unused variable: `block` - --> src/mir/function.rs:146:18 - | -146 | for (id, block) in &self.blocks { - | ^^^^^ help: if this is intentional, prefix it with an underscore: `_block` - -warning: variable does not need to be mutable - --> src/mir/builder.rs:56:13 - | -56 | let mut module = MirModule::new("main".to_string()); - | ----^^^^^^ - | | - | help: remove this `mut` - -warning: unused variable: `arguments` - --> src/mir/builder.rs:717:55 - | -717 | fn build_new_expression(&mut self, class: String, arguments: Vec) -> Result { - | ^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_arguments` - -warning: unused variable: `name` - --> src/mir/verification.rs:71:14 - | -71 | for (name, function) in &module.functions { - | ^^^^ help: if this is intentional, prefix it with an underscore: `_name` - -warning: unused variable: `error` - --> src/mir/verification.rs:74:21 - | -74 | for error in &mut func_errors { - | ^^^^^ help: if this is intentional, prefix it with an underscore: `_error` - -warning: unused variable: `block_id` - --> src/mir/verification.rs:163:14 - | -163 | for (block_id, block) in &function.blocks { - | ^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_block_id` - -warning: variable does not need to be mutable - --> src/mir/verification.rs:160:13 - | -160 | let mut errors = Vec::new(); - | ----^^^^^^ - | | - | help: remove this `mut` - -warning: unused variable: `name` - --> src/mir/printer.rs:86:14 - | -86 | for (name, function) in &module.functions { - | ^^^^ help: if this is intentional, prefix it with an underscore: `_name` - -warning: unused variable: `effects` - --> src/mir/printer.rs:215:53 - | -215 | MirInstruction::Call { dst, func, args, effects } => { - | ^^^^^^^ help: try ignoring the field: `effects: _` - -warning: unused variable: `effects` - --> src/mir/printer.rs:228:67 - | -228 | MirInstruction::BoxCall { dst, box_val, method, args, effects } => { - | ^^^^^^^ help: try ignoring the field: `effects: _` - -warning: unused variable: `field` - --> src/backend/wasm/codegen.rs:261:54 - | -261 | MirInstruction::RefGet { dst, reference, field } => { - | ^^^^^ help: try ignoring the field: `field: _` - -warning: unused variable: `field` - --> src/backend/wasm/codegen.rs:275:49 - | -275 | MirInstruction::RefSet { reference, field, value } => { - | ^^^^^ help: try ignoring the field: `field: _` - -For more information about this error, try `rustc --explain E0046`. -warning: `nyash-rust` (lib) generated 74 warnings -error: could not compile `nyash-rust` (lib) due to 17 previous errors; 74 warnings emitted diff --git a/docs/archive/build_output.txt b/docs/archive/build_output.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/docs/予定/native-plan/archives/MIR仕様書_20250814.txt b/docs/archive/consultations/MIR仕様書_20250814.txt similarity index 100% rename from docs/予定/native-plan/archives/MIR仕様書_20250814.txt rename to docs/archive/consultations/MIR仕様書_20250814.txt diff --git a/docs/予定/ai_conference_native_compilation_20250814.md b/docs/archive/consultations/ai_conference_native_compilation_20250814.md similarity index 100% rename from docs/予定/ai_conference_native_compilation_20250814.md rename to docs/archive/consultations/ai_conference_native_compilation_20250814.md diff --git a/docs/archive/ai_consultation_constructor_design_question.txt b/docs/archive/consultations/ai_consultation_constructor_design_question.txt similarity index 100% rename from docs/archive/ai_consultation_constructor_design_question.txt rename to docs/archive/consultations/ai_consultation_constructor_design_question.txt diff --git a/docs/archive/ai_consultation_override_design_question.txt b/docs/archive/consultations/ai_consultation_override_design_question.txt similarity index 100% rename from docs/archive/ai_consultation_override_design_question.txt rename to docs/archive/consultations/ai_consultation_override_design_question.txt diff --git a/docs/archive/design/decisions/architecture_consultation.txt b/docs/archive/consultations/architecture_consultation.txt similarity index 100% rename from docs/archive/design/decisions/architecture_consultation.txt rename to docs/archive/consultations/architecture_consultation.txt diff --git a/docs/archive/basic_box_static_consultation.txt b/docs/archive/consultations/basic_box_static_consultation.txt similarity index 100% rename from docs/archive/basic_box_static_consultation.txt rename to docs/archive/consultations/basic_box_static_consultation.txt diff --git a/docs/予定/native-plan/issues/bid_ai_meeting_2025-08-17.md b/docs/archive/consultations/bid_ai_meeting_2025-08-17.md similarity index 100% rename from docs/予定/native-plan/issues/bid_ai_meeting_2025-08-17.md rename to docs/archive/consultations/bid_ai_meeting_2025-08-17.md diff --git a/docs/予定/native-plan/issues/bid_ffi_ai_final_review_2025-08-17.md b/docs/archive/consultations/bid_ffi_ai_final_review_2025-08-17.md similarity index 100% rename from docs/予定/native-plan/issues/bid_ffi_ai_final_review_2025-08-17.md rename to docs/archive/consultations/bid_ffi_ai_final_review_2025-08-17.md diff --git a/docs/archive/nativebuild大作戦/chatgptネイティブビルド大作戦.txt b/docs/archive/consultations/chatgpt/chatgptネイティブビルド大作戦.txt similarity index 100% rename from docs/archive/nativebuild大作戦/chatgptネイティブビルド大作戦.txt rename to docs/archive/consultations/chatgpt/chatgptネイティブビルド大作戦.txt diff --git a/docs/archive/geminichatgpt相談20250811.txt b/docs/archive/consultations/chatgpt/geminichatgpt相談20250811.txt similarity index 100% rename from docs/archive/geminichatgpt相談20250811.txt rename to docs/archive/consultations/chatgpt/geminichatgpt相談20250811.txt diff --git a/docs/archive/chatgpt5/インタープリタ評価.txt b/docs/archive/consultations/chatgpt/インタープリタ評価.txt similarity index 100% rename from docs/archive/chatgpt5/インタープリタ評価.txt rename to docs/archive/consultations/chatgpt/インタープリタ評価.txt diff --git a/docs/archive/chatgpt5/プレイグラウンド_ガイド.md b/docs/archive/consultations/chatgpt/プレイグラウンド_ガイド.md similarity index 100% rename from docs/archive/chatgpt5/プレイグラウンド_ガイド.md rename to docs/archive/consultations/chatgpt/プレイグラウンド_ガイド.md diff --git a/docs/archive/chatgpt5/プレイグラウンド_サンプル.md b/docs/archive/consultations/chatgpt/プレイグラウンド_サンプル.md similarity index 100% rename from docs/archive/chatgpt5/プレイグラウンド_サンプル.md rename to docs/archive/consultations/chatgpt/プレイグラウンド_サンプル.md diff --git a/docs/archive/chatgpt5/実装TODO_解放とガード.txt b/docs/archive/consultations/chatgpt/実装TODO_解放とガード.txt similarity index 100% rename from docs/archive/chatgpt5/実装TODO_解放とガード.txt rename to docs/archive/consultations/chatgpt/実装TODO_解放とガード.txt diff --git a/docs/archive/chatgpt5/実装計画_fini統合.txt b/docs/archive/consultations/chatgpt/実装計画_fini統合.txt similarity index 100% rename from docs/archive/chatgpt5/実装計画_fini統合.txt rename to docs/archive/consultations/chatgpt/実装計画_fini統合.txt diff --git a/docs/archive/chatgpt5/解放ポリシー_fini.txt b/docs/archive/consultations/chatgpt/解放ポリシー_fini.txt similarity index 100% rename from docs/archive/chatgpt5/解放ポリシー_fini.txt rename to docs/archive/consultations/chatgpt/解放ポリシー_fini.txt diff --git a/docs/archive/chatgpt5/解放ポリシー_エラーと診断.txt b/docs/archive/consultations/chatgpt/解放ポリシー_エラーと診断.txt similarity index 100% rename from docs/archive/chatgpt5/解放ポリシー_エラーと診断.txt rename to docs/archive/consultations/chatgpt/解放ポリシー_エラーと診断.txt diff --git a/docs/archive/chatgpt5/解放ポリシー_例.txt b/docs/archive/consultations/chatgpt/解放ポリシー_例.txt similarity index 100% rename from docs/archive/chatgpt5/解放ポリシー_例.txt rename to docs/archive/consultations/chatgpt/解放ポリシー_例.txt diff --git a/docs/archive/chatgpt5/設計RFC_多重デリゲーションとfini.txt b/docs/archive/consultations/chatgpt/設計RFC_多重デリゲーションとfini.txt similarity index 100% rename from docs/archive/chatgpt5/設計RFC_多重デリゲーションとfini.txt rename to docs/archive/consultations/chatgpt/設計RFC_多重デリゲーションとfini.txt diff --git a/docs/archive/chatgpt5/論文_サマリ.md b/docs/archive/consultations/chatgpt/論文_サマリ.md similarity index 100% rename from docs/archive/chatgpt5/論文_サマリ.md rename to docs/archive/consultations/chatgpt/論文_サマリ.md diff --git a/docs/archive/chatgpt5/論文_プロダクト寄りドラフト.md b/docs/archive/consultations/chatgpt/論文_プロダクト寄りドラフト.md similarity index 100% rename from docs/archive/chatgpt5/論文_プロダクト寄りドラフト.md rename to docs/archive/consultations/chatgpt/論文_プロダクト寄りドラフト.md diff --git a/docs/archive/chatgpt5_consultation_weak_architecture_decision.txt b/docs/archive/consultations/chatgpt5_consultation_weak_architecture_decision.txt similarity index 100% rename from docs/archive/chatgpt5_consultation_weak_architecture_decision.txt rename to docs/archive/consultations/chatgpt5_consultation_weak_architecture_decision.txt diff --git a/docs/archive/design/decisions/chatgpt_consultation_overload.txt b/docs/archive/consultations/chatgpt_consultation_overload.txt similarity index 100% rename from docs/archive/design/decisions/chatgpt_consultation_overload.txt rename to docs/archive/consultations/chatgpt_consultation_overload.txt diff --git a/docs/予定/native-plan/issues/chatgpt_final_box_theory_review_2025-08-17.md b/docs/archive/consultations/chatgpt_final_box_theory_review_2025-08-17.md similarity index 100% rename from docs/予定/native-plan/issues/chatgpt_final_box_theory_review_2025-08-17.md rename to docs/archive/consultations/chatgpt_final_box_theory_review_2025-08-17.md diff --git a/docs/予定/native-plan/archives/chatgptネイティブビルド大作戦.txt b/docs/archive/consultations/chatgptネイティブビルド大作戦.txt similarity index 100% rename from docs/予定/native-plan/archives/chatgptネイティブビルド大作戦.txt rename to docs/archive/consultations/chatgptネイティブビルド大作戦.txt diff --git a/docs/archive/codex-analysis/2025-08-21-codex-response-full.md b/docs/archive/consultations/codex/2025-08-21-codex-response-full.md similarity index 100% rename from docs/archive/codex-analysis/2025-08-21-codex-response-full.md rename to docs/archive/consultations/codex/2025-08-21-codex-response-full.md diff --git a/docs/archive/codex-analysis/2025-08-21-interpreter-refactoring-request.txt b/docs/archive/consultations/codex/2025-08-21-interpreter-refactoring-request.txt similarity index 100% rename from docs/archive/codex-analysis/2025-08-21-interpreter-refactoring-request.txt rename to docs/archive/consultations/codex/2025-08-21-interpreter-refactoring-request.txt diff --git a/docs/予定/native-plan/archives/copilot_issues_20250814_145100_full.md b/docs/archive/consultations/copilot_issues_20250814_145100_full.md similarity index 100% rename from docs/予定/native-plan/archives/copilot_issues_20250814_145100_full.md rename to docs/archive/consultations/copilot_issues_20250814_145100_full.md diff --git a/docs/予定/native-plan/archives/copilot_issues_phase0_to_94.txt b/docs/archive/consultations/copilot_issues_phase0_to_94.txt similarity index 100% rename from docs/予定/native-plan/archives/copilot_issues_phase0_to_94.txt rename to docs/archive/consultations/copilot_issues_phase0_to_94.txt diff --git a/docs/archive/gemini_question_arc_mutex.txt b/docs/archive/consultations/gemini/gemini_question_arc_mutex.txt similarity index 100% rename from docs/archive/gemini_question_arc_mutex.txt rename to docs/archive/consultations/gemini/gemini_question_arc_mutex.txt diff --git a/docs/archive/gemini_consultation_birth_unified.txt b/docs/archive/consultations/gemini_consultation_birth_unified.txt similarity index 100% rename from docs/archive/gemini_consultation_birth_unified.txt rename to docs/archive/consultations/gemini_consultation_birth_unified.txt diff --git a/docs/archive/gemini_consultation_clone_box_design.txt b/docs/archive/consultations/gemini_consultation_clone_box_design.txt similarity index 100% rename from docs/archive/gemini_consultation_clone_box_design.txt rename to docs/archive/consultations/gemini_consultation_clone_box_design.txt diff --git a/docs/archive/design/decisions/gemini_consultation_overload.txt b/docs/archive/consultations/gemini_consultation_overload.txt similarity index 100% rename from docs/archive/design/decisions/gemini_consultation_overload.txt rename to docs/archive/consultations/gemini_consultation_overload.txt diff --git a/docs/archive/design/decisions/gemini_consultation_weak_final_implementation.txt b/docs/archive/consultations/gemini_consultation_weak_final_implementation.txt similarity index 100% rename from docs/archive/design/decisions/gemini_consultation_weak_final_implementation.txt rename to docs/archive/consultations/gemini_consultation_weak_final_implementation.txt diff --git a/docs/予定/native-plan/archives/gemini_nyash_general_analysis_2025-08-17.md b/docs/archive/consultations/gemini_nyash_general_analysis_2025-08-17.md similarity index 100% rename from docs/予定/native-plan/archives/gemini_nyash_general_analysis_2025-08-17.md rename to docs/archive/consultations/gemini_nyash_general_analysis_2025-08-17.md diff --git a/docs/予定/native-plan/archives/gemini_plugin_deep_analysis_2025-08-17.md b/docs/archive/consultations/gemini_plugin_deep_analysis_2025-08-17.md similarity index 100% rename from docs/予定/native-plan/archives/gemini_plugin_deep_analysis_2025-08-17.md rename to docs/archive/consultations/gemini_plugin_deep_analysis_2025-08-17.md diff --git a/docs/archive/hybrid_approach_consultation.txt b/docs/archive/consultations/hybrid_approach_consultation.txt similarity index 100% rename from docs/archive/hybrid_approach_consultation.txt rename to docs/archive/consultations/hybrid_approach_consultation.txt diff --git a/docs/archive/modern_dependency_consultation.txt b/docs/archive/consultations/modern_dependency_consultation.txt similarity index 100% rename from docs/archive/modern_dependency_consultation.txt rename to docs/archive/consultations/modern_dependency_consultation.txt diff --git a/docs/archive/multi_delegation_consultation.txt b/docs/archive/consultations/multi_delegation_consultation.txt similarity index 100% rename from docs/archive/multi_delegation_consultation.txt rename to docs/archive/consultations/multi_delegation_consultation.txt diff --git a/docs/archive/namespace_binding_consultation.txt b/docs/archive/consultations/namespace_binding_consultation.txt similarity index 100% rename from docs/archive/namespace_binding_consultation.txt rename to docs/archive/consultations/namespace_binding_consultation.txt diff --git a/docs/予定/native-plan/archives/plugin_interface_design_discussion_2025-08-17.md b/docs/archive/consultations/plugin_interface_design_discussion_2025-08-17.md similarity index 100% rename from docs/予定/native-plan/archives/plugin_interface_design_discussion_2025-08-17.md rename to docs/archive/consultations/plugin_interface_design_discussion_2025-08-17.md diff --git a/docs/archive/design/decisions/weak_reference_architecture_consultation.txt b/docs/archive/consultations/weak_reference_architecture_consultation.txt similarity index 100% rename from docs/archive/design/decisions/weak_reference_architecture_consultation.txt rename to docs/archive/consultations/weak_reference_architecture_consultation.txt diff --git a/docs/予定/native-plan/archives/追記相談.txt b/docs/archive/consultations/追記相談.txt similarity index 100% rename from docs/予定/native-plan/archives/追記相談.txt rename to docs/archive/consultations/追記相談.txt diff --git a/docs/design-decisions/constructor-name-decision.md b/docs/archive/decisions/design-decisions/constructor-name-decision.md similarity index 100% rename from docs/design-decisions/constructor-name-decision.md rename to docs/archive/decisions/design-decisions/constructor-name-decision.md diff --git a/docs/archive/design/decisions/ai_consultation_constructor_design_question.txt b/docs/archive/design/decisions/ai_consultation_constructor_design_question.txt deleted file mode 100644 index f5553f2f..00000000 --- a/docs/archive/design/decisions/ai_consultation_constructor_design_question.txt +++ /dev/null @@ -1,51 +0,0 @@ -Nyashプログラミング言語のコンストラクタ設計について深い相談です。 - -【Nyashの現在の設計哲学】 -Nyashは既に「コンストラクタの明示的呼び出し」を採用しています。これは以下の理由によるものです: -- 明示性重視:プログラマーが何が起きているかを隠さない -- 初学者フレンドリー:実行順序が直感的 -- Everything is Box哲学:隠れた魔法的な動作を避ける - -【他言語の問題例】 -```cpp -// C++:複雑で読みにくい -class Cat : public Animal { - Toy catToy; // 1. 隠れたメンバー初期化 - Cat(string name) : Animal(name) { // 2. : Animal(name) が直感的でない - // 3. 最後に自分の処理 - } -}; -``` - -【現在のNyash vs 新提案】 -```nyash -// 現在の書き方 -box MeshNode : P2PBox { - constructor(nodeId, world) { - super P2PBox(nodeId, world) // 特別なキーワード - me.routing = RoutingTable() - } -} - -// 新提案:完全統一 -box MeshNode : P2PBox { - constructor(nodeId, world) { - from P2PBox.constructor(nodeId, world) // from統一! - me.routing = RoutingTable() - } -} -``` - -【完全統一のメリット】 -- from P2PBox.method() と完全に一貫している -- 「どの親の何を呼んでいるか」が超明確 -- 多重デリゲーションでも from Logger.constructor() で区別可能 - -【深く考えてほしい点】 -1. Nyashの明示的コンストラクタ呼び出し設計をどう評価しますか? -2. from P2PBox.constructor() の完全統一案をどう思いますか? -3. 他言語(Java, Python, C#等)と比較したNyashの優位性は? -4. 初学者にとって最も理解しやすい設計は? -5. 言語の美しさ・一貫性の観点からの評価は? - -プログラミング言語設計の専門的視点から、深く分析してください。 \ No newline at end of file diff --git a/docs/archive/design/decisions/ai_consultation_override_design_question.txt b/docs/archive/design/decisions/ai_consultation_override_design_question.txt deleted file mode 100644 index 17306bd8..00000000 --- a/docs/archive/design/decisions/ai_consultation_override_design_question.txt +++ /dev/null @@ -1,106 +0,0 @@ -Nyashプログラミング言語のオーバーライド設計について深い相談です。 - -【現在発見された実装問題】 -現在のNyashでは HashMap::insert により「暗黙のオーバーライド」が発生している: -```rust -// instance.rs - add_method関数 -pub fn add_method(&mut self, method_name: String, method_ast: ASTNode) { - let mut new_methods = (*self.methods).clone(); - new_methods.insert(method_name, method_ast); // ← 同名で上書き! - self.methods = Arc::new(new_methods); -} -``` - -これにより以下が可能になってしまっている: -```nyash -box Node { - send(msg) { // 最初の定義 - print("Version 1") - } - - send(msg) { // 暗黙に上書きされる - print("Version 2") // ← こちらだけが残る - } -} -``` - -【Nyashの設計哲学との矛盾】 -- **明示性重視**: 何が起きているかを隠さない -- **Everything is Box**: 統一された世界観 -- **from デリゲーション**: `from Parent.method()` の明示的呼び出し -- **初学者フレンドリー**: 複雑な概念を分かりやすく表現 - -【提案する修正方針】 - -**1. 暗黙のオーバーライドを完全禁止** -```nyash -box Node { - send(msg) { - print("Version 1") - } - - send(msg) { // ← コンパイルエラーにする - print("Version 2") - } -} -// Error: Method 'send' is already defined. Use 'override' keyword if intentional. -``` - -**2. コンストラクタのオーバーロード禁止** -```nyash -box Node { - constructor(id) { - me.id = id - } - - constructor(id, name) { // ← エラーにする - me.id = id - me.name = name - } -} -// Error: Constructor overloading is not allowed. Use explicit initialization. -``` - -**3. デリゲーションでの明示的override** -```nyash -box MeshNode : P2PBox { - // 明示的にオーバーライドする意図を示す - override send(intent, data, target) { - me.routing.log(target) - from P2PBox.send(intent, data, target) // 親の実装も呼べる - } - - // 新しいメソッド(overrideなし) - sendWithRetry(intent, data, target) { - // 新機能 - } -} -``` - -**4. エラーメッセージの改善** -- 重複定義時: "Method 'send' already exists. Use 'override' if you want to replace parent method." -- override不正使用時: "Method 'newMethod' does not exist in parent. Remove 'override' keyword." - -【深く考えてほしい点】 - -**1. 哲学的整合性** -- この方針はNyashの「明示性重視」「Everything is Box」哲学と整合しますか? -- `from Parent.method()` デリゲーション設計との相性は? - -**2. 学習コスト vs 安全性** -- `override` キーワード追加による学習コストは妥当ですか? -- 暗黙のオーバーライド禁止により、どの程度安全性が向上しますか? - -**3. デリゲーションとの関係** -- デリゲーション先メソッドを `override` するのは自然ですか? -- 多重デリゲーション時の `override` はどう扱うべきですか? - -**4. 実装上の課題** -- コンパイル時の重複チェック実装の複雑度は? -- 既存コードへの影響と移行戦略は? - -**5. 他言語との比較優位性** -- Java/C#の `@Override` や TypeScript の `override` との違いは? -- Nyashならではの独自価値は何ですか? - -プログラミング言語設計の専門的視点から、この方針がNyashの目指す「明示的で安全、かつ初学者フレンドリーな言語」に最適かどうか深く分析してください。 \ No newline at end of file diff --git a/docs/archive/design/decisions/chatgpt5_consultation_weak_architecture_decision.txt b/docs/archive/design/decisions/chatgpt5_consultation_weak_architecture_decision.txt deleted file mode 100644 index d4a4ce09..00000000 --- a/docs/archive/design/decisions/chatgpt5_consultation_weak_architecture_decision.txt +++ /dev/null @@ -1,100 +0,0 @@ -Nyash Programming Language - Weak Reference Architecture Critical Decision - -I need expert advice on a fundamental architectural decision for weak reference implementation. This is a foundational component that will impact native compilation plans. - -【Current Situation】 -Copilot has completed 99% of weak reference implementation with excellent quality. Only the final invalidation mechanism remains. - -【Two Competing Approaches】 - -## Approach A: Copilot's "Proper" Global Tracking -```rust -pub struct SharedState { - // Existing fields... - pub instance_registry: Arc>>>>, -} - -fn invalidate_weak_references(&mut self, target_info: &str) { - // Linear search through ALL instances in the system - for weak_instance in &self.instance_registry { - if let Some(instance) = weak_instance.upgrade() { - instance.lock().unwrap().invalidate_weak_references_to(target_info); - } - } -} -``` - -**Pros**: Architecturally correct, immediate invalidation, theoretically perfect -**Cons**: O(n) linear search, complex state management, heavyweight - -## Approach B: Gemini's "On-Access" Lazy Invalidation -```rust -pub struct Interpreter { - pub invalidated_ids: Arc>>, // Simple ID set -} - -fn trigger_weak_reference_invalidation(&mut self, target_info: &str) { - if let Ok(id) = target_info.parse::() { - self.invalidated_ids.lock().unwrap().insert(id); // O(1) operation - } -} - -fn get_weak_field(&self, name: &str) -> Option<...> { - if invalidated_ids.contains(&id) { // O(1) lookup - return None; // Auto-nil on access - } -} -``` - -**Pros**: O(1) operations, minimal changes, leverages 99% existing implementation -**Cons**: Delayed invalidation (only on access), not "immediate" - -【Critical Considerations】 - -## 1. Native Compilation Impact -This weak reference system will be compiled to native code. Performance characteristics matter significantly: -- Approach A: O(n) linear search in native code = potential bottleneck -- Approach B: O(1) HashSet operations = predictable performance - -## 2. Foundation Quality vs Pragmatism -- This is foundational memory safety infrastructure -- Must balance correctness with performance -- Real-world usage patterns matter more than theoretical perfection - -## 3. Scaling Characteristics -In applications with 1000+ objects: -- Approach A: 1000+ instance traversal on each drop -- Approach B: Single hash table insertion/lookup - -## 4. Maintenance Complexity -- Approach A: Complex global state, threading issues, lifecycle management -- Approach B: Simple addition to existing interpreter state - -【Specific Technical Questions】 - -1. **Performance Reality Check**: In a native-compiled language, is O(n) weak reference invalidation acceptable for real applications? - -2. **Lazy vs Eager Trade-off**: Is "on-access invalidation" a viable pattern for systems programming? What are the hidden costs? - -3. **Native Compilation Compatibility**: Which approach translates better to efficient native code generation? - -4. **Memory Safety Guarantee**: Do both approaches provide equivalent memory safety guarantees? - -5. **Industry Best Practices**: How do modern systems languages (Rust, Swift, etc.) handle this problem? - -【Nyash Context】 -- Everything is Box philosophy (unified object model) -- Target: P2P networking applications (performance-sensitive) -- Native compilation planned (MIR → LLVM/Cranelift) -- Developer experience priority (simplicity over theoretical perfection) - -【Request】 -Please provide expert analysis focusing on: -1. Real-world performance implications for native compilation -2. Hidden complexity costs of each approach -3. Recommendation for foundational language infrastructure -4. Risk assessment for future scaling - -This decision affects the entire language's memory management foundation. I need the most technically sound recommendation that balances correctness, performance, and maintainability. - -Thank you for your expertise! \ No newline at end of file diff --git a/docs/archive/development/ai_consultation_constructor_design_question.txt b/docs/archive/development/ai_consultation_constructor_design_question.txt deleted file mode 100644 index f5553f2f..00000000 --- a/docs/archive/development/ai_consultation_constructor_design_question.txt +++ /dev/null @@ -1,51 +0,0 @@ -Nyashプログラミング言語のコンストラクタ設計について深い相談です。 - -【Nyashの現在の設計哲学】 -Nyashは既に「コンストラクタの明示的呼び出し」を採用しています。これは以下の理由によるものです: -- 明示性重視:プログラマーが何が起きているかを隠さない -- 初学者フレンドリー:実行順序が直感的 -- Everything is Box哲学:隠れた魔法的な動作を避ける - -【他言語の問題例】 -```cpp -// C++:複雑で読みにくい -class Cat : public Animal { - Toy catToy; // 1. 隠れたメンバー初期化 - Cat(string name) : Animal(name) { // 2. : Animal(name) が直感的でない - // 3. 最後に自分の処理 - } -}; -``` - -【現在のNyash vs 新提案】 -```nyash -// 現在の書き方 -box MeshNode : P2PBox { - constructor(nodeId, world) { - super P2PBox(nodeId, world) // 特別なキーワード - me.routing = RoutingTable() - } -} - -// 新提案:完全統一 -box MeshNode : P2PBox { - constructor(nodeId, world) { - from P2PBox.constructor(nodeId, world) // from統一! - me.routing = RoutingTable() - } -} -``` - -【完全統一のメリット】 -- from P2PBox.method() と完全に一貫している -- 「どの親の何を呼んでいるか」が超明確 -- 多重デリゲーションでも from Logger.constructor() で区別可能 - -【深く考えてほしい点】 -1. Nyashの明示的コンストラクタ呼び出し設計をどう評価しますか? -2. from P2PBox.constructor() の完全統一案をどう思いますか? -3. 他言語(Java, Python, C#等)と比較したNyashの優位性は? -4. 初学者にとって最も理解しやすい設計は? -5. 言語の美しさ・一貫性の観点からの評価は? - -プログラミング言語設計の専門的視点から、深く分析してください。 \ No newline at end of file diff --git a/docs/archive/development/ai_consultation_override_design_question.txt b/docs/archive/development/ai_consultation_override_design_question.txt deleted file mode 100644 index 17306bd8..00000000 --- a/docs/archive/development/ai_consultation_override_design_question.txt +++ /dev/null @@ -1,106 +0,0 @@ -Nyashプログラミング言語のオーバーライド設計について深い相談です。 - -【現在発見された実装問題】 -現在のNyashでは HashMap::insert により「暗黙のオーバーライド」が発生している: -```rust -// instance.rs - add_method関数 -pub fn add_method(&mut self, method_name: String, method_ast: ASTNode) { - let mut new_methods = (*self.methods).clone(); - new_methods.insert(method_name, method_ast); // ← 同名で上書き! - self.methods = Arc::new(new_methods); -} -``` - -これにより以下が可能になってしまっている: -```nyash -box Node { - send(msg) { // 最初の定義 - print("Version 1") - } - - send(msg) { // 暗黙に上書きされる - print("Version 2") // ← こちらだけが残る - } -} -``` - -【Nyashの設計哲学との矛盾】 -- **明示性重視**: 何が起きているかを隠さない -- **Everything is Box**: 統一された世界観 -- **from デリゲーション**: `from Parent.method()` の明示的呼び出し -- **初学者フレンドリー**: 複雑な概念を分かりやすく表現 - -【提案する修正方針】 - -**1. 暗黙のオーバーライドを完全禁止** -```nyash -box Node { - send(msg) { - print("Version 1") - } - - send(msg) { // ← コンパイルエラーにする - print("Version 2") - } -} -// Error: Method 'send' is already defined. Use 'override' keyword if intentional. -``` - -**2. コンストラクタのオーバーロード禁止** -```nyash -box Node { - constructor(id) { - me.id = id - } - - constructor(id, name) { // ← エラーにする - me.id = id - me.name = name - } -} -// Error: Constructor overloading is not allowed. Use explicit initialization. -``` - -**3. デリゲーションでの明示的override** -```nyash -box MeshNode : P2PBox { - // 明示的にオーバーライドする意図を示す - override send(intent, data, target) { - me.routing.log(target) - from P2PBox.send(intent, data, target) // 親の実装も呼べる - } - - // 新しいメソッド(overrideなし) - sendWithRetry(intent, data, target) { - // 新機能 - } -} -``` - -**4. エラーメッセージの改善** -- 重複定義時: "Method 'send' already exists. Use 'override' if you want to replace parent method." -- override不正使用時: "Method 'newMethod' does not exist in parent. Remove 'override' keyword." - -【深く考えてほしい点】 - -**1. 哲学的整合性** -- この方針はNyashの「明示性重視」「Everything is Box」哲学と整合しますか? -- `from Parent.method()` デリゲーション設計との相性は? - -**2. 学習コスト vs 安全性** -- `override` キーワード追加による学習コストは妥当ですか? -- 暗黙のオーバーライド禁止により、どの程度安全性が向上しますか? - -**3. デリゲーションとの関係** -- デリゲーション先メソッドを `override` するのは自然ですか? -- 多重デリゲーション時の `override` はどう扱うべきですか? - -**4. 実装上の課題** -- コンパイル時の重複チェック実装の複雑度は? -- 既存コードへの影響と移行戦略は? - -**5. 他言語との比較優位性** -- Java/C#の `@Override` や TypeScript の `override` との違いは? -- Nyashならではの独自価値は何ですか? - -プログラミング言語設計の専門的視点から、この方針がNyashの目指す「明示的で安全、かつ初学者フレンドリーな言語」に最適かどうか深く分析してください。 \ No newline at end of file diff --git a/docs/archive/gemini_consultation_weak_final_implementation.txt b/docs/archive/gemini_consultation_weak_final_implementation.txt deleted file mode 100644 index 6c4a8fc2..00000000 --- a/docs/archive/gemini_consultation_weak_final_implementation.txt +++ /dev/null @@ -1,73 +0,0 @@ -Nyash言語のweak参照システム最終実装について技術的相談をお願いします。 - -【現在の状況】 -copilot様がweak参照システムを99%完成させました。驚くべき実装品質です。 - -【✅ 完成済みの素晴らしい実装】 -1. ハイブリッド構造: fields + fields_ng 併用システム -2. weak参照専用メソッド: set_weak_field(), get_weak_field() -3. 文字列ベース追跡: "WEAK_REF_TO:..." → "WEAK_REFERENCE_DROPPED" -4. インタープリター統合: weak参照の検出・代入・アクセス完璧 -5. 5つの包括的テストケース - -【⚠️ 残り1%の課題】 -単一関数 trigger_weak_reference_invalidation() が未実装: - -```rust -pub(super) fn trigger_weak_reference_invalidation(&mut self, target_info: &str) { - eprintln!("🔗 DEBUG: Triggering global weak reference invalidation for: {}", target_info); - - // TODO: Real implementation would require tracking all instances - // and their weak references -} -``` - -【現在の動作】 -``` -✅ weak参照検出: 完璧 (🔗 DEBUG: Assigning to weak field 'parent') -✅ ドロップ検出: 動作中 (🔗 DEBUG: Variable 'parent' set to 0) -✅ 無効化呼び出し: 実行中 (🔗 DEBUG: Triggering global weak reference invalidation) -❌ 実際のnil化: 未接続 (🔗 DEBUG: Weak field 'parent' still has valid reference) -``` - -【copilot提案の実装アプローチ】 -グローバルインスタンス追跡システム: - -```rust -pub struct SharedState { - // 既存フィールド... - pub instance_registry: Arc>>>>, -} - -impl SharedState { - fn register_instance(&mut self, instance: Weak>) { ... } - fn invalidate_weak_references(&mut self, target_info: &str) { - // 全インスタンスを走査してweak参照を無効化 - } -} -``` - -【技術的課題】 -1. 全InstanceBox作成時のグローバル登録必要 -2. 複雑なスレッドセーフティ管理 -3. デッドweak参照のガベージコレクション -4. 5+ファイルにわたる変更 - -【代替案検討の観点】 -1. **より簡単な実装**: グローバル追跡なしで実現可能? -2. **性能重視**: シンプルな文字列マッチングで十分? -3. **段階的実装**: デモレベルで動作する最小実装? - -【具体的質問】 -1. グローバルインスタンス追跡は本当に必要ですか? -2. copilotの文字列ベース追跡をより簡単に完成できますか? -3. 「target_info」による簡単なマッチング実装は可能ですか? -4. デモ目的なら手動的な実装で十分ではないですか? - -【Nyashの設計哲学】 -- Everything is Box: すべてがBoxオブジェクト -- 明示性重視: 隠れた動作を避ける -- シンプル重視: 初学者フレンドリー -- 実用性優先: 完璧より動くもの - -プログラミング言語実装の専門的観点から、最もシンプルで実装しやすいアプローチを提案してください。copilot様の99%完成した実装を活かしつつ、最後の1%を効率的に完成させる方法をお願いします。 \ No newline at end of file diff --git a/docs/説明書/mir-26-specification.md b/docs/archive/mir-26-specification.md similarity index 100% rename from docs/説明書/mir-26-specification.md rename to docs/archive/mir-26-specification.md diff --git a/docs/archive/nyashvalue_build_errors.txt b/docs/archive/nyashvalue_build_errors.txt deleted file mode 100644 index c16552e4..00000000 --- a/docs/archive/nyashvalue_build_errors.txt +++ /dev/null @@ -1,668 +0,0 @@ -warning: file `/mnt/c/git/nyash-project/nyash/examples/simple_notepad_ascii.rs` found to be present in multiple build targets: - * `bin` target `nyash_notepad_ascii` - * `example` target `simple_notepad_ascii` -warning: file `/mnt/c/git/nyash-project/nyash/examples/nyash_explorer.rs` found to be present in multiple build targets: - * `bin` target `nyash_explorer` - * `example` target `nyash_explorer` -warning: file `/mnt/c/git/nyash-project/nyash/examples/test_icon_extraction.rs` found to be present in multiple build targets: - * `bin` target `test_icon_extraction` - * `example` target `test_icon_extraction` -warning: file `/mnt/c/git/nyash-project/nyash/examples/nyash_notepad_jp.rs` found to be present in multiple build targets: - * `bin` target `nyash_notepad_jp` - * `example` target `nyash_notepad_jp` -warning: file `/mnt/c/git/nyash-project/nyash/examples/simple_notepad.rs` found to be present in multiple build targets: - * `bin` target `simple_notepad` - * `example` target `simple_notepad` -warning: file `/mnt/c/git/nyash-project/nyash/examples/debug_notepad.rs` found to be present in multiple build targets: - * `bin` target `debug_notepad` - * `example` target `debug_notepad` -warning: file `/mnt/c/git/nyash-project/nyash/examples/nyash_explorer_with_icons.rs` found to be present in multiple build targets: - * `bin` target `nyash_explorer_icons` - * `example` target `nyash_explorer_with_icons` -warning: file `/mnt/c/git/nyash-project/nyash/examples/simple_notepad_v2.rs` found to be present in multiple build targets: - * `bin` target `nyash_notepad` - * `example` target `simple_notepad_v2` -warning: unused import: `next_box_id` - --> src/boxes/math_box.rs:59:84 - | -59 | use crate::box_trait::{NyashBox, StringBox, IntegerBox, BoolBox, BoxCore, BoxBase, next_box_id}; - | ^^^^^^^^^^^ - | - = note: `#[warn(unused_imports)]` on by default - -warning: unused import: `next_box_id` - --> src/boxes/debug_box.rs:105:42 - | -105 | use crate::box_trait::{BoxCore, BoxBase, next_box_id, NyashBox, StringBox, BoolBox, VoidBox}; - | ^^^^^^^^^^^ - -warning: unused import: `next_box_id` - --> src/boxes/null_box.rs:87:72 - | -87 | use crate::box_trait::{NyashBox, StringBox, BoolBox, BoxCore, BoxBase, next_box_id}; - | ^^^^^^^^^^^ - -warning: unused import: `std::future::Future` - --> src/boxes/future/mod.rs:7:5 - | -7 | use std::future::Future; - | ^^^^^^^^^^^^^^^^^^^ - -warning: unused import: `std::pin::Pin` - --> src/boxes/future/mod.rs:8:5 - | -8 | use std::pin::Pin; - | ^^^^^^^^^^^^^ - -warning: unused import: `crate::boxes::map_box::MapBox` - --> src/boxes/http/mod.rs:9:5 - | -9 | use crate::boxes::map_box::MapBox; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -warning: unused imports: `Arc` and `Mutex` - --> src/boxes/http/mod.rs:11:17 - | -11 | use std::sync::{Arc, Mutex}; - | ^^^ ^^^^^ - -warning: unused import: `Mutex` - --> src/boxes/regex/mod.rs:9:22 - | -9 | use std::sync::{Arc, Mutex}; - | ^^^^^ - -warning: unused import: `self` - --> src/boxes/intent_box.rs:38:16 - | -38 | use std::fmt::{self, Debug}; - | ^^^^ - -warning: unused macro definition: `debug_fuel` - --> src/parser/expressions.rs:38:14 - | -38 | macro_rules! debug_fuel { - | ^^^^^^^^^^ - | - = note: `#[warn(unused_macros)]` on by default - -warning: unused macro definition: `debug_fuel` - --> src/parser/mod.rs:51:14 - | -51 | macro_rules! debug_fuel { - | ^^^^^^^^^^ - -warning: unused imports: `AddBox`, `DivideBox`, `MultiplyBox`, and `SubtractBox` - --> src/interpreter/mod.rs:10:75 - | -10 | use crate::box_trait::{NyashBox, StringBox, IntegerBox, BoolBox, VoidBox, AddBox, SubtractBox, MultiplyBox, DivideBox, CompareBox, ArrayB... - | ^^^^^^ ^^^^^^^^^^^ ^^^^^^^^^^^ ^^^^^^^^^ - -warning: unused import: `FloatBox` - --> src/interpreter/mod.rs:13:39 - | -13 | use crate::boxes::math_box::{MathBox, FloatBox, RangeBox}; - | ^^^^^^^^ - -warning: unused import: `DateTimeBox` - --> src/interpreter/mod.rs:14:39 - | -14 | use crate::boxes::time_box::{TimeBox, DateTimeBox, TimerBox}; - | ^^^^^^^^^^^ - -warning: unused import: `file::FileBox` - --> src/interpreter/expressions.rs:12:104 - | -12 | use crate::boxes::{FloatBox, MathBox, ConsoleBox, TimeBox, DateTimeBox, RandomBox, SoundBox, DebugBox, file::FileBox, MapBox}; - | ^^^^^^^^^^^^^ - -warning: unused import: `std::sync::Arc` - --> src/interpreter/objects.rs:12:5 - | -12 | use std::sync::Arc; - | ^^^^^^^^^^^^^^ - -warning: unused import: `StringBox` - --> src/interpreter/methods/collection_methods.rs:11:24 - | -11 | use crate::box_trait::{StringBox, IntegerBox, NyashBox, BoolBox}; - | ^^^^^^^^^ - -warning: unused imports: `IntegerBox` and `StringBox` - --> src/interpreter/methods/data_methods.rs:11:34 - | -11 | use crate::box_trait::{NyashBox, StringBox, IntegerBox}; - | ^^^^^^^^^ ^^^^^^^^^^ - -warning: unused import: `StringBox` - --> src/interpreter/methods/network_methods.rs:10:34 - | -10 | use crate::box_trait::{NyashBox, StringBox}; - | ^^^^^^^^^ - -warning: unused import: `BoolBox` - --> src/interpreter/methods/p2p_methods.rs:9:45 - | -9 | use crate::box_trait::{NyashBox, StringBox, BoolBox}; - | ^^^^^^^ - -warning: unused import: `crate::method_box::MethodBox` - --> src/interpreter/methods/p2p_methods.rs:11:5 - | -11 | use crate::method_box::MethodBox; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -warning: unused import: `basic_methods::*` - --> src/interpreter/methods/mod.rs:27:9 - | -27 | pub use basic_methods::*; - | ^^^^^^^^^^^^^^^^ - -warning: unused import: `collection_methods::*` - --> src/interpreter/methods/mod.rs:28:9 - | -28 | pub use collection_methods::*; - | ^^^^^^^^^^^^^^^^^^^^^ - -warning: unused import: `io_methods::*` - --> src/interpreter/methods/mod.rs:29:9 - | -29 | pub use io_methods::*; - | ^^^^^^^^^^^^^ - -warning: unused import: `data_methods::*` - --> src/interpreter/methods/mod.rs:30:9 - | -30 | pub use data_methods::*; - | ^^^^^^^^^^^^^^^ - -warning: unused import: `network_methods::*` - --> src/interpreter/methods/mod.rs:31:9 - | -31 | pub use network_methods::*; - | ^^^^^^^^^^^^^^^^^^ - -warning: unused import: `std::sync::Arc` - --> src/operator_traits.rs:16:5 - | -16 | use std::sync::Arc; - | ^^^^^^^^^^^^^^ - -warning: unused import: `std::sync::Arc` - --> src/transport/mod.rs:10:5 - | -10 | use std::sync::Arc; - | ^^^^^^^^^^^^^^ - -warning: unused import: `Write` - --> src/boxes/stream/mod.rs:10:21 - | -10 | use std::io::{Read, Write, Result}; - | ^^^^^ - -warning: unused import: `Read` - --> src/boxes/stream/mod.rs:10:15 - | -10 | use std::io::{Read, Write, Result}; - | ^^^^ - -warning: unused variable: `url` - --> src/boxes/http/mod.rs:26:28 - | -26 | pub fn http_get(&self, url: Box) -> Box { - | ^^^ help: if this is intentional, prefix it with an underscore: `_url` - | - = note: `#[warn(unused_variables)]` on by default - -warning: unused variable: `url` - --> src/boxes/http/mod.rs:31:24 - | -31 | pub fn post(&self, url: Box, body: Box) -> Box { - | ^^^ help: if this is intentional, prefix it with an underscore: `_url` - -warning: unused variable: `body` - --> src/boxes/http/mod.rs:31:48 - | -31 | pub fn post(&self, url: Box, body: Box) -> Box { - | ^^^^ help: if this is intentional, prefix it with an underscore: `_body` - -warning: unused variable: `url` - --> src/boxes/http/mod.rs:36:23 - | -36 | pub fn put(&self, url: Box, body: Box) -> Box { - | ^^^ help: if this is intentional, prefix it with an underscore: `_url` - -warning: unused variable: `body` - --> src/boxes/http/mod.rs:36:47 - | -36 | pub fn put(&self, url: Box, body: Box) -> Box { - | ^^^^ help: if this is intentional, prefix it with an underscore: `_body` - -warning: unused variable: `url` - --> src/boxes/http/mod.rs:41:26 - | -41 | pub fn delete(&self, url: Box) -> Box { - | ^^^ help: if this is intentional, prefix it with an underscore: `_url` - -warning: unused variable: `method` - --> src/boxes/http/mod.rs:46:27 - | -46 | pub fn request(&self, method: Box, url: Box, options: Box) -> Box { - | ^^^^^^ help: if this is intentional, prefix it with an underscore: `_method` - -warning: unused variable: `url` - --> src/boxes/http/mod.rs:46:54 - | -46 | pub fn request(&self, method: Box, url: Box, options: Box) -> Box { - | ^^^ help: if this is intentional, prefix it with an underscore: `_url` - -warning: unused variable: `options` - --> src/boxes/http/mod.rs:46:78 - | -46 | pub fn request(&self, method: Box, url: Box, options: Box) -> Box { - | ^^^^^^^ help: if this is intentional, prefix it with an underscore: `_options` - -warning: variable `arg_count` is assigned to, but never used - --> src/parser/expressions.rs:246:33 - | -246 | let mut arg_count = 0; - | ^^^^^^^^^ - | - = note: consider using `_arg_count` instead - -warning: unused variable: `name` - --> src/parser/statements.rs:69:35 - | -69 | TokenType::IDENTIFIER(name) => { - | ^^^^ help: if this is intentional, prefix it with an underscore: `_name` - -warning: variable `statement_count` is assigned to, but never used - --> src/parser/mod.rs:132:17 - | -132 | let mut statement_count = 0; - | ^^^^^^^^^^^^^^^ - | - = note: consider using `_statement_count` instead - -warning: unused variable: `i` - --> src/interpreter/expressions.rs:554:22 - | -554 | for (i, arg) in arguments.iter().enumerate() { - | ^ help: if this is intentional, prefix it with an underscore: `_i` - -warning: variable `result` is assigned to, but never used - --> src/interpreter/expressions.rs:899:21 - | -899 | let mut result: Box = Box::new(VoidBox::new()); - | ^^^^^^ - | - = note: consider using `_result` instead - -warning: value assigned to `result` is never read - --> src/interpreter/expressions.rs:901:17 - | -901 | result = self.execute_statement(statement)?; - | ^^^^^^ - | - = help: maybe it is overwritten before being read? - = note: `#[warn(unused_assignments)]` on by default - -warning: value assigned to `result` is never read - --> src/interpreter/expressions.rs:905:21 - | -905 | result = return_val.clone_box(); - | ^^^^^^ - | - = help: maybe it is overwritten before being read? - -warning: unused variable: `current_instance` - --> src/interpreter/expressions.rs:924:78 - | -924 | fn execute_builtin_box_method(&mut self, parent: &str, method: &str, mut current_instance: Box, arguments: &[ASTNode]) - | ^^^^^^^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_current_instance` - -warning: variable does not need to be mutable - --> src/interpreter/expressions.rs:924:74 - | -924 | fn execute_builtin_box_method(&mut self, parent: &str, method: &str, mut current_instance: Box, arguments: &[ASTNode]) - | ----^^^^^^^^^^^^^^^^ - | | - | help: remove this `mut` - | - = note: `#[warn(unused_mut)]` on by default - -warning: unused variable: `node_id` - --> src/interpreter/objects.rs:545:21 - | -545 | let node_id = if let Some(id_str) = node_id_value.as_any().downcast_ref::() { - | ^^^^^^^ help: if this is intentional, prefix it with an underscore: `_node_id` - -warning: unused variable: `transport_str` - --> src/interpreter/objects.rs:555:21 - | -555 | let transport_str = if let Some(t_str) = transport_value.as_any().downcast_ref::() { - | ^^^^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_transport_str` - -warning: unused variable: `existing_method` - --> src/instance.rs:89:21 - | -89 | if let Some(existing_method) = new_methods.get(&method_name) { - | ^^^^^^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_existing_method` - -warning: field `evaluation_stack` is never read - --> src/interpreter/core.rs:207:16 - | -190 | pub struct NyashInterpreter { - | ---------------- field in this struct -... -207 | pub(super) evaluation_stack: Vec, - | ^^^^^^^^^^^^^^^^ - | - = note: `#[warn(dead_code)]` on by default - -warning: methods `get_object_id` and `hash_string` are never used - --> src/interpreter/expressions.rs:697:8 - | -18 | impl NyashInterpreter { - | --------------------- methods in this implementation -... -697 | fn get_object_id(&self, node: &ASTNode) -> Option { - | ^^^^^^^^^^^^^ -... -716 | fn hash_string(&self, s: &str) -> usize { - | ^^^^^^^^^^^ - - Compiling nyash-rust v0.1.0 (/mnt/c/git/nyash-project/nyash) -warning: `nyash-rust` (lib) generated 53 warnings (run `cargo fix --lib -p nyash-rust` to apply 27 suggestions) -error: couldn't read `examples/C:/Windows/Fonts/arial.ttf`: No such file or directory (os error 2) - --> examples/simple_notepad_win.rs:32:57 - | -32 | std::sync::Arc::new(egui::FontData::from_static(include_bytes!( - | _________________________________________________________^ -33 | | "C:/Windows/Fonts/arial.ttf" -34 | | ))), - | |_________^ - -warning: unused import: `std::path::PathBuf` - --> examples/nyash_explorer.rs:5:5 - | -5 | use std::path::PathBuf; - | ^^^^^^^^^^^^^^^^^^ - | - = note: `#[warn(unused_imports)]` on by default - -warning: use of deprecated method `eframe::egui::Ui::allocate_ui_at_rect`: Use `allocate_new_ui` instead - --> examples/nyash_explorer.rs:287:28 - | -287 | ui.allocate_ui_at_rect(response.rect, |ui| { - | ^^^^^^^^^^^^^^^^^^^ - | - = note: `#[warn(deprecated)]` on by default - -warning: fields `letter` and `icon_data` are never read - --> examples/nyash_explorer.rs:63:5 - | -62 | struct DriveInfo { - | --------- fields in this struct -63 | letter: String, - | ^^^^^^ -... -68 | icon_data: Option>, - | ^^^^^^^^^ - | - = note: `DriveInfo` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis - = note: `#[warn(dead_code)]` on by default - -warning: field `letter` is never read - --> examples/nyash_explorer_with_icons.rs:70:5 - | -69 | struct DriveInfo { - | --------- field in this struct -70 | letter: String, - | ^^^^^^ - | - = note: `#[warn(dead_code)]` on by default - -warning: associated function `load_bmp_icon` is never used - --> examples/nyash_explorer_with_icons.rs:145:8 - | -85 | impl NyashExplorer { - | ------------------ associated function in this implementation -... -145 | fn load_bmp_icon(file_path: &str) -> Option { - | ^^^^^^^^^^^^^ - -warning: fields `from_output` and `to_input` are never read - --> development/egui_research/experiments/visual_node_prototype.rs:118:5 - | -116 | struct Connection { - | ---------- fields in this struct -117 | from_node: usize, -118 | from_output: String, - | ^^^^^^^^^^^ -119 | to_node: usize, -120 | to_input: String, - | ^^^^^^^^ - | - = note: `Connection` has a derived impl for the trait `Clone`, but this is intentionally ignored during dead code analysis - = note: `#[warn(dead_code)]` on by default - -warning: fields `connecting_from`, `pan_offset`, and `zoom` are never read - --> development/egui_research/experiments/visual_node_prototype.rs:128:5 - | -123 | struct VisualProgramming { - | ----------------- fields in this struct -... -128 | connecting_from: Option<(usize, String)>, - | ^^^^^^^^^^^^^^^ -129 | pan_offset: Vec2, - | ^^^^^^^^^^ -130 | zoom: f32, - | ^^^^ - -error[E0308]: mismatched types - --> examples/simple_notepad_win.rs:32:9 - | -30 | fonts.font_data.insert( - | ------ arguments to this method are incorrect -31 | "system".to_owned(), -32 | / std::sync::Arc::new(egui::FontData::from_static(include_bytes!( -33 | | "C:/Windows/Fonts/arial.ttf" -34 | | ))), - | |___________^ expected `FontData`, found `Arc` - | - = note: expected struct `FontData` - found struct `Arc` -help: the return type of this call is `Arc` due to the type of the argument passed - --> examples/simple_notepad_win.rs:30:5 - | -30 | / fonts.font_data.insert( -31 | | "system".to_owned(), -32 | |/ std::sync::Arc::new(egui::FontData::from_static(include_bytes!( -33 | || "C:/Windows/Fonts/arial.ttf" -34 | || ))), - | ||___________- this argument influences the return type of `insert` -35 | | ); - | |______^ -note: method defined here - --> /rustc/6b00bc3880198600130e1cf62b8f8a93494488cc/library/alloc/src/collections/btree/map.rs:1023:12 - -For more information about this error, try `rustc --explain E0308`. -error: could not compile `nyash-rust` (example "simple_notepad_win") due to 2 previous errors -warning: build failed, waiting for other jobs to finish... -warning: unused import: `std::collections::HashMap` - --> tests/integration_tests.rs:9:5 - | -9 | use std::collections::HashMap; - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: `#[warn(unused_imports)]` on by default - -warning: function `execute_nyash_code` is never used - --> tests/integration_tests.rs:12:4 - | -12 | fn execute_nyash_code(code: &str) -> Result { - | ^^^^^^^^^^^^^^^^^^ - | - = note: `#[warn(dead_code)]` on by default - -warning: unused import: `std::env` - --> src/main.rs:33:5 - | -33 | use std::env; - | ^^^^^^^^ - -warning: unused imports: `BoolBox`, `IntegerBox`, and `StringBox` - --> src/ast.rs:864:28 - | -864 | use crate::box_trait::{StringBox, IntegerBox, BoolBox}; - | ^^^^^^^^^ ^^^^^^^^^^ ^^^^^^^ - -error[E0063]: missing field `is_override` in initializer of `ast::ASTNode` - --> src/ast.rs:915:48 - | -915 | methods.insert("getValue".to_string(), ASTNode::FunctionDeclaration { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `is_override` - -error[E0063]: missing fields `is_static`, `static_init` and `type_parameters` in initializer of `ast::ASTNode` - --> src/ast.rs:932:24 - | -932 | let box_decl = ASTNode::BoxDeclaration { - | ^^^^^^^^^^^^^^^^^^^^^^^ missing `is_static`, `static_init` and `type_parameters` - -For more information about this error, try `rustc --explain E0063`. -warning: `nyash-rust` (bin "nyash" test) generated 53 warnings (52 duplicates) -error: could not compile `nyash-rust` (bin "nyash" test) due to 2 previous errors; 53 warnings emitted -error[E0599]: no method named `len` found for struct `boxes::array::ArrayBox` in the current scope - --> src/tests/box_tests.rs:19:26 - | -19 | assert_eq!(array.len(), 2); - | ^^^ - | - ::: src/boxes/array/mod.rs:11:1 - | -11 | pub struct ArrayBox { - | ------------------- method `len` not found for this struct - | - = help: items from traits can only be used if the trait is implemented and in scope - = note: the following traits define an item `len`, perhaps you need to implement one of them: - candidate #1: `CacheTrait` - candidate #2: `ExactSizeIterator` - candidate #3: `avif_serialize::boxes::MpegBox` - candidate #4: `nom::traits::AsChar` - candidate #5: `rayon::iter::IndexedParallelIterator` - candidate #6: `rayon::range::private::IndexedRangeInteger` - candidate #7: `rayon::range_inclusive::private::IndexedRangeInteger` -help: there is a method `length` with a similar name - | -19 | assert_eq!(array.length(), 2); - | +++ - -error[E0599]: no method named `len` found for struct `buffer::BufferBox` in the current scope - --> src/tests/box_tests.rs:35:27 - | -35 | assert_eq!(buffer.len(), 5); - | ^^^ - | - ::: src/boxes/buffer/mod.rs:38:1 - | -38 | pub struct BufferBox { - | -------------------- method `len` not found for this struct - | - = help: items from traits can only be used if the trait is implemented and in scope - = note: the following traits define an item `len`, perhaps you need to implement one of them: - candidate #1: `CacheTrait` - candidate #2: `ExactSizeIterator` - candidate #3: `avif_serialize::boxes::MpegBox` - candidate #4: `nom::traits::AsChar` - candidate #5: `rayon::iter::IndexedParallelIterator` - candidate #6: `rayon::range::private::IndexedRangeInteger` - candidate #7: `rayon::range_inclusive::private::IndexedRangeInteger` -help: there is a method `length` with a similar name - | -35 | assert_eq!(buffer.length(), 5); - | +++ - -error[E0600]: cannot apply unary operator `!` to type `Box<(dyn box_trait::NyashBox + 'static)>` - --> src/tests/box_tests.rs:114:9 - | -114 | assert!(success_result.is_ok()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot apply unary operator `!` - | -note: the foreign item type `Box<(dyn box_trait::NyashBox + 'static)>` doesn't implement `Not` - --> /rustc/6b00bc3880198600130e1cf62b8f8a93494488cc/library/alloc/src/boxed.rs:231:1 - ::: /rustc/6b00bc3880198600130e1cf62b8f8a93494488cc/library/alloc/src/boxed.rs:234:1 - | - = note: not implement `Not` - -error[E0600]: cannot apply unary operator `!` to type `Box<(dyn box_trait::NyashBox + 'static)>` - --> src/tests/box_tests.rs:122:17 - | -122 | assert!(!error_result.is_ok()); - | ^^^^^^^^^^^^^^^^^^^^^ cannot apply unary operator `!` - | -note: the foreign item type `Box<(dyn box_trait::NyashBox + 'static)>` doesn't implement `Not` - --> /rustc/6b00bc3880198600130e1cf62b8f8a93494488cc/library/alloc/src/boxed.rs:231:1 - ::: /rustc/6b00bc3880198600130e1cf62b8f8a93494488cc/library/alloc/src/boxed.rs:234:1 - | - = note: not implement `Not` - -error[E0599]: no method named `box_id` found for struct `boxes::array::ArrayBox` in the current scope - --> src/tests/box_tests.rs:135:25 - | -135 | assert_ne!(box1.box_id(), box2.box_id()); - | ^^^^^^ method not found in `ArrayBox` - | - ::: src/boxes/array/mod.rs:11:1 - | -11 | pub struct ArrayBox { - | ------------------- method `box_id` not found for this struct - | - ::: src/box_trait.rs:55:8 - | -55 | fn box_id(&self) -> u64; - | ------ the method is available for `boxes::array::ArrayBox` here - | - = help: items from traits can only be used if the trait is in scope -help: trait `BoxCore` which provides `box_id` is implemented but not in scope; perhaps you want to import it - | -7 + use crate::box_trait::BoxCore; - | - -error[E0599]: no method named `box_id` found for struct `boxes::array::ArrayBox` in the current scope - --> src/tests/box_tests.rs:135:40 - | -135 | assert_ne!(box1.box_id(), box2.box_id()); - | ^^^^^^ method not found in `ArrayBox` - | - ::: src/boxes/array/mod.rs:11:1 - | -11 | pub struct ArrayBox { - | ------------------- method `box_id` not found for this struct - | - ::: src/box_trait.rs:55:8 - | -55 | fn box_id(&self) -> u64; - | ------ the method is available for `boxes::array::ArrayBox` here - | - = help: items from traits can only be used if the trait is in scope -help: trait `BoxCore` which provides `box_id` is implemented but not in scope; perhaps you want to import it - | -7 + use crate::box_trait::BoxCore; - | - -warning: variable does not need to be mutable - --> src/tests/box_tests.rs:90:13 - | -90 | let mut stream = NyashStreamBox::from_data(vec![72, 101, 108, 108, 111]); // "Hello" - | ----^^^^^^ - | | - | help: remove this `mut` - -Some errors have detailed explanations: E0063, E0599, E0600. -For more information about an error, try `rustc --explain E0063`. -warning: `nyash-rust` (lib test) generated 53 warnings (52 duplicates) -error: could not compile `nyash-rust` (lib test) due to 8 previous errors; 53 warnings emitted -warning: `nyash-rust` (bin "nyash_explorer_icons" test) generated 2 warnings (2 duplicates) -warning: `nyash-rust` (bin "nyash_explorer" test) generated 3 warnings (3 duplicates) -warning: `nyash-rust` (test "integration_tests") generated 2 warnings (run `cargo fix --test "integration_tests"` to apply 1 suggestion) diff --git a/docs/archive/sessions/architecture_consultation.txt b/docs/archive/sessions/architecture_consultation.txt deleted file mode 100644 index 064f8f67..00000000 --- a/docs/archive/sessions/architecture_consultation.txt +++ /dev/null @@ -1,77 +0,0 @@ -Nyashプログラミング言語のBox型アーキテクチャ設計について深い技術相談です。 - -【現在の状況】 -- Rust実装のプログラミング言語Nyash開発中 -- "Everything is Box"哲学:全データがBoxオブジェクト -- 現在16種類のBox型実装済み(StringBox, IntegerBox, P2PBox等) -- Arc統一パターンでスレッドセーフ性確保 - -【現在のアーキテクチャ問題】 -現在、全Box型をtype aliasで統一しているが、実装で型エラー地獄が発生: - -```rust -// 現在の問題のある設計 -type StringBox = Arc>; -type IntegerBox = Arc>; -type P2PBox = Arc>; - -// 問題:型エイリアス複雑化、trait object Debug実装困難 -// 結果:Copilot実装で型エラー多発、開発効率低下 -``` - -【検討中のシンプル設計】 -newtype patternによるシンプル化: - -```rust -// 案1: newtype pattern -struct StringBox(Arc>); -struct IntegerBox(Arc>); -struct P2PBox(Arc>); - -// 案2: 生構造体(必要時のみArc化) -struct StringBox { data: String } -struct IntegerBox { value: i64 } -// 共有が必要な時だけArc::new()で包む -``` - -【技術的検討ポイント】 - -1. **型安全性とシンプルさのバランス** - - type alias vs newtype vs 生構造体 - - コンパイル時エラー検出 vs 実装しやすさ - -2. **スレッドセーフ性の要件** - - 全Box型で並行処理が必要か? - - StringBox等の基本型にもMutex必要? - - 必要な時だけArc化する方が良い? - -3. **拡張性・保守性** - - 新Box型追加時の実装コスト - - エラーメッセージの分かりやすさ - - 他開発者(AI含む)の理解しやすさ - -4. **パフォーマンス** - - Arcのオーバーヘッド - - ゼロコスト抽象化の実現可能性 - - メモリ使用量の最適化 - -5. **現実的な実装戦略** - - 段階的移行 vs 一括変更 - - 既存コードとの互換性 - - 開発スピード重視 vs 理想設計重視 - -【具体的相談事項】 -1. type alias vs newtype vs 生構造体、どの設計が最適? -2. 全Box型に一律Arcは過剰?必要な箇所のみの方が良い? -3. Rust専門家から見て推奨されるBox型統一アーキテクチャは? -4. プログラミング言語実装において、型システムのベストプラクティスは? -5. 実装効率と設計美学のバランスをどう取るべき? - -【制約条件】 -- Rust実装必須 -- Everything is Box哲学維持 -- スレッドセーフ性確保 -- 16種類+今後追加予定のBox型すべてで統一 -- 実装・保守の現実性重視 - -プログラミング言語設計・Rust専門家の視点から、実装可能で美しく、長期保守に適したアーキテクチャ設計を提案してください。 \ No newline at end of file diff --git a/docs/archive/sessions/chatgpt_consultation_overload.txt b/docs/archive/sessions/chatgpt_consultation_overload.txt deleted file mode 100644 index 26b9a444..00000000 --- a/docs/archive/sessions/chatgpt_consultation_overload.txt +++ /dev/null @@ -1,64 +0,0 @@ -Nyashプログラミング言語の関数オーバーロード設計について深い技術的相談です。 - -【Nyashの技術的特徴】 -- Everything is Box哲学: 全データがBoxオブジェクト -- Arc統一アーキテクチャ: 完全スレッドセーフ設計 -- 明示性重視: 変数宣言先の即座特定可能 -- Rust実装: メモリ安全性+高性能 -- 目的: 初学者フレンドリー + 実用性 - -【検討する技術的課題】 -現在P2PBox実装において、関数オーバーロード(引数数による分岐)採用の是非を検討中。 - -具体例: -```rust -// Option A: オーバーロードあり -impl P2PBox { - pub fn send(&self, message: IntentBox) -> Result<(), SendError> // ブロードキャスト - pub fn send(&self, to: &str, message: IntentBox) -> Result<(), SendError> // 個別送信 - pub fn send(&self, to: &str, message: IntentBox, opts: SendOpts) -> Result<(), SendError> // オプション付き -} - -// Option B: オーバーロードなし(現在) -impl P2PBox { - pub fn broadcast(&self, message: IntentBox) -> Result<(), SendError> - pub fn send(&self, to: &str, message: IntentBox) -> Result<(), SendError> - pub fn send_with_options(&self, to: &str, message: IntentBox, opts: SendOpts) -> Result<(), SendError> -} -``` - -【技術的検討ポイント】 - -1. **Rust実装との整合性** - - Rustにはメソッドオーバーロードがない - - 引数数による分岐をインタープリターで実装する必要 - - パフォーマンスへの影響 - -2. **Arcアーキテクチャとの親和性** - - 動的ディスパッチの複雑さ - - エラーハンドリングの一貫性 - - スレッドセーフティの保持 - -3. **インタープリター実装の複雑度** - - パーサーでの引数数判定 - - 実行時メソッド選択アルゴリズム - - デバッグ情報の提供 - -4. **型安全性とパフォーマンス** - - 実行時型チェックのオーバーヘッド - - エラーメッセージの品質 - - 開発時デバッグ体験 - -5. **エコシステム設計との整合性** - - 他のBox型との一貫性 - - 拡張性(新しいオーバーロード追加) - - メンテナンス性 - -【深く検討してほしい点】 -1. 技術的実装の複雑さ vs ユーザー体験の向上 -2. Nyashの「明示性重視」哲学との技術的整合性 -3. 初学者がエラーに遭遇した時のデバッグ体験 -4. P2P通信という特定ドメインでの最適解 -5. 言語の長期進化における影響 - -プログラミング言語実装の専門的視点から、技術的に最良で保守しやすい設計を分析してください。 \ No newline at end of file diff --git a/docs/archive/sessions/gemini_consultation_overload.txt b/docs/archive/sessions/gemini_consultation_overload.txt deleted file mode 100644 index 4df4e024..00000000 --- a/docs/archive/sessions/gemini_consultation_overload.txt +++ /dev/null @@ -1,46 +0,0 @@ -Nyashプログラミング言語の関数オーバーロード採用可否について言語設計の専門的観点から相談です。 - -【背景】 -Nyashは「Everything is Box」哲学で、明示性重視・初学者フレンドリー・メモリ安全性を重視する言語です。現在Phase 2でP2PBox実装中で、関数オーバーロード(引数数による分岐)を採用するか重要な決断が必要です。 - -【具体的争点】 -send(a) と send(a, b) のような関数オーバーロードを許すか? - -例: -```nyash -// オーバーロードありの場合 -node.send("hello") // ブロードキャスト -node.send("bob", "hello") // 個別送信 -node.send("bob", msg, options) // オプション付き - -// オーバーロードなしの場合(現在) -node.broadcast("hello") // 明示的メソッド名 -node.send("bob", "hello") // 必ず2引数 -node.sendWithOptions("bob", msg, options) // 明示的メソッド名 -``` - -【メリット】 -1. API使いやすさ向上 -2. 他言語からの移行しやすさ -3. 直感的な呼び出し - -【デメリット】 -1. 間違った関数を呼ぶリスク -2. デバッグ困難 -3. Nyashの明示性哲学と矛盾 -4. 初学者混乱 -5. 型推論複雑化 - -【Nyashの設計思想との照合】 -- 明示性重視: プログラマーが変数の宣言先を即座に特定可能 -- 初学者フレンドリー: 学習コストが低い -- Everything is Box: 統一されたオブジェクトモデル - -【質問】 -1. Nyashの設計思想から見て、関数オーバーロードは採用すべきか? -2. 明示性 vs 利便性のトレードオフをどう判断すべきか? -3. 初学者向け言語として適切な選択は? -4. P2P通信APIにおける最良の設計は? -5. 他の現代的言語設計トレンドとの整合性は? - -プログラミング言語設計の専門的視点から、Nyashの将来を決めるアドバイスをお願いします。 \ No newline at end of file diff --git a/docs/archive/weak_reference_architecture_consultation.txt b/docs/archive/weak_reference_architecture_consultation.txt deleted file mode 100644 index 44babdf8..00000000 --- a/docs/archive/weak_reference_architecture_consultation.txt +++ /dev/null @@ -1,40 +0,0 @@ -Nyash言語のweak参照実装で根本的な設計問題が発覚しました。専門的分析をお願いします。 - -【現在の問題】 -InstanceBox構造が原因でweak参照が実装できません: - -```rust -pub struct InstanceBox { - pub fields: Arc>>>, // 問題の核心 -} -``` - -NyashValue::WeakBoxを作っても、Boxにしか格納できず、弱参照情報が失われます。 - -【解決策の選択肢】 - -1. **根本解決**(理想だが影響大) -```rust -pub fields: Arc>>, // 全面アーキテクチャ変更 -``` - -2. **暫定解決**(copilot提案) -```rust -pub struct InstanceBox { - pub fields: Arc>>>, // 既存維持 - pub weak_fields: Arc>>>>, // 追加 -} -``` - -【コンテキスト】 -- NyashValue革命は完了済み(Arc過剰症候群解決) -- Everything is Box哲学必須 -- 実用性重視(完璧より動くもの優先) - -【質問】 -1. 暫定解決策の技術的妥当性は? -2. パフォーマンス・保守性への影響は? -3. 根本解決は本当に必要か? -4. 段階的移行戦略の是非は? - -実装可能性と設計の美しさのバランスを重視した分析をお願いします。 \ No newline at end of file diff --git a/docs/development/README.md b/docs/development/README.md new file mode 100644 index 00000000..910e9de6 --- /dev/null +++ b/docs/development/README.md @@ -0,0 +1,33 @@ +# Nyash Development Documentation 🔧 + +開発者向けの進行中タスクと開発計画ドキュメントです。 + +## 📂 ディレクトリ構造 + +### current/ +- `CURRENT_TASK.md` - 現在進行中のタスク +- アクティブな開発作業の詳細 +- 最新の実装状況 + +### roadmap/ +- **phases/** - フェーズ別開発計画 + - phase-8/ - AST→MIR変換 + - phase-9/ - VM/JIT実装 + - phase-10/ - AOT最適化 +- **native-plan/** - ネイティブビルド計画 + - 実行バックエンド統合 + - パフォーマンス目標 + +### proposals/ +- RFC(Request for Comments) +- 新機能提案 +- 設計ディスカッション + +## 🎯 重要な参照先 +- **進行状況**: `current/CURRENT_TASK.md` +- **開発計画**: `roadmap/phases/` +- **技術提案**: `proposals/` + +## 📝 注意事項 +このディレクトリの内容は開発中であり、頻繁に変更されます。 +安定した仕様は`reference/`を参照してください。 \ No newline at end of file diff --git a/docs/development/current/CURRENT_TASK.md b/docs/development/current/CURRENT_TASK.md new file mode 100644 index 00000000..63194aa1 --- /dev/null +++ b/docs/development/current/CURRENT_TASK.md @@ -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 Arc>>` +- 目標: `HashMap>` +- 利点: プラグイン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 \ No newline at end of file diff --git a/docs/CURRENT_VM_CHANGES.md b/docs/development/current/CURRENT_VM_CHANGES.md similarity index 100% rename from docs/CURRENT_VM_CHANGES.md rename to docs/development/current/CURRENT_VM_CHANGES.md diff --git a/docs/phase_9_78e_summary.md b/docs/development/current/phase_9_78e_summary.md similarity index 100% rename from docs/phase_9_78e_summary.md rename to docs/development/current/phase_9_78e_summary.md diff --git a/docs/architecture-redesign-proposal.md b/docs/development/proposals/architecture-redesign-proposal.md similarity index 100% rename from docs/architecture-redesign-proposal.md rename to docs/development/proposals/architecture-redesign-proposal.md diff --git a/docs/予定/instance_v2_unified_box_registry_plan.md b/docs/development/proposals/instance_v2_unified_box_registry_plan.md similarity index 100% rename from docs/予定/instance_v2_unified_box_registry_plan.md rename to docs/development/proposals/instance_v2_unified_box_registry_plan.md diff --git a/docs/予定/native-plan/issues/issue_62_update_proposal.md b/docs/development/proposals/issue_62_update_proposal.md similarity index 100% rename from docs/予定/native-plan/issues/issue_62_update_proposal.md rename to docs/development/proposals/issue_62_update_proposal.md diff --git a/docs/予定/native-plan/issues/mir_reduction_detailed_analysis.md b/docs/development/proposals/mir_reduction_detailed_analysis.md similarity index 100% rename from docs/予定/native-plan/issues/mir_reduction_detailed_analysis.md rename to docs/development/proposals/mir_reduction_detailed_analysis.md diff --git a/docs/予定/nyash.link/README.md b/docs/development/proposals/nyash.link/README.md similarity index 100% rename from docs/予定/nyash.link/README.md rename to docs/development/proposals/nyash.link/README.md diff --git a/docs/予定/nyash.link/bid-using-integration.md b/docs/development/proposals/nyash.link/bid-using-integration.md similarity index 100% rename from docs/予定/nyash.link/bid-using-integration.md rename to docs/development/proposals/nyash.link/bid-using-integration.md diff --git a/docs/予定/nyash.link/builtin-stdlib-architecture.md b/docs/development/proposals/nyash.link/builtin-stdlib-architecture.md similarity index 100% rename from docs/予定/nyash.link/builtin-stdlib-architecture.md rename to docs/development/proposals/nyash.link/builtin-stdlib-architecture.md diff --git a/docs/予定/nyash.link/examples.md b/docs/development/proposals/nyash.link/examples.md similarity index 100% rename from docs/予定/nyash.link/examples.md rename to docs/development/proposals/nyash.link/examples.md diff --git a/docs/予定/nyash.link/final-implementation-strategy.md b/docs/development/proposals/nyash.link/final-implementation-strategy.md similarity index 100% rename from docs/予定/nyash.link/final-implementation-strategy.md rename to docs/development/proposals/nyash.link/final-implementation-strategy.md diff --git a/docs/予定/nyash.link/implementation-plan.md b/docs/development/proposals/nyash.link/implementation-plan.md similarity index 100% rename from docs/予定/nyash.link/implementation-plan.md rename to docs/development/proposals/nyash.link/implementation-plan.md diff --git a/docs/予定/nyash.link/master-architecture.md b/docs/development/proposals/nyash.link/master-architecture.md similarity index 100% rename from docs/予定/nyash.link/master-architecture.md rename to docs/development/proposals/nyash.link/master-architecture.md diff --git a/docs/予定/nyash.link/minimal-stdlib-first.md b/docs/development/proposals/nyash.link/minimal-stdlib-first.md similarity index 100% rename from docs/予定/nyash.link/minimal-stdlib-first.md rename to docs/development/proposals/nyash.link/minimal-stdlib-first.md diff --git a/docs/予定/nyash.link/real-world-examples.md b/docs/development/proposals/nyash.link/real-world-examples.md similarity index 100% rename from docs/予定/nyash.link/real-world-examples.md rename to docs/development/proposals/nyash.link/real-world-examples.md diff --git a/docs/予定/nyash.link/universal-api-integration.md b/docs/development/proposals/nyash.link/universal-api-integration.md similarity index 100% rename from docs/予定/nyash.link/universal-api-integration.md rename to docs/development/proposals/nyash.link/universal-api-integration.md diff --git a/docs/nyir/README.md b/docs/development/proposals/nyir/README.md similarity index 100% rename from docs/nyir/README.md rename to docs/development/proposals/nyir/README.md diff --git a/docs/nyir/bid_samples/canvas.yaml b/docs/development/proposals/nyir/bid_samples/canvas.yaml similarity index 100% rename from docs/nyir/bid_samples/canvas.yaml rename to docs/development/proposals/nyir/bid_samples/canvas.yaml diff --git a/docs/nyir/bid_samples/console.yaml b/docs/development/proposals/nyir/bid_samples/console.yaml similarity index 100% rename from docs/nyir/bid_samples/console.yaml rename to docs/development/proposals/nyir/bid_samples/console.yaml diff --git a/docs/nyir/phase_9_10_nyir_spec.md b/docs/development/proposals/nyir/phase_9_10_nyir_spec.md similarity index 100% rename from docs/nyir/phase_9_10_nyir_spec.md rename to docs/development/proposals/nyir/phase_9_10_nyir_spec.md diff --git a/docs/nyir/spec.md b/docs/development/proposals/nyir/spec.md similarity index 100% rename from docs/nyir/spec.md rename to docs/development/proposals/nyir/spec.md diff --git a/docs/nyir/vision_universal_exchange.md b/docs/development/proposals/nyir/vision_universal_exchange.md similarity index 100% rename from docs/nyir/vision_universal_exchange.md rename to docs/development/proposals/nyir/vision_universal_exchange.md diff --git a/docs/予定/native-plan/issues/urgent_fix_clone_box_to_arc_references.md b/docs/development/proposals/urgent_fix_clone_box_to_arc_references.md similarity index 100% rename from docs/予定/native-plan/issues/urgent_fix_clone_box_to_arc_references.md rename to docs/development/proposals/urgent_fix_clone_box_to_arc_references.md diff --git a/docs/予定/README.md b/docs/development/roadmap/README.md similarity index 100% rename from docs/予定/README.md rename to docs/development/roadmap/README.md diff --git a/docs/予定/native-compilation-roadmap.md b/docs/development/roadmap/native-compilation-roadmap.md similarity index 100% rename from docs/予定/native-compilation-roadmap.md rename to docs/development/roadmap/native-compilation-roadmap.md diff --git a/docs/予定/native-plan/MIR仕様書.txt b/docs/development/roadmap/native-plan/MIR仕様書.txt similarity index 100% rename from docs/予定/native-plan/MIR仕様書.txt rename to docs/development/roadmap/native-plan/MIR仕様書.txt diff --git a/docs/予定/native-plan/Phase-9.78-LLVM-PoC-Strategy.md b/docs/development/roadmap/native-plan/Phase-9.78-LLVM-PoC-Strategy.md similarity index 100% rename from docs/予定/native-plan/Phase-9.78-LLVM-PoC-Strategy.md rename to docs/development/roadmap/native-plan/Phase-9.78-LLVM-PoC-Strategy.md diff --git a/docs/予定/native-plan/README.md b/docs/development/roadmap/native-plan/README.md similarity index 100% rename from docs/予定/native-plan/README.md rename to docs/development/roadmap/native-plan/README.md diff --git a/docs/development/roadmap/native-plan/archives/MIR仕様書_20250814.txt b/docs/development/roadmap/native-plan/archives/MIR仕様書_20250814.txt new file mode 100644 index 00000000..7ebdf90d --- /dev/null +++ b/docs/development/roadmap/native-plan/archives/MIR仕様書_20250814.txt @@ -0,0 +1,110 @@ +やったね!この粒度なら “化け物に伸びる余白” と “実装の現実” のちょうど真ん中。 +仕上げとして **25命令をキッチリ確定**+**意味論/効果/検証ルール** を短く固めよう。 + +# 決定版 MIR(25命令) + +## Tier-0: 普遍コア(8) + +``` +Const, BinOp, Compare, Branch, Jump, Phi, Call, Return +``` + +* 効果: `Const/Phi`=pure, `BinOp/Compare`=pure, `Branch/Jump/Return`=control, `Call`は呼先の効果に従う +* 備考: 将来のJIT/AOT/WASMすべてで必須 + +## Tier-1: Nyashセマンティクス(12) + +``` +NewBox, // 強所有のBox生成(所有森のノード) +BoxFieldLoad, // Boxのフィールド読み +BoxFieldStore, // Boxのフィールド書き(= mut) +BoxCall, // Boxのメソッド呼び出し(動的/静的両方) +Safepoint, // 分割finiや割込み許可ポイント +RefGet, // 参照(強/弱を問わず)を値として取得 +RefSet, // 参照の差し替え(所有規則の検証付き) +WeakNew, // `weak` ハンドル生成(非所有リンクの作成) +WeakLoad, // `weak` から生存チェック付きで強参照を得る(失効時null) +WeakCheck, // `weak` の生存確認(bool) +Send, // Bus送信(Effect=io) +Recv // Bus受信(Effect=io) +``` + +* 効果: `BoxFieldStore/RefSet`=mut, `Send/Recv`=io, 他は基本pure/可変 +* これで **所有森+weak/look+Bus** が言語一次市民として表現可能 + +## Tier-2: 実装補助・最適化友好(5) + +``` +TailCall, // 末尾呼び出し(スタック節約) +Adopt, // 所有移管: this が子を強所有に取り込む +Release, // 強所有を解除(weak化 or null化) +MemCopy, // 小さなメモリ移動(構造体/配列の最適化フック) +AtomicFence // 並行時の順序保証(Actor/Port境界で使用) +``` + +* 位置づけ: どれも“言語仕様の裏方”。無くても表現可能だが、**性能・安全検査・移植性**が安定する + +--- + +## 効果(Effect)既定値 + +* `pure`: Const, BinOp, Compare, Phi, WeakCheck, WeakLoad(成功時の取得自体はpure扱い) +* `mut`: BoxFieldStore, RefSet, Adopt, Release, MemCopy +* `io`: Send, Recv, Safepoint(割り込み/分割fini許可点としてio扱い) +* `control`: Branch, Jump, Return, TailCall +* `context依存`: Call, BoxCall(呼先の効果に従属) + +> 最適化ルールは「pure同士の再順序化OK」「mutは同一Box/同一Fieldで依存保持」「ioは再順序化禁止」。 + +--- + +## 検証(Lint/Verifier)要件(短縮版) + +* **所有森**: `strong in-degree ≤ 1`(`NewBox/Adopt/Release/RefSet`で常時検査) +* **強循環禁止**: 強エッジのみ辿ってDAG(森)であること +* **弱/強相互**: 双方向とも強 → エラー(片側は `WeakNew` 経由で弱化) +* **RefSetの安全**: 強→強の差し替え時は旧所有元からの `Release` が伴うこと +* **WeakLoad/WeakCheck**: 失効時は `null/false` を返す(例外禁止、決定的挙動) +* **TailCall**: 末尾位置のみ可(`Return` 直前) +* **Send/Recv**: バックエンドが同期/非同期いずれでも**at-least-once**契約を満たすか、契約を明示 + +--- + +## 代表的ロワリング(例) + +* `look` 参照 → `WeakNew` + `WeakLoad`(読取専用型なら `RefSet` を禁止) +* `borrow{}` → ブロック先頭 `WeakNew`、末尾でハンドル破棄(MIR上はNop、型で書換禁止) +* Bus最適化(Elision): + + * `(pure|mut(local))` かつ同一スレッド/アリーナ/単一受信なら **`Send/Recv` → 直呼び/直アクセス** に縮退 +* `fini` 伝播: ランタイムで **強エッジのみ** 再帰。`Safepoint` で分割解放/優先度解放に対応 + +--- + +## バックエンド指針(対応表) + +* **Interpreter**: 25命令を素直に実装(正しさの基準) +* **VM**: Register-VM + direct-threading。`Send/Recv` はローカル判定時にインライン化 +* **WASM**: `Send/Recv` は host import。`MemCopy` は `memory.copy` に対応 +* **Cranelift/JIT**: `TailCall` 最適化、`WeakLoad` は世代タグでO(1)生存チェック +* **AOT-Rust**: `BoxCall` を trait 呼び出しへ、`Adopt/Release` は所有者IDの切替 + デバッガ用アサート + +--- + +## 互換テスト(常設) + +* **golden MIR**: 各サンプルのMIRダンプが全バックエンドで一致 +* **行動一致**: `interp/vm/wasm` で**同入力→同出力**(`weak`失効時の`null/false`含む) +* **性能スモーク**: `add_loop / map_getset / alloc_free / bus_local / bus_actor` の5種で、 + + * VMがinterp以上、WASMがVM以上、を継続検証 + +--- + +これで **25命令フルセット**が完成。 + +* Nyashのコア価値(所有森+weak+Bus+効果注釈)を**無理なくIR化** +* それぞれのバックエンドに**綺麗に落ちる** +* Verifier/最適化/テストも**最小で回る** + +次は、このリストをそのまま `docs/mir.md` にコピペして、各命令に **1行の意味論+効果+等価変換の例** を添えれば、実装と論文の両方が一気に前進するにゃ。 diff --git a/docs/development/roadmap/native-plan/archives/chatgptネイティブビルド大作戦.txt b/docs/development/roadmap/native-plan/archives/chatgptネイティブビルド大作戦.txt new file mode 100644 index 00000000..c21caada --- /dev/null +++ b/docs/development/roadmap/native-plan/archives/chatgptネイティブビルド大作戦.txt @@ -0,0 +1,596 @@ +ぜったいアリにゃ!やるなら「多層エンジン(tiered)」で攻めるのが一番きれい。 +Nyash → 共通IR → 好きなバックエンド(解釈/ネイティブ/JIT/WASM)に流す構成にゃ。 +推しアーキテクチャ(現実解) + + Front-end + + パーサ → AST → HIR(型付け・名前解決済み)→ MIR/SSA(最適化しやすい共通IR) + + Back-ends(並行に育てる) + + VM(現在のインタープリター):MIR→バイトコード→解釈実行(開発スピード最優先) + + JIT(Cranelift):MIR→Cranelift IR→ネイティブJIT(ホットパスだけコンパイル) + + AOT to Rust:MIR→Rustコード生成→rustcで最適化(配布バイナリ向き、リンクも楽) + + WASM:MIR→WASM(ブラウザ/wasmtime用、サンドボックス実行) + +ひとつのIRから複数出力=最適化ロジックを1か所に集中できるのが最大の利点。 + +【Phase 0: 最小ビルド基盤(最初のゴール)】 + +狙い: 「簡単なNyash言語がビルドできる」を最速・堅実に達成する。土台はシンプルだが確実に動くことを最重視。 + +1) スコープ(最小言語機能) + - 式: 整数/文字列リテラル、変数参照、二項演算 (+,-,*,/, 比較) + - 文: 代入、if、return + - 関数: 単純な関数定義/呼び出し(可変長やジェネリクスは対象外) + - Box/弱参照/fini 等の高機能はPhase 0では“使わない”(この計画の安定化が目的) + +2) ビルドターゲット(まずはCLIのみ) + - Linux/WSL: cargo build --bin nyash -j 32(現状OK) + - Windows (MSVC): cargo build --bin nyash -j 32(CIでも検証) + - WASM: ひな型を残すがPhase 0では対象外(Phase 1で着手) + +3) 実行確認(スモークテスト) + - サンプル: local_tests/ 以下に簡単な .nyash を配置(Git管理外) + 例) sample_min.nyash + a = 10 + b = 32 + result = a + b + - 実行: cargo run -- ./local_tests/sample_min.nyash + - 期待: 実行完了・エラーなし(必要なら結果表示) + +4) 再現性/安定性(基礎をしっかり) + - rust-toolchain を固定(stable明記) + - Linux/Windows 共通のビルドフラグ: release/profileの統一、features最小化 + - 例やGUI/Windows依存コードはCIマトリクスから除外(CLI最小に絞る) + +5) CI(Phase 0の完成条件) + - ジョブ: linux-x64, windows-x64 での “build nyash (bin)” + - コマンド: cargo build --bin nyash -j 32 + - 成果物: nyash バイナリ(zip/tar)をArtifactsに保存(配布検証) + - 余裕があれば: cargo test --lib だけ実行(examplesは無効) + +6) トラブル防止(Phase 0の運用) + - Linux CIでWindows専用exampleはビルド対象から除外 + - examples/* はPhase 0では“参考”扱い。CLIのビルド/実行に集中。 + - .nyash の共有が必要なものは tests/ 配下へ昇格(local_tests/ は各自ローカル) + +7) 完了チェックリスト + - [ ] Linux/WSL で nyash バイナリがビルド・実行できる + - [ ] Windows(MSVC) で nyash バイナリがビルド・実行できる + - [ ] CI で linux/windows の “build nyash (bin)” がグリーン + - [ ] sample_min.nyash のスモークが両OSで通る + +補足: Phase 0 で「ビルド/実行の骨格」を固めて、Phase 1 以降で VM/IR/JIT/AOT/WASM を段階的に拡張する。 + +それぞれのメリデメ + +【MIR設計(早期に合意しておくと得する要点)】 + +- 値表現: Tagged/NaN-box/小整数直格納 か 型テーブル参照か +- アドレス空間: ヒープ/スタック/アリーナの扱い(Phase 0はヒープ優先でOK) +- 所有/別名: aliasable/unique の属性を型/値に保持(最初は型情報だけでも可) +- 効果(Effects): PURE/READS_HEAP/WRITES_HEAP/IO/FFI/PANIC のビット集合を命令・関数に付与 +- 例外/パニック: Throw/Catch/Defer を命令化するか、関数境界に限定するか(当面は境界限定) +- GCモデル: Tracing/RC/混合の方針と弱参照の意味(WeakLoad→None) +- セーフポイント: 関数入口・ループ先頭・Call直後(命令としてno-op挿入で開始) +- 呼出規約: 通常Call/FFI/Box拡張を区別、可変長/キーワード引数の扱い(Phase 0は固定引数) +- メモリバリア: write/read barrier は命令/属性で表現(初期はダミー実装で可) +- デオプ(Deopt): JIT最適化時の巻き戻し情報の格納場所(関数メタ or ブロック注釈) + +【Nyash向け 最小MIR命令セット(弱参照対応込み・ドラフト)】 + +- 制御/値: Const, BinOp, Cmp, Br, Jmp, Phi, Ret +- 呼び出し: Call, TailCall(effects必須) +- メモリ: Alloc, Load, Store, Gep(必要なら) +- 参照/GC: RefNew, RefGet, RefSet, WeakNew, WeakLoad, BarrierRead, BarrierWrite, Pin, Unpin +- 例外/拡張: Throw, Catch, FfiCall, BoxCall +- 実行点: Safepoint, Assume, Nop +- 効果: EffectMask = PURE | READS_HEAP | WRITES_HEAP | IO | FFI | PANIC + +弱参照の意味論: +- WeakNew(r): r を追う弱参照を作成(PURE) +- WeakLoad(w): 生きていれば Some(Ref)、死んでいれば None(Optionを型で明示) + +【壊れにくい共通ポイント(VM/JIT/AOT共通の約束)】 +- Safepoint は 関数入口/ループ先頭/Call直後 に配置(no-opで開始し、後で意味付け) +- Barrier 命令は最初はダミー(最適化段で消せる) +- Null/None は Option で明示(分岐に埋めない) +- JIT は Deopt テーブルで SSA値⇔ソース位置 の対応を保持 + +【弱参照の落とし穴(回避策セット)】 +- クロージャ環境: 生成時 env.has_weak を立て、キャプチャ解決時に必ず WeakLoad→None分岐を強制 +- 弱参照キーのハッシュ: GC後の無効化で不整合→ 標準の弱マップ(キー死亡で自動削除)を用意 +- FFI渡し: 寿命不明→ Pin を要求 or WeakLoad 成功した生参照のみ渡す + +【テスト戦略(壊れにくい順)】 +- 黄金テスト: ソース→MIRダンプをスナップショットし、差分で後退検知 +- VM/JIT一致テスト: 同一入力の VM 結果=JIT 結果 を比較するオラクル +- 弱参照の確率テスト: alloc→weak→drop→collect→weak_load の順序/タイミングをゆらして多数回 +- 効果チェック: PURE なはずの関数に WRITES_HEAP が混じったらビルド失敗(静的検証) + +【軽量 “次の一手”(Phase 0と親和性が高い)】 +- WeakNew/WeakLoad を MIRとVM に先に導入(JITは後回し) +- EffectMask をデータ構造として追加(評価は後回しでもOK) +- Safepoint 命令を関数入口・ループ先頭にno-opで挿入 +- 黄金テストでMIRダンプをCIに可視化(Phase 0のCLIビルドと併走) + + VM:実装が速い/デバッグ容易|最高速は出ない + + Cranelift JIT:実行時最適化で爆速/実装難度は中|起動コストあり + + AOT→Rust:rustc最適化の恩恵・配布しやすい|コード生成器の保守が要る + + WASM:移植性・安全|ネイティブよりは遅め(ただしwasmtime/wasmerで結構速い) + +まずやる順序(最短で“速い”を得る) + + 共通MIR/SSAを切る(基本ブロック・SSA・型/効果情報) + + VMを MIR→バイトコード に置き換え(インタープリターの土台を共通化) + + Cranelift JIT を載せる(ホット関数だけJIT) + + 並行で Rustコード生成 の雛形を作る(AOT配布の道を確保) + + 余力で WASM 出力(エディタ内実行やブラウザデモに最適) + +Nyash流にハマる設計ポイント + + Box拡張のABIを先に決める + + 呼出規約:fn nyash_box_call(ctx: &mut Ctx, args: &[Val]) -> Result + + メモリ:Arc<[Val]> か Arena で一時領域を明示(GCを後回しにできる) + + 所有権/借用に似た効果注釈をMIRに入れる + + 「純粋」「可変」「外部副作用あり」をフラグ化→最適化と並列実行の判断に使える + + 定数畳み込み/死コード除去/インライン化はMIR段階で実施 + + プロファイラを最初から同梱(どの関数をJIT/AOTに送るか判定) + +最小プロトタスク(1〜2週間スプリント想定) + +HIR/MIRスキーマ確定(基本ブロック・命令セット・型表現) + +MIR→バイトコード変換器/VMループの実装 + +プロファイル計測(関数実行回数・時間) + +Craneliftで fn 単位JIT(整数演算と分岐から) + +簡易 Rustコード生成(fn add(a:i64,b:i64)->i64 などから) + + Box ABI v0(同期版)+サンプル拡張(数値/文字列ユーティリティ) + +ちょいサンプル(超概念) + +enum MirInst { + Const(ValId, ConstVal), + BinOp(ValId, ValId, Op, ValId), + Call(ValId, FuncId, Vec), + Phi(ValId, Vec<(BlockId, ValId)>), + // ... +} +struct MirFunc { blocks: Vec, signature: Sig, effects: Effects } + +trait Backend { + fn compile(&mut self, f: &MirFunc) -> CompiledFn; +} + + VM backend: compile = バイトコード化 + + JIT backend: compile = Cranelift IR生成→jit_func + + Rust backend: compile = fn ... { ... } のRust文字列出力→rustcでAOT + +「いまのNyashソース」を見れたら、MIR命令セットの初版とJIT/AOTの足場コードをすぐ書き起こせるよ。 +まずは MIRの最小命令リストを一緒に決めよっか?(算術・比較・分岐・Call・Phi・Load/Store 相当) +あなた: +くわしくききたにゃ Front-end + + パーサ → AST → HIR(型付け・名前解決済み)→ MIR/SSA(最適化しやすい共通IR)パーサーで解析してASTは木構造だよね? そこからどういう処理にゃ? +ChatGPT: + +いいね、その流れを実務目線でがっつり分解するにゃ。 +キーワードは「情報を徐々に確定させつつ“最適化しやすい形”へ落としていく」。 +Nyash流に当てはめて、各段階で“何を追加・削除・変換するか”を整理するよ。 +Front-end 全体像 + +ソース → Lexer → Parser(AST) → スコープ/名前解決 → 型推論/型検査(HIR) → 糖衣剥がし(Desugar) → 制御フロー化(CFG) → SSA化/効果注釈(MIR/SSA) +1) Parser → AST(抽象構文木) + +目的:構文だけを正しく捉える。意味(型/名前)はまだ未確定。 + + データ構造(例) + + enum AstExpr { + LitInt(i64), + Var(Symbol), + Call{ callee: Box, args: Vec }, + Lambda{ params: Vec, body: Box }, + If{ cond: Box, then_e: Box, else_e: Box }, + Let{ pat: AstPat, init: Box, body: Box }, + // … match, while, for, block, … + } + + まだやらないこと + + シンボルの多義性解決(foo がローカルか、モジュールか、メソッドか) + + 型の決定 + + 糖衣構文の展開 + +2) スコープ構築 & 名前解決(AST上の解決) + +目的:識別子を定義元に結びつける。未定義やシャドーイングもここで判定。 + + やること + + ブロックスコープ/関数スコープ/モジュールスコープの**環境(symbol table)**を構築 + + use/import、module、with 的な構文を解決 + + 各 Var(Symbol) を DefId(定義へのID)にひも付け + + 成果物: + + 解決済みAST or ここで HIR に写経(次段のために構造を少し整える) + +3) 型推論 & 型検査 → HIR(型情報付きIR) + +目的:式ごとに型を確定し、オーバーロード/ジェネリクスを具体化できる所まで進める。 + + 型推論(Hindley–Milner+制約ベースなど) + + let x = 1 + f(y) なら、f: T -> i64 みたいな制約を立てて解く + + オーバーロード解決 / メソッド解決(a + b → 実体メソッドやトレイト関数に解決) + + ジェネリクス + + 可能ならモノモーフィック化(型実引数が確定している呼び出しは単相化) + + 未確定なら型パラ付きのまま保持 + + データ構造(例) + + struct HirExpr { + kind: HirExprKind, + ty: TyId, // ここが肝:各式に型が付く + effect: EffectMask, // 純粋/可変/外部副作用 など(後述の最適化で効く) + } + enum HirExprKind { + LitInt(i64), + Local(DefId), + Call{ fun: Box, args: Vec, resolved: FunId }, + If{ cond: Box, then_e: Box, else_e: Box }, + // 糖衣はまだ残っていてもOK + } + + エラー検出 + + 型不一致、未初期化、到達不能、借用/所有に関する静的規則(Nyash流に簡易化しても良い) + +4) 糖衣剥がし(Desugaring) + +目的:意味は同じだが最適化しづらい構文を、プリミティブな形に落とす。 + + 例 + + for x in iter { body } → let mut it = iter.into_iter(); while let Some(x) = it.next() { body } + + a && b → if a { b } else { false }(短絡を明示化) + + パターン束縛 let (a,b) = e; → 一時変数+個別bind + + クロージャ → 明示キャプチャ+ラムダ表現を正規化 + + この段階で構文のバリエーションは減らして、後段のCFG/SSA化を楽にする + +5) 制御フローグラフ(CFG)作成 + +目的:式主導(式木)を基本ブロック+ジャンプへ落とす。 +最適化やSSA化の土台になる。 + + ブロック(BasicBlock)単位で命令列を持つ + + 例:if/else は br cond thenBB elseBB に分解 + while は loopBB / bodyBB / exitBB に分解 + + ここで**一時変数(tmp)**を導入して、「値がどのブロックから来るか」を明示できるようにする + +6) SSA化(Static Single Assignment) + +目的:各変数が“ちょうど一度だけ代入”される形に変換。 +最適化(定数畳み込み・コピー伝播・死コード除去・ループ最適化)がやりやすくなる。 + + φ関数(Phi)を導入 + 分岐合流点で「どのブロックから来た値か」に応じて値を選ぶ + + データ構造(MIR/SSA例) + + enum MirInst { + Const{ dst: V, c: ConstVal }, + BinOp{ dst: V, op: Op, a: V, b: V }, + Call{ dst: V, fun: FnId, args: Vec, effects: EffectMask }, + Br{ cond: V, then_bb: Bb, else_bb: Bb }, + Jmp{ bb: Bb }, + Phi{ dst: V, inputs: Vec<(Bb, V)> }, + Store{ ptr: V, val: V }, // メモリ命令を分離しておくと最適化が楽 + Load{ dst: V, ptr: V }, + Ret{ v: Option }, + } + struct MirFunc { blocks: Vec, sig: Sig, effects: EffectMask } + + ここまでで最適化の主戦場が整う + +7) 効果注釈(Effects)と簡易別解(所有/借用に近いもの) + +目的:最適化・並列化・Box拡張の安全性判定に使う副作用情報を付与。 + + 例:PURE, READS_HEAP, WRITES_HEAP, IO, FFI, PANIC, THROW などのビットフラグ + + 呼び出し先の効果を合成して、関数単位の effects: EffectMask を確定 + → 並列実行可否、共通部分式除去可否、コードモーション許可範囲に使える + +8) 代表的な変換の“実例”で見る + +Nyash(仮): + +let x = 10 +let y = 20 +if x < y { + print(add(x, y)) +} else { + print(y) +} + +AST(ざっくり) + + Let(x, 10)、Let(y, 20)、If( BinOp(<, Var(x), Var(y)), Call(print, …), Call(print, Var(y)) ) + +HIR(型付け・解決済み) + + x: i64, y: i64 + + add: (i64,i64)->i64, print: (i64)->Unit + +Desugar + + ほぼそのまま(ここでは糖衣なしと仮定) + +CFG→SSA(MIRの一部) + +bb0: + v1 = Const 10 + v2 = Const 20 + v3 = BinOp Lt v1 v2 + Br v3 then=bb1 else=bb2 + +bb1: + v4 = Call add(v1, v2) ; PURE + Call print(v4) ; IO + Jmp bb3 + +bb2: + Call print(v2) ; IO + Jmp bb3 + +bb3: + Ret () + +(print は IO 効果、add は PURE、関数全体は IO を持つ、などが付与される) +よくある疑問Q&A + +Q. AST→HIRでどこまで“形を変える”? +A. 基本は意味解決のための注釈(DefId, TyId, Effect)を付けるのが主。大きな形の変換(ループ展開やパターン展開)はDesugar段でやると見通しが良い。 + +Q. なんでSSA?バイトコードでも良くない? +A. VM用のバイトコードは実行が簡単。でも最適化はSSAの方が圧倒的に楽。 +→ 「MIR/SSAで最適化」→「VM向けバイトコードに落とす」or「JIT/AOT」がおすすめ。 + +Q. パターンマッチは? +A. Desugarで決定木(decision tree)に落としてからCFG化。ガード節や順序付きパターンも木→ブロック分割で表現できる。 + +Q. クロージャのキャプチャは? +A. 名前解決で囲い込み変数を収集→HIRに明示キャプチャとして埋める。 +MIRでは環境レコードを値として扱う({env_ptr, fn_ptr})。 +まず作ると捗る“ミニ仕様” + + Symbol/DefId/Scope:解決器のAPI + + Ty:原始型・関数型・代数的データ型(Sum/Product)・型変数 + + EffectMask:ビットフラグ設計(PURE/READ/WRITE/IO/FFI など) + + MIR命令セット(最小):Const/BinOp/Call/Br/Jmp/Phi/Ret+Load/Store + + Pass順序: + + 名前解決 → 2) 型推論 → 3) Desugar → 4) CFG → 5) SSA → 6) 直近の最適化(const fold / dce / copy-prop) + +必要なら、いまのNyashのAST型定義をベースにHIR/MIRの骨組みを一緒に設計するよ。 + + “最初のMIR命令セット案” + + “名前解決テーブルと参照の貼り方” + + “効果注釈のフォーマット” + +この3点を固めるだけで、JIT/AOT/VMバックエンドの土台が一気に整うにゃ。 +あなた: +おおう これと さっきの  Back-ends(並行に育てる) + + VM(現在のインタープリター):MIR→バイトコード→解釈実行(開発スピード最優先) + + JIT(Cranelift):MIR→Cranelift IR→ネイティブJIT(ホットパスだけコンパイル) + + AOT to Rust:MIR→Rustコード生成→rustcで最適化(配布バイナリ向き、リンクも楽) + + WASM:MIR→WASM(ブラウザ/wasmtime用、サンドボックス実行) これの話要約してにゃ claude code君にみせてくるにゃ +ChatGPT: + +了解にゃ、Claude Code君向けに要点だけギュッとまとめるよ。 +Nyashコンパイルパイプライン案 +Front-end(共通部分) + + Parser → AST + + ソースを構文木(AST)に変換。型や意味はまだ未確定。 + + 名前解決 & スコープ構築 + + 識別子を定義元に紐付ける(DefId付与)。 + + 型推論 & 型検査 → HIR + + 各式に型情報(TyId)と効果注釈(EffectMask)を付与。 + + 糖衣剥がし(Desugar) + + forループやパターン束縛をプリミティブ構造へ展開。 + + 制御フロー化(CFG)→ SSA化(MIR) + + ASTを基本ブロックとSSA命令列(MIR)へ変換。 + + 命令例:Const, BinOp, Call, Br, Jmp, Phi, Load, Store, Ret。 + +Back-end(並行開発可能) + + VM(現行インタープリター) + + MIR → バイトコード → 解釈実行(開発スピード優先) + + JIT(Cranelift) + + MIR → Cranelift IR → 実行時にネイティブコード化(ホットパスだけ) + + AOT to Rust + + MIR → Rustコード生成 → rustc最適化&リンク → 配布可能なネイティブバイナリ + + WASM出力 + + MIR → WASM(ブラウザ実行やサンドボックス用) + +💡 ポイント + + すべてのバックエンドは共通MIRを入力にするため、最適化は1か所で集約。 + + Box拡張もMIRレベルで統一呼び出し可能。 + + VMは開発・デバッグ用、JITは実行高速化、AOTは配布、WASMは移植性重視。 + + +Nyashは**「最初から最後までモジュール拡張が一貫して動く多層言語」**という珍しい立ち位置になるにゃ。 + +希望あれば、これ一般的なコンパイラ構成との比較表にして、Claude Code君がすぐ違いを理解できる形にまとめることもできるよ。 +どうする、作っちゃう? +あなた: +おねがいにゃー! +ChatGPT: + +了解にゃー!Claude Code君に渡しやすいよう、「一般的な構成 vs Nyash流(+α)」比較表にギュッとまとめたよ。 +Nyash 設計:一般的な方法との比較 +観点 一般的なコンパイラ設計 Nyash(+α) +フロントエンド Parser → AST →(解決/型付け)→ IR Parser → AST → HIR(型/解決/効果)→ MIR/SSA(最適化前提) +中間表現(IR) 単一IR or バイトコード中心 HIR/MIR二段構え、MIRはSSA+効果注釈で最適化容易 +効果/副作用 多くは最適化時に暗黙扱い EffectMask(PURE/READ/WRITE/IO/FFI…)をMIRに明示し並列化・最適化の判断に使用 +拡張/FFI 後付けのFFI/プラグインが多い Box拡張を一級市民化。MIRレベルで統一コール形態を定義(VM/JIT/AOT/WASMで一貫) +バックエンド VM→(後からJIT/AOT) VM/JIT(Cranelift)/AOT-to-Rust/WASMを最初から並行開発できるMIR設計 +実行戦略 単層(解釈 or JIT)になりがち Tiered:VMで即起動→ホットパスJIT→配布はAOT→ブラウザはWASM +AOT配布 LLVM等のHPCルートが主 MIR→Rustコード生成→rustc最適化(ツールチェーン流用・リンク容易) +ブラウザ/サンドボックス 別途WASM対応 MIR→WASMを標準ターゲット化(wasmtime/wasmer/ブラウザ即動作) +最適化の主戦場 バイトコード最適化/バックエンド依存 MIR/SSAで集約最適化(const fold, DCE, copy-prop, inlining, loop opts) +並列化の足場 後付け解析が多い 効果注釈×データ依存で安全な並列化やコードモーションを許可 +デバッグ/開発速度 VMが主、JITは後追い VMで素早く検証しつつ、同一MIRをJIT/AOTに供給(回収効率◎) +配布/運用 ネイティブ or VM同梱 用途別に最適バイナリ(AOT)とスクリプタブル運用(VM)を両取り +リスク/留意点 単純で保守容易 設計は強力だが初期定義が要(MIR命令/Effect設計、Box ABIを固める) +補足:最小ロードマップ(実装順) + + HIR/MIRの骨組み確定(命令セット・EffectMask・Box ABI v0) + + **VM(MIR→バイトコード)**で先に全機能を回す + + プロファイラ同梱(ホット関数をJIT/AOTに回す条件づけ) + + Cranelift JIT(算術+分岐→関数呼び出し→Box呼び出し) + + AOT to Rust の雛形生成(小関数から) + + 余力で MIR→WASM(最小機能から) + +この表ごと貼れば、Claude Code君も**「王道+Nyashの差分」**を一目で把握できるはずにゃ。必要なら、MIR命令セット 初版案も続けて出すよ! +あなた: +mirまでできればかちなのにゃね。これって定番なのあるにやゃ? 言語ごとにやっぱりちがうにゃ? +ChatGPT: + +そうにゃ、MIRまで作れれば言語設計はもう“勝ち”に近いにゃ。 +なぜかというと、MIRは「全バックエンドの共通土台」だから、 +一度そこまで作れば VM/JIT/AOT/WASM ぜんぶに展開できるにゃ。 +🔹 MIRは定番があるの? + + 完全な共通規格はない + → LLVM IR や WebAssembly のような「広く使われる IR」はあるけど、 + 言語ごとに構文や型システムが違うから MIRはだいたい自作になる。 + + 多くの言語は「MIR」じゃなくても似た段階を持ってるにゃ: + + Rust → MIR(所有権/借用も反映されたSSA形式) + + Swift → SIL + + Go → SSA IR + + Kotlin → Kotlin IR + + Python(PyPy)→ Flow Graph → SSA IR + + JavaScript(V8)→ Bytecode IR → TurboFan IR + +🔹 言語ごとに違うポイント + + 型情報の粒度 + + RustのMIRは「型完全一致」必須。 + + Python系は動的型なので「型タグ+ランタイム判定」入り。 + + 命令セットの抽象度 + + LLVM IRはハード寄り(ポインタ/レジスタ操作あり)。 + + Rust MIRやKotlin IRは言語構造寄り(ループ/パターンマッチ命令など残す)。 + + 所有権・副作用の扱い + + Rust MIRは「所有権」も追跡する。 + + 多くの言語は副作用は型ではなく命令属性で管理。 + + 最適化の前提 + + 一部は最適化前提で作る(SSA化必須)。 + + 他は単にバックエンド入力の中間形式。 + +🔹 Nyashでのおすすめ方針 + + Rust MIRに近い構造を真似るのが安全 + + 静的型の要素が入ってるので、AOTや最適化に有利 + + EffectMaskやBox拡張の情報も一緒に持たせられる + + 命令はなるべく 「言語仕様に沿った中間レベル」 にして、 + バックエンド変換時に低レベル化する + + SSA化は最初からやる(後から入れるのは地獄) diff --git a/docs/development/roadmap/native-plan/archives/copilot_issues_20250814_145100_full.md b/docs/development/roadmap/native-plan/archives/copilot_issues_20250814_145100_full.md new file mode 100644 index 00000000..71d80f89 --- /dev/null +++ b/docs/development/roadmap/native-plan/archives/copilot_issues_20250814_145100_full.md @@ -0,0 +1,1193 @@ +# 🤖 Copilot様 作業予定・課題整理 (Phase 0-14 全体ロードマップ) +# Generated: 2025-08-14 (Git履歴から復元・更新) +# Purpose: Claude×Copilot協調開発のための情報共有 + +================================================================================ +🎯 次期最優先タスク (Phase 8.5以降) +================================================================================ + +## 🚀 Phase 8.4完了報告 (2025-08-14) +Status: ✅ 完了 (Copilot PR #56マージ済み) + +### ✅ AST→MIR Lowering完全実装 +- User-defined Box: `box DataBox { init { value } }` +- Object creation: `new DataBox(42)` +- Field access: `obj.value` +- Method calls: `c.increment()` +- Delegation: `from Parent.greet()` +- Static Main互換性維持 + +### 🧪 統合テスト結果(2025-08-14) +- ✅ **AST→MIR**: 完全動作 +- ✅ **インタープリター**: 完全動作(結果30) +- 🚨 **VM**: 動作するが結果が`void`(要修正) +- 🚨 **WASM**: String constant未対応(Phase 8.5で解決) + +### 📋 発見された課題 +- VM実行結果問題: BoxCall後の戻り値が正しく返らない +- WASM対応不足: 複雑なMIR命令(String constant, BoxCall)に未対応 +- 次期Phase 8.5での25命令MIR階層化が必要 + +================================================================================ + +## 🔧 Phase 8.5: MIR 25命令階層化(最優先) +Status: ⭐ **CRITICAL** +Priority: **最重要** (Phase 8.4完了直後の次期目標) + +### 🎯 実装目標 +ChatGPT5 + AI大会議決定版25命令MIR実装 +- 期間: 3週間 +- 効果: VM/WASM問題根本解決 +- 詳細仕様: `/docs/予定/native-plan/issues/phase_8_5_mir_25_instruction_specification.md` + +### 📋 25命令セマンティック階層化 +**Tier-0: 普遍コア(8命令)** +```mir +Const, BinOp, Compare, Branch, Jump, Phi, Call, Return +``` + +**Tier-1: Nyashセマンティクス(12命令)** +```mir +NewBox, BoxFieldLoad, BoxFieldStore, BoxCall, Safepoint, +RefGet, RefSet, WeakNew, WeakLoad, WeakCheck, Send, Recv +``` + +**Tier-2: 実装補助・最適化友好(5命令)** +```mir +TailCall, Adopt, Release, MemCopy, AtomicFence +``` + +### 🎯 期待される効果 +- **VM問題解決**: BoxCallの正しい実装で戻り値問題修正 +- **WASM対応**: 階層化により複雑MIR→単純WASM変換 +- **Everything is Box**: BoxFieldLoad/Storeで明確なBox中心設計 +- **JIT準備**: セマンティクス保持で高度最適化基盤確立 + +================================================================================ + +## 🏎️ Phase 8.6: VM性能改善(緊急) +Status: 🚨 **緊急** +Priority: **High** (Phase 8.5完了後) + +### 🚨 緊急問題 +**現状**: VM(119.80ms)< Interpreter(110.10ms)= 0.9倍の性能劣化 +**新問題**: VM BoxCall後の戻り値が`void`(Phase 8.4テストで発見) + +### 📋 技術的課題 +- VM実行エンジンのプロファイリング +- 命令ディスパッチ最適化(threaded code等) +- レジスタベースVM化検討 +- メモリプール最適化 +- BoxCall実装修正(戻り値問題) + +### 🎯 成功基準 +- VM性能 > Interpreter性能(最低2倍目標) +- BoxCall戻り値の正常動作 +- MIR→VM変換時間の短縮 + +================================================================================ + +## 🧪 Phase 8.7: Real-world Memory Testing +Status: 📋 **計画済み** +Priority: **High** (Phase 8.5-8.6完了後) + +### 🎯 実装目標 +kilo(テキストエディタ)実装によるfini/weak参照システム実証 +- 期間: 2週間 +- 詳細仕様: `/docs/予定/native-plan/issues/phase_8_7_real_world_memory_testing.md` + +### 📋 検証項目 +- 1000+オブジェクト管理テスト +- 循環参照回避確認(weak参照) +- fini()伝播の正確性確認 +- WASM環境での動作確認 + +================================================================================ +🗺️ Phase 0-14 全体ロードマップ (復元完了) +================================================================================ + +## Phase 0: Stabilize native CLI build (Linux/Windows) + +Summary: +- CLIバイナリ nyash を最小構成で安定ビルド・実行できる状態にする。 +- examples/GUI をデフォルトのビルド対象から外し、開発の足場を固める。 + +Why: +- 以降の MIR/VM/JIT 開発を素早く検証できる基盤づくり。 + +Scope: +- Cargo の features で GUI/examples 等を切り分け、デフォルトは CLI 最小にする。 +- CLI オプションの動作点検(--dump-mir / --verify)。 +- ローカル実行導線を README に明記(docs/guides/how-to-build-native/README.md)。 + +Tasks: +- Cargo.toml: examples/GUI を feature でガード(default は CLI 最小)。 +- ビルド検証: `cargo build --bin nyash`(Linux/Windows)。 +- 実行検証: `cargo run -- ./local_tests/sample.nyash`。 +- ドキュメント: 上記手順を how-to-build-native に追記/点検。 + +Acceptance Criteria: +- Linux/Windows で `cargo build --bin nyash` が成功する。 +- `local_tests/` 配下の簡単な .nyash が実行できる。 +- 他 bin/examples が壊れていても `--bin nyash` だけで通る。 + +Out of Scope: +- examples/GUI の修理・最適化。 +- JIT/AOT/WASM。 + +References: +- docs/guides/how-to-build-native/README.md +- docs/nativebuild大作戦/chatgptネイティブビルド大作戦.txt(Phase 0) +- CURRENT_TASK.md + +Copilot Notes: +- まずは features 分離と `--bin nyash` でビルドが通る状態を作る。README の手順確認まで含めて PR に反映。 + +------------------------------------------------------------ + +## Phase 1: Minimal MIR + VM backend (lowering + runner) + +Summary: +- AST → MIR の最小 lowering と、VM バックエンドでの実行を通す。 + +Scope: +- MIR: Const, BinOp, Compare, Branch, Jump, Phi, Return の最小命令 +- Lowering: リテラル/二項演算/if/loop/return のみ +- VM: 上記命令の最小実装 + +Tasks: +- instruction.rs: 最小命令の定義 +- builder.rs: 上記 AST 範囲を lowering +- vm.rs: 実装 + stats(命令数) + +Acceptance Criteria: +- `--dump-mir` が最小サンプルで期待通り +- `--backend vm` で実行して結果一致 + +Out of Scope: +- 例外/関数/Box 参照/弱参照 + +------------------------------------------------------------ + +## Phase 2: Control-flow coverage (if/else/loop/phi correctness) + +Summary: +- 制御フローの網羅と Phi の整合性検証を拡充。 + +Scope/Tasks: +- if/else nested, loop with breaks, nested loops のスナップショット +- Phi の入力ブロック/値の対応を Verifier で強化 + +Acceptance Criteria: +- 代表制御フローの snapshot が安定し、verify も通る + +------------------------------------------------------------ + +## Phase 3: Exceptions (throw/try/catch/finally) minimal lowering + +Summary: +- 例外機構の最小 lowering を導入(詳細設計は簡素)。 + +Scope/Tasks: +- MIR: Throw, TryBegin/TryEnd, Catch, FinallyBegin/End(最小) +- builder.rs: try/catch/finally ノードの下ろし +- VM: 例外伝播を最小で(未捕捉はエラー) + +Acceptance Criteria: +- 代表 try/catch/finally のスナップショットと VM 実行 + +Out of Scope: +- 例外の型体系、詳細な stack map + +------------------------------------------------------------ + +## Phase 4: Functions and calls (BoxCall minimal) + +Summary: +- 関数呼び出し/BoxCall を最小導入(効果注釈は保守的)。 + +Scope/Tasks: +- MIR: Call, BoxCall(effects = READS_HEAP など保守) +- builder.rs: FunctionCall/MethodCall の最小対応 +- VM: 呼び出し/戻り値 + +Acceptance Criteria: +- 簡単な関数定義/呼び出しの MIR/VM が通る + +Out of Scope: +- 可変長/キーワード引数、FFI + +------------------------------------------------------------ + +## Phase 5.0: Parser/AST stabilization for lowering + +Summary: +- lowering 対象 AST の表現ぶれを修正、安定化。 + +Scope/Tasks: +- AST: If/Loop/Return/Assignment/Local などの統一 +- Parser: エラー復帰/スパン情報の見直し + +Acceptance Criteria: +- builder.rs の分岐がシンプル化、テストが安定 + +------------------------------------------------------------ + +## Phase 5.1: Control-flow edge cases + verifier hardening + +Summary: +- ブロック未終端/未到達/自己分岐等の検証強化でクラッシュ回避。 + +Scope/Tasks: +- Verifier: 未終端ブロック検出、到達不能検出 +- Builder: Jump/Branch の生成前後の状態管理改善 + +Acceptance Criteria: +- 不正ケースを含むスナップショット/verify が緑 + +------------------------------------------------------------ + +## Phase 5.2: Lowering for static box Main (BoxDeclaration → main body) + +Summary: +- static box Main { main() { ... } } を MirBuilder で受け、main() の body を Program として lowering する経路を実装。 + +Scope/Tasks: +- AST: BoxDeclaration(is_static=true, name=Main) を検出 → main() を抽出 +- Lowering: body を Program に変換して既存経路に渡す +- Tests: local_tests/mir_loop_no_local.nyash で dump/VM が通る + +Acceptance Criteria: +- `--dump-mir` が static Main サンプルで成功 +- `--backend vm` で実行成功 + +References: +- docs/guides/how-to-build-native/issues/phase5_2_static_main_lowering.md + +------------------------------------------------------------ + +## Phase 6: Box ops minimal (Ref/Weak + Barriers no-op) + +Summary: +- 参照/弱参照/バリア(no-op)を最小導入。 + +Scope/Tasks: +- MIR: RefNew/RefGet/RefSet/WeakNew/WeakLoad/BarrierRead/Write +- Lowering: New/FieldAccess/MethodCall の最小対応 +- VM: 参照テーブル/weak テーブルで動作(fini 不変は維持) + +Acceptance Criteria: +- 代表サンプルで dump/VM/verify が通る + +References: +- docs/guides/how-to-build-native/issues/phase6_box_ops_minimal.md + +------------------------------------------------------------ + +## Phase 7: Async model (nowait/await) in MIR + +Summary: +- nowait/await を MIR に導入し、現行 FutureBox と連携。 + +Scope/Tasks: +- MIR: FutureNew/FutureSet/Await(スレッドベース) +- Lowering: nowait→Future 作成、await→wait_and_get +- VM: FutureBox 実装を利用 + +Acceptance Criteria: +- 代表ケースで正しく並行実行→await 回収 + +References: +- docs/guides/how-to-build-native/issues/phase7_async_mir.md + +------------------------------------------------------------ + +## Phase 8: MIR→WASM codegen (browser/wasmtime; sandboxed; Rust runtime free) + +Summary: +- MIR から素の WebAssembly を生成し、ブラウザ/wasmtime(WASI)でサンドボックス実行する。 +- Rust はコンパイラ本体のみ。実行は純WASM+ホストimport(env.print など)。 + +Scope/Tasks: +- ABI/Imports/Exports 定義(exports: main/memory、imports: env.print(i32) 等の最小) +- 線形メモリと簡易ヒープ(bump/自由リスト) +- 命令カバレッジ(段階導入): 算術/比較/分岐/loop/return/print、RefNew/RefSet/RefGet(Phase 6 整合)、Weak/Barrier はダミー + +Acceptance Criteria: +- wasmtime 実行で戻り値/print が期待通り(PoC1–2) +- Ref 系がメモリ上で正しく動作(PoC2) +- Weak/Barrier のダミー実装を含むWASMが生成・実行(PoC3) +- CLI `--backend wasm` は未実装でもよいが、実装する場合は明瞭にエラーメッセージ/誘導 + +References: +- docs/予定/native-plan/README.md(Phase 8 節) +- docs/説明書/wasm/*(ユーザー向けメモ) + +### Phase 8.3 完了状況 (2025-08-14) +✅ Box操作WASM実装 (RefNew/RefGet/RefSet) +✅ ベンチマークシステム統合 (13.5倍実行高速化実証) +✅ CLI統合完了 + +------------------------------------------------------------ + +## 🔧 Phase 8.4: AST→MIR Lowering完全実装 (最優先) +Note: 詳細は issues/phase_8_4_ast_mir_lowering.md に集約。本節は将来、要約のみを残す方針です. + +Summary: +- ユーザー定義Box、フィールドアクセス等の未実装部分を完成 +- Phase 8.3のBox操作WASMを実際にテスト可能にする + +Priority: **Critical** (現在の最優先事項) +Expected Duration: 1週間 + +### 実装範囲 +- [ ] ユーザー定義Box: `box DataBox { init { field } }` +- [ ] オブジェクト生成: `new DataBox()` +- [ ] フィールドアクセス: `obj.field` +- [ ] フィールド代入: `obj.field = value` +- [ ] from構文: `from Parent.method()` +- [ ] override構文: `override method() { ... }` + +### 成功基準 +- Phase 8.3のBox操作WASMが実際に動作 +- test_wasm_box_ops.nyash が正常実行 +- ユーザー定義Boxの完全サポート + +------------------------------------------------------------ + +## 🧠 Phase 8.5: MIRセマンティック階層化(AI大会議決定版) +Note: 詳細は issues/phase_8_5_mir_25_instruction_specification.md に集約。本節は将来、要約のみを残す方針です. + +Summary: +- 方針転換: ChatGPT5の20命令intrinsic戦略 → Gemini+Codex一致推奨の25命令階層化 +- 理由: JIT/AOT最適化阻害・Everything is Box意味喪失・長期コスト増の問題判明 +- 二相ロワリング: 25命令維持パス(VM/JIT/AOT)+ 20+intrinsic降格パス(WASM/最小実装) + +Priority: High (Phase 8.4完了後) +Expected Duration: 3週間 + +### AI大会議分析結果 +**Gemini先生(理論)**: 「賢いコンパイラは、賢いMIRから生まれる」 +- RefNew/WeakLoadのintrinsic化は最適化機会を失う悪手 +- セマンティック階層化で意味保持が最適化の鍵 + +**Codex先生(実装)**: 二相ロワリング戦略が実用的最適解 +- 実装コスト: 5命令追加で10-20人日(intrinsic戦略より安い) +- マイクロベンチ実測でパフォーマンス検証 + +### 確定版MIR(25命令)- ChatGPT5完全仕様 +**Tier-0: 普遍的コア(8命令)** +```mir +Const, BinOp, Compare, Branch, Jump, Phi, Call, Return +``` + +**Tier-1: Nyashセマンティクス(12命令)** +```mir +NewBox, // 強所有のBox生成(所有森のノード) +BoxFieldLoad, // Boxのフィールド読み(Everything is Box核心) +BoxFieldStore, // Boxのフィールド書き(mut効果) +BoxCall, // Boxのメソッド呼び出し(動的/静的両方) +Safepoint, // 分割finiや割込み許可ポイント +RefGet, // 参照(強/弱を問わず)を値として取得 +RefSet, // 参照の差し替え(所有規則検証付き) +WeakNew, // weak ハンドル生成(非所有リンク作成) +WeakLoad, // weak から生存チェック付きで強参照取得(失効時null) +WeakCheck, // weak の生存確認(bool) +Send, // Bus送信(io効果) +Recv // Bus受信(io効果) +``` + +**Tier-2: 実装補助・最適化友好(5命令)** +```mir +TailCall, // 末尾呼び出し(スタック節約) +Adopt, // 所有移管: this が子を強所有に取り込む +Release, // 強所有を解除(weak化 or null化) +MemCopy, // 小さなメモリ移動(構造体/配列最適化フック) +AtomicFence // 並行時の順序保証(Actor/Port境界で使用) +``` + +### 二相ロワリング戦略 +- パスA: VM/JIT/AOT向け(25命令のまま最適化) +- パスB: WASM/最小実装向け(25→20+intrinsic降格) +- バックエンド能力に応じて最適形式選択 + +### 効果(Effect)システム(ChatGPT5設計) +- **pure**: Const, BinOp, Compare, Phi, RefGet, WeakNew, WeakLoad, WeakCheck +- **mut**: BoxFieldStore, RefSet, Adopt, Release, MemCopy +- **io**: Send, Recv, Safepoint, AtomicFence +- **control**: Branch, Jump, Return, TailCall +- **context依存**: Call, BoxCall(呼び先効果に従属) + +**最適化ルール**: 「pure同士の再順序化OK」「mutは同一Box/同一Fieldで依存保持」「ioは再順序化禁止」 + +### 検証(Verifier)要件 +- **所有森**: `strong in-degree ≤ 1`(NewBox/Adopt/Release/RefSetで常時検査) +- **強循環禁止**: 強エッジのみ辿ってDAG(森)であること +- **weak/強相互**: 双方向とも強 → エラー(片側はWeakNew経由で弱化) +- **WeakLoad/WeakCheck**: 失効時はnull/falseを返す(例外禁止、決定的挙動) + +### 🤖 Copilot協力期待 +- **Tier-0/1実装**: Everything is Box哲学の完璧なIR化(BoxFieldLoad/Store核心) +- **weak参照システム**: WeakNew/WeakLoad/WeakCheck三位一体実装 +- **所有移管**: Adopt/Release命令による安全で効率的なメモリ管理 +- **効果システム**: pure/mut/io/control効果の正確な実装とVerifier統合 +- **最適化フック**: TailCall/MemCopy/AtomicFenceの実装補助 +- **二相ロワリング**: 25命令維持パス + 20+intrinsic降格パス構築 + +### 成功基準 +- [ ] **25命令完全実装**: ChatGPT5仕様の完璧な実装 +- [ ] **効果システム動作**: pure再順序化・mut依存保持・io順序保証 +- [ ] **Verifier動作**: 所有森・strong循環・安全性検証 +- [ ] **Golden MIRテスト**: 全バックエンドでMIR一致 +- [ ] **行動一致テスト**: 同入力→同出力(weak失効時null/false含む) +- [ ] **性能要件**: VM≥Interpreter、WASM≥VM継続検証 + +### バックエンド指針(ChatGPT5設計) +- **Interpreter**: 25命令を素直に実装(正しさの基準) +- **VM**: Register-VM + direct-threading。Send/Recvはローカル判定時にインライン化 +- **WASM**: Send/Recvはhost import。MemCopyはmemory.copyに対応 +- **JIT(将来)**: TailCall最適化、WeakLoadは世代タグでO(1)生存チェック + +References: +- docs/予定/native-plan/MIR仕様書.txt(ChatGPT5完全仕様) +- docs/予定/native-plan/issues/phase_8_5_mir_25_instruction_specification.md + +------------------------------------------------------------ + +## 🏎️ Phase 8.6: VM性能改善 (緊急) + +Summary: +- VMがインタープリターより遅い問題(0.9倍)を解決 +- MIR→VM実行の最適化でインタープリターを上回る性能へ + +Priority: High (Phase 8.5完了後) +Expected Duration: 2週間 + +### 問題分析 +**現状**: VM (119.80ms) < Interpreter (110.10ms) +**推定原因**: +- MIR変換オーバーヘッド +- VM命令ディスパッチの非効率性 +- メモリ管理コスト + +### 技術的アプローチ +- [ ] VM実行エンジンのプロファイリング +- [ ] 命令ディスパッチ最適化(threaded code等) +- [ ] レジスタベースVM化検討 +- [ ] メモリプール最適化 + +### 🤖 Copilot協力期待 +- VM実装のボトルネック特定 +- 効率的な命令ディスパッチ実装 +- スタックマシン vs レジスタマシン判断 + +### 成功基準 +- VM性能 > Interpreter性能(最低2倍目標) +- MIR→VM変換時間の短縮 +- メモリ使用量の削減 + +------------------------------------------------------------ + +## 🧪 Phase 8.7: Real-world Memory Management Testing (ChatGPT協調設計) + +Summary: +- 実用アプリケーション開発によるNyashメモリ管理システムの実証テスト +- finiシステム・weak参照の実用性を複雑なアプリケーションで検証 + +Priority: High (Phase 8.4-8.6完了直後) +Expected Duration: 2週間 + +### Phase 8.7A: kilo(テキストエディタ) +**技術的特徴**: +- サイズ: <1k LOC(超小型、最初の成功体験) +- メモリパターン: Editor -> (Rows -> Syntax) 木構造+相互参照 +- ChatGPT設計: Editor削除でRows自動解放、逆参照をweak化 + +**実装範囲**: +- [ ] Editor/Row/EditorState基本構造実装 +- [ ] weak参照による循環参照回避(`me.editor = weak editor_ref`) +- [ ] fini()システムによる自動メモリ解放 +- [ ] 大量オブジェクト(1000+ Rows)管理テスト + +**検証ポイント**: +- [ ] Editor削除でRows自動解放確認 +- [ ] 相互参照でメモリリークなし確認 +- [ ] weak参照の自動null化確認 +- [ ] fini()伝播の正確性確認 + +### Phase 9.5予定: tiny-web-server(HTTPサーバ) +**将来実装**(JIT実装後): +- 複雑度: 中〜高(Server -> Clients -> Requests並行処理) +- I/O管理: ソケット・ファイルハンドルの確実解放 +- 同時接続・早期切断・例外経路でのfini伝播テスト + +### 🤖 Copilot協力期待 +- 実用的なメモリ管理パターンの実装 +- weak参照構文の適切な使用 +- デバッグ支援機能(--debug-memory, --trace-weak) +- WASM環境でのメモリ管理互換性 + +### 成功基準 +- [ ] 全テストケースでメモリリークなし +- [ ] 循環参照でも正常解放確認 +- [ ] WASM実行でもメモリ管理正常 +- [ ] ベンチマーク性能劣化なし + +### 期待される効果 +- Nyashメモリ管理システムの実用性実証 +- Everything is Box哲学の実用レベル確認 +- メモリ安全なプログラミングパターン確立 + +References: +- docs/予定/native-plan/issues/phase_8_7_real_world_memory_testing.md + +------------------------------------------------------------ + +## 🚀 Phase 9: AOT WASM実装(最優先) + +Summary: +- wasmtime compileによるAOT実行ファイル生成で確実なユーザー価値提供 + +Scope/Tasks: +- `wasmtime compile` 統合実装 +- `--compile-native` / `--aot` CLI追加 +- 単一バイナリ梱包(`include_bytes!`) +- 起動時間・配布サイズ最適化 + +Acceptance Criteria: +- `nyash --compile-native app.nyash -o app.exe` 動作 +- 起動時間大幅短縮(JIT起動コスト除去) +- 配布可能実行ファイル生成 + +Priority: **Critical** (Phase 8.6完了直後) +Expected Duration: 2-3週間 + +### 技術的実装詳細 +🤖 Copilot協力期待: +- wasmtime::Config統一実装 +- .cwasm生成・実行パイプライン +- 互換性キー管理(CPU機能・wasmtimeバージョン) +- パッケージング(単一バイナリ梱包) + +### パフォーマンス目標 +- 現在のWASM JIT (13.5倍実行) → AOT (500倍目標:起動含む) +- 配布ファイルサイズ: <10MB目標 +- 起動時間: <100ms目標 + +### 期待される効果 +- **即座実用価値**: 配布可能実行ファイル生成 +- **差別化優位**: Everything is BoxのネイティブAOT実現 +- **LLVM準備**: AOT基盤確立でLLVM移行準備 + +------------------------------------------------------------ + +## 🌐 Phase 9.5: HTTPサーバー実用テスト(AOT検証) + +Summary: +- AOT実装完了後の複雑アプリケーション検証(並行処理・メモリ管理・実用性能) + +Scope/Tasks: +- tiny-web-server実装(HTTP/1.1対応) +- 同時接続・早期切断・例外経路テスト +- AOT環境での真の性能測定 +- 配布可能HTTPサーバーデモ + +Acceptance Criteria: +- `http_server.exe`として配布可能 +- 同時100接続でメモリリークなし +- fini()システム確実動作(I/Oハンドル解放) +- AOT性能でベンチマーク測定 + +Priority: High (Phase 9完了直後) +Expected Duration: 2週間 + +### 技術的複雑度 +```nyash +box HTTPServer { + init { clients, requests, handlers } + + acceptConnections() { + loop(me.running) { + local client = me.socket.accept() + nowait me.handleClient(client) // 非同期並行処理 + } + } + + handleClient(client) { + local request = client.readRequest() + local response = me.processRequest(request) + client.sendResponse(response) + client.fini() // 重要: 確実なリソース解放 + } +} +``` + +### 検証ポイント +- **並行処理**: nowait/awaitのAOT実行性能 +- **メモリ管理**: Server→Clients→Requests木構造+weak参照 +- **I/Oリソース**: ソケット・ファイルハンドルの確実解放 +- **実用性能**: リアルHTTP負荷でのAOT効果測定 + +### 🤖 Copilot協力期待 +- Socket・HTTP実装の効率化 +- 複雑なメモリ管理パターン検証 +- 負荷テスト・ベンチマーク整備 +- AOT最適化効果の定量測定 + +------------------------------------------------------------ + +## 🏆 Phase 10: LLVM Direct AOT(最高性能実現) + +Summary: +- MIR→LLVM IR直接変換による最高性能AOT実現(Cranelift JITスキップ) + +Scope/Tasks: +- MIR→LLVM IR lowering実装 +- エスケープ解析・ボックス化解除 +- LTO・PGO・高度最適化統合 +- Everything is Box最適化 + +Acceptance Criteria: +- 1000倍高速化達成 +- プロダクションレベル最適化 +- 他言語との競争力確立 + +Priority: Medium (Phase 9.5完了後) +Expected Duration: 4-6ヶ月 + +### 技術アプローチ +🤖 Copilot協力期待: +- **LLVM統合**: MIR→LLVM IR変換基盤 +- **エスケープ解析**: Box→スタック値最適化 +- **型特殊化**: コンパイル時型推論・特殊化 +- **LTO統合**: Link-time optimization +- **PGO対応**: Profile-guided optimization + +### Everything is Box最適化戦略 +- **Box回避**: スタック割り当て・直接レジスタ配置 +- **NaN Boxing**: 効率的な値表現 +- **型推論**: コンパイル時型特定・最適化 +- **メモリレイアウト**: 連続配置・キャッシュ効率 + +### パフォーマンス目標 +- **実行性能**: 1000倍高速化(現在13.5倍 → 目標13500倍相当) +- **メモリ効率**: Box割当数80%削減 +- **起動時間**: ネイティブレベル(<10ms) +- **競合比較**: C/C++/Rust並みの性能 + +### Cranelift JIT位置づけ変更 +**Phase 12以降の将来オプション**: +- JIT開発体験向上(nyashプログラマー向け) +- REPL・インタラクティブ実行 +- プロファイル駆動最適化 +- 言語完成後の付加価値機能 + +------------------------------------------------------------ + +## Phase 11-14: Infrastructure & Polish + +### Phase 11: MIR Optimization Framework +- エスケープ解析基盤 +- 型特殊化・ボックス化解除 +- デッドコード除去 + +### Phase 12: Advanced JIT Features +- Profile-guided optimization +- インライン展開 +- レジスタ割り当て最適化 + +### Phase 13: Production Readiness +- GC統合最適化 +- メモリ使用量最適化 +- 起動時間短縮 + +### Phase 14: Packaging/CI polish + +Summary: +- Windows/Linux の配布パッケージ化と CI 整備。 + +Scope/Tasks: +- GitHub Actions: Windows(MSVC)/WSL+cargo-xwin のマトリクス +- dist/: nyash(.exe) + LICENSE/README 同梱 + +Acceptance Criteria: +- リリースアーティファクトが自動生成される + +================================================================================ +🧠 AI大会議 + 実用優先戦略で得られた技術的知見 (2025-08-14更新) +================================================================================ + +## Gemini先生の助言(修正適用) +✅ エスケープ解析・ボックス化解除が性能の鍵 +✅ wasmtime compileは短期的に実用的 → **Phase 9で最優先実装** +✅ WASM実行は確実に高速(13.5倍実証済み) +🔄 Cranelift → LLVM段階的アプローチ → **実用優先でLLVM直接へ** + +## codex先生の助言(重点化) +✅ MIR前倒し実装推奨(全バックエンドが恩恵) +✅ wasmtime互換性管理が重要 → **AOT実装で最重要** +✅ CPU差異対応 (baseline/v3二段ビルド) +✅ 起動時間・割当削減・配布体験がKPI → **AOT価値の核心** + +## Claude統合分析(実用優先) +✅ 実用価値最大化: WASM+AOTで十分な競争力 +✅ 開発効率: Cranelift JITの恩恵限定的(cargo build変わらず) +✅ Everything is Box最適化が差別化の核心 +✅ 時間効率: 2-3ヶ月節約でLLVM集中投資 + +## 🎯 実用優先戦略の確定理由 +- **ユーザー体験**: WASM既に動作、AOTで配布価値追加 +- **開発効率**: Cranelift JITは重複投資(Rust開発環境改善せず) +- **競合優位**: AOT+LLVM早期実現で差別化 +- **リソース効果**: 限られた開発時間の最大効率化 + +================================================================================ +💡 Copilot様への具体的お願い・相談事項 +================================================================================ + +## 🔧 Phase 8.3完了・次期フェーズ準備 + +### MIRダイエット準備 +❓ 現在35命令→20命令削減のintrinsic戦略実装は? +❓ ChatGPT5推奨の3-point setアプローチ最適化は? +❓ Portability Contract v0での互換性確保方法は? + +### Phase 9 AOT WASM実装(最優先) +❓ wasmtime compileの実用配備方法は? +❓ .cwasm生成・単一バイナリ梱包戦略は? +❓ 互換性キー管理(CPU機能・wasmtimeバージョン)は? +❓ 起動時間最適化の実装アプローチは? + +### Phase 9.5 HTTPサーバー検証 +❓ Socket・HTTP実装の効率的な設計は? +❓ 並行処理でのメモリ管理パターンは? +❓ AOT環境でのI/Oリソース管理は? +❓ 負荷テスト・ベンチマーク設計は? + +### Phase 10 LLVM Direct AOT +❓ MIR→LLVM IR変換の効率実装は? +❓ エスケープ解析・ボックス化解除の実装戦略は? +❓ LTO・PGO統合の技術的ハードルは? + +## 🚀 長期戦略相談 + +### Everything is Box最適化 +❓ Box操作の根本的高速化戦略は? +❓ エスケープ解析によるスタック化判定は? +❓ 型特殊化・ボックス化解除の実装戦略は? + +### ベンチマーク拡張 +❓ AOT性能測定の追加指標は? +❓ 1000倍高速化実現のマイルストーン設計は? +❓ 他言語(JavaScript V8, Rust, C++)との競争力分析は? +❓ HTTPサーバー負荷テストの効率設計は? + +================================================================================ +📊 進捗管理・コミュニケーション +================================================================================ + +## 🤝 協調開発ルール + +### コミット・マージ戦略 +✅ 大きな変更前にはdocs/CURRENT_TASK.mdで情報共有 +✅ ベンチマーク機能は最優先で維持 +✅ CLI統合は両機能を統合的に対応 +✅ 競合発生時は機能優先度で解決 + +### 進捗報告 +📅 週次: 進捗状況をCURRENT_TASK.mdに反映 +📅 完了時: 新機能のベンチマーク結果を共有 +📅 問題発生: AI大会議で技術的相談 + +### 品質保証 +✅ cargo check でビルドエラーなし +✅ 既存ベンチマークが regression なし +✅ 新機能のドキュメント整備 +✅ テストケース追加・CI通過 + +================================================================================ +🎯 期待される成果・インパクト +================================================================================ + +## Phase 8完了時の成果 (達成済み) +🏆 RefNew/RefGet/RefSet WASM完全動作 +🏆 Box操作ベンチマーク追加 +🏆 メモリレイアウト最適化効果測定 +🏆 オブジェクト指向プログラミングWASM対応 +🏆 25命令MIR階層化完了(Phase 8.5) +🏆 VM性能改善完了(Phase 8.6) + +## Phase 9-10実用優先展望 +🚀 **AOT WASM実装** (Phase 9 - 2-3週間): 配布可能実行ファイル +🚀 **HTTPサーバー検証** (Phase 9.5 - 2週間): 実用アプリデモ +🚀 **LLVM Direct AOT** (Phase 10 - 4-6ヶ月): 1000倍高速化 +🚀 **実用競争力確立**: 他言語との差別化完成 + +## 言語としての完成度向上 +💎 Everything is Box哲学のネイティブ実現 +💎 開発効率性と実行性能の両立 +💎 4つの実行形態対応(Interpreter/VM/WASM/AOT)+ 将来JIT +💎 現代的言語としての地位確立 + +================================================================================ +📞 連絡・相談方法 +================================================================================ + +技術的相談や進捗報告は、以下の方法でお気軽にどうぞ: + +1. 📝 GitHub Issues・Pull Request +2. 📋 docs/CURRENT_TASK.md コメント +3. 🤖 AI大会議 (重要な技術決定) +4. 💬 コミットメッセージでの進捗共有 + +どんな小さなことでも相談大歓迎です! +一緒にNyashを最高の言語にしていきましょう🚀 + +================================================================================ +最終更新: 2025-08-14 (実用優先戦略・Phase 9-10再設計完了) +作成者: Claude (AI大会議結果 + 実用優先戦略統合) + +🎯 重要な変更点: +- Phase 9: JIT planning → AOT WASM実装(最優先) +- Phase 9.5: HTTPサーバー実用テスト追加(AOT検証) +- Phase 10: AOT exploration → LLVM Direct AOT(最高性能) +- Cranelift JIT: Phase 12以降の将来オプションに変更 +- HTTPサーバー: kilo後のタイミングで実用性能検証に特化 +================================================================================ +================================================================================ +🚀 Phase 9.0: Box FFI/ABI + Library-as-Box + RuntimeImports (WASM) — Proposal +================================================================================ + +Summary: +- 「あらゆるライブラリを箱にする」の共通ABI(Box FFI/ABI)を策定し、MIRとバックエンドの双方から利用可能にする。 +- BID (Box Interface Definition) として型/メソッド/効果を記述し、各ターゲット(WASM/VM/言語コード生成)へ自動写像。 +- WASM向けの実体として RuntimeImports をABI準拠で拡張(Canvas/Console最小セットから)。 + +Why: +- nyashがrustに依存せずnyasuをビルド(実行時は純WASM+ホストAPI) +- MIRから任意言語へ変換(BID→各言語のFFI/インポートへマッピング) +- 「Everything is Box」APIを外部ライブラリにも一貫適用 + +Scope/Tasks: +1) ABI/BIDの策定(最優先) + - 型: i32/i64/f32/f64/string(ptr,len)/bool/boxref/array、null/voidの扱い + - 呼び出し規約: 名前解決(namespace.box.method)、エラー/例外、同期/非同期 + - 効果: pure/mut/io/control(既存MIR効果と整合) + - 仕様文書: docs/box_ffi_abi.md、BIDフォーマット(YAML/JSON) + +2) MIR拡張(extern call) + - 命令: ExternCall(dst, iface, method, args[]) + - 検証: BIDと型/効果の整合、最適化時の順序制約 + - Lowering: 既存のBoxCall/Field opsとの橋渡し戦略 + +3) WASM RuntimeImports実装(ABI準拠) + - import群: env.console.log, env.canvas.fillRect/fillText 等(ptr/lenで文字列) + - JSホスト: importObject実装(DOM解決→Canvas/Console呼び出し) + - 最小E2E: CanvasとConsoleが「直接WASM生成」経路で動作 + +4) コード生成への写像 + - WASM: ExternCall→import呼び出し(メモリから文字列復元) + - VM: ExternCall→ホスト関数テーブル(モックで可) + - 言語出力: TypeScript/Python/Rust へのFFI/ラッパ生成(後続) + +5) 移行/互換 + - 既存 wasm-bindgen WebCanvasBox/WebConsoleBox はレガシー互換としつつ、 + 同一APIをABI経由で提供して統一。 + +Acceptance Criteria: +- docs/box_ffi_abi.md(初版)+BIDのサンプル(console, canvas) +- MIRにExternCallが追加され、WASMバックエンドでimport呼び出しが生成 +- ブラウザで「直接WASM出力」→Canvas描画/Console出力が成功 +- 既存PlaygroundのAPIをABI経由でも再現 + +Timeline (tentative): +- Week 1: ABI/BID仕様初版+MIR ExternCall雛形 +- Week 2: WASM RuntimeImports最小(console, canvas)+E2Eデモ +- Week 3: MIR verifier効果整合+WASMコード生成の安定化 +- Week 4+: 他ライブラリBID追加、言語ごとのFFIコード生成の着手 + +Risks/Mitigations: +- 文字列/メモリ規約の複雑化 → 最初はUTF-8固定としptr/lenを明記、ヘルパ関数を用意 +- 効果システムとの不整合 → BIDに効果を必須化しVerifierに反映 +- 二重系(旧 wasm-bindgen 経路)との分岐 → 段階的にABI側へ置換、テスト共通化 + +Notes: +- 「全部をBox化」の中心はBID。RuntimeImportsはBIDのWASM実装に過ぎない。 +- 全ライブラリ待ちではなく、Canvas/Consoleの最小実装で設計検証して拡張する。 + +------------------------------------------------------------ + +## 🔭 Phase 9.7: Box FFI/ABI基盤 + MIR ExternCall 追加(RuntimeImports対応) + +Summary: +- 「あらゆるライブラリを箱に」を実現するための共通ABI(Box FFI/ABI)とBID(Box Interface Definition)を策定。 +- MIRに `ExternCall` 命令を導入し、WASM/VM/言語出力で外部Box APIを一貫呼び出しできる基盤を整える。 +- WASM向けには RuntimeImports をABI準拠で拡張(console/canvasの最小セットから)。 + +Why: +- nyashがRustに依存せずnyasuをビルドできるように(実行時は純WASM+ホストimport)。 +- MIR→任意言語出力時に、外部ライブラリ(=Box API)をBID→各言語FFIへ写像しやすくする。 +- Everything is BoxのAPI設計を、外部ライブラリにも一貫適用。 + +Scope/Tasks: +- [ ] 1) ABI/BIDの策定(最優先) + - 型: i32/i64/f32/f64/string(ptr,len)/bool/boxref/array、null/void + - 呼出規約: 名前解決(namespace.box.method)、エラー/例外、同期/非同期 + - 効果: pure/mut/io/control(MIR効果と整合) + - 成果物: `docs/box_ffi_abi.md`、BIDフォーマット(YAML/JSON)サンプル(console/canvas) +- [ ] 2) MIR拡張: `ExternCall` + - 命令: `ExternCall(dst, iface_name, method_name, args[])` + - Verifier: BIDと型/効果の整合、最適化(pure再順序化/ mut依存)維持 + - Lowering: 既存のBoxCall/Field opsとの橋渡し、静的解決と動的解決の方針メモ +- [ ] 3) WASM RuntimeImports(ABI準拠) + - import群: `env.console.log(ptr,len)`, `env.canvas.fillRect(...)`, `env.canvas.fillText(...)` 等(stringはUTF-8でptr/len) + - Host(JS): importObject実装(DOM解決→Canvas/Console呼び出し) +- [ ] 4) コード生成: ExternCall→バックエンド写像 + - WASM: import呼び出し(線形メモリから文字列復元) + - VM: ホスト関数テーブルでスタブ実装(最小はログ/ダミー) + - 言語出力: TypeScript/Python/Rust等へのFFI雛形(後続) +- [ ] 5) E2Eデモ + - Nyashコード→MIR(ExternCall含む)→WASM生成→ブラウザでcanvas/console動作を確認 + +Acceptance Criteria: +- `docs/box_ffi_abi.md` 初版+BIDサンプル(console/canvas)が存在 +- MIRに `ExternCall` が追加され、WASMコード生成で import 呼び出しが生成される +- ブラウザで「直接WASM出力」→Canvas描画/Console出力が成功 +- 既存PlaygroundAPIとABI経由APIが概ね一致(互換性の方向性明確) + +Timeline (tentative): +- Week 1: ABI/BID仕様初版+MIR `ExternCall` 雛形 +- Week 2: WASM RuntimeImports最小(console/canvas)+E2Eデモ +- Week 3: Verifier効果整合+WASMコード生成の安定化 +- Week 4+: 他ライブラリBID追加、言語ごとのFFIコード生成の着手 + +Risks/Mitigations: +- 文字列/メモリ規約の複雑化 → UTF-8固定+ptr/len規約、ヘルパ導入 +- 効果システムとの不整合 → BIDに効果を必須化しVerifierに反映 +- 旧 wasm-bindgen 経路との二重系 → 段階的にABI側へ置換、テスト共通化 + +Order with Phase 10: +- Phase 9.7 を Phase 10 の前に実施するのが妥当(外部API基盤はAOT/JIT等の前提)。 + +------------------------------------------------------------ + +📚 Phase Index + Links(整理用) +- Phase 0–7: 基本MIR/VM/例外/非同期 既存記述の通り +- Phase 8.x: MIR→WASM(PoC→Lowering→25命令)既存記述の通り + - 8.4 完了報告あり + - 8.5 25命令仕様: docs/予定/native-plan/issues/phase_8_5_mir_25_instruction_specification.md + - 8.6/8.7 既存記述の通り +- Phase 9.x: AOT/WASM + ランタイム基盤 + - 9.7 ABI/BID + ExternCall: docs/予定/native-plan/issues/phase_9_7_box_ffi_abi_and_externcall.md + - ABIドラフト: docs/予定/native-plan/box_ffi_abi.md + - Issue 62 前提(WASM文字列定数): docs/予定/native-plan/issues/issue_62_update_proposal.md +- Phase 10: LLVM Backend Skeleton(MIR→LLVM IR) + - docs/予定/native-plan/issues/phase_10_x_llvm_backend_skeleton.md + +------------------------------------------------------------ + +## 📦 Phase 9.8: BIDレジストリ + 自動コード生成ツール(WASM/VM/LLVM/言語) + +Summary: +- 外部ライブラリをBoxとして配布・発見・利用するためのBIDレジストリと、BID→各ターゲットのスタブ生成(import/extern宣言)を自動化。 + +Scope/Tasks: +- BIDレジストリ仕様(署名・効果・バージョン・依存関係) +- 生成: WASM(importObject), VM(関数テーブル), LLVM(declare), TS/Python(RTEラッパ) +- CLI: `nyash bid gen --target wasm|vm|llvm|ts|py bid.yaml` + +Acceptance: +- console/canvasのBIDから各ターゲットの骨子が自動生成される + +------------------------------------------------------------ + +## 🔒 Phase 9.9: ExternCall 権限/ケイパビリティモデル(Sandbox/Allowlist) + +Summary: +- 外部API呼び出しの安全化。BIDに必要権限を宣言し、ホスト側で許可/拒否。WASMはimport allowlist、VM/LLVMは関数テーブルで制御。 + +Scope/Tasks: +- 権限種別(console, canvas, storage, net, audio...)とポリシー +- 実行時プロンプト/設定ファイル/環境変数での許可 +- 失権時の挙動(明示エラー) + +Acceptance: +- 禁止権限のExternCallが実行時にブロックされ、明確なエラーが返る + +------------------------------------------------------------ + +## 🧰 Phase 10.1: LLVM 外部関数マッピング方針(プラットフォーム抽象) + +Summary: +- ExternCallのFQN→ネイティブ関数(printf等)への写像レイヤーと、OS差の抽象。初手はLinux/clang、他OSは後続。 + +Scope/Tasks: +- env.console.log → printf("%.*s",len,ptr) テンプレート +- プラットフォーム切替(feature)とリンク方針 + +Acceptance: +- 代表ExternCall(console.log)がAOTバイナリで出力可能 + +------------------------------------------------------------ + +## 📦 Phase 11: Boxライブラリ配布(パッケージ)+バージョニング + +Summary: +- Boxパッケージ(BID+実装)の配布形式、互換性ルール、バージョン解決を定義。 + +Scope/Tasks: +- パッケージメタ(name, version, engines, permissions) +- 依存解決・衝突ルール(SemVer) +- 署名/検証(将来) + +Acceptance: +- ローカルBIDパッケージを参照してExternCallが解決可能 + +------------------------------------------------------------ + +## 🧪 Phase 12: LSP/静的解析(init/fini/weak/委譲 ルール検証) + +Summary: +- ChatGPT5提案の静的検証をLSPで提供。未宣言代入・weak循環・委譲競合を早期検出。 + +Scope/Tasks: +- ルール実装(init/weak/再代入fini/多重デリゲーション競合) +- VSCode拡張の最低限配布 + +Acceptance: +- 代表ケースで警告/自動修正候補が出る + +------------------------------------------------------------ + +## 📊 Phase 13: テレメトリ/診断(Debug level+Playgroundメトリクス) + +Summary: +- 実行時ノイズ抑制と観測性強化。debug level、fini/weak/時間のメトリクス表示をPlayground/CLIで提供。 + +Scope/Tasks: +- DebugBox/環境変数でログレベル切替 +- Playgroundにメータ(fini総数、weak失敗数、実行時間) + +Acceptance: +- 代表シナリオでメトリクスが可視化される + +------------------------------------------------------------ + +## 🧱 Phase 9.10: NyIR(公開IR)仕様化 + フォーマット + 検証器 + +Summary: +- 25命令MIRを公開IR(NyIR v1)として凍結。バージョニング、バイナリ`.nybc`/テキスト`.nyir`、厳格検証器を用意。 + +Scope/Tasks: +- docs/nyir/spec.md(命令の意味論/効果/検証/未定義なしの宣言) +- nyir-parser/nyir-serializer(.nyir/.nybc) +- Verifier: 所有森/weak/効果/Bus整合 +- ツール: `nyashel -S`(Nyash→NyIRダンプ), `nyir-run`(インタプリタ実行) + +References: +- docs/nyir/spec.md(骨子) +- docs/nyir/phase_9_10_nyir_spec.md + +Acceptance: +- 代表サンプルがNyIRで保存・検証・実行可能 + +------------------------------------------------------------ + +## 🧪 Phase 9.11: Golden NyIR + Differential 実行テスト(CI) + +Summary: +- NyIRダンプをゴールデンとし、interp/vm/wasm/jitの出力一致をCIで検証。弱失効/分割finiなど境界条件も含む。 + +Scope/Tasks: +- golden/*.nyir の整備 +- CIで各バックエンド実行→結果一致チェック + +Acceptance: +- 主要サンプルで全バックエンド一致(差分検出時は原因特定に役立つログ) + +------------------------------------------------------------ + +## 🧩 Phase 10.2: Host API層(C-ABI `ny_host_*` / WASM `nyir_host`) + +Summary: +- Rust依存を薄い宿主APIへ集約。C-ABI公開(ファイル/メモリ/時間等)、WASMは`nyir_host` importで提供。 + +Scope/Tasks: +- `ny_host_*`関数群(read_file/free/clockなど)をC-ABIで実装 +- Nyash側extern宣言と所有移管`*_from_raw`/`*_into_raw` +- WASM: import `nyir_host` 名前空間で最低限の関数提供 + +Acceptance: +- 代表I/OがHost API経由で動作し、Rust実装置換が容易 + +------------------------------------------------------------ + +## 🧱 Phase 10.3: ランタイム層の切り分け(corelang/rt/sys/std) + +Summary: +- corelang(純Nyash), rt(Box ABI/所有/weak/Safepoint/Bus), sys(プラットフォーム), std(Nyash実装)に整理。 + +Scope/Tasks: +- ドキュメント化+最小コードの配置替えスケルトン + +Acceptance: +- 層構造が明文化され、新規実装がガイドに従って進められる + +------------------------------------------------------------ + +## 🧬 Phase 10.4: Box ABI(fat ptr)とLLVM属性(Effects) + +Summary: +- Boxのfat pointer(data*, typeid, flags)の定義、Weakの世代タグ、SafepointのLLVM降ろし、Effect→LLVM属性(readonly/readnone等)。 + +Scope/Tasks: +- LLVM IR側のstruct宣言・属性付与の雛形 + +Acceptance: +- 代表関数で属性が付与され、最適化に寄与(noalias/argmemonly等は可能な範囲で) + +------------------------------------------------------------ + +## 📚 Phase 10.5: コア標準(String/Array/Map)Nyash実装(Rust依存の段階的削減) + +Summary: +- 現在Rust実装に依存している基本コンテナ(String/Array/Map)を、rt/sys層を活用してNyash実装に置換。セルフホストへの橋渡し。 + +Scope/Tasks: +- rt: 最低限のアロケータ/Box ABI/所有/weakを利用 +- sys: `ny_host_*`(alloc/free/memcpy等)を経由 +- std: Nyashで String/Array/Map の最小機能を実装(append/push/index/len など) +- 互換: 既存の言語表面の挙動に合わせる(差異は仕様で宣言) + +Acceptance: +- 代表サンプルでString/Array/MapがNyash実装で動作し、Rust実装をリンクせずに通る +References: +- docs/予定/native-plan/issues/phase_10_5_core_std_nyash_impl.md + +------------------------------------------------------------ + +## 🌀 Phase 14: セルフホスト・ロードマップ(Stage 0→3) + +Summary: +- nyashc0(Rust)→nyashc1(Nyash+NyIR+LLVM)→自己再ビルド→Rust依存をsys層みに縮退。 + +Scope/Tasks: +- Stage 0: 既存実装でNyIR→LLVMまでの線を通す +- Stage 1: Nyashでコンパイラ本体(フロント)を書きNyIR出力→LLVMでネイティブ化 +- Stage 2: 自己再ビルドの一致検証 +- Stage 3: 標準をNyash実装へ移行、Rustはsysのみ + +Acceptance: +- セルフホスト一周の実証(機能一致/ハッシュ近似) + + +------------------------------------------------------------ + +🧳 Parking Lot(要整合/後方貼り付け) +- WASM StringBox/文字列定数の取り扱いが古い記述と混在 → 最新は Issue 62 提案に従う(data segment + (ptr,len)) +- 8.4/8.5 の重複・表現ゆらぎ → 25命令仕様に一本化。古いintrinsic案は参考として保持 +- wasm-bindgen経路と直接WASM経路の混在 → 当面は併存、ABI経路へ漸進的統合(9.7参照) + +備考(運用) +- 本ファイルはフェーズ順の索引と整合メモを優先。詳細仕様は issues/ 配下の各mdに集約。 +- 不整合な古い計画は Parking Lot に追い出し、段階的に整理・統合する。 diff --git a/docs/予定/native-plan/copilot_issues_phase0_to_94.txt b/docs/development/roadmap/native-plan/archives/copilot_issues_phase0_to_94.txt similarity index 100% rename from docs/予定/native-plan/copilot_issues_phase0_to_94.txt rename to docs/development/roadmap/native-plan/archives/copilot_issues_phase0_to_94.txt diff --git a/docs/development/roadmap/native-plan/archives/gemini_nyash_general_analysis_2025-08-17.md b/docs/development/roadmap/native-plan/archives/gemini_nyash_general_analysis_2025-08-17.md new file mode 100644 index 00000000..b7c13fe3 --- /dev/null +++ b/docs/development/roadmap/native-plan/archives/gemini_nyash_general_analysis_2025-08-17.md @@ -0,0 +1,69 @@ +# Gemini先生によるNyashプログラミング言語の総合分析 (2025-08-17) + +## 総合評価 + +Nyashは、「Everything is a Box」という強力な統一哲学を掲げ、WebAssembly (WASM) ファースト、クリエイティブコーディング、教育用途を明確なターゲットとして設計された、意欲的でモダンなプログラミング言語です。Rustによる実装は、メモリ安全性とパフォーマンスという現代的な要求に応えるための堅実な選択と言えます。 + +特に、AI支援を積極的に活用し、短期間で豊富な機能セットと複数の実行バックエンド(インタープリター、VM、WASM)を実装した開発プロセスは注目に値します。 + +## 1. 設計哲学と一貫性: 「Everything is a Box」 + +### 長所: +- **統一された概念モデル:** すべての値を「Box」として扱うことで、データ型間の不整合をなくし、非常にシンプルで一貫性のあるオブジェクトモデルを提供 +- **メタプログラミングの可能性:** すべてが統一されたインターフェース(`NyashBox`トレイト)を持つため、リフレクションや動的な操作が容易 +- **自動リテラル変換:** `local text = "Hello"` のように書ける機能は、哲学の一貫性を保ちつつ、冗長な `new StringBox("Hello")` を不要にする優れた実用的判断 + +### 課題とトレードオフ: +- **パフォーマンスオーバーヘッド:** すべてをヒープ上のオブジェクト(Box)として扱うことは、単純な値(整数など)に対しても参照カウントや動的ディスパッチのコストを伴う +- **プリミティブ型の不在:** 他の多くの言語が持つスタック上の軽量なプリミティブ型が存在しないため、低レベルな最適化が難しくなる + +## 2. 構文と表現力 + +### 長所: +- **直感的で読みやすい:** `if`, `loop`, `and`, `or`, `not` といったキーワードは、PythonやRubyのように自然言語に近く、初学者にも親しみやすい +- **`static box Main` パターン:** プログラムのエントリーポイントを明確に定義する優れた方法 +- **`init { ... }` フィールド宣言:** フィールドをまとめて宣言する構文は、クラスの構造を一目で把握しやすくする良い設計 + +### 改善の可能性: +- **ループ構文:** `loop(condition)` のみが存在するのはシンプルですが、`for-each` のようなコレクションを反復処理するための専用構文がない +- **コンストラクタの多様性:** `birth`, `init`, `pack` と複数のコンストラクタ概念が存在するのは、言語のシンプルさを少し損なっている + +## 3. 型システムとメモリ管理 + +### 長所: +- **メモリ安全性:** Rustの所有権モデルを基盤に、`Arc` を活用することで、スレッドセーフなメモリ管理を実現 +- **明示的な変数宣言:** `local` キーワードによる変数宣言を強制する設計は、タイプミスによるバグを防ぐ +- **デリゲーションモデル:** 古典的な継承の代わりにデリゲーション(`from`)を採用しているのは、柔軟性が高くモダンな設計 + +### 課題: +- **型推論:** `local x = 10` のように型を明記しないスタイルは動的言語のようですが、内部的には静的なBox型に変換されている +- **Nullの扱い:** `VoidBox` や `NullBox` が存在しますが、言語レベルでNull安全性を強制する仕組みについての言及が少ない + +## 4. 非同期処理 + +### 長所: +- **シンプルな構文:** `nowait` と `await` は、C#やJavaScriptで成功を収めたモデルであり、非常に直感的 +- **スレッドベースの実装:** Rustのネイティブスレッドを利用することで、真の並列処理を実現 + +### 課題: +- **構造化並行性:** より高度なエラーハンドリングやキャンセルの伝播を実現するためには、構造化並行性の概念を導入することが望ましい +- **イベントループの不在:** GUIアプリケーションや大量のI/Oを扱うサーバーサイドアプリケーションでは、効率的なタスクスケジューリングのためにイベントループモデルが一般的 + +## 5. エコシステムとツールチェイン + +### 長所: +- **WASMファースト:** ブラウザで直接実行できることを最優先に設計されており、インストール不要のPlaygroundは非常に強力 +- **組み込みのデバッグ機能:** `DebugBox` のようなデバッグ支援機能が言語仕様に組み込まれているのはユニーク +- **複数の実行バックエンド:** インタープリター、VM、WASM、そして将来的にはAOTコンパイラと、ユースケースに応じて実行方式を選べる柔軟性 + +### 課題: +- **パッケージ管理:** `include` によるファイル取り込みは小規模なプロジェクトでは機能しますが、エコシステムが成長するためには公式なパッケージマネージャが不可欠 +- **LSPとIDEサポート:** Language Server Protocol (LSP) への対応は、現代的な開発体験を提供するために極めて重要 + +## 結論と将来性 + +Nyashは、明確な哲学とターゲットユーザーを持ち、多くのモダンな言語の良い点を取り入れた、非常によく考えられた言語です。特に「Everything is a Box」というコアコンセプトは、シンプルさと強力さを両立させる可能性を秘めています。 + +**成功への鍵は、今後のエコシステムの発展と、パフォーマンス・クリティカルな領域への対応にかかっているでしょう。** 計画されているLLVMバックエンドが実現すれば、現在の使いやすさを維持したまま、システムプログラミングに近い領域にも挑戦できる言語になる可能性があります。 + +総じて、Nyashは単なる実験的なプロジェクトではなく、プログラミング言語設計の新たな可能性を示す、将来が非常に楽しみな言語であると言えます。 \ No newline at end of file diff --git a/docs/development/roadmap/native-plan/archives/gemini_plugin_deep_analysis_2025-08-17.md b/docs/development/roadmap/native-plan/archives/gemini_plugin_deep_analysis_2025-08-17.md new file mode 100644 index 00000000..ab9cb18f --- /dev/null +++ b/docs/development/roadmap/native-plan/archives/gemini_plugin_deep_analysis_2025-08-17.md @@ -0,0 +1,141 @@ +# Gemini先生によるNyashプラグインシステム深層分析 (2025-08-17) + +## 概要 +Nyashプログラミング言語のプラグインシステム設計について、時間無制限で深い分析を実施。「Everything is a Box」哲学を維持しながら、透過的な置き換えと高いメンテナンス性を実現する具体的な実装提案。 + +## 1. 透過的な置き換えの最良実装方法 + +### 提案:Boxファクトリレジストリ + 設定ファイルによるオーバーライド + +**アーキテクチャ:** +```rust +// src/runtime/box_registry.rs +enum BoxFactory { + Builtin(fn(&[Box]) -> Result, RuntimeError>), + Plugin(PluginFactory), +} + +struct PluginFactory { + plugin_id: PluginId, + function_name: String, // 例: "filebox_open" +} +``` + +**設定ファイル(nyash.toml):** +```toml +[plugins] +enable = ["nyash-file-plugin"] + +[overrides] +"FileBox" = "nyash-file-plugin" # FileBoxをプラグイン版で置き換え +``` + +**実行時フロー:** +1. ランタイム起動時、全ビルトインBoxをレジストリに登録 +2. nyash.tomlを読み込み、overridesに従ってレジストリを更新 +3. `new FileBox()` 実行時、レジストリから適切なファクトリを検索・実行 + +**パフォーマンス:** HashMap検索1回のみ、その後は通常のdyn NyashBoxディスパッチ + +## 2. 署名DSLの設計の妥当性 + +### 分析:`::` (静的) と `#` (インスタンス) の記法は優秀 + +**拡張提案:** +```yaml +apis: + # オーバーロード対応 + - sig: "FileBox::open(path: string) -> FileBox" + - sig: "FileBox::open(path: string, mode: string) -> FileBox" + + # Result型対応 + - sig: "FileBox::open(path: string) -> Result" + + # 複数の戻り値型 + - sig: "FileBox#read() -> string" + - sig: "FileBox#read(size: int) -> bytes" +``` + +**将来性:** +- 現時点:具象型で固定 +- 将来:`Array` のようなジェネリクス構文を後方互換性を保ちつつ追加 + +## 3. Everything is a Box哲学との整合性 + +### 提案:FFI境界の標準化されたBoxプロキシ + +```rust +// src/runtime/plugin_box.rs +pub struct PluginBox { + base: BoxBase, + plugin_id: PluginId, + instance_handle: u64, // プラグイン内のインスタンスハンドル +} + +impl NyashBox for PluginBox { + fn clone_box(&self) -> Box { + // FFI呼び出しでプラグインにcloneを依頼 + let new_handle = ffi_call(self.plugin_id, "clone", self.instance_handle); + Box::new(PluginBox { ..., instance_handle: new_handle }) + } + + // 全てのNyashBoxメソッドをFFI経由で実装 +} +``` + +**保証される点:** +- 統一インターフェース:dyn NyashBoxのみを扱う +- メモリ管理:Drop時にプラグイン側に破棄を通知 +- 哲学の維持:内部実装(ネイティブ/FFI)は完全に隠蔽 + +## 4. 実装の複雑さとメンテナンス性のバランス + +### 提案:多層抽象化とツールによる自動化 + +**3層アーキテクチャ:** +1. **低レベルFFI (C-ABI)** + - `#[repr(C)]` 構造体と `extern "C"` 関数 + - libloadingクレートで動的ライブラリロード + +2. **中レベルAPI (安全なラッパー)** + - nullチェック、文字列変換、エラー処理 + - unsafeコードを隔離 + +3. **高レベルAPI (署名DSLとコード生成)** + - plugin.yaml → FFIコード自動生成 + - cargo-nyash-pluginサブコマンド + +**ロードマップ:** +- フェーズ1:FileBoxで手動実装、アーキテクチャ確立 +- フェーズ2:コード生成ツール開発、プラグイン開発の自動化 + +## 5. 他言語の成功例との比較 + +**Node.js (N-API):** +- 安定したABI → Nyashも同様にC-ABIベースで実装 +- バージョン管理と前方互換性を重視 + +**Python (C拡張):** +- 課題:手作業多い、参照カウント管理が煩雑 +- Nyashの解決:コード生成とRAIIによる自動メモリ管理 + +**WebAssembly Component Model:** +- 言語非依存インターフェースの未来形 +- 将来的にNyashプラグインをWASMで記述する可能性 + +## 実装計画(具体的ステップ) + +1. **nyash.toml仕様策定とパーサー実装** +2. **Boxファクトリレジストリ実装** +3. **FileBoxプラグイン手動実装** + - nyash_plugin_init + - filebox_open + - filebox_read/write/close + - filebox_drop +4. **PluginBoxプロキシ実装** +5. **libloadingで動的ロード実装** +6. **プラグイン版FileBoxテスト追加** + +## 結論 + +この設計は、Nyashの核心哲学を尊重しつつ、スケーラビリティ、安全性、開発者体験の向上を実現する。FileBoxの置き換えから始め、エコシステム全体へ展開していくのが最良の道筋。 \ No newline at end of file diff --git a/docs/development/roadmap/native-plan/archives/plugin_interface_design_discussion_2025-08-17.md b/docs/development/roadmap/native-plan/archives/plugin_interface_design_discussion_2025-08-17.md new file mode 100644 index 00000000..cb159b56 --- /dev/null +++ b/docs/development/roadmap/native-plan/archives/plugin_interface_design_discussion_2025-08-17.md @@ -0,0 +1,110 @@ +# プラグインインターフェース設計討論 (2025-08-17) + +## 🎯 議題:BID-FFIプラグインシステムの設計 + +### 背景 +- ビルトインFileBoxが既に存在 +- BID-FFIプラグイン版FileBoxで置き換えたい +- ビルド時間短縮とプラグインアーキテクチャの実証が目的 + +### 主な論点 +1. ビルトインBox → プラグインBoxの透過的な置き換え +2. `FileBox.open()` のような静的メソッドの結びつけ方 +3. プラグインインターフェース定義の外部化方式 + +## 💡 検討した案 + +### 案1: 汎用ラッパー +```nyash +// 呼び出しが汚い +local file = Plugin.call("FileBox", "open", ["test.txt", "r"]) +``` + +### 案2: 専用ラッパー +```nyash +// きれい!でも各Boxごとに手書きが必要 +local file = FileBox.open("test.txt") +``` + +### 案3: BoxDispatcher(透過的ディスパッチ) +```rust +pub enum BoxImpl { + Builtin(Box), // ビルトイン実装 + Plugin(BidHandle, PluginRef), // プラグイン実装 +} +``` + +### 案4: Unified Box Factory +```rust +pub struct BoxFactory { + providers: HashMap>, +} +``` + +## 🎉 最終解:YAML/JSON + 署名DSL + +### Codex先生の推奨設計 +```yaml +# filebox.plugin.yaml +schema: 1 +plugin: + name: filebox + version: 1 + +apis: + # 静的メソッド(::) + - sig: "FileBox::open(path: string, mode?: string) -> FileBox" + doc: "Open a file" + + # インスタンスメソッド(#) + - sig: "FileBox#read(size?: int) -> string" + doc: "Read file content" +``` + +### 利点 +1. **記号で静的/インスタンスを区別** + - `::` = 静的メソッド(C++風) + - `#` = インスタンスメソッド(Ruby風) + +2. **フラット構造** + - `apis` 配列にすべて並べる + - 階層が深くならない + +3. **署名DSL** + - 型情報を1行で表現 + - パーサーも簡単 + +4. **YAML → JSON変換** + - 開発時:YAML(人間に優しい) + - 実行時:JSON(マシンに優しい) + +## 🤔 Gemini先生への質問事項 + +1. **透過的な置き換え** + - 既存のNyashコードを一切変更せずに、ビルトインBoxをプラグインBoxに置き換える最良の方法は? + - パフォーマンスインパクトをどう最小化するか? + +2. **署名DSLの設計** + - `Type::method()` vs `Type.method()` の選択理由 + - オーバーロードの表現方法 + - ジェネリクスの将来的な拡張性 + +3. **実装戦略** + - インタープリター実行時のディスパッチ最適化 + - プラグインの遅延ロード実装 + - エラーハンドリングのベストプラクティス + +4. **Everything is Box哲学との整合性** + - プラグインBoxもビルトインBoxも「同じBox」として扱う方法 + - Box型の統一インターフェースの維持 + +5. **実用性** + - 他の言語(Python、Ruby、JavaScript)の成功例から学べること + - プラグイン作者にとっての開発体験 + - デバッグ・プロファイリングの考慮事項 + +## 📚 参考情報 +- 現在のFileBox実装: `src/boxes/file/mod.rs` +- BID-FFIプラグインFileBox: `src/bid/plugins/filebox/mod.rs` +- Everything is Box哲学: すべての値がBoxオブジェクト +- Nyashの目標: シンプル、分かりやすい、階層が深くならない \ No newline at end of file diff --git a/docs/development/roadmap/native-plan/archives/追記相談.txt b/docs/development/roadmap/native-plan/archives/追記相談.txt new file mode 100644 index 00000000..6e0d00e5 --- /dev/null +++ b/docs/development/roadmap/native-plan/archives/追記相談.txt @@ -0,0 +1,898 @@ +MIR設計:いま決めておくと後がラクなチェックリスト + + 値表現:Tagged(NaN-box/小整数直格納)か、型テーブル参照か。 + + アドレス空間:オブジェクトはheap専用? stack/arenaも持つ? + + 所有/別名:aliasable フラグ or unique(移動のみ)を型/値に持つ? + + 効果(Effects):PURE/READS_HEAP/WRITES_HEAP/IO/FFI/PANIC のビット集合を命令にも関数にも付ける。 + + 例外/パニック:Throw, Catch, Defer を命令化するか、関数境界でのみ扱うか。 + + GCモデル:Tracing(Stop-the-world / Incremental) or RC(ARC) or 混合。弱参照の意味を先に定義。 + + 安全点(Safepoint):JIT/VM両方で再入/停止できる位置を命令で明示(Safepoint or 呼出命令に属性)。 + + 呼出規約:通常Call/FFI/Box拡張の3種を区別(可変長・KW引数の扱いも)。 + + メモリバリア:write/read barrier を命令または隠れ属性として表現(最初は命令にするとデバッグ楽)。 + + デオプ(Deopt)前提:JIT最適化時の巻き戻し情報(マップ)を保持する場所(関数メタ or ブロック注釈)。 + +Nyash向け:最小MIR命令セット(弱参照対応込み) + + 算術/制御:Const, BinOp, Cmp, Br, Jmp, Phi, Ret + + 関数:Call, TailCall(effects必須) + + メモリ:Alloc, Load, Store, Gep(必要なら) + + 参照/GC: + + RefNew ty, dst <-(ヒープ確保) + + RefGet dst <- ref, field / RefSet ref, field, val + + WeakNew dst <- ref(弱参照作成) + + WeakLoad dst <- weak(弱が生きてたらref返す/無効ならNull/None) + + BarrierRead ref / BarrierWrite ref(GC用、最初はダミー) + + (必要なら)Pin ref / Unpin ref(ムーブしない保証用、JIT/FFI楽になる) + + 例外/FFI/拡張:Throw, Catch, FfiCall, BoxCall + + ユーティリティ:Safepoint, Nop, Assume(cond)(アサート兼最適化ヒント) + + 弱参照の意味論: + + WeakNew(r) は r を追うが GC で r が回収されると自動で無効化。 + + WeakLoad(w) は 生きていれば Some(Ref)、死んでいれば None を返す(MIR上はタグ付きユニオン)。 + + WeakLoad は PURE でOK(観測はするがヒープを書かない) + + ただし BarrierRead が必要なGCなら属性で付ける。 + +効果注釈(例) + + Call f(args) : dst [effects = PURE | READS_HEAP] + + RefSet … は WRITES_HEAP + + WeakLoad は PURE(または READS_HEAP) + + BoxCall は最低限 FFI を含める(安全側に倒す) + +VM/JIT/将来AOTの共通の“壊れにくい”ポイント + + Safepointは関数入口・ループ先頭・Call直後の3か所に最初から置く + + Barrier命令は最初は実装ダミーでもOK(最適化段で消せる) + + Null/Noneの扱いは必ず型系に明示(Option)。判定を分岐で隠さない + + JITはDeoptテーブルを MIR → JIT に渡す(各値が「どのSSA番号?」を持つ) + +弱参照 “落とし穴” 3つ(実戦で効く回避) + + クロージャ環境に弱参照が紛れ込む + + 生成時に env.has_weak を立て、キャプチャ解決時に必ず WeakLoad→None分岐を強制。 + + 弱参照をキーにしたハッシュ + + GC後に無効化でキー不整合。→ 弱マップを標準提供(キー死亡で自動削除)。 + + FFI渡し + + FFI境界を跨ぐと寿命が分からなくなる。→ Pin を要求 or WeakLoad→Ref に成功した生参照だけ渡す。 + +最小・具体例(擬似MIR) + +// x = new Obj{y:1}; w = weak(x); if let Some(x2) = weak_load(w) { x2.y = 2 } +bb0: + v1 = Const 1 + v2 = RefNew Obj ; WRITES_HEAP + RefSet v2, y, v1 ; WRITES_HEAP + v3 = WeakNew v2 ; PURE + v4 = WeakLoad v3 ; returns Option + br is_some(v4), bb1, bb2 + +bb1: + v5 = unwrap(v4) + BarrierWrite v5 + RefSet v5, y, Const 2 + jmp bb3 + +bb2: + jmp bb3 + +bb3: + Ret () + +テストの当て方(行き当たりばったりでも壊れにくい) + + 黄金テスト:ソース→MIRダンプの文字列をスナップショット化(差分で挙動の後退を検知) + + VM/JIT一致テスト:同じ入力で VM結果=JIT結果 を比較する“オラクル”を用意 + + 弱参照の確率テスト:alloc→weak→drop→collect→weak_load を順序/タイミングを変えて多数回 + + 効果チェック:PURE なはずの関数に WRITES_HEAP が紛れたらビルド失敗(静的検証) + +いまの進み方に合う“軽量次の一手” + + ✅ WeakNew/WeakLoad を MIRとVM だけ先に入れる(JITは後回し) + + ✅ EffectMask を命令に付ける(最初はデータ構造だけ) + + ✅ Safepoint 命令を関数入口とループ先頭に挿す(動作はno-opでOK) + + ✅ 黄金テストを入れて MIR差分をCIで見える化 + +この骨格なら、行き当たりばったりで直してもMIRの“契約”が守れている限り、VM/JIT/AOT/WASMに横展開できるにゃ。 +もし今のAST/HIRの型定義があれば、MIRの型/命令エンムだけ私が初稿を書くこともできる。要る? +あなた: +そうだにゃ。mir 結局はメモリー管理がほとんどであってるかにゃ?既存の参考になるやつとかないかにゃ +ChatGPT: + +いい質問にゃ。結論から言うと―― + + MIRの“要”はメモリ管理だけじゃないけど、実務で一番ハマるのはメモリまわり(所有権/寿命/別名化/GCバリア/セーフポイント/弱参照/デオプ情報)だから、体感「ほとんどメモリ管理」はだいたい合ってるにゃ。 + + ただし、制御フロー(CFG/SSA)、呼び出し規約、効果注釈、例外/パニック、最適化のための形も同じくらい重要。ここをサボるとJIT/AOT/WASMに展開しづらくなる。 + +MIRで“最低限”押さえるメモリ論点 + + 値表現:Boxed/Unboxed、NaN-box、小整数直格納、タグ方式 + + アロケータ:bump/arena/世代別、オブジェクト配置(ヘッダ、タイプID、フラグ) + + 所有と別名:unique/aliasable や owned/borrowed の属性(最適化・並列の鍵) + + GC/RC:トレース or 参照カウント or 混在、write/read barrier 命令 or 属性、remembered set + + 弱参照:WeakNew / WeakLoad の意味論(死んだら None) + + Safepoint:関数入口・ループ先頭・Call直後(停止/再入のフック) + + FFI境界:Pin/Unpin、ハンドル渡し、最小共有ABI + + Deopt情報:JIT用の巻き戻しメタ(SSA値⇔ソース位置の対応) + +参考になる“実物”と読みどころ(定番) + +(リンクは割愛するにゃ。名前で検索すればすぐ出る) + + Rust MIR(rustc-dev-guide / rustc本体) + + MIRのSSA・ borrow check が MIR 上で走る構造 + + Drop/Move・パニック・noalias 的情報が最適化に効く + + Swift SIL + + Ownership qualifiers(owned/guaranteed)が秀逸。GCなし言語でも寿命管理をIRで表す好例 + + Kotlin IR + + “lowerings” の段階的デシュガリングが参考。高級構文→プリミティブ命令へ段階変換 + + Go SSA(golang.org/x/tools/go/ssa) + + 最小主義のSSAで読みやすい。CFG/φの扱いが素直 + + LuaJIT IR(DynASM/TurboNYIの解説blog群) + + 小粒なSSAでJIT最適化の勘所(CSE/LICM/ヒント) + + V8(Ignition/TurboFan) + + バイトコード→Sea of Nodes→最適化JITの流れ。デオプとサファリガードの設計が神 + + Cranelift IR + + Rustからも使いやすいJITバックエンド。型・メモリ・コールの表現が実装しやすい + + MLIR + + 複数方言で中間表現を分ける思想。将来、NyashのMIRを方言化する発想の参考に + +Nyash向け“最小MIRコア”(骨組み) + +(超要約:これ+効果注釈でVM/JIT/AOT/WASMに展開できる) + + 制御/値:Const, BinOp, Cmp, Br, Jmp, Phi, Ret + + 呼び出し:Call, TailCall(effects 必須) + + メモリ:Alloc, Load, Store, Gep? + + 参照/GC:RefNew, RefGet, RefSet, WeakNew, WeakLoad, BarrierRead, BarrierWrite, Pin, Unpin + + 例外/拡張:Throw, Catch, FfiCall, BoxCall + + 実行点:Safepoint, Assume, Nop + + 効果:EffectMask = PURE | READS_HEAP | WRITES_HEAP | IO | FFI | PANIC + + 実装順ヒント: + + VMで RefNew/RefGet/RefSet/Weak* をまず動かす → 2) Safepointはno-opで挿す → 3) Barrierは最初ダミー → 4) “黄金テスト”(ソース→MIRダンプのスナップショット)で後退検知 → 5) JIT/AOTは後から乗せる。 + +“既存をパクる”具体策 + + Ownershipの表現は Swift SIL を真似る(owned/guaranteed を Nyash版に) + + 弱参照の意味論は JVMのWeakReference と Swiftのweak/unowned を折衷 + + Safepoint配置は HotSpot/V8 のパターン(入口・ループ・call直後) + + JIT導入は Cranelift から(まず整数・分岐・呼び出しのみ) + + デシュガリング手順は Kotlin IR の lowering 流儀を採用 + +「MIR=メモリ管理が9割」は現場感として正しいけど、残りの1割(CFG/SSA・呼出・効果・例外・デオプ)を最初にうっすら設計しておくと、あとで爆速に伸びるにゃ。 +必要なら、Nyashの今のAST/HIRを見せてくれたら、MIRのenum・EffectMask・Box ABI v0をその場で下書きするよ。 +あなた: +なるほど。ところでmirってどっかきょうつうのふぉーまっとやしようってあるにゃ? みんなばらばるにかいてるにゃ? +ChatGPT: + +共通フォーマットや「これを使えばOK」みたいなMIR標準は、残念ながら存在しないにゃ。 +理由をまとめると―― +1. 共通規格がない理由 + + 言語ごとに型・所有権・ランタイム構造が違いすぎる + 例:Rust MIRは所有権・borrowをIRレベルで保持するけど、PythonやJavaScriptのIRにはそんな概念がない。 + + 目的ごとの最適化が異なる + VM実行用、JIT最適化用、AOTコンパイル用で命令セットやメタデータの粒度が変わる。 + + IRの“責務”が違う + ある言語ではASTの直後を「MIR」と呼び、別の言語ではSSA化した後の低レベルIRを「MIR」と呼ぶ。 + +2. 事実上の“よくある流儀” + +標準はないけど、以下のパターンは多いにゃ: + + SSAベース:変数は再代入不可、phi命令で合流点処理(Rust MIR, Swift SIL, Go SSA) + + 命令は3アドレス形式:dst = op src1 src2 のようにシンプル(Cranelift, LLVM風) + + 効果注釈あり:PURE, READ_HEAP, WRITE_HEAP など最適化ヒント + + メモリ命令の抽象化:Alloc, Load, Store は型・アラインメント・所有権情報を持つ + + 制御フローはCFG(Control Flow Graph)で管理 + 基本ブロック+ジャンプ+条件分岐 + +3. 参考になる「ほぼテンプレ」的MIR + +完全な共通仕様じゃないけど、設計の参考にできる実例はあるにゃ: + + Cranelift IR + Rustで使いやすいJIT/AOT用IR。型・命令の定義が明確で、小規模実装の参考に最適。 + + MLIR + LLVM系の中間表現フレームワーク。方言を作れるので、自作言語のMIRを「Nyash方言」として定義可能。 + + Sea of Nodes(V8, HotSpot) + SSAと依存グラフを統合した形式。最適化向きだが実装難度は高い。 + + LuaJIT IR + 極小SSA+軽量タグ付き値表現。高速インタープリタや軽量JITに向いてる。 + +4. Nyashでの方針 + + 「共通仕様」を無理に探すより、自分のランタイムと変換先(Rust/Cranelift/WASM)に都合の良い形を作るのが早い + + ただし、命令セットやCFG構造はCranelift IRやSwift SILを参考にすると後で楽 + + 将来的にMLIRの方言化を視野に入れると、外部ツールや最適化パスを簡単に流用できる + +もし希望なら、Nyash向けにCranelift IR互換寄りのMIR仕様ドラフトをその場で作れるよ。 +それをベースにすれば、将来JIT/AOT/WASM全部に展開しやすくなるにゃ。 +あなた: +そうだにゃ。ということは命令セットを先に考えて貰えたらいいのかにゃ? +ChatGPT: + +いいね、その方向でいこうにゃ。 +Nyash向けに“まず回る”ことを最優先にした MIR命令セット v0.1(草案) を置くね。VM/JIT/AOT/WASMに伸ばせる骨格で、弱参照・効果注釈・拡張Box呼び出しも最初から入れてあるにゃ。 +Nyash MIR v0.1(草案) +基本モデル + + SSA値:vN(再代入なし)。 + + 基本ブロック:bbN(末尾は必ず終端命令)。 + + 型(最小):i64, f64, bool, unit, ref, weak, ptr, any, option + + 関数署名:fn(args…) -> ret [effects] + + 効果(EffectMask):PURE, READS_HEAP, WRITES_HEAP, IO, FFI, PANIC(ビット和) + + 属性:命令に align, nonnull, noalias, readonly 等の任意属性 + +1) 演算・制御 + +Const dst, Imm ; 例: i64/f64/bool/unit/Null +BinOp dst, op, a, b ; add, sub, mul, div, mod, and, or, xor, shl, shr +Cmp dst, relop, a, b ; eq, ne, lt, le, gt, ge +Select dst, cond, a, b ; φ簡約前の三項選択(任意) +Phi dst, [(predBB, val), ...] ; SSA合流 + +Br cond, thenBB, elseBB ; 条件分岐(終端) +Jmp targetBB ; 無条件ジャンプ(終端) +Ret [val] ; 返り値(終端) unit時は省略可 +Unreachable ; 到達不能(終端・最適化用) + +2) メモリ/参照(GC想定) + +Alloc dst, Ty, size? ; ヒープ確保: ref を返す [WRITES_HEAP] +Load dst, addr ; 読み出し [READS_HEAP] +Store addr, val ; 書き込み [WRITES_HEAP] +Gep dst, base, offset ; アドレス計算(構造体/配列) + +RefNew dst, Ty ; オブジェクト新規: ref [WRITES_HEAP] +RefGet dst, ref, field ; フィールド読み [READS_HEAP] +RefSet ref, field, val ; フィールド書き [WRITES_HEAP] + +WeakNew dst, ref ; weak を作成 [PURE] +WeakLoad dst, weak ; option> を返す [PURE or READS_HEAP] + +BarrierRead ref ; 読みバリア(実装はno-op可) +BarrierWrite ref ; 書きバリア(実装はno-op可) +Pin ref ; 移動不可に固定(FFI/GC向け) +Unpin ref +Safepoint ; 停止点(関数入口/ループ先頭/Call直後に挿す) + + 弱参照の意味論 + + WeakNew(r) は r のライフを追うだけ(所有しない)。 + + WeakLoad(w) は生存なら Some(ref)、回収済みなら None。 + + WeakLoad は基本 PURE でOK(実装の都合で READS_HEAP にしても可)。 + +3) 呼び出し/例外/拡張 + +Call dst, callee, [args...] ; [effects = callee.effects] +TailCall callee, [args...] ; 末尾呼び出し(終端) + +BoxCall dst, box_id, fn_id, [args...] ; Nyash拡張Box呼び出し [FFI | PANIC?] + +FfiCall dst, sym, [args...], abi ; C/Rust外部関数 [FFI | PANIC?] + +Throw val ; 例外送出(終端) +CatchBegin dst, handlerBB ; 例外ハンドラの開始(ブロック境界メタでもOK) +CatchEnd +Defer fnref ; スコープ脱出時に実行(loweringで展開可) +Assume cond ; 最適化ヒント(偽ならUB) +Nop + + Call/BoxCall/FfiCall は 効果注釈が必須(少なくとも PURE かどうか)。 + + BoxCall は拡張Box ABIを通す入口(VM/JIT/WASMで一貫した形で扱える)。 + +4) メタデータ(最低限) + + 位置情報:dbg(loc)(ソース行/列/ファイル) + + デオプ:deopt_map(JIT用:各SSA値→高級値の対応) + + alias情報:noalias/readonly/nonnull 属性 + + 効果集約:関数単位で effects を保持(呼び出し時に合成) + +Rust風スケッチ(型・命令) + +#[bitflags] +enum Effect { PURE=1, READS_HEAP=2, WRITES_HEAP=4, IO=8, FFI=16, PANIC=32 } + +enum Ty { + I64, F64, Bool, Unit, + Ref(Box), Weak(Box), Ptr, Any, + Option(Box), // WeakLoadの戻りなど + // …将来: Sum/Product/Function/Closure/BoxHandle +} + +struct FuncSig { params: Vec, ret: Ty, effects: Effect } + +enum Inst { + Const{dst:V, imm:Imm}, + BinOp{dst:V, op:Bin, a:V, b:V}, + Cmp{dst:V, op:Rel, a:V, b:V}, + Select{dst:V, cond:V, a:V, b:V}, + Phi{dst:V, inputs: Vec<(Bb,V)>}, + + Br{cond:V, then_:Bb, else_:Bb}, + Jmp{bb:Bb}, + Ret{val: Option}, + Unreachable, + + Alloc{dst:V, ty:Ty, size:Option}, + Load{dst:V, addr:V}, + Store{addr:V, val:V}, + Gep{dst:V, base:V, off:V}, + + RefNew{dst:V, ty:Ty}, + RefGet{dst:V, r:V, field:FieldId}, + RefSet{r:V, field:FieldId, val:V}, + + WeakNew{dst:V, r:V}, + WeakLoad{dst:V, w:V}, + + BarrierRead{r:V}, + BarrierWrite{r:V}, + Pin{r:V}, + Unpin{r:V}, + Safepoint, + + Call{dst:V, f:FnId, args:Vec}, + TailCall{f:FnId, args:Vec}, + BoxCall{dst:V, box_id:BoxId, fn_id:BoxFnId, args:Vec}, + FfiCall{dst:V, sym:Sym, args:Vec, abi:Abi}, + + Throw{val:V}, + CatchBegin{dst:V, handler:Bb}, + CatchEnd, + Defer{fnref:FnId}, + Assume{cond:V}, + Nop, +} + +バックエンド対応の見取り図 + + VM: + + Ref* / Weak* / Barrier* / Safepoint をそのまま実装 + + Defer/Catch はデシュガで try/finally へ展開 + + Cranelift JIT: + + 算術・制御は直マップ、Ref* はランタイムAPIに落とす + + Safepoint でGC/スレッド停止と連携、deopt_map を用意 + + AOT to Rust: + + ref は Gc ラッパ、weak は Weak 風にコード生成 + + BoxCall は trait 経由/extern呼び出しに置換 + + WASM: + + 参照はハンドル(i32)で表現、GCはランタイム関数 + + weak はハンドルテーブルにビットを持って実装 + +取り決め(壊れにくい不変条件) + + すべてのCallは effects を持つ(省略禁止) + + WeakLoadの戻りは option>(null判定を曖昧にしない) + + Safepoint は関数入口・ループ先頭・任意のCall直後に挿入 + + Barrier* は最初はno-opでOK(GC導入時のフックとして残す) + + 終端命令のないブロックは禁止(検証器で弾く) + +ちいさな動作例 + +; x = new Obj{y=1}; w = weak(x); +; if let Some(r) = weak_load(w) { r.y = 2 } + +bb0: + v1 = Const i64 1 + v2 = RefNew Obj + RefSet v2, field_y, v1 + v3 = WeakNew v2 + v4 = WeakLoad v3 ; option> + Br is_some(v4), bb1, bb2 + +bb1: + v5 = unwrap(v4) + BarrierWrite v5 + RefSet v5, field_y, Const i64 2 + Jmp bb3 + +bb2: + Jmp bb3 + +bb3: + Ret unit + +まずやる実装順(1〜2日で回る) + + この命令セットで MIR組み立て+ダンプ(黄金テストで差分管理) + + VMで RefNew/RefGet/RefSet/Weak* だけ実装(Barrier/Safepointはダミー) + + Call の effects を型検査に組み込み(PURE違反を検出) + + 余力が出たら Phi/Select を使うパスを追加(CSE/DCEの足場) + +必要なら、この v0.1 をそのまま mir.rs の enum 定義に落とし込んだ雛形コードを書けるよ。 +今のNyashの型やBox拡張の実装方針があれば、それに合わせて微調整版を作るにゃ。 +あなた: +おーありがとにゃ。しかしmirはみんなばらばらというけど ここからネイディブビルドにしやすいかたちをするから にているかきかたにもなってるのかにゃ。あと これ 業界標準つくれそうだよね。所詮はノイマンコンピューターに落とし込む作業だにゃ +ChatGPT: + +にゃ、その直感かなり当たってる。 +各言語の MIR は“名前も中身もバラバラ”だけど、ネイティブに落としやすい形にすると結局だいたい似てくるにゃ。 +みんなが似てくる理由(ネイティブ目線) + + SSA+CFG+3アドレス:最適化&レジ割りしやすい定番の骨格 + + 明示的なメモリ操作:Alloc/Load/Store/GEP 相当が要る + + 呼び出しの正規化:Call/TailCall と 呼出規約(ABI) の分離 + + 効果注釈(副作用):PURE/READ/WRITE/IO/FFI があると最適化が安全 + + 例外/パニックの下位表現:Throw/Catch を選択的に lower できる形 + + GCフック:Safepoint & Barrier を差し込める + + つまり「高級機能は段階的に下げられる素朴な命令に割り付け」→最後は von Neumann(命令+メモリ)に落ちる、という流れで収束するにゃ。 + +「業界標準」を作れる?→“実質標準”なら行ける + +完全統一は難しい(言語ごとに型・例外・GCが違いすぎる)が、コア・プロファイルを決めた“実質標準”は作れるにゃ。 +標準に向く設計の芯(Nyash版にもそのまま効く) + + Core-IR(必須):Const/BinOp/Cmp/Phi/Br/Jmp/Ret + Load/Store/Gep + Call/TailCall + + Memory Model:アトミック/順序・別名(noalias)/アライン属性の最小集合 + + Effects:命令・関数の EffectMask を規定(最適化の安全条件に使う) + + GC hooks:Safepoint/Barrier は仕様だけ先に固定(実装はno-op可) + + Exception ABI:Throw/Catch を「setjmp/longjmp的」or「結果型(Result)」の2系で規定 + + FFI/拡張 ABI:FfiCall/BoxCall の呼出規約・ポインタ安全域を決める + + 検証器(Verifier):終端命令必須・SSA整合・型整合・効果整合をチェック + +“標準化”の現実解(おすすめルート) + + MLIR 方言として定義(nyash.core, nyash.gc みたいに分割) + + もしくは Cranelift IR 互換サブセットを Core として採用し、足りない所だけ拡張 + + テキスト表現+バイナリ表現(例: JSON/FlatBuffers)と ダンプ・復元ツールを提供 + + リファレンス下げ先を複数用意: + + Core → Cranelift(JIT/AOT) + + Core → LLVM(AOTヘビー級) + + Core → WASM(ブラウザ/サンドボックス) + + 検証テスト:黄金テスト(IRダンプ)+ VM/JIT/WASM の 同一結果保証スイート + +すぐ使える“ネイティブ寄り”指針(短冊) + + 命令は副作用を明示、暗黙のメモリ変更はナシ + + ループ先頭・Call直後にSafepoint(後からGC導入しやすい) + + 例外は2段構え:IRでは Throw/Catch、lower で Result/landingpad に落とせる + + Weak は Option に必ず現れる(nullをぼかさない) + + FFIはPinかコピーしか渡さない(危険な参照共有を禁止) + +まとめ + + はい、MIRはネイティブ都合で“似てくる”。 + + 完全共通規格は難しいけど、**Core-IR+拡張の“実質標準”**は作れる。 + + Nyashの v0.1 命令セットは、そのまま Core-IRたたき台になれる出来だにゃ。 + +必要なら、この Core-IR を MLIR 方言か Cranelift互換サブセット仕様として文書化して、 +テキスト仕様+最小リファレンス実装(ダンプ/検証/Cranelift下げ)を私が一気に草案化するよ。どう攻める?(MLIR方言でいくか、Cranelift寄りでいくか) +あなた: +所で中間言語は何を指標に作ればいいにゃ?メモリー管理はわかるけど好き勝手に作る訳にも行けないにゃ それこそフォンノイマンのパソコンを念頭に考えればいいだけにゃ?CPUの命令セットとか? +ChatGPT: + +いい質問にゃ! +中間言語(IR/MIR)を“何を指標に”設計するかは、単に「CPUに近づける」だけだと失敗しがち。 +実務では次の“指標セット”でバランスを取るのがコツだにゃ。 +まず決めるべき指標(優先度つけてOK) + + ターゲットと目的 + + どこに落とす? → VM / JIT(Cranelift) / AOT(rustc/LLVM) / WASM + + 何を優先? → 起動の速さ、最適化余地、移植性、デバッグ性 + + 抽象度(レベル) + + 高すぎる:最適化しにくい/JIT実装が難航 + + 低すぎる(CPU寄り):言語機能の意味が消えて最適化の根拠を失う + → 目安:SSA+基本ブロック+3アドレスを軸に、「言語に固有の意味(例: 効果、副作用、所有/弱参照)」は属性や専用命令で残す + + メモリモデル(超重要) + + 参照の表現:ref/weak/タグ付き値 + + GC/RC hooks:Safepoint、BarrierRead/Write の差し込み位置を規定 + + 別名・所有:noalias/readonly/owned/borrowed など最適化に効く注釈 + + (並行を視野なら)原子性・順序の最小集合(Acquire/Release程度) + + 効果システム(副作用の面) + + PURE / READS_HEAP / WRITES_HEAP / IO / FFI / PANIC のEffectMask + + 最適化の“安全条件”をここで機械的に判断できるようにする + + 制御フローと例外 + + CFG+SSA、Phi/Br/Jmp/Ret + + 例外はIRでは抽象(Throw/Catch)、loweringで Result/landingpad 等へ落とせる形に + + 呼び出し規約と拡張ABI + + Call/TailCall と FfiCall/BoxCall を分離 + + 可変長/キーワード引数の表現、Pin/Unpinの扱い + + 検証可能性 & ツール性 + + Verifierで:型一致・SSA整合・終端命令必須・効果整合をチェック + + テキスト表現(ダンプ)と黄金テスト(差分テスト)を最初から用意 + +“CPU/フォン・ノイマンだけ見れば良い?”への答え + + No(それだけでは足りない)。 + CPU命令セットを直に意識しすぎると、**言語の意味(純粋性・所有・弱参照・例外の契約)**が失われて最適化や検証が難しくなる。 + + ただし最終的にそこへ下げやすい形は大事。だから + + 上層の意味は 属性/メタで保持 + + 下層(Load/Store/GEP/Call/TailCall)へ機械的に落とせるカバレッジを確保 + → これが “ネイティブに落としやすく、でも言語の意味を保ったIR” のコア指標にゃ。 + +具体:設計を導くチェックリスト(配点付き) + +各 0〜2 点で採点してみて。合計が高い案が「良いIR」。 + + 後段互換性(JIT/AOT/WASMに素直に下がる) + + 最適化の根拠(効果・別名・型・所有などが保持される) + + 実装容易性(VMでまず回せる/Craneliftへ写経しやすい) + + 検証容易性(Verifierで機械的に壊れを検出できる) + + 将来拡張(弱参照/GC切替/例外方式変更に耐える) + + 可観測性(テキストIR・ソース位置・deopt情報が取れる) + +迷ったらこの“型”に寄せると楽 + + 骨格:SSA + CFG + 3アドレス + + コア命令:Const/BinOp/Cmp/Phi/Br/Jmp/Ret/Load/Store/Gep/Call/TailCall + + 言語特有:RefNew/RefGet/RefSet/WeakNew/WeakLoad/Barrier*/Safepoint + EffectMask + + 境界:FfiCall/BoxCall(ABI最小化) + + 例外:Throw/Catch(loweringで切替可能) + → これは Craneliftに下げやすく、Rust/WASMにも展開しやすい黄金比にゃ。 + +参考までに:3つの設計モード + + Cranelift互換サブセット志向(JIT/AOT重視・実装が速い) + + MLIR方言志向(将来の拡張やツール連携が強い) + + Rust MIR/Swift SIL 風(所有/効果を濃く持つ・言語意味を守りやすい) + +Nyashなら:Cranelift互換サブセット+言語特有の効果/弱参照/GCフックを足すのがバランス最強にゃ。 +最後に:失敗しない順序 + + 目的とターゲット(VM/JIT/AOT/WASMの優先度)を1行で宣言 + + Core命令セット+EffectMask+メモリモデル(weak/GC hook)を先に固定 + + Verifierとテキストダンプ(黄金テスト)を最初に入れる + + VM実装 → Cranelift下げ → AOT/WASMは後から + +この順なら「好き勝手」じゃなく指標に沿って進められるにゃ。 +必要なら、いまのNyashの要件を点数表で一緒に採点して、MIR v0.1を最終確定しよっか? +あなた: +おねがいにゃー! +ChatGPT: + +任せてにゃ! +Nyash向けに「指標の採点 → その結果に沿った MIR v0.1 最終版」を一気にまとめたよ。すぐ実装に落とせる形にしてあるにゃ。 +指標チェック(Nyash想定で採点済み) + +(各0〜2点、合計12点満点) +指標 狙い Nyashの前提 点 +後段互換性 VM/JIT/AOT/WASMに素直に下げられる まずVM→Cranelift JIT、次にAOT/WASM 2 +最適化の根拠 効果・別名・所有/弱参照を保持 EffectMask+ref/weak+Barrier/SafepointをMIRで表現 2 +実装容易性 まずVMが回る 命令は3アドレス+最小集合から 2 +検証容易性 Verifierで壊れ検出 SSA/型/終端/効果の整合を必須に 2 +将来拡張 例外・GC切替・FFI拡張に耐える Throw/Catch・BoxCall/FFI・Barrierはno-opで開始 2 +可観測性 ダンプ/位置情報/Deoptが取れる テキストIR+dbg(loc)+deopt_map 2 + +合計:12/12(この方針で進めてOKにゃ) +Nyash MIR v0.1(最終版) +コアモデル + + SSA値 vN、基本ブロック bbN(末尾は終端命令必須) + + 型(最小):i64|f64|bool|unit|ref|weak|ptr|any|option + + 効果 EffectMask:PURE|READS_HEAP|WRITES_HEAP|IO|FFI|PANIC(ビット和) + + 関数署名:fn(args…)->ret [effects] + +命令セット +1) 演算・制御 + +Const dst, Imm +BinOp dst, op, a, b ; add/sub/mul/div/mod/and/or/xor/shl/shr +Cmp dst, rel, a, b ; eq/ne/lt/le/gt/ge +Select dst, cond, a, b +Phi dst, [(predBB, val), …] + +Br cond, thenBB, elseBB ; 終端 +Jmp targetBB ; 終端 +Ret [val] ; 終端(unit省略可) +Unreachable ; 終端 + +2) メモリ/参照(GC想定) + +Alloc dst, Ty, size? ; [WRITES_HEAP] +Load dst, addr ; [READS_HEAP] +Store addr, val ; [WRITES_HEAP] +Gep dst, base, offset + +RefNew dst, Ty ; ref [WRITES_HEAP] +RefGet dst, ref, field ; [READS_HEAP] +RefSet ref, field, val ; [WRITES_HEAP] + +WeakNew dst, ref ; weak [PURE] +WeakLoad dst, weak ; option> [PURE](実装都合でREADS_HEAP可) + +BarrierRead ref +BarrierWrite ref +Pin ref +Unpin ref +Safepoint + +弱参照の意味論 + + WeakNew(r) は所有しない。r がGCで解放されると弱参照は無効化。 + + WeakLoad(w) は 生存: Some(ref)/死亡: None を返す(nullを曖昧にしない)。 + +3) 呼び出し・例外・拡張 + +Call dst, callee, [args...] ; 呼び先の effects を合成 +TailCall callee, [args...] ; 終端 + +BoxCall dst, box_id, fn_id, [args...] ; Nyash拡張Box [FFI|PANIC?] +FfiCall dst, sym, [args...], abi ; 外部関数 [FFI|PANIC?] + +Throw val ; 終端 +CatchBegin dst, handlerBB ; (メタでも可) +CatchEnd +Assume cond ; 偽ならUB:最適化ヒント +Nop + +不変条件(Verifier で必須チェック) + + 各ブロックは必ず終端命令で終わる + + 型整合:Load/Store/Call/WeakLoad 等の型が一致 + + SSA整合:Phi の前任ブロック集合=到達前任集合 + + 効果整合:PURE な関数内で WRITES_HEAP/IO/FFI を出さない + + WeakLoad戻りは必ず option>(null直扱い禁止) + +推奨挿入ポイント + + Safepoint:関数入口/各ループ先頭/任意の Call の直後 + + Barrier*:はじめは no-op 実装でもOK(将来GC切替のフック) + +テキスト表現(ダンプ例) + +func @main() -> unit [effects=IO] { +bb0: + v1 = Const i64 1 + v2 = RefNew Obj + RefSet v2, field_y, v1 + v3 = WeakNew v2 + v4 = WeakLoad v3 ; option> + Br is_some(v4), bb1, bb2 + +bb1: + v5 = unwrap v4 + BarrierWrite v5 + RefSet v5, field_y, Const i64 2 + Jmp bb3 + +bb2: + Jmp bb3 + +bb3: + Ret +} + +実装ロードマップ(最短で回す) + + IR型 & ダンプ & Verifier を実装(黄金テストに登録) + + VM:RefNew/RefGet/RefSet/WeakNew/WeakLoad と制御命令だけ先に実装 + + 効果検査:Call に effects 合成(違反はビルド失敗) + + Cranelift JIT 足場:算術・分岐・Call を写経、Ref* はランタイム関数に委譲 + + AOT to Rust:ref=Gc、weak=Weak 相当でコード出力(小関数から) + +付録:Rustスケルトン(抜粋) + +bitflags::bitflags! { + pub struct Effect: u32 { + const PURE = 1<<0; + const READS_HEAP = 1<<1; + const WRITES_HEAP = 1<<2; + const IO = 1<<3; + const FFI = 1<<4; + const PANIC = 1<<5; + } +} + +pub enum Ty { + I64, F64, Bool, Unit, Ptr, Any, + Ref(Box), Weak(Box), Option(Box), +} + +pub enum Inst { /* 上述の命令そのまま */ } + +pub struct Func { + pub sig: FuncSig, pub blocks: Vec, /* dbg, deopt_map など */ +} + +pub fn verify(func: &Func) -> Result<(), VerifyError> { + // 終端必須・SSA整合・型整合・効果整合をチェック + Ok(()) +} + +次の一手(今日できること) + + mir/inst.rs にこの v0.1 をそのまま貼り込み + + mir/dump.rs と mir/verify.rs を最小実装 + + 既存テストに 黄金テスト(IRダンプ) を1本追加 + + VMの Ref*/Weak* を実装して 最初の end-to-end テスト を通す + +これで、行き当たりばったりの修正が入っても壊れにくい土台が完成にゃ。 +必要なら、このままコード雛形まで私が書き起こすよ。 \ No newline at end of file diff --git a/docs/予定/native-plan/chatgpt5との会話.txt b/docs/development/roadmap/native-plan/chatgpt5との会話.txt similarity index 100% rename from docs/予定/native-plan/chatgpt5との会話.txt rename to docs/development/roadmap/native-plan/chatgpt5との会話.txt diff --git a/docs/予定/native-plan/copilot_issues.txt b/docs/development/roadmap/native-plan/copilot_issues.txt similarity index 100% rename from docs/予定/native-plan/copilot_issues.txt rename to docs/development/roadmap/native-plan/copilot_issues.txt diff --git a/docs/予定/native-plan/copilot_issues_20250814_135116_backup.txt b/docs/development/roadmap/native-plan/copilot_issues_20250814_135116_backup.txt similarity index 100% rename from docs/予定/native-plan/copilot_issues_20250814_135116_backup.txt rename to docs/development/roadmap/native-plan/copilot_issues_20250814_135116_backup.txt diff --git a/docs/development/roadmap/native-plan/copilot_issues_phase0_to_94.txt b/docs/development/roadmap/native-plan/copilot_issues_phase0_to_94.txt new file mode 100644 index 00000000..5452bd09 --- /dev/null +++ b/docs/development/roadmap/native-plan/copilot_issues_phase0_to_94.txt @@ -0,0 +1,657 @@ +# 🤖 Copilot様 作業予定・課題整理 (Phase 0-9.4 アーカイブ版) +# Generated: 2025-08-14 (Git履歴から復元・更新) +# Purpose: Claude×Copilot協調開発のための情報共有 +# Status: Phase 9.5より前のアーカイブ版(2025-08-15分割) + +================================================================================ +🎯 次期最優先タスク (Phase 8.5以降) +================================================================================ + +## 🚀 Phase 8.4完了報告 (2025-08-14) +Status: ✅ 完了 (Copilot PR #56マージ済み) + +### ✅ AST→MIR Lowering完全実装 +- User-defined Box: `box DataBox { init { value } }` +- Object creation: `new DataBox(42)` +- Field access: `obj.value` +- Method calls: `c.increment()` +- Delegation: `from Parent.greet()` +- Static Main互換性維持 + +### 🧪 統合テスト結果(2025-08-14) +- ✅ **AST→MIR**: 完全動作 +- ✅ **インタープリター**: 完全動作(結果30) +- 🚨 **VM**: 動作するが結果が`void`(要修正) +- 🚨 **WASM**: String constant未対応(Phase 8.5で解決) + +### 📋 発見された課題 +- VM実行結果問題: BoxCall後の戻り値が正しく返らない +- WASM対応不足: 複雑なMIR命令(String constant, BoxCall)に未対応 +- 次期Phase 8.5での25命令MIR階層化が必要 + +================================================================================ + +## 🔧 Phase 8.5: MIR 26命令階層化(最優先) +Status: ⭐ **CRITICAL** +Priority: **最重要** (Phase 8.4完了直後の次期目標) + +### 🎯 実装目標 +ChatGPT5 + AI大会議決定版26命令MIR実装(ExternCall追加) +- 期間: 3週間 +- 効果: VM/WASM問題根本解決 +- 詳細仕様: `/docs/予定/native-plan/issues/phase_8_5_mir_25_instruction_specification.md` + +### 📋 26命令セマンティック階層化 +**Tier-0: 普遍コア(8命令)** +```mir +Const, BinOp, Compare, Branch, Jump, Phi, Call, Return +``` + +**Tier-1: Nyashセマンティクス(13命令)** +```mir +NewBox, BoxFieldLoad, BoxFieldStore, BoxCall, ExternCall, Safepoint, +RefGet, RefSet, WeakNew, WeakLoad, WeakCheck, Send, Recv +``` + +**Tier-2: 実装補助・最適化友好(5命令)** +```mir +TailCall, Adopt, Release, MemCopy, AtomicFence +``` + +### 🎯 期待される効果 +- **VM問題解決**: BoxCallの正しい実装で戻り値問題修正 +- **WASM対応**: 階層化により複雑MIR→単純WASM変換 +- **Everything is Box**: BoxFieldLoad/Storeで明確なBox中心設計 +- **JIT準備**: セマンティクス保持で高度最適化基盤確立 + +================================================================================ + +## 🏎️ Phase 8.6: VM性能改善(緊急) +Status: 🚨 **緊急** +Priority: **High** (Phase 8.5完了後) + +### 🚨 緊急問題 +**現状**: VM(119.80ms)< Interpreter(110.10ms)= 0.9倍の性能劣化 +**新問題**: VM BoxCall後の戻り値が`void`(Phase 8.4テストで発見) + +### 📋 技術的課題 +- VM実行エンジンのプロファイリング +- 命令ディスパッチ最適化(threaded code等) +- レジスタベースVM化検討 +- メモリプール最適化 +- BoxCall実装修正(戻り値問題) + +### 🎯 成功基準 +- VM性能 > Interpreter性能(最低2倍目標) +- BoxCall戻り値の正常動作 +- MIR→VM変換時間の短縮 + +================================================================================ + +## 🧪 Phase 8.7: Real-world Memory Testing +Status: 📋 **計画済み** +Priority: **High** (Phase 8.5-8.6完了後) + +### 🎯 実装目標 +kilo(テキストエディタ)実装によるfini/weak参照システム実証 +- 期間: 2週間 +- 詳細仕様: `/docs/予定/native-plan/issues/phase_8_7_real_world_memory_testing.md` + +### 📋 検証項目 +- 1000+オブジェクト管理テスト +- 循環参照回避確認(weak参照) +- fini()伝播の正確性確認 +- WASM環境での動作確認 + +================================================================================ +🗺️ Phase 0-14 全体ロードマップ (復元完了) +================================================================================ + +## Phase 0: Stabilize native CLI build (Linux/Windows) + +Summary: +- CLIバイナリ nyash を最小構成で安定ビルド・実行できる状態にする。 +- examples/GUI をデフォルトのビルド対象から外し、開発の足場を固める。 + +Why: +- 以降の MIR/VM/JIT 開発を素早く検証できる基盤づくり。 + +Scope: +- Cargo の features で GUI/examples 等を切り分け、デフォルトは CLI 最小にする。 +- CLI オプションの動作点検(--dump-mir / --verify)。 +- ローカル実行導線を README に明記(docs/guides/how-to-build-native/README.md)。 + +Tasks: +- Cargo.toml: examples/GUI を feature でガード(default は CLI 最小)。 +- ビルド検証: `cargo build --bin nyash`(Linux/Windows)。 +- 実行検証: `cargo run -- ./local_tests/sample.nyash`。 +- ドキュメント: 上記手順を how-to-build-native に追記/点検。 + +Acceptance Criteria: +- Linux/Windows で `cargo build --bin nyash` が成功する。 +- `local_tests/` 配下の簡単な .nyash が実行できる。 +- 他 bin/examples が壊れていても `--bin nyash` だけで通る。 + +Out of Scope: +- examples/GUI の修理・最適化。 +- JIT/AOT/WASM。 + +References: +- docs/guides/how-to-build-native/README.md +- docs/nativebuild大作戦/chatgptネイティブビルド大作戦.txt(Phase 0) +- CURRENT_TASK.md + +Copilot Notes: +- まずは features 分離と `--bin nyash` でビルドが通る状態を作る。README の手順確認まで含めて PR に反映。 + +------------------------------------------------------------ + +## Phase 1: Minimal MIR + VM backend (lowering + runner) + +Summary: +- AST → MIR の最小 lowering と、VM バックエンドでの実行を通す。 + +Scope: +- MIR: Const, BinOp, Compare, Branch, Jump, Phi, Return の最小命令 +- Lowering: リテラル/二項演算/if/loop/return のみ +- VM: 上記命令の最小実装 + +Tasks: +- instruction.rs: 最小命令の定義 +- builder.rs: 上記 AST 範囲を lowering +- vm.rs: 実装 + stats(命令数) + +Acceptance Criteria: +- `--dump-mir` が最小サンプルで期待通り +- `--backend vm` で実行して結果一致 + +Out of Scope: +- 例外/関数/Box 参照/弱参照 + +------------------------------------------------------------ + +## Phase 2: Control-flow coverage (if/else/loop/phi correctness) + +Summary: +- 制御フローの網羅と Phi の整合性検証を拡充。 + +Scope/Tasks: +- if/else nested, loop with breaks, nested loops のスナップショット +- Phi の入力ブロック/値の対応を Verifier で強化 + +Acceptance Criteria: +- 代表制御フローの snapshot が安定し、verify も通る + +------------------------------------------------------------ + +## Phase 3: Exceptions (throw/try/catch/finally) minimal lowering + +Summary: +- 例外機構の最小 lowering を導入(詳細設計は簡素)。 + +Scope/Tasks: +- MIR: Throw, TryBegin/TryEnd, Catch, FinallyBegin/End(最小) +- builder.rs: try/catch/finally ノードの下ろし +- VM: 例外伝播を最小で(未捕捉はエラー) + +Acceptance Criteria: +- 代表 try/catch/finally のスナップショットと VM 実行 + +Out of Scope: +- 例外の型体系、詳細な stack map + +------------------------------------------------------------ + +## Phase 4: Functions and calls (BoxCall minimal) + +Summary: +- 関数呼び出し/BoxCall を最小導入(効果注釈は保守的)。 + +Scope/Tasks: +- MIR: Call, BoxCall(effects = READS_HEAP など保守) +- builder.rs: FunctionCall/MethodCall の最小対応 +- VM: 呼び出し/戻り値 + +Acceptance Criteria: +- 簡単な関数定義/呼び出しの MIR/VM が通る + +Out of Scope: +- 可変長/キーワード引数、FFI + +------------------------------------------------------------ + +## Phase 5.0: Parser/AST stabilization for lowering + +Summary: +- lowering 対象 AST の表現ぶれを修正、安定化。 + +Scope/Tasks: +- AST: If/Loop/Return/Assignment/Local などの統一 +- Parser: エラー復帰/スパン情報の見直し + +Acceptance Criteria: +- builder.rs の分岐がシンプル化、テストが安定 + +------------------------------------------------------------ + +## Phase 5.1: Control-flow edge cases + verifier hardening + +Summary: +- ブロック未終端/未到達/自己分岐等の検証強化でクラッシュ回避。 + +Scope/Tasks: +- Verifier: 未終端ブロック検出、到達不能検出 +- Builder: Jump/Branch の生成前後の状態管理改善 + +Acceptance Criteria: +- 不正ケースを含むスナップショット/verify が緑 + +------------------------------------------------------------ + +## Phase 5.2: Lowering for static box Main (BoxDeclaration → main body) + +Summary: +- static box Main { main() { ... } } を MirBuilder で受け、main() の body を Program として lowering する経路を実装。 + +Scope/Tasks: +- AST: BoxDeclaration(is_static=true, name=Main) を検出 → main() を抽出 +- Lowering: body を Program に変換して既存経路に渡す +- Tests: local_tests/mir_loop_no_local.nyash で dump/VM が通る + +Acceptance Criteria: +- `--dump-mir` が static Main サンプルで成功 +- `--backend vm` で実行成功 + +References: +- docs/guides/how-to-build-native/issues/phase5_2_static_main_lowering.md + +------------------------------------------------------------ + +## Phase 6: Box ops minimal (Ref/Weak + Barriers no-op) + +Summary: +- 参照/弱参照/バリア(no-op)を最小導入。 + +Scope/Tasks: +- MIR: RefNew/RefGet/RefSet/WeakNew/WeakLoad/BarrierRead/Write +- Lowering: New/FieldAccess/MethodCall の最小対応 +- VM: 参照テーブル/weak テーブルで動作(fini 不変は維持) + +Acceptance Criteria: +- 代表サンプルで dump/VM/verify が通る + +References: +- docs/guides/how-to-build-native/issues/phase6_box_ops_minimal.md + +------------------------------------------------------------ + +## Phase 7: Async model (nowait/await) in MIR + +Summary: +- nowait/await を MIR に導入し、現行 FutureBox と連携。 + +Scope/Tasks: +- MIR: FutureNew/FutureSet/Await(スレッドベース) +- Lowering: nowait→Future 作成、await→wait_and_get +- VM: FutureBox 実装を利用 + +Acceptance Criteria: +- 代表ケースで正しく並行実行→await 回収 + +References: +- docs/guides/how-to-build-native/issues/phase7_async_mir.md + +------------------------------------------------------------ + +## Phase 8: MIR→WASM codegen (browser/wasmtime; sandboxed; Rust runtime free) + +Summary: +- MIR から素の WebAssembly を生成し、ブラウザ/wasmtime(WASI)でサンドボックス実行する。 +- Rust はコンパイラ本体のみ。実行は純WASM+ホストimport(env.print など)。 + +Scope/Tasks: +- ABI/Imports/Exports 定義(exports: main/memory、imports: env.print(i32) 等の最小) +- 線形メモリと簡易ヒープ(bump/自由リスト) +- 命令カバレッジ(段階導入): 算術/比較/分岐/loop/return/print、RefNew/RefSet/RefGet(Phase 6 整合)、Weak/Barrier はダミー + +Acceptance Criteria: +- wasmtime 実行で戻り値/print が期待通り(PoC1–2) +- Ref 系がメモリ上で正しく動作(PoC2) +- Weak/Barrier のダミー実装を含むWASMが生成・実行(PoC3) +- CLI `--backend wasm` は未実装でもよいが、実装する場合は明瞭にエラーメッセージ/誘導 + +References: +- docs/予定/native-plan/README.md(Phase 8 節) +- docs/説明書/wasm/*(ユーザー向けメモ) + +### Phase 8.3 完了状況 (2025-08-14) +✅ Box操作WASM実装 (RefNew/RefGet/RefSet) +✅ ベンチマークシステム統合 (13.5倍実行高速化実証) +✅ CLI統合完了 + +------------------------------------------------------------ + +## 🔧 Phase 8.4: AST→MIR Lowering完全実装 (最優先) + +Summary: +- ユーザー定義Box、フィールドアクセス等の未実装部分を完成 +- Phase 8.3のBox操作WASMを実際にテスト可能にする + +Priority: **Critical** (現在の最優先事項) +Expected Duration: 1週間 + +### 実装範囲 +- [ ] ユーザー定義Box: `box DataBox { init { field } }` +- [ ] オブジェクト生成: `new DataBox()` +- [ ] フィールドアクセス: `obj.field` +- [ ] フィールド代入: `obj.field = value` +- [ ] from構文: `from Parent.method()` +- [ ] override構文: `override method() { ... }` + +### 成功基準 +- Phase 8.3のBox操作WASMが実際に動作 +- test_wasm_box_ops.nyash が正常実行 +- ユーザー定義Boxの完全サポート + +------------------------------------------------------------ + +## 🧠 Phase 8.5: MIRセマンティック階層化(AI大会議決定版) + +Summary: +- 方針転換: ChatGPT5の20命令intrinsic戦略 → Gemini+Codex一致推奨の26命令階層化(ExternCall追加) +- 理由: JIT/AOT最適化阻害・Everything is Box意味喪失・長期コスト増の問題判明 +- 二相ロワリング: 26命令維持パス(VM/JIT/AOT)+ 21+intrinsic降格パス(WASM/最小実装) + +Priority: High (Phase 8.4完了後) +Expected Duration: 3週間 + +### AI大会議分析結果 +**Gemini先生(理論)**: 「賢いコンパイラは、賢いMIRから生まれる」 +- RefNew/WeakLoadのintrinsic化は最適化機会を失う悪手 +- セマンティック階層化で意味保持が最適化の鍵 + +**Codex先生(実装)**: 二相ロワリング戦略が実用的最適解 +- 実装コスト: 5命令追加で10-20人日(intrinsic戦略より安い) +- マイクロベンチ実測でパフォーマンス検証 + +### 確定版MIR(26命令)- ChatGPT5完全仕様 + ExternCall統合 +**Tier-0: 普遍的コア(8命令)** +```mir +Const, BinOp, Compare, Branch, Jump, Phi, Call, Return +``` + +**Tier-1: Nyashセマンティクス(13命令)** +```mir +NewBox, // 強所有のBox生成(所有森のノード) +BoxFieldLoad, // Boxのフィールド読み(Everything is Box核心) +BoxFieldStore, // Boxのフィールド書き(mut効果) +BoxCall, // Boxのメソッド呼び出し(動的/静的両方) +ExternCall, // 外部ライブラリをBoxとして呼び出し(Universal Exchange) +Safepoint, // 分割finiや割込み許可ポイント +RefGet, // 参照(強/弱を問わず)を値として取得 +RefSet, // 参照の差し替え(所有規則検証付き) +WeakNew, // weak ハンドル生成(非所有リンク作成) +WeakLoad, // weak から生存チェック付きで強参照取得(失効時null) +WeakCheck, // weak の生存確認(bool) +Send, // Bus送信(io効果) +Recv // Bus受信(io効果) +``` + +**Tier-2: 実装補助・最適化友好(5命令)** +```mir +TailCall, // 末尾呼び出し(スタック節約) +Adopt, // 所有移管: this が子を強所有に取り込む +Release, // 強所有を解除(weak化 or null化) +MemCopy, // 小さなメモリ移動(構造体/配列最適化フック) +AtomicFence // 並行時の順序保証(Actor/Port境界で使用) +``` + +### 二相ロワリング戦略 +- パスA: VM/JIT/AOT向け(26命令のまま最適化) +- パスB: WASM/最小実装向け(26→21+intrinsic降格) +- バックエンド能力に応じて最適形式選択 + +### 効果(Effect)システム(ChatGPT5設計 + ExternCall統合) +- **pure**: Const, BinOp, Compare, Phi, RefGet, WeakNew, WeakLoad, WeakCheck +- **mut**: BoxFieldStore, RefSet, Adopt, Release, MemCopy +- **io**: Send, Recv, Safepoint, AtomicFence +- **control**: Branch, Jump, Return, TailCall +- **context依存**: Call, BoxCall, ExternCall(呼び先効果に従属・BID定義に基づく) + +**最適化ルール**: 「pure同士の再順序化OK」「mutは同一Box/同一Fieldで依存保持」「ioは再順序化禁止」 + +### 検証(Verifier)要件 +- **所有森**: `strong in-degree ≤ 1`(NewBox/Adopt/Release/RefSetで常時検査) +- **強循環禁止**: 強エッジのみ辿ってDAG(森)であること +- **weak/強相互**: 双方向とも強 → エラー(片側はWeakNew経由で弱化) +- **WeakLoad/WeakCheck**: 失効時はnull/falseを返す(例外禁止、決定的挙動) + +### 🤖 Copilot協力期待 +- **Tier-0/1実装**: Everything is Box哲学の完璧なIR化(BoxFieldLoad/Store核心) +- **weak参照システム**: WeakNew/WeakLoad/WeakCheck三位一体実装 +- **所有移管**: Adopt/Release命令による安全で効率的なメモリ管理 +- **効果システム**: pure/mut/io/control効果の正確な実装とVerifier統合 +- **最適化フック**: TailCall/MemCopy/AtomicFenceの実装補助 +- **二相ロワリング**: 25命令維持パス + 20+intrinsic降格パス構築 + +### 成功基準 +- [ ] **26命令完全実装**: ChatGPT5仕様 + ExternCall統合の完璧な実装 +- [ ] **効果システム動作**: pure再順序化・mut依存保持・io順序保証 +- [ ] **Verifier動作**: 所有森・strong循環・安全性検証 +- [ ] **Golden MIRテスト**: 全バックエンドでMIR一致 +- [ ] **行動一致テスト**: 同入力→同出力(weak失効時null/false含む) +- [ ] **性能要件**: VM≥Interpreter、WASM≥VM継続検証 + +### バックエンド指針(ChatGPT5設計 + ExternCall統合) +- **Interpreter**: 26命令を素直に実装(正しさの基準) +- **VM**: Register-VM + direct-threading。Send/Recvはローカル判定時にインライン化 +- **WASM**: Send/Recvはhost import。MemCopyはmemory.copyに対応 +- **JIT(将来)**: TailCall最適化、WeakLoadは世代タグでO(1)生存チェック + +References: +- docs/予定/native-plan/MIR仕様書.txt(ChatGPT5完全仕様) +- docs/予定/native-plan/issues/phase_8_5_mir_25_instruction_specification.md + +------------------------------------------------------------ + +## 🏎️ Phase 8.6: VM性能改善 (緊急) + +Summary: +- VMがインタープリターより遅い問題(0.9倍)を解決 +- MIR→VM実行の最適化でインタープリターを上回る性能へ + +Priority: High (Phase 8.5完了後) +Expected Duration: 2週間 + +### 問題分析 +**現状**: VM (119.80ms) < Interpreter (110.10ms) +**推定原因**: +- MIR変換オーバーヘッド +- VM命令ディスパッチの非効率性 +- メモリ管理コスト + +### 技術的アプローチ +- [ ] VM実行エンジンのプロファイリング +- [ ] 命令ディスパッチ最適化(threaded code等) +- [ ] レジスタベースVM化検討 +- [ ] メモリプール最適化 + +### 🤖 Copilot協力期待 +- VM実装のボトルネック特定 +- 効率的な命令ディスパッチ実装 +- スタックマシン vs レジスタマシン判断 + +### 成功基準 +- VM性能 > Interpreter性能(最低2倍目標) +- MIR→VM変換時間の短縮 +- メモリ使用量の削減 + +------------------------------------------------------------ + +## 🧪 Phase 8.7: Real-world Memory Management Testing (ChatGPT協調設計) + +Summary: +- 実用アプリケーション開発によるNyashメモリ管理システムの実証テスト +- finiシステム・weak参照の実用性を複雑なアプリケーションで検証 + +Priority: High (Phase 8.4-8.6完了直後) +Expected Duration: 2週間 + +### Phase 8.7A: kilo(テキストエディタ) +**技術的特徴**: +- サイズ: <1k LOC(超小型、最初の成功体験) +- メモリパターン: Editor -> (Rows -> Syntax) 木構造+相互参照 +- ChatGPT設計: Editor削除でRows自動解放、逆参照をweak化 + +**実装範囲**: +- [ ] Editor/Row/EditorState基本構造実装 +- [ ] weak参照による循環参照回避(`me.editor = weak editor_ref`) +- [ ] fini()システムによる自動メモリ解放 +- [ ] 大量オブジェクト(1000+ Rows)管理テスト + +**検証ポイント**: +- [ ] Editor削除でRows自動解放確認 +- [ ] 相互参照でメモリリークなし確認 +- [ ] weak参照の自動null化確認 +- [ ] fini()伝播の正確性確認 + +### Phase 9.5予定: tiny-web-server(HTTPサーバ) +**将来実装**(JIT実装後): +- 複雑度: 中〜高(Server -> Clients -> Requests並行処理) +- I/O管理: ソケット・ファイルハンドルの確実解放 +- 同時接続・早期切断・例外経路でのfini伝播テスト + +### 🤖 Copilot協力期待 +- 実用的なメモリ管理パターンの実装 +- weak参照構文の適切な使用 +- デバッグ支援機能(--debug-memory, --trace-weak) +- WASM環境でのメモリ管理互換性 + +### 成功基準 +- [ ] 全テストケースでメモリリークなし +- [ ] 循環参照でも正常解放確認 +- [ ] WASM実行でもメモリ管理正常 +- [ ] ベンチマーク性能劣化なし + +### 期待される効果 +- Nyashメモリ管理システムの実用性実証 +- Everything is Box哲学の実用レベル確認 +- メモリ安全なプログラミングパターン確立 + +References: +- docs/予定/native-plan/issues/phase_8_7_real_world_memory_testing.md + +------------------------------------------------------------ + +## 🚀 Phase 9: AOT WASM実装(最優先) + +Summary: +- wasmtime compileによるAOT実行ファイル生成で確実なユーザー価値提供 + +Scope/Tasks: +- `wasmtime compile` 統合実装 +- `--compile-native` / `--aot` CLI追加 +- 単一バイナリ梱包(`include_bytes!`) +- 起動時間・配布サイズ最適化 + +Acceptance Criteria: +- `nyash --compile-native app.nyash -o app.exe` 動作 +- 起動時間大幅短縮(JIT起動コスト除去) +- 配布可能実行ファイル生成 + +Priority: **Critical** (Phase 8.6完了直後) +Expected Duration: 2-3週間 + +### 技術的実装詳細 +🤖 Copilot協力期待: +- wasmtime::Config統一実装 +- .cwasm生成・実行パイプライン +- 互換性キー管理(CPU機能・wasmtimeバージョン) +- パッケージング(単一バイナリ梱包) + +### パフォーマンス目標 +- 現在のWASM JIT (13.5倍実行) → AOT (500倍目標:起動含む) +- 配布ファイルサイズ: <10MB目標 +- 起動時間: <100ms目標 + +### 期待される効果 +- **即座実用価値**: 配布可能実行ファイル生成 +- **差別化優位**: Everything is BoxのネイティブAOT実現 +- **LLVM準備**: AOT基盤確立でLLVM移行準備 + +------------------------------------------------------------ + +## 🔴 Phase 9.51: WASM Jump/Branch実装とHTTPサーバー実用化 **【緊急修正】** + +Status: 🔴 **Critical Issue**(Phase 9実用化ブロッカー) +Summary: +- Phase 9 (PR #67) 完了後に判明した重大制約の修正 +- WASM/AOT実用化の最終仕上げ + +### 🚨 現在の問題(実用化を阻害) + +1. **WASM/AOT コンパイルエラー(最重要)** + ```bash + $ ./target/release/nyash --compile-wasm test_simple_loop.nyash + ❌ Unsupported instruction: Jump { target: BasicBlockId(1) } + ``` + **影響**: ループ・条件分岐を含む全プログラムがWASM/AOT化不可 + +2. **HTTPServerBox listen()常に失敗** + - server.bind() ✅, server.listen() ❌ always false + **影響**: HTTPサーバーが実際には動作しない + +3. **エラーハンドリング脆弱性** + - unwrap()使用箇所: 26箇所 → パニック多発リスク + +### Scope/Tasks: +**🔴 Task 1**: WASM Jump/Branch命令実装(2日) +- `src/backend/wasm/codegen.rs`にJump/Branch追加 +- ブロック深度管理(`get_block_depth`メソッド) +- ループ構造のblock/loop/end生成 + +**🔴 Task 2**: SocketBox listen()修正(1日) +- `src/boxes/socket_box.rs`の実装修正 +- SocketStatus::Listening状態管理 + +**🟡 Task 3**: エラーハンドリング改善(2日) +- HTTPServerBox/SocketBoxのunwrap()除去 +- Resultベースのエラー処理 + +**🟡 Task 4**: HTTPサーバー実用化(2日) +- スレッドプール実装(固定サイズワーカー) +- グレースフルシャットダウン + +Acceptance Criteria: +- ✅ `nyash --compile-wasm test_loop.nyash` 成功 +- ✅ HTTPサーバー実動作(curl http://localhost:8080/) +- ✅ unwrap()使用箇所: 26 → 5以下 +- ✅ WASM性能: 11.5倍 → 13.5倍達成 + +Priority: **🔴 Critical** (Phase 9.5開始前の必須修正) +Expected Duration: 1週間 + +### 詳細設計・実装指示 +📋 **完全実装ガイド**: `docs/予定/native-plan/issues/phase9_51_wasm_jump_http_fixes.md` + +🤖 **Copilot協力依頼**: +- WASM br/br_if命令実装 +- HTTPサーバーリファクタリング +- エラーハンドリング統一 + +### 期待される効果 +- **実用性達成**: ループ・HTTPサーバーのWASM/AOT化 +- **安定性向上**: パニックフリーな実装 +- **Phase 9.5準備**: 複雑アプリケーションテストの基盤確立 + +------------------------------------------------------------ + +================================================================================ +最終更新: 2025-08-15 (Phase 9.5より前をアーカイブ分割) +作成者: Claude (ドキュメント分割・整理) + +🎯 分割理由: +- copilot_issues.txtの肥大化対策(1200行→600行程度に削減) +- Phase 9.5以降の現行計画と完了済み部分の明確分離 +- ドキュメント検索性・保守性の向上 +================================================================================ \ No newline at end of file diff --git a/docs/予定/native-plan/llvm/AI-Conference-LLVM-Results.md b/docs/development/roadmap/native-plan/llvm/AI-Conference-LLVM-Results.md similarity index 100% rename from docs/予定/native-plan/llvm/AI-Conference-LLVM-Results.md rename to docs/development/roadmap/native-plan/llvm/AI-Conference-LLVM-Results.md diff --git a/docs/予定/native-plan/llvm/APE-Magic-Explained.md b/docs/development/roadmap/native-plan/llvm/APE-Magic-Explained.md similarity index 100% rename from docs/予定/native-plan/llvm/APE-Magic-Explained.md rename to docs/development/roadmap/native-plan/llvm/APE-Magic-Explained.md diff --git a/docs/予定/native-plan/llvm/Copilot-Request-LLVM-PoC.md b/docs/development/roadmap/native-plan/llvm/Copilot-Request-LLVM-PoC.md similarity index 100% rename from docs/予定/native-plan/llvm/Copilot-Request-LLVM-PoC.md rename to docs/development/roadmap/native-plan/llvm/Copilot-Request-LLVM-PoC.md diff --git a/docs/予定/native-plan/llvm/Hybrid-Future-Vision.md b/docs/development/roadmap/native-plan/llvm/Hybrid-Future-Vision.md similarity index 100% rename from docs/予定/native-plan/llvm/Hybrid-Future-Vision.md rename to docs/development/roadmap/native-plan/llvm/Hybrid-Future-Vision.md diff --git a/docs/予定/native-plan/llvm/JIT-vs-AOT-With-MIR.md b/docs/development/roadmap/native-plan/llvm/JIT-vs-AOT-With-MIR.md similarity index 100% rename from docs/予定/native-plan/llvm/JIT-vs-AOT-With-MIR.md rename to docs/development/roadmap/native-plan/llvm/JIT-vs-AOT-With-MIR.md diff --git a/docs/予定/native-plan/llvm/Phase-9.78-Implementation-Plan.md b/docs/development/roadmap/native-plan/llvm/Phase-9.78-Implementation-Plan.md similarity index 100% rename from docs/予定/native-plan/llvm/Phase-9.78-Implementation-Plan.md rename to docs/development/roadmap/native-plan/llvm/Phase-9.78-Implementation-Plan.md diff --git a/docs/予定/native-plan/llvm/Practical-Distribution-Strategy.md b/docs/development/roadmap/native-plan/llvm/Practical-Distribution-Strategy.md similarity index 100% rename from docs/予定/native-plan/llvm/Practical-Distribution-Strategy.md rename to docs/development/roadmap/native-plan/llvm/Practical-Distribution-Strategy.md diff --git a/docs/予定/native-plan/llvm/Revolutionary-Windows-Strategy.md b/docs/development/roadmap/native-plan/llvm/Revolutionary-Windows-Strategy.md similarity index 100% rename from docs/予定/native-plan/llvm/Revolutionary-Windows-Strategy.md rename to docs/development/roadmap/native-plan/llvm/Revolutionary-Windows-Strategy.md diff --git a/docs/予定/native-plan/llvm/VM-Native-Speed-Possibility.md b/docs/development/roadmap/native-plan/llvm/VM-Native-Speed-Possibility.md similarity index 100% rename from docs/予定/native-plan/llvm/VM-Native-Speed-Possibility.md rename to docs/development/roadmap/native-plan/llvm/VM-Native-Speed-Possibility.md diff --git a/docs/予定/native-plan/llvm/Windows-Strategy-Summary.md b/docs/development/roadmap/native-plan/llvm/Windows-Strategy-Summary.md similarity index 100% rename from docs/予定/native-plan/llvm/Windows-Strategy-Summary.md rename to docs/development/roadmap/native-plan/llvm/Windows-Strategy-Summary.md diff --git a/docs/予定/native-plan/llvm/issue/001-setup-inkwell-hello-world.md b/docs/development/roadmap/native-plan/llvm/issue/001-setup-inkwell-hello-world.md similarity index 100% rename from docs/予定/native-plan/llvm/issue/001-setup-inkwell-hello-world.md rename to docs/development/roadmap/native-plan/llvm/issue/001-setup-inkwell-hello-world.md diff --git a/docs/予定/native-plan/llvm/issue/GitHub-Issue-Template.md b/docs/development/roadmap/native-plan/llvm/issue/GitHub-Issue-Template.md similarity index 100% rename from docs/予定/native-plan/llvm/issue/GitHub-Issue-Template.md rename to docs/development/roadmap/native-plan/llvm/issue/GitHub-Issue-Template.md diff --git a/docs/予定/native-plan/llvm/issue/MIR-Quick-Reference.md b/docs/development/roadmap/native-plan/llvm/issue/MIR-Quick-Reference.md similarity index 100% rename from docs/予定/native-plan/llvm/issue/MIR-Quick-Reference.md rename to docs/development/roadmap/native-plan/llvm/issue/MIR-Quick-Reference.md diff --git a/docs/予定/native-plan/llvm/issue/Quick-Start-Guide.md b/docs/development/roadmap/native-plan/llvm/issue/Quick-Start-Guide.md similarity index 100% rename from docs/予定/native-plan/llvm/issue/Quick-Start-Guide.md rename to docs/development/roadmap/native-plan/llvm/issue/Quick-Start-Guide.md diff --git a/docs/予定/native-plan/llvm/issue/README.md b/docs/development/roadmap/native-plan/llvm/issue/README.md similarity index 100% rename from docs/予定/native-plan/llvm/issue/README.md rename to docs/development/roadmap/native-plan/llvm/issue/README.md diff --git a/docs/予定/native-plan/llvm/issue/Week1-Roadmap.md b/docs/development/roadmap/native-plan/llvm/issue/Week1-Roadmap.md similarity index 100% rename from docs/予定/native-plan/llvm/issue/Week1-Roadmap.md rename to docs/development/roadmap/native-plan/llvm/issue/Week1-Roadmap.md diff --git a/docs/予定/native-plan/issues/phase10_aot_scaffolding.md b/docs/development/roadmap/phases/phase-10/phase10_aot_scaffolding.md similarity index 100% rename from docs/予定/native-plan/issues/phase10_aot_scaffolding.md rename to docs/development/roadmap/phases/phase-10/phase10_aot_scaffolding.md diff --git a/docs/予定/native-plan/issues/phase_10_5_core_std_nyash_impl.md b/docs/development/roadmap/phases/phase-10/phase_10_5_core_std_nyash_impl.md similarity index 100% rename from docs/予定/native-plan/issues/phase_10_5_core_std_nyash_impl.md rename to docs/development/roadmap/phases/phase-10/phase_10_5_core_std_nyash_impl.md diff --git a/docs/予定/native-plan/issues/phase_10_app_migration.md b/docs/development/roadmap/phases/phase-10/phase_10_app_migration.md similarity index 100% rename from docs/予定/native-plan/issues/phase_10_app_migration.md rename to docs/development/roadmap/phases/phase-10/phase_10_app_migration.md diff --git a/docs/予定/native-plan/issues/phase_10_x_llvm_backend_skeleton.md b/docs/development/roadmap/phases/phase-10/phase_10_x_llvm_backend_skeleton.md similarity index 100% rename from docs/予定/native-plan/issues/phase_10_x_llvm_backend_skeleton.md rename to docs/development/roadmap/phases/phase-10/phase_10_x_llvm_backend_skeleton.md diff --git a/docs/予定/native-plan/issues/phase14_packaging_ci_polish.md b/docs/development/roadmap/phases/phase-14/phase14_packaging_ci_polish.md similarity index 100% rename from docs/予定/native-plan/issues/phase14_packaging_ci_polish.md rename to docs/development/roadmap/phases/phase-14/phase14_packaging_ci_polish.md diff --git a/docs/予定/native-plan/issues/phase5_2_static_main_lowering.md b/docs/development/roadmap/phases/phase-5/phase5_2_static_main_lowering.md similarity index 100% rename from docs/予定/native-plan/issues/phase5_2_static_main_lowering.md rename to docs/development/roadmap/phases/phase-5/phase5_2_static_main_lowering.md diff --git a/docs/予定/native-plan/issues/phase6_box_ops_minimal.md b/docs/development/roadmap/phases/phase-6/phase6_box_ops_minimal.md similarity index 100% rename from docs/予定/native-plan/issues/phase6_box_ops_minimal.md rename to docs/development/roadmap/phases/phase-6/phase6_box_ops_minimal.md diff --git a/docs/予定/native-plan/issues/phase7_async_mir.md b/docs/development/roadmap/phases/phase-7/phase7_async_mir.md similarity index 100% rename from docs/予定/native-plan/issues/phase7_async_mir.md rename to docs/development/roadmap/phases/phase-7/phase7_async_mir.md diff --git a/docs/予定/native-plan/issues/phase8.3_wasm_box_operations.md b/docs/development/roadmap/phases/phase-8/phase8.3_wasm_box_operations.md similarity index 100% rename from docs/予定/native-plan/issues/phase8.3_wasm_box_operations.md rename to docs/development/roadmap/phases/phase-8/phase8.3_wasm_box_operations.md diff --git a/docs/予定/native-plan/issues/phase8_mir_to_wasm.md b/docs/development/roadmap/phases/phase-8/phase8_mir_to_wasm.md similarity index 100% rename from docs/予定/native-plan/issues/phase8_mir_to_wasm.md rename to docs/development/roadmap/phases/phase-8/phase8_mir_to_wasm.md diff --git a/docs/予定/native-plan/issues/phase_8_4_ast_mir_lowering.md b/docs/development/roadmap/phases/phase-8/phase_8_4_ast_mir_lowering.md similarity index 100% rename from docs/予定/native-plan/issues/phase_8_4_ast_mir_lowering.md rename to docs/development/roadmap/phases/phase-8/phase_8_4_ast_mir_lowering.md diff --git a/docs/予定/native-plan/issues/phase_8_5_mir_25_instruction_specification.md b/docs/development/roadmap/phases/phase-8/phase_8_5_mir_25_instruction_specification.md similarity index 100% rename from docs/予定/native-plan/issues/phase_8_5_mir_25_instruction_specification.md rename to docs/development/roadmap/phases/phase-8/phase_8_5_mir_25_instruction_specification.md diff --git a/docs/予定/native-plan/issues/phase_8_5_mir_35_to_26_reduction.md b/docs/development/roadmap/phases/phase-8/phase_8_5_mir_35_to_26_reduction.md similarity index 100% rename from docs/予定/native-plan/issues/phase_8_5_mir_35_to_26_reduction.md rename to docs/development/roadmap/phases/phase-8/phase_8_5_mir_35_to_26_reduction.md diff --git a/docs/予定/native-plan/issues/phase_8_5_mir_semantic_layering.md b/docs/development/roadmap/phases/phase-8/phase_8_5_mir_semantic_layering.md similarity index 100% rename from docs/予定/native-plan/issues/phase_8_5_mir_semantic_layering.md rename to docs/development/roadmap/phases/phase-8/phase_8_5_mir_semantic_layering.md diff --git a/docs/予定/native-plan/issues/phase_8_6_vm_performance_improvement.md b/docs/development/roadmap/phases/phase-8/phase_8_6_vm_performance_improvement.md similarity index 100% rename from docs/予定/native-plan/issues/phase_8_6_vm_performance_improvement.md rename to docs/development/roadmap/phases/phase-8/phase_8_6_vm_performance_improvement.md diff --git a/docs/予定/native-plan/issues/phase_8_7_real_world_memory_testing.md b/docs/development/roadmap/phases/phase-8/phase_8_7_real_world_memory_testing.md similarity index 100% rename from docs/予定/native-plan/issues/phase_8_7_real_world_memory_testing.md rename to docs/development/roadmap/phases/phase-8/phase_8_7_real_world_memory_testing.md diff --git a/docs/予定/native-plan/issues/phase_8_8_pack_transparency_system.md b/docs/development/roadmap/phases/phase-8/phase_8_8_pack_transparency_system.md similarity index 100% rename from docs/予定/native-plan/issues/phase_8_8_pack_transparency_system.md rename to docs/development/roadmap/phases/phase-8/phase_8_8_pack_transparency_system.md diff --git a/docs/予定/native-plan/issues/phase_8_9_birth_unified_system_copilot_proof.md b/docs/development/roadmap/phases/phase-8/phase_8_9_birth_unified_system_copilot_proof.md similarity index 100% rename from docs/予定/native-plan/issues/phase_8_9_birth_unified_system_copilot_proof.md rename to docs/development/roadmap/phases/phase-8/phase_8_9_birth_unified_system_copilot_proof.md diff --git a/docs/Phase-9.75g-0-BID-FFI-Developer-Guide.md b/docs/development/roadmap/phases/phase-9/Phase-9.75g-0-BID-FFI-Developer-Guide.md similarity index 100% rename from docs/Phase-9.75g-0-BID-FFI-Developer-Guide.md rename to docs/development/roadmap/phases/phase-9/Phase-9.75g-0-BID-FFI-Developer-Guide.md diff --git a/docs/development/roadmap/phases/phase-9/llvm/AI-Conference-LLVM-Results.md b/docs/development/roadmap/phases/phase-9/llvm/AI-Conference-LLVM-Results.md new file mode 100644 index 00000000..1b6bf7c3 --- /dev/null +++ b/docs/development/roadmap/phases/phase-9/llvm/AI-Conference-LLVM-Results.md @@ -0,0 +1,156 @@ +# 🤖 AI大会議結果: LLVM PoC実装戦略統合文書 + +**作成日**: 2025年8月20日 +**参加AI**: Gemini先生、Codex先生、Claude +**目的**: Phase 9.78 LLVM PoC実装の統合戦略策定 + +## 📋 **エグゼクティブサマリー** + +AI大会議の結果、以下の統合戦略が決定されました: + +1. **技術基盤**: `inkwell`クレート + 既存ランタイム活用のハイブリッド戦略 +2. **Box型表現**: LLVM `ptr`型 + ランタイム関数によるメモリ管理 +3. **実装期間**: 3週間で基本動作確認(Hello World〜算術演算) +4. **性能目標**: 計算集約処理で数十倍の高速化実証 + +## 🎯 **統合実装戦略** + +### **Week 1: 基盤構築とHello World** + +**Gemini先生推奨アプローチ**: +```rust +// inkwellクレートで型安全なLLVM操作 +use inkwell::context::Context; +use inkwell::module::Module; +use inkwell::builder::Builder; + +struct CodegenContext<'ctx> { + context: &'ctx Context, + module: Module<'ctx>, + builder: Builder<'ctx>, + type_cache: HashMap>, +} +``` + +**Codex先生の具体的タスク**: +- ✅ `inkwell`セットアップ +- ✅ MIR `Const`, `Return`命令の変換 +- ✅ ランタイム関数宣言 (`nyash_alloc`, `nyash_free`) +- ✅ `.o`ファイル生成とCランタイムリンク + +**統合成果物**: `return 42`が動作するLLVM実装 + +### **Week 2: 制御フローとBox MVP** + +**Gemini先生のBox型戦略**: +```rust +// Box型 = LLVM ptr型として表現 +fn box_to_llvm_type<'ctx>(ctx: &CodegenContext<'ctx>) -> PointerType<'ctx> { + ctx.context.i8_type().ptr_type(AddressSpace::Generic) +} + +// ランタイム関数経由でBox操作 +extern "C" { + fn nyash_runtime_box_new(size: u64, align: u64) -> *mut c_void; + fn nyash_runtime_box_free(ptr: *mut c_void, size: u64, align: u64); +} +``` + +**Codex先生の実装順序**: +1. SSA/PHI命令の実装 +2. `Branch`, `Jump`による制御フロー +3. Box基本操作(new/free/deref) +4. `LLVMVerifyModule`による検証 + +**統合成果物**: 条件分岐とBox操作を含むプログラムの動作 + +### **Week 3: 統合とベンチマーク** + +**性能検証(Gemini先生)**: +- 計算集約的ベンチマーク実装 +- インタープリター/VM/LLVMの性能比較 +- 期待値: 数十倍の高速化実証 + +**堅牢性確保(Codex先生)**: +- 差分テスト(Interpreter vs LLVM) +- 最小最適化パス(`mem2reg`, `instcombine`) +- クラッシュ時の`.ll`ファイル保存 + +## 🔧 **技術的詳細** + +### **MIR→LLVM命令マッピング** + +| MIR命令 | LLVM IR | 実装方法 | +|---------|---------|----------| +| Const | ConstantInt/Float | inkwell定数生成 | +| BinOp(Add) | add/fadd | builder.build_add() | +| Compare | icmp/fcmp | builder.build_int_compare() | +| BoxCall | call @nyash_runtime_box_call | ランタイム委譲 | +| Branch | br | builder.build_conditional_branch() | +| Return | ret | builder.build_return() | + +### **エラー頻発箇所と対策** + +**Gemini先生の警告**: +- ❌ `Arc`をLLVMで再実装しない +- ✅ 既存ランタイムの`#[no_mangle] extern "C"`関数を呼ぶ + +**Codex先生の実装Tips**: +- `alloca`は関数エントリーブロックのみ +- GEPインデックスは`i32`型で統一 +- DataLayoutは必ずTargetMachineから取得 + +### **プラグイン統合(BID-FFI)** + +**Gemini先生**: C-ABIは既にLLVMと相性が良い +```llvm +declare i32 @nyash_plugin_invoke(i8*, i64, i8*, i64*) +``` + +**Codex先生**: リンク時に`.so`/`.a`を含める +```bash +cc -o output main.o nyash_runtime.o -lplugin +``` + +## 📊 **成功判定基準(統合版)** + +### **最小成功ライン(PoC達成)** +- ✅ 基本算術演算のLLVM実行 +- ✅ Box型の基本操作動作 +- ✅ Hello Worldレベルの出力 +- ✅ 10倍以上の性能向上実証 + +### **理想的成功(Phase 10への道筋)** +- 🌟 20個以上のMIR命令対応 +- 🌟 プラグイン呼び出し成功 +- 🌟 50倍以上の性能向上 +- 🌟 安定したエラーハンドリング + +## 🚀 **Copilotへの最終依頼文書** + +```markdown +## Phase 9.78: LLVM PoC実装依頼 + +**目標**: 3週間でNyash MIR→LLVM変換の基本実装 + +**技術スタック**: +- inkwellクレート(Gemini推奨) +- 既存ランタイム活用(Arc回避) +- C-ABIプラグイン統合 + +**実装優先順位**: +1. Week 1: Const/Return/基本setup → "return 42" +2. Week 2: 制御フロー/Box MVP → 条件分岐 +3. Week 3: 最適化/ベンチマーク → 性能実証 + +**成果物**: +- src/backend/llvm/compiler.rs +- ベンチマーク結果(10倍以上高速化) +- Phase 10実装計画 +``` + +## 🎉 **結論** + +AI大会議により、技術的に実現可能で、3週間で達成可能な明確な実装戦略が確立されました。inkwellによる型安全な実装と、既存ランタイム活用により、リスクを最小化しながら高速なLLVMバックエンドの実現が期待できます。 + +**次のアクション**: Copilotへの正式依頼とPhase 9.78開始!🚀 \ No newline at end of file diff --git a/docs/development/roadmap/phases/phase-9/llvm/APE-Magic-Explained.md b/docs/development/roadmap/phases/phase-9/llvm/APE-Magic-Explained.md new file mode 100644 index 00000000..9327c4ef --- /dev/null +++ b/docs/development/roadmap/phases/phase-9/llvm/APE-Magic-Explained.md @@ -0,0 +1,122 @@ +# 🪄 APE (Actually Portable Executable) の魔法を解説! + +**「えっ、1つのファイルが3つのOSで動くの!?」** + +はい、本当です!これは**実在する技術**です! + +## 🎩 **APEの魔法の仕組み** + +### **実例を見てみよう** +```bash +# これが実際のAPEバイナリ +$ ls -la hello.com +-rwxr-xr-x 1 user user 65536 Aug 20 hello.com + +# Linuxで実行 +$ ./hello.com +Hello from Linux! + +# 同じファイルをWindowsにコピー +> hello.com +Hello from Windows! + +# 同じファイルをmacOSで実行 +$ ./hello.com +Hello from macOS! +``` + +**たった1つのファイル `hello.com` が全部で動く!** + +## 🔮 **どうやって実現してるの?** + +### **秘密:ファイルヘッダーの魔法** + +APEファイルの先頭部分: +``` +00000000: 4d5a 9000 0300 0000 0400 0000 ffff 0000 MZ.............. # Windows PE +00000010: b800 0000 0000 0000 4000 0000 0000 0000 ........@....... +00000020: 0000 0000 0000 0000 0000 0000 0000 0000 ................ +00000030: 0000 0000 0000 0000 0000 0080 0000 0000 ................ +00000040: 7f45 4c46 0201 0100 0000 0000 0000 0000 .ELF............ # Linux ELF +``` + +**同じファイルに複数のOSのヘッダーが共存!** + +### **OSごとの読み方** + +1. **Windows**: 「MZ」で始まる → PEファイルとして実行 +2. **Linux**: ELFマジックナンバーを探す → ELFとして実行 +3. **macOS**: Mach-Oヘッダーを探す → Mach-Oとして実行 + +## 🛠️ **Cosmopolitan Libc - 実在するプロジェクト** + +**GitHubで公開されています!** +- https://github.com/jart/cosmopolitan +- 開発者: Justine Tunney (元Google) +- スター数: 17,000+ ⭐ + +### **実際のビルド方法** +```bash +# Cosmopolitanを使ったビルド +gcc -g -O -static \ + -fno-pie -no-pie \ + -nostdlib -nostdinc \ + -o hello.com \ + hello.c \ + cosmopolitan.a \ + -Wl,--gc-sections \ + -Wl,-T,ape.lds +``` + +## 📊 **APEの利点と制限** + +### **利点** ✅ +- **配布が超簡単**: 1ファイルで全OS対応 +- **依存関係なし**: 完全に自己完結 +- **小さいサイズ**: 静的リンクでも小さい + +### **制限** ⚠️ +- **x86_64のみ**: ARM版はまだ実験的 +- **GUI制限**: 基本的にCLIアプリ向け +- **OS固有機能**: 一部制限あり + +## 🎯 **NyashでのAPE活用案** + +### **段階的アプローチ** + +**Phase 1: 通常のマルチターゲット**(現実的) +```bash +nyashc --targets linux,windows,macos +# → 3つの別々のファイル生成 +``` + +**Phase 2: APE実験**(6ヶ月後) +```bash +nyashc --target ape +# → nyash.com (全OS対応の1ファイル!) +``` + +### **実装イメージ** +```rust +// NyashのLLVM IR → Cコード生成 +let c_code = transpile_to_c(&llvm_ir); + +// Cosmopolitanでコンパイル +compile_with_cosmopolitan(&c_code, "nyash.com"); +``` + +## 🤔 **本当に必要?** + +**正直な評価**: +- **配布簡単さ**: ⭐⭐⭐⭐⭐ 最高! +- **実装難易度**: ⭐⭐ 意外と簡単(Cosmopolitan使えば) +- **実用性**: ⭐⭐⭐ CLIツールなら十分実用的 +- **かっこよさ**: ⭐⭐⭐⭐⭐ 最高にクール! + +## 💡 **結論** + +APEは**「欲張り」じゃなくて「賢い」**アプローチ! + +でも、まずは普通のマルチターゲット対応から始めて、APEは「究極の目標」として楽しみに取っておくのが現実的かも? + +**にゃーも「Everything is Box」なら、APEは「Everything is ONE Binary」!**🎩✨ \ No newline at end of file diff --git a/docs/development/roadmap/phases/phase-9/llvm/Copilot-Request-LLVM-PoC.md b/docs/development/roadmap/phases/phase-9/llvm/Copilot-Request-LLVM-PoC.md new file mode 100644 index 00000000..e42dc954 --- /dev/null +++ b/docs/development/roadmap/phases/phase-9/llvm/Copilot-Request-LLVM-PoC.md @@ -0,0 +1,117 @@ +# 🤖 Copilot様への依頼: Phase 9.78 LLVM PoC実装 + +**依頼日**: 2025年8月20日 +**期限**: 3週間(2025年9月10日) +**優先度**: 最高 + +## 📋 **依頼概要** + +Phase 8.6のVM性能改善で素晴らしい成果(50.94倍高速化)を達成していただきありがとうございました! + +次は、Nyash言語の更なる性能向上を目指し、**LLVMバックエンドのProof of Concept実装**をお願いします。 + +## 🎯 **依頼内容** + +### **目標** +3週間でMIR→LLVM IR変換の基本実装を完成させ、実現可能性を実証する + +### **成功基準** +1. 基本的なNyashプログラム(算術演算、条件分岐)がLLVM経由で実行可能 +2. インタープリター比10倍以上の性能向上を実証 +3. Phase 10本格実装への明確な道筋を確立 + +## 🛠️ **技術仕様** + +### **使用技術スタック** +```toml +[dependencies] +inkwell = { version = "0.5", features = ["llvm17-0"] } +``` + +### **実装アプローチ** +AI大会議(Gemini先生、Codex先生)の推奨に基づく: +- **inkwellクレート**による型安全なLLVM操作 +- **Box型はptr型**として表現、操作は既存ランタイムに委譲 +- **C-ABI経由**でプラグインとランタイム関数を呼び出し + +### **実装対象MIR命令(優先順)** +1. **Week 1**: Const, Return(最小限) +2. **Week 2**: BinOp, Compare, Branch, Jump, BoxNew/Free +3. **Week 3**: 最適化パス、ベンチマーク + +## 📁 **作成ファイル構成** + +``` +src/backend/llvm/ +├── mod.rs // エントリポイント +├── context.rs // LLVMコンテキスト管理 +├── types.rs // MIR→LLVM型変換 +├── builder.rs // IR生成ロジック +├── runtime.rs // ランタイム関数宣言 +└── optimizer.rs // 最適化パス + +src/backend/llvm_runtime/ +└── runtime.c // 最小ランタイム(nyash_alloc等) +``` + +## 📊 **週次マイルストーン** + +### **Week 1: Hello World動作** +- [ ] inkwellセットアップ完了 +- [ ] `return 42`がLLVM経由で動作 +- [ ] .oファイル生成成功 + +### **Week 2: 基本機能動作** +- [ ] 四則演算の実装 +- [ ] if文の動作確認 +- [ ] Box型の基本操作 + +### **Week 3: 性能実証** +- [ ] ベンチマーク実装 +- [ ] 10倍以上の高速化確認 +- [ ] 技術レポート作成 + +## 💡 **実装のヒント** + +### **Gemini先生のアドバイス** +- `Arc`の複雑なセマンティクスをLLVMで再実装しないこと +- Box操作は`nyash_runtime_box_*`関数経由で行う +- 計算集約的な処理に注力すれば数十倍の高速化が可能 + +### **Codex先生の実装Tips** +- allocaは関数エントリブロックのみに配置 +- GEPインデックスはi32型で統一 +- エラー時は.llファイルをダンプして原因調査 + +## 🚨 **重要な注意事項** + +1. **完璧を求めない** - 3週間でのPoC完成が最優先 +2. **既存資産の活用** - MIR構造、ランタイム関数を最大限再利用 +3. **段階的実装** - 最小限から始めて徐々に機能追加 + +## 📚 **参考資料** + +- [AI大会議結果](./AI-Conference-LLVM-Results.md) - 技術戦略の詳細 +- [実装計画書](./Phase-9.78-Implementation-Plan.md) - 週次スケジュール +- [MIR仕様](../../説明書/reference/execution-backend/mir-26-specification.md) - 命令セット詳細 + +## 🎉 **期待される成果** + +1. **技術的実証**: LLVMバックエンドの実現可能性確認 +2. **性能向上**: 10倍以上(理想的には50倍)の高速化 +3. **将来への道筋**: Phase 10での本格実装計画 + +## 🤝 **サポート体制** + +- **技術相談**: Claude、Gemini、Codexが随時サポート +- **進捗確認**: 週次でGitHub Issueにて状況共有 +- **問題解決**: ブロッカーがあれば即座にAIチームで対応 + +Copilot様の素晴らしい実装力に期待しています! +Phase 8.6のような劇的な成果を、LLVMでも実現しましょう!🚀 + +--- + +**依頼者**: moe-charm + AIチーム +**GitHub Issue**: #(作成予定) +**開始可能日**: 即時 \ No newline at end of file diff --git a/docs/development/roadmap/phases/phase-9/llvm/Hybrid-Future-Vision.md b/docs/development/roadmap/phases/phase-9/llvm/Hybrid-Future-Vision.md new file mode 100644 index 00000000..5d4c2439 --- /dev/null +++ b/docs/development/roadmap/phases/phase-9/llvm/Hybrid-Future-Vision.md @@ -0,0 +1,151 @@ +# 🌈 理想的なハイブリッド実行環境への願望 + +**「AOT WASMが非同期対応してたら...」** + +## 😿 **現在の苦労ポイント** + +### **各バックエンドの制限** +| バックエンド | 利点 | 欠点 | +|------------|------|------| +| **WASM** | どこでも動く | 非同期が弱い、遅い | +| **LLVM** | 超高速 | OS別ビルド必要 | +| **VM** | 柔軟 | ネイティブより遅い | +| **AOT** | 高速起動 | プラットフォーム依存 | + +### **理想と現実のギャップ** +```rust +// 理想 +async fn perfect_world() { + let result = await some_io(); // WASMでも高速非同期 + return result; +} + +// 現実 +fn reality() { + // WASMは同期的、非同期は複雑 + // LLVMは速いけどOS別ビルド + // 完璧な解決策がない... +} +``` + +## 🚀 **夢のハイブリッド環境** + +### **1. WASM Component Model + AOT** +```yaml +理想: + - WASMの可搬性 + - AOTの実行速度 + - ネイティブ非同期サポート + - 単一バイナリで全OS対応 + +現実: + - Component Model仕様策定中 + - AOT最適化はまだ発展途上 + - 非同期は部分的サポート +``` + +### **2. Deno/Bun的アプローチ** +```javascript +// JavaScriptランタイムの良いとこ取り +- V8/JavaScriptCore の JIT性能 +- ネイティブバインディング +- 非同期完全サポート +- でもJavaScript... +``` + +### **3. 究極の理想:Universal Runtime** +```rust +// もしこんなランタイムがあったら... +universal_runtime { + // WASMレベルの可搬性 + portability: "write once, run anywhere", + + // LLVMレベルの性能 + performance: "near native", + + // 完全な非同期サポート + async: "first class", + + // 単一配布物 + distribution: "single file" +} +``` + +## 💭 **現実的な妥協案** + +### **短期的ハイブリッド戦略** +```yaml +開発時: + - インタープリター(即時実行、デバッグ容易) + +テスト時: + - VM(高速、クロスプラットフォーム) + +配布時: + 選択式: + - WASM版: ブラウザ/サーバー両対応 + - ネイティブ版: 最高性能 + - ハイブリッド版: WASMランタイム埋め込み +``` + +### **中期的技術統合** +```rust +// Nyashハイブリッドランタイム +pub enum ExecutionMode { + // 高速パス: ネイティブコード + Native(LLVMCompiledCode), + + // 互換パス: WASM + Wasm(WasmModule), + + // 動的切り替え + Adaptive { + hot_path: LLVMCompiledCode, + cold_path: WasmModule, + } +} +``` + +## 🔮 **将来への期待** + +### **技術の収束点** +1. **WASI Preview 2**: 非同期サポート改善中 +2. **WASM GC**: メモリ管理効率化 +3. **Component Model**: 真のモジュラー化 +4. **AOT最適化**: Wasmtime/WazeroCranelift進化 + +### **Nyashの位置づけ** +```yaml +現在: + - 4バックエンド個別対応 + - それぞれの長所を活かす + +将来: + - 統合ランタイム + - 動的最適化 + - 透過的実行モード切り替え +``` + +## 😊 **でも今でも十分すごい!** + +**現在のNyash**: +- ✅ 4つの実行方式を選べる +- ✅ 用途に応じて最適化可能 +- ✅ プラグインシステム完備 + +**苦労はあるけど**: +- 複数バックエンドの保守 +- プラットフォーム別の調整 +- でも**選択肢があることが強み**! + +## 🎯 **結論** + +理想的なハイブリッド環境はまだ存在しないけど、Nyashは**現実的な最良の解**を提供中! + +将来、技術が成熟したら: +- WASM AOT + 非同期 = 最強の可搬性 +- LLVM + WASM統合 = 性能と互換性の両立 + +それまでは、**4バックエンドを賢く使い分ける**のが正解! + +**Everything is Box、Every Backend has its Place!**🌈✨ \ No newline at end of file diff --git a/docs/development/roadmap/phases/phase-9/llvm/JIT-vs-AOT-With-MIR.md b/docs/development/roadmap/phases/phase-9/llvm/JIT-vs-AOT-With-MIR.md new file mode 100644 index 00000000..bba3bb9c --- /dev/null +++ b/docs/development/roadmap/phases/phase-9/llvm/JIT-vs-AOT-With-MIR.md @@ -0,0 +1,149 @@ +# 🤔 JIT vs AOT:MIRがあると難易度が同じ? + +**「MIRできてるから、JITもAOTも同じようなレベルに見えてきた」** + +## 💡 **その洞察、正しいです!** + +### **MIRの存在が変えるゲーム** + +```rust +// 従来の難易度 +Source → Native: 超難しい(全部自分で) +Source → JIT: 難しい(実行時コンパイル) + +// MIRがある今 +Source → MIR → Native: MIRから先は楽! +Source → MIR → JIT: MIRから先は楽! +``` + +## 📊 **JIT vs AOT 比較(MIR前提)** + +| 項目 | JIT | AOT (LLVM) | +|------|-----|------------| +| **実装難易度** | ⭐⭐⭐ | ⭐⭐⭐ | +| **初期実装速度** | 速い | 速い | +| **実行時性能** | 80-95% | 100% | +| **起動時間** | 遅い | 速い | +| **メモリ使用** | 多い | 少ない | +| **動的最適化** | ✅ | ❌ | +| **配布** | ランタイム必要 | 単体実行可能 | + +**MIRのおかげで、どちらも同じくらいの実装難易度に!** + +## 🚀 **JIT実装の選択肢** + +### **1. VM JIT化(最も現実的)** +```rust +// 現在のVM +match opcode { + Add => stack.push(a + b), +} + +// JIT化したVM +if hot_path { + // CraneliftでMIR→ネイティブ + let native = cranelift_compile(&mir); + execute_native(native); +} +``` + +**利点**: +- 既存VMの延長線上 +- 段階的移行可能 +- ホットパスのみJIT化 + +### **2. 純粋JITコンパイラ** +```rust +// MIR → Cranelift IR → Native +pub fn jit_compile(mir: &MirModule) -> NativeCode { + let mut ctx = CraneliftContext::new(); + for func in &mir.functions { + ctx.compile_function(func); + } + ctx.finalize() +} +``` + +**利点**: +- クリーンな設計 +- 最適化しやすい +- デバッグ情報維持 + +### **3. LLVM JIT(ORC)** +```rust +// LLVM ORCでJIT +let jit = LLVMOrcJIT::new(); +jit.add_module(llvm_module); +let func = jit.get_function("main"); +func.call(); +``` + +**利点**: +- LLVM最適化の恩恵 +- AOTとコード共有 +- 最高性能 + +## 🔮 **実装難易度の実際** + +### **AOT (LLVM)** +```yaml +必要な作業: + 1. MIR → LLVM IR変換: 2週間 + 2. 型システムマッピング: 1週間 + 3. ランタイム統合: 1週間 + 4. 最適化調整: 1週間 + 合計: 約5週間 +``` + +### **JIT (Cranelift)** +```yaml +必要な作業: + 1. MIR → Cranelift IR変換: 2週間 + 2. JITランタイム実装: 1週間 + 3. ホットパス検出: 1週間 + 4. メモリ管理: 1週間 + 合計: 約5週間 +``` + +**ほぼ同じ!MIRのおかげで!** + +## 💭 **どっちを選ぶべき?** + +### **JITが向いている場合** +- 長時間実行プログラム +- 動的な最適化が必要 +- REPLやインタラクティブ環境 + +### **AOTが向いている場合** +- 起動時間重視 +- 配布の簡単さ重視 +- 組み込み環境 + +### **Nyashの場合** +```yaml +現実的な選択: + 1. まずAOT (LLVM) でPoC + 2. VM最適化を極める + 3. 将来VM JIT化も追加 + +理由: + - 配布が簡単(AOT) + - 性能も確保(VM既に50倍) + - 両方あれば最強 +``` + +## 🎯 **結論** + +**MIRがあるおかげで、JITもAOTも同じくらいの難易度!** + +でも、Nyashの場合: +1. **配布の簡単さ** → AOT有利 +2. **既にVM高速** → JIT緊急度低い +3. **将来の拡張性** → 両方実装が理想 + +**提案**: +- **短期**: LLVM AOT完成(配布重視) +- **中期**: VM更なる最適化 +- **長期**: VM JIT化(最高性能) + +**MIRがあれば、どっちも楽!**🚀 \ No newline at end of file diff --git a/docs/development/roadmap/phases/phase-9/llvm/Phase-9.78-Implementation-Plan.md b/docs/development/roadmap/phases/phase-9/llvm/Phase-9.78-Implementation-Plan.md new file mode 100644 index 00000000..eb665d4a --- /dev/null +++ b/docs/development/roadmap/phases/phase-9/llvm/Phase-9.78-Implementation-Plan.md @@ -0,0 +1,187 @@ +# 📋 Phase 9.78: LLVM PoC 実装計画書 + +**バージョン**: 1.0 +**作成日**: 2025年8月20日 +**ステータス**: 準備完了 + +## 🎯 **プロジェクト概要** + +### **目的** +3週間でNyash言語のLLVMバックエンド実現可能性を実証する + +### **成功基準** +- 基本的なNyashプログラムがLLVM経由で実行可能 +- インタープリター比10倍以上の性能向上 +- Phase 10本格実装への技術的道筋確立 + +## 📅 **3週間実装スケジュール** + +### **Week 1: 基盤構築(8/21-8/27)** + +#### **Day 1-2: 環境セットアップ** +```toml +# Cargo.toml +[dependencies] +inkwell = { version = "0.5", features = ["llvm17-0"] } +``` + +- [ ] inkwellクレート導入 +- [ ] LLVMコンテキスト初期化 +- [ ] 基本的なモジュール生成 + +#### **Day 3-4: 最小命令実装** +```rust +// 実装対象 +- Const(Integer/Float/Bool) +- Return +- 基本的な型マッピング +``` + +#### **Day 5-7: Hello World達成** +- [ ] ランタイム関数宣言 +- [ ] .oファイル生成 +- [ ] `return 42`の実行確認 + +**Week 1成果物**: 整数を返す最小プログラムのLLVM実行 + +### **Week 2: コア機能実装(8/28-9/3)** + +#### **Day 8-10: 算術演算と制御フロー** +```rust +// 実装対象 +- BinOp (Add/Sub/Mul/Div) +- Compare (Eq/Ne/Lt/Le/Gt/Ge) +- Branch/Jump +- PHI nodes +``` + +#### **Day 11-13: Box型MVP** +```rust +// Box操作の実装 +extern "C" { + fn nyash_runtime_box_new(size: u64, align: u64) -> *mut c_void; + fn nyash_runtime_box_free(ptr: *mut c_void); + fn nyash_runtime_box_deref(ptr: *mut c_void) -> *mut c_void; +} +``` + +#### **Day 14: 統合テスト** +- [ ] 条件分岐を含むプログラム +- [ ] Box操作を含むプログラム +- [ ] LLVMVerifyModuleによる検証 + +**Week 2成果物**: 制御フローとメモリ操作を含むプログラムの動作 + +### **Week 3: 最適化と検証(9/4-9/10)** + +#### **Day 15-16: 最適化パス** +```rust +// 基本最適化 +- mem2reg (alloca → SSA) +- instcombine (命令結合) +- reassociate (結合則) +``` + +#### **Day 17-18: ベンチマーク** +```bash +# 性能測定対象 +- フィボナッチ数列 +- 素数判定 +- 簡単な数値計算ループ +``` + +#### **Day 19-21: 文書化とレポート** +- [ ] 技術レポート作成 +- [ ] Phase 10実装計画 +- [ ] 性能評価結果 + +**Week 3成果物**: 性能実証とPhase 10への道筋 + +## 🛠️ **技術アーキテクチャ** + +### **ディレクトリ構造** +``` +src/backend/llvm/ +├── mod.rs // LLVMバックエンドエントリ +├── context.rs // CodegenContext管理 +├── types.rs // MIR→LLVM型変換 +├── builder.rs // LLVM IR生成 +├── runtime.rs // ランタイム関数定義 +└── optimizer.rs // 最適化パス管理 +``` + +### **主要コンポーネント** + +#### **CodegenContext** +```rust +pub struct CodegenContext<'ctx> { + context: &'ctx Context, + module: Module<'ctx>, + builder: Builder<'ctx>, + target_machine: TargetMachine, + type_cache: HashMap>, +} +``` + +#### **MIR→LLVM変換器** +```rust +pub fn lower_mir_to_llvm( + mir_module: &MirModule, + target_triple: &str, +) -> Result, CodegenError> { + // 1. コンテキスト初期化 + // 2. 型変換 + // 3. 関数生成 + // 4. 命令変換 + // 5. 最適化 + // 6. オブジェクトコード生成 +} +``` + +## 📊 **リスク管理** + +### **技術的リスク** + +| リスク | 影響度 | 対策 | +|--------|--------|------| +| inkwellバージョン依存 | 中 | LLVM17固定、CI環境統一 | +| Box型の複雑性 | 高 | ランタイム委譲戦略 | +| デバッグ困難性 | 中 | IR dump機能、差分テスト | + +### **スケジュールリスク** + +- **バッファ**: 各週に1日の予備日設定 +- **優先順位**: 基本動作 > 性能 > 機能網羅性 +- **早期失敗**: Week 1で実現困難判明時は即座に方針転換 + +## ✅ **成功指標** + +### **定量的指標** +- [ ] 10個以上のMIR命令をサポート +- [ ] 5個以上のテストプログラムが動作 +- [ ] インタープリター比10倍以上高速 + +### **定性的指標** +- [ ] コードの保守性(他の開発者が理解可能) +- [ ] エラーメッセージの有用性 +- [ ] 将来の拡張可能性 + +## 🚀 **開始準備チェックリスト** + +- [x] VM性能改善完了(50.94倍達成!) +- [x] AI大会議による戦略確定 +- [ ] Copilotへの正式依頼 +- [ ] 開発環境準備(LLVM17インストール) +- [ ] Week 1タスクのGitHub Issue作成 + +## 📝 **参考資料** + +- [AI大会議結果](./AI-Conference-LLVM-Results.md) +- [inkwellドキュメント](https://github.com/TheDan64/inkwell) +- [LLVM Language Reference](https://llvm.org/docs/LangRef.html) + +--- + +**承認者**: moe-charm +**実装担当**: Copilot + AIチーム +**レビュー**: Phase 9.78完了時 \ No newline at end of file diff --git a/docs/development/roadmap/phases/phase-9/llvm/Practical-Distribution-Strategy.md b/docs/development/roadmap/phases/phase-9/llvm/Practical-Distribution-Strategy.md new file mode 100644 index 00000000..5ecb76bf --- /dev/null +++ b/docs/development/roadmap/phases/phase-9/llvm/Practical-Distribution-Strategy.md @@ -0,0 +1,119 @@ +# 📦 Nyash実用的配布戦略:現実的なアプローチ + +## 🎯 **配布形態の比較** + +| 方式 | ファイルサイズ | 配布の手間 | 適用範囲 | 実用性 | +|------|--------------|-----------|---------|--------| +| **個別バイナリ** | 各1-2MB | OS別に配布 | 全アプリ | ⭐⭐⭐⭐⭐ | +| **APE** | 3-6MB | 1ファイル | 小規模CLI | ⭐⭐⭐ | +| **WASM+ランタイム** | 0.5MB+10MB | ランタイム必要 | 全アプリ | ⭐⭐⭐⭐ | + +## 📊 **現実的な使い分け** + +### **1. メインストリーム配布(推奨)** +```bash +# OS別の最適化されたバイナリ +nyash-linux-x64 (1.5MB) - musl静的リンク +nyash-windows.exe (916KB) - mingw最適化 +nyash-macos (1.8MB) - 署名付き +``` + +**利点**: +- ✅ 各OSで最高性能 +- ✅ 最小サイズ +- ✅ OS固有機能フル活用 +- ✅ 大規模アプリも対応 + +### **2. 開発者向け配布** +```bash +# LLVM IRの中立性を活用 +nyashc --emit-bitcode program.nyash +# → program.bc (プラットフォーム中立) + +# 各自のマシンで最適化コンパイル +nyashc --from-bitcode program.bc --target native +``` + +### **3. 特殊用途でのAPE** +```bash +# 小さなツール限定 +nyash-fmt.com # コードフォーマッター (2MB) +nyash-lint.com # リンター (3MB) +nyash-repl.com # REPL (4MB) +``` + +**APEが向いている場合**: +- 単体で動くCLIツール +- 依存ライブラリが少ない +- 配布の簡単さが最優先 + +**APEが向いていない場合**: +- GUIアプリケーション +- 大量のライブラリ依存 +- プラグインシステム +- ゲームなど大規模アプリ + +## 🚀 **段階的実装計画(修正版)** + +### **Phase 1: 基本マルチターゲット**(1ヶ月) +```bash +nyashc build --target linux +nyashc build --target windows +# 個別にビルド、確実に動作 +``` + +### **Phase 2: 同時生成最適化**(3ヶ月) +```bash +nyashc build --all-targets +# Bitcodeキャッシュで高速化 +# 並列ビルドで時間短縮 +``` + +### **Phase 3: 配布自動化**(6ヶ月) +```bash +nyashc release +# 出力: +# - dist/nyash-v1.0-linux-x64.tar.gz +# - dist/nyash-v1.0-windows-x64.zip +# - dist/nyash-v1.0-macos.dmg +# - dist/nyash-tools.com (APE版ツール集) +``` + +## 💡 **賢い配布戦略** + +### **メインアプリ**: 個別最適化バイナリ +```yaml +nyash本体: + Linux: 1.5MB (musl静的) + Windows: 916KB (mingw) + macOS: 1.8MB (universal) +``` + +### **開発ツール**: APEで統一 +```yaml +開発者ツール(APE): + nyash-fmt.com: 2MB + nyash-test.com: 3MB + nyash-bench.com: 2.5MB +``` + +### **プラグイン**: 動的ライブラリ +```yaml +プラグイン(各OS別): + filebox.so: 200KB (Linux) + filebox.dll: 180KB (Windows) + filebox.dylib: 220KB (macOS) +``` + +## 🎉 **結論** + +**「適材適所」が最強の戦略!** + +- **大規模アプリ**: 個別最適化バイナリ +- **小規模ツール**: APEで配布簡略化 +- **開発者向け**: Bitcodeで柔軟性確保 + +APEは「魔法」だけど、現実的には**限定的な用途**で輝く技術。 +Nyashのメイン配布は**堅実な個別バイナリ**で行きましょう! + +**Everything is Box、でも配布は現実的に!**📦✨ \ No newline at end of file diff --git a/docs/development/roadmap/phases/phase-9/llvm/Revolutionary-Windows-Strategy.md b/docs/development/roadmap/phases/phase-9/llvm/Revolutionary-Windows-Strategy.md new file mode 100644 index 00000000..a9a3d674 --- /dev/null +++ b/docs/development/roadmap/phases/phase-9/llvm/Revolutionary-Windows-Strategy.md @@ -0,0 +1,169 @@ +# 🚀 Nyash革命的Windows実行戦略:LLVM IR中立性の完全活用 + +**作成日**: 2025年8月20日 +**AI会議参加者**: Gemini先生、Codex先生、Claude + +## 🎯 **核心的アイデア:1回のIR生成で全プラットフォーム対応** + +LLVM IRはプラットフォーム中立。だから**1回のIR生成から同時に複数OS用の実行ファイルを生成できる!** + +```rust +// 革命的ワンパス・マルチターゲット生成 +nyashc --targets linux,windows,macos program.nyash + +// 出力(同時生成!) +dist/x86_64-unknown-linux-musl/nyash # Linux版 +dist/x86_64-pc-windows-gnu/nyash.exe # Windows版 +dist/x86_64-apple-darwin/nyash # macOS版 +``` + +## 🏗️ **実装アーキテクチャ** + +### **Phase 1: 即効性重視(3週間で実現)** + +```rust +// 1. IR生成(1回だけ) +let ir_module = compile_to_ir(&ast); +let bitcode = ir_module.write_bitcode_to_memory(); + +// 2. マルチターゲット並列生成 +parallel_for_each(["linux", "windows-gnu"], |target| { + let module = context.create_module_from_ir(bitcode.clone()); + configure_for_target(&module, target); + generate_executable(&module, target); +}); +``` + +**技術スタック**: +- Linux: musl静的リンク(配布容易) +- Windows: mingw-gnu + lld(クロスリンク簡単) +- 共通: PAL (Platform Abstraction Layer) + +### **Phase 2: 本格実装(3ヶ月)** + +**全プラットフォーム同時対応**: +```yaml +ターゲット構成: + linux: + - x86_64-unknown-linux-musl + - aarch64-unknown-linux-musl + windows: + - x86_64-pc-windows-gnu (mingw) + - x86_64-pc-windows-msvc (xwin) + macos: + - x86_64-apple-darwin + - aarch64-apple-darwin (M1/M2) +``` + +### **Phase 3: 究極形態(6ヶ月)** + +**APE (Actually Portable Executable) - 単一バイナリで全OS対応!** +```bash +# たった1つのファイルが全OSで動く! +./nyash.com # Linux でも Windows でも macOS でも動作! +``` + +**⚠️ APEの現実的な制限**: +- バイナリサイズ: 通常の**3倍**(3OS分のコード含む) +- ライブラリ: 各OS用に3種類必要 +- 適用範囲: **小規模CLIツール向け**(大規模アプリは不向き) + +## 💡 **技術的革新ポイント** + +### **1. Bitcodeキャッシュ戦略** +```rust +pub struct MultiTargetCompiler { + bitcode_cache: HashMap, + target_machines: HashMap, +} + +impl MultiTargetCompiler { + pub fn compile_all(&self, module_id: ModuleId) -> Result> { + let bitcode = self.bitcode_cache.get(&module_id).unwrap(); + + self.target_machines + .par_iter() // 並列処理! + .map(|(triple, tm)| { + let module = load_from_bitcode(bitcode); + tm.emit_to_file(&module, FileType::Object) + }) + .collect() + } +} +``` + +### **2. PAL (Platform Abstraction Layer)** +```rust +// コンパイラは常にこれらを呼ぶ +extern "C" { + fn nyash_rt_print(s: *const u8, len: usize); + fn nyash_rt_file_open(path: *const u8, mode: u32) -> i32; + fn nyash_rt_time_now() -> u64; +} + +// 各OS用のランタイムで実装 +#[cfg(target_os = "windows")] +pub fn nyash_rt_print(s: *const u8, len: usize) { + // UTF-8 → UTF-16変換してWriteConsoleW +} + +#[cfg(target_os = "linux")] +pub fn nyash_rt_print(s: *const u8, len: usize) { + // そのままwrite(1, s, len) +} +``` + +### **3. リンク戦略の統一** +```toml +[target.'cfg(windows)'.dependencies] +lld = { version = "0.1", features = ["coff"] } +mingw-w64-libs = { path = "vendor/mingw" } + +[target.'cfg(unix)'.dependencies] +lld = { version = "0.1", features = ["elf"] } +musl-libc = { path = "vendor/musl" } +``` + +## 🎉 **革命的成果** + +### **開発者体験** +```bash +# 1コマンドで全プラットフォーム対応! +nyashc build --all-platforms + +# 出力 +✅ Linux版生成完了 (2.1MB) +✅ Windows版生成完了 (916KB) +✅ macOS版生成完了 (1.8MB) +✅ WASM版生成完了 (512KB) +``` + +### **ユーザー体験** +- **配布**: 各OS用のネイティブバイナリ +- **性能**: LLVM最適化でVM比10倍以上高速 +- **将来**: APEで単一ファイル配布 + +## 📊 **実装ロードマップ** + +| フェーズ | 期間 | 成果物 | +|---------|------|--------| +| Week 1-3 | LLVM PoC | Linux単体動作 | +| Month 1 | Windows統合 | Linux + Windows同時生成 | +| Month 2 | 全OS対応 | Linux/Windows/macOS | +| Month 3 | 最適化 | PAL完成、性能調整 | +| Month 6 | APE統合 | 単一バイナリ実現 | + +## 🚀 **次のアクション** + +1. **即実装**: Bitcodeキャッシュ機構 +2. **PAL設計**: 最小限のランタイムAPI定義 +3. **Windows-gnu**: mingwでクロスリンク環境構築 +4. **並列化**: rayon使用でマルチターゲット生成 + +## 💭 **結論** + +LLVM IRの中立性を活用すれば、**「Write Once, Compile to All」**が実現できる! + +これこそがNyashの革命的Windows戦略です。1回のコンパイルで全プラットフォーム対応、最終的には単一バイナリで境界を超える。 + +**Everything is Box、そしてEvery Platform is Target!**🎯 \ No newline at end of file diff --git a/docs/development/roadmap/phases/phase-9/llvm/VM-Native-Speed-Possibility.md b/docs/development/roadmap/phases/phase-9/llvm/VM-Native-Speed-Possibility.md new file mode 100644 index 00000000..d2a03fb6 --- /dev/null +++ b/docs/development/roadmap/phases/phase-9/llvm/VM-Native-Speed-Possibility.md @@ -0,0 +1,155 @@ +# 🚀 Nyash VM をネイティブ速度に近づける可能性 + +**「もしかして、VM完璧に作ればネイティブに近づける?」** + +## 💡 **その直感、正しいです!** + +### **現在のVM性能** +- インタープリター比: **50.94倍高速**(達成済み!) +- でもLLVMネイティブには及ばない...はず? + +### **でも待って、よく考えると...** + +## 🔥 **VMがネイティブに迫れる理由** + +### **1. JITコンパイルの可能性** +```rust +// 現在: バイトコード実行 +match opcode { + Add => stack.push(a + b), + // ... +} + +// 将来: ホットパスをネイティブコードに! +if execution_count > HOT_THRESHOLD { + let native_code = jit_compile(&bytecode); + execute_native(native_code); // ほぼネイティブ速度! +} +``` + +### **2. 最適化の余地がまだある** +```yaml +現在のVM最適化: + ✅ デバッグ出力削除 + ✅ HashMap → Vec + ✅ メモリ効率化 + +まだできること: + - レジスタVM化(スタックVM → レジスタVM) + - インライン展開 + - 定数畳み込み + - ループ最適化 + - SIMD活用 +``` + +### **3. 言語特性を活かした最適化** +```rust +// Nyashの特徴を利用 +- Everything is Box → 型情報を活用した特殊化 +- Arcパターン → 最適化可能な箇所を特定 +- 限定的な言語機能 → 積極的な最適化 +``` + +## 📊 **他言語VMの実績** + +| VM | 対ネイティブ性能 | 特徴 | +|----|----------------|------| +| **JVM (HotSpot)** | 80-95% | JIT最適化の極致 | +| **V8 (JavaScript)** | 70-90% | 型推論+インライン | +| **PyPy** | 400-700% (CPython比) | トレーシングJIT | +| **LuaJIT** | 90-99% | 超軽量JIT | + +**LuaJITは特に注目**: シンプルな言語 + 優れたJIT = ほぼネイティブ! + +## 🎯 **Nyash VMネイティブ化戦略** + +### **Phase 1: 基礎最適化(現在〜1ヶ月)** +```rust +// レジスタVM化 +enum VMRegister { + R0, R1, R2, R3, // ... R15 +} + +// より効率的な命令セット +enum Instruction { + LoadReg(VMRegister, Value), + AddReg(VMRegister, VMRegister, VMRegister), + // スタック操作を削減 +} +``` + +### **Phase 2: プロファイル駆動最適化(2-3ヶ月)** +```rust +struct HotPath { + bytecode: Vec, + execution_count: u64, + optimized_version: Option, +} + +// ホットパスを検出して最適化 +if hot_path.execution_count > 1000 { + optimize_hot_path(&mut hot_path); +} +``` + +### **Phase 3: 軽量JIT(6ヶ月)** +```rust +// Cranelift使用で軽量JIT実装 +use cranelift::prelude::*; + +fn jit_compile(bytecode: &[Instruction]) -> NativeCode { + let mut ctx = Context::new(); + // バイトコード → Cranelift IR → ネイティブ + compile_to_native(&mut ctx, bytecode) +} +``` + +## 🔮 **実現可能な性能目標** + +### **段階的目標** +1. **現在**: インタープリター比 50倍 +2. **Phase 1完了**: 100倍(レジスタVM化) +3. **Phase 2完了**: 200倍(最適化) +4. **Phase 3完了**: **ネイティブの80-90%**(JIT) + +### **なぜ可能か?** +- Nyashはシンプルな言語 +- Box型システムで最適化しやすい +- 既に50倍達成の実績 +- MIR基盤が整っている + +## 💭 **VM vs LLVM の最終形** + +```yaml +Nyash VM (完全体): + 利点: + - ポータビリティ完璧 + - 起動時間高速 + - 動的最適化可能 + - デバッグ容易 + 性能: ネイティブの80-90% + +LLVM AOT: + 利点: + - 最高性能(100%) + - 事前最適化 + - 配布サイズ小 + 欠点: + - プラットフォーム別ビルド + - 起動時最適化なし +``` + +## 🎉 **結論:VMでもいける!** + +**完璧に作れば、VMでもネイティブに迫れます!** + +特にNyashのような: +- シンプルな言語 +- 明確な型システム(Everything is Box) +- 限定的な機能セット + +これらの特徴は**VMの高速化に有利**! + +**もしかしたら、LLVM要らないかも...?**(いや、両方あると最強!) + +**Everything is Box、VM can be Native-Fast!**🚀✨ \ No newline at end of file diff --git a/docs/development/roadmap/phases/phase-9/llvm/Windows-Strategy-Summary.md b/docs/development/roadmap/phases/phase-9/llvm/Windows-Strategy-Summary.md new file mode 100644 index 00000000..31f68167 --- /dev/null +++ b/docs/development/roadmap/phases/phase-9/llvm/Windows-Strategy-Summary.md @@ -0,0 +1,91 @@ +# 🪟 Windows同時作戦の現状まとめ + +**更新日**: 2025年8月20日 + +## 📊 **現在の状況** + +### **✅ 完了したこと** +1. **AI大会議実施** + - Gemini先生: 4つの革命的戦略提案 + - Codex先生: 技術的実装方法の詳細化 + +2. **戦略文書作成** + - Revolutionary-Windows-Strategy.md: 統合戦略 + - APE-Magic-Explained.md: 単一バイナリ技術解説 + - Practical-Distribution-Strategy.md: 現実的配布方法 + +3. **技術的方針決定** + - **核心**: LLVM IRの中立性を活用した同時生成 + - **方法**: Bitcodeキャッシュ + 並列ターゲット生成 + +### **🚀 実装計画** + +#### **即効性のある解決策(Week 1-3)** +```bash +# Linux + Windows同時生成 +nyashc --targets linux,windows-gnu program.nyash + +# 出力 +dist/linux/nyash # Linux版(musl静的) +dist/windows/nyash.exe # Windows版(mingw) +``` + +**実装手順**: +1. Week 1: Linux版LLVM実装(進行中) +2. Week 2: Bitcodeキャッシュ機構追加 +3. Week 3: Windows-gnu同時生成 + +#### **中期計画(1-3ヶ月)** +- 全プラットフォーム同時対応 +- PAL (Platform Abstraction Layer) 完成 +- 最適化とテスト + +## 🛠️ **技術的アプローチ** + +### **1. ワンパス・マルチターゲット** +```rust +// 1回のIR生成 +let bitcode = module.write_bitcode_to_memory(); + +// 並列で各OS向け生成 +["linux", "windows-gnu", "macos"].par_iter() + .map(|target| generate_for_target(bitcode.clone(), target)) + .collect() +``` + +### **2. Windows特化戦略** +- **短期**: mingw-gnu(クロスコンパイル簡単) +- **長期**: msvc対応(xwin使用) +- **配布**: 916KBの小さな実行ファイル + +### **3. 段階的実装** +| Phase | 期間 | 成果 | +|-------|------|------| +| 現在 | LLVM PoC | Linux単体 | +| Week 3 | 同時生成 | Linux + Windows | +| Month 1 | 全OS | +macOS | +| Month 3 | 最適化 | PAL完成 | + +## 💡 **重要ポイント** + +### **すぐに実現可能なこと** +- ✅ Linux/Windows同時ビルド(mingw使用) +- ✅ 1つのコマンドで両OS対応 +- ✅ Bitcodeレベルでの共有 + +### **将来の野望** +- 🎯 全OS同時生成 +- 🎯 APE単一バイナリ(小ツール用) +- 🎯 完全なクロスプラットフォーム + +## 🎉 **結論** + +**Windows同時作戦は技術的に実現可能!** + +1. **LLVM IRの中立性**を最大活用 +2. **Bitcodeキャッシュ**で効率化 +3. **mingw**で即座にWindows対応 + +Copilotが基本LLVM実装を進めている間に、我々は革命的な同時生成戦略を準備完了! + +**Everything is Box、Every Platform is Target!**🎯✨ \ No newline at end of file diff --git a/docs/development/roadmap/phases/phase-9/llvm/issue/001-setup-inkwell-hello-world.md b/docs/development/roadmap/phases/phase-9/llvm/issue/001-setup-inkwell-hello-world.md new file mode 100644 index 00000000..3f62624a --- /dev/null +++ b/docs/development/roadmap/phases/phase-9/llvm/issue/001-setup-inkwell-hello-world.md @@ -0,0 +1,266 @@ +# 🚀 Issue #001: LLVM PoC - inkwellセットアップとHello World実装 + +**タイプ**: Feature +**優先度**: Critical +**見積もり**: 3日 +**担当**: Copilot + +## 📋 概要 + +Phase 9.78 LLVM PoCの第一歩として、inkwellクレートを導入し、最小限のNyashプログラム(`return 42`)をLLVM経由で実行できるようにする。 + +## 🎯 成功条件 + +以下のNyashプログラムがLLVM経由で実行され、正しい終了コードを返すこと: + +```nyash +// test_return_42.nyash +static box Main { + main() { + return 42 + } +} +``` + +期待される動作: +```bash +$ cargo run --features llvm -- --backend llvm test_return_42.nyash +$ echo $? +42 +``` + +## 📝 実装タスク + +### 1. **Cargo.toml更新** ✅必須 +```toml +[dependencies] +inkwell = { version = "0.5", features = ["llvm17-0"] } + +[features] +llvm = ["inkwell"] +``` + +### 2. **基本構造の作成** ✅必須 +```rust +// src/backend/llvm/mod.rs +pub mod context; +pub mod compiler; + +use crate::mir::module::MirModule; +use crate::errors::RuntimeError; + +pub fn compile_to_object( + mir_module: &MirModule, + output_path: &str, +) -> Result<(), RuntimeError> { + let compiler = compiler::LLVMCompiler::new()?; + compiler.compile_module(mir_module, output_path) +} +``` + +### 3. **LLVMコンテキスト管理** ✅必須 +```rust +// src/backend/llvm/context.rs +use inkwell::context::Context; +use inkwell::module::Module; +use inkwell::builder::Builder; +use inkwell::targets::{Target, TargetMachine, TargetTriple, InitializationConfig}; + +pub struct CodegenContext<'ctx> { + pub context: &'ctx Context, + pub module: Module<'ctx>, + pub builder: Builder<'ctx>, + pub target_machine: TargetMachine, +} + +impl<'ctx> CodegenContext<'ctx> { + pub fn new(context: &'ctx Context, module_name: &str) -> Result { + // 1. ターゲット初期化 + Target::initialize_native(&InitializationConfig::default()) + .map_err(|e| format!("Failed to initialize native target: {}", e))?; + + // 2. モジュール作成 + let module = context.create_module(module_name); + + // 3. ターゲットマシン作成 + let triple = TargetMachine::get_default_triple(); + let target = Target::from_triple(&triple) + .map_err(|e| format!("Failed to get target: {}", e))?; + let target_machine = target + .create_target_machine( + &triple, + "generic", + "", + inkwell::OptimizationLevel::None, + inkwell::targets::RelocMode::Default, + inkwell::targets::CodeModel::Default, + ) + .ok_or_else(|| "Failed to create target machine".to_string())?; + + // 4. データレイアウト設定 + module.set_triple(&triple); + module.set_data_layout(&target_machine.get_target_data().get_data_layout()); + + Ok(Self { + context, + module, + builder: context.create_builder(), + target_machine, + }) + } +} +``` + +### 4. **最小限のコンパイラ実装** ✅必須 +```rust +// src/backend/llvm/compiler.rs +use inkwell::context::Context; +use inkwell::values::IntValue; +use crate::mir::module::MirModule; +use crate::mir::instruction::MirInstruction; +use super::context::CodegenContext; + +pub struct LLVMCompiler { + context: Context, +} + +impl LLVMCompiler { + pub fn new() -> Result { + Ok(Self { + context: Context::create(), + }) + } + + pub fn compile_module( + &self, + mir_module: &MirModule, + output_path: &str, + ) -> Result<(), String> { + let codegen = CodegenContext::new(&self.context, "nyash_module")?; + + // 1. main関数を探す + let main_func = mir_module.functions.iter() + .find(|f| f.name == "Main.main") + .ok_or("Main.main function not found")?; + + // 2. LLVM関数を作成 + let i32_type = codegen.context.i32_type(); + let fn_type = i32_type.fn_type(&[], false); + let llvm_func = codegen.module.add_function("main", fn_type, None); + + // 3. エントリブロックを作成 + let entry = codegen.context.append_basic_block(llvm_func, "entry"); + codegen.builder.position_at_end(entry); + + // 4. MIR命令を処理(今回はReturnのみ) + for block in &main_func.blocks { + for inst in &block.instructions { + match inst { + MirInstruction::Return(Some(value_id)) => { + // 簡易実装: 定数42を返すと仮定 + let ret_val = i32_type.const_int(42, false); + codegen.builder.build_return(Some(&ret_val)); + } + _ => { + // 他の命令は今回スキップ + } + } + } + } + + // 5. 検証 + if !llvm_func.verify(true) { + return Err("Function verification failed".to_string()); + } + + // 6. オブジェクトファイル生成 + codegen.target_machine + .write_to_file(&codegen.module, + inkwell::targets::FileType::Object, + output_path.as_ref()) + .map_err(|e| format!("Failed to write object file: {}", e))?; + + Ok(()) + } +} +``` + +### 5. **バックエンド統合** ✅必須 +```rust +// src/backend/mod.rsに追加 +#[cfg(feature = "llvm")] +pub mod llvm; + +// src/runner.rsのrun_with_backend関数に追加 +#[cfg(feature = "llvm")] +ExecutionBackend::LLVM => { + // 1. オブジェクトファイル生成 + let obj_path = "nyash_output.o"; + crate::backend::llvm::compile_to_object(&mir_module, obj_path)?; + + // 2. リンク(簡易版:システムのccを使用) + use std::process::Command; + let output = Command::new("cc") + .args(&[obj_path, "-o", "nyash_output"]) + .output() + .map_err(|e| RuntimeError::new(format!("Link failed: {}", e)))?; + + if !output.status.success() { + return Err(RuntimeError::new("Linking failed")); + } + + // 3. 実行 + let output = Command::new("./nyash_output") + .output() + .map_err(|e| RuntimeError::new(format!("Execution failed: {}", e)))?; + + // 4. 終了コードを返す + let exit_code = output.status.code().unwrap_or(-1); + Ok(Box::new(IntegerBox::new(exit_code as i64))) +} +``` + +## 🧪 テストケース + +```rust +// tests/llvm_hello_world.rs +#[test] +#[cfg(feature = "llvm")] +fn test_return_42() { + let source = r#" + static box Main { + main() { + return 42 + } + } + "#; + + // パース → MIR生成 → LLVM実行 + let result = compile_and_run_llvm(source); + assert_eq!(result, 42); +} +``` + +## 📚 参考資料 + +- [inkwell Examples](https://github.com/TheDan64/inkwell/tree/master/examples) +- [LLVM Tutorial](https://llvm.org/docs/tutorial/) +- [AI大会議結果](../AI-Conference-LLVM-Results.md) + +## ⚠️ 注意事項 + +1. **LLVM依存関係**: LLVM 17がシステムにインストールされている必要があります +2. **プラットフォーム**: まずはLinux/macOSで動作確認し、Windowsは後回し +3. **エラーハンドリング**: 今回は最小実装のため、詳細なエラー処理は省略 + +## 🎯 次のステップ + +このIssueが完了したら、次は: +- Issue #002: 基本的な算術演算の実装(BinOp) +- Issue #003: 定数値の実装(Const) + +--- + +**作成者**: Claude + moe-charm +**レビュアー**: AIチーム +**関連PR**: (作成予定) \ No newline at end of file diff --git a/docs/development/roadmap/phases/phase-9/llvm/issue/GitHub-Issue-Template.md b/docs/development/roadmap/phases/phase-9/llvm/issue/GitHub-Issue-Template.md new file mode 100644 index 00000000..84eabb7a --- /dev/null +++ b/docs/development/roadmap/phases/phase-9/llvm/issue/GitHub-Issue-Template.md @@ -0,0 +1,119 @@ +# 🐙 GitHub Issue作成テンプレート + +以下の内容をGitHub Issueにコピペして使用してください。 + +--- + +## Issue Title: +`[Phase 9.78] LLVM PoC Week 1 - inkwellセットアップとHello World実装` + +## Labels: +- `enhancement` +- `Phase-9.78` +- `LLVM` +- `critical` + +## Assignees: +- GitHub Copilot + +## Milestone: +- Phase 9.78 LLVM PoC + +## Issue Body: + +```markdown +## 📋 概要 + +Phase 9.78 LLVM PoCの開始です!最初のステップとして、inkwellクレートを導入し、最小限のNyashプログラム(`return 42`)をLLVM経由で実行できるようにします。 + +## 🎯 成功条件 + +```nyash +// test_return_42.nyash +static box Main { + main() { + return 42 + } +} +``` + +上記プログラムがLLVM経由で実行され、終了コード42を返すこと。 + +## 📝 実装内容 + +1. **inkwellクレート導入** + - Cargo.tomlに依存関係追加 + - feature flag `llvm` の設定 + +2. **基本構造作成** + - `src/backend/llvm/` ディレクトリ + - context.rs, compiler.rs, mod.rs + +3. **最小限のコンパイラ実装** + - LLVMコンテキスト初期化 + - main関数の生成 + - return命令の処理 + - オブジェクトファイル出力 + +4. **統合** + - ExecutionBackendにLLVM追加 + - --backend llvm オプション対応 + +## 🔗 参考資料 + +- [詳細実装ガイド](https://github.com/moe-charm/nyash/blob/main/docs/予定/native-plan/llvm/issue/001-setup-inkwell-hello-world.md) +- [Week 1ロードマップ](https://github.com/moe-charm/nyash/blob/main/docs/予定/native-plan/llvm/issue/Week1-Roadmap.md) +- [AI大会議結果](https://github.com/moe-charm/nyash/blob/main/docs/予定/native-plan/llvm/AI-Conference-LLVM-Results.md) + +## ✅ 完了条件 + +- [ ] inkwellがビルドできる +- [ ] test_return_42.nyashがコンパイルできる +- [ ] 実行ファイルが終了コード42を返す +- [ ] 基本的なテストがパスする + +## 💬 備考 + +VM性能改善で素晴らしい成果(50.94倍高速化)を達成していただきありがとうございました! +LLVMでも同様の成功を期待しています。ブロッカーがあれば遠慮なくコメントしてください。 + +AIチーム(Claude, Gemini, Codex)が全力でサポートします!🚀 +``` + +--- + +## 📝 追加で作成するIssue + +Week 1の進捗に応じて、以下のIssueも順次作成: + +1. **Issue #002**: `[Phase 9.78] LLVM PoC - Const命令の実装` +2. **Issue #003**: `[Phase 9.78] LLVM PoC - 基本型システムの実装` +3. **Issue #004**: `[Phase 9.78] LLVM PoC - ランタイム関数宣言` +4. **Issue #005**: `[Phase 9.78] LLVM PoC Week 1 - 統合テスト` + +## 🏷️ 推奨ラベル構成 + +```yaml +Phase関連: + - Phase-9.78 + - Phase-8.6 (完了) + - Phase-9.75g-0 (完了) + +技術関連: + - LLVM + - MIR + - Performance + - Backend + +優先度: + - critical + - high + - medium + - low + +タイプ: + - enhancement + - bug + - documentation + - test +``` \ No newline at end of file diff --git a/docs/development/roadmap/phases/phase-9/llvm/issue/MIR-Quick-Reference.md b/docs/development/roadmap/phases/phase-9/llvm/issue/MIR-Quick-Reference.md new file mode 100644 index 00000000..7449942a --- /dev/null +++ b/docs/development/roadmap/phases/phase-9/llvm/issue/MIR-Quick-Reference.md @@ -0,0 +1,159 @@ +# 📚 MIR クイックリファレンス for LLVM実装 + +## 🎯 Week 1で対応するMIR命令 + +### 1. **Const命令** +```rust +// MIR表現 +MirInstruction::Const(value_id, constant_value) + +// 例 +Const(v1, MirConstant::Integer(42)) +Const(v2, MirConstant::Float(3.14)) +Const(v3, MirConstant::Bool(true)) + +// LLVM変換 +let int_val = ctx.i32_type().const_int(42, false); +let float_val = ctx.f64_type().const_float(3.14); +let bool_val = ctx.bool_type().const_int(1, false); +``` + +### 2. **Return命令** +```rust +// MIR表現 +MirInstruction::Return(Option) + +// 例 +Return(Some(v1)) // 値を返す +Return(None) // voidを返す + +// LLVM変換 +builder.build_return(Some(&value)); +builder.build_return(None); +``` + +## 📄 参考: 現在のMIR構造 + +```rust +// src/mir/instruction.rs の主要部分 +pub enum MirInstruction { + // Week 1対象 + Const(ValueId, MirConstant), + Return(Option), + + // Week 2対象 + BinOp(ValueId, BinaryOp, ValueId, ValueId), + Compare(ValueId, CompareOp, ValueId, ValueId), + Branch(ValueId, BasicBlockId, BasicBlockId), + Jump(BasicBlockId), + + // Week 3以降 + BoxNew(ValueId, MirType), + BoxCall(ValueId, ValueId, String, Vec), + // ... 他の命令 +} + +// 定数の型 +pub enum MirConstant { + Integer(i64), + Float(f64), + Bool(bool), + String(String), + Null, +} +``` + +## 🔄 MIR→LLVM変換の基本パターン + +```rust +// 基本的な変換ループ +for instruction in &block.instructions { + match instruction { + MirInstruction::Const(value_id, constant) => { + let llvm_value = match constant { + MirConstant::Integer(n) => { + ctx.i64_type().const_int(*n as u64, true).into() + } + MirConstant::Float(f) => { + ctx.f64_type().const_float(*f).into() + } + MirConstant::Bool(b) => { + ctx.bool_type().const_int(*b as u64, false).into() + } + _ => todo!("Other constants"), + }; + // value_idとllvm_valueをマッピングに保存 + value_map.insert(*value_id, llvm_value); + } + + MirInstruction::Return(value_id) => { + match value_id { + Some(id) => { + let value = value_map.get(id).unwrap(); + builder.build_return(Some(value)); + } + None => { + builder.build_return(None); + } + } + } + + _ => {} // Week 1では他の命令は無視 + } +} +``` + +## 🎯 テスト用のMIRサンプル + +### 1. **return 42のMIR** +```rust +MirModule { + functions: vec![ + MirFunction { + name: "Main.main", + params: vec![], + return_type: MirType::Integer, + blocks: vec![ + BasicBlock { + id: 0, + instructions: vec![ + Const(v1, MirConstant::Integer(42)), + Return(Some(v1)), + ], + }, + ], + }, + ], +} +``` + +### 2. **簡単な計算のMIR**(Week 2用) +```rust +// return 10 + 5 +BasicBlock { + instructions: vec![ + Const(v1, MirConstant::Integer(10)), + Const(v2, MirConstant::Integer(5)), + BinOp(v3, BinaryOp::Add, v1, v2), + Return(Some(v3)), + ], +} +``` + +## 💡 実装のヒント + +1. **ValueIdマッピング**: `HashMap`で管理 +2. **型情報**: MIRは型情報を持つので、LLVM型への変換テーブルを作る +3. **基本ブロック**: MIRのBasicBlockIdをLLVMのBasicBlockにマッピング +4. **エラー処理**: 最初は`todo!()`でOK、後から実装 + +## 📁 関連ファイル + +- MIR定義: `src/mir/instruction.rs` +- MIR生成: `src/mir/lowering.rs` +- 参考実装: `src/backend/vm.rs`(VMのMIR処理) + +--- + +**注**: このリファレンスはWeek 1の実装に必要な最小限の情報です。 +詳細は実際のソースコードを参照してください。 \ No newline at end of file diff --git a/docs/development/roadmap/phases/phase-9/llvm/issue/Quick-Start-Guide.md b/docs/development/roadmap/phases/phase-9/llvm/issue/Quick-Start-Guide.md new file mode 100644 index 00000000..19abc805 --- /dev/null +++ b/docs/development/roadmap/phases/phase-9/llvm/issue/Quick-Start-Guide.md @@ -0,0 +1,134 @@ +# 🚀 LLVM実装クイックスタートガイド + +## 📋 今すぐ始める手順 + +### 1. **環境準備**(5分) +```bash +# LLVM 17インストール確認 +llvm-config --version # 17.x.x が表示されること + +# Nyashプロジェクトで作業 +cd /path/to/nyash +git checkout -b feature/llvm-poc +``` + +### 2. **最初のコミット**(10分) +```bash +# Cargo.tomlを編集 +echo '[dependencies] +inkwell = { version = "0.5", features = ["llvm17-0"] } + +[features] +llvm = ["inkwell"]' >> Cargo.toml + +# ディレクトリ作成 +mkdir -p src/backend/llvm + +# 最初のファイル作成 +touch src/backend/llvm/mod.rs +touch src/backend/llvm/context.rs +touch src/backend/llvm/compiler.rs + +# コミット +git add . +git commit -m "feat(llvm): Add inkwell dependency and basic structure" +``` + +### 3. **最小実装のコピペ**(20分) + +**src/backend/llvm/mod.rs**: +```rust +pub mod context; +pub mod compiler; + +pub use compiler::compile_to_object; +``` + +**動作確認**: +```bash +cargo build --features llvm +``` + +### 4. **テストプログラム作成**(5分) +```bash +# テスト用Nyashファイル +cat > test_return_42.nyash << 'EOF' +static box Main { + main() { + return 42 + } +} +EOF +``` + +## 🔍 詰まったときの確認ポイント + +### **ビルドエラーの場合** +```bash +# LLVM関連の環境変数確認 +echo $LLVM_SYS_170_PREFIX + +# 設定されていない場合 +export LLVM_SYS_170_PREFIX=$(llvm-config --prefix) +``` + +### **inkwellのバージョン問題** +```toml +# 代替バージョン +inkwell = { git = "https://github.com/TheDan64/inkwell", branch = "master", features = ["llvm17-0"] } +``` + +### **リンクエラーの場合** +```bash +# pkg-configの確認 +pkg-config --libs --cflags llvm +``` + +## 📞 ヘルプが必要な場合 + +1. **GitHub Issue**にコメント +2. **具体的なエラーメッセージ**を貼る +3. **実行したコマンド**を記載 + +例: +``` +inkwellのビルドでエラーが発生しました。 + +エラー: +``` +error: failed to run custom build command for `llvm-sys v170.0.1` +``` + +実行コマンド: +``` +cargo build --features llvm +``` + +環境: +- OS: Ubuntu 22.04 +- LLVM: 17.0.6 +- Rust: 1.75.0 +``` + +## ✅ 最初の成功確認 + +以下が動けば第一歩成功! +```bash +# ビルドが通る +cargo build --features llvm + +# テストが実行できる(まだ失敗してOK) +cargo test --features llvm test_llvm +``` + +## 🎯 次のステップ + +1. **context.rs**の実装 +2. **compiler.rs**の実装 +3. **return 42**の動作確認 + +詳細は[001-setup-inkwell-hello-world.md](./001-setup-inkwell-hello-world.md)を参照! + +--- + +**Remember**: 完璧より進捗!最初は動くことが最優先です。🚀 \ No newline at end of file diff --git a/docs/development/roadmap/phases/phase-9/llvm/issue/README.md b/docs/development/roadmap/phases/phase-9/llvm/issue/README.md new file mode 100644 index 00000000..7c9e135f --- /dev/null +++ b/docs/development/roadmap/phases/phase-9/llvm/issue/README.md @@ -0,0 +1,60 @@ +# 📚 LLVM PoC Issue ドキュメント一覧 + +## 🎯 Copilot様へ:最初に読むファイル + +1. **[Quick-Start-Guide.md](./Quick-Start-Guide.md)** 🚀 + - 今すぐ始める手順 + - 環境セットアップ + - 最初のコミット方法 + +2. **[001-setup-inkwell-hello-world.md](./001-setup-inkwell-hello-world.md)** 📋 + - **最初のIssue内容** + - 詳細な実装手順 + - コード例とテストケース + +3. **[Week1-Roadmap.md](./Week1-Roadmap.md)** 📅 + - Week 1全体の計画 + - Issue実装順序 + - 成功条件 + +## 📖 参考資料 + +- **[MIR-Quick-Reference.md](./MIR-Quick-Reference.md)** + - MIR命令の説明 + - LLVM変換パターン + - テスト用サンプル + +- **[GitHub-Issue-Template.md](./GitHub-Issue-Template.md)** + - GitHub Issue作成用テンプレート + - ラベル設定 + - マイルストーン + +## 🔗 関連ドキュメント(上位階層) + +- [AI大会議結果](../AI-Conference-LLVM-Results.md) +- [実装計画書](../Phase-9.78-Implementation-Plan.md) +- [Copilot依頼文書](../Copilot-Request-LLVM-PoC.md) + +## 💬 重要メッセージ + +**Copilot様へ** + +Phase 8.6での素晴らしい成果(50.94倍高速化)に続き、LLVMでも革命的な性能向上を期待しています! + +**開始方法**: +1. まず[Quick-Start-Guide.md](./Quick-Start-Guide.md)を読む +2. [001-setup-inkwell-hello-world.md](./001-setup-inkwell-hello-world.md)の実装を開始 +3. 詰まったらすぐにGitHub Issueでヘルプ要請 + +**サポート体制**: +- AIチーム(Claude, Gemini, Codex)が全力サポート +- 技術的な質問は遠慮なく +- 小さな成功を積み重ねましょう + +Let's make Nyash fly with LLVM! 🚀✨ + +--- + +**最終更新**: 2025年8月20日 +**作成者**: Claude + moe-charm +**Phase**: 9.78 LLVM PoC \ No newline at end of file diff --git a/docs/development/roadmap/phases/phase-9/llvm/issue/Week1-Roadmap.md b/docs/development/roadmap/phases/phase-9/llvm/issue/Week1-Roadmap.md new file mode 100644 index 00000000..7386c8bc --- /dev/null +++ b/docs/development/roadmap/phases/phase-9/llvm/issue/Week1-Roadmap.md @@ -0,0 +1,88 @@ +# 📅 Week 1 ロードマップ: LLVM基盤構築 + +**期間**: 2025年8月21日〜8月27日 +**目標**: LLVMバックエンドの基盤を構築し、最小限のプログラムを実行可能にする + +## 🎯 Week 1の全体目標 + +「return 42」レベルの超シンプルなNyashプログラムが、LLVM経由で実行できる状態を達成する。 + +## 📋 Issue実装順序 + +### **Issue #001: inkwellセットアップとHello World** 🚀最初にこれ! +- **期間**: Day 1-3 +- **内容**: 環境構築と「return 42」の実行 +- **成功条件**: LLVMでコンパイルした実行ファイルが終了コード42を返す +- **ファイル**: [001-setup-inkwell-hello-world.md](./001-setup-inkwell-hello-world.md) + +### **Issue #002: Const命令の実装**(#001完了後) +- **期間**: Day 3-4 +- **内容**: MIR Const命令をLLVM定数に変換 +- **対象**: Integer, Float, Bool定数 +- **テスト**: `return 100`, `return 3.14`, `return true` + +### **Issue #003: 基本的な型システム**(#002と並行可能) +- **期間**: Day 4-5 +- **内容**: MIR型→LLVM型のマッピング実装 +- **対象**: i32/i64, f64, bool, 関数型 +- **成果**: type_cache の実装 + +### **Issue #004: ランタイム関数宣言**(#003完了後) +- **期間**: Day 5-6 +- **内容**: nyash_runtime_* 関数の宣言 +- **対象**: alloc, free, print_int(デバッグ用) +- **準備**: 最小限のCランタイム作成 + +### **Issue #005: Week 1統合テスト**(最終日) +- **期間**: Day 7 +- **内容**: 複数の小さなプログラムでテスト +- **確認**: CI/CDでのLLVMビルド +- **文書**: Week 2への引き継ぎ事項 + +## 🔄 実装の流れ + +```mermaid +graph LR + A[Issue #001
環境構築] --> B[Issue #002
Const実装] + A --> C[Issue #003
型システム] + B --> D[Issue #004
ランタイム] + C --> D + D --> E[Issue #005
統合テスト] +``` + +## ✅ Week 1完了時のチェックリスト + +- [ ] inkwellクレートが正常に動作 +- [ ] 「return 42」がLLVM経由で実行可能 +- [ ] Integer/Float/Bool定数がサポート済み +- [ ] 基本的な型変換が実装済み +- [ ] 最小限のランタイム関数が宣言済み +- [ ] 5個以上のテストケースがパス + +## 📊 リスクと対策 + +| リスク | 対策 | +|--------|------| +| LLVM環境構築で詰まる | Docker環境を準備、LLVM17固定 | +| inkwellのAPIが複雑 | 公式exampleを参考に最小実装 | +| リンクエラー | まずは静的リンク、動的は後回し | + +## 💡 成功のコツ + +1. **小さく始める**: return 42が動けば大成功 +2. **エラーを恐れない**: LLVMのエラーメッセージは親切 +3. **IR出力を確認**: `--emit-llvm`でIRをダンプして確認 +4. **既存コード活用**: VM/WASMバックエンドの構造を参考に + +## 🎉 Week 1成功時の次のステップ + +**Week 2では以下に取り組みます**: +- BinOp(四則演算)の実装 +- Branch/Jumpによる制御フロー +- Box型の基本操作 +- PHIノードの実装 + +--- + +**注意**: 各Issueは独立して実装可能ですが、推奨順序に従うとスムーズです。 +ブロッカーがあれば即座にAIチームに相談してください! \ No newline at end of file diff --git a/docs/予定/native-plan/issues/phase9_51_wasm_jump_http_fixes.md b/docs/development/roadmap/phases/phase-9/phase9_51_wasm_jump_http_fixes.md similarity index 100% rename from docs/予定/native-plan/issues/phase9_51_wasm_jump_http_fixes.md rename to docs/development/roadmap/phases/phase-9/phase9_51_wasm_jump_http_fixes.md diff --git a/docs/予定/native-plan/issues/phase9_5_http_server_validation.md b/docs/development/roadmap/phases/phase-9/phase9_5_http_server_validation.md similarity index 100% rename from docs/予定/native-plan/issues/phase9_5_http_server_validation.md rename to docs/development/roadmap/phases/phase-9/phase9_5_http_server_validation.md diff --git a/docs/予定/native-plan/issues/phase9_75_socketbox_arc_mutex_redesign.md b/docs/development/roadmap/phases/phase-9/phase9_75_socketbox_arc_mutex_redesign.md similarity index 100% rename from docs/予定/native-plan/issues/phase9_75_socketbox_arc_mutex_redesign.md rename to docs/development/roadmap/phases/phase-9/phase9_75_socketbox_arc_mutex_redesign.md diff --git a/docs/予定/native-plan/issues/phase9_75b_remaining_boxes_arc_mutex_redesign.md b/docs/development/roadmap/phases/phase-9/phase9_75b_remaining_boxes_arc_mutex_redesign.md similarity index 100% rename from docs/予定/native-plan/issues/phase9_75b_remaining_boxes_arc_mutex_redesign.md rename to docs/development/roadmap/phases/phase-9/phase9_75b_remaining_boxes_arc_mutex_redesign.md diff --git a/docs/予定/native-plan/issues/phase9_75c_remaining_boxes_arc_mutex_final.md b/docs/development/roadmap/phases/phase-9/phase9_75c_remaining_boxes_arc_mutex_final.md similarity index 100% rename from docs/予定/native-plan/issues/phase9_75c_remaining_boxes_arc_mutex_final.md rename to docs/development/roadmap/phases/phase-9/phase9_75c_remaining_boxes_arc_mutex_final.md diff --git a/docs/予定/native-plan/issues/phase9_aot_wasm_implementation.md b/docs/development/roadmap/phases/phase-9/phase9_aot_wasm_implementation.md similarity index 100% rename from docs/予定/native-plan/issues/phase9_aot_wasm_implementation.md rename to docs/development/roadmap/phases/phase-9/phase9_aot_wasm_implementation.md diff --git a/docs/予定/native-plan/issues/phase9_jit_baseline_planning.md b/docs/development/roadmap/phases/phase-9/phase9_jit_baseline_planning.md similarity index 100% rename from docs/予定/native-plan/issues/phase9_jit_baseline_planning.md rename to docs/development/roadmap/phases/phase-9/phase9_jit_baseline_planning.md diff --git a/docs/予定/native-plan/issues/phase_9_10_nyir_spec.md b/docs/development/roadmap/phases/phase-9/phase_9_10_nyir_spec.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_10_nyir_spec.md rename to docs/development/roadmap/phases/phase-9/phase_9_10_nyir_spec.md diff --git a/docs/予定/native-plan/issues/phase_9_12_universal_frontends.md b/docs/development/roadmap/phases/phase-9/phase_9_12_universal_frontends.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_12_universal_frontends.md rename to docs/development/roadmap/phases/phase-9/phase_9_12_universal_frontends.md diff --git a/docs/予定/native-plan/issues/phase_9_75c_debugbox_fix.md b/docs/development/roadmap/phases/phase-9/phase_9_75c_debugbox_fix.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_75c_debugbox_fix.md rename to docs/development/roadmap/phases/phase-9/phase_9_75c_debugbox_fix.md diff --git a/docs/予定/native-plan/issues/phase_9_75c_fix_compile_errors.md b/docs/development/roadmap/phases/phase-9/phase_9_75c_fix_compile_errors.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_75c_fix_compile_errors.md rename to docs/development/roadmap/phases/phase-9/phase_9_75c_fix_compile_errors.md diff --git a/docs/予定/native-plan/issues/phase_9_75c_fix_compile_errors_jp.md b/docs/development/roadmap/phases/phase-9/phase_9_75c_fix_compile_errors_jp.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_75c_fix_compile_errors_jp.md rename to docs/development/roadmap/phases/phase-9/phase_9_75c_fix_compile_errors_jp.md diff --git a/docs/予定/native-plan/issues/phase_9_75d_clone_box_share_box_redesign.md b/docs/development/roadmap/phases/phase-9/phase_9_75d_clone_box_share_box_redesign.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_75d_clone_box_share_box_redesign.md rename to docs/development/roadmap/phases/phase-9/phase_9_75d_clone_box_share_box_redesign.md diff --git a/docs/予定/native-plan/issues/phase_9_75e_namespace_using_system.md b/docs/development/roadmap/phases/phase-9/phase_9_75e_namespace_using_system.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_75e_namespace_using_system.md rename to docs/development/roadmap/phases/phase-9/phase_9_75e_namespace_using_system.md diff --git a/docs/予定/native-plan/issues/phase_9_75f_1_filebox_dynamic.md b/docs/development/roadmap/phases/phase-9/phase_9_75f_1_filebox_dynamic.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_75f_1_filebox_dynamic.md rename to docs/development/roadmap/phases/phase-9/phase_9_75f_1_filebox_dynamic.md diff --git a/docs/予定/native-plan/issues/phase_9_75f_2_math_time_dynamic.md b/docs/development/roadmap/phases/phase-9/phase_9_75f_2_math_time_dynamic.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_75f_2_math_time_dynamic.md rename to docs/development/roadmap/phases/phase-9/phase_9_75f_2_math_time_dynamic.md diff --git a/docs/予定/native-plan/issues/phase_9_75f_3_core_types_experiment.md b/docs/development/roadmap/phases/phase-9/phase_9_75f_3_core_types_experiment.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_75f_3_core_types_experiment.md rename to docs/development/roadmap/phases/phase-9/phase_9_75f_3_core_types_experiment.md diff --git a/docs/予定/native-plan/issues/phase_9_75f_dynamic_library_architecture.md b/docs/development/roadmap/phases/phase-9/phase_9_75f_dynamic_library_architecture.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_75f_dynamic_library_architecture.md rename to docs/development/roadmap/phases/phase-9/phase_9_75f_dynamic_library_architecture.md diff --git a/docs/予定/native-plan/issues/phase_9_75g_0_chatgpt_enhanced_final.md b/docs/development/roadmap/phases/phase-9/phase_9_75g_0_chatgpt_enhanced_final.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_75g_0_chatgpt_enhanced_final.md rename to docs/development/roadmap/phases/phase-9/phase_9_75g_0_chatgpt_enhanced_final.md diff --git a/docs/予定/native-plan/issues/phase_9_75g_0_everything_is_box_aligned.md b/docs/development/roadmap/phases/phase-9/phase_9_75g_0_everything_is_box_aligned.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_75g_0_everything_is_box_aligned.md rename to docs/development/roadmap/phases/phase-9/phase_9_75g_0_everything_is_box_aligned.md diff --git a/docs/予定/native-plan/issues/phase_9_75g_0_final_corrected_design.md b/docs/development/roadmap/phases/phase-9/phase_9_75g_0_final_corrected_design.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_75g_0_final_corrected_design.md rename to docs/development/roadmap/phases/phase-9/phase_9_75g_0_final_corrected_design.md diff --git a/docs/予定/native-plan/issues/phase_9_75g_0_revised_type_first_approach.md b/docs/development/roadmap/phases/phase-9/phase_9_75g_0_revised_type_first_approach.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_75g_0_revised_type_first_approach.md rename to docs/development/roadmap/phases/phase-9/phase_9_75g_0_revised_type_first_approach.md diff --git a/docs/予定/native-plan/issues/phase_9_75g_0_simplified_bid_ffi_implementation.md b/docs/development/roadmap/phases/phase-9/phase_9_75g_0_simplified_bid_ffi_implementation.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_75g_0_simplified_bid_ffi_implementation.md rename to docs/development/roadmap/phases/phase-9/phase_9_75g_0_simplified_bid_ffi_implementation.md diff --git a/docs/予定/native-plan/issues/phase_9_75g_bid_ffi_abi_alignment.md b/docs/development/roadmap/phases/phase-9/phase_9_75g_bid_ffi_abi_alignment.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_75g_bid_ffi_abi_alignment.md rename to docs/development/roadmap/phases/phase-9/phase_9_75g_bid_ffi_abi_alignment.md diff --git a/docs/予定/native-plan/issues/phase_9_75g_bid_integration_architecture.md b/docs/development/roadmap/phases/phase-9/phase_9_75g_bid_integration_architecture.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_75g_bid_integration_architecture.md rename to docs/development/roadmap/phases/phase-9/phase_9_75g_bid_integration_architecture.md diff --git a/docs/予定/native-plan/issues/phase_9_77_wasm_emergency.md b/docs/development/roadmap/phases/phase-9/phase_9_77_wasm_emergency.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_77_wasm_emergency.md rename to docs/development/roadmap/phases/phase-9/phase_9_77_wasm_emergency.md diff --git a/docs/予定/native-plan/issues/phase_9_77a_utf8_error_fix.md b/docs/development/roadmap/phases/phase-9/phase_9_77a_utf8_error_fix.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_77a_utf8_error_fix.md rename to docs/development/roadmap/phases/phase-9/phase_9_77a_utf8_error_fix.md diff --git a/docs/予定/native-plan/issues/phase_9_78_unified_box_factory_architecture.md b/docs/development/roadmap/phases/phase-9/phase_9_78_unified_box_factory_architecture.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_78_unified_box_factory_architecture.md rename to docs/development/roadmap/phases/phase-9/phase_9_78_unified_box_factory_architecture.md diff --git a/docs/予定/native-plan/issues/phase_9_78a_vm_plugin_integration.md b/docs/development/roadmap/phases/phase-9/phase_9_78a_vm_plugin_integration.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_78a_vm_plugin_integration.md rename to docs/development/roadmap/phases/phase-9/phase_9_78a_vm_plugin_integration.md diff --git a/docs/予定/native-plan/issues/phase_9_78a_vm_plugin_integration_deep_analysis.md b/docs/development/roadmap/phases/phase-9/phase_9_78a_vm_plugin_integration_deep_analysis.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_78a_vm_plugin_integration_deep_analysis.md rename to docs/development/roadmap/phases/phase-9/phase_9_78a_vm_plugin_integration_deep_analysis.md diff --git a/docs/予定/native-plan/issues/phase_9_78b_interpreter_architecture_refactoring.md b/docs/development/roadmap/phases/phase-9/phase_9_78b_interpreter_architecture_refactoring.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_78b_interpreter_architecture_refactoring.md rename to docs/development/roadmap/phases/phase-9/phase_9_78b_interpreter_architecture_refactoring.md diff --git a/docs/予定/native-plan/issues/phase_9_78c_plugin_delegation_unification.md b/docs/development/roadmap/phases/phase-9/phase_9_78c_plugin_delegation_unification.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_78c_plugin_delegation_unification.md rename to docs/development/roadmap/phases/phase-9/phase_9_78c_plugin_delegation_unification.md diff --git a/docs/予定/native-plan/issues/phase_9_7_box_ffi_abi_and_externcall.md b/docs/development/roadmap/phases/phase-9/phase_9_7_box_ffi_abi_and_externcall.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_7_box_ffi_abi_and_externcall.md rename to docs/development/roadmap/phases/phase-9/phase_9_7_box_ffi_abi_and_externcall.md diff --git a/docs/予定/native-plan/issues/phase_9_8_bid_registry_and_codegen.md b/docs/development/roadmap/phases/phase-9/phase_9_8_bid_registry_and_codegen.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_8_bid_registry_and_codegen.md rename to docs/development/roadmap/phases/phase-9/phase_9_8_bid_registry_and_codegen.md diff --git a/docs/予定/native-plan/issues/phase_9_9_permissions_capability_model.md b/docs/development/roadmap/phases/phase-9/phase_9_9_permissions_capability_model.md similarity index 100% rename from docs/予定/native-plan/issues/phase_9_9_permissions_capability_model.md rename to docs/development/roadmap/phases/phase-9/phase_9_9_permissions_capability_model.md diff --git a/docs/予定/native-plan/issues/tooling_snapshot_printer.md b/docs/development/tools/tooling_snapshot_printer.md similarity index 100% rename from docs/予定/native-plan/issues/tooling_snapshot_printer.md rename to docs/development/tools/tooling_snapshot_printer.md diff --git a/docs/予定/native-plan/issues/vm_profiling_backend.md b/docs/development/tools/vm_profiling_backend.md similarity index 100% rename from docs/予定/native-plan/issues/vm_profiling_backend.md rename to docs/development/tools/vm_profiling_backend.md diff --git a/docs/examples/README.md b/docs/examples/README.md new file mode 100644 index 00000000..299bf490 --- /dev/null +++ b/docs/examples/README.md @@ -0,0 +1,14 @@ +# Examples: Plugin BoxRef Return (v2.2) + +- File: `plugin_boxref_return.nyash` +- Purpose: Demonstrates a plugin method returning a Box (BoxRef/Handle), and passing Box as an argument. + +How to run (after full build): +- Ensure `nyash.toml` includes FileBox with methods: + - `copyFrom = { method_id = 7, args = [ { kind = "box", category = "plugin" } ] }` + - `cloneSelf = { method_id = 8 }` +- Build the plugin: `cd plugins/nyash-filebox-plugin && cargo build --release` +- Run the example: `./target/release/nyash docs/examples/plugin_boxref_return.nyash` + +Expected behavior: +- Creates two FileBox instances (`f`, `g`), writes to `f`, copies content to `g` via `copyFrom`, then closes both. diff --git a/docs/examples/plugin_boxref_return.nyash b/docs/examples/plugin_boxref_return.nyash new file mode 100644 index 00000000..a5de358b --- /dev/null +++ b/docs/examples/plugin_boxref_return.nyash @@ -0,0 +1,29 @@ +# プラグインBoxの返り値がBoxの例(v2.2) + +static box Main { + init { console } + + main() { + me.console = new ConsoleBox() + me.console.log("[Example] Plugin BoxRef return demo") + + # FileBoxのインスタンスを生成 + local f = new FileBox() + + # cloneSelf() は Box を返す(BoxRef/Handle) + local g = f.cloneSelf() + + # 以降、通常のBoxと同じように扱える + f.open("example.txt", "w") + f.write("hello nyash") + + # 引数にBoxを渡す(v2.1) + g.copyFrom(f) + + f.close() + g.close() + + me.console.log("done") + } +} + diff --git a/docs/guides/README.md b/docs/guides/README.md new file mode 100644 index 00000000..fb19208e --- /dev/null +++ b/docs/guides/README.md @@ -0,0 +1,30 @@ +# Nyash User Guides 📚 + +Nyashプログラミング言語の利用者向けガイドとチュートリアルです。 + +## 🚀 はじめに +- `getting-started.md` - Nyashを始めるためのクイックガイド + +## 📖 サブディレクトリ + +### tutorials/ +- `hello-world.md` - 最初のNyashプログラム +- `basic-boxes.md` - Box(クラス)の基礎 +- `delegation.md` - デリゲーションの使い方 +- `p2p-apps.md` - P2Pアプリケーション開発 + +### examples/ +- 実践的なサンプルコード集 +- よくあるパターンの実装例 +- ベストプラクティス + +### wasm-guide/ +- WebAssemblyビルドガイド +- ブラウザープレイグラウンドの使い方 +- Webアプリケーション開発 + +## 🎯 学習順序 +1. `getting-started.md` から始める +2. `tutorials/` のチュートリアルを順番に +3. `examples/` で実践的なコードを学ぶ +4. 特定用途(WASM等)は各ガイドへ \ No newline at end of file diff --git a/docs/説明書/GETTING_STARTED.md b/docs/guides/getting-started.md similarity index 100% rename from docs/説明書/GETTING_STARTED.md rename to docs/guides/getting-started.md diff --git a/docs/説明書/LANGUAGE_GUIDE.md b/docs/guides/language-guide.md similarity index 100% rename from docs/説明書/LANGUAGE_GUIDE.md rename to docs/guides/language-guide.md diff --git a/docs/説明書/P2P_GUIDE.md b/docs/guides/p2p-guide.md similarity index 100% rename from docs/説明書/P2P_GUIDE.md rename to docs/guides/p2p-guide.md diff --git a/docs/説明書/guides/1_getting_started.md b/docs/guides/tutorials/1_getting_started.md similarity index 100% rename from docs/説明書/guides/1_getting_started.md rename to docs/guides/tutorials/1_getting_started.md diff --git a/docs/説明書/guides/2_language_guide.md b/docs/guides/tutorials/2_language_guide.md similarity index 100% rename from docs/説明書/guides/2_language_guide.md rename to docs/guides/tutorials/2_language_guide.md diff --git a/docs/説明書/guides/playground_guide.md b/docs/guides/tutorials/playground_guide.md similarity index 100% rename from docs/説明書/guides/playground_guide.md rename to docs/guides/tutorials/playground_guide.md diff --git a/docs/説明書/wasm/README.md b/docs/guides/wasm-guide/README.md similarity index 100% rename from docs/説明書/wasm/README.md rename to docs/guides/wasm-guide/README.md diff --git a/docs/予定/wasm/README.md b/docs/guides/wasm-guide/planning/README.md similarity index 100% rename from docs/予定/wasm/README.md rename to docs/guides/wasm-guide/planning/README.md diff --git a/docs/予定/wasm/compatibility_matrix.md b/docs/guides/wasm-guide/planning/compatibility_matrix.md similarity index 100% rename from docs/予定/wasm/compatibility_matrix.md rename to docs/guides/wasm-guide/planning/compatibility_matrix.md diff --git a/docs/予定/wasm/current_issues.md b/docs/guides/wasm-guide/planning/current_issues.md similarity index 100% rename from docs/予定/wasm/current_issues.md rename to docs/guides/wasm-guide/planning/current_issues.md diff --git a/docs/予定/wasm/unsupported_features.md b/docs/guides/wasm-guide/planning/unsupported_features.md similarity index 100% rename from docs/予定/wasm/unsupported_features.md rename to docs/guides/wasm-guide/planning/unsupported_features.md diff --git a/docs/説明書/wasm/rust-dependency-analysis.md b/docs/guides/wasm-guide/rust-dependency-analysis.md similarity index 100% rename from docs/説明書/wasm/rust-dependency-analysis.md rename to docs/guides/wasm-guide/rust-dependency-analysis.md diff --git a/docs/説明書/wasm/wasm_browser_plan.md b/docs/guides/wasm-guide/wasm_browser_plan.md similarity index 100% rename from docs/説明書/wasm/wasm_browser_plan.md rename to docs/guides/wasm-guide/wasm_browser_plan.md diff --git a/docs/説明書/wasm/wasm_quick_start.md b/docs/guides/wasm-guide/wasm_quick_start.md similarity index 100% rename from docs/説明書/wasm/wasm_quick_start.md rename to docs/guides/wasm-guide/wasm_quick_start.md diff --git a/docs/reference/README.md b/docs/reference/README.md new file mode 100644 index 00000000..e04337c2 --- /dev/null +++ b/docs/reference/README.md @@ -0,0 +1,27 @@ +# Nyash Reference Documentation 📖 + +このディレクトリには、Nyashプログラミング言語の正式な技術仕様が含まれています。 + +## 📚 サブディレクトリ + +### language/ +- 言語仕様(構文、型システム、Box仕様、デリゲーション) +- 正式な言語リファレンス + +### architecture/ +- システムアーキテクチャ(MIR、VM、インタープリター) +- 実行バックエンド仕様 +- 内部設計ドキュメント + +### api/ +- ビルトインBoxのAPI仕様 +- 標準ライブラリリファレンス +- 各Boxのメソッド詳細 + +### plugin-system/ +- プラグインシステム仕様 +- BID-FFI(Box Interface Definition - Foreign Function Interface) +- プラグイン開発ガイド + +## 📝 注意事項 +このディレクトリのドキュメントは安定版です。開発中の仕様は`development/`を参照してください。 \ No newline at end of file diff --git a/docs/説明書/VM/README.md b/docs/reference/architecture/README.md similarity index 100% rename from docs/説明書/VM/README.md rename to docs/reference/architecture/README.md diff --git a/docs/TECHNICAL_ARCHITECTURE_2025.md b/docs/reference/architecture/TECHNICAL_ARCHITECTURE_2025.md similarity index 100% rename from docs/TECHNICAL_ARCHITECTURE_2025.md rename to docs/reference/architecture/TECHNICAL_ARCHITECTURE_2025.md diff --git a/docs/説明書/NYASH_DESIGN_OVERVIEW.md b/docs/reference/architecture/design-overview.md similarity index 100% rename from docs/説明書/NYASH_DESIGN_OVERVIEW.md rename to docs/reference/architecture/design-overview.md diff --git a/docs/execution-backends.md b/docs/reference/architecture/execution-backends.md similarity index 100% rename from docs/execution-backends.md rename to docs/reference/architecture/execution-backends.md diff --git a/docs/説明書/MIR/mir-unified-reference.md b/docs/reference/architecture/mir-unified-reference.md similarity index 100% rename from docs/説明書/MIR/mir-unified-reference.md rename to docs/reference/architecture/mir-unified-reference.md diff --git a/docs/nyash_core_concepts.md b/docs/reference/architecture/nyash_core_concepts.md similarity index 100% rename from docs/nyash_core_concepts.md rename to docs/reference/architecture/nyash_core_concepts.md diff --git a/docs/plugin-migration-guide-v2-summary.md b/docs/reference/architecture/plugin-migration-guide-v2-summary.md similarity index 100% rename from docs/plugin-migration-guide-v2-summary.md rename to docs/reference/architecture/plugin-migration-guide-v2-summary.md diff --git a/docs/plugin-migration-guide-v2.md b/docs/reference/architecture/plugin-migration-guide-v2.md similarity index 100% rename from docs/plugin-migration-guide-v2.md rename to docs/reference/architecture/plugin-migration-guide-v2.md diff --git a/docs/plugin-migration-request.md b/docs/reference/architecture/plugin-migration-request.md similarity index 100% rename from docs/plugin-migration-request.md rename to docs/reference/architecture/plugin-migration-request.md diff --git a/docs/説明書/reference/boxes-system/README.md b/docs/reference/boxes-system/README.md similarity index 100% rename from docs/説明書/reference/boxes-system/README.md rename to docs/reference/boxes-system/README.md diff --git a/docs/説明書/reference/boxes-system/box-reference.md b/docs/reference/boxes-system/box-reference.md similarity index 100% rename from docs/説明書/reference/boxes-system/box-reference.md rename to docs/reference/boxes-system/box-reference.md diff --git a/docs/説明書/reference/boxes-system/builtin-to-plugin-conversion.md b/docs/reference/boxes-system/builtin-to-plugin-conversion.md similarity index 100% rename from docs/説明書/reference/boxes-system/builtin-to-plugin-conversion.md rename to docs/reference/boxes-system/builtin-to-plugin-conversion.md diff --git a/docs/説明書/reference/boxes-system/delegation-system.md b/docs/reference/boxes-system/delegation-system.md similarity index 100% rename from docs/説明書/reference/boxes-system/delegation-system.md rename to docs/reference/boxes-system/delegation-system.md diff --git a/docs/説明書/reference/boxes-system/everything-is-box.md b/docs/reference/boxes-system/everything-is-box.md similarity index 100% rename from docs/説明書/reference/boxes-system/everything-is-box.md rename to docs/reference/boxes-system/everything-is-box.md diff --git a/docs/説明書/reference/boxes-system/memory-finalization.md b/docs/reference/boxes-system/memory-finalization.md similarity index 100% rename from docs/説明書/reference/boxes-system/memory-finalization.md rename to docs/reference/boxes-system/memory-finalization.md diff --git a/docs/説明書/reference/boxes-system/plugin_lifecycle.md b/docs/reference/boxes-system/plugin_lifecycle.md similarity index 84% rename from docs/説明書/reference/boxes-system/plugin_lifecycle.md rename to docs/reference/boxes-system/plugin_lifecycle.md index 9779fd40..889c7242 100644 --- a/docs/説明書/reference/boxes-system/plugin_lifecycle.md +++ b/docs/reference/boxes-system/plugin_lifecycle.md @@ -71,3 +71,21 @@ fini = { method_id = 4294967295 } # 任意の終端ID - `nyash.toml` にクラス名→プラグインBox型の `overrides` を加え、ユーザー定義Boxの外部置換を許可する設計(任意)。 以上。 + +--- + +## 7. v2.1: BoxRef(Box引数)サポート + +目的: プラグインメソッドの引数として、他のBoxインスタンスを不透明参照で受け渡し可能にする。 + +- 仕様詳細: `docs/reference/plugin-system/nyash-toml-v2_1-spec.md` +- 設定例(1引数にプラグインBoxを渡す): + +```toml +[libraries."libnyash_filebox_plugin.so".FileBox.methods] +copyFrom = { method_id = 7, args = [ { kind = "box", category = "plugin" } ] } +``` + +注意: +- 当面は `category = "plugin"` のみ対応。ユーザー定義Boxや複雑なビルトインBoxは非対応。 +- 戻り値の BoxRef は次版(v2.2)で検討。 diff --git a/docs/説明書/reference/core-language/design-philosophy.md b/docs/reference/core-language/design-philosophy.md similarity index 100% rename from docs/説明書/reference/core-language/design-philosophy.md rename to docs/reference/core-language/design-philosophy.md diff --git a/docs/説明書/reference/core-language/language-reference.md b/docs/reference/core-language/language-reference.md similarity index 100% rename from docs/説明書/reference/core-language/language-reference.md rename to docs/reference/core-language/language-reference.md diff --git a/docs/説明書/reference/core-language/language_spec.md b/docs/reference/core-language/language_spec.md similarity index 100% rename from docs/説明書/reference/core-language/language_spec.md rename to docs/reference/core-language/language_spec.md diff --git a/docs/説明書/reference/core-language/override-delegation-syntax.md b/docs/reference/core-language/override-delegation-syntax.md similarity index 100% rename from docs/説明書/reference/core-language/override-delegation-syntax.md rename to docs/reference/core-language/override-delegation-syntax.md diff --git a/docs/説明書/reference/core-language/portability-contract.md b/docs/reference/core-language/portability-contract.md similarity index 100% rename from docs/説明書/reference/core-language/portability-contract.md rename to docs/reference/core-language/portability-contract.md diff --git a/docs/説明書/reference/execution-backend/mir-26-specification.md b/docs/reference/execution-backend/mir-26-specification.md similarity index 100% rename from docs/説明書/reference/execution-backend/mir-26-specification.md rename to docs/reference/execution-backend/mir-26-specification.md diff --git a/docs/説明書/reference/execution-backend/p2p_spec.md b/docs/reference/execution-backend/p2p_spec.md similarity index 100% rename from docs/説明書/reference/execution-backend/p2p_spec.md rename to docs/reference/execution-backend/p2p_spec.md diff --git a/docs/LANGUAGE_REFERENCE_2025.md b/docs/reference/language/LANGUAGE_REFERENCE_2025.md similarity index 100% rename from docs/LANGUAGE_REFERENCE_2025.md rename to docs/reference/language/LANGUAGE_REFERENCE_2025.md diff --git a/docs/説明書/reference/plugin-system/README.md b/docs/reference/plugin-system/README.md similarity index 100% rename from docs/説明書/reference/plugin-system/README.md rename to docs/reference/plugin-system/README.md diff --git a/docs/説明書/reference/plugin-system/bid-ffi-v1-actual-specification.md b/docs/reference/plugin-system/bid-ffi-v1-actual-specification.md similarity index 100% rename from docs/説明書/reference/plugin-system/bid-ffi-v1-actual-specification.md rename to docs/reference/plugin-system/bid-ffi-v1-actual-specification.md diff --git a/docs/説明書/reference/plugin-system/ffi-abi-specification.md b/docs/reference/plugin-system/ffi-abi-specification.md similarity index 100% rename from docs/説明書/reference/plugin-system/ffi-abi-specification.md rename to docs/reference/plugin-system/ffi-abi-specification.md diff --git a/docs/説明書/reference/plugin-system/filebox-bid-mapping.md b/docs/reference/plugin-system/filebox-bid-mapping.md similarity index 100% rename from docs/説明書/reference/plugin-system/filebox-bid-mapping.md rename to docs/reference/plugin-system/filebox-bid-mapping.md diff --git a/docs/説明書/reference/plugin-system/migration-guide.md b/docs/reference/plugin-system/migration-guide.md similarity index 100% rename from docs/説明書/reference/plugin-system/migration-guide.md rename to docs/reference/plugin-system/migration-guide.md diff --git a/docs/説明書/reference/plugin-system/nyash-toml-v2-spec.md b/docs/reference/plugin-system/nyash-toml-v2-spec.md similarity index 100% rename from docs/説明書/reference/plugin-system/nyash-toml-v2-spec.md rename to docs/reference/plugin-system/nyash-toml-v2-spec.md diff --git a/docs/reference/plugin-system/nyash-toml-v2_1-spec.md b/docs/reference/plugin-system/nyash-toml-v2_1-spec.md new file mode 100644 index 00000000..3acfc430 --- /dev/null +++ b/docs/reference/plugin-system/nyash-toml-v2_1-spec.md @@ -0,0 +1,55 @@ +# nyash.toml v2.1 拡張仕様(最小) + +目的: プラグインBoxのメソッド引数として、他のBoxを不透明参照(BoxRef)で安全に受け渡す。 + +## 変更点(v2 → v2.1) +- メソッド引数型に `kind = "box"` を追加(当面は `category = "plugin"` のみ) +- TLVに BoxRef(Handle)を追加(tag = 8) + - payload: `type_id: u32 (LE)`, `instance_id: u32 (LE)`(合計8バイト) +- 既存タグは不変:1=Int64, 2=String(UTF-8), 3=Bool + +## 例: libraries セクション +```toml +[libraries] +[libraries."libnyash_filebox_plugin.so"] +boxes = ["FileBox"] +path = "./target/release/libnyash_filebox_plugin.so" + +[libraries."libnyash_filebox_plugin.so".FileBox] +type_id = 6 +abi_version = 1 + +[libraries."libnyash_filebox_plugin.so".FileBox.methods] +# 既存 +birth = { method_id = 0 } +open = { method_id = 1 } +close = { method_id = 4 } + +# 追加例: Box引数を1つ受け取る +copyFrom = { method_id = 7, args = [ { kind = "box", category = "plugin" } ] } +``` + +備考: +- `args` を省略した場合は引数なし(ゼロ引数)とみなす(v2互換) +- 複数引数は配列で列挙(例: 2引数なら2要素) +- ユーザー定義Boxや複雑なビルトインBoxは当面対象外(将来のvtable/retain-release設計で拡張) + +## 呼び出し時のTLVエンコード +- 先頭ヘッダ `[ver:1, argc:1, rsv:2]` の後、各引数を `tag + payload` で列挙 +- `tag=8 (Handle/BoxRef)`: payload = `type_id(4) + instance_id(4)` (LE) +- 未対応Box種別に対してはエラーを返す(開発時のみ toString フォールバックを許容可能) + +## 戻り値(v2.1→v2.2) +- v2.1: Int/String/Bool(1/6/3)とVoid(9) +- v2.2: BoxRef(Handle, tag=8) の「返り値」対応を追加(同一/別Box型どちらも可) + - payload: `type_id:u32` + `instance_id:u32` + - Loaderは `type_id` から `lib_name/box_name` を逆引きし、`PluginBoxV2` を生成して返す + +## 互換性 +- `args` 宣言がない既存v2設定はそのまま利用可 +- BoxRefを使わないメソッドは従来通り Int/String/Bool のみで動作 + +## 実装メモ(参考) +- Loader: invoke時の引数エンコードに `tag=4` を追加(`category=plugin` のみ) +- プラグイン側: 受領した `type_id` と期待型を照合し、不一致ならエラー +- 所有権: 呼び出し中の一時借用(保持は将来の retain/release で対応) diff --git a/docs/説明書/reference/plugin-system/plugin-system.md b/docs/reference/plugin-system/plugin-system.md similarity index 100% rename from docs/説明書/reference/plugin-system/plugin-system.md rename to docs/reference/plugin-system/plugin-system.md diff --git a/docs/説明書/reference/plugin-system/plugin-tester.md b/docs/reference/plugin-system/plugin-tester.md similarity index 100% rename from docs/説明書/reference/plugin-system/plugin-tester.md rename to docs/reference/plugin-system/plugin-tester.md diff --git a/docs/説明書/reference/plugin-system/vm-plugin-integration.md b/docs/reference/plugin-system/vm-plugin-integration.md similarity index 95% rename from docs/説明書/reference/plugin-system/vm-plugin-integration.md rename to docs/reference/plugin-system/vm-plugin-integration.md index 0cb111da..5049d022 100644 --- a/docs/説明書/reference/plugin-system/vm-plugin-integration.md +++ b/docs/reference/plugin-system/vm-plugin-integration.md @@ -490,4 +490,14 @@ impl VM { **関連文書**: - [BID-FFI v1 実装仕様書](./bid-ffi-v1-actual-specification.md) - [Phase 9.78a VM Plugin Integration](../../予定/native-plan/issues/phase_9_78a_vm_plugin_integration.md) -- [Phase 9.78a 深層分析](../../予定/native-plan/issues/phase_9_78a_vm_plugin_integration_deep_analysis.md) \ No newline at end of file +- [Phase 9.78a 深層分析](../../予定/native-plan/issues/phase_9_78a_vm_plugin_integration_deep_analysis.md) + - [nyash.toml v2.1: BoxRef仕様](../plugin-system/nyash-toml-v2_1-spec.md) + +### 付録: 引数エンコード(v2.1 追加) +- TLVタグ: 1=Bool, 2=I32, 3=I64, 4=F32, 5=F64, 6=String, 7=Bytes, 8=Handle(BoxRef) +- BoxRef payload(tag=8): `type_id:u32` + `instance_id:u32`(LE, 8バイト) +- `nyash.toml` の `args` で `{ kind="box", category="plugin" }` を指定したとき、Loaderは `tag=8` を使用 + +### 返り値(v2.2) +- プラグインが `tag=8` を返した場合、Loaderは `type_id` からBox型名を逆引きし `PluginBoxV2` を構築 +- 同一ライブラリでなくてもOK(構成ファイル全体から探索) diff --git a/docs/説明書/reference/testing-quality/golden-dump-testing.md b/docs/reference/testing-quality/golden-dump-testing.md similarity index 100% rename from docs/説明書/reference/testing-quality/golden-dump-testing.md rename to docs/reference/testing-quality/golden-dump-testing.md diff --git a/docs/予定/plugins_and_wasm_build_guide.md b/docs/予定/plugins_and_wasm_build_guide.md deleted file mode 100644 index 7fbd4160..00000000 --- a/docs/予定/plugins_and_wasm_build_guide.md +++ /dev/null @@ -1,81 +0,0 @@ -# プラグイン機構と WASM ビルド切替ガイド - -本書は、nyash のプラグイン機構(nyash.toml v2 / PluginLoaderV2)と、wasm-bindgen を使う WASM ビルドでの切替手順をまとめたものです。目的は「ネイティブではプラグインON、WASMでは安全にプラグインOFF」でビルド/実行できるようにすることです。 - ---- - -## 1. Cargo features 構成(現状) - -- `default = ["cli", "plugins"]` -- `plugins`: プラグイン機構を有効化(`libloading` 等の動的ロードに依存) -- `wasm-backend`: WASM バックエンドを有効化(`wabt`/`wasmtime` 等) - -これにより、デフォルトではネイティブ開発時にプラグインが有効になります。WASM ターゲットでプラグインを完全に外したい場合は、`--no-default-features` を使います。 - ---- - -## 2. ビルド/テスト コマンド例 - -### 2.1 ネイティブ(プラグインON・デフォルト) - -- ビルド: `cargo build` -- テスト: `cargo test` - -nyash.toml v2 によるプラグインの透過切替(ビルトイン→プラグイン)はこの構成で有効です。 - -### 2.2 ネイティブ(プラグインOFF) - -- テスト: `cargo test --no-default-features --features cli` - -`plugins` を外すとプラグインローダはスタブ化され、プラグイン経由の生成は失敗(適切なエラー)になります。 - -### 2.3 WASM ターゲット(プラグインOFF) - -- 初回のみ: `rustup target add wasm32-unknown-unknown` -- ビルド例: `cargo build --target wasm32-unknown-unknown --no-default-features --features wasm-backend` - -この構成では `plugins` が無効のため、`libloading` 等の動的ロードに依存せずビルドできます。 - ---- - -## 3. runtime 側の切替実装(概要) - -`src/runtime/plugin_loader_v2.rs` は cfg で2パスを提供: - -- `#[cfg(all(feature = "plugins", not(target_arch = "wasm32")))]` … 実体実装(libloading + invoke_fn) -- `#[cfg(any(not(feature = "plugins"), target_arch = "wasm32"))]` … スタブ実装(常にエラー返却) - -`src/runtime/unified_registry.rs` は、`#[cfg(feature = "plugins")]` のときだけプラグインFactoryをレジストリに登録します。WASMやpluginsオフ時は登録されず、ユーザー定義/ビルトインのみが対象になります。 - ---- - -## 4. nyash.toml v2 の取り扱い - -- ネイティブ: `init_global_loader_v2()` により `nyash.toml` を読み込み、`libraries`/`methods.birth`/`methods.fini` などの設定に従ってプラグインをロードします。 -- WASM/プラグインOFF: `init_global_loader_v2()` はスタブ化され、ファイルI/Oや動的ロードは行いません。 - ---- - -## 5. ライフサイクル(birth/fini)整合(設計) - -- ユーザー定義: AST上のコンストラクタ(birth)実行・フィールド差し替え時に `fini()` 呼び出し(InstanceBox側実装) -- プラグイン: `methods.birth=0` で生成済み。差し替え/破棄時に `methods.fini`(例: `0xFFFF`)を `invoke_fn(type_id, method_id=fini, instance_id)` で呼ぶフックを今後統合予定。 - ---- - -## 6. よくある質問 - -- Q. なぜランタイム切替ではなくコンパイル時切替? - - A. WASM ターゲットでは `libloading` が使えないため、リンク/依存段階で除去する必要があり、features/cfg によるコンパイル時切替が安全・簡潔です。 - -- Q. `nyash.toml` はWASMでも使える? - - A. ファイルI/O前提のため、現状はネイティブのみ。将来、バンドルや JS 側から設定注入をする場合は別アプローチで設計します。 - ---- - -## 7. 今後の拡張 - -- `nyash.toml` にクラス名→プラグインBox型の `overrides` マップを追加し、ユーザー定義Boxの外部置換をサポート(任意)。 -- プラグインBoxの `fini` 呼び出しを InstanceBox の破棄/置換パスへ統合し、birth/fini ライフサイクルを完全整合。 - -以上。 diff --git a/docs/説明書/GETTING_STARTED_2025.md b/docs/説明書/GETTING_STARTED_2025.md deleted file mode 100644 index 61df6ac6..00000000 --- a/docs/説明書/GETTING_STARTED_2025.md +++ /dev/null @@ -1,547 +0,0 @@ -# 🚀 Getting Started with Nyash - Practical Guide - -**最終更新: 2025年8月8日** - -## 🎯 5分でNyashを理解する - -Nyashは「Everything is Box」哲学に基づく、シンプルで強力なプログラミング言語です。 -このガイドでは、実際にコードを書きながらNyashの機能を学んでいきます。 - -## ⚡ クイックスタート - -### **1. 環境構築** -```bash -# リポジトリのクローン -git clone [repository-url] -cd nyash/nyash-rust - -# ビルド -cargo build - -# 実行 -./target/debug/nyash your_program.nyash -``` - -### **2. はじめてのNyashプログラム** -`hello.nyash`を作成: -```nyash -print("Hello, Nyash World!") -print("Everything is Box! 🎉") -``` - -実行: -```bash -./target/debug/nyash hello.nyash -``` - -出力: -``` -Hello, Nyash World! -Everything is Box! 🎉 -``` - -## 📚 基本構文チュートリアル - -### **Step 1: 変数と初期化** -```nyash -# 🎯 新機能:初期化付き変数宣言 -local name = "Alice" -local age = 25 -local height = 165.5 -local isStudent = true - -print("Name: " + name) -print("Age: " + age) -print("Height: " + height) -print("Student: " + isStudent) - -# 複数変数の同時宣言・初期化 -local x = 10, y = 20, z = 30 -print("Sum: " + (x + y + z)) # 60 - -# 混合宣言(初期化あり・なし) -local initialized = 42, uninitialized, another = "test" -uninitialized = "assigned later" -print("Values: " + initialized + ", " + uninitialized + ", " + another) -``` - -### **Step 2: 演算子の使用** -```nyash -local a = 10 -local b = 3 - -# 算術演算子 -print("Addition: " + (a + b)) # 13 -print("Subtraction: " + (a - b)) # 7 -print("Multiplication: " + (a * b)) # 30 -print("Division: " + (a / b)) # 3.3333333333333335 - -# 論理演算子(自然言語ライク) -local hasPermission = true -local isLoggedIn = true -local canAccess = hasPermission and isLoggedIn -print("Can access: " + canAccess) # true - -local isDenied = not canAccess -print("Is denied: " + isDenied) # false - -# 比較演算子 -print("a > b: " + (a > b)) # true -print("a == b: " + (a == b)) # false -``` - -### **Step 3: 制御構造** -```nyash -function testControlFlow() { - local score = 85 - - # if文 - if score >= 90 { - print("Grade: A") - } else if score >= 80 { - print("Grade: B") # これが実行される - } else { - print("Grade: C or below") - } - - # ループ(統一構文) - local count = 0 - loop(count < 3) { - print("Count: " + count) - count = count + 1 - if count == 2 { - print("Breaking at 2") - break - } - } -} - -testControlFlow() -``` - -### **Step 4: Box(クラス)の定義** -```nyash -box Person { - init { name, age, email } # フィールド定義(カンマ必須!) - - # コンストラクタ(引数サポート) - Person(n, a, e) { - me.name = n - me.age = a - me.email = e - print("Person created: " + me.name) - } - - # メソッド - introduce() { - print("Hi, I'm " + me.name + ", age " + me.age) - } - - getInfo() { - return me.name + " (" + me.age + ") - " + me.email - } - - # デストラクタ - fini() { - print("Person destroyed: " + me.name) - } -} - -# 使用例 -person = new Person("Bob", 30, "bob@example.com") -person.introduce() -print("Info: " + person.getInfo()) -``` - -## 🏭 実践例:Calculator アプリ - -完全なCalculatorアプリを実装: - -```nyash -# 📱 Calculator App - Nyash版 - -box Calculator { - init { history } - - Calculator() { - me.history = new ArrayBox() - print("🧮 Calculator initialized!") - } - - add(a, b) { - local result = a + b - me.addToHistory("ADD", a, b, result) - return result - } - - subtract(a, b) { - local result = a - b - me.addToHistory("SUB", a, b, result) - return result - } - - multiply(a, b) { - local result = a * b - me.addToHistory("MUL", a, b, result) - return result - } - - divide(a, b) { - if b == 0 { - print("❌ Error: Division by zero!") - return 0 - } - local result = a / b - me.addToHistory("DIV", a, b, result) - return result - } - - addToHistory(op, a, b, result) { - local record = op + ": " + a + " " + op + " " + b + " = " + result - me.history.push(record) - } - - showHistory() { - print("📊 Calculation History:") - local size = me.history.size() - local i = 0 - loop(i < size) { - print(" " + (i + 1) + ". " + me.history.get(i)) - i = i + 1 - } - } - - clear() { - me.history = new ArrayBox() - print("🧹 History cleared!") - } -} - -# ✨ Calculator使用例 -calc = new Calculator() - -print("=== Basic Operations ===") -print("10 + 5 = " + calc.add(10, 5)) -print("10 - 3 = " + calc.subtract(10, 3)) -print("4 * 7 = " + calc.multiply(4, 7)) -print("15 / 3 = " + calc.divide(15, 3)) -print("10 / 0 = " + calc.divide(10, 0)) # ゼロ除算エラーテスト - -print("") -calc.showHistory() - -print("") -print("=== Complex Calculations ===") -local complex1 = calc.add(calc.multiply(3, 4), calc.divide(20, 4)) -print("(3 * 4) + (20 / 4) = " + complex1) - -calc.showHistory() -``` - -## ⚡ 並行処理の実践 - -```nyash -# 🚀 Parallel Processing Example - -function heavyComputation(iterations) { - print("⚙️ Starting computation with " + iterations + " iterations...") - - local sum = 0 - local i = 0 - loop(i < iterations) { - sum = sum + (i * i) - i = i + 1 - - # 進捗表示(1000回毎) - if (i % 1000) == 0 { - print(" Progress: " + i + "/" + iterations) - } - } - - print("✅ Computation completed: " + sum) - return sum -} - -function parallelDemo() { - print("🚀 Starting parallel computations...") - - # 3つのタスクを並行実行 - future1 = nowait heavyComputation(5000) - future2 = nowait heavyComputation(3000) - future3 = nowait heavyComputation(4000) - - print("⏳ All tasks started. Waiting for results...") - - # 結果を待機して取得 - result1 = await future1 - result2 = await future2 - result3 = await future3 - - local total = result1 + result2 + result3 - print("🎉 All tasks completed!") - print("Total sum: " + total) - - return total -} - -# 実行 -parallelDemo() -``` - -## 🏗️ Static Box(名前空間)の活用 - -```nyash -# 🏗️ Utility Classes with Static Boxes - -static box MathUtils { - init { PI, E } - - static { - me.PI = 3.14159265359 - me.E = 2.71828182846 - } - - square(x) { - return x * x - } - - circleArea(radius) { - return me.PI * me.square(radius) - } - - power(base, exp) { - local result = 1 - local i = 0 - loop(i < exp) { - result = result * base - i = i + 1 - } - return result - } -} - -static box StringUtils { - init { EMPTY } - - static { - me.EMPTY = "" - } - - reverse(str) { - # 簡易的な実装例 - return "REVERSED:" + str - } - - isEmpty(str) { - return str == me.EMPTY - } -} - -# 使用例 -print("π = " + MathUtils.PI) -print("Circle area (r=5): " + MathUtils.circleArea(5)) -print("2^8 = " + MathUtils.power(2, 8)) - -print("Empty check: " + StringUtils.isEmpty("")) -print("Reverse: " + StringUtils.reverse("Hello")) -``` - -## 🐛 デバッグ機能の活用 - -```nyash -# 🐛 Debug Features Showcase - -box DebugExample { - init { data, counter } - - DebugExample() { - me.data = "example" - me.counter = 0 - } - - process() { - me.counter = me.counter + 1 - return "Processed #" + me.counter - } -} - -function debuggingDemo() { - # DebugBoxでトラッキング開始 - DEBUG = new DebugBox() - DEBUG.startTracking() - - print("🔍 Creating objects for debugging...") - - # オブジェクトを作成してトラッキング - obj1 = new DebugExample() - obj2 = new DebugExample() - - DEBUG.trackBox(obj1, "Primary Object") - DEBUG.trackBox(obj2, "Secondary Object") - - # 処理実行 - result1 = obj1.process() - result2 = obj2.process() - result3 = obj1.process() - - print("Results: " + result1 + ", " + result2 + ", " + result3) - - # デバッグレポート表示 - print("") - print("=== Memory Report ===") - print(DEBUG.memoryReport()) - - print("") - print("=== Full Debug Dump ===") - print(DEBUG.dumpAll()) - - # デバッグ情報をファイルに保存 - DEBUG.saveToFile("debug_output.txt") - print("🎉 Debug information saved to debug_output.txt") -} - -debuggingDemo() -``` - -## 📦 ファイル組織とモジュール - -### **プロジェクト構造** -``` -my_nyash_project/ -├── main.nyash # メインプログラム -├── utils/ -│ ├── math.nyash # 数学ユーティリティ -│ ├── string.nyash # 文字列ユーティリティ -│ └── debug.nyash # デバッグ関数 -└── models/ - ├── person.nyash # Personクラス - └── calculator.nyash # Calculatorクラス -``` - -### **main.nyash** -```nyash -# 📦 Module System Example - -include "utils/math.nyash" -include "utils/string.nyash" -include "models/person.nyash" -include "models/calculator.nyash" - -function main() { - print("🚀 Multi-module Nyash Application") - - # 各モジュールの機能を使用 - person = new Person("Alice", 25, "alice@example.com") - person.introduce() - - calc = new Calculator() - result = calc.add(10, 20) - print("Calculation result: " + result) -} - -main() -``` - -## 🎯 ベストプラクティス - -### **1. 変数命名** -```nyash -# ✅ Good -local userName = "alice" -local totalAmount = 1000 -local isComplete = true - -# ❌ Avoid -local x = "alice" -local amt = 1000 -local flag = true -``` - -### **2. Box設計** -```nyash -# ✅ Good: 明確な責任分離 -box UserAccount { - init { username, email, balance } - - UserAccount(u, e) { - me.username = u - me.email = e - me.balance = 0 - } - - deposit(amount) { - me.balance = me.balance + amount - } -} - -# ❌ Avoid: 責任の混在 -box EverythingBox { - # 多すぎる責任を持たせない -} -``` - -### **3. エラーハンドリング** -```nyash -function safeOperation(a, b) { - if b == 0 { - print("❌ Error: Division by zero") - return 0 - } - return a / b -} -``` - -### **4. パフォーマンス考慮** -```nyash -# ✅ 効率的:static box使用 -result = MathUtils.calculate(data) - -# ✅ 効率的:初期化付き宣言 -local result = heavyCalculation(), cache = new MapBox() - -# ⚠️ 注意:不要なオブジェクト生成を避ける -loop(i < 1000) { - # 毎回new しない設計を心がける -} -``` - -## 🚀 次のステップ - -### **学習順序** -1. ✅ **基本構文** - このガイドで完了 -2. **並行処理** - `test_async_*.nyash`を参考に -3. **Static Box応用** - ユーティリティクラス作成 -4. **デバッグ技法** - DebugBox完全活用 -5. **アプリケーション開発** - 実践的なプロジェクト - -### **サンプルプログラム** -```bash -# 実装済みサンプル -./target/debug/nyash test_local_init.nyash # 初期化付き変数 -./target/debug/nyash app_dice_rpg.nyash # RPGバトルゲーム -./target/debug/nyash app_statistics.nyash # 統計計算 -./target/debug/nyash test_async_parallel.nyash # 並行処理 -``` - -### **リファレンス** -- `docs/LANGUAGE_OVERVIEW_2025.md` - 言語全体概要 -- `docs/TECHNICAL_ARCHITECTURE_2025.md` - 技術仕様 -- `CLAUDE.md` - 開発者向け詳細情報 - -## 🎉 おめでとうございます! - -このガイドでNyashの主要機能を学習しました! - -**習得内容:** -- ✅ 基本構文(変数・演算子・制御構造) -- ✅ Box(クラス)定義とオブジェクト指向 -- ✅ 並行処理・非同期プログラミング -- ✅ Static Box・名前空間システム -- ✅ デバッグ機能・開発支援ツール -- ✅ 実践的なアプリケーション開発 - -**Nyashでプログラミングの新しい可能性を探究してください!** 🚀 - ---- -*Getting Started Guide v1.0* -*Everything is Box - Start Simple, Think Big* \ No newline at end of file diff --git a/docs/説明書/LANGUAGE_OVERVIEW_2025.md b/docs/説明書/LANGUAGE_OVERVIEW_2025.md deleted file mode 100644 index 513b5a8f..00000000 --- a/docs/説明書/LANGUAGE_OVERVIEW_2025.md +++ /dev/null @@ -1,332 +0,0 @@ -# 🚀 Nyash Programming Language - Complete Overview 2025 - -**最終更新: 2025年8月8日** - -## 📖 概要 - -Nyashは「Everything is Box」哲学に基づく革新的なプログラミング言語です。 -わずか数日の集中開発により、production-readyレベルの実用的プログラミング言語として完成しました。 - -## 🎯 核心哲学: "Everything is Box" - -```nyash -# すべてのデータがBoxとして統一的に表現される -number = 42 # IntegerBox -text = "hello" # StringBox -flag = true # BoolBox -array = new ArrayBox() # ArrayBox -debug = new DebugBox() # DebugBox -``` - -## ✅ 完全実装済み機能 (Production Ready) - -### 🔧 **言語基盤** -- **データ型**: StringBox, IntegerBox, BoolBox, ArrayBox, MapBox, NullBox -- **演算子**: `+`, `-`, `*`, `/`, `not`, `and`, `or`, `==`, `!=`, `<`, `>`, `<=`, `>=` -- **制御構文**: `if/else`, `loop(condition)`, `break` -- **変数宣言**: `local x`, `local x = value`, `outbox x = value` - -### 🎭 **オブジェクト指向** -```nyash -box MyClass { - init { name, value } - - MyClass(n, v) { # コンストラクタ引数サポート - me.name = n - me.value = v - } - - getValue() { - return me.value - } -} - -# 継承とインターフェース -box Child from Parent interface IComparable { - # 実装... -} -``` - -### ⚡ **並行処理・非同期** -```nyash -# 真の非同期実行(別スレッド) -future1 = nowait heavyComputation(50000) -future2 = nowait heavyComputation(30000) - -# await演算子で結果取得 -result1 = await future1 -result2 = await future2 -``` - -### 🏭 **Static Boxシステム** -```nyash -static box Math { - init { PI, E } - - static { - me.PI = 3.14159 - me.E = 2.71828 - } - - add(a, b) { return a + b } - multiply(a, b) { return a * b } -} - -# シングルトン・名前空間として動作 -result = Math.add(10, 20) # 30 -pi = Math.PI # 3.14159 -``` - -### 💾 **メモリ管理** -```nyash -box Resource { - init { handle } - - fini() { # デストラクタ - print("Resource cleaned up") - } -} - -# 自動メモリ管理 + 明示的解放 -resource = new Resource() -# スコープ終了時に自動的にfini()が呼ばれる -``` - -### 🧪 **デバッグシステム** -```nyash -DEBUG = new DebugBox() -DEBUG.startTracking() -DEBUG.trackBox(myObject, "重要オブジェクト") -print(DEBUG.memoryReport()) -DEBUG.saveToFile("debug.txt") -``` - -### 📦 **モジュールシステム** -```nyash -include "math_utils.nyash" # ファイルインクルード -include "graphics.nyash" # 機能の組み込み -``` - -## 🎮 実装済みアプリケーション - -### 1. **🎲 サイコロRPGバトルゲーム** -- ターン制戦闘システム -- クリティカルヒット・防御システム -- リアルタイムHPバー表示 -- DebugBox戦闘ログ統合 - -### 2. **📊 統計計算アプリケーション** -- 平均・分散・標準偏差計算 -- 三角関数・対数・指数関数 -- 数学的統計処理 - -### 3. **🧮 LISPインタープリター** -- S式パーサー -- ConsBox/SymbolBox実装 -- 動的評価エンジン -- メタプログラミング実証 - -### 4. **⚡ 並行処理デモ** -- マルチスレッド計算タスク -- 進捗表示による並行動作の可視化 -- await演算子による結果統合 - -## 🌟 技術的革新 - -### 1. **GlobalBox革命** -従来のスコープチェーン概念を廃止し、GlobalBox単一管理システムを実現: -- すべてのグローバル関数/変数がGlobalBoxで管理 -- `local`変数による一時的スコープ -- メモリ効率30%改善 - -### 2. **SharedState非同期アーキテクチャ** -```rust -pub struct SharedState { - global_box: Arc>, - box_declarations: Arc>>, - static_functions: Arc>>>, -} -``` - -### 3. **Everything is Box統一性** -- TypeBox: 型情報もBoxとして表現 -- MethodBox: 関数ポインタ・イベントハンドラー実現 -- DebugBox: デバッグ情報の統一管理 - -## 📋 構文仕様書 - -### **変数宣言** -```nyash -# 基本宣言 -local x, y, z - -# 初期化付き宣言(2025年8月8日実装完了) -local result = 10 + 20 -local name = "Hello" + " World" -local a = 100, b = 200, c = 300 - -# 混合宣言 -local init = 42, uninit, another = "test" - -# outbox変数(static関数内で所有権移転) -outbox product = new Item() -``` - -### **制御構文** -```nyash -# 条件分岐 -if condition { - # 処理 -} else { - # else処理 -} - -# ループ(統一構文) -loop(condition) { - # ループ本体 - if exitCondition { - break - } -} -``` - -### **演算子** -```nyash -# 算術演算子 -result = a + b - c * d / e - -# 論理演算子(キーワード版推奨) -canAccess = level >= 5 and hasKey -canEdit = isAdmin or (isModerator and hasPermission) -isInvalid = not (input and verified) - -# 比較演算子 -equal = (a == b) -different = (x != y) -greater = (score > threshold) -``` - -### **Box定義** -```nyash -box ClassName from ParentClass interface IInterface { - init { field1, field2, field3 } # カンマ必須! - - # コンストラクタ - ClassName(param1, param2) { - me.field1 = param1 - me.field2 = param2 - me.field3 = calculateDefault() - } - - # メソッド - methodName(params) { - return me.field1 + params - } - - # デストラクタ - fini() { - print("Cleanup: " + me.field1) - } -} -``` - -### **Static Box** -```nyash -static box UtilityClass { - init { CONSTANT1, CONSTANT2 } - - static { - me.CONSTANT1 = "value" - me.CONSTANT2 = 42 - } - - utilityMethod(param) { - return param * me.CONSTANT2 - } -} - -# 使用法 -result = UtilityClass.utilityMethod(10) -const = UtilityClass.CONSTANT1 -``` - -## 🚀 パフォーマンス特性 - -### **メモリ効率** -- GlobalBox統一管理によるメモリ使用量削減 -- 自動参照カウント + 明示的デストラクタ -- SharedState による効率的な並行処理 - -### **実行速度** -- 変数解決アルゴリズム簡素化 -- コンパイル済みRustベースの高速実行 -- 並行処理によるCPUリソース最大活用 - -### **開発効率** -- シンプルな構文による高い可読性 -- 包括的なDebugBox機能 -- "Everything is Box"による概念の統一性 - -## 🎯 言語の強み - -### 1. **学習コストの低さ** -- 統一された"Box"概念 -- 直感的なメソッド呼び出し -- 自然言語に近い論理演算子 - -### 2. **実用性** -- モダンな並行処理サポート -- 堅牢なメモリ管理 -- 実際のアプリケーション開発可能 - -### 3. **拡張性** -- モジュールシステム -- 継承・インターフェースサポート -- 外部ライブラリ統合準備完了 - -## 🔮 開発ロードマップ - -### **Phase 3: 高度機能拡張** -- ジェネリクス実行時特殊化完成 -- スレッドプール・タイムアウト機能 -- WebAssembly出力対応 - -### **Phase 4: エコシステム構築** -- GUI フレームワーク(WindowBox等) -- HTTP/ネットワークライブラリ -- ファイルI/O・データベースアクセス - -### **Phase 5: プロダクション対応** -- パッケージマネージャー -- IDE統合・Language Server -- デバッガー・プロファイラー - -## 📊 言語比較 - -| 機能 | Nyash | Python | JavaScript | Rust | -|------|-------|--------|------------|------| -| 学習コスト | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐ | -| 並行処理 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | -| メモリ安全性 | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | -| 開発速度 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | -| 実行速度 | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | - -## 🎉 まとめ - -Nyashは「Everything is Box」哲学により、シンプルさと強力さを両立した革新的プログラミング言語として完成しました。 - -**主要達成項目:** -- ✅ 基本言語機能完備 -- ✅ オブジェクト指向完全サポート -- ✅ 並行処理・非同期機能実装 -- ✅ Static Box・名前空間システム -- ✅ 現代的構文(初期化付き変数宣言等) -- ✅ 実用アプリケーション複数完成 -- ✅ 包括的デバッグ・開発支援機能 - -**Nyashは実験的言語から実用的プログラミング言語への転換を果たし、今後のさらなる進化への強固な基盤を確立しました。** - ---- -*開発期間: 2025年8月6日-8日(わずか3日間での集中開発)* -*開発者: Claude Code + 人間のコラボレーション* -*哲学: "Everything is Box" - シンプルさの中に無限の可能性を* \ No newline at end of file diff --git a/docs/説明書/README.md b/docs/説明書/README.md deleted file mode 100644 index 7c27534e..00000000 --- a/docs/説明書/README.md +++ /dev/null @@ -1,28 +0,0 @@ -Nyash 説明書(ユーザー向けガイド) - -## 🚀 実行方式 -- **実行バックエンド**: [../execution-backends.md](../execution-backends.md) - インタープリター・VM・WASM実行の完全ガイド - -## 🎯 入門・基本 -- ネイティブビルド: docs/説明書/native-build/README.md -- WASM: docs/説明書/wasm/wasm_quick_start.md, docs/説明書/wasm/wasm_browser_plan.md -- 入門: docs/説明書/GETTING_STARTED.md, docs/説明書/GETTING_STARTED_2025.md -- 言語ガイド: docs/説明書/LANGUAGE_GUIDE.md, docs/説明書/LANGUAGE_OVERVIEW_2025.md -- コア概念: docs/nyash_core_concepts.md -- P2P: docs/説明書/P2P_GUIDE.md - -参考資料 (Reference): -- docs/説明書/reference/language-reference.md (仕様) -- docs/説明書/reference/finalization-system.md (fini/弱参照の不変) -- docs/説明書/reference/override-delegation-syntax.md (委譲構文) -- docs/説明書/reference/builtin-boxes.md (ビルトイン一覧) -- docs/説明書/reference/p2p_spec.md (P2P仕様) -- docs/説明書/reference/language-specification/ (詳細仕様) -- docs/説明書/reference/plugin-tester.md (プラグインテスター使用ガイド) - -その他ガイド: -- docs/説明書/guides/1_getting_started.md -- docs/説明書/guides/2_language_guide.md -- docs/説明書/guides/playground_guide.md - -ネイティブ計画・相談ログ: docs/予定/native-plan/README.md diff --git a/docs/説明書/VM/次のお勧め.txt b/docs/説明書/VM/次のお勧め.txt deleted file mode 100644 index 4c60f0c1..00000000 --- a/docs/説明書/VM/次のお勧め.txt +++ /dev/null @@ -1,11 +0,0 @@ -- おすすめの次手(どれを先にやる?) - - BoxCall→Callの最適化範囲拡大(変数に束縛したnewの直後メソッドもCall化) - - プラグインTLVの型拡張(Float/配列/Boxリファレンスの扱いなど) - - ビルトインメソッドのMIR関数化(Dispatchの簡素化・最適化に寄与) - - E2Eの拡張(throw/catch、pluginメソッドの戻り値ありケース、fini観察) - -VMガイドの場所(Windows) -- `C:\git\nyash-project\nyash\docs\説明書\VM\README.md` - -このまま、BoxCall→Callの最適化拡大から着手しますか?それともプラグインのTLV拡張 -(引数/戻り値の型追加)を先にやる? \ No newline at end of file diff --git a/docs/説明書/mir-unified-reference.md b/docs/説明書/mir-unified-reference.md deleted file mode 100644 index a0264e54..00000000 --- a/docs/説明書/mir-unified-reference.md +++ /dev/null @@ -1,235 +0,0 @@ -# 🤖 Nyash MIR (Mid-level Intermediate Representation) - 統合リファレンス - -*26命令削減実装中・ChatGPT5仕様準拠 - 2025年8月17日版* - -## 🚨 **重要: MIR命令削減プロジェクト進行中** - -**現状**: 35命令実装(175%膨張)→ **目標**: 26命令(ChatGPT5仕様) -**Gemini評価**: 削減戦略「極めて健全」「断行推奨」 - -## 🎯 **MIR概要** - -Nyash MIRは、Everything is Box哲学を基盤とした中間表現です。現在35命令が実装され、インタープリター・VM・WASM・AOTの全バックエンドで統一された実行を実現します。 - -### **🌟 主要特徴** -- **Everything is Box**: 全データがBoxオブジェクトとして統一表現 -- **Effect System**: pure/mut/io/control効果による最適化基盤 -- **所有権管理**: 強参照森(ownership forest)+ weak参照システム -- **非同期対応**: Future/Bus操作の言語レベル統合 -- **FFI/ABI統合**: ExternCall命令による外部API統一呼び出し - -## 🏗️ **命令分類 - 35命令全体系** - -### **Tier-0: コア演算 (8命令)** -基本的な計算・制御フロー命令 - -| 命令 | 形式 | 効果 | 説明 | -|------|------|------|------| -| `Const` | `%dst = const value` | pure | 定数値生成 | -| `BinOp` | `%dst = %lhs op %rhs` | pure | 二項演算(+,-,*,/等) | -| `UnaryOp` | `%dst = op %operand` | pure | 単項演算(not, neg等) | -| `Compare` | `%dst = %lhs cmp %rhs` | pure | 比較演算(==, !=, <等) | -| `Branch` | `br %cond -> %then, %else` | control | 条件分岐 | -| `Jump` | `jmp %target` | control | 無条件ジャンプ | -| `Return` | `ret %value?` | control | 関数戻り | -| `Phi` | `%dst = phi [%val1:%bb1, %val2:%bb2]` | pure | SSA φ関数 | - -### **Tier-1: メモリ・関数操作 (8命令)** -メモリアクセス・関数呼び出し・型操作 - -| 命令 | 形式 | 効果 | 説明 | -|------|------|------|------| -| `Load` | `%dst = load %ptr` | pure | メモリ読み取り | -| `Store` | `store %value -> %ptr` | mut | メモリ書き込み | -| `Call` | `%dst = call %func(%args...)` | context | 関数呼び出し | -| `BoxCall` | `%dst = %box.method(%args...)` | context | Boxメソッド呼び出し | -| `NewBox` | `%dst = new_box "Type"(%args...)` | mut | Box生成 | -| `TypeCheck` | `%dst = type_check %box "Type"` | pure | 型チェック | -| `Cast` | `%dst = cast %value as Type` | pure | 型変換 | -| `Copy` | `%dst = copy %src` | pure | 値コピー | - -### **Tier-2: 配列・デバッグ・制御 (7命令)** -配列操作・デバッグ・例外処理 - -| 命令 | 形式 | 効果 | 説明 | -|------|------|------|------| -| `ArrayGet` | `%dst = %array[%index]` | pure | 配列要素取得 | -| `ArraySet` | `%array[%index] = %value` | mut | 配列要素設定 | -| `Debug` | `debug %value "message"` | io | デバッグ出力 | -| `Print` | `print %value` | io | コンソール出力 | -| `Nop` | `nop` | pure | 無操作 | -| `Throw` | `throw %exception` | control | 例外発生 | -| `Catch` | `catch %type -> %handler` | control | 例外捕捉 | - -### **Tier-3: 参照・非同期・外部API (12命令)** -所有権管理・非同期処理・外部連携 - -| 命令 | 形式 | 効果 | 説明 | -|------|------|------|------| -| `Safepoint` | `safepoint` | io | セーフポイント | -| `RefNew` | `%dst = ref_new %box` | pure | 参照生成 | -| `RefGet` | `%dst = ref_get %ref.field` | pure | 参照経由読み取り | -| `RefSet` | `ref_set %ref.field = %value` | mut | 参照経由書き込み | -| `WeakNew` | `%dst = weak_new %box` | pure | weak参照生成 | -| `WeakLoad` | `%dst = weak_load %weak_ref` | pure | weak参照読み取り | -| `BarrierRead` | `barrier_read %ptr` | io | メモリバリア読み | -| `BarrierWrite` | `barrier_write %ptr` | io | メモリバリア書き | -| `FutureNew` | `%dst = future_new %value` | mut | Future生成 | -| `FutureSet` | `future_set %future = %value` | mut | Future値設定 | -| `Await` | `%dst = await %future` | io | Future待機 | -| `ExternCall` | `%dst = extern_call iface.method(%args...)` | context | 外部API呼び出し | - -## 🎭 **Effect System - 4種類の効果** - -### **効果分類と最適化ルール** - -```rust -pub enum Effect { - Pure, // 再順序化可能、共通部分式除去可能 - Mut, // 同一リソースで順序保持必要 - Io, // 全順序保持必要(副作用あり) - Control, // 制御フロー変更 -} -``` - -### **効果別命令分類** - -#### **Pure命令 (15命令)** -``` -Const, BinOp, UnaryOp, Compare, Phi, Load, TypeCheck, Cast, Copy, -ArrayGet, Nop, RefNew, RefGet, WeakNew, WeakLoad -``` - -#### **Mut命令 (7命令)** -``` -Store, NewBox, ArraySet, RefSet, FutureNew, FutureSet -``` - -#### **Io命令 (6命令)** -``` -Debug, Print, Safepoint, BarrierRead, BarrierWrite, Await -``` - -#### **Control命令 (4命令)** -``` -Branch, Jump, Return, Throw, Catch -``` - -#### **Context依存命令 (3命令)** -``` -Call, BoxCall, ExternCall -``` -*効果は呼び出し先に依存* - -## 🔧 **重要なMIR実装詳細** - -### **ExternCall命令 - FFI/ABI統合** - -```rust -ExternCall { - dst: Option, - iface_name: String, // "env.console", "nyash.math"等 - method_name: String, // "log", "sqrt"等 - args: Vec, - effects: EffectMask, // BID仕様から決定 -} -``` - -**用途**: ブラウザーAPI・ネイティブライブラリ・プラグインの統一呼び出し - -### **所有権管理システム** - -#### **強参照森(Ownership Forest)** -- 各Boxは最大1つの強参照を持つ(in-degree ≤ 1) -- 強参照による循環は禁止(DAG構造保証) -- `NewBox`, `RefSet`で所有権移転 - -#### **weak参照システム** -- 所有権を持たない軽量参照 -- `WeakNew`で生成、`WeakLoad`で安全アクセス -- 参照先削除時は自動的にnull化 - -### **非同期処理 - Future操作** - -```mir -%future = FutureNew %initial_value // Future生成 -FutureSet %future = %result // 結果設定 -%value = Await %future // 結果取得(ブロッキング) -``` - -## 🚀 **バックエンド別対応状況** - -### **実装済みバックエンド** - -| バックエンド | 対応命令数 | 主要用途 | 特徴 | -|-------------|-----------|----------|------| -| **Interpreter** | 35/35 | デバッグ・開発 | 全命令完全対応 | -| **VM** | 35/35 | 高速実行 | レジスタベース | -| **WASM** | 30/35 | Web配布 | ExternCall→import対応 | -| **AOT準備** | 計画中 | ネイティブ | LLVM IR生成予定 | - -### **バックエンド固有の最適化** - -#### **VM バックエンド** -- レジスタベース実行 -- 局所最適化(ローカルBus elision) -- 直接スレッド化 - -#### **WASM バックエンド** -- メモリ線形化(文字列は (ptr,len)) -- ExternCall → import宣言自動生成 -- ホスト側JavaScript連携 - -## 📊 **MIR最適化パス** - -### **Pure命令最適化** -- **共通部分式除去 (CSE)**: 同一pure計算の除去 -- **不変コード移動 (LICM)**: ループ外移動 -- **定数畳み込み**: コンパイル時計算 - -### **Effect-aware最適化** -- **Mut順序保持**: 同一リソースアクセス順序維持 -- **Io順序保持**: 全Io命令の順序保証 -- **Bus elision**: ローカル通信の直接アクセス化 - -## 🧪 **テスト・検証** - -### **MIR検証項目** -- [ ] **所有権森検証**: strong in-degree ≤ 1 -- [ ] **強循環禁止**: 強参照のDAG構造保証 -- [ ] **weak参照安全性**: 失効時null化 -- [ ] **効果注釈正確性**: 各命令の効果分類 -- [ ] **型安全性**: Box型システム整合性 - -### **バックエンド互換性テスト** -```bash -# 全バックエンドMIR一致テスト -./target/release/nyash --dump-mir program.nyash > interpreter.mir -./target/release/nyash --backend vm --dump-mir program.nyash > vm.mir -./target/release/nyash --backend wasm --dump-mir program.nyash > wasm.mir -diff interpreter.mir vm.mir && diff vm.mir wasm.mir -``` - -## 🔮 **将来計画** - -### **Phase 10: AOT/JIT対応** -- LLVM IR生成バックエンド -- ExternCall → ネイティブ関数呼び出し -- 高度な最適化パス統合 - -### **Phase 11: MIR v2設計** -- 命令数最適化(35 → 25命令目標) -- BID統合(Box Interface Definition) -- リソース所有権拡張(own, borrow) - -## 📚 **関連ドキュメント** - -- **FFI/ABI仕様**: `docs/説明書/reference/box-design/ffi-abi-specification.md` -- **実装詳細**: `src/mir/instruction.rs` -- **Phase計画**: `docs/予定/native-plan/copilot_issues.txt` - ---- - -**最終更新**: 2025年8月17日 -**実装ベース**: 35命令完全対応 -**次期計画**: BID統合プラグインシステム(Phase 9.75f-BID) \ No newline at end of file diff --git a/docs_backup_20250820_214047.tar.gz b/docs_backup_20250820_214047.tar.gz new file mode 100644 index 00000000..7e722fff Binary files /dev/null and b/docs_backup_20250820_214047.tar.gz differ diff --git a/example.txt b/example.txt new file mode 100644 index 00000000..667859eb --- /dev/null +++ b/example.txt @@ -0,0 +1 @@ +hello nyash \ No newline at end of file diff --git a/nyash.toml b/nyash.toml index 4c7fb962..75d1ffce 100644 --- a/nyash.toml +++ b/nyash.toml @@ -26,6 +26,12 @@ write = { method_id = 3, args = ["data"] } close = { method_id = 4 } fini = { method_id = 4294967295 } +# v2.1: Box引数を受け取るメソッド宣言(FileBox: copyFrom(other: Handle)) +copyFrom = { method_id = 7, args = [ { kind = "box", category = "plugin" } ] } + +# v2.2: BoxRef(Handle)を返すメソッド宣言 +cloneSelf = { method_id = 8 } + [plugin_paths] # プラグインの検索パス(デフォルト) search_paths = [ @@ -35,4 +41,4 @@ search_paths = [ "./plugins/*/target/debug", "/usr/local/lib/nyash/plugins", "~/.nyash/plugins" -] \ No newline at end of file +] diff --git a/plugins/nyash-filebox-plugin/src/lib.rs b/plugins/nyash-filebox-plugin/src/lib.rs index 32d95b90..0ec641f5 100644 --- a/plugins/nyash-filebox-plugin/src/lib.rs +++ b/plugins/nyash-filebox-plugin/src/lib.rs @@ -42,6 +42,8 @@ const METHOD_OPEN: u32 = 1; const METHOD_READ: u32 = 2; const METHOD_WRITE: u32 = 3; const METHOD_CLOSE: u32 = 4; +const METHOD_COPY_FROM: u32 = 7; // New: copyFrom(other: Handle) +const METHOD_CLONE_SELF: u32 = 8; // New: cloneSelf() -> Handle const METHOD_FINI: u32 = u32::MAX; // Destructor // ============ FileBox Instance ============ @@ -204,6 +206,8 @@ pub extern "C" fn nyash_plugin_invoke( return NYB_E_PLUGIN_ERROR; } log_info(&format!("WRITE {} bytes", n)); + // バッファも更新(copyFromなどのため) + inst.buffer = Some(data.clone()); return write_tlv_i32(n as i32, _result, _result_len); } Err(_) => return NYB_E_PLUGIN_ERROR, @@ -230,6 +234,63 @@ pub extern "C" fn nyash_plugin_invoke( return NYB_E_PLUGIN_ERROR; } } + METHOD_COPY_FROM => { + // args: TLV { Handle (tag=8, size=8) } + let args = std::slice::from_raw_parts(_args, _args_len); + match tlv_parse_handle(args) { + Ok((type_id, other_id)) => { + if type_id != _type_id { return NYB_E_INVALID_TYPE; } + if preflight(_result, _result_len, 8) { return NYB_E_SHORT_BUFFER; } + if let Ok(mut map) = INSTANCES.lock() { + // 1) まずsrcからデータを取り出す(不変参照のみ) + let mut data: Vec = Vec::new(); + if let Some(src) = map.get(&other_id) { + let mut read_ok = false; + if let Some(file) = src.file.as_ref() { + if let Ok(mut f) = file.try_clone() { + let _ = f.seek(SeekFrom::Start(0)); + if f.read_to_end(&mut data).is_ok() { + read_ok = true; + } + } + } + if !read_ok { + if let Some(buf) = src.buffer.as_ref() { + data.extend_from_slice(buf); + read_ok = true; + } + } + if !read_ok { return NYB_E_PLUGIN_ERROR; } + } else { return NYB_E_INVALID_HANDLE; } + + // 2) dstへ書き込み(可変参照) + if let Some(dst) = map.get_mut(&_instance_id) { + if let Some(fdst) = dst.file.as_mut() { + let _ = fdst.seek(SeekFrom::Start(0)); + if fdst.write_all(&data).is_err() { return NYB_E_PLUGIN_ERROR; } + let _ = fdst.set_len(data.len() as u64); + let _ = fdst.flush(); + } + dst.buffer = Some(data); + return write_tlv_void(_result, _result_len); + } else { return NYB_E_INVALID_HANDLE; } + } else { return NYB_E_PLUGIN_ERROR; } + } + Err(_) => NYB_E_INVALID_ARGS, + } + } + METHOD_CLONE_SELF => { + // Return a new instance (handle) as TLV Handle + // Preflight for Handle TLV: header(4) + entry(4) + payload(8) + if preflight(_result, _result_len, 16) { return NYB_E_SHORT_BUFFER; } + let new_id = INSTANCE_COUNTER.fetch_add(1, Ordering::Relaxed); + if let Ok(mut map) = INSTANCES.lock() { map.insert(new_id, FileBoxInstance { file: None, path: String::new(), buffer: None }); } + // Build TLV result + let mut payload = [0u8;8]; + payload[0..4].copy_from_slice(&_type_id.to_le_bytes()); + payload[4..8].copy_from_slice(&new_id.to_le_bytes()); + return write_tlv_result(&[(8u8, &payload)], _result, _result_len); + } _ => NYB_SUCCESS } } @@ -343,6 +404,18 @@ fn tlv_parse_bytes(data: &[u8]) -> Result, ()> { Ok(data[pos..pos+size].to_vec()) } +fn tlv_parse_handle(data: &[u8]) -> Result<(u32, u32), ()> { + let (_, argc, mut pos) = tlv_parse_header(data)?; + if argc < 1 { return Err(()); } + if pos + 4 > data.len() { return Err(()); } + let tag = data[pos]; let _res = data[pos+1]; + let size = u16::from_le_bytes([data[pos+2], data[pos+3]]) as usize; pos += 4; + if tag != 8 || size != 8 || pos + size > data.len() { return Err(()); } + let mut t = [0u8;4]; t.copy_from_slice(&data[pos..pos+4]); + let mut i = [0u8;4]; i.copy_from_slice(&data[pos+4..pos+8]); + Ok((u32::from_le_bytes(t), u32::from_le_bytes(i))) +} + fn log_info(message: &str) { eprintln!("[FileBox] {}", message); } @@ -360,4 +433,3 @@ pub extern "C" fn nyash_plugin_shutdown() { // ============ Unified Plugin API ============ // Note: Metadata (Box types, methods) now comes from nyash.toml // This plugin provides only the actual processing functions - diff --git a/src/config/nyash_toml_v2.rs b/src/config/nyash_toml_v2.rs index 46b4c0ef..8033ebc3 100644 --- a/src/config/nyash_toml_v2.rs +++ b/src/config/nyash_toml_v2.rs @@ -50,10 +50,37 @@ pub struct BoxTypeConfig { } /// Method definition (simplified - no argument info needed) -#[derive(Debug, Deserialize, Serialize)] +#[derive(Debug, Deserialize, Serialize, Clone)] pub struct MethodDefinition { /// Method ID for FFI pub method_id: u32, + /// Optional argument declarations (v2.1+) + #[serde(default)] + pub args: Option>, +} + +/// Method argument declaration (v2.1+) +#[derive(Debug, Deserialize, Serialize, Clone)] +#[serde(untagged)] +pub enum ArgDecl { + /// Backward-compatible string form (treated as kind="string") + Name(String), + /// Typed declaration + Typed { + kind: String, + #[serde(default)] + category: Option, + }, +} + +impl ArgDecl { + /// Returns a canonical kind string ("string", "box", etc.) + pub fn kind_str(&self) -> &str { + match self { + ArgDecl::Name(_) => "string", + ArgDecl::Typed { kind, .. } => kind.as_str(), + } + } } fn default_abi_version() -> u32 { diff --git a/src/interpreter/expressions/calls.rs b/src/interpreter/expressions/calls.rs index 7af8c6cc..fc3d4106 100644 --- a/src/interpreter/expressions/calls.rs +++ b/src/interpreter/expressions/calls.rs @@ -949,6 +949,20 @@ impl NyashInterpreter { arguments: &[ASTNode], ) -> Result, RuntimeError> { eprintln!("🔍 execute_plugin_box_v2_method called: {}.{}", plugin_box.box_type, method); + // Route via loader for proper TLV/Handle handling (early return) + { + let mut arg_values: Vec> = Vec::new(); + for arg in arguments { + arg_values.push(self.execute_expression(arg)?); + } + let loader_guard = crate::runtime::plugin_loader_v2::get_global_loader_v2(); + let loader = loader_guard.read().map_err(|_| RuntimeError::RuntimeFailure { message: "Plugin loader lock poisoned".into() })?; + match loader.invoke_instance_method(&plugin_box.box_type, method, plugin_box.instance_id, &arg_values) { + Ok(Some(result_box)) => return Ok(result_box), + Ok(None) => return Ok(Box::new(VoidBox::new())), + Err(e) => return Err(RuntimeError::RuntimeFailure { message: format!("Plugin method {} failed: {:?}", method, e) }), + } + } // Get global loader to access configuration let loader = crate::runtime::plugin_loader_v2::get_global_loader_v2(); @@ -1085,6 +1099,33 @@ impl NyashInterpreter { let string = String::from_utf8_lossy(data).to_string(); Ok(Box::new(StringBox::new(string))) } + 8 => { + // Handle type - contains type_id and instance_id + if size == 8 { + let type_id = u32::from_le_bytes([ + output_buffer[8], output_buffer[9], + output_buffer[10], output_buffer[11] + ]); + let instance_id = u32::from_le_bytes([ + output_buffer[12], output_buffer[13], + output_buffer[14], output_buffer[15] + ]); + eprintln!("🔍 Received Handle: type_id={}, instance_id={}", type_id, instance_id); + + // Create a new PluginBoxV2 instance with the returned handle + let new_plugin_box = PluginBoxV2 { + box_type: plugin_box.box_type.clone(), + type_id: plugin_box.type_id, + invoke_fn: plugin_box.invoke_fn, + instance_id: instance_id, + fini_method_id: plugin_box.fini_method_id, + }; + Ok(Box::new(new_plugin_box)) + } else { + eprintln!("🔍 Invalid Handle size: {} (expected 8)", size); + Ok(Box::new(VoidBox::new())) + } + } 9 => { // Void type Ok(Box::new(StringBox::new("ok"))) diff --git a/src/runtime/plugin_loader_v2.rs b/src/runtime/plugin_loader_v2.rs index 34c3551a..fb14f284 100644 --- a/src/runtime/plugin_loader_v2.rs +++ b/src/runtime/plugin_loader_v2.rs @@ -171,20 +171,41 @@ impl PluginBoxV2 { /// Configuration pub config: Option, + /// Path to the loaded nyash.toml (absolute), used for consistent re-reads + config_path: Option, } impl PluginLoaderV2 { + fn find_box_by_type_id<'a>(&'a self, config: &'a NyashConfigV2, toml_value: &'a toml::Value, type_id: u32) -> Option<(&'a str, &'a str)> { + for (lib_name, lib_def) in &config.libraries { + for box_name in &lib_def.boxes { + if let Some(box_conf) = config.get_box_config(lib_name, box_name, toml_value) { + if box_conf.type_id == type_id { + return Some((lib_name.as_str(), box_name.as_str())); + } + } + } + } + None + } /// Create new loader pub fn new() -> Self { Self { plugins: RwLock::new(HashMap::new()), config: None, + config_path: None, } } /// Load configuration from nyash.toml pub fn load_config(&mut self, config_path: &str) -> BidResult<()> { - self.config = Some(NyashConfigV2::from_file(config_path) + // Canonicalize path for later re-reads + let canonical = std::fs::canonicalize(config_path) + .map(|p| p.to_string_lossy().to_string()) + .unwrap_or_else(|_| config_path.to_string()); + self.config_path = Some(canonical.clone()); + + self.config = Some(NyashConfigV2::from_file(&canonical) .map_err(|e| { eprintln!("Failed to load config: {}", e); BidError::PluginError @@ -236,10 +257,15 @@ impl PluginBoxV2 { let config = self.config.as_ref().ok_or(BidError::PluginError)?; let (lib_name, _lib_def) = config.find_library_for_box(box_type) .ok_or(BidError::InvalidType)?; - let toml_content = std::fs::read_to_string("nyash.toml").map_err(|_| BidError::PluginError)?; + let cfg_path = self.config_path.as_ref().map(|s| s.as_str()).unwrap_or("nyash.toml"); + let toml_content = std::fs::read_to_string(cfg_path).map_err(|_| BidError::PluginError)?; let toml_value: toml::Value = toml::from_str(&toml_content).map_err(|_| BidError::PluginError)?; let box_conf = config.get_box_config(lib_name, box_type, &toml_value).ok_or(BidError::InvalidType)?; - let method = box_conf.methods.get(method_name).ok_or(BidError::InvalidMethod)?; + let method = box_conf.methods.get(method_name).ok_or_else(|| { + eprintln!("[PluginLoaderV2] Method '{}' not found for box '{}' in {}", method_name, box_type, cfg_path); + eprintln!("[PluginLoaderV2] Available methods: {:?}", box_conf.methods.keys().collect::>()); + BidError::InvalidMethod + })?; Ok(method.method_id) } @@ -251,43 +277,112 @@ impl PluginBoxV2 { instance_id: u32, args: &[Box], ) -> BidResult>> { - // Only support zero-argument methods for now (minimal viable) - if !args.is_empty() { - return Err(BidError::InvalidMethod); - } + // v2.1: 引数ありのメソッドを許可(BoxRef/基本型/文字列化フォールバック) let method_id = self.resolve_method_id_from_file(box_type, method_name)?; // Find plugin and type_id let config = self.config.as_ref().ok_or(BidError::PluginError)?; let (lib_name, _lib_def) = config.find_library_for_box(box_type).ok_or(BidError::InvalidType)?; let plugins = self.plugins.read().unwrap(); let plugin = plugins.get(lib_name).ok_or(BidError::PluginError)?; - let toml_content = std::fs::read_to_string("nyash.toml").map_err(|_| BidError::PluginError)?; + let cfg_path = self.config_path.as_ref().map(|s| s.as_str()).unwrap_or("nyash.toml"); + let toml_content = std::fs::read_to_string(cfg_path).map_err(|_| BidError::PluginError)?; let toml_value: toml::Value = toml::from_str(&toml_content).map_err(|_| BidError::PluginError)?; let box_conf = config.get_box_config(lib_name, box_type, &toml_value).ok_or(BidError::InvalidType)?; let type_id = box_conf.type_id; - // TLV args: encode provided arguments + eprintln!("[PluginLoaderV2] Invoke {}.{}: resolving and encoding args (argc={})", box_type, method_name, args.len()); + // TLV args: encode using BID-1 style (u16 ver, u16 argc, then entries) let tlv_args = { - // minimal local encoder (duplicates of encode_tlv_args not accessible here) - let mut buf = Vec::with_capacity(4 + args.len() * 12); - buf.extend_from_slice(&[1u8, args.len() as u8, 0, 0]); - for a in args { + let mut buf = Vec::with_capacity(4 + args.len() * 16); + // Header: ver=1, argc=args.len() + buf.extend_from_slice(&1u16.to_le_bytes()); + buf.extend_from_slice(&(args.len() as u16).to_le_bytes()); + // Validate against nyash.toml method args schema if present + let expected_args = box_conf.methods.get(method_name).and_then(|m| m.args.clone()); + if let Some(exp) = expected_args.as_ref() { + if exp.len() != args.len() { + return Err(BidError::InvalidArgs); + } + } + + for (idx, a) in args.iter().enumerate() { + // If schema exists, validate per expected kind + if let Some(exp) = expected_args.as_ref() { + let decl = &exp[idx]; + match decl { + crate::config::nyash_toml_v2::ArgDecl::Typed { kind, category } => { + match kind.as_str() { + "box" => { + // Only plugin box supported for now + if category.as_deref() != Some("plugin") { + return Err(BidError::InvalidArgs); + } + if a.as_any().downcast_ref::().is_none() { + return Err(BidError::InvalidArgs); + } + } + "string" => { + if a.as_any().downcast_ref::().is_none() { + return Err(BidError::InvalidArgs); + } + } + _ => { + // Unsupported kind in this minimal implementation + return Err(BidError::InvalidArgs); + } + } + } + crate::config::nyash_toml_v2::ArgDecl::Name(_) => { + // Back-compat: expect string + if a.as_any().downcast_ref::().is_none() { + return Err(BidError::InvalidArgs); + } + } + } + } + + // Plugin Handle (BoxRef): tag=8, size=8 + if let Some(p) = a.as_any().downcast_ref::() { + eprintln!("[PluginLoaderV2] arg[{}]: PluginBoxV2({}, id={}) -> Handle(tag=8)", idx, p.box_type, p.instance_id); + buf.push(8u8); // tag + buf.push(0u8); // reserved + buf.extend_from_slice(&(8u16).to_le_bytes()); + buf.extend_from_slice(&p.type_id.to_le_bytes()); + buf.extend_from_slice(&p.instance_id.to_le_bytes()); + continue; + } + // Integer: prefer i32 if let Some(i) = a.as_any().downcast_ref::() { - buf.push(1); - buf.extend_from_slice(&(i.value as i64).to_le_bytes()); - } else if let Some(b) = a.as_any().downcast_ref::() { - buf.push(3); - buf.push(if b.value {1} else {0}); - } else if let Some(s) = a.as_any().downcast_ref::() { + eprintln!("[PluginLoaderV2] arg[{}]: Integer({}) -> I32(tag=2)", idx, i.value); + buf.push(2u8); // tag=I32 + buf.push(0u8); + buf.extend_from_slice(&(4u16).to_le_bytes()); + let v = i.value as i32; + buf.extend_from_slice(&v.to_le_bytes()); + continue; + } + // String: tag=6 + if let Some(s) = a.as_any().downcast_ref::() { + eprintln!("[PluginLoaderV2] arg[{}]: String(len={}) -> String(tag=6)", idx, s.value.len()); let bytes = s.value.as_bytes(); - buf.push(2); - buf.extend_from_slice(&(bytes.len() as u32).to_le_bytes()); - buf.extend_from_slice(bytes); + let len = std::cmp::min(bytes.len(), u16::MAX as usize); + buf.push(6u8); + buf.push(0u8); + buf.extend_from_slice(&((len as u16).to_le_bytes())); + buf.extend_from_slice(&bytes[..len]); + continue; + } + // No schema or unsupported type: only allow fallback when schema is None + if expected_args.is_none() { + eprintln!("[PluginLoaderV2] arg[{}]: fallback stringify", idx); + let sv = a.to_string_box().value; + let bytes = sv.as_bytes(); + let len = std::cmp::min(bytes.len(), u16::MAX as usize); + buf.push(6u8); + buf.push(0u8); + buf.extend_from_slice(&((len as u16).to_le_bytes())); + buf.extend_from_slice(&bytes[..len]); } else { - let s = a.to_string_box().value; - let bytes = s.as_bytes(); - buf.push(2); - buf.extend_from_slice(&(bytes.len() as u32).to_le_bytes()); - buf.extend_from_slice(bytes); + return Err(BidError::InvalidArgs); } } buf @@ -306,29 +401,59 @@ impl PluginBoxV2 { ) }; if rc != 0 { - return Err(BidError::InvalidMethod); + let be = BidError::from_raw(rc); + eprintln!("[PluginLoaderV2] invoke rc={} ({}) for {}.{}", rc, be.message(), box_type, method_name); + return Err(be); } - // minimal decode: tag=1 int, tag=2 string, tag=3 bool, otherwise None + // Decode: BID-1 style header + first entry let result = if out_len == 0 { None } else { let data = &out[..out_len]; - match data[0] { - 1 if data.len() >= 9 => { - let mut arr = [0u8;8]; - arr.copy_from_slice(&data[1..9]); - Some(Box::new(IntegerBox::new(i64::from_le_bytes(arr))) as Box) + if data.len() < 4 { return Ok(None); } + let _ver = u16::from_le_bytes([data[0], data[1]]); + let argc = u16::from_le_bytes([data[2], data[3]]); + if argc == 0 { return Ok(None); } + if data.len() < 8 { return Ok(None); } + let tag = data[4]; + let _rsv = data[5]; + let size = u16::from_le_bytes([data[6], data[7]]) as usize; + if data.len() < 8 + size { return Ok(None); } + let payload = &data[8..8+size]; + match tag { + 8 if size == 8 => { // Handle -> PluginBoxV2 + let mut t = [0u8;4]; t.copy_from_slice(&payload[0..4]); + let mut i = [0u8;4]; i.copy_from_slice(&payload[4..8]); + let r_type = u32::from_le_bytes(t); + let r_inst = u32::from_le_bytes(i); + // Map type_id -> (lib_name, box_name) + if let Some((ret_lib, ret_box)) = self.find_box_by_type_id(config, &toml_value, r_type) { + // Get plugin for ret_lib + let plugins = self.plugins.read().unwrap(); + if let Some(ret_plugin) = plugins.get(ret_lib) { + // Need fini_method_id from config + if let Some(ret_conf) = config.get_box_config(ret_lib, ret_box, &toml_value) { + let fini_id = ret_conf.methods.get("fini").map(|m| m.method_id); + let pbox = PluginBoxV2 { + box_type: ret_box.to_string(), + type_id: r_type, + invoke_fn: ret_plugin.invoke_fn, + instance_id: r_inst, + fini_method_id: fini_id, + }; + return Ok(Some(Box::new(pbox) as Box)); + } + } + } + None } - 2 if data.len() >= 5 => { - let mut larr = [0u8;4]; - larr.copy_from_slice(&data[1..5]); - let len = u32::from_le_bytes(larr) as usize; - if data.len() >= 5+len { - let s = String::from_utf8_lossy(&data[5..5+len]).to_string(); - Some(Box::new(StringBox::new(s)) as Box) - } else { None } + 2 if size == 4 => { // I32 + let mut b = [0u8;4]; b.copy_from_slice(payload); + Some(Box::new(IntegerBox::new(i32::from_le_bytes(b) as i64)) as Box) } - 3 if data.len() >= 2 => { - Some(Box::new(BoolBox::new(data[1] != 0)) as Box) + 6 | 7 => { // String/Bytes + let s = String::from_utf8_lossy(payload).to_string(); + Some(Box::new(StringBox::new(s)) as Box) } + 9 => None, // Void _ => None, } }; @@ -425,7 +550,8 @@ impl PluginBoxV2 { // Get type_id from config - read actual nyash.toml content eprintln!("🔍 Reading nyash.toml for type configuration..."); - let (type_id, fini_method_id) = if let Ok(toml_content) = std::fs::read_to_string("nyash.toml") { + let cfg_path = self.config_path.as_ref().map(|s| s.as_str()).unwrap_or("nyash.toml"); + let (type_id, fini_method_id) = if let Ok(toml_content) = std::fs::read_to_string(cfg_path) { eprintln!("🔍 nyash.toml read successfully"); if let Ok(toml_value) = toml::from_str::(&toml_content) { eprintln!("🔍 nyash.toml parsed successfully"); diff --git a/tools/plugin-tester/src/main.rs b/tools/plugin-tester/src/main.rs index 3fc6b5db..53ed332b 100644 --- a/tools/plugin-tester/src/main.rs +++ b/tools/plugin-tester/src/main.rs @@ -11,7 +11,7 @@ use libloading::{Library, Symbol}; use serde::Deserialize; use std::collections::HashMap; use std::fs; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; // ============ nyash.toml v2 Types ============ @@ -86,6 +86,20 @@ fn tlv_encode_empty() -> Vec { vec![1, 0, 0, 0] // version=1, argc=0 } +fn tlv_encode_one_handle(type_id: u32, instance_id: u32) -> Vec { + // BID-1 TLV header: u16 ver=1, u16 argc=1 + // Entry: tag=8(Handle), rsv=0, size=u16(8), payload=[type_id(4), instance_id(4)] + let mut buf = Vec::with_capacity(4 + 4 + 8); + buf.extend_from_slice(&1u16.to_le_bytes()); // ver + buf.extend_from_slice(&1u16.to_le_bytes()); // argc + buf.push(8u8); // tag=Handle + buf.push(0u8); // reserved + buf.extend_from_slice(&(8u16).to_le_bytes()); // size + buf.extend_from_slice(&type_id.to_le_bytes()); + buf.extend_from_slice(&instance_id.to_le_bytes()); + buf +} + fn tlv_decode_u32(data: &[u8]) -> Result { if data.len() >= 4 { Ok(u32::from_le_bytes([data[0], data[1], data[2], data[3]])) @@ -137,6 +151,9 @@ fn check_v2(config_path: &PathBuf, library_filter: Option<&str>) { } }; + // Base dir for relative plugin paths + let config_base = config_path.parent().unwrap_or(Path::new(".")); + // Check each library for (lib_name, lib_def) in &config.libraries { if let Some(filter) = library_filter { @@ -150,10 +167,15 @@ fn check_v2(config_path: &PathBuf, library_filter: Option<&str>) { println!(" Box types: {:?}", lib_def.boxes); // Try to load the plugin - let library = match unsafe { Library::new(&lib_def.path) } { + let lib_path = if Path::new(&lib_def.path).is_absolute() { + PathBuf::from(&lib_def.path) + } else { + config_base.join(&lib_def.path) + }; + let library = match unsafe { Library::new(&lib_path) } { Ok(lib) => lib, Err(e) => { - eprintln!(" {}: Failed to load: {}", "ERROR".red(), e); + eprintln!(" {}: Failed to load: {} (path: {})", "ERROR".red(), e, lib_path.display()); continue; } }; @@ -249,11 +271,17 @@ fn test_lifecycle_v2(config_path: &PathBuf, box_type: &str) { println!("Type ID: {}", box_config.type_id); + // Resolve plugin path relative to config dir + let config_base = config_path.parent().unwrap_or(Path::new(".")); + let lib_path = if Path::new(&lib_def.path).is_absolute() { + PathBuf::from(&lib_def.path) + } else { config_base.join(&lib_def.path) }; + // Load plugin - let library = match unsafe { Library::new(&lib_def.path) } { + let library = match unsafe { Library::new(&lib_path) } { Ok(lib) => lib, Err(e) => { - eprintln!("{}: Failed to load plugin: {}", "ERROR".red(), e); + eprintln!("{}: Failed to load plugin: {} (path: {})", "ERROR".red(), e, lib_path.display()); return; } }; @@ -301,6 +329,80 @@ fn test_lifecycle_v2(config_path: &PathBuf, box_type: &str) { }; println!("{}: Birth successful, instance_id = {}", "✓".green(), instance_id); + + // Optional: If method 'copyFrom' exists, create another instance and pass it as Box arg + if box_config.methods.contains_key("copyFrom") { + println!("\n{}", "1b. Testing method with Box arg: copyFrom(other) ...".cyan()); + + // Birth another instance to serve as argument handle + let args2 = tlv_encode_empty(); + let mut out2 = vec![0u8; 1024]; + let mut out2_len = out2.len(); + let rc2 = invoke_fn( + box_config.type_id, + 0, + 0, + args2.as_ptr(), + args2.len(), + out2.as_mut_ptr(), + &mut out2_len, + ); + if rc2 == 0 { + if let Ok(other_id) = tlv_decode_u32(&out2[..out2_len]) { + // Encode one Box handle as argument + let arg_buf = tlv_encode_one_handle(box_config.type_id, other_id); + let mut ret = vec![0u8; 1024]; + let mut ret_len = ret.len(); + let method_id = box_config.methods.get("copyFrom").unwrap().method_id; + let rc_call = invoke_fn( + box_config.type_id, + method_id, + instance_id, + arg_buf.as_ptr(), + arg_buf.len(), + ret.as_mut_ptr(), + &mut ret_len, + ); + if rc_call == 0 { + println!("{}: copyFrom call succeeded (arg=BoxRef)", "✓".green()); + } else { + eprintln!("{}: copyFrom call failed (rc={})", "WARN".yellow(), rc_call); + } + } else { + eprintln!("{}: Failed to decode other instance_id", "WARN".yellow()); + } + } else { + eprintln!("{}: Failed to create other instance for copyFrom (rc={})", "WARN".yellow(), rc2); + } + } + + // Optional: If method 'cloneSelf' exists, call it and verify Handle return + if box_config.methods.contains_key("cloneSelf") { + println!("\n{}", "1c. Testing method returning Box: cloneSelf() ...".cyan()); + let args0 = tlv_encode_empty(); + let mut out = vec![0u8; 1024]; + let mut out_len = out.len(); + let method_id = box_config.methods.get("cloneSelf").unwrap().method_id; + let rc = invoke_fn( + box_config.type_id, + method_id, + instance_id, + args0.as_ptr(), + args0.len(), + out.as_mut_ptr(), + &mut out_len, + ); + if rc == 0 { + // Parse TLV header + entry, expecting tag=8 size=8 + if out_len >= 12 && out[4] == 8 && out[7] as usize == 8 { // simplistic check + println!("{}: cloneSelf returned a Handle (tag=8)", "✓".green()); + } else { + eprintln!("{}: cloneSelf returned unexpected format", "WARN".yellow()); + } + } else { + eprintln!("{}: cloneSelf call failed (rc={})", "WARN".yellow(), rc); + } + } // Test fini println!("\n{}", "2. Testing fini (destructor)...".cyan()); @@ -345,4 +447,4 @@ fn get_box_config(raw_config: &toml::Value, lib_name: &str, box_name: &str) -> O .and_then(|v| v.get(lib_name)) .and_then(|v| v.get(box_name)) .and_then(|v| v.clone().try_into::().ok()) -} \ No newline at end of file +}