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.

fix(hogvm): return null from string and array functions given null (#104482)

Meikel Ratzb22ee4690c5d
diff --git a/common/hogvm/__tests__/__snapshots__/arrays.js b/common/hogvm/__tests__/__snapshots__/arrays.js
index d7195f0bb881..47f785fbb5f8 100644
--- a/common/hogvm/__tests__/__snapshots__/arrays.js
+++ b/common/hogvm/__tests__/__snapshots__/arrays.js
@@ -9,7 +9,7 @@ function arrayPushFront (arr, item) { if (!Array.isArray(arr)) { return [item] }
function arrayPushBack (arr, item) { if (!Array.isArray(arr)) { return [item] } return [...arr, item] }
function arrayPopFront (arr) { if (!Array.isArray(arr)) { return [] } return arr.slice(1) }
function arrayPopBack (arr) { if (!Array.isArray(arr)) { return [] } return arr.slice(0, arr.length - 1) }
-function arrayCount (func, arr) { let count = 0; for (let i = 0; i < arr.length; i++) { if (func(arr[i])) { count = count + 1 } } return count }
+function arrayCount (func, arr) { let count = 0; for (let i = 0; i < (arr ?? []).length; i++) { if (func(arr[i])) { count = count + 1 } } return count }
function __setProperty(objectOrArray, key, value) {
if (Array.isArray(objectOrArray)) { if (key > 0) { objectOrArray[key - 1] = value } else { objectOrArray[objectOrArray.length + key] = value } }
else { objectOrArray[key] = value }
@@ -43,6 +43,7 @@ function __lambda (fn) { return fn }
function __isHogError(obj) {return obj && obj.__hogError__ === true}
function __isHogDateTime(obj) { return obj && obj.__hogDateTime__ === true }
function __isHogDate(obj) { return obj && obj.__hogDate__ === true }
+function __gt (a, b) { return a === null || a === undefined || b === null || b === undefined ? false : a > b }
function __getProperty(objectOrArray, key, nullish) {
if ((nullish && !objectOrArray) || key === 0) { return null }
if (Array.isArray(objectOrArray)) { return key > 0 ? objectOrArray[key - 1] : objectOrArray[objectOrArray.length + key] }
@@ -123,7 +124,7 @@ print(indexOf([1, 2, 3], 1));
print(indexOf([1, 2, 3], 2));
print(indexOf([1, 2, 3], 3));
print(indexOf([1, 2, 3], 4));
-print(arrayCount(__lambda((x) => (x > 2)), [1, 2, 3, 4, 5]));
+print(arrayCount(__lambda((x) => __gt(x, 2)), [1, 2, 3, 4, 5]));
print("------");
let c = [1, 2, 3];
print(__getProperty(c, 1, false), __getProperty(c, 2, false), __getProperty(c, 3, false), __getProperty(c, 4, false));
diff --git a/common/hogvm/__tests__/__snapshots__/bytecodeStl.js b/common/hogvm/__tests__/__snapshots__/bytecodeStl.js
index 864b2ab0daaa..49d522daf394 100644
--- a/common/hogvm/__tests__/__snapshots__/bytecodeStl.js
+++ b/common/hogvm/__tests__/__snapshots__/bytecodeStl.js
@@ -1,10 +1,10 @@
function print (...args) { console.log(...args.map(__printHogStringOutput)) }
function like (str, pattern) { return __like(str, pattern, false) }
-function arrayReduce (func, arr, initial) { let result = initial; for (let i = 0; i < arr.length; i++) { result = func(result, arr[i]) } return result }
-function arrayMap (func, arr) { let result = []; for (let i = 0; i < arr.length; i++) { result = arrayPushBack(result, func(arr[i])) } return result }
-function arrayFilter (func, arr) { let result = []; for (let i = 0; i < arr.length; i++) { if (func(arr[i])) { result = arrayPushBack(result, arr[i]) } } return result}
+function arrayReduce (func, arr, initial) { let result = initial; for (let i = 0; i < (arr ?? []).length; i++) { result = func(result, arr[i]) } return result }
+function arrayMap (func, arr) { let result = []; for (let i = 0; i < (arr ?? []).length; i++) { result = arrayPushBack(result, func(arr[i])) } return result }
+function arrayFilter (func, arr) { let result = []; for (let i = 0; i < (arr ?? []).length; i++) { if (func(arr[i])) { result = arrayPushBack(result, arr[i]) } } return result}
function arrayPushBack (arr, item) { if (!Array.isArray(arr)) { return [item] } return [...arr, item] }
-function arrayExists (func, arr) { for (let i = 0; i < arr.length; i++) { if (func(arr[i])) { return true } } return false }
+function arrayExists (func, arr) { for (let i = 0; i < (arr ?? []).length; i++) { if (func(arr[i])) { return true } } return false }
function __printHogStringOutput(obj) { if (typeof obj === 'string') { return obj } return __printHogValue(obj) }
function __printHogValue(obj, marked = new Set()) {
if (typeof obj === 'object' && obj !== null && obj !== undefined) {
diff --git a/common/hogvm/__tests__/__snapshots__/crypto.hoge b/common/hogvm/__tests__/__snapshots__/crypto.hoge
index 7e4817c42f61..32560867cf55 100644
--- a/common/hogvm/__tests__/__snapshots__/crypto.hoge
+++ b/common/hogvm/__tests__/__snapshots__/crypto.hoge
@@ -1,36 +1,34 @@
-["_H", 1, 32, "this is a secure string", 32, "string:", 36, 0, 2, "print", 2, 35, 32, "md5Hex(string):", 36, 0, 2,
-"md5Hex", 1, 2, "print", 2, 35, 32, "md5Hex(null):", 31, 2, "md5Hex", 1, 2, "print", 2, 35, 32, "md5(string, 'hex'):",
-36, 0, 32, "hex", 2, "md5", 2, 2, "print", 2, 35, 32, "md5(null, 'hex'):", 31, 32, "hex", 2, "md5", 2, 2, "print", 2,
-35, 32, "md5(string, 'binary'):", 36, 0, 32, "binary", 2, "md5", 2, 2, "print", 2, 35, 32, "md5(null, 'binary'):", 31,
-32, "binary", 2, "md5", 2, 2, "print", 2, 35, 32, "md5(string, 'base64'):", 36, 0, 32, "base64", 2, "md5", 2, 2,
-"print", 2, 35, 32, "md5(null, 'base64'):", 31, 32, "base64", 2, "md5", 2, 2, "print", 2, 35, 32,
-"md5(string, 'base64url'):", 36, 0, 32, "base64url", 2, "md5", 2, 2, "print", 2, 35, 32, "md5(null, 'base64url'):", 31,
-32, "base64url", 2, "md5", 2, 2, "print", 2, 35, 32, "sha256Hex(string):", 36, 0, 2, "sha256Hex", 1, 2, "print", 2, 35,
-32, "sha256Hex(null):", 31, 2, "sha256Hex", 1, 2, "print", 2, 35, 32, "sha256(string, 'hex'):", 36, 0, 32, "hex", 2,
-"sha256", 2, 2, "print", 2, 35, 32, "sha256(null, 'hex'):", 31, 32, "hex", 2, "sha256", 2, 2, "print", 2, 35, 32,
-"sha256(string, 'binary'):", 36, 0, 32, "binary", 2, "sha256", 2, 2, "print", 2, 35, 32, "sha256(null, 'binary'):", 31,
-32, "binary", 2, "sha256", 2, 2, "print", 2, 35, 32, "sha256(string, 'base64'):", 36, 0, 32, "base64", 2, "sha256", 2,
-2, "print", 2, 35, 32, "sha256(null, 'base64'):", 31, 32, "base64", 2, "sha256", 2, 2, "print", 2, 35, 32,
-"sha256(string, 'base64url'):", 36, 0, 32, "base64url", 2, "sha256", 2, 2, "print", 2, 35, 32,
-"sha256(null, 'base64url'):", 31, 32, "base64url", 2, "sha256", 2, 2, "print", 2, 35, 32, "sha1Hex(string):", 36, 0, 2,
-"sha1Hex", 1, 2, "print", 2, 35, 32, "sha1Hex(null):", 31, 2, "sha1Hex", 1, 2, "print", 2, 35, 32,
-"sha1(string, 'hex'):", 36, 0, 32, "hex", 2, "sha1", 2, 2, "print", 2, 35, 32, "sha1(null, 'hex'):", 31, 32, "hex", 2,
-"sha1", 2, 2, "print", 2, 35, 32, "sha1(string, 'binary'):", 36, 0, 32, "binary", 2, "sha1", 2, 2, "print", 2, 35, 32,
-"sha1(null, 'binary'):", 31, 32, "binary", 2, "sha1", 2, 2, "print", 2, 35, 32, "sha1(string, 'base64'):", 36, 0, 32,
-"base64", 2, "sha1", 2, 2, "print", 2, 35, 32, "sha1(null, 'base64'):", 31, 32, "base64", 2, "sha1", 2, 2, "print", 2,
-35, 32, "sha1(string, 'base64url'):", 36, 0, 32, "base64url", 2, "sha1", 2, 2, "print", 2, 35, 32,
-"sha1(null, 'base64url'):", 31, 32, "base64url", 2, "sha1", 2, 2, "print", 2, 35, 32, "1", 32, "string", 32, "more", 32,
-"keys", 43, 4, 32, "data:", 36, 1, 2, "print", 2, 35, 32, "sha256HmacChainHex(data):", 36, 1, 2, "sha256HmacChainHex",
-1, 2, "print", 2, 35, 32, "sha256HmacChain(data, 'hex'):", 36, 1, 32, "hex", 2, "sha256HmacChain", 2, 2, "print", 2, 35,
-32, "sha256HmacChain(data, 'base64'):", 36, 1, 32, "base64", 2, "sha256HmacChain", 2, 2, "print", 2, 35, 32,
-"sha256HmacChain(data, 'binary'):", 36, 1, 32, "binary", 2, "sha256HmacChain", 2, 2, "print", 2, 35, 32,
-"sha256HmacChain(data, 'base64url'):", 36, 1, 32, "base64url", 2, "sha256HmacChain", 2, 2, "print", 2, 35, 32,
-"sha1HmacChainHex(data):", 36, 1, 2, "sha1HmacChainHex", 1, 2, "print", 2, 35, 32, "sha1HmacChain(data, 'hex'):", 36, 1,
-32, "hex", 2, "sha1HmacChain", 2, 2, "print", 2, 35, 32, "sha1HmacChain(data, 'base64'):", 36, 1, 32, "base64", 2,
-"sha1HmacChain", 2, 2, "print", 2, 35, 32, "sha1HmacChain(data, 'binary'):", 36, 1, 32, "binary", 2, "sha1HmacChain", 2,
-2, "print", 2, 35, 32, "sha1HmacChain(data, 'base64url'):", 36, 1, 32, "base64url", 2, "sha1HmacChain", 2, 2, "print",
-2, 35, 32, "sha1Hex('abc'):", 32, "abc", 2, "sha1Hex", 1, 2, "print", 2, 35, 32, "sha1Hex(''):", 32, "", 2, "sha1Hex",
-1, 2, "print", 2, 35, 32, "rfc2202 case 1:", 32,
+["_H", 1, 32, "this is a secure string", 32, "string:", 36, 0, 2, "print", 2, 35, 32, "md5(string, 'hex'):", 36, 0, 32,
+"hex", 2, "md5", 2, 2, "print", 2, 35, 32, "md5(null, 'hex'):", 31, 32, "hex", 2, "md5", 2, 2, "print", 2, 35, 32,
+"md5(string, 'binary'):", 36, 0, 32, "binary", 2, "md5", 2, 2, "print", 2, 35, 32, "md5(null, 'binary'):", 31, 32,
+"binary", 2, "md5", 2, 2, "print", 2, 35, 32, "md5(string, 'base64'):", 36, 0, 32, "base64", 2, "md5", 2, 2, "print", 2,
+35, 32, "md5(null, 'base64'):", 31, 32, "base64", 2, "md5", 2, 2, "print", 2, 35, 32, "md5(string, 'base64url'):", 36,
+0, 32, "base64url", 2, "md5", 2, 2, "print", 2, 35, 32, "md5(null, 'base64url'):", 31, 32, "base64url", 2, "md5", 2, 2,
+"print", 2, 35, 32, "sha256(string, 'hex'):", 36, 0, 32, "hex", 2, "sha256", 2, 2, "print", 2, 35, 32,
+"sha256(null, 'hex'):", 31, 32, "hex", 2, "sha256", 2, 2, "print", 2, 35, 32, "sha256(string, 'binary'):", 36, 0, 32,
+"binary", 2, "sha256", 2, 2, "print", 2, 35, 32, "sha256(null, 'binary'):", 31, 32, "binary", 2, "sha256", 2, 2,
+"print", 2, 35, 32, "sha256(string, 'base64'):", 36, 0, 32, "base64", 2, "sha256", 2, 2, "print", 2, 35, 32,
+"sha256(null, 'base64'):", 31, 32, "base64", 2, "sha256", 2, 2, "print", 2, 35, 32, "sha256(string, 'base64url'):", 36,
+0, 32, "base64url", 2, "sha256", 2, 2, "print", 2, 35, 32, "sha256(null, 'base64url'):", 31, 32, "base64url", 2,
+"sha256", 2, 2, "print", 2, 35, 32, "sha1Hex(string):", 36, 0, 2, "sha1Hex", 1, 2, "print", 2, 35, 32, "sha1Hex(null):",
+31, 2, "sha1Hex", 1, 2, "print", 2, 35, 32, "sha1(string, 'hex'):", 36, 0, 32, "hex", 2, "sha1", 2, 2, "print", 2, 35,
+32, "sha1(null, 'hex'):", 31, 32, "hex", 2, "sha1", 2, 2, "print", 2, 35, 32, "sha1(string, 'binary'):", 36, 0, 32,
+"binary", 2, "sha1", 2, 2, "print", 2, 35, 32, "sha1(null, 'binary'):", 31, 32, "binary", 2, "sha1", 2, 2, "print", 2,
+35, 32, "sha1(string, 'base64'):", 36, 0, 32, "base64", 2, "sha1", 2, 2, "print", 2, 35, 32, "sha1(null, 'base64'):",
+31, 32, "base64", 2, "sha1", 2, 2, "print", 2, 35, 32, "sha1(string, 'base64url'):", 36, 0, 32, "base64url", 2, "sha1",
+2, 2, "print", 2, 35, 32, "sha1(null, 'base64url'):", 31, 32, "base64url", 2, "sha1", 2, 2, "print", 2, 35, 32, "1", 32,
+"string", 32, "more", 32, "keys", 43, 4, 32, "data:", 36, 1, 2, "print", 2, 35, 32, "sha256HmacChainHex(data):", 36, 1,
+2, "sha256HmacChainHex", 1, 2, "print", 2, 35, 32, "sha256HmacChain(data, 'hex'):", 36, 1, 32, "hex", 2,
+"sha256HmacChain", 2, 2, "print", 2, 35, 32, "sha256HmacChain(data, 'base64'):", 36, 1, 32, "base64", 2,
+"sha256HmacChain", 2, 2, "print", 2, 35, 32, "sha256HmacChain(data, 'binary'):", 36, 1, 32, "binary", 2,
+"sha256HmacChain", 2, 2, "print", 2, 35, 32, "sha256HmacChain(data, 'base64url'):", 36, 1, 32, "base64url", 2,
+"sha256HmacChain", 2, 2, "print", 2, 35, 32, "sha1HmacChainHex(data):", 36, 1, 2, "sha1HmacChainHex", 1, 2, "print", 2,
+35, 32, "sha1HmacChain(data, 'hex'):", 36, 1, 32, "hex", 2, "sha1HmacChain", 2, 2, "print", 2, 35, 32,
+"sha1HmacChain(data, 'base64'):", 36, 1, 32, "base64", 2, "sha1HmacChain", 2, 2, "print", 2, 35, 32,
+"sha1HmacChain(data, 'binary'):", 36, 1, 32, "binary", 2, "sha1HmacChain", 2, 2, "print", 2, 35, 32,
+"sha1HmacChain(data, 'base64url'):", 36, 1, 32, "base64url", 2, "sha1HmacChain", 2, 2, "print", 2, 35, 32,
+"sha1Hex('abc'):", 32, "abc", 2, "sha1Hex", 1, 2, "print", 2, 35, 32, "sha1Hex(''):", 32, "", 2, "sha1Hex", 1, 2,
+"print", 2, 35, 32, "rfc2202 case 1:", 32,
"\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b\u000b",
32, "Hi There", 43, 2, 2, "sha1HmacChainHex", 1, 2, "print", 2, 35, 32, "rfc2202 case 2:", 32, "Jefe", 32,
"what do ya want for nothing?", 43, 2, 2, "sha1HmacChainHex", 1, 2, "print", 2, 35, 32, "rfc2202 case 5:", 32,
diff --git a/common/hogvm/__tests__/__snapshots__/crypto.stdout b/common/hogvm/__tests__/__snapshots__/crypto.stdout
index 919fc57dc552..195842a42d1b 100644
Binary files a/common/hogvm/__tests__/__snapshots__/crypto.stdout and b/common/hogvm/__tests__/__snapshots__/crypto.stdout differ
diff --git a/common/hogvm/__tests__/__snapshots__/crypto.stdout.compiledjs b/common/hogvm/__tests__/__snapshots__/crypto.stdout.compiledjs
deleted file mode 100644
index 340003bcefcb..000000000000
--- a/common/hogvm/__tests__/__snapshots__/crypto.stdout.compiledjs
+++ /dev/null
@@ -1,47 +0,0 @@
-string: this is a secure string
-md5Hex(string): e7b466647ea215dbe59b00c756560911
-md5Hex(null): null
-md5(string, 'hex'): md5 not implemented
-md5(null, 'hex'): md5 not implemented
-md5(string, 'binary'): md5 not implemented
-md5(null, 'binary'): md5 not implemented
-md5(string, 'base64'): md5 not implemented
-md5(null, 'base64'): md5 not implemented
-md5(string, 'base64url'): md5 not implemented
-md5(null, 'base64url'): md5 not implemented
-sha256Hex(string): 5216c0931310b31737ef30353830c234901283544e934f54eb75f622cfb86c9d
-sha256Hex(null): null
-sha256(string, 'hex'): sha256 not implemented
-sha256(null, 'hex'): sha256 not implemented
-sha256(string, 'binary'): sha256 not implemented
-sha256(null, 'binary'): sha256 not implemented
-sha256(string, 'base64'): sha256 not implemented
-sha256(null, 'base64'): sha256 not implemented
-sha256(string, 'base64url'): sha256 not implemented
-sha256(null, 'base64url'): sha256 not implemented
-sha1Hex(string): sha1Hex not implemented
-sha1Hex(null): sha1Hex not implemented
-sha1(string, 'hex'): sha1 not implemented
-sha1(null, 'hex'): sha1 not implemented
-sha1(string, 'binary'): sha1 not implemented
-sha1(null, 'binary'): sha1 not implemented
-sha1(string, 'base64'): sha1 not implemented
-sha1(null, 'base64'): sha1 not implemented
-sha1(string, 'base64url'): sha1 not implemented
-sha1(null, 'base64url'): sha1 not implemented
-data: ['1', 'string', 'more', 'keys']
-sha256HmacChainHex(data): sha256HmacChainHex not implemented
-sha256HmacChain(data, 'hex'): sha256HmacChain not implemented
-sha256HmacChain(data, 'base64'): sha256HmacChain not implemented
-sha256HmacChain(data, 'binary'): sha256HmacChain not implemented
-sha256HmacChain(data, 'base64url'): sha256HmacChain not implemented
-sha1HmacChainHex(data): sha1HmacChainHex not implemented
-sha1HmacChain(data, 'hex'): sha1HmacChain not implemented
-sha1HmacChain(data, 'base64'): sha1HmacChain not implemented
-sha1HmacChain(data, 'binary'): sha1HmacChain not implemented
-sha1HmacChain(data, 'base64url'): sha1HmacChain not implemented
-sha1Hex('abc'): sha1Hex not implemented
-sha1Hex(''): sha1Hex not implemented
-rfc2202 case 1: sha1HmacChainHex not implemented
-rfc2202 case 2: sha1HmacChainHex not implemented
-rfc2202 case 5: sha1HmacChainHex not implemented
diff --git a/common/hogvm/__tests__/__snapshots__/crypto.stdout.nodejs b/common/hogvm/__tests__/__snapshots__/crypto.stdout.nodejs
deleted file mode 100644
index 466d121779cb..000000000000
Binary files a/common/hogvm/__tests__/__snapshots__/crypto.stdout.nodejs and /dev/null differ
diff --git a/common/hogvm/__tests__/__snapshots__/crypto.stdout.python b/common/hogvm/__tests__/__snapshots__/crypto.stdout.python
deleted file mode 100644
index 466d121779cb..000000000000
Binary files a/common/hogvm/__tests__/__snapshots__/crypto.stdout.python and /dev/null differ
diff --git a/common/hogvm/__tests__/__snapshots__/cryptoHex.hoge b/common/hogvm/__tests__/__snapshots__/cryptoHex.hoge
new file mode 100644
index 000000000000..8dbbf0330a77
--- /dev/null
+++ b/common/hogvm/__tests__/__snapshots__/cryptoHex.hoge
@@ -0,0 +1,3 @@
+["_H", 1, 32, "this is a secure string", 32, "string:", 36, 0, 2, "print", 2, 35, 32, "md5Hex(string):", 36, 0, 2,
+"md5Hex", 1, 2, "print", 2, 35, 32, "md5Hex(null):", 31, 2, "md5Hex", 1, 2, "print", 2, 35, 32, "sha256Hex(string):",
+36, 0, 2, "sha256Hex", 1, 2, "print", 2, 35, 32, "sha256Hex(null):", 31, 2, "sha256Hex", 1, 2, "print", 2, 35, 35]
diff --git a/common/hogvm/__tests__/__snapshots__/cryptoHex.js b/common/hogvm/__tests__/__snapshots__/cryptoHex.js
new file mode 100644
index 000000000000..ea0bbf1b52dc
--- /dev/null
+++ b/common/hogvm/__tests__/__snapshots__/cryptoHex.js
@@ -0,0 +1,47 @@
+function sha256Hex(data) {if (data === null || data == undefined) return null; let h0=0x6a09e667,h1=0xbb67ae85,h2=0x3c6ef372,h3=0xa54ff53a,h4=0x510e527f,h5=0x9b05688c,h6=0x1f83d9ab,h7=0x5be0cd19,tsz=0,bp=0;const k=[0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2],rrot=(x,n)=>(x>>>n)|(x<<(32-n)),w=new Uint32Array(64),buf=new Uint8Array(64),process=()=>{for(let j=0,r=0;j<16;j++,r+=4){w[j]=(buf[r]<<24)|(buf[r+1]<<16)|(buf[r+2]<<8)|buf[r+3]}for(let j=16;j<64;j++){let s0=rrot(w[j-15],7)^rrot(w[j-15],18)^(w[j-15]>>>3);let s1=rrot(w[j-2],17)^rrot(w[j-2],19)^(w[j-2]>>>10);w[j]=(w[j-16]+s0+w[j-7]+s1)|0}let a=h0,b=h1,c=h2,d=h3,e=h4,f=h5,g=h6,h=h7;for(let j=0;j<64;j++){let S1=rrot(e,6)^rrot(e,11)^rrot(e,25),ch=(e&f)^((~e)&g),t1=(h+S1+ch+k[j]+w[j])|0,S0=rrot(a,2)^rrot(a,13)^rrot(a,22),maj=(a&b)^(a&c)^(b&c),t2=(S0+maj)|0;h=g;g=f;f=e;e=(d+t1)|0;d=c;c=b;b=a;a=(t1+t2)|0}h0=(h0+a)|0;h1=(h1+b)|0;h2=(h2+c)|0;h3=(h3+d)|0;h4=(h4+e)|0;h5=(h5+f)|0;h6=(h6+g)|0;h7=(h7+h)|0;bp=0},add=data=>{if(typeof data==="string"){data=typeof TextEncoder==="undefined"?Buffer.from(data):(new TextEncoder).encode(data)}for(let i=0;i<data.length;i++){buf[bp++]=data[i];if(bp===64)process();}tsz+=data.length},digest=()=>{buf[bp++]=0x80;if(bp==64)process();if(bp+8>64){while(bp<64)buf[bp++]=0x00;process()}while(bp<58)buf[bp++]=0x00;let L=tsz*8;buf[bp++]=(L/1099511627776.)&255;buf[bp++]=(L/4294967296.)&255;buf[bp++]=L>>>24;buf[bp++]=(L>>>16)&255;buf[bp++]=(L>>>8)&255;buf[bp++]=L&255;process();let reply=new Uint8Array(32);reply[0]=h0>>>24;reply[1]=(h0>>>16)&255;reply[2]=(h0>>>8)&255;reply[3]=h0&255;reply[4]=h1>>>24;reply[5]=(h1>>>16)&255;reply[6]=(h1>>>8)&255;reply[7]=h1&255;reply[8]=h2>>>24;reply[9]=(h2>>>16)&255;reply[10]=(h2>>>8)&255;reply[11]=h2&255;reply[12]=h3>>>24;reply[13]=(h3>>>16)&255;reply[14]=(h3>>>8)&255;reply[15]=h3&255;reply[16]=h4>>>24;reply[17]=(h4>>>16)&255;reply[18]=(h4>>>8)&255;reply[19]=h4&255;reply[20]=h5>>>24;reply[21]=(h5>>>16)&255;reply[22]=(h5>>>8)&255;reply[23]=h5&255;reply[24]=h6>>>24;reply[25]=(h6>>>16)&255;reply[26]=(h6>>>8)&255;reply[27]=h6&255;reply[28]=h7>>>24;reply[29]=(h7>>>16)&255;reply[30]=(h7>>>8)&255;reply[31]=h7&255;reply.hex=()=>{let res="";reply.forEach(x=>res+=("0"+x.toString(16)).slice(-2));return res};return reply};if(data===undefined)return{add,digest};add(data);return digest().hex()}
+function print (...args) { console.log(...args.map(__printHogStringOutput)) }
+function md5Hex(s) {if (s === null || s == undefined) return null; var k=[],i=0;for(;i<64;){k[i]=0|Math.sin(++i%Math.PI)*4294967296}var b,c,d,h=[b=0x67452301,c=0xEFCDAB89,~b,~c],words=[],j=unescape(encodeURI(s))+'€',a=j.length;s=(--a/4+2)|15;words[--s]=a*8;for(;~a;){words[a>>2]|=j.charCodeAt(a)<<8*a--}for(i=j=0;i<s;i+=16){a=h;for(;j<64;a=[d=a[3],(b+((d=a[0]+[b&c|~b&d,d&b|~d&c,b^c^d,c^(b|~d)][a=j>>4]+k[j]+~~words[i|[j,5*j+1,3*j+5,7*j][a]&15])<<(a=[7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21][4*a+j++%4])|d>>>-a)),b,c]){b=a[1]|0;c=a[2]}for(j=4;j;)h[--j]+=a[j]}for(s='';j<32;){s+=((h[j>>3]>>((1^j++)*4))&15).toString(16)}return s}
+function __printHogStringOutput(obj) { if (typeof obj === 'string') { return obj } return __printHogValue(obj) }
+function __printHogValue(obj, marked = new Set()) {
+ if (typeof obj === 'object' && obj !== null && obj !== undefined) {
+ if (marked.has(obj) && !__isHogDateTime(obj) && !__isHogDate(obj) && !__isHogError(obj)) { return 'null'; }
+ marked.add(obj);
+ try {
+ if (Array.isArray(obj)) {
+ if (obj.__isHogTuple) { return obj.length < 2 ? `tuple(${obj.map((o) => __printHogValue(o, marked)).join(', ')})` : `(${obj.map((o) => __printHogValue(o, marked)).join(', ')})`; }
+ return `[${obj.map((o) => __printHogValue(o, marked)).join(', ')}]`;
+ }
+ if (__isHogDateTime(obj)) { const millis = String(obj.dt); return `DateTime(${millis}${millis.includes('.') ? '' : '.0'}, ${__escapeString(obj.zone)})`; }
+ if (__isHogDate(obj)) return `Date(${obj.year}, ${obj.month}, ${obj.day})`;
+ if (__isHogError(obj)) { return `${String(obj.type)}(${__escapeString(obj.message)}${obj.payload ? `, ${__printHogValue(obj.payload, marked)}` : ''})`; }
+ if (obj instanceof Map) { return `{${Array.from(obj.entries()).map(([key, value]) => `${__printHogValue(key, marked)}: ${__printHogValue(value, marked)}`).join(', ')}}`; }
+ return `{${Object.entries(obj).map(([key, value]) => `${__printHogValue(key, marked)}: ${__printHogValue(value, marked)}`).join(', ')}}`;
+ } finally {
+ marked.delete(obj);
+ }
+ } else if (typeof obj === 'boolean') return obj ? 'true' : 'false';
+ else if (obj === null || obj === undefined) return 'null';
+ else if (typeof obj === 'string') return __escapeString(obj);
+ if (typeof obj === 'function') return `fn<${__escapeIdentifier(obj.name || 'lambda')}(${obj.length})>`;
+ return obj.toString();
+}
+function __isHogError(obj) {return obj && obj.__hogError__ === true}
+function __isHogDateTime(obj) { return obj && obj.__hogDateTime__ === true }
+function __isHogDate(obj) { return obj && obj.__hogDate__ === true }
+function __escapeString(value) {
+ const singlequoteEscapeCharsMap = { '\b': '\\b', '\f': '\\f', '\r': '\\r', '\n': '\\n', '\t': '\\t', '\0': '\\0', '\v': '\\v', '\\': '\\\\', "'": "\\'" }
+ return `'${value.split('').map((c) => singlequoteEscapeCharsMap[c] || c).join('')}'`;
+}
+function __escapeIdentifier(identifier) {
+ const backquoteEscapeCharsMap = { '\b': '\\b', '\f': '\\f', '\r': '\\r', '\n': '\\n', '\t': '\\t', '\0': '\\0', '\v': '\\v', '\\': '\\\\', '`': '``' }
+ if (typeof identifier === 'number') return identifier.toString();
+ if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(identifier)) return identifier;
+ return `\`${identifier.split('').map((c) => backquoteEscapeCharsMap[c] || c).join('')}\``;
+}
+
+let string = "this is a secure string";
+print("string:", string);
+print("md5Hex(string):", md5Hex(string));
+print("md5Hex(null):", md5Hex(null));
+print("sha256Hex(string):", sha256Hex(string));
+print("sha256Hex(null):", sha256Hex(null));
diff --git a/common/hogvm/__tests__/__snapshots__/cryptoHex.stdout b/common/hogvm/__tests__/__snapshots__/cryptoHex.stdout
new file mode 100644
index 000000000000..04164d02092c
--- /dev/null
+++ b/common/hogvm/__tests__/__snapshots__/cryptoHex.stdout
@@ -0,0 +1,5 @@
+string: this is a secure string
+md5Hex(string): e7b466647ea215dbe59b00c756560911
+md5Hex(null): null
+sha256Hex(string): 5216c0931310b31737ef30353830c234901283544e934f54eb75f622cfb86c9d
+sha256Hex(null): null
diff --git a/common/hogvm/__tests__/__snapshots__/hogqlx.js b/common/hogvm/__tests__/__snapshots__/hogqlx.js
index bed7c4d2a6e6..721bc89c0f92 100644
--- a/common/hogvm/__tests__/__snapshots__/hogqlx.js
+++ b/common/hogvm/__tests__/__snapshots__/hogqlx.js
@@ -1,4 +1,4 @@
-function replaceAll (str, searchValue, replaceValue) { return str.replaceAll(searchValue, replaceValue) }
+function replaceAll (str, searchValue, replaceValue) { return str === null || str === undefined ? null : str.replaceAll(searchValue, replaceValue) }
function print (...args) { console.log(...args.map(__printHogStringOutput)) }
function jsonStringify (value, spacing) {
function convert(x, marked) {
diff --git a/common/hogvm/__tests__/__snapshots__/lambdas.js b/common/hogvm/__tests__/__snapshots__/lambdas.js
index e44df512d201..a63842c049fe 100644
--- a/common/hogvm/__tests__/__snapshots__/lambdas.js
+++ b/common/hogvm/__tests__/__snapshots__/lambdas.js
@@ -37,7 +37,7 @@ function jsonParse (str) {
const obj = {}; for (const key in x) { obj[key] = convert(x[key]) }; return obj }
return x }
return convert(JSON.parse(str)) }
-function arrayMap (func, arr) { let result = []; for (let i = 0; i < arr.length; i++) { result = arrayPushBack(result, func(arr[i])) } return result }
+function arrayMap (func, arr) { let result = []; for (let i = 0; i < (arr ?? []).length; i++) { result = arrayPushBack(result, func(arr[i])) } return result }
function arrayPushBack (arr, item) { if (!Array.isArray(arr)) { return [item] } return [...arr, item] }
function __toHogDateTime(timestamp, zone) {
if (__isHogDate(timestamp)) {
diff --git a/common/hogvm/__tests__/__snapshots__/loops.js b/common/hogvm/__tests__/__snapshots__/loops.js
index 5da1e3089e50..9622dc40fb4e 100644
--- a/common/hogvm/__tests__/__snapshots__/loops.js
+++ b/common/hogvm/__tests__/__snapshots__/loops.js
@@ -26,6 +26,7 @@ function __printHogValue(obj, marked = new Set()) {
if (typeof obj === 'function') return `fn<${__escapeIdentifier(obj.name || 'lambda')}(${obj.length})>`;
return obj.toString();
}
+function __lt (a, b) { return a === null || a === undefined || b === null || b === undefined ? false : a < b }
function __isHogError(obj) {return obj && obj.__hogError__ === true}
function __isHogDateTime(obj) { return obj && obj.__hogDateTime__ === true }
function __isHogDate(obj) { return obj && obj.__hogDate__ === true }
@@ -43,7 +44,7 @@ function __escapeIdentifier(identifier) {
print("-- test while loop --");
{
let i = 0;
- while ((i < 3)) {
+ while (__lt(i, 3)) {
i = (i + 1)
print(i);
}
@@ -51,14 +52,14 @@ print("-- test while loop --");
}
print("-- test for loop --");
{
- for (let i = 0; (i < 3); i = (i + 1)) {
+ for (let i = 0; __lt(i, 3); i = (i + 1)) {
print(i);
}
}
print("-- test emptier for loop --");
{
let i = 0;
- for (; (i < 3); ) {
+ for (; __lt(i, 3); ) {
print("woo");
i = (i + 1)
}
diff --git a/common/hogvm/__tests__/__snapshots__/mandelbrot.js b/common/hogvm/__tests__/__snapshots__/mandelbrot.js
index eef7a38c0e6a..2b681eddcef6 100644
--- a/common/hogvm/__tests__/__snapshots__/mandelbrot.js
+++ b/common/hogvm/__tests__/__snapshots__/mandelbrot.js
@@ -1,5 +1,7 @@
function print (...args) { console.log(...args.map(__printHogStringOutput)) }
function concat (...args) { return args.map((arg) => (arg === null ? '' : __STLToString(arg))).join('') }
+function __lte (a, b) { return a === null || a === undefined || b === null || b === undefined ? false : a <= b }
+function __lt (a, b) { return a === null || a === undefined || b === null || b === undefined ? false : a < b }
function __STLToString(arg) {
if (arg && __isHogDate(arg)) { return `${arg.year}-${arg.month.toString().padStart(2, '0')}-${arg.day.toString().padStart(2, '0')}`; }
else if (arg && __isHogDateTime(arg)) { return __DateTimeToString(arg); }
@@ -86,7 +88,7 @@ function mandelbrot(re, im, max_iter) {
let z_re = 0.0;
let z_im = 0.0;
let n = 0;
- while (!!((((z_re * z_re) + (z_im * z_im)) <= 4) && (n < max_iter))) {
+ while (!!(__lte(((z_re * z_re) + (z_im * z_im)), 4) && __lt(n, max_iter))) {
let temp_re = (((z_re * z_re) - (z_im * z_im)) + re);
let temp_im = (((2 * z_re) * z_im) + im);
z_re = temp_re
@@ -108,10 +110,10 @@ function main() {
let ymax = 1.0;
let max_iter = 30;
let y = 0;
- while ((y < height)) {
+ while (__lt(y, height)) {
let row = "";
let x = 0;
- while ((x < width)) {
+ while (__lt(x, width)) {
let re = (((x / width) * (xmax - xmin)) + xmin);
let im = (((y / height) * (ymax - ymin)) + ymin);
let letter = mandelbrot(re, im, max_iter);
diff --git a/common/hogvm/__tests__/__snapshots__/nulls.hoge b/common/hogvm/__tests__/__snapshots__/nulls.hoge
index 158c79563beb..2f28888abb69 100644
--- a/common/hogvm/__tests__/__snapshots__/nulls.hoge
+++ b/common/hogvm/__tests__/__snapshots__/nulls.hoge
@@ -2,4 +2,22 @@
2, "match", 2, 2, "print", 1, 35, 31, 32, "u", 2, "match", 2, 2, "print", 1, 35, 31, 32, "b", 2, "match", 2, 2, "print",
1, 35, 32, "uu", 31, 2, "match", 2, 2, "print", 1, 35, 32, "null", 31, 2, "match", 2, 2, "print", 1, 35, 32, "u", 32,
"uu", 23, 2, "print", 1, 35, 32, "b", 32, "uu", 23, 2, "print", 1, 35, 32, "u", 31, 23, 2, "print", 1, 35, 32, "b", 31,
-23, 2, "print", 1, 35, 31, 32, "uu", 23, 2, "print", 1, 35, 31, 32, "null", 23, 2, "print", 1, 35]
+23, 2, "print", 1, 35, 31, 32, "uu", 23, 2, "print", 1, 35, 31, 32, "null", 23, 2, "print", 1, 35, 32,
+"-- string and array functions on null --", 2, "print", 1, 35, 31, 2, "length", 1, 2, "print", 1, 35, 31, 2, "upper", 1,
+2, "print", 1, 35, 31, 2, "reverse", 1, 2, "print", 1, 35, 31, 32, "a", 32, "b", 2, "replaceOne", 3, 2, "print", 1, 35,
+31, 32, "a", 32, "b", 2, "replaceAll", 3, 2, "print", 1, 35, 31, 2, "trim", 1, 2, "print", 1, 35, 31, 2, "trimLeft", 1,
+2, "print", 1, 35, 31, 2, "trimRight", 1, 2, "print", 1, 35, 31, 2, "keys", 1, 2, "print", 1, 35, 31, 2, "values", 1, 2,
+"print", 1, 35, 52, "lambda", 1, 0, 6, 32, "a", 36, 0, 11, 38, 53, 0, 31, 2, "arrayExists", 2, 2, "print", 1, 35, 52,
+"lambda", 1, 0, 3, 36, 0, 38, 53, 0, 31, 2, "arrayMap", 2, 2, "print", 1, 35, 52, "lambda", 1, 0, 6, 32, "a", 36, 0, 11,
+38, 53, 0, 31, 2, "arrayFilter", 2, 2, "print", 1, 35, 52, "lambda", 1, 0, 6, 32, "a", 36, 0, 11, 38, 53, 0, 31, 2,
+"arrayCount", 2, 2, "print", 1, 35, 52, "lambda", 2, 0, 6, 36, 1, 36, 0, 6, 38, 53, 0, 31, 33, 0, 2, "arrayReduce", 3,
+2, "print", 1, 35, 32, " ", 31, 2, "splitByString", 2, 2, "print", 1, 35, 32, " ", 31, 2, "splitByString", 2, 2,
+"arrayPopFront", 1, 32, " ", 2, "arrayStringConcat", 2, 2, "print", 1, 35, 31, 33, 0, 11, 2, "print", 1, 35, 31, 33, 0,
+12, 2, "print", 1, 35, 31, 33, 0, 33, 1, 33, 10, 36, 2, 31, 12, 36, 3, 31, 12, 36, 1, 31, 12, 3, 3, 40, 14, 36, 2, 36,
+1, 15, 36, 3, 36, 1, 13, 4, 2, 39, 1, 30, 37, 0, 35, 35, 35, 2, "print", 1, 35, 33, 3, 31, 2, "length", 1, 13, 2,
+"print", 1, 35, 33, 3, 31, 2, "length", 1, 15, 2, "print", 1, 35, 33, 3, 31, 15, 2, "print", 1, 35, 33, 0, 31, 16, 2,
+"print", 1, 35, 33, 3, 31, 13, 2, "print", 1, 35, 33, 0, 31, 14, 2, "print", 1, 35, 31, 33, 3, 13, 2, "print", 1, 35,
+31, 31, 13, 2, "print", 1, 35, 33, 3, 31, 2, "length", 1, 13, 5, 2, "print", 1, 35, 33, 0, 31, 2, "length", 1, 11, 2,
+"print", 1, 35, 31, 33, 3, 2, "less", 2, 2, "print", 1, 35, 33, 3, 31, 2, "greater", 2, 2, "print", 1, 35, 31, 31, 2,
+"lessOrEquals", 2, 2, "print", 1, 35, 31, 33, 0, 2, "greaterOrEquals", 2, 2, "print", 1, 35, 33, 1, 33, 3, 2, "less", 2,
+2, "print", 1, 35]
diff --git a/common/hogvm/__tests__/__snapshots__/nulls.js b/common/hogvm/__tests__/__snapshots__/nulls.js
index e3fcd93b9c52..8b32fff07682 100644
--- a/common/hogvm/__tests__/__snapshots__/nulls.js
+++ b/common/hogvm/__tests__/__snapshots__/nulls.js
@@ -1,5 +1,80 @@
+function values (obj) { if (typeof obj === 'object' && obj !== null) { if (Array.isArray(obj)) { return [...obj] } else if (obj instanceof Map) { return Array.from(obj.values()) } return Object.values(obj) } return [] }
+function upper (value) { return value === null || value === undefined ? null : value.toUpperCase() }
+function trimRight (str, char) {
+ if (str === null || str === undefined) {
+ return null
+ }
+ if (char === null || char === undefined) {
+ char = ' '
+ }
+ if (char.length !== 1) {
+ return ''
+ }
+ let end = str.length
+ while (str[end - 1] === char) {
+ end--
+ }
+ return str.slice(0, end)
+}
+function trimLeft (str, char) {
+ if (str === null || str === undefined) {
+ return null
+ }
+ if (char === null || char === undefined) {
+ char = ' '
+ }
+ if (char.length !== 1) {
+ return ''
+ }
+ let start = 0
+ while (str[start] === char) {
+ start++
+ }
+ return str.slice(start)
+}
+function trim (str, char) {
+ if (str === null || str === undefined) {
+ return null
+ }
+ if (char === null || char === undefined) {
+ char = ' '
+ }
+ if (char.length !== 1) {
+ return ''
+ }
+ let start = 0
+ while (str[start] === char) {
+ start++
+ }
+ let end = str.length
+ while (str[end - 1] === char) {
+ end--
+ }
+ if (start >= end) {
+ return ''
+ }
+ return str.slice(start, end)
+}
+function splitByString (separator, str, maxSplits) { if (str === null || str === undefined) { return null } if (maxSplits === undefined || maxSplits === null) { return str.split(separator) } return str.split(separator, maxSplits) }
+function reverse (value) { return value === null || value === undefined ? null : value.split('').reverse().join('') }
+function replaceOne (str, searchValue, replaceValue) { return str === null || str === undefined ? null : str.replace(searchValue, replaceValue) }
+function replaceAll (str, searchValue, replaceValue) { return str === null || str === undefined ? null : str.replaceAll(searchValue, replaceValue) }
function print (...args) { console.log(...args.map(__printHogStringOutput)) }
function match (str, pattern) { return !str || !pattern ? false : new RegExp(pattern).test(str) }
+function lessOrEquals(a, b) { return a !== null && a !== undefined && b !== null && b !== undefined && a <= b }
+function less(a, b) { return a !== null && a !== undefined && b !== null && b !== undefined && a < b }
+function length (value) { return value === null || value === undefined ? null : value.length }
+function keys (obj) { if (typeof obj === 'object' && obj !== null) { if (Array.isArray(obj)) { return Array.from(obj.keys()) } else if (obj instanceof Map) { return Array.from(obj.keys()) } return Object.keys(obj) } return [] }
+function greaterOrEquals(a, b) { return a !== null && a !== undefined && b !== null && b !== undefined && a >= b }
+function greater(a, b) { return a !== null && a !== undefined && b !== null && b !== undefined && a > b }
+function arrayStringConcat (arr, separator = '') { if (!Array.isArray(arr)) { return '' } return arr.join(separator) }
+function arrayReduce (func, arr, initial) { let result = initial; for (let i = 0; i < (arr ?? []).length; i++) { result = func(result, arr[i]) } return result }
+function arrayPopFront (arr) { if (!Array.isArray(arr)) { return [] } return arr.slice(1) }
+function arrayMap (func, arr) { let result = []; for (let i = 0; i < (arr ?? []).length; i++) { result = arrayPushBack(result, func(arr[i])) } return result }
+function arrayFilter (func, arr) { let result = []; for (let i = 0; i < (arr ?? []).length; i++) { if (func(arr[i])) { result = arrayPushBack(result, arr[i]) } } return result}
+function arrayPushBack (arr, item) { if (!Array.isArray(arr)) { return [item] } return [...arr, item] }
+function arrayExists (func, arr) { for (let i = 0; i < (arr ?? []).length; i++) { if (func(arr[i])) { return true } } return false }
+function arrayCount (func, arr) { let count = 0; for (let i = 0; i < (arr ?? []).length; i++) { if (func(arr[i])) { count = count + 1 } } return count }
function __printHogStringOutput(obj) { if (typeof obj === 'string') { return obj } return __printHogValue(obj) }
function __printHogValue(obj, marked = new Set()) {
if (typeof obj === 'object' && obj !== null && obj !== undefined) {
@@ -24,9 +99,14 @@ function __printHogValue(obj, marked = new Set()) {
if (typeof obj === 'function') return `fn<${__escapeIdentifier(obj.name || 'lambda')}(${obj.length})>`;
return obj.toString();
}
+function __lte (a, b) { return a === null || a === undefined || b === null || b === undefined ? false : a <= b }
+function __lt (a, b) { return a === null || a === undefined || b === null || b === undefined ? false : a < b }
+function __lambda (fn) { return fn }
function __isHogError(obj) {return obj && obj.__hogError__ === true}
function __isHogDateTime(obj) { return obj && obj.__hogDateTime__ === true }
function __isHogDate(obj) { return obj && obj.__hogDate__ === true }
+function __gte (a, b) { return a === null || a === undefined || b === null || b === undefined ? false : a >= b }
+function __gt (a, b) { return a === null || a === undefined || b === null || b === undefined ? false : a > b }
function __escapeString(value) {
const singlequoteEscapeCharsMap = { '\b': '\\b', '\f': '\\f', '\r': '\\r', '\n': '\\n', '\t': '\\t', '\0': '\\0', '\v': '\\v', '\\': '\\\\', "'": "\\'" }
return `'${value.split('').map((c) => singlequoteEscapeCharsMap[c] || c).join('')}'`;
@@ -51,3 +131,39 @@ print(match(null, "u"));
print(match(null, "b"));
print(match("uu", null));
print(match("null", null));
+print("-- string and array functions on null --");
+print(length(null));
+print(upper(null));
+print(reverse(null));
+print(replaceOne(null, "a", "b"));
+print(replaceAll(null, "a", "b"));
+print(trim(null));
+print(trimLeft(null));
+print(trimRight(null));
+print(keys(null));
+print(values(null));
+print(arrayExists(__lambda((x) => (x == "a")), null));
+print(arrayMap(__lambda((x) => x), null));
+print(arrayFilter(__lambda((x) => (x == "a")), null));
+print(arrayCount(__lambda((x) => (x == "a")), null));
+print(arrayReduce(__lambda((acc, x) => (acc + x)), null, 0));
+print(splitByString(" ", null));
+print(arrayStringConcat(arrayPopFront(splitByString(" ", null)), " "));
+print((0 == null));
+print((0 != null));
+print((() => { const expr=(0), low=(1), high=(10); return expr !== null && expr !== undefined && low !== null && low !== undefined && high !== null && high !== undefined && !!(expr < 1 || expr > 10); })());
+print(__gt(length(null), 3));
+print(__lt(length(null), 3));
+print(__lt(null, 3));
+print(__lte(null, 0));
+print(__gt(null, 3));
+print(__gte(null, 0));
+print(__gt(3, null));
+print(__gt(null, null));
+print((!__gt(length(null), 3)));
+print((length(null) == 0));
+print(less(null, 3));
+print(greater(3, null));
+print(lessOrEquals(null, null));
+print(greaterOrEquals(null, 0));
+print(less(1, 3));
diff --git a/common/hogvm/__tests__/__snapshots__/nulls.stdout b/common/hogvm/__tests__/__snapshots__/nulls.stdout
index 5061b9659db8..4dc09fcc1098 100644
--- a/common/hogvm/__tests__/__snapshots__/nulls.stdout
+++ b/common/hogvm/__tests__/__snapshots__/nulls.stdout
@@ -11,3 +11,39 @@ false
false
false
false
+-- string and array functions on null --
+null
+null
+null
+null
+null
+null
+null
+null
+[]
+[]
+false
+[]
+[]
+0
+0
+null
+
+false
+true
+true
+false
+false
+false
+false
+false
+false
+false
+false
+true
+false
+false
+false
+false
+false
+true
diff --git a/common/hogvm/__tests__/__snapshots__/operations.js b/common/hogvm/__tests__/__snapshots__/operations.js
index ad85996fc3ec..ea964aeec2f9 100644
--- a/common/hogvm/__tests__/__snapshots__/operations.js
+++ b/common/hogvm/__tests__/__snapshots__/operations.js
@@ -41,6 +41,8 @@ function jsonStringify (value, spacing) {
}
function ilike (str, pattern) { return __like(str, pattern, true) }
function concat (...args) { return args.map((arg) => (arg === null ? '' : __STLToString(arg))).join('') }
+function __lte (a, b) { return a === null || a === undefined || b === null || b === undefined ? false : a <= b }
+function __lt (a, b) { return a === null || a === undefined || b === null || b === undefined ? false : a < b }
function __like(str, pattern, caseInsensitive = false) {
if (caseInsensitive) {
str = str.toLowerCase()
@@ -53,6 +55,8 @@ function __like(str, pattern, caseInsensitive = false) {
return new RegExp(pattern).test(str)
}
function __imatch (str, pattern) { return !str || !pattern ? false : new RegExp(pattern, 'i').test(str) }
+function __gte (a, b) { return a === null || a === undefined || b === null || b === undefined ? false : a >= b }
+function __gt (a, b) { return a === null || a === undefined || b === null || b === undefined ? false : a > b }
function __STLToString(arg) {
if (arg && __isHogDate(arg)) { return `${arg.year}-${arg.month.toString().padStart(2, '0')}-${arg.day.toString().padStart(2, '0')}`; }
else if (arg && __isHogDateTime(arg)) { return __DateTimeToString(arg); }
@@ -158,10 +162,10 @@ test(3.14);
test((1 == 2));
test((1 == 2));
test((1 != 2));
-test((1 < 2));
-test((1 <= 2));
-test((1 > 2));
-test((1 >= 2));
+test(__lt(1, 2));
+test(__lte(1, 2));
+test(__gt(1, 2));
+test(__gte(1, 2));
test(like("a", "b"));
test(like("baa", "%a%"));
test(like("baa", "%x%"));
@@ -212,14 +216,14 @@ test((1 != false));
test((1 == "2"));
test((1 == "2"));
test((1 != "2"));
-test((1 < "2"));
-test((1 <= "2"));
-test((1 > "2"));
-test((1 >= "2"));
+test(__lt(1, "2"));
+test(__lte(1, "2"));
+test(__gt(1, "2"));
+test(__gte(1, "2"));
test(("1" == 2));
test(("1" == 2));
test(("1" != 2));
-test(("1" < 2));
-test(("1" <= 2));
-test(("1" > 2));
-test(("1" >= 2));
+test(__lt("1", 2));
+test(__lte("1", 2));
+test(__gt("1", 2));
+test(__gte("1", 2));
diff --git a/common/hogvm/__tests__/__snapshots__/printLoops.js b/common/hogvm/__tests__/__snapshots__/printLoops.js
index e2f9f92c09b9..779e44f3bbd1 100644
--- a/common/hogvm/__tests__/__snapshots__/printLoops.js
+++ b/common/hogvm/__tests__/__snapshots__/printLoops.js
@@ -58,6 +58,7 @@ function __newHogError(type, message, payload) {
error.payload = payload
return error
}
+function __lt (a, b) { return a === null || a === undefined || b === null || b === undefined ? false : a < b }
function __STLToString(arg) {
if (arg && __isHogDate(arg)) { return `${arg.year}-${arg.month.toString().padStart(2, '0')}-${arg.day.toString().padStart(2, '0')}`; }
else if (arg && __isHogDateTime(arg)) { return __DateTimeToString(arg); }
@@ -142,7 +143,7 @@ function __DateTimeToString(dt) {
let obj = {"key": "value", "key2": "value2"};
let str = "na";
-for (let i = 0; (i < 100); i = (i + 1)) {
+for (let i = 0; __lt(i, 100); i = (i + 1)) {
str = concat(str, "na")
__setProperty(obj, concat("key_", i), {"wasted": concat("memory: ", str, " batman!"), "something": obj});
}
diff --git a/common/hogvm/__tests__/__snapshots__/printLoops2.js b/common/hogvm/__tests__/__snapshots__/printLoops2.js
index 0c4c3e2f66a5..e6fc42a3ec72 100644
--- a/common/hogvm/__tests__/__snapshots__/printLoops2.js
+++ b/common/hogvm/__tests__/__snapshots__/printLoops2.js
@@ -58,6 +58,7 @@ function __newHogError(type, message, payload) {
error.payload = payload
return error
}
+function __lt (a, b) { return a === null || a === undefined || b === null || b === undefined ? false : a < b }
function __STLToString(arg) {
if (arg && __isHogDate(arg)) { return `${arg.year}-${arg.month.toString().padStart(2, '0')}-${arg.day.toString().padStart(2, '0')}`; }
else if (arg && __isHogDateTime(arg)) { return __DateTimeToString(arg); }
@@ -142,7 +143,7 @@ function __DateTimeToString(dt) {
let root = {"key": "value", "key2": "value2"};
let leaf = {"key": "value", "key2": "value2"};
-for (let i = 0; (i < 30); i = (i + 1)) {
+for (let i = 0; __lt(i, 30); i = (i + 1)) {
__setProperty(root, concat("key_", i), {"something": leaf});
}
print(root);
diff --git a/common/hogvm/__tests__/__snapshots__/recursion.js b/common/hogvm/__tests__/__snapshots__/recursion.js
index 341f87fb5168..2577c0118a7c 100644
--- a/common/hogvm/__tests__/__snapshots__/recursion.js
+++ b/common/hogvm/__tests__/__snapshots__/recursion.js
@@ -23,6 +23,7 @@ function __printHogValue(obj, marked = new Set()) {
if (typeof obj === 'function') return `fn<${__escapeIdentifier(obj.name || 'lambda')}(${obj.length})>`;
return obj.toString();
}
+function __lt (a, b) { return a === null || a === undefined || b === null || b === undefined ? false : a < b }
function __lambda (fn) { return fn }
function __isHogError(obj) {return obj && obj.__hogError__ === true}
function __isHogDateTime(obj) { return obj && obj.__hogDateTime__ === true }
@@ -39,7 +40,7 @@ function __escapeIdentifier(identifier) {
}
let fibonacci = __lambda((number) => {
- if ((number < 2)) {
+ if (__lt(number, 2)) {
return number;
} else {
return (fibonacci((number - 1)) + fibonacci((number - 2)));
@@ -47,7 +48,7 @@ let fibonacci = __lambda((number) => {
});
print(fibonacci(6));
function hogonacci(number) {
- if ((number < 2)) {
+ if (__lt(number, 2)) {
return number;
} else {
return (hogonacci((number - 1)) + hogonacci((number - 2)));
diff --git a/common/hogvm/__tests__/__snapshots__/stl.js b/common/hogvm/__tests__/__snapshots__/stl.js
index 6eb8a98ea828..5b6dc55a8adb 100644
--- a/common/hogvm/__tests__/__snapshots__/stl.js
+++ b/common/hogvm/__tests__/__snapshots__/stl.js
@@ -1,4 +1,4 @@
-function upper (value) { return value.toUpperCase() }
+function upper (value) { return value === null || value === undefined ? null : value.toUpperCase() }
function __x_typeof (value) {
if (value === null || value === undefined) { return 'null'
} else if (__isHogDateTime(value)) { return 'datetime'
@@ -74,9 +74,9 @@ function startsWith(str, prefix) {
return typeof str === 'string' && typeof prefix === 'string' && str.startsWith(prefix);
}
function round(a) { return Math.round(a) }
-function reverse (value) { return value.split('').reverse().join('') }
-function replaceOne (str, searchValue, replaceValue) { return str.replace(searchValue, replaceValue) }
-function replaceAll (str, searchValue, replaceValue) { return str.replaceAll(searchValue, replaceValue) }
+function reverse (value) { return value === null || value === undefined ? null : value.split('').reverse().join('') }
+function replaceOne (str, searchValue, replaceValue) { return str === null || str === undefined ? null : str.replace(searchValue, replaceValue) }
+function replaceAll (str, searchValue, replaceValue) { return str === null || str === undefined ? null : str.replaceAll(searchValue, replaceValue) }
function range(...args) {
if (args.length === 1) {
const end = args[0];
@@ -96,9 +96,9 @@ function notEmpty (value) { return !empty(value) }
function minus(a, b) { return a - b }
function min2(a, b) { return a < b ? a : b }
function lower (value) { if (value === null || value === undefined) { return null } return value.toLowerCase() }
-function lessOrEquals(a, b) { return a <= b }
-function less(a, b) { return a < b }
-function length (value) { return value.length }
+function lessOrEquals(a, b) { return a !== null && a !== undefined && b !== null && b !== undefined && a <= b }
+function less(a, b) { return a !== null && a !== undefined && b !== null && b !== undefined && a < b }
+function length (value) { return value === null || value === undefined ? null : value.length }
function jsonStringify (value, spacing) {
function convert(x, marked) {
if (!marked) { marked = new Set() }
@@ -135,8 +135,8 @@ function __x_in(val, arr) {
}
return false;
}
-function greaterOrEquals(a, b) { return a >= b }
-function greater(a, b) { return a > b }
+function greaterOrEquals(a, b) { return a !== null && a !== undefined && b !== null && b !== undefined && a >= b }
+function greater(a, b) { return a !== null && a !== undefined && b !== null && b !== undefined && a > b }
function generateUUIDv4 () { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { const r = (Math.random() * 16) | 0; const v = c === 'x' ? r : (r & 0x3) | 0x8; return v.toString(16) })}
function floor(a) { return Math.floor(a) }
function extract(part, val) {
diff --git a/common/hogvm/__tests__/__snapshots__/strings.hoge b/common/hogvm/__tests__/__snapshots__/strings.hoge
index 2143350e53df..1444bf640329 100644
--- a/common/hogvm/__tests__/__snapshots__/strings.hoge
+++ b/common/hogvm/__tests__/__snapshots__/strings.hoge
@@ -5,12 +5,12 @@
"splitByString", 2, 2, "print", 1, 35, 32, " ", 32, "hello world and more", 33, 1, 2, "splitByString", 3, 2, "print", 1,
35, 32, " ", 32, "hello world and more", 33, 2, 2, "splitByString", 3, 2, "print", 1, 35, 32, " ", 32,
"hello world and more", 33, 10, 2, "splitByString", 3, 2, "print", 1, 35, 32, "banana", 32, "N", 2, "like", 2, 2,
-"print", 1, 35, 32, "banana", 32, "n", 2, "like", 2, 2, "print", 1, 35, 32, "banana", 32, "naan", 2, "like", 2, 2,
-"print", 1, 35, 32, "banana", 32, "N", 2, "ilike", 2, 2, "print", 1, 35, 32, "banana", 32, "n", 2, "ilike", 2, 2,
-"print", 1, 35, 32, "banana", 32, "naan", 2, "ilike", 2, 2, "print", 1, 35, 32, "banana", 32, "N", 2, "notLike", 2, 2,
-"print", 1, 35, 32, "banana", 32, "NO", 2, "notILike", 2, 2, "print", 1, 35, 32, "abc", 32, "a", 2, "position", 2, 2,
-"print", 1, 35, 32, "abc", 32, "b", 2, "position", 2, 2, "print", 1, 35, 32, "abc", 32, "c", 2, "position", 2, 2,
-"print", 1, 35, 32, "abc", 32, "d", 2, "position", 2, 2, "print", 1, 35, 32, "AbC", 32, "a", 2,
-"positionCaseInsensitive", 2, 2, "print", 1, 35, 32, "AbC", 32, "b", 2, "positionCaseInsensitive", 2, 2, "print", 1, 35,
-32, "AbC", 32, "c", 2, "positionCaseInsensitive", 2, 2, "print", 1, 35, 32, "AbC", 32, "d", 2,
-"positionCaseInsensitive", 2, 2, "print", 1, 35]
+"print", 1, 35, 32, "b%x", 32, "baax", 17, 2, "print", 1, 35, 32, "b%x", 32, "b%x", 17, 2, "print", 1, 35, 32, "banana",
+32, "n", 2, "like", 2, 2, "print", 1, 35, 32, "banana", 32, "naan", 2, "like", 2, 2, "print", 1, 35, 32, "banana", 32,
+"N", 2, "ilike", 2, 2, "print", 1, 35, 32, "banana", 32, "n", 2, "ilike", 2, 2, "print", 1, 35, 32, "banana", 32,
+"naan", 2, "ilike", 2, 2, "print", 1, 35, 32, "banana", 32, "N", 2, "notLike", 2, 2, "print", 1, 35, 32, "banana", 32,
+"NO", 2, "notILike", 2, 2, "print", 1, 35, 32, "abc", 32, "a", 2, "position", 2, 2, "print", 1, 35, 32, "abc", 32, "b",
+2, "position", 2, 2, "print", 1, 35, 32, "abc", 32, "c", 2, "position", 2, 2, "print", 1, 35, 32, "abc", 32, "d", 2,
+"position", 2, 2, "print", 1, 35, 32, "AbC", 32, "a", 2, "positionCaseInsensitive", 2, 2, "print", 1, 35, 32, "AbC", 32,
+"b", 2, "positionCaseInsensitive", 2, 2, "print", 1, 35, 32, "AbC", 32, "c", 2, "positionCaseInsensitive", 2, 2,
+"print", 1, 35, 32, "AbC", 32, "d", 2, "positionCaseInsensitive", 2, 2, "print", 1, 35]
diff --git a/common/hogvm/__tests__/__snapshots__/strings.js b/common/hogvm/__tests__/__snapshots__/strings.js
index 05cc27caec58..28200e2e99cd 100644
--- a/common/hogvm/__tests__/__snapshots__/strings.js
+++ b/common/hogvm/__tests__/__snapshots__/strings.js
@@ -1,4 +1,7 @@
function trimRight (str, char) {
+ if (str === null || str === undefined) {
+ return null
+ }
if (char === null || char === undefined) {
char = ' '
}
@@ -12,6 +15,9 @@ function trimRight (str, char) {
return str.slice(0, end)
}
function trimLeft (str, char) {
+ if (str === null || str === undefined) {
+ return null
+ }
if (char === null || char === undefined) {
char = ' '
}
@@ -25,6 +31,9 @@ function trimLeft (str, char) {
return str.slice(start)
}
function trim (str, char) {
+ if (str === null || str === undefined) {
+ return null
+ }
if (char === null || char === undefined) {
char = ' '
}
@@ -44,7 +53,7 @@ function trim (str, char) {
}
return str.slice(start, end)
}
-function splitByString (separator, str, maxSplits) { if (maxSplits === undefined || maxSplits === null) { return str.split(separator) } return str.split(separator, maxSplits) }
+function splitByString (separator, str, maxSplits) { if (str === null || str === undefined) { return null } if (maxSplits === undefined || maxSplits === null) { return str.split(separator) } return str.split(separator, maxSplits) }
function print (...args) { console.log(...args.map(__printHogStringOutput)) }
function positionCaseInsensitive (str, elem) { if (typeof str === 'string') { return str.toLowerCase().indexOf(String(elem).toLowerCase()) + 1 } else { return 0 } }
function position (str, elem) { if (typeof str === 'string') { return str.indexOf(String(elem)) + 1 } else { return 0 } }
@@ -112,6 +121,8 @@ print(splitByString(" ", "hello world and more", 1));
print(splitByString(" ", "hello world and more", 2));
print(splitByString(" ", "hello world and more", 10));
print(like("banana", "N"));
+print(like("baax", "b%x"));
+print(like("b%x", "b%x"));
print(like("banana", "n"));
print(like("banana", "naan"));
print(ilike("banana", "N"));
diff --git a/common/hogvm/__tests__/__snapshots__/strings.stdout b/common/hogvm/__tests__/__snapshots__/strings.stdout
index 57808971dd3f..97e885c28798 100644
--- a/common/hogvm/__tests__/__snapshots__/strings.stdout
+++ b/common/hogvm/__tests__/__snapshots__/strings.stdout
@@ -10,6 +10,8 @@ xxxx hello world
['hello', 'world', 'and', 'more']
false
true
+true
+true
false
true
true
diff --git a/common/hogvm/__tests__/crypto.hog b/common/hogvm/__tests__/crypto.hog
index a3f49a24b673..be3324ea3909 100644
--- a/common/hogvm/__tests__/crypto.hog
+++ b/common/hogvm/__tests__/crypto.hog
@@ -1,7 +1,5 @@
let string := 'this is a secure string'
print('string:', string)
-print('md5Hex(string):', md5Hex(string))
-print('md5Hex(null):', md5Hex(null))
print('md5(string, \'hex\'):', md5(string, 'hex'))
print('md5(null, \'hex\'):', md5(null, 'hex'))
print('md5(string, \'binary\'):', md5(string, 'binary'))
@@ -10,8 +8,6 @@ print('md5(string, \'base64\'):', md5(string, 'base64'))
print('md5(null, \'base64\'):', md5(null, 'base64'))
print('md5(string, \'base64url\'):', md5(string, 'base64url'))
print('md5(null, \'base64url\'):', md5(null, 'base64url'))
-print('sha256Hex(string):', sha256Hex(string))
-print('sha256Hex(null):', sha256Hex(null))
print('sha256(string, \'hex\'):', sha256(string, 'hex'))
print('sha256(null, \'hex\'):', sha256(null, 'hex'))
print('sha256(string, \'binary\'):', sha256(string, 'binary'))
diff --git a/common/hogvm/__tests__/cryptoHex.hog b/common/hogvm/__tests__/cryptoHex.hog
new file mode 100644
index 000000000000..85b9f4bdad1b
--- /dev/null
+++ b/common/hogvm/__tests__/cryptoHex.hog
@@ -0,0 +1,6 @@
+let string := 'this is a secure string'
+print('string:', string)
+print('md5Hex(string):', md5Hex(string))
+print('md5Hex(null):', md5Hex(null))
+print('sha256Hex(string):', sha256Hex(string))
+print('sha256Hex(null):', sha256Hex(null))
diff --git a/common/hogvm/__tests__/nulls.hog b/common/hogvm/__tests__/nulls.hog
index fece4d8c1a4f..e0e9f740e8ae 100644
--- a/common/hogvm/__tests__/nulls.hog
+++ b/common/hogvm/__tests__/nulls.hog
@@ -12,3 +12,40 @@ print(null =~ 'u')
print(null =~ 'b')
print('uu' =~ null)
print('null' =~ null)
+
+print('-- string and array functions on null --')
+print(length(null))
+print(upper(null))
+print(reverse(null))
+print(replaceOne(null, 'a', 'b'))
+print(replaceAll(null, 'a', 'b'))
+print(trim(null))
+print(trimLeft(null))
+print(trimRight(null))
+print(keys(null))
+print(values(null))
+print(arrayExists(x -> x = 'a', null))
+print(arrayMap(x -> x, null))
+print(arrayFilter(x -> x = 'a', null))
+print(arrayCount(x -> x = 'a', null))
+print(arrayReduce((acc, x) -> acc + x, null, 0))
+print(splitByString(' ', null))
+print(arrayStringConcat(arrayPopFront(splitByString(' ', null)), ' '))
+print(0 == null)
+print(0 != null)
+print(0 not between 1 and 10)
+print(length(null) > 3)
+print(length(null) < 3)
+print(null < 3)
+print(null <= 0)
+print(null > 3)
+print(null >= 0)
+print(3 > null)
+print(null > null)
+print(not (length(null) > 3))
+print(length(null) = 0)
+print(less(null, 3))
+print(greater(3, null))
+print(lessOrEquals(null, null))
+print(greaterOrEquals(null, 0))
+print(less(1, 3))
diff --git a/common/hogvm/__tests__/strings.hog b/common/hogvm/__tests__/strings.hog
index e8d0eab7b8e9..0f17f0bffe03 100644
--- a/common/hogvm/__tests__/strings.hog
+++ b/common/hogvm/__tests__/strings.hog
@@ -9,6 +9,8 @@ print(splitByString(' ', 'hello world and more', 1))
print(splitByString(' ', 'hello world and more', 2))
print(splitByString(' ', 'hello world and more', 10))
print(like('banana', 'N'))
+print('baax' like 'b%x')
+print('b%x' like 'b%x')
print(like('banana', 'n'))
print(like('banana', 'naan'))
print(ilike('banana', 'N'))
diff --git a/common/hogvm/python/execute.py b/common/hogvm/python/execute.py
index 6a7b514b4d63..ae4cac83c0fe 100644
--- a/common/hogvm/python/execute.py
+++ b/common/hogvm/python/execute.py
@@ -54,6 +54,13 @@ def _compare_values(left: Any, right: Any, comparison: Callable[[Any, Any], bool
raise HogVMException(str(e)) from e
+def _ordered(left: Any, right: Any, comparison: Callable[[Any, Any], bool]) -> bool:
+ # SQL semantics: a null on either side of an ordering comparison is no match.
+ if left is None or right is None:
+ return False
+ return _compare_values(left, right, comparison)
+
+
def execute_bytecode(
input: list[Any] | dict,
globals: Optional[dict[str, Any]] = None,
@@ -286,16 +293,16 @@ def execute_bytecode(
push_stack(var1 != var2)
case Operation.GT:
var1, var2 = unify_comparison_types(pop_stack(), pop_stack())
- push_stack(_compare_values(var1, var2, operator.gt))
+ push_stack(_ordered(var1, var2, operator.gt))
case Operation.GT_EQ:
var1, var2 = unify_comparison_types(pop_stack(), pop_stack())
- push_stack(_compare_values(var1, var2, operator.ge))
+ push_stack(_ordered(var1, var2, operator.ge))
case Operation.LT:
var1, var2 = unify_comparison_types(pop_stack(), pop_stack())
- push_stack(_compare_values(var1, var2, operator.lt))
+ push_stack(_ordered(var1, var2, operator.lt))
case Operation.LT_EQ:
var1, var2 = unify_comparison_types(pop_stack(), pop_stack())
- push_stack(_compare_values(var1, var2, operator.le))
+ push_stack(_ordered(var1, var2, operator.le))
case Operation.LIKE:
push_stack(like(pop_stack(), pop_stack()))
case Operation.ILIKE:
diff --git a/common/hogvm/python/stl/__init__.py b/common/hogvm/python/stl/__init__.py
index 9c437ffedd77..ce573606c1dc 100644
--- a/common/hogvm/python/stl/__init__.py
+++ b/common/hogvm/python/stl/__init__.py
@@ -14,7 +14,6 @@ from ..objects import is_hog_callable, is_hog_closure, is_hog_error, new_hog_err
from ..utils import (
COST_PER_UNIT,
MAX_MEMORY,
- HogVMException,
HogVMMemoryExceededException,
_compile_regex,
_require_string,
@@ -126,7 +125,7 @@ def empty(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]],
def length(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float):
if args[0] is None:
- raise HogVMException("Can not call length on null")
+ return None
return len(args[0])
@@ -302,7 +301,9 @@ def tryDecodeURLComponent(
return None
-def trim(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float) -> str:
+def trim(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float) -> str | None:
+ if args[0] is None:
+ return None
char = str(args[1]) if len(args) > 1 and isinstance(args[1], str) else None
if len(args) > 1:
if char is None:
@@ -312,7 +313,9 @@ def trim(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], t
return args[0].strip(char)
-def trimLeft(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float) -> str:
+def trimLeft(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float) -> str | None:
+ if args[0] is None:
+ return None
char = str(args[1]) if len(args) > 1 and isinstance(args[1], str) else None
if len(args) > 1:
if char is None:
@@ -322,7 +325,9 @@ def trimLeft(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]
return args[0].lstrip(char)
-def trimRight(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float) -> str:
+def trimRight(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float) -> str | None:
+ if args[0] is None:
+ return None
char = str(args[1]) if len(args) > 1 and isinstance(args[1], str) else None
if len(args) > 1:
if char is None:
@@ -332,9 +337,11 @@ def trimRight(args: list[Any], team: Optional["Team"], stdout: Optional[list[str
return args[0].rstrip(char)
-def splitByString(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float) -> list:
+def splitByString(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float) -> list | None:
separator = args[0]
string = args[1]
+ if string is None:
+ return None
if len(args) > 2 and args[2] is not None:
parts = string.split(separator, args[2])
if len(parts) > args[2]:
@@ -650,19 +657,19 @@ def equals(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]],
def greater(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float) -> bool:
- return args[0] > args[1]
+ return args[0] is not None and args[1] is not None and args[0] > args[1]
def greaterOrEquals(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float) -> bool:
- return args[0] >= args[1]
+ return args[0] is not None and args[1] is not None and args[0] >= args[1]
def less(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float) -> bool:
- return args[0] < args[1]
+ return args[0] is not None and args[1] is not None and args[0] < args[1]
def lessOrEquals(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float) -> bool:
- return args[0] <= args[1]
+ return args[0] is not None and args[1] is not None and args[0] <= args[1]
def notEquals(args: list[Any], team: Optional["Team"], stdout: Optional[list[str]], timeout: float) -> bool:
@@ -1021,8 +1028,12 @@ STL: dict[str, STLFunction] = {
"lower": STLFunction(
fn=lambda args, team, stdout, timeout: args[0].lower() if args[0] is not None else None, minArgs=1, maxArgs=1
),
- "upper": STLFunction(fn=lambda args, team, stdout, timeout: args[0].upper(), minArgs=1, maxArgs=1),
- "reverse": STLFunction(fn=lambda args, team, stdout, timeout: args[0][::-1], minArgs=1, maxArgs=1),
+ "upper": STLFunction(
+ fn=lambda args, team, stdout, timeout: args[0].upper() if args[0] is not None else None, minArgs=1, maxArgs=1
+ ),
+ "reverse": STLFunction(
+ fn=lambda args, team, stdout, timeout: args[0][::-1] if args[0] is not None else None, minArgs=1, maxArgs=1
+ ),
"print": STLFunction(fn=print, minArgs=0, maxArgs=None),
"jsonParse": STLFunction(fn=jsonParse, minArgs=1, maxArgs=1),
"jsonStringify": STLFunction(fn=jsonStringify, minArgs=1, maxArgs=2),
@@ -1036,10 +1047,14 @@ STL: dict[str, STLFunction] = {
"decodeURLComponent": STLFunction(fn=decodeURLComponent, minArgs=1, maxArgs=1),
"tryDecodeURLComponent": STLFunction(fn=tryDecodeURLComponent, minArgs=1, maxArgs=1),
"replaceOne": STLFunction(
- fn=lambda args, team, stdout, timeout: args[0].replace(args[1], args[2], 1), minArgs=3, maxArgs=3
+ fn=lambda args, team, stdout, timeout: args[0].replace(args[1], args[2], 1) if args[0] is not None else None,
+ minArgs=3,
+ maxArgs=3,
),
"replaceAll": STLFunction(
- fn=lambda args, team, stdout, timeout: args[0].replace(args[1], args[2]), minArgs=3, maxArgs=3
+ fn=lambda args, team, stdout, timeout: args[0].replace(args[1], args[2]) if args[0] is not None else None,
+ minArgs=3,
+ maxArgs=3,
),
"position": STLFunction(
fn=lambda args, team, stdout, timeout: (
diff --git a/common/hogvm/python/test/test_execute.py b/common/hogvm/python/test/test_execute.py
index 4376a69b723f..2ad1d01f771b 100644
--- a/common/hogvm/python/test/test_execute.py
+++ b/common/hogvm/python/test/test_execute.py
@@ -120,8 +120,8 @@ class TestBytecodeExecute:
assert self._run("1 != null") is True
def test_ordering_comparison_type_error_raises_hogvm_exception(self):
- with pytest.raises(HogVMException, match="'<=' not supported between instances of 'NoneType' and 'float'"):
- self._run("properties.missing <= 1.0")
+ with pytest.raises(HogVMException, match="'<=' not supported between instances of 'list' and 'float'"):
+ self._run("[1] <= 1.0")
@parameterized.expand(
[
@@ -839,9 +839,32 @@ class TestBytecodeExecute:
assert self._run_program("if (lower('Tdd4gh') == 'tdd4gh') return upper('test');") == "TEST"
assert self._run_program("return reverse('spinner');") == "rennips"
- def test_bytecode_length_null_raises_hogvm_exception(self):
- with pytest.raises(HogVMException, match="Can not call length on null"):
- self._run_program("return length(null);")
+ def test_bytecode_string_functions_return_null_for_null(self):
+ for program in (
+ "return length(null);",
+ "return upper(null);",
+ "return reverse(null);",
+ "return replaceOne(null, 'a', 'b');",
+ "return replaceAll(null, 'a', 'b');",
+ "return trim(null);",
+ "return splitByString(' ', null);",
+ ):
+ assert self._run_program(program) is None, program
+
+ def test_bytecode_ordering_with_a_null_operand_is_false(self):
+ # A filter comparing a missing value must not match, and must not fail either.
+ for program in (
+ "return length(null) > 3;",
+ "return length(null) < 3;",
+ "return null >= 0;",
+ "return 1 > null;",
+ "return null > true;",
+ "return null < null;",
+ ):
+ assert self._run_program(program) is False, program
+ # Equality does not coerce: a zero is not a null.
+ assert self._run_program("return 0 == null;") is False
+ assert self._run_program("return 0 != null;") is True
@parameterized.expand(
[
diff --git a/common/hogvm/python/utils.py b/common/hogvm/python/utils.py
index 99e2f5aea0f1..cdfc33c5306a 100644
--- a/common/hogvm/python/utils.py
+++ b/common/hogvm/python/utils.py
@@ -123,7 +123,8 @@ def regex_extract(string: Any, pattern: Any) -> str:
def like(string: Any, pattern: Any, case_insensitive: bool = False) -> bool:
_validate_regex_pattern(pattern)
- pattern = re2.escape(pattern).replace("%", ".*").replace("_", ".")
+ # re2.escape backslash-escapes % (and not _), so undo that before the wildcards turn into regex.
+ pattern = re2.escape(pattern).replace("\\%", "%").replace("%", ".*").replace("_", ".")
re_pattern = re2.compile(pattern, options=_CASE_INSENSITIVE_OPTS) if case_insensitive else re2.compile(pattern)
return re_pattern.search(string) is not None
diff --git a/common/hogvm/test.sh b/common/hogvm/test.sh
index 0120b8585b09..afd04b7f6232 100755
--- a/common/hogvm/test.sh
+++ b/common/hogvm/test.sh
@@ -1,8 +1,9 @@
#!/bin/bash
set -e
-# List of test files to skip the compiledjs tests
-SKIP_COMPILEDJS_FILES=("")
+# Files whose compiled-JavaScript leg is skipped: the encoded and HMAC hash functions are stubs there.
+# The hex functions it does implement are covered by cryptoHex.hog.
+SKIP_COMPILEDJS_FILES=("crypto.hog")
# Files on which we only want to run Node.js tests
ONLY_NODEJS_FILES=("sql.hog")
diff --git a/common/hogvm/typescript/src/__tests__/execute.test.ts b/common/hogvm/typescript/src/__tests__/execute.test.ts
index 9d7ad19c8db9..2d3e13ee4efe 100644
--- a/common/hogvm/typescript/src/__tests__/execute.test.ts
+++ b/common/hogvm/typescript/src/__tests__/execute.test.ts
@@ -231,43 +231,21 @@ describe('hogvm execute', () => {
).toEqual(expected)
})
- test('null coercion in ordering comparisons - preserved behavior', () => {
- // This test documents the current typescript hogvm behavior where null is coerced to 0 in ordering comparisons.
- // HogVM in python/rust does not share this behavior.
- // It is preserved for backward compatibility - users depend on it.
- // See: https://github.com/PostHog/posthog/pull/45328
+ test('an ordering comparison with a null operand is false', () => {
+ // SQL semantics, shared with the Python and Rust VMs. JavaScript would read null as 0, which
+ // made `missing <= 18` match every person without the property.
const options = {}
-
- // null is coerced to 0 in JavaScript comparisons
- // 0 <= null is true (null coerces to 0, 0 <= 0)
- expect(execSync(['_h', op.NULL, op.INTEGER, 0, op.LT_EQ], options)).toBe(true)
- // 0 >= null is true (null coerces to 0, 0 >= 0)
- expect(execSync(['_h', op.NULL, op.INTEGER, 0, op.GT_EQ], options)).toBe(true)
- // 0 < null is false (null coerces to 0, 0 < 0 is false)
- expect(execSync(['_h', op.NULL, op.INTEGER, 0, op.LT], options)).toBe(false)
- // 0 > null is false (null coerces to 0, 0 > 0 is false)
- expect(execSync(['_h', op.NULL, op.INTEGER, 0, op.GT], options)).toBe(false)
-
- // 1 < null is false (null coerces to 0, 1 < 0 is false)
- expect(execSync(['_h', op.NULL, op.INTEGER, 1, op.LT], options)).toBe(false)
- // 1 <= null is false (null coerces to 0, 1 <= 0 is false)
- expect(execSync(['_h', op.NULL, op.INTEGER, 1, op.LT_EQ], options)).toBe(false)
- // 1 > null is true (null coerces to 0, 1 > 0 is true)
- expect(execSync(['_h', op.NULL, op.INTEGER, 1, op.GT], options)).toBe(true)
- // 1 >= null is true (null coerces to 0, 1 >= 0 is true)
- expect(execSync(['_h', op.NULL, op.INTEGER, 1, op.GT_EQ], options)).toBe(true)
-
- // -1 < null is true (null coerces to 0, -1 < 0 is true)
- expect(execSync(['_h', op.NULL, op.INTEGER, -1, op.LT], options)).toBe(true)
- // -1 > null is false (null coerces to 0, -1 > 0 is false)
- expect(execSync(['_h', op.NULL, op.INTEGER, -1, op.GT], options)).toBe(false)
-
- // Reverse order: null < 0 is false (null coerces to 0, 0 < 0 is false)
- expect(execSync(['_h', op.INTEGER, 0, op.NULL, op.LT], options)).toBe(false)
- // Reverse order: null < 1 is true (null coerces to 0, 0 < 1 is true)
- expect(execSync(['_h', op.INTEGER, 1, op.NULL, op.LT], options)).toBe(true)
- // Reverse order: null > 1 is false (null coerces to 0, 0 > 1 is false)
- expect(execSync(['_h', op.INTEGER, 1, op.NULL, op.GT], options)).toBe(false)
+ for (const operation of [op.LT, op.LT_EQ, op.GT, op.GT_EQ]) {
+ for (const value of [-1, 0, 1]) {
+ expect(execSync(['_h', op.NULL, op.INTEGER, value, operation], options)).toBe(false)
+ expect(execSync(['_h', op.INTEGER, value, op.NULL, operation], options)).toBe(false)
+ }
+ expect(execSync(['_h', op.NULL, op.NULL, operation], options)).toBe(false)
+ }
+ // Equality keeps its meaning.
+ expect(execSync(['_h', op.NULL, op.NULL, op.EQ], options)).toBe(true)
+ expect(execSync(['_h', op.NULL, op.INTEGER, 0, op.EQ], options)).toBe(false)
+ expect(execSync(['_h', op.NULL, op.INTEGER, 0, op.NOT_EQ], options)).toBe(true)
})
test('async limits', async () => {
diff --git a/common/hogvm/typescript/src/execute.ts b/common/hogvm/typescript/src/execute.ts
index 540e9fdeea52..051a20302a7f 100644
--- a/common/hogvm/typescript/src/execute.ts
+++ b/common/hogvm/typescript/src/execute.ts
@@ -32,7 +32,17 @@ import {
unifyComparisonTypes,
} from './utils'
+const ORDERING_OPERATIONS = new Set([Operation.GT, Operation.GT_EQ, Operation.LT, Operation.LT_EQ])
+
function compareValues(left: any, right: any, operation: Operation): boolean {
+ // SQL semantics: a null on either side of an ordering comparison is no match. Without this the
+ // native operator reads null as 0, so `length(missing) < 3` would match.
+ if (
+ ORDERING_OPERATIONS.has(operation) &&
+ (left === null || left === undefined || right === null || right === undefined)
+ ) {
+ return false
+ }
;[left, right] = unifyComparisonTypes(left, right)
if (Array.isArray(left) && Array.isArray(right) && left.every(Number.isFinite) && right.every(Number.isFinite)) {
@@ -855,7 +865,9 @@ export function exec(input: any[] | VMState | Bytecodes, options?: ExecOptions):
} else if (Object.hasOwn(STL, name)) {
const stlFn = STL[name]
if (stlFn.minArgs !== undefined && temp < stlFn.minArgs) {
- throw new HogVMException(`Function ${name} requires at least ${stlFn.minArgs} arguments`)
+ throw new HogVMException(
+ `Function ${name} requires at least ${stlFn.minArgs} arguments`
+ )
}
if (stlFn.maxArgs !== undefined && temp > stlFn.maxArgs) {
throw new HogVMException(`Function ${name} requires at most ${stlFn.maxArgs} arguments`)
diff --git a/common/hogvm/typescript/src/stl/stl.ts b/common/hogvm/typescript/src/stl/stl.ts
index 27933fba5efd..bbf31b67d30e 100644
--- a/common/hogvm/typescript/src/stl/stl.ts
+++ b/common/hogvm/typescript/src/stl/stl.ts
@@ -208,20 +208,25 @@ function equalsFn([a, b]: any[]): boolean {
return a === b
}
+// A null on either side is no match, the same as the comparison operators.
+function isNullish(value: any): boolean {
+ return value === null || value === undefined
+}
+
function greaterFn([a, b]: any[]): boolean {
- return a > b
+ return !isNullish(a) && !isNullish(b) && a > b
}
function greaterOrEqualsFn([a, b]: any[]): boolean {
- return a >= b
+ return !isNullish(a) && !isNullish(b) && a >= b
}
function lessFn([a, b]: any[]): boolean {
- return a < b
+ return !isNullish(a) && !isNullish(b) && a < b
}
function lessOrEqualsFn([a, b]: any[]): boolean {
- return a <= b
+ return !isNullish(a) && !isNullish(b) && a <= b
}
function notEqualsFn([a, b]: any[]): boolean {
@@ -629,6 +634,9 @@ export const STL: Record<string, STLFunction> = {
},
length: {
fn: (args) => {
+ if (args[0] === null || args[0] === undefined) {
+ return null
+ }
return args[0].length
},
description: 'Returns the length of a string or array',
@@ -691,6 +699,9 @@ export const STL: Record<string, STLFunction> = {
},
upper: {
fn: (args) => {
+ if (args[0] === null || args[0] === undefined) {
+ return null
+ }
return args[0].toUpperCase()
},
description: 'Converts a string to uppercase',
@@ -700,6 +711,9 @@ export const STL: Record<string, STLFunction> = {
},
reverse: {
fn: (args) => {
+ if (args[0] === null || args[0] === undefined) {
+ return null
+ }
return args[0].split('').reverse().join('')
},
description: 'Reverses a string',
@@ -970,6 +984,9 @@ export const STL: Record<string, STLFunction> = {
},
replaceOne: {
fn: (args) => {
+ if (args[0] === null || args[0] === undefined) {
+ return null
+ }
return args[0].replace(args[1], args[2])
},
description: 'Replaces first occurrence of a substring',
@@ -979,6 +996,9 @@ export const STL: Record<string, STLFunction> = {
},
replaceAll: {
fn: (args) => {
+ if (args[0] === null || args[0] === undefined) {
+ return null
+ }
return args[0].replaceAll(args[1], args[2])
},
description: 'Replaces all occurrences of a substring',
@@ -1012,6 +1032,9 @@ export const STL: Record<string, STLFunction> = {
},
trim: {
fn: ([str, char]) => {
+ if (str === null || str === undefined) {
+ return null
+ }
if (char === null || char === undefined) {
char = ' '
}
@@ -1038,6 +1061,9 @@ export const STL: Record<string, STLFunction> = {
},
trimLeft: {
fn: ([str, char]) => {
+ if (str === null || str === undefined) {
+ return null
+ }
if (char === null || char === undefined) {
char = ' '
}
@@ -1057,6 +1083,9 @@ export const STL: Record<string, STLFunction> = {
},
trimRight: {
fn: ([str, char]) => {
+ if (str === null || str === undefined) {
+ return null
+ }
if (char === null || char === undefined) {
char = ' '
}
@@ -1076,6 +1105,9 @@ export const STL: Record<string, STLFunction> = {
},
splitByString: {
fn: ([separator, str, maxSplits = undefined]) => {
+ if (str === null || str === undefined) {
+ return null
+ }
if (maxSplits === undefined || maxSplits === null) {
return str.split(separator)
}
@@ -1185,7 +1217,7 @@ export const STL: Record<string, STLFunction> = {
},
keys: {
fn: ([obj]) => {
- if (typeof obj === 'object') {
+ if (obj !== null && typeof obj === 'object') {
if (Array.isArray(obj)) {
return Array.from(obj.keys())
} else if (obj instanceof Map) {
@@ -1202,7 +1234,7 @@ export const STL: Record<string, STLFunction> = {
},
values: {
fn: ([obj]) => {
- if (typeof obj === 'object') {
+ if (obj !== null && typeof obj === 'object') {
if (Array.isArray(obj)) {
return [...obj]
} else if (obj instanceof Map) {
diff --git a/posthog/hogql/compiler/javascript.py b/posthog/hogql/compiler/javascript.py
index 3980984370f6..771e0f31f39e 100644
--- a/posthog/hogql/compiler/javascript.py
+++ b/posthog/hogql/compiler/javascript.py
@@ -12,6 +12,13 @@ from posthog.hogql.parser import parse_expr, parse_program
from posthog.hogql.visitor import Visitor
_JS_GET_GLOBAL = "__getGlobal"
+# Emitted for the ordering comparisons, so a Hog program must not be able to declare these names.
+_JS_ORDERING_HELPERS = {
+ ast.CompareOperationOp.Gt: "__gt",
+ ast.CompareOperationOp.GtEq: "__gte",
+ ast.CompareOperationOp.Lt: "__lt",
+ ast.CompareOperationOp.LtEq: "__lte",
+}
_JS_KEYWORDS = {
"await",
"break",
@@ -63,6 +70,7 @@ _JS_KEYWORDS = {
"eval",
"Error",
_JS_GET_GLOBAL, # don't let this get overridden
+ *_JS_ORDERING_HELPERS.values(),
}
@@ -195,6 +203,9 @@ class JavaScriptCompiler(Visitor):
ast.CompareOperationOp.LtEq: "<=",
}
+ if op in _JS_ORDERING_HELPERS:
+ self.stl_functions.add(_JS_ORDERING_HELPERS[op])
+ return f"{_JS_ORDERING_HELPERS[op]}({left_code}, {right_code})"
if op in op_map:
return f"({left_code} {op_map[op]} {right_code})"
elif op == ast.CompareOperationOp.In:
diff --git a/posthog/hogql/compiler/javascript_stl.py b/posthog/hogql/compiler/javascript_stl.py
index 604b90eb845d..6017b5c22ebe 100644
--- a/posthog/hogql/compiler/javascript_stl.py
+++ b/posthog/hogql/compiler/javascript_stl.py
@@ -9,6 +9,22 @@ STL_FUNCTIONS: dict[str, list[str | list[str]]] = {
"function match (str, pattern) { return !str || !pattern ? false : new RegExp(pattern).test(str) }",
[],
],
+ "__gt": [
+ "function __gt (a, b) { return a === null || a === undefined || b === null || b === undefined ? false : a > b }",
+ [],
+ ],
+ "__gte": [
+ "function __gte (a, b) { return a === null || a === undefined || b === null || b === undefined ? false : a >= b }",
+ [],
+ ],
+ "__lt": [
+ "function __lt (a, b) { return a === null || a === undefined || b === null || b === undefined ? false : a < b }",
+ [],
+ ],
+ "__lte": [
+ "function __lte (a, b) { return a === null || a === undefined || b === null || b === undefined ? false : a <= b }",
+ [],
+ ],
"__imatch": [
"function __imatch (str, pattern) { return !str || !pattern ? false : new RegExp(pattern, 'i').test(str) }",
[],
@@ -64,7 +80,7 @@ STL_FUNCTIONS: dict[str, list[str | list[str]]] = {
[],
],
"length": [
- "function length (value) { return value.length }",
+ "function length (value) { return value === null || value === undefined ? null : value.length }",
[],
],
"empty": [
@@ -89,11 +105,11 @@ STL_FUNCTIONS: dict[str, list[str | list[str]]] = {
[],
],
"upper": [
- "function upper (value) { return value.toUpperCase() }",
+ "function upper (value) { return value === null || value === undefined ? null : value.toUpperCase() }",
[],
],
"reverse": [
- "function reverse (value) { return value.split('').reverse().join('') }",
+ "function reverse (value) { return value === null || value === undefined ? null : value.split('').reverse().join('') }",
[],
],
"print": [
@@ -231,11 +247,11 @@ STL_FUNCTIONS: dict[str, list[str | list[str]]] = {
[],
],
"replaceOne": [
- "function replaceOne (str, searchValue, replaceValue) { return str.replace(searchValue, replaceValue) }",
+ "function replaceOne (str, searchValue, replaceValue) { return str === null || str === undefined ? null : str.replace(searchValue, replaceValue) }",
[],
],
"replaceAll": [
- "function replaceAll (str, searchValue, replaceValue) { return str.replaceAll(searchValue, replaceValue) }",
+ "function replaceAll (str, searchValue, replaceValue) { return str === null || str === undefined ? null : str.replaceAll(searchValue, replaceValue) }",
[],
],
"position": [
@@ -248,6 +264,9 @@ STL_FUNCTIONS: dict[str, list[str | list[str]]] = {
],
"trim": [
"""function trim (str, char) {
+ if (str === null || str === undefined) {
+ return null
+ }
if (char === null || char === undefined) {
char = ' '
}
@@ -271,6 +290,9 @@ STL_FUNCTIONS: dict[str, list[str | list[str]]] = {
],
"trimLeft": [
"""function trimLeft (str, char) {
+ if (str === null || str === undefined) {
+ return null
+ }
if (char === null || char === undefined) {
char = ' '
}
@@ -287,6 +309,9 @@ STL_FUNCTIONS: dict[str, list[str | list[str]]] = {
],
"trimRight": [
"""function trimRight (str, char) {
+ if (str === null || str === undefined) {
+ return null
+ }
if (char === null || char === undefined) {
char = ' '
}
@@ -302,7 +327,7 @@ STL_FUNCTIONS: dict[str, list[str | list[str]]] = {
[],
],
"splitByString": [
- "function splitByString (separator, str, maxSplits) { if (maxSplits === undefined || maxSplits === null) { return str.split(separator) } return str.split(separator, maxSplits) }",
+ "function splitByString (separator, str, maxSplits) { if (str === null || str === undefined) { return null } if (maxSplits === undefined || maxSplits === null) { return str.split(separator) } return str.split(separator, maxSplits) }",
[],
],
"generateUUIDv4": [
@@ -476,23 +501,23 @@ function isIPAddressInRange(address, prefix) {
[],
],
"arrayCount": [
- "function arrayCount (func, arr) { let count = 0; for (let i = 0; i < arr.length; i++) { if (func(arr[i])) { count = count + 1 } } return count }",
+ "function arrayCount (func, arr) { let count = 0; for (let i = 0; i < (arr ?? []).length; i++) { if (func(arr[i])) { count = count + 1 } } return count }",
[],
],
"arrayExists": [
- """function arrayExists (func, arr) { for (let i = 0; i < arr.length; i++) { if (func(arr[i])) { return true } } return false }""",
+ """function arrayExists (func, arr) { for (let i = 0; i < (arr ?? []).length; i++) { if (func(arr[i])) { return true } } return false }""",
[],
],
"arrayFilter": [
- """function arrayFilter (func, arr) { let result = []; for (let i = 0; i < arr.length; i++) { if (func(arr[i])) { result = arrayPushBack(result, arr[i]) } } return result}""",
+ """function arrayFilter (func, arr) { let result = []; for (let i = 0; i < (arr ?? []).length; i++) { if (func(arr[i])) { result = arrayPushBack(result, arr[i]) } } return result}""",
["arrayPushBack"],
],
"arrayMap": [
- """function arrayMap (func, arr) { let result = []; for (let i = 0; i < arr.length; i++) { result = arrayPushBack(result, func(arr[i])) } return result }""",
+ """function arrayMap (func, arr) { let result = []; for (let i = 0; i < (arr ?? []).length; i++) { result = arrayPushBack(result, func(arr[i])) } return result }""",
["arrayPushBack"],
],
"arrayReduce": [
- """function arrayReduce (func, arr, initial) { let result = initial; for (let i = 0; i < arr.length; i++) { result = func(result, arr[i]) } return result }""",
+ """function arrayReduce (func, arr, initial) { let result = initial; for (let i = 0; i < (arr ?? []).length; i++) { result = func(result, arr[i]) } return result }""",
[],
],
"has": [
@@ -1251,11 +1276,11 @@ function __setProperty(objectOrArray, key, value) {
[],
],
"greater": [
- "function greater(a, b) { return a > b }",
+ "function greater(a, b) { return a !== null && a !== undefined && b !== null && b !== undefined && a > b }",
[],
],
"greaterOrEquals": [
- "function greaterOrEquals(a, b) { return a >= b }",
+ "function greaterOrEquals(a, b) { return a !== null && a !== undefined && b !== null && b !== undefined && a >= b }",
[],
],
"if": [
@@ -1272,11 +1297,11 @@ function __setProperty(objectOrArray, key, value) {
[],
],
"less": [
- "function less(a, b) { return a < b }",
+ "function less(a, b) { return a !== null && a !== undefined && b !== null && b !== undefined && a < b }",
[],
],
"lessOrEquals": [
- "function lessOrEquals(a, b) { return a <= b }",
+ "function lessOrEquals(a, b) { return a !== null && a !== undefined && b !== null && b !== undefined && a <= b }",
[],
],
"min2": [
diff --git a/posthog/hogql/compiler/test/test_javascript.py b/posthog/hogql/compiler/test/test_javascript.py
index 73d8a03514ba..dedd5a0b06d4 100644
--- a/posthog/hogql/compiler/test/test_javascript.py
+++ b/posthog/hogql/compiler/test/test_javascript.py
@@ -13,6 +13,11 @@ class TestSanitizeIdentifier(BaseTest):
def test_keywords(self):
self.assertEqual(_sanitize_identifier("await"), "__x_await")
self.assertEqual(_sanitize_identifier("class"), "__x_class")
+ # The compiler emits these for the ordering comparisons, so a program must not declare them.
+ self.assertEqual(_sanitize_identifier("__lt"), "__x___lt")
+ self.assertEqual(_sanitize_identifier("__lte"), "__x___lte")
+ self.assertEqual(_sanitize_identifier("__gt"), "__x___gt")
+ self.assertEqual(_sanitize_identifier("__gte"), "__x___gte")
def test_internal_conflicts(self):
self.assertEqual(_sanitize_identifier("__x_internal"), "__x___x_internal")
@@ -31,7 +36,7 @@ class TestJavaScript(BaseTest):
self.assertEqual(to_js_expr("1 and 2"), "!!(1 && 2)")
self.assertEqual(to_js_expr("1 or 2"), "!!(1 || 2)")
self.assertEqual(to_js_expr("not true"), "(!true)")
- self.assertEqual(to_js_expr("1 < 2"), "(1 < 2)")
+ self.assertEqual(to_js_expr("1 < 2"), "__lt(1, 2)")
self.assertEqual(to_js_expr("properties.bla"), '__getProperty(__getGlobal("properties"), "bla", true)')
def test_javascript_string_functions(self):
@@ -49,10 +54,10 @@ class TestJavaScript(BaseTest):
def test_comparison_operations(self):
self.assertEqual(to_js_expr("3 = 4"), "(3 == 4)")
self.assertEqual(to_js_expr("3 != 4"), "(3 != 4)")
- self.assertEqual(to_js_expr("3 < 4"), "(3 < 4)")
- self.assertEqual(to_js_expr("3 <= 4"), "(3 <= 4)")
- self.assertEqual(to_js_expr("3 > 4"), "(3 > 4)")
- self.assertEqual(to_js_expr("3 >= 4"), "(3 >= 4)")
+ self.assertEqual(to_js_expr("3 < 4"), "__lt(3, 4)")
+ self.assertEqual(to_js_expr("3 <= 4"), "__lte(3, 4)")
+ self.assertEqual(to_js_expr("3 > 4"), "__gt(3, 4)")
+ self.assertEqual(to_js_expr("3 >= 4"), "__gte(3, 4)")
def test_javascript_create_query_error(self):
with self.assertRaises(QueryError) as e:
@@ -79,8 +84,10 @@ class TestJavaScript(BaseTest):
def test_if_else(self):
code = to_js_program("if (1 < 2) { return true } else { return false }")
- expected_code = "if ((1 < 2)) {\n return true;\n} else {\n return false;\n}"
- self.assertEqual(code.strip(), expected_code.strip())
+ expected_code = "if (__lt(1, 2)) {\n return true;\n} else {\n return false;\n}"
+ self.assertTrue(code.strip().endswith(expected_code), code)
+ # A null on either side of an ordering comparison is false, so the helper is part of the program.
+ self.assertIn("function __lt (a, b)", code)
def test_declare_local(self):
compiler = JavaScriptCompiler()
@@ -166,14 +173,15 @@ class TestJavaScript(BaseTest):
return fibonacci(6);
""")
expected_js = """function fibonacci(number) {
- if ((number < 2)) {
+ if (__lt(number, 2)) {
return number;
} else {
return (fibonacci((number - 1)) + fibonacci((number - 2)));
}
}
return fibonacci(6);"""
- self.assertEqual(js_code.strip(), expected_js.strip())
+ self.assertTrue(js_code.strip().endswith(expected_js.strip()), js_code)
+ self.assertIn("function __lt (a, b)", js_code)
def test_javascript_hogqlx(self):
code = to_js_expr("<Sparkline data={[1,2,3]} />")
diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.py
index 186e69a6bd59..5c0b744e7ba1 100644
--- a/posthog/temporal/ai_observability/test_run_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_evaluation.py
@@ -2326,41 +2326,21 @@ class TestExecuteHogEvalActivity:
assert "Global variable not found" in result["reasoning"]
@pytest.mark.asyncio
- async def test_hog_eval_length_null_returns_skipped(self):
- from posthog.cdp.validation import compile_hog
-
- bytecode = compile_hog("return length(null) > 0", "destination")
- evaluation = {
- "id": "eval-id",
- "name": "Hog Eval",
- "evaluation_type": "hog",
- "evaluation_config": {"source": "return length(null) > 0", "bytecode": bytecode},
- "output_type": "boolean",
- "output_config": {},
- "team_id": 1,
- }
-
- result = await execute_hog_eval_activity(evaluation, create_mock_event_data(1))
-
- assert result["skipped"] is True
- assert result["skip_reason"] == "hog_error"
- assert result["terminal_user_error"] is True
- assert result["status_reason"] == "hog_error"
- assert result["verdict"] is False
- assert "Runtime error: Can not call length on null" in result["reasoning"]
- assert "TypeError" not in result["reasoning"]
- assert "NoneType" not in result["reasoning"]
-
- @pytest.mark.asyncio
- async def test_hog_eval_comparison_type_error_returns_skipped(self):
+ @pytest.mark.parametrize(
+ "source",
+ ["return length(null) > 0", "return properties.missing <= 1.0"],
+ ids=["length-of-null", "ordering-against-null"],
+ )
+ async def test_hog_eval_null_comparisons_evaluate_to_false(self, source):
+ # A missing value is no match, not a runtime error, so the eval completes with a verdict.
from posthog.cdp.validation import compile_hog
- bytecode = compile_hog("return properties.missing <= 1.0", "destination")
+ bytecode = compile_hog(source, "destination")
evaluation = {
"id": "eval-id",
"name": "Hog Eval",
"evaluation_type": "hog",
- "evaluation_config": {"source": "return properties.missing <= 1.0", "bytecode": bytecode},
+ "evaluation_config": {"source": source, "bytecode": bytecode},
"output_type": "boolean",
"output_config": {},
"team_id": 1,
@@ -2368,13 +2348,9 @@ class TestExecuteHogEvalActivity:
result = await execute_hog_eval_activity(evaluation, create_mock_event_data(1))
- assert result["skipped"] is True
- assert result["skip_reason"] == "hog_error"
- assert result["terminal_user_error"] is True
- assert result["status_reason"] == "hog_error"
assert result["verdict"] is False
- assert "Runtime error: '<=' not supported between instances of 'NoneType' and 'float'" in result["reasoning"]
- assert "Unexpected error during evaluation" not in result["reasoning"]
+ assert not result.get("skipped")
+ assert "Runtime error" not in (result.get("reasoning") or "")
@pytest.mark.asyncio
@pytest.mark.parametrize(
diff --git a/rust/common/hogvm/src/stl.rs b/rust/common/hogvm/src/stl.rs
index 7eb1657241df..7ba2ec35372a 100644
--- a/rust/common/hogvm/src/stl.rs
+++ b/rust/common/hogvm/src/stl.rs
@@ -116,6 +116,9 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
assert_argc(&args, 1, "values")?;
let arg = args[0].deref(&vm.heap)?;
match arg {
+ // A null array reads as empty, so the bytecode array helpers built on values()
+ // see no elements instead of failing the whole program.
+ HogLiteral::Null => Ok(HogLiteral::Array(vec![]).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())
@@ -141,6 +144,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
assert_argc(&args, 1, "length")?;
let arg = args[0].deref(&vm.heap)?;
match arg {
+ HogLiteral::Null => Ok(HogLiteral::Null.into()),
HogLiteral::Array(arr) | HogLiteral::Tuple(arr) => {
Ok(HogLiteral::Number(arr.len().into()).into())
}
@@ -160,14 +164,12 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
let array = args[0].deref(&vm.heap)?;
let value = args[1].clone();
match array {
- HogLiteral::Array(arr) => {
+ HogLiteral::Array(arr) | HogLiteral::Tuple(arr) => {
let mut arr = arr.clone();
arr.push(value);
Ok(HogLiteral::Array(arr).into())
}
- _ => Err(VmError::NativeCallFailed(
- "arrayPushBack() only supports arrays".to_string(),
- )),
+ _ => Ok(HogLiteral::Array(vec![value]).into()),
}
}),
),
@@ -178,14 +180,12 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
let array = args[0].deref(&vm.heap)?;
let value = args[1].clone();
match array {
- HogLiteral::Array(arr) => {
+ HogLiteral::Array(arr) | HogLiteral::Tuple(arr) => {
let mut arr = arr.clone();
arr.insert(0, value);
Ok(HogLiteral::Array(arr).into())
}
- _ => Err(VmError::NativeCallFailed(
- "arrayPushFront() only supports arrays".to_string(),
- )),
+ _ => Ok(HogLiteral::Array(vec![value]).into()),
}
}),
),
@@ -195,14 +195,13 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
assert_argc(&args, 1, "arrayPopBack")?;
let array = args[0].deref(&vm.heap)?;
match array {
- HogLiteral::Array(arr) => {
+ HogLiteral::Array(arr) | HogLiteral::Tuple(arr) => {
let mut arr = arr.clone();
arr.pop();
Ok(HogLiteral::Array(arr).into())
}
- _ => Err(VmError::NativeCallFailed(
- "arrayPopBack() only supports arrays".to_string(),
- )),
+ // A non-array reads as empty, matching the Node VM.
+ _ => Ok(HogLiteral::Array(vec![]).into()),
}
}),
),
@@ -212,16 +211,15 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
assert_argc(&args, 1, "arrayPopFront")?;
let array = args[0].deref(&vm.heap)?;
match array {
- HogLiteral::Array(arr) => {
+ HogLiteral::Array(arr) | HogLiteral::Tuple(arr) => {
let mut arr = arr.clone();
if !arr.is_empty() {
arr.remove(0);
}
Ok(HogLiteral::Array(arr).into())
}
- _ => Err(VmError::NativeCallFailed(
- "arrayPopFront() only supports arrays".to_string(),
- )),
+ // A non-array reads as empty, matching the Node VM.
+ _ => Ok(HogLiteral::Array(vec![]).into()),
}
}),
),
@@ -231,13 +229,12 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
assert_argc(&args, 1, "arraySort")?;
let array = args[0].deref(&vm.heap)?;
match array {
- HogLiteral::Array(arr) => {
+ HogLiteral::Array(arr) | HogLiteral::Tuple(arr) => {
let nums = collect_sorted_nums(&vm.heap, arr, "arraySort")?;
Ok(HogLiteral::Array(nums.into_iter().map(|n| n.into()).collect()).into())
}
- _ => Err(VmError::NativeCallFailed(
- "arraySort() only supports arrays".to_string(),
- )),
+ // A non-array reads as empty, matching the Node VM.
+ _ => Ok(HogLiteral::Array(vec![]).into()),
}
}),
),
@@ -247,14 +244,13 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
assert_argc(&args, 1, "arrayReverse")?;
let array = args[0].deref(&vm.heap)?;
match array {
- HogLiteral::Array(arr) => {
+ HogLiteral::Array(arr) | HogLiteral::Tuple(arr) => {
let mut arr = arr.clone();
arr.reverse();
Ok(HogLiteral::Array(arr).into())
}
- _ => Err(VmError::NativeCallFailed(
- "arrayReverse() only supports arrays".to_string(),
- )),
+ // A non-array reads as empty, matching the Node VM.
+ _ => Ok(HogLiteral::Array(vec![]).into()),
}
}),
),
@@ -264,14 +260,13 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
assert_argc(&args, 1, "arrayReverseSort")?;
let array = args[0].deref(&vm.heap)?;
match array {
- HogLiteral::Array(arr) => {
+ HogLiteral::Array(arr) | HogLiteral::Tuple(arr) => {
let mut nums = collect_sorted_nums(&vm.heap, arr, "arrayReverseSort")?;
nums.reverse();
Ok(HogLiteral::Array(nums.into_iter().map(|n| n.into()).collect()).into())
}
- _ => Err(VmError::NativeCallFailed(
- "arrayReverseSort() only supports arrays".to_string(),
- )),
+ // A non-array reads as empty, matching the Node VM.
+ _ => Ok(HogLiteral::Array(vec![]).into()),
}
}),
),
@@ -281,10 +276,8 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
assert_argc(&args, 2, "arrayStringConcat")?;
let vals = args[0].deref(&vm.heap)?;
let sep = args[1].deref(&vm.heap)?.try_as::<str>()?;
- let HogLiteral::Array(vals) = vals else {
- return Err(VmError::NativeCallFailed(
- "arrayStringConcat() only supports arrays".to_string(),
- ));
+ let (HogLiteral::Array(vals) | HogLiteral::Tuple(vals)) = vals else {
+ return Ok(HogLiteral::from(String::new()).into());
};
let mut parts = Vec::with_capacity(vals.len());
for val in vals.iter() {
@@ -491,7 +484,11 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
"upper",
native_func(|vm, args| {
assert_argc(&args, 1, "upper")?;
- let s: &str = args[0].deref(&vm.heap)?.try_as()?;
+ let subject = args[0].deref(&vm.heap)?;
+ if matches!(subject, HogLiteral::Null) {
+ return Ok(HogLiteral::Null.into());
+ }
+ let s: &str = subject.try_as()?;
Ok(HogLiteral::from(s.to_uppercase()).into())
}),
),
@@ -500,6 +497,7 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
native_func(|vm, args| {
assert_argc(&args, 1, "reverse")?;
match args[0].deref(&vm.heap)? {
+ HogLiteral::Null => Ok(HogLiteral::Null.into()),
HogLiteral::String(s) => {
Ok(HogLiteral::from(s.chars().rev().collect::<String>()).into())
}
@@ -769,7 +767,11 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
"replaceOne",
native_func(|vm, args| {
assert_argc(&args, 3, "replaceOne")?;
- let s: &str = args[0].deref(&vm.heap)?.try_as()?;
+ let subject = args[0].deref(&vm.heap)?;
+ if matches!(subject, HogLiteral::Null) {
+ return Ok(HogLiteral::Null.into());
+ }
+ let s: &str = subject.try_as()?;
let from: &str = args[1].deref(&vm.heap)?.try_as()?;
let to: &str = args[2].deref(&vm.heap)?.try_as()?;
Ok(HogLiteral::from(s.replacen(from, to, 1)).into())
@@ -779,7 +781,11 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
"replaceAll",
native_func(|vm, args| {
assert_argc(&args, 3, "replaceAll")?;
- let s: &str = args[0].deref(&vm.heap)?.try_as()?;
+ let subject = args[0].deref(&vm.heap)?;
+ if matches!(subject, HogLiteral::Null) {
+ return Ok(HogLiteral::Null.into());
+ }
+ let s: &str = subject.try_as()?;
let from: &str = args[1].deref(&vm.heap)?.try_as()?;
let to: &str = args[2].deref(&vm.heap)?.try_as()?;
Ok(HogLiteral::from(s.replace(from, to)).into())
@@ -794,6 +800,9 @@ pub fn stl() -> Vec<(String, NativeFunction)> {
));
}
// splitByString(separator, string[, max])
+ if matches!(args[1].deref(&vm.heap)?, HogLiteral::Null) {
+ return Ok(HogLiteral::Null.into());
+ }
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 {
@@ -2005,7 +2014,11 @@ fn trim_impl(vm: &HogVM, args: Vec<HogValue>, side: TrimSide) -> Result<HogValue
"trim takes 1 or 2 arguments".to_string(),
));
}
- let s: &str = args[0].deref(&vm.heap)?.try_as()?;
+ let subject = args[0].deref(&vm.heap)?;
+ if matches!(subject, HogLiteral::Null) {
+ return Ok(HogLiteral::Null.into());
+ }
+ let s: &str = subject.try_as()?;
let result = if args.len() == 2 {
let chars: Vec<char> = match args[1].deref(&vm.heap)? {
HogLiteral::String(c) => c.chars().collect(),
diff --git a/rust/common/hogvm/src/values.rs b/rust/common/hogvm/src/values.rs
index 91185f83ed83..4c87361b8034 100644
--- a/rust/common/hogvm/src/values.rs
+++ b/rust/common/hogvm/src/values.rs
@@ -543,11 +543,15 @@ pub(crate) fn temporal_seconds_pair(
/// Ordering comparison (`Gt`/`Lt`/`GtEq`/`LtEq`) for two literals, two concerns in order:
///
-/// OPT-IN ONLY: this is reached exclusively from the coercing `compare_op` path, which the VM takes
-/// only when the context sets [`ExecutionContext::with_coercing_comparisons`](crate::ExecutionContext::with_coercing_comparisons),
+/// TWO ENTRY POINTS, and only one of them is opt-in, so weigh both before you edit this. The
+/// `compare_op` opcode path reaches this only when the context sets
+/// [`ExecutionContext::with_coercing_comparisons`](crate::ExecutionContext::with_coercing_comparisons),
/// today just the realtime-cohort evaluator. Every other shared-crate consumer (e.g. `cymbal`) keeps
/// the strict ordering path where operands other than numbers and numeric arrays error, so this
-/// coercion of ORDERING operands does NOT change their behavior. It says nothing about equality:
+/// coercion of ORDERING operands does NOT change their opcode behavior. The named functions
+/// `less`/`greater`/`lessOrEquals`/`greaterOrEquals` are the ungated entry point: they reach this
+/// through [`compare_fn`](crate::stl) on every consumer, so an edit here moves them everywhere. It
+/// says nothing about equality:
/// `Eq`/`NotEq` unify the int and float variants of a number on every path (see
/// [`PartialEq for Num`](Num)). The semantics here match the Python/TS reference VMs (and ClickHouse
/// for temporals).
@@ -570,13 +574,11 @@ pub fn compare_values(
use HogLiteral::{Boolean, Null, Number, String as HString};
match (a, b) {
+ // SQL semantics, shared with the Node and Python VMs: a null on either side is no match.
+ // `compare_op` answers a null operand before it calls here, so this arm is what the named
+ // comparison functions get, and it keeps them equal to the operators.
+ (Null, _) | (_, Null) => Ok(Boolean(false)),
(Number(x), Number(y)) => Num::binary_op(op, x, y),
- // JS relational coercion: null behaves as 0 against numbers and booleans.
- (Null, Number(y)) => Num::binary_op(op, &Num::Integer(0), y),
- (Number(x), Null) => Num::binary_op(op, x, &Num::Integer(0)),
- (Null, Null) => Num::binary_op(op, &Num::Integer(0), &Num::Integer(0)),
- (Null, Boolean(y)) => Num::binary_op(op, &Num::Integer(0), &bool_to_num(*y)),
- (Boolean(x), Null) => Num::binary_op(op, &bool_to_num(*x), &Num::Integer(0)),
(Number(x), HString(s)) => Num::binary_op(op, x, &Num::from_str(s)?),
(HString(s), Number(y)) => Num::binary_op(op, &Num::from_str(s)?, y),
(Boolean(x), Number(y)) => Num::binary_op(op, &bool_to_num(*x), y),
diff --git a/rust/common/hogvm/src/vm.rs b/rust/common/hogvm/src/vm.rs
index 9e1d4e5e6823..ec740f94e9a7 100644
--- a/rust/common/hogvm/src/vm.rs
+++ b/rust/common/hogvm/src/vm.rs
@@ -1007,7 +1007,10 @@ impl<'a> HogVM<'a> {
let result = {
let a_lit = a.deref(&self.heap)?;
let b_lit = b.deref(&self.heap)?;
- if self.context.coerce_comparisons {
+ if matches!(a_lit, HogLiteral::Null) || matches!(b_lit, HogLiteral::Null) {
+ // SQL semantics, shared with the Node and Python VMs: a null on either side is no match.
+ HogLiteral::Boolean(false)
+ } else if self.context.coerce_comparisons {
compare_values(op, a_lit, b_lit, &self.heap)?
} else if let (HogLiteral::Array(a_values), HogLiteral::Array(b_values)) =
(a_lit, b_lit)