/
compiler.clj
1881 lines (1686 loc) · 69.2 KB
/
compiler.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.
(set! *warn-on-reflection* true)
(ns cljs.compiler
(:refer-clojure :exclude [munge macroexpand-1])
(:require [clojure.java.io :as io]
[clojure.string :as string])
(:import java.lang.StringBuilder))
(declare resolve-var)
(declare resolve-existing-var)
(declare warning)
(def ^:dynamic *cljs-warn-on-undeclared* false)
(declare confirm-bindings)
(declare munge)
(declare ^:dynamic *cljs-file*)
(require 'cljs.core)
(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"})
(def cljs-reserved-file-names #{"deps.cljs"})
(defonce namespaces (atom '{cljs.core {:name cljs.core}
cljs.user {:name cljs.user}}))
(defn reset-namespaces! []
(reset! namespaces
'{cljs.core {:name cljs.core}
cljs.user {:name cljs.user}}))
(def ^:dynamic *cljs-ns* 'cljs.user)
(def ^:dynamic *cljs-file* nil)
(def ^:dynamic *cljs-warn-on-redef* true)
(def ^:dynamic *cljs-warn-on-dynamic* true)
(def ^:dynamic *cljs-warn-on-fn-var* true)
(def ^:dynamic *cljs-warn-fn-arity* true)
(def ^:dynamic *unchecked-if* (atom false))
(def ^:dynamic *cljs-static-fns* false)
(def ^:dynamic *position* nil)
(defmacro ^:private debug-prn
[& args]
`(.println System/err (str ~@args)))
(defn warning [env s]
(binding [*out* *err*]
(println
(str s (when (:line env)
(str " at line " (:line env) " " *cljs-file*))))))
(defn munge [s]
(let [ss (str s)
ms (if (.contains ss "]")
(let [idx (inc (.lastIndexOf ss "]"))]
(str (subs ss 0 idx)
(clojure.lang.Compiler/munge (subs ss idx))))
(clojure.lang.Compiler/munge ss))
ms (if (js-reserved ms) (str ms "$") ms)]
(if (symbol? s)
(symbol ms)
ms)))
(defn confirm-var-exists [env prefix suffix]
(when *cljs-warn-on-undeclared*
(let [crnt-ns (-> env :ns :name)]
(when (= prefix crnt-ns)
(when-not (-> @namespaces crnt-ns :defs suffix)
(warning env
(str "WARNING: Use of undeclared Var " prefix "/" suffix)))))))
(defn resolve-ns-alias [env name]
(let [sym (symbol name)]
(get (:requires (:ns env)) sym sym)))
(defn core-name?
"Is sym visible from core in the current compilation namespace?"
[env sym]
(and (get (:defs (@namespaces 'cljs.core)) sym)
(not (contains? (-> env :ns :excludes) sym))))
(defn js-var [sym]
(let [parts (string/split (name sym) #"\.")
first (first parts)
step (fn [part] (str "['" part "']"))]
(apply str first (map step (rest parts)))))
(defn resolve-existing-var [env sym]
(if (= (namespace sym) "js")
{:name (js-var 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)]
(confirm-var-exists env full-ns (symbol (name sym)))
(merge (get-in @namespaces [full-ns :defs (symbol (name sym))])
{:name (symbol (str full-ns "." (munge (name sym))))
:name-sym (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 idx)
lb (-> env :locals prefix)]
(if lb
{:name (munge (symbol (str (:name lb) suffix)))
:name-sym (symbol (str (:name lb) suffix))}
(do
(confirm-var-exists env prefix (symbol suffix))
(merge (get-in @namespaces [prefix :defs (symbol suffix)])
{:name (munge sym)
:name-sym (symbol (str prefix) suffix)
:ns prefix}))))
(get-in @namespaces [(-> env :ns :name) :uses sym])
(let [full-ns (get-in @namespaces [(-> env :ns :name) :uses sym])]
(merge
(get-in @namespaces [full-ns :defs sym])
{:name (symbol (str full-ns "." (munge (name sym))))
:name-sym (symbol (str full-ns) (str sym))
:ns (-> env :ns :name)}))
:else
(let [full-ns (if (core-name? env sym)
'cljs.core
(-> env :ns :name))]
(confirm-var-exists env full-ns sym)
(merge (get-in @namespaces [full-ns :defs sym])
{:name (munge (symbol (str full-ns "." (munge (name sym)))))
:name-sym (symbol (str full-ns) (str sym))
:ns full-ns}))))))
(defn resolve-var [env sym]
(if (= (namespace sym) "js")
{:name (js-var sym)}
(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)]
{:name (symbol (str (resolve-ns-alias env ns) "." (munge (name sym))))})
(.contains s ".")
(let [idx (.indexOf s ".")
prefix (symbol (subs s 0 idx))
suffix (subs s idx)
lb (-> env :locals prefix)]
(if lb
{:name (munge (symbol (str (:name lb) suffix)))}
{:name (munge sym)}))
(get-in @namespaces [(-> env :ns :name) :uses sym])
(let [full-ns (get-in @namespaces [(-> env :ns :name) :uses sym])]
(merge
(get-in @namespaces [full-ns :defs sym])
{:name (symbol (str full-ns "." (munge (name sym))))}))
:else
(let [s (str (if (core-name? env sym)
'cljs.core
(-> env :ns :name))
"." (munge (name sym)))]
{:name (munge (symbol s))})))))
(defn confirm-bindings [env names]
(doseq [name names]
(let [env (merge env {:ns (@namespaces *cljs-ns*)})
ev (resolve-existing-var env name)]
(when (and *cljs-warn-on-dynamic*
ev (not (-> ev :dynamic)))
(warning env
(str "WARNING: " (:name-sym ev) " not declared ^:dynamic"))))))
(defn- comma-sep [xs]
(interpose "," xs))
(defn- escape-char [^Character c]
(let [cp (.hashCode c)]
(case cp
; Handle printable escapes before ASCII
34 "\\\""
92 "\\\\"
; Handle non-printable escapes
8 "\\b"
12 "\\f"
10 "\\n"
13 "\\r"
9 "\\t"
(if (< 31 cp 127)
c ; Print simple ASCII characters
(format "\\u%04X" cp))))) ; Any other character is Unicode
(defn- escape-string [^CharSequence s]
(let [sb (StringBuilder. (count s))]
(doseq [c s]
(.append sb (escape-char c)))
(.toString sb)))
(defn- wrap-in-double-quotes [x]
(str \" x \"))
(defmulti emit :op)
(defn emits [& xs]
(doseq [x xs]
(cond
(nil? x) nil
(map? x) (emit x)
(seq? x) (apply emits x)
(fn? x) (x)
:else (do
(let [s (print-str x)]
(when *position*
(swap! *position* (fn [[line column]]
[line (+ column (count s))])))
(print s)))))
nil)
(defn ^String emit-str [expr]
(with-out-str (emit expr)))
(defn emitln [& xs]
(apply emits xs)
;; Prints column-aligned line number comments; good test of *position*.
;(when *position*
; (let [[line column] @*position*]
; (print (apply str (concat (repeat (- 120 column) \space) ["// " (inc line)])))))
(println)
(when *position*
(swap! *position* (fn [[line column]]
[(inc line) 0])))
nil)
(defmulti emit-constant class)
(defmethod emit-constant nil [x] (emits "null"))
(defmethod emit-constant Long [x] (emits x))
(defmethod emit-constant Integer [x] (emits x)) ; reader puts Integers in metadata
(defmethod emit-constant Double [x] (emits x))
(defmethod emit-constant String [x]
(emits (wrap-in-double-quotes (escape-string x))))
(defmethod emit-constant Boolean [x] (emits (if x "true" "false")))
(defmethod emit-constant Character [x]
(emits (wrap-in-double-quotes (escape-char x))))
(defmethod emit-constant java.util.regex.Pattern [x]
(let [[_ flags pattern] (re-find #"^(?:\(\?([idmsux]*)\))?(.*)" (str x))]
(emits \/ (.replaceAll (re-matcher #"/" pattern) "\\\\/") \/ flags)))
(defmethod emit-constant clojure.lang.Keyword [x]
(emits \" "\\uFDD0" \'
(if (namespace x)
(str (namespace x) "/") "")
(name x)
\"))
(defmethod emit-constant clojure.lang.Symbol [x]
(emits \" "\\uFDD1" \'
(if (namespace x)
(str (namespace x) "/") "")
(name x)
\"))
(defn- emit-meta-constant [x & body]
(if (meta x)
(do
(emits "cljs.core.with_meta(" body ",")
(emit-constant (meta x))
(emits ")"))
(emits body)))
(defmethod emit-constant clojure.lang.PersistentList$EmptyList [x]
(emit-meta-constant x "cljs.core.List.EMPTY"))
(defmethod emit-constant clojure.lang.PersistentList [x]
(emit-meta-constant x
(concat ["cljs.core.list("]
(comma-sep (map #(fn [] (emit-constant %)) x))
[")"])))
(defmethod emit-constant clojure.lang.Cons [x]
(emit-meta-constant x
(concat ["cljs.core.list("]
(comma-sep (map #(fn [] (emit-constant %)) x))
[")"])))
(defmethod emit-constant clojure.lang.IPersistentVector [x]
(emit-meta-constant x
(concat ["cljs.core.vec(["]
(comma-sep (map #(fn [] (emit-constant %)) x))
["])"])))
(defmethod emit-constant clojure.lang.IPersistentMap [x]
(emit-meta-constant x
(concat ["cljs.core.hash_map("]
(comma-sep (map #(fn [] (emit-constant %))
(apply concat x)))
[")"])))
(defmethod emit-constant clojure.lang.PersistentHashSet [x]
(emit-meta-constant x
(concat ["cljs.core.set(["]
(comma-sep (map #(fn [] (emit-constant %)) x))
["])"])))
(defn emit-block
[context statements ret]
(when statements
(emits statements))
(emit ret))
(defmacro emit-wrap [env & body]
`(let [env# ~env]
(when (= :return (:context env#)) (emits "return "))
~@body
(when-not (= :expr (:context env#)) (emitln ";"))))
(defmethod emit :no-op
[m] (emits "void 0;"))
(defmethod emit :var
[{:keys [info env] :as arg}]
(emit-wrap env (emits (munge (:name info)))))
(defmethod emit :meta
[{:keys [expr meta env]}]
(emit-wrap env
(emits "cljs.core.with_meta(" expr "," meta ")")))
(def ^:private array-map-threshold 16)
(def ^:private obj-map-threshold 32)
(defmethod emit :map
[{:keys [env simple-keys? keys vals]}]
(emit-wrap env
(cond
(and simple-keys? (<= (count keys) obj-map-threshold))
(emits "cljs.core.ObjMap.fromObject(["
(comma-sep keys) ; keys
"],{"
(comma-sep (map (fn [k v]
(with-out-str (emit k) (print ":") (emit v)))
keys vals)) ; js obj
"})")
(<= (count keys) array-map-threshold)
(emits "cljs.core.PersistentArrayMap.fromArrays(["
(comma-sep keys)
"],["
(comma-sep vals)
"])")
:else
(emits "cljs.core.PersistentHashMap.fromArrays(["
(comma-sep keys)
"],["
(comma-sep vals)
"])"))))
(defmethod emit :vector
[{:keys [items env]}]
(emit-wrap env
(emits "cljs.core.PersistentVector.fromArray(["
(comma-sep items) "])")))
(defmethod emit :set
[{:keys [items env]}]
(emit-wrap env
(emits "cljs.core.set(["
(comma-sep items) "])")))
(defmethod emit :constant
[{:keys [form env]}]
(when-not (= :statement (:context env))
(emit-wrap env (emit-constant form))))
(defn get-tag [e]
(or (-> e :tag)
(-> e :info :tag)))
(defn infer-tag [e]
(if-let [tag (get-tag e)]
tag
(case (:op e)
:let (infer-tag (:ret e))
:if (let [then-tag (infer-tag (:then e))
else-tag (infer-tag (:else e))]
(when (= then-tag else-tag)
then-tag))
:constant (case (:form e)
true 'boolean
false 'boolean
nil)
nil)))
(defn safe-test? [e]
(let [tag (infer-tag e)]
(or (#{'boolean 'seq} tag)
(when (= (:op e) :constant)
(let [form (:form e)]
(not (or (and (string? form) (= form ""))
(and (number? form) (zero? form)))))))))
(defmethod emit :if
[{:keys [test then else env unchecked]}]
(let [context (:context env)
checked (not (or unchecked (safe-test? test)))]
(if (= :expr context)
(emits "(" (when checked "cljs.core.truth_") "(" test ")?" then ":" else ")")
(do
(if checked
(emitln "if(cljs.core.truth_(" test "))")
(emitln "if(" test ")"))
(emitln "{" then "} else")
(emitln "{" else "}")))))
(defmethod emit :throw
[{:keys [throw env]}]
(if (= :expr (:context env))
(emits "(function(){throw " throw "})()")
(emitln "throw " throw ";")))
(defn emit-comment
"Emit a nicely formatted comment string."
[doc jsdoc]
(let [docs (when doc [doc])
docs (if jsdoc (concat docs jsdoc) docs)
docs (remove nil? docs)]
(letfn [(print-comment-lines [e] (doseq [next-line (string/split-lines e)]
(emitln "* " (string/trim next-line))))]
(when (seq docs)
(emitln "/**")
(doseq [e docs]
(when e
(print-comment-lines e)))
(emitln "*/")))))
(defmethod emit :def
[{:keys [name init env doc export]}]
(if init
(do
(emit-comment doc (:jsdoc init))
(emits name)
(emits " = " init)
(when-not (= :expr (:context env)) (emitln ";"))
(when export
(emitln "goog.exportSymbol('" export "', " name ");")))
(emitln "void 0;")))
(defn emit-apply-to
[{:keys [name params env]}]
(let [arglist (gensym "arglist__")
delegate-name (str name "__delegate")]
(emitln "(function (" arglist "){")
(doseq [[i param] (map-indexed vector (butlast params))]
(emits "var " param " = cljs.core.first(")
(dotimes [_ i] (emits "cljs.core.next("))
(emits arglist ")")
(dotimes [_ i] (emits ")"))
(emitln ";"))
(if (< 1 (count params))
(do
(emits "var " (last params) " = cljs.core.rest(")
(dotimes [_ (- (count params) 2)] (emits "cljs.core.next("))
(emits arglist)
(dotimes [_ (- (count params) 2)] (emits ")"))
(emitln ");")
(emitln "return " delegate-name "(" (string/join ", " params) ");"))
(do
(emits "var " (last params) " = ")
(emits "cljs.core.seq(" arglist ");")
(emitln ";")
(emitln "return " delegate-name "(" (string/join ", " params) ");")))
(emits "})")))
(defn emit-fn-method
[{:keys [gthis name variadic params statements ret env recurs max-fixed-arity]}]
(emit-wrap env
(emitln "(function " name "(" (comma-sep params) "){")
(when gthis
(emitln "var " gthis " = this;"))
(when recurs (emitln "while(true){"))
(emit-block :return statements ret)
(when recurs
(emitln "break;")
(emitln "}"))
(emits "})")))
(defn emit-variadic-fn-method
[{:keys [gthis name variadic params statements ret env recurs max-fixed-arity] :as f}]
(emit-wrap env
(let [name (or name (gensym))
delegate-name (str name "__delegate")]
(emitln "(function() { ")
(emitln "var " delegate-name " = function (" (comma-sep params) "){")
(when recurs (emitln "while(true){"))
(emit-block :return statements ret)
(when recurs
(emitln "break;")
(emitln "}"))
(emitln "};")
(emitln "var " name " = function (" (comma-sep
(if variadic
(concat (butlast params) ['var_args])
params)) "){")
(when gthis
(emitln "var " gthis " = this;"))
(when variadic
(emitln "var " (last params) " = null;")
(emitln "if (goog.isDef(var_args)) {")
(emitln " " (last params) " = cljs.core.array_seq(Array.prototype.slice.call(arguments, " (dec (count params)) "),0);")
(emitln "} "))
(emitln "return " delegate-name ".call(" (string/join ", " (cons "this" params)) ");")
(emitln "};")
(emitln name ".cljs$lang$maxFixedArity = " max-fixed-arity ";")
(emits name ".cljs$lang$applyTo = ")
(emit-apply-to (assoc f :name name))
(emitln ";")
(emitln name ".cljs$lang$arity$variadic = " delegate-name ";")
(emitln "return " name ";")
(emitln "})()"))))
(defmethod emit :fn
[{:keys [name env methods max-fixed-arity variadic recur-frames loop-lets]}]
;;fn statements get erased, serve no purpose and can pollute scope if named
(when-not (= :statement (:context env))
(let [loop-locals (seq (concat
(mapcat :names (filter #(and % @(:flag %)) recur-frames))
(mapcat :names loop-lets)))]
(when loop-locals
(when (= :return (:context env))
(emits "return "))
(emitln "((function (" (comma-sep loop-locals) "){")
(when-not (= :return (:context env))
(emits "return ")))
(if (= 1 (count methods))
(if variadic
(emit-variadic-fn-method (assoc (first methods) :name name))
(emit-fn-method (assoc (first methods) :name name)))
(let [has-name? (and name true)
name (or name (gensym))
maxparams (apply max-key count (map :params methods))
mmap (into {}
(map (fn [method]
[(symbol (str name "__" (count (:params method))))
method])
methods))
ms (sort-by #(-> % second :params count) (seq mmap))]
(when (= :return (:context env))
(emits "return "))
(emitln "(function() {")
(emitln "var " name " = null;")
(doseq [[n meth] ms]
(emits "var " n " = ")
(if (:variadic meth)
(emit-variadic-fn-method meth)
(emit-fn-method meth))
(emitln ";"))
(emitln name " = function(" (comma-sep (if variadic
(concat (butlast maxparams) ['var_args])
maxparams)) "){")
(when variadic
(emitln "var " (last maxparams) " = var_args;"))
(emitln "switch(arguments.length){")
(doseq [[n meth] ms]
(if (:variadic meth)
(do (emitln "default:")
(emitln "return " n ".cljs$lang$arity$variadic("
(comma-sep (butlast maxparams))
(and (> (count maxparams) 1) ", ")
"cljs.core.array_seq(arguments, " max-fixed-arity "));"))
(let [pcnt (count (:params meth))]
(emitln "case " pcnt ":")
(emitln "return " n ".call(this" (if (zero? pcnt) nil
(list "," (comma-sep (take pcnt maxparams)))) ");"))))
(emitln "}")
(emitln "throw('Invalid arity: ' + arguments.length);")
(emitln "};")
(when variadic
(emitln name ".cljs$lang$maxFixedArity = " max-fixed-arity ";")
(emitln name ".cljs$lang$applyTo = " (some #(let [[n m] %] (when (:variadic m) n)) ms) ".cljs$lang$applyTo;"))
(when has-name?
(doseq [[n meth] ms]
(let [c (count (:params meth))]
(if (:variadic meth)
(emitln name ".cljs$lang$arity$variadic = " n ".cljs$lang$arity$variadic;")
(emitln name ".cljs$lang$arity$" c " = " n ";")))))
(emitln "return " name ";")
(emitln "})()")))
(when loop-locals
(emitln ";})(" (comma-sep loop-locals) "))")))))
(defmethod emit :do
[{:keys [statements ret env]}]
(let [context (:context env)]
(when (and statements (= :expr context)) (emits "(function (){"))
;(when statements (emitln "{"))
(emit-block context statements ret)
;(when statements (emits "}"))
(when (and statements (= :expr context)) (emits "})()"))))
(defmethod emit :try*
[{:keys [env try catch name finally]}]
(let [context (:context env)
subcontext (if (= :expr context) :return context)]
(if (or name finally)
(do
(when (= :expr context) (emits "(function (){"))
(emits "try{")
(let [{:keys [statements ret]} try]
(emit-block subcontext statements ret))
(emits "}")
(when name
(emits "catch (" name "){")
(when catch
(let [{:keys [statements ret]} catch]
(emit-block subcontext statements ret)))
(emits "}"))
(when finally
(let [{:keys [statements ret]} finally]
(assert (not= :constant (:op ret)) "finally block cannot contain constant")
(emits "finally {")
(emit-block subcontext statements ret)
(emits "}")))
(when (= :expr context) (emits "})()")))
(let [{:keys [statements ret]} try]
(when (and statements (= :expr context)) (emits "(function (){"))
(emit-block subcontext statements ret)
(when (and statements (= :expr context)) (emits "})()"))))))
(defmethod emit :let
[{:keys [bindings statements ret env loop]}]
(let [context (:context env)]
(when (= :expr context) (emits "(function (){"))
(doseq [{:keys [name init]} bindings]
(emitln "var " name " = " init ";"))
(when loop (emitln "while(true){"))
(emit-block (if (= :expr context) :return context) statements ret)
(when loop
(emitln "break;")
(emitln "}"))
;(emits "}")
(when (= :expr context) (emits "})()"))))
(defmethod emit :recur
[{:keys [frame exprs env]}]
(let [temps (vec (take (count exprs) (repeatedly gensym)))
names (:names frame)]
(emitln "{")
(dotimes [i (count exprs)]
(emitln "var " (temps i) " = " (exprs i) ";"))
(dotimes [i (count exprs)]
(emitln (names i) " = " (temps i) ";"))
(emitln "continue;")
(emitln "}")))
(defmethod emit :letfn
[{:keys [bindings statements ret env]}]
(let [context (:context env)]
(when (= :expr context) (emits "(function (){"))
(doseq [{:keys [name init]} bindings]
(emitln "var " name " = " init ";"))
(emit-block (if (= :expr context) :return context) statements ret)
(when (= :expr context) (emits "})()"))))
(defmethod emit :invoke
[{:keys [f args env] :as expr}]
(let [info (:info f)
fn? (and *cljs-static-fns*
(not (:dynamic info))
(:fn-var info))
opt-not? (and (= (:name-sym info) 'cljs.core/not)
(= (infer-tag (first (:args expr))) 'boolean))
ns (:ns info)
js? (= ns 'js)
goog? (when ns
(or (= ns 'goog)
(when-let [ns-str (str ns)]
(= (get (string/split ns-str #"\.") 0 nil) "goog"))))
keyword? (and (= (-> f :op) :constant)
(keyword? (-> f :form)))
[f variadic-invoke]
(if fn?
(let [arity (count args)
variadic? (:variadic info)
mps (:method-params info)
mfa (:max-fixed-arity info)]
(cond
;; if only one method, no renaming needed
(and (not variadic?)
(= (count mps) 1))
[f nil]
;; direct dispatch to variadic case
(and variadic? (> arity mfa))
[(update-in f [:info :name]
(fn [name] (symbol (str name ".cljs$lang$arity$variadic"))))
{:max-fixed-arity mfa}]
;; direct dispatch to specific arity case
:else
(let [arities (map count mps)]
(if (some #{arity} arities)
[(update-in f [:info :name]
(fn [name] (symbol (str name ".cljs$lang$arity$" arity)))) nil]
[f nil]))))
[f nil])]
(emit-wrap env
(cond
opt-not?
(emits "!(" (first args) ")")
keyword?
(emits "(new cljs.core.Keyword(" f ")).call(" (comma-sep (cons "null" args)) ")")
variadic-invoke
(let [mfa (:max-fixed-arity variadic-invoke)]
(emits f "(" (comma-sep (take mfa args))
(when-not (zero? mfa) ",")
"cljs.core.array_seq([" (comma-sep (drop mfa args)) "], 0))"))
(or fn? js? goog?)
(emits f "(" (comma-sep args) ")")
:else
(emits f ".call(" (comma-sep (cons "null" args)) ")")))))
(defmethod emit :new
[{:keys [ctor args env]}]
(emit-wrap env
(emits "(new " ctor "("
(comma-sep args)
"))")))
(defmethod emit :set!
[{:keys [target val env]}]
(emit-wrap env (emits target " = " val)))
(defmethod emit :ns
[{:keys [name requires uses requires-macros env]}]
(emitln "goog.provide('" (munge name) "');")
(when-not (= name 'cljs.core)
(emitln "goog.require('cljs.core');"))
(doseq [lib (into (vals requires) (distinct (vals uses)))]
(emitln "goog.require('" (munge lib) "');")))
(defmethod emit :deftype*
[{:keys [t fields pmasks]}]
(let [fields (map munge fields)]
(emitln "")
(emitln "/**")
(emitln "* @constructor")
(emitln "*/")
(emitln t " = (function (" (comma-sep (map str fields)) "){")
(doseq [fld fields]
(emitln "this." fld " = " fld ";"))
(doseq [[pno pmask] pmasks]
(emitln "this.cljs$lang$protocol_mask$partition" pno "$ = " pmask ";"))
(emitln "})")))
(defmethod emit :defrecord*
[{:keys [t fields pmasks]}]
(let [fields (concat (map munge fields) '[__meta __extmap])]
(emitln "")
(emitln "/**")
(emitln "* @constructor")
(doseq [fld fields]
(emitln "* @param {*} " fld))
(emitln "* @param {*=} __meta ")
(emitln "* @param {*=} __extmap")
(emitln "*/")
(emitln t " = (function (" (comma-sep (map str fields)) "){")
(doseq [fld fields]
(emitln "this." fld " = " fld ";"))
(doseq [[pno pmask] pmasks]
(emitln "this.cljs$lang$protocol_mask$partition" pno "$ = " pmask ";"))
(emitln "if(arguments.length>" (- (count fields) 2) "){")
(emitln "this.__meta = __meta;")
(emitln "this.__extmap = __extmap;")
(emitln "} else {")
(emits "this.__meta=")
(emit-constant nil)
(emitln ";")
(emits "this.__extmap=")
(emit-constant nil)
(emitln ";")
(emitln "}")
(emitln "})")))
(defmethod emit :dot
[{:keys [target field method args env]}]
(emit-wrap env
(if field
(emits target "." field)
(emits target "." method "("
(comma-sep args)
")"))))
(defmethod emit :js
[{:keys [env code segs args]}]
(emit-wrap env
(if code
(emits code)
(emits (interleave (concat segs (repeat nil))
(concat args [nil]))))))
(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))
(defn analyze-block
"returns {:statements .. :ret ..}"
[env exprs]
(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)))]
{:statements statements :ret ret}))
(defmulti parse (fn [op & rest] op))
(defmethod parse 'if
[op env [_ test then else :as form] name]
(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]}))
(defn- block-children [{:keys [statements ret]}]
(conj (vec statements) ret))
(defmethod parse 'try*
[op env [_ & body :as form] name]
(let [body (vec body)
catchenv (update-in env [:context] #(if (= :expr %) :return %))
tail (peek body)
fblock (when (and (seq? tail) (= 'finally (first tail)))
(rest tail))
finally (when fblock
(analyze-block
(assoc env :context :statement)
fblock))
body (if finally (pop body) body)
tail (peek body)
cblock (when (and (seq? tail)
(= 'catch (first tail)))
(rest tail))
name (first cblock)
locals (:locals catchenv)
mname (when name (munge name))
locals (if name
(assoc locals name {:name mname})
locals)
catch (when cblock
(analyze-block (assoc catchenv :locals locals) (rest cblock)))
body (if name (pop body) body)
try (when body
(analyze-block (if (or name finally) catchenv env) body))]
(when name (assert (not (namespace name)) "Can't qualify symbol in catch"))
{:env env :op :try* :form form
:try try
:finally finally
:name mname
:catch catch
:children (vec (mapcat block-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)
tag (-> sym meta :tag)
protocol (-> sym meta :protocol)
dynamic (-> sym meta :dynamic)
ns-name (-> env :ns :name)]
(assert (not (namespace sym)) "Can't def ns-qualified name")
(let [env (if (or (and (not= ns-name 'cljs.core)
(core-name? env sym))
(get-in @namespaces [ns-name :uses sym]))
(let [ev (resolve-existing-var (dissoc env :locals) sym)]
(when *cljs-warn-on-redef*
(warning env
(str "WARNING: " sym " already refers to: " (symbol (str (:ns ev)) (str sym))
" being replaced by: " (symbol (str ns-name) (str sym)))))
(swap! namespaces update-in [ns-name :excludes] conj sym)
(update-in env [:ns :excludes] conj sym))
env)
name (munge (:name (resolve-var (dissoc env :locals) sym)))
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))
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 @namespaces [ns-name :defs sym])]
(when (and *cljs-warn-on-fn-var*
(not (-> sym meta :declared))
(and (:fn-var v) (not fn-var?)))
(warning env
(str "WARNING: " (symbol (str ns-name) (str sym))
" no longer fn, references are stale"))))
(swap! namespaces update-in [ns-name :defs sym]
(fn [m]
(let [m (assoc (or m {}) :name name)]
(merge m
(when tag {:tag tag})
(when dynamic {:dynamic true})
(when-let [line (:line env)]
{:file *cljs-file* :line line})
(when protocol
{:protocol protocol})
(when-let [protocol-symbol (-> sym meta :protocol-symbol)]
{:protocol-symbol protocol-symbol})
(when fn-var?
{:fn-var true
:variadic (:variadic init-expr)
:max-fixed-arity (:max-fixed-arity init-expr)
:method-params (map (fn [m]
(:params m))
(:methods init-expr))})))))
(merge {:env env :op :def :form form
:name name :doc doc :init init-expr}
(when 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 meth]
(letfn [(uniqify [[p & r]]
(when p
(cons (if (some #{p} r) (gensym (str p)) p)
(uniqify r))))]
(let [params (first meth)
fields (-> params meta ::fields)
variadic (boolean (some '#{&} params))
params (uniqify (remove '#{&} params))
fixed-arity (count (if variadic (butlast params) params))
body (next meth)
gthis (and fields (gensym "this__"))
locals (reduce (fn [m fld]
(assoc m fld
{:name (symbol (str gthis "." (munge fld)))
:field true
:mutable (-> fld meta :mutable)}))
locals fields)
locals (reduce (fn [m name] (assoc m name {:name (munge name)})) locals params)
recur-frame {:names (vec (map munge params)) :flag (atom nil)}
block (binding [*recur-frames* (cons recur-frame *recur-frames*)]
(analyze-block (assoc env :context :return :locals locals) body))]
(merge {:env env :variadic variadic :params (map munge params) :max-fixed-arity fixed-arity