/
core.cljc
1296 lines (1110 loc) · 57.8 KB
/
core.cljc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;; Copyright (c) George Lipov. All rights reserved.
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 2.0 (https://choosealicense.com/licenses/epl-2.0/)
;; which can be found in the file LICENSE 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 ghostwheel.core
#?(:cljs (:require-macros ghostwheel.core))
(:require [clojure.string :as string]
[clojure.set :refer [union difference map-invert]]
[clojure.walk :as walk]
[clojure.test :as t]
[clojure.spec.alpha :as s]
[clojure.spec.test.alpha :as st]
[clojure.spec.gen.alpha :as gen]
[ghostwheel.reporting :as r]
[ghostwheel.unghost :refer [clean-defn]]
[ghostwheel.utils :as u
:refer [cljs-env? get-ghostwheel-compiler-config
get-ns-meta get-ns-name clj->cljs]
:include-macros true]
[ghostwheel.logging :as l]
[ghostwheel.threading-macros :include-macros true]
[expound.alpha :as expound]
#?@(:clj [[clojure.core.specs.alpha]
[ghostwheel.stubs.ana-api :as ana-api]
[orchestra.spec.test :as ost]]
:cljs [[cljs.core.specs.alpha :include-macros true]
[cljs.analyzer.api :as ana-api]
[orchestra-cljs.spec.test :as ost]])))
;; REVIEW: Replace this pattern:
;; `(let [fn-name (fn ...)] (defn ...))` with
;; `letfn` when the ClojureScript bug is fixed:
;; https://dev.clojure.org/jira/browse/CLJS-1965
;;;; Global vars and state
;; This isn't particularly pretty, but it's how we avoid
;; having ClojureScript as a required dependency on Clojure
#?(:clj (try
(do
(ns-unalias (find-ns 'ghostwheel.core) 'ana-api)
(require '[cljs.analyzer.api :as ana-api]))
(catch Exception _ (require '[ghostwheel.stubs.ana-api :as ana-api]))))
(let [{:keys [::report-output] :as config} (u/get-env-config*)]
#?(:clj (alter-var-root #'ghostwheel.logging/*report-output* (constantly report-output))
:cljs (set! ghostwheel.logging/*report-output* report-output))
(when-let [expound-config (::expound config)]
#?(:clj (alter-var-root #'s/*explain-out* (constantly (expound/custom-printer expound-config)))
:cljs (set! s/*explain-out* (expound/custom-printer expound-config)))))
(def ^:private test-suffix "__ghostwheel-test")
(def ^:private *after-check-callbacks (atom []))
(def ^:private ^:dynamic *unsafe-bound-ops* #{})
(def ^:dynamic *global-trace-allowed?* true)
(def ^:dynamic *global-check-allowed?* true) ; REVIEW: Is anyone using this?
;;;; Misc helper functions
(defn- set-trace [enabled]
#?(:clj (alter-var-root #'*global-trace-allowed?* (constantly enabled))
:cljs (set! *global-trace-allowed?* enabled)))
(defn enable-trace! [] (set-trace true) "Tracing enabled.")
(defn disable-trace! [] (set-trace false) "Tracing disabled.")
(defn- set-check [enabled]
#?(:clj (alter-var-root #'*global-check-allowed?* (constantly enabled))
:cljs (set! *global-check-allowed?* enabled)))
(defn enable-check! [] (set-check true) "Check enabled.")
(defn disable-check! [] (set-check false) "Check disabled.")
(defn- count-args
"Returns a tuple with the number of regular and non-variadic arguments."
[conformed-args]
[(count (:args conformed-args))
(if (:varargs conformed-args) 1 0)])
;;;; Operators
;; It doesn't actually matter what these are bound to, they are stripped by the macros
;; they're used in and never end up in the final code. This is just so they can be used
;; without '=> cannot be resolved' errors in the IDE.
(def => :ret)
(def | :st)
(def <- :gen)
(defmacro ? [& forms]
(cond-> `(s/nilable ~@forms)
(cljs-env? &env) clj->cljs))
;;;; Specs
(s/def ::trace #{0 1 2 3 4 5 true})
(s/def ::trace-color (s/or :keyword keyword?
:literal (s/and string?
#(re-matches #"#[a-fA-F0-9]+" %)
#(or (= (count %) 7)
(= (count %) 4)))))
(s/def ::check boolean?)
(s/def ::check-coverage boolean?)
(s/def ::ignore-fx boolean?)
(s/def ::num-tests nat-int?)
(s/def ::num-tests-ext nat-int?)
(s/def ::extensive-tests boolean?)
(s/def ::defn-macro (s/nilable string?))
(s/def ::instrument boolean?)
(s/def ::outstrument boolean?)
(s/def ::extrument (s/nilable (s/coll-of qualified-symbol? :kind vector?)))
(s/def ::expound (s/nilable (s/map-of keyword? any?)))
(s/def ::report-output (s/coll-of #{:repl :js-console} :kind set? :distinct true :min-count 1))
;; TODO: Integrate bhauman/spell-spec
(s/def ::ghostwheel-config
(s/and (s/keys :req [::trace ::trace-color ::check ::check-coverage ::ignore-fx
::num-tests ::num-tests-ext ::extensive-tests ::defn-macro
::instrument ::outstrument ::extrument ::expound ::report-output])))
(s/assert ::ghostwheel-config u/ghostwheel-default-config)
;; TODO: Add check to make sure instrument and outstrument aren't both on
;; These are lifted straight from clojure.core.specs.alpha, because it
;; didn't seem possible to access them directly in the original namespace.
(s/def ::local-name (s/and simple-symbol? #(not= '& %)))
;; sequential destructuring
(s/def ::seq-binding-form
(s/and vector?
(s/cat :elems (s/* ::binding-form)
:rest (s/? (s/cat :amp #{'&} :form ::binding-form))
:as (s/? (s/cat :as #{:as} :sym ::local-name)))))
;; map destructuring
(s/def ::keys (s/coll-of ident? :kind vector?))
(s/def ::syms (s/coll-of symbol? :kind vector?))
(s/def ::strs (s/coll-of simple-symbol? :kind vector?))
(s/def ::or (s/map-of simple-symbol? any?))
(s/def ::as ::local-name)
(s/def ::map-special-binding
(s/keys :opt-un [::as ::or ::keys ::syms ::strs]))
(s/def ::map-binding (s/tuple ::binding-form any?))
(s/def ::ns-keys
(s/tuple
(s/and qualified-keyword? #(-> % name #{"keys" "syms"}))
(s/coll-of simple-symbol? :kind vector?)))
(s/def ::map-bindings
(s/every (s/or :mb ::map-binding
:nsk ::ns-keys
:msb (s/tuple #{:as :or :keys :syms :strs} any?))
:into {}))
(s/def ::map-binding-form (s/merge ::map-bindings ::map-special-binding))
(s/def ::binding-form
(s/or :sym ::local-name
:seq ::seq-binding-form
:map ::map-binding-form))
;;; Function and >defn specs
(s/def ::arg-list
(s/and vector?
(s/cat :args (s/* ::binding-form)
:varargs (s/? (s/cat :amp #{'&} :form ::binding-form)))))
(s/def ::pred-arg-list
(s/and vector?
(s/cat :args (s/* (s/or :sym ::local-name)))))
(s/def ::anon-args+body
(s/cat :args ::arg-list
:body (s/* any?)))
(s/def ::anon-fn
(s/and seq?
(s/cat :op #{'fn* 'fn}
:name (s/? simple-symbol?)
:bs (s/alt :arity-1 ::anon-args+body
:arity-n (s/+ (s/spec ::anon-args+body))))))
(s/def ::pred-fn
(s/and seq?
(s/cat :op #{'fn* 'fn}
:name (s/? simple-symbol?)
:args ::pred-arg-list
:body any?)))
(s/def ::spec-elem
(s/or :set set?
:pred-sym (s/and symbol?
(complement #{'| '=>})
;; REVIEW: should the `?` be a requirement?
#(string/ends-with? (str %) "?"))
:gspec (s/or :nilable-gspec ::nilable-gspec :gspec ::gspec)
:spec-key qualified-keyword?
:fun ::pred-fn
:list seq?))
(s/def ::such-that-op #{:st '|})
(s/def ::ret-op #{:ret '=>})
(s/def ::gen-op #{:gen '<-})
(s/def ::gspec
(s/and vector?
(s/cat :args (s/? (s/cat :args (s/+ ::spec-elem)
:args-such-that (s/? (s/cat :op ::such-that-op
:preds (s/+ ::pred-fn)))))
:ret-op ::ret-op
:ret ::spec-elem
:fn-such-that (s/? (s/cat :op ::such-that-op
:preds (s/+ ::pred-fn)))
:gen (s/? (s/cat :op ::gen-op
:gen-fn (s/? (some-fn seq? symbol?)))))))
(s/def ::nilable-gspec
(s/and vector?
(s/cat :maybe #{'? 's/nilable}
:gspec ::gspec)))
(s/def ::prepost (s/map-of #{:pre :post}
(s/coll-of seq?
:kind vector?
:distinct true)))
(s/def ::args+body
(s/cat :args ::arg-list
:body (s/alt :prepost+body (s/cat :prepost ::prepost
:body (s/+ any?))
:body (s/* any?))))
(s/def ::args+gspec+body
(s/&
(s/cat :args ::arg-list
:gspec (s/nilable ::gspec)
:body (s/alt :prepost+body (s/cat :prepost ::prepost
:body (s/+ any?))
:body (s/* any?)))
(fn arg-specs-match-param-count? [{:keys [args gspec]}]
(if-not gspec
true
(let [argcount (->> args count-args (apply +))
spec-args (:args gspec)]
(if spec-args
(-> spec-args :args count (= argcount))
(= argcount 0)))))))
(s/def ::defn
(s/and seq?
(s/cat :op #{'defn 'defn-}
:name simple-symbol?
:docstring (s/? string?)
:meta (s/? map?)
:bs (s/alt :arity-1 ::args+body
:arity-n (s/cat :bodies (s/+ (s/spec ::args+body))
:attr (s/? map?))))))
(s/def ::deftest
(s/and seq?
(s/cat :op #{'clojure.test/deftest 'cljs.test/deftest}
:name symbol?
:body any?)))
;;; Side effect detection specs
(s/def ::threading-macro-op
#{'-> '->> 'as-> 'cond-> 'cond->> 'some-> 'some->>
'*-> '*->> '*as-> '*cond-> '*cond->> '*some-> '*some->>})
(s/def ::binding-op
#{'let 'for 'doseq 'binding})
(s/def ::single-function-composition
#{'partial 'fnil})
(s/def ::safe-single-function-composition
#{'memoize 'complement})
(s/def ::multi-function-composition
#{'comp})
(s/def ::safe-multi-function-composition
#{'juxt 'every-pred 'some-fn})
(s/def ::function-application
#{'apply 'map 'fmap 'map-indexed 'reduce})
(s/def ::safe-function-application
#{'mapcat 'reduce-kv 'mapv 'reductions 'iterate 'keep 'keep-indexed
'remove 'filter 'filterv 'take-while 'drop-while
'sort 'sort-by 'sorted-map-by 'group-by 'merge-with})
(s/def ::unsafe-clj-block #{'do
'doseq
'dotimes})
;; REVIEW: maybe move the re-frame stuff out of here
(s/def ::unsafe-clj-call #{'dorun
'repeatedly
'dispatch
'js-delete
'aset})
(s/def ::unsafe-clj-comp
(s/alt :single-fn (s/cat :composition (s/alt :generic ::single-function-composition
:safe ::safe-single-function-composition)
:unsafe-op ::unsafe-op
:rest ::rest)
:multi-fn (s/cat :composition (s/alt :generic ::multi-function-composition
:safe ::safe-multi-function-composition)
:some-unsafe-ops ::some-unsafe-ops
:rest ::rest)))
(let [bang-suffix? #(string/ends-with? (str %) "!")]
(s/def ::bang-suffix (every-pred symbol? bang-suffix?))
(s/def ::unsafe-op
(s/alt :bang-suffix ::bang-suffix
:unsafe-anon-fn (s/and seq?
(s/alt :unsafe-body (s/cat :fun #{'fn 'fn*}
:name (s/? simple-symbol?)
:args ::arg-list
:body ::unsafe-form)
:unsafe-name (s/cat :fun #{'fn 'fn*}
:name (every-pred simple-symbol?
bang-suffix?)
:args ::arg-list
:body any?)))
:unsafe-clj-call ::unsafe-clj-call
:unsafe-clj-comp (s/spec ::unsafe-clj-comp)
:unsafe-bound-call #(contains? *unsafe-bound-ops* %)
:multi-form-op (s/cat :op #{'when 'when-not 'when-let 'when-first
'when-some 'let 'binding}
:pred-or-bindings any?
:fx (s/+ any?)
:return any?))))
(s/def ::safe-op #(not (s/valid? ::unsafe-op (list %))))
(s/def ::some-unsafe-ops (s/+ (s/cat :skipped-ops (s/* ::safe-op)
:unsafe-op ::unsafe-op)))
(s/def ::rest (s/* any?))
(s/def ::some-unsafe-bindings
(s/and vector?
(s/+ (s/cat :skipped-bindings (s/* (s/cat :binding ::binding-form
:value ::safe-op))
:unsafe-binding (s/cat :binding ::binding-form
:value ::unsafe-op)))))
(s/def ::unsafe-form
;; REVIEW: maybe make sure we are only matching on the simple symbol part
(s/or :unsafe-block (s/and seq?
(s/cat :unsafe-clj-block ::unsafe-clj-block
:rest ::rest))
:unsafe-call
(s/and seq?
(s/alt :direct (s/cat :application
(s/? (s/alt :generic ::function-application
:safe ::safe-function-application))
:unsafe-op ::unsafe-op
:rest ::rest)
:threading (s/cat :threading-macro-op ::threading-macro-op
:threaded-form any?
:some-unsafe-ops ::some-unsafe-ops
:rest ::rest)
:update (s/cat :update #{'update 'update-in}
:map any?
:path any?
:unsafe-op ::unsafe-op
:rest ::rest)))
:unsafe-composition (s/and seq? ::unsafe-clj-comp)
:unsafe-binding (s/and seq?
(s/cat :binding-op ::binding-op
:bindings ::some-unsafe-bindings
:rest ::rest))
:unsafe-argument (s/and seq?
(s/cat :fun ::safe-op
:some-unsafe-ops ::some-unsafe-ops
:rest ::rest))
#_::unsafe-something #_(s/spec (s/cat ::some-unsafe-ops ::some-unsafe-ops
::rest ::rest))))
;;;; Main code generating functions
(let [find-fx
(fn find-fx [form]
(let [maybe-fx (s/conform ::unsafe-form form)
[found-fx
unsafe-bindings] (if (= maybe-fx ::s/invalid)
[nil nil]
[(conj {} maybe-fx)
(when (= (key maybe-fx) :unsafe-binding)
(-> maybe-fx
val
:bindings))])
;; TODO implement map and vec destructuring support for bindings
unsafe-binding-set (when unsafe-bindings
(->> unsafe-bindings
(map #(-> % :unsafe-binding :binding val))
(set)))]
[found-fx (vec
(for [nested-form form
:when (and (coll? nested-form))]
;; REVIEW go into nested anon-fns or not?
;(not (contains? #{'fn 'fn*} (first nested-form))))]
(binding [*unsafe-bound-ops* (cond-> *unsafe-bound-ops*
unsafe-bindings (union unsafe-binding-set))]
(find-fx nested-form))))]))
check-arity-fx
(fn [unformed-args-gspec-body]
(let [effects (->> (find-fx unformed-args-gspec-body)
(flatten)
(remove nil?)
(map first)
(vec))]
(-> (for [fx effects]
[(-> fx key name keyword)
(->> fx
(s/unform ::unsafe-form)
(apply list)
(str))
(->> fx
val
(walk/postwalk #(if (qualified-keyword? %)
(keyword (name %))
%))
vec)])
(cond->> (next unformed-args-gspec-body) (cons [:multiple-body-forms])))))]
(defn- generate-test [fn-name fspecs body-forms config cljs?]
(let [{:keys [::check ::num-tests ::num-tests-ext ::extensive-tests
::check-coverage ::ignore-fx]}
config
num-tests (if extensive-tests num-tests-ext num-tests)
marked-unsafe (s/valid? ::bang-suffix fn-name)
found-fx (if ignore-fx
[]
(->> (case (key body-forms)
:arity-1 [(val body-forms)]
:arity-n (val body-forms))
(map #(->> % (s/unform ::args+gspec+body) (drop 2)))
(mapcat check-arity-fx)
distinct
vec))
unexpected-fx (boolean (and (not ignore-fx)
(not marked-unsafe)
(seq found-fx)))
unexpected-safety (boolean (and (not ignore-fx)
marked-unsafe
(empty? found-fx)))
spec-keyword-ns (if cljs? 'clojure.test.check 'clojure.spec.test.check)
spec-checks (let [defined-fspecs (->> fspecs (remove nil?) vec)]
(when (and (seq defined-fspecs)
(not marked-unsafe)
(empty? found-fx)
(> num-tests 0))
`(for [spec# ~defined-fspecs]
(st/check-fn
~fn-name
spec#
{~(keyword (str spec-keyword-ns) "opts")
{:num-tests ~num-tests}}))))]
[unexpected-fx
`(t/deftest ~(symbol (str fn-name test-suffix))
(let [spec-checks# ~spec-checks]
;; TODO The `spec-checks#` thing trips up clairvoyant
;; and prevents tracing during ghostwheel development
(t/is (and (every? #(-> %
~(keyword (str spec-keyword-ns) "ret")
:pass?)
spec-checks#)
~(not unexpected-fx)
~(not unexpected-safety))
{::r/fn-name (quote ~fn-name)
::r/fspec ~(every? some? fspecs)
::r/spec-checks spec-checks#
::r/check-coverage ~check-coverage
::r/failure ~(cond unexpected-fx ::r/unexpected-fx
unexpected-safety ::r/unexpected-safety
:else ::r/spec-failure)
::r/found-fx (quote ~found-fx)
::r/marked-unsafe ~marked-unsafe})))])))
(defn- unscrew-vec-unform
"Half-arsed workaround for spec bugs CLJ-2003 and CLJ-2021."
[unformed-arg]
(if-not (sequential? unformed-arg)
unformed-arg
(let [malformed-seq-destructuring? (every-pred seq? (comp #{:as '&} first))
[unformed malformed] (split-with (complement malformed-seq-destructuring?) unformed-arg)]
(vec (concat unformed (apply concat malformed))))))
(defn- gspec->fspec*
[conformed-arg-list conformed-gspec anon-fspec? multi-arity-args? nilable?]
(let [{argspec-def :args
retspec :ret
fn-such-that :fn-such-that
{:keys [gen-fn] :as gen} :gen}
conformed-gspec]
(if (and anon-fspec?
argspec-def
(not gen)
(some #{'any?} (-> argspec-def :args vals)))
(if nilable? `(s/nilable ifn?) `ifn?)
(let [extract-spec
(fn extract-spec [[spec-type spec]]
(if (= spec-type :gspec)
(if (= (key spec) :nilable-gspec)
(gspec->fspec* nil (-> spec val :gspec) true false true)
(gspec->fspec* nil (val spec) true false false))
spec))
named-conformed-args
(when argspec-def
(let [all-args (remove nil? (concat (:args conformed-arg-list)
[(-> conformed-arg-list :varargs :form)]))
gen-arg-name (fn [index] (str "arg" (inc index)))
gen-name (fn [index [arg-type arg :as full-arg]]
(let [arg-name (if-not arg-type
(gen-arg-name index)
(case arg-type
:sym arg
:seq (or (-> arg :as :sym)
(gen-arg-name index))
:map (or (-> arg :as)
(gen-arg-name index))))]
[(keyword arg-name) full-arg]))]
(map-indexed gen-name (or (seq all-args)
(-> argspec-def :args count (repeat nil))))))
arg-binding-map
(if-not conformed-arg-list
{}
(if (every? #(= (-> % second key) :sym) named-conformed-args)
`{:keys ~(vec (map #(-> % first name symbol) named-conformed-args))}
(->> named-conformed-args
(map (fn [[arg-key conformed-arg]]
[(->> conformed-arg (s/unform ::binding-form) unscrew-vec-unform)
arg-key]))
(into {}))))
process-arg-pred
(fn process-arg-pred [{:keys [name args body]}]
(let [bindings (if-let [anon-arg (some-> args :args first second)]
(assoc arg-binding-map :as anon-arg)
arg-binding-map)]
(remove nil? `(fn ~name [~bindings] ~body))))
processed-args
(if-not argspec-def
`(s/cat)
(let [wrapped-params (->> argspec-def
:args
(map extract-spec)
(interleave (map first named-conformed-args))
(cons `s/cat))]
(if-let [args-such-that (:args-such-that argspec-def)]
(->> args-such-that
:preds
(map process-arg-pred)
(list* `s/and wrapped-params))
wrapped-params)))
process-ret-pred
(fn process-ret-pred [{:keys [name args body]}]
(let [anon-arg (some-> args :args first second)
ret-sym (gensym "ret__")
bindings [{(if multi-arity-args?
['_ arg-binding-map]
arg-binding-map) :args
ret-sym :ret}]
processed-body (if anon-arg
(walk/postwalk-replace {anon-arg ret-sym} body)
body)]
(remove nil? `(fn ~name ~bindings ~processed-body))))
fn-spec
(when fn-such-that
(let [processed-ret-preds (map process-ret-pred (:preds fn-such-that))]
(if (next processed-ret-preds)
(cons `s/and processed-ret-preds)
(first processed-ret-preds))))
final-fspec
(concat (when anon-fspec? [`s/fspec])
[:args processed-args]
[:ret (extract-spec retspec)]
(when fn-spec [:fn fn-spec])
(when gen-fn [:gen gen-fn]))]
(if nilable? `(s/nilable ~final-fspec) final-fspec)))))
;; TODO make sure we check whether the variadic bodies are legit
;; Can not have more than one
;; Can not have one with more regular args than the variadic one
;; To what extent does the compiler already check this?
(let [get-fspecs (fn [fn-body]
(let [[param-count variadic] (-> fn-body :args count-args)
gspec (or (:gspec fn-body)
(s/conform ::gspec
(vec (concat (repeat param-count 'any?)
(when (> variadic 0)
`[(s/* any?)])
'[=> any?]))))]
[(->> (if (> variadic 0) "n" param-count)
(str "arity-")
keyword)
(gspec->fspec* (:args fn-body) gspec false true false)]))
get-spec-part (fn [part spec]
(->> spec
(drop-while (complement #{part}))
second))]
(defn- generate-fspec-body [fn-bodies]
(case (key fn-bodies)
:arity-1
(when-let [gspec (-> fn-bodies val :gspec)]
(gspec->fspec* (-> fn-bodies val :args) gspec false false false))
:arity-n
(when (some :gspec (val fn-bodies))
(let [fspecs (map get-fspecs (val fn-bodies))
arg-specs (mapcat (fn [[arity spec]]
[arity (or (get-spec-part :args spec) `empty?)])
fspecs)
fn-param (gensym "p1__")
multi-ret-specs (when (->> fspecs
(map #(get-spec-part :ret (second %)))
distinct
count
(not= 1))
(mapcat (fn [[arity spec]]
[arity `(s/valid? ~(get-spec-part :ret spec)
(:ret ~fn-param))])
fspecs))
get-fn-clause (partial get-spec-part :fn)
fn-specs (when (->> fspecs (map second) (some get-fn-clause))
(mapcat (fn [[arity spec]]
[arity (if-let [fn-spec (get-fn-clause spec)]
`(s/valid? ~fn-spec ~fn-param)
true)])
fspecs))
;; NOTE: destructure args and ret in the arg vec
multi-ret-clause (when multi-ret-specs
`(fn ~'valid-multi-arity-ret? [~fn-param]
(case (-> ~fn-param :args key)
~@multi-ret-specs)))
multi-fn-clause (when fn-specs
`(fn ~'valid-multi-arity-fn? [~fn-param]
(case (-> ~fn-param :args key)
~@fn-specs)))]
;; Using s/or here even though s/alt seems to be more common
;; for multi-arity specs in the wild. The spec error reporting
;; is much better and it's immediately clear what didn't match.
(concat [:args `(s/or ~@arg-specs)]
(when-not multi-ret-clause
[:ret (get-spec-part :ret (-> fspecs first second))])
(when (or multi-ret-clause multi-fn-clause)
[:fn (if multi-fn-clause
(if multi-ret-clause
`(s/and ~multi-ret-clause ~multi-fn-clause)
multi-fn-clause)
multi-ret-clause)])))))))
(def ^:private spec-op->type
(let [map-prot "cljs.core.IMap"
coll-prot "cljs.core.ICollection"
;; Needed because Closure compiler/JS doesn't consider strings seqable
seqable-prot "(cljs.core.ISeqable|string)"]
{'number? "number"
'integer? "number"
'int? "number"
'nat-int? "number"
'pos-int? "number"
'neg-int? "number"
'float? "number"
'double? "number"
'int-in "number"
'double-in "number"
'string? "string"
'boolean? "boolean"
'keys map-prot
'map-of map-prot
'map? map-prot
'merge map-prot
'set? "cljs.core.ISet"
'vector? "cljs.core.IVector"
'tuple "cljs.core.IVector"
'seq? "cljs.core.ISeq"
'seqable? seqable-prot
'associative? "cljs.core.IAssociative"
'atom? "cljs.core.IAtom"
'coll-of coll-prot
'every coll-prot
'keyword? "cljs.core.Keyword"
'ifn? "cljs.core.IFn"
'fn? "Function"}))
(declare get-gspec-type)
(defn- get-type [recursive-call conformed-spec-elem]
(let [[spec-type spec-def] conformed-spec-elem
spec-op
;; REVIEW: This kinda wants to be a multi-method when it grows up.
(case spec-type
:list (let [op (-> spec-def first name symbol)]
(cond
(#{'nilable '?} op) (concat (->> spec-def
second
(s/conform ::spec-elem)
(get-type true))
[::nilable])
(#{'* '+} op) (concat (->> spec-def
second
(s/conform ::spec-elem)
(get-type true))
[::variadic])
(#{'and} op) [(-> spec-def second)] ; TODO
(#{'coll-of 'every} op) [(or (->> spec-def
(drop-while (complement #{:kind}))
second)
op)]
:else [op]))
;;TODO support (some-fn and (s/or
:gspec (let [gspec-def (val spec-def)]
(if (= (key spec-def) :nilable-gspec)
[(get-gspec-type (:gspec gspec-def)) ::nilable]
[(get-gspec-type gspec-def)]))
:pred-sym [spec-def]
[nil])]
(if recursive-call
spec-op
(if-let [js-type (spec-op->type (first spec-op))]
(let [modifiers (set (rest spec-op))]
(as-> js-type t
(str (if (::nilable modifiers) "?" "!") t)
(str (when (::variadic modifiers) "...") t)))
"*"))))
(defn- get-gspec-type [conformed-gspec]
(let [argspec-def (:args conformed-gspec)
args-jstype (if-not argspec-def
""
(->> (-> conformed-gspec :args :args)
(map (partial get-type false))
(string/join ", ")))
ret-jstype (get-type false (:ret conformed-gspec))]
(str "function(" args-jstype "): " ret-jstype)))
(defn- generate-type-annotations [env conformed-bs]
(when (cljs-env? env)
(case (key conformed-bs)
:arity-1 (when-let [gspec (-> conformed-bs val :gspec)]
{:jsdoc [(str "@type {" (get-gspec-type gspec) "}")]})
;; REVIEW: There doesn't seem to be a way to get valid annotations for args of
;; multi-arity functions and attempts to just annotate the return value(s) failed
;; as well. It wasn't possible to put together an annotation which was both
;; considered valid and resulted in a successful type check.
:arity-n nil #_(when-let [ret-types (as-> (val conformed-bs) x
(map #(get-type false (-> % :gspec :ret)) x)
(distinct x)
(when (not-any? #{"*" "?"} x) x))]
{:jsdoc [(str "@return {" (string/join "|" ret-types) "}")]}))))
(defn- merge-config [env metadata]
(s/assert ::ghostwheel-config
(->> (merge (u/get-env-config env)
(get-ns-meta env)
metadata)
(filter #(= (-> % key namespace) (name `ghostwheel.core)))
(into {}))))
(defn- get-quoted-qualified-fn-name [env fn-name]
`(quote ~(symbol (str (get-ns-name env)) (str fn-name))))
(defn- generate-fdef
[forms env]
(let [{[type fn-name] :name bs :bs} (s/conform ::>fdef-args forms)]
(case type
:sym (let [quoted-qualified-fn-name (get-quoted-qualified-fn-name env fn-name)
{:keys [::instrument ::outstrument]} (merge-config env (meta fn-name))
instrumentation (cond outstrument `(ost/instrument ~quoted-qualified-fn-name)
instrument `(st/instrument ~quoted-qualified-fn-name)
:else nil)
fdef `(s/fdef ~fn-name ~@(generate-fspec-body bs))]
(if instrumentation
`(do ~fdef ~instrumentation)
fdef))
:key `(s/def ~fn-name (s/fspec ~@(generate-fspec-body bs))))))
(let [process-defn-body
(fn [cfg fspec args+gspec+body]
(let [{:keys [env fn-name traced-fn-name trace color unexpected-fx]} cfg
{:keys [args body]} args+gspec+body
[prepost orig-body-forms] (case (key body)
:prepost+body [(-> body val :prepost)
(-> body val :body)]
:body [nil (val body)])
process-arg (fn [[arg-type arg]]
(as-> arg arg
(case arg-type
:sym [arg-type arg]
:seq [arg-type (update arg :as #(or % {:as :as :sym (gensym "arg_")}))]
:map [arg-type (update arg :as #(or % (gensym "arg_")))])))
;; NOTE: usage of extract-arg isn't elegant, there's duplication, refactor
extract-arg (fn [[arg-type arg]]
(case arg-type
:sym arg
:seq (get-in arg [:as :sym])
:map (:as arg)
nil))
unform-arg #(->> % (s/unform ::binding-form) unscrew-vec-unform)
reg-args (->> args :args (map process-arg))
var-arg (some-> args :varargs :form process-arg)
arg-list (vec (concat (map unform-arg reg-args)
(when var-arg ['& (unform-arg var-arg)])))
body-forms (if (and fspec (every? nil? orig-body-forms))
;; TODO error handling when specs too fancy for stub auto-generation
[`(apply (-> ~fspec s/gen gen/generate)
~@(map extract-arg reg-args) ~(extract-arg var-arg))]
(cond unexpected-fx
[`(throw (~(if (cljs-env? env) 'js/Error. 'Exception.)
~(str "Calling function `"
fn-name
"` which has unexpected side effects.")))]
(= trace :dispatch)
[`(if *global-trace-allowed?*
(apply ~traced-fn-name
~@(map extract-arg reg-args)
~(extract-arg var-arg))
(do ~@orig-body-forms))]
(= trace 1)
`[(do
(l/pr-clog ~(str (list fn-name arg-list))
nil
{::r/background ~color})
~@orig-body-forms)]
(>= trace 4)
(let [threading-macros-mappings
{'-> 'ghostwheel.threading-macros/*->
'->> 'ghostwheel.threading-macros/*->>
'as-> 'ghostwheel.threading-macros/*as->
'cond-> 'ghostwheel.threading-macros/*cond->
'cond->> 'ghostwheel.threading-macros/*cond->>
'some-> 'ghostwheel.threading-macros/*some->
'some->> 'ghostwheel.threading-macros/*some->>}]
(cond->> (walk/postwalk-replace threading-macros-mappings
orig-body-forms)
;; Make sure we don't trace threading macros in anon-fns
;; when anon-fns themselves aren't traced
(< trace 5)
(walk/postwalk
#(if (and (list? %)
(#{'fn 'fn*} (first %)))
(walk/postwalk-replace (map-invert threading-macros-mappings) %)
%))))
:else
orig-body-forms))]
(remove nil? `(~arg-list ~prepost ~@body-forms))))]
(defn- generate-defn
[forms private env]
(let [cljs? (cljs-env? env)
conformed-gdefn (s/conform ::>defn-args forms)
fn-bodies (:bs conformed-gdefn)
empty-bodies (every? empty?
(case (key fn-bodies)
:arity-1 (list (-> fn-bodies val :body val))
:arity-n (->> fn-bodies
val
(map :body)
(map val))))
arity (key fn-bodies)
fn-name (:name conformed-gdefn)
quoted-qualified-fn-name
(get-quoted-qualified-fn-name env fn-name)
traced-fn-name (gensym (str fn-name "__"))
docstring (:docstring conformed-gdefn)
meta-map (merge (:meta conformed-gdefn)
(generate-type-annotations env fn-bodies)
{::ghostwheel true})
;;; Assemble the config
config (merge-config env
(merge (meta fn-name) meta-map))
color (if-let [color (get l/ghostwheel-colors (::trace-color config))]
color
(:black l/ghostwheel-colors))
{:keys [::defn-macro ::instrument ::outstrument ::trace ::check]} config
defn-sym (cond defn-macro (with-meta (symbol defn-macro) {:private private})
private 'defn-
:else 'defn)
trace (if (cljs-env? env)
(cond empty-bodies 0
(true? trace) 4
:else trace)
0) ; TODO: Clojure
;;; Code generation
fdef-body (generate-fspec-body fn-bodies)
fdef (when fdef-body `(s/fdef ~fn-name ~@fdef-body))
instrumentation (when (not empty-bodies)
(cond outstrument `(ost/instrument ~quoted-qualified-fn-name)
instrument `(st/instrument ~quoted-qualified-fn-name)
:else nil))
individual-arity-fspecs
(map (fn [{:keys [args gspec]}]
(when gspec
(gspec->fspec* args gspec true false false)))
(val fn-bodies))
[unexpected-fx generated-test] (when (and check (not empty-bodies))
(let [fspecs (case arity
:arity-1 [(when fdef-body `(s/fspec ~@fdef-body))]
:arity-n individual-arity-fspecs)]
(generate-test fn-name fspecs fn-bodies config cljs?)))
process-fn-bodies (fn [trace]
(let [process-cfg {:env env
:fn-name fn-name
:traced-fn-name traced-fn-name
:trace trace
:color color
:unexpected-fx unexpected-fx}]
(case arity
:arity-1 (->> fn-bodies val (process-defn-body process-cfg `(s/fspec ~@fdef-body)))
:arity-n (map (partial process-defn-body process-cfg)
individual-arity-fspecs
(val fn-bodies)))))
clairvoyant-trace (fn [forms exclude]
(let [clairvoyant 'clairvoyant.core/trace-forms
tracer 'ghostwheel.tracer/tracer]
#?(:clj (if cljs?
(when-not (and (find-ns (symbol (namespace clairvoyant)))
(find-ns (symbol (namespace tracer))))
(throw (Exception. "Can't find tracing namespaces. Either add `gnl/ghostwheel-tracer` artifact and `(:require [ghostwheel.tracer])`, or disable tracing in order to compile.")))
(throw (Exception. "Tracing is not yet implemented for Clojure."))))
`(~clairvoyant
{:enabled true
:tracer (~tracer
:color "#fff"
:background ~color
:expand ~(if (>= trace 3)