-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathcore.cljd
7168 lines (6586 loc) · 228 KB
/
core.cljd
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
; Copyright (c) Baptiste Dupuch & Christophe Grand . All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns cljd.core
(:require ["dart:math" :as math]
["dart:collection" :as dart-coll]
["dart:io" :as dart-io]))
(def ^:private sentinel (Object.))
(def ^:macro-support argument-error
(fn [msg]
(new #?(:cljd ArgumentError :clj IllegalArgumentException) msg)))
(def ^:macro-support ^:private maybe-destructured
(fn* [params body]
(if (every? symbol? params)
(cons params body)
(loop [params params
new-params (with-meta [] (meta params))
lets []]
(if params
(if (symbol? (first params))
(recur (next params) (conj new-params (first params)) lets)
(let [gparam (gensym "p__")]
(recur (next params) (conj new-params gparam)
(-> lets (conj (first params)) (conj gparam)))))
`(~new-params
(let ~lets
~@body)))))))
(def ^{:macro true
:doc
"params => positional-params* , or positional-params* & next-param
positional-param => binding-form
next-param => binding-form
name => symbol
Defines a function"
:arglists '[[& sigs]],
:special-form true,
:forms '[(fn name? [params* ] exprs*) (fn name? ([params* ] exprs*)+)]}
fn
(fn*
[&form &env & sigs]
(let [name (if (symbol? (first sigs)) (first sigs) nil)
sigs (if name (next sigs) sigs)
sigs (if (vector? (first sigs))
(list sigs)
(if (seq? (first sigs))
sigs
;; Assume single arity syntax
(throw (argument-error
(if (seq sigs)
(str "Parameter declaration "
(first sigs)
" should be a vector")
(str "Parameter declaration missing"))))))
psig (fn* [sig]
;; Ensure correct type before destructuring sig
(when (not (seq? sig))
(throw (argument-error
(str "Invalid signature " sig
" should be a list"))))
(let [[params & body] sig
_ (when (not (vector? params))
(throw (argument-error
(if (seq? (first sigs))
(str "Parameter declaration " params
" should be a vector")
(str "Invalid signature " sig
" should be a list")))))
conds (when (and (next body) (map? (first body)))
(first body))
body (if conds (next body) body)
conds (or conds (meta params))
pre (:pre conds)
post (:post conds)
body (if post
`((let [~'% ~(if (.< 1 (count body))
`(do ~@body)
(first body))]
~@(map (fn* [c] `(assert ~c)) post)
~'%))
body)
body (if pre
(concat (map (fn* [c] `(assert ~c)) pre)
body)
body)]
(maybe-destructured params body)))
new-sigs (map psig sigs)]
(with-meta
(if name
(list* 'fn* name new-sigs)
(cons 'fn* new-sigs))
(meta &form)))))
(def ^:macro-support ^:private
sigs
(fn [fdecl]
#_(assert-valid-fdecl fdecl)
(let [asig
(fn [fdecl]
(let [arglist (first fdecl)
;elide implicit macro args
arglist (if (= '&form (first arglist))
(subvec arglist 2 (count arglist))
arglist)
body (next fdecl)]
(if (map? (first body))
(if (next body)
(with-meta arglist (conj (if (meta arglist) (meta arglist) {}) (first body)))
arglist)
arglist)))
resolve-tag (fn [argvec]
(let [m (meta argvec)
tag (:tag m)]
argvec
; TODO how to port to CLJD?
#_(if (symbol? tag)
(if (= (.indexOf ^String (name tag) ".") -1)
(if (nil? (clojure.lang.Compiler$HostExpr/maybeSpecialTag tag))
(let [c (clojure.lang.Compiler$HostExpr/maybeClass tag false)]
(if c
(with-meta argvec (assoc m :tag (symbol (name c))))
argvec))
argvec)
argvec)
argvec)))]
(if (seq? (first fdecl))
(loop [ret [] fdecls fdecl]
(if fdecls
(recur (conj ret (resolve-tag (asig (first fdecls)))) (next fdecls))
(seq ret)))
(list (resolve-tag (asig fdecl)))))))
(def
^{:macro true
:doc "Same as (def name (fn [params* ] exprs*)) or (def
name (fn ([params* ] exprs*)+)) with any doc-string or attrs added
to the var metadata. prepost-map defines a map with optional keys
:pre and :post that contain collections of pre or post conditions."
:arglists '([name doc-string? attr-map? [params*] prepost-map? body]
[name doc-string? attr-map? ([params*] prepost-map? body)+ attr-map?])}
defn (fn defn [&form &env fname & fdecl]
;; Note: Cannot delegate this check to def because of the call to (with-meta name ..)
(if (symbol? fname)
nil
(throw (argument-error "First argument to defn must be a symbol")))
(let [m (if (string? (first fdecl))
{:doc (first fdecl)}
{})
fdecl (if (string? (first fdecl))
(next fdecl)
fdecl)
m (if (map? (first fdecl))
(conj m (first fdecl))
m)
fdecl (if (map? (first fdecl))
(next fdecl)
fdecl)
fdecl (if (vector? (first fdecl))
(list fdecl)
fdecl)
m (if (map? (last fdecl))
(conj m (last fdecl))
m)
fdecl (if (map? (last fdecl))
(butlast fdecl)
fdecl)
m (conj {:arglists (list 'quote (sigs fdecl))} m)
m (let [inline (:inline m)
ifn (first inline)
iname (second inline)]
;; same as: (if (and (= 'fn ifn) (not (symbol? iname))) ...)
(if (if (= 'fn ifn)
(if (symbol? iname) false true))
;; inserts the same fn name to the inline fn if it does not have one
(assoc m :inline (cons ifn (cons (symbol (str (name fname) "__inliner"))
(next inline))))
m))
m (conj (if (meta fname) (meta fname) {}) m)]
(list 'def (with-meta fname m)
;;todo - restore propagation of fn name
;;must figure out how to convey primitive hints to self calls first
;;(cons `fn fdecl)
(with-meta (cons `fn fdecl) {:rettag (:tag m) :async (:async m)})))))
(def
^{:macro true
:doc "Like defn, but the resulting function name is declared as a
macro and will be used as a macro by the compiler when it is
called."
:arglists '([name doc-string? attr-map? [params*] body]
[name doc-string? attr-map? ([params*] body)+ attr-map?])
:added "1.0"}
defmacro (fn [&form &env
name & args]
(let [name (vary-meta name assoc :macro true)
prefix (loop [p (list name) args args]
(let [f (first args)]
(if (string? f)
(recur (cons f p) (next args))
(if (map? f)
(recur (cons f p) (next args))
p))))
fdecl (loop [fd args]
(if (string? (first fd))
(recur (next fd))
(if (map? (first fd))
(recur (next fd))
fd)))
fdecl (if (vector? (first fdecl))
(list fdecl)
fdecl)
add-implicit-args (fn [fd]
(let [args (first fd)]
(cons (vec (cons '&form (cons '&env args))) (next fd))))
add-args (fn [acc ds]
(if (nil? ds)
acc
(let [d (first ds)]
(if (map? d)
(conj acc d)
(recur (conj acc (add-implicit-args d)) (next ds))))))
fdecl (seq (add-args [] fdecl))
decl (loop [p prefix d fdecl]
(if p
(recur (next p) (cons (first p) d))
d))]
(cons `defn decl))))
(defmacro defn-
"same as defn, yielding non-public def"
[name & decls]
(list* `clojure.core/defn (with-meta name (assoc (meta name) :private true)) decls))
(defn ^:macro-support destructure [bindings]
(let [bents (partition 2 bindings)
pb (fn pb [bvec b v]
(let [pvec
(fn [bvec b val]
(let [gvec (gensym "vec__")
gseq (gensym "seq__")
gfirst (gensym "first__")
has-rest (some #{'&} b)]
(loop [ret (let [ret (conj bvec gvec val)]
(if has-rest
(conj ret gseq (list `seq gvec))
ret))
n 0
bs b
seen-rest? false]
(if (seq bs)
(let [firstb (first bs)]
(cond
(= firstb '&) (recur (pb ret (second bs) gseq)
n
(nnext bs)
true)
(= firstb :as) (pb ret (second bs) gvec)
:else (if seen-rest?
(throw (new Exception "Unsupported binding form, only :as can follow & parameter"))
(recur (pb (if has-rest
(conj ret
gfirst `(first ~gseq)
gseq `(next ~gseq))
ret)
firstb
(if has-rest
gfirst
(list `nth gvec n nil)))
(inc n)
(next bs)
seen-rest?))))
ret))))
pmap
(fn [bvec b v]
(let [gmap (gensym "map__")
defaults (:or b)]
(loop [ret (-> bvec (conj gmap) (conj v)
(conj gmap) (conj `(if (seq? ~gmap) (-map-lit (seq ~gmap)) ~gmap))
((fn [ret]
(if (:as b)
(conj ret (:as b) gmap)
ret))))
bes (let [transforms
(reduce
(fn [transforms mk]
(if (keyword? mk)
(let [mkns (namespace mk)
mkn (name mk)]
(cond (= mkn "keys") (assoc transforms mk #(keyword (or mkns (namespace %)) (name %)))
(= mkn "syms") (assoc transforms mk #(list `quote (symbol (or mkns (namespace %)) (name %))))
(= mkn "strs") (assoc transforms mk str)
:else transforms))
transforms))
{}
(keys b))]
(reduce
(fn [bes entry]
(reduce #(assoc %1 %2 ((val entry) %2))
(dissoc bes (key entry))
((key entry) bes)))
(dissoc b :as :or)
transforms))]
(if (seq bes)
(let [bb (key (first bes))
bk (val (first bes))
local (if (ident? bb) (with-meta (symbol nil (name bb)) (meta bb)) bb)
bv (if (contains? defaults local)
(list `get gmap bk (defaults local))
(list `get gmap bk))]
(recur (if (ident? bb)
(-> ret (conj local bv))
(pb ret bb bv))
(next bes)))
ret))))]
(cond
(symbol? b) (-> bvec (conj b) (conj v))
(vector? b) (pvec bvec b v)
(map? b) (pmap bvec b v)
:else (throw (new Exception (str "Unsupported binding form: " b))))))
process-entry (fn [bvec b] (pb bvec (first b) (second b)))]
(if (every? symbol? (map first bents))
bindings
(reduce process-entry [] bents))))
(defmacro let
"binding => binding-form init-expr
Evaluates the exprs in a lexical context in which the symbols in
the binding-forms are bound to their respective init-exprs or parts
therein."
{:special-form true, :forms '[(let [bindings*] exprs*)]}
[bindings & body]
#_(assert-args
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
`(let* ~(destructure bindings) ~@body))
(defmacro case [expr & clauses]
(cond
(not (symbol? expr))
`(let* [test# ~expr] (case test# ~@clauses))
(even? (count clauses))
`(~'case ~expr ~@clauses (throw (ArgumentError/value ~expr nil "No matching clause.")))
:else
(let [clauses (vec (partition-all 2 clauses))
[default] (peek clauses)
clauses (pop clauses)]
(list 'case* expr (for [[v e] clauses] [(if (seq? v) v (list v)) e]) default))))
(defn- ^:macro-support roll-leading-opts [body]
(loop [[k v & more :as body] (seq body) opts {}]
(if (and body (keyword? k))
(recur more (assoc opts k v))
[opts body])))
(defmacro reify [& body]
(let [[opts specs] (roll-leading-opts body)]
(list* 'reify* opts specs)))
(defmacro deftype [& args]
(let [[class-name fields & args] args
[opts specs] (roll-leading-opts args)
deftype-form (list* 'deftype* class-name fields opts specs)]
(if (or (:type-only opts) (:abstract (meta class-name)))
deftype-form
`(do
~deftype-form
(defn
~(symbol (str "->" class-name))
[~@fields]
(new ~(vary-meta class-name dissoc :type-params) ~@fields))))))
(defmacro definterface [iface & meths]
`(deftype ~(vary-meta iface assoc :abstract true) []
:type-only true
~iface
~@(map (fn [[meth args]] `(~meth [~'_ ~@args])) meths)))
(definterface IProtocol
(extensions [x])
(satisfies [x]))
(def -DYNAMIC-BINDINGS {})
(defprotocol Fn
"Marker protocol, used to mark multiple/variable arities cljd functions.")
(defn ^bool fn?
"Return true if f is a Dart function or satisfies the Fn protocol."
[f]
(or (dart/is? f Function) (satisfies? Fn f)))
(defprotocol IFn
"Protocol for adding the ability to invoke an object as a function.
For example, a vector can also be used to look up a value:
([1 2 3 4] 1) => 2"
(-invoke
[this]
[this a]
[this a b]
[this a b c]
[this a b c d]
[this a b c d e]
[this a b c d e f]
[this a b c d e f g]
[this a b c d e f g h]
[this a b c d e f g h i])
(-invoke-more [this a b c d e f g h i rest])
(-apply [this more]))
(defn ^bool ifn?
"Returns true if f returns true for fn? or satisfies IFn."
[f]
(or (fn? f) (satisfies? IFn f)))
(defmacro declare
"defs the supplied var names with no bindings, useful for making forward declarations."
[& names] `(do ~@(map #(list 'def % nil) names)))
(defn ^bool satisfies?
{:inline (fn [protocol x] `(.satisfies ~protocol ~x))
:inline-arities #{2}}
[^IProtocol protocol x]
(.satisfies protocol x))
(defn ^bool false?
"Returns true if x is the value false, false otherwise."
{:inline (fn [x] `(.== false ~x))
:inline-arities #{1}}
[x]
(.== false x))
(defn ^bool true?
"Returns true if x is the value true, false otherwise."
{:inline (fn [x] `(.== true ~x))
:inline-arities #{1}}
[x]
(.== true x))
(defn ^bool nil?
{:inline-arities #{1}
:inline (fn [x] `(.== nil ~x))}
[x] (.== nil x))
(defn ^bool boolean
"Coerce to boolean"
[x]
(if (or (nil? x) (false? x))
false
true))
(defn ^bool boolean?
"Return true if x is a Boolean"
[x]
(dart/is? x bool))
(defn ^bool some?
"Returns true if x is not nil, false otherwise."
{:inline-arities #{1}
:inline (fn [x] `(. ~x "!=" nil))}
[x] (. x "!=" nil))
;redefine fn with destructuring and pre/post conditions
#_(defmacro fn
"params => positional-params* , or positional-params* & next-param
positional-param => binding-form
next-param => binding-form
name => symbol
Defines a function"
{:added "1.0", :special-form true,
:forms '[(fn name? [params* ] exprs*) (fn name? ([params* ] exprs*)+)]}
[& sigs]
(let [name (if (symbol? (first sigs)) (first sigs) nil)
sigs (if name (next sigs) sigs)
sigs (if (vector? (first sigs))
(list sigs)
(if (seq? (first sigs))
sigs
;; Assume single arity syntax
(throw (argument-error
(if (seq sigs)
(str "Parameter declaration "
(first sigs)
" should be a vector")
(str "Parameter declaration missing"))))))
psig (fn* [sig]
;; Ensure correct type before destructuring sig
(when (not (seq? sig))
(throw (argument-error
(str "Invalid signature " sig
" should be a list"))))
(let [[params & body] sig
_ (when (not (vector? params))
(throw (argument-error
(if (seq? (first sigs))
(str "Parameter declaration " params
" should be a vector")
(str "Invalid signature " sig
" should be a list")))))
conds (when (and (next body) (map? (first body)))
(first body))
body (if conds (next body) body)
conds (or conds (meta params))
pre (:pre conds)
post (:post conds)
body (if post
`((let [~'% ~(if (.< 1 (count body))
`(do ~@body)
(first body))]
~@(map (fn* [c] `(assert ~c)) post)
~'%))
body)
body (if pre
(concat (map (fn* [c] `(assert ~c)) pre)
body)
body)]
(maybe-destructured params body)))
new-sigs (map psig sigs)]
(with-meta
(if name
(list* 'fn* name new-sigs)
(cons 'fn* new-sigs))
(meta &form))))
(defmacro and
"Evaluates exprs one at a time, from left to right. If a form
returns logical false (nil or false), and returns that value and
doesn't evaluate any of the other expressions, otherwise it returns
the value of the last expr. (and) returns true."
{:added "1.0"}
([] true)
([x] x)
([x & next]
`(let [and# ~x]
(if and# (and ~@next) and#))))
(defmacro when
"Evaluates test. If logical true, evaluates body in an implicit do."
[test & body]
`(if ~test (do ~@body)))
(defmacro when-not
"Evaluates test. If logical false, evaluates body in an implicit do."
[test & body]
`(if ~test nil (do ~@body)))
(defmacro if-some
"bindings => binding-form test
If test is not nil, evaluates then with binding-form bound to the
value of test, if not, yields else"
([bindings then]
`(if-some ~bindings ~then nil))
([bindings then else & oldform]
#_(assert-args
(vector? bindings) "a vector for its binding"
(nil? oldform) "1 or 2 forms after binding vector"
(= 2 (count bindings)) "exactly 2 forms in binding vector")
(let [form (bindings 0) tst (bindings 1)]
`(let [temp# ~tst]
(if (nil? temp#)
~else
(let [~form temp#]
~then))))))
(defmacro when-some
"bindings => binding-form test
When test is not nil, evaluates body with binding-form bound to the
value of test"
[bindings & body]
#_(assert-args
(vector? bindings) "a vector for its binding"
(= 2 (count bindings)) "exactly 2 forms in binding vector")
(let [form (bindings 0) tst (bindings 1)]
`(let [temp# ~tst]
(if (nil? temp#)
nil
(let [~form temp#]
~@body)))))
(defmacro if-let
"bindings => binding-form test
If test is true, evaluates then with binding-form bound to the value of
test, if not, yields else"
([bindings then]
`(if-let ~bindings ~then nil))
([bindings then else & oldform]
#_(assert-args
(vector? bindings) "a vector for its binding"
(nil? oldform) "1 or 2 forms after binding vector"
(= 2 (count bindings)) "exactly 2 forms in binding vector")
(let [form (bindings 0) tst (bindings 1)]
`(let [temp# ~tst]
(if temp#
(let [~form temp#]
~then)
~else)))))
(defmacro when-let
"bindings => binding-form test
When test is true, evaluates body with binding-form bound to the value of test"
[bindings & body]
;; TODO assert-args
#_(assert-args
(vector? bindings) "a vector for its binding"
(= 2 (count bindings)) "exactly 2 forms in binding vector")
(let [form (bindings 0) tst (bindings 1)]
`(let [temp# ~tst]
(when temp#
(let [~form temp#]
~@body)))))
(defmacro when-first
"bindings => x xs
Roughly the same as (when (seq xs) (let [x (first xs)] body)) but xs is evaluated only once"
[bindings & body]
(let [[x xs] bindings]
`(when-let [xs# (seq ~xs)]
(let [~x (first xs#)]
~@body))))
(defmacro or
"Evaluates exprs one at a time, from left to right. If a form
returns a logical true value, or returns that value and doesn't
evaluate any of the other expressions, otherwise it returns the
value of the last expression. (or) returns nil."
{:added "1.0"}
([] nil)
([x] x)
([x & next]
`(let [or# ~x]
(if or# or# (or ~@next)))))
(defmacro cond
"Takes a set of test/expr pairs. It evaluates each test one at a
time. If a test returns logical true, cond evaluates and returns
the value of the corresponding expr and doesn't evaluate any of the
other tests or exprs. (cond) returns nil."
{:added "1.0"}
[& clauses]
(when clauses
(list 'if (first clauses)
(if (next clauses)
(second clauses)
(throw (argument-error
"cond requires an even number of forms")))
(cons 'cljd.core/cond (next (next clauses))))))
(defmacro cond->
"Takes an expression and a set of test/form pairs. Threads expr (via ->)
through each form for which the corresponding test
expression is true. Note that, unlike cond branching, cond-> threading does
not short circuit after the first true test expression."
[expr & clauses]
#_(assert (even? (count clauses)))
(let [g (gensym)
steps (map (fn [[test step]] `(if ~test (-> ~g ~step) ~g))
(partition 2 clauses))]
`(let [~g ~expr
~@(interleave (repeat g) (butlast steps))]
~(if (empty? steps)
g
(last steps)))))
(defmacro cond->>
"Takes an expression and a set of test/form pairs. Threads expr (via ->>)
through each form for which the corresponding test expression
is true. Note that, unlike cond branching, cond->> threading does not short circuit
after the first true test expression."
[expr & clauses]
#_(assert (even? (count clauses)))
(let [g (gensym)
steps (map (fn [[test step]] `(if ~test (->> ~g ~step) ~g))
(partition 2 clauses))]
`(let [~g ~expr
~@(interleave (repeat g) (butlast steps))]
~(if (empty? steps)
g
(last steps)))))
(defmacro condp
"Takes a binary predicate, an expression, and a set of clauses.
Each clause can take the form of either:
test-expr result-expr
test-expr :>> result-fn
Note :>> is an ordinary keyword.
For each clause, (pred test-expr expr) is evaluated. If it returns
logical true, the clause is a match. If a binary clause matches, the
result-expr is returned, if a ternary clause matches, its result-fn,
which must be a unary function, is called with the result of the
predicate as its argument, the result of that call being the return
value of condp. A single default expression can follow the clauses,
and its value will be returned if no clause matches. If no default
expression is provided and no clause matches, an
IllegalArgumentException is thrown."
[pred expr & clauses]
(let [gpred (gensym "pred__")
gexpr (gensym "expr__")
emit (fn emit [pred expr args]
(let [[[a b c :as clause] more]
(split-at (if (= :>> (second args)) 3 2) args)
n (count clause)]
(cond
(= 0 n) `(throw (ArgumentError. (str "No matching clause: " ~expr)))
(= 1 n) a
(= 2 n) `(if (~pred ~a ~expr)
~b
~(emit pred expr more))
:else `(if-let [p# (~pred ~a ~expr)]
(~c p#)
~(emit pred expr more)))))]
`(let [~gpred ~pred
~gexpr ~expr]
~(emit gpred gexpr clauses))))
(defmacro loop
"Evaluates the exprs in a lexical context in which the symbols in
the binding-forms are bound to their respective init-exprs or parts
therein. Acts as a recur target."
{:added "1.0", :special-form true, :forms '[(loop [bindings*] exprs*)]}
[bindings & body]
#_(assert-args
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
(let [db (destructure bindings)]
(if (= db bindings)
`(loop* ~bindings ~@body)
(let [vs (take-nth 2 (drop 1 bindings))
bs (take-nth 2 bindings)
gs (map (fn [b] (if (symbol? b) b (gensym))) bs)
bfs (reduce (fn [ret [b v g]]
(if (symbol? b)
(conj ret g v)
(conj ret g v b g)))
[] (map vector bs vs gs))]
`(let ~bfs
(loop* ~(vec (interleave gs gs))
(let ~(vec (interleave bs gs))
~@body)))))))
(defmacro while
"Repeatedly executes body while test expression is true. Presumes
some side-effect will cause test to become false/nil. Returns nil"
[test & body]
`(loop []
(when ~test
~@body
(recur))))
(defmacro comment
"Ignores body, yields nil"
{:added "1.0"}
[& body])
(def ^:dynamic *print-readably* true)
(def ^:dynamic *print-dup* false)
(defprotocol IPrint
(-print [o string-sink]))
(extend-type fallback
IPrint
(-print [o sink]
(.write ^StringSink sink (.toString o))))
(extend-type Null
IPrint
(-print [o sink]
(.write ^StringSink sink "nil")))
(extend-type RegExp
IPrint
(-print [o sink]
(.write ^StringSink sink (.-pattern o))))
;; TODO js does define infinite but not native & VM, handle theses cases
(extend-type num
IPrint
(-print [o sink]
(cond
(and (.-isInfinite o) (.-isNegative o)) (.write ^StringSink sink "##-Inf")
(.-isInfinite o) (.write ^StringSink sink "##Inf")
(.-isNaN o) (.write ^StringSink sink "##Nan")
:else (.write ^StringSink sink (.toString o)))))
(defn ^bool string?
"Return true if x is a String"
[x]
(dart/is? x String))
(defn ^bool number?
"Returns true if x is a Number"
[x]
(dart/is? x num))
(defn ^bool int?
"Returns true if x is an int?"
[x]
(dart/is? x int))
(extend-type String
IPrint
(-print [s sink]
(let [^StringSink sink sink]
(if (or *print-dup* *print-readably*)
(do (.write sink \")
(dotimes [n (count s)]
(let [c (. s "[]" n)]
(.write sink (case c
\newline "\\n"
\tab "\\t"
\return "\\r"
\" "\\\""
\\ "\\\\"
\formfeed "\\f"
\backspace "\\b"
c))))
(.write sink \"))
(.write ^StringSink sink s)))
nil))
(deftype ^:abstract ToStringMixin []
Object
(toString [o]
(let [sb (StringBuffer.)]
(-print o sb)
(.toString sb))))
(defprotocol INamed
"Protocol for adding a name."
(-name [x]
"Returns the name String of x.")
(-namespace [x]
"Returns the namespace String of x."))
(defn ^String name
"Returns the name String of a string, symbol or keyword."
[x]
(if (string? x) x (-name x)))
(defn ^String? namespace
"Returns the namespace String of a symbol or keyword, or nil if not present."
{:inline (fn [x] `(-namespace ~x))
:inline-arities #{1}}
[x]
(-namespace x))
(defprotocol ISeqable
"Protocol for adding the ability to a type to be transformed into a sequence."
(-seq [o]
"Returns a seq of o, or nil if o is empty."))
(defn ^bool seqable?
"Return true if the seq function is supported for x."
[x]
(satisfies? ISeqable x))
(defn seq
"Returns a seq on the collection. If the collection is
empty, returns nil. (seq nil) returns nil. seq also works on
Strings, native Java arrays (of reference types) and any objects
that implement Iterable. Note that seqs cache values, thus seq
should not be used on any Iterable whose iterator repeatedly
returns the same mutable object."
{:inline (fn [coll] `(-seq ~coll))
:inline-arities #{1}}
[coll] (-seq coll))
(defprotocol ISeq
"Protocol for collections to provide access to their items as sequences."
(-first [coll]
"Returns the first item in the collection coll.")
(-rest [coll]
"Returns a new collection of coll without the first item. It should
always return a seq, e.g.
(rest []) => ()
(rest nil) => ()")
(-next [coll]
"Returns a new collection of coll without the first item. In contrast to
rest, it should return nil if there are no more items, e.g.
(next []) => nil
(next nil) => nil"))
(defn ^bool seq?
{:inline (fn [x] `(satisfies? ISeq ~x))
:inline-arities #{1}}
[x] (satisfies? ISeq x))
(extend-type Null
ISeqable
(-seq [coll] nil)
ISeq
(-first [coll] nil)
(-rest [coll] ())
(-next [coll] nil))
(defn first
"Returns the first item in the collection. Calls seq on its
argument. If coll is nil, returns nil."
[coll]
(-first (seq coll)))
(defn next
"Returns a seq of the items after the first. Calls seq on its
argument. If there are no more items, returns nil."
[coll]
(-next (seq coll)))
(defn rest
"Returns a possibly empty seq of the items after the first. Calls seq on its
argument."
[coll]
(-rest (seq coll)))
(defprotocol ISequential
"Marker interface indicating a persistent collection of sequential items")
(defn ^bool sequential?
"Returns true if coll implements Sequential"
{:inline-arities #{1}
:inline (fn [coll] `(satisfies? ISequential ~coll))}
[coll]
(satisfies? ISequential coll))
(defn ^bool realized?
"Returns true if a value has been produced for a promise, delay, future or lazy sequence."
{:inline-arities #{1}
:inline (fn [x] `(-realized? ~x))}
[x]
(-realized? x))
(defprotocol IPending
"Protocol for types which can have a deferred realization. Currently only
implemented by Delay and LazySeq."
(-realized? [x]
"Returns true if a value for x has been produced, false otherwise."))
(defn ^bool realized?
"Returns true if a value has been produced for a promise, delay, future or lazy sequence."
{:inline-arities #{1}
:inline (fn [x] `(-realized? ~x))}
[x]
(-realized? x))
(defprotocol IList
"Marker interface indicating a persistent list")
(defprotocol ICollection
"Protocol for adding to a collection."
(-conj [coll o]
"Returns a new collection of coll with o added to it. The new item
should be added to the most efficient place, e.g.
(conj [1 2 3 4] 5) => [1 2 3 4 5]
(conj '(2 3 4 5) 1) => '(1 2 3 4 5)"))
(extend-type Null
ICollection
(-conj [coll o] (cons o nil)))
(defn conj
"conj[oin]. Returns a new collection with the xs
'added'. (conj nil item) returns (item). The 'addition' may
happen at different 'places' depending on the concrete type."
{:inline-arities #{0 1 2}
:inline (fn
([] [])
([coll] coll)
([coll x] `(-conj ~coll ~x)))}
([] [])
([coll] coll)
([coll x] (-conj coll x))
([coll x & xs]
(if xs
(recur (-conj coll x) (first xs) (next xs))
(-conj coll x))))
(defn ^bool coll?
"Returns true if x satisfies ICollection"
[x]
(if (nil? x)
false
(satisfies? ICollection x)))
(defprotocol IDeref
"Protocol for adding dereference functionality to a reference."