shape-jit 0.3.2

Tiered JIT compiler (Cranelift) for the Shape virtual machine
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
// ============================================================================
// Intrinsic Aggregation Functions (operate on column references)
// ============================================================================

use crate::context::JITContext;
// crate::jit_array::JitArray removed — see jit_array.rs SURFACE comment.
// `jit_time_range` returned a `JitArray` of HK_TIME elements; it
// surfaces per ADR-006 §2.7.4 / W10 jit-playbook §5.
use crate::ffi::jit_kinds::*;
use crate::ffi::value_ffi::*;

/// Intrinsic sum: compute sum of all values in a column.
pub extern "C" fn jit_intrinsic_sum(series_bits: u64) -> u64 {
    unsafe {
        if let Some(data) = extract_column(series_bits) {
            box_number(shape_runtime::columnar_aggregations::sum_f64_slice(data))
        } else {
            box_number(f64::NAN)
        }
    }
}

/// Intrinsic mean: compute mean of all values in a column.
pub extern "C" fn jit_intrinsic_mean(series_bits: u64) -> u64 {
    unsafe {
        if let Some(data) = extract_column(series_bits) {
            box_number(shape_runtime::columnar_aggregations::mean_f64_slice(data))
        } else {
            box_number(f64::NAN)
        }
    }
}

/// Intrinsic min: compute minimum of all values in a column.
pub extern "C" fn jit_intrinsic_min(series_bits: u64) -> u64 {
    unsafe {
        if let Some(data) = extract_column(series_bits) {
            box_number(shape_runtime::columnar_aggregations::min_f64_slice(data))
        } else {
            box_number(f64::NAN)
        }
    }
}

/// Intrinsic max: compute maximum of all values in a column.
pub extern "C" fn jit_intrinsic_max(series_bits: u64) -> u64 {
    unsafe {
        if let Some(data) = extract_column(series_bits) {
            box_number(shape_runtime::columnar_aggregations::max_f64_slice(data))
        } else {
            box_number(f64::NAN)
        }
    }
}

/// Intrinsic variance: compute variance of all values in a column.
pub extern "C" fn jit_intrinsic_variance(series_bits: u64) -> u64 {
    unsafe {
        if let Some(data) = extract_column(series_bits) {
            let mean = shape_runtime::columnar_aggregations::mean_f64_slice(data);
            let n = data.len() as f64;
            if n < 2.0 {
                return box_number(f64::NAN);
            }
            let sum_sq: f64 = data.iter().map(|&x| (x - mean) * (x - mean)).sum();
            box_number(sum_sq / (n - 1.0))
        } else {
            box_number(f64::NAN)
        }
    }
}

/// Intrinsic std: compute standard deviation of all values in a column.
pub extern "C" fn jit_intrinsic_std(series_bits: u64) -> u64 {
    let var_bits = jit_intrinsic_variance(series_bits);
    if is_number(var_bits) {
        let var = unbox_number(var_bits);
        box_number(var.sqrt())
    } else {
        box_number(f64::NAN)
    }
}

/// Intrinsic median: compute median of all values in a column.
pub extern "C" fn jit_intrinsic_median(series_bits: u64) -> u64 {
    unsafe {
        if let Some(data) = extract_column(series_bits) {
            let mut sorted: Vec<f64> = data.to_vec();
            sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
            let n = sorted.len();
            if n == 0 {
                return box_number(f64::NAN);
            }
            let median = if n % 2 == 0 {
                (sorted[n / 2 - 1] + sorted[n / 2]) / 2.0
            } else {
                sorted[n / 2]
            };
            box_number(median)
        } else {
            box_number(f64::NAN)
        }
    }
}

/// Intrinsic percentile: compute percentile of column values.
pub extern "C" fn jit_intrinsic_percentile(series_bits: u64, percentile_bits: u64) -> u64 {
    unsafe {
        if let Some(data) = extract_column(series_bits) {
            let pct = if is_number(percentile_bits) {
                unbox_number(percentile_bits)
            } else {
                return box_number(f64::NAN);
            };

            let mut sorted: Vec<f64> = data.to_vec();
            sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
            let n = sorted.len();
            if n == 0 {
                return box_number(f64::NAN);
            }
            let idx = (pct / 100.0 * (n - 1) as f64).round() as usize;
            let idx = idx.min(n - 1);
            box_number(sorted[idx])
        } else {
            box_number(f64::NAN)
        }
    }
}

/// Intrinsic correlation: compute Pearson correlation between two columns.
pub extern "C" fn jit_intrinsic_correlation(a_bits: u64, b_bits: u64) -> u64 {
    unsafe {
        if let (Some(a), Some(b)) = (extract_column(a_bits), extract_column(b_bits)) {
            if a.len() != b.len() || a.is_empty() {
                return box_number(f64::NAN);
            }
            box_number(shape_runtime::simd_statistics::correlation(a, b))
        } else {
            box_number(f64::NAN)
        }
    }
}

/// Intrinsic covariance: compute sample covariance between two columns.
pub extern "C" fn jit_intrinsic_covariance(a_bits: u64, b_bits: u64) -> u64 {
    unsafe {
        if let (Some(a), Some(b)) = (extract_column(a_bits), extract_column(b_bits)) {
            if a.len() != b.len() || a.is_empty() {
                return box_number(f64::NAN);
            }
            box_number(shape_runtime::simd_statistics::covariance(a, b))
        } else {
            box_number(f64::NAN)
        }
    }
}

// ============================================================================
// Rolling/Transform Intrinsics (return column references)
// ============================================================================

/// Rolling min of a column.
pub extern "C" fn jit_series_rolling_min(series_bits: u64, window_bits: u64) -> u64 {
    unsafe {
        if let Some(data) = extract_column(series_bits) {
            let window = if is_number(window_bits) {
                unbox_number(window_bits) as usize
            } else {
                return TAG_NULL;
            };
            let result = shape_runtime::simd_rolling::rolling_min_deque(data, window);
            box_column_result(result)
        } else {
            TAG_NULL
        }
    }
}

/// Rolling max of a column.
pub extern "C" fn jit_series_rolling_max(series_bits: u64, window_bits: u64) -> u64 {
    unsafe {
        if let Some(data) = extract_column(series_bits) {
            let window = if is_number(window_bits) {
                unbox_number(window_bits) as usize
            } else {
                return TAG_NULL;
            };
            let result = shape_runtime::simd_rolling::rolling_max_deque(data, window);
            box_column_result(result)
        } else {
            TAG_NULL
        }
    }
}

/// EMA (exponential moving average) of a column.
pub extern "C" fn jit_series_ema(series_bits: u64, period_bits: u64) -> u64 {
    unsafe {
        if let Some(data) = extract_column(series_bits) {
            let period = if is_number(period_bits) {
                unbox_number(period_bits) as usize
            } else {
                return TAG_NULL;
            };
            if period == 0 || data.is_empty() {
                return TAG_NULL;
            }
            let alpha = 2.0 / (period as f64 + 1.0);
            let mut result = Vec::with_capacity(data.len());
            result.push(data[0]);
            for i in 1..data.len() {
                let ema = alpha * data[i] + (1.0 - alpha) * result[i - 1];
                result.push(ema);
            }
            box_column_result(result)
        } else {
            TAG_NULL
        }
    }
}

/// Diff (first difference) of a column.
pub extern "C" fn jit_series_diff(series_bits: u64, _periods_bits: u64) -> u64 {
    unsafe {
        if let Some(data) = extract_column(series_bits) {
            let result = shape_runtime::simd_rolling::diff(data);
            box_column_result(result)
        } else {
            TAG_NULL
        }
    }
}

/// Percent change of a column.
pub extern "C" fn jit_series_pct_change(series_bits: u64, _periods_bits: u64) -> u64 {
    unsafe {
        if let Some(data) = extract_column(series_bits) {
            let result = shape_runtime::simd_rolling::pct_change(data);
            box_column_result(result)
        } else {
            TAG_NULL
        }
    }
}

/// Cumulative product of a column.
pub extern "C" fn jit_series_cumprod(series_bits: u64) -> u64 {
    unsafe {
        if let Some(data) = extract_column(series_bits) {
            let mut result = Vec::with_capacity(data.len());
            let mut acc = 1.0;
            for &v in data {
                acc *= v;
                result.push(acc);
            }
            box_column_result(result)
        } else {
            TAG_NULL
        }
    }
}

/// Clip values in a column to [min, max] range.
pub extern "C" fn jit_series_clip(series_bits: u64, min_bits: u64, max_bits: u64) -> u64 {
    unsafe {
        if let Some(data) = extract_column(series_bits) {
            let min_val = if is_number(min_bits) {
                unbox_number(min_bits)
            } else {
                return TAG_NULL;
            };
            let max_val = if is_number(max_bits) {
                unbox_number(max_bits)
            } else {
                return TAG_NULL;
            };
            let mut result = data.to_vec();
            shape_runtime::simd_rolling::clip(&mut result, min_val, max_val);
            box_column_result(result)
        } else {
            TAG_NULL
        }
    }
}

/// Broadcast a scalar value to a column of given length.
pub extern "C" fn jit_series_broadcast(value_bits: u64, len_bits: u64) -> u64 {
    let value = if is_number(value_bits) {
        unbox_number(value_bits)
    } else {
        return TAG_NULL;
    };
    let len = if is_number(len_bits) {
        unbox_number(len_bits) as usize
    } else {
        return TAG_NULL;
    };
    let result = vec![value; len];
    box_column_result(result)
}

/// Get index of highest value in a column.
pub extern "C" fn jit_series_highest_index(series_bits: u64) -> u64 {
    unsafe {
        if let Some(data) = extract_column(series_bits) {
            if data.is_empty() {
                return TAG_NULL;
            }
            let mut max_idx = 0;
            let mut max_val = f64::NEG_INFINITY;
            for (i, &v) in data.iter().enumerate() {
                if v > max_val {
                    max_val = v;
                    max_idx = i;
                }
            }
            box_number(max_idx as f64)
        } else {
            TAG_NULL
        }
    }
}

/// Get index of lowest value in a column.
pub extern "C" fn jit_series_lowest_index(series_bits: u64) -> u64 {
    unsafe {
        if let Some(data) = extract_column(series_bits) {
            if data.is_empty() {
                return TAG_NULL;
            }
            let mut min_idx = 0;
            let mut min_val = f64::INFINITY;
            for (i, &v) in data.iter().enumerate() {
                if v < min_val {
                    min_val = v;
                    min_idx = i;
                }
            }
            box_number(min_idx as f64)
        } else {
            TAG_NULL
        }
    }
}

/// Get current time from execution context
pub extern "C" fn jit_time_current_time(ctx: *mut JITContext) -> u64 {
    unsafe {
        if ctx.is_null() {
            return TAG_NULL;
        }
        let ctx_ref = &*ctx;

        // Priority 1: Use timestamp from timestamps_ptr at current_row if available
        // Note: timestamps are stored in MICROSECONDS, convert to SECONDS for TAG_TIME
        if !ctx_ref.timestamps_ptr.is_null() && ctx_ref.current_row < ctx_ref.row_count {
            let ts_micros = *ctx_ref.timestamps_ptr.add(ctx_ref.current_row);
            if ts_micros != 0 {
                let ts_seconds = ts_micros / 1_000_000;
                return unified_box(HK_TIME, ts_seconds);
            }
        }

        // Priority 2: Fall back to ExecutionContext reference datetime
        if !ctx_ref.exec_context_ptr.is_null() {
            use shape_runtime::context::ExecutionContext;
            let exec_ctx = &*(ctx_ref.exec_context_ptr as *const ExecutionContext);
            if let Some(ref_dt) = exec_ctx.get_reference_datetime() {
                let ts = ref_dt.timestamp();
                return unified_box(HK_TIME, ts);
            }
        }

        TAG_NULL
    }
}

/// Get current symbol from execution context
pub extern "C" fn jit_time_symbol(ctx: *mut JITContext) -> u64 {
    unsafe {
        if ctx.is_null() {
            return TAG_NULL;
        }
        let ctx_ref = &*ctx;

        // Try to get symbol from exec_context using the public method
        if !ctx_ref.exec_context_ptr.is_null() {
            use shape_runtime::context::ExecutionContext;
            let exec_ctx = &*(ctx_ref.exec_context_ptr as *const ExecutionContext);
            if let Ok(id) = exec_ctx.get_current_id() {
                return box_string(id);
            }
        }
        TAG_NULL
    }
}

/// Get last data row from execution context (the actual last row in the dataset)
/// Returns a TAG_INT with the last row index
pub extern "C" fn jit_time_last_row(ctx: *mut JITContext) -> u64 {
    unsafe {
        if ctx.is_null() {
            return TAG_NULL;
        }
        let ctx_ref = &*ctx;

        // Use DataFrame row count from JITContext
        // Note: get_all_rows() requires &mut self which we can't get from a raw pointer safely
        if ctx_ref.row_count > 0 && !ctx_ref.column_ptrs.is_null() {
            let last_idx = ctx_ref.row_count - 1;
            // Return data row index for the last row
            return box_data_row(last_idx);
        }

        TAG_NULL
    }
}

/// Generate a range of Time values.
///
/// SURFACE (W10 jit-playbook §5 / ADR-006 §2.7.4): result allocation
/// went through the deleted `JitArray::from_vec(...).heap_box()`
/// wrapping HK_TIME elements. Kinded rebuild allocates a
/// `TypedArray<HeapValue>` (with element kind
/// `NativeKind::Ptr(HeapKind::Time)`) per ADR-006 §2.7.6/Q8.
pub extern "C" fn jit_time_range(_start_bits: u64, _end_bits: u64, _step_bits: u64) -> u64 {
    todo!(
        "phase-2c §2.7.4 / W10 jit-playbook §5: JitArray rebuild — \
         jit_time_range. Result allocation needs `TypedArray<...>` \
         of HeapKind::Time elements per ADR-006 §2.7.6/Q8."
    )
}