-
Notifications
You must be signed in to change notification settings - Fork 328
Expand file tree
/
Copy pathReplacements.fs
More file actions
4199 lines (3811 loc) · 172 KB
/
Copy pathReplacements.fs
File metadata and controls
4199 lines (3811 loc) · 172 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.Dart.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 (|DartInt|_|) =
function
| Int8
| UInt8
| Int16
| UInt16
| Int32
| UInt32
| Int64
| UInt64 -> ValueSome DartInt
| _ -> ValueNone
[<return: Struct>]
let (|DartDouble|_|) =
function
| Float32
| Float64 -> ValueSome DartDouble
| _ -> ValueNone
let error com msg =
let e = makeImportLib com Any "ExceptionBase" "Types"
Helper.ConstructorCall(e, Any, [ msg ])
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 makeLongInt com r t signed (x: uint64) =
let lowBits =
NumberConstant(NumberValue.Float64(float (uint32 x)), NumberInfo.Empty)
let highBits =
NumberConstant(NumberValue.Float64(float (x >>> 32)), NumberInfo.Empty)
let unsigned = BoolConstant(not signed)
let args =
[ makeValue None lowBits; makeValue None highBits; makeValue None unsigned ]
Helper.LibCall(com, "Long", "fromBits", t, args, ?loc = r)
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)
// TODO: Split into make decimal from int/char and from double
let makeDecimalFromExpr com r t (e: Expr) =
Helper.LibCall(com, "Decimal", "default", t, [ e ], isConstructor = true, ?loc = r)
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
| Int128 -> false, "Int32", false, 64 //128
| UInt128 -> false, "Int32", true, 64 //128
| Float16 -> true, "Double", false, 32 //16
| 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 castBigIntMethod typeTo =
match typeTo with
| Number(kind, _) ->
match kind with
| Int8 -> "toSByte"
| Int16 -> "toInt16"
| Int32 -> "toInt32"
| Int64 -> "toInt64"
| UInt8 -> "toByte"
| UInt16 -> "toUInt16"
| UInt32 -> "toUInt32"
| UInt64 -> "toUInt64"
| Float32 -> "toSingle"
| Float64 -> "toDouble"
| Decimal -> "toDecimal"
| Int128
| UInt128
| Float16
| BigInt
| NativeInt
| UNativeInt -> FableError $"Unexpected BigInt/%A{kind} conversion" |> raise
| _ -> FableError $"Unexpected non-number type %A{typeTo}" |> raise
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))
let stringToDouble (_com: ICompiler) (_ctx: Context) r targetType (args: Expr list) : Expr =
Helper.GlobalCall("double", targetType, args, memb = "parse", ?loc = r)
/// Conversions to floating point
let toFloat com (ctx: Context) r targetType (args: Expr list) : Expr =
let arg = args.Head
match arg.Type with
| Char -> Helper.InstanceCall(arg, "toDouble", targetType, [])
| String -> stringToDouble com ctx r targetType args
| Number(kind, _) ->
match kind with
| BigInt -> Helper.LibCall(com, "BigInt", castBigIntMethod targetType, targetType, args)
| Decimal -> Helper.LibCall(com, "Decimal", "toNumber", targetType, args)
| DartDouble -> arg
| _ -> Helper.InstanceCall(arg, "toDouble", targetType, [])
| _ ->
addWarning com ctx.InlinePath r "Cannot make conversion because source type is unknown"
TypeCast(arg, targetType)
let toDecimal com (ctx: Context) r targetType (args: Expr list) : Expr =
match args.Head.Type with
| Char -> makeDecimalFromExpr com r targetType args.Head
| String -> makeDecimalFromExpr com r targetType args.Head
| Number(kind, _) ->
match kind with
| Decimal -> args.Head
| BigInt -> Helper.LibCall(com, "BigInt", castBigIntMethod targetType, 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: ICompiler) (_ctx: Context) r targetType (args: Expr list) : Expr =
Helper.GlobalCall("int", targetType, args, memb = "parse", ?loc = r)
// 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)
/// Conversion to integers (excluding longs and bigints)
let toInt com (ctx: Context) r targetType (args: Expr list) =
let arg = args.Head
// TODO: Review this and include Int64
let emitCast typeTo arg = arg
// match typeTo 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{typeTo}" |> raise
match arg.Type, targetType with
| Char, Number(typeTo, _) -> emitCast typeTo arg
| String, _ -> stringToInt com ctx r targetType args
| Number(BigInt, _), _ -> Helper.LibCall(com, "BigInt", castBigIntMethod targetType, targetType, args)
| Number(typeFrom, _), Number(typeTo, _) ->
if needToCast typeFrom typeTo then
match typeFrom with
| Decimal -> Helper.LibCall(com, "Decimal", "toNumber", targetType, args) |> emitCast typeTo
| DartInt -> arg |> emitCast typeTo
| _ -> Helper.InstanceCall(arg, "toInt", targetType, [])
else
TypeCast(arg, targetType)
| _ ->
addWarning com ctx.InlinePath r "Cannot make conversion because source type is unknown"
TypeCast(arg, targetType)
let toChar com (ctx: Context) r (arg: Expr) =
match arg.Type with
// TODO: Check length
| Char -> arg
| String -> Helper.InstanceCall(arg, "codeUnitAt", Char, [ makeIntConst 0 ])
| _ -> TypeCast(arg, Char)
let charToString =
function
| Value(CharConstant v, r) -> Value(StringConstant(string<char> v), r)
| e -> Helper.GlobalCall("String", String, [ e ], 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 -> charToString head
// | 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|UInt64),_) -> Helper.LibCall(com, "Long", "toString", String, args)
// | Number(BigInt,_) -> Helper.LibCall(com, "BigInt", "toString", String, args)
// | Number(Decimal,_) -> Helper.LibCall(com, "Decimal", "toString", String, args)
| _ -> Helper.InstanceCall(head, "toString", String, tail)
let round com (args: Expr list) =
match args.Head.Type with
| Number(Decimal, _) ->
let n = Helper.LibCall(com, "Decimal", "toNumber", Float64.Number, [ args.Head ])
let rounded = Helper.LibCall(com, "Util", "round", Float64.Number, [ n ])
rounded :: args.Tail
| Number((Float32 | Float64), _) ->
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 =
let t = Array(Char, ImmutableArray)
// Setting as immutable so values can be inlined, review
getImmutableFieldWith None t e "codeUnits"
let stringToCharSeq e =
// Setting as immutable so values can be inlined, review
getImmutableFieldWith None Any e "runes"
let getSubtractToDateMethodName =
function
| [ _; ExprType(Builtin BclDateTime) ] -> "subtractDate"
| _ -> "subtract"
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 (Number(UInt16, NumberInfo.Empty)) [ 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)
| Number(UInt64, _) -> Helper.LibCall(com, "Util", "toUInt64", t, [ operation ], ?loc = 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 ] -> binOp BinaryDivide left right
// In dart % operator and .remainder give different values for negative numbers
| Operators.modulus, [ left; right ] -> Helper.InstanceCall(left, "remainder", t, [ right ], ?loc = r)
| 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
| Number(UInt64, _) :: _ ->
Helper.LibCall(com, "Util", "rightShiftUnsigned64", t, [ left; right ], argTypes, ?loc = r)
| _ -> 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, "Util", "negateInt8", t, args, ?loc = r)
| Number(Int16, _) :: _ -> Helper.LibCall(com, "Util", "negateInt16", t, args, ?loc = r)
| Number(Int32, _) :: _ -> Helper.LibCall(com, "Util", "negateInt32", t, args, ?loc = r)
| Number(Int64, _) :: _ -> Helper.LibCall(com, "Util", "negateInt64", 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(BigInt | Decimal as kind, _) :: _ ->
let modName, opName =
match kind, opName with
| UInt64, Operators.rightShift -> "Long", "op_RightShiftUnsigned" // See #1482
| Decimal, Operators.divideByInt -> "Decimal", Operators.division
| Decimal, _ -> "Decimal", opName
// | BigInt, _ -> "BigInt", opName
| _ -> "BigInt", opName
Helper.LibCall(com, modName, opName, t, args, argTypes, ?loc = r)
| Builtin(BclDateTime | BclTimeSpan | BclDateTimeOffset | BclDateOnly as bt) :: _ ->
let meth =
match opName with
| "op_Addition" -> "add"
| "op_Subtraction" -> getSubtractToDateMethodName args
| "op_Multiply" -> "multiply"
| "op_Division" -> "divide"
| _ -> opName
Helper.LibCall(com, coreModFor bt, meth, 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)
| CustomOp com ctx r t opName args e -> e
| _ -> nativeOp opName argTypes args
let isCompatibleWithNativeComparison =
function
| Number((Int8 | Int16 | Int32 | UInt8 | UInt16 | UInt32 | Int64 | UInt64 | Float32 | Float64), _) -> true
| _ -> 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 t = Int32.Number
getImmutableFieldWith r t arg "hashCode"
// let methodName =
// match arg.Type with
// // These are the same for identity/structural hashing
// | Char | String | Builtin BclGuid -> "stringHash"
// | Number((Decimal|BigInt|Int64|UInt64),_) -> "safeHash"
// | Number _ | 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 t = Int32.Number
getImmutableFieldWith r t arg "hashCode"
// let methodName =
// match arg.Type with
// | Char | String | Builtin BclGuid -> "stringHash"
// | Number ((BigInt|Decimal|Int64|UInt64),_) -> "fastStructuralHash"
// | Number _ | 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)
// Mirrors Fable2Dart.Util.equals
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
| Array(_, ResizeArray) -> Helper.GlobalCall("identical", Boolean, [ left; right ], ?loc = r) |> is equal
| Array(t, _) ->
match left, right with
// F# compiler introduces null checks in array pattern matching
// but this are not necessary because of null safety in Dart
| NullConst, _
| _, NullConst -> makeBoolConst (not equal)
| _ ->
let fn = makeEqualityFunction com ctx t
Helper.LibCall(com, "Util", "equalsList", Boolean, [ left; right; fn ], ?loc = r)
|> is equal
| Any
| GenericParam _ ->
Helper.LibCall(com, "Util", "equalsDynamic", Boolean, [ left; right ], ?loc = r)
|> is equal
| _ ->
if equal then
BinaryEqual
else
BinaryUnequal
|> makeEqOp r left right
// Mirrors Fable2Dart.Util.compare
and compare (com: ICompiler) ctx r (left: Expr) (right: Expr) =
let t = Int32.Number
match left.Type with
| Array(t, _) ->
let fn = makeComparerFunction com ctx t
Helper.LibCall(com, "Util", "compareList", t, [ left; right; fn ], ?loc = r)
| Option(t, _) ->
let fn = makeComparerFunction com ctx t
Helper.LibCall(com, "Util", "compareNullable", t, [ left; right; fn ], ?loc = r)
| Boolean -> Helper.LibCall(com, "Util", "compareBool", t, [ left; right ], ?loc = r)
| Any
| GenericParam _ -> Helper.LibCall(com, "Util", "compareDynamic", t, [ left; right ], ?loc = r)
| _ -> Helper.InstanceCall(left, "compareTo", t, [ 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 = makeTypedIdent typArg "x"
let y = makeTypedIdent 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 =
Helper.LibCall(com, "Types", "Comparer", Any, [ makeComparerFunction com ctx typArg ])
and makeEqualityFunction (com: ICompiler) ctx typArg =
let x = makeTypedIdent typArg "x"
let y = makeTypedIdent 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 = makeTypedIdent typArg "x"
let y = makeTypedIdent typArg "y"
Helper.LibCall(
com,
"Types",
"EqualityComparer",
Any,
[
Delegate([ x; y ], equals com ctx None true (IdentExpr x) (IdentExpr y), None, Tags.empty)
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 genArgs =
let elType = List.tryHead genArgs |> Option.defaultValue Any
let args = args @ [ makeComparer com ctx elType ]
Helper.LibCall(com, "Set", Naming.lowerFirst methName, t, args, genArgs = genArgs, ?loc = r)
/// Adds comparer as last argument for map creator methods
let makeMap (com: ICompiler) ctx r t methName args genArgs =
let keyType = List.tryHead genArgs |> Option.defaultValue Any
let args = args @ [ makeComparer com ctx keyType ]
Helper.LibCall(com, "Map", Naming.lowerFirst methName, t, args, genArgs = genArgs, ?loc = r)
let getZeroTimeSpan t =
Helper.GlobalIdent("Duration", "zero", t)
let emptyGuid () =
makeStrConst "00000000-0000-0000-0000-000000000000"
let rec getZero (com: ICompiler) (ctx: Context) (t: Type) =
match t with
| Tuple(args, true) -> NewTuple(args |> List.map (getZero com ctx), true) |> makeValue None
| Boolean -> makeBoolConst false
| Char -> TypeCast(makeIntConst 0, t)
| String -> makeStrConst "" // Using empty string instead of null so Dart doesn't complain
| Number(BigInt, _) as t -> Helper.LibCall(com, "BigInt", "fromInt32", t, [ makeIntConst 0 ])
| Number(Decimal, _) as t -> makeIntConst 0 |> makeDecimalFromExpr com None t
| Number(kind, uom) -> NumberConstant(NumberValue.GetZero kind, uom) |> makeValue None
| Builtin(BclTimeSpan | BclTimeOnly) -> getZeroTimeSpan 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 BclGuid -> emptyGuid ()
| Builtin(FSharpSet genArg) as t -> makeSet com ctx None t "Empty" [] [ genArg ]
| Builtin(BclKeyValuePair(k, v)) ->
let args = [ getZero com ctx k; getZero com ctx v ]
Helper.ConstructorCall(makeIdentExpr "MapEntry", t, args)
| ListSingleton(CustomOp com ctx None t "get_Zero" [] e) -> e
| _ -> Value(Null Any, None) // null
let getOne (com: ICompiler) (ctx: Context) (t: Type) =
match t with
| Boolean -> makeBoolConst true
| Number(BigInt, _) as t -> Helper.LibCall(com, "BigInt", "fromInt32", t, [ makeIntConst 1 ])
| Number(Decimal, _) as t -> makeIntConst 1 |> makeDecimalFromExpr com None t
| 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 = makeTypedIdent t "x"
let y = makeTypedIdent 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 =
Helper.LibCall(
com,
"Types",
"GenericAdder",
Any,
[ getZero com ctx t |> makeDelegate []; makeAddFunction com ctx t ]
)
let makeGenericAverager (com: ICompiler) ctx t =
let divideFn =
let x = makeTypedIdent t "x"
let i = makeTypedIdent Int32.Number "i"
let body = applyOp com ctx None t Operators.divideByInt [ IdentExpr x; IdentExpr i ]
Delegate([ x; i ], body, None, Tags.empty)
Helper.LibCall(
com,
"Types",
"GenericAverager",
Any,
[ getZero com ctx t |> makeDelegate []; makeAddFunction com ctx t; divideFn ]
)
let injectArg (com: ICompiler) (ctx: Context) r moduleName methName (genArgs: Type list) args =
let injectArgInner args (injectType, injectGenArgIndex) =
List.tryItem injectGenArgIndex genArgs
|> Option.bind (fun genArg ->
match injectType with
| Types.icomparerGeneric -> args @ [ makeComparer com ctx genArg ] |> Some
| Types.iequalityComparerGeneric -> args @ [ makeEqualityComparer com ctx genArg ] |> Some
| Types.adder -> args @ [ makeGenericAdder com ctx genArg ] |> Some
| Types.averager -> args @ [ makeGenericAverager com ctx genArg ] |> Some
| _ -> None
)
Map.tryFind moduleName ReplacementsInject.fableReplacementsModules
|> Option.bind (Map.tryFind methName)
|> Option.bind (injectArgInner args)
|> Option.defaultValue args
let tryEntityIdent (com: Compiler) entFullName =
match entFullName with
| "Fable.Core.Dart.Future`1" -> makeIdentExpr "Future" |> Some
| "Fable.Core.Dart.Stream`1" -> makeIdentExpr "Stream" |> Some
| BuiltinDefinition BclDateOnly
| BuiltinDefinition BclDateTime
| BuiltinDefinition BclDateTimeOffset -> makeIdentExpr "DateTime" |> Some
| BuiltinDefinition BclTimeSpan -> makeIdentExpr "Duration" |> Some
| BuiltinDefinition BclTimer -> makeImportLib com MetaType "default" "Timer" |> Some
| BuiltinDefinition(FSharpReference _) -> makeImportLib com MetaType "FSharpRef" "Types" |> Some
| BuiltinDefinition(FSharpResult _) -> makeImportLib com MetaType "FSharpResult$2" "Result" |> Some
| BuiltinDefinition(FSharpChoice genArgs) ->
let membName = $"FSharpChoice$%d{List.length genArgs}"
makeImportLib com MetaType membName "Choice" |> Some
// | BuiltinDefinition BclGuid -> jsTypeof "string" expr
| BuiltinDefinition(BclHashSet _)
| Types.iset -> makeIdentExpr "Set" |> Some
| BuiltinDefinition(BclDictionary _)
| Types.idictionary -> makeIdentExpr "Map" |> Some
| BuiltinDefinition(BclKeyValuePair _) -> makeIdentExpr "MapEntry" |> Some
| BuiltinDefinition(FSharpSet _) -> makeImportLib com MetaType "FSharpSet" "Set" |> Some
| BuiltinDefinition(FSharpMap _) -> makeImportLib com MetaType "FSharpMap" "Map" |> Some
// | "System.DateTimeKind" -> makeImportLib com MetaType "DateTimeKind" "Date" |> Some
| Types.ienumerable
| Types.ienumerableGeneric
| Types.icollection
| Types.icollectionGeneric
| Naming.EndsWith "Collection" _ -> makeIdentExpr "Iterable" |> Some
| Types.ienumerator
| Types.ienumeratorGeneric
// | "System.Collections.Generic.HashSet`1.Enumerator"
// | "System.Collections.Generic.Dictionary`2.Enumerator"
// | "System.Collections.Generic.Dictionary`2.KeyCollection.Enumerator"
// | "System.Collections.Generic.Dictionary`2.ValueCollection.Enumerator"
| Naming.EndsWith "Enumerator" _ -> makeIdentExpr "Iterator" |> Some
| Types.icomparable
| Types.icomparableGeneric -> makeIdentExpr "Comparable" |> Some
| Types.idisposable
| Types.adder
| Types.averager
| Types.icomparerGeneric
| Types.iequalityComparerGeneric ->
let entFullName =
entFullName[entFullName.LastIndexOf(".", StringComparison.Ordinal) + 1 ..]
let entFullName =
match entFullName.IndexOf("`", StringComparison.Ordinal) with
| -1 -> entFullName
| i -> entFullName[0 .. i - 1]
makeImportLib com MetaType entFullName "Types" |> Some
// Don't use `Exception` for now because it doesn't catch all errors in Dart
// See Fable2Dart.transformDeclaredType
// | Types.exception_ ->
// makeImportLib com Any "ExceptionBase" "Types" |> Some
| "System.Collections.Generic.KeyNotFoundException" ->
makeImportLib com Any "KeyNotFoundException" "System.Collections.Generic"
|> Some
| BuiltinSystemException entName -> makeImportLib com Any entName "System" |> Some
| Naming.EndsWith "Exception" _ -> makeIdentExpr "Exception" |> Some
| "System.Lazy`1" -> makeImportLib com MetaType "Lazy" "FSharp.Core" |> 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 r -> r
| None -> $"Cannot find %s{ent.FullName} constructor" |> addErrorAndReturnNull com [] None
let tryOp com r t op args =
Helper.LibCall(com, "Option", "tryOp", t, op :: args, ?loc = r)
let tryCoreOp com r t coreModule coreMember args =
let op = Helper.LibValue(com, coreModule, coreMember, Any)
tryOp com r t op args
let fableCoreLib (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr option) (args: Expr list) =
match i.DeclaringEntityFullName, i.CompiledName with
| _, UniversalFableCoreHelpers com ctx r t i args error expr -> Some expr
| "Fable.Core.Reflection", meth -> Helper.LibCall(com, "Reflection", meth, t, args, ?loc = r) |> Some
| "Fable.Core.Compiler", meth ->
match meth with
| "version" -> makeStrConst Literals.VERSION |> Some
| "majorMinorVersion" ->
try
let m = System.Text.RegularExpressions.Regex.Match(Literals.VERSION, @"^\d+\.\d+")
float m.Value |> makeFloatConst |> Some
with _ ->
"Cannot parse compiler version"
|> addErrorAndReturnNull com ctx.InlinePath r
|> Some
| "debugMode" -> makeBoolConst com.Options.DebugMode |> Some
| "typedArrays" -> makeBoolConst com.Options.TypedArrays |> Some
| "extension" -> makeStrConst com.Options.FileExtension |> Some
| "triggeredByDependency" -> makeBoolConst com.Options.TriggeredByDependency |> Some
| _ -> None
| Naming.StartsWith "Fable.Core.Dart" rest, _ ->
match rest with
| ".DartNullable`1" ->
match i.CompiledName, thisArg with
| ".ctor", None ->
match args with
| arg :: _ -> Some arg
| [] -> makeNull () |> Some
| "get_Value", Some c -> Helper.LibCall(com, "Util", "value", t, [ c ], ?loc = r) |> Some
| "get_HasValue", Some c -> makeEqOp r c (makeNull ()) BinaryUnequal |> Some
| _ -> None
| _ ->
match i.CompiledName, args with
| Naming.StartsWith "import" suffix, _ ->
match suffix, args with
| "Member", [ RequireStringConst com ctx r path ] ->
makeImportUserGenerated r t Naming.placeholder path |> Some
| "All", [ RequireStringConst com ctx r path ] -> makeImportUserGenerated r t "*" path |> Some
| _, [ RequireStringConst com ctx r selector; RequireStringConst com ctx r path ] ->
makeImportUserGenerated r t selector path |> Some
| _ -> None
| Naming.StartsWith "emit" rest, [ args; macro ] ->
match macro with
| RequireStringConstOrTemplate com ctx r template ->
let args = destructureTupleArgs [ args ]
let isStatement = rest = "Statement"
emitTemplate r t args isStatement template |> Some
| ("toNullable" | "ofNullable"), [ arg ] -> Some arg
| "toOption" | "ofOption" | "defaultValue" | "defaultWith" as meth, args ->
Helper.LibCall(com, "Types", meth, t, args, ?loc = r) |> Some
| _ -> None
| _ -> None
let getRefCell com r typ (expr: Expr) = getFieldWith r typ expr "contents"
let setRefCell com r (expr: Expr) (value: Expr) = setField r expr "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 = makeFSharpCoreType [ value.Type ] Types.refCell
let fsharpRef = Helper.LibValue(com, "Types", "FSharpRef", MetaType)
Helper.InstanceCall(fsharpRef, "ofValue", typ, [ value ], genArgs = typ.Generics, ?loc = r)
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 ]
// Not sure if this is needed in Dart, see comment in JS.Replacements.makeRefFromMutableFunc
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; makeBoolConst true ]
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 refCells (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr option) (args: Expr list) =
match i.CompiledName, thisArg, args with
| "get_Value", Some callee, _ -> getRefCell com r t callee |> Some
| "set_Value", Some callee, [ value ] -> setRefCell com r callee value |> Some
| _ -> None
let getMangledNames (i: CallInfo) (thisArg: Expr option) =
let isStatic = Option.isNone thisArg
let pos = i.DeclaringEntityFullName.LastIndexOf('.')
let moduleName =
i.DeclaringEntityFullName.Substring(0, pos).Replace("Microsoft.", "")
let entityName =
i.DeclaringEntityFullName.Substring(pos + 1)
|> FSharp2Fable.Helpers.cleanNameAsJsIdentifier
let memberName = i.CompiledName |> FSharp2Fable.Helpers.cleanNameAsJsIdentifier
let mangledName =
Naming.buildNameWithoutSanitationFrom entityName isStatic memberName i.OverloadSuffix
moduleName, mangledName
let bclType (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr option) (args: Expr list) =
let moduleName, mangledName = getMangledNames i thisArg
let args =
match thisArg with
| Some callee -> callee :: args
| _ -> args
Helper.LibCall(com, moduleName, mangledName, t, args, i.SignatureArgTypes, genArgs = i.GenericArgs, ?loc = r)
|> Some
let fsharpModule (com: ICompiler) (ctx: Context) r (t: Type) (i: CallInfo) (thisArg: Expr option) (args: Expr list) =
let moduleName, mangledName = getMangledNames i thisArg
Helper.LibCall(com, moduleName, mangledName, t, args, i.SignatureArgTypes, genArgs = i.GenericArgs, ?loc = r)
|> Some
let printJsTaggedTemplate
(str: string)
(holes:
{|
Index: int
Length: int
|}[])
(printHoleContent: int -> string)
=
// Escape ` quotations for JS. Note F# escapes for {, } and % are already replaced by the compiler
// TODO: Do we need to escape other sequences? See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates_and_escape_sequences
let escape (str: string) =
Regex.Replace(str, @"(?<!\\)\\", @"\\").Replace("`", @"\`") //.Replace("{{", "{").Replace("}}", "}").Replace("%%", "%")
let sb = System.Text.StringBuilder("`")
let mutable prevIndex = 0
for i = 0 to holes.Length - 1 do
let m = holes[i]
let strPart = str.Substring(prevIndex, m.Index - prevIndex) |> escape
sb.Append(strPart + "${" + (printHoleContent i) + "}") |> ignore
prevIndex <- m.Index + m.Length
sb.Append(str.Substring(prevIndex) |> escape) |> ignore
sb.Append("`") |> ignore
sb.ToString()
let fsFormat (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr option) (args: Expr list) =
match i.CompiledName, thisArg, args with
| "get_Value", Some callee, _ -> getFieldWith None t callee "input" |> Some
| "PrintFormatToStringThen", _, _ ->
match args with
| [ _ ] ->
Helper.LibCall(com, "String", "toText", t, args, i.SignatureArgTypes, ?loc = r)
|> Some
| [ cont; fmt ] -> Helper.InstanceCall(fmt, "cont", t, [ cont ]) |> Some
| _ -> None
| "PrintFormatToString", _, _ ->
match args with
| [ template ] when template.Type = String -> Some template
| _ ->
Helper.LibCall(com, "String", "toText", t, args, i.SignatureArgTypes, ?loc = r)
|> Some
| "PrintFormatLine", _, _ ->
Helper.LibCall(com, "String", "toConsole", t, args, i.SignatureArgTypes, ?loc = r)
|> Some
| ("PrintFormatToError" | "PrintFormatLineToError"), _, _ ->
// addWarning com ctx.FileName r "eprintf will behave as eprintfn"
Helper.LibCall(com, "String", "toConsoleError", t, args, i.SignatureArgTypes, ?loc = r)
|> Some
| ("PrintFormatToTextWriter" | "PrintFormatLineToTextWriter"), _, _ :: args ->
// addWarning com ctx.FileName r "fprintfn will behave as printfn"
Helper.LibCall(com, "String", "toConsole", t, args, i.SignatureArgTypes, ?loc = r)
|> Some
| "PrintFormat", _, _ ->
// addWarning com ctx.FileName r "Printf will behave as printfn"
Helper.LibCall(com, "String", "toConsole", t, args, i.SignatureArgTypes, ?loc = r)
|> Some
| "PrintFormatThen", _, arg :: callee :: _ -> Helper.InstanceCall(callee, "cont", t, [ arg ]) |> Some
| "PrintFormatToStringThenFail", _, _ ->
Helper.LibCall(com, "String", "toFail", t, args, i.SignatureArgTypes, ?loc = r)
|> Some
| ("PrintFormatToStringBuilder" | "PrintFormatToStringBuilderThen"), // Printf.kbprintf
_,
_ -> fsharpModule com ctx r t i thisArg args
| ".ctor", _, str :: (Value(NewArray(ArrayValues templateArgs, _, MutableArray), _) as values) :: _ ->
match makeStringTemplateFrom [| "%s"; "%i" |] templateArgs str with
| Some v -> makeValue r v |> Some
| None ->
Helper.LibCall(com, "String", "interpolate", t, [ str; values ], i.SignatureArgTypes, ?loc = r)
|> Some
| ".ctor", _, arg :: _ ->
Helper.LibCall(com, "String", "printf", t, [ arg ], i.SignatureArgTypes, ?loc = r)
|> Some
| _ -> None
let defaultValue com ctx r t defValue option =
match option with
| MaybeInScope ctx (Value(NewOption(opt, _, _), _)) ->
match opt with
| Some value -> Some value
| None -> Some defValue
| _ ->
Helper.LibCall(com, "Option", "defaultValue", t, [ defValue; option ], ?loc = r)
|> Some
let operators (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr option) (args: Expr list) =
let math r t (args: Expr list) argTypes methName =
let meth = Naming.lowerFirst methName
let call = Helper.ImportedCall("dart:math", meth, t, args, argTypes, ?loc = r)
match meth, t with
| "pow", Number((Float32 | Float64), _) -> Helper.InstanceCall(call, "toDouble", t, [], ?loc = r)
| _ -> call
match i.CompiledName, args with
| ("DefaultArg" | "DefaultValueArg"), [ option; defValue ] -> defaultValue com ctx r t defValue option
| "DefaultAsyncBuilder", _ -> makeImportLib com t "singleton" "AsyncBuilder" |> Some
| "KeyValuePattern", [ arg ] -> Helper.LibCall(com, "Types", "mapEntryToTuple", t, [ arg ], ?loc = r) |> Some
// Erased operators.
| ("Identity" | "Box" | "Unbox" | "ToEnum"), [ arg ] -> TypeCast(arg, t) |> Some
// Cast to unit to make sure nothing is returned when wrapped in a lambda, see #1360
| "Ignore", _ ->
Helper.LibCall(com, "Util", "ignore", t, args, ?loc = r)
|> withTag "ignore"
|> Some
// Number and String conversions
| ("ToSByte" | "ToByte" | "ToInt8" | "ToUInt8" | "ToInt16" | "ToUInt16" | "ToInt" | "ToUInt" | "ToInt32" | "ToUInt32" | "ToInt64" | "ToUInt64"),
_ -> toInt com ctx r t args |> Some
| ("ToSingle" | "ToDouble"), _ -> toFloat com ctx r t args |> Some
| "ToDecimal", _ -> toDecimal com ctx r t args |> Some
| "ToChar", _ -> toChar com ctx r args.Head |> Some
| "ToString", _ -> toString com ctx r args |> Some
| "CreateSequence", [ xs ] -> TypeCast(xs, t) |> Some
| ("CreateDictionary" | "CreateReadOnlyDictionary"), [ arg ] ->
Helper.LibCall(com, "Types", "mapFromTuples", t, [ arg ], genArgs = i.GenericArgs, ?loc = r)
|> withTag "const-map"
|> Some
| "CreateSet", _ -> makeSet com ctx r t "OfSeq" args i.GenericArgs |> Some
// Ranges
| ("op_Range" | "op_RangeStep"), _ ->
let genArg = genArg com ctx r 0 i.GenericArgs
let addStep args =
match args with
| [ first; last ] -> [ first; getOne com ctx genArg; last ]
| _ -> args
let modul, meth, args =
match genArg with
| Char -> "Range", "rangeChar", args
| Number(Decimal, _) -> "Range", "rangeDecimal", addStep args
| Number(BigInt, _) -> "Range", "rangeBigInt", addStep args
| Number(DartInt, _) -> "Range", "rangeInt", addStep args
| _ -> "Range", "rangeDouble", addStep args