/
encore.cljc
7838 lines (6609 loc) · 297 KB
/
encore.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 taoensso.encore
"Extended core library for Clojure/Script that emphasizes:
* Cross-platform API
* Flexibility
* Performance
* Backwards compatibility
This lib's mostly for my own use and for advanced users that feel
comfortable reading this source. Not providing much beginner-oriented
documentation for this, sorry.
Common naming conventions used across my libs:
**foo** - Dynamic var
foo! - Fn with side-effects, or that should otherwise be used cautiously
foo? - Truthy val or fn that returns truthy val
foo!? - Fn that has side-effects (or requires caution) and that return
a truthy val. Note: !?, not ?!
foo$ - Fn that's notably expensive to compute (e.g. hits db)
foo_ - Derefable val (e.g. atom, volatile, delay, etc.)
foo__ - Derefable in a derefable (e.g. delay in an atom), etc.
_ - Unnamed val
_foo - Named but unused val
?foo - Optional val (emphasize that val may be nil)
foo* - A variation of `foo` (e.g. `foo*` macro vs `foo` fn)
foo' - ''
-foo - Public implementation detail or intermediate (e.g. uncoerced) val
>foo - Val \"to foo\" (e.g. >sender, >host), or fn to put/coerce/transform
<foo - Val \"from foo\" (e.g. <sender, <host), or fn to take/coerce/transform
->foo - Fn to put/coerce/transform
Type affixes may be used for clarity:
<prefix>-<name> - m-users, v-users, n-users, etc. (also nusers when unambiguous)
<name>-<postfix> - users-map, users-vec, user-count, etc.
Regarding name heirarchy:
When there's a significant num of syms with a meaningful hierarchy,
prefer names with descending hierarchy to emphasize structure and
related groups/functionality, e.g.:
`user-add`, `user-remove`, `user-mod` vs
`add-user`, `remove-user`, `mod-user`, etc.
Commit message tags (in priority order):
[wip] - Work-in-progress (still under development)
[mod] - Modify behaviour (=> breaking), [mod!], [mod!!], etc. for attention
[fix] - Fix broken behaviour (=> usu. non-breaking)
[new] - Add new behaviour (=> non-breaking)
[doc] - Documentation changes besides those better labelled as [mod], [fix], or [new]
[nop] - Other non-breaking changes (to implementation details, non-code changes, etc.)
[x] [y] - Single commit with multiple tags (in priority order), try avoid
Example commit messages:
v1.0.0 (2022-01-27) ; Tagged release
[new] [#122] Add new feature x (@contributor)
Version numbers:
Ver tables: X.Y.Z (without backticks)
Min ver: vX.Y.Z+
Elsewhere: vX.Y.Z"
{:author "Peter Taoussanis (@ptaoussanis)"}
(:refer-clojure :exclude
[if-let if-some if-not when when-not when-some when-let cond defonce binding
run! some? ident? float? boolean? uri? indexed? bytes?
int? pos-int? neg-int? nat-int? inst?
simple-ident? qualified-ident?
simple-symbol? qualified-symbol?
simple-keyword? qualified-keyword?
format update-in merge merge-with
memoize abs ex-message ex-data ex-cause
newline satisfies? uuid
pr prn print println])
#?(:clj
(:require
[clojure.string :as str]
[clojure.set :as set]
[clojure.java.io :as jio]
[clojure.tools.reader.edn :as edn]
[taoensso.truss :as truss])
:cljs
(:require
[clojure.string :as str]
[clojure.set :as set]
[cljs.reader]
[cljs.tools.reader.edn :as edn]
[goog.object :as gobj]
[goog.array :as garray]
[goog.string :as gstr]
[goog.string.format]
[goog.string.StringBuffer]
[goog.events :as gevents]
[goog.net.XhrIo :as gxhr]
[goog.net.XhrIoPool :as gxhr-pool]
[goog.Uri.QueryData :as gquery-data]
[goog.net.EventType]
[goog.net.ErrorCode]
[taoensso.truss :as truss]))
#?(:clj
(:import
[java.util Date Locale TimeZone]
[java.text SimpleDateFormat]
[java.util.concurrent CountDownLatch]
[java.util.concurrent.atomic AtomicReference]
[java.util.function UnaryOperator])
:cljs
(:require-macros
[taoensso.encore :as enc-macros :refer
[have have! have? compile-if try-eval qb
if-let if-some if-not when when-not when-some when-let -cond cond cond!
def* defonce try* catching binding -cas!? now-udt* now-nano* min* max*
name-with-attrs deprecated new-object defalias throws throws?
identical-kw? satisfies? satisfies! instance! use-transient?
with-default-print-opts typed-val]])))
(def encore-version [3 105 1])
(comment "∴ ∵ ℕ ℤ ℝ ∞ ≠ ∈ ∉ ⇒⇔ → × ⊃⊂ ⊇⊆ ≡ ¬ ∀ ∃ ∝"
(set! *unchecked-math* :warn-on-boxed)
(set! *unchecked-math* false))
#?(:clj
(do ; Bootstrap Truss aliases
(defmacro ^:private -have [& args] `(taoensso.truss/have ~@args))
(defmacro ^:private -have? [& args] `(taoensso.truss/have? ~@args))))
(comment
(remove-ns 'taoensso.encore)
(:api (interns-overview))
(test/run-tests))
;;;;
#?(:clj
(defmacro ^:no-doc typed-val
"Private, don't use.
Expands to `{:value ~x, :type (type ~x)}."
{:added "Encore v3.105.0 (2024-04-29)"}
[x] `{:value ~x, :type (type ~x)}))
(defn unexpected-arg!
"Throws runtime `ExceptionInfo` to indicate an unexpected argument.
Takes optional kvs for merging into exception's data map.
(let [mode :unexpected]
(case mode
:read (do <...>)
:write (do <...>)
(unexpected-arg! mode
{:context `my-function
:param 'mode
:expected #{:read :write}}))) =>
Unexpected argument: :unexpected
{:arg {:value :unexpected, :type clojure.lang.Keyword},
:context 'taoensso.encore/my-function
:param 'mode
:expected #{:read :write}}"
{:added "Encore v3.51.0 (2023-03-13)"
:arglists
'([arg]
[arg {:keys [msg context param expected ...]}]
[arg & {:keys [msg context param expected ...]}])}
([arg ] (unexpected-arg! arg nil))
([arg opts]
(throw
(ex-info (or (get opts :msg) (str "Unexpected argument: " arg))
(conj {:arg (typed-val arg)} (dissoc opts :msg)))))
([arg k1 v1 ] (unexpected-arg! arg {k1 v1}))
([arg k1 v1 k2 v2 ] (unexpected-arg! arg {k1 v1, k2 v2}))
([arg k1 v1 k2 v2 k3 v3 ] (unexpected-arg! arg {k1 v1, k2 v2, k3 v3}))
([arg k1 v1 k2 v2 k3 v3 k4 v4] (unexpected-arg! arg {k1 v1, k2 v2, k3 v3, k4 v4})))
(comment (unexpected-arg! :arg :expected '#{string?}))
#?(:clj
(defn ^:no-doc have-resource? "Private, don't use."
[res-name] (boolean (try (jio/resource res-name) (catch Throwable _)))))
#?(:clj
(defn ^:no-doc have-class?
"Private, don't use."
[class-name]
(boolean
(try
(Class/forName class-name true (.getContextClassLoader (Thread/currentThread)))
(catch Throwable _)))))
(comment (have-class? "org.slf4j.Logger"))
(defn ^:no-doc list-form?
"Private, don't use.
Returns true if given a list or Cons (=> possible call form)."
{:added "Encore v3.105.0 (2024-04-29)"}
[x] (or (list? x) (instance? #?(:clj clojure.lang.Cons :cljs cljs.core/Cons) x)))
;;;; Core macros
#?(:clj
(defmacro compile-if
"Evaluates `test`. If it returns logical true (and doesn't throw), expands
to `then`, otherwise expands to `else`."
{:style/indent 1}
([test then ] `(compile-if ~test ~then nil))
([test then else]
(if (try (eval test) (catch Throwable _ false))
`(do ~then)
`(do ~else)))))
#?(:clj (defmacro compile-when {:style/indent 1} [test & body] `(compile-if ~test (do ~@body) nil)))
#?(:clj
(defmacro try-eval
"If `form` can be successfully evaluated at macro-expansion time, expands to `form`.
Otherwise expands to `nil`."
{:added "Encore v3.50.0 (2023-03-07)"}
[form] `(compile-if ~form ~form nil)))
(comment (macroexpand '(try-eval (com.google.common.io.BaseEncoding/base16))))
#?(:clj
(defmacro if-let
"Supersets `core/if-let` functionality. Like `core/if-let` but supports multiple
bindings, and unconditional bindings with `:let`:
(if-let [x (rand-nth [:x1 :x2 false nil ]) ; Bind truthy x, or -> `else`
:let [y (rand-nth [:y1 :y2 false nil x ])] ; Bind any y
z (rand-nth [:z1 :z2 false nil x y]) ; Bind truthy z, or -> `else`
]
[:then-clause x y z]
[:else-clause])"
{:style/indent 1}
([bindings then ] `(if-let ~bindings ~then nil))
([bindings then else]
(let [s (seq bindings)]
(if s ; (if-let [] true false) => true
(let [[b1 b2 & bnext] s]
(if (= b1 :let)
`(let ~b2 (if-let ~(vec bnext) ~then ~else))
`(let [b2# ~b2]
(if b2#
(let [~b1 b2#]
(if-let ~(vec bnext) ~then ~else))
~else))))
then)))))
#?(:clj
(defmacro if-some
"Supersets `core/if-some` functionality. Like `core/if-some` but supports multiple
bindings, and unconditional bindings with `:let`:
(if-some [x (rand-nth [:x1 :x2 false nil ]) ; Bind non-nil x, or -> `else`
:let [y (rand-nth [:y1 :y2 false nil x ])] ; Bind any y
z (rand-nth [:z1 :z2 false nil x y]) ; Bind non-nil z, or -> `else`
]
[:then-clause x y z]
[:else-clause])"
{:style/indent 1}
([bindings then] `(if-some ~bindings ~then nil))
([bindings then else]
(let [s (seq bindings)]
(if s ; (if-some [] true false) => true
(let [[b1 b2 & bnext] s]
(if (= b1 :let)
`(let ~b2 (if-some ~(vec bnext) ~then ~else))
`(let [b2# ~b2]
(if (nil? b2#)
~else
(let [~b1 b2#]
(if-some ~(vec bnext) ~then ~else))))))
then)))))
#?(:clj
(defmacro if-not
"Supersets `core/if-not` functionality.
Same as `encore/if-let` with `then` `and `else` forms swapped."
;; Also avoids unnecessary `(not test)`
{:style/indent 1}
([test-or-bindings then]
(if (vector? test-or-bindings)
`(if-let ~test-or-bindings nil ~then)
`(if ~test-or-bindings nil ~then)))
([test-or-bindings then else]
(if (vector? test-or-bindings)
`(if-let ~test-or-bindings ~else ~then)
`(if ~test-or-bindings ~else ~then)))))
#?(:clj
(defmacro when-let
"Supersets `core/when-let` functionality. Like `core/when-let` but supports multiple
bindings, and unconditional bindings with `:let`:
(when-let [x (rand-nth [:x1 :x2 false nil ]) ; Bind truthy x, or -> nil
:let [y (rand-nth [:y1 :y2 false nil x ])] ; Bind any y
z (rand-nth [:z1 :z2 false nil x y]) ; Bind truthy z, or -> nil
]
[:body x y z])"
;; Now a feature subset of all-case `when`
{:style/indent 1}
[bindings & body] `(if-let ~bindings (do ~@body))))
#?(:clj
(defmacro when
"Supersets `core/when` and `core/when-let` functionality. When `test-or-bindings` is
a vector, same as `encore/when-let`. Otherwise same as `core/when`."
{:style/indent 1}
[test-or-bindings & body]
(if (vector? test-or-bindings)
`(if-let ~test-or-bindings (do ~@body) nil)
`(if ~test-or-bindings (do ~@body) nil))))
#?(:clj
(defmacro when-not
"Supersets `core/when-not` functionality.
Same as `encore/if-let` with `body` as `else` form."
{:style/indent 1}
[test-or-bindings & body]
(if (vector? test-or-bindings)
`(if-let ~test-or-bindings nil (do ~@body))
`(if ~test-or-bindings nil (do ~@body)))))
#?(:clj
(defmacro when-some
"Supersets `core/when-some` functionality. Like `core/when-some` but supports multiple
bindings, and unconditional bindings with `:let`:
(when-some [x (rand-nth [:x1 :x2 false nil ]) ; Bind non-nil x, or -> `else`
:let [y (rand-nth [:y1 :y2 false nil x ])] ; Bind any y
z (rand-nth [:z1 :z2 false nil x y]) ; Bind non-nil z, or -> `else`
]
[:body x y z])"
{:style/indent 1}
[test-or-bindings & body]
(if (vector? test-or-bindings)
`(if-some ~test-or-bindings (do ~@body) nil)
`(if (nil? ~test-or-bindings) nil (do ~@body)))))
(comment
(if-let [a :a b (= a :a)] [a b] "else")
(if-let [a :a b (= a :b)] [a b] "else")
(if-some [a :a b (= a :b)] [a b] "else")
(when-let [a :a b nil] "true")
(when-let [:let [a :a b :b] c (str a b)] c))
;; (:ns &env) is nnil iff compiling for Cljs. This gives macros a way to produce
;; different code depending on target (Clj/s), something reader conditionals cannot do.
#?(:clj (defmacro if-clj [then & [else]] (if (:ns &env) else then)))
#?(:clj (defmacro if-cljs [then & [else]] (if (:ns &env) then else)))
#?(:clj
(defn compiling-cljs?
"Return truthy iff currently generating Cljs code.
See also `if-cljs`, `if-clj`."
[]
(when-let [ns (find-ns 'cljs.analyzer)]
(when-let [v (ns-resolve ns '*cljs-file*)]
(boolean @v)))))
(comment (compiling-cljs?))
#?(:clj
(defmacro binding
"For Clj: faster version of `core/binding`.
For Cljs: identical to `core/binding`."
{:added "Encore v3.98.0 (2024-04-08)"
:style/indent 1}
[bindings & body]
(if (:ns &env)
`(cljs.core/binding ~bindings ~@body)
(let [;; Avoids unnecessary runtime map construction
bindings-map ; #{<var-form> <val-form>}
(reduce-kv (fn [m k v] (assoc m `(var ~k) v))
{} (apply hash-map bindings))]
`(let [] ; Nb for frame
(push-thread-bindings ~bindings-map)
(try ~@body (finally (pop-thread-bindings))))))))
(comment
(do
(def ^:dynamic *d1* nil)
(def ^:dynamic *d2* nil)
(qb 1e6 ; [409.01 302.93]
(clojure.core/binding [*d1* :d1, *d2* :d2] [*d1* *d2*])
(binding [*d1* :d1, *d2* :d2] [*d1* *d2*]))))
#?(:clj
(defmacro ^:no-doc -cond [throw? & clauses]
(if-let [[test expr & more] (seq clauses)]
(if-not (next clauses)
test ; Implicit else
(case test
(true :else :default) expr ; Faster than (if <truthy> ...)
(false nil) `(-cond ~throw? ~@more) ; Faster than (if <falsey> ...)
:do `(do ~expr (-cond ~throw? ~@more))
:let `(let ~expr (-cond ~throw? ~@more))
:binding `(binding ~expr (-cond ~throw? ~@more))
:with-redefs `(with-redefs ~expr (-cond ~throw? ~@more)) ; Undocumented
:return-when `(if-let [x# ~expr] x# (-cond ~throw? ~@more)) ; ''
:return-some `(if-some [x# ~expr] x# (-cond ~throw? ~@more)) ; ''
:when `(when ~expr (-cond ~throw? ~@more)) ; ''
:when-not `(when-not ~expr (-cond ~throw? ~@more)) ; ''
:when-some `(when-some ~expr (-cond ~throw? ~@more)) ; ''
;;; 3-clause cases
(:if-let :if-some :if-not)
(if (empty? more) ; Missing 3rd clause
(throw
(ex-info (str "[encore/cond] Missing `then` clause for special test keyword: " test)
{:test-form test :expr-form expr}))
(case test
:if-let `(if-let ~expr ~(first more) (-cond ~throw? ~@(next more)))
:if-some `(if-some ~expr ~(first more) (-cond ~throw? ~@(next more)))
:if-not `(if-not ~expr ~(first more) (-cond ~throw? ~@(next more))) ; Undocumented
))
(if (keyword? test)
(throw ; Undocumented, but throws at compile-time so easy to catch
(ex-info (str "[encore/cond] Unrecognized special test keyword: " test)
{:test-form test :expr-form expr}))
(if (vector? test) ; Undocumented
`(if-let ~test ~expr (-cond ~throw? ~@more))
;; Experimental, assumes `not` = `core/not`:
(if (and (list-form? test) (= (first test) 'not))
`(if ~(second test) (-cond ~throw? ~@more) ~expr)
`(if ~test ~expr (-cond ~throw? ~@more)))))))
(when throw?
`(throw
(ex-info "[encore/cond!] No matching clause" {}))))))
#?(:clj
(defmacro cond
"Supersets `core/cond` functionality. Like `core/cond` but supports implicit
final `else` clause, and special clause keywords for advanced behaviour:
(cond
:let [x \"x\"] ; Establish let binding/s for remaining forms
:binding [*x* \"x\"] ; Establish dynamic binding/s for remaining forms
:do (println (str \"x value: \" x)) ; Eval expr for side-effects
:if-let [y \"y\"
z nil]
\"y and z were both truthy\"
:if-some [y \"y\"
z nil]
\"y and z were both non-nil\")
`:let` support inspired by <https://github.com/Engelberg/better-cond>.
Simple, flexible way to eliminate deeply-nested control flow code."
;; Also avoids unnecessary `(if :else ...)`, etc.
[& clauses] `(-cond false ~@clauses)))
#?(:clj
(defmacro cond!
"Like `cond` but throws on non-match like `case` and `condp`."
[& clauses] `(-cond true ~@clauses)))
(comment
[(macroexpand-all '(clojure.core/cond nil "a" nil "b" :else "c"))
(macroexpand-all '(cond nil "a" nil "b" :else "c"))
(macroexpand-all '(cond nil "a" nil "b" (println "bar")))
(macroexpand-all '(cond :when true :let [x "x"] :else x))
(macroexpand-all '(cond false 0 (not false) 1 2))
(macroexpand-all '(cond [a :A] a))]
(cond
:if-not [n "Stu"] "Don't have a name"
:else (str n " Smith"))
(cond false "false")
(cond! false "false")
(cond :if-let [])
(cond :if-let [a :a])
(cond :when [a :a])
(cond! :return-when (when true "foo"))
(cond! :return-when (when false "foo"))
[(macroexpand-all '(cond (= 1 0) "a"))
(macroexpand-all '(cond! (= 1 0) "a"))
(macroexpand-all '(cond :let [a :a] (= 1 0) "a"))
(macroexpand-all '(cond! :let [a :a] (= 1 0) "a"))
(macroexpand-all '(cond :if-let [a nil] a (= 1 0) "1=0" #_"default"))
(macroexpand-all '(cond! :if-let [a nil] a (= 1 0) "1=0" #_"default"))
(cond :if-let [a nil] a (= 1 0) "1=0" #_"default")
(cond! :if-let [a nil] a (= 1 0) "1=0" #_"default")])
#?(:cljs
(defn ^boolean some?
"Same as `core/some?` (added in Clojure v1.6)."
[x] (if (nil? x) false true))
:clj
(defn some?
"Same as `core/some?` (added in Clojure v1.6)."
{:inline (fn [x] `(if (identical? ~x nil) false true))}
[x] (if (identical? x nil) false true)))
(defmacro or-some
"Like `or`, but returns the first non-nil form (may be falsey)."
{:added "Encore v3.67.0 (2023-09-08)"}
([ ] nil)
([x ] x)
([x & next] `(let [x# ~x] (if (identical? x# nil) (or-some ~@next) x#))))
(comment (or-some nil nil false true))
(defn name-with-attrs
"Given a symbol and args, returns [<name-with-attrs-meta> <args> <attrs>]
with support for `defn` style `?docstring` and `?attrs-map`."
([sym args ] (name-with-attrs sym args nil))
([sym args attrs-merge]
(let [[?docstring args] (if (and (string? (first args)) (next args)) [(first args) (next args)] [nil args])
[attrs args] (if (and (map? (first args)) (next args)) [(first args) (next args)] [{} args])
attrs (if ?docstring (assoc attrs :doc ?docstring) attrs)
attrs (if-let [m (meta sym)] (conj m attrs) attrs)
attrs (conj attrs attrs-merge)]
[(with-meta sym attrs) args attrs])))
#?(:clj
(defmacro def*
"Like `core/def` but supports attrs map."
{:added "Encore v3.67.0 (2023-09-08)"
:style/indent 1}
[sym & args]
(let [[sym body] (name-with-attrs sym args)]
`(def ~sym ~@body))))
#?(:clj
(defmacro defonce
"Like `core/defonce` but supports docstring and attrs map."
{:style/indent 1}
[sym & args]
(let [[sym body] (name-with-attrs sym args)]
(if (:ns &env)
`(cljs.core/defonce ~sym ~@body)
`(clojure.core/defonce ~sym ~@body)))))
#?(:clj
(defmacro identical-kw?
"Returns true iff two keywords are identical.
Portable and maximally fast.
For Clj this expands to: `(identical? x y)`
For Cljs this expands to: `(keyword-identical? x y)`"
{:added "Encore v3.67.0 (2023-09-08)"}
[x y]
(if (:ns &env)
`(cljs.core/keyword-identical? ~x ~y)
`(identical? ~x ~y))))
#?(:clj
(defmacro case-eval
"Like `case` but test expressions are evaluated for their compile-time value."
{:style/indent 1}
[expr & clauses]
(let [default (when (odd? (count clauses)) (last clauses))
clauses (if default (butlast clauses) clauses)]
`(case ~expr
~@(map-indexed (fn [i# form#] (if (even? i#) (eval form#) form#)) clauses)
~(when default default)))))
#?(:clj
(defmacro doto-cond
"Cross between `doto`, `cond->` and `as->`."
{:style/indent 1}
[[sym x] & clauses]
(assert (even? (count clauses)))
(let [g (gensym)
pstep (fn [[test-expr step]]
`(when-let [~sym ~test-expr] (-> ~g ~step)))]
`(let [~g ~x]
~@(map pstep (partition 2 clauses))
~g))))
;;;;
(def ^:private core-merge #?(:clj clojure.core/merge :cljs cljs.core/merge))
(def ^:private core-update-in #?(:clj clojure.core/update-in :cljs cljs.core/update-in))
(declare merge update-in)
;;;;
#?(:clj
(defmacro declare-remote
"Declares given ns-qualified symbols, preserving metadata.
Clj only. Useful for circular dependencies."
[& syms]
(let [original-ns (str *ns*)]
`(do ~@(map (fn [s]
(let [ns (namespace s)
v (name s)
m (meta s)]
`(do (in-ns '~(symbol ns))
(declare ~(with-meta (symbol v) m))))) syms)
(in-ns '~(symbol original-ns))))))
#?(:clj
(defn ^:no-doc -alias-link-var [dst-var src-var dst-attrs]
(add-watch src-var dst-var
(fn [_ _ _ new-val]
(alter-var-root dst-var (fn [_] new-val))
;; Wait for src-var meta to change. This is hacky, but
;; generally only relevant for REPL dev so seems tolerable.
(let [t (Thread/currentThread)]
(future
(.join t 100)
(reset-meta! dst-var
(core-merge (meta src-var) dst-attrs))))))))
#?(:clj (defn- alias-attrs [meta] (select-keys meta )))
#?(:clj
(let [resolve-clj resolve ; Returns var
resolve-cljs ; Returns analysis map, {:keys [meta ...]}
(when-let [ns (find-ns 'cljs.analyzer.api)
v (ns-resolve ns 'resolve)]
@v)]
(defn- var-info
"Returns {:keys [var meta]} for given symbol."
[macro-env sym]
(when (symbol? sym)
(if (:ns macro-env)
(when resolve-cljs {:meta (:meta (resolve-cljs macro-env sym))})
(let [v (resolve macro-env sym)]
{:var v
:meta
(let [m (meta v)]
(if-let [x (get m :arglists)]
(assoc m :arglists `'~x) ; Quote
(do m)))}))))))
#?(:clj
(defmacro defalias
"Defines a local alias for the var identified by given qualified
source symbol: (defalias my-map clojure.core/map), etc.
Source var's metadata will be preserved (docstring, arglists, etc.).
Changes to Clj source var's value will also be applied to alias.
See also `defaliases`."
([ src ] `(defalias nil ~src nil nil))
([alias src ] `(defalias ~alias ~src nil nil))
([alias src alias-attrs ] `(defalias ~alias ~src ~alias-attrs nil))
([alias src alias-attrs alias-body]
(let [cljs? (some? (:ns &env))
src-sym (-have symbol? src)
alias-sym (-have symbol? (or alias (symbol (name src-sym))))
{src-var, :var src-attrs :meta} (var-info &env src-sym)
alias-attrs
(if (string? alias-attrs) ; Back compatibility
{:doc alias-attrs}
(do alias-attrs))
link? (get alias-attrs :link? true)
alias-attrs (dissoc alias-attrs :link?)
final-attrs
(select-keys (core-merge src-attrs (meta alias-sym) alias-attrs)
[:doc :no-doc :arglists :private :macro :added :deprecated :inline :tag])
alias-sym (with-meta alias-sym final-attrs)
alias-body (or alias-body (if cljs? src-sym `@~src-var))]
#_(spit "debug.txt" (str (if cljs? "cljs: " "clj: ") src-sym ": " (meta alias-sym) "\n") :append true)
(if cljs?
`(def ~alias-sym ~alias-body)
`(do
;; Need `alter-meta!` to reliably retain macro status!
(alter-meta! (def ~alias-sym ~alias-body) conj ~final-attrs)
(when ~link? (-alias-link-var (var ~alias-sym) ~src-var ~alias-attrs))
;; (assert (bound? (var ~alias-sym)) ~(str "Alias `" alias-sym "` is bound"))
(do (var ~alias-sym))))))))
#?(:clj
(defmacro defaliases
"Bulk version of `defalias`.
Takes source symbols or {:keys [alias src attrs body]} maps:
(defaliases
{:alias my-map, :src map, :attrs {:doc \"My `map` alias\"}}
{:alias my-vec, :src vec, :attrs {:doc \"My `vec` alias\"}})"
{:added "Encore v3.58.0 (2023-04-09)"
:arglists '([{:keys [alias src attrs body]} ...])}
[& clauses]
`(do
~@(map
(fn [x]
(cond
(symbol? x) `(defalias ~x)
(map? x)
(let [{:keys [alias src attrs body]
:or {attrs (dissoc x :alias :src)}} x]
`(defalias ~alias ~src ~attrs ~body))
:else
(unexpected-arg! x
{:context `defaliases
:param 'alias-clause
:expected '#{symbol map}})))
clauses))))
(comment
(defn src "src doc 1" [] "val1")
(defalias ^{:doc "alias doc 1"} src* src {:doc "alias doc 2"})
[(src*) (meta #'src*)]
(macroexpand '(defaliases {:alias map2 :src map :doc "map2"}))
(do (defaliases {:alias map2 :src map :doc "map2"}))
(defn myfn "myfn doc" [x y] (Thread/sleep 2000) (+ x y))
(defaliases {:alias myfn2 :src myfn :body (fmemoize myfn)})
(myfn2 1 1))
;;;; Truss aliases (for back compatibility, convenience)
#?(:clj
(do
(defalias taoensso.truss/have)
(defalias taoensso.truss/have!)
(defalias taoensso.truss/have?)
(defalias taoensso.truss/have!?)
(defalias with-truss-data taoensso.truss/with-data)))
(defalias get-truss-data taoensso.truss/get-data)
;;;;
#?(:clj
(defn class-sym
"Returns class name symbol of given argument."
{:added "Encore v3.98.0 (2024-04-08)"}
[x] (when x (symbol (.getName (class x))))))
;;;; Forms
;; Useful for macros, etc.
(declare rsome revery?)
#?(:clj
(do
(defn ^:no-doc runtime-form? "Private, don't use." {:added "Encore v3.67.0 (2023-09-08)"} [form] (or (symbol? form) (list-form? form)))
(defn ^:no-doc const-form? "Private, don't use." {:added "Encore v3.67.0 (2023-09-08)"} [form] (not (runtime-form? form)))
(defn ^:no-doc const-form "Private, don't use." {:added "Encore v3.67.0 (2023-09-08)"} [form] (when (const-form? form) form))
(defn ^:no-doc const-forms? "Private, don't use." {:added "Encore v3.68.0 (2023-09-25)"} [& forms] (revery? const-form? forms))
(defn ^:no-doc const-forms "Private, don't use." {:added "Encore v3.68.0 (2023-09-25)"} [& forms] (mapv const-form forms))))
;;;; Errors
(defn error?
"Returns true iff given platform error (`Throwable` or `js/Error`)."
#?(:cljs {:tag 'boolean})
[x]
#?(:clj (instance? Throwable x)
:cljs (instance? js/Error x)))
(defn ex-message
"Same as `core/ex-message` (added in Clojure v1.10)."
{:added "Encore v3.41.0 (2022-12-03)"}
[x]
#?(:clj (when (instance? Throwable x) (.getMessage ^Throwable x))
:cljs (when (instance? js/Error x) (.-message x))))
(defn ex-data
"Same as `core/ex-data` (added in Clojure v1.4)."
{:added "Encore v3.98.0 (2024-04-08)"}
[x]
#?(:clj (when (instance? clojure.lang.IExceptionInfo x) (.getData ^clojure.lang.IExceptionInfo x))
:cljs (when (instance? ExceptionInfo x) (.-data x))))
(defn ex-cause
"Same as `core/ex-cause` (added in Clojure v1.10)."
{:added "Encore v3.41.0 (2022-12-03)"}
[x]
#?(:clj (when (instance? Throwable x) (.getCause ^Throwable x))
:cljs (when (instance? ExceptionInfo x) (.-cause x))))
(defn ex-root
"Returns root cause of given platform error."
{:added "Encore v3.98.0 (2024-04-08)"}
[x]
(when (error? x)
(loop [error x]
(if-let [cause (ex-cause error)]
(recur cause)
error))))
(comment (ex-root (ex-info "Ex2" {:k2 "v2"} (ex-info "Ex1" {:k1 "v1"}))))
(defn ^:no-doc ex-type
"Private, don't use.
Returns class symbol of given platform error."
{:added "Encore v3.98.0 (2024-04-08)"}
[x]
#?(:clj (symbol (.getName (class x)))
:cljs
(cond
(instance? ExceptionInfo x) `ExceptionInfo ; Note namespaced
(instance? js/Error x) (symbol "js" (.-name x)))))
(defn ^:no-doc ex-map*
"Private, don't use.
Returns ?{:keys [type msg data]} for given platform error."
{:added "Encore v3.98.0 (2024-04-08)"}
[x]
(when-let [msg (ex-message x)]
(if-let [data (not-empty (ex-data x))]
{:type (ex-type x), :msg msg, :data data}
{:type (ex-type x), :msg msg})))
(comment (ex-map* (ex-info "Ex2" {:k2 "v2"} (ex-info "Ex1" {:k1 "v1"}))))
(defn ^:no-doc ex-chain
"Private, don't use.
Returns vector cause chain of given platform error."
{:added "Encore v3.98.0 (2024-04-08)"}
([ x] (ex-chain false x))
([as-maps? x]
(when (error? x)
(let [xf (if as-maps? ex-map* identity)]
(loop [acc [(xf x)], error x]
(if-let [cause (ex-cause error)]
(recur (conj acc (xf cause)) cause)
(do acc)))))))
(comment (ex-chain :as-maps (ex-info "Ex2" {:k2 "v2"} (ex-info "Ex1" {:k1 "v1"}))))
#?(:clj
(defn- st-element->map [^StackTraceElement ste]
{:class (symbol (.getClassName ste))
:method (symbol (.getMethodName ste))
:file (.getFileName ste)
:line (.getLineNumber ste)}))
;; #?(:clj
;; (defn- st-element->str ^String [^StackTraceElement ste]
;; (str
;; "`" (.getClassName ste) "/" (.getMethodName ste) "`"
;; " at " (.getFileName ste) ":" (.getLineNumber ste))))
(declare assoc-some as-?nempty-str)
(defn ^:no-doc ex-map
"Private, don't use.
Returns ?{:keys [type msg data chain trace]} for given platform error."
{:added "Encore v3.98.0 (2024-04-08)"}
[x]
(when-let [chain (ex-chain x)]
(let [maps (mapv ex-map* chain)
root (peek chain)
root-map (peek maps)]
(assoc-some root-map
:chain maps
:trace
#?(:cljs (as-?nempty-str (.-stack root))
:clj
(when-let [st (not-empty (.getStackTrace ^Throwable root))] ; Don't delay
(delay (mapv st-element->map st))))))))
(comment
(ex-map (ex-info "Ex2" {:k2 "v2"} (ex-info "Ex1" {:k1 "v1"})))
(ex-map (ex-info "Ex2" {:k2 "v2"} (ex-info "Ex1" {:k1 "v1"})))
(let [ex (ex-info "Ex2" {:k2 "v2"} (ex-info "Ex1" {:k1 "v1"}))]
(qb 1e5 ; [34.01 435.45]
(ex-map ex)
(Throwable->map ex))))
#?(:clj (defn- critical-throwable? [x] (and (instance? Error x) (not (instance? AssertionError x)))))
#?(:clj (defn- non-critical-throwable? [x] (and (instance? Throwable x) (not (critical-throwable? x)))))
#?(:clj
(defn ^:no-doc throw-critical
"Private, don't use.
If given any `Error` besides `AssertionError`, (re)throw it.
Useful as a hack to allow easily catching both `Exception` and `AssertionError`:
(try <body> (catch Throwable t (throw-critical t) <body>)), etc."
{:added "Encore v3.98.0 (2024-04-08)"}
[x] (when (critical-throwable? x) (throw x))))
#?(:clj
(defmacro try*
"Like `try`, but `catch` clause class may be:
`:ex-info` - Catches only `ExceptionInfo`
`:common` - Catches `js/Error` (Cljs), `Exception` (Clj)
`:all` - Catches `:default` (Cljs), `Throwable` (Clj)
`:all-but-critical` - Catches `:default` (Cljs), `Exception` and `AssertionError` (Clj)
Addresses CLJ-1293 and the fact that `AssertionError`s are typically NON-critical
(so desirable to catch, in contrast to other `Error` classes)."
{:added "Encore v3.67.0 (2023-09-08)"
:arglists '([expr* catch-clauses* ?finally-clause])}
[& forms]
(let [cljs? (some? (:ns &env))
forms
(mapv
(fn [in]
(cond
(not (list-form? in)) in
:let [[s1 s2 s3 & more] in]
(not= s1 'catch) in
(not (keyword? s2)) in
:else
(let [[rethrow-critical? s2]
(case s2
;; Note unfortunate naming of `:default` in Cljs to refer to any error type
(:common :default) (if cljs? [false 'js/Error] [false `Exception])
(:all :any ) (if cljs? [false :default] [false `Throwable])
(:all-but-critical) (if cljs? [false :default] [true `Throwable])
(:ex-info)
(if cljs?
[false 'cljs.core.ExceptionInfo]
[false 'clojure.lang.ExceptionInfo])
(throw
(ex-info "[encore/try*] Unexpected catch clause keyword"
{:given (typed-val s2)
:expected '#{:common :all :all-but-critical :ex-info}})))]
(if rethrow-critical?
`(catch ~s2 ~s3 (throw-critical ~s3) ~@more)
`(catch ~s2 ~s3 ~@more)))))
forms)]
`(try ~@forms))))
(comment
(macroexpand '(try* (catch :all t t 1 2 3) (finally 1 2 3)))
(macroexpand '(try* (/ 1 0) (catch :all t t 1 2 3) (finally 1 2 3)))
(macroexpand '(try* (/ 1 0) (catch :all-but-critical t t 1 2 3) (finally 1 2 3))))
#?(:clj
(defmacro catching
"Terse, cross-platform (try* expr (catch :all _)).
See also `try*` for more flexibility."
([ expr] `(try* ~expr (catch :all ~'_)))
([error-type expr] `(try* ~expr (catch ~error-type ~'_)))))
(comment (catching (zero? "9")))
(declare submap? str-contains? re-pattern?)
(defn matching-error
"Given a platform error and criteria, returns the error if it matches
all criteria. Otherwise returns nil.
`kind` may be:
- A predicate function, (fn match? [x]) -> bool
- A class (e.g. `ArithmeticException`, `AssertionError`, etc.)
- `:all` => any platform error (Throwable or js/Error, etc.)
- `:common` => common platform error (Exception or js/Error)
- `:ex-info` => an `IExceptionInfo` as created by `ex-info`
- A set of `kind`s as above, at least one of which must match
`pattern` may be:
- A string or Regex against which `ex-message` must match
- A map against which `ex-data` must match using `submap?`
- A set of `pattern`s as above, at least one of which must match
When an error with (nested) causes doesn't match, a match will be attempted
against its (nested) causes.
Low-level util, see also `throws`, `throws?`."
{:added "Encore v3.70.0 (2023-10-17)"}
([ err] err)
([kind err]
(when-let [match?
(cond
(error? kind) (= kind err) ; Exact match
(fn? kind) (kind err) ; pred kind
(set? kind) (rsome #(matching-error % err) kind) ; set kind
:else
(case kind
(:common :default) #?(:clj (instance? Exception err) :cljs (instance? js/Error err))
(:all :any) #?(:clj (instance? Throwable err) :cljs (some? err))
(:all-but-critical) #?(:clj (non-critical-throwable? err) :cljs (some? err))
:ex-info #?(:clj (instance? clojure.lang.IExceptionInfo err) :cljs (instance? ExceptionInfo err))