/
repl.cljc
1363 lines (1240 loc) · 53.7 KB
/
repl.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.repl
(:refer-clojure :exclude [load load-file])
(:require [clojure.java.io :as io]
[clojure.string :as string]
[clojure.set :as set]
[clojure.data.json :as json]
[clojure.tools.reader :as reader]
[clojure.tools.reader.reader-types :as readers]
[cljs.tagged-literals :as tags]
[clojure.edn :as edn]
[cljs.util :as util]
[cljs.compiler :as comp]
[cljs.analyzer :as ana]
[cljs.analyzer.api :as ana-api]
[cljs.env :as env]
[cljs.js-deps :as deps]
[cljs.closure :as cljsc]
[cljs.source-map :as sm])
(:import [java.io File PushbackReader FileWriter PrintWriter]
[java.net URL]
[java.util Base64]
[clojure.lang IExceptionInfo]
[java.util.regex Pattern]
[com.google.common.base Throwables]))
(def ^:dynamic *cljs-verbose* false)
(def ^:dynamic *repl-opts* nil)
(def ^:dynamic *repl-env* nil)
(def known-repl-opts
"Set of all known REPL options."
#{:analyze-path :bind-err :caught :compiler-env :def-emits-var :eval :flush
:init :inits :need-prompt :print :print-no-newline :prompt :quit-prompt :read
:reader :repl-requires :repl-verbose :source-map-inline :watch :watch-fn
:wrap})
(defmacro err-out [& body]
`(binding [*out* *err*]
~@body))
;; =============================================================================
;; Copied over from clojure.main
(defn skip-if-eol
"If the next character on stream s is a newline, skips it, otherwise
leaves the stream untouched. Returns :line-start, :stream-end, or :body
to indicate the relative location of the next character on s. The stream
must either be an instance of LineNumberingPushbackReader or duplicate
its behavior of both supporting .unread and collapsing all of CR, LF, and
CRLF to a single \\newline."
[s]
(let [c (readers/read-char s)]
(case c
\newline :line-start
nil :stream-end
(do (readers/unread s c) :body))))
(defn skip-whitespace
"Skips whitespace characters on stream s. Returns :line-start, :stream-end,
or :body to indicate the relative location of the next character on s.
Interprets comma as whitespace and semicolon as comment to end of line.
Does not interpret #! as comment to end of line because only one
character of lookahead is available. The stream must either be an
instance of LineNumberingPushbackReader or duplicate its behavior of both
supporting .unread and collapsing all of CR, LF, and CRLF to a single
\\newline."
[s]
(loop [c (readers/read-char s)]
(case c
\newline :line-start
nil :stream-end
\; (do (readers/read-line s) :line-start)
(if (or (Character/isWhitespace c) (identical? c \,))
(recur (readers/read-char s))
(do (readers/unread s c) :body)))))
(defn repl-read
"Default :read hook for repl. Reads from *in* which must either be an
instance of LineNumberingPushbackReader or duplicate its behavior of both
supporting .unread and collapsing all of CR, LF, and CRLF into a single
\\newline. repl-read:
- skips whitespace, then
- returns request-prompt on start of line, or
- returns request-exit on end of stream, or
- reads an object from the input stream, then
- skips the next input character if it's end of line, then
- returns the object."
([request-prompt request-exit]
(repl-read request-prompt request-exit *repl-opts*))
([request-prompt request-exit opts]
(let [current-in *in*
bind-in? (true? (:source-map-inline opts))]
(binding [*in* (if bind-in?
((:reader opts))
*in*)]
(or ({:line-start request-prompt :stream-end request-exit}
(skip-whitespace *in*))
(let [input (reader/read {:read-cond :allow :features #{:cljs}} *in*)]
;; Transfer 1-char buffer to original *in*
(readers/unread current-in (readers/read-char *in*))
(skip-if-eol (if bind-in? current-in *in*))
input))))))
;; =============================================================================
;; CLJS Specifics
(defprotocol IReplEnvOptions
(-repl-options [repl-env] "Return default REPL options for a REPL Env"))
(defn repl-options [repl-env]
(-repl-options repl-env))
(defprotocol IJavaScriptEnv
(-setup [repl-env opts] "initialize the environment")
(-evaluate [repl-env filename line js] "evaluate a javascript string")
(-load [repl-env provides url] "load code at url into the environment")
(-tear-down [repl-env] "dispose of the environment"))
(defn setup [repl-env opts]
(-setup repl-env opts))
(defn evaluate [repl-env filename line js]
(-evaluate repl-env filename line js))
(defn load [repl-env provides url]
(-load repl-env provides url))
(defn tear-down [repl-env]
(-tear-down repl-env))
(extend-type
Object
IReplEnvOptions
(-repl-options [_] nil))
(defprotocol IParseError
(-parse-error [repl-env error build-options]
"Given the original JavaScript error return the error to actually
use."))
(defprotocol IGetError
(-get-error [repl-env name env build-options]
"Given a symbol representing a var holding an error, an analysis
environment, and the REPL/compiler options return the canonical error
representation:
{:value <string>
:stacktrace <string>}
:value should be the host environment JavaScript error message string.
:stacktrace should be the host JavaScript environment stacktrace string."))
(defprotocol IParseStacktrace
(-parse-stacktrace [repl-env stacktrace error build-options]
"Given the original JavaScript stacktrace string, the entire original error
value and current compiler build options, parse the stacktrace into the
canonical form:
[{:file <string>
:function <string>
:line <integer>
:column <integer>}*]
:file must be a URL path (without protocol) relative to :output-dir. If
no source file can be supplied (such as REPL defs), :file may be a custom
identifier string surrounded by angle brackets, i.e. \"<cljs repl>\"."))
(defprotocol IPrintStacktrace
(-print-stacktrace [repl-env stacktrace error build-options]
"Implementing REPL evaluation environments are given the opportunity to
print the mapped stacktrace themselves. This permits further processing."))
(defn- env->opts
"Returns a hash-map containing all of the entries in [repl-env], translating
:working-dir to :output-dir."
([repl-env] (env->opts repl-env nil))
([repl-env opts]
;; some bits in cljs.closure use the options value as an ifn :-/
(-> (into {} repl-env)
(assoc :optimizations
(or (:optimizations opts) (get repl-env :optimizations :none)))
(assoc :output-dir
(or (:output-dir opts) (get repl-env :working-dir ".repl"))))))
(defn load-namespace
"Load a namespace and all of its dependencies into the evaluation environment.
The environment is responsible for ensuring that each namespace is loaded once and
only once."
([repl-env ns] (load-namespace repl-env ns nil))
([repl-env ns opts]
(let [ns (if (and (seq? ns)
(= (first ns) 'quote))
(second ns)
ns)
;; TODO: add pre-condition to source-on-disk, the
;; source must supply at least :url - David
sources (binding [ana/*analyze-deps* false]
(cljsc/add-dependencies
(merge (env->opts repl-env) opts)
{:requires [(name ns)] :type :seed}))
deps (->> sources
(remove (comp #{["goog"]} :provides))
(remove (comp #{:seed} :type))
(map #(select-keys % [:provides :url])))]
(cljsc/handle-js-modules opts sources env/*compiler*)
(if (:output-dir opts)
;; REPLs that read from :output-dir just need to add deps,
;; environment will handle actual loading - David
(let [sb (StringBuffer.)]
(doseq [source (->> sources
(remove (comp #{:seed} :type))
(map #(cljsc/source-on-disk opts %)))]
(when (:repl-verbose opts)
(println "Loading:" (:provides source)))
;; Need to get :requires and :provides from compiled source
;; not from our own compilation, this issue oddly doesn't seem to
;; affect compiled ClojureScript, should be cleaned up so we
;; don't need this step here - David
(with-open [rdr (io/reader (:url source))]
(.append sb
(cljsc/add-dep-string opts
(merge source
(deps/parse-js-ns (line-seq rdr)))))))
(when (:repl-verbose opts)
(println (.toString sb)))
(-evaluate repl-env "<cljs repl>" 1 (.toString sb)))
;; REPLs that stream must manually load each dep - David
(doseq [{:keys [url provides]} deps]
(-load repl-env provides url))))))
(defn- load-dependencies
([repl-env requires] (load-dependencies repl-env requires nil))
([repl-env requires opts]
(doseq [ns (distinct requires)]
(load-namespace repl-env ns opts))))
(defn ^File js-src->cljs-src
"Map a JavaScript output file back to the original ClojureScript source
file (.cljs or .cljc)."
[f]
(let [f (io/file f)
dir (.getParentFile f)
base-name (string/replace (.getName f) ".js" "")
cljsf (io/file dir (str base-name ".cljs"))]
(if (.exists cljsf)
cljsf
(let [cljcf (io/file dir (str base-name ".cljc"))]
(if (.exists cljcf)
cljcf)))))
(defn read-source-map
"Return the source map for the JavaScript source file."
[f]
(when-let [smf (util/file-or-resource (str f ".map"))]
(let [ns (if (= f "cljs/core.aot.js")
'cljs.core
(some-> (js-src->cljs-src f) ana/parse-ns :ns))]
(when ns
(as-> @env/*compiler* compiler-env
(let [t (util/last-modified smf)]
(if (or (and (= ns 'cljs.core)
(nil? (get-in compiler-env [::source-maps ns])))
(and (not= ns 'cljs.core)
(> t (get-in compiler-env [::source-maps ns :last-modified] 0))))
(swap! env/*compiler* assoc-in [::source-maps ns]
{:last-modified t
:source-map (sm/decode (json/read-str (slurp smf) :key-fn keyword))})
compiler-env))
(get-in compiler-env [::source-maps ns :source-map]))))))
(defn ns-info
"Given a path to a js source file return the ns info for the corresponding
ClojureScript file if it exists."
[f]
(let [f' (js-src->cljs-src f)]
(when (and f' (.exists f'))
(ana/parse-ns f'))))
(defn- mapped-line-column-call
"Given a cljs.source-map source map data structure map a generated line
and column back to the original line, column, and function called."
[source-map line column]
(let [default [line column nil]]
;; source maps are 0 indexed for lines
(if-let [columns (get source-map (dec line))]
(vec
(map #(%1 %2)
[inc inc identity]
(map
;; source maps are 0 indexed for columns
;; multiple segments may exist at column
;; the last segment seems most accurate
(last
(or
(get columns (last (filter #(<= % (dec column)) (sort (keys columns)))))
(second (first columns))))
[:line :col :name])))
default)))
(defn- mapped-frame
"Given opts and a canonicalized JavaScript stacktrace frame, return the
ClojureScript frame."
[{:keys [function file line column]} opts]
(let [no-source-file? (if-not file
true
(.startsWith file "<"))
rfile (when-not no-source-file?
(io/file (URL. (.toURL (io/file (util/output-directory opts))) file)))
[sm {:keys [ns source-file] :as ns-info}]
(when-not no-source-file?
((juxt read-source-map ns-info) rfile))
[line' column' call] (if ns-info
(mapped-line-column-call sm line column)
[line column])
name' (when (and ns-info function)
function)
file' (if no-source-file?
file
(string/replace
(.getCanonicalFile
(if ns-info
source-file
(io/file rfile)))
(str (System/getProperty "user.dir") File/separator) ""))
url (or (and ns-info (util/ns->source ns))
(and file (io/resource file)))]
(merge
{:function name'
:call call
:file (if no-source-file?
(str "NO_SOURCE_FILE"
(when file
(str " " file)))
(io/file file'))
:line line'
:column column'}
(when url
{:url url}))))
(defn mapped-stacktrace
"Given a vector representing the canonicalized JavaScript stacktrace
return the ClojureScript stacktrace. The canonical stacktrace must be
in the form:
[{:file <string>
:function <string>
:line <integer>
:column <integer>}*]
:file must be a URL path (without protocol) relative to :output-dir or a
identifier delimited by angle brackets. The returned mapped stacktrace will
also contain :url entries to the original sources if it can be determined
from the classpath."
([stacktrace] (mapped-stacktrace stacktrace nil))
([stacktrace opts]
(vec
(let [mapped-frames (map (memoize #(mapped-frame % opts)) stacktrace)]
;; take each non-nil :call and optionally merge it into :function one-level up
;; to avoid replacing with local symbols, we only replace munged name if we can munge call symbol back to it
(map #(merge-with (fn [munged-fn-name unmunged-call-name]
(if (= munged-fn-name (string/replace (cljs.compiler/munge unmunged-call-name) "." "$"))
unmunged-call-name
munged-fn-name)) %1 %2)
(map #(dissoc % :call) mapped-frames)
(concat (rest (map #(if (:call %)
(hash-map :function (:call %))
{})
mapped-frames)) [{}]))))))
(defn file-display
[file {:keys [output-dir temp-output-dir?]}]
(if temp-output-dir?
(let [canonicalize (fn [file] (.getCanonicalPath (io/file file)))]
(subs (canonicalize file) (inc (count (canonicalize output-dir)))))
file))
(defn print-mapped-stacktrace
"Given a vector representing the canonicalized JavaScript stacktrace
print the ClojureScript stacktrace. See mapped-stacktrace."
([stacktrace] (print-mapped-stacktrace stacktrace *repl-opts*))
([stacktrace opts]
(doseq [{:keys [function file line column]}
(mapped-stacktrace stacktrace opts)]
(err-out
(println "\t"
(str (when function (str function " "))
"(" (file-display file opts) (when line (str ":" line)) (when column (str ":" column)) ")"))))))
(comment
(def st (env/default-compiler-env))
(cljsc/build "samples/hello/src"
{:optimizations :none
:output-dir "samples/hello/out"
:output-to "samples/hello/out/hello.js"
:source-map true}
st)
(env/with-compiler-env st
(mapped-stacktrace
[{:file "hello/core.js"
:function "first"
:line 6
:column 0}]
{:output-dir "samples/hello/out"}))
(env/with-compiler-env st
(print-mapped-stacktrace
[{:file "hello/core.js"
:function "first"
:line 6
:column 0}]
{:output-dir "samples/hello/out"}))
;; URL example
(cljsc/build "samples/hello/src"
{:optimizations :none
:output-dir "out"
:output-to "out/hello.js"
:source-map true}
st)
(env/with-compiler-env st
(mapped-stacktrace
[{:file "cljs/core.js"
:function "first"
:line 2
:column 1}]
{:output-dir "out"}))
(env/with-compiler-env st
(print-mapped-stacktrace
[{:file "cljs/core.js"
:function "first"
:line 2
:column 1}]
{:output-dir "out"}))
)
(defn- display-error
([repl-env ret form opts]
(display-error repl-env ret form (constantly nil) opts))
([repl-env ret form f opts]
(err-out
(f)
(when-let [value (:value ret)]
(println value))
(when-let [st (:stacktrace ret)]
(if (and (true? (:source-map opts))
(satisfies? IParseStacktrace repl-env))
(let [cst (try
(-parse-stacktrace repl-env st ret opts)
(catch Throwable e
(when (:repl-verbose opts)
(println "Failed to canonicalize stacktrace")
(println (Throwables/getStackTraceAsString e)))))]
(if (vector? cst)
(if (satisfies? IPrintStacktrace repl-env)
(-print-stacktrace repl-env cst ret opts)
(print-mapped-stacktrace cst opts))
(println st)))
(println st))))))
(defn- bytes-to-base64-str
"Convert a byte array into a base-64 encoded string."
[^bytes bytes]
(.encodeToString (Base64/getEncoder) bytes))
(defn evaluate-form
"Evaluate a ClojureScript form in the JavaScript environment. Returns a
string which is the ClojureScript return value. This string may or may
not be readable by the Clojure reader."
([repl-env env filename form]
(evaluate-form repl-env env filename form identity))
([repl-env env filename form wrap]
(evaluate-form repl-env env filename form wrap *repl-opts*))
([repl-env env filename form wrap opts]
(binding [ana/*cljs-file* filename]
(let [env (merge env
{:root-source-info {:source-type :fragment
:source-form form}
:repl-env repl-env})
def-emits-var (:def-emits-var opts)
backup-comp @env/*compiler*
->ast (fn [form]
(binding [ana/*analyze-deps* false]
(ana/analyze (assoc env :def-emits-var def-emits-var)
(wrap form) nil opts)))
ast (->ast form)
ast (if-not (#{:ns :ns*} (:op ast))
ast
(let [ijs (ana/parse-ns [form])] ;; if ns form need to check for js modules - David
(cljsc/handle-js-modules opts [ijs] env/*compiler*)
(binding [ana/*check-alias-dupes* false]
(ana/no-warn (->ast form))))) ;; need new AST after we know what the modules are - David
wrap-js
;; TODO: check opts as well - David
(if (:source-map repl-env)
(binding [comp/*source-map-data*
(atom {:source-map (sorted-map)
:gen-col 0
:gen-line 0})]
(let [js (comp/emit-str ast)
t (System/currentTimeMillis)]
(str js
"\n//# sourceURL=repl-" t ".js"
"\n//# sourceMappingURL=data:application/json;base64,"
(bytes-to-base64-str
(.getBytes
(sm/encode
{(str "repl-" t ".cljs")
(:source-map @comp/*source-map-data*)}
{:lines (+ (:gen-line @comp/*source-map-data*) 3)
:file (str "repl-" t ".js")
:sources-content
[(or (:source (meta form))
;; handle strings / primitives without metadata
(with-out-str (pr form)))]})
"UTF-8")))))
(comp/emit-str ast))]
;; NOTE: means macros which expand to ns aren't supported for now
;; when eval'ing individual forms at the REPL - David
(when (#{:ns :ns*} (:op ast))
(let [ast (try
(ana/no-warn (ana/analyze env form nil opts))
(catch #?(:clj Exception :cljs js/Error) e
(reset! env/*compiler* backup-comp)
(throw e)))]
(load-dependencies repl-env
(into (vals (:requires ast))
(distinct (vals (:uses ast))))
opts)))
(when *cljs-verbose*
(err-out (println wrap-js)))
(let [ret (-evaluate repl-env filename (:line (meta form)) wrap-js)]
(case (:status ret)
:error (throw
(ex-info (:value ret)
{:type :js-eval-error
:error ret
:repl-env repl-env
:form form}))
:exception (throw
(ex-info (:value ret)
{:type :js-eval-exception
:error ret
:repl-env repl-env
:form form
:js wrap-js}))
:success (:value ret)))))))
(defn load-stream [repl-env filename res]
(let [env (ana/empty-env)]
(with-open [rdr (io/reader res)]
(doseq [form (ana/forms-seq* rdr filename)]
(let [env (assoc env :ns (ana/get-namespace ana/*cljs-ns*))]
(evaluate-form repl-env env filename form))))))
(defn load-file
([repl-env f] (load-file repl-env f *repl-opts*))
([repl-env f opts]
(if (:output-dir opts)
(let [src (cond
(util/url? f) f
(.exists (io/file f)) (io/file f)
:else (io/resource f))
compiled (binding [ana/*reload-macros* true]
(cljsc/compile src
(assoc opts
:output-file (cljsc/src-file->target-file src)
:force true
:mode :interactive)))]
;; copy over the original source file if source maps enabled
(when-let [ns (and (:source-map opts) (first (:provides compiled)))]
(spit
(io/file (io/file (util/output-directory opts))
(util/ns->relpath ns (util/ext (:source-url compiled))))
(slurp src)))
;; need to load dependencies first
(load-dependencies repl-env (:requires compiled) opts)
(-evaluate repl-env f 1 (cljsc/add-dep-string opts compiled))
(-evaluate repl-env f 1
(cljsc/src-file->goog-require src
{:wrap true :reload true :macros-ns (:macros-ns compiled)})))
(binding [ana/*cljs-ns* ana/*cljs-ns*]
(let [res (if (= File/separatorChar (first f)) f (io/resource f))]
(assert res (str "Can't find " f " in classpath"))
(load-stream repl-env f res))))))
(defn- root-resource
"Returns the root directory path for a lib"
{:tag String}
[lib]
(str \/
(.. (name lib)
(replace \- \_)
(replace \. \/))))
(defn- root-directory
"Returns the root resource path for a lib"
[lib]
(let [d (root-resource lib)]
(subs d 0 (.lastIndexOf d "/"))))
(defn- load-path->cp-path
[path]
(let [src (if (= File/separatorChar (first path))
path
(str (root-directory ana/*cljs-ns*) \/ path))
src (.substring src 1)]
(or (io/resource (str src ".cljs"))
(io/resource (str src ".cljc")))))
(defn- wrap-fn [form]
(cond
(and (seq? form)
(#{'ns 'require 'require-macros
'use 'use-macros 'import 'refer-clojure} (first form)))
identity
('#{*1 *2 *3 *e} form) (fn [x] `(cljs.core.pr-str ~x))
:else
(fn [x]
`(try
(cljs.core.pr-str
(let [ret# ~x]
(set! *3 *2)
(set! *2 *1)
(set! *1 ret#)
ret#))
(catch :default e#
(set! *e e#)
(throw e#))))))
(defn- init-wrap-fn [form]
(cond
(and (seq? form)
(#{'ns 'require 'require-macros
'use 'use-macros 'import 'refer-clojure} (first form)))
identity
('#{*1 *2 *3 *e} form) (fn [x] `(cljs.core.pr-str ~x))
:else
(fn [x]
`(cljs.core.pr-str ~x))))
(defn eval-cljs
"Given a REPL evaluation environment, an analysis environment, and a
form, evaluate the form and return the result. The result is always the value
represented as a string."
([repl-env env form]
(eval-cljs repl-env env form *repl-opts*))
([repl-env env form opts]
(evaluate-form repl-env
(assoc env :ns (ana/get-namespace ana/*cljs-ns*))
"<cljs repl>"
form
;; the pluggability of :wrap is needed for older JS runtimes like Rhino
;; where catching the error will swallow the original trace
((or (:wrap opts) wrap-fn) form)
opts)))
(defn decorate-specs [specs]
(if-let [k (some #{:reload :reload-all} specs)]
(->> specs (remove #{k}) (map #(vary-meta % assoc :reload k)))
specs))
(comment
(ana/canonicalize-specs
'['foo.bar '[bar.core :as bar]])
(ana/canonicalize-specs
'['foo.bar '[bar.core :as bar] :reload])
(map meta
(decorate-specs
(ana/canonicalize-specs
'['foo.bar '[bar.core :as bar] :reload])))
)
;; Special REPL fns, these provide compatiblity with Clojure functions
;; that are not possible to reproduce given ClojureScript's compilation model
;; All functions should have the following signature
;;
;; (fn self
;; ([repl-env env form]
;; (self repl-env env form))
;; ([repl-env env form opts]
;; ..))
;;
;; repl-env - IJavaScriptEnv instance
;; env - a cljs.analyzer environment, *not* cljs.env environment
;; form - complete form entered at the repl
;; opts - REPL options, essentially augmented cljs.closure/build options
(defn- wrap-self
"Takes a self-ish fn and returns it wrapped with exception handling.
Compiler state is restored if self-ish fn fails."
[f]
(fn g
([a b c]
(g a b c nil))
([a b c d]
(let [backup-comp @env/*compiler*]
(try
(apply f [a b c d])
(catch #?(:clj Exception :cljs js/Error) e ;;Exception
(reset! env/*compiler* backup-comp)
(throw e)))))))
(defn- wrap-special-fns
[wfn fns]
"Wrap wfn around all (fn) values in fns hashmap."
(into {} (for [[k v] fns] [k (wfn v)])))
(def default-special-fns
(let [load-file-fn
(fn self
([repl-env env form]
(self repl-env env form nil))
([repl-env env [_ file :as form] opts]
(load-file repl-env file opts)))
in-ns-fn
(fn self
([repl-env env form]
(self repl-env env form nil))
([repl-env env [_ [quote ns-name] :as form] _]
;; guard against craziness like '5 which wreaks havoc
(when-not (and (= quote 'quote) (symbol? ns-name))
(throw (IllegalArgumentException. "Argument to in-ns must be a symbol.")))
(when-not (ana/get-namespace ns-name)
(swap! env/*compiler* assoc-in [::ana/namespaces ns-name] {:name ns-name})
(-evaluate repl-env "<cljs repl>" 1
(str "goog.provide('" (comp/munge ns-name) "');")))
(set! ana/*cljs-ns* ns-name)))
load-fn
(fn self
([repl-env env form]
(self env repl-env form nil))
([repl-env env [_ & paths :as form] opts]
(let [cp-paths (map load-path->cp-path paths)]
(run! #(load-file repl-env % opts) cp-paths))))]
(wrap-special-fns wrap-self
{'in-ns in-ns-fn
'clojure.core/in-ns in-ns-fn
'load-file load-file-fn
'clojure.core/load-file load-file-fn
'load-namespace
(fn self
([repl-env env form]
(self env repl-env form nil))
([repl-env env [_ ns :as form] opts]
(load-namespace repl-env ns opts)))
'load load-fn
'clojure.core/load load-fn})))
(defn analyze-source
"Given a source directory, analyzes all .cljs files. Used to populate
(:cljs.analyzer/namespaces compiler-env) so as to support code reflection."
([src-dir] (analyze-source src-dir nil))
([src-dir opts]
(if-let [src-dir (and (not (empty? src-dir))
(File. src-dir))]
(doseq [file (comp/cljs-files-in src-dir)]
(ana/analyze-file (str "file://" (.getAbsolutePath file)) opts)))))
(defn repl-title []
(when-not (util/synthetic-version?)
(println "ClojureScript" (util/clojurescript-version))))
(defn repl-quit-prompt []
(println "To quit, type:" :cljs/quit))
(defn repl-prompt []
(print (str ana/*cljs-ns* "=> ")))
(defn repl-caught [e repl-env opts]
(if (and (instance? IExceptionInfo e)
(#{:js-eval-error :js-eval-exception} (:type (ex-data e))))
(let [{:keys [type repl-env error form js]} (ex-data e)]
(case type
:js-eval-error
(display-error repl-env error form opts)
:js-eval-exception
(display-error repl-env error form
(if (:repl-verbose opts)
#(prn "Error evaluating:" form :as js)
(constantly nil))
opts)))
(.printStackTrace e *err*)))
(defn repl-nil? [x]
(boolean (#{"" "nil"} x)))
(defn run-inits [renv inits]
(doseq [{:keys [type] :as init} inits]
(case type
:init-forms
(doseq [form (:forms init)]
(eval-cljs renv (ana/empty-env) form))
:eval-forms
(binding [*repl-opts* (merge *repl-opts* {:def-emits-var true :wrap init-wrap-fn})]
(doseq [form (:forms init)]
(let [value (eval-cljs renv (ana/empty-env) form *repl-opts*)]
(when-not (repl-nil? value)
(println value)))))
:init-script
(let [script (:script init)]
(load-stream renv (util/get-name script) script)))))
(defn maybe-install-npm-deps [opts]
(when (:install-deps opts)
(cljsc/check-npm-deps opts)
(swap! env/*compiler* update-in [:npm-deps-installed?]
(fn [installed?]
(if-not installed?
(cljsc/maybe-install-node-deps! opts)
installed?)))))
(defn repl*
[repl-env {:keys [init inits need-prompt quit-prompt prompt flush read eval print caught reader
print-no-newline source-map-inline wrap repl-requires
compiler-env bind-err]
:or {need-prompt #(if (readers/indexing-reader? *in*)
(== (readers/get-column-number *in*) 1)
(identity true))
quit-prompt repl-title
prompt repl-prompt
flush flush
read repl-read
eval eval-cljs
print println
caught repl-caught
reader #(readers/source-logging-push-back-reader
*in*
1 "NO_SOURCE_FILE")
print-no-newline print
source-map-inline true
repl-requires '[[cljs.repl :refer-macros [source doc find-doc apropos dir pst]]
[cljs.pprint :refer [pprint] :refer-macros [pp]]]
bind-err true}
:as opts}]
(doseq [[unknown-opt suggested-opt] (util/unknown-opts (set (keys opts)) (set/union known-repl-opts cljsc/known-opts))]
(when suggested-opt
(println (str "WARNING: Unknown option '" unknown-opt "'. Did you mean '" suggested-opt "'?"))))
(let [repl-opts (-repl-options repl-env)
repl-requires (into repl-requires (:repl-requires repl-opts))
{:keys [analyze-path repl-verbose warn-on-undeclared special-fns
checked-arrays static-fns fn-invoke-direct]
:as opts
:or {warn-on-undeclared true}}
(merge
{:def-emits-var true}
(cljsc/add-implicit-options
(merge-with (fn [a b] (if (nil? b) a b))
repl-opts
opts
{:prompt prompt
:need-prompt need-prompt
:flush flush
:read read
:print print
:caught caught
:reader reader
:print-no-newline print-no-newline
:source-map-inline source-map-inline})))
done? (atom false)]
(env/with-compiler-env (or compiler-env env/*compiler* (env/default-compiler-env opts))
(when (:source-map opts)
(.start (Thread. (bound-fn [] (read-source-map "cljs/core.aot.js")))))
(binding [*repl-env* repl-env
ana/*unchecked-if* false
ana/*unchecked-arrays* false
*err* (if bind-err
(cond-> *out*
(not (instance? PrintWriter *out*)) (PrintWriter.))
*err*)
ana/*cljs-ns* ana/*cljs-ns*
*cljs-verbose* repl-verbose
ana/*cljs-warnings*
(let [warnings (opts :warnings)]
(merge
ana/*cljs-warnings*
(if (or (true? warnings)
(false? warnings))
(zipmap (keys ana/*cljs-warnings*) (repeat warnings))
warnings)
(zipmap
[:unprovided :undeclared-var
:undeclared-ns :undeclared-ns-form]
(repeat (if (false? warnings)
false
warn-on-undeclared)))
{:infer-warning false}))
ana/*checked-arrays* checked-arrays
ana/*cljs-static-fns* static-fns
ana/*fn-invoke-direct* (and static-fns fn-invoke-direct)
*repl-opts* opts]
(try
(let [env {:context :expr :locals {}}
special-fns (merge default-special-fns special-fns)
is-special-fn? (set (keys special-fns))
request-prompt (Object.)
request-exit (Object.)
opts (comp/with-core-cljs opts
(fn []
(if-let [merge-opts (:merge-opts (-setup repl-env opts))]
(merge opts merge-opts)
opts)))
init (do
(evaluate-form repl-env env "<cljs repl>"
`(~'set! ~'cljs.core/*print-namespace-maps* true)
identity opts)
(or init
#(evaluate-form repl-env env "<cljs repl>"
(with-meta
`(~'ns ~'cljs.user
(:require ~@repl-requires))
{:line 1 :column 1})
identity opts)))
read-eval-print
(fn []
(let [input (binding [*ns* (create-ns ana/*cljs-ns*)
reader/resolve-symbol ana/resolve-symbol
reader/*data-readers* tags/*cljs-data-readers*
reader/*alias-map*
(apply merge
((juxt :requires :require-macros)
(ana/get-namespace ana/*cljs-ns*)))]
(read request-prompt request-exit))]
(or ({request-exit request-exit
:cljs/quit request-exit
request-prompt request-prompt} input)
(if (and (seq? input) (is-special-fn? (first input)))
(do
((get special-fns (first input)) repl-env env input opts)
(print nil))
(let [value (eval repl-env env input opts)]
(print value))))))]
(maybe-install-npm-deps opts)
(comp/with-core-cljs opts
(fn []
(binding [*repl-opts* opts]
(try
(when analyze-path
(if (vector? analyze-path)
(run! #(analyze-source % opts) analyze-path)
(analyze-source analyze-path opts)))
(init)
(run-inits repl-env inits)
(catch Throwable e
(caught e repl-env opts)))
(when-let [src (:watch opts)]
(.start
(Thread.
((ns-resolve 'clojure.core 'binding-conveyor-fn)
(fn []
(let [log-file (io/file (util/output-directory opts) "watch.log")]
(err-out (println "Watch compilation log available at:" (str log-file)))
(try
(let [log-out (FileWriter. log-file)]
(binding [*err* log-out
*out* log-out]
(cljsc/watch src (dissoc opts :watch)
env/*compiler* done?)))
(catch Throwable e
(caught e repl-env opts)))))))))
;; let any setup async messages flush
(Thread/sleep 50)
(binding [*in* (if (true? (:source-map-inline opts))
*in*
(reader))]
(quit-prompt)
(prompt)
(flush)
(loop []
(when-not
(try
(identical? (read-eval-print) request-exit)
(catch Throwable e
(caught e repl-env opts)
nil))
(when (need-prompt)
(prompt)
(flush))
(recur))))))))
(finally
(reset! done? true)
(-tear-down repl-env)))))))