-
Notifications
You must be signed in to change notification settings - Fork 790
/
Copy pathanalyzer.cljc
4731 lines (4322 loc) · 185 KB
/
analyzer.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) Rich Hickey. 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 cljs.analyzer
#?(:clj (:refer-clojure :exclude [macroexpand-1 ensure])
:cljs (:refer-clojure :exclude [macroexpand-1 ns-interns ensure js-reserved]))
#?(:cljs (:require-macros
[cljs.analyzer.macros
:refer [no-warn wrapping-errors with-warning-handlers
disallowing-recur allowing-redef disallowing-ns*]]
[cljs.env.macros :refer [ensure]]))
#?(:clj (:require [cljs.util :as util :refer [ns->relpath topo-sort]]
[clojure.java.io :as io]
[clojure.string :as string]
[clojure.set :as set]
[cljs.env :as env :refer [ensure]]
[cljs.js-deps :as deps]
[cljs.tagged-literals :as tags]
[clojure.tools.reader :as reader]
[clojure.tools.reader.reader-types :as readers]
[clojure.edn :as edn]
[cljs.externs :as externs])
:cljs (:require [goog.string :as gstring]
[clojure.string :as string]
[clojure.set :as set]
[cljs.env :as env]
[cljs.tagged-literals :as tags]
[cljs.tools.reader :as reader]
[cljs.tools.reader.reader-types :as readers]
[cljs.reader :as edn]))
#?(:clj (:import [java.io File Reader PushbackReader]
[java.util.regex Pattern]
[java.net URL]
[java.lang Throwable]
[clojure.lang Namespace Var LazySeq ArityException]
[cljs.tagged_literals JSValue])))
#?(:clj (set! *warn-on-reflection* true))
;; User file-local compiler flags
#?(:clj (def ^:dynamic *unchecked-if* false))
#?(:clj (def ^:dynamic *unchecked-arrays* false))
;; Compiler dynamic vars
(def ^:dynamic *cljs-ns* 'cljs.user)
(def ^:dynamic *cljs-file* nil)
(def ^:dynamic *checked-arrays* false)
(def ^:dynamic *check-alias-dupes* true)
(def ^:dynamic *cljs-static-fns* false)
(def ^:dynamic *fn-invoke-direct* false)
(def ^:dynamic *cljs-macros-path* "/cljs/core")
(def ^:dynamic *cljs-macros-is-classpath* true)
(def ^:dynamic *cljs-dep-set* (with-meta #{} {:dep-path []}))
(def ^:dynamic *analyze-deps* true)
(def ^:dynamic *load-tests* true)
(def ^:dynamic *load-macros* true)
(def ^:dynamic *reload-macros* false)
(def ^:dynamic *macro-infer* true)
(def ^:dynamic *passes* nil)
(def ^:dynamic *file-defs* nil)
(def ^:dynamic *private-var-access-nowarn* false)
(def constants-ns-sym
"The namespace of the constants table as a symbol."
'cljs.core.constants)
#?(:clj
(def transit-read-opts
(try
(require '[cognitect.transit])
(when-some [ns (find-ns 'cognitect.transit)]
(let [read-handler @(ns-resolve ns 'read-handler)
read-handler-map @(ns-resolve ns 'read-handler-map)]
{:handlers
(read-handler-map
{"cljs/js" (read-handler (fn [v] (JSValue. v)))
"cljs/regex" (read-handler (fn [v] (Pattern/compile v)))})}))
(catch Throwable t
nil))))
#?(:clj
(def transit-write-opts
(try
(require '[cognitect.transit])
(when-some [ns (find-ns 'cognitect.transit)]
(let [write-handler @(ns-resolve ns 'write-handler)
write-handler-map @(ns-resolve ns 'write-handler-map)]
{:handlers
(write-handler-map
{JSValue
(write-handler
(fn [_] "cljs/js")
(fn [js] (.val ^JSValue js)))
Pattern
(write-handler
(fn [_] "cljs/regex")
(fn [pat] (.pattern ^Pattern pat)))})}))
(catch Throwable t
nil))))
#?(:clj
(def transit
(delay
(try
(require '[cognitect.transit])
(when-some [ns (find-ns 'cognitect.transit)]
{:writer @(ns-resolve ns 'writer)
:reader @(ns-resolve ns 'reader)
:write @(ns-resolve ns 'write)
:read @(ns-resolve ns 'read)})
(catch Throwable t
nil)))))
;; log compiler activities
(def ^:dynamic *verbose* false)
(def -cljs-macros-loaded (atom false))
(def ^:dynamic *cljs-warnings*
{:preamble-missing true
:unprovided true
:undeclared-var true
:private-var-access true
:undeclared-ns true
:undeclared-ns-form true
:redef true
:redef-in-file true
:dynamic true
:fn-var true
:fn-arity true
:fn-deprecated true
:declared-arglists-mismatch true
:protocol-deprecated true
:undeclared-protocol-symbol true
:invalid-protocol-symbol true
:multiple-variadic-overloads true
:variadic-max-arity true
:overload-arity true
:extending-base-js-type true
:invoke-ctor true
:invalid-arithmetic true
:invalid-array-access true
:protocol-invalid-method true
:protocol-duped-method true
:protocol-multiple-impls true
:protocol-with-variadic-method true
:protocol-with-overwriting-method true
:protocol-impl-with-variadic-method true
:protocol-impl-recur-with-target true
:single-segment-namespace true
:munged-namespace true
:ns-var-clash true
:non-dynamic-earmuffed-var true
:extend-type-invalid-method-shape true
:unsupported-js-module-type true
:unsupported-preprocess-value true
:js-shadowed-by-local true
:infer-warning false})
(defn unchecked-arrays? []
*unchecked-arrays*)
(defn checked-arrays
"Returns false-y, :warn, or :error based on configuration and the
current value of *unchecked-arrays*."
[]
(when (and (not (-> @env/*compiler* :options :advanced))
(not *unchecked-arrays*))
*checked-arrays*))
(def js-reserved
#{"arguments" "abstract" "await" "boolean" "break" "byte" "case"
"catch" "char" "class" "const" "continue"
"debugger" "default" "delete" "do" "double"
"else" "enum" "export" "extends" "final"
"finally" "float" "for" "function" "goto" "if"
"implements" "import" "in" "instanceof" "int"
"interface" "let" "long" "native" "new"
"package" "private" "protected" "public"
"return" "short" "static" "super" "switch"
"synchronized" "this" "throw" "throws"
"transient" "try" "typeof" "var" "void"
"volatile" "while" "with" "yield" "methods"
"null" "constructor"})
(def es5-allowed
#{"default"})
#?(:clj (def SENTINEL (Object.))
:cljs (def SENTINEL (js-obj)))
(defn gets
([m k0 k1]
(let [m (get m k0 SENTINEL)]
(when-not (identical? m SENTINEL)
(get m k1))))
([m k0 k1 k2]
(let [m (get m k0 SENTINEL)]
(when-not (identical? m SENTINEL)
(let [m (get m k1 SENTINEL)]
(when-not (identical? m SENTINEL)
(get m k2))))))
([m k0 k1 k2 k3]
(let [m (get m k0 SENTINEL)]
(when-not (identical? m SENTINEL)
(let [m (get m k1 SENTINEL)]
(when-not (identical? m SENTINEL)
(let [m (get m k2 SENTINEL)]
(when-not (identical? m SENTINEL)
(get m k3)))))))))
#?(:cljs
(def CLJ_NIL_SYM 'clj-nil))
#?(:cljs
(def NUMBER_SYM 'number))
#?(:cljs
(def STRING_SYM 'string))
(def BOOLEAN_SYM 'boolean)
#?(:cljs
(def JS_STAR_SYM 'js*))
#?(:cljs
(def DOT_SYM '.))
#?(:cljs
(def NEW_SYM 'new))
#?(:cljs
(def CLJS_CORE_SYM 'cljs.core))
#?(:cljs
(def CLJS_CORE_MACROS_SYM 'cljs.core$macros))
(def IGNORE_SYM 'ignore)
(def ANY_SYM 'any)
#?(:cljs
(defn ^boolean cljs-seq? [x]
(implements? ISeq x)))
#?(:cljs
(defn ^boolean cljs-map? [x]
(implements? IMap x)))
#?(:cljs
(defn ^boolean cljs-vector? [x]
(implements? IVector x)))
#?(:cljs
(defn ^boolean cljs-set? [x]
(implements? ISet x)))
#?(:cljs
(defn munge-path [ss]
(munge (str ss))))
#?(:cljs
(defn ns->relpath
"Given a namespace as a symbol return the relative path. May optionally
provide the file extension, defaults to :cljs."
([ns] (ns->relpath ns :cljs))
([ns ext]
(str (string/replace (munge-path ns) \. \/) "." (name ext)))))
#?(:cljs
(defn topo-sort
([x get-deps]
(topo-sort x 0 (atom (sorted-map)) (memoize get-deps)))
([x depth state memo-get-deps]
(let [deps (memo-get-deps x)]
(swap! state update-in [depth] (fnil into #{}) deps)
(doseq [dep deps]
(topo-sort dep (inc depth) state memo-get-deps))
(doseq [[<depth _] (subseq @state < depth)]
(swap! state update-in [<depth] set/difference deps))
(when (= depth 0)
(distinct (apply concat (vals @state))))))))
(declare message namespaces)
(defn ast?
#?(:cljs {:tag boolean})
[x]
(and (map? x) (contains? x :op)))
(defmulti error-message (fn [warning-type & _] warning-type))
(defmethod error-message :preamble-missing
[warning-type info]
(str "Preamble resource file not found: " (string/join " " (:missing info))))
(defmethod error-message :unprovided
[warning-type info]
(str "Required namespace not provided for " (string/join " " (:unprovided info))))
(defmethod error-message :undeclared-var
[warning-type info]
(str (if (:macro-present? info)
"Can't take value of macro "
"Use of undeclared Var ")
(:prefix info) "/" (:suffix info)))
(defmethod error-message :private-var-access
[warning-type info]
(str "var: " (:sym info) " is not public"))
(defmethod error-message :undeclared-ns
[warning-type {:keys [ns-sym js-provide] :as info}]
(str "No such namespace: " ns-sym
", could not locate " (ns->relpath ns-sym :cljs)
", " (ns->relpath ns-sym :cljc)
", or JavaScript source providing \"" js-provide "\""
(when (string/includes? (ns->relpath ns-sym) "_")
" (Please check that namespaces with dashes use underscores in the ClojureScript file name)")))
(defmethod error-message :undeclared-macros-ns
[warning-type {:keys [ns-sym js-provide] :as info}]
(str "No such macros namespace: " ns-sym
", could not locate " (ns->relpath ns-sym :clj)
" or " (ns->relpath ns-sym :cljc)))
(defmethod error-message :dynamic
[warning-type info]
(str (:name info) " not declared ^:dynamic"))
(defmethod error-message :redef
[warning-type info]
(str (:sym info) " already refers to: " (symbol (str (:ns info)) (str (:sym info)))
" being replaced by: " (symbol (str (:ns-name info)) (str (:sym info)))))
(defmethod error-message :redef-in-file
[warning-type info]
(str (:sym info) " at line " (:line info) " is being replaced"))
(defmethod error-message :fn-var
[warning-type info]
(str (symbol (str (:ns-name info)) (str (:sym info)))
" no longer fn, references are stale"))
(defmethod error-message :fn-arity
[warning-type info]
(str "Wrong number of args (" (:argc info) ") passed to "
(or (:ctor info)
(:name info))))
(defmethod error-message :fn-deprecated
[warning-type info]
(str (-> info :fexpr :info :name) " is deprecated"))
(defmethod error-message :declared-arglists-mismatch
[warning-type info]
(str (symbol (str (:ns-name info)) (str (:sym info)))
" declared arglists " (:declared info)
" mismatch defined arglists " (:defined info)))
(defmethod error-message :undeclared-ns-form
[warning-type info]
(str "Invalid :refer, " (:type info) " " (:lib info) "/" (:sym info) " does not exist"))
(defmethod error-message :protocol-deprecated
[warning-type info]
(str "Protocol " (:protocol info) " is deprecated"))
(defmethod error-message :undeclared-protocol-symbol
[warning-type info]
(str "Can't resolve protocol symbol " (:protocol info)))
(defmethod error-message :invalid-protocol-symbol
[warning-type info]
(str "Symbol " (:protocol info) " is not a protocol"))
(defmethod error-message :protocol-invalid-method
[warning-type info]
(if (:no-such-method info)
(str "Bad method signature in protocol implementation, "
(:protocol info) " does not declare method called " (:fname info))
(str "Bad method signature in protocol implementation, "
(:protocol info) " " (:fname info) " does not declare arity " (:invalid-arity info))))
(defmethod error-message :protocol-duped-method
[warning-type info]
(str "Duplicated methods in protocol implementation " (:protocol info) " " (:fname info)))
(defmethod error-message :protocol-multiple-impls
[warning-type info]
(str "Protocol " (:protocol info) " implemented multiple times"))
(defmethod error-message :protocol-with-variadic-method
[warning-type info]
(str "Protocol " (:protocol info) " declares method "
(:name info) " with variadic signature (&)"))
(defmethod error-message :protocol-with-overwriting-method
[warning-type info]
(let [overwritten-protocol (-> info :existing :protocol)]
(str "Protocol " (:protocol info) " is overwriting "
(if overwritten-protocol "method" "function")
" " (:name info)
(when overwritten-protocol (str " of protocol " (name overwritten-protocol))))))
(defmethod error-message :protocol-impl-with-variadic-method
[warning-type info]
(str "Protocol " (:protocol info) " implements method "
(:name info) " with variadic signature (&)"))
(defmethod error-message :protocol-impl-recur-with-target
[warning-type info]
(str "Ignoring target object \"" (pr-str (:form info)) "\" passed in recur to protocol method head"))
(defmethod error-message :multiple-variadic-overloads
[warning-type info]
(str (:name info) ": Can't have more than 1 variadic overload"))
(defmethod error-message :variadic-max-arity
[warning-type info]
(str (:name info) ": Can't have fixed arity function with more params than variadic function"))
(defmethod error-message :overload-arity
[warning-type info]
(str (:name info) ": Can't have 2 overloads with same arity"))
(defmethod error-message :extending-base-js-type
[warning-type info]
(str "Extending an existing JavaScript type - use a different symbol name "
"instead of " (:current-symbol info) " e.g " (:suggested-symbol info)))
(defmethod error-message :invalid-arithmetic
[warning-type info]
(str (:js-op info) ", all arguments must be numbers, got " (:types info) " instead"))
(defmethod error-message :invalid-array-access
[warning-type {:keys [name types]}]
(case name
(cljs.core/checked-aget cljs.core/checked-aget')
(str "cljs.core/aget, arguments must be an array followed by numeric indices, got " types " instead"
(when (or (= 'object (first types))
(every? #{'string} (rest types)))
(str " (consider "
(if (== 2 (count types))
"goog.object/get"
"goog.object/getValueByKeys")
" for object access)")))
(cljs.core/checked-aset cljs.core/checked-aset')
(str "cljs.core/aset, arguments must be an array, followed by numeric indices, followed by a value, got " types " instead"
(when (or (= 'object (first types))
(every? #{'string} (butlast (rest types))))
" (consider goog.object/set for object access)"))))
(defmethod error-message :invoke-ctor
[warning-type info]
(str "Cannot invoke type constructor " (-> info :fexpr :info :name) " as function "))
(defmethod error-message :single-segment-namespace
[warning-type info]
(str (:name info) " is a single segment namespace"))
(defmethod error-message :munged-namespace
[warning-type {:keys [name] :as info}]
(let [munged (->> (string/split (clojure.core/name name) #"\.")
(map #(if (js-reserved %) (str % "$") %))
(string/join ".")
(munge))]
(str "Namespace " name " contains a reserved JavaScript keyword,"
" the corresponding Google Closure namespace will be munged to " munged)))
(defmethod error-message :ns-var-clash
[warning-type {:keys [ns var] :as info}]
(str "Namespace " ns " clashes with var " var))
(defmethod error-message :non-dynamic-earmuffed-var
[warning-type {:keys [var] :as info}]
(str var " not declared dynamic and thus is not dynamically rebindable, but its name "
"suggests otherwise. Please either indicate ^:dynamic " var " or change the name"))
(defmethod error-message :extend-type-invalid-method-shape
[warning-type {:keys [protocol method] :as info}]
(str "Bad extend-type method shape for protocol " protocol " method " method
", method arities must be grouped together"))
(defmethod error-message :unsupported-js-module-type
[warning-type {:keys [module-type file] :as info}]
(str "Unsupported JavaScript module type " module-type " for foreign library "
file "."))
(defmethod error-message :unsupported-preprocess-value
[warning-type {:keys [preprocess file]}]
(str "Unsupported preprocess value " preprocess " for foreign library "
file "."))
(defmethod error-message :js-shadowed-by-local
[warning-type {:keys [name]}]
(str name " is shadowed by a local"))
(defmethod error-message :infer-warning
[warning-type {:keys [warn-type form type property]}]
(case warn-type
:target (str "Cannot infer target type in expression " form "")
:property (str "Cannot resolve property " property
" for inferred type " type " in expression " form)
:object (str "Adding extern to Object for property " property " due to "
"ambiguous expression " form)))
(defn default-warning-handler [warning-type env extra]
(when (warning-type *cljs-warnings*)
(when-let [s (error-message warning-type extra)]
#?(:clj (binding [*out* *err*]
(println (message env (str "WARNING: " s))))
:cljs (binding [*print-fn* *print-err-fn*]
(println (message env (str "WARNING: " s))))))))
(def ^:dynamic *cljs-warning-handlers*
[default-warning-handler])
#?(:clj
(defmacro with-warning-handlers [handlers & body]
`(binding [*cljs-warning-handlers* ~handlers]
~@body)))
(defn- repeat-char [c n]
(loop [ret c n n]
(if (pos? n)
(recur (str ret c) (dec n))
ret)))
(defn- hex-format [s pad]
#?(:clj (str "_u" (format (str "%0" pad "x") (int (first s))) "_")
:cljs (let [hex (.toString (.charCodeAt s 0) 16)
len (. hex -length)
hex (if (< len pad)
(str (repeat-char "0" (- pad len)) hex)
hex)]
(str "_u" hex "_"))))
(defn gen-constant-id [value]
(let [prefix (cond
(keyword? value) "cst$kw$"
(symbol? value) "cst$sym$"
:else
(throw
#?(:clj (Exception. (str "constant type " (type value) " not supported"))
:cljs (js/Error. (str "constant type " (type value) " not supported")))))
name (if (keyword? value)
(subs (str value) 1)
(str value))
name (if (= "." name)
"_DOT_"
(-> name
(string/replace "-" "_DASH_")
(munge)
(string/replace "." "$")
(string/replace #"(?i)[^a-z0-9$_]" #(hex-format % 4))))]
(symbol (str prefix name))))
(defn- register-constant!
([val] (register-constant! nil val))
([env val]
(swap! env/*compiler*
(fn [cenv]
(cond->
(-> cenv
(update-in [::constant-table]
(fn [table]
(if (get table val)
table
(assoc table val (gen-constant-id val))))))
env (update-in [::namespaces (-> env :ns :name) ::constants]
(fn [{:keys [seen order] :or {seen #{} order []} :as constants}]
(cond-> constants
(not (contains? seen val))
(assoc
:seen (conj seen val)
:order (conj order val))))))))))
(def default-namespaces '{cljs.core {:name cljs.core}
cljs.user {:name cljs.user}})
;; this exists solely to support read-only namespace access from macros.
;; External tools should look at the authoritative ::namespaces slot in the
;; compiler-env atoms/maps they're using already; this value will yield only
;; `default-namespaces` when accessed outside the scope of a
;; compilation/analysis call
(def namespaces
#?(:clj
(reify clojure.lang.IDeref
(deref [_]
(if (some? env/*compiler*)
(::namespaces @env/*compiler*)
default-namespaces)))
:cljs
(reify IDeref
(-deref [_]
(if (some? env/*compiler*)
(::namespaces @env/*compiler*)
default-namespaces)))))
(defn get-namespace
([key]
(get-namespace env/*compiler* key))
([cenv key]
(if-some [ns (get-in @cenv [::namespaces key])]
ns
(when (= 'cljs.user key)
{:name 'cljs.user}))))
#?(:clj
(defmacro no-warn [& body]
(let [no-warnings (zipmap (keys *cljs-warnings*) (repeat false))]
`(binding [*cljs-warnings* ~no-warnings]
~@body))))
#?(:clj
(defmacro all-warn [& body]
(let [all-warnings (zipmap (keys *cljs-warnings*) (repeat true))]
`(binding [*cljs-warnings* ~all-warnings]
~@body))))
(defn get-line [x env]
(or (-> x meta :line) (:line env)))
(defn get-col [x env]
(or (-> x meta :column) (:column env)))
(defn intern-macros
"Given a Clojure namespace intern all macros into the ambient ClojureScript
analysis environment."
([ns] (intern-macros ns false))
([ns reload]
(when (or (nil? (gets @env/*compiler* ::namespaces ns :macros))
reload)
(swap! env/*compiler* assoc-in [::namespaces ns :macros]
(->> #?(:clj (ns-interns ns) :cljs (ns-interns* ns))
(filter (fn [[_ ^Var v]] (.isMacro v)))
(map (fn [[k v]]
[k (as-> (meta v) vm
(let [ns (.getName ^Namespace (:ns vm))]
(assoc vm
:ns ns
:name (symbol (str ns) (str k))
:macro true)))]))
(into {}))))))
#?(:clj
(def load-mutex (Object.)))
#?(:clj
(defn load-core []
(when (not @-cljs-macros-loaded)
(reset! -cljs-macros-loaded true)
(if *cljs-macros-is-classpath*
(locking load-mutex
(load *cljs-macros-path*))
(locking load-mutex
(load-file *cljs-macros-path*))))
(intern-macros 'cljs.core)))
#?(:clj
(defmacro with-core-macros
[path & body]
`(do
(when (not= *cljs-macros-path* ~path)
(reset! -cljs-macros-loaded false))
(binding [*cljs-macros-path* ~path]
~@body))))
#?(:clj
(defmacro with-core-macros-file
[path & body]
`(do
(when (not= *cljs-macros-path* ~path)
(reset! -cljs-macros-loaded false))
(binding [*cljs-macros-path* ~path
*cljs-macros-is-classpath* false]
~@body))))
(defn empty-env
"Construct an empty analysis environment. Required to analyze forms."
[]
(ensure
{:ns (get-namespace *cljs-ns*)
:context :statement
:locals {}
:fn-scope []
:js-globals (into {}
(map #(vector % {:op :js-var :name % :ns 'js})
'(alert window document console escape unescape
screen location navigator history location
global process require module exports)))}))
(defn- source-info->error-data
[{:keys [file line column]}]
{:clojure.error/source file
:clojure.error/line line
:clojure.error/column column})
(defn source-info
([env]
(when (:line env)
(source-info nil env)))
([name env]
(cond-> {:file (if (= (-> env :ns :name) 'cljs.core)
"cljs/core.cljs"
*cljs-file*)
:line (get-line name env)
:column (get-col name env)}
(:root-source-info env)
(merge (select-keys env [:root-source-info])))))
(defn message [env s]
(str s
(if (:line env)
(str " at line " (:line env) " " *cljs-file*)
(when *cljs-file*
(str " in file " *cljs-file*)))))
(defn warning [warning-type env extra]
(doseq [handler *cljs-warning-handlers*]
(handler warning-type env extra)))
(defn- accumulating-warning-handler [warn-acc]
(fn [warning-type env extra]
(when (warning-type *cljs-warnings*)
(swap! warn-acc conj [warning-type env extra]))))
(defn- replay-accumulated-warnings [warn-acc]
(run! #(apply warning %) @warn-acc))
(defn- error-data
([env phase]
(error-data env phase nil))
([env phase symbol]
(merge (-> (source-info env) source-info->error-data)
{:clojure.error/phase phase}
(when symbol
{:clojure.error/symbol symbol}))))
(defn- compile-syntax-error
[env msg symbol]
(ex-info nil (error-data env :compile-syntax-check symbol)
#?(:clj (RuntimeException. ^String msg) :cljs (js/Error. msg))))
(defn error
([env msg]
(error env msg nil))
([env msg cause]
(ex-info (message env msg)
(assoc (source-info env) :tag :cljs/analysis-error)
cause)))
(defn analysis-error?
#?(:cljs {:tag boolean})
[ex]
(= :cljs/analysis-error (:tag (ex-data ex))))
(defn has-error-data?
#?(:cljs {:tag boolean})
[ex]
(contains? (ex-data ex) :clojure.error/phase))
#?(:clj
(defmacro wrapping-errors [env & body]
`(try
~@body
(catch Throwable err#
(cond
(has-error-data? err#) (throw err#)
(analysis-error? err#) (throw (ex-info nil (error-data ~env :compilation) err#))
:else (throw (ex-info nil (error-data ~env :compilation) (error ~env (.getMessage err#) err#))))))))
;; namespaces implicit to the inclusion of cljs.core
(def implicit-nses '#{goog goog.object goog.string goog.array Math String})
(defn implicit-import?
#?(:cljs {:tag boolean})
[env prefix suffix]
(contains? implicit-nses prefix))
(declare get-expander)
(defn confirm-var-exist-warning [env prefix suffix]
(fn [env prefix suffix]
(warning :undeclared-var env
{:prefix prefix
:suffix suffix
:macro-present? (not (nil? (get-expander (symbol (str prefix) (str suffix)) env)))})))
(defn loaded-js-ns?
"Check if a JavaScript namespace has been loaded. JavaScript vars are
not currently checked."
#?(:cljs {:tag boolean})
[env prefix]
(when-not (gets @env/*compiler* ::namespaces prefix)
(let [ns (:ns env)]
(or (some? (get (:requires ns) prefix))
(some? (get (:imports ns) prefix))))))
(defn- internal-js-module-exists?
[js-module-index module]
;; we need to check both keys and values of the JS module index, because
;; macroexpansion will be looking for the provided name - António Monteiro
(contains?
(into #{}
(mapcat (fn [[k v]]
[k (:name v)]))
js-module-index)
(str module)))
(def js-module-exists?* (memoize internal-js-module-exists?))
(defn js-module-exists?
[module]
(js-module-exists?* (get-in @env/*compiler* [:js-module-index]) module))
(defn node-module-dep?
#?(:cljs {:tag boolean})
[module]
#?(:clj (contains?
(get-in @env/*compiler* [:node-module-index])
(str module))
:cljs (try
(and (= *target* "nodejs")
(boolean (js/require.resolve (str module))))
(catch :default _
false))))
(defn dep-has-global-exports?
[module]
(let [global-exports (get-in @env/*compiler* [:js-dependency-index (str module) :global-exports])]
(or (contains? global-exports (symbol module))
(contains? global-exports (name module)))))
(defn confirm-var-exists
([env prefix suffix]
(let [warn (confirm-var-exist-warning env prefix suffix)]
(confirm-var-exists env prefix suffix warn)))
([env prefix suffix missing-fn]
(let [sufstr (str suffix)
suffix-str (if (and #?(:clj (not= ".." sufstr)
:cljs (not (identical? ".." sufstr))) ;; leave cljs.core$macros/.. alone
#?(:clj (re-find #"\." sufstr)
:cljs ^boolean (.test #"\." sufstr)))
(first (string/split sufstr #"\."))
suffix)
suffix (symbol suffix-str)]
(when (and (not (implicit-import? env prefix suffix))
(not (loaded-js-ns? env prefix))
(not (and (= 'cljs.core prefix) (= 'unquote suffix)))
(nil? (gets @env/*compiler* ::namespaces prefix :defs suffix))
(not (js-module-exists? prefix)))
(missing-fn env prefix suffix)))))
(defn confirm-var-exists-throw []
(fn [env prefix suffix]
(confirm-var-exists env prefix suffix
(fn [env prefix suffix]
(throw (error env (str "Unable to resolve var: " suffix " in this context")))))))
(defn resolve-ns-alias
([env name]
(resolve-ns-alias env name (symbol name)))
([env name not-found]
(let [sym (symbol name)]
(get (:requires (:ns env)) sym not-found))))
(defn resolve-macro-ns-alias
([env name]
(resolve-macro-ns-alias env name (symbol name)))
([env name not-found]
(let [sym (symbol name)]
(get (:require-macros (:ns env)) sym not-found))))
(defn confirm-ns
"Given env, an analysis environment, and ns-sym, a symbol identifying a
namespace, confirm that the namespace exists. Warn if not found."
[env ns-sym]
(when (and (not= 'cljs.core ns-sym)
(nil? (get implicit-nses ns-sym))
(nil? (get (-> env :ns :requires) ns-sym))
;; something else may have loaded the namespace, i.e. load-file
(nil? (gets @env/*compiler* ::namespaces ns-sym))
;; macros may refer to namespaces never explicitly required
;; confirm that the library at least exists
#?(:clj (nil? (util/ns->source ns-sym)))
(not (js-module-exists? ns-sym)))
(warning :undeclared-ns env {:ns-sym ns-sym :js-provide ns-sym})))
(defn core-name?
"Is sym visible from core in the current compilation namespace?"
#?(:cljs {:tag boolean})
[env sym]
(and (or (some? (gets @env/*compiler* ::namespaces 'cljs.core :defs sym))
(if-some [mac (get-expander sym env)]
(let [^Namespace ns (-> mac meta :ns)]
(= (.getName ns) #?(:clj 'cljs.core :cljs 'cljs.core$macros)))
false))
(not (contains? (-> env :ns :excludes) sym))))
(defn public-name?
"Is sym public?"
#?(:cljs {:tag boolean})
[ns sym]
(let [var-ast (or (gets @env/*compiler* ::namespaces ns :defs sym)
#?(:clj (gets @env/*compiler* ::namespaces ns :macros sym)
:cljs (gets @env/*compiler* ::namespaces (symbol (str (name ns) "$macros")) :defs sym)))]
(and (some? var-ast)
(not (or (:private var-ast)
(:anonymous var-ast))))))
(defn js-tag? [x]
(and (symbol? x)
(or (= 'js x)
(= "js" (namespace x)))))
(defn normalize-js-tag [x]
;; if not 'js, assume constructor
(if-not (= 'js x)
(with-meta 'js
{:prefix (conj (->> (string/split (name x) #"\.")
(map symbol) vec)
'prototype)})
x))
(defn ->type-set
"Ensures that a type tag is a set."
[t]
(if #?(:clj (set? t)
:cljs (cljs-set? t))
t
#{t}))
(defn canonicalize-type [t]
"Ensures that a type tag is either nil, a type symbol, or a non-singleton
set of type symbols, absorbing clj-nil into seq and all types into any."
(cond
(symbol? t) t
(empty? t) nil
(== 1 (count t)) (first t)
(contains? t 'any) 'any
(contains? t 'seq) (let [res (disj t 'clj-nil)]
(if (== 1 (count res))
'seq
res))
:else t))
(defn add-types
"Produces a union of types."
([] 'any)
([t1] t1)
([t1 t2]
(if (or (nil? t1)
(nil? t2))
'any
(-> (set/union (->type-set t1) (->type-set t2))
canonicalize-type)))
([t1 t2 & ts]
(apply add-types (add-types t1 t2) ts)))
(def alias->type
'{object Object
string String
number Number
array Array
function Function
boolean Boolean
symbol Symbol})
(defn has-extern?*
([pre externs]
(let [pre (if-some [me (find
(get-in externs '[Window prototype])
(first pre))]
(if-some [tag (-> me first meta :tag)]
(into [tag 'prototype] (next pre))
pre)
pre)]
(has-extern?* pre externs externs)))
([pre externs top]
(cond
(empty? pre) true
:else
(let [x (first pre)
me (find externs x)]
(cond
(not me) false
:else
(let [[x' externs'] me
xmeta (meta x')]
(if (and (= 'Function (:tag xmeta)) (:ctor xmeta))
(or (has-extern?* (into '[prototype] (next pre)) externs' top)
(has-extern?* (next pre) externs' top))