-
-
Notifications
You must be signed in to change notification settings - Fork 50
/
encore.cljc
5610 lines (4705 loc) · 206 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 compatibility
* 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.
Quick Taoensso naming conventions:
**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):
~ - 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)
[nop] - Unmodified behaviour (=> non-breaking implementation or 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)"
{:author "Peter Taoussanis (@ptaoussanis)"}
(:refer-clojure :exclude
[if-let if-some if-not when when-not when-some when-let cond defonce
run! some? ident? float? boolean? uri? indexed? bytes?
int? pos-int? neg-int? nat-int?
simple-ident? qualified-ident?
simple-symbol? qualified-symbol?
simple-keyword? qualified-keyword?
format update-in merge merge-with
memoize abs ex-message ex-cause])
#?(:clj
(:require
[clojure.string :as str]
[clojure.set :as set]
[clojure.java.io :as io]
[clojure.walk :as walk :refer [macroexpand-all]]
;; [clojure.core.async :as async]
[clojure.tools.reader.edn :as edn]
[taoensso.truss :as truss])
:cljs
(:require
[clojure.string :as str]
[clojure.set :as set]
;; [cljs.core.async :as async]
[cljs.reader]
[cljs.tools.reader.edn :as edn]
;;[goog.crypt.base64 :as base64]
[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]
;; [org.apache.commons.codec.binary Base64]
)
:cljs
(:require-macros
[taoensso.encore :as enc-macros :refer
[have have! have? compile-if
if-let if-some if-not when when-not when-some when-let -cond cond defonce
cond! catching -if-cas! now-dt* now-udt* now-nano* min* max*
name-with-attrs deprecated new-object defalias throws throws?]])))
(def encore-version [3 57 2])
(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)
(test/run-tests))
;;;; TODO v4
;; - Drop previously deprecated vars
;; - Transducers first
;; - Better match naming of late Clojure additions (e.g. nnil->some / sor)
;; - Consider docstrings catered for public consumption
;; - Imports from tl-core, tl-math, tl-nodes, baget, etc.
;; - Unit tests
;;;; 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)) ; Back compatibility
([test then else]
(if (try (eval test) (catch Throwable _ false))
`(do ~then)
`(do ~else)))))
#?(:clj
(defmacro try-eval
"Evaluates `form`. If eval doesn't throw, expands to `form`, otherwise to nil."
{:added "v3.50.0 (2023-03-07)"}
[form] `(compile-if ~form ~form nil)))
(comment
(macroexpand '(try-eval (java.util.concurrent.atomic.AtomicLong.)))
(macroexpand '(try-eval (java.util.concurrent.Executors/newVirtualThreadPerTaskExecutor)))
(macroexpand '(try-eval (do (println "effect") :x))))
#?(:clj (defmacro compile-when {:style/indent 1} [test & body] `(compile-if ~test (do ~@body) nil)))
#?(:clj
(compile-if
;; Avoiding for edge case where user cares about startup time and has
;; `core.async` as dependency but it never gets required anywhere else
;; (do (require 'clojure.core.async) true)
(do (or
(io/resource "clojure/core/async.clj")
(io/resource "clojure/core/async.cljc")))
(def have-core-async? true)
(def have-core-async? false)))
(comment (require '[clojure.core.async] :verbose))
;;; (:ns &env) is nnil iff compiling for ClojureScript, giving us a way to
;;; write macros that produce different Clj/Cljs code (not something that
;;; .cljx or .cljc currently provide support for):
#?(:clj (defmacro if-clj {:style/indent 1} [then & [else]] (if (:ns &env) else then)))
#?(:clj (defmacro if-cljs {:style/indent 1} [then & [else]] (if (:ns &env) then else)))
#?(:clj
(defmacro if-let
"Like `core/if-let` but can bind multiple values for `then` iff all tests
are truthy, supports internal unconditional `:let`s."
{: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
"Like `core/if-some` but can bind multiple values for `then` iff all tests
are non-nil, supports internal unconditional `:let`s."
{: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
"Like `core/if-not` but acts like `if-let` when given a binding vector
as test expr."
;; 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
"Like `core/when` but acts like `when-let` when given a binding vector
as test expr."
{: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
"Like `core/when-not` but acts like `when-let` when given a binding vector
as test expr."
{: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
{: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)))))
#?(:clj
(defmacro when-let
"Like `core/when-let` but can bind multiple values for `body` iff all tests
are truthy, supports internal unconditional `:let`s."
{:style/indent 1}
;; Now a feature subset of all-case `when`
[bindings & body] `(if-let ~bindings (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))
#?(:clj
(defmacro -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? 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
"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")])
(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 defonce
"Like `core/defonce` but supports optional docstring and attrs map."
{:style/indent 1}
[sym & args]
(let [[sym body] (name-with-attrs sym args)]
`(if-cljs
(cljs.core/defonce ~sym ~@body)
(clojure.core/defonce ~sym ~@body)))))
#?(:clj
(defn compiling-cljs?
"Return truthy iff currently generating Cljs code."
[]
(when-let [n (find-ns 'cljs.analyzer)]
(when-let [v (ns-resolve n '*cljs-file*)]
@v))))
(comment (compiling-cljs?))
;;;; Core fns
(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)
#?(:cljs (defn ^boolean some? [x] (if (nil? x) false true))
:clj
(defn some?
{:inline (fn [x] `(if (identical? ~x nil) false true))}
[x] (if (identical? x nil) false true)))
;;;; Secondary macros
#?(:clj
(defmacro case-eval
"Like `case` but evals test constants 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
(do
(defmacro do-nil [& body] `(do ~@body nil))
(defmacro do-false [& body] `(do ~@body false))
(defmacro do-true [& body] `(do ~@body true))))
#?(: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))))
#?(:clj
(defmacro declare-remote
"Declares given ns-qualified symbols, preserving metadata. 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))))))
(defn- quote-arglists [m]
(if-let [x (get m :arglists)]
(assoc m :arglists `'~x)
(do m)))
(comment (quote-arglists {:a :A :arglists '([x])}))
(def ^:private alias-src-attrs [:doc :arglists :private :macro :added :deprecated])
#?(:clj
(defn -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
(defmacro defalias
"Defines a local alias for the var identified by the given qualified
source symbol: (defalias my-map clojure.core/map), etc.
For Clj:
- Source var's metadata will be preserved (docstring, arglists, etc.).
- Changes to source var's value will also be applied to alias."
([ src-sym ] `(defalias ~(symbol (name src-sym)) ~src-sym nil))
([alias-sym src-sym ] `(defalias ~alias-sym ~src-sym nil))
([alias-sym src-sym alias-attrs]
(-have? symbol? alias-sym src-sym)
(let [compiling-cljs? (boolean (:ns &env))
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?)
alias-attrs (core-merge (meta alias-sym) alias-attrs)]
(if compiling-cljs?
(let [alias-sym (with-meta alias-sym alias-attrs)]
`(def ~alias-sym ~src-sym))
(let [src-var (resolve src-sym)
_
(when-not src-var
(throw
(ex-info
(str "[encore/defalias] Failed to resolve source var for sym: " src-sym)
{:alias-sym alias-sym
:src-sym src-sym
:alias-attrs alias-attrs
:compiling-cljs? compiling-cljs?
:reader-mode #?(:clj :clj, :cljs :cljs, :default :other)})))
src-attrs
(let [src-meta (quote-arglists (meta src-var))]
(select-keys src-meta alias-src-attrs))
final-attrs (core-merge src-attrs alias-attrs)
alias-sym (with-meta alias-sym final-attrs)]
`(do
;; Need `alter-meta!` to reliably retain ?macro status, Ref. Timbre #364
(alter-meta! (def ~alias-sym @~src-var) conj ~final-attrs)
(when ~link? (-alias-link-var (var ~alias-sym) ~src-var ~alias-attrs))
(do (var ~alias-sym)))))))))
(comment :see-tests)
(comment
(defn src "src doc 1" [] "val1")
(defalias ^{:doc "alias doc 1"} src* src {:doc "alias doc 2"})
[(src*) (meta #'src*)])
#?(:clj
(defmacro deftype-print-methods
"Private, used by other Taoensso libs."
{:added "v3.57.0 (2023-03-29)"}
[& types]
`(do ~@(map (fn [type]
`(defmethod print-method ~type [~'x ~(with-meta 'w {:tag 'java.io.Writer})]
(.write ~'w (str ~(str "#" *ns* ".") ~'x)))) types))))
(comment
(do
(deftype Foo [] Object (toString [x] "Foo[]"))
(defrecord Bar [] Object (toString [x] "Bar{}"))
(deftype-print-methods Foo Bar)
[(str (Foo.) " " (Bar.)) (Foo.) (Bar.)]))
;;;; 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 taoensso.truss/keep-callsite)))
(defalias get-truss-data taoensso.truss/get-data)
;;;; Edn
(declare map-keys kw-identical?)
(defn read-edn
"Attempts to pave over differences in:
`clojure.edn/read-string`, `clojure.tools.edn/read-string`,
`cljs.reader/read-string`, `cljs.tools.reader/read-string`.
`cljs.reader` in particular can be a pain."
([ s] (read-edn nil s))
([opts s]
;; First normalize behaviour for unexpected inputs:
(if (or (nil? s) (identical? s ""))
nil
(if-not (string? s)
(throw
(ex-info "[encore/read-edn] Unexpected arg type (expected string or nil)"
{:arg {:value s :type (type s)}}))
(let [readers (get opts :readers ::dynamic)
default (get opts :default ::dynamic)
;; Nb we ignore as implementation[1] detail:
;; *.tools.reader/*data-readers*,
;; *.tools.reader/default-data-reader-fn*
;;
;; [1] Lib consumer doesn't care that we've standardized to
;; using tools.reader under the covers
readers
(if-not (kw-identical? readers ::dynamic)
readers
#?(:clj clojure.core/*data-readers*
;; Unfortunate (slow), but faster than gc'd memoization in most cases:
:cljs (map-keys symbol @cljs.reader/*tag-table*)))
default
(if-not (kw-identical? default ::dynamic)
default
#?(:clj clojure.core/*default-data-reader-fn*
:cljs @cljs.reader/*default-data-reader-fn*))
opts (assoc opts :readers readers :default default)]
#?(:clj (clojure.tools.reader.edn/read-string opts s)
:cljs (cljs.tools.reader.edn/read-string opts s)))))))
(defn pr-edn
"Prints arg to an edn string readable with `read-edn`."
([ x] (pr-edn nil x))
([_opts x]
#?(:cljs (binding [*print-level* nil, *print-length* nil] (pr-str x))
:clj
(let [sw (java.io.StringWriter.)]
(binding [*print-level* nil, *print-length* nil,
;; *out* sw, *print-dup* false
]
;; (pr x)
(print-method x sw) ; Bypass *out*, *print-dup*
(.toString sw))))))
;;;; Errors
(defn ex-message
"Copy of `core/ex-message` (added in Clojure v1.10)"
{:added "v3.41.0 (2022-12-03)"}
[ex]
#?(:clj (when (instance? Throwable ex) (.getMessage ^Throwable ex))
:cljs (when (instance? js/Error ex) (.-message ex))))
(defn ex-cause
"Copy of `core/ex-cause` (added in Clojure v1.10)"
{:added "v3.41.0 (2022-12-03)"}
[ex]
#?(:clj (when (instance? Throwable ex) (.getCause ^Throwable ex))
:cljs (when (instance? ExceptionInfo ex) (.-cause ex))))
#?(:clj
(defmacro catching
"Cross-platform try/catch/finally."
;; Very unfortunate that CLJ-1293 has not yet been addressed
([try-expr ] `(catching ~try-expr :all ~'__ nil nil))
([try-expr error-sym catch-expr ] `(catching ~try-expr :all ~error-sym ~catch-expr nil))
([try-expr error-sym catch-expr finally-expr] `(catching ~try-expr :all ~error-sym ~catch-expr ~finally-expr))
([try-expr error-type error-sym catch-expr finally-expr]
(case error-type
(:common :default) ; `:default` is a poor name, here only for back compatibility
(if (nil? finally-expr)
`(if-cljs
(try ~try-expr (catch js/Error ~error-sym ~catch-expr))
(try ~try-expr (catch Exception ~error-sym ~catch-expr)))
`(if-cljs
(try ~try-expr (catch js/Error ~error-sym ~catch-expr) (finally ~finally-expr))
(try ~try-expr (catch Exception ~error-sym ~catch-expr) (finally ~finally-expr))))
(:all :any)
;; Note unfortunate naming of `:default` in Cljs to refer to any error type
(if (nil? finally-expr)
`(if-cljs
(try ~try-expr (catch :default ~error-sym ~catch-expr))
(try ~try-expr (catch Throwable ~error-sym ~catch-expr)))
`(if-cljs
(try ~try-expr (catch :default ~error-sym ~catch-expr) (finally ~finally-expr))
(try ~try-expr (catch Throwable ~error-sym ~catch-expr) (finally ~finally-expr))))
;; Specific error-type provided
(if (nil? finally-expr)
`(if-cljs
(try ~try-expr (catch ~error-type ~error-sym ~catch-expr) (finally ~finally-expr))
(try ~try-expr (catch ~error-type ~error-sym ~catch-expr) (finally ~finally-expr)))
`(if-cljs
(try ~try-expr (catch ~error-type ~error-sym ~catch-expr))
(try ~try-expr (catch ~error-type ~error-sym ~catch-expr))))))))
(comment
(macroexpand '(catching (do "foo") e e (println "finally")))
(catching (zero? "9")))
(defn error-data
"Returns data map iff `x` is an error of any type on platform."
;; Note Clojure >= 1.7 now has `Throwable->map` (clj only)
[x]
(when-let [data-map
(and x
(or
(ex-data x) ; ExceptionInfo
#?(:clj (when (instance? Throwable x) {})
:cljs {})))]
(let [base-map
#?(:clj
(let [^Throwable t x] ; (catch Throwable t <...>)
{:err-type (type t)
:err-msg (.getLocalizedMessage t)
:err-cause (.getCause t)})
:cljs
(let [err x] ; (catch :default t <...)
{:err-type (type err)
:err-msg (.-message err)
:err-cause (.-cause err)}))]
#_(assoc base-map :err-data data-map)
(conj base-map data-map))))
(comment
(error-data (Throwable. "foo"))
(error-data (Exception. "foo"))
(error-data (ex-info "foo" {:bar :baz})))
#?(:clj
(defmacro caught-error-data
"Handy for error-throwing unit tests."
[& body] `(catching (do ~@body nil) e# (error-data e#))))
(comment (caught-error-data (/ 5 0)))
(defn- error-message
;; Note Clojure >= 1.10 now has `ex-message`
[x]
#?(:clj (when (instance? Throwable x) (.getMessage ^Throwable x))
:cljs (when (instance? js/Error x) (.-message x))))
(declare submap?)
(defn -matching-error
;; Ref. also CLJ-1293
([ err] err)
([c err]
(when-let [match?
(if (fn? c) ; Treat as pred
(c err)
#?(:clj
(case c
(:all :any) (instance? Throwable err)
(:common :default) (instance? Exception err)
:ex-info (instance? clojure.lang.ExceptionInfo err)
(do (instance? c err)))
:cljs
(case c
(:all :any) (some? err)
(:common :default) (instance? js/Error err)
:ex-info (instance? ExceptionInfo err)
(do (instance? c err)))))]
err))
([c pattern err]
(when-let [match?
(and
(-matching-error c err)
(cond
(nil? pattern) true
(map? pattern)
(if-let [data (ex-data err)]
(submap? data pattern)
false #_(empty? pattern))
:else
(boolean
(re-find
(re-pattern pattern)
(error-message err)))))]
err)))
(comment
(-matching-error (catching (/ 4 0) t t))
(-matching-error :default #"Divide by zero" (catching (/ 4 0) t t))
(-matching-error :default #"Nope" (catching (/ 4 0) t t))
(-matching-error :default #"Test" (ex-info "Test" {:a :b}))
(-matching-error :default {:a :b} (ex-info "Test" {:a :b :c :d})))
#?(:clj
(defmacro throws
"Like `throws?`, but returns ?matching-error instead of true/false."
{:added "v3.31.0 (2022-10-27)"}
([ form] `(-matching-error (catching (do ~form nil) ~'t ~'t)))
([c form] `(-matching-error ~c (catching (do ~form nil) ~'t ~'t)))
([c pattern form] `(-matching-error ~c ~pattern (catching (do ~form nil) ~'t ~'t)))))
#?(:clj
(defmacro throws?
"Evals `form` and returns true iff it throws an error that matches given
criteria:
- `c` 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)
- `pattern` may be:
- A string or Regex against which `ex-message` will be matched.
- A map against which `ex-data` will be matched.
Useful for unit tests, e.g.:
(is (throws? {:a :b} (throw (ex-info \"Test\" {:a :b :c :d}))))
See also `throws`."
{:added "v3.31.0 (2022-10-27)"}
([ form] `(boolean (throws ~form)))
([c form] `(boolean (throws ~c ~form)))
([c pattern form] `(boolean (throws ~c ~pattern ~form)))))
(comment :see-tests)
(let [get-default-error-fn
(fn [base-data]
(let [msg (get base-data :error/msg "Error thrown during reduction")
base-data (dissoc base-data :error/msg)]
(fn default-error-fn [data cause] ; == (partial ex-info <msg>)
(throw (ex-info msg (conj base-data data) cause)))))]
(defn catching-rf
"Returns wrapper around given reducing function `rf` so that if `rf`
throws, (error-fn <thrown-error> <contextual-data>) will be called.
The default `error-fn` will rethrow the original error, wrapped in
extra contextual information to aid debugging.
See also `catching-xform`."
{:added "v3.32.0 (2022-11-07)"}
([ rf] (catching-rf (get-default-error-fn {:rf rf}) rf))
([error-fn rf]
(let [error-fn
(if (map? error-fn) ; Undocumented convenience
(get-default-error-fn error-fn)
(do error-fn))]
(fn catching-rf
([ ] (catching (rf) t (error-fn {:rf rf :call '(rf)} t)))
([acc ] (catching (rf acc) t (error-fn {:rf rf :call '(rf acc) :args {:acc {:value acc :type (type acc)}}} t)))
([acc in ] (catching (rf acc in) t (error-fn {:rf rf :call '(rf acc in) :args {:acc {:value acc :type (type acc)}
:in {:value in :type (type in)}}} t)))
([acc k v]
(catching (rf acc k v) t
(error-fn
{:rf rf
:call '(rf acc k v)
:args
{:acc {:value acc :type (type acc)}
:k {:value k :type (type k)}
:v {:value v :type (type v)}}}
t))))))))
(comment :see-tests)
(defn catching-xform
"Like `catching-rf`, but applies to a transducer (`xform`).
Makes debugging transductions much easier by greatly improving
the information provided in any errors thrown by `xform` or the
reducing fn:
(transduce
(catching-xform (comp (filter even?) (map inc))) ; Modified xform
<reducing-fn>
<...>)"
{:added "v3.32.0 (2022-11-07)"}
([error-fn xform] (comp (fn [rf] (catching-rf error-fn rf)) xform))
([ xform] (comp catching-rf xform)))
(comment :see-tests)
;;;; Tests
(defn test-fixtures
"Given a {:before ?(fn []) :after ?(fn [])} map, returns cross-platform
test fixtures for use by both `clojure.test` and `cljs.test`:
(let [f (test-fixtures {:before (fn [] (test-setup))})]
(clojure.test/use-fixtures :once f)
(cljs.test/use-fixtures :once f))"
{:added "v3.31.0 (2022-10-27)"}
[fixtures-map]
(have? map? fixtures-map)
;; (have? [:ks<= #{:before :after}] fixtures-map)
#?(:cljs fixtures-map ; Cljs supports a map with {:keys [before after]}
:clj ; Clj wants a fn
(let [{:keys [before after]} fixtures-map]
(fn fixtures [f]
(when before (before))
(f)
(when after (after))))))
(comment (test-fixtures {:before (fn [])}))
;;;; Type preds, etc.
;; - TODO Could really do with a portable ^boolean hint
;; - Some of these have slowly been getting added to Clojure core; make sure
;; to :exclude any official preds using the same name
#?(:clj
(do
(defn stringy? [x] (or (keyword? x) (string? x)))
(defn ident? [x] (or (keyword? x) (symbol? x)))
(defn boolean? [x] (instance? Boolean x))
(defn uri? [x] (instance? java.net.URI x))
(defn indexed? [x] (instance? clojure.lang.Indexed x))
(defn named? [x] (instance? clojure.lang.Named x))
(defn editable? [x] (instance? clojure.lang.IEditableCollection x))
(defn derefable? [x] (instance? clojure.lang.IDeref x))
(defn throwable? [x] (instance? Throwable x))
(defn exception? [x] (instance? Exception x))
(defn error? [x] (instance? Throwable x))
(defn atom? [x] (instance? clojure.lang.Atom x))
(defn transient? [x] (instance? clojure.lang.ITransientCollection x))
(defn lazy-seq? [x] (instance? clojure.lang.LazySeq x))
(defn re-pattern? [x] (instance? java.util.regex.Pattern x))
(defn simple-ident? [x] (and (ident? x) (nil? (namespace x))))
(defn qualified-ident? [x] (and (ident? x) (namespace x) true))
(defn simple-symbol? [x] (and (symbol? x) (nil? (namespace x))))
(defn qualified-symbol? [x] (and (symbol? x) (namespace x) true))
(defn simple-keyword? [x] (and (keyword? x) (nil? (namespace x))))
(defn qualified-keyword? [x] (and (keyword? x) (namespace x) true))
(defn nempty-str? [x] (and (string? x) (not (.isEmpty ^String x))))
(defn nblank-str? [x] (and (string? x) (not (str/blank? x))))
(defn nblank? [x] (not (str/blank? x)))
(defn vec2? [x] (and (vector? x) (= (count x) 2)))
(defn vec3? [x] (and (vector? x) (= (count x) 3))))
:cljs
(do
(defn ^boolean stringy? [x] (or (keyword? x) (string? x)))
(defn ^boolean ident? [x] (or (keyword? x) (symbol? x)))
(defn ^boolean boolean? [x] (or (true? x) (false? x)))
;; (defn uri? [x])
(defn ^boolean indexed? [x] (satisfies? IIndexed x))
(defn ^boolean named? [x] (implements? INamed x))
(defn ^boolean editable? [x] (implements? IEditableCollection x))
(defn ^boolean derefable? [x] (satisfies? IDeref x))
;; (defn throwable? [x])
;; (defn exception? [x])
(defn ^boolean error? [x] (instance? js/Error x))
(defn ^boolean atom? [x] (instance? Atom x))
(defn ^boolean transient? [x] (instance? ITransientCollection x))
(defn ^boolean lazy-seq? [x] (instance? LazySeq x))
(defn ^boolean re-pattern? [x] (instance? js/RegExp x))
(defn ^boolean simple-ident? [x] (and (ident? x) (nil? (namespace x))))
(defn ^boolean qualified-ident? [x] (and (ident? x) (namespace x) true))
(defn ^boolean simple-symbol? [x] (and (symbol? x) (nil? (namespace x))))
(defn ^boolean qualified-symbol? [x] (and (symbol? x) (namespace x) true))
(defn ^boolean simple-keyword? [x] (and (keyword? x) (nil? (namespace x))))
(defn ^boolean qualified-keyword? [x] (and (keyword? x) (namespace x) true))
(defn ^boolean nempty-str? [x] (and (string? x) (not (= x ""))))
(defn ^boolean nblank-str? [x] (and (string? x) (not (str/blank? x))))
(defn ^boolean nblank? [x] (not (str/blank? x)))
(defn ^boolean vec2? [x] (and (vector? x) (= (count x) 2)))
(defn ^boolean vec3? [x] (and (vector? x) (= (count x) 3)))))
;;; Number type naming conventions
;; Since Clojure usu. defaults to larger types (long>integer, double>long),
;; I'm appropriating the rarely-used smaller type names (int, float) to
;; refer to types of generic size.
;;
;; All fixed-precision:
;; - int - Generic size: long or integer, etc.
;; - float - Generic size: double or float, etc.
;; - long - Specific size: long ; Only used when emphasizing specific size
;; - double - Specific size: double ; Only used when emphasizing specific size
(defn #?(:clj finite-num? :cljs ^boolean finite-num?)
"Returns true iff given a number (of standard type) that is: