-
Notifications
You must be signed in to change notification settings - Fork 213
/
core.cljc
2816 lines (2600 loc) · 127 KB
/
core.cljc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(ns malli.core
(:refer-clojure :exclude [eval type -deref deref -lookup -key assert])
#?(:cljs (:require-macros malli.core))
(:require #?(:clj [clojure.walk :as walk])
[clojure.core :as c]
[malli.impl.regex :as re]
[malli.impl.util :as miu]
[malli.registry :as mr]
[malli.sci :as ms])
#?(:clj (:import #?(:bb (clojure.lang Associative IPersistentCollection MapEntry IPersistentVector PersistentArrayMap)
:clj (clojure.lang Associative IPersistentCollection MapEntry IPersistentVector LazilyPersistentVector PersistentArrayMap))
(java.util.concurrent.atomic AtomicReference)
(java.util.regex Pattern))))
(declare schema schema? into-schema into-schema? type eval default-registry
-simple-schema -val-schema -ref-schema -schema-schema -registry
parser unparser ast from-ast -instrument ^:private -safely-countable?)
;;
;; protocols and records
;;
(defprotocol IntoSchema
(-type [this] "returns type of the schema")
(-type-properties [this] "returns schema type properties")
(-properties-schema [this options] "maybe returns :map schema describing schema properties")
(-children-schema [this options] "maybe returns sequence schema describing schema children")
(-into-schema [this properties children options] "creates a new schema instance"))
(defprotocol Schema
(-validator [this] "returns a predicate function that checks if the schema is valid")
(-explainer [this path] "returns a function of `x in acc -> maybe errors` to explain the errors for invalid values")
(-parser [this] "return a function of `x -> parsed-x | ::m/invalid` to explain how schema is valid.")
(-unparser [this] "return the inverse (partial) function wrt. `-parser`; `parsed-x -> x | ::m/invalid`")
(-transformer [this transformer method options]
"returns a function to transform the value for the given schema and method.
Can also return nil instead of `identity` so that more no-op transforms can be elided.")
(-walk [this walker path options] "walks the schema and it's children, ::m/walk-entry-vals, ::m/walk-refs, ::m/walk-schema-refs options effect how walking is done.")
(-properties [this] "returns original schema properties")
(-options [this] "returns original options")
(-children [this] "returns schema children")
(-parent [this] "returns the IntoSchema instance")
(-form [this] "returns original form of the schema"))
(defprotocol AST
(-to-ast [this options] "schema to ast")
(-from-ast [this ast options] "ast to schema"))
(defprotocol EntryParser
(-entry-keyset [this])
(-entry-children [this])
(-entry-entries [this])
(-entry-forms [this]))
(defprotocol EntrySchema
(-entries [this] "returns sequence of `key -val-schema` entries")
(-entry-parser [this]))
(defprotocol Cached
(-cache [this]))
(defprotocol LensSchema
(-keep [this] "returns truthy if schema contributes to value path")
(-get [this key default] "returns schema at key")
(-set [this key value] "returns a copy with key having new value"))
(defprotocol RefSchema
(-ref [this] "returns the reference name")
(-deref [this] "returns the referenced schema"))
(defprotocol Walker
(-accept [this schema path options])
(-inner [this schema path options])
(-outer [this schema path children options]))
(defprotocol Transformer
(-transformer-chain [this] "returns transformer chain as a vector of maps with :name, :encoders, :decoders and :options")
(-value-transformer [this schema method options] "returns a value transforming interceptor for the given schema and method"))
(defprotocol RegexSchema
(-regex-op? [this] "is this a regex operator (e.g. :cat, :*...)")
(-regex-validator [this] "returns the raw internal regex validator implementation")
(-regex-explainer [this path] "returns the raw internal regex explainer implementation")
(-regex-unparser [this] "returns the raw internal regex unparser implementation")
(-regex-parser [this] "returns the raw internal regex parser implementation")
(-regex-transformer [this transformer method options] "returns the raw internal regex transformer implementation")
(-regex-min-max [this nested?] "returns size of the sequence as {:min min :max max}. nil max means unbounded. nested? is true when this schema is nested inside an outer regex schema."))
(defprotocol FunctionSchema
(-function-schema? [this])
(-function-schema-arities [this])
(-function-info [this])
(-instrument-f [schema props f options]))
(defprotocol DistributiveSchema
(-distributive-schema? [this])
(-distribute-to-children [this f options]))
(defn -ref-schema? [x] (#?(:clj instance?, :cljs implements?) malli.core.RefSchema x))
(defn -entry-parser? [x] (#?(:clj instance?, :cljs implements?) malli.core.EntryParser x))
(defn -entry-schema? [x] (#?(:clj instance?, :cljs implements?) malli.core.EntrySchema x))
(defn -cached? [x] (#?(:clj instance?, :cljs implements?) malli.core.Cached x))
(defn -ast? [x] (#?(:clj instance?, :cljs implements?) malli.core.AST x))
(defn -transformer? [x] (#?(:clj instance?, :cljs implements?) malli.core.Transformer x))
(extend-type #?(:clj Object, :cljs default)
FunctionSchema
(-function-schema? [_] false)
(-function-info [_])
(-function-schema-arities [_])
(-instrument-f [_ _ _ _])
DistributiveSchema
(-distributive-schema? [_] false)
(-distribute-to-children [this _ _]
(throw (ex-info "Not distributive" {:schema this})))
RegexSchema
(-regex-op? [_] false)
(-regex-validator [this]
(if (-ref-schema? this)
(-regex-validator (-deref this))
(re/item-validator (-validator this))))
(-regex-explainer [this path]
(if (-ref-schema? this)
(-regex-explainer (-deref this) path)
(re/item-explainer path this (-explainer this path))))
(-regex-parser [this]
(if (-ref-schema? this)
(-regex-parser (-deref this))
(re/item-parser (parser this))))
(-regex-unparser [this]
(if (-ref-schema? this)
(-regex-unparser (-deref this))
(re/item-unparser (unparser this))))
(-regex-transformer [this transformer method options]
(if (-ref-schema? this)
(-regex-transformer (-deref this) transformer method options)
(re/item-transformer method (-validator this) (or (-transformer this transformer method options) identity))))
(-regex-min-max [_ _] {:min 1, :max 1}))
#?(:clj (defmethod print-method ::into-schema [v ^java.io.Writer w] (.write w (str "#IntoSchema{:type " (pr-str (-type ^IntoSchema v)) "}"))))
#?(:clj (defmethod print-method ::schema [v ^java.io.Writer w] (.write w (pr-str (-form ^Schema v)))))
;;
;; impl
;;
(defn -deprecated! [x] (println "DEPRECATED:" x))
(defn -exception [type data] (ex-info (str type) {:type type, :message type, :data data}))
(defn -fail!
([type] (-fail! type nil))
([type data] (throw (-exception type data))))
(defn -safe-pred [f] #(try (boolean (f %)) (catch #?(:clj Exception, :cljs js/Error) _ false)))
(defn -keyword->string [x]
(if (keyword? x)
(if-let [nn (namespace x)]
(str nn "/" (name x))
(name x))
x))
(defn -guard [pred tf] (when tf (fn [x] (if (pred x) (tf x) x))))
(defn -unlift-keys [m prefix]
(reduce-kv #(if (= (name prefix) (namespace %2)) (assoc %1 (keyword (name %2)) %3) %1) {} m))
(defn ^:no-doc -check-children? [] true)
(defn -check-children!
([type properties children props]
(-deprecated! "use (m/-check-children! type properties children min max) instead.")
(-check-children! type properties children (:min props) (:max props)))
([type properties children min max]
(when (-check-children?)
(when-let [size (and (or (sequential? children) (nil? children)) (count children))]
(when (or (and min (< size ^long min)) (and max (> size ^long max)))
(-fail! ::child-error {:type type, :properties properties, :children children, :min min, :max max}))))))
(defn -pointer [id schema options] (-into-schema (-schema-schema {:id id}) nil [schema] options))
(defn -reference? [?schema] (or (string? ?schema) (qualified-ident? ?schema) (var? ?schema)))
(defn -lazy [ref options] (-into-schema (-ref-schema {:lazy true}) nil [ref] options))
(defn -boolean-fn [x] (cond (boolean? x) (constantly x) (ifn? x) x :else (constantly false)))
(defn -infer [children]
(loop [[[s f] & fs] [[:string string?] [:keyword keyword?] [:symbol symbol?] [:int int?] [:double float?]]]
(if (every? f children) s (when fs (recur fs)))))
(defn -comp
([] identity)
([f] f)
([f g] (fn [x] (f (g x))))
([f g h] (fn [x] (f (g (h x)))))
#?@(:clj [([f1 f2 f3 f4] (fn [x] (-> x f4 f3 f2 f1)))
([f1 f2 f3 f4 f5] (fn [x] (-> x f5 f4 f3 f2 f1)))
([f1 f2 f3 f4 f5 f6] (fn [x] (-> x f6 f5 f4 f3 f2 f1)))
([f1 f2 f3 f4 f5 f6 f7] (fn [x] (-> x f7 f6 f5 f4 f3 f2 f1)))
([f1 f2 f3 f4 f5 f6 f7 f8] (fn [x] (-> x f8 f7 f6 f5 f4 f3 f2 f1)))
([f1 f2 f3 f4 f5 f6 f7 f8 & fs] (let [f9 (apply -comp fs)]
(fn [x] (-> x f9 f8 f7 f6 f5 f4 f3 f2 f1))))]
:cljs [([f1 f2 f3 & fs] (let [f4 (apply -comp fs)]
(fn [x] (-> x f4 f3 f2 f1))))]))
(defn -update [x k f] (assoc x k (f (get x k))))
(defn -equals [x y] (or (identical? x y) (= x y)))
(defn -vmap ([os] (miu/-vmap identity os)) ([f os] (miu/-vmap f os)))
(defn -memoize [f]
(let [value #?(:clj (AtomicReference. nil), :cljs (atom nil))]
(fn [] #?(:clj (or (.get value) (do (.set value (f)) (.get value))), :cljs (or @value (reset! value (f)))))))
(defn -group-by-arity! [infos]
(let [aritys (atom #{})]
(reduce
(fn [acc {:keys [min arity] :as info}]
(let [vararg (= :varargs arity)
min (if (and vararg (@aritys min)) (inc (apply max (filter int? @aritys))) min)]
(cond (and vararg (@aritys arity))
(-fail! ::multiple-varargs {:infos infos})
(@aritys min)
(-fail! ::duplicate-arities {:infos infos})
:else
(do (swap! aritys conj arity)
(assoc acc arity (assoc info :min min)))))) {} infos)))
(defn- -re-min-max [f {min' :min, max' :max} child]
(let [{min'' :min max'' :max} (-regex-min-max child true)]
(cond-> {:min (f (or min' 0) min'')} (and max' max'') (assoc :max (f max' max'')))))
(defn- -re-alt-min-max [{min' :min, max' :max} child]
(let [{min'' :min max'' :max} (-regex-min-max child true)]
(cond-> {:min (min (or min' miu/+max-size+) min'')} (and max' max'') (assoc :max (max max' max'')))))
;;
;; registry
;;
(defn- -register-var [registry ?v]
(let [[v pred] (if (vector? ?v) ?v [?v @?v])
name (-> v meta :name)
schema (-simple-schema {:type name, :pred pred})]
(-> registry
(assoc name schema)
(assoc @v schema))))
(defn -registry {:arglists '([] [{:keys [registry]}])}
([] default-registry)
([opts] (or (when opts (mr/registry (opts :registry))) default-registry)))
(defn -property-registry [m options f]
(let [options (assoc options ::allow-invalid-refs true)]
(reduce-kv (fn [acc k v] (assoc acc k (f (schema v options)))) {} m)))
(defn -delayed-registry [m f]
(reduce-kv (fn [acc k v] (assoc acc k (reify IntoSchema (-into-schema [_ _ _ options] (f v options))))) {} m))
(defn- -lookup [?schema options]
(let [registry (-registry options)]
(or (mr/-schema registry ?schema)
(when-some [p (some-> registry (mr/-schema (c/type ?schema)))]
(when (schema? ?schema)
(when (= p (-parent ?schema))
(-fail! ::infinitely-expanding-schema {:schema ?schema})))
(-into-schema p nil [?schema] options)))))
(defn- -lookup! [?schema ?form f rec options]
(or (and f (f ?schema) ?schema)
(if-let [?schema (-lookup ?schema options)]
(cond-> ?schema rec (recur ?form f rec options))
(-fail! ::invalid-schema {:schema ?schema, :form ?form}))))
(defn -properties-and-options [properties options f]
(if-let [r (:registry properties)]
(let [options (-update options :registry #(mr/composite-registry r (or % (-registry options))))]
[(assoc properties :registry (-property-registry r options f)) options])
[properties options]))
;;
;; cache
;;
(defn -create-cache [_options] (atom {}))
(defn -cached [s k f]
(if (-cached? s)
(let [c (-cache s)]
(or (@c k) ((swap! c assoc k (f s)) k)))
(f s)))
;;
;; forms
;;
(defn -raw-form [type properties children]
(let [has-children (seq children), has-properties (seq properties)]
(cond (and has-properties has-children) (reduce conj [type properties] children)
has-properties [type properties]
has-children (let [fchild (nth children 0)]
(reduce conj
(cond-> [type]
(or (map? fchild)
(nil? fchild)) (conj nil))
children))
:else type)))
(defn -create-form [type properties children options]
(let [properties (when (seq properties)
(let [registry (:registry properties)]
(cond-> properties registry (assoc :registry (-property-registry registry options -form)))))]
(-raw-form type properties children)))
(defn -simple-form [parent properties children f options]
(-create-form (-type parent) properties (-vmap f children) options))
(defn -create-entry-form [parent properties entry-parser options]
(-create-form (-type parent) properties (-entry-forms entry-parser) options))
;;
;; walkers
;;
(defn -inner-indexed [walker path children options]
(-vmap (fn [[i c]] (-inner walker c (conj path i) options)) (map-indexed vector children)))
(defn -inner-entries [walker path entries options]
(-vmap (fn [[k s]] [k (-properties s) (-inner walker s (conj path k) options)]) entries))
(defn -walk-entries [schema walker path options]
(when (-accept walker schema path options)
(-outer walker schema path (-inner-entries walker path (-entries schema) options) options)))
(defn -walk-indexed [schema walker path options]
(when (-accept walker schema path options)
(-outer walker schema path (-inner-indexed walker path (-children schema) options) options)))
(defn -walk-leaf [schema walker path options]
(when (-accept walker schema path options)
(-outer walker schema path (-children schema) options)))
;;
;; lenses
;;
(defn -set-children [schema children]
(if (-equals children (-children schema))
schema (-into-schema (-parent schema) (-properties schema) children (-options schema))))
(defn -set-properties [schema properties]
(if (-equals properties (-properties schema))
schema (-into-schema (-parent schema) properties (or (and (-entry-schema? schema) (-entry-parser schema)) (-children schema)) (-options schema))))
(defn -update-properties [schema f & args]
(-set-properties schema (not-empty (apply f (-properties schema) args))))
(defn -update-options [schema f]
(-into-schema (-parent schema) (-properties schema) (-children schema) (f (-options schema))))
(defn -set-assoc-children [schema key value]
(-set-children schema (assoc (-children schema) key value)))
(defn -get-entries [schema key default]
(or (some (if (and (vector? key) (= ::find (nth key 0)))
(fn [e] (when (= (nth e 0) (nth key 1)) e))
(fn [e] (when (= (nth e 0) key) (nth e 2))))
(-children schema)) default))
;;
;; entries
;;
(defn -simple-entry-parser [keyset children forms]
(let [entries (map (fn [[k p s]] (miu/-tagged k (-val-schema s p))) children)]
(reify EntryParser
(-entry-keyset [_] keyset)
(-entry-children [_] children)
(-entry-entries [_] entries)
(-entry-forms [_] forms))))
(defn- -update-parsed [entry-parser ?key value options]
(let [[override k p] (if (and (vector? ?key) (nth ?key 0)) (cons true ?key) [false ?key])
keyset (-entry-keyset entry-parser)
children (-entry-children entry-parser)
forms (-entry-forms entry-parser)
s (when value (schema value options))
i (:order (keyset k))]
(if (nil? s)
;; remove
(letfn [(cut [v] (into (subvec v 0 i) (subvec v (inc i))))]
(-simple-entry-parser (dissoc keyset k) (cut children) (cut forms)))
(let [p (if i (if override p (nth (children i) 1)) p)
c [k p s]
f (if (seq p) [k p (-form s)] [k (-form s)])]
(if i
;; update
(-simple-entry-parser keyset (assoc children i c) (assoc forms i f))
;; assoc
(-simple-entry-parser (assoc keyset k {:order (count keyset)}) (conj children c) (conj forms f)))))))
(defn -set-entries
([schema ?key value]
(if-let [entry-parser (-entry-parser schema)]
(-set-children schema (-update-parsed entry-parser ?key value (-options schema)))
(let [found (atom nil)
[key props override] (if (vector? ?key) [(nth ?key 0) (second ?key) true] [?key])
children (cond-> (-vmap (fn [[k p :as entry]]
(if (= key k)
(do (reset! found true) [key (if override props p) value])
entry))
(-children schema))
(not @found) (conj (if key [key props value] (-fail! ::key-missing)))
:always (->> (filter (fn [e] (-> e last some?)))))]
(-set-children schema children)))))
(defn- -parse-entry [e naked-keys lazy-refs options i ^objects -children ^objects -forms ^objects -keyset]
(letfn [(-collect [k c f i]
(let [i (int i)]
(aset -keyset (* 2 i) k)
(aset -keyset (inc (* 2 i)) {:order i})
(aset -children i c)
(aset -forms i f)
(unchecked-inc-int i)))
(-schema [e] (schema (cond-> e (and (-reference? e) lazy-refs) (-lazy options)) options))
(-parse-ref-entry [e]
(let [s (-schema e)
c [e nil s]]
(-collect e c e i)))
(-parse-ref-vector1 [e e0]
(let [s (-schema e0)
c [e0 nil s]]
(-collect e0 c e i)))
(-parse-ref-vector2 [e e0 e1]
(let [s (-schema e0)
c [e0 e1 s]]
(-collect e0 c e i)))
(-parse-entry-else2 [e0 e1]
(let [s (-schema e1)
f [e0 (-form s)]
c [e0 nil s]]
(-collect e0 c f i)))
(-parse-entry-else3 [e0 e1 e2]
(let [s (-schema e2)
f' (-form s)
f (if e1 [e0 e1 f'] [e0 f'])
c [e0 e1 s]]
(-collect e0 c f i)))]
(if (vector? e)
(let [ea (object-array e)
n (alength ea)
e0 (aget ea 0)]
(if (== n 1)
(if (and (-reference? e0) naked-keys)
(-parse-ref-vector1 e e0)
(-fail! ::invalid-entry {:entry e}))
(let [e1 (aget ea 1)]
(if (== n 2)
(if (and (-reference? e0) (map? e1))
(if naked-keys (-parse-ref-vector2 e e0 e1) i)
(-parse-entry-else2 e0 e1))
(let [e2 (aget ea 2)]
(-parse-entry-else3 e0 e1 e2))))))
(if (and naked-keys (-reference? e))
(-parse-ref-entry e)
(-fail! ::invalid-entry {:entry e})))))
(defn -eager-entry-parser [children props options]
(letfn [(-vec [^objects arr] #?(:bb (vec arr) :clj (LazilyPersistentVector/createOwning arr), :cljs (vec arr)))
(-map [^objects arr] #?(:bb (let [m (apply array-map arr)]
(when-not (= (* 2 (count m)) (count arr))
(-fail! ::duplicate-keys {:arr arr})) m)
:clj (try (PersistentArrayMap/createWithCheck arr)
(catch Exception _ (-fail! ::duplicate-keys {:arr arr})))
:cljs (let [m (apply array-map arr)]
(when-not (= (* 2 (count m)) (count arr))
(-fail! ::duplicate-keys {:arr arr})) m)))
(-arange [^objects arr to]
#?(:clj (let [-arr (object-array to)] (System/arraycopy arr 0 -arr 0 to) -arr)
:cljs (.slice arr 0 to)))]
(let [{:keys [naked-keys lazy-refs]} props
ca (object-array children)
n (alength ca)
-children (object-array n)
-forms (object-array n)
-keyset (object-array (* 2 n))]
(loop [i (int 0), ci (int 0)]
(if (== ci n)
(let [f (if (== ci i) -vec #(-vec (-arange % i)))]
(-simple-entry-parser (-map -keyset) (f -children) (f -forms)))
(recur (int (-parse-entry (aget ca i) naked-keys lazy-refs options i -children -forms -keyset))
(unchecked-inc-int ci)))))))
(defn -lazy-entry-parser [?children props options]
(let [parser (delay (-eager-entry-parser ?children props options))]
(reify EntryParser
(-entry-keyset [_] (-entry-keyset @parser))
(-entry-children [_] (-entry-children @parser))
(-entry-entries [_] (-entry-entries @parser))
(-entry-forms [_] (-entry-forms @parser)))))
(defn -create-entry-parser [?children props options]
(cond (-entry-parser? ?children) ?children
(or (:lazy props) (::lazy-entries options)) (-lazy-entry-parser ?children props options)
:else (-eager-entry-parser ?children props options)))
(defn -default-entry [e] (-equals (nth e 0) ::default))
(defn -default-entry-schema [children] (some (fn [e] (when (-default-entry e) (nth e 2))) children))
;;
;; transformers
;;
(defn -no-op-transformer []
(reify Transformer
(-transformer-chain [_])
(-value-transformer [_ _ _ _])))
(defn -intercepting
([interceptor] (-intercepting interceptor nil))
([{:keys [enter leave]} f] (some->> [leave f enter] (keep identity) (seq) (apply -comp))))
(defn -into-transformer [x]
(cond
(-transformer? x) x
(fn? x) (-into-transformer (x))
(nil? x) (-no-op-transformer)
:else (-fail! ::invalid-transformer {:value x})))
(defn -parent-children-transformer [parent children transformer method options]
(let [parent-transformer (-value-transformer transformer parent method options)
child-transformers (into [] (keep #(-transformer % transformer method options)) children)
child-transformer (when (seq child-transformers) (apply -comp (rseq child-transformers)))]
(-intercepting parent-transformer child-transformer)))
(defn -map-transformer [ts]
#?(:bb (fn [x] (reduce (fn child-transformer [m [k t]]
(if-let [entry (find m k)]
(assoc m k (t (val entry)))
m)) x ts))
:clj (let [not-found (Object.)]
(apply -comp (map (fn child-transformer [[k t]]
(fn [^Associative x]
(let [val (.valAt x k not-found)]
(if (identical? val not-found)
x (.assoc x k (t val)))))) (rseq ts))))
:cljs (fn [x] (reduce (fn child-transformer [m [k t]]
(if-let [entry (find m k)]
(assoc m k (t (val entry)))
m)) x ts))))
(defn -tuple-transformer [ts] (fn [x] (reduce-kv -update x ts)))
(defn -collection-transformer [t empty]
#?(:bb (fn [x] (into (when x empty) (map t) x))
:clj (fn [x] (let [i (.iterator ^Iterable x)]
(loop [x ^IPersistentCollection empty]
(if (.hasNext i)
(recur (.cons x (t (.next i))))
x))))
:cljs (fn [x] (into (when x empty) (map t) x))))
(defn -or-transformer [this transformer child-schemas method options]
(let [this-transformer (-value-transformer transformer this method options)]
(if (seq child-schemas)
(let [transformers (-vmap #(or (-transformer % transformer method options) identity) child-schemas)
validators (-vmap -validator child-schemas)]
(-intercepting this-transformer
(if (= :decode method)
(fn [x]
(reduce-kv
(fn [acc i transformer]
(let [x* (transformer x)]
(if ((nth validators i) x*)
(reduced x*)
(if (-equals acc ::nil) x* acc))))
::nil transformers))
(fn [x]
(reduce-kv
(fn [x i validator] (if (validator x) (reduced ((nth transformers i) x)) x))
x validators)))))
(-intercepting this-transformer))))
;;
;; ast
;;
(defn -parse-entry-ast [ast options]
(let [ast-entry-order (::ast-entry-order options)
keyset (:keys ast)
->child (fn [[k v]] [k (:properties v) (from-ast (:value v) options)])
children (delay (-vmap ->child (cond->> keyset ast-entry-order (sort-by #(:order (val %)) keyset))))]
(reify EntryParser
(-entry-keyset [_] keyset)
(-entry-children [_] @children)
(-entry-entries [_] (-vmap (fn [[k p s]] (miu/-tagged k (-val-schema s p))) @children))
(-entry-forms [_] (->> @children (-vmap (fn [[k p v]] (if p [k p (-form v)] [k (-form v)]))))))))
(defn -from-entry-ast [parent ast options]
(-into-schema parent (:properties ast) (-parse-entry-ast ast options) options))
(defn -ast [acc properties options]
(let [registry (when-let [registry (:registry properties)]
(into {} (map (fn [[k v]] [k (ast v options)])) registry))
properties (not-empty (cond-> properties registry (dissoc :registry)))]
(cond-> acc properties (assoc :properties properties) registry (assoc :registry registry))))
(defn -entry-ast [schema keyset]
(-ast {:type (type schema)
:keys (reduce (fn [acc [k p s]] (assoc acc k (cond-> {:order (-> keyset (get k) :order),
:value (ast s)} p (assoc :properties p))))
{} (-children schema))}
(-properties schema)
(-options schema)))
(defn -from-child-ast [parent ast options]
(-into-schema parent (:properties ast) [(from-ast (:child ast) options)] options))
(defn -to-child-ast [schema]
(-ast {:type (type schema), :child (ast (nth (-children schema) 0))} (-properties schema) (-options schema)))
(defn -from-value-ast [parent ast options]
(-into-schema parent (:properties ast) (when-let [value (:value ast)] [value]) options))
(defn -to-value-ast [schema]
(-ast {:type (type schema), :value (nth (-children schema) 0)} (-properties schema) (-options schema)))
(defn -from-type-ast [parent ast options]
(-into-schema parent (:properties ast) nil options))
(defn -to-type-ast [schema]
(-ast {:type (type schema)} (-properties schema) (-options schema)))
;;
;; simple schema helpers
;;
(defn -min-max-pred [f]
(fn [{:keys [min max]}]
(cond
(not (or min max)) nil
(and (and min max) f) (fn [x] (let [size (f x)]
(and (<= min size) (<= size max))))
(and min max) (fn [x] (and (<= min x) (<= x max)))
(and min f) (fn [x] (<= min (f x)))
min (fn [x] (<= min x))
(and max f) (fn [x] (<= (f x) max))
max (fn [x] (<= x max)))))
(defn- -safe-count [x]
(if (-safely-countable? x)
(count x)
(reduce (fn [cnt _] (inc cnt)) 0 x)))
(defn -validate-limits [min max] (or ((-min-max-pred -safe-count) {:min min :max max}) (constantly true)))
(defn -needed-bounded-checks [min max options]
(c/max (or (some-> max inc) 0)
(or min 0)
(::coll-check-limit options 101)))
(defn -validate-bounded-limits [needed min max]
(or ((-min-max-pred #(bounded-count needed %)) {:min min :max max}) (constantly true)))
(defn -qualified-keyword-pred [properties]
(when-let [ns-name (some-> properties :namespace name)]
(fn [x] (= (namespace x) ns-name))))
;;
;; Schemas
;;
(defn -simple-schema [props]
(let [{:keys [type type-properties pred property-pred min max from-ast to-ast compile]
:or {min 0, max 0, from-ast -from-value-ast, to-ast -to-type-ast}} props]
(if (fn? props)
(do
(-deprecated! "-simple-schema doesn't take fn-props, use :compile property instead")
(-simple-schema {:compile (fn [c p _] (props c p))}))
^{:type ::into-schema}
(reify
AST
(-from-ast [parent ast options] (from-ast parent ast options))
IntoSchema
(-type [_] type)
(-type-properties [_] type-properties)
(-properties-schema [_ _])
(-children-schema [_ _])
(-into-schema [parent properties children options]
(if compile
(-into-schema (-simple-schema (merge (dissoc props :compile) (compile properties children options))) properties children options)
(let [form (delay (-simple-form parent properties children identity options))
cache (-create-cache options)]
(-check-children! type properties children min max)
^{:type ::schema}
(reify
AST
(-to-ast [this _] (to-ast this))
Schema
(-validator [_]
(if-let [pvalidator (when property-pred (property-pred properties))]
(fn [x] (and (pred x) (pvalidator x))) pred))
(-explainer [this path]
(let [validator (-validator this)]
(fn explain [x in acc]
(if-not (validator x) (conj acc (miu/-error path in this x)) acc))))
(-parser [this]
(let [validator (-validator this)]
(fn [x] (if (validator x) x ::invalid))))
(-unparser [this] (-parser this))
(-transformer [this transformer method options]
(-intercepting (-value-transformer transformer this method options)))
(-walk [this walker path options] (-walk-leaf this walker path options))
(-properties [_] properties)
(-options [_] options)
(-children [_] children)
(-parent [_] parent)
(-form [_] @form)
Cached
(-cache [_] cache)
LensSchema
(-keep [_])
(-get [_ _ default] default)
(-set [this key _] (-fail! ::non-associative-schema {:schema this, :key key}))))))))))
(defn -nil-schema [] (-simple-schema {:type :nil, :pred nil?}))
(defn -any-schema [] (-simple-schema {:type :any, :pred any?}))
(defn -some-schema [] (-simple-schema {:type :some, :pred some?}))
(defn -string-schema [] (-simple-schema {:type :string, :pred string?, :property-pred (-min-max-pred count)}))
(defn -int-schema [] (-simple-schema {:type :int, :pred int?, :property-pred (-min-max-pred nil)}))
(defn -float-schema [] (-simple-schema {:type :float, :pred float?, :property-pred (-min-max-pred nil)}))
(defn -double-schema [] (-simple-schema {:type :double, :pred double?, :property-pred (-min-max-pred nil)}))
(defn -boolean-schema [] (-simple-schema {:type :boolean, :pred boolean?}))
(defn -keyword-schema [] (-simple-schema {:type :keyword, :pred keyword?}))
(defn -symbol-schema [] (-simple-schema {:type :symbol, :pred symbol?}))
(defn -qualified-keyword-schema [] (-simple-schema {:type :qualified-keyword, :pred qualified-keyword?, :property-pred -qualified-keyword-pred}))
(defn -qualified-symbol-schema [] (-simple-schema {:type :qualified-symbol, :pred qualified-symbol?}))
(defn -uuid-schema [] (-simple-schema {:type :uuid, :pred uuid?}))
(defn -and-schema []
^{:type ::into-schema}
(reify IntoSchema
(-type [_] :and)
(-type-properties [_])
(-properties-schema [_ _])
(-children-schema [_ _])
(-into-schema [parent properties children options]
(-check-children! :and properties children 1 nil)
(let [children (-vmap #(schema % options) children)
form (delay (-simple-form parent properties children -form options))
cache (-create-cache options)
->parser (fn [f m] (let [parsers (m (-vmap f children))]
#(reduce (fn [x parser] (miu/-map-invalid reduced (parser x))) % parsers)))]
^{:type ::schema}
(reify
Schema
(-validator [_]
(let [validators (-vmap -validator children)] (miu/-every-pred validators)))
(-explainer [_ path]
(let [explainers (-vmap (fn [[i c]] (-explainer c (conj path i))) (map-indexed vector children))]
(fn explain [x in acc] (reduce (fn [acc' explainer] (explainer x in acc')) acc explainers))))
(-parser [_] (->parser -parser seq))
(-unparser [_] (->parser -unparser rseq))
(-transformer [this transformer method options]
(-parent-children-transformer this children transformer method options))
(-walk [this walker path options] (-walk-indexed this walker path options))
(-properties [_] properties)
(-options [_] options)
(-children [_] children)
(-parent [_] parent)
(-form [_] @form)
Cached
(-cache [_] cache)
LensSchema
(-keep [_])
(-get [_ key default] (get children key default))
(-set [this key value] (-set-assoc-children this key value)))))))
(defn -or-schema []
^{:type ::into-schema}
(reify IntoSchema
(-type [_] :or)
(-type-properties [_])
(-properties-schema [_ _])
(-children-schema [_ _])
(-into-schema [parent properties children options]
(-check-children! :or properties children 1 nil)
(let [children (-vmap #(schema % options) children)
form (delay (-simple-form parent properties children -form options))
cache (-create-cache options)
->parser (fn [f] (let [parsers (-vmap f children)]
#(reduce (fn [_ parser] (miu/-map-valid reduced (parser %))) ::invalid parsers)))]
^{:type ::schema}
(reify
Schema
(-validator [_]
(let [validators (-vmap -validator children)] (miu/-some-pred validators)))
(-explainer [_ path]
(let [explainers (-vmap (fn [[i c]] (-explainer c (conj path i))) (map-indexed vector children))]
(fn explain [x in acc]
(reduce
(fn [acc' explainer]
(let [acc'' (explainer x in acc')]
(if (identical? acc' acc'') (reduced acc) acc'')))
acc explainers))))
(-parser [_] (->parser -parser))
(-unparser [_] (->parser -unparser))
(-transformer [this transformer method options]
(-or-transformer this transformer children method options))
(-walk [this walker path options] (-walk-indexed this walker path options))
(-properties [_] properties)
(-options [_] options)
(-children [_] children)
(-parent [_] parent)
(-form [_] @form)
Cached
(-cache [_] cache)
LensSchema
(-keep [_])
(-get [_ key default] (get children key default))
(-set [this key value] (-set-assoc-children this key value)))))))
(defn -orn-schema []
^{:type ::into-schema}
(reify
AST
(-from-ast [parent ast options] (-from-entry-ast parent ast options))
IntoSchema
(-type [_] :orn)
(-type-properties [_])
(-properties-schema [_ _])
(-children-schema [_ _])
(-into-schema [parent properties children options]
(-check-children! :orn properties children 1 nil)
(let [entry-parser (-create-entry-parser children {:naked-keys true} options)
form (delay (-create-entry-form parent properties entry-parser options))
cache (-create-cache options)]
^{:type ::schema}
(reify
AST
(-to-ast [this _] (-entry-ast this (-entry-keyset entry-parser)))
Schema
(-validator [this] (miu/-some-pred (-vmap (fn [[_ _ c]] (-validator c)) (-children this))))
(-explainer [this path]
(let [explainers (-vmap (fn [[k _ c]] (-explainer c (conj path k))) (-children this))]
(fn explain [x in acc]
(reduce
(fn [acc' explainer]
(let [acc'' (explainer x in acc')]
(if (identical? acc' acc'') (reduced acc) acc'')))
acc explainers))))
(-parser [this]
(let [parsers (-vmap (fn [[k _ c]]
(let [c (-parser c)]
(fn [x] (miu/-map-valid #(reduced (miu/-tagged k %)) (c x)))))
(-children this))]
(fn [x] (reduce (fn [_ parser] (parser x)) x parsers))))
(-unparser [this]
(let [unparsers (into {} (map (fn [[k _ c]] [k (-unparser c)])) (-children this))]
(fn [x]
(if (miu/-tagged? x)
(if-some [unparse (get unparsers (key x))]
(unparse (val x))
::invalid)
::invalid))))
(-transformer [this transformer method options]
(-or-transformer this transformer (-vmap #(nth % 2) (-children this)) method options))
(-walk [this walker path options] (-walk-entries this walker path options))
(-properties [_] properties)
(-options [_] options)
(-children [_] (-entry-children entry-parser))
(-parent [_] parent)
(-form [_] @form)
EntrySchema
(-entries [_] (-entry-entries entry-parser))
(-entry-parser [_] entry-parser)
Cached
(-cache [_] cache)
LensSchema
(-keep [_])
(-get [this key default] (-get-entries this key default))
(-set [this key value] (-set-entries this key value)))))))
(defn -not-schema []
^{:type ::into-schema}
(reify
AST
(-from-ast [parent ast options] (-from-child-ast parent ast options))
IntoSchema
(-type [_] :not)
(-type-properties [_])
(-properties-schema [_ _])
(-children-schema [_ _])
(-into-schema [parent properties children options]
(-check-children! :not properties children 1 1)
(let [[schema :as children] (-vmap #(schema % options) children)
form (delay (-simple-form parent properties children -form options))
cache (-create-cache options)]
^{:type ::schema}
(reify
AST
(-to-ast [this _] (-to-child-ast this))
Schema
(-validator [_] (complement (-validator schema)))
(-explainer [this path]
(let [validator (-validator this)]
(fn explain [x in acc]
(if-not (validator x) (conj acc (miu/-error (conj path 0) in this x)) acc))))
(-parser [this]
(let [validator (-validator this)]
(fn [x] (if (validator x) x ::invalid))))
(-unparser [this] (-parser this))
(-transformer [this transformer method options]
(-parent-children-transformer this children transformer method options))
(-walk [this walker path options] (-walk-indexed this walker path options))
(-properties [_] properties)
(-options [_] options)
(-children [_] children)
(-parent [_] parent)
(-form [_] @form)
Cached
(-cache [_] cache)
LensSchema
(-keep [_])
(-get [_ key default] (get children key default))
(-set [this key value] (-set-assoc-children this key value)))))))
(defn -val-schema
([schema properties]
(-into-schema (-val-schema) properties (list schema) (-options schema)))
([]
^{:type ::into-schema}
(reify
AST
(-from-ast [parent ast options] (-from-child-ast parent ast options))
IntoSchema
(-type [_] ::val)
(-type-properties [_])
(-properties-schema [_ _])
(-children-schema [_ _])
(-into-schema [parent properties children options]
#_(-check-children! ::val properties children 1 1)
(let [children (-vmap #(schema % options) children)
form (delay (-simple-form parent properties children -form options))
schema (first children)
cache (-create-cache options)]
^{:type ::schema}
(reify
AST
(-to-ast [this _] (-to-child-ast this))
Schema
(-validator [_] (-validator schema))
(-explainer [_ path] (-explainer schema path))
(-parser [_] (-parser schema))
(-unparser [_] (-unparser schema))
(-transformer [this transformer method options]
(-parent-children-transformer this (list schema) transformer method options))
(-walk [this walker path options]
(if (::walk-entry-vals options)
(when (-accept walker this path options)
(-outer walker this path (list (-inner walker schema path options)) options))
(-walk schema walker path options)))
(-properties [_] properties)
(-options [_] (-options schema))
(-children [_] [schema])
(-parent [_] parent)
(-form [_] @form)
Cached
(-cache [_] cache)
LensSchema
(-keep [_])
(-get [_ key default] (if (= 0 key) schema default))
(-set [_ key value] (when (= 0 key) (-val-schema value properties)))
RefSchema
(-ref [_])
(-deref [_] schema)))))))
(defn -map-schema
([]
(-map-schema {:naked-keys true}))
([opts] ;; :naked-keys, :lazy, :pred
^{:type ::into-schema}
(reify
AST
(-from-ast [parent ast options] (-from-entry-ast parent ast options))
IntoSchema
(-type [_] (:type opts :map))