eliscript 0.0.3 → 0.0.4
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 +5 -5
- 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/package.json +2 -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/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
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.map-internals
|
|
2
|
+
(js* "import { equalValues, hashValue } from \"./value.mjs\";\n\nexport const MAP_STATE = Symbol(\"eliscript.map.state\");\nexport const MAP_CONSTRUCTOR_TOKEN = Symbol(\"eliscript.map.constructor\");\nexport const MAP_NOT_FOUND = Symbol(\"eliscript.map.not-found\");\nexport const TRANSIENT_MAP_STATE = Symbol(\"eliscript.map.transient-state\");\nexport const TRANSIENT_MAP_CONSTRUCTOR_TOKEN = Symbol(\n \"eliscript.map.transient-constructor\",\n);\n\nexport const ARRAY_NODE_THRESHOLD = 32;\nexport const BITMAP_NODE_THRESHOLD = 24;\n\nconst BRANCH_MASK = 31;\n\nconst metrics = {\n nodeAllocations: 0,\n nodeVisits: 0,\n entryAllocations: 0,\n keyEqualityChecks: 0,\n promotions: 0,\n demotions: 0,\n};\n\nconst transientMetrics = {\n nodeClones: 0,\n nodeMutations: 0,\n persistentCalls: 0,\n invalidCalls: 0,\n};\n\nexport class MapEntry {\n constructor(key, value, hash) {\n metrics.entryAllocations += 1;\n this.key = key;\n this.value = value;\n this.hash = hash >>> 0;\n Object.freeze(this);\n }\n}\n\nexport class BitmapIndexedNode {\n constructor(bitmap = 0, items = [], owner = null) {\n metrics.nodeAllocations += 1;\n this.bitmap = bitmap >>> 0;\n this.owner = owner;\n this.items = owner === null ? Object.freeze(items) : items;\n if (owner === null) {\n Object.freeze(this);\n }\n }\n}\n\nexport class ArrayNode {\n constructor(count, children, owner = null) {\n metrics.nodeAllocations += 1;\n this.count = count;\n this.owner = owner;\n this.children = owner === null ? Object.freeze(children) : children;\n if (owner === null) {\n Object.freeze(this);\n }\n }\n}\n\nexport class HashCollisionNode {\n constructor(hash, entries, owner = null) {\n metrics.nodeAllocations += 1;\n this.hash = hash >>> 0;\n this.owner = owner;\n this.entries = owner === null ? Object.freeze(entries) : entries;\n if (owner === null) {\n Object.freeze(this);\n }\n }\n}\n\nfunction editableMapNode(node, owner) {\n if (node.owner === owner) {\n return node;\n }\n transientMetrics.nodeClones += 1;\n if (node instanceof BitmapIndexedNode) {\n return new BitmapIndexedNode(node.bitmap, node.items.slice(), owner);\n }\n if (node instanceof ArrayNode) {\n return new ArrayNode(node.count, node.children.slice(), owner);\n }\n return new HashCollisionNode(node.hash, node.entries.slice(), owner);\n}\n\nfunction recordTransientNodeMutation() {\n transientMetrics.nodeMutations += 1;\n}\n\nfunction visitNode(node) {\n metrics.nodeVisits += 1;\n return node;\n}\n\nfunction keysEqual(left, right) {\n metrics.keyEqualityChecks += 1;\n return equalValues(left, right);\n}\n\nfunction branchIndex(hash, shift) {\n return (hash >>> shift) & BRANCH_MASK;\n}\n\nfunction bitPosition(hash, shift) {\n return (1 << branchIndex(hash, shift)) >>> 0;\n}\n\nfunction popcount(value) {\n let bits = value >>> 0;\n bits -= (bits >>> 1) & 0x5555_5555;\n bits = (bits & 0x3333_3333) + ((bits >>> 2) & 0x3333_3333);\n return Math.imul((bits + (bits >>> 4)) & 0x0f0f_0f0f, 0x0101_0101) >>> 24;\n}\n\nfunction packedIndex(bitmap, bit) {\n return popcount((bitmap & ((bit - 1) >>> 0)) >>> 0);\n}\n\nfunction sameEntry(entry, hash, key) {\n return entry.hash === hash && keysEqual(entry.key, key);\n}\n\nfunction mergeEntries(shift, left, right) {\n if (left.hash === right.hash) {\n return new HashCollisionNode(left.hash, [left, right]);\n }\n const leftIndex = branchIndex(left.hash, shift);\n const rightIndex = branchIndex(right.hash, shift);\n if (leftIndex === rightIndex) {\n return new BitmapIndexedNode(\n (1 << leftIndex) >>> 0,\n [mergeEntries(shift + 5, left, right)],\n );\n }\n const bitmap = ((1 << leftIndex) | (1 << rightIndex)) >>> 0;\n return new BitmapIndexedNode(\n bitmap,\n leftIndex < rightIndex ? [left, right] : [right, left],\n );\n}\n\nfunction mergeCollisionAndEntry(shift, node, entry) {\n const nodeIndex = branchIndex(node.hash, shift);\n const entryIndex = branchIndex(entry.hash, shift);\n if (nodeIndex === entryIndex) {\n return new BitmapIndexedNode(\n (1 << nodeIndex) >>> 0,\n [mergeCollisionAndEntry(shift + 5, node, entry)],\n );\n }\n const bitmap = ((1 << nodeIndex) | (1 << entryIndex)) >>> 0;\n return new BitmapIndexedNode(\n bitmap,\n nodeIndex < entryIndex ? [node, entry] : [entry, node],\n );\n}\n\nfunction assocEntry(entry, shift, hash, key, value) {\n if (sameEntry(entry, hash, key)) {\n if (equalValues(entry.value, value)) {\n return { item: entry, added: false, changed: false };\n }\n return {\n item: new MapEntry(entry.key, value, entry.hash),\n added: false,\n changed: true,\n };\n }\n return {\n item: mergeEntries(shift, entry, new MapEntry(key, value, hash)),\n added: true,\n changed: true,\n };\n}\n\nfunction findEntry(entry, hash, key, notFound) {\n return sameEntry(entry, hash, key) ? entry.value : notFound;\n}\n\nfunction promoteBitmapNode(node, shift, hash, key, value) {\n const children = Array(32).fill(undefined);\n let packed = 0;\n for (let index = 0; index < 32; index += 1) {\n const bit = (1 << index) >>> 0;\n if ((node.bitmap & bit) !== 0) {\n children[index] = node.items[packed];\n packed += 1;\n }\n }\n children[branchIndex(hash, shift)] = new MapEntry(key, value, hash);\n metrics.promotions += 1;\n return new ArrayNode(node.items.length + 1, children);\n}\n\nfunction packArrayNode(children) {\n let bitmap = 0;\n const items = [];\n for (let index = 0; index < 32; index += 1) {\n const child = children[index];\n if (child !== undefined) {\n bitmap = (bitmap | (1 << index)) >>> 0;\n items.push(child);\n }\n }\n metrics.demotions += 1;\n return new BitmapIndexedNode(bitmap, items);\n}\n\nfunction findInNode(node, shift, hash, key, notFound) {\n visitNode(node);\n if (node instanceof BitmapIndexedNode) {\n const bit = bitPosition(hash, shift);\n if ((node.bitmap & bit) === 0) {\n return notFound;\n }\n const item = node.items[packedIndex(node.bitmap, bit)];\n return item instanceof MapEntry\n ? findEntry(item, hash, key, notFound)\n : findInNode(item, shift + 5, hash, key, notFound);\n }\n if (node instanceof ArrayNode) {\n const item = node.children[branchIndex(hash, shift)];\n if (item instanceof MapEntry) return findEntry(item, hash, key, notFound);\n return item === undefined\n ? notFound\n : findInNode(item, shift + 5, hash, key, notFound);\n }\n if (node.hash !== hash) {\n return notFound;\n }\n for (const entry of node.entries) {\n if (keysEqual(entry.key, key)) {\n return entry.value;\n }\n }\n return notFound;\n}\n\nfunction assocNode(node, shift, hash, key, value) {\n visitNode(node);\n if (node instanceof BitmapIndexedNode) {\n const bit = bitPosition(hash, shift);\n const index = packedIndex(node.bitmap, bit);\n if ((node.bitmap & bit) === 0) {\n if (node.items.length + 1 >= ARRAY_NODE_THRESHOLD) {\n return {\n item: promoteBitmapNode(node, shift, hash, key, value),\n added: true,\n changed: true,\n };\n }\n const items = node.items.slice();\n items.splice(index, 0, new MapEntry(key, value, hash));\n return {\n item: new BitmapIndexedNode((node.bitmap | bit) >>> 0, items),\n added: true,\n changed: true,\n };\n }\n\n const existing = node.items[index];\n const result = existing instanceof MapEntry\n ? assocEntry(existing, shift + 5, hash, key, value)\n : assocNode(existing, shift + 5, hash, key, value);\n if (!result.changed) {\n return { item: node, added: false, changed: false };\n }\n const items = node.items.slice();\n items[index] = result.item;\n return {\n item: new BitmapIndexedNode(node.bitmap, items),\n added: result.added,\n changed: true,\n };\n }\n\n if (node instanceof ArrayNode) {\n const index = branchIndex(hash, shift);\n const existing = node.children[index];\n // Saturated branches contain no holes. Keep their common leaf update in\n // this frame instead of allocating an intermediate assocEntry result.\n if (node.count === BRANCH_MASK + 1 && existing instanceof MapEntry) {\n let replacement;\n let added;\n if (sameEntry(existing, hash, key)) {\n if (equalValues(existing.value, value)) {\n return { item: node, added: false, changed: false };\n }\n replacement = new MapEntry(existing.key, value, existing.hash);\n added = false;\n } else {\n replacement = mergeEntries(shift + 5, existing, new MapEntry(key, value, hash));\n added = true;\n }\n const children = node.children.slice();\n children[index] = replacement;\n return { item: new ArrayNode(node.count, children), added, changed: true };\n }\n if (existing === undefined) {\n const children = node.children.slice();\n children[index] = new MapEntry(key, value, hash);\n return {\n item: new ArrayNode(node.count + 1, children),\n added: true,\n changed: true,\n };\n }\n const result = existing instanceof MapEntry\n ? assocEntry(existing, shift + 5, hash, key, value)\n : assocNode(existing, shift + 5, hash, key, value);\n if (!result.changed) {\n return { item: node, added: false, changed: false };\n }\n const children = node.children.slice();\n children[index] = result.item;\n return {\n item: new ArrayNode(node.count, children),\n added: result.added,\n changed: true,\n };\n }\n\n if (node.hash !== hash) {\n return {\n item: mergeCollisionAndEntry(\n shift,\n node,\n new MapEntry(key, value, hash),\n ),\n added: true,\n changed: true,\n };\n }\n const index = node.entries.findIndex((entry) => keysEqual(entry.key, key));\n if (index >= 0) {\n const existing = node.entries[index];\n if (equalValues(existing.value, value)) {\n return { item: node, added: false, changed: false };\n }\n const entries = node.entries.slice();\n entries[index] = new MapEntry(existing.key, value, hash);\n return {\n item: new HashCollisionNode(hash, entries),\n added: false,\n changed: true,\n };\n }\n return {\n item: new HashCollisionNode(\n hash,\n [...node.entries, new MapEntry(key, value, hash)],\n ),\n added: true,\n changed: true,\n };\n}\n\nfunction removePackedItem(node, bit, index) {\n if (node.items.length === 1) {\n return undefined;\n }\n const items = node.items.slice();\n items.splice(index, 1);\n return new BitmapIndexedNode((node.bitmap ^ bit) >>> 0, items);\n}\n\nfunction dissocNode(node, shift, hash, key) {\n visitNode(node);\n if (node instanceof BitmapIndexedNode) {\n const bit = bitPosition(hash, shift);\n if ((node.bitmap & bit) === 0) {\n return { item: node, removed: false };\n }\n const index = packedIndex(node.bitmap, bit);\n const existing = node.items[index];\n if (existing instanceof MapEntry) {\n if (!sameEntry(existing, hash, key)) {\n return { item: node, removed: false };\n }\n return {\n item: removePackedItem(node, bit, index),\n removed: true,\n };\n }\n const result = dissocNode(existing, shift + 5, hash, key);\n if (!result.removed) {\n return { item: node, removed: false };\n }\n if (result.item === undefined) {\n return {\n item: removePackedItem(node, bit, index),\n removed: true,\n };\n }\n const items = node.items.slice();\n items[index] = result.item;\n return {\n item: new BitmapIndexedNode(node.bitmap, items),\n removed: true,\n };\n }\n\n if (node instanceof ArrayNode) {\n const index = branchIndex(hash, shift);\n const existing = node.children[index];\n if (existing === undefined) {\n return { item: node, removed: false };\n }\n let result;\n if (existing instanceof MapEntry) {\n result = sameEntry(existing, hash, key)\n ? { item: undefined, removed: true }\n : { item: existing, removed: false };\n } else {\n result = dissocNode(existing, shift + 5, hash, key);\n }\n if (!result.removed) {\n return { item: node, removed: false };\n }\n const children = node.children.slice();\n children[index] = result.item;\n const count = result.item === undefined ? node.count - 1 : node.count;\n return {\n item: count <= BITMAP_NODE_THRESHOLD\n ? packArrayNode(children)\n : new ArrayNode(count, children),\n removed: true,\n };\n }\n\n if (node.hash !== hash) {\n return { item: node, removed: false };\n }\n const index = node.entries.findIndex((entry) => keysEqual(entry.key, key));\n if (index < 0) {\n return { item: node, removed: false };\n }\n if (node.entries.length === 2) {\n return { item: node.entries[index === 0 ? 1 : 0], removed: true };\n }\n const entries = node.entries.slice();\n entries.splice(index, 1);\n return {\n item: new HashCollisionNode(hash, entries),\n removed: true,\n };\n}\n\nfunction transientMergeEntries(shift, left, right, owner) {\n if (left.hash === right.hash) {\n return new HashCollisionNode(left.hash, [left, right], owner);\n }\n const leftIndex = branchIndex(left.hash, shift);\n const rightIndex = branchIndex(right.hash, shift);\n if (leftIndex === rightIndex) {\n return new BitmapIndexedNode(\n (1 << leftIndex) >>> 0,\n [transientMergeEntries(shift + 5, left, right, owner)],\n owner,\n );\n }\n const bitmap = ((1 << leftIndex) | (1 << rightIndex)) >>> 0;\n return new BitmapIndexedNode(\n bitmap,\n leftIndex < rightIndex ? [left, right] : [right, left],\n owner,\n );\n}\n\nfunction transientMergeCollisionAndEntry(shift, node, entry, owner) {\n const nodeIndex = branchIndex(node.hash, shift);\n const entryIndex = branchIndex(entry.hash, shift);\n if (nodeIndex === entryIndex) {\n return new BitmapIndexedNode(\n (1 << nodeIndex) >>> 0,\n [transientMergeCollisionAndEntry(shift + 5, node, entry, owner)],\n owner,\n );\n }\n const bitmap = ((1 << nodeIndex) | (1 << entryIndex)) >>> 0;\n return new BitmapIndexedNode(\n bitmap,\n nodeIndex < entryIndex ? [node, entry] : [entry, node],\n owner,\n );\n}\n\nfunction transientAssocEntry(entry, shift, hash, key, value, owner) {\n if (sameEntry(entry, hash, key)) {\n if (equalValues(entry.value, value)) {\n return { item: entry, added: false, changed: false };\n }\n return {\n item: new MapEntry(entry.key, value, entry.hash),\n added: false,\n changed: true,\n };\n }\n return {\n item: transientMergeEntries(\n shift,\n entry,\n new MapEntry(key, value, hash),\n owner,\n ),\n added: true,\n changed: true,\n };\n}\n\nfunction transientPromoteBitmapNode(node, shift, hash, key, value, owner) {\n const children = Array(32).fill(undefined);\n let packed = 0;\n for (let index = 0; index < 32; index += 1) {\n const bit = (1 << index) >>> 0;\n if ((node.bitmap & bit) !== 0) {\n children[index] = node.items[packed];\n packed += 1;\n }\n }\n children[branchIndex(hash, shift)] = new MapEntry(key, value, hash);\n metrics.promotions += 1;\n return new ArrayNode(node.items.length + 1, children, owner);\n}\n\nfunction transientPackArrayNode(node, removedIndex, owner) {\n let bitmap = 0;\n const items = [];\n for (let index = 0; index < 32; index += 1) {\n if (index === removedIndex) {\n continue;\n }\n const child = node.children[index];\n if (child !== undefined) {\n bitmap = (bitmap | (1 << index)) >>> 0;\n items.push(child);\n }\n }\n metrics.demotions += 1;\n return new BitmapIndexedNode(bitmap, items, owner);\n}\n\nfunction transientAssocNode(node, shift, hash, key, value, owner) {\n visitNode(node);\n if (node instanceof BitmapIndexedNode) {\n const bit = bitPosition(hash, shift);\n const index = packedIndex(node.bitmap, bit);\n if ((node.bitmap & bit) === 0) {\n if (node.items.length + 1 >= ARRAY_NODE_THRESHOLD) {\n return {\n item: transientPromoteBitmapNode(\n node,\n shift,\n hash,\n key,\n value,\n owner,\n ),\n added: true,\n changed: true,\n };\n }\n const editable = editableMapNode(node, owner);\n editable.bitmap = (editable.bitmap | bit) >>> 0;\n editable.items.splice(index, 0, new MapEntry(key, value, hash));\n recordTransientNodeMutation();\n return { item: editable, added: true, changed: true };\n }\n\n const existing = node.items[index];\n const result = existing instanceof MapEntry\n ? transientAssocEntry(existing, shift + 5, hash, key, value, owner)\n : transientAssocNode(existing, shift + 5, hash, key, value, owner);\n if (!result.changed) {\n return { item: node, added: false, changed: false };\n }\n const editable = editableMapNode(node, owner);\n editable.items[index] = result.item;\n recordTransientNodeMutation();\n return { item: editable, added: result.added, changed: true };\n }\n\n if (node instanceof ArrayNode) {\n const index = branchIndex(hash, shift);\n const existing = node.children[index];\n if (existing === undefined) {\n const editable = editableMapNode(node, owner);\n editable.children[index] = new MapEntry(key, value, hash);\n editable.count += 1;\n recordTransientNodeMutation();\n return { item: editable, added: true, changed: true };\n }\n const result = existing instanceof MapEntry\n ? transientAssocEntry(existing, shift + 5, hash, key, value, owner)\n : transientAssocNode(existing, shift + 5, hash, key, value, owner);\n if (!result.changed) {\n return { item: node, added: false, changed: false };\n }\n const editable = editableMapNode(node, owner);\n editable.children[index] = result.item;\n recordTransientNodeMutation();\n return { item: editable, added: result.added, changed: true };\n }\n\n if (node.hash !== hash) {\n return {\n item: transientMergeCollisionAndEntry(\n shift,\n node,\n new MapEntry(key, value, hash),\n owner,\n ),\n added: true,\n changed: true,\n };\n }\n const index = node.entries.findIndex((entry) => keysEqual(entry.key, key));\n if (index >= 0) {\n const existing = node.entries[index];\n if (equalValues(existing.value, value)) {\n return { item: node, added: false, changed: false };\n }\n const editable = editableMapNode(node, owner);\n editable.entries[index] = new MapEntry(existing.key, value, hash);\n recordTransientNodeMutation();\n return { item: editable, added: false, changed: true };\n }\n const editable = editableMapNode(node, owner);\n editable.entries.push(new MapEntry(key, value, hash));\n recordTransientNodeMutation();\n return { item: editable, added: true, changed: true };\n}\n\nfunction transientRemovePackedItem(node, bit, index, owner) {\n if (node.items.length === 1) {\n return undefined;\n }\n const editable = editableMapNode(node, owner);\n editable.bitmap = (editable.bitmap ^ bit) >>> 0;\n editable.items.splice(index, 1);\n recordTransientNodeMutation();\n return editable;\n}\n\nfunction transientDissocNode(node, shift, hash, key, owner) {\n visitNode(node);\n if (node instanceof BitmapIndexedNode) {\n const bit = bitPosition(hash, shift);\n if ((node.bitmap & bit) === 0) {\n return { item: node, removed: false };\n }\n const index = packedIndex(node.bitmap, bit);\n const existing = node.items[index];\n if (existing instanceof MapEntry) {\n if (!sameEntry(existing, hash, key)) {\n return { item: node, removed: false };\n }\n return {\n item: transientRemovePackedItem(node, bit, index, owner),\n removed: true,\n };\n }\n const result = transientDissocNode(\n existing,\n shift + 5,\n hash,\n key,\n owner,\n );\n if (!result.removed) {\n return { item: node, removed: false };\n }\n if (result.item === undefined) {\n return {\n item: transientRemovePackedItem(node, bit, index, owner),\n removed: true,\n };\n }\n const editable = editableMapNode(node, owner);\n editable.items[index] = result.item;\n recordTransientNodeMutation();\n return { item: editable, removed: true };\n }\n\n if (node instanceof ArrayNode) {\n const index = branchIndex(hash, shift);\n const existing = node.children[index];\n if (existing === undefined) {\n return { item: node, removed: false };\n }\n const result = existing instanceof MapEntry\n ? (sameEntry(existing, hash, key)\n ? { item: undefined, removed: true }\n : { item: existing, removed: false })\n : transientDissocNode(existing, shift + 5, hash, key, owner);\n if (!result.removed) {\n return { item: node, removed: false };\n }\n const count = result.item === undefined ? node.count - 1 : node.count;\n if (result.item === undefined && count <= BITMAP_NODE_THRESHOLD) {\n return {\n item: transientPackArrayNode(node, index, owner),\n removed: true,\n };\n }\n const editable = editableMapNode(node, owner);\n editable.children[index] = result.item;\n editable.count = count;\n recordTransientNodeMutation();\n return { item: editable, removed: true };\n }\n\n if (node.hash !== hash) {\n return { item: node, removed: false };\n }\n const index = node.entries.findIndex((entry) => keysEqual(entry.key, key));\n if (index < 0) {\n return { item: node, removed: false };\n }\n if (node.entries.length === 2) {\n return { item: node.entries[index === 0 ? 1 : 0], removed: true };\n }\n const editable = editableMapNode(node, owner);\n editable.entries.splice(index, 1);\n recordTransientNodeMutation();\n return { item: editable, removed: true };\n}\n\nexport function mapFind(root, hash, key, notFound) {\n return findInNode(root, 0, hash >>> 0, key, notFound);\n}\n\nexport function mapAssoc(root, hash, key, value) {\n return assocNode(root, 0, hash >>> 0, key, value);\n}\n\nexport function mapDissoc(root, hash, key) {\n return dissocNode(root, 0, hash >>> 0, key);\n}\n\nexport function mapAssocTransient(root, owner, hash, key, value) {\n return transientAssocNode(root, 0, hash >>> 0, key, value, owner);\n}\n\nexport function mapDissocTransient(root, owner, hash, key) {\n return transientDissocNode(root, 0, hash >>> 0, key, owner);\n}\n\nexport function* mapEntries(item) {\n if (item instanceof MapEntry) {\n yield item;\n return;\n }\n if (item instanceof BitmapIndexedNode) {\n for (const child of item.items) {\n yield* mapEntries(child);\n }\n return;\n }\n if (item instanceof ArrayNode) {\n for (const child of item.children) {\n if (child !== undefined) {\n yield* mapEntries(child);\n }\n }\n return;\n }\n for (const entry of item.entries) {\n yield entry;\n }\n}\n\nexport function mapHash(key) {\n return hashValue(key);\n}\n\nexport function resetMapMetrics() {\n for (const key of Object.keys(metrics)) {\n metrics[key] = 0;\n }\n}\n\nexport function readMapMetrics() {\n return Object.freeze({ ...metrics });\n}\n\nexport function resetTransientMapMetrics() {\n for (const key of Object.keys(transientMetrics)) {\n transientMetrics[key] = 0;\n }\n}\n\nexport function readTransientMapMetrics() {\n return Object.freeze({ ...transientMetrics });\n}\n\nexport function recordTransientMapPersistent() {\n transientMetrics.persistentCalls += 1;\n}\n\nexport function recordInvalidTransientMapCall() {\n transientMetrics.invalidCalls += 1;\n}\n\nexport const EMPTY_BITMAP_NODE = new BitmapIndexedNode();\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.map
|
|
2
|
+
(js* "import {\n MAP_CONSTRUCTOR_TOKEN,\n MAP_NOT_FOUND,\n MAP_STATE,\n TRANSIENT_MAP_CONSTRUCTOR_TOKEN,\n TRANSIENT_MAP_STATE,\n EMPTY_BITMAP_NODE,\n mapAssoc,\n mapAssocTransient,\n mapDissoc,\n mapDissocTransient,\n mapEntries,\n mapFind,\n mapHash,\n recordInvalidTransientMapCall,\n recordTransientMapPersistent,\n} from \"./map-internals.mjs\";\nimport {\n VALUE_EQUAL,\n VALUE_HASH,\n finishHash,\n mixHash,\n unorderedCollectionHash,\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_REDUCE,\n COLLECTION_REDUCE_KV,\n COLLECTION_DISSOC,\n COLLECTION_SEQ,\n isReducedValue,\n reduceIterable,\n readCollectionEntry,\n sequenceView,\n unreducedValue,\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_MAP_HAS_VALUE_KEY,\n PERSISTENT_MAP_KIND,\n persistentMapValueEqual,\n} from \"./persistent-kind.mjs\";\n\nconst MAP_HASH_TAG = 0x6c8e_9cf5;\nconst MAP_ENTRY_HASH_TAG = 0x3a91_72eb;\n\nfunction makeMap(count, root, metadata = null) {\n return new PersistentHashMap(MAP_CONSTRUCTOR_TOKEN, count, root, metadata);\n}\n\nfunction emptyMapWithMetadata(metadata) {\n return metadata === null\n ? EMPTY_MAP\n : makeMap(0, EMPTY_BITMAP_NODE, metadata);\n}\n\nfunction makeTransientMap(map) {\n return new TransientHashMap(TRANSIENT_MAP_CONSTRUCTOR_TOKEN, map);\n}\n\nfunction activeTransientMapState(map) {\n const state = map[TRANSIENT_MAP_STATE];\n if (!state.active) {\n recordInvalidTransientMapCall();\n throw new TypeError(\"transient hash map is no longer editable\");\n }\n return state;\n}\n\nfunction pairHash(entry, hash) {\n return finishHash(\n mixHash(mixHash(MAP_ENTRY_HASH_TAG, hash(entry.key)), hash(entry.value)),\n 2,\n );\n}\n\nclass TransientHashMap {\n constructor(token, map) {\n if (token !== TRANSIENT_MAP_CONSTRUCTOR_TOKEN ||\n !(map instanceof PersistentHashMap)) {\n throw new TypeError(\n \"transient hash maps must be created from a persistent hash map\",\n );\n }\n const source = map[MAP_STATE];\n this[TRANSIENT_MAP_STATE] = {\n active: true,\n changed: false,\n owner: Object.freeze({}),\n source: map,\n count: source.count,\n root: source.root,\n metadata: source.metadata,\n };\n Object.defineProperty(this, \"__eliscript_transient__\", {\n enumerable: true,\n get() {\n throw new TypeError(\"transient hash maps cannot be serialized\");\n },\n });\n Object.freeze(this);\n }\n\n [TRANSIENT_CONJ](entry) {\n const [key, value] = readCollectionEntry(entry);\n return this[TRANSIENT_ASSOC](key, value);\n }\n\n get(key, notFound = null) {\n const state = activeTransientMapState(this);\n return mapFind(state.root, mapHash(key), key, notFound);\n }\n\n [TRANSIENT_ASSOC](key, value) {\n const state = activeTransientMapState(this);\n const result = mapAssocTransient(\n state.root,\n state.owner,\n mapHash(key),\n key,\n value,\n );\n if (result.changed) {\n state.root = result.item;\n state.count += result.added ? 1 : 0;\n state.changed = true;\n }\n return this;\n }\n\n [TRANSIENT_DISSOC](key) {\n const state = activeTransientMapState(this);\n const result = mapDissocTransient(\n state.root,\n state.owner,\n mapHash(key),\n key,\n );\n if (result.removed) {\n state.count -= 1;\n state.root = state.count === 0\n ? EMPTY_BITMAP_NODE\n : (result.item ?? EMPTY_BITMAP_NODE);\n state.changed = true;\n }\n return this;\n }\n\n [TRANSIENT_PERSISTENT]() {\n const state = activeTransientMapState(this);\n const result = !state.changed\n ? state.source\n : state.count === 0\n ? emptyMapWithMetadata(state.metadata)\n : makeMap(state.count, state.root, state.metadata);\n state.active = false;\n state.owner = null;\n recordTransientMapPersistent();\n return result;\n }\n\n toJSON() {\n throw new TypeError(\"transient hash maps cannot be serialized\");\n }\n\n get [Symbol.toStringTag]() {\n return \"EliscriptTransientHashMap\";\n }\n}\n\nexport class PersistentHashMap {\n constructor(token, count, root, metadata = null) {\n if (token !== MAP_CONSTRUCTOR_TOKEN) {\n throw new TypeError(\n \"PersistentHashMap values must be created with persistentHashMap or PersistentHashMap.from\",\n );\n }\n this[MAP_STATE] = Object.freeze({ count, root, metadata });\n Object.freeze(this);\n }\n\n static empty() {\n return EMPTY_MAP;\n }\n\n static from(entries) {\n if (entries instanceof PersistentHashMap) {\n return entries;\n }\n let result = EMPTY_MAP;\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[MAP_STATE].count;\n }\n\n get size() {\n return this[MAP_STATE].count;\n }\n\n get(key, notFound = null) {\n return mapFind(\n this[MAP_STATE].root,\n mapHash(key),\n key,\n notFound,\n );\n }\n\n has(key) {\n return this.get(key, MAP_NOT_FOUND) !== MAP_NOT_FOUND;\n }\n\n assoc(key, value) {\n const state = this[MAP_STATE];\n const result = mapAssoc(state.root, mapHash(key), key, value);\n if (!result.changed) {\n return this;\n }\n return makeMap(\n state.count + (result.added ? 1 : 0),\n result.item,\n state.metadata,\n );\n }\n\n dissoc(key) {\n const state = this[MAP_STATE];\n const result = mapDissoc(state.root, mapHash(key), key);\n if (!result.removed) {\n return this;\n }\n if (state.count === 1) {\n return emptyMapWithMetadata(state.metadata);\n }\n return makeMap(\n state.count - 1,\n result.item ?? EMPTY_BITMAP_NODE,\n state.metadata,\n );\n }\n\n *entries() {\n for (const entry of mapEntries(this[MAP_STATE].root)) {\n yield Object.freeze([entry.key, entry.value]);\n }\n }\n\n *keys() {\n for (const entry of mapEntries(this[MAP_STATE].root)) {\n yield entry.key;\n }\n }\n\n *values() {\n for (const entry of mapEntries(this[MAP_STATE].root)) {\n yield entry.value;\n }\n }\n\n reduce(reducer, initial) {\n if (typeof reducer !== \"function\") {\n throw new TypeError(\"persistent hash map reducer must be a function\");\n }\n if (arguments.length < 2) {\n throw new TypeError(\"persistent hash map reduce requires an initial value\");\n }\n let result = initial;\n for (const entry of mapEntries(this[MAP_STATE].root)) {\n result = reducer(result, entry.value, entry.key, this);\n }\n return result;\n }\n\n [COLLECTION_COUNT]() {\n return this.count;\n }\n\n [COLLECTION_EMPTY]() {\n return emptyMapWithMetadata(this[MAP_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_REDUCE](reducer, ...initial) {\n return reduceIterable(this, reducer, ...initial);\n }\n\n [COLLECTION_REDUCE_KV](reducer, initial) {\n let result = initial;\n for (const entry of mapEntries(this[MAP_STATE].root)) {\n result = reducer(result, entry.key, entry.value);\n if (isReducedValue(result)) return unreducedValue(result);\n }\n return result;\n }\n\n [EDITABLE_TRANSIENT]() {\n return makeTransientMap(this);\n }\n\n toMap() {\n return new Map(this.entries());\n }\n\n [PERSISTENT_MAP_HAS_VALUE_KEY](key) {\n return this.has(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(\n mapEntries(this[MAP_STATE].root),\n (entry) => pairHash(entry, hash),\n MAP_HASH_TAG,\n );\n }\n\n [METADATA_READ]() {\n return this[MAP_STATE].metadata;\n }\n\n [METADATA_WITH](metadata) {\n const state = this[MAP_STATE];\n return metadata === state.metadata\n ? this\n : makeMap(state.count, state.root, metadata);\n }\n\n [Symbol.iterator]() {\n return this.entries();\n }\n\n get [Symbol.toStringTag]() {\n return \"EliscriptPersistentHashMap\";\n }\n}\n\nexport const EMPTY_MAP = makeMap(0, EMPTY_BITMAP_NODE);\n\nexport function persistentHashMap(...entries) {\n return PersistentHashMap.from(entries);\n}\n\nexport function isPersistentHashMap(value) {\n return value instanceof PersistentHashMap;\n}\n"))
|
package/runtime/core/map.mjs
CHANGED
|
@@ -121,6 +121,11 @@ class TransientHashMap {
|
|
|
121
121
|
return this[TRANSIENT_ASSOC](key, value);
|
|
122
122
|
}
|
|
123
123
|
|
|
124
|
+
get(key, notFound = null) {
|
|
125
|
+
const state = activeTransientMapState(this);
|
|
126
|
+
return mapFind(state.root, mapHash(key), key, notFound);
|
|
127
|
+
}
|
|
128
|
+
|
|
124
129
|
[TRANSIENT_ASSOC](key, value) {
|
|
125
130
|
const state = activeTransientMapState(this);
|
|
126
131
|
const result = mapAssocTransient(
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.metadata-internals
|
|
2
|
+
(js* "import {\n defineProtocol,\n protocolMethod,\n protocolSlot,\n} from \"./protocol.mjs\";\n\nexport const I_META = defineProtocol(\"IMeta\", [\"meta\"]);\nexport const I_WITH_META = defineProtocol(\"IWithMeta\", [\"withMeta\"]);\n\nexport const METADATA_READ = protocolSlot(I_META, \"meta\");\nexport const METADATA_WITH = protocolSlot(I_WITH_META, \"withMeta\");\n\nexport const dispatchMetadataRead = protocolMethod(I_META, \"meta\");\nexport const dispatchMetadataWith = protocolMethod(I_WITH_META, \"withMeta\");\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.metadata
|
|
2
|
+
(js* "import { isPersistentHashMap } from \"./map.mjs\";\nimport {\n I_META,\n I_WITH_META,\n METADATA_READ,\n METADATA_WITH,\n dispatchMetadataRead,\n dispatchMetadataWith,\n} from \"./metadata-internals.mjs\";\nimport { implementsProtocolOperation } from \"./protocol.mjs\";\n\nexport const IMeta = I_META;\nexport const IWithMeta = I_WITH_META;\n\nfunction validateMetadata(metadata) {\n if (metadata !== null && !isPersistentHashMap(metadata)) {\n throw new TypeError(\"metadata must be null or a persistent hash map\");\n }\n return metadata;\n}\n\nexport function supportsMetadata(value) {\n return implementsProtocolOperation(IMeta, \"meta\", value) &&\n implementsProtocolOperation(IWithMeta, \"withMeta\", value);\n}\n\nexport function meta(value) {\n if (value !== null && value !== undefined) {\n const direct = value[METADATA_READ];\n if (typeof direct === \"function\") {\n return direct.call(value);\n }\n }\n return implementsProtocolOperation(IMeta, \"meta\", value)\n ? dispatchMetadataRead(value)\n : null;\n}\n\nexport function withMeta(value, metadata) {\n validateMetadata(metadata);\n if (value !== null && value !== undefined) {\n const direct = value[METADATA_WITH];\n if (typeof direct === \"function\") {\n return direct.call(value, metadata);\n }\n }\n if (!implementsProtocolOperation(IWithMeta, \"withMeta\", value)) {\n throw new TypeError(\"value does not support metadata\");\n }\n return dispatchMetadataWith(value, metadata);\n}\n\nexport function varyMeta(value, transform, ...arguments_) {\n if (typeof transform !== \"function\") {\n throw new TypeError(\"metadata transform must be a function\");\n }\n return withMeta(value, transform(meta(value), ...arguments_));\n}\n"))
|
|
@@ -2,6 +2,8 @@ import { isPersistentHashMap } from "./map.mjs";
|
|
|
2
2
|
import {
|
|
3
3
|
I_META,
|
|
4
4
|
I_WITH_META,
|
|
5
|
+
METADATA_READ,
|
|
6
|
+
METADATA_WITH,
|
|
5
7
|
dispatchMetadataRead,
|
|
6
8
|
dispatchMetadataWith,
|
|
7
9
|
} from "./metadata-internals.mjs";
|
|
@@ -23,6 +25,12 @@ export function supportsMetadata(value) {
|
|
|
23
25
|
}
|
|
24
26
|
|
|
25
27
|
export function meta(value) {
|
|
28
|
+
if (value !== null && value !== undefined) {
|
|
29
|
+
const direct = value[METADATA_READ];
|
|
30
|
+
if (typeof direct === "function") {
|
|
31
|
+
return direct.call(value);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
26
34
|
return implementsProtocolOperation(IMeta, "meta", value)
|
|
27
35
|
? dispatchMetadataRead(value)
|
|
28
36
|
: null;
|
|
@@ -30,6 +38,12 @@ export function meta(value) {
|
|
|
30
38
|
|
|
31
39
|
export function withMeta(value, metadata) {
|
|
32
40
|
validateMetadata(metadata);
|
|
41
|
+
if (value !== null && value !== undefined) {
|
|
42
|
+
const direct = value[METADATA_WITH];
|
|
43
|
+
if (typeof direct === "function") {
|
|
44
|
+
return direct.call(value, metadata);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
33
47
|
if (!implementsProtocolOperation(IWithMeta, "withMeta", value)) {
|
|
34
48
|
throw new TypeError("value does not support metadata");
|
|
35
49
|
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.order
|
|
2
|
+
(js* "import { reduce } from \"./collection.mjs\";\nimport {\n EliscriptSymbol,\n Keyword,\n qualifiedIdentifierName,\n} from \"./identifier.mjs\";\nimport { PersistentList } from \"./list.mjs\";\nimport {\n defineProtocol,\n extendProtocolCategory,\n extendProtocolType,\n protocolMethod,\n} from \"./protocol.mjs\";\nimport {\n conjBang,\n persistentBang,\n transient,\n} from \"./transient.mjs\";\nimport { isTruthy } from \"./truth.mjs\";\nimport { EMPTY_VECTOR, PersistentVector } from \"./vector.mjs\";\n\nexport const IComparable = defineProtocol(\"IComparable\", [\"compare\"]);\nconst dispatchCompare = protocolMethod(IComparable, \"compare\");\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 comparisonResult(value, label) {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw new TypeError(`${label} must return a finite number`);\n }\n return value < 0 ? -1 : value > 0 ? 1 : 0;\n}\n\nfunction typeName(value) {\n if (value === null) return \"null\";\n if (value === undefined) return \"undefined\";\n if (value instanceof Keyword) return \"keyword\";\n if (value instanceof EliscriptSymbol) return \"symbol\";\n if (value instanceof PersistentVector) return \"vector\";\n if (value instanceof PersistentList) return \"list\";\n return typeof value;\n}\n\nfunction requireComparableType(right, predicate, leftName) {\n if (!predicate(right)) {\n throw new TypeError(`cannot compare ${leftName} to ${typeName(right)}`);\n }\n return right;\n}\n\nfunction comparePrimitive(left, right, predicate, name) {\n requireComparableType(right, predicate, name);\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\nfunction compareNumber(left, right) {\n requireComparableType(right, (value) => typeof value === \"number\", \"number\");\n if (Number.isNaN(left)) return Number.isNaN(right) ? 0 : 1;\n if (Number.isNaN(right)) return -1;\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\nfunction compareIdentifier(left, right, Constructor, name) {\n requireComparableType(right, (value) => value instanceof Constructor, name);\n return comparePrimitive(\n qualifiedIdentifierName(left),\n qualifiedIdentifierName(right),\n (value) => typeof value === \"string\",\n \"string\",\n );\n}\n\nfunction compareSequential(left, right, Constructor, name) {\n requireComparableType(right, (value) => value instanceof Constructor, name);\n if (left === right) return 0;\n const leftIterator = left[Symbol.iterator]();\n const rightIterator = right[Symbol.iterator]();\n while (true) {\n const leftItem = leftIterator.next();\n const rightItem = rightIterator.next();\n if (leftItem.done || rightItem.done) {\n return leftItem.done === rightItem.done ? 0 : leftItem.done ? -1 : 1;\n }\n const result = compareValues(leftItem.value, rightItem.value);\n if (result !== 0) return result;\n }\n}\n\nextendProtocolCategory(IComparable, \"boolean\", {\n compare: (left, right) => comparePrimitive(\n left,\n right,\n (value) => typeof value === \"boolean\",\n \"boolean\",\n ),\n});\nextendProtocolCategory(IComparable, \"number\", { compare: compareNumber });\nextendProtocolCategory(IComparable, \"bigint\", {\n compare: (left, right) => comparePrimitive(\n left,\n right,\n (value) => typeof value === \"bigint\",\n \"bigint\",\n ),\n});\nextendProtocolCategory(IComparable, \"string\", {\n compare: (left, right) => comparePrimitive(\n left,\n right,\n (value) => typeof value === \"string\",\n \"string\",\n ),\n});\nextendProtocolType(IComparable, Keyword, {\n compare: (left, right) => compareIdentifier(left, right, Keyword, \"keyword\"),\n});\nextendProtocolType(IComparable, EliscriptSymbol, {\n compare: (left, right) =>\n compareIdentifier(left, right, EliscriptSymbol, \"symbol\"),\n});\nextendProtocolType(IComparable, PersistentVector, {\n compare: (left, right) =>\n compareSequential(left, right, PersistentVector, \"vector\"),\n});\nextendProtocolType(IComparable, PersistentList, {\n compare: (left, right) =>\n compareSequential(left, right, PersistentList, \"list\"),\n});\n\nexport function compareValues(left, right) {\n if (left === right || (Number.isNaN(left) && Number.isNaN(right))) return 0;\n if (typeof left === \"number\" && typeof right === \"number\") {\n if (Number.isNaN(left)) return 1;\n if (Number.isNaN(right)) return -1;\n return left < right ? -1 : 1;\n }\n if (typeof left === \"string\" && typeof right === \"string\") {\n return left < right ? -1 : 1;\n }\n if (left === null) return -1;\n if (right === null) return 1;\n if (left === undefined) return -1;\n if (right === undefined) return 1;\n return comparisonResult(\n dispatchCompare(left, right),\n \"IComparable/compare\",\n );\n}\n\nexport function comparator(comparison) {\n requireFunction(comparison, \"comparator comparison\");\n if (comparison === compareValues) return compareValues;\n return (left, right) => {\n const result = comparison(left, right);\n if (typeof result === \"number\") {\n return comparisonResult(result, \"comparator comparison\");\n }\n if (isTruthy(result)) return -1;\n return isTruthy(comparison(right, left)) ? 1 : 0;\n };\n}\n\nexport function reverseComparator(...arguments_) {\n if (arguments_.length > 1) {\n throw new TypeError(\"reverseComparator expects zero or one comparator\");\n }\n const normalized = comparator(\n arguments_.length === 0 ? compareValues : arguments_[0],\n );\n return (left, right) => normalized(right, left);\n}\n\nfunction sortDecorated(values, comparison) {\n if (values.length === 0) return EMPTY_VECTOR;\n values.sort((left, right) =>\n comparison(left.key, right.key) || left.index - right.index);\n const result = new Array(values.length);\n for (let index = 0; index < values.length; index += 1) {\n result[index] = values[index].value;\n }\n return PersistentVector.from(result);\n}\n\nfunction collectDecorated(collection, keyFunction) {\n const values = [];\n reduce(collection, (result, value) => {\n result.push({ index: result.length, key: keyFunction(value), value });\n return result;\n }, values);\n return values;\n}\n\nfunction collectValues(collection) {\n const values = [];\n reduce(collection, (result, value) => {\n result.push(value);\n return result;\n }, values);\n return values;\n}\n\nexport function sort(...arguments_) {\n if (arguments_.length !== 1 && arguments_.length !== 2) {\n throw new TypeError(\"sort expects a collection or comparator and collection\");\n }\n const comparison = arguments_.length === 1\n ? compareValues\n : arguments_[0];\n const collection = arguments_[arguments_.length - 1];\n const values = collectValues(collection);\n const normalized = comparator(comparison);\n if (values.length === 0) return EMPTY_VECTOR;\n values.sort(normalized);\n return PersistentVector.from(values);\n}\n\nexport function sortBy(keyFunction, ...arguments_) {\n requireFunction(keyFunction, \"sortBy key function\");\n if (arguments_.length !== 1 && arguments_.length !== 2) {\n throw new TypeError(\n \"sortBy expects a key function, optional comparator, and collection\",\n );\n }\n const comparison = arguments_.length === 1\n ? compareValues\n : arguments_[0];\n const collection = arguments_[arguments_.length - 1];\n return sortDecorated(\n collectDecorated(collection, keyFunction),\n comparator(comparison),\n );\n}\n\nfunction extremeKey(label, direction, keyFunction, values) {\n requireFunction(keyFunction, `${label} key function`);\n if (values.length === 0) {\n throw new TypeError(`${label} expects a key function and at least one value`);\n }\n let selected = values[0];\n let selectedKey = keyFunction(selected);\n for (let index = 1; index < values.length; index += 1) {\n const candidate = values[index];\n const candidateKey = keyFunction(candidate);\n if (compareValues(candidateKey, selectedKey) * direction >= 0) {\n selected = candidate;\n selectedKey = candidateKey;\n }\n }\n return selected;\n}\n\nexport function minKey(keyFunction, ...values) {\n return extremeKey(\"minKey\", -1, keyFunction, values);\n}\n\nexport function maxKey(keyFunction, ...values) {\n return extremeKey(\"maxKey\", 1, keyFunction, values);\n}\n"))
|
package/runtime/core/order.mjs
CHANGED
|
@@ -11,7 +11,11 @@ import {
|
|
|
11
11
|
extendProtocolType,
|
|
12
12
|
protocolMethod,
|
|
13
13
|
} from "./protocol.mjs";
|
|
14
|
-
import {
|
|
14
|
+
import {
|
|
15
|
+
conjBang,
|
|
16
|
+
persistentBang,
|
|
17
|
+
transient,
|
|
18
|
+
} from "./transient.mjs";
|
|
15
19
|
import { isTruthy } from "./truth.mjs";
|
|
16
20
|
import { EMPTY_VECTOR, PersistentVector } from "./vector.mjs";
|
|
17
21
|
|
|
@@ -73,6 +77,7 @@ function compareIdentifier(left, right, Constructor, name) {
|
|
|
73
77
|
|
|
74
78
|
function compareSequential(left, right, Constructor, name) {
|
|
75
79
|
requireComparableType(right, (value) => value instanceof Constructor, name);
|
|
80
|
+
if (left === right) return 0;
|
|
76
81
|
const leftIterator = left[Symbol.iterator]();
|
|
77
82
|
const rightIterator = right[Symbol.iterator]();
|
|
78
83
|
while (true) {
|
|
@@ -129,6 +134,14 @@ extendProtocolType(IComparable, PersistentList, {
|
|
|
129
134
|
|
|
130
135
|
export function compareValues(left, right) {
|
|
131
136
|
if (left === right || (Number.isNaN(left) && Number.isNaN(right))) return 0;
|
|
137
|
+
if (typeof left === "number" && typeof right === "number") {
|
|
138
|
+
if (Number.isNaN(left)) return 1;
|
|
139
|
+
if (Number.isNaN(right)) return -1;
|
|
140
|
+
return left < right ? -1 : 1;
|
|
141
|
+
}
|
|
142
|
+
if (typeof left === "string" && typeof right === "string") {
|
|
143
|
+
return left < right ? -1 : 1;
|
|
144
|
+
}
|
|
132
145
|
if (left === null) return -1;
|
|
133
146
|
if (right === null) return 1;
|
|
134
147
|
if (left === undefined) return -1;
|
|
@@ -141,6 +154,7 @@ export function compareValues(left, right) {
|
|
|
141
154
|
|
|
142
155
|
export function comparator(comparison) {
|
|
143
156
|
requireFunction(comparison, "comparator comparison");
|
|
157
|
+
if (comparison === compareValues) return compareValues;
|
|
144
158
|
return (left, right) => {
|
|
145
159
|
const result = comparison(left, right);
|
|
146
160
|
if (typeof result === "number") {
|
|
@@ -162,9 +176,14 @@ export function reverseComparator(...arguments_) {
|
|
|
162
176
|
}
|
|
163
177
|
|
|
164
178
|
function sortDecorated(values, comparison) {
|
|
179
|
+
if (values.length === 0) return EMPTY_VECTOR;
|
|
165
180
|
values.sort((left, right) =>
|
|
166
181
|
comparison(left.key, right.key) || left.index - right.index);
|
|
167
|
-
|
|
182
|
+
const result = new Array(values.length);
|
|
183
|
+
for (let index = 0; index < values.length; index += 1) {
|
|
184
|
+
result[index] = values[index].value;
|
|
185
|
+
}
|
|
186
|
+
return PersistentVector.from(result);
|
|
168
187
|
}
|
|
169
188
|
|
|
170
189
|
function collectDecorated(collection, keyFunction) {
|
|
@@ -176,6 +195,15 @@ function collectDecorated(collection, keyFunction) {
|
|
|
176
195
|
return values;
|
|
177
196
|
}
|
|
178
197
|
|
|
198
|
+
function collectValues(collection) {
|
|
199
|
+
const values = [];
|
|
200
|
+
reduce(collection, (result, value) => {
|
|
201
|
+
result.push(value);
|
|
202
|
+
return result;
|
|
203
|
+
}, values);
|
|
204
|
+
return values;
|
|
205
|
+
}
|
|
206
|
+
|
|
179
207
|
export function sort(...arguments_) {
|
|
180
208
|
if (arguments_.length !== 1 && arguments_.length !== 2) {
|
|
181
209
|
throw new TypeError("sort expects a collection or comparator and collection");
|
|
@@ -184,10 +212,11 @@ export function sort(...arguments_) {
|
|
|
184
212
|
? compareValues
|
|
185
213
|
: arguments_[0];
|
|
186
214
|
const collection = arguments_[arguments_.length - 1];
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
);
|
|
215
|
+
const values = collectValues(collection);
|
|
216
|
+
const normalized = comparator(comparison);
|
|
217
|
+
if (values.length === 0) return EMPTY_VECTOR;
|
|
218
|
+
values.sort(normalized);
|
|
219
|
+
return PersistentVector.from(values);
|
|
191
220
|
}
|
|
192
221
|
|
|
193
222
|
export function sortBy(keyFunction, ...arguments_) {
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.persistent-kind
|
|
2
|
+
(js* "export const PERSISTENT_MAP_KIND = Symbol(\"eliscript.persistent-map.kind\");\nexport const PERSISTENT_MAP_HAS_VALUE_KEY = Symbol(\n \"eliscript.persistent-map.has-value-key\",\n);\nexport const PERSISTENT_SET_KIND = Symbol(\"eliscript.persistent-set.kind\");\nexport const PERSISTENT_SET_HAS_VALUE = Symbol(\n \"eliscript.persistent-set.has-value\",\n);\n\nexport function isPersistentMapValue(value) {\n return value?.[PERSISTENT_MAP_KIND] === true &&\n typeof value?.[PERSISTENT_MAP_HAS_VALUE_KEY] === \"function\";\n}\n\nexport function isPersistentSetValue(value) {\n return value?.[PERSISTENT_SET_KIND] === true &&\n typeof value?.[PERSISTENT_SET_HAS_VALUE] === \"function\";\n}\n\nexport function persistentMapValueEqual(left, right, equal) {\n if (left === right) {\n return true;\n }\n if (!isPersistentMapValue(right) || right.count !== left.count) {\n return false;\n }\n for (const [key, value] of left) {\n if (!right[PERSISTENT_MAP_HAS_VALUE_KEY](key) ||\n !equal(value, right.get(key))) {\n return false;\n }\n }\n return true;\n}\n\nexport function persistentSetValueEqual(left, right, equal) {\n if (left === right) {\n return true;\n }\n if (!isPersistentSetValue(right) || right.count !== left.count) {\n return false;\n }\n for (const value of left) {\n if (!right[PERSISTENT_SET_HAS_VALUE](value, equal)) {\n return false;\n }\n }\n return true;\n}\n"))
|
|
@@ -18,6 +18,9 @@ export function isPersistentSetValue(value) {
|
|
|
18
18
|
}
|
|
19
19
|
|
|
20
20
|
export function persistentMapValueEqual(left, right, equal) {
|
|
21
|
+
if (left === right) {
|
|
22
|
+
return true;
|
|
23
|
+
}
|
|
21
24
|
if (!isPersistentMapValue(right) || right.count !== left.count) {
|
|
22
25
|
return false;
|
|
23
26
|
}
|
|
@@ -31,6 +34,9 @@ export function persistentMapValueEqual(left, right, equal) {
|
|
|
31
34
|
}
|
|
32
35
|
|
|
33
36
|
export function persistentSetValueEqual(left, right, equal) {
|
|
37
|
+
if (left === right) {
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
34
40
|
if (!isPersistentSetValue(right) || right.count !== left.count) {
|
|
35
41
|
return false;
|
|
36
42
|
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.protocol-error
|
|
2
|
+
(js* "function protocolHostCategory(value) {\n return value === null ? \"null\" : typeof value;\n}\n\nfunction observedType(value) {\n const category = protocolHostCategory(value);\n if (category !== \"object\" && category !== \"function\") {\n return category;\n }\n try {\n const prototype = Object.getPrototypeOf(value);\n const constructor = prototype?.constructor;\n const name = typeof constructor === \"function\" && constructor.name.length > 0\n ? constructor.name\n : \"anonymous\";\n return `${category}:${name}`;\n } catch {\n return category;\n }\n}\n\nexport class ProtocolDispatchError extends TypeError {\n constructor(protocol, operation, receiver, reason = \"missing\") {\n const type = observedType(receiver);\n const detail = reason === \"missing\"\n ? \"has no implementation\"\n : \"has a non-callable direct slot\";\n super(`protocol ${protocol.name}/${operation} ${detail} for ${type}`);\n this.name = \"ProtocolDispatchError\";\n this.code = \"ELI-RUNTIME-PROTOCOL\";\n this.protocol = protocol.name;\n this.operation = operation;\n this.observedType = type;\n this.reason = reason;\n }\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.protocol
|
|
2
|
+
(js* "export { ProtocolDispatchError } from \"./protocol-error.mjs\";\nexport {\n define_protocol as defineProtocol,\n define_protocol_from_definition as defineProtocolFromDefinition,\n extend_protocol_category as extendProtocolCategory,\n extend_protocol_default as extendProtocolDefault,\n extend_protocol_type as extendProtocolType,\n implements_protocol_operation_QMARK_ as implementsProtocolOperation,\n implements_protocol_QMARK_ as implementsProtocol,\n protocol_definition as protocolDefinition,\n protocol_host_category as protocolHostCategory,\n protocol_method as protocolMethod,\n protocol_QMARK_ as isProtocol,\n materialize_protocol_from_definition as materializeProtocolFromDefinition,\n read_protocol_operations_owner as readProtocolOperationsOwner,\n read_protocol_method_owner as readProtocolMethodOwner,\n protocol_slot as protocolSlot,\n} from \"./protocol-impl.mjs\";\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.queue-internals
|
|
2
|
+
(js* "export const QUEUE_CONSTRUCTOR_TOKEN = Symbol(\"eliscript.queue.constructor\");\nexport const QUEUE_STATE = Symbol(\"eliscript.queue.state\");\n\nconst metrics = {\n queueAllocations: 0,\n frontPromotions: 0,\n promotedValues: 0,\n};\n\nexport function recordQueueAllocation() {\n metrics.queueAllocations += 1;\n}\n\nexport function recordQueueFrontPromotion(count) {\n metrics.frontPromotions += 1;\n metrics.promotedValues += count;\n}\n\nexport function resetQueueMetrics() {\n metrics.queueAllocations = 0;\n metrics.frontPromotions = 0;\n metrics.promotedValues = 0;\n}\n\nexport function readQueueMetrics() {\n return Object.freeze({ ...metrics });\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.queue
|
|
2
|
+
(js* "import {\n COLLECTION_CONJ,\n COLLECTION_COUNT,\n COLLECTION_EMPTY,\n COLLECTION_PEEK,\n COLLECTION_POP,\n COLLECTION_REDUCE,\n COLLECTION_SEQ,\n reduceIterable,\n sequenceView,\n} from \"./collection-internals.mjs\";\nimport {\n METADATA_READ,\n METADATA_WITH,\n} from \"./metadata-internals.mjs\";\nimport {\n QUEUE_CONSTRUCTOR_TOKEN,\n QUEUE_STATE,\n recordQueueAllocation,\n recordQueueFrontPromotion,\n} from \"./queue-internals.mjs\";\nimport {\n VALUE_EQUAL,\n VALUE_HASH,\n orderedCollectionHash,\n} from \"./value-internals.mjs\";\nimport {\n EMPTY_VECTOR,\n PersistentVector,\n persistentVector,\n subvec,\n} from \"./vector.mjs\";\n\nconst MAX_COUNT = 0x7fff_ffff;\nconst QUEUE_HASH_TAG = 0x6b3d_1f27;\n\nfunction makeQueue(count, front, rear, metadata = null) {\n recordQueueAllocation();\n return new PersistentQueue(\n QUEUE_CONSTRUCTOR_TOKEN,\n count,\n front,\n rear,\n metadata,\n );\n}\n\nfunction emptyQueueWithMetadata(metadata) {\n return metadata === null\n ? EMPTY_QUEUE\n : makeQueue(0, EMPTY_VECTOR, EMPTY_VECTOR, metadata);\n}\n\nexport class PersistentQueue {\n constructor(token, count, front, rear, metadata = null) {\n if (token !== QUEUE_CONSTRUCTOR_TOKEN) {\n throw new TypeError(\n \"PersistentQueue values must be created with persistentQueue or PersistentQueue.from\",\n );\n }\n if (!Number.isSafeInteger(count) || count < 0 || count > MAX_COUNT ||\n !(front instanceof PersistentVector) ||\n !(rear instanceof PersistentVector) ||\n front.count + rear.count !== count ||\n (count === 0 ? front.count !== 0 || rear.count !== 0 : front.count === 0)) {\n throw new TypeError(\"invalid persistent queue state\");\n }\n this[QUEUE_STATE] = Object.freeze({\n count,\n front,\n rear,\n metadata,\n });\n Object.freeze(this);\n }\n\n static empty() {\n return EMPTY_QUEUE;\n }\n\n static from(iterable) {\n if (iterable instanceof PersistentQueue) return iterable;\n let result = EMPTY_QUEUE;\n for (const value of iterable) result = result.conj(value);\n return result;\n }\n\n get count() {\n return this[QUEUE_STATE].count;\n }\n\n get size() {\n return this[QUEUE_STATE].count;\n }\n\n get isEmpty() {\n return this[QUEUE_STATE].count === 0;\n }\n\n conj(value) {\n const state = this[QUEUE_STATE];\n if (state.count === MAX_COUNT) {\n throw new RangeError(`persistent queue cannot exceed ${MAX_COUNT} values`);\n }\n return state.count === 0\n ? makeQueue(1, persistentVector(value), EMPTY_VECTOR, state.metadata)\n : makeQueue(\n state.count + 1,\n state.front,\n state.rear.conj(value),\n state.metadata,\n );\n }\n\n peek(notFound = null) {\n const state = this[QUEUE_STATE];\n return state.count === 0 ? notFound : state.front.nth(0);\n }\n\n pop() {\n const state = this[QUEUE_STATE];\n if (state.count === 0) {\n throw new RangeError(\"cannot pop an empty persistent queue\");\n }\n if (state.front.count > 1) {\n return makeQueue(\n state.count - 1,\n subvec(state.front, 1),\n state.rear,\n state.metadata,\n );\n }\n if (state.rear.count === 0) {\n return emptyQueueWithMetadata(state.metadata);\n }\n recordQueueFrontPromotion(state.rear.count);\n return makeQueue(\n state.count - 1,\n state.rear,\n EMPTY_VECTOR,\n state.metadata,\n );\n }\n\n reduce(reducer, ...initial) {\n return reduceIterable(this, reducer, ...initial);\n }\n\n toArray() {\n return [...this];\n }\n\n [COLLECTION_COUNT]() {\n return this.count;\n }\n\n [COLLECTION_EMPTY]() {\n return emptyQueueWithMetadata(this[QUEUE_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_SEQ]() {\n return this.isEmpty\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 [VALUE_EQUAL](other, equal) {\n if (this === other) {\n return true;\n }\n if (!(other instanceof PersistentQueue) || 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)) return false;\n }\n return true;\n }\n\n [VALUE_HASH](hash) {\n return orderedCollectionHash(this, hash, QUEUE_HASH_TAG);\n }\n\n [METADATA_READ]() {\n return this[QUEUE_STATE].metadata;\n }\n\n [METADATA_WITH](metadata) {\n const state = this[QUEUE_STATE];\n return metadata === state.metadata\n ? this\n : makeQueue(\n state.count,\n state.front,\n state.rear,\n metadata,\n );\n }\n\n *[Symbol.iterator]() {\n const state = this[QUEUE_STATE];\n yield* state.front;\n yield* state.rear;\n }\n\n get [Symbol.toStringTag]() {\n return \"EliscriptPersistentQueue\";\n }\n}\n\nexport const EMPTY_QUEUE = new PersistentQueue(\n QUEUE_CONSTRUCTOR_TOKEN,\n 0,\n EMPTY_VECTOR,\n EMPTY_VECTOR,\n);\n\nexport function persistentQueue(...values) {\n return PersistentQueue.from(values);\n}\n\nexport function isPersistentQueue(value) {\n return value instanceof PersistentQueue;\n}\n"))
|
package/runtime/core/queue.mjs
CHANGED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.record
|
|
2
|
+
(js* "import {\n COLLECTION_ASSOC,\n COLLECTION_CONJ,\n COLLECTION_CONTAINS,\n COLLECTION_COUNT,\n COLLECTION_DISSOC,\n COLLECTION_EMPTY,\n COLLECTION_GET,\n COLLECTION_REDUCE,\n COLLECTION_REDUCE_KV,\n COLLECTION_SEQ,\n isReducedValue,\n readCollectionEntry,\n reduceIterable,\n sequenceView,\n unreducedValue,\n} from \"./collection-internals.mjs\";\nimport {\n identifierName,\n identifierNamespace,\n isKeyword,\n keyword,\n} from \"./identifier.mjs\";\nimport { EMPTY_MAP, PersistentHashMap } from \"./map.mjs\";\nimport { METADATA_READ, METADATA_WITH } from \"./metadata-internals.mjs\";\nimport {\n VALUE_EQUAL,\n VALUE_HASH,\n finishHash,\n hashString,\n mixHash,\n} from \"./value-internals.mjs\";\n\nconst MAX_FIELDS = 1024;\nconst RECORD_CONSTRUCTOR_TOKEN = Symbol(\"eliscript.record.constructor-token\");\nconst RECORD_STATE = Symbol(\"eliscript.record.state\");\nconst RECORD_HASH_TAG = 0x4d83_a92f;\nconst recordTypes = new WeakSet();\n\nfunction fail(message) {\n throw new TypeError(message);\n}\n\nfunction normalizeTypeName(name) {\n if (typeof name !== \"string\" || name.length === 0) {\n fail(\"record type name must be a non-empty string\");\n }\n return name;\n}\n\nfunction normalizeFieldNames(fields) {\n if (!Array.isArray(fields) || fields.length > MAX_FIELDS) {\n fail(`record fields must be a dense array of at most ${MAX_FIELDS} names`);\n }\n const descriptors = Object.getOwnPropertyDescriptors(fields);\n if (Reflect.ownKeys(descriptors).length !== fields.length + 1) {\n fail(\"record fields must be a dense array with no extra properties\");\n }\n const seen = new Set();\n const result = [];\n for (let index = 0; index < fields.length; index += 1) {\n const descriptor = descriptors[String(index)];\n const field = descriptor?.value;\n if (!descriptor?.enumerable || typeof field !== \"string\" ||\n field.length === 0 || field.includes(\"/\")) {\n fail(\"record field names must be non-empty unqualified strings\");\n }\n if (seen.has(field)) {\n fail(`record declares duplicate field ${field}`);\n }\n seen.add(field);\n result.push(field);\n }\n return Object.freeze(result);\n}\n\nfunction declaredFieldIndex(typeState, key) {\n if (!isKeyword(key) || identifierNamespace(key) !== null) return -1;\n return typeState.fieldIndexes.get(identifierName(key)) ?? -1;\n}\n\nfunction mapWithMetadata(map, metadata) {\n return metadata === null ? map : map[METADATA_WITH](metadata);\n}\n\nfunction defineFieldAccessors(RecordValue, typeState) {\n for (let index = 0; index < typeState.fieldNames.length; index += 1) {\n const fieldName = typeState.fieldNames[index];\n if (fieldName in RecordValue.prototype) {\n fail(`record field ${fieldName} conflicts with a record member`);\n }\n const fieldKey = typeState.fieldKeys[index];\n Object.defineProperty(RecordValue.prototype, fieldName, {\n configurable: false,\n enumerable: true,\n get() {\n return this[RECORD_STATE].map.get(fieldKey);\n },\n });\n }\n}\n\nfunction makeInitialMap(typeState, values) {\n let map = EMPTY_MAP;\n for (let index = 0; index < values.length; index += 1) {\n map = map.assoc(typeState.fieldKeys[index], values[index]);\n }\n return map;\n}\n\nfunction normalizeSourceMap(typeState, source) {\n let map;\n try {\n map = PersistentHashMap.from(source);\n } catch (error) {\n throw new TypeError(\n `map->${typeState.name} expects an iterable collection of entries`,\n { cause: error },\n );\n }\n for (const fieldKey of typeState.fieldKeys) {\n if (!map.has(fieldKey)) map = map.assoc(fieldKey, null);\n }\n return map;\n}\n\nfunction makeRecordType(name, fields, reuseFields) {\n const typeName = normalizeTypeName(name);\n const normalizedFields = normalizeFieldNames(fields);\n if (reuseFields && !Object.isFrozen(fields)) {\n fail(\"materialized record fields must be a frozen array\");\n }\n const fieldNames = reuseFields ? fields : normalizedFields;\n const fieldKeys = Object.freeze(fieldNames.map((field) => keyword(field)));\n const fieldIndexes = new Map(\n fieldNames.map((field, index) => [field, index]),\n );\n const typeState = Object.freeze({\n name: typeName,\n fieldNames,\n fieldKeys,\n fieldIndexes,\n signature: `${typeName}[${fieldNames.join(\",\")}]`,\n });\n\n class RecordValue {\n constructor(token, map, metadata = null) {\n if (token !== RECORD_CONSTRUCTOR_TOKEN ||\n !(map instanceof PersistentHashMap)) {\n fail(`${typeName} values must be created with its record constructors`);\n }\n this[RECORD_STATE] = Object.freeze({ map, metadata });\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 RecordValue(\n RECORD_CONSTRUCTOR_TOKEN,\n makeInitialMap(typeState, values),\n );\n }\n\n static fromMap(source) {\n return new RecordValue(\n RECORD_CONSTRUCTOR_TOKEN,\n normalizeSourceMap(typeState, source),\n );\n }\n\n static isInstance(value) {\n return value instanceof RecordValue;\n }\n\n get count() {\n return this[RECORD_STATE].map.count;\n }\n\n get size() {\n return this.count;\n }\n\n get(key, notFound = null) {\n return this[RECORD_STATE].map.get(key, notFound);\n }\n\n has(key) {\n return this[RECORD_STATE].map.has(key);\n }\n\n assoc(key, value) {\n const state = this[RECORD_STATE];\n const map = state.map.assoc(key, value);\n return map === state.map\n ? this\n : new RecordValue(RECORD_CONSTRUCTOR_TOKEN, map, state.metadata);\n }\n\n dissoc(key) {\n const state = this[RECORD_STATE];\n if (declaredFieldIndex(typeState, key) >= 0) {\n return mapWithMetadata(state.map.dissoc(key), state.metadata);\n }\n const map = state.map.dissoc(key);\n return map === state.map\n ? this\n : new RecordValue(RECORD_CONSTRUCTOR_TOKEN, map, state.metadata);\n }\n\n entries() {\n return this[RECORD_STATE].map.entries();\n }\n\n keys() {\n return this[RECORD_STATE].map.keys();\n }\n\n values() {\n return this[RECORD_STATE].map.values();\n }\n\n toPersistentMap() {\n return mapWithMetadata(\n this[RECORD_STATE].map,\n this[RECORD_STATE].metadata,\n );\n }\n\n [COLLECTION_COUNT]() {\n return this.count;\n }\n\n [COLLECTION_EMPTY]() {\n return mapWithMetadata(EMPTY_MAP, this[RECORD_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_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.entries()) {\n result = reducer(result, key, value);\n if (isReducedValue(result)) return unreducedValue(result);\n }\n return result;\n }\n\n [VALUE_EQUAL](other, equal) {\n return other instanceof RecordValue &&\n equal(this[RECORD_STATE].map, other[RECORD_STATE].map);\n }\n\n [VALUE_HASH](hash) {\n return finishHash(\n mixHash(\n mixHash(RECORD_HASH_TAG, hashString(typeState.signature)),\n hash(this[RECORD_STATE].map),\n ),\n this.count,\n );\n }\n\n [METADATA_READ]() {\n return this[RECORD_STATE].metadata;\n }\n\n [METADATA_WITH](metadata) {\n const state = this[RECORD_STATE];\n return metadata === state.metadata\n ? this\n : new RecordValue(RECORD_CONSTRUCTOR_TOKEN, state.map, metadata);\n }\n\n [Symbol.iterator]() {\n return this.entries();\n }\n\n get [Symbol.toStringTag]() {\n return `EliscriptRecord:${typeName}`;\n }\n }\n\n Object.defineProperty(RecordValue, \"name\", { value: typeName });\n Object.defineProperties(RecordValue, {\n recordName: { enumerable: true, value: typeName },\n recordFields: { enumerable: true, value: fieldNames },\n });\n defineFieldAccessors(RecordValue, typeState);\n Object.freeze(RecordValue.prototype);\n Object.freeze(RecordValue);\n recordTypes.add(RecordValue);\n return RecordValue;\n}\n\nexport function defineRecordType(name, fields) {\n return makeRecordType(name, fields, false);\n}\n\nexport function materializeRecordType(name, fields) {\n return makeRecordType(name, fields, true);\n}\n\nexport function isRecordType(value) {\n return typeof value === \"function\" && recordTypes.has(value);\n}\n\nexport function isRecord(value) {\n return value !== null && typeof value === \"object\" &&\n isRecordType(value.constructor);\n}\n\nexport function recordType(value) {\n if (!isRecord(value)) fail(\"expected an Eliscript record\");\n return value.constructor;\n}\n\nexport function recordTypeName(value) {\n const type = isRecordType(value) ? value : recordType(value);\n return type.recordName;\n}\n\nexport function recordFieldNames(value) {\n const type = isRecordType(value) ? value : recordType(value);\n return type.recordFields;\n}\n\n// The bulk transport reads the constructor's actual immutable payload without\n// guessing a private Symbol from its description or invoking a state getter.\nexport function readRecordState(value) {\n if (value === null || typeof value !== \"object\") return undefined;\n const descriptor = Object.getOwnPropertyDescriptor(value, RECORD_STATE);\n return descriptor !== undefined && \"value\" in descriptor\n ? descriptor.value : undefined;\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.regex
|
|
2
|
+
(js* "import { memoizedSequenceView } from \"./collection.mjs\";\nimport { persistentVector } from \"./vector.mjs\";\n\nconst patternStates = new WeakMap();\nconst ALLOWED_FLAGS = \"imsu\";\n\nfunction requireArity(actual, expected, name) {\n if (actual !== expected) {\n const unit = expected === 1 ? \"argument\" : \"arguments\";\n throw new TypeError(`${name} requires exactly ${expected} ${unit}`);\n }\n}\n\nfunction requireString(value, label) {\n if (typeof value !== \"string\") {\n throw new TypeError(`${label} must be a string`);\n }\n return value;\n}\n\nfunction normalizeFlags(value) {\n const flags = requireString(value, \"regex flags\");\n const seen = new Set();\n for (const flag of flags) {\n if (!ALLOWED_FLAGS.includes(flag)) {\n throw new TypeError(`regex flags contain unsupported flag: ${flag}`);\n }\n if (seen.has(flag)) {\n throw new TypeError(`regex flags contain duplicate flag: ${flag}`);\n }\n seen.add(flag);\n }\n return [...ALLOWED_FLAGS].filter((flag) => seen.has(flag)).join(\"\");\n}\n\nfunction stateOf(pattern) {\n const state = patternStates.get(pattern);\n if (state === undefined) {\n throw new TypeError(\"operation requires an Eliscript regex pattern\");\n }\n return state;\n}\n\nexport function readRegexState(value) {\n return patternStates.get(value);\n}\n\nfunction nativePattern(pattern, global = false) {\n const state = stateOf(pattern);\n return new RegExp(state.source, global ? `${state.flags}g` : state.flags);\n}\n\nfunction matchValue(match) {\n if (match.length === 1) return match[0];\n return persistentVector(...Array.from(\n match,\n (value) => value === undefined ? null : value,\n ));\n}\n\nfunction requireStart(value) {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new TypeError(\"regex start must be a non-negative safe integer\");\n }\n return value;\n}\n\nfunction advanceStringIndex(text, index, unicode) {\n if (!unicode || index + 1 >= text.length) return index + 1;\n const first = text.charCodeAt(index);\n if (first < 0xD800 || first > 0xDBFF) return index + 1;\n const second = text.charCodeAt(index + 1);\n return second >= 0xDC00 && second <= 0xDFFF ? index + 2 : index + 1;\n}\n\nfunction advanceEmptyMatch(matcher, text, match) {\n if (match[0] === \"\") {\n matcher.lastIndex = advanceStringIndex(\n text,\n matcher.lastIndex,\n matcher.unicode,\n );\n }\n}\n\nfunction scanIterator(pattern, text, start) {\n const matcher = nativePattern(pattern, true);\n matcher.lastIndex = start;\n return (function* matches() {\n while (true) {\n const match = matcher.exec(text);\n if (match === null) return;\n advanceEmptyMatch(matcher, text, match);\n yield matchValue(match);\n }\n })();\n}\n\nexport function compileRegex(...arguments_) {\n if (arguments_.length < 1 || arguments_.length > 2) {\n throw new TypeError(\"compileRegex expects a source and optional flags\");\n }\n const source = requireString(arguments_[0], \"regex source\");\n const flags = normalizeFlags(arguments_.length === 2 ? arguments_[1] : \"\");\n try {\n new RegExp(source, flags);\n } catch {\n throw new SyntaxError(\"regex source is invalid\");\n }\n const pattern = Object.freeze({});\n patternStates.set(pattern, Object.freeze({ source, flags }));\n return pattern;\n}\n\nexport function isRegexPattern(value) {\n requireArity(arguments.length, 1, \"isRegexPattern\");\n return patternStates.has(value);\n}\n\nexport function regexSource(pattern) {\n requireArity(arguments.length, 1, \"regexSource\");\n return stateOf(pattern).source;\n}\n\nexport function regexFlags(pattern) {\n requireArity(arguments.length, 1, \"regexFlags\");\n return stateOf(pattern).flags;\n}\n\nexport function regexMatches(pattern, text) {\n requireArity(arguments.length, 2, \"regexMatches\");\n const input = requireString(text, \"regex input\");\n const match = nativePattern(pattern).exec(input);\n return match !== null && match.index === 0 && match[0].length === input.length\n ? matchValue(match)\n : null;\n}\n\nexport function regexFind(...arguments_) {\n if (arguments_.length < 2 || arguments_.length > 3) {\n throw new TypeError(\"regexFind expects a pattern, input, and optional start\");\n }\n const input = requireString(arguments_[1], \"regex input\");\n const start = requireStart(arguments_.length === 3 ? arguments_[2] : 0);\n const matcher = nativePattern(arguments_[0], true);\n matcher.lastIndex = start;\n const match = matcher.exec(input);\n return match === null ? null : matchValue(match);\n}\n\nexport function regexSequence(...arguments_) {\n if (arguments_.length < 2 || arguments_.length > 3) {\n throw new TypeError(\"regexSequence expects a pattern, input, and optional start\");\n }\n const pattern = arguments_[0];\n stateOf(pattern);\n const input = requireString(arguments_[1], \"regex input\");\n const start = requireStart(arguments_.length === 3 ? arguments_[2] : 0);\n return memoizedSequenceView(() => scanIterator(pattern, input, start));\n}\n\nexport function regexReplace(pattern, replacement, text) {\n requireArity(arguments.length, 3, \"regexReplace\");\n stateOf(pattern);\n const input = requireString(text, \"regex input\");\n if (typeof replacement !== \"string\" && typeof replacement !== \"function\") {\n throw new TypeError(\"regex replacement must be a string or function\");\n }\n\n const matcher = nativePattern(pattern, true);\n let cursor = 0;\n let output = \"\";\n while (true) {\n const match = matcher.exec(input);\n if (match === null) break;\n output += input.slice(cursor, match.index);\n const value = typeof replacement === \"function\"\n ? replacement(matchValue(match), match.index, input)\n : replacement;\n if (typeof value !== \"string\") {\n throw new TypeError(\"regex replacement function must return a string\");\n }\n output += value;\n cursor = match.index + match[0].length;\n advanceEmptyMatch(matcher, input, match);\n }\n return output + input.slice(cursor);\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.sequence
|
|
2
|
+
(js* "import {\n count as collectionCount,\n IReversible,\n isReduced,\n nth as collectionNth,\n reduce,\n reduced,\n rseq,\n seq,\n sequenceView,\n unboundedSequenceView,\n unreduced,\n} from \"./collection.mjs\";\nimport {\n prependSequenceView,\n sliceSequenceView,\n} from \"./collection-internals.mjs\";\nimport { EMPTY_LIST, isPersistentList } from \"./list.mjs\";\nimport { implementsProtocolOperation } from \"./protocol.mjs\";\nimport {\n deduping,\n distincting,\n dropping,\n droppingWhile,\n filtering,\n into,\n interposing,\n keeping,\n keepingIndexed,\n mapcatting,\n mapping,\n mappingIndexed,\n partitioningAll,\n partitioningBy,\n removing,\n taking,\n takingNth,\n takingWhile,\n} from \"./transducer.mjs\";\nimport {\n conjBang,\n persistentBang,\n transient,\n} from \"./transient.mjs\";\nimport { isTruthy } from \"./truth.mjs\";\nimport {\n EMPTY_VECTOR,\n isPersistentVector,\n persistentVector,\n} from \"./vector.mjs\";\n\nconst NOT_FOUND = Symbol(\"eliscript.sequence.not-found\");\nconst NO_PARTITION_PAD = Symbol(\"eliscript.sequence.no-partition-pad\");\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 requireNonNegativeSafeInteger(value, label) {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new TypeError(`${label} must be a non-negative safe integer`);\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 materializeSources(collections) {\n const sources = [];\n for (const collection of collections) {\n sources.push(into(EMPTY_VECTOR, collection));\n }\n return sources;\n}\n\nfunction partitionWindows(\n size,\n step,\n collection,\n { includePartial = false, pad = NO_PARTITION_PAD } = {},\n) {\n requirePositiveSafeInteger(size, \"partition size\");\n requirePositiveSafeInteger(step, \"partition step\");\n const values = into(EMPTY_VECTOR, collection);\n const valueCount = collectionCount(values);\n const result = transient(EMPTY_VECTOR);\n\n for (let start = 0; start < valueCount; start += step) {\n const group = transient(EMPTY_VECTOR);\n let groupCount = Math.min(size, valueCount - start);\n for (let offset = 0; offset < groupCount; offset += 1) {\n conjBang(group, collectionNth(values, start + offset));\n }\n\n const partial = groupCount < size;\n if (partial && pad !== NO_PARTITION_PAD) {\n reduce(pad, (builder, value) => {\n conjBang(builder, value);\n groupCount += 1;\n return groupCount >= size ? reduced(builder) : builder;\n }, group);\n }\n const completed = persistentBang(group);\n if (!partial || includePartial || pad !== NO_PARTITION_PAD) {\n conjBang(result, completed);\n }\n if (partial && !includePartial) break;\n }\n return persistentBang(result);\n}\n\nfunction isSequentialBranch(value) {\n return Array.isArray(value) ||\n isPersistentList(value) ||\n isPersistentVector(value);\n}\n\nfunction requireFiniteNumber(value, label) {\n if (!Number.isFinite(value)) {\n throw new TypeError(`${label} must be a finite number`);\n }\n return value;\n}\n\nfunction rangeCount(start, end, step) {\n const distance = (end - start) / step;\n if (!(distance > 0)) return 0;\n return requireNonNegativeSafeInteger(Math.ceil(distance), \"range count\");\n}\n\nfunction rangeFactory(start, step, count = null) {\n return () => (function* rangeValues() {\n let index = 0;\n while (count === null || index < count) {\n yield start + index * step;\n index += 1;\n }\n })();\n}\n\nexport function range(...bounds) {\n if (bounds.length === 0) {\n return unboundedSequenceView(rangeFactory(0, 1));\n }\n if (bounds.length > 3) {\n throw new TypeError(\"range expects zero to three arguments\");\n }\n\n const start = requireFiniteNumber(\n bounds.length === 1 ? 0 : bounds[0],\n \"range start\",\n );\n const end = requireFiniteNumber(\n bounds.length === 1 ? bounds[0] : bounds[1],\n \"range end\",\n );\n const step = requireFiniteNumber(bounds.length === 3 ? bounds[2] : 1, \"range step\");\n if (step === 0) {\n throw new TypeError(\"range step must be non-zero\");\n }\n const count = rangeCount(start, end, step);\n return sequenceView(rangeFactory(start, step, count), count);\n}\n\nfunction repeatFactory(value, count = null) {\n return () => (function* repeatedValues() {\n let index = 0;\n while (count === null || index < count) {\n yield value;\n index += 1;\n }\n })();\n}\n\nexport function repeat(...arguments_) {\n if (arguments_.length === 1) {\n return unboundedSequenceView(repeatFactory(arguments_[0]));\n }\n if (arguments_.length === 2) {\n const count = requireNonNegativeSafeInteger(arguments_[0], \"repeat count\");\n return sequenceView(repeatFactory(arguments_[1], count), count);\n }\n throw new TypeError(\"repeat expects a value or a count and value\");\n}\n\nfunction repeatedlyFactory(producer, count = null) {\n return () => (function* producedValues() {\n let index = 0;\n while (count === null || index < count) {\n yield producer();\n index += 1;\n }\n })();\n}\n\nexport function repeatedly(...arguments_) {\n if (arguments_.length === 1) {\n const producer = requireFunction(arguments_[0], \"repeatedly producer\");\n return unboundedSequenceView(repeatedlyFactory(producer));\n }\n if (arguments_.length === 2) {\n const count = requireNonNegativeSafeInteger(arguments_[0], \"repeatedly count\");\n const producer = requireFunction(arguments_[1], \"repeatedly producer\");\n return sequenceView(repeatedlyFactory(producer, count), count);\n }\n throw new TypeError(\"repeatedly expects a producer or a count and producer\");\n}\n\nexport function iterate(transform, seed) {\n requireFunction(transform, \"iterate transform\");\n return unboundedSequenceView(() => (function* iterationValues() {\n let value = seed;\n while (true) {\n yield value;\n value = transform(value);\n }\n })());\n}\n\nexport function cycle(collection) {\n const values = into(EMPTY_VECTOR, collection);\n const count = collectionCount(values);\n if (count === 0) return null;\n return unboundedSequenceView(() => (function* cycledValues() {\n let index = 0;\n while (true) {\n yield collectionNth(values, index);\n index = (index + 1) % count;\n }\n })());\n}\n\nexport function generate(count, producer) {\n requireNonNegativeSafeInteger(count, \"generate count\");\n requireFunction(producer, \"generate producer\");\n return sequenceView(() => (function* generatedValues() {\n for (let index = 0; index < count; index += 1) {\n yield producer(index);\n }\n })(), count);\n}\n\nexport function first(collection, notFound = null) {\n if (isPersistentList(collection)) {\n return collection.isEmpty ? notFound : collection.first(notFound);\n }\n if (isPersistentVector(collection)) {\n return collection.count === 0 ? notFound : collection.nth(0);\n }\n let found = false;\n let foundValue = null;\n reduce(collection, (missing, value) => {\n found = true;\n foundValue = value;\n return reduced(missing);\n }, null);\n return found ? foundValue : notFound;\n}\n\nexport function nthRest(limit, collection) {\n requireNonNegativeSafeInteger(limit, \"nthRest limit\");\n if (limit === 0) return collection;\n return sliceSequenceView(seq(collection), limit) ?? EMPTY_LIST;\n}\n\nexport function nthNext(limit, collection) {\n requireNonNegativeSafeInteger(limit, \"nthNext limit\");\n const result = limit === 0\n ? seq(collection)\n : sliceSequenceView(seq(collection), limit);\n return result === null ? null : seq(result);\n}\n\nexport function rest(collection) {\n return nthRest(1, collection);\n}\n\nexport function next(collection) {\n return nthNext(1, collection);\n}\n\nexport function prepend(value, collection) {\n return prependSequenceView(value, seq(collection));\n}\n\nexport function second(collection, notFound = null) {\n return first(next(collection), notFound);\n}\n\nexport function ffirst(collection) {\n return first(first(collection));\n}\n\nexport function nfirst(collection) {\n return next(first(collection));\n}\n\nexport function fnext(collection) {\n return first(next(collection));\n}\n\nexport function nnext(collection) {\n return next(next(collection));\n}\n\nexport function sequenceNth(index, collection, notFound = null) {\n requireNonNegativeSafeInteger(index, \"sequenceNth index\");\n let position = 0;\n let found = false;\n let foundValue = null;\n reduce(collection, (missing, value) => {\n if (position === index) {\n found = true;\n foundValue = value;\n return reduced(missing);\n }\n position += 1;\n return missing;\n }, null);\n return found ? foundValue : notFound;\n}\n\nexport function last(collection, notFound = null) {\n if (isPersistentVector(collection)) {\n return collection.peek(notFound);\n }\n if (implementsProtocolOperation(IReversible, \"rseq\", collection)) {\n return first(rseq(collection), notFound);\n }\n let found = false;\n let lastValue = null;\n reduce(collection, (missing, value) => {\n found = true;\n lastValue = value;\n return missing;\n }, null);\n return found ? lastValue : notFound;\n}\n\nexport function takeLast(limit, collection) {\n requireNonNegativeSafeInteger(limit, \"takeLast limit\");\n if (limit === 0) return EMPTY_VECTOR;\n if (isPersistentVector(collection)) {\n const total = collection.count;\n if (total === 0) return EMPTY_VECTOR;\n if (limit >= total) return collection;\n if (typeof collection.sliceVector === \"function\") {\n return collection.sliceVector(total - limit, total);\n }\n const builder = transient(EMPTY_VECTOR);\n for (let index = total - limit; index < total; index += 1) {\n conjBang(builder, collection.nth(index));\n }\n return persistentBang(builder);\n }\n\n const ring = new Array(limit);\n let count = 0;\n let start = 0;\n reduce(collection, (state, value) => {\n if (count < limit) {\n ring[count] = value;\n count += 1;\n } else {\n ring[start] = value;\n start = (start + 1) % limit;\n }\n return state;\n }, null);\n\n const builder = transient(EMPTY_VECTOR);\n for (let index = 0; index < count; index += 1) {\n conjBang(builder, ring[(start + index) % limit]);\n }\n return persistentBang(builder);\n}\n\nexport function dropLast(limit, collection) {\n requireNonNegativeSafeInteger(limit, \"dropLast limit\");\n if (limit === 0) {\n return isPersistentVector(collection) ? collection : into(EMPTY_VECTOR, collection);\n }\n if (isPersistentVector(collection)) {\n const total = collection.count;\n if (limit >= total) return EMPTY_VECTOR;\n const keep = total - limit;\n if (typeof collection.sliceVector === \"function\") {\n return collection.sliceVector(0, keep);\n }\n const builder = transient(EMPTY_VECTOR);\n for (let index = 0; index < keep; index += 1) {\n conjBang(builder, collection.nth(index));\n }\n return persistentBang(builder);\n }\n\n const ring = new Array(limit);\n const builder = transient(EMPTY_VECTOR);\n let count = 0;\n let start = 0;\n reduce(collection, (state, value) => {\n if (count < limit) {\n ring[count] = value;\n count += 1;\n } else {\n conjBang(builder, ring[start]);\n ring[start] = value;\n start = (start + 1) % limit;\n }\n return state;\n }, null);\n return persistentBang(builder);\n}\n\nexport function butlast(collection) {\n return dropLast(1, collection);\n}\n\nexport function splitAt(limit, collection) {\n requireNonNegativeSafeInteger(limit, \"splitAt limit\");\n const left = transient(EMPTY_VECTOR);\n const right = transient(EMPTY_VECTOR);\n let index = 0;\n reduce(collection, (state, value) => {\n conjBang(index < limit ? left : right, value);\n index += 1;\n return state;\n }, null);\n return persistentVector(persistentBang(left), persistentBang(right));\n}\n\nexport function splitWith(predicate, collection) {\n requireFunction(predicate, \"splitWith predicate\");\n const left = transient(EMPTY_VECTOR);\n const right = transient(EMPTY_VECTOR);\n let prefix = true;\n reduce(collection, (state, value) => {\n if (prefix && isTruthy(predicate(value))) {\n conjBang(left, value);\n } else {\n prefix = false;\n conjBang(right, value);\n }\n return state;\n }, null);\n return persistentVector(persistentBang(left), persistentBang(right));\n}\n\nexport function reverse(collection) {\n if (implementsProtocolOperation(IReversible, \"rseq\", collection)) {\n return into(EMPTY_VECTOR, rseq(collection));\n }\n const values = reduce(collection, (result, value) => {\n result.push(value);\n return result;\n }, []);\n values.reverse();\n return into(EMPTY_VECTOR, values);\n}\n\nexport function map(transform, collection) {\n return into(EMPTY_VECTOR, mapping(transform), collection);\n}\n\nexport function mapIndexed(transform, collection) {\n return into(EMPTY_VECTOR, mappingIndexed(transform), collection);\n}\n\nexport function keep(transform, collection) {\n return into(EMPTY_VECTOR, keeping(transform), collection);\n}\n\nexport function keepIndexed(transform, collection) {\n return into(EMPTY_VECTOR, keepingIndexed(transform), collection);\n}\n\nexport function filter(predicate, collection) {\n return into(EMPTY_VECTOR, filtering(predicate), collection);\n}\n\nexport function remove(predicate, collection) {\n return into(EMPTY_VECTOR, removing(predicate), collection);\n}\n\nexport function take(limit, collection) {\n return into(EMPTY_VECTOR, taking(limit), collection);\n}\n\nexport function drop(limit, collection) {\n return into(EMPTY_VECTOR, dropping(limit), collection);\n}\n\nexport function takeWhile(predicate, collection) {\n return into(EMPTY_VECTOR, takingWhile(predicate), collection);\n}\n\nexport function dropWhile(predicate, collection) {\n return into(EMPTY_VECTOR, droppingWhile(predicate), collection);\n}\n\nexport function takeNth(interval, collection) {\n return into(EMPTY_VECTOR, takingNth(interval), collection);\n}\n\nexport function interpose(separator, collection) {\n return into(EMPTY_VECTOR, interposing(separator), collection);\n}\n\nexport function dedupe(collection) {\n return into(EMPTY_VECTOR, deduping(), collection);\n}\n\nexport function distinct(collection) {\n return into(EMPTY_VECTOR, distincting(), collection);\n}\n\nexport function mapcat(transform, collection) {\n return into(EMPTY_VECTOR, mapcatting(transform), collection);\n}\n\nexport function partition(size, ...arguments_) {\n if (arguments_.length === 1) {\n return partitionWindows(size, size, arguments_[0]);\n }\n if (arguments_.length === 2) {\n return partitionWindows(size, arguments_[0], arguments_[1]);\n }\n if (arguments_.length === 3) {\n return partitionWindows(size, arguments_[0], arguments_[2], {\n pad: arguments_[1],\n });\n }\n throw new TypeError(\n \"partition expects size and collection, optional step, or step and pad\",\n );\n}\n\nexport function partitionAll(size, ...arguments_) {\n if (arguments_.length === 1) {\n requirePositiveSafeInteger(size, \"partition size\");\n return into(EMPTY_VECTOR, partitioningAll(size), arguments_[0]);\n }\n if (arguments_.length === 2) {\n return partitionWindows(size, arguments_[0], arguments_[1], {\n includePartial: true,\n });\n }\n throw new TypeError(\n \"partitionAll expects size and collection or size, step, and collection\",\n );\n}\n\nexport function partitionBy(classifier, collection) {\n return into(EMPTY_VECTOR, partitioningBy(classifier), collection);\n}\n\nexport function concat(...collections) {\n const result = transient(EMPTY_VECTOR);\n for (const collection of collections) {\n reduce(collection, (builder, value) => conjBang(builder, value), result);\n }\n return persistentBang(result);\n}\n\nexport function interleave(...collections) {\n if (collections.length === 0) return EMPTY_VECTOR;\n const sources = materializeSources(collections);\n let limit = collectionCount(sources[0]);\n for (let index = 1; index < sources.length; index += 1) {\n limit = Math.min(limit, collectionCount(sources[index]));\n }\n const result = transient(EMPTY_VECTOR);\n for (let valueIndex = 0; valueIndex < limit; valueIndex += 1) {\n for (const source of sources) {\n conjBang(result, collectionNth(source, valueIndex));\n }\n }\n return persistentBang(result);\n}\n\nexport function interleaveAll(...collections) {\n if (collections.length === 0) return EMPTY_VECTOR;\n const sources = materializeSources(collections);\n let limit = 0;\n for (const source of sources) {\n limit = Math.max(limit, collectionCount(source));\n }\n const result = transient(EMPTY_VECTOR);\n for (let valueIndex = 0; valueIndex < limit; valueIndex += 1) {\n for (const source of sources) {\n if (valueIndex < collectionCount(source)) {\n conjBang(result, collectionNth(source, valueIndex));\n }\n }\n }\n return persistentBang(result);\n}\n\nexport function some(predicate, collection, notFound = null) {\n requireFunction(predicate, \"some predicate\");\n const result = reduce(collection, (missing, value) => {\n const matched = predicate(value);\n return isTruthy(matched) ? reduced(matched) : missing;\n }, NOT_FOUND);\n return result === NOT_FOUND ? notFound : result;\n}\n\nexport function every(predicate, collection) {\n requireFunction(predicate, \"every predicate\");\n return reduce(collection, (result, value) =>\n isTruthy(predicate(value)) ? result : reduced(false), true);\n}\n\nexport function notAny(predicate, collection) {\n return !isTruthy(some(predicate, collection));\n}\n\nexport function notEvery(predicate, collection) {\n return !every(predicate, collection);\n}\n\nexport function find(predicate, collection, notFound = null) {\n requireFunction(predicate, \"find predicate\");\n let found = false;\n let foundValue = null;\n reduce(collection, (missing, value) => {\n if (isTruthy(predicate(value))) {\n found = true;\n foundValue = value;\n return reduced(missing);\n }\n return missing;\n }, null);\n return found ? foundValue : notFound;\n}\n\nexport function reductions(step, initial, collection) {\n requireFunction(step, \"reductions step\");\n const builder = transient(EMPTY_VECTOR);\n const seed = unreduced(initial);\n conjBang(builder, seed);\n if (!isReduced(initial)) {\n reduce(collection, (current, input) => {\n const next = step(current, input);\n const value = unreduced(next);\n conjBang(builder, value);\n return isReduced(next) ? reduced(value) : value;\n }, seed);\n }\n return persistentBang(builder);\n}\n\nexport function treeSeq(branchPredicate, childrenFunction, root) {\n requireFunction(branchPredicate, \"treeSeq branch predicate\");\n requireFunction(childrenFunction, \"treeSeq children function\");\n const result = transient(EMPTY_VECTOR);\n const stack = [root];\n while (stack.length > 0) {\n const value = stack.pop();\n conjBang(result, value);\n if (isTruthy(branchPredicate(value))) {\n const children = into(EMPTY_VECTOR, childrenFunction(value));\n for (let index = collectionCount(children) - 1; index >= 0; index -= 1) {\n stack.push(collectionNth(children, index));\n }\n }\n }\n return persistentBang(result);\n}\n\nexport function flatten(root) {\n const result = transient(EMPTY_VECTOR);\n const stack = [root];\n while (stack.length > 0) {\n const value = stack.pop();\n if (isSequentialBranch(value)) {\n const children = into(EMPTY_VECTOR, value);\n for (let index = collectionCount(children) - 1; index >= 0; index -= 1) {\n stack.push(collectionNth(children, index));\n }\n } else {\n conjBang(result, value);\n }\n }\n return persistentBang(result);\n}\n"))
|
|
@@ -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"))
|