Files
hakorune/src/mir/builder.rs

1259 lines
56 KiB
Rust
Raw Normal View History

/*!
* MIR Builder - Converts AST to MIR/SSA form
*
* Implements AST MIR conversion with SSA construction
*/
use super::slot_registry::resolve_slot_by_type_name;
use super::{
BasicBlock, BasicBlockId, BasicBlockIdGenerator, CompareOp, ConstValue, Effect, EffectMask,
FunctionSignature, MirFunction, MirInstruction, MirModule, MirType, ValueId, ValueIdGenerator,
};
use crate::ast::{ASTNode, LiteralValue, Span};
use crate::mir::builder::builder_calls::CallTarget;
use crate::mir::region::function_slot_registry::FunctionSlotRegistry;
use crate::mir::region::RegionId;
docs: Add field visibility analysis and MIR BoxCall documentation ## Field Visibility Analysis Results - Confirmed init{} fields are **public** in current Nyash implementation - No access modifier (private/public) system currently implemented - All fields accessible via me.fieldname syntax - Documented findings for future reference ## MIR Documentation Enhancements - Created comprehensive mir-dumper-guide.md for reading MIR dumps - Enhanced mir-26-specification.md with BoxCall vs regular Call examples - Added clear identification patterns: * BoxCall: `call %value.method(args)` (plugins/builtins) * Regular Call: `call %func(%me, args)` (user-defined boxes) ## VM Backend BoxRef Handling Improvements - Fixed BoxRef method dispatch using share_box() instead of clone_box() - Prevents unintended constructor calls during method resolution - Maintains proper instance identity throughout VM execution ## MIR Builder User-Defined Box Tracking - Added user_defined_boxes HashSet to track declared user boxes - Improved method lowering decisions for user-defined vs builtin boxes - Enhanced AST→MIR conversion accuracy for method calls ## Plugin Tester Lifecycle Enhancements - Added comprehensive FileBox lifecycle testing (open/write/close) - Enhanced cloneSelf() and copyFrom() testing with proper Handle parsing - Added TLV encoding helpers for strings and bytes - Improved error reporting and step-by-step validation 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-08-21 01:18:25 +09:00
use std::collections::HashSet;
use std::collections::{BTreeMap, HashMap};
mod builder_calls;
mod call_resolution; // ChatGPT5 Pro: Type-safe call resolution utilities
mod calls; // Call system modules (refactored from builder_calls)
mod binding_context; // Phase 136 follow-up (Step 4/7): BindingContext extraction
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
mod compilation_context; // Phase 136 follow-up (Step 7/7): CompilationContext extraction
feat(mir/builder): implement BoxCompilationContext for structural metadata isolation 箱理論の完璧な実装!各static boxコンパイルを独立したコンテキストで実行。 設計: - BoxCompilationContext: variable_map, value_origin_newbox, value_types を箱化 - MirBuilder: compilation_context: Option<BoxCompilationContext> フィールド追加 - context swap: lower_static_method_as_function 開始/終了時に std::mem::swap - 自動クリーンアップ: スコープ終了でコンテキスト破棄 実装: 1. src/mir/builder/context.rs: BoxCompilationContext構造体定義(テスト付き) 2. src/mir/builder.rs: compilation_contextフィールド追加、既存フィールドにコメント追加 3. src/mir/builder/lifecycle.rs: 各static boxでコンテキスト作成・破棄 4. src/mir/builder/builder_calls.rs: lower_static_method_as_functionでcontext swap 5. src/mir/builder/decls.rs, exprs.rs: 古いmanual clear()削除 効果: ✅ グローバル状態汚染を構造的に不可能化 ✅ 各static boxが完全に独立したコンテキストでコンパイル ✅ 既存コード変更なし(swap技法で完全後方互換性) ✅ StageBArgsBox ValueId(21)エラー完全解決 箱理論的評価: 🟢 95点 - 明示的な境界: 各boxのコンテキストが物理的に分離 - 汚染不可能: 前の箱の状態が構造的に残らない - 戻せる: コンテキスト差し替えで簡単ロールバック - 美しい設計: スコープベースのリソース管理 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-17 11:28:18 +09:00
mod context; // BoxCompilationContext - 箱理論による静的Boxコンパイル時のコンテキスト分離
mod core_context; // Phase 136 follow-up (Step 2/7): CoreContext extraction
refactor(mir): Extract MetadataContext from MirBuilder (Phase 136 follow-up 6/7) ## Summary Extracted metadata and debug information management into dedicated MetadataContext struct, completing step 6 of 7 in the Context Box refactoring plan. ## Changes - NEW: src/mir/builder/metadata_context.rs (MetadataContext struct + helpers) - Modified: src/mir/builder.rs (added metadata_ctx field + sync helpers) - Modified: src/mir/hints.rs (added Clone + Debug derives to HintSink) - Updated: phase-136-context-box-progress.md (6/7 progress) ## Extracted Fields - current_span: Span → metadata_ctx.current_span - source_file: Option<String> → metadata_ctx.source_file - hint_sink: HintSink → metadata_ctx.hint_sink - current_region_stack: Vec<RegionId> → metadata_ctx.current_region_stack ## Key Features - Zero-cost type inference hints (HintSink) - Source position tracking for error messages - Region observation stack for debug builds - Phase 135 contract_checks integration ## Tests - cargo test --release --lib: 1019/1023 passed (4 pre-existing failures) - phase135_trim_mir_verify.sh: PASS - Backward compatibility: 100% maintained (deprecated fields synced) ## Progress Phase 136 Context Extraction: 6/7 complete (86%) - ✅ Step 1: TypeContext - ✅ Step 2: CoreContext - ✅ Step 3: ScopeContext - ✅ Step 4: BindingContext - ✅ Step 5: VariableContext - ✅ Step 6: MetadataContext (this commit) - ⏳ Step 7: CompilationContext 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:03:34 +09:00
mod metadata_context; // Phase 136 follow-up (Step 6/7): MetadataContext extraction
refactor(mir): Extract VariableContext from MirBuilder (Phase 136 follow-up 5/7) ## Summary Extracted variable mapping management into dedicated VariableContext struct, completing step 5 of 7 in the Context Box refactoring plan. ## Changes - NEW: src/mir/builder/variable_context.rs (VariableContext struct + helpers) - Modified: src/mir/builder.rs (added variable_ctx field + sync helpers) - Updated: phase-136-context-box-progress.md (5/7 progress) ## Extracted Fields - variable_map: BTreeMap<String, ValueId> → variable_ctx.variable_map ## Key Features - snapshot/restore for if/loop pattern state management - JoinIR integration: CarrierInfo::from_variable_map() - ExitLine contract enforcement (carriers in variable_map) - NYASH_TRACE_VARMAP debug visualization support ## Design Clarity - BindingContext: String → BindingId (binding identity, survives SSA renaming) - VariableContext: String → ValueId (current SSA values, block-local) - Both contexts work together for complete variable management ## Tests - cargo test --release --lib: 1014/1018 passed (4 pre-existing failures) - phase135_trim_mir_verify.sh: PASS - Backward compatibility: 100% maintained (deprecated fields synced) ## Progress Phase 136 Context Extraction: 5/7 complete (71%) - ✅ Step 1: TypeContext - ✅ Step 2: CoreContext - ✅ Step 3: ScopeContext - ✅ Step 4: BindingContext - ✅ Step 5: VariableContext (this commit) - ⏳ Step 6: MetadataContext - ⏳ Step 7: CompilationContext 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 21:50:50 +09:00
mod variable_context; // Phase 136 follow-up (Step 5/7): VariableContext extraction
mod decls; // declarations lowering split
mod exprs; // expression lowering split
mod exprs_call;
mod method_call_handlers; // Method call handler separation (Phase 3) // call(expr)
// include lowering removed (using is handled in runner)
mod control_flow; // thin wrappers to centralize control-flow entrypoints
mod exprs_lambda; // lambda lowering
mod exprs_peek; // peek expression
mod exprs_qmark; // ?-propagate
mod fields; // field access/assignment lowering split
mod if_form;
mod joinir_id_remapper; // Phase 189: JoinIR ID remapping (ValueId/BlockId translation)
mod joinir_inline_boundary_injector; // Phase 189: JoinInlineBoundary Copy instruction injector
mod lifecycle;
mod loop_frontend_binding; // Phase 50: Loop Frontend Binding (JoinIR variable mapping)
pub(crate) mod loops;
mod ops;
mod phi;
mod phi_merge; // Phase 25.1q: Unified PHI merge helper // prepare/lower_root/finalize split
// legacy large-match remains inline for now (planned extraction)
mod emission; // emission::*Const/Compare/Branch の薄い発行箱)
mod emit_guard; // EmitGuardBoxemit直前の最終関所
mod metadata; // MetadataPropagationBoxtype/originの伝播
mod name_const; // NameConstBox関数名Const生成
mod observe; // P0: dev-only observability helpersssa/resolve
mod origin; // P0: origin inferenceme/Knownと PHI 伝播(軽量)
mod plugin_sigs; // plugin signature loader
mod receiver; // ReceiverMaterializationBoxMethod recv の pin+LocalSSA 集約)
mod rewrite; // P1: Known rewrite & special consolidation
mod router; // RouterPolicyBoxUnified vs BoxCall
mod schedule; // BlockScheduleBox物理順序: PHI→materialize→body
mod ssa; // LocalSSA helpers (in-block materialization)
mod stmts;
feat(mir): Phase 136 Step 3/7 - ScopeContext extraction ## Summary Extract scope and control flow management into ScopeContext for better organization. ## Changes - **New file**: src/mir/builder/scope_context.rs (264 lines) - Lexical scope stack management - Control flow stacks (loop/if) - Function context tracking - Debug scope helpers - **Updated**: src/mir/builder.rs - Add scope_ctx field - Mark legacy fields as deprecated - Add sync helpers (sync_scope_ctx_to_legacy, sync_legacy_to_scope_ctx) - **Updated**: src/mir/builder/vars/lexical_scope.rs - Use scope_ctx as SSOT - Sync to legacy fields for backward compat - **Updated**: src/mir/builder/lifecycle.rs - Sync current_function via scope_ctx - **Updated**: src/mir/builder/calls/lowering.rs - Sync function context in lowering flow ## Extracted Fields (7) 1. lexical_scope_stack - Block-scoped locals 2. loop_header_stack - Loop headers for break/continue 3. loop_exit_stack - Loop exit blocks 4. if_merge_stack - If merge blocks 5. current_function - Currently building function 6. function_param_names - Function parameters (for LoopForm) 7. debug_scope_stack - Debug region identifiers ## Test Results - ✅ cargo build --release (291 warnings - deprecated usage) - ✅ cargo test --release --lib - 1005/1009 PASS - ✅ phase135_trim_mir_verify.sh - PASS - ⚠️ phase132_exit_phi_parity.sh - Error (pre-existing issue) ## Progress Phase 136: 3/7 Contexts complete (TypeContext, CoreContext, ScopeContext) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 20:28:21 +09:00
mod scope_context; // Phase 136 follow-up (Step 3/7): ScopeContext extraction
mod type_context; // Phase 136 follow-up: TypeContext extraction
mod type_facts; // Phase 136 follow-up: Type inference facts box
pub(crate) mod type_registry;
mod types; // types::annotation / inference型注釈/推論の箱: 推論は後段)
mod utils;
mod vars; // variables/scope helpers // small loop helpers (header/exit context) // TypeRegistryBox型情報管理の一元化
// Unified member property kinds for computed/once/birth_once
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) enum PropertyKind {
Computed,
Once,
BirthOnce,
}
/// MIR builder for converting AST to SSA form
pub struct MirBuilder {
/// Current module being built
pub(super) current_module: Option<MirModule>,
/// Current basic block being built
pub(super) current_block: Option<BasicBlockId>,
/// Phase 136 follow-up (Step 2/7): Core ID generation context
/// Consolidates value_gen, block_gen, next_binding_id, temp_slot_counter, debug_join_counter.
/// Direct field access for backward compatibility (migration in progress).
pub(super) core_ctx: core_context::CoreContext,
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
/// [DEPRECATED] 箱理論: Static boxコンパイル時のコンテキスト分離
/// Phase 136 Step 7/7: Moved to comp_ctx.compilation_context (backward compat wrapper)
feat(mir/builder): implement BoxCompilationContext for structural metadata isolation 箱理論の完璧な実装!各static boxコンパイルを独立したコンテキストで実行。 設計: - BoxCompilationContext: variable_map, value_origin_newbox, value_types を箱化 - MirBuilder: compilation_context: Option<BoxCompilationContext> フィールド追加 - context swap: lower_static_method_as_function 開始/終了時に std::mem::swap - 自動クリーンアップ: スコープ終了でコンテキスト破棄 実装: 1. src/mir/builder/context.rs: BoxCompilationContext構造体定義(テスト付き) 2. src/mir/builder.rs: compilation_contextフィールド追加、既存フィールドにコメント追加 3. src/mir/builder/lifecycle.rs: 各static boxでコンテキスト作成・破棄 4. src/mir/builder/builder_calls.rs: lower_static_method_as_functionでcontext swap 5. src/mir/builder/decls.rs, exprs.rs: 古いmanual clear()削除 効果: ✅ グローバル状態汚染を構造的に不可能化 ✅ 各static boxが完全に独立したコンテキストでコンパイル ✅ 既存コード変更なし(swap技法で完全後方互換性) ✅ StageBArgsBox ValueId(21)エラー完全解決 箱理論的評価: 🟢 95点 - 明示的な境界: 各boxのコンテキストが物理的に分離 - 汚染不可能: 前の箱の状態が構造的に残らない - 戻せる: コンテキスト差し替えで簡単ロールバック - 美しい設計: スコープベースのリソース管理 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-17 11:28:18 +09:00
/// Some(ctx)の場合、variable_map/value_origin_newbox/value_typesはctxから取得
/// Noneの場合、従来のフィールドを使用後方互換性
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
#[deprecated(note = "Use comp_ctx.compilation_context instead")]
feat(mir/builder): implement BoxCompilationContext for structural metadata isolation 箱理論の完璧な実装!各static boxコンパイルを独立したコンテキストで実行。 設計: - BoxCompilationContext: variable_map, value_origin_newbox, value_types を箱化 - MirBuilder: compilation_context: Option<BoxCompilationContext> フィールド追加 - context swap: lower_static_method_as_function 開始/終了時に std::mem::swap - 自動クリーンアップ: スコープ終了でコンテキスト破棄 実装: 1. src/mir/builder/context.rs: BoxCompilationContext構造体定義(テスト付き) 2. src/mir/builder.rs: compilation_contextフィールド追加、既存フィールドにコメント追加 3. src/mir/builder/lifecycle.rs: 各static boxでコンテキスト作成・破棄 4. src/mir/builder/builder_calls.rs: lower_static_method_as_functionでcontext swap 5. src/mir/builder/decls.rs, exprs.rs: 古いmanual clear()削除 効果: ✅ グローバル状態汚染を構造的に不可能化 ✅ 各static boxが完全に独立したコンテキストでコンパイル ✅ 既存コード変更なし(swap技法で完全後方互換性) ✅ StageBArgsBox ValueId(21)エラー完全解決 箱理論的評価: 🟢 95点 - 明示的な境界: 各boxのコンテキストが物理的に分離 - 汚染不可能: 前の箱の状態が構造的に残らない - 戻せる: コンテキスト差し替えで簡単ロールバック - 美しい設計: スコープベースのリソース管理 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-17 11:28:18 +09:00
pub(super) compilation_context: Option<context::BoxCompilationContext>,
/// Phase 136 follow-up: Type information context
/// Consolidates value_types, value_kinds, value_origin_newbox for better organization.
/// Direct field access for backward compatibility (migration in progress).
pub(super) type_ctx: type_context::TypeContext,
feat(mir): Phase 136 Step 3/7 - ScopeContext extraction ## Summary Extract scope and control flow management into ScopeContext for better organization. ## Changes - **New file**: src/mir/builder/scope_context.rs (264 lines) - Lexical scope stack management - Control flow stacks (loop/if) - Function context tracking - Debug scope helpers - **Updated**: src/mir/builder.rs - Add scope_ctx field - Mark legacy fields as deprecated - Add sync helpers (sync_scope_ctx_to_legacy, sync_legacy_to_scope_ctx) - **Updated**: src/mir/builder/vars/lexical_scope.rs - Use scope_ctx as SSOT - Sync to legacy fields for backward compat - **Updated**: src/mir/builder/lifecycle.rs - Sync current_function via scope_ctx - **Updated**: src/mir/builder/calls/lowering.rs - Sync function context in lowering flow ## Extracted Fields (7) 1. lexical_scope_stack - Block-scoped locals 2. loop_header_stack - Loop headers for break/continue 3. loop_exit_stack - Loop exit blocks 4. if_merge_stack - If merge blocks 5. current_function - Currently building function 6. function_param_names - Function parameters (for LoopForm) 7. debug_scope_stack - Debug region identifiers ## Test Results - ✅ cargo build --release (291 warnings - deprecated usage) - ✅ cargo test --release --lib - 1005/1009 PASS - ✅ phase135_trim_mir_verify.sh - PASS - ⚠️ phase132_exit_phi_parity.sh - Error (pre-existing issue) ## Progress Phase 136: 3/7 Contexts complete (TypeContext, CoreContext, ScopeContext) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 20:28:21 +09:00
/// Phase 136 follow-up (Step 3/7): Scope and control flow context
/// Consolidates lexical_scope_stack, loop stacks, if_merge_stack, current_function,
/// function_param_names, debug_scope_stack for better organization.
/// Direct field access for backward compatibility (migration in progress).
pub(super) scope_ctx: scope_context::ScopeContext,
/// Phase 136 follow-up (Step 4/7): Binding context
/// Consolidates binding_map (String -> BindingId mapping).
/// Direct field access for backward compatibility (migration in progress).
pub(super) binding_ctx: binding_context::BindingContext,
refactor(mir): Extract VariableContext from MirBuilder (Phase 136 follow-up 5/7) ## Summary Extracted variable mapping management into dedicated VariableContext struct, completing step 5 of 7 in the Context Box refactoring plan. ## Changes - NEW: src/mir/builder/variable_context.rs (VariableContext struct + helpers) - Modified: src/mir/builder.rs (added variable_ctx field + sync helpers) - Updated: phase-136-context-box-progress.md (5/7 progress) ## Extracted Fields - variable_map: BTreeMap<String, ValueId> → variable_ctx.variable_map ## Key Features - snapshot/restore for if/loop pattern state management - JoinIR integration: CarrierInfo::from_variable_map() - ExitLine contract enforcement (carriers in variable_map) - NYASH_TRACE_VARMAP debug visualization support ## Design Clarity - BindingContext: String → BindingId (binding identity, survives SSA renaming) - VariableContext: String → ValueId (current SSA values, block-local) - Both contexts work together for complete variable management ## Tests - cargo test --release --lib: 1014/1018 passed (4 pre-existing failures) - phase135_trim_mir_verify.sh: PASS - Backward compatibility: 100% maintained (deprecated fields synced) ## Progress Phase 136 Context Extraction: 5/7 complete (71%) - ✅ Step 1: TypeContext - ✅ Step 2: CoreContext - ✅ Step 3: ScopeContext - ✅ Step 4: BindingContext - ✅ Step 5: VariableContext (this commit) - ⏳ Step 6: MetadataContext - ⏳ Step 7: CompilationContext 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 21:50:50 +09:00
/// Phase 136 follow-up (Step 5/7): Variable context
/// Consolidates variable_map (String -> ValueId mapping for SSA conversion).
/// Direct field access for backward compatibility (migration in progress).
pub(super) variable_ctx: variable_context::VariableContext,
refactor(mir): Extract MetadataContext from MirBuilder (Phase 136 follow-up 6/7) ## Summary Extracted metadata and debug information management into dedicated MetadataContext struct, completing step 6 of 7 in the Context Box refactoring plan. ## Changes - NEW: src/mir/builder/metadata_context.rs (MetadataContext struct + helpers) - Modified: src/mir/builder.rs (added metadata_ctx field + sync helpers) - Modified: src/mir/hints.rs (added Clone + Debug derives to HintSink) - Updated: phase-136-context-box-progress.md (6/7 progress) ## Extracted Fields - current_span: Span → metadata_ctx.current_span - source_file: Option<String> → metadata_ctx.source_file - hint_sink: HintSink → metadata_ctx.hint_sink - current_region_stack: Vec<RegionId> → metadata_ctx.current_region_stack ## Key Features - Zero-cost type inference hints (HintSink) - Source position tracking for error messages - Region observation stack for debug builds - Phase 135 contract_checks integration ## Tests - cargo test --release --lib: 1019/1023 passed (4 pre-existing failures) - phase135_trim_mir_verify.sh: PASS - Backward compatibility: 100% maintained (deprecated fields synced) ## Progress Phase 136 Context Extraction: 6/7 complete (86%) - ✅ Step 1: TypeContext - ✅ Step 2: CoreContext - ✅ Step 3: ScopeContext - ✅ Step 4: BindingContext - ✅ Step 5: VariableContext - ✅ Step 6: MetadataContext (this commit) - ⏳ Step 7: CompilationContext 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:03:34 +09:00
/// Phase 136 follow-up (Step 6/7): Metadata context
/// Consolidates current_span, source_file, hint_sink, current_region_stack.
/// Direct field access for backward compatibility (migration in progress).
pub(super) metadata_ctx: metadata_context::MetadataContext,
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
/// Phase 136 follow-up (Step 7/7): Compilation context
/// Consolidates compilation_context, current_static_box, user_defined_boxes, reserved_value_ids,
/// fn_body_ast, weak_fields_by_box, property_getters_by_box, field_origin_class, field_origin_by_box,
/// static_method_index, method_tail_index, type_registry, current_slot_registry, plugin_method_sigs.
/// Direct field access for backward compatibility (migration in progress).
pub(super) comp_ctx: compilation_context::CompilationContext,
refactor(mir): Extract VariableContext from MirBuilder (Phase 136 follow-up 5/7) ## Summary Extracted variable mapping management into dedicated VariableContext struct, completing step 5 of 7 in the Context Box refactoring plan. ## Changes - NEW: src/mir/builder/variable_context.rs (VariableContext struct + helpers) - Modified: src/mir/builder.rs (added variable_ctx field + sync helpers) - Updated: phase-136-context-box-progress.md (5/7 progress) ## Extracted Fields - variable_map: BTreeMap<String, ValueId> → variable_ctx.variable_map ## Key Features - snapshot/restore for if/loop pattern state management - JoinIR integration: CarrierInfo::from_variable_map() - ExitLine contract enforcement (carriers in variable_map) - NYASH_TRACE_VARMAP debug visualization support ## Design Clarity - BindingContext: String → BindingId (binding identity, survives SSA renaming) - VariableContext: String → ValueId (current SSA values, block-local) - Both contexts work together for complete variable management ## Tests - cargo test --release --lib: 1014/1018 passed (4 pre-existing failures) - phase135_trim_mir_verify.sh: PASS - Backward compatibility: 100% maintained (deprecated fields synced) ## Progress Phase 136 Context Extraction: 5/7 complete (71%) - ✅ Step 1: TypeContext - ✅ Step 2: CoreContext - ✅ Step 3: ScopeContext - ✅ Step 4: BindingContext - ✅ Step 5: VariableContext (this commit) - ⏳ Step 6: MetadataContext - ⏳ Step 7: CompilationContext 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 21:50:50 +09:00
/// [DEPRECATED] Variable name to ValueId mapping (for SSA conversion)
/// Phase 136 Step 5/7: Moved to variable_ctx.variable_map (backward compat wrapper)
feat(mir/builder): implement BoxCompilationContext for structural metadata isolation 箱理論の完璧な実装!各static boxコンパイルを独立したコンテキストで実行。 設計: - BoxCompilationContext: variable_map, value_origin_newbox, value_types を箱化 - MirBuilder: compilation_context: Option<BoxCompilationContext> フィールド追加 - context swap: lower_static_method_as_function 開始/終了時に std::mem::swap - 自動クリーンアップ: スコープ終了でコンテキスト破棄 実装: 1. src/mir/builder/context.rs: BoxCompilationContext構造体定義(テスト付き) 2. src/mir/builder.rs: compilation_contextフィールド追加、既存フィールドにコメント追加 3. src/mir/builder/lifecycle.rs: 各static boxでコンテキスト作成・破棄 4. src/mir/builder/builder_calls.rs: lower_static_method_as_functionでcontext swap 5. src/mir/builder/decls.rs, exprs.rs: 古いmanual clear()削除 効果: ✅ グローバル状態汚染を構造的に不可能化 ✅ 各static boxが完全に独立したコンテキストでコンパイル ✅ 既存コード変更なし(swap技法で完全後方互換性) ✅ StageBArgsBox ValueId(21)エラー完全解決 箱理論的評価: 🟢 95点 - 明示的な境界: 各boxのコンテキストが物理的に分離 - 汚染不可能: 前の箱の状態が構造的に残らない - 戻せる: コンテキスト差し替えで簡単ロールバック - 美しい設計: スコープベースのリソース管理 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-17 11:28:18 +09:00
/// 注意: compilation_contextがSomeの場合は使用されません
/// Phase 25.1: HashMap → BTreeMapPHI生成の決定性確保
refactor(mir): Extract VariableContext from MirBuilder (Phase 136 follow-up 5/7) ## Summary Extracted variable mapping management into dedicated VariableContext struct, completing step 5 of 7 in the Context Box refactoring plan. ## Changes - NEW: src/mir/builder/variable_context.rs (VariableContext struct + helpers) - Modified: src/mir/builder.rs (added variable_ctx field + sync helpers) - Updated: phase-136-context-box-progress.md (5/7 progress) ## Extracted Fields - variable_map: BTreeMap<String, ValueId> → variable_ctx.variable_map ## Key Features - snapshot/restore for if/loop pattern state management - JoinIR integration: CarrierInfo::from_variable_map() - ExitLine contract enforcement (carriers in variable_map) - NYASH_TRACE_VARMAP debug visualization support ## Design Clarity - BindingContext: String → BindingId (binding identity, survives SSA renaming) - VariableContext: String → ValueId (current SSA values, block-local) - Both contexts work together for complete variable management ## Tests - cargo test --release --lib: 1014/1018 passed (4 pre-existing failures) - phase135_trim_mir_verify.sh: PASS - Backward compatibility: 100% maintained (deprecated fields synced) ## Progress Phase 136 Context Extraction: 5/7 complete (71%) - ✅ Step 1: TypeContext - ✅ Step 2: CoreContext - ✅ Step 3: ScopeContext - ✅ Step 4: BindingContext - ✅ Step 5: VariableContext (this commit) - ⏳ Step 6: MetadataContext - ⏳ Step 7: CompilationContext 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 21:50:50 +09:00
#[deprecated(note = "Use variable_ctx.variable_map instead")]
pub(super) variable_map: BTreeMap<String, ValueId>,
/// Pending phi functions to be inserted
#[allow(dead_code)]
pub(super) pending_phis: Vec<(BasicBlockId, ValueId, String)>,
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
/// [DEPRECATED] Names of user-defined boxes declared in the current module
/// Phase 136 Step 7/7: Moved to comp_ctx.user_defined_boxes (backward compat wrapper)
#[deprecated(note = "Use comp_ctx.user_defined_boxes instead")]
docs: Add field visibility analysis and MIR BoxCall documentation ## Field Visibility Analysis Results - Confirmed init{} fields are **public** in current Nyash implementation - No access modifier (private/public) system currently implemented - All fields accessible via me.fieldname syntax - Documented findings for future reference ## MIR Documentation Enhancements - Created comprehensive mir-dumper-guide.md for reading MIR dumps - Enhanced mir-26-specification.md with BoxCall vs regular Call examples - Added clear identification patterns: * BoxCall: `call %value.method(args)` (plugins/builtins) * Regular Call: `call %func(%me, args)` (user-defined boxes) ## VM Backend BoxRef Handling Improvements - Fixed BoxRef method dispatch using share_box() instead of clone_box() - Prevents unintended constructor calls during method resolution - Maintains proper instance identity throughout VM execution ## MIR Builder User-Defined Box Tracking - Added user_defined_boxes HashSet to track declared user boxes - Improved method lowering decisions for user-defined vs builtin boxes - Enhanced AST→MIR conversion accuracy for method calls ## Plugin Tester Lifecycle Enhancements - Added comprehensive FileBox lifecycle testing (open/write/close) - Enhanced cloneSelf() and copyFrom() testing with proper Handle parsing - Added TLV encoding helpers for strings and bytes - Improved error reporting and step-by-step validation 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-08-21 01:18:25 +09:00
pub(super) user_defined_boxes: HashSet<String>,
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
/// [DEPRECATED] Weak field registry: BoxName -> {weak field names}
/// Phase 136 Step 7/7: Moved to comp_ctx.weak_fields_by_box (backward compat wrapper)
#[deprecated(note = "Use comp_ctx.weak_fields_by_box instead")]
pub(super) weak_fields_by_box: HashMap<String, HashSet<String>>,
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
/// [DEPRECATED] Unified members: BoxName -> {propName -> Kind}
/// Phase 136 Step 7/7: Moved to comp_ctx.property_getters_by_box (backward compat wrapper)
#[deprecated(note = "Use comp_ctx.property_getters_by_box instead")]
pub(super) property_getters_by_box: HashMap<String, HashMap<String, PropertyKind>>,
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
/// [DEPRECATED] Remember class of object fields after assignments: (base_id, field) -> class_name
/// Phase 136 Step 7/7: Moved to comp_ctx.field_origin_class (backward compat wrapper)
#[deprecated(note = "Use comp_ctx.field_origin_class instead")]
pub(super) field_origin_class: HashMap<(ValueId, String), String>,
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
/// [DEPRECATED] Class-level field origin (cross-function heuristic): (BaseBoxName, field) -> FieldBoxName
/// Phase 136 Step 7/7: Moved to comp_ctx.field_origin_by_box (backward compat wrapper)
#[deprecated(note = "Use comp_ctx.field_origin_by_box instead")]
pub(super) field_origin_by_box: HashMap<(String, String), String>,
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
/// [DEPRECATED] 関数スコープの SlotRegistry観測専用
/// Phase 136 Step 7/7: Moved to comp_ctx.current_slot_registry (backward compat wrapper)
/// - current_function と同じライフサイクルを持つよ。
/// - 既存の variable_map/SSA には影響しない(メタデータのみ)。
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
#[deprecated(note = "Use comp_ctx.current_slot_registry instead")]
pub(super) current_slot_registry: Option<FunctionSlotRegistry>,
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
/// [DEPRECATED] 🎯 箱理論: 型情報管理の一元化TypeRegistryBox
/// Phase 136 Step 7/7: Moved to comp_ctx.type_registry (backward compat wrapper)
feat(builder): CalleeBoxKind構造ガードで静的/ランタイムBox混線を根絶 🎯 箱理論の実践: 「境界を作る」原則による構造レベル分離 ## 問題 - StageBArgsBox.resolve_src内のargs.get(i)が Stage1UsingResolverBox.getに化ける(静的Box名混入) - 未定義ValueIdエラー発生(receiver定義なし) ## 解決策(構造ガード) ✅ CalleeBoxKind enum追加 - StaticCompiler: Stage-B/Stage-1コンパイラBox - RuntimeData: MapBox/ArrayBox等ランタイムBox - UserDefined: ユーザー定義Box ✅ classify_box_kind(): Box名から種別判定 - 静的Box群を明示的に列挙(1箇所に集約) - ランタイムBox群を明示的に列挙 - 将来の拡張も容易 ✅ apply_static_runtime_guard(): 混線検出・正規化 - me-call判定(receiver型==box_name → 静的降下に委ねる) - 真の混線検出(receiver型≠box_name → 正規化) - トレースログで可視化 ## 効果 - 修正前: Invalid value ValueId(150/187) - 修正後: Unknown method 'is_space' (別issue、StringBox実装不足) - → 静的Box名混入問題を根絶! ## 箱理論原則 - ✅ 境界を作る: Static/Runtime/UserDefinedを構造的に分離 - ✅ Fail-Fast: フォールバックより明示的エラー - ✅ 箱にする: CalleeBoxKindでBox種類を1箇所に集約 ## ファイル - src/mir/definitions/call_unified.rs: CalleeBoxKind enum - src/mir/builder/calls/call_unified.rs: classify_box_kind() - src/mir/builder/calls/emit.rs: apply_static_runtime_guard() - docs/development/roadmap/phases/phase-25.1d/README.md: 箱化メモ更新 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-17 23:13:57 +09:00
/// NYASH_USE_TYPE_REGISTRY=1 で有効化(段階的移行用)
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
#[deprecated(note = "Use comp_ctx.type_registry instead")]
feat(builder): CalleeBoxKind構造ガードで静的/ランタイムBox混線を根絶 🎯 箱理論の実践: 「境界を作る」原則による構造レベル分離 ## 問題 - StageBArgsBox.resolve_src内のargs.get(i)が Stage1UsingResolverBox.getに化ける(静的Box名混入) - 未定義ValueIdエラー発生(receiver定義なし) ## 解決策(構造ガード) ✅ CalleeBoxKind enum追加 - StaticCompiler: Stage-B/Stage-1コンパイラBox - RuntimeData: MapBox/ArrayBox等ランタイムBox - UserDefined: ユーザー定義Box ✅ classify_box_kind(): Box名から種別判定 - 静的Box群を明示的に列挙(1箇所に集約) - ランタイムBox群を明示的に列挙 - 将来の拡張も容易 ✅ apply_static_runtime_guard(): 混線検出・正規化 - me-call判定(receiver型==box_name → 静的降下に委ねる) - 真の混線検出(receiver型≠box_name → 正規化) - トレースログで可視化 ## 効果 - 修正前: Invalid value ValueId(150/187) - 修正後: Unknown method 'is_space' (別issue、StringBox実装不足) - → 静的Box名混入問題を根絶! ## 箱理論原則 - ✅ 境界を作る: Static/Runtime/UserDefinedを構造的に分離 - ✅ Fail-Fast: フォールバックより明示的エラー - ✅ 箱にする: CalleeBoxKindでBox種類を1箇所に集約 ## ファイル - src/mir/definitions/call_unified.rs: CalleeBoxKind enum - src/mir/builder/calls/call_unified.rs: classify_box_kind() - src/mir/builder/calls/emit.rs: apply_static_runtime_guard() - docs/development/roadmap/phases/phase-25.1d/README.md: 箱化メモ更新 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-17 23:13:57 +09:00
pub(super) type_registry: type_registry::TypeRegistry,
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
/// [DEPRECATED] Plugin method return type signatures loaded from nyash_box.toml
/// Phase 136 Step 7/7: Moved to comp_ctx.plugin_method_sigs (backward compat wrapper)
#[deprecated(note = "Use comp_ctx.plugin_method_sigs instead")]
plugin_method_sigs: HashMap<(String, String), super::MirType>,
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
/// [DEPRECATED] Current static box name when lowering a static box body (e.g., "Main")
/// Phase 136 Step 7/7: Moved to comp_ctx.current_static_box (backward compat wrapper)
#[deprecated(note = "Use comp_ctx.current_static_box instead")]
current_static_box: Option<String>,
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
/// [DEPRECATED] Index of static methods seen during lowering: name -> [(BoxName, arity)]
/// Phase 136 Step 7/7: Moved to comp_ctx.static_method_index (backward compat wrapper)
#[deprecated(note = "Use comp_ctx.static_method_index instead")]
pub(super) static_method_index: std::collections::HashMap<String, Vec<(String, usize)>>,
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
/// [DEPRECATED] Fast lookup: method+arity tail → candidate function names (e.g., ".str/0" → ["JsonNode.str/0", ...])
/// Phase 136 Step 7/7: Moved to comp_ctx.method_tail_index (backward compat wrapper)
#[deprecated(note = "Use comp_ctx.method_tail_index instead")]
pub(super) method_tail_index: std::collections::HashMap<String, Vec<String>>,
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
/// [DEPRECATED] Source size snapshot to detect when to rebuild the tail index
/// Phase 136 Step 7/7: Moved to comp_ctx.method_tail_index_source_len (backward compat wrapper)
#[deprecated(note = "Use comp_ctx.method_tail_index_source_len instead")]
pub(super) method_tail_index_source_len: usize,
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
/// [DEPRECATED] Phase 200-C: Original function body AST for capture analysis
/// Phase 136 Step 7/7: Moved to comp_ctx.fn_body_ast (backward compat wrapper)
/// Stored temporarily during function lowering to support FunctionScopeCaptureAnalyzer.
/// None when not lowering a function, or when fn_body is not available.
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
#[deprecated(note = "Use comp_ctx.fn_body_ast instead")]
pub(super) fn_body_ast: Option<Vec<ASTNode>>,
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
/// [DEPRECATED] Phase 201-A: Reserved ValueIds that must not be allocated
/// Phase 136 Step 7/7: Moved to comp_ctx.reserved_value_ids (backward compat wrapper)
/// These are PHI dst ValueIds created by LoopHeaderPhiBuilder.
/// When next_value_id() encounters a reserved ID, it skips to the next.
/// Cleared after JoinIR merge completes.
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
#[deprecated(note = "Use comp_ctx.reserved_value_ids instead")]
pub(super) reserved_value_ids: HashSet<ValueId>,
// Phase 2-5: binding_map removed - use binding_ctx.binding_map instead
feat: using構文完全実装&json_native大幅進化 ## 🎉 using構文の完全実装(ChatGPT作業) - ✅ **include → using移行完了**: 全ファイルでusing構文に統一 - `local X = include` → `using "path" as X` - 約70ファイルを一括変換 - ✅ **AST/パーサー/MIR完全対応**: using専用処理実装 - ASTNode::Using追加 - MIRビルダーでの解決処理 - include互換性も維持 ## 🚀 json_native実装進化(ChatGPT追加実装) - ✅ **浮動小数点対応追加**: is_float/parse_float実装 - ✅ **配列/オブジェクトパーサー実装**: parse_array/parse_object完成 - ✅ **エスケープ処理強化**: Unicode対応、全制御文字サポート - ✅ **StringUtils大幅拡張**: 文字列操作メソッド多数追加 - contains, index_of_string, split, join等 - 大文字小文字変換(全アルファベット対応) ## 💡 MIR SIMD & ハイブリッド戦略考察 - **MIR15 SIMD命令案**: SimdLoad/SimdScan等の新命令セット - **C ABIハイブリッド**: ホットパスのみC委託で10倍速化可能 - **並行処理でyyjson超え**: 100KB以上で2-10倍速の可能性 - **3層アーキテクチャ**: Nyash層/MIR層/C ABI層の美しい分離 ## 📊 技術的成果 - using構文により名前空間管理が明確化 - json_nativeが実用レベルに接近(完成度25%→40%) - 将来的にyyjsonの70%速度達成可能と判明 ChatGPT爆速実装×Claude深い考察の完璧な協働! 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-25 00:41:56 +09:00
// include guards removed
// フェーズM: no_phi_modeフィールド削除常にPHI使用
// ---- Try/Catch/Cleanup lowering context ----
/// When true, `return` statements are deferred: they assign to `return_defer_slot`
/// and jump to `return_defer_target` (typically the cleanup/exit block).
pub(super) return_defer_active: bool,
/// Slot value to receive deferred return values (edge-copy mode friendly).
pub(super) return_defer_slot: Option<ValueId>,
/// Target block to jump to on deferred return.
pub(super) return_defer_target: Option<BasicBlockId>,
/// Set to true when a deferred return has been emitted in the current context.
pub(super) return_deferred_emitted: bool,
/// True while lowering the cleanup block.
pub(super) in_cleanup_block: bool,
/// Policy flags (snapshotted at entry of try/catch lowering)
pub(super) cleanup_allow_return: bool,
pub(super) cleanup_allow_throw: bool,
/// If true, skip entry materialization of pinned slots on the next start_new_block call.
suppress_pin_entry_copy_next: bool,
// ----------------------
// Debug scope context (dev only; zero-cost when unused)
// ----------------------
/// Local SSA cache: ensure per-block materialization for critical operands (e.g., recv)
/// Key: (bb, original ValueId, kind) -> local ValueId
/// kind: 0=recv, 1+ reserved for future (args etc.)
pub(super) local_ssa_map: HashMap<(BasicBlockId, ValueId, u8), ValueId>,
/// BlockSchedule cache: deduplicate materialize copies per (bb, src)
pub(super) schedule_mat_map: HashMap<(BasicBlockId, ValueId), ValueId>,
/// Mapping from ValueId to its pin slot name (e.g., "__pin$3$@recv")
/// Used by LocalSSA to redirect old pinned values to the latest slot value.
pub(super) pin_slot_names: HashMap<ValueId, String>,
fix(builder): 修正案A実装 - emit_unified_call↔emit_box_or_plugin_call再入防止 🎯 無限再帰の構造的防止(修正案A採用) ## 問題 Phase 2リファクタリング後、stack overflow発生: ``` emit_unified_call (emit.rs:15) ↓ emit_box_or_plugin_call (utils.rs:136) ↓ line 190 emit_unified_call (emit.rs:15) ← 無限ループ! ``` ## 修正案A: 再入防止ガード(採用理由) - B(Math機能削除): 対処療法で仕様削減 ❌ - C("birth"特別扱い): 局所的修正で他Boxに波及 ❌ - A(構造的再入防止): 根治的アプローチ ✅ ## 実装内容 ### 1. MirBuilder にフラグ追加 ```rust pub(super) in_unified_boxcall_fallback: bool ``` 役割: RouterPolicyでRoute::BoxCallと決めたフォールバック中マーク ### 2. emit_unified_call 側修正 (emit.rs) ```rust // Route::BoxCall のときだけ self.in_unified_boxcall_fallback = true; emit_box_or_plugin_call(...); self.in_unified_boxcall_fallback = false; ``` ### 3. emit_box_or_plugin_call 側修正 (utils.rs) ```rust if use_unified_env && matches!(route, Route::Unified) && !self.in_unified_boxcall_fallback // ← 追加 { // emit_unified_call(...) への再入を防止 } ``` ## 構造的改善 - RouterPolicyBox の決定を優先 - emit_unified_call → emit_box_or_plugin_call の一方向化 - 「上位の決定を尊重する」という明確なルール ## 残存課題 ⚠️ まだstack overflowが残存(別の再帰ルート存在の可能性) → 次のステップでstack trace解析が必要 ## テスト状況 - Test 1 (Direct VM): ✅ 成功 - Test 2 (Stage-B): ❌ stack overflow(別ルート調査中) - Test 3 (MIR verification): ✅ 成功 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-17 17:31:09 +09:00
/// Guard flag to prevent re-entering emit_unified_call from BoxCall fallback.
/// Used when RouterPolicyBox in emit_unified_call has already decided to
/// route a given Method call to BoxCall; emit_box_or_plugin_call must not
/// bounce back into the unified path for the same call, otherwise an
/// infinite recursion (emit_unified_call → emit_box_or_plugin_call →
/// emit_unified_call …) can occur when routing decisions disagree.
pub(super) in_unified_boxcall_fallback: bool,
/// Recursion depth counter for debugging stack overflow
/// Tracks the depth of build_expression calls to detect infinite loops
pub(super) recursion_depth: usize,
📦 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
/// Root lowering mode: how to treat top-level Program
/// - None: not decided yet (lower_root not called)
/// - Some(true): App mode (static box Main.main is entry)
/// - Some(false): Script/Test mode (top-level Program runs sequentially)
pub(super) root_is_app_mode: Option<bool>,
/// 🎯 Phase 21.7: Static box singleton instances for methodization
/// Maps BoxName → ValueId of singleton instance (created on demand)
/// Used when HAKO_MIR_BUILDER_METHODIZE=1 to convert Global("BoxName.method/arity")
/// to Method{receiver=singleton} calls
pub(super) static_box_singletons: HashMap<String, ValueId>,
}
impl MirBuilder {
/// Create a new MIR builder
pub fn new() -> Self {
2025-09-11 04:20:28 +09:00
let plugin_method_sigs = plugin_sigs::load_plugin_method_sigs();
let core_ctx = core_context::CoreContext::new();
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
// Phase 136 Step 7/7: Compilation context (new SSOT)
let comp_ctx = compilation_context::CompilationContext::with_plugin_sigs(plugin_method_sigs.clone());
// フェーズM: no_phi_mode初期化削除
#[allow(deprecated)]
Self {
current_module: None,
current_block: None,
// Phase 136 Step 2/7: Core context (new SSOT)
core_ctx,
compilation_context: None, // 箱理論: デフォルトは従来モード
type_ctx: type_context::TypeContext::new(), // Phase 136: Type context
feat(mir): Phase 136 Step 3/7 - ScopeContext extraction ## Summary Extract scope and control flow management into ScopeContext for better organization. ## Changes - **New file**: src/mir/builder/scope_context.rs (264 lines) - Lexical scope stack management - Control flow stacks (loop/if) - Function context tracking - Debug scope helpers - **Updated**: src/mir/builder.rs - Add scope_ctx field - Mark legacy fields as deprecated - Add sync helpers (sync_scope_ctx_to_legacy, sync_legacy_to_scope_ctx) - **Updated**: src/mir/builder/vars/lexical_scope.rs - Use scope_ctx as SSOT - Sync to legacy fields for backward compat - **Updated**: src/mir/builder/lifecycle.rs - Sync current_function via scope_ctx - **Updated**: src/mir/builder/calls/lowering.rs - Sync function context in lowering flow ## Extracted Fields (7) 1. lexical_scope_stack - Block-scoped locals 2. loop_header_stack - Loop headers for break/continue 3. loop_exit_stack - Loop exit blocks 4. if_merge_stack - If merge blocks 5. current_function - Currently building function 6. function_param_names - Function parameters (for LoopForm) 7. debug_scope_stack - Debug region identifiers ## Test Results - ✅ cargo build --release (291 warnings - deprecated usage) - ✅ cargo test --release --lib - 1005/1009 PASS - ✅ phase135_trim_mir_verify.sh - PASS - ⚠️ phase132_exit_phi_parity.sh - Error (pre-existing issue) ## Progress Phase 136: 3/7 Contexts complete (TypeContext, CoreContext, ScopeContext) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 20:28:21 +09:00
scope_ctx: scope_context::ScopeContext::new(), // Phase 136 Step 3/7: Scope context
binding_ctx: binding_context::BindingContext::new(), // Phase 136 Step 4/7: Binding context
refactor(mir): Extract VariableContext from MirBuilder (Phase 136 follow-up 5/7) ## Summary Extracted variable mapping management into dedicated VariableContext struct, completing step 5 of 7 in the Context Box refactoring plan. ## Changes - NEW: src/mir/builder/variable_context.rs (VariableContext struct + helpers) - Modified: src/mir/builder.rs (added variable_ctx field + sync helpers) - Updated: phase-136-context-box-progress.md (5/7 progress) ## Extracted Fields - variable_map: BTreeMap<String, ValueId> → variable_ctx.variable_map ## Key Features - snapshot/restore for if/loop pattern state management - JoinIR integration: CarrierInfo::from_variable_map() - ExitLine contract enforcement (carriers in variable_map) - NYASH_TRACE_VARMAP debug visualization support ## Design Clarity - BindingContext: String → BindingId (binding identity, survives SSA renaming) - VariableContext: String → ValueId (current SSA values, block-local) - Both contexts work together for complete variable management ## Tests - cargo test --release --lib: 1014/1018 passed (4 pre-existing failures) - phase135_trim_mir_verify.sh: PASS - Backward compatibility: 100% maintained (deprecated fields synced) ## Progress Phase 136 Context Extraction: 5/7 complete (71%) - ✅ Step 1: TypeContext - ✅ Step 2: CoreContext - ✅ Step 3: ScopeContext - ✅ Step 4: BindingContext - ✅ Step 5: VariableContext (this commit) - ⏳ Step 6: MetadataContext - ⏳ Step 7: CompilationContext 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 21:50:50 +09:00
variable_ctx: variable_context::VariableContext::new(), // Phase 136 Step 5/7: Variable context
refactor(mir): Extract MetadataContext from MirBuilder (Phase 136 follow-up 6/7) ## Summary Extracted metadata and debug information management into dedicated MetadataContext struct, completing step 6 of 7 in the Context Box refactoring plan. ## Changes - NEW: src/mir/builder/metadata_context.rs (MetadataContext struct + helpers) - Modified: src/mir/builder.rs (added metadata_ctx field + sync helpers) - Modified: src/mir/hints.rs (added Clone + Debug derives to HintSink) - Updated: phase-136-context-box-progress.md (6/7 progress) ## Extracted Fields - current_span: Span → metadata_ctx.current_span - source_file: Option<String> → metadata_ctx.source_file - hint_sink: HintSink → metadata_ctx.hint_sink - current_region_stack: Vec<RegionId> → metadata_ctx.current_region_stack ## Key Features - Zero-cost type inference hints (HintSink) - Source position tracking for error messages - Region observation stack for debug builds - Phase 135 contract_checks integration ## Tests - cargo test --release --lib: 1019/1023 passed (4 pre-existing failures) - phase135_trim_mir_verify.sh: PASS - Backward compatibility: 100% maintained (deprecated fields synced) ## Progress Phase 136 Context Extraction: 6/7 complete (86%) - ✅ Step 1: TypeContext - ✅ Step 2: CoreContext - ✅ Step 3: ScopeContext - ✅ Step 4: BindingContext - ✅ Step 5: VariableContext - ✅ Step 6: MetadataContext (this commit) - ⏳ Step 7: CompilationContext 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:03:34 +09:00
metadata_ctx: metadata_context::MetadataContext::new(), // Phase 136 Step 6/7: Metadata context
feat(mir): Phase 136 Step 7/7 - CompilationContext extraction **Step 7/7 Complete**: Extract compilation-related fields into CompilationContext **抽出したフィールド** (15個): - compilation_context: Box compilation context - current_static_box: Current static box name - user_defined_boxes: User-defined box registry - reserved_value_ids: Reserved ValueIds for PHI - fn_body_ast: Function body AST for capture analysis - weak_fields_by_box: Weak field registry - property_getters_by_box: Property getter registry - field_origin_class: Field origin tracking - field_origin_by_box: Class-level field origin - static_method_index: Static method index - method_tail_index: Method tail index (fast lookup) - method_tail_index_source_len: Source size snapshot - type_registry: Type registry (TypeRegistryBox) - current_slot_registry: Function scope SlotRegistry - plugin_method_sigs: Plugin method signatures **新規ファイル**: - src/mir/builder/compilation_context.rs (435 lines) - CompilationContext struct with 15 fields - Helper methods for all compilation operations - Comprehensive tests (13 test cases) **MirBuilder 統合**: - Added comp_ctx: CompilationContext field - Marked 15 legacy fields as #[deprecated] - CompilationContext::with_plugin_sigs() initialization **テスト結果**: - ✅ cargo build --release (469 warnings - deprecated) - ✅ cargo test --release --lib (1029/1033 PASS) - ✅ phase135_trim_mir_verify.sh (PASS) **影響範囲**: - 12 files use comp_ctx fields (87 total usages) - 36 deprecated fields in builder.rs (ready for Phase 2 cleanup) **Phase 136 Status**: ✅ 7/7 Context Boxes Complete! - TypeContext, CoreContext, ScopeContext (Steps 1-3) - BindingContext, VariableContext, MetadataContext (Steps 4-6) - CompilationContext (Step 7) - NOW COMPLETE **Next Phase**: Legacy field deletion (Phase 2) - Remove #[deprecated] fields from builder.rs - Migrate all code to ctx accessors - Reduce deprecation warnings from 469 → 0 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:12:33 +09:00
comp_ctx, // Phase 136 Step 7/7: Compilation context
refactor(mir): Extract VariableContext from MirBuilder (Phase 136 follow-up 5/7) ## Summary Extracted variable mapping management into dedicated VariableContext struct, completing step 5 of 7 in the Context Box refactoring plan. ## Changes - NEW: src/mir/builder/variable_context.rs (VariableContext struct + helpers) - Modified: src/mir/builder.rs (added variable_ctx field + sync helpers) - Updated: phase-136-context-box-progress.md (5/7 progress) ## Extracted Fields - variable_map: BTreeMap<String, ValueId> → variable_ctx.variable_map ## Key Features - snapshot/restore for if/loop pattern state management - JoinIR integration: CarrierInfo::from_variable_map() - ExitLine contract enforcement (carriers in variable_map) - NYASH_TRACE_VARMAP debug visualization support ## Design Clarity - BindingContext: String → BindingId (binding identity, survives SSA renaming) - VariableContext: String → ValueId (current SSA values, block-local) - Both contexts work together for complete variable management ## Tests - cargo test --release --lib: 1014/1018 passed (4 pre-existing failures) - phase135_trim_mir_verify.sh: PASS - Backward compatibility: 100% maintained (deprecated fields synced) ## Progress Phase 136 Context Extraction: 5/7 complete (71%) - ✅ Step 1: TypeContext - ✅ Step 2: CoreContext - ✅ Step 3: ScopeContext - ✅ Step 4: BindingContext - ✅ Step 5: VariableContext (this commit) - ⏳ Step 6: MetadataContext - ⏳ Step 7: CompilationContext 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 21:50:50 +09:00
variable_map: BTreeMap::new(), // Phase 25.1: 決定性確保 (backward compat)
pending_phis: Vec::new(),
docs: Add field visibility analysis and MIR BoxCall documentation ## Field Visibility Analysis Results - Confirmed init{} fields are **public** in current Nyash implementation - No access modifier (private/public) system currently implemented - All fields accessible via me.fieldname syntax - Documented findings for future reference ## MIR Documentation Enhancements - Created comprehensive mir-dumper-guide.md for reading MIR dumps - Enhanced mir-26-specification.md with BoxCall vs regular Call examples - Added clear identification patterns: * BoxCall: `call %value.method(args)` (plugins/builtins) * Regular Call: `call %func(%me, args)` (user-defined boxes) ## VM Backend BoxRef Handling Improvements - Fixed BoxRef method dispatch using share_box() instead of clone_box() - Prevents unintended constructor calls during method resolution - Maintains proper instance identity throughout VM execution ## MIR Builder User-Defined Box Tracking - Added user_defined_boxes HashSet to track declared user boxes - Improved method lowering decisions for user-defined vs builtin boxes - Enhanced AST→MIR conversion accuracy for method calls ## Plugin Tester Lifecycle Enhancements - Added comprehensive FileBox lifecycle testing (open/write/close) - Enhanced cloneSelf() and copyFrom() testing with proper Handle parsing - Added TLV encoding helpers for strings and bytes - Improved error reporting and step-by-step validation 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-08-21 01:18:25 +09:00
user_defined_boxes: HashSet::new(),
weak_fields_by_box: HashMap::new(),
property_getters_by_box: HashMap::new(),
field_origin_class: HashMap::new(),
field_origin_by_box: HashMap::new(),
current_slot_registry: None,
feat(builder): CalleeBoxKind構造ガードで静的/ランタイムBox混線を根絶 🎯 箱理論の実践: 「境界を作る」原則による構造レベル分離 ## 問題 - StageBArgsBox.resolve_src内のargs.get(i)が Stage1UsingResolverBox.getに化ける(静的Box名混入) - 未定義ValueIdエラー発生(receiver定義なし) ## 解決策(構造ガード) ✅ CalleeBoxKind enum追加 - StaticCompiler: Stage-B/Stage-1コンパイラBox - RuntimeData: MapBox/ArrayBox等ランタイムBox - UserDefined: ユーザー定義Box ✅ classify_box_kind(): Box名から種別判定 - 静的Box群を明示的に列挙(1箇所に集約) - ランタイムBox群を明示的に列挙 - 将来の拡張も容易 ✅ apply_static_runtime_guard(): 混線検出・正規化 - me-call判定(receiver型==box_name → 静的降下に委ねる) - 真の混線検出(receiver型≠box_name → 正規化) - トレースログで可視化 ## 効果 - 修正前: Invalid value ValueId(150/187) - 修正後: Unknown method 'is_space' (別issue、StringBox実装不足) - → 静的Box名混入問題を根絶! ## 箱理論原則 - ✅ 境界を作る: Static/Runtime/UserDefinedを構造的に分離 - ✅ Fail-Fast: フォールバックより明示的エラー - ✅ 箱にする: CalleeBoxKindでBox種類を1箇所に集約 ## ファイル - src/mir/definitions/call_unified.rs: CalleeBoxKind enum - src/mir/builder/calls/call_unified.rs: classify_box_kind() - src/mir/builder/calls/emit.rs: apply_static_runtime_guard() - docs/development/roadmap/phases/phase-25.1d/README.md: 箱化メモ更新 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-17 23:13:57 +09:00
type_registry: type_registry::TypeRegistry::new(),
plugin_method_sigs,
current_static_box: None,
static_method_index: std::collections::HashMap::new(),
method_tail_index: std::collections::HashMap::new(),
method_tail_index_source_len: 0,
feat(mir/phi): improve LoopForm parameter detection - track param names **Problem**: is_parameter() was too simple, checking only ValueId which changes through copies/PHIs. This caused parameters like 'data' to be misclassified as carriers, leading to incorrect PHI construction. **Solution**: Track original parameter names at function entry. **Changes**: 1. **Added function_param_names field** (builder.rs): - HashSet<String> to track original parameter names - Populated in lower_static_method_as_function() - Cleared and repopulated for each new function 2. **Improved is_parameter()** (loop_builder.rs): - Check name against function_param_names instead of ValueId - More reliable than checking func.params (ValueIds change) - __pin$*$@* variables correctly classified as carriers - Added debug logging with NYASH_LOOPFORM_DEBUG 3. **Enhanced debug output** (loopform_builder.rs): - Show carrier/pinned classification during prepare_structure() - Show variable_map state after emit_header_phis() **Test Results**: - ✅ 'args' correctly identified as parameter (was working) - ✅ 'data' now correctly identified as parameter (was broken) - ✅ __pin variables correctly classified as carriers - ✅ PHI values allocated and variable_map updated correctly - ⚠️ ValueId undefined errors persist (separate issue) **Remaining Issue**: ValueId(10) undefined error suggests PHI visibility problem or VM verification issue. Needs further investigation of emit_phi_at_block_start() or VM executor. **Backward Compatibility**: - Flag OFF: 100% existing behavior preserved (legacy path unchanged) - Feature-flagged with NYASH_LOOPFORM_PHI_V2=1 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-17 05:24:07 +09:00
fn_body_ast: None, // Phase 200-C: Initialize to None
reserved_value_ids: HashSet::new(), // Phase 201-A: Initialize to empty
// Phase 2-5: binding_map initialization removed
// フェーズM: no_phi_modeフィールド削除
return_defer_active: false,
return_defer_slot: None,
return_defer_target: None,
return_deferred_emitted: false,
in_cleanup_block: false,
cleanup_allow_return: false,
cleanup_allow_throw: false,
suppress_pin_entry_copy_next: false,
local_ssa_map: HashMap::new(),
schedule_mat_map: HashMap::new(),
pin_slot_names: HashMap::new(),
fix(builder): 修正案A実装 - emit_unified_call↔emit_box_or_plugin_call再入防止 🎯 無限再帰の構造的防止(修正案A採用) ## 問題 Phase 2リファクタリング後、stack overflow発生: ``` emit_unified_call (emit.rs:15) ↓ emit_box_or_plugin_call (utils.rs:136) ↓ line 190 emit_unified_call (emit.rs:15) ← 無限ループ! ``` ## 修正案A: 再入防止ガード(採用理由) - B(Math機能削除): 対処療法で仕様削減 ❌ - C("birth"特別扱い): 局所的修正で他Boxに波及 ❌ - A(構造的再入防止): 根治的アプローチ ✅ ## 実装内容 ### 1. MirBuilder にフラグ追加 ```rust pub(super) in_unified_boxcall_fallback: bool ``` 役割: RouterPolicyでRoute::BoxCallと決めたフォールバック中マーク ### 2. emit_unified_call 側修正 (emit.rs) ```rust // Route::BoxCall のときだけ self.in_unified_boxcall_fallback = true; emit_box_or_plugin_call(...); self.in_unified_boxcall_fallback = false; ``` ### 3. emit_box_or_plugin_call 側修正 (utils.rs) ```rust if use_unified_env && matches!(route, Route::Unified) && !self.in_unified_boxcall_fallback // ← 追加 { // emit_unified_call(...) への再入を防止 } ``` ## 構造的改善 - RouterPolicyBox の決定を優先 - emit_unified_call → emit_box_or_plugin_call の一方向化 - 「上位の決定を尊重する」という明確なルール ## 残存課題 ⚠️ まだstack overflowが残存(別の再帰ルート存在の可能性) → 次のステップでstack trace解析が必要 ## テスト状況 - Test 1 (Direct VM): ✅ 成功 - Test 2 (Stage-B): ❌ stack overflow(別ルート調査中) - Test 3 (MIR verification): ✅ 成功 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-17 17:31:09 +09:00
in_unified_boxcall_fallback: false,
recursion_depth: 0,
📦 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
root_is_app_mode: None,
static_box_singletons: HashMap::new(), // Phase 21.7: methodization support
}
}
// Phase 2-5: BindingContext sync helpers removed - binding_ctx is now SSOT
refactor(mir): Extract VariableContext from MirBuilder (Phase 136 follow-up 5/7) ## Summary Extracted variable mapping management into dedicated VariableContext struct, completing step 5 of 7 in the Context Box refactoring plan. ## Changes - NEW: src/mir/builder/variable_context.rs (VariableContext struct + helpers) - Modified: src/mir/builder.rs (added variable_ctx field + sync helpers) - Updated: phase-136-context-box-progress.md (5/7 progress) ## Extracted Fields - variable_map: BTreeMap<String, ValueId> → variable_ctx.variable_map ## Key Features - snapshot/restore for if/loop pattern state management - JoinIR integration: CarrierInfo::from_variable_map() - ExitLine contract enforcement (carriers in variable_map) - NYASH_TRACE_VARMAP debug visualization support ## Design Clarity - BindingContext: String → BindingId (binding identity, survives SSA renaming) - VariableContext: String → ValueId (current SSA values, block-local) - Both contexts work together for complete variable management ## Tests - cargo test --release --lib: 1014/1018 passed (4 pre-existing failures) - phase135_trim_mir_verify.sh: PASS - Backward compatibility: 100% maintained (deprecated fields synced) ## Progress Phase 136 Context Extraction: 5/7 complete (71%) - ✅ Step 1: TypeContext - ✅ Step 2: CoreContext - ✅ Step 3: ScopeContext - ✅ Step 4: BindingContext - ✅ Step 5: VariableContext (this commit) - ⏳ Step 6: MetadataContext - ⏳ Step 7: CompilationContext 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 21:50:50 +09:00
/// Phase 136 Step 5/7: Sync variable_ctx changes back to legacy field (backward compatibility)
#[allow(deprecated)]
fn sync_variable_ctx_to_legacy(&mut self) {
self.variable_map = self.variable_ctx.variable_map.clone();
}
/// Phase 136 Step 5/7: Sync legacy field changes to variable_ctx (backward compatibility)
#[allow(deprecated)]
fn sync_legacy_to_variable_ctx(&mut self) {
self.variable_ctx.variable_map = self.variable_map.clone();
}
/// Push/pop helpers for If merge context (best-effort; optional usage)
feat(mir): Phase 136 Step 3/7 - ScopeContext extraction ## Summary Extract scope and control flow management into ScopeContext for better organization. ## Changes - **New file**: src/mir/builder/scope_context.rs (264 lines) - Lexical scope stack management - Control flow stacks (loop/if) - Function context tracking - Debug scope helpers - **Updated**: src/mir/builder.rs - Add scope_ctx field - Mark legacy fields as deprecated - Add sync helpers (sync_scope_ctx_to_legacy, sync_legacy_to_scope_ctx) - **Updated**: src/mir/builder/vars/lexical_scope.rs - Use scope_ctx as SSOT - Sync to legacy fields for backward compat - **Updated**: src/mir/builder/lifecycle.rs - Sync current_function via scope_ctx - **Updated**: src/mir/builder/calls/lowering.rs - Sync function context in lowering flow ## Extracted Fields (7) 1. lexical_scope_stack - Block-scoped locals 2. loop_header_stack - Loop headers for break/continue 3. loop_exit_stack - Loop exit blocks 4. if_merge_stack - If merge blocks 5. current_function - Currently building function 6. function_param_names - Function parameters (for LoopForm) 7. debug_scope_stack - Debug region identifiers ## Test Results - ✅ cargo build --release (291 warnings - deprecated usage) - ✅ cargo test --release --lib - 1005/1009 PASS - ✅ phase135_trim_mir_verify.sh - PASS - ⚠️ phase132_exit_phi_parity.sh - Error (pre-existing issue) ## Progress Phase 136: 3/7 Contexts complete (TypeContext, CoreContext, ScopeContext) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 20:28:21 +09:00
#[allow(deprecated)]
pub(super) fn push_if_merge(&mut self, bb: BasicBlockId) {
feat(mir): Phase 136 Step 3/7 - ScopeContext extraction ## Summary Extract scope and control flow management into ScopeContext for better organization. ## Changes - **New file**: src/mir/builder/scope_context.rs (264 lines) - Lexical scope stack management - Control flow stacks (loop/if) - Function context tracking - Debug scope helpers - **Updated**: src/mir/builder.rs - Add scope_ctx field - Mark legacy fields as deprecated - Add sync helpers (sync_scope_ctx_to_legacy, sync_legacy_to_scope_ctx) - **Updated**: src/mir/builder/vars/lexical_scope.rs - Use scope_ctx as SSOT - Sync to legacy fields for backward compat - **Updated**: src/mir/builder/lifecycle.rs - Sync current_function via scope_ctx - **Updated**: src/mir/builder/calls/lowering.rs - Sync function context in lowering flow ## Extracted Fields (7) 1. lexical_scope_stack - Block-scoped locals 2. loop_header_stack - Loop headers for break/continue 3. loop_exit_stack - Loop exit blocks 4. if_merge_stack - If merge blocks 5. current_function - Currently building function 6. function_param_names - Function parameters (for LoopForm) 7. debug_scope_stack - Debug region identifiers ## Test Results - ✅ cargo build --release (291 warnings - deprecated usage) - ✅ cargo test --release --lib - 1005/1009 PASS - ✅ phase135_trim_mir_verify.sh - PASS - ⚠️ phase132_exit_phi_parity.sh - Error (pre-existing issue) ## Progress Phase 136: 3/7 Contexts complete (TypeContext, CoreContext, ScopeContext) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 20:28:21 +09:00
// Phase 136 Step 3/7: Update both scope_ctx (SSOT) and legacy field (backward compat)
self.scope_ctx.push_if_merge(bb);
self.if_merge_stack.push(bb);
}
feat(mir): Phase 136 Step 3/7 - ScopeContext extraction ## Summary Extract scope and control flow management into ScopeContext for better organization. ## Changes - **New file**: src/mir/builder/scope_context.rs (264 lines) - Lexical scope stack management - Control flow stacks (loop/if) - Function context tracking - Debug scope helpers - **Updated**: src/mir/builder.rs - Add scope_ctx field - Mark legacy fields as deprecated - Add sync helpers (sync_scope_ctx_to_legacy, sync_legacy_to_scope_ctx) - **Updated**: src/mir/builder/vars/lexical_scope.rs - Use scope_ctx as SSOT - Sync to legacy fields for backward compat - **Updated**: src/mir/builder/lifecycle.rs - Sync current_function via scope_ctx - **Updated**: src/mir/builder/calls/lowering.rs - Sync function context in lowering flow ## Extracted Fields (7) 1. lexical_scope_stack - Block-scoped locals 2. loop_header_stack - Loop headers for break/continue 3. loop_exit_stack - Loop exit blocks 4. if_merge_stack - If merge blocks 5. current_function - Currently building function 6. function_param_names - Function parameters (for LoopForm) 7. debug_scope_stack - Debug region identifiers ## Test Results - ✅ cargo build --release (291 warnings - deprecated usage) - ✅ cargo test --release --lib - 1005/1009 PASS - ✅ phase135_trim_mir_verify.sh - PASS - ⚠️ phase132_exit_phi_parity.sh - Error (pre-existing issue) ## Progress Phase 136: 3/7 Contexts complete (TypeContext, CoreContext, ScopeContext) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 20:28:21 +09:00
#[allow(deprecated)]
pub(super) fn pop_if_merge(&mut self) {
feat(mir): Phase 136 Step 3/7 - ScopeContext extraction ## Summary Extract scope and control flow management into ScopeContext for better organization. ## Changes - **New file**: src/mir/builder/scope_context.rs (264 lines) - Lexical scope stack management - Control flow stacks (loop/if) - Function context tracking - Debug scope helpers - **Updated**: src/mir/builder.rs - Add scope_ctx field - Mark legacy fields as deprecated - Add sync helpers (sync_scope_ctx_to_legacy, sync_legacy_to_scope_ctx) - **Updated**: src/mir/builder/vars/lexical_scope.rs - Use scope_ctx as SSOT - Sync to legacy fields for backward compat - **Updated**: src/mir/builder/lifecycle.rs - Sync current_function via scope_ctx - **Updated**: src/mir/builder/calls/lowering.rs - Sync function context in lowering flow ## Extracted Fields (7) 1. lexical_scope_stack - Block-scoped locals 2. loop_header_stack - Loop headers for break/continue 3. loop_exit_stack - Loop exit blocks 4. if_merge_stack - If merge blocks 5. current_function - Currently building function 6. function_param_names - Function parameters (for LoopForm) 7. debug_scope_stack - Debug region identifiers ## Test Results - ✅ cargo build --release (291 warnings - deprecated usage) - ✅ cargo test --release --lib - 1005/1009 PASS - ✅ phase135_trim_mir_verify.sh - PASS - ⚠️ phase132_exit_phi_parity.sh - Error (pre-existing issue) ## Progress Phase 136: 3/7 Contexts complete (TypeContext, CoreContext, ScopeContext) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 20:28:21 +09:00
// Phase 136 Step 3/7: Update both scope_ctx (SSOT) and legacy field (backward compat)
let _ = self.scope_ctx.pop_if_merge();
let _ = self.if_merge_stack.pop();
}
/// Suppress entry pin copy for the next start_new_block (used for merge blocks).
pub(super) fn suppress_next_entry_pin_copy(&mut self) {
self.suppress_pin_entry_copy_next = true;
}
// ---- Phase 74: BindingId allocation ----
/// Allocate a new BindingId (parallel to ValueId allocation)
///
/// ## Parallel ValueId/BindingId Allocation
///
/// BindingId allocation is completely independent from ValueId allocation:
/// - `next_value_id()` increments `value_gen` counter
/// - `allocate_binding_id()` increments `next_binding_id` counter
///
/// This parallelism enables:
/// 1. **Stable binding identity** across SSA transformations
/// 2. **Independent shadowing tracking** separate from SSA renaming
/// 3. **Future ScopeManager migration** (Phase 75+) without breaking SSA
///
/// Example:
/// ```ignore
/// // local x = 1; <- allocate_binding_id() -> BindingId(0)
/// // next_value_id() -> ValueId(10)
/// // {
/// // local x = 2; <- allocate_binding_id() -> BindingId(1)
/// // next_value_id() -> ValueId(20)
/// // }
/// ```
pub fn allocate_binding_id(&mut self) -> super::BindingId {
// Phase 136 Step 2/7 + Phase 2-2: Use core_ctx as SSOT (no sync needed)
self.core_ctx.next_binding()
}
// ---- Hint helpers (no-op by default) ----
refactor(mir): Extract MetadataContext from MirBuilder (Phase 136 follow-up 6/7) ## Summary Extracted metadata and debug information management into dedicated MetadataContext struct, completing step 6 of 7 in the Context Box refactoring plan. ## Changes - NEW: src/mir/builder/metadata_context.rs (MetadataContext struct + helpers) - Modified: src/mir/builder.rs (added metadata_ctx field + sync helpers) - Modified: src/mir/hints.rs (added Clone + Debug derives to HintSink) - Updated: phase-136-context-box-progress.md (6/7 progress) ## Extracted Fields - current_span: Span → metadata_ctx.current_span - source_file: Option<String> → metadata_ctx.source_file - hint_sink: HintSink → metadata_ctx.hint_sink - current_region_stack: Vec<RegionId> → metadata_ctx.current_region_stack ## Key Features - Zero-cost type inference hints (HintSink) - Source position tracking for error messages - Region observation stack for debug builds - Phase 135 contract_checks integration ## Tests - cargo test --release --lib: 1019/1023 passed (4 pre-existing failures) - phase135_trim_mir_verify.sh: PASS - Backward compatibility: 100% maintained (deprecated fields synced) ## Progress Phase 136 Context Extraction: 6/7 complete (86%) - ✅ Step 1: TypeContext - ✅ Step 2: CoreContext - ✅ Step 3: ScopeContext - ✅ Step 4: BindingContext - ✅ Step 5: VariableContext - ✅ Step 6: MetadataContext (this commit) - ⏳ Step 7: CompilationContext 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:03:34 +09:00
// Phase 136 Step 6/7: Delegate to metadata_ctx with legacy sync
#[inline]
pub(crate) fn hint_scope_enter(&mut self, id: u32) {
refactor(mir): Extract MetadataContext from MirBuilder (Phase 136 follow-up 6/7) ## Summary Extracted metadata and debug information management into dedicated MetadataContext struct, completing step 6 of 7 in the Context Box refactoring plan. ## Changes - NEW: src/mir/builder/metadata_context.rs (MetadataContext struct + helpers) - Modified: src/mir/builder.rs (added metadata_ctx field + sync helpers) - Modified: src/mir/hints.rs (added Clone + Debug derives to HintSink) - Updated: phase-136-context-box-progress.md (6/7 progress) ## Extracted Fields - current_span: Span → metadata_ctx.current_span - source_file: Option<String> → metadata_ctx.source_file - hint_sink: HintSink → metadata_ctx.hint_sink - current_region_stack: Vec<RegionId> → metadata_ctx.current_region_stack ## Key Features - Zero-cost type inference hints (HintSink) - Source position tracking for error messages - Region observation stack for debug builds - Phase 135 contract_checks integration ## Tests - cargo test --release --lib: 1019/1023 passed (4 pre-existing failures) - phase135_trim_mir_verify.sh: PASS - Backward compatibility: 100% maintained (deprecated fields synced) ## Progress Phase 136 Context Extraction: 6/7 complete (86%) - ✅ Step 1: TypeContext - ✅ Step 2: CoreContext - ✅ Step 3: ScopeContext - ✅ Step 4: BindingContext - ✅ Step 5: VariableContext - ✅ Step 6: MetadataContext (this commit) - ⏳ Step 7: CompilationContext 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:03:34 +09:00
self.metadata_ctx.hint_scope_enter(id);
}
#[inline]
pub(crate) fn hint_scope_leave(&mut self, id: u32) {
refactor(mir): Extract MetadataContext from MirBuilder (Phase 136 follow-up 6/7) ## Summary Extracted metadata and debug information management into dedicated MetadataContext struct, completing step 6 of 7 in the Context Box refactoring plan. ## Changes - NEW: src/mir/builder/metadata_context.rs (MetadataContext struct + helpers) - Modified: src/mir/builder.rs (added metadata_ctx field + sync helpers) - Modified: src/mir/hints.rs (added Clone + Debug derives to HintSink) - Updated: phase-136-context-box-progress.md (6/7 progress) ## Extracted Fields - current_span: Span → metadata_ctx.current_span - source_file: Option<String> → metadata_ctx.source_file - hint_sink: HintSink → metadata_ctx.hint_sink - current_region_stack: Vec<RegionId> → metadata_ctx.current_region_stack ## Key Features - Zero-cost type inference hints (HintSink) - Source position tracking for error messages - Region observation stack for debug builds - Phase 135 contract_checks integration ## Tests - cargo test --release --lib: 1019/1023 passed (4 pre-existing failures) - phase135_trim_mir_verify.sh: PASS - Backward compatibility: 100% maintained (deprecated fields synced) ## Progress Phase 136 Context Extraction: 6/7 complete (86%) - ✅ Step 1: TypeContext - ✅ Step 2: CoreContext - ✅ Step 3: ScopeContext - ✅ Step 4: BindingContext - ✅ Step 5: VariableContext - ✅ Step 6: MetadataContext (this commit) - ⏳ Step 7: CompilationContext 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:03:34 +09:00
self.metadata_ctx.hint_scope_leave(id);
}
#[inline]
pub(crate) fn hint_join_result<S: Into<String>>(&mut self, var: S) {
refactor(mir): Remove MetadataContext legacy fields (Phase 2-1/7) 完全移行→削除の安全順序(Option C)に従い、MetadataContext の deprecated フィールドと sync helpers を完全削除。 ## Changes - Migrated all access sites to metadata_ctx.* (builder methods) - current_span → metadata_ctx.current_span() / set_current_span() - source_file → metadata_ctx.current_source_file() / set_source_file() / clear_source_file() - hint_sink → metadata_ctx.hint_scope_enter/leave/join_result() - current_region_stack → metadata_ctx.push_region/pop_region/current_region_stack() - Removed 4 deprecated fields from MirBuilder - current_span, source_file, hint_sink, current_region_stack - Removed 2 sync helpers - sync_metadata_ctx_to_legacy(), sync_legacy_to_metadata_ctx() - Updated 10 files with direct field accesses ## Files Modified - src/mir/builder.rs: -56 lines (fields + sync helpers + initialization) - src/mir/builder/exprs.rs: metadata_ctx.set_current_span() - src/mir/builder/exprs_peek.rs: metadata_ctx.current_span() - src/mir/builder/if_form.rs: metadata_ctx.current_span() - src/mir/builder/phi.rs: metadata_ctx.current_span() - src/mir/builder/stmts.rs: metadata_ctx.set_current_span() - src/mir/builder/utils.rs: metadata_ctx.current_span() - src/mir/loop_api.rs: metadata_ctx.current_span() - src/mir/region/observer.rs: metadata_ctx.push/pop_region() - src/mir/utils/phi_helpers.rs: metadata_ctx.current_span() ## Tests - cargo build --release: SUCCESS (1m 10s) - cargo test --release --lib: 1029 PASS, 4 FAIL (pre-existing) - Deprecation warnings: 469 → 435 (-34 warnings) ## Verification ✅ No direct access to removed fields (grep count: 0) ✅ No sync helper calls (grep count: 0) ✅ Build success ✅ MetadataContext is now complete SSOT (二重管理解消) Phase 2 Progress: 1/7 contexts complete (MetadataContext ✅) 🎉 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:44:38 +09:00
self.metadata_ctx.hint_join_result(var);
}
// ----------------------
// Debug scope helpers (region_id for DebugHub events)
// ----------------------
#[inline]
pub(crate) fn debug_next_join_id(&mut self) -> u32 {
// Phase 136 Step 2/7 + Phase 2-2: Use core_ctx as SSOT (no sync needed)
self.core_ctx.next_debug_join()
}
#[inline]
feat(mir): Phase 136 Step 3/7 - ScopeContext extraction ## Summary Extract scope and control flow management into ScopeContext for better organization. ## Changes - **New file**: src/mir/builder/scope_context.rs (264 lines) - Lexical scope stack management - Control flow stacks (loop/if) - Function context tracking - Debug scope helpers - **Updated**: src/mir/builder.rs - Add scope_ctx field - Mark legacy fields as deprecated - Add sync helpers (sync_scope_ctx_to_legacy, sync_legacy_to_scope_ctx) - **Updated**: src/mir/builder/vars/lexical_scope.rs - Use scope_ctx as SSOT - Sync to legacy fields for backward compat - **Updated**: src/mir/builder/lifecycle.rs - Sync current_function via scope_ctx - **Updated**: src/mir/builder/calls/lowering.rs - Sync function context in lowering flow ## Extracted Fields (7) 1. lexical_scope_stack - Block-scoped locals 2. loop_header_stack - Loop headers for break/continue 3. loop_exit_stack - Loop exit blocks 4. if_merge_stack - If merge blocks 5. current_function - Currently building function 6. function_param_names - Function parameters (for LoopForm) 7. debug_scope_stack - Debug region identifiers ## Test Results - ✅ cargo build --release (291 warnings - deprecated usage) - ✅ cargo test --release --lib - 1005/1009 PASS - ✅ phase135_trim_mir_verify.sh - PASS - ⚠️ phase132_exit_phi_parity.sh - Error (pre-existing issue) ## Progress Phase 136: 3/7 Contexts complete (TypeContext, CoreContext, ScopeContext) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 20:28:21 +09:00
#[allow(deprecated)]
pub(crate) fn debug_push_region<S: Into<String>>(&mut self, region: S) {
feat(mir): Phase 136 Step 3/7 - ScopeContext extraction ## Summary Extract scope and control flow management into ScopeContext for better organization. ## Changes - **New file**: src/mir/builder/scope_context.rs (264 lines) - Lexical scope stack management - Control flow stacks (loop/if) - Function context tracking - Debug scope helpers - **Updated**: src/mir/builder.rs - Add scope_ctx field - Mark legacy fields as deprecated - Add sync helpers (sync_scope_ctx_to_legacy, sync_legacy_to_scope_ctx) - **Updated**: src/mir/builder/vars/lexical_scope.rs - Use scope_ctx as SSOT - Sync to legacy fields for backward compat - **Updated**: src/mir/builder/lifecycle.rs - Sync current_function via scope_ctx - **Updated**: src/mir/builder/calls/lowering.rs - Sync function context in lowering flow ## Extracted Fields (7) 1. lexical_scope_stack - Block-scoped locals 2. loop_header_stack - Loop headers for break/continue 3. loop_exit_stack - Loop exit blocks 4. if_merge_stack - If merge blocks 5. current_function - Currently building function 6. function_param_names - Function parameters (for LoopForm) 7. debug_scope_stack - Debug region identifiers ## Test Results - ✅ cargo build --release (291 warnings - deprecated usage) - ✅ cargo test --release --lib - 1005/1009 PASS - ✅ phase135_trim_mir_verify.sh - PASS - ⚠️ phase132_exit_phi_parity.sh - Error (pre-existing issue) ## Progress Phase 136: 3/7 Contexts complete (TypeContext, CoreContext, ScopeContext) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 20:28:21 +09:00
// Phase 136 Step 3/7: Update both scope_ctx (SSOT) and legacy field (backward compat)
let region = region.into();
self.scope_ctx.debug_push_region(region.clone());
self.debug_scope_stack.push(region);
}
#[inline]
feat(mir): Phase 136 Step 3/7 - ScopeContext extraction ## Summary Extract scope and control flow management into ScopeContext for better organization. ## Changes - **New file**: src/mir/builder/scope_context.rs (264 lines) - Lexical scope stack management - Control flow stacks (loop/if) - Function context tracking - Debug scope helpers - **Updated**: src/mir/builder.rs - Add scope_ctx field - Mark legacy fields as deprecated - Add sync helpers (sync_scope_ctx_to_legacy, sync_legacy_to_scope_ctx) - **Updated**: src/mir/builder/vars/lexical_scope.rs - Use scope_ctx as SSOT - Sync to legacy fields for backward compat - **Updated**: src/mir/builder/lifecycle.rs - Sync current_function via scope_ctx - **Updated**: src/mir/builder/calls/lowering.rs - Sync function context in lowering flow ## Extracted Fields (7) 1. lexical_scope_stack - Block-scoped locals 2. loop_header_stack - Loop headers for break/continue 3. loop_exit_stack - Loop exit blocks 4. if_merge_stack - If merge blocks 5. current_function - Currently building function 6. function_param_names - Function parameters (for LoopForm) 7. debug_scope_stack - Debug region identifiers ## Test Results - ✅ cargo build --release (291 warnings - deprecated usage) - ✅ cargo test --release --lib - 1005/1009 PASS - ✅ phase135_trim_mir_verify.sh - PASS - ⚠️ phase132_exit_phi_parity.sh - Error (pre-existing issue) ## Progress Phase 136: 3/7 Contexts complete (TypeContext, CoreContext, ScopeContext) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 20:28:21 +09:00
#[allow(deprecated)]
pub(crate) fn debug_pop_region(&mut self) {
feat(mir): Phase 136 Step 3/7 - ScopeContext extraction ## Summary Extract scope and control flow management into ScopeContext for better organization. ## Changes - **New file**: src/mir/builder/scope_context.rs (264 lines) - Lexical scope stack management - Control flow stacks (loop/if) - Function context tracking - Debug scope helpers - **Updated**: src/mir/builder.rs - Add scope_ctx field - Mark legacy fields as deprecated - Add sync helpers (sync_scope_ctx_to_legacy, sync_legacy_to_scope_ctx) - **Updated**: src/mir/builder/vars/lexical_scope.rs - Use scope_ctx as SSOT - Sync to legacy fields for backward compat - **Updated**: src/mir/builder/lifecycle.rs - Sync current_function via scope_ctx - **Updated**: src/mir/builder/calls/lowering.rs - Sync function context in lowering flow ## Extracted Fields (7) 1. lexical_scope_stack - Block-scoped locals 2. loop_header_stack - Loop headers for break/continue 3. loop_exit_stack - Loop exit blocks 4. if_merge_stack - If merge blocks 5. current_function - Currently building function 6. function_param_names - Function parameters (for LoopForm) 7. debug_scope_stack - Debug region identifiers ## Test Results - ✅ cargo build --release (291 warnings - deprecated usage) - ✅ cargo test --release --lib - 1005/1009 PASS - ✅ phase135_trim_mir_verify.sh - PASS - ⚠️ phase132_exit_phi_parity.sh - Error (pre-existing issue) ## Progress Phase 136: 3/7 Contexts complete (TypeContext, CoreContext, ScopeContext) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 20:28:21 +09:00
// Phase 136 Step 3/7: Update both scope_ctx (SSOT) and legacy field (backward compat)
self.scope_ctx.debug_pop_region();
let _ = self.debug_scope_stack.pop();
}
#[inline]
feat(mir): Phase 136 Step 3/7 - ScopeContext extraction ## Summary Extract scope and control flow management into ScopeContext for better organization. ## Changes - **New file**: src/mir/builder/scope_context.rs (264 lines) - Lexical scope stack management - Control flow stacks (loop/if) - Function context tracking - Debug scope helpers - **Updated**: src/mir/builder.rs - Add scope_ctx field - Mark legacy fields as deprecated - Add sync helpers (sync_scope_ctx_to_legacy, sync_legacy_to_scope_ctx) - **Updated**: src/mir/builder/vars/lexical_scope.rs - Use scope_ctx as SSOT - Sync to legacy fields for backward compat - **Updated**: src/mir/builder/lifecycle.rs - Sync current_function via scope_ctx - **Updated**: src/mir/builder/calls/lowering.rs - Sync function context in lowering flow ## Extracted Fields (7) 1. lexical_scope_stack - Block-scoped locals 2. loop_header_stack - Loop headers for break/continue 3. loop_exit_stack - Loop exit blocks 4. if_merge_stack - If merge blocks 5. current_function - Currently building function 6. function_param_names - Function parameters (for LoopForm) 7. debug_scope_stack - Debug region identifiers ## Test Results - ✅ cargo build --release (291 warnings - deprecated usage) - ✅ cargo test --release --lib - 1005/1009 PASS - ✅ phase135_trim_mir_verify.sh - PASS - ⚠️ phase132_exit_phi_parity.sh - Error (pre-existing issue) ## Progress Phase 136: 3/7 Contexts complete (TypeContext, CoreContext, ScopeContext) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 20:28:21 +09:00
#[allow(deprecated)]
pub(crate) fn debug_current_region_id(&self) -> Option<String> {
feat(mir): Phase 136 Step 3/7 - ScopeContext extraction ## Summary Extract scope and control flow management into ScopeContext for better organization. ## Changes - **New file**: src/mir/builder/scope_context.rs (264 lines) - Lexical scope stack management - Control flow stacks (loop/if) - Function context tracking - Debug scope helpers - **Updated**: src/mir/builder.rs - Add scope_ctx field - Mark legacy fields as deprecated - Add sync helpers (sync_scope_ctx_to_legacy, sync_legacy_to_scope_ctx) - **Updated**: src/mir/builder/vars/lexical_scope.rs - Use scope_ctx as SSOT - Sync to legacy fields for backward compat - **Updated**: src/mir/builder/lifecycle.rs - Sync current_function via scope_ctx - **Updated**: src/mir/builder/calls/lowering.rs - Sync function context in lowering flow ## Extracted Fields (7) 1. lexical_scope_stack - Block-scoped locals 2. loop_header_stack - Loop headers for break/continue 3. loop_exit_stack - Loop exit blocks 4. if_merge_stack - If merge blocks 5. current_function - Currently building function 6. function_param_names - Function parameters (for LoopForm) 7. debug_scope_stack - Debug region identifiers ## Test Results - ✅ cargo build --release (291 warnings - deprecated usage) - ✅ cargo test --release --lib - 1005/1009 PASS - ✅ phase135_trim_mir_verify.sh - PASS - ⚠️ phase132_exit_phi_parity.sh - Error (pre-existing issue) ## Progress Phase 136: 3/7 Contexts complete (TypeContext, CoreContext, ScopeContext) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 20:28:21 +09:00
// Phase 136 Step 3/7: Read from scope_ctx (SSOT)
self.scope_ctx.debug_current_region_id()
}
/// Hint for downstream metadata: set the logical source file name/path for the next build.
refactor(mir): Remove MetadataContext legacy fields (Phase 2-1/7) 完全移行→削除の安全順序(Option C)に従い、MetadataContext の deprecated フィールドと sync helpers を完全削除。 ## Changes - Migrated all access sites to metadata_ctx.* (builder methods) - current_span → metadata_ctx.current_span() / set_current_span() - source_file → metadata_ctx.current_source_file() / set_source_file() / clear_source_file() - hint_sink → metadata_ctx.hint_scope_enter/leave/join_result() - current_region_stack → metadata_ctx.push_region/pop_region/current_region_stack() - Removed 4 deprecated fields from MirBuilder - current_span, source_file, hint_sink, current_region_stack - Removed 2 sync helpers - sync_metadata_ctx_to_legacy(), sync_legacy_to_metadata_ctx() - Updated 10 files with direct field accesses ## Files Modified - src/mir/builder.rs: -56 lines (fields + sync helpers + initialization) - src/mir/builder/exprs.rs: metadata_ctx.set_current_span() - src/mir/builder/exprs_peek.rs: metadata_ctx.current_span() - src/mir/builder/if_form.rs: metadata_ctx.current_span() - src/mir/builder/phi.rs: metadata_ctx.current_span() - src/mir/builder/stmts.rs: metadata_ctx.set_current_span() - src/mir/builder/utils.rs: metadata_ctx.current_span() - src/mir/loop_api.rs: metadata_ctx.current_span() - src/mir/region/observer.rs: metadata_ctx.push/pop_region() - src/mir/utils/phi_helpers.rs: metadata_ctx.current_span() ## Tests - cargo build --release: SUCCESS (1m 10s) - cargo test --release --lib: 1029 PASS, 4 FAIL (pre-existing) - Deprecation warnings: 469 → 435 (-34 warnings) ## Verification ✅ No direct access to removed fields (grep count: 0) ✅ No sync helper calls (grep count: 0) ✅ Build success ✅ MetadataContext is now complete SSOT (二重管理解消) Phase 2 Progress: 1/7 contexts complete (MetadataContext ✅) 🎉 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:44:38 +09:00
/// Phase 136 Step 6/7: Delegate to metadata_ctx
pub fn set_source_file_hint<S: Into<String>>(&mut self, source: S) {
refactor(mir): Remove MetadataContext legacy fields (Phase 2-1/7) 完全移行→削除の安全順序(Option C)に従い、MetadataContext の deprecated フィールドと sync helpers を完全削除。 ## Changes - Migrated all access sites to metadata_ctx.* (builder methods) - current_span → metadata_ctx.current_span() / set_current_span() - source_file → metadata_ctx.current_source_file() / set_source_file() / clear_source_file() - hint_sink → metadata_ctx.hint_scope_enter/leave/join_result() - current_region_stack → metadata_ctx.push_region/pop_region/current_region_stack() - Removed 4 deprecated fields from MirBuilder - current_span, source_file, hint_sink, current_region_stack - Removed 2 sync helpers - sync_metadata_ctx_to_legacy(), sync_legacy_to_metadata_ctx() - Updated 10 files with direct field accesses ## Files Modified - src/mir/builder.rs: -56 lines (fields + sync helpers + initialization) - src/mir/builder/exprs.rs: metadata_ctx.set_current_span() - src/mir/builder/exprs_peek.rs: metadata_ctx.current_span() - src/mir/builder/if_form.rs: metadata_ctx.current_span() - src/mir/builder/phi.rs: metadata_ctx.current_span() - src/mir/builder/stmts.rs: metadata_ctx.set_current_span() - src/mir/builder/utils.rs: metadata_ctx.current_span() - src/mir/loop_api.rs: metadata_ctx.current_span() - src/mir/region/observer.rs: metadata_ctx.push/pop_region() - src/mir/utils/phi_helpers.rs: metadata_ctx.current_span() ## Tests - cargo build --release: SUCCESS (1m 10s) - cargo test --release --lib: 1029 PASS, 4 FAIL (pre-existing) - Deprecation warnings: 469 → 435 (-34 warnings) ## Verification ✅ No direct access to removed fields (grep count: 0) ✅ No sync helper calls (grep count: 0) ✅ Build success ✅ MetadataContext is now complete SSOT (二重管理解消) Phase 2 Progress: 1/7 contexts complete (MetadataContext ✅) 🎉 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:44:38 +09:00
self.metadata_ctx.set_source_file(source);
}
/// Clear the source file hint (used when reusing the builder across modules).
refactor(mir): Remove MetadataContext legacy fields (Phase 2-1/7) 完全移行→削除の安全順序(Option C)に従い、MetadataContext の deprecated フィールドと sync helpers を完全削除。 ## Changes - Migrated all access sites to metadata_ctx.* (builder methods) - current_span → metadata_ctx.current_span() / set_current_span() - source_file → metadata_ctx.current_source_file() / set_source_file() / clear_source_file() - hint_sink → metadata_ctx.hint_scope_enter/leave/join_result() - current_region_stack → metadata_ctx.push_region/pop_region/current_region_stack() - Removed 4 deprecated fields from MirBuilder - current_span, source_file, hint_sink, current_region_stack - Removed 2 sync helpers - sync_metadata_ctx_to_legacy(), sync_legacy_to_metadata_ctx() - Updated 10 files with direct field accesses ## Files Modified - src/mir/builder.rs: -56 lines (fields + sync helpers + initialization) - src/mir/builder/exprs.rs: metadata_ctx.set_current_span() - src/mir/builder/exprs_peek.rs: metadata_ctx.current_span() - src/mir/builder/if_form.rs: metadata_ctx.current_span() - src/mir/builder/phi.rs: metadata_ctx.current_span() - src/mir/builder/stmts.rs: metadata_ctx.set_current_span() - src/mir/builder/utils.rs: metadata_ctx.current_span() - src/mir/loop_api.rs: metadata_ctx.current_span() - src/mir/region/observer.rs: metadata_ctx.push/pop_region() - src/mir/utils/phi_helpers.rs: metadata_ctx.current_span() ## Tests - cargo build --release: SUCCESS (1m 10s) - cargo test --release --lib: 1029 PASS, 4 FAIL (pre-existing) - Deprecation warnings: 469 → 435 (-34 warnings) ## Verification ✅ No direct access to removed fields (grep count: 0) ✅ No sync helper calls (grep count: 0) ✅ Build success ✅ MetadataContext is now complete SSOT (二重管理解消) Phase 2 Progress: 1/7 contexts complete (MetadataContext ✅) 🎉 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:44:38 +09:00
/// Phase 136 Step 6/7: Delegate to metadata_ctx
pub fn clear_source_file_hint(&mut self) {
refactor(mir): Extract MetadataContext from MirBuilder (Phase 136 follow-up 6/7) ## Summary Extracted metadata and debug information management into dedicated MetadataContext struct, completing step 6 of 7 in the Context Box refactoring plan. ## Changes - NEW: src/mir/builder/metadata_context.rs (MetadataContext struct + helpers) - Modified: src/mir/builder.rs (added metadata_ctx field + sync helpers) - Modified: src/mir/hints.rs (added Clone + Debug derives to HintSink) - Updated: phase-136-context-box-progress.md (6/7 progress) ## Extracted Fields - current_span: Span → metadata_ctx.current_span - source_file: Option<String> → metadata_ctx.source_file - hint_sink: HintSink → metadata_ctx.hint_sink - current_region_stack: Vec<RegionId> → metadata_ctx.current_region_stack ## Key Features - Zero-cost type inference hints (HintSink) - Source position tracking for error messages - Region observation stack for debug builds - Phase 135 contract_checks integration ## Tests - cargo test --release --lib: 1019/1023 passed (4 pre-existing failures) - phase135_trim_mir_verify.sh: PASS - Backward compatibility: 100% maintained (deprecated fields synced) ## Progress Phase 136 Context Extraction: 6/7 complete (86%) - ✅ Step 1: TypeContext - ✅ Step 2: CoreContext - ✅ Step 3: ScopeContext - ✅ Step 4: BindingContext - ✅ Step 5: VariableContext - ✅ Step 6: MetadataContext (this commit) - ⏳ Step 7: CompilationContext 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:03:34 +09:00
self.metadata_ctx.clear_source_file();
}
/// Resolve current source file hint (builder field or env fallback).
refactor(mir): Extract MetadataContext from MirBuilder (Phase 136 follow-up 6/7) ## Summary Extracted metadata and debug information management into dedicated MetadataContext struct, completing step 6 of 7 in the Context Box refactoring plan. ## Changes - NEW: src/mir/builder/metadata_context.rs (MetadataContext struct + helpers) - Modified: src/mir/builder.rs (added metadata_ctx field + sync helpers) - Modified: src/mir/hints.rs (added Clone + Debug derives to HintSink) - Updated: phase-136-context-box-progress.md (6/7 progress) ## Extracted Fields - current_span: Span → metadata_ctx.current_span - source_file: Option<String> → metadata_ctx.source_file - hint_sink: HintSink → metadata_ctx.hint_sink - current_region_stack: Vec<RegionId> → metadata_ctx.current_region_stack ## Key Features - Zero-cost type inference hints (HintSink) - Source position tracking for error messages - Region observation stack for debug builds - Phase 135 contract_checks integration ## Tests - cargo test --release --lib: 1019/1023 passed (4 pre-existing failures) - phase135_trim_mir_verify.sh: PASS - Backward compatibility: 100% maintained (deprecated fields synced) ## Progress Phase 136 Context Extraction: 6/7 complete (86%) - ✅ Step 1: TypeContext - ✅ Step 2: CoreContext - ✅ Step 3: ScopeContext - ✅ Step 4: BindingContext - ✅ Step 5: VariableContext - ✅ Step 6: MetadataContext (this commit) - ⏳ Step 7: CompilationContext 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:03:34 +09:00
/// Phase 136 Step 6/7: Delegate to metadata_ctx
fn current_source_file(&self) -> Option<String> {
refactor(mir): Extract MetadataContext from MirBuilder (Phase 136 follow-up 6/7) ## Summary Extracted metadata and debug information management into dedicated MetadataContext struct, completing step 6 of 7 in the Context Box refactoring plan. ## Changes - NEW: src/mir/builder/metadata_context.rs (MetadataContext struct + helpers) - Modified: src/mir/builder.rs (added metadata_ctx field + sync helpers) - Modified: src/mir/hints.rs (added Clone + Debug derives to HintSink) - Updated: phase-136-context-box-progress.md (6/7 progress) ## Extracted Fields - current_span: Span → metadata_ctx.current_span - source_file: Option<String> → metadata_ctx.source_file - hint_sink: HintSink → metadata_ctx.hint_sink - current_region_stack: Vec<RegionId> → metadata_ctx.current_region_stack ## Key Features - Zero-cost type inference hints (HintSink) - Source position tracking for error messages - Region observation stack for debug builds - Phase 135 contract_checks integration ## Tests - cargo test --release --lib: 1019/1023 passed (4 pre-existing failures) - phase135_trim_mir_verify.sh: PASS - Backward compatibility: 100% maintained (deprecated fields synced) ## Progress Phase 136 Context Extraction: 6/7 complete (86%) - ✅ Step 1: TypeContext - ✅ Step 2: CoreContext - ✅ Step 3: ScopeContext - ✅ Step 4: BindingContext - ✅ Step 5: VariableContext - ✅ Step 6: MetadataContext (this commit) - ⏳ Step 7: CompilationContext 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:03:34 +09:00
self.metadata_ctx
.current_source_file()
.or_else(|| std::env::var("NYASH_SOURCE_FILE_HINT").ok())
}
/// Create a new MirFunction with source metadata applied.
fn new_function_with_metadata(
&self,
signature: FunctionSignature,
entry_block: BasicBlockId,
) -> MirFunction {
let mut f = MirFunction::new(signature, entry_block);
f.metadata.source_file = self.current_source_file();
f
}
// ----------------------
// Compile trace helpers (dev only; env-gated)
// ----------------------
#[inline]
pub(super) fn compile_trace_enabled() -> bool {
std::env::var("NYASH_MIR_COMPILE_TRACE").ok().as_deref() == Some("1")
}
#[inline]
pub(super) fn trace_compile<S: AsRef<str>>(&self, msg: S) {
if Self::compile_trace_enabled() {
eprintln!("[mir-compile] {}", msg.as_ref());
}
}
// ----------------------
// Method tail index (performance helper)
// ----------------------
fn rebuild_method_tail_index(&mut self) {
self.method_tail_index.clear();
if let Some(ref module) = self.current_module {
for name in module.functions.keys() {
if let (Some(dot), Some(slash)) = (name.rfind('.'), name.rfind('/')) {
if slash > dot {
let tail = &name[dot..];
self.method_tail_index
.entry(tail.to_string())
.or_insert_with(Vec::new)
.push(name.clone());
}
}
}
self.method_tail_index_source_len = module.functions.len();
} else {
self.method_tail_index_source_len = 0;
}
}
fn ensure_method_tail_index(&mut self) {
let need_rebuild = match self.current_module {
Some(ref refmod) => self.method_tail_index_source_len != refmod.functions.len(),
None => self.method_tail_index_source_len != 0,
};
if need_rebuild {
self.rebuild_method_tail_index();
}
}
pub(super) fn method_candidates(&mut self, method: &str, arity: usize) -> Vec<String> {
self.ensure_method_tail_index();
let tail = format!(".{}{}", method, format!("/{}", arity));
self.method_tail_index
.get(&tail)
.cloned()
.unwrap_or_default()
}
pub(super) fn method_candidates_tail<S: AsRef<str>>(&mut self, tail: S) -> Vec<String> {
self.ensure_method_tail_index();
self.method_tail_index
.get(tail.as_ref())
.cloned()
.unwrap_or_default()
}
/// Build a complete MIR module from AST
pub fn build_module(&mut self, ast: ASTNode) -> Result<MirModule, String> {
2025-09-17 07:29:28 +09:00
self.prepare_module()?;
let result_value = self.lower_root(ast)?;
self.finalize_module(result_value)
}
/// Build an expression and return its value ID
pub(super) fn build_expression(&mut self, ast: ASTNode) -> Result<ValueId, String> {
// Delegated to exprs.rs to keep this file lean
// Debug: Track recursion depth to detect infinite loops
const MAX_RECURSION_DEPTH: usize = 200;
self.recursion_depth += 1;
if self.recursion_depth > MAX_RECURSION_DEPTH {
eprintln!("\n[FATAL] ============================================");
eprintln!(
"[FATAL] Recursion depth exceeded {} in build_expression",
MAX_RECURSION_DEPTH
);
eprintln!("[FATAL] Current depth: {}", self.recursion_depth);
eprintln!("[FATAL] AST node type: {:?}", std::mem::discriminant(&ast));
eprintln!("[FATAL] ============================================\n");
return Err(format!(
"Recursion depth exceeded: {} (possible infinite loop)",
self.recursion_depth
));
}
let result = self.build_expression_impl(ast);
self.recursion_depth -= 1;
result
}
/// Build a literal value
pub(super) fn build_literal(&mut self, literal: LiteralValue) -> Result<ValueId, String> {
// Determine type without moving literal
let ty_for_dst = match &literal {
LiteralValue::Integer(_) => Some(super::MirType::Integer),
LiteralValue::Float(_) => Some(super::MirType::Float),
LiteralValue::Bool(_) => Some(super::MirType::Bool),
LiteralValue::String(_) => Some(super::MirType::String),
_ => None,
};
// Emit via ConstantEmissionBox仕様不変の統一ルート
let dst = match literal {
LiteralValue::Integer(n) => {
crate::mir::builder::emission::constant::emit_integer(self, n)
}
LiteralValue::Float(f) => crate::mir::builder::emission::constant::emit_float(self, f),
LiteralValue::String(s) => {
crate::mir::builder::emission::constant::emit_string(self, s)
}
LiteralValue::Bool(b) => crate::mir::builder::emission::constant::emit_bool(self, b),
LiteralValue::Null => crate::mir::builder::emission::constant::emit_null(self),
LiteralValue::Void => crate::mir::builder::emission::constant::emit_void(self),
};
// Annotate type
if let Some(ty) = ty_for_dst {
self.type_ctx.value_types.insert(dst, ty);
}
Ok(dst)
}
/// Build variable access
pub(super) fn build_variable_access(&mut self, name: String) -> Result<ValueId, String> {
// Step 5-5-G: __pin$ variables should NEVER be accessed from variable_map
// They are transient temporaries created during expression building and
// should not persist across blocks. If we see one here, it's a compiler bug.
if name.starts_with("__pin$") {
return Err(format!(
"COMPILER BUG: Attempt to access __pin$ temporary '{}' from variable_map. \
__pin$ variables should only exist as direct SSA values, not as named variables.",
name
));
}
if let Some(&value_id) = self.variable_map.get(&name) {
Ok(value_id)
} else {
Err(self.undefined_variable_message(&name))
}
}
pub(in crate::mir::builder) fn undefined_variable_message(&self, name: &str) -> String {
// Enhance diagnostics using Using simple registry (Phase 1)
let mut msg = format!("Undefined variable: {}", name);
// Stage-3 keyword diagnostic (local/flow/try/catch/throw)
if name == "local" && !crate::config::env::parser_stage3_enabled() {
msg.push_str("\nHint: 'local' is a Stage-3 keyword. Prefer NYASH_FEATURES=stage3 (legacy: NYASH_PARSER_STAGE3=1 / HAKO_PARSER_STAGE3=1 for Stage-B).");
msg.push_str("\nFor AotPrep verification, use tools/hakorune_emit_mir.sh which sets these automatically.");
} else if (name == "flow" || name == "try" || name == "catch" || name == "throw")
&& !crate::config::env::parser_stage3_enabled()
{
msg.push_str(&format!("\nHint: '{}' is a Stage-3 keyword. Prefer NYASH_FEATURES=stage3 (legacy: NYASH_PARSER_STAGE3=1 / HAKO_PARSER_STAGE3=1 for Stage-B).", name));
}
let suggest = crate::using::simple_registry::suggest_using_for_symbol(name);
if !suggest.is_empty() {
msg.push_str("\nHint: symbol appears in using module(s): ");
msg.push_str(&suggest.join(", "));
msg.push_str("\nConsider adding 'using <module> [as Alias]' or check nyash.toml [using].");
}
msg
}
/// Build assignment
pub(super) fn build_assignment(
&mut self,
var_name: String,
value: ASTNode,
) -> Result<ValueId, String> {
// SSOT (LANGUAGE_REFERENCE_2025 / syntax-cheatsheet):
// - Assignment to an undeclared name is an error.
// - Use `local name = ...` (or `local name; name = ...`) to declare.
vars::assignment_resolver::AssignmentResolverBox::ensure_declared(self, &var_name)?;
let value_id = self.build_expression(value)?;
// Step 5-5-E: FIX variable map corruption bug
// REMOVED pin_to_slot() call - it was causing __pin$ temporaries to overwrite
// real variable names in the variable map.
//
// Root cause: pin_to_slot(raw_value_id, "@assign") would sometimes return
// a ValueId from a previous __pin$ temporary (e.g., __pin$767$@binop_lhs),
// causing variable_map["m"] to point to the wrong ValueId.
//
// SSA + PHI merges work correctly without explicit pinning here.
// The expression building already creates necessary temporaries.
// Step 5-5-F: NEVER insert __pin$ temporaries into variable_map
// __pin$ variables are transient compiler-generated temporaries that should
// never be tracked as real variables. They are used only within expression
// building and should not persist across blocks or loops.
//
// BUG FIX: Previously, __pin$ variables would be inserted into variable_map,
// causing stale references after LoopForm transformation renumbers blocks.
// Result: VM would try to read undefined ValueIds (e.g., ValueId(270) at bb303).
if !var_name.starts_with("__pin$") {
// In SSA form, each assignment creates a new value
self.variable_map.insert(var_name.clone(), value_id);
}
Ok(value_id)
}
/// Emit an instruction to the current basic block
pub(super) fn emit_instruction(&mut self, instruction: MirInstruction) -> Result<(), String> {
let block_id = self.current_block.ok_or("No current basic block")?;
// Make instruction mutable for potential receiver materialization
let mut instruction = instruction;
// Precompute debug metadata to avoid borrow conflicts later
let _dbg_fn_name = self
.current_function
.as_ref()
.map(|f| f.signature.name.clone());
let _dbg_region_id = self.debug_current_region_id();
// P0: PHI の軽量補強と観測は、関数ブロック取得前に実施して借用競合を避ける
if let MirInstruction::Phi { dst, inputs, .. } = &instruction {
origin::phi::propagate_phi_meta(self, *dst, inputs);
observe::ssa::emit_phi(self, *dst, inputs);
}
// CRITICAL: Final receiver materialization for MethodCall
// This ensures the receiver has an in-block definition in the same block as the Call.
// Must happen BEFORE function mutable borrow to avoid borrowck conflicts.
if let MirInstruction::Call {
callee: Some(callee),
dst,
args,
effects,
..
} = &instruction
{
use crate::mir::definitions::call_unified::Callee;
if let Callee::Method {
box_name,
method,
receiver: Some(r),
certainty,
box_kind,
} = callee.clone()
{
// LocalSSA: ensure receiver has a Copy in current_block
let r_local = crate::mir::builder::ssa::local::recv(self, r);
// Update instruction with materialized receiver
let new_callee = Callee::Method {
box_name: box_name.clone(),
method: method.clone(),
receiver: Some(r_local),
feat(builder): CalleeBoxKind構造ガードで静的/ランタイムBox混線を根絶 🎯 箱理論の実践: 「境界を作る」原則による構造レベル分離 ## 問題 - StageBArgsBox.resolve_src内のargs.get(i)が Stage1UsingResolverBox.getに化ける(静的Box名混入) - 未定義ValueIdエラー発生(receiver定義なし) ## 解決策(構造ガード) ✅ CalleeBoxKind enum追加 - StaticCompiler: Stage-B/Stage-1コンパイラBox - RuntimeData: MapBox/ArrayBox等ランタイムBox - UserDefined: ユーザー定義Box ✅ classify_box_kind(): Box名から種別判定 - 静的Box群を明示的に列挙(1箇所に集約) - ランタイムBox群を明示的に列挙 - 将来の拡張も容易 ✅ apply_static_runtime_guard(): 混線検出・正規化 - me-call判定(receiver型==box_name → 静的降下に委ねる) - 真の混線検出(receiver型≠box_name → 正規化) - トレースログで可視化 ## 効果 - 修正前: Invalid value ValueId(150/187) - 修正後: Unknown method 'is_space' (別issue、StringBox実装不足) - → 静的Box名混入問題を根絶! ## 箱理論原則 - ✅ 境界を作る: Static/Runtime/UserDefinedを構造的に分離 - ✅ Fail-Fast: フォールバックより明示的エラー - ✅ 箱にする: CalleeBoxKindでBox種類を1箇所に集約 ## ファイル - src/mir/definitions/call_unified.rs: CalleeBoxKind enum - src/mir/builder/calls/call_unified.rs: classify_box_kind() - src/mir/builder/calls/emit.rs: apply_static_runtime_guard() - docs/development/roadmap/phases/phase-25.1d/README.md: 箱化メモ更新 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-17 23:13:57 +09:00
certainty,
box_kind,
};
instruction = MirInstruction::Call {
dst: *dst,
func: crate::mir::ValueId::INVALID, // Legacy dummy (not a real SSA use)
callee: Some(new_callee),
args: args.clone(),
effects: *effects,
};
}
}
if let Some(ref mut function) = self.current_function {
// Pre-capture branch/jump targets for predecessor update after we finish
// mutably borrowing the current block.
let (then_t, else_t, jump_t) = match &instruction {
MirInstruction::Branch {
then_bb, else_bb, ..
} => (Some(*then_bb), Some(*else_bb), None),
MirInstruction::Jump { target } => (None, None, Some(*target)),
_ => (None, None, None),
};
// Extract function name before mutable borrow to avoid borrowck error
let current_fn_name = function.signature.name.clone();
if let Some(block) = function.get_block_mut(block_id) {
// CRITICAL: Copy専用トレースLocalSSA調査用
if let MirInstruction::Copy { dst, src } = &instruction {
if std::env::var("NYASH_LOCAL_SSA_TRACE").ok().as_deref() == Some("1") {
eprintln!(
"[emit-inst] fn={} bb={:?} COPY %{} <- %{}",
current_fn_name,
self.current_block.map(|b| b.0).unwrap_or(0),
dst.0,
src.0
);
}
}
// Invariant: Call must always carry a Callee (unified path).
if let MirInstruction::Call { callee, .. } = &instruction {
if callee.is_none() {
return Err("builder invariant violated: MirInstruction::Call.callee must be Some (unified call)".into());
} else if std::env::var("NYASH_LOCAL_SSA_TRACE").ok().as_deref() == Some("1") {
use crate::mir::definitions::call_unified::Callee;
if let Some(Callee::Method {
box_name,
method,
receiver: Some(r),
..
}) = callee
{
eprintln!(
"[emit-inst] fn={} bb={:?} Call {}.{} recv=%{}",
current_fn_name,
self.current_block.map(|b| b.0).unwrap_or(0),
box_name,
method,
r.0
);
}
} else if std::env::var("NYASH_BUILDER_TRACE_RECV").ok().as_deref() == Some("1")
{
use crate::mir::definitions::call_unified::Callee;
if let Some(Callee::Method {
box_name,
method,
receiver: Some(r),
..
}) = callee
{
let names: Vec<String> = self
.variable_map
.iter()
.filter(|(_, &vid)| vid == *r)
.map(|(k, _)| k.clone())
.collect();
eprintln!(
"[builder/recv-trace] fn={} bb={:?} method={}.{} recv=%{} aliases={:?}",
current_fn_name,
self.current_block,
box_name,
method,
r.0,
names
);
}
}
}
if utils::builder_debug_enabled() {
eprintln!(
"[BUILDER] emit @bb{} -> {}",
block_id,
match &instruction {
MirInstruction::TypeOp { dst, op, value, ty } =>
format!("typeop {:?} {} {:?} -> {}", op, value, ty, dst),
MirInstruction::Print { value, .. } => format!("print {}", value),
MirInstruction::BoxCall {
box_val,
method,
method_id,
args,
dst,
..
} => {
if let Some(mid) = method_id {
format!(
"boxcall {}.{}[#{}]({:?}) -> {:?}",
box_val, method, mid, args, dst
)
} else {
format!(
"boxcall {}.{}({:?}) -> {:?}",
box_val, method, args, dst
)
}
}
MirInstruction::Call {
func, args, dst, ..
} => format!("call {}({:?}) -> {:?}", func, args, dst),
MirInstruction::NewBox {
dst,
box_type,
args,
} => format!("new {}({:?}) -> {}", box_type, args, dst),
MirInstruction::Const { dst, value } =>
format!("const {:?} -> {}", value, dst),
MirInstruction::Branch {
condition,
then_bb,
else_bb,
} => format!("br {}, {}, {}", condition, then_bb, else_bb),
MirInstruction::Jump { target } => format!("br {}", target),
_ => format!("{:?}", instruction),
}
);
}
refactor(mir): Extract MetadataContext from MirBuilder (Phase 136 follow-up 6/7) ## Summary Extracted metadata and debug information management into dedicated MetadataContext struct, completing step 6 of 7 in the Context Box refactoring plan. ## Changes - NEW: src/mir/builder/metadata_context.rs (MetadataContext struct + helpers) - Modified: src/mir/builder.rs (added metadata_ctx field + sync helpers) - Modified: src/mir/hints.rs (added Clone + Debug derives to HintSink) - Updated: phase-136-context-box-progress.md (6/7 progress) ## Extracted Fields - current_span: Span → metadata_ctx.current_span - source_file: Option<String> → metadata_ctx.source_file - hint_sink: HintSink → metadata_ctx.hint_sink - current_region_stack: Vec<RegionId> → metadata_ctx.current_region_stack ## Key Features - Zero-cost type inference hints (HintSink) - Source position tracking for error messages - Region observation stack for debug builds - Phase 135 contract_checks integration ## Tests - cargo test --release --lib: 1019/1023 passed (4 pre-existing failures) - phase135_trim_mir_verify.sh: PASS - Backward compatibility: 100% maintained (deprecated fields synced) ## Progress Phase 136 Context Extraction: 6/7 complete (86%) - ✅ Step 1: TypeContext - ✅ Step 2: CoreContext - ✅ Step 3: ScopeContext - ✅ Step 4: BindingContext - ✅ Step 5: VariableContext - ✅ Step 6: MetadataContext (this commit) - ⏳ Step 7: CompilationContext 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 22:03:34 +09:00
// Phase 136 Step 6/7: Use metadata_ctx for span
block.add_instruction_with_span(instruction.clone(), self.metadata_ctx.current_span());
// Drop the mutable borrow of `block` before updating other blocks
}
// Update predecessor sets for branch/jump immediately so that
// debug_verify_phi_inputs can observe a consistent CFG without
// requiring a full function.update_cfg() pass.
if let Some(t) = then_t {
if let Some(succ) = function.get_block_mut(t) {
succ.add_predecessor(block_id);
}
}
if let Some(t) = else_t {
if let Some(succ) = function.get_block_mut(t) {
succ.add_predecessor(block_id);
}
}
if let Some(t) = jump_t {
if let Some(succ) = function.get_block_mut(t) {
succ.add_predecessor(block_id);
}
}
Ok(())
} else {
Err(format!("Basic block {} does not exist", block_id))
}
}
feat(mir/phi): improve LoopForm parameter detection - track param names **Problem**: is_parameter() was too simple, checking only ValueId which changes through copies/PHIs. This caused parameters like 'data' to be misclassified as carriers, leading to incorrect PHI construction. **Solution**: Track original parameter names at function entry. **Changes**: 1. **Added function_param_names field** (builder.rs): - HashSet<String> to track original parameter names - Populated in lower_static_method_as_function() - Cleared and repopulated for each new function 2. **Improved is_parameter()** (loop_builder.rs): - Check name against function_param_names instead of ValueId - More reliable than checking func.params (ValueIds change) - __pin$*$@* variables correctly classified as carriers - Added debug logging with NYASH_LOOPFORM_DEBUG 3. **Enhanced debug output** (loopform_builder.rs): - Show carrier/pinned classification during prepare_structure() - Show variable_map state after emit_header_phis() **Test Results**: - ✅ 'args' correctly identified as parameter (was working) - ✅ 'data' now correctly identified as parameter (was broken) - ✅ __pin variables correctly classified as carriers - ✅ PHI values allocated and variable_map updated correctly - ⚠️ ValueId undefined errors persist (separate issue) **Remaining Issue**: ValueId(10) undefined error suggests PHI visibility problem or VM verification issue. Needs further investigation of emit_phi_at_block_start() or VM executor. **Backward Compatibility**: - Flag OFF: 100% existing behavior preserved (legacy path unchanged) - Feature-flagged with NYASH_LOOPFORM_PHI_V2=1 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-17 05:24:07 +09:00
/// Update an existing PHI instruction's inputs (for loop sealing)
/// Used by LoopFormBuilder to complete incomplete PHI nodes
#[allow(dead_code)]
feat(mir/phi): improve LoopForm parameter detection - track param names **Problem**: is_parameter() was too simple, checking only ValueId which changes through copies/PHIs. This caused parameters like 'data' to be misclassified as carriers, leading to incorrect PHI construction. **Solution**: Track original parameter names at function entry. **Changes**: 1. **Added function_param_names field** (builder.rs): - HashSet<String> to track original parameter names - Populated in lower_static_method_as_function() - Cleared and repopulated for each new function 2. **Improved is_parameter()** (loop_builder.rs): - Check name against function_param_names instead of ValueId - More reliable than checking func.params (ValueIds change) - __pin$*$@* variables correctly classified as carriers - Added debug logging with NYASH_LOOPFORM_DEBUG 3. **Enhanced debug output** (loopform_builder.rs): - Show carrier/pinned classification during prepare_structure() - Show variable_map state after emit_header_phis() **Test Results**: - ✅ 'args' correctly identified as parameter (was working) - ✅ 'data' now correctly identified as parameter (was broken) - ✅ __pin variables correctly classified as carriers - ✅ PHI values allocated and variable_map updated correctly - ⚠️ ValueId undefined errors persist (separate issue) **Remaining Issue**: ValueId(10) undefined error suggests PHI visibility problem or VM verification issue. Needs further investigation of emit_phi_at_block_start() or VM executor. **Backward Compatibility**: - Flag OFF: 100% existing behavior preserved (legacy path unchanged) - Feature-flagged with NYASH_LOOPFORM_PHI_V2=1 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-17 05:24:07 +09:00
pub(super) fn update_phi_instruction(
&mut self,
block: BasicBlockId,
phi_id: ValueId,
new_inputs: Vec<(BasicBlockId, ValueId)>,
) -> Result<(), String> {
if let Some(ref mut function) = self.current_function {
if let Some(block_data) = function.get_block_mut(block) {
// Find PHI instruction with matching dst
for inst in &mut block_data.instructions {
if let MirInstruction::Phi { dst, inputs, .. } = inst {
feat(mir/phi): improve LoopForm parameter detection - track param names **Problem**: is_parameter() was too simple, checking only ValueId which changes through copies/PHIs. This caused parameters like 'data' to be misclassified as carriers, leading to incorrect PHI construction. **Solution**: Track original parameter names at function entry. **Changes**: 1. **Added function_param_names field** (builder.rs): - HashSet<String> to track original parameter names - Populated in lower_static_method_as_function() - Cleared and repopulated for each new function 2. **Improved is_parameter()** (loop_builder.rs): - Check name against function_param_names instead of ValueId - More reliable than checking func.params (ValueIds change) - __pin$*$@* variables correctly classified as carriers - Added debug logging with NYASH_LOOPFORM_DEBUG 3. **Enhanced debug output** (loopform_builder.rs): - Show carrier/pinned classification during prepare_structure() - Show variable_map state after emit_header_phis() **Test Results**: - ✅ 'args' correctly identified as parameter (was working) - ✅ 'data' now correctly identified as parameter (was broken) - ✅ __pin variables correctly classified as carriers - ✅ PHI values allocated and variable_map updated correctly - ⚠️ ValueId undefined errors persist (separate issue) **Remaining Issue**: ValueId(10) undefined error suggests PHI visibility problem or VM verification issue. Needs further investigation of emit_phi_at_block_start() or VM executor. **Backward Compatibility**: - Flag OFF: 100% existing behavior preserved (legacy path unchanged) - Feature-flagged with NYASH_LOOPFORM_PHI_V2=1 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-17 05:24:07 +09:00
if *dst == phi_id {
*inputs = new_inputs;
return Ok(());
}
}
}
Err(format!(
"PHI instruction {} not found in block {}",
phi_id, block
))
feat(mir/phi): improve LoopForm parameter detection - track param names **Problem**: is_parameter() was too simple, checking only ValueId which changes through copies/PHIs. This caused parameters like 'data' to be misclassified as carriers, leading to incorrect PHI construction. **Solution**: Track original parameter names at function entry. **Changes**: 1. **Added function_param_names field** (builder.rs): - HashSet<String> to track original parameter names - Populated in lower_static_method_as_function() - Cleared and repopulated for each new function 2. **Improved is_parameter()** (loop_builder.rs): - Check name against function_param_names instead of ValueId - More reliable than checking func.params (ValueIds change) - __pin$*$@* variables correctly classified as carriers - Added debug logging with NYASH_LOOPFORM_DEBUG 3. **Enhanced debug output** (loopform_builder.rs): - Show carrier/pinned classification during prepare_structure() - Show variable_map state after emit_header_phis() **Test Results**: - ✅ 'args' correctly identified as parameter (was working) - ✅ 'data' now correctly identified as parameter (was broken) - ✅ __pin variables correctly classified as carriers - ✅ PHI values allocated and variable_map updated correctly - ⚠️ ValueId undefined errors persist (separate issue) **Remaining Issue**: ValueId(10) undefined error suggests PHI visibility problem or VM verification issue. Needs further investigation of emit_phi_at_block_start() or VM executor. **Backward Compatibility**: - Flag OFF: 100% existing behavior preserved (legacy path unchanged) - Feature-flagged with NYASH_LOOPFORM_PHI_V2=1 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-17 05:24:07 +09:00
} else {
Err(format!("Block {} not found", block))
}
} else {
Err("No current function".to_string())
}
}
// フェーズM: is_no_phi_mode()メソッド削除
// フェーズM: insert_edge_copy()メソッド削除no_phi_mode撤廃により不要
/// Build new expression: new ClassName(arguments)
pub(super) fn build_new_expression(
&mut self,
class: String,
arguments: Vec<ASTNode>,
) -> Result<ValueId, String> {
// Phase 9.78a: Unified Box creation using NewBox instruction
// Core-13 pure mode: emit ExternCall(env.box.new) with type name const only
if crate::config::env::mir_core13_pure() {
// Emit Const String for type nameConstantEmissionBox
let ty_id = crate::mir::builder::emission::constant::emit_string(self, class.clone());
// Evaluate arguments (pass through to env.box.new shim)
let mut arg_vals: Vec<ValueId> = Vec::with_capacity(arguments.len());
for a in arguments {
arg_vals.push(self.build_expression(a)?);
}
// Build arg list: [type, a1, a2, ...]
let mut args: Vec<ValueId> = Vec::with_capacity(1 + arg_vals.len());
args.push(ty_id);
args.extend(arg_vals);
// Call env.box.new
// 📦 Hotfix 3: Use next_value_id() to respect function parameter reservation
let dst = self.next_value_id();
self.emit_instruction(MirInstruction::ExternCall {
dst: Some(dst),
iface_name: "env.box".to_string(),
method_name: "new".to_string(),
args,
effects: EffectMask::PURE,
})?;
// 型注釈(最小)
self.type_ctx.value_types
.insert(dst, super::MirType::Box(class.clone()));
return Ok(dst);
}
// Optimization: Primitive wrappers → emit Const directly when possible
if class == "IntegerBox" && arguments.len() == 1 {
if let ASTNode::Literal {
value: LiteralValue::Integer(n),
..
} = arguments[0].clone()
{
// 📦 Hotfix 3: Use next_value_id() to respect function parameter reservation
let dst = self.next_value_id();
self.emit_instruction(MirInstruction::Const {
dst,
value: ConstValue::Integer(n),
})?;
self.type_ctx.value_types.insert(dst, super::MirType::Integer);
return Ok(dst);
}
}
// First, evaluate all arguments to get their ValueIds
let mut arg_values = Vec::new();
for arg in arguments {
let arg_value = self.build_expression(arg)?;
arg_values.push(arg_value);
}
// Generate the destination ValueId
// 📦 Hotfix 3: Use next_value_id() to respect function parameter reservation
let dst = self.next_value_id();
// Emit NewBox instruction for all Box types
// VM will handle optimization for basic types internally
self.emit_instruction(MirInstruction::NewBox {
dst,
box_type: class.clone(),
args: arg_values.clone(),
})?;
// Phase 15.5: Unified box type handling
// All boxes (including former core boxes) are treated uniformly as Box types
self.type_ctx.value_types
.insert(dst, super::MirType::Box(class.clone()));
// Record origin for optimization: dst was created by NewBox of class
self.type_ctx.value_origin_newbox.insert(dst, class.clone());
// birth 呼び出しBuilder 正規化)
// 優先: 低下済みグローバル関数 `<Class>.birth/Arity`Arity は me を含まない)
// 代替: 既存互換として BoxCall("birth")(プラグイン/ビルトインの初期化に対応)
if class != "StringBox" {
let arity = arg_values.len();
let lowered =
crate::mir::builder::calls::function_lowering::generate_method_function_name(
&class, "birth", arity,
);
let use_lowered = if let Some(ref module) = self.current_module {
module.functions.contains_key(&lowered)
} else {
false
};
if use_lowered {
// Call Global("Class.birth/Arity") with argv = [me, args...]
let mut argv: Vec<ValueId> = Vec::with_capacity(1 + arity);
argv.push(dst);
argv.extend(arg_values.iter().copied());
self.emit_legacy_call(None, CallTarget::Global(lowered), argv)?;
} else {
// Fallback policy:
// - For user-defined boxes (no explicit constructor), do NOT emit BoxCall("birth").
// VM will treat plain NewBox as constructed; dev verify warns if needed.
// - For builtins/plugins, keep BoxCall("birth") fallback to preserve legacy init.
let is_user_box = self.user_defined_boxes.contains(&class);
// Dev safety: allow disabling birth() injection for builtins to avoid
// unified-call method dispatch issues while migrating. Off by default unless explicitly enabled.
let allow_builtin_birth = std::env::var("NYASH_DEV_BIRTH_INJECT_BUILTINS")
.ok()
.as_deref()
== Some("1");
if !is_user_box && allow_builtin_birth {
let birt_mid = resolve_slot_by_type_name(&class, "birth");
self.emit_box_or_plugin_call(
None,
dst,
"birth".to_string(),
birt_mid,
arg_values,
EffectMask::READ.add(Effect::ReadHeap),
)?;
}
}
}
Ok(dst)
}
/// Check if the current basic block is terminated
fn is_current_block_terminated(&self) -> bool {
if let (Some(block_id), Some(ref function)) = (self.current_block, &self.current_function) {
if let Some(block) = function.get_block(block_id) {
return block.is_terminated();
}
}
false
}
// ============================================================================
// Phase 26-A: ValueId型安全化メソッド
// ============================================================================
/// 型付きValueIdを発行新API
feat(mir): Phase 136 P0 - ValueId allocator SSOT 徹底(関数内経路から value_gen.next() 掃討) ## Summary Eliminates remaining `value_gen.next()` calls from function-context code paths, unifying all ValueId allocation through `MirBuilder::next_value_id()` SSOT allocator. ## Changes ### 1. Fixed `new_typed_value()` (src/mir/builder.rs:1068) **Before**: `let id = self.value_gen.next();` (bypasses function context) **After**: `let id = self.next_value_id();` (respects function context) This is a public API used in function context, so must use SSOT allocator to avoid collisions with reserved PHI dsts and function params. ### 2. Fixed test code (src/mir/builder.rs) **test_shadowing_binding_restore** (lines 1161, 1171): - Simulates function scope with `push_lexical_scope()` - Changed to `builder.next_value_id()` for function scope simulation **test_valueid_binding_parallel_allocation** (lines 1196-1216): - Tests ValueId/BindingId independence - Changed to `builder.next_value_id()` with note that Module context fallback preserves test intent ### 3. Verified Module context fallbacks (OK, no change needed) These already check `current_function.is_some()` and use `value_gen.next()` only as Module context fallback: - `src/mir/builder/utils.rs:43` - next_value_id() SSOT implementation - `src/mir/builder/utils.rs:436` - pin_to_slot() - `src/mir/builder/utils.rs:467` - materialize_local() - `src/mir/utils/phi_helpers.rs:69` - insert_phi_unified() ## Verification ```bash rg -n "value_gen\.next\(" src/mir --type rust | grep -v "Module context" | grep -v "//" # Result: Only comments/docs remain ``` ## Acceptance ✅ cargo test --release --lib - 997 passed ✅ phase135_trim_mir_verify.sh - PASS ✅ phase132_exit_phi_parity.sh - 3/3 PASS ✅ All function-context `value_gen.next()` eliminated ## Effect - **Collision prevention**: No more ValueId collisions between function-level allocations and reserved PHI dsts - **SSOT compliance**: All ValueId allocation flows through single allocator - **Contract enforcement**: Phase 135 P1 contract_checks will catch violations immediately 🤖 Generated with Claude Code Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 19:37:30 +09:00
/// Phase 136 P0: Use SSOT allocator (next_value_id) to respect function context
pub fn new_typed_value(&mut self, kind: super::MirValueKind) -> super::TypedValueId {
feat(mir): Phase 136 P0 - ValueId allocator SSOT 徹底(関数内経路から value_gen.next() 掃討) ## Summary Eliminates remaining `value_gen.next()` calls from function-context code paths, unifying all ValueId allocation through `MirBuilder::next_value_id()` SSOT allocator. ## Changes ### 1. Fixed `new_typed_value()` (src/mir/builder.rs:1068) **Before**: `let id = self.value_gen.next();` (bypasses function context) **After**: `let id = self.next_value_id();` (respects function context) This is a public API used in function context, so must use SSOT allocator to avoid collisions with reserved PHI dsts and function params. ### 2. Fixed test code (src/mir/builder.rs) **test_shadowing_binding_restore** (lines 1161, 1171): - Simulates function scope with `push_lexical_scope()` - Changed to `builder.next_value_id()` for function scope simulation **test_valueid_binding_parallel_allocation** (lines 1196-1216): - Tests ValueId/BindingId independence - Changed to `builder.next_value_id()` with note that Module context fallback preserves test intent ### 3. Verified Module context fallbacks (OK, no change needed) These already check `current_function.is_some()` and use `value_gen.next()` only as Module context fallback: - `src/mir/builder/utils.rs:43` - next_value_id() SSOT implementation - `src/mir/builder/utils.rs:436` - pin_to_slot() - `src/mir/builder/utils.rs:467` - materialize_local() - `src/mir/utils/phi_helpers.rs:69` - insert_phi_unified() ## Verification ```bash rg -n "value_gen\.next\(" src/mir --type rust | grep -v "Module context" | grep -v "//" # Result: Only comments/docs remain ``` ## Acceptance ✅ cargo test --release --lib - 997 passed ✅ phase135_trim_mir_verify.sh - PASS ✅ phase132_exit_phi_parity.sh - 3/3 PASS ✅ All function-context `value_gen.next()` eliminated ## Effect - **Collision prevention**: No more ValueId collisions between function-level allocations and reserved PHI dsts - **SSOT compliance**: All ValueId allocation flows through single allocator - **Contract enforcement**: Phase 135 P1 contract_checks will catch violations immediately 🤖 Generated with Claude Code Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 19:37:30 +09:00
let id = self.next_value_id();
self.type_ctx.value_kinds.insert(id, kind);
super::TypedValueId::new(id, kind)
}
/// 既存ValueIdの型情報を取得
pub fn get_value_kind(&self, id: ValueId) -> Option<super::MirValueKind> {
self.type_ctx.value_kinds.get(&id).copied()
}
/// 既存ValueIdに型情報を後付けレガシー互換用
pub fn register_value_kind(&mut self, id: ValueId, kind: super::MirValueKind) {
self.type_ctx.value_kinds.insert(id, kind);
}
/// 型安全なパラメータ判定ValueIdベース - GUARD Bug Prevention
pub fn is_value_parameter(&self, id: ValueId) -> bool {
self.get_value_kind(id)
.map(|kind| kind.is_parameter())
.unwrap_or(false)
}
/// 型安全なローカル変数判定ValueIdベース
pub fn is_value_local(&self, id: ValueId) -> bool {
self.get_value_kind(id)
.map(|kind| kind.is_local())
.unwrap_or(false)
}
/// 型安全なLoopCarrier判定ValueIdベース
pub fn is_value_loop_carrier(&self, id: ValueId) -> bool {
self.get_value_kind(id)
.map(|kind| kind.is_loop_carrier())
.unwrap_or(false)
}
}
impl Default for MirBuilder {
fn default() -> Self {
Self::new()
}
}
refactor(joinir): Phase 79 - Detector/Recorder separation + BindingMapProvider **Phase 79 Medium-Priority Refactoring Complete** ## Action 1: Detector/Recorder Separation **New Pure Detection Logic:** - `digitpos_detector.rs` (~350 lines, 7 tests) - Pure detection for A-4 DigitPos pattern - No binding_map dependency - Independently testable - `trim_detector.rs` (~410 lines, 9 tests) - Pure detection for A-3 Trim pattern - No binding_map dependency - Comprehensive test coverage **Simplified Promoters:** - `DigitPosPromoter`: 200+ → 80 lines (60% reduction) - Uses DigitPosDetector for detection - Focuses on orchestration + recording - Removed 6 helper methods - `LoopBodyCarrierPromoter`: 160+ → 70 lines (56% reduction) - Uses TrimDetector for detection - Clean separation of concerns - Removed 3 helper methods ## Action 2: BindingMapProvider Trait **Centralized Feature Gate:** - `binding_map_provider.rs` (~100 lines, 3 tests) - Trait to abstract binding_map access - #[cfg] guards: 10+ locations → 2 locations (80% reduction) - `MirBuilder` implementation - Clean feature-gated access - Single point of control ## Quality Metrics **Code Reduction:** - DigitPosPromoter: 200+ → 80 lines (60%) - LoopBodyCarrierPromoter: 160+ → 70 lines (56%) - Feature guards: 10+ → 2 locations (80%) **Tests:** - All tests passing: 970/970 (100%) - New test coverage: 19+ tests for detectors - No regressions **Design Improvements:** - ✅ Single Responsibility Principle - ✅ Independent unit testing - ✅ Reusable detection logic - ✅ Centralized feature gating 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2025-12-13 07:05:30 +09:00
// Phase 79: BindingMapProvider implementation
// Centralizes feature-gated binding_map access for promoters
use crate::mir::loop_pattern_detection::BindingMapProvider;
impl BindingMapProvider for MirBuilder {
#[cfg(feature = "normalized_dev")]
fn get_binding_map(&self) -> Option<&std::collections::BTreeMap<String, crate::mir::BindingId>> {
// Phase 136 Step 4/7: Use binding_ctx (SSOT)
Some(self.binding_ctx.binding_map())
refactor(joinir): Phase 79 - Detector/Recorder separation + BindingMapProvider **Phase 79 Medium-Priority Refactoring Complete** ## Action 1: Detector/Recorder Separation **New Pure Detection Logic:** - `digitpos_detector.rs` (~350 lines, 7 tests) - Pure detection for A-4 DigitPos pattern - No binding_map dependency - Independently testable - `trim_detector.rs` (~410 lines, 9 tests) - Pure detection for A-3 Trim pattern - No binding_map dependency - Comprehensive test coverage **Simplified Promoters:** - `DigitPosPromoter`: 200+ → 80 lines (60% reduction) - Uses DigitPosDetector for detection - Focuses on orchestration + recording - Removed 6 helper methods - `LoopBodyCarrierPromoter`: 160+ → 70 lines (56% reduction) - Uses TrimDetector for detection - Clean separation of concerns - Removed 3 helper methods ## Action 2: BindingMapProvider Trait **Centralized Feature Gate:** - `binding_map_provider.rs` (~100 lines, 3 tests) - Trait to abstract binding_map access - #[cfg] guards: 10+ locations → 2 locations (80% reduction) - `MirBuilder` implementation - Clean feature-gated access - Single point of control ## Quality Metrics **Code Reduction:** - DigitPosPromoter: 200+ → 80 lines (60%) - LoopBodyCarrierPromoter: 160+ → 70 lines (56%) - Feature guards: 10+ → 2 locations (80%) **Tests:** - All tests passing: 970/970 (100%) - New test coverage: 19+ tests for detectors - No regressions **Design Improvements:** - ✅ Single Responsibility Principle - ✅ Independent unit testing - ✅ Reusable detection logic - ✅ Centralized feature gating 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2025-12-13 07:05:30 +09:00
}
#[cfg(not(feature = "normalized_dev"))]
fn get_binding_map(&self) -> Option<&std::collections::BTreeMap<String, crate::mir::BindingId>> {
None
}
}
#[cfg(test)]
mod binding_id_tests {
use super::*;
#[test]
#[allow(deprecated)]
fn test_binding_map_initialization() {
let builder = MirBuilder::new();
assert_eq!(builder.core_ctx.next_binding_id, 0);
// Phase 136 Step 4/7: Check both binding_ctx (SSOT) and legacy field
assert!(builder.binding_ctx.is_empty());
assert!(builder.binding_map.is_empty());
}
#[test]
fn test_binding_allocation_sequential() {
let mut builder = MirBuilder::new();
let bid0 = builder.allocate_binding_id();
let bid1 = builder.allocate_binding_id();
let bid2 = builder.allocate_binding_id();
assert_eq!(bid0.raw(), 0);
assert_eq!(bid1.raw(), 1);
assert_eq!(bid2.raw(), 2);
assert_eq!(builder.core_ctx.next_binding_id, 3);
}
#[test]
#[allow(deprecated)]
fn test_shadowing_binding_restore() {
let mut builder = MirBuilder::new();
// Simulate function entry scope
builder.push_lexical_scope();
// Declare outer x
feat(mir): Phase 136 P0 - ValueId allocator SSOT 徹底(関数内経路から value_gen.next() 掃討) ## Summary Eliminates remaining `value_gen.next()` calls from function-context code paths, unifying all ValueId allocation through `MirBuilder::next_value_id()` SSOT allocator. ## Changes ### 1. Fixed `new_typed_value()` (src/mir/builder.rs:1068) **Before**: `let id = self.value_gen.next();` (bypasses function context) **After**: `let id = self.next_value_id();` (respects function context) This is a public API used in function context, so must use SSOT allocator to avoid collisions with reserved PHI dsts and function params. ### 2. Fixed test code (src/mir/builder.rs) **test_shadowing_binding_restore** (lines 1161, 1171): - Simulates function scope with `push_lexical_scope()` - Changed to `builder.next_value_id()` for function scope simulation **test_valueid_binding_parallel_allocation** (lines 1196-1216): - Tests ValueId/BindingId independence - Changed to `builder.next_value_id()` with note that Module context fallback preserves test intent ### 3. Verified Module context fallbacks (OK, no change needed) These already check `current_function.is_some()` and use `value_gen.next()` only as Module context fallback: - `src/mir/builder/utils.rs:43` - next_value_id() SSOT implementation - `src/mir/builder/utils.rs:436` - pin_to_slot() - `src/mir/builder/utils.rs:467` - materialize_local() - `src/mir/utils/phi_helpers.rs:69` - insert_phi_unified() ## Verification ```bash rg -n "value_gen\.next\(" src/mir --type rust | grep -v "Module context" | grep -v "//" # Result: Only comments/docs remain ``` ## Acceptance ✅ cargo test --release --lib - 997 passed ✅ phase135_trim_mir_verify.sh - PASS ✅ phase132_exit_phi_parity.sh - 3/3 PASS ✅ All function-context `value_gen.next()` eliminated ## Effect - **Collision prevention**: No more ValueId collisions between function-level allocations and reserved PHI dsts - **SSOT compliance**: All ValueId allocation flows through single allocator - **Contract enforcement**: Phase 135 P1 contract_checks will catch violations immediately 🤖 Generated with Claude Code Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 19:37:30 +09:00
// Phase 136 P0: Use SSOT allocator for function scope simulation
let outer_vid = builder.next_value_id();
builder
.declare_local_in_current_scope("x", outer_vid)
.unwrap();
// Phase 136 Step 4/7: Check binding_ctx (SSOT)
let outer_bid = builder.binding_ctx.lookup("x").unwrap();
assert_eq!(outer_bid.raw(), 0);
// Also verify legacy field is synced
assert_eq!(*builder.binding_map.get("x").unwrap(), outer_bid);
// Enter inner scope and shadow x
builder.push_lexical_scope();
feat(mir): Phase 136 P0 - ValueId allocator SSOT 徹底(関数内経路から value_gen.next() 掃討) ## Summary Eliminates remaining `value_gen.next()` calls from function-context code paths, unifying all ValueId allocation through `MirBuilder::next_value_id()` SSOT allocator. ## Changes ### 1. Fixed `new_typed_value()` (src/mir/builder.rs:1068) **Before**: `let id = self.value_gen.next();` (bypasses function context) **After**: `let id = self.next_value_id();` (respects function context) This is a public API used in function context, so must use SSOT allocator to avoid collisions with reserved PHI dsts and function params. ### 2. Fixed test code (src/mir/builder.rs) **test_shadowing_binding_restore** (lines 1161, 1171): - Simulates function scope with `push_lexical_scope()` - Changed to `builder.next_value_id()` for function scope simulation **test_valueid_binding_parallel_allocation** (lines 1196-1216): - Tests ValueId/BindingId independence - Changed to `builder.next_value_id()` with note that Module context fallback preserves test intent ### 3. Verified Module context fallbacks (OK, no change needed) These already check `current_function.is_some()` and use `value_gen.next()` only as Module context fallback: - `src/mir/builder/utils.rs:43` - next_value_id() SSOT implementation - `src/mir/builder/utils.rs:436` - pin_to_slot() - `src/mir/builder/utils.rs:467` - materialize_local() - `src/mir/utils/phi_helpers.rs:69` - insert_phi_unified() ## Verification ```bash rg -n "value_gen\.next\(" src/mir --type rust | grep -v "Module context" | grep -v "//" # Result: Only comments/docs remain ``` ## Acceptance ✅ cargo test --release --lib - 997 passed ✅ phase135_trim_mir_verify.sh - PASS ✅ phase132_exit_phi_parity.sh - 3/3 PASS ✅ All function-context `value_gen.next()` eliminated ## Effect - **Collision prevention**: No more ValueId collisions between function-level allocations and reserved PHI dsts - **SSOT compliance**: All ValueId allocation flows through single allocator - **Contract enforcement**: Phase 135 P1 contract_checks will catch violations immediately 🤖 Generated with Claude Code Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 19:37:30 +09:00
// Phase 136 P0: Use SSOT allocator for function scope simulation
let inner_vid = builder.next_value_id();
builder
.declare_local_in_current_scope("x", inner_vid)
.unwrap();
// Phase 136 Step 4/7: Check binding_ctx (SSOT)
let inner_bid = builder.binding_ctx.lookup("x").unwrap();
assert_eq!(inner_bid.raw(), 1);
// Also verify legacy field is synced
assert_eq!(*builder.binding_map.get("x").unwrap(), inner_bid);
// Exit inner scope - should restore outer binding
builder.pop_lexical_scope();
// Phase 136 Step 4/7: Check binding_ctx (SSOT)
let restored_bid = builder.binding_ctx.lookup("x").unwrap();
assert_eq!(restored_bid, outer_bid);
assert_eq!(restored_bid.raw(), 0);
// Also verify legacy field is synced
assert_eq!(*builder.binding_map.get("x").unwrap(), restored_bid);
// Cleanup
builder.pop_lexical_scope();
}
#[test]
fn test_valueid_binding_parallel_allocation() {
let mut builder = MirBuilder::new();
feat(mir): Phase 136 P0 - ValueId allocator SSOT 徹底(関数内経路から value_gen.next() 掃討) ## Summary Eliminates remaining `value_gen.next()` calls from function-context code paths, unifying all ValueId allocation through `MirBuilder::next_value_id()` SSOT allocator. ## Changes ### 1. Fixed `new_typed_value()` (src/mir/builder.rs:1068) **Before**: `let id = self.value_gen.next();` (bypasses function context) **After**: `let id = self.next_value_id();` (respects function context) This is a public API used in function context, so must use SSOT allocator to avoid collisions with reserved PHI dsts and function params. ### 2. Fixed test code (src/mir/builder.rs) **test_shadowing_binding_restore** (lines 1161, 1171): - Simulates function scope with `push_lexical_scope()` - Changed to `builder.next_value_id()` for function scope simulation **test_valueid_binding_parallel_allocation** (lines 1196-1216): - Tests ValueId/BindingId independence - Changed to `builder.next_value_id()` with note that Module context fallback preserves test intent ### 3. Verified Module context fallbacks (OK, no change needed) These already check `current_function.is_some()` and use `value_gen.next()` only as Module context fallback: - `src/mir/builder/utils.rs:43` - next_value_id() SSOT implementation - `src/mir/builder/utils.rs:436` - pin_to_slot() - `src/mir/builder/utils.rs:467` - materialize_local() - `src/mir/utils/phi_helpers.rs:69` - insert_phi_unified() ## Verification ```bash rg -n "value_gen\.next\(" src/mir --type rust | grep -v "Module context" | grep -v "//" # Result: Only comments/docs remain ``` ## Acceptance ✅ cargo test --release --lib - 997 passed ✅ phase135_trim_mir_verify.sh - PASS ✅ phase132_exit_phi_parity.sh - 3/3 PASS ✅ All function-context `value_gen.next()` eliminated ## Effect - **Collision prevention**: No more ValueId collisions between function-level allocations and reserved PHI dsts - **SSOT compliance**: All ValueId allocation flows through single allocator - **Contract enforcement**: Phase 135 P1 contract_checks will catch violations immediately 🤖 Generated with Claude Code Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 19:37:30 +09:00
// Phase 136 P0: Use SSOT allocator (next_value_id)
// Note: Without current_function, next_value_id() falls back to value_gen.next()
// so this test still validates ValueId/BindingId independence
// Allocate ValueIds and BindingIds in parallel
feat(mir): Phase 136 P0 - ValueId allocator SSOT 徹底(関数内経路から value_gen.next() 掃討) ## Summary Eliminates remaining `value_gen.next()` calls from function-context code paths, unifying all ValueId allocation through `MirBuilder::next_value_id()` SSOT allocator. ## Changes ### 1. Fixed `new_typed_value()` (src/mir/builder.rs:1068) **Before**: `let id = self.value_gen.next();` (bypasses function context) **After**: `let id = self.next_value_id();` (respects function context) This is a public API used in function context, so must use SSOT allocator to avoid collisions with reserved PHI dsts and function params. ### 2. Fixed test code (src/mir/builder.rs) **test_shadowing_binding_restore** (lines 1161, 1171): - Simulates function scope with `push_lexical_scope()` - Changed to `builder.next_value_id()` for function scope simulation **test_valueid_binding_parallel_allocation** (lines 1196-1216): - Tests ValueId/BindingId independence - Changed to `builder.next_value_id()` with note that Module context fallback preserves test intent ### 3. Verified Module context fallbacks (OK, no change needed) These already check `current_function.is_some()` and use `value_gen.next()` only as Module context fallback: - `src/mir/builder/utils.rs:43` - next_value_id() SSOT implementation - `src/mir/builder/utils.rs:436` - pin_to_slot() - `src/mir/builder/utils.rs:467` - materialize_local() - `src/mir/utils/phi_helpers.rs:69` - insert_phi_unified() ## Verification ```bash rg -n "value_gen\.next\(" src/mir --type rust | grep -v "Module context" | grep -v "//" # Result: Only comments/docs remain ``` ## Acceptance ✅ cargo test --release --lib - 997 passed ✅ phase135_trim_mir_verify.sh - PASS ✅ phase132_exit_phi_parity.sh - 3/3 PASS ✅ All function-context `value_gen.next()` eliminated ## Effect - **Collision prevention**: No more ValueId collisions between function-level allocations and reserved PHI dsts - **SSOT compliance**: All ValueId allocation flows through single allocator - **Contract enforcement**: Phase 135 P1 contract_checks will catch violations immediately 🤖 Generated with Claude Code Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 19:37:30 +09:00
let vid0 = builder.next_value_id();
let bid0 = builder.allocate_binding_id();
feat(mir): Phase 136 P0 - ValueId allocator SSOT 徹底(関数内経路から value_gen.next() 掃討) ## Summary Eliminates remaining `value_gen.next()` calls from function-context code paths, unifying all ValueId allocation through `MirBuilder::next_value_id()` SSOT allocator. ## Changes ### 1. Fixed `new_typed_value()` (src/mir/builder.rs:1068) **Before**: `let id = self.value_gen.next();` (bypasses function context) **After**: `let id = self.next_value_id();` (respects function context) This is a public API used in function context, so must use SSOT allocator to avoid collisions with reserved PHI dsts and function params. ### 2. Fixed test code (src/mir/builder.rs) **test_shadowing_binding_restore** (lines 1161, 1171): - Simulates function scope with `push_lexical_scope()` - Changed to `builder.next_value_id()` for function scope simulation **test_valueid_binding_parallel_allocation** (lines 1196-1216): - Tests ValueId/BindingId independence - Changed to `builder.next_value_id()` with note that Module context fallback preserves test intent ### 3. Verified Module context fallbacks (OK, no change needed) These already check `current_function.is_some()` and use `value_gen.next()` only as Module context fallback: - `src/mir/builder/utils.rs:43` - next_value_id() SSOT implementation - `src/mir/builder/utils.rs:436` - pin_to_slot() - `src/mir/builder/utils.rs:467` - materialize_local() - `src/mir/utils/phi_helpers.rs:69` - insert_phi_unified() ## Verification ```bash rg -n "value_gen\.next\(" src/mir --type rust | grep -v "Module context" | grep -v "//" # Result: Only comments/docs remain ``` ## Acceptance ✅ cargo test --release --lib - 997 passed ✅ phase135_trim_mir_verify.sh - PASS ✅ phase132_exit_phi_parity.sh - 3/3 PASS ✅ All function-context `value_gen.next()` eliminated ## Effect - **Collision prevention**: No more ValueId collisions between function-level allocations and reserved PHI dsts - **SSOT compliance**: All ValueId allocation flows through single allocator - **Contract enforcement**: Phase 135 P1 contract_checks will catch violations immediately 🤖 Generated with Claude Code Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 19:37:30 +09:00
let vid1 = builder.next_value_id();
let bid1 = builder.allocate_binding_id();
// ValueId and BindingId should be independent
assert_eq!(vid0.0, 0);
assert_eq!(bid0.raw(), 0);
assert_eq!(vid1.0, 1);
assert_eq!(bid1.raw(), 1);
// Allocating more ValueIds should not affect BindingId counter
feat(mir): Phase 136 P0 - ValueId allocator SSOT 徹底(関数内経路から value_gen.next() 掃討) ## Summary Eliminates remaining `value_gen.next()` calls from function-context code paths, unifying all ValueId allocation through `MirBuilder::next_value_id()` SSOT allocator. ## Changes ### 1. Fixed `new_typed_value()` (src/mir/builder.rs:1068) **Before**: `let id = self.value_gen.next();` (bypasses function context) **After**: `let id = self.next_value_id();` (respects function context) This is a public API used in function context, so must use SSOT allocator to avoid collisions with reserved PHI dsts and function params. ### 2. Fixed test code (src/mir/builder.rs) **test_shadowing_binding_restore** (lines 1161, 1171): - Simulates function scope with `push_lexical_scope()` - Changed to `builder.next_value_id()` for function scope simulation **test_valueid_binding_parallel_allocation** (lines 1196-1216): - Tests ValueId/BindingId independence - Changed to `builder.next_value_id()` with note that Module context fallback preserves test intent ### 3. Verified Module context fallbacks (OK, no change needed) These already check `current_function.is_some()` and use `value_gen.next()` only as Module context fallback: - `src/mir/builder/utils.rs:43` - next_value_id() SSOT implementation - `src/mir/builder/utils.rs:436` - pin_to_slot() - `src/mir/builder/utils.rs:467` - materialize_local() - `src/mir/utils/phi_helpers.rs:69` - insert_phi_unified() ## Verification ```bash rg -n "value_gen\.next\(" src/mir --type rust | grep -v "Module context" | grep -v "//" # Result: Only comments/docs remain ``` ## Acceptance ✅ cargo test --release --lib - 997 passed ✅ phase135_trim_mir_verify.sh - PASS ✅ phase132_exit_phi_parity.sh - 3/3 PASS ✅ All function-context `value_gen.next()` eliminated ## Effect - **Collision prevention**: No more ValueId collisions between function-level allocations and reserved PHI dsts - **SSOT compliance**: All ValueId allocation flows through single allocator - **Contract enforcement**: Phase 135 P1 contract_checks will catch violations immediately 🤖 Generated with Claude Code Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 19:37:30 +09:00
let _ = builder.next_value_id();
let _ = builder.next_value_id();
let bid2 = builder.allocate_binding_id();
assert_eq!(bid2.raw(), 2); // Still sequential
// Allocating more BindingIds should not affect ValueId counter
let _ = builder.allocate_binding_id();
let _ = builder.allocate_binding_id();
feat(mir): Phase 136 P0 - ValueId allocator SSOT 徹底(関数内経路から value_gen.next() 掃討) ## Summary Eliminates remaining `value_gen.next()` calls from function-context code paths, unifying all ValueId allocation through `MirBuilder::next_value_id()` SSOT allocator. ## Changes ### 1. Fixed `new_typed_value()` (src/mir/builder.rs:1068) **Before**: `let id = self.value_gen.next();` (bypasses function context) **After**: `let id = self.next_value_id();` (respects function context) This is a public API used in function context, so must use SSOT allocator to avoid collisions with reserved PHI dsts and function params. ### 2. Fixed test code (src/mir/builder.rs) **test_shadowing_binding_restore** (lines 1161, 1171): - Simulates function scope with `push_lexical_scope()` - Changed to `builder.next_value_id()` for function scope simulation **test_valueid_binding_parallel_allocation** (lines 1196-1216): - Tests ValueId/BindingId independence - Changed to `builder.next_value_id()` with note that Module context fallback preserves test intent ### 3. Verified Module context fallbacks (OK, no change needed) These already check `current_function.is_some()` and use `value_gen.next()` only as Module context fallback: - `src/mir/builder/utils.rs:43` - next_value_id() SSOT implementation - `src/mir/builder/utils.rs:436` - pin_to_slot() - `src/mir/builder/utils.rs:467` - materialize_local() - `src/mir/utils/phi_helpers.rs:69` - insert_phi_unified() ## Verification ```bash rg -n "value_gen\.next\(" src/mir --type rust | grep -v "Module context" | grep -v "//" # Result: Only comments/docs remain ``` ## Acceptance ✅ cargo test --release --lib - 997 passed ✅ phase135_trim_mir_verify.sh - PASS ✅ phase132_exit_phi_parity.sh - 3/3 PASS ✅ All function-context `value_gen.next()` eliminated ## Effect - **Collision prevention**: No more ValueId collisions between function-level allocations and reserved PHI dsts - **SSOT compliance**: All ValueId allocation flows through single allocator - **Contract enforcement**: Phase 135 P1 contract_checks will catch violations immediately 🤖 Generated with Claude Code Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-15 19:37:30 +09:00
let vid2 = builder.next_value_id();
assert_eq!(vid2.0, 4); // Continues from where we left off
}
}