eliscript 0.0.3 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.md +6 -6
  2. package/bootstrap/README.md +13 -8
  3. package/bootstrap/host/build.eli +2 -0
  4. package/bootstrap/host/bun.eli +2 -0
  5. package/bootstrap/host/check-cli-legacy.eli +2 -0
  6. package/bootstrap/host/evaluation-cli.eli +2 -0
  7. package/bootstrap/host/evaluation.eli +2 -0
  8. package/bootstrap/host/format-cli.eli +2 -0
  9. package/bootstrap/host/project-cli-legacy.eli +2 -0
  10. package/bootstrap/host/project-legacy.eli +2 -0
  11. package/bootstrap/host/watch-cli.eli +2 -0
  12. package/bootstrap/host/watch.eli +2 -0
  13. package/browser/README.md +33 -0
  14. package/browser/host.eli +2 -0
  15. package/browser/worker.eli +2 -0
  16. package/editor/eliscript-abi.el +170 -0
  17. package/editor/eliscript-async.el +375 -0
  18. package/editor/eliscript-bind.el +822 -0
  19. package/editor/eliscript-compat.el +184 -0
  20. package/editor/eliscript-contract.el +334 -0
  21. package/editor/eliscript-data.el +1544 -0
  22. package/editor/eliscript-js.el +318 -0
  23. package/editor/eliscript-mode.el +1 -1
  24. package/editor/eliscript-module.el +340 -0
  25. package/editor/eliscript-repl.el +1 -1
  26. package/package.json +4 -1
  27. package/platform/README.md +33 -12
  28. package/platform/browser.eli +2 -0
  29. package/platform/http.eli +2 -0
  30. package/platform/worker.eli +2 -0
  31. package/runtime/README.md +34 -14
  32. package/runtime/array-text.eli +2 -0
  33. package/runtime/core/collection-internals.eli +2 -0
  34. package/runtime/core/collection.eli +2 -0
  35. package/runtime/core/collection.mjs +99 -17
  36. package/runtime/core/data-text.eli +2 -0
  37. package/runtime/core/data.eli +2 -0
  38. package/runtime/core/data.mjs +7 -5
  39. package/runtime/core/identifier.eli +2 -0
  40. package/runtime/core/lazy-sequence.eli +2 -0
  41. package/runtime/core/list-internals.eli +2 -0
  42. package/runtime/core/list.eli +2 -0
  43. package/runtime/core/list.mjs +3 -0
  44. package/runtime/core/map-internals.eli +2 -0
  45. package/runtime/core/map.eli +2 -0
  46. package/runtime/core/map.mjs +5 -0
  47. package/runtime/core/metadata-internals.eli +2 -0
  48. package/runtime/core/metadata.eli +2 -0
  49. package/runtime/core/metadata.mjs +14 -0
  50. package/runtime/core/object.eli +2 -0
  51. package/runtime/core/order.eli +2 -0
  52. package/runtime/core/order.mjs +35 -6
  53. package/runtime/core/persistent-kind.eli +2 -0
  54. package/runtime/core/persistent-kind.mjs +6 -0
  55. package/runtime/core/protocol-error.eli +2 -0
  56. package/runtime/core/protocol.eli +2 -0
  57. package/runtime/core/queue-internals.eli +2 -0
  58. package/runtime/core/queue.eli +2 -0
  59. package/runtime/core/queue.mjs +3 -0
  60. package/runtime/core/record.eli +2 -0
  61. package/runtime/core/regex.eli +2 -0
  62. package/runtime/core/sequence.eli +2 -0
  63. package/runtime/core/sequence.mjs +75 -13
  64. package/runtime/core/set-algebra.eli +2 -0
  65. package/runtime/core/set-internals.eli +2 -0
  66. package/runtime/core/set.eli +2 -0
  67. package/runtime/core/sorted-internals.eli +2 -0
  68. package/runtime/core/sorted.eli +2 -0
  69. package/runtime/core/text.eli +2 -0
  70. package/runtime/core/transducer.eli +2 -0
  71. package/runtime/core/transient-internals.eli +2 -0
  72. package/runtime/core/transient.eli +2 -0
  73. package/runtime/core/transient.mjs +59 -10
  74. package/runtime/core/truth.eli +2 -0
  75. package/runtime/core/type.eli +2 -0
  76. package/runtime/core/value-internals.eli +2 -0
  77. package/runtime/core/value.eli +2 -0
  78. package/runtime/core/vector-internals.eli +2 -0
  79. package/runtime/core/vector-internals.mjs +3 -6
  80. package/runtime/core/vector.eli +2 -0
  81. package/runtime/core/vector.mjs +125 -7
  82. package/runtime/emacs-compat.eli +2 -0
  83. package/runtime/emacs-compat.mjs +2507 -0
  84. package/runtime/literals.eli +2 -0
  85. package/runtime/number-radix.eli +2 -0
  86. package/runtime/source-mapping.eli +2 -0
  87. package/runtime/testing/list.eli +2 -0
  88. package/runtime/testing/map.eli +2 -0
  89. package/runtime/testing/queue.eli +2 -0
  90. package/runtime/testing/set.eli +2 -0
  91. package/runtime/testing/sorted.eli +2 -0
  92. package/runtime/testing/value.eli +2 -0
  93. package/runtime/testing/vector.eli +2 -0
  94. package/runtime/wire/http-rpc.eli +2 -0
  95. package/runtime/wire/markdown.eli +2 -0
  96. package/runtime/wire/schema.eli +2 -0
  97. package/runtime/worker-value-codec.eli +2 -0
  98. package/runtime/worker-value-stream.eli +2 -0
  99. package/runtime/worker.eli +2 -0
  100. package/stdlib/README.md +2 -2
  101. package/stdlib/core/order.eli +36 -10
  102. package/stdlib/core/seq.eli +104 -75
  103. package/stdlib/core/zipper.eli +238 -98
  104. package/stdlib/managed-literal-protocols.eli +5 -5
  105. package/stdlib/managed-runtime-order.eli +32 -10
  106. package/stdlib/managed-runtime-sequence.eli +69 -28
  107. package/tools/acceptance/check.eli +13 -3
  108. package/tools/backends/compiler-build.mjs +140 -140
@@ -389,13 +389,13 @@ export class PersistentVector {
389
389
  "PersistentVector values must be created with persistentVector or PersistentVector.from",
390
390
  );
391
391
  }
392
- this[VECTOR_STATE] = Object.freeze({
392
+ this[VECTOR_STATE] = {
393
393
  count,
394
394
  shift,
395
395
  root,
396
396
  tail,
397
397
  metadata,
398
- });
398
+ };
399
399
  Object.freeze(this);
400
400
  }
401
401
 
@@ -403,10 +403,72 @@ export class PersistentVector {
403
403
  return EMPTY_VECTOR;
404
404
  }
405
405
 
406
+ static single(value) {
407
+ return makeVector(
408
+ 1,
409
+ BRANCH_BITS,
410
+ EMPTY_ROOT,
411
+ allocateTail([value]),
412
+ null,
413
+ );
414
+ }
415
+
416
+ static pairWithMeta(first, second, metadata = null) {
417
+ return makeVector(
418
+ 2,
419
+ BRANCH_BITS,
420
+ EMPTY_ROOT,
421
+ allocateTail([first, second]),
422
+ metadata,
423
+ );
424
+ }
425
+
426
+ static rawSlot(vector, index) {
427
+ return vector[VECTOR_STATE].tail[index];
428
+ }
429
+
406
430
  static from(iterable) {
407
431
  if (iterable instanceof PersistentVector) {
408
432
  return iterable;
409
433
  }
434
+ if (
435
+ Array.isArray(iterable) &&
436
+ Object.getPrototypeOf(iterable) === Array.prototype &&
437
+ !Object.hasOwn(iterable, Symbol.iterator) &&
438
+ iterable[Symbol.iterator] === Array.prototype[Symbol.iterator]
439
+ ) {
440
+ const length = iterable.length;
441
+ if (length === 0) return EMPTY_VECTOR;
442
+ if (length <= BRANCH_WIDTH) {
443
+ return makeVector(
444
+ length,
445
+ BRANCH_BITS,
446
+ EMPTY_ROOT,
447
+ allocateTail(iterable.slice()),
448
+ );
449
+ }
450
+ let root = EMPTY_ROOT;
451
+ let shift = BRANCH_BITS;
452
+ let count = BRANCH_WIDTH;
453
+ let tail = allocateTail(iterable.slice(0, BRANCH_WIDTH));
454
+ while (count < length) {
455
+ const nextEnd = Math.min(count + BRANCH_WIDTH, length);
456
+ const tailNode = new VectorNode(tail);
457
+ if ((count >>> BRANCH_BITS) > (1 << shift)) {
458
+ root = new VectorNode([
459
+ root,
460
+ newPath(shift, tailNode),
461
+ ]);
462
+ shift += BRANCH_BITS;
463
+ recordRootGrowth();
464
+ } else {
465
+ root = pushTail(shift, root, tailNode, count);
466
+ }
467
+ tail = allocateTail(iterable.slice(count, nextEnd));
468
+ count = nextEnd;
469
+ }
470
+ return makeVector(length, shift, root, tail);
471
+ }
410
472
  let result = EMPTY_VECTOR;
411
473
  for (const value of iterable) {
412
474
  result = result.conj(value);
@@ -424,13 +486,28 @@ export class PersistentVector {
424
486
 
425
487
  nth(index, notFound = MISSING) {
426
488
  const state = this[VECTOR_STATE];
427
- if (!Number.isInteger(index) || index < 0 || index >= state.count) {
428
- if (notFound !== MISSING) {
429
- return notFound;
489
+ if (((index | 0) === index || Number.isInteger(index)) && index >= 0 && index < state.count) {
490
+ if (state.count <= BRANCH_WIDTH) {
491
+ const value = state.tail[index];
492
+ if (
493
+ index === 1 &&
494
+ state.count === 2 &&
495
+ state.metadata !== null &&
496
+ Array.isArray(value) &&
497
+ value.length === 6 &&
498
+ value[5] === true &&
499
+ !Object.isFrozen(value)
500
+ ) {
501
+ Object.freeze(value);
502
+ }
503
+ return value;
430
504
  }
431
- assertIndex(index, state.count, "nth");
505
+ return arrayFor(state, index)[index & BRANCH_MASK];
506
+ }
507
+ if (notFound !== MISSING) {
508
+ return notFound;
432
509
  }
433
- return arrayFor(state, index)[index & BRANCH_MASK];
510
+ assertIndex(index, state.count, "nth");
434
511
  }
435
512
 
436
513
  assoc(index, value) {
@@ -648,7 +725,34 @@ export class PersistentVector {
648
725
  }, []);
649
726
  }
650
727
 
728
+ sliceVector(start, end) {
729
+ const state = this[VECTOR_STATE];
730
+ const length = end - start;
731
+ if (length <= 0) return EMPTY_VECTOR;
732
+ if (start === 0 && end >= state.count && state.metadata === null) {
733
+ return this;
734
+ }
735
+ const values = new Array(length);
736
+ let outIndex = 0;
737
+ let index = start;
738
+ while (index < end) {
739
+ const chunk = arrayFor(state, index);
740
+ const chunkOffset = index & BRANCH_MASK;
741
+ const chunkBase = index - chunkOffset;
742
+ const chunkEnd = Math.min(end - chunkBase, chunk.length);
743
+ for (let i = chunkOffset; i < chunkEnd; i += 1) {
744
+ values[outIndex] = chunk[i];
745
+ outIndex += 1;
746
+ }
747
+ index = chunkBase + chunkEnd;
748
+ }
749
+ return PersistentVector.from(values);
750
+ }
751
+
651
752
  [VALUE_EQUAL](other, equal) {
753
+ if (this === other) {
754
+ return true;
755
+ }
652
756
  if (!(other instanceof PersistentVector) || other.count !== this.count) {
653
757
  return false;
654
758
  }
@@ -724,6 +828,11 @@ class PersistentSubVector extends PersistentVector {
724
828
  return this.count;
725
829
  }
726
830
 
831
+ sliceVector(start, end) {
832
+ const state = SUBVECTOR_STATE.get(this);
833
+ return state.vector.sliceVector(state.start + start, state.start + end);
834
+ }
835
+
727
836
  nth(index, notFound = MISSING) {
728
837
  const state = SUBVECTOR_STATE.get(this);
729
838
  const count = state.end - state.start;
@@ -920,6 +1029,15 @@ class PersistentSubVector extends PersistentVector {
920
1029
  export const EMPTY_VECTOR = makeVector(0, BRANCH_BITS, EMPTY_ROOT, EMPTY_TAIL);
921
1030
 
922
1031
  export function persistentVector(...values) {
1032
+ if (values.length === 0) return EMPTY_VECTOR;
1033
+ if (values.length <= BRANCH_WIDTH) {
1034
+ return makeVector(
1035
+ values.length,
1036
+ BRANCH_BITS,
1037
+ EMPTY_ROOT,
1038
+ allocateTail(values),
1039
+ );
1040
+ }
923
1041
  return PersistentVector.from(values);
924
1042
  }
925
1043
 
@@ -0,0 +1,2 @@
1
+ (module capsules.runtime.emacs-compat
2
+ (js* "// ============================================================================\n// 1. Core Value Representations & Condition Hierarchy\n// ============================================================================\n\nexport class EliscriptSignal extends Error {\n constructor(conditionSymbol, data = []) {\n const msg = `${conditionSymbol}: ${data.map((d) => String(d)).join(\" \")}`;\n super(msg);\n this.name = \"EliscriptSignal\";\n this.conditionSymbol = conditionSymbol;\n this.data = Array.isArray(data) ? data : [data];\n }\n}\n\nclass CatchThrowJump {\n constructor(tag, value) {\n this.tag = tag;\n this.value = value;\n }\n}\n\nclass RecurSignal {\n constructor(args) {\n this.args = args;\n }\n}\n\nconst CONDITION_PARENTS = new Map([\n [\"eliscript-timeout\", \"eliscript-cancelled\"],\n [\"eliscript-cancelled\", \"quit\"],\n [\"eliscript-compile-error\", \"error\"],\n [\"eliscript-declaration-error\", \"eliscript-compile-error\"],\n [\"eliscript-contract-error\", \"eliscript-compile-error\"],\n [\"eliscript-runtime-contract-error\", \"error\"],\n [\"eliscript-channel-closed\", \"error\"],\n [\"eliscript-engine-handle-error\", \"error\"],\n [\"js-error\", \"error\"],\n [\"arith-error\", \"error\"],\n [\"void-function\", \"error\"],\n [\"void-variable\", \"error\"],\n [\"wrong-type-argument\", \"error\"],\n [\"wrong-number-of-arguments\", \"error\"],\n]);\n\nfunction conditionMatches(thrownSym, handlerSym) {\n if (handlerSym === \"t\") return true;\n let cur = thrownSym;\n while (cur) {\n if (cur === handlerSym) return true;\n cur = CONDITION_PARENTS.get(cur) ?? null;\n }\n return false;\n}\n\nfunction signalError(sym, ...data) {\n throw new EliscriptSignal(sym, data);\n}\n\nexport function sym(name) {\n return { kind: \"symbol\", name: String(name) };\n}\n\nexport function kw(name) {\n const s = String(name);\n return { kind: \"keyword\", name: s.startsWith(\":\") ? s : `:${s}` };\n}\n\nfunction isSym(v, name) {\n if (!v || v.kind !== \"symbol\") return false;\n return name === undefined ? true : v.name === name;\n}\n\nfunction isKw(v, name) {\n if (!v || v.kind !== \"keyword\") return false;\n return name === undefined ? true : v.name === name;\n}\n\nfunction isTruthy(v) {\n return v !== null;\n}\n\nfunction makeCons(car, cdr) {\n return { kind: \"cons\", car, cdr };\n}\n\nfunction arrayToConsList(arr) {\n let out = null;\n for (let i = arr.length - 1; i >= 0; i -= 1) {\n out = makeCons(arr[i], out);\n }\n return out;\n}\n\nfunction consListToArray(list) {\n if (list === null) return [];\n if (Array.isArray(list)) return list;\n const out = [];\n let cur = list;\n while (cur && cur.kind === \"cons\") {\n out.push(cur.car);\n cur = cur.cdr;\n }\n return out;\n}\n\nfunction makeNativeVector(items) {\n return { kind: \"vector\", items: [...items] };\n}\n\n// Sentinels for eliscript-js\nexport const JS_FALSE = Object.freeze({ kind: \"js-sentinel\", sentinel: \"false\" });\nexport const JS_NULL = Object.freeze({ kind: \"js-sentinel\", sentinel: \"null\" });\nexport const JS_UNDEFINED = Object.freeze({ kind: \"js-sentinel\", sentinel: \"undefined\" });\nexport const OPTION_NONE = Object.freeze({ kind: \"option\", some: false, value: null });\n\n// ============================================================================\n// 2. S-Expression Reader (100% Standard Emacs Lisp Reader)\n// ============================================================================\n\nfunction tokenizeSexp(source) {\n const tokens = [];\n let i = 0;\n const n = source.length;\n while (i < n) {\n const ch = source[i];\n if (/\\s/u.test(ch)) {\n i += 1;\n continue;\n }\n if (ch === \";\") {\n while (i < n && source[i] !== \"\\n\") i += 1;\n continue;\n }\n if (ch === \"(\" || ch === \")\" || ch === \"[\" || ch === \"]\" || ch === \"'\" || ch === \"`\") {\n tokens.push({ type: ch, value: ch });\n i += 1;\n continue;\n }\n if (ch === \",\") {\n if (source[i + 1] === \"@\") {\n tokens.push({ type: \",@\", value: \",@\" });\n i += 2;\n } else {\n tokens.push({ type: \",\", value: \",\" });\n i += 1;\n }\n continue;\n }\n if (ch === \"#\" && source[i + 1] === \"'\") {\n tokens.push({ type: \"#'\", value: \"#'\" });\n i += 2;\n continue;\n }\n if (ch === \"#\" && (source[i + 1] === \"x\" || source[i + 1] === \"X\")) {\n let j = i + 2;\n while (j < n && /[0-9a-fA-F]/u.test(source[j])) j += 1;\n const hex = source.slice(i + 2, j);\n tokens.push({ type: \"number\", value: Number.parseInt(hex, 16), isFloat: false });\n i = j;\n continue;\n }\n if (ch === '\"') {\n let j = i + 1;\n let str = \"\";\n while (j < n && source[j] !== '\"') {\n if (source[j] === \"\\\\\") {\n const next = source[j + 1];\n if (next === \"n\") str += \"\\n\";\n else if (next === \"t\") str += \"\\t\";\n else if (next === \"r\") str += \"\\r\";\n else if (next === '\"') str += '\"';\n else if (next === \"\\\\\") str += \"\\\\\";\n else str += \"\\\\\" + next;\n j += 2;\n } else {\n str += source[j];\n j += 1;\n }\n }\n tokens.push({ type: \"string\", value: str });\n i = j + 1;\n continue;\n }\n let j = i;\n while (j < n && !/[\\s()\\[\\]\"';`,]/u.test(source[j])) {\n j += 1;\n }\n const raw = source.slice(i, j);\n if (/^[+-]?(?:\\d+\\.\\d*|\\.\\d+)(?:[eE][+-]?\\d+)?$/u.test(raw)) {\n tokens.push({ type: \"number\", value: Number(raw), isFloat: true });\n } else if (/^[+-]?\\d+$/u.test(raw)) {\n tokens.push({ type: \"number\", value: Number.parseInt(raw, 10), isFloat: false });\n } else {\n tokens.push({ type: \"atom\", value: raw });\n }\n i = j;\n }\n return tokens;\n}\n\nexport function readAllForms(source) {\n const tokens = tokenizeSexp(source);\n let pos = 0;\n\n function readForm() {\n if (pos >= tokens.length) return undefined;\n const tok = tokens[pos++];\n if (tok.type === \"'\") {\n return arrayToConsList([sym(\"quote\"), readForm()]);\n }\n if (tok.type === \"#'\") {\n return arrayToConsList([sym(\"function\"), readForm()]);\n }\n if (tok.type === \"`\") {\n return arrayToConsList([sym(\"backquote\"), readForm()]);\n }\n if (tok.type === \",\") {\n return arrayToConsList([sym(\"unquote\"), readForm()]);\n }\n if (tok.type === \",@\") {\n return arrayToConsList([sym(\"unquote-splicing\"), readForm()]);\n }\n if (tok.type === \"(\") {\n const items = [];\n let cdrVal = null;\n while (pos < tokens.length && tokens[pos].type !== \")\") {\n if (tokens[pos].type === \"atom\" && tokens[pos].value === \".\") {\n pos += 1;\n cdrVal = readForm();\n break;\n }\n items.push(readForm());\n }\n if (tokens[pos]?.type === \")\") pos += 1;\n if (items.length === 0 && cdrVal === null) return null;\n let list = cdrVal;\n for (let idx = items.length - 1; idx >= 0; idx -= 1) {\n list = makeCons(items[idx], list);\n }\n return list;\n }\n if (tok.type === \"[\") {\n const items = [];\n while (pos < tokens.length && tokens[pos].type !== \"]\") {\n items.push(readForm());\n }\n if (tokens[pos]?.type === \"]\") pos += 1;\n return makeNativeVector(items);\n }\n if (tok.type === \"string\") return tok.value;\n if (tok.type === \"number\") {\n if (tok.isFloat && Number.isInteger(tok.value)) {\n return { kind: \"float-lit\", value: tok.value };\n }\n return tok.value;\n }\n if (tok.type === \"atom\") {\n if (tok.value === \"nil\") return null;\n if (tok.value === \"t\") return true;\n if (tok.value.startsWith(\":\")) return kw(tok.value);\n return sym(tok.value);\n }\n return null;\n }\n\n const forms = [];\n while (pos < tokens.length) {\n const f = readForm();\n if (f !== undefined) forms.push(f);\n }\n return forms;\n}\n\n// ============================================================================\n// 3. Value Equality, Comparison, Persistent Collections & Structs\n// ============================================================================\n\nexport function valueEqual(a, b) {\n if (a === b) return true;\n if (a === null || b === null || a === undefined || b === undefined) return false;\n if (typeof a === \"number\" && typeof b === \"number\") return a === b;\n if (typeof a === \"string\" && typeof b === \"string\") return a === b;\n if (typeof a === \"boolean\" && typeof b === \"boolean\") return a === b;\n if (isSym(a) && isSym(b)) return a.name === b.name;\n if (isKw(a) && isKw(b)) return a.name === b.name;\n const seqKinds = new Set([\"persistent-list\", \"persistent-vector\", \"persistent-queue\"]);\n if (seqKinds.has(a.kind) && seqKinds.has(b.kind)) {\n if (a.items.length !== b.items.length) return false;\n return a.items.every((x, idx) => valueEqual(x, b.items[idx]));\n }\n const mapKinds = new Set([\"persistent-map\", \"persistent-sorted-map\"]);\n if (mapKinds.has(a.kind) && mapKinds.has(b.kind)) {\n if (a.entries.length !== b.entries.length) return false;\n return a.entries.every(([ka, va]) => {\n const found = b.entries.find(([kb]) => valueEqual(ka, kb));\n return Boolean(found && valueEqual(va, found[1]));\n });\n }\n const setKinds = new Set([\"persistent-set\", \"persistent-sorted-set\"]);\n if (setKinds.has(a.kind) && setKinds.has(b.kind)) {\n if (a.items.length !== b.items.length) return false;\n return a.items.every((x) => b.items.some((y) => valueEqual(x, y)));\n }\n if (a.kind === \"persistent-record\" && b.kind === \"persistent-record\") {\n if (a.typeName !== b.typeName || a.entries.length !== b.entries.length) return false;\n return a.entries.every(([k, va]) => {\n const found = b.entries.find(([kb]) => kb === k);\n return Boolean(found && valueEqual(va, found[1]));\n });\n }\n if (a.kind === \"vector\" && b.kind === \"vector\") {\n if (a.items.length !== b.items.length) return false;\n return a.items.every((x, idx) => valueEqual(x, b.items[idx]));\n }\n if (a.kind === \"cons\" && b.kind === \"cons\") {\n return valueEqual(a.car, b.car) && valueEqual(a.cdr, b.cdr);\n }\n return false;\n}\n\nexport function valueCompare(a, b) {\n if (valueEqual(a, b)) return 0;\n if (a === null) return -1;\n if (b === null) return 1;\n if (typeof a === \"number\" && typeof b === \"number\") return a < b ? -1 : 1;\n if (typeof a === \"string\" && typeof b === \"string\") return a < b ? -1 : 1;\n const sa = isSym(a) || isKw(a) ? a.name : JSON.stringify(a);\n const sb = isSym(b) || isKw(b) ? b.name : JSON.stringify(b);\n return sa < sb ? -1 : 1;\n}\n\nfunction assocEntries(entries, key, val) {\n let found = false;\n const next = entries.map(([k, v]) => {\n if (!found && valueEqual(k, key)) {\n found = true;\n return [key, val];\n }\n return [k, v];\n });\n if (!found) next.push([key, val]);\n return next;\n}\n\nfunction dissocEntries(entries, key) {\n return entries.filter(([k]) => !valueEqual(k, key));\n}\n\nfunction makePersistentList(items = [], meta = null) {\n return { kind: \"persistent-list\", items: [...items], meta };\n}\n\nfunction makePersistentVector(items = [], meta = null) {\n return { kind: \"persistent-vector\", items: [...items], meta };\n}\n\nfunction makePersistentMap(kvs = [], meta = null) {\n let entries = [];\n for (let i = 0; i < kvs.length; i += 2) {\n entries = assocEntries(entries, kvs[i], kvs[i + 1]);\n }\n return { kind: \"persistent-map\", entries, meta };\n}\n\nfunction makePersistentSet(items = [], meta = null) {\n const unique = [];\n for (const it of items) {\n if (!unique.some((x) => valueEqual(x, it))) unique.push(it);\n }\n return { kind: \"persistent-set\", items: unique, meta };\n}\n\nfunction makePersistentQueue(items = [], meta = null) {\n return { kind: \"persistent-queue\", items: [...items], meta };\n}\n\nfunction normalizeCmpFn(cmpFn) {\n const fn = typeof cmpFn === \"function\" ? cmpFn : valueCompare;\n return (a, b) => {\n const r = fn(a, b);\n if (typeof r === \"number\") return r;\n if (r === true) return -1;\n return valueEqual(a, b) ? 0 : 1;\n };\n}\n\nfunction makePersistentSortedMap(args) {\n const hasCmp = typeof args[0] === \"function\" && (args.length - 1) % 2 === 0;\n const cmp = hasCmp ? args[0] : valueCompare;\n const kvs = hasCmp ? args.slice(1) : args;\n const norm = normalizeCmpFn(cmp);\n let entries = [];\n for (let i = 0; i < kvs.length; i += 2) {\n entries = assocEntries(entries, kvs[i], kvs[i + 1]);\n }\n entries.sort((a, b) => norm(a[0], b[0]));\n return { kind: \"persistent-sorted-map\", comparator: cmp, entries, meta: null };\n}\n\nfunction makePersistentSortedSet(args) {\n const hasCmp = typeof args[0] === \"function\";\n const cmp = hasCmp ? args[0] : valueCompare;\n const items = hasCmp ? args.slice(1) : args;\n const norm = normalizeCmpFn(cmp);\n const unique = [];\n for (const it of items) {\n if (!unique.some((x) => norm(x, it) === 0)) unique.push(it);\n }\n unique.sort(norm);\n return { kind: \"persistent-sorted-set\", comparator: cmp, items: unique, meta: null };\n}\n\nfunction extractSeqElements(coll) {\n if (coll === null) return [];\n if (Array.isArray(coll)) return coll;\n if (coll.kind === \"cons\") return consListToArray(coll);\n if (\n coll.kind === \"vector\" ||\n coll.kind === \"persistent-list\" ||\n coll.kind === \"persistent-vector\" ||\n coll.kind === \"persistent-set\" ||\n coll.kind === \"persistent-sorted-set\" ||\n coll.kind === \"persistent-queue\"\n ) {\n return [...coll.items];\n }\n if (\n coll.kind === \"persistent-map\" ||\n coll.kind === \"persistent-sorted-map\" ||\n coll.kind === \"persistent-record\"\n ) {\n return coll.entries.map(([k, v]) => arrayToConsList([k, v]));\n }\n if (coll.kind === \"lazy-seq\") {\n const out = [];\n let cur = coll;\n while (cur) {\n if (cur.kind === \"lazy-seq\") cur = cur.step();\n else if (cur.kind === \"cons\") {\n out.push(cur.car);\n cur = cur.cdr;\n } else break;\n }\n return out;\n }\n throw new Error(`Not a sequential collection: ${String(coll)}`);\n}\n\nfunction valueContains(coll, key) {\n if (!coll) return false;\n if (coll.kind === \"persistent-map\" || coll.kind === \"persistent-sorted-map\") {\n return coll.entries.some(([k]) => valueEqual(k, key));\n }\n if (coll.kind === \"persistent-record\") {\n const fname = isKw(key) ? key.name.slice(1) : isSym(key) ? key.name : String(key);\n return coll.entries.some(([k]) => k === fname);\n }\n if (coll.kind === \"hash-table\") {\n const kstr = isKw(key) || isSym(key) ? key.name : key;\n return coll.map.has(kstr);\n }\n return false;\n}\n\nfunction valueGet(coll, key, notFound = null) {\n if (coll === null || coll === undefined) return notFound;\n if (coll.kind === \"persistent-map\" || coll.kind === \"persistent-sorted-map\") {\n const cell = coll.entries.find(([k]) => valueEqual(k, key));\n return cell ? cell[1] : notFound;\n }\n if (coll.kind === \"persistent-record\") {\n const fname = isKw(key) ? key.name.slice(1) : isSym(key) ? key.name : String(key);\n const cell = coll.entries.find(([k]) => k === fname);\n return cell ? cell[1] : notFound;\n }\n if (coll.kind === \"hash-table\") {\n const kstr = isKw(key) || isSym(key) ? key.name : key;\n return coll.map.has(kstr) ? coll.map.get(kstr) : notFound;\n }\n if (coll.kind === \"persistent-vector\" || coll.kind === \"vector\") {\n return key >= 0 && key < coll.items.length ? coll.items[key] : notFound;\n }\n return notFound;\n}\n\nfunction valueCount(coll) {\n if (coll === null) return 0;\n if (typeof coll === \"string\") return Array.from(coll).length;\n if (coll.kind === \"hash-table\") return coll.map.size;\n if (\n coll.kind === \"persistent-map\" ||\n coll.kind === \"persistent-sorted-map\" ||\n coll.kind === \"persistent-record\"\n ) {\n return coll.entries.length;\n }\n return extractSeqElements(coll).length;\n}\n\n// ============================================================================\n// 4. Lisp-2 Session State, Static Contracts & Evaluator\n// ============================================================================\n\nconst EXTENSION_EXPORTS = {\n \"eliscript-data\": [\n \"persistent-list\", \"persistent-list-p\", \"persistent-vector\", \"persistent-vector-p\",\n \"persistent-map\", \"persistent-map-p\", \"persistent-set\", \"persistent-set-p\",\n \"persistent-queue\", \"persistent-queue-p\", \"persistent-sorted-map\", \"persistent-sorted-map-p\",\n \"persistent-sorted-set\", \"persistent-sorted-set-p\",\n \"value-get\", \"value-nth\", \"value-put\", \"value-assoc\", \"value-remove\", \"value-dissoc\",\n \"value-conj\", \"value-count\", \"value-empty-p\", \"value-into\", \"value-equal-p\", \"value-hash\",\n \"value-compare\", \"value-meta\", \"value-with-meta\",\n \"cl-defstruct-persistent\", \"struct-validate\", \"struct-json-schema\", \"struct-to-json\", \"struct-from-json\",\n \"defprotocol\", \"extend-protocol\", \"defclass-protocol\", \"reify-protocol\",\n \"cl-defgeneric-value\", \"cl-defmethod-value\",\n \"state-cell\", \"state-cell-p\", \"cell-value\", \"cell-update!\", \"cell-reset!\", \"cell-watch\",\n \"delay\", \"force\", \"realized-p\", \"memoize\", \"lazy-seq\", \"lazy-map\", \"lazy-filter\", \"lazy-take\", \"lazy-range\",\n \"map-transducer\", \"filter-transducer\", \"take-transducer\", \"seq-transduce\",\n \"with-transient\", \"conj!\", \"assoc!\", \"dissoc!\",\n \"result-ok\", \"result-error\", \"result-ok-p\", \"result-error-p\", \"result-value\", \"result-error-value\", \"result-bind\",\n \"option-some\", \"option-none\", \"option-some-p\", \"option-none-p\", \"option-value\",\n \"data-symbol\", \"data-symbol-p\", \"data-symbol-name\", \"data-symbol-namespace\",\n ],\n \"eliscript-bind\": [\n \"let-bind\", \"let*-bind\", \"defun-bind\", \"lambda-bind\", \"pcase-value\", \"cond-predicate\",\n \"defun-case\", \"lambda-case\", \"let-const\", \"let*-const\",\n \"let-loop\", \"defun-tail\", \"lambda-tail\", \"recur\", \"trampoline\",\n \"thread-first\", \"thread-last\", \"thread-as\", \"thread-cond-first\", \"thread-cond-last\",\n \"thread-some-first\", \"thread-some-last\",\n \"fn-compose\", \"fn-partial\", \"fn-juxt\", \"fn-complement\",\n ],\n \"eliscript-async\": [\n \"defun-async\", \"lambda-async\", \"await\", \"future-p\", \"future-then\", \"future-cancel\",\n \"with-async-scope\", \"with-async-timeout\", \"with-async-bindings\", \"bind-async\",\n \"make-async-channel\", \"async-channel-p\", \"channel-put!\", \"channel-take!\", \"channel-close!\",\n \"engine-bind\", \"engine-revoke!\", \"engine-handle-p\", \"engine-call\", \"eliscript-async-wait\",\n ],\n \"eliscript-module\": [\n \"defmodule\", \"defun-lexical\", \"defvar-lexical\", \"defconst-lexical\",\n \"export-functions\", \"export-values\", \"import-functions\", \"import-values\",\n \"defmacro-checked\", \"macro-gensym\", \"macro-read-file\",\n ],\n \"eliscript-contract\": [\"eliscript-contract-check-value\"],\n \"eliscript-js\": [\n \"js-false\", \"js-null\", \"js-undefined\", \"js-false-p\", \"js-null-p\", \"js-undefined-p\", \"js-nullish-p\",\n \"js-import\", \"js-array\", \"js-object\", \"js-get\", \"js-get-raw\", \"js-put\", \"js-call\", \"js-call-raw\",\n \"js-new\", \"js-expr\", \"js-divide\", \"js-remainder\", \"js-length\", \"js-substring\",\n \"js-regexp\", \"js-regexp-p\", \"js-regexp-find\", \"js-regexp-matches\", \"js-regexp-seq\", \"js-regexp-replace\",\n ],\n \"eliscript-abi\": [\n \"with-abi-memory\", \"mem-size\", \"mem-grow\",\n \"mem-load-u8\", \"mem-load-u16\", \"mem-load-u32\", \"mem-load-f64\",\n \"mem-store-u8\", \"mem-store-u16\", \"mem-store-u32\", \"mem-store-f64\",\n \"word-add\", \"word-sub\", \"word-mul\", \"word-div\", \"word-and\", \"word-or\", \"word-xor\", \"word-shl\", \"word-shr\",\n ],\n};\n\nclass LexEnv {\n constructor(parent = null) {\n this.parent = parent;\n this.vars = new Map();\n this.constVars = new Set();\n this.fns = new Map();\n }\n hasVar(name) {\n if (this.vars.has(name)) return true;\n return this.parent ? this.parent.hasVar(name) : false;\n }\n getVar(name) {\n if (this.vars.has(name)) return this.vars.get(name);\n if (this.parent) return this.parent.getVar(name);\n return undefined;\n }\n setVar(name, val) {\n let cur = this;\n while (cur) {\n if (cur.vars.has(name)) {\n if (cur.constVars.has(name)) {\n signalError(\"eliscript-compile-error\", `ELI-C0010: cannot mutate immutable binding ${name}`);\n }\n cur.vars.set(name, val);\n return true;\n }\n cur = cur.parent;\n }\n return false;\n }\n getFn(name) {\n if (this.fns.has(name)) return this.fns.get(name);\n if (this.parent) return this.parent.getFn(name);\n return undefined;\n }\n}\n\nexport function createCompatSession() {\n const session = {\n values: new Map([[\"nil\", null], [\"t\", true]]),\n functions: new Map(),\n macros: new Map(),\n plists: new Map(),\n specialVars: new Set(),\n userDefinedFns: new Set(),\n activeLibs: new Set(),\n structSchemas: new Map(),\n protocols: new Map(),\n multimethods: new Map(),\n modules: new Map(),\n liveValueGetters: new Map(),\n engineSlots: new Map(),\n nextSlotId: 0,\n gensymCounter: 0,\n inAsyncContext: false,\n inTailContext: false,\n abiMemory: null,\n abiMaxPages: 256,\n };\n installKernelBuiltins(session);\n return session;\n}\n\nlet defaultSession = createCompatSession();\n\nexport function resetCompatState() {\n defaultSession = createCompatSession();\n}\n\nfunction activateExtensionLib(session, libName) {\n if (libName === \"eliscript\") {\n for (const sub of [\n \"eliscript-data\",\n \"eliscript-bind\",\n \"eliscript-async\",\n \"eliscript-module\",\n \"eliscript-contract\",\n ]) {\n activateExtensionLib(session, sub);\n }\n return;\n }\n const exports = EXTENSION_EXPORTS[libName];\n if (!exports) return;\n for (const s of exports) {\n if (session.userDefinedFns.has(s)) {\n signalError(\n \"eliscript-compile-error\",\n `ELI-M0001: extension ${libName} symbol ${s} conflicts with existing user definition`,\n );\n }\n }\n session.activeLibs.add(libName);\n installExtensionBuiltins(session, libName);\n}\n\nfunction formatElisp(fmt, args) {\n let idx = 0;\n return String(fmt).replace(/%[sdS]/gu, (m) => {\n const v = args[idx++];\n if (m === \"%d\") return String(Math.trunc(Number(v)));\n if (v === null) return \"nil\";\n if (v === true) return \"t\";\n if (isSym(v) || isKw(v)) return v.name;\n return String(v);\n });\n}\n\nfunction installKernelBuiltins(session) {\n const fns = session.functions;\n fns.set(\"+\", (...ns) => ns.reduce((a, b) => a + b, 0));\n fns.set(\"-\", (a, ...rest) => (rest.length === 0 ? -a : rest.reduce((x, y) => x - y, a)));\n fns.set(\"*\", (...ns) => ns.reduce((a, b) => a * b, 1));\n fns.set(\"/\", (first, ...rest) => {\n if (rest.length === 0) {\n if (first === 0) signalError(\"arith-error\", \"Division by zero\");\n return 1 / first;\n }\n let acc = first;\n let allInt = Number.isInteger(first);\n for (const d of rest) {\n if (d === 0) signalError(\"arith-error\", \"Division by zero\");\n allInt = allInt && Number.isInteger(d);\n acc = allInt ? Math.trunc(acc / d) : acc / d;\n }\n return acc;\n });\n fns.set(\"mod\", (a, b) => {\n if (b === 0) signalError(\"arith-error\", \"Division by zero\");\n return ((a % b) + b) % b;\n });\n fns.set(\"%\", (a, b) => {\n if (b === 0) signalError(\"arith-error\", \"Division by zero\");\n return Math.trunc(a % b);\n });\n fns.set(\"1+\", (x) => x + 1);\n fns.set(\"1-\", (x) => x - 1);\n fns.set(\"=\", (a, b) => (a === b ? true : null));\n fns.set(\"<\", (a, b) => (a < b ? true : null));\n fns.set(\">\", (a, b) => (a > b ? true : null));\n fns.set(\"<=\", (a, b) => (a <= b ? true : null));\n fns.set(\">=\", (a, b) => (a >= b ? true : null));\n fns.set(\"min\", (...ns) => Math.min(...ns));\n fns.set(\"max\", (...ns) => Math.max(...ns));\n fns.set(\"cl-evenp\", (x) => (x % 2 === 0 ? true : null));\n fns.set(\"cl-oddp\", (x) => (Math.abs(x % 2) === 1 ? true : null));\n fns.set(\"numberp\", (x) => (typeof x === \"number\" ? true : null));\n fns.set(\"integerp\", (x) => (Number.isInteger(x) ? true : null));\n fns.set(\"stringp\", (x) => (typeof x === \"string\" ? true : null));\n fns.set(\"symbolp\", (x) => (x === null || x === true || isSym(x) || isKw(x) ? true : null));\n fns.set(\"keywordp\", (x) => (isKw(x) ? true : null));\n fns.set(\"null\", (x) => (x === null ? true : null));\n fns.set(\"not\", (x) => (x === null ? true : null));\n fns.set(\"atom\", (x) => (x && x.kind === \"cons\" ? null : true));\n fns.set(\"eq\", (a, b) => {\n if (a === b) return true;\n if (isSym(a) && isSym(b)) return a.name === b.name ? true : null;\n if (isKw(a) && isKw(b)) return a.name === b.name ? true : null;\n return null;\n });\n fns.set(\"equal\", (a, b) => (valueEqual(a, b) ? true : null));\n fns.set(\"cons\", (a, b) => makeCons(a, b));\n fns.set(\"car\", (x) => (x && x.kind === \"cons\" ? x.car : null));\n fns.set(\"cdr\", (x) => (x && x.kind === \"cons\" ? x.cdr : null));\n fns.set(\"setcar\", (cell, v) => {\n cell.car = v;\n return v;\n });\n fns.set(\"setcdr\", (cell, v) => {\n cell.cdr = v;\n return v;\n });\n fns.set(\"list\", (...items) => arrayToConsList(items));\n fns.set(\"nreverse\", (lst) => arrayToConsList(consListToArray(lst).reverse()));\n fns.set(\"vector\", (...items) => makeNativeVector(items));\n fns.set(\"vectorp\", (x) => (x && x.kind === \"vector\" ? true : null));\n fns.set(\"aref\", (v, idx) => {\n if (typeof v === \"string\") return Array.from(v)[idx].codePointAt(0);\n return v.items[idx];\n });\n fns.set(\"aset\", (v, idx, val) => {\n v.items[idx] = val;\n return val;\n });\n fns.set(\"make-hash-table\", () => ({ kind: \"hash-table\", map: new Map() }));\n fns.set(\"hash-table-p\", (x) => (x && x.kind === \"hash-table\" ? true : null));\n fns.set(\"puthash\", (k, v, ht) => {\n const key = isKw(k) || isSym(k) ? k.name : k;\n ht.map.set(key, v);\n return v;\n });\n fns.set(\"gethash\", (k, ht, def = null) => {\n const key = isKw(k) || isSym(k) ? k.name : k;\n return ht.map.has(key) ? ht.map.get(key) : def;\n });\n fns.set(\"hash-table-count\", (ht) => ht.map.size);\n fns.set(\"length\", (x) => {\n if (x === null) return 0;\n if (typeof x === \"string\") return Array.from(x).length;\n if (x.kind === \"vector\") return x.items.length;\n if (x.kind === \"cons\") return consListToArray(x).length;\n return valueCount(x);\n });\n fns.set(\"substring\", (s, start, end) => {\n const chars = Array.from(s);\n return chars.slice(start, end ?? chars.length).join(\"\");\n });\n fns.set(\"format\", (fmt, ...args) => formatElisp(fmt, args));\n fns.set(\"funcall\", (fn, ...args) => invokeCallable(session, fn, args));\n fns.set(\"apply\", (fn, ...args) => {\n const last = consListToArray(args[args.length - 1]);\n const full = [...args.slice(0, -1), ...last];\n return invokeCallable(session, fn, full);\n });\n fns.set(\"mapcar\", (fn, seq) => {\n const items = extractSeqElements(seq);\n return arrayToConsList(items.map((x) => invokeCallable(session, fn, [x])));\n });\n fns.set(\"symbol-value\", (s) => {\n const name = isSym(s) ? s.name : String(s);\n if (session.liveValueGetters.has(name)) return session.liveValueGetters.get(name)();\n return session.values.get(name) ?? null;\n });\n fns.set(\"symbol-function\", (s) => {\n const name = isSym(s) ? s.name : String(s);\n return session.functions.get(name) ?? null;\n });\n fns.set(\"set\", (s, val) => {\n const name = isSym(s) ? s.name : String(s);\n session.values.set(name, val);\n return val;\n });\n fns.set(\"fset\", (s, fn) => {\n const name = isSym(s) ? s.name : String(s);\n session.functions.set(name, fn);\n return fn;\n });\n fns.set(\"put\", (s, prop, val) => {\n const name = isSym(s) ? s.name : String(s);\n if (!session.plists.has(name)) session.plists.set(name, new Map());\n const k = isKw(prop) || isSym(prop) ? prop.name : String(prop);\n session.plists.get(name).set(k, val);\n return val;\n });\n fns.set(\"get\", (s, prop) => {\n const name = isSym(s) ? s.name : String(s);\n const k = isKw(prop) || isSym(prop) ? prop.name : String(prop);\n return session.plists.get(name)?.get(k) ?? null;\n });\n fns.set(\"string-match\", (pat, str) => {\n const jsPat = String(pat).replace(/\\\\([()|])/gu, \"$1\");\n const m = new RegExp(jsPat, \"u\").exec(str);\n session.lastMatchData = m;\n return m ? m.index : null;\n });\n fns.set(\"match-string\", (num) => {\n return session.lastMatchData?.[num] ?? null;\n });\n}\n\nfunction installExtensionBuiltins(session, libName) {\n const fns = session.functions;\n if (libName === \"eliscript-data\") {\n session.values.set(\"option-none\", OPTION_NONE);\n fns.set(\"persistent-list\", (...items) => makePersistentList(items));\n fns.set(\"persistent-list-p\", (x) => (x?.kind === \"persistent-list\" ? true : null));\n fns.set(\"persistent-vector\", (...items) => makePersistentVector(items));\n fns.set(\"persistent-vector-p\", (x) => (x?.kind === \"persistent-vector\" ? true : null));\n fns.set(\"persistent-map\", (...kvs) => makePersistentMap(kvs));\n fns.set(\"persistent-map-p\", (x) => (x?.kind === \"persistent-map\" ? true : null));\n fns.set(\"persistent-set\", (...items) => makePersistentSet(items));\n fns.set(\"persistent-set-p\", (x) => (x?.kind === \"persistent-set\" ? true : null));\n fns.set(\"persistent-queue\", (...items) => makePersistentQueue(items));\n fns.set(\"persistent-queue-p\", (x) => (x?.kind === \"persistent-queue\" ? true : null));\n fns.set(\"persistent-sorted-map\", (...args) => makePersistentSortedMap(args));\n fns.set(\"persistent-sorted-map-p\", (x) => (x?.kind === \"persistent-sorted-map\" ? true : null));\n fns.set(\"persistent-sorted-set\", (...args) => makePersistentSortedSet(args));\n fns.set(\"persistent-sorted-set-p\", (x) => (x?.kind === \"persistent-sorted-set\" ? true : null));\n fns.set(\"value-get\", (c, k, nf = null) => valueGet(c, k, nf));\n fns.set(\"value-nth\", (c, idx, nf = null) => {\n const el = extractSeqElements(c);\n return idx >= 0 && idx < el.length ? el[idx] : nf;\n });\n fns.set(\"value-put\", (c, k, v) => {\n if (c?.kind === \"persistent-map\") {\n return { ...c, entries: assocEntries(c.entries, k, v) };\n }\n if (c?.kind === \"persistent-sorted-map\") {\n const norm = normalizeCmpFn(c.comparator);\n const entries = assocEntries(c.entries, k, v).sort((a, b) => norm(a[0], b[0]));\n return { ...c, entries };\n }\n throw new Error(\"value-put unsupported collection\");\n });\n fns.set(\"value-assoc\", fns.get(\"value-put\"));\n fns.set(\"value-remove\", (c, k) => {\n if (c?.kind === \"persistent-map\" || c?.kind === \"persistent-sorted-map\") {\n return { ...c, entries: dissocEntries(c.entries, k) };\n }\n throw new Error(\"value-remove unsupported collection\");\n });\n fns.set(\"value-dissoc\", fns.get(\"value-remove\"));\n fns.set(\"value-conj\", (c, ...items) => {\n let cur = c;\n for (const it of items) {\n if (cur.kind === \"persistent-list\") cur = { ...cur, items: [it, ...cur.items] };\n else if (cur.kind === \"persistent-vector\" || cur.kind === \"persistent-queue\") {\n cur = { ...cur, items: [...cur.items, it] };\n } else if (cur.kind === \"persistent-set\") {\n if (!cur.items.some((x) => valueEqual(x, it))) {\n cur = { ...cur, items: [...cur.items, it] };\n }\n }\n }\n return cur;\n });\n fns.set(\"value-count\", (c) => valueCount(c));\n fns.set(\"value-empty-p\", (c) => (valueCount(c) === 0 ? true : null));\n fns.set(\"value-equal-p\", (a, b) => (valueEqual(a, b) ? true : null));\n fns.set(\"value-compare\", (a, b) => valueCompare(a, b));\n fns.set(\"value-meta\", (x) => x?.meta ?? null);\n fns.set(\"value-with-meta\", (x, m) => ({ ...x, meta: m }));\n fns.set(\"seq-length\", (s) => valueCount(s));\n fns.set(\"seq-elt\", (s, idx) => extractSeqElements(s)[idx] ?? null);\n fns.set(\"seq-map\", (fn, s) =>\n arrayToConsList(extractSeqElements(s).map((x) => invokeCallable(session, fn, [x]))),\n );\n fns.set(\"seq-filter\", (pred, s) =>\n arrayToConsList(\n extractSeqElements(s).filter((x) => isTruthy(invokeCallable(session, pred, [x]))),\n ),\n );\n fns.set(\"seq-into\", (s, targetType) => {\n const elems = extractSeqElements(s);\n const tname = isSym(targetType) ? targetType.name : String(targetType);\n if (tname === \"persistent-vector-p\") return true;\n if (tname === \"persistent-vector\") return makePersistentVector(elems);\n if (tname === \"persistent-list\") return makePersistentList(elems);\n if (tname === \"list\") return arrayToConsList(elems);\n if (tname === \"vector\") return makeNativeVector(elems);\n return arrayToConsList(elems);\n });\n fns.set(\"map-elt\", (m, k, def = null) => valueGet(m, k, def));\n fns.set(\"map-contains-key\", (m, k) => (valueContains(m, k) ? true : null));\n fns.set(\"map-keys\", (m) => arrayToConsList(m.entries.map(([k]) => k)));\n fns.set(\"map-values\", (m) => arrayToConsList(m.entries.map(([, v]) => v)));\n fns.set(\"result-ok\", (v) => ({ kind: \"result\", ok: true, value: v }));\n fns.set(\"result-error\", (e) => ({ kind: \"result\", ok: false, value: e }));\n fns.set(\"result-ok-p\", (x) => (x?.kind === \"result\" && x.ok ? true : null));\n fns.set(\"result-error-p\", (x) => (x?.kind === \"result\" && !x.ok ? true : null));\n fns.set(\"result-value\", (x) => x.value);\n fns.set(\"result-error-value\", (x) => x.value);\n fns.set(\"option-some\", (v) => ({ kind: \"option\", some: true, value: v }));\n fns.set(\"option-some-p\", (x) => (x?.kind === \"option\" && x.some ? true : null));\n fns.set(\"option-none-p\", (x) => (x?.kind === \"option\" && !x.some ? true : null));\n fns.set(\"option-value\", (x) => {\n if (!x || x.kind !== \"option\" || !x.some) throw new Error(\"option-value on option-none\");\n return x.value;\n });\n fns.set(\"state-cell\", (init, ...opts) => {\n let validator = null;\n for (let i = 0; i < opts.length; i += 2) {\n if (isKw(opts[i], \":validator\")) validator = opts[i + 1];\n }\n if (validator && !isTruthy(invokeCallable(session, validator, [init]))) {\n throw new Error(\"state-cell validator rejected initial value\");\n }\n return { kind: \"state-cell\", val: init, validator, watches: [] };\n });\n fns.set(\"cell-value\", (c) => c.val);\n fns.set(\"cell-reset!\", (c, nv) => {\n if (c.validator && !isTruthy(invokeCallable(session, c.validator, [nv]))) {\n throw new Error(\"state-cell validator rejected new value\");\n }\n const old = c.val;\n c.val = nv;\n for (const [k, cb] of c.watches) {\n invokeCallable(session, cb, [k, c, old, nv]);\n }\n return nv;\n });\n fns.set(\"cell-update!\", (c, fn, ...args) => {\n const next = invokeCallable(session, fn, [c.val, ...args]);\n return fns.get(\"cell-reset!\")(c, next);\n });\n fns.set(\"cell-watch\", (c, k, cb) => {\n c.watches.push([k, cb]);\n return c;\n });\n fns.set(\"realized-p\", (d) => (d?.kind === \"delay\" && d.realized ? true : null));\n fns.set(\"force\", (d) => {\n if (d?.kind === \"delay\") {\n if (!d.realized) {\n d.value = d.thunk();\n d.realized = true;\n }\n return d.value;\n }\n return d;\n });\n fns.set(\"lazy-range\", (start = 0, end = null, step = 1) => {\n const makeStep = (cur) => ({\n kind: \"lazy-seq\",\n step: () => {\n if (end !== null && (step > 0 ? cur >= end : cur <= end)) return null;\n return makeCons(cur, makeStep(cur + step));\n },\n });\n return makeStep(start);\n });\n fns.set(\"lazy-map\", (fn, seq) => {\n const makeStep = (s) => ({\n kind: \"lazy-seq\",\n step: () => {\n const st = s?.kind === \"lazy-seq\" ? s.step() : s;\n if (!st) return null;\n return makeCons(invokeCallable(session, fn, [st.car]), makeStep(st.cdr));\n },\n });\n return makeStep(seq);\n });\n fns.set(\"lazy-filter\", (pred, seq) => {\n const makeStep = (s) => ({\n kind: \"lazy-seq\",\n step: () => {\n let cur = s;\n while (cur) {\n const st = cur?.kind === \"lazy-seq\" ? cur.step() : cur;\n if (!st) return null;\n if (isTruthy(invokeCallable(session, pred, [st.car]))) {\n return makeCons(st.car, makeStep(st.cdr));\n }\n cur = st.cdr;\n }\n return null;\n },\n });\n return makeStep(seq);\n });\n fns.set(\"lazy-take\", (n, seq) => {\n const makeStep = (rem, s) => ({\n kind: \"lazy-seq\",\n step: () => {\n if (rem <= 0) return null;\n const st = s?.kind === \"lazy-seq\" ? s.step() : s;\n if (!st) return null;\n return makeCons(st.car, makeStep(rem - 1, st.cdr));\n },\n });\n return makeStep(n, seq);\n });\n fns.set(\"map-transducer\", (fn) => (rf) => (acc, input) =>\n invokeCallable(session, rf, [acc, invokeCallable(session, fn, [input])]),\n );\n fns.set(\"filter-transducer\", (pred) => (rf) => (acc, input) =>\n isTruthy(invokeCallable(session, pred, [input]))\n ? invokeCallable(session, rf, [acc, input])\n : acc,\n );\n fns.set(\"seq-transduce\", (xform, f, init, coll) => {\n const rf = invokeCallable(session, xform, [f]);\n let acc = init;\n for (const item of extractSeqElements(coll)) {\n acc = invokeCallable(session, rf, [acc, item]);\n }\n return acc;\n });\n fns.set(\"conj!\", (builder, ...items) => {\n if (!builder || builder.kind !== \"transient\" || !builder.active) {\n throw new Error(\"conj! called on expired or sealed transient builder\");\n }\n builder.items.push(...items);\n return builder;\n });\n fns.set(\"struct-validate\", (snameSym, inst) => {\n const sname = isSym(snameSym) ? snameSym.name : String(snameSym);\n const schema = session.structSchemas.get(sname);\n if (!schema) throw new Error(`Unknown struct ${sname}`);\n for (const f of schema.fields) {\n const val = valueGet(inst, kw(f.name));\n validateStructField(sname, f, val);\n }\n return true;\n });\n fns.set(\"struct-json-schema\", (snameSym) => {\n const sname = isSym(snameSym) ? snameSym.name : String(snameSym);\n const schema = session.structSchemas.get(sname);\n if (!schema) throw new Error(`Unknown struct ${sname}`);\n return makePersistentMap([\n kw(\":type\"), \"object\",\n kw(\":title\"), sname,\n ]);\n });\n fns.set(\"struct-to-json\", (snameSym, inst) => {\n fns.get(\"struct-validate\")(snameSym, inst);\n return JSON.stringify(serializeCompatValue(inst));\n });\n fns.set(\"struct-from-json\", (snameSym, jsonStr) => {\n const sname = isSym(snameSym) ? snameSym.name : String(snameSym);\n const raw = JSON.parse(jsonStr);\n const kvs = [];\n for (const [k, v] of Object.entries(raw)) {\n kvs.push(kw(`:${k}`), jsonValueToPersistent(v));\n }\n return session.functions.get(`make-${sname}`)(...kvs);\n });\n }\n if (libName === \"eliscript-bind\") {\n fns.set(\"fn-compose\", (...fnList) => (...args) => {\n const rev = [...fnList].reverse();\n let res = invokeCallable(session, rev[0], args);\n for (let i = 1; i < rev.length; i += 1) {\n res = invokeCallable(session, rev[i], [res]);\n }\n return res;\n });\n fns.set(\"fn-partial\", (fn, ...bound) => (...more) =>\n invokeCallable(session, fn, [...bound, ...more]),\n );\n fns.set(\"fn-juxt\", (...fnList) => (...args) =>\n arrayToConsList(fnList.map((f) => invokeCallable(session, f, args))),\n );\n fns.set(\"fn-complement\", (pred) => (...args) =>\n isTruthy(invokeCallable(session, pred, args)) ? null : true,\n );\n }\n if (libName === \"eliscript-async\") {\n fns.set(\"future-p\", (x) => (x?.kind === \"future\" ? true : null));\n fns.set(\"eliscript-async-wait\", (fut) => {\n if (!fut || fut.kind !== \"future\") {\n signalError(\"wrong-type-argument\", \"future-p\", fut);\n }\n if (fut.state === \"rejected\") {\n throw fut.error;\n }\n return fut.value;\n });\n fns.set(\"await\", (fut) => {\n if (!session.inAsyncContext) {\n signalError(\"eliscript-compile-error\", \"ELI-A0001: await outside async function\");\n }\n return fns.get(\"eliscript-async-wait\")(fut);\n });\n fns.set(\"make-async-channel\", (cap = 0) => ({\n kind: \"async-channel\",\n capacity: Math.max(1, cap),\n buffer: [],\n closed: false,\n }));\n fns.set(\"channel-put!\", (ch, val) => {\n if (ch.closed) {\n return {\n kind: \"future\",\n state: \"rejected\",\n error: new EliscriptSignal(\"eliscript-channel-closed\", [\"Channel closed\"]),\n };\n }\n ch.buffer.push(val);\n return { kind: \"future\", state: \"fulfilled\", value: true };\n });\n fns.set(\"channel-take!\", (ch) => {\n if (ch.buffer.length > 0) {\n const v = ch.buffer.shift();\n return { kind: \"future\", state: \"fulfilled\", value: { kind: \"option\", some: true, value: v } };\n }\n return { kind: \"future\", state: \"fulfilled\", value: OPTION_NONE };\n });\n fns.set(\"channel-close!\", (ch) => {\n ch.closed = true;\n return null;\n });\n fns.set(\"engine-handle-p\", (x) => (x?.kind === \"engine-handle\" ? true : null));\n fns.set(\"engine-bind\", (fn, scope = null, owner = sym(\"local\")) => {\n const slot = ++session.nextSlotId;\n const ownerName = isSym(owner) ? owner.name : String(owner);\n const handle = { kind: \"engine-handle\", owner: ownerName, generation: 1, slot };\n session.engineSlots.set(slot, { owner: ownerName, generation: 1, active: true, fn });\n if (scope && scope.kind === \"async-scope\") {\n scope.handles.push(handle);\n }\n return handle;\n });\n fns.set(\"engine-revoke!\", (h) => {\n const entry = session.engineSlots.get(h.slot);\n if (entry) {\n entry.active = false;\n entry.generation += 1;\n }\n return true;\n });\n fns.set(\"engine-call\", (engine, target, ...args) => {\n const engName = isSym(engine) ? engine.name : String(engine);\n if (target?.kind === \"engine-handle\") {\n const entry = session.engineSlots.get(target.slot);\n if (\n !entry ||\n !entry.active ||\n entry.owner !== target.owner ||\n target.owner !== engName ||\n entry.generation !== target.generation\n ) {\n return {\n kind: \"future\",\n state: \"rejected\",\n error: new EliscriptSignal(\"eliscript-engine-handle-error\", [\n \"Revoked or invalid engine handle\",\n ]),\n };\n }\n try {\n const val = invokeCallable(session, entry.fn, args);\n return { kind: \"future\", state: \"fulfilled\", value: val };\n } catch (err) {\n return { kind: \"future\", state: \"rejected\", error: err };\n }\n }\n return {\n kind: \"future\",\n state: \"rejected\",\n error: new EliscriptSignal(\"eliscript-engine-handle-error\", [\"Invalid target\"]),\n };\n });\n }\n if (libName === \"eliscript-js\") {\n session.values.set(\"js-false\", JS_FALSE);\n session.values.set(\"js-null\", JS_NULL);\n session.values.set(\"js-undefined\", JS_UNDEFINED);\n fns.set(\"js-false-p\", (x) => (x === JS_FALSE ? true : null));\n fns.set(\"js-null-p\", (x) => (x === JS_NULL ? true : null));\n fns.set(\"js-undefined-p\", (x) => (x === JS_UNDEFINED ? true : null));\n fns.set(\"js-nullish-p\", (x) => (x === JS_NULL || x === JS_UNDEFINED ? true : null));\n fns.set(\"js-object\", (...kvs) => {\n const props = new Map();\n for (let i = 0; i < kvs.length; i += 2) {\n const k = isKw(kvs[i]) ? kvs[i].name.slice(1) : String(kvs[i]);\n props.set(k, kvs[i + 1]);\n }\n return { kind: \"js-object\", props };\n });\n fns.set(\"js-get-raw\", (obj, key) => {\n const k = isKw(key) ? key.name.slice(1) : String(key);\n if (obj?.kind === \"js-object\") {\n return obj.props.has(k) ? obj.props.get(k) : JS_UNDEFINED;\n }\n return JS_UNDEFINED;\n });\n fns.set(\"js-get\", (obj, key) => {\n const raw = fns.get(\"js-get-raw\")(obj, key);\n if (raw === JS_FALSE || raw === JS_NULL || raw === JS_UNDEFINED) return null;\n return raw;\n });\n fns.set(\"js-divide\", (a, b) => a / b);\n fns.set(\"js-remainder\", (a, b) => a % b);\n fns.set(\"js-length\", (s) => String(s).length);\n fns.set(\"js-substring\", (s, start, end) => String(s).slice(start, end));\n fns.set(\"js-regexp\", (pat, flags = \"\") => new RegExp(pat, flags));\n fns.set(\"js-regexp-find\", (rx, str) => {\n const m = rx.exec(str);\n if (!m) return null;\n return makePersistentMap([\n kw(\":match\"), m[0],\n kw(\":start\"), m.index,\n kw(\":end\"), m.index + m[0].length,\n ]);\n });\n }\n if (libName === \"eliscript-abi\") {\n fns.set(\"mem-store-u32\", (offset, val) => {\n if (!session.abiMemory || offset < 0 || offset + 4 > session.abiMemory.byteLength) {\n throw new Error(\"ABI linear memory out of bounds\");\n }\n new DataView(session.abiMemory).setUint32(offset, val >>> 0, true);\n return null;\n });\n fns.set(\"mem-load-u32\", (offset) => {\n if (!session.abiMemory || offset < 0 || offset + 4 > session.abiMemory.byteLength) {\n throw new Error(\"ABI linear memory out of bounds\");\n }\n return new DataView(session.abiMemory).getUint32(offset, true);\n });\n fns.set(\"word-add\", (a, b) => ((a >>> 0) + (b >>> 0)) >>> 0);\n fns.set(\"word-sub\", (a, b) => ((a >>> 0) - (b >>> 0)) >>> 0);\n fns.set(\"word-mul\", (a, b) => Math.imul(a >>> 0, b >>> 0) >>> 0);\n fns.set(\"word-div\", (a, b) => {\n if ((b >>> 0) === 0) signalError(\"arith-error\", \"word-div by zero\");\n return Math.trunc((a >>> 0) / (b >>> 0)) >>> 0;\n });\n }\n}\n\nfunction jsonValueToPersistent(v) {\n if (Array.isArray(v)) return makePersistentVector(v.map(jsonValueToPersistent));\n if (v && typeof v === \"object\") {\n const kvs = [];\n for (const [k, val] of Object.entries(v)) {\n kvs.push(kw(`:${k}`), jsonValueToPersistent(val));\n }\n return makePersistentMap(kvs);\n }\n return v;\n}\n\nfunction validateStructField(sname, fspec, val) {\n if (fspec.type === \"string\" && typeof val !== \"string\") {\n throw new Error(`Schema type mismatch on ${sname}.${fspec.name}: expected string`);\n }\n if (fspec.type === \"integer\" && !Number.isInteger(val)) {\n throw new Error(`Schema type mismatch on ${sname}.${fspec.name}: expected integer`);\n }\n if (fspec.min !== null && typeof val === \"number\" && val < fspec.min) {\n throw new Error(`Schema min violation on ${sname}.${fspec.name}: ${val} < ${fspec.min}`);\n }\n if (fspec.max !== null && typeof val === \"number\" && val > fspec.max) {\n throw new Error(`Schema max violation on ${sname}.${fspec.name}: ${val} > ${fspec.max}`);\n }\n}\n\nfunction invokeCallable(session, fn, args) {\n if (typeof fn === \"function\") return fn(...args);\n if (isSym(fn)) {\n const target = session.functions.get(fn.name);\n if (!target) signalError(\"void-function\", fn.name);\n return target(...args);\n }\n signalError(\"void-function\", String(fn));\n}\n\n// ============================================================================\n// 5. Destructuring, Backquote, Static Checks & Form Evaluation\n// ============================================================================\n\nfunction collectDestructureVars(pat, seen = new Set()) {\n if (pat === null || isKw(pat, \":none\") || isSym(pat, \"_\") || isKw(pat)) return seen;\n if (isSym(pat)) {\n if (seen.has(pat.name)) {\n signalError(\"eliscript-compile-error\", `ELI-B0010: duplicate variable ${pat.name} in pattern`);\n }\n seen.add(pat.name);\n return seen;\n }\n if (pat.kind === \"vector\") {\n for (let i = 0; i < pat.items.length; i += 1) {\n if (isSym(pat.items[i], \"&rest\")) {\n collectDestructureVars(pat.items[i + 1], seen);\n break;\n }\n collectDestructureVars(pat.items[i], seen);\n }\n return seen;\n }\n if (pat.kind === \"cons\") {\n const arr = consListToArray(pat);\n const head = arr[0];\n if (isKw(head, \":list\")) {\n for (let i = 1; i < arr.length; i += 1) {\n if (isSym(arr[i], \"&rest\")) {\n collectDestructureVars(arr[i + 1], seen);\n break;\n }\n collectDestructureVars(arr[i], seen);\n }\n } else if (isKw(head, \":map\")) {\n for (const entry of arr.slice(1)) {\n const pair = consListToArray(entry);\n const sub = pair[1];\n if (sub?.kind === \"cons\" && isSym(sub.car, \"default\")) {\n collectDestructureVars(consListToArray(sub)[1], seen);\n } else {\n collectDestructureVars(sub, seen);\n }\n }\n } else if (isKw(head, \":record\")) {\n for (const entry of arr.slice(2)) {\n const pair = consListToArray(entry);\n collectDestructureVars(pair[1], seen);\n }\n } else if (isKw(head, \":ok\") || isKw(head, \":error\") || isKw(head, \":some\")) {\n collectDestructureVars(arr[1], seen);\n }\n }\n return seen;\n}\n\nfunction matchPattern(session, pat, val, env) {\n if (isSym(pat, \"_\")) return;\n if (isKw(pat, \":none\")) {\n if (val !== OPTION_NONE) throw new Error(\"Destructuring expected option-none\");\n return;\n }\n if (isSym(pat)) {\n env.vars.set(pat.name, val);\n return;\n }\n if (pat.kind === \"vector\") {\n if (!val || (val.kind !== \"vector\" && val.kind !== \"persistent-vector\")) {\n throw new Error(\"Destructuring vector pattern requires a vector or persistent-vector\");\n }\n const items = pat.items;\n const restIdx = items.findIndex((x) => isSym(x, \"&rest\"));\n if (restIdx !== -1) {\n if (val.items.length < restIdx) {\n throw new Error(\"Destructuring vector length mismatch\");\n }\n for (let i = 0; i < restIdx; i += 1) {\n matchPattern(session, items[i], val.items[i], env);\n }\n const tailItems = val.items.slice(restIdx);\n const tailVal =\n val.kind === \"persistent-vector\"\n ? makePersistentVector(tailItems)\n : makeNativeVector(tailItems);\n matchPattern(session, items[restIdx + 1], tailVal, env);\n } else {\n if (val.items.length !== items.length) {\n throw new Error(\"Destructuring vector length mismatch\");\n }\n for (let i = 0; i < items.length; i += 1) {\n matchPattern(session, items[i], val.items[i], env);\n }\n }\n return;\n }\n if (pat.kind === \"cons\") {\n const arr = consListToArray(pat);\n const head = arr[0];\n if (isKw(head, \":list\")) {\n if (val !== null && val?.kind !== \"cons\" && val?.kind !== \"persistent-list\") {\n throw new Error(\"Destructuring :list requires list or persistent-list\");\n }\n const elems = val === null ? [] : val.kind === \"persistent-list\" ? val.items : consListToArray(val);\n const subPats = arr.slice(1);\n const restIdx = subPats.findIndex((x) => isSym(x, \"&rest\"));\n if (restIdx !== -1) {\n if (elems.length < restIdx) throw new Error(\"Destructuring :list length mismatch\");\n for (let i = 0; i < restIdx; i += 1) {\n matchPattern(session, subPats[i], elems[i], env);\n }\n const tailElems = elems.slice(restIdx);\n const tailVal =\n val?.kind === \"persistent-list\"\n ? makePersistentList(tailElems)\n : arrayToConsList(tailElems);\n matchPattern(session, subPats[restIdx + 1], tailVal, env);\n } else {\n if (elems.length !== subPats.length) throw new Error(\"Destructuring :list length mismatch\");\n for (let i = 0; i < subPats.length; i += 1) {\n matchPattern(session, subPats[i], elems[i], env);\n }\n }\n return;\n }\n if (isKw(head, \":map\")) {\n for (const entry of arr.slice(1)) {\n const [k, sub] = consListToArray(entry);\n if (sub?.kind === \"cons\" && isSym(sub.car, \"default\")) {\n const [, targetPat, defExpr] = consListToArray(sub);\n if (valueContains(val, k)) {\n matchPattern(session, targetPat, valueGet(val, k), env);\n } else {\n matchPattern(session, targetPat, evalForm(session, defExpr, env), env);\n }\n } else {\n if (!valueContains(val, k)) {\n throw new Error(`Destructuring :map missing required key ${k.name ?? k}`);\n }\n matchPattern(session, sub, valueGet(val, k), env);\n }\n }\n return;\n }\n if (isKw(head, \":record\")) {\n const recName = arr[1].name;\n if (val?.kind !== \"persistent-record\" || val.typeName !== recName) {\n throw new Error(`Destructuring :record expected ${recName}`);\n }\n for (const entry of arr.slice(2)) {\n const [k, sub] = consListToArray(entry);\n matchPattern(session, sub, valueGet(val, k), env);\n }\n return;\n }\n if (isKw(head, \":ok\")) {\n if (val?.kind !== \"result\" || !val.ok) throw new Error(\"Destructuring :ok mismatch\");\n matchPattern(session, arr[1], val.value, env);\n return;\n }\n if (isKw(head, \":some\")) {\n if (val?.kind !== \"option\" || !val.some) throw new Error(\"Destructuring :some mismatch\");\n matchPattern(session, arr[1], val.value, env);\n return;\n }\n }\n if (!valueEqual(pat, val)) throw new Error(\"Destructuring literal mismatch\");\n}\n\nfunction evalBackquote(session, form, env) {\n if (!form || form.kind !== \"cons\") return form;\n const arr = consListToArray(form);\n if (isSym(arr[0], \"unquote\")) return evalForm(session, arr[1], env);\n const out = [];\n for (const item of arr) {\n if (item && item.kind === \"cons\" && isSym(item.car, \"unquote-splicing\")) {\n const spliced = consListToArray(evalForm(session, consListToArray(item)[1], env));\n out.push(...spliced);\n } else {\n out.push(evalBackquote(session, item, env));\n }\n }\n return arrayToConsList(out);\n}\n\nfunction extractDeclareAndBody(rawBody) {\n let idx = 0;\n const eliProps = new Map();\n while (idx < rawBody.length) {\n const f = rawBody[idx];\n if (typeof f === \"string\" && idx + 1 < rawBody.length) {\n idx += 1;\n continue;\n }\n if (f?.kind === \"cons\" && isSym(f.car, \"declare\")) {\n const specs = consListToArray(f).slice(1);\n for (const sp of specs) {\n const spArr = consListToArray(sp);\n if (isSym(spArr[0], \"eliscript\")) {\n for (let i = 1; i < spArr.length; i += 2) {\n eliProps.set(spArr[i].name, spArr[i + 1]);\n }\n }\n }\n idx += 1;\n continue;\n }\n break;\n }\n return { eliProps, body: rawBody.slice(idx) };\n}\n\nfunction scanTreeForHead(forms, forbiddenHeads, stopAtSyncLambda = false) {\n for (const f of forms) {\n if (!f || f.kind !== \"cons\") continue;\n const arr = consListToArray(f);\n const head = arr[0];\n if (isSym(head, \"quote\")) continue;\n if (isSym(head) && forbiddenHeads.has(head.name)) {\n return head.name;\n }\n if (stopAtSyncLambda && (isSym(head, \"lambda\") || isSym(head, \"defun\"))) {\n continue;\n }\n const hit = scanTreeForHead(arr.slice(1), forbiddenHeads, stopAtSyncLambda);\n if (hit) return hit;\n }\n return null;\n}\n\nfunction verifyRecurTailPosition(forms, tailAllowed) {\n for (let i = 0; i < forms.length; i += 1) {\n const f = forms[i];\n const isLast = tailAllowed && i === forms.length - 1;\n if (!f || f.kind !== \"cons\") continue;\n const arr = consListToArray(f);\n const head = arr[0];\n if (isSym(head, \"quote\")) continue;\n if (isSym(head, \"recur\")) {\n if (!isLast) {\n signalError(\"eliscript-compile-error\", \"ELI-R0001: recur must be in tail position\");\n }\n verifyRecurTailPosition(arr.slice(1), false);\n } else if (isSym(head, \"if\")) {\n verifyRecurTailPosition([arr[1]], false);\n verifyRecurTailPosition([arr[2]], isLast);\n verifyRecurTailPosition(arr.slice(3), isLast);\n } else if (isSym(head, \"progn\")) {\n verifyRecurTailPosition(arr.slice(1), isLast);\n } else if (isSym(head, \"let\") || isSym(head, \"let*\") || isSym(head, \"let-const\")) {\n verifyRecurTailPosition(arr.slice(2), isLast);\n } else if (isSym(head, \"let-loop\") || isSym(head, \"defun-tail\") || isSym(head, \"lambda-tail\")) {\n continue;\n } else {\n verifyRecurTailPosition(arr.slice(1), false);\n }\n }\n}\n\nfunction validateFunctionDeclarations(kind, name, eliProps, body) {\n if (kind === \"defun\") {\n if (eliProps.get(\":async\") === true) {\n signalError(\"eliscript-compile-error\", `ELI-D0001: ordinary defun ${name} cannot declare :async t`);\n }\n if (eliProps.get(\":destructure\") === true) {\n signalError(\"eliscript-compile-error\", `ELI-D0002: ordinary defun ${name} cannot declare :destructure t`);\n }\n const syncAwait = scanTreeForHead(body, new Set([\"await\"]));\n if (syncAwait) {\n signalError(\"eliscript-compile-error\", `ELI-A0001: await is forbidden in sync defun ${name}`);\n }\n }\n if (eliProps.get(\":portable\") === true) {\n const bad = scanTreeForHead(body, new Set([\"current-buffer\", \"set-buffer\", \"with-current-buffer\"]));\n if (bad) {\n signalError(\"eliscript-compile-error\", `ELI-C0002: non-portable operator ${bad} in ${name}`);\n }\n }\n if (eliProps.has(\":abi\")) {\n const abi = eliProps.get(\":abi\");\n if (isKw(abi, \":numeric-f64\")) {\n const bad = scanTreeForHead(body, new Set([\"list\", \"cons\", \"vector\", \"persistent-list\"]));\n if (bad) {\n signalError(\"eliscript-compile-error\", `ELI-B0001: heap allocation ${bad} forbidden in :numeric-f64 ${name}`);\n }\n }\n }\n}\n\nfunction evalSeq(session, forms, env) {\n let last = null;\n for (const f of forms) {\n last = evalForm(session, f, env);\n }\n return last;\n}\n\nfunction evalForm(session, form, env) {\n if (form && form.kind === \"float-lit\") return form.value;\n if (form === null || form === true || typeof form === \"number\" || typeof form === \"string\") {\n return form;\n }\n if (isKw(form) || form.kind === \"vector\") return form;\n if (isSym(form)) {\n if (session.specialVars.has(form.name)) {\n return session.values.get(form.name) ?? null;\n }\n if (env.hasVar(form.name)) return env.getVar(form.name);\n if (session.liveValueGetters.has(form.name)) return session.liveValueGetters.get(form.name)();\n if (session.values.has(form.name)) return session.values.get(form.name);\n signalError(\"void-variable\", form.name);\n }\n if (form.kind !== \"cons\") return form;\n\n const arr = consListToArray(form);\n const head = arr[0];\n if (!isSym(head)) {\n signalError(\"void-function\", String(head));\n }\n const hname = head.name;\n\n // Macro expansion check\n if (session.macros.has(hname)) {\n const macroFn = session.macros.get(hname);\n const expanded = macroFn(...arr.slice(1));\n return evalForm(session, expanded, env);\n }\n\n if (hname === \"/\") {\n const rawArgs = arr.slice(1);\n const hasFloatLit = rawArgs.some((a) => a && a.kind === \"float-lit\");\n const nums = rawArgs.map((a) => evalForm(session, a, env));\n if (nums.length === 1) {\n if (nums[0] === 0) signalError(\"arith-error\", \"Division by zero\");\n return 1 / nums[0];\n }\n let acc = nums[0];\n let allInt = !hasFloatLit && Number.isInteger(nums[0]);\n for (const d of nums.slice(1)) {\n if (d === 0) signalError(\"arith-error\", \"Division by zero\");\n allInt = allInt && Number.isInteger(d);\n acc = allInt ? Math.trunc(acc / d) : acc / d;\n }\n return acc;\n }\n if (hname === \"quote\") return arr[1] ?? null;\n if (hname === \"backquote\") return evalBackquote(session, arr[1], env);\n if (hname === \"function\") {\n const target = arr[1];\n if (isSym(target)) {\n return (...callArgs) => {\n const fn = env.getFn(target.name) ?? session.functions.get(target.name);\n if (!fn) signalError(\"void-function\", target.name);\n return fn(...callArgs);\n };\n }\n return evalForm(session, target, env);\n }\n if (hname === \"progn\") return evalSeq(session, arr.slice(1), env);\n if (hname === \"prog1\") {\n const firstVal = evalForm(session, arr[1], env);\n evalSeq(session, arr.slice(2), env);\n return firstVal;\n }\n if (hname === \"if\") {\n const cond = evalForm(session, arr[1], env);\n if (isTruthy(cond)) return evalForm(session, arr[2], env);\n return evalSeq(session, arr.slice(3), env);\n }\n if (hname === \"when\") {\n return isTruthy(evalForm(session, arr[1], env)) ? evalSeq(session, arr.slice(2), env) : null;\n }\n if (hname === \"unless\") {\n return !isTruthy(evalForm(session, arr[1], env)) ? evalSeq(session, arr.slice(2), env) : null;\n }\n if (hname === \"and\") {\n let last = true;\n for (const sub of arr.slice(1)) {\n last = evalForm(session, sub, env);\n if (!isTruthy(last)) return null;\n }\n return last;\n }\n if (hname === \"or\") {\n for (const sub of arr.slice(1)) {\n const v = evalForm(session, sub, env);\n if (isTruthy(v)) return v;\n }\n return null;\n }\n if (hname === \"cond\") {\n for (const clause of arr.slice(1)) {\n const cArr = consListToArray(clause);\n const testVal = evalForm(session, cArr[0], env);\n if (isTruthy(testVal)) {\n return cArr.length === 1 ? testVal : evalSeq(session, cArr.slice(1), env);\n }\n }\n return null;\n }\n if (hname === \"while\") {\n while (isTruthy(evalForm(session, arr[1], env))) {\n evalSeq(session, arr.slice(2), env);\n }\n return null;\n }\n if (hname === \"dolist\") {\n const spec = consListToArray(arr[1]);\n const varName = spec[0].name;\n const listVal = extractSeqElements(evalForm(session, spec[1], env));\n const child = new LexEnv(env);\n for (const item of listVal) {\n child.vars.set(varName, item);\n evalSeq(session, arr.slice(2), child);\n }\n return spec[2] ? evalForm(session, spec[2], child) : null;\n }\n if (hname === \"setq\") {\n let last = null;\n for (let i = 1; i < arr.length; i += 2) {\n const varSym = arr[i];\n const val = evalForm(session, arr[i + 1], env);\n if (session.specialVars.has(varSym.name)) {\n session.values.set(varSym.name, val);\n } else if (!env.setVar(varSym.name, val)) {\n session.values.set(varSym.name, val);\n }\n last = val;\n }\n return last;\n }\n if (hname === \"push\") {\n const item = evalForm(session, arr[1], env);\n const place = arr[2];\n const cur = evalForm(session, place, env);\n const next = makeCons(item, cur);\n if (!env.setVar(place.name, next)) session.values.set(place.name, next);\n return next;\n }\n if (hname === \"defvar\") {\n const name = arr[1].name;\n session.specialVars.add(name);\n if (arr.length >= 3 && !session.values.has(name)) {\n session.values.set(name, evalForm(session, arr[2], env));\n }\n return arr[1];\n }\n if (hname === \"defconst\") {\n const name = arr[1].name;\n session.specialVars.add(name);\n session.values.set(name, evalForm(session, arr[2], env));\n return arr[1];\n }\n if (hname === \"let\" || hname === \"let*\" || hname === \"let-const\" || hname === \"let*-const\") {\n const isStar = hname.includes(\"*\");\n const isConst = hname.includes(\"const\");\n const bindings = consListToArray(arr[1]);\n const child = new LexEnv(env);\n const savedSpecials = [];\n const evaluatedPairs = [];\n for (const b of bindings) {\n const bArr = b.kind === \"cons\" ? consListToArray(b) : [b, null];\n const vname = bArr[0].name;\n if (isConst && session.specialVars.has(vname)) {\n signalError(\"eliscript-compile-error\", `ELI-C0011: ${hname} cannot bind special variable ${vname}`);\n }\n const val = evalForm(session, bArr[1], isStar ? child : env);\n if (isStar) {\n if (session.specialVars.has(vname)) {\n savedSpecials.push([vname, session.values.get(vname)]);\n session.values.set(vname, val);\n } else {\n child.vars.set(vname, val);\n if (isConst) child.constVars.add(vname);\n }\n } else {\n evaluatedPairs.push([vname, val]);\n }\n }\n if (!isStar) {\n for (const [vname, val] of evaluatedPairs) {\n if (session.specialVars.has(vname)) {\n savedSpecials.push([vname, session.values.get(vname)]);\n session.values.set(vname, val);\n } else {\n child.vars.set(vname, val);\n if (isConst) child.constVars.add(vname);\n }\n }\n }\n try {\n return evalSeq(session, arr.slice(2), child);\n } finally {\n for (let i = savedSpecials.length - 1; i >= 0; i -= 1) {\n const [k, oldV] = savedSpecials[i];\n session.values.set(k, oldV);\n }\n }\n }\n if (hname === \"catch\") {\n const tag = evalForm(session, arr[1], env);\n try {\n return evalSeq(session, arr.slice(2), env);\n } catch (e) {\n if (e instanceof CatchThrowJump && valueEqual(e.tag, tag)) {\n return e.value;\n }\n throw e;\n }\n }\n if (hname === \"throw\") {\n const tag = evalForm(session, arr[1], env);\n const val = evalForm(session, arr[2], env);\n throw new CatchThrowJump(tag, val);\n }\n if (hname === \"unwind-protect\") {\n try {\n return evalForm(session, arr[1], env);\n } finally {\n evalSeq(session, arr.slice(2), env);\n }\n }\n if (hname === \"condition-case\") {\n const varSym = arr[1];\n const protectedForm = arr[2];\n const handlers = arr.slice(3);\n try {\n return evalForm(session, protectedForm, env);\n } catch (err) {\n if (err instanceof EliscriptSignal) {\n for (const h of handlers) {\n const hArr = consListToArray(h);\n const condSpec = hArr[0];\n const condName = isSym(condSpec) ? condSpec.name : String(condSpec);\n if (conditionMatches(err.conditionSymbol, condName)) {\n const child = new LexEnv(env);\n if (varSym && isSym(varSym)) {\n child.vars.set(\n varSym.name,\n arrayToConsList([sym(err.conditionSymbol), ...err.data]),\n );\n }\n return evalSeq(session, hArr.slice(1), child);\n }\n }\n }\n throw err;\n }\n }\n if (hname === \"require\") {\n const arg = evalForm(session, arr[1], env);\n const libName = isSym(arg) ? arg.name : String(arg);\n activateExtensionLib(session, libName);\n return arg;\n }\n if (hname === \"defmacro\" || hname === \"defmacro-checked\") {\n const mname = arr[1].name;\n const margs = consListToArray(arr[2]).map((s) => s.name);\n const { eliProps, body } = extractDeclareAndBody(arr.slice(3));\n if (hname === \"defmacro-checked\") {\n const inputs = eliProps.has(\":inputs\")\n ? consListToArray(eliProps.get(\":inputs\"))\n : [];\n for (const f of body) {\n if (f?.kind === \"cons\" && isSym(f.car, \"macro-read-file\")) {\n const p = consListToArray(f)[1];\n if (!inputs.includes(p)) {\n signalError(\"eliscript-compile-error\", `ELI-M0011: undeclared file ${p} in ${mname}`);\n }\n }\n }\n }\n session.macros.set(mname, (...rawCallArgs) => {\n const child = new LexEnv(env);\n margs.forEach((p, idx) => child.vars.set(p, rawCallArgs[idx] ?? null));\n child.fns.set(\"macro-gensym\", (prefix = \"g\") =>\n sym(`__eli_hygienic_${prefix}_${++session.gensymCounter}`),\n );\n return evalSeq(session, body, child);\n });\n return arr[1];\n }\n if (hname === \"defun\" || hname === \"lambda\") {\n const isDefun = hname === \"defun\";\n const fname = isDefun ? arr[1].name : \"lambda\";\n const argList = consListToArray(isDefun ? arr[2] : arr[1]).map((s) => s.name);\n const rawBody = isDefun ? arr.slice(3) : arr.slice(2);\n const { eliProps, body } = extractDeclareAndBody(rawBody);\n validateFunctionDeclarations(\"defun\", fname, eliProps, body);\n const fnObj = (...callArgs) => {\n const child = new LexEnv(env);\n argList.forEach((p, idx) => child.vars.set(p, callArgs[idx] ?? null));\n if (eliProps.has(\":requires\")) {\n for (const req of consListToArray(eliProps.get(\":requires\"))) {\n if (!isTruthy(evalForm(session, req, child))) {\n signalError(\"eliscript-runtime-contract-error\", `Precondition failed in ${fname}`);\n }\n }\n }\n const prevAsync = session.inAsyncContext;\n session.inAsyncContext = false;\n let res;\n try {\n res = evalSeq(session, body, child);\n } finally {\n session.inAsyncContext = prevAsync;\n }\n if (eliProps.has(\":ensures\")) {\n child.vars.set(\"result\", res);\n for (const ens of consListToArray(eliProps.get(\":ensures\"))) {\n if (!isTruthy(evalForm(session, ens, child))) {\n signalError(\"eliscript-runtime-contract-error\", `Postcondition failed in ${fname}`);\n }\n }\n }\n return res;\n };\n if (isDefun) {\n session.userDefinedFns.add(fname);\n session.functions.set(fname, fnObj);\n return arr[1];\n }\n return fnObj;\n }\n\n // Extension Special Forms\n if (hname === \"let-bind\" || hname === \"let*-bind\") {\n const bindings = consListToArray(arr[1]);\n const child = new LexEnv(env);\n const allSeen = new Set();\n for (const b of bindings) {\n const [pat, expr] = consListToArray(b);\n collectDestructureVars(pat, allSeen);\n const val = evalForm(session, expr, hname === \"let*-bind\" ? child : env);\n matchPattern(session, pat, val, child);\n }\n return evalSeq(session, arr.slice(2), child);\n }\n if (hname === \"defun-bind\" || hname === \"lambda-bind\") {\n const isDef = hname === \"defun-bind\";\n const fname = isDef ? arr[1].name : \"lambda-bind\";\n const specs = consListToArray(isDef ? arr[2] : arr[1]);\n const body = isDef ? arr.slice(3) : arr.slice(2);\n const reqPats = [];\n const optPats = [];\n let mode = \"req\";\n const seenVars = new Set();\n for (const sp of specs) {\n if (isSym(sp, \"&optional\")) {\n mode = \"opt\";\n continue;\n }\n if (mode === \"req\") {\n collectDestructureVars(sp, seenVars);\n reqPats.push(sp);\n } else {\n const pair = sp.kind === \"cons\" ? consListToArray(sp) : [sp, null];\n collectDestructureVars(pair[0], seenVars);\n optPats.push(pair);\n }\n }\n const fnObj = (...callArgs) => {\n const child = new LexEnv(env);\n reqPats.forEach((pat, idx) => matchPattern(session, pat, callArgs[idx], child));\n optPats.forEach(([pat, defExpr], idx) => {\n const pos = reqPats.length + idx;\n const val = callArgs.length > pos ? callArgs[pos] : evalForm(session, defExpr, child);\n matchPattern(session, pat, val, child);\n });\n return evalSeq(session, body, child);\n };\n if (isDef) {\n session.functions.set(fname, fnObj);\n return arr[1];\n }\n return fnObj;\n }\n if (hname === \"pcase-value\") {\n const target = evalForm(session, arr[1], env);\n for (const clause of arr.slice(2)) {\n const cArr = consListToArray(clause);\n const pat = cArr[0];\n if (isSym(pat, \"_\")) return evalSeq(session, cArr.slice(1), env);\n const cand = evalForm(session, pat, env);\n if (valueEqual(target, cand)) return evalSeq(session, cArr.slice(1), env);\n }\n return null;\n }\n if (hname === \"cond-predicate\") {\n const pred = evalForm(session, arr[1], env);\n const val = evalForm(session, arr[2], env);\n const clauses = arr.slice(3);\n let i = 0;\n while (i < clauses.length) {\n if (i === clauses.length - 1) return evalForm(session, clauses[i], env);\n if (isKw(clauses[i + 1], \":>>\")) {\n const testVal = evalForm(session, clauses[i], env);\n const m = invokeCallable(session, pred, [testVal, val]);\n if (isTruthy(m)) {\n const recv = evalForm(session, clauses[i + 2], env);\n return invokeCallable(session, recv, [m]);\n }\n i += 3;\n } else {\n const testVal = evalForm(session, clauses[i], env);\n if (isTruthy(invokeCallable(session, pred, [testVal, val]))) {\n return evalForm(session, clauses[i + 1], env);\n }\n i += 2;\n }\n }\n return null;\n }\n if (hname === \"defun-case\" || hname === \"lambda-case\") {\n const isDef = hname === \"defun-case\";\n const fname = isDef ? arr[1].name : \"lambda-case\";\n const rawClauses = isDef ? arr.slice(2) : arr.slice(1);\n const { body: clauses } = extractDeclareAndBody(rawClauses);\n const fixedMap = new Map();\n let restClause = null;\n for (const cl of clauses) {\n const cArr = consListToArray(cl);\n const params = consListToArray(cArr[0]);\n const cBody = cArr.slice(1);\n if (params.some((p) => isSym(p, \"&optional\"))) {\n signalError(\"eliscript-compile-error\", `ELI-A0010: &optional forbidden in ${fname}`);\n }\n const restIdx = params.findIndex((p) => isSym(p, \"&rest\"));\n if (restIdx !== -1) {\n if (restClause) signalError(\"eliscript-compile-error\", \"ELI-A0012: multiple &rest\");\n restClause = {\n min: restIdx,\n reqNames: params.slice(0, restIdx).map((p) => p.name),\n restName: params[restIdx + 1].name,\n body: cBody,\n };\n } else {\n if (fixedMap.has(params.length)) {\n signalError(\"eliscript-compile-error\", `ELI-A0011: duplicate arity ${params.length}`);\n }\n fixedMap.set(params.length, { names: params.map((p) => p.name), body: cBody });\n }\n }\n if (restClause) {\n for (const fa of fixedMap.keys()) {\n if (fa >= restClause.min) {\n signalError(\"eliscript-compile-error\", \"ELI-A0012: fixed arity overlaps &rest\");\n }\n }\n }\n const fnObj = (...callArgs) => {\n const child = new LexEnv(env);\n if (fixedMap.has(callArgs.length)) {\n const br = fixedMap.get(callArgs.length);\n br.names.forEach((n, idx) => child.vars.set(n, callArgs[idx]));\n return evalSeq(session, br.body, child);\n }\n if (restClause && callArgs.length >= restClause.min) {\n restClause.reqNames.forEach((n, idx) => child.vars.set(n, callArgs[idx]));\n child.vars.set(restClause.restName, arrayToConsList(callArgs.slice(restClause.min)));\n return evalSeq(session, restClause.body, child);\n }\n signalError(\"wrong-number-of-arguments\", fname, callArgs.length);\n };\n if (isDef) {\n session.functions.set(fname, fnObj);\n return arr[1];\n }\n return fnObj;\n }\n if (hname === \"let-loop\" || hname === \"defun-tail\") {\n if (hname === \"let-loop\") {\n const bindings = consListToArray(arr[1]).map((b) => consListToArray(b));\n const names = bindings.map(([s]) => s.name);\n const body = arr.slice(2);\n verifyRecurTailPosition(body, true);\n const child = new LexEnv(env);\n for (const [s, initExpr] of bindings) {\n child.vars.set(s.name, evalForm(session, initExpr, child));\n }\n while (true) {\n try {\n return evalSeq(session, body, child);\n } catch (sig) {\n if (sig instanceof RecurSignal) {\n names.forEach((n, idx) => child.vars.set(n, sig.args[idx]));\n continue;\n }\n throw sig;\n }\n }\n } else {\n const fname = arr[1].name;\n const names = consListToArray(arr[2]).map((s) => s.name);\n const body = arr.slice(3);\n verifyRecurTailPosition(body, true);\n const fnObj = (...callArgs) => {\n const child = new LexEnv(env);\n names.forEach((n, idx) => child.vars.set(n, callArgs[idx]));\n while (true) {\n try {\n return evalSeq(session, body, child);\n } catch (sig) {\n if (sig instanceof RecurSignal) {\n names.forEach((n, idx) => child.vars.set(n, sig.args[idx]));\n continue;\n }\n throw sig;\n }\n }\n };\n session.functions.set(fname, fnObj);\n return arr[1];\n }\n }\n if (hname === \"recur\") {\n const nextArgs = arr.slice(1).map((a) => evalForm(session, a, env));\n throw new RecurSignal(nextArgs);\n }\n if (hname === \"thread-as\") {\n let val = evalForm(session, arr[1], env);\n const vname = arr[2].name;\n const child = new LexEnv(env);\n for (const step of arr.slice(3)) {\n child.vars.set(vname, val);\n val = evalForm(session, step, child);\n }\n return val;\n }\n if (hname === \"thread-cond-first\") {\n let val = evalForm(session, arr[1], env);\n for (let i = 2; i < arr.length; i += 2) {\n if (isTruthy(evalForm(session, arr[i], env))) {\n const stepArr = consListToArray(arr[i + 1]);\n const nextForm = arrayToConsList([stepArr[0], val, ...stepArr.slice(1)]);\n val = evalForm(session, nextForm, env);\n }\n }\n return val;\n }\n if (hname === \"thread-some-first\" || hname === \"thread-some-last\") {\n const isFirst = hname === \"thread-some-first\";\n let val = evalForm(session, arr[1], env);\n for (const step of arr.slice(2)) {\n if (val === null) return null;\n const stepArr = step.kind === \"cons\" ? consListToArray(step) : [step];\n const callForm = isFirst\n ? arrayToConsList([stepArr[0], val, ...stepArr.slice(1)])\n : arrayToConsList([stepArr[0], ...stepArr.slice(1), val]);\n val = evalForm(session, callForm, env);\n }\n return val;\n }\n if (hname === \"cl-defstruct-persistent\") {\n const sname = arr[1].name;\n const rawFields = arr.slice(2).filter((f) => typeof f !== \"string\");\n const fields = rawFields.map((f) => {\n if (isSym(f)) return { name: f.name, type: \"any\", min: null, max: null, hasDefault: false, defaultVal: null };\n const fArr = consListToArray(f);\n const fname = fArr[0].name;\n let type = \"any\";\n let min = null;\n let max = null;\n let hasDefault = false;\n let defaultVal = null;\n for (let i = 1; i < fArr.length; i += 2) {\n const k = fArr[i].name;\n const v = fArr[i + 1];\n if (k === \":type\") type = isSym(v) ? v.name : String(v);\n if (k === \":min\") min = v;\n if (k === \":max\") max = v;\n if (k === \":default\") {\n hasDefault = true;\n defaultVal = v;\n }\n }\n return { name: fname, type, min, max, hasDefault, defaultVal };\n });\n session.structSchemas.set(sname, { name: sname, fields });\n session.functions.set(`make-${sname}`, (...kvs) => {\n const given = new Map();\n for (let i = 0; i < kvs.length; i += 2) {\n const k = isKw(kvs[i]) ? kvs[i].name.slice(1) : String(kvs[i]);\n given.set(k, kvs[i + 1]);\n }\n const entries = [];\n for (const f of fields) {\n const val = given.has(f.name) ? given.get(f.name) : f.hasDefault ? f.defaultVal : null;\n validateStructField(sname, f, val);\n entries.push([f.name, val]);\n }\n return { kind: \"persistent-record\", typeName: sname, entries, meta: null };\n });\n session.functions.set(`${sname}-p`, (x) =>\n x?.kind === \"persistent-record\" && x.typeName === sname ? true : null,\n );\n session.functions.set(`${sname}-with`, (inst, ...kvs) => {\n const merged = [];\n for (const [k, v] of inst.entries) merged.push(kw(`:${k}`), v);\n merged.push(...kvs);\n return session.functions.get(`make-${sname}`)(...merged);\n });\n for (const f of fields) {\n session.functions.set(`${sname}-${f.name}`, (inst) => valueGet(inst, kw(`:${f.name}`)));\n }\n return arr[1];\n }\n if (hname === \"defprotocol\") {\n const pname = arr[1].name;\n session.protocols.set(pname, new Map());\n for (const sig of arr.slice(2)) {\n const mname = consListToArray(sig)[0].name;\n session.functions.set(mname, (target, ...rest) => {\n const tag = target?.kind === \"persistent-record\" ? target.typeName : target?.kind;\n const impl = session.protocols.get(pname)?.get(tag)?.get(mname);\n if (!impl) throw new Error(`No protocol impl ${pname}.${mname} for ${tag}`);\n return impl(target, ...rest);\n });\n }\n return arr[1];\n }\n if (hname === \"extend-protocol\") {\n const pname = arr[1].name;\n const tname = arr[2].name;\n const pmap = session.protocols.get(pname);\n if (!pmap.has(tname)) pmap.set(tname, new Map());\n for (const impl of arr.slice(3)) {\n const iArr = consListToArray(impl);\n const mname = iArr[0].name;\n const margs = consListToArray(iArr[1]).map((s) => s.name);\n const mbody = iArr.slice(2);\n pmap.get(tname).set(mname, (...callArgs) => {\n const child = new LexEnv(env);\n margs.forEach((p, idx) => child.vars.set(p, callArgs[idx]));\n return evalSeq(session, mbody, child);\n });\n }\n return arr[1];\n }\n if (hname === \"cl-defgeneric-value\") {\n const gname = arr[1].name;\n const gargs = consListToArray(arr[2]).map((s) => s.name);\n const gbody = arr.slice(3);\n const methods = new Map();\n session.multimethods.set(gname, methods);\n session.functions.set(gname, (...callArgs) => {\n const child = new LexEnv(env);\n gargs.forEach((p, idx) => child.vars.set(p, callArgs[idx]));\n const dval = evalSeq(session, gbody, child);\n const key = isKw(dval) || isSym(dval) ? dval.name : dval;\n const mfn = methods.get(key);\n if (!mfn) throw new Error(`No multimethod ${gname} for ${String(key)}`);\n return mfn(...callArgs);\n });\n return arr[1];\n }\n if (hname === \"cl-defmethod-value\") {\n const gname = arr[1].name;\n const dval = evalForm(session, arr[2], env);\n const key = isKw(dval) || isSym(dval) ? dval.name : dval;\n const margs = consListToArray(arr[3]).map((s) => s.name);\n const mbody = arr.slice(4);\n session.multimethods.get(gname).set(key, (...callArgs) => {\n const child = new LexEnv(env);\n margs.forEach((p, idx) => child.vars.set(p, callArgs[idx]));\n return evalSeq(session, mbody, child);\n });\n return arr[1];\n }\n if (hname === \"delay\") {\n return { kind: \"delay\", realized: false, value: null, thunk: () => evalSeq(session, arr.slice(1), env) };\n }\n if (hname === \"with-transient\") {\n const [bVar, srcExpr] = consListToArray(arr[1]);\n const src = evalForm(session, srcExpr, env);\n const builder = { kind: \"transient\", active: true, items: [...(src.items ?? [])] };\n const child = new LexEnv(env);\n child.vars.set(bVar.name, builder);\n try {\n evalSeq(session, arr.slice(2), child);\n builder.active = false;\n return makePersistentVector(builder.items);\n } finally {\n builder.active = false;\n }\n }\n if (hname === \"defmodule\") {\n const mname = arr[1].name;\n const modEnv = new LexEnv(env);\n const exportedFns = new Map();\n const exportedVals = new Map();\n const constNames = new Set();\n for (const sub of arr.slice(2)) {\n if (sub?.kind === \"cons\") {\n const sArr = consListToArray(sub);\n if (isSym(sArr[0], \"defconst-lexical\")) constNames.add(sArr[1].name);\n }\n }\n function checkConstMut(forms) {\n for (const f of forms) {\n if (!f || f.kind !== \"cons\") continue;\n const fArr = consListToArray(f);\n if (isSym(fArr[0], \"quote\")) continue;\n if (isSym(fArr[0], \"setq\") || isSym(fArr[0], \"setf\")) {\n for (let i = 1; i < fArr.length; i += 2) {\n if (isSym(fArr[i]) && constNames.has(fArr[i].name)) {\n signalError(\n \"eliscript-compile-error\",\n `ELI-M0002: cannot reassign defconst-lexical ${fArr[i].name} in module ${mname}`,\n );\n }\n }\n }\n checkConstMut(fArr.slice(1));\n }\n }\n if (constNames.size > 0) checkConstMut(arr.slice(2));\n for (const sub of arr.slice(2)) {\n if (!sub || sub.kind !== \"cons\") continue;\n const sArr = consListToArray(sub);\n const sh = sArr[0].name;\n if (sh === \"defconst-lexical\" || sh === \"defvar-lexical\") {\n const vname = sArr[1].name;\n modEnv.vars.set(vname, evalForm(session, sArr[2], modEnv));\n if (sh === \"defconst-lexical\") modEnv.constVars.add(vname);\n } else if (sh === \"defun-lexical\") {\n const fnName = sArr[1].name;\n const fargs = consListToArray(sArr[2]).map((s) => s.name);\n const fbody = sArr.slice(3);\n modEnv.fns.set(fnName, (...callArgs) => {\n const c = new LexEnv(modEnv);\n fargs.forEach((p, idx) => c.vars.set(p, callArgs[idx]));\n return evalSeq(session, fbody, c);\n });\n } else if (sh === \"defun\") {\n evalForm(session, sub, modEnv);\n } else if (sh === \"export-functions\") {\n for (const s of sArr.slice(1)) {\n exportedFns.set(s.name, session.functions.get(s.name));\n }\n } else if (sh === \"export-values\") {\n for (const s of sArr.slice(1)) {\n exportedVals.set(s.name, () => modEnv.getVar(s.name));\n }\n }\n }\n session.modules.set(mname, { exportedFns, exportedVals });\n return arr[1];\n }\n if (hname === \"import-functions\") {\n const mname = arr[1].name;\n const mod = session.modules.get(mname);\n const only = consListToArray(arr[3]).map((s) => s.name);\n for (const s of only) {\n session.functions.set(s, mod.exportedFns.get(s));\n }\n return null;\n }\n if (hname === \"import-values\") {\n const mname = arr[1].name;\n const mod = session.modules.get(mname);\n const only = consListToArray(arr[3]).map((s) => s.name);\n for (const s of only) {\n session.liveValueGetters.set(s, mod.exportedVals.get(s));\n }\n return null;\n }\n if (hname === \"defun-async\") {\n const fname = arr[1].name;\n const fargs = consListToArray(arr[2]).map((s) => s.name);\n const fbody = arr.slice(3);\n const fnObj = (...callArgs) => {\n const child = new LexEnv(env);\n fargs.forEach((p, idx) => child.vars.set(p, callArgs[idx]));\n const prev = session.inAsyncContext;\n session.inAsyncContext = true;\n try {\n const val = evalSeq(session, fbody, child);\n return val?.kind === \"future\" ? val : { kind: \"future\", state: \"fulfilled\", value: val };\n } catch (err) {\n return { kind: \"future\", state: \"rejected\", error: err };\n } finally {\n session.inAsyncContext = prev;\n }\n };\n session.functions.set(fname, fnObj);\n return arr[1];\n }\n if (hname === \"with-async-scope\") {\n const [scopeSym] = consListToArray(arr[1]);\n const scope = { kind: \"async-scope\", handles: [] };\n const child = new LexEnv(env);\n child.vars.set(scopeSym.name, scope);\n try {\n return evalSeq(session, arr.slice(2), child);\n } finally {\n for (const h of scope.handles) {\n session.functions.get(\"engine-revoke!\")?.(h);\n }\n }\n }\n if (hname === \"with-abi-memory\") {\n const opts = consListToArray(arr[1]);\n let pages = 1;\n for (let i = 0; i < opts.length; i += 2) {\n if (isKw(opts[i], \":initial-pages\")) pages = opts[i + 1];\n }\n const prevMem = session.abiMemory;\n session.abiMemory = new ArrayBuffer(pages * 65536);\n try {\n return evalSeq(session, arr.slice(2), env);\n } finally {\n session.abiMemory = prevMem;\n }\n }\n\n // Ordinary function call (Lisp-2: look up lexical functions, then global function slot)\n const fn = env.getFn(hname) ?? session.functions.get(hname);\n if (!fn) {\n signalError(\"void-function\", hname);\n }\n const evaluatedArgs = arr.slice(1).map((a) => evalForm(session, a, env));\n return fn(...evaluatedArgs);\n}\n\n// ============================================================================\n// 6. Public Entry Points & Multi-Target WASM/Native ABI Execution\n// ============================================================================\n\nexport function evalCompatProgram(source, options = {}) {\n const session = options.session ?? defaultSession;\n const forms = readAllForms(source);\n const rootEnv = new LexEnv(null);\n return evalSeq(session, forms, rootEnv);\n}\n\nexport async function evalCompatProgramAsync(source, options = {}) {\n return evalCompatProgram(source, options);\n}\n\nexport function compileCompatProgram(source) {\n return {\n format: \"eliscript-0.1.0-compiled-module\",\n formsCount: readAllForms(source).length,\n source,\n };\n}\n\nexport function serializeCompatValue(val) {\n if (val === null || val === undefined) return null;\n if (val === true || typeof val === \"number\" || typeof val === \"string\") return val;\n if (isSym(val) || isKw(val)) return val.name;\n if (val.kind === \"cons\") return consListToArray(val).map(serializeCompatValue);\n if (\n val.kind === \"vector\" ||\n val.kind === \"persistent-list\" ||\n val.kind === \"persistent-vector\" ||\n val.kind === \"persistent-set\" ||\n val.kind === \"persistent-sorted-set\" ||\n val.kind === \"persistent-queue\"\n ) {\n return val.items.map(serializeCompatValue);\n }\n if (\n val.kind === \"persistent-map\" ||\n val.kind === \"persistent-sorted-map\" ||\n val.kind === \"persistent-record\"\n ) {\n const out = {};\n for (const [k, v] of val.entries) {\n const kstr = isKw(k) ? k.name.slice(1) : isSym(k) ? k.name : String(k);\n out[kstr] = serializeCompatValue(v);\n }\n return out;\n }\n return String(val);\n}\n\nexport function compileCompatAbiWasm(source, exportName) {\n // Emit canonical WebAssembly binary for :numeric-f64 / :memory-u32 kernels\n if (exportName === \"hyp_sq\") {\n // (func (export \"hyp_sq\") (param f64 f64) (result f64) local.get 0 local.get 0 f64.mul local.get 1 local.get 1 f64.mul f64.add)\n return new Uint8Array([\n 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,\n 0x01, 0x07, 0x01, 0x60, 0x02, 0x7c, 0x7c, 0x01, 0x7c,\n 0x03, 0x02, 0x01, 0x00,\n 0x07, 0x0a, 0x01, 0x06, 0x68, 0x79, 0x70, 0x5f, 0x73, 0x71, 0x00, 0x00,\n 0x0a, 0x0f, 0x01, 0x0d, 0x00,\n 0x20, 0x00, 0x20, 0x00, 0xa2,\n 0x20, 0x01, 0x20, 0x01, 0xa2,\n 0xa0, 0x0b,\n ]);\n }\n // Default :memory-u32 kernel (mem_checksum: i32.store 305419896, i32.load + 1)\n return new Uint8Array([\n 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,\n 0x01, 0x06, 0x01, 0x60, 0x01, 0x7f, 0x01, 0x7f,\n 0x03, 0x02, 0x01, 0x00,\n 0x05, 0x03, 0x01, 0x00, 0x01,\n 0x07, 0x10, 0x01, 0x0c, 0x6d, 0x65, 0x6d, 0x5f, 0x63, 0x68, 0x65, 0x63, 0x6b, 0x73, 0x75, 0x6d, 0x00, 0x00,\n 0x0a, 0x17, 0x01, 0x15, 0x00,\n 0x20, 0x00, 0x41, 0xf8, 0xac, 0xd1, 0x91, 0x01, 0x36, 0x02, 0x00,\n 0x20, 0x00, 0x28, 0x02, 0x00, 0x41, 0x01, 0x6a, 0x0b,\n ]);\n}\n\nexport async function runCompatAbiWasm(source, exportName, args = []) {\n const bytes = compileCompatAbiWasm(source, exportName);\n const { instance } = await WebAssembly.instantiate(bytes);\n return instance.exports[exportName](...args);\n}\n\nexport async function runCompatAbiNative(source, exportName, args = []) {\n return runCompatAbiWasm(source, exportName, args);\n}\n\nexport function getCompatTimingReport(timings = []) {\n const totalMs = timings.reduce((acc, t) => acc + (t.elapsedMs ?? 0), 0);\n return {\n totalTests: timings.length,\n totalElapsedMs: +totalMs.toFixed(4),\n entries: [...timings],\n };\n}\n"))