Files
zeekayandHanzo Dev b7e2b62a39 refactor(scriptvm): name the emitted runtime for what it does
The compiler emits its runtime helpers by name and the VM defines them by
name, so the two are one contract. It was renamed on one side only: all
three engines -- the Python VM, the TypeScript VM, and the JS emitter --
already said `__printScriptValue`, while every committed snapshot still
said `__printHogValue`. The snapshots had not been regenerated since.

That was not only cosmetic. `catch.script` and `catch2.script` call
`HogError(...)`, an STL name that became `ScriptError`, so both had been
failing; and `stl.stdout` recorded `__hogInterval__` for a marker the
engines stopped writing two renames ago.

So: drop the language's name from the helpers, since inside its own
runtime every value is a Script value and the infix distinguishes
nothing. Both sides move here, together, and the snapshots are
regenerated from the compiler rather than edited to agree.

Two names could not simply lose the infix, and the collision is the
interesting part:

  __toScriptDate/DateTime -> __newDate/__newDateTime, not __toDate,
  which already exists and is a different function -- the STL builtin
  that PARSES a foreign input, where these build a value from its parts.
  They join `__newError`, which was already named that way.

  ScriptError stays. Its remaining word is `Error`, also taken, and also
  a different function: `Error(message)` fixes the type, `ScriptError(
  type, message)` takes it.

Leaving the families orthogonal: `__new*` builds, `__to*` converts,
`__is*` tests, `__x__` marks, `__print*` renders.

Verified with the two engines this ABI spans, python-VM output against
compiled-JS output per test: 31 pass / 4 fail, against 29 / 6 on the
commit before this one. The two it fixes are catch and catch2. The four
that remain fail identically on both trees and are untouched by this.

`insightsqlx.js` is deliberately NOT regenerated and still spells the
old names: its source does not compile on either tree
(`BytecodeCompiler has no method visit_insights_qlxtag`), and editing a
snapshot by hand to agree with a rename is the exact failure this commit
exists to undo.

Co-authored-by: Hanzo Dev <[email protected]>
2026-08-13 20:04:08 -07:00

132 lines
6.4 KiB
JavaScript

function print (...args) { console.log(...args.map(__printStringOutput)) }
function jsonStringify (value, spacing) {
function convert(x, marked) {
if (!marked) { marked = new Set() }
if (typeof x === 'object' && x !== null) {
if (marked.has(x)) { return null }
marked.add(x)
try {
if (x instanceof Map) {
const obj = {}
x.forEach((value, key) => { obj[convert(key, marked)] = convert(value, marked) })
return obj
}
if (Array.isArray(x)) { return x.map((v) => convert(v, marked)) }
if (__isDateTime(x) || __isDate(x) || __isError(x)) { return x }
if (typeof x === 'function') { return `fn<${x.name || 'lambda'}(${x.length})>` }
const obj = {}; for (const key in x) { obj[key] = convert(x[key], marked) }
return obj
} finally {
marked.delete(x)
}
}
return x
}
if (spacing && typeof spacing === 'number' && spacing > 0) {
return JSON.stringify(convert(value), null, spacing)
}
return JSON.stringify(convert(value), (key, val) => typeof val === 'function' ? `fn<${val.name || 'lambda'}(${val.length})>` : val)
}
function jsonParse (str) {
function convert(x) {
if (Array.isArray(x)) { return x.map(convert) }
else if (typeof x === 'object' && x !== null) {
if (x.__dateTime__) { return __newDateTime(x.dt, x.zone)
} else if (x.__date__) { return __newDate(x.year, x.month, x.day)
} else if (x.__error__) { return __newError(x.type, x.message, x.payload) }
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 arrayPushBack (arr, item) { if (!Array.isArray(arr)) { return [item] } return [...arr, item] }
function __printStringOutput(obj) { if (typeof obj === 'string') { return obj } return __printValue(obj) }
function __printValue(obj, marked = new Set()) {
if (typeof obj === 'object' && obj !== null && obj !== undefined) {
if (marked.has(obj) && !__isDateTime(obj) && !__isDate(obj) && !__isError(obj)) { return 'null'; }
marked.add(obj);
try {
if (Array.isArray(obj)) {
if (obj.__isTuple) { return obj.length < 2 ? `tuple(${obj.map((o) => __printValue(o, marked)).join(', ')})` : `(${obj.map((o) => __printValue(o, marked)).join(', ')})`; }
return `[${obj.map((o) => __printValue(o, marked)).join(', ')}]`;
}
if (__isDateTime(obj)) { const millis = String(obj.dt); return `DateTime(${millis}${millis.includes('.') ? '' : '.0'}, ${__escapeString(obj.zone)})`; }
if (__isDate(obj)) return `Date(${obj.year}, ${obj.month}, ${obj.day})`;
if (__isError(obj)) { return `${String(obj.type)}(${__escapeString(obj.message)}${obj.payload ? `, ${__printValue(obj.payload, marked)}` : ''})`; }
if (obj instanceof Map) { return `{${Array.from(obj.entries()).map(([key, value]) => `${__printValue(key, marked)}: ${__printValue(value, marked)}`).join(', ')}}`; }
return `{${Object.entries(obj).map(([key, value]) => `${__printValue(key, marked)}: ${__printValue(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 __newError(type, message, payload) {
let error = new Error(message || 'An error occurred');
error.__error__ = true
error.type = type
error.payload = payload
return error
}
function __newDateTime(timestamp, zone) {
if (__isDate(timestamp)) {
const date = new Date(Date.UTC(timestamp.year, timestamp.month - 1, timestamp.day));
const dt = date.getTime() / 1000;
return { __dateTime__: true, dt: dt, zone: zone || 'UTC' };
}
return { __dateTime__: true, dt: timestamp, zone: zone || 'UTC' }; }
function __newDate(year, month, day) { return { __date__: true, year: year, month: month, day: day, } }
function __lambda (fn) { return fn }
function __isError(obj) {return obj && obj.__error__ === true}
function __isDateTime(obj) { return obj && obj.__dateTime__ === true }
function __isDate(obj) { return obj && obj.__date__ === true }
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] }
else { return objectOrArray[key] }
}
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 b = __lambda((x) => (x * 2));
print(b);
print(b(2));
print(b(8));
print("--------");
let func = __lambda((x) => (x * 2));
let arr = [func];
print(func(2));
print(__getProperty(arr, 1, false)(2));
print(__lambda((x) => (x * 2))(2));
print("--------");
let withArg = __lambda((x) => {
print(x);
print("moo");
print("cow");
});
withArg(2);
print("--------");
let noArg = __lambda(() => {
print("moo");
print("cow");
});
noArg();
print("-------- lambdas do not survive json --------");
print(b);
print(jsonStringify(b));
let c = jsonParse(jsonStringify(b));
print(c);
print("--------");
let arrayMapObjects = arrayMap(__lambda((a) => ({"a": a})), [1, 2, 3]);
print(arrayMapObjects);