-
Notifications
You must be signed in to change notification settings - Fork 326
Expand file tree
/
Copy pathReplacements.fs
More file actions
4499 lines (4049 loc) · 195 KB
/
Copy pathReplacements.fs
File metadata and controls
4499 lines (4049 loc) · 195 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 Fable.Transforms.JS.Replacements
#nowarn "1182"
open System
open System.Text.RegularExpressions
open Fable
open Fable.AST
open Fable.AST.Fable
open Fable.Transforms
open Replacements.Util
[<return: Struct>]
let (|Floats|_|) =
function
| Float16
| Float32
| Float64 as kind -> ValueSome kind
| _ -> ValueNone
[<return: Struct>]
let (|Integers|_|) =
function
| Int8
| UInt8
| Int16
| UInt16
| Int32
| UInt32 as kind -> ValueSome kind
| _ -> ValueNone
[<return: Struct>]
let (|BigIntegers|_|) =
function
| Int64
| UInt64
| Int128
| UInt128
| NativeInt
| UNativeInt
| BigInt as kind -> ValueSome kind
| _ -> ValueNone
[<return: Struct>]
let (|Numbers|_|) =
function
| Integers kind -> ValueSome kind
| Floats kind -> ValueSome kind
| _ -> ValueNone
[<return: Struct>]
let (|TypedArrayCompatible|_|) (com: Compiler) (arrayKind: ArrayKind) t =
match arrayKind, t with
| ResizeArray, _ -> ValueNone
| _, Number(kind, _) when com.Options.TypedArrays ->
match kind with
| Int8 -> ValueSome "Int8Array"
| UInt8 when com.Options.ClampByteArrays -> ValueSome "Uint8ClampedArray"
| UInt8 -> ValueSome "Uint8Array"
| Int16 -> ValueSome "Int16Array"
| UInt16 -> ValueSome "Uint16Array"
| Int32 -> ValueSome "Int32Array"
| UInt32 -> ValueSome "Uint32Array"
| Int64 -> ValueSome "BigInt64Array"
| UInt64 -> ValueSome "BigUint64Array"
| Float32 -> ValueSome "Float32Array"
| Float64 -> ValueSome "Float64Array"
| Float16
| Int128
| UInt128
| NativeInt
| UNativeInt
| Decimal
| BigInt -> ValueNone
| _ -> ValueNone
let error com msg =
Helper.LibCall(com, "Util", "Exception", Any, [ msg ], isConstructor = true)
let coreModFor =
function
| BclGuid -> "Guid"
| BclDateTime -> "Date"
| BclDateTimeOffset -> "DateOffset"
| BclDateOnly -> "DateOnly"
| BclTimeOnly -> "TimeOnly"
| BclTimer -> "Timer"
| BclTimeSpan -> "TimeSpan"
| FSharpSet _ -> "Set"
| FSharpMap _ -> "Map"
| FSharpResult _ -> "Result"
| FSharpChoice _ -> "Choice"
| FSharpReference _ -> "Types"
| BclHashSet _ -> "MutableSet"
| BclDictionary _ -> "MutableMap"
| BclKeyValuePair _ -> FableError "Cannot decide core module" |> raise
let makeDecimal com r t (x: decimal) =
let str = x.ToString(System.Globalization.CultureInfo.InvariantCulture)
Helper.LibCall(com, "Decimal", "default", t, [ makeStrConst str ], isConstructor = true, ?loc = r)
let makeDecimalFromExpr com r t (e: Expr) =
Helper.LibCall(com, "Decimal", "default", t, [ e ], isConstructor = true, ?loc = r)
let createAtom com (value: Expr) =
let typ = value.Type
Helper.LibCall(com, "Util", "createAtom", typ, [ value ], [ typ ], genArgs = [ typ ])
let getRefCell com r typ (expr: Expr) = getFieldWith r typ expr "contents"
let setRefCell com r (expr: Expr) (value: Expr) =
setExpr r expr (makeStrConst "contents") value
let makeRefCell com r genArg args =
let typ = makeFSharpCoreType [ genArg ] Types.refCell
Helper.LibCall(com, "Types", "FSharpRef", typ, args, isConstructor = true, ?loc = r)
let makeRefCellFromValue com r (value: Expr) =
let typ = value.Type
makeRefCell com r typ [ value ]
let makeRefFromMutableValue com ctx r t (value: Expr) =
let getter = Delegate([], value, None, Tags.empty)
let setter =
let v = makeUniqueIdent com ctx t "v"
Delegate([ v ], Set(value, ValueSet, t, IdentExpr v, None), None, Tags.empty)
makeRefCell com r t [ getter; setter ]
let makeRefFromMutableField com ctx r t callee key =
let getter =
Delegate([], Get(callee, FieldInfo.Create(key, isMutable = true), t, r), None, Tags.empty)
let setter =
let v = makeUniqueIdent com ctx t "v"
Delegate([ v ], Set(callee, FieldSet(key), t, IdentExpr v, r), None, Tags.empty)
makeRefCell com r t [ getter; setter ]
// Mutable and public module values are compiled as functions, because
// values imported from ES2015 modules cannot be modified (see #986)
let makeRefFromMutableFunc com ctx r t (value: Expr) =
let getter =
let info = makeCallInfo None [] []
let value = makeCall r t info value
Delegate([], value, None, Tags.empty)
let setter =
let v = makeUniqueIdent com ctx t "v"
let args = [ IdentExpr v ]
let info = makeCallInfo None args [ t; Boolean ]
let value = makeCall r Unit info value
Delegate([ v ], value, None, Tags.empty)
makeRefCell com r t [ getter; setter ]
let getParseParams (kind: NumberKind) =
let isFloatOrDecimal, numberModule, unsigned, bitsize =
match kind with
| Int8 -> false, "Int32", false, 8
| UInt8 -> false, "Int32", true, 8
| Int16 -> false, "Int32", false, 16
| UInt16 -> false, "Int32", true, 16
| Int32 -> false, "Int32", false, 32
| UInt32 -> false, "Int32", true, 32
| Int64 -> false, "Long", false, 64
| UInt64 -> false, "Long", true, 64
| Float32 -> true, "Double", false, 32
| Float64 -> true, "Double", false, 64
| Decimal -> true, "Decimal", false, 128
| x -> FableError $"Unexpected kind in getParseParams: %A{x}" |> raise
isFloatOrDecimal, numberModule, unsigned, bitsize
let kindIndex kind = // 0 1 2 3 4 5 6 7 8 9 10 11
match kind with // i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 dec big
| Int8 -> 0 // 0 i8 - - - - + + + + - - - +
| Int16 -> 1 // 1 i16 + - - - + + + + - - - +
| Int32 -> 2 // 2 i32 + + - - + + + + - - - +
| Int64 -> 3 // 3 i64 + + + - + + + + - - - +
| UInt8 -> 4 // 4 u8 + + + + - - - - - - - +
| UInt16 -> 5 // 5 u16 + + + + + - - - - - - +
| UInt32 -> 6 // 6 u32 + + + + + + - - - - - +
| UInt64 -> 7 // 7 u64 + + + + + + + - - - - +
| Float32 -> 8 // 8 f32 + + + + + + + + - - - +
| Float64 -> 9 // 9 f64 + + + + + + + + - - - +
| Decimal -> 10 // 10 dec + + + + + + + + - - - +
| BigInt -> 11 // 11 big + + + + + + + + + + + -
| Float16 -> FableError "Casting to/from float16 is unsupported" |> raise
| Int128
| UInt128 -> FableError "Casting to/from (u)int128 is unsupported" |> raise
| NativeInt
| UNativeInt -> FableError "Casting to/from (u)nativeint is unsupported" |> raise
let needToCast fromKind toKind =
let v = kindIndex fromKind // argument type (vertical)
let h = kindIndex toKind // return type (horizontal)
((v > h) || (v < 4 && h > 3)) && (h < 8) || (h <> v && (h = 11 || v = 11))
/// Conversions to floating point
let toFloat com (ctx: Context) r targetType (args: Expr list) : Expr =
match args.Head.Type with
| Char -> Helper.InstanceCall(args.Head, "charCodeAt", Int32.Number, [ makeIntConst 0 ])
| String -> Helper.LibCall(com, "Double", "parse", targetType, args)
| Number(kind, _) ->
match kind with
| Decimal -> Helper.LibCall(com, "Decimal", "toFloat64", targetType, args)
| BigIntegers _ -> Helper.LibCall(com, "BigInt", "toFloat64", targetType, args)
| _ -> TypeCast(args.Head, targetType)
| _ ->
addWarning com ctx.InlinePath r "Cannot make conversion because source type is unknown"
TypeCast(args.Head, targetType)
let toDecimal com (ctx: Context) r targetType (args: Expr list) : Expr =
match args.Head.Type with
| Char ->
Helper.InstanceCall(args.Head, "charCodeAt", Int32.Number, [ makeIntConst 0 ])
|> makeDecimalFromExpr com r targetType
| String -> makeDecimalFromExpr com r targetType args.Head
| Number(kind, _) ->
match kind with
| Decimal -> args.Head
| BigIntegers _ -> Helper.LibCall(com, "BigInt", "toDecimal", targetType, args)
| _ -> makeDecimalFromExpr com r targetType args.Head
| _ ->
addWarning com ctx.InlinePath r "Cannot make conversion because source type is unknown"
TypeCast(args.Head, targetType)
// Apparently ~~ is faster than Math.floor (see https://coderwall.com/p/9b6ksa/is-faster-than-math-floor)
let fastIntFloor expr =
let inner = makeUnOp None Any expr UnaryNotBitwise
makeUnOp None (Int32.Number) inner UnaryNotBitwise
let stringToInt com (ctx: Context) r targetType (args: Expr list) : Expr =
let kind =
match targetType with
| Number(kind, _) -> kind
| x -> FableError $"Unexpected type in stringToInt: %A{x}" |> raise
let style = int System.Globalization.NumberStyles.Any
let _isFloatOrDecimal, numberModule, unsigned, bitsize = getParseParams kind
let parseArgs = [ makeIntConst style; makeBoolConst unsigned; makeIntConst bitsize ]
Helper.LibCall(com, numberModule, "parse", targetType, [ args.Head ] @ parseArgs @ args.Tail, ?loc = r)
let wrapLong com (ctx: Context) r t (arg: Expr) : Expr =
match t with
| Number(BigInt, _) -> arg
| Number(kind, _) ->
let toMeth = "to" + kind.ToString() + "_unchecked"
Helper.LibCall(com, "BigInt", toMeth, t, [ arg ])
| _ ->
addWarning com ctx.InlinePath r "Unexpected conversion to long"
TypeCast(arg, t)
let toLong com (ctx: Context) r targetType (args: Expr list) : Expr =
let sourceType = args.Head.Type
match sourceType, targetType with
| Char, _ ->
Helper.LibCall(com, "BigInt", "fromChar", targetType, args, ?loc = r)
|> wrapLong com ctx r targetType
| String, _ -> stringToInt com ctx r targetType args |> wrapLong com ctx r targetType
| Number(fromKind, _), Number(toKind, _) ->
match fromKind with
| BigInt ->
let toMeth = "to" + toKind.ToString()
Helper.LibCall(com, "BigInt", toMeth, targetType, args)
| Decimal ->
let toMeth = "to" + toKind.ToString()
Helper.LibCall(com, "Decimal", toMeth, targetType, args)
| _ ->
let fromMeth = "from" + fromKind.ToString()
Helper.LibCall(com, "BigInt", fromMeth, BigInt.Number, args, ?loc = r)
|> wrapLong com ctx r targetType
| _ ->
addWarning com ctx.InlinePath r "Cannot make conversion because source type is unknown"
TypeCast(args.Head, targetType)
let emitIntCast toKind arg =
match toKind with
| Int8 -> emitExpr None Int8.Number [ arg ] "($0 + 0x80 & 0xFF) - 0x80"
| Int16 -> emitExpr None Int16.Number [ arg ] "($0 + 0x8000 & 0xFFFF) - 0x8000"
| Int32 -> fastIntFloor arg
| UInt8 -> emitExpr None UInt8.Number [ arg ] "$0 & 0xFF"
| UInt16 -> emitExpr None UInt16.Number [ arg ] "$0 & 0xFFFF"
| UInt32 -> emitExpr None UInt32.Number [ arg ] "$0 >>> 0"
| _ -> FableError $"Unexpected non-integer type %A{toKind}" |> raise
/// Conversion to integers (excluding longs and bigints)
let toInt com (ctx: Context) r targetType (args: Expr list) =
let sourceType = args.Head.Type
match sourceType, targetType with
| Char, Number(toKind, _) ->
Helper.InstanceCall(args.Head, "charCodeAt", targetType, [ makeIntConst 0 ])
|> emitIntCast toKind
| String, _ -> stringToInt com ctx r targetType args
| Number(fromKind, _), Number(toKind, _) ->
if needToCast fromKind toKind then
match fromKind with
| BigInt ->
let toMeth = "to" + toKind.ToString()
Helper.LibCall(com, "BigInt", toMeth, targetType, args)
| BigIntegers _ ->
let toMeth = "to" + toKind.ToString() + "_unchecked"
Helper.LibCall(com, "BigInt", toMeth, targetType, args)
| Decimal ->
let toMeth = "to" + toKind.ToString()
Helper.LibCall(com, "Decimal", toMeth, targetType, args)
| _ -> args.Head
|> emitIntCast toKind
else
TypeCast(args.Head, targetType)
| _ ->
addWarning com ctx.InlinePath r "Cannot make conversion because source type is unknown"
TypeCast(args.Head, targetType)
let toChar com (ctx: Context) r (arg: Expr) =
match arg.Type with
| Char -> arg
| String -> TypeCast(arg, Char)
| Number(BigInt, _) -> Helper.LibCall(com, "BigInt", "toChar", Char, [ arg ], ?loc = r)
| Number(Decimal, _) -> Helper.LibCall(com, "Decimal", "toChar", Char, [ arg ], ?loc = r)
| _ ->
let code = toInt com ctx r UInt16.Number [ arg ]
Helper.GlobalCall("String", Char, [ code ], memb = "fromCharCode")
let toString com (ctx: Context) r (args: Expr list) =
match args with
| [] ->
"toString is called with empty args"
|> addErrorAndReturnNull com ctx.InlinePath r
| head :: tail ->
match head.Type with
| String -> head
| Char -> TypeCast(head, String)
| Builtin BclGuid when tail.IsEmpty -> head
| Builtin(BclGuid | BclTimeSpan | BclTimeOnly | BclDateOnly as bt) ->
Helper.LibCall(com, coreModFor bt, "toString", String, args)
| Number(Int16, _) -> Helper.LibCall(com, "Util", "int16ToString", String, args)
| Number(Int32, _) -> Helper.LibCall(com, "Util", "int32ToString", String, args)
| Number(Int64, _) -> Helper.LibCall(com, "Util", "int64ToString", String, args)
| Number(NativeInt, _) -> Helper.LibCall(com, "Util", "int64ToString", String, args)
| Number(BigInt, _) -> Helper.LibCall(com, "BigInt", "toString", String, args)
| Number(Decimal, _) -> Helper.LibCall(com, "Decimal", "toString", String, args)
| Number _ -> Helper.InstanceCall(head, "toString", String, tail)
| Array _
| List _ -> Helper.LibCall(com, "Types", "seqToString", String, [ head ], ?loc = r)
// | DeclaredType(ent, _) when ent.IsFSharpUnion || ent.IsFSharpRecord || ent.IsValueType ->
// Helper.InstanceCall(head, "toString", String, [], ?loc=r)
// | DeclaredType(ent, _) ->
| _ -> Helper.LibCall(com, "Types", "toString", String, [ head ], ?loc = r)
let round com (args: Expr list) =
match args.Head.Type with
| Number(Decimal, _) ->
let rounded = Helper.LibCall(com, "Decimal", "round", Decimal.Number, [ args.Head ])
rounded :: args.Tail
| Number(Floats _, _) ->
let rounded = Helper.LibCall(com, "Util", "round", Float64.Number, [ args.Head ])
rounded :: args.Tail
| _ -> args
let toList com returnType expr =
Helper.LibCall(com, "List", "ofSeq", returnType, [ expr ])
let stringToCharArray e =
Helper.InstanceCall(e, "split", Array(Char, MutableArray), [ makeStrConst "" ])
let applyOp (com: ICompiler) (ctx: Context) r t opName (args: Expr list) =
let unOp operator operand =
Operation(Unary(operator, operand), Tags.empty, t, r)
let binOp op left right =
Operation(Binary(op, left, right), Tags.empty, t, r)
let binOpChar op left right =
let toUInt16 e = toInt com ctx None UInt16.Number [ e ]
Operation(Binary(op, toUInt16 left, toUInt16 right), Tags.empty, UInt16.Number, r)
|> toChar com ctx r
let truncateUnsigned operation = // see #1550
match t with
| Number(UInt32, _) -> Operation(Binary(BinaryShiftRightZeroFill, operation, makeIntConst 0), Tags.empty, t, r)
| _ -> operation
let logicOp op left right =
Operation(Logical(op, left, right), Tags.empty, Boolean, r)
let nativeOp opName argTypes args =
match opName, args with
| Operators.addition, [ left; right ] ->
match argTypes with
| Char :: _ -> binOpChar BinaryPlus left right
| _ -> binOp BinaryPlus left right
| Operators.subtraction, [ left; right ] ->
match argTypes with
| Char :: _ -> binOpChar BinaryMinus left right
| _ -> binOp BinaryMinus left right
| Operators.multiply, [ left; right ] -> binOp BinaryMultiply left right
| (Operators.division | Operators.divideByInt), [ left; right ] ->
match argTypes with
// Floor result of integer divisions (see #172)
| Number(Integers _, _) :: _ -> binOp BinaryDivide left right |> fastIntFloor
| _ -> binOp BinaryDivide left right
| Operators.modulus, [ left; right ] -> binOp BinaryModulus left right
| Operators.leftShift, [ left; right ] -> binOp BinaryShiftLeft left right |> truncateUnsigned // See #1530
| Operators.rightShift, [ left; right ] ->
match argTypes with
| Number(UInt32, _) :: _ -> binOp BinaryShiftRightZeroFill left right // See #646
| _ -> binOp BinaryShiftRightSignPropagating left right
| Operators.bitwiseAnd, [ left; right ] -> binOp BinaryAndBitwise left right |> truncateUnsigned
| Operators.bitwiseOr, [ left; right ] -> binOp BinaryOrBitwise left right |> truncateUnsigned
| Operators.exclusiveOr, [ left; right ] -> binOp BinaryXorBitwise left right |> truncateUnsigned
| Operators.booleanAnd, [ left; right ] -> logicOp LogicalAnd left right
| Operators.booleanOr, [ left; right ] -> logicOp LogicalOr left right
| Operators.logicalNot, [ operand ] -> unOp UnaryNotBitwise operand |> truncateUnsigned
| Operators.unaryNegation, [ operand ] ->
match argTypes with
| Number(Int8, _) :: _ -> Helper.LibCall(com, "Int32", "op_UnaryNegation_Int8", t, args, ?loc = r)
| Number(Int16, _) :: _ -> Helper.LibCall(com, "Int32", "op_UnaryNegation_Int16", t, args, ?loc = r)
| Number(Int32, _) :: _ -> Helper.LibCall(com, "Int32", "op_UnaryNegation_Int32", t, args, ?loc = r)
| _ -> unOp UnaryMinus operand
| Operators.unaryPlus, [ operand ] -> unOp UnaryPlus operand
| _ ->
$"Operator %s{opName} not found in %A{argTypes}"
|> addErrorAndReturnNull com ctx.InlinePath r
let argTypes = args |> List.map (fun a -> a.Type)
match argTypes with
| Number(Decimal, _) :: _ ->
let opName =
if opName = Operators.divideByInt then
Operators.division
else
opName
Helper.LibCall(com, "Decimal", opName, t, args, argTypes, ?loc = r)
| Number(BigIntegers kind, _) :: _ ->
let op = Helper.LibCall(com, "BigInt", opName, t, args, argTypes, ?loc = r)
if kind = BigInt then
op
else
wrapLong com ctx r t op
| Builtin(BclDateTime | BclDateTimeOffset | BclDateOnly as bt) :: _ ->
Helper.LibCall(com, coreModFor bt, opName, t, args, argTypes, ?loc = r)
| Builtin(FSharpSet _) :: _ ->
let mangledName = Naming.buildNameWithoutSanitationFrom "FSharpSet" true opName ""
Helper.LibCall(com, "Set", mangledName, t, args, argTypes, ?loc = r)
// | Builtin (FSharpMap _)::_ ->
// let mangledName = Naming.buildNameWithoutSanitationFrom "FSharpMap" true opName overloadSuffix.Value
// Helper.LibCall(com, "Map", mangledName, t, args, argTypes, ?loc=r)
| Builtin BclTimeSpan :: _ -> nativeOp opName argTypes args
| CustomOp com ctx r t opName args e -> e
| _ -> nativeOp opName argTypes args
let isCompatibleWithNativeComparison =
function
| Builtin(BclGuid | BclTimeSpan | BclTimeOnly)
| Boolean
| Char
| String
| Number(Numbers _, _) -> true
// TODO: Non-record/union declared types without custom equality
// should be compatible with JS comparison
| _ -> false
// Overview of hash rules:
// * `hash`, `Unchecked.hash` first check if GetHashCode is implemented and then default to structural hash.
// * `.GetHashCode` called directly defaults to identity hash (for reference types except string) if not implemented.
// * `LanguagePrimitive.PhysicalHash` creates an identity hash no matter whether GetHashCode is implemented or not.
let identityHash com r (arg: Expr) =
let methodName =
match arg.Type with
// These are the same for identity/structural hashing
| Char
| String
| Builtin BclGuid -> "stringHash"
| Number(Decimal, _) -> "safeHash"
| Number(BigIntegers _, _) -> "bigintHash"
| Number(Numbers _, _) -> "numberHash"
| Builtin BclTimeSpan
| Builtin BclTimeOnly -> "numberHash"
| List _ -> "safeHash"
| Tuple _ -> "arrayHash" // F# tuples must use structural hashing
// These are only used for structural hashing
// | Array _ -> "arrayHash"
// | Builtin (BclDateTime|BclDateTimeOffset) -> "dateHash"
| DeclaredType _ -> "safeHash"
| _ -> "identityHash"
Helper.LibCall(com, "Util", methodName, Int32.Number, [ arg ], ?loc = r)
let structuralHash (com: ICompiler) r (arg: Expr) =
let methodName =
match arg.Type with
| Char
| String
| Builtin BclGuid -> "stringHash"
| Number(Decimal, _) -> "fastStructuralHash"
| Number(BigIntegers _, _) -> "bigintHash"
| Number(Numbers _, _) -> "numberHash"
| Builtin BclTimeSpan
| Builtin BclTimeOnly -> "numberHash"
| List _ -> "safeHash"
// TODO: Get hash functions of the generic arguments
// for better performance when using tuples as map keys
| Tuple _
| Array _ -> "arrayHash"
| Builtin(BclDateTime | BclDateTimeOffset | BclDateOnly) -> "dateHash"
| DeclaredType(ent, _) ->
let ent = com.GetEntity(ent)
if not ent.IsInterface then
"safeHash"
else
"structuralHash"
| _ -> "structuralHash"
Helper.LibCall(com, "Util", methodName, Int32.Number, [ arg ], ?loc = r)
let rec equals (com: ICompiler) ctx r equal (left: Expr) (right: Expr) =
let is equal expr =
if equal then
expr
else
makeUnOp None Boolean expr UnaryNot
match left.Type with
| Number(Decimal, _) ->
Helper.LibCall(com, "Decimal", "equals", Boolean, [ left; right ], ?loc = r)
|> is equal
| Number(BigIntegers _, _) ->
Helper.LibCall(com, "BigInt", "equals", Boolean, [ left; right ], ?loc = r)
|> is equal
| Builtin(BclGuid | BclTimeSpan | BclTimeOnly)
| Boolean
| Char
| String
| Number _
| Nullable _
| MetaType ->
if equal then
makeBinOp r Boolean left right BinaryEqual
else
makeBinOp r Boolean left right BinaryUnequal
// Use BinaryEquals for MetaType to have a change of optimization in FableTransforms.operationReduction
// We will call Reflection.equals in the Fable2Babel step
//| MetaType -> Helper.LibCall(com, "Reflection", "equals", Boolean, [left; right], ?loc=r) |> is equal
| Builtin(BclDateTime | BclDateTimeOffset | BclDateOnly) ->
Helper.LibCall(com, "Date", "equals", Boolean, [ left; right ], ?loc = r)
|> is equal
| Builtin(FSharpSet _ | FSharpMap _) -> Helper.InstanceCall(left, "Equals", Boolean, [ right ]) |> is equal
| DeclaredType _ ->
Helper.LibCall(com, "Util", "equals", Boolean, [ left; right ], ?loc = r)
|> is equal
| Array(_, ResizeArray) ->
// ResizeArray (System.Collections.Generic.List) uses reference equality in .NET, see #3718
if equal then
makeBinOp r Boolean left right BinaryEqual
else
makeBinOp r Boolean left right BinaryUnequal
| Array(t, _) ->
let f = makeEqualityFunction com ctx t
Helper.LibCall(com, "Array", "equalsWith", Boolean, [ f; left; right ], ?loc = r)
|> is equal
| List _ ->
Helper.LibCall(com, "Util", "equals", Boolean, [ left; right ], ?loc = r)
|> is equal
| Tuple _ ->
Helper.LibCall(com, "Util", "equalArrays", Boolean, [ left; right ], ?loc = r)
|> is equal
| _ ->
Helper.LibCall(com, "Util", "equals", Boolean, [ left; right ], ?loc = r)
|> is equal
/// Compare function that will call Util.compare or instance `CompareTo` as appropriate
and compare (com: ICompiler) ctx r (left: Expr) (right: Expr) =
let t = Int32.Number
match left.Type with
| Number(Decimal, _) -> Helper.LibCall(com, "Decimal", "compare", t, [ left; right ], ?loc = r)
| Number(BigIntegers _, _) -> Helper.LibCall(com, "BigInt", "compare", t, [ left; right ], ?loc = r)
| Builtin(BclGuid | BclTimeSpan | BclTimeOnly)
| Boolean
| Char
| String
| Number _ -> Helper.LibCall(com, "Util", "comparePrimitives", t, [ left; right ], ?loc = r)
| Builtin(BclDateTime | BclDateTimeOffset | BclDateOnly) ->
Helper.LibCall(com, "Date", "compare", t, [ left; right ], ?loc = r)
| DeclaredType _ -> Helper.LibCall(com, "Util", "compare", t, [ left; right ], ?loc = r)
| Array(t, _) ->
let f = makeComparerFunction com ctx t
// Note Array.compareWith doesn't check the length first, see #2961
Helper.LibCall(com, "Array", "compareTo", t, [ f; left; right ], ?loc = r)
| List _ -> Helper.LibCall(com, "Util", "compare", t, [ left; right ], ?loc = r)
| Tuple _ -> Helper.LibCall(com, "Util", "compareArrays", t, [ left; right ], ?loc = r)
| _ -> Helper.LibCall(com, "Util", "compare", t, [ left; right ], ?loc = r)
/// Boolean comparison operators like <, >, <=, >=
and booleanCompare (com: ICompiler) ctx r (left: Expr) (right: Expr) op =
if isCompatibleWithNativeComparison left.Type then
makeEqOp r left right op
else
let comparison = compare com ctx r left right
makeEqOp r comparison (makeIntConst 0) op
and makeComparerFunction (com: ICompiler) ctx typArg =
let x = makeUniqueIdent com ctx typArg "x"
let y = makeUniqueIdent com ctx typArg "y"
let body = compare com ctx None (IdentExpr x) (IdentExpr y)
Delegate([ x; y ], body, None, Tags.empty)
and makeComparer (com: ICompiler) ctx typArg =
objExpr [ "Compare", makeComparerFunction com ctx typArg ]
and makeEqualityFunction (com: ICompiler) ctx typArg =
let x = makeUniqueIdent com ctx typArg "x"
let y = makeUniqueIdent com ctx typArg "y"
let body = equals com ctx None true (IdentExpr x) (IdentExpr y)
Delegate([ x; y ], body, None, Tags.empty)
let makeEqualityComparer (com: ICompiler) ctx typArg =
let x = makeUniqueIdent com ctx typArg "x"
let y = makeUniqueIdent com ctx typArg "y"
objExpr
[
"Equals", Delegate([ x; y ], equals com ctx None true (IdentExpr x) (IdentExpr y), None, Tags.empty)
"GetHashCode", Delegate([ x ], structuralHash com None (IdentExpr x), None, Tags.empty)
]
// TODO: Try to detect at compile-time if the object already implements `Compare`?
let inline makeComparerFromEqualityComparer e = e // leave it as is, if implementation supports it
// Helper.LibCall(com, "Util", "comparerFromEqualityComparer", Any, [e])
/// Adds comparer as last argument for set creator methods
let makeSet (com: ICompiler) ctx r t methName args genArg =
let args = args @ [ makeComparer com ctx genArg ]
Helper.LibCall(com, "Set", Naming.lowerFirst methName, t, args, ?loc = r)
/// Adds comparer as last argument for map creator methods
let makeMap (com: ICompiler) ctx r t methName args genArg =
let args = args @ [ makeComparer com ctx genArg ]
Helper.LibCall(com, "Map", Naming.lowerFirst methName, t, args, ?loc = r)
let makeDictionaryWithComparer com r t sourceSeq comparer =
Helper.LibCall(com, "MutableMap", "Dictionary", t, [ sourceSeq; comparer ], isConstructor = true, ?loc = r)
let makeDictionary (com: ICompiler) ctx r t sourceSeq =
match t with
| DeclaredType(_, [ key; _ ]) when not (isCompatibleWithNativeComparison key) ->
// makeComparer com ctx key
makeEqualityComparer com ctx key |> makeDictionaryWithComparer com r t sourceSeq
| _ -> Helper.GlobalCall("Map", t, [ sourceSeq ], isConstructor = true, ?loc = r)
let makeHashSetWithComparer com r t sourceSeq comparer =
Helper.LibCall(com, "MutableSet", "HashSet", t, [ sourceSeq; comparer ], isConstructor = true, ?loc = r)
let makeHashSet (com: ICompiler) ctx r t sourceSeq =
match t with
| DeclaredType(_, [ key ]) when not (isCompatibleWithNativeComparison key) ->
// makeComparer com ctx key
makeEqualityComparer com ctx key |> makeHashSetWithComparer com r t sourceSeq
| _ -> Helper.GlobalCall("Set", t, [ sourceSeq ], isConstructor = true, ?loc = r)
let tryEntityIdent (com: Compiler) entFullName =
match entFullName with
| BuiltinDefinition BclDateOnly
| BuiltinDefinition BclDateTime
| BuiltinDefinition BclDateTimeOffset -> makeIdentExpr "Date" |> Some
| BuiltinDefinition BclTimer -> makeImportLib com Any "default" "Timer" |> Some
| BuiltinDefinition(FSharpReference _) -> makeImportLib com Any "FSharpRef" "Types" |> Some
| BuiltinDefinition(FSharpResult _) -> makeImportLib com Any "FSharpResult$2" "Result" |> Some
| BuiltinDefinition(FSharpChoice genArgs) ->
let membName = $"FSharpChoice$%d{List.length genArgs}"
makeImportLib com Any membName "Choice" |> Some
// | BuiltinDefinition BclGuid -> jsTypeof "string" expr
// | BuiltinDefinition BclTimeSpan -> jsTypeof "number" expr
// | BuiltinDefinition BclHashSet _ -> fail "MutableSet" // TODO:
// | BuiltinDefinition BclDictionary _ -> fail "MutableMap" // TODO:
// | BuiltinDefinition BclKeyValuePair _ -> fail "KeyValuePair" // TODO:
// | BuiltinDefinition FSharpSet _ -> fail "Set" // TODO:
// | BuiltinDefinition FSharpMap _ -> fail "Map" // TODO:
| Types.matchFail -> makeImportLib com Any "MatchFailureException" "Types" |> Some
| Types.exception_ -> makeImportLib com Any "Exception" "Util" |> Some
| "System.OperationCanceledException" -> makeImportLib com Any "OperationCanceledException" "AsyncBuilder" |> Some
| "System.Collections.Generic.KeyNotFoundException" ->
makeImportLib com Any "KeyNotFoundException" "System.Collections.Generic"
|> Some
| BuiltinSystemException entName -> makeImportLib com Any entName "System" |> Some
// | Naming.EndsWith "Exception" _ -> makeImportLib com Any "Exception" "Util" |> Some
| Types.attribute -> makeImportLib com Any "Attribute" "Types" |> Some
| "System.Uri" -> makeImportLib com Any "Uri" "Uri" |> Some
| "Microsoft.FSharp.Control.FSharpAsyncReplyChannel`1" ->
makeImportLib com Any "AsyncReplyChannel" "AsyncBuilder" |> Some
| "Microsoft.FSharp.Control.FSharpEvent`1" -> makeImportLib com Any "Event" "Event" |> Some
| "Microsoft.FSharp.Control.FSharpEvent`2" -> makeImportLib com Any "Event$2" "Event" |> Some
| "Microsoft.FSharp.Core.CompilerServices.ListCollector`1" ->
makeImportLib com Any "ListCollector$1" "FSharp.Core.CompilerServices" |> Some
| _ -> None
let tryConstructor com (ent: Entity) =
if FSharp2Fable.Util.isReplacementCandidate ent.Ref then
tryEntityIdent com ent.FullName
else
FSharp2Fable.Util.tryEntityIdentMaybeGlobalOrImported com ent
let constructor com ent =
match tryConstructor com ent with
| Some e -> e
| None -> $"Cannot find %s{ent.FullName} constructor" |> addErrorAndReturnNull com [] None
/// For user-defined value types (structs), returns a constructor call initialized with
/// a zero value for each instance field. Only instance fields are constructor parameters;
/// static fields (from `static let` bindings) are excluded to avoid deep recursion through
/// static field type graphs. Returns None if no constructor is available or the type is
/// not a value type.
let rec private tryZeroValueTypeConstructor (com: ICompiler) (ctx: Context) (t: Type) (ent: Entity) =
if ent.IsValueType then
tryConstructor com ent
|> Option.map (fun e ->
let args =
ent.FSharpFields
|> List.choose (fun f ->
if f.IsStatic then
None
else
getZero com ctx f.FieldType |> Some
)
Helper.ConstructorCall(e, t, args)
)
else
None
and private getZero (com: ICompiler) (ctx: Context) (t: Type) =
match t with
| Boolean -> makeBoolConst false
| Char -> makeCharConst '\000'
| String -> makeStrConst "" // TODO: Use null for string?
| Number(kind, uom) -> NumberConstant(NumberValue.GetZero kind, uom) |> makeValue None
| Builtin(BclTimeSpan | BclTimeOnly) -> TypeCast(makeIntConst 0, t)
| Builtin BclDateTime as t -> Helper.LibCall(com, "Date", "minValue", t, [])
| Builtin BclDateTimeOffset as t -> Helper.LibCall(com, "DateOffset", "minValue", t, [])
| Builtin BclDateOnly as t -> Helper.LibCall(com, "DateOnly", "minValue", t, [])
| Builtin(FSharpSet genArg) as t -> makeSet com ctx None t "Empty" [] genArg
| Builtin(BclKeyValuePair(k, v)) -> makeTuple None true [ getZero com ctx k; getZero com ctx v ]
| ListSingleton(CustomOp com ctx None t "get_Zero" [] e) -> e
| DeclaredType(entRef, _) ->
com.GetEntity(entRef)
|> tryZeroValueTypeConstructor com ctx t
|> Option.defaultValue (Value(Null Any, None)) // null
| _ -> Value(Null Any, None) // null
let getOne (com: ICompiler) (ctx: Context) (t: Type) =
match t with
| Boolean -> makeBoolConst true
| Number(kind, uom) -> NumberConstant(NumberValue.GetOne kind, uom) |> makeValue None
| ListSingleton(CustomOp com ctx None t "get_One" [] e) -> e
| _ -> makeIntConst 1
let makeAddFunction (com: ICompiler) ctx t =
let x = makeUniqueIdent com ctx t "x"
let y = makeUniqueIdent com ctx t "y"
let body = applyOp com ctx None t Operators.addition [ IdentExpr x; IdentExpr y ]
Delegate([ x; y ], body, None, Tags.empty)
let makeGenericAdder (com: ICompiler) ctx t =
objExpr
[
"GetZero", getZero com ctx t |> makeDelegate []
"Add", makeAddFunction com ctx t
]
let makeGenericAverager (com: ICompiler) ctx t =
let divideFn =
let x = makeUniqueIdent com ctx t "x"
let i = makeUniqueIdent com ctx (Int32.Number) "i"
let body = applyOp com ctx None t Operators.divideByInt [ IdentExpr x; IdentExpr i ]
Delegate([ x; i ], body, None, Tags.empty)
objExpr
[
"GetZero", getZero com ctx t |> makeDelegate []
"Add", makeAddFunction com ctx t
"DivideByInt", divideFn
]
// The code below is not functional because I was not able to make a clean implementation
// of it using functional approach.
// I believe this is not an issue because the code is more readable than all my functional attempts.
type private MakePojoFromLambdaItem =
| Property of string * Expr
| Object of MakePojoFromLambdaContext
and private MakePojoFromLambdaContext(segment: string) =
// We can't use ResizeArray alias here because it also exist in Fable AST
member val Children = Collections.Generic.List<MakePojoFromLambdaItem>()
member val Segment = segment
member this.AddChildAt(segments: string list, property: string * Expr) =
let rec add (path: string list) (newProperty: string * Expr) (current: MakePojoFromLambdaContext) =
match path with
| [] -> current.Children.Add(Property(newProperty))
| head :: tailPath ->
let child =
let existingObject =
current.Children
|> Seq.tryFind (fun c ->
match c with
| Object b -> b.Segment = head
| _ -> false
)
match existingObject with
| Some(Object c) -> c
| None ->
let newChild = MakePojoFromLambdaContext(head)
current.Children.Add(Object(newChild))
newChild
| _ -> failwith "Should not happen, as 'Some' case can only be an Object at this point"
add tailPath newProperty child
add segments property this
this
let makePojoFromLambda com (arg: Expr) =
let rec flattenSequential =
function
| Sequential statements -> List.collect flattenSequential statements
| e -> [ e ]
let typ, genArgs =
match arg.Type with
| LambdaType(argType, _) -> argType, Some [ argType ]
| _ -> Any, None
match arg with
| Lambda(_, lambdaBody, _) ->
let flattened = flattenSequential lambdaBody
let rec groupByGetter (acc: MakePojoFromLambdaContext) (body: Expr list) =
match body with
| [] -> acc
| head :: tail ->
match head with
| Set(IdentExpr _, FieldSet(fieldName), _, value, _) ->
let updatedAcc = acc.AddChildAt([], (fieldName, value))
groupByGetter updatedAcc tail
| Set(Get _ as getExpr, FieldSet(fieldName), _, value, _) ->
let rec getGetterSegments (acc: string list) (expr: Expr) =
match expr with
| Get(IdentExpr _, FieldGet(name), _, _) -> name.Name :: acc
| Get(expr, FieldGet(name), _, _) -> getGetterSegments (name.Name :: acc) expr
| _ -> acc
let updatedAcc =
let getterSegments = getGetterSegments [] getExpr
acc.AddChildAt(getterSegments, (fieldName, value))
// This is a nested property
groupByGetter updatedAcc tail
// Assigning to a non-property interface member (a plain abstract method
// declared without `with get, set`) is invalid F#: the compiler rejects it
// with `FS0971: Undefined value 'copyOfStruct'`. Fable's FCS fork doesn't
// surface that diagnostic, instead handing us the address of a throwaway
// local (`©OfStruct`) compiled as `let addr = FSharpRef(...) in addr.contents <- value`.
| Let(addrIdent,
Call(Import(importInfo, _, _), callInfo, _, _),
Set(IdentExpr setIdent, ExprSet _, _, _, r)) when
importInfo.Selector = "FSharpRef"
&& List.contains "new" callInfo.Tags
&& setIdent.Name = addrIdent.Name
->
"Cannot set a non-property member in 'jsOptions'. Declare the interface member as a settable property, e.g. `abstract X: T with get, set`."
|> addError com [] r
groupByGetter acc tail
| _ -> groupByGetter acc tail
let root = groupByGetter (MakePojoFromLambdaContext("/")) flattened
let rec mapToExpression (node: MakePojoFromLambdaItem) =
match node with
| Property(name, value) -> objValue (name, value)
| Object b ->
let mappedChildren = b.Children |> Seq.map mapToExpression |> Seq.toList
objValue (b.Segment, ObjectExpr(mappedChildren, Any, None))
// Note: If the user mix nested getter and jsOptions then the last one will bein effect
// We could try to generate a warning/error in this case but it seems complicated for little gain
if root.Children.Count = 0 then
None
else
root.Children |> Seq.map mapToExpression |> Seq.toList |> Some
| _ -> None
|> Option.map (fun members -> ObjectExpr(members, typ, None))
|> Option.defaultWith (fun () ->
// TODO: Do we want to support nested getters here too?
// This could be complex because here the user can mix any code
// so it can be difficult to detect the pattern we want
Helper.LibCall(com, "Util", "jsOptions", typ, [ arg ], ?genArgs = genArgs)
)
let makePojo (com: Compiler) caseRule keyValueList =
let makeObjMember caseRule name values =
let value =
match values with
| [] -> makeBoolConst true
| [ value ] -> value
| values -> Value(NewArray(ArrayValues values, Any, MutableArray), None)
objValue (Naming.applyCaseRule caseRule name, value)
// let rec findKeyValueList scope identName =
// match scope with
// | [] -> None
// | (_,ident2,expr)::prevScope ->
// if identName = ident2.Name then
// match expr with
// | Some(ArrayOrListLiteral(kvs,_)) -> Some kvs
// | Some(MaybeCasted(IdentExpr ident)) -> findKeyValueList prevScope ident.Name
// | _ -> None
// else findKeyValueList prevScope identName
let caseRule =
match caseRule with
| Some(NumberConst(NumberValue.Int32 rule, _)) -> Some rule
| _ -> None
|> Option.map enum
|> Option.defaultValue Fable.Core.CaseRules.None
match keyValueList with
| ArrayOrListLiteral(kvs, _) -> Some kvs
// | MaybeCasted(IdentExpr ident) -> findKeyValueList ctx.Scope ident.Name
| _ -> None
|> Option.bind (fun kvs ->
(kvs, Some [])
||> List.foldBack (fun m acc ->
match acc, m with
// Try to get the member key and value at compile time for unions and tuples
| Some acc, MaybeCasted(Value(NewUnion(values, uci, ent, _), _)) ->
let uci = com.GetEntity(ent).UnionCases |> List.item uci
let name = defaultArg uci.CompiledName uci.Name
makeObjMember caseRule name values :: acc |> Some
| Some acc, MaybeCasted(Value(NewTuple((StringConst name) :: values, _), _)) ->
match values with
| [ MaybeCasted(Value(NewOption(None, _, _), _)) ] -> Some acc
| values ->
// Don't change the case for tuples in disguise
makeObjMember Core.CaseRules.None name values :: acc |> Some
| _ -> None
)
)
|> Option.map (fun members -> ObjectExpr(members, Any, None))
let injectArg (com: ICompiler) (ctx: Context) r moduleName methName (genArgs: Type list) args =
let injectArgInner args (injectType, injectGenArgIndex) =
let fail () =
$"Cannot inject arg to %s{moduleName}.%s{methName} (genArgs %A{genArgs} - expected index %i{injectGenArgIndex})"
|> addError com ctx.InlinePath r
args
match List.tryItem injectGenArgIndex genArgs with
| None -> fail ()
| Some genArg ->
match injectType with
| Types.icomparerGeneric -> args @ [ makeComparer com ctx genArg ]