behavior-contracts 0.12.1 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,334 @@
1
+ package coderuntime
2
+
3
+ // exprcore.go — the expression-operator value-core (semantics SSoT), split out
4
+ // of the parent package's expr.go so the JSON-free codegen surface owns it.
5
+ //
6
+ // Every operator's semantics (INT_OVERFLOW / PRECISION_LOSS / MOD_ZERO /
7
+ // NULL_REF / TYPE_MISMATCH / code-point order / FORBIDDEN_KEY / finite-float
8
+ // discipline) is implemented ONCE here, over already-evaluated Values. The
9
+ // native primitives in primitives.go (*Native, called by generated straight-line
10
+ // code) and the IR interpreter's evalOp arms (parent package expr.go) both
11
+ // delegate to these functions — the interpreter and generated code cannot
12
+ // diverge (expression-ir.md §2/§3).
13
+
14
+ import (
15
+ "fmt"
16
+ "math"
17
+ "strconv"
18
+ "strings"
19
+ )
20
+
21
+ // ExprFailure is an expression evaluation Failure with a stable code (PROTOCOL §3.1).
22
+ type ExprFailure struct {
23
+ Code string
24
+ Msg string
25
+ Detail *ErrorDetail
26
+ }
27
+
28
+ func (e *ExprFailure) Error() string { return e.Code + ": " + e.Msg }
29
+
30
+ func exprFail(code, msg string) *ExprFailure { return &ExprFailure{Code: code, Msg: msg} }
31
+
32
+ const widenExact = int64(1) << 53 // ±2^53 exact in float64
33
+
34
+ // ForbiddenObjectKey is rejected fail-closed anywhere an object is built from
35
+ // IR/JSON-derived arbitrary string keys (obj node eval, DecodeValue, canonical).
36
+ // JS drops a "__proto__" own key (prototype setter) while Go/Python/Rust keep it,
37
+ // so the same IR diverges across languages (prototype-pollution footgun); all
38
+ // languages fail with FORBIDDEN_KEY instead (expression-ir.md §2.3/§8).
39
+ const ForbiddenObjectKey = "__proto__"
40
+
41
+ // CheckFinite rejects NaN/±Inf with a NAN_OR_INF Failure (finite-float boundary
42
+ // discipline). It is the float-result gate every arithmetic arm routes through.
43
+ func CheckFinite(v float64) (Value, error) {
44
+ if math.IsNaN(v) || math.IsInf(v, 0) {
45
+ return nil, exprFail("NAN_OR_INF", fmt.Sprintf("non-finite float: %v", v))
46
+ }
47
+ return v, nil
48
+ }
49
+
50
+ func widenToFloat(v Value) (float64, error) {
51
+ switch t := v.(type) {
52
+ case float64:
53
+ return t, nil
54
+ case int64:
55
+ if t > widenExact || t < -widenExact {
56
+ return 0, exprFail("PRECISION_LOSS", fmt.Sprintf("int %d exceeds exact float range (±2^53)", t))
57
+ }
58
+ return float64(t), nil
59
+ default:
60
+ return 0, exprFail("TYPE_MISMATCH", fmt.Sprintf("numeric operand expected, got %s", typeName(v)))
61
+ }
62
+ }
63
+
64
+ // RequireBool asserts strict bool (no truthiness), with the operator context in
65
+ // the TYPE_MISMATCH message.
66
+ func RequireBool(v Value, ctx string) (bool, error) {
67
+ if b, ok := v.(bool); ok {
68
+ return b, nil
69
+ }
70
+ return false, exprFail("TYPE_MISMATCH", fmt.Sprintf("%s: bool expected, got %s (no truthiness)", ctx, typeName(v)))
71
+ }
72
+
73
+ func intArith(op string, a, b int64) (Value, error) {
74
+ switch op {
75
+ case "add":
76
+ r := a + b
77
+ if (r > a) != (b > 0) {
78
+ return nil, exprFail("INT_OVERFLOW", "i64 overflow in add")
79
+ }
80
+ return r, nil
81
+ case "sub":
82
+ r := a - b
83
+ if (r < a) != (b > 0) {
84
+ return nil, exprFail("INT_OVERFLOW", "i64 overflow in sub")
85
+ }
86
+ return r, nil
87
+ default: // mul
88
+ if a == 0 || b == 0 {
89
+ return int64(0), nil
90
+ }
91
+ r := a * b
92
+ if r/b != a || (a == math.MinInt64 && b == -1) {
93
+ return nil, exprFail("INT_OVERFLOW", "i64 overflow in mul")
94
+ }
95
+ return r, nil
96
+ }
97
+ }
98
+
99
+ // ── 値受けオペレータ core(single-source)─────────────────────────────────────
100
+ // codegen の native 経路(primitives.go の *Native)は被演算子を評価済み Value に
101
+ // してから下の core を呼び、IR インタプリタ(親パッケージ expr.go)の evalOp の
102
+ // 各アームも同じ core を呼ぶ。意味論(overflow/finite/code-point 順/FORBIDDEN_KEY
103
+ // 等)は一本。
104
+
105
+ // ArithValues は add/sub/mul(int×int checked, float×float finite, 混在は TYPE_MISMATCH)。
106
+ func ArithValues(op string, a, b Value) (Value, error) {
107
+ ai, aok := a.(int64)
108
+ bi, bok := b.(int64)
109
+ if aok && bok {
110
+ return intArith(op, ai, bi)
111
+ }
112
+ af, aok2 := a.(float64)
113
+ bf, bok2 := b.(float64)
114
+ if aok2 && bok2 {
115
+ var r float64
116
+ switch op {
117
+ case "add":
118
+ r = af + bf
119
+ case "sub":
120
+ r = af - bf
121
+ default:
122
+ r = af * bf
123
+ }
124
+ return CheckFinite(r)
125
+ }
126
+ return nil, exprFail("TYPE_MISMATCH", fmt.Sprintf("%s: int×int or float×float (got %s×%s)", op, typeName(a), typeName(b)))
127
+ }
128
+
129
+ // NegValue は単項マイナス。
130
+ func NegValue(a Value) (Value, error) {
131
+ switch t := a.(type) {
132
+ case int64:
133
+ if t == math.MinInt64 {
134
+ return nil, exprFail("INT_OVERFLOW", "i64 overflow in neg")
135
+ }
136
+ return -t, nil
137
+ case float64:
138
+ return CheckFinite(-t)
139
+ default:
140
+ return nil, exprFail("TYPE_MISMATCH", fmt.Sprintf("neg: numeric expected, got %s", typeName(a)))
141
+ }
142
+ }
143
+
144
+ // DivValues は常に float 除算(0除算は NaN/Inf 規則で Failure)。
145
+ func DivValues(a, b Value) (Value, error) {
146
+ fa, err := widenToFloat(a)
147
+ if err != nil {
148
+ return nil, err
149
+ }
150
+ fb, err := widenToFloat(b)
151
+ if err != nil {
152
+ return nil, err
153
+ }
154
+ return CheckFinite(fa / fb)
155
+ }
156
+
157
+ // ModValues は truncated 剰余(int mod 0 は MOD_ZERO、MinInt64%-1 は 0)。
158
+ func ModValues(a, b Value) (Value, error) {
159
+ ai, aok := a.(int64)
160
+ bi, bok := b.(int64)
161
+ if aok && bok {
162
+ if bi == 0 {
163
+ return nil, exprFail("MOD_ZERO", "int mod by zero")
164
+ }
165
+ if ai == math.MinInt64 && bi == -1 {
166
+ return int64(0), nil
167
+ }
168
+ return ai % bi, nil
169
+ }
170
+ af, aok2 := a.(float64)
171
+ bf, bok2 := b.(float64)
172
+ if aok2 && bok2 {
173
+ return CheckFinite(math.Mod(af, bf))
174
+ }
175
+ return nil, exprFail("TYPE_MISMATCH", fmt.Sprintf("mod: int×int or float×float (got %s×%s)", typeName(a), typeName(b)))
176
+ }
177
+
178
+ // EqNeValues は eq/ne(valueEquals SSoT)。
179
+ func EqNeValues(op string, a, b Value) (Value, error) {
180
+ equal, err := valueEquals(a, b)
181
+ if err != nil {
182
+ return nil, err
183
+ }
184
+ if op == "eq" {
185
+ return equal, nil
186
+ }
187
+ return !equal, nil
188
+ }
189
+
190
+ // LenValue は配列長(配列のみ)。
191
+ func LenValue(a Value) (Value, error) {
192
+ arr, ok := a.([]Value)
193
+ if !ok {
194
+ return nil, exprFail("TYPE_MISMATCH", fmt.Sprintf("len: arrays only (string length is not v1; got %s)", typeName(a)))
195
+ }
196
+ return int64(len(arr)), nil
197
+ }
198
+
199
+ // IntLitValue は {int:"…"} リテラル(decimal string → i64、overflow と garbage を区別)。
200
+ func IntLitValue(s string) (Value, error) {
201
+ i, err := strconv.ParseInt(s, 10, 64)
202
+ if err != nil {
203
+ if isDecimalInt(s) {
204
+ return nil, exprFail("INT_OVERFLOW", "i64 overflow: "+s)
205
+ }
206
+ return nil, exprFail("INVALID_LITERAL", "invalid int literal: "+s)
207
+ }
208
+ return i, nil
209
+ }
210
+
211
+ // numberLitValue は bare number リテラル(§2.3 分類: 整数値かつ安全域→int、小数→float、範囲外→INVALID_LITERAL)。
212
+ func numberLitValue(n float64) (Value, error) {
213
+ const safe = float64(9007199254740991) // 2^53-1
214
+ if n == math.Trunc(n) && !math.IsInf(n, 0) && !math.IsNaN(n) {
215
+ if n >= -safe && n <= safe {
216
+ return int64(n), nil
217
+ }
218
+ return nil, exprFail("INVALID_LITERAL", fmt.Sprintf("integral literal %v exceeds safe range; use {int:\"…\"}", n))
219
+ }
220
+ return CheckFinite(n)
221
+ }
222
+
223
+ // CompareValues は lt/le/gt/ge(同一型 int/float/string のみ、string は code-point 順)。
224
+ // float は IEEE-754 の半順序: NaN が絡む対は順序付け不能で lt/le/gt/ge すべて false
225
+ // (int/string は全順序なので必ず順序が付く)。
226
+ func CompareValues(op string, a, b Value) (Value, error) {
227
+ var c int // -1, 0, 1
228
+ switch av := a.(type) {
229
+ case int64:
230
+ bv, ok := b.(int64)
231
+ if !ok {
232
+ return nil, cmpTypeErr(op, a, b)
233
+ }
234
+ c = cmpInt(av, bv)
235
+ case float64:
236
+ bv, ok := b.(float64)
237
+ if !ok {
238
+ return nil, cmpTypeErr(op, a, b)
239
+ }
240
+ var ordered bool
241
+ if c, ordered = cmpFloat(av, bv); !ordered {
242
+ return false, nil // 順序付け不能(NaN)
243
+ }
244
+ case string:
245
+ bv, ok := b.(string)
246
+ if !ok {
247
+ return nil, cmpTypeErr(op, a, b)
248
+ }
249
+ c = strings.Compare(av, bv) // byte-wise = code-point order
250
+ default:
251
+ return nil, cmpTypeErr(op, a, b)
252
+ }
253
+ switch op {
254
+ case "lt":
255
+ return c < 0, nil
256
+ case "le":
257
+ return c <= 0, nil
258
+ case "gt":
259
+ return c > 0, nil
260
+ default:
261
+ return c >= 0, nil
262
+ }
263
+ }
264
+
265
+ func cmpTypeErr(op string, a, b Value) error {
266
+ return exprFail("TYPE_MISMATCH", fmt.Sprintf("%s: same-typed int/float/string only (got %s×%s)", op, typeName(a), typeName(b)))
267
+ }
268
+
269
+ func cmpInt(a, b int64) int {
270
+ if a < b {
271
+ return -1
272
+ }
273
+ if a > b {
274
+ return 1
275
+ }
276
+ return 0
277
+ }
278
+
279
+ // cmpFloat は IEEE-754 の半順序。順序が付かない対(どちらかが NaN)は ordered=false。
280
+ func cmpFloat(a, b float64) (c int, ordered bool) {
281
+ if a < b {
282
+ return -1, true
283
+ }
284
+ if a > b {
285
+ return 1, true
286
+ }
287
+ if a == b {
288
+ return 0, true
289
+ }
290
+ return 0, false
291
+ }
292
+
293
+ func valueEquals(a, b Value) (bool, error) {
294
+ if a == nil || b == nil {
295
+ return a == nil && b == nil, nil
296
+ }
297
+ ta, tb := typeName(a), typeName(b)
298
+ if ta != tb {
299
+ return false, exprFail("TYPE_MISMATCH", fmt.Sprintf("eq/ne: same type only (got %s×%s)", ta, tb))
300
+ }
301
+ if ta == "arr" || ta == "obj" {
302
+ return false, exprFail("TYPE_MISMATCH", "eq/ne: obj/arr equality is undefined in v1")
303
+ }
304
+ // 残るのは同一型のスカラのみ。float は IEEE-754 の等価(NaN != NaN)。DeepEquals の
305
+ // 「NaN == NaN を等しいとみなす」は conformance の照合規則(PROTOCOL §4.1)であって
306
+ // 実行時 eq/ne の意味論ではない — 借りると生成物(`a == b` を直に出す)と食い違う。
307
+ switch av := a.(type) {
308
+ case bool:
309
+ return av == b.(bool), nil
310
+ case int64:
311
+ return av == b.(int64), nil
312
+ case float64:
313
+ return av == b.(float64), nil
314
+ case string:
315
+ return av == b.(string), nil
316
+ }
317
+ return false, exprFail("TYPE_MISMATCH", fmt.Sprintf("eq/ne: unsupported value type (%s)", ta))
318
+ }
319
+
320
+ func isDecimalInt(s string) bool {
321
+ if s == "" || s == "-" {
322
+ return false
323
+ }
324
+ body := s
325
+ if strings.HasPrefix(body, "-") {
326
+ body = body[1:]
327
+ }
328
+ for _, c := range body {
329
+ if c < '0' || c > '9' {
330
+ return false
331
+ }
332
+ }
333
+ return body != ""
334
+ }