eliscript 0.0.2 → 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 +13 -11
- 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/host.mjs +643 -11
- package/browser/worker.eli +2 -0
- package/browser/worker.mjs +6 -3
- package/dist/browser/host.mjs +643 -11
- package/dist/browser/worker.mjs +6 -3
- package/dist/compiler-artifact.json +1 -1
- package/dist/literal-sources/runtime/core/collection.eli +76 -16
- package/dist/literal-sources/runtime/core/metadata.eli +25 -8
- package/dist/literal-sources/runtime/core/vector.eli +7 -2
- package/dist/literal-sources/stdlib/managed-literal-protocols.eli +18 -7
- package/dist/literal-sources/stdlib/managed-literals.eli +121 -66
- package/dist/stage3-release.json +1 -1
- package/package.json +11 -2
- 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 +274 -101
- package/stdlib/managed-literal-protocols.eli +18 -7
- package/stdlib/managed-literals.eli +121 -66
- package/stdlib/managed-runtime-collection.eli +76 -16
- package/stdlib/managed-runtime-metadata.eli +25 -8
- package/stdlib/managed-runtime-order.eli +32 -10
- package/stdlib/managed-runtime-sequence.eli +69 -28
- package/stdlib/managed-runtime-vector.eli +7 -2
- package/tools/acceptance/check.eli +13 -3
- package/tools/backends/compiler-build.mjs +140 -140
- package/tools/backends/dist/release-cli.mjs +2 -0
- package/tools/backends/dist/release-cli.mjs.map +1 -1
- package/tools/backends/stage3-targets.mjs +121 -114
- package/bootstrap/host/eliscript-cli-legacy.mjs +0 -37
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.identifier
|
|
2
|
+
(js* "import {\n VALUE_EQUAL,\n VALUE_HASH,\n finishHash,\n hashString,\n mixHash,\n} from \"./value-internals.mjs\";\nimport {\n METADATA_READ,\n METADATA_WITH,\n} from \"./metadata-internals.mjs\";\n\nconst VALUE_TYPE = Symbol.for(\"eliscript.value.type\");\nconst KEYWORD_TYPE = \"keyword\";\nconst SYMBOL_TYPE = \"symbol\";\n\nconst KEYWORD_HASH_TAG = 0x2f6d_31a7;\nconst SYMBOL_HASH_TAG = 0x71c8_4e93;\nconst UNQUALIFIED_HASH = 0x4a91_b67d;\n\nconst KEYWORD_TOKEN = Object.freeze({});\nconst SYMBOL_TOKEN = Object.freeze({});\nconst keywordState = new WeakMap();\nconst symbolState = new WeakMap();\nconst keywordInterns = new Map();\n\nfunction logicalType(value) {\n if ((typeof value !== \"object\" || value === null) &&\n typeof value !== \"function\") {\n return null;\n }\n try {\n const descriptor = Object.getOwnPropertyDescriptor(value, VALUE_TYPE);\n return descriptor !== undefined && \"value\" in descriptor\n ? descriptor.value\n : null;\n } catch {\n return null;\n }\n}\n\nfunction normalizePart(value, label) {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new TypeError(`${label} must be a non-empty string`);\n }\n if (value.includes(\"/\")) {\n throw new TypeError(`${label} cannot contain /`);\n }\n return value;\n}\n\nfunction splitQualified(value, label) {\n if (typeof value !== \"string\" || value.length === 0) {\n throw new TypeError(`${label} must be a non-empty string`);\n }\n const separator = value.indexOf(\"/\");\n if (separator === -1) {\n return { namespace: null, name: value };\n }\n if (separator === 0 || separator === value.length - 1 ||\n value.indexOf(\"/\", separator + 1) !== -1) {\n throw new TypeError(`${label} must be name or namespace/name`);\n }\n return {\n namespace: value.slice(0, separator),\n name: value.slice(separator + 1),\n };\n}\n\nfunction normalizeArguments(arguments_, type, predicate) {\n if (arguments_.length === 1) {\n const value = arguments_[0];\n if (predicate(value)) {\n return {\n existing: value,\n namespace: identifierNamespace(value),\n name: identifierName(value),\n };\n }\n return { existing: null, ...splitQualified(value, `${type} name`) };\n }\n if (arguments_.length === 2) {\n const [namespace, name] = arguments_;\n if (namespace !== null) {\n normalizePart(namespace, `${type} namespace`);\n }\n return {\n existing: null,\n namespace,\n name: normalizePart(name, `${type} name`),\n };\n }\n throw new TypeError(`${type} expects one qualified name or namespace and name`);\n}\n\nfunction qualifiedName(state) {\n return state.namespace === null\n ? state.name\n : `${state.namespace}/${state.name}`;\n}\n\nfunction identifierHash(tag, state) {\n const namespaceHash = state.namespace === null\n ? UNQUALIFIED_HASH\n : hashString(state.namespace);\n return finishHash(\n mixHash(mixHash(tag, namespaceHash), hashString(state.name)),\n 2,\n );\n}\n\nfunction defineIdentifier(instance, type, state, table) {\n table.set(instance, state);\n Object.defineProperty(instance, VALUE_TYPE, {\n value: type,\n enumerable: false,\n });\n Object.freeze(instance);\n}\n\nfunction equalIdentifier(leftType, leftState, right) {\n if (logicalType(right) !== leftType) {\n return false;\n }\n try {\n return identifierNamespace(right) === leftState.namespace &&\n identifierName(right) === leftState.name;\n } catch {\n return false;\n }\n}\n\nexport class Keyword {\n constructor(token, namespace, name) {\n if (token !== KEYWORD_TOKEN) {\n throw new TypeError(\"Keyword values must be created with keyword()\");\n }\n defineIdentifier(this, KEYWORD_TYPE, { namespace, name }, keywordState);\n }\n\n get name() {\n return keywordState.get(this).name;\n }\n\n get namespace() {\n return keywordState.get(this).namespace;\n }\n\n get qualifiedName() {\n return qualifiedName(keywordState.get(this));\n }\n\n toString() {\n return `:${this.qualifiedName}`;\n }\n\n toJSON() {\n throw new TypeError(\"Keyword values require an explicit serialization codec\");\n }\n\n [VALUE_EQUAL](other) {\n return equalIdentifier(KEYWORD_TYPE, keywordState.get(this), other);\n }\n\n [VALUE_HASH]() {\n return identifierHash(KEYWORD_HASH_TAG, keywordState.get(this));\n }\n\n get [Symbol.toStringTag]() {\n return \"EliscriptKeyword\";\n }\n}\n\nexport class EliscriptSymbol {\n constructor(token, namespace, name, metadata = null) {\n if (token !== SYMBOL_TOKEN) {\n throw new TypeError(\n \"EliscriptSymbol values must be created with eliscriptSymbol()\",\n );\n }\n defineIdentifier(\n this,\n SYMBOL_TYPE,\n { namespace, name, metadata },\n symbolState,\n );\n }\n\n get name() {\n return symbolState.get(this).name;\n }\n\n get namespace() {\n return symbolState.get(this).namespace;\n }\n\n get qualifiedName() {\n return qualifiedName(symbolState.get(this));\n }\n\n toString() {\n return this.qualifiedName;\n }\n\n toJSON() {\n throw new TypeError(\n \"EliscriptSymbol values require an explicit serialization codec\",\n );\n }\n\n [VALUE_EQUAL](other) {\n return equalIdentifier(SYMBOL_TYPE, symbolState.get(this), other);\n }\n\n [VALUE_HASH]() {\n return identifierHash(SYMBOL_HASH_TAG, symbolState.get(this));\n }\n\n [METADATA_READ]() {\n return symbolState.get(this).metadata;\n }\n\n [METADATA_WITH](metadata) {\n const state = symbolState.get(this);\n return metadata === state.metadata\n ? this\n : new EliscriptSymbol(\n SYMBOL_TOKEN,\n state.namespace,\n state.name,\n metadata,\n );\n }\n\n get [Symbol.toStringTag]() {\n return \"EliscriptSymbol\";\n }\n}\n\nexport function keyword(...arguments_) {\n const normalized = normalizeArguments(arguments_, KEYWORD_TYPE, isKeyword);\n if (normalized.existing !== null) {\n return normalized.existing;\n }\n const key = normalized.namespace === null\n ? normalized.name\n : `${normalized.namespace}/${normalized.name}`;\n const existing = keywordInterns.get(key);\n if (existing !== undefined) {\n return existing;\n }\n const result = new Keyword(\n KEYWORD_TOKEN,\n normalized.namespace,\n normalized.name,\n );\n keywordInterns.set(key, result);\n return result;\n}\n\nexport function eliscriptSymbol(...arguments_) {\n const normalized = normalizeArguments(\n arguments_,\n SYMBOL_TYPE,\n isEliscriptSymbol,\n );\n return normalized.existing ?? new EliscriptSymbol(\n SYMBOL_TOKEN,\n normalized.namespace,\n normalized.name,\n );\n}\n\nexport function isKeyword(value) {\n return logicalType(value) === KEYWORD_TYPE;\n}\n\nexport function isEliscriptSymbol(value) {\n return logicalType(value) === SYMBOL_TYPE;\n}\n\nexport function isIdentifier(value) {\n return isKeyword(value) || isEliscriptSymbol(value);\n}\n\nexport function identifierName(value) {\n if (!isIdentifier(value)) {\n throw new TypeError(\"expected an Eliscript keyword or symbol\");\n }\n const name = value.name;\n if (typeof name !== \"string\" || name.length === 0 || name.includes(\"/\")) {\n throw new TypeError(\"expected an Eliscript keyword or symbol\");\n }\n return name;\n}\n\nexport function identifierNamespace(value) {\n if (!isIdentifier(value)) {\n throw new TypeError(\"expected an Eliscript keyword or symbol\");\n }\n const namespace = value.namespace;\n if (namespace !== null &&\n (typeof namespace !== \"string\" || namespace.length === 0 ||\n namespace.includes(\"/\"))) {\n throw new TypeError(\"expected an Eliscript keyword or symbol\");\n }\n return namespace;\n}\n\nexport function qualifiedIdentifierName(value) {\n const namespace = identifierNamespace(value);\n const name = identifierName(value);\n return namespace === null ? name : `${namespace}/${name}`;\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.lazy-sequence
|
|
2
|
+
(js* "import {\n MemoizedSequenceView,\n memoizedSequenceView,\n seq,\n} from \"./collection.mjs\";\nimport { memoizedSequenceStatus } from \"./collection-internals.mjs\";\nimport {\n deduping,\n distincting,\n dropping,\n droppingWhile,\n filtering,\n interposing,\n keeping,\n keepingIndexed,\n mapcatting,\n mapping,\n mappingIndexed,\n partitioningAll,\n partitioningBy,\n removing,\n sequence as transducerSequence,\n taking,\n takingNth,\n takingWhile,\n} from \"./transducer.mjs\";\n\nconst lazyConsStates = new WeakMap();\nconst NO_LAZY_CONS_FAILURE = Symbol(\"eliscript.lazy-cons.no-failure\");\n\nfunction requireThunk(value, label) {\n if (typeof value !== \"function\") {\n throw new TypeError(`${label} must be a function`);\n }\n return value;\n}\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 sequenceIterator(value) {\n const sequence = seq(value);\n return sequence === null\n ? [][Symbol.iterator]()\n : sequence[Symbol.iterator]();\n}\n\nfunction realizeConsTail(state) {\n if (state.failure !== NO_LAZY_CONS_FAILURE) throw state.failure;\n if (!state.tailStarted) {\n state.tailStarted = true;\n try {\n state.tail = state.tailThunk();\n state.tailThunk = null;\n } catch (error) {\n state.failure = error;\n throw error;\n }\n }\n return state.tail;\n}\n\nfunction lazyConsIterator(initialState) {\n let state = initialState;\n let headPending = true;\n let tailIterator = null;\n let complete = false;\n return {\n next() {\n while (!complete) {\n if (state !== null && headPending) {\n headPending = false;\n return { value: state.value, done: false };\n }\n if (state !== null) {\n const tail = realizeConsTail(state);\n const tailState = lazyConsStates.get(tail);\n if (tailState !== undefined) {\n state = tailState;\n headPending = true;\n continue;\n }\n state = null;\n tailIterator = sequenceIterator(tail);\n }\n const result = tailIterator.next();\n if (!result.done) return result;\n complete = true;\n }\n return { value: undefined, done: true };\n },\n return(value) {\n complete = true;\n if (tailIterator !== null && typeof tailIterator.return === \"function\") {\n tailIterator.return();\n }\n return { value, done: true };\n },\n [Symbol.iterator]() {\n return this;\n },\n };\n}\n\nexport function lazySequence(thunk) {\n if (arguments.length !== 1) {\n throw new TypeError(\"lazySequence requires exactly one thunk\");\n }\n requireThunk(thunk, \"lazySequence thunk\");\n return memoizedSequenceView(() => sequenceIterator(thunk()));\n}\n\nexport function lazyCons(value, tailThunk) {\n if (arguments.length !== 2) {\n throw new TypeError(\"lazyCons requires a value and tail thunk\");\n }\n requireThunk(tailThunk, \"lazyCons tail thunk\");\n const state = {\n value,\n tailThunk,\n tailStarted: false,\n tail: null,\n failure: NO_LAZY_CONS_FAILURE,\n };\n const result = memoizedSequenceView(() => lazyConsIterator(state));\n lazyConsStates.set(result, state);\n return result;\n}\n\nexport function lazyMap(transform, collection) {\n requireArity(arguments.length, 2, \"lazyMap\");\n return transducerSequence(mapping(transform), collection);\n}\n\nexport function lazyMapIndexed(transform, collection) {\n requireArity(arguments.length, 2, \"lazyMapIndexed\");\n return transducerSequence(mappingIndexed(transform), collection);\n}\n\nexport function lazyKeep(transform, collection) {\n requireArity(arguments.length, 2, \"lazyKeep\");\n return transducerSequence(keeping(transform), collection);\n}\n\nexport function lazyKeepIndexed(transform, collection) {\n requireArity(arguments.length, 2, \"lazyKeepIndexed\");\n return transducerSequence(keepingIndexed(transform), collection);\n}\n\nexport function lazyFilter(predicate, collection) {\n requireArity(arguments.length, 2, \"lazyFilter\");\n return transducerSequence(filtering(predicate), collection);\n}\n\nexport function lazyRemove(predicate, collection) {\n requireArity(arguments.length, 2, \"lazyRemove\");\n return transducerSequence(removing(predicate), collection);\n}\n\nexport function lazyTake(limit, collection) {\n requireArity(arguments.length, 2, \"lazyTake\");\n return transducerSequence(taking(limit), collection);\n}\n\nexport function lazyDrop(limit, collection) {\n requireArity(arguments.length, 2, \"lazyDrop\");\n return transducerSequence(dropping(limit), collection);\n}\n\nexport function lazyTakeWhile(predicate, collection) {\n requireArity(arguments.length, 2, \"lazyTakeWhile\");\n return transducerSequence(takingWhile(predicate), collection);\n}\n\nexport function lazyDropWhile(predicate, collection) {\n requireArity(arguments.length, 2, \"lazyDropWhile\");\n return transducerSequence(droppingWhile(predicate), collection);\n}\n\nexport function lazyTakeNth(interval, collection) {\n requireArity(arguments.length, 2, \"lazyTakeNth\");\n return transducerSequence(takingNth(interval), collection);\n}\n\nexport function lazyInterpose(separator, collection) {\n requireArity(arguments.length, 2, \"lazyInterpose\");\n return transducerSequence(interposing(separator), collection);\n}\n\nexport function lazyDedupe(collection) {\n requireArity(arguments.length, 1, \"lazyDedupe\");\n return transducerSequence(deduping(), collection);\n}\n\nexport function lazyDistinct(collection) {\n requireArity(arguments.length, 1, \"lazyDistinct\");\n return transducerSequence(distincting(), collection);\n}\n\nexport function lazyMapcat(transform, collection) {\n requireArity(arguments.length, 2, \"lazyMapcat\");\n return transducerSequence(mapcatting(transform), collection);\n}\n\nexport function lazyPartitionAll(size, collection) {\n requireArity(arguments.length, 2, \"lazyPartitionAll\");\n return transducerSequence(partitioningAll(size), collection);\n}\n\nexport function lazyPartitionBy(classifier, collection) {\n requireArity(arguments.length, 2, \"lazyPartitionBy\");\n return transducerSequence(partitioningBy(classifier), collection);\n}\n\nexport function isLazySequence(value) {\n return value instanceof MemoizedSequenceView;\n}\n\nfunction status(value) {\n if (!isLazySequence(value)) {\n throw new TypeError(\"operation requires a lazy sequence\");\n }\n return memoizedSequenceStatus(value);\n}\n\nexport function isLazySequenceRealized(value) {\n return status(value).started;\n}\n\nexport function realizedLazySequenceCount(value) {\n return status(value).realizedCount;\n}\n\nexport function realizeLazySequence(value) {\n status(value);\n for (const _element of value) {\n // Traversal commits each produced value to the shared realization cache.\n }\n return value;\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.list-internals
|
|
2
|
+
(js* "export const LIST_CONSTRUCTOR_TOKEN = Symbol(\"eliscript.list.constructor\");\nexport const LIST_STATE = Symbol(\"eliscript.list.state\");\n\nconst metrics = {\n nodeAllocations: 0,\n};\n\nexport function recordListNodeAllocation() {\n metrics.nodeAllocations += 1;\n}\n\nexport function resetListMetrics() {\n metrics.nodeAllocations = 0;\n}\n\nexport function readListMetrics() {\n return Object.freeze({ ...metrics });\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.list
|
|
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 LIST_CONSTRUCTOR_TOKEN,\n LIST_STATE,\n recordListNodeAllocation,\n} from \"./list-internals.mjs\";\nimport {\n METADATA_READ,\n METADATA_WITH,\n} from \"./metadata-internals.mjs\";\nimport {\n VALUE_EQUAL,\n VALUE_HASH,\n orderedCollectionHash,\n} from \"./value-internals.mjs\";\n\nconst MAX_COUNT = 0x7fff_ffff;\nconst MISSING = Symbol(\"eliscript.list.missing\");\nconst LIST_HASH_TAG = 0x2f4a_6d19;\n\nfunction makeList(count, value, rest, metadata = null) {\n recordListNodeAllocation();\n return new PersistentList(\n LIST_CONSTRUCTOR_TOKEN,\n count,\n false,\n value,\n rest,\n metadata,\n );\n}\n\nfunction emptyListWithMetadata(metadata) {\n return metadata === null\n ? EMPTY_LIST\n : new PersistentList(\n LIST_CONSTRUCTOR_TOKEN,\n 0,\n true,\n undefined,\n null,\n metadata,\n );\n}\n\nexport class PersistentList {\n constructor(token, count, empty, value, rest, metadata = null) {\n if (token !== LIST_CONSTRUCTOR_TOKEN) {\n throw new TypeError(\n \"PersistentList values must be created with persistentList or PersistentList.from\",\n );\n }\n this[LIST_STATE] = Object.freeze({\n count,\n empty,\n value,\n rest,\n metadata,\n });\n Object.freeze(this);\n }\n\n static empty() {\n return EMPTY_LIST;\n }\n\n static from(iterable) {\n if (iterable instanceof PersistentList) {\n return iterable;\n }\n const values = Array.from(iterable);\n if (values.length > MAX_COUNT) {\n throw new RangeError(`persistent list cannot exceed ${MAX_COUNT} values`);\n }\n let result = EMPTY_LIST;\n for (let index = values.length - 1; index >= 0; index -= 1) {\n result = makeList(result.count + 1, values[index], result);\n }\n return result;\n }\n\n get count() {\n return this[LIST_STATE].count;\n }\n\n get size() {\n return this[LIST_STATE].count;\n }\n\n get isEmpty() {\n return this[LIST_STATE].empty;\n }\n\n first(notFound = null) {\n const state = this[LIST_STATE];\n return state.empty ? notFound : state.value;\n }\n\n rest() {\n const state = this[LIST_STATE];\n return state.empty ? this : state.rest;\n }\n\n peek(notFound = null) {\n return this.first(notFound);\n }\n\n pop() {\n if (this[LIST_STATE].empty) {\n throw new RangeError(\"cannot pop an empty persistent list\");\n }\n return this[LIST_STATE].rest;\n }\n\n conj(value) {\n if (this.count === MAX_COUNT) {\n throw new RangeError(`persistent list cannot exceed ${MAX_COUNT} values`);\n }\n return makeList(this.count + 1, value, this, this[LIST_STATE].metadata);\n }\n\n cons(value) {\n return this.conj(value);\n }\n\n nth(index, notFound = MISSING) {\n if (!Number.isInteger(index) || index < 0 || index >= this.count) {\n if (notFound !== MISSING) {\n return notFound;\n }\n throw new RangeError(\n `nth index ${String(index)} is outside [0, ${this.count})`,\n );\n }\n let node = this;\n let remaining = index;\n while (remaining > 0) {\n node = node[LIST_STATE].rest;\n remaining -= 1;\n }\n return node[LIST_STATE].value;\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 emptyListWithMetadata(this[LIST_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 PersistentList) || other.count !== this.count) {\n return false;\n }\n const right = other[Symbol.iterator]();\n for (const value of this) {\n if (!equal(value, right.next().value)) {\n return false;\n }\n }\n return true;\n }\n\n [VALUE_HASH](hash) {\n return orderedCollectionHash(this, hash, LIST_HASH_TAG);\n }\n\n [METADATA_READ]() {\n return this[LIST_STATE].metadata;\n }\n\n [METADATA_WITH](metadata) {\n const state = this[LIST_STATE];\n if (metadata === state.metadata) {\n return this;\n }\n return state.empty\n ? emptyListWithMetadata(metadata)\n : makeList(state.count, state.value, state.rest, metadata);\n }\n\n *[Symbol.iterator]() {\n let node = this;\n while (!node[LIST_STATE].empty) {\n yield node[LIST_STATE].value;\n node = node[LIST_STATE].rest;\n }\n }\n\n get [Symbol.toStringTag]() {\n return \"EliscriptPersistentList\";\n }\n}\n\nexport const EMPTY_LIST = new PersistentList(\n LIST_CONSTRUCTOR_TOKEN,\n 0,\n true,\n undefined,\n null,\n);\n\nexport function persistentList(...values) {\n return PersistentList.from(values);\n}\n\nexport function isPersistentList(value) {\n return value instanceof PersistentList;\n}\n\nfunction requireList(value, operation) {\n if (!(value instanceof PersistentList)) {\n throw new TypeError(`${operation} expects a persistent List or nil`);\n }\n return value;\n}\n\nexport function first(value, notFound = null) {\n return value == null\n ? notFound\n : requireList(value, \"first\").first(notFound);\n}\n\nexport function rest(value) {\n return value == null\n ? EMPTY_LIST\n : requireList(value, \"rest\").rest();\n}\n\nexport function cons(value, list) {\n return (list == null ? EMPTY_LIST : requireList(list, \"cons\")).cons(value);\n}\n"))
|
package/runtime/core/list.mjs
CHANGED
|
@@ -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"))
|