/
typed.clj
2309 lines (2047 loc) · 83 KB
/
typed.clj
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
^{:doc "This namespace contains typed wrapper macros, type aliases
and functions for type checking Clojure code. check-ns is the interface
for checking namespaces, cf for checking individual forms."}
clojure.core.typed
(:refer-clojure :exclude [type defprotocol #_letfn fn loop dotimes let for doseq
defn atom ref
#_def #_filter #_remove])
(:require [clojure.core :as core]
[clojure.pprint :as pprint]
[clojure.set :as set]
[clojure.string :as str]
[clojure.core.typed.current-impl :as impl]
[clojure.core.typed.load-if-needed :as load]
[clojure.core.typed.util-vars :as vs]
[clojure.core.typed.profiling :as p]
;[clojure.core.typed.parse-ast :as ast]
[clojure.core.typed.internal :as internal]
[clojure.core.typed.errors :as err]
[clojure.core.typed.special-form :as spec]
[clojure.core.typed.import-macros :as import-m]
[clojure.core.typed.macros :as macros]
[clojure.java.io :as io])
(:import (clojure.lang Compiler)))
(import-m/import-macros clojure.core.typed.macros
[def fn loop let ann-form tc-ignore defprotocol
when-let-fail defn atom ref])
;=============================================================
; # core.typed
;
; This is the main namespace for core.typed. This project is
; split into many internal namespaces. Here are some of the main ones:
;
; c.c.typed.base-env
; The base global type environment. All base Var Annotations,
; Java method annotations, Class overriding and other annotations
; live here.
;
; c.c.typed.type-{rep,ctors}, c.c.parse-unparse,
; c.c.typed.fold-{rep,default}
; Internal type representation and operations.
;
; c.c.typed.check
; The type checker.
;
; c.c.typed.cs-gen
; Polymorphic local type inference algorithm.
(defn load-if-needed
"Load and initialize all of core.typed if not already"
[]
(load/load-if-needed))
(defn reset-caches
"Reset internal type caches."
[]
(load-if-needed)
((impl/v 'clojure.core.typed.reset-caches/reset-caches))
nil)
;(ann method-type [Symbol -> nil])
(defn method-type
"Given a method symbol, print the core.typed types assigned to it.
Intended for use at the REPL."
[mname]
(load-if-needed)
(let [type-reflect (impl/v 'clojure.reflect/type-reflect)
unparse-type (impl/v 'clojure.core.typed.parse-unparse/unparse-type)
Method->Type (impl/v 'clojure.core.typed.check/Method->Type)
ms (->> (type-reflect (Class/forName (namespace mname)))
:members
(core/filter #(and (instance? clojure.reflect.Method %)
(= (str (:name %)) (name mname))))
set)
_ (assert (seq ms) (str "Method " mname " not found"))]
(println "Method name:" mname)
(flush)
(core/doseq [m ms]
(println (unparse-type
(Method->Type m)))
(flush))))
;=============================================================
; Special functions
(defn print-filterset
"During type checking, print the filter set attached to form,
preceeded by literal string debug-string.
Returns nil.
eg. (let [s (seq (get-a-seqable))]
(print-filterset \"Here now\" s))"
[debug-string frm]
frm)
(defn ^:skip-wiki
inst-poly
"Internal use only. Use inst."
[inst-of types-syn]
inst-of)
(defn ^:skip-wiki
inst-poly-ctor
"Internal use only. Use inst-ctor"
[inst-of types-syn]
inst-of)
;FIXME should be a special do-op
(defmacro inst
"Instantiate a polymorphic type with a number of types.
eg. (inst foo-fn t1 t2 t3 ...)"
[inst-of & types]
`(inst-poly ~inst-of '~types))
;FIXME should be a special do-op
(defmacro inst-ctor
"Instantiate a call to a constructor with a number of types.
First argument must be an immediate call to a constructor.
Returns exactly the instantiatee (the first argument).
eg. (inst-ctor (PolyCtor. a b c)
t1 t2 ...)"
[inst-of & types]
`(inst-poly-ctor ~inst-of '~types))
(defn ^:skip-wiki
fn>-ann
"Internal use only. Use fn>."
[fn-of param-types-syn]
fn-of)
(defn ^:skip-wiki
pfn>-ann
"Internal use only. Use pfn>."
[fn-of polys param-types-syn]
fn-of)
(defn ^:skip-wiki
loop>-ann
"Internal use only. Use loop>"
[loop-of bnding-types]
loop-of)
(defmacro ^{:deprecated "0.2.45"} dotimes>
"DEPRECATED: Use clojure.core.typed/dotimes
Like dotimes.
eg. (dotimes> [_ 100]
(println \"like normal\"))"
[bindings & body]
(err/deprecated-renamed-macro
&form
'dotimes>
'dotimes)
(@#'core/assert-args
(vector? bindings) "a vector for its binding"
(= 2 (count bindings)) "exactly 2 forms in binding vector")
(let [i (first bindings)
n (second bindings)]
`(let [n# (long ~n)]
(loop> [~i :- ~'clojure.core.typed/AnyInteger 0]
(when (< ~i n#)
~@body
(recur (unchecked-inc ~i)))))))
(defmacro dotimes
"Like clojure.core/dotimes, but with optional annotations.
If annotation for binding is omitted, defaults to Int.
eg. (dotimes [_ 100]
(println \"like normal\"))
(dotimes [x :- Num, 100.123]
(println \"like normal\" x))"
[bindings & body]
(@#'core/assert-args
(vector? bindings) "a vector for its binding"
(= 2 (count bindings)) "exactly 2 forms in binding vector")
(let [i (first bindings)
n (second bindings)]
`(let [n# (long ~n)]
(loop [~i :- Int 0]
(when (< ~i n#)
~@body
(recur (unchecked-inc ~i)))))))
(defmacro ^{:deprecated "0.2.45"} for>
"DEPRECATED: use clojure.core.typed/for
Like for but requires annotation for each loop variable: [a [1 2]] becomes [a :- Long [1 2]]
Also requires annotation for return type.
eg. (for> :- Number
[a :- (U nil AnyInteger) [1 nil 2 3]
:when a]
(inc a))"
[tk ret-ann seq-exprs body-expr]
(err/deprecated-macro-syntax
&form
(str "clojure.core.typed/for> renamed to clojure.core.typed/for."
" Note the return type annotation has changed to after the binder: (for [a :- t, i] :- r, i)"))
(@#'core/assert-args
(vector? seq-exprs) "a vector for its binding"
(even? (count seq-exprs)) "an even number of forms in binding vector")
(assert (#{:-} tk) "Must provide return type annotation for for>.")
(let [normalise-args
; change [a :- b c] to [[a :- b] c]
(fn [seq-exprs]
(loop [flat-result ()
seq-exprs seq-exprs]
(cond
(empty? seq-exprs) flat-result
(keyword? (first seq-exprs)) (recur (concat flat-result (take 2 seq-exprs))
(drop 2 seq-exprs))
(and (vector? (first seq-exprs))
(#{:-} (-> seq-exprs first second))) (do
(err/deprecated-macro-syntax
&form
"for> syntax has changed, use [b :- t i] for clauses")
(recur (concat flat-result (take 2 seq-exprs))
(drop 2 seq-exprs)))
:else (do (assert (#{:-} (second seq-exprs))
"Incorrect syntax in for>.")
(recur (concat flat-result [(vec (take 3 seq-exprs))
(nth seq-exprs 3)])
(drop 4 seq-exprs))))))
; normalise seq-exprs to be flat pairs
seq-exprs (normalise-args seq-exprs)
to-groups (fn [seq-exprs]
(@#'core/reduce1 (fn [groups [k v]]
(if (keyword? k)
(conj (pop groups) (conj (peek groups) [k v]))
(conj groups [k v])))
[] (partition 2 seq-exprs)))
err (fn [& msg] (throw (IllegalArgumentException. ^String (apply str msg))))
emit-bind (fn emit-bind [[[bind expr & mod-pairs]
& [[_ next-expr] :as next-groups]]]
(let [_ (assert (and (vector? bind)
(#{3} (count bind))
(#{:-} (second bind)))
"Binder must be of the form [lhs :- type]")
bind-ann (nth bind 2)
bind (nth bind 0)
giter (gensym "iter__")
gxs (gensym "s__")
do-mod (fn do-mod [[[k v :as pair] & etc]]
(cond
(= k :let) `(core/let ~v ~(do-mod etc))
(= k :while) `(when ~v ~(do-mod etc))
(= k :when) `(if ~v
~(do-mod etc)
(recur (rest ~gxs)))
(keyword? k) (err "Invalid 'for' keyword " k)
next-groups
`(core/let [iterys# ~(emit-bind next-groups)
fs# (seq (iterys# ~next-expr))]
(if fs#
(concat fs# (~giter (rest ~gxs)))
(recur (rest ~gxs))))
:else `(cons ~body-expr
(~giter (rest ~gxs)))))]
(if next-groups
#_"not the inner-most loop"
`(ann-form
(fn ~giter [~gxs]
(lazy-seq
(loop> [~gxs :- (Option (Seqable ~bind-ann)) ~gxs]
(when-first [~bind ~gxs]
~(do-mod mod-pairs)))))
[(~'clojure.core.typed/Option (~'clojure.lang.Seqable ~bind-ann)) ~'-> (~'clojure.core.typed/Seq ~ret-ann)])
#_"inner-most loop"
(let [gi (gensym "i__")
gb (gensym "b__")
do-cmod (fn do-cmod [[[k v :as pair] & etc]]
(cond
(= k :let) `(core/let ~v ~(do-cmod etc))
(= k :while) `(when ~v ~(do-cmod etc))
(= k :when) `(if ~v
~(do-cmod etc)
(recur
(unchecked-inc ~gi)))
(keyword? k)
(err "Invalid 'for' keyword " k)
:else
`(do (chunk-append ~gb
; put an ann-form here so at least one error message
; points to code the user can recognise.
(ann-form ~body-expr
~ret-ann))
(recur (unchecked-inc ~gi)))))]
`(ann-form
(fn ~giter [~gxs]
(lazy-seq
(loop> [~gxs :- (Option (Seqable ~bind-ann)) ~gxs]
(when-let [~gxs (seq ~gxs)]
(if (chunked-seq? ~gxs)
(core/let [c# (chunk-first ~gxs)
size# (int (count c#))
~gb (ann-form (chunk-buffer size#)
(~'clojure.lang.ChunkBuffer ~ret-ann))]
(if (loop> [~gi :- AnyInteger, (int 0)]
(if (< ~gi size#)
(core/let [;~bind (.nth c# ~gi)]
~bind (nth c# ~gi)]
~(do-cmod mod-pairs))
true))
(chunk-cons
(chunk ~gb)
(~giter (chunk-rest ~gxs)))
(chunk-cons (chunk ~gb) nil)))
(core/let [~bind (first ~gxs)]
~(do-mod mod-pairs)))))))
[(~'clojure.core.typed/Option (~'clojure.lang.Seqable ~bind-ann)) ~'->
(~'clojure.core.typed/Seq ~ret-ann)])))))]
`(core/let [iter# ~(emit-bind (to-groups seq-exprs))]
(iter# ~(second seq-exprs)))))
(defmacro for
"Like clojure.core/for with optional type annotations.
All types default to Any.
The :let option uses clojure.core.typed/let.
eg. (for [a :- (U nil Int) [1 nil 2 3]
:when a]
:- Number
(inc a))"
[seq-exprs & maybe-ann-body-expr]
(@#'core/assert-args
(vector? seq-exprs) "a vector for its binding"
(even? (count seq-exprs)) "an even number of forms in binding vector")
(let [[ret-ann body-expr] (if (#{:-} (first maybe-ann-body-expr))
(let [_ (assert (#{3} (count maybe-ann-body-expr))
(str "Wrong arguments to for: " maybe-ann-body-expr))
[colon t body] maybe-ann-body-expr]
[t body])
(let [_ (assert (#{1} (count maybe-ann-body-expr))
(str "Wrong arguments to for: " maybe-ann-body-expr))
[body] maybe-ann-body-expr]
[`Any body]))
normalise-args
; change [a :- b c] to [[a :- b] c]
(fn [seq-exprs]
(loop [flat-result []
seq-exprs seq-exprs]
(cond
(empty? seq-exprs) flat-result
;for options (:let, :while etc)
(keyword? (first seq-exprs)) (let [_ (assert (#{2} (count (take 2 seq-exprs)))
(str "for option missing " (first seq-exprs)))
[k v & rst] seq-exprs]
(recur (conj flat-result k v)
rst))
:else (if (#{:-} (second seq-exprs))
(let [_ (assert (#{4} (count (take 4 seq-exprs)))
(str "for parameter missing after ':-'"))
[b colon t init & rst] seq-exprs]
(recur (conj flat-result [b colon t] init)
rst))
(let [_ (assert (#{2} (count (take 2 seq-exprs)))
(str "for binding needs initial values"))
[b init & rst] seq-exprs]
(recur (conj flat-result [b :- `Any] init)
rst))))))
; normalise seq-exprs to be flat pairs
seq-exprs (normalise-args seq-exprs)
to-groups (fn [seq-exprs]
(reduce (fn [groups [k v]]
(if (keyword? k)
(conj (pop groups) (conj (peek groups) [k v]))
(conj groups [k v])))
[] (partition 2 seq-exprs)))
err (fn [& msg] (throw (IllegalArgumentException. ^String (apply str msg))))
emit-bind (fn emit-bind [[[bind expr & mod-pairs]
& [[_ next-expr] :as next-groups]]]
(let [_ (assert (and (vector? bind)
(#{3} (count bind))
(#{:-} (second bind)))
"Binder must be of the form [lhs :- type]")
bind-ann (nth bind 2)
bind (nth bind 0)
giter (gensym "iter__")
gxs (gensym "s__")
do-mod (fn do-mod [[[k v :as pair] & etc]]
(cond
;typed let
(= k :let) `(let ~v ~(do-mod etc))
(= k :while) `(when ~v ~(do-mod etc))
(= k :when) `(if ~v
~(do-mod etc)
(recur (rest ~gxs)))
(keyword? k) (err "Invalid 'for' keyword " k)
next-groups
`(let [iterys# ~(emit-bind next-groups)
fs# (seq (iterys# ~next-expr))]
(if fs#
(concat fs# (~giter (rest ~gxs)))
(recur (rest ~gxs))))
:else `(cons ~body-expr
(~giter (rest ~gxs)))))]
(if next-groups
#_"not the inner-most loop"
`(fn ~giter [~gxs :- (Option (Seqable ~bind-ann))]
:- (Seq ~ret-ann)
(lazy-seq
(loop [~gxs :- (Option (Seqable ~bind-ann)) ~gxs]
(when-first [~bind ~gxs]
~(do-mod mod-pairs)))))
#_"inner-most loop"
(let [gi (gensym "i__")
gb (gensym "b__")
do-cmod (fn do-cmod [[[k v :as pair] & etc]]
(cond
; typed let
(= k :let) `(let ~v ~(do-cmod etc))
(= k :while) `(when ~v ~(do-cmod etc))
(= k :when) `(if ~v
~(do-cmod etc)
(recur
(unchecked-inc ~gi)))
(keyword? k)
(err "Invalid 'for' keyword " k)
:else
`(do (chunk-append ~gb
; put an ann-form here so at least one error message
; points to code the user can recognise.
(ann-form ~body-expr
~ret-ann))
(recur (unchecked-inc ~gi)))))]
`(fn ~giter [~gxs :- (Option (Seqable ~bind-ann))]
:- (Seq ~ret-ann)
(lazy-seq
(loop [~gxs :- (Option (Seqable ~bind-ann)) ~gxs]
(when-let [~gxs (seq ~gxs)]
(if (chunked-seq? ~gxs)
(let [c# (chunk-first ~gxs)
size# (int (count c#))
~gb (ann-form (chunk-buffer size#)
(~'clojure.lang.ChunkBuffer ~ret-ann))]
(if (loop [~gi :- Int, (int 0)]
(if (< ~gi size#)
(let [;~bind (.nth c# ~gi)]
~bind (nth c# ~gi)]
~(do-cmod mod-pairs))
true))
(chunk-cons
(chunk ~gb)
(~giter (chunk-rest ~gxs)))
(chunk-cons (chunk ~gb) nil)))
(let [~bind (first ~gxs)]
~(do-mod mod-pairs)))))))))))]
`(let [iter# ~(emit-bind (to-groups seq-exprs))]
(iter# ~(second seq-exprs)))))
(defmacro ^{:deprecated "0.2.45"} doseq>
"DEPRECATED: use clojure.core.typed/doseq
Like doseq but requires annotation for each loop variable:
[a [1 2]] becomes [a :- Long [1 2]]
eg.
(doseq> [a :- (U nil AnyInteger) [1 nil 2 3]
:when a]
(inc a))"
[seq-exprs & body]
(err/deprecated-renamed-macro
&form
'doseq>
'doseq)
(@#'core/assert-args
(vector? seq-exprs) "a vector for its binding"
(even? (count seq-exprs)) "an even number of forms in binding vector")
(let [normalise-args
; change [a :- b c] to [[a :- b] c]
(fn [seq-exprs]
(loop [flat-result ()
seq-exprs seq-exprs]
(cond
(empty? seq-exprs) flat-result
(keyword? (first seq-exprs)) (recur (concat flat-result (take 2 seq-exprs))
(drop 2 seq-exprs))
(and (vector? (first seq-exprs))
(#{:-} (-> seq-exprs first second))) (do
(err/deprecated-macro-syntax
&form
"doseq> binder syntax [[b :- t] i] has changed, use [b :- t i]")
(recur (concat flat-result (take 2 seq-exprs))
(drop 2 seq-exprs)))
:else (do (assert (#{:-} (second seq-exprs))
"Incorrect syntax in doseq>")
(recur (concat flat-result [(vec (take 3 seq-exprs))
(nth seq-exprs 3)])
(drop 4 seq-exprs))))))
; normalise seq-exprs to be flat pairs
seq-exprs (normalise-args seq-exprs)
step (fn step [recform exprs]
(if-not exprs
[true `(do ~@body)]
(let [k (first exprs)
v (second exprs)]
(if (keyword? k)
(let [steppair (step recform (nnext exprs))
needrec (steppair 0)
subform (steppair 1)]
(cond
(= k :let) [needrec `(core/let ~v ~subform)]
(= k :while) [false `(when ~v
~subform
~@(when needrec [recform]))]
(= k :when) [false `(if ~v
(do
~subform
~@(when needrec [recform]))
~recform)]))
;; k is [k :- k-ann]
(let [_ (assert (and (vector? k)
(#{3} (count k))
(#{:-} (second k)))
"Binder must be of the form [lhs :- type]")
k-ann (nth k 2)
k (nth k 0)
; k is the lhs binding
seq- (gensym "seq_")
chunk- (with-meta (gensym "chunk_")
{:tag 'clojure.lang.IChunk})
count- (gensym "count_")
i- (gensym "i_")
recform `(recur (next ~seq-) nil 0 0)
steppair (step recform (nnext exprs))
needrec (steppair 0)
subform (steppair 1)
recform-chunk
`(recur ~seq- ~chunk- ~count- (unchecked-inc ~i-))
steppair-chunk (step recform-chunk (nnext exprs))
subform-chunk (steppair-chunk 1)]
[true
`(loop> [~seq- :- (U nil (Seq ~k-ann)) (seq ~v),
~chunk- :- (U nil (clojure.lang.IChunk ~k-ann)) nil
~count- :- (U Integer Long) 0,
~i- :- (U Integer Long) 0]
(if (and (< ~i- ~count-)
;; FIXME review this
;; core.typed thinks chunk- could be nil here
~chunk-)
(core/let [;~k (.nth ~chunk- ~i-)
~k (nth ~chunk- ~i-)]
~subform-chunk
~@(when needrec [recform-chunk]))
(when-let [~seq- (seq ~seq-)]
(if (chunked-seq? ~seq-)
(core/let [c# (chunk-first ~seq-)]
(recur (chunk-rest ~seq-) c#
(int (count c#)) (int 0)))
(core/let [~k (first ~seq-)]
~subform
~@(when needrec [recform]))))))])))))]
(nth (step nil (seq seq-exprs)) 1)))
(defmacro doseq
"Like clojure.core/doseq with optional annotations.
:let option uses clojure.core.typed/let
eg.
(doseq [a :- (U nil AnyInteger) [1 nil 2 3]
:when a]
(inc a))"
[seq-exprs & body]
(@#'core/assert-args
(vector? seq-exprs) "a vector for its binding"
(even? (count seq-exprs)) "an even number of forms in binding vector")
(let [normalise-args
; change [a :- b c] to [[a :- b] c]
(fn [seq-exprs]
(loop [flat-result []
seq-exprs seq-exprs]
(cond
(empty? seq-exprs) flat-result
;for options (:let, :while etc)
(keyword? (first seq-exprs)) (let [_ (assert (#{2} (count (take 2 seq-exprs)))
(str "for option missing " (first seq-exprs)))
[k v & rst] seq-exprs]
(recur (conj flat-result k v)
rst))
:else (if (#{:-} (second seq-exprs))
(let [_ (assert (#{4} (count (take 4 seq-exprs)))
(str "for parameter missing after ':-'"))
[b colon t init & rst] seq-exprs]
(recur (conj flat-result [b colon t] init)
rst))
(let [_ (assert (#{2} (count (take 2 seq-exprs)))
(str "for binding needs initial values"))
[b init & rst] seq-exprs]
(recur (conj flat-result [b :- `Any] init)
rst))))))
; normalise seq-exprs to be flat pairs
seq-exprs (normalise-args seq-exprs)
step (fn step [recform exprs]
(if-not exprs
[true `(do ~@body)]
(let [k (first exprs)
v (second exprs)]
(if (keyword? k)
(let [steppair (step recform (nnext exprs))
needrec (steppair 0)
subform (steppair 1)]
(cond
;typed let
(= k :let) [needrec `(let ~v ~subform)]
(= k :while) [false `(when ~v
~subform
~@(when needrec [recform]))]
(= k :when) [false `(if ~v
(do
~subform
~@(when needrec [recform]))
~recform)]))
;; k is [k :- k-ann]
(let [_ (assert (and (vector? k)
(#{3} (count k))
(#{:-} (second k)))
"Binder must be of the form [lhs :- type]")
k-ann (nth k 2)
k (nth k 0)
; k is the lhs binding
seq- (gensym "seq_")
chunk- (with-meta (gensym "chunk_")
{:tag 'clojure.lang.IChunk})
count- (gensym "count_")
i- (gensym "i_")
recform `(recur (next ~seq-) nil 0 0)
steppair (step recform (nnext exprs))
needrec (steppair 0)
subform (steppair 1)
recform-chunk
`(recur ~seq- ~chunk- ~count- (unchecked-inc ~i-))
steppair-chunk (step recform-chunk (nnext exprs))
subform-chunk (steppair-chunk 1)]
[true
`(loop [~seq- :- (U nil (Seq ~k-ann)) (seq ~v),
~chunk- :- (U nil (clojure.lang.IChunk ~k-ann)) nil
~count- :- Int 0,
~i- :- Int 0]
(if (and (< ~i- ~count-)
;; FIXME review this
;; core.typed thinks chunk- could be nil here
~chunk-)
(let [;~k (.nth ~chunk- ~i-)
~k (nth ~chunk- ~i-)]
~subform-chunk
~@(when needrec [recform-chunk]))
(when-let [~seq- (seq ~seq-)]
(if (chunked-seq? ~seq-)
(let [c# (chunk-first ~seq-)]
(recur (chunk-rest ~seq-) c#
(int (count c#)) (int 0)))
(let [~k (first ~seq-)]
~subform
~@(when needrec [recform]))))))])))))]
(nth (step nil (seq seq-exprs)) 1)))
(defmacro pfn>
"Define a polymorphic typed anonymous function.
(pfn> name? [binder+] :- type? [[param :- type]* & [param :- type *]?] exprs*)
(pfn> name? [binder+] (:- type? [[param :- type]* & [param :- type *]?] exprs*)+)"
[& forms]
(let [{:keys [poly fn parsed-methods]} (internal/parse-fn> true forms)]
`(pfn>-ann ~fn '~poly '~parsed-methods)))
(defmacro
^{:forms '[(fn> name? :- type? [param :- type* & param :- type * ?] exprs*)
(fn> name? (:- type? [param :- type* & param :- type * ?] exprs*)+)]}
^{:deprecated "0.2.45"}
fn>
"DEPRECATED: use clojure.core.typed/fn
Like fn, but with annotations. Annotations are mandatory
for parameters, with optional annotations for return type.
If fn is named, return type annotation is mandatory.
Suggested idiom: use commas between parameter annotation triples.
eg. (fn> [a :- Number, b :- (U Symbol nil)] ...)
;annotate return
(fn> :- String [a :- String] ...)
;named fn
(fn> fname :- String [a :- String] ...)
;multi-arity
(fn> fname
(:- String [a :- String] ...)
(:- Long [a :- String, b :- Number] ...))"
[& forms]
(err/deprecated-macro-syntax
&form
(str "clojure.core.typed/fn> renamed to clojure.core.typed/fn. "
"Note return type annotation now goes after the binder: (fn [a :- t] :- r, b)"))
(let [{:keys [fn parsed-methods]} (internal/parse-fn> false forms)]
`(fn>-ann ~fn '~parsed-methods)))
(defn- defn>-parse-typesig
"Helper for parsing type signatures out of defn> forms"
[forms]
(if (= :- (first forms))
(let [ret (second forms)
args (take-nth 3 (drop 2 (first (drop 2 forms))))]
`[~@args ~'-> ~ret])
`(IFn ~@(map defn>-parse-typesig forms))))
(defmacro
^{:deprecated "0.2.57"}
^{:forms '[(defn> name docstring? :- type [param :- type *] exprs*)
(defn> name docstring? (:- type [param :- type *] exprs*)+)]}
defn>
"DEPRECATED: Use defn
Like defn, but with annotations. Annotations are mandatory for
parameters and for return type.
eg. (defn> fname :- Integer [a :- Number, b :- (U Symbol nil)] ...)
;annotate return
(defn> fname :- String [a :- String] ...)
;multi-arity
(defn> fname
(:- String [a :- String] ...)
(:- Long [a :- String, b :- Number] ...))"
[name & fdecl]
(err/deprecated-renamed-macro
&form
'defn>
'defn)
(let [[docstring fdecl] (internal/take-when string? fdecl)
signature (defn>-parse-typesig fdecl)]
`(do (ann ~name ~signature)
~(list* 'def name
(concat
(when docstring [docstring])
[`(fn> ~name ~@fdecl)])))))
(defmacro
^{:forms '[(def> name docstring? :- type expr)]}
^{:deprecated "0.2.45"}
def>
"DEPRECATED: use clojure.core.typed/def
Like def, but with annotations.
eg. (def> vname :- Long 1)
;doc
(def> vname
\"Docstring\"
:- Long
1)"
[name & fdecl]
(err/deprecated-macro-syntax
&form
(str "clojure.core.typed/def> renamed to clojure.core.typed/def."
" Note that it is impossible to :refer to a var called def."))
(let [[docstring fdecl] (internal/take-when string? fdecl)
_ (assert (and (#{3} (count fdecl))
(#{:-} (first fdecl)))
(str "Bad def> syntax: " fdecl))
[_ tsyn body] fdecl]
`(do (ann ~name ~tsyn)
~(list* 'def name
(concat
(when docstring [docstring])
[body])))))
(defmacro
^{:forms '[(letfn> [fn-spec-or-annotation*] expr*)]}
letfn>
"Like letfn, but each function spec must be annotated.
eg. (letfn> [a :- [Number -> Number]
(a [b] 2)
c :- [Symbol -> nil]
(c [s] nil)]
...)"
[fn-specs-and-annotations & body]
(let [bindings fn-specs-and-annotations
; (Vector (U '[Symbol TypeSyn] LetFnInit))
normalised-bindings
(loop [[fbnd :as bindings] bindings
norm []]
(cond
(empty? bindings) norm
(symbol? fbnd) (do
(assert (#{:-} (second bindings))
"letfn> annotations require :- separator")
(assert (<= 3 (count bindings)))
(recur
(drop 3 bindings)
(conj norm [(nth bindings 0)
(nth bindings 2)])))
(list? fbnd) (recur
(next bindings)
(conj norm fbnd))
:else (throw (Exception. (str "Unknown syntax to letfn>: " fbnd)))))
{anns false inits true} (group-by list? normalised-bindings)
; init-syn unquotes local binding references to be compatible with hygienic expansion
init-syn (into {}
(for [[lb type] anns]
[lb `'~type]))]
`(core/letfn ~(vec inits)
;unquoted to allow bindings to resolve with hygiene
~init-syn
;preserve letfn empty body
~@(or body [nil]))))
(comment
(letfn :- Type
[(a (:- RetType [b :- Type] b)
(:- Any [b :- Type, c :- Type] c))]
)
(let :- Type
[f :- Type, foo]
(f 1))
(do :- Type
)
(fn ([a :- Type & r Type ... a] :- Type))
(pfn [x]
(:- Type [a :- Type & r Type ... a]))
(for :- Type
[a :- Type, init]
)
(dotimes
[a :- Type, init]
)
(loop :- Type
[a :- Type, init]
)
(doseq
[a :- Type, init]
)
(deftype [[x :variance :covariant]]
Name
[x :- Foo, y :- Bar]
)
(defrecord [[x :variance :covariant]]
Name
[x :- Foo, y :- Bar]
)
(definterface Name)
(reify)
)
;(defmacro
; ^{:see-also '[filter-identity]}
; filter
; "The same as clojure.core/filter, but supports inline annotations
; to help instantiate negative predicates.
;
; # Positive predicates
;
; Simple positive predicates like `number?` or `symbol?` that have a
; :then filter of the form `(is x 0) do not require annotation:
;
; (filter number? [1 2 3 nil 'a])
; ; (Seq Number)
;
; # Negative predicates
;
; If the predicate's :then filter has the form `(! x 0)`, like
; for example `identity`, this macro can help instantiate the expression.
;
; 2 type annotations are needed:
; :in the member type of the input
; :remove a type the predicate removes from the input collection
;
; (filter :in (U nil Number), :remove nil
; identity [1 2 nil])
; ; Number"
; [& args]
; (let [[flat-opt tail] (split-at (- (count args) 2) args)
; _ (assert (even? (count flat-opt)) (str "Uneven keyword arguments to filter"))
; _ (assert (#{2} (count tail)) "Wrong arguments to filter")
; {:as opt} flat-opt
; extra (seq (set/difference (set (keys opt)) #{:in :remove}))
; _ (assert (not extra) (str "Unsupported options to filter: " (set extra)))
; has-in (contains? opt :in)
; has-remove (contains? opt :remove)
; _ (assert (or (and has-in has-remove)
; (and (not has-in)
; (not has-remove)))
; "Must provide both :in and :remove if supplying one.")]
; (if (and has-in has-remove)
; `((inst core/filter ~(:in opt) ~(:remove opt)) ~@tail)
; `(core/filter ~@tail))))
;
;(defmacro filter-identity
; "Semantically the same as (filter identity coll).
;
; Expands out to the equivalent of
;
; ((inst filter t (U nil false))
; (inst identity t)
; coll)
;
; The type t is the member type of the collection argument.
;
; eg.
; (filter-identity :- (U nil Number) [1 2 nil 3])
; ; (Seq Number)
;
; (filter-identity :- (U nil Number false) [1 2 nil 3 false])
; ; (Seq Number)"
; [colon t coll]
; (assert (#{:in} colon)
; (str "Must provide :in option to filter-identity"))
; `(filter :in ~t :remove ~'(U nil false)
; (inst identity ~t)
; ; better error message
; (ann-form ~coll ~`(~'U nil (Seqable ~t)))))
;
;(defmacro
; ^{:see-also '[remove-nil remove-false]}
; remove
; "The same as clojure.core/remove, but supports inline annotations
; to help instantiate positive predicates.
;
; # Negative predicates
;
; Simple negative predicates like `number?` or `symbol?` that have a
; :else filter of the form `(is x 0) do not require annotation:
;
; (filter number? [1 2 3 nil 'a])
; ; (Seq Number)
;
; # Negative predicates
;
; If the predicate's :then filter has the form `(! x 0)`, like
; for example `identity`, this macro can help instantiate the expression.
;
; 2 type annotations are needed:
; :in the member type of the input
; :remove a type the predicate removes from the input collection
;
; (filter :in (U nil Number), :remove nil
; identity [1 2 nil])
; ; Number"
; [& args]
; (let [[flat-opt tail] (split-at (- (count args) 2) args)
; _ (assert (even? (count flat-opt)) (str "Uneven keyword arguments to filter"))
; _ (assert (#{2} (count tail)) "Wrong arguments to filter")
; {:as opt} flat-opt
; extra (seq (set/difference #{:in :remove} (set (keys opt))))
; _ (assert (not extra) (str "Unsupported options to filter: " (set extra)))
; has-in (contains? opt :in)
; has-remove (contains? opt :remove)
; _ (assert (or (and has-in has-remove)
; (and (not has-in)
; (not has-remove)))
; "Must provide both :in and :remove if supplying one.")]
; (if (and has-in has-remove)
; `((inst core/filter ~(:in opt) ~(:remove opt)) ~@tail)
; `(filter ~@tail))))
;
;(defmacro remove-nil
; "Semantically the same as (remove nil? coll)
;
; eg. (remove-nil :in (U nil Number) [1 2 nil 3])
; ; (Seq Number)