-
Notifications
You must be signed in to change notification settings - Fork 323
Expand file tree
/
Copy pathFable2Babel.fs
More file actions
4735 lines (3972 loc) · 196 KB
/
Fable2Babel.fs
File metadata and controls
4735 lines (3972 loc) · 196 KB
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
module rec Fable.Transforms.Fable2Babel
open System
open Fable
open Fable.AST
open Fable.AST.Babel
open System.Collections.Generic
open System.Text.RegularExpressions
type ReturnStrategy =
| Return
| ReturnUnit
| Assign of Expression
| Target of Identifier
type ConstructorRef =
| Annotation
| ActualConsRef
| Reflection
type Import =
{
Selector: string
LocalIdent: string option
Path: string
}
type ITailCallOpportunity =
abstract Label: string
abstract Args: string list
abstract IsRecursiveRef: Fable.Expr -> bool
type UsedNames =
{
RootScope: HashSet<string>
DeclarationScopes: HashSet<string>
CurrentDeclarationScope: HashSet<string>
}
type Context =
{
File: Fable.File
UsedNames: UsedNames
DecisionTargets: (Fable.Ident list * Fable.Expr) list
HoistVars: Fable.Ident list -> bool
TailCallOpportunity: ITailCallOpportunity option
OptimizeTailCall: unit -> unit
ScopedTypeParams: Set<string>
ForcedIdents: Set<string>
}
type ModuleDecl(name, ?isPublic, ?isMutable, ?typ, ?doc) =
member _.Name: string = name
member _.IsPublic = defaultArg isPublic false
member _.IsMutable = defaultArg isMutable false
member _.Type = defaultArg typ Fable.Any
member _.JsDoc: string option = doc
type IBabelCompiler =
inherit Compiler
abstract IsTypeScript: bool
abstract GetAllImports: unit -> Import seq
abstract GetImportExpr:
Context * selector: string * path: string * range: SourceLocation option * ?noMangle: bool -> Expression
abstract TransformAsExpr: Context * Fable.Expr -> Expression
abstract TransformAsStatements: Context * ReturnStrategy option * Fable.Expr -> Statement array
abstract TransformImport: Context * selector: string * path: string -> Expression
abstract TransformFunction:
Context * string option * Fable.Ident list * Fable.Expr -> (Parameter array) * BlockStatement
abstract WarnOnlyOnce: string * ?range: SourceLocation -> unit
abstract SaveTopDirectivePrologue: string -> unit
abstract GetAllAllTopDirectivesPrologue: unit -> string seq
module Lib =
let libCall (com: IBabelCompiler) ctx r moduleName memberName genArgs args =
let typeArguments =
Annotation.makeTypeParamInstantiationIfTypeScript com ctx genArgs
let callee = com.TransformImport(ctx, memberName, getLibPath com moduleName)
Expression.callExpression (callee, List.toArray args, ?typeArguments = typeArguments, ?loc = r)
let libValue (com: IBabelCompiler) ctx moduleName memberName =
com.TransformImport(ctx, memberName, getLibPath com moduleName)
let tryJsConstructorWithSuffix (com: IBabelCompiler) ctx ent (suffix: string) =
match JS.Replacements.tryConstructor com ent with
| Some(Fable.Import(info, typ, range)) when suffix.Length > 0 ->
let consExpr =
Fable.Import({ info with Selector = info.Selector + suffix }, typ, range)
com.TransformAsExpr(ctx, consExpr) |> Some
| Some(Fable.IdentExpr ident) when suffix.Length > 0 ->
let consExpr = Fable.IdentExpr { ident with Name = ident.Name + suffix }
com.TransformAsExpr(ctx, consExpr) |> Some
| consExpr -> consExpr |> Option.map (fun e -> com.TransformAsExpr(ctx, e))
let tryJsConstructorFor purpose (com: IBabelCompiler) ctx (ent: Fable.Entity) =
let isErased =
match purpose with
| Annotation ->
ent.IsMeasure
|| (ent.IsInterface && not com.IsTypeScript)
|| (FSharp2Fable.Util.isErasedOrStringEnumEntity ent && not ent.IsFSharpUnion)
// Historically we have used interfaces to represent JS classes in bindings,
// so we allow explicit type references (e.g. for type testing) when the interface is global or imported.
// But just in case we avoid referencing interfaces for reflection (as the type may not exist in actual code)
| ActualConsRef ->
if ent.IsInterface then
not (FSharp2Fable.Util.isGlobalOrImportedEntity ent)
else
ent.IsMeasure || FSharp2Fable.Util.isErasedOrStringEnumEntity ent
| Reflection ->
ent.IsInterface
|| ent.IsMeasure
|| FSharp2Fable.Util.isErasedOrStringEnumEntity ent
if isErased then
None
else
let suffix =
match purpose with
| Reflection
| ActualConsRef -> ""
| Annotation when
com.IsTypeScript
&& ent.IsFSharpUnion
&& List.isMultiple ent.UnionCases
&& not (Util.hasAnyAttribute [ Atts.stringEnum; Atts.erase; Atts.tsTaggedUnion ] ent.Attributes)
->
Util.UnionHelpers.UNION_SUFFIX
| Annotation -> ""
tryJsConstructorWithSuffix com ctx ent suffix
/// Cannot be used for annotations (use `tryJsConstructorFor Annotation` instead)
let jsConstructor (com: IBabelCompiler) ctx (ent: Fable.Entity) =
tryJsConstructorFor ActualConsRef com ctx ent
|> Option.defaultWith (fun () ->
$"Cannot find %s{ent.FullName} constructor" |> addError com [] None
Expression.nullLiteral ()
)
let sanitizeMemberName memberName =
if memberName = "constructor" then
memberName + "$"
else
memberName
module Reflection =
open Lib
let private libReflectionCall (com: IBabelCompiler) ctx r memberName args =
libCall com ctx r "Reflection" (memberName + "_type") [] args
let private transformRecordReflectionInfo com ctx r (ent: Fable.Entity) generics =
// TODO: Refactor these three bindings to reuse in transformUnionReflectionInfo
let fullname = ent.FullName
let fullnameExpr = Expression.stringLiteral (fullname)
let genMap =
let genParamNames =
ent.GenericParameters |> List.mapToArray (fun x -> x.Name) |> Seq.toArray
Array.zip genParamNames generics |> Map |> Some
let fields =
ent.FSharpFields
|> List.map (fun fi ->
let fieldName = sanitizeMemberName fi.Name |> Expression.stringLiteral
let typeInfo = transformTypeInfoFor Reflection com ctx r genMap fi.FieldType
Expression.arrayExpression ([| fieldName; typeInfo |])
)
|> List.toArray
let fields =
Expression.arrowFunctionExpression ([||], Expression.arrayExpression (fields))
[
fullnameExpr
Expression.arrayExpression (generics)
jsConstructor com ctx ent
fields
]
|> libReflectionCall com ctx None "record"
let private transformUnionReflectionInfo com ctx r (ent: Fable.Entity) generics =
let fullname = ent.FullName
let fullnameExpr = Expression.stringLiteral (fullname)
let genMap =
let genParamNames =
ent.GenericParameters |> List.map (fun x -> x.Name) |> Seq.toArray
Array.zip genParamNames generics |> Map |> Some
let cases =
ent.UnionCases
|> Seq.map (fun uci ->
uci.UnionCaseFields
|> List.mapToArray (fun fi ->
Expression.arrayExpression (
[|
fi.Name |> Expression.stringLiteral
transformTypeInfoFor Reflection com ctx r genMap fi.FieldType
|]
)
)
|> Expression.arrayExpression
)
|> Seq.toArray
let cases =
Expression.arrowFunctionExpression ([||], Expression.arrayExpression (cases))
[
fullnameExpr
Expression.arrayExpression (generics)
jsConstructor com ctx ent
cases
]
|> libReflectionCall com ctx None "union"
let transformTypeInfoFor
purpose
(com: IBabelCompiler)
ctx
r
(genMap: Map<string, Expression> option)
typ
: Expression
=
let primitiveTypeInfo name =
libValue com ctx "Reflection" (name + "_type")
let numberInfo kind =
getNumberKindName kind |> primitiveTypeInfo
let nonGenericTypeInfo fullname =
[ Expression.stringLiteral (fullname) ]
|> libReflectionCall com ctx None "class"
let resolveGenerics generics : Expression list =
generics |> List.map (transformTypeInfoFor purpose com ctx r genMap)
let genericTypeInfo name genArgs =
let resolved = resolveGenerics genArgs
libReflectionCall com ctx None name resolved
let genericEntity (fullname: string) generics =
libReflectionCall
com
ctx
None
"class"
[
Expression.stringLiteral (fullname)
if not (Array.isEmpty generics) then
Expression.arrayExpression (generics)
]
let genericGlobalOrImportedEntity generics (ent: Fable.Entity) =
libReflectionCall
com
ctx
None
"class"
[
yield Expression.stringLiteral (ent.FullName)
match generics with
| [||] -> yield Util.undefined None None
| generics -> yield Expression.arrayExpression (generics)
match tryJsConstructorFor purpose com ctx ent with
| Some cons -> yield cons
| None -> ()
]
match typ with
| Fable.Measure _
| Fable.Any -> primitiveTypeInfo "obj"
| Fable.GenericParam(name = name) ->
match genMap with
| None -> [ Expression.stringLiteral (name) ] |> libReflectionCall com ctx None "generic"
| Some genMap ->
match Map.tryFind name genMap with
| Some t -> t
| None ->
Replacements.Util.genericTypeInfoError name |> addError com [] r
Expression.nullLiteral ()
| Fable.Unit -> primitiveTypeInfo "unit"
| Fable.Boolean -> primitiveTypeInfo "bool"
| Fable.Char -> primitiveTypeInfo "char"
| Fable.String -> primitiveTypeInfo "string"
| Fable.Number(kind, info) ->
match info with
| Fable.NumberInfo.IsEnum entRef ->
let ent = com.GetEntity(entRef)
let cases =
ent.FSharpFields
|> List.choose (fun fi ->
match fi.Name with
| "value__" -> None
| name ->
let value =
match fi.LiteralValue with
| Some v -> System.Convert.ToDouble v
| None -> 0.
Expression.arrayExpression (
[| Expression.stringLiteral (name); Expression.numericLiteral (value) |]
)
|> Some
)
|> Seq.toArray
|> Expression.arrayExpression
[ Expression.stringLiteral (entRef.FullName); numberInfo kind; cases ]
|> libReflectionCall com ctx None "enum"
| _ -> numberInfo kind
| Fable.LambdaType(argType, returnType) -> genericTypeInfo "lambda" [ argType; returnType ]
| Fable.DelegateType(argTypes, returnType) -> genericTypeInfo "delegate" [ yield! argTypes; yield returnType ]
| Fable.Tuple(genArgs, _) -> genericTypeInfo "tuple" genArgs
| Fable.Nullable(genArg, true) -> genericTypeInfo "option" [ genArg ]
| Fable.Nullable(genArg, false) -> transformTypeInfoFor purpose com ctx r genMap genArg
| Fable.Option(genArg, _) -> genericTypeInfo "option" [ genArg ]
| Fable.Array(genArg, _) -> genericTypeInfo "array" [ genArg ]
| Fable.List genArg -> genericTypeInfo "list" [ genArg ]
| Fable.Regex -> nonGenericTypeInfo Types.regex
| Fable.MetaType -> nonGenericTypeInfo Types.type_
| Fable.AnonymousRecordType(fieldNames, genArgs, _isStruct) ->
let genArgs = resolveGenerics genArgs
List.zip (fieldNames |> Array.toList) genArgs
|> List.map (fun (k, t) -> Expression.arrayExpression [| Expression.stringLiteral (k); t |])
|> libReflectionCall com ctx None "anonRecord"
| Fable.DeclaredType(entRef, genArgs) ->
let fullName = entRef.FullName
match fullName, genArgs with
| Replacements.Util.BuiltinEntity kind ->
match kind with
| Replacements.Util.BclGuid
| Replacements.Util.BclTimeSpan
| Replacements.Util.BclDateTime
| Replacements.Util.BclDateTimeOffset
| Replacements.Util.BclDateOnly
| Replacements.Util.BclTimeOnly
| Replacements.Util.BclTimer -> genericEntity fullName [||]
| Replacements.Util.BclHashSet gen
| Replacements.Util.FSharpSet gen ->
genericEntity fullName [| transformTypeInfoFor purpose com ctx r genMap gen |]
| Replacements.Util.BclDictionary(key, value)
| Replacements.Util.BclKeyValuePair(key, value)
| Replacements.Util.FSharpMap(key, value) ->
genericEntity
fullName
[|
transformTypeInfoFor purpose com ctx r genMap key
transformTypeInfoFor purpose com ctx r genMap value
|]
| Replacements.Util.FSharpResult(ok, err) ->
let ent = com.GetEntity(entRef)
transformUnionReflectionInfo
com
ctx
r
ent
[|
transformTypeInfoFor purpose com ctx r genMap ok
transformTypeInfoFor purpose com ctx r genMap err
|]
| Replacements.Util.FSharpChoice gen ->
let ent = com.GetEntity(entRef)
let gen = List.map (transformTypeInfoFor purpose com ctx r genMap) gen
List.toArray gen |> transformUnionReflectionInfo com ctx r ent
| Replacements.Util.FSharpReference gen ->
let ent = com.GetEntity(entRef)
[| transformTypeInfoFor purpose com ctx r genMap gen |]
|> transformRecordReflectionInfo com ctx r ent
| _ ->
let generics =
genArgs
|> List.map (transformTypeInfoFor purpose com ctx r genMap)
|> List.toArray
match com.GetEntity(entRef) with
| Patterns.Try (Util.tryFindAnyEntAttribute [ Atts.stringEnum
Atts.erase
Atts.tsTaggedUnion
Atts.pojoDefinedByConsArgs ]) (att, _) as ent ->
match att with
| Atts.stringEnum -> primitiveTypeInfo "string"
| Atts.erase ->
match ent.UnionCases with
| [ uci ] when List.isSingle uci.UnionCaseFields ->
transformTypeInfoFor purpose com ctx r genMap uci.UnionCaseFields[0].FieldType
| cases when cases |> List.forall (fun c -> List.isEmpty c.UnionCaseFields) ->
primitiveTypeInfo "string"
| _ -> genericEntity ent.FullName generics
| _ -> genericEntity ent.FullName generics
| ent ->
if FSharp2Fable.Util.isGlobalOrImportedEntity ent then
genericGlobalOrImportedEntity generics ent
elif ent.IsInterface || FSharp2Fable.Util.isReplacementCandidate entRef then
genericEntity ent.FullName generics
elif ent.IsMeasure then
[ Expression.stringLiteral (ent.FullName) ]
|> libReflectionCall com ctx None "measure"
else
let reflectionMethodExpr =
FSharp2Fable.Util.entityIdentWithSuffix com entRef Naming.reflectionSuffix
let callee = com.TransformAsExpr(ctx, reflectionMethodExpr)
Expression.callExpression (callee, generics)
let transformReflectionInfo com ctx r (ent: Fable.Entity) generics =
if ent.IsFSharpRecord then
transformRecordReflectionInfo com ctx r ent generics
elif ent.IsFSharpUnion then
transformUnionReflectionInfo com ctx r ent generics
else
[
yield Expression.stringLiteral (ent.FullName)
match generics with
| [||] -> yield Util.undefined None None
| generics -> yield Expression.arrayExpression (generics)
match tryJsConstructorFor Reflection com ctx ent with
| Some cons when not (com.IsTypeScript && ent.IsAbstractClass) -> yield cons
| _ -> yield Util.undefined None None
match ent.BaseType with
| Some d ->
let genMap =
Seq.zip ent.GenericParameters generics
|> Seq.map (fun (p, e) -> p.Name, e)
|> Map
|> Some
yield
Fable.DeclaredType(d.Entity, d.GenericArgs)
|> transformTypeInfoFor Reflection com ctx r genMap
| None -> ()
]
|> libReflectionCall com ctx r "class"
let transformTypeTest (com: IBabelCompiler) ctx range expr typ : Expression =
let warnAndEvalToFalse msg =
"Cannot type test (evals to false): " + msg |> addWarning com [] range
Expression.booleanLiteral (false)
let jsTypeof (primitiveType: string) (Util.TransformExpr com ctx expr) : Expression =
let typeof = Expression.unaryExpression ("typeof", expr)
Expression.binaryExpression (BinaryEqual, typeof, Expression.stringLiteral (primitiveType), ?loc = range)
let jsInstanceof consExpr (Util.TransformExpr com ctx expr) : Expression =
BinaryExpression(expr, consExpr, "instanceof", range)
match typ with
| Fable.Measure _ // Dummy, shouldn't be possible to test against a measure type
| Fable.Any -> Expression.booleanLiteral (true)
| Fable.Unit -> com.TransformAsExpr(ctx, expr) |> Util.makeNullCheck range true
| Fable.Boolean -> jsTypeof "boolean" expr
| Fable.Char
| Fable.String -> jsTypeof "string" expr
| Fable.Number(Decimal, _) -> jsInstanceof (libValue com ctx "Decimal" "default") expr
| Fable.Number(JS.Replacements.BigIntegers _, _) -> jsTypeof "bigint" expr
| Fable.Number _ -> jsTypeof "number" expr
| Fable.Regex -> jsInstanceof (Expression.identifier ("RegExp")) expr
| Fable.LambdaType _
| Fable.DelegateType _ -> jsTypeof "function" expr
| Fable.Array _
| Fable.Tuple _ -> libCall com ctx None "Util" "isArrayLike" [] [ com.TransformAsExpr(ctx, expr) ]
| Fable.List _ -> jsInstanceof (libValue com ctx "List" "FSharpList") expr
| Fable.AnonymousRecordType _ -> warnAndEvalToFalse "anonymous records"
| Fable.MetaType -> jsInstanceof (libValue com ctx "Reflection" "TypeInfo") expr
| Fable.Option _ -> warnAndEvalToFalse "options" // TODO
| Fable.GenericParam _ -> warnAndEvalToFalse "generic parameters"
| Fable.Nullable(genArg, _isStruct) -> transformTypeTest com ctx range expr genArg
| Fable.DeclaredType(entRef, genArgs) ->
match entRef.FullName with
| Types.idisposable ->
match expr with
| MaybeCasted(ExprType(Fable.DeclaredType(entRef2, _))) when
com.GetEntity(entRef2) |> FSharp2Fable.Util.hasInterface Types.idisposable
->
Expression.booleanLiteral (true)
| _ ->
[ com.TransformAsExpr(ctx, expr) ]
|> libCall com ctx range "Util" "isDisposable" []
| Types.ienumerable ->
[ com.TransformAsExpr(ctx, expr) ]
|> libCall com ctx range "Util" "isIterable" []
| Types.array ->
[ com.TransformAsExpr(ctx, expr) ]
|> libCall com ctx range "Util" "isArrayLike" []
| Types.exception_ ->
[ com.TransformAsExpr(ctx, expr) ]
|> libCall com ctx range "Util" "isException" []
| _ ->
match com.GetEntity(entRef) with
| Patterns.Try (Util.tryFindAnyEntAttribute [ Atts.stringEnum; Atts.erase; Atts.tsTaggedUnion ]) (att, _) as ent ->
match att with
| Atts.stringEnum -> jsTypeof "string" expr
| Atts.erase when ent.IsFSharpUnion ->
match ent.UnionCases with
| [ uci ] when List.isSingle uci.UnionCaseFields ->
transformTypeTest com ctx range expr uci.UnionCaseFields[0].FieldType
| cases when cases |> List.forall (fun c -> List.isEmpty c.UnionCaseFields) ->
jsTypeof "string" expr
| _ -> warnAndEvalToFalse (ent.FullName + " (erased)")
| _ -> warnAndEvalToFalse (ent.FullName + " (erased)")
| Patterns.Try (tryJsConstructorFor ActualConsRef com ctx) cons ->
if not (List.isEmpty genArgs) then
com.WarnOnlyOnce("Generic args are ignored in type testing", ?range = range)
jsInstanceof cons expr
| _ -> warnAndEvalToFalse entRef.FullName
module Annotation =
let isByRefOrAnyType (com: IBabelCompiler) =
function
| Replacements.Util.IsByRefType com _ -> true
| Fable.Any -> true
| _ -> false
let isInRefOrAnyType (com: IBabelCompiler) =
function
| Replacements.Util.IsInRefType com _ -> true
| Fable.Any -> true
| _ -> false
let makeTypeParamDecl (com: IBabelCompiler) (ctx: Context) genArgs =
// Maybe there's a way to represent measurements in TypeScript
genArgs
|> List.chooseToArray (
function
| Fable.GenericParam(name, isMeasure, constraints) when not isMeasure ->
// TODO: Other constraints? comparison, nullable
let bound =
constraints
|> List.choose (
function
| Fable.Constraint.CoercesTo t -> makeTypeAnnotation com ctx t |> Some
| _ -> None
)
|> function
| [] -> None
| [ t ] -> Some t
| ts -> ts |> List.toArray |> IntersectionTypeAnnotation |> Some
TypeParameter.typeParameter (name, ?bound = bound) |> Some
| _ -> None
)
|> Array.distinct
let makeTypeParamInstantiation (com: IBabelCompiler) ctx genArgs =
if List.isEmpty genArgs then
[||]
else
genArgs
|> List.chooseToArray (fun t ->
if isUnitOfMeasure t then
None
else
makeTypeAnnotation com ctx t |> Some
)
let makeTypeParamInstantiationIfTypeScript (com: IBabelCompiler) ctx genArgs =
if com.IsTypeScript then
makeTypeParamInstantiation com ctx genArgs |> Some
else
None
let getGenericTypeAnnotation com ctx name genArgs =
let typeParamInst = makeTypeParamInstantiation com ctx genArgs
TypeAnnotation.aliasTypeAnnotation (Identifier.identifier (name), typeArguments = typeParamInst)
let makeTypeAnnotation com ctx typ : TypeAnnotation =
match typ with
| Fable.Measure _
| Fable.MetaType
| Fable.Any -> AnyTypeAnnotation
| Fable.Unit -> VoidTypeAnnotation
| Fable.Boolean -> BooleanTypeAnnotation
| Fable.Char -> StringTypeAnnotation
| Fable.String -> StringTypeAnnotation
| Fable.Regex -> makeAliasTypeAnnotation com ctx "RegExp"
| Fable.Number(BigInt, _) -> makeAliasTypeAnnotation com ctx "bigint"
| Fable.Number(Int32, Fable.NumberInfo.IsEnum ent) when ent.FullName = "System.DateTimeKind" ->
makeFableLibImportTypeAnnotation com ctx [] "Util" "DateTimeKind"
| Fable.Number(kind, _) -> makeNumericTypeAnnotation com ctx kind
| Fable.Nullable(genArg, isStruct) -> makeNullableTypeAnnotation com ctx isStruct genArg
| Fable.Option(genArg, isStruct) -> makeOptionTypeAnnotation com ctx isStruct genArg
| Fable.Tuple(genArgs, isStruct) -> makeTupleTypeAnnotation com ctx isStruct genArgs
| Fable.Array(genArg, kind) -> makeArrayTypeAnnotation com ctx genArg kind
| Fable.List genArg -> makeListTypeAnnotation com ctx genArg
| Fable.GenericParam(name = name) -> makeAliasTypeAnnotation com ctx name
| Fable.LambdaType(argType, returnType) -> makeFunctionTypeAnnotation com ctx typ [ argType ] returnType
| Fable.DelegateType(argTypes, returnType) -> makeFunctionTypeAnnotation com ctx typ argTypes returnType
| Fable.AnonymousRecordType(fieldNames, fieldTypes, _isStruct) ->
makeAnonymousRecordTypeAnnotation com ctx fieldNames fieldTypes
| Replacements.Util.Builtin kind -> makeBuiltinTypeAnnotation com ctx typ kind
| Fable.DeclaredType(entRef, genArgs) -> com.GetEntity(entRef) |> makeEntityTypeAnnotation com ctx genArgs
let makeTypeAnnotationIfTypeScript (com: IBabelCompiler) ctx typ expr =
if com.IsTypeScript then
match typ, expr with
| Fable.Option _, _ -> makeTypeAnnotation com ctx typ |> Some
// Use type annotation for NullLiteral and enum cases
| _, Some(Literal(Literal.StringLiteral _))
| _, Some(Literal(StringTemplate _))
| _, Some(Literal(BooleanLiteral _))
| _, Some(Literal(NumericLiteral _))
| _, Some(Literal(RegExp _))
| _, Some(FunctionExpression _)
| _, Some(ArrowFunctionExpression _) -> None
| _, Some(AsExpression _) -> None
| _ -> makeTypeAnnotation com ctx typ |> Some
else
None
// Fields are uncurried in the AST but not the declaration
let makeFieldAnnotation (com: IBabelCompiler) ctx (fieldType: Fable.Type) =
FableTransforms.uncurryType fieldType |> makeTypeAnnotation com ctx
let makeFieldAnnotationIfTypeScript (com: IBabelCompiler) ctx (fieldType: Fable.Type) =
if com.IsTypeScript then
makeFieldAnnotation com ctx fieldType |> Some
else
None
let makeTypeAnnotationWithParametersIfTypeScript (com: IBabelCompiler) ctx typ expr =
match makeTypeAnnotationIfTypeScript com ctx typ expr with
| Some(FunctionTypeAnnotation _) as annotation ->
let _, typeParams =
match typ with
| Fable.LambdaType(argType, returnType) -> [ argType; returnType ]
| Fable.DelegateType(argTypes, returnType) -> argTypes @ [ returnType ]
| _ -> []
|> Util.getTypeParameters ctx
annotation, makeTypeParamDecl com ctx typeParams
| annotation -> annotation, [||]
let makeAliasTypeAnnotation _com _ctx name =
TypeAnnotation.aliasTypeAnnotation (Identifier.identifier (name))
let makeGenericTypeAnnotation com ctx genArgs id =
let typeParamInst = makeTypeParamInstantiation com ctx genArgs
TypeAnnotation.aliasTypeAnnotation (id, typeArguments = typeParamInst)
let makeNativeTypeAnnotation com ctx genArgs typeName =
Identifier.identifier (typeName) |> makeGenericTypeAnnotation com ctx genArgs
let makeFableLibImportTypeId (com: IBabelCompiler) ctx moduleName typeName =
let expr = com.GetImportExpr(ctx, typeName, getLibPath com moduleName, None)
match expr with
| Expression.Identifier(id) -> id
| _ -> Identifier.identifier (typeName)
let makeFableLibImportTypeAnnotation com ctx genArgs moduleName typeName =
let id = makeFableLibImportTypeId com ctx moduleName typeName
makeGenericTypeAnnotation com ctx genArgs id
let makeNumericTypeAnnotation com ctx kind =
let moduleName =
match kind with
| Decimal -> "Decimal"
| JS.Replacements.BigIntegers _ -> "BigInt"
| _ -> "Int32"
let typeName = getNumberKindName kind
makeFableLibImportTypeAnnotation com ctx [] moduleName typeName
let makeNullableTypeAnnotation com ctx isStruct genArg =
if isStruct then
makeFableLibImportTypeAnnotation com ctx [ genArg ] "Util" "Nullable"
else
makeTypeAnnotation com ctx genArg // nullable reference types are erased
let makeOptionTypeAnnotation com ctx _isStruct genArg =
makeFableLibImportTypeAnnotation com ctx [ genArg ] "Option" "Option"
let makeTupleTypeAnnotation com ctx _isStruct genArgs =
List.map (makeTypeAnnotation com ctx) genArgs
|> List.toArray
|> TupleTypeAnnotation
let makeArrayTypeAnnotation com ctx genArg kind =
match kind with
| Fable.ResizeArray ->
// makeNativeTypeAnnotation com ctx [genArg] "Array"
makeTypeAnnotation com ctx genArg |> ArrayTypeAnnotation
| Fable.MutableArray
| Fable.ImmutableArray -> makeFableLibImportTypeAnnotation com ctx [ genArg ] "Util" "MutableArray"
let makeListTypeAnnotation com ctx genArg =
makeFableLibImportTypeAnnotation com ctx [ genArg ] "List" "FSharpList"
let makeUnionTypeAnnotation com ctx genArgs =
List.map (makeTypeAnnotation com ctx) genArgs
|> List.toArray
|> UnionTypeAnnotation
let makeBuiltinTypeAnnotation com ctx typ kind =
match kind with
| Replacements.Util.BclGuid -> StringTypeAnnotation
| Replacements.Util.BclTimeSpan -> NumberTypeAnnotation
| Replacements.Util.BclDateTime -> makeAliasTypeAnnotation com ctx "Date"
| Replacements.Util.BclDateTimeOffset -> makeAliasTypeAnnotation com ctx "Date"
| Replacements.Util.BclDateOnly -> makeAliasTypeAnnotation com ctx "Date"
| Replacements.Util.BclTimeOnly -> NumberTypeAnnotation
| Replacements.Util.BclTimer -> makeFableLibImportTypeAnnotation com ctx [] "Timer" "Timer"
| Replacements.Util.BclHashSet key -> makeFableLibImportTypeAnnotation com ctx [ key ] "Util" "ISet"
| Replacements.Util.BclDictionary(key, value) ->
makeFableLibImportTypeAnnotation com ctx [ key; value ] "Util" "IMap"
| Replacements.Util.BclKeyValuePair(key, value) -> makeTupleTypeAnnotation com ctx true [ key; value ]
| Replacements.Util.FSharpSet key -> makeFableLibImportTypeAnnotation com ctx [ key ] "Set" "FSharpSet"
| Replacements.Util.FSharpMap(key, value) ->
makeFableLibImportTypeAnnotation com ctx [ key; value ] "Map" "FSharpMap"
| Replacements.Util.FSharpResult(ok, err) ->
$"FSharpResult$2{Util.UnionHelpers.UNION_SUFFIX}"
|> makeFableLibImportTypeAnnotation com ctx [ ok; err ] "Result"
| Replacements.Util.FSharpChoice genArgs ->
$"FSharpChoice${List.length genArgs}{Util.UnionHelpers.UNION_SUFFIX}"
|> makeFableLibImportTypeAnnotation com ctx genArgs "Choice"
| Replacements.Util.FSharpReference genArg ->
if isInRefOrAnyType com typ then
makeTypeAnnotation com ctx genArg
else
makeFableLibImportTypeAnnotation com ctx [ genArg ] "Types" "FSharpRef"
let makeFunctionTypeAnnotation com ctx _typ argTypes returnType =
let funcTypeParams =
match argTypes with
| [ Fable.Unit ] -> []
| _ -> argTypes
|> List.mapi (fun i argType ->
FunctionTypeParam.functionTypeParam (
Identifier.identifier ($"arg{i}"),
makeTypeAnnotation com ctx argType
)
)
|> List.toArray
let returnType = makeTypeAnnotation com ctx returnType
TypeAnnotation.functionTypeAnnotation (funcTypeParams, returnType)
// Move this to Replacements.tryEntity?
let tryNativeOrFableLibraryInterface com ctx genArgs (ent: Fable.Entity) =
match ent.FullName with
| Types.fsharpAsyncGeneric -> makeFableLibImportTypeAnnotation com ctx genArgs "AsyncBuilder" "Async" |> Some
| _ when not ent.IsInterface -> None
// everything below is an interface
| Types.icollection ->
// makeFableLibImportTypeAnnotation com ctx [Fable.Any] "Util" "ICollection" |> Some
makeNativeTypeAnnotation com ctx [ Fable.Any ] "Iterable" |> Some
| Types.icollectionGeneric ->
// makeFableLibImportTypeAnnotation com ctx genArgs "Util" "ICollection" |> Some
makeNativeTypeAnnotation com ctx genArgs "Iterable" |> Some
// | Types.idictionary
// | Types.ireadonlydictionary
| Types.idisposable -> makeFableLibImportTypeAnnotation com ctx genArgs "Util" "IDisposable" |> Some
| Types.ienumerable ->
// makeFableLibImportTypeAnnotation com ctx [Fable.Any] "Util" "IEnumerable" |> Some
makeNativeTypeAnnotation com ctx [ Fable.Any ] "Iterable" |> Some
| Types.ienumerableGeneric ->
// makeFableLibImportTypeAnnotation com ctx genArgs "Util" "IEnumerable" |> Some
makeNativeTypeAnnotation com ctx genArgs "Iterable" |> Some
| Types.ienumerator ->
makeFableLibImportTypeAnnotation com ctx [ Fable.Any ] "Util" "IEnumerator"
|> Some
| Types.ienumeratorGeneric -> makeFableLibImportTypeAnnotation com ctx genArgs "Util" "IEnumerator" |> Some
| Types.icomparable ->
makeFableLibImportTypeAnnotation com ctx [ Fable.Any ] "Util" "IComparable"
|> Some
| Types.icomparableGeneric
| Types.iStructuralComparable -> makeFableLibImportTypeAnnotation com ctx genArgs "Util" "IComparable" |> Some
| Types.iequatableGeneric
| Types.iStructuralEquatable -> makeFableLibImportTypeAnnotation com ctx genArgs "Util" "IEquatable" |> Some
| Types.icomparer ->
makeFableLibImportTypeAnnotation com ctx [ Fable.Any ] "Util" "IComparer"
|> Some
| Types.icomparerGeneric -> makeFableLibImportTypeAnnotation com ctx genArgs "Util" "IComparer" |> Some
| Types.iequalityComparerGeneric ->
makeFableLibImportTypeAnnotation com ctx genArgs "Util" "IEqualityComparer"
|> Some
| Types.iobserverGeneric ->
makeFableLibImportTypeAnnotation com ctx genArgs "Observable" "IObserver"
|> Some
| Types.iobservableGeneric ->
makeFableLibImportTypeAnnotation com ctx genArgs "Observable" "IObservable"
|> Some
| "Microsoft.FSharp.Control.IEvent`1" ->
makeFableLibImportTypeAnnotation com ctx genArgs "Event" "IEvent" |> Some
| Types.ievent2 -> makeFableLibImportTypeAnnotation com ctx genArgs "Event" "IEvent$2" |> Some
| "Fable.Core.JS.Set`1" -> makeFableLibImportTypeAnnotation com ctx genArgs "Util" "ISet" |> Some
| "Fable.Core.JS.Map`2" -> makeFableLibImportTypeAnnotation com ctx genArgs "Util" "IMap" |> Some
| _ -> None
let makeStringEnumTypeAnnotation (ent: Fable.Entity) (attArgs: obj list) =
let rule =
match List.tryHead attArgs with
| Some(:? int as rule) -> enum<Core.CaseRules> (rule)
| _ -> Core.CaseRules.LowerFirst
ent.UnionCases
|> List.mapToArray (fun uci ->
match uci.CompiledName with
| Some name -> name
| None -> Naming.applyCaseRule rule uci.Name
|> Literal.stringLiteral
|> LiteralTypeAnnotation
)
|> UnionTypeAnnotation
let makeErasedUnionTypeAnnotation com ctx genArgs (ent: Fable.Entity) =
let transformSingleFieldType (uci: Fable.UnionCase) =
List.tryHead uci.UnionCaseFields
|> Option.map (fun fi -> fi.FieldType |> resolveInlineType genArgs |> makeFieldAnnotation com ctx)
|> Option.defaultValue VoidTypeAnnotation
match ent.UnionCases with
| [ uci ] when List.isMultiple uci.UnionCaseFields ->
uci.UnionCaseFields
|> List.mapToArray (fun fi -> fi.FieldType |> resolveInlineType genArgs |> makeFieldAnnotation com ctx)
|> TupleTypeAnnotation
| [ uci ] -> transformSingleFieldType uci
| ucis -> ucis |> List.mapToArray transformSingleFieldType |> UnionTypeAnnotation
let makeTypeScriptTaggedUnionTypeAnnotation com ctx genArgs (ent: Fable.Entity) (attArgs: obj list) =
let tag, rule =
match attArgs with
| (:? string as tag) :: (:? int as rule) :: _ -> tag, enum<Core.CaseRules> (rule)
| (:? string as tag) :: _ -> tag, Core.CaseRules.LowerFirst
| _ -> "kind", Core.CaseRules.LowerFirst
ent.UnionCases
|> List.mapToArray (fun uci ->
let tagMember =
let tagType =
match uci.CompiledName with
| Some name -> name
| None -> Naming.applyCaseRule rule uci.Name
|> Literal.stringLiteral
|> LiteralTypeAnnotation
let prop, isComputed = Util.memberFromName tag
AbstractMember.abstractProperty (prop, tagType, isComputed = isComputed)
match uci.UnionCaseFields with
// | [ field ] when field.Name = "Item" ->
// IntersectionTypeAnnotation
// [|
// field.FieldType |> resolveInlineType genArgs |> makeFieldAnnotation com ctx
// ObjectTypeAnnotation [| tagMember |]
// |]
| fields ->
let names, types =
fields |> List.map (fun fi -> fi.Name, fi.FieldType) |> List.unzip
makeAnonymousRecordTypeAnnotation com ctx (List.toArray names) types
|> function
| ObjectTypeAnnotation members -> ObjectTypeAnnotation(Array.append [| tagMember |] members)
| t -> t // Unexpected
)
|> UnionTypeAnnotation
let makeEntityTypeAnnotation com ctx genArgs (ent: Fable.Entity) =
match genArgs, ent with
| _, Patterns.Try (tryNativeOrFableLibraryInterface com ctx genArgs) ta -> ta
| _, Patterns.Try (Lib.tryJsConstructorFor Annotation com ctx) entRef ->
match entRef with
| Literal(Literal.StringLiteral(StringLiteral(str, _))) ->
match str with
| "number" -> NumberTypeAnnotation
| "boolean" -> BooleanTypeAnnotation
| "string" -> StringTypeAnnotation
| _ -> AnyTypeAnnotation
| Expression.Identifier(id) -> makeGenericTypeAnnotation com ctx genArgs id
// TODO: Resolve references to types in nested modules
| _ -> AnyTypeAnnotation
| _,
Patterns.Try (Util.tryFindAnyEntAttribute [ Atts.erase; Atts.stringEnum; Atts.tsTaggedUnion ]) (attFullName,
attArgs) when
ent.IsFSharpUnion
->
let genArgs =
List.zip ent.GenericParameters genArgs
|> List.map (fun (p, a) -> p.Name, a)
|> Map
match attFullName with
| Atts.stringEnum -> makeStringEnumTypeAnnotation ent attArgs
| Atts.erase -> makeErasedUnionTypeAnnotation com ctx genArgs ent
| _ -> makeTypeScriptTaggedUnionTypeAnnotation com ctx genArgs ent attArgs
| _ -> AnyTypeAnnotation
let unwrapOptionalType t =
match t with
| Fable.Option(t, _) when not (mustWrapOption t) -> t
| _ -> t
let unwrapOptionalArg com (arg: Fable.Expr) =
match arg.Type with
| Fable.Option(t, _) when not (mustWrapOption t) ->
match arg with
| Fable.Value(Fable.NewOption(Some arg, _, _), _) -> true, arg
| Fable.Value(Fable.NewOption(None, _, _), _) -> true, Fable.TypeCast(arg, t)
| _ -> true, Replacements.Util.Helper.LibCall(com, "Option", "unwrap", t, [ arg ])
| _ -> false, arg
// In TypeScript we don't need to type optional properties or arguments as Option (e.g. `{ foo?: string }` so we try to unwrap the option.
// But in some situations this may conflict with TS type cheking, usually when we assing an Option ident directly to the field (e.g. `fun (i: int option) -> {| foo = i |})
// If we find problems we may need to disable this, or make sure somehow the values assigned to the fields are not `Some`.
let makeAbstractPropertyAnnotation com ctx typ =
let isOptional, typ =
match typ with
| Fable.Option(genArg, _) ->
if mustWrapOption genArg then
true, typ
else
true, genArg
| typ -> false, typ
isOptional, makeFieldAnnotation com ctx typ
let makeAnonymousRecordTypeAnnotation com ctx fieldNames fieldTypes : TypeAnnotation =
Seq.zip fieldNames fieldTypes
|> Seq.mapToArray (fun (name, typ) ->
let prop, isComputed = Util.memberFromName name
let isOptional, typ = makeAbstractPropertyAnnotation com ctx typ
AbstractMember.abstractProperty (prop, typ, isComputed = isComputed, isOptional = isOptional)
)
|> ObjectTypeAnnotation
let transformFunctionWithAnnotations
(com: IBabelCompiler)
ctx
name
typeParams
(args: Fable.Ident list)
(body: Fable.Expr)
=
if com.IsTypeScript then
let argTypes = args |> List.map (fun id -> id.Type)
let scopedTypeParams, genParams =
match typeParams with
| Some typeParams -> ctx.ScopedTypeParams, typeParams
| None -> Util.getTypeParameters ctx (argTypes @ [ body.Type ])
let ctx = { ctx with ScopedTypeParams = scopedTypeParams }
let args', body' = com.TransformFunction(ctx, name, args, body)
let returnType = makeTypeAnnotation com ctx body.Type
let typeParamDecl = makeTypeParamDecl com ctx genParams
args', body', Some returnType, Some typeParamDecl
else
let args', body' = com.TransformFunction(ctx, name, args, body)
args', body', None, None
module Util =
open Lib
open Reflection
open Annotation
module UnionHelpers =
[<Literal>]
let CASES_SUFFIX = "_$cases"