Phase 12: 統一TypeBox ABI実装開始 - ChatGPT5による極小コアABI基盤構築

- TypeBox ABI雛形: メソッドスロット管理システム追加
- Type Registry: Array/Map/StringBoxの基本メソッド定義
- Host API: C ABI逆呼び出しシステム実装
- Phase 12ドキュメント整理: 設計文書統合・アーカイブ化
- MIR Builder: クリーンアップと分離実装完了

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

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Moe Charm
2025-09-03 05:04:56 +09:00
parent e2e25f6615
commit 53d88157aa
84 changed files with 4739 additions and 2750 deletions

View File

@ -0,0 +1,307 @@
# Nyash Export/Import構文仕様 v1.0
## 🎯 概要
Nyashのコード共有エコシステムを実現するための`export`/`import`構文仕様。「Everything is Box」哲学に基づき、Boxを中心とした明快な構文を提供する。
## 📝 基本構文
### Export構文
```nyash
# 単一Boxのエクスポート
export box MathUtils {
init { precision }
factorial(n) {
if n <= 1 { return 1 }
return n * me.factorial(n - 1)
}
fibonacci(n) {
if n <= 1 { return n }
return me.fibonacci(n - 1) + me.fibonacci(n - 2)
}
}
# Static Boxのエクスポート
export static box Constants {
init { }
PI = 3.14159265359
E = 2.71828182846
GOLDEN_RATIO = 1.61803398875
}
# 複数Boxの名前付きエクスポート
export {
MathUtils,
Constants,
StringHelpers as StrUtils # エイリアス付き
}
# デフォルトエクスポート
export default box Calculator {
init { display }
// ...
}
```
### Import構文
```nyash
# 名前付きインポート
import { MathUtils } from "math_utils.ny"
import { MathUtils, Constants } from "math_lib.ny"
# エイリアス付きインポート
import { MathUtils as Math } from "math_utils.ny"
# デフォルトインポート
import Calculator from "calculator.ny"
# 全体インポート(名前空間)
import * as MathLib from "math_lib.ny"
# 複合インポート
import Calculator, { MathUtils, Constants } from "advanced_calc.ny"
```
## 🔧 モジュール解決
### ファイルパス解決
```nyash
# 相対パス
import { Utils } from "./utils.ny"
import { Common } from "../common/helpers.ny"
# パッケージ名nyash_modules/から)
import { Logger } from "awesome-logger"
# 絶対パス(非推奨、移植性のため)
import { Config } from "/home/user/project/config.ny"
```
### 解決順序
1. 相対パス(`./`または`../`で始まる)
2. `nyash_modules/`ディレクトリ
3. グローバルパッケージディレクトリ(設定可能)
4. 絶対パス
## 📦 パッケージ構造
### 基本的なパッケージ構成
```
my-math-package/
├── nyash.toml # パッケージメタデータ
├── src/
│ ├── index.ny # メインエントリーポイント
│ ├── utils.ny
│ └── advanced.ny
├── tests/
│ └── test_math.ny
└── README.md
```
### nyash.toml
```toml
[package]
name = "awesome-math"
version = "1.0.0"
description = "素晴らしい数学ユーティリティ"
author = "Nyash Developer"
license = "MIT"
[dependencies]
# 他のNyashパッケージへの依存
basic-utils = "^2.0.0"
[export]
# パッケージのメインエクスポート
main = "src/index.ny"
```
### index.nyエントリーポイント
```nyash
# 内部モジュールをインポート
import { InternalUtils } from "./utils.ny"
import { AdvancedMath } from "./advanced.ny"
# 外部にエクスポート
export {
InternalUtils as Utils,
AdvancedMath
}
# デフォルトエクスポート
export default box MathPackage {
init {
me.utils = new Utils()
me.advanced = new AdvancedMath()
}
}
```
## 🚀 高度な機能
### 条件付きエクスポート
```nyash
# プラットフォーム別エクスポート
if PLATFORM == "web" {
export { WebLogger as Logger } from "./web_logger.ny"
} else {
export { ConsoleLogger as Logger } from "./console_logger.ny"
}
```
### 再エクスポート
```nyash
# 他のモジュールから再エクスポート
export { MathUtils } from "./math_utils.ny"
export * from "./string_helpers.ny"
```
### 動的インポート(将来拡張)
```nyash
# 実行時に動的にインポート
local dynamicModule = await import("./heavy_module.ny")
local HeavyBox = dynamicModule.HeavyBox
```
## 🔒 スコープとアクセス制御
### プライベートメンバー
```nyash
export box SecureBox {
init {
_privateData # アンダースコアプレフィックスは慣習的にプライベート
publicData
}
# プライベートメソッド(エクスポートされない)
_internalProcess() {
// 内部処理
}
# パブリックメソッド
process() {
return me._internalProcess()
}
}
```
## 🎯 実装優先順位
### Phase 1: 基本機能(必須)
- [ ] `export box`構文
- [ ] `import { Box } from "file"`構文
- [ ] 相対パス解決
- [ ] 基本的な循環参照チェック
### Phase 2: 拡張機能(推奨)
- [ ] `export default`
- [ ] `import * as namespace`
- [ ] エイリアス(`as`
- [ ] nyash_modules/ディレクトリサポート
### Phase 3: 高度な機能(オプション)
- [ ] 条件付きエクスポート
- [ ] 再エクスポート
- [ ] 動的インポート
- [ ] パッケージマネージャー統合
## ⚠️ 制約事項
1. **循環参照の禁止**
```nyash
# ❌ エラー: 循環参照
# a.ny: import { B } from "./b.ny"
# b.ny: import { A } from "./a.ny"
```
2. **トップレベルでのみ許可**
```nyash
# ✅ OK
import { Utils } from "./utils.ny"
# ❌ エラー: 関数内でのインポート
box MyBox {
method() {
import { Helper } from "./helper.ny" # エラー!
}
}
```
3. **export前の参照禁止**
```nyash
# ❌ エラー: 定義前のエクスポート
export { UndefinedBox } # エラー!
box UndefinedBox { }
```
## 🔄 他言語との比較
| 機能 | Nyash | JavaScript | Python | Rust |
|------|-------|------------|--------|------|
| 名前付きexport | ✅ | ✅ | ✅ | ✅ |
| デフォルトexport | ✅ | ✅ | ❌ | ❌ |
| 名前空間import | ✅ | ✅ | ✅ | ✅ |
| 動的import | 🔄 | ✅ | ✅ | ❌ |
| 再export | ✅ | ✅ | ✅ | ✅ |
## 📚 使用例
### 数学ライブラリ
```nyash
# math_lib.ny
export box Vector2D {
init { x, y }
add(other) {
return new Vector2D(me.x + other.x, me.y + other.y)
}
magnitude() {
return Math.sqrt(me.x * me.x + me.y * me.y)
}
}
export static box MathConstants {
init { }
TAU = 6.28318530718
}
```
### 使用側
```nyash
# game.ny
import { Vector2D, MathConstants } from "./math_lib.ny"
box Player {
init {
me.position = new Vector2D(0, 0)
me.velocity = new Vector2D(1, 1)
}
update() {
me.position = me.position.add(me.velocity)
local angle = MathConstants.TAU / 4 # 90度
}
}
```
---
*Everything is Box - そしてBoxは共有される*

View File

@ -0,0 +1,328 @@
# Nyashパッケージマネージャー設計書 v1.0
## 🎯 概要
Nyashのコード共有エコシステムを支える、シンプルで直感的なパッケージマネージャー「nypm (Nyash Package Manager)」の設計。
## 📊 設計原則
1. **シンプルさ優先** - npmの良い部分を参考に、複雑さを避ける
2. **Everything is Box** - パッケージもBoxの集合として扱う
3. **明示性** - 依存関係は常に明確に
4. **高速性** - 並列ダウンロード、効率的なキャッシュ
## 🔧 基本コマンド
### パッケージのインストール
```bash
# 依存関係をインストール
nyash install
# 特定パッケージをインストール
nyash install awesome-math
nyash install awesome-math@1.2.0
# 開発依存として追加
nyash install --dev test-framework
# グローバルインストール
nyash install -g nyash-formatter
```
### パッケージの公開
```bash
# パッケージを公開
nyash publish
# ドライラン(実際には公開しない)
nyash publish --dry-run
# アクセス制御付き公開
nyash publish --access public
```
### その他のコマンド
```bash
# パッケージ初期化
nyash init
# 依存関係の更新
nyash update
nyash update awesome-math
# パッケージの削除
nyash uninstall awesome-math
# 依存関係ツリーの表示
nyash list
nyash list --depth=0
# パッケージ検索
nyash search math
# パッケージ情報表示
nyash info awesome-math
```
## 📦 パッケージ構造
### ディレクトリ構成
```
my-awesome-package/
├── nyash.toml # パッケージマニフェスト
├── src/
│ ├── index.ny # メインエントリーポイント
│ └── lib/
│ └── utils.ny
├── tests/
│ └── test_main.ny
├── docs/
│ └── README.md
├── examples/
│ └── basic_usage.ny
└── .nyashignore # 公開時の除外ファイル
```
### nyash.toml仕様
```toml
[package]
name = "awesome-math"
version = "1.0.0"
description = "高度な数学計算ライブラリ"
author = "Nyash Developer <dev@example.com>"
license = "MIT"
repository = "https://github.com/user/awesome-math"
keywords = ["math", "calculation", "algebra"]
# メインエントリーポイント
main = "src/index.ny"
# 最小Nyashバージョン
nyash = ">=1.0.0"
[dependencies]
# 実行時依存
basic-utils = "^2.0.0"
string-helpers = "~1.5.0"
[dev-dependencies]
# 開発時のみ必要
test-framework = "^3.0.0"
mock-library = "^1.2.0"
[scripts]
# カスタムスクリプト
test = "nyash test tests/"
build = "nyash compile src/"
lint = "nyash-lint src/"
```
### バージョン指定
```toml
# 正確なバージョン
"1.2.3"
# 互換性のあるバージョン(推奨)
"^1.2.3" # >=1.2.3 <2.0.0
# 近似バージョン
"~1.2.3" # >=1.2.3 <1.3.0
# 範囲指定
">=1.0.0 <2.0.0"
# ワイルドカード
"1.2.*" # >=1.2.0 <1.3.0
```
## 🗂️ ローカルレジストリ
### nyash_modules構造
```
project/
├── nyash.toml
├── src/
│ └── main.ny
└── nyash_modules/ # 依存パッケージ格納場所
├── awesome-math/
│ ├── nyash.toml
│ └── src/
├── string-helpers/
│ ├── nyash.toml
│ └── src/
└── .cache/ # ダウンロードキャッシュ
```
### パッケージ解決アルゴリズム
1. 現在のディレクトリの`nyash_modules/`をチェック
2. 親ディレクトリを再帰的に探索
3. グローバルインストールディレクトリをチェック
4. 見つからない場合はエラー
## 🌐 中央レジストリ
### レジストリAPI
```
GET /packages/{name} # パッケージ情報取得
GET /packages/{name}/versions # バージョン一覧
GET /packages/{name}/{version} # 特定バージョン情報
POST /packages # パッケージ公開
GET /search?q={query} # パッケージ検索
```
### パッケージメタデータ
```json
{
"name": "awesome-math",
"version": "1.0.0",
"description": "高度な数学計算ライブラリ",
"author": {
"name": "Nyash Developer",
"email": "dev@example.com"
},
"repository": "https://github.com/user/awesome-math",
"downloads": {
"last_day": 150,
"last_week": 1200,
"last_month": 5000
},
"versions": ["1.0.0", "0.9.0", "0.8.0"],
"dependencies": {
"basic-utils": "^2.0.0"
},
"tarball": "https://registry.nyash.dev/awesome-math-1.0.0.tgz"
}
```
## 🔒 セキュリティ
### パッケージ署名
```toml
# nyash.toml
[package.signature]
algorithm = "ed25519"
public_key = "..."
```
### 整合性チェック
```
nyash_modules/
└── awesome-math/
├── nyash.toml
└── .nyash-integrity # SHA256ハッシュ
```
### 権限システム
- **read**: パッケージの参照(デフォルト:全員)
- **write**: パッケージの更新(デフォルト:作者のみ)
- **admin**: 権限管理(デフォルト:作者のみ)
## 🚀 高度な機能
### ワークスペース
```toml
# ルートnyash.toml
[workspace]
members = [
"packages/core",
"packages/utils",
"packages/cli"
]
```
### プライベートレジストリ
```toml
# .nyashrc
[registries]
default = "https://registry.nyash.dev"
company = "https://npm.company.com"
[scopes]
"@company" = "company"
```
### オフラインモード
```bash
# キャッシュからインストール
nyash install --offline
# キャッシュの事前ダウンロード
nyash cache add awesome-math@1.0.0
```
## 📈 パフォーマンス最適化
### 並列ダウンロード
- 最大10パッケージ同時ダウンロード
- HTTP/2による効率的な接続再利用
### インテリジェントキャッシュ
```
~/.nyash/cache/
├── packages/
│ └── awesome-math-1.0.0.tgz
├── metadata/
│ └── awesome-math.json
└── index.db # SQLiteインデックス
```
### 差分更新
- パッケージ更新時は差分のみダウンロード
- バイナリdiffアルゴリズム使用
## 🛣️ 実装ロードマップ
### Phase 1: MVP4週間
- [ ] 基本的なinstall/publishコマンド
- [ ] nyash.tomlパーサー
- [ ] シンプルな依存解決
- [ ] ローカルファイルシステムレジストリ
### Phase 2: 中央レジストリ6週間
- [ ] HTTPSレジストリAPI
- [ ] ユーザー認証システム
- [ ] パッケージ検索
- [ ] Webインターフェース
### Phase 3: 高度な機能8週間
- [ ] ワークスペースサポート
- [ ] プライベートレジストリ
- [ ] セキュリティ機能(署名・監査)
- [ ] 差分更新
## 🎯 成功指標
1. **使いやすさ**: 3コマンド以内で基本操作完了
2. **高速性**: npm比で2倍以上の速度
3. **信頼性**: 99.9%のアップタイム
4. **エコシステム**: 1年で1000パッケージ
## 📚 参考実装
- **npm**: UIとワークフローを参考
- **Cargo**: 依存解決アルゴリズム
- **pnpm**: 効率的なディスク使用
- **Deno**: セキュリティモデル
---
*Everything is Box - パッケージマネージャーもBoxを運ぶ*

View File

@ -0,0 +1,282 @@
# 統一TypeBox API リファレンス
## 📋 目次
1. [基本構造体](#基本構造体)
2. [関数ポインタ仕様](#関数ポインタ仕様)
3. [NyValue型システム](#nyvalue型システム)
4. [機能フラグ](#機能フラグ)
5. [エラーハンドリング](#エラーハンドリング)
6. [プラグイン間連携](#プラグイン間連携)
## 基本構造体
### NyashTypeBox
```c
typedef struct {
uint32_t abi_tag; // 必須: 0x54594258 ('TYBX')
uint16_t version; // APIバージョン現在: 1
uint16_t struct_size; // sizeof(NyashTypeBox)
const char* name; // Box型名NULL終端
// 基本操作
void* (*create)(void* args);
void (*destroy)(void* self);
// 高速ディスパッチ
uint32_t (*resolve)(const char* name);
NyResult (*invoke_id)(void* self, uint32_t method_id,
NyValue* args, int argc);
// 互換性
void* (*method)(void* self, const char* name,
void** args, int argc);
// メタ情報
const char* (*get_type_info)(void);
uint64_t capabilities;
// 予約済み
void* reserved[4];
} NyashTypeBox;
```
## 関数ポインタ仕様
### create
```c
void* (*create)(void* args);
```
- **目的**: 新しいBoxインスタンスを生成
- **引数**: `args` - 初期化パラメータ(型依存)
- **戻り値**: 生成されたインスタンスのポインタ
- **所有権**: 呼び出し元が所有destroy必須
### destroy
```c
void (*destroy)(void* self);
```
- **目的**: Boxインスタンスを破棄
- **引数**: `self` - 破棄するインスタンス
- **注意**: NULLチェックは呼び出し元の責任
### resolve
```c
uint32_t (*resolve)(const char* name);
```
- **目的**: メソッド名を数値IDに変換
- **引数**: `name` - メソッド名
- **戻り値**: メソッドID0 = 未知のメソッド)
- **用途**: JIT最適化、キャッシング
### invoke_id
```c
NyResult (*invoke_id)(void* self, uint32_t method_id,
NyValue* args, int argc);
```
- **目的**: 高速メソッド呼び出し
- **引数**:
- `self` - 対象インスタンス
- `method_id` - resolveで取得したID
- `args` - 引数配列
- `argc` - 引数数
- **戻り値**: NyResult成功/エラー)
### method互換用
```c
void* (*method)(void* self, const char* name,
void** args, int argc);
```
- **目的**: 従来互換のメソッド呼び出し
- **注意**: 新規実装では非推奨
### get_type_info
```c
const char* (*get_type_info)(void);
```
- **目的**: 型情報をJSON形式で返す
- **戻り値**: JSON文字列静的メモリ
- **形式例**:
```json
{
"methods": [
{"name": "length", "id": 1, "returns": "int"},
{"name": "concat", "id": 2, "returns": "string"}
]
}
```
## NyValue型システム
### 基本構造
```c
typedef struct __attribute__((aligned(16))) {
uint64_t type_tag; // 型識別子
union {
int64_t i64; // 整数
double f64; // 浮動小数点
void* ptr; // ポインタ
uint64_t bits; // ビットパターン
} payload;
} NyValue;
```
### 型タグ定義
```c
#define NYVAL_NULL 0x00
#define NYVAL_BOOL 0x01
#define NYVAL_INT 0x02
#define NYVAL_FLOAT 0x03
#define NYVAL_STRING 0x04
#define NYVAL_BOX 0x05
#define NYVAL_ARRAY 0x06
#define NYVAL_MAP 0x07
```
### ヘルパー関数
```c
// 値生成
NyValue ny_value_null(void);
NyValue ny_value_bool(bool val);
NyValue ny_value_int(int64_t val);
NyValue ny_value_float(double val);
NyValue ny_value_string(const char* str);
NyValue ny_value_box(void* box, NyashTypeBox* type);
// 値取得
bool ny_is_null(NyValue val);
bool ny_to_bool(NyValue val);
int64_t ny_to_int(NyValue val);
double ny_to_float(NyValue val);
const char* ny_to_string(NyValue val);
void* ny_to_box(NyValue val);
```
## 機能フラグ
### 基本フラグ
```c
#define NYASH_CAP_THREAD_SAFE (1 << 0) // スレッドセーフ
#define NYASH_CAP_ASYNC_SAFE (1 << 1) // async/await対応
#define NYASH_CAP_REENTRANT (1 << 2) // 再入可能
#define NYASH_CAP_PARALLELIZABLE (1 << 3) // 並列実行可能
#define NYASH_CAP_PURE (1 << 4) // 副作用なし
#define NYASH_CAP_DETERMINISTIC (1 << 5) // 決定的動作
```
### 拡張フラグ
```c
#define NYASH_CAP_GPU_ACCEL (1 << 8) // GPU実行可能
#define NYASH_CAP_SIMD_OPTIMIZED (1 << 9) // SIMD最適化済み
#define NYASH_CAP_LAZY_EVAL (1 << 10) // 遅延評価対応
```
## エラーハンドリング
### NyResult構造体
```c
typedef struct {
int status; // 0 = 成功、非0 = エラー
NyValue value; // 戻り値(成功時)
const char* error_msg; // エラーメッセージ(エラー時)
} NyResult;
```
### ステータスコード
```c
#define NY_OK 0
#define NY_ERROR_GENERIC -1
#define NY_ERROR_NULL_PTR -2
#define NY_ERROR_TYPE -3
#define NY_ERROR_BOUNDS -4
#define NY_ERROR_NOT_FOUND -5
#define NY_ERROR_MEMORY -6
```
### ヘルパー関数
```c
NyResult ny_result_ok(NyValue val);
NyResult ny_result_error(const char* msg);
bool ny_result_is_ok(NyResult res);
bool ny_result_is_error(NyResult res);
```
## プラグイン間連携
### TypeBox取得
```c
NyashTypeBox* ny_host_get_typebox(const char* name);
```
- **目的**: 他のプラグインのTypeBoxを取得
- **引数**: `name` - Box型名
- **戻り値**: TypeBoxポインタNULL = 未登録)
### 使用例
```c
// MapBoxがArrayBoxを生成する例
NyResult map_keys(void* self, uint32_t method_id,
NyValue* args, int argc) {
MapBoxImpl* map = (MapBoxImpl*)self;
// ArrayBoxを取得
NyashTypeBox* array_type = ny_host_get_typebox("ArrayBox");
if (!array_type) {
return ny_result_error("ArrayBox not found");
}
// 新しいArrayBoxを生成
void* array = array_type->create(NULL);
// キーを追加
for (int i = 0; i < map->key_count; i++) {
NyValue key = ny_value_string(map->keys[i]);
array_type->invoke_id(array, 1, &key, 1); // push
}
return ny_result_ok(ny_value_box(array, array_type));
}
```
## 所有権ルール
### 基本原則
1. **create**の戻り値 → 呼び出し元が**destroy**責任
2. **invoke_id**の引数 → プラグインは**借用**(変更/解放禁止)
3. **invoke_id**の戻り値 → 呼び出し元が所有
### 文字列の扱い
- 引数の文字列:コピー必須(借用のため)
- 戻り値の文字列:新規確保(呼び出し元が解放)
### メモリ管理ベストプラクティス
```c
// 良い例:文字列をコピー
void* string_concat(void* self, NyValue* args, int argc) {
char* str1 = (char*)self;
char* str2 = ny_to_string(args[0]);
// 新しいメモリを確保
size_t len = strlen(str1) + strlen(str2) + 1;
char* result = malloc(len);
snprintf(result, len, "%s%s", str1, str2);
return ny_value_string(result);
}
```
## バージョニング
### APIバージョン
- **現在**: 1
- **互換性**: 上位互換を維持
- **チェック**: `version`フィールドで確認
### 構造体サイズ
- **用途**: 前方互換性の確保
- **チェック**: `struct_size >= sizeof(NyashTypeBox)`
### 将来の拡張
- `reserved`配列を使用
- 新フィールドは構造体末尾に追加
- 既存フィールドの意味は変更禁止