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.
- package/README.md +6 -6
- package/bootstrap/README.md +13 -8
- package/bootstrap/host/build.eli +2 -0
- package/bootstrap/host/bun.eli +2 -0
- package/bootstrap/host/check-cli-legacy.eli +2 -0
- package/bootstrap/host/evaluation-cli.eli +2 -0
- package/bootstrap/host/evaluation.eli +2 -0
- package/bootstrap/host/format-cli.eli +2 -0
- package/bootstrap/host/project-cli-legacy.eli +2 -0
- package/bootstrap/host/project-legacy.eli +2 -0
- package/bootstrap/host/watch-cli.eli +2 -0
- package/bootstrap/host/watch.eli +2 -0
- package/browser/README.md +33 -0
- package/browser/host.eli +2 -0
- package/browser/worker.eli +2 -0
- package/editor/eliscript-abi.el +170 -0
- package/editor/eliscript-async.el +375 -0
- package/editor/eliscript-bind.el +822 -0
- package/editor/eliscript-compat.el +184 -0
- package/editor/eliscript-contract.el +334 -0
- package/editor/eliscript-data.el +1544 -0
- package/editor/eliscript-js.el +318 -0
- package/editor/eliscript-mode.el +1 -1
- package/editor/eliscript-module.el +340 -0
- package/editor/eliscript-repl.el +1 -1
- package/package.json +4 -1
- package/platform/README.md +33 -12
- package/platform/browser.eli +2 -0
- package/platform/http.eli +2 -0
- package/platform/worker.eli +2 -0
- package/runtime/README.md +34 -14
- package/runtime/array-text.eli +2 -0
- package/runtime/core/collection-internals.eli +2 -0
- package/runtime/core/collection.eli +2 -0
- package/runtime/core/collection.mjs +99 -17
- package/runtime/core/data-text.eli +2 -0
- package/runtime/core/data.eli +2 -0
- package/runtime/core/data.mjs +7 -5
- package/runtime/core/identifier.eli +2 -0
- package/runtime/core/lazy-sequence.eli +2 -0
- package/runtime/core/list-internals.eli +2 -0
- package/runtime/core/list.eli +2 -0
- package/runtime/core/list.mjs +3 -0
- package/runtime/core/map-internals.eli +2 -0
- package/runtime/core/map.eli +2 -0
- package/runtime/core/map.mjs +5 -0
- package/runtime/core/metadata-internals.eli +2 -0
- package/runtime/core/metadata.eli +2 -0
- package/runtime/core/metadata.mjs +14 -0
- package/runtime/core/object.eli +2 -0
- package/runtime/core/order.eli +2 -0
- package/runtime/core/order.mjs +35 -6
- package/runtime/core/persistent-kind.eli +2 -0
- package/runtime/core/persistent-kind.mjs +6 -0
- package/runtime/core/protocol-error.eli +2 -0
- package/runtime/core/protocol.eli +2 -0
- package/runtime/core/queue-internals.eli +2 -0
- package/runtime/core/queue.eli +2 -0
- package/runtime/core/queue.mjs +3 -0
- package/runtime/core/record.eli +2 -0
- package/runtime/core/regex.eli +2 -0
- package/runtime/core/sequence.eli +2 -0
- package/runtime/core/sequence.mjs +75 -13
- package/runtime/core/set-algebra.eli +2 -0
- package/runtime/core/set-internals.eli +2 -0
- package/runtime/core/set.eli +2 -0
- package/runtime/core/sorted-internals.eli +2 -0
- package/runtime/core/sorted.eli +2 -0
- package/runtime/core/text.eli +2 -0
- package/runtime/core/transducer.eli +2 -0
- package/runtime/core/transient-internals.eli +2 -0
- package/runtime/core/transient.eli +2 -0
- package/runtime/core/transient.mjs +59 -10
- package/runtime/core/truth.eli +2 -0
- package/runtime/core/type.eli +2 -0
- package/runtime/core/value-internals.eli +2 -0
- package/runtime/core/value.eli +2 -0
- package/runtime/core/vector-internals.eli +2 -0
- package/runtime/core/vector-internals.mjs +3 -6
- package/runtime/core/vector.eli +2 -0
- package/runtime/core/vector.mjs +125 -7
- package/runtime/emacs-compat.eli +2 -0
- package/runtime/emacs-compat.mjs +2507 -0
- package/runtime/literals.eli +2 -0
- package/runtime/number-radix.eli +2 -0
- package/runtime/source-mapping.eli +2 -0
- package/runtime/testing/list.eli +2 -0
- package/runtime/testing/map.eli +2 -0
- package/runtime/testing/queue.eli +2 -0
- package/runtime/testing/set.eli +2 -0
- package/runtime/testing/sorted.eli +2 -0
- package/runtime/testing/value.eli +2 -0
- package/runtime/testing/vector.eli +2 -0
- package/runtime/wire/http-rpc.eli +2 -0
- package/runtime/wire/markdown.eli +2 -0
- package/runtime/wire/schema.eli +2 -0
- package/runtime/worker-value-codec.eli +2 -0
- package/runtime/worker-value-stream.eli +2 -0
- package/runtime/worker.eli +2 -0
- package/stdlib/README.md +2 -2
- package/stdlib/core/order.eli +36 -10
- package/stdlib/core/seq.eli +104 -75
- package/stdlib/core/zipper.eli +238 -98
- package/stdlib/managed-literal-protocols.eli +5 -5
- package/stdlib/managed-runtime-order.eli +32 -10
- package/stdlib/managed-runtime-sequence.eli +69 -28
- package/tools/acceptance/check.eli +13 -3
- package/tools/backends/compiler-build.mjs +140 -140
|
@@ -249,9 +249,20 @@ export function generate(count, producer) {
|
|
|
249
249
|
}
|
|
250
250
|
|
|
251
251
|
export function first(collection, notFound = null) {
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
252
|
+
if (isPersistentList(collection)) {
|
|
253
|
+
return collection.isEmpty ? notFound : collection.first(notFound);
|
|
254
|
+
}
|
|
255
|
+
if (isPersistentVector(collection)) {
|
|
256
|
+
return collection.count === 0 ? notFound : collection.nth(0);
|
|
257
|
+
}
|
|
258
|
+
let found = false;
|
|
259
|
+
let foundValue = null;
|
|
260
|
+
reduce(collection, (missing, value) => {
|
|
261
|
+
found = true;
|
|
262
|
+
foundValue = value;
|
|
263
|
+
return reduced(missing);
|
|
264
|
+
}, null);
|
|
265
|
+
return found ? foundValue : notFound;
|
|
255
266
|
}
|
|
256
267
|
|
|
257
268
|
export function nthRest(limit, collection) {
|
|
@@ -303,25 +314,53 @@ export function nnext(collection) {
|
|
|
303
314
|
export function sequenceNth(index, collection, notFound = null) {
|
|
304
315
|
requireNonNegativeSafeInteger(index, "sequenceNth index");
|
|
305
316
|
let position = 0;
|
|
306
|
-
|
|
307
|
-
|
|
317
|
+
let found = false;
|
|
318
|
+
let foundValue = null;
|
|
319
|
+
reduce(collection, (missing, value) => {
|
|
320
|
+
if (position === index) {
|
|
321
|
+
found = true;
|
|
322
|
+
foundValue = value;
|
|
323
|
+
return reduced(missing);
|
|
324
|
+
}
|
|
308
325
|
position += 1;
|
|
309
326
|
return missing;
|
|
310
|
-
},
|
|
311
|
-
return
|
|
327
|
+
}, null);
|
|
328
|
+
return found ? foundValue : notFound;
|
|
312
329
|
}
|
|
313
330
|
|
|
314
331
|
export function last(collection, notFound = null) {
|
|
332
|
+
if (isPersistentVector(collection)) {
|
|
333
|
+
return collection.peek(notFound);
|
|
334
|
+
}
|
|
315
335
|
if (implementsProtocolOperation(IReversible, "rseq", collection)) {
|
|
316
336
|
return first(rseq(collection), notFound);
|
|
317
337
|
}
|
|
318
|
-
|
|
319
|
-
|
|
338
|
+
let found = false;
|
|
339
|
+
let lastValue = null;
|
|
340
|
+
reduce(collection, (missing, value) => {
|
|
341
|
+
found = true;
|
|
342
|
+
lastValue = value;
|
|
343
|
+
return missing;
|
|
344
|
+
}, null);
|
|
345
|
+
return found ? lastValue : notFound;
|
|
320
346
|
}
|
|
321
347
|
|
|
322
348
|
export function takeLast(limit, collection) {
|
|
323
349
|
requireNonNegativeSafeInteger(limit, "takeLast limit");
|
|
324
350
|
if (limit === 0) return EMPTY_VECTOR;
|
|
351
|
+
if (isPersistentVector(collection)) {
|
|
352
|
+
const total = collection.count;
|
|
353
|
+
if (total === 0) return EMPTY_VECTOR;
|
|
354
|
+
if (limit >= total) return collection;
|
|
355
|
+
if (typeof collection.sliceVector === "function") {
|
|
356
|
+
return collection.sliceVector(total - limit, total);
|
|
357
|
+
}
|
|
358
|
+
const builder = transient(EMPTY_VECTOR);
|
|
359
|
+
for (let index = total - limit; index < total; index += 1) {
|
|
360
|
+
conjBang(builder, collection.nth(index));
|
|
361
|
+
}
|
|
362
|
+
return persistentBang(builder);
|
|
363
|
+
}
|
|
325
364
|
|
|
326
365
|
const ring = new Array(limit);
|
|
327
366
|
let count = 0;
|
|
@@ -346,7 +385,22 @@ export function takeLast(limit, collection) {
|
|
|
346
385
|
|
|
347
386
|
export function dropLast(limit, collection) {
|
|
348
387
|
requireNonNegativeSafeInteger(limit, "dropLast limit");
|
|
349
|
-
if (limit === 0)
|
|
388
|
+
if (limit === 0) {
|
|
389
|
+
return isPersistentVector(collection) ? collection : into(EMPTY_VECTOR, collection);
|
|
390
|
+
}
|
|
391
|
+
if (isPersistentVector(collection)) {
|
|
392
|
+
const total = collection.count;
|
|
393
|
+
if (limit >= total) return EMPTY_VECTOR;
|
|
394
|
+
const keep = total - limit;
|
|
395
|
+
if (typeof collection.sliceVector === "function") {
|
|
396
|
+
return collection.sliceVector(0, keep);
|
|
397
|
+
}
|
|
398
|
+
const builder = transient(EMPTY_VECTOR);
|
|
399
|
+
for (let index = 0; index < keep; index += 1) {
|
|
400
|
+
conjBang(builder, collection.nth(index));
|
|
401
|
+
}
|
|
402
|
+
return persistentBang(builder);
|
|
403
|
+
}
|
|
350
404
|
|
|
351
405
|
const ring = new Array(limit);
|
|
352
406
|
const builder = transient(EMPTY_VECTOR);
|
|
@@ -575,9 +629,17 @@ export function notEvery(predicate, collection) {
|
|
|
575
629
|
|
|
576
630
|
export function find(predicate, collection, notFound = null) {
|
|
577
631
|
requireFunction(predicate, "find predicate");
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
632
|
+
let found = false;
|
|
633
|
+
let foundValue = null;
|
|
634
|
+
reduce(collection, (missing, value) => {
|
|
635
|
+
if (isTruthy(predicate(value))) {
|
|
636
|
+
found = true;
|
|
637
|
+
foundValue = value;
|
|
638
|
+
return reduced(missing);
|
|
639
|
+
}
|
|
640
|
+
return missing;
|
|
641
|
+
}, null);
|
|
642
|
+
return found ? foundValue : notFound;
|
|
581
643
|
}
|
|
582
644
|
|
|
583
645
|
export function reductions(step, initial, collection) {
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.set-algebra
|
|
2
|
+
(js* "import {\n assoc,\n conj,\n contains,\n count,\n empty,\n get,\n reduce,\n reduceKV,\n reduced,\n} from \"./collection.mjs\";\nimport {\n keys,\n merge,\n selectKeys,\n vals,\n} from \"./data.mjs\";\nimport { EMPTY_MAP } from \"./map.mjs\";\nimport { meta, withMeta } from \"./metadata.mjs\";\nimport {\n EMPTY_SET,\n isPersistentHashSet,\n} from \"./set.mjs\";\nimport {\n assocBang,\n conjBang,\n dissocBang,\n persistentBang,\n transient,\n} from \"./transient.mjs\";\nimport { isTruthy } from \"./truth.mjs\";\n\nconst NOT_FOUND = Object.freeze({});\n\nfunction requireArity(actual, expected, label) {\n if (actual !== expected) {\n throw new TypeError(`${label} expects ${expected} collection${expected === 1 ? \"\" : \"s\"}`);\n }\n}\n\nfunction requireNonEmpty(actual, label) {\n if (actual === 0) {\n throw new TypeError(`${label} expects at least one collection`);\n }\n}\n\nfunction requireFunction(value, label) {\n if (typeof value !== \"function\") {\n throw new TypeError(`${label} must be a function`);\n }\n return value;\n}\n\nfunction requireJoinArity(actual) {\n if (actual !== 2 && actual !== 3) {\n throw new TypeError(\"join expects 2 or 3 relations\");\n }\n}\n\nfunction persistentMap(collection) {\n return withMeta(merge(collection), meta(collection));\n}\n\nfunction firstValue(collection) {\n return reduce(collection, (_missing, value) =>\n reduced({ value }), NOT_FOUND);\n}\n\nexport function set(collection) {\n requireArity(arguments.length, 1, \"set\");\n if (isPersistentHashSet(collection)) return collection;\n\n const result = transient(EMPTY_SET);\n reduce(collection, (builder, value) => {\n conjBang(builder, value);\n return builder;\n }, result);\n return persistentBang(result);\n}\n\nexport function union(...collections) {\n if (collections.length === 0) return EMPTY_SET;\n\n const result = transient(set(collections[0]));\n for (let index = 1; index < collections.length; index += 1) {\n reduce(collections[index], (builder, value) => {\n conjBang(builder, value);\n return builder;\n }, result);\n }\n return persistentBang(result);\n}\n\nfunction intersectPair(left, right) {\n const leftSet = set(left);\n const rightSet = set(right);\n const candidates = count(leftSet) <= count(rightSet) ? leftSet : rightSet;\n const membership = candidates === leftSet ? rightSet : leftSet;\n const builder = transient(empty(leftSet));\n reduce(candidates, (result, value) => {\n if (contains(membership, value)) conjBang(result, value);\n return result;\n }, builder);\n const retained = persistentBang(builder);\n return count(retained) === count(leftSet) ? leftSet : retained;\n}\n\nexport function intersection(...collections) {\n requireNonEmpty(collections.length, \"intersection\");\n let result = set(collections[0]);\n for (let index = 1;\n index < collections.length && count(result) > 0;\n index += 1) {\n result = intersectPair(result, collections[index]);\n }\n return result;\n}\n\nexport function difference(...collections) {\n requireNonEmpty(collections.length, \"difference\");\n const result = transient(set(collections[0]));\n for (let index = 1; index < collections.length; index += 1) {\n reduce(collections[index], (builder, value) => {\n dissocBang(builder, value);\n return builder;\n }, result);\n }\n return persistentBang(result);\n}\n\nexport function subset(left, right) {\n requireArity(arguments.length, 2, \"subset\");\n const candidates = set(left);\n const membership = set(right);\n if (count(candidates) > count(membership)) return false;\n return reduce(candidates, (result, value) =>\n contains(membership, value) ? result : reduced(false), true);\n}\n\nexport function superset(left, right) {\n requireArity(arguments.length, 2, \"superset\");\n return subset(right, left);\n}\n\nexport function disjoint(left, right) {\n requireArity(arguments.length, 2, \"disjoint\");\n const leftSet = set(left);\n const rightSet = set(right);\n const candidates = count(leftSet) <= count(rightSet) ? leftSet : rightSet;\n const membership = candidates === leftSet ? rightSet : leftSet;\n return reduce(candidates, (result, value) =>\n contains(membership, value) ? reduced(false) : result, true);\n}\n\nexport function select(predicate, collection) {\n requireArity(arguments.length, 2, \"select\");\n requireFunction(predicate, \"select predicate\");\n const source = set(collection);\n const builder = transient(source);\n reduce(source, (result, value) => {\n if (!isTruthy(predicate(value))) dissocBang(result, value);\n return result;\n }, builder);\n const selected = persistentBang(builder);\n return count(selected) === count(source) ? source : selected;\n}\n\nexport function project(relation, selectedKeys) {\n requireArity(arguments.length, 2, \"project\");\n const source = set(relation);\n const keySet = set(selectedKeys);\n const builder = transient(empty(source));\n reduce(source, (result, row) => {\n conjBang(result, selectKeys(row, keySet));\n return result;\n }, builder);\n return persistentBang(builder);\n}\n\nexport function renameKeys(collection, keyMap) {\n requireArity(arguments.length, 2, \"renameKeys\");\n const source = persistentMap(collection);\n const mappings = persistentMap(keyMap);\n const builder = transient(source);\n reduceKV(mappings, (result, oldKey) => {\n dissocBang(result, oldKey);\n return result;\n }, builder);\n reduceKV(mappings, (result, oldKey, newKey) => {\n if (contains(source, oldKey)) {\n assocBang(result, newKey, get(source, oldKey));\n }\n return result;\n }, builder);\n return persistentBang(builder);\n}\n\nexport function rename(relation, keyMap) {\n requireArity(arguments.length, 2, \"rename\");\n const source = set(relation);\n const mappings = persistentMap(keyMap);\n const builder = transient(empty(source));\n reduce(source, (result, row) => {\n conjBang(result, renameKeys(row, mappings));\n return result;\n }, builder);\n return persistentBang(builder);\n}\n\nexport function index(relation, selectedKeys) {\n requireArity(arguments.length, 2, \"index\");\n const source = set(relation);\n const keySet = set(selectedKeys);\n return reduce(source, (result, row) => {\n const indexedKey = selectKeys(row, keySet);\n const group = get(result, indexedKey, EMPTY_SET);\n return assoc(result, indexedKey, conj(group, row));\n }, EMPTY_MAP);\n}\n\nexport function mapInvert(collection) {\n requireArity(arguments.length, 1, \"mapInvert\");\n const builder = transient(EMPTY_MAP);\n reduceKV(collection, (result, key, value) => {\n assocBang(result, value, key);\n return result;\n }, builder);\n return withMeta(persistentBang(builder), meta(collection));\n}\n\nfunction joinIndexed(probe, indexed, probeKeys, keyMap, builder) {\n return reduce(probe, (result, row) => {\n const selected = selectKeys(row, probeKeys);\n const indexedKey = keyMap === null\n ? selected\n : renameKeys(selected, keyMap);\n const matches = get(indexed, indexedKey, EMPTY_SET);\n reduce(matches, (output, matched) => {\n conjBang(output, merge(matched, row));\n return output;\n }, result);\n return result;\n }, builder);\n}\n\nexport function join(left, right, keyMap) {\n requireJoinArity(arguments.length);\n const leftSet = set(left);\n const rightSet = set(right);\n const builder = transient(empty(leftSet));\n if (count(leftSet) === 0 || count(rightSet) === 0) {\n return persistentBang(builder);\n }\n\n if (arguments.length === 2) {\n const leftRow = firstValue(leftSet).value;\n const rightRow = firstValue(rightSet).value;\n const joinKeys = intersection(set(keys(leftRow)), set(keys(rightRow)));\n const indexedRelation = count(leftSet) <= count(rightSet)\n ? leftSet\n : rightSet;\n const probeRelation = indexedRelation === leftSet ? rightSet : leftSet;\n return persistentBang(joinIndexed(\n probeRelation,\n index(indexedRelation, joinKeys),\n joinKeys,\n null,\n builder,\n ));\n }\n\n const mappings = persistentMap(keyMap);\n const effectiveMap = count(leftSet) <= count(rightSet)\n ? mapInvert(mappings)\n : mappings;\n const indexedRelation = count(leftSet) <= count(rightSet)\n ? leftSet\n : rightSet;\n const probeRelation = indexedRelation === leftSet ? rightSet : leftSet;\n return persistentBang(joinIndexed(\n probeRelation,\n index(indexedRelation, vals(effectiveMap)),\n keys(effectiveMap),\n effectiveMap,\n builder,\n ));\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.set-internals
|
|
2
|
+
(js* "export const SET_CONSTRUCTOR_TOKEN = Symbol(\"eliscript.set.constructor\");\nexport const SET_STATE = Symbol(\"eliscript.set.state\");\nexport const TRANSIENT_SET_CONSTRUCTOR_TOKEN = Symbol(\n \"eliscript.set.transient-constructor\",\n);\nexport const TRANSIENT_SET_STATE = Symbol(\"eliscript.set.transient-state\");\n\nconst transientMetrics = {\n persistentCalls: 0,\n invalidCalls: 0,\n};\n\nexport const SET_PRESENT = Object.freeze({\n [Symbol.toStringTag]: \"EliscriptPersistentHashSetEntry\",\n});\n\nexport function resetTransientSetMetrics() {\n for (const key of Object.keys(transientMetrics)) {\n transientMetrics[key] = 0;\n }\n}\n\nexport function readTransientSetMetrics() {\n return Object.freeze({ ...transientMetrics });\n}\n\nexport function recordTransientSetPersistent() {\n transientMetrics.persistentCalls += 1;\n}\n\nexport function recordInvalidTransientSetCall() {\n transientMetrics.invalidCalls += 1;\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.set
|
|
2
|
+
(js* "import {\n EMPTY_MAP,\n PersistentHashMap,\n} from \"./map.mjs\";\nimport {\n SET_CONSTRUCTOR_TOKEN,\n SET_PRESENT,\n SET_STATE,\n TRANSIENT_SET_CONSTRUCTOR_TOKEN,\n TRANSIENT_SET_STATE,\n recordInvalidTransientSetCall,\n recordTransientSetPersistent,\n} from \"./set-internals.mjs\";\nimport {\n VALUE_EQUAL,\n VALUE_HASH,\n unorderedCollectionHash,\n} from \"./value-internals.mjs\";\nimport {\n COLLECTION_COUNT,\n COLLECTION_EMPTY,\n COLLECTION_CONJ,\n COLLECTION_GET,\n COLLECTION_CONTAINS,\n COLLECTION_REDUCE,\n COLLECTION_DISJ,\n COLLECTION_SEQ,\n reduceIterable,\n sequenceView,\n} from \"./collection-internals.mjs\";\nimport {\n EDITABLE_TRANSIENT,\n TRANSIENT_ASSOC,\n TRANSIENT_CONJ,\n TRANSIENT_DISSOC,\n TRANSIENT_PERSISTENT,\n} from \"./transient-internals.mjs\";\nimport {\n METADATA_READ,\n METADATA_WITH,\n} from \"./metadata-internals.mjs\";\nimport {\n PERSISTENT_SET_HAS_VALUE,\n PERSISTENT_SET_KIND,\n persistentSetValueEqual,\n} from \"./persistent-kind.mjs\";\n\nconst SET_HASH_TAG = 0x51e7_b32d;\n\nfunction makeSet(map, metadata = null) {\n return new PersistentHashSet(SET_CONSTRUCTOR_TOKEN, map, metadata);\n}\n\nfunction emptySetWithMetadata(metadata) {\n return metadata === null ? EMPTY_SET : makeSet(EMPTY_MAP, metadata);\n}\n\nfunction makeTransientSet(set) {\n return new TransientHashSet(TRANSIENT_SET_CONSTRUCTOR_TOKEN, set);\n}\n\nfunction activeTransientSetState(set) {\n const state = set[TRANSIENT_SET_STATE];\n if (!state.active) {\n recordInvalidTransientSetCall();\n throw new TypeError(\"transient hash set is no longer editable\");\n }\n return state;\n}\n\nfunction asPersistentSet(values) {\n return values instanceof PersistentHashSet\n ? values\n : PersistentHashSet.from(values);\n}\n\nclass TransientHashSet {\n constructor(token, set) {\n if (token !== TRANSIENT_SET_CONSTRUCTOR_TOKEN ||\n !(set instanceof PersistentHashSet)) {\n throw new TypeError(\n \"transient hash sets must be created from a persistent hash set\",\n );\n }\n const sourceMap = set[SET_STATE].map;\n const metadata = set[SET_STATE].metadata;\n this[TRANSIENT_SET_STATE] = {\n active: true,\n source: set,\n sourceMap,\n map: sourceMap[EDITABLE_TRANSIENT](),\n metadata,\n };\n Object.defineProperty(this, \"__eliscript_transient__\", {\n enumerable: true,\n get() {\n throw new TypeError(\"transient hash sets cannot be serialized\");\n },\n });\n Object.freeze(this);\n }\n\n [TRANSIENT_CONJ](value) {\n const state = activeTransientSetState(this);\n state.map[TRANSIENT_ASSOC](value, SET_PRESENT);\n return this;\n }\n\n [TRANSIENT_DISSOC](value) {\n const state = activeTransientSetState(this);\n state.map[TRANSIENT_DISSOC](value);\n return this;\n }\n\n [TRANSIENT_PERSISTENT]() {\n const state = activeTransientSetState(this);\n const map = state.map[TRANSIENT_PERSISTENT]();\n const result = map === state.sourceMap\n ? state.source\n : (map === EMPTY_MAP\n ? emptySetWithMetadata(state.metadata)\n : makeSet(map, state.metadata));\n state.active = false;\n recordTransientSetPersistent();\n return result;\n }\n\n toJSON() {\n throw new TypeError(\"transient hash sets cannot be serialized\");\n }\n\n get [Symbol.toStringTag]() {\n return \"EliscriptTransientHashSet\";\n }\n}\n\nexport class PersistentHashSet {\n constructor(token, map, metadata = null) {\n if (token !== SET_CONSTRUCTOR_TOKEN || !(map instanceof PersistentHashMap)) {\n throw new TypeError(\n \"PersistentHashSet values must be created with persistentHashSet or PersistentHashSet.from\",\n );\n }\n this[SET_STATE] = Object.freeze({ map, metadata });\n Object.freeze(this);\n }\n\n static empty() {\n return EMPTY_SET;\n }\n\n static from(values) {\n if (values instanceof PersistentHashSet) {\n return values;\n }\n let result = EMPTY_SET;\n for (const value of values) {\n result = result.conj(value);\n }\n return result;\n }\n\n get count() {\n return this[SET_STATE].map.count;\n }\n\n get size() {\n return this[SET_STATE].map.count;\n }\n\n has(value) {\n return this[SET_STATE].map.has(value);\n }\n\n conj(value) {\n const state = this[SET_STATE];\n const map = state.map.assoc(value, SET_PRESENT);\n return map === state.map ? this : makeSet(map, state.metadata);\n }\n\n disj(value) {\n const state = this[SET_STATE];\n const map = state.map.dissoc(value);\n if (map === state.map) {\n return this;\n }\n return map === EMPTY_MAP\n ? emptySetWithMetadata(state.metadata)\n : makeSet(map, state.metadata);\n }\n\n union(...collections) {\n let result = this;\n for (const collection of collections) {\n for (const value of collection) {\n result = result.conj(value);\n }\n }\n return result;\n }\n\n intersection(...collections) {\n let result = this;\n for (const collection of collections) {\n const other = asPersistentSet(collection);\n if (result.count === 0) {\n return result;\n }\n const candidates = result.count <= other.count ? result : other;\n const membership = candidates === result ? other : result;\n let retained = emptySetWithMetadata(this[SET_STATE].metadata);\n for (const value of candidates) {\n if (membership.has(value)) {\n retained = retained.conj(value);\n }\n }\n result = retained.count === result.count ? result : retained;\n }\n return result;\n }\n\n difference(...collections) {\n let result = this;\n for (const collection of collections) {\n for (const value of collection) {\n result = result.disj(value);\n }\n if (result.count === 0) {\n return result;\n }\n }\n return result;\n }\n\n isSubsetOf(collection) {\n const other = asPersistentSet(collection);\n if (this.count > other.count) {\n return false;\n }\n for (const value of this) {\n if (!other.has(value)) {\n return false;\n }\n }\n return true;\n }\n\n isSupersetOf(collection) {\n return asPersistentSet(collection).isSubsetOf(this);\n }\n\n isDisjointFrom(collection) {\n const other = asPersistentSet(collection);\n const candidates = this.count <= other.count ? this : other;\n const membership = candidates === this ? other : this;\n for (const value of candidates) {\n if (membership.has(value)) {\n return false;\n }\n }\n return true;\n }\n\n values() {\n return this[SET_STATE].map.keys();\n }\n\n keys() {\n return this.values();\n }\n\n *entries() {\n for (const value of this) {\n yield Object.freeze([value, value]);\n }\n }\n\n reduce(reducer, initial) {\n if (typeof reducer !== \"function\") {\n throw new TypeError(\"persistent hash set reducer must be a function\");\n }\n if (arguments.length < 2) {\n throw new TypeError(\"persistent hash set reduce requires an initial value\");\n }\n let result = initial;\n for (const value of this) {\n result = reducer(result, value, this);\n }\n return result;\n }\n\n [COLLECTION_COUNT]() {\n return this.count;\n }\n\n [COLLECTION_EMPTY]() {\n return emptySetWithMetadata(this[SET_STATE].metadata);\n }\n\n [COLLECTION_CONJ](value) {\n return this.conj(value);\n }\n\n [COLLECTION_DISJ](value) {\n return this.disj(value);\n }\n\n [COLLECTION_GET](value, notFound = null) {\n return this.has(value) ? value : notFound;\n }\n\n [COLLECTION_CONTAINS](value) {\n return this.has(value);\n }\n\n [COLLECTION_SEQ]() {\n return this.count === 0\n ? null\n : sequenceView(() => this.values(), this.count);\n }\n\n [COLLECTION_REDUCE](reducer, ...initial) {\n return reduceIterable(this, reducer, ...initial);\n }\n\n [EDITABLE_TRANSIENT]() {\n return makeTransientSet(this);\n }\n\n toSet() {\n return new Set(this);\n }\n\n [PERSISTENT_SET_HAS_VALUE](value) {\n return this.has(value);\n }\n\n get [PERSISTENT_SET_KIND]() {\n return true;\n }\n\n [VALUE_EQUAL](other, equal) {\n return persistentSetValueEqual(this, other, equal);\n }\n\n [VALUE_HASH](hash) {\n return unorderedCollectionHash(this, hash, SET_HASH_TAG);\n }\n\n [METADATA_READ]() {\n return this[SET_STATE].metadata;\n }\n\n [METADATA_WITH](metadata) {\n const state = this[SET_STATE];\n return metadata === state.metadata\n ? this\n : makeSet(state.map, metadata);\n }\n\n [Symbol.iterator]() {\n return this.values();\n }\n\n get [Symbol.toStringTag]() {\n return \"EliscriptPersistentHashSet\";\n }\n}\n\nexport const EMPTY_SET = makeSet(EMPTY_MAP);\n\nexport function persistentHashSet(...values) {\n return PersistentHashSet.from(values);\n}\n\nexport function isPersistentHashSet(value) {\n return value instanceof PersistentHashSet;\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.sorted-internals
|
|
2
|
+
(js* "import { equalValues } from \"./value.mjs\";\n\nexport const SORTED_MAP_STATE = Symbol(\"eliscript.sorted-map.state\");\nexport const SORTED_SET_STATE = Symbol(\"eliscript.sorted-set.state\");\n\nconst metrics = {\n nodeAllocations: 0,\n comparisons: 0,\n rotations: 0,\n};\n\nfunction height(node) {\n return node === null ? 0 : node.height;\n}\n\nfunction size(node) {\n return node === null ? 0 : node.size;\n}\n\nexport class SortedNode {\n constructor(key, value, left = null, right = null) {\n this.key = key;\n this.value = value;\n this.left = left;\n this.right = right;\n this.height = Math.max(height(left), height(right)) + 1;\n this.size = size(left) + size(right) + 1;\n metrics.nodeAllocations += 1;\n Object.freeze(this);\n }\n}\n\nfunction node(key, value, left, right) {\n return new SortedNode(key, value, left, right);\n}\n\nfunction rotateLeft(root) {\n const promoted = root.right;\n const retained = node(root.key, root.value, root.left, promoted.left);\n metrics.rotations += 1;\n return node(promoted.key, promoted.value, retained, promoted.right);\n}\n\nfunction rotateRight(root) {\n const promoted = root.left;\n const retained = node(root.key, root.value, promoted.right, root.right);\n metrics.rotations += 1;\n return node(promoted.key, promoted.value, promoted.left, retained);\n}\n\nfunction balance(root) {\n const delta = height(root.left) - height(root.right);\n if (delta > 1) {\n const left = root.left;\n const prepared = height(left.left) < height(left.right)\n ? node(root.key, root.value, rotateLeft(left), root.right)\n : root;\n return rotateRight(prepared);\n }\n if (delta < -1) {\n const right = root.right;\n const prepared = height(right.right) < height(right.left)\n ? node(root.key, root.value, root.left, rotateRight(right))\n : root;\n return rotateLeft(prepared);\n }\n return root;\n}\n\nexport function compareSortedKeys(comparison, left, right) {\n metrics.comparisons += 1;\n return comparison(left, right);\n}\n\nexport function sortedFind(root, key, comparison) {\n let current = root;\n while (current !== null) {\n const order = compareSortedKeys(comparison, key, current.key);\n if (order === 0) return current;\n current = order < 0 ? current.left : current.right;\n }\n return null;\n}\n\nexport function sortedAssoc(root, key, value, comparison) {\n if (root === null) {\n return { root: node(key, value, null, null), added: true, changed: true };\n }\n const order = compareSortedKeys(comparison, key, root.key);\n if (order === 0) {\n if (equalValues(root.value, value)) {\n return { root, added: false, changed: false };\n }\n return {\n root: node(root.key, value, root.left, root.right),\n added: false,\n changed: true,\n };\n }\n const side = order < 0 ? \"left\" : \"right\";\n const result = sortedAssoc(root[side], key, value, comparison);\n if (!result.changed) return { root, added: result.added, changed: false };\n const updated = side === \"left\"\n ? node(root.key, root.value, result.root, root.right)\n : node(root.key, root.value, root.left, result.root);\n return { root: balance(updated), added: result.added, changed: true };\n}\n\nfunction minimum(root) {\n let current = root;\n while (current.left !== null) current = current.left;\n return current;\n}\n\nfunction removeMinimum(root) {\n if (root.left === null) return root.right;\n return balance(node(\n root.key,\n root.value,\n removeMinimum(root.left),\n root.right,\n ));\n}\n\nexport function sortedDissoc(root, key, comparison) {\n if (root === null) return { root, removed: false };\n const order = compareSortedKeys(comparison, key, root.key);\n if (order === 0) {\n if (root.left === null) return { root: root.right, removed: true };\n if (root.right === null) return { root: root.left, removed: true };\n const successor = minimum(root.right);\n return {\n root: balance(node(\n successor.key,\n successor.value,\n root.left,\n removeMinimum(root.right),\n )),\n removed: true,\n };\n }\n const side = order < 0 ? \"left\" : \"right\";\n const result = sortedDissoc(root[side], key, comparison);\n if (!result.removed) return { root, removed: false };\n const updated = side === \"left\"\n ? node(root.key, root.value, result.root, root.right)\n : node(root.key, root.value, root.left, result.root);\n return { root: balance(updated), removed: true };\n}\n\nfunction eligibleStart(order, ascending, inclusive) {\n return ascending\n ? order > 0 || (inclusive && order === 0)\n : order < 0 || (inclusive && order === 0);\n}\n\nfunction pushStart(stack, root, comparison, ascending, start) {\n let current = root;\n while (current !== null) {\n if (start === null) {\n stack.push(current);\n current = ascending ? current.left : current.right;\n continue;\n }\n const order = compareSortedKeys(comparison, current.key, start.key);\n if (eligibleStart(order, ascending, start.inclusive)) {\n stack.push(current);\n current = ascending ? current.left : current.right;\n } else {\n current = ascending ? current.right : current.left;\n }\n }\n}\n\nfunction beyondEnd(order, ascending, inclusive) {\n return ascending\n ? order > 0 || (!inclusive && order === 0)\n : order < 0 || (!inclusive && order === 0);\n}\n\nexport function* sortedEntries(\n root,\n comparison,\n ascending = true,\n start = null,\n end = null,\n) {\n const stack = [];\n pushStart(stack, root, comparison, ascending, start);\n while (stack.length > 0) {\n const current = stack.pop();\n if (end !== null) {\n const order = compareSortedKeys(comparison, current.key, end.key);\n if (beyondEnd(order, ascending, end.inclusive)) return;\n }\n yield current;\n pushStart(\n stack,\n ascending ? current.right : current.left,\n comparison,\n ascending,\n null,\n );\n }\n}\n\nexport function resetSortedMetrics() {\n metrics.nodeAllocations = 0;\n metrics.comparisons = 0;\n metrics.rotations = 0;\n}\n\nexport function readSortedMetrics() {\n return Object.freeze({ ...metrics });\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.sorted
|
|
2
|
+
(js* "import {\n COLLECTION_ASSOC,\n COLLECTION_CONJ,\n COLLECTION_CONTAINS,\n COLLECTION_COUNT,\n COLLECTION_DISSOC,\n COLLECTION_DISJ,\n COLLECTION_EMPTY,\n COLLECTION_GET,\n COLLECTION_REDUCE,\n COLLECTION_REDUCE_KV,\n COLLECTION_RSEQ,\n COLLECTION_SEQ,\n isReducedValue,\n readCollectionEntry,\n reduceIterable,\n sequenceView,\n unreducedValue,\n} from \"./collection-internals.mjs\";\nimport { identifierName, identifierNamespace, isKeyword } from \"./identifier.mjs\";\nimport { METADATA_READ, METADATA_WITH } from \"./metadata-internals.mjs\";\nimport { comparator, compareValues } from \"./order.mjs\";\nimport {\n PERSISTENT_MAP_HAS_VALUE_KEY,\n PERSISTENT_MAP_KIND,\n PERSISTENT_SET_HAS_VALUE,\n PERSISTENT_SET_KIND,\n persistentMapValueEqual,\n persistentSetValueEqual,\n} from \"./persistent-kind.mjs\";\nimport {\n SORTED_MAP_STATE,\n SORTED_SET_STATE,\n SortedNode,\n sortedAssoc,\n sortedDissoc,\n sortedEntries,\n sortedFind,\n} from \"./sorted-internals.mjs\";\nimport {\n VALUE_EQUAL,\n VALUE_HASH,\n finishHash,\n mixHash,\n unorderedCollectionHash,\n} from \"./value-internals.mjs\";\nimport { equalValues } from \"./value.mjs\";\n\nconst SORTED_MAP_TOKEN = Symbol(\"eliscript.sorted-map.constructor-token\");\nconst SORTED_SET_TOKEN = Symbol(\"eliscript.sorted-set.constructor-token\");\nconst NOT_FOUND = Symbol(\"eliscript.sorted.not-found\");\nconst PRESENT = Object.freeze({});\nconst MAP_HASH_TAG = 0x6c8e_9cf5;\nconst MAP_ENTRY_HASH_TAG = 0x3a91_72eb;\nconst SET_HASH_TAG = 0x51e7_b32d;\nconst BOUND_TESTS = new Set([\"<\", \"<=\", \">\", \">=\"]);\nconst DEFAULT_COMPARATOR = comparator(compareValues);\n\nexport function isDefaultSortedComparator(value) {\n return value === DEFAULT_COMPARATOR;\n}\n\nexport function defaultSortedComparator() {\n return DEFAULT_COMPARATOR;\n}\n\nfunction normalizeComparator(comparison) {\n return comparison === compareValues || comparison === DEFAULT_COMPARATOR\n ? DEFAULT_COMPARATOR\n : comparator(comparison);\n}\n\nfunction makeMap(root, comparison, metadata = null) {\n return new PersistentSortedMap(\n SORTED_MAP_TOKEN,\n root,\n comparison,\n metadata,\n );\n}\n\nfunction makeSet(map, metadata = null) {\n return new PersistentSortedSet(SORTED_SET_TOKEN, map, metadata);\n}\n\nexport function readSortedMapState(value) {\n if (!(value instanceof PersistentSortedMap)) return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(value, SORTED_MAP_STATE);\n return descriptor !== undefined && \"value\" in descriptor ? descriptor.value : undefined;\n}\n\nexport function readSortedSetState(value) {\n if (!(value instanceof PersistentSortedSet)) return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(value, SORTED_SET_STATE);\n return descriptor !== undefined && \"value\" in descriptor ? descriptor.value : undefined;\n}\n\n// Transport already supplies ordered, unique data. Rebuild only its physical\n// host representation; normalizing or comparing again would invoke user code\n// a second time and change the comparator's observable identity.\nfunction materializeSortedRoot(values, set, start, end) {\n if (start === end) return null;\n const middle = start + Math.floor((end - start) / 2);\n const item = values[middle];\n if (!set && (!Array.isArray(item) || item.length !== 2)) {\n throw new TypeError(\"invalid sorted map transport entry\");\n }\n return new SortedNode(\n set ? item : item[0],\n set ? PRESENT : item[1],\n materializeSortedRoot(values, set, start, middle),\n materializeSortedRoot(values, set, middle + 1, end),\n );\n}\n\nexport function materializeSortedMap(entries, comparison, metadata = null) {\n if (!Array.isArray(entries) || typeof comparison !== \"function\") {\n throw new TypeError(\"invalid sorted map transport record\");\n }\n return makeMap(materializeSortedRoot(entries, false, 0, entries.length), comparison, metadata);\n}\n\nexport function materializeSortedSet(values, comparison, metadata = null) {\n if (!Array.isArray(values) || typeof comparison !== \"function\") {\n throw new TypeError(\"invalid sorted set transport record\");\n }\n return makeSet(makeMap(materializeSortedRoot(values, true, 0, values.length), comparison), metadata);\n}\n\nfunction mapPairHash(entry, hash) {\n return finishHash(\n mixHash(mixHash(MAP_ENTRY_HASH_TAG, hash(entry[0])), hash(entry[1])),\n 2,\n );\n}\n\nfunction mapIterator(root, comparison, ascending, start = null, end = null) {\n const nodes = sortedEntries(root, comparison, ascending, start, end);\n return (function* entries() {\n for (const item of nodes) {\n yield Object.freeze([item.key, item.value]);\n }\n })();\n}\n\nfunction setIterator(root, comparison, ascending, start = null, end = null) {\n const nodes = sortedEntries(root, comparison, ascending, start, end);\n return (function* values() {\n for (const item of nodes) yield item.key;\n })();\n}\n\nfunction sequenceOrNull(factory) {\n const probe = factory();\n try {\n if (probe.next().done) return null;\n } finally {\n if (typeof probe.return === \"function\") probe.return();\n }\n return sequenceView(factory);\n}\n\nexport class PersistentSortedMap {\n constructor(token, root, comparison, metadata = null) {\n if (token !== SORTED_MAP_TOKEN || typeof comparison !== \"function\") {\n throw new TypeError(\n \"PersistentSortedMap values must be created with persistentSortedMap or persistentSortedMapBy\",\n );\n }\n this[SORTED_MAP_STATE] = Object.freeze({ root, comparison, metadata });\n Object.freeze(this);\n }\n\n static empty(comparison = compareValues) {\n return emptySortedMapBy(comparison);\n }\n\n static from(entries, comparison = compareValues) {\n if (entries instanceof PersistentSortedMap && arguments.length === 1) {\n return entries;\n }\n let result = emptySortedMapBy(comparison);\n for (const entry of entries) {\n const [key, value] = readCollectionEntry(entry);\n result = result.assoc(key, value);\n }\n return result;\n }\n\n get count() {\n return this[SORTED_MAP_STATE].root?.size ?? 0;\n }\n\n get size() {\n return this.count;\n }\n\n get comparator() {\n return this[SORTED_MAP_STATE].comparison;\n }\n\n get(key, notFound = null) {\n const state = this[SORTED_MAP_STATE];\n const found = sortedFind(state.root, key, state.comparison);\n return found === null ? notFound : found.value;\n }\n\n has(key) {\n const state = this[SORTED_MAP_STATE];\n return sortedFind(state.root, key, state.comparison) !== null;\n }\n\n assoc(key, value) {\n const state = this[SORTED_MAP_STATE];\n const result = sortedAssoc(state.root, key, value, state.comparison);\n return result.changed\n ? makeMap(result.root, state.comparison, state.metadata)\n : this;\n }\n\n dissoc(key) {\n const state = this[SORTED_MAP_STATE];\n const result = sortedDissoc(state.root, key, state.comparison);\n return result.removed\n ? makeMap(result.root, state.comparison, state.metadata)\n : this;\n }\n\n entries(ascending = true) {\n const state = this[SORTED_MAP_STATE];\n return mapIterator(state.root, state.comparison, ascending);\n }\n\n keys(ascending = true) {\n const entries = this.entries(ascending);\n return (function* keys() {\n for (const entry of entries) yield entry[0];\n })();\n }\n\n values(ascending = true) {\n const entries = this.entries(ascending);\n return (function* values() {\n for (const entry of entries) yield entry[1];\n })();\n }\n\n [COLLECTION_COUNT]() {\n return this.count;\n }\n\n [COLLECTION_EMPTY]() {\n const state = this[SORTED_MAP_STATE];\n return makeMap(null, state.comparison, state.metadata);\n }\n\n [COLLECTION_CONJ](entry) {\n const [key, value] = readCollectionEntry(entry);\n return this.assoc(key, value);\n }\n\n [COLLECTION_GET](key, notFound = null) {\n return this.get(key, notFound);\n }\n\n [COLLECTION_ASSOC](key, value) {\n return this.assoc(key, value);\n }\n\n [COLLECTION_CONTAINS](key) {\n return this.has(key);\n }\n\n [COLLECTION_DISSOC](key) {\n return this.dissoc(key);\n }\n\n [COLLECTION_SEQ]() {\n return this.count === 0\n ? null\n : sequenceView(() => this.entries(), this.count);\n }\n\n [COLLECTION_RSEQ]() {\n return this.count === 0\n ? null\n : sequenceView(() => this.entries(false), this.count);\n }\n\n [COLLECTION_REDUCE](reducer, ...initial) {\n return reduceIterable(this, reducer, ...initial);\n }\n\n [COLLECTION_REDUCE_KV](reducer, initial) {\n let result = initial;\n for (const [key, value] of this) {\n result = reducer(result, key, value);\n if (isReducedValue(result)) return unreducedValue(result);\n }\n return result;\n }\n\n [PERSISTENT_MAP_HAS_VALUE_KEY](key) {\n const state = this[SORTED_MAP_STATE];\n const found = sortedFind(state.root, key, state.comparison);\n return found !== null && equalValues(found.key, key);\n }\n\n get [PERSISTENT_MAP_KIND]() {\n return true;\n }\n\n [VALUE_EQUAL](other, equal) {\n return persistentMapValueEqual(this, other, equal);\n }\n\n [VALUE_HASH](hash) {\n return unorderedCollectionHash(this, (entry) => mapPairHash(entry, hash), MAP_HASH_TAG);\n }\n\n [METADATA_READ]() {\n return this[SORTED_MAP_STATE].metadata;\n }\n\n [METADATA_WITH](metadata) {\n const state = this[SORTED_MAP_STATE];\n return metadata === state.metadata\n ? this\n : makeMap(state.root, state.comparison, metadata);\n }\n\n [Symbol.iterator]() {\n return this.entries();\n }\n\n get [Symbol.toStringTag]() {\n return \"EliscriptPersistentSortedMap\";\n }\n}\n\nexport class PersistentSortedSet {\n constructor(token, map, metadata = null) {\n if (token !== SORTED_SET_TOKEN || !(map instanceof PersistentSortedMap)) {\n throw new TypeError(\n \"PersistentSortedSet values must be created with persistentSortedSet or persistentSortedSetBy\",\n );\n }\n this[SORTED_SET_STATE] = Object.freeze({ map, metadata });\n Object.freeze(this);\n }\n\n static empty(comparison = compareValues) {\n return emptySortedSetBy(comparison);\n }\n\n static from(values, comparison = compareValues) {\n if (values instanceof PersistentSortedSet && arguments.length === 1) {\n return values;\n }\n let result = emptySortedSetBy(comparison);\n for (const value of values) result = result.conj(value);\n return result;\n }\n\n get count() {\n return this[SORTED_SET_STATE].map.count;\n }\n\n get size() {\n return this.count;\n }\n\n get comparator() {\n return this[SORTED_SET_STATE].map.comparator;\n }\n\n has(value) {\n return this[SORTED_SET_STATE].map.has(value);\n }\n\n conj(value) {\n const state = this[SORTED_SET_STATE];\n const map = state.map.assoc(value, PRESENT);\n return map === state.map ? this : makeSet(map, state.metadata);\n }\n\n disj(value) {\n const state = this[SORTED_SET_STATE];\n const map = state.map.dissoc(value);\n return map === state.map ? this : makeSet(map, state.metadata);\n }\n\n values(ascending = true) {\n const state = this[SORTED_SET_STATE].map[SORTED_MAP_STATE];\n return setIterator(state.root, state.comparison, ascending);\n }\n\n keys(ascending = true) {\n return this.values(ascending);\n }\n\n *entries(ascending = true) {\n for (const value of this.values(ascending)) {\n yield Object.freeze([value, value]);\n }\n }\n\n [COLLECTION_COUNT]() {\n return this.count;\n }\n\n [COLLECTION_EMPTY]() {\n const state = this[SORTED_SET_STATE];\n return makeSet(state.map[COLLECTION_EMPTY](), state.metadata);\n }\n\n [COLLECTION_CONJ](value) {\n return this.conj(value);\n }\n\n [COLLECTION_DISJ](value) {\n return this.disj(value);\n }\n\n [COLLECTION_GET](value, notFound = null) {\n const state = this[SORTED_SET_STATE].map[SORTED_MAP_STATE];\n const found = sortedFind(state.root, value, state.comparison);\n return found === null ? notFound : found.key;\n }\n\n [COLLECTION_CONTAINS](value) {\n return this.has(value);\n }\n\n [COLLECTION_SEQ]() {\n return this.count === 0\n ? null\n : sequenceView(() => this.values(), this.count);\n }\n\n [COLLECTION_RSEQ]() {\n return this.count === 0\n ? null\n : sequenceView(() => this.values(false), this.count);\n }\n\n [COLLECTION_REDUCE](reducer, ...initial) {\n return reduceIterable(this, reducer, ...initial);\n }\n\n [PERSISTENT_SET_HAS_VALUE](value, equal) {\n const state = this[SORTED_SET_STATE].map[SORTED_MAP_STATE];\n const found = sortedFind(state.root, value, state.comparison);\n return found !== null && equal(found.key, value);\n }\n\n get [PERSISTENT_SET_KIND]() {\n return true;\n }\n\n [VALUE_EQUAL](other, equal) {\n return persistentSetValueEqual(this, other, equal);\n }\n\n [VALUE_HASH](hash) {\n return unorderedCollectionHash(this, hash, SET_HASH_TAG);\n }\n\n [METADATA_READ]() {\n return this[SORTED_SET_STATE].metadata;\n }\n\n [METADATA_WITH](metadata) {\n const state = this[SORTED_SET_STATE];\n return metadata === state.metadata\n ? this\n : makeSet(state.map, metadata);\n }\n\n [Symbol.iterator]() {\n return this.values();\n }\n\n get [Symbol.toStringTag]() {\n return \"EliscriptPersistentSortedSet\";\n }\n}\n\nexport const EMPTY_SORTED_MAP = makeMap(null, DEFAULT_COMPARATOR);\nexport const EMPTY_SORTED_SET = makeSet(EMPTY_SORTED_MAP);\n\nexport function emptySortedMapBy(comparison) {\n const normalized = normalizeComparator(comparison);\n return normalized === DEFAULT_COMPARATOR\n ? EMPTY_SORTED_MAP\n : makeMap(null, normalized);\n}\n\nexport function emptySortedSetBy(comparison) {\n const map = emptySortedMapBy(comparison);\n return map === EMPTY_SORTED_MAP ? EMPTY_SORTED_SET : makeSet(map);\n}\n\nfunction requireEvenKeyValues(keyValues, label) {\n if (keyValues.length % 2 !== 0) {\n throw new TypeError(`${label} expects an even number of key/value forms`);\n }\n}\n\nfunction populateMap(map, keyValues) {\n let result = map;\n for (let index = 0; index < keyValues.length; index += 2) {\n result = result.assoc(keyValues[index], keyValues[index + 1]);\n }\n return result;\n}\n\nexport function persistentSortedMap(...keyValues) {\n requireEvenKeyValues(keyValues, \"persistentSortedMap\");\n return populateMap(EMPTY_SORTED_MAP, keyValues);\n}\n\nexport function persistentSortedMapBy(comparison, ...keyValues) {\n requireEvenKeyValues(keyValues, \"persistentSortedMapBy\");\n return populateMap(emptySortedMapBy(comparison), keyValues);\n}\n\nexport function persistentSortedSet(...values) {\n let result = EMPTY_SORTED_SET;\n for (const value of values) result = result.conj(value);\n return result;\n}\n\nexport function persistentSortedSetBy(comparison, ...values) {\n let result = emptySortedSetBy(comparison);\n for (const value of values) result = result.conj(value);\n return result;\n}\n\nexport function isPersistentSortedMap(value) {\n return value instanceof PersistentSortedMap;\n}\n\nexport function isPersistentSortedSet(value) {\n return value instanceof PersistentSortedSet;\n}\n\nexport function isPersistentSortedCollection(value) {\n return isPersistentSortedMap(value) || isPersistentSortedSet(value);\n}\n\nfunction sortedState(collection) {\n if (collection instanceof PersistentSortedMap) {\n const state = collection[SORTED_MAP_STATE];\n return {\n root: state.root,\n comparison: state.comparison,\n factory: (ascending, start, end) =>\n mapIterator(state.root, state.comparison, ascending, start, end),\n };\n }\n if (collection instanceof PersistentSortedSet) {\n const state = collection[SORTED_SET_STATE].map[SORTED_MAP_STATE];\n return {\n root: state.root,\n comparison: state.comparison,\n factory: (ascending, start, end) =>\n setIterator(state.root, state.comparison, ascending, start, end),\n };\n }\n throw new TypeError(\"operation requires a persistent sorted collection\");\n}\n\nfunction requireBoolean(value, label) {\n if (typeof value !== \"boolean\") throw new TypeError(`${label} must be a boolean`);\n return value;\n}\n\nexport function sortedComparator(collection) {\n return sortedState(collection).comparison;\n}\n\nexport function sortedSequence(collection, ascending = true) {\n requireBoolean(ascending, \"sortedSequence ascending\");\n const state = sortedState(collection);\n return state.root === null\n ? null\n : sequenceView(() => state.factory(ascending, null, null), state.root.size);\n}\n\nexport function sortedSequenceFrom(\n collection,\n key,\n ascending = true,\n inclusive = true,\n) {\n requireBoolean(ascending, \"sortedSequenceFrom ascending\");\n requireBoolean(inclusive, \"sortedSequenceFrom inclusive\");\n const state = sortedState(collection);\n const start = { key, inclusive };\n return sequenceOrNull(() => state.factory(ascending, start, null));\n}\n\nfunction boundTestName(test) {\n const name = isKeyword(test) && identifierNamespace(test) === null\n ? identifierName(test)\n : test;\n if (typeof name !== \"string\" || !BOUND_TESTS.has(name)) {\n throw new TypeError(\"sorted bound test must be one of :<, :<=, :>, or :>=\");\n }\n return name;\n}\n\nfunction rangeBounds(bounds) {\n if (bounds.length !== 2 && bounds.length !== 4) {\n throw new TypeError(\"subsequence expects one or two test/key bounds\");\n }\n const firstTest = boundTestName(bounds[0]);\n const first = { key: bounds[1], inclusive: firstTest.includes(\"=\") };\n if (bounds.length === 2) {\n return firstTest.startsWith(\">\")\n ? { lower: first, upper: null }\n : { lower: null, upper: first };\n }\n const secondTest = boundTestName(bounds[2]);\n if (!firstTest.startsWith(\">\") || !secondTest.startsWith(\"<\")) {\n throw new TypeError(\n \"two-bound subsequence requires a lower :>/:>= bound then an upper :</:<= bound\",\n );\n }\n return {\n lower: first,\n upper: { key: bounds[3], inclusive: secondTest.includes(\"=\") },\n };\n}\n\nfunction rangeSequence(collection, ascending, bounds) {\n const state = sortedState(collection);\n const normalized = rangeBounds(bounds);\n const start = ascending ? normalized.lower : normalized.upper;\n const end = ascending ? normalized.upper : normalized.lower;\n return sequenceOrNull(() => state.factory(ascending, start, end));\n}\n\nexport function subsequence(collection, ...bounds) {\n return rangeSequence(collection, true, bounds);\n}\n\nexport function reverseSubsequence(collection, ...bounds) {\n return rangeSequence(collection, false, bounds);\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.text
|
|
2
|
+
(js* "export {\n blank_QMARK_ as blank,\n contains_QMARK_ as contains,\n empty_QMARK_ as empty,\n ends_with_QMARK_ as endsWith,\n join,\n repeat,\n slice,\n starts_at_QMARK_ as startsAt,\n starts_with_QMARK_ as startsWith,\n strip_prefix as stripPrefix,\n strip_suffix as stripSuffix,\n trim,\n whitespace_QMARK_ as whitespace,\n} from \"./text-impl.mjs\";\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.transducer
|
|
2
|
+
(js* "import {\n conj,\n contains,\n empty,\n isReduced,\n memoizedSequenceView,\n reduce,\n reduced,\n reductionView,\n seq,\n unreduced,\n} from \"./collection.mjs\";\nimport { implementsProtocolOperation } from \"./protocol.mjs\";\nimport { EMPTY_SET } from \"./set.mjs\";\nimport {\n IEditable,\n conjBang,\n persistentBang,\n transient,\n} from \"./transient.mjs\";\nimport { isTruthy } from \"./truth.mjs\";\nimport { equalValues } from \"./value.mjs\";\nimport { EMPTY_VECTOR } from \"./vector.mjs\";\n\nconst REDUCING_FUNCTION = Symbol(\"eliscript.transducer.reducing-function\");\nconst ZERO_INPUT = Symbol(\"eliscript.transducer.zero-input\");\nconst NO_PREVIOUS_VALUE = Symbol(\"eliscript.transducer.no-previous-value\");\nconst NO_PARTITION_KEY = Symbol(\"eliscript.transducer.no-partition-key\");\nconst NO_REDUCTION_INITIAL = Symbol(\"eliscript.transducer.no-reduction-initial\");\n\nfunction identity(value) {\n return value;\n}\n\nfunction requireFunction(value, label) {\n if (typeof value !== \"function\") {\n throw new TypeError(`${label} must be a function`);\n }\n return value;\n}\n\nfunction requirePositiveSafeInteger(value, label) {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new TypeError(`${label} must be a positive safe integer`);\n }\n return value;\n}\n\nfunction asReducingFunction(value, label) {\n requireFunction(value, label);\n return value[REDUCING_FUNCTION] === true ? value : completing(value);\n}\n\nfunction makeTransducer(transform, zeroInput = false) {\n Object.defineProperty(transform, ZERO_INPUT, { value: zeroInput });\n return Object.freeze(transform);\n}\n\nfunction applyTransducer(transducer, reducingFunction) {\n requireFunction(transducer, \"transducer\");\n return asReducingFunction(\n transducer(reducingFunction),\n \"transducer result\",\n );\n}\n\nfunction createPartitionBuffer() {\n let builder = transient(EMPTY_VECTOR);\n let length = 0;\n return Object.freeze({\n append(value) {\n builder = conjBang(builder, value);\n length += 1;\n return length;\n },\n flush(result, downstream) {\n if (length === 0) return result;\n const partition = persistentBang(builder);\n builder = transient(EMPTY_VECTOR);\n length = 0;\n return downstream(result, partition);\n },\n });\n}\n\nconst IDENTITY_TRANSDUCER = makeTransducer((reducingFunction) =>\n reducingFunction);\n\nexport function completing(step, complete = identity) {\n requireFunction(step, \"reducing step\");\n requireFunction(complete, \"reducing completion\");\n\n const reducingFunction = (...arguments_) => {\n if (arguments_.length === 1) {\n return complete(arguments_[0]);\n }\n if (arguments_.length === 2) {\n return step(arguments_[0], arguments_[1]);\n }\n throw new TypeError(\n \"reducing functions accept one completion argument or two step arguments\",\n );\n };\n Object.defineProperty(reducingFunction, REDUCING_FUNCTION, { value: true });\n return Object.freeze(reducingFunction);\n}\n\nexport function mapping(transform) {\n requireFunction(transform, \"mapping transform\");\n return makeTransducer((reducingFunction) => {\n const downstream = asReducingFunction(\n reducingFunction,\n \"mapping reducing function\",\n );\n return completing(\n (result, input) => downstream(result, transform(input)),\n (result) => downstream(result),\n );\n });\n}\n\nexport function mappingIndexed(transform) {\n requireFunction(transform, \"mapping-indexed transform\");\n return makeTransducer((reducingFunction) => {\n const downstream = asReducingFunction(\n reducingFunction,\n \"mapping-indexed reducing function\",\n );\n let index = 0;\n return completing(\n (result, input) => {\n const currentIndex = index;\n index += 1;\n return downstream(result, transform(currentIndex, input));\n },\n (result) => downstream(result),\n );\n });\n}\n\nexport function keeping(transform) {\n requireFunction(transform, \"keeping transform\");\n return makeTransducer((reducingFunction) => {\n const downstream = asReducingFunction(\n reducingFunction,\n \"keeping reducing function\",\n );\n return completing(\n (result, input) => {\n const value = transform(input);\n return value === null ? result : downstream(result, value);\n },\n (result) => downstream(result),\n );\n });\n}\n\nexport function keepingIndexed(transform) {\n requireFunction(transform, \"keeping-indexed transform\");\n return makeTransducer((reducingFunction) => {\n const downstream = asReducingFunction(\n reducingFunction,\n \"keeping-indexed reducing function\",\n );\n let index = 0;\n return completing(\n (result, input) => {\n const currentIndex = index;\n index += 1;\n const value = transform(currentIndex, input);\n return value === null ? result : downstream(result, value);\n },\n (result) => downstream(result),\n );\n });\n}\n\nexport function catting() {\n return makeTransducer((reducingFunction) => {\n const downstream = asReducingFunction(\n reducingFunction,\n \"catting reducing function\",\n );\n return completing(\n (result, input) => {\n let stopped = false;\n const flattened = reduce(\n input,\n (nestedResult, value) => {\n const stepped = downstream(nestedResult, value);\n if (isReduced(stepped)) stopped = true;\n return stepped;\n },\n result,\n );\n return stopped ? reduced(flattened) : flattened;\n },\n (result) => downstream(result),\n );\n });\n}\n\nexport function mapcatting(transform) {\n requireFunction(transform, \"mapcatting transform\");\n return composeTransducers(mapping(transform), catting());\n}\n\nexport function filtering(predicate) {\n requireFunction(predicate, \"filtering predicate\");\n return makeTransducer((reducingFunction) => {\n const downstream = asReducingFunction(\n reducingFunction,\n \"filtering reducing function\",\n );\n return completing(\n (result, input) => isTruthy(predicate(input))\n ? downstream(result, input)\n : result,\n (result) => downstream(result),\n );\n });\n}\n\nexport function removing(predicate) {\n requireFunction(predicate, \"removing predicate\");\n return makeTransducer((reducingFunction) => {\n const downstream = asReducingFunction(\n reducingFunction,\n \"removing reducing function\",\n );\n return completing(\n (result, input) => isTruthy(predicate(input))\n ? result\n : downstream(result, input),\n (result) => downstream(result),\n );\n });\n}\n\nexport function taking(limit) {\n if (!Number.isSafeInteger(limit) || limit < 0) {\n throw new TypeError(\"taking limit must be a non-negative safe integer\");\n }\n return makeTransducer((reducingFunction) => {\n const downstream = asReducingFunction(\n reducingFunction,\n \"taking reducing function\",\n );\n let remaining = limit;\n return completing(\n (result, input) => {\n if (remaining === 0) {\n return reduced(result);\n }\n remaining -= 1;\n const stepped = downstream(result, input);\n return remaining === 0 && !isReduced(stepped)\n ? reduced(stepped)\n : stepped;\n },\n (result) => downstream(result),\n );\n }, limit === 0);\n}\n\nexport function dropping(limit) {\n if (!Number.isSafeInteger(limit) || limit < 0) {\n throw new TypeError(\"dropping limit must be a non-negative safe integer\");\n }\n return makeTransducer((reducingFunction) => {\n const downstream = asReducingFunction(\n reducingFunction,\n \"dropping reducing function\",\n );\n let remaining = limit;\n return completing(\n (result, input) => {\n if (remaining > 0) {\n remaining -= 1;\n return result;\n }\n return downstream(result, input);\n },\n (result) => downstream(result),\n );\n });\n}\n\nexport function takingWhile(predicate) {\n requireFunction(predicate, \"taking-while predicate\");\n return makeTransducer((reducingFunction) => {\n const downstream = asReducingFunction(\n reducingFunction,\n \"taking-while reducing function\",\n );\n return completing(\n (result, input) => isTruthy(predicate(input))\n ? downstream(result, input)\n : reduced(result),\n (result) => downstream(result),\n );\n });\n}\n\nexport function droppingWhile(predicate) {\n requireFunction(predicate, \"dropping-while predicate\");\n return makeTransducer((reducingFunction) => {\n const downstream = asReducingFunction(\n reducingFunction,\n \"dropping-while reducing function\",\n );\n let dropping = true;\n return completing(\n (result, input) => {\n if (dropping && isTruthy(predicate(input))) return result;\n dropping = false;\n return downstream(result, input);\n },\n (result) => downstream(result),\n );\n });\n}\n\nexport function takingNth(interval) {\n requirePositiveSafeInteger(interval, \"taking-nth interval\");\n return makeTransducer((reducingFunction) => {\n const downstream = asReducingFunction(\n reducingFunction,\n \"taking-nth reducing function\",\n );\n let remaining = 0;\n return completing(\n (result, input) => {\n if (remaining > 0) {\n remaining -= 1;\n return result;\n }\n remaining = interval - 1;\n return downstream(result, input);\n },\n (result) => downstream(result),\n );\n });\n}\n\nexport function interposing(separator) {\n return makeTransducer((reducingFunction) => {\n const downstream = asReducingFunction(\n reducingFunction,\n \"interposing reducing function\",\n );\n let started = false;\n return completing(\n (result, input) => {\n if (!started) {\n started = true;\n return downstream(result, input);\n }\n const separated = downstream(result, separator);\n return isReduced(separated)\n ? separated\n : downstream(separated, input);\n },\n (result) => downstream(result),\n );\n });\n}\n\nexport function partitioningAll(size) {\n requirePositiveSafeInteger(size, \"partitioning-all size\");\n return makeTransducer((reducingFunction) => {\n const downstream = asReducingFunction(\n reducingFunction,\n \"partitioning-all reducing function\",\n );\n const buffer = createPartitionBuffer();\n return completing(\n (result, input) => buffer.append(input) === size\n ? buffer.flush(result, downstream)\n : result,\n (result) => downstream(unreduced(buffer.flush(result, downstream))),\n );\n });\n}\n\nexport function partitioningBy(classifier) {\n requireFunction(classifier, \"partitioning-by classifier\");\n return makeTransducer((reducingFunction) => {\n const downstream = asReducingFunction(\n reducingFunction,\n \"partitioning-by reducing function\",\n );\n const buffer = createPartitionBuffer();\n let previousKey = NO_PARTITION_KEY;\n return completing(\n (result, input) => {\n const key = classifier(input);\n if (previousKey === NO_PARTITION_KEY || equalValues(previousKey, key)) {\n previousKey = key;\n buffer.append(input);\n return result;\n }\n const stepped = buffer.flush(result, downstream);\n if (isReduced(stepped)) return stepped;\n previousKey = key;\n buffer.append(input);\n return stepped;\n },\n (result) => downstream(unreduced(buffer.flush(result, downstream))),\n );\n });\n}\n\nexport function deduping() {\n return makeTransducer((reducingFunction) => {\n const downstream = asReducingFunction(\n reducingFunction,\n \"deduping reducing function\",\n );\n let previous = NO_PREVIOUS_VALUE;\n return completing(\n (result, input) => {\n if (previous !== NO_PREVIOUS_VALUE && equalValues(previous, input)) {\n return result;\n }\n previous = input;\n return downstream(result, input);\n },\n (result) => downstream(result),\n );\n });\n}\n\nexport function distincting() {\n return makeTransducer((reducingFunction) => {\n const downstream = asReducingFunction(\n reducingFunction,\n \"distincting reducing function\",\n );\n let seen = EMPTY_SET;\n return completing(\n (result, input) => {\n if (contains(seen, input)) return result;\n seen = conj(seen, input);\n return downstream(result, input);\n },\n (result) => downstream(result),\n );\n });\n}\n\nexport function composeTransducers(...transducers) {\n for (const transducer of transducers) {\n requireFunction(transducer, \"composed transducer\");\n }\n return makeTransducer(\n (reducingFunction) => transducers.reduceRight(\n (downstream, transducer) => applyTransducer(transducer, downstream),\n asReducingFunction(reducingFunction, \"composed reducing function\"),\n ),\n transducers.some((transducer) => transducer[ZERO_INPUT] === true),\n );\n}\n\nexport function transduce(transducer, reducer, initial, collection) {\n if (arguments.length !== 4) {\n throw new TypeError(\n \"transduce requires a transducer, reducer, initial value, and collection\",\n );\n }\n const transformed = applyTransducer(\n transducer,\n asReducingFunction(reducer, \"transduce reducer\"),\n );\n const seed = unreduced(initial);\n const result = transducer[ZERO_INPUT] === true\n ? seed\n : reduce(collection, transformed, seed);\n return unreduced(transformed(unreduced(result)));\n}\n\nexport function eduction(...arguments_) {\n if (arguments_.length < 2) {\n throw new TypeError(\"eduction requires one or more transducers and a collection\");\n }\n const collection = arguments_[arguments_.length - 1];\n const transducer = composeTransducers(...arguments_.slice(0, -1));\n return reductionView((reducer, ...initial) => {\n requireFunction(reducer, \"eduction reducer\");\n if (initial.length > 0) {\n return transduce(\n transducer,\n completing(reducer),\n initial[0],\n collection,\n );\n }\n return transduce(\n transducer,\n completing(\n (result, value) => result === NO_REDUCTION_INITIAL\n ? value\n : reducer(result, value),\n (result) => {\n if (result === NO_REDUCTION_INITIAL) {\n throw new TypeError(\n \"cannot reduce an empty eduction without an initial value\",\n );\n }\n return result;\n },\n ),\n NO_REDUCTION_INITIAL,\n collection,\n );\n });\n}\n\nfunction transformedSequenceIterator(transducer, collection) {\n const output = [];\n let outputIndex = 0;\n let input = null;\n let transformed = null;\n let accumulator = null;\n let initialized = false;\n let complete = false;\n\n function closeInput() {\n if (input !== null && typeof input.return === \"function\") input.return();\n input = null;\n }\n\n function finish() {\n if (complete) return;\n complete = true;\n closeInput();\n accumulator = unreduced(transformed(unreduced(accumulator)));\n }\n\n function initialize() {\n if (initialized) return;\n initialized = true;\n transformed = applyTransducer(\n transducer,\n completing((result, value) => {\n output.push(value);\n return result;\n }),\n );\n if (transducer[ZERO_INPUT] === true) {\n finish();\n return;\n }\n const source = seq(collection);\n if (source === null) {\n finish();\n return;\n }\n input = source[Symbol.iterator]();\n }\n\n function pump() {\n initialize();\n while (outputIndex === output.length && !complete) {\n output.length = 0;\n outputIndex = 0;\n let next;\n try {\n next = input.next();\n } catch (error) {\n closeInput();\n complete = true;\n throw error;\n }\n if (next.done) {\n finish();\n continue;\n }\n let stepped;\n try {\n stepped = transformed(accumulator, next.value);\n } catch (error) {\n closeInput();\n complete = true;\n throw error;\n }\n if (isReduced(stepped)) {\n accumulator = unreduced(stepped);\n finish();\n } else {\n accumulator = stepped;\n }\n }\n }\n\n return {\n next() {\n pump();\n if (outputIndex === output.length) {\n return { value: undefined, done: true };\n }\n const value = output[outputIndex];\n outputIndex += 1;\n return { value, done: false };\n },\n return(value) {\n output.length = 0;\n outputIndex = 0;\n complete = true;\n closeInput();\n return { value, done: true };\n },\n [Symbol.iterator]() {\n return this;\n },\n };\n}\n\nexport function sequence(transducer, collection) {\n if (arguments.length !== 2) {\n throw new TypeError(\"sequence requires a transducer and collection\");\n }\n requireFunction(transducer, \"sequence transducer\");\n return memoizedSequenceView(() =>\n transformedSequenceIterator(transducer, collection));\n}\n\nexport function runBang(procedure, collection) {\n if (arguments.length !== 2) {\n throw new TypeError(\"run! requires a procedure and collection\");\n }\n requireFunction(procedure, \"run! procedure\");\n reduce(collection, (_result, value) => {\n procedure(value);\n return null;\n }, null);\n return null;\n}\n\nexport function into(target, ...arguments_) {\n if (arguments_.length !== 1 && arguments_.length !== 2) {\n throw new TypeError(\n \"into requires a target and source, or a target, transducer, and source\",\n );\n }\n const transducer = arguments_.length === 1\n ? IDENTITY_TRANSDUCER\n : arguments_[0];\n const source = arguments_.length === 1 ? arguments_[0] : arguments_[1];\n const seed = empty(target);\n if (implementsProtocolOperation(IEditable, \"transient\", seed)) {\n return transduce(\n transducer,\n completing(\n (result, value) => conjBang(result, value),\n (result) => persistentBang(result),\n ),\n transient(seed),\n source,\n );\n }\n return transduce(\n transducer,\n (result, value) => conj(result, value),\n seed,\n source,\n );\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.transient-internals
|
|
2
|
+
(js* "import {\n defineProtocol,\n protocolMethod,\n protocolSlot,\n} from \"./protocol.mjs\";\n\nexport const I_EDITABLE = defineProtocol(\"IEditable\", [\"transient\"]);\nexport const I_TRANSIENT_COLLECTION = defineProtocol(\n \"ITransientCollection\",\n [\"conj!\", \"assoc!\", \"dissoc!\", \"persistent!\"],\n);\n\nexport const EDITABLE_TRANSIENT = protocolSlot(I_EDITABLE, \"transient\");\nexport const TRANSIENT_CONJ = protocolSlot(I_TRANSIENT_COLLECTION, \"conj!\");\nexport const TRANSIENT_ASSOC = protocolSlot(I_TRANSIENT_COLLECTION, \"assoc!\");\nexport const TRANSIENT_DISSOC = protocolSlot(I_TRANSIENT_COLLECTION, \"dissoc!\");\nexport const TRANSIENT_PERSISTENT = protocolSlot(\n I_TRANSIENT_COLLECTION,\n \"persistent!\",\n);\n\nexport const dispatchEditableTransient = protocolMethod(I_EDITABLE, \"transient\");\nexport const dispatchTransientConj = protocolMethod(\n I_TRANSIENT_COLLECTION,\n \"conj!\",\n);\nexport const dispatchTransientAssoc = protocolMethod(\n I_TRANSIENT_COLLECTION,\n \"assoc!\",\n);\nexport const dispatchTransientDissoc = protocolMethod(\n I_TRANSIENT_COLLECTION,\n \"dissoc!\",\n);\nexport const dispatchTransientPersistent = protocolMethod(\n I_TRANSIENT_COLLECTION,\n \"persistent!\",\n);\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.transient
|
|
2
|
+
(js* "import {\n EDITABLE_TRANSIENT,\n I_EDITABLE,\n I_TRANSIENT_COLLECTION,\n TRANSIENT_ASSOC,\n TRANSIENT_CONJ,\n TRANSIENT_DISSOC,\n TRANSIENT_PERSISTENT,\n dispatchEditableTransient,\n dispatchTransientAssoc,\n dispatchTransientConj,\n dispatchTransientDissoc,\n dispatchTransientPersistent,\n} from \"./transient-internals.mjs\";\n\nexport const IEditable = I_EDITABLE;\nexport const ITransientCollection = I_TRANSIENT_COLLECTION;\n\nexport function transient(collection) {\n if (collection !== null && collection !== undefined) {\n const direct = collection[EDITABLE_TRANSIENT];\n if (typeof direct === \"function\") {\n return direct.call(collection);\n }\n }\n return dispatchEditableTransient(collection);\n}\n\nexport function conjBang(collection, value) {\n const argCount = arguments.length;\n if (argCount <= 1) return collection;\n if (argCount === 2) {\n if (collection !== null && collection !== undefined) {\n const direct = collection[TRANSIENT_CONJ];\n if (typeof direct === \"function\") {\n return direct.call(collection, value);\n }\n }\n return dispatchTransientConj(collection, value);\n }\n let result = collection;\n for (let index = 1; index < argCount; index += 1) {\n const nextValue = arguments[index];\n if (result !== null && result !== undefined) {\n const direct = result[TRANSIENT_CONJ];\n if (typeof direct === \"function\") {\n result = direct.call(result, nextValue);\n continue;\n }\n }\n result = dispatchTransientConj(result, nextValue);\n }\n return result;\n}\n\nexport function assocBang(collection, key, value, ...keyValues) {\n if (arguments.length < 3 || keyValues.length % 2 !== 0) {\n throw new TypeError(\n \"assocBang requires a transient collection followed by one or more key/value pairs\",\n );\n }\n let result;\n if (collection !== null && collection !== undefined && typeof collection[TRANSIENT_ASSOC] === \"function\") {\n result = collection[TRANSIENT_ASSOC](key, value);\n } else {\n result = dispatchTransientAssoc(collection, key, value);\n }\n for (let index = 0; index < keyValues.length; index += 2) {\n if (result !== null && result !== undefined && typeof result[TRANSIENT_ASSOC] === \"function\") {\n result = result[TRANSIENT_ASSOC](keyValues[index], keyValues[index + 1]);\n } else {\n result = dispatchTransientAssoc(\n result,\n keyValues[index],\n keyValues[index + 1],\n );\n }\n }\n return result;\n}\n\nexport function dissocBang(collection, ...keys) {\n let result = collection;\n for (const key of keys) {\n if (result !== null && result !== undefined && typeof result[TRANSIENT_DISSOC] === \"function\") {\n result = result[TRANSIENT_DISSOC](key);\n } else {\n result = dispatchTransientDissoc(result, key);\n }\n }\n return result;\n}\n\nexport function persistentBang(collection) {\n if (collection !== null && collection !== undefined) {\n const direct = collection[TRANSIENT_PERSISTENT];\n if (typeof direct === \"function\") {\n return direct.call(collection);\n }\n }\n return dispatchTransientPersistent(collection);\n}\n"))
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import {
|
|
2
|
+
EDITABLE_TRANSIENT,
|
|
2
3
|
I_EDITABLE,
|
|
3
4
|
I_TRANSIENT_COLLECTION,
|
|
5
|
+
TRANSIENT_ASSOC,
|
|
6
|
+
TRANSIENT_CONJ,
|
|
7
|
+
TRANSIENT_DISSOC,
|
|
8
|
+
TRANSIENT_PERSISTENT,
|
|
4
9
|
dispatchEditableTransient,
|
|
5
10
|
dispatchTransientAssoc,
|
|
6
11
|
dispatchTransientConj,
|
|
@@ -12,13 +17,38 @@ export const IEditable = I_EDITABLE;
|
|
|
12
17
|
export const ITransientCollection = I_TRANSIENT_COLLECTION;
|
|
13
18
|
|
|
14
19
|
export function transient(collection) {
|
|
20
|
+
if (collection !== null && collection !== undefined) {
|
|
21
|
+
const direct = collection[EDITABLE_TRANSIENT];
|
|
22
|
+
if (typeof direct === "function") {
|
|
23
|
+
return direct.call(collection);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
15
26
|
return dispatchEditableTransient(collection);
|
|
16
27
|
}
|
|
17
28
|
|
|
18
|
-
export function conjBang(collection,
|
|
29
|
+
export function conjBang(collection, value) {
|
|
30
|
+
const argCount = arguments.length;
|
|
31
|
+
if (argCount <= 1) return collection;
|
|
32
|
+
if (argCount === 2) {
|
|
33
|
+
if (collection !== null && collection !== undefined) {
|
|
34
|
+
const direct = collection[TRANSIENT_CONJ];
|
|
35
|
+
if (typeof direct === "function") {
|
|
36
|
+
return direct.call(collection, value);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return dispatchTransientConj(collection, value);
|
|
40
|
+
}
|
|
19
41
|
let result = collection;
|
|
20
|
-
for (
|
|
21
|
-
|
|
42
|
+
for (let index = 1; index < argCount; index += 1) {
|
|
43
|
+
const nextValue = arguments[index];
|
|
44
|
+
if (result !== null && result !== undefined) {
|
|
45
|
+
const direct = result[TRANSIENT_CONJ];
|
|
46
|
+
if (typeof direct === "function") {
|
|
47
|
+
result = direct.call(result, nextValue);
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
result = dispatchTransientConj(result, nextValue);
|
|
22
52
|
}
|
|
23
53
|
return result;
|
|
24
54
|
}
|
|
@@ -29,13 +59,22 @@ export function assocBang(collection, key, value, ...keyValues) {
|
|
|
29
59
|
"assocBang requires a transient collection followed by one or more key/value pairs",
|
|
30
60
|
);
|
|
31
61
|
}
|
|
32
|
-
let result
|
|
62
|
+
let result;
|
|
63
|
+
if (collection !== null && collection !== undefined && typeof collection[TRANSIENT_ASSOC] === "function") {
|
|
64
|
+
result = collection[TRANSIENT_ASSOC](key, value);
|
|
65
|
+
} else {
|
|
66
|
+
result = dispatchTransientAssoc(collection, key, value);
|
|
67
|
+
}
|
|
33
68
|
for (let index = 0; index < keyValues.length; index += 2) {
|
|
34
|
-
result
|
|
35
|
-
result,
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
69
|
+
if (result !== null && result !== undefined && typeof result[TRANSIENT_ASSOC] === "function") {
|
|
70
|
+
result = result[TRANSIENT_ASSOC](keyValues[index], keyValues[index + 1]);
|
|
71
|
+
} else {
|
|
72
|
+
result = dispatchTransientAssoc(
|
|
73
|
+
result,
|
|
74
|
+
keyValues[index],
|
|
75
|
+
keyValues[index + 1],
|
|
76
|
+
);
|
|
77
|
+
}
|
|
39
78
|
}
|
|
40
79
|
return result;
|
|
41
80
|
}
|
|
@@ -43,11 +82,21 @@ export function assocBang(collection, key, value, ...keyValues) {
|
|
|
43
82
|
export function dissocBang(collection, ...keys) {
|
|
44
83
|
let result = collection;
|
|
45
84
|
for (const key of keys) {
|
|
46
|
-
result
|
|
85
|
+
if (result !== null && result !== undefined && typeof result[TRANSIENT_DISSOC] === "function") {
|
|
86
|
+
result = result[TRANSIENT_DISSOC](key);
|
|
87
|
+
} else {
|
|
88
|
+
result = dispatchTransientDissoc(result, key);
|
|
89
|
+
}
|
|
47
90
|
}
|
|
48
91
|
return result;
|
|
49
92
|
}
|
|
50
93
|
|
|
51
94
|
export function persistentBang(collection) {
|
|
95
|
+
if (collection !== null && collection !== undefined) {
|
|
96
|
+
const direct = collection[TRANSIENT_PERSISTENT];
|
|
97
|
+
if (typeof direct === "function") {
|
|
98
|
+
return direct.call(collection);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
52
101
|
return dispatchTransientPersistent(collection);
|
|
53
102
|
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.type
|
|
2
|
+
(js* "const MAX_FIELDS = 1024;\nconst MAX_PROTOCOLS = 1024;\nconst TYPE_CONSTRUCTOR_TOKEN = Symbol(\"eliscript.type.constructor-token\");\nconst TYPE_VALUE_STATE = new WeakMap();\nconst typeStates = new WeakMap();\nconst reifiedStates = new WeakMap();\n\nfunction fail(message) {\n throw new TypeError(message);\n}\n\nfunction denseArray(value, label, maximum) {\n if (!Array.isArray(value) || value.length > maximum) {\n fail(`${label} must be a dense array of at most ${maximum} values`);\n }\n const descriptors = Object.getOwnPropertyDescriptors(value);\n if (Reflect.ownKeys(descriptors).length !== value.length + 1) {\n fail(`${label} must be a dense array with no extra properties`);\n }\n for (let index = 0; index < value.length; index += 1) {\n const descriptor = descriptors[String(index)];\n if (!descriptor?.enumerable || !(\"value\" in descriptor)) {\n fail(`${label} must contain enumerable data values`);\n }\n }\n return value;\n}\n\nfunction normalizeTypeName(name) {\n if (typeof name !== \"string\" || name.length === 0) {\n fail(\"type name must be a non-empty string\");\n }\n return name;\n}\n\nfunction normalizeFieldNames(fields) {\n denseArray(fields, \"type fields\", MAX_FIELDS);\n const seen = new Set();\n const normalized = fields.map((field) => {\n if (typeof field !== \"string\" || field.length === 0 || field.includes(\"/\")) {\n fail(\"type field names must be non-empty unqualified strings\");\n }\n if (seen.has(field)) fail(`type declares duplicate field ${field}`);\n seen.add(field);\n return field;\n });\n return Object.freeze(normalized);\n}\n\nfunction protocolShape(protocol) {\n if (protocol === null || typeof protocol !== \"object\") {\n fail(\"expected an Eliscript protocol\");\n }\n const descriptors = Object.getOwnPropertyDescriptors(protocol);\n const keys = Reflect.ownKeys(descriptors);\n const nameDescriptor = descriptors.name;\n const operationsDescriptor = descriptors.operations;\n if (keys.length !== 2 || !nameDescriptor?.enumerable ||\n !(\"value\" in nameDescriptor) ||\n typeof nameDescriptor.value !== \"string\" ||\n nameDescriptor.value.length === 0 ||\n !operationsDescriptor?.enumerable || !(\"value\" in operationsDescriptor) ||\n !Object.isFrozen(protocol)) {\n fail(\"expected an Eliscript protocol\");\n }\n const operations = operationsDescriptor.value;\n if (operations === null || typeof operations !== \"object\" ||\n Array.isArray(operations) || !Object.isFrozen(operations)) {\n fail(\"expected an Eliscript protocol\");\n }\n const operationDescriptors = Object.getOwnPropertyDescriptors(operations);\n const operationNames = Reflect.ownKeys(operationDescriptors);\n if (operationNames.length === 0 || operationNames.length > MAX_FIELDS ||\n operationNames.some((operation) => typeof operation !== \"string\")) {\n fail(\"expected an Eliscript protocol\");\n }\n const methods = operationNames.map((operation) => {\n const descriptor = operationDescriptors[operation];\n const method = descriptor?.value;\n const methodDescriptors = typeof method === \"function\"\n ? Object.getOwnPropertyDescriptors(method)\n : {};\n if (!descriptor?.enumerable || !(\"value\" in descriptor) ||\n methodDescriptors.protocol?.value !== protocol ||\n methodDescriptors.operation?.value !== operation ||\n typeof methodDescriptors.slot?.value !== \"symbol\" ||\n !Object.isFrozen(method)) {\n fail(\"expected an Eliscript protocol\");\n }\n return Object.freeze({ operation, slot: methodDescriptors.slot.value });\n });\n return Object.freeze({\n name: nameDescriptor.value,\n operations: Object.freeze(methods),\n });\n}\n\nfunction normalizeMethods(protocol, implementations) {\n const definition = protocolShape(protocol);\n if (implementations === null || typeof implementations !== \"object\" ||\n Array.isArray(implementations)) {\n fail(`protocol ${definition.name} implementations must be a plain object`);\n }\n const prototype = Object.getPrototypeOf(implementations);\n if (prototype !== Object.prototype && prototype !== null) {\n fail(`protocol ${definition.name} implementations must be a plain object`);\n }\n const descriptors = Object.getOwnPropertyDescriptors(implementations);\n const keys = Reflect.ownKeys(descriptors);\n if (keys.length !== definition.operations.length) {\n fail(`protocol ${definition.name} implementation must define every operation`);\n }\n const operationNames = definition.operations.map(({ operation }) => operation);\n if (keys.some((key) => typeof key !== \"string\" ||\n !operationNames.includes(key))) {\n fail(`protocol ${definition.name} implementation contains an unknown operation`);\n }\n const normalized = [];\n for (const { operation, slot } of definition.operations) {\n const descriptor = descriptors[operation];\n if (!descriptor?.enumerable || !(\"value\" in descriptor) ||\n typeof descriptor.value !== \"function\") {\n fail(`protocol ${definition.name}/${operation} implementation must be a function`);\n }\n normalized.push(Object.freeze({\n operation,\n slot,\n implementation: descriptor.value,\n }));\n }\n return Object.freeze({ protocol, name: definition.name, methods: normalized });\n}\n\nfunction normalizeProtocolPlans(plans, allowEmpty) {\n denseArray(plans, \"protocol implementations\", MAX_PROTOCOLS);\n if (!allowEmpty && plans.length === 0) {\n fail(\"reify requires at least one protocol implementation\");\n }\n const seen = new Set();\n return Object.freeze(plans.map((plan, index) => {\n denseArray(plan, `protocol implementation ${index}`, 2);\n if (plan.length !== 2) {\n fail(`protocol implementation ${index} must contain a protocol and methods`);\n }\n const [protocol, methods] = plan;\n if (seen.has(protocol)) fail(\"protocol may be implemented only once\");\n seen.add(protocol);\n return normalizeMethods(protocol, methods);\n }));\n}\n\nfunction installProtocolMethods(target, plans) {\n for (const plan of plans) {\n for (const { slot, implementation } of plan.methods) {\n if (Reflect.has(target, slot)) {\n fail(`protocol slot conflict while implementing ${plan.name}`);\n }\n Object.defineProperty(target, slot, {\n configurable: false,\n enumerable: false,\n writable: false,\n value: function (...argumentsList) {\n return implementation(this, ...argumentsList);\n },\n });\n }\n }\n return target;\n}\n\nfunction protocolPlanSnapshot(plans) {\n const snapshot = [];\n for (let index = 0; index < plans.length; index += 1) {\n const plan = plans[index];\n const implementations = Object.create(null);\n for (let methodIndex = 0; methodIndex < plan.methods.length; methodIndex += 1) {\n const method = plan.methods[methodIndex];\n Object.defineProperty(implementations, method.operation, {\n value: method.implementation,\n enumerable: true,\n });\n }\n Object.defineProperty(snapshot, String(index), {\n value: Object.freeze([plan.protocol, Object.freeze(implementations)]),\n writable: true,\n configurable: true,\n enumerable: true,\n });\n }\n return Object.freeze(snapshot);\n}\n\nfunction defineFieldAccessors(TypeValue, fieldNames) {\n for (let index = 0; index < fieldNames.length; index += 1) {\n const fieldName = fieldNames[index];\n if (fieldName in TypeValue.prototype) {\n fail(`type field ${fieldName} conflicts with a type member`);\n }\n Object.defineProperty(TypeValue.prototype, fieldName, {\n configurable: false,\n enumerable: true,\n get() {\n return TYPE_VALUE_STATE.get(this).values[index];\n },\n });\n }\n}\n\nexport function defineType(name, fields, protocolPlans = []) {\n return makeTypeDefinition(name, fields, protocolPlans, false);\n}\n\n// Used only by the trusted bulk boundary after transporting the declaration.\n// Keep that frozen array so an independently transported typeFields reference\n// remains the very same object; public defineType still makes its usual copy.\nexport function materializeTypeDefinition(name, fields, protocolPlans = []) {\n return makeTypeDefinition(name, fields, protocolPlans, true);\n}\n\nfunction makeTypeDefinition(name, fields, protocolPlans, retainFields) {\n const typeName = normalizeTypeName(name);\n const normalized = normalizeFieldNames(fields);\n if (retainFields && !Object.isFrozen(fields)) {\n fail(\"transported type fields must be frozen\");\n }\n const fieldNames = retainFields ? fields : normalized;\n const plans = normalizeProtocolPlans(protocolPlans, true);\n\n class TypeValue {\n constructor(token, values) {\n if (token !== TYPE_CONSTRUCTOR_TOKEN) {\n fail(`${typeName} values must be created with its positional constructor`);\n }\n TYPE_VALUE_STATE.set(this, Object.freeze({\n type: TypeValue,\n values: Object.freeze(values),\n }));\n Object.freeze(this);\n }\n\n static create(...values) {\n if (values.length !== fieldNames.length) {\n fail(\n `->${typeName} expects ${fieldNames.length} values, received ${values.length}`,\n );\n }\n return new TypeValue(TYPE_CONSTRUCTOR_TOKEN, values);\n }\n\n static isInstance(value) {\n return TYPE_VALUE_STATE.get(value)?.type === TypeValue;\n }\n\n get [Symbol.toStringTag]() {\n return `EliscriptType:${typeName}`;\n }\n }\n\n Object.defineProperty(TypeValue, \"name\", { value: typeName });\n Object.defineProperties(TypeValue, {\n typeName: { enumerable: true, value: typeName },\n typeFields: { enumerable: true, value: fieldNames },\n });\n defineFieldAccessors(TypeValue, fieldNames);\n installProtocolMethods(TypeValue.prototype, plans);\n Object.freeze(TypeValue.prototype);\n Object.freeze(TypeValue);\n typeStates.set(TypeValue, Object.freeze({\n name: typeName,\n fields: fieldNames,\n protocolPlans: protocolPlanSnapshot(plans),\n }));\n return TypeValue;\n}\n\nexport function reifyProtocols(protocolPlans) {\n const plans = normalizeProtocolPlans(protocolPlans, false);\n const value = Object.freeze(installProtocolMethods(Object.create(null), plans));\n reifiedStates.set(value, Object.freeze({ protocolPlans: protocolPlanSnapshot(plans) }));\n return value;\n}\n\n// Read only the states owned by these constructors. The transport preserves\n// actual protocol and function references instead of inferring a type from its\n// printable name, field names, or Symbol descriptions.\nexport function readTypeState(type) {\n return typeof type === \"function\" ? typeStates.get(type) : undefined;\n}\n\nexport function readTypeValueState(value) {\n return value !== null && typeof value === \"object\"\n ? TYPE_VALUE_STATE.get(value) : undefined;\n}\n\nexport function materializeTypeValue(type, values) {\n const state = readTypeState(type);\n if (state === undefined) fail(\"expected an Eliscript type\");\n denseArray(values, \"type values\", MAX_FIELDS);\n if (values.length !== state.fields.length) {\n fail(`->${state.name} expects ${state.fields.length} values, received ${values.length}`);\n }\n if (!Object.isFrozen(values)) fail(\"transported type values must be frozen\");\n return new type(TYPE_CONSTRUCTOR_TOKEN, values);\n}\n\nexport function readReifiedState(value) {\n return value !== null && typeof value === \"object\"\n ? reifiedStates.get(value) : undefined;\n}\n\nexport function isType(value) {\n return typeof value === \"function\" && typeStates.has(value);\n}\n\nexport function isTypeValue(value) {\n return value !== null && typeof value === \"object\" &&\n TYPE_VALUE_STATE.has(value);\n}\n\nexport function typeOf(value) {\n const state = TYPE_VALUE_STATE.get(value);\n if (state === undefined) fail(\"expected an Eliscript type value\");\n return state.type;\n}\n\nexport function typeName(value) {\n const type = isType(value) ? value : typeOf(value);\n return typeStates.get(type).name;\n}\n\nexport function typeFieldNames(value) {\n const type = isType(value) ? value : typeOf(value);\n return typeStates.get(type).fields;\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.value-internals
|
|
2
|
+
(js* "import {\n defineProtocol,\n protocolMethod,\n protocolSlot,\n} from \"./protocol.mjs\";\n\nexport const I_EQUIV = defineProtocol(\"IEquiv\", [\"equal\"]);\nexport const I_HASH = defineProtocol(\"IHash\", [\"hash\"]);\nexport const VALUE_EQUAL = protocolSlot(I_EQUIV, \"equal\");\nexport const VALUE_HASH = protocolSlot(I_HASH, \"hash\");\nexport const dispatchValueEqual = protocolMethod(I_EQUIV, \"equal\");\nexport const dispatchValueHash = protocolMethod(I_HASH, \"hash\");\n\nconst BOOLEAN_TAG = 0x4b1d_9f73;\nconst BIGINT_TAG = 0x7845_9ad1;\nconst GLOBAL_SYMBOL_TAG = 0x9e65_8cab;\nconst HOST_IDENTITY_TAG = 0x2d6f_5a8d;\nconst NUMBER_TAG = 0x1656_67b1;\nconst STRING_TAG = 0x6d2b_79f5;\n\nconst FALSE_HASH = 0x193a_7c41;\nconst TRUE_HASH = 0x71f4_9d0b;\nconst NULL_HASH = 0x4210_8421;\nconst UNDEFINED_HASH = 0x7f4a_7c15;\nconst NAN_HASH = 0x58d0_2a6f;\n\nconst floatBytes = new DataView(new ArrayBuffer(8));\n\nlet protocolHashes = new WeakMap();\nlet hostObjectHashes = new WeakMap();\nlet hostSymbolHashes = new Map();\nlet nextHostIdentity = 1;\n\nconst metrics = {\n hashValueCalls: 0,\n protocolHashComputations: 0,\n protocolHashCacheHits: 0,\n hostIdentityAssignments: 0,\n};\n\nexport function avalancheHash(value) {\n let hash = value >>> 0;\n hash ^= hash >>> 16;\n hash = Math.imul(hash, 0x85eb_ca6b);\n hash ^= hash >>> 13;\n hash = Math.imul(hash, 0xc2b2_ae35);\n hash ^= hash >>> 16;\n return hash >>> 0;\n}\n\nexport function mixHash(hash, value) {\n let mixed = (hash ^ value) >>> 0;\n mixed = Math.imul(mixed, 0x5bd1_e995);\n mixed ^= mixed >>> 15;\n return mixed >>> 0;\n}\n\nexport function finishHash(hash, count) {\n return avalancheHash(mixHash(hash, count >>> 0));\n}\n\nexport function hashString(value, tag = STRING_TAG) {\n let hash = mixHash(tag, value.length);\n for (let index = 0; index < value.length; index += 1) {\n hash = mixHash(hash, value.charCodeAt(index));\n }\n return finishHash(hash, value.length);\n}\n\nexport function hashNumber(value) {\n if (Number.isNaN(value)) {\n return NAN_HASH;\n }\n const normalized = value === 0 ? 0 : value;\n floatBytes.setFloat64(0, normalized, true);\n const low = floatBytes.getUint32(0, true);\n const high = floatBytes.getUint32(4, true);\n return finishHash(mixHash(mixHash(NUMBER_TAG, low), high), 2);\n}\n\nexport function hashBigInt(value) {\n let magnitude = value < 0n ? -value : value;\n let hash = mixHash(BIGINT_TAG, value < 0n ? 1 : 0);\n let limbs = 0;\n do {\n hash = mixHash(hash, Number(magnitude & 0xffff_ffffn));\n magnitude >>= 32n;\n limbs += 1;\n } while (magnitude !== 0n);\n return finishHash(hash, limbs);\n}\n\nexport function hashBoolean(value) {\n return mixHash(BOOLEAN_TAG, value ? TRUE_HASH : FALSE_HASH);\n}\n\nexport function hashNull() {\n return NULL_HASH;\n}\n\nexport function hashUndefined() {\n return UNDEFINED_HASH;\n}\n\nexport function hashGlobalSymbol(key) {\n return hashString(key, GLOBAL_SYMBOL_TAG);\n}\n\nexport function orderedCollectionHash(iterable, hashValue, tag) {\n let hash = tag >>> 0;\n let count = 0;\n for (const value of iterable) {\n hash = mixHash(hash, hashValue(value));\n count += 1;\n }\n return finishHash(hash, count);\n}\n\nfunction rotateLeft(value, distance) {\n const shift = distance & 31;\n return ((value << shift) | (value >>> (32 - shift))) >>> 0;\n}\n\nexport function unorderedCollectionHash(iterable, hashElement, tag) {\n let sum = 0;\n let xor = 0;\n let product = 1;\n let count = 0;\n for (const element of iterable) {\n const hash = hashElement(element) >>> 0;\n sum = (sum + hash) >>> 0;\n xor = (xor ^ rotateLeft(hash, hash & 31)) >>> 0;\n product = Math.imul(product, hash | 1) >>> 0;\n count += 1;\n }\n return finishHash(\n mixHash(mixHash(mixHash(tag, sum), xor), product),\n count,\n );\n}\n\nexport function cachedProtocolHash(value, compute) {\n const cached = protocolHashes.get(value);\n if (cached !== undefined) {\n metrics.protocolHashCacheHits += 1;\n return cached;\n }\n metrics.protocolHashComputations += 1;\n const hash = compute() >>> 0;\n protocolHashes.set(value, hash);\n return hash;\n}\n\nexport function recordHashValueCall() {\n metrics.hashValueCalls += 1;\n}\n\nexport function hostIdentityHash(value) {\n const hashes = typeof value === \"symbol\" ? hostSymbolHashes : hostObjectHashes;\n const cached = hashes.get(value);\n if (cached !== undefined) {\n return cached;\n }\n const hash = finishHash(HOST_IDENTITY_TAG, nextHostIdentity);\n nextHostIdentity += 1;\n metrics.hostIdentityAssignments += 1;\n hashes.set(value, hash);\n return hash;\n}\n\nexport function resetValueMetrics() {\n metrics.hashValueCalls = 0;\n metrics.protocolHashComputations = 0;\n metrics.protocolHashCacheHits = 0;\n metrics.hostIdentityAssignments = 0;\n}\n\nexport function clearValueCaches() {\n protocolHashes = new WeakMap();\n hostObjectHashes = new WeakMap();\n hostSymbolHashes = new Map();\n nextHostIdentity = 1;\n resetValueMetrics();\n}\n\nexport function readValueMetrics() {\n return Object.freeze({ ...metrics });\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.value
|
|
2
|
+
(js* "import {\n I_EQUIV,\n I_HASH,\n cachedProtocolHash,\n dispatchValueEqual,\n dispatchValueHash,\n hashBigInt,\n hashBoolean,\n hashGlobalSymbol,\n hashNull,\n hashNumber,\n hashString,\n hashUndefined,\n hostIdentityHash,\n recordHashValueCall,\n} from \"./value-internals.mjs\";\nimport {\n extendProtocolType,\n implementsProtocolOperation,\n} from \"./protocol.mjs\";\n\nexport const IEquiv = I_EQUIV;\nexport const IHash = I_HASH;\n\nexport function extendValueType(constructor, implementations) {\n if (implementations === null || typeof implementations !== \"object\" ||\n typeof implementations.equal !== \"function\" ||\n typeof implementations.hash !== \"function\") {\n throw new TypeError(\n \"value type extension requires equal and hash functions\",\n );\n }\n extendProtocolType(IEquiv, constructor, { equal: implementations.equal });\n extendProtocolType(IHash, constructor, { hash: implementations.hash });\n return constructor;\n}\n\nexport function equalValues(left, right) {\n if (left === right) {\n return true;\n }\n if (typeof left === \"number\" && typeof right === \"number\") {\n return Number.isNaN(left) && Number.isNaN(right);\n }\n if (left === null || right === null ||\n (typeof left !== \"object\" && typeof left !== \"function\") ||\n (typeof right !== \"object\" && typeof right !== \"function\")) {\n return false;\n }\n\n if (!implementsProtocolOperation(IEquiv, \"equal\", left) ||\n !implementsProtocolOperation(IEquiv, \"equal\", right)) {\n return false;\n }\n return dispatchValueEqual(left, right, equalValues) === true;\n}\n\nexport function hashValue(value) {\n recordHashValueCall();\n if (value === null) {\n return hashNull();\n }\n switch (typeof value) {\n case \"undefined\":\n return hashUndefined();\n case \"boolean\":\n return hashBoolean(value);\n case \"number\":\n return hashNumber(value);\n case \"bigint\":\n return hashBigInt(value);\n case \"string\":\n return hashString(value);\n case \"symbol\": {\n const globalKey = Symbol.keyFor(value);\n return globalKey === undefined\n ? hostIdentityHash(value)\n : hashGlobalSymbol(globalKey);\n }\n case \"function\":\n case \"object\": {\n if (implementsProtocolOperation(IHash, \"hash\", value)) {\n return cachedProtocolHash(\n value,\n () => dispatchValueHash(value, hashValue),\n );\n }\n return hostIdentityHash(value);\n }\n default:\n throw new TypeError(`cannot hash JavaScript value of type ${typeof value}`);\n }\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.vector-internals
|
|
2
|
+
(js* "export const BRANCH_BITS = 5;\nexport const BRANCH_WIDTH = 1 << BRANCH_BITS;\nexport const BRANCH_MASK = BRANCH_WIDTH - 1;\n\nexport const VECTOR_STATE = Symbol(\"eliscript.vector.state\");\nexport const VECTOR_CONSTRUCTOR_TOKEN = Symbol(\"eliscript.vector.constructor\");\nexport const TRANSIENT_VECTOR_STATE = Symbol(\"eliscript.vector.transient-state\");\nexport const TRANSIENT_VECTOR_CONSTRUCTOR_TOKEN = Symbol(\n \"eliscript.vector.transient-constructor\",\n);\n\nconst metrics = {\n nodeAllocations: 0,\n nodeVisits: 0,\n tailAllocations: 0,\n rootGrowths: 0,\n};\n\nconst transientMetrics = {\n nodeClones: 0,\n nodeMutations: 0,\n tailCopies: 0,\n tailMutations: 0,\n persistentCalls: 0,\n invalidCalls: 0,\n};\n\nexport class VectorNode {\n constructor(slots = [], owner = null) {\n metrics.nodeAllocations += 1;\n this.owner = owner;\n this.slots = slots;\n }\n}\n\nexport function editableVectorNode(node, owner) {\n if (node.owner === owner) {\n return node;\n }\n transientMetrics.nodeClones += 1;\n return new VectorNode(node.slots.slice(), owner);\n}\n\nexport function recordTransientVectorNodeMutation() {\n transientMetrics.nodeMutations += 1;\n}\n\nexport function recordTransientVectorTailCopy() {\n transientMetrics.tailCopies += 1;\n}\n\nexport function recordTransientVectorTailMutation() {\n transientMetrics.tailMutations += 1;\n}\n\nexport function recordTransientVectorPersistent() {\n transientMetrics.persistentCalls += 1;\n}\n\nexport function recordInvalidTransientVectorCall() {\n transientMetrics.invalidCalls += 1;\n}\n\nexport function allocateTail(values) {\n metrics.tailAllocations += 1;\n return values;\n}\n\nexport function visitNode(node) {\n metrics.nodeVisits += 1;\n return node;\n}\n\nexport function recordRootGrowth() {\n metrics.rootGrowths += 1;\n}\n\nexport function resetVectorMetrics() {\n for (const key of Object.keys(metrics)) {\n metrics[key] = 0;\n }\n}\n\nexport function readVectorMetrics() {\n return Object.freeze({ ...metrics });\n}\n\nexport function resetTransientVectorMetrics() {\n for (const key of Object.keys(transientMetrics)) {\n transientMetrics[key] = 0;\n }\n}\n\nexport function readTransientVectorMetrics() {\n return Object.freeze({ ...transientMetrics });\n}\n\nexport const EMPTY_ROOT = new VectorNode();\nexport const EMPTY_TAIL = Object.freeze(allocateTail([]));\n"))
|
|
@@ -29,10 +29,7 @@ export class VectorNode {
|
|
|
29
29
|
constructor(slots = [], owner = null) {
|
|
30
30
|
metrics.nodeAllocations += 1;
|
|
31
31
|
this.owner = owner;
|
|
32
|
-
this.slots =
|
|
33
|
-
if (owner === null) {
|
|
34
|
-
Object.freeze(this);
|
|
35
|
-
}
|
|
32
|
+
this.slots = slots;
|
|
36
33
|
}
|
|
37
34
|
}
|
|
38
35
|
|
|
@@ -66,7 +63,7 @@ export function recordInvalidTransientVectorCall() {
|
|
|
66
63
|
|
|
67
64
|
export function allocateTail(values) {
|
|
68
65
|
metrics.tailAllocations += 1;
|
|
69
|
-
return
|
|
66
|
+
return values;
|
|
70
67
|
}
|
|
71
68
|
|
|
72
69
|
export function visitNode(node) {
|
|
@@ -99,4 +96,4 @@ export function readTransientVectorMetrics() {
|
|
|
99
96
|
}
|
|
100
97
|
|
|
101
98
|
export const EMPTY_ROOT = new VectorNode();
|
|
102
|
-
export const EMPTY_TAIL = allocateTail([]);
|
|
99
|
+
export const EMPTY_TAIL = Object.freeze(allocateTail([]));
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.vector
|
|
2
|
+
(js* "import {\n BRANCH_BITS,\n BRANCH_MASK,\n BRANCH_WIDTH,\n EMPTY_ROOT,\n EMPTY_TAIL,\n TRANSIENT_VECTOR_CONSTRUCTOR_TOKEN,\n TRANSIENT_VECTOR_STATE,\n VECTOR_CONSTRUCTOR_TOKEN,\n VECTOR_STATE,\n VectorNode,\n allocateTail,\n editableVectorNode,\n recordInvalidTransientVectorCall,\n recordRootGrowth,\n recordTransientVectorNodeMutation,\n recordTransientVectorPersistent,\n recordTransientVectorTailCopy,\n recordTransientVectorTailMutation,\n visitNode,\n} from \"./vector-internals.mjs\";\nimport {\n VALUE_EQUAL,\n VALUE_HASH,\n orderedCollectionHash,\n} from \"./value-internals.mjs\";\nimport {\n COLLECTION_COUNT,\n COLLECTION_EMPTY,\n COLLECTION_CONJ,\n COLLECTION_GET,\n COLLECTION_ASSOC,\n COLLECTION_CONTAINS,\n COLLECTION_NTH,\n COLLECTION_REDUCE,\n COLLECTION_REDUCE_KV,\n COLLECTION_PEEK,\n COLLECTION_POP,\n COLLECTION_RSEQ,\n COLLECTION_SEQ,\n isReducedValue,\n reduceIterable,\n sequenceView,\n unreducedValue,\n} from \"./collection-internals.mjs\";\nimport {\n EDITABLE_TRANSIENT,\n TRANSIENT_ASSOC,\n TRANSIENT_CONJ,\n TRANSIENT_PERSISTENT,\n} from \"./transient-internals.mjs\";\nimport {\n METADATA_READ,\n METADATA_WITH,\n} from \"./metadata-internals.mjs\";\n\nconst MAX_COUNT = 0x7fffffff;\nconst MISSING = Symbol(\"eliscript.vector.missing\");\nconst VECTOR_HASH_TAG = 0x4f1b_2c3d;\nconst SUBVECTOR_STATE = new WeakMap();\n\nfunction assertIndex(index, upperBound, operation) {\n if (!Number.isInteger(index) || index < 0 || index >= upperBound) {\n throw new RangeError(\n `${operation} index ${String(index)} is outside [0, ${upperBound})`,\n );\n }\n}\n\nfunction tailOffset(count) {\n return count < BRANCH_WIDTH\n ? 0\n : ((count - 1) >>> BRANCH_BITS) << BRANCH_BITS;\n}\n\nfunction reverseVectorIterator(state) {\n let index = state.count - 1;\n let chunk = EMPTY_TAIL;\n let chunkStart = state.count;\n return {\n next() {\n if (index < 0) return { value: undefined, done: true };\n if (index < chunkStart) {\n chunk = arrayFor(state, index);\n chunkStart = index - (index & BRANCH_MASK);\n }\n const value = chunk[index - chunkStart];\n index -= 1;\n return { value, done: false };\n },\n };\n}\n\nfunction vectorRangeIterator(vector, start, end, reverse = false) {\n let index = reverse ? end - 1 : start;\n return {\n next() {\n if (reverse ? index < start : index >= end) {\n return { value: undefined, done: true };\n }\n const value = vector.nth(index);\n index += reverse ? -1 : 1;\n return { value, done: false };\n },\n };\n}\n\nfunction newPath(level, node) {\n if (level === 0) {\n return node;\n }\n return new VectorNode([newPath(level - BRANCH_BITS, node)]);\n}\n\nfunction pushTail(level, parent, tailNode, count) {\n visitNode(parent);\n const subindex = ((count - 1) >>> level) & BRANCH_MASK;\n const slots = parent.slots.slice();\n\n if (level === BRANCH_BITS) {\n slots[subindex] = tailNode;\n } else {\n const child = parent.slots[subindex];\n slots[subindex] = child === undefined\n ? newPath(level - BRANCH_BITS, tailNode)\n : pushTail(level - BRANCH_BITS, child, tailNode, count);\n }\n return new VectorNode(slots);\n}\n\nfunction assocNode(level, node, index, value) {\n visitNode(node);\n const slots = node.slots.slice();\n if (level === 0) {\n slots[index & BRANCH_MASK] = value;\n } else {\n const subindex = (index >>> level) & BRANCH_MASK;\n slots[subindex] = assocNode(\n level - BRANCH_BITS,\n node.slots[subindex],\n index,\n value,\n );\n }\n return new VectorNode(slots);\n}\n\nfunction transientNewPath(level, node, owner) {\n if (level === 0) {\n return node;\n }\n return new VectorNode(\n [transientNewPath(level - BRANCH_BITS, node, owner)],\n owner,\n );\n}\n\nfunction transientPushTail(level, parent, tailNode, count, owner) {\n visitNode(parent);\n const editable = editableVectorNode(parent, owner);\n const subindex = ((count - 1) >>> level) & BRANCH_MASK;\n if (level === BRANCH_BITS) {\n editable.slots[subindex] = tailNode;\n } else {\n const child = editable.slots[subindex];\n editable.slots[subindex] = child === undefined\n ? transientNewPath(level - BRANCH_BITS, tailNode, owner)\n : transientPushTail(level - BRANCH_BITS, child, tailNode, count, owner);\n }\n recordTransientVectorNodeMutation();\n return editable;\n}\n\nfunction transientAssocNode(level, node, index, value, owner) {\n visitNode(node);\n const editable = editableVectorNode(node, owner);\n if (level === 0) {\n editable.slots[index & BRANCH_MASK] = value;\n } else {\n const subindex = (index >>> level) & BRANCH_MASK;\n editable.slots[subindex] = transientAssocNode(\n level - BRANCH_BITS,\n editable.slots[subindex],\n index,\n value,\n owner,\n );\n }\n recordTransientVectorNodeMutation();\n return editable;\n}\n\nfunction popTail(level, node, count) {\n visitNode(node);\n const subindex = ((count - 2) >>> level) & BRANCH_MASK;\n if (level > BRANCH_BITS) {\n const child = popTail(\n level - BRANCH_BITS,\n node.slots[subindex],\n count,\n );\n if (child === undefined && subindex === 0) {\n return undefined;\n }\n const slots = node.slots.slice();\n slots[subindex] = child;\n return new VectorNode(slots);\n }\n if (subindex === 0) {\n return undefined;\n }\n const slots = node.slots.slice();\n slots[subindex] = undefined;\n return new VectorNode(slots);\n}\n\nfunction arrayFor(state, index) {\n if (index >= tailOffset(state.count)) {\n return state.tail;\n }\n\n let node = state.root;\n for (let level = state.shift; level > 0; level -= BRANCH_BITS) {\n visitNode(node);\n node = node.slots[(index >>> level) & BRANCH_MASK];\n }\n visitNode(node);\n return node.slots;\n}\n\nfunction makeVector(count, shift, root, tail, metadata = null) {\n return new PersistentVector(\n VECTOR_CONSTRUCTOR_TOKEN,\n count,\n shift,\n root,\n tail,\n metadata,\n );\n}\n\nfunction emptyVectorWithMetadata(metadata) {\n return metadata === null\n ? EMPTY_VECTOR\n : makeVector(0, BRANCH_BITS, EMPTY_ROOT, EMPTY_TAIL, metadata);\n}\n\nfunction makeTransientVector(vector) {\n return new TransientVector(TRANSIENT_VECTOR_CONSTRUCTOR_TOKEN, vector);\n}\n\nfunction activeTransientVectorState(vector) {\n const state = vector[TRANSIENT_VECTOR_STATE];\n if (!state.active) {\n recordInvalidTransientVectorCall();\n throw new TypeError(\"transient vector is no longer editable\");\n }\n return state;\n}\n\nfunction editableTransientTail(state) {\n if (!state.tailOwned) {\n state.tail = state.tail.slice();\n state.tailOwned = true;\n recordTransientVectorTailCopy();\n }\n return state.tail;\n}\n\nclass TransientVector {\n constructor(token, vector) {\n if (token !== TRANSIENT_VECTOR_CONSTRUCTOR_TOKEN ||\n !(vector instanceof PersistentVector)) {\n throw new TypeError(\"transient vectors must be created from a persistent vector\");\n }\n const source = vector[VECTOR_STATE];\n this[TRANSIENT_VECTOR_STATE] = {\n active: true,\n changed: false,\n owner: Object.freeze({}),\n source: vector,\n count: source.count,\n shift: source.shift,\n root: source.root,\n tail: source.tail,\n tailOwned: false,\n metadata: source.metadata,\n };\n Object.defineProperty(this, \"__eliscript_transient__\", {\n enumerable: true,\n get() {\n throw new TypeError(\"transient vectors cannot be serialized\");\n },\n });\n Object.freeze(this);\n }\n\n [TRANSIENT_CONJ](value) {\n const state = activeTransientVectorState(this);\n if (state.count === MAX_COUNT) {\n throw new RangeError(`persistent vector cannot exceed ${MAX_COUNT} values`);\n }\n if (state.tail.length < BRANCH_WIDTH) {\n editableTransientTail(state).push(value);\n recordTransientVectorTailMutation();\n } else {\n if (!state.tailOwned) {\n state.tail = state.tail.slice();\n recordTransientVectorTailCopy();\n }\n const tailNode = new VectorNode(state.tail, state.owner);\n if ((state.count >>> BRANCH_BITS) > (1 << state.shift)) {\n state.root = new VectorNode([\n state.root,\n transientNewPath(state.shift, tailNode, state.owner),\n ], state.owner);\n state.shift += BRANCH_BITS;\n recordRootGrowth();\n } else {\n state.root = transientPushTail(\n state.shift,\n state.root,\n tailNode,\n state.count,\n state.owner,\n );\n }\n state.tail = [value];\n state.tailOwned = true;\n recordTransientVectorTailMutation();\n }\n state.count += 1;\n state.changed = true;\n return this;\n }\n\n [TRANSIENT_ASSOC](index, value) {\n const state = activeTransientVectorState(this);\n if (index === state.count) {\n return this[TRANSIENT_CONJ](value);\n }\n assertIndex(index, state.count, \"assocBang\");\n if (index >= tailOffset(state.count)) {\n editableTransientTail(state)[index & BRANCH_MASK] = value;\n recordTransientVectorTailMutation();\n } else {\n state.root = transientAssocNode(\n state.shift,\n state.root,\n index,\n value,\n state.owner,\n );\n }\n state.changed = true;\n return this;\n }\n\n [TRANSIENT_PERSISTENT]() {\n const state = activeTransientVectorState(this);\n const result = state.changed\n ? makeVector(\n state.count,\n state.shift,\n state.root,\n state.tail,\n state.metadata,\n )\n : state.source;\n state.active = false;\n state.owner = null;\n recordTransientVectorPersistent();\n return result;\n }\n\n toJSON() {\n throw new TypeError(\"transient vectors cannot be serialized\");\n }\n\n get [Symbol.toStringTag]() {\n return \"EliscriptTransientVector\";\n }\n}\n\nexport class PersistentVector {\n constructor(token, count, shift, root, tail, metadata = null) {\n if (token !== VECTOR_CONSTRUCTOR_TOKEN) {\n throw new TypeError(\n \"PersistentVector values must be created with persistentVector or PersistentVector.from\",\n );\n }\n this[VECTOR_STATE] = {\n count,\n shift,\n root,\n tail,\n metadata,\n };\n Object.freeze(this);\n }\n\n static empty() {\n return EMPTY_VECTOR;\n }\n\n static single(value) {\n return makeVector(\n 1,\n BRANCH_BITS,\n EMPTY_ROOT,\n allocateTail([value]),\n null,\n );\n }\n\n static pairWithMeta(first, second, metadata = null) {\n return makeVector(\n 2,\n BRANCH_BITS,\n EMPTY_ROOT,\n allocateTail([first, second]),\n metadata,\n );\n }\n\n static rawSlot(vector, index) {\n return vector[VECTOR_STATE].tail[index];\n }\n\n static from(iterable) {\n if (iterable instanceof PersistentVector) {\n return iterable;\n }\n if (\n Array.isArray(iterable) &&\n Object.getPrototypeOf(iterable) === Array.prototype &&\n !Object.hasOwn(iterable, Symbol.iterator) &&\n iterable[Symbol.iterator] === Array.prototype[Symbol.iterator]\n ) {\n const length = iterable.length;\n if (length === 0) return EMPTY_VECTOR;\n if (length <= BRANCH_WIDTH) {\n return makeVector(\n length,\n BRANCH_BITS,\n EMPTY_ROOT,\n allocateTail(iterable.slice()),\n );\n }\n let root = EMPTY_ROOT;\n let shift = BRANCH_BITS;\n let count = BRANCH_WIDTH;\n let tail = allocateTail(iterable.slice(0, BRANCH_WIDTH));\n while (count < length) {\n const nextEnd = Math.min(count + BRANCH_WIDTH, length);\n const tailNode = new VectorNode(tail);\n if ((count >>> BRANCH_BITS) > (1 << shift)) {\n root = new VectorNode([\n root,\n newPath(shift, tailNode),\n ]);\n shift += BRANCH_BITS;\n recordRootGrowth();\n } else {\n root = pushTail(shift, root, tailNode, count);\n }\n tail = allocateTail(iterable.slice(count, nextEnd));\n count = nextEnd;\n }\n return makeVector(length, shift, root, tail);\n }\n let result = EMPTY_VECTOR;\n for (const value of iterable) {\n result = result.conj(value);\n }\n return result;\n }\n\n get count() {\n return this[VECTOR_STATE].count;\n }\n\n get size() {\n return this[VECTOR_STATE].count;\n }\n\n nth(index, notFound = MISSING) {\n const state = this[VECTOR_STATE];\n if (((index | 0) === index || Number.isInteger(index)) && index >= 0 && index < state.count) {\n if (state.count <= BRANCH_WIDTH) {\n const value = state.tail[index];\n if (\n index === 1 &&\n state.count === 2 &&\n state.metadata !== null &&\n Array.isArray(value) &&\n value.length === 6 &&\n value[5] === true &&\n !Object.isFrozen(value)\n ) {\n Object.freeze(value);\n }\n return value;\n }\n return arrayFor(state, index)[index & BRANCH_MASK];\n }\n if (notFound !== MISSING) {\n return notFound;\n }\n assertIndex(index, state.count, \"nth\");\n }\n\n assoc(index, value) {\n const state = this[VECTOR_STATE];\n if (index === state.count) {\n return this.conj(value);\n }\n assertIndex(index, state.count, \"assoc\");\n\n if (index >= tailOffset(state.count)) {\n const tail = state.tail.slice();\n tail[index & BRANCH_MASK] = value;\n return makeVector(\n state.count,\n state.shift,\n state.root,\n allocateTail(tail),\n state.metadata,\n );\n }\n return makeVector(\n state.count,\n state.shift,\n assocNode(state.shift, state.root, index, value),\n state.tail,\n state.metadata,\n );\n }\n\n conj(value) {\n const state = this[VECTOR_STATE];\n if (state.count === MAX_COUNT) {\n throw new RangeError(`persistent vector cannot exceed ${MAX_COUNT} values`);\n }\n if (state.tail.length < BRANCH_WIDTH) {\n return makeVector(\n state.count + 1,\n state.shift,\n state.root,\n allocateTail([...state.tail, value]),\n state.metadata,\n );\n }\n\n const tailNode = new VectorNode(state.tail);\n let shift = state.shift;\n let root;\n if ((state.count >>> BRANCH_BITS) > (1 << state.shift)) {\n root = new VectorNode([\n state.root,\n newPath(state.shift, tailNode),\n ]);\n shift += BRANCH_BITS;\n recordRootGrowth();\n } else {\n root = pushTail(state.shift, state.root, tailNode, state.count);\n }\n return makeVector(\n state.count + 1,\n shift,\n root,\n allocateTail([value]),\n state.metadata,\n );\n }\n\n peek(notFound = null) {\n const state = this[VECTOR_STATE];\n return state.count === 0 ? notFound : state.tail[state.tail.length - 1];\n }\n\n pop() {\n const state = this[VECTOR_STATE];\n if (state.count === 0) {\n throw new RangeError(\"cannot pop an empty persistent vector\");\n }\n if (state.count === 1) {\n return emptyVectorWithMetadata(state.metadata);\n }\n if (state.tail.length > 1) {\n return makeVector(\n state.count - 1,\n state.shift,\n state.root,\n allocateTail(state.tail.slice(0, -1)),\n state.metadata,\n );\n }\n\n const tail = allocateTail([...arrayFor(state, state.count - 2)]);\n let root = popTail(state.shift, state.root, state.count) ?? EMPTY_ROOT;\n let shift = state.shift;\n if (shift > BRANCH_BITS && root.slots[1] === undefined) {\n root = root.slots[0];\n shift -= BRANCH_BITS;\n }\n return makeVector(\n state.count - 1,\n shift,\n root,\n tail,\n state.metadata,\n );\n }\n\n reduce(reducer, ...initial) {\n if (typeof reducer !== \"function\") {\n throw new TypeError(\"persistent vector reducer must be a function\");\n }\n const state = this[VECTOR_STATE];\n let accumulator;\n let index = 0;\n if (initial.length === 0) {\n if (state.count === 0) {\n throw new TypeError(\"cannot reduce an empty persistent vector without an initial value\");\n }\n accumulator = this.nth(0);\n index = 1;\n } else {\n accumulator = initial[0];\n }\n\n while (index < state.count) {\n const chunk = arrayFor(state, index);\n const chunkStart = index & BRANCH_MASK;\n const chunkLength = Math.min(chunk.length, state.count - (index - chunkStart));\n for (let offset = chunkStart; offset < chunkLength; offset += 1) {\n accumulator = reducer(accumulator, chunk[offset], index);\n index += 1;\n }\n }\n return accumulator;\n }\n\n [COLLECTION_COUNT]() {\n return this.count;\n }\n\n [COLLECTION_EMPTY]() {\n return emptyVectorWithMetadata(this[VECTOR_STATE].metadata);\n }\n\n [COLLECTION_CONJ](value) {\n return this.conj(value);\n }\n\n [COLLECTION_PEEK]() {\n return this.peek();\n }\n\n [COLLECTION_POP]() {\n return this.pop();\n }\n\n [COLLECTION_RSEQ]() {\n const state = this[VECTOR_STATE];\n return state.count === 0\n ? null\n : sequenceView(() => reverseVectorIterator(state), state.count);\n }\n\n [COLLECTION_GET](index, notFound = null) {\n return this.nth(index, notFound);\n }\n\n [COLLECTION_ASSOC](index, value) {\n return this.assoc(index, value);\n }\n\n [COLLECTION_CONTAINS](index) {\n return Number.isInteger(index) && index >= 0 && index < this.count;\n }\n\n [COLLECTION_NTH](index, ...notFound) {\n return notFound.length === 0\n ? this.nth(index)\n : this.nth(index, notFound[0]);\n }\n\n [COLLECTION_SEQ]() {\n return this.count === 0\n ? null\n : sequenceView(() => this[Symbol.iterator](), this.count);\n }\n\n [COLLECTION_REDUCE](reducer, ...initial) {\n return reduceIterable(this, reducer, ...initial);\n }\n\n [COLLECTION_REDUCE_KV](reducer, initial) {\n const state = this[VECTOR_STATE];\n let result = initial;\n let index = 0;\n while (index < state.count) {\n const chunk = arrayFor(state, index);\n const chunkStart = index & BRANCH_MASK;\n const chunkLength = Math.min(chunk.length, state.count - (index - chunkStart));\n for (let offset = chunkStart; offset < chunkLength; offset += 1) {\n result = reducer(result, index, chunk[offset]);\n index += 1;\n if (isReducedValue(result)) return unreducedValue(result);\n }\n }\n return result;\n }\n\n [EDITABLE_TRANSIENT]() {\n return makeTransientVector(this);\n }\n\n toArray() {\n return this.reduce((values, value) => {\n values.push(value);\n return values;\n }, []);\n }\n\n sliceVector(start, end) {\n const state = this[VECTOR_STATE];\n const length = end - start;\n if (length <= 0) return EMPTY_VECTOR;\n if (start === 0 && end >= state.count && state.metadata === null) {\n return this;\n }\n const values = new Array(length);\n let outIndex = 0;\n let index = start;\n while (index < end) {\n const chunk = arrayFor(state, index);\n const chunkOffset = index & BRANCH_MASK;\n const chunkBase = index - chunkOffset;\n const chunkEnd = Math.min(end - chunkBase, chunk.length);\n for (let i = chunkOffset; i < chunkEnd; i += 1) {\n values[outIndex] = chunk[i];\n outIndex += 1;\n }\n index = chunkBase + chunkEnd;\n }\n return PersistentVector.from(values);\n }\n\n [VALUE_EQUAL](other, equal) {\n if (this === other) {\n return true;\n }\n if (!(other instanceof PersistentVector) || other.count !== this.count) {\n return false;\n }\n const right = other[Symbol.iterator]();\n for (const value of this) {\n if (!equal(value, right.next().value)) {\n return false;\n }\n }\n return true;\n }\n\n [VALUE_HASH](hash) {\n return orderedCollectionHash(this, hash, VECTOR_HASH_TAG);\n }\n\n [METADATA_READ]() {\n return this[VECTOR_STATE].metadata;\n }\n\n [METADATA_WITH](metadata) {\n const state = this[VECTOR_STATE];\n return metadata === state.metadata\n ? this\n : makeVector(\n state.count,\n state.shift,\n state.root,\n state.tail,\n metadata,\n );\n }\n\n *[Symbol.iterator]() {\n const state = this[VECTOR_STATE];\n let index = 0;\n while (index < state.count) {\n const chunk = arrayFor(state, index);\n const chunkStart = index & BRANCH_MASK;\n const chunkLength = Math.min(chunk.length, state.count - (index - chunkStart));\n for (let offset = chunkStart; offset < chunkLength; offset += 1) {\n yield chunk[offset];\n index += 1;\n }\n }\n }\n\n get [Symbol.toStringTag]() {\n return \"EliscriptPersistentVector\";\n }\n}\n\nclass PersistentSubVector extends PersistentVector {\n constructor(vector, start, end, metadata = null) {\n const source = vector[VECTOR_STATE];\n super(\n VECTOR_CONSTRUCTOR_TOKEN,\n source.count,\n source.shift,\n source.root,\n source.tail,\n metadata,\n );\n SUBVECTOR_STATE.set(this, Object.freeze({ vector, start, end, metadata }));\n }\n\n get count() {\n const state = SUBVECTOR_STATE.get(this);\n return state.end - state.start;\n }\n\n get size() {\n return this.count;\n }\n\n sliceVector(start, end) {\n const state = SUBVECTOR_STATE.get(this);\n return state.vector.sliceVector(state.start + start, state.start + end);\n }\n\n nth(index, notFound = MISSING) {\n const state = SUBVECTOR_STATE.get(this);\n const count = state.end - state.start;\n if (!Number.isInteger(index) || index < 0 || index >= count) {\n if (notFound !== MISSING) return notFound;\n assertIndex(index, count, \"subvec nth\");\n }\n return state.vector.nth(state.start + index);\n }\n\n assoc(index, value) {\n const state = SUBVECTOR_STATE.get(this);\n const count = state.end - state.start;\n if (!Number.isInteger(index) || index < 0 || index > count) {\n throw new RangeError(\n `subvec assoc index ${String(index)} is outside [0, ${count}]`,\n );\n }\n const absoluteIndex = state.start + index;\n const vector = absoluteIndex === state.vector.count\n ? state.vector.conj(value)\n : state.vector.assoc(absoluteIndex, value);\n return new PersistentSubVector(\n vector,\n state.start,\n Math.max(state.end, absoluteIndex + 1),\n state.metadata,\n );\n }\n\n conj(value) {\n return this.assoc(this.count, value);\n }\n\n peek(notFound = null) {\n const state = SUBVECTOR_STATE.get(this);\n return state.start === state.end\n ? notFound\n : state.vector.nth(state.end - 1);\n }\n\n pop() {\n const state = SUBVECTOR_STATE.get(this);\n if (state.start === state.end) {\n throw new RangeError(\"cannot pop an empty persistent subvector\");\n }\n return state.end - state.start === 1\n ? emptyVectorWithMetadata(state.metadata)\n : new PersistentSubVector(\n state.vector,\n state.start,\n state.end - 1,\n state.metadata,\n );\n }\n\n reduce(reducer, ...initial) {\n if (typeof reducer !== \"function\") {\n throw new TypeError(\"persistent subvector reducer must be a function\");\n }\n const state = SUBVECTOR_STATE.get(this);\n let index = 0;\n let result;\n if (initial.length === 0) {\n if (state.start === state.end) {\n throw new TypeError(\n \"cannot reduce an empty persistent subvector without an initial value\",\n );\n }\n result = state.vector.nth(state.start);\n index = 1;\n } else {\n result = initial[0];\n }\n while (index < state.end - state.start) {\n result = reducer(result, state.vector.nth(state.start + index), index);\n index += 1;\n }\n return result;\n }\n\n [COLLECTION_COUNT]() {\n return this.count;\n }\n\n [COLLECTION_EMPTY]() {\n return emptyVectorWithMetadata(SUBVECTOR_STATE.get(this).metadata);\n }\n\n [COLLECTION_CONJ](value) {\n return this.conj(value);\n }\n\n [COLLECTION_PEEK]() {\n return this.peek();\n }\n\n [COLLECTION_POP]() {\n return this.pop();\n }\n\n [COLLECTION_RSEQ]() {\n const state = SUBVECTOR_STATE.get(this);\n return state.start === state.end\n ? null\n : sequenceView(\n () => vectorRangeIterator(\n state.vector,\n state.start,\n state.end,\n true,\n ),\n state.end - state.start,\n );\n }\n\n [COLLECTION_GET](index, notFound = null) {\n return this.nth(index, notFound);\n }\n\n [COLLECTION_ASSOC](index, value) {\n return this.assoc(index, value);\n }\n\n [COLLECTION_CONTAINS](index) {\n return Number.isInteger(index) && index >= 0 && index < this.count;\n }\n\n [COLLECTION_NTH](index, ...notFound) {\n return notFound.length === 0\n ? this.nth(index)\n : this.nth(index, notFound[0]);\n }\n\n [COLLECTION_SEQ]() {\n return this.count === 0\n ? null\n : sequenceView(() => this[Symbol.iterator](), this.count);\n }\n\n [COLLECTION_REDUCE](reducer, ...initial) {\n return reduceIterable(this, reducer, ...initial);\n }\n\n [COLLECTION_REDUCE_KV](reducer, initial) {\n const state = SUBVECTOR_STATE.get(this);\n let result = initial;\n let index = 0;\n while (state.start + index < state.end) {\n result = reducer(result, index, state.vector.nth(state.start + index));\n index += 1;\n if (isReducedValue(result)) return unreducedValue(result);\n }\n return result;\n }\n\n [EDITABLE_TRANSIENT]() {\n const state = SUBVECTOR_STATE.get(this);\n const builder = makeTransientVector(\n emptyVectorWithMetadata(state.metadata),\n );\n for (const value of this) {\n builder[TRANSIENT_CONJ](value);\n }\n return builder;\n }\n\n [METADATA_READ]() {\n return SUBVECTOR_STATE.get(this).metadata;\n }\n\n [METADATA_WITH](metadata) {\n const state = SUBVECTOR_STATE.get(this);\n return metadata === state.metadata\n ? this\n : new PersistentSubVector(\n state.vector,\n state.start,\n state.end,\n metadata,\n );\n }\n\n [Symbol.iterator]() {\n const state = SUBVECTOR_STATE.get(this);\n return vectorRangeIterator(state.vector, state.start, state.end);\n }\n\n get [Symbol.toStringTag]() {\n return \"EliscriptPersistentSubVector\";\n }\n}\n\nexport const EMPTY_VECTOR = makeVector(0, BRANCH_BITS, EMPTY_ROOT, EMPTY_TAIL);\n\nexport function persistentVector(...values) {\n if (values.length === 0) return EMPTY_VECTOR;\n if (values.length <= BRANCH_WIDTH) {\n return makeVector(\n values.length,\n BRANCH_BITS,\n EMPTY_ROOT,\n allocateTail(values),\n );\n }\n return PersistentVector.from(values);\n}\n\nexport function subvec(vector, start, end = undefined) {\n if (!(vector instanceof PersistentVector)) {\n throw new TypeError(\"subvec expects a persistent vector\");\n }\n const count = vector.count;\n const limit = end == null ? count : end;\n if (!Number.isSafeInteger(start) || !Number.isSafeInteger(limit) ||\n start < 0 || limit < start || limit > count) {\n throw new RangeError(\n `subvec range [${String(start)}, ${String(limit)}) is outside [0, ${count}]`,\n );\n }\n if (vector instanceof PersistentSubVector) {\n const state = SUBVECTOR_STATE.get(vector);\n return new PersistentSubVector(\n state.vector,\n state.start + start,\n state.start + limit,\n );\n }\n return new PersistentSubVector(vector, start, limit);\n}\n\nexport function isPersistentVector(value) {\n return value instanceof PersistentVector;\n}\n\n// Bulk transports preserve a view's original base and bounds. Only the\n// constructor-owned WeakMap establishes this brand; user properties do not.\nexport function readPersistentVectorView(value) {\n return SUBVECTOR_STATE.get(value);\n}\n"))
|