eliscript 0.0.3 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/bootstrap/README.md +13 -8
- package/bootstrap/host/build.eli +2 -0
- package/bootstrap/host/bun.eli +2 -0
- package/bootstrap/host/check-cli-legacy.eli +2 -0
- package/bootstrap/host/evaluation-cli.eli +2 -0
- package/bootstrap/host/evaluation.eli +2 -0
- package/bootstrap/host/format-cli.eli +2 -0
- package/bootstrap/host/project-cli-legacy.eli +2 -0
- package/bootstrap/host/project-legacy.eli +2 -0
- package/bootstrap/host/watch-cli.eli +2 -0
- package/bootstrap/host/watch.eli +2 -0
- package/browser/README.md +33 -0
- package/browser/host.eli +2 -0
- package/browser/worker.eli +2 -0
- package/package.json +2 -1
- package/platform/README.md +33 -12
- package/platform/browser.eli +2 -0
- package/platform/http.eli +2 -0
- package/platform/worker.eli +2 -0
- package/runtime/README.md +34 -14
- package/runtime/array-text.eli +2 -0
- package/runtime/core/collection-internals.eli +2 -0
- package/runtime/core/collection.eli +2 -0
- package/runtime/core/collection.mjs +99 -17
- package/runtime/core/data-text.eli +2 -0
- package/runtime/core/data.eli +2 -0
- package/runtime/core/data.mjs +7 -5
- package/runtime/core/identifier.eli +2 -0
- package/runtime/core/lazy-sequence.eli +2 -0
- package/runtime/core/list-internals.eli +2 -0
- package/runtime/core/list.eli +2 -0
- package/runtime/core/list.mjs +3 -0
- package/runtime/core/map-internals.eli +2 -0
- package/runtime/core/map.eli +2 -0
- package/runtime/core/map.mjs +5 -0
- package/runtime/core/metadata-internals.eli +2 -0
- package/runtime/core/metadata.eli +2 -0
- package/runtime/core/metadata.mjs +14 -0
- package/runtime/core/object.eli +2 -0
- package/runtime/core/order.eli +2 -0
- package/runtime/core/order.mjs +35 -6
- package/runtime/core/persistent-kind.eli +2 -0
- package/runtime/core/persistent-kind.mjs +6 -0
- package/runtime/core/protocol-error.eli +2 -0
- package/runtime/core/protocol.eli +2 -0
- package/runtime/core/queue-internals.eli +2 -0
- package/runtime/core/queue.eli +2 -0
- package/runtime/core/queue.mjs +3 -0
- package/runtime/core/record.eli +2 -0
- package/runtime/core/regex.eli +2 -0
- package/runtime/core/sequence.eli +2 -0
- package/runtime/core/sequence.mjs +75 -13
- package/runtime/core/set-algebra.eli +2 -0
- package/runtime/core/set-internals.eli +2 -0
- package/runtime/core/set.eli +2 -0
- package/runtime/core/sorted-internals.eli +2 -0
- package/runtime/core/sorted.eli +2 -0
- package/runtime/core/text.eli +2 -0
- package/runtime/core/transducer.eli +2 -0
- package/runtime/core/transient-internals.eli +2 -0
- package/runtime/core/transient.eli +2 -0
- package/runtime/core/transient.mjs +59 -10
- package/runtime/core/truth.eli +2 -0
- package/runtime/core/type.eli +2 -0
- package/runtime/core/value-internals.eli +2 -0
- package/runtime/core/value.eli +2 -0
- package/runtime/core/vector-internals.eli +2 -0
- package/runtime/core/vector-internals.mjs +3 -6
- package/runtime/core/vector.eli +2 -0
- package/runtime/core/vector.mjs +125 -7
- package/runtime/literals.eli +2 -0
- package/runtime/number-radix.eli +2 -0
- package/runtime/source-mapping.eli +2 -0
- package/runtime/testing/list.eli +2 -0
- package/runtime/testing/map.eli +2 -0
- package/runtime/testing/queue.eli +2 -0
- package/runtime/testing/set.eli +2 -0
- package/runtime/testing/sorted.eli +2 -0
- package/runtime/testing/value.eli +2 -0
- package/runtime/testing/vector.eli +2 -0
- package/runtime/wire/http-rpc.eli +2 -0
- package/runtime/wire/markdown.eli +2 -0
- package/runtime/wire/schema.eli +2 -0
- package/runtime/worker-value-codec.eli +2 -0
- package/runtime/worker-value-stream.eli +2 -0
- package/runtime/worker.eli +2 -0
- package/stdlib/README.md +2 -2
- package/stdlib/core/order.eli +36 -10
- package/stdlib/core/seq.eli +104 -75
- package/stdlib/core/zipper.eli +238 -98
- package/stdlib/managed-literal-protocols.eli +5 -5
- package/stdlib/managed-runtime-order.eli +32 -10
- package/stdlib/managed-runtime-sequence.eli +69 -28
- package/tools/acceptance/check.eli +13 -3
- package/tools/backends/compiler-build.mjs +140 -140
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.platform.http
|
|
2
|
+
(js* "const names = new Set([\n \"URL\", \"Response\", \"Headers\", \"AbortController\", \"AbortSignal\",\n \"TextDecoder\", \"Uint8Array\", \"fetch\", \"setTimeout\", \"clearTimeout\",\n]);\n\n// Web transport capabilities are read at the point of use. The protocol and\n// representation algorithms remain in the calling Eliscript module.\nexport function readHttpGlobal(name) {\n if (!names.has(name)) throw new TypeError(\"unknown HTTP host capability\");\n return globalThis[name];\n}\n\nconst capabilities = Object.create(null);\nfor (const name of names) {\n Object.defineProperty(capabilities, name, {\n get() { return globalThis[name]; },\n enumerable: true,\n });\n}\nexport const globals = Object.freeze(capabilities);\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.platform.worker
|
|
2
|
+
(js* "export {\n WorkerValueCodecError,\n decodeWorkerValue,\n decodeWorkerValues,\n encodeWorkerValue,\n encodeWorkerValues,\n workerValueEncoding,\n workerValueLimits,\n} from \"../runtime/worker-value-codec.mjs\";\nexport {\n WorkerValueStreamDecoder,\n WorkerValueStreamError,\n decodeWorkerValueChunks,\n encodeWorkerValueChunks,\n encodeWorkerValueEvents,\n workerValueFraming,\n workerValueStreamLimits,\n} from \"../runtime/worker-value-stream.mjs\";\n\nexport const workerCapabilityKinds = Object.freeze([\n \"cancellation\",\n \"progress\",\n]);\n\nconst capabilityState = new WeakMap();\nconst knownCapabilities = new Set(workerCapabilityKinds);\n\nexport class WorkerCapabilityError extends Error {\n constructor(code, message, capability) {\n super(message);\n this.name = \"WorkerCapabilityError\";\n this.code = code;\n this.capability = capability;\n }\n}\n\nfunction fail(code, message, capability) {\n throw new WorkerCapabilityError(code, message, capability);\n}\n\nfunction normalizeGrants(grants) {\n if (!Array.isArray(grants) || grants.some(\n (grant) => typeof grant !== \"string\" || grant.length === 0,\n )) {\n fail(\"invalid-grants\", \"worker grants must be an array of non-empty strings\");\n }\n const normalized = [...new Set(grants)].sort();\n if (normalized.length !== grants.length) {\n fail(\"duplicate-grant\", \"worker grants must not contain duplicates\");\n }\n for (const grant of normalized) {\n if (!knownCapabilities.has(grant)) {\n fail(\"unknown-grant\", `unknown worker capability ${grant}`, grant);\n }\n }\n return normalized;\n}\n\nfunction operationTable(context, grants) {\n const operations = Object.create(null);\n for (const grant of grants) {\n if (grant === \"progress\") {\n if (typeof context.progress !== \"function\") {\n fail(\n \"unavailable-capability\",\n \"worker context does not provide progress\",\n grant,\n );\n }\n operations.progress = (value) => Reflect.apply(\n context.progress,\n context,\n [value],\n );\n } else if (grant === \"cancellation\") {\n const signal = context.signal;\n if (signal === null || typeof signal !== \"object\" ||\n typeof signal.aborted !== \"boolean\" ||\n typeof signal.addEventListener !== \"function\") {\n fail(\n \"unavailable-capability\",\n \"worker context does not provide an AbortSignal\",\n grant,\n );\n }\n operations.signal = () => signal;\n }\n }\n return Object.freeze(operations);\n}\n\nexport function workerCapabilities(context, grants = []) {\n if (context === null || typeof context !== \"object\") {\n fail(\"invalid-host\", \"worker context must be an object\");\n }\n const normalized = normalizeGrants(grants);\n const capabilities = Object.freeze({\n format: \"eliscript-worker-capabilities\",\n version: 1,\n grants: Object.freeze(normalized),\n });\n capabilityState.set(capabilities, operationTable(context, normalized));\n return capabilities;\n}\n\nexport function isWorkerCapabilities(value) {\n return value !== null && typeof value === \"object\" && capabilityState.has(value);\n}\n\nfunction stateFor(capabilities) {\n const state = isWorkerCapabilities(capabilities)\n ? capabilityState.get(capabilities)\n : undefined;\n if (state === undefined) {\n fail(\"invalid-capabilities\", \"expected Eliscript worker capabilities\");\n }\n return state;\n}\n\nexport function workerCapabilityDescriptor(capabilities) {\n stateFor(capabilities);\n return Object.freeze({\n format: capabilities.format,\n version: capabilities.version,\n grants: Object.freeze([...capabilities.grants]),\n });\n}\n\nexport function hasWorkerCapability(capabilities, capability) {\n stateFor(capabilities);\n return typeof capability === \"string\" && capabilities.grants.includes(capability);\n}\n\nfunction operationFor(capabilities, operation, capability) {\n const operation_ = stateFor(capabilities)[operation];\n if (operation_ === undefined) {\n fail(\n \"missing-capability\",\n `worker capability ${capability} was not granted`,\n capability,\n );\n }\n return operation_;\n}\n\nexport function workerProgress(capabilities, value) {\n return operationFor(capabilities, \"progress\", \"progress\")(value);\n}\n\nexport function workerSignal(capabilities) {\n return operationFor(capabilities, \"signal\", \"cancellation\")();\n}\n\nexport function workerCancelled(capabilities) {\n return workerSignal(capabilities).aborted;\n}\n\nexport function throwIfWorkerCancelled(capabilities) {\n if (workerCancelled(capabilities)) {\n fail(\n \"worker-cancelled\",\n \"worker operation has been cancelled\",\n \"cancellation\",\n );\n }\n}\n"))
|
package/runtime/README.md
CHANGED
|
@@ -10,9 +10,17 @@ represented by ordinary host values alone. Ordinary JavaScript values and APIs
|
|
|
10
10
|
should still be emitted directly; helpers need a concrete semantic reason to
|
|
11
11
|
exist.
|
|
12
12
|
|
|
13
|
+
All runtime modules in this directory (`literals.eli`, `worker.eli`,
|
|
14
|
+
`math.eli`, `unicode-case.eli`, `core/*.eli`, `testing/*.eli`, and `wire/*.eli`)
|
|
15
|
+
are maintained as `.eli` sources in Git and materialized or compiled to `.mjs`
|
|
16
|
+
during `make bootstrap-backends` (zero tracked `.mjs` files in the repository).
|
|
17
|
+
Eliscript modules may import `eliscript/runtime/*` either without the `.mjs`
|
|
18
|
+
extension (for example `(import "eliscript/runtime/core/order" sort)`) or with
|
|
19
|
+
an explicit `.mjs` suffix.
|
|
20
|
+
|
|
13
21
|
The compiler still emits a local Lisp-truthiness helper for standalone
|
|
14
|
-
generated forms. `core/truth.mjs` exposes the same semantics
|
|
15
|
-
algorithms: only `false`, `null`, and `undefined` are false.
|
|
22
|
+
generated forms. `core/truth.eli` (`core/truth.mjs`) exposes the same semantics
|
|
23
|
+
to shared runtime algorithms: only `false`, `null`, and `undefined` are false.
|
|
16
24
|
|
|
17
25
|
Host libraries are imported explicitly by application modules. The runtime
|
|
18
26
|
contains no UI-framework wrapper, element constructor, or bundler adapter.
|
|
@@ -236,26 +244,38 @@ is exposed only through `testing/vector.mjs`, `testing/map.mjs`, and
|
|
|
236
244
|
|
|
237
245
|
### Core Algorithms
|
|
238
246
|
|
|
239
|
-
`core/sequence.mjs` implements replayable range,
|
|
247
|
+
`core/sequence.eli` (`core/sequence.mjs`) implements replayable range,
|
|
248
|
+
repetition, iteration, cycle,
|
|
240
249
|
and indexed generation sources plus eager indexed/keep, prefix, sampling,
|
|
241
250
|
interposition, dedupe/distinct, flattening, partitioning, reduction-history,
|
|
242
251
|
boundary lookup, bounded tail selection, one-pass splitting, and search
|
|
243
252
|
operations against `IReduce`. Results are persistent Vectors, reduced values
|
|
244
|
-
stop bounded traversal exactly, and tail selection
|
|
245
|
-
|
|
253
|
+
stop bounded traversal exactly, and tail selection (`takeLast`, `dropLast`) uses
|
|
254
|
+
fixed-size `Array(limit)` circular ring buffers without integer-key hash-table
|
|
255
|
+
boxing. `first` dispatches in $O(1)$ on `PersistentList`, `PersistentVector`,
|
|
256
|
+
and `Array`; `last` dispatches in $O(1)$ on `PersistentVector` (via `.peek()`)
|
|
257
|
+
and `Array`; generic `first`, `last`, `sequenceNth`, and `find` reduction loops
|
|
258
|
+
use stack-local state without allocating temporary `{ value }` wrapper objects.
|
|
259
|
+
Source callbacks are lazy, finite sources expose exact counts, and
|
|
246
260
|
unbounded sources compose with every reduced-value bounded consumer.
|
|
247
|
-
`core/data.mjs` implements
|
|
261
|
+
`core/data.eli` (`core/data.mjs`) implements
|
|
248
262
|
value-semantic indexing, grouping, counting, frequencies, nested associative
|
|
249
|
-
reads and updates, key selection, merging, and key/value zipping.
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
263
|
+
reads and updates, key selection, merging, and key/value zipping. `groupBy`,
|
|
264
|
+
`countBy`, and `frequencies` accumulate bucket indices via transient HAMT
|
|
265
|
+
builders (`transient(EMPTY_MAP)` + `TransientHashMap.get` + `assocBang` +
|
|
266
|
+
`persistentBang`) and build group Vectors via `transient(EMPTY_VECTOR)` +
|
|
267
|
+
`conjBang` + `persistentBang`. Native and persistent collections, null, and
|
|
268
|
+
external protocol extensions all use the same algorithm path.
|
|
269
|
+
|
|
270
|
+
`core/order.eli` (`core/order.mjs`) defines the open `IComparable` protocol,
|
|
271
|
+
deterministic
|
|
272
|
+
natural comparison for scalar, identifier, List, and Vector values (with $O(1)$
|
|
273
|
+
reference-identity short-circuiting in `compareSequential` and `[VALUE_EQUAL]`
|
|
274
|
+
across all persistent collections), comparator
|
|
256
275
|
adaptation, stable `sort` and `sortBy`, and keyed extrema. Sorting consumes any
|
|
257
276
|
`IReduce` source, caches each sort key once, preserves equal-value source order,
|
|
258
|
-
and
|
|
277
|
+
and constructs the resulting persistent Vector in a single `transient` +
|
|
278
|
+
`conjBang` + `persistentBang` pass without intermediate array `.map()` copies.
|
|
259
279
|
|
|
260
280
|
`core/text-impl.mjs` and `core/object-impl.mjs` are generated from
|
|
261
281
|
`stdlib/core/text.eli` and `stdlib/core/object.eli`. Their public modules are
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.array-text
|
|
2
|
+
(js* "// Internal JS target support. Generated modules import identical data URLs so\n// recursive conversions share one guard without modifying global prototypes.\nimport {numberStringBuiltin, numberRadixText} from './number-radix.mjs';\nconst apply = Reflect.apply;\nconst functionCall = Function.prototype.call, functionApply = Function.prototype.apply, functionBind = Function.prototype.bind;\nconst define = Object.defineProperty, descriptor = Object.getOwnPropertyDescriptor;\nconst prototype = Object.getPrototypeOf, setPrototype = Object.setPrototypeOf, ownKeys = Reflect.ownKeys;\nconst hasInstance = Symbol.hasInstance;\nconst array = Array.isArray;\nconst intrinsicJoin = Array.prototype.join;\nconst intrinsicArrayString = Array.prototype.toString;\nconst objectString = Object.prototype.toString;\nconst string = String;\nconst TypeErrorClass = TypeError;\nconst primitiveKey = Symbol.toPrimitive;\nconst weakHas = WeakSet.prototype.has, weakAdd = WeakSet.prototype.add, weakDelete = WeakSet.prototype.delete;\nconst active = new WeakSet();\nlet activeRoot = null;\nconst object = value => value !== null && (typeof value === 'object' || typeof value === 'function' || (typeof value === 'undefined' && value !== void 0));\nconst callable = value => typeof value === 'function' || (typeof value === 'undefined' && value !== void 0);\nfunction cycle() {\n const message = 'cyclic array text conversion', error = new TypeErrorClass(message);\n error.eliscriptDiagnostic = {format: 'eliscript-diagnostic', version: 1, code: 'ELI-RT0009', severity: 'error', phase: 'runtime', message};\n throw error;\n}\nfunction primitive(value) {\n if (!object(value)) return value;\n const exotic = value[primitiveKey];\n if (exotic !== void 0 && exotic !== null) {\n const result = apply(exotic, value, ['string']);\n if (!object(result)) return result;\n throw new TypeErrorClass('Cannot convert object to primitive value');\n }\n for (let index = 0; index < 2; index++) {\n const method = value[index === 0 ? 'toString' : 'valueOf'];\n if (callable(method)) {\n const result = method === intrinsicArrayString && array(value) ? arrayString(value) : apply(method, value, []);\n if (!object(result)) return result;\n }\n }\n throw new TypeErrorClass('Cannot convert object to primitive value');\n}\nfunction text(value) {\n const result = primitive(value);\n if (typeof result === 'symbol') throw new TypeErrorClass('Cannot convert a Symbol value to a string');\n return string(result);\n}\nfunction join(value, separator) {\n // Length is observed before separator conversion; indexed values stay live.\n const size = +value.length;\n const length = size !== size || size <= 0 ? 0 : size >= 9007199254740991 ? 9007199254740991 : size - size % 1;\n const sep = separator === void 0 ? ',' : text(separator);\n // The common outermost conversion needs only one private root reference.\n // Descendants retain weak membership and check that root before entering.\n const root = activeRoot === null;\n if (root) activeRoot = value;\n else {\n if (value === activeRoot || apply(weakHas, active, [value])) cycle();\n apply(weakAdd, active, [value]);\n }\n try {\n let result = '';\n for (let index = 0; index < length; index++) {\n if (index) result += sep;\n const child = value[index];\n if (child !== null && child !== void 0) result += text(child);\n }\n return result;\n } finally {\n if (root) activeRoot = null;\n else apply(weakDelete, active, [value]);\n }\n}\nfunction arrayString(value) {\n const method = value.join;\n return callable(method) ? method === intrinsicJoin ? join(value, void 0) : apply(method, value, []) : apply(objectString, value, []);\n}\nfunction argument(args, index) {return index < args.length ? args[index] : void 0;}\nfunction argumentTail(args, start) {\n const result = [];\n for (let index = start; index < args.length; index++) {\n // This is an internal argument List, not a user array operation: neither\n // species, iterators nor inherited numeric setters participate.\n define(result, result.length, {value: args[index], writable: true, enumerable: true, configurable: true});\n }\n return result;\n}\nfunction joinArguments(first, second) {\n const result = [];\n for (let index = 0; index < first.length + second.length; index++) {\n define(result, index, {value: index < first.length ? first[index] : second[index - first.length],\n writable: true, enumerable: true, configurable: true});\n }\n return result;\n}\nfunction collectArguments(...args) {return args;}\nfunction argumentList(value, optional) {\n // Native apply performs complete CreateListFromArrayLike in its original\n // order, even for ignored arguments. Reflect.apply deliberately rejects\n // null/undefined whereas Function.apply treats them as an empty list.\n return optional ? apply(functionApply, collectArguments, [void 0, value]) : apply(collectArguments, void 0, value);\n}\nfunction dispatch(method, receiver, args) {\n for (;;) {\n if (method === numberStringBuiltin) return numberRadixText(receiver, argument(args, 0));\n if (method === intrinsicJoin && array(receiver)) return join(receiver, argument(args, 0));\n if (method === intrinsicArrayString && array(receiver)) return arrayString(receiver);\n if (method === functionCall) {\n if (!callable(receiver)) return apply(method, receiver, args);\n const target = receiver, nextReceiver = argument(args, 0);\n args = argumentTail(args, 1);method = target;receiver = nextReceiver;continue;\n }\n if (method === functionApply) {\n // Reject a noncallable target before even asking for list.length.\n if (!callable(receiver)) return apply(method, receiver, args);\n const target = receiver, nextReceiver = argument(args, 0);\n args = argumentList(argument(args, 1), true);method = target;receiver = nextReceiver;continue;\n }\n if (method === apply) {\n const target = argument(args, 0), nextReceiver = argument(args, 1);\n if (!callable(target)) return apply(method, receiver, args);\n args = argumentList(argument(args, 2), false);method = target;receiver = nextReceiver;continue;\n }\n if (method === functionBind) {\n // Real bind owns the observable length/name reads, descriptors, prototype\n // and constructibility. Only its call behavior is handled privately.\n const bound = apply(method, receiver, args);\n if (receiver !== numberStringBuiltin && receiver !== intrinsicJoin && receiver !== intrinsicArrayString &&\n receiver !== functionCall && receiver !== functionApply && receiver !== apply && receiver !== functionBind) return bound;\n const target = receiver, boundReceiver = argument(args, 0), prefix = argumentTail(args, 1);\n // Return a real BoundFunction, so OrdinaryHasInstance can follow its\n // bound target. A Proxy around `bound` would lose that internal-slot\n // behavior even with no get trap. The private arrow is nonconstructible,\n // as are all supported native targets, and delegates live instanceof\n // checks to the original target (including a subsequently changed\n // prototype or Symbol.hasInstance).\n const invoke = (...values) => dispatch(target, boundReceiver, joinArguments(prefix, values));\n define(invoke, hasInstance, {value: value => value instanceof target, configurable: true});\n const result = apply(functionBind, invoke, [void 0]);\n setPrototype(result, prototype(bound));\n const keys = ownKeys(bound);\n for (let index = 0; index < keys.length; index++) define(result, keys[index], descriptor(bound, keys[index]));\n return result;\n }\n return apply(method, receiver, args);\n }\n}\nfunction captureArrayText(value, key) {\n // Capture before source argument evaluation, including a failing lookup.\n const method = value[key];\n return (...args) => dispatch(method, value, args);\n}\n// Literal actual arguments have no observable evaluation before this lookup.\n// Other calls must retain captureArrayText's lookup-before-arguments boundary.\nfunction invokeArrayText(value, key, ...args) {\n const method = value[key];\n return dispatch(method, value, args);\n}\nexport {captureArrayText as c, invokeArrayText as d};\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.collection-internals
|
|
2
|
+
(js* "import {\n defineProtocol,\n protocolMethod,\n protocolSlot,\n} from \"./protocol.mjs\";\n\nexport const I_COUNTED = defineProtocol(\"ICounted\", [\"count\"]);\nexport const I_EMPTYABLE = defineProtocol(\"IEmptyable\", [\"empty\"]);\nexport const I_CONJ = defineProtocol(\"IConj\", [\"conj\"]);\nexport const I_LOOKUP = defineProtocol(\"ILookup\", [\"get\"]);\nexport const I_ASSOCIATIVE = defineProtocol(\"IAssociative\", [\n \"assoc\",\n \"contains\",\n]);\nexport const I_INDEXED = defineProtocol(\"IIndexed\", [\"nth\"]);\nexport const I_SEQABLE = defineProtocol(\"ISeqable\", [\"seq\"]);\nexport const I_REDUCE = defineProtocol(\"IReduce\", [\"reduce\"]);\nexport const I_KV_REDUCE = defineProtocol(\"IKVReduce\", [\"reduceKV\"]);\nexport const I_MAP = defineProtocol(\"IMap\", [\"dissoc\"]);\nexport const I_SET = defineProtocol(\"ISet\", [\"disj\"]);\nexport const I_STACK = defineProtocol(\"IStack\", [\"peek\", \"pop\"]);\nexport const I_REVERSIBLE = defineProtocol(\"IReversible\", [\"rseq\"]);\n\nexport const COLLECTION_COUNT = protocolSlot(I_COUNTED, \"count\");\nexport const COLLECTION_EMPTY = protocolSlot(I_EMPTYABLE, \"empty\");\nexport const COLLECTION_CONJ = protocolSlot(I_CONJ, \"conj\");\nexport const COLLECTION_GET = protocolSlot(I_LOOKUP, \"get\");\nexport const COLLECTION_ASSOC = protocolSlot(I_ASSOCIATIVE, \"assoc\");\nexport const COLLECTION_CONTAINS = protocolSlot(I_ASSOCIATIVE, \"contains\");\nexport const COLLECTION_NTH = protocolSlot(I_INDEXED, \"nth\");\nexport const COLLECTION_SEQ = protocolSlot(I_SEQABLE, \"seq\");\nexport const COLLECTION_REDUCE = protocolSlot(I_REDUCE, \"reduce\");\nexport const COLLECTION_REDUCE_KV = protocolSlot(I_KV_REDUCE, \"reduceKV\");\nexport const COLLECTION_DISSOC = protocolSlot(I_MAP, \"dissoc\");\nexport const COLLECTION_DISJ = protocolSlot(I_SET, \"disj\");\nexport const COLLECTION_PEEK = protocolSlot(I_STACK, \"peek\");\nexport const COLLECTION_POP = protocolSlot(I_STACK, \"pop\");\nexport const COLLECTION_RSEQ = protocolSlot(I_REVERSIBLE, \"rseq\");\n\nexport const dispatchCollectionCount = protocolMethod(I_COUNTED, \"count\");\nexport const dispatchCollectionEmpty = protocolMethod(I_EMPTYABLE, \"empty\");\nexport const dispatchCollectionConj = protocolMethod(I_CONJ, \"conj\");\nexport const dispatchCollectionGet = protocolMethod(I_LOOKUP, \"get\");\nexport const dispatchCollectionAssoc = protocolMethod(I_ASSOCIATIVE, \"assoc\");\nexport const dispatchCollectionContains = protocolMethod(\n I_ASSOCIATIVE,\n \"contains\",\n);\nexport const dispatchCollectionNth = protocolMethod(I_INDEXED, \"nth\");\nexport const dispatchCollectionSeq = protocolMethod(I_SEQABLE, \"seq\");\nexport const dispatchCollectionReduce = protocolMethod(I_REDUCE, \"reduce\");\nexport const dispatchCollectionReduceKV = protocolMethod(I_KV_REDUCE, \"reduceKV\");\nexport const dispatchCollectionDissoc = protocolMethod(I_MAP, \"dissoc\");\nexport const dispatchCollectionDisj = protocolMethod(I_SET, \"disj\");\nexport const dispatchCollectionPeek = protocolMethod(I_STACK, \"peek\");\nexport const dispatchCollectionPop = protocolMethod(I_STACK, \"pop\");\nexport const dispatchCollectionRseq = protocolMethod(I_REVERSIBLE, \"rseq\");\n\nconst NO_INITIAL = Symbol(\"eliscript.collection.no-initial\");\nconst REDUCED_STATE = Symbol(\"eliscript.collection.reduced-state\");\nconst REDUCTION_STATE = Symbol(\"eliscript.collection.reduction-state\");\nconst REDUCTION_TOKEN = Symbol(\"eliscript.collection.reduction-token\");\nconst MEMOIZED_SEQUENCE_STATE = Symbol(\n \"eliscript.collection.memoized-sequence-state\",\n);\nconst MEMOIZED_SEQUENCE_TOKEN = Symbol(\n \"eliscript.collection.memoized-sequence-token\",\n);\nconst NO_MEMOIZED_SEQUENCE_FAILURE = Symbol(\n \"eliscript.collection.no-memoized-sequence-failure\",\n);\nconst SEQUENCE_STATE = Symbol(\"eliscript.collection.sequence-state\");\nconst SEQUENCE_TOKEN = Symbol(\"eliscript.collection.sequence-token\");\nconst UNBOUNDED_SEQUENCE = Symbol(\"eliscript.collection.unbounded-sequence\");\n\nfunction checkedCount(value) {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new TypeError(\"collection count must be a non-negative safe integer\");\n }\n return value;\n}\n\nfunction iteratorFromFactory(factory) {\n const iterator = factory();\n if (iterator === null || typeof iterator !== \"object\" ||\n typeof iterator.next !== \"function\") {\n throw new TypeError(\"sequence view factory must return an iterator\");\n }\n return iterator;\n}\n\nclass MemoizedSequenceSource {\n constructor(factory) {\n this.factory = factory;\n this.source = null;\n this.values = [];\n this.started = false;\n this.complete = false;\n this.failure = NO_MEMOIZED_SEQUENCE_FAILURE;\n }\n\n read(index) {\n if (index < this.values.length) {\n return { value: this.values[index], done: false };\n }\n if (this.failure !== NO_MEMOIZED_SEQUENCE_FAILURE) throw this.failure;\n if (this.complete) return { value: undefined, done: true };\n if (!this.started) {\n this.started = true;\n try {\n this.source = iteratorFromFactory(this.factory);\n this.factory = null;\n } catch (error) {\n this.failure = error;\n throw error;\n }\n }\n try {\n const result = this.source.next();\n if (result === null || typeof result !== \"object\" ||\n typeof result.done !== \"boolean\") {\n throw new TypeError(\"sequence iterator must return an iterator result\");\n }\n if (result.done) {\n this.complete = true;\n this.source = null;\n return { value: undefined, done: true };\n }\n this.values.push(result.value);\n return { value: result.value, done: false };\n } catch (error) {\n const source = this.source;\n this.failure = error;\n this.source = null;\n if (source !== null && typeof source.return === \"function\") {\n try {\n source.return();\n } catch {\n // Preserve the original realization failure as the stable result.\n }\n }\n throw error;\n }\n }\n\n iterator() {\n const source = this;\n let index = 0;\n let closed = false;\n return {\n next() {\n if (closed) return { value: undefined, done: true };\n const result = source.read(index);\n if (!result.done) index += 1;\n return result;\n },\n return(value) {\n closed = true;\n return { value, done: true };\n },\n [Symbol.iterator]() {\n return this;\n },\n };\n }\n}\n\nexport function readCollectionEntry(entry) {\n if (entry === null || entry === undefined ||\n typeof entry[Symbol.iterator] !== \"function\") {\n throw new TypeError(\n \"persistent hash map entries must be iterable key/value pairs\",\n );\n }\n const iterator = iteratorFromFactory(() => entry[Symbol.iterator]());\n let complete = false;\n try {\n const first = iterator.next();\n if (first.done) {\n throw new TypeError(\n \"persistent hash map entries must contain exactly two values\",\n );\n }\n const second = iterator.next();\n if (second.done) {\n throw new TypeError(\n \"persistent hash map entries must contain exactly two values\",\n );\n }\n const third = iterator.next();\n if (!third.done) {\n throw new TypeError(\n \"persistent hash map entries must contain exactly two values\",\n );\n }\n complete = true;\n return [first.value, second.value];\n } finally {\n if (!complete && typeof iterator.return === \"function\") {\n iterator.return();\n }\n }\n}\n\nfunction sequenceCount(state) {\n if (state.count === UNBOUNDED_SEQUENCE) {\n throw new RangeError(\"unbounded sequence does not have a finite count\");\n }\n if (typeof state.count === \"function\") {\n return checkedCount(state.count());\n }\n if (state.count !== null) {\n return state.count;\n }\n const iterator = iteratorFromFactory(state.factory);\n let count = 0;\n while (!iterator.next().done) {\n count += 1;\n checkedCount(count);\n }\n return count;\n}\n\nfunction slicedSequenceCount(state, offset) {\n if (state.count === UNBOUNDED_SEQUENCE) {\n return UNBOUNDED_SEQUENCE;\n }\n if (typeof state.count === \"function\") {\n return () => Math.max(0, sequenceCount(state) - offset);\n }\n if (state.count === null) {\n return null;\n }\n return Math.max(0, state.count - offset);\n}\n\nfunction prependedSequenceCount(state) {\n if (state.count === UNBOUNDED_SEQUENCE) {\n return UNBOUNDED_SEQUENCE;\n }\n if (typeof state.count === \"function\") {\n return () => checkedCount(sequenceCount(state) + 1);\n }\n if (state.count === null) {\n return null;\n }\n return checkedCount(state.count + 1);\n}\n\nexport class SequenceView {\n constructor(token, factory, count) {\n if (token !== SEQUENCE_TOKEN || typeof factory !== \"function\") {\n throw new TypeError(\"SequenceView values must be created by seq\");\n }\n this[SEQUENCE_STATE] = Object.freeze({ factory, count });\n Object.freeze(this);\n }\n\n [COLLECTION_COUNT]() {\n return sequenceCount(this[SEQUENCE_STATE]);\n }\n\n [COLLECTION_SEQ]() {\n const state = this[SEQUENCE_STATE];\n if (state.count === UNBOUNDED_SEQUENCE) {\n return this;\n }\n if (state.count === null) {\n const iterator = iteratorFromFactory(state.factory);\n try {\n return iterator.next().done ? null : this;\n } finally {\n if (typeof iterator.return === \"function\") {\n iterator.return();\n }\n }\n }\n return this[COLLECTION_COUNT]() === 0 ? null : this;\n }\n\n [COLLECTION_REDUCE](reducer, ...initial) {\n return reduceIterable(this, reducer, ...initial);\n }\n\n [Symbol.iterator]() {\n return iteratorFromFactory(this[SEQUENCE_STATE].factory);\n }\n\n get [Symbol.toStringTag]() {\n return \"EliscriptSequenceView\";\n }\n}\n\nexport class MemoizedSequenceView {\n constructor(token, factory, count) {\n if (token !== MEMOIZED_SEQUENCE_TOKEN || typeof factory !== \"function\") {\n throw new TypeError(\n \"MemoizedSequenceView values must be created by memoizedSequenceView\",\n );\n }\n this[MEMOIZED_SEQUENCE_STATE] = Object.freeze({\n source: new MemoizedSequenceSource(factory),\n count,\n });\n Object.freeze(this);\n }\n\n [COLLECTION_COUNT]() {\n return sequenceCount({\n factory: () => this[Symbol.iterator](),\n count: this[MEMOIZED_SEQUENCE_STATE].count,\n });\n }\n\n [COLLECTION_SEQ]() {\n const iterator = this[Symbol.iterator]();\n try {\n return iterator.next().done ? null : this;\n } finally {\n iterator.return();\n }\n }\n\n [COLLECTION_REDUCE](reducer, ...initial) {\n return reduceIterable(this, reducer, ...initial);\n }\n\n [Symbol.iterator]() {\n return this[MEMOIZED_SEQUENCE_STATE].source.iterator();\n }\n\n get [Symbol.toStringTag]() {\n return \"EliscriptMemoizedSequenceView\";\n }\n}\n\nexport class ReductionView {\n constructor(token, reduceFunction) {\n if (token !== REDUCTION_TOKEN || typeof reduceFunction !== \"function\") {\n throw new TypeError(\"ReductionView values must be created by reductionView\");\n }\n this[REDUCTION_STATE] = reduceFunction;\n Object.freeze(this);\n }\n\n [COLLECTION_REDUCE](reducer, ...initial) {\n return this[REDUCTION_STATE](reducer, ...initial);\n }\n\n get [Symbol.toStringTag]() {\n return \"EliscriptReductionView\";\n }\n}\n\nexport function sequenceView(factory, count = null) {\n if (typeof factory !== \"function\") {\n throw new TypeError(\"sequence view factory must be a function\");\n }\n if (count !== null && typeof count !== \"function\") {\n checkedCount(count);\n if (count === 0) {\n return null;\n }\n }\n return new SequenceView(SEQUENCE_TOKEN, factory, count);\n}\n\nexport function unboundedSequenceView(factory) {\n if (typeof factory !== \"function\") {\n throw new TypeError(\"unbounded sequence view factory must be a function\");\n }\n return new SequenceView(SEQUENCE_TOKEN, factory, UNBOUNDED_SEQUENCE);\n}\n\nexport function memoizedSequenceView(factory, count = null) {\n if (typeof factory !== \"function\") {\n throw new TypeError(\"memoized sequence view factory must be a function\");\n }\n if (count !== null) {\n checkedCount(count);\n if (count === 0) return null;\n }\n return new MemoizedSequenceView(MEMOIZED_SEQUENCE_TOKEN, factory, count);\n}\n\nexport function memoizedSequenceStatus(value) {\n if (!(value instanceof MemoizedSequenceView)) {\n throw new TypeError(\"expected a memoized sequence view\");\n }\n const source = value[MEMOIZED_SEQUENCE_STATE].source;\n return Object.freeze({\n started: source.started,\n complete: source.complete,\n failed: source.failure !== NO_MEMOIZED_SEQUENCE_FAILURE,\n realizedCount: source.values.length,\n });\n}\n\nexport function sliceSequenceView(sequence, offset) {\n if (sequence === null) {\n return null;\n }\n if (!(sequence instanceof SequenceView) &&\n !(sequence instanceof MemoizedSequenceView)) {\n throw new TypeError(\"sequence slice expects a SequenceView or nil\");\n }\n checkedCount(offset);\n if (offset === 0) {\n return sequence;\n }\n\n const state = sequence instanceof SequenceView\n ? sequence[SEQUENCE_STATE]\n : {\n factory: () => sequence[Symbol.iterator](),\n count: sequence[MEMOIZED_SEQUENCE_STATE].count,\n };\n const factory = () => {\n const iterator = sequence[Symbol.iterator]();\n let remaining = offset;\n while (remaining > 0) {\n if (iterator.next().done) {\n return iterator;\n }\n remaining -= 1;\n }\n return iterator;\n };\n const count = slicedSequenceCount(state, offset);\n return count === UNBOUNDED_SEQUENCE\n ? unboundedSequenceView(factory)\n : sequenceView(factory, count);\n}\n\nexport function prependSequenceView(value, sequence) {\n if (sequence !== null && !(sequence instanceof SequenceView) &&\n !(sequence instanceof MemoizedSequenceView)) {\n throw new TypeError(\"sequence prepend expects a SequenceView or nil\");\n }\n\n const factory = () => (function* prependedValues() {\n yield value;\n if (sequence !== null) {\n yield* sequence;\n }\n })();\n if (sequence === null) {\n return sequenceView(factory, 1);\n }\n\n const state = sequence instanceof SequenceView\n ? sequence[SEQUENCE_STATE]\n : {\n factory: () => sequence[Symbol.iterator](),\n count: sequence[MEMOIZED_SEQUENCE_STATE].count,\n };\n const count = prependedSequenceCount(state);\n return count === UNBOUNDED_SEQUENCE\n ? unboundedSequenceView(factory)\n : sequenceView(factory, count);\n}\n\nexport function reductionView(reduceFunction) {\n if (typeof reduceFunction !== \"function\") {\n throw new TypeError(\"reduction view function must be a function\");\n }\n return new ReductionView(REDUCTION_TOKEN, reduceFunction);\n}\n\nexport function reducedValue(value) {\n if (isReducedValue(value)) {\n return value;\n }\n const result = Object.create(null);\n Object.defineProperty(result, REDUCED_STATE, { value });\n return Object.freeze(result);\n}\n\nexport function isReducedValue(value) {\n return value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n Object.prototype.hasOwnProperty.call(value, REDUCED_STATE);\n}\n\nexport function unreducedValue(value) {\n return isReducedValue(value) ? value[REDUCED_STATE] : value;\n}\n\nexport function reduceIterable(iterable, reducer, ...initial) {\n if (typeof reducer !== \"function\") {\n throw new TypeError(\"collection reducer must be a function\");\n }\n let accumulator = initial.length === 0 ? NO_INITIAL : initial[0];\n for (const value of iterable) {\n if (accumulator === NO_INITIAL) {\n accumulator = value;\n continue;\n }\n accumulator = reducer(accumulator, value);\n if (isReducedValue(accumulator)) {\n return unreducedValue(accumulator);\n }\n }\n if (accumulator === NO_INITIAL) {\n throw new TypeError(\"cannot reduce an empty collection without an initial value\");\n }\n return accumulator;\n}\n\nexport function validateCollectionCount(value) {\n return checkedCount(value);\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.collection
|
|
2
|
+
(js* "import {\n extendProtocolCategory,\n extendProtocolType,\n implementsProtocol,\n} from \"./protocol.mjs\";\nimport {\n COLLECTION_ASSOC,\n COLLECTION_CONJ,\n COLLECTION_COUNT,\n COLLECTION_EMPTY,\n COLLECTION_GET,\n COLLECTION_NTH,\n COLLECTION_PEEK,\n COLLECTION_POP,\n COLLECTION_REDUCE,\n COLLECTION_REDUCE_KV,\n I_COUNTED,\n I_EMPTYABLE,\n I_CONJ,\n I_INDEXED,\n I_LOOKUP,\n I_ASSOCIATIVE,\n I_REDUCE,\n I_KV_REDUCE,\n I_MAP,\n I_SET,\n I_STACK,\n I_REVERSIBLE,\n I_SEQABLE,\n ReductionView as InternalReductionView,\n MemoizedSequenceView as InternalMemoizedSequenceView,\n SequenceView as InternalSequenceView,\n dispatchCollectionCount,\n dispatchCollectionEmpty,\n dispatchCollectionConj,\n dispatchCollectionGet,\n dispatchCollectionAssoc,\n dispatchCollectionContains,\n dispatchCollectionNth,\n dispatchCollectionReduce,\n dispatchCollectionReduceKV,\n dispatchCollectionDissoc,\n dispatchCollectionDisj,\n dispatchCollectionPeek,\n dispatchCollectionPop,\n dispatchCollectionRseq,\n dispatchCollectionSeq,\n isReducedValue,\n readCollectionEntry,\n reduceIterable,\n reducedValue,\n reductionView as createReductionView,\n memoizedSequenceView as createMemoizedSequenceView,\n sequenceView as createSequenceView,\n unboundedSequenceView as createUnboundedSequenceView,\n unreducedValue,\n validateCollectionCount,\n} from \"./collection-internals.mjs\";\nimport { isPersistentList } from \"./list.mjs\";\nimport { isPersistentQueue } from \"./queue.mjs\";\nimport { isRecord } from \"./record.mjs\";\nimport { isPersistentMapValue, isPersistentSetValue } from \"./persistent-kind.mjs\";\nimport { EMPTY_SET } from \"./set.mjs\";\nimport { isPersistentVector } from \"./vector.mjs\";\n\nconst MISSING = Symbol(\"eliscript.collection.missing\");\n\nfunction indexedValue(values, index, notFound = MISSING) {\n if (Number.isInteger(index) && index >= 0 && index < values.length) {\n return values[index];\n }\n if (notFound !== MISSING) {\n return notFound;\n }\n throw new RangeError(`nth index ${String(index)} is outside collection bounds`);\n}\n\nfunction indexedAssoc(values, index, value) {\n if (!Number.isInteger(index) || index < 0 || index > values.length) {\n throw new RangeError(\n `assoc index ${String(index)} is outside collection bounds`,\n );\n }\n const result = values.slice();\n result[index] = value;\n return result;\n}\n\nfunction indexedContains(values, index) {\n return Number.isInteger(index) && index >= 0 && index < values.length;\n}\n\nfunction mapConj(values, entry) {\n const [key, value] = readCollectionEntry(entry);\n const result = new Map(values);\n result.set(key, value);\n return result;\n}\n\nfunction mapAssoc(values, key, value) {\n const result = new Map(values);\n result.set(key, value);\n return result;\n}\n\nfunction mapDissoc(values, key) {\n const result = new Map(values);\n result.delete(key);\n return result;\n}\n\nfunction setConj(values, value) {\n const result = new Set(values);\n result.add(value);\n return result;\n}\n\nfunction setDisj(values, value) {\n const result = new Set(values);\n result.delete(value);\n return result;\n}\n\nfunction objectAssoc(values, key, value) {\n if (typeof key !== \"string\") {\n throw new TypeError(\"plain object association keys must be strings\");\n }\n return { ...values, [key]: value };\n}\n\nfunction objectConj(values, entry) {\n const [key, value] = readCollectionEntry(entry);\n return objectAssoc(values, key, value);\n}\n\nfunction objectDissoc(values, key) {\n if (typeof key !== \"string\") {\n throw new TypeError(\"plain object dissociation keys must be strings\");\n }\n const result = { ...values };\n delete result[key];\n return result;\n}\n\nfunction arrayPeek(values) {\n return values.length === 0 ? null : values[values.length - 1];\n}\n\nfunction arrayPop(values) {\n if (values.length === 0) {\n throw new RangeError(\"cannot pop an empty array\");\n }\n return values.slice(0, -1);\n}\n\nfunction indexedReverseSequence(values) {\n return values.length === 0\n ? null\n : createSequenceView(\n () => {\n let index = values.length;\n return {\n next() {\n if (index === 0) return { value: undefined, done: true };\n index -= 1;\n return { value: values[index], done: false };\n },\n };\n },\n () => values.length,\n );\n}\n\nfunction arraySequence(values) {\n return values.length === 0\n ? null\n : createSequenceView(() => values[Symbol.iterator](), () => values.length);\n}\n\nfunction mapSequence(values) {\n if (values.size === 0) {\n return null;\n }\n return createSequenceView(\n () => (function* entries() {\n for (const entry of values) {\n yield Object.freeze([entry[0], entry[1]]);\n }\n })(),\n () => values.size,\n );\n}\n\nfunction setSequence(values) {\n return values.size === 0\n ? null\n : createSequenceView(() => values[Symbol.iterator](), () => values.size);\n}\n\nfunction stringSequence(value) {\n return value.length === 0\n ? null\n : createSequenceView(\n () => (function* codeUnits() {\n for (let index = 0; index < value.length; index += 1) {\n yield value[index];\n }\n })(),\n () => value.length,\n );\n}\n\nfunction objectSequence(value) {\n const keys = Object.keys(value);\n return keys.length === 0\n ? null\n : createSequenceView(\n () => (function* entries() {\n for (const key of Object.keys(value)) {\n yield Object.freeze([key, value[key]]);\n }\n })(),\n () => Object.keys(value).length,\n );\n}\n\nfunction reduceIndexedValues(values, reducer, initial) {\n let result = initial;\n for (let index = 0; index < values.length; index += 1) {\n result = reducer(result, index, values[index]);\n if (isReducedValue(result)) return unreducedValue(result);\n }\n return result;\n}\n\nfunction reduceMapValues(values, reducer, initial) {\n let result = initial;\n for (const [key, value] of values) {\n result = reducer(result, key, value);\n if (isReducedValue(result)) return unreducedValue(result);\n }\n return result;\n}\n\nfunction reduceObjectValues(value, reducer, initial) {\n let result = initial;\n for (const key of Object.keys(value)) {\n result = reducer(result, key, value[key]);\n if (isReducedValue(result)) return unreducedValue(result);\n }\n return result;\n}\n\nextendProtocolCategory(I_COUNTED, \"string\", {\n count: (value) => value.length,\n});\nextendProtocolCategory(I_EMPTYABLE, \"string\", { empty: () => \"\" });\nextendProtocolCategory(I_LOOKUP, \"string\", {\n get: (value, index, notFound = null) => indexedValue(value, index, notFound),\n});\nextendProtocolCategory(I_INDEXED, \"string\", { nth: indexedValue });\nextendProtocolCategory(I_SEQABLE, \"string\", { seq: stringSequence });\nextendProtocolCategory(I_REDUCE, \"string\", {\n reduce: (value, reducer, ...initial) =>\n reduceIterable(stringSequence(value) ?? [], reducer, ...initial),\n});\nextendProtocolCategory(I_REVERSIBLE, \"string\", {\n rseq: indexedReverseSequence,\n});\n\nextendProtocolType(I_COUNTED, Object, {\n count: (value) => Object.keys(value).length,\n});\nextendProtocolType(I_EMPTYABLE, Object, { empty: () => ({}) });\nextendProtocolType(I_CONJ, Object, { conj: objectConj });\nextendProtocolType(I_LOOKUP, Object, {\n get: (value, key, notFound = null) =>\n typeof key === \"string\" && Object.hasOwn(value, key)\n ? value[key]\n : notFound,\n});\nextendProtocolType(I_ASSOCIATIVE, Object, {\n assoc: objectAssoc,\n contains: (value, key) =>\n typeof key === \"string\" && Object.hasOwn(value, key),\n});\nextendProtocolType(I_SEQABLE, Object, { seq: objectSequence });\nextendProtocolType(I_REDUCE, Object, {\n reduce: (value, reducer, ...initial) =>\n reduceIterable(objectSequence(value) ?? [], reducer, ...initial),\n});\nextendProtocolType(I_KV_REDUCE, Object, { reduceKV: reduceObjectValues });\nextendProtocolType(I_MAP, Object, { dissoc: objectDissoc });\n\nextendProtocolType(I_COUNTED, Array, { count: (values) => values.length });\nextendProtocolType(I_EMPTYABLE, Array, { empty: () => [] });\nextendProtocolType(I_CONJ, Array, {\n conj: (values, value) => [...values, value],\n});\nextendProtocolType(I_LOOKUP, Array, {\n get: (values, index, notFound = null) => indexedValue(values, index, notFound),\n});\nextendProtocolType(I_ASSOCIATIVE, Array, {\n assoc: indexedAssoc,\n contains: indexedContains,\n});\nextendProtocolType(I_INDEXED, Array, { nth: indexedValue });\nextendProtocolType(I_SEQABLE, Array, { seq: arraySequence });\nextendProtocolType(I_REDUCE, Array, { reduce: reduceIterable });\nextendProtocolType(I_KV_REDUCE, Array, { reduceKV: reduceIndexedValues });\nextendProtocolType(I_STACK, Array, { peek: arrayPeek, pop: arrayPop });\nextendProtocolType(I_REVERSIBLE, Array, { rseq: indexedReverseSequence });\n\nextendProtocolType(I_COUNTED, Map, { count: (values) => values.size });\nextendProtocolType(I_EMPTYABLE, Map, { empty: () => new Map() });\nextendProtocolType(I_CONJ, Map, { conj: mapConj });\nextendProtocolType(I_LOOKUP, Map, {\n get: (values, key, notFound = null) =>\n values.has(key) ? values.get(key) : notFound,\n});\nextendProtocolType(I_ASSOCIATIVE, Map, {\n assoc: mapAssoc,\n contains: (values, key) => values.has(key),\n});\nextendProtocolType(I_SEQABLE, Map, { seq: mapSequence });\nextendProtocolType(I_REDUCE, Map, {\n reduce: (values, reducer, ...initial) =>\n reduceIterable(mapSequence(values) ?? [], reducer, ...initial),\n});\nextendProtocolType(I_KV_REDUCE, Map, { reduceKV: reduceMapValues });\nextendProtocolType(I_MAP, Map, { dissoc: mapDissoc });\n\nextendProtocolType(I_COUNTED, Set, { count: (values) => values.size });\nextendProtocolType(I_EMPTYABLE, Set, { empty: () => new Set() });\nextendProtocolType(I_CONJ, Set, { conj: setConj });\nextendProtocolType(I_LOOKUP, Set, {\n get: (values, key, notFound = null) => values.has(key) ? key : notFound,\n});\nextendProtocolType(I_ASSOCIATIVE, Set, {\n contains: (values, key) => values.has(key),\n});\nextendProtocolType(I_SEQABLE, Set, { seq: setSequence });\nextendProtocolType(I_REDUCE, Set, { reduce: reduceIterable });\nextendProtocolType(I_SET, Set, { disj: setDisj });\n\nextendProtocolCategory(I_COUNTED, \"null\", { count: () => 0 });\nextendProtocolCategory(I_EMPTYABLE, \"null\", { empty: () => null });\nextendProtocolCategory(I_SEQABLE, \"null\", { seq: () => null });\nextendProtocolCategory(I_REDUCE, \"null\", {\n reduce: (_value, reducer, ...initial) => reduceIterable([], reducer, ...initial),\n});\nextendProtocolCategory(I_KV_REDUCE, \"null\", {\n reduceKV: (_value, _reducer, initial) => initial,\n});\nextendProtocolCategory(I_MAP, \"null\", { dissoc: () => null });\nextendProtocolCategory(I_SET, \"null\", { disj: () => null });\nextendProtocolCategory(I_STACK, \"null\", { peek: () => null, pop: () => null });\nextendProtocolCategory(I_REVERSIBLE, \"null\", { rseq: () => null });\n\nexport const ICounted = I_COUNTED;\nexport const IEmptyable = I_EMPTYABLE;\nexport const IConj = I_CONJ;\nexport const ILookup = I_LOOKUP;\nexport const IAssociative = I_ASSOCIATIVE;\nexport const IIndexed = I_INDEXED;\nexport const ISeqable = I_SEQABLE;\nexport const IReduce = I_REDUCE;\nexport const IKVReduce = I_KV_REDUCE;\nexport const IMap = I_MAP;\nexport const ISet = I_SET;\nexport const IStack = I_STACK;\nexport const IReversible = I_REVERSIBLE;\n\nexport const ReductionView = InternalReductionView;\nexport const MemoizedSequenceView = InternalMemoizedSequenceView;\nexport const SequenceView = InternalSequenceView;\n\nexport function reductionView(reduceFunction) {\n return createReductionView(reduceFunction);\n}\n\nexport function memoizedSequenceView(factory, count = null) {\n return createMemoizedSequenceView(factory, count);\n}\n\nexport function sequenceView(factory, count = null) {\n return createSequenceView(factory, count);\n}\n\nexport function unboundedSequenceView(factory) {\n return createUnboundedSequenceView(factory);\n}\n\nexport function count(collection) {\n if (collection !== null && collection !== undefined) {\n const direct = collection[COLLECTION_COUNT];\n if (typeof direct === \"function\") {\n return validateCollectionCount(direct.call(collection));\n }\n }\n return validateCollectionCount(dispatchCollectionCount(collection));\n}\n\nexport function isCounted(collection) {\n return implementsProtocol(ICounted, collection);\n}\n\nexport function isIndexed(collection) {\n return implementsProtocol(IIndexed, collection);\n}\n\nexport function isSeqable(collection) {\n return implementsProtocol(ISeqable, collection);\n}\n\nexport function isReducible(collection) {\n return implementsProtocol(IReduce, collection);\n}\n\nexport function isReversible(collection) {\n return implementsProtocol(IReversible, collection);\n}\n\nexport function isAssociative(collection) {\n return implementsProtocol(IAssociative, collection);\n}\n\nexport function isCollection(value) {\n return value instanceof InternalSequenceView ||\n value instanceof InternalMemoizedSequenceView ||\n isPersistentList(value) ||\n isPersistentQueue(value) ||\n isPersistentVector(value) ||\n isPersistentMapValue(value) ||\n isRecord(value) ||\n isPersistentSetValue(value);\n}\n\nexport function isList(value) {\n return isPersistentList(value);\n}\n\nexport function isVector(value) {\n return isPersistentVector(value);\n}\n\nexport function isQueue(value) {\n return isPersistentQueue(value);\n}\n\nexport function isMap(value) {\n return isPersistentMapValue(value) || isRecord(value);\n}\n\nexport function isSet(value) {\n return isPersistentSetValue(value);\n}\n\nexport function isSequential(value) {\n return value instanceof InternalSequenceView ||\n value instanceof InternalMemoizedSequenceView ||\n isPersistentList(value) ||\n isPersistentQueue(value) ||\n isPersistentVector(value);\n}\n\nexport function isSequence(value) {\n return value instanceof InternalSequenceView ||\n value instanceof InternalMemoizedSequenceView ||\n isPersistentList(value);\n}\n\nexport function boundedCount(limit, collection) {\n if (!Number.isSafeInteger(limit) || limit < 0) {\n throw new TypeError(\"boundedCount limit must be a non-negative safe integer\");\n }\n if (limit === 0) return 0;\n\n const sequence = seq(collection);\n if (sequence === null) return 0;\n const iterator = sequence[Symbol.iterator]();\n let result = 0;\n let complete = false;\n try {\n while (result < limit && !iterator.next().done) {\n result += 1;\n }\n complete = true;\n } finally {\n if (\n (!complete || result === limit) &&\n typeof iterator.return === \"function\"\n ) {\n iterator.return();\n }\n }\n return result;\n}\n\nexport function areDistinct(...values) {\n let seen = EMPTY_SET;\n for (const value of values) {\n if (seen.has(value)) return false;\n seen = seen.conj(value);\n }\n return true;\n}\n\nexport function empty(collection) {\n if (collection !== null && collection !== undefined) {\n const direct = collection[COLLECTION_EMPTY];\n if (typeof direct === \"function\") {\n return direct.call(collection);\n }\n }\n return dispatchCollectionEmpty(collection);\n}\n\nexport function conj(collection, value) {\n const argCount = arguments.length;\n if (argCount <= 1) return collection;\n if (argCount === 2) {\n if (collection !== null && collection !== undefined) {\n const direct = collection[COLLECTION_CONJ];\n if (typeof direct === \"function\") {\n return direct.call(collection, value);\n }\n }\n return dispatchCollectionConj(collection, value);\n }\n let result = collection;\n for (let index = 1; index < argCount; index += 1) {\n const nextValue = arguments[index];\n if (result !== null && result !== undefined) {\n const direct = result[COLLECTION_CONJ];\n if (typeof direct === \"function\") {\n result = direct.call(result, nextValue);\n continue;\n }\n }\n result = dispatchCollectionConj(result, nextValue);\n }\n return result;\n}\n\nexport function get(collection, key, notFound = null) {\n if (collection !== null && collection !== undefined) {\n const direct = collection[COLLECTION_GET];\n if (typeof direct === \"function\") {\n return direct.call(collection, key, notFound);\n }\n }\n return dispatchCollectionGet(collection, key, notFound);\n}\n\nexport function assoc(collection, key, value, ...keyValues) {\n if (arguments.length < 3 || keyValues.length % 2 !== 0) {\n throw new TypeError(\n \"assoc requires a collection followed by one or more key/value pairs\",\n );\n }\n let result;\n if (collection !== null && collection !== undefined && typeof collection[COLLECTION_ASSOC] === \"function\") {\n result = collection[COLLECTION_ASSOC](key, value);\n } else {\n result = dispatchCollectionAssoc(collection, key, value);\n }\n for (let index = 0; index < keyValues.length; index += 2) {\n if (result !== null && result !== undefined && typeof result[COLLECTION_ASSOC] === \"function\") {\n result = result[COLLECTION_ASSOC](keyValues[index], keyValues[index + 1]);\n } else {\n result = dispatchCollectionAssoc(\n result,\n keyValues[index],\n keyValues[index + 1],\n );\n }\n }\n return result;\n}\n\nexport function contains(collection, key) {\n const result = dispatchCollectionContains(collection, key);\n if (typeof result !== \"boolean\") {\n throw new TypeError(\"IAssociative/contains must return a boolean\");\n }\n return result;\n}\n\nexport function nth(collection, index, notFound) {\n const hasNotFound = arguments.length >= 3;\n if (collection !== null && collection !== undefined) {\n const direct = collection[COLLECTION_NTH];\n if (typeof direct === \"function\") {\n return hasNotFound\n ? direct.call(collection, index, notFound)\n : direct.call(collection, index);\n }\n }\n return hasNotFound\n ? dispatchCollectionNth(collection, index, notFound)\n : dispatchCollectionNth(collection, index);\n}\n\nexport function seq(collection) {\n const result = dispatchCollectionSeq(collection);\n if (result === null) {\n return null;\n }\n if (result === undefined || typeof result[Symbol.iterator] !== \"function\") {\n throw new TypeError(\"ISeqable/seq must return null or an iterable sequence view\");\n }\n return result;\n}\n\nexport function isEmpty(collection) {\n return seq(collection) === null;\n}\n\nexport function notEmpty(collection) {\n return isEmpty(collection) ? null : collection;\n}\n\nexport function reduce(collection, reducer, initial) {\n if (typeof reducer !== \"function\") {\n throw new TypeError(\"collection reducer must be a function\");\n }\n const hasInitial = arguments.length >= 3;\n if (collection !== null && collection !== undefined) {\n const direct = collection[COLLECTION_REDUCE];\n if (typeof direct === \"function\") {\n return unreducedValue(\n hasInitial\n ? direct.call(collection, reducer, initial)\n : direct.call(collection, reducer),\n );\n }\n }\n return unreducedValue(\n hasInitial\n ? dispatchCollectionReduce(collection, reducer, initial)\n : dispatchCollectionReduce(collection, reducer),\n );\n}\n\nexport function reduceKV(collection, reducer, initial) {\n if (arguments.length !== 3) {\n throw new TypeError(\"reduceKV requires a collection, reducer, and initial value\");\n }\n if (typeof reducer !== \"function\") {\n throw new TypeError(\"key/value reducer must be a function\");\n }\n if (collection !== null && collection !== undefined) {\n const direct = collection[COLLECTION_REDUCE_KV];\n if (typeof direct === \"function\") {\n return unreducedValue(direct.call(collection, reducer, initial));\n }\n }\n return unreducedValue(dispatchCollectionReduceKV(collection, reducer, initial));\n}\n\nexport function dissoc(collection, ...keys) {\n let result = collection;\n for (const key of keys) {\n result = dispatchCollectionDissoc(result, key);\n }\n return result;\n}\n\nexport function disj(collection, ...values) {\n let result = collection;\n for (const value of values) {\n result = dispatchCollectionDisj(result, value);\n }\n return result;\n}\n\nexport function peek(collection) {\n if (arguments.length !== 1) {\n throw new TypeError(\"peek requires exactly one collection\");\n }\n return dispatchCollectionPeek(collection);\n}\n\nexport function pop(collection) {\n if (arguments.length !== 1) {\n throw new TypeError(\"pop requires exactly one collection\");\n }\n return dispatchCollectionPop(collection);\n}\n\nexport function rseq(collection) {\n if (arguments.length !== 1) {\n throw new TypeError(\"rseq requires exactly one collection\");\n }\n const result = dispatchCollectionRseq(collection);\n if (result === null) {\n return null;\n }\n if (result === undefined || typeof result[Symbol.iterator] !== \"function\") {\n throw new TypeError(\n \"IReversible/rseq must return null or an iterable sequence view\",\n );\n }\n return result;\n}\n\nexport function reduced(value) {\n return reducedValue(value);\n}\n\nexport function isReduced(value) {\n return isReducedValue(value);\n}\n\nexport function unreduced(value) {\n return unreducedValue(value);\n}\n\nexport function isSequenceView(value) {\n return value instanceof InternalSequenceView ||\n value instanceof InternalMemoizedSequenceView;\n}\n\nexport function isReductionView(value) {\n return value instanceof InternalReductionView;\n}\n"))
|
|
@@ -4,6 +4,16 @@ import {
|
|
|
4
4
|
implementsProtocol,
|
|
5
5
|
} from "./protocol.mjs";
|
|
6
6
|
import {
|
|
7
|
+
COLLECTION_ASSOC,
|
|
8
|
+
COLLECTION_CONJ,
|
|
9
|
+
COLLECTION_COUNT,
|
|
10
|
+
COLLECTION_EMPTY,
|
|
11
|
+
COLLECTION_GET,
|
|
12
|
+
COLLECTION_NTH,
|
|
13
|
+
COLLECTION_PEEK,
|
|
14
|
+
COLLECTION_POP,
|
|
15
|
+
COLLECTION_REDUCE,
|
|
16
|
+
COLLECTION_REDUCE_KV,
|
|
7
17
|
I_COUNTED,
|
|
8
18
|
I_EMPTYABLE,
|
|
9
19
|
I_CONJ,
|
|
@@ -382,6 +392,12 @@ export function unboundedSequenceView(factory) {
|
|
|
382
392
|
}
|
|
383
393
|
|
|
384
394
|
export function count(collection) {
|
|
395
|
+
if (collection !== null && collection !== undefined) {
|
|
396
|
+
const direct = collection[COLLECTION_COUNT];
|
|
397
|
+
if (typeof direct === "function") {
|
|
398
|
+
return validateCollectionCount(direct.call(collection));
|
|
399
|
+
}
|
|
400
|
+
}
|
|
385
401
|
return validateCollectionCount(dispatchCollectionCount(collection));
|
|
386
402
|
}
|
|
387
403
|
|
|
@@ -491,18 +507,49 @@ export function areDistinct(...values) {
|
|
|
491
507
|
}
|
|
492
508
|
|
|
493
509
|
export function empty(collection) {
|
|
510
|
+
if (collection !== null && collection !== undefined) {
|
|
511
|
+
const direct = collection[COLLECTION_EMPTY];
|
|
512
|
+
if (typeof direct === "function") {
|
|
513
|
+
return direct.call(collection);
|
|
514
|
+
}
|
|
515
|
+
}
|
|
494
516
|
return dispatchCollectionEmpty(collection);
|
|
495
517
|
}
|
|
496
518
|
|
|
497
|
-
export function conj(collection,
|
|
519
|
+
export function conj(collection, value) {
|
|
520
|
+
const argCount = arguments.length;
|
|
521
|
+
if (argCount <= 1) return collection;
|
|
522
|
+
if (argCount === 2) {
|
|
523
|
+
if (collection !== null && collection !== undefined) {
|
|
524
|
+
const direct = collection[COLLECTION_CONJ];
|
|
525
|
+
if (typeof direct === "function") {
|
|
526
|
+
return direct.call(collection, value);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
return dispatchCollectionConj(collection, value);
|
|
530
|
+
}
|
|
498
531
|
let result = collection;
|
|
499
|
-
for (
|
|
500
|
-
|
|
532
|
+
for (let index = 1; index < argCount; index += 1) {
|
|
533
|
+
const nextValue = arguments[index];
|
|
534
|
+
if (result !== null && result !== undefined) {
|
|
535
|
+
const direct = result[COLLECTION_CONJ];
|
|
536
|
+
if (typeof direct === "function") {
|
|
537
|
+
result = direct.call(result, nextValue);
|
|
538
|
+
continue;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
result = dispatchCollectionConj(result, nextValue);
|
|
501
542
|
}
|
|
502
543
|
return result;
|
|
503
544
|
}
|
|
504
545
|
|
|
505
546
|
export function get(collection, key, notFound = null) {
|
|
547
|
+
if (collection !== null && collection !== undefined) {
|
|
548
|
+
const direct = collection[COLLECTION_GET];
|
|
549
|
+
if (typeof direct === "function") {
|
|
550
|
+
return direct.call(collection, key, notFound);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
506
553
|
return dispatchCollectionGet(collection, key, notFound);
|
|
507
554
|
}
|
|
508
555
|
|
|
@@ -512,13 +559,22 @@ export function assoc(collection, key, value, ...keyValues) {
|
|
|
512
559
|
"assoc requires a collection followed by one or more key/value pairs",
|
|
513
560
|
);
|
|
514
561
|
}
|
|
515
|
-
let result
|
|
562
|
+
let result;
|
|
563
|
+
if (collection !== null && collection !== undefined && typeof collection[COLLECTION_ASSOC] === "function") {
|
|
564
|
+
result = collection[COLLECTION_ASSOC](key, value);
|
|
565
|
+
} else {
|
|
566
|
+
result = dispatchCollectionAssoc(collection, key, value);
|
|
567
|
+
}
|
|
516
568
|
for (let index = 0; index < keyValues.length; index += 2) {
|
|
517
|
-
result
|
|
518
|
-
result,
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
569
|
+
if (result !== null && result !== undefined && typeof result[COLLECTION_ASSOC] === "function") {
|
|
570
|
+
result = result[COLLECTION_ASSOC](keyValues[index], keyValues[index + 1]);
|
|
571
|
+
} else {
|
|
572
|
+
result = dispatchCollectionAssoc(
|
|
573
|
+
result,
|
|
574
|
+
keyValues[index],
|
|
575
|
+
keyValues[index + 1],
|
|
576
|
+
);
|
|
577
|
+
}
|
|
522
578
|
}
|
|
523
579
|
return result;
|
|
524
580
|
}
|
|
@@ -531,10 +587,19 @@ export function contains(collection, key) {
|
|
|
531
587
|
return result;
|
|
532
588
|
}
|
|
533
589
|
|
|
534
|
-
export function nth(collection, index,
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
590
|
+
export function nth(collection, index, notFound) {
|
|
591
|
+
const hasNotFound = arguments.length >= 3;
|
|
592
|
+
if (collection !== null && collection !== undefined) {
|
|
593
|
+
const direct = collection[COLLECTION_NTH];
|
|
594
|
+
if (typeof direct === "function") {
|
|
595
|
+
return hasNotFound
|
|
596
|
+
? direct.call(collection, index, notFound)
|
|
597
|
+
: direct.call(collection, index);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
return hasNotFound
|
|
601
|
+
? dispatchCollectionNth(collection, index, notFound)
|
|
602
|
+
: dispatchCollectionNth(collection, index);
|
|
538
603
|
}
|
|
539
604
|
|
|
540
605
|
export function seq(collection) {
|
|
@@ -556,14 +621,25 @@ export function notEmpty(collection) {
|
|
|
556
621
|
return isEmpty(collection) ? null : collection;
|
|
557
622
|
}
|
|
558
623
|
|
|
559
|
-
export function reduce(collection, reducer,
|
|
624
|
+
export function reduce(collection, reducer, initial) {
|
|
560
625
|
if (typeof reducer !== "function") {
|
|
561
626
|
throw new TypeError("collection reducer must be a function");
|
|
562
627
|
}
|
|
628
|
+
const hasInitial = arguments.length >= 3;
|
|
629
|
+
if (collection !== null && collection !== undefined) {
|
|
630
|
+
const direct = collection[COLLECTION_REDUCE];
|
|
631
|
+
if (typeof direct === "function") {
|
|
632
|
+
return unreducedValue(
|
|
633
|
+
hasInitial
|
|
634
|
+
? direct.call(collection, reducer, initial)
|
|
635
|
+
: direct.call(collection, reducer),
|
|
636
|
+
);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
563
639
|
return unreducedValue(
|
|
564
|
-
|
|
565
|
-
? dispatchCollectionReduce(collection, reducer)
|
|
566
|
-
: dispatchCollectionReduce(collection, reducer
|
|
640
|
+
hasInitial
|
|
641
|
+
? dispatchCollectionReduce(collection, reducer, initial)
|
|
642
|
+
: dispatchCollectionReduce(collection, reducer),
|
|
567
643
|
);
|
|
568
644
|
}
|
|
569
645
|
|
|
@@ -574,6 +650,12 @@ export function reduceKV(collection, reducer, initial) {
|
|
|
574
650
|
if (typeof reducer !== "function") {
|
|
575
651
|
throw new TypeError("key/value reducer must be a function");
|
|
576
652
|
}
|
|
653
|
+
if (collection !== null && collection !== undefined) {
|
|
654
|
+
const direct = collection[COLLECTION_REDUCE_KV];
|
|
655
|
+
if (typeof direct === "function") {
|
|
656
|
+
return unreducedValue(direct.call(collection, reducer, initial));
|
|
657
|
+
}
|
|
658
|
+
}
|
|
577
659
|
return unreducedValue(dispatchCollectionReduceKV(collection, reducer, initial));
|
|
578
660
|
}
|
|
579
661
|
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.data-text
|
|
2
|
+
(js* "import {\n EliscriptSymbol,\n Keyword,\n eliscriptSymbol,\n identifierName,\n identifierNamespace,\n keyword,\n qualifiedIdentifierName,\n} from \"./identifier.mjs\";\nimport {\n EMPTY_MAP,\n PersistentHashMap,\n isPersistentHashMap,\n} from \"./map.mjs\";\nimport { PersistentList } from \"./list.mjs\";\nimport { meta, withMeta } from \"./metadata.mjs\";\nimport { PersistentQueue, persistentQueue } from \"./queue.mjs\";\nimport {\n defineProtocol,\n extendProtocolCategory,\n extendProtocolType,\n protocolMethod,\n} from \"./protocol.mjs\";\nimport {\n EMPTY_SET,\n PersistentHashSet,\n} from \"./set.mjs\";\nimport { PersistentSortedMap, PersistentSortedSet } from \"./sorted.mjs\";\nimport {\n assocBang,\n conjBang,\n persistentBang,\n transient,\n} from \"./transient.mjs\";\nimport {\n EMPTY_VECTOR,\n PersistentVector,\n isPersistentVector,\n} from \"./vector.mjs\";\n\nconst DEFAULT_MAX_DEPTH = 256;\nconst DEFAULT_MAX_LENGTH = 16 * 1024 * 1024;\nconst DEFAULT_MAX_VALUES = 1_000_000;\nconst NUMBER_PATTERN = /^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/;\nconst BIGINT_PATTERN = /^-?(?:0|[1-9]\\d*)N$/;\nconst UNSAFE_IDENTIFIER = /[\\s()[\\]{}\"';,@^`~\\\\]/u;\nconst RESERVED_SYMBOLS = new Set([\n \"nil\",\n \"true\",\n \"false\",\n \"undefined\",\n \"##NaN\",\n \"##Inf\",\n \"##-Inf\",\n]);\n\nexport const IPrint = defineProtocol(\"IPrint\", [\"print\"]);\nconst dispatchPrint = protocolMethod(IPrint, \"print\");\n\nfunction positiveIntegerOption(options, name, fallback) {\n const value = options?.[name] ?? fallback;\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new TypeError(`${name} must be a positive safe integer`);\n }\n return value;\n}\n\nfunction normalizeOptions(options) {\n if (options === undefined || options === null) {\n return Object.freeze({\n maxDepth: DEFAULT_MAX_DEPTH,\n maxLength: DEFAULT_MAX_LENGTH,\n maxValues: DEFAULT_MAX_VALUES,\n });\n }\n if (typeof options !== \"object\" || Array.isArray(options)) {\n throw new TypeError(\"data text options must be an object\");\n }\n return Object.freeze({\n maxDepth: positiveIntegerOption(options, \"maxDepth\", DEFAULT_MAX_DEPTH),\n maxLength: positiveIntegerOption(options, \"maxLength\", DEFAULT_MAX_LENGTH),\n maxValues: positiveIntegerOption(options, \"maxValues\", DEFAULT_MAX_VALUES),\n });\n}\n\nfunction compareText(left, right) {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n\nfunction safeIdentifierPart(value) {\n return value.length > 0 && !value.includes(\"/\") &&\n !UNSAFE_IDENTIFIER.test(value);\n}\n\nfunction safeBareIdentifier(value, symbol) {\n const namespace = identifierNamespace(value);\n const name = identifierName(value);\n if (!safeIdentifierPart(name) ||\n (namespace !== null && !safeIdentifierPart(namespace))) {\n return false;\n }\n const qualified = qualifiedIdentifierName(value);\n return !symbol ||\n (!RESERVED_SYMBOLS.has(qualified) &&\n !NUMBER_PATTERN.test(qualified) &&\n !BIGINT_PATTERN.test(qualified) &&\n !qualified.startsWith(\":\") &&\n !qualified.startsWith(\"#\"));\n}\n\nfunction taggedIdentifier(tag, value) {\n const namespace = identifierNamespace(value);\n return `#eliscript/${tag} [${namespace === null\n ? \"nil\"\n : JSON.stringify(namespace)} ${JSON.stringify(identifierName(value))}]`;\n}\n\nfunction printNumber(value) {\n if (Number.isNaN(value)) return \"##NaN\";\n if (value === Number.POSITIVE_INFINITY) return \"##Inf\";\n if (value === Number.NEGATIVE_INFINITY) return \"##-Inf\";\n return Object.is(value, -0) ? \"0\" : String(value);\n}\n\nfunction printKeyword(value) {\n return safeBareIdentifier(value, false)\n ? `:${qualifiedIdentifierName(value)}`\n : taggedIdentifier(\"keyword\", value);\n}\n\nfunction printSymbol(value) {\n return safeBareIdentifier(value, true)\n ? qualifiedIdentifierName(value)\n : taggedIdentifier(\"symbol\", value);\n}\n\nfunction printVector(value, context) {\n return `[${[...value].map((item) => context.print(item)).join(\" \")}]`;\n}\n\nfunction printList(value, context) {\n return `(${[...value].map((item) => context.print(item)).join(\" \")})`;\n}\n\nfunction printMap(value, context) {\n const entries = [...value].map(([key, item]) => ({\n key: context.print(key),\n value: context.print(item),\n }));\n entries.sort((left, right) =>\n compareText(left.key, right.key) || compareText(left.value, right.value));\n return `{${entries.map(({ key, value: item }) => `${key} ${item}`).join(\" \")}}`;\n}\n\nfunction printSet(value, context) {\n const items = [...value].map((item) => context.print(item));\n items.sort(compareText);\n return `#{${items.join(\" \")}}`;\n}\n\nfunction printQueue(value, context) {\n return `#queue [${[...value].map((item) => context.print(item)).join(\" \")}]`;\n}\n\nextendProtocolCategory(IPrint, \"null\", { print: () => \"nil\" });\nextendProtocolCategory(IPrint, \"undefined\", { print: () => \"undefined\" });\nextendProtocolCategory(IPrint, \"boolean\", {\n print: (value) => value ? \"true\" : \"false\",\n});\nextendProtocolCategory(IPrint, \"number\", { print: printNumber });\nextendProtocolCategory(IPrint, \"bigint\", {\n print: (value) => `${value}N`,\n});\nextendProtocolCategory(IPrint, \"string\", {\n print: (value) => JSON.stringify(value),\n});\nextendProtocolType(IPrint, Keyword, { print: printKeyword });\nextendProtocolType(IPrint, EliscriptSymbol, { print: printSymbol });\nextendProtocolType(IPrint, PersistentList, { print: printList });\nextendProtocolType(IPrint, PersistentVector, { print: printVector });\nextendProtocolType(IPrint, PersistentHashMap, { print: printMap });\nextendProtocolType(IPrint, PersistentHashSet, { print: printSet });\nextendProtocolType(IPrint, PersistentSortedMap, { print: printMap });\nextendProtocolType(IPrint, PersistentSortedSet, { print: printSet });\nextendProtocolType(IPrint, PersistentQueue, { print: printQueue });\n\nfunction makePrintContext(options) {\n const state = { values: 0 };\n\n function render(value, depth) {\n if (depth > options.maxDepth) {\n throw new RangeError(`data text exceeds maxDepth ${options.maxDepth}`);\n }\n state.values += 1;\n if (state.values > options.maxValues) {\n throw new RangeError(`data text exceeds maxValues ${options.maxValues}`);\n }\n const context = Object.freeze({\n print: (item) => render(item, depth + 1),\n });\n const body = dispatchPrint(value, context);\n if (typeof body !== \"string\") {\n throw new TypeError(\"IPrint/print must return a string\");\n }\n const metadata = meta(value);\n const result = metadata === null\n ? body\n : `^${render(metadata, depth + 1)} ${body}`;\n if (result.length > options.maxLength) {\n throw new RangeError(`data text exceeds maxLength ${options.maxLength}`);\n }\n return result;\n }\n\n return (value) => render(value, 0);\n}\n\nexport function printValue(value, options = undefined) {\n return makePrintContext(normalizeOptions(options))(value);\n}\n\nexport class DataTextError extends SyntaxError {\n constructor(message, source, position) {\n super(`${message} at ${position.line}:${position.column}`);\n this.name = \"DataTextError\";\n this.code = \"ELI-DATA-TEXT\";\n this.offset = position.index;\n this.line = position.line;\n this.column = position.column;\n this.sourceLength = source.length;\n }\n}\n\nclass Reader {\n constructor(source, options) {\n this.source = source;\n this.options = options;\n this.index = 0;\n this.line = 1;\n this.column = 1;\n this.values = 0;\n }\n\n position() {\n return { index: this.index, line: this.line, column: this.column };\n }\n\n fail(message, position = this.position()) {\n throw new DataTextError(message, this.source, position);\n }\n\n peek(ahead = 0) {\n return this.source[this.index + ahead];\n }\n\n advance() {\n const code = this.source.codePointAt(this.index);\n if (code === undefined) return undefined;\n this.index += code > 0xffff ? 2 : 1;\n if (code === 10) {\n this.line += 1;\n this.column = 1;\n } else {\n this.column += 1;\n }\n return code;\n }\n\n skipIgnored() {\n while (this.index < this.source.length) {\n const character = this.peek();\n if (/\\s/u.test(character) || character === \",\") {\n this.advance();\n } else if (character === \";\") {\n while (this.index < this.source.length && this.peek() !== \"\\n\") {\n this.advance();\n }\n } else {\n return;\n }\n }\n }\n\n delimiter(character) {\n return character === undefined || /[\\s,()[\\]{}\";^]/u.test(character);\n }\n\n token(start) {\n while (!this.delimiter(this.peek())) this.advance();\n const token = this.source.slice(start.index, this.index);\n if (token.length === 0) this.fail(\"expected token\", start);\n return token;\n }\n\n string(start) {\n this.advance();\n let escaped = false;\n while (this.index < this.source.length) {\n const character = this.peek();\n if (!escaped && character === \"\\n\") {\n this.fail(\"newline in string literal\", start);\n }\n this.advance();\n if (!escaped && character === \"\\\"\") {\n const raw = this.source.slice(start.index, this.index);\n try {\n return JSON.parse(raw);\n } catch {\n this.fail(\"invalid string escape\", start);\n }\n }\n escaped = !escaped && character === \"\\\\\";\n if (character !== \"\\\\\") escaped = false;\n }\n this.fail(\"unexpected end of string\", start);\n }\n\n vector(depth, start) {\n this.advance();\n const editable = transient(EMPTY_VECTOR);\n while (true) {\n this.skipIgnored();\n if (this.peek() === \"]\") {\n this.advance();\n return persistentBang(editable);\n }\n if (this.peek() === undefined) {\n this.fail(\"unexpected end of vector\", start);\n }\n conjBang(editable, this.value(depth + 1));\n }\n }\n\n list(depth, start) {\n this.advance();\n const values = [];\n while (true) {\n this.skipIgnored();\n if (this.peek() === \")\") {\n this.advance();\n return PersistentList.from(values);\n }\n if (this.peek() === undefined) {\n this.fail(\"unexpected end of list\", start);\n }\n values.push(this.value(depth + 1));\n }\n }\n\n map(depth, start) {\n this.advance();\n const editable = transient(EMPTY_MAP);\n let seen = EMPTY_MAP;\n while (true) {\n this.skipIgnored();\n if (this.peek() === \"}\") {\n this.advance();\n return persistentBang(editable);\n }\n if (this.peek() === undefined) {\n this.fail(\"unexpected end of map\", start);\n }\n const keyPosition = this.position();\n const key = this.value(depth + 1);\n this.skipIgnored();\n if (this.peek() === \"}\" || this.peek() === undefined) {\n this.fail(\"map requires a value for every key\", keyPosition);\n }\n const item = this.value(depth + 1);\n if (seen.has(key)) this.fail(\"duplicate map key\", keyPosition);\n seen = seen.assoc(key, true);\n assocBang(editable, key, item);\n }\n }\n\n set(depth, start) {\n this.advance();\n const editable = transient(EMPTY_SET);\n let seen = EMPTY_SET;\n while (true) {\n this.skipIgnored();\n if (this.peek() === \"}\") {\n this.advance();\n return persistentBang(editable);\n }\n if (this.peek() === undefined) {\n this.fail(\"unexpected end of set\", start);\n }\n const position = this.position();\n const item = this.value(depth + 1);\n if (seen.has(item)) this.fail(\"duplicate set value\", position);\n seen = seen.conj(item);\n conjBang(editable, item);\n }\n }\n\n taggedIdentifier(tag, depth, start) {\n this.skipIgnored();\n const payload = this.value(depth + 1);\n if (!isPersistentVector(payload) || payload.count !== 2) {\n this.fail(`${tag} tag requires [namespace name]`, start);\n }\n const namespace = payload.nth(0);\n const name = payload.nth(1);\n if ((namespace !== null && typeof namespace !== \"string\") ||\n typeof name !== \"string\") {\n this.fail(`${tag} tag requires a nil/string namespace and string name`, start);\n }\n try {\n return tag === \"keyword\"\n ? keyword(namespace, name)\n : eliscriptSymbol(namespace, name);\n } catch (error) {\n this.fail(error.message, start);\n }\n }\n\n taggedQueue(depth, start) {\n this.skipIgnored();\n const payload = this.value(depth + 1);\n if (!isPersistentVector(payload)) {\n this.fail(\"queue tag requires a vector\", start);\n }\n return persistentQueue(...payload);\n }\n\n dispatch(depth, start) {\n if (this.peek(1) === \"{\") {\n this.advance();\n return this.set(depth, start);\n }\n const token = this.token(start);\n if (token === \"##NaN\") return Number.NaN;\n if (token === \"##Inf\") return Number.POSITIVE_INFINITY;\n if (token === \"##-Inf\") return Number.NEGATIVE_INFINITY;\n if (token === \"#eliscript/keyword\") {\n return this.taggedIdentifier(\"keyword\", depth, start);\n }\n if (token === \"#eliscript/symbol\") {\n return this.taggedIdentifier(\"symbol\", depth, start);\n }\n if (token === \"#queue\") return this.taggedQueue(depth, start);\n this.fail(`unknown dispatch ${token}`, start);\n }\n\n atom(start) {\n const token = this.token(start);\n if (token === \"nil\") return null;\n if (token === \"true\") return true;\n if (token === \"false\") return false;\n if (token === \"undefined\") return undefined;\n if (BIGINT_PATTERN.test(token)) return BigInt(token.slice(0, -1));\n if (NUMBER_PATTERN.test(token)) return Number(token);\n try {\n return token.startsWith(\":\")\n ? keyword(token.slice(1))\n : eliscriptSymbol(token);\n } catch (error) {\n this.fail(error.message, start);\n }\n }\n\n metadata(depth, start) {\n this.advance();\n const metadata = this.value(depth + 1);\n if (!isPersistentHashMap(metadata)) {\n this.fail(\"metadata prefix requires a persistent map\", start);\n }\n const value = this.value(depth + 1);\n try {\n return withMeta(value, metadata);\n } catch (error) {\n this.fail(error.message, start);\n }\n }\n\n value(depth) {\n this.skipIgnored();\n const start = this.position();\n if (depth > this.options.maxDepth) {\n this.fail(`data text exceeds maxDepth ${this.options.maxDepth}`, start);\n }\n this.values += 1;\n if (this.values > this.options.maxValues) {\n this.fail(`data text exceeds maxValues ${this.options.maxValues}`, start);\n }\n const character = this.peek();\n if (character === undefined) this.fail(\"unexpected end of input\", start);\n if (character === \"\\\"\") return this.string(start);\n if (character === \"(\") return this.list(depth, start);\n if (character === \"[\") return this.vector(depth, start);\n if (character === \"{\") return this.map(depth, start);\n if (character === \"#\") return this.dispatch(depth, start);\n if (character === \"^\") return this.metadata(depth, start);\n if (\"]})\".includes(character)) {\n this.fail(`unexpected closing delimiter ${character}`, start);\n }\n return this.atom(start);\n }\n}\n\nfunction makeReader(source, options) {\n if (typeof source !== \"string\") {\n throw new TypeError(\"data text source must be a string\");\n }\n const normalized = normalizeOptions(options);\n if (source.length > normalized.maxLength) {\n throw new RangeError(`data text exceeds maxLength ${normalized.maxLength}`);\n }\n return new Reader(source, normalized);\n}\n\nexport function readValue(source, options = undefined) {\n const reader = makeReader(source, options);\n const value = reader.value(0);\n reader.skipIgnored();\n if (reader.index !== source.length) {\n reader.fail(\"trailing data after value\");\n }\n return value;\n}\n\nexport function readValues(source, options = undefined) {\n const reader = makeReader(source, options);\n const values = [];\n reader.skipIgnored();\n while (reader.index < source.length) {\n values.push(reader.value(0));\n reader.skipIgnored();\n }\n return Object.freeze(values);\n}\n"))
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(module capsules.runtime.core.data
|
|
2
|
+
(js* "import {\n assoc,\n contains,\n count,\n get,\n IIndexed,\n IKVReduce,\n nth,\n reduce,\n reduceKV,\n} from \"./collection.mjs\";\nimport { implementsProtocolOperation } from \"./protocol.mjs\";\nimport {\n EMPTY_MAP,\n} from \"./map.mjs\";\nimport {\n assocBang,\n conjBang,\n persistentBang,\n transient,\n} from \"./transient.mjs\";\nimport { into } from \"./transducer.mjs\";\nimport { EMPTY_VECTOR, PersistentVector } from \"./vector.mjs\";\n\nconst MISSING = Symbol(\"eliscript.data.missing\");\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 pathVector(path) {\n return into(EMPTY_VECTOR, path);\n}\n\nfunction readEntry(entry) {\n if (count(entry) !== 2) {\n throw new TypeError(\"data entries must contain exactly one key/value pair\");\n }\n return [nth(entry, 0), nth(entry, 1)];\n}\n\nfunction reduceEntries(collection, reducer, initial) {\n if (implementsProtocolOperation(IKVReduce, \"reduceKV\", collection) &&\n !implementsProtocolOperation(IIndexed, \"nth\", collection)) {\n return reduceKV(collection, reducer, initial);\n }\n return reduce(collection, (result, entry) => {\n const [key, value] = readEntry(entry);\n return reducer(result, key, value);\n }, initial);\n}\n\nfunction collectBuckets(keyFunction, collection, createBucket, updateBucket) {\n requireFunction(keyFunction, \"data key function\");\n const bucketIndex = transient(EMPTY_MAP);\n const keys = [];\n const buckets = [];\n reduce(collection, (result, value) => {\n const key = keyFunction(value);\n let index = bucketIndex.get(key, MISSING);\n if (index === MISSING) {\n index = keys.length;\n assocBang(bucketIndex, key, index);\n keys.push(key);\n buckets.push(createBucket(value));\n } else {\n updateBucket(buckets, index, value);\n }\n return result;\n }, null);\n return { keys, buckets };\n}\n\nfunction persistentMapFromBuckets(keys, buckets, finishBucket) {\n const result = transient(EMPTY_MAP);\n for (let index = 0; index < keys.length; index += 1) {\n assocBang(result, keys[index], finishBucket(buckets[index]));\n }\n return persistentBang(result);\n}\n\nexport function indexBy(keyFunction, collection) {\n requireFunction(keyFunction, \"indexBy key function\");\n const result = transient(EMPTY_MAP);\n reduce(collection, (builder, value) => {\n assocBang(builder, keyFunction(value), value);\n return builder;\n }, result);\n return persistentBang(result);\n}\n\nexport function groupBy(keyFunction, collection) {\n const { keys, buckets } = collectBuckets(\n keyFunction,\n collection,\n (value) => [value],\n (values, index, value) => {\n values[index].push(value);\n },\n );\n return persistentMapFromBuckets(\n keys,\n buckets,\n (bucket) => PersistentVector.from(bucket),\n );\n}\n\nexport function countBy(keyFunction, collection) {\n const { keys, buckets } = collectBuckets(\n keyFunction,\n collection,\n () => 1,\n (counts, index) => {\n counts[index] += 1;\n },\n );\n return persistentMapFromBuckets(keys, buckets, (count) => count);\n}\n\nexport function frequencies(collection) {\n return countBy((value) => value, collection);\n}\n\nexport function getIn(collection, path, notFound = null) {\n const keys = pathVector(path);\n let current = collection;\n for (let index = 0; index < count(keys); index += 1) {\n if (current == null) return notFound;\n current = get(current, nth(keys, index), MISSING);\n if (current === MISSING) return notFound;\n }\n return current;\n}\n\nexport function assocIn(collection, path, value) {\n const keys = pathVector(path);\n const size = count(keys);\n if (size === 0) return value;\n\n const parents = [];\n let current = collection;\n for (let index = 0; index < size - 1; index += 1) {\n parents.push(current);\n if (current == null) {\n current = EMPTY_MAP;\n continue;\n }\n const child = get(current, nth(keys, index), MISSING);\n current = child === MISSING || child == null ? EMPTY_MAP : child;\n }\n\n let result = assoc(\n current == null ? EMPTY_MAP : current,\n nth(keys, size - 1),\n value,\n );\n for (let index = size - 2; index >= 0; index -= 1) {\n const parent = parents[index];\n result = assoc(\n parent == null ? EMPTY_MAP : parent,\n nth(keys, index),\n result,\n );\n }\n return result;\n}\n\nexport function update(collection, key, transform, ...arguments_) {\n requireFunction(transform, \"update transform\");\n const target = collection == null ? EMPTY_MAP : collection;\n return assoc(target, key, transform(get(target, key), ...arguments_));\n}\n\nexport function updateIn(collection, path, transform, ...arguments_) {\n requireFunction(transform, \"updateIn transform\");\n return assocIn(\n collection,\n path,\n transform(getIn(collection, path), ...arguments_),\n );\n}\n\nexport function keys(collection) {\n const result = transient(EMPTY_VECTOR);\n reduceKV(collection, (builder, key) => {\n conjBang(builder, key);\n return builder;\n }, result);\n return persistentBang(result);\n}\n\nexport function vals(collection) {\n const result = transient(EMPTY_VECTOR);\n reduceKV(collection, (builder, _key, value) => {\n conjBang(builder, value);\n return builder;\n }, result);\n return persistentBang(result);\n}\n\nexport function updateKeys(collection, transform) {\n requireFunction(transform, \"updateKeys transform\");\n const result = transient(EMPTY_MAP);\n reduceKV(collection, (builder, key, value) => {\n assocBang(builder, transform(key), value);\n return builder;\n }, result);\n return persistentBang(result);\n}\n\nexport function updateVals(collection, transform) {\n requireFunction(transform, \"updateVals transform\");\n const result = transient(EMPTY_MAP);\n reduceKV(collection, (builder, key, value) => {\n assocBang(builder, key, transform(value));\n return builder;\n }, result);\n return persistentBang(result);\n}\n\nexport function selectKeys(collection, keys) {\n const result = transient(EMPTY_MAP);\n reduce(keys, (builder, key) => {\n if (collection != null && contains(collection, key)) {\n assocBang(builder, key, get(collection, key));\n }\n return builder;\n }, result);\n return persistentBang(result);\n}\n\nexport function merge(...collections) {\n const result = transient(EMPTY_MAP);\n for (const collection of collections) {\n reduceEntries(collection, (builder, key, value) => {\n assocBang(builder, key, value);\n return builder;\n }, result);\n }\n return persistentBang(result);\n}\n\nexport function mergeWith(combine, ...collections) {\n requireFunction(combine, \"mergeWith combine function\");\n let result = EMPTY_MAP;\n for (const collection of collections) {\n result = reduceEntries(collection, (current, key, value) => {\n return assoc(\n current,\n key,\n contains(current, key) ? combine(get(current, key), value) : value,\n );\n }, result);\n }\n return result;\n}\n\nexport function zipmap(keys, values) {\n const keyVector = pathVector(keys);\n const valueVector = pathVector(values);\n const size = Math.min(count(keyVector), count(valueVector));\n const result = transient(EMPTY_MAP);\n for (let index = 0; index < size; index += 1) {\n assocBang(result, nth(keyVector, index), nth(valueVector, index));\n }\n return persistentBang(result);\n}\n"))
|
package/runtime/core/data.mjs
CHANGED
|
@@ -20,7 +20,7 @@ import {
|
|
|
20
20
|
transient,
|
|
21
21
|
} from "./transient.mjs";
|
|
22
22
|
import { into } from "./transducer.mjs";
|
|
23
|
-
import { EMPTY_VECTOR } from "./vector.mjs";
|
|
23
|
+
import { EMPTY_VECTOR, PersistentVector } from "./vector.mjs";
|
|
24
24
|
|
|
25
25
|
const MISSING = Symbol("eliscript.data.missing");
|
|
26
26
|
|
|
@@ -55,7 +55,7 @@ function reduceEntries(collection, reducer, initial) {
|
|
|
55
55
|
|
|
56
56
|
function collectBuckets(keyFunction, collection, createBucket, updateBucket) {
|
|
57
57
|
requireFunction(keyFunction, "data key function");
|
|
58
|
-
|
|
58
|
+
const bucketIndex = transient(EMPTY_MAP);
|
|
59
59
|
const keys = [];
|
|
60
60
|
const buckets = [];
|
|
61
61
|
reduce(collection, (result, value) => {
|
|
@@ -63,7 +63,7 @@ function collectBuckets(keyFunction, collection, createBucket, updateBucket) {
|
|
|
63
63
|
let index = bucketIndex.get(key, MISSING);
|
|
64
64
|
if (index === MISSING) {
|
|
65
65
|
index = keys.length;
|
|
66
|
-
bucketIndex
|
|
66
|
+
assocBang(bucketIndex, key, index);
|
|
67
67
|
keys.push(key);
|
|
68
68
|
buckets.push(createBucket(value));
|
|
69
69
|
} else {
|
|
@@ -97,12 +97,14 @@ export function groupBy(keyFunction, collection) {
|
|
|
97
97
|
keyFunction,
|
|
98
98
|
collection,
|
|
99
99
|
(value) => [value],
|
|
100
|
-
(values, index, value) =>
|
|
100
|
+
(values, index, value) => {
|
|
101
|
+
values[index].push(value);
|
|
102
|
+
},
|
|
101
103
|
);
|
|
102
104
|
return persistentMapFromBuckets(
|
|
103
105
|
keys,
|
|
104
106
|
buckets,
|
|
105
|
-
(
|
|
107
|
+
(bucket) => PersistentVector.from(bucket),
|
|
106
108
|
);
|
|
107
109
|
}
|
|
108
110
|
|
|
@@ -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