behavior-contracts 0.2.5

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 を additive に切り出す。
//!
//! 最重要規律(AC 7): **演算子意味論は再実装しない。** 各 primitive は Expression IR の
//! 単一キーノード(`serde_json::json!`)を組んで既存 SSoT [`crate::expr::evaluate`] へ委譲する
//! だけの薄いラッパ。よって意味論(INT_OVERFLOW / PRECISION_LOSS / MOD_ZERO / NULL_REF /
//! TYPE_MISMATCH / 短絡未評価 / code-point 順 等)は `evaluate` と**完全一致**する。
//!
//! 短絡の保存: `and`/`or`/`cond`/`coalesce` は **未評価の IR ノード**(`&J`)を引数に取り、
//! 内部で `evaluate` が短絡する(値を先に渡す API は採らない)。
//!
//! 加えて run_plan / run_plan_parallel の bounded 並行 / skip・unproduced / hydration helper を
//! 再エクスポートまたは薄く公開する(いずれも既存実装を SSoT として共有)。

use crate::expr::{evaluate, ExprFailure, ExprFailureCode};
use crate::plan::RelationKind;
use crate::value::Value;
use serde_json::{json, Value as J};

/// 未評価の Expression IR ノード(primitive の被演算子)。
pub type Expr = J;
/// primitive の返却型(`evaluate` と同一)。
pub type R = Result<Value, ExprFailure>;

// ── (a) Expression IR 全演算子の個別 primitive ────────────────────────────────
// 各関数は単一キーの IR ノードを組んで evaluate に委譲する(意味論 SSoT は evaluate 一本)。

/// 参照。中間 null は NULL_REF。
pub fn r#ref(path: &[&str], scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "ref": path }), scope)
}
/// null 安全参照。中間 null は null 伝播。
pub fn ref_opt(path: &[&str], scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "refOpt": path }), scope)
}
/// `{int:"..."}` リテラル(i64 checked)。
pub fn int_lit(literal: &str, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "int": literal }), scope)
}
/// `{float:n}` リテラル(NaN/Inf は NAN_OR_INF)。
pub fn float_lit(n: f64, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "float": n }), scope)
}
/// object 構築(own key `__proto__` は FORBIDDEN_KEY)。
pub fn obj(fields: &J, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "obj": fields }), scope)
}
/// array 構築。
pub fn arr(elems: &[J], scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "arr": elems }), scope)
}

/// 加算(int×int / float×float checked。混在は TYPE_MISMATCH)。
pub fn add(a: &Expr, b: &Expr, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "add": [a, b] }), scope)
}
/// 減算。
pub fn sub(a: &Expr, b: &Expr, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "sub": [a, b] }), scope)
}
/// 乗算。
pub fn mul(a: &Expr, b: &Expr, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "mul": [a, b] }), scope)
}
/// 単項マイナス。
pub fn neg(a: &Expr, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "neg": [a] }), scope)
}
/// 除算(常に float。|int|>2^53 は PRECISION_LOSS、0除算は NAN_OR_INF)。
pub fn div(a: &Expr, b: &Expr, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "div": [a, b] }), scope)
}
/// 剰余(truncated、符号は被除数。int の 0 剰余は MOD_ZERO)。
pub fn r#mod(a: &Expr, b: &Expr, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "mod": [a, b] }), scope)
}

/// 文字列連結(n-ary, min 2。string のみ)。
pub fn concat(parts: &[J], scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "concat": parts }), scope)
}

/// 等価(同一スカラ型のみ。null==null 可)。
pub fn eq(a: &Expr, b: &Expr, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "eq": [a, b] }), scope)
}
/// 非等価。
pub fn ne(a: &Expr, b: &Expr, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "ne": [a, b] }), scope)
}
/// 小なり(同一型 int/float/string。string は code-point 順)。
pub fn lt(a: &Expr, b: &Expr, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "lt": [a, b] }), scope)
}
/// 以下。
pub fn le(a: &Expr, b: &Expr, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "le": [a, b] }), scope)
}
/// 大なり。
pub fn gt(a: &Expr, b: &Expr, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "gt": [a, b] }), scope)
}
/// 以上。
pub fn ge(a: &Expr, b: &Expr, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "ge": [a, b] }), scope)
}

/// 論理積(短絡: a=false なら b は評価されない)。b は未評価 IR で渡す。
pub fn and(a: &Expr, b: &Expr, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "and": [a, b] }), scope)
}
/// 論理和(短絡: a=true なら b は評価されない)。
pub fn or(a: &Expr, b: &Expr, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "or": [a, b] }), scope)
}
/// 論理否定(strict bool。truthiness なし)。
pub fn not(a: &Expr, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "not": [a] }), scope)
}
/// null 合体(左が null のときだけ右を評価)。右は未評価 IR で渡す。
pub fn coalesce(a: &Expr, b: &Expr, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "coalesce": [a, b] }), scope)
}
/// 条件(strict bool。採用側のみ評価)。then/else は未評価 IR で渡す。
pub fn cond(c: &Expr, then: &Expr, els: &Expr, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "cond": [c, then, els] }), scope)
}
/// 配列長(配列のみ。string length は v1 に無い)。
pub fn len(a: &Expr, scope: &[(String, Value)]) -> R {
    evaluate(&json!({ "len": [a] }), scope)
}

/// 生の Expression IR を直接評価する汎用 primitive(意味論は個別 primitive と同一 SSoT)。
pub fn eval_expr(node: &Expr, scope: &[(String, Value)]) -> R {
    evaluate(node, scope)
}

// ── (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)
}