Phase 12: TypeBox革命とJIT制御フロー修正 - セルフホスティングへの道

## 🔥 TypeBox ABI革命(セルフホスティング実現)
- Nyash ABIをC実装TypeBoxで提供する画期的設計
- Gemini/Codexの深い考察を反映した詳細仕様書作成
- 16バイトアライメント、セレクターキャッシング、弱参照等の具体実装案
- Rust依存を完全排除し、セルフホスティングへの明確な道筋を確立

## 🎯 JIT制御フロー根本修正(ChatGPT5の25分長考の成果)
- ブロック挿入点の明確化: switch_to_block()で各ブロックemit開始時に切替
- シール戦略の簡潔化: br/jump直後のseal撤廃、最終シールに一本化
- PHI最小経路実装: ブロック引数の事前プリスキャン、後付けPHI問題解決
- Cranelift制約対応: 開始済みブロックへのappend禁止を正しく実装

## 📚 ドキュメント更新
- Phase 12全体のセルフホスティング対応更新
- NYASH-ABI-C-IMPLEMENTATION.md: 実装仕様書作成
- gemini-codex-deep-thoughts.md: AI専門家の考察アーカイブ
- 各種README/TASKS更新でセルフホスティング要件追加

##  テスト結果
- mir-branch-ret: OK (Result: 1)
- mir-phi-min: OK (Result: 10)
- mir-branch-multi: OK (Result: 1)

「Everything is Box」の究極形態:ABIすらBoxとして扱う革命的設計!

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

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Moe Charm
2025-09-02 11:18:19 +09:00
parent de99b40bee
commit b05d5dd7ca
13 changed files with 949 additions and 203 deletions

View File

@ -1,14 +1,15 @@
# 🚀 Nyash開発マスタープラン
Status: Active Development
Last Updated: 2025-08-26
Purpose: Claude×Copilot×ChatGPT協調開発の総合ロードマップ
Last Updated: 2025-09-02
Purpose: Claude×Copilot×ChatGPT×Gemini×Codex協調開発の総合ロードマップ
## 📍 現在位置
- 現在フェーズ: Phase 10.5b ネイティブビルド基盤の固めMIR→VM→AOTの足固め
- 次フェーズ: Phase 10.5c Handle-First PluginInvokePython統合の実装着手
- 備考: 旧10.1系10.1c/dは「PythonをNyashで動かすフェーズ」の設計資料Archived。順番を入れ替え、先にネイティブビルド基盤を完成させています。
- 現在フェーズ: Phase 12 TypeBox統合ABI・セルフホスティング準備
- 最新成果: 🔥 **Nyash ABIをC実装TypeBoxで提供** - Rust依存排除への道
- 次フェーズ: Phase 12.0.5 Nyash ABI C実装開始
- 備考: GeminiとCodexの深い考察により、セルフホスティングへの明確な道筋が見えました。
## 🗺️ フェーズ概要
@ -23,9 +24,9 @@ Purpose: Claude×Copilot×ChatGPT協調開発の総合ロードマップ
| 10 | 📅予定 | Cranelift JIT主経路 | [phase_10_cranelift_jit_backend.md](phase-10/phase_10_cranelift_jit_backend.md) |
| 11 | ✅完了 | LLVM統合・AOT実装依存重い | [phase-11/](phase-11/) |
| 11.8 | 📅予定 | MIR整理Core-15→Core-13 | [phase-11.8_mir_cleanup/](phase-11.8_mir_cleanup/) |
| 12 | 🔄進行中 | MIR Core-15確定・プラグイン統一 | [phase-12/](phase-12/) |
| 12 | 🔄進行中 | TypeBox統合ABI・セルフホスティング準備 | [phase-12/](phase-12/) |
| 12.5 | 📅予定 | MIR15最適化戦略 | [phase-12.5/](phase-12.5/) |
| 15 | 🌟将来 | セルフホスティング(Nyashコンパイラ | [phase-15/](phase-15/) |
| 15 | 🌟実現可能 | セルフホスティング(C実装ABI経由 | [phase-15/](phase-15/) |
---
@ -157,17 +158,21 @@ nyash bid gen --target llvm bid.yaml # AOT用declare生成LLVM実装時
---
### 🎯 Phase 12: MIR Core-15確定・プラグイン統一(進行中)
### 🎯 Phase 12: TypeBox統合ABI・セルフホスティング準備(進行中)
**Summary**:
- MIR Core-1514の最終確定
- プラグインシステムの3層統一
- Nyash ABI設計
- TypeBox革命型情報もBoxとして扱う統一設計
- C ABI + Nyash ABI完全統合
- 🔥 **Nyash ABIのC実装**でRust依存排除
**3層プラグインシステム**:
1. Nyashスクリプトプラグイン.nyash
2. C ABIプラグイン高速・安定
3. Nyash ABIプラグイン将来拡張
**革命的成果**:
1. TypeBoxプラグイン間Box生成を可能に
2. 統合ABIC/Nyash ABIをシームレス統合
3. **セルフホスティング**C実装ABIで実現可能
**AI専門家の評価**:
- Gemini「技術的妥当性が高く、哲学とも合致した極めて優れた設計」
- Codex「16バイトアライメント、セレクターキャッシング等の具体案」
---
@ -229,12 +234,30 @@ nyash bid gen --target llvm bid.yaml # AOT用declare生成LLVM実装時
---
## 🌟 Phase 15: セルフホスティング(実現可能!)
**革命的発見**: Nyash ABIをC実装TypeBoxで提供することで、Rust依存を排除
### 実現への道筋(明確化)
1. **Phase 12.0.5**: Nyash ABI C Shim実装Rust FFI経由
2. **Phase 13**: C実装の完全化基本型・参照カウント
3. **Phase 14**: NyashでABI再実装AOTでC ABI公開
4. **Phase 15**: Nyashコンパイラ自身をNyashで実装
### 技術的革新
- **TypeBox哲学**: ABIすらBoxとして扱う究極の統一
- **C ABI基盤**: 最も安定した普遍的インターフェース
- **段階的移行**: 既存Rust実装との共存期間を確保
---
## 📊 進捗管理・コミュニケーション
### 🤝 協調開発ルール
- ✅ 大きな変更前にはdocs/CURRENT_TASK.mdで情報共有
- ✅ ベンチマーク機能は最優先で維持
- ✅ 競合発生時は機能優先度で解決
- ✅ AI専門家Gemini/Codexの深い考察を活用
### 品質保証
- ✅ cargo check でビルドエラーなし

View File

@ -0,0 +1,229 @@
# Nyash ABIをC実装TypeBoxで提供する設計仕様書
## 🎯 概要
「Everything is Box」哲学の究極形**ABIすらBoxとして扱う**
本設計は、Nyash ABIをTypeBoxC ABIとして実装することで、Rust依存を排除し、完全なセルフホスティングを実現する革新的アプローチです。
**3大AI専門家の評価**
- **Gemini**: 「技術的妥当性が高く、言語哲学とも合致した、極めて優れた設計」
- **Codex**: 「Feasible and attractive: ABI-as-Box completes the idea」
- **ChatGPT5**: 「実装に耐える設計。10の改善点で完璧」統合ABI設計に反映済み
## 📐 技術設計
### 基本アーキテクチャ
```c
// nyash_abi_provider.h - Codex推奨の16バイトアライメント版
typedef struct __attribute__((aligned(16))) {
// TypeBox標準ヘッダバージョニング対応
uint32_t abi_tag; // 'NABI' (0x4942414E)
uint16_t api_version; // APIバージョン
uint16_t struct_size; // 構造体サイズ(互換性チェック用)
const char* name; // "NyashABIProvider"
void* (*create)(void); // プロバイダインスタンス生成
// Nyash ABI専用拡張コンテキストベース
struct {
// セレクターキャッシング対応
nyash_status (*lookup_selector)(nyash_ctx*, uint64_t type_id, const char* name, nyash_selector* out);
nyash_status (*call)(nyash_ctx*, void* obj, nyash_selector sel, nyash_value* argv, int argc, nyash_value* out);
// 基本操作
nyash_status (*create_value)(nyash_ctx*, uint64_t type_id, void* data, uint64_t flags, nyash_value* out);
void (*retain)(void* obj);
void (*release)(void* obj);
// 型情報
uint64_t (*type_of)(nyash_value value);
bool (*is_null)(nyash_value value);
bool (*eq)(nyash_value a, nyash_value b);
uint64_t (*hash)(nyash_value value);
} nyash_ops;
// 機能ビット(将来拡張用)
uint64_t capabilities; // NYASH_CAP_ASYNC | NYASH_CAP_WEAKREF等
void* reserved[4]; // 将来拡張用
} NyashABITypeBox;
```
### NyashValue - 16バイト最適化構造Codex提案
```c
// JIT/LLVM最適化を考慮した16バイトアライメント
typedef struct __attribute__((aligned(16))) {
uint64_t type_id; // 型識別子上位16bit: vendor, 8bit: kind
uint64_t payload; // ポインタまたはインライン値
uint64_t metadata; // フラグ・追加情報下位3bit: タグ)
} nyash_value;
// メタデータタグGemini提案のTagged Pointers
#define NYASH_TAG_POINTER 0x0 // ヒープオブジェクトへのポインタ
#define NYASH_TAG_SMALL_INT 0x1 // 61ビット整数符号付き
#define NYASH_TAG_BOOL 0x2 // 真偽値
#define NYASH_TAG_NULL 0x3 // null
#define NYASH_TAG_SMALL_ENUM 0x4 // 小さな列挙型
```
### メモリ管理 - Intrusive参照カウントGemini詳細提案
```c
// すべてのヒープBoxの共通ヘッダ
typedef struct {
atomic_size_t ref_count; // アトミック参照カウント
const nyash_obj_vtable* vtable; // メソッドテーブル
uint64_t type_id; // 型識別子
uint64_t flags; // THREAD_AFFINE等のフラグ
// 弱参照サポート(循環参照対策)
struct weak_ref_list* weak_refs; // 弱参照リスト(オプション)
} nyash_obj_header;
// Gemini推奨弱参照による循環参照回避
typedef struct {
nyash_obj_header* target; // 対象オブジェクトNULL可能
atomic_bool is_valid; // 有効性フラグ
} nyash_weak_ref;
```
### コンテキストベースAPICodex推奨
```c
// グローバル状態を避けるコンテキスト構造
typedef struct {
nyash_allocator* allocator; // カスタムアロケータ
nyash_scheduler* scheduler; // スケジューラasync用
void* tls; // スレッドローカルストレージ
uint64_t feature_flags; // 機能フラグ
nyash_error* last_error; // 最後のエラー
} nyash_ctx;
// ステータスコード(例外を使わない)
typedef enum {
NYASH_OK = 0,
NYASH_E_TYPE, // 型エラー
NYASH_E_NULL, // NULL参照
NYASH_E_BOUNDS, // 境界外アクセス
NYASH_E_MEMORY, // メモリ不足
NYASH_E_NOT_FOUND, // メソッド/プロパティ未定義
} nyash_status;
```
## 🚀 実装戦略3段階
### Phase 1: C Shim実装1-2週間
既存Rust実装へのCラッパーとして開始
```c
// plugins/nyash_abi_c/src/shim.c
nyash_status nyash_call_shim(nyash_ctx* ctx, void* obj,
nyash_selector sel, nyash_value* argv,
int argc, nyash_value* out) {
// Rust FFI経由で既存実装を呼び出し
extern nyash_status rust_nyash_call(/* ... */);
return rust_nyash_call(ctx, obj, sel, argv, argc, out);
}
```
### Phase 2: フルC実装1ヶ月
- 基本型Integer/String/Bool/Array/Mapの完全実装
- セレクターキャッシング機構
- アトミック参照カウント + 弱参照
- 型情報レジストリ
### Phase 3: Nyash再実装2ヶ月
- C実装をNyashで書き直し
- AOTコンパイルで同じC ABIを公開
- セルフホスティング達成!
## 🔧 パフォーマンス最適化
### セレクターキャッシングCodex提案
```c
// 文字列ルックアップは初回のみ
typedef struct {
uint32_t vtable_slot; // 解決済みvtableスロット
uint64_t cache_cookie; // インラインキャッシュ用
} nyash_selector;
// JITは直接vtable_slotを使用可能
```
### Tagged PointersGemini提案
- 64bitポインタの下位3bitをタグとして活用
- 小さな整数61bit、真偽値、nullをヒープ確保なしで表現
- `metadata & 0x7`でタグ判定、分岐なしアンボックス可能
## 📊 テスト戦略
### 適合性テストスイート
```bash
tests/abi/
├── conformance/ # ABI適合性テスト
├── memory/ # 参照カウント・弱参照テスト
├── threading/ # マルチスレッド安全性
├── performance/ # ベンチマーク1.5x以内目標)
└── compatibility/ # Rust/C実装の差分テスト
```
### ファジングCodex提案
- `nyash_value`エンコード/デコード
- `type_id`正規化
- 循環参照パターン
## 🌟 技術的革新性
### 1. ABI as a Box
「Everything is Box」哲学の完成形。ABIそのものがBoxとして扱われることで
- 実行時のABI切り替えが可能
- デバッグ用ABI、プロファイリング用ABIの動的ロード
- 異なるメモリ管理モデルGC等の実験が容易
### 2. セルフホスティングへの明確な道筋
1. **Rust製コンパイラ** → **C ABI上のNyashコンパイラ**をビルド
2. **Nyashコンパイラ****自分自身を再コンパイル**
3. Rust依存完全排除
### 3. 長期的保守性
- C ABIは最も安定した普遍的インターフェース
- プラットフォーム非依存
- 30年後も動作する設計
## 📝 配布と使用
### nyash.toml設定
```toml
[plugins.nyash_abi_provider]
path = "plugins/nyash_abi_provider.so"
abi = "c"
types = ["NyashABIProvider"]
capabilities = ["async", "weakref", "selector_cache"]
```
### Nyashコードでの使用
```nyash
// ABIプロバイダーの取得
local abiType = getTypeBox("NyashABIProvider")
local abi = abiType.create()
// セレクターキャッシングを活用した高速呼び出し
local strType = abi.lookupType("StringBox")
local lengthSel = abi.lookupSelector(strType, "length")
local str = abi.createValue(strType, "Hello World")
local len = abi.call(str, lengthSel, [])
print(len) // 11
```
## 🎯 まとめ
本設計により、Nyashは
- **Rust非依存**でセルフホスティング可能に
- **「Everything is Box」哲学**を完全実現
- **高性能**Tagged Pointers、セレクターキャッシング
- **安全**(アトミック参照カウント、弱参照)
- **拡張可能**(バージョニング、機能ビット)
これは単なる実装の変更ではなく、言語の哲学を技術で体現する、美しいアーキテクチャの完成です。

View File

@ -1,23 +1,33 @@
# Phase 12: Nyashコード共有エコシステム - Everything is Box の実現
## 🚀 最新ブレイクスルー (2025-09-01)
## 🚀 最新ブレイクスルー (2025-09-02)
### TypeBox統合ABI - プラグイン革命の実現
「Everything is Box」哲学の究極形態**型情報すらBoxとして扱う**TypeBoxにより、C ABI + Nyash ABIの完全統合を達成
### 🔥 セルフホスティングへの道 - ABIすらBoxとして扱う
「Everything is Box」哲学の究極形態**ABIそのものをBoxとして実装**することで、Rust依存を完全排除
```c
// TypeBox - 型情報をBoxとして扱う最小構造
// Nyash ABIもTypeBoxとして提供C言語実装
typedef struct {
uint32_t abi_tag; // 'TYBX'
const char* name; // "ArrayBox"
void* (*create)(void); // Box生成関数
} NyrtTypeBox;
uint32_t abi_tag; // 'NABI'
const char* name; // "NyashABIProvider"
void* (*create)(void); // ABIプロバイダ生成
// Nyash ABI操作Rust非依存
struct {
nyash_status (*call)(nyash_ctx*, void* obj, nyash_selector, ...);
void (*retain)(void* obj);
void (*release)(void* obj);
} nyash_ops;
} NyashABITypeBox;
```
**3大AI専門家の一致した結論**:
- **Codex**: 「TypeBoxブリッジは理想的なアーキテクチャ
- **ChatGPT5**: 「実装に耐える設計。10の改善点で完璧
- **Gemini**: 「Nyash哲学に最適なシンプルさ」
**AI専門家たちの深い考察**:
- **Gemini**: 「技術的妥当性が高く、言語哲学とも合致した、極めて優れた設計
- **Codex**: 「Feasible and attractive: 16バイトアライメント、セレクターキャッシング等の具体的実装提案
- **ChatGPT5**: 「統合ABI設計に10の改善点を提供」反映済み
### TypeBox統合ABI - プラグイン革命の実現!
「Everything is Box」哲学**型情報すらBoxとして扱う**TypeBoxにより、C ABI + Nyash ABIの完全統合を達成
## 🎯 重要な変更 (2025-09-01)
@ -131,15 +141,22 @@ void* map_keys(void* self, void* array_type_box) {
- VM層でC ABI/Nyash ABI/Scriptを自動判定
- Core-15 → Core-14 へ(命令数削減)
## 🛣️ 実装ロードマップ(TypeBox優先版)
## 🛣️ 実装ロードマップ(セルフホスティング対応版)
### Phase 12.0: TypeBox統合ABI実装1週間🆕
- [ ] nyrt_typebox.h完全ヘッダー定義
- [ ] Rust FFIミラー実装
- [ ] nyrt_typebox.h完全ヘッダー定義16バイトアライメント
- [ ] セレクターキャッシング機構
- [ ] MapBox両ABI実装実証テスト
- [ ] 所有権ファズテスト
- 📄 **[統合ABI設計仕様書](./UNIFIED-ABI-DESIGN.md)**
### Phase 12.0.5: Nyash ABI C実装2週間🔥🆕
- [ ] C Shim実装既存Rustへのラッパー
- [ ] 基本型のC完全実装Integer/String/Bool
- [ ] アトミック参照カウント + 弱参照
- [ ] 適合性テストスイート
- 📄 **[Nyash ABI C実装設計書](./NYASH-ABI-C-IMPLEMENTATION.md)**
---
## 現状サマリ2025-09-02
@ -174,6 +191,7 @@ void* map_keys(void* self, void* array_type_box) {
### 🎯 主要設計ドキュメント
- **[統合ABI設計仕様書](./UNIFIED-ABI-DESIGN.md)** ← 🆕🚀 C ABI + Nyash ABI統合の完全設計**3大AI専門家検証済み**
- **[C ABI TypeBox設計仕様書](./C-ABI-BOX-FACTORY-DESIGN.md)** ← 🆕 シンプルなプラグイン間Box生成
- **[Nyash ABI C実装設計書](./NYASH-ABI-C-IMPLEMENTATION.md)** ← 🆕🔥 セルフホスティング実現!**Gemini/Codex絶賛**
- **[Nyash ABI統合設計図](./NYASH-ABI-DESIGN.md)** ← 将来拡張用の高度なABI
- [export/import仕様](./export-import-spec.md)
- [パッケージマネージャー設計](./package-manager-design.md)

View File

@ -1,6 +1,6 @@
# Phase 12 Task Board (v1)
# Phase 12 Task Board (v2 - セルフホスティング対応)
目的: C ABI を壊さず、TypeBox + 統一ディスパッチで Nyash ABI を段階導入。MIR→VM→JIT を「綺麗な箱」で統一。
目的: C ABI を壊さず、TypeBox + 統一ディスパッチで Nyash ABI を段階導入。MIR→VM→JIT を「綺麗な箱」で統一。**最終的にRust依存を排除し、セルフホスティングを実現。**
## Tier-0直近・安全に積める
- [x] MapBoxの実用拡張stringキー/便利API
@ -27,6 +27,20 @@
- 選択肢A: ランタイムで ArrayBox を構築
- 選択肢B: Mapプラグインに KeysArrayBox を同梱(要設定追加)
## Tier-3セルフホスティング🔥新規
- [ ] Nyash ABI C実装の開始
- [ ] nyash_abi_provider.h定義16バイトアライメント
- [ ] C Shim実装Rust FFI経由
- [ ] 基本型実装Tagged Pointers対応
- [ ] アトミック参照カウント実装
- [ ] 弱参照による循環参照対策
- [ ] セレクターキャッシング実装
- [ ] lookup_selector API
- [ ] JIT統合vtable_slot直接呼び出し
- [ ] 適合性テストスイート構築
- [ ] Rust/C実装の差分テスト
- [ ] パフォーマンス測定1.5x以内)
## ドキュメント/管理
- [ ] UNIFIED-ABI-DESIGN.md の「最小導入プロファイル」明記
- [ ] VM/JIT実装メモ統一ディスパッチの呼出し順
@ -38,10 +52,12 @@
- GCセーフポイントのMAY_BLOCK以外の一般化
- keys()/values() の正式ArrayBox返却現状はシム
- AOT(LLVM)のbuild失敗nyrt借用修正、後回し方針
- Nyash ABI C実装セルフホスティングの要🔥新規
## Doneの定義Phase 12
## Doneの定義Phase 12 - 更新版
1) TypeBoxレジストリと統一ディスパッチがVMに入り、C ABI互換で全プラグインが動作
2) 1プラグインでNyash ABIの成功パスが通るVM/JIT
3) keys()/values() が ArrayBox 返却で安定
4) 基本の所有権・セーフポイントルールが守られる
5) **Nyash ABI C実装の基礎が動作し、セルフホスティングへの道筋が明確**🔥新規

View File

@ -0,0 +1,134 @@
Nyash ABIをC実装TypeBoxで提供する設計案
========================================
【核心的アイデア】
Nyash ABIそのものをTypeBoxC ABIとして実装することで、
Rust依存を排除し、セルフホスティングへの道を開く。
【基本構造】
1. Nyash ABIもTypeBoxの一種として定義
2. C言語で完全実装Rust非依存
3. 既存のプラグインシステムで配布可能
【実装詳細】
■ TypeBox定義
```c
// nyash_abi_provider.h
typedef struct {
// TypeBox標準ヘッダ
uint32_t abi_tag; // 'NABI'
const char* name; // "NyashABIProvider"
void* (*create)(void); // プロバイダインスタンス生成
// Nyash ABI専用拡張
struct {
void* (*create_value)(uint64_t type_id, void* data);
void* (*invoke_method)(void* obj, const char* method, void* args[], int argc);
void (*retain)(void* value);
void (*release)(void* value);
} nyash_ops;
} NyashABITypeBox;
```
■ NyashValueC構造体版
```c
typedef struct {
uint64_t type_id; // 型識別子
uint64_t box_handle; // ポインタまたはインライン値
uint64_t metadata; // フラグ・追加情報
} NyashValue_C;
```
■ 実装戦略
Phase 1: 最小C実装
------------------
- 基本型Integer/String/Boolのみサポート
- シンプルなメソッド呼び出し
- plugins/nyash_abi_c/ として実装
Phase 2: フル機能実装
-------------------
- 全Box型サポート
- エラーハンドリング
- 非同期サポート
Phase 3: Nyashで再実装
--------------------
- C実装をNyashで書き直し
- セルフホスティング達成
【利点】
1. Rust完全非依存
2. 既存インフラTypeBox/C ABI活用
3. 段階的移行可能
4. セルフホスティング対応
【実装例】
```c
// nyash_abi_impl.c
static NyashValue_C call_method_c(
const char* type_name,
const char* method,
void* instance,
NyashValue_C* args,
int argc
) {
// StringBoxの例
if (strcmp(type_name, "StringBox") == 0) {
if (strcmp(method, "length") == 0) {
char* str = (char*)instance;
int len = strlen(str);
return (NyashValue_C){
.type_id = TYPE_INTEGER,
.box_handle = (uint64_t)len,
.metadata = INLINE_FLAG
};
}
}
// 他のBox型も同様に実装...
}
```
【配布方法】
```toml
# nyash.toml
[plugins.nyash_abi_provider]
path = "plugins/nyash_abi_provider.so"
abi = "c"
types = ["NyashABIProvider"]
```
【使用例Nyashコード
```nyash
// TypeBox経由でNyash ABIプロバイダ取得
local abiType = getTypeBox("NyashABIProvider")
local abi = abiType.create()
// Nyash ABIで呼び出し
local str = abi.createValue(TYPE_STRING, "Hello")
local len = abi.invoke(str, "length", [])
print(len) // 5
```
【移行パス】
1. 現在: Rust実装のNyash ABI
2. Phase 12.5: C実装のNyash ABIプロバイダ追加
3. Phase 13: プロバイダ経由に移行
4. Phase 14: Nyashでプロバイダ再実装
5. Phase 15: 完全セルフホスティング
【技術的課題と解決】
- メモリ管理 → 参照カウントCで実装
- 型安全性 → type_idで厳密チェック
- パフォーマンス → インライン値で最適化
- 互換性 → 既存Rust実装と同じインターフェース
【結論】
TypeBoxシステムを使ってNyash ABIをC実装すれば、
Rust依存を排除しつつ、既存のエコシステムを活用して
スムーズにセルフホスティングへ移行できる。
「Everything is Box」の究極形ABIすらBoxとして扱う

View File

@ -0,0 +1,37 @@
# Nyash ABI議論アーカイブ
このディレクトリには、Nyash ABIの設計に関する重要な議論や考察が保存されています。
## 📚 ドキュメント一覧
### 🌟 AI専門家の深い考察
- **[gemini-codex-deep-thoughts.md](gemini-codex-deep-thoughts.md)** - Gemini先生とCodex先生によるNyash ABI C実装の深い考察2025年9月2日
- セルフホスティング実現への技術的妥当性
- 具体的な実装提案16バイトアライメント、セレクターキャッシング等
- 哲学的観点からの分析
### 🎯 設計の進化過程
- 初期提案: 複雑なFactory設計
- 転換点: 「型をC ABIの箱として渡す共通ルール」という洞察
- 最終形: TypeBox + Nyash ABI C実装による統一設計
## 💡 重要な洞察
### 「Everything is Box」の究極形
ABIそのものをBoxとして扱うことで、言語の哲学が技術的実装と完全に一致しました。
### セルフホスティングへの道
1. C Shim実装既存Rustへのラッパー
2. フルC実装基本型・参照カウント
3. Nyashで再実装AOTでC ABI公開
4. Nyashコンパイラ自身をNyashで実装
### AI専門家の評価
- **Gemini**: 「技術的妥当性が高く、言語哲学とも合致した、極めて優れた設計」
- **Codex**: 「Feasible and attractive: ABI-as-Box completes the idea」
- **ChatGPT5**: 「実装に耐える設計。10の改善点で完璧」
## 📝 関連ドキュメント
- [../NYASH-ABI-C-IMPLEMENTATION.md](../NYASH-ABI-C-IMPLEMENTATION.md) - 実装仕様書
- [../UNIFIED-ABI-DESIGN.md](../UNIFIED-ABI-DESIGN.md) - 統合ABI設計
- [../README.md](../README.md) - Phase 12概要

View File

@ -0,0 +1,235 @@
# Gemini先生とCodex先生のNyash ABI C実装についての深い考察
2025年9月2日、Nyashのセルフホスティング実現に向けて、2人のAI専門家が深い考察を提供しました。
## 🌟 Gemini先生の考察
### 総評
**「技術的妥当性が高く、言語哲学とも合致した、極めて優れた設計」**
### 1. 技術的妥当性
#### C言語によるNyash ABI実装の現実性
- **現実的です。** C言語は、OSのカーネルから他のプログラミング言語のランタイムまで、システムコンポーネントを記述するためのデファクトスタンダードです。
- 参照カウント、動的な型情報メソッドテーブルなどの管理、メモリレイアウトの精密な制御といった、ABIの実装に必要な低レベルな操作は、すべてC言語の得意分野です。
#### TypeBoxシステムとの統合の自然さ
- **極めて自然です。** TypeBoxがC ABIベースのプラグインシステムであるため、Cで実装されたNyash ABIをTypeBoxの一種として動的にロードする、というアイデアは既存の仕組みに完璧に乗っかります。
- `abi_tag: 'NABI'` のような識別子で他のTypeBoxと区別するのも、クリーンで拡張性の高い方法です。
- これは、システムの複雑性を爆発させることなく、コア機能の差し替えを実現するエレガントなソリューションです。
#### セルフホスティングへの道筋の明確さ
- **明確かつ論理的です。** 提示された3段階の移行戦略は、セルフホスティングを達成するための古典的かつ実績のあるブートストラップ手順を踏んでいます。
1. **Rust製コンパイラ** を使って、**C実装ABI**上で動く **Nyash製コンパイラ** をコンパイルする。
2. 生成された **Nyash製コンパイラ** を使って、**それ自身を再度コンパイル**する。
- この時点でRustツールチェインへの依存が切れ、セルフホスティングが達成されます。
### 2. 実装上の課題と解決策
#### メモリ管理の具体的な実装方法
- **参照カウント:** 提案通り、参照カウントが基本になります。
- 具体的には、Nyashの各Boxオブジェクトが確保するメモリブロックのヘッダ部分に、参照カウント数を格納するフィールド例: `atomic_size_t ref_count;`)を設けます。
- `retain` / `release` は、このカウンタを**アトミック操作**で増減させる必要があります。これにより、マルチスレッド環境下でも安全なメモリ管理が保証されます。C11の `<stdatomic.h>` が利用できます)
- **循環参照への対策:** 初期段階では「循環参照は未定義動作(メモリリーク)」と割り切ることも可能ですが、長期的には**弱参照Weak Reference**の仕組みをABIレベルで導入することを強く推奨します。
#### 型安全性をどう保証するか
- `type_id` が鍵となります。これは単なる整数ではなく、**グローバルな型情報テーブルへのインデックス(またはポインタ)**として機能させるべきです。
- このテーブルには、型名、メソッドテーブル(メソッド名と関数ポインタのマップ)、親の型への参照などの情報が含まれます。
- `invoke_method` を実行する際は、まずオブジェクトの `type_id` から型情報を引き、メソッドテーブル内に要求されたメソッドが存在するかを検証します。
#### パフォーマンスへの影響
- **ディスパッチのオーバーヘッド:** 文字列比較によるメソッド検索は遅延の原因になります。これを緩和するため、コンパイル時にメソッド名をハッシュ化し、ランタイムでは整数(ハッシュ値)で比較する方法が効果的です。
- **インライン値Tagged Pointers:** `NyashValue_C` の設計はパフォーマンスの鍵です。64bit環境では、ポインタの下位ビットがアラインメントにより常に0であることを利用し、このビットを「タグ」として使うことで、小さな整数や真偽値などをポインタに直接埋め込めます。
### 3. 段階的移行戦略
#### 既存Rust実装との共存方法
- 移行期間中、Nyashランタイムは**2種類のBox表現Rustネイティブ版とC ABI版を同時に扱える**必要があります。
- 両者の間で値をやり取りするための**ブリッジ(変換層)**が不可欠です。
- 最初は、コアな組み込み型はRust実装のまま、新しいプラグインや一部のモジュールをC ABI版で実装していくのが安全な進め方でしょう。
#### 互換性維持とテスト戦略
- **ABIインターフェースの凍結:** `nyash_ops` の関数シグネチャとセマンティクス(所有権のルールなど)を一度定義したら、それを厳格に守ることが極めて重要です。
- **大規模なテストスイート:** 移行を成功させるには、テストがすべてを決定します。
1. **振る舞いの一致テスト:** 同じNyashソースコードを「Rust ABIのみ」「C ABIのみ」「両者混在」の3つのモードで実行し、出力や結果が完全に一致することを検証するテストスイートを構築します。
2. **ユニットテスト:** Cで実装されたABIの各関数`create_value`, `retain`, `release`などを、Cのテストフレームワーク例: `check`)で徹底的にテストします。
3. **ベンチマーク:** 各フェーズでパフォーマンスを計測し、意図しない性能劣化(リグレッション)が起きていないかを常に監視します。
### 4. 哲学的な観点
#### 「Everything is Box」哲学との整合性
- **完璧に整合しています。** これは「Everything is Box」という哲学の究極的な表現です。
- 言語を構成するユーザーレベルのオブジェクトだけでなく、言語の実行基盤であるABIそのものまでもが「Box」という統一された概念で扱われる。
- これは、LISPがコードとデータをS式で統一的に扱う美しさに通じる、自己言及的なエレガンスを持っています。
#### ABIをBoxとして扱うことの意味
- これは、**言語の振る舞いを定義する「メタオブジェクト」**を導入することに他なりません。
- これにより、Nyashは自分自身の実行セマンティクスすら、理論上は動的に差し替えたり拡張したりできる可能性を秘めることになります。
- 例えば、デバッグ用のABI、プロファイリング用のABI、あるいは全く異なるメモリ管理モデル例: GCを持つABIを、同じTypeBoxの仕組みでロードすることも夢ではありません。
### 5. 他の選択肢との比較
#### Rust依存を維持する場合
- 実装は楽ですが、言語としての独立性を永遠に失います。
- Nyashをビルドするのに常にRustが必要というのは、言語のポータビリティと自己完結性を著しく損ないます。
#### 他のセルフホスティング戦略(例: LLVMへのコンパイル
- LLVM IRのような中間言語にコンパイルするのも強力な戦略です。
- しかし、それはNyashの実行モデルをLLVMのモデルにマッピングする作業であり、依存先がRustからLLVMに変わるだけとも言えます。
- ご提案の「ABIのBox化」は、**Nyash自身の実行モデルを維持したまま独立を果たす**という点で、より自己完結的で野心的なアプローチです。
#### 長期的な保守性
- C ABIは、コンピューティングの世界で最も安定し、普遍的なインターフェースです。
- ここに基盤を置くことで、Nyashは将来にわたって非常に高い安定性とポータビリティを獲得できます。
### 結論と最終的なアドバイス
ご提案の設計は、Nyashを真に独立した言語へと飛躍させ、その哲学を完成させるための、**実装可能かつ美しいブループリント**です。この方向性で進むことを強く推奨します。
**追加のアドバイス:**
- **所有権ルールの厳密な定義:** ABIの関数呼び出しにおける値の所有権誰が`release`の責任を持つか)を、ドキュメントで厳密に定義してください。
- **エラーハンドリング:** `invoke_method`などが失敗した場合に、どのようにエラー情報(型ミスマッチ、メソッド未定義など)を呼び出し元に伝えるか。
---
## 🔧 Codex先生の考察
### Executive Summary
- Feasible and attractive: treating the Nyash ABI itself as a TypeBox (C ABI) is a clean way to deRust the runtime boundary while aligning with "Everything is Box".
- Key to success: keep the ABI surface minimal, versioned, allocator/contextcentric, and futureproofed; treat reflection, invocation, and async as Boxes too.
- Migration: start as a C shim over current Rust NyRT, run conformance tests in parallel, then swap implementations behind the same ABI, and finally reimplement in Nyash.
### Technical Feasibility
- C implementation: realistic if the ABI is small, pure C (no exceptions), with explicit lifetimes, error/status returns, and allocator control. Similar precedents exist (CPython C-API, Lua C API, COMstyle vtables).
- TypeBox integration: natural fit if the ABI object is "just another Box" exposing a stable vtable plus discovery via `nyash.toml`/plugin loader.
- Selfhosting path: clear when the compiler and runtime only depend on the C ABI Box; the compiler written in Nyash can build itself by linking against that Box.
### ABI Shape: Recommended Adjustments
- Versioning and size: include `api_version` and `struct_size` in the TypeBox header so older loaders can detect compatibility.
- Context first: most functions accept a `nyash_ctx*` holding allocator, scheduler, TLS, and feature flags; this avoids global state.
- Status + outparams: adopt `nyash_status` enum return, with outputs via outparams; do not return ownership in a raw return position.
- Object model: make every heap object implement retain/release via a common header/layout and expose a `nyash_obj_vtable` for method lookup.
- Method invocation: prefer selector/handle lookup over raw string calls. Pattern:
- `nyash_status lookup_selector(ctx, type_id, name, out nyash_selector*)`
- `nyash_status call(ctx, obj, selector, argv, argc, out result)`
- Allows caching and JIT fast paths; string lookup happens at most once per callsite.
### Minimal core surface:
- `retain(obj)`, `release(obj)`
- `type_of(value) -> type_id`
- `is_null`, `eq`, `hash`
- `lookup_selector`, `call`
- `create_value(type_id, data, flags)`
- `alloc`, `free`, `mem_stats` via `nyash_allocator`
- `error_new`, `error_code`, `error_message` (errors are Boxes)
- Async primitives as Boxes (see below)
- Binary hygiene: add `vendor_tag`, `abi_tag = 'NABI'`, reserved fields, and explicit alignment requirements.
### Value Layout and Type Identity
- `nyash_value`: 16byte payload recommended for portability and JIT friendliness:
- `u64 type_id; u64 payload; u64 meta;` or `u64[2] payload` if you want 128bit immediates later. Ensure 16byte alignment for vector ops and stable lowering in LLVM.
- Inline vs heap:
- Use low meta bits for immediate tags (small int, bool, null, small enum).
- Heap payloads are opaque pointers to refcounted objects with a common header.
- `type_id`: stable 64bit value with namespacing: top 16 bits vendor, 8 bits kind (struct, enum, trait/interface, array, func), remaining bits a stable hash of the fullyqualified name + version.
### Memory Model
- Intrusive refcount header: for all heap Boxes:
- `struct header { atomic_uintptr_t rc; const nyash_obj_vtable* vtable; u64 type_id; u64 flags; }`
- Thread safety: use atomic increments/decrements; defer destruction on the owning scheduler thread if the vtable marks "affine".
- Cycle handling: three options; pick one early and document:
- No crosscycle guarantee, plus "weakref" Boxes and explicit `close()` for graph owners (lowest complexity).
- Trialdeferred cycle detection (BaconRajan) at safepoints.
- Arena/region Boxes for compiler/IR lifetimes (good for selfhosting).
- Allocation: `nyash_allocator` in `nyash_ctx` allows embedding, custom arenas, and leak accounting. Every allocation path must route through it.
### Type Safety Guarantees
- Validate `type_id` on every API entry that consumes a `nyash_value`. Return `NYASH_E_TYPE`.
- Provide `nyash_cast(ctx, value, target_type_id, out value2)` that performs runtime checks (and potentially conversion) in one place.
- For generics/parametric types, define a "type constructor" `type_id` plus encoded parameters hashed into a derived `type_id`.
### Performance Considerations
- Selector caching: make `nyash_selector` a stable handle (contains resolved vtable slot + inline cache cookie). JIT can inline calls directly via the slot.
- Avoid string dispatch in hot paths: strings resolve only once per callsite; ABI preserves handles to avoid repeated lookups.
- Small immediates: keep i31/i61, bool, small enum as immediates; `meta` carries tag; JIT emits zerobranch unbox.
- Error handling: status codes + separate error Box avoids exceptions; zerooverhead fast path.
- Marshaling: keep `argv` as a flat `nyash_value*` slice; for varargs heavy sites, support `nyash_tuple` Box to amortize allocations.
- Layout stability: document alignment and endianness; avoid bitfields in the ABI; use masks and shifts.
### Async and Errors
- Async as Box: define `nyash_future` TypeBox with
- `poll(ctx, self, out ready, out result_or_err)`
- `awaitable` integration at the language level; scheduler belongs to `nyash_ctx`.
- Cancellation: `cancel(ctx, self, reason)`; guarantee idempotence.
- Errors as Box: `nyash_error` carries `code`, `message`, `data` (Box). Every API returning nonOK can also optionally fill an out error Box.
### Versioning and Compatibility
- Feature negotiation: `supports(ctx, feature_id)` and a `capabilities` bitmask in the provider header.
- Semantic version in header, strict size check: reject if `struct_size < required`.
- Reserved fields: pad both the provider and object vtables with reserved pointers for forward extension.
- Crossplatform: define `NYASH_ABI_API` macro for visibility/calling convention; test x86_64 Linux, macOS, Windows (MSVC) early.
### Coexistence and Migration
- Phase 1 (C shim over Rust):
- Implement the C TypeBox provider whose functions forward to existing Rust NyRT via `extern "C"` glue. This validates the ABI without rewriting runtime logic.
- Place under `plugins/nyash_abi_c/` and add mapping in `nyash.toml`.
- Phase 2 (feature parity in C):
- Incrementally reimplement hot paths: small immediates, retain/release, allocator, string, array. Keep complex features (async, reflection) temporarily forwarded to Rust until replaced.
- Phase 3 (Nyash reimplementation):
- Recode the C provider in Nyash, but keep the exact same C ABI surface via an AOT target producing the same symbols.
- Coexistence:
- Loader picks provider by name and version from `nyash.toml`. Keep Rust and C providers shippable concurrently; choose via env (`NYASH_ABI_IMPL=c,rust`).
- Compatibility:
- Add a conformance suite that exercises only the ABI; run it against both providers until results match.
### Testing Strategy
- Conformance tests under `tests/abi/`:
- Retain/release semantics, crossthread retain, immediate encoding, selector lookup caching, error propagation, async poll semantics.
- Fuzz/property tests for `nyash_value` encode/decode and `type_id` canonicalization.
- ABI stability:
- Generate a C header from a single source of truth; forbid breaking changes unless version bumps.
- Integration smokes:
- Use `tools/llvm_smoke.sh` with `NYASH_C_ABI=1` to validate JIT/AOT endtoend with the C provider loaded.
### Philosophical Fit
- ABIasBox completes the idea that "runtime powers" are themselves values. It turns reflection, invocation, and scheduling into firstclass participants rather than privileged side channels.
- Beauty comes from uniform dispatch: the compiler, runtime, and plugins all talk through the same Box vocabulary with selectors and capabilities.
### Alternatives and Tradeoffs
- Keep Rust dependency:
- Pro: faster to evolve; borrowchecker catches many bugs.
- Con: selfhosting depends on Rust toolchain; ABI surface must still be C for plugins; harder for other ecosystems to embed.
- WASM/WASI ABI:
- Pro: portable sandbox, good for plugins.
- Con: host interop and lowlatency GC/RC semantics are harder; JIT integration overhead.
- Minimal microkernel runtime in C + highlevel services in Rust:
- Pro: balance; critical ABI in C, complex features in Rust behind handles.
- Con: more moving parts, boundary crossings remain.
### Concrete Next Steps
- Define and freeze a v0 ABI header:
- Add `api_version`, `struct_size`, `nyash_ctx*`, `nyash_allocator*`, `nyash_status`, `nyash_value` 16byte layout, `retain/release`, `lookup_selector`, `call`, `error` primitives, and capability bits.
- Scaffold `plugins/nyash_abi_c/`:
- Provide a stub provider that returns `NYASH_E_NOT_IMPL` but passes header/version checks; wire it in `nyash.toml`.
- Add a conformance test crate in `tests/abi/` that loads the provider by name and validates the header, alloc, retain/release, and immediate encodes.
- Implement small immediates + retain/release + strings:
- Backed by a simple threadsafe RC and arena allocator in C.
- Introduce selector caching in the VM/JIT:
- Plumb `nyash_selector` handles in the call path; deopt to string lookup on cache miss.
If you want, I can draft the minimal v0 header (with versioning/capabilities and 16byte value layout) and a stub `plugins/nyash_abi_c` skeleton that loads in the current repo, plus a small conformance test to exercise header negotiation.
---
## まとめ
両AI専門家が一致して、Nyash ABIをC実装TypeBoxとして提供する設計案を高く評価しています。
共通する重要ポイント:
1. **技術的に実現可能** - C言語でのABI実装は現実的で実績もある
2. **哲学的に美しい** - Everything is Boxの究極的表現
3. **段階的移行が鍵** - C Shim → フル実装 → Nyash再実装
4. **パフォーマンス最適化** - Tagged Pointers、セレクターキャッシング
5. **セルフホスティング実現** - Rust依存を完全に排除可能
この深い考察により、Nyashのセルフホスティングへの道筋が明確になりました。