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>
This commit is contained in:
@ -386,6 +386,19 @@ impl MirBuilder {
|
||||
arguments: &[ASTNode],
|
||||
) -> Result<Option<ValueId>, String> {
|
||||
let is_local_var = self.variable_map.contains_key(obj_name);
|
||||
|
||||
// Debug trace
|
||||
if std::env::var("NYASH_STATIC_CALL_TRACE").ok().as_deref() == Some("1") {
|
||||
eprintln!("[DEBUG] try_build_static_method_call: obj_name={}, method={}", obj_name, method);
|
||||
eprintln!("[DEBUG] is_local_var={}", is_local_var);
|
||||
if is_local_var {
|
||||
eprintln!("[DEBUG] variable_map contains '{}' - treating as local variable, will use method call", obj_name);
|
||||
eprintln!("[DEBUG] variable_map keys: {:?}", self.variable_map.keys().collect::<Vec<_>>());
|
||||
} else {
|
||||
eprintln!("[DEBUG] '{}' not in variable_map - treating as static box, will use global call", obj_name);
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 15.5: Treat unknown identifiers in receiver position as static type names
|
||||
if !is_local_var {
|
||||
let result = self.handle_static_method_call(obj_name, method, arguments)?;
|
||||
|
||||
@ -6,7 +6,7 @@
|
||||
*/
|
||||
|
||||
use crate::mir::{Callee, Effect, EffectMask, ValueId};
|
||||
use crate::mir::definitions::call_unified::{CallFlags, MirCall};
|
||||
use crate::mir::definitions::call_unified::{CallFlags, MirCall, TypeCertainty};
|
||||
use super::call_target::CallTarget;
|
||||
use super::method_resolution;
|
||||
use super::extern_calls;
|
||||
@ -19,13 +19,52 @@ pub fn is_unified_call_enabled() -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Classify box type to prevent static/runtime mixing
|
||||
/// Prevents Stage-B/Stage-1 compiler boxes from being confused with runtime data boxes
|
||||
pub fn classify_box_kind(box_name: &str) -> crate::mir::definitions::call_unified::CalleeBoxKind {
|
||||
use crate::mir::definitions::call_unified::CalleeBoxKind;
|
||||
|
||||
// Static compiler boxes (Stage-B, Stage-1, parsers, resolvers)
|
||||
// These should ONLY appear in static method lowering, never in runtime method dispatch
|
||||
match box_name {
|
||||
// Stage-B compiler boxes
|
||||
"StageBArgsBox" | "StageBBodyExtractorBox" | "StageBDriverBox" |
|
||||
// Stage-1 using/namespace resolver boxes
|
||||
"Stage1UsingResolverBox" | "BundleResolver" |
|
||||
// Parser boxes
|
||||
"ParserBox" | "ParserStmtBox" | "ParserExprBox" | "ParserControlBox" |
|
||||
"ParserLiteralBox" | "ParserTokenBox" |
|
||||
// Scanner/builder boxes
|
||||
"FuncScannerBox" | "MirBuilderBox" |
|
||||
// Other compiler-internal boxes
|
||||
"JsonFragBox"
|
||||
=> CalleeBoxKind::StaticCompiler,
|
||||
|
||||
// Runtime data boxes (built-in types that handle actual runtime values)
|
||||
"MapBox" | "ArrayBox" | "StringBox" | "IntegerBox" | "BoolBox" |
|
||||
"FloatBox" | "NullBox" | "VoidBox" | "UnknownBox" |
|
||||
"FileBox" | "ConsoleBox" | "PathBox"
|
||||
=> CalleeBoxKind::RuntimeData,
|
||||
|
||||
// Everything else is user-defined
|
||||
_ => CalleeBoxKind::UserDefined,
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert CallTarget to Callee
|
||||
/// Main translation layer between builder and MIR representations
|
||||
/// Convert CallTarget to Callee with type resolution
|
||||
/// 🎯 TypeRegistry 対応: NYASH_USE_TYPE_REGISTRY=1 で registry 優先
|
||||
pub fn convert_target_to_callee(
|
||||
target: CallTarget,
|
||||
value_origin_newbox: &std::collections::HashMap<ValueId, String>,
|
||||
value_types: &std::collections::HashMap<ValueId, crate::mir::MirType>,
|
||||
type_registry: Option<&crate::mir::builder::type_registry::TypeRegistry>,
|
||||
) -> Result<Callee, String> {
|
||||
let use_registry = std::env::var("NYASH_USE_TYPE_REGISTRY")
|
||||
.ok()
|
||||
.as_deref() == Some("1");
|
||||
|
||||
match target {
|
||||
CallTarget::Global(name) => {
|
||||
// Prefer explicit categories; otherwise treat as module-global function
|
||||
@ -40,32 +79,81 @@ pub fn convert_target_to_callee(
|
||||
},
|
||||
|
||||
CallTarget::Method { box_type, method, receiver } => {
|
||||
// 🔍 Debug: trace box_name resolution (before consuming box_type)
|
||||
let trace_enabled = std::env::var("NYASH_CALLEE_RESOLVE_TRACE").ok().as_deref() == Some("1");
|
||||
if trace_enabled {
|
||||
eprintln!("[callee-resolve] receiver=%{} method={}", receiver.0, method);
|
||||
eprintln!("[callee-resolve] explicit box_type: {:?}", box_type);
|
||||
eprintln!("[callee-resolve] use_registry: {}", use_registry);
|
||||
}
|
||||
|
||||
let inferred_box_type = box_type.unwrap_or_else(|| {
|
||||
// Try to infer box type from value origin or type annotation
|
||||
value_origin_newbox.get(&receiver)
|
||||
.cloned()
|
||||
.or_else(|| {
|
||||
value_types.get(&receiver)
|
||||
.and_then(|t| match t {
|
||||
crate::mir::MirType::Box(box_name) => Some(box_name.clone()),
|
||||
_ => None,
|
||||
})
|
||||
// 🎯 TypeRegistry 対応: 優先して registry から推論
|
||||
if use_registry {
|
||||
if let Some(reg) = type_registry {
|
||||
let inferred = reg.infer_class(receiver, None);
|
||||
if trace_enabled {
|
||||
eprintln!("[callee-resolve] from_registry: {}", inferred);
|
||||
// トレースチェーン表示
|
||||
let chain = reg.trace_origin(receiver);
|
||||
if !chain.is_empty() {
|
||||
eprintln!("[callee-resolve] trace_chain: {:?}", chain);
|
||||
}
|
||||
}
|
||||
return inferred;
|
||||
}
|
||||
}
|
||||
|
||||
// 従来: HashMap から推論(型情報を優先し、origin は補助とする)
|
||||
let from_type = value_types
|
||||
.get(&receiver)
|
||||
.and_then(|t| match t {
|
||||
crate::mir::MirType::Box(box_name) => Some(box_name.clone()),
|
||||
_ => None,
|
||||
});
|
||||
let from_origin = value_origin_newbox.get(&receiver).cloned();
|
||||
|
||||
if trace_enabled {
|
||||
eprintln!("[callee-resolve] from_type: {:?}", from_type);
|
||||
eprintln!("[callee-resolve] from_origin: {:?}", from_origin);
|
||||
}
|
||||
|
||||
// 型情報(MirType)がある場合はそれを優先し、無い場合のみ origin にフォールバックする。
|
||||
from_type
|
||||
.or(from_origin)
|
||||
.unwrap_or_else(|| {
|
||||
if trace_enabled {
|
||||
eprintln!("[callee-resolve] FALLBACK: UnknownBox");
|
||||
}
|
||||
"UnknownBox".to_string()
|
||||
})
|
||||
.unwrap_or_else(|| "UnknownBox".to_string())
|
||||
});
|
||||
|
||||
// Certainty is Known when origin propagation provides a concrete class name
|
||||
let certainty = if value_origin_newbox.contains_key(&receiver) {
|
||||
crate::mir::definitions::call_unified::TypeCertainty::Known
|
||||
// Certainty is Known when we have explicit origin or Box型の型情報を持つ場合
|
||||
let has_box_type = value_types
|
||||
.get(&receiver)
|
||||
.map(|t| matches!(t, crate::mir::MirType::Box(_)))
|
||||
.unwrap_or(false);
|
||||
let certainty = if value_origin_newbox.contains_key(&receiver) || has_box_type {
|
||||
TypeCertainty::Known
|
||||
} else {
|
||||
crate::mir::definitions::call_unified::TypeCertainty::Union
|
||||
TypeCertainty::Union
|
||||
};
|
||||
|
||||
// Classify box kind to prevent static/runtime mixing
|
||||
let box_kind = classify_box_kind(&inferred_box_type);
|
||||
|
||||
if trace_enabled {
|
||||
eprintln!("[callee-resolve] inferred_box_name: {}", inferred_box_type);
|
||||
eprintln!("[callee-resolve] box_kind: {:?}", box_kind);
|
||||
}
|
||||
|
||||
Ok(Callee::Method {
|
||||
box_name: inferred_box_type,
|
||||
method,
|
||||
receiver: Some(receiver),
|
||||
certainty,
|
||||
box_kind,
|
||||
})
|
||||
},
|
||||
|
||||
|
||||
@ -89,6 +89,7 @@ impl MirBuilder {
|
||||
target.clone(),
|
||||
&self.value_origin_newbox,
|
||||
&self.value_types,
|
||||
Some(&self.type_registry), // 🎯 TypeRegistry を渡す
|
||||
) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
@ -105,6 +106,10 @@ impl MirBuilder {
|
||||
// Safety: ensure receiver is materialized even after callee conversion
|
||||
callee = self.materialize_receiver_in_callee(callee)?;
|
||||
|
||||
// Structural guard: prevent static compiler boxes from being called with runtime receivers
|
||||
// If box_kind is StaticCompiler but receiver has a runtime Box type, normalize to runtime
|
||||
callee = self.apply_static_runtime_guard(callee)?;
|
||||
|
||||
// Emit resolve.choose for method callee (dev-only; default OFF)
|
||||
if let Callee::Method { box_name, method, certainty, .. } = &callee {
|
||||
let chosen = format!("{}.{}{}", box_name, method, format!("/{}", arity_for_try));
|
||||
@ -123,7 +128,7 @@ impl MirBuilder {
|
||||
call_unified::validate_call_args(&callee, &args)?;
|
||||
|
||||
// Stability guard: decide route via RouterPolicyBox (behavior-preserving rules)
|
||||
if let Callee::Method { box_name, method, receiver: Some(r), certainty } = &callee {
|
||||
if let Callee::Method { box_name, method, receiver: Some(r), certainty, .. } = &callee {
|
||||
let route = crate::mir::builder::router::policy::choose_route(box_name, method, *certainty, arity_for_try);
|
||||
if let crate::mir::builder::router::policy::Route::BoxCall = route {
|
||||
if super::super::utils::builder_debug_enabled() || std::env::var("NYASH_LOCAL_SSA_TRACE").ok().as_deref() == Some("1") {
|
||||
@ -368,7 +373,7 @@ impl MirBuilder {
|
||||
callee: Callee,
|
||||
) -> Result<Callee, String> {
|
||||
match callee {
|
||||
Callee::Method { box_name, method, receiver: Some(r), certainty } => {
|
||||
Callee::Method { box_name, method, receiver: Some(r), certainty, box_kind } => {
|
||||
if std::env::var("NYASH_BUILDER_TRACE_RECV").ok().as_deref() == Some("1") {
|
||||
let current_fn = self
|
||||
.current_function
|
||||
@ -401,7 +406,7 @@ impl MirBuilder {
|
||||
}
|
||||
// Prefer pinning to a slot so start_new_block can propagate it across entries.
|
||||
let r_pinned = self.pin_to_slot(r, "@recv").unwrap_or(r);
|
||||
Ok(Callee::Method { box_name, method, receiver: Some(r_pinned), certainty })
|
||||
Ok(Callee::Method { box_name, method, receiver: Some(r_pinned), certainty, box_kind })
|
||||
}
|
||||
other => Ok(other),
|
||||
}
|
||||
@ -449,4 +454,60 @@ impl MirBuilder {
|
||||
effects: EffectMask::IO,
|
||||
})
|
||||
}
|
||||
|
||||
/// Structural guard: prevent static compiler boxes from mixing with runtime data boxes
|
||||
///
|
||||
/// 箱理論の「境界を作る」原則: Stage-B/Stage-1コンパイラBoxとランタイムDataBoxを
|
||||
/// 構造レベルで分離し、型メタデータの混入を防ぐ。
|
||||
///
|
||||
/// If box_kind is StaticCompiler but receiver has a runtime Box type (MapBox/ArrayBox/etc.),
|
||||
/// normalize box_name to the runtime type. This prevents cases like:
|
||||
/// - Stage1UsingResolverBox.get where receiver is actually MapBox
|
||||
/// - StageBArgsBox.length where receiver is actually ArrayBox
|
||||
///
|
||||
/// This is a Fail-Fast structural guard, not a fallback.
|
||||
fn apply_static_runtime_guard(&self, callee: Callee) -> Result<Callee, String> {
|
||||
use crate::mir::definitions::call_unified::CalleeBoxKind;
|
||||
|
||||
if let Callee::Method { ref box_name, ref method, receiver: Some(recv), certainty, box_kind } = callee {
|
||||
// Only apply guard if box_kind is StaticCompiler
|
||||
if box_kind == CalleeBoxKind::StaticCompiler {
|
||||
// Check if receiver has a Box type
|
||||
if let Some(crate::mir::MirType::Box(receiver_box)) = self.value_types.get(&recv) {
|
||||
let trace_enabled = std::env::var("NYASH_CALLEE_RESOLVE_TRACE").ok().as_deref() == Some("1");
|
||||
|
||||
// If receiver box type matches the static box name, this is a me-call
|
||||
// Let it through for static method lowering (don't normalize)
|
||||
if receiver_box == box_name {
|
||||
if trace_enabled {
|
||||
eprintln!("[static-runtime-guard] ME-CALL detected:");
|
||||
eprintln!(" {}.{} with receiver type: {} (same as box_name)", box_name, method, receiver_box);
|
||||
eprintln!(" → Allowing for static method lowering");
|
||||
}
|
||||
return Ok(callee); // Pass through unchanged
|
||||
}
|
||||
|
||||
// Otherwise, this is a true mix-up: runtime box with static box name
|
||||
// Normalize to the runtime box type
|
||||
if trace_enabled {
|
||||
eprintln!("[static-runtime-guard] CORRECTING mix-up:");
|
||||
eprintln!(" Original: {}.{} (box_kind=StaticCompiler)", box_name, method);
|
||||
eprintln!(" Receiver %{} has runtime type: {}", recv.0, receiver_box);
|
||||
eprintln!(" Normalized: {}.{}", receiver_box, method);
|
||||
}
|
||||
|
||||
return Ok(Callee::Method {
|
||||
box_name: receiver_box.clone(),
|
||||
method: method.clone(),
|
||||
receiver: Some(recv),
|
||||
certainty,
|
||||
box_kind: CalleeBoxKind::RuntimeData, // Switch to runtime
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// No guard needed, return as-is
|
||||
Ok(callee)
|
||||
}
|
||||
}
|
||||
|
||||
@ -46,7 +46,11 @@ impl MirBuilder {
|
||||
if context_active {
|
||||
self.variable_map.clear();
|
||||
self.value_origin_newbox.clear();
|
||||
// value_types は clear しない(パラメータ型情報を保持)
|
||||
// value_types も static box 単位で独立させる。
|
||||
// これにより、前の static box で使用された ValueId に紐づく型情報が
|
||||
// 次の box にリークして誤った box_name 推論(例: Stage1UsingResolverBox)
|
||||
// を引き起こすことを防ぐ。
|
||||
self.value_types.clear();
|
||||
}
|
||||
|
||||
LoweringContext {
|
||||
@ -170,7 +174,8 @@ impl MirBuilder {
|
||||
// BoxCompilationContext mode: clear のみ(次回も完全独立)
|
||||
self.variable_map.clear();
|
||||
self.value_origin_newbox.clear();
|
||||
// value_types は clear しない(パラメータ型情報を保持)
|
||||
// static box ごとに型情報も独立させる(前 box の型メタデータを引きずらない)
|
||||
self.value_types.clear();
|
||||
} else if let Some(saved) = ctx.saved_var_map {
|
||||
// Legacy mode: Main.main 側の variable_map を元に戻す
|
||||
self.variable_map = saved;
|
||||
|
||||
@ -33,6 +33,7 @@ pub fn resolve_call_target(
|
||||
method: name.to_string(),
|
||||
receiver: None, // Static method call
|
||||
certainty: crate::mir::definitions::call_unified::TypeCertainty::Known,
|
||||
box_kind: super::call_unified::classify_box_kind(box_name),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user