eliscript 0.0.3 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/README.md +6 -6
  2. package/bootstrap/README.md +13 -8
  3. package/bootstrap/host/build.eli +2 -0
  4. package/bootstrap/host/bun.eli +2 -0
  5. package/bootstrap/host/check-cli-legacy.eli +2 -0
  6. package/bootstrap/host/evaluation-cli.eli +2 -0
  7. package/bootstrap/host/evaluation.eli +2 -0
  8. package/bootstrap/host/format-cli.eli +2 -0
  9. package/bootstrap/host/project-cli-legacy.eli +2 -0
  10. package/bootstrap/host/project-legacy.eli +2 -0
  11. package/bootstrap/host/watch-cli.eli +2 -0
  12. package/bootstrap/host/watch.eli +2 -0
  13. package/browser/README.md +33 -0
  14. package/browser/host.eli +2 -0
  15. package/browser/worker.eli +2 -0
  16. package/editor/eliscript-abi.el +170 -0
  17. package/editor/eliscript-async.el +375 -0
  18. package/editor/eliscript-bind.el +822 -0
  19. package/editor/eliscript-compat.el +184 -0
  20. package/editor/eliscript-contract.el +334 -0
  21. package/editor/eliscript-data.el +1544 -0
  22. package/editor/eliscript-js.el +318 -0
  23. package/editor/eliscript-mode.el +1 -1
  24. package/editor/eliscript-module.el +340 -0
  25. package/editor/eliscript-repl.el +1 -1
  26. package/package.json +4 -1
  27. package/platform/README.md +33 -12
  28. package/platform/browser.eli +2 -0
  29. package/platform/http.eli +2 -0
  30. package/platform/worker.eli +2 -0
  31. package/runtime/README.md +34 -14
  32. package/runtime/array-text.eli +2 -0
  33. package/runtime/core/collection-internals.eli +2 -0
  34. package/runtime/core/collection.eli +2 -0
  35. package/runtime/core/collection.mjs +99 -17
  36. package/runtime/core/data-text.eli +2 -0
  37. package/runtime/core/data.eli +2 -0
  38. package/runtime/core/data.mjs +7 -5
  39. package/runtime/core/identifier.eli +2 -0
  40. package/runtime/core/lazy-sequence.eli +2 -0
  41. package/runtime/core/list-internals.eli +2 -0
  42. package/runtime/core/list.eli +2 -0
  43. package/runtime/core/list.mjs +3 -0
  44. package/runtime/core/map-internals.eli +2 -0
  45. package/runtime/core/map.eli +2 -0
  46. package/runtime/core/map.mjs +5 -0
  47. package/runtime/core/metadata-internals.eli +2 -0
  48. package/runtime/core/metadata.eli +2 -0
  49. package/runtime/core/metadata.mjs +14 -0
  50. package/runtime/core/object.eli +2 -0
  51. package/runtime/core/order.eli +2 -0
  52. package/runtime/core/order.mjs +35 -6
  53. package/runtime/core/persistent-kind.eli +2 -0
  54. package/runtime/core/persistent-kind.mjs +6 -0
  55. package/runtime/core/protocol-error.eli +2 -0
  56. package/runtime/core/protocol.eli +2 -0
  57. package/runtime/core/queue-internals.eli +2 -0
  58. package/runtime/core/queue.eli +2 -0
  59. package/runtime/core/queue.mjs +3 -0
  60. package/runtime/core/record.eli +2 -0
  61. package/runtime/core/regex.eli +2 -0
  62. package/runtime/core/sequence.eli +2 -0
  63. package/runtime/core/sequence.mjs +75 -13
  64. package/runtime/core/set-algebra.eli +2 -0
  65. package/runtime/core/set-internals.eli +2 -0
  66. package/runtime/core/set.eli +2 -0
  67. package/runtime/core/sorted-internals.eli +2 -0
  68. package/runtime/core/sorted.eli +2 -0
  69. package/runtime/core/text.eli +2 -0
  70. package/runtime/core/transducer.eli +2 -0
  71. package/runtime/core/transient-internals.eli +2 -0
  72. package/runtime/core/transient.eli +2 -0
  73. package/runtime/core/transient.mjs +59 -10
  74. package/runtime/core/truth.eli +2 -0
  75. package/runtime/core/type.eli +2 -0
  76. package/runtime/core/value-internals.eli +2 -0
  77. package/runtime/core/value.eli +2 -0
  78. package/runtime/core/vector-internals.eli +2 -0
  79. package/runtime/core/vector-internals.mjs +3 -6
  80. package/runtime/core/vector.eli +2 -0
  81. package/runtime/core/vector.mjs +125 -7
  82. package/runtime/emacs-compat.eli +2 -0
  83. package/runtime/emacs-compat.mjs +2507 -0
  84. package/runtime/literals.eli +2 -0
  85. package/runtime/number-radix.eli +2 -0
  86. package/runtime/source-mapping.eli +2 -0
  87. package/runtime/testing/list.eli +2 -0
  88. package/runtime/testing/map.eli +2 -0
  89. package/runtime/testing/queue.eli +2 -0
  90. package/runtime/testing/set.eli +2 -0
  91. package/runtime/testing/sorted.eli +2 -0
  92. package/runtime/testing/value.eli +2 -0
  93. package/runtime/testing/vector.eli +2 -0
  94. package/runtime/wire/http-rpc.eli +2 -0
  95. package/runtime/wire/markdown.eli +2 -0
  96. package/runtime/wire/schema.eli +2 -0
  97. package/runtime/worker-value-codec.eli +2 -0
  98. package/runtime/worker-value-stream.eli +2 -0
  99. package/runtime/worker.eli +2 -0
  100. package/stdlib/README.md +2 -2
  101. package/stdlib/core/order.eli +36 -10
  102. package/stdlib/core/seq.eli +104 -75
  103. package/stdlib/core/zipper.eli +238 -98
  104. package/stdlib/managed-literal-protocols.eli +5 -5
  105. package/stdlib/managed-runtime-order.eli +32 -10
  106. package/stdlib/managed-runtime-sequence.eli +69 -28
  107. package/tools/acceptance/check.eli +13 -3
  108. package/tools/backends/compiler-build.mjs +140 -140
@@ -0,0 +1,1544 @@
1
+ ;;; eliscript-data.el --- Persistent collections, schemas, protocols, cells, and lazy streams -*- lexical-binding: t; -*-
2
+
3
+ ;;; Commentary:
4
+
5
+ ;; Implements `eliscript-data` for Eliscript 0.1.0:
6
+ ;; - 7 persistent collection types with Emacs `seq.el` and `map.el` integration
7
+ ;; - `value-*` pure collection, structural equality, hash, compare, and metadata APIs
8
+ ;; - `cl-defstruct-persistent` with field contracts and JSON Schema roundtrip
9
+ ;; - `defprotocol`, `extend-protocol`, `defclass-protocol`, `reify-protocol`
10
+ ;; - `cl-defgeneric-value` and `cl-defmethod-value`
11
+ ;; - `state-cell`, `cell-value`, `cell-update!`, `cell-reset!`, `cell-watch`
12
+ ;; - `delay`, `force`, `realized-p`, `memoize`, `lazy-seq`, `lazy-map`, `lazy-filter`, `lazy-take`, `lazy-range`
13
+ ;; - `map-transducer`, `filter-transducer`, `take-transducer`, `seq-transduce`
14
+ ;; - `with-transient`, `conj!`, `assoc!`, `dissoc!`
15
+ ;; - `result-*`, `option-*`, `data-symbol*`
16
+
17
+ ;;; Code:
18
+
19
+ (require 'cl-lib)
20
+ (require 'seq)
21
+ (require 'map)
22
+ (require 'json)
23
+ (require 'eliscript-contract)
24
+
25
+ ;; ============================================================================
26
+ ;; 1. Persistent Collection Structures & Predicates
27
+ ;; ============================================================================
28
+
29
+ (progn
30
+ (cl-defstruct (eliscript-persistent-list (:constructor eliscript-persistent-list--create))
31
+ items meta)
32
+
33
+ (cl-defstruct (eliscript-persistent-vector (:constructor eliscript-persistent-vector--create))
34
+ items meta)
35
+
36
+ (cl-defstruct (eliscript-persistent-map (:constructor eliscript-persistent-map--create))
37
+ entries meta)
38
+
39
+ (cl-defstruct (eliscript-persistent-set (:constructor eliscript-persistent-set--create))
40
+ items meta)
41
+
42
+ (cl-defstruct (eliscript-persistent-queue (:constructor eliscript-persistent-queue--create))
43
+ items meta)
44
+
45
+ (cl-defstruct (eliscript-persistent-sorted-map (:constructor eliscript-persistent-sorted-map--create))
46
+ comparator entries meta)
47
+
48
+ (cl-defstruct (eliscript-persistent-sorted-set (:constructor eliscript-persistent-sorted-set--create))
49
+ comparator items meta)
50
+
51
+ (cl-defstruct (eliscript-persistent-record (:constructor eliscript-persistent-record--create))
52
+ type-name fields meta))
53
+
54
+ (defun persistent-list-p (obj)
55
+ "Return t if OBJ is a persistent-list."
56
+ (and (eliscript-persistent-list-p obj) t))
57
+
58
+ (defun persistent-vector-p (obj)
59
+ "Return t if OBJ is a persistent-vector."
60
+ (and (eliscript-persistent-vector-p obj) t))
61
+
62
+ (defun persistent-map-p (obj)
63
+ "Return t if OBJ is a persistent-map."
64
+ (and (eliscript-persistent-map-p obj) t))
65
+
66
+ (defun persistent-set-p (obj)
67
+ "Return t if OBJ is a persistent-set."
68
+ (and (eliscript-persistent-set-p obj) t))
69
+
70
+ (defun persistent-queue-p (obj)
71
+ "Return t if OBJ is a persistent-queue."
72
+ (and (eliscript-persistent-queue-p obj) t))
73
+
74
+ (defun persistent-sorted-map-p (obj)
75
+ "Return t if OBJ is a persistent-sorted-map."
76
+ (and (eliscript-persistent-sorted-map-p obj) t))
77
+
78
+ (defun persistent-sorted-set-p (obj)
79
+ "Return t if OBJ is a persistent-sorted-set."
80
+ (and (eliscript-persistent-sorted-set-p obj) t))
81
+
82
+ (progn
83
+ (defun eliscript-persistent-collection-p (obj)
84
+ "Return t if OBJ is any Eliscript persistent collection or lazy sequence."
85
+ (or (eliscript-persistent-list-p obj)
86
+ (eliscript-persistent-vector-p obj)
87
+ (eliscript-persistent-map-p obj)
88
+ (eliscript-persistent-set-p obj)
89
+ (eliscript-persistent-queue-p obj)
90
+ (eliscript-persistent-sorted-map-p obj)
91
+ (eliscript-persistent-sorted-set-p obj)
92
+ (eliscript-persistent-record-p obj))))
93
+
94
+ (defun persistent-list (&rest items)
95
+ "Construct an immutable persistent list from ITEMS."
96
+ (eliscript-persistent-list--create :items (copy-sequence items) :meta nil))
97
+
98
+ (defun persistent-vector (&rest items)
99
+ "Construct an immutable persistent vector from ITEMS."
100
+ (eliscript-persistent-vector--create :items (vconcat items) :meta nil))
101
+
102
+ (defun eliscript-data--assoc-alist (entries key val)
103
+ "Return a new alist from ENTRIES with KEY mapped to VAL using `value-equal-p'."
104
+ (let ((found nil)
105
+ (out nil))
106
+ (dolist (cell entries)
107
+ (if (and (not found) (value-equal-p (car cell) key))
108
+ (progn
109
+ (setq found t)
110
+ (push (cons key val) out))
111
+ (push cell out)))
112
+ (setq out (nreverse out))
113
+ (unless found
114
+ (setq out (append out (list (cons key val)))))
115
+ out))
116
+
117
+ (defun eliscript-data--dissoc-alist (entries key)
118
+ "Return a new alist from ENTRIES without KEY using `value-equal-p'."
119
+ (let ((out nil))
120
+ (dolist (cell entries)
121
+ (unless (value-equal-p (car cell) key)
122
+ (push cell out)))
123
+ (nreverse out)))
124
+
125
+ (defun persistent-map (&rest kvs)
126
+ "Construct an immutable persistent map from alternating KVS."
127
+ (when (/= (% (length kvs) 2) 0)
128
+ (error "persistent-map requires an even number of key/value arguments"))
129
+ (let ((entries nil)
130
+ (cursor kvs))
131
+ (while cursor
132
+ (setq entries (eliscript-data--assoc-alist entries (car cursor) (cadr cursor)))
133
+ (setq cursor (cddr cursor)))
134
+ (eliscript-persistent-map--create :entries entries :meta nil)))
135
+
136
+ (defun persistent-set (&rest items)
137
+ "Construct an immutable persistent set from ITEMS."
138
+ (let ((unique nil))
139
+ (dolist (it items)
140
+ (unless (cl-some (lambda (existing) (value-equal-p existing it)) unique)
141
+ (push it unique)))
142
+ (eliscript-persistent-set--create :items (nreverse unique) :meta nil)))
143
+
144
+ (defun persistent-queue (&rest items)
145
+ "Construct an immutable persistent FIFO queue from ITEMS."
146
+ (eliscript-persistent-queue--create :items (copy-sequence items) :meta nil))
147
+
148
+ (defun eliscript-data--normalize-cmp (cmp)
149
+ "Wrap comparator CMP so it returns a negative, zero, or positive integer."
150
+ (let ((fn (or cmp #'value-compare)))
151
+ (lambda (a b)
152
+ (let ((res (funcall fn a b)))
153
+ (cond
154
+ ((numberp res) res)
155
+ ((eq res t) -1)
156
+ (t (if (value-equal-p a b) 0 1)))))))
157
+
158
+ (defun persistent-sorted-map (&rest args)
159
+ "Construct an immutable sorted map. Optional first arg is comparator function."
160
+ (let* ((has-cmp (and args (functionp (car args)) (= (% (length (cdr args)) 2) 0)))
161
+ (cmp (if has-cmp (car args) #'value-compare))
162
+ (kvs (if has-cmp (cdr args) args))
163
+ (norm-cmp (eliscript-data--normalize-cmp cmp))
164
+ (entries nil)
165
+ (cursor kvs))
166
+ (when (/= (% (length kvs) 2) 0)
167
+ (error "persistent-sorted-map requires an even number of key/value arguments"))
168
+ (while cursor
169
+ (setq entries (eliscript-data--assoc-alist entries (car cursor) (cadr cursor)))
170
+ (setq cursor (cddr cursor)))
171
+ (setq entries
172
+ (sort (copy-sequence entries)
173
+ (lambda (c1 c2) (< (funcall norm-cmp (car c1) (car c2)) 0))))
174
+ (eliscript-persistent-sorted-map--create
175
+ :comparator cmp
176
+ :entries entries
177
+ :meta nil)))
178
+
179
+ (defun persistent-sorted-set (&rest args)
180
+ "Construct an immutable sorted set. Optional first arg is comparator function."
181
+ (let* ((has-cmp (and args (functionp (car args))))
182
+ (cmp (if has-cmp (car args) #'value-compare))
183
+ (items (if has-cmp (cdr args) args))
184
+ (norm-cmp (eliscript-data--normalize-cmp cmp))
185
+ (unique nil))
186
+ (dolist (it items)
187
+ (unless (cl-some (lambda (existing) (= (funcall norm-cmp existing it) 0)) unique)
188
+ (push it unique)))
189
+ (setq unique
190
+ (sort (nreverse unique)
191
+ (lambda (a b) (< (funcall norm-cmp a b) 0))))
192
+ (eliscript-persistent-sorted-set--create
193
+ :comparator cmp
194
+ :items unique
195
+ :meta nil)))
196
+
197
+ ;; ============================================================================
198
+ ;; 2. Result, Option, and DataSymbol Types
199
+ ;; ============================================================================
200
+
201
+ (progn
202
+ (cl-defstruct (eliscript-result (:constructor eliscript-result--create))
203
+ ok-p payload))
204
+
205
+ (defun result-ok (value)
206
+ "Construct a successful Result wrapping VALUE."
207
+ (eliscript-result--create :ok-p t :payload value))
208
+
209
+ (defun result-error (err)
210
+ "Construct a failed Result wrapping ERR."
211
+ (eliscript-result--create :ok-p nil :payload err))
212
+
213
+ (defun result-ok-p (res)
214
+ "Return t if RES is a successful Result."
215
+ (and (eliscript-result-p res) (eliscript-result-ok-p res) t))
216
+
217
+ (defun result-error-p (res)
218
+ "Return t if RES is a failed Result."
219
+ (and (eliscript-result-p res) (not (eliscript-result-ok-p res)) t))
220
+
221
+ (defun result-value (res)
222
+ "Return the value inside `result-ok' RES, or signal an error."
223
+ (unless (result-ok-p res)
224
+ (error "result-value called on non-ok result: %S" res))
225
+ (eliscript-result-payload res))
226
+
227
+ (defun result-error-value (res)
228
+ "Return the error payload inside `result-error' RES, or signal an error."
229
+ (unless (result-error-p res)
230
+ (error "result-error-value called on non-error result: %S" res))
231
+ (eliscript-result-payload res))
232
+
233
+ (defun result-bind (res fn)
234
+ "If RES is ok, apply FN to its payload; otherwise return RES unchanged."
235
+ (if (result-ok-p res)
236
+ (funcall fn (eliscript-result-payload res))
237
+ res))
238
+
239
+ (progn
240
+ (cl-defstruct (eliscript-option (:constructor eliscript-option--create))
241
+ some-p payload))
242
+
243
+ (defconst option-none (eliscript-option--create :some-p nil :payload nil)
244
+ "Singleton non-nil value representing an absent Option.")
245
+
246
+ (defun option-some (value)
247
+ "Construct a present Option wrapping VALUE."
248
+ (eliscript-option--create :some-p t :payload value))
249
+
250
+ (defun option-some-p (opt)
251
+ "Return t if OPT is `option-some'."
252
+ (and (eliscript-option-p opt) (eliscript-option-some-p opt) t))
253
+
254
+ (defun option-none-p (opt)
255
+ "Return t if OPT is `option-none'."
256
+ (and (eliscript-option-p opt) (not (eliscript-option-some-p opt)) t))
257
+
258
+ (defun option-value (opt)
259
+ "Return the value inside `option-some' OPT, or signal an error."
260
+ (unless (option-some-p opt)
261
+ (error "option-value called on option-none"))
262
+ (eliscript-option-payload opt))
263
+
264
+ (progn
265
+ (cl-defstruct (eliscript-data-symbol (:constructor eliscript-data-symbol--create))
266
+ namespace name))
267
+
268
+ (defun data-symbol (name &optional namespace)
269
+ "Construct an immutable data-symbol with NAME and optional NAMESPACE."
270
+ (if (and (null namespace) (stringp name) (string-match "\\`\\([^/]+\\)/\\(.+\\)\\'" name))
271
+ (eliscript-data-symbol--create
272
+ :namespace (match-string 1 name)
273
+ :name (match-string 2 name))
274
+ (eliscript-data-symbol--create
275
+ :namespace (and namespace (format "%s" namespace))
276
+ :name (format "%s" name))))
277
+
278
+ (defun data-symbol-p (obj)
279
+ "Return t if OBJ is a data-symbol."
280
+ (and (eliscript-data-symbol-p obj) t))
281
+
282
+ (defun data-symbol-name (sym)
283
+ "Return the name string of data-symbol SYM."
284
+ (eliscript-data-symbol-name sym))
285
+
286
+ (defun data-symbol-namespace (sym)
287
+ "Return the namespace string (or nil) of data-symbol SYM."
288
+ (eliscript-data-symbol-namespace sym))
289
+
290
+ ;; ============================================================================
291
+ ;; 3. Value Equality, Hash, Comparison, Metadata, and `value-*` Operations
292
+ ;; ============================================================================
293
+
294
+ (defun eliscript-data--seq-elements (coll)
295
+ "Return elements of persistent or native sequential COLL as an Emacs list."
296
+ (cond
297
+ ((eliscript-persistent-list-p coll)
298
+ (eliscript-persistent-list-items coll))
299
+ ((eliscript-persistent-vector-p coll)
300
+ (append (eliscript-persistent-vector-items coll) nil))
301
+ ((eliscript-persistent-queue-p coll)
302
+ (eliscript-persistent-queue-items coll))
303
+ ((eliscript-persistent-set-p coll)
304
+ (eliscript-persistent-set-items coll))
305
+ ((eliscript-persistent-sorted-set-p coll)
306
+ (eliscript-persistent-sorted-set-items coll))
307
+ ((eliscript-persistent-map-p coll)
308
+ (mapcar (lambda (c) (list (car c) (cdr c)))
309
+ (eliscript-persistent-map-entries coll)))
310
+ ((eliscript-persistent-sorted-map-p coll)
311
+ (mapcar (lambda (c) (list (car c) (cdr c)))
312
+ (eliscript-persistent-sorted-map-entries coll)))
313
+ ((eliscript-persistent-record-p coll)
314
+ (mapcar (lambda (c) (list (car c) (cdr c)))
315
+ (eliscript-persistent-record-fields coll)))
316
+ ((lazy-seq-p coll)
317
+ (eliscript-lazy-seq--realize-list coll))
318
+ ((vectorp coll)
319
+ (append coll nil))
320
+ ((listp coll)
321
+ coll)
322
+ (t (error "Not a sequential or collection value: %S" coll))))
323
+
324
+ (defun eliscript-data--map-entries (m)
325
+ "Return alist entries of persistent map or record M."
326
+ (cond
327
+ ((eliscript-persistent-map-p m)
328
+ (eliscript-persistent-map-entries m))
329
+ ((eliscript-persistent-sorted-map-p m)
330
+ (eliscript-persistent-sorted-map-entries m))
331
+ ((eliscript-persistent-record-p m)
332
+ (eliscript-persistent-record-fields m))
333
+ ((hash-table-p m)
334
+ (let ((acc nil))
335
+ (maphash (lambda (k v) (push (cons k v) acc)) m)
336
+ (nreverse acc)))
337
+ (t nil)))
338
+
339
+ (defun value-equal-p (a b)
340
+ "Return t if A and B are structurally equal by value."
341
+ (cond
342
+ ((eq a b) t)
343
+ ((and (numberp a) (numberp b))
344
+ (and (eq (floatp a) (floatp b)) (= a b)))
345
+ ((and (stringp a) (stringp b))
346
+ (string-equal a b))
347
+ ((and (or (eliscript-persistent-list-p a)
348
+ (eliscript-persistent-vector-p a)
349
+ (eliscript-persistent-queue-p a))
350
+ (or (eliscript-persistent-list-p b)
351
+ (eliscript-persistent-vector-p b)
352
+ (eliscript-persistent-queue-p b)))
353
+ (let ((la (eliscript-data--seq-elements a))
354
+ (lb (eliscript-data--seq-elements b)))
355
+ (and (= (length la) (length lb))
356
+ (cl-every #'value-equal-p la lb))))
357
+ ((and (or (eliscript-persistent-map-p a) (eliscript-persistent-sorted-map-p a))
358
+ (or (eliscript-persistent-map-p b) (eliscript-persistent-sorted-map-p b)))
359
+ (let ((ea (eliscript-data--map-entries a))
360
+ (eb (eliscript-data--map-entries b)))
361
+ (and (= (length ea) (length eb))
362
+ (cl-every
363
+ (lambda (ca)
364
+ (let ((match (cl-find-if (lambda (cb) (value-equal-p (car ca) (car cb))) eb)))
365
+ (and match (value-equal-p (cdr ca) (cdr match)))))
366
+ ea))))
367
+ ((and (or (eliscript-persistent-set-p a) (eliscript-persistent-sorted-set-p a))
368
+ (or (eliscript-persistent-set-p b) (eliscript-persistent-sorted-set-p b)))
369
+ (let ((sa (eliscript-data--seq-elements a))
370
+ (sb (eliscript-data--seq-elements b)))
371
+ (and (= (length sa) (length sb))
372
+ (cl-every (lambda (x) (cl-some (lambda (y) (value-equal-p x y)) sb)) sa))))
373
+ ((and (eliscript-persistent-record-p a) (eliscript-persistent-record-p b))
374
+ (and (eq (eliscript-persistent-record-type-name a)
375
+ (eliscript-persistent-record-type-name b))
376
+ (let ((fa (eliscript-persistent-record-fields a))
377
+ (fb (eliscript-persistent-record-fields b)))
378
+ (and (= (length fa) (length fb))
379
+ (cl-every (lambda (ca)
380
+ (let ((cb (assq (car ca) fb)))
381
+ (and cb (value-equal-p (cdr ca) (cdr cb)))))
382
+ fa)))))
383
+ ((and (eliscript-result-p a) (eliscript-result-p b))
384
+ (and (eq (eliscript-result-ok-p a) (eliscript-result-ok-p b))
385
+ (value-equal-p (eliscript-result-payload a) (eliscript-result-payload b))))
386
+ ((and (eliscript-option-p a) (eliscript-option-p b))
387
+ (and (eq (eliscript-option-some-p a) (eliscript-option-some-p b))
388
+ (value-equal-p (eliscript-option-payload a) (eliscript-option-payload b))))
389
+ ((and (eliscript-data-symbol-p a) (eliscript-data-symbol-p b))
390
+ (and (equal (eliscript-data-symbol-namespace a) (eliscript-data-symbol-namespace b))
391
+ (equal (eliscript-data-symbol-name a) (eliscript-data-symbol-name b))))
392
+ ((and (vectorp a) (vectorp b))
393
+ (and (= (length a) (length b))
394
+ (cl-every #'value-equal-p (append a nil) (append b nil))))
395
+ ((and (consp a) (consp b))
396
+ (and (value-equal-p (car a) (car b))
397
+ (value-equal-p (cdr a) (cdr b))))
398
+ (t (equal a b))))
399
+
400
+ (defun value-hash (x)
401
+ "Compute a deterministic structural hash for X."
402
+ (cond
403
+ ((eliscript-persistent-collection-p x)
404
+ (sxhash-equal (eliscript-data--seq-elements x)))
405
+ (t (sxhash-equal x))))
406
+
407
+ (defun value-compare (a b)
408
+ "Deterministic structural comparison of A and B returning -1, 0, or 1."
409
+ (cond
410
+ ((value-equal-p a b) 0)
411
+ ((null a) -1)
412
+ ((null b) 1)
413
+ ((and (numberp a) (numberp b))
414
+ (if (< a b) -1 1))
415
+ ((and (stringp a) (stringp b))
416
+ (if (string< a b) -1 1))
417
+ ((and (symbolp a) (symbolp b))
418
+ (if (string< (symbol-name a) (symbol-name b)) -1 1))
419
+ ((and (eliscript-data-symbol-p a) (eliscript-data-symbol-p b))
420
+ (let ((na (or (eliscript-data-symbol-namespace a) ""))
421
+ (nb (or (eliscript-data-symbol-namespace b) "")))
422
+ (if (not (string-equal na nb))
423
+ (if (string< na nb) -1 1)
424
+ (if (string< (eliscript-data-symbol-name a) (eliscript-data-symbol-name b)) -1 1))))
425
+ (t
426
+ (let ((sa (format "%S" a))
427
+ (sb (format "%S" b)))
428
+ (if (string< sa sb) -1 1)))))
429
+
430
+ (defun value-meta (obj)
431
+ "Return the persistent metadata attached to OBJ, or nil."
432
+ (cond
433
+ ((eliscript-persistent-list-p obj) (eliscript-persistent-list-meta obj))
434
+ ((eliscript-persistent-vector-p obj) (eliscript-persistent-vector-meta obj))
435
+ ((eliscript-persistent-map-p obj) (eliscript-persistent-map-meta obj))
436
+ ((eliscript-persistent-set-p obj) (eliscript-persistent-set-meta obj))
437
+ ((eliscript-persistent-queue-p obj) (eliscript-persistent-queue-meta obj))
438
+ ((eliscript-persistent-sorted-map-p obj) (eliscript-persistent-sorted-map-meta obj))
439
+ ((eliscript-persistent-sorted-set-p obj) (eliscript-persistent-sorted-set-meta obj))
440
+ ((eliscript-persistent-record-p obj) (eliscript-persistent-record-meta obj))
441
+ (t nil)))
442
+
443
+ (defun value-with-meta (obj meta-val)
444
+ "Return a copy of persistent value OBJ carrying META-VAL."
445
+ (cond
446
+ ((eliscript-persistent-list-p obj)
447
+ (eliscript-persistent-list--create
448
+ :items (eliscript-persistent-list-items obj) :meta meta-val))
449
+ ((eliscript-persistent-vector-p obj)
450
+ (eliscript-persistent-vector--create
451
+ :items (eliscript-persistent-vector-items obj) :meta meta-val))
452
+ ((eliscript-persistent-map-p obj)
453
+ (eliscript-persistent-map--create
454
+ :entries (eliscript-persistent-map-entries obj) :meta meta-val))
455
+ ((eliscript-persistent-set-p obj)
456
+ (eliscript-persistent-set--create
457
+ :items (eliscript-persistent-set-items obj) :meta meta-val))
458
+ ((eliscript-persistent-queue-p obj)
459
+ (eliscript-persistent-queue--create
460
+ :items (eliscript-persistent-queue-items obj) :meta meta-val))
461
+ ((eliscript-persistent-sorted-map-p obj)
462
+ (eliscript-persistent-sorted-map--create
463
+ :comparator (eliscript-persistent-sorted-map-comparator obj)
464
+ :entries (eliscript-persistent-sorted-map-entries obj)
465
+ :meta meta-val))
466
+ ((eliscript-persistent-sorted-set-p obj)
467
+ (eliscript-persistent-sorted-set--create
468
+ :comparator (eliscript-persistent-sorted-set-comparator obj)
469
+ :items (eliscript-persistent-sorted-set-items obj)
470
+ :meta meta-val))
471
+ ((eliscript-persistent-record-p obj)
472
+ (eliscript-persistent-record--create
473
+ :type-name (eliscript-persistent-record-type-name obj)
474
+ :fields (eliscript-persistent-record-fields obj)
475
+ :meta meta-val))
476
+ (t (error "value-with-meta requires a persistent value, got %S" obj))))
477
+
478
+ (defun value-count (coll)
479
+ "Return the number of elements or entries in COLL."
480
+ (cond
481
+ ((null coll) 0)
482
+ ((eliscript-persistent-list-p coll) (length (eliscript-persistent-list-items coll)))
483
+ ((eliscript-persistent-vector-p coll) (length (eliscript-persistent-vector-items coll)))
484
+ ((eliscript-persistent-map-p coll) (length (eliscript-persistent-map-entries coll)))
485
+ ((eliscript-persistent-set-p coll) (length (eliscript-persistent-set-items coll)))
486
+ ((eliscript-persistent-queue-p coll) (length (eliscript-persistent-queue-items coll)))
487
+ ((eliscript-persistent-sorted-map-p coll) (length (eliscript-persistent-sorted-map-entries coll)))
488
+ ((eliscript-persistent-sorted-set-p coll) (length (eliscript-persistent-sorted-set-items coll)))
489
+ ((eliscript-persistent-record-p coll) (length (eliscript-persistent-record-fields coll)))
490
+ ((lazy-seq-p coll) (length (eliscript-lazy-seq--realize-list coll)))
491
+ ((hash-table-p coll) (hash-table-count coll))
492
+ (t (length coll))))
493
+
494
+ (defun value-empty-p (coll)
495
+ "Return t if COLL has 0 elements."
496
+ (= (value-count coll) 0))
497
+
498
+ (defun value-nth (coll index &optional not-found)
499
+ "Return element at INDEX in sequential COLL."
500
+ (let ((elems (cond
501
+ ((eliscript-persistent-vector-p coll)
502
+ (let ((v (eliscript-persistent-vector-items coll)))
503
+ (if (and (>= index 0) (< index (length v)))
504
+ (cons t (aref v index))
505
+ nil)))
506
+ ((vectorp coll)
507
+ (if (and (>= index 0) (< index (length coll)))
508
+ (cons t (aref coll index))
509
+ nil))
510
+ (t
511
+ (let ((lst (eliscript-data--seq-elements coll)))
512
+ (if (and (>= index 0) (< index (length lst)))
513
+ (cons t (nth index lst))
514
+ nil))))))
515
+ (if elems
516
+ (cdr elems)
517
+ not-found)))
518
+
519
+ (defun eliscript-data--normalize-field-key (key)
520
+ "Normalize keyword `:foo' to symbol `foo' for record field lookup."
521
+ (if (keywordp key)
522
+ (intern (substring (symbol-name key) 1))
523
+ key))
524
+
525
+ (defun value-contains-p (coll key)
526
+ "Return t if COLL contains KEY (even if mapped to nil)."
527
+ (cond
528
+ ((or (eliscript-persistent-map-p coll) (eliscript-persistent-sorted-map-p coll))
529
+ (and (cl-find-if (lambda (c) (value-equal-p (car c) key))
530
+ (eliscript-data--map-entries coll))
531
+ t))
532
+ ((eliscript-persistent-record-p coll)
533
+ (let ((fk (eliscript-data--normalize-field-key key)))
534
+ (and (assq fk (eliscript-persistent-record-fields coll)) t)))
535
+ ((or (eliscript-persistent-set-p coll) (eliscript-persistent-sorted-set-p coll))
536
+ (and (cl-some (lambda (it) (value-equal-p it key))
537
+ (eliscript-data--seq-elements coll))
538
+ t))
539
+ ((hash-table-p coll)
540
+ (let ((sentinel (make-symbol "missing")))
541
+ (not (eq (gethash key coll sentinel) sentinel))))
542
+ ((eliscript-persistent-vector-p coll)
543
+ (and (integerp key) (>= key 0) (< key (value-count coll))))
544
+ ((vectorp coll)
545
+ (and (integerp key) (>= key 0) (< key (length coll))))
546
+ (t nil)))
547
+
548
+ (defun value-get (coll key &optional not-found)
549
+ "Look up KEY in COLL, returning NOT-FOUND (default nil) when absent."
550
+ (cond
551
+ ((null coll) not-found)
552
+ ((or (eliscript-persistent-map-p coll) (eliscript-persistent-sorted-map-p coll))
553
+ (let ((cell (cl-find-if (lambda (c) (value-equal-p (car c) key))
554
+ (eliscript-data--map-entries coll))))
555
+ (if cell (cdr cell) not-found)))
556
+ ((eliscript-persistent-record-p coll)
557
+ (let* ((fk (eliscript-data--normalize-field-key key))
558
+ (cell (assq fk (eliscript-persistent-record-fields coll))))
559
+ (if cell (cdr cell) not-found)))
560
+ ((or (eliscript-persistent-set-p coll) (eliscript-persistent-sorted-set-p coll))
561
+ (let ((found (cl-find-if (lambda (it) (value-equal-p it key))
562
+ (eliscript-data--seq-elements coll))))
563
+ (if found found not-found)))
564
+ ((eliscript-persistent-vector-p coll)
565
+ (value-nth coll key not-found))
566
+ ((hash-table-p coll)
567
+ (gethash key coll not-found))
568
+ ((vectorp coll)
569
+ (if (and (integerp key) (>= key 0) (< key (length coll)))
570
+ (aref coll key)
571
+ not-found))
572
+ (t not-found)))
573
+
574
+ (defun value-put (coll key val)
575
+ "Return a new persistent collection from COLL with KEY set to VAL."
576
+ (cond
577
+ ((eliscript-persistent-map-p coll)
578
+ (eliscript-persistent-map--create
579
+ :entries (eliscript-data--assoc-alist (eliscript-persistent-map-entries coll) key val)
580
+ :meta (eliscript-persistent-map-meta coll)))
581
+ ((eliscript-persistent-sorted-map-p coll)
582
+ (let* ((cmp (eliscript-persistent-sorted-map-comparator coll))
583
+ (norm-cmp (eliscript-data--normalize-cmp cmp))
584
+ (entries (eliscript-data--assoc-alist
585
+ (eliscript-persistent-sorted-map-entries coll) key val)))
586
+ (eliscript-persistent-sorted-map--create
587
+ :comparator cmp
588
+ :entries (sort (copy-sequence entries)
589
+ (lambda (c1 c2) (< (funcall norm-cmp (car c1) (car c2)) 0)))
590
+ :meta (eliscript-persistent-sorted-map-meta coll))))
591
+ ((eliscript-persistent-vector-p coll)
592
+ (let* ((old (eliscript-persistent-vector-items coll))
593
+ (len (length old)))
594
+ (when (or (< key 0) (> key len))
595
+ (error "value-put index %d out of bounds for vector of length %d" key len))
596
+ (let ((copy (vconcat old (if (= key len) (vector val) []))))
597
+ (when (< key len)
598
+ (aset copy key val))
599
+ (eliscript-persistent-vector--create
600
+ :items copy :meta (eliscript-persistent-vector-meta coll)))))
601
+ (t (error "value-put unsupported on %S" coll))))
602
+
603
+ (defalias 'value-assoc #'value-put)
604
+
605
+ (defun value-remove (coll key)
606
+ "Return a new persistent collection from COLL with KEY removed."
607
+ (cond
608
+ ((eliscript-persistent-map-p coll)
609
+ (eliscript-persistent-map--create
610
+ :entries (eliscript-data--dissoc-alist (eliscript-persistent-map-entries coll) key)
611
+ :meta (eliscript-persistent-map-meta coll)))
612
+ ((eliscript-persistent-sorted-map-p coll)
613
+ (eliscript-persistent-sorted-map--create
614
+ :comparator (eliscript-persistent-sorted-map-comparator coll)
615
+ :entries (eliscript-data--dissoc-alist (eliscript-persistent-sorted-map-entries coll) key)
616
+ :meta (eliscript-persistent-sorted-map-meta coll)))
617
+ ((eliscript-persistent-set-p coll)
618
+ (eliscript-persistent-set--create
619
+ :items (cl-remove-if (lambda (it) (value-equal-p it key))
620
+ (eliscript-persistent-set-items coll))
621
+ :meta (eliscript-persistent-set-meta coll)))
622
+ ((eliscript-persistent-sorted-set-p coll)
623
+ (eliscript-persistent-sorted-set--create
624
+ :comparator (eliscript-persistent-sorted-set-comparator coll)
625
+ :items (cl-remove-if (lambda (it) (value-equal-p it key))
626
+ (eliscript-persistent-sorted-set-items coll))
627
+ :meta (eliscript-persistent-sorted-set-meta coll)))
628
+ (t (error "value-remove unsupported on %S" coll))))
629
+
630
+ (defalias 'value-dissoc #'value-remove)
631
+
632
+ (defun value-conj (coll &rest items)
633
+ "Return a new persistent collection with ITEMS added to COLL."
634
+ (let ((cur coll))
635
+ (dolist (item items cur)
636
+ (setq cur
637
+ (cond
638
+ ((eliscript-persistent-list-p cur)
639
+ (eliscript-persistent-list--create
640
+ :items (cons item (eliscript-persistent-list-items cur))
641
+ :meta (eliscript-persistent-list-meta cur)))
642
+ ((eliscript-persistent-vector-p cur)
643
+ (eliscript-persistent-vector--create
644
+ :items (vconcat (eliscript-persistent-vector-items cur) (vector item))
645
+ :meta (eliscript-persistent-vector-meta cur)))
646
+ ((eliscript-persistent-queue-p cur)
647
+ (eliscript-persistent-queue--create
648
+ :items (append (eliscript-persistent-queue-items cur) (list item))
649
+ :meta (eliscript-persistent-queue-meta cur)))
650
+ ((eliscript-persistent-set-p cur)
651
+ (let ((existing (eliscript-persistent-set-items cur)))
652
+ (if (cl-some (lambda (x) (value-equal-p x item)) existing)
653
+ cur
654
+ (eliscript-persistent-set--create
655
+ :items (append existing (list item))
656
+ :meta (eliscript-persistent-set-meta cur)))))
657
+ ((eliscript-persistent-sorted-set-p cur)
658
+ (apply #'persistent-sorted-set
659
+ (eliscript-persistent-sorted-set-comparator cur)
660
+ (append (eliscript-persistent-sorted-set-items cur) (list item))))
661
+ ((or (eliscript-persistent-map-p cur) (eliscript-persistent-sorted-map-p cur))
662
+ (cond
663
+ ((and (vectorp item) (= (length item) 2))
664
+ (value-put cur (aref item 0) (aref item 1)))
665
+ ((consp item)
666
+ (value-put cur (car item) (if (consp (cdr item)) (cadr item) (cdr item))))
667
+ (t (error "value-conj on map expects [k v] or (k . v), got %S" item))))
668
+ (t (error "value-conj unsupported on %S" cur)))))))
669
+
670
+ (defun value-into (to from)
671
+ "Pour elements of FROM into persistent collection TO."
672
+ (apply #'value-conj to (eliscript-data--seq-elements from)))
673
+
674
+ ;; ============================================================================
675
+ ;; 4. Emacs `seq.el` and `map.el` Seamless Generic Interoperability
676
+ ;; ============================================================================
677
+
678
+ (defun eliscript-data--seq-like-p (obj)
679
+ "Return non-nil if OBJ is an Eliscript persistent collection or lazy-seq."
680
+ (or (eliscript-persistent-collection-p obj)
681
+ (lazy-seq-p obj)))
682
+
683
+ (defun eliscript-data--advise-seq-p (orig-fn obj)
684
+ "Return t for Eliscript persistent collections or delegate to ORIG-FN for OBJ."
685
+ (if (eliscript-data--seq-like-p obj)
686
+ t
687
+ (funcall orig-fn obj)))
688
+
689
+ (defun eliscript-data--advise-seq-length (orig-fn seq)
690
+ "Return length for Eliscript SEQ or delegate to ORIG-FN."
691
+ (if (eliscript-data--seq-like-p seq)
692
+ (value-count seq)
693
+ (funcall orig-fn seq)))
694
+
695
+ (defun eliscript-data--advise-seq-elt (orig-fn seq n)
696
+ "Return element N of Eliscript SEQ or delegate to ORIG-FN."
697
+ (if (eliscript-data--seq-like-p seq)
698
+ (value-nth seq n)
699
+ (funcall orig-fn seq n)))
700
+
701
+ (defun eliscript-data--advise-seq-empty-p (orig-fn seq)
702
+ "Return t if Eliscript SEQ is empty or delegate to ORIG-FN."
703
+ (if (eliscript-data--seq-like-p seq)
704
+ (value-empty-p seq)
705
+ (funcall orig-fn seq)))
706
+
707
+ (defun eliscript-data--advise-seq-do (orig-fn fn seq)
708
+ "Apply FN to each element of Eliscript SEQ or delegate to ORIG-FN."
709
+ (if (eliscript-data--seq-like-p seq)
710
+ (dolist (x (eliscript-data--seq-elements seq) seq)
711
+ (funcall fn x))
712
+ (funcall orig-fn fn seq)))
713
+
714
+ (defun eliscript-data--advise-seq-map (orig-fn fn seq)
715
+ "Map FN over Eliscript SEQ or delegate to ORIG-FN."
716
+ (if (eliscript-data--seq-like-p seq)
717
+ (mapcar fn (eliscript-data--seq-elements seq))
718
+ (funcall orig-fn fn seq)))
719
+
720
+ (defun eliscript-data--advise-seq-filter (orig-fn pred seq)
721
+ "Filter Eliscript SEQ by PRED or delegate to ORIG-FN."
722
+ (if (eliscript-data--seq-like-p seq)
723
+ (cl-remove-if-not pred (eliscript-data--seq-elements seq))
724
+ (funcall orig-fn pred seq)))
725
+
726
+ (defun eliscript-data--advise-seq-reduce (orig-fn fn seq initial-value)
727
+ "Reduce Eliscript SEQ with FN and INITIAL-VALUE or delegate to ORIG-FN."
728
+ (if (eliscript-data--seq-like-p seq)
729
+ (cl-reduce fn (eliscript-data--seq-elements seq) :initial-value initial-value)
730
+ (funcall orig-fn fn seq initial-value)))
731
+
732
+ (defun eliscript-data--advise-seq-subseq (orig-fn seq start &optional end)
733
+ "Return subsequence of Eliscript SEQ or delegate to ORIG-FN."
734
+ (if (eliscript-data--seq-like-p seq)
735
+ (let ((sub (cl-subseq (eliscript-data--seq-elements seq) start end)))
736
+ (cond
737
+ ((eliscript-persistent-vector-p seq) (apply #'persistent-vector sub))
738
+ ((eliscript-persistent-list-p seq) (apply #'persistent-list sub))
739
+ (t sub)))
740
+ (funcall orig-fn seq start end)))
741
+
742
+ (defun eliscript-data--advise-seq-into (orig-fn seq type)
743
+ "Convert SEQ into TYPE, supporting persistent collections and native types."
744
+ (cond
745
+ ((eq type 'persistent-vector-p)
746
+ (persistent-vector-p (apply #'persistent-vector (eliscript-data--seq-elements seq))))
747
+ ((eq type 'persistent-vector)
748
+ (apply #'persistent-vector (eliscript-data--seq-elements seq)))
749
+ ((eq type 'persistent-list)
750
+ (apply #'persistent-list (eliscript-data--seq-elements seq)))
751
+ ((eq type 'persistent-set)
752
+ (apply #'persistent-set (eliscript-data--seq-elements seq)))
753
+ ((eliscript-data--seq-like-p seq)
754
+ (let ((elems (eliscript-data--seq-elements seq)))
755
+ (cond
756
+ ((eq type 'list) elems)
757
+ ((eq type 'vector) (vconcat elems))
758
+ (t (funcall orig-fn elems type)))))
759
+ (t (funcall orig-fn seq type))))
760
+
761
+ (defun eliscript-data--map-like-p (m)
762
+ "Return non-nil if M is an Eliscript map or persistent record."
763
+ (or (eliscript-persistent-map-p m)
764
+ (eliscript-persistent-sorted-map-p m)
765
+ (eliscript-persistent-record-p m)))
766
+
767
+ (defun eliscript-data--advise-map-p (orig-fn m)
768
+ "Return t if M is an Eliscript map/record or delegate to ORIG-FN."
769
+ (if (eliscript-data--map-like-p m)
770
+ t
771
+ (funcall orig-fn m)))
772
+
773
+ (defun eliscript-data--advise-map-elt (orig-fn m key &optional default testfn)
774
+ "Look up KEY in Eliscript map M or delegate to ORIG-FN."
775
+ (if (eliscript-data--map-like-p m)
776
+ (value-get m key default)
777
+ (funcall orig-fn m key default testfn)))
778
+
779
+ (defun eliscript-data--advise-map-contains-key (orig-fn m key &optional testfn)
780
+ "Return t if Eliscript map M contains KEY or delegate to ORIG-FN."
781
+ (if (eliscript-data--map-like-p m)
782
+ (value-contains-p m key)
783
+ (funcall orig-fn m key testfn)))
784
+
785
+ (defun eliscript-data--advise-map-keys (orig-fn m)
786
+ "Return keys of Eliscript map M or delegate to ORIG-FN."
787
+ (if (eliscript-data--map-like-p m)
788
+ (mapcar #'car (eliscript-data--map-entries m))
789
+ (funcall orig-fn m)))
790
+
791
+ (defun eliscript-data--advise-map-values (orig-fn m)
792
+ "Return values of Eliscript map M or delegate to ORIG-FN."
793
+ (if (eliscript-data--map-like-p m)
794
+ (mapcar #'cdr (eliscript-data--map-entries m))
795
+ (funcall orig-fn m)))
796
+
797
+ (defun eliscript-data--advise-map-apply (orig-fn fn m)
798
+ "Apply FN to each (key val) of Eliscript map M or delegate to ORIG-FN."
799
+ (if (eliscript-data--map-like-p m)
800
+ (mapcar (lambda (c) (funcall fn (car c) (cdr c)))
801
+ (eliscript-data--map-entries m))
802
+ (funcall orig-fn fn m)))
803
+
804
+ (advice-add 'seq-p :around #'eliscript-data--advise-seq-p)
805
+ (advice-add 'seq-length :around #'eliscript-data--advise-seq-length)
806
+ (advice-add 'seq-elt :around #'eliscript-data--advise-seq-elt)
807
+ (advice-add 'seq-empty-p :around #'eliscript-data--advise-seq-empty-p)
808
+ (advice-add 'seq-do :around #'eliscript-data--advise-seq-do)
809
+ (advice-add 'seq-map :around #'eliscript-data--advise-seq-map)
810
+ (advice-add 'seq-filter :around #'eliscript-data--advise-seq-filter)
811
+ (advice-add 'seq-reduce :around #'eliscript-data--advise-seq-reduce)
812
+ (advice-add 'seq-subseq :around #'eliscript-data--advise-seq-subseq)
813
+ (advice-add 'seq-into :around #'eliscript-data--advise-seq-into)
814
+
815
+ (advice-add 'map-p :around #'eliscript-data--advise-map-p)
816
+ (advice-add 'map-elt :around #'eliscript-data--advise-map-elt)
817
+ (advice-add 'map-contains-key :around #'eliscript-data--advise-map-contains-key)
818
+ (advice-add 'map-keys :around #'eliscript-data--advise-map-keys)
819
+ (advice-add 'map-values :around #'eliscript-data--advise-map-values)
820
+ (advice-add 'map-apply :around #'eliscript-data--advise-map-apply)
821
+
822
+ ;; ============================================================================
823
+ ;; 5. Persistent Structs & AI-Native JSON Schema (`cl-defstruct-persistent`)
824
+ ;; ============================================================================
825
+
826
+ (defvar eliscript-data--struct-schemas (make-hash-table :test 'eq)
827
+ "Registry of `cl-defstruct-persistent' schemas keyed by struct name symbol.")
828
+
829
+ (defun eliscript-data--parse-field-spec (spec)
830
+ "Parse field SPEC from `cl-defstruct-persistent' into a plist."
831
+ (if (symbolp spec)
832
+ (list :name spec :type 'any :has-default nil :default nil :min nil :max nil :doc nil)
833
+ (let ((fname (car spec))
834
+ (opts (cdr spec)))
835
+ (list :name fname
836
+ :type (or (plist-get opts :type) 'any)
837
+ :has-default (and (plist-member opts :default) t)
838
+ :default (plist-get opts :default)
839
+ :min (plist-get opts :min)
840
+ :max (plist-get opts :max)
841
+ :doc (plist-get opts :doc)))))
842
+
843
+ (defun eliscript-data--validate-field-value (struct-name field-plist val)
844
+ "Validate VAL against FIELD-PLIST for STRUCT-NAME."
845
+ (let ((fname (plist-get field-plist :name))
846
+ (ftype (plist-get field-plist :type))
847
+ (fmin (plist-get field-plist :min))
848
+ (fmax (plist-get field-plist :max)))
849
+ (let ((type-ok
850
+ (cond
851
+ ((memq ftype '(any t nil)) t)
852
+ ((eq ftype 'string) (stringp val))
853
+ ((eq ftype 'integer) (integerp val))
854
+ ((eq ftype 'number) (numberp val))
855
+ ((eq ftype 'float) (floatp val))
856
+ ((eq ftype 'boolean) (booleanp val))
857
+ ((eq ftype 'symbol) (symbolp val))
858
+ ((eq ftype 'keyword) (keywordp val))
859
+ ((and (symbolp ftype) (fboundp ftype)) (funcall ftype val))
860
+ (t t))))
861
+ (unless type-ok
862
+ (error "Schema validation failed for %s.%s: expected type %S, got %S"
863
+ struct-name fname ftype val))
864
+ (when (and fmin (numberp val) (< val fmin))
865
+ (error "Schema validation failed for %s.%s: value %S is below :min %S"
866
+ struct-name fname val fmin))
867
+ (when (and fmax (numberp val) (> val fmax))
868
+ (error "Schema validation failed for %s.%s: value %S exceeds :max %S"
869
+ struct-name fname val fmax))
870
+ t)))
871
+
872
+ (defun eliscript-data--construct-struct (struct-name kvs)
873
+ "Construct a persistent record of STRUCT-NAME from keyword arguments KVS."
874
+ (let ((schema (gethash struct-name eliscript-data--struct-schemas)))
875
+ (unless schema
876
+ (error "Unknown persistent struct %S" struct-name))
877
+ (let ((given (make-hash-table :test 'eq))
878
+ (cursor kvs))
879
+ (while cursor
880
+ (let ((k (eliscript-data--normalize-field-key (car cursor)))
881
+ (v (cadr cursor)))
882
+ (puthash k v given))
883
+ (setq cursor (cddr cursor)))
884
+ (let ((fields-alist nil))
885
+ (dolist (fspec (plist-get schema :fields))
886
+ (let* ((fname (plist-get fspec :name))
887
+ (sentinel (make-symbol "absent"))
888
+ (provided (gethash fname given sentinel))
889
+ (val (if (not (eq provided sentinel))
890
+ provided
891
+ (if (plist-get fspec :has-default)
892
+ (plist-get fspec :default)
893
+ nil))))
894
+ (eliscript-data--validate-field-value struct-name fspec val)
895
+ (push (cons fname val) fields-alist)))
896
+ (eliscript-persistent-record--create
897
+ :type-name struct-name
898
+ :fields (nreverse fields-alist)
899
+ :meta nil)))))
900
+
901
+ (defun eliscript-data--update-struct (struct-name instance kvs)
902
+ "Return a new persistent record of STRUCT-NAME copying INSTANCE with KVS updated."
903
+ (unless (and (eliscript-persistent-record-p instance)
904
+ (eq (eliscript-persistent-record-type-name instance) struct-name))
905
+ (error "%s-with expected a %s instance, got %S" struct-name struct-name instance))
906
+ (let ((merged-kvs nil))
907
+ (dolist (cell (eliscript-persistent-record-fields instance))
908
+ (push (intern (concat ":" (symbol-name (car cell)))) merged-kvs)
909
+ (push (cdr cell) merged-kvs))
910
+ (setq merged-kvs (append (nreverse merged-kvs) kvs))
911
+ (let ((updated (eliscript-data--construct-struct struct-name merged-kvs)))
912
+ (if (eliscript-persistent-record-meta instance)
913
+ (value-with-meta updated (eliscript-persistent-record-meta instance))
914
+ updated))))
915
+
916
+ (defmacro cl-defstruct-persistent (name &rest body)
917
+ "Define an immutable persistent record NAME with optional doc and fields."
918
+ (let* ((doc (and (stringp (car body)) (car body)))
919
+ (raw-fields (if doc (cdr body) body))
920
+ (parsed-fields (mapcar #'eliscript-data--parse-field-spec raw-fields))
921
+ (make-sym (intern (format "make-%s" name)))
922
+ (pred-sym (intern (format "%s-p" name)))
923
+ (with-sym (intern (format "%s-with" name)))
924
+ (accessor-forms nil))
925
+ (dolist (fspec parsed-fields)
926
+ (let* ((fname (plist-get fspec :name))
927
+ (acc-sym (intern (format "%s-%s" name fname))))
928
+ (push `(progn
929
+ (defun ,acc-sym (instance)
930
+ (unless (and (eliscript-persistent-record-p instance)
931
+ (eq (eliscript-persistent-record-type-name instance) ',name))
932
+ (error "%s expected a %s instance, got %S" ',acc-sym ',name instance))
933
+ (cdr (assq ',fname (eliscript-persistent-record-fields instance))))
934
+ (gv-define-setter ,acc-sym (_val _instance)
935
+ (error "Cannot mutate immutable persistent struct field %s via setf" ',acc-sym)))
936
+ accessor-forms)))
937
+ `(progn
938
+ (puthash ',name
939
+ (list :name ',name :doc ,doc :fields ',parsed-fields)
940
+ eliscript-data--struct-schemas)
941
+ (defun ,make-sym (&rest kvs)
942
+ (eliscript-data--construct-struct ',name kvs))
943
+ (defun ,pred-sym (obj)
944
+ (and (eliscript-persistent-record-p obj)
945
+ (eq (eliscript-persistent-record-type-name obj) ',name)
946
+ t))
947
+ (defun ,with-sym (instance &rest kvs)
948
+ (eliscript-data--update-struct ',name instance kvs))
949
+ ,@(nreverse accessor-forms)
950
+ ',name)))
951
+
952
+ (defun struct-validate (struct-name value)
953
+ "Validate that VALUE conforms to the schema of STRUCT-NAME."
954
+ (let ((schema (gethash struct-name eliscript-data--struct-schemas)))
955
+ (unless schema
956
+ (error "Unknown persistent struct %S" struct-name))
957
+ (dolist (fspec (plist-get schema :fields))
958
+ (let* ((fname (plist-get fspec :name))
959
+ (kw (intern (concat ":" (symbol-name fname))))
960
+ (val (cond
961
+ ((and (eliscript-persistent-record-p value)
962
+ (eq (eliscript-persistent-record-type-name value) struct-name))
963
+ (cdr (assq fname (eliscript-persistent-record-fields value))))
964
+ ((eliscript-data--map-like-p value)
965
+ (value-get value kw (value-get value fname)))
966
+ (t (error "struct-validate expected %s or map, got %S" struct-name value)))))
967
+ (eliscript-data--validate-field-value struct-name fspec val)))
968
+ t))
969
+
970
+ (defun struct-json-schema (struct-name)
971
+ "Export a persistent-map representing the JSON Schema for STRUCT-NAME."
972
+ (let ((schema (gethash struct-name eliscript-data--struct-schemas)))
973
+ (unless schema
974
+ (error "Unknown persistent struct %S" struct-name))
975
+ (let ((props (persistent-map))
976
+ (req nil))
977
+ (dolist (fspec (plist-get schema :fields))
978
+ (let* ((fname (plist-get fspec :name))
979
+ (kw (intern (concat ":" (symbol-name fname))))
980
+ (ftype (plist-get fspec :type))
981
+ (json-type (cond
982
+ ((eq ftype 'string) "string")
983
+ ((eq ftype 'integer) "integer")
984
+ ((memq ftype '(number float)) "number")
985
+ ((eq ftype 'boolean) "boolean")
986
+ (t "any")))
987
+ (fmap (persistent-map :type json-type)))
988
+ (when (plist-get fspec :doc)
989
+ (setq fmap (value-put fmap :description (plist-get fspec :doc))))
990
+ (when (plist-get fspec :min)
991
+ (setq fmap (value-put fmap :minimum (plist-get fspec :min))))
992
+ (when (plist-get fspec :max)
993
+ (setq fmap (value-put fmap :maximum (plist-get fspec :max))))
994
+ (setq props (value-put props kw fmap))
995
+ (unless (or (plist-get fspec :has-default) (eq ftype 'any))
996
+ (push (symbol-name fname) req))))
997
+ (persistent-map
998
+ :type "object"
999
+ :title (symbol-name struct-name)
1000
+ :description (or (plist-get schema :doc) "")
1001
+ :properties props
1002
+ :required (apply #'persistent-vector (nreverse req))))))
1003
+
1004
+ (defun eliscript-data--to-json-ready (val)
1005
+ "Convert persistent/Lisp VAL into a form suitable for `json-serialize'."
1006
+ (cond
1007
+ ((null val) nil)
1008
+ ((eq val t) t)
1009
+ ((or (numberp val) (stringp val)) val)
1010
+ ((keywordp val) (substring (symbol-name val) 1))
1011
+ ((symbolp val) (symbol-name val))
1012
+ ((or (eliscript-persistent-map-p val)
1013
+ (eliscript-persistent-sorted-map-p val)
1014
+ (eliscript-persistent-record-p val))
1015
+ (let ((ht (make-hash-table :test 'equal)))
1016
+ (dolist (cell (eliscript-data--map-entries val))
1017
+ (let ((k (if (keywordp (car cell))
1018
+ (substring (symbol-name (car cell)) 1)
1019
+ (format "%s" (car cell)))))
1020
+ (puthash k (eliscript-data--to-json-ready (cdr cell)) ht)))
1021
+ ht))
1022
+ ((or (eliscript-persistent-vector-p val)
1023
+ (eliscript-persistent-list-p val)
1024
+ (eliscript-persistent-set-p val)
1025
+ (eliscript-persistent-sorted-set-p val)
1026
+ (eliscript-persistent-queue-p val))
1027
+ (vconcat (mapcar #'eliscript-data--to-json-ready (eliscript-data--seq-elements val))))
1028
+ ((vectorp val)
1029
+ (vconcat (mapcar #'eliscript-data--to-json-ready (append val nil))))
1030
+ ((listp val)
1031
+ (vconcat (mapcar #'eliscript-data--to-json-ready val)))
1032
+ (t val)))
1033
+
1034
+ (defun eliscript-data--from-json-ready (val)
1035
+ "Convert parsed JSON VAL into Eliscript persistent maps and vectors."
1036
+ (cond
1037
+ ((eq val :null) nil)
1038
+ ((eq val :false) nil)
1039
+ ((hash-table-p val)
1040
+ (let ((kvs nil))
1041
+ (maphash (lambda (k v)
1042
+ (push (intern (concat ":" k)) kvs)
1043
+ (push (eliscript-data--from-json-ready v) kvs))
1044
+ val)
1045
+ (apply #'persistent-map (nreverse kvs))))
1046
+ ((vectorp val)
1047
+ (apply #'persistent-vector (mapcar #'eliscript-data--from-json-ready (append val nil))))
1048
+ (t val)))
1049
+
1050
+ (defun struct-to-json (struct-name instance)
1051
+ "Validate INSTANCE against STRUCT-NAME and serialize to a JSON string."
1052
+ (struct-validate struct-name instance)
1053
+ (json-serialize (eliscript-data--to-json-ready instance)
1054
+ :null-object nil
1055
+ :false-object :false))
1056
+
1057
+ (defun struct-from-json (struct-name json-str)
1058
+ "Parse JSON-STR and construct a validated persistent struct of STRUCT-NAME."
1059
+ (let* ((raw (json-parse-string json-str
1060
+ :object-type 'hash-table
1061
+ :array-type 'array
1062
+ :null-object :null
1063
+ :false-object :false))
1064
+ (kvs nil))
1065
+ (maphash (lambda (k v)
1066
+ (push (intern (concat ":" k)) kvs)
1067
+ (push (eliscript-data--from-json-ready v) kvs))
1068
+ raw)
1069
+ (eliscript-data--construct-struct struct-name (nreverse kvs))))
1070
+
1071
+ ;; ============================================================================
1072
+ ;; 6. Open Protocols & Value-Dispatched Multimethods
1073
+ ;; ============================================================================
1074
+
1075
+ (defvar eliscript-data--protocols (make-hash-table :test 'eq)
1076
+ "Registry of open protocols.")
1077
+
1078
+ (defvar eliscript-data--multimethods (make-hash-table :test 'eq)
1079
+ "Registry of value-dispatched multimethods.")
1080
+
1081
+ (defun eliscript-data--type-tag (val)
1082
+ "Return the protocol dispatch type symbol for VAL."
1083
+ (cond
1084
+ ((eliscript-persistent-record-p val)
1085
+ (eliscript-persistent-record-type-name val))
1086
+ ((eliscript-persistent-list-p val) 'persistent-list)
1087
+ ((eliscript-persistent-vector-p val) 'persistent-vector)
1088
+ ((eliscript-persistent-map-p val) 'persistent-map)
1089
+ ((eliscript-persistent-set-p val) 'persistent-set)
1090
+ ((eliscript-persistent-queue-p val) 'persistent-queue)
1091
+ ((and (consp val) (eq (car val) :eliscript-reified))
1092
+ (cadr val))
1093
+ ((null val) 'null)
1094
+ ((stringp val) 'string)
1095
+ ((integerp val) 'integer)
1096
+ ((floatp val) 'float)
1097
+ ((vectorp val) 'vector)
1098
+ ((consp val) 'cons)
1099
+ ((hash-table-p val) 'hash-table)
1100
+ (t (type-of val))))
1101
+
1102
+ (defun eliscript-data--dispatch-protocol (proto-name method-name args)
1103
+ "Dispatch METHOD-NAME of PROTO-NAME on first argument of ARGS."
1104
+ (let* ((target (car args))
1105
+ (tag (eliscript-data--type-tag target))
1106
+ (proto-table (gethash proto-name eliscript-data--protocols))
1107
+ (type-table (and proto-table (gethash tag proto-table)))
1108
+ (fn (and type-table (gethash method-name type-table))))
1109
+ (unless fn
1110
+ (error "No implementation of protocol %S method %S for %S (tag %S)"
1111
+ proto-name method-name target tag))
1112
+ (apply fn args)))
1113
+
1114
+ (defmacro defprotocol (name &rest method-sigs)
1115
+ "Define an open protocol NAME with METHOD-SIGS."
1116
+ (let ((forms nil))
1117
+ (dolist (sig method-sigs)
1118
+ (when (consp sig)
1119
+ (let ((mname (car sig)))
1120
+ (push `(defun ,mname (&rest args)
1121
+ (eliscript-data--dispatch-protocol ',name ',mname args))
1122
+ forms))))
1123
+ `(progn
1124
+ (unless (gethash ',name eliscript-data--protocols)
1125
+ (puthash ',name (make-hash-table :test 'eq) eliscript-data--protocols))
1126
+ ,@(nreverse forms)
1127
+ ',name)))
1128
+
1129
+ (defun eliscript-data--register-protocol-impl (proto-name type-sym method-name fn)
1130
+ "Register FN as implementation of METHOD-NAME for TYPE-SYM in PROTO-NAME."
1131
+ (let ((proto-table (or (gethash proto-name eliscript-data--protocols)
1132
+ (let ((ht (make-hash-table :test 'eq)))
1133
+ (puthash proto-name ht eliscript-data--protocols)
1134
+ ht))))
1135
+ (let ((type-table (or (gethash type-sym proto-table)
1136
+ (let ((ht (make-hash-table :test 'eq)))
1137
+ (puthash type-sym ht proto-table)
1138
+ ht))))
1139
+ (puthash method-name fn type-table))))
1140
+
1141
+ (defmacro extend-protocol (proto-name type-sym &rest method-impls)
1142
+ "Extend PROTO-NAME to TYPE-SYM with METHOD-IMPLS."
1143
+ (let ((forms nil))
1144
+ (dolist (impl method-impls)
1145
+ (let ((mname (car impl))
1146
+ (margs (cadr impl))
1147
+ (mbody (cddr impl)))
1148
+ (push `(eliscript-data--register-protocol-impl
1149
+ ',proto-name ',type-sym ',mname
1150
+ (lambda ,margs ,@mbody))
1151
+ forms)))
1152
+ `(progn ,@(nreverse forms) ',proto-name)))
1153
+
1154
+ (defalias 'defclass-protocol #'extend-protocol)
1155
+
1156
+ (defmacro reify-protocol (proto-name &rest method-impls)
1157
+ "Create an anonymous instance implementing PROTO-NAME with METHOD-IMPLS."
1158
+ (let ((anon-tag (make-symbol "reified-instance"))
1159
+ (forms nil))
1160
+ (dolist (impl method-impls)
1161
+ (let ((mname (car impl))
1162
+ (margs (cadr impl))
1163
+ (mbody (cddr impl)))
1164
+ (push `(eliscript-data--register-protocol-impl
1165
+ ',proto-name ',anon-tag ',mname
1166
+ (lambda ,margs ,@mbody))
1167
+ forms)))
1168
+ `(progn
1169
+ ,@(nreverse forms)
1170
+ (list :eliscript-reified ',anon-tag))))
1171
+
1172
+ (defmacro cl-defgeneric-value (name args &rest body)
1173
+ "Define a value-dispatched generic function NAME with ARGS and dispatch BODY."
1174
+ (let ((dispatch-expr (if (and (stringp (car body)) (cdr body))
1175
+ (cdr body)
1176
+ body)))
1177
+ `(progn
1178
+ (puthash ',name
1179
+ (list :dispatch (lambda ,args ,@dispatch-expr)
1180
+ :methods (make-hash-table :test 'equal))
1181
+ eliscript-data--multimethods)
1182
+ (defun ,name (&rest call-args)
1183
+ (let* ((entry (gethash ',name eliscript-data--multimethods))
1184
+ (dval (apply (plist-get entry :dispatch) call-args))
1185
+ (methods (plist-get entry :methods))
1186
+ (mfn (or (gethash dval methods)
1187
+ (gethash :default methods))))
1188
+ (unless mfn
1189
+ (error "No method in %s for dispatch value %S" ',name dval))
1190
+ (apply mfn call-args))))))
1191
+
1192
+ (defmacro cl-defmethod-value (name dispatch-val args &rest body)
1193
+ "Define a method on value-generic NAME for DISPATCH-VAL with ARGS and BODY."
1194
+ `(let ((entry (gethash ',name eliscript-data--multimethods)))
1195
+ (unless entry
1196
+ (error "cl-defmethod-value on unknown generic %S" ',name))
1197
+ (puthash ,dispatch-val (lambda ,args ,@body) (plist-get entry :methods))
1198
+ ',name))
1199
+
1200
+ ;; ============================================================================
1201
+ ;; 7. Observable State Cells (`state-cell`)
1202
+ ;; ============================================================================
1203
+
1204
+ (progn
1205
+ (cl-defstruct (eliscript-state-cell (:constructor eliscript-state-cell--create))
1206
+ val validator watches))
1207
+
1208
+ (defun state-cell (initial-value &rest options)
1209
+ "Create an observable state-cell holding INITIAL-VALUE."
1210
+ (let ((validator (plist-get options :validator)))
1211
+ (when (and validator (not (funcall validator initial-value)))
1212
+ (error "state-cell initial value %S rejected by :validator" initial-value))
1213
+ (eliscript-state-cell--create
1214
+ :val initial-value
1215
+ :validator validator
1216
+ :watches nil)))
1217
+
1218
+ (defun state-cell-p (obj)
1219
+ "Return t if OBJ is a state-cell."
1220
+ (and (eliscript-state-cell-p obj) t))
1221
+
1222
+ (defun cell-value (cell)
1223
+ "Return the current value of state-cell CELL."
1224
+ (unless (eliscript-state-cell-p cell)
1225
+ (error "cell-value expected a state-cell, got %S" cell))
1226
+ (eliscript-state-cell-val cell))
1227
+
1228
+ (defun cell-reset! (cell new-val)
1229
+ "Synchronously set CELL to NEW-VAL after `:validator' and notify watches."
1230
+ (unless (eliscript-state-cell-p cell)
1231
+ (error "cell-reset! expected a state-cell, got %S" cell))
1232
+ (let ((validator (eliscript-state-cell-validator cell))
1233
+ (old-val (eliscript-state-cell-val cell)))
1234
+ (when (and validator (not (funcall validator new-val)))
1235
+ (error "state-cell validator rejected new value %S" new-val))
1236
+ (setf (eliscript-state-cell-val cell) new-val)
1237
+ (dolist (w (eliscript-state-cell-watches cell))
1238
+ (funcall (cdr w) (car w) cell old-val new-val))
1239
+ new-val))
1240
+
1241
+ (defun cell-update! (cell fn &rest args)
1242
+ "Update CELL by applying FN to its current value and ARGS."
1243
+ (cell-reset! cell (apply fn (cell-value cell) args)))
1244
+
1245
+ (defun cell-watch (cell key callback)
1246
+ "Register CALLBACK under KEY to be notified when CELL changes."
1247
+ (let ((existing (eliscript-state-cell-watches cell)))
1248
+ (setf (eliscript-state-cell-watches cell)
1249
+ (cons (cons key callback)
1250
+ (cl-remove-if (lambda (w) (equal (car w) key)) existing)))
1251
+ cell))
1252
+
1253
+ (defun cell-unwatch (cell key)
1254
+ "Remove watch KEY from CELL."
1255
+ (setf (eliscript-state-cell-watches cell)
1256
+ (cl-remove-if (lambda (w) (equal (car w) key))
1257
+ (eliscript-state-cell-watches cell)))
1258
+ cell)
1259
+
1260
+ ;; ============================================================================
1261
+ ;; 8. Delay, Memoize, Lazy Sequences, Transducers & Scoped Transients
1262
+ ;; ============================================================================
1263
+
1264
+ (progn
1265
+ (cl-defstruct (eliscript-delay (:constructor eliscript-delay--create))
1266
+ thunk realized value))
1267
+
1268
+ (defmacro delay (&rest body)
1269
+ "Create a delayed computation from BODY."
1270
+ `(eliscript-delay--create :thunk (lambda () ,@body) :realized nil :value nil))
1271
+
1272
+ (defun delay-p (obj)
1273
+ "Return t if OBJ is a delay object."
1274
+ (and (eliscript-delay-p obj) t))
1275
+
1276
+ (defun realized-p (d)
1277
+ "Return t if delay or lazy-seq D has been realized."
1278
+ (cond
1279
+ ((eliscript-delay-p d) (and (eliscript-delay-realized d) t))
1280
+ (t nil)))
1281
+
1282
+ (defun force (d)
1283
+ "Force delay D (caching its result) or return D if not a delay."
1284
+ (if (eliscript-delay-p d)
1285
+ (progn
1286
+ (unless (eliscript-delay-realized d)
1287
+ (setf (eliscript-delay-value d) (funcall (eliscript-delay-thunk d)))
1288
+ (setf (eliscript-delay-realized d) t)
1289
+ (setf (eliscript-delay-thunk d) nil))
1290
+ (eliscript-delay-value d))
1291
+ d))
1292
+
1293
+ (defun memoize (fn)
1294
+ "Return a memoized version of function FN."
1295
+ (let ((cache (make-hash-table :test 'equal))
1296
+ (miss (make-symbol "miss")))
1297
+ (lambda (&rest args)
1298
+ (let ((cached (gethash args cache miss)))
1299
+ (if (eq cached miss)
1300
+ (let ((res (apply fn args)))
1301
+ (puthash args res cache)
1302
+ res)
1303
+ cached)))))
1304
+
1305
+ (progn
1306
+ (cl-defstruct (eliscript-lazy-seq (:constructor eliscript-lazy-seq--create))
1307
+ generator))
1308
+
1309
+ (defun lazy-seq-p (obj)
1310
+ "Return t if OBJ is a lazy sequence."
1311
+ (and (eliscript-lazy-seq-p obj) t))
1312
+
1313
+ (defmacro lazy-seq (&rest body)
1314
+ "Construct a lazy sequence whose elements are computed by BODY."
1315
+ `(eliscript-lazy-seq--create :generator (lambda () ,@body)))
1316
+
1317
+ (defun eliscript-lazy-seq--step (s)
1318
+ "Realize one step of sequence S into nil or (head . rest-seq)."
1319
+ (cond
1320
+ ((null s) nil)
1321
+ ((eliscript-lazy-seq-p s)
1322
+ (eliscript-lazy-seq--step (funcall (eliscript-lazy-seq-generator s))))
1323
+ ((consp s) s)
1324
+ (t (eliscript-data--seq-elements s))))
1325
+
1326
+ (defun eliscript-lazy-seq--realize-list (s)
1327
+ "Realize bounded lazy sequence S into an Emacs list."
1328
+ (let ((acc nil)
1329
+ (cur (eliscript-lazy-seq--step s)))
1330
+ (while cur
1331
+ (push (car cur) acc)
1332
+ (setq cur (eliscript-lazy-seq--step (cdr cur))))
1333
+ (nreverse acc)))
1334
+
1335
+ (defun lazy-range (&optional start end step)
1336
+ "Return a potentially infinite lazy sequence of numbers."
1337
+ (let ((s (or start 0))
1338
+ (st (or step 1)))
1339
+ (cl-labels ((gen (cur)
1340
+ (lazy-seq
1341
+ (if (and end (if (> st 0) (>= cur end) (<= cur end)))
1342
+ nil
1343
+ (cons cur (gen (+ cur st)))))))
1344
+ (gen s))))
1345
+
1346
+ (defun lazy-map (fn seq)
1347
+ "Lazily map FN over SEQ."
1348
+ (cl-labels ((gen (cur)
1349
+ (lazy-seq
1350
+ (let ((step (eliscript-lazy-seq--step cur)))
1351
+ (when step
1352
+ (cons (funcall fn (car step))
1353
+ (gen (cdr step))))))))
1354
+ (gen seq)))
1355
+
1356
+ (defun lazy-filter (pred seq)
1357
+ "Lazily filter SEQ by PRED."
1358
+ (cl-labels ((gen (cur)
1359
+ (lazy-seq
1360
+ (let ((step (eliscript-lazy-seq--step cur))
1361
+ (found nil))
1362
+ (while (and step (not found))
1363
+ (if (funcall pred (car step))
1364
+ (setq found (cons (car step) (gen (cdr step))))
1365
+ (setq step (eliscript-lazy-seq--step (cdr step)))))
1366
+ found))))
1367
+ (gen seq)))
1368
+
1369
+ (defun lazy-take (n seq)
1370
+ "Lazily take at most N elements from SEQ."
1371
+ (cl-labels ((gen (rem cur)
1372
+ (lazy-seq
1373
+ (when (> rem 0)
1374
+ (let ((step (eliscript-lazy-seq--step cur)))
1375
+ (when step
1376
+ (cons (car step)
1377
+ (gen (1- rem) (cdr step)))))))))
1378
+ (gen n seq)))
1379
+
1380
+ ;; Transducers
1381
+
1382
+ (progn
1383
+ (cl-defstruct (eliscript-reduced (:constructor eliscript-reduced--create))
1384
+ val))
1385
+
1386
+ (defun map-transducer (fn)
1387
+ "Return a mapping transducer applying FN."
1388
+ (lambda (rf)
1389
+ (lambda (acc &optional input)
1390
+ (if (= (length (list input)) 0)
1391
+ acc
1392
+ (funcall rf acc (funcall fn input))))))
1393
+
1394
+ (defun filter-transducer (pred)
1395
+ "Return a filtering transducer keeping elements satisfying PRED."
1396
+ (lambda (rf)
1397
+ (lambda (acc &optional input)
1398
+ (if (funcall pred input)
1399
+ (funcall rf acc input)
1400
+ acc))))
1401
+
1402
+ (defun take-transducer (n)
1403
+ "Return a stateful transducer taking at most N elements."
1404
+ (lambda (rf)
1405
+ (let ((remaining n))
1406
+ (lambda (acc &optional input)
1407
+ (if (> remaining 0)
1408
+ (progn
1409
+ (setq remaining (1- remaining))
1410
+ (let ((res (funcall rf acc input)))
1411
+ (if (<= remaining 0)
1412
+ (eliscript-reduced--create :val res)
1413
+ res)))
1414
+ (eliscript-reduced--create :val acc))))))
1415
+
1416
+ (defun seq-transduce (xform f init coll)
1417
+ "Transduce COLL using transducer XFORM, reducing function F, and INIT."
1418
+ (let ((rf (funcall xform f))
1419
+ (acc init)
1420
+ (elems (eliscript-data--seq-elements coll)))
1421
+ (catch 'reduced-done
1422
+ (dolist (item elems)
1423
+ (let ((next (funcall rf acc item)))
1424
+ (if (eliscript-reduced-p next)
1425
+ (progn
1426
+ (setq acc (eliscript-reduced-val next))
1427
+ (throw 'reduced-done acc))
1428
+ (setq acc next)))))
1429
+ acc))
1430
+
1431
+ ;; Scoped Transients (`with-transient`, `conj!`, `assoc!`, `dissoc!`)
1432
+
1433
+ (progn
1434
+ (cl-defstruct (eliscript-transient (:constructor eliscript-transient--create))
1435
+ kind active data meta comparator))
1436
+
1437
+ (defun eliscript-data--make-transient (source)
1438
+ "Create an active transient builder from persistent collection SOURCE."
1439
+ (cond
1440
+ ((eliscript-persistent-vector-p source)
1441
+ (eliscript-transient--create
1442
+ :kind 'vector :active t
1443
+ :data (append (eliscript-persistent-vector-items source) nil)
1444
+ :meta (eliscript-persistent-vector-meta source)))
1445
+ ((eliscript-persistent-list-p source)
1446
+ (eliscript-transient--create
1447
+ :kind 'list :active t
1448
+ :data (copy-sequence (eliscript-persistent-list-items source))
1449
+ :meta (eliscript-persistent-list-meta source)))
1450
+ ((eliscript-persistent-map-p source)
1451
+ (eliscript-transient--create
1452
+ :kind 'map :active t
1453
+ :data (copy-sequence (eliscript-persistent-map-entries source))
1454
+ :meta (eliscript-persistent-map-meta source)))
1455
+ ((eliscript-persistent-set-p source)
1456
+ (eliscript-transient--create
1457
+ :kind 'set :active t
1458
+ :data (copy-sequence (eliscript-persistent-set-items source))
1459
+ :meta (eliscript-persistent-set-meta source)))
1460
+ (t (error "with-transient requires a persistent collection, got %S" source))))
1461
+
1462
+ (defun eliscript-data--seal-transient (builder)
1463
+ "Seal transient BUILDER and return the resulting persistent collection."
1464
+ (unless (and (eliscript-transient-p builder) (eliscript-transient-active builder))
1465
+ (error "Transient builder is already sealed"))
1466
+ (setf (eliscript-transient-active builder) nil)
1467
+ (let ((kind (eliscript-transient-kind builder))
1468
+ (data (eliscript-transient-data builder))
1469
+ (meta (eliscript-transient-meta builder)))
1470
+ (cond
1471
+ ((eq kind 'vector)
1472
+ (eliscript-persistent-vector--create :items (vconcat data) :meta meta))
1473
+ ((eq kind 'list)
1474
+ (eliscript-persistent-list--create :items data :meta meta))
1475
+ ((eq kind 'map)
1476
+ (eliscript-persistent-map--create :entries data :meta meta))
1477
+ ((eq kind 'set)
1478
+ (eliscript-persistent-set--create :items data :meta meta)))))
1479
+
1480
+ (defun eliscript-data--ensure-active-transient (builder op-name)
1481
+ "Ensure BUILDER is an active transient for OP-NAME."
1482
+ (unless (and (eliscript-transient-p builder) (eliscript-transient-active builder))
1483
+ (error "%s called on expired or sealed transient builder" op-name)))
1484
+
1485
+ (defun conj! (builder &rest items)
1486
+ "Mutate active transient BUILDER in place by appending ITEMS."
1487
+ (eliscript-data--ensure-active-transient builder 'conj!)
1488
+ (let ((kind (eliscript-transient-kind builder)))
1489
+ (dolist (it items builder)
1490
+ (cond
1491
+ ((eq kind 'vector)
1492
+ (setf (eliscript-transient-data builder)
1493
+ (append (eliscript-transient-data builder) (list it))))
1494
+ ((eq kind 'list)
1495
+ (setf (eliscript-transient-data builder)
1496
+ (cons it (eliscript-transient-data builder))))
1497
+ ((eq kind 'set)
1498
+ (unless (cl-some (lambda (x) (value-equal-p x it))
1499
+ (eliscript-transient-data builder))
1500
+ (setf (eliscript-transient-data builder)
1501
+ (append (eliscript-transient-data builder) (list it)))))
1502
+ ((eq kind 'map)
1503
+ (if (consp it)
1504
+ (setf (eliscript-transient-data builder)
1505
+ (eliscript-data--assoc-alist
1506
+ (eliscript-transient-data builder) (car it) (cdr it)))
1507
+ (error "conj! on transient map expects pair, got %S" it)))))))
1508
+
1509
+ (defun assoc! (builder key val)
1510
+ "Mutate active transient BUILDER by associating KEY with VAL."
1511
+ (eliscript-data--ensure-active-transient builder 'assoc!)
1512
+ (setf (eliscript-transient-data builder)
1513
+ (eliscript-data--assoc-alist (eliscript-transient-data builder) key val))
1514
+ builder)
1515
+
1516
+ (defun dissoc! (builder key)
1517
+ "Mutate active transient BUILDER by removing KEY."
1518
+ (eliscript-data--ensure-active-transient builder 'dissoc!)
1519
+ (setf (eliscript-transient-data builder)
1520
+ (eliscript-data--dissoc-alist (eliscript-transient-data builder) key))
1521
+ builder)
1522
+
1523
+ (defmacro with-transient (binding &rest body)
1524
+ "Bind `(VAR SOURCE)' to a transient builder, run BODY, and seal result."
1525
+ (let ((var (car binding))
1526
+ (source (cadr binding)))
1527
+ `(let ((,var (eliscript-data--make-transient ,source)))
1528
+ (unwind-protect
1529
+ (progn
1530
+ ,@body
1531
+ (eliscript-data--seal-transient ,var))
1532
+ (when (eliscript-transient-active ,var)
1533
+ (setf (eliscript-transient-active ,var) nil))))))
1534
+
1535
+ (progn
1536
+ (defun eliscript-data-reset-state! ()
1537
+ "Reset protocol, multimethod, and struct registries for isolated tests."
1538
+ (clrhash eliscript-data--struct-schemas)
1539
+ (clrhash eliscript-data--protocols)
1540
+ (clrhash eliscript-data--multimethods)))
1541
+
1542
+ (provide 'eliscript-data)
1543
+
1544
+ ;;; eliscript-data.el ends here