/
analyzer.clj
1575 lines (1434 loc) · 63.6 KB
/
analyzer.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
; 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 [clojure.java.io :as io]
[clojure.string :as string]
[clojure.set :as set]
[cljs.env :as env]
[cljs.tagged-literals :as tags]
[clojure.tools.reader :as reader]
[clojure.tools.reader.reader-types :as readers])
(:import java.lang.StringBuilder
java.io.File
[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 -cljs-macros-loaded (atom false))
(def ^:dynamic *cljs-warnings*
{:undeclared-var false
:undeclared-ns false
:undeclared-ns-form true
:redef 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})
(declare message namespaces)
(defmulti error-message (fn [warning-type & _] warning-type))
(defmethod error-message :undeclared-var
[warning-type info]
(str "Use of undeclared Var " (:prefix info) "/" (:suffix info)))
(defmethod error-message :undeclared-ns
[warning-type info]
(str "No such namespace: " (:ns-sym info)))
(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 :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 :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 "))
(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])
(defn with-warning-handlers [handlers]
(binding [*cljs-warning-handlers* handlers]))
(defmacro with-warning-handlers [handlers & body]
`(binding [*cljs-warning-handlers* ~handlers]
~@body))
(defn munge-path [ss]
(clojure.lang.Compiler/munge (str ss)))
(defn ns->relpath [s]
(str (string/replace (munge-path s) \. \/) ".cljs"))
(def ^:private constant-counter (atom 0))
(defn gen-constant-id [value]
(let [prefix (cond
(keyword? value) "constant$keyword$"
:else
(throw
(Exception. (str "constant type " (type value) " not supported"))))]
(symbol (str prefix (swap! constant-counter inc)))))
(defn- register-constant! [val]
(swap! env/*compiler* update-in [::constant-table]
(fn [table]
(if (get table val)
table
(assoc table val (gen-constant-id 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 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*))))
(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 []
(env/ensure
{:ns (get-namespace *cljs-ns*)
:context :statement
:locals {}
:js-globals (into {}
(map #(vector % {:name %})
'(alert window document console escape unescape
screen location navigator history location
global process require module exports)))}))
(defmacro ^:private debug-prn
[& args]
`(.println System/err (str ~@args)))
(defn source-info
([env]
(when-let [line (:line env)]
{:file *cljs-file*
:line (get-line name env)
:column (get-col name env)}))
([name env]
{:file *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 confirm-var-exists [env prefix suffix]
(when (:undeclared-var *cljs-warnings*)
(let [crnt-ns (-> env :ns :name)]
(when (= prefix crnt-ns)
(when-not (get-in @env/*compiler* [::namespaces crnt-ns :defs suffix])
(warning :undeclared-var env {:prefix prefix :suffix suffix}))))))
(defn resolve-ns-alias [env name]
(let [sym (symbol name)]
(get (:requires (:ns env)) sym sym)))
(defn confirm-ns [env ns-sym]
(when (and (nil? (get '#{cljs.core goog Math} ns-sym))
(nil? (get (-> env :ns :requires) ns-sym))
;; macros may refer to namespaces never explicitly required
;; confirm that the library at least exists
(nil? (io/resource (ns->relpath ns-sym)))
(:undeclared-ns *cljs-warnings*))
(warning :undeclared-ns env {:ns-sym ns-sym})))
(defn core-name?
"Is sym visible from core in the current compilation namespace?"
[env sym]
(and (get-in @env/*compiler* [::namespaces 'cljs.core :defs sym])
(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 [full-ns (if (core-name? env sym)
'cljs.core
(-> env :ns :name))]
(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 [env sym]
(if-not (-> sym meta ::no-resolve)
(resolve-var env sym confirm-var-exists)
(resolve-var env sym)))
(defn confirm-bindings [env names]
(doseq [name names]
(let [env (assoc env :ns (get-namespace *cljs-ns*))
ev (resolve-existing-var env name)]
(when (and (:dynamic *cljs-warnings*)
ev (not (-> ev :dynamic)))
(warning :dynamic env {:ev ev})))))
(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})
(def ^:dynamic *recur-frames* nil)
(def ^:dynamic *loop-lets* nil)
(defmacro disallowing-recur [& body]
`(binding [*recur-frames* (cons nil *recur-frames*)] ~@body))
;; TODO: move this logic out - David
(defn analyze-keyword
[env sym]
(register-constant! 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 [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)))
nil)))
(defmulti parse (fn [op & rest] op))
(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 (analyze env then)
else-expr (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 '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]}))
(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)]
(when (namespace sym)
(throw (error env "Can't def ns-qualified name")))
(when-let [doc (:doc args)]
(when-not (string? doc)
(throw (error env "Too many arguments to def"))))
(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)]
(when (:redef *cljs-warnings*)
(warning :redef env {:ev ev :sym sym :ns-name ns-name}))
(swap! env/*compiler* update-in [::namespaces ns-name :excludes] conj sym)
(update-in env [:ns :excludes] conj sym))
env)
name (:name (resolve-var (dissoc env :locals) sym))
var-expr (assoc (analyze (-> env (dissoc :locals)
(assoc :context :expr)
(assoc :def-var true))
sym)
:op :var)
init-expr (when (contains? args :init)
(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) name export-val))
doc (or (:doc args) (-> sym meta :doc))]
(when-let [v (get-in @env/*compiler* [::namespaces ns-name :defs sym])]
(when (and (:fn-var *cljs-warnings*)
(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 name}
sym-meta
(when doc {:doc doc})
(when dynamic {:dynamic true})
(source-info 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
:impls #{}})
(when fn-var?
{:fn-var true
;; protocol implementation context
:protocol-impl (:protocol-impl init-expr)
;; inline protocol implementation context
:protocol-inline (:protocol-inline init-expr)
:variadic (:variadic init-expr)
:max-fixed-arity (:max-fixed-arity init-expr)
:method-params (map :params (:methods init-expr))
:methods (map (fn [method]
(let [tag (infer-tag env (assoc method :op :method))]
(cond-> (select-keys method
[:max-fixed-arity :variadic])
tag (assoc :tag tag))))
(:methods init-expr))})
(when (and fn-var? tag)
{:ret-tag tag})))
(merge {:env env :op :def :form form
:name name :var var-expr :doc doc :init init-expr}
(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}))
(defmethod parse 'fn*
[op env [_ & args :as form] name]
(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 {:shadow (or (locals name)
(get-in env [:js-globals name]))}}
(when-let [tag (-> name meta :tag)]
{:ret-tag tag})))
locals (if (and locals name) (assoc locals name name-var) locals)
type (-> form meta ::type)
fields (-> form meta ::fields)
protocol-impl (-> form meta :protocol-impl)
protocol-inline (-> form meta :protocol-inline)
locals (reduce (fn [m fld]
(assoc m fld
{:name fld
:line (get-line fld env)
:column (get-col fld env)
:field true
:mutable (-> fld meta :mutable)
:unsynchronized-mutable (-> fld meta :unsynchronized-mutable)
:volatile-mutable (-> fld meta :volatile-mutable)
:tag (-> fld meta :tag)
:shadow (m fld)}))
locals fields)
menv (if (> (count meths) 1) (assoc env :context :expr) env)
menv (merge menv
{:protocol-impl protocol-impl
:protocol-inline protocol-inline})
methods (map #(analyze-fn-method menv locals % type) meths)
max-fixed-arity (apply max (map :max-fixed-arity methods))
variadic (boolean (some :variadic methods))
locals (if name
(update-in locals [name] assoc
;; TODO: can we simplify? - David
:fn-var true
:variadic variadic
:max-fixed-arity max-fixed-arity
:method-params (map :params methods)
:methods methods)
locals)
methods (if name
;; a second pass with knowledge of our function-ness/arity
;; lets us optimize self calls
(no-warn (doall (map #(analyze-fn-method menv locals % type) meths)))
methods)]
(let [variadic-methods (filter :variadic methods)
variadic-params (count (:params (first variadic-methods)))
param-counts (map (comp count :params) methods)]
(when (and (:multiple-variadic-overloads *cljs-warnings*) (< 1 (count variadic-methods)))
(warning :multiple-variadic-overloads env {:name name-var}))
(when (and (:variadic-max-arity *cljs-warnings*)
(not (or (zero? variadic-params) (= variadic-params (+ 1 max-fixed-arity)))))
(warning :variadic-max-arity env {:name name-var}))
(when (and (:overload-arity *cljs-warnings*) (not= (distinct param-counts) param-counts))
(warning :overload-arity env {:name name-var})))
{:env env :op :fn :form form :name name-var :methods methods :variadic variadic
:tag 'function
:recur-frames *recur-frames* :loop-lets *loop-lets*
:jsdoc [(when variadic "@param {...*} var_args")]
:max-fixed-arity max-fixed-arity
:protocol-impl protocol-impl
:protocol-inline protocol-inline
:children (mapv :expr methods)}))
(defmethod parse 'letfn*
[op env [_ bindings & exprs :as form] name]
(when-not (and (vector? bindings) (even? (count bindings)))
(throw (error env "bindings must be vector of even number of elements")))
(let [n->fexpr (into {} (map (juxt first second) (partition 2 bindings)))
names (keys n->fexpr)
context (:context env)
;; first pass to collect information for recursive references
[meth-env bes]
(reduce (fn [[{:keys [locals] :as env} bes] n]
(let [ret-tag (-> n meta :tag)
fexpr (no-warn (analyze env (n->fexpr n)))
be (cond->
{:name n
:fn-var true
:line (get-line n env)
:column (get-col n env)
:local true
:shadow (locals n)
:variadic (:variadic fexpr)
:max-fixed-arity (:max-fixed-arity fexpr)
:method-params (map :params (:methods fexpr))
:methods (:methods fexpr)}
ret-tag (assoc :ret-tag ret-tag))]
[(assoc-in env [:locals n] be)
(conj bes be)]))
[env []] names)
meth-env (assoc meth-env :context :expr)
;; the real pass
[meth-env bes]
(reduce (fn [[meth-env bes] {:keys [name shadow] :as be}]
(let [env (assoc-in meth-env [:locals name] shadow)
fexpr (analyze env (n->fexpr name))
be' (assoc be
:init fexpr
:variadic (:variadic fexpr)
:max-fixed-arity (:max-fixed-arity fexpr)
:method-params (map :params (:methods fexpr))
:methods (:methods fexpr))]
[(assoc-in env [:locals name] be')
(conj bes be')]))
[meth-env []] bes)
expr (analyze (assoc meth-env :context (if (= :expr context) :return context)) `(do ~@exprs))]
{:env env :op :letfn :bindings bes :expr expr :form form
:children (conj (vec (map :init bes)) expr)}))
(defmethod parse 'do
[op env [_ & exprs :as form] _]
(let [statements (disallowing-recur
(seq (map #(analyze (assoc env :context :statement) %) (butlast exprs))))
ret (if (<= (count exprs) 1)
(analyze env (first exprs))
(analyze (assoc env :context (if (= :statement (:context env)) :statement :return)) (last exprs)))]
{:env env :op :do :form form
:statements statements :ret ret
:children (conj (vec statements) ret)}))
(defn analyze-let
[encl-env [_ bindings & exprs :as form] is-loop]
(when-not (and (vector? bindings) (even? (count bindings)))
(throw (error encl-env "bindings must be vector of even number of elements")))
(let [context (:context encl-env)
[bes env]
(disallowing-recur
(loop [bes []
env (assoc encl-env :context :expr)
bindings (seq (partition 2 bindings))]
(if-let [[name init] (first bindings)]
(do
(when (or (namespace name) (.contains (str name) "."))
(throw (error encl-env (str "Invalid local name: " name))))
(let [init-expr (binding [*loop-lets* (cons {:params bes} (or *loop-lets* ()))]
(analyze env init))
be {:name name
:line (get-line name env)
:column (get-col name env)
:init init-expr
:tag (or (-> name meta :tag)
(-> init-expr :tag)
(-> init-expr :info :tag))
:local true
:shadow (-> env :locals name)
;; Give let* bindings same shape as var so
;; they get routed correctly in the compiler
:op :var
:env {:line (get-line name env)
:column (get-col name env)}
:info {:name name
:shadow (-> env :locals name)}
:binding-form? true}
be (if (= (:op init-expr) :fn)
;; TODO: can we simplify - David
(merge be
{:fn-var true
:variadic (:variadic init-expr)
:max-fixed-arity (:max-fixed-arity init-expr)
:method-params (map :params (:methods init-expr))
:methods (:methods init-expr)})
be)]
(recur (conj bes be)
(assoc-in env [:locals name] be)
(next bindings))))
[bes env])))
recur-frame (when is-loop {:params bes :flag (atom nil)})
expr
(binding [*recur-frames* (if recur-frame (cons recur-frame *recur-frames*) *recur-frames*)
*loop-lets* (cond
is-loop (or *loop-lets* ())
*loop-lets* (cons {:params bes} *loop-lets*))]
(analyze (assoc env :context (if (= :expr context) :return context)) `(do ~@exprs)))]
{:env encl-env :op (if is-loop :loop :let)
:bindings bes :expr expr :form form
:children (conj (vec (map :init bes)) expr)}))
(defmethod parse 'let*
[op encl-env form _]
(analyze-let encl-env form false))
(defmethod parse 'loop*
[op encl-env form _]
(analyze-let encl-env form true))
(defmethod parse 'recur
[op env [_ & exprs :as form] _]
(let [context (:context env)
frame (first *recur-frames*)
exprs (disallowing-recur (vec (map #(analyze (assoc env :context :expr) %) exprs)))]
(when-not frame
(throw (error env "Can't recur here")))
(when-not (= (count exprs) (count (:params frame)))
(throw (error env "recur argument count mismatch")))
(reset! (:flag frame) true)
(assoc {:env env :op :recur :form form}
:frame frame
:exprs exprs
:children exprs)))
(defmethod parse 'quote
[_ env [_ x] _]
(analyze (assoc env :quoted? true) x))
(defmethod parse 'new
[_ env [_ ctor & args :as form] _]
(when-not (symbol? ctor)
(throw (error env "First arg to new must be a symbol")))
(disallowing-recur
(let [enve (assoc env :context :expr)
ctorexpr (analyze enve ctor)
argexprs (vec (map #(analyze enve %) args))
known-num-fields (:num-fields (resolve-existing-var env ctor))
argc (count args)]
(when (and (:fn-arity *cljs-warnings*)
(not (-> ctor meta :internal-ctor))
known-num-fields (not= known-num-fields argc))
(warning :fn-arity env {:argc argc :ctor ctor}))
{:env env :op :new :form form :ctor ctorexpr :args argexprs
:children (into [ctorexpr] argexprs)
:tag (let [name (-> ctorexpr :info :name)]
(or ('{js/Object object
js/String string
js/Array array
js/Number number
js/Function function
js/Boolean boolean} name)
name))})))
(defmethod parse 'set!
[_ env [_ target val alt :as form] _]
(let [[target val] (if alt
;; (set! o -prop val)
[`(. ~target ~val) alt]
[target val])]
(disallowing-recur
(let [enve (assoc env :context :expr)
targetexpr (cond
;; TODO: proper resolve
(= target '*unchecked-if*)
(do
(reset! *unchecked-if* val)
::set-unchecked-if)
(symbol? target)
(do
(let [local (-> env :locals target)]
(when-not (or (nil? local)
(and (:field local)
(or (:mutable local)
(:unsynchronized-mutable local)
(:volatile-mutable local))))
(throw (error env "Can't set! local var or non-mutable field"))))
(analyze-symbol enve target))
:else
(when (seq? target)
(let [targetexpr (analyze-seq enve target nil)]
(when (:field targetexpr)
targetexpr))))
valexpr (analyze enve val)]
(when-not targetexpr
(throw (error env "set! target must be a field or a symbol naming a var")))
(cond
(= targetexpr ::set-unchecked-if) {:env env :op :no-op}
:else {:env env :op :set! :form form :target targetexpr :val valexpr
:children [targetexpr valexpr]})))))
(declare analyze-file)
(defn analyze-deps [lib deps]
(binding [*cljs-dep-set* (vary-meta (conj *cljs-dep-set* lib) update-in [:dep-path] conj lib)]
(assert (every? #(not (contains? *cljs-dep-set* %)) deps)
(str "Circular dependency detected " (-> *cljs-dep-set* meta :dep-path)))
(doseq [dep deps]
(when-not (contains? (::namespaces @env/*compiler*) dep)
(let [relpath (ns->relpath dep)]
(when (io/resource relpath)
(no-warn
(analyze-file relpath))))))))
(defn check-uses [uses env]
(doseq [[sym lib] uses]
(when (and (:undeclared-ns-form *cljs-warnings*)
(= (get-in @env/*compiler* [::namespaces lib :defs sym] ::not-found) ::not-found))
(warning :undeclared-ns-form env {:type :var :lib lib :sym sym}))))
(defn check-use-macros [use-macros env]
(doseq [[sym lib] use-macros]
(when (and (:undeclared-ns *cljs-warnings*)
(nil? (.findInternedVar ^clojure.lang.Namespace (find-ns lib) sym)))
(warning :undeclared-ns env {:type :macro :lib lib :sym sym}))))
(defn parse-ns-error-msg [spec msg]
(str msg "; offending spec: " (pr-str spec)))
(defn basic-validate-ns-spec [env macros? spec]
(when-not (or (symbol? spec) (sequential? spec))
(throw
(error env
(parse-ns-error-msg spec
"Only [lib.ns & options] and lib.ns specs supported in :require / :require-macros"))))
(when (sequential? spec)
(when-not (symbol? (first spec))
(throw
(error env
(parse-ns-error-msg spec
"Library name must be specified as a symbol in :require / :require-macros"))))
(when-not (odd? (count spec))
(throw
(error env
(parse-ns-error-msg spec
"Only :as alias and :refer (names) options supported in :require"))))
(when-not (every? #{:as :refer} (map first (partition 2 (next spec))))
(throw
(error env
(parse-ns-error-msg spec
"Only :as and :refer options supported in :require / :require-macros"))))
(when-not (let [fs (frequencies (next spec))]
(and (<= (fs :as 0) 1)
(<= (fs :refer 0) 1)))