behavior-contracts 0.5.0

Language-neutral IR runtime core (expression evaluation, template rendering, execution plan, canonical serialization) shared across DSL implementations. Passes the dsl-contracts conformance vectors byte-for-byte.
Documentation
//! primitives — codegen が直呼びできる安定 primitive 公開面(bc#36 / typed-codegen.md §3.4)。
//!
//! A0 = 公開面の確定(emitter 生成ロジックは A1/#37)。生成コードが「細粒度 primitive を
//! 呼ぶ」ための callable surface。
//!
//! 最重要規律: **演算子意味論は再実装しない**、かつ **codegen は IR を出力しない**(bc no-ir
//! invariant)。各 native primitive は被演算子を**評価済み Value** で受け、意味論 SSoT の
//! [`crate::expr`] value-core(`arith`/`compare`/`make_obj`/… — `evaluate` の各アームと**同一実装**)
//! へ委譲する。よって意味論(INT_OVERFLOW / PRECISION_LOSS / MOD_ZERO / NULL_REF / TYPE_MISMATCH /
//! FORBIDDEN_KEY / code-point 順 等)は `evaluate` と完全一致(実装が一本なので divergence 不能)。
//! 短絡(and/or/cond/coalesce)は生成コードが native 制御フローで綴じ、bool 検査だけ primitive を使う。
//!
//! 生 IR をそのまま実行する経路(`ir` exec surface / execute_bundle)は `crate::expr::evaluate` を
//! 直接使う(primitives 面は経由しない)。
//!
//! 加えて run_plan / run_plan_parallel の bounded 並行 / skip・unproduced / hydration helper を
//! 再エクスポートまたは薄く公開する(いずれも既存実装を SSoT として共有)。

use crate::expr::{ExprFailure, ExprFailureCode};
use crate::plan::RelationKind;
use crate::value::Value;

/// primitive の返却型(`crate::expr::evaluate` と同一)。
pub type R = Result<Value, ExprFailure>;

// ── (a) 演算子/構築/リテラルの codegen callable surface ───────────────────────
// bc no-ir invariant: codegen は IR を出力しない。かつてここには「単一キー IR ノードを組んで
// `evaluate` に委譲する」薄いラッパ(ref/obj/add/…/eval_expr)が並んでいたが、それは生成コードに
// インタプリタを再導入する松葉杖だった。撤去済み。callable surface は下記 (f)/(f0) の *_native
// のみ(被演算子を評価済み Value で受け、`crate::expr::*` value-core = evaluate と同一実装へ委譲)。
// 生 IR の実行が要る経路(`ir` exec surface / execute_bundle)は `crate::expr::evaluate` を直接使う。

// ── (f0) 演算子/構築/リテラルのネイティブ面(bc no-ir invariant)──────────────────
//
// 直線 emitter (A2 rust) は被演算子を native emit → `?` で評価済み Value を得て、下の native
// primitive に **値のまま**渡す。これらは `evaluate`(インタプリタ)も `json!`(IR ノード
// 構築)も**呼ばない**。意味論(overflow / finite / code-point 順 / MOD_ZERO / FORBIDDEN_KEY /
// short-circuit の bool 検査 等)は SSoT の `crate::expr::*` value-core を Value 直で呼ぶ
// ——core は `evaluate` と**実装が一本**なので divergence しない。短絡(and/or/coalesce/cond)は
// 生成コード側が native 制御フローで表現し、bool 検査だけ `require_bool_native` を使う。

/// add / sub / mul(被演算子は評価済み Value)。
pub fn add_native(a: Value, b: Value) -> R {
    crate::expr::arith("add", &a, &b)
}
pub fn sub_native(a: Value, b: Value) -> R {
    crate::expr::arith("sub", &a, &b)
}
pub fn mul_native(a: Value, b: Value) -> R {
    crate::expr::arith("mul", &a, &b)
}
pub fn neg_native(a: Value) -> R {
    crate::expr::neg(&a)
}
pub fn div_native(a: Value, b: Value) -> R {
    crate::expr::div(&a, &b)
}
pub fn mod_native(a: Value, b: Value) -> R {
    crate::expr::rem(&a, &b)
}
pub fn eq_native(a: Value, b: Value) -> R {
    crate::expr::eq_ne("eq", &a, &b)
}
pub fn ne_native(a: Value, b: Value) -> R {
    crate::expr::eq_ne("ne", &a, &b)
}
pub fn lt_native(a: Value, b: Value) -> R {
    crate::expr::compare("lt", &a, &b)
}
pub fn le_native(a: Value, b: Value) -> R {
    crate::expr::compare("le", &a, &b)
}
pub fn gt_native(a: Value, b: Value) -> R {
    crate::expr::compare("gt", &a, &b)
}
pub fn ge_native(a: Value, b: Value) -> R {
    crate::expr::compare("ge", &a, &b)
}
pub fn len_native(a: Value) -> R {
    crate::expr::len(&a)
}
/// not(bool 検査 → 反転)。
pub fn not_native(a: Value) -> R {
    Ok(Value::Bool(!crate::expr::require_bool(&a, "not")?))
}

/// obj 構築(キーは静的・順序保存で codegen が渡す。`__proto__` は FORBIDDEN_KEY)。
pub fn obj_native(pairs: Vec<(String, Value)>) -> R {
    crate::expr::make_obj(pairs)
}
/// arr 構築(要素は評価済み Value)。
pub fn arr_native(elems: Vec<Value>) -> R {
    Ok(Value::Arr(elems))
}

/// `{int:"…"}` リテラル。
pub fn int_lit_native(s: &str) -> R {
    crate::expr::int_lit(s)
}
/// `{float:n}` リテラル。
pub fn float_lit_native(n: f64) -> R {
    crate::expr::float_lit(n)
}
/// bare number リテラル(§2.3 分類)。
pub fn number_lit_native(n: f64) -> R {
    crate::expr::number_lit(n)
}
/// bare スカラリテラル(null / bool / string)。型付き `R` を返すので生成コードで型注釈不要。
pub fn null_native() -> R {
    Ok(Value::Null)
}
pub fn bool_native(b: bool) -> R {
    Ok(Value::Bool(b))
}
pub fn str_native(s: &str) -> R {
    Ok(Value::Str(s.to_string()))
}

/// 短絡の bool 検査(and/or/cond/not の生成 native 制御フローが Value→bool に使う)。
pub fn require_bool_native(v: Value, ctx: &str) -> Result<bool, ExprFailure> {
    crate::expr::require_bool(&v, ctx)
}

// ── (f) 脱解釈ネイティブ面(Phase B — typed-codegen.md §4.1)─────────────────────
//
// 単純式(`ref`/`refOpt`/`concat`)は**式ツリーを `evaluate` で解釈しない**。直線 emitter
// (A2 rust) は各 port を下の native helper 直呼び+ネイティブ被演算子へ展開する。よって
// これらの関数は `evaluate`(インタプリタ)も `json!`(IR ノード構築)も**呼ばない**——
// scope walk と `String` 連結を直接行う。意味論(NULL_REF / MISSING_PROP / UNKNOWN_BINDING /
// TYPE_MISMATCH / refOpt の null 伝播 / code-point 連結)は [`crate::expr::evaluate`] の
// `ref`/`refOpt`/`concat` アームと**同一**になるよう写し取る(同じ ExprFailureCode を返す)。
// 対照的に overflow/短絡系(add/sub/…/and/or/cond/coalesce)は fail-closed 意味論を SSoT に
// 一本化するため上の `evaluate` 委譲 primitive を使い続ける(native 化しない)。

fn expr_fail(code: ExprFailureCode, message: String) -> ExprFailure {
    ExprFailure { code, message }
}

/// `ref` のネイティブ実装(`evaluate` 非経由)。scope→field を直接歩く。
/// 中間 null は `NULL_REF`(`evaluate` の `ref` アームと同一)。
pub fn ref_native(path: &[&str], scope: &[(String, Value)]) -> R {
    ref_walk(path, scope, false)
}

/// `refOpt` のネイティブ実装(`evaluate` 非経由)。中間 null は null 伝播。
pub fn ref_opt_native(path: &[&str], scope: &[(String, Value)]) -> R {
    ref_walk(path, scope, true)
}

/// scope 束縛 head → object field を native に歩く(`eval_ref` の写像)。`optional=true` は
/// 中間 null で null を返す(refOpt)、false は `NULL_REF`(ref)。
fn ref_walk(path: &[&str], scope: &[(String, Value)], optional: bool) -> R {
    let op = if optional { "refOpt" } else { "ref" };
    if path.is_empty() {
        return Err(expr_fail(
            ExprFailureCode::InvalidNode,
            format!("{op} expects a non-empty string path"),
        ));
    }
    let head = path[0];
    let mut cur: Value = match scope.iter().find(|(k, _)| k == head) {
        Some((_, v)) => v.clone(),
        None => {
            return Err(expr_fail(
                ExprFailureCode::UnknownBinding,
                format!("unknown binding: {head}"),
            ))
        }
    };
    for &seg in &path[1..] {
        match cur {
            Value::Null => {
                if optional {
                    return Ok(Value::Null);
                }
                return Err(expr_fail(
                    ExprFailureCode::NullRef,
                    format!("null intermediate at .{seg} (use ?.)"),
                ));
            }
            Value::Obj(ref pairs) => match pairs.iter().find(|(k, _)| k == seg) {
                Some((_, v)) => cur = v.clone(),
                None => {
                    return Err(expr_fail(
                        ExprFailureCode::MissingProp,
                        format!("missing property .{seg}"),
                    ))
                }
            },
            ref other => {
                return Err(expr_fail(
                    ExprFailureCode::TypeMismatch,
                    format!("cannot access .{seg} on {}", other.type_name()),
                ))
            }
        }
    }
    Ok(cur)
}

/// `concat` のネイティブ実装(`evaluate` 非経由)。既にネイティブ評価済みの parts を
/// `String::push_str` で連結する。非 string 部分は `TYPE_MISMATCH`(`evaluate` の `concat`
/// アームと同一)。arity<2 は不正 IR(`InvalidNode`)。parts は emitter が各要素を再帰的に
/// native emit した Value 列(=式ツリー解釈が消えている)。
pub fn concat_native(parts: &[Value]) -> R {
    if parts.len() < 2 {
        return Err(expr_fail(
            ExprFailureCode::InvalidNode,
            format!("concat expects >= 2 args, got {}", parts.len()),
        ));
    }
    let mut s = String::new();
    for p in parts {
        match p {
            Value::Str(part) => s.push_str(part),
            other => {
                return Err(expr_fail(
                    ExprFailureCode::TypeMismatch,
                    format!(
                        "concat: strings only (got {}; no implicit toString)",
                        other.type_name()
                    ),
                ))
            }
        }
    }
    Ok(Value::Str(s))
}

// ── (c) bounded 並行プリミティブ(順序保存)─────────────────────────────────────
/// 入力順を保存し in-flight を `concurrency` で上限する bounded 並行 map。
///
/// execution-plan.md §4 の determinism 規律(output[i]=worker(items[i]) / 完了順非依存 /
/// bounded dispatch)を単体 primitive として公開する。runtime は同期のため
/// [`std::thread::scope`] の scoped worker で実装する([`crate::plan::run_plan_parallel`] と同一機構)。
///
/// `worker` は `Fn + Sync`(並行呼び出し安全)を要求する。結果は index 固定スロットに書くため
/// 完了順に依存しない(逐次 map と同一の結果列)。
pub fn map_with_concurrency<T, U, F>(items: &[T], concurrency: i64, worker: F) -> Vec<U>
where
    T: Sync,
    U: Send,
    F: Fn(&T, usize) -> U + Sync,
{
    let n = items.len();
    let limit = concurrency.max(1) as usize;
    if limit <= 1 || n <= 1 {
        return items
            .iter()
            .enumerate()
            .map(|(i, it)| worker(it, i))
            .collect();
    }
    // 各スロットは Option<U>。worker は disjoint な index にしか書かないので競合しない。
    let mut slots: Vec<Option<U>> = (0..n).map(|_| None).collect();
    let cursor = std::sync::atomic::AtomicUsize::new(0);
    let workers = limit.min(n);
    let worker_ref = &worker;
    let items_ref = items;
    {
        // 生ポインタ経由で disjoint スロットへ書き込む(各 index は 1 worker のみが触る)。
        struct SlotsPtr<U>(*mut Option<U>);
        unsafe impl<U: Send> Sync for SlotsPtr<U> {}
        let base = SlotsPtr(slots.as_mut_ptr());
        std::thread::scope(|s| {
            for _ in 0..workers {
                let cursor = &cursor;
                let base = &base;
                s.spawn(move || loop {
                    let i = cursor.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    if i >= n {
                        break;
                    }
                    let out = worker_ref(&items_ref[i], i);
                    // SAFETY: index i はこの worker だけが取得した(AtomicUsize で一意)ので
                    // slots[i] への書き込みは disjoint・データ競合なし。
                    unsafe {
                        *base.0.add(i) = Some(out);
                    }
                });
            }
        });
    }
    slots
        .into_iter()
        .map(|o| o.expect("all slots filled"))
        .collect()
}

// ── (d) skip / unproduced-value helper ────────────────────────────────────────
/// 未生成 Port(Skip)の表現値。single→Null / connection→空 connection。
pub fn unproduced_value(kind: Option<RelationKind>) -> Value {
    match kind {
        Some(RelationKind::Connection) => skip_connection(),
        _ => Value::Null,
    }
}
/// single relation の未生成 = Null。
pub fn skip_single() -> Value {
    Value::Null
}
/// connection relation の未生成 = {items:[],cursor:null}。
pub fn skip_connection() -> Value {
    Value::Obj(vec![
        ("items".to_string(), Value::Arr(vec![])),
        ("cursor".to_string(), Value::Null),
    ])
}

// ── (e) hydration / relation helper ───────────────────────────────────────────
/// behavior.rs の map.into と同一規律の zip-attach helper。
///
/// `over` の各要素へ `key` で `values[k]` を書き戻した augment 済みリストを返す
/// (over と同じ長さ・順序、親不変=コピー、guard skip 要素は無変更で pass-through)。
/// `kept_idx` は augment 対象の over index(昇順)。augment 対象が object でなければ Err。
pub fn hydrate_into(
    over: &[Value],
    key: &str,
    kept_idx: &[usize],
    values: &[Value],
) -> Result<Vec<Value>, String> {
    let mut augmented: Vec<Value> = Vec::with_capacity(over.len());
    let mut k = 0usize;
    for (i, el) in over.iter().enumerate() {
        if k < kept_idx.len() && kept_idx[k] == i {
            match el {
                Value::Obj(pairs) => {
                    let mut next: Vec<(String, Value)> = pairs.clone();
                    // 既存 key を上書き(無ければ追記)。宣言順を保つ。
                    if let Some(slot) = next.iter_mut().find(|(kk, _)| kk == key) {
                        slot.1 = values[k].clone();
                    } else {
                        next.push((key.to_string(), values[k].clone()));
                    }
                    augmented.push(Value::Obj(next));
                }
                _ => {
                    return Err(format!(
                        "hydrate_into: element {i} is not an object (into requires object elements)"
                    ))
                }
            }
            k += 1;
        } else {
            augmented.push(el.clone());
        }
    }
    Ok(augmented)
}