behavior-contracts 0.3.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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
//! expr — reference evaluator for expression-ir.md (normative).
//!
//! Value model: int = checked i64 (overflow → Failure, never wrap/panic),
//! float = f64 (NaN/±Inf → Failure), string / bool / null / arr / obj.
//!
//! Normative points (§6/§8 traps):
//!   - int arithmetic is checked i64 (overflow = INT_OVERFLOW).
//!   - a result that becomes NaN/±Inf is a Failure.
//!   - mod is truncated division (sign follows dividend; Rust `%` already does this).
//!   - string comparison is code-point order (Rust `str` Ord = UTF-8 byte order = code point).
//!   - and/or/coalesce/cond short-circuit.
//!   - unknown operators fail closed.

use crate::value::{deep_equals, Value};
use serde_json::Value as J;

/// Expression failure codes (PROTOCOL §3.1).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExprFailureCode {
    IntOverflow,
    NanOrInf,
    ModZero,
    PrecisionLoss,
    TypeMismatch,
    NullRef,
    MissingProp,
    UnknownBinding,
    UnknownOp,
    InvalidNode,
    InvalidLiteral,
    ForbiddenKey,
}

/// Forbidden object key (expression-ir.md §2.3/§8). Any path that builds an object
/// from IR/JSON-derived arbitrary string keys must reject an own key equal to
/// `"__proto__"` fail-closed: JS drops it (prototype setter), while Python/Rust/Go
/// keep it, so the same IR diverges across languages (prototype-pollution footgun).
pub const FORBIDDEN_OBJECT_KEY: &str = "__proto__";

impl ExprFailureCode {
    /// The stable string form used for conformance code matching.
    pub fn as_str(self) -> &'static str {
        match self {
            ExprFailureCode::IntOverflow => "INT_OVERFLOW",
            ExprFailureCode::NanOrInf => "NAN_OR_INF",
            ExprFailureCode::ModZero => "MOD_ZERO",
            ExprFailureCode::PrecisionLoss => "PRECISION_LOSS",
            ExprFailureCode::TypeMismatch => "TYPE_MISMATCH",
            ExprFailureCode::NullRef => "NULL_REF",
            ExprFailureCode::MissingProp => "MISSING_PROP",
            ExprFailureCode::UnknownBinding => "UNKNOWN_BINDING",
            ExprFailureCode::UnknownOp => "UNKNOWN_OP",
            ExprFailureCode::InvalidNode => "INVALID_NODE",
            ExprFailureCode::InvalidLiteral => "INVALID_LITERAL",
            ExprFailureCode::ForbiddenKey => "FORBIDDEN_KEY",
        }
    }
}

#[derive(Debug, Clone)]
pub struct ExprFailure {
    pub code: ExprFailureCode,
    pub message: String,
}

impl std::fmt::Display for ExprFailure {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.code.as_str(), self.message)
    }
}
impl std::error::Error for ExprFailure {}

type R = Result<Value, ExprFailure>;

fn fail<T>(code: ExprFailureCode, message: impl Into<String>) -> Result<T, ExprFailure> {
    Err(ExprFailure {
        code,
        message: message.into(),
    })
}

const WIDEN_EXACT: i64 = 1 << 53; // ±2^53 exact in f64

fn check_finite(v: f64) -> R {
    if v.is_finite() {
        Ok(Value::Float(v))
    } else {
        fail(ExprFailureCode::NanOrInf, format!("non-finite float: {v}"))
    }
}

fn widen_to_float(v: &Value) -> Result<f64, ExprFailure> {
    match v {
        Value::Float(f) => Ok(*f),
        Value::Int(i) => {
            if *i > WIDEN_EXACT || *i < -WIDEN_EXACT {
                fail(
                    ExprFailureCode::PrecisionLoss,
                    format!("int {i} exceeds exact float range (±2^53)"),
                )
            } else {
                Ok(*i as f64)
            }
        }
        other => fail(
            ExprFailureCode::TypeMismatch,
            format!("numeric operand expected, got {}", other.type_name()),
        ),
    }
}

/// Compare two strings by code point. Rust `str` Ord IS UTF-8 byte order which
/// equals Unicode code-point order, so we can delegate to the native comparison.
/// Kept as a named function to make the normative choice explicit.
pub fn cmp_code_points(a: &str, b: &str) -> std::cmp::Ordering {
    a.cmp(b)
}

pub(crate) fn require_bool(v: &Value, ctx: &str) -> Result<bool, ExprFailure> {
    match v {
        Value::Bool(b) => Ok(*b),
        other => fail(
            ExprFailureCode::TypeMismatch,
            format!(
                "{ctx}: bool expected, got {} (no truthiness)",
                other.type_name()
            ),
        ),
    }
}

// ── 値受けオペレータ core(single-source)─────────────────────────────────────
// codegen(A2 rust)の native 経路が「被演算子を native 評価済みの Value」で直呼びし、
// `eval_op` の各アームも同じ core を呼ぶ。意味論(overflow / finite / code-point 順 /
// FORBIDDEN_KEY 等)は evaluate と完全一致(実装が一本なので divergence 不能)。

/// add / sub / mul(int×int は checked、float×float は finite 検査、混在は TYPE_MISMATCH)。
pub(crate) fn arith(op: &str, a: &Value, b: &Value) -> R {
    match (a, b) {
        (Value::Int(x), Value::Int(y)) => {
            let r = match op {
                "add" => x.checked_add(*y),
                "sub" => x.checked_sub(*y),
                _ => x.checked_mul(*y),
            };
            match r {
                Some(v) => Ok(Value::Int(v)),
                None => fail(
                    ExprFailureCode::IntOverflow,
                    format!("i64 overflow in {op}"),
                ),
            }
        }
        (Value::Float(x), Value::Float(y)) => {
            let r = match op {
                "add" => x + y,
                "sub" => x - y,
                _ => x * y,
            };
            check_finite(r)
        }
        _ => fail(
            ExprFailureCode::TypeMismatch,
            format!(
                "{op}: int×int or float×float (got {}×{})",
                a.type_name(),
                b.type_name()
            ),
        ),
    }
}

/// neg(int は checked_neg、float は finite)。
pub(crate) fn neg(a: &Value) -> R {
    match a {
        Value::Int(i) => match i.checked_neg() {
            Some(v) => Ok(Value::Int(v)),
            None => fail(ExprFailureCode::IntOverflow, "i64 overflow in neg"),
        },
        Value::Float(f) => check_finite(-f),
        other => fail(
            ExprFailureCode::TypeMismatch,
            format!("neg: numeric expected, got {}", other.type_name()),
        ),
    }
}

/// div(常に float 除算・0除算は NaN/Inf 規則で Failure)。
pub(crate) fn div(a: &Value, b: &Value) -> R {
    let fa = widen_to_float(a)?;
    let fb = widen_to_float(b)?;
    check_finite(fa / fb)
}

/// mod(truncated・符号は被除数。int mod 0 は MOD_ZERO、i64::MIN%-1 は checked_rem で overflow)。
pub(crate) fn rem(a: &Value, b: &Value) -> R {
    match (a, b) {
        (Value::Int(x), Value::Int(y)) => {
            if *y == 0 {
                return fail(ExprFailureCode::ModZero, "int mod by zero");
            }
            match x.checked_rem(*y) {
                Some(v) => Ok(Value::Int(v)),
                None => fail(ExprFailureCode::IntOverflow, "i64 overflow in mod"),
            }
        }
        (Value::Float(x), Value::Float(y)) => check_finite(x % y),
        _ => fail(
            ExprFailureCode::TypeMismatch,
            format!(
                "mod: int×int or float×float (got {}×{})",
                a.type_name(),
                b.type_name()
            ),
        ),
    }
}

/// eq / ne(value_equals SSoT。arr/obj は TYPE_MISMATCH は value_equals 内で判定)。
pub(crate) fn eq_ne(op: &str, a: &Value, b: &Value) -> R {
    let equal = value_equals(a, b)?;
    Ok(Value::Bool(if op == "eq" { equal } else { !equal }))
}

/// lt / le / gt / ge(同一型 int/float/string のみ。string は code-point 順)。
pub(crate) fn compare(op: &str, a: &Value, b: &Value) -> R {
    use std::cmp::Ordering;
    let c: Ordering = match (a, b) {
        (Value::Int(x), Value::Int(y)) => x.cmp(y),
        (Value::Float(x), Value::Float(y)) => x.partial_cmp(y).unwrap_or(Ordering::Equal),
        (Value::Str(x), Value::Str(y)) => cmp_code_points(x, y),
        _ => {
            return fail(
                ExprFailureCode::TypeMismatch,
                format!(
                    "{op}: same-typed int/float/string only (got {}×{})",
                    a.type_name(),
                    b.type_name()
                ),
            )
        }
    };
    let res = match op {
        "lt" => c == Ordering::Less,
        "le" => c != Ordering::Greater,
        "gt" => c == Ordering::Greater,
        _ => c != Ordering::Less,
    };
    Ok(Value::Bool(res))
}

/// obj 構築。`__proto__` キーは fail-closed(FORBIDDEN_KEY)。キーは codegen では静的なので
/// 生成側が順序どおり本 core を呼ぶ(値は評価済み Value)。
pub(crate) fn make_obj(pairs: Vec<(String, Value)>) -> R {
    for (k, _) in &pairs {
        if k == FORBIDDEN_OBJECT_KEY {
            return fail(
                ExprFailureCode::ForbiddenKey,
                format!("obj key \"{FORBIDDEN_OBJECT_KEY}\" is forbidden (fail-closed)"),
            );
        }
    }
    Ok(Value::Obj(pairs))
}

/// len(配列のみ。string length は v1 に無い)。
pub(crate) fn len(a: &Value) -> R {
    match a {
        Value::Arr(v) => Ok(Value::Int(v.len() as i64)),
        other => fail(
            ExprFailureCode::TypeMismatch,
            format!(
                "len: arrays only (string length is not v1; got {})",
                other.type_name()
            ),
        ),
    }
}

const SAFE_INT: i64 = 9_007_199_254_740_991; // 2^53-1

/// `{int:"…"}` リテラル(decimal 文字列 → i64。overflow と garbage を区別)。
pub(crate) fn int_lit(s: &str) -> R {
    match s.parse::<i64>() {
        Ok(v) => Ok(Value::Int(v)),
        Err(_) => {
            if s.trim_start_matches('-')
                .chars()
                .all(|c| c.is_ascii_digit())
                && !s.is_empty()
                && s != "-"
            {
                fail(ExprFailureCode::IntOverflow, format!("i64 overflow: {s}"))
            } else {
                fail(
                    ExprFailureCode::InvalidLiteral,
                    format!("invalid int literal: {s}"),
                )
            }
        }
    }
}

/// `{float:n}` リテラル(finite 検査)。
pub(crate) fn float_lit(n: f64) -> R {
    check_finite(n)
}

/// bare number リテラル(§2.3 分類: 整数値かつ安全域 → int、小数 → float、整数だが範囲外 → INVALID_LITERAL)。
pub(crate) fn number_lit(n: f64) -> R {
    if n.is_finite() && n.fract() == 0.0 {
        if n.abs() <= SAFE_INT as f64 {
            Ok(Value::Int(n as i64))
        } else {
            fail(
                ExprFailureCode::InvalidLiteral,
                format!("integral literal {n} exceeds safe range; use {{int:\"\"}}"),
            )
        }
    } else {
        check_finite(n)
    }
}

/// Evaluate an IR expression node against a scope, producing a runtime [`Value`].
pub fn evaluate(node: &J, scope: &[(String, Value)]) -> R {
    match node {
        J::Null => Ok(Value::Null),
        J::Bool(b) => Ok(Value::Bool(*b)),
        J::String(s) => Ok(Value::Str(s.clone())),
        J::Number(n) => {
            // Classification (§2.3): integral → int (must be safe-range), fractional → float.
            if n.is_i64() {
                let i = n.as_i64().unwrap();
                // safe integer check: |i| <= 2^53-1
                const SAFE: i64 = 9_007_199_254_740_991;
                if !(-SAFE..=SAFE).contains(&i) {
                    return fail(
                        ExprFailureCode::InvalidLiteral,
                        format!("integral literal {i} exceeds safe range; use {{int:\"\"}}"),
                    );
                }
                Ok(Value::Int(i))
            } else if n.is_u64() {
                // u64 beyond i64 => beyond safe range
                fail(
                    ExprFailureCode::InvalidLiteral,
                    format!("integral literal {n} exceeds safe range; use {{int:\"\"}}"),
                )
            } else {
                let f = n.as_f64().ok_or(ExprFailure {
                    code: ExprFailureCode::InvalidLiteral,
                    message: format!("bad number literal {n}"),
                })?;
                check_finite(f)
            }
        }
        J::Array(_) => fail(
            ExprFailureCode::InvalidNode,
            "bare array is not an expression (use {arr:[...]})",
        ),
        J::Object(map) => {
            if map.len() != 1 {
                let keys: Vec<&str> = map.keys().map(|s| s.as_str()).collect();
                return fail(
                    ExprFailureCode::InvalidNode,
                    format!(
                        "operator node must have exactly one key, got [{}]",
                        keys.join(", ")
                    ),
                );
            }
            let (op, arg) = map.iter().next().unwrap();
            eval_op(op, arg, scope)
        }
    }
}

fn eval_op(op: &str, arg: &J, scope: &[(String, Value)]) -> R {
    match op {
        "int" => {
            let s = arg.as_str().ok_or_else(|| ExprFailure {
                code: ExprFailureCode::InvalidNode,
                message: "{int:…} expects a string".into(),
            })?;
            int_lit(s)
        }
        "float" => {
            let n = arg.as_f64().ok_or_else(|| ExprFailure {
                code: ExprFailureCode::InvalidNode,
                message: "{float:…} expects a number".into(),
            })?;
            float_lit(n)
        }
        "ref" | "refOpt" => eval_ref(op, arg, scope),
        "obj" => {
            let m = arg.as_object().ok_or_else(|| ExprFailure {
                code: ExprFailureCode::InvalidNode,
                message: "{obj:…} expects an object".into(),
            })?;
            // 順序どおり: __proto__ は値評価前に fail-closed(make_obj は評価済み対象なので
            // ここではキー検査を先に行い evaluate の順序を保つ)。
            let mut out = Vec::with_capacity(m.len());
            for (k, v) in m {
                if k == FORBIDDEN_OBJECT_KEY {
                    return fail(
                        ExprFailureCode::ForbiddenKey,
                        format!("obj key \"{FORBIDDEN_OBJECT_KEY}\" is forbidden (fail-closed)"),
                    );
                }
                out.push((k.clone(), evaluate(v, scope)?));
            }
            Ok(Value::Obj(out))
        }
        "arr" => {
            let a = arg_array(op, arg)?;
            let mut out = Vec::with_capacity(a.len());
            for e in a {
                out.push(evaluate(e, scope)?);
            }
            Ok(Value::Arr(out))
        }
        "add" | "sub" | "mul" => {
            let (a, b) = eval_binary(op, arg, scope)?;
            arith(op, &a, &b)
        }
        "neg" => {
            let a = evaluate(arg_unary(op, arg)?, scope)?;
            neg(&a)
        }
        "div" => {
            let (a, b) = eval_binary(op, arg, scope)?;
            div(&a, &b)
        }
        "mod" => {
            let (a, b) = eval_binary(op, arg, scope)?;
            rem(&a, &b)
        }
        "concat" => {
            let a = arg_array(op, arg)?;
            // n-ary(min 2 args)。arity<2 は不正 IR(expression-ir.md §2.1/§3/§6)。
            if a.len() < 2 {
                return fail(
                    ExprFailureCode::InvalidNode,
                    format!("concat expects >= 2 args, got {}", a.len()),
                );
            }
            let mut s = String::new();
            for e in a {
                match evaluate(e, scope)? {
                    Value::Str(p) => s.push_str(&p),
                    other => {
                        return fail(
                            ExprFailureCode::TypeMismatch,
                            format!(
                                "concat: strings only (got {}; no implicit toString)",
                                other.type_name()
                            ),
                        )
                    }
                }
            }
            Ok(Value::Str(s))
        }
        "eq" | "ne" => {
            let (a, b) = eval_binary(op, arg, scope)?;
            eq_ne(op, &a, &b)
        }
        "lt" | "le" | "gt" | "ge" => {
            let (a, b) = eval_binary(op, arg, scope)?;
            compare(op, &a, &b)
        }
        "and" | "or" => {
            let (ea, eb) = raw_binary(op, arg)?;
            let a = require_bool(&evaluate(ea, scope)?, op)?;
            if op == "and" && !a {
                return Ok(Value::Bool(false));
            }
            if op == "or" && a {
                return Ok(Value::Bool(true));
            }
            Ok(Value::Bool(require_bool(&evaluate(eb, scope)?, op)?))
        }
        "not" => {
            let a = require_bool(&evaluate(arg_unary(op, arg)?, scope)?, "not")?;
            Ok(Value::Bool(!a))
        }
        "coalesce" => {
            let (ea, eb) = raw_binary(op, arg)?;
            let a = evaluate(ea, scope)?;
            match a {
                Value::Null => evaluate(eb, scope),
                other => Ok(other),
            }
        }
        "cond" => {
            let a = arg
                .as_array()
                .filter(|a| a.len() == 3)
                .ok_or_else(|| ExprFailure {
                    code: ExprFailureCode::InvalidNode,
                    message: "cond expects [c, t, e]".into(),
                })?;
            let c = require_bool(&evaluate(&a[0], scope)?, "cond")?;
            evaluate(if c { &a[1] } else { &a[2] }, scope)
        }
        "len" => {
            let a = evaluate(arg_unary(op, arg)?, scope)?;
            len(&a)
        }
        _ => fail(
            ExprFailureCode::UnknownOp,
            format!("unknown operator: {op} (fail-closed)"),
        ),
    }
}

fn eval_ref(op: &str, arg: &J, scope: &[(String, Value)]) -> R {
    let path = arg_array(op, arg)?;
    if path.is_empty() || !path.iter().all(|p| p.is_string()) {
        return fail(
            ExprFailureCode::InvalidNode,
            format!("{op} expects a non-empty string path"),
        );
    }
    let head = path[0].as_str().unwrap();
    let mut cur: Value = match scope.iter().find(|(k, _)| k == head) {
        Some((_, v)) => v.clone(),
        None => {
            return fail(
                ExprFailureCode::UnknownBinding,
                format!("unknown binding: {head}"),
            )
        }
    };
    for seg_node in &path[1..] {
        let seg = seg_node.as_str().unwrap();
        match cur {
            Value::Null => {
                if op == "refOpt" {
                    return Ok(Value::Null);
                }
                return fail(
                    ExprFailureCode::NullRef,
                    format!("null intermediate at .{seg} (use ?.)"),
                );
            }
            Value::Obj(ref pairs) => match pairs.iter().find(|(k, _)| k == seg) {
                Some((_, v)) => {
                    let next = v.clone();
                    cur = next;
                }
                None => {
                    return fail(
                        ExprFailureCode::MissingProp,
                        format!("missing property .{seg}"),
                    )
                }
            },
            ref other => {
                return fail(
                    ExprFailureCode::TypeMismatch,
                    format!("cannot access .{seg} on {}", other.type_name()),
                )
            }
        }
    }
    Ok(cur)
}

/// Equality for eq/ne: null-vs-null allowed; otherwise same scalar type only.
fn value_equals(a: &Value, b: &Value) -> Result<bool, ExprFailure> {
    if matches!(a, Value::Null) || matches!(b, Value::Null) {
        return Ok(matches!(a, Value::Null) && matches!(b, Value::Null));
    }
    let ta = a.type_name();
    let tb = b.type_name();
    if ta != tb {
        return fail(
            ExprFailureCode::TypeMismatch,
            format!("eq/ne: same type only (got {ta}×{tb})"),
        );
    }
    if ta == "arr" || ta == "obj" {
        return fail(
            ExprFailureCode::TypeMismatch,
            "eq/ne: obj/arr equality is undefined in v1",
        );
    }
    Ok(deep_equals(a, b))
}

// ── arg helpers ──────────────────────────────────────────────────────────────
fn arg_array<'a>(op: &str, arg: &'a J) -> Result<&'a Vec<J>, ExprFailure> {
    arg.as_array().ok_or_else(|| ExprFailure {
        code: ExprFailureCode::InvalidNode,
        message: format!("{op} expects an args array"),
    })
}
fn arg_unary<'a>(op: &str, arg: &'a J) -> Result<&'a J, ExprFailure> {
    let a = arg_array(op, arg)?;
    if a.len() != 1 {
        return Err(ExprFailure {
            code: ExprFailureCode::InvalidNode,
            message: format!("{op} expects 1 arg"),
        });
    }
    Ok(&a[0])
}
fn raw_binary<'a>(op: &str, arg: &'a J) -> Result<(&'a J, &'a J), ExprFailure> {
    let a = arg_array(op, arg)?;
    if a.len() != 2 {
        return Err(ExprFailure {
            code: ExprFailureCode::InvalidNode,
            message: format!("{op} expects 2 args"),
        });
    }
    Ok((&a[0], &a[1]))
}
fn eval_binary(
    op: &str,
    arg: &J,
    scope: &[(String, Value)],
) -> Result<(Value, Value), ExprFailure> {
    let (ea, eb) = raw_binary(op, arg)?;
    Ok((evaluate(ea, scope)?, evaluate(eb, scope)?))
}