/
analyzer.cljc
2255 lines (2077 loc) · 92 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
(:refer-clojure :exclude [macroexpand-1])
(:require [cljs.util :as util]
[clojure.java.io :as io]
[clojure.string :as string]
[clojure.set :as set]
[cljs.env :as env]
[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])
(:import [java.io File Reader PushbackReader]
[java.net URL]
[clojure.lang Namespace Var]
[cljs.tagged_literals JSValue]))
(set! *warn-on-reflection* true)
(def ^:dynamic *cljs-ns* 'cljs.user)
(def ^:dynamic *cljs-file* nil)
(def ^:dynamic *unchecked-if* (atom false))
(def ^:dynamic *cljs-static-fns* 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 *file-defs* 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
:undeclared-ns true
:undeclared-ns-form true
:redef true
:redef-in-file true
:dynamic true
:fn-var true
:fn-arity true
:fn-deprecated 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
:protocol-invalid-method true
:protocol-duped-method true
:protocol-multiple-impls true
:single-segment-namespace true
:munged-namespace true
:ns-var-clash true
:extend-type-invalid-method-shape true})
(def js-reserved
#{"abstract" "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"})
(declare message namespaces)
(defn ast? [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 "Use of undeclared Var " (:prefix info) "/" (:suffix info)))
(defmethod error-message :undeclared-ns
[warning-type {:keys [ns-sym js-provide] :as info}]
(str "No such namespace: " ns-sym
", could not locate " (util/ns->relpath ns-sym :cljs)
", " (util/ns->relpath ns-sym :cljc)
", or Closure namespace \"" js-provide "\""))
(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 :undeclared-ns-form
[warning-type info]
(str "Referred " (: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 :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 :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 :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"))
(defn ^:private default-warning-handler [warning-type env extra]
(when (warning-type *cljs-warnings*)
(when-let [s (error-message warning-type extra)]
(binding [*out* *err*]
(println (message env (str "WARNING: " s)))))))
(def ^:dynamic *cljs-warning-handlers*
[default-warning-handler])
(defmacro with-warning-handlers [handlers & body]
`(binding [*cljs-warning-handlers* ~handlers]
~@body))
(defn gen-constant-id [value]
(let [prefix (cond
(keyword? value) "constant$keyword$"
:else
(throw
(Exception. (str "constant type " (type value) " not supported"))))
name (-> value (str) (subs 1) (string/replace "-" "_DASH_") (munge) (string/replace "." "$"))]
(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
(reify clojure.lang.IDeref
(deref [_]
(if-not (nil? env/*compiler*)
(::namespaces @env/*compiler*)
default-namespaces))))
(defn get-namespace [key]
(get-in @env/*compiler* [::namespaces key]))
(defmacro no-warn [& body]
(let [no-warnings (zipmap (keys *cljs-warnings*) (repeat false))]
`(binding [*cljs-warnings* ~no-warnings]
~@body)))
(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? (get-in @env/*compiler* [::namespaces ns :macros]))
reload)
(swap! env/*compiler* assoc-in [::namespaces ns :macros]
(->> (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)))))]))
(into {}))))))
(defn load-core []
(when (not @-cljs-macros-loaded)
(reset! -cljs-macros-loaded true)
(if *cljs-macros-is-classpath*
(load *cljs-macros-path*)
(load-file *cljs-macros-path*)))
(intern-macros 'cljs.core))
(defmacro with-core-macros
[path & body]
`(do
(when (not= *cljs-macros-path* ~path)
(reset! -cljs-macros-loaded false))
(binding [*cljs-macros-path* ~path]
~@body)))
(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."
[]
(env/ensure
{:ns (get-namespace *cljs-ns*)
:context :statement
:locals {}
:fn-scope []
:js-globals (into {}
(map #(vector % {:name %})
'(alert window document console escape unescape
screen location navigator history location
global process require module exports)))}))
(defn source-info
([env]
(when-let [line (:line env)]
{:file (if (= (-> env :ns :name) 'cljs.core)
"cljs/core.cljs"
*cljs-file*)
:line (get-line name env)
:column (get-col name env)}))
([name env]
{:file (if (= (-> env :ns :name) 'cljs.core)
"cljs/core.cljs"
*cljs-file*)
:line (get-line name env)
:column (get-col name env)}))
(defn message [env s]
(str s (when (:line env)
(str " at line " (:line env) " " *cljs-file*))))
(defn warning [warning-type env extra]
(doseq [handler *cljs-warning-handlers*]
(handler warning-type env extra)))
(defn error
([env s] (error env s nil))
([env s cause]
(ex-info (message env s)
(assoc (source-info env) :tag :cljs/analysis-error)
cause)))
(defn analysis-error? [ex]
(= :cljs/analysis-error (:tag (ex-data ex))))
(defmacro wrapping-errors [env & body]
`(try
~@body
(catch Throwable err#
(if (analysis-error? err#)
(throw err#)
(throw (error ~env (.getMessage err#) err#))))))
(defn implicit-import? [env prefix suffix]
(contains? '#{goog goog.object goog.string goog.array Math} prefix))
(defn confirm-var-exists
([env prefix suffix]
(confirm-var-exists env prefix suffix
(fn [env prefix suffix]
(warning :undeclared-var env {:prefix prefix :suffix suffix}))))
([env prefix suffix missing-fn]
(let [sufstr (str suffix)
suffix (symbol
(if (re-find #"\." sufstr)
(first (string/split sufstr #"\."))
suffix))]
(when (and (not (implicit-import? env prefix suffix))
(not (and (not (get-in @env/*compiler* [::namespaces prefix]))
(or (get (:requires (:ns env)) prefix)
(get (:imports (:ns env)) prefix))))
(not (and (= prefix 'cljs.core) (= suffix 'unquote)))
(not (get-in @env/*compiler* [::namespaces prefix :defs suffix])))
(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]
(let [sym (symbol name)]
(get (:requires (:ns env)) sym sym)))
(defn resolve-macro-ns-alias [env name]
(let [sym (symbol name)]
(get (:require-macros (:ns env)) sym sym)))
(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 (nil? (get '#{cljs.core goog Math goog.string} ns-sym))
(nil? (get (-> env :ns :requires) ns-sym))
;; something else may have loaded the namespace, i.e. load-file
(nil? (get-in @env/*compiler* [::namespaces ns-sym]))
;; macros may refer to namespaces never explicitly required
;; confirm that the library at least exists
(nil? (util/ns->source ns-sym)))
(warning :undeclared-ns env {:ns-sym ns-sym})))
(declare get-expander)
(defn core-name?
"Is sym visible from core in the current compilation namespace?"
[env sym]
(and (or (get-in @env/*compiler* [::namespaces 'cljs.core :defs sym])
(when-let [mac (get-expander sym env)]
(let [^Namespace ns (-> mac meta :ns)]
(= (.getName ns) 'cljs.core))))
(not (contains? (-> env :ns :excludes) sym))))
(defn resolve-var
"Resolve a var. Accepts a side-effecting confirm fn for producing
warnings about unresolved vars."
([env sym] (resolve-var env sym nil))
([env sym confirm]
(if (= (namespace sym) "js")
{:name sym :ns 'js}
(let [s (str sym)
lb (-> env :locals sym)]
(cond
lb lb
(namespace sym)
(let [ns (namespace sym)
ns (if (= "clojure.core" ns) "cljs.core" ns)
full-ns (resolve-ns-alias env ns)]
(when confirm
(when (not= (-> env :ns :name) full-ns)
(confirm-ns env full-ns))
(confirm env full-ns (symbol (name sym))))
(merge (get-in @env/*compiler* [::namespaces full-ns :defs (symbol (name sym))])
{:name (symbol (str full-ns) (str (name sym)))
:ns full-ns}))
(.contains s ".")
(let [idx (.indexOf s ".")
prefix (symbol (subs s 0 idx))
suffix (subs s (inc idx))
lb (-> env :locals prefix)]
(if lb
{:name (symbol (str (:name lb)) suffix)}
(let [cur-ns (-> env :ns :name)]
(if-let [full-ns (get-in @env/*compiler* [::namespaces cur-ns :imports prefix])]
{:name (symbol (str full-ns) suffix)}
(if-let [info (get-in @env/*compiler* [::namespaces cur-ns :defs prefix])]
(merge info
{:name (symbol (str cur-ns) (str sym))
:ns cur-ns})
(merge (get-in @env/*compiler* [::namespaces prefix :defs (symbol suffix)])
{:name (if (= "" prefix) (symbol suffix) (symbol (str prefix) suffix))
:ns prefix}))))))
(get-in @env/*compiler* [::namespaces (-> env :ns :name) :uses sym])
(let [full-ns (get-in @env/*compiler* [::namespaces (-> env :ns :name) :uses sym])]
(merge
(get-in @env/*compiler* [::namespaces full-ns :defs sym])
{:name (symbol (str full-ns) (str sym))
:ns (-> env :ns :name)}))
(get-in @env/*compiler* [::namespaces (-> env :ns :name) :imports sym])
(recur env (get-in @env/*compiler* [::namespaces (-> env :ns :name) :imports sym]) confirm)
:else
(let [cur-ns (-> env :ns :name)
full-ns (cond
(get-in @env/*compiler* [::namespaces cur-ns :defs sym]) cur-ns
(core-name? env sym) 'cljs.core
:else cur-ns)]
(when confirm
(confirm env full-ns sym))
(merge (get-in @env/*compiler* [::namespaces full-ns :defs sym])
{:name (symbol (str full-ns) (str sym))
:ns full-ns})))))))
(defn resolve-existing-var
"Given env, an analysis environment, and sym, a symbol, resolve an existing var.
Emits a warning if no such var exists."
[env sym]
(if-not (-> sym meta ::no-resolve)
(resolve-var env sym confirm-var-exists)
(resolve-var env sym)))
(defn confirm-bindings
"Given env, an analysis environment env, and names, a list of symbols, confirm
that all correspond to declared dynamic vars."
[env names]
(doseq [name names]
(let [env (assoc env :ns (get-namespace *cljs-ns*))
ev (resolve-existing-var env name)]
(when (and ev (not (-> ev :dynamic)))
(warning :dynamic env {:ev ev :name (:name ev)})))))
(defn resolve-macro-var
"Given env, an analysis environment, and sym, a symbol, resolve a macro."
[env sym]
(let [ns (-> env :ns :name)
namespaces (get @env/*compiler* ::namespaces)]
(cond
(namespace sym)
(let [ns (namespace sym)
ns (if (= "clojure.core" ns) "cljs.core" ns)
full-ns (resolve-macro-ns-alias env ns)]
(get-in namespaces [full-ns :macros (symbol (name sym))]))
(get-in namespaces [ns :use-macros sym])
(let [full-ns (get-in namespaces [ns :use-macros sym])]
(get-in namespaces [full-ns :macros sym]))
:else
(let [ns (cond
(get-in namespaces [ns :macros sym]) ns
(core-name? env sym) 'cljs.core)]
(when ns
(get-in namespaces [ns :macros sym]))))))
(defn ns-dependents
"Given a namespace as a symbol and a map from namespace symbol to
namespace information return the topologically sorted list of all
dependent namespaces. The map values of the optional second argument must
be maps with a :requires set of symbols, a :requires map of symbol -> alias
(analyzer format) or a :requires vector of munged namespace strings
(closure format)."
([ns] (ns-dependents ns (get @env/*compiler* ::namespaces)))
([ns ns-map]
(letfn [(parent? [parent [child {:keys [requires] :as ns-info}]]
(when-not (= parent child)
(cond
(or (map? requires)
(set? requires)) (contains? requires parent)
(vector? requires) (some #{(munge (name parent))} requires))))]
(util/topo-sort ns
(fn [ns']
(set (map first (filter #(parent? ns' %) ns-map))))))))
(comment
(ns-dependents 'bar
'{bar {:requires #{cljs.core}}
foo {:requires #{cljs.core bar}}})
)
(declare analyze analyze-symbol analyze-seq)
(def specials '#{if def fn* do let* loop* letfn* throw try recur new set!
ns deftype* defrecord* . js* & quote case* var})
(def ^:dynamic *recur-frames* nil)
(def ^:dynamic *loop-lets* ())
(def ^:dynamic *allow-redef* false)
(defmacro disallowing-recur [& body]
`(binding [*recur-frames* (cons nil *recur-frames*)] ~@body))
(defmacro allowing-redef [& body]
`(binding [*allow-redef* true] ~@body))
;; TODO: move this logic out - David
(defn analyze-keyword
[env sym]
(register-constant! env sym)
{:op :constant :env env :form sym :tag 'cljs.core/Keyword})
(defn get-tag [e]
(or (-> e :tag)
(-> e :info :tag)
(-> e :form meta :tag)))
(defn find-matching-method [f params]
;; if local fn, need to look in :info
(let [methods (or (:methods f) (-> f :info :methods))
c (count params)]
(some
(fn [m]
(and (or (== (:max-fixed-arity m) c)
(:variadic m))
m))
methods)))
(defn type? [env t]
;; don't use resolve-existing-var to avoid warnings
(when (and t (symbol? t))
(let [var (resolve-var env t)]
(or (:type var)
(-> var :info :type)
(:protocol-symbol var)
;; need to hard code some cases because of
;; forward declaration - David
('#{cljs.core/PersistentHashMap
cljs.core/List} t)))))
(defn infer-tag
"Given env, an analysis environment, and e, an AST node, return the inferred
type of the node"
[env e]
(if-let [tag (get-tag e)]
tag
(case (:op e)
:recur 'ignore
:throw 'ignore
:let (infer-tag env (:expr e))
:loop (infer-tag env (:expr e))
:do (infer-tag env (:ret e))
:method (infer-tag env (:expr e))
:def (infer-tag env (:init e))
:invoke (let [{info :info :as f} (:f e)]
(or (and (:fn-var info) (:ret-tag info))
(infer-tag env
(assoc (find-matching-method f (:args e)) :op :method))
'any))
:if (let [{{:keys [op form]} :test} e
then-tag (infer-tag env (:then e))]
(if (and (= op :constant)
(not (#{nil false} form)))
then-tag
(let [else-tag (infer-tag env (:else e))]
(cond
(or (= then-tag else-tag)
(= else-tag 'ignore)) then-tag
(= then-tag 'ignore) else-tag
;; TODO: temporary until we move not-native -> clj - David
(and (or ('#{clj not-native} then-tag) (type? env then-tag))
(or ('#{clj not-native} else-tag) (type? env else-tag)))
'clj
:else
(if (every? '#{boolean seq} [then-tag else-tag])
'seq
(let [then-tag (if (set? then-tag) then-tag #{then-tag})
else-tag (if (set? else-tag) else-tag #{else-tag})]
(into then-tag else-tag)))))))
:constant (case (:form e)
true 'boolean
false 'boolean
'any)
:var (if (:init e)
(infer-tag env (:init e))
(infer-tag env (:info e)))
:dot 'any
:js 'any
nil)))
(defmulti parse (fn [op & rest] op))
(defmethod parse 'var
[op env [_ sym :as form] _ _]
(let [var (resolve-var env sym (confirm-var-exists-throw))
expr-env (assoc env :context :expr)]
{:env env :op :var-special :form form
:var (analyze expr-env sym)
:sym (analyze expr-env `(quote ~(symbol (name (:ns var)) (name (:name var)))))
:meta (let [ks [:ns :doc :file :line :column]
m (merge
(let [user-meta (:meta var)
uks (keys user-meta)]
(zipmap uks
(map #(list 'quote (get user-meta %)) uks)))
(assoc (zipmap ks (map #(list 'quote (get var %)) ks))
:name `(quote ~(symbol (name (:name var))))
:test `(when ~sym (.-cljs$lang$test ~sym))
:arglists (let [arglists (:arglists var)
arglists' (if (= 'quote (first arglists))
(second arglists)
arglists)]
(list 'quote
(doall (map with-meta arglists'
(:arglists-meta var)))))))]
(analyze expr-env m))}))
(defmethod parse 'if
[op env [_ test then else :as form] name _]
(when (< (count form) 3)
(throw (error env "Too few arguments to if")))
(let [test-expr (disallowing-recur (analyze (assoc env :context :expr) test))
then-expr (allowing-redef (analyze env then))
else-expr (allowing-redef (analyze env else))]
{:env env :op :if :form form
:test test-expr :then then-expr :else else-expr
:unchecked @*unchecked-if*
:children [test-expr then-expr else-expr]}))
(defmethod parse 'case*
[op env [_ sym tests thens default :as form] name _]
(assert (symbol? sym) "case* must switch on symbol")
(assert (every? vector? tests) "case* tests must be grouped in vectors")
(let [expr-env (assoc env :context :expr)
v (disallowing-recur (analyze expr-env sym))
tests (mapv #(mapv (fn [t] (analyze expr-env t)) %) tests)
thens (mapv #(analyze env %) thens)
default (analyze env default)]
(assert (every? (fn [t]
(or
(-> t :info :const)
(and (= :constant (:op t))
((some-fn number? string? char?) (:form t)))))
(apply concat tests))
"case* tests must be numbers, strings, or constants")
{:env env :op :case* :form form
:v v :tests tests :thens thens :default default
:children (vec (concat [v] tests thens (if default [default])))}))
(defmethod parse 'throw
[op env [_ throw :as form] name _]
(let [throw-expr (disallowing-recur (analyze (assoc env :context :expr) throw))]
{:env env :op :throw :form form
:throw throw-expr
:children [throw-expr]}))
(defmethod parse 'try
[op env [_ & body :as form] name _]
(let [catchenv (update-in env [:context] #(if (= :expr %) :return %))
catch? (every-pred seq? #(= (first %) 'catch))
default? (every-pred catch? #(= (second %) :default))
finally? (every-pred seq? #(= (first %) 'finally))
{:keys [body cblocks dblock fblock]}
(loop [parser {:state :start :forms body
:body [] :cblocks [] :dblock nil :fblock nil}]
(if (seq? (:forms parser))
(let [[form & forms*] (:forms parser)
parser* (assoc parser :forms forms*)]
(case (:state parser)
:start (cond
(catch? form) (recur (assoc parser :state :catches))
(finally? form) (recur (assoc parser :state :finally))
:else (recur (update-in parser* [:body] conj form)))
:catches (cond
(default? form) (recur (assoc parser* :dblock form :state :finally))
(catch? form) (recur (update-in parser* [:cblocks] conj form))
(finally? form) (recur (assoc parser :state :finally))
:else (throw (error env "Invalid try form")))
:finally (recur (assoc parser* :fblock form :state :done))
:done (throw (error env "Unexpected form after finally"))))
parser))
finally (when (seq fblock)
(analyze (assoc env :context :statement) `(do ~@(rest fblock))))
e (when (or (seq cblocks) dblock) (gensym "e"))
default (if-let [[_ _ name & cb] dblock]
`(cljs.core/let [~name ~e] ~@cb)
`(throw ~e))
cblock (if (seq cblocks)
`(cljs.core/cond
~@(mapcat
(fn [[_ type name & cb]]
(when name (assert (not (namespace name)) "Can't qualify symbol in catch"))
`[(cljs.core/instance? ~type ~e)
(cljs.core/let [~name ~e] ~@cb)])
cblocks)
:else ~default)
default)
locals (:locals catchenv)
locals (if e
(assoc locals e
{:name e
:line (get-line e env)
:column (get-col e env)})
locals)
catch (when cblock
(analyze (assoc catchenv :locals locals) cblock))
try (analyze (if (or e finally) catchenv env) `(do ~@body))]
{:env env :op :try :form form
:try try
:finally finally
:name e
:catch catch
:children [try catch finally]}))
(declare get-expander)
(defmethod parse 'def
[op env form name _]
(let [pfn (fn
([_ sym] {:sym sym})
([_ sym init] {:sym sym :init init})
([_ sym doc init] {:sym sym :doc doc :init init}))
args (apply pfn form)
sym (:sym args)
sym-meta (meta sym)
tag (-> sym meta :tag)
protocol (-> sym meta :protocol)
dynamic (-> sym meta :dynamic)
ns-name (-> env :ns :name)
locals (:locals env)
clash-ns (symbol (str ns-name "." sym))]
(when (get-in @env/*compiler* [::namespaces clash-ns])
(warning :ns-var-clash env
{:ns (symbol (str ns-name "." sym))
:var (symbol (str ns-name) (str sym))}))
(when (namespace sym)
(throw (error env "Can't def ns-qualified name")))
(when (:const (resolve-var (dissoc env :locals) sym))
(throw (error env "Can't redefine a constant")))
(when-let [doc (:doc args)]
(when-not (string? doc)
(throw (error env "Too many arguments to def"))))
(when-let [v (get-in @env/*compiler* [::namespaces ns-name :defs sym])]
(when (and (not *allow-redef*)
(not (:declared v))
(not (:declared sym-meta))
*file-defs*
(get @*file-defs* sym))
(warning :redef-in-file env {:sym sym :line (:line v)})))
(when *file-defs*
(swap! *file-defs* conj sym))
(let [env (if (or (and (not= ns-name 'cljs.core)
(core-name? env sym))
(get-in @env/*compiler* [::namespaces ns-name :uses sym]))
(let [ev (resolve-existing-var (dissoc env :locals) sym)]
(warning :redef env {:sym sym :ns (:ns ev) :ns-name ns-name})
(swap! env/*compiler* update-in [::namespaces ns-name :excludes] conj sym)
(update-in env [:ns :excludes] conj sym))
env)
var-name (:name (resolve-var (dissoc env :locals) sym))
init-expr (when (contains? args :init)
(swap! env/*compiler* assoc-in [::namespaces ns-name :defs sym]
(merge
{:name var-name}
sym-meta
(when dynamic {:dynamic true})
(source-info var-name env)))
(disallowing-recur
(analyze (assoc env :context :expr) (:init args) sym)))
fn-var? (and init-expr (= (:op init-expr) :fn))
tag (if fn-var?
(or (:ret-tag init-expr) tag)
tag)
export-as (when-let [export-val (-> sym meta :export)]
(if (= true export-val) var-name export-val))
doc (or (:doc args) (-> sym meta :doc))]
(when-let [v (get-in @env/*compiler* [::namespaces ns-name :defs sym])]
(when (and (not (-> sym meta :declared))
(and (:fn-var v) (not fn-var?)))
(warning :fn-var env {:ns-name ns-name :sym sym})))
(swap! env/*compiler* assoc-in [::namespaces ns-name :defs sym]
(merge
{:name var-name}
;; remove actual test metadata, as it includes non-valid EDN and
;; cannot be present in analysis cached to disk - David
(cond-> sym-meta
(:test sym-meta) (assoc :test true))
{:meta (-> sym-meta
(dissoc :test)
(update-in [:file]
(fn [f]
(if (= (-> env :ns :name) 'cljs.core)
"cljs/core.cljs"
f))))}
(when doc {:doc doc})
(when dynamic {:dynamic true})
(source-info var-name env)
;; the protocol a protocol fn belongs to
(when protocol
{:protocol protocol})
;; symbol for reified protocol
(when-let [protocol-symbol (-> sym meta :protocol-symbol)]
{:protocol-symbol protocol-symbol
:info (-> protocol-symbol meta :protocol-info)
:impls #{}})
(when fn-var?
(let [params (map #(vec (map :name (:params %))) (:methods init-expr))]
(merge
{:fn-var true
;; protocol implementation context
:protocol-impl (:protocol-impl init-expr)
;; inline protocol implementation context
:protocol-inline (:protocol-inline init-expr)}
(if-let [top-fn-meta (:top-fn sym-meta)]
top-fn-meta
{:variadic (:variadic init-expr)
:max-fixed-arity (:max-fixed-arity init-expr)
:method-params params
:arglists (:arglists sym-meta)
:arglists-meta (doall (map meta (:arglists sym-meta)))}))) )
(when (and fn-var? tag)
{:ret-tag tag})))
(merge
{:env env
:op :def
:form form
:name var-name
:var (assoc
(analyze
(-> env (dissoc :locals)
(assoc :context :expr)
(assoc :def-var true))
sym)
:op :var)
:doc doc
:jsdoc (:jsdoc sym-meta)
:init init-expr}
(when-let [test (:test sym-meta)]
{:test (analyze (assoc env :context :expr) test)})
(when tag
(if fn-var?
{:ret-tag tag}
{:tag tag}))
(when dynamic {:dynamic true})
(when export-as {:export export-as})
(when init-expr {:children [init-expr]})))))
(defn- analyze-fn-method [env locals form type]
(let [param-names (first form)
variadic (boolean (some '#{&} param-names))
param-names (vec (remove '#{&} param-names))
body (next form)
[locals params] (reduce (fn [[locals params] name]
(let [param {:name name
:line (get-line name env)
:column (get-col name env)
:tag (-> name meta :tag)
:shadow (when locals (locals name))
;; Give the fn params the same shape
;; as a :var, so it gets routed
;; correctly in the compiler
:op :var
:env (merge (select-keys env [:context])
{:line (get-line name env)
:column (get-col name env)})
:info {:name name
:shadow (when locals (locals name))}
:binding-form? true}]
[(assoc locals name param) (conj params param)]))
[locals []] param-names)
fixed-arity (count (if variadic (butlast params) params))
recur-frame {:params params :flag (atom nil)}
expr (binding [*recur-frames* (cons recur-frame *recur-frames*)]
(analyze (assoc env :context :return :locals locals) `(do ~@body)))]
{:env env :variadic variadic :params params :max-fixed-arity fixed-arity
:type type :form form :recurs @(:flag recur-frame) :expr expr}))
(declare analyze-wrap-meta)
(defmethod parse 'fn*
[op env [_ & args :as form] name _]
(analyze-wrap-meta
(let [[name meths] (if (symbol? (first args))
[(first args) (next args)]
[name (seq args)])
;;turn (fn [] ...) into (fn ([]...))
meths (if (vector? (first meths)) (list meths) meths)
locals (:locals env)
name-var (if name
(merge
{:name name
:info {:fn-self-name true
:fn-scope (:fn-scope env)
:ns (-> env :ns :name)
:shadow (or (locals name)
(get-in env [:js-globals name]))}}
(when-let [tag (-> name meta :tag)]
{:ret-tag tag})))
env (if name
(update-in env [:fn-scope] conj name-var)