Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(hogvm): Node-parity Rust VM with async suspend/resume (#66631)

José Sequeira5f64906f6b1c
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 7b02fee9efb6..1ab0611b225b 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -4497,14 +4497,19 @@ dependencies = [
name = "hogvm"
version = "0.1.0"
dependencies = [
+ "base64 0.22.1",
"chrono",
"chrono-tz",
+ "hmac",
+ "indexmap 2.13.0",
+ "md-5",
"once_cell",
"quick_cache",
"rand 0.8.5",
"regex",
"serde",
"serde_json",
+ "sha2",
"thiserror 2.0.18",
]
diff --git a/rust/cohort-stream-processor/src/hogvm/executor.rs b/rust/cohort-stream-processor/src/hogvm/executor.rs
index de29e86ca118..3e4396de0427 100644
--- a/rust/cohort-stream-processor/src/hogvm/executor.rs
+++ b/rust/cohort-stream-processor/src/hogvm/executor.rs
@@ -19,12 +19,11 @@ use crate::observability::metrics::{STAGE1_HOGVM_ERROR, STAGE1_HOGVM_UNKNOWN_FUN
/// observable in prod logs without a line per event.
static SEEN_UNKNOWN_FNS: LazyLock<DashSet<String>> = LazyLock::new(DashSet::new);
-/// HogVM stack ceiling for cohort evaluation. `with_defaults` caps the stack at 128, far below real
-/// cohort bytecode: a `person.properties.X IN (...)` leaf compiles to a tuple build that pushes every
-/// list element before `In` pops them, so peak depth ≈ list size. Production catalogs already hold
-/// IN-lists of several thousand elements (largest observed ~8.6k), which overflow 128 and silently
-/// match nobody. A correctness floor, not a tuning knob — it must exceed real list sizes regardless
-/// of environment.
+/// HogVM stack ceiling for cohort evaluation. A `person.properties.X IN (...)` leaf compiles to a
+/// tuple build that pushes every list element before `In` pops them, so peak depth ≈ list size.
+/// Production catalogs already hold IN-lists of several thousand elements (largest observed ~8.6k).
+/// A correctness floor, not a tuning knob — it must exceed real list sizes regardless of environment
+/// (and independent of the VM's own default ceiling).
const COHORT_HOGVM_MAX_STACK_DEPTH: usize = 32_768;
/// Step ceiling. Cohort filter bytecode is loop-free, so step count ≈ program length and raising this
/// cannot cause a runaway; kept above the stack ceiling so a max-size tuple build can't trip it.
@@ -428,17 +427,17 @@ mod tests {
}
#[test]
- fn large_tuple_overflows_at_default_depth_but_evaluates_in_cohort_context() {
- // N comfortably above the 128 default, small enough to be instant.
+ fn large_tuple_overflows_at_shallow_depth_but_evaluates_in_cohort_context() {
+ // N comfortably above a 128-deep stack, small enough to be instant.
let prog = tuple_build_program(200);
- // Control: the production default depth (128) must StackOverflow on the tuple build, pinning
- // the exact failure the raised ceiling fixes.
+ // Control: an explicit 128-deep stack (the old `with_defaults` value, before the ceiling was
+ // raised) must StackOverflow on the tuple build, pinning the failure the cohort context avoids.
let program = Program::new(prog.clone()).expect("valid program");
- let control = ExecutionContext::with_defaults(program);
+ let control = ExecutionContext::with_defaults(program).with_max_stack_depth(128);
assert!(
matches!(sync_execute(&control, false), Err(failure) if matches!(failure.error, VmError::StackOverflow)),
- "expected StackOverflow at the default depth of 128",
+ "expected StackOverflow at a stack depth of 128",
);
// Fix, free-function site (parity path): no overflow. A tuple result coerces to false, so we
diff --git a/rust/common/hogvm/Cargo.toml b/rust/common/hogvm/Cargo.toml
index b808c6952e4e..0e04374fb141 100644
--- a/rust/common/hogvm/Cargo.toml
+++ b/rust/common/hogvm/Cargo.toml
@@ -14,5 +14,10 @@ regex.workspace = true
rand.workspace = true
chrono.workspace = true
chrono-tz.workspace = true
+indexmap = "2"
+md-5 = "0.10"
+sha2.workspace = true
+hmac.workspace = true
+base64.workspace = true
once_cell.workspace = true
quick_cache.workspace = true
diff --git a/rust/common/hogvm/README.md b/rust/common/hogvm/README.md
new file mode 100644
index 000000000000..1eb11f798dfc
--- /dev/null
+++ b/rust/common/hogvm/README.md
@@ -0,0 +1,36 @@
+# hogvm
+
+A Rust implementation of the Hog virtual machine, at behavioral parity with the Node reference VM
+(`@posthog/hogvm`, `common/hogvm/typescript`). Parity is enforced by `tests/parity.rs` (the full
+program corpus, diffed against committed Node output) and `tests/stl_parity.rs` (per-STL cases).
+
+## Execution modes
+
+- **`sync_execute`** — synchronous, boolean/value-returning evaluation. This is what the production
+ consumers use (`cymbal` error-tracking rule evaluation, `cohort-stream-processor`), and it is at
+ parity with the reference VM.
+- **`execute_resumable` / `resume`** — the suspendable-coroutine model for CDP hog functions
+ (destinations): on a registered async function (`fetch`, `sleep`, …) the VM suspends and returns a
+ serializable `VmSnapshot`; the host performs the side effect and resumes.
+
+## Node interop status (`VmSnapshot` / `VMState`)
+
+The snapshot JSON is designed to be byte-compatible with the reference VM's `VMState` so a snapshot
+can round-trip through either VM. **Rust↔Rust** round-trips are covered by `tests/async_resume.rs`.
+Exchanging state with the **live Node VM** has known encoding gaps — tracked in
+[#67272](https://github.com/PostHog/posthog/issues/67272), surfaced in review of
+[#66631](https://github.com/PostHog/posthog/pull/66631):
+
+1. **Tuples aren't flattened like Node.** Rust encodes tuples as `{"__hogTuple__": true, "items":
+ [...]}`; Node's `getVMState` flattens them to bare arrays. A live tuple in a snapshot therefore
+ doesn't survive a cross-VM round-trip.
+2. **JSON number int/float ambiguity.** Rust deserializes an integer-valued JSON number (`5`) as an
+ integer; Node always yields a float.
+3. **Cumulative timeout not preserved across resume.** `drive_resumable` restarts the step counter
+ each resume and hardcodes `sync_duration: 0`; Node bounds cumulative work by wall-clock across
+ resumes.
+4. **Header-inclusive ip for module chunks.** A snapshot taken while suspended inside an STL hog
+ module (e.g. an async call within an `arrayMap` callback) would resume at the wrong ip in Node.
+
+None of these affect the sync path — they only matter when exchanging `VMState` with the Node VM,
+which is the live-Node cross-check follow-up.
diff --git a/rust/common/hogvm/src/context.rs b/rust/common/hogvm/src/context.rs
index 4975f2185a77..1311cf8e4ece 100644
--- a/rust/common/hogvm/src/context.rs
+++ b/rust/common/hogvm/src/context.rs
@@ -1,6 +1,7 @@
+use indexmap::IndexMap;
use once_cell::sync::Lazy;
use serde_json::{json, Value as JsonValue};
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use crate::{
@@ -11,6 +12,10 @@ use crate::{
HogLiteral, HogValue,
};
+/// Function names that always suspend, mirroring the reference VM's `ASYNC_STL`. These are async
+/// regardless of host configuration; `with_async_functions` registers additional ones.
+const BUILTIN_ASYNC_FNS: &[&str] = &["sleep"];
+
/// Default native-function and symbol tables, built once from the process-static STL and shared via
/// `Arc` by every [`ExecutionContext::with_defaults`] so the maps aren't rebuilt per context.
static DEFAULT_NATIVE_FNS: Lazy<Arc<HashMap<String, NativeFunction>>> =
@@ -50,6 +55,17 @@ pub struct ExecutionContext {
// copy-on-write via `Arc::make_mut`.
native_fns: Arc<HashMap<String, NativeFunction>>,
symbol_table: Arc<HashMap<Symbol, ExportedFunction>>, // Flattened symbol table of all imported hog modules
+ // Names of global functions that suspend the VM instead of executing inline (the reference VM's
+ // `asyncFunctions` + `ASYNC_STL`). When the VM hits a `CALL_GLOBAL` for one of these and the
+ // async-step budget still allows it, execution suspends and the host performs the side effect
+ // (e.g. `fetch`) out-of-band, then resumes. See `HogVM::execute_resumable` / `resume`.
+ async_fns: HashSet<String>,
+ // How many async suspensions a single run may take before the VM errors instead of suspending
+ // (the reference VM's `maxAsyncSteps`). Default 0: no async allowed (matches the sync consumers).
+ pub(crate) max_async_steps: usize,
+ // When set, the VM records a per-opcode execution trace (the reference's `telemetry`), surfaced
+ // in the snapshot for the playground/debugger. Off by default (it has a per-step cost).
+ pub(crate) collect_telemetry: bool,
}
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
@@ -77,20 +93,30 @@ impl ExecutionContext {
coerce_comparisons: false,
native_fns: Arc::new(native_fns),
symbol_table: Arc::new(flatten_modules(&modules)),
+ async_fns: HashSet::new(),
+ max_async_steps: 0,
+ collect_telemetry: false,
}
}
pub fn with_defaults(bytecode: Program) -> Self {
- // TODO - these limits are basically randomly chosen
Self {
program: bytecode,
globals: json!({}),
- max_stack_depth: 128,
+ // Operand-stack ceiling. The reference (Node) VM imposes no operand-stack limit — it is
+ // bounded only by memory — so the old default of 128 spuriously overflowed valid programs
+ // that build large array/object literals. `max_steps` below already caps total pushes (a
+ // program can't push more values than it executes ops), so this is a generous safety
+ // ceiling rather than a functional bound (a prod hog-function survey hit 128 on real fns).
+ max_stack_depth: 1 << 20,
max_heap_size: 1024 * 1024,
max_steps: 10_000,
coerce_comparisons: false,
native_fns: DEFAULT_NATIVE_FNS.clone(),
symbol_table: DEFAULT_SYMBOL_TABLE.clone(),
+ async_fns: HashSet::new(),
+ max_async_steps: 0,
+ collect_telemetry: false,
}
}
@@ -132,6 +158,32 @@ impl ExecutionContext {
self
}
+ /// Register the global function names that suspend the VM (the reference `asyncFunctions`). Pair
+ /// with [`Self::with_max_async_steps`] to allow at least one suspension, otherwise the VM errors
+ /// the moment it calls one. Accumulates across calls, like [`Self::with_ext_fns`].
+ pub fn with_async_functions(mut self, names: HashSet<String>) -> Self {
+ self.async_fns.extend(names);
+ self
+ }
+
+ /// How many async suspensions a single run may take before erroring (reference `maxAsyncSteps`).
+ pub fn with_max_async_steps(mut self, max_async_steps: usize) -> Self {
+ self.max_async_steps = max_async_steps;
+ self
+ }
+
+ /// Opt into per-opcode telemetry (the reference's execution trace), surfaced in the snapshot.
+ pub fn with_telemetry(mut self) -> Self {
+ self.collect_telemetry = true;
+ self
+ }
+
+ pub fn is_async(&self, name: &str) -> bool {
+ // The reference's `ASYNC_STL` (currently just `sleep`) is always async, regardless of the
+ // host-registered `asyncFunctions`. Host registrations are additive on top.
+ BUILTIN_ASYNC_FNS.contains(&name) || self.async_fns.contains(name)
+ }
+
pub fn with_max_stack_depth(mut self, max_stack_depth: usize) -> Self {
self.max_stack_depth = max_stack_depth;
self
@@ -174,6 +226,12 @@ impl ExecutionContext {
.ok_or(VmError::UnknownSymbol(symbol.to_string()))
}
+ // Whether `name` is a registered native (STL/ext) function — used to resolve first-class
+ // references to native functions in GetGlobal.
+ pub fn has_native(&self, name: &str) -> bool {
+ self.native_fns.contains_key(name)
+ }
+
pub fn execute_native_function_call(
&self,
vm: &mut HogVM,
@@ -203,6 +261,17 @@ impl ExecutionContext {
pub fn version(&self) -> u64 {
self.program.version()
}
+
+ /// The root program's full bytecode (header included), for a snapshot's `bytecodes.root`.
+ pub fn program_tokens(&self) -> &[JsonValue] {
+ self.program.tokens()
+ }
+
+ /// Header-token count of the root program — the offset between our body-relative `ip` and the
+ /// reference VM's header-inclusive per-frame `ip` for the root chunk.
+ pub fn program_header_len(&self) -> usize {
+ self.program.header_len()
+ }
}
impl Symbol {
@@ -237,18 +306,29 @@ fn walk_emplacing(vm: &mut HogVM, value: HogValue) -> Result<HogValue, VmError>
}
};
+ // Arrays and tuples emplace identically; only the rebuilt variant differs (tuples must stay
+ // tuples so they keep their `(a, b)` printing and "tuple" typeof through the heap).
+ let is_tuple = matches!(literal, HogLiteral::Tuple(_));
+
match literal {
- HogLiteral::Array(arr) => {
+ HogLiteral::Array(arr) | HogLiteral::Tuple(arr) => {
+ let rebuild = |v: Vec<HogValue>| {
+ if is_tuple {
+ HogLiteral::Tuple(v)
+ } else {
+ HogLiteral::Array(v)
+ }
+ };
// Fast path: when every element is a plain (non-container, non-reference) literal there
// is nothing to emplace, so skip the per-element walk + re-collect entirely. Native STL
// results are overwhelmingly flat numeric/string arrays, and this walk was the single
// hottest function in the interpreter (~25% of instructions) before this guard.
let emplaced_arr = if arr.iter().all(is_flat_literal) {
- HogLiteral::Array(arr)
+ rebuild(arr)
} else {
let walked: Result<Vec<HogValue>, _> =
arr.into_iter().map(|i| walk_emplacing(vm, i)).collect();
- HogLiteral::Array(walked?)
+ rebuild(walked?)
};
if let Some(ptr) = existing_location {
@@ -261,7 +341,7 @@ fn walk_emplacing(vm: &mut HogVM, value: HogValue) -> Result<HogValue, VmError>
}
}
HogLiteral::Object(obj) => {
- let emplaced_obj: Result<HashMap<String, HogValue>, _> = obj
+ let emplaced_obj: Result<IndexMap<String, HogValue>, _> = obj
.into_iter()
.map(|(k, v)| Ok((k, walk_emplacing(vm, v)?)))
.collect();
diff --git a/rust/common/hogvm/src/lib.rs b/rust/common/hogvm/src/lib.rs
index db783fdea482..aabd83dec707 100644
--- a/rust/common/hogvm/src/lib.rs
+++ b/rust/common/hogvm/src/lib.rs
@@ -2,7 +2,9 @@ mod context;
mod error;
mod memory;
mod ops;
+mod print;
mod program;
+mod state;
mod stl;
mod util;
mod values;
@@ -22,6 +24,17 @@ pub use vm::HogVM;
pub use vm::StepOutcome;
pub use vm::VmFailure;
+// Suspend/resume (async-coroutine) execution and state serialization
+pub use state::Resumable;
+pub use state::VmSnapshot;
+pub use vm::execute_resumable;
+pub use vm::resume;
+
+// Canonical value printing (the `print(...)` oracle), used by the parity harness
+pub use print::escape_string;
+pub use print::print_hog_string_output;
+pub use print::print_hog_value;
+
// STL - again, we expose a lot, because we want to make it easy to extend this
pub use stl::hog_stl;
pub use stl::native_func;
diff --git a/rust/common/hogvm/src/memory.rs b/rust/common/hogvm/src/memory.rs
index 08cd454d44d0..bd1ffe84b7f6 100644
--- a/rust/common/hogvm/src/memory.rs
+++ b/rust/common/hogvm/src/memory.rs
@@ -19,7 +19,10 @@ pub struct VmHeap {
// improve this. Right now our heap is append-only
freed: Vec<HeapReference>, // Indices of freed heap values, for reuse
- pub(crate) current_bytes: usize, // Pub: the vm occasionally directly writes to this
+ pub(crate) current_bytes: usize, // Pub: the vm occasionally writes to this via set_current_bytes
+ // High-water mark of current_bytes — mirrors the reference VM's `maxMemUsed`. Bumped whenever
+ // usage rises and never decremented, so it reports the true peak even after values are replaced.
+ pub(crate) peak_bytes: usize,
max_bytes: usize,
}
@@ -31,10 +34,18 @@ impl VmHeap {
inner: Vec::new(),
freed: Vec::new(),
current_bytes: 0,
+ peak_bytes: 0,
max_bytes,
}
}
+ /// Set current usage and raise the high-water mark. Used by ops that replace a heap value in
+ /// place (which can lower `current_bytes`) so the peak still reflects the largest usage seen.
+ pub(crate) fn set_current_bytes(&mut self, bytes: usize) {
+ self.current_bytes = bytes;
+ self.peak_bytes = self.peak_bytes.max(bytes);
+ }
+
fn assert_can_allocate(&self, new_bytes: usize) -> Result<(), VmError> {
if self.current_bytes.saturating_add(new_bytes) > self.max_bytes {
Err(VmError::OutOfResource("Heap Memory".to_string()))
@@ -52,6 +63,7 @@ impl VmHeap {
};
self.current_bytes = self.current_bytes.saturating_add(value.size());
+ self.peak_bytes = self.peak_bytes.max(self.current_bytes);
if self.inner.len() <= next_idx {
self.inner.push(HeapValue {
diff --git a/rust/common/hogvm/src/print.rs b/rust/common/hogvm/src/print.rs
new file mode 100644
index 000000000000..f7ac56d634bf
--- /dev/null
+++ b/rust/common/hogvm/src/print.rs
@@ -0,0 +1,673 @@
+//! Canonical Hog value formatting, matching the reference VMs' `printHogValue` /
+//! `printHogStringOutput` (see `common/hogvm/typescript/src/stl/print.ts` and
+//! `common/hogvm/python/stl/print.py`). This is what `print(...)` emits and is the
+//! oracle the parity harness diffs against. Kept separate from `stl::to_string`
+//! (which is `toString` semantics) on purpose — the two are subtly different and the
+//! parity loop is what reconciles them.
+
+use indexmap::IndexMap;
+
+use crate::{
+ memory::{HeapReference, VmHeap},
+ values::{Callable, HogLiteral, HogValue},
+};
+
+const PRINT_RECURSION_LIMIT: usize = 64;
+
+/// Escape a string the way the reference VMs do: wrap in single quotes and escape the
+/// clickhouse-style control characters plus the quote and backslash.
+pub fn escape_string(value: &str) -> String {
+ let mut out = String::with_capacity(value.len() + 2);
+ out.push('\'');
+ for c in value.chars() {
+ match c {
+ '\u{08}' => out.push_str("\\b"),
+ '\u{0C}' => out.push_str("\\f"),
+ '\r' => out.push_str("\\r"),
+ '\n' => out.push_str("\\n"),
+ '\t' => out.push_str("\\t"),
+ '\0' => out.push_str("\\0"),
+ '\u{0B}' => out.push_str("\\v"),
+ '\\' => out.push_str("\\\\"),
+ '\'' => out.push_str("\\'"),
+ other => out.push(other),
+ }
+ }
+ out.push('\'');
+ out
+}
+
+/// Format a value as `print(...)` would. Top-level strings are emitted raw; everything
+/// else (including strings nested inside arrays/objects) goes through [`print_hog_value`].
+pub fn print_hog_string_output(heap: &VmHeap, value: &HogValue) -> Result<String, crate::VmError> {
+ match value.deref(heap)? {
+ HogLiteral::String(s) => Ok(s.clone()),
+ _ => print_hog_value(heap, value, &mut Vec::new(), 0),
+ }
+}
+
+/// The recursive canonical printer. `marked` tracks the heap references currently being
+/// printed so self-referential containers render as `null` (matching the reference VMs'
+/// `marked` set), rather than recursing forever.
+pub fn print_hog_value(
+ heap: &VmHeap,
+ value: &HogValue,
+ marked: &mut Vec<HeapReference>,
+ depth: usize,
+) -> Result<String, crate::VmError> {
+ if depth > PRINT_RECURSION_LIMIT {
+ return Ok("null".to_string());
+ }
+
+ let lit = value.deref(heap)?;
+ let container_ptr = match value {
+ HogValue::Ref(ptr) if matches!(lit, HogLiteral::Array(_) | HogLiteral::Object(_)) => {
+ Some(*ptr)
+ }
+ _ => None,
+ };
+
+ if let Some(ptr) = container_ptr {
+ if marked.contains(&ptr) {
+ return Ok("null".to_string());
+ }
+ marked.push(ptr);
+ }
+
+ let result = format_literal(heap, lit, marked, depth);
+
+ if container_ptr.is_some() {
+ marked.pop();
+ }
+
+ result
+}
+
+fn format_literal(
+ heap: &VmHeap,
+ lit: &HogLiteral,
+ marked: &mut Vec<HeapReference>,
+ depth: usize,
+) -> Result<String, crate::VmError> {
+ match lit {
+ HogLiteral::Null => Ok("null".to_string()),
+ HogLiteral::Boolean(b) => Ok(if *b { "true" } else { "false" }.to_string()),
+ HogLiteral::Number(n) => Ok(if n.is_float() {
+ n.to_float().to_string()
+ } else {
+ n.to_integer().to_string()
+ }),
+ HogLiteral::String(s) => Ok(escape_string(s)),
+ HogLiteral::Array(arr) => {
+ let mut parts = Vec::with_capacity(arr.len());
+ for elem in arr {
+ parts.push(print_hog_value(heap, elem, marked, depth + 1)?);
+ }
+ Ok(format!("[{}]", parts.join(", ")))
+ }
+ HogLiteral::Tuple(arr) => {
+ let mut parts = Vec::with_capacity(arr.len());
+ for elem in arr {
+ parts.push(print_hog_value(heap, elem, marked, depth + 1)?);
+ }
+ // The reference disambiguates 0/1-element tuples as `tuple(...)`; 2+ print as `(a, b)`.
+ if arr.len() < 2 {
+ Ok(format!("tuple({})", parts.join(", ")))
+ } else {
+ Ok(format!("({})", parts.join(", ")))
+ }
+ }
+ HogLiteral::Object(obj) => {
+ // Hog temporals are duck-typed objects; the reference prints them as DateTime(...)/Date(...).
+ if let Some(temporal) = format_temporal(heap, obj)? {
+ return Ok(temporal);
+ }
+ // Hog errors are duck-typed too; the reference prints them as `Type('message'[, payload])`.
+ if let Some(err) = format_error(heap, obj, marked, depth)? {
+ return Ok(err);
+ }
+ // HogQL AST nodes (`{__hx_ast: …}`) render back to SQL, wrapped as `sql(…)`.
+ if obj.contains_key("__hx_ast") {
+ return Ok(format!("sql({})", HogQLPrinter::new(heap).print_node(obj)?));
+ }
+ let mut parts = Vec::with_capacity(obj.len());
+ for (key, val) in obj {
+ parts.push(format!(
+ "{}: {}",
+ escape_string(key),
+ print_hog_value(heap, val, marked, depth + 1)?
+ ));
+ }
+ Ok(format!("{{{}}}", parts.join(", ")))
+ }
+ // The reference VMs print both callables and closures as `fn<name(argCount)>`.
+ HogLiteral::Callable(callable) => Ok(print_callable(callable)),
+ HogLiteral::Closure(closure) => Ok(print_callable(&closure.callable)),
+ }
+}
+
+fn print_callable(callable: &Callable) -> String {
+ match callable {
+ Callable::Local(local) => {
+ format!(
+ "fn<{}({})>",
+ escape_identifier(&local.name),
+ local.stack_arg_count
+ )
+ }
+ // Native arity isn't tracked here; the reference prints maxArgs, but no corpus program
+ // prints a bare native-function value, so the count is a placeholder.
+ Callable::Stl(name) => format!("fn<{}(0)>", escape_identifier(name)),
+ }
+}
+
+// Render the Hog temporal duck-types: `{__hogDateTime__: true, dt, zone}` -> `DateTime(dt, 'zone')`
+// and `{__hogDate__: true, year, month, day}` -> `Date(y, m, d)`. Returns None for plain objects.
+fn format_temporal(
+ heap: &VmHeap,
+ obj: &IndexMap<String, HogValue>,
+) -> Result<Option<String>, crate::VmError> {
+ if marker(heap, obj.get("__hogDateTime__"))? {
+ let dt = number(heap, obj.get("dt"))?.unwrap_or(0.0);
+ let zone = string(heap, obj.get("zone"))?.unwrap_or_else(|| "UTC".to_string());
+ return Ok(Some(format!(
+ "DateTime({}, {})",
+ format_dt_seconds(dt),
+ escape_string(&zone)
+ )));
+ }
+ if marker(heap, obj.get("__hogDate__"))? {
+ let y = number(heap, obj.get("year"))?.unwrap_or(0.0) as i64;
+ let m = number(heap, obj.get("month"))?.unwrap_or(0.0) as i64;
+ let d = number(heap, obj.get("day"))?.unwrap_or(0.0) as i64;
+ return Ok(Some(format!("Date({y}, {m}, {d})")));
+ }
+ Ok(None)
+}
+
+// Render the Hog error duck-type `{__hogError__: true, type, message, payload?}` as
+// `Type('message')` or `Type('message', payload)`. Returns None for plain objects.
+fn format_error(
+ heap: &VmHeap,
+ obj: &IndexMap<String, HogValue>,
+ marked: &mut Vec<HeapReference>,
+ depth: usize,
+) -> Result<Option<String>, crate::VmError> {
+ if !marker(heap, obj.get("__hogError__"))? {
+ return Ok(None);
+ }
+ let type_str = string(heap, obj.get("type"))?.unwrap_or_else(|| "Error".to_string());
+ let message = string(heap, obj.get("message"))?.unwrap_or_default();
+ let payload = match obj.get("payload") {
+ Some(p) if !matches!(p.deref(heap)?, HogLiteral::Null) => {
+ format!(", {}", print_hog_value(heap, p, marked, depth + 1)?)
+ }
+ _ => String::new(),
+ };
+ Ok(Some(format!(
+ "{type_str}({}{payload})",
+ escape_string(&message)
+ )))
+}
+
+fn marker(heap: &VmHeap, v: Option<&HogValue>) -> Result<bool, crate::VmError> {
+ match v {
+ Some(v) => Ok(matches!(v.deref(heap)?, HogLiteral::Boolean(true))),
+ None => Ok(false),
+ }
+}
+
+fn number(heap: &VmHeap, v: Option<&HogValue>) -> Result<Option<f64>, crate::VmError> {
+ match v {
+ Some(v) => Ok(match v.deref(heap)? {
+ HogLiteral::Number(n) => Some(n.to_float()),
+ _ => None,
+ }),
+ None => Ok(None),
+ }
+}
+
+fn string(heap: &VmHeap, v: Option<&HogValue>) -> Result<Option<String>, crate::VmError> {
+ match v {
+ Some(v) => Ok(match v.deref(heap)? {
+ HogLiteral::String(s) => Some(s.clone()),
+ _ => None,
+ }),
+ None => Ok(None),
+ }
+}
+
+// DateTime seconds print with a trailing `.0` when integral (matching Python's `float(dt)` str and
+// the reference DateTime() format), e.g. 1609504496 -> "1609504496.0", 1609504496.5 unchanged.
+fn format_dt_seconds(f: f64) -> String {
+ let s = format!("{f}");
+ if s.contains(['.', 'e', 'E']) || !f.is_finite() {
+ s
+ } else {
+ format!("{s}.0")
+ }
+}
+
+/// Identifiers print raw when they look like identifiers, else backtick-escaped — matching
+/// the reference `escapeIdentifier`.
+fn escape_identifier(identifier: &str) -> String {
+ let is_ident = {
+ let mut chars = identifier.chars();
+ matches!(chars.next(), Some(c) if c.is_ascii_alphabetic() || c == '_' || c == '$')
+ && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
+ };
+ if is_ident && !identifier.is_empty() {
+ identifier.to_string()
+ } else {
+ let mut out = String::with_capacity(identifier.len() + 2);
+ out.push('`');
+ for c in identifier.chars() {
+ match c {
+ '\u{08}' => out.push_str("\\b"),
+ '\u{0C}' => out.push_str("\\f"),
+ '\r' => out.push_str("\\r"),
+ '\n' => out.push_str("\\n"),
+ '\t' => out.push_str("\\t"),
+ '\0' => out.push_str("\\0"),
+ '\u{0B}' => out.push_str("\\v"),
+ '\\' => out.push_str("\\\\"),
+ '`' => out.push_str("\\`"),
+ other => out.push(other),
+ }
+ }
+ out.push('`');
+ out
+ }
+}
+
+// ── HogQL AST → SQL printer ──────────────────────────────────────────────────────────────────
+// Port of the reference `HogQLPrinter` (common/hogvm/typescript/src/stl/print.ts). HogQL queries
+// built via `sql(...)` are duck-typed AST objects (`{__hx_ast: <type>, …}`); this renders them back
+// to SQL. Only the non-pretty path is implemented (the VM never pretty-prints). The outer `sql(…)`
+// wrapper is added by the caller (`format_literal`), matching `printHogValue`.
+struct HogQLPrinter<'a> {
+ heap: &'a VmHeap,
+ // Mirrors the reference's `stack.length`: a query that isn't the outermost node is parenthesised.
+ depth: usize,
+}
+
+impl<'a> HogQLPrinter<'a> {
+ fn new(heap: &'a VmHeap) -> Self {
+ HogQLPrinter { heap, depth: 0 }
+ }
+
+ // Entry point: an already-dereferenced AST object.
+ fn print_node(&mut self, obj: &IndexMap<String, HogValue>) -> Result<String, crate::VmError> {
+ self.depth += 1;
+ let result = self.dispatch(obj);
+ self.depth -= 1;
+ result
+ }
+
+ // Visit any child: a nested AST object dispatches; a null renders empty; anything else goes
+ // through the canonical value printer (the reference's `escapeValue`).
+ fn visit(&mut self, node: &HogValue) -> Result<String, crate::VmError> {
+ match node.deref(self.heap)? {
+ HogLiteral::Null => Ok(String::new()),
+ HogLiteral::Object(obj) if obj.contains_key("__hx_ast") => self.print_node(obj),
+ _ => print_hog_value(self.heap, node, &mut Vec::new(), 0),
+ }
+ }
+
+ fn dispatch(&mut self, obj: &IndexMap<String, HogValue>) -> Result<String, crate::VmError> {
+ let node_type = self.str_field(obj, "__hx_ast")?.ok_or_else(|| {
+ crate::VmError::NativeCallFailed("HogQL node missing __hx_ast".to_string())
+ })?;
+ match node_type.as_str() {
+ "SelectQuery" => self.select_query(obj),
+ "SelectSetQuery" => self.select_set_query(obj),
+ "JoinExpr" => self.join_expr(obj),
+ "JoinConstraint" => self.visit_child(obj, "expr"),
+ "Call" => self.call(obj),
+ "Constant" => self.visit_child(obj, "value"),
+ "Field" => self.field(obj),
+ "Alias" => self.alias(obj),
+ "And" => self.logical(obj, "and"),
+ "Or" => self.logical(obj, "or"),
+ "Not" => Ok(format!("not({})", self.visit_child(obj, "expr")?)),
+ "CompareOperation" => self.compare(obj),
+ "Tuple" => Ok(format!("tuple({})", self.exprs(obj)?.join(", "))),
+ "Array" => Ok(format!("[{}]", self.exprs(obj)?.join(", "))),
+ "ArithmeticOperation" => self.arithmetic(obj),
+ "OrderExpr" => Ok(format!(
+ "{} {}",
+ self.visit_child(obj, "expr")?,
+ self.str_field(obj, "order")?.unwrap_or_default()
+ )),
+ "Lambda" => self.lambda(obj),
+ "Asterisk" => Ok("*".to_string()),
+ other => Err(crate::VmError::NativeCallFailed(format!(
+ "Unknown HogQL AST node type: {other}"
+ ))),
+ }
+ }
+
+ fn select_query(&mut self, obj: &IndexMap<String, HogValue>) -> Result<String, crate::VmError> {
+ let is_top_level = self.depth <= 1;
+ let distinct = if self.bool_field(obj, "distinct")? {
+ " DISTINCT"
+ } else {
+ ""
+ };
+ let select = self.exprs_field(obj, "select")?;
+ let mut clauses = vec![format!("SELECT{distinct} {}", select.join(", "))];
+
+ if let Some(from) = obj.get("select_from") {
+ let rendered = self.visit_join_expression(from)?;
+ if !rendered.is_empty() {
+ clauses.push(format!("FROM {rendered}"));
+ }
+ }
+ for (key, kw) in [
+ ("prewhere", "PREWHERE"),
+ ("where", "WHERE"),
+ ("having", "HAVING"),
+ ] {
+ if obj.contains_key(key) {
+ let rendered = self.visit_child(obj, key)?;
+ if !rendered.is_empty() {
+ clauses.push(format!("{kw} {rendered}"));
+ }
+ }
+ }
+ for (key, kw) in [("group_by", "GROUP BY"), ("order_by", "ORDER BY")] {
+ let parts = self.exprs_field(obj, key)?;
+ if !parts.is_empty() {
+ clauses.push(format!("{kw} {}", parts.join(", ")));
+ }
+ }
+ if obj.contains_key("limit") {
+ let limit = self.visit_child(obj, "limit")?;
+ if !limit.is_empty() {
+ clauses.push(format!("LIMIT {limit}"));
+ if self.bool_field(obj, "limit_with_ties")? {
+ clauses.push("WITH TIES".to_string());
+ }
+ if obj.contains_key("offset") {
+ let offset = self.visit_child(obj, "offset")?;
+ if !offset.is_empty() {
+ clauses.push(format!("OFFSET {offset}"));
+ }
+ }
+ }
+ }
+
+ let response = clauses.join(" ");
+ Ok(if is_top_level {
+ response
+ } else {
+ format!("({response})")
+ })
+ }
+
+ fn select_set_query(
+ &mut self,
+ obj: &IndexMap<String, HogValue>,
+ ) -> Result<String, crate::VmError> {
+ // The reference decrements/increments the indent around the set query; with pretty=false that
+ // only affects the parenthesisation check, which we approximate via depth.
+ let mut result = self.visit_child(obj, "initial_select_query")?;
+ for entry in self.array_field(obj, "subsequent_select_queries")? {
+ let HogLiteral::Object(eo) = entry.deref(self.heap)? else {
+ continue;
+ };
+ let op = self.str_field(eo, "set_operator")?.unwrap_or_default();
+ let query = match eo.get("select_query") {
+ Some(q) => self.visit(q)?,
+ None => String::new(),
+ };
+ if !op.is_empty() {
+ result.push_str(&format!(" {op} "));
+ }
+ result.push_str(&query);
+ }
+ Ok(if self.depth > 1 {
+ format!("({})", result.trim())
+ } else {
+ result
+ })
+ }
+
+ fn visit_join_expression(&mut self, node: &HogValue) -> Result<String, crate::VmError> {
+ if let HogLiteral::Object(obj) = node.deref(self.heap)? {
+ if self.str_field(obj, "__hx_ast")?.as_deref() == Some("JoinExpr") {
+ return self.join_expr(obj);
+ }
+ }
+ self.visit(node)
+ }
+
+ fn join_expr(&mut self, obj: &IndexMap<String, HogValue>) -> Result<String, crate::VmError> {
+ let mut parts = Vec::new();
+ let table = self.visit_child(obj, "table")?;
+ match self.str_field(obj, "alias")? {
+ Some(alias) if alias != table => {
+ parts.push(format!("{table} AS {}", escape_identifier(&alias)));
+ }
+ _ => parts.push(table),
+ }
+
+ let mut current = obj.get("next_join").cloned();
+ while let Some(join) = current {
+ let HogLiteral::Object(jo) = join.deref(self.heap)? else {
+ break;
+ };
+ let jo = jo.clone();
+ let join_type = self
+ .str_field(&jo, "join_type")?
+ .unwrap_or_else(|| "JOIN".to_string());
+ let table = self.visit_child(&jo, "table")?;
+ let constraint = match jo.get("constraint") {
+ Some(c) => {
+ if let HogLiteral::Object(co) = c.deref(self.heap)? {
+ let ctype = self.str_field(co, "constraint_type")?.unwrap_or_default();
+ format!("{ctype} {}", self.visit(c)?)
+ } else {
+ String::new()
+ }
+ }
+ None => String::new(),
+ };
+ let table_with_alias = match self.str_field(&jo, "alias")? {
+ Some(alias) if alias != table => {
+ format!("{table} AS {}", escape_identifier(&alias))
+ }
+ _ => table,
+ };
+ parts.push(
+ format!("{join_type} {table_with_alias} {constraint}")
+ .trim()
+ .to_string(),
+ );
+ current = jo.get("next_join").cloned();
+ }
+ Ok(parts.join(" "))
+ }
+
+ fn call(&mut self, obj: &IndexMap<String, HogValue>) -> Result<String, crate::VmError> {
+ let name = self.str_field(obj, "name")?.unwrap_or_default();
+ Ok(format!(
+ "{name}({})",
+ self.exprs_field(obj, "args")?.join(", ")
+ ))
+ }
+
+ fn field(&mut self, obj: &IndexMap<String, HogValue>) -> Result<String, crate::VmError> {
+ let chain = self.array_field(obj, "chain")?;
+ if chain.len() == 1 {
+ if let HogLiteral::String(s) = chain[0].deref(self.heap)? {
+ if s == "*" {
+ return Ok("*".to_string());
+ }
+ }
+ }
+ let mut parts = Vec::with_capacity(chain.len());
+ for elem in &chain {
+ parts.push(self.escape_identifier_or_index(elem)?);
+ }
+ Ok(parts.join("."))
+ }
+
+ fn alias(&mut self, obj: &IndexMap<String, HogValue>) -> Result<String, crate::VmError> {
+ if self.bool_field(obj, "hidden")? {
+ return self.visit_child(obj, "expr");
+ }
+ let inside = self.visit_child(obj, "expr")?;
+ let alias = self.str_field(obj, "alias")?.unwrap_or_default();
+ Ok(format!("{inside} AS {}", escape_identifier(&alias)))
+ }
+
+ fn logical(
+ &mut self,
+ obj: &IndexMap<String, HogValue>,
+ func: &str,
+ ) -> Result<String, crate::VmError> {
+ let exprs = self.exprs_field(obj, "exprs")?;
+ match exprs.len() {
+ 0 => Ok(String::new()),
+ 1 => Ok(exprs.into_iter().next().unwrap()),
+ _ => Ok(format!("{func}({})", exprs.join(", "))),
+ }
+ }
+
+ fn compare(&mut self, obj: &IndexMap<String, HogValue>) -> Result<String, crate::VmError> {
+ let left = self.visit_child(obj, "left")?;
+ let right = self.visit_child(obj, "right")?;
+ let op = self.str_field(obj, "op")?.unwrap_or_default();
+ let func = match op.as_str() {
+ "==" => "equals",
+ "!=" => "notEquals",
+ "<" => "less",
+ ">" => "greater",
+ "<=" => "lessOrEquals",
+ ">=" => "greaterOrEquals",
+ "in" => "in",
+ "not in" => "notIn",
+ "like" => "like",
+ "not like" => "notLike",
+ "ilike" => "ilike",
+ "not ilike" => "notILike",
+ "=~" | "!~" | "=~*" | "!~*" => "match",
+ other => other,
+ };
+ Ok(match op.as_str() {
+ "!~*" => format!("not({func}({left}, concat('(?i)', {right})))"),
+ "=~*" => format!("{func}({left}, concat('(?i)', {right}))"),
+ "!~" => format!("not({func}({left}, {right}))"),
+ _ => format!("{func}({left}, {right})"),
+ })
+ }
+
+ fn arithmetic(&mut self, obj: &IndexMap<String, HogValue>) -> Result<String, crate::VmError> {
+ let left = self.visit_child(obj, "left")?;
+ let right = self.visit_child(obj, "right")?;
+ let func = match self.str_field(obj, "op")?.as_deref() {
+ Some("+") => "plus",
+ Some("-") => "minus",
+ Some("*") => "multiply",
+ Some("/") => "divide",
+ Some("%") => "modulo",
+ other => {
+ return Err(crate::VmError::NativeCallFailed(format!(
+ "Unknown ArithmeticOperation operator: {other:?}"
+ )))
+ }
+ };
+ Ok(format!("{func}({left}, {right})"))
+ }
+
+ fn lambda(&mut self, obj: &IndexMap<String, HogValue>) -> Result<String, crate::VmError> {
+ let args = self.array_field(obj, "args")?;
+ let escaped: Vec<String> = args
+ .iter()
+ .filter_map(|a| match a.deref(self.heap) {
+ Ok(HogLiteral::String(s)) => Some(escape_identifier(s)),
+ _ => None,
+ })
+ .collect();
+ let arg_list = if escaped.len() == 1 {
+ escaped[0].clone()
+ } else {
+ format!("({})", escaped.join(", "))
+ };
+ Ok(format!("{arg_list} -> {}", self.visit_child(obj, "expr")?))
+ }
+
+ // ── helpers ──
+ fn exprs(&mut self, obj: &IndexMap<String, HogValue>) -> Result<Vec<String>, crate::VmError> {
+ self.exprs_field(obj, "exprs")
+ }
+
+ fn exprs_field(
+ &mut self,
+ obj: &IndexMap<String, HogValue>,
+ key: &str,
+ ) -> Result<Vec<String>, crate::VmError> {
+ let items = self.array_field(obj, key)?;
+ let mut out = Vec::with_capacity(items.len());
+ for item in &items {
+ out.push(self.visit(item)?);
+ }
+ Ok(out)
+ }
+
+ fn visit_child(
+ &mut self,
+ obj: &IndexMap<String, HogValue>,
+ key: &str,
+ ) -> Result<String, crate::VmError> {
+ match obj.get(key) {
+ Some(v) => self.visit(v),
+ None => Ok(String::new()),
+ }
+ }
+
+ fn array_field(
+ &self,
+ obj: &IndexMap<String, HogValue>,
+ key: &str,
+ ) -> Result<Vec<HogValue>, crate::VmError> {
+ match obj.get(key) {
+ Some(v) => Ok(match v.deref(self.heap)? {
+ HogLiteral::Array(a) | HogLiteral::Tuple(a) => a.clone(),
+ _ => Vec::new(),
+ }),
+ None => Ok(Vec::new()),
+ }
+ }
+
+ fn str_field(
+ &self,
+ obj: &IndexMap<String, HogValue>,
+ key: &str,
+ ) -> Result<Option<String>, crate::VmError> {
+ string(self.heap, obj.get(key))
+ }
+
+ fn bool_field(
+ &self,
+ obj: &IndexMap<String, HogValue>,
+ key: &str,
+ ) -> Result<bool, crate::VmError> {
+ marker(self.heap, obj.get(key))
+ }
+
+ // `escapeIdentifierOrIndex`: a non-negative integer stays bare; everything else is an identifier.
+ fn escape_identifier_or_index(&self, value: &HogValue) -> Result<String, crate::VmError> {
+ Ok(match value.deref(self.heap)? {
+ HogLiteral::Number(n) if !n.is_float() => n.to_integer().to_string(),
+ HogLiteral::String(s) => escape_identifier(s),
+ other => escape_identifier(&print_hog_value(
+ self.heap,
+ &HogLiteral::clone(other).into(),
+ &mut Vec::new(),
+ 0,
+ )?),
+ })
+ }
+}
diff --git a/rust/common/hogvm/src/program.rs b/rust/common/hogvm/src/program.rs
index a5aa7dbcc5ec..9f59edc9dc90 100644
--- a/rust/common/hogvm/src/program.rs
+++ b/rust/common/hogvm/src/program.rs
@@ -84,6 +84,19 @@ impl Program {
pub fn version(&self) -> u64 {
self.version
}
+
+ /// The full bytecode array, header included — used to populate the reference VM's
+ /// `bytecodes.root.bytecode` in a snapshot.
+ pub fn tokens(&self) -> &[JsonValue] {
+ &self.bytecode
+ }
+
+ /// Number of header tokens (`_H` + version) before the first opcode. The reference VM's
+ /// per-frame `ip` is an index into the full array (header included), whereas our `ip` is
+ /// body-relative, so root-chunk ips differ by exactly this offset.
+ pub fn header_len(&self) -> usize {
+ self.program_start_offset
+ }
}
impl Module {
diff --git a/rust/common/hogvm/src/state.rs b/rust/common/hogvm/src/state.rs
new file mode 100644
index 000000000000..d031e091f49e
--- /dev/null
+++ b/rust/common/hogvm/src/state.rs
@@ -0,0 +1,461 @@
+//! Suspend/resume state serialization — the async-coroutine half of Node-VM parity.
+//!
+//! The reference VM (`@posthog/hogvm`) is a suspendable coroutine: when a program calls a registered
+//! async function (`fetch`, `email`, `sleep`) it returns a fully-serializable `VMState`; the host
+//! performs the side effect out-of-band (often across a queue) and resumes by re-entering with that
+//! state. CDP hog functions (destinations) depend on this. This module snapshots the live
+//! [`crate::vm::HogVM`] to a [`VmSnapshot`] whose JSON is **byte-compatible with the reference's
+//! `VMState`**, so the two VMs can resume each other's states during migration.
+//!
+//! Shape decisions that mirror the reference:
+//! - the heap is flattened (`HogValue::Ref`s resolved inline; JSON can't share anyway),
+//! - closures serialize as `{__hogClosure__, callable, upvalues: [id…]}`,
+//! - upvalues are a flat `__hogUpValue__[]` keyed by `id` and **sorted by location** (the
+//! reference keeps `sortedUpValues` sorted so its capture early-break stays correct on resume),
+//! - the call stack carries a per-frame `{closure, ip, chunk, stackStart, argCount}` with an
+//! explicit root frame, and `ip` is header-inclusive for the root chunk (see [`VmSnapshot`]).
+
+use std::cell::RefCell;
+use std::collections::HashMap;
+use std::rc::Rc;
+
+use indexmap::IndexMap;
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value as JsonValue};
+
+use crate::context::Symbol;
+use crate::error::VmError;
+use crate::memory::VmHeap;
+use crate::values::{Callable, Closure, HogLiteral, HogValue, LocalCallable, Upvalue, UpvalueCell};
+
+/// A snapshot of a suspended VM, serializing to the reference VM's `VMState` JSON. Field names match
+/// the reference (camelCase) so a state produced here can be resumed by Node and vice versa.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct VmSnapshot {
+ /// The chunk map — `{ "root": { "bytecode": [...] } }` (globals are re-supplied via options on
+ /// resume, matching the reference). Carried for wire compatibility; Rust resume ignores it and
+ /// uses the supplied `ExecutionContext` instead.
+ pub bytecodes: JsonValue,
+ /// The value stack, heap flattened, in reference value shapes.
+ pub stack: Vec<JsonValue>,
+ /// Hoisted upvalues, flat, sorted by location, each carrying its `id`; closures reference ids.
+ pub upvalues: Vec<UpvalueJson>,
+ /// The call stack, root frame first, active frame last (never empty).
+ #[serde(rename = "callStack")]
+ pub call_stack: Vec<CallFrameJson>,
+ #[serde(rename = "throwStack")]
+ pub throw_stack: Vec<ThrowFrameJson>,
+ /// Deprecated reference field; always empty here.
+ #[serde(rename = "declaredFunctions")]
+ pub declared_functions: JsonValue,
+ pub ops: usize,
+ #[serde(rename = "asyncSteps")]
+ pub async_steps: usize,
+ #[serde(rename = "syncDuration")]
+ pub sync_duration: u64,
+ #[serde(rename = "maxMemUsed")]
+ pub max_mem_used: usize,
+ #[serde(skip_serializing_if = "Option::is_none", default)]
+ pub telemetry: Option<Vec<JsonValue>>,
+}
+
+/// One hoisted upvalue. `closed` upvalues own their `value`; open ones read through `location` into
+/// the live stack, so their `value` is `null`.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct UpvalueJson {
+ #[serde(rename = "__hogUpValue__")]
+ pub marker: bool,
+ pub id: usize,
+ pub location: usize,
+ pub closed: bool,
+ pub value: JsonValue,
+}
+
+/// A call frame in the reference's layout: the `closure` running in this frame, its current `ip`
+/// (header-inclusive for the root chunk), the `chunk` (module) it runs in, where its stack window
+/// starts, and how many args it was called with.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CallFrameJson {
+ pub closure: JsonValue,
+ pub ip: usize,
+ pub chunk: String,
+ #[serde(rename = "stackStart")]
+ pub stack_start: usize,
+ #[serde(rename = "argCount")]
+ pub arg_count: usize,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ThrowFrameJson {
+ #[serde(rename = "callStackLen")]
+ pub call_stack_len: usize,
+ #[serde(rename = "stackLen")]
+ pub stack_len: usize,
+ #[serde(rename = "catchIp")]
+ pub catch_ip: usize,
+}
+
+/// The result of driving a resumable execution: either the program finished, or it suspended on an
+/// async call and handed back everything the host needs to perform the side effect and resume.
+#[derive(Debug, Clone)]
+pub enum Resumable {
+ Finished(JsonValue),
+ Suspended {
+ function: String,
+ args: Vec<JsonValue>,
+ // Boxed: the snapshot is much larger than the `Finished` variant, so keep the enum small.
+ state: Box<VmSnapshot>,
+ },
+}
+
+/// Interns `UpvalueCell`s by pointer identity so the shared `Rc<RefCell<Upvalue>>` graph serializes
+/// to stable ids (mirroring the reference's `HogUpValue.id`). Ids are assigned in intern order.
+#[derive(Default)]
+pub struct CellRegistry {
+ by_ptr: HashMap<usize, usize>,
+ cells: Vec<UpvalueCell>,
+}
+
+impl CellRegistry {
+ pub fn intern(&mut self, cell: &UpvalueCell) -> usize {
+ let ptr = Rc::as_ptr(cell) as usize;
+ if let Some(&id) = self.by_ptr.get(&ptr) {
+ return id;
+ }
+ let id = self.cells.len();
+ self.by_ptr.insert(ptr, id);
+ self.cells.push(cell.clone());
+ id
+ }
+
+ pub fn cells(&self) -> &[UpvalueCell] {
+ &self.cells
+ }
+}
+
+// ---- chunk <-> symbol -------------------------------------------------------------------------
+
+/// Render a module as a reference chunk name: `None` (the top-level program) is `"root"`; an STL or
+/// imported module symbol is `"module/name"`.
+pub fn chunk_str(symbol: &Option<Symbol>) -> String {
+ match symbol {
+ None => "root".to_string(),
+ Some(s) => format!("{}/{}", s.module, s.name),
+ }
+}
+
+/// Inverse of [`chunk_str`].
+pub fn chunk_to_symbol(chunk: &str) -> Option<Symbol> {
+ if chunk == "root" {
+ return None;
+ }
+ chunk.split_once('/').map(|(m, n)| Symbol::new(m, n))
+}
+
+// ---- serialize: HogValue -> reference-shaped JSON --------------------------------------------
+
+/// Walk a value (deref-ing through the heap) and intern every `UpvalueCell` reachable through any
+/// closure it contains, so the flat upvalue array is complete before any value is serialized.
+pub fn collect_cells(
+ value: &HogValue,
+ heap: &VmHeap,
+ registry: &mut CellRegistry,
+) -> Result<(), VmError> {
+ match value.deref(heap)? {
+ HogLiteral::Array(items) | HogLiteral::Tuple(items) => {
+ for item in items {
+ collect_cells(item, heap, registry)?;
+ }
+ }
+ HogLiteral::Object(map) => {
+ for v in map.values() {
+ collect_cells(v, heap, registry)?;
+ }
+ }
+ HogLiteral::Closure(closure) => {
+ for cell in &closure.captures {
+ registry.intern(cell);
+ }
+ }
+ _ => {}
+ }
+ Ok(())
+}
+
+/// Drain the registry's worklist: every closed cell's owned value may itself hold closures, whose
+/// cells must also be interned. Iterates by index because interning appends.
+pub fn close_over_cells(heap: &VmHeap, registry: &mut CellRegistry) -> Result<(), VmError> {
+ let mut i = 0;
+ while i < registry.cells.len() {
+ let snapshot = {
+ let cell = registry.cells[i].borrow();
+ if cell.closed {
+ cell.value.clone()
+ } else {
+ None
+ }
+ };
+ if let Some(value) = snapshot {
+ collect_cells(&value, heap, registry)?;
+ }
+ i += 1;
+ }
+ Ok(())
+}
+
+pub fn value_to_json(
+ value: &HogValue,
+ heap: &VmHeap,
+ registry: &mut CellRegistry,
+ header_len: usize,
+) -> Result<JsonValue, VmError> {
+ let lit = value.deref(heap)?;
+ Ok(match lit {
+ HogLiteral::Null => JsonValue::Null,
+ HogLiteral::Boolean(b) => json!(b),
+ HogLiteral::Number(n) => JsonValue::Number(n.clone().try_into()?),
+ HogLiteral::String(s) => json!(s),
+ HogLiteral::Array(items) => {
+ let mut out = Vec::with_capacity(items.len());
+ for item in items {
+ out.push(value_to_json(item, heap, registry, header_len)?);
+ }
+ json!(out)
+ }
+ HogLiteral::Tuple(items) => {
+ let mut out = Vec::with_capacity(items.len());
+ for item in items {
+ out.push(value_to_json(item, heap, registry, header_len)?);
+ }
+ // The reference duck-types tuples as arrays with a marker; keep one so restore can tell
+ // them apart (tuple `typeof` and `(a, b)` printing depend on it).
+ json!({ "__hogTuple__": true, "items": out })
+ }
+ HogLiteral::Object(map) => {
+ let mut out = serde_json::Map::with_capacity(map.len());
+ for (k, v) in map {
+ out.insert(k.clone(), value_to_json(v, heap, registry, header_len)?);
+ }
+ JsonValue::Object(out)
+ }
+ HogLiteral::Callable(callable) => callable_to_json(callable, header_len),
+ HogLiteral::Closure(closure) => closure_to_json(closure, registry, header_len),
+ })
+}
+
+pub fn closure_to_json(
+ closure: &Closure,
+ registry: &mut CellRegistry,
+ header_len: usize,
+) -> JsonValue {
+ // Upvalue ids are 1-based to match the reference (`id: sortedUpValues.length + 1`).
+ let ids: Vec<usize> = closure
+ .captures
+ .iter()
+ .map(|cell| registry.intern(cell) + 1)
+ .collect();
+ json!({
+ "__hogClosure__": true,
+ "callable": callable_to_json(&closure.callable, header_len),
+ "upvalues": ids,
+ })
+}
+
+fn callable_to_json(callable: &Callable, header_len: usize) -> JsonValue {
+ match callable {
+ Callable::Local(lc) => {
+ // The reference's callable ip is header-inclusive for the root chunk; module callables
+ // carry no header. Our `ip` is body-relative, so add the header for root-chunk callables.
+ let ip = lc.ip + if lc.symbol.is_none() { header_len } else { 0 };
+ json!({
+ "__hogCallable__": "local",
+ "name": lc.name,
+ "argCount": lc.stack_arg_count,
+ "upvalueCount": lc.capture_count,
+ "ip": ip,
+ "chunk": chunk_str(&lc.symbol),
+ })
+ }
+ Callable::Stl(name) => json!({
+ "__hogCallable__": "stl",
+ "name": name,
+ "argCount": 0,
+ "upvalueCount": 0,
+ "ip": 0,
+ "chunk": JsonValue::Null,
+ }),
+ }
+}
+
+/// The reference's synthetic root-frame closure (an empty local callable in chunk `root`).
+pub fn root_closure_json() -> JsonValue {
+ json!({
+ "__hogClosure__": true,
+ "callable": {
+ "__hogCallable__": "local",
+ "name": "",
+ "argCount": 0,
+ "upvalueCount": 0,
+ "ip": 1,
+ "chunk": "root",
+ },
+ "upvalues": [],
+ })
+}
+
+// ---- deserialize: reference-shaped JSON -> HogValue ------------------------------------------
+
+/// Rebuild a value, re-emplacing containers into `heap` and resolving closure captures against the
+/// already-created `cells` (keyed by id).
+pub fn value_from_json(
+ json: &JsonValue,
+ heap: &mut VmHeap,
+ cells: &HashMap<usize, UpvalueCell>,
+ header_len: usize,
+) -> Result<HogValue, VmError> {
+ match json {
+ JsonValue::Null => Ok(HogLiteral::Null.into()),
+ JsonValue::Bool(b) => Ok(HogLiteral::Boolean(*b).into()),
+ JsonValue::Number(n) => Ok(HogLiteral::Number(n.clone().into()).into()),
+ JsonValue::String(s) => Ok(HogLiteral::String(s.clone()).into()),
+ JsonValue::Array(items) => {
+ let mut out = Vec::with_capacity(items.len());
+ for item in items {
+ out.push(value_from_json(item, heap, cells, header_len)?);
+ }
+ Ok(heap.emplace(HogLiteral::Array(out))?.into())
+ }
+ JsonValue::Object(map) => object_from_json(map, heap, cells, header_len),
+ }
+}
+
+fn object_from_json(
+ map: &serde_json::Map<String, JsonValue>,
+ heap: &mut VmHeap,
+ cells: &HashMap<usize, UpvalueCell>,
+ header_len: usize,
+) -> Result<HogValue, VmError> {
+ if map.contains_key("__hogClosure__") {
+ return Ok(HogLiteral::Closure(closure_from_json(
+ &JsonValue::Object(map.clone()),
+ cells,
+ header_len,
+ )?)
+ .into());
+ }
+ if map.contains_key("__hogCallable__") {
+ return Ok(HogLiteral::Callable(callable_from_json(
+ &JsonValue::Object(map.clone()),
+ header_len,
+ )?)
+ .into());
+ }
+ if map.get("__hogTuple__").and_then(|v| v.as_bool()) == Some(true) {
+ let items = map
+ .get("items")
+ .and_then(|v| v.as_array())
+ .ok_or_else(|| VmError::Other("tuple missing items".to_string()))?;
+ let mut out = Vec::with_capacity(items.len());
+ for item in items {
+ out.push(value_from_json(item, heap, cells, header_len)?);
+ }
+ return Ok(heap.emplace(HogLiteral::Tuple(out))?.into());
+ }
+ // A plain object (including reference duck-types like __hogDateTime__, which Rust also models as
+ // marked objects) — preserve key order.
+ let mut out = IndexMap::with_capacity(map.len());
+ for (k, v) in map {
+ out.insert(k.clone(), value_from_json(v, heap, cells, header_len)?);
+ }
+ Ok(heap.emplace(HogLiteral::Object(out))?.into())
+}
+
+pub fn closure_from_json(
+ json: &JsonValue,
+ cells: &HashMap<usize, UpvalueCell>,
+ header_len: usize,
+) -> Result<Closure, VmError> {
+ let callable = callable_from_json(
+ json.get("callable")
+ .ok_or_else(|| VmError::Other("closure missing callable".to_string()))?,
+ header_len,
+ )?;
+ let ids = json
+ .get("upvalues")
+ .and_then(|v| v.as_array())
+ .ok_or_else(|| VmError::Other("closure missing upvalues".to_string()))?;
+ let mut captures = Vec::with_capacity(ids.len());
+ for id in ids {
+ let id = id
+ .as_u64()
+ .ok_or_else(|| VmError::Other("bad upvalue id".to_string()))? as usize;
+ let cell = cells
+ .get(&id)
+ .ok_or_else(|| VmError::Other(format!("upvalue id {id} not found")))?;
+ captures.push(cell.clone());
+ }
+ Ok(Closure { captures, callable })
+}
+
+fn callable_from_json(json: &JsonValue, header_len: usize) -> Result<Callable, VmError> {
+ let kind = json
+ .get("__hogCallable__")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| VmError::Other("callable missing kind".to_string()))?;
+ match kind {
+ "stl" => Ok(Callable::Stl(str_field(json, "name")?)),
+ _ => {
+ let chunk = json.get("chunk").and_then(|v| v.as_str()).unwrap_or("root");
+ // Inverse of the serialize-side header offset: root-chunk ips are header-inclusive.
+ let offset = if chunk == "root" { header_len } else { 0 };
+ Ok(Callable::Local(LocalCallable {
+ name: str_field(json, "name")?,
+ stack_arg_count: usize_field(json, "argCount")?,
+ capture_count: usize_field(json, "upvalueCount")?,
+ ip: usize_field(json, "ip")?.saturating_sub(offset),
+ symbol: chunk_to_symbol(chunk),
+ }))
+ }
+ }
+}
+
+/// Build the flat upvalue cells from the snapshot, keyed by id, in two passes: create empty cells
+/// first (so closure captures resolve by id), then fill each closed cell's owned value.
+pub fn rebuild_cells(
+ upvalues: &[UpvalueJson],
+ heap: &mut VmHeap,
+ header_len: usize,
+) -> Result<HashMap<usize, UpvalueCell>, VmError> {
+ let mut cells: HashMap<usize, UpvalueCell> = HashMap::with_capacity(upvalues.len());
+ for uv in upvalues {
+ cells.insert(
+ uv.id,
+ Rc::new(RefCell::new(Upvalue {
+ location: uv.location,
+ closed: uv.closed,
+ value: None,
+ })),
+ );
+ }
+ for uv in upvalues {
+ if uv.closed {
+ let value = value_from_json(&uv.value, heap, &cells, header_len)?;
+ cells[&uv.id].borrow_mut().value = Some(value);
+ }
+ }
+ Ok(cells)
+}
+
+fn str_field(json: &JsonValue, key: &str) -> Result<String, VmError> {
+ json.get(key)
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_string())
+ .ok_or_else(|| VmError::Other(format!("missing string field '{key}'")))
+}
+
+fn usize_field(json: &JsonValue, key: &str) -> Result<usize, VmError> {
+ json.get(key)
+ .and_then(|v| v.as_u64())
+ .map(|n| n as usize)
+ .ok_or_else(|| VmError::Other(format!("missing numeric field '{key}'")))
+}
diff --git a/rust/common/hogvm/src/stl.rs b/rust/common/hogvm/src/stl.rs
index b9a84ce778b6..3383a0ac5dc1 100644
--- a/rust/common/hogvm/src/stl.rs
+++ b/rust/common/hogvm/src/stl.rs
@@ -2,24 +2,29 @@ use core::str;
use std::collections::HashMap;
use std::sync::Arc;
-use chrono::{DateTime, Datelike, LocalResult, NaiveDate, NaiveDateTime, TimeZone};
+use base64::Engine as _;
+use chrono::{DateTime, Datelike, LocalResult, NaiveDate, NaiveDateTime, TimeZone, Timelike};
+use hmac::{Hmac, Mac};
+use indexmap::IndexMap;
+use md5::Md5;
use once_cell::sync::Lazy;
use rand::Rng;
+use serde::de::{MapAccess, SeqAccess, Visitor};
use serde_json::{json, Value as JsonValue};
+use sha2::{Digest, Sha256};
use crate::{
construct_free_standing,
error::VmError,
- memory::VmHeap,
+ memory::{HeapReference, VmHeap},
+ print_hog_string_output,
program::Module,
util::{get_json_nested, regex_extract, regex_match},
- values::{HogLiteral, HogValue, Num},
- vm::HogVM,
+ values::{compare_values, HogLiteral, HogValue, Num, NumOp},
+ vm::{HogVM, MAX_JSON_SERDE_DEPTH},
ExportedFunction,
};
-pub const TO_STRING_RECURSION_LIMIT: usize = 32;
-
// A "native function" is a function that can be called from within the VM. It takes a list
// of arguments, and returns either a value, or null. It's pure (cannot modify the VM state).
// `Arc` (not `Box`) so the static registry below can be cloned cheaply per execution context.
@@ -58,20 +63,35 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
native_func(|vm, args| {
assert_argc(&args, 1, "typeof")?;
let arg = args[0].deref(&vm.heap)?;
- // TODO - tuples, dates, datetimes, errors are all just duck-typed "objects" or "arrays", but we should
- // still support them I guess
- match arg {
- HogLiteral::Number(_) => Ok(HogLiteral::String("number".to_string()).into()),
- HogLiteral::Boolean(_) => Ok(HogLiteral::String("boolean".to_string()).into()),
- HogLiteral::String(_) => Ok(HogLiteral::String("string".to_string()).into()),
- HogLiteral::Array(_) => Ok(HogLiteral::String("array".to_string()).into()),
- HogLiteral::Object(_) => Ok(HogLiteral::String("object".to_string()).into()),
- HogLiteral::Callable(_) => {
- Ok(HogLiteral::String("function".to_string()).into())
+ let t = match arg {
+ // The reference distinguishes integer/float, not a single "number".
+ HogLiteral::Number(n) => {
+ if n.is_float() {
+ "float"
+ } else {
+ "integer"
+ }
}
- HogLiteral::Closure(_) => Ok(HogLiteral::String("function".to_string()).into()),
- HogLiteral::Null => Ok(HogLiteral::String("null".to_string()).into()),
- }
+ HogLiteral::Boolean(_) => "boolean",
+ HogLiteral::String(_) => "string",
+ HogLiteral::Array(_) => "array",
+ HogLiteral::Tuple(_) => "tuple",
+ // Datetimes, dates, and errors are duck-typed objects distinguished by markers.
+ HogLiteral::Object(obj) => {
+ if obj_marker(&vm.heap, obj, "__hogDateTime__")? {
+ "datetime"
+ } else if obj_marker(&vm.heap, obj, "__hogDate__")? {
+ "date"
+ } else if obj_marker(&vm.heap, obj, "__hogError__")? {
+ "error"
+ } else {
+ "object"
+ }
+ }
+ HogLiteral::Callable(_) | HogLiteral::Closure(_) => "function",
+ HogLiteral::Null => "null",
+ };
+ Ok(HogLiteral::String(t.to_string()).into())
}),
),
(
@@ -91,7 +111,10 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
assert_argc(&args, 1, "values")?;
let arg = args[0].deref(&vm.heap)?;
match arg {
- HogLiteral::Array(_) => Ok(arg.clone().into()),
+ // Arrays and tuples both yield a plain array of their elements (reference: [...obj]).
+ HogLiteral::Array(a) | HogLiteral::Tuple(a) => {
+ Ok(HogLiteral::Array(a.clone()).into())
+ }
HogLiteral::Object(obj) => {
Ok(HogLiteral::Array(obj.values().cloned().collect()).into())
}
@@ -101,13 +124,21 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
}
}),
),
+ (
+ "tuple",
+ // `tuple(a, b, c)` constructs a tuple from its arguments (reference: args.slice() tagged
+ // __isHogTuple). Any arity is allowed, including zero.
+ native_func(|_vm, args| Ok(HogLiteral::Tuple(args).into())),
+ ),
(
"length",
native_func(|vm, args| {
assert_argc(&args, 1, "length")?;
let arg = args[0].deref(&vm.heap)?;
match arg {
- HogLiteral::Array(arr) => Ok(HogLiteral::Number(arr.len().into()).into()),
+ HogLiteral::Array(arr) | HogLiteral::Tuple(arr) => {
+ Ok(HogLiteral::Number(arr.len().into()).into())
+ }
HogLiteral::Object(obj) => Ok(HogLiteral::Number(obj.len().into()).into()),
HogLiteral::String(str) => Ok(HogLiteral::Number(str.len().into()).into()),
_ => Err(VmError::NativeCallFailed(
@@ -260,10 +291,21 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
(
"has",
native_func(|vm, args| {
+ // Unlike the `in` opcode, the reference `has` STL is array-only: a non-array
+ // haystack (string, object, null, …) is never a member, yielding false.
assert_argc(&args, 2, "has")?;
- let haystack = &args[0];
let needle = &args[1];
- haystack.contains(needle, &vm.heap).map(|res| res.into())
+ match args[0].deref(&vm.heap)? {
+ HogLiteral::Array(vals) => {
+ for val in vals.iter() {
+ if *needle.equals(val, &vm.heap)?.try_as()? {
+ return Ok(HogLiteral::Boolean(true).into());
+ }
+ }
+ Ok(HogLiteral::Boolean(false).into())
+ }
+ _ => Ok(HogLiteral::Boolean(false).into()),
+ }
}),
),
(
@@ -279,11 +321,11 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
return Ok((i as i64).saturating_add(1).into());
}
}
- Ok(HogLiteral::Null.into())
+ // The reference returns 0 (arr.indexOf(elem) + 1) when not found.
+ Ok(HogLiteral::Number(Num::Integer(0)).into())
}
- _ => Err(VmError::NativeCallFailed(
- "indexOf() only supports arrays".to_string(),
- )),
+ // Non-array arguments yield 0, matching the reference.
+ _ => Ok(HogLiteral::Number(Num::Integer(0)).into()),
}
}),
),
@@ -291,27 +333,39 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
"notEmpty",
native_func(|vm, args| {
assert_argc(&args, 1, "notEmpty")?;
- let val = &args[0];
- match val.deref(&vm.heap)? {
- HogLiteral::Array(a) => Ok(HogLiteral::Boolean(!a.is_empty()).into()),
- HogLiteral::String(s) => Ok(HogLiteral::Boolean(!s.is_empty()).into()),
- HogLiteral::Object(o) => Ok(HogLiteral::Boolean(!o.is_empty()).into()),
- _ => Err(VmError::NativeCallFailed(format!(
- "{} not supported by notEmpty",
- val.type_name()
- ))),
- }
+ // The reference defines notEmpty as the exact negation of empty.
+ Ok(HogLiteral::Boolean(!is_hog_empty(args[0].deref(&vm.heap)?)).into())
}),
),
(
"match",
native_func(|vm, args| {
assert_argc(&args, 2, "match")?;
- let value = args[0].deref(&vm.heap)?.try_as::<str>()?;
- let regex = args[1].deref(&vm.heap)?.try_as::<str>()?;
- Ok(HogLiteral::Boolean(regex_match(value, regex, true)?).into())
+ let value = args[0].deref(&vm.heap)?;
+ let regex = args[1].deref(&vm.heap)?;
+ // The reference returns false when either arg is falsy (null/empty) rather than matching.
+ if !value.truthy() || !regex.truthy() {
+ return Ok(HogLiteral::Boolean(false).into());
+ }
+ Ok(HogLiteral::Boolean(regex_match(value.try_as::<str>()?, regex.try_as::<str>()?, true)?).into())
}),
),
+ (
+ "like",
+ native_func(|vm, args| like_impl(vm, &args, "like", false, false)),
+ ),
+ (
+ "ilike",
+ native_func(|vm, args| like_impl(vm, &args, "ilike", true, false)),
+ ),
+ (
+ "notLike",
+ native_func(|vm, args| like_impl(vm, &args, "notLike", false, true)),
+ ),
+ (
+ "notILike",
+ native_func(|vm, args| like_impl(vm, &args, "notILike", true, true)),
+ ),
(
"extractRegex",
native_func(err_to_null(|vm, args| {
@@ -401,191 +455,2133 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
Ok(HogLiteral::Number(Num::Float(value)).into())
}),
),
- ]
- .into_iter()
- .map(|(name, func)| (name.to_string(), func))
- .collect()
-}
-
-pub fn hog_stl() -> Module {
- let funcs = json!({
- "arrayCount": [2, [33, 0, 36, 1, 36, 3, 2, "values", 1, 33, 1, 36, 4, 2, "length", 1, 31, 36, 6, 36, 5, 16, 40, 31, 36, 4, 36, 5, 45, 37, 7, 36, 7, 36, 0, 54, 1, 40, 7, 33, 1, 36, 2, 6, 37, 2, 36, 5, 33, 1, 6, 37, 5, 39, -38, 35, 35, 35, 35, 35, 36, 2, 38, 35]],
- "arrayExists": [2, [36, 1, 36, 2, 2, "values", 1, 33, 1, 36, 3, 2, "length", 1, 31, 36, 5, 36, 4, 16, 40, 26, 36, 3, 36, 4, 45, 37, 6, 36, 6, 36, 0, 54, 1, 40, 2, 29, 38, 36, 4, 33, 1, 6, 37, 4, 39, -33, 35, 35, 35, 35, 35, 30, 38]],
- "arrayFilter": [2, [43, 0, 36, 1, 36, 3, 2, "values", 1, 33, 1, 36, 4, 2, "length", 1, 31, 36, 6, 36, 5, 16, 40, 33, 36, 4, 36, 5, 45, 37, 7, 36, 7, 36, 0, 54, 1, 40, 9, 36, 2, 36, 7, 2, "arrayPushBack", 2, 37, 2, 36, 5, 33, 1, 6, 37, 5, 39, -40, 35, 35, 35, 35, 35, 36, 2, 38, 35]],
- "arrayMap": [2, [43, 0, 36, 1, 36, 3, 2, "values", 1, 33, 1, 36, 4, 2, "length", 1, 31, 36, 6, 36, 5, 16, 40, 29, 36, 4, 36, 5, 45, 37, 7, 36, 2, 36, 7, 36, 0, 54, 1, 2, "arrayPushBack", 2, 37, 2, 36, 5, 33, 1, 6, 37, 5, 39, -36, 35, 35, 35, 35, 35, 36, 2, 38, 35]],
- "arrayReduce": [3, [36, 2, 36, 1, 36, 4, 2, "values", 1, 33, 1, 36, 5, 2, "length", 1, 31, 36, 7, 36, 6, 16, 40, 26, 36, 5, 36, 6, 45, 37, 8, 36, 3, 36, 8, 36, 0, 54, 2, 37, 3, 36, 6, 33, 1, 6, 37, 6, 39, -33, 35, 35, 35, 35, 35, 36, 3, 38, 35]],
- "sortableSemver": [1, [31, 36, 0, 11, 40, 3, 43, 0, 38, 36, 0, 32, "(\\d+(\\.\\d+)+)", 2, "extractRegex", 2, 36, 1, 2, "empty", 1, 40, 3, 43, 0, 38, 32, ".", 36, 1, 2, "splitByString", 2, 52, "lambda", 1, 0, 11, 36, 0, 2, "toInt", 1, 47, 3, 35, 33, 0, 38, 53, 0, 36, 2, 2, "arrayMap", 2, 38, 35, 35]],
- });
-
- let funcs: HashMap<String, (usize, Vec<JsonValue>)> =
- serde_json::from_value(funcs).expect("All stl functions are valid");
- let mut res = Module::new();
- for (name, (arg_count, bytecode)) in funcs {
- let func = ExportedFunction::new(arg_count, bytecode);
- res.add_function(name, func);
- }
- res
-}
-
-// TODO - this is slow, because rather than using a string buffer, we're allocating a new string each time
-// we recurse
-fn to_string(heap: &VmHeap, val: &HogValue, depth: usize) -> Result<String, VmError> {
- if depth > TO_STRING_RECURSION_LIMIT {
- return Err(VmError::NativeCallFailed(
- "Maximum toString recursion depth exceeded".to_string(),
- ));
- }
-
- let val = val.deref(heap)?;
- match val {
- HogLiteral::Number(num) => {
- let val = if num.is_float() {
- num.to_float().to_string()
- } else {
- num.to_integer().to_string()
- };
- Ok(val)
- }
- HogLiteral::Boolean(bool) => Ok(bool.to_string()),
- HogLiteral::String(string) => Ok(string.clone()),
- HogLiteral::Array(hog_values) => Ok(format!(
- "[{}]",
- hog_values
- .iter()
- .map(|v| to_string(heap, v, depth + 1))
- .collect::<Result<Vec<String>, VmError>>()?
- .join(", ")
- )),
- HogLiteral::Object(hash_map) => {
- let mut entries = Vec::new();
- for (key, value) in hash_map {
- entries.push(format!("{}: {}", key, to_string(heap, value, depth + 1)?));
- }
- Ok(format!("{{{}}}", entries.join(", ")))
- }
- HogLiteral::Callable(callable) => Ok(callable.to_string()),
- HogLiteral::Closure(closure) => Ok(closure.to_string()),
- HogLiteral::Null => Ok("null".to_string()),
- }
-}
-
-/// `toDateTime(input[, zone])` → a Hog DateTime object `{ __hogDateTime__: true, dt, zone }`.
-///
-/// To match ClickHouse (the parity oracle), this VM orders Hog temporals by `dt` seconds
-/// ([`crate::values::compare_values`]) — the reference Python/TS HogVMs cannot order them, so their
-/// `is_date_before`/`is_date_after` always return `false`. Naive strings parse as UTC (or `zone` for
-/// the 2-arg form), not the process-local timezone; an explicit offset/`Z` is honored as written.
-fn to_datetime(vm: &HogVM, args: Vec<HogValue>) -> Result<HogValue, VmError> {
- if args.is_empty() || args.len() > 2 {
- return Err(VmError::NativeCallFailed(
- "toDateTime takes 1 or 2 arguments".to_string(),
- ));
- }
- let zone = match args.get(1) {
- Some(arg) => Some(arg.deref(&vm.heap)?.try_as::<str>()?.to_string()),
- None => None,
- };
- let zone = zone.as_deref();
- let dt_seconds = match args[0].deref(&vm.heap)? {
- HogLiteral::Number(n) => n.to_float(),
- HogLiteral::String(s) => parse_datetime_to_seconds(s, zone)?,
- other => {
- return Err(VmError::NativeCallFailed(format!(
- "toDateTime expects a number or string, got {}",
- other.type_name()
- )))
- }
- };
- construct_free_standing(
- json!({ "__hogDateTime__": true, "dt": dt_seconds, "zone": zone.unwrap_or("UTC") }),
- 0,
- )
-}
-
-/// `toDate(input)` → a Hog Date object `{ __hogDate__: true, year, month, day }` in UTC.
-fn to_date(vm: &HogVM, args: Vec<HogValue>) -> Result<HogValue, VmError> {
- assert_argc(&args, 1, "toDate")?;
- let seconds = match args[0].deref(&vm.heap)? {
- HogLiteral::Number(n) => n.to_float(),
- HogLiteral::String(s) => parse_datetime_to_seconds(s, None)?,
- other => {
- return Err(VmError::NativeCallFailed(format!(
- "toDate expects a number or string, got {}",
- other.type_name()
- )))
- }
- };
- let dt = DateTime::from_timestamp(seconds as i64, 0).ok_or_else(|| {
- VmError::NativeCallFailed(format!("toDate: timestamp {seconds} out of range"))
- })?;
- construct_free_standing(
- json!({ "__hogDate__": true, "year": dt.year(), "month": dt.month(), "day": dt.day() }),
- 0,
- )
-}
-
-const NAIVE_DATETIME_FORMATS: [&str; 2] = ["%Y-%m-%d %H:%M:%S%.f", "%Y-%m-%dT%H:%M:%S%.f"];
-
-fn parse_datetime_to_seconds(input: &str, zone: Option<&str>) -> Result<f64, VmError> {
- let input = input.trim();
- // An explicit offset/`Z` pins the absolute instant regardless of `zone`.
- if let Ok(dt) = DateTime::parse_from_rfc3339(input) {
- return Ok(datetime_to_seconds(dt));
- }
- for fmt in NAIVE_DATETIME_FORMATS {
- if let Ok(naive) = NaiveDateTime::parse_from_str(input, fmt) {
- return naive_to_seconds(naive, zone);
- }
- }
- if let Some(naive) = NaiveDate::parse_from_str(input, "%Y-%m-%d")
- .ok()
- .and_then(|date| date.and_hms_opt(0, 0, 0))
- {
- return naive_to_seconds(naive, zone);
- }
- // A bare numeric string is unix seconds (e.g. an upstream `toString(<number>)`).
- if let Ok(seconds) = input.parse::<f64>() {
- return Ok(seconds);
- }
- Err(VmError::NativeCallFailed(format!(
- "toDateTime could not parse {input:?}"
- )))
-}
-
-fn naive_to_seconds(naive: NaiveDateTime, zone: Option<&str>) -> Result<f64, VmError> {
- let Some(zone) = zone else {
- return Ok(datetime_to_seconds(naive.and_utc()));
- };
- let tz: chrono_tz::Tz = zone
- .parse()
- .map_err(|_| VmError::NativeCallFailed(format!("toDateTime: unknown timezone {zone:?}")))?;
- match tz.from_local_datetime(&naive) {
- // DST fold: ClickHouse resolves to a single instant; take the earlier one.
- LocalResult::Single(dt) | LocalResult::Ambiguous(dt, _) => Ok(datetime_to_seconds(dt)),
- LocalResult::None => Err(VmError::NativeCallFailed(format!(
- "toDateTime: {naive} does not exist in {zone}"
- ))),
- }
-}
-
-/// `f64` epoch seconds with sub-second precision, matching Python's `datetime.timestamp()`.
-fn datetime_to_seconds<Tz: TimeZone>(dt: DateTime<Tz>) -> f64 {
- dt.timestamp() as f64 + f64::from(dt.timestamp_subsec_nanos()) / 1_000_000_000.0
-}
-
-// Extract every element as a Num and return them sorted ascending. Single allocation + early error,
-// rather than partitioning into (oks, errs) Vecs and unwrapping — the old path allocated several
-// intermediate Vecs per call, which showed up under profiling for sort-heavy workloads.
-fn collect_sorted_nums(heap: &VmHeap, arr: &[HogValue], name: &str) -> Result<Vec<Num>, VmError> {
- let mut nums = Vec::with_capacity(arr.len());
- for v in arr {
- let n = v.deref(heap)?.try_as::<Num>().map_err(|_| {
- VmError::NativeCallFailed(format!("{name}() only supports arrays of numbers"))
- })?;
- nums.push(n.clone());
- }
- nums.sort_unstable_by(|a, b| a.compare(b));
- Ok(nums)
+ (
+ "concat",
+ native_func(|vm, args| {
+ // Stringify each arg via the canonical print-string formatting; nulls become "".
+ let mut out = String::new();
+ for arg in &args {
+ if !matches!(arg.deref(&vm.heap)?, HogLiteral::Null) {
+ out.push_str(&print_hog_string_output(&vm.heap, arg)?);
+ }
+ }
+ Ok(HogLiteral::String(out).into())
+ }),
+ ),
+ (
+ "lower",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "lower")?;
+ match args[0].deref(&vm.heap)? {
+ HogLiteral::Null => Ok(HogLiteral::Null.into()),
+ HogLiteral::String(s) => Ok(HogLiteral::String(s.to_lowercase()).into()),
+ other => Err(VmError::NativeCallFailed(format!(
+ "lower() expects a string, got {}",
+ other.type_name()
+ ))),
+ }
+ }),
+ ),
+ (
+ "upper",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "upper")?;
+ let s: &str = args[0].deref(&vm.heap)?.try_as()?;
+ Ok(HogLiteral::String(s.to_uppercase()).into())
+ }),
+ ),
+ (
+ "reverse",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "reverse")?;
+ match args[0].deref(&vm.heap)? {
+ HogLiteral::String(s) => {
+ Ok(HogLiteral::String(s.chars().rev().collect()).into())
+ }
+ HogLiteral::Array(arr) => {
+ let mut a = arr.clone();
+ a.reverse();
+ Ok(HogLiteral::Array(a).into())
+ }
+ other => Err(VmError::NativeCallFailed(format!(
+ "reverse() expects a string or array, got {}",
+ other.type_name()
+ ))),
+ }
+ }),
+ ),
+ ("trim", native_func(|vm, args| trim_impl(vm, args, TrimSide::Both))),
+ ("trimLeft", native_func(|vm, args| trim_impl(vm, args, TrimSide::Left))),
+ ("trimRight", native_func(|vm, args| trim_impl(vm, args, TrimSide::Right))),
+ (
+ "isNotNull",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "isNotNull")?;
+ Ok(
+ HogLiteral::Boolean(!matches!(args[0].deref(&vm.heap)?, HogLiteral::Null))
+ .into(),
+ )
+ }),
+ ),
+ (
+ "jsonParse",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "jsonParse")?;
+ let s: &str = args[0].deref(&vm.heap)?.try_as()?;
+ // Deserialize straight to a HogValue (not serde_json::Value, which sorts object keys
+ // without the preserve_order feature) to keep document order.
+ let parsed: HogJson = serde_json::from_str(s)
+ .map_err(|e| VmError::NativeCallFailed(format!("jsonParse: {e}")))?;
+ Ok(parsed.0)
+ }),
+ ),
+ (
+ "jsonStringify",
+ native_func(|vm, args| {
+ // The optional 2nd "indent" arg (pretty-print) isn't used by the corpus; we emit the
+ // compact-with-spaces form (Python json.dumps default) the single-arg callers expect.
+ assert(
+ !args.is_empty(),
+ "jsonStringify requires at least one argument",
+ )?;
+ let s = json_stringify(&vm.heap, &args[0], &mut Vec::new(), 0)?;
+ Ok(HogLiteral::String(s).into())
+ }),
+ ),
+ (
+ "isValidJSON",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "isValidJSON")?;
+ let valid = match args[0].deref(&vm.heap)? {
+ HogLiteral::String(s) => serde_json::from_str::<JsonValue>(s).is_ok(),
+ _ => false,
+ };
+ Ok(HogLiteral::Boolean(valid).into())
+ }),
+ ),
+ (
+ "toInt",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "toInt")?;
+ let res = match args[0].deref(&vm.heap)? {
+ // Datetimes floor to whole seconds; dates to whole days since the epoch.
+ HogLiteral::Object(obj) if obj_marker(&vm.heap, obj, "__hogDateTime__")? => {
+ Some(obj_number(&vm.heap, obj, "dt")?.unwrap_or(0.0).floor() as i64)
+ }
+ HogLiteral::Object(obj) if obj_marker(&vm.heap, obj, "__hogDate__")? => {
+ Some(hog_date_epoch_days(&vm.heap, obj)?)
+ }
+ HogLiteral::Number(n) => Some(if n.is_float() {
+ n.to_float() as i64
+ } else {
+ n.to_integer()
+ }),
+ HogLiteral::Boolean(b) => Some(*b as i64),
+ HogLiteral::String(s) => s.trim().parse::<i64>().ok(),
+ _ => None,
+ };
+ // ValueError -> null in the reference.
+ Ok(res
+ .map(|i| HogLiteral::Number(Num::Integer(i)))
+ .unwrap_or(HogLiteral::Null)
+ .into())
+ }),
+ ),
+ (
+ "toFloat",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "toFloat")?;
+ let res = match args[0].deref(&vm.heap)? {
+ HogLiteral::Object(obj) if obj_marker(&vm.heap, obj, "__hogDateTime__")? => {
+ Some(obj_number(&vm.heap, obj, "dt")?.unwrap_or(0.0))
+ }
+ HogLiteral::Object(obj) if obj_marker(&vm.heap, obj, "__hogDate__")? => {
+ Some(hog_date_epoch_days(&vm.heap, obj)? as f64)
+ }
+ HogLiteral::Number(n) => Some(n.to_float()),
+ HogLiteral::String(s) => s.trim().parse::<f64>().ok(),
+ _ => None,
+ };
+ Ok(res
+ .map(|f| HogLiteral::Number(Num::Float(f)))
+ .unwrap_or(HogLiteral::Null)
+ .into())
+ }),
+ ),
+ (
+ "ifNull",
+ native_func(|vm, args| {
+ assert_argc(&args, 2, "ifNull")?;
+ if matches!(args[0].deref(&vm.heap)?, HogLiteral::Null) {
+ Ok(args[1].clone())
+ } else {
+ Ok(args[0].clone())
+ }
+ }),
+ ),
+ (
+ "coalesce",
+ native_func(|vm, args| {
+ for arg in &args {
+ if !matches!(arg.deref(&vm.heap)?, HogLiteral::Null) {
+ return Ok(arg.clone());
+ }
+ }
+ Ok(HogLiteral::Null.into())
+ }),
+ ),
+ (
+ "assumeNotNull",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "assumeNotNull")?;
+ if matches!(args[0].deref(&vm.heap)?, HogLiteral::Null) {
+ Err(VmError::NativeCallFailed(
+ "Value is null in assumeNotNull".to_string(),
+ ))
+ } else {
+ Ok(args[0].clone())
+ }
+ }),
+ ),
+ (
+ "empty",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "empty")?;
+ Ok(HogLiteral::Boolean(is_hog_empty(args[0].deref(&vm.heap)?)).into())
+ }),
+ ),
+ (
+ "keys",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "keys")?;
+ match args[0].deref(&vm.heap)? {
+ HogLiteral::Object(o) => Ok(HogLiteral::Array(
+ o.keys().map(|k| HogLiteral::String(k.clone()).into()).collect(),
+ )
+ .into()),
+ // Arrays/tuples -> 0-based index list, matching the reference.
+ HogLiteral::Array(a) | HogLiteral::Tuple(a) => Ok(HogLiteral::Array(
+ (0..a.len())
+ .map(|i| HogLiteral::Number(Num::Integer(i as i64)).into())
+ .collect(),
+ )
+ .into()),
+ _ => Ok(HogLiteral::Array(vec![]).into()),
+ }
+ }),
+ ),
+ (
+ "round",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "round")?;
+ let n: &Num = args[0].deref(&vm.heap)?.try_as()?;
+ // Python round() is round-half-to-even and returns an int.
+ Ok(HogLiteral::Number(Num::Integer(n.to_float().round_ties_even() as i64)).into())
+ }),
+ ),
+ (
+ "floor",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "floor")?;
+ let n: &Num = args[0].deref(&vm.heap)?.try_as()?;
+ Ok(HogLiteral::Number(Num::Integer(n.to_float().floor() as i64)).into())
+ }),
+ ),
+ (
+ "min2",
+ native_func(|vm, args| {
+ assert_argc(&args, 2, "min2")?;
+ let less = {
+ let a: &Num = args[0].deref(&vm.heap)?.try_as()?;
+ let b: &Num = args[1].deref(&vm.heap)?.try_as()?;
+ a.compare(b) == std::cmp::Ordering::Less
+ };
+ Ok(if less { args[0].clone() } else { args[1].clone() })
+ }),
+ ),
+ (
+ "max2",
+ native_func(|vm, args| {
+ assert_argc(&args, 2, "max2")?;
+ let greater = {
+ let a: &Num = args[0].deref(&vm.heap)?.try_as()?;
+ let b: &Num = args[1].deref(&vm.heap)?.try_as()?;
+ a.compare(b) == std::cmp::Ordering::Greater
+ };
+ Ok(if greater { args[0].clone() } else { args[1].clone() })
+ }),
+ ),
+ (
+ "range",
+ native_func(|vm, args| {
+ if args.is_empty() || args.len() > 2 {
+ return Err(VmError::NativeCallFailed(
+ "range supports 1 or 2 arguments".to_string(),
+ ));
+ }
+ let (start, end) = if args.len() == 1 {
+ (0, args[0].deref(&vm.heap)?.try_as::<Num>()?.to_integer())
+ } else {
+ (
+ args[0].deref(&vm.heap)?.try_as::<Num>()?.to_integer(),
+ args[1].deref(&vm.heap)?.try_as::<Num>()?.to_integer(),
+ )
+ };
+ let arr = (start..end)
+ .map(|i| HogLiteral::Number(Num::Integer(i)).into())
+ .collect();
+ Ok(HogLiteral::Array(arr).into())
+ }),
+ ),
+ (
+ "substring",
+ native_func(|vm, args| {
+ if args.len() < 2 || args.len() > 3 {
+ return Err(VmError::NativeCallFailed(
+ "substring takes 2 or 3 arguments".to_string(),
+ ));
+ }
+ let chars: Vec<char> = match args[0].deref(&vm.heap)? {
+ HogLiteral::String(s) => s.chars().collect(),
+ _ => return Ok(HogLiteral::String(String::new()).into()),
+ };
+ // start is 1-based.
+ let start_idx = args[1].deref(&vm.heap)?.try_as::<Num>()?.to_integer() - 1;
+ let length = if args.len() > 2 {
+ args[2].deref(&vm.heap)?.try_as::<Num>()?.to_integer()
+ } else {
+ chars.len() as i64 - start_idx
+ };
+ if start_idx < 0 || length < 0 || start_idx >= chars.len() as i64 {
+ return Ok(HogLiteral::String(String::new()).into());
+ }
+ let s_u = start_idx as usize;
+ let e_u = ((start_idx + length) as usize).min(chars.len());
+ Ok(HogLiteral::String(chars[s_u..e_u].iter().collect()).into())
+ }),
+ ),
+ (
+ "replaceOne",
+ native_func(|vm, args| {
+ assert_argc(&args, 3, "replaceOne")?;
+ let s: &str = args[0].deref(&vm.heap)?.try_as()?;
+ let from: &str = args[1].deref(&vm.heap)?.try_as()?;
+ let to: &str = args[2].deref(&vm.heap)?.try_as()?;
+ Ok(HogLiteral::String(s.replacen(from, to, 1)).into())
+ }),
+ ),
+ (
+ "replaceAll",
+ native_func(|vm, args| {
+ assert_argc(&args, 3, "replaceAll")?;
+ let s: &str = args[0].deref(&vm.heap)?.try_as()?;
+ let from: &str = args[1].deref(&vm.heap)?.try_as()?;
+ let to: &str = args[2].deref(&vm.heap)?.try_as()?;
+ Ok(HogLiteral::String(s.replace(from, to)).into())
+ }),
+ ),
+ (
+ "splitByString",
+ native_func(|vm, args| {
+ if args.len() < 2 || args.len() > 3 {
+ return Err(VmError::NativeCallFailed(
+ "splitByString takes 2 or 3 arguments".to_string(),
+ ));
+ }
+ // splitByString(separator, string[, max])
+ let sep: &str = args[0].deref(&vm.heap)?.try_as()?;
+ let s: &str = args[1].deref(&vm.heap)?.try_as()?;
+ let parts: Vec<HogValue> = if args.len() > 2 {
+ let max = args[2].deref(&vm.heap)?.try_as::<Num>()?.to_integer();
+ let max = if max < 0 { 0 } else { max as usize };
+ s.split(sep)
+ .take(max)
+ .map(|p| HogLiteral::String(p.to_string()).into())
+ .collect()
+ } else {
+ s.split(sep)
+ .map(|p| HogLiteral::String(p.to_string()).into())
+ .collect()
+ };
+ Ok(HogLiteral::Array(parts).into())
+ }),
+ ),
+ (
+ "startsWith",
+ native_func(|vm, args| {
+ assert_argc(&args, 2, "startsWith")?;
+ let result = matches!(
+ (args[0].deref(&vm.heap)?, args[1].deref(&vm.heap)?),
+ (HogLiteral::String(s), HogLiteral::String(p)) if s.starts_with(p.as_str())
+ );
+ Ok(HogLiteral::Boolean(result).into())
+ }),
+ ),
+ (
+ "position",
+ native_func(|vm, args| {
+ assert_argc(&args, 2, "position")?;
+ Ok(HogLiteral::Number(Num::Integer(position_impl(vm, &args[0], &args[1], false)?))
+ .into())
+ }),
+ ),
+ (
+ "positionCaseInsensitive",
+ native_func(|vm, args| {
+ assert_argc(&args, 2, "positionCaseInsensitive")?;
+ Ok(HogLiteral::Number(Num::Integer(position_impl(vm, &args[0], &args[1], true)?))
+ .into())
+ }),
+ ),
+ (
+ "JSONHas",
+ native_func(|vm, args| {
+ assert(!args.is_empty(), "JSONHas requires at least one argument")?;
+ Ok(HogLiteral::Boolean(json_path_value(vm, &args)?.is_some()).into())
+ }),
+ ),
+ (
+ "JSONLength",
+ native_func(|vm, args| {
+ assert(!args.is_empty(), "JSONLength requires at least one argument")?;
+ let len = match json_path_value(vm, &args)? {
+ Some(JsonValue::Array(a)) => a.len() as i64,
+ Some(JsonValue::Object(o)) => o.len() as i64,
+ _ => 0,
+ };
+ Ok(HogLiteral::Number(Num::Integer(len)).into())
+ }),
+ ),
+ (
+ "JSONExtractString",
+ native_func(|vm, args| {
+ assert(!args.is_empty(), "JSONExtractString requires at least one argument")?;
+ let res = match json_path_value(vm, &args)? {
+ None | Some(JsonValue::Null) => HogLiteral::Null,
+ Some(JsonValue::String(s)) => HogLiteral::String(s),
+ Some(JsonValue::Bool(b)) => {
+ HogLiteral::String(if b { "True" } else { "False" }.to_string())
+ }
+ Some(JsonValue::Number(n)) => HogLiteral::String(n.to_string()),
+ Some(other) => HogLiteral::String(other.to_string()),
+ };
+ Ok(res.into())
+ }),
+ ),
+ (
+ "JSONExtractInt",
+ native_func(|vm, args| {
+ assert(!args.is_empty(), "JSONExtractInt requires at least one argument")?;
+ let res = match json_path_value(vm, &args)? {
+ Some(JsonValue::Number(n)) => n.as_i64().or_else(|| n.as_f64().map(|f| f as i64)),
+ Some(JsonValue::String(s)) => s.trim().parse::<i64>().ok(),
+ _ => None,
+ };
+ Ok(res
+ .map(|i| HogLiteral::Number(Num::Integer(i)))
+ .unwrap_or(HogLiteral::Null)
+ .into())
+ }),
+ ),
+ (
+ "JSONExtractFloat",
+ native_func(|vm, args| {
+ assert(!args.is_empty(), "JSONExtractFloat requires at least one argument")?;
+ let res = match json_path_value(vm, &args)? {
+ Some(JsonValue::Number(n)) => n.as_f64(),
+ Some(JsonValue::String(s)) => s.trim().parse::<f64>().ok(),
+ _ => None,
+ };
+ Ok(res
+ .map(|f| HogLiteral::Number(Num::Float(f)))
+ .unwrap_or(HogLiteral::Null)
+ .into())
+ }),
+ ),
+ (
+ "JSONExtractBool",
+ native_func(|vm, args| {
+ assert(!args.is_empty(), "JSONExtractBool requires at least one argument")?;
+ let b = matches!(json_path_value(vm, &args)?, Some(JsonValue::Bool(true)));
+ Ok(HogLiteral::Boolean(b).into())
+ }),
+ ),
+ (
+ "JSONExtractArrayRaw",
+ native_func(|vm, args| {
+ assert(!args.is_empty(), "JSONExtractArrayRaw requires at least one argument")?;
+ match json_path_value(vm, &args)? {
+ Some(arr @ JsonValue::Array(_)) => construct_free_standing(arr, 0),
+ _ => Ok(HogLiteral::Null.into()),
+ }
+ }),
+ ),
+ (
+ "fromUnixTimestamp",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "fromUnixTimestamp")?;
+ let ts = args[0].deref(&vm.heap)?.try_as::<Num>()?.to_float();
+ make_hog_datetime(ts, "UTC")
+ }),
+ ),
+ (
+ "fromUnixTimestampMilli",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "fromUnixTimestampMilli")?;
+ let ms = args[0].deref(&vm.heap)?.try_as::<Num>()?.to_float();
+ make_hog_datetime(ms / 1000.0, "UTC")
+ }),
+ ),
+ (
+ "toUnixTimestamp",
+ native_func(|vm, args| {
+ assert(!args.is_empty(), "toUnixTimestamp requires at least one argument")?;
+ let secs = temporal_seconds(vm, &args[0], "toUnixTimestamp")?;
+ Ok(HogLiteral::Number(Num::Float(secs)).into())
+ }),
+ ),
+ (
+ "toUnixTimestampMilli",
+ native_func(|vm, args| {
+ assert(!args.is_empty(), "toUnixTimestampMilli requires at least one argument")?;
+ let secs = temporal_seconds(vm, &args[0], "toUnixTimestampMilli")?;
+ Ok(HogLiteral::Number(Num::Integer((secs * 1000.0) as i64)).into())
+ }),
+ ),
+ (
+ "toTimeZone",
+ native_func(|vm, args| {
+ assert_argc(&args, 2, "toTimeZone")?;
+ let secs = temporal_seconds(vm, &args[0], "toTimeZone")?;
+ let zone: String = args[1].deref(&vm.heap)?.try_as::<str>()?.to_string();
+ make_hog_datetime(secs, &zone)
+ }),
+ ),
+ (
+ "toYear",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "toYear")?;
+ Ok(HogLiteral::Number(Num::Integer(extract_utc_field(vm, &args[0], "year", "toYear")?))
+ .into())
+ }),
+ ),
+ (
+ "toMonth",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "toMonth")?;
+ Ok(
+ HogLiteral::Number(Num::Integer(extract_utc_field(vm, &args[0], "month", "toMonth")?))
+ .into(),
+ )
+ }),
+ ),
+ (
+ "toYYYYMM",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "toYYYYMM")?;
+ let y = extract_utc_field(vm, &args[0], "year", "toYYYYMM")?;
+ let m = extract_utc_field(vm, &args[0], "month", "toYYYYMM")?;
+ Ok(HogLiteral::Number(Num::Integer(y * 100 + m)).into())
+ }),
+ ),
+ (
+ "dateTrunc",
+ native_func(|vm, args| {
+ assert_argc(&args, 2, "dateTrunc")?;
+ let unit: String = args[0].deref(&vm.heap)?.try_as::<str>()?.to_string();
+ date_trunc_impl(vm, &unit, &args[1])
+ }),
+ ),
+ (
+ "toStartOfDay",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "toStartOfDay")?;
+ date_trunc_impl(vm, "day", &args[0])
+ }),
+ ),
+ (
+ "toStartOfHour",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "toStartOfHour")?;
+ date_trunc_impl(vm, "hour", &args[0])
+ }),
+ ),
+ (
+ "toStartOfMonth",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "toStartOfMonth")?;
+ date_trunc_impl(vm, "month", &args[0])
+ }),
+ ),
+ (
+ "toStartOfWeek",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "toStartOfWeek")?;
+ let (secs, zone) = hog_datetime_parts(vm, &args[0], "toStartOfWeek")?;
+ let utc = DateTime::from_timestamp(secs.floor() as i64, 0).ok_or_else(|| {
+ VmError::NativeCallFailed("toStartOfWeek: timestamp out of range".to_string())
+ })?;
+ let n = utc.naive_utc();
+ let weekday = n.weekday().number_from_monday() as i64; // Mon=1..Sun=7
+ let start = (n.date() - chrono::Duration::days(weekday - 1))
+ .and_hms_opt(0, 0, 0)
+ .ok_or_else(|| VmError::NativeCallFailed("toStartOfWeek: bad date".to_string()))?;
+ make_hog_datetime(zone_local_timestamp(&zone, &start)?, &zone)
+ }),
+ ),
+ (
+ "toIntervalDay",
+ native_func(|vm, args| make_hog_interval(vm, &args, "day")),
+ ),
+ (
+ "toIntervalHour",
+ native_func(|vm, args| make_hog_interval(vm, &args, "hour")),
+ ),
+ (
+ "toIntervalMinute",
+ native_func(|vm, args| make_hog_interval(vm, &args, "minute")),
+ ),
+ (
+ "toIntervalMonth",
+ native_func(|vm, args| make_hog_interval(vm, &args, "month")),
+ ),
+ (
+ "dateAdd",
+ native_func(|vm, args| {
+ assert_argc(&args, 3, "dateAdd")?;
+ let unit: String = args[0].deref(&vm.heap)?.try_as::<str>()?.to_string();
+ let amount = args[1].deref(&vm.heap)?.try_as::<Num>()?.to_integer();
+ date_add_impl(vm, &unit, amount, &args[2])
+ }),
+ ),
+ (
+ "addDays",
+ native_func(|vm, args| {
+ assert_argc(&args, 2, "addDays")?;
+ let n = args[1].deref(&vm.heap)?.try_as::<Num>()?.to_integer();
+ apply_interval(vm, &args[0], "day", n)
+ }),
+ ),
+ (
+ "dateDiff",
+ native_func(|vm, args| {
+ assert_argc(&args, 3, "dateDiff")?;
+ let unit: String = args[0].deref(&vm.heap)?.try_as::<str>()?.to_string();
+ date_diff_impl(vm, &unit, &args[1], &args[2])
+ }),
+ ),
+ (
+ "formatDateTime",
+ native_func(|vm, args| {
+ if args.len() < 2 || args.len() > 3 {
+ return Err(VmError::NativeCallFailed(
+ "formatDateTime takes 2 or 3 arguments".to_string(),
+ ));
+ }
+ format_datetime_impl(vm, &args)
+ }),
+ ),
+ (
+ "isIPAddressInRange",
+ native_func(|vm, args| {
+ assert_argc(&args, 2, "isIPAddressInRange")?;
+ // Reference: `!address || !prefix => false`, so non-string (incl. null) args are false.
+ let (HogLiteral::String(address), HogLiteral::String(prefix)) =
+ (args[0].deref(&vm.heap)?, args[1].deref(&vm.heap)?)
+ else {
+ return Ok(HogLiteral::Boolean(false).into());
+ };
+ Ok(HogLiteral::Boolean(is_ip_address_in_range(address, prefix)).into())
+ }),
+ ),
+ (
+ "md5Hex",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "md5Hex")?;
+ hash_with_encoding(vm, &args, |data| Md5::digest(data).to_vec(), "hex")
+ }),
+ ),
+ (
+ "md5",
+ native_func(|vm, args| {
+ hash_optional_encoding(vm, &args, "md5", |data| Md5::digest(data).to_vec())
+ }),
+ ),
+ (
+ "sha256Hex",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "sha256Hex")?;
+ hash_with_encoding(vm, &args, |data| Sha256::digest(data).to_vec(), "hex")
+ }),
+ ),
+ (
+ "sha256",
+ native_func(|vm, args| {
+ hash_optional_encoding(vm, &args, "sha256", |data| Sha256::digest(data).to_vec())
+ }),
+ ),
+ (
+ "sha256HmacChainHex",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "sha256HmacChainHex")?;
+ let digest = sha256_hmac_chain(vm, &args[0])?;
+ Ok(HogLiteral::String(to_hex(&digest)).into())
+ }),
+ ),
+ (
+ "sha256HmacChain",
+ native_func(|vm, args| {
+ if args.is_empty() || args.len() > 2 {
+ return Err(VmError::NativeCallFailed(
+ "sha256HmacChain takes 1 or 2 arguments".to_string(),
+ ));
+ }
+ let digest = sha256_hmac_chain(vm, &args[0])?;
+ let encoding = encoding_arg(vm, &args, 1)?;
+ Ok(HogLiteral::String(encode_digest(&digest, &encoding)?).into())
+ }),
+ ),
+ (
+ "base64Encode",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "base64Encode")?;
+ let s: &str = args[0].deref(&vm.heap)?.try_as()?;
+ let out = base64::engine::general_purpose::STANDARD.encode(s.as_bytes());
+ Ok(HogLiteral::String(out).into())
+ }),
+ ),
+ (
+ "base64Decode",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "base64Decode")?;
+ let s: &str = args[0].deref(&vm.heap)?.try_as()?;
+ Ok(HogLiteral::String(base64_decode_to_string(s)?).into())
+ }),
+ ),
+ (
+ "tryBase64Decode",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "tryBase64Decode")?;
+ let s: &str = args[0].deref(&vm.heap)?.try_as()?;
+ // Reference returns "" on failure (Buffer.from never throws, but mirror the intent).
+ Ok(HogLiteral::String(base64_decode_to_string(s).unwrap_or_default()).into())
+ }),
+ ),
+ (
+ "encodeURLComponent",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "encodeURLComponent")?;
+ let s: &str = args[0].deref(&vm.heap)?.try_as()?;
+ Ok(HogLiteral::String(encode_uri_component(s)).into())
+ }),
+ ),
+ (
+ "decodeURLComponent",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "decodeURLComponent")?;
+ let s: &str = args[0].deref(&vm.heap)?.try_as()?;
+ decode_uri_component(s).map(|d| HogLiteral::String(d).into())
+ }),
+ ),
+ (
+ "tryDecodeURLComponent",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "tryDecodeURLComponent")?;
+ let s: &str = args[0].deref(&vm.heap)?.try_as()?;
+ // Reference returns null on malformed input rather than erroring.
+ Ok(match decode_uri_component(s) {
+ Ok(d) => HogLiteral::String(d).into(),
+ Err(_) => HogLiteral::Null.into(),
+ })
+ }),
+ ),
+ (
+ "toUUID",
+ native_func(|vm, args| {
+ // Reference `toUUID` is just `toString`.
+ assert_argc(&args, 1, "toUUID")?;
+ to_string(&vm.heap, &args[0], 0).map(|s| HogLiteral::String(s).into())
+ }),
+ ),
+ (
+ "generateUUIDv4",
+ native_func(|_vm, args| {
+ assert_argc(&args, 0, "generateUUIDv4")?;
+ Ok(HogLiteral::String(generate_uuid_v4()).into())
+ }),
+ ),
+ (
+ "now",
+ native_func(|vm, args| {
+ // Optional timezone arg; the value is non-deterministic (smoke-tested only).
+ if args.len() > 1 {
+ return Err(VmError::NativeCallFailed(
+ "now takes 0 or 1 arguments".to_string(),
+ ));
+ }
+ let zone = match args.first() {
+ Some(v) => match v.deref(&vm.heap)? {
+ HogLiteral::String(s) => s.clone(),
+ _ => "UTC".to_string(),
+ },
+ None => "UTC".to_string(),
+ };
+ let now = chrono::Utc::now();
+ let secs = now.timestamp() as f64 + f64::from(now.timestamp_subsec_nanos()) / 1e9;
+ make_hog_datetime(secs, &zone)
+ }),
+ ),
+ (
+ "today",
+ native_func(|_vm, args| {
+ assert_argc(&args, 0, "today")?;
+ let now = chrono::Utc::now();
+ construct_free_standing(
+ json!({ "__hogDate__": true, "year": now.year(), "month": now.month(), "day": now.day() }),
+ 0,
+ )
+ }),
+ ),
+ (
+ "HogError",
+ native_func(|vm, args| {
+ if args.len() > 3 {
+ return Err(VmError::NativeCallFailed(
+ "HogError takes 1 to 3 arguments".to_string(),
+ ));
+ }
+ let type_str = arg_string_or(vm, &args, 0, "Error")?;
+ let message = arg_string_or(vm, &args, 1, "An error occurred")?;
+ new_hog_error(vm, type_str, message, args.get(2))
+ }),
+ ),
+ (
+ "Error",
+ native_func(|vm, args| error_constructor(vm, &args, "Error")),
+ ),
+ (
+ "RetryError",
+ native_func(|vm, args| error_constructor(vm, &args, "RetryError")),
+ ),
+ (
+ "NotImplementedError",
+ native_func(|vm, args| error_constructor(vm, &args, "NotImplementedError")),
+ ),
+ // Operator-alias functions: the function forms of Hog operators. Note these are the *function*
+ // semantics, which differ slightly from the opcodes — e.g. `equals` is strict (no string
+ // coercion) whereas the `==` opcode coerces via unifyComparisonTypes.
+ (
+ "equals",
+ native_func(|vm, args| {
+ assert_argc(&args, 2, "equals")?;
+ Ok(HogLiteral::Boolean(strict_equals(vm, &args[0], &args[1])?).into())
+ }),
+ ),
+ (
+ "notEquals",
+ native_func(|vm, args| {
+ assert_argc(&args, 2, "notEquals")?;
+ Ok(HogLiteral::Boolean(!strict_equals(vm, &args[0], &args[1])?).into())
+ }),
+ ),
+ (
+ "greater",
+ native_func(|vm, args| compare_fn(vm, &args, NumOp::Gt, "greater")),
+ ),
+ (
+ "greaterOrEquals",
+ native_func(|vm, args| compare_fn(vm, &args, NumOp::Gte, "greaterOrEquals")),
+ ),
+ (
+ "less",
+ native_func(|vm, args| compare_fn(vm, &args, NumOp::Lt, "less")),
+ ),
+ (
+ "lessOrEquals",
+ native_func(|vm, args| compare_fn(vm, &args, NumOp::Lte, "lessOrEquals")),
+ ),
+ (
+ "plus",
+ native_func(|vm, args| arith_fn(vm, &args, NumOp::Add, "plus")),
+ ),
+ (
+ "minus",
+ native_func(|vm, args| arith_fn(vm, &args, NumOp::Sub, "minus")),
+ ),
+ (
+ "and",
+ native_func(|vm, args| {
+ // `args.every(Boolean)` — all operands truthy.
+ for arg in &args {
+ if !arg.deref(&vm.heap)?.truthy() {
+ return Ok(HogLiteral::Boolean(false).into());
+ }
+ }
+ Ok(HogLiteral::Boolean(true).into())
+ }),
+ ),
+ (
+ "or",
+ native_func(|vm, args| {
+ // `args.some(Boolean)` — any operand truthy.
+ for arg in &args {
+ if arg.deref(&vm.heap)?.truthy() {
+ return Ok(HogLiteral::Boolean(true).into());
+ }
+ }
+ Ok(HogLiteral::Boolean(false).into())
+ }),
+ ),
+ (
+ "not",
+ native_func(|vm, args| {
+ assert_argc(&args, 1, "not")?;
+ Ok(HogLiteral::Boolean(!args[0].deref(&vm.heap)?.truthy()).into())
+ }),
+ ),
+ (
+ "if",
+ native_func(|vm, args| {
+ assert_argc(&args, 3, "if")?;
+ if args[0].deref(&vm.heap)?.truthy() {
+ Ok(args[1].clone())
+ } else {
+ Ok(args[2].clone())
+ }
+ }),
+ ),
+ (
+ "multiIf",
+ native_func(|vm, args| {
+ // multiIf(cond1, val1, cond2, val2, ..., default).
+ if args.is_empty() {
+ return Err(VmError::NativeCallFailed(
+ "multiIf requires at least one argument".to_string(),
+ ));
+ }
+ let default = args.last().unwrap();
+ let pairs = &args[..args.len() - 1];
+ let mut i = 0;
+ while i + 1 < pairs.len() {
+ if pairs[i].deref(&vm.heap)?.truthy() {
+ return Ok(pairs[i + 1].clone());
+ }
+ i += 2;
+ }
+ Ok(default.clone())
+ }),
+ ),
+ (
+ "in",
+ native_func(|vm, args| {
+ // `in(val, arr)` — array/tuple membership only (the function form, like `has`).
+ assert_argc(&args, 2, "in")?;
+ let needle = &args[0];
+ match args[1].deref(&vm.heap)? {
+ HogLiteral::Array(vals) | HogLiteral::Tuple(vals) => {
+ for val in vals.iter() {
+ if *needle.equals(val, &vm.heap)?.try_as()? {
+ return Ok(HogLiteral::Boolean(true).into());
+ }
+ }
+ Ok(HogLiteral::Boolean(false).into())
+ }
+ _ => Ok(HogLiteral::Boolean(false).into()),
+ }
+ }),
+ ),
+ ]
+ .into_iter()
+ .map(|(name, func)| (name.to_string(), func))
+ .collect()
+}
+
+pub fn hog_stl() -> Module {
+ let funcs = json!({
+ "arrayCount": [2, [33, 0, 36, 1, 36, 3, 2, "values", 1, 33, 1, 36, 4, 2, "length", 1, 31, 36, 6, 36, 5, 16, 40, 31, 36, 4, 36, 5, 45, 37, 7, 36, 7, 36, 0, 54, 1, 40, 7, 33, 1, 36, 2, 6, 37, 2, 36, 5, 33, 1, 6, 37, 5, 39, -38, 35, 35, 35, 35, 35, 36, 2, 38, 35]],
+ "arrayExists": [2, [36, 1, 36, 2, 2, "values", 1, 33, 1, 36, 3, 2, "length", 1, 31, 36, 5, 36, 4, 16, 40, 26, 36, 3, 36, 4, 45, 37, 6, 36, 6, 36, 0, 54, 1, 40, 2, 29, 38, 36, 4, 33, 1, 6, 37, 4, 39, -33, 35, 35, 35, 35, 35, 30, 38]],
+ "arrayFilter": [2, [43, 0, 36, 1, 36, 3, 2, "values", 1, 33, 1, 36, 4, 2, "length", 1, 31, 36, 6, 36, 5, 16, 40, 33, 36, 4, 36, 5, 45, 37, 7, 36, 7, 36, 0, 54, 1, 40, 9, 36, 2, 36, 7, 2, "arrayPushBack", 2, 37, 2, 36, 5, 33, 1, 6, 37, 5, 39, -40, 35, 35, 35, 35, 35, 36, 2, 38, 35]],
+ "arrayMap": [2, [43, 0, 36, 1, 36, 3, 2, "values", 1, 33, 1, 36, 4, 2, "length", 1, 31, 36, 6, 36, 5, 16, 40, 29, 36, 4, 36, 5, 45, 37, 7, 36, 2, 36, 7, 36, 0, 54, 1, 2, "arrayPushBack", 2, 37, 2, 36, 5, 33, 1, 6, 37, 5, 39, -36, 35, 35, 35, 35, 35, 36, 2, 38, 35]],
+ "arrayReduce": [3, [36, 2, 36, 1, 36, 4, 2, "values", 1, 33, 1, 36, 5, 2, "length", 1, 31, 36, 7, 36, 6, 16, 40, 26, 36, 5, 36, 6, 45, 37, 8, 36, 3, 36, 8, 36, 0, 54, 2, 37, 3, 36, 6, 33, 1, 6, 37, 6, 39, -33, 35, 35, 35, 35, 35, 36, 3, 38, 35]],
+ "sortableSemver": [1, [31, 36, 0, 11, 40, 3, 43, 0, 38, 36, 0, 32, "(\\d+(\\.\\d+)+)", 2, "extractRegex", 2, 36, 1, 2, "empty", 1, 40, 3, 43, 0, 38, 32, ".", 36, 1, 2, "splitByString", 2, 52, "lambda", 1, 0, 11, 36, 0, 2, "toInt", 1, 47, 3, 35, 33, 0, 38, 53, 0, 36, 2, 2, "arrayMap", 2, 38, 35, 35]],
+ });
+
+ let funcs: HashMap<String, (usize, Vec<JsonValue>)> =
+ serde_json::from_value(funcs).expect("All stl functions are valid");
+ let mut res = Module::new();
+ for (name, (arg_count, bytecode)) in funcs {
+ let func = ExportedFunction::new(arg_count, bytecode);
+ res.add_function(name, func);
+ }
+ res
+}
+
+// TODO - this is slow, because rather than using a string buffer, we're allocating a new string each time
+// we recurse
+// `toString` semantics (reference `STLToString`): a top-level Hog date renders as `YYYY-MM-DD` and a
+// top-level Hog datetime as an ISO 8601 string; every other value (including nested temporals inside
+// containers) goes through the canonical printer, which raw-prints a top-level string but quotes
+// strings nested in arrays/objects. The `depth` arg is retained for call-site compatibility.
+fn to_string(heap: &VmHeap, val: &HogValue, _depth: usize) -> Result<String, VmError> {
+ if let HogLiteral::Object(obj) = val.deref(heap)? {
+ if obj_marker(heap, obj, "__hogDate__")? {
+ let year = obj_number(heap, obj, "year")?.unwrap_or(0.0) as i64;
+ let month = obj_number(heap, obj, "month")?.unwrap_or(0.0) as i64;
+ let day = obj_number(heap, obj, "day")?.unwrap_or(0.0) as i64;
+ return Ok(format!("{year}-{month:02}-{day:02}"));
+ }
+ if obj_marker(heap, obj, "__hogDateTime__")? {
+ return hog_datetime_to_iso(heap, obj);
+ }
+ }
+ print_hog_string_output(heap, val)
+}
+
+// Render a Hog datetime as Luxon's `DateTime.fromSeconds(dt, {zone}).toISO()` does: millisecond
+// precision, `Z` for UTC and a `+HH:MM` offset otherwise.
+fn hog_datetime_to_iso(heap: &VmHeap, obj: &IndexMap<String, HogValue>) -> Result<String, VmError> {
+ let dt = obj_number(heap, obj, "dt")?.unwrap_or(0.0);
+ let zone = obj_string(heap, obj, "zone")?.unwrap_or_else(|| "UTC".to_string());
+ // Luxon keeps millisecond precision; round to whole millis first to avoid float drift turning
+ // e.g. .123 into .122 when splitting seconds and sub-second nanos.
+ let total_millis = (dt * 1000.0).round() as i64;
+ let secs = total_millis.div_euclid(1000);
+ let nanos = (total_millis.rem_euclid(1000) * 1_000_000) as u32;
+ let utc = DateTime::from_timestamp(secs, nanos).ok_or_else(|| {
+ VmError::NativeCallFailed(format!("toString: datetime {dt} out of range"))
+ })?;
+ let formatted = if zone == "UTC" {
+ utc.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string()
+ } else {
+ let tz: chrono_tz::Tz = zone
+ .parse()
+ .map_err(|_| VmError::NativeCallFailed(format!("unknown timezone {zone}")))?;
+ utc.with_timezone(&tz)
+ .format("%Y-%m-%dT%H:%M:%S%.3f%:z")
+ .to_string()
+ };
+ Ok(formatted)
+}
+
+fn obj_marker(heap: &VmHeap, obj: &IndexMap<String, HogValue>, key: &str) -> Result<bool, VmError> {
+ match obj.get(key) {
+ Some(v) => Ok(matches!(v.deref(heap)?, HogLiteral::Boolean(true))),
+ None => Ok(false),
+ }
+}
+
+fn obj_number(
+ heap: &VmHeap,
+ obj: &IndexMap<String, HogValue>,
+ key: &str,
+) -> Result<Option<f64>, VmError> {
+ match obj.get(key) {
+ Some(v) => Ok(match v.deref(heap)? {
+ HogLiteral::Number(n) => Some(n.to_float()),
+ _ => None,
+ }),
+ None => Ok(None),
+ }
+}
+
+fn obj_string(
+ heap: &VmHeap,
+ obj: &IndexMap<String, HogValue>,
+ key: &str,
+) -> Result<Option<String>, VmError> {
+ match obj.get(key) {
+ Some(v) => Ok(match v.deref(heap)? {
+ HogLiteral::String(s) => Some(s.clone()),
+ _ => None,
+ }),
+ None => Ok(None),
+ }
+}
+
+// Whole days from the Unix epoch to a Hog date (reference: `day.diff(epoch, 'days').days` floored).
+fn hog_date_epoch_days(heap: &VmHeap, obj: &IndexMap<String, HogValue>) -> Result<i64, VmError> {
+ let year = obj_number(heap, obj, "year")?.unwrap_or(0.0) as i32;
+ let month = obj_number(heap, obj, "month")?.unwrap_or(0.0) as u32;
+ let day = obj_number(heap, obj, "day")?.unwrap_or(0.0) as u32;
+ let date = NaiveDate::from_ymd_opt(year, month, day)
+ .ok_or_else(|| VmError::NativeCallFailed(format!("invalid date {year}-{month}-{day}")))?;
+ let epoch = NaiveDate::from_ymd_opt(1970, 1, 1).expect("epoch is valid");
+ Ok(date.signed_duration_since(epoch).num_days())
+}
+
+/// `toDateTime(input[, zone])` → a Hog DateTime object `{ __hogDateTime__: true, dt, zone }`.
+///
+/// To match ClickHouse (the parity oracle), this VM orders Hog temporals by `dt` seconds
+/// ([`crate::values::compare_values`]) — the reference Python/TS HogVMs cannot order them, so their
+/// `is_date_before`/`is_date_after` always return `false`. Naive strings parse as UTC (or `zone` for
+/// the 2-arg form), not the process-local timezone; an explicit offset/`Z` is honored as written.
+fn to_datetime(vm: &HogVM, args: Vec<HogValue>) -> Result<HogValue, VmError> {
+ if args.is_empty() || args.len() > 2 {
+ return Err(VmError::NativeCallFailed(
+ "toDateTime takes 1 or 2 arguments".to_string(),
+ ));
+ }
+ let zone = match args.get(1) {
+ Some(arg) => Some(arg.deref(&vm.heap)?.try_as::<str>()?.to_string()),
+ None => None,
+ };
+ let zone = zone.as_deref();
+ let dt_seconds = match args[0].deref(&vm.heap)? {
+ HogLiteral::Number(n) => n.to_float(),
+ HogLiteral::String(s) => parse_datetime_to_seconds(s, zone)?,
+ other => {
+ return Err(VmError::NativeCallFailed(format!(
+ "toDateTime expects a number or string, got {}",
+ other.type_name()
+ )))
+ }
+ };
+ construct_free_standing(
+ json!({ "__hogDateTime__": true, "dt": dt_seconds, "zone": zone.unwrap_or("UTC") }),
+ 0,
+ )
+}
+
+/// `toDate(input)` → a Hog Date object `{ __hogDate__: true, year, month, day }` in UTC.
+fn to_date(vm: &HogVM, args: Vec<HogValue>) -> Result<HogValue, VmError> {
+ assert_argc(&args, 1, "toDate")?;
+ let seconds = match args[0].deref(&vm.heap)? {
+ HogLiteral::Number(n) => n.to_float(),
+ HogLiteral::String(s) => parse_datetime_to_seconds(s, None)?,
+ other => {
+ return Err(VmError::NativeCallFailed(format!(
+ "toDate expects a number or string, got {}",
+ other.type_name()
+ )))
+ }
+ };
+ let dt = DateTime::from_timestamp(seconds as i64, 0).ok_or_else(|| {
+ VmError::NativeCallFailed(format!("toDate: timestamp {seconds} out of range"))
+ })?;
+ construct_free_standing(
+ json!({ "__hogDate__": true, "year": dt.year(), "month": dt.month(), "day": dt.day() }),
+ 0,
+ )
+}
+
+const NAIVE_DATETIME_FORMATS: [&str; 2] = ["%Y-%m-%d %H:%M:%S%.f", "%Y-%m-%dT%H:%M:%S%.f"];
+
+fn parse_datetime_to_seconds(input: &str, zone: Option<&str>) -> Result<f64, VmError> {
+ let input = input.trim();
+ // An explicit offset/`Z` pins the absolute instant regardless of `zone`.
+ if let Ok(dt) = DateTime::parse_from_rfc3339(input) {
+ return Ok(datetime_to_seconds(dt));
+ }
+ for fmt in NAIVE_DATETIME_FORMATS {
+ if let Ok(naive) = NaiveDateTime::parse_from_str(input, fmt) {
+ return naive_to_seconds(naive, zone);
+ }
+ }
+ if let Some(naive) = NaiveDate::parse_from_str(input, "%Y-%m-%d")
+ .ok()
+ .and_then(|date| date.and_hms_opt(0, 0, 0))
+ {
+ return naive_to_seconds(naive, zone);
+ }
+ // A bare numeric string is unix seconds (e.g. an upstream `toString(<number>)`).
+ if let Ok(seconds) = input.parse::<f64>() {
+ return Ok(seconds);
+ }
+ Err(VmError::NativeCallFailed(format!(
+ "toDateTime could not parse {input:?}"
+ )))
+}
+
+fn naive_to_seconds(naive: NaiveDateTime, zone: Option<&str>) -> Result<f64, VmError> {
+ let Some(zone) = zone else {
+ return Ok(datetime_to_seconds(naive.and_utc()));
+ };
+ let tz: chrono_tz::Tz = zone
+ .parse()
+ .map_err(|_| VmError::NativeCallFailed(format!("toDateTime: unknown timezone {zone:?}")))?;
+ match tz.from_local_datetime(&naive) {
+ // DST fold: ClickHouse resolves to a single instant; take the earlier one.
+ LocalResult::Single(dt) | LocalResult::Ambiguous(dt, _) => Ok(datetime_to_seconds(dt)),
+ LocalResult::None => Err(VmError::NativeCallFailed(format!(
+ "toDateTime: {naive} does not exist in {zone}"
+ ))),
+ }
+}
+
+/// `f64` epoch seconds with sub-second precision, matching Python's `datetime.timestamp()`.
+fn datetime_to_seconds<Tz: TimeZone>(dt: DateTime<Tz>) -> f64 {
+ dt.timestamp() as f64 + f64::from(dt.timestamp_subsec_nanos()) / 1_000_000_000.0
+}
+
+// Extract every element as a Num and return them sorted ascending. Single allocation + early error,
+// rather than partitioning into (oks, errs) Vecs and unwrapping — the old path allocated several
+// intermediate Vecs per call, which showed up under profiling for sort-heavy workloads.
+fn collect_sorted_nums(heap: &VmHeap, arr: &[HogValue], name: &str) -> Result<Vec<Num>, VmError> {
+ let mut nums = Vec::with_capacity(arr.len());
+ for v in arr {
+ let n = v.deref(heap)?.try_as::<Num>().map_err(|_| {
+ VmError::NativeCallFailed(format!("{name}() only supports arrays of numbers"))
+ })?;
+ nums.push(n.clone());
+ }
+ nums.sort_unstable_by(|a, b| a.compare(b));
+ Ok(nums)
+}
+
+// Order-preserving JSON -> HogValue deserialization (serde_json's Deserializer yields map entries
+// in document order; collecting into IndexMap keeps it, unlike serde_json::Value's sorted BTreeMap).
+struct HogJson(HogValue);
+
+impl<'de> serde::Deserialize<'de> for HogJson {
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ deserializer
+ .deserialize_any(HogJsonVisitor)
+ .map(|lit| HogJson(lit.into()))
+ }
+}
+
+struct HogJsonVisitor;
+
+impl<'de> Visitor<'de> for HogJsonVisitor {
+ type Value = HogLiteral;
+
+ fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ f.write_str("a JSON value")
+ }
+
+ fn visit_bool<E>(self, v: bool) -> Result<HogLiteral, E> {
+ Ok(HogLiteral::Boolean(v))
+ }
+ fn visit_i64<E>(self, v: i64) -> Result<HogLiteral, E> {
+ Ok(HogLiteral::Number(Num::Integer(v)))
+ }
+ fn visit_u64<E>(self, v: u64) -> Result<HogLiteral, E> {
+ Ok(HogLiteral::Number(Num::Integer(v as i64)))
+ }
+ fn visit_f64<E>(self, v: f64) -> Result<HogLiteral, E> {
+ Ok(HogLiteral::Number(Num::Float(v)))
+ }
+ fn visit_str<E>(self, v: &str) -> Result<HogLiteral, E> {
+ Ok(HogLiteral::String(v.to_string()))
+ }
+ fn visit_string<E>(self, v: String) -> Result<HogLiteral, E> {
+ Ok(HogLiteral::String(v))
+ }
+ fn visit_none<E>(self) -> Result<HogLiteral, E> {
+ Ok(HogLiteral::Null)
+ }
+ fn visit_unit<E>(self) -> Result<HogLiteral, E> {
+ Ok(HogLiteral::Null)
+ }
+ fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<HogLiteral, A::Error> {
+ let mut vals = Vec::new();
+ while let Some(HogJson(v)) = seq.next_element()? {
+ vals.push(v);
+ }
+ Ok(HogLiteral::Array(vals))
+ }
+ fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<HogLiteral, A::Error> {
+ let mut obj = IndexMap::new();
+ while let Some((k, HogJson(v))) = map.next_entry::<String, HogJson>()? {
+ obj.insert(k, v);
+ }
+ Ok(HogLiteral::Object(obj))
+ }
+}
+
+// Serialize a HogValue to a JSON string matching Python's `json.dumps` default: `, ` / `: `
+// separators (not serde's compact form), object keys in insertion order (IndexMap), and
+// self-referential containers rendered as `null` (cycle detection via `marked`).
+fn json_stringify(
+ heap: &VmHeap,
+ value: &HogValue,
+ marked: &mut Vec<HeapReference>,
+ depth: usize,
+) -> Result<String, VmError> {
+ if depth > MAX_JSON_SERDE_DEPTH {
+ return Ok("null".to_string());
+ }
+ let lit = value.deref(heap)?;
+ let container_ptr = match value {
+ HogValue::Ref(ptr) if matches!(lit, HogLiteral::Array(_) | HogLiteral::Object(_)) => {
+ Some(*ptr)
+ }
+ _ => None,
+ };
+ if let Some(ptr) = container_ptr {
+ if marked.contains(&ptr) {
+ return Ok("null".to_string());
+ }
+ marked.push(ptr);
+ }
+
+ let escape = |s: &str| -> Result<String, VmError> {
+ serde_json::to_string(s).map_err(|e| VmError::NativeCallFailed(e.to_string()))
+ };
+ let result = (|| match lit {
+ HogLiteral::Null => Ok("null".to_string()),
+ HogLiteral::Boolean(b) => Ok(if *b { "true" } else { "false" }.to_string()),
+ HogLiteral::Number(n) => Ok(if n.is_float() {
+ // Debug formatting keeps the decimal point (2.0 -> "2.0"), matching Python's repr.
+ format!("{:?}", n.to_float())
+ } else {
+ n.to_integer().to_string()
+ }),
+ HogLiteral::String(s) => escape(s),
+ // Tuples serialize as JSON arrays, same as arrays.
+ HogLiteral::Array(arr) | HogLiteral::Tuple(arr) => {
+ let mut parts = Vec::with_capacity(arr.len());
+ for v in arr {
+ parts.push(json_stringify(heap, v, marked, depth + 1)?);
+ }
+ Ok(format!("[{}]", parts.join(", ")))
+ }
+ HogLiteral::Object(map) => {
+ let mut parts = Vec::with_capacity(map.len());
+ for (k, v) in map {
+ parts.push(format!(
+ "{}: {}",
+ escape(k)?,
+ json_stringify(heap, v, marked, depth + 1)?
+ ));
+ }
+ Ok(format!("{{{}}}", parts.join(", ")))
+ }
+ // Callables/closures serialize as the quoted `fn<name(argCount)>` string, like the reference.
+ HogLiteral::Callable(_) | HogLiteral::Closure(_) => {
+ escape(&print_hog_string_output(heap, value)?)
+ }
+ })();
+
+ if container_ptr.is_some() {
+ marked.pop();
+ }
+ result
+}
+
+// Shared by the JSON-extract family: parse args[0] (a JSON string, or convert a Hog value) and
+// navigate args[1..] as a path. A parse error or a bad path is nullish (None), matching the
+// reference's JSONDecodeError / nullish get_nested_value handling.
+fn json_path_value(vm: &HogVM, args: &[HogValue]) -> Result<Option<JsonValue>, VmError> {
+ let json = match args[0].deref(&vm.heap)? {
+ HogLiteral::String(s) => match serde_json::from_str::<JsonValue>(s) {
+ Ok(j) => j,
+ Err(_) => return Ok(None),
+ },
+ _ => vm.hog_to_json(&args[0])?,
+ };
+ let path = &args[1..];
+ if path.is_empty() {
+ return Ok(Some(json));
+ }
+ Ok(get_json_nested(&json, path, vm).unwrap_or(None).cloned())
+}
+
+// position(haystack, needle): 1-based char index of str(needle) in haystack, or 0 if absent (or
+// haystack isn't a string). The case-insensitive variant lowercases both first.
+// SQL LIKE matching (like/ilike/notLike/notILike). The reference escapes regex specials in the
+// pattern, maps `%`→`.*` and `_`→`.`, then does an *unanchored* match (`.test()`), so a pattern
+// without wildcards matches as a substring.
+fn like_impl(
+ vm: &HogVM,
+ args: &[HogValue],
+ name: &str,
+ case_insensitive: bool,
+ negate: bool,
+) -> Result<HogValue, VmError> {
+ assert_argc(args, 2, name)?;
+ let string: &str = args[0].deref(&vm.heap)?.try_as()?;
+ let pattern: &str = args[1].deref(&vm.heap)?.try_as()?;
+ let regex = like_to_regex(pattern);
+ let matched = regex_match(string, &regex, !case_insensitive)?;
+ Ok(HogLiteral::Boolean(matched ^ negate).into())
+}
+
+fn like_to_regex(pattern: &str) -> String {
+ let mut out = String::with_capacity(pattern.len() * 2);
+ for c in pattern.chars() {
+ match c {
+ '-' | '/' | '\\' | '^' | '$' | '*' | '+' | '?' | '.' | '(' | ')' | '|' | '[' | ']'
+ | '{' | '}' => {
+ out.push('\\');
+ out.push(c);
+ }
+ '%' => out.push_str(".*"),
+ '_' => out.push('.'),
+ other => out.push(other),
+ }
+ }
+ out
+}
+
+fn position_impl(
+ vm: &HogVM,
+ haystack: &HogValue,
+ needle: &HogValue,
+ ci: bool,
+) -> Result<i64, VmError> {
+ let s = match haystack.deref(&vm.heap)? {
+ HogLiteral::String(s) => s.clone(),
+ _ => return Ok(0),
+ };
+ let n = to_string(&vm.heap, needle, 0)?; // str(needle)
+ let (s, n) = if ci {
+ (s.to_lowercase(), n.to_lowercase())
+ } else {
+ (s, n)
+ };
+ match s.find(&n) {
+ Some(byte_idx) => Ok(s[..byte_idx].chars().count() as i64 + 1),
+ None => Ok(0),
+ }
+}
+
+enum TrimSide {
+ Both,
+ Left,
+ Right,
+}
+
+// trim/trimLeft/trimRight: 1 arg strips whitespace; 2nd arg strips a single char (a non-string
+// 2nd arg defaults to space, a multi-char string yields "") — matching the reference.
+fn trim_impl(vm: &HogVM, args: Vec<HogValue>, side: TrimSide) -> Result<HogValue, VmError> {
+ if args.is_empty() || args.len() > 2 {
+ return Err(VmError::NativeCallFailed(
+ "trim takes 1 or 2 arguments".to_string(),
+ ));
+ }
+ let s: &str = args[0].deref(&vm.heap)?.try_as()?;
+ let result = if args.len() == 2 {
+ let chars: Vec<char> = match args[1].deref(&vm.heap)? {
+ HogLiteral::String(c) => c.chars().collect(),
+ _ => vec![' '],
+ };
+ if chars.len() > 1 {
+ String::new()
+ } else {
+ let pat = |x: char| chars.contains(&x);
+ match side {
+ TrimSide::Both => s.trim_matches(pat).to_string(),
+ TrimSide::Left => s.trim_start_matches(pat).to_string(),
+ TrimSide::Right => s.trim_end_matches(pat).to_string(),
+ }
+ }
+ } else {
+ match side {
+ TrimSide::Both => s.trim().to_string(),
+ TrimSide::Left => s.trim_start().to_string(),
+ TrimSide::Right => s.trim_end().to_string(),
+ }
+ };
+ Ok(HogLiteral::String(result).into())
+}
+
+fn make_hog_datetime(dt: f64, zone: &str) -> Result<HogValue, VmError> {
+ construct_free_standing(
+ json!({ "__hogDateTime__": true, "dt": dt, "zone": zone }),
+ 0,
+ )
+}
+
+// Epoch seconds of a Hog Date/DateTime value (the `dt` field, or UTC midnight for a Date).
+fn temporal_seconds(vm: &HogVM, value: &HogValue, name: &str) -> Result<f64, VmError> {
+ value
+ .deref(&vm.heap)?
+ .as_temporal_seconds(&vm.heap)
+ .ok_or_else(|| VmError::NativeCallFailed(format!("{name} expects a Date or DateTime")))
+}
+
+// (epoch seconds, zone string) of a Hog DateTime; zone defaults to UTC (Hog Dates carry no zone).
+fn hog_datetime_parts(vm: &HogVM, value: &HogValue, name: &str) -> Result<(f64, String), VmError> {
+ let lit = value.deref(&vm.heap)?;
+ let secs = lit
+ .as_temporal_seconds(&vm.heap)
+ .ok_or_else(|| VmError::NativeCallFailed(format!("{name} expects a DateTime")))?;
+ let zone = match lit {
+ HogLiteral::Object(map) => match map.get("zone").map(|z| z.deref(&vm.heap)) {
+ Some(Ok(HogLiteral::String(s))) => s.clone(),
+ _ => "UTC".to_string(),
+ },
+ _ => "UTC".to_string(),
+ };
+ Ok((secs, zone))
+}
+
+// The reference reads the UTC wall-clock of `dt` (its localize is a no-op re-label), so year/month
+// are the UTC fields of the instant.
+fn extract_utc_field(
+ vm: &HogVM,
+ value: &HogValue,
+ field: &str,
+ name: &str,
+) -> Result<i64, VmError> {
+ let secs = temporal_seconds(vm, value, name)?;
+ let utc = DateTime::from_timestamp(secs.floor() as i64, 0)
+ .ok_or_else(|| VmError::NativeCallFailed(format!("{name}: timestamp out of range")))?;
+ Ok(match field {
+ "year" => utc.year() as i64,
+ "month" => utc.month() as i64,
+ "day" => utc.day() as i64,
+ "hour" => utc.hour() as i64,
+ "minute" => utc.minute() as i64,
+ "second" => utc.second() as i64,
+ _ => 0,
+ })
+}
+
+// dateTrunc: truncate the UTC wall-clock to the unit, then re-interpret in the value's zone.
+fn date_trunc_impl(vm: &HogVM, unit: &str, value: &HogValue) -> Result<HogValue, VmError> {
+ let (secs, zone) = hog_datetime_parts(vm, value, "dateTrunc")?;
+ let utc = DateTime::from_timestamp(secs.floor() as i64, 0).ok_or_else(|| {
+ VmError::NativeCallFailed("dateTrunc: timestamp out of range".to_string())
+ })?;
+ let n = utc.naive_utc();
+ let truncated = match unit {
+ "year" => NaiveDate::from_ymd_opt(n.year(), 1, 1).and_then(|d| d.and_hms_opt(0, 0, 0)),
+ "month" => {
+ NaiveDate::from_ymd_opt(n.year(), n.month(), 1).and_then(|d| d.and_hms_opt(0, 0, 0))
+ }
+ "day" => n.date().and_hms_opt(0, 0, 0),
+ "hour" => n.date().and_hms_opt(n.hour(), 0, 0),
+ "minute" => n.date().and_hms_opt(n.hour(), n.minute(), 0),
+ _ => {
+ return Err(VmError::NativeCallFailed(format!(
+ "Unsupported unit for dateTrunc: {unit}"
+ )))
+ }
+ }
+ .ok_or_else(|| VmError::NativeCallFailed("dateTrunc: invalid date".to_string()))?;
+
+ let tz: chrono_tz::Tz = zone
+ .parse()
+ .map_err(|_| VmError::NativeCallFailed(format!("dateTrunc: unknown timezone {zone}")))?;
+ let new_secs = match tz.from_local_datetime(&truncated) {
+ LocalResult::Single(dt) | LocalResult::Ambiguous(dt, _) => dt.timestamp() as f64,
+ LocalResult::None => {
+ return Err(VmError::NativeCallFailed(
+ "dateTrunc: local time does not exist".to_string(),
+ ))
+ }
+ };
+ make_hog_datetime(new_secs, &zone)
+}
+
+// Epoch seconds of a naive wall-clock interpreted in `zone`.
+fn zone_local_timestamp(zone: &str, naive: &NaiveDateTime) -> Result<f64, VmError> {
+ let tz: chrono_tz::Tz = zone
+ .parse()
+ .map_err(|_| VmError::NativeCallFailed(format!("unknown timezone {zone}")))?;
+ match tz.from_local_datetime(naive) {
+ LocalResult::Single(dt) | LocalResult::Ambiguous(dt, _) => Ok(dt.timestamp() as f64),
+ LocalResult::None => Err(VmError::NativeCallFailed(
+ "local time does not exist".to_string(),
+ )),
+ }
+}
+
+// {__hogInterval__: true, value, unit} built directly so keys stay in insertion order when printed.
+fn make_hog_interval(vm: &HogVM, args: &[HogValue], unit: &str) -> Result<HogValue, VmError> {
+ assert_argc(args, 1, "toInterval")?;
+ let n = args[0].deref(&vm.heap)?.try_as::<Num>()?.clone();
+ let mut map = IndexMap::new();
+ map.insert(
+ "__hogInterval__".to_string(),
+ HogLiteral::Boolean(true).into(),
+ );
+ map.insert("value".to_string(), HogLiteral::Number(n).into());
+ map.insert(
+ "unit".to_string(),
+ HogLiteral::String(unit.to_string()).into(),
+ );
+ Ok(HogLiteral::Object(map).into())
+}
+
+// Add an interval to a DateTime. day/hour/minute/second are absolute durations; month is wall-clock
+// field math (clamping the day) re-interpreted in the value's zone.
+fn apply_interval(
+ vm: &HogVM,
+ dt_value: &HogValue,
+ unit: &str,
+ value: i64,
+) -> Result<HogValue, VmError> {
+ // Adding an interval to a Date yields a Date; to a DateTime yields a DateTime (reference
+ // applyIntervalToDateTime). We do the arithmetic in epoch seconds either way, then re-wrap.
+ let is_date = match dt_value.deref(&vm.heap)? {
+ HogLiteral::Object(obj) => obj_marker(&vm.heap, obj, "__hogDate__")?,
+ _ => false,
+ };
+ let (secs, zone) = hog_datetime_parts(vm, dt_value, "dateAdd")?;
+ let new_secs = match unit {
+ "day" => secs + (value as f64) * 86400.0,
+ "hour" => secs + (value as f64) * 3600.0,
+ "minute" => secs + (value as f64) * 60.0,
+ "second" => secs + value as f64,
+ "month" => {
+ let utc = DateTime::from_timestamp(secs.floor() as i64, 0).ok_or_else(|| {
+ VmError::NativeCallFailed("dateAdd: timestamp out of range".to_string())
+ })?;
+ let n = utc.naive_utc();
+ let total = (n.year() as i64) * 12 + (n.month() as i64 - 1) + value;
+ let new_year = total.div_euclid(12) as i32;
+ let new_month = (total.rem_euclid(12) + 1) as u32;
+ let mut day = n.day();
+ let truncated = loop {
+ if let Some(d) = NaiveDate::from_ymd_opt(new_year, new_month, day)
+ .and_then(|d| d.and_hms_opt(n.hour(), n.minute(), n.second()))
+ {
+ break d;
+ }
+ if day <= 1 {
+ return Err(VmError::NativeCallFailed(
+ "dateAdd: invalid date".to_string(),
+ ));
+ }
+ day -= 1;
+ };
+ zone_local_timestamp(&zone, &truncated)?
+ }
+ _ => {
+ return Err(VmError::NativeCallFailed(format!(
+ "Unknown interval unit {unit}"
+ )))
+ }
+ };
+ if is_date {
+ let utc = DateTime::from_timestamp(new_secs.floor() as i64, 0).ok_or_else(|| {
+ VmError::NativeCallFailed("dateAdd: timestamp out of range".to_string())
+ })?;
+ return construct_free_standing(
+ json!({ "__hogDate__": true, "year": utc.year(), "month": utc.month(), "day": utc.day() }),
+ 0,
+ );
+ }
+ make_hog_datetime(new_secs, &zone)
+}
+
+fn date_add_impl(
+ vm: &HogVM,
+ unit: &str,
+ amount: i64,
+ dt_value: &HogValue,
+) -> Result<HogValue, VmError> {
+ let (unit, amount) = match unit {
+ "day" | "hour" | "minute" | "second" | "month" => (unit, amount),
+ "week" => ("day", amount * 7),
+ "year" => ("month", amount * 12),
+ _ => {
+ return Err(VmError::NativeCallFailed(format!(
+ "Unsupported interval unit: {unit}"
+ )))
+ }
+ };
+ apply_interval(vm, dt_value, unit, amount)
+}
+
+fn date_diff_impl(
+ vm: &HogVM,
+ unit: &str,
+ start_v: &HogValue,
+ end_v: &HogValue,
+) -> Result<HogValue, VmError> {
+ let start = temporal_seconds(vm, start_v, "dateDiff")?;
+ let end = temporal_seconds(vm, end_v, "dateDiff")?;
+ let diff = end - start;
+ let utc_year_month = |secs: f64| -> Result<(i64, i64), VmError> {
+ let dt = DateTime::from_timestamp(secs.floor() as i64, 0).ok_or_else(|| {
+ VmError::NativeCallFailed("dateDiff: timestamp out of range".to_string())
+ })?;
+ Ok((dt.year() as i64, dt.month() as i64))
+ };
+ let result = match unit {
+ "day" => (diff / 86400.0).floor() as i64,
+ "hour" => (diff / 3600.0).floor() as i64,
+ "minute" => (diff / 60.0).floor() as i64,
+ "second" => diff as i64,
+ "week" => ((diff / 86400.0).floor() as i64) / 7,
+ "month" => {
+ let (sy, sm) = utc_year_month(start)?;
+ let (ey, em) = utc_year_month(end)?;
+ (ey * 12 + em) - (sy * 12 + sm)
+ }
+ "year" => utc_year_month(end)?.0 - utc_year_month(start)?.0,
+ _ => {
+ return Err(VmError::NativeCallFailed(format!(
+ "Unsupported unit for dateDiff: {unit}"
+ )))
+ }
+ };
+ Ok(HogLiteral::Number(Num::Integer(result)).into())
+}
+
+fn format_datetime_impl(vm: &HogVM, args: &[HogValue]) -> Result<HogValue, VmError> {
+ let (secs, dt_zone) = hog_datetime_parts(vm, &args[0], "formatDateTime")?;
+ let format: String = args[1].deref(&vm.heap)?.try_as::<str>()?.to_string();
+ let zone = if args.len() > 2 {
+ args[2].deref(&vm.heap)?.try_as::<str>()?.to_string()
+ } else {
+ dt_zone
+ };
+ let translated = translate_clickhouse_format(&format);
+ let tz: chrono_tz::Tz = zone.parse().map_err(|_| {
+ VmError::NativeCallFailed(format!("formatDateTime: unknown timezone {zone}"))
+ })?;
+ let dt = match tz.timestamp_opt(secs.floor() as i64, 0) {
+ LocalResult::Single(dt) | LocalResult::Ambiguous(dt, _) => dt,
+ LocalResult::None => {
+ return Err(VmError::NativeCallFailed(
+ "formatDateTime: invalid timestamp".to_string(),
+ ))
+ }
+ };
+ Ok(HogLiteral::String(dt.format(&translated).to_string()).into())
+}
+
+// Translate the reference's ClickHouse-style format tokens (% + token) to chrono strftime codes.
+fn translate_clickhouse_format(format: &str) -> String {
+ let chars: Vec<char> = format.chars().collect();
+ let mut out = String::new();
+ let mut i = 0;
+ while i < chars.len() {
+ if chars[i] == '%' && i + 1 < chars.len() {
+ i += 1;
+ out.push_str(translate_format_token(chars[i]));
+ } else {
+ out.push(chars[i]);
+ }
+ i += 1;
+ }
+ out
+}
+
+fn translate_format_token(c: char) -> &'static str {
+ match c {
+ 'a' => "%a",
+ 'b' => "%b",
+ 'c' => "%m",
+ 'C' => "%y",
+ 'd' => "%d",
+ 'D' => "%m/%d/%y",
+ 'e' => "%d",
+ 'f' => "%f",
+ 'F' => "%Y-%m-%d",
+ 'g' => "%y",
+ 'G' => "%Y",
+ 'h' => "%I",
+ 'H' => "%H",
+ 'i' => "%M",
+ 'I' => "%I",
+ 'j' => "%j",
+ 'k' => "%H",
+ 'l' => "%I",
+ 'm' => "%m",
+ 'M' => "%B",
+ 'n' => "\n",
+ 'p' => "%p",
+ 'r' => "%I:%M %p",
+ 'R' => "%H:%M",
+ 's' => "%S",
+ 'S' => "%S",
+ 't' => "\t",
+ 'T' => "%H:%M:%S",
+ 'u' => "%u",
+ 'V' => "%V",
+ 'w' => "%w",
+ 'W' => "%A",
+ 'y' => "%y",
+ 'Y' => "%Y",
+ 'z' => "%z",
+ '%' => "%%",
+ _ => "",
+ }
+}
+
+// Port of the reference `isIPAddressInRange` (common/hogvm/typescript/src/stl/ip.ts): is `address`
+// inside the CIDR `prefix`? Any malformed input returns false rather than erroring, matching the
+// reference's try/catch. We reimplement parsing instead of leaning on std::net so the strict
+// validation (no leading zeros, exact segment counts, single `::`) matches byte-for-byte.
+fn is_ip_address_in_range(address: &str, prefix: &str) -> bool {
+ if address.is_empty() || prefix.is_empty() {
+ return false;
+ }
+ let Some((net, mask)) = prefix.split_once('/') else {
+ return false;
+ };
+ if net.is_empty() || mask.is_empty() {
+ return false;
+ }
+ let Ok(cidr) = mask.parse::<i64>() else {
+ return false;
+ };
+ if cidr < 0 {
+ return false;
+ }
+ let v4 = address.contains('.') && net.contains('.');
+ let v6 = !v4 && address.contains(':') && net.contains(':');
+ if !v4 && !v6 {
+ return false;
+ }
+ if (v4 && cidr > 32) || (v6 && cidr > 128) {
+ return false;
+ }
+ let (Some(a_bytes), Some(n_bytes)) = (ip_to_bytes(address, v4), ip_to_bytes(net, v4)) else {
+ return false;
+ };
+ let cidr = cidr as usize;
+ let full_bytes = cidr >> 3;
+ for i in 0..full_bytes {
+ if a_bytes[i] != n_bytes[i] {
+ return false;
+ }
+ }
+ let bits = cidr & 7;
+ if bits != 0 && full_bytes < a_bytes.len() {
+ let m = 0xffu16 << (8 - bits);
+ if (u16::from(a_bytes[full_bytes]) & m) != (u16::from(n_bytes[full_bytes]) & m) {
+ return false;
+ }
+ }
+ true
+}
+
+fn ip_to_bytes(ip: &str, is_v4: bool) -> Option<Vec<u8>> {
+ if is_v4 {
+ let parts: Vec<&str> = ip.split('.').collect();
+ if parts.len() != 4 {
+ return None;
+ }
+ let mut bytes = Vec::with_capacity(4);
+ for part in parts {
+ let n: u32 = part.parse().ok()?;
+ // Reject n > 255 and non-canonical forms like "01" (parse() already rejects "+1"/" 1").
+ if n > 255 || part != n.to_string() {
+ return None;
+ }
+ bytes.push(n as u8);
+ }
+ return Some(bytes);
+ }
+
+ let segments: Vec<String> = if ip.contains("::") {
+ if ip.matches("::").count() > 1 {
+ return None;
+ }
+ let (pre, post) = ip.split_once("::")?;
+ let pre_seg: Vec<&str> = if pre.is_empty() {
+ vec![]
+ } else {
+ pre.split(':').collect()
+ };
+ let post_seg: Vec<&str> = if post.is_empty() {
+ vec![]
+ } else {
+ post.split(':').collect()
+ };
+ if pre_seg.len() + post_seg.len() > 7 {
+ return None;
+ }
+ let fill = 8 - pre_seg.len() - post_seg.len();
+ pre_seg
+ .iter()
+ .map(|s| s.to_string())
+ .chain((0..fill).map(|_| "0".to_string()))
+ .chain(post_seg.iter().map(|s| s.to_string()))
+ .collect()
+ } else {
+ let segs: Vec<&str> = ip.split(':').collect();
+ if segs.len() != 8 {
+ return None;
+ }
+ segs.iter().map(|s| s.to_string()).collect()
+ };
+
+ let mut bytes = vec![0u8; 16];
+ for (i, seg) in segments.iter().enumerate() {
+ if seg.is_empty() {
+ return None;
+ }
+ let v = u16::from_str_radix(seg, 16).ok()?;
+ bytes[i * 2] = (v >> 8) as u8;
+ bytes[i * 2 + 1] = (v & 0xff) as u8;
+ }
+ Some(bytes)
+}
+
+type HmacSha256 = Hmac<Sha256>;
+
+// Hash `data` with the supplied digest fn, then encode. Used by md5Hex/sha256Hex (fixed "hex").
+// `null` data returns `null`, matching the reference.
+fn hash_with_encoding(
+ vm: &HogVM,
+ args: &[HogValue],
+ hasher: impl Fn(&[u8]) -> Vec<u8>,
+ encoding: &str,
+) -> Result<HogValue, VmError> {
+ match args[0].deref(&vm.heap)? {
+ HogLiteral::Null => Ok(HogLiteral::Null.into()),
+ lit => {
+ let data: &str = lit.try_as()?;
+ Ok(HogLiteral::String(encode_digest(&hasher(data.as_bytes()), encoding)?).into())
+ }
+ }
+}
+
+// md5/sha256 take an optional 2nd encoding arg (default "hex").
+fn hash_optional_encoding(
+ vm: &HogVM,
+ args: &[HogValue],
+ name: &str,
+ hasher: impl Fn(&[u8]) -> Vec<u8>,
+) -> Result<HogValue, VmError> {
+ if args.is_empty() || args.len() > 2 {
+ return Err(VmError::NativeCallFailed(format!(
+ "{name} takes 1 or 2 arguments"
+ )));
+ }
+ let encoding = encoding_arg(vm, args, 1)?;
+ hash_with_encoding(vm, args, hasher, &encoding)
+}
+
+// sha256HmacChain: HMAC-SHA256 chained across an array of strings, re-keying each step with the
+// previous raw digest. Mirrors common/hogvm/typescript/src/stl/crypto.ts.
+fn sha256_hmac_chain(vm: &HogVM, arg: &HogValue) -> Result<Vec<u8>, VmError> {
+ let arr = match arg.deref(&vm.heap)? {
+ HogLiteral::Array(a) => a.clone(),
+ _ => {
+ return Err(VmError::NativeCallFailed(
+ "sha256HmacChain expects an array".to_string(),
+ ))
+ }
+ };
+ if arr.len() < 2 {
+ return Err(VmError::NativeCallFailed(
+ "Data array must contain at least two elements.".to_string(),
+ ));
+ }
+ let key0: &str = arr[0].deref(&vm.heap)?.try_as()?;
+ let mut mac = HmacSha256::new_from_slice(key0.as_bytes())
+ .map_err(|e| VmError::NativeCallFailed(e.to_string()))?;
+ let msg1: &str = arr[1].deref(&vm.heap)?.try_as()?;
+ mac.update(msg1.as_bytes());
+ let mut digest = mac.finalize().into_bytes().to_vec();
+ for elem in &arr[2..] {
+ let mut next = HmacSha256::new_from_slice(&digest)
+ .map_err(|e| VmError::NativeCallFailed(e.to_string()))?;
+ let msg: &str = elem.deref(&vm.heap)?.try_as()?;
+ next.update(msg.as_bytes());
+ digest = next.finalize().into_bytes().to_vec();
+ }
+ Ok(digest)
+}
+
+// Encode raw digest bytes the way Node's `hash.digest(encoding)` does.
+fn encode_digest(digest: &[u8], encoding: &str) -> Result<String, VmError> {
+ match encoding {
+ "hex" => Ok(to_hex(digest)),
+ "base64" => Ok(base64::engine::general_purpose::STANDARD.encode(digest)),
+ "base64url" => Ok(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(digest)),
+ // Node's "binary"/"latin1" maps each byte to the code point equal to its value.
+ "binary" => Ok(digest.iter().map(|&b| b as char).collect()),
+ other => Err(VmError::NativeCallFailed(format!(
+ "Unsupported encoding: {other}"
+ ))),
+ }
+}
+
+// Read an optional encoding arg, defaulting to "hex" when absent or null.
+fn encoding_arg(vm: &HogVM, args: &[HogValue], idx: usize) -> Result<String, VmError> {
+ match args.get(idx) {
+ Some(v) => match v.deref(&vm.heap)? {
+ HogLiteral::String(s) => Ok(s.clone()),
+ _ => Ok("hex".to_string()),
+ },
+ None => Ok("hex".to_string()),
+ }
+}
+
+fn to_hex(bytes: &[u8]) -> String {
+ const HEX: &[u8; 16] = b"0123456789abcdef";
+ let mut out = String::with_capacity(bytes.len() * 2);
+ for &b in bytes {
+ out.push(HEX[(b >> 4) as usize] as char);
+ out.push(HEX[(b & 0xf) as usize] as char);
+ }
+ out
+}
+
+// Node's `Buffer.from(s, 'base64').toString()` — lenient about padding, UTF-8 decode lossily.
+fn base64_decode_to_string(s: &str) -> Result<String, VmError> {
+ let engine = base64::engine::GeneralPurpose::new(
+ &base64::alphabet::STANDARD,
+ base64::engine::GeneralPurposeConfig::new()
+ .with_decode_padding_mode(base64::engine::DecodePaddingMode::Indifferent)
+ .with_decode_allow_trailing_bits(true),
+ );
+ let bytes = engine
+ .decode(s.trim())
+ .map_err(|e| VmError::NativeCallFailed(format!("base64 decode failed: {e}")))?;
+ Ok(String::from_utf8_lossy(&bytes).into_owned())
+}
+
+// JS `encodeURIComponent`: keep the unreserved set, percent-encode every other UTF-8 byte.
+fn encode_uri_component(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ for &b in s.as_bytes() {
+ let keep = b.is_ascii_alphanumeric()
+ || matches!(
+ b,
+ b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')'
+ );
+ if keep {
+ out.push(b as char);
+ } else {
+ out.push('%');
+ out.push((b"0123456789ABCDEF"[(b >> 4) as usize]) as char);
+ out.push((b"0123456789ABCDEF"[(b & 0xf) as usize]) as char);
+ }
+ }
+ out
+}
+
+// JS `decodeURIComponent`: decode %XX into bytes and require the result be valid UTF-8, erroring
+// (like JS's URIError) on a malformed escape or invalid UTF-8 — callers map that to null/"".
+fn decode_uri_component(s: &str) -> Result<String, VmError> {
+ let bytes = s.as_bytes();
+ let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
+ let mut i = 0;
+ while i < bytes.len() {
+ if bytes[i] == b'%' {
+ if i + 2 >= bytes.len() {
+ return Err(VmError::NativeCallFailed("URI malformed".to_string()));
+ }
+ let hi = hex_val(bytes[i + 1]);
+ let lo = hex_val(bytes[i + 2]);
+ match (hi, lo) {
+ (Some(h), Some(l)) => out.push((h << 4) | l),
+ _ => return Err(VmError::NativeCallFailed("URI malformed".to_string())),
+ }
+ i += 3;
+ } else {
+ out.push(bytes[i]);
+ i += 1;
+ }
+ }
+ String::from_utf8(out).map_err(|_| VmError::NativeCallFailed("URI malformed".to_string()))
+}
+
+fn hex_val(b: u8) -> Option<u8> {
+ match b {
+ b'0'..=b'9' => Some(b - b'0'),
+ b'a'..=b'f' => Some(b - b'a' + 10),
+ b'A'..=b'F' => Some(b - b'A' + 10),
+ _ => None,
+ }
+}
+
+// Mirror the reference UUID v4 template fill: random hex for `x`, `(r & 0x3) | 0x8` for `y`.
+fn generate_uuid_v4() -> String {
+ let mut rng = rand::thread_rng();
+ let mut out = String::with_capacity(36);
+ for c in "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".chars() {
+ match c {
+ 'x' => {
+ let r: u8 = rng.gen_range(0..16);
+ out.push(char::from_digit(u32::from(r), 16).unwrap());
+ }
+ 'y' => {
+ let r: u8 = rng.gen_range(0..16);
+ let v = (r & 0x3) | 0x8;
+ out.push(char::from_digit(u32::from(v), 16).unwrap());
+ }
+ other => out.push(other),
+ }
+ }
+ out
+}
+
+// Error/RetryError/NotImplementedError share one body: the function name is the error type, the
+// first arg is the message, the second is the optional payload (mirrors the reference's `name` arg).
+fn error_constructor(vm: &HogVM, args: &[HogValue], type_str: &str) -> Result<HogValue, VmError> {
+ if args.len() > 2 {
+ return Err(VmError::NativeCallFailed(format!(
+ "{type_str} takes 0 to 2 arguments"
+ )));
+ }
+ let message = arg_string_or(vm, args, 0, "An error occurred")?;
+ new_hog_error(vm, type_str.to_string(), message, args.get(1))
+}
+
+// Build the Hog error duck-type `{ __hogError__, type, message, payload? }`. Payload is included
+// only when present and non-null, matching the reference printer's `obj.payload ? …` guard.
+fn new_hog_error(
+ vm: &HogVM,
+ type_str: String,
+ message: String,
+ payload: Option<&HogValue>,
+) -> Result<HogValue, VmError> {
+ let mut map = IndexMap::new();
+ map.insert("__hogError__".to_string(), HogLiteral::Boolean(true).into());
+ map.insert("type".to_string(), HogLiteral::String(type_str).into());
+ map.insert("message".to_string(), HogLiteral::String(message).into());
+ if let Some(p) = payload {
+ if !matches!(p.deref(&vm.heap)?, HogLiteral::Null) {
+ map.insert("payload".to_string(), p.clone());
+ }
+ }
+ Ok(HogLiteral::Object(map).into())
+}
+
+// Resolve a string arg with the reference's `value || default` falsiness: missing, null, or empty
+// string fall back to `default`; other values stringify.
+fn arg_string_or(
+ vm: &HogVM,
+ args: &[HogValue],
+ idx: usize,
+ default: &str,
+) -> Result<String, VmError> {
+ match args.get(idx) {
+ None => Ok(default.to_string()),
+ Some(v) => match v.deref(&vm.heap)? {
+ HogLiteral::String(s) if s.is_empty() => Ok(default.to_string()),
+ HogLiteral::String(s) => Ok(s.clone()),
+ HogLiteral::Null => Ok(default.to_string()),
+ _ => to_string(&vm.heap, v, 0),
+ },
+ }
+}
+
+// `empty` semantics (and `notEmpty` is its negation): numbers/booleans are never empty; null and
+// empty "" / [] / () / {} are empty. Matches the reference STL.empty.
+fn is_hog_empty(lit: &HogLiteral) -> bool {
+ match lit {
+ HogLiteral::Number(_) | HogLiteral::Boolean(_) => false,
+ HogLiteral::Null => true,
+ HogLiteral::String(s) => s.is_empty(),
+ HogLiteral::Array(a) | HogLiteral::Tuple(a) => a.is_empty(),
+ HogLiteral::Object(o) => o.is_empty(),
+ _ => false,
+ }
+}
+
+// `equals`/`notEquals` use strict equality (reference `a === b`): no cross-type coercion, so a
+// number and a numeric string are never equal. Differs from the coercing `==`/`!=` opcodes.
+fn strict_equals(vm: &HogVM, a: &HogValue, b: &HogValue) -> Result<bool, VmError> {
+ Ok(a.deref(&vm.heap)? == b.deref(&vm.heap)?)
+}
+
+// greater/less/greaterOrEquals/lessOrEquals as functions — reuse the VM's comparison semantics.
+fn compare_fn(vm: &HogVM, args: &[HogValue], op: NumOp, name: &str) -> Result<HogValue, VmError> {
+ assert_argc(args, 2, name)?;
+ let a = args[0].deref(&vm.heap)?;
+ let b = args[1].deref(&vm.heap)?;
+ Ok(compare_values(op, a, b, &vm.heap)?.into())
+}
+
+// plus/minus as functions — numeric arithmetic over the two operands.
+fn arith_fn(vm: &HogVM, args: &[HogValue], op: NumOp, name: &str) -> Result<HogValue, VmError> {
+ assert_argc(args, 2, name)?;
+ let a = args[0].deref(&vm.heap)?.try_as::<Num>()?.clone();
+ let b = args[1].deref(&vm.heap)?.try_as::<Num>()?.clone();
+ Ok(Num::binary_op(op, &a, &b)?.into())
}
fn assert(test: bool, msg: impl AsRef<str>) -> Result<(), VmError> {
diff --git a/rust/common/hogvm/src/util.rs b/rust/common/hogvm/src/util.rs
index f7d86ad8f0eb..8b5b65229b42 100644
--- a/rust/common/hogvm/src/util.rs
+++ b/rust/common/hogvm/src/util.rs
@@ -133,11 +133,20 @@ pub fn get_json_nested<'h>(
match val {
Value::Array(values) => {
let key: &Num = next_key.try_as()?;
- if key.is_float() || key.to_integer() < 1 {
+ if key.is_float() {
return Err(VmError::InvalidIndex);
}
- let key = (key.to_integer() as usize) - 1; // Hog indices are 1 based
- let Some(found) = values.get(key) else {
+ // Hog JSON-path indices are 1-based; the reference also allows negatives counting
+ // from the end. Index 0 and out-of-range yield "not found" (None), not an error.
+ let raw = key.to_integer();
+ let len = values.len() as i64;
+ let idx = match raw {
+ 0 => return Ok(None),
+ r if r > 0 && r <= len => (r - 1) as usize,
+ r if r < 0 && -r <= len => (len + r) as usize,
+ _ => return Ok(None),
+ };
+ let Some(found) = values.get(idx) else {
return Ok(None);
};
current = Some(found);
diff --git a/rust/common/hogvm/src/values.rs b/rust/common/hogvm/src/values.rs
index f8668c9f1d00..11569e001f26 100644
--- a/rust/common/hogvm/src/values.rs
+++ b/rust/common/hogvm/src/values.rs
@@ -1,6 +1,7 @@
-use std::{cmp::Ordering, collections::HashMap, fmt::Display, str::FromStr};
+use std::{cell::RefCell, cmp::Ordering, collections::HashMap, fmt::Display, rc::Rc, str::FromStr};
use chrono::NaiveDate;
+use indexmap::IndexMap;
use serde_json::Value as JsonValue;
use crate::{
@@ -10,6 +11,20 @@ use crate::{
vm::MAX_JSON_SERDE_DEPTH,
};
+/// A closure upvalue, Lua-style. While **open** it is a view onto a live stack slot at `location`
+/// (reads/writes go through `stack[location]`); when the slot leaves scope it is **closed** —
+/// `value` is snapshotted from the slot and the upvalue owns it thereafter. Shared via
+/// [`UpvalueCell`] so several closures (and the VM's open-upvalue list) reference the same cell and
+/// all observe the close.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Upvalue {
+ pub location: usize,
+ pub closed: bool,
+ pub value: Option<HogValue>,
+}
+
+pub type UpvalueCell = Rc<RefCell<Upvalue>>;
+
#[derive(Debug, Clone, PartialEq)]
pub enum Num {
Integer(i64),
@@ -19,11 +34,14 @@ pub enum Num {
#[derive(Debug, Clone, PartialEq)]
pub enum Callable {
Local(LocalCallable),
+ // A reference to a native (STL) function used as a first-class value, e.g. `let f := base64Encode`.
+ // Calling it dispatches to the native function by name rather than jumping to hog bytecode.
+ Stl(String),
}
#[derive(Debug, Clone, PartialEq)]
pub struct Closure {
- pub captures: Vec<HeapReference>,
+ pub captures: Vec<UpvalueCell>,
pub callable: Callable,
}
@@ -51,7 +69,13 @@ pub enum HogLiteral {
Boolean(bool),
String(String),
Array(Vec<HogValue>),
- Object(HashMap<String, HogValue>),
+ // A tuple is an array that prints as `(a, b)` and whose `typeof` is "tuple"; for every other
+ // operation it behaves exactly like an array (the reference duck-types it as an array with an
+ // `__isHogTuple` marker). Kept as a distinct variant so those two behaviors can diverge.
+ Tuple(Vec<HogValue>),
+ // Insertion-ordered (IndexMap, not HashMap) to match the reference VMs: object literals,
+ // `keys()`/`values()`, JSON serialization, and `print` all preserve the order keys were added.
+ Object(IndexMap<String, HogValue>),
Callable(Callable),
Closure(Closure),
Null,
@@ -112,13 +136,26 @@ impl HogValue {
};
found.get_nested(&chain[1..], heap)
}
- HogLiteral::Array(vals) => {
+ HogLiteral::Array(vals) | HogLiteral::Tuple(vals) => {
let index: &Num = chain[0].deref(heap)?.try_as()?;
- if index.is_float() || index.to_integer() < 1 {
+ if index.is_float() {
return Err(VmError::InvalidIndex);
}
- let index = (index.to_integer() as usize) - 1; // Hog indices are 1 based
- let Some(found) = vals.get(index) else {
+ let raw = index.to_integer();
+ // Hog indices are 1-based; the reference VMs also allow negative indices counting
+ // from the end (-1 is the last element). Index 0 is an error; out of range is null.
+ let resolved = match raw {
+ 0 => return Err(VmError::InvalidIndex),
+ r if r > 0 => (r as usize) - 1,
+ r => {
+ let from_end = vals.len() as i64 + r;
+ if from_end < 0 {
+ return Ok(None);
+ }
+ from_end as usize
+ }
+ };
+ let Some(found) = vals.get(resolved) else {
return Ok(None);
};
found.get_nested(&chain[1..], heap)
@@ -139,6 +176,10 @@ impl HogValue {
self.equals(rhs, heap)?.not()
}
+ // Backs the `in`/`notIn` opcodes (`x in y`). The reference IN opcode is `haystack.includes(needle)`
+ // (TS) / `needle in haystack` (Python): substring for a string haystack, element membership for an
+ // array, key membership for an object. (The `has` STL is different — array-only — so it has its own
+ // check and does NOT route through here.)
pub fn contains(&self, other: &HogValue, heap: &VmHeap) -> Result<HogLiteral, VmError> {
let (haystack, needle) = (self.deref(heap)?, other.deref(heap)?);
match haystack {
@@ -146,7 +187,7 @@ impl HogValue {
let needle: &str = needle.try_as()?;
Ok(s.contains(needle).into())
}
- HogLiteral::Array(vals) => {
+ HogLiteral::Array(vals) | HogLiteral::Tuple(vals) => {
for val in vals.iter() {
if *val.equals(other, heap)?.try_as::<bool>()? {
return Ok(true.into());
@@ -180,6 +221,7 @@ impl HogLiteral {
HogLiteral::Number(_) => "Number",
HogLiteral::Boolean(_) => "Boolean",
HogLiteral::Array(_) => "Array",
+ HogLiteral::Tuple(_) => "Tuple",
HogLiteral::Object(_) => "Object",
HogLiteral::Null => "Null",
HogLiteral::Callable(_) => "Callable",
@@ -196,13 +238,13 @@ impl HogLiteral {
HogLiteral::String(s) => s.len(),
HogLiteral::Number(_) => std::mem::size_of::<f64>(),
HogLiteral::Boolean(_) => std::mem::size_of::<bool>(),
- HogLiteral::Array(a) => a.iter().map(|v| v.size()).sum(),
+ HogLiteral::Array(a) | HogLiteral::Tuple(a) => a.iter().map(|v| v.size()).sum(),
HogLiteral::Object(o) => o.iter().map(|(k, v)| k.len() + v.size()).sum(),
HogLiteral::Null => std::mem::size_of::<()>(),
HogLiteral::Callable(_) => std::mem::size_of::<Callable>(),
HogLiteral::Closure(c) => {
std::mem::size_of::<Closure>()
- + (c.captures.len() * std::mem::size_of::<HeapReference>())
+ + (c.captures.len() * std::mem::size_of::<UpvalueCell>())
}
}
}
@@ -221,16 +263,35 @@ impl HogLiteral {
T::from_val(self)
}
+ // JS-style truthiness, matching the reference VMs' `!!` coercion in AND/OR/NOT/JUMP_IF_FALSE:
+ // false, 0, NaN, "" and null are falsy; everything else (including empty arrays/objects) is truthy.
+ pub fn truthy(&self) -> bool {
+ match self {
+ Self::Boolean(b) => *b,
+ Self::Number(n) => {
+ if n.is_float() {
+ let f = n.to_float();
+ f != 0.0 && !f.is_nan()
+ } else {
+ n.to_integer() != 0
+ }
+ }
+ Self::String(s) => !s.is_empty(),
+ Self::Null => false,
+ _ => true,
+ }
+ }
+
pub fn and(&self, rhs: &HogLiteral) -> Result<HogLiteral, VmError> {
- Ok(Self::Boolean(*self.try_as()? && *rhs.try_as()?))
+ Ok(Self::Boolean(self.truthy() && rhs.truthy()))
}
pub fn or(&self, rhs: &HogLiteral) -> Result<HogLiteral, VmError> {
- Ok(Self::Boolean(*self.try_as()? || *rhs.try_as()?))
+ Ok(Self::Boolean(self.truthy() || rhs.truthy()))
}
pub fn not(&self) -> Result<HogLiteral, VmError> {
- Ok(Self::Boolean(!*self.try_as::<bool>()?))
+ Ok(Self::Boolean(!self.truthy()))
}
fn coerce_types(&self, rhs: &HogLiteral) -> Result<(HogLiteral, HogLiteral), VmError> {
@@ -550,6 +611,14 @@ impl From<Vec<HogValue>> for HogLiteral {
impl From<HashMap<String, HogValue>> for HogLiteral {
fn from(value: HashMap<String, HogValue>) -> Self {
+ // External callers handing us an unordered HashMap get arbitrary key order; internal
+ // object construction (Dict op, json_to_hog) builds the IndexMap directly, in order.
+ Self::Object(value.into_iter().collect())
+ }
+}
+
+impl From<IndexMap<String, HogValue>> for HogLiteral {
+ fn from(value: IndexMap<String, HogValue>) -> Self {
Self::Object(value)
}
}
@@ -670,7 +739,9 @@ impl Num {
(Num::Float(a), Num::Float(b)) => a.total_cmp(b),
(Num::Integer(a), Num::Integer(b)) => a.cmp(b),
(Num::Float(a), Num::Integer(b)) => a.total_cmp(&(*b as f64)),
- (Num::Integer(a), Num::Float(b)) => (*a as f64).partial_cmp(b).unwrap(),
+ // total_cmp (like the other arms) so a NaN operand yields a deterministic ordering
+ // instead of panicking — reachable from min2/max2/arraySort via Hog-produced NaN.
+ (Num::Integer(a), Num::Float(b)) => (*a as f64).total_cmp(b),
}
}
@@ -703,7 +774,9 @@ impl Num {
NumOp::Add => Ok((a.saturating_add(b)).into()),
NumOp::Sub => Ok((a.saturating_sub(b)).into()),
NumOp::Mul => Ok((a.saturating_mul(b)).into()),
- NumOp::Div => Ok((a.saturating_div(b)).into()),
+ // `/` is float division in the reference VMs (JS `/`, Python true division), even
+ // for two integers: 3 / 2 is 1.5, not 1. Use `intDiv` for integer division.
+ NumOp::Div => Ok(((a as f64) / (b as f64)).into()),
NumOp::Mod => Ok((a % b).into()),
NumOp::Gt => Ok((a > b).into()),
NumOp::Lt => Ok((a < b).into()),
@@ -724,6 +797,7 @@ impl Display for Callable {
c.name, c.stack_arg_count, c.capture_count, c.ip
)
}
+ Self::Stl(name) => write!(f, "native fn {name}"),
}
}
}
@@ -763,7 +837,7 @@ pub fn construct_free_standing(current: JsonValue, depth: usize) -> Result<HogVa
Ok(HogLiteral::Array(values).into())
}
JsonValue::Object(obj) => {
- let mut map = HashMap::new();
+ let mut map = IndexMap::new();
for (key, value) in obj {
map.insert(key, construct_free_standing(value, depth + 1)?);
}
@@ -771,3 +845,31 @@ pub fn construct_free_standing(current: JsonValue, depth: usize) -> Result<HogVa
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::Num;
+ use std::cmp::Ordering;
+
+ #[test]
+ fn compare_with_nan_does_not_panic() {
+ // A NaN operand must yield a deterministic ordering rather than panicking. This path is
+ // reachable from min2/max2/arraySort with a Hog-produced NaN, so a panic here is a
+ // process-crash DoS. Every arm must return some Ordering.
+ let nan = Num::Float(f64::NAN);
+ let int = Num::Integer(1);
+ let float = Num::Float(1.0);
+ for (a, b) in [
+ (&int, &nan),
+ (&nan, &int),
+ (&float, &nan),
+ (&nan, &float),
+ (&nan, &nan),
+ ] {
+ assert!(matches!(
+ a.compare(b),
+ Ordering::Less | Ordering::Equal | Ordering::Greater
+ ));
+ }
+ }
+}
diff --git a/rust/common/hogvm/src/vm.rs b/rust/common/hogvm/src/vm.rs
index 89fcf583d82f..6552d79b3f3f 100644
--- a/rust/common/hogvm/src/vm.rs
+++ b/rust/common/hogvm/src/vm.rs
@@ -1,17 +1,25 @@
-use std::{any::Any, collections::HashMap};
+use std::any::Any;
+use std::cell::RefCell;
+use std::rc::Rc;
+use indexmap::IndexMap;
use serde::de::DeserializeOwned;
-use serde_json::Value as JsonValue;
+use serde_json::{json, Value as JsonValue};
use crate::{
context::{ExecutionContext, Symbol},
error::VmError,
memory::{HeapReference, VmHeap},
ops::Operation,
+ state::{
+ chunk_str, chunk_to_symbol, close_over_cells, closure_from_json, closure_to_json,
+ collect_cells, rebuild_cells, root_closure_json, value_from_json, value_to_json,
+ CallFrameJson, CellRegistry, Resumable, ThrowFrameJson, UpvalueJson, VmSnapshot,
+ },
util::{get_json_nested, like, regex_match},
values::{
compare_values, Callable, Closure, FromHogLiteral, HogLiteral, HogValue, LocalCallable,
- Num, NumOp,
+ Num, NumOp, Upvalue, UpvalueCell,
},
};
@@ -22,7 +30,10 @@ pub const MAX_JSON_SERDE_DEPTH: usize = 64;
pub enum StepOutcome {
/// The program has completed, returning a value
Finished(JsonValue),
- /// The program has requested a native function call
+ /// The program has requested a global function call. The driver dispatches it: a registered
+ /// native (STL/ext) runs inline; a registered *async* function (see [`ExecutionContext::is_async`])
+ /// suspends the resumable driver instead — at this point the args are already popped and `ip` is
+ /// past the call, so a snapshot taken now resumes correctly once the result is pushed.
NativeCall(String, Vec<HogValue>),
/// The program has requested another step
Continue,
@@ -47,7 +58,19 @@ pub struct HogVM<'a> {
stack_frames: Vec<CallFrame>,
throw_frames: Vec<ThrowFrame>,
+ // Upvalues still open (viewing a live stack slot). Closures created in this scope share these
+ // cells; when a slot leaves scope (stack truncation) the matching upvalue is closed (snapshotted)
+ // and removed from here. See `capture_upvalue` / `close_upvalues`.
+ open_upvalues: Vec<UpvalueCell>,
ip: usize,
+ // How many times this run has suspended on an async function call. Carried into snapshots and
+ // restored on resume, so the per-run async budget survives the suspend/resume round-trip.
+ async_steps: usize,
+ // Count of opcodes dispatched this run (the reference's `ops`). Carried across suspend/resume.
+ ops: usize,
+ // Per-opcode execution trace, collected only when the context opts into telemetry. Each entry is
+ // the reference's `[time, chunk, ip, "op/NAME", debug]` tuple. Carried across suspend/resume.
+ telemetry: Vec<JsonValue>,
context: &'a ExecutionContext,
// The base program is None, but calling into e.g. hog standard library functions involves changing the "module"
@@ -57,10 +80,13 @@ pub struct HogVM<'a> {
}
struct CallFrame {
- ret_ptr: usize, // Where to jump back to when we're done
- ret_symbol: Option<Symbol>, // The module to return to when we're done
- stack_start: usize, // Point in the stack the frame values start
- captures: Vec<HeapReference>, // Values captured from the parent scope/frame
+ ret_ptr: usize, // Where to jump back to when we're done
+ ret_symbol: Option<Symbol>, // The module to return to when we're done
+ stack_start: usize, // Point in the stack the frame values start
+ // The closure this frame is running (its callable + captured upvalues). Captures are read by
+ // `frame_capture`; the callable identity is what lets a snapshot reconstruct the reference VM's
+ // per-frame `closure`. Cross-module (STL) frames synthesize a callable for their symbol.
+ closure: Closure,
}
struct ThrowFrame {
@@ -76,7 +102,11 @@ impl<'a> HogVM<'a> {
stack: Vec::new(),
stack_frames: Vec::new(),
throw_frames: Vec::new(),
+ open_upvalues: Vec::new(),
ip: 0,
+ async_steps: 0,
+ ops: 0,
+ telemetry: Vec::new(),
current_symbol: None,
context,
heap: VmHeap::new(context.max_heap_size),
@@ -104,7 +134,39 @@ impl<'a> HogVM<'a> {
/// Step the virtual machine one cycle.
pub fn step(&mut self) -> Result<StepOutcome, VmError> {
- let op: Operation = self.next()?;
+ let pre_ip = self.ip;
+ let op: Operation = match self.next() {
+ Ok(op) => op,
+ // The reference VMs halt gracefully when the instruction pointer runs off the
+ // end of the top-level program (it has no trailing RETURN), yielding the top of
+ // stack or null. Only do this at the top level — running off the end inside a
+ // function/module is still malformed bytecode.
+ Err(VmError::EndOfProgram(_))
+ if self.stack_frames.is_empty() && self.current_symbol.is_none() =>
+ {
+ let result = if self.stack.is_empty() {
+ HogLiteral::Null.into()
+ } else {
+ self.pop_stack()?
+ };
+ return Ok(StepOutcome::Finished(self.hog_to_json(&result)?));
+ }
+ Err(e) => return Err(e),
+ };
+
+ self.ops += 1;
+
+ if self.context.collect_telemetry {
+ // The reference's `[time, chunk, ip, "op/NAME", debug]`. Time is a placeholder (we don't
+ // expose a wall clock here) and debug is unused; the chunk/ip/op trace is the substance.
+ self.telemetry.push(json!([
+ 0,
+ chunk_str(&self.current_symbol),
+ self.node_ip(pre_ip, &self.current_symbol),
+ op_telemetry_name(&op),
+ "",
+ ]));
+ }
match op {
Operation::GetGlobal => {
@@ -172,8 +234,9 @@ impl<'a> HogVM<'a> {
// but always popping, but then maybe reversing
args.reverse();
}
- // This VM does native calls like so: it returns a "native call" struct,
- // which the executing environment can use to execute the native call.
+ // This VM does native calls like so: it returns a "native call" struct, which the
+ // executing environment dispatches — inline for a native, or as a suspension for a
+ // registered async function (handled in the resumable driver).
return Ok(self.prep_native_call(name, args));
}
Operation::And => {
@@ -197,10 +260,9 @@ impl<'a> HogVM<'a> {
self.push_stack(acc)?;
}
Operation::Not => {
- let val = self.pop_stack_as::<bool>()?;
- // TODO - technically, we could assert here that this push will always succeed,
- // and it'd let us skip a bounds check I /think/, but lets not go microoptimizing yet
- self.push_stack(HogLiteral::from(!val))?;
+ let val = self.pop_stack()?;
+ let result = val.deref(&self.heap)?.not()?;
+ self.push_stack(result)?;
}
Operation::Plus => {
let (a, b) = (self.pop_stack_as()?, self.pop_stack_as()?);
@@ -260,22 +322,10 @@ impl<'a> HogVM<'a> {
let (needle, haystack) = (self.pop_stack()?, self.pop_stack()?);
self.push_stack(haystack.contains(&needle, &self.heap)?.not()?)?;
}
- Operation::Regex => {
- let (val, pat): (String, String) = (self.pop_stack_as()?, self.pop_stack_as()?);
- self.push_stack(regex_match(val, pat, true)?)?;
- }
- Operation::NotRegex => {
- let (val, pat): (String, String) = (self.pop_stack_as()?, self.pop_stack_as()?);
- self.push_stack(!regex_match(val, pat, true)?)?;
- }
- Operation::Iregex => {
- let (val, pat): (String, String) = (self.pop_stack_as()?, self.pop_stack_as()?);
- self.push_stack(regex_match(val, pat, false)?)?;
- }
- Operation::NotIregex => {
- let (val, pat): (String, String) = (self.pop_stack_as()?, self.pop_stack_as()?);
- self.push_stack(!regex_match(val, pat, false)?)?;
- }
+ Operation::Regex => self.regex_op(true, false)?,
+ Operation::NotRegex => self.regex_op(true, true)?,
+ Operation::Iregex => self.regex_op(false, false)?,
+ Operation::NotIregex => self.regex_op(false, true)?,
Operation::InCohort => return Err(VmError::NotImplemented("InCohort".to_string())),
Operation::NotInCohort => {
return Err(VmError::NotImplemented("NotInCohort".to_string()))
@@ -293,14 +343,31 @@ impl<'a> HogVM<'a> {
let val: String = self.next()?;
self.push_stack(val)?;
}
- Operation::Integer => {
- let val: i64 = self.next()?;
- self.push_stack(val)?;
- }
Operation::Float => {
let val: f64 = self.next()?;
self.push_stack(val)?;
}
+ // The reference's INTEGER opcode is untyped `pushStack(next())`; the SQL-AST compiler
+ // emits it with a boolean operand. Fast-path the overwhelmingly common i64 (this is a hot
+ // opcode — loop counters etc.), and fall back to pushing the raw token for anything else.
+ Operation::Integer => {
+ let as_int = self
+ .context
+ .get_bytecode(self.ip, &self.current_symbol)?
+ .as_i64();
+ if let Some(i) = as_int {
+ self.ip += 1;
+ self.push_stack(i)?;
+ } else {
+ let token = self
+ .context
+ .get_bytecode(self.ip, &self.current_symbol)?
+ .clone();
+ self.ip += 1;
+ let val = self.json_to_hog(&token)?;
+ self.push_stack(val)?;
+ }
+ }
Operation::Pop => {
self.pop_stack()?;
}
@@ -349,7 +416,9 @@ impl<'a> HogVM<'a> {
Operation::JumpIfFalse => {
// i32 to permit branching backwards
let offset: i32 = self.next()?;
- if !self.pop_stack_as::<bool>()? {
+ // The reference coerces with `!popStack()`, so any falsy value (0, "", null, …) branches.
+ let val = self.pop_stack()?;
+ if !val.deref(&self.heap)?.truthy() {
self.ip = ((self.ip as i64)
.checked_add(offset as i64)
.ok_or(VmError::IntegerOverflow)?) as usize;
@@ -381,8 +450,9 @@ impl<'a> HogVM<'a> {
values.push(self.pop_stack()?);
keys.push(self.pop_stack_as::<String>()?);
}
- let map: HashMap<String, HogValue> =
- HashMap::from_iter(keys.into_iter().zip(values));
+ // keys/values were popped in reverse (stack order), so reverse the zip to restore
+ // the source insertion order in the IndexMap.
+ let map: IndexMap<String, HogValue> = keys.into_iter().zip(values).rev().collect();
let obj = HogLiteral::Object(map);
// For the non-primitive types below (objects, arrays, "tuples"), we /always/ heap allocate them. The reason
// is that the pattern for e.g. nestedly setting an array value is to GetLocal followed by GetProperty, followed
@@ -409,30 +479,24 @@ impl<'a> HogVM<'a> {
self.push_stack(ptr)?;
}
Operation::Tuple => {
- // The compiler has special case handling for tuples, but the typescript VM doesn't, so neither do we,
- // this is effectively Array
+ // A tuple behaves like an array but prints as `(a, b)` and has typeof "tuple", so it
+ // gets its own literal variant rather than reusing Array.
let element_count: usize = self.next()?;
let mut elements = Vec::with_capacity(element_count);
for _ in 0..element_count {
elements.push(self.pop_stack()?);
}
- // We've walked back down the stack, but the compiler expects the "tuple" to be in pushed order
+ // We've walked back down the stack, but the compiler expects the tuple in pushed order
elements.reverse();
- let tuple = HogLiteral::Array(elements);
- // See above
+ let tuple = HogLiteral::Tuple(elements);
let ptr = self.heap.emplace(tuple)?;
self.push_stack(ptr)?;
}
- Operation::GetProperty => {
- let needle = self.pop_stack()?;
- let haystack = self.pop_stack()?;
- let chain = [needle];
- let Some(res) = haystack.get_nested(&chain, &self.heap)? else {
- return Err(VmError::UnknownProperty(format!("{:?}", chain[0])));
- };
- self.push_stack(res.clone())?;
- }
- Operation::GetPropertyNullish => {
+ // Both reference VMs (`getNestedValue`/`get_nested_value`) return null for a missing
+ // object key or out-of-range array index — the `nullish` flag only short-circuits a
+ // null *intermediate* in a multi-key chain, which these single-key opcodes never hit.
+ // So plain GetProperty and GetPropertyNullish behave identically here: null on miss.
+ Operation::GetProperty | Operation::GetPropertyNullish => {
let needle = self.pop_stack()?;
let haystack = self.pop_stack()?;
let chain = [needle];
@@ -476,18 +540,21 @@ impl<'a> HogVM<'a> {
}
// This doesn't assert the allocation is possible - the next one will fail, which is good enough
- self.heap.current_bytes = self
+ let new_bytes = self
.heap
.current_bytes
.saturating_sub(freed_bytes)
.saturating_add(allocated_bytes);
+ self.heap.set_current_bytes(new_bytes);
}
Operation::Try => {
// i32 to permit setting a catch offset lower than the IP
let catch_offset: i32 = self.next()?;
- // +1 to skip the POP_TRY that follows the try'd operations
+ // The reference computes `catchIp = <TRY position> + 1 + offset`. After reading the
+ // opcode and offset, self.ip points two past the TRY position, so subtract one to land
+ // on the same instruction (the compiler's offset already skips the POP_TRY).
let catch_ip = (self.ip as i64)
- .checked_add(catch_offset as i64 + 1)
+ .checked_add(catch_offset as i64 - 1)
.ok_or(VmError::IntegerOverflow)? as usize;
let frame = ThrowFrame {
catch_ptr: catch_ip,
@@ -559,8 +626,13 @@ impl<'a> HogVM<'a> {
Operation::Closure => {
let callable: Callable = self.pop_stack_as()?;
let capture_count: usize = self.next()?;
- // Irrefutable match for now
- let Callable::Local(unwrapped) = &callable;
+ // Only hog-local callables are wrapped by the CLOSURE opcode; native (STL) callables
+ // are produced already-closed by GetGlobal, so they should never reach here.
+ let Callable::Local(unwrapped) = &callable else {
+ return Err(VmError::InvalidCall(
+ "cannot close over a native function".to_string(),
+ ));
+ };
// Because captures are an implicit part of compilation, it's never valid
// for them to be different from the number of captures in the callable.
if capture_count != unwrapped.capture_count {
@@ -570,19 +642,19 @@ impl<'a> HogVM<'a> {
}
let mut captures = Vec::with_capacity(capture_count);
for _ in 0..capture_count {
- // Indicates whether this captured argument is to a stack variable in this
- // frames stack, or a captured argument in this frames captured arguments list
+ // Indicates whether this captured value is a local in this frame's stack, or an
+ // upvalue already captured by this frame's closure.
let is_local: bool = self.next()?;
- // usize as closures can only capture stack variables in the current scope
let offset: usize = self.next()?;
if is_local {
- let index = self
+ let location = self
.current_frame_base()
.checked_add(offset)
.ok_or(VmError::IntegerOverflow)?;
- captures.push(self.hoist(index)?);
+ captures.push(self.capture_upvalue(location));
} else {
- captures.push(self.get_capture(offset)?);
+ // Nested closure: share the parent frame's upvalue cell.
+ captures.push(self.frame_capture(offset)?);
}
}
@@ -592,14 +664,34 @@ impl<'a> HogVM<'a> {
Operation::CallLocal => {
let closure: Closure = self.pop_stack_as()?;
let arg_count: usize = self.next()?;
- let Callable::Local(callable) = &closure.callable;
- if arg_count > callable.stack_arg_count {
+ // Extract the scalar callable fields up front so `closure` can be moved into the frame
+ // (which now retains it for snapshotting). A native-function value dispatches inline.
+ let (ip, symbol, stack_arg_count) = match &closure.callable {
+ Callable::Local(callable) => (
+ callable.ip,
+ callable.symbol.clone(),
+ callable.stack_arg_count,
+ ),
+ // A first-class native function value (e.g. `let f := base64Encode; f(x)`):
+ // pop the args (push order, reversed for v>0 like CallGlobal) and dispatch natively.
+ Callable::Stl(name) => {
+ let name = name.clone();
+ let mut args = Vec::with_capacity(arg_count);
+ for _ in 0..arg_count {
+ args.push(self.pop_stack()?);
+ }
+ if self.context.version() != 0 {
+ args.reverse();
+ }
+ return Ok(self.prep_native_call(name, args));
+ }
+ };
+ if arg_count > stack_arg_count {
return Err(VmError::InvalidCall(format!(
- "Too many args - expected {}, got {}",
- callable.stack_arg_count, arg_count
+ "Too many args - expected {stack_arg_count}, got {arg_count}"
)));
}
- let null_args = callable.stack_arg_count.saturating_sub(arg_count);
+ let null_args = stack_arg_count.saturating_sub(arg_count);
// For pure-hog function calls (calls to "local" callables), we just push a null onto the stack for each missing argument,
// then construct the stack frame, and jump to the callable's frame ip. For other kinds of calls (which we don't support yet),
// we'll have to do something more complicated
@@ -609,44 +701,50 @@ impl<'a> HogVM<'a> {
let frame = CallFrame {
ret_ptr: self.ip,
ret_symbol: self.current_symbol.clone(),
- stack_start: self.stack.len().saturating_sub(callable.stack_arg_count),
- captures: closure.captures,
+ stack_start: self.stack.len().saturating_sub(stack_arg_count),
+ closure,
};
self.stack_frames.push(frame);
- self.current_symbol = callable.symbol.clone(); // Prep to jump across the module boundary, if that's what we're doing
- self.ip = callable.ip; // Do the jump
+ self.current_symbol = symbol; // Prep to jump across the module boundary, if that's what we're doing
+ self.ip = ip; // Do the jump
}
Operation::GetUpvalue => {
let index: usize = self.next()?;
- let ptr = self.get_capture(index)?;
- self.push_stack(ptr)?;
+ let cell = self.frame_capture(index)?;
+ // Open: read through to the live stack slot. Closed: read the snapshot it owns.
+ let val = {
+ let uv = cell.borrow();
+ if uv.closed {
+ uv.value.clone().unwrap_or_else(|| HogLiteral::Null.into())
+ } else {
+ self.stack
+ .get(uv.location)
+ .cloned()
+ .ok_or(VmError::StackIndexOutOfBounds)?
+ }
+ };
+ self.push_stack(val)?;
}
Operation::SetUpvalue => {
let index: usize = self.next()?;
- let ptr = self.get_capture(index)?;
- // If the top of the stack was a reference, we write that reference to the capture,
- // but if it was a literal, we write the literal to the heap location the capture points
- // to.
+ let cell = self.frame_capture(index)?;
let val = self.pop_stack()?;
- let new_size = val.size();
- match val {
- HogValue::Lit(hog_literal) => {
- let target = self.heap.get_mut(ptr)?;
- let old_size = target.size();
- *target = hog_literal;
- // This doesn't assert the allocation is possible - the next one will fail, which is good enough
- self.heap.current_bytes = self
- .heap
- .current_bytes
- .saturating_sub(old_size)
- .saturating_add(new_size)
- }
- HogValue::Ref(heap_reference) => self.set_capture(index, heap_reference)?,
+ // Open: write through to the live stack slot. Closed: store into the snapshot.
+ let (closed, location) = {
+ let uv = cell.borrow();
+ (uv.closed, uv.location)
+ };
+ if closed {
+ cell.borrow_mut().value = Some(val);
+ } else {
+ self.set_stack_val(location, val)?;
}
}
Operation::CloseUpvalue => {
- // The TS impl just pops here - I don't really understand why
- self.pop_stack()?;
+ // Reference: `stackKeepFirstElements(stack.length - 1)` — close any upvalue viewing
+ // the top slot (snapshot it), then drop the slot.
+ let new_len = self.stack.len().saturating_sub(1);
+ self.truncate_stack(new_len)?;
}
}
@@ -662,31 +760,66 @@ impl<'a> HogVM<'a> {
}
}
- // Returns a ptr to the captured value in this frames scope, if there is one,
- // or an error if the index is out of bounds
- fn get_capture(&self, index: usize) -> Result<HeapReference, VmError> {
+ // The upvalue cell captured at `index` by the currently-executing closure.
+ fn frame_capture(&self, index: usize) -> Result<UpvalueCell, VmError> {
let Some(frame) = self.stack_frames.last() else {
return Err(VmError::NoFrame);
};
frame
+ .closure
.captures
.get(index)
.cloned()
.ok_or(VmError::CaptureOutOfBounds(index))
}
- // Changes the location on the heap a capture points to, as distinct from changing the
- // value on the heap the capture points to. Think of this like storing a new pointer into
- // a variable name, vs. writing a new value into the variable itself
- fn set_capture(&mut self, index: usize, value: HeapReference) -> Result<(), VmError> {
- let Some(frame) = self.stack_frames.last_mut() else {
- return Err(VmError::NoFrame);
- };
- frame
- .captures
- .get_mut(index)
- .ok_or(VmError::CaptureOutOfBounds(index))
- .map(|capture| *capture = value)
+ // Capture the stack slot at `location` as an open upvalue, deduplicating so all closures that
+ // capture the same live slot share one cell (and therefore observe the same close). Matches the
+ // reference's `captureUpValue`.
+ fn capture_upvalue(&mut self, location: usize) -> UpvalueCell {
+ if let Some(existing) = self
+ .open_upvalues
+ .iter()
+ .find(|cell| cell.borrow().location == location)
+ .cloned()
+ {
+ return existing;
+ }
+ let cell = Rc::new(RefCell::new(Upvalue {
+ location,
+ closed: false,
+ value: None,
+ }));
+ self.open_upvalues.push(cell.clone());
+ cell
+ }
+
+ // Close every open upvalue whose slot is at or above `from` (i.e. about to leave scope):
+ // snapshot the current stack value into the cell and drop it from the open list. The closures
+ // holding the cell keep the snapshot. Matches the reference's `stackKeepFirstElements` close loop.
+ fn close_upvalues(&mut self, from: usize) {
+ if self.open_upvalues.is_empty() {
+ return;
+ }
+ let mut i = 0;
+ while i < self.open_upvalues.len() {
+ let location = self.open_upvalues[i].borrow().location;
+ if location >= from {
+ let snapshot = self
+ .stack
+ .get(location)
+ .cloned()
+ .unwrap_or_else(|| HogLiteral::Null.into());
+ {
+ let mut uv = self.open_upvalues[i].borrow_mut();
+ uv.closed = true;
+ uv.value = Some(snapshot);
+ }
+ self.open_upvalues.swap_remove(i);
+ } else {
+ i += 1;
+ }
+ }
}
fn next<T>(&mut self) -> Result<T, VmError>
@@ -730,6 +863,28 @@ impl<'a> HogVM<'a> {
/// [`ExecutionContext::with_coercing_comparisons`](crate::ExecutionContext::with_coercing_comparisons))
/// does a non-`Number` operand reach [`compare_values`]' coercion instead of erroring. `a` is the
/// top of the stack.
+ // `=~`/`!~` (and the case-insensitive variants). The stack holds the pattern below the value;
+ // either operand being null never matches (the reference's external matcher returns false), so
+ // `=~` is false and `!~` is true.
+ fn regex_op(&mut self, case_sensitive: bool, negate: bool) -> Result<(), VmError> {
+ let val = self.pop_stack()?;
+ let pat = self.pop_stack()?;
+ let matched = {
+ let val_lit = val.deref(&self.heap)?;
+ let pat_lit = pat.deref(&self.heap)?;
+ if matches!(val_lit, HogLiteral::Null) || matches!(pat_lit, HogLiteral::Null) {
+ false
+ } else {
+ regex_match(
+ val_lit.try_as::<str>()?,
+ pat_lit.try_as::<str>()?,
+ case_sensitive,
+ )?
+ }
+ };
+ self.push_stack(HogLiteral::Boolean(matched ^ negate))
+ }
+
fn compare_op(&mut self, op: NumOp) -> Result<(), VmError> {
if !self.context.coerce_comparisons {
// Legacy/reference path: both operands must be `Number` or this errors.
@@ -790,6 +945,9 @@ impl<'a> HogVM<'a> {
if new_len > self.stack.len() {
return Err(VmError::StackIndexOutOfBounds);
}
+ // Any upvalue viewing a slot that's about to disappear must be closed (snapshotted) first,
+ // so closures that captured it keep the value rather than a dangling stack index.
+ self.close_upvalues(new_len);
self.stack.truncate(new_len);
Ok(())
}
@@ -804,7 +962,19 @@ impl<'a> HogVM<'a> {
// TODO - we don't support function imports right now - most trivial programs don't need them,
// and filters are generally trivial
- fn get_fn_reference(&self, _chain: &[HogValue]) -> Result<HogLiteral, VmError> {
+ // Resolve a global name referenced as a first-class function value. Currently supports native
+ // (STL) functions — `let f := base64Encode` yields a closure that dispatches to the native fn.
+ fn get_fn_reference(&self, chain: &[HogValue]) -> Result<HogLiteral, VmError> {
+ if chain.len() != 1 {
+ return Err(VmError::NotImplemented("imports".to_string()));
+ }
+ let name: &str = chain[0].deref(&self.heap)?.try_as()?;
+ if self.context.has_native(name) {
+ return Ok(HogLiteral::Closure(Closure {
+ callable: Callable::Stl(name.to_string()),
+ captures: Vec::new(),
+ }));
+ }
Err(VmError::NotImplemented("imports".to_string()))
}
@@ -831,15 +1001,28 @@ impl<'a> HogVM<'a> {
arg_count
)));
}
- let null_args = to_call.arg_count().saturating_sub(arg_count);
+ let callee_arg_count = to_call.arg_count();
+ let null_args = callee_arg_count.saturating_sub(arg_count);
for _ in 0..null_args {
self.push_stack(HogLiteral::Null)?;
}
+ // Cross-module calls never involve captures, but the frame still carries a synthesized
+ // callable for its symbol so a snapshot can render the reference VM's per-frame closure
+ // (e.g. `fn<arrayMap>` in chunk `stl/arrayMap`).
let frame = CallFrame {
ret_ptr: self.ip,
ret_symbol: self.current_symbol.clone(),
- stack_start: self.stack.len().saturating_sub(to_call.arg_count()),
- captures: Vec::new(), // Cross module calls never involve captures
+ stack_start: self.stack.len().saturating_sub(callee_arg_count),
+ closure: Closure {
+ callable: Callable::Local(LocalCallable {
+ name: symbol.name.clone(),
+ stack_arg_count: callee_arg_count,
+ capture_count: 0,
+ ip: 0,
+ symbol: Some(symbol.clone()),
+ }),
+ captures: Vec::new(),
+ },
};
self.stack_frames.push(frame);
@@ -886,7 +1069,7 @@ impl<'a> HogVM<'a> {
Ok(ptr.into())
}
JsonValue::Object(obj) => {
- let mut map = HashMap::new();
+ let mut map = IndexMap::new();
for (key, value) in obj {
map.insert(key.clone(), self.json_to_hog_impl(value, depth + 1)?);
}
@@ -916,7 +1099,7 @@ impl<'a> HogVM<'a> {
HogLiteral::Boolean(b) => Ok(JsonValue::Bool(*b)),
HogLiteral::Number(n) => Ok(JsonValue::Number(n.clone().try_into()?)),
HogLiteral::String(s) => Ok(JsonValue::String(s.clone())),
- HogLiteral::Array(arr) => {
+ HogLiteral::Array(arr) | HogLiteral::Tuple(arr) => {
let mut json_arr = Vec::new();
for elem in arr {
json_arr.push(self.hog_to_json_impl(elem, depth + 1)?);
@@ -938,6 +1121,234 @@ impl<'a> HogVM<'a> {
}
}
}
+
+ /// Capture the full live state as a serializable [`VmSnapshot`]. The program/STL are not part of
+ /// the snapshot — [`resume`] re-supplies them via the `ExecutionContext`. The upvalue graph
+ /// (`Rc<RefCell<Upvalue>>`, shared between the open list and closures) is flattened to ids.
+ pub fn snapshot(&self) -> Result<VmSnapshot, VmError> {
+ let mut registry = CellRegistry::default();
+ // Intern open upvalues first (stable low ids), then everything reachable from the stack and
+ // frame captures, then chase closed-cell values for nested closures.
+ for cell in &self.open_upvalues {
+ registry.intern(cell);
+ }
+ for value in &self.stack {
+ collect_cells(value, &self.heap, &mut registry)?;
+ }
+ for frame in &self.stack_frames {
+ for cell in &frame.closure.captures {
+ registry.intern(cell);
+ }
+ }
+ close_over_cells(&self.heap, &mut registry)?;
+
+ // Read each cell's data out before serializing (so the value walk isn't aliasing the
+ // registry it borrows; it is already complete, so no new ids are minted).
+ let cell_data: Vec<(usize, bool, Option<HogValue>)> = registry
+ .cells()
+ .iter()
+ .map(|c| {
+ let b = c.borrow();
+ (b.location, b.closed, b.value.clone())
+ })
+ .collect();
+
+ let header_len = self.context.program_header_len();
+ let mut stack = Vec::with_capacity(self.stack.len());
+ for value in &self.stack {
+ stack.push(value_to_json(value, &self.heap, &mut registry, header_len)?);
+ }
+
+ let mut upvalues = Vec::with_capacity(cell_data.len());
+ for (id, (location, closed, value)) in cell_data.into_iter().enumerate() {
+ let value_json = match (closed, &value) {
+ (true, Some(v)) => value_to_json(v, &self.heap, &mut registry, header_len)?,
+ _ => JsonValue::Null,
+ };
+ upvalues.push(UpvalueJson {
+ marker: true,
+ // 1-based, matching the reference (`id: sortedUpValues.length + 1`).
+ id: id + 1,
+ location,
+ closed,
+ value: value_json,
+ });
+ }
+
+ // The reference keeps upvalues sorted by location so its capture early-break stays valid on
+ // resume; each entry keeps its id so closure references still resolve.
+ upvalues.sort_by_key(|u| u.location);
+
+ let call_stack = self.build_call_stack(&mut registry, header_len)?;
+
+ let throw_stack = self
+ .throw_frames
+ .iter()
+ .map(|t| ThrowFrameJson {
+ // The reference's callStackLen counts its frames — our depth plus the root frame.
+ call_stack_len: t.call_depth + 1,
+ stack_len: t.stack_start,
+ catch_ip: self.node_ip(t.catch_ptr, &t.catch_symbol),
+ })
+ .collect();
+
+ // The reference stores `bytecodes.root` as just `{ bytecode }` (globals are re-supplied via
+ // options on resume), so omit globals to match its wire shape.
+ Ok(VmSnapshot {
+ bytecodes: json!({ "root": { "bytecode": self.context.program_tokens() } }),
+ stack,
+ upvalues,
+ call_stack,
+ throw_stack,
+ declared_functions: json!({}),
+ ops: self.ops,
+ async_steps: self.async_steps,
+ sync_duration: 0,
+ max_mem_used: self.heap.peak_bytes,
+ telemetry: self
+ .context
+ .collect_telemetry
+ .then(|| self.telemetry.clone()),
+ })
+ }
+
+ /// Build the reference's `callStack` (root frame first, active frame last). Frame `d` < N draws
+ /// its ip/chunk from the frame pushed when depth `d` called `d+1` (which stored `d`'s resume
+ /// point) and its closure/stackStart from that same callee frame; depth N is the live position.
+ fn build_call_stack(
+ &self,
+ registry: &mut CellRegistry,
+ header_len: usize,
+ ) -> Result<Vec<CallFrameJson>, VmError> {
+ let n = self.stack_frames.len();
+ let mut frames = Vec::with_capacity(n + 1);
+ for d in 0..=n {
+ let (rust_ip, symbol) = if d == n {
+ (self.ip, self.current_symbol.clone())
+ } else {
+ (
+ self.stack_frames[d].ret_ptr,
+ self.stack_frames[d].ret_symbol.clone(),
+ )
+ };
+ let (closure, stack_start, arg_count) = if d == 0 {
+ (root_closure_json(), 0, 0)
+ } else {
+ let frame = &self.stack_frames[d - 1];
+ let arg_count = match &frame.closure.callable {
+ Callable::Local(lc) => lc.stack_arg_count,
+ Callable::Stl(_) => 0,
+ };
+ (
+ closure_to_json(&frame.closure, registry, header_len),
+ frame.stack_start,
+ arg_count,
+ )
+ };
+ frames.push(CallFrameJson {
+ closure,
+ ip: self.node_ip(rust_ip, &symbol),
+ chunk: chunk_str(&symbol),
+ stack_start,
+ arg_count,
+ });
+ }
+ Ok(frames)
+ }
+
+ /// Our `ip` is body-relative; the reference's per-frame `ip` indexes the full bytecode array
+ /// (header included) for the root chunk. Module chunks (STL bodies) carry no header.
+ fn node_ip(&self, rust_ip: usize, symbol: &Option<Symbol>) -> usize {
+ rust_ip
+ + if symbol.is_none() {
+ self.context.program_header_len()
+ } else {
+ 0
+ }
+ }
+
+ fn rust_ip(node_ip: usize, chunk: &str, context: &ExecutionContext) -> usize {
+ node_ip.saturating_sub(if chunk == "root" {
+ context.program_header_len()
+ } else {
+ 0
+ })
+ }
+
+ /// Rebuild a VM from a [`VmSnapshot`] against `context`. Inverse of [`Self::snapshot`]: cells are
+ /// created empty first so closure captures resolve by id, containers are re-emplaced onto a fresh
+ /// heap, and the open-upvalue list is reconstructed from the still-open cells.
+ pub fn restore(
+ context: &'a ExecutionContext,
+ snapshot: &VmSnapshot,
+ ) -> Result<HogVM<'a>, VmError> {
+ let mut vm = HogVM::new(context)?;
+ let header_len = context.program_header_len();
+
+ let cells = rebuild_cells(&snapshot.upvalues, &mut vm.heap, header_len)?;
+
+ let mut stack = Vec::with_capacity(snapshot.stack.len());
+ for value in &snapshot.stack {
+ stack.push(value_from_json(value, &mut vm.heap, &cells, header_len)?);
+ }
+
+ // Inverse of `build_call_stack`: the reference callStack has N+1 frames (root + N); we keep N
+ // frames plus the live ip/symbol. Frame i bundles depth-i's return point (callStack[i]'s
+ // ip/chunk) with depth-(i+1)'s closure and stack window.
+ let call_stack = &snapshot.call_stack;
+ let Some(active) = call_stack.last() else {
+ return Err(VmError::Other("snapshot callStack is empty".to_string()));
+ };
+ vm.ip = Self::rust_ip(active.ip, &active.chunk, context);
+ vm.current_symbol = chunk_to_symbol(&active.chunk);
+
+ let n = call_stack.len() - 1;
+ let mut stack_frames = Vec::with_capacity(n);
+ for i in 0..n {
+ stack_frames.push(CallFrame {
+ ret_ptr: Self::rust_ip(call_stack[i].ip, &call_stack[i].chunk, context),
+ ret_symbol: chunk_to_symbol(&call_stack[i].chunk),
+ stack_start: call_stack[i + 1].stack_start,
+ closure: closure_from_json(&call_stack[i + 1].closure, &cells, header_len)?,
+ });
+ }
+
+ let mut throw_frames = Vec::with_capacity(snapshot.throw_stack.len());
+ for t in &snapshot.throw_stack {
+ // callStackLen counts reference frames (root + our depth); recover our depth and the
+ // chunk that depth ran in so we can restore catch_symbol.
+ let call_depth = t.call_stack_len.saturating_sub(1);
+ let chunk = call_stack
+ .get(call_depth)
+ .map(|f| f.chunk.as_str())
+ .unwrap_or("root");
+ throw_frames.push(ThrowFrame {
+ catch_ptr: Self::rust_ip(t.catch_ip, chunk, context),
+ catch_symbol: chunk_to_symbol(chunk),
+ stack_start: t.stack_len,
+ call_depth,
+ });
+ }
+
+ let open_upvalues = cells
+ .values()
+ .filter(|c| !c.borrow().closed)
+ .cloned()
+ .collect();
+
+ vm.stack = stack;
+ vm.stack_frames = stack_frames;
+ vm.throw_frames = throw_frames;
+ vm.open_upvalues = open_upvalues;
+ vm.async_steps = snapshot.async_steps;
+ vm.ops = snapshot.ops;
+ // Carry the recorded high-water mark across resume — rebuilding the heap only accounts for
+ // live values, so without this a restore→snapshot round-trip would lose the original peak.
+ vm.heap.peak_bytes = vm.heap.peak_bytes.max(snapshot.max_mem_used);
+ // Carry the trace across resume so a multi-suspension run accumulates one continuous trace.
+ vm.telemetry = snapshot.telemetry.clone().unwrap_or_default();
+ Ok(vm)
+ }
}
// Helper function to simply run a program until it either finishes or returns an error
@@ -964,6 +1375,9 @@ pub fn sync_execute(context: &ExecutionContext, print_debug: bool) -> Result<Jso
StepOutcome::Continue => {}
StepOutcome::Finished(res) => return Ok(res),
StepOutcome::NativeCall(name, args) => {
+ // Sync execution can't suspend: an async function name isn't a registered native, so
+ // this surfaces as an `UnknownFunction` error here — the correct outcome for a sync
+ // consumer that hits an async call. Resumable execution handles it via [`resume`].
match context.execute_native_function_call(&mut vm, &name, args) {
Ok(_) => {}
Err(err) => return Err(fail(err, Some(&vm), i)),
@@ -978,6 +1392,99 @@ pub fn sync_execute(context: &ExecutionContext, print_debug: bool) -> Result<Jso
Err(fail(err, Some(&vm), i))
}
+/// Drive a fresh program to completion or its first async suspension — the resumable counterpart to
+/// [`sync_execute`]. On a registered async call it returns [`Resumable::Suspended`] with a
+/// serializable snapshot; the host performs the side effect and calls [`resume`].
+pub fn execute_resumable(context: &ExecutionContext) -> Result<Resumable, VmFailure> {
+ let vm = HogVM::new(context).map_err(|e| failure(e, None, 0))?;
+ drive_resumable(vm, context)
+}
+
+/// Resume a snapshot with the result of the async function it suspended on. The result is pushed as
+/// the value the suspended `CALL_GLOBAL` yields, and execution continues from where it left off.
+pub fn resume(
+ context: &ExecutionContext,
+ state: &VmSnapshot,
+ async_result: JsonValue,
+) -> Result<Resumable, VmFailure> {
+ let mut vm = HogVM::restore(context, state).map_err(|e| failure(e, None, 0))?;
+ let value = vm
+ .json_to_hog(&async_result)
+ .map_err(|e| failure(e, Some(&vm), 0))?;
+ vm.push_stack(value).map_err(|e| failure(e, Some(&vm), 0))?;
+ drive_resumable(vm, context)
+}
+
+fn drive_resumable(mut vm: HogVM, context: &ExecutionContext) -> Result<Resumable, VmFailure> {
+ let mut i = 0;
+ while i < context.max_steps {
+ let res = vm.step().map_err(|e| failure(e, Some(&vm), i))?;
+ match res {
+ StepOutcome::Continue => {}
+ StepOutcome::Finished(result) => return Ok(Resumable::Finished(result)),
+ StepOutcome::NativeCall(name, args) => {
+ // A registered async function suspends instead of running inline: snapshot the state
+ // (args already popped, `ip` past the call) and hand it back for the host to perform
+ // the side effect and `resume`. Everything else is a normal inline native call.
+ if context.is_async(&name) {
+ if vm.async_steps >= context.max_async_steps {
+ return Err(failure(
+ VmError::OutOfResource(format!(
+ "async steps ({})",
+ context.max_async_steps
+ )),
+ Some(&vm),
+ i,
+ ));
+ }
+ vm.async_steps += 1;
+ let mut json_args = Vec::with_capacity(args.len());
+ for arg in &args {
+ json_args.push(vm.hog_to_json(arg).map_err(|e| failure(e, Some(&vm), i))?);
+ }
+ let state = vm.snapshot().map_err(|e| failure(e, Some(&vm), i))?;
+ return Ok(Resumable::Suspended {
+ function: name,
+ args: json_args,
+ state: Box::new(state),
+ });
+ }
+ context
+ .execute_native_function_call(&mut vm, &name, args)
+ .map_err(|e| failure(e, Some(&vm), i))?;
+ }
+ }
+ i += 1;
+ }
+ Err(failure(
+ VmError::OutOfResource("steps".to_string()),
+ Some(&vm),
+ i,
+ ))
+}
+
+fn failure(error: VmError, vm: Option<&HogVM>, step: usize) -> VmFailure {
+ VmFailure {
+ error,
+ ip: vm.map_or(0, |vm| vm.ip),
+ stack: vm.map_or(Vec::new(), |vm| vm.stack.clone()),
+ step,
+ }
+}
+
+/// The reference's telemetry opcode label: `"<num>/<SCREAMING_SNAKE_NAME>"` (e.g. `2/CALL_GLOBAL`).
+fn op_telemetry_name(op: &Operation) -> String {
+ let pascal = format!("{op:?}");
+ let mut name = String::with_capacity(pascal.len() + 4);
+ for (i, c) in pascal.char_indices() {
+ if c.is_ascii_uppercase() && i != 0 {
+ name.push('_');
+ }
+ name.push(c.to_ascii_uppercase());
+ }
+ format!("{}/{}", op.clone() as u8, name)
+}
+
fn next_type_name(next: &JsonValue) -> String {
match next {
JsonValue::Null => "null".to_string(),
diff --git a/rust/common/hogvm/tests/async_resume.rs b/rust/common/hogvm/tests/async_resume.rs
new file mode 100644
index 000000000000..300f7d9753be
--- /dev/null
+++ b/rust/common/hogvm/tests/async_resume.rs
@@ -0,0 +1,241 @@
+//! Suspend/resume (async-coroutine) execution + VMState serialization.
+//!
+//! These lock in the contract the CDP hog-function path depends on: a program that calls a
+//! registered async function suspends with a fully serializable snapshot, and resuming with the
+//! async result continues to the correct value — across a real JSON text round-trip of the state,
+//! and with a closure whose open upvalue (a live stack reference) must survive serialization.
+
+use std::collections::HashSet;
+
+use hogvm::{execute_resumable, resume, ExecutionContext, Program, Resumable, VmSnapshot};
+use serde_json::{json, Value};
+
+// Opcodes used below (see common/hogvm/python/operation.py).
+const CALL_GLOBAL: i64 = 2;
+const PLUS: i64 = 6;
+const INTEGER: i64 = 33;
+const GET_LOCAL: i64 = 36;
+const RETURN: i64 = 38;
+const CALLABLE: i64 = 52;
+const CLOSURE: i64 = 53;
+const CALL_LOCAL: i64 = 54;
+const GET_UPVALUE: i64 = 55;
+
+// Drive a program that calls `asyncFetch`, injecting `inject` as the async result at each
+// suspension. Each suspension's snapshot is serialized to JSON text and parsed back before resuming,
+// proving the state survives a real serialization boundary (not just an in-memory handoff).
+fn run_injecting(tokens: Vec<Value>, inject: Value) -> Value {
+ let program = Program::new(tokens).expect("valid program");
+ let context = ExecutionContext::with_defaults(program)
+ .with_async_functions(HashSet::from(["asyncFetch".to_string()]))
+ .with_max_async_steps(4);
+
+ let mut outcome = execute_resumable(&context).expect("initial execution");
+ loop {
+ match outcome {
+ Resumable::Finished(value) => return value,
+ Resumable::Suspended { state, .. } => {
+ let text = serde_json::to_string(&state).expect("snapshot serializes");
+ let restored: VmSnapshot =
+ serde_json::from_str(&text).expect("snapshot parses back");
+ outcome = resume(&context, &restored, inject.clone()).expect("resume");
+ }
+ }
+ }
+}
+
+#[test]
+fn scalar_async_round_trips() {
+ // asyncFetch(2) + 40, injecting 2 => 42. Exercises the bare suspend/serialize/resume cycle.
+ let result = run_injecting(
+ vec![
+ json!("_H"),
+ json!(1),
+ json!(INTEGER),
+ json!(2),
+ json!(CALL_GLOBAL),
+ json!("asyncFetch"),
+ json!(1),
+ json!(INTEGER),
+ json!(40),
+ json!(PLUS),
+ json!(RETURN),
+ ],
+ json!(2),
+ );
+ assert_eq!(result, json!(42));
+}
+
+#[test]
+fn open_upvalue_survives_suspend() {
+ // let x := 5
+ // let f := () -> x // f captures root local 0 (x) as an OPEN upvalue
+ // let y := asyncFetch(0) // suspend while x is in scope => the upvalue is open at snapshot time
+ // return f() + y // after resume, f() must still read x (=5) through that upvalue
+ // injecting 37 => 5 + 37 = 42. Regresses the upvalue-graph-by-id flattening + reconnect on resume.
+ let result = run_injecting(
+ vec![
+ json!("_H"),
+ json!(1),
+ json!(INTEGER),
+ json!(5), // x = 5 (local 0)
+ json!(CALLABLE),
+ json!("lambda"),
+ json!(0),
+ json!(1),
+ json!(3),
+ json!(GET_UPVALUE),
+ json!(0),
+ json!(RETURN), // lambda body: return x (upvalue 0)
+ json!(CLOSURE),
+ json!(1),
+ json!(true),
+ json!(0), // capture parent local 0 -> f (local 1)
+ json!(INTEGER),
+ json!(0), // asyncFetch arg
+ json!(CALL_GLOBAL),
+ json!("asyncFetch"),
+ json!(1), // suspend (x still in scope)
+ json!(GET_LOCAL),
+ json!(1), // f
+ json!(CALL_LOCAL),
+ json!(0), // f()
+ json!(PLUS), // f() + y
+ json!(RETURN),
+ ],
+ json!(37),
+ );
+ assert_eq!(result, json!(42));
+}
+
+#[test]
+fn nested_call_suspend_round_trips() {
+ // fun helper() { return asyncFetch(0) } // suspend one frame deep (callStack = [root, helper])
+ // return helper() + 40
+ // injecting 2 => 42. Exercises the N>=1 call-stack mapping: the snapshot must reconstruct the
+ // helper frame's return point + stack window so it returns into root correctly.
+ let result = run_injecting(
+ vec![
+ json!("_H"),
+ json!(1),
+ json!(CALLABLE),
+ json!("helper"),
+ json!(0),
+ json!(0),
+ json!(6),
+ json!(INTEGER),
+ json!(0),
+ json!(CALL_GLOBAL),
+ json!("asyncFetch"),
+ json!(1),
+ json!(RETURN),
+ json!(CLOSURE),
+ json!(0), // helper -> local 0
+ json!(GET_LOCAL),
+ json!(0),
+ json!(CALL_LOCAL),
+ json!(0), // helper()
+ json!(INTEGER),
+ json!(40),
+ json!(PLUS),
+ json!(RETURN),
+ ],
+ json!(2),
+ );
+ assert_eq!(result, json!(42));
+}
+
+#[test]
+fn sleep_is_builtin_async() {
+ // sleep(1) suspends as async even with no host-registered async functions, mirroring the
+ // reference's ASYNC_STL (which sleep is the sole member of).
+ let program = Program::new(vec![
+ json!("_H"),
+ json!(1),
+ json!(INTEGER),
+ json!(1),
+ json!(CALL_GLOBAL),
+ json!("sleep"),
+ json!(1),
+ json!(RETURN),
+ ])
+ .expect("valid program");
+ let context = ExecutionContext::with_defaults(program).with_max_async_steps(1);
+ match execute_resumable(&context).expect("exec") {
+ Resumable::Suspended { function, .. } => assert_eq!(function, "sleep"),
+ Resumable::Finished(_) => panic!("expected suspension on sleep"),
+ }
+}
+
+#[test]
+fn telemetry_traces_opcodes() {
+ // With telemetry on, the suspend snapshot carries the reference's [time, chunk, ip, "op/NAME",
+ // debug] trace. The first opcode is INTEGER at header-inclusive ip 2, and a CALL_GLOBAL follows.
+ let program = Program::new(vec![
+ json!("_H"),
+ json!(1),
+ json!(INTEGER),
+ json!(2),
+ json!(CALL_GLOBAL),
+ json!("asyncFetch"),
+ json!(1),
+ json!(RETURN),
+ ])
+ .expect("valid program");
+ let context = ExecutionContext::with_defaults(program)
+ .with_async_functions(HashSet::from(["asyncFetch".to_string()]))
+ .with_max_async_steps(1)
+ .with_telemetry();
+ let Resumable::Suspended { state, .. } = execute_resumable(&context).expect("exec") else {
+ panic!("expected suspension");
+ };
+ let telemetry = state.telemetry.expect("telemetry collected");
+ assert_eq!(telemetry[0][3], json!("33/INTEGER"));
+ assert_eq!(telemetry[0][2], json!(2));
+ assert!(telemetry.iter().any(|e| e[3] == json!("2/CALL_GLOBAL")));
+}
+
+#[test]
+fn resumes_a_node_produced_state() {
+ // A real VMState captured from the Node reference VM (@posthog/hogvm) for the open-upvalue
+ // program (let x := 5; let f := () -> x; let y := asyncFetch(0); return f() + y), suspended on
+ // asyncFetch. Rust must resume it from Node's exact wire format — reconstructing the program from
+ // the state's own `bytecodes` — and reach f() + y = 5 + 37 = 42. Frozen oracle (no Node at test
+ // time): guards the callable-ip header offset, 1-based upvalue ids, and the frame mapping so a
+ // serialize/deserialize drift can't silently break cross-VM resume.
+ let node_state = r#"{"bytecodes":{"root":{"bytecode":["_H",1,33,5,52,"lambda",0,1,3,55,0,38,53,1,true,0,33,0,2,"asyncFetch",1,36,1,54,0,6,38]}},"stack":[5,{"__hogClosure__":true,"callable":{"__hogCallable__":"local","name":"lambda","chunk":"root","argCount":0,"upvalueCount":1,"ip":9},"upvalues":[1]}],"upvalues":[{"__hogUpValue__":true,"id":1,"location":0,"closed":false,"value":null}],"callStack":[{"ip":21,"chunk":"root","stackStart":0,"argCount":0,"closure":{"__hogClosure__":true,"callable":{"__hogCallable__":"local","name":"","chunk":"root","argCount":0,"upvalueCount":0,"ip":1},"upvalues":[]}}],"throwStack":[],"declaredFunctions":{},"ops":5,"asyncSteps":1,"syncDuration":0,"maxMemUsed":267}"#;
+ let snapshot: VmSnapshot = serde_json::from_str(node_state).expect("parse node state");
+ let tokens: Vec<Value> = snapshot.bytecodes["root"]["bytecode"]
+ .as_array()
+ .expect("bytecode array")
+ .clone();
+ let program = Program::new(tokens).expect("valid program");
+ let context = ExecutionContext::with_defaults(program)
+ .with_async_functions(HashSet::from(["asyncFetch".to_string()]))
+ .with_max_async_steps(4);
+ match resume(&context, &snapshot, json!(37)).expect("resume") {
+ Resumable::Finished(v) => assert_eq!(v, json!(42)),
+ Resumable::Suspended { .. } => panic!("unexpected re-suspension"),
+ }
+}
+
+#[test]
+fn sync_execution_rejects_async() {
+ // A registered async function under the sync driver can't suspend; with the default budget the
+ // resumable driver also refuses. This guards that async never silently no-ops in a sync consumer.
+ let program = Program::new(vec![
+ json!("_H"),
+ json!(1),
+ json!(INTEGER),
+ json!(0),
+ json!(CALL_GLOBAL),
+ json!("asyncFetch"),
+ json!(1),
+ json!(RETURN),
+ ])
+ .expect("valid program");
+ // max_async_steps defaults to 0: the first suspension exceeds the budget and errors.
+ let context = ExecutionContext::with_defaults(program)
+ .with_async_functions(HashSet::from(["asyncFetch".to_string()]));
+ assert!(execute_resumable(&context).is_err());
+}
diff --git a/rust/common/hogvm/tests/large_literals.rs b/rust/common/hogvm/tests/large_literals.rs
new file mode 100644
index 000000000000..f930b8c15707
--- /dev/null
+++ b/rust/common/hogvm/tests/large_literals.rs
@@ -0,0 +1,33 @@
+//! Regression for the operand-stack ceiling: building a large array literal must not overflow the
+//! operand stack. The reference (Node) VM has no operand-stack limit, but the Rust VM's old default
+//! of 128 tripped valid programs that push many values at once (surfaced by replaying production hog
+//! functions). `with_defaults` now uses a non-binding ceiling.
+
+use hogvm::{sync_execute, ExecutionContext, Program};
+use serde_json::json;
+
+// Opcode numeric values (mirror common/hogvm/python/operation.py).
+const OP_CALL_GLOBAL: i64 = 2;
+const OP_INTEGER: i64 = 33;
+const OP_RETURN: i64 = 38;
+const OP_ARRAY: i64 = 43;
+
+#[test]
+fn large_array_literal_does_not_overflow() {
+ // Push N integers (peak operand stack = N, well past the old 128 cap), build an array from them,
+ // and return its length.
+ const N: i64 = 500;
+ let mut bc = vec![json!("_H"), json!(1)];
+ for i in 0..N {
+ bc.push(json!(OP_INTEGER));
+ bc.push(json!(i));
+ }
+ bc.extend([json!(OP_ARRAY), json!(N)]);
+ bc.extend([json!(OP_CALL_GLOBAL), json!("length"), json!(1)]);
+ bc.push(json!(OP_RETURN));
+
+ let program = Program::new(bc).expect("valid program");
+ let ctx = ExecutionContext::with_defaults(program).with_globals(json!({}));
+ let result = sync_execute(&ctx, false).expect("execution succeeds");
+ assert_eq!(result, json!(N));
+}
diff --git a/rust/common/hogvm/tests/parity.rs b/rust/common/hogvm/tests/parity.rs
new file mode 100644
index 000000000000..998002dd6a7a
--- /dev/null
+++ b/rust/common/hogvm/tests/parity.rs
@@ -0,0 +1,281 @@
+//! Correctness parity harness — the engine of the "HogVM in Rust" loop.
+//!
+//! For every program in the shared reference corpus (`common/hogvm/__tests__/*.hog`) it:
+//! 1. loads the committed `.hoge` bytecode snapshot,
+//! 2. runs it through this Rust VM with a `print` that formats values canonically,
+//! 3. diffs the captured output against the committed Node oracle
+//! (`__snapshots__/<name>.stdout.nodejs`, falling back to `<name>.stdout`).
+//!
+//! Each program lands in one of three buckets: PASS (output matches Node), MISMATCH
+//! (ran but diverged — a real parity bug), or ERROR (the VM bailed — usually an
+//! unimplemented opcode or STL function). The aggregated ERROR/MISMATCH reasons ARE the
+//! loop backlog: every distinct "Unknown function X" / "Not implemented: Y" is the next
+//! thing to build.
+//!
+//! The corpus lives outside this crate, so point the harness at it with
+//! `HOGVM_CORPUS_DIR=/abs/path/to/common/hogvm/__tests__`; otherwise it walks up from the
+//! manifest dir looking for `common/hogvm/__tests__`.
+
+use std::{
+ collections::BTreeMap,
+ path::PathBuf,
+ sync::{Arc, Mutex},
+};
+
+use hogvm::{
+ native_func, print_hog_string_output, sync_execute, ExecutionContext, HogLiteral, Program,
+ VmError,
+};
+use serde_json::Value;
+
+#[derive(Debug)]
+enum Outcome {
+ Pass,
+ Mismatch {
+ expected: String,
+ actual: String,
+ },
+ Error {
+ reason: String,
+ capability: Option<String>,
+ },
+ Skipped(String),
+}
+
+fn corpus_dir() -> Option<PathBuf> {
+ if let Ok(dir) = std::env::var("HOGVM_CORPUS_DIR") {
+ let p = PathBuf::from(dir);
+ return p.is_dir().then_some(p);
+ }
+ // Walk up from the crate manifest dir looking for common/hogvm/__tests__
+ let mut cur = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
+ loop {
+ let candidate = cur.join("common/hogvm/__tests__");
+ if candidate.is_dir() {
+ return Some(candidate);
+ }
+ if !cur.pop() {
+ return None;
+ }
+ }
+}
+
+// Pull the missing-capability name out of the errors the loop cares about, so distinct
+// gaps can be tallied across the whole corpus.
+fn capability_of(err: &VmError) -> Option<String> {
+ match err {
+ VmError::UnknownFunction(name) => Some(format!("stl:{name}")),
+ VmError::NotImplemented(what) => Some(format!("op/feature:{what}")),
+ VmError::UnknownGlobal(_) => Some("global (test setup)".to_string()),
+ _ => None,
+ }
+}
+
+fn run_one(hoge_path: &PathBuf, oracle: &str) -> Outcome {
+ let code = match std::fs::read_to_string(hoge_path) {
+ Ok(c) => c,
+ Err(e) => return Outcome::Skipped(format!("unreadable .hoge: {e}")),
+ };
+ let parsed: Vec<Value> = match serde_json::from_str(&code) {
+ Ok(p) => p,
+ Err(e) => return Outcome::Skipped(format!("bad .hoge json: {e}")),
+ };
+ let program = match Program::new(parsed) {
+ Ok(p) => p,
+ Err(e) => {
+ return Outcome::Error {
+ reason: format!("{e:?}"),
+ capability: capability_of(&e),
+ }
+ }
+ };
+
+ // Capture print output the way `console.log(...args.map(printHogStringOutput))` does:
+ // args space-separated, one newline per call.
+ // Arc<Mutex> rather than Rc<RefCell> because NativeFunction requires Send + Sync.
+ let captured = Arc::new(Mutex::new(String::new()));
+ let sink = captured.clone();
+ let print_fn = native_func(move |vm, args| {
+ let mut line = String::new();
+ for (i, arg) in args.iter().enumerate() {
+ if i > 0 {
+ line.push(' ');
+ }
+ line.push_str(&print_hog_string_output(&vm.heap, arg)?);
+ }
+ line.push('\n');
+ sink.lock().unwrap().push_str(&line);
+ Ok(HogLiteral::Null.into())
+ });
+
+ // The reference VM bounds execution by a 5s timeout, not a step count; use a generous step cap
+ // so compute-heavy corpus programs (e.g. mandelbrot) can finish rather than tripping the default.
+ // The reference VMs always coerce comparison operands (unifyComparisonTypes), so enable the
+ // coercing path here to replicate reference semantics — this is the behavior we diff against.
+ let ctx = ExecutionContext::with_defaults(program)
+ .with_max_steps(50_000_000)
+ .with_coercing_comparisons()
+ .with_ext_fn("print".to_string(), print_fn);
+
+ match sync_execute(&ctx, false) {
+ Ok(_) => {
+ let actual = captured.lock().unwrap().trim_end_matches('\n').to_string();
+ let expected = oracle.trim_end_matches('\n').to_string();
+ if actual == expected {
+ Outcome::Pass
+ } else {
+ Outcome::Mismatch { expected, actual }
+ }
+ }
+ Err(failure) => Outcome::Error {
+ reason: format!("{}", failure.error),
+ capability: capability_of(&failure.error),
+ },
+ }
+}
+
+#[test]
+fn parity_report() {
+ let Some(corpus) = corpus_dir() else {
+ panic!("Could not locate common/hogvm/__tests__ — set HOGVM_CORPUS_DIR");
+ };
+ let snapshots = corpus.join("__snapshots__");
+
+ let mut programs: Vec<String> = std::fs::read_dir(&corpus)
+ .expect("read corpus dir")
+ .filter_map(|e| e.ok())
+ .filter_map(|e| e.file_name().to_str().map(str::to_string))
+ .filter(|n| n.ends_with(".hog"))
+ .map(|n| n.trim_end_matches(".hog").to_string())
+ .collect();
+ programs.sort();
+
+ let mut pass = Vec::new();
+ let mut mismatch = Vec::new();
+ let mut errored = Vec::new();
+ let mut skipped = Vec::new();
+ // capability -> programs that need it
+ let mut backlog: BTreeMap<String, Vec<String>> = BTreeMap::new();
+
+ for name in &programs {
+ let hoge = snapshots.join(format!("{name}.hoge"));
+ if !hoge.is_file() {
+ skipped.push((name.clone(), "no .hoge snapshot".to_string()));
+ continue;
+ }
+ // Node is the oracle; prefer the node-specific snapshot when Node/Python diverge.
+ let oracle_path = {
+ let nodejs = snapshots.join(format!("{name}.stdout.nodejs"));
+ if nodejs.is_file() {
+ nodejs
+ } else {
+ snapshots.join(format!("{name}.stdout"))
+ }
+ };
+ let Ok(oracle) = std::fs::read_to_string(&oracle_path) else {
+ skipped.push((name.clone(), "no oracle stdout".to_string()));
+ continue;
+ };
+
+ match run_one(&hoge, &oracle) {
+ Outcome::Pass => pass.push(name.clone()),
+ Outcome::Mismatch { expected, actual } => {
+ mismatch.push((name.clone(), expected, actual))
+ }
+ Outcome::Error { reason, capability } => {
+ if let Some(cap) = capability {
+ backlog.entry(cap).or_default().push(name.clone());
+ }
+ errored.push((name.clone(), reason));
+ }
+ Outcome::Skipped(why) => skipped.push((name.clone(), why)),
+ }
+ }
+
+ let total = programs.len();
+ println!("\n================ HogVM Rust↔Node parity report ================");
+ println!(
+ "corpus: {}\nprograms: {total} | PASS {} | MISMATCH {} | ERROR {} | SKIP {}",
+ corpus.display(),
+ pass.len(),
+ mismatch.len(),
+ errored.len(),
+ skipped.len()
+ );
+
+ println!("\n-- PASS ({}) --", pass.len());
+ println!(" {}", pass.join(", "));
+
+ println!(
+ "\n-- MISMATCH ({}) — ran but diverged from Node (parity bugs) --",
+ mismatch.len()
+ );
+ for (name, expected, actual) in &mismatch {
+ let (line_no, exp, act) = first_diff(expected, actual);
+ println!(" {name} (first diff at line {line_no})\n node: {exp}\n rust: {act}");
+ }
+
+ println!(
+ "\n-- ERROR ({}) — VM bailed (usually unimplemented) --",
+ errored.len()
+ );
+ for (name, reason) in &errored {
+ println!(" {name}: {reason}");
+ }
+
+ println!("\n-- BACKLOG (missing capabilities, by program count) --");
+ let mut ranked: Vec<(&String, &Vec<String>)> = backlog.iter().collect();
+ ranked.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then(a.0.cmp(b.0)));
+ for (cap, progs) in ranked {
+ println!(" [{}] {} ({})", progs.len(), cap, progs.join(", "));
+ }
+
+ if !skipped.is_empty() {
+ println!("\n-- SKIPPED ({}) --", skipped.len());
+ for (name, why) in &skipped {
+ println!(" {name}: {why}");
+ }
+ }
+ println!("===============================================================\n");
+
+ // Regression gate: the Rust VM must match Node on every committed corpus program. The whole
+ // corpus passes today (36/36), so any mismatch (ran but diverged) or error (VM bailed) is a
+ // real parity regression and fails the test.
+ assert!(total > 0, "no corpus programs found");
+ assert!(
+ mismatch.is_empty() && errored.is_empty(),
+ "corpus parity regressed: {} mismatch(es), {} error(s) vs Node — see report above",
+ mismatch.len(),
+ errored.len()
+ );
+}
+
+// Find the first line where expected and actual diverge, returning (1-based line, exp, act).
+fn first_diff(expected: &str, actual: &str) -> (usize, String, String) {
+ let mut exp_lines = expected.lines();
+ let mut act_lines = actual.lines();
+ let mut n = 0;
+ loop {
+ n += 1;
+ match (exp_lines.next(), act_lines.next()) {
+ (None, None) => return (n, "<eof>".to_string(), "<eof>".to_string()),
+ (e, a) => {
+ let e = e.unwrap_or("<eof>");
+ let a = a.unwrap_or("<eof>");
+ if e != a {
+ return (n, clip(e), clip(a));
+ }
+ }
+ }
+ }
+}
+
+fn clip(line: &str) -> String {
+ let limit = 200;
+ if line.chars().count() > limit {
+ let truncated: String = line.chars().take(limit).collect();
+ format!("{truncated}…")
+ } else {
+ line.to_string()
+ }
+}
diff --git a/rust/common/hogvm/tests/printer.rs b/rust/common/hogvm/tests/printer.rs
new file mode 100644
index 000000000000..62ad03b347de
--- /dev/null
+++ b/rust/common/hogvm/tests/printer.rs
@@ -0,0 +1,24 @@
+//! Direct coverage for the canonical value printer's string escaping (`print.rs`), which renders
+//! Hog string literals the way the reference VMs do for `sql`/`print` output. Pure and known-answer,
+//! so it pins the escaping rules without standing up a VM heap.
+
+use hogvm::escape_string;
+
+#[test]
+fn escapes_quotes_backslashes_and_control_chars() {
+ let cases: &[(&str, &str)] = &[
+ ("hi", "'hi'"),
+ ("", "''"),
+ ("it's", r"'it\'s'"),
+ (r"a\b", r"'a\\b'"),
+ ("line\nbreak", r"'line\nbreak'"),
+ ("tab\there", r"'tab\there'"),
+ ("carriage\rreturn", r"'carriage\rreturn'"),
+ ("null\0byte", r"'null\0byte'"),
+ // Non-control Unicode passes through untouched, only wrapped in quotes.
+ ("café 🦔", "'café 🦔'"),
+ ];
+ for (input, expected) in cases {
+ assert_eq!(escape_string(input), *expected, "escape_string({input:?})");
+ }
+}
diff --git a/rust/common/hogvm/tests/static/stl_oracle.jsonl b/rust/common/hogvm/tests/static/stl_oracle.jsonl
new file mode 100644
index 000000000000..4d3af3dcdfae
--- /dev/null
+++ b/rust/common/hogvm/tests/static/stl_oracle.jsonl
@@ -0,0 +1,125 @@
+{"fn":"concat","label":"concat#0","match":"exact","bytecode":["_H",1,32,"a",32,"b",32,"c",2,"concat",3,2,"print",1],"expected":"abc"}
+{"fn":"concat","label":"concat#1","match":"exact","bytecode":["_H",1,33,1,31,32,"x",2,"concat",3,2,"print",1],"expected":"1x"}
+{"fn":"lower","label":"lower#0","match":"exact","bytecode":["_H",1,32,"HeLLo",2,"lower",1,2,"print",1],"expected":"hello"}
+{"fn":"upper","label":"upper#0","match":"exact","bytecode":["_H",1,32,"HeLLo",2,"upper",1,2,"print",1],"expected":"HELLO"}
+{"fn":"reverse","label":"reverse#0","match":"exact","bytecode":["_H",1,32,"abc",2,"reverse",1,2,"print",1],"expected":"cba"}
+{"fn":"trim","label":"trim#0","match":"exact","bytecode":["_H",1,32," hi ",2,"trim",1,2,"print",1],"expected":"hi"}
+{"fn":"trimLeft","label":"trimLeft#0","match":"exact","bytecode":["_H",1,32," hi ",2,"trimLeft",1,2,"print",1],"expected":"hi "}
+{"fn":"trimRight","label":"trimRight#0","match":"exact","bytecode":["_H",1,32," hi ",2,"trimRight",1,2,"print",1],"expected":" hi"}
+{"fn":"substring","label":"substring#0","match":"exact","bytecode":["_H",1,32,"hello world",33,1,33,5,2,"substring",3,2,"print",1],"expected":"hello"}
+{"fn":"replaceOne","label":"replaceOne#0","match":"exact","bytecode":["_H",1,32,"hello",32,"l",32,"L",2,"replaceOne",3,2,"print",1],"expected":"heLlo"}
+{"fn":"replaceAll","label":"replaceAll#0","match":"exact","bytecode":["_H",1,32,"hello",32,"l",32,"L",2,"replaceAll",3,2,"print",1],"expected":"heLLo"}
+{"fn":"splitByString","label":"splitByString#0","match":"exact","bytecode":["_H",1,32,",",32,"a,b,c",2,"splitByString",2,2,"print",1],"expected":"['a', 'b', 'c']"}
+{"fn":"startsWith","label":"startsWith#0","match":"exact","bytecode":["_H",1,32,"hello",32,"he",2,"startsWith",2,2,"print",1],"expected":"true"}
+{"fn":"position","label":"position#0","match":"exact","bytecode":["_H",1,32,"hello",32,"l",2,"position",2,2,"print",1],"expected":"3"}
+{"fn":"positionCaseInsensitive","label":"positionCaseInsensitive#0","match":"exact","bytecode":["_H",1,32,"heLLo",32,"l",2,"positionCaseInsensitive",2,2,"print",1],"expected":"3"}
+{"fn":"encodeURLComponent","label":"encodeURLComponent#0","match":"exact","bytecode":["_H",1,32,"a b&c=d",2,"encodeURLComponent",1,2,"print",1],"expected":"a%20b%26c%3Dd"}
+{"fn":"decodeURLComponent","label":"decodeURLComponent#0","match":"exact","bytecode":["_H",1,32,"a%20b%26c",2,"decodeURLComponent",1,2,"print",1],"expected":"a b&c"}
+{"fn":"base64Encode","label":"base64Encode#0","match":"exact","bytecode":["_H",1,32,"hello",2,"base64Encode",1,2,"print",1],"expected":"aGVsbG8="}
+{"fn":"base64Decode","label":"base64Decode#0","match":"exact","bytecode":["_H",1,32,"aGVsbG8=",2,"base64Decode",1,2,"print",1],"expected":"hello"}
+{"fn":"tryDecodeURLComponent","label":"tryDecodeURLComponent#0","match":"exact","bytecode":["_H",1,32,"a%20b",2,"tryDecodeURLComponent",1,2,"print",1],"expected":"a b"}
+{"fn":"length","label":"length#0","match":"exact","bytecode":["_H",1,32,"hello",2,"length",1,2,"print",1],"expected":"5"}
+{"fn":"length","label":"length#1","match":"exact","bytecode":["_H",1,33,1,33,2,33,3,43,3,2,"length",1,2,"print",1],"expected":"3"}
+{"fn":"empty","label":"empty#0","match":"exact","bytecode":["_H",1,32,"",2,"empty",1,2,"print",1],"expected":"true"}
+{"fn":"empty","label":"empty#1","match":"exact","bytecode":["_H",1,43,0,2,"empty",1,2,"print",1],"expected":"true"}
+{"fn":"empty","label":"empty#2","match":"exact","bytecode":["_H",1,33,0,2,"empty",1,2,"print",1],"expected":"false"}
+{"fn":"notEmpty","label":"notEmpty#0","match":"exact","bytecode":["_H",1,32,"x",2,"notEmpty",1,2,"print",1],"expected":"true"}
+{"fn":"notEmpty","label":"notEmpty#1","match":"exact","bytecode":["_H",1,43,0,2,"notEmpty",1,2,"print",1],"expected":"false"}
+{"fn":"keys","label":"keys#0","match":"exact","bytecode":["_H",1,32,"a",33,1,32,"b",33,2,42,2,2,"keys",1,2,"print",1],"expected":"['a', 'b']"}
+{"fn":"values","label":"values#0","match":"exact","bytecode":["_H",1,32,"a",33,1,32,"b",33,2,42,2,2,"values",1,2,"print",1],"expected":"[1, 2]"}
+{"fn":"has","label":"has#0","match":"exact","bytecode":["_H",1,33,1,33,2,33,3,43,3,33,2,2,"has",2,2,"print",1],"expected":"true"}
+{"fn":"indexOf","label":"indexOf#0","match":"exact","bytecode":["_H",1,33,10,33,20,33,30,43,3,33,20,2,"indexOf",2,2,"print",1],"expected":"2"}
+{"fn":"arrayPushBack","label":"arrayPushBack#0","match":"exact","bytecode":["_H",1,33,1,33,2,43,2,33,3,2,"arrayPushBack",2,2,"print",1],"expected":"[1, 2, 3]"}
+{"fn":"arrayPushFront","label":"arrayPushFront#0","match":"exact","bytecode":["_H",1,33,1,33,2,43,2,33,0,2,"arrayPushFront",2,2,"print",1],"expected":"[0, 1, 2]"}
+{"fn":"arrayPopBack","label":"arrayPopBack#0","match":"exact","bytecode":["_H",1,33,1,33,2,33,3,43,3,2,"arrayPopBack",1,2,"print",1],"expected":"[1, 2]"}
+{"fn":"arrayPopFront","label":"arrayPopFront#0","match":"exact","bytecode":["_H",1,33,1,33,2,33,3,43,3,2,"arrayPopFront",1,2,"print",1],"expected":"[2, 3]"}
+{"fn":"arraySort","label":"arraySort#0","match":"exact","bytecode":["_H",1,33,3,33,1,33,2,43,3,2,"arraySort",1,2,"print",1],"expected":"[1, 2, 3]"}
+{"fn":"arrayReverse","label":"arrayReverse#0","match":"exact","bytecode":["_H",1,33,1,33,2,33,3,43,3,2,"arrayReverse",1,2,"print",1],"expected":"[3, 2, 1]"}
+{"fn":"arrayReverseSort","label":"arrayReverseSort#0","match":"exact","bytecode":["_H",1,33,1,33,3,33,2,43,3,2,"arrayReverseSort",1,2,"print",1],"expected":"[3, 2, 1]"}
+{"fn":"arrayStringConcat","label":"arrayStringConcat#0","match":"exact","bytecode":["_H",1,33,1,33,2,33,3,43,3,32,"-",2,"arrayStringConcat",2,2,"print",1],"expected":"1-2-3"}
+{"fn":"tuple","label":"tuple#0","match":"exact","bytecode":["_H",1,33,1,32,"a",29,2,"tuple",3,2,"print",1],"expected":"(1, 'a', true)"}
+{"fn":"range","label":"range#0","match":"exact","bytecode":["_H",1,33,5,2,"range",1,2,"print",1],"expected":"[0, 1, 2, 3, 4]"}
+{"fn":"range","label":"range#1","match":"exact","bytecode":["_H",1,33,2,33,6,2,"range",2,2,"print",1],"expected":"[2, 3, 4, 5]"}
+{"fn":"round","label":"round#0","match":"exact","bytecode":["_H",1,34,2.5,2,"round",1,2,"print",1],"expected":"2"}
+{"fn":"round","label":"round#1","match":"exact","bytecode":["_H",1,34,2.4,2,"round",1,2,"print",1],"expected":"2"}
+{"fn":"floor","label":"floor#0","match":"exact","bytecode":["_H",1,34,2.9,2,"floor",1,2,"print",1],"expected":"2"}
+{"fn":"min2","label":"min2#0","match":"exact","bytecode":["_H",1,33,3,33,5,2,"min2",2,2,"print",1],"expected":"3"}
+{"fn":"max2","label":"max2#0","match":"exact","bytecode":["_H",1,33,3,33,5,2,"max2",2,2,"print",1],"expected":"5"}
+{"fn":"toInt","label":"toInt#0","match":"exact","bytecode":["_H",1,32,"42",2,"toInt",1,2,"print",1],"expected":"42"}
+{"fn":"toInt","label":"toInt#1","match":"exact","bytecode":["_H",1,34,3.9,2,"toInt",1,2,"print",1],"expected":"3"}
+{"fn":"toFloat","label":"toFloat#0","match":"exact","bytecode":["_H",1,32,"3.14",2,"toFloat",1,2,"print",1],"expected":"3.14"}
+{"fn":"toString","label":"toString#0","match":"exact","bytecode":["_H",1,33,42,2,"toString",1,2,"print",1],"expected":"42"}
+{"fn":"toString","label":"toString#1","match":"exact","bytecode":["_H",1,29,2,"toString",1,2,"print",1],"expected":"true"}
+{"fn":"toString","label":"toString#2","match":"exact","bytecode":["_H",1,33,1,32,"2",33,3,43,3,2,"toString",1,2,"print",1],"expected":"[1, '2', 3]"}
+{"fn":"toString","label":"toString#3","match":"exact","bytecode":["_H",1,31,2,"toString",1,2,"print",1],"expected":"null"}
+{"fn":"typeof","label":"typeof#0","match":"exact","bytecode":["_H",1,33,1,2,"typeof",1,2,"print",1],"expected":"integer"}
+{"fn":"typeof","label":"typeof#1","match":"exact","bytecode":["_H",1,32,"x",2,"typeof",1,2,"print",1],"expected":"string"}
+{"fn":"typeof","label":"typeof#2","match":"exact","bytecode":["_H",1,33,1,43,1,2,"typeof",1,2,"print",1],"expected":"array"}
+{"fn":"typeof","label":"typeof#3","match":"exact","bytecode":["_H",1,32,"a",33,1,42,1,2,"typeof",1,2,"print",1],"expected":"object"}
+{"fn":"typeof","label":"typeof#4","match":"exact","bytecode":["_H",1,31,2,"typeof",1,2,"print",1],"expected":"null"}
+{"fn":"ifNull","label":"ifNull#0","match":"exact","bytecode":["_H",1,31,32,"x",2,"ifNull",2,2,"print",1],"expected":"x"}
+{"fn":"ifNull","label":"ifNull#1","match":"exact","bytecode":["_H",1,32,"y",32,"x",2,"ifNull",2,2,"print",1],"expected":"y"}
+{"fn":"coalesce","label":"coalesce#0","match":"exact","bytecode":["_H",1,31,31,33,3,2,"coalesce",3,2,"print",1],"expected":"3"}
+{"fn":"assumeNotNull","label":"assumeNotNull#0","match":"exact","bytecode":["_H",1,33,5,2,"assumeNotNull",1,2,"print",1],"expected":"5"}
+{"fn":"isNull","label":"isNull#0","match":"exact","bytecode":["_H",1,31,2,"isNull",1,2,"print",1],"expected":"true"}
+{"fn":"isNull","label":"isNull#1","match":"exact","bytecode":["_H",1,33,1,2,"isNull",1,2,"print",1],"expected":"false"}
+{"fn":"isNotNull","label":"isNotNull#0","match":"exact","bytecode":["_H",1,31,2,"isNotNull",1,2,"print",1],"expected":"false"}
+{"fn":"isNotNull","label":"isNotNull#1","match":"exact","bytecode":["_H",1,33,1,2,"isNotNull",1,2,"print",1],"expected":"true"}
+{"fn":"jsonStringify","label":"jsonStringify#0","match":"exact","bytecode":["_H",1,32,"a",33,1,32,"b",33,2,33,3,43,2,42,2,2,"jsonStringify",1,2,"print",1],"expected":"{\"a\": 1, \"b\": [2, 3]}"}
+{"fn":"jsonParse","label":"jsonParse#0","match":"exact","bytecode":["_H",1,32,"{\"a\":1,\"b\":[2,3]}",2,"jsonParse",1,2,"print",1],"expected":"{'a': 1, 'b': [2, 3]}"}
+{"fn":"isValidJSON","label":"isValidJSON#0","match":"exact","bytecode":["_H",1,32,"{\"a\":1}",2,"isValidJSON",1,2,"print",1],"expected":"true"}
+{"fn":"isValidJSON","label":"isValidJSON#1","match":"exact","bytecode":["_H",1,32,"nope",2,"isValidJSON",1,2,"print",1],"expected":"false"}
+{"fn":"JSONHas","label":"JSONHas#0","match":"exact","bytecode":["_H",1,32,"a",33,1,42,1,32,"a",2,"JSONHas",2,2,"print",1],"expected":"true"}
+{"fn":"JSONHas","label":"JSONHas#1","match":"exact","bytecode":["_H",1,32,"a",33,1,42,1,32,"z",2,"JSONHas",2,2,"print",1],"expected":"false"}
+{"fn":"JSONLength","label":"JSONLength#0","match":"exact","bytecode":["_H",1,32,"a",33,1,32,"b",33,2,42,2,2,"JSONLength",1,2,"print",1],"expected":"2"}
+{"fn":"JSONExtractString","label":"JSONExtractString#0","match":"exact","bytecode":["_H",1,32,"{\"a\":\"x\"}",32,"a",2,"JSONExtractString",2,2,"print",1],"expected":"x"}
+{"fn":"JSONExtractInt","label":"JSONExtractInt#0","match":"exact","bytecode":["_H",1,32,"{\"a\":7}",32,"a",2,"JSONExtractInt",2,2,"print",1],"expected":"7"}
+{"fn":"JSONExtractFloat","label":"JSONExtractFloat#0","match":"exact","bytecode":["_H",1,32,"{\"a\":1.5}",32,"a",2,"JSONExtractFloat",2,2,"print",1],"expected":"1.5"}
+{"fn":"JSONExtractBool","label":"JSONExtractBool#0","match":"exact","bytecode":["_H",1,32,"{\"a\":true}",32,"a",2,"JSONExtractBool",2,2,"print",1],"expected":"true"}
+{"fn":"JSONExtract","label":"JSONExtract#0","match":"exact","bytecode":["_H",1,32,"{\"a\":{\"b\":7}}",32,"a",32,"b",2,"JSONExtract",3,2,"print",1],"expected":"{'b': 7}"}
+{"fn":"JSONExtractArrayRaw","label":"JSONExtractArrayRaw#0","match":"exact","bytecode":["_H",1,32,"[1,2,3]",2,"JSONExtractArrayRaw",1,2,"print",1],"expected":"[1, 2, 3]"}
+{"fn":"match","label":"match#0","match":"exact","bytecode":["_H",1,32,"fish",32,"fi",2,"match",2,2,"print",1],"expected":"true"}
+{"fn":"extractRegex","label":"extractRegex#0","match":"exact","bytecode":["_H",1,32,"abc123",32,"\\d+",2,"extractRegex",2,2,"print",1],"expected":"123"}
+{"fn":"multiSearchAnyCaseInsensitive","label":"multiSearchAnyCaseInsensitive#0","match":"exact","bytecode":["_H",1,32,"Hello World",32,"foo",32,"world",43,2,2,"multiSearchAnyCaseInsensitive",2,2,"print",1],"expected":"1"}
+{"fn":"md5Hex","label":"md5Hex#0","match":"exact","bytecode":["_H",1,32,"hello",2,"md5Hex",1,2,"print",1],"expected":"5d41402abc4b2a76b9719d911017c592"}
+{"fn":"md5","label":"md5#0","match":"exact","bytecode":["_H",1,32,"hello",32,"hex",2,"md5",2,2,"print",1],"expected":"5d41402abc4b2a76b9719d911017c592"}
+{"fn":"sha256Hex","label":"sha256Hex#0","match":"exact","bytecode":["_H",1,32,"hello",2,"sha256Hex",1,2,"print",1],"expected":"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"}
+{"fn":"sha256","label":"sha256#0","match":"exact","bytecode":["_H",1,32,"hello",32,"hex",2,"sha256",2,2,"print",1],"expected":"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"}
+{"fn":"sha256HmacChain","label":"sha256HmacChain#0","match":"exact","bytecode":["_H",1,32,"key",32,"data",43,2,2,"sha256HmacChain",1,2,"print",1],"expected":"5031fe3d989c6d1537a013fa6e739da23463fdaec3b70137d828e36ace221bd0"}
+{"fn":"sha256HmacChainHex","label":"sha256HmacChainHex#0","match":"exact","bytecode":["_H",1,32,"key",32,"data",43,2,2,"sha256HmacChainHex",1,2,"print",1],"expected":"5031fe3d989c6d1537a013fa6e739da23463fdaec3b70137d828e36ace221bd0"}
+{"fn":"toUUID","label":"toUUID#0","match":"exact","bytecode":["_H",1,32,"123e4567-e89b-12d3-a456-426614174000",2,"toUUID",1,2,"print",1],"expected":"123e4567-e89b-12d3-a456-426614174000"}
+{"fn":"isIPAddressInRange","label":"isIPAddressInRange#0","match":"exact","bytecode":["_H",1,32,"192.168.1.5",32,"192.168.1.0/24",2,"isIPAddressInRange",2,2,"print",1],"expected":"true"}
+{"fn":"isIPAddressInRange","label":"isIPAddressInRange#1","match":"exact","bytecode":["_H",1,32,"10.0.0.1",32,"192.168.1.0/24",2,"isIPAddressInRange",2,2,"print",1],"expected":"false"}
+{"fn":"toDateTime","label":"toDateTime#0","match":"exact","bytecode":["_H",1,32,"2021-01-01 12:34:56",2,"toDateTime",1,2,"print",1],"expected":"DateTime(1609504496.0, 'UTC')"}
+{"fn":"toDateTime","label":"toDateTime#1","match":"exact","bytecode":["_H",1,33,1700000000,2,"toDateTime",1,2,"print",1],"expected":"DateTime(1700000000.0, 'UTC')"}
+{"fn":"toDate","label":"toDate#0","match":"exact","bytecode":["_H",1,32,"2021-06-15",2,"toDate",1,2,"print",1],"expected":"Date(2021, 6, 15)"}
+{"fn":"fromUnixTimestamp","label":"fromUnixTimestamp#0","match":"exact","bytecode":["_H",1,33,1700000000,2,"fromUnixTimestamp",1,2,"print",1],"expected":"DateTime(1700000000.0, 'UTC')"}
+{"fn":"toUnixTimestamp","label":"toUnixTimestamp#0","match":"exact","bytecode":["_H",1,32,"2021-01-01 12:34:56",2,"toDateTime",1,2,"toUnixTimestamp",1,2,"print",1],"expected":"1609504496.0"}
+{"fn":"toYear","label":"toYear#0","match":"exact","bytecode":["_H",1,32,"2021-01-01 12:34:56",2,"toDateTime",1,2,"toYear",1,2,"print",1],"expected":"2021"}
+{"fn":"toMonth","label":"toMonth#0","match":"exact","bytecode":["_H",1,32,"2021-01-01 12:34:56",2,"toDateTime",1,2,"toMonth",1,2,"print",1],"expected":"1"}
+{"fn":"toStartOfDay","label":"toStartOfDay#0","match":"exact","bytecode":["_H",1,32,"2021-01-01 12:34:56",2,"toDateTime",1,2,"toStartOfDay",1,2,"print",1],"expected":"DateTime(1609459200.0, 'UTC')"}
+{"fn":"toStartOfMonth","label":"toStartOfMonth#0","match":"exact","bytecode":["_H",1,32,"2021-01-01 12:34:56",2,"toDateTime",1,2,"toStartOfMonth",1,2,"print",1],"expected":"DateTime(1609459200.0, 'UTC')"}
+{"fn":"formatDateTime","label":"formatDateTime#0","match":"exact","bytecode":["_H",1,32,"2021-01-01 12:34:56",2,"toDateTime",1,32,"%Y-%m-%d",2,"formatDateTime",2,2,"print",1],"expected":"2021-01-01"}
+{"fn":"dateDiff","label":"dateDiff#0","match":"exact","bytecode":["_H",1,32,"day",32,"2021-01-01 12:34:56",2,"toDateTime",1,32,"2021-01-05 12:34:56",2,"toDateTime",1,2,"dateDiff",3,2,"print",1],"expected":"4"}
+{"fn":"dateAdd","label":"dateAdd#0","match":"exact","bytecode":["_H",1,32,"day",33,3,32,"2021-01-01 12:34:56",2,"toDateTime",1,2,"dateAdd",3,2,"print",1],"expected":"DateTime(1609763696.0, 'UTC')"}
+{"fn":"addDays","label":"addDays#0","match":"exact","bytecode":["_H",1,32,"2021-01-01 12:34:56",2,"toDateTime",1,33,3,2,"addDays",2,2,"print",1],"expected":"DateTime(1609763696.0, 'UTC')"}
+{"fn":"dateTrunc","label":"dateTrunc#0","match":"exact","bytecode":["_H",1,32,"day",32,"2021-01-01 12:34:56",2,"toDateTime",1,2,"dateTrunc",2,2,"print",1],"expected":"DateTime(1609459200.0, 'UTC')"}
+{"fn":"toStartOfHour","label":"toStartOfHour#0","match":"exact","bytecode":["_H",1,32,"2021-01-01 12:34:56",2,"toDateTime",1,2,"toStartOfHour",1,2,"print",1],"expected":"DateTime(1609502400.0, 'UTC')"}
+{"fn":"toStartOfWeek","label":"toStartOfWeek#0","match":"exact","bytecode":["_H",1,32,"2021-01-01 12:34:56",2,"toDateTime",1,2,"toStartOfWeek",1,2,"print",1],"expected":"DateTime(1609113600.0, 'UTC')"}
+{"fn":"toTimeZone","label":"toTimeZone#0","match":"exact","bytecode":["_H",1,32,"2021-01-01 12:34:56",2,"toDateTime",1,32,"America/New_York",2,"toTimeZone",2,2,"print",1],"expected":"DateTime(1609504496.0, 'America/New_York')"}
+{"fn":"toYYYYMM","label":"toYYYYMM#0","match":"exact","bytecode":["_H",1,32,"2021-01-01 12:34:56",2,"toDateTime",1,2,"toYYYYMM",1,2,"print",1],"expected":"202101"}
+{"fn":"toUnixTimestampMilli","label":"toUnixTimestampMilli#0","match":"exact","bytecode":["_H",1,32,"2021-01-01 12:34:56",2,"toDateTime",1,2,"toUnixTimestampMilli",1,2,"print",1],"expected":"1609504496000"}
+{"fn":"fromUnixTimestampMilli","label":"fromUnixTimestampMilli#0","match":"exact","bytecode":["_H",1,33,1700000000123,2,"fromUnixTimestampMilli",1,2,"print",1],"expected":"DateTime(1700000000.123, 'UTC')"}
+{"fn":"toIntervalDay","label":"toIntervalDay#0","match":"exact","bytecode":["_H",1,33,3,2,"toIntervalDay",1,2,"print",1],"expected":"{'__hogInterval__': true, 'value': 3, 'unit': 'day'}"}
+{"fn":"toIntervalHour","label":"toIntervalHour#0","match":"exact","bytecode":["_H",1,33,2,2,"toIntervalHour",1,2,"print",1],"expected":"{'__hogInterval__': true, 'value': 2, 'unit': 'hour'}"}
+{"fn":"toIntervalMinute","label":"toIntervalMinute#0","match":"exact","bytecode":["_H",1,33,30,2,"toIntervalMinute",1,2,"print",1],"expected":"{'__hogInterval__': true, 'value': 30, 'unit': 'minute'}"}
+{"fn":"toIntervalMonth","label":"toIntervalMonth#0","match":"exact","bytecode":["_H",1,33,1,2,"toIntervalMonth",1,2,"print",1],"expected":"{'__hogInterval__': true, 'value': 1, 'unit': 'month'}"}
+{"fn":"sortableSemver","label":"sortableSemver#0","match":"exact","bytecode":["_H",1,32,"1.20.3",2,"sortableSemver",1,2,"print",1],"expected":"[1, 20, 3]"}
+{"fn":"Error","label":"Error#0","match":"exact","bytecode":["_H",1,32,"boom",2,"Error",1,2,"print",1],"expected":"Error('boom')"}
+{"fn":"HogError","label":"HogError#0","match":"exact","bytecode":["_H",1,32,"MyError",32,"boom",2,"HogError",2,2,"print",1],"expected":"MyError('boom')"}
+{"fn":"RetryError","label":"RetryError#0","match":"exact","bytecode":["_H",1,32,"retry me",2,"RetryError",1,2,"print",1],"expected":"RetryError('retry me')"}
+{"fn":"NotImplementedError","label":"NotImplementedError#0","match":"exact","bytecode":["_H",1,32,"nope",2,"NotImplementedError",1,2,"print",1],"expected":"NotImplementedError('nope')"}
+{"fn":"now","label":"now#0","match":"smoke","bytecode":["_H",1,2,"now",0,2,"print",1],"expected":""}
+{"fn":"today","label":"today#0","match":"smoke","bytecode":["_H",1,2,"today",0,2,"print",1],"expected":""}
+{"fn":"randomFloat","label":"randomFloat#0","match":"smoke","bytecode":["_H",1,2,"randomFloat",0,2,"print",1],"expected":""}
+{"fn":"generateUUIDv4","label":"generateUUIDv4#0","match":"smoke","bytecode":["_H",1,2,"generateUUIDv4",0,2,"print",1],"expected":""}
diff --git a/rust/common/hogvm/tests/static/test_programs/arrays.hog b/rust/common/hogvm/tests/static/test_programs/arrays.hog
index ac2e2159fb00..0d7bce23eb69 100644
--- a/rust/common/hogvm/tests/static/test_programs/arrays.hog
+++ b/rust/common/hogvm/tests/static/test_programs/arrays.hog
@@ -57,14 +57,14 @@ assert_eq(arr, [1,2,3,4])
assert_eq(has(arr, 0), false)
assert_eq(has(arr, 2), true)
assert_eq(has(arr, 'banana'), false)
-assert_eq(has('banananas', 'banana'), true)
+assert_eq(has('banananas', 'banana'), false)
assert_eq(has('banananas', 'foo'), false)
assert_eq(has(['1', '2'], '1'), true)
assert_eq(indexOf([1,2,3], 1), 1)
assert_eq(indexOf([1,2,3], 2), 2)
assert_eq(indexOf([1,2,3], 3), 3)
-assert_eq(indexOf([1,2,3], 4), null)
+assert_eq(indexOf([1,2,3], 4), 0)
// This is part of the "hog STL" in other impls
fun arrayCount(func, arr) {
diff --git a/rust/common/hogvm/tests/static/test_programs/arrays.hoge b/rust/common/hogvm/tests/static/test_programs/arrays.hoge
index 0d414a8d8ad6..f8cad5b6b956 100644
--- a/rust/common/hogvm/tests/static/test_programs/arrays.hoge
+++ b/rust/common/hogvm/tests/static/test_programs/arrays.hoge
@@ -1,38 +1,38 @@
-["_H", 1, 33, 1, 33, 2, 33, 3, 43, 3, 36, 0, 33, 2, 45, 33, 2, 2, "assert_eq", 2, 35, 36, 0, 33, 2, 48, 33, 2, 2,
-"assert_eq", 2, 35, 36, 0, 33, 2, 48, 33, 2, 2, "assert_eq", 2, 35, 36, 0, 33, 7, 48, 31, 2, "assert_eq", 2, 35, 36, 0,
-33, 7, 48, 31, 2, "assert_eq", 2, 35, 33, 1, 33, 2, 33, 3, 43, 3, 33, 2, 45, 33, 2, 2, "assert_eq", 2, 35, 33, 1, 33, 2,
-33, 3, 33, 4, 43, 2, 43, 2, 33, 5, 43, 3, 33, 2, 45, 33, 2, 45, 33, 2, 45, 33, 4, 2, "assert_eq", 2, 35, 33, 1, 33, 2,
-33, 3, 33, 4, 43, 2, 43, 2, 33, 5, 43, 3, 33, 2, 48, 33, 2, 48, 33, 2, 48, 33, 4, 2, "assert_eq", 2, 35, 33, 1, 33, 2,
-33, 3, 33, 4, 43, 2, 43, 2, 33, 5, 43, 3, 33, 2, 48, 33, 2, 48, 33, 2, 48, 33, 4, 2, "assert_eq", 2, 35, 33, 1, 33, 2,
-33, 3, 33, 4, 43, 2, 43, 2, 33, 5, 43, 3, 33, 7, 48, 33, 4, 48, 33, 2, 48, 31, 2, "assert_eq", 2, 35, 33, 1, 33, 2, 33,
-3, 33, 4, 43, 2, 43, 2, 33, 5, 43, 3, 33, 7, 48, 33, 4, 48, 33, 2, 48, 31, 2, "assert_eq", 2, 35, 33, 1, 33, 1, 33, 2,
-33, 3, 33, 4, 43, 2, 43, 2, 33, 5, 43, 3, 33, 2, 45, 33, 2, 45, 33, 2, 45, 6, 33, 5, 2, "assert_eq", 2, 35, 33, 1, 33,
-2, 33, 3, 33, 4, 43, 2, 43, 2, 33, 5, 43, 3, 33, 2, 45, 33, 2, 45, 33, 2, 45, 33, 4, 2, "assert_eq", 2, 35, 33, 1, 33,
-2, 33, 1, 33, 2, 33, 3, 43, 3, 43, 3, 36, 1, 33, 2, 33, 4, 46, 36, 1, 33, 1, 45, 33, 1, 2, "assert_eq", 2, 35, 36, 1,
-33, 2, 45, 33, 4, 2, "assert_eq", 2, 35, 36, 1, 33, 3, 45, 33, 1, 33, 2, 33, 3, 43, 3, 2, "assert_eq", 2, 35, 36, 1, 33,
-3, 45, 33, 3, 33, 8, 46, 36, 1, 33, 3, 45, 33, 1, 33, 2, 33, 8, 43, 3, 2, "assert_eq", 2, 35, 33, 1, 33, 2, 33, 3, 43,
-3, 33, 4, 2, "arrayPushBack", 2, 33, 1, 33, 2, 33, 3, 33, 4, 43, 4, 2, "assert_eq", 2, 35, 33, 1, 33, 2, 33, 3, 43, 3,
-33, 0, 2, "arrayPushFront", 2, 33, 0, 33, 1, 33, 2, 33, 3, 43, 4, 2, "assert_eq", 2, 35, 33, 1, 33, 2, 33, 3, 43, 3, 2,
-"arrayPopBack", 1, 33, 1, 33, 2, 43, 2, 2, "assert_eq", 2, 35, 33, 1, 33, 2, 33, 3, 43, 3, 2, "arrayPopFront", 1, 33, 2,
-33, 3, 43, 2, 2, "assert_eq", 2, 35, 33, 3, 33, 2, 33, 1, 43, 3, 2, "arraySort", 1, 33, 1, 33, 2, 33, 3, 43, 3, 2,
-"assert_eq", 2, 35, 33, 1, 33, 2, 33, 3, 43, 3, 2, "arrayReverse", 1, 33, 3, 33, 2, 33, 1, 43, 3, 2, "assert_eq", 2, 35,
-33, 3, 33, 2, 33, 1, 43, 3, 2, "arrayReverseSort", 1, 33, 3, 33, 2, 33, 1, 43, 3, 2, "assert_eq", 2, 35, 33, 1, 33, 2,
-33, 3, 43, 3, 32, ",", 2, "arrayStringConcat", 2, 32, "1,2,3", 2, "assert_eq", 2, 35, 33, 1, 33, 2, 33, 3, 33, 4, 43, 4,
-36, 2, 33, 1, 33, 2, 33, 3, 33, 4, 43, 4, 2, "assert_eq", 2, 35, 36, 2, 33, 5, 2, "arrayPushBack", 2, 35, 36, 2, 33, 1,
-33, 2, 33, 3, 33, 4, 43, 4, 2, "assert_eq", 2, 35, 36, 2, 33, 0, 2, "arrayPushFront", 2, 35, 36, 2, 33, 1, 33, 2, 33, 3,
-33, 4, 43, 4, 2, "assert_eq", 2, 35, 36, 2, 2, "arrayPopBack", 1, 35, 36, 2, 33, 1, 33, 2, 33, 3, 33, 4, 43, 4, 2,
-"assert_eq", 2, 35, 36, 2, 2, "arrayPopFront", 1, 35, 36, 2, 33, 1, 33, 2, 33, 3, 33, 4, 43, 4, 2, "assert_eq", 2, 35,
-36, 2, 2, "arraySort", 1, 35, 36, 2, 33, 1, 33, 2, 33, 3, 33, 4, 43, 4, 2, "assert_eq", 2, 35, 36, 2, 2, "arrayReverse",
-1, 35, 36, 2, 33, 1, 33, 2, 33, 3, 33, 4, 43, 4, 2, "assert_eq", 2, 35, 36, 2, 2, "arrayReverseSort", 1, 35, 36, 2, 33,
-1, 33, 2, 33, 3, 33, 4, 43, 4, 2, "assert_eq", 2, 35, 36, 2, 33, 0, 2, "has", 2, 30, 2, "assert_eq", 2, 35, 36, 2, 33,
-2, 2, "has", 2, 29, 2, "assert_eq", 2, 35, 36, 2, 32, "banana", 2, "has", 2, 30, 2, "assert_eq", 2, 35, 32, "banananas",
-32, "banana", 2, "has", 2, 29, 2, "assert_eq", 2, 35, 32, "banananas", 32, "foo", 2, "has", 2, 30, 2, "assert_eq", 2,
-35, 32, "1", 32, "2", 43, 2, 32, "1", 2, "has", 2, 29, 2, "assert_eq", 2, 35, 33, 1, 33, 2, 33, 3, 43, 3, 33, 1, 2,
-"indexOf", 2, 33, 1, 2, "assert_eq", 2, 35, 33, 1, 33, 2, 33, 3, 43, 3, 33, 2, 2, "indexOf", 2, 33, 2, 2, "assert_eq",
-2, 35, 33, 1, 33, 2, 33, 3, 43, 3, 33, 3, 2, "indexOf", 2, 33, 3, 2, "assert_eq", 2, 35, 33, 1, 33, 2, 33, 3, 43, 3, 33,
-4, 2, "indexOf", 2, 31, 2, "assert_eq", 2, 35, 52, "arrayCount", 2, 0, 64, 33, 0, 36, 1, 36, 3, 2, "values", 1, 33, 1,
-36, 4, 2, "length", 1, 31, 36, 6, 36, 5, 16, 40, 31, 36, 4, 36, 5, 45, 37, 7, 36, 7, 36, 0, 54, 1, 40, 7, 33, 1, 36, 2,
-6, 37, 2, 36, 5, 33, 1, 6, 37, 5, 39, -38, 35, 35, 35, 35, 35, 36, 2, 38, 35, 53, 0, 52, "lambda", 1, 0, 6, 33, 2, 36,
-0, 13, 38, 53, 0, 33, 1, 33, 2, 33, 3, 33, 4, 33, 5, 43, 5, 36, 3, 54, 2, 33, 3, 2, "assert_eq", 2, 35, 32, "a", 32,
-"b", 32, "c", 43, 3, 32, "a", 21, 29, 2, "assert_eq", 2, 35, 32, "a", 32, "b", 32, "c", 43, 3, 32, "d", 21, 30, 2,
-"assert_eq", 2, 35, 43, 0, 32, "a", 21, 30, 2, "assert_eq", 2, 35, 29, 38, 35, 35, 35, 35]
+["_H", 1, 33, 1, 33, 2, 33, 3, 43, 3, 36, 0, 33, 2, 45, 33, 2, 2, "assert_eq", 2, 35, 36, 0, 33, 2, 48, 33, 2, 2,
+"assert_eq", 2, 35, 36, 0, 33, 2, 48, 33, 2, 2, "assert_eq", 2, 35, 36, 0, 33, 7, 48, 31, 2, "assert_eq", 2, 35, 36, 0,
+33, 7, 48, 31, 2, "assert_eq", 2, 35, 33, 1, 33, 2, 33, 3, 43, 3, 33, 2, 45, 33, 2, 2, "assert_eq", 2, 35, 33, 1, 33,
+2, 33, 3, 33, 4, 43, 2, 43, 2, 33, 5, 43, 3, 33, 2, 45, 33, 2, 45, 33, 2, 45, 33, 4, 2, "assert_eq", 2, 35, 33, 1, 33,
+2, 33, 3, 33, 4, 43, 2, 43, 2, 33, 5, 43, 3, 33, 2, 48, 33, 2, 48, 33, 2, 48, 33, 4, 2, "assert_eq", 2, 35, 33, 1, 33,
+2, 33, 3, 33, 4, 43, 2, 43, 2, 33, 5, 43, 3, 33, 2, 48, 33, 2, 48, 33, 2, 48, 33, 4, 2, "assert_eq", 2, 35, 33, 1, 33,
+2, 33, 3, 33, 4, 43, 2, 43, 2, 33, 5, 43, 3, 33, 7, 48, 33, 4, 48, 33, 2, 48, 31, 2, "assert_eq", 2, 35, 33, 1, 33, 2,
+33, 3, 33, 4, 43, 2, 43, 2, 33, 5, 43, 3, 33, 7, 48, 33, 4, 48, 33, 2, 48, 31, 2, "assert_eq", 2, 35, 33, 1, 33, 1, 33,
+2, 33, 3, 33, 4, 43, 2, 43, 2, 33, 5, 43, 3, 33, 2, 45, 33, 2, 45, 33, 2, 45, 6, 33, 5, 2, "assert_eq", 2, 35, 33, 1,
+33, 2, 33, 3, 33, 4, 43, 2, 43, 2, 33, 5, 43, 3, 33, 2, 45, 33, 2, 45, 33, 2, 45, 33, 4, 2, "assert_eq", 2, 35, 33, 1,
+33, 2, 33, 1, 33, 2, 33, 3, 43, 3, 43, 3, 36, 1, 33, 2, 33, 4, 46, 36, 1, 33, 1, 45, 33, 1, 2, "assert_eq", 2, 35, 36,
+1, 33, 2, 45, 33, 4, 2, "assert_eq", 2, 35, 36, 1, 33, 3, 45, 33, 1, 33, 2, 33, 3, 43, 3, 2, "assert_eq", 2, 35, 36, 1,
+33, 3, 45, 33, 3, 33, 8, 46, 36, 1, 33, 3, 45, 33, 1, 33, 2, 33, 8, 43, 3, 2, "assert_eq", 2, 35, 33, 1, 33, 2, 33, 3,
+43, 3, 33, 4, 2, "arrayPushBack", 2, 33, 1, 33, 2, 33, 3, 33, 4, 43, 4, 2, "assert_eq", 2, 35, 33, 1, 33, 2, 33, 3, 43,
+3, 33, 0, 2, "arrayPushFront", 2, 33, 0, 33, 1, 33, 2, 33, 3, 43, 4, 2, "assert_eq", 2, 35, 33, 1, 33, 2, 33, 3, 43, 3,
+2, "arrayPopBack", 1, 33, 1, 33, 2, 43, 2, 2, "assert_eq", 2, 35, 33, 1, 33, 2, 33, 3, 43, 3, 2, "arrayPopFront", 1,
+33, 2, 33, 3, 43, 2, 2, "assert_eq", 2, 35, 33, 3, 33, 2, 33, 1, 43, 3, 2, "arraySort", 1, 33, 1, 33, 2, 33, 3, 43, 3,
+2, "assert_eq", 2, 35, 33, 1, 33, 2, 33, 3, 43, 3, 2, "arrayReverse", 1, 33, 3, 33, 2, 33, 1, 43, 3, 2, "assert_eq", 2,
+35, 33, 3, 33, 2, 33, 1, 43, 3, 2, "arrayReverseSort", 1, 33, 3, 33, 2, 33, 1, 43, 3, 2, "assert_eq", 2, 35, 33, 1, 33,
+2, 33, 3, 43, 3, 32, ",", 2, "arrayStringConcat", 2, 32, "1,2,3", 2, "assert_eq", 2, 35, 33, 1, 33, 2, 33, 3, 33, 4,
+43, 4, 36, 2, 33, 1, 33, 2, 33, 3, 33, 4, 43, 4, 2, "assert_eq", 2, 35, 36, 2, 33, 5, 2, "arrayPushBack", 2, 35, 36, 2,
+33, 1, 33, 2, 33, 3, 33, 4, 43, 4, 2, "assert_eq", 2, 35, 36, 2, 33, 0, 2, "arrayPushFront", 2, 35, 36, 2, 33, 1, 33,
+2, 33, 3, 33, 4, 43, 4, 2, "assert_eq", 2, 35, 36, 2, 2, "arrayPopBack", 1, 35, 36, 2, 33, 1, 33, 2, 33, 3, 33, 4, 43,
+4, 2, "assert_eq", 2, 35, 36, 2, 2, "arrayPopFront", 1, 35, 36, 2, 33, 1, 33, 2, 33, 3, 33, 4, 43, 4, 2, "assert_eq",
+2, 35, 36, 2, 2, "arraySort", 1, 35, 36, 2, 33, 1, 33, 2, 33, 3, 33, 4, 43, 4, 2, "assert_eq", 2, 35, 36, 2, 2,
+"arrayReverse", 1, 35, 36, 2, 33, 1, 33, 2, 33, 3, 33, 4, 43, 4, 2, "assert_eq", 2, 35, 36, 2, 2, "arrayReverseSort",
+1, 35, 36, 2, 33, 1, 33, 2, 33, 3, 33, 4, 43, 4, 2, "assert_eq", 2, 35, 36, 2, 33, 0, 2, "has", 2, 30, 2, "assert_eq",
+2, 35, 36, 2, 33, 2, 2, "has", 2, 29, 2, "assert_eq", 2, 35, 36, 2, 32, "banana", 2, "has", 2, 30, 2, "assert_eq", 2,
+35, 32, "banananas", 32, "banana", 2, "has", 2, 30, 2, "assert_eq", 2, 35, 32, "banananas", 32, "foo", 2, "has", 2, 30,
+2, "assert_eq", 2, 35, 32, "1", 32, "2", 43, 2, 32, "1", 2, "has", 2, 29, 2, "assert_eq", 2, 35, 33, 1, 33, 2, 33, 3,
+43, 3, 33, 1, 2, "indexOf", 2, 33, 1, 2, "assert_eq", 2, 35, 33, 1, 33, 2, 33, 3, 43, 3, 33, 2, 2, "indexOf", 2, 33, 2,
+2, "assert_eq", 2, 35, 33, 1, 33, 2, 33, 3, 43, 3, 33, 3, 2, "indexOf", 2, 33, 3, 2, "assert_eq", 2, 35, 33, 1, 33, 2,
+33, 3, 43, 3, 33, 4, 2, "indexOf", 2, 33, 0, 2, "assert_eq", 2, 35, 52, "arrayCount", 2, 0, 64, 33, 0, 36, 1, 36, 3, 2,
+"values", 1, 33, 1, 36, 4, 2, "length", 1, 31, 36, 6, 36, 5, 16, 40, 31, 36, 4, 36, 5, 45, 37, 7, 36, 7, 36, 0, 54, 1,
+40, 7, 33, 1, 36, 2, 6, 37, 2, 36, 5, 33, 1, 6, 37, 5, 39, -38, 35, 35, 35, 35, 35, 36, 2, 38, 35, 53, 0, 52, "lambda",
+1, 0, 6, 33, 2, 36, 0, 13, 38, 53, 0, 33, 1, 33, 2, 33, 3, 33, 4, 33, 5, 43, 5, 36, 3, 54, 2, 33, 3, 2, "assert_eq", 2,
+35, 32, "a", 32, "b", 32, "c", 43, 3, 32, "a", 21, 29, 2, "assert_eq", 2, 35, 32, "a", 32, "b", 32, "c", 43, 3, 32,
+"d", 21, 30, 2, "assert_eq", 2, 35, 43, 0, 32, "a", 21, 30, 2, "assert_eq", 2, 35, 29, 38, 35, 35, 35, 35]
diff --git a/rust/common/hogvm/tests/stl.rs b/rust/common/hogvm/tests/stl.rs
new file mode 100644
index 000000000000..08eac3e6afd5
--- /dev/null
+++ b/rust/common/hogvm/tests/stl.rs
@@ -0,0 +1,164 @@
+//! Self-contained STL coverage: builds tiny bytecode programs that call a single native function
+//! and asserts the result. These replace the (omitted) Node-oracle parity harness for the STL
+//! surface that carries the most regression risk — the crypto/base64 natives backed by new
+//! dependencies, JSON round-tripping that must preserve key order, and first-class tuples.
+
+use hogvm::{sync_execute, ExecutionContext, Program};
+use serde_json::{json, Value};
+
+// Opcode numeric values (mirror common/hogvm/python/operation.py).
+const OP_CALL_GLOBAL: i64 = 2;
+const OP_STRING: i64 = 32;
+const OP_INTEGER: i64 = 33;
+const OP_RETURN: i64 = 38;
+const OP_ARRAY: i64 = 43;
+const OP_TUPLE: i64 = 44;
+
+/// Wrap a value-producing fragment in a program header + `RETURN` and execute it.
+fn run(fragment: Vec<Value>) -> Value {
+ let mut bc = vec![json!("_H"), json!(1)];
+ bc.extend(fragment);
+ bc.push(json!(OP_RETURN));
+ let program = Program::new(bc).expect("valid program");
+ let ctx = ExecutionContext::with_defaults(program).with_globals(json!({}));
+ sync_execute(&ctx, false).expect("execution succeeds")
+}
+
+fn str_lit(s: &str) -> Vec<Value> {
+ vec![json!(OP_STRING), json!(s)]
+}
+
+fn int_lit(n: i64) -> Vec<Value> {
+ vec![json!(OP_INTEGER), json!(n)]
+}
+
+/// `name(args…)`. The compiler pushes args left-to-right, so `args[0]` is the first listed.
+fn call(name: &str, args: &[Vec<Value>]) -> Vec<Value> {
+ let mut f = Vec::new();
+ for a in args {
+ f.extend(a.clone());
+ }
+ f.extend([json!(OP_CALL_GLOBAL), json!(name), json!(args.len() as i64)]);
+ f
+}
+
+fn collection(op: i64, elems: &[Vec<Value>]) -> Vec<Value> {
+ let mut f = Vec::new();
+ for e in elems {
+ f.extend(e.clone());
+ }
+ f.extend([json!(op), json!(elems.len() as i64)]);
+ f
+}
+
+/// Single-string-arg native returning a string — the shape most STL functions take.
+fn call_str(name: &str, arg: &str) -> Value {
+ run(call(name, &[str_lit(arg)]))
+}
+
+#[test]
+fn crypto_and_encoding_known_answers() {
+ // Known-answer vectors — these are RFC/spec fixed, so they pin both our wiring and the
+ // md-5 / sha2 / base64 dependencies to the correct output.
+ let cases: &[(&str, &str, &str)] = &[
+ ("md5Hex", "hello", "5d41402abc4b2a76b9719d911017c592"),
+ (
+ "sha256Hex",
+ "hello",
+ "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824",
+ ),
+ ("base64Encode", "hello", "aGVsbG8="),
+ ("base64Decode", "aGVsbG8=", "hello"),
+ ];
+ for (name, input, expected) in cases {
+ assert_eq!(call_str(name, input), json!(expected), "{name}({input:?})");
+ }
+}
+
+#[test]
+fn base64_round_trips() {
+ let encoded = run(call("base64Encode", &[str_lit("Hello, World! 🦔")]));
+ let decoded = run(call(
+ "base64Decode",
+ &[call("base64Encode", &[str_lit("Hello, World! 🦔")])],
+ ));
+ assert!(matches!(encoded, Value::String(_)));
+ assert_eq!(decoded, json!("Hello, World! 🦔"));
+}
+
+#[test]
+fn string_natives() {
+ let cases: &[(&str, &[&str], Value)] = &[
+ ("upper", &["aBc"], json!("ABC")),
+ ("lower", &["aBc"], json!("abc")),
+ ("trim", &[" hi "], json!("hi")),
+ ("trimLeft", &[" hi "], json!("hi ")),
+ ("trimRight", &[" hi "], json!(" hi")),
+ ("concat", &["foo", "bar"], json!("foobar")),
+ ("replaceAll", &["aaa", "a", "b"], json!("bbb")),
+ ("replaceOne", &["aaa", "a", "b"], json!("baa")),
+ ("length", &["hello"], json!(5)),
+ ];
+ for (name, args, expected) in cases {
+ let arg_lits: Vec<Vec<Value>> = args.iter().map(|s| str_lit(s)).collect();
+ assert_eq!(run(call(name, &arg_lits)), *expected, "{name}({args:?})");
+ }
+}
+
+#[test]
+fn type_coercion_natives() {
+ assert_eq!(run(call("toString", &[int_lit(42)])), json!("42"));
+ assert_eq!(run(call("toInt", &[str_lit("42")])), json!(42));
+ assert_eq!(run(call("toFloat", &[str_lit("1.5")])), json!(1.5));
+}
+
+#[test]
+fn array_natives() {
+ let arr = || collection(OP_ARRAY, &[int_lit(1), int_lit(2), int_lit(3)]);
+
+ assert_eq!(run(call("length", &[arr()])), json!(3));
+ assert_eq!(run(call("has", &[arr(), int_lit(2)])), json!(true));
+ assert_eq!(run(call("has", &[arr(), int_lit(9)])), json!(false));
+ // arrayPushBack is pure (does not mutate in place) and appends.
+ assert_eq!(
+ run(call("arrayPushBack", &[arr(), int_lit(4)])),
+ json!([1, 2, 3, 4])
+ );
+ // indexOf is 1-based; 0 means "not found" (Node-aligned, asserted in arrays.hog too).
+ assert_eq!(run(call("indexOf", &[arr(), int_lit(3)])), json!(3));
+ assert_eq!(run(call("indexOf", &[arr(), int_lit(9)])), json!(0));
+}
+
+#[test]
+fn json_round_trip_preserves_key_order() {
+ // The crux of the order-preserving HogJson deserialization: serde_json::Value would sort keys
+ // (BTreeMap); the VM must keep document order so re-stringifying is stable.
+ let result = run(call(
+ "jsonStringify",
+ &[call("jsonParse", &[str_lit(r#"{"b":1,"a":2,"c":3}"#)])],
+ ));
+ let Value::String(s) = result else {
+ panic!("jsonStringify should return a string, got {result:?}");
+ };
+ let pos = |needle: &str| {
+ s.find(needle)
+ .unwrap_or_else(|| panic!("{needle} missing from {s}"))
+ };
+ assert!(
+ pos("\"b\"") < pos("\"a\"") && pos("\"a\"") < pos("\"c\""),
+ "expected insertion order b, a, c — got {s}"
+ );
+}
+
+#[test]
+fn tuples_are_distinct_from_arrays() {
+ // A tuple prints with parens and reports its own type, unlike an array.
+ let tup = || collection(OP_TUPLE, &[int_lit(1), int_lit(2), int_lit(3)]);
+ assert_eq!(run(call("typeof", &[tup()])), json!("tuple"));
+ assert_eq!(
+ run(call("typeof", &[collection(OP_ARRAY, &[int_lit(1)])])),
+ json!("array")
+ );
+ // Tuples still index and report length like arrays.
+ assert_eq!(run(call("length", &[tup()])), json!(3));
+}
diff --git a/rust/common/hogvm/tests/stl_parity.rs b/rust/common/hogvm/tests/stl_parity.rs
new file mode 100644
index 000000000000..a182d322d9b2
--- /dev/null
+++ b/rust/common/hogvm/tests/stl_parity.rs
@@ -0,0 +1,130 @@
+//! Per-STL parity test — every STL function gets a focused case checked against the Node/
+//! Python reference VM.
+//!
+//! The fixture `tests/static/stl_oracle.jsonl` holds one case per line: the `print(fn(args))`
+//! bytecode and the output the *reference* VM produced. Here we replay that exact bytecode
+//! through the Rust VM and assert it matches. "exact" cases must match byte-for-byte; "smoke"
+//! cases (non-deterministic functions like `now()`) only have to run without error.
+//!
+//! The fixture is committed reference output (generated from the Node/Python VMs), so this runs
+//! without a live reference VM.
+
+use std::{
+ collections::BTreeSet,
+ sync::{Arc, Mutex},
+};
+
+use hogvm::{
+ native_func, print_hog_string_output, sync_execute, ExecutionContext, HogLiteral, Program,
+};
+use serde_json::Value;
+
+#[derive(serde::Deserialize)]
+struct Entry {
+ #[serde(rename = "fn")]
+ fn_: String,
+ label: String,
+ #[serde(rename = "match")]
+ match_mode: String,
+ bytecode: Vec<Value>,
+ expected: String,
+}
+
+fn run_bytecode(bytecode: Vec<Value>) -> Result<String, String> {
+ let program = Program::new(bytecode).map_err(|e| format!("{e:?}"))?;
+ // Arc<Mutex> rather than Rc<RefCell> because NativeFunction requires Send + Sync.
+ let captured = Arc::new(Mutex::new(String::new()));
+ let sink = captured.clone();
+ let print_fn = native_func(move |vm, args| {
+ let mut line = String::new();
+ for (i, arg) in args.iter().enumerate() {
+ if i > 0 {
+ line.push(' ');
+ }
+ line.push_str(&print_hog_string_output(&vm.heap, arg)?);
+ }
+ line.push('\n');
+ sink.lock().unwrap().push_str(&line);
+ Ok(HogLiteral::Null.into())
+ });
+ // Match reference semantics: the reference VMs always coerce comparison operands.
+ let ctx = ExecutionContext::with_defaults(program)
+ .with_coercing_comparisons()
+ .with_ext_fn("print".to_string(), print_fn);
+ match sync_execute(&ctx, false) {
+ Ok(_) => Ok(captured.lock().unwrap().trim_end_matches('\n').to_string()),
+ Err(f) => Err(format!("{}", f.error)),
+ }
+}
+
+fn load_oracle() -> Vec<Entry> {
+ let path = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/static/stl_oracle.jsonl");
+ let raw = std::fs::read_to_string(path).unwrap_or_else(|e| panic!("read {path}: {e}"));
+ raw.lines()
+ .filter(|l| !l.trim().is_empty())
+ .map(|l| serde_json::from_str(l).unwrap_or_else(|e| panic!("bad oracle line: {e}\n{l}")))
+ .collect()
+}
+
+#[test]
+fn stl_parity() {
+ let entries = load_oracle();
+
+ let mut pass = 0usize;
+ let mut failed: Vec<(String, String)> = Vec::new(); // (label, detail)
+ let mut failing_fns: BTreeSet<String> = BTreeSet::new();
+
+ for e in &entries {
+ let expected = e.expected.trim_end_matches('\n');
+ match run_bytecode(e.bytecode.clone()) {
+ Ok(_) if e.match_mode == "smoke" => {
+ // smoke: ran without error
+ pass += 1;
+ }
+ Ok(actual) if actual == expected => pass += 1,
+ Ok(actual) => {
+ failed.push((
+ e.label.clone(),
+ format!("node={expected:?} rust={actual:?}"),
+ ));
+ failing_fns.insert(e.fn_.clone());
+ }
+ Err(err) => {
+ failed.push((e.label.clone(), format!("ERROR {err}")));
+ failing_fns.insert(e.fn_.clone());
+ }
+ }
+ }
+
+ let total = entries.len();
+ println!("\n============ HogVM per-STL parity ============");
+ println!("cases: {total} | PASS {pass} | FAIL {}", failed.len());
+ println!("STL functions with a failing case: {}", failing_fns.len());
+ if !failed.is_empty() {
+ println!("\n-- FAIL --");
+ for (label, detail) in &failed {
+ println!(" {label}: {detail}");
+ }
+ println!(
+ "\n-- failing functions --\n {}",
+ failing_fns.iter().cloned().collect::<Vec<_>>().join(", ")
+ );
+ }
+ println!("==============================================\n");
+
+ // Regression gate: every failure must be a known, accepted divergence — a new one is a parity
+ // regression. `toUnixTimestamp#0` is a reference float-formatting artifact (the oracle prints
+ // "1609504496.0"; the Rust VM prints the integer) and is the sole tolerated case.
+ const KNOWN_DIVERGENCES: &[&str] = &["toUnixTimestamp#0"];
+ let unexpected: Vec<&String> = failed
+ .iter()
+ .map(|(label, _)| label)
+ .filter(|label| !KNOWN_DIVERGENCES.contains(&label.as_str()))
+ .collect();
+
+ assert!(total > 0, "no STL cases in fixture");
+ assert!(
+ unexpected.is_empty(),
+ "unexpected STL parity failures (not in the known-divergence allowlist): {unexpected:?}"
+ );
+}