1a8a70cc99
refactor(joinir): Phase 286C-2.1 - 3-stage pipeline scaffolding (Scan/Plan/Apply)
...
- Create 3-stage pipeline architecture to solve borrow checker conflicts
- Stage 1 (ScanBox): Read-only scanning, identify rewrites (170 lines)
- Stage 2 (PlanBox): Pure transformation, generate new blocks (85 lines)
- Stage 3 (ApplyBox): Builder mutation only (75 lines)
New Files:
- scan_box.rs: Stage 1 - Read-only scan for RewritePlan
- plan_box.rs: Stage 2 - Transform RewritePlan → RewrittenBlocks
- apply_box.rs: Stage 3 - Apply RewrittenBlocks to MirBuilder
- C-2.1-pipeline-refactoring.md: Implementation guide
Data Structures:
- RewritePlan: Describes WHAT to rewrite (tail calls, returns, PHI, params)
- RewrittenBlocks: Contains HOW to rewrite (new blocks, replacements, inputs)
Benefits:
- Borrow checker safety: No overlapping mutable/immutable borrows
- Single responsibility: Each stage has one clear purpose
- Testability: Each stage can be unit tested independently
- Maintainability: Clear data flow, isolated changes
Status:
- Scaffolding: ✅ Complete (structure defined, stub implementations)
- Integration: ⏳ Next step (refactor merge_and_rewrite to use 3 stages)
Build: cargo build --release ✅
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-25 03:05:44 +09:00
d81937e744
refactor(joinir): Phase 286C-2 - RewriteContext state consolidation
...
- Create RewriteContext struct to consolidate 11 scattered state variables
- Add 4 helper Boxes: InstructionFilterBox, ParameterBindingBox, ReturnConverterBox, TailCallDetectorBox
- Reduce instruction_rewriter.rs cognitive overhead via centralized state API
- All state mutations now go through consistent RewriteContext methods
Changes:
- New: rewrite_context.rs (94 lines) - State consolidation SSOT
- New: 4 helper Box modules (instruction_filter, parameter_binding, return_converter, tail_call_detector)
- Modified: instruction_rewriter.rs (1454 → 1421 lines)
- Modified: rewriter/mod.rs (export RewriteContext)
Benefits:
- State tracking simplified (11 variables → 1 context object)
- Clearer intent via API methods (add_exit_phi_input vs push)
- Foundation for future refactoring (Phase 286C-2.1: 3-stage pipeline)
- Zero functionality changes (pure refactoring)
Build: cargo build --release ✅
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-25 02:58:36 +09:00
843d094598
refactor(joinir): Phase 286 P1-P3 - Boundary contract context enrichment
...
- P1: Add alloc_join_param()/alloc_join_local() API to JoinValueSpace
- Prevents future API misuse (thin wrappers with explicit "JoinIR" context)
- Updated docs with footnote-style number references
- P2: Enrich error context with host_fn for better diagnostics
- Added context: &str parameter to verify_boundary_contract_at_creation()
- Error format now shows: [merge_joinir_mir_blocks host=<fn> ...]
- P3: Add join-side info to error context (continuation count + boundary summary)
- Uses boundary.continuation_func_ids.len() for join=
- Adds [conts=X exits=Y conds=Z] suffix with fixed key names
- Enables faster debugging with log-searchable format
Error format: [merge_joinir_mir_blocks host=X join=Y [conts=A exits=B conds=C]]
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude <noreply@anthropic.com >
2025-12-25 02:15:40 +09:00
ab76e39036
feat(parser): Phase 285A1.4 & A1.5 - Weak field sugar + Parser hang fix
...
A1.4: Add sugar syntax `public weak parent` ≡ `public { weak parent }`
A1.5: Fix parser hang on unsupported `param: Type` syntax
Key changes:
- A1.4: Extend visibility parser to handle weak modifier (fields.rs)
- A1.5: Shared helper `parse_param_name_list()` with progress-zero detection
- A1.5: Fix 6 vulnerable parameter parsing loops (methods, constructors, functions)
- Tests: Sugar syntax (OK/NG), parser hang (timeout-based)
- Docs: lifecycle.md, EBNF.md, phase-285a1-boxification.md
Additional changes:
- weak() builtin implementation (handlers/weak.rs)
- Leak tracking improvements (leak_tracker.rs)
- Documentation updates (lifecycle, types, memory-finalization, etc.)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-24 07:44:50 +09:00
dac57ec350
refactor(cleanup): Large-scale dead code elimination (Task 5)
...
Removed 966 lines of dead code identified by Rust compiler warnings.
4 files completely deleted, multiple pattern implementations cleaned up.
**Files Completely Deleted (4)**:
- src/mir/builder/control_flow/joinir/api/entry.rs (15 lines)
- src/mir/builder/control_flow/joinir/api/pipeline_contracts.rs (17 lines)
- src/mir/builder/control_flow/joinir/api/receiver.rs (21 lines)
- src/mir/builder/control_flow/joinir/patterns/pattern2_steps/promote_step_box.rs (33 lines)
**Pattern 7 (SplitScan) - 423 lines deleted**:
- Removed: can_lower(), lower(), cf_loop_pattern7_split_scan_impl()
- Removed helper functions: contains_methodcall(), contains_variable_step(), contains_push()
- Removed test code
- Kept: extract_split_scan_plan() (used by router.rs)
**Pattern 8 (BoolPredicate) - 222 lines deleted**:
- Removed: cf_loop_pattern8_bool_predicate_impl() (impl MirBuilder block)
- Kept: can_lower(), lower() (used by router.rs)
**Pattern 5 (InfiniteEarlyExit) - 95 lines deleted**:
- Removed: count_breaks_and_continues(), validate_continue_position(), validate_break_pattern()
**Pattern 6 (ScanWithInit) - 110 lines deleted**:
- Removed: contains_methodcall(), is_const_step_pattern()
- Removed 4 test functions
**JoinIR API - 53 lines deleted**:
- Removed module: api/entry.rs
- Removed module: api/pipeline_contracts.rs
- Removed module: api/receiver.rs
**EdgeCFG API - 30 lines deleted**:
- EdgeStub: Removed new(), with_target() methods
**Statistics**:
- Total lines deleted: 966
- Files deleted: 4
- Dead code warnings eliminated: Multiple pattern implementations
Build Status: ✅ Release build successful (0 errors)
🤖 Generated with Claude Code
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-24 04:49:52 +09:00
2da730de35
refactor(cleanup): Phase 285A1 Post-Implementation Cleanup
...
Code quality improvements after Phase 285A1 implementation:
**Task 1: Dead Code Cleanup**
- Removed unnecessary #[allow(dead_code)] from emit_weak_load()
- Function is actively used in weak_to_strong() method handler
**Task 2: Unused Import Removal (cargo fix)**
- edgecfg/api/mod.rs: Removed seq, if_, loop_, cleanup, verify_frag_invariants
- pattern3.rs: Removed BinaryOperator
- pattern2/api/mod.rs: Removed PromoteStepResult
- jump.rs: Removed EffectMask, Span
- Result: 6 unused imports eliminated
**Task 3: Deprecated Pattern Removal**
- Fixed 4 PlanKind::LoopWithPost deprecated warnings
- Updated to Phase 142 P0 architecture (statement-level normalization)
- Files: normalized_shadow_suffix_router_box.rs, routing.rs,
execute_box.rs, plan.rs
- Removed 2 deprecated tests: test_loop_with_post_*
**Task 4: WeakFieldValidatorBox Boxification**
- Extracted weak field validation logic into dedicated Box
- New file: src/mir/builder/weak_field_validator.rs (147 lines)
- fields.rs: 277 → 237 lines (-40 lines, -14.4%)
- Added 5 unit tests for validation logic
- Follows Phase 33 boxification principles (single responsibility,
testability, reusability)
**Metrics**:
- Code reduction: -40 lines in fields.rs
- Test coverage: +5 unit tests
- Warnings fixed: 4 deprecated warnings
- Imports cleaned: 6 unused imports
🤖 Generated with Claude Code
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-24 03:44:56 +09:00
b0eeb14c54
refactor(phase284): P1 SSOT Consolidation - Block Remapper & Return Emitter
...
## Summary
Refactored Phase 284 P1 codebase to consolidate scattered logic into SSOT
(Single Source of Truth) modules, improving maintainability and enabling
Pattern4/5 code reuse.
## New Modules
### 1. Block Remapper SSOT
**File**: `src/mir/builder/control_flow/joinir/merge/block_remapper.rs` (152 lines)
- **Purpose**: Consolidate block ID remapping logic (Phase 284 P1 fix)
- **Function**: `remap_block_id(block_id, local_block_map, skipped_entry_redirects)`
- **Rule**: local_block_map priority > skipped_entry_redirects (prevents ID collision)
- **Tests**: 4 unit tests (priority cascade, collision handling, etc.)
### 2. Return Jump Emitter
**File**: `src/mir/join_ir/lowering/return_jump_emitter.rs` (354 lines)
- **Purpose**: Reusable return handling helper for Pattern4/5
- **Function**: `emit_return_conditional_jump(loop_step_func, return_info, k_return_id, ...)`
- **Scope**: P1 - unconditional return + conditional (loop_var == N) only
- **Tests**: 3 unit tests (unconditional, no return, conditional)
## Modified Files
**merge/instruction_rewriter.rs** (-15 lines):
- Replaced inline block remapping with `remap_block_id()` call
- Cleaner Branch remap logic
**merge/rewriter/terminator.rs** (-43 lines):
- Delegates remap_jump/remap_branch to block_remapper SSOT
- Simplified duplicate logic
**lowering/loop_with_continue_minimal.rs** (-108 lines):
- Replaced ~100 line return handling with `emit_return_conditional_jump()` call
- Extracted helper functions to return_jump_emitter.rs
- Line reduction: 57% decrease in function complexity
**merge/mod.rs, lowering/mod.rs**:
- Added new module exports (block_remapper, return_jump_emitter)
**phase-284/README.md**:
- Updated completion status (P1 Complete + Refactored)
- Added SSOT consolidation notes
- Documented module architecture
## Code Quality Improvements
| Metric | Before | After | Change |
|--------|--------|-------|--------|
| Duplicate block remap logic | 2 places | SSOT | -15 lines |
| Return handling code | inline (100L) | helper call | -99 lines |
| Testability | Limited | Unit tests (7) | +7 tests |
| Module cohesion | Low (scattered) | High (consolidated) | Better |
## Testing
✅ Build: Success (cargo build --release)
✅ Smoke tests: All pass (46 PASS, 1 pre-existing FAIL)
✅ Regression: Zero
✅ Unit tests: 7 new tests added
## Future Benefits
1. **Pattern5 Reuse**: Direct use of `emit_return_conditional_jump()` helper
2. **Phase 285 (P2)**: Nested if/loop returns via same infrastructure
3. **Maintainability**: SSOT reduces debugging surface area
4. **Clarity**: Each module has single responsibility
## Architectural Notes
**Block Remapper SSOT Rule**:
```
remap_block_id(id, local_block_map, skipped_entry_redirects):
1. Check local_block_map (function-local priority)
2. Fall back to skipped_entry_redirects (global redirects)
3. Return original if not found
```
Prevents function-local block ID collisions with global remap entries.
**Return Emitter Pattern**:
```
emit_return_conditional_jump(func, return_info, k_return_id, alloc_value):
- Pattern1-5: All use same infrastructure
- P1 scope: top-level return only (nested if/loop → P2)
- Returns: JoinInst::Jump(cont=k_return, cond=Some(return_cond))
```
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com >
2025-12-23 14:37:01 +09:00
661bbe1ab7
feat(phase284): P1 Complete - Return in Loop with Block Remap Fix
...
## Summary
Completed Phase 284 P1: Enable return statements in Pattern4/5 loops via
JoinInst::Ret infrastructure (100% pre-existing, no new infrastructure needed).
**Critical Bug Fix**: Block ID remap priority
- Fixed: local_block_map must take precedence over skipped_entry_redirects
- Root cause: Function-local block IDs can collide with global remap entries
(example: loop_step:bb4 vs k_exit:bb4 after merge allocation)
- Impact: Conditional Jump else branches were incorrectly redirected to exit
- Solution: Check local_block_map FIRST, then skipped_entry_redirects
## Implementation
### New Files
- `src/mir/join_ir/lowering/return_collector.rs` - Return detection SSOT (top-level only, P1 scope)
- `apps/tests/phase284_p1_return_in_loop_min.hako` - Test fixture (exit code 7)
- Smoke test scripts (VM/LLVM)
### Modified Files
- `loop_with_continue_minimal.rs`: Return condition check + Jump generation
- `pattern4_with_continue.rs`: K_RETURN registration in continuation_funcs
- `canonical_names.rs`: K_RETURN constant
- `instruction_rewriter.rs`: Fixed Branch remap priority (P1 fix)
- `terminator.rs`: Fixed Jump/Branch remap priority (P1 fix)
- `conversion_pipeline.rs`: Return normalization support
## Testing
✅ VM: exit=7 PASS
✅ LLVM: exit=7 PASS
✅ Baseline: 46 PASS, 1 FAIL (pre-existing emit issue)
✅ Zero regression
## Design Notes
- JoinInst::Ret infrastructure was 100% complete before P1
- Bridge automatically converts JoinInst::Ret → MIR Return terminator
- Pattern4/5 now properly merge k_return as non-skippable continuation
- Correct semantics: true condition → return, false → continue loop
## Next Phase (P2+)
- Refactor: Block remap SSOT (block_remapper.rs)
- Refactor: Return jump emitter extraction
- Scope: Nested if/loop returns, multiple returns
- Design: Standardize early exit pattern (return/break/continue as Jump with cond)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com >
2025-12-23 14:21:27 +09:00
41d92bedb9
refactor(extractors): Phase 282 P9a - CommonExtractionHelpers SSOT統合(スコープ限定版)
...
# Phase 282 P9a 完了 (Scope-Limited Integration)
## 実装内容
- **common_helpers.rs 作成**: 4グループの共通ヘルパー統合 (316行)
- Group 1: Control Flow Counting (count_control_flow - 汎用カウンター)
- Group 2: Control Flow Detection (has_break/continue/return_statement)
- Group 3: Condition Validation (extract_loop_variable, is_true_literal)
- Group 4: Pattern5専用ヘルパー (validate_continue_at_end, validate_break_in_simple_if)
- **Pattern統合完了**: Pattern5 → Pattern4 → Pattern2 → Pattern1
- Pattern5: ~90行削減 (5 tests PASS)
- Pattern4: ~66行削減 (5 tests PASS)
- Pattern2: ~67行削減 (4 tests PASS)
- Pattern1: ~28行削減 (3 tests PASS)
- Pattern3: 別フェーズに延期(pattern固有ロジック除外)
## 成果
- **コード削減**: ~251行(Pattern3除く、total ~400行見込み)
- **テスト**: 40 unit tests PASS (23 common_helpers + 17 extractors)
- **スモークテスト**: 45 PASS, 1 pre-existing FAIL(退行ゼロ)
- **ビルド警告**: 130 → 120 (-10)
## USER CORRECTIONS適用済み
1. ✅ スコープ限定(共通ロジックのみ、pattern固有除外)
2. ✅ Placeholder禁止(SSOT違反排除)
3. ✅ 統合順序変更(Pattern3を最後/別フェーズへ)
## 追加ドキュメント
- Phase 284 計画追加(Return as ExitKind SSOT)
- 10-Now.md, 30-Backlog.md 更新
🎯 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-23 11:14:28 +09:00
bfbc9b26bf
fix(joinir): Phase 283 P0 - Pattern3 Undefined ValueId Bug Fix
...
- Fix: extract_if_condition() moved after local_cond_env construction
(loop_with_if_phi_if_sum.rs:175)
- Root cause: condition extraction before i_param/sum_param creation
- Result: i % 2 referenced caller's ConditionEnv with unmapped ValueId
- Fail-Fast: Add condition_bindings validation in merge (mod.rs)
- Fixture: Update loop_if_phi.hako for C2 compatibility (sum.toString())
- Verified: VM execution outputs sum=9 ✅
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-23 08:14:27 +09:00
32ccccd272
feat(plan): Phase 282 P5 - Pattern3 ExtractionBased Migration & Classification
...
- Pattern3 extraction logic separated to extractors/pattern3.rs
- ExtractionBased strategy: pure functions, Fail-Fast, SSOT
- Pattern classification restored (AST-based pattern detection)
- Pattern1 extractor migrated (extractors/pattern1.rs)
- Documentation: phase-282 README updated, joinir-architecture updated
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-23 08:13:47 +09:00
c3fb3c5833
feat(joinir): Phase 282 P4 - Pattern2 ExtractionBased Migration
...
## Summary
Migrated Pattern2 (Loop with Conditional Break) from StructureBased to ExtractionBased detection following Pattern1 template (P3). Safety valve + extraction SSOT strategy with zero regression.
## Implementation
- **extractors/pattern2.rs**: 4-phase validation (condition, HAS break, NO continue/return, extraction)
- **pattern2_with_break.rs**: Updated can_lower() (safety valve + extraction) and lower() (re-extraction + ctx.skeleton)
- **extractors/mod.rs**: Registered pattern2 module
## Key Design Decisions
- **Lightweight Parts**: loop_var (String), is_loop_true (bool), break_count (usize) - no AST duplication
- **4-Phase Validation**: Lightweight checks only (condition, break presence, continue/return absence, extraction)
- **Hybrid loop(true) Handling**: Quick detection in extractor, deep validation in can_lower() via LoopTrueCounterExtractorBox
- **SSOT Carrier Validation**: Deferred to CommonPatternInitializer in can_lower() (Step 4)
- **ctx.skeleton Usage**: Re-uses existing ctx.skeleton instead of new env var (避けenv増殖)
## Testing Results
- ✅ Unit tests: 4/4 PASS (extractors::pattern2)
- ✅ Build: 0 errors
- ✅ Regression: 46/49 PASS (zero regression, 1 unrelated pre-existing failure)
- ⚠️ Pattern2 smoke test: Pre-existing PHI bug confirmed (not a regression)
## Migration Template
This implementation provides a template for Pattern3-5 ExtractionBased migration:
1. Lightweight Parts structure (validation results only)
2. 4-phase extraction validation
3. Safety valve (pattern_kind) + extraction (SSOT)
4. Re-extraction in lower() (no caching)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-23 06:49:49 +09:00
8d0808b6d4
feat(joinir): Phase 282 P3 - Pattern1 ExtractionBased Migration
...
Migrated Pattern1 (Simple While Loop) from StructureBased to ExtractionBased
detection, creating a migration template for Pattern2-5.
**Changes**:
1. Created extractors/mod.rs - Module entry point with design principles
2. Created extractors/pattern1.rs - Pure extraction functions with 4-phase validation
3. Updated pattern1_minimal.rs - can_lower() + lower() use extraction
4. Updated mod.rs - Registered extractors module
**Pattern1Parts Design** (Lightweight):
- Stores only loop_var (AST reused from ctx, no heavy copies)
- Validation: 比較条件 + no break/continue/if-else + 単純step (i = i ± const)
- Return statements allowed (not loop control flow)
**4-Phase Validation**:
1. Validate condition structure (比較演算, left=variable)
2. Validate body (no break/continue/if-else-phi)
3. Validate step pattern (simple i = i ± const only)
4. Extract loop variable
**Safety Valve Strategy**:
- pattern_kind as O(1) early rejection guard
- Extraction as SSOT authoritative check
- Re-extraction in lower() (no caching from can_lower)
**Testing**:
- Unit tests: 3/3 PASS
- Build: 0 errors
- Regression: 45/46 PASS (zero regression)
**Migration Template**:
- Result<Option<Parts>, String> return type (Pattern8/9 model)
- Pure functions (no builder mutations)
- Fail-Fast error handling (Err for logic bugs, Ok(None) for non-matches)
🎉 Generated with Claude Code (https://claude.com/claude-code )
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-23 06:09:57 +09:00
a2be79b875
docs(router): Phase 282 P2 - Comment archaeology + TODO cleanup
...
Step 2: Router comment updates
- Update Phase references (183, 273, 282 retained)
- Document ExtractionBased status (Pattern8/9 already done)
- Remove obsolete Phase references (187, 193, 195)
Step 3: TODO cleanup
- pattern5: Remove completed TODO (lowering fully implemented)
- pattern_pipeline: Clarify loop_update_summary status (reserved)
- apply_policy: Mark current_static_box_name as low-priority refactor
Step 4: Pattern3 legacy references
- Simplify module docstring (remove legacy mode details)
- Update inline comments (legacy removal Phase 242-EX-A)
Changes: Comment/docstring only (zero behavior change)
Test: cargo build --release (0 errors)
2025-12-23 05:35:42 +09:00
519e58a977
docs(router): Phase 282 P0+P1 - Router shrinkage SSOT + entrypoint logging
...
P0: Documentation SSOT (~80 lines added)
- Router Responsibilities SSOT (DOES/DOESN'T split)
- Ok(None)/Err boundary rules (Fail-Fast principle)
- Entrypoint table (Plan/JoinIR/None, 収束先明記)
- Pattern番号 = 症状ラベル定義(最小記述)
P1: Minimal Code (~10 lines)
- 4 trace statements modified (router.rs)
- Entrypoint-based logging (route=plan/joinir/none)
- Pattern names preserved (backward compatible)
- No new environment variables (既存trace機構のみ)
Test Results:
- quick profile: 45 PASS / 1 FAIL (既知failure)
- Pattern6 VM: PASS (phase258_p0_index_of_string_vm.sh)
- Pattern6 LLVM: PASS (phase258_p0_index_of_string_llvm_exe.sh)
- Zero regression ✅
Phase 282 Goal Achieved:
- Router shrinkage complete (SSOT positioning clear)
- Pattern numbers → symptom labels transition documented
- CFG construction converges to emit_frag() SSOT
2025-12-23 05:03:25 +09:00
a744be929a
feat(edgecfg): Phase 281 P3 - cleanup Normal wiring + docs
2025-12-23 04:11:02 +09:00
2d5607930c
docs(edgecfg): Phase 280 - Frag Composition SSOT Positioning (A→B→C)
...
## Purpose
Stop pattern number enumeration proliferation by establishing Frag composition API
as the Single Source of Truth (SSOT) for structured control flow → CFG lowering.
Pattern numbers (1-9+) are **symptom labels** for regression tests, NOT architectural
concepts. The architectural SSOT is **Frag composition rules** (seq/if/loop/cleanup).
## Changes Summary
**Phase A (Docs-only, no code)**: SSOT Positioning
- edgecfg-fragments.md: Status Draft → Active SSOT (+243 lines)
- Added 5 sections: Composition SSOT, Rules, Laws, Fail-Fast, Ownership
- Documented 3-tier ownership model (Normalizer/Composition/Lowerer)
- Established composition as pattern absorption destination
- joinir-architecture-overview.md: Pattern absorption documentation (+90 lines)
- Added Section 0.2: Pattern Number Absorption Destination
- JoinIR vs Plan comparison (different extraction, same SSOT)
- Pattern absorption status table (Pattern6/7 as Phase 280 targets)
- phase-280/README.md: Full roadmap (new)
**Phase B (API solidification)**: Contract Verification
- compose.rs: Module-level + function-level Phase 280 docs (+149 lines)
- Documented composition SSOT, ownership model, usage example
- Added constraint/composition law sections to seq/if/loop/cleanup
- Contract verification: All seq/if/loop contracts verified (no gaps)
- Test gap analysis: No missing tests (wires/exits separation explicitly tested)
**Phase C (Pattern preparation)**: Documentation-only
- normalizer.rs: Pattern6/7 TODO comments (+10 lines)
- Pattern6: Early exit doesn't fit compose::if_() → cleanup() target
- Pattern7: 挙動不変保証難 → compose::if_() migration deferred to Phase 281
## Impact
- **Net +460 lines** (docs-heavy, minimal code)
- **4 files modified**, 1 directory created
- **SSOT established**: Frag composition is now THE absorption destination
- **導線固定**: Clear migration path for Pattern6/7 (Phase 281+)
- **No behavior change**: Documentation-only for Phase C (tests not run)
## Phase 280 Goal Achieved
✅ SSOT positioning + 導線固定 (NOT full migration - that's Phase 281)
✅ Phase A complete: Docs updated to "Active SSOT"
✅ Phase B complete: API contract verified and documented
✅ Phase C complete: Pattern6/7 hand-rolled locations documented
## Next Phase (Phase 281+)
- Phase 281: Full Pattern6/7 absorption (replace hand-rolled with compose_*)
- Phase 282: Router shrinkage (pattern numbers → test labels)
- Phase 283+: Pattern8 and beyond
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-23 01:18:36 +09:00
6f1d0df187
docs(plan): Phase 273 P4 - Plan Line SSOT Documentation Finalization
...
Phase 273 P4 では、Plan ライン(Extractor → Normalizer → Verifier → Lowerer)を
"current operational SSOT" として文書化し、アーキテクチャの収束を明文化した。
## Changes
### router.rs docstring 更新
- "Phase 273 P3: Plan Line is Current SSOT for Pattern6/7" セクション追加
- ルーティング戦略を明示(Plan entry points → legacy table)
- SSOT Entry Points を列挙(Pattern6/7 Normalizer, Pattern1-5 各 Lowerer)
### phase-273/README.md 更新
- P3 completion section 追加(generalized CoreLoopPlan 移行完了)
- P3+ Legacy Removal section 追加(~174 lines 削除記録)
- P4 Proposal section 追加(Documentation Finalization チェックリスト)
- SSOT Documentation Entry Points リスト追加(5 つの SSOT 入口)
### joinir-architecture-overview.md 更新
- Section 2.1.2 "Plan-Based Patterns (Pattern6-7, Phase 273 P3)" 追加
- Plan Extractor, Normalizer, Verifier, Lowerer の Box 構造を文書化
- Plan line vs JoinIR line 比較表追加(収束性・SSOT 特性の対比)
- SSOT characteristics リスト追加(Normalizer SSOT, emit_frag SSOT 等)
## SSOT Entry Points(Phase 273 P3 完了時点)
1. **ルーティング**: `router.rs::route_loop_pattern()` - Pattern6/7 Plan entry points
2. **型定義**: `plan/mod.rs` - DomainPlan/CorePlan 固定語彙
3. **正規化**: `plan/normalizer.rs` - Pattern 固有知識一元管理
4. **検証**: `plan/verifier.rs` - fail-fast 不変条件(V2-V9)
5. **降格**: `plan/lowerer.rs` - Pattern-agnostic MIR emission
## Test
- ✅ VM regression: phase254_p0_index_of_vm.sh (PASS)
- ✅ LLVM regression: phase258_p0_index_of_string_llvm_exe.sh (PASS)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-23 00:34:38 +09:00
1b7fd7a0ff
refactor(plan): Phase 273 P3+ - Legacy code removal
...
Phase 273 P3+ 完成: レガシーコード削除 + 未使用 import 整理
Removed Legacy Items:
1. emit_scan_with_init_edgecfg() - Pattern6 固有の emission 関数
- File deleted: src/mir/builder/emission/loop_scan_with_init.rs (~144 lines)
- Replaced by: generalized Frag API (Phase 273 P2)
2. CoreCarrierInfo struct - Legacy carrier representation
- Removed from: src/mir/builder/control_flow/plan/mod.rs (~15 lines)
- Replaced by: CorePhiInfo (generalized PHI representation)
3. verify_carrier() function - CoreCarrierInfo validator
- Removed from: src/mir/builder/control_flow/plan/verifier.rs (~15 lines)
- Replaced by: generalized PHI verification (V7-V9)
Code Cleanup:
- cargo fix applied: unused imports removed (~30 files)
- Verifier invariants updated: V1→V2-V9 (carrier→PHI model)
- Module declaration cleanup in emission/mod.rs
Impact:
- Total lines removed: ~174 lines (net reduction)
- Pattern-agnostic architecture strengthened
- All legacy Pattern6 references eliminated
Tests:
- ✅ VM tests PASS (phase254/256/258)
- ✅ LLVM tests PASS (phase256/258)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com >
2025-12-23 00:11:20 +09:00
0664526d99
feat(plan): Phase 273 P3 - Plan Lowering SSOT Finalize
...
Phase 273 P3 完成: CoreLoopPlan SSOT 化、legacy fallback 撤去
Changes:
- CoreLoopPlan: Option<...> → 必須フィールド化(構造で "揺れ" を消す)
- block_effects, phis, frag, final_values が必須に
- legacy fields 削除 (header_effects, step_effects, carriers, loop_var_name)
- Lowerer: lower_loop_legacy() 撤去、generalized 経路のみ
- emit_scan_with_init_edgecfg() 参照が完全に消えた
- Normalizer: Pattern6/7 両方が generalized fields のみを使用
- Verifier: generalized 専用の不変条件追加 (V7-V9)
- V7: PHI non-empty
- V8: frag.entry == header_bb
- V9: block_effects contains header_bb
Acceptance Criteria:
- ✅ Lowerer から pattern 固有参照が消えている
- ✅ Pattern6/7 が generalized CoreLoopPlan を使用
- ✅ legacy fallback 撤去、欠落時は型エラー (Fail-Fast)
- ✅ VM テスト PASS (phase254/256/258)
- ✅ LLVM テスト PASS (phase256/258)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com >
2025-12-23 00:01:58 +09:00
e4b5a8e832
feat(plan): Phase 273 P2 Step 3-6 - Pattern7 (SplitScan) to Plan line
...
Migrate Pattern7 from legacy lowering to Plan architecture:
DomainPlan (mod.rs):
- Added SplitScan(SplitScanPlan) variant
- SplitScanPlan: s_var, sep_var, result_var, i_var, start_var
Extractor (pattern7_split_scan.rs):
- extract_split_scan_plan() returning DomainPlan
- Reuses existing extract_split_scan_parts()
Router (router.rs):
- Pattern7 now uses Plan line (Normalize→Verify→Lower)
- Removed from LOOP_PATTERNS table
Normalizer (normalizer.rs):
- normalize_split_scan() - 400+ lines migrated from impl
- 6 blocks: preheader/header/body/then/else/step/after
- 4 PHIs: header(2) + step(2) for i/start carriers
- Side effect: push with EffectMask::MUT
Bug fixes:
- Pattern6 extractor returns Ok(None) for non-match (allows fallback)
- Reverse scan filtered early in extractor (P1 scope)
Tests:
- phase256_p0_split_vm: PASS (exit=3)
- phase258_p0_index_of_string_vm: PASS (exit=6)
Lowerer no longer contains "split" - pattern-agnostic achieved!
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com >
2025-12-22 23:35:43 +09:00
d16800741f
feat(plan): Phase 273 P2 Step 1-2 - CoreLoopPlan generalization
...
Generalize CoreLoopPlan for Pattern7+ support:
New structures (mod.rs):
- CorePhiInfo: PHI info with block, dst, inputs, tag
- CoreLoopPlan new optional fields:
- block_effects: Vec<(BasicBlockId, Vec<CoreEffectPlan>)>
- phis: Vec<CorePhiInfo>
- frag: Frag (EdgeCFG)
- final_values: Vec<(String, ValueId)>
Normalizer (normalizer.rs):
- Pattern6 now populates all new fields
- Frag construction matches emit_scan_with_init_edgecfg
- SSOT ordering: preheader → header → body → step
Lowerer (lowerer.rs):
- lower_loop() dispatches to generalized or legacy path
- lower_loop_generalized(): emit blocks → PHI → emit_frag()
- lower_loop_legacy(): backward compatible fallback
Test: phase258_p0_index_of_string_vm PASS (exit=6)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com >
2025-12-22 23:18:51 +09:00
ec792983cc
feat(plan): Phase 273 P2 Step 0 - CoreEffectPlan side effect support
...
Prepare CoreEffectPlan::MethodCall for Pattern7 (split) support:
- dst: ValueId → Option<ValueId> (for void methods like push)
- effects: EffectMask field added (PURE+Io vs MUT)
Changes:
- plan/mod.rs: MethodCall struct updated
- plan/lowerer.rs: emit_effect() uses dst/effects from plan
- plan/normalizer.rs: MethodCall with explicit effects
- plan/verifier.rs: Handle Option<ValueId> dst
Test: phase258_p0_index_of_string_vm PASS (exit=6)
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com >
2025-12-22 23:07:49 +09:00
960241795d
feat(mir/llvm): Phase 273 P0-P1 DomainPlan→CorePlan + LLVM arg fix
...
Phase 273 P0-P1: Two-layer plan architecture
- DomainPlan: Pattern-specific knowledge (ScanWithInit)
- CorePlan: Fixed vocabulary (Seq, Loop, If, Effect, Exit)
- ValueId references only (String expressions forbidden)
- Pipeline: Extractor→Normalizer→Verifier→Lowerer
New plan/ module:
- mod.rs: Type definitions, SSOT spec
- normalizer.rs: DomainPlan→CorePlan + ID allocation
- verifier.rs: V1-V6 invariant checks (fail-fast)
- lowerer.rs: CorePlan→MIR (pattern-agnostic)
LLVM fix (ChatGPT):
- function_lower.py: Fix argument reference bug
- Phase 258 index_of_string now PASS on LLVM backend
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com >
2025-12-22 22:42:56 +09:00
757193891f
feat(llvm/phi): Phase 277 P1 - fail-fast validation for PHI strict mode
...
## Summary
Implemented fail-fast validation for PHI ordering and value resolution in strict mode.
## Changes
### P1-1: Strict mode for "PHI after terminator"
- File: `src/llvm_py/phi_wiring/wiring.py::ensure_phi`
- Behavior: `NYASH_LLVM_PHI_STRICT=1` → RuntimeError if PHI created after terminator
- Default: Warning only (no regression)
### P1-2: Strict mode for "fallback 0"
- File: `src/llvm_py/phi_wiring/wiring.py::wire_incomings`
- Behavior: Strict mode forbids silent fallback to 0 (2 locations)
- Location 1: Unresolvable incoming value
- Location 2: Type coercion failure
- Error messages point to next debug file: `llvm_builder.py::_value_at_end_i64`
### P1-3: Connect verify_phi_ordering() to execution path
- File: `src/llvm_py/builders/function_lower.py`
- Behavior: Verify PHI ordering after all instructions emitted
- Debug mode: Shows "✅ All N blocks have correct PHI ordering"
- Strict mode: Raises RuntimeError with block list if violations found
## Testing
✅ Test 1: strict=OFF - passes without errors
✅ Test 2: strict=ON - passes without errors (no violations in test fixtures)
✅ Test 3: debug mode - verify_phi_ordering() connected and running
## Scope
- LLVM harness (Python) changes only
- No new environment variables (uses existing 3 from Phase 277 P2)
- No JoinIR/Rust changes (root fix is Phase 279)
- Default behavior unchanged (strict mode opt-in)
## Next Steps
- Phase 278: Remove deprecated env var support
- Phase 279: Root fix - unify "2本のコンパイラ" pipelines
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-22 14:48:37 +09:00
4ef2261e97
fix(joinir): Phase 269 P1.2 - static call normalization for this.method()
...
Problem:
- `this.method()` calls in static box loops were using string constant "StringUtils" as receiver
- This violated Box Theory (static box this should not be runtime object)
- Pattern8 was trying to pass receiver to JoinIR, causing SSA/PHI issues
Solution (3-part fix):
1. **MeResolverBox Fail-Fast** (stmts.rs): Remove string fallback, error message cleanup
2. **ReceiverNormalizeBox** (calls/build.rs): Normalize `this/me.method()` → static call at compile-time
3. **Pattern8 Skip Static Box** (pattern8_scan_bool_predicate.rs): Reject Pattern8 for static box contexts
Key changes:
- **stmts.rs**: Update error message - remove MeBindingInitializerBox mentions
- **calls/build.rs**: Add This/Me receiver check, normalize to static call if current_static_box exists
- **calls/lowering.rs**: Remove NewBox-based "me" initialization (2 locations - fixes Stage1Cli regression)
- **pattern8_scan_bool_predicate.rs**: Skip Pattern8 for static boxes (use Pattern1 fallback instead)
Result:
- ✅ phase269_p1_2_this_method_in_loop_vm.sh PASS (exit=7)
- ✅ No regression: phase259_p0_is_integer_vm PASS
- ✅ No regression: phase269_p0_pattern8_frag_vm PASS
- ✅ Stage1Cli unit tests PASS
- ✅ MIR uses CallTarget::Global, no const "StringUtils" as receiver
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-22 03:33:30 +09:00
5f22fe8fcd
feat(pattern8): Phase 269 P1 - SSA fix and call_method type annotation
...
Phase 269 P1.0: Pattern8 SSA correctness
- Add PHI node for loop variable `i` in pattern8_scan_bool_predicate.rs
- Ensure proper SSA form: i_current = phi [(preheader, i_init), (step, i_next)]
- Create loop_predicate_scan.rs for Pattern8 Frag emission
- Pre-allocate PHI destination before block generation
- Use insert_phi_at_head_spanned() for span synchronization
Phase 269 P1.1: call_method return type SSOT propagation
- Add callee_sig_name() helper in annotation.rs for function name formatting
- Annotate call_method return types in emit_unified_call_impl()
- Use module signature as SSOT for return type resolution (no hardcoding)
- Arity-aware function name: "BoxName.method/arity"
Fixes: is_integer() now correctly returns Bool instead of String
Test: Simple call_method test returns exit=7 (loop test has pre-existing bug)
Unit tests: All 1389 tests passing
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-22 01:41:19 +09:00
df715e909e
feat(edgecfg): Phase 268-270 savepoint (if_form adoption + Pattern9 minimal loop SSOT)
2025-12-21 23:12:52 +09:00
bd84fdf78f
feat(edgecfg): Phase 267 P0 BranchStub + emit_frag (Branch→MIR)
2025-12-21 20:33:11 +09:00
f8779df5a6
feat(edgecfg): Phase 266 emit_wires PoC (wires→MIR Jump/Return)
2025-12-21 17:20:48 +09:00
21387f3816
feat(edgecfg): Phase 265 P2 - seq/if_ 実装(wires/exits 分離)
...
## 目的
「解決済み配線(wires)」と「未解決 exit(exits)」を分離し、
Frag 合成の基本パターンを完成させる。
## 実装内容
### 1. Frag 構造体の変更
- `wires: Vec<EdgeStub>` フィールド追加
- 不変条件:
- exits: target = None のみ(未配線、外へ出る exit)
- wires: target = Some(...) のみ(配線済み、内部配線)
### 2. loop_() の wires 対応
- Break/Continue を exits から wires に移動
- P1 テスト 3個を wires 検証に更新
### 3. seq(a, b) 実装
- a.Normal → b.entry を wires に追加(内部配線)
- seq の exits[Normal] は b の Normal のみ
- 新規テスト 2個追加
### 4. if_(header, cond, t, e, join_frag) 実装
- シグネチャ変更: join: BasicBlockId → join_frag: Frag
- t/e.Normal → join_frag.entry を wires に追加
- if の exits は join_frag.exits
- 新規テスト 2個追加
### 5. verify_frag_invariants() 強化
- wires/exits 分離契約の検証追加(警告のみ)
- Err 化は Phase 266 で実施
## テスト結果
- edgecfg::api: 13/13 PASS(frag 3 + compose 9 + verify 1)
- 全 lib テスト: 1388/1388 PASS(退行なし)
## 核心的な設計判断
1. **wires/exits 分離**:
- 問題: 解決済み配線と未解決 exit を混ぜると再配線バグ
- 解決: 分離して不変条件を強化
- 効果: Phase 266 で wires を MIR terminator に落とすだけ
2. **if_ は join_frag 受け取り**:
- 問題: join: BasicBlockId では「join block」か「join 以降」か曖昧
- 解決: join_frag: Frag で「join 以降」を明確化
- 効果: PHI 生成の柔軟性確保
3. **verify は警告のみ**:
- P2 の役割: wires/exits 分離の証明に集中
- Phase 266 で MIR 生成時に厳格化
## 次フェーズへの橋渡し
- Phase 266: wires を MIR terminator に落とす
- Phase 267: Pattern6/7/8 を Frag 化
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-21 16:47:47 +09:00
cda034fe8f
feat(edgecfg): Phase 265 P1 - compose 配線ロジック実装(test-only PoC)
...
## 目的
Frag/ExitKind が BasicBlockId 層で配線できることを証明
## 実装完了内容
- EdgeStub に target: Option<BasicBlockId> 追加
- compose::loop_() 配線ロジック実装(Continue → header, Break → after)
- verify_frag_invariants() 配線契約検証追加
- test-only PoC で実証完了(5個のテスト)
## 配線契約
- Continue(loop_id) の EdgeStub.target = Some(header)
- Break(loop_id) の EdgeStub.target = Some(after)
- Normal/Return/Unwind の EdgeStub.target = None(上位へ伝搬)
## テスト
- compose::tests: 5 PASS(既存2個更新 + 新規3個追加)
- verify::tests: 1 PASS(基本smoke test)
- cargo test -p nyash-rust --lib: SUCCESS
## 重要な制約
- MIR 命令生成はまだしない(Frag 層の配線能力証明のみ)
- NormalizedShadow/JoinIR層への適用は Phase 266 に繰り越し
- Pattern6/7/8 未改変(配線能力の証明に集中)
## 次のステップ
- Phase 265 P2: seq/if_ 実装(順次合成・条件分岐合成)
- Phase 266: JoinIR-VM Bridge 改修後、NormalizedShadow への適用
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-21 16:22:46 +09:00
ab1510920c
feat(edgecfg): Phase 265 P0 - compose/verify 最小実装(入口SSOT迷子防止)
...
🎯 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-21 13:07:17 +09:00
923a442326
refactor(edgecfg): add Frag/ExitKind API entrypoint (Phase 264 design-first)
...
Phase 264 P0: EdgeCFG Fragment 入口API作成(実装置換なし)
- 入口フォルダ作成: src/mir/builder/control_flow/edgecfg/api/
- コア型定義: ExitKind, EdgeStub, Frag
- 合成関数シグネチャ: seq, if_, loop_, cleanup(中身TODO、pub(crate))
- 最小テスト: 3個のユニットテスト追加(frag.rs)
- ドキュメント連動: edgecfg-fragments.md に実装入口追記
制約遵守:
- 既存 pattern6/7/8 未改変
- merge/EdgeCFG 未改変
- 既存LoopId使用(control_form.rs に PartialOrd, Ord 追加)
- MIR側EdgeArgs使用(JoinIRと混線回避)
- BTreeMap採用(決定的順序保証、Phase 69-3 教訓)
次フェーズ: Phase 265 で Pattern8 適用時に compose::loop_ を実装
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-21 12:49:53 +09:00
be4de67601
fix(joinir): improve Pattern3 classification to exclude simple conditional assignment (Phase 264 P0)
...
Problem:
- Pattern3 heuristic was too conservative: detect_if_in_body() returned
true for ANY if statement, causing simple conditional assignments to be
misclassified as Pattern3IfPhi
- Example: `if i == 0 then seg = "first" else seg = "other"` was routed
to Pattern3, but Pattern3 only handles if-sum patterns like
`sum = sum + (if x then 1 else 0)`
- This caused loops with conditional assignment to fail Pattern3 check
and exhaust all routing paths
Solution (Conservative, Phase 264 P0):
- ast_feature_extractor.rs:
- detect_if_else_phi_in_body(): Always return false
- has_if = has_if_else_phi (don't use detect_if_in_body())
- loop_pattern_detection/mod.rs:
- Add has_if_sum_signature() (returns false for P0)
- has_if_else_phi = carrier_count > 1 && has_if_sum_signature(scope)
Effect:
- Simple conditional assignment loops now fall through to Pattern1 ✅
- Pattern3 misrouting prevented ✅
Results:
- Lib tests: 1368/1368 PASS (no regression)
- Minimal repro: phase264_p0_bundle_resolver_loop_min.hako PASS ✅
- Quick smoke: 45/46 (unchanged - complex BundleResolver loop needs P1)
Phase 264 P1 TODO:
- Implement accurate if-sum signature detection (AST/CFG analysis)
- Support complex nested loops in Pattern2 or new pattern
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-21 11:49:03 +09:00
e17902a443
refactor(pattern2): move promotion decision into pattern2/api SSOT
...
Phase 263 P0.2: pattern2/api/ フォルダ化 - 入口SSOTの物理固定
目的: PromoteDecision/try_promote の参照点を1箇所に閉じ込めて、迷子防止
Changes:
1. 新規フォルダ構造:
- pattern2/api/mod.rs - 入口SSOT(try_promote と PromoteDecision を再export)
- pattern2/api/promote_decision.rs - PromoteDecision/PromoteStepResult 型定義
- pattern2/api/promote_runner.rs - try_promote(...) 実装(SSOT entry point)
- pattern2/mod.rs - api モジュールを公開
2. 移動/抽出:
- PromoteDecision enum を promote_step_box.rs → pattern2/api/promote_decision.rs へ
- promote_and_prepare_carriers を try_promote として pattern2/api/promote_runner.rs へ抽出
3. promote_step_box.rs を薄いラッパに縮退(35行, -177行):
- pattern2::api::try_promote を呼び出すだけの互換用ラッパ
- 将来的に削除予定(deprecated)
4. orchestrator を新API に書き換え:
- use super::pattern2::api::{try_promote, PromoteDecision};
- try_promote(...) を直接呼び出し
5. 参照確認:
- rg で確認: すべての参照が pattern2::api 経由に収束 ✅
検証:
- cargo test --lib: 1368/1368 PASS ✅
- quick smoke: 45/46 PASS ✅ (悪化なし)
- 参照点が pattern2/api に一本化され、迷子防止を物理的に保証
2025-12-21 11:07:36 +09:00
abdb860e7e
refactor(pattern2): introduce PromoteDecision enum to eliminate Option wrapping ambiguity
...
Phase 263 P0.1: PromoteDecision API hardening
目的: Result<Option<PromoteStepResult>, String> の揺れを型で固定し、迷子をゼロに
Changes:
- promote_step_box.rs:
- PromoteDecision enum を導入(Promoted/NotApplicable/Freeze)
- PromoteStepBox::run() の戻り値を Result<PromoteDecision, String> に統一
- promote_and_prepare_carriers() が inputs の所有権を受け取り、PromoteDecision を直接構築
- Reject 分岐を型安全に二分化(文字列マッチング維持、型で意図を明確化)
- pattern2_lowering_orchestrator.rs:
- orchestrator 側の分岐を1箇所に固定(match PromoteDecision {...})
- NotApplicable → Ok(None) で後続経路へ
- Freeze → Err で Fail-Fast
受け入れ:
- quick smoke: 45/46 PASS ✅ (悪化なし)
- NotApplicable は必ず Ok(None) で Pattern2全体を抜ける
- Freeze は必ず Err(fail-fast)
Next: ファイル構造リファクタリング(pattern2/api/ フォルダ化)を別フェーズで検討
2025-12-21 10:54:46 +09:00
93022e7e10
fix(pattern2): abort entire Pattern2 on unpromoted LoopBodyLocal instead of partial execution
...
Phase 263 P0: Pattern2 で処理できない LoopBodyLocal を検出したら Pattern2 全体を早期終了
Changes:
- promote_step_box.rs: 戻り値を Result<Option<_>, String> に変更
- Reject を二分化: 対象外(not_readonly等)→ Ok(None)、対象だが未対応 → Err
- pattern2_lowering_orchestrator.rs: Ok(None) 検出で早期 return
- apps/tests/phase263_p0_pattern2_seg_min.hako: test simplification
後続経路(legacy binding等)へ fallback させる(detection→extract→lower SSOT 維持)
Fail-Fast 原則: 対象外は Ok(None) で後続経路へ、対象だが未対応は Err で即座に失敗
Fixes: core_direct_array_oob_set_rc_vm smoke test FAIL
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com >
2025-12-21 10:23:38 +09:00
a15821cb17
Revert "fix(pattern2): return Ok(None) for unpromoted LoopBodyLocal instead of Err"
...
This reverts commit e0278405c0 .
2025-12-21 10:21:05 +09:00
e0278405c0
fix(pattern2): return Ok(None) for unpromoted LoopBodyLocal instead of Err
...
- Pattern2 で処理できない LoopBodyLocal は Err ではなく処理続行
- Pattern1 等に fallback させる(detection→extract→lower SSOT 維持)
- out-of-scope 変数(reassigned body-local)はreject不要
Fixes: core_direct_array_oob_set_rc_vm smoke test FAIL
Fixes: phase263_p0_pattern2_seg_min (新規テスト)
2025-12-21 09:56:56 +09:00
c0334f8b7e
refactor(mir): phase260 p0.2 hide legacy edge-args reads behind BasicBlock API
...
- Add block.return_env() getter for Return env metadata
- Update instruction_rewriter.rs to use block.return_env()
- Update exit_collection.rs to use block.return_env()
- Prepare for Phase 260 P2 (jump_args deletion)
This consolidates all legacy edge-args reads through BasicBlock API,
enabling clean deletion of jump_args field in P2.
2025-12-21 09:01:35 +09:00
aa3fdf3c18
refactor(joinir): Phase 260 P0.1 Step 6b - fix tests and add TODO
...
- Fix helpers.rs tests to use new MirFunction::new(FunctionSignature, BasicBlockId) API
- Update continuation_contract.rs import path to use rewriter::helpers
- Add TODO comment for future exit_collection integration
- All 6 rewriter tests pass
The exit_collection module is complete and tested but full integration
with instruction_rewriter.rs deferred (80/20 rule - logging context
and flow control require careful refactoring).
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com >
2025-12-21 06:33:11 +09:00
cbed040a74
refactor(joinir): Phase 260 P0.1 Step 6 - extract exit_collection.rs
...
Extract exit value collection logic from instruction_rewriter.rs into
dedicated rewriter/exit_collection.rs module (~305 lines).
New functions:
- collect_exit_values_from_legacy_edge_args(): Phase 246-EX collection
- add_carrier_values_to_inputs(): carrier values → carrier_inputs map
- handle_fallback_exit_collection(): Phase 246-EX/131 P1.5 fallback
- collect_k_exit_values(): k_exit tail call lowering (Phase 131)
Key changes:
- ExitCollectionResult struct for structured return values
- Uses Vec<(String, (BasicBlockId, ValueId))> for carrier_values
(matching ExitArgsCollectorBox output format)
- Logging removed from helpers (caller handles via local log! macro)
- 3 unit tests for add_carrier_values_to_inputs
🤖 Generated with [Claude Code](https://claude.com/claude-code )
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com >
2025-12-21 06:28:09 +09:00
15b3352e21
refactor(joinir): Phase 260 P0.1 Step 5 - Extract terminator.rs (Jump/Branch remapping)
...
Extract Jump/Branch terminator remapping to dedicated module.
3 clean functions: remap_jump, remap_branch, apply_remapped_terminator.
Changes:
- NEW: rewriter/terminator.rs - 3 functions (145 lines)
- remap_jump(): Jump block ID + edge_args remapping
- remap_branch(): Branch block ID + condition + edge_args remapping
- apply_remapped_terminator(): Apply remapped terminator with edge_args handling
- CHANGED: instruction_rewriter.rs - use terminator module (deleted local logic)
- Deleted remap_edge_args closure (lines 902-911)
- Replaced Jump remapping (lines 1056-1067) → remap_jump()
- Replaced Branch remapping (lines 1069-1094) → remap_branch()
- Replaced terminator setting (lines 1098-1127) → apply_remapped_terminator()
- CHANGED: rewriter/mod.rs - declare terminator module
Benefits:
- Phase 259 P0 FIX: skipped_entry_redirects handling centralized
- Testable in isolation (pure block ID/ValueId mapping)
- Reduces instruction_rewriter.rs by ~40 lines
Reduction:
- instruction_rewriter.rs: 1396 → ~1356 lines (-40)
Next: Extract exit_collection.rs (Return→Jump + exit value collection)
2025-12-21 06:17:14 +09:00
d9ff3f60ff
refactor(joinir): Phase 260 P0.1 Step 4 - Extract type_propagation.rs (70 lines)
...
Extract propagate_value_type_for_inst to dedicated type_propagation module.
Handles type info flow from JoinIR→MIR merge (SSOT + fallback inference).
Changes:
- NEW: rewriter/type_propagation.rs - propagate_value_type_for_inst
- CHANGED: instruction_rewriter.rs - import from type_propagation (deleted local fn)
- CHANGED: rewriter/mod.rs - declare type_propagation module
Design:
- SSOT: Prefer type info from JoinIR source function metadata
- Fallback: Infer from instruction structure (Const/Copy/BinOp/Compare)
- LLVM: Ensures '+' stays numeric (not concat_hh_mixed)
Reduction:
- instruction_rewriter.rs: 1466 → 1396 lines (-70)
Next: Start terminator.rs extraction (Branch/Jump/Return remapping)
2025-12-21 06:11:53 +09:00
e555b4ad31
refactor(joinir): Phase 260 P0.1 Step 3 - Extract helpers.rs (is_skippable_continuation)
...
Extract is_skippable_continuation to dedicated helpers module.
Small pure function (12 lines) with comprehensive tests (3 test cases).
Changes:
- NEW: rewriter/helpers.rs - is_skippable_continuation + 3 tests
- CHANGED: instruction_rewriter.rs - import from helpers (deleted local definition)
- CHANGED: rewriter/mod.rs - re-export from helpers
Benefits:
- Testable in isolation (pure function)
- Clear module boundary (structural checks)
- instruction_rewriter.rs: 1477 → 1466 lines (-11)
Tests:
- test_is_skippable_continuation_pure_stub ✅
- test_is_skippable_continuation_has_instructions ✅
- test_is_skippable_continuation_multiple_blocks ✅
Next: Extract type_propagation.rs (propagate_value_type_for_inst - 70 lines)
2025-12-21 06:09:45 +09:00
b87760e247
refactor(joinir): Phase 260 P0.1 Step 2 - Extract logging.rs (DEBUG-177 style)
...
Extract logging utilities into dedicated module (safest first split).
Provides log_if() function + rewriter_log!() macro as alternatives to local log! macro.
Changes:
- NEW: rewriter/logging.rs - log_if() + rewriter_log!() macro
- CHANGED: rewriter/mod.rs - declare logging module
Design:
- log_if(trace, enabled, msg): Function form for explicit control
- rewriter_log!(): Macro form for format!() convenience
- Both wrap JoinLoopTrace::stderr_if() (existing infrastructure)
Status:
- instruction_rewriter.rs still uses local log! macro (unchanged)
- Future: Gradually migrate to logging::log_if() or rewriter_log!()
- cargo check PASS ✅
Next: Extract is_skippable_continuation to helpers.rs (smallest function)
2025-12-21 06:06:29 +09:00
4bc469239d
refactor(joinir): Phase 260 P0.1 Step 1 - Create rewriter/ skeleton (box-first modularization)
...
Create rewriter/ directory with re-export skeleton for instruction_rewriter.rs.
This enables gradual refactoring without breaking existing code.
Changes:
- NEW: src/.../joinir/merge/rewriter/mod.rs (re-exports instruction_rewriter)
- CHANGED: merge/mod.rs - route calls through rewriter module
- STRATEGY: Keep instruction_rewriter.rs intact, split later into:
- terminator.rs (Branch/Jump/Return remapping)
- exit_line.rs (ExitLine/exit-phi wiring)
- carriers.rs (loop_invariants, exit_bindings)
- logging.rs (DEBUG-177 style verbose logs)
Acceptance:
- cargo check PASS ✅
- No behavior change (挙動変更なし)
- Backward compatible (instruction_rewriter.rs still exists)
Next: Extract terminator.rs (smallest, safest first split)
2025-12-21 06:03:43 +09:00
1fe5be347d
refactor(mir): phase260 p0.1 strangler hardening + smoke fixtures
2025-12-21 05:47:37 +09:00
4dfe3349bf
refactor(mir): phase260 p0 edge-args plumbing (strangler) + ssot api + docs
2025-12-21 04:34:22 +09:00