shape-value 0.1.4

NaN-boxed value representation and heap types for Shape
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
//! TypedScalar: type-preserving scalar boundary contract for VM↔JIT exchange.
//!
//! When scalar values cross the VM/JIT boundary, their type identity (int vs float)
//! must be preserved. `TypedScalar` carries an explicit `ScalarKind` discriminator
//! alongside the raw payload bits, eliminating the ambiguity between NaN-boxed I48
//! integers and plain f64 numbers.

use crate::slot::ValueSlot;
use crate::value_word::{NanTag, ValueWord};

/// Scalar type discriminator.
///
/// Covers all width-specific numeric types plus bool/none/unit sentinels.
/// Discriminant values are part of the ABI — do not reorder.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum ScalarKind {
    I8 = 0,
    U8 = 1,
    I16 = 2,
    U16 = 3,
    I32 = 4,
    U32 = 5,
    I64 = 6,
    U64 = 7,
    I128 = 8,
    U128 = 9,
    F32 = 10,
    F64 = 11,
    Bool = 12,
    None = 13,
    Unit = 14,
}

impl ScalarKind {
    /// True if this kind represents an integer type (signed or unsigned).
    #[inline]
    pub fn is_integer(self) -> bool {
        matches!(
            self,
            ScalarKind::I8
                | ScalarKind::U8
                | ScalarKind::I16
                | ScalarKind::U16
                | ScalarKind::I32
                | ScalarKind::U32
                | ScalarKind::I64
                | ScalarKind::U64
                | ScalarKind::I128
                | ScalarKind::U128
        )
    }

    /// True if this kind represents a floating-point type.
    #[inline]
    pub fn is_float(self) -> bool {
        matches!(self, ScalarKind::F32 | ScalarKind::F64)
    }

    /// True if this kind represents a numeric type (integer or float).
    #[inline]
    pub fn is_numeric(self) -> bool {
        self.is_integer() || self.is_float()
    }

    /// True if this kind represents an unsigned integer type.
    #[inline]
    pub fn is_unsigned_integer(self) -> bool {
        matches!(
            self,
            ScalarKind::U8 | ScalarKind::U16 | ScalarKind::U32 | ScalarKind::U64 | ScalarKind::U128
        )
    }

    /// True if this kind represents a signed integer type.
    #[inline]
    pub fn is_signed_integer(self) -> bool {
        matches!(
            self,
            ScalarKind::I8 | ScalarKind::I16 | ScalarKind::I32 | ScalarKind::I64 | ScalarKind::I128
        )
    }
}

/// Type-preserving scalar value for VM↔JIT boundary exchange.
///
/// Carries an explicit type discriminator (`kind`) so that integer 42 and
/// float 42.0 are distinguishable even when their f64 bit patterns would
/// be identical.
///
/// `payload_hi` is zero for all types smaller than 128 bits.
#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(C)]
pub struct TypedScalar {
    pub kind: ScalarKind,
    pub payload_lo: u64,
    /// Second 64-bit word — only used for I128/U128. Zero otherwise.
    pub payload_hi: u64,
}

impl TypedScalar {
    /// Create an I64 scalar.
    #[inline]
    pub fn i64(v: i64) -> Self {
        Self {
            kind: ScalarKind::I64,
            payload_lo: v as u64,
            payload_hi: 0,
        }
    }

    /// Create an F64 scalar from a value.
    #[inline]
    pub fn f64(v: f64) -> Self {
        Self {
            kind: ScalarKind::F64,
            payload_lo: v.to_bits(),
            payload_hi: 0,
        }
    }

    /// Create an F64 scalar from raw bits.
    #[inline]
    pub fn f64_from_bits(bits: u64) -> Self {
        Self {
            kind: ScalarKind::F64,
            payload_lo: bits,
            payload_hi: 0,
        }
    }

    /// Create a Bool scalar.
    #[inline]
    pub fn bool(v: bool) -> Self {
        Self {
            kind: ScalarKind::Bool,
            payload_lo: v as u64,
            payload_hi: 0,
        }
    }

    /// Create a None scalar.
    #[inline]
    pub fn none() -> Self {
        Self {
            kind: ScalarKind::None,
            payload_lo: 0,
            payload_hi: 0,
        }
    }

    /// Create a Unit scalar.
    #[inline]
    pub fn unit() -> Self {
        Self {
            kind: ScalarKind::Unit,
            payload_lo: 0,
            payload_hi: 0,
        }
    }

    /// Create an I8 scalar.
    #[inline]
    pub fn i8(v: i8) -> Self {
        Self {
            kind: ScalarKind::I8,
            payload_lo: v as i64 as u64,
            payload_hi: 0,
        }
    }

    /// Create a U8 scalar.
    #[inline]
    pub fn u8(v: u8) -> Self {
        Self {
            kind: ScalarKind::U8,
            payload_lo: v as u64,
            payload_hi: 0,
        }
    }

    /// Create an I16 scalar.
    #[inline]
    pub fn i16(v: i16) -> Self {
        Self {
            kind: ScalarKind::I16,
            payload_lo: v as i64 as u64,
            payload_hi: 0,
        }
    }

    /// Create a U16 scalar.
    #[inline]
    pub fn u16(v: u16) -> Self {
        Self {
            kind: ScalarKind::U16,
            payload_lo: v as u64,
            payload_hi: 0,
        }
    }

    /// Create an I32 scalar.
    #[inline]
    pub fn i32(v: i32) -> Self {
        Self {
            kind: ScalarKind::I32,
            payload_lo: v as i64 as u64,
            payload_hi: 0,
        }
    }

    /// Create a U32 scalar.
    #[inline]
    pub fn u32(v: u32) -> Self {
        Self {
            kind: ScalarKind::U32,
            payload_lo: v as u64,
            payload_hi: 0,
        }
    }

    /// Create a U64 scalar.
    #[inline]
    pub fn u64(v: u64) -> Self {
        Self {
            kind: ScalarKind::U64,
            payload_lo: v,
            payload_hi: 0,
        }
    }

    /// Create an F32 scalar.
    #[inline]
    pub fn f32(v: f32) -> Self {
        Self {
            kind: ScalarKind::F32,
            payload_lo: f64::from(v).to_bits(),
            payload_hi: 0,
        }
    }

    /// Extract as i64 (only valid if kind is an integer type).
    /// Returns None for U64 values > i64::MAX (use `as_u64()` instead).
    #[inline]
    pub fn as_i64(&self) -> Option<i64> {
        if self.kind == ScalarKind::U64 {
            i64::try_from(self.payload_lo).ok()
        } else if self.kind.is_integer() {
            Some(self.payload_lo as i64)
        } else {
            Option::None
        }
    }

    /// Extract as u64 (only valid if kind is an unsigned integer type).
    #[inline]
    pub fn as_u64(&self) -> Option<u64> {
        if self.kind.is_unsigned_integer() {
            Some(self.payload_lo)
        } else if self.kind.is_signed_integer() {
            // Signed → u64: return raw bits (caller interprets)
            Some(self.payload_lo)
        } else {
            Option::None
        }
    }

    /// Extract as f64 (only valid if kind is F64 or F32).
    #[inline]
    pub fn as_f64(&self) -> Option<f64> {
        match self.kind {
            ScalarKind::F64 => Some(f64::from_bits(self.payload_lo)),
            ScalarKind::F32 => Some(f64::from_bits(self.payload_lo)),
            _ => Option::None,
        }
    }

    /// Extract as bool (only valid if kind is Bool).
    #[inline]
    pub fn as_bool(&self) -> Option<bool> {
        if self.kind == ScalarKind::Bool {
            Some(self.payload_lo != 0)
        } else {
            Option::None
        }
    }

    /// Interpret this scalar as an f64 regardless of kind (for numeric comparison).
    /// Integer kinds are cast; float kinds use their stored value; non-numeric returns None.
    #[inline]
    pub fn to_f64_lossy(&self) -> Option<f64> {
        match self.kind {
            ScalarKind::F64 | ScalarKind::F32 => Some(f64::from_bits(self.payload_lo)),
            k if k.is_unsigned_integer() => Some(self.payload_lo as f64),
            k if k.is_signed_integer() => Some(self.payload_lo as i64 as f64),
            _ => Option::None,
        }
    }
}

// ============================================================================
// NumericWidth mapping
// ============================================================================

// Note: `From<NumericWidth> for ScalarKind` is implemented in shape-vm
// (where NumericWidth is defined) since shape-value cannot depend on shape-vm.

// ============================================================================
// ValueWord <-> TypedScalar conversions
// ============================================================================

impl ValueWord {
    /// Convert this ValueWord to a TypedScalar, preserving type identity.
    ///
    /// Returns `None` for heap-allocated values (strings, arrays, objects, etc.)
    /// which are not representable as scalars.
    #[inline]
    pub fn to_typed_scalar(&self) -> Option<TypedScalar> {
        match self.tag() {
            NanTag::F64 => {
                let bits = self.raw_bits();
                Some(TypedScalar {
                    kind: ScalarKind::F64,
                    payload_lo: bits,
                    payload_hi: 0,
                })
            }
            NanTag::I48 => {
                let i = unsafe { self.as_i64_unchecked() };
                Some(TypedScalar::i64(i))
            }
            NanTag::Bool => {
                let b = unsafe { self.as_bool_unchecked() };
                Some(TypedScalar::bool(b))
            }
            NanTag::None => Some(TypedScalar::none()),
            NanTag::Unit => Some(TypedScalar::unit()),
            NanTag::Heap | NanTag::Function | NanTag::ModuleFunction | NanTag::Ref => Option::None,
        }
    }

    /// Create a ValueWord from a TypedScalar.
    ///
    /// Integer kinds are stored as I48 (clamped to the 48-bit range; values
    /// outside [-2^47, 2^47-1] are heap-boxed as BigInt via `from_i64`).
    /// Float kinds are stored as plain f64. Bool/None/Unit use their direct
    /// ValueWord constructors.
    #[inline]
    pub fn from_typed_scalar(ts: TypedScalar) -> Self {
        match ts.kind {
            ScalarKind::I64 => ValueWord::from_i64(ts.payload_lo as i64),
            ScalarKind::I8 | ScalarKind::I16 | ScalarKind::I32 => {
                // Sign-extend to i64, then use from_i64
                ValueWord::from_i64(ts.payload_lo as i64)
            }
            ScalarKind::U8 | ScalarKind::U16 | ScalarKind::U32 => {
                // Unsigned sub-64: always fits in i64
                ValueWord::from_i64(ts.payload_lo as i64)
            }
            ScalarKind::U64 => {
                if ts.payload_lo <= i64::MAX as u64 {
                    ValueWord::from_i64(ts.payload_lo as i64)
                } else {
                    ValueWord::from_native_u64(ts.payload_lo)
                }
            }
            ScalarKind::I128 | ScalarKind::U128 => {
                // Truncate to i64 (best effort for 128-bit)
                ValueWord::from_i64(ts.payload_lo as i64)
            }
            ScalarKind::F64 => ValueWord::from_f64(f64::from_bits(ts.payload_lo)),
            ScalarKind::F32 => ValueWord::from_f64(f64::from_bits(ts.payload_lo)),
            ScalarKind::Bool => ValueWord::from_bool(ts.payload_lo != 0),
            ScalarKind::None => ValueWord::none(),
            ScalarKind::Unit => ValueWord::unit(),
        }
    }
}

// ============================================================================
// ValueSlot <- TypedScalar conversion
// ============================================================================

impl ValueSlot {
    /// Create a ValueSlot from a TypedScalar.
    ///
    /// Returns `(slot, is_heap)` — `is_heap` is always false for scalars
    /// since all scalar values fit in 8 bytes without heap allocation.
    #[inline]
    pub fn from_typed_scalar(ts: TypedScalar) -> (Self, bool) {
        match ts.kind {
            ScalarKind::I8 | ScalarKind::I16 | ScalarKind::I32 | ScalarKind::I64 => {
                (ValueSlot::from_int(ts.payload_lo as i64), false)
            }
            ScalarKind::U8 | ScalarKind::U16 | ScalarKind::U32 => {
                (ValueSlot::from_int(ts.payload_lo as i64), false)
            }
            ScalarKind::U64 => (ValueSlot::from_u64(ts.payload_lo), false),
            ScalarKind::I128 | ScalarKind::U128 => {
                (ValueSlot::from_int(ts.payload_lo as i64), false)
            }
            ScalarKind::F64 | ScalarKind::F32 => {
                (ValueSlot::from_number(f64::from_bits(ts.payload_lo)), false)
            }
            ScalarKind::Bool => (ValueSlot::from_bool(ts.payload_lo != 0), false),
            ScalarKind::None | ScalarKind::Unit => (ValueSlot::none(), false),
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tags::{I48_MAX, I48_MIN};

    #[test]
    fn round_trip_i64() {
        let vw = ValueWord::from_i64(42);
        let ts = vw.to_typed_scalar().unwrap();
        assert_eq!(ts.kind, ScalarKind::I64);
        assert_eq!(ts.payload_lo, 42u64);
        assert_eq!(ts.payload_hi, 0);
        let vw2 = ValueWord::from_typed_scalar(ts);
        assert_eq!(vw.raw_bits(), vw2.raw_bits());
    }

    #[test]
    fn round_trip_negative_i64() {
        let vw = ValueWord::from_i64(-99);
        let ts = vw.to_typed_scalar().unwrap();
        assert_eq!(ts.kind, ScalarKind::I64);
        assert_eq!(ts.payload_lo as i64, -99);
        let vw2 = ValueWord::from_typed_scalar(ts);
        assert_eq!(vw.raw_bits(), vw2.raw_bits());
    }

    #[test]
    fn round_trip_i48_max() {
        let vw = ValueWord::from_i64(I48_MAX);
        let ts = vw.to_typed_scalar().unwrap();
        assert_eq!(ts.kind, ScalarKind::I64);
        assert_eq!(ts.payload_lo as i64, I48_MAX);
        let vw2 = ValueWord::from_typed_scalar(ts);
        assert_eq!(vw.raw_bits(), vw2.raw_bits());
    }

    #[test]
    fn round_trip_i48_min() {
        let vw = ValueWord::from_i64(I48_MIN);
        let ts = vw.to_typed_scalar().unwrap();
        assert_eq!(ts.kind, ScalarKind::I64);
        assert_eq!(ts.payload_lo as i64, I48_MIN);
        let vw2 = ValueWord::from_typed_scalar(ts);
        assert_eq!(vw.raw_bits(), vw2.raw_bits());
    }

    #[test]
    fn round_trip_f64() {
        let vw = ValueWord::from_f64(3.14);
        let ts = vw.to_typed_scalar().unwrap();
        assert_eq!(ts.kind, ScalarKind::F64);
        assert_eq!(f64::from_bits(ts.payload_lo), 3.14);
        let vw2 = ValueWord::from_typed_scalar(ts);
        assert_eq!(vw.raw_bits(), vw2.raw_bits());
    }

    #[test]
    fn round_trip_f64_nan() {
        let vw = ValueWord::from_f64(f64::NAN);
        let ts = vw.to_typed_scalar().unwrap();
        assert_eq!(ts.kind, ScalarKind::F64);
        assert!(f64::from_bits(ts.payload_lo).is_nan());
        let vw2 = ValueWord::from_typed_scalar(ts);
        // Both should be canonical NaN
        assert_eq!(vw.raw_bits(), vw2.raw_bits());
    }

    #[test]
    fn round_trip_f64_infinity() {
        let vw = ValueWord::from_f64(f64::INFINITY);
        let ts = vw.to_typed_scalar().unwrap();
        assert_eq!(ts.kind, ScalarKind::F64);
        assert_eq!(f64::from_bits(ts.payload_lo), f64::INFINITY);
        let vw2 = ValueWord::from_typed_scalar(ts);
        assert_eq!(vw.raw_bits(), vw2.raw_bits());
    }

    #[test]
    fn round_trip_f64_neg_zero() {
        let vw = ValueWord::from_f64(-0.0);
        let ts = vw.to_typed_scalar().unwrap();
        assert_eq!(ts.kind, ScalarKind::F64);
        // -0.0 has specific bit pattern (sign bit set)
        assert_eq!(ts.payload_lo, (-0.0f64).to_bits());
        let vw2 = ValueWord::from_typed_scalar(ts);
        assert_eq!(vw.raw_bits(), vw2.raw_bits());
    }

    #[test]
    fn round_trip_bool_true() {
        let vw = ValueWord::from_bool(true);
        let ts = vw.to_typed_scalar().unwrap();
        assert_eq!(ts.kind, ScalarKind::Bool);
        assert_eq!(ts.payload_lo, 1);
        let vw2 = ValueWord::from_typed_scalar(ts);
        assert_eq!(vw.raw_bits(), vw2.raw_bits());
    }

    #[test]
    fn round_trip_bool_false() {
        let vw = ValueWord::from_bool(false);
        let ts = vw.to_typed_scalar().unwrap();
        assert_eq!(ts.kind, ScalarKind::Bool);
        assert_eq!(ts.payload_lo, 0);
        let vw2 = ValueWord::from_typed_scalar(ts);
        assert_eq!(vw.raw_bits(), vw2.raw_bits());
    }

    #[test]
    fn round_trip_none() {
        let vw = ValueWord::none();
        let ts = vw.to_typed_scalar().unwrap();
        assert_eq!(ts.kind, ScalarKind::None);
        let vw2 = ValueWord::from_typed_scalar(ts);
        assert_eq!(vw.raw_bits(), vw2.raw_bits());
    }

    #[test]
    fn round_trip_unit() {
        let vw = ValueWord::unit();
        let ts = vw.to_typed_scalar().unwrap();
        assert_eq!(ts.kind, ScalarKind::Unit);
        let vw2 = ValueWord::from_typed_scalar(ts);
        assert_eq!(vw.raw_bits(), vw2.raw_bits());
    }

    #[test]
    fn heap_value_returns_none() {
        let vw = ValueWord::from_string(std::sync::Arc::new("hello".to_string()));
        assert!(vw.to_typed_scalar().is_none());
    }

    #[test]
    fn typed_scalar_convenience_constructors() {
        assert_eq!(TypedScalar::i64(42).kind, ScalarKind::I64);
        assert_eq!(TypedScalar::i64(42).payload_lo, 42);
        assert_eq!(TypedScalar::f64(1.5).kind, ScalarKind::F64);
        assert_eq!(TypedScalar::bool(true).payload_lo, 1);
        assert_eq!(TypedScalar::none().kind, ScalarKind::None);
        assert_eq!(TypedScalar::unit().kind, ScalarKind::Unit);
    }

    #[test]
    fn scalar_kind_classification() {
        assert!(ScalarKind::I64.is_integer());
        assert!(ScalarKind::U32.is_integer());
        assert!(!ScalarKind::F64.is_integer());
        assert!(!ScalarKind::Bool.is_integer());

        assert!(ScalarKind::F64.is_float());
        assert!(ScalarKind::F32.is_float());
        assert!(!ScalarKind::I64.is_float());

        assert!(ScalarKind::I64.is_numeric());
        assert!(ScalarKind::F64.is_numeric());
        assert!(!ScalarKind::Bool.is_numeric());
        assert!(!ScalarKind::None.is_numeric());
    }

    #[test]
    fn value_slot_from_typed_scalar() {
        // Integer
        let (slot, is_heap) = ValueSlot::from_typed_scalar(TypedScalar::i64(-42));
        assert!(!is_heap);
        assert_eq!(slot.as_i64(), -42);

        // Float
        let (slot, is_heap) = ValueSlot::from_typed_scalar(TypedScalar::f64(3.14));
        assert!(!is_heap);
        assert_eq!(slot.as_f64(), 3.14);

        // Bool
        let (slot, is_heap) = ValueSlot::from_typed_scalar(TypedScalar::bool(true));
        assert!(!is_heap);
        assert!(slot.as_bool());

        // None
        let (slot, is_heap) = ValueSlot::from_typed_scalar(TypedScalar::none());
        assert!(!is_heap);
        assert_eq!(slot.raw(), 0);
    }

    #[test]
    fn to_f64_lossy_works() {
        assert_eq!(TypedScalar::f64(3.14).to_f64_lossy(), Some(3.14));
        assert_eq!(TypedScalar::i64(42).to_f64_lossy(), Some(42.0));
        assert_eq!(TypedScalar::bool(true).to_f64_lossy(), Option::None);
        assert_eq!(TypedScalar::none().to_f64_lossy(), Option::None);
    }

    #[test]
    fn typed_scalar_extraction_methods() {
        assert_eq!(TypedScalar::i64(42).as_i64(), Some(42));
        assert_eq!(TypedScalar::f64(3.14).as_i64(), Option::None);
        assert_eq!(TypedScalar::f64(3.14).as_f64(), Some(3.14));
        assert_eq!(TypedScalar::i64(42).as_f64(), Option::None);
        assert_eq!(TypedScalar::bool(true).as_bool(), Some(true));
        assert_eq!(TypedScalar::i64(1).as_bool(), Option::None);
    }
}