parser(match): add MVP type patterns (IntegerBox(x)/StringBox(s)) via AST If-chain; keep literal-only path using PeekExpr; add smoke app (apps/tests/match_type_pattern_basic.nyash); build + stage-2 smokes green

This commit is contained in:
Selfhosting Dev
2025-09-19 08:34:29 +09:00
parent f4e340da08
commit 9142476484
348 changed files with 2539 additions and 281 deletions

View File

@ -3,7 +3,7 @@
目的: 現行の Plugin-FirstPyRuntimeBox/PyObjectBox, Handle-First/TLVを維持しつつ、トランスパイル路線Python→Nyashを“All or Nothing”原則で段階導入。10.6の足場Thread-Safety/Scheduler上で、AOT配布体験に直結する最短ラインを構築する。
====================
A) 方針(判断)
A) 方針(判断)+ Property System革命統合2025-09-18追加
====================
- 二本立てを明確化:
1) 実行系(現行): PyRuntimeBox 経由VM=仕様、JIT=AOT生成のみ。配布/運用の実用ライン。
@ -65,3 +65,50 @@ G) 現行との接続
- 10.6の足場Thread-Safety/Schedulerは維持。トランスパイル系は単一スレッド/VM基準で十分。
- 10.5のAOT導線/nyrtシムはそのまま活用生成Nyashに対して適用
====================
H) Property System革命統合2025-09-18 ブレイクスルー)
====================
### 🌟 Python → Nyash Property マッピング革命
今日完成したProperty Systemstored/computed/once/birth_onceにより、Python transpilationが飛躍的に向上
**Pythonプロパティの完全対応**:
```python
# Python側
class PyClass:
def __init__(self):
self._value = 42
@property
def computed_prop(self):
return self._value * 2
@functools.cached_property
def expensive_prop(self):
return heavy_computation()
```
**自動生成Nyash革命的シンプル**:
```nyash
box PyClass {
_value: IntegerBox // stored: 通常フィールド
computed_prop: IntegerBox { me._value * 2 } // computed: @property
once expensive_prop: ResultBox { heavy_computation() } // once: @cached_property
birth() { me._value = 42 }
}
```
### 🎯 実装戦略更新
- **C2フェーズ拡張**: PythonCompilerBoxにProperty System生成機能追加
- **descriptor protocol**: Python property/method → Nyash property 4分類自動判定
- **poison-on-throw**: cached_property例外時の安全性保証
### 📊 成功指標追加
```
Property coverage: @property(100%), @cached_property(100%), descriptors(80%)
Performance boost: cached property 10-50x faster (LLVM最適化
Code generation: Python class → 50%短いNyashコード
```

View File

@ -0,0 +1,274 @@
# PythonCompilerBox Property System活用実装
## 🎯 概要
Property System革命stored/computed/once/birth_onceをPythonCompilerBoxで活用し、Python→Nyash transpilationを実現する技術実装設計。
## 🏗️ アーキテクチャ設計
### コアコンポーネント
```nyash
box PythonCompilerBox {
// Property System を活用したコンパイラ実装
classifier: PropertyClassifierBox
generator: NyashCodeGeneratorBox
validator: SemanticValidatorBox
// コンパイル結果のキャッシュonce使用
once compilation_cache: MapBox { new MapBox() }
// 動的に計算される統計情報computed使用
success_rate: FloatBox { me.get_success_statistics() }
total_files_processed: IntegerBox { me.compilation_cache.size() }
birth() {
me.classifier = new PropertyClassifierBox()
me.generator = new NyashCodeGeneratorBox()
me.validator = new SemanticValidatorBox()
}
}
```
## 🧠 PropertyClassifierBox実装
```nyash
box PropertyClassifierBox {
// 分類ルールのキャッシュonce
once classification_rules: RuleSetBox { load_classification_rules() }
// 統計情報computed
classified_count: IntegerBox { me.get_classification_stats().count }
accuracy_rate: FloatBox { me.get_classification_stats().accuracy }
classify_python_property(ast_node) {
// Python AST → Property type 分類
if me.has_decorator(ast_node, "@property") {
if me.is_simple_computation(ast_node) {
return "computed" // 単純計算 → computed
} else {
return "once" // 複雑処理 → キャッシュ推奨
}
}
if me.has_decorator(ast_node, "@functools.cached_property") {
return "once" // 明示的キャッシュ
}
if me.is_init_assignment(ast_node) {
return "stored" // 通常フィールド
}
if me.is_birth_once_candidate(ast_node) {
return "birth_once" // 初期化時のみ評価
}
return "unsupported" // Phase 2以降
}
// ヒューリスティック判定
is_simple_computation(node) {
// 副作用なし+計算量小 → computed適合性判定
return me.has_no_side_effects(node) and me.is_lightweight(node)
}
is_birth_once_candidate(node) {
// 初期化時のみ必要な重い処理を検出
return me.called_in_init_only(node) and me.is_expensive(node)
}
}
```
## 🏭 NyashCodeGeneratorBox実装
```nyash
box NyashCodeGeneratorBox {
// テンプレートエンジンonce
once property_templates: TemplateEngineBox {
load_property_templates()
}
// 生成コード統計computed
generated_lines: IntegerBox { me.count_generated_code_lines() }
compression_ratio: FloatBox { me.calculate_compression_ratio() }
generate_property_declaration(property_info) {
local template = me.property_templates.get(property_info.type)
// Property typeごとの生成
peek property_info.type {
"stored" => me.generate_stored_property(property_info),
"computed" => me.generate_computed_property(property_info),
"once" => me.generate_once_property(property_info),
"birth_once" => me.generate_birth_once_property(property_info),
else => throw UnsupportedPropertyError(property_info.type)
}
}
generate_computed_property(info) {
// computed property テンプレート
return info.name + ": " + info.type + " { " + info.expression + " }"
}
generate_once_property(info) {
// once property テンプレート(キャッシュ+例外安全)
local code = "once " + info.name + ": " + info.type + " { " + info.expression + " }"
if info.has_exception_risk {
code = code + " catch(ex) { poison(me." + info.name + ", ex); throw ex }"
}
return code
}
generate_birth_once_property(info) {
// birth_once property テンプレート
return "birth_once " + info.name + ": " + info.type + " { " + info.expression + " }"
}
}
```
## 🔍 SemanticValidatorBox実装
```nyash
box SemanticValidatorBox {
// 検証ルールonce
once validation_rules: ValidationRuleSetBox {
load_semantic_validation_rules()
}
// 検証結果統計computed
validation_success_rate: FloatBox { me.get_validation_stats().success_rate }
error_categories: ArrayBox { me.get_validation_stats().error_types }
validate_property_semantics(python_ast, nyash_code) {
local errors = new ArrayBox()
// 1. Property type一致性検証
me.validate_property_type_consistency(python_ast, nyash_code, errors)
// 2. 例外安全性検証
me.validate_exception_safety(python_ast, nyash_code, errors)
// 3. 性能特性検証
me.validate_performance_characteristics(python_ast, nyash_code, errors)
return ValidationResult.new(errors)
}
validate_property_type_consistency(python_ast, nyash_code, errors) {
// Pythonの@propertyとNyashのcomputedが対応しているかチェック
local python_properties = me.extract_python_properties(python_ast)
local nyash_properties = me.extract_nyash_properties(nyash_code)
loop(python_properties.iter()) property {
local expected_type = me.infer_nyash_property_type(property)
local actual_type = nyash_properties.get(property.name).type
if expected_type != actual_type {
errors.add(PropertyTypeMismatchError.new(property.name, expected_type, actual_type))
}
}
}
}
```
## 🎯 統合ワークフロー
```nyash
box PythonTranspilationWorkflow {
compiler: PythonCompilerBox
birth() {
me.compiler = new PythonCompilerBox()
}
transpile_python_file(file_path) {
// 1. Pythonファイル解析
local python_ast = me.parse_python_file(file_path)
// 2. Property分類
local classified_properties = me.compiler.classifier.classify_all_properties(python_ast)
// 3. Nyashコード生成
local nyash_code = me.compiler.generator.generate_nyash_code(classified_properties)
// 4. セマンティック検証
local validation_result = me.compiler.validator.validate_property_semantics(python_ast, nyash_code)
if validation_result.has_errors() {
throw TranspilationError.new(validation_result.errors)
}
// 5. コンパイル結果キャッシュonce活用
me.compiler.compilation_cache.set(file_path, nyash_code)
return nyash_code
}
}
```
## 🧪 テスト実装例
```nyash
box PropertySystemTranspilationTest {
test_computed_property_generation() {
local python_code = '''
class TestClass:
@property
def doubled_value(self):
return self.value * 2
'''
local compiler = new PythonCompilerBox()
local result = compiler.transpile(python_code)
assert result.contains("doubled_value: IntegerBox { me.value * 2 }")
}
test_once_property_generation() {
local python_code = '''
class TestClass:
@functools.cached_property
def expensive_calc(self):
return heavy_computation()
'''
local compiler = new PythonCompilerBox()
local result = compiler.transpile(python_code)
assert result.contains("once expensive_calc: ResultBox { heavy_computation() }")
}
test_poison_on_throw_integration() {
local python_code = '''
class TestClass:
@functools.cached_property
def risky_operation(self):
if random.random() < 0.1:
raise ValueError("Failed")
return success_result()
'''
local compiler = new PythonCompilerBox()
local result = compiler.transpile(python_code)
assert result.contains("catch(ex) { poison(me.risky_operation, ex); throw ex }")
}
}
```
## 📊 期待される効果
### 1. 実装効率の向上
- Property System活用により、コンパイラ自体の実装がクリーン
- once活用でコンパイルキャッシュ、computed活用で統計計算
### 2. 生成コードの高品質化
- Python property → Nyash property の自然な1:1マッピング
- poison-on-throw統合による例外安全性
### 3. 保守性の向上
- Box化されたコンポーネント設計
- 明確な責任分離(分類・生成・検証)
この設計により、Property System革命を最大限活用したPython transpilation実装が実現できます

View File

@ -0,0 +1,194 @@
# Python Descriptor Protocol → Nyash Property System マッピング
## 🎯 概要
2025-09-18のProperty System革命により、Python transpilationが飛躍的に向上。Pythonのdescriptor protocolを完全にNyashのProperty Systemstored/computed/once/birth_onceにマッピングする設計。
## 🧬 Pythonプロパティ分類とNyashマッピング
### 1. 通常フィールド → stored
```python
class PyClass:
def __init__(self):
self.name = "example" # 通常の属性
```
```nyash
box PyClass {
name: StringBox // stored: 通常のフィールドストレージ
birth() {
me.name = "example"
}
}
```
### 2. @property → computed
```python
class PyClass:
@property
def full_name(self):
return f"{self.first} {self.last}"
```
```nyash
box PyClass {
first: StringBox
last: StringBox
full_name: StringBox { me.first + " " + me.last } // computed: 毎回計算
}
```
### 3. @functools.cached_property → once
```python
import functools
class PyClass:
@functools.cached_property
def expensive_data(self):
return expensive_computation()
```
```nyash
box PyClass {
once expensive_data: DataBox { expensive_computation() } // once: 遅延評価+キャッシュ
}
```
### 4. カスタムdescriptor → 判定ロジック
```python
class CustomDescriptor:
def __get__(self, obj, objtype=None):
# カスタムロジック
pass
def __set__(self, obj, value):
# セットロジック
pass
class PyClass:
custom_prop = CustomDescriptor()
```
**判定ロジックPythonCompilerBox内**:
```nyash
box DescriptorAnalyzer {
analyze_descriptor(descriptor_ast) {
if descriptor_ast.has_get_only() {
if descriptor_ast.is_pure_computation() {
return "computed" // 副作用なし計算
} else {
return "once" // 副作用あり=キャッシュ推奨
}
}
if descriptor_ast.has_get_and_set() {
return "stored" // getterとsetterあり通常フィールド
}
return "unsupported" // 複雑すぎ→Phase 2以降
}
}
```
## 🎯 自動判定アルゴリズム
### Phase 1: 基本パターン認識
```python
def classify_python_property(ast_node):
# 1. デコレータ解析
if has_decorator(ast_node, "@property"):
if is_simple_computation(ast_node.body):
return "computed"
else:
return "once" # 複雑→キャッシュ推奨
# 2. cached_property検出
if has_decorator(ast_node, "@functools.cached_property"):
return "once"
# 3. 通常の__init__内代入
if is_init_assignment(ast_node):
return "stored"
# 4. descriptor検出Phase 2以降
if has_custom_descriptor(ast_node):
return analyze_descriptor_complexity(ast_node)
```
### Phase 2: 高度な判定(将来)
- **副作用解析**: I/O、外部状態変更の検出
- **コスト解析**: 計算量推定による once vs computed 判定
- **依存解析**: 他のプロパティとの依存関係
## 🌟 poison-on-throw統合
### Python例外 → Nyash例外処理
```python
class PyClass:
@functools.cached_property
def risky_operation(self):
if random.random() < 0.1:
raise ValueError("Failed!")
return expensive_result()
```
```nyash
box PyClass {
once risky_operation: ResultBox {
if random_float() < 0.1 {
throw ValueError("Failed!")
}
return expensive_result()
} catch(ex) {
poison(me.risky_operation, ex) // poison-on-throw適用
throw ex
}
}
```
## 📊 実装フェーズ
### Phase 10.7a: 基本認識1週間
- @property, @cached_property, 通常フィールドの自動分類
- 単純なcomputedプロパティ生成
### Phase 10.7b: 拡張判定2週間
- カスタムdescriptor解析
- 副作用検出ロジック
- poison-on-throw統合
### Phase 10.7c: 最適化1週間
- 依存解析による once vs computed 最適選択
- LLVM最適化との連携
## 🧪 テストケース
### 成功パターン
```python
# シンプルcomputed
@property
def area(self): return self.width * self.height # → computed
# キャッシュ必要
@functools.cached_property
def heavy_calc(self): return sum(range(1000000)) # → once
# 通常フィールド
def __init__(self): self.name = "test" # → stored
```
### 限界ケースPhase 2以降
```python
# 複雑なdescriptor未対応
class ComplexDescriptor:
def __get__(self, obj, objtype=None):
# 複雑な条件分岐、外部API呼び出し等
pass
```
## 🚀 期待される効果
1. **開発体験**: PythonプロパティがNyashで自然に表現
2. **性能向上**: LLVMによるproperty最適化10-50x高速化
3. **型安全性**: NyashのBox型システムによる実行時安全性
4. **保守性**: 生成されたNyashコードの可読性・編集可能性
このマッピング設計により、PythonからNyashへの自然で高性能なtranspilationが実現できます

View File

@ -0,0 +1,152 @@
# Phase 10.7 × Property System 革命 - 今すぐ始めるクイックスタート
## 🎯 Property System革命により実現可能になったPython→Nyash実行
2025-09-18のProperty System革命により、Python transpilationが飛躍的に実現可能に
## 🚀 最短実装ルート3週間で実用レベル
### Week 1: 基本プロパティ認識
```bash
# プラグイン作成
cd plugins/
cargo new nyash-python-parser-plugin --lib
# 最小依存関係
echo '[dependencies]
pyo3 = { version = "0.22", features = ["auto-initialize"] }
nyash-plugin-sdk = { path = "../../crates/plugin-sdk" }' >> Cargo.toml
```
### Week 2-3: Property System活用コンパイラ
```rust
// src/lib.rs - 最小実装例
use pyo3::prelude::*;
#[pyclass]
pub struct PythonCompilerBox {
property_classifier: PropertyClassifier,
}
#[pymethods]
impl PythonCompilerBox {
#[new]
pub fn new() -> Self {
Self {
property_classifier: PropertyClassifier::new(),
}
}
pub fn compile_simple(&self, python_code: &str) -> PyResult<String> {
let ast = self.parse_python(python_code)?;
let classified = self.property_classifier.classify(ast);
let nyash_code = self.generate_nyash_with_properties(classified);
Ok(nyash_code)
}
}
struct PropertyClassifier;
impl PropertyClassifier {
fn new() -> Self { Self }
fn classify(&self, ast: PythonAst) -> ClassifiedAst {
// Phase 1: 基本パターンのみ
// @property → computed
// @cached_property → once
// __init__代入 → stored
todo!("実装")
}
}
```
## 🧪 MVP テストケース
### 入力Python
```python
# test_simple.py
class Counter:
def __init__(self):
self.value = 0
@property
def doubled(self):
return self.value * 2
@functools.cached_property
def expensive_result(self):
return sum(range(1000))
```
### 期待されるNyash出力
```nyash
box Counter {
value: IntegerBox // stored
doubled: IntegerBox { me.value * 2 } // computed
once expensive_result: IntegerBox { sum_range(1000) } // once
birth() {
me.value = 0
}
}
```
### 実行テスト
```bash
# transpilation
nyash --pyc test_simple.py -o test_simple.ny
# ネイティブコンパイル
nyash --compile-native test_simple.ny -o test_app
# 実行CPython依存なし
./test_app
```
## 📊 段階的成功指標
### Phase 1 (1週間後)
-@property, @cached_property認識
- ✅ 基本クラス → box変換
- ✅ 1つのサンプルPythonファイルが動作
### Phase 2 (2週間後)
- ✅ 継承、メソッド呼び出し対応
- ✅ 10個のサンプルファイル成功
- ✅ 性能測定CPythonとの比較
### Phase 3 (3週間後)
- ✅ エラーハンドリング、例外処理
- ✅ 実用的なPythonライブラリ部分対応
- ✅ AOT配布可能なサンプルアプリ
## 🌟 創造的可能性
### ハイブリッド開発
```python
# Python側で開発・デバッグ
@nyash.optimize # デコレータで高速化指定
def heavy_computation(data):
return complex_algorithm(data)
# 本番はNyash AOTで配布
```
### リアルタイムtranspilation IDE
- 左: Pythonコード編集
- 右: リアルタイムNyash生成表示
- 下: 性能比較グラフ
### 教育効果
- Pythonユーザーが自然にNyashを学習
- Property Systemの概念理解促進
## 🎯 今日から始められるアクション
1. **プラグイン skelton作成** (30分)
2. **pyo3でPython AST取得** (2時間)
3. **@property検出ロジック** (半日)
4. **最初のbox変換** (1日)
5. **テスト実行** (30分)
Property System革命により、この夢が現実になりました🚀