Commit Graph

9 Commits

Author SHA1 Message Date
59a985b7fa joinir: clean pattern visibility and refactor pattern2 pipeline 2025-12-11 19:11:26 +09:00
d7805e5974 feat(joinir): Phase 213-2 Step 2-2 & 2-3 Data structure extensions
Extended PatternPipelineContext and CarrierUpdateInfo for Pattern 3 AST-based generalization.

Changes:
1. PatternPipelineContext:
   - Added loop_condition: Option<ASTNode>
   - Added loop_body: Option<Vec<ASTNode>>
   - Added loop_update_summary: Option<LoopUpdateSummary>
   - Updated build_pattern_context() for Pattern 3

2. CarrierUpdateInfo:
   - Added then_expr: Option<ASTNode>
   - Added else_expr: Option<ASTNode>
   - Updated analyze_loop_updates() with None defaults

Status: Phase 213-2 Steps 2-2 & 2-3 complete
Next: Create Pattern3IfAnalyzer to extract if statement and populate update summary
2025-12-10 00:01:53 +09:00
32a91e31ac feat(joinir): Phase 200-B/C/D capture analysis + Phase 201-A reserved_value_ids infra
Phase 200-B: FunctionScopeCaptureAnalyzer implementation
- analyze_captured_vars_v2() with structural loop matching
- CapturedEnv for immutable function-scope variables
- ParamRole::Condition for condition-only variables

Phase 200-C: ConditionEnvBuilder extension
- build_with_captures() integrates CapturedEnv into ConditionEnv
- fn_body propagation through LoopPatternContext to Pattern 2

Phase 200-D: E2E verification
- capture detection working for base, limit, n etc.
- Test files: phase200d_capture_minimal.hako, phase200d_capture_in_condition.hako

Phase 201-A: MirBuilder reserved_value_ids infrastructure
- reserved_value_ids: HashSet<ValueId> field in MirBuilder
- next_value_id() skips reserved IDs
- merge/mod.rs sets/clears reserved IDs around JoinIR merge

Phase 201: JoinValueSpace design document
- Param/Local/PHI disjoint regions design
- API: alloc_param(), alloc_local(), reserve_phi()
- Migration plan for Pattern 1-4 lowerers

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-09 18:32:03 +09:00
3ece6896c4 refactor(joinir): Phase 183-1 Unify pattern detection in loop_pattern_detection
Consolidates duplicate pattern detection logic across two routing layers.

## Changes

1. **Unified Detection Documentation**:
   - Added Phase 183 comments to `loop_pattern_detection::classify()`
   - Documented that this is the single source of truth for pattern classification
   - Both routers now reference this centralized function

2. **Router Documentation Updates**:
   - `patterns/router.rs`: Added Phase 183 comments explaining structure-based routing
   - `loop_pattern_router.rs`: Added unified detection section
   - Both routers now explicitly reference shared detection logic

3. **Improved Debug Output**:
   - Added `pattern_kind` to debug message in `route_loop_pattern()`
   - Helps diagnose pattern matching failures

## Benefits

- **Single source of truth**: Pattern classification logic in one place
- **Consistency**: Both routers use same detection algorithm
- **Maintainability**: Changes to classification rules only needed once
- **Documentation**: Clear references between routers and detection module

## Testing

 All loop_pattern_detection tests pass
 Pattern 2 tests pass
 No behavioral changes, pure documentation/organization refactoring

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-08 22:17:06 +09:00
95f3aa429e refactor(joinir): Extract legacy binding path to routing_legacy_binding.rs
Phase 179-A Step 2: Separate LoopFrontendBinding JSON construction logic
into dedicated module for better organization.

Changes:
- New file: routing_legacy_binding.rs (223 lines)
- routing.rs: cf_loop_joinir_impl() simplified to 15 lines (delegates to legacy path)
- Routing now clearly separates pattern-based vs. legacy binding paths

Benefits:
- Clear separation of concerns (pattern router vs. legacy whitelist)
- routing.rs reduced from 364 to 146 lines (60% reduction)
- Legacy path isolated for future deprecation
2025-12-08 18:36:13 +09:00
d28ba4cd9d refactor(joinir): Phase 193-1 - AST Feature Extractor Box modularization
**Phase 193-1**: Create independent AST Feature Extractor Box module

## Summary
Extracted feature detection logic from router.rs into a new, reusable
ast_feature_extractor.rs module. This improves:
- **Modularity**: Feature extraction is now a pure, side-effect-free module
- **Reusability**: Can be used for Pattern 5-6 detection and analysis tools
- **Testability**: Pure functions can be unit tested independently
- **Maintainability**: Clear separation of concerns (router does dispatch, extractor does analysis)

## Changes

### New Files
- **src/mir/builder/control_flow/joinir/patterns/ast_feature_extractor.rs** (+180 lines)
  - `detect_continue_in_body()`: Detect continue statements
  - `detect_break_in_body()`: Detect break statements
  - `extract_features()`: Full feature extraction pipeline
  - `detect_if_else_phi_in_body()`: Pattern detection for if-else PHI
  - `count_carriers_in_body()`: Heuristic carrier counting
  - Unit tests for basic functionality

### Modified Files
- **src/mir/builder/control_flow/joinir/patterns/router.rs**
  - Removed 75 lines of feature detection code
  - Now delegates to `ast_features::` module
  - Phase 193 documentation in comments
  - Cleaner separation of concerns

- **src/mir/builder/control_flow/joinir/patterns/mod.rs**
  - Added module declaration for ast_feature_extractor
  - Updated documentation with Phase 193 info

## Architecture
```
router.rs (10 lines)
  └─→ ast_feature_extractor.rs (180 lines)
      - Pure functions for AST analysis
      - No side effects
      - High reusability
      - Testable in isolation
```

## Testing
 Build succeeds: `cargo build --release` compiles cleanly
 Binary compatibility: Existing .hako files execute correctly
 No logic changes: Feature detection identical to previous implementation

## Metrics
- Lines moved from router to new module: 75
- New module total: 180 lines (including tests and documentation)
- Router.rs reduced by ~40% in feature detection code
- New module rated  for reusability and independence

## Next Steps
- Phase 193-2: CarrierInfo Builder Enhancement
- Phase 193-3: Pattern Classification Improvement
- Phase 194: Further pattern detection optimizations

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-06 03:30:03 +09:00
a21501286e feat(joinir): Structural pattern detection + Pattern 4 scaffold
- Add LoopFeatures struct for structure-based detection (no name deps)
- Add LoopPatternKind enum and classify() function
- Pattern 3: has_if_else_phi && !has_break && !has_continue
- Pattern 4: has_continue == true (detection only, lowering TODO)
- Unify router to use extract_features()/classify() instead of legacy
- Remove AST dependency, use LoopForm/LoopScope only
- Add Pattern 4 test file (loop_continue_pattern4.hako)
- Pattern 3 test passes (sum=9)

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-06 00:10:27 +09:00
abfe0b198b feat(joinir): Phase 195 - Unified JoinLoopTrace for all JoinIR debug output
Created centralized tracing module for JoinIR loop lowering operations,
consolidating scattered eprintln! calls into a single SSOT interface.

# Implementation

1. **Created trace.rs module** (~233 lines)
   - JoinLoopTrace struct with env var controls
   - Unified API: pattern(), varmap(), joinir_stats(), phi(), merge(), etc.
   - Global singleton via trace() function
   - Supports 5 env vars: NYASH_TRACE_VARMAP, NYASH_JOINIR_DEBUG,
     NYASH_OPTION_C_DEBUG, NYASH_JOINIR_MAINLINE_DEBUG, NYASH_LOOPFORM_DEBUG

2. **Updated debug.rs** - Delegates trace_varmap() to JoinLoopTrace

3. **Updated routing.rs** - All eprintln! replaced with trace calls (10 instances)

4. **Updated pattern routers** - All 3 patterns now use unified trace
   - pattern1_minimal.rs: 6 replacements
   - pattern2_with_break.rs: 6 replacements
   - pattern3_with_if_phi.rs: 6 replacements
   - router.rs: 2 replacements

5. **Updated merge/block_allocator.rs** - 6 eprintln! → trace calls

# Benefits

- **Single Source of Truth**: All trace control through environment variables
- **Consistent Format**: Unified [trace:*] prefix for easy filtering
- **Zero Overhead**: No output when env vars unset
- **Easy Extension**: Add new trace points via existing API
- **Better Debug Experience**: Structured output with clear categories

# Testing

 cargo build --release - Success
 NYASH_TRACE_VARMAP=1 - Shows varmap traces only
 NYASH_JOINIR_DEBUG=1 - Shows joinir + blocks + routing traces
 No env vars - No debug output
 apps/tests/loop_min_while.hako - All tests pass

# Related

- Phase 191-194 groundwork (modular merge structure)
- NYASH_TRACE_VARMAP added today for variable_map debugging
- Consolidates ~80 scattered eprintln! calls across JoinIR

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-05 22:23:51 +09:00
67e2bfada4 feat(joinir): Phase 194 - Table-driven loop pattern router
Replace if/else chain with table-driven pattern dispatch for easier
pattern addition and maintenance.

# Changes

## New Files
- router.rs (137 lines): Pattern router table and dispatch logic
  - LoopPatternContext: Context passed to detect/lower functions
  - LoopPatternEntry: Pattern registration structure
  - LOOP_PATTERNS: Static table with 3 registered patterns
  - route_loop_pattern(): Single dispatch function

## Modified Files
- patterns/mod.rs (+8 lines): Export router module
- pattern1_minimal.rs (+19 lines): Added can_lower() + lower() wrapper
- pattern2_with_break.rs (+17 lines): Added can_lower() + lower() wrapper
- pattern3_with_if_phi.rs (+22 lines): Added can_lower() + lower() wrapper
- routing.rs (-21 lines): Replaced if/else chain with router call

# Architecture Improvement

## Before (if/else chain)
```rust
if func_name == "main" && has_sum {
    return pattern3(...);
} else if func_name == "main" {
    return pattern1(...);
} else if func_name == "JoinIrMin.main/0" {
    return pattern2(...);
}
```

## After (table-driven)
```rust
let ctx = LoopPatternContext::new(...);
route_loop_pattern(self, &ctx)?
```

# Adding New Patterns (Now Trivial!)

1. Create pattern4_your_name.rs
2. Implement can_lower() + lower()
3. Add entry to LOOP_PATTERNS table

That's it! No routing logic changes needed.

# Testing

 Pattern 1 (loop_min_while.hako): PASSED
 Pattern 2 (joinir_min_loop.hako): PASSED
 Pattern 3 (loop_if_phi.hako): Routes correctly (VM error is pre-existing)

Router logging verified:
```
NYASH_TRACE_VARMAP=1 ./target/release/hakorune apps/tests/*.hako
[route] Pattern 'Pattern1_Minimal' matched for function 'main'
[route] Pattern 'Pattern2_WithBreak' matched for function 'JoinIrMin.main/0'
[route] Pattern 'Pattern3_WithIfPhi' matched for function 'main'
```

# Line Counts

- router.rs: 137 lines (new)
- Total pattern files: 491 lines (3 patterns)
- routing.rs: Reduced by 21 lines (-6%)
- Net addition: +137 lines (infrastructure investment)

# Documentation

See router.rs header for:
- Architecture overview
- How to add new patterns
- Priority ordering (Pattern3=30, Pattern1=10, Pattern2=20)

Phase 194 complete - pattern addition is now a trivial task!

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-05 22:11:39 +09:00