-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathcompiler.cljc
3912 lines (3657 loc) · 167 KB
/
compiler.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) Baptiste Dupuch & Christophe Grand. 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 cljd.compiler
(:refer-clojure :exclude [macroexpand macroexpand-1 munge compile])
(:require [clojure.string :as str]
[clojure.java.io :as io]))
(def dc-void {:kind :class
:element-name "void"
:canon-qname 'void
:qname 'void})
(def dc-dynamic '{:kind :class
:qname dc.dynamic,
:canon-qname dc.dynamic
:canon-lib "dart:core"
:lib "dart:core",
:element-name "dynamic",
:type-parameters []})
(def dc-Never '{:kind :class
:qname dc.Never,
:canon-qname dc.Never
:canon-lib "dart:core"
:lib "dart:core",
:element-name "Never"})
(def dc-Object '{:kind :class
:qname dc.Object,
:canon-qname dc.Object
:canon-lib "dart:core"
:lib "dart:core",
:element-name "Object",
:type-parameters []})
(def dc-Future '{:kind :class
:element-name "Future",
:qname dc.Future
:canon-qname da.Future
:canon-lib "dart:async"
:lib "dart:core",
:type-parameters [{:element-name "T", :is-param true, :qname T :canon-qname T}],})
(def da-FutureOr '{:kind :class
:element-name "FutureOr",
:canon-lib "dart:async"
:lib "dart:async",
:type-parameters [{:element-name "T", :is-param true, :qname T :canon-qname T}],
:qname da.FutureOr
:canon-qname da.FutureOr})
(def dc-Null '{:kind :class
:qname dc.Null,
:canon-qname dc.Null
:canon-lib "dart:core"
:lib "dart:core",
:element-name "Null",
:type-parameters []})
(def dc-String '{:kind :class
:qname dc.String,
:canon-qname dc.String
:canon-lib "dart:core"
:lib "dart:core",
:element-name "String",
:type-parameters []})
(def dc-Function '{:kind :class
:qname dc.Function,
:canon-qname dc.Function
:canon-lib "dart:core"
:lib "dart:core",
:element-name "Function",
:type-parameters []})
(def dc-bool '{:kind :class
:qname dc.bool,
:canon-qname dc.bool
:canon-lib "dart:core"
:lib "dart:core",
:element-name "bool",
:type-parameters []})
(def dc-int '{:kind :class
:qname dc.int,
:canon-qname dc.int
:canon-lib "dart:core"
:lib "dart:core",
:element-name "int",
:type-parameters []})
(def dc-double '{:kind :class
:qname dc.double,
:canon-qname dc.double
:canon-lib "dart:core"
:lib "dart:core",
:element-name "double",
:type-parameters []})
(def dc-num '{:kind :class
:qname dc.num,
:canon-qname dc.num
:canon-lib "dart:core"
:lib "dart:core",
:element-name "num",
:type-parameters []})
(def pseudo-num-tower '{:kind :class
:qname pseudo.num-tower
:canon-qname pseudo.num-tower})
(def pseudo-some '{:kind :class
:qname dc.dynamic
:lib "dart:core"
:canon-qname pseudo.some})
(declare global-lib-alias)
(defn update-if
[m k f]
(if-some [v (get m k)]
(assoc m k (f v))
m))
(defn load-libs-info []
(let [dart-libs-info
(-> (str (System/getProperty "user.dir") "/.clojuredart/libs-info.edn")
java.io.File.
clojure.java.io/reader
clojure.lang.LineNumberingPushbackReader.
clojure.edn/read)
inline-exports
(fn export [{exports :exports :as v}]
(into v (map (fn [{:keys [lib shown hidden]}]
(cond
shown
(select-keys (export (dart-libs-info lib)) shown)
hidden
(reduce dissoc (export (dart-libs-info lib)) hidden)
:else (export (dart-libs-info lib))))) exports))
assoc->qnames
(fn [{name :element-name :as entity}]
(case name
"void" (assoc entity :qname (:qname dc-void) :canon-qname (:qname dc-void))
(if (:is-param entity)
(let [qname (symbol name)]
(assoc entity :qname qname :canon-qname qname))
(let [lib (:lib entity "dart:core")
canon-lib (or (:canon-lib entity) lib)
canon-qname (-> (global-lib-alias canon-lib nil) (str "." name) symbol)
qname (if (= lib canon-lib)
canon-qname
(-> (global-lib-alias lib nil) (str "." name) symbol))]
(assoc entity
:qname qname
:canon-qname canon-qname
:lib lib
:canon-lib canon-lib)))))
qualify-entity
(fn qualify-entity [entity]
(case (:kind entity)
:class (->
(assoc->qnames entity)
(update-if :type-parameters #(into [] (map qualify-entity) %))
(update-if :super qualify-entity)
(update-if :bound qualify-entity)
(update-if :interfaces #(into [] (map qualify-entity) %))
(update-if :on #(into [] (map qualify-entity) %))
(update-if :mixins #(into [] (map qualify-entity) %))
(into (comp (filter #(string? (first %)))
(map (fn [[n v]] [n (qualify-entity v)])))
entity))
:field (cond-> (update entity :type qualify-entity)
(:toplevel entity) assoc->qnames)
:function (->
(assoc->qnames entity)
(update-if :return-type qualify-entity)
(update-if :parameters #(into [] (map qualify-entity) %))
(update-if :type-parameters #(into [] (map qualify-entity) %)))
:method (-> entity
(update :return-type qualify-entity)
(update-if :parameters #(into [] (map qualify-entity) %))
(update-if :type-parameters #(into [] (map qualify-entity) %)))
:constructor (-> entity
(update-if :parameters #(into [] (map qualify-entity) %))
(update-if :type-parameters #(into [] (map qualify-entity) %))
(update :return-type qualify-entity))
(:named :positional) (update entity :type qualify-entity)
; type
(recur (-> entity
(dissoc :type)
(assoc
:kind (case (:type entity) "Function" :function :class)
:element-name (:type entity))))))]
(-> (into {}
(map (fn [[lib content]]
[lib (into {}
(map (fn [[name entity]]
[name
(cond-> entity
(string? name)
(->
(assoc
:element-name name
:lib lib
:toplevel true
:canon-lib (:lib entity))
qualify-entity))]))
(inline-exports content))]))
dart-libs-info)
(assoc-in ["dart:core" "Never"] dc-Never)
(assoc-in ["dart:core" "dynamic"] dc-dynamic)
(assoc-in ["dart:_internal" :private] true))))
(def ^:dynamic dart-libs-info)
(def ^:dynamic *hosted* false)
(def ^:dynamic *host-eval* false)
(def ^:dynamic ^String *lib-path* "lib/")
(def ^:dynamic ^String *test-path* "test/")
(def ^:dynamic *target-subdir*
"Relative path to the lib directory (*lib-dir*) where compiled dart file will be put.
Defaults to \"cljd-out/\"."
"cljd-out/")
(def ^:dynamic *source-info* {})
(defn source-info []
(let [{:keys [line column]} *source-info*]
(if line
(str " at line: " line ", column: " column ", file: " *file*)
" (no source location)")))
(defmacro ^:private else->> [& forms]
`(->> ~@(reverse forms)))
(defn- replace-all [^String s regexp f]
#?(:cljd
(.replaceAllMapped s regexp f)
:clj
(str/replace s regexp f)))
(def ns-prototype
{:imports {"dart:core" {}}
; map from aliases found in clj code to dart libs
:clj-aliases {"dart:core" "dart:core"}
:mappings
'{Type dart:core/Type,
BidirectionalIterator dart:core/BidirectionalIterator,
bool dart:core/bool,
UnimplementedError dart:core/UnimplementedError,
Match dart:core/Match,
Error dart:core/Error,
Uri dart:core/Uri,
Object dart:core/Object,
IndexError dart:core/IndexError,
MapEntry dart:core/MapEntry,
DateTime dart:core/DateTime,
StackTrace dart:core/StackTrace,
Symbol dart:core/Symbol,
String dart:core/String,
Future dart:core/Future,
StringSink dart:core/StringSink,
Expando dart:core/Expando,
BigInt dart:core/BigInt,
num dart:core/num,
Function dart:core/Function,
TypeError dart:core/TypeError,
StackOverflowError dart:core/StackOverflowError,
Comparator dart:core/Comparator,
double dart:core/double,
Iterable dart:core/Iterable,
UnsupportedError dart:core/UnsupportedError,
Iterator dart:core/Iterator,
Stopwatch dart:core/Stopwatch,
int dart:core/int,
dynamic dart:core/dynamic
Invocation dart:core/Invocation,
RuneIterator dart:core/RuneIterator,
RegExpMatch dart:core/RegExpMatch,
Deprecated dart:core/Deprecated,
StateError dart:core/StateError,
Map dart:core/Map,
pragma dart:core/pragma,
Sink dart:core/Sink,
NoSuchMethodError dart:core/NoSuchMethodError,
Set dart:core/Set,
FallThroughError dart:core/FallThroughError,
StringBuffer dart:core/StringBuffer,
RangeError dart:core/RangeError,
Comparable dart:core/Comparable,
CyclicInitializationError dart:core/CyclicInitializationError,
LateInitializationError dart:core/LateInitializationError,
FormatException dart:core/FormatException,
Null dart:core/Null,
NullThrownError dart:core/NullThrownError,
Exception dart:core/Exception,
RegExp dart:core/RegExp,
Stream dart:core/Stream,
Pattern dart:core/Pattern,
AbstractClassInstantiationError
dart:core/AbstractClassInstantiationError,
OutOfMemoryError dart:core/OutOfMemoryError,
UriData dart:core/UriData,
Runes dart:core/Runes,
IntegerDivisionByZeroException
dart:core/IntegerDivisionByZeroException,
ConcurrentModificationError dart:core/ConcurrentModificationError,
AssertionError dart:core/AssertionError,
Duration dart:core/Duration,
ArgumentError dart:core/ArgumentError,
List dart:core/List}})
(def nses (atom {:current-ns 'user
:libs {"dart:core" {:dart-alias "dc" :ns nil}
"dart:async" {:dart-alias "da" :ns nil}} ; dc can't clash with user aliases because they go through dart-global
; map from dart aliases to libs
:dart-aliases {"dc" "dart:core"
"da" "dart:async"}
:ifn-mixins {}
'user ns-prototype}))
(defn global-lib-alias
"ns may be nil, returns the alias for this lib"
[lib ns]
(or (-> @nses :libs (get lib) :dart-alias)
(let [[_ trimmed-lib] (re-matches #"(?:package:)?(.+?)(?:\.dart)?" lib)
segments (re-seq #"[a-zA-Z][a-zA-Z_0-9]*" trimmed-lib)
prefix (apply str (map first (butlast segments)))
base (cond->> (last segments) (not= prefix "") (str prefix "_"))
nses (swap! nses
(fn [nses]
(if (-> nses :libs (get lib) :dart-alias)
nses
(let [alias (some #(when-not (get (:dart-aliases nses) %) %)
(cons base (map #(str base "_" (inc %)) (range))))]
(-> nses
(assoc-in [:libs lib] {:dart-alias alias :ns ns})
(assoc-in [:dart-aliases alias] lib))))))]
(-> nses :libs (get lib) :dart-alias))))
(declare resolve-type type-str actual-member)
(defn- resolve-clj-alias
"Resolves the namespace part of a clojure symbol referencing a dart element to the dart lib
of this element."
[clj-alias]
(when clj-alias
(let [{:keys [libs current-ns dart-aliases] :as all-nses} @nses
{:keys [clj-aliases imports]} (all-nses current-ns)]
(or (get clj-aliases clj-alias)
(some-> (re-matches #"\$lib:(.*)" clj-alias) second dart-aliases)))))
(defn- resolve-dart-type
[clj-sym type-vars]
(let [{:keys [libs current-ns] :as nses} @nses
typename (name clj-sym)
typens (namespace clj-sym)]
(else->>
(when-not (.endsWith (name clj-sym) "."))
(if ('#{void dart:core/void} clj-sym)
dc-void)
(if (and (nil? typens) (contains? type-vars (symbol typename)))
{:kind :class :canon-qname clj-sym :qname clj-sym :element-name typename :is-param true})
(when-some [lib (resolve-clj-alias typens)]
(or (-> dart-libs-info (get lib) (get typename))
(let [dart-alias (:dart-alias (libs lib))
qname (symbol (str dart-alias "." typename))]
(case clj-sym
cljd.core/IFn$iface
'{:kind :class
:qname lcoc_core.IFn$iface
:canon-qname lcoc_core.IFn$iface
:element-name "IFn$iface"}
nil)))))))
(defn non-nullable [tag]
(when-some [[_ base] (re-matches #"(.+)[?]" (name tag))]
(if (symbol? tag) ; is string support still desirable?
(with-meta (symbol (namespace tag) base) (meta tag))
base)))
(defn- type-env-from-map
"Takes a map from type params names (as strings) to types (as maps).
Returns a function from types (as maps) to types (as maps)."
[type-map]
#(if-some [t (when (:is-param %) (type-map (:element-name %)))]
(assoc t :nullable (:nullable %))
%))
(defn- type-map-for
[class-or-member type-args type-params]
(let [nargs (count type-args)
nparams (count type-params)]
(cond
(= nargs nparams)
(zipmap (map :element-name type-params) type-args)
(zero? nargs)
(into {} (map (fn [p] [(:element-name p) (:bound p dc-dynamic)])) type-params)
:else
(throw (Exception. (str "Expecting " nparams " type arguments to " class-or-member ", got " nargs "."))))))
(def type-env-for (comp type-env-from-map type-map-for))
(defn specialize-type [dart-type nullable clj-sym type-vars]
; there's some serious duplication going on between here and actual-*
(when dart-type
(->
(case (:canon-qname dart-type)
dc.Function
(if-some [type-parameters (seq (:type-parameters dart-type))]
(let [type-env (type-env-for
(:canon-qname dart-type)
(map #(resolve-type % type-vars) (:type-params (meta clj-sym)))
type-parameters)
type-vars (into type-vars (map :element-name) type-parameters)]
(assoc dart-type
:type-parameters
(into []
(keep (fn [p] (let [t (type-env (:element-name p))] (when (:is-param t) t))))
type-parameters)
:parameters (into [] (map #(update-in % :type type-env))
(:parameters dart-type))))
dart-type)
(assoc dart-type
:type-parameters (into [] (map #(resolve-type % type-vars)) (:type-params (meta clj-sym)))))
(assoc :nullable nullable))))
(defn specialize-function [function-info clj-sym type-vars]
(actual-member
[(type-env-for clj-sym
(map #(resolve-type % type-vars) (:type-params (meta clj-sym)))
(:type-parameters function-info))
function-info]))
(defn- cljdize [ns]
(if (symbol? ns)
(some-> (cljdize (name ns)) symbol (with-meta (meta ns)))
(when-some [[_ sub-ns] (some->> ns (re-matches #"clojure\.(.+)"))]
(str "cljd." sub-ns))))
(defn- resolve-non-local-symbol [sym type-vars]
(let [{:keys [libs] :as nses} @nses
{:keys [mappings clj-aliases] :as current-ns} (nses (:current-ns nses))
resolve (fn [sym]
(else->>
(if-some [v (get current-ns sym)] [:def v])
(if-some [v (get mappings sym)]
(recur (with-meta v (meta sym))))
(let [sym-ns (namespace sym)
lib-ns (or (cljdize sym-ns)
(some-> (get clj-aliases sym-ns) libs :ns name))])
(if (some-> lib-ns (not= sym-ns))
(recur (with-meta (symbol lib-ns (name sym)) (meta sym))))
(if-some [info (some-> sym-ns symbol nses (get (symbol (name sym))))]
[:def info])
(when-not (non-nullable sym))
(if-some [atype (resolve-dart-type sym type-vars)]
[:dart atype])))
specialize (fn [[tag info] nullable]
[tag (case tag
:def (update info :dart/type specialize-type nullable sym type-vars)
:dart (case (:kind info)
:function (specialize-function info sym type-vars)
:class (specialize-type info nullable sym type-vars)
:field info))])]
(or (some-> (resolve sym) (specialize false))
(some-> (non-nullable sym) resolve (specialize true)))))
(defn resolve-symbol
"Returns either a pair [tag value] or nil when the symbol can't be resolved.
tag can be :local, :def or :dart respectively indicating the symbol refers
to a local, a global def (var-like) or a Dart global.
The value depends on the tag:
- for :local it's whatever is in the env,
- for :def it's what's is in nses,
- for :dart it's the aliased dart symbol."
[sym env]
(if-some [v (env sym)]
[:local v]
(resolve-non-local-symbol sym (:type-vars env))))
(defn dart-alias-for-ns [ns]
(let [{:keys [current-ns] :as nses} @nses
lib (get-in nses [ns :lib])]
(-> nses :libs (get lib) :dart-alias)))
(defn resolve-type
"Resolves a type to map with keys :qname :lib :element-name and :type-parameters."
([sym type-vars]
(or (resolve-type sym type-vars nil) (throw (ex-info (str "Can't resolve type: " sym) {:sym sym}))))
([sym type-vars not-found]
(when-some [[tag info] (resolve-non-local-symbol sym type-vars)]
(case tag
:dart (do
(some-> info :lib (global-lib-alias nil))
(case (:canon-qname info)
dc.Function
;; TODO enrich type-vars with locally defined type params
(if-some [[rt & pt] (seq (map #(resolve-type % type-vars) (:params-types (meta sym))))]
(assoc info
:parameters (map (fn [t] {:kind :positional :type t}) pt)
:return-type rt)
info)
info))
:def (case (:type info)
:class (:dart/type info)
:field (case (when (= 'cljd.core (:ns info)) (:name info))
int dc-int
int? (assoc dc-int :nullable true)
double dc-double
double? (assoc dc-double :nullable true)
not-found)
not-found)
not-found))))
(defn unresolve-type [{:keys [is-param lib qname element-name type-parameters nullable] :as x}]
(if is-param
(symbol (cond-> qname nullable (str "?")))
(let [{:keys [current-ns] :as nses} @nses]
(when (nil? element-name)
(throw (ex-info (pr-str x) {:x x})))
(with-meta
(symbol
(when-not (= lib (:lib (nses current-ns)))
(or (get-in nses [current-ns :imports lib :clj-alias])
(some-> lib (global-lib-alias nil) (->> (str "$lib:")))))
(cond-> element-name nullable (str "?")))
{:type-params (mapv unresolve-type type-parameters)}))))
(defn emit-type
[tag {:keys [type-vars] :as env}]
(cond
(= 'some tag) pseudo-some
('#{void dart:core/void} tag) dc-void
:else
(or (resolve-type tag type-vars nil) (when *hosted* (resolve-type (symbol (name tag)) type-vars nil))
(throw (Exception. (str "Can't resolve type " tag "."))))))
(defn dart-type-truthiness [type]
(case (:canon-qname type)
(nil dc.Object dc.dynamic dc.Never) nil
(dc.Null void) :falsy
pseudo.some :some
dc.bool (when-not (:nullable type) :boolean)
(if (:nullable type) :some :truthy)))
(defn dart-meta
"Takes a clojure symbol and returns its dart metadata."
[sym env]
(let [{:keys [tag] :as m} (meta sym)
type (some-> tag (emit-type env))]
(cond-> {}
(:async m) (assoc :dart/async true)
(:getter m) (assoc :dart/getter true)
(:setter m) (assoc :dart/setter true)
(:const m) (assoc :dart/const true)
(:dart m) (assoc :dart/fn-type :native)
(:clj m) (assoc :dart/fn-type :ifn)
type (assoc :dart/type type)
(= (:canon-qname dc-Function) (:canon-qname type)) (assoc :dart/fn-type :native))))
(def reserved-words ; and built-in identifiers for good measure
#{"Function" "abstract" "as" "assert" "async" "await" "break" "case" "catch"
"class" "const" "continue" "covariant" "default" "deferred" "do" "dynamic"
"else" "enum" "export" "extends" "extension" "external" "factory" "false"
"final" "finally" "for" "get" "hide" "if" "implements" "import" "in"
"interface" "is" "library" "mixin" "new" "null" "on" "operator" "part"
"rethrow" "return" "set" "show" "static" "super" "switch" "sync" "this"
"throw" "true" "try" "typedef" "var" "void" "while" "with" "yield"})
(def char-map
{"-" "_"
"." "$DOT_"
"_" "$UNDERSCORE_"
"$" "$DOLLAR_"
":" "$COLON_"
"+" "$PLUS_"
">" "$GT_"
"<" "$LT_"
"=" "$EQ_"
"~" "$TILDE_"
"!" "$BANG_"
"@" "$CIRCA_"
"#" "$SHARP_"
"'" "$PRIME_"
"\"" "$QUOTE_"
"%" "$PERCENT_"
"^" "$CARET_"
"&" "$AMPERSAND_"
"*" "$STAR_"
"|" "$BAR_"
"{" "$LBRACE_"
"}" "$RBRACE_"
"[" "$LBRACK_"
"]" "$RBRACK_"
"/" "$SLASH_"
"\\" "$BSLASH_"
"?" "$QMARK_"})
(defn munge
([sym env] (munge sym nil env))
([sym suffix env]
(let [s (name sym)]
(with-meta
(or
(-> sym meta :dart/name)
(symbol
(cond->
(or (when (reserved-words s) (str "$" s "_"))
(replace-all s #"__(\d+)|__auto__|(^-)|[^a-zA-Z0-9]"
(fn [[x n leading-dash]]
(else->>
(if leading-dash "$_")
(if n (str "$" n "_"))
(if (= "__auto__" x) "$AUTO_")
(or (char-map x))
(str "$u"
;; TODO SELFHOST :cljd version
(str/join "_$u" (map #(-> % int Long/toHexString .toUpperCase) x))
"_")))))
suffix (str "$" suffix))))
(dart-meta sym env)))))
(defn munge* [dart-names]
(let [sb (StringBuilder. "$C$")]
(reduce
(fn [need-sep ^String dart-name]
(when (and need-sep (not (.startsWith dart-name "$C$")))
(.append sb "$$"))
(.append sb dart-name)
(not (.endsWith dart-name "$D$")))
false (map name dart-names))
(.append sb "$D$")
(symbol (.toString sb))))
(defn- dont-munge [sym suffix]
(let [m (meta sym)
sym (cond-> sym suffix (-> name (str "$" suffix) symbol))]
(with-meta sym (assoc m :dart/name sym))))
(defonce ^:private gens (atom 1))
(defn dart-global
([] (dart-global ""))
([prefix] (munge prefix (swap! gens inc) {})))
(def ^:dynamic *locals-gen*)
(defn dart-local
"Generates a unique (relative to the top-level being compiled) dart symbol.
Hint is a string/symbol/keyword which gives a hint (duh) on how to name the
dart symbol. Type tags when present are translated."
([env] (dart-local "" env))
([hint env]
(let [dart-hint (munge hint env)
{n dart-hint} (set! *locals-gen* (assoc *locals-gen* dart-hint (inc (*locals-gen* dart-hint 0))))
{:dart/keys [type] :as dart-meta} (dart-meta hint env)]
(with-meta (symbol (str dart-hint "$" n)) dart-meta))))
(defn- parse-dart-params [params]
(let [[fixed-params [delim & opt-params]] (split-with (complement '#{.& ...}) params)]
{:fixed-params fixed-params
:opt-kind (case delim .& :named :positional)
:opt-params
(for [[p d] (partition-all 2 1 opt-params)
:when (symbol? p)]
[p (when-not (symbol? d) d)])}))
(defn expand-protocol-impl [{:keys [name impl iface iext extensions]}]
(list `deftype impl []
:type-only true
'cljd.core/IProtocol
(list 'satisfies '[_ x]
(list* 'or (list 'dart/is? 'x iface)
(concat (for [t (keys (dissoc extensions 'fallback))] (list 'dart/is? 'x t)) [false])))
(list 'extensions '[_ x]
;; TODO SELFHOST sort types
(cons 'cond
(concat
(mapcat (fn [[t ext]] [(list 'dart/is? 'x t) ext]) (sort-by (fn [[x]] (case x Object 1 0)) (dissoc extensions 'fallback)))
[:else (or ('fallback extensions) `(throw (dart:core/Exception. (.+ (.+ ~(str "No extension of protocol " name " found for type ") (.toString (.-runtimeType ~'x))) "."))))])))))
(defn- roll-leading-opts [body]
(loop [[k v & more :as body] (seq body) opts {}]
(if (and body (keyword? k))
(recur more (assoc opts k v))
[opts body])))
(defn resolve-protocol-mname-to-dart-mname*
"Takes a protocol map and a method (as symbol) and the number of arguments passed
to this method.
Returns the name (as symbol) of the dart method backing this clojure method."
[protocol mname args-count type-env]
(or
(let [mname' (get-in protocol [:sigs mname args-count :dart/name] mname)]
(with-meta mname' (meta mname)))
(throw (Exception. (str "No method " mname " with " args-count " arg(s) for protocol " (:name protocol) ".")))))
(defn resolve-protocol-mname-to-dart-mname
"Takes two symbols (a protocol and one of its method) and the number
of arguments passed to this method.
Returns the name (as symbol) of the dart method backing this clojure method."
[pname mname args-count type-env]
(let [[tag protocol] (resolve-symbol pname {:type-vars type-env})]
(when (and (= :def tag) (= :protocol (:type protocol)))
(resolve-protocol-mname-to-dart-mname* protocol mname args-count type-env))))
(defn resolve-protocol-method [protocol mname args type-env]
(some-> (resolve-protocol-mname-to-dart-mname* protocol mname (count args) type-env)
(vector (into [] (map #(cond-> % (symbol? %) (vary-meta dissoc :tag))) args))))
(defn dart-method-sig
"Returns either nil or [[fixed params types] opts type-parameters]
where opts is either [opt-param1-type ... opt-paramN-type] or {opt-param-name type ...}."
[member-info]
(when-some [params (:parameters member-info)]
(let [[fixed opts] (split-with (fn [p] (and (= :positional (:kind p)) (not (:optional p)))) params)
opts (case (:kind (first opts))
:named (into {} (map (juxt (comp keyword :name) :type)) opts)
(into [] (map :type) opts))]
[(into [] (map :type) fixed) opts (:type-parameters member-info)])))
(defn full-class-info
"Takes a partial dart type (as map or discrete lib + element-name as strings).
Returns a fully populated type map."
([dart-type] (full-class-info (:lib dart-type) (:element-name dart-type)))
([lib element-name]
(let [{:keys [libs current-ns] :as all-nses} @nses]
(or (-> dart-libs-info (get lib) (get element-name))
(some-> (libs lib)
:ns
(vector (symbol element-name))
(some->> (get-in all-nses))
:dart/type)))))
(defn dart-member-lookup
"member is a symbol or a string"
([class member env]
(dart-member-lookup class member (meta member) env))
([class member member-meta {:keys [type-vars] :as env}]
(let [member-type-arguments (map #(resolve-type % type-vars) (:type-params member-meta))
member (name member)]
(when-some [class-info (full-class-info class)]
(when-some [[type-env member-info]
(or
(when-some [member-info (class-info member)]
[identity member-info])
(some #(dart-member-lookup % member env)
(cond->> (mapcat class-info [:interfaces :mixins :on])
(:super class-info) (cons (:super class-info)))))]
[(comp ; ordering matters
(type-env-for member member-type-arguments (:type-parameters member-info))
(type-env-for class (:type-parameters class) (:type-parameters class-info))
type-env)
member-info])))))
(declare actual-parameters)
(defn actual-type [analyzer-type type-env]
(case (:canon-qname analyzer-type)
nil nil
dc.Function
(-> analyzer-type
(update :return-type actual-type type-env)
(update :parameters actual-parameters type-env)
(update :type-parameters (fn [ps] (map #(actual-type % type-env) ps))))
(if (:is-param analyzer-type)
(type-env analyzer-type)
(update analyzer-type :type-parameters (fn [ps] (map #(actual-type % type-env) ps))))))
(defn actual-parameters [parameters type-env]
(map #(update % :type actual-type type-env) parameters))
(defn actual-member [[type-env member-info]]
(case (:kind member-info)
(:function :method)
(-> member-info
(update :return-type actual-type type-env)
(update :parameters actual-parameters type-env)
(update :type-parameters (fn [ps] (map #(actual-type % type-env) ps))))
:field
(update member-info :type actual-type type-env)
:constructor
;; TODO: what about type-parameters
(-> member-info
(update :return-type actual-type type-env)
(update :parameters actual-parameters type-env))))
(defn dart-fn-lookup [function function-info]
(let [type-args (:type-parameters function) ; TODO
type-params (:type-parameters function-info)
nargs (count type-args)
nparams (count type-params)
type-env (cond
(= nargs nparams)
(zipmap (map :element-name type-params) (:type-parameters class))
(zero? nargs)
(zipmap (map :element-name type-params)
(repeat (resolve-type 'dart:core/dynamic #{})))
:else
(throw (Exception. (str "Expecting " nparams " type arguments to " class ", got " nargs "."))))]
(actual-member
[#(or (when (:is-param %)
(cond-> (type-env (:element-name %))
(:nullable %) (assoc :nullable true))) %)
function-info])))
(defn unresolve-params
"Takes a list of parameters from the analyzer and returns a pair
[fixed-args opt-args] where fixed-args is a vector of symbols (with :tag meta)
and opt-args is either a set (named) or a vector (positional) of tagged symbols."
[parameters]
(let [[fixed optionals]
(split-with (fn [{:keys [kind optional]}]
(and (= kind :positional) (not optional))) parameters)
opts (case (:kind (first optionals))
:named #{}
[])
as-sym (fn [{:keys [name type]}]
(with-meta (symbol name) {:tag (unresolve-type type)}))]
[(into [] (map as-sym) fixed)
(conj (into opts (map as-sym) optionals))]))
(defn- transfer-tag [actual decl]
(let [m (meta actual)]
(cond-> actual
(nil? (:tag m))
(vary-meta assoc :tag (:tag (meta decl))))))
(defn resolve-dart-method
[type mname args type-env]
(if-some [member-info
(some->
(dart-member-lookup type mname
{:type-vars (into (or type-env #{}) (:type-params (meta mname)))})
actual-member)] ; TODO are there special cases for operators? eg unary-
(case (:kind member-info)
:field
(do
(when-not (:type member-info)
(throw (ex-info (pr-str member-info) {:member-info member-info})))
[(vary-meta mname assoc (case (count args) 1 :getter 2 :setter) true :tag (unresolve-type (:type member-info))) args])
:method
(let [[fixeds opts] (unresolve-params (:parameters member-info))
{:as actual :keys [opt-kind] [this & fixed-opts] :fixed-params}
(parse-dart-params args)
_ (when-not (= (count fixeds) (count fixed-opts))
(throw (Exception. (str "Fixed arity mismatch on " mname " for " (:element-name type) " of library " (:lib type)))))
_ (when-not (case opt-kind :named (set? opts) (vector? opts))
(throw (Exception. (str "Optional mismatch on " mname " for " (:element-name type) "of library " (:lib type)))))
actual-fixeds
(into [this] (map transfer-tag fixed-opts fixeds))
actual-opts
(case opt-kind
:named
(into []
(mapcat (fn [[p d]] [(transfer-tag p (opts p)) d]))
(:opt-params actual))
:positional
(mapv transfer-tag (:opt-params actual) opts))]
(when (= (:return-type member-info) {:nullable true})
(throw (ex-info (pr-str mname member-info) {:member-info member-info})))
[(vary-meta mname assoc :tag (unresolve-type (:return-type member-info)))
(cond-> actual-fixeds
(seq actual-opts)
(-> (conj (case opt-kind :named '.& '...))
(into actual-opts)))]))
#_(TODO WARN)))
(defn- expand-defprotocol [proto & methods]
;; TODO do something with docstrings
(let [proto (vary-meta proto assoc :tag 'cljd.core/IProtocol)
[doc-string & methods] (if (string? (first methods)) methods (list* nil methods))
method-mapping
(into {} (map (fn [[m & arglists]]
(let [dart-m (munge m {})
[doc-string & arglists] (if (string? (last arglists)) (reverse arglists) (list* nil arglists))]
[(with-meta m {:doc doc-string})
(into {} (map #(let [l (count %)] [l {:dart/name (symbol (str dart-m "$" (dec l)))
:args %}]))
arglists)]))) methods)
iface (munge proto "iface" {})
iface (with-meta iface {:dart/name iface})
iext (munge proto "ext" {})
iext (with-meta iext {:dart/name iext})
impl (munge proto "iprot" {})
impl (with-meta impl {:dart/name impl})
proto-map
{:name proto
:iface iface
:iext iext
:impl impl
:sigs method-mapping}
the-ns (name (:current-ns @nses))
full-iface (symbol the-ns (name iface))
full-iext (symbol the-ns (name iext))
full-proto (symbol the-ns (name proto))]
(list* 'do
(list* 'definterface iface
(for [[method arity-mapping] method-mapping
{:keys [dart/name args]} (vals arity-mapping)]
(list name (subvec args 1))))
(list* 'definterface iext
(for [[method arity-mapping] method-mapping
{:keys [dart/name args]} (vals arity-mapping)]
(list name args)))
(expand-protocol-impl proto-map)
(list 'defprotocol* proto proto-map)
(concat
(for [[method arity-mapping] method-mapping]
`(defn ~method
{:inline-arities ~(into #{} (map (comp count :args)) (vals arity-mapping))
:inline
(fn
~@(for [{:keys [dart/name] all-args :args} (vals arity-mapping)
:let [[[_ this] & args :as locals] (map (fn [arg] (list 'quote (gensym arg))) all-args)]]
`(~all-args
`(let [~~@(interleave locals all-args)]
(if (dart/is? ~'~this ~'~full-iface)
(. ~'~(with-meta this {:tag full-iface}) ~'~name ~~@args)
(. ^{:tag ~'~full-iext} (.extensions ~'~full-proto ~'~this) ~'~name ~'~this ~~@args))))))}
~@(for [{:keys [dart/name] [this & args :as all-args] :args} (vals arity-mapping)]
`(~all-args
(if (dart/is? ~this ~full-iface)
(. ~(with-meta this {:tag full-iface}) ~name ~@args)
(. ^{:tag ~full-iext} (.extensions ~proto ~this) ~name ~@all-args))))))
(list proto)))))
(defn- ensure-bodies [body-or-bodies]
(cond-> body-or-bodies (vector? (first body-or-bodies)) list))
(defn expand-extend-type [type & specs]
(let [proto+meths (reduce
(fn [proto+meths x]
(if (symbol? x)
(conj proto+meths [x])
(conj (pop proto+meths) (conj (peek proto+meths) x))))
[] specs)]
(cons 'do
(when-not *host-eval*
(for [[protocol & meths] proto+meths
:let [[tag info] (resolve-symbol protocol {})
_ (when-not (and (= tag :def) (= :protocol (:type info)))
(throw (Exception. (str protocol " isn't a protocol."))))
extension-base (munge* [(str type) (str protocol)]) ; str to get ns aliases if any
extension-name (dont-munge extension-base "cext")
extension-instance (dont-munge extension-base "extension")]]
(list 'do
(list* `deftype extension-name []
:type-only true
(:iext info)
(for [[mname & body-or-bodies] meths
[[this & args] & body] (ensure-bodies body-or-bodies)
:let [mname (get-in info [:sigs mname (inc (count args)) :dart/name])]]
`(~mname [~'_ ~this ~@args] (let* [~@(when-not (= type 'fallback)
[(vary-meta this assoc :tag type) this])] ~@body))))
(list 'def extension-instance (list 'new extension-name))
(list 'extend-type-protocol* type (:ns info) (:name info)
(symbol (name (:current-ns @nses)) (name extension-instance)))))))))
(defn create-host-ns [ns-sym directives]
(let [sym (symbol (str ns-sym "$host"))]
(remove-ns sym)
(binding [*ns* *ns*
*err* (java.io.Writer/nullWriter)]
(eval (list* 'ns sym directives))
;; NOTE: big trick here...
(require '[clojure.core :as cljd.core])
*ns*)))
(defn- hint-as [x tag]
(cond-> x (and tag (or (seq? x) (symbol? x))) (vary-meta assoc :tag tag)))
(defn- propagate-hints [expansion form]
(cond-> expansion (not (identical? form expansion)) (hint-as (:tag (meta form)))))
(defn inline-expand-1 [env form]
(->
(if-let [[f & args] (and (seq? form) (symbol? (first form)) form)]
(let [f-name (name f)
[f-type f-v] (resolve-symbol f env)
{:keys [inline-arities inline tag]} (case f-type
:def (:meta f-v)
nil)]
(cond
(env f) form
(and inline-arities (inline-arities (count args)))
(hint-as (apply inline args) tag)
:else form))
form)
(propagate-hints form)))
(defn resolve-static-member [sym]
(when-some [[_ alias t] (some->> sym namespace (re-matches #"(?:(.+)\.)?(.+)"))]
(when-some [type (resolve-type (symbol alias t) #{} nil)]
(let [[_ alias t] (re-matches #"(.+)\.(.+)" (name (:qname type)))]
[(with-meta (symbol (str "$lib:" alias) t) (meta sym)) (symbol (name sym))]))))
(defn macroexpand-1 [env form]
(->
(if-let [[f & args] (and (seq? form) (symbol? (first form)) form)]
(let [f-name (name f)
[f-type f-v] (resolve-symbol f env)
macro-fn (case f-type
:def (-> f-v :meta :macro-host-fn)