397bc77eb3
refactor(vm): StaticBoxRegistry unifies static box management
...
箱化モジュール化: Phase 173-B の散在した static box 管理を一元化
Before (4箇所に散在):
- static_box_decls: HashMap (AST経由のBox宣言)
- static_boxes: HashMap (実行時シングルトン)
- vm.rs Phase 173-B手動検出コード (~60行)
- method.rs static_box_decls.contains_key() 直接参照
After (StaticBoxRegistry箱に統一):
- declarations: AST経由のBox宣言を登録
- detected_boxes: MIR関数名から自動検出 (using import対応)
- instances: 遅延作成シングルトン
- naming utilities: parse/format関数
Benefits:
- vm.rs: 63行削減 (Phase 173-B手動コード削除)
- 自動検出: using import した static box も対応
- 単一責務: static box lifecycle を1箱に集約
- Fail-Fast: 存在しないBoxへのアクセスは即エラー
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-04 18:56:23 +09:00
9d29718f03
fix(vm): Phase 173-B using-imported static box method calls
...
Enable static box method calls for boxes imported via `using` statement.
Root cause: 3 interrelated issues
1. Cross-function ValueId: methodize created singleton with ValueId that
can't be used across MIR function boundaries
2. Missing registration: using-imported static boxes weren't in
static_box_decls (only AST-based boxes were registered)
3. Wrong dispatch: method.rs tried InstanceBox dispatch instead of
MIR function table lookup for static boxes
Fixes:
- unified_emitter.rs: Use receiver=None for StaticCompiler boxes
- vm.rs: Auto-detect and register static boxes from MIR function names
- mod.rs: Add has_static_box_decl() helper
- method.rs: Add MIR function table lookup path for static boxes
- guard.rs: Trust methodize for StaticCompiler boxes without type info
Test: JsonParserBox.toString() via using import now works correctly
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-04 18:49:10 +09:00
66479f921d
feat(phase106): FileBox provider_lock整理 & Fail-Fast強化(案B統一版)
...
Task 1: CoreBoxId.category() 修正
- File を CoreRequired 側に移動(L126)
- テスト期待値修正(L371)
- Phase 106 intent コメント更新(L107-115)
Task 2: provider_lock API 確認
- 変更なし(既存の set/get API をそのまま使用)
- get_filebox_provider_strict() は追加しない(シンプルに保つ)
Task 3: FileBox SSOT コメント追加
- L5-7 に責務明示コメント追加
Task 4: PluginHost に FileBox provider チェック追加
- with_core_from_registry_optional() に Phase 106 チェック追加(L158-167)
- test_with_core_from_registry_filebox_required() 追加(L413-445)
- 既存テスト2件を FileBox provider 初期化対応(L301-321, L323-351)
- test_with_core_from_registry_missing_box() をエラーメッセージ拡張(L386-410)
Task 5: ドキュメント更新
- core_boxes_design.md に Phase 106 セクション追加(L248-265)
- 責務分離原則・Ring0.FsApi 延期を明記
完了条件:
✅ ビルド成功(cargo build --release)
✅ テスト全PASS(cargo test --lib runtime: 64 passed; 0 failed)
✅ 指示書の実装チェックリスト全て completed
2025-12-03 17:55:26 +09:00
ea4c164dae
refactor(runner): Phase 105.5 Console出力のmacro統一化
...
- Replace direct console.println() calls with console_println! macro
- Simplify error handling in vm.rs (RC output)
- Simplify success logging in selfhost.rs (PluginHost init)
- Remove redundant nested if-let structures for Option handling
- Macro already handles all fallback scenarios (eprintln!)
This reduces code duplication and improves consistency. The macro
centralizes the fallback logic, making it easier to maintain.
Files modified:
- src/runner/modes/vm.rs (simplified RC output)
- src/runner/selfhost.rs (simplified PluginHost init message)
Line reduction: ~13 lines (nested if-let structures removed)
2025-12-03 14:25:28 +09:00
6ecd8f7f52
feat(runtime): Phase 103 CoreServices Optional化 - Memory Constraints対応
...
- Add CoreServicesConfig struct (from_env, minimal, all_enabled)
- Implement with_core_from_registry_optional() for selective initialization
- Update CoreBoxesImpl fields to Option<Arc<dyn XyzService>>
- Maintain backward compatibility (with_core_from_registry calls all_enabled)
- Add NYASH_CORE_DISABLE_* environment variable support
- ConsoleBox remains mandatory (Graceful Degradation principle)
- Add unit tests for optional initialization
- Update console_println! macro to handle Option type
- Fix direct console.println() calls in vm.rs and selfhost.rs
- Create core_optional_design.md documentation
Note: Phase 104 will extend ConsoleService to be optional as well with
graceful fallback in console_println! macro.
Files modified:
- src/runtime/plugin_host.rs (CoreServicesConfig, with_core_from_registry_optional, tests)
- src/runtime/core_services.rs (CoreBoxesImpl fields → Option type)
- src/runtime/mod.rs (console_println! macro updated)
- src/runner/modes/vm.rs (handle Option console)
- src/runner/selfhost.rs (handle Option console)
- docs/development/current/main/core_optional_design.md (new)
- docs/development/current/main/ring0-inventory.md (Phase 103 entry)
Test results:
- Build: ✅ Success (0 errors, 7 warnings)
- Unit tests: ✅ 3/3 passed (optional_core_tests)
- Runtime tests: ✅ 63/63 passed
- Smoke tests: ✅ 30/31 passed (1 pre-existing timeout)
2025-12-03 13:59:06 +09:00
0c527dcd22
feat(runtime): Phase 101-A dev-debug ログの Ring0.log 統一 - 34箇所完了
...
## Phase 101-A 完了項目
- ✅ llvm.rs: 13箇所([joinir/llvm], [parse/context]) → Ring0.log
- ✅ loop_form.rs: [loopform] 系ログ → Ring0.log
- ✅ loopform_builder.rs: 16箇所([loopform/prepare], [loopform/seal_phis]) → Ring0.log
- ✅ loop_snapshot_merge.rs: 5箇所([Option C]) → Ring0.log
- ✅ 全テストPASS(ビルド成功)
## 置き換え箇所(34箇所)
**llvm.rs**(13箇所):
- [joinir/llvm] JoinIR 実験パスログ(12箇所)
- [parse/context] プリロードファイルリスト(1箇所)
**loop_form.rs**(複数箇所):
- [loopform] 基本ログ
- [loopform/condition] 条件式処理
- [loopform/writes] 変数書き込み収集
**loopform_builder.rs**(16箇所):
- [loopform/prepare] 構造準備
- [loopform/seal_phis] PHI シーリング処理
**loop_snapshot_merge.rs**(5箇所):
- [Option C] Exit PHI 分類
- [Option C] 変数解析
## 技術的成果
- Ring0.log で dev-debug ログを一元管理
- stderr の cleanness 向上(ユーザー向けメッセージのみ)
- 環境に応じた出力制御が可能(NYASH_LOOPFORM_DEBUG等)
- Phase 99-100 で確立した 3層設計を実装レベルで完成
## 実装パターン
```rust
// Before
eprintln!("[loopform] variable_map: {:?}", map);
// After
crate::runtime::get_global_ring0().log.debug(&format!(
"[loopform] variable_map: {:?}", map
));
```
## 統計
- Phase 98: 7箇所(ConsoleService)
- Phase 100: 29箇所(ConsoleService)
- Phase 101-A: 34箇所(Ring0.log)
- **合計**: 70箇所で統一(ConsoleService/Ring0.log)
- 残り: ~905箇所(test含む)
## ドキュメント更新
- logging_policy.md: Section 7-A 追加(Phase 101-A 実装記録)
- ring0-inventory.md: Category 2 更新(dev-debug 進捗反映)
- CURRENT_TASK.md: Phase 85 セクション追記
## Phase 85-101-A 総括
- Phase 95.5-97: CoreServices 6個完全実装(String/Integer/Bool/Array/Map/Console)
- Phase 98-98.5: ConsoleService 代表パス拡張(7箇所)
- Phase 99: ログ/出力ポリシー確定(3層設計文書化)
- Phase 100: user-facing 出力の ConsoleService 化(29箇所)
- Phase 101-A: dev-debug ログの Ring0.log 統一(34箇所) ✅
次: Phase 101-B(internal/test ログの整理、別検討)
🎊 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-03 12:25:32 +09:00
7cf11fbc5c
feat(runtime): Phase 100 user-facing 出力の ConsoleService 完全統一 - 29箇所完了
...
## Phase 100 完了項目
- ✅ selfhost.rs: 6箇所 → console_println!
- ✅ llvm.rs: 23箇所(主要メッセージ) → console_println!
- ✅ 全テストPASS(core_services: 11, plugin_host: 7)
- ✅ ドキュメント更新完了
## 置き換え箇所(29箇所)
**selfhost.rs**(6箇所):
- Line 57: CoreInitError 出力
- Lines 194/363/418/519/570: Result 出力
**llvm.rs**(23箇所、ユーザー向けメッセージのみ):
- エラーメッセージ(❌ ): ファイル読み込み、using/parse エラー
- 成功メッセージ(📊 ): MIR コンパイル成功
- LLVM/harness 関連エラー
- 実行結果出力
- Mock LLVM メッセージ
## 意図的に除外(Phase 101 対象)
- llvm.rs の `[joinir/llvm]`, `[parse/context]` デバッグログ
- hack_check: .hako アプリ(Nyash言語の ConsoleBox 経由)
- bench.rs: テスト・性能表示(dev-debug)
- mir.rs: 内部 MIR ダンプ(dev-debug)
## 技術的成果
- selfhost/LLVM runner のユーザー向けメッセージを ConsoleService に統一
- Phase 99 で確立したログ/出力ポリシーを実装レベルで実現
- デバッグログとユーザー向け出力の明確な分離
- Graceful Degradation パターンの実用確認
## 統計
- Phase 98: 7箇所
- Phase 100: 29箇所
- **合計**: 36箇所で ConsoleService 経由に移行完了
- 残り user-facing: ~330箇所(Phase 101-102 で段階的拡張)
## ドキュメント更新
- logging_policy.md: Section 7 追加(Phase 100 実装完了記録)
- ring0-inventory.md: Category 1 更新(Phase 100 進捗反映)
- CURRENT_TASK.md: Phase 85 セクション追記
## Phase 85-100 総括
- Phase 95.5-97: CoreServices 6個完全実装(String/Integer/Bool/Array/Map/Console)
- Phase 98-98.5: ConsoleService 代表パス拡張(7箇所)
- Phase 99: ログ/出力ポリシー確定(3層設計文書化)
- Phase 100: user-facing 出力の ConsoleService 化(29箇所) ✅
次: Phase 101(dev-debug/test/internal 出力の整理、Ring0.log 活用)
🎊 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-03 11:55:14 +09:00
44c6ca9585
chore(runtime): Phase 98.5 Arc 完全修飾パス簡略化 & コメント統一
...
## 修正内容
**src/runtime/mod.rs** (4箇所):
- use文: std::sync::OnceLock → std::sync::{Arc, OnceLock}
- Line 64: OnceLock<std::sync::Arc<...>> → OnceLock<Arc<...>>
- Line 68: std::sync::Arc::new(...) → Arc::new(...)
- Line 72/80: 戻り値型で std::sync::Arc → Arc に統一
**src/runner/modes/vm.rs** (1箇所):
- Line 589: コメント統一 "println" → "eprintln"(実装に合わせる)
## 効果
- 可読性向上: std::sync:: プレフィックス4箇所削除
- 一貫性向上: console_println! マクロの説明と実装を統一
- 追加依存なし、機能変更なし
## テスト結果
✅ cargo build --release: 成功
✅ cargo test --lib runtime::core_services: 11 passed
🧹 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-03 11:17:41 +09:00
7bcb7ec596
feat(runtime): Phase 98 ConsoleService 代表パス拡張 - 7箇所置き換え完了
...
## Phase 98 完了項目
- ✅ println!/eprintln! 7箇所 → ConsoleService 経由に移行
- ✅ console_println! マクロ追加(Graceful Degradation パターン)
- ✅ try_get_core_plugin_host() 追加(安全なアクセサー)
- ✅ 全テストPASS(core_services: 11, plugin_host: 7)
## 置き換え箇所(7箇所)
**selfhost/child.rs** (3箇所):
- spawn失敗エラー
- タイムアウトメッセージ(stdout/stderr)
**core_bridge.rs** (2箇所):
- DUMP書き込みエラー
- DUMP_MUT書き込みエラー
**vm.rs** (1箇所):
- RC(return code)出力
**selfhost/json.rs** (2箇所, オプション達成):
- PyVM MIR JSON emit エラー
- PyVM 使用ログ(verbose時)
## 技術的成果
**Graceful Degradation パターン確立**:
- PluginHost 初期化前: eprintln! フォールバック
- PluginHost 初期化後: ConsoleService 使用(Ring0直結)
- Fail-Fast原則との整合性: 出力先選択のみ動的
**実装インフラ**:
- src/runtime/mod.rs: console_println! マクロ & try_get_core_plugin_host()
- 既存の get_core_plugin_host() は panic! 保持(Fail-Fast)
## 統計
- 置き換え完了: 7箇所(全体の約2%)
- 残り候補: 約359箇所(Phase 99以降)
- テスト: ビルド成功、全ユニットテストPASS
## ドキュメント
- docs/development/current/main/core_boxes_design.md: Section 15 追加(128行)
- 実装パターン、設計判断、テスト結果を完全記録
## Phase 85-98 総括
- Phase 85-94: 構造設計 & 箱化モジュール化
- Phase 95.5: StringService/ConsoleService(Ring0直結型・純粋関数型)
- Phase 96-96.5: ArrayService/MapService(downcast型)& コード整理
- Phase 97: IntegerService/BoolService(純粋関数型、#[allow(dead_code)] 根絶)
- Phase 98: ConsoleService 実用拡大(7箇所)✅ 完了
次: Phase 99(CoreServices 完全統合、残り約359箇所の段階的移行)
🎊 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-03 11:04:58 +09:00
4e2e45a79d
feat(phase90): Ring0Context fs/time/thread migration complete
...
Phase 90 完了: IO/fs/time/thread 系の Ring0 移行
**Phase 90-A: fs 系移行(7箇所)**
- FsApi trait 追加(6メソッド)
- StdFs 実装(std::fs ベース)
- IoError 拡張(4バリアント追加)
- 移行: strip.rs(4), dispatch.rs(1), mod.rs(3)
**Phase 90-B: io 系移行**
- Phase 88 完了済み(スキップ)
**Phase 90-C: time 系移行(3箇所)**
- TimeApi に elapsed() 追加
- 移行: selfhost_exe.rs(1), io.rs(1), plugin_loader_unified.rs(1)
**Phase 90-D: thread 系移行(2箇所)**
- ThreadApi trait 追加(sleep メソッド)
- StdThread 実装
- 移行: global_hooks.rs(1), plugin_loader_unified.rs(1)
**Phase 90-E: 統合テスト**
- ビルド成功(6 warnings, 0 errors)
- テスト: 522/554 passed (94.2%)
- 退行なし
**実装成果**:
- Ring0Context 拡張: fs, thread フィールド追加
- 総移行: 12箇所(fs: 7, time: 3, thread: 2)
- 移行率: fs(2.9%), time(2.1%), thread(5.4%)
**次のステップ**: Phase 91 (PluginHost/CoreServices skeleton)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-03 06:14:57 +09:00
a01110e791
feat(phase89-a): Ring0Context logs migration - 56 locations
...
Phase 89-A 完了: println!/eprintln! → ring0.log.* 移行
**実装内容**:
- 環境変数制御: NYASH_RING0_LOG_LEVEL (DEBUG/INFO/WARN/ERROR)
- selfhost.rs: 24箇所移行 (error:14, warn:2, info:5, debug:3)
- vm.rs: 32箇所移行 (error:5, warn:4, info:2, debug:21)
**実装効果**:
- 総移行箇所: 56箇所 (目標: 10-15箇所 → 373%達成)
- 累計進捗: 58/3,955箇所 (1.47%)
- テスト結果: 521 passed; 33 failed (変化なし)
**次のステップ**: Phase 89-B (IO/time 棚卸し)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-02 23:27:41 +09:00
8633224061
JoinIR/SSA/Stage-3: sync CURRENT_TASK and dev env
2025-12-01 11:10:46 +09:00
a3d5bacc55
Phase 30.1 & 73: Stage-3 features env and JoinIR flag cleanup
2025-11-30 14:30:28 +09:00
447bbec998
refactor(joinir): Split ast_lowerer and join_ir_vm_bridge into modules
...
ast_lowerer.rs → ast_lowerer/ (10 files):
- mod.rs: public surface + entry dispatch
- context.rs: ExtractCtx helpers
- expr.rs: expression-to-JoinIR extraction
- if_return.rs: simple if→Select lowering
- loop_patterns.rs: loop variants (simple/break/continue)
- read_quoted.rs: read_quoted_from lowering (Phase 45-46)
- nested_if.rs: NestedIfMerge lowering
- analysis.rs: loop if-var analysis + metadata helpers
- tests.rs: frontend lowering tests
- README.md: module documentation
join_ir_vm_bridge.rs → join_ir_vm_bridge/ (5 files):
- mod.rs: public surface + shared helpers
- convert.rs: JoinIR→MIR lowering
- runner.rs: VM execution entry (run_joinir_via_vm)
- meta.rs: experimental metadata-aware hooks
- tests.rs: bridge-specific unit tests
- README.md: module documentation
Benefits:
- Clear separation of concerns per pattern
- Easier navigation and maintenance
- Each file has single responsibility
- README documents module boundaries
Co-authored-by: ChatGPT <noreply@openai.com >
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-28 17:42:19 +09:00
588129db65
feat(joinir): Phase 34-6 MethodCall 構造と本物の substring 意味論
...
**Phase 34-6 実装完了**: MethodCall 構造を JoinIR に追加し、本物の substring
呼び出しを通すことに成功。
## 主要変更
### 1. MethodCall 構造追加 (34-6.1)
- `src/mir/join_ir/mod.rs`: JoinInst::MethodCall バリアント (+8 lines)
- 構造: `{ dst, receiver, method, args }`
- 設計原則: JoinIR は構造のみ、意味論は MIR レベル
### 2. extract_value 更新 (34-6.2)
- `src/mir/join_ir/frontend/ast_lowerer.rs`: Method 処理本物化 (+37 lines)
- receiver/args を extract_value で再帰処理
- ダミー Const(0) 削除 → 本物の MethodCall 生成
- cond 処理修正: ValueId(0) ハードコード → extract_value で取得
### 3. JoinIR→MIR 変換実装 (34-6.3)
- `src/mir/join_ir_vm_bridge.rs`: MethodCall → BoxCall 変換 (+12 lines)
- `src/mir/join_ir/json.rs`: MethodCall JSON シリアライゼーション (+16 lines)
- `src/mir/join_ir_runner.rs`: MethodCall 未対応エラー (+7 lines)
### 4. テスト更新 (34-6.4)
- `docs/.../fixtures/json_shape_read_value.program.json`: 本物の substring 構造
- `src/tests/joinir_frontend_if_select.rs`: run_joinir_via_vm 使用
- テスト成功: v="hello", at=3 → "hel" ✅
## 成果
- ✅ テスト全通過(1 passed; 0 failed)
- ✅ 設計原則確立: JoinIR = 構造 SSOT、意味論 = MIR レベル
- ✅ Phase 33-10 原則との整合性: Method でも同じ原則適用
**ドキュメント更新**: CURRENT_TASK.md + TASKS.md(Phase 34-6 完了記録)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-27 17:05:46 +09:00
35cd93a37a
Phase 33-2: JoinInst::Select implementation + minimal If JoinIR lowering
...
Implementation:
- Add JoinInst::Select variant to JoinIR schema
- Implement Select execution in JoinIR Runner (Bool/Int cond support)
- Add Select handling in JoinIR→MIR Bridge (4-block structure)
- Create test cases (joinir_if_select_simple/local.hako)
- Add dev toggle NYASH_JOINIR_IF_SELECT=1
- Create lowering infrastructure (if_select.rs, stub for Phase 33-3)
Tests:
- 3/3 unit tests pass (test_select_true/false/int_cond)
- Integration tests pass (RC: 0)
- A/B execution verified (existing if_phi vs JoinIR Select)
Files changed:
- New: apps/tests/joinir_if_select_{simple,local}.hako
- New: src/mir/join_ir/lowering/if_select.rs
- Modified: src/mir/join_ir/{mod,json,runner,vm_bridge}.rs
- Modified: src/config/env.rs (joinir_if_select_enabled)
- Modified: docs/reference/environment-variables.md
Phase 33-3 ready: MIR pattern recognition + auto-lowering pending
🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-27 02:58:38 +09:00
51ff558904
feat(phase32): L-2.1 Stage-1 UsingResolver JoinIR integration + cleanup
...
Phase 32 L-2.1 complete implementation:
1. Stage-1 UsingResolver main line JoinIR connection
- CFG-based LoopForm construction for resolve_for_source/5
- LoopToJoinLowerer integration with handwritten fallback
- JSON snapshot tests 6/6 PASS
2. JoinIR/VM Bridge improvements
- Simplified join_ir_vm_bridge.rs dispatch logic
- Enhanced json.rs serialization
- PHI core boxes cleanup (local_scope_inspector, loop_exit_liveness, loop_var_classifier)
3. Stage-1 CLI enhancements
- Extended args.rs, groups.rs, mod.rs for new options
- Improved stage1_bridge module (args, env, mod)
- Updated stage1_cli.hako
4. MIR builder cleanup
- Simplified if_form.rs control flow
- Removed dead code from loop_builder.rs
- Enhanced phi_merge.rs
5. Runner module updates
- json_v0_bridge/lowering.rs improvements
- dispatch.rs, selfhost.rs, modes/vm.rs cleanup
6. Documentation updates
- CURRENT_TASK.md, AGENTS.md
- Various docs/ updates
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-26 10:17:37 +09:00
29ae922a57
feat(joinir): Stage-1 UsingResolver JoinIR VM Bridge A/B test
...
Phase 30.x: Stage-1 ループでも PHI バグが発生することを確認・JoinIR で設計根絶可能を実証
変更内容:
- src/tests/joinir_vm_bridge_stage1_usingresolver.rs: 新規作成(モジュール化・削除容易)
- empty_entries: VM → "void" (PHI bug, expected "init")
- with_entries: VM → "void" (PHI bug, expected "ABC")
- lowering_sanity: 常時実行の構造検証
- src/runner/modes/vm.rs: Stage1UsingResolverBox.resolve_for_source/5 検出・JoinIR lowering 確認
- src/tests/mod.rs: モジュール追加(1行で削除可能)
- docs: Phase 30 TASKS.md に L-0.5 追加
発見:
Stage-1 ループでも PHI バグが発生 → JoinIR で設計根絶可能を確認
(ArrayBox/MapBox 引数対応は TODO)
テスト結果:
✅ empty_entries ... ok (VM="void", expected="init", PHI bug detected)
✅ with_entries ... ok (VM="void", expected="ABC", PHI bug detected)
✅ lowering_sanity ... ok (JoinIR structure: 2 functions)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-25 12:34:20 +09:00
ee2b3115ee
feat(joinir): FuncScannerBox.trim/1 JoinIR VM Bridge A/B test
...
Phase 30.x: JoinIR VM Bridge でPHI問題を設計で解決できることを実証
変更内容:
- src/runner/modes/vm.rs: FuncScannerBox.trim/1 検出時にJoinIR経由実行
- src/mir/join_ir_vm_bridge.rs: Non-tail call サポート追加
- dst=Some(id) の場合、結果を格納して次の命令へ継続
- src/tests/joinir_vm_bridge_trim.rs: A/Bテスト新規作成
- メインテスト: Route A (VM) → "void" (PHI bug), Route C (JoinIR) → "abc" ✅
- エッジケース: 5パターン全てPASS
- src/config/env.rs: joinir_vm_bridge_debug() 追加
- docs: Phase 30 TASKS.md に L-0.4 追加
テスト結果:
Route A (MIR→VM直接): "void" ← PHI バグ
Route C (MIR→JoinIR→VM): "abc" ← 正解 ✅
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-25 12:22:08 +09:00
c479e5f527
fix(dx): Quick Win 1-3 for better error messages and API simplification
...
Quick Win 1: Show available boxes on "Unknown Box type" error
- vm.rs, vm_fallback.rs: Display sorted list of available user-defined boxes
- Before: "Unknown Box type: Foo"
- After: "Unknown Box type: Foo. Available: Bar, Baz, Main"
Quick Win 2: Show stderr on child process timeout
- child.rs, selfhost_exe.rs: Capture and display stderr (up to 500 chars)
- Helps diagnose what went wrong in selfhost compiler child process
Quick Win 3: Simplify Stage-B compiler API (SSOT)
- compiler_stageb.hako: Add StageBDriverBox.compile() as single entry point
- compiler_stageb.hako: Remove StageBMain compatibility wrapper
- compiler.hako: Change from `using ... as StageBMain` to direct import
- compiler.hako: Call StageBDriverBox.compile() directly
Also includes child_env.rs NYASH_MODULES env var for module mapping.
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-25 08:44:31 +09:00
c6c5653ae0
fix(parser): Stage-1 CLI infinite loop - MirBuilder-friendly refactoring (Part 1/3)
...
**Problem**: Stage-1 CLI hits VM step budget (infinite loops) in multiple functions
- ParserBox.parse_program2: bb2853→bb2854 loop
- StringHelpers.skip_ws: bb488→bb491 loop
**Root Cause**: MirBuilder bug with `loop(cont==1)` + nested `if-else` pattern
- PHI instructions with self-references
- Loop exit blocks jumping back to header instead of continuation
**Solution**: Refactor to MirBuilder-friendly pattern
```hako
// Before (causes infinite loop):
loop(cont == 1) {
if guard > max { return j } else { guard++ }
if condition { action } else { cont = 0 }
}
// After (MirBuilder-friendly):
loop(j < n) {
if condition { j++; continue }
break
}
```
**Changes**:
1. parser_box.hako: parse_program2 main loop refactored
- 7 sections: ws→EOF/guard→parse_stmt2→progress guard→trace→semicolons→emit
- Unconditional parse_stmt2 execution (no nested if-else)
- Explicit `break` for loop exits
2. string_helpers.hako: StringHelpers.skip_ws simplified
- Removed `cont` flag and guard counter
- Direct `loop(j < n)` with `continue/break`
3. vm.rs, vm_fallback.rs: RUST_MIR_DUMP_PATH support
- Enables offline MIR analysis for debugging
**Progress**:
- ✅ parse_program2: infinite loop fixed
- ✅ StringHelpers.skip_ws: infinite loop fixed
- ⏳ ParserIdentScanBox.scan_ident: next target (bb985 loop)
**Testing**:
- MIR dumps generated successfully (116K+ lines)
- ws_init loop completes
- parse_program2 progresses further
- Still hits infinite loop in scan_ident (Part 2 needed)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-24 18:19:31 +09:00
da1a5558e5
Normalize passes keep spans and clean warnings
2025-11-24 15:02:51 +09:00
466e636af6
Span trace utilities and runner source hint
2025-11-24 14:17:02 +09:00
63012932eb
feat(phase-0): 観測ライン緊急構築完了 - Silent Failure 根絶
...
Phase 21.7++ Phase 0: 開発者体験を劇的に向上させる3つの改善
## 🎯 実装内容
### ✅ Phase 0.1: populate_from_toml エラー即座表示
**ファイル**: src/runner/pipeline.rs:57-65
**Before**: TOML parse エラーが silent failure
**After**: エラーを即座に警告表示 + デバッグ方法提示
```
⚠️ [using/workspace] Failed to load TOML modules:
Error: TOML parse error at line 18...
→ All 'using' aliases will be unavailable
→ Fix TOML syntax errors in workspace modules
💡 Debug: NYASH_DEBUG_USING=1 for detailed logs
```
**効果**: 今回の StringUtils バグなら即発見できた!
### ✅ Phase 0.2: VM 関数ルックアップ常時提案
**ファイル**: src/backend/mir_interpreter/handlers/calls/global.rs:179-206
**Before**: "Unknown: StringUtils.starts_with" だけ
**After**: 類似関数を自動提案 + デバッグ方法提示
```
Function not found: StringUtils.starts_with
💡 Did you mean:
- StringUtils.starts_with/2
- StringUtils.ends_with/2
🔍 Debug: NYASH_DEBUG_FUNCTION_LOOKUP=1 for full lookup trace
```
**効果**: arity 問題を即発見!環境変数不要で親切!
### ✅ Phase 0.3: using not found 詳細化
**ファイル**: src/runner/modes/common_util/resolve/strip.rs:354-389
**Before**: "'StringUtils' not found" だけ
**After**: 類似モジュール提案 + 利用可能数 + 修正方法提示
```
using: 'StringUtil' not found in nyash.toml [using]/[modules]
💡 Did you mean:
- StringUtils
- JsonUtils
Available modules: 4 aliases
📝 Suggestions:
- Add an alias in nyash.toml: [using.aliases] YourModule = "path/to/module"
- Use the alias: using YourModule as YourModule
- Dev/test mode: NYASH_PREINCLUDE=1
🔍 Debug: NYASH_DEBUG_USING=1 for detailed logs
```
**効果**: タイポを即発見!TOML エラーとの因果関係も提示!
## 📊 Phase 0 成果まとめ
**工数**: 約2.5時間(予想: 2-3時間)✅
**効果**: Silent Failure 完全根絶 🎉
### Before Phase 0
- TOML エラー: 無言で失敗
- 関数が見つからない: "Unknown" だけ
- using が見つからない: "not found" だけ
- デバッグ方法: 環境変数を知ってる人だけ
### After Phase 0
- TOML エラー: 即座に警告 + 影響範囲説明
- 関数が見つからない: 類似関数提案 + デバッグ方法
- using が見つからない: 類似モジュール提案 + 修正方法 + デバッグ方法
- すべてのエラーが親切 🎊
## ✅ テスト結果
- StringUtils テスト: ✅ PASS
- 既存テスト: ✅ 337 passed(16 failed は元々の失敗)
- ビルド: ✅ SUCCESS
- 退行: ❌ なし
## 🎉 開発者体験の改善
今回のような StringUtils using バグが起きても:
1. **TOML エラー**: 即発見(数秒)
2. **arity 問題**: 提案から即解決(数分)
3. **タイポ**: 提案から即修正(数秒)
**Before**: 数時間のデバッグ
**After**: 数分で解決 🚀
次のステップ: Phase 1(基盤整備)に進む準備完了!
2025-11-22 02:13:10 +09:00
bceb20ed66
refactor(naming): 箱理論 - Entry選択ロジック統一&NamingBox統合
...
Phase 25.4 メンテナンス: Task A延長線上の箱化リファクタリング
## 📦 箱化内容
### 1. Entry選択ロジック統一箱
- 新規作成: `src/runner/modes/common_util/entry_selection.rs`
- 3箇所の重複ロジックを `select_entry_function()` に集約
- `selfhost/json.rs:48-59` (11行削減)
- `pyvm.rs:32-43` (11行削減)
- `pyvm.rs:102-113` (11行削減)
- `llvm.rs:292` (直接アクセス→統一関数呼び出し)
### 2. NamingBox SSOT 統合
- arity-aware優先フォールバック実装
1. `Main.main/0` (arity付き、NYASH_BUILD_STATIC_MAIN_ENTRY=1時)
2. `Main.main` (legacy、arity無し、現行デフォルト)
3. `main` (top-level、NYASH_ENTRY_ALLOW_TOPLEVEL_MAIN=1時)
4. `"Main.main"` (デフォルトフォールバック)
## 技術的成果
- **重複削減**: 33行の重複ロジック→1箇所に集約
- **NamingBox統一**: 全Entry選択が `src/mir/naming.rs` 経由
- **将来対応**: arity付き名前に自動対応(互換性維持)
## テスト結果
✅ cargo test mir_static_box_naming: 2 passed
✅ cargo test stage1_cli_entry_ssa_smoke: 2 passed
## 参考
- Phase 25.4-A完了commit: fa9cea51
- 箱理論原則: 重複ロジックを箱化→境界を明確化→一元管理
🎉 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-21 09:33:56 +09:00
f9d100ce01
chore: Phase 25.1 完了 - LoopForm v2/Stage1 CLI/環境変数削減 + Phase 26-D からの変更
...
Phase 25.1 完了成果:
- ✅ LoopForm v2 テスト・ドキュメント・コメント完備
- 4ケース(A/B/C/D)完全テストカバレッジ
- 最小再現ケース作成(SSAバグ調査用)
- SSOT文書作成(loopform_ssot.md)
- 全ソースに [LoopForm] コメントタグ追加
- ✅ Stage-1 CLI デバッグ環境構築
- stage1_cli.hako 実装
- stage1_bridge.rs ブリッジ実装
- デバッグツール作成(stage1_debug.sh/stage1_minimal.sh)
- アーキテクチャ改善提案文書
- ✅ 環境変数削減計画策定
- 25変数の完全調査・分類
- 6段階削減ロードマップ(25→5、80%削減)
- 即時削除可能変数特定(NYASH_CONFIG/NYASH_DEBUG)
Phase 26-D からの累積変更:
- PHI実装改善(ExitPhiBuilder/HeaderPhiBuilder等)
- MIRビルダーリファクタリング
- 型伝播・最適化パス改善
- その他約300ファイルの累積変更
🎯 技術的成果:
- SSAバグ根本原因特定(条件分岐内loop変数変更)
- Region+next_iパターン適用完了(UsingCollectorBox等)
- LoopFormパターン文書化・テスト化完了
- セルフホスティング基盤強化
Co-Authored-By: Claude <noreply@anthropic.com >
Co-Authored-By: ChatGPT <noreply@openai.com >
Co-Authored-By: Task Assistant <task@anthropic.com >
2025-11-21 06:25:17 +09:00
d3cbc71c9b
feat(mir): Phase 25.1f完了 - Conservative PHI + ControlForm観測レイヤー
...
🎉 Conservative PHI Box理論による完全SSA構築
**Phase 7-B: Conservative PHI実装**
- 片方branchのみ定義変数に対応(emit_void使用)
- 全変数にPHI生成(Conservative Box理論)
- Stage-1 resolver全テスト緑化(3/3 PASS)
**Phase 25.1f: ControlForm観測レイヤー**
- LoopShape/IfShape/ControlForm構造定義
- Loop/If統一インターフェース実装
- debug_dump/debug_validate機能追加
- NYASH_CONTROL_FORM_TRACE環境変数対応
**主な変更**:
- src/mir/builder/phi.rs: Conservative PHI実装
- src/mir/control_form.rs: ControlForm構造(NEW)
- src/mir/loop_builder.rs: LoopForm v2デフォルト化
**テスト結果**:
✅ mir_stage1_using_resolver_min_fragment_verifies
✅ mir_stage1_using_resolver_full_collect_entries_verifies
✅ mir_parserbox_parse_program2_harness_parses_minimal_source
🤖 Generated with Claude Code
Co-Authored-By: Claude <noreply@anthropic.com >
Co-Authored-By: ChatGPT <chatgpt@openai.com >
2025-11-18 18:56:35 +09:00
f74b7d2b04
📦 Hotfix 1 & 2: Parameter ValueId Reservation + Exit PHI Validation (Box-First Theory)
...
**箱理論に基づく根治的修正**:
## 🎯 Hotfix 1: Parameter ValueId Reservation (パラメータ ValueId 予約)
### 根本原因
- MirFunction counter が params.len() を考慮していなかった
- local variables が parameter ValueIds を上書き
### 箱理論的解決
1. **LoopFormContext Box**
- パラメータ予約を明示的に管理
- 境界をはっきりさせる
2. **MirFunction::new() 改善**
- `initial_counter = param_count.max(1)` でパラメータ予約
- Parameters are %0, %1, ..., %N-1
3. **ensure_counter_after() 強化**
- パラメータ数 + 既存 ValueIds 両方を考慮
- `min_counter = param_count.max(max_id + 1)`
4. **reserve_parameter_value_ids() 追加**
- 明示的な予約メソッド(Box-First)
## 🎯 Hotfix 2: Exit PHI Predecessor Validation (Exit PHI 検証)
### 根本原因
- LoopForm builder が存在しないブロックを PHI predecessor に追加
- 「幽霊ブロック」問題
### 箱理論的解決
1. **LoopFormOps.block_exists() 追加**
- CFG 存在確認メソッド
- 境界を明確化
2. **build_exit_phis() 検証**
- 非存在ブロックをスキップ
- デバッグログ付き
### 実装ファイル
- `src/mir/function.rs`: Parameter reservation
- `src/mir/phi_core/loopform_builder.rs`: Context + validation
- `src/mir/loop_builder.rs`: LoopFormOps impl
- `src/mir/builder/stmts.rs`: Local variable allocation
### 業界標準準拠
- ✅ LLVM IR: Parameters are %0, %1, ...
- ✅ SSA Form: PHI predecessors must exist in CFG
- ✅ Cytron et al. (1991): Parameter reservation principle
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-18 06:39:45 +09:00
4b078e6df9
fix(vm): register static boxes in user factory for NewBox support
...
**Problem**: NewBox for static boxes (e.g., HakoCli) failed with
"Plugins disabled, cannot create HakoCli" error when NYASH_DISABLE_PLUGINS=1.
**Root cause**: static box declarations were only registered with
VM's register_static_box_decl for singleton persistence, but NOT
included in InlineUserBoxFactory's decls. This caused UnifiedBoxRegistry
to skip User factory and fall through to Plugin factory, which failed
when plugins were disabled.
**Fix**: Include static_box_decls in InlineUserBoxFactory's decls map.
Static boxes remain singletons (VM ensures single instance via
register_static_box_decl), but now they're also advertised by User factory
so NewBox doesn't incorrectly route to Plugin factory.
**Implementation** (src/runner/modes/vm.rs):
1. Add static_box_decls to InlineUserBoxFactory decls after nonstatic_decls
2. nonstatic takes precedence if name conflicts (rare but possible)
3. StaticName -> StaticNameInstance aliases still work as before
**Behavior** (UnifiedBoxRegistry with StrictPluginFirst policy):
- try factory#1 Plugin → fails (NYASH_DISABLE_PLUGINS=1)
- try factory#2 User → succeeds (static box found in decls)
- NewBox creates InstanceBox, VM ensures singleton semantics
**Verification**:
- Test case: /tmp/test_static_newbox.hako
- NewBox TestStatic successfully creates instance via User factory
- Methods callable, return values correct
- No plugin errors with NYASH_DISABLE_PLUGINS=1
**Impact**: static box new instances now work correctly without plugins,
matching Rust layer's design where static boxes are user-defined types
(not plugin types) with singleton semantics.
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-17 02:38:54 +09:00
eadde8d1dd
fix(mir/builder): use function-local ValueId throughout MIR builder
...
Phase 25.1b: Complete SSA fix - eliminate all global ValueId usage in function contexts.
Root cause: ~75 locations throughout MIR builder were using global value
generator (self.value_gen.next()) instead of function-local allocator
(f.next_value_id()), causing SSA verification failures and runtime
"use of undefined value" errors.
Solution:
- Added next_value_id() helper that automatically chooses correct allocator
- Fixed 19 files with ~75 occurrences of ValueId allocation
- All function-context allocations now use function-local IDs
Files modified:
- src/mir/builder/utils.rs: Added next_value_id() helper, fixed 8 locations
- src/mir/builder/builder_calls.rs: 17 fixes
- src/mir/builder/ops.rs: 8 fixes
- src/mir/builder/stmts.rs: 7 fixes
- src/mir/builder/emission/constant.rs: 6 fixes
- src/mir/builder/rewrite/*.rs: 10 fixes
- + 13 other files
Verification:
- cargo build --release: SUCCESS
- Simple tests with NYASH_VM_VERIFY_MIR=1: Zero undefined errors
- Multi-parameter static methods: All working
Known remaining: ValueId(22) in Stage-B (separate issue to investigate)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-17 00:48:18 +09:00
7ca7f646de
Phase 25.1b: Step2完了(FuncBodyBasicLowerBox導入)
...
Step2実装内容:
- FuncBodyBasicLowerBox導入(defs専用下請けモジュール)
- _try_lower_local_if_return実装(Local+単純if)
- _inline_local_ints実装(軽い正規化)
- minimal lowers統合(Return/BinOp/IfCompare/MethodArray系)
Fail-Fast体制確立:
- MirBuilderBox: defs_onlyでも必ずタグ出力
- [builder/selfhost-first:unsupported:defs_only]
- [builder/selfhost-first:unsupported:no_match]
Phase構造整備:
- Phase 25.1b README新設(Step0-3計画)
- Phase 25.2b README新設(次期計画)
- UsingResolverBox追加(using system対応準備)
スモークテスト:
- stage1_launcher_program_to_mir_canary_vm.sh追加
Next: Step3 LoopForm対応
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-15 22:32:13 +09:00
1f961b3e75
feat(phase-21.8): extend collect_using_and_strip to return imports HashMap
...
**Step 6 Complete**: Extract using imports from .hako source in pipeline
Changes:
- Modified collect_using_and_strip() to return (cleaned, prelude_paths, imports)
- Build imports HashMap from seen_aliases (alias -> alias mapping)
- Updated all 6 call sites to handle new 3-tuple return type
- This provides MirBuilder with info about which names are valid static box references
Next: Wire imports through extern_provider to MirBuilder (Step 7)
Related: #phase-21.8 MatI64/IntArrayCore integration
2025-11-14 16:03:32 +09:00
f1fa182a4b
AotPrep collections_hot matmul tuning and bench tweaks
2025-11-14 13:36:20 +09:00
dda65b94b7
Phase 21.7 normalization: optimization pre-work + bench harness expansion
...
- Add opt-in optimizations (defaults OFF)
- Ret purity verifier: NYASH_VERIFY_RET_PURITY=1
- strlen FAST enhancement for const handles
- FAST_INT gate for same-BB SSA optimization
- length cache for string literals in llvmlite
- Expand bench harness (tools/perf/microbench.sh)
- Add branch/call/stringchain/arraymap/chip8/kilo cases
- Auto-calculate ratio vs C reference
- Document in benchmarks/README.md
- Compiler health improvements
- Unify PHI insertion to insert_phi_at_head()
- Add NYASH_LLVM_SKIP_BUILD=1 for build reuse
- Runtime & safety enhancements
- Clarify Rust/Hako ownership boundaries
- Strengthen receiver localization (LocalSSA/pin/after-PHIs)
- Stop excessive PluginInvoke→BoxCall rewrites
- Update CURRENT_TASK.md, docs, and canaries
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-13 16:40:58 +09:00
07a254fc0d
feat(phase21.5): MirBuilder optimization prep + crate EXE infrastructure
...
Phase 21.5 optimization readiness - C-level performance target:
- MirBuilder: JsonFrag purify toggle (HAKO_MIR_BUILDER_JSONFRAG_PURIFY=1)
- Normalizer: extended f64 canonicalization + dedupe improvements
- loop_opts_adapter: JsonFrag path refinement for crate EXE compatibility
Infrastructure improvements:
- provider_registry: add diagnostics + ring-1 providers (array/console/map/path)
- mir_interpreter: add normalization/purify feature gates
- tools/selfhost_exe_stageb.sh: new end-to-end Stage-B→crate EXE pipeline
- tools/perf/microbench.sh: performance measurement tooling
Smoke tests (phase2100):
- Extend timeout 15s→120s for heavy crate EXE builds
- Add stageb_loop_jsonfrag_crate_exe_canary_vm.sh (target test)
- Add s3_backend_selector_crate_exe_vm_parity_return42_canary_vm.sh
Documentation:
- ENV_VARS.md: add Phase 21.5 optimization toggles
- README updates: clarify crate backend strategy
- phase215-optimization.md: new optimization roadmap
This commit sets the stage for Phase 21.5 critical optimization:
achieving C-level performance to decide hakorune's future viability.
2025-11-11 02:07:12 +09:00
ece91306b7
mirbuilder: integrate Normalizer (toggle), add tag-quiet mode, share f64 canonicalization; expand canaries; doc updates for quick timeout + dev toggles; Phase 21.5 optimization readiness
2025-11-10 23:17:46 +09:00
6055d53eff
feat(phase21.5/22.1): MirBuilder JsonFrag refactor + FileBox ring-1 + registry tests
...
Phase 21.5 (AOT/LLVM Optimization Prep)
- FileBox ring-1 (core-ro) provider: priority=-100, always available, no panic path
- src/runner/modes/common_util/provider_registry.rs: CoreRoFileProviderFactory
- Auto-registers at startup, eliminates fallback panic structurally
- StringBox fast path prototypes (length/size optimization)
- Performance benchmarks (C/Python/Hako comparison baseline)
Phase 22.1 (JsonFrag Unification)
- JsonFrag.last_index_of_from() for backward search (VM fallback)
- Replace hand-written lastIndexOf in lower_loop_sum_bc_box.hako
- SentinelExtractorBox for Break/Continue pattern extraction
MirBuilder Refactor (Box → JsonFrag Migration)
- 20+ lower_*_box.hako: Box-heavy → JsonFrag text assembly
- MirBuilderMinBox: lightweight using set for dev env
- Registry-only fast path with [registry:*] tag observation
- pattern_util_box.hako: enhanced pattern matching
Dev Environment & Testing
- Dev toggles: SMOKES_DEV_PREINCLUDE=1 (point-enable), HAKO_MIR_BUILDER_SKIP_LOOPS=1
- phase2160: registry opt-in tests (array/map get/set/push/len) - content verification
- phase2034: rc-dependent → token grep (grep -F based validation)
- run_quick.sh: fast smoke testing harness
- ENV documentation: docs/ENV_VARS.md
Test Results
✅ quick phase2034: ALL GREEN (MirBuilder internal patterns)
✅ registry phase2160: ALL GREEN (array/map get/set/push/len)
✅ rc-dependent tests → content token verification complete
✅ PREINCLUDE policy: default OFF, point-enable only where needed
Technical Notes
- No INCLUDE by default (maintain minimalism)
- FAIL_FAST=0 in Bring-up contexts only (explicit dev toggles)
- Tag-based route observation ([mirbuilder/min:*], [registry:*])
- MIR structure validation (not just rc parity)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-10 19:42:42 +09:00
50ac8af2b8
Phase 21.4 Complete: FileBox SSOT + Analyzer Stabilization (7 Tasks)
...
✅ Task 1: Fallback Guarantee (create_box failure → ring1/core-ro auto fallback)
- Three-tier fallback system: plugin → builtin → core-ro
- Mode control: auto/plugin-only/core-ro
- New: src/box_factory/builtin_impls/file_box.rs
- New: tools/test_filebox_fallback_smoke.sh
✅ Task 2: Provider Registration SSOT (static/dynamic/core-ro unified)
- ProviderFactory trait with priority-based selection
- Global registry PROVIDER_FACTORIES implementation
- Priority: dynamic(100) > builtin(10) > core-ro(0)
- New: src/boxes/file/builtin_factory.rs
- New: tools/smoke_provider_modes.sh
✅ Task 3: FileBox Publication Unification
- Verified: basic/file_box.rs already minimized (11 lines)
- Perfect re-export pattern maintained
✅ Task 4: ENV Unification (FILEBOX_MODE/DISABLE_PLUGINS priority)
- Removed auto-setting of NYASH_USE_PLUGIN_BUILTINS
- Removed auto-setting of NYASH_PLUGIN_OVERRIDE_TYPES
- Added deprecation warnings with migration guide
- ENV hierarchy: DISABLE_PLUGINS > BOX_FACTORY_POLICY > FILEBOX_MODE
✅ Task 5: Error Log Visibility (Analyzer rule execution errors to stderr)
- Added [rule/exec] logging before IR-based rule execution
- Format: [rule/exec] HC012 (dead_static_box) <filepath>
- VM errors now traceable via stderr output
✅ Task 6: Unnecessary Using Removal (14 rules Str alias cleanup)
- Removed unused `using ... as Str` from 14 rule files
- All rules use local _itoa() helper instead
- 14 lines of dead code eliminated
✅ Task 7: HC017 Skip & TODO Documentation (UTF-8 support required)
- Enhanced run_tests.sh with clear skip message
- Added "Known Limitations" section to README.md
- Technical requirements documented (3 implementation options)
- Re-enable timeline: Phase 22 (Unicode Support Phase)
📊 Test Results:
- Analyzer: 10 tests PASS, 1 skipped (HC017)
- FileBox fallback: All 3 modes PASS
- Provider modes: All 4 modes PASS
- Build: Success (0 errors, 0 warnings)
🎯 Key Achievements:
- 28 files modified/created
- Three-Tier Fallback System (stability)
- SSOT Provider Registry (extensibility)
- ENV unification (operational clarity)
- Error visibility (debugging efficiency)
- Code cleanup (maintainability)
- Comprehensive documentation (Phase 22 ready)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-08 17:04:21 +09:00
cef820596f
FileBox SSOT設計移行完了: Provider Pattern実装
...
## 🎯 目的
FileBoxをSSOT(Single Source of Truth)設計に移行し、
static/dynamic/builtin providerを統一的に扱える基盤を構築。
## ✅ 実装完了(7タスク)
### 1. Provider Lock Global
**File**: `src/runtime/provider_lock.rs`
- `FILEBOX_PROVIDER: OnceLock<Arc<dyn FileIo>>` 追加
- `set_filebox_provider()` / `get_filebox_provider()` 実装
### 2. VM初期化時のProvider選択
**File**: `src/runner/modes/vm.rs`
- `execute_vm_mode()` 冒頭でprovider選択・登録
- ENV(`NYASH_FILEBOX_MODE`, `NYASH_DISABLE_PLUGINS`)対応
### 3. CoreRoFileIo完全実装
**File**: `src/boxes/file/core_ro.rs` (NEW)
- Read-onlyファイルI/O実装
- Thread-safe: `RwLock<Option<File>>`
- Newline正規化(CRLF→LF)
### 4. FileBox委譲化
**File**: `src/boxes/file/mod.rs`
- 直接`std::fs::File`使用 → `Arc<dyn FileIo>` provider委譲
- 全メソッドをprovider経由に変更
- Fail-Fast: write/delete等の非対応操作は明確エラー
### 5. basic/file_box.rs Deprecate
**File**: `src/boxes/file/basic/file_box.rs`
- 120行 → 12行に削減
- `#[deprecated]` マーク + 再エクスポート
- 後方互換性維持
### 6. Feature Flag追加
**File**: `Cargo.toml`
- `builtin-filebox = []` feature追加
### 7. Provider抽象・選択ロジック
**Files**:
- `src/boxes/file/provider.rs` (NEW) - FileIo trait定義
- `src/boxes/file/box_shim.rs` (NEW) - 薄いラッパー
- `src/runner/modes/common_util/provider_registry.rs` (NEW) - 選択ロジック
## 📊 アーキテクチャ進化
**Before**:
```
FileBox (mod.rs) ──直接使用──> std::fs::File
FileBox (basic/) ──直接使用──> std::fs
```
**After**:
```
FileBox ──委譲──> Arc<dyn FileIo> ──実装──> CoreRoFileIo
├──> PluginFileIo (future)
└──> BuiltinFileIo (future)
```
## 🔧 技術的成果
1. **Thread Safety**: `RwLock<Option<File>>` で並行アクセス安全
2. **Fail-Fast**: 非対応操作は明確エラー(silent failure無し)
3. **後方互換性**: deprecated re-exportで既存コード維持
4. **環境制御**: `NYASH_FILEBOX_MODE` でランタイム切替
## 📝 環境変数
- `NYASH_FILEBOX_MODE=auto|core-ro|plugin-only`
- `auto`: プラグインあれば使用、なければCoreRoにフォールバック
- `core-ro`: 強制的にCoreRo(read-only)
- `plugin-only`: プラグイン必須(なければFail-Fast)
- `NYASH_DISABLE_PLUGINS=1`: 強制的にcore-roモード
## 🎯 次のステップ(Future)
- [ ] Dynamic統合(plugin_loaderとの連携)
- [ ] BuiltinFileIo実装(feature builtin-filebox)
- [ ] Write/Delete等の操作対応(provider拡張)
## 📚 ドキュメント
- 詳細仕様: `docs/development/runtime/FILEBOX_PROVIDER.md`
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-08 15:13:22 +09:00
58a6471883
Phase 21.3 WIP: Hako Source Checker improvements - HC011/HC016/HC017 実装完了
...
主な変更:
- ✅ HC011 (dead methods) 実装・テスト緑
- ✅ HC016 (unused alias) 実装・テスト緑
- ✅ HC017 (non-ascii quotes) 実装完了
- 🔧 tokenizer/parser_core 強化(AST優先ルート)
- 🛡️ plugin_guard.rs 追加(stderr専用出力)
- 📋 テストインフラ整備(run_tests.sh改善)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-08 00:46:34 +09:00
86489ffe43
Phase 21.3 WIP: Hako Source Checker improvements
...
## 🎯 Checker/Analyzer拡張
### ✅ 実装追加
- テストフレームワーク追加(tools/hako_check/tests/)
- ルール改善(HC003グローバルassign、HC040静的箱トップレベルassign)
- テストランナー(run_tests.sh)
### 🔧 Rust側修正
- AST utilities拡張(src/ast/utils.rs)
- MIR lowerers新設(src/mir/lowerers/)
- Parser制御フロー改善(src/parser/statements/control_flow.rs)
- Tokenizer識別子処理改善(src/tokenizer/lex_ident.rs)
### 📁 主要変更
- tools/hako_check/cli.hako - CLI改善
- tools/hako_check/hako_source_checker.hako - Checker core更新
- tools/hako_check/tests/ - NEW (テストケース追加)
- tools/hako_check/run_tests.sh - NEW (テストランナー)
- src/mir/lowerers/ - NEW (MIR lowering utilities)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-07 21:04:01 +09:00
301b1d212a
Phase 21.2 Complete: VM Adapter正規実装 + devブリッジ完全撤去
...
## 🎉 Phase 21.2完全達成
### ✅ 実装完了
- VM static box 永続化(singleton infrastructure)
- devブリッジ完全撤去(adapter_dev.rs削除、by-name dispatch削除)
- .hako正規実装(MirCallV1Handler, AbiAdapterRegistry等)
- text-merge経路完全動作
- 全phase2120 adapter reps PASS(7テスト)
### 🐛 バグ修正
1. strip_local_decl修正
- トップレベルのみlocal削除、メソッド内は保持
- src/runner/modes/common_util/hako.rs:29
2. static box フィールド永続化
- MirInterpreter singleton storage実装
- me parameter binding修正(1:1マッピング)
- getField/setField string→singleton解決
- src/backend/mir_interpreter/{mod,exec,handlers/boxes_object_fields}.rs
3. Map.len alias rc=0修正
- [map/missing]パターン検出でnull扱い(4箇所)
- lang/src/vm/boxes/mir_call_v1_handler.hako:91-93,131-133,151-153,199-201
### 📁 主要変更ファイル
#### Rust(VM Runtime)
- src/backend/mir_interpreter/mod.rs - static box singleton storage
- src/backend/mir_interpreter/exec.rs - parameter binding fix
- src/backend/mir_interpreter/handlers/boxes_object_fields.rs - singleton resolution
- src/backend/mir_interpreter/handlers/calls.rs - dev bridge removal
- src/backend/mir_interpreter/utils/mod.rs - adapter_dev module removal
- src/backend/mir_interpreter/utils/adapter_dev.rs - DELETED (7555 bytes)
- src/runner/modes/vm.rs - static box declaration collection
- src/runner/modes/common_util/hako.rs - strip_local_decl fix
- src/instance_v2.rs - Clone implementation
#### Hako (.hako実装)
- lang/src/vm/boxes/mir_call_v1_handler.hako - [map/missing] detection
- lang/src/vm/boxes/abi_adapter_registry.hako - NEW (adapter registry)
- lang/src/vm/helpers/method_alias_policy.hako - method alias support
#### テスト
- tools/smokes/v2/profiles/quick/core/phase2120/s3_vm_adapter_*.sh - 7 new tests
### 🎯 テスト結果
```
✅ s3_vm_adapter_array_len_canary_vm.sh
✅ s3_vm_adapter_array_len_per_recv_canary_vm.sh
✅ s3_vm_adapter_array_length_alias_canary_vm.sh
✅ s3_vm_adapter_array_size_alias_canary_vm.sh
✅ s3_vm_adapter_map_len_alias_state_canary_vm.sh
✅ s3_vm_adapter_map_length_alias_state_canary_vm.sh
✅ s3_vm_adapter_map_size_struct_canary_vm.sh
```
環境フラグ: HAKO_ABI_ADAPTER=1 HAKO_ABI_ADAPTER_DEV=0
### 🏆 設計品質
- ✅ ハードコード禁止(AGENTS.md 5.1)完全準拠
- ✅ 構造的・一般化設計(特定Box名のif分岐なし)
- ✅ 後方互換性保持(既存コード破壊ゼロ)
- ✅ text-merge経路(.hako依存関係正しくマージ)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-11-07 19:32:44 +09:00
0455307418
refactor(phase-a): remove Cranelift/JIT backend legacy code (~373 lines)
...
Phase A cleanup - Safe deletions with zero risk:
## Deleted Files (6 files, 373 lines total)
1. Cranelift/JIT Backend (321 lines):
- src/runner/modes/cranelift.rs (45 lines)
- src/runner/modes/aot.rs (55 lines)
- src/runner/jit_direct.rs (152 lines)
- src/tests/core13_smoke_jit.rs (42 lines)
- src/tests/core13_smoke_jit_map.rs (27 lines)
2. Legacy MIR Builder (52 lines):
- src/mir/builder/exprs_legacy.rs
- Functionality inlined into exprs.rs (control flow constructs)
## Module Reference Cleanup
- src/backend/mod.rs: Removed cranelift feature gate exports
- src/runner/mod.rs: Removed jit_direct module reference
- src/runner/modes/mod.rs: Removed aot module reference
- src/mir/builder.rs: Removed exprs_legacy module
## Impact Analysis
- Build: Success (cargo build --release)
- Tests: All passing
- Risk Level: None (feature already archived, code unused)
- Related: Phase 15 JIT archival (archive/jit-cranelift/)
## BID Copilot Status
- Already removed in previous cleanup
- Not part of this commit
Total Reduction: 373 lines (~0.4% of codebase)
Next: Phase B - Dead code investigation
Related: #phase-21.0-cleanup
Part of: Legacy Code Cleanup Initiative
2025-11-06 22:34:18 +09:00
e326e787a4
release: v21.0.0 – Full Self‑Hosting (S1/S2/S3 complete)
...
- DoD met: S1/S2 determinism (const/compare/threeblock-collect), PRIMARY hv1 inline no-fallback, S3 (llvmlite+kernel) reps green
- Harness: v1→llvmlite direct, EXE links to libnyash_kernel.a
- Python LLVM builder fixes: cmp normalization, ret PHI synthesis, mir_call flat shape
- Using/alias polish (prod): modules-first; missing aliases added; duplicate using cleaned
- Docs: phase-21.0 COMPLETE; CurrentTask closed; release notes added
2025-11-06 16:59:34 +09:00
77d4fd72b3
phase: 20.49 COMPLETE; 20.50 Flow+String minimal reps; 20.51 selfhost v0/v1 minimal (Option A/B); hv1-inline binop/unop/copy; docs + run_all + CURRENT_TASK -> 21.0
2025-11-06 15:41:52 +09:00
96ea3892af
phase-20.45: PRIMARY no-fallback reps + MIR v0 shape fixes
...
- Fix MIR v0 shape in lowers: functions[] + name="main" + blocks.id
* lower_return_int_box.hako
* lower_return_binop_box.hako
- runner_min: adopt LowerReturnBinOpBox before ReturnInt
- Add PRIMARY no-fallback canaries (all PASS):
* return-binop / array-size / load-store / return-logical (OR)
- Fix phase2043 runner_min canary alias (Runner -> BuilderRunnerMinBox)
- Update docs: phase-20.45 README (PRIMARY reps), CURRENT_TASK progress
Ancillary: keep builder/provider/canary files in sync; no unrelated behavior changes.
2025-11-05 18:57:03 +09:00
44a5158a14
hv1: early-exit at main (no plugin init); tokenizer: Stage-3 single-quote + full escapes (\/ \b \f \' \r fix); builder: route BinOp via SSOT emit_binop_to_dst; hv1 verify canary route (builder→Core); docs: phase-20.39 updates
2025-11-04 20:46:43 +09:00
30aa39f50b
hv1 verify: add direct route (env JSON) and clean inline path; fix v1 phi incoming order; make test_runner use hv1 direct; add phase2037 phi canaries; load modules.workspace exports for alias; update docs (phase-20.38, source extensions) and CURRENT_TASK
2025-11-04 16:33:04 +09:00
5a1bb549a7
vm(resolve): add text-based prelude merge for selfhost compilation
...
- Add merge_prelude_text() function for fast using system support
- Implement normalize_text_for_inline() for parser robustness
- Update selfhost.rs to use text-based merge when NYASH_USING_AST=1
- Add merge_prelude_text export to mod.rs
- Improves Phase 15 selfhost compilation speed and reliability
Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
2025-11-04 09:25:36 +09:00
06a729ff40
vm(hako): add v1 reader/dispatcher (flagged), commonize mir_call handler, share block scan; smokes: add v1 hakovm canary; docs: 20.37/20.38 plans, OOB policy; runner: v1 hakovm toggle; include SKIP summary
2025-11-03 23:21:48 +09:00