Phase番号再編成: プラグインBox統一化を10.1に昇格
- 革新的発見: 既存プラグインシステム(C ABI)でJIT→EXE実現可能 - Phase 10.1: プラグインBox統一化(新規) - Phase 10.5: Python統合(旧10.1を移動) - CURRENT_TASKを更新して新計画を反映 Everything is Box → Everything is Plugin への進化
This commit is contained in:
@ -0,0 +1,27 @@
|
||||
# Phase 10.1a - 計画と設計
|
||||
|
||||
## 🎯 このフェーズの目的
|
||||
PythonParserBoxの全体計画を理解し、実装の方向性を把握する。
|
||||
|
||||
## 📁 含まれるファイル
|
||||
- **`pythonparser_integrated_plan_summary.txt`** - 統合実装計画(最重要)
|
||||
- **`expert_feedback_gemini_codex.txt`** - Gemini先生とCodex先生の技術評価
|
||||
- **`archive/`** - 初期検討資料
|
||||
|
||||
## ✅ 完了条件
|
||||
- [ ] 統合計画を読んで理解
|
||||
- [ ] エキスパートフィードバックを確認
|
||||
- [ ] 5つの核心戦略を把握
|
||||
- 関数単位フォールバック
|
||||
- Python 3.11固定
|
||||
- 意味論の正確な実装優先
|
||||
- GIL管理の最小化
|
||||
- テレメトリー重視
|
||||
|
||||
## 📝 重要ポイント
|
||||
- **Differential Testing戦略** - 世界中のPythonコードがテストケースに
|
||||
- **段階的実装** - 完璧を求めず動くものから
|
||||
- **成功の測定基準** - カバレッジ率70%以上、性能向上2-10倍
|
||||
|
||||
## ⏭️ 次のフェーズ
|
||||
→ Phase 10.1b (環境設定)
|
||||
@ -0,0 +1,138 @@
|
||||
# ChatGPT5の革命的アイデア - 多言語統合とBox化
|
||||
|
||||
## 元の発想
|
||||
|
||||
ChatGPT5さんの発想は「すべての言語をBoxで包んで統一的に扱う」という革命的なアプローチです。
|
||||
これにより、Python、Rust、JavaScript、Java等の既存エコシステムをNyashから自然に利用できるようになります。
|
||||
|
||||
## 核心概念
|
||||
|
||||
### 1. ForeignBox - 外部リソースのBox化
|
||||
```nyash
|
||||
// 外部言語のオブジェクトをBoxとして扱う
|
||||
box ForeignBox<T> {
|
||||
private { handle } // 外部リソースへのハンドル
|
||||
|
||||
fini() {
|
||||
ny_host_finalizer(me.handle) // 適切にリソース解放
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. ProxyBox - スレッドセーフな委譲
|
||||
```nyash
|
||||
// GILやイベントループを持つ言語用
|
||||
box ProxyBox<T> {
|
||||
private { bus, worker_id } // Bus経由で別スレッドに委譲
|
||||
|
||||
call(method, args) {
|
||||
return me.bus.send_and_wait(me.worker_id, method, args)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 言語別統合戦略(ChatGPT5原案)
|
||||
|
||||
### Python統合
|
||||
- **課題**: GIL(Global Interpreter Lock)
|
||||
- **解決**: ProxyBoxでBus経由ワーカー委譲
|
||||
- **実装**: CPython C-APIで`PyObject*`をForeignBoxに入れる
|
||||
|
||||
### JavaScript/Node.js統合
|
||||
- **課題**: イベントループを壊さない
|
||||
- **解決**: ProxyBox(postMessage/uv_queue_work)
|
||||
- **短い同期関数**: ForeignBoxでも可
|
||||
|
||||
### Rust/C統合
|
||||
- **最短パス**: C-ABI直接
|
||||
- **Rust側**: `#[no_mangle] extern "C"`
|
||||
- **所有権**: Nyash↔Rustのどちらかに寄せる(二重所有禁止)
|
||||
|
||||
### JVM/.NET統合
|
||||
- **方式**: JNI/P-Invoke
|
||||
- **要件**: Pinning必要
|
||||
- **GC連携**: SafeHandle/PhantomReferenceでFinalizer橋渡し
|
||||
|
||||
### WASM統合
|
||||
- **方式**: `ny_host_*`をimport
|
||||
- **データ**: リニアメモリへBytes/Strで搬送
|
||||
|
||||
## 統一インターフェース設計
|
||||
|
||||
### NyIDL(Nyash Interface Definition Language)
|
||||
```idl
|
||||
module ny {
|
||||
box Image;
|
||||
fn load(path: str) -> Image effects = io
|
||||
fn resize(img: Image, w: i32, h: i32) -> Image effects = mut
|
||||
fn width(img: look Image) -> i32 effects = pure
|
||||
}
|
||||
```
|
||||
|
||||
### 自動生成される要素
|
||||
1. Nyash側extern宣言
|
||||
2. C-ABIシム層
|
||||
3. 各言語用スタブ(Rust/Node/Python/JVM)
|
||||
4. ForeignBox/ProxyBoxラッパー
|
||||
|
||||
## 所有権と寿命管理
|
||||
|
||||
### One Strong Owner原則
|
||||
- ForeignBoxは所有者1本(NyashまたはA外部)
|
||||
- 弱参照は`weak/look`で管理
|
||||
- 失効時はnull/false
|
||||
|
||||
### Finalizerの橋渡し
|
||||
1. Nyash `fini` → `ny_host_finalizer`呼び出し
|
||||
2. 外部GC/finalize → `ny_host_finalizer`経由でNyashのweakを失効
|
||||
|
||||
## 効果システムとの統合
|
||||
|
||||
```nyash
|
||||
// 効果注釈でFFI境界の振る舞いを明示
|
||||
extern fn py_numpy_matmul(a: ForeignBox<ndarray>, b: ForeignBox<ndarray>)
|
||||
-> ForeignBox<ndarray> effects mut
|
||||
|
||||
extern fn rust_image_load(path: str)
|
||||
-> ForeignBox<Image> effects io
|
||||
|
||||
extern fn js_fetch(url: str)
|
||||
-> ProxyBox<Promise> effects io
|
||||
```
|
||||
|
||||
## MIRレベルでの統合
|
||||
|
||||
### BoxCall命令の拡張
|
||||
```
|
||||
// 通常のBoxCall
|
||||
BoxCall(%result, %box, "method", [%arg1, %arg2])
|
||||
|
||||
// ForeignBoxのメソッド呼び出し
|
||||
BoxCall(%result, %foreign_box, "py_method", [%arg1])
|
||||
// → 内部でFFI境界を越えて呼び出し
|
||||
|
||||
// ProxyBoxの非同期呼び出し
|
||||
Send(%msg_id, %proxy_box, "method", [%args])
|
||||
Recv(%result, %msg_id)
|
||||
```
|
||||
|
||||
## 革命的な利点
|
||||
|
||||
1. **即座の多言語資産活用**: 既存ライブラリを「箱に詰めて」即Nyashで使える
|
||||
2. **統一的な寿命管理**: 強1+weak/look+finiで外部リソースも確定的に回収
|
||||
3. **配布の柔軟性**: WASM/VM/ネイティブのどれでも同じIDLから出荷
|
||||
4. **MIR最適化の恩恵**: 外部言語呼び出しもMIRレベルで最適化可能
|
||||
5. **段階的移行**: 既存プロジェクトを徐々にNyashに移行
|
||||
|
||||
## 実装優先順位
|
||||
|
||||
1. **Phase 1**: C/Rust統合(最も単純)
|
||||
2. **Phase 2**: Python統合(PythonParserBox)
|
||||
3. **Phase 3**: JavaScript/Node.js統合
|
||||
4. **Phase 4**: JVM/.NET統合
|
||||
5. **Phase 5**: 統一IDLと自動生成ツール
|
||||
|
||||
## まとめ
|
||||
|
||||
「すべてをBoxに閉じ込める」という設計を正式化することで、あらゆる言語→NyashとNyash→あらゆる実行系が綺麗に繋がる。
|
||||
これはまさに「Everything is Box」哲学の究極の実現形態といえる。
|
||||
@ -0,0 +1,207 @@
|
||||
# PythonParserBox設計提案 - CPythonパーサーを使ったPython→Nyash変換
|
||||
|
||||
## 概要
|
||||
CPythonの公式パーサーを活用して、PythonコードをNyashで直接実行可能にする革命的なアプローチ。
|
||||
PythonコードをNyashのAST/MIRに変換し、Nyashの最適化・JITコンパイルの恩恵を受けられるようにする。
|
||||
|
||||
## アーキテクチャ
|
||||
|
||||
### 1. PythonParserBox(ビルトインBox)
|
||||
```nyash
|
||||
// 使用例
|
||||
local py_parser = new PythonParserBox()
|
||||
|
||||
// Pythonコードを直接パース
|
||||
local ast = py_parser.parse("""
|
||||
def calculate(x, y):
|
||||
return x * 2 + y
|
||||
|
||||
result = calculate(10, 5)
|
||||
""")
|
||||
|
||||
// NyashのASTに変換
|
||||
local nyash_ast = py_parser.to_nyash_ast(ast)
|
||||
|
||||
// 直接実行も可能
|
||||
local result = py_parser.run(python_code)
|
||||
```
|
||||
|
||||
### 2. 実装構造
|
||||
```rust
|
||||
pub struct PythonParserBox {
|
||||
base: BoxBase,
|
||||
parser: CPythonParser, // CPythonの公式パーサー使用
|
||||
}
|
||||
|
||||
impl PythonParserBox {
|
||||
// Python → Python AST
|
||||
pub fn parse(&self, code: &str) -> Box<dyn NyashBox> {
|
||||
let py_ast = self.parser.parse_string(code);
|
||||
Box::new(PythonAstBox { ast: py_ast })
|
||||
}
|
||||
|
||||
// Python AST → Nyash AST
|
||||
pub fn to_nyash_ast(&self, py_ast: &PythonAstBox) -> Box<dyn NyashBox> {
|
||||
let converter = AstConverter::new();
|
||||
converter.convert_python_to_nyash(py_ast)
|
||||
}
|
||||
|
||||
// Python AST → MIR(直接変換)
|
||||
pub fn to_mir(&self, py_ast: &PythonAstBox) -> MirModule {
|
||||
let mut builder = MirBuilder::new();
|
||||
for func in py_ast.functions() {
|
||||
self.convert_function_to_mir(&mut builder, func);
|
||||
}
|
||||
builder.build()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## AST変換マッピング
|
||||
|
||||
### Python → Nyash対応表
|
||||
| Python AST | Nyash AST | 説明 |
|
||||
|------------|-----------|------|
|
||||
| FunctionDef | FunctionDecl | 関数定義 |
|
||||
| BinOp | BinaryOp | 二項演算 |
|
||||
| Call | MethodCall | 関数呼び出し |
|
||||
| Assign | Assignment | 代入 |
|
||||
| If | IfStatement | 条件分岐 |
|
||||
| While/For | LoopStatement | ループ |
|
||||
| Return | ReturnStatement | return文 |
|
||||
| Import | NewBox/LoadPlugin | import → Box化 |
|
||||
|
||||
### 型変換戦略
|
||||
```rust
|
||||
// Python動的型 → Nyash Box
|
||||
match py_value {
|
||||
PyInt(n) => IntegerBox::new(n),
|
||||
PyFloat(f) => FloatBox::new(f),
|
||||
PyStr(s) => StringBox::new(s),
|
||||
PyList(items) => ArrayBox::from_iter(items),
|
||||
PyDict(map) => MapBox::from_iter(map),
|
||||
PyObject(obj) => PythonObjectBox::new(obj), // 変換不能な場合
|
||||
}
|
||||
```
|
||||
|
||||
## MIR生成例
|
||||
|
||||
### Pythonコード
|
||||
```python
|
||||
def calculate(x, y):
|
||||
return x * 2 + y
|
||||
```
|
||||
|
||||
### 生成されるMIR
|
||||
```
|
||||
function calculate(%x, %y) {
|
||||
Load(%1, %x)
|
||||
Const(%2, 2)
|
||||
BinOp(%3, Mul, %1, %2)
|
||||
Load(%4, %y)
|
||||
BinOp(%5, Add, %3, %4)
|
||||
Return(%5)
|
||||
}
|
||||
```
|
||||
|
||||
## 利点
|
||||
|
||||
1. **完全な互換性**: CPython公式パーサーで100%正確なパース
|
||||
2. **統一最適化**: PythonコードもNyashのMIR最適化パイプラインを通る
|
||||
3. **JIT/AOTコンパイル**: PythonコードをネイティブコードにJIT/AOTコンパイル可能
|
||||
4. **段階的移行**: 既存Pythonコードを徐々にNyashに移行
|
||||
5. **デバッグ統一**: Nyashのデバッグツールでpythonコードもデバッグ可能
|
||||
|
||||
## 実装フェーズ
|
||||
|
||||
### Phase 1: 基本パーサー統合
|
||||
- CPythonパーサーのFFIバインディング
|
||||
- parse()メソッドでPython ASTを取得
|
||||
- AST可視化(dump_ast)
|
||||
|
||||
### Phase 2: AST変換
|
||||
- Python AST → Nyash AST変換器
|
||||
- 基本的な文法要素のサポート
|
||||
- 型変換システム
|
||||
|
||||
### Phase 3: MIR直接生成
|
||||
- Python AST → MIR変換
|
||||
- Python特有の最適化(動的型推論等)
|
||||
- ベンチマーク
|
||||
|
||||
### Phase 4: エコシステム統合
|
||||
- NumPy等の主要ライブラリサポート
|
||||
- Python例外 → Nyashエラー変換
|
||||
- async/await対応
|
||||
- GIL管理の自動化
|
||||
|
||||
## 技術的課題と解決策
|
||||
|
||||
### 1. GIL(Global Interpreter Lock)
|
||||
- 解決策: PythonコードはGILスコープ内で実行
|
||||
- 将来: MIR変換後はGILフリーで実行可能
|
||||
|
||||
### 2. Python動的型とNyash Box型のマッピング
|
||||
- 解決策: 実行時型情報を保持するPythonObjectBox
|
||||
- 最適化: よく使う型(int, str等)は専用Boxに変換
|
||||
|
||||
### 3. Pythonモジュールシステム
|
||||
- 解決策: importをNyashのプラグインロードにマッピング
|
||||
- pip packages → Nyashプラグインとして扱う
|
||||
|
||||
## 実用例
|
||||
|
||||
### 機械学習コードの実行
|
||||
```nyash
|
||||
local ml_code = """
|
||||
import numpy as np
|
||||
from sklearn.linear_model import LinearRegression
|
||||
|
||||
# データ準備
|
||||
X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])
|
||||
y = np.dot(X, np.array([1, 2])) + 3
|
||||
|
||||
# モデル訓練
|
||||
model = LinearRegression()
|
||||
model.fit(X, y)
|
||||
|
||||
# 予測
|
||||
predictions = model.predict(np.array([[3, 5]]))
|
||||
print(f'Prediction: {predictions[0]}')
|
||||
"""
|
||||
|
||||
local py_parser = new PythonParserBox()
|
||||
local result = py_parser.run(ml_code)
|
||||
```
|
||||
|
||||
### Webアプリケーション
|
||||
```nyash
|
||||
local flask_app = """
|
||||
from flask import Flask, jsonify
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
@app.route('/api/hello/<name>')
|
||||
def hello(name):
|
||||
return jsonify({'message': f'Hello, {name}!'})
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(port=5000)
|
||||
"""
|
||||
|
||||
local py_parser = new PythonParserBox()
|
||||
py_parser.run(flask_app) // FlaskアプリがNyash内で起動
|
||||
```
|
||||
|
||||
## 期待される効果
|
||||
|
||||
1. **パフォーマンス向上**: PythonコードがJITコンパイルされ高速化
|
||||
2. **メモリ効率**: NyashのGC/メモリ管理を活用
|
||||
3. **相互運用性**: Python↔Nyash↔Rust↔JS等の自由な組み合わせ
|
||||
4. **開発効率**: 既存Pythonライブラリをそのまま使える
|
||||
5. **将来性**: PythonコードをネイティブAOTコンパイル可能
|
||||
|
||||
## まとめ
|
||||
|
||||
PythonParserBoxは、Pythonの豊富なエコシステムとNyashの高性能実行エンジンを組み合わせる画期的なアプローチ。
|
||||
CPythonパーサーの信頼性とNyashのMIR/JIT最適化により、Pythonコードをより高速に、より効率的に実行できる。
|
||||
@ -0,0 +1,98 @@
|
||||
# 2025-08-27 議論まとめ - PythonParserBoxと言語間統合
|
||||
|
||||
## 本日の議論の流れ
|
||||
|
||||
### 1. ベンチマーク実行と問題発見
|
||||
- インタープリター性能問題(10万回ループで2分以上)
|
||||
- VM変数管理エラー
|
||||
- Box APIの成熟度不足(TimeBox.elapsed()が呼べない)
|
||||
- 問題点をPhase 10ドキュメントに追記
|
||||
|
||||
### 2. Cranelift AOT Backendの追加(Phase 10.9)
|
||||
- JIT実装の基盤を再利用して事前コンパイル可能
|
||||
- 非同期完全サポート(WASMの制限なし)
|
||||
- 実装期間2-3週間で可能(上乗せだけ)
|
||||
|
||||
### 3. PythonParserBox構想の深堀り
|
||||
- ChatGPT5さんの「CPythonをBoxで包みMIRに落とし込む」アイデアを具体化
|
||||
- CPythonの公式パーサーを使ってPythonコード→Nyash AST/MIR変換
|
||||
- ビルトインBoxとして分離実装
|
||||
|
||||
### 4. エキスパートへの相談結果
|
||||
|
||||
#### Gemini先生の分析
|
||||
- pyo3活用で技術的課題は解決可能
|
||||
- 最初は特定ドメインのサブセットから開始すべき
|
||||
- GIL管理のBox隠蔽は現実的
|
||||
- 設計思想は他言語(Ruby/JS)にも応用可能
|
||||
|
||||
#### Codex先生の実装提案
|
||||
- CPython内部APIではなく、安定した`ast`モジュール経由
|
||||
- Python側で`ast.parse()` → JSON → Rust側で処理
|
||||
- 最小実装セット定義(基本構造+演算+制御フロー)
|
||||
- 純Pythonループで2-10倍の高速化が現実的
|
||||
|
||||
### 5. Phase 10.1フォルダの作成と整理
|
||||
以下のドキュメントをPhase 10.1に整理:
|
||||
- python_parser_box_design.txt(基本設計)
|
||||
- python_parser_box_implementation_plan.txt(実装計画)
|
||||
- chatgpt5_original_idea.txt(元のアイデア)
|
||||
- summary_2025_08_27.txt(本まとめ)
|
||||
|
||||
## 技術的な要点
|
||||
|
||||
### 実装アプローチ
|
||||
```rust
|
||||
// pyo3でCPythonを埋め込み
|
||||
pyo3 = { version = "0.22", features = ["auto-initialize"] }
|
||||
|
||||
// Python側でAST→JSON変換
|
||||
def parse_to_json(code):
|
||||
tree = ast.parse(code)
|
||||
return json.dumps(ast_to_dict(tree))
|
||||
|
||||
// Rust側で受け取り
|
||||
let json_ast = py_helper.parse_to_json(python_code);
|
||||
let nyash_ast = convert_json_to_nyash_ast(json_ast);
|
||||
```
|
||||
|
||||
### 最小実装セット(Phase 1-2)
|
||||
- 構造: Module, FunctionDef, Return, Assign
|
||||
- 演算: BinOp, Compare, Call, Name, Constant
|
||||
- 制御: If, While, Br, CondBr
|
||||
- 実行: 最初はCPython exec委譲、段階的にMIR実行へ
|
||||
|
||||
### データ共有戦略
|
||||
- NumPy配列: pyo3-numpyでゼロコピー共有
|
||||
- NdArrayBox: Nyash側でNumPy配列を効率的に扱う
|
||||
- バッファプロトコル: PEP 3118で汎用オブジェクト共有
|
||||
|
||||
### 期待される効果
|
||||
- 純Pythonループ: 2-10倍高速化
|
||||
- NumPy処理: 1.0-1.2倍(既に最適化済み)
|
||||
- 将来的: トレースベース最適化で10-30倍も可能
|
||||
|
||||
## 次のステップ
|
||||
|
||||
1. **Phase 1実装開始**(1-2週間)
|
||||
- pyo3統合とPythonParserBox基本実装
|
||||
- parse_to_jsonヘルパー作成
|
||||
- 最小AST変換動作確認
|
||||
|
||||
2. **小規模ベンチマーク**
|
||||
- 簡単なPython関数で動作確認
|
||||
- 性能測定と改善点洗い出し
|
||||
|
||||
3. **段階的拡張**
|
||||
- MIR変換実装
|
||||
- NumPy統合
|
||||
- より複雑なPython機能対応
|
||||
|
||||
## まとめ
|
||||
|
||||
PythonParserBoxは、Nyashの「Everything is Box」哲学を言語間統合に拡張する革命的なアプローチ。
|
||||
CPythonパーサーの信頼性とNyashのMIR/JIT最適化を組み合わせることで、Pythonエコシステムを
|
||||
Nyashから自然に利用でき、かつ高速化も実現できる。
|
||||
|
||||
ChatGPT5さんの最初のアイデア(ForeignBox/ProxyBox)を基に、具体的な実装計画まで落とし込めた。
|
||||
技術的にも実現可能で、段階的なアプローチにより着実に実装できる見込み。
|
||||
@ -0,0 +1,197 @@
|
||||
# PythonParserBox実装計画 - エキスパートフィードバック
|
||||
日付: 2025-08-27
|
||||
|
||||
## Gemini先生のフィードバック
|
||||
|
||||
### 総評
|
||||
これは非常に野心的で、言語の成熟度を飛躍的に高める可能性を秘めた素晴らしい計画です。Nyashの「Everything is a Box」哲学とPythonエコシステムを融合させるという着眼点に大変興奮しました。
|
||||
|
||||
### 1. 実装計画は技術的に健全か?落とし穴は?
|
||||
|
||||
**技術的健全性:**
|
||||
はい、計画は全体として技術的に非常に健全です。
|
||||
|
||||
* **CPythonパーサーの利用:** `pyo3`経由で`ast.parse()`を利用するのは、Python構文との互換性を100%保証するための最も確実で賢明なアプローチです。
|
||||
* **JSON中間表現(IR):** Python AST (Pythonメモリ空間) と Nyash AST (Rustメモリ空間) の間にJSONを挟むのは、言語間の境界を明確に分離する良い設計です。
|
||||
* **段階的実装とフォールバック:** 未実装機能を`exec()`にフォールバックする戦略は、実用性を保ちながら段階的に実装を進めるための極めて現実的なアプローチです。
|
||||
|
||||
**潜在的な落とし穴:**
|
||||
* **パフォーマンス:** `Python AST → JSON → Nyash AST → Nyash実行`というパイプラインは、特に初期段階では非常に低速になります。
|
||||
* **ASTの複雑性の爆発:** PythonのASTは非常に巨大で、言語バージョンの更新も速いです。
|
||||
* **標準ライブラリの壁:** Pythonの真の力は広範な標準/サードパーティライブラリにあります。`import`文をどう扱うかは最重要課題です。
|
||||
|
||||
### 2. Python AST → Nyash AST変換で注意すべき意味論の違いは?
|
||||
|
||||
* **型システム:** Pythonは動的型付け、Nyashは静的型付けまたはより厳格な型システムを持つと推測
|
||||
* **オブジェクトモデルと可変性:** Pythonのオブジェクトは基本的に可変(mutable)
|
||||
* **スコープとクロージャ:** Pythonの`global`や`nonlocal`の挙動は独特
|
||||
* **特殊メソッド (`__dunder__`):** Pythonの挙動は特殊メソッドで定義される
|
||||
* **組み込み関数:** `len()`, `print()`, `range()`などをどう扱うか
|
||||
|
||||
### 3. Nyashパーサーのバグ検証戦略として効果的か?
|
||||
|
||||
**非常に効果的です。** これは「Differential Testing(差分テスト)」と呼ばれる強力な手法です。
|
||||
* **巨大なテストスイート:** 事実上、世の中にある無数のPythonコードがNyashのテストケースになります。
|
||||
* **微妙なバグの発見:** 手書きの単体テストでは見逃しがちなセマンティクスのバグを発見するのに絶大な効果を発揮します。
|
||||
|
||||
### 4. pyo3統合でのGIL管理のベストプラクティスは?
|
||||
|
||||
* **基本原則:** Pythonオブジェクトに触れるコードは、必ずGILを獲得した状態で実行
|
||||
* **GILの必要期間を最小化する**
|
||||
* **`py.allow_threads`の活用:** 時間がかかり、かつPythonオブジェクトに触れない処理で使用
|
||||
|
||||
### 5. 段階的実装(Phase 1-4)の優先順位は適切か?
|
||||
|
||||
はい、提案されている優先順位は非常に適切です。
|
||||
1. Phase 1: 基本構文 + 変数束縛 + 基本的な式 + プリミティブ型
|
||||
2. Phase 2: list, dict, tuple
|
||||
3. Phase 3: 関数とスコープ
|
||||
4. Phase 4: モジュールとクラス
|
||||
|
||||
**最優先で並行すべきこと:** `exec()`へのフォールバック機構
|
||||
|
||||
### 6. 言語成熟度向上への貢献度をどう評価する?
|
||||
|
||||
**定量的指標:**
|
||||
* ライブラリ互換性カバレッジ
|
||||
* パフォーマンステスト
|
||||
* 発見バグ数
|
||||
|
||||
**定性的指標:**
|
||||
* 表現力の向上
|
||||
* 開発者体験
|
||||
* エコシステムのマイルストーン
|
||||
|
||||
### 結論
|
||||
|
||||
この`PythonParserBox`計画は、単なる機能追加ではなく、**Nyash言語のテスト、デバッグ、そしてエコシステム獲得を同時に加速させる、極めて戦略的な一手**です。
|
||||
|
||||
---
|
||||
|
||||
## Codex先生のフィードバック
|
||||
|
||||
### Overall Verdict
|
||||
- Sound approach: Using CPython's parser via pyo3, lowering via a JSON IR, and gradually replacing exec() with Nyash MIR/JIT is feasible and strategically strong.
|
||||
- Biggest risks: Semantic mismatches at statement/expression boundaries, version skew of Python AST, and boundary-costs between CPython and Nyash during phased rollout.
|
||||
|
||||
### Architectural Pitfalls
|
||||
- **Python version skew:** `ast` schema changes across minors. Pin and encode `py_version` + `ast_format` in the JSON.
|
||||
- **AST stability vs syntax fidelity:** `ast` loses comments and some token distinctions
|
||||
- **Boundary granularity:** Whole-file fallback wastes partial coverage; per-node fallback is unsafe. **The practical unit is per-function.**
|
||||
- **Import system and environment:** Python imports pull arbitrary code
|
||||
- **Error mapping:** Propagate Python exceptions with full traceback
|
||||
- **Performance overhead:** Python AST→JSON→Nyash→MIR is heavy
|
||||
- **Object model mismatch:** Identity (`is`), mutability, truthiness, numeric tower
|
||||
- **Concurrency:** GIL limits parallel parse/exec
|
||||
|
||||
### AST→Nyash Semantics: High-Risk Differences
|
||||
- **Names and scope:**
|
||||
- LEGB resolution; `global`/`nonlocal` behavior; closures and cell variables
|
||||
- Comprehension scopes (separate scope in Python 3)
|
||||
- **Control flow:**
|
||||
- `for` iterates via iterator protocol; `for/else`, `while/else` semantics
|
||||
- Short-circuit truthiness uses Python rules; `__bool__` then `__len__`
|
||||
- **Functions:**
|
||||
- Defaults evaluated at definition time; `*args/**kwargs`
|
||||
- Decorators transform functions at definition time
|
||||
- **Operators and numbers:**
|
||||
- `/` true division; `//` floor division; big integers by default
|
||||
- Operator dispatch via dunder methods; `is` vs `==`
|
||||
|
||||
For Phase 1, the must-haves are: LEGB + locals/freevars, default args timing, iterator-based `for`, `for/else` + `while/else`, Python truthiness and short-circuiting.
|
||||
|
||||
### Fallback Strategy
|
||||
- **Fallback unit: Per-function.** If a function body contains unsupported nodes, compile a "PyThunk" that calls into CPython.
|
||||
- **Boundary types:** Define canonical bridges: `PyAnyBox` in Nyash wrapping `Py<PyAny>`
|
||||
- **Imports and globals:** Execute module top-level in Python; then selectively replace functions
|
||||
|
||||
### pyo3/GIL Best Practices
|
||||
- **Initialization:** Call `pyo3::prepare_freethreaded_python()` once
|
||||
- **GIL usage:**
|
||||
- Use `Python::with_gil(|py| { ... })` for all Python calls
|
||||
- Minimize time under GIL; copy data out promptly
|
||||
- For heavy Rust work, drop GIL: `py.allow_threads(|| { ... })`
|
||||
- **Data transfer:** Prefer building JSON on the Python side
|
||||
- **Versioning:** Pin Python minor version; embed version string in the IR
|
||||
|
||||
### Phasing and Priorities (Refined)
|
||||
- **Phase 1 (Parser + Minimal Semantics):**
|
||||
- Python→JSON exporter with location info
|
||||
- Nyash IR for expressions and basic statements
|
||||
- Semantics fidelity for: iterator protocol, truthiness, scoping
|
||||
- **Fallback per-function for anything else**
|
||||
- **Phase 2-4:** Coverage expansion → Objects/Runtime → MIR/JIT
|
||||
|
||||
### Parser Bug Validation Strategy
|
||||
- **Differential execution:** Curate pairs of semantically equivalent snippets
|
||||
- **Oracle testing:** Run CPython as oracle and compare
|
||||
- **Fuzzing:** Grammar-based fuzzers
|
||||
- **Coverage and gating:** Track node-kind coverage
|
||||
|
||||
### IR/JSON Design Tips
|
||||
- Include: `node_type`, children, `lineno/col_offset`, `py_version`, `ast_format`, `support_level`
|
||||
- Canonicalize: normalize forms, operator names
|
||||
- Determinism: maintain stable field ordering
|
||||
|
||||
### Concrete Recommendations
|
||||
- **Pin to one Python minor (e.g., 3.11 or 3.12)**
|
||||
- **Choose per-function fallback as the core boundary**
|
||||
- **Implement Python truthiness, iterator protocol, and scoping correctly before optimizing**
|
||||
- **Keep the GIL minimal: build the JSON in Python; parse in Rust**
|
||||
- **Telemetry from day one: log unsupported node kinds and fallback counts**
|
||||
- **Start with JSON; plan migration to a compact binary once stable**
|
||||
|
||||
---
|
||||
|
||||
## 統合された重要ポイント
|
||||
|
||||
### 🎯 両エキスパートが一致した最重要事項
|
||||
|
||||
1. **関数単位のフォールバック戦略**
|
||||
- ファイル全体でなく関数レベルでコンパイル/フォールバックを切り替え
|
||||
- 未対応機能を含む関数はCPython exec、対応済み関数はNyash MIR/JIT
|
||||
|
||||
2. **Python バージョン固定**
|
||||
- Python 3.11または3.12に固定
|
||||
- AST安定性の確保とバージョン間の差異回避
|
||||
|
||||
3. **意味論の正確な実装が最優先**
|
||||
- 最適化より先にPython互換性を確保
|
||||
- 特に: イテレータプロトコル、真偽値判定、スコーピング規則
|
||||
|
||||
4. **GIL管理の最小化**
|
||||
- Python側でJSON生成、Rust側で解析
|
||||
- 重い処理はGIL外で実行
|
||||
|
||||
5. **テレメトリーの重要性**
|
||||
- 未対応ノードの記録
|
||||
- フォールバック率の計測
|
||||
- 実行時の統計情報収集
|
||||
|
||||
### 🚨 特に注意すべき意味論の違い
|
||||
|
||||
1. **制御フロー**
|
||||
- for/else, while/else の独特な挙動
|
||||
- forループのイテレータプロトコル
|
||||
|
||||
2. **スコープ規則**
|
||||
- LEGB(Local, Enclosing, Global, Builtins)
|
||||
- global/nonlocal宣言
|
||||
- 内包表記の独立スコープ(Python 3)
|
||||
|
||||
3. **数値演算**
|
||||
- / (true division) vs // (floor division)
|
||||
- デフォルトで大整数
|
||||
- NaN の扱い
|
||||
|
||||
4. **関数定義**
|
||||
- デフォルト引数は定義時に評価
|
||||
- *args/**kwargs の扱い
|
||||
- デコレータの実行順序
|
||||
|
||||
### 📊 成功の測定指標
|
||||
|
||||
1. **カバレッジ**: コンパイル済み vs フォールバック関数の比率
|
||||
2. **性能向上**: 数値計算ベンチマークでの改善率
|
||||
3. **バグ発見数**: Differential Testingで発見されたバグ数
|
||||
4. **エコシステム**: 動作する有名Pythonライブラリの数
|
||||
@ -0,0 +1,148 @@
|
||||
# PythonParserBox統合実装計画 - エキスパート評価後の最終版
|
||||
作成日: 2025-08-27
|
||||
|
||||
## 🎯 革命的な3つの価値
|
||||
|
||||
### 1. Pythonエコシステムの即座活用
|
||||
- 既存のPythonライブラリをNyashから直接利用可能
|
||||
- 段階的な移行パスの提供
|
||||
|
||||
### 2. Nyashパーサーのバグ自動検証(Differential Testing)
|
||||
- **世界中のPythonコードがNyashのテストケースに!**
|
||||
- CPythonをオラクルとして使用、出力・戻り値・例外を自動比較
|
||||
- 微妙なセマンティクスバグを大量に発見可能
|
||||
|
||||
### 3. 言語成熟度の飛躍的向上
|
||||
- 実用的なPythonコードでNyashをストレステスト
|
||||
- 発見されたバグ数が成熟度向上の定量的指標
|
||||
|
||||
## 🏆 エキスパート評価サマリー
|
||||
|
||||
### Gemini先生の評価
|
||||
**「非常に野心的で、言語の成熟度を飛躍的に高める可能性を秘めた素晴らしい計画」**
|
||||
|
||||
- 技術的に健全なアプローチ
|
||||
- pyo3経由のCPythonパーサー利用は最も確実
|
||||
- Differential Testingは極めて強力な手法
|
||||
|
||||
### Codex先生の評価
|
||||
**「Sound approach with strategic strength」**
|
||||
|
||||
- 関数単位フォールバックが実用的かつ効果的
|
||||
- Python 3.11固定でAST安定性確保
|
||||
- テレメトリー重視で継続的改善可能
|
||||
|
||||
## 🔑 統合された5つの核心戦略
|
||||
|
||||
### 1. 関数単位フォールバック(両エキスパート一致)
|
||||
```python
|
||||
def supported_function(): # → Nyash MIR/JIT
|
||||
return x + y
|
||||
|
||||
def unsupported_function(): # → CPython exec
|
||||
yield from generator # Phase 1では未対応
|
||||
```
|
||||
|
||||
### 2. Python 3.11固定
|
||||
- AST安定性確保(3.8 Constant統一、3.10 match/case、3.12位置情報)
|
||||
- `py_version`と`ast_format`をJSON IRに埋め込む
|
||||
|
||||
### 3. 意味論の正確な実装優先
|
||||
Phase 1必須要素(Codex先生強調):
|
||||
- LEGB + locals/freevars(スコーピング)
|
||||
- デフォルト引数の評価タイミング(定義時)
|
||||
- イテレータベースのfor文
|
||||
- for/else + while/else(Python独特)
|
||||
- Python真偽値判定(`__bool__` → `__len__`)
|
||||
- 短絡評価(and/or)
|
||||
|
||||
### 4. GIL管理の最小化
|
||||
```rust
|
||||
// GILは最小限に!
|
||||
let json_ast = Python::with_gil(|py| {
|
||||
py_helper.parse_to_json(py, code) // Python側でJSON生成
|
||||
})?;
|
||||
|
||||
// GIL外でRust処理
|
||||
let nyash_ast = py.allow_threads(|| {
|
||||
convert_json_to_nyash(json_ast)
|
||||
});
|
||||
```
|
||||
|
||||
### 5. テレメトリー基盤
|
||||
```bash
|
||||
[PythonParser] Module: example.py (Python 3.11)
|
||||
Functions: 10 total
|
||||
Compiled: 7 (70%)
|
||||
Fallback: 3 (30%)
|
||||
- async_function: unsupported node 'AsyncFunctionDef' at line 23
|
||||
```
|
||||
|
||||
## 📋 実装フェーズ(詳細版)
|
||||
|
||||
### Phase 0: 準備(1週間)
|
||||
- [ ] Python 3.11.9環境固定
|
||||
- [ ] テレメトリー基盤構築
|
||||
- [ ] Differential Testingフレームワーク
|
||||
- [ ] JSON IR仕様策定
|
||||
|
||||
### Phase 1: Core Subset(2週間)
|
||||
- [ ] pyo3統合(prepare_freethreaded_python)
|
||||
- [ ] 関数単位コンパイル判定器
|
||||
- [ ] 基本構文(def/if/for/while/return)
|
||||
- [ ] 意味論必須要素の実装
|
||||
- [ ] CPythonとの出力比較テスト
|
||||
|
||||
### Phase 2: Data Model(3週間)
|
||||
- [ ] 特殊メソッドマッピング
|
||||
- [ ] list/dict/tuple実装
|
||||
- [ ] 演算子オーバーロード
|
||||
|
||||
### Phase 3: Advanced Features(1ヶ月)
|
||||
- [ ] 例外処理(try/except)
|
||||
- [ ] with文、ジェネレータ
|
||||
- [ ] 内包表記、デコレータ
|
||||
|
||||
## 📊 成功の測定基準
|
||||
|
||||
### 定量的指標
|
||||
| 指標 | 目標 | 測定方法 |
|
||||
|------|------|----------|
|
||||
| カバレッジ率 | 70%以上 | コンパイル済み vs フォールバック関数 |
|
||||
| 性能向上 | 2-10倍 | 純Pythonループのベンチマーク |
|
||||
| バグ発見数 | 10+件/Phase | Differential Testing |
|
||||
| エコシステム | 1以上 | 動作する有名ライブラリ数 |
|
||||
|
||||
### マイルストーン
|
||||
- Phase 1: "Hello from Python in Nyash"が動作
|
||||
- Phase 2: scikit-learnの基本アルゴリズムが動作
|
||||
- Phase 3: FlaskのHello Worldが動作
|
||||
- Phase 4: PyPIトップ100の30%が基本動作
|
||||
|
||||
## 🚨 注意すべき意味論の違い(トップ5)
|
||||
|
||||
1. **制御フロー**: for/else, while/else
|
||||
2. **スコープ規則**: LEGB、global/nonlocal
|
||||
3. **数値演算**: / (true division) vs //
|
||||
4. **関数定義**: デフォルト引数は定義時評価
|
||||
5. **真偽値判定**: Pythonの__bool__/__len__ルール
|
||||
|
||||
## 🎉 期待されるインパクト
|
||||
|
||||
### 技術的成果
|
||||
- Pythonエコシステムの活用
|
||||
- Nyashパーサーの品質向上
|
||||
- 性能最適化の実証
|
||||
|
||||
### 戦略的価値
|
||||
- 言語成熟度の飛躍的向上
|
||||
- 開発者コミュニティの拡大
|
||||
- 実用アプリケーション開発の加速
|
||||
|
||||
## 📝 結論
|
||||
|
||||
PythonParserBoxは、単なる機能追加ではなく、**Nyash言語のテスト、デバッグ、エコシステム獲得を同時に加速させる極めて戦略的なプロジェクト**。
|
||||
|
||||
両エキスパートの技術的評価と具体的な実装指針により、実現可能性が確認され、明確な実装パスが定まった。
|
||||
|
||||
**「Everything is Box」哲学を、言語の壁を超えて実現する革命的な一歩。**
|
||||
@ -0,0 +1,55 @@
|
||||
# Phase 10.1b - 環境設定とセットアップ
|
||||
|
||||
## 🎯 このフェーズの目的
|
||||
PythonParserBox実装に必要な開発環境を整える。
|
||||
|
||||
## 📋 セットアップ手順
|
||||
|
||||
### 1. Python 3.11環境の固定
|
||||
```bash
|
||||
# pyenvを使用する場合
|
||||
pyenv install 3.11.9
|
||||
pyenv local 3.11.9
|
||||
|
||||
# または直接指定
|
||||
python3.11 --version # 3.11.9であることを確認
|
||||
```
|
||||
|
||||
### 2. Cargo.tomlへの依存関係追加
|
||||
```toml
|
||||
[dependencies]
|
||||
pyo3 = { version = "0.22", features = ["auto-initialize"] }
|
||||
pyo3-numpy = "0.22" # NumPy連携用(Phase 3で使用)
|
||||
serde_json = "1.0" # JSON中間表現用
|
||||
```
|
||||
|
||||
### 3. 環境変数の設定
|
||||
```bash
|
||||
# テレメトリー用
|
||||
export NYASH_PYTHONPARSER_TELEMETRY=1 # 基本統計
|
||||
export NYASH_PYTHONPARSER_TELEMETRY=2 # 詳細ログ
|
||||
export NYASH_PYTHONPARSER_STRICT=1 # フォールバック時にパニック(CI用)
|
||||
```
|
||||
|
||||
### 4. ディレクトリ構造の準備
|
||||
```
|
||||
src/boxes/python_parser_box/
|
||||
├── mod.rs # メインモジュール
|
||||
├── py_helper.rs # Python側ヘルパー
|
||||
├── converter.rs # AST変換器
|
||||
└── telemetry.rs # テレメトリー実装
|
||||
```
|
||||
|
||||
## ✅ 完了条件
|
||||
- [ ] Python 3.11.9がインストールされている
|
||||
- [ ] Cargo.tomlに依存関係が追加されている
|
||||
- [ ] 開発ディレクトリ構造が準備されている
|
||||
- [ ] 環境変数の設定方法を理解している
|
||||
|
||||
## 🚨 注意事項
|
||||
- **Python 3.11固定必須** - AST安定性のため
|
||||
- **pyo3::prepare_freethreaded_python()** を一度だけ呼ぶ
|
||||
- GIL管理に注意(Phase 10.1cで詳細)
|
||||
|
||||
## ⏭️ 次のフェーズ
|
||||
→ Phase 10.1c (パーサー統合実装)
|
||||
@ -0,0 +1,61 @@
|
||||
# Phase 10.1c - パーサー統合実装
|
||||
|
||||
## 🎯 このフェーズの目的
|
||||
pyo3を使ってCPythonパーサーをNyashに統合し、Python AST → JSON → Nyash ASTの変換パイプラインを構築する。
|
||||
|
||||
## 📁 実装ドキュメント
|
||||
- **`python_parser_box_implementation_plan.txt`** - 技術的実装計画
|
||||
- **`builtin_box_implementation_flow.txt`** - ビルトインBox実装フロー
|
||||
|
||||
## 🔧 実装タスク
|
||||
|
||||
### 1. PythonParserBoxの基本構造
|
||||
```rust
|
||||
pub struct PythonParserBox {
|
||||
base: BoxBase,
|
||||
py_helper: Arc<Mutex<PyHelper>>,
|
||||
}
|
||||
```
|
||||
|
||||
### 2. GIL管理の実装
|
||||
```rust
|
||||
// ✅ 良い例:GILを最小限に
|
||||
let json_ast = Python::with_gil(|py| {
|
||||
py_helper.parse_to_json(py, code)
|
||||
})?;
|
||||
|
||||
// GIL外でRust処理
|
||||
let nyash_ast = py.allow_threads(|| {
|
||||
convert_json_to_nyash(json_ast)
|
||||
});
|
||||
```
|
||||
|
||||
### 3. Python側ヘルパー実装
|
||||
- `ast.parse()` → JSON変換
|
||||
- 位置情報の保持(lineno, col_offset)
|
||||
- Python 3.11固定チェック
|
||||
|
||||
### 4. 関数単位フォールバック判定
|
||||
```rust
|
||||
pub fn can_compile(&self, func_def: &PythonAst) -> CompileResult {
|
||||
// サポートされているノードかチェック
|
||||
// CompileResult::Compile or CompileResult::Fallback
|
||||
}
|
||||
```
|
||||
|
||||
## ✅ 完了条件
|
||||
- [ ] PythonParserBoxがビルトインBoxとして登録されている
|
||||
- [ ] `parse_to_json()` メソッドが動作する
|
||||
- [ ] GIL管理が適切に実装されている
|
||||
- [ ] テレメトリー基盤が組み込まれている
|
||||
- [ ] 簡単なPythonコードでJSON ASTが取得できる
|
||||
|
||||
## 🧪 動作確認
|
||||
```nyash
|
||||
local py = new PythonParserBox()
|
||||
local json_ast = py.parse_to_json("def hello(): return 'Hello'")
|
||||
print(json_ast) // JSON ASTが表示される
|
||||
```
|
||||
|
||||
## ⏭️ 次のフェーズ
|
||||
→ Phase 10.1d (Core実装)
|
||||
@ -0,0 +1,553 @@
|
||||
# PythonParserBox ビルトインBox実装フロー(エキスパート統合版)
|
||||
~CPythonパーサー統合とPhase 1実装の具体的な流れ~
|
||||
更新日: 2025-08-27
|
||||
|
||||
## 🎯 全体の実装フロー
|
||||
|
||||
### Step 0: Python 3.11固定(エキスパート推奨)
|
||||
```
|
||||
- Python 3.11.9を使用(AST安定性確保)
|
||||
- pyenvまたはpython3.11コマンドで固定
|
||||
- py_versionとast_formatをJSON IRに必ず含める
|
||||
```
|
||||
|
||||
### Step 1: ビルトインBoxとしての基盤作成
|
||||
```
|
||||
1. src/boxes/python_parser_box/mod.rs を作成
|
||||
2. BoxBase + BoxCore統一アーキテクチャに準拠
|
||||
3. PythonParserBoxの基本構造を定義
|
||||
4. src/boxes/mod.rs に登録
|
||||
5. テレメトリー基盤を初期から組み込む
|
||||
```
|
||||
|
||||
### Step 2: pyo3統合とCPythonパーサー接続
|
||||
```
|
||||
1. Cargo.tomlに pyo3依存関係追加
|
||||
2. pyo3::prepare_freethreaded_python()で一度だけ初期化
|
||||
3. ast.parse()へのFFIブリッジ実装
|
||||
4. JSON中間表現への変換(Python側でJSON生成)
|
||||
5. GILは最小限に、py.allow_threads()でRust処理
|
||||
```
|
||||
|
||||
### Step 3: Phase 1機能の実装(必須意味論要素)
|
||||
```
|
||||
必須要素(Codex先生強調):
|
||||
- LEGBスコーピング + locals/freevars
|
||||
- デフォルト引数の定義時評価
|
||||
- イテレータプロトコル(for文)
|
||||
- for/else + while/else
|
||||
- Python真偽値判定
|
||||
- 短絡評価(and/or)
|
||||
|
||||
実装手順:
|
||||
1. 関数単位フォールバック戦略の実装
|
||||
2. 基本的なAST変換(def, if, for, while, return)
|
||||
3. 式の変換(算術/比較/論理演算子、関数呼び出し)
|
||||
4. Nyash ASTへの意味論を保ったマッピング
|
||||
5. Differential Testingフレームワーク
|
||||
```
|
||||
|
||||
## 📝 具体的な実装コード
|
||||
|
||||
### 1. ビルトインBox定義(src/boxes/python_parser_box/mod.rs)
|
||||
```rust
|
||||
use crate::core::{BoxBase, BoxCore, NyashBox};
|
||||
use crate::ast;
|
||||
use pyo3::prelude::*;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
pub struct PythonParserBox {
|
||||
base: BoxBase,
|
||||
py_helper: Arc<Mutex<PyHelper>>, // Python実行環境
|
||||
}
|
||||
|
||||
impl BoxCore for PythonParserBox {
|
||||
fn box_id(&self) -> u64 {
|
||||
self.base.box_id()
|
||||
}
|
||||
|
||||
fn parent_type_id(&self) -> Option<std::any::TypeId> {
|
||||
self.base.parent_type_id()
|
||||
}
|
||||
|
||||
fn fmt_box(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
write!(f, "PythonParserBox#{}", self.box_id())
|
||||
}
|
||||
}
|
||||
|
||||
impl NyashBox for PythonParserBox {
|
||||
fn type_name(&self) -> &'static str {
|
||||
"PythonParserBox"
|
||||
}
|
||||
|
||||
fn clone_box(&self) -> Box<dyn NyashBox> {
|
||||
Box::new(PythonParserBox {
|
||||
base: BoxBase::new(),
|
||||
py_helper: self.py_helper.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. メソッド実装(Phase 1対応)
|
||||
```rust
|
||||
// テレメトリー用構造体
|
||||
#[derive(Default)]
|
||||
pub struct CompilationTelemetry {
|
||||
compiled_functions: Vec<String>,
|
||||
fallback_functions: Vec<(String, String, usize)>, // (name, reason, lineno)
|
||||
unsupported_nodes: HashMap<String, usize>, // node_type -> count
|
||||
}
|
||||
|
||||
impl PythonParserBox {
|
||||
// コンストラクタ
|
||||
pub fn new() -> Result<Self, String> {
|
||||
// 一度だけ初期化
|
||||
static INIT: std::sync::Once = std::sync::Once::new();
|
||||
INIT.call_once(|| {
|
||||
pyo3::prepare_freethreaded_python();
|
||||
});
|
||||
|
||||
// Python環境の初期化
|
||||
Python::with_gil(|py| {
|
||||
// Python 3.11確認
|
||||
let version = py.version_info();
|
||||
if version.major != 3 || version.minor != 11 {
|
||||
return Err(format!("Python 3.11 required, got {}.{}",
|
||||
version.major, version.minor));
|
||||
}
|
||||
|
||||
let helper = PyHelper::new(py)?;
|
||||
Ok(PythonParserBox {
|
||||
base: BoxBase::new(),
|
||||
py_helper: Arc::new(Mutex::new(helper)),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Python code → JSON AST
|
||||
pub fn parse_to_json(&self, code: &str) -> Result<String, String> {
|
||||
let helper = self.py_helper.lock().unwrap();
|
||||
Python::with_gil(|py| {
|
||||
helper.parse_to_json(py, code)
|
||||
})
|
||||
}
|
||||
|
||||
// JSON AST → Nyash AST(Phase 1機能のみ)
|
||||
pub fn json_to_nyash_ast(&self, json: &str) -> Result<ast::Program, String> {
|
||||
let py_ast: Phase1PythonAst = serde_json::from_str(json)
|
||||
.map_err(|e| format!("JSON parse error: {}", e))?;
|
||||
|
||||
let converter = Phase1Converter::new();
|
||||
converter.convert(py_ast)
|
||||
}
|
||||
|
||||
// 直接実行(関数単位フォールバック)
|
||||
pub fn run(&self, code: &str) -> Result<Box<dyn NyashBox>, String> {
|
||||
// まずJSON ASTを取得
|
||||
let json_ast = self.parse_to_json(code)?;
|
||||
let py_ast: serde_json::Value = serde_json::from_str(&json_ast)?;
|
||||
|
||||
// モジュール内の各関数をチェック
|
||||
let compiler = FunctionCompiler::new();
|
||||
let module_result = compiler.compile_module(&py_ast)?;
|
||||
|
||||
// テレメトリー出力(環境変数で制御)
|
||||
if std::env::var("NYASH_PYTHONPARSER_TELEMETRY").is_ok() {
|
||||
compiler.print_telemetry();
|
||||
}
|
||||
|
||||
// 実行(コンパイル済み関数はMIR、他はCPython)
|
||||
module_result.execute()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Python側ヘルパー実装
|
||||
```rust
|
||||
// Pythonコードを文字列として埋め込み
|
||||
const PYTHON_HELPER_CODE: &str = r#"
|
||||
import ast
|
||||
import json
|
||||
import sys
|
||||
|
||||
# Python 3.11固定チェック
|
||||
assert sys.version_info[:2] == (3, 11), f"Python 3.11 required, got {sys.version}"
|
||||
|
||||
def ast_to_dict(node):
|
||||
"""Phase 1: 基本的なAST要素のみ変換(エキスパート推奨JSON IR)"""
|
||||
|
||||
result = {
|
||||
"node_type": node.__class__.__name__,
|
||||
"py_version": "3.11",
|
||||
"ast_format": "v1"
|
||||
}
|
||||
|
||||
# 位置情報(エラー診断用)
|
||||
if hasattr(node, 'lineno'):
|
||||
result['lineno'] = node.lineno
|
||||
result['col_offset'] = node.col_offset
|
||||
if hasattr(node, 'end_lineno'):
|
||||
result['end_lineno'] = node.end_lineno
|
||||
result['end_col_offset'] = node.end_col_offset
|
||||
if isinstance(node, ast.Module):
|
||||
return {
|
||||
"type": "Module",
|
||||
"body": [ast_to_dict(stmt) for stmt in node.body]
|
||||
}
|
||||
elif isinstance(node, ast.FunctionDef):
|
||||
# 意味論上重要:デフォルト引数情報を保存
|
||||
args_info = {
|
||||
"args": [arg.arg for arg in node.args.args],
|
||||
"defaults": [ast_to_dict(default) for default in node.args.defaults],
|
||||
"kwonlyargs": [arg.arg for arg in node.args.kwonlyargs],
|
||||
"kw_defaults": [ast_to_dict(d) if d else None for d in node.args.kw_defaults]
|
||||
}
|
||||
result.update({
|
||||
"name": node.name,
|
||||
"args": args_info,
|
||||
"body": [ast_to_dict(stmt) for stmt in node.body],
|
||||
"decorator_list": [], # Phase 1では未対応
|
||||
"support_level": "full" # コンパイル可能
|
||||
})
|
||||
return result
|
||||
elif isinstance(node, ast.Return):
|
||||
return {
|
||||
"type": "Return",
|
||||
"value": ast_to_dict(node.value) if node.value else None
|
||||
}
|
||||
elif isinstance(node, ast.BinOp):
|
||||
return {
|
||||
"type": "BinOp",
|
||||
"op": node.op.__class__.__name__,
|
||||
"left": ast_to_dict(node.left),
|
||||
"right": ast_to_dict(node.right)
|
||||
}
|
||||
elif isinstance(node, ast.Call):
|
||||
return {
|
||||
"type": "Call",
|
||||
"func": ast_to_dict(node.func),
|
||||
"args": [ast_to_dict(arg) for arg in node.args]
|
||||
}
|
||||
elif isinstance(node, ast.Name):
|
||||
return {
|
||||
"type": "Name",
|
||||
"id": node.id
|
||||
}
|
||||
elif isinstance(node, ast.Constant):
|
||||
return {
|
||||
"type": "Constant",
|
||||
"value": node.value
|
||||
}
|
||||
elif isinstance(node, ast.If):
|
||||
return {
|
||||
"type": "If",
|
||||
"test": ast_to_dict(node.test),
|
||||
"body": [ast_to_dict(stmt) for stmt in node.body],
|
||||
"orelse": [ast_to_dict(stmt) for stmt in node.orelse]
|
||||
}
|
||||
elif isinstance(node, ast.For):
|
||||
# 意味論上重要:for/else構文
|
||||
result.update({
|
||||
"target": ast_to_dict(node.target),
|
||||
"iter": ast_to_dict(node.iter),
|
||||
"body": [ast_to_dict(stmt) for stmt in node.body],
|
||||
"orelse": [ast_to_dict(stmt) for stmt in node.orelse], # else節
|
||||
"support_level": "full"
|
||||
})
|
||||
return result
|
||||
|
||||
elif isinstance(node, ast.While):
|
||||
# 意味論上重要:while/else構文
|
||||
result.update({
|
||||
"test": ast_to_dict(node.test),
|
||||
"body": [ast_to_dict(stmt) for stmt in node.body],
|
||||
"orelse": [ast_to_dict(stmt) for stmt in node.orelse], # else節
|
||||
"support_level": "full"
|
||||
})
|
||||
return result
|
||||
|
||||
elif isinstance(node, ast.BoolOp):
|
||||
# 意味論上重要:短絡評価
|
||||
result.update({
|
||||
"op": node.op.__class__.__name__, # And, Or
|
||||
"values": [ast_to_dict(v) for v in node.values],
|
||||
"support_level": "full"
|
||||
})
|
||||
return result
|
||||
else:
|
||||
# Phase 1では未対応(テレメトリー用)
|
||||
return {
|
||||
"node_type": "Unsupported",
|
||||
"original_type": type(node).__name__,
|
||||
"support_level": "fallback",
|
||||
"lineno": getattr(node, 'lineno', -1)
|
||||
}
|
||||
|
||||
def parse_to_json(code):
|
||||
try:
|
||||
tree = ast.parse(code)
|
||||
return json.dumps(ast_to_dict(tree))
|
||||
except Exception as e:
|
||||
return json.dumps({"type": "Error", "message": str(e)})
|
||||
"#;
|
||||
|
||||
struct PyHelper {
|
||||
// Python側のヘルパー関数への参照を保持
|
||||
parse_func: PyObject,
|
||||
}
|
||||
|
||||
impl PyHelper {
|
||||
fn new(py: Python) -> PyResult<Self> {
|
||||
// ヘルパーコードをPythonで実行
|
||||
let helpers = PyModule::from_code(py, PYTHON_HELPER_CODE, "helper.py", "helper")?;
|
||||
let parse_func = helpers.getattr("parse_to_json")?.to_object(py);
|
||||
|
||||
Ok(PyHelper { parse_func })
|
||||
}
|
||||
|
||||
fn parse_to_json(&self, py: Python, code: &str) -> Result<String, String> {
|
||||
match self.parse_func.call1(py, (code,)) {
|
||||
Ok(result) => result.extract::<String>(py)
|
||||
.map_err(|e| format!("Extract error: {}", e)),
|
||||
Err(e) => Err(format!("Parse error: {}", e))
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Phase 1 AST変換器
|
||||
```rust
|
||||
struct Phase1Converter;
|
||||
|
||||
impl Phase1Converter {
|
||||
fn new() -> Self {
|
||||
Phase1Converter
|
||||
}
|
||||
|
||||
fn convert(&self, py_ast: Phase1PythonAst) -> Result<ast::Program, String> {
|
||||
match py_ast {
|
||||
Phase1PythonAst::Module { body } => {
|
||||
let mut items = vec![];
|
||||
for stmt in body {
|
||||
match self.convert_statement(stmt)? {
|
||||
Some(item) => items.push(item),
|
||||
None => {} // 未対応要素はスキップ
|
||||
}
|
||||
}
|
||||
Ok(ast::Program { items })
|
||||
}
|
||||
_ => Err("Expected Module at top level".into())
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_statement(&self, stmt: Phase1PythonAst) -> Result<Option<ast::ProgramItem>, String> {
|
||||
match stmt {
|
||||
Phase1PythonAst::FunctionDef { name, args, body } => {
|
||||
// Python def → Nyash function
|
||||
let params = args.into_iter()
|
||||
.map(|arg| ast::Parameter { name: arg, ty: None })
|
||||
.collect();
|
||||
|
||||
let nyash_body = self.convert_body(body)?;
|
||||
|
||||
Ok(Some(ast::ProgramItem::Function(ast::FunctionDef {
|
||||
name,
|
||||
params,
|
||||
body: nyash_body,
|
||||
return_type: None,
|
||||
})))
|
||||
}
|
||||
Phase1PythonAst::Return { value } => {
|
||||
let expr = value
|
||||
.map(|v| self.convert_expression(v))
|
||||
.transpose()?;
|
||||
|
||||
Ok(Some(ast::ProgramItem::Statement(ast::Statement::Return(expr))))
|
||||
}
|
||||
// 他の文も同様に変換
|
||||
_ => Ok(None) // Phase 1では未対応
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_expression(&self, expr: Phase1PythonAst) -> Result<ast::Expression, String> {
|
||||
match expr {
|
||||
Phase1PythonAst::BinOp { op, left, right } => {
|
||||
let left = Box::new(self.convert_expression(*left)?);
|
||||
let right = Box::new(self.convert_expression(*right)?);
|
||||
|
||||
let op = match op.as_str() {
|
||||
"Add" => ast::BinaryOp::Add,
|
||||
"Sub" => ast::BinaryOp::Sub,
|
||||
"Mul" => ast::BinaryOp::Mul,
|
||||
"Div" => ast::BinaryOp::Div,
|
||||
_ => return Err(format!("Unsupported operator: {}", op))
|
||||
};
|
||||
|
||||
Ok(ast::Expression::BinaryOp { op, left, right })
|
||||
}
|
||||
Phase1PythonAst::Constant { value } => {
|
||||
// Python定数 → Nyashリテラル
|
||||
match value {
|
||||
serde_json::Value::Number(n) => {
|
||||
if let Some(i) = n.as_i64() {
|
||||
Ok(ast::Expression::Integer(i))
|
||||
} else if let Some(f) = n.as_f64() {
|
||||
Ok(ast::Expression::Float(f))
|
||||
} else {
|
||||
Err("Unsupported number type".into())
|
||||
}
|
||||
}
|
||||
serde_json::Value::String(s) => {
|
||||
Ok(ast::Expression::String(s))
|
||||
}
|
||||
serde_json::Value::Bool(b) => {
|
||||
Ok(ast::Expression::Bool(b))
|
||||
}
|
||||
_ => Err("Unsupported constant type".into())
|
||||
}
|
||||
}
|
||||
// 他の式も同様
|
||||
_ => Err("Unsupported expression in Phase 1".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5. インタープリター統合(src/interpreter/builtins.rs)
|
||||
```rust
|
||||
// ビルトインBox登録に追加
|
||||
pub fn register_builtin_boxes(env: &mut Environment) {
|
||||
// 既存のBox登録...
|
||||
|
||||
// PythonParserBox追加
|
||||
env.register_builtin_box("PythonParserBox", || {
|
||||
match PythonParserBox::new() {
|
||||
Ok(parser) => Arc::new(parser) as Arc<dyn NyashBox>,
|
||||
Err(e) => panic!("Failed to initialize PythonParserBox: {}", e)
|
||||
}
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### 6. 使用例とテストケース
|
||||
```nyash
|
||||
// test_python_parser_phase1.nyash
|
||||
local py = new PythonParserBox()
|
||||
|
||||
// Phase 1: 基本的な関数定義と演算
|
||||
local code = """
|
||||
def add(x, y):
|
||||
return x + y
|
||||
|
||||
def multiply(x, y):
|
||||
return x * y
|
||||
|
||||
def calculate(a, b):
|
||||
sum_val = add(a, b)
|
||||
prod_val = multiply(a, b)
|
||||
return sum_val + prod_val
|
||||
"""
|
||||
|
||||
// パースしてJSON ASTを確認
|
||||
local json_ast = py.parse_to_json(code)
|
||||
print("JSON AST: " + json_ast)
|
||||
|
||||
// Nyash ASTに変換
|
||||
local nyash_ast = py.json_to_nyash_ast(json_ast)
|
||||
print("Conversion successful!")
|
||||
|
||||
// 実行(最初はCPython経由)
|
||||
local result = py.run(code + "\nprint(calculate(10, 5))")
|
||||
```
|
||||
|
||||
## 📊 段階的な実装計画
|
||||
|
||||
### Week 1: 基盤構築
|
||||
- [ ] PythonParserBoxの基本構造
|
||||
- [ ] pyo3統合とPython環境初期化
|
||||
- [ ] parse_to_json基本実装
|
||||
- [ ] エラーハンドリング
|
||||
|
||||
### Week 2: Phase 1変換器
|
||||
- [ ] Phase1PythonAstの定義
|
||||
- [ ] Phase1Converterの実装
|
||||
- [ ] 基本的な文と式の変換
|
||||
- [ ] テストケース作成
|
||||
|
||||
### Week 3: 統合とテスト
|
||||
- [ ] インタープリター統合
|
||||
- [ ] CPython exec経由の実行
|
||||
- [ ] ベンチマーク準備
|
||||
- [ ] ドキュメント整備
|
||||
|
||||
## 🚀 期待される成果
|
||||
|
||||
### Phase 1完了時点で実現できること:
|
||||
1. **基本的なPythonコードの実行**
|
||||
- 関数定義、算術演算、条件分岐、ループ
|
||||
|
||||
2. **Nyash ASTへの変換**
|
||||
- 将来のMIR/JIT最適化への道筋
|
||||
|
||||
3. **統合開発環境**
|
||||
- PythonコードとNyashコードの混在実行
|
||||
|
||||
4. **性能測定基盤**
|
||||
- CPython実行 vs Nyash実行の比較
|
||||
|
||||
## 📡 テレメトリー出力例
|
||||
|
||||
```bash
|
||||
# 環境変数で制御
|
||||
export NYASH_PYTHONPARSER_TELEMETRY=1 # 基本統計
|
||||
export NYASH_PYTHONPARSER_TELEMETRY=2 # 詳細ログ
|
||||
export NYASH_PYTHONPARSER_STRICT=1 # フォールバック時にパニック
|
||||
|
||||
# 実行例
|
||||
./target/release/nyash test_python_parser.nyash
|
||||
|
||||
# 出力
|
||||
[PythonParser] Module: test.py (Python 3.11)
|
||||
Functions: 10 total
|
||||
Compiled: 7 (70%) → Nyash MIR/JIT
|
||||
Fallback: 3 (30%) → CPython exec
|
||||
- async_function: unsupported node 'AsyncFunctionDef' at line 23
|
||||
- generator_func: unsupported node 'Yield' at line 45
|
||||
- decorator_func: unsupported node 'decorator_list' at line 67
|
||||
|
||||
Unsupported Nodes Summary:
|
||||
AsyncFunctionDef: 1
|
||||
Yield: 2
|
||||
ClassDef: 1
|
||||
```
|
||||
|
||||
## 📊 Differential Testingフレームワーク
|
||||
|
||||
```rust
|
||||
// CPythonとNyashの出力比較
|
||||
pub fn differential_test(code: &str) -> TestResult {
|
||||
// CPythonで実行(オラクル)
|
||||
let python_result = Python::with_gil(|py| {
|
||||
capture_python_execution(py, code)
|
||||
})?;
|
||||
|
||||
// Nyashで実行
|
||||
let nyash_result = execute_with_pythonparser(code)?;
|
||||
|
||||
// 結果比較
|
||||
compare_results(python_result, nyash_result)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
作成日: 2025-08-27
|
||||
Phase 1実装の具体的な手順とエキスパートフィードバック統合
|
||||
@ -0,0 +1,361 @@
|
||||
# PythonParserBox実装計画(統合版)
|
||||
更新日: 2025-08-27
|
||||
|
||||
## 🎯 エキスパートからの統合フィードバック
|
||||
|
||||
### 最重要ポイント(両エキスパートが一致)
|
||||
1. **関数単位のフォールバック戦略**
|
||||
- ファイル全体でなく関数レベルでコンパイル/フォールバックを切り替え
|
||||
- 未対応機能を含む関数はCPython exec、対応済み関数はNyash MIR/JIT
|
||||
|
||||
2. **Python 3.11固定**
|
||||
- AST安定性の確保(3.8 Constant統一、3.10 match/case、3.12位置情報)
|
||||
- `py_version`と`ast_format`をJSON IRに埋め込む
|
||||
|
||||
3. **意味論の正確な実装が最優先**
|
||||
- 最適化より先にPython互換性を確保
|
||||
- 特に: イテレータプロトコル、真偽値判定、スコーピング規則(LEGB)
|
||||
|
||||
4. **GIL管理の最小化**
|
||||
- Python側でJSON生成(`ast.NodeVisitor` + `json.dumps`)
|
||||
- Rust側で解析(GIL外で実行)
|
||||
- `py.allow_threads(|| { ... })`で重い処理をGIL外実行
|
||||
|
||||
5. **テレメトリー重視**
|
||||
- 未対応ノードの記録(`support_level`フィールド)
|
||||
- フォールバック率の計測
|
||||
- ソース位置情報の保持(`lineno/col_offset/end_*`)
|
||||
|
||||
### Differential Testing戦略
|
||||
- **世界中のPythonコードがNyashのテストケース**
|
||||
- CPythonを「オラクル」として使用
|
||||
- 出力、戻り値、例外を比較
|
||||
- Grammar-based fuzzing(Hypothesis活用)
|
||||
|
||||
## 技術的実装方針
|
||||
|
||||
### 1. CPythonパーサー統合(pyo3使用)
|
||||
```rust
|
||||
// Cargo.toml
|
||||
[dependencies]
|
||||
pyo3 = { version = "0.22", features = ["auto-initialize"] }
|
||||
pyo3-numpy = "0.22" // NumPy連携用
|
||||
|
||||
// 初期化(一度だけ)
|
||||
pyo3::prepare_freethreaded_python();
|
||||
|
||||
// Python側ヘルパー(embedded)
|
||||
const PYTHON_HELPER: &str = r#"
|
||||
import ast
|
||||
import json
|
||||
import sys
|
||||
|
||||
def parse_to_json(code, filename="<string>", mode="exec"):
|
||||
tree = ast.parse(code, filename, mode)
|
||||
return json.dumps(ast_to_dict(tree))
|
||||
|
||||
def ast_to_dict(node):
|
||||
result = {}
|
||||
|
||||
# 必須フィールド
|
||||
result['node_type'] = node.__class__.__name__
|
||||
result['py_version'] = f"{sys.version_info.major}.{sys.version_info.minor}"
|
||||
|
||||
# 位置情報(エラー診断用)
|
||||
if hasattr(node, 'lineno'):
|
||||
result['lineno'] = node.lineno
|
||||
result['col_offset'] = node.col_offset
|
||||
if hasattr(node, 'end_lineno'): # Python 3.8+
|
||||
result['end_lineno'] = node.end_lineno
|
||||
result['end_col_offset'] = node.end_col_offset
|
||||
|
||||
# サポートレベル(Nyash側で設定)
|
||||
result['support_level'] = 'unknown'
|
||||
|
||||
# ASTフィールド
|
||||
if isinstance(node, ast.AST):
|
||||
for field in node._fields:
|
||||
value = getattr(node, field)
|
||||
result[field] = ast_to_dict(value)
|
||||
elif isinstance(node, list):
|
||||
return [ast_to_dict(x) for x in node]
|
||||
else:
|
||||
return node
|
||||
|
||||
return result
|
||||
"#;
|
||||
```
|
||||
|
||||
### 2. 最小実装セット(Phase 1: Must-Have)
|
||||
```
|
||||
Phase 1 意味論の必須要素(Codex先生強調):
|
||||
- LEGB + locals/freevars(スコーピング)
|
||||
- デフォルト引数の評価タイミング(定義時)
|
||||
- イテレータベースのfor文
|
||||
- for/else + while/else(Python独特)
|
||||
- Python真偽値判定(__bool__ → __len__)
|
||||
- 短絡評価(and/or)
|
||||
|
||||
Phase 1 AST構造:
|
||||
├─ Module (py_version, ast_format)
|
||||
├─ FunctionDef (name, args, body, decorator_list=[])
|
||||
│ └─ arguments (args, defaults, kwonlyargs=[], kw_defaults=[])
|
||||
├─ Return (value)
|
||||
├─ Assign (targets, value)
|
||||
├─ AugAssign (target, op, value) # +=, -=等
|
||||
└─ Expr (value)
|
||||
|
||||
Phase 1 式:
|
||||
├─ BinOp (left, op, right)
|
||||
│ └─ ops: Add, Sub, Mult, Div, FloorDiv, Mod, Pow
|
||||
├─ Compare (left, ops, comparators)
|
||||
│ └─ ops: Eq, NotEq, Lt, LtE, Gt, GtE, Is, IsNot
|
||||
├─ BoolOp (op, values) # and/or
|
||||
├─ UnaryOp (op, operand) # not, -, +
|
||||
├─ Call (func, args, keywords=[])
|
||||
├─ Name (id, ctx=Load/Store/Del)
|
||||
├─ Constant (value) # Python 3.8+統一
|
||||
└─ IfExp (test, body, orelse) # 三項演算子
|
||||
|
||||
Phase 1 制御フロー:
|
||||
├─ If (test, body, orelse)
|
||||
├─ While (test, body, orelse) # else節対応必須
|
||||
├─ For (target, iter, body, orelse) # else節対応必須
|
||||
├─ Break
|
||||
└─ Continue
|
||||
```
|
||||
|
||||
### 3. 関数単位フォールバック戦略
|
||||
```rust
|
||||
// 関数単位のコンパイル判定
|
||||
pub struct FunctionCompiler {
|
||||
supported_nodes: HashSet<&'static str>,
|
||||
telemetry: CompilationTelemetry,
|
||||
}
|
||||
|
||||
impl FunctionCompiler {
|
||||
pub fn can_compile(&self, func_def: &PythonAst) -> CompileResult {
|
||||
let mut visitor = SupportChecker::new(&self.supported_nodes);
|
||||
visitor.visit(func_def);
|
||||
|
||||
if visitor.has_unsupported() {
|
||||
// CPython execへフォールバック
|
||||
CompileResult::Fallback {
|
||||
reason: visitor.unsupported_nodes(),
|
||||
location: func_def.location(),
|
||||
}
|
||||
} else {
|
||||
// Nyash MIR/JITへコンパイル
|
||||
CompileResult::Compile
|
||||
}
|
||||
}
|
||||
|
||||
pub fn compile_module(&mut self, module: &PythonAst) -> ModuleUnit {
|
||||
let mut units = vec![];
|
||||
|
||||
// モジュールトップレベルはPythonで実行(globals設定)
|
||||
units.push(ExecutionUnit::PythonExec(module.top_level));
|
||||
|
||||
// 各関数を判定
|
||||
for func in module.functions() {
|
||||
match self.can_compile(func) {
|
||||
CompileResult::Compile => {
|
||||
let mir = self.compile_to_mir(func);
|
||||
units.push(ExecutionUnit::NyashFunction(mir));
|
||||
self.telemetry.record_compiled(func.name);
|
||||
}
|
||||
CompileResult::Fallback { reason, location } => {
|
||||
units.push(ExecutionUnit::PythonThunk(func));
|
||||
self.telemetry.record_fallback(func.name, reason, location);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ModuleUnit { units }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4. データ共有戦略
|
||||
```rust
|
||||
// NdArrayBox定義
|
||||
pub struct NdArrayBox {
|
||||
base: BoxBase,
|
||||
py_array: Py<PyArray<f64, Dim<[usize; 2]>>>, // Python側の参照保持
|
||||
// 操作時のみGIL取得してArrayViewを取る
|
||||
}
|
||||
|
||||
impl NdArrayBox {
|
||||
pub fn to_view(&self) -> PyResult<ArrayView2<f64>> {
|
||||
Python::with_gil(|py| {
|
||||
let array = self.py_array.as_ref(py);
|
||||
Ok(array.readonly())
|
||||
})
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4. 実装ロードマップ
|
||||
|
||||
#### Phase 1: パーサー統合(1-2週間)
|
||||
- [ ] pyo3セットアップとPythonParserBox骨格
|
||||
- [ ] Python側parse_to_jsonヘルパー実装
|
||||
- [ ] JSON→Nyash AST最小変換
|
||||
- [ ] run()メソッド(CPython exec委譲)
|
||||
- [ ] 例外変換(PyErr → NyashError)
|
||||
|
||||
#### Phase 2: MIR変換(2-4週間)
|
||||
- [ ] AST→MIR変換器(最小セット)
|
||||
- [ ] 数値演算プリミティブ実装
|
||||
- [ ] スコープ解決(関数ローカル/グローバル)
|
||||
- [ ] 基本的な制御フロー(If/While)
|
||||
|
||||
#### Phase 3: NumPy統合(並行可能)
|
||||
- [ ] pyo3-numpy統合
|
||||
- [ ] NdArrayBox実装
|
||||
- [ ] ゼロコピーベンチマーク
|
||||
- [ ] バッファプロトコル対応
|
||||
|
||||
#### Phase 4: 最適化と拡張
|
||||
- [ ] 型特化とガード最適化
|
||||
- [ ] 例外処理(try/except)
|
||||
- [ ] クラス/メソッド対応
|
||||
- [ ] import統合
|
||||
|
||||
## 性能目標(現実的な見積もり)
|
||||
|
||||
| コードタイプ | 期待される高速化 | 備考 |
|
||||
|------------|----------------|------|
|
||||
| 純Pythonループ | 2-10倍 | 型安定なホットパス |
|
||||
| 関数呼び出し多 | 1.5-3倍 | インライン化効果 |
|
||||
| NumPy処理中心 | 1.0-1.2倍 | 既に最適化済み |
|
||||
| 動的特性多用 | 1.2-3倍 | ガード頻発で限定的 |
|
||||
|
||||
## 実装上の注意点(エキスパート推奨)
|
||||
|
||||
### 意味論の重要な違い(Phase 1で対応必須)
|
||||
|
||||
1. **制御フロー**
|
||||
- `for`文: イテレータプロトコル必須(`__iter__`/`__next__`)
|
||||
- `for/else`, `while/else`: breakしなかった場合のelse実行
|
||||
- 短絡評価: `and`は左がFalseなら右を評価しない
|
||||
|
||||
2. **スコープ規則(LEGB)**
|
||||
```python
|
||||
# Local → Enclosing → Global → Builtins
|
||||
global_var = 1
|
||||
|
||||
def outer():
|
||||
enclosing_var = 2
|
||||
|
||||
def inner():
|
||||
local_var = 3
|
||||
nonlocal enclosing_var # 明示的な宣言
|
||||
global global_var # 明示的な宣言
|
||||
```
|
||||
|
||||
3. **数値演算の違い**
|
||||
- `/`: Python 3では常にfloat(true division)
|
||||
- `//`: floor division(整数除算)
|
||||
- 大整数: デフォルトで無限精度
|
||||
- `is` vs `==`: オブジェクト同一性 vs 値の等価性
|
||||
|
||||
4. **関数定義の罠**
|
||||
```python
|
||||
def f(x, y=[]): # デフォルト引数は定義時に1度だけ評価!
|
||||
y.append(x) # 全呼び出しで同じリストを共有
|
||||
return y
|
||||
```
|
||||
|
||||
### GIL管理のベストプラクティス
|
||||
|
||||
```rust
|
||||
// ❌ 悪い例: GILを長時間保持
|
||||
let result = Python::with_gil(|py| {
|
||||
let ast = parse_python(py, code)?;
|
||||
let json = convert_to_json(py, ast)?; // ここまでGIL必要
|
||||
let nyash_ast = parse_json(&json)?; // GIL不要なのに保持
|
||||
compile_to_mir(nyash_ast)? // GIL不要なのに保持
|
||||
});
|
||||
|
||||
// ✅ 良い例: GILを最小限に
|
||||
let json = Python::with_gil(|py| {
|
||||
let ast = parse_python(py, code)?;
|
||||
convert_to_json(py, ast) // JSON生成まで
|
||||
})?;
|
||||
|
||||
// GIL外で重い処理
|
||||
let nyash_ast = parse_json(&json)?;
|
||||
let mir = compile_to_mir(nyash_ast)?;
|
||||
|
||||
// 必要時のみ再取得
|
||||
Python::with_gil(|py| {
|
||||
py.allow_threads(|| {
|
||||
// 時間のかかるRust処理
|
||||
optimize_mir(mir)
|
||||
})
|
||||
})
|
||||
```
|
||||
|
||||
### テレメトリーとデバッグ
|
||||
|
||||
```rust
|
||||
// 環境変数で制御
|
||||
NYASH_PYTHONPARSER_TELEMETRY=1 # 基本統計
|
||||
NYASH_PYTHONPARSER_TELEMETRY=2 # 詳細ログ
|
||||
NYASH_PYTHONPARSER_STRICT=1 # フォールバック時にパニック(CI用)
|
||||
|
||||
// 出力例
|
||||
[PythonParser] Module: example.py
|
||||
Functions: 10 total
|
||||
Compiled: 7 (70%)
|
||||
Fallback: 3 (30%)
|
||||
- async_function: unsupported node 'AsyncFunctionDef' at line 23
|
||||
- generator_func: unsupported node 'Yield' at line 45
|
||||
- class_method: unsupported node 'ClassDef' at line 67
|
||||
```
|
||||
|
||||
## 次のステップ
|
||||
|
||||
### 即座に開始すべきこと
|
||||
|
||||
1. **Python 3.11環境固定**
|
||||
```bash
|
||||
pyenv install 3.11.9
|
||||
pyenv local 3.11.9
|
||||
```
|
||||
|
||||
2. **最小動作確認**
|
||||
```python
|
||||
# test_minimal.py
|
||||
def add(x, y):
|
||||
return x + y
|
||||
|
||||
result = add(10, 5)
|
||||
print(f"Result: {result}") # → Nyashで15が出力されれば成功!
|
||||
```
|
||||
|
||||
3. **テレメトリー基盤構築**
|
||||
- 未対応ノードの記録システム
|
||||
- フォールバック率の可視化
|
||||
- ソース位置情報の保持
|
||||
|
||||
4. **Differential Testingの準備**
|
||||
- CPythonとの出力比較フレームワーク
|
||||
- 標準出力、戻り値、例外のキャプチャ
|
||||
- テストコーパスの選定
|
||||
|
||||
### 成功の測定基準
|
||||
|
||||
| フェーズ | 目標 | 測定指標 |
|
||||
|---------|------|----------|
|
||||
| Phase 1 | 基本動作 | 簡単な数値計算の70%がコンパイル可能 |
|
||||
| Phase 2 | 実用性 | scikit-learnの基本アルゴリズムが動作 |
|
||||
| Phase 3 | 性能 | 純Pythonループで5倍以上の高速化 |
|
||||
| Phase 4 | 成熟度 | PyPIトップ100の30%が基本動作 |
|
||||
|
||||
## まとめ
|
||||
|
||||
このPythonParserBox実装は、単なる機能追加ではなく、Nyash言語の成熟度を飛躍的に高める戦略的プロジェクト。
|
||||
エキスパートの指摘を踏まえ、関数単位のフォールバック、Python 3.11固定、意味論の正確な実装、
|
||||
GIL最小化、テレメトリー重視で着実に実装を進める。
|
||||
@ -0,0 +1,72 @@
|
||||
# Phase 10.1d - Core実装(Phase 1機能)
|
||||
|
||||
## 🎯 このフェーズの目的
|
||||
Python AST → Nyash AST変換のPhase 1機能(基本構文)を実装する。
|
||||
|
||||
## 📁 実装ドキュメント
|
||||
- **`python_implementation_roadmap.txt`** - Phase別実装ロードマップ
|
||||
|
||||
## 🔧 Phase 1必須要素(Codex先生強調)
|
||||
|
||||
### 意味論の必須実装
|
||||
1. **LEGB + locals/freevars** - スコーピング規則
|
||||
2. **デフォルト引数の評価タイミング** - 定義時に一度だけ
|
||||
3. **イテレータベースのfor文** - `__iter__`/`__next__`プロトコル
|
||||
4. **for/else + while/else** - Python独特のelse節
|
||||
5. **Python真偽値判定** - `__bool__` → `__len__`
|
||||
6. **短絡評価** - and/orの正確な挙動
|
||||
|
||||
### サポートする文(Statement)
|
||||
- [x] def - 関数定義
|
||||
- [x] if/elif/else - 条件分岐
|
||||
- [x] for - ループ(else節対応必須)
|
||||
- [x] while - ループ(else節対応必須)
|
||||
- [x] break/continue - ループ制御
|
||||
- [x] return - 戻り値
|
||||
|
||||
### サポートする式(Expression)
|
||||
- [x] 算術演算子(+,-,*,/,//,%)
|
||||
- [x] 比較演算子(==,!=,<,>,<=,>=,is,is not)
|
||||
- [x] 論理演算子(and,or,not)- 短絡評価
|
||||
- [x] 関数呼び出し
|
||||
- [x] 変数参照/代入
|
||||
- [x] リテラル(数値/文字列/bool)
|
||||
|
||||
## 🧪 テストケース
|
||||
```python
|
||||
# Phase 1で動作すべきコード
|
||||
def fibonacci(n):
|
||||
if n <= 1:
|
||||
return n
|
||||
return fibonacci(n-1) + fibonacci(n-2)
|
||||
|
||||
# for/else のテスト
|
||||
for i in range(10):
|
||||
if i == 5:
|
||||
break
|
||||
else:
|
||||
print("No break") # 実行されない
|
||||
|
||||
# デフォルト引数の罠
|
||||
def append_to_list(item, lst=[]): # 定義時に評価!
|
||||
lst.append(item)
|
||||
return lst
|
||||
```
|
||||
|
||||
## ✅ 完了条件
|
||||
- [ ] 基本的な関数定義が変換できる
|
||||
- [ ] 制御フローが正しく変換される
|
||||
- [ ] 演算子が正しくマッピングされる
|
||||
- [ ] Python意味論が保たれている
|
||||
- [ ] 70%以上の関数がコンパイル可能
|
||||
|
||||
## 📊 テレメトリー確認
|
||||
```bash
|
||||
[PythonParser] Module: test.py (Python 3.11)
|
||||
Functions: 10 total
|
||||
Compiled: 7 (70%) ← 目標達成!
|
||||
Fallback: 3 (30%)
|
||||
```
|
||||
|
||||
## ⏭️ 次のフェーズ
|
||||
→ Phase 10.1e (トランスパイラー)
|
||||
@ -0,0 +1,264 @@
|
||||
# PythonParserBox 実装ロードマップ(エキスパート統合版)
|
||||
Based on ChatGPT5's Python Language Feature Surface Map + Expert Feedback
|
||||
更新日: 2025-08-27
|
||||
|
||||
## 🎯 実装優先順位の考え方(エキスパート統合)
|
||||
|
||||
### 🏯 核心戦略:関数単位フォールバック
|
||||
**両エキスパートが強調:** ファイル全体ではなく、**関数単位**でコンパイル/フォールバックを判断
|
||||
```python
|
||||
def supported_function(): # → Nyash MIR/JIT
|
||||
return x + y
|
||||
|
||||
def unsupported_function(): # → CPython exec
|
||||
yield from generator # Phase 1では未対応
|
||||
```
|
||||
|
||||
### 🔧 Python 3.11固定
|
||||
- AST安定性確保(3.8 Constant統一、3.10 match/case、3.12位置情報)
|
||||
- `py_version`と`ast_format`をJSON IRに埋め込む
|
||||
|
||||
### 🌟 Differential Testing戦略
|
||||
- **世界中のPythonコードがNyashのテストケースに**
|
||||
- CPythonをオラクルとして使用、出力・戻り値・例外を比較
|
||||
- 微妙なセマンティクスバグを自動発見
|
||||
|
||||
### 📊 テレメトリー重視
|
||||
- 未対応ノードの記録(`support_level`フィールド)
|
||||
- フォールバック率の計測
|
||||
- ソース位置情報保持(`lineno/col_offset/end_*`)
|
||||
|
||||
## 📋 Phase 1: Core Subset(1-2週間)
|
||||
**目標**: 基本的なPythonコードをNyashで実行可能にする
|
||||
|
||||
### ❌ Phase 1での必須意味論要素(Codex先生強調)
|
||||
- **LEGB + locals/freevars**: スコーピング規則
|
||||
- **デフォルト引数の評価タイミング**: 定義時に一度だけ
|
||||
- **イテレータベースのfor文**: `__iter__`/`__next__`プロトコル
|
||||
- **for/else + while/else**: Python独特のelse節
|
||||
- **Python真偽値判定**: `__bool__` → `__len__`
|
||||
- **短絡評価**: and/orの正確な挙動
|
||||
|
||||
### 文(Statement)
|
||||
- [x] def - 関数定義 → Nyash関数/Box
|
||||
- デフォルト引数の定義時評価
|
||||
- argumentsオブジェクトの完全解析
|
||||
- [x] if/elif/else - 条件分岐 → CondBr
|
||||
- [x] for - ループ → Loop + Iterator
|
||||
- **else節対応必須**
|
||||
- [x] while - ループ → Loop
|
||||
- **else節対応必須**
|
||||
- [x] break/continue - ループ制御
|
||||
- [x] return - 戻り値 → Return
|
||||
- [ ] pass - 空文
|
||||
- [ ] import(Phase 3へ延期)
|
||||
|
||||
### 式(Expression)
|
||||
- [x] 関数呼び出し - Call → BoxCall
|
||||
- [x] 算術演算子 - +,-,*,/,//,% → BinOp
|
||||
- `/`: true division(常にfloat)
|
||||
- `//`: floor division
|
||||
- [x] 比較演算子 - ==,!=,<,>,<=,>=,is,is not → Compare
|
||||
- [x] 論理演算子 - and,or,not → BoolOp/UnaryOp
|
||||
- 短絡評価の正確な実装
|
||||
- [x] 変数参照/代入 - Name → Load/Store
|
||||
- [x] リテラル - 数値/文字列/bool → Constant
|
||||
- [x] 三項演算子 - IfExp
|
||||
|
||||
### データ型(最小限)
|
||||
- [x] int → IntegerBox(大整数対応)
|
||||
- [x] float → FloatBox(NaNの扱い注意)
|
||||
- [x] str → StringBox
|
||||
- [x] bool → BoolBox
|
||||
- [x] list(基本) → ArrayBox
|
||||
|
||||
## 📋 Phase 2: Data Model(2-3週間)
|
||||
**目標**: Pythonの特殊メソッドをNyashのBoxメソッドにマッピング
|
||||
|
||||
### 特殊メソッド
|
||||
- [ ] __init__ → constructor/birth
|
||||
- [ ] __len__ → length()
|
||||
- [ ] __getitem__ → get()
|
||||
- [ ] __setitem__ → set()
|
||||
- [ ] __iter__ → iterator()
|
||||
- [ ] __str__ → toString()
|
||||
|
||||
### コレクション拡張
|
||||
- [ ] dict → MapBox
|
||||
- [ ] tuple → ImmutableArrayBox(新規)
|
||||
- [ ] set → SetBox(新規)
|
||||
|
||||
### 演算子オーバーロード
|
||||
- [ ] __add__, __sub__ 等 → operator+, operator-
|
||||
- [ ] __eq__, __lt__ 等 → equals(), compareTo()
|
||||
|
||||
## 📋 Phase 3: Advanced Features(1ヶ月)
|
||||
**目標**: Pythonの生産性の高い機能を実装
|
||||
|
||||
### 制御フロー拡張
|
||||
- [ ] try/except → エラーハンドリング
|
||||
- [ ] with文 → リソース管理
|
||||
- [ ] break/continue → ループ制御
|
||||
|
||||
### 高度な機能
|
||||
- [ ] ジェネレータ(yield) → GeneratorBox
|
||||
- [ ] デコレータ → 関数ラッパー
|
||||
- [ ] 内包表記 → 最適化されたループ
|
||||
- [ ] ラムダ式 → 匿名関数
|
||||
|
||||
### クラスシステム
|
||||
- [ ] class文 → box定義
|
||||
- [ ] 継承 → from構文
|
||||
- [ ] super() → from Parent.method()
|
||||
|
||||
## 📋 Phase 4: Modern Python(将来)
|
||||
**目標**: 最新のPython機能をサポート
|
||||
|
||||
### 非同期
|
||||
- [ ] async/await → 非同期Box(将来のNyash非同期と統合)
|
||||
- [ ] async for/with → 非同期イテレータ
|
||||
|
||||
### パターンマッチ(3.10+)
|
||||
- [ ] match/case → Nyashのパターンマッチ(将来実装時)
|
||||
|
||||
### 型ヒント
|
||||
- [ ] 型アノテーション → MIRの型情報として活用
|
||||
- [ ] typing モジュール → 静的型チェック情報
|
||||
|
||||
## 🚀 実装戦略
|
||||
|
||||
### Step 1: AST変換の基礎(Phase 1開始)
|
||||
```python
|
||||
# Python側でAST→JSON
|
||||
import ast
|
||||
import json
|
||||
|
||||
def parse_to_json(code):
|
||||
tree = ast.parse(code)
|
||||
return json.dumps(ast_to_dict(tree))
|
||||
|
||||
# 最小限のノードから実装
|
||||
def ast_to_dict(node):
|
||||
if isinstance(node, ast.FunctionDef):
|
||||
return {
|
||||
"type": "FunctionDef",
|
||||
"name": node.name,
|
||||
"args": [arg.arg for arg in node.args.args],
|
||||
"body": [ast_to_dict(stmt) for stmt in node.body]
|
||||
}
|
||||
# ... 他のノードタイプを順次追加
|
||||
```
|
||||
|
||||
### Step 2: Nyash AST生成(Rust側)
|
||||
```rust
|
||||
// JSON → Nyash AST
|
||||
fn convert_python_ast(json: &str) -> Result<ast::Program> {
|
||||
let py_ast: PythonAst = serde_json::from_str(json)?;
|
||||
match py_ast {
|
||||
PythonAst::FunctionDef { name, args, body } => {
|
||||
// Python def → Nyash function
|
||||
ast::BoxDef {
|
||||
name,
|
||||
methods: vec![ast::Method {
|
||||
name: name.clone(),
|
||||
params: args,
|
||||
body: convert_statements(body),
|
||||
}],
|
||||
..
|
||||
}
|
||||
}
|
||||
// ... 他のケース
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 3: 段階的な実行
|
||||
1. 最初はCPython exec()でそのまま実行
|
||||
2. 変換可能な部分からMIR生成
|
||||
3. MIR化された部分はVM/JITで高速実行
|
||||
4. 未対応部分は自動的にCPythonフォールバック
|
||||
|
||||
## 📊 期待される成果
|
||||
|
||||
### Phase 1完了時点
|
||||
- 簡単な数値計算スクリプトが2-5倍高速化
|
||||
- 基本的なループが最適化される
|
||||
- Nyashの既存Box(FileBox等)がPythonから使える
|
||||
|
||||
### Phase 2完了時点
|
||||
- Pythonのリスト/辞書操作が高速化
|
||||
- NyashとPythonのデータ構造が相互運用可能
|
||||
- 特殊メソッドによる自然な統合
|
||||
|
||||
### Phase 3完了時点
|
||||
- Pythonの生産的な機能がNyashで高速実行
|
||||
- 既存Pythonコードの大部分が動作
|
||||
- デコレータやジェネレータも最適化
|
||||
|
||||
## 🎯 最初の一歩(今すぐ開始)
|
||||
|
||||
1. pyo3でPythonParserBoxの骨組み作成
|
||||
2. 最小限のparse_to_json実装(def + return)
|
||||
3. 単純な関数のAST変換テスト
|
||||
4. "Hello from Python in Nyash"を表示
|
||||
|
||||
```python
|
||||
# 最初のテストケース
|
||||
def hello():
|
||||
return "Hello from Python in Nyash"
|
||||
|
||||
# これがNyashで動けば成功!
|
||||
```
|
||||
|
||||
## 📊 成功の測定基準(エキスパート推奨)
|
||||
|
||||
### 定量的指標
|
||||
| 指標 | 目標 | 測定方法 |
|
||||
|------|-------|----------|
|
||||
| カバレッジ率 | 70%以上 | コンパイル済み vs フォールバック関数の比率 |
|
||||
| 性能向上 | 2-10倍 | 純Pythonループのベンチマーク |
|
||||
| バグ発見数 | 10+件/Phase | Differential Testingで発見されたNyashバグ |
|
||||
| エコシステム | 1以上 | 動作する有名Pythonライブラリ |
|
||||
|
||||
### マイルストーン
|
||||
- Phase 1: "Hello from Python in Nyash"が動作
|
||||
- Phase 2: scikit-learnの基本アルゴリズムが動作
|
||||
- Phase 3: FlaskのHello Worldが動作
|
||||
- Phase 4: PyPIトップ100の30%が基本動作
|
||||
|
||||
## 🔧 GIL管理の黄金律
|
||||
|
||||
```rust
|
||||
// GILは最小限に!
|
||||
let json_ast = Python::with_gil(|py| {
|
||||
// Python側でJSON生成(高速)
|
||||
py_helper.parse_to_json(py, code)
|
||||
})?;
|
||||
|
||||
// GIL外でRust処理(並列可能)
|
||||
let nyash_ast = py.allow_threads(|| {
|
||||
convert_json_to_nyash(json_ast)
|
||||
});
|
||||
```
|
||||
|
||||
## 🔍 JSON IR設計(Codex先生推奨)
|
||||
|
||||
```json
|
||||
{
|
||||
"node_type": "FunctionDef",
|
||||
"py_version": "3.11",
|
||||
"ast_format": "v2",
|
||||
"support_level": "full", // "partial", "fallback"
|
||||
"lineno": 1,
|
||||
"col_offset": 0,
|
||||
"end_lineno": 3,
|
||||
"end_col_offset": 15,
|
||||
"name": "hello",
|
||||
"args": {...},
|
||||
"body": [...]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
作成日: 2025-08-27
|
||||
ChatGPT5のサーフェスマップ + Gemini/Codex先生のエキスパートフィードバックを統合
|
||||
@ -0,0 +1,70 @@
|
||||
# Phase 10.1e - Python → Nyashトランスパイラー
|
||||
|
||||
## 🎯 このフェーズの目的
|
||||
Python ASTをNyashソースコードとして出力する機能を実装する。
|
||||
|
||||
## 📁 実装ドキュメント
|
||||
- **`python_to_nyash_transpiler.txt`** - トランスパイラー設計
|
||||
|
||||
## 🔧 実装機能
|
||||
|
||||
### 1. AST → Nyashソース生成
|
||||
```rust
|
||||
impl PythonParserBox {
|
||||
pub fn to_nyash_source(&self, python_code: &str) -> Result<String, String> {
|
||||
// Python → JSON AST → Nyash AST → Nyashソース
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 変換例
|
||||
```python
|
||||
# Python入力
|
||||
def add(x, y):
|
||||
return x + y
|
||||
|
||||
result = add(10, 5)
|
||||
```
|
||||
|
||||
```nyash
|
||||
# Nyash出力
|
||||
function add(x, y) {
|
||||
return x + y
|
||||
}
|
||||
|
||||
local result
|
||||
result = add(10, 5)
|
||||
```
|
||||
|
||||
### 3. 出力フォーマッター
|
||||
- インデント管理
|
||||
- 括弧の追加(Nyashは明示的)
|
||||
- コメント保持(可能な範囲で)
|
||||
|
||||
## 🛠️ コマンドラインツール
|
||||
```bash
|
||||
# 基本変換
|
||||
nyash-transpile input.py -o output.nyash
|
||||
|
||||
# 変換統計付き
|
||||
nyash-transpile --stats complex.py
|
||||
# Output: Converted 15/17 functions (88%)
|
||||
|
||||
# 部分変換(サポート関数のみ)
|
||||
nyash-transpile --partial script.py
|
||||
```
|
||||
|
||||
## ✅ 完了条件
|
||||
- [ ] `to_nyash_source()` メソッドが動作する
|
||||
- [ ] 基本的なPythonコードが正しいNyashに変換される
|
||||
- [ ] インデントが正しく管理される
|
||||
- [ ] 変換統計が表示される
|
||||
- [ ] ファイル出力ができる
|
||||
|
||||
## 🌟 期待される利用シーン
|
||||
1. **学習ツール** - PythonユーザーがNyash構文を学ぶ
|
||||
2. **段階的移行** - 既存Pythonコードの移行
|
||||
3. **性能最適化** - ホットパスをNyashネイティブに
|
||||
|
||||
## ⏭️ 次のフェーズ
|
||||
→ Phase 10.1f (テストとベンチマーク)
|
||||
@ -0,0 +1,225 @@
|
||||
# Python → Nyashトランスパイラー機能
|
||||
~PythonParserBoxの応用による自動変換~
|
||||
|
||||
## 🎯 概要
|
||||
|
||||
PythonParserBoxでPython AST → Nyash ASTの変換ができるなら、それを**Nyashソースコードとして出力**できる!
|
||||
|
||||
## 🚀 実現可能な機能
|
||||
|
||||
### 1. Python → Nyashファイル変換
|
||||
```python
|
||||
# input.py
|
||||
def calculate(x, y):
|
||||
result = x * 2 + y
|
||||
return result
|
||||
|
||||
for i in range(10):
|
||||
print(calculate(i, 5))
|
||||
```
|
||||
|
||||
↓ 変換
|
||||
|
||||
```nyash
|
||||
# output.nyash
|
||||
function calculate(x, y) {
|
||||
local result
|
||||
result = x * 2 + y
|
||||
return result
|
||||
}
|
||||
|
||||
local i
|
||||
for i in range(0, 10) {
|
||||
print(calculate(i, 5))
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 実装方法
|
||||
|
||||
```rust
|
||||
impl PythonParserBox {
|
||||
// Python → Nyashファイル出力
|
||||
pub fn transpile_to_file(&self, python_code: &str, output_path: &str) -> Result<(), String> {
|
||||
// 1. Python → JSON AST
|
||||
let json_ast = self.parse_to_json(python_code)?;
|
||||
|
||||
// 2. JSON AST → Nyash AST
|
||||
let nyash_ast = self.json_to_nyash_ast(&json_ast)?;
|
||||
|
||||
// 3. Nyash AST → Nyashソースコード
|
||||
let nyash_code = self.ast_to_nyash_source(&nyash_ast)?;
|
||||
|
||||
// 4. ファイルに出力
|
||||
std::fs::write(output_path, nyash_code)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// AST → Nyashソースコード生成
|
||||
fn ast_to_nyash_source(&self, ast: &NyashAst) -> Result<String, String> {
|
||||
let mut output = String::new();
|
||||
let formatter = NyashFormatter::new();
|
||||
|
||||
for item in &ast.items {
|
||||
formatter.format_item(item, &mut output)?;
|
||||
}
|
||||
|
||||
Ok(output)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 📋 使用例
|
||||
|
||||
### コマンドライン版
|
||||
```bash
|
||||
# PythonファイルをNyashに変換
|
||||
nyash-transpile input.py -o output.nyash
|
||||
|
||||
# 標準出力に出力
|
||||
nyash-transpile script.py
|
||||
|
||||
# 部分変換(サポートされる構文のみ)
|
||||
nyash-transpile --partial complex_script.py
|
||||
```
|
||||
|
||||
### Nyashスクリプト内での使用
|
||||
```nyash
|
||||
local transpiler = new PythonParserBox()
|
||||
|
||||
// Pythonコードを読み込み
|
||||
local python_code = FileBox.read("algorithm.py")
|
||||
|
||||
// Nyashに変換
|
||||
local nyash_code = transpiler.to_nyash_source(python_code)
|
||||
|
||||
// ファイルに保存
|
||||
FileBox.write("algorithm.nyash", nyash_code)
|
||||
|
||||
// または直接実行
|
||||
eval(nyash_code)
|
||||
```
|
||||
|
||||
## 🎨 変換マッピング例
|
||||
|
||||
### 基本構文
|
||||
| Python | Nyash |
|
||||
|--------|-------|
|
||||
| `def func():` | `function func() {` |
|
||||
| `if x > 0:` | `if (x > 0) {` |
|
||||
| `for i in range(10):` | `for i in range(0, 10) {` |
|
||||
| `while x < 10:` | `while (x < 10) {` |
|
||||
| `x = 5` | `local x; x = 5` または `x = 5`(スコープによる)|
|
||||
|
||||
### データ型
|
||||
| Python | Nyash |
|
||||
|--------|-------|
|
||||
| `x = 42` | `x = 42` |
|
||||
| `s = "hello"` | `s = "hello"` |
|
||||
| `lst = [1, 2, 3]` | `lst = new ArrayBox([1, 2, 3])` |
|
||||
| `d = {"a": 1}` | `d = new MapBox(); d.set("a", 1)` |
|
||||
|
||||
### 特殊なケース
|
||||
```python
|
||||
# Pythonのfor/else
|
||||
for i in items:
|
||||
if condition:
|
||||
break
|
||||
else:
|
||||
print("No break")
|
||||
```
|
||||
|
||||
```nyash
|
||||
# Nyashでの実装(フラグを使用)
|
||||
local broke = false
|
||||
for i in items {
|
||||
if (condition) {
|
||||
broke = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if (not broke) {
|
||||
print("No break")
|
||||
}
|
||||
```
|
||||
|
||||
## 🌟 利点
|
||||
|
||||
### 1. 段階的移行支援
|
||||
- 既存のPythonプロジェクトを段階的にNyashに移行
|
||||
- 変換されたコードを手動で最適化可能
|
||||
|
||||
### 2. 学習ツールとして
|
||||
- PythonユーザーがNyash構文を学ぶ
|
||||
- 両言語の違いを理解
|
||||
|
||||
### 3. コード生成
|
||||
- Pythonで書いたアルゴリズムをNyashネイティブコードに
|
||||
- より高速な実行のための前処理
|
||||
|
||||
### 4. 逆方向変換の可能性
|
||||
- Nyash → Pythonも将来的に可能
|
||||
- 真のバイリンガル環境
|
||||
|
||||
## ⚠️ 制限事項と課題
|
||||
|
||||
### 1. 完全な互換性は不可能
|
||||
- Pythonの動的機能すべては変換できない
|
||||
- 一部の構文は手動調整が必要
|
||||
|
||||
### 2. 意味論の違い
|
||||
```python
|
||||
# Pythonのデフォルト引数(定義時評価)
|
||||
def f(x, lst=[]):
|
||||
lst.append(x)
|
||||
return lst
|
||||
```
|
||||
|
||||
```nyash
|
||||
// Nyashでは毎回新しいリスト(異なる挙動)
|
||||
function f(x, lst) {
|
||||
if (lst == null) {
|
||||
lst = new ArrayBox()
|
||||
}
|
||||
lst.push(x)
|
||||
return lst
|
||||
}
|
||||
```
|
||||
|
||||
### 3. サポートレベルの明示
|
||||
```nyash
|
||||
// 生成されたファイルのヘッダー
|
||||
// Generated from Python by Nyash Transpiler v1.0
|
||||
// Original file: script.py
|
||||
// Conversion rate: 85% (15/17 functions transpiled)
|
||||
// Manual review recommended for: async_func, generator_func
|
||||
```
|
||||
|
||||
## 📊 実装フェーズ
|
||||
|
||||
### Phase 1.5: 基本トランスパイラ(Phase 1と並行)
|
||||
- [ ] NyashFormatter実装(AST → ソースコード)
|
||||
- [ ] 基本構文の出力(def, if, for, while)
|
||||
- [ ] インデント管理
|
||||
- [ ] コメント保持(可能な範囲で)
|
||||
|
||||
### Phase 2.5: 高度な変換
|
||||
- [ ] クラス → Box変換
|
||||
- [ ] 特殊メソッド → Nyashメソッド
|
||||
- [ ] import文の処理
|
||||
|
||||
### Phase 3.5: ツール化
|
||||
- [ ] コマンドラインツール
|
||||
- [ ] VSCode拡張機能
|
||||
- [ ] オンライン変換ツール
|
||||
|
||||
## 🎉 期待される効果
|
||||
|
||||
1. **Pythonエコシステムの資産をNyashネイティブ化**
|
||||
2. **パフォーマンスクリティカルな部分をNyash/MIR/JITで高速化**
|
||||
3. **両言語間のシームレスな相互運用**
|
||||
4. **Nyashの採用障壁を大幅に下げる**
|
||||
|
||||
---
|
||||
|
||||
これは**PythonParserBoxの価値をさらに高める**素晴らしい応用です!
|
||||
@ -0,0 +1,92 @@
|
||||
# Phase 10.1f - テストとベンチマーク
|
||||
|
||||
## 🎯 このフェーズの目的
|
||||
Differential Testingでバグを発見し、性能向上を検証する。
|
||||
|
||||
## 🧪 Differential Testing戦略
|
||||
|
||||
### 1. テストフレームワーク
|
||||
```rust
|
||||
pub fn differential_test(code: &str) -> TestResult {
|
||||
// CPythonで実行(オラクル)
|
||||
let python_result = capture_python_execution(code)?;
|
||||
|
||||
// Nyashで実行
|
||||
let nyash_result = execute_with_pythonparser(code)?;
|
||||
|
||||
// 結果比較
|
||||
compare_results(python_result, nyash_result)
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 比較項目
|
||||
- **標準出力** - print文の結果
|
||||
- **戻り値** - 関数の返す値
|
||||
- **例外** - エラーメッセージ(正規化後)
|
||||
- **副作用** - グローバル変数の変更等
|
||||
|
||||
### 3. テストコーパス
|
||||
```
|
||||
test_corpus/
|
||||
├── basic/ # 基本構文テスト
|
||||
├── stdlib/ # 標準ライブラリから抜粋
|
||||
├── pypi_top100/ # 人気ライブラリから抜粋
|
||||
└── edge_cases/ # エッジケース集
|
||||
```
|
||||
|
||||
## 📊 ベンチマーク
|
||||
|
||||
### 1. 性能測定対象
|
||||
```python
|
||||
# 数値計算ベンチマーク
|
||||
def mandelbrot(max_iter=100):
|
||||
# フラクタル計算
|
||||
pass
|
||||
|
||||
# ループベンチマーク
|
||||
def sum_of_primes(n):
|
||||
# 素数の和
|
||||
pass
|
||||
|
||||
# 再帰ベンチマーク
|
||||
def ackermann(m, n):
|
||||
# アッカーマン関数
|
||||
pass
|
||||
```
|
||||
|
||||
### 2. 測定項目
|
||||
- **実行時間** - CPython vs Nyash
|
||||
- **メモリ使用量** - 最大/平均
|
||||
- **コンパイル時間** - AST変換時間
|
||||
- **フォールバック率** - 関数別統計
|
||||
|
||||
## 🐛 バグ発見と報告
|
||||
|
||||
### 発見されたバグの例
|
||||
```
|
||||
[BUG-001] for/else semantics mismatch
|
||||
Python: else executed when no break
|
||||
Nyash: else never executed
|
||||
Fixed in: commit abc123
|
||||
|
||||
[BUG-002] Division operator difference
|
||||
Python: 5/2 = 2.5 (float)
|
||||
Nyash: 5/2 = 2 (integer)
|
||||
Fixed in: commit def456
|
||||
```
|
||||
|
||||
## ✅ 完了条件
|
||||
- [ ] Differential Testingフレームワークが動作する
|
||||
- [ ] 基本的なテストコーパスが準備されている
|
||||
- [ ] 10個以上のバグを発見・修正
|
||||
- [ ] ベンチマークで2倍以上の高速化を確認
|
||||
- [ ] CI/CDパイプラインに統合されている
|
||||
|
||||
## 📈 成功の測定
|
||||
- **カバレッジ率**: 70%以上の関数がコンパイル
|
||||
- **性能向上**: 純Pythonループで2-10倍
|
||||
- **バグ発見数**: Phase毎に10件以上
|
||||
- **テスト成功率**: 95%以上
|
||||
|
||||
## ⏭️ 次のフェーズ
|
||||
→ Phase 10.1g (ドキュメント作成)
|
||||
@ -0,0 +1,100 @@
|
||||
# Phase 10.1g - ドキュメントとリリース準備
|
||||
|
||||
## 🎯 このフェーズの目的
|
||||
PythonParserBoxの使い方を文書化し、コミュニティに公開する準備をする。
|
||||
|
||||
## 📚 作成するドキュメント
|
||||
|
||||
### 1. ユーザーガイド
|
||||
- **Getting Started** - 最初の一歩
|
||||
- **Python互換性ガイド** - サポートされる構文
|
||||
- **トランスパイラー使用法** - Python→Nyash変換
|
||||
- **トラブルシューティング** - よくある問題と解決法
|
||||
|
||||
### 2. API リファレンス
|
||||
```nyash
|
||||
// PythonParserBox API
|
||||
box PythonParserBox {
|
||||
// Python code → JSON AST
|
||||
parse_to_json(code: String) -> String
|
||||
|
||||
// JSON AST → Nyash AST
|
||||
json_to_nyash_ast(json: String) -> AstBox
|
||||
|
||||
// Python code → Nyash source
|
||||
to_nyash_source(code: String) -> String
|
||||
|
||||
// 直接実行(関数単位フォールバック)
|
||||
run(code: String) -> Box
|
||||
|
||||
// 変換統計
|
||||
get_conversion_stats() -> MapBox
|
||||
}
|
||||
```
|
||||
|
||||
### 3. 移行ガイド
|
||||
- **段階的移行戦略** - Pythonプロジェクトの移行手順
|
||||
- **パフォーマンスチューニング** - ホットパスの最適化
|
||||
- **ベストプラクティス** - 推奨される使い方
|
||||
|
||||
### 4. 内部設計ドキュメント
|
||||
- **アーキテクチャ** - 全体設計
|
||||
- **関数単位フォールバック** - 実装詳細
|
||||
- **GIL管理** - pyo3との統合
|
||||
- **テレメトリー** - 統計収集の仕組み
|
||||
|
||||
## 🎬 デモとチュートリアル
|
||||
|
||||
### 1. 動画チュートリアル
|
||||
- 5分で分かるPythonParserBox
|
||||
- Python→Nyash移行実演
|
||||
- パフォーマンス比較デモ
|
||||
|
||||
### 2. サンプルプロジェクト
|
||||
```
|
||||
examples/
|
||||
├── hello_python/ # 最小限の例
|
||||
├── data_analysis/ # データ分析の移行例
|
||||
├── web_api/ # WebAPIの移行例
|
||||
└── benchmarks/ # ベンチマーク比較
|
||||
```
|
||||
|
||||
## 📣 リリース準備
|
||||
|
||||
### 1. リリースノート作成
|
||||
```markdown
|
||||
# PythonParserBox v1.0 リリース!
|
||||
|
||||
## 🎉 新機能
|
||||
- Python AST → Nyash AST変換
|
||||
- 関数単位フォールバック
|
||||
- Python→Nyashトランスパイラー
|
||||
- Differential Testing
|
||||
|
||||
## 📊 パフォーマンス
|
||||
- 純Pythonループ: 2-10倍高速化
|
||||
- 数値計算: 5倍以上の改善
|
||||
- メモリ効率: 30%削減
|
||||
|
||||
## 🐛 発見されたバグ
|
||||
- Nyashパーサー: 15件修正
|
||||
- セマンティクス: 8件修正
|
||||
```
|
||||
|
||||
### 2. ブログ記事
|
||||
- 「なぜPythonParserBoxを作ったのか」
|
||||
- 「Differential Testingの威力」
|
||||
- 「Everything is Boxの新たな展開」
|
||||
|
||||
## ✅ 完了条件
|
||||
- [ ] ユーザーガイドが完成している
|
||||
- [ ] APIリファレンスが完成している
|
||||
- [ ] サンプルプロジェクトが動作する
|
||||
- [ ] リリースノートが準備されている
|
||||
- [ ] CI/CDでの自動テストが通る
|
||||
|
||||
## 🎯 Phase 10.1の完了!
|
||||
これでPythonParserBoxの最初のリリースが完成!
|
||||
|
||||
## ⏭️ 次の展開
|
||||
→ Phase 10.2 (Phase 2機能の実装) または Phase 10.x (他言語対応)
|
||||
80
docs/development/roadmap/phases/phase-10.5/README.md
Normal file
80
docs/development/roadmap/phases/phase-10.5/README.md
Normal file
@ -0,0 +1,80 @@
|
||||
# Phase 10.5 - PythonParserBox実装
|
||||
*(旧Phase 10.1 - プラグインBox統一化の発見により番号変更)*
|
||||
|
||||
見ただけで実装手順が分かる!順番通りに進めてください。
|
||||
|
||||
## 📂 サブフェーズ構成(順番に実行)
|
||||
|
||||
### 📋 Phase 10.1a - 計画と設計
|
||||
最初にここから!全体像を理解する。
|
||||
- 統合実装計画を読む
|
||||
- エキスパート評価を確認
|
||||
- 5つの核心戦略を把握
|
||||
|
||||
### ⚙️ Phase 10.1b - 環境設定
|
||||
開発環境を整える。
|
||||
- Python 3.11.9をインストール
|
||||
- Cargo.tomlに依存関係追加
|
||||
- ディレクトリ構造準備
|
||||
|
||||
### 🔧 Phase 10.1c - パーサー統合
|
||||
CPythonパーサーをNyashに統合。
|
||||
- PythonParserBox実装
|
||||
- GIL管理の実装
|
||||
- JSON中間表現への変換
|
||||
|
||||
### 💻 Phase 10.1d - Core実装
|
||||
基本的なPython構文の変換。
|
||||
- Phase 1機能(def/if/for/while)
|
||||
- 意味論の正確な実装
|
||||
- 70%コンパイル率達成
|
||||
|
||||
### 🔄 Phase 10.1e - トランスパイラー
|
||||
Python→Nyashソース変換。
|
||||
- AST→Nyashソース生成
|
||||
- フォーマッター実装
|
||||
- コマンドラインツール
|
||||
|
||||
### 🧪 Phase 10.1f - テスト
|
||||
Differential Testingでバグ発見。
|
||||
- CPython vs Nyash比較
|
||||
- ベンチマーク実行
|
||||
- バグ修正とCI統合
|
||||
|
||||
### 📚 Phase 10.1g - ドキュメント
|
||||
使い方を文書化してリリース。
|
||||
- ユーザーガイド作成
|
||||
- APIリファレンス
|
||||
- サンプルプロジェクト
|
||||
|
||||
## 🎯 各フェーズの目安時間
|
||||
|
||||
| フェーズ | 内容 | 目安時間 |
|
||||
|---------|------|----------|
|
||||
| 10.1a | 計画理解 | 2-3時間 |
|
||||
| 10.1b | 環境設定 | 1-2時間 |
|
||||
| 10.1c | パーサー統合 | 3-5日 |
|
||||
| 10.1d | Core実装 | 1-2週間 |
|
||||
| 10.1e | トランスパイラー | 3-5日 |
|
||||
| 10.1f | テスト | 1週間 |
|
||||
| 10.1g | ドキュメント | 3-5日 |
|
||||
|
||||
**合計**: 約1ヶ月
|
||||
|
||||
## 🌟 最終目標
|
||||
|
||||
- **70%以上**の関数がコンパイル可能
|
||||
- **2-10倍**の性能向上
|
||||
- **10件以上**のNyashバグ発見
|
||||
- **実用的な**Python→Nyash移行ツール
|
||||
|
||||
## 💡 Tips
|
||||
|
||||
- 各フェーズのREADME.mdを必ず読む
|
||||
- 完了条件をチェックしながら進める
|
||||
- テレメトリーで進捗を確認
|
||||
- 困ったらarchive/の資料も参照
|
||||
|
||||
---
|
||||
|
||||
**さあ、Phase 10.1a から始めましょう!**
|
||||
@ -0,0 +1,239 @@
|
||||
# Phase 10.1 - Python統合計画(ChatGPT5高速開発版)
|
||||
最終更新: 2025-08-27
|
||||
|
||||
## 🚀 概要:2週間での爆速実装
|
||||
|
||||
ChatGPT5の最小Box設計により、元の1ヶ月計画を**2週間**に圧縮。Nyash既存アーキテクチャ(MirBuilder 100%実装済み、HandleRegistry 80%実装済み)を最大活用。
|
||||
|
||||
## 📦 ChatGPT5の6つの必須Box(最小実装)
|
||||
|
||||
### 1. **PythonParserBox** - CPython AST取得(3日)
|
||||
```rust
|
||||
// 既存: pyo3統合済み
|
||||
// 追加: JSON出力とバージョン固定
|
||||
pub struct PythonParserBox {
|
||||
base: BoxBase,
|
||||
py_helper: Arc<Mutex<PyHelper>>,
|
||||
version: String, // "3.11"固定
|
||||
}
|
||||
|
||||
// メソッド(最小限)
|
||||
- parse_to_json(src: String) -> String // ast.parse() → JSON
|
||||
- get_version() -> String // "3.11"
|
||||
```
|
||||
|
||||
### 2. **Py2NyASTBox** - AST変換(3日)
|
||||
```rust
|
||||
// 新規実装
|
||||
pub struct Py2NyASTBox {
|
||||
base: BoxBase,
|
||||
normalizer: AstNormalizer,
|
||||
}
|
||||
|
||||
// メソッド(制御フロー正規化)
|
||||
- convert(json: String) -> NyashAst
|
||||
- normalize_for_else(ast: &mut PyAst) // for/else → if分岐
|
||||
- normalize_comprehensions(ast: &mut PyAst)
|
||||
```
|
||||
|
||||
### 3. **MirBuilderBox** - MIR生成(0日 - 既存活用)
|
||||
```rust
|
||||
// 既存実装100%活用
|
||||
// 追加: Python由来フラグのみ
|
||||
pub struct MirBuilderBox {
|
||||
// 既存フィールド
|
||||
is_python_origin: bool, // 追加
|
||||
}
|
||||
```
|
||||
|
||||
### 4. **BoundaryBox** - 型変換(2日)
|
||||
```rust
|
||||
// Python版のHandleRegistry相当
|
||||
pub struct BoundaryBox {
|
||||
base: BoxBase,
|
||||
handle_registry: Arc<Mutex<HandleRegistry>>, // 既存80%活用
|
||||
}
|
||||
|
||||
// メソッド
|
||||
- py_to_jit(py_val: PyValBox) -> JitValue
|
||||
- jit_to_py(jit_val: JitValue) -> PyValBox
|
||||
- register_handle(obj: Arc<dyn NyashBox>) -> u64
|
||||
```
|
||||
|
||||
### 5. **PyRuntimeBox** - 実行制御(2日)
|
||||
```rust
|
||||
pub struct PyRuntimeBox {
|
||||
base: BoxBase,
|
||||
fallback_stats: FallbackStats,
|
||||
}
|
||||
|
||||
// メソッド(関数単位フォールバック)
|
||||
- execute_function(name: &str, args: Vec<JitValue>) -> JitValue
|
||||
- should_fallback(func_ast: &PyAst) -> bool // Phase1機能判定
|
||||
- fallback_to_cpython(code: &str) -> PyObject
|
||||
```
|
||||
|
||||
### 6. **ObservabilityBox** - 統計収集(1日)
|
||||
```rust
|
||||
// 既存のJIT統計システム(70%実装済み)を拡張
|
||||
pub struct ObservabilityBox {
|
||||
base: BoxBase,
|
||||
stats_collector: StatsCollector,
|
||||
}
|
||||
|
||||
// JSONLフォーマット出力
|
||||
- log_attempt(module: &str, func: &str, compiled: bool, reason: Option<&str>)
|
||||
- output_jsonl() -> String
|
||||
```
|
||||
|
||||
## 🗓️ 実装タイムライン(2週間)
|
||||
|
||||
### Week 1: 基盤実装(7日)
|
||||
- **Day 1-3**: PythonParserBox実装
|
||||
- pyo3統合(既存活用)
|
||||
- Python 3.11固定
|
||||
- JSON出力実装
|
||||
|
||||
- **Day 4-6**: Py2NyASTBox実装
|
||||
- 制御フロー正規化
|
||||
- for/else, while/else変換
|
||||
- Phase1機能のみサポート
|
||||
|
||||
- **Day 7**: ObservabilityBox実装
|
||||
- 既存JIT統計拡張
|
||||
- JSONLフォーマット
|
||||
|
||||
### Week 2: 統合と検証(7日)
|
||||
- **Day 8-9**: BoundaryBox実装
|
||||
- HandleRegistry活用
|
||||
- 型変換ルール確立
|
||||
|
||||
- **Day 10-11**: PyRuntimeBox実装
|
||||
- 関数単位フォールバック
|
||||
- CPython連携
|
||||
|
||||
- **Day 12-13**: 統合テスト
|
||||
- Differential Testing
|
||||
- ベンチマーク実行
|
||||
|
||||
- **Day 14**: ドキュメント・リリース
|
||||
- 使用例作成
|
||||
- パフォーマンス測定
|
||||
|
||||
## 📊 既存アーキテクチャとの整合性
|
||||
|
||||
### 活用率
|
||||
- **MirBuilderBox**: 100%(変更なし)
|
||||
- **HandleRegistry**: 80%(BoundaryBoxで再利用)
|
||||
- **JIT統計**: 70%(ObservabilityBoxで拡張)
|
||||
- **VM/JIT実行**: 100%(そのまま使用)
|
||||
|
||||
### 新規実装
|
||||
- **PythonParserBox**: 30%(pyo3部分は既存)
|
||||
- **Py2NyASTBox**: 100%新規
|
||||
- **PyRuntimeBox**: 100%新規
|
||||
|
||||
## 🎯 Phase 1でサポートする機能(Codex先生推奨)
|
||||
|
||||
### 必須実装
|
||||
1. **LEGB + locals/freevars** - スコーピング規則
|
||||
2. **デフォルト引数の評価タイミング** - 定義時評価
|
||||
3. **イテレータベースのfor文**
|
||||
4. **for/else + while/else**
|
||||
5. **Python真偽値判定**
|
||||
6. **短絡評価**
|
||||
|
||||
### サポートする文
|
||||
- def(関数定義)
|
||||
- if/elif/else
|
||||
- for(else節対応)
|
||||
- while(else節対応)
|
||||
- break/continue
|
||||
- return
|
||||
|
||||
### サポートする式
|
||||
- 算術演算子(+,-,*,/,//,%)
|
||||
- 比較演算子(==,!=,<,>,<=,>=)
|
||||
- 論理演算子(and,or,not)
|
||||
- 関数呼び出し
|
||||
- リテラル(数値/文字列/bool)
|
||||
|
||||
## 📈 成功指標(2週間後)
|
||||
|
||||
### 定量的
|
||||
- **関数コンパイル率**: 70%以上(Phase 1機能)
|
||||
- **実行速度**: 純Pythonループで2倍以上
|
||||
- **メモリ効率**: CPython比50%削減
|
||||
|
||||
### 定性的
|
||||
- **統計可視化**: JSONL形式で全実行を記録
|
||||
- **デバッグ容易性**: 関数単位でフォールバック理由明示
|
||||
- **将来拡張性**: Phase 2-4への明確な道筋
|
||||
|
||||
## 🔧 実装例(最終形)
|
||||
|
||||
```nyash
|
||||
// Nyashから使用
|
||||
local py = new PythonParserBox()
|
||||
local converter = new Py2NyASTBox()
|
||||
local builder = new MirBuilderBox()
|
||||
local runtime = new PyRuntimeBox()
|
||||
local stats = new ObservabilityBox()
|
||||
|
||||
// Pythonコードをコンパイル・実行
|
||||
local code = "def fib(n): return n if n <= 1 else fib(n-1) + fib(n-2)"
|
||||
local json_ast = py.parse_to_json(code)
|
||||
local ny_ast = converter.convert(json_ast)
|
||||
local mir = builder.build(ny_ast)
|
||||
|
||||
// 実行(自動的にJIT/VMで高速化)
|
||||
local result = runtime.execute_function("fib", [10])
|
||||
print(result) // 55
|
||||
|
||||
// 統計出力
|
||||
print(stats.output_jsonl())
|
||||
// {"mod":"test","func":"fib","attempt":1,"jitted":true,"native":true}
|
||||
```
|
||||
|
||||
## 🚨 重要な設計判断
|
||||
|
||||
### 1. 関数単位の境界
|
||||
- ファイル単位ではなく**関数単位**でコンパイル/フォールバック
|
||||
- 未対応機能を含む関数のみCPython実行
|
||||
|
||||
### 2. Python 3.11固定
|
||||
- AST安定性の確保
|
||||
- 将来のバージョンアップは別Phase
|
||||
|
||||
### 3. 箱境界の明確化
|
||||
- 各Boxは単一責任
|
||||
- 相互依存を最小化
|
||||
- テスト可能な粒度
|
||||
|
||||
### 4. 既存資産の最大活用
|
||||
- MirBuilder/VM/JITはそのまま使用
|
||||
- 新規実装は変換層のみ
|
||||
|
||||
## 🎉 期待される成果
|
||||
|
||||
### 即時的効果(2週間後)
|
||||
- Pythonコードの70%がNyashで高速実行
|
||||
- バグ検出力の飛躍的向上(Differential Testing)
|
||||
- 統計による最適化ポイントの可視化
|
||||
|
||||
### 長期的効果
|
||||
- Python→Nyash→Native の世界初パイプライン確立
|
||||
- Nyash言語の成熟度向上
|
||||
- エコシステムの爆発的拡大
|
||||
|
||||
## 📝 次のステップ
|
||||
|
||||
1. **Phase 10.7完了確認** - JIT統計JSONの安定化
|
||||
2. **PythonParserBox実装開始** - pyo3統合から着手
|
||||
3. **テストコーパス準備** - Python標準ライブラリから抜粋
|
||||
|
||||
---
|
||||
|
||||
**作成者**: Claude(Claude Code)
|
||||
**承認者**: ChatGPT5(予定)
|
||||
**開始予定**: Phase 10.7完了直後
|
||||
Reference in New Issue
Block a user