-
Notifications
You must be signed in to change notification settings - Fork 326
Expand file tree
/
Copy pathReplacements.fs
More file actions
3662 lines (3322 loc) · 171 KB
/
Copy pathReplacements.fs
File metadata and controls
3662 lines (3322 loc) · 171 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
[<RequireQualifiedAccess>]
module Fable.Transforms.Rust.Replacements
#nowarn "1182"
open System
open System.Text.RegularExpressions
open Fable
open Fable.AST
open Fable.AST.Fable
open Fable.Transforms
open Replacements.Util
type Context = FSharp2Fable.Context
type ICompiler = FSharp2Fable.IFableCompiler
type CallInfo = ReplaceCallInfo
// let partialApplyAtRuntime (com: Compiler) t arity (expr: Expr) (partialArgs: Expr list) =
// let rec makeNestedLambda body args =
// match args with
// | [] -> body
// | arg::restArgs ->
// let body = Fable.Lambda(arg, body, None)
// makeNestedLambda body restArgs
// let makeArgIdent i typ = makeTypedIdent typ $"a{i}"
// let argTypes, returnType = uncurryLambdaType arity [] t
// let argIdents = argTypes |> List.mapi makeArgIdent
// let args = argIdents |> List.map Fable.IdentExpr
// let body = Helper.Application(expr, returnType, partialArgs @ args)
// makeNestedLambda body (List.rev argIdents)
// let curryExprAtRuntime (com: Compiler) arity (expr: Expr) =
// partialApplyAtRuntime com expr.Type arity expr []
// let uncurryExprAtRuntime (com: Compiler) t arity (expr: Expr) =
// let argTypes, returnType =
// match t with
// | Fable.LambdaType(argType, returnType) -> uncurryLambdaType arity [] t
// | Fable.DelegateType(argTypes, returnType) -> argTypes, returnType
// | _ -> [], expr.Type
// let makeArgIdent i typ = makeTypedIdent typ $"b{i}$"
// let argIdents = argTypes |> List.mapi makeArgIdent
// let args = argIdents |> List.map Fable.IdentExpr
// let body = curriedApply None returnType expr args
// Fable.Delegate(argIdents, body, None, Fable.Tags.empty)
let error com (msg: Expr) = msg
let coreModFor =
function
| BclGuid -> "Guid"
| BclDateTime -> "DateTime"
| BclDateTimeOffset -> "DateTimeOffset"
| BclDateOnly -> "DateOnly"
| BclTimeOnly -> "TimeOnly"
| BclTimer -> "Timer"
| BclTimeSpan -> "TimeSpan"
| FSharpSet _ -> "Set"
| FSharpMap _ -> "Map"
| FSharpResult _ -> "Result"
| FSharpChoice _ -> "Choice"
| FSharpReference _ -> "Native"
| BclHashSet _ -> "HashSet"
| BclDictionary _ -> "HashMap"
| BclKeyValuePair _ -> "Native"
let makeInstanceCall r t (i: CallInfo) callee memberName args =
Helper.InstanceCall(callee, memberName, t, args, i.SignatureArgTypes, i.GenericArgs, ?loc = r)
let makeStaticLibCall com r t (i: CallInfo) moduleName memberName args =
let isConstructor = (i.CompiledName = ".ctor" || i.CompiledName = ".cctor")
Helper.LibCall(
com,
moduleName,
memberName,
t,
args,
i.SignatureArgTypes,
i.GenericArgs,
isModuleMember = false,
isConstructor = isConstructor,
?loc = r
)
let makeStaticMemberCall com r t (i: CallInfo) moduleName memberName args =
let fullName = i.DeclaringEntityFullName
let entityName =
fullName.Substring(fullName.LastIndexOf(".", StringComparison.Ordinal) + 1)
let memberName = entityName + "::" + memberName
makeStaticLibCall com r t i moduleName memberName args
let makeStaticFieldCall com r t moduleName entityName memberName =
let memberName = entityName + "::" + memberName
Helper.LibCall(com, moduleName, memberName, t, [], ?isModuleMember = Some(false), ?loc = r)
let makeLibCall com r t (i: CallInfo) moduleName memberName args =
Helper.LibCall(com, moduleName, memberName, t, args, i.SignatureArgTypes, i.GenericArgs, ?loc = r)
let makeLibModuleCall com r t (i: CallInfo) moduleName memberName (thisArg: Expr option) (args: Expr list) =
let args, argTypes =
match thisArg with
| Some c -> c :: args, c.Type :: i.SignatureArgTypes
| None -> args, i.SignatureArgTypes
Helper.LibCall(com, moduleName, memberName, t, args, argTypes, i.GenericArgs, ?loc = r)
let makeGlobalIdent (ident: string, memb: string, typ: Type) =
makeTypedIdentExpr typ (ident + "::" + memb)
let makeUniqueIdent com ctx t name =
FSharp2Fable.Helpers.getIdentUniqueName com ctx name |> makeTypedIdent t
let makeDecimal com r t (x: decimal) =
let str = x.ToString(System.Globalization.CultureInfo.InvariantCulture)
Helper.LibCall(com, "Decimal", "fromString", t, [ makeStrConst str ], isConstructor = true, ?loc = r)
let makeRef (value: Expr) =
Operation(Unary(UnaryAddressOf, value), Tags.empty, value.Type, None)
let makeClone com r t (expr: Expr) =
Helper.InstanceCall(expr, "clone", t, [], ?loc = r)
let getRefCell com r t (expr: Expr) =
Helper.InstanceCall(expr, "get", t, [], ?loc = r) |> makeClone com r t
let setRefCell com r (expr: Expr) (value: Expr) =
Set(expr, ValueSet, value.Type, value, r)
let makeRefCell com r genArg args =
let typ = makeFSharpCoreType [ genArg ] Types.refCell
Helper.LibCall(com, "Native", "refCell", typ, args, isConstructor = true, ?loc = r)
let makeRefCellFromValue com r (value: Expr) = makeRefCell com r value.Type [ value ]
let makeRefFromMutableValue com ctx r t (value: Expr) =
Operation(Unary(UnaryAddressOf, value), Tags.empty, t, r)
let makeRefFromMutableField com ctx r t callee key =
let value = Get(callee, FieldInfo.Create(key), t, r)
Operation(Unary(UnaryAddressOf, value), Tags.empty, t, r)
// Mutable and public module values are compiled as functions
let makeRefFromMutableFunc com ctx r t (value: Expr) = value
let toNativeIndex expr = TypeCast(expr, UNativeInt.Number)
let toLowerFirstWithArgsCountSuffix (args: Expr list) meth =
let argCount = List.length args - 1 // don't count first arg
let meth = Naming.lowerFirst meth
if argCount > 1 then
meth + (string<int> argCount)
else
meth
// 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 convertTo com (ctx: Context) r t (args: Expr list) =
let sourceType = args.Head.Type
match t with
| Boolean ->
match sourceType with
| Number(Decimal, _) -> Helper.LibCall(com, "Decimal", "toBoolean", t, args, ?loc = r)
| Number(BigInt, _) -> Helper.LibCall(com, "BigInt", "toBoolean", t, args, ?loc = r)
| Number(_kind, _) -> Helper.LibCall(com, "Convert", "toBoolean", t, args, ?loc = r)
| Char -> Helper.LibCall(com, "Convert", "toBoolean", t, args, ?loc = r)
| String -> Helper.LibCall(com, "Convert", "parseBoolean", t, args, ?loc = r)
| _ ->
addWarning com ctx.InlinePath r "Unsupported conversion"
TypeCast(args.Head, t)
| Char ->
match sourceType with
| Char -> args.Head
| String -> Helper.LibCall(com, "Convert", "parseChar", t, args, ?loc = r)
| Number(Decimal, _) -> Helper.LibCall(com, "Decimal", "toChar", t, args, ?loc = r)
| Number(BigInt, _) -> Helper.LibCall(com, "BigInt", "toChar", t, args, ?loc = r)
| Number(_kind, _) ->
let code = TypeCast(args.Head, UInt32.Number)
Helper.LibCall(com, "Char", "fromCharCode", t, [ code ])
| _ ->
addWarning com ctx.InlinePath r "Unsupported conversion"
TypeCast(args.Head, t)
| Number(Decimal, _) ->
match sourceType with
| Array(Number(Int32, _), _) -> Helper.LibCall(com, "Decimal", "fromIntArray", t, args, ?loc = r)
| Boolean -> Helper.LibCall(com, "Decimal", "fromBoolean", t, args, ?loc = r)
| Char -> Helper.LibCall(com, "Decimal", "fromChar", t, args, ?loc = r)
| String -> Helper.LibCall(com, "Decimal", "fromString", t, args, ?loc = r)
| Number(BigInt, _) -> Helper.LibCall(com, "BigInt", "toDecimal", t, args, ?loc = r)
| Number(kind, _) ->
let meth = "from" + kind.ToString()
Helper.LibCall(com, "Decimal", meth, t, args, ?loc = r)
| _ ->
addWarning com ctx.InlinePath r "Unsupported conversion"
TypeCast(args.Head, t)
| Number(BigInt, _) ->
match sourceType with
| Array(Number(UInt8, _), _) -> Helper.LibCall(com, "BigInt", "fromByteArray", t, args, ?loc = r)
| Boolean -> Helper.LibCall(com, "BigInt", "fromBoolean", t, args, ?loc = r)
| Char -> Helper.LibCall(com, "BigInt", "fromChar", t, args, ?loc = r)
| String -> Helper.LibCall(com, "BigInt", "fromString", t, args, ?loc = r)
| Number(kind, _) ->
let meth = "from" + kind.ToString()
Helper.LibCall(com, "BigInt", meth, t, args, ?loc = r)
| _ ->
addWarning com ctx.InlinePath r "Unsupported conversion"
TypeCast(args.Head, t)
| Number(kind, _) ->
match sourceType with
| Char ->
let code = TypeCast(args.Head, UInt32.Number)
TypeCast(code, t)
| String ->
let meth = "to" + kind.ToString()
Helper.LibCall(com, "Convert", meth, t, args, ?loc = r)
| Number(Decimal, _) ->
let meth = "to" + kind.ToString()
Helper.LibCall(com, "Decimal", meth, t, args, ?loc = r)
| Number(BigInt, _) ->
let meth = "to" + kind.ToString()
Helper.LibCall(com, "BigInt", meth, t, args, ?loc = r)
| Number _ -> TypeCast(args.Head, t)
| _ ->
addWarning com ctx.InlinePath r "Unsupported conversion"
TypeCast(args.Head, t)
| _ ->
addWarning com ctx.InlinePath r "Unsupported conversion"
TypeCast(args.Head, t)
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 -> Helper.LibCall(com, "String", "ofChar", String, [ head ])
| Boolean -> Helper.LibCall(com, "String", "ofBoolean", String, [ head ])
| Number(BigInt, _) -> Helper.LibCall(com, "BigInt", "toString", String, args)
| Number(Decimal, _) -> Helper.LibCall(com, "Decimal", "toString", String, args)
// | 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, "String", "toString", String, [ head ])
let toRoundInt com (ctx: Context) r t i (args: Expr list) =
let sourceType = args.Head.Type
let args =
match sourceType with
| Number((Float16 | Float32 | Float64 | Decimal), _) ->
let rounded = makeInstanceCall r sourceType i args.Head "round" []
rounded :: args.Tail
| _ -> args
convertTo com ctx r t args
let toRadixInt com (ctx: Context) r t i (args: Expr list) =
match t with
| Number(kind, _) ->
let meth = "to" + kind.ToString() + "_radix"
Helper.LibCall(com, "Convert", meth, t, args, ?loc = r)
| _ -> FableError $"Unexpected conversion %s{i.CompiledName}" |> raise
let toArray com t (expr: Expr) =
match expr.Type with
| Array _ -> expr
| List _ -> Helper.LibCall(com, "List", "toArray", t, [ expr ])
| String -> Helper.LibCall(com, "String", "toCharArray", t, [ expr ])
| IEnumerable -> Helper.LibCall(com, "Seq", "toArray", t, [ expr ])
| _ -> TypeCast(expr, t)
let toList com t (expr: Expr) =
match expr.Type with
| List _ -> expr
| Array _ -> Helper.LibCall(com, "List", "ofArray", t, [ expr ])
| String ->
let chars = Helper.LibCall(com, "String", "toCharArray", t, [ expr ])
Helper.LibCall(com, "List", "ofArray", t, [ chars ])
| IEnumerable -> Helper.LibCall(com, "List", "ofSeq", t, [ expr ])
| _ -> TypeCast(expr, t)
let toSeq com t (expr: Expr) =
match expr.Type with
| IEnumerable -> expr
| List _ -> Helper.LibCall(com, "Seq", "ofList", t, [ expr ])
| Array _ -> Helper.LibCall(com, "Seq", "ofArray", t, [ expr ])
| String ->
let chars = Helper.LibCall(com, "String", "toCharArray", t, [ expr ])
Helper.LibCall(com, "Seq", "ofArray", t, [ chars ])
| _ -> TypeCast(expr, t)
let emitRawString (s: string) = $"\"%s{s}\"" |> emitExpr None String []
let emitFormat (com: ICompiler) r t (args: Expr list) macro =
let args =
match args with
| [] -> [ emitRawString "" ]
| [ StringConst fmt; Value(NewArray(ArrayValues restArgs, _, _), _) ] -> (emitRawString fmt) :: restArgs
| (StringConst fmt) :: restArgs -> (emitRawString fmt) :: restArgs
| [ StringTempl(fmt, args); Value(NewArray(ArrayValues restArgs, _, _), _) ] ->
(emitRawString fmt) :: args @ restArgs
| (StringTempl(fmt, args)) :: restArgs -> (emitRawString fmt) :: args @ restArgs
| [ ExprTypeAs(String, str); Value(NewArray(ArrayValues restArgs, _, _), _) ] ->
(emitRawString "{0}") :: str :: restArgs
| _ -> (emitRawString "{0}") :: args
let unboxedArgs = args |> FSharp2Fable.Util.unboxBoxedArgs
Helper.LibCall(com, "String", macro, t, unboxedArgs)
let getMut expr =
Helper.InstanceCall(expr, "get_mut", expr.Type, [])
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 toUInt32 e =
convertTo com ctx None UInt32.Number [ e ]
Operation(Binary(op, toUInt32 left, toUInt32 right), Tags.empty, UInt32.Number, r)
|> List.singleton
|> convertTo com ctx r Char
let truncateUnsigned operation = // see #1550
match t with
// | Number(UInt32,_) ->
// Operation(Binary(BinaryShiftRightZeroFill,operation,makeIntConst 0), 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, [ left; right ] -> binOp BinaryDivide left right
| Operators.divideByInt, [ left; right ] ->
Helper.LibCall(com, "Native", "divideByInt", t, [ left; right ], argTypes, ?loc = r)
| 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 ] -> 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 as kind,_)::_ ->
// Helper.LibCall(com, "BigInt", opName, t, args, argTypes, ?loc=r)
| Builtin(BclDateTime | BclDateTimeOffset | BclTimeOnly | BclTimeSpan) :: _ -> nativeOp opName argTypes args
| Builtin(FSharpSet _) :: _ ->
let methName =
match opName with
| Operators.addition -> "union"
| Operators.subtraction -> "difference"
| _ -> opName
Helper.LibCall(com, "Set", methName, 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
| Boolean
| Char
| String
| Number _
| GenericParam _
// | Array _
// | List _
| Builtin(BclGuid) -> true
| Builtin(BclTimeSpan) -> 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 referenceHash (com: ICompiler) ctx r (arg: Expr) =
match arg.Type with
| Boolean
| Char
| String
| Number _ -> Helper.InstanceCall(arg, "getHashCode", Int32.Number, [], [], [], ?loc = r)
| _ -> Helper.LibCall(com, "Native", "referenceHash", Int32.Number, [ makeRef arg ], ?loc = r)
let getHashCode (com: ICompiler) ctx r (arg: Expr) =
match arg.Type with
| HasReferenceEquality com _ -> referenceHash com ctx r arg
| _ -> Helper.InstanceCall(arg, "getHashCode", Int32.Number, [], [], [], ?loc = r)
let objectHash (com: ICompiler) ctx r (arg: Expr) =
match arg.Type with
| Array _ -> referenceHash com ctx r arg
| _ -> getHashCode com ctx r arg
let referenceEquals (com: ICompiler) ctx r (left: Expr) (right: Expr) =
match left, right with
| Value(Null _, _), o
| o, Value(Null _, _) -> Helper.LibCall(com, "Native", "is_null", Boolean, [ makeRef o ], ?loc = r)
| _ ->
match left.Type with
| Boolean
| Char
| String
| Number _ -> makeEqOp r left right BinaryEqual
| _ -> Helper.LibCall(com, "Native", "referenceEquals", Boolean, [ makeRef left; makeRef right ], ?loc = r)
let equals (com: ICompiler) ctx r (left: Expr) (right: Expr) =
let t = Boolean
match left.Type with
| Boolean
| Char
| String
| Number _
| Builtin(FSharpChoice _ | FSharpResult _) -> makeEqOp r left right BinaryEqual
| Builtin kind -> Helper.LibCall(com, coreModFor kind, "equals", t, [ left; right ], ?loc = r)
| Array(_, ResizeArray) -> referenceEquals com ctx r left right
| Array _ -> Helper.LibCall(com, "Array", "equals", t, [ left; right ], ?loc = r)
| List _ -> Helper.LibCall(com, "List", "equals", t, [ left; right ], ?loc = r)
| IEnumerable -> Helper.LibCall(com, "Seq", "equals", t, [ left; right ], ?loc = r)
// | MetaType ->
// Helper.LibCall(com, "Reflection", "equals", t, [left; right], ?loc=r)
| HasReferenceEquality com _ -> referenceEquals com ctx r left right
| Nullable _ ->
// transforms null checks into option tests
match left, right with
| expr, Value(NewOption(None, _, _), _) -> Test(expr, OptionTest false, r)
| Value(NewOption(None, _, _), _), expr -> Test(expr, OptionTest false, r)
| _ -> makeEqOp r left right BinaryEqual
| _ ->
// Helper.LibCall(com, "Native", "equals", t, [left; right], ?loc=r)
makeEqOp r left right BinaryEqual
/// Compare function that will call Util.compare or instance `CompareTo` as appropriate
let compare (com: ICompiler) ctx r (left: Expr) (right: Expr) =
let t = Int32.Number
match left.Type with
| Boolean
| Char
| String
| Number _
| Builtin(FSharpChoice _ | FSharpResult _) -> Helper.LibCall(com, "Native", "compare", t, [ left; right ], ?loc = r)
| Builtin kind -> Helper.LibCall(com, coreModFor kind, "compareTo", t, [ left; right ], ?loc = r)
| Array _ -> Helper.LibCall(com, "Array", "compareTo", t, [ left; right ], ?loc = r)
| List _ -> Helper.LibCall(com, "List", "compareTo", t, [ left; right ], ?loc = r)
| IEnumerable -> Helper.LibCall(com, "Seq", "compareTo", t, [ left; right ], ?loc = r)
| _ -> Helper.LibCall(com, "Native", "compare", t, [ left; right ], ?loc = r)
/// Boolean comparison operators like <, >, <=, >=
let 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
let applyCompareOp (com: ICompiler) (ctx: Context) r t opName (left: Expr) (right: Expr) =
let op =
match opName with
| Operators.equality
| "Eq" -> BinaryEqual
| Operators.inequality
| "Neq" -> BinaryUnequal
| Operators.lessThan
| "Lt" -> BinaryLess
| Operators.lessThanOrEqual
| "Lte" -> BinaryLessOrEqual
| Operators.greaterThan
| "Gt" -> BinaryGreater
| Operators.greaterThanOrEqual
| "Gte" -> BinaryGreaterOrEqual
| _ -> FableError $"Unexpected operator %s{opName}" |> raise
match op with
| BinaryEqual -> equals com ctx r left right
| BinaryUnequal ->
match left.Type with
| Boolean
| Char
| String
| Number _ -> makeEqOp r left right BinaryUnequal
| _ ->
let expr = equals com ctx r left right
makeUnOp None Boolean expr UnaryNot
| _ -> booleanCompare com ctx r left right op
// let 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)
// let makeComparer (com: ICompiler) ctx typArg =
// objExpr ["Compare", makeComparerFunction com ctx typArg]
// let 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 (IdentExpr x) (IdentExpr y)
// Delegate([x; y], body, None, Tags.empty)
// let makeEqualityComparer (com: ICompiler) ctx typArg =
// let x = makeUniqueIdent ctx typArg "x"
// let y = makeUniqueIdent ctx typArg "y"
// objExpr
// [
// "Equals", Delegate([ x; y ], equals com ctx None (IdentExpr x) (IdentExpr y), None, Tags.empty)
// "GetHashCode", Delegate([ x ], getHashCode com ctx 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 args genArg =
// let args = args @ [makeComparer com ctx genArg]
let meth =
match args with
| [] -> "empty"
| [ ExprType(List _) ] -> "ofList"
| [ ExprType(Array _) ] -> "ofArray"
| _ -> "ofSeq"
Helper.LibCall(com, "Set", meth, t, args, ?loc = r)
/// Adds comparer as last argument for map creator methods
let makeMap (com: ICompiler) ctx r t args genArg =
// let args = args @ [makeComparer com ctx genArg]
let meth =
match args with
| [] -> "empty"
| [ ExprType(List _) ] -> "ofList"
| [ ExprType(Array _) ] -> "ofArray"
| _ -> "ofSeq"
Helper.LibCall(com, "Map", Naming.lowerFirst meth, 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 =
// Helper.LibCall(com, "Dict", "ofSeq", t, [sourceSeq], ?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 rec getZero (com: ICompiler) (ctx: Context) (t: Type) =
match t with
| Nullable(genArg, true) -> NewOption(None, genArg, false) |> makeValue None
| Nullable(genArg, false) -> Null t |> makeValue None
| Boolean -> makeBoolConst false
| Number(BigInt, _) -> Helper.LibCall(com, "BigInt", "zero", t, [])
| Number(Decimal, _) -> Helper.LibValue(com, "Decimal", "Zero", t)
| Number(kind, uom) -> NumberConstant(NumberValue.GetZero kind, uom) |> makeValue None
| Char -> CharConstant '\u0000' |> makeValue None
| String -> Null t |> makeValue None
| Array(typ, _) -> makeArray typ []
| List genArg -> NewList(None, genArg) |> makeValue None
| Builtin BclDateTime -> Helper.LibCall(com, "DateTime", "zero", t, [])
| Builtin BclDateTimeOffset -> Helper.LibCall(com, "DateTimeOffset", "zero", t, [])
| Builtin BclDateOnly -> Helper.LibCall(com, "DateOnly", "zero", t, [])
| Builtin BclTimeOnly -> Helper.LibCall(com, "TimeOnly", "zero", t, [])
| Builtin BclTimeSpan -> Helper.LibValue(com, "TimeSpan", "zero", t)
| Builtin(FSharpSet genArg) -> makeSet com ctx None t [] genArg
| Builtin BclGuid -> Helper.LibValue(com, "Guid", "empty", t)
| 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
| IsReferenceType com _ -> Null t |> makeValue None
| _ -> Helper.LibCall(com, "Native", "getZero", t, [])
let getOne (com: ICompiler) (ctx: Context) (t: Type) =
match t with
| Boolean -> makeBoolConst true
| Number(BigInt, _) -> Helper.LibCall(com, "BigInt", "one", t, [])
| Number(Decimal, _) -> Helper.LibValue(com, "Decimal", "One", 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 = 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
// ]
// let injectArg (com: ICompiler) (ctx: Context) r moduleName methName (genArgs: (string * Type) list) args =
// let injectArgInner args (injectType, injectGenArgIndex) =
// let fail () =
// $"Cannot inject arg to %s{moduleName}.%s{methName} (genArgs %A{List.map fst 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]
// | Types.iequalityComparer ->
// args @ [makeEqualityComparer com ctx genArg]
// | Types.arrayCons ->
// match genArg with
// | Number(numberKind,_) when com.Options.TypedArrays ->
// args @ [getTypedArrayName com numberKind |> makeIdentExpr]
// // Python will complain if we miss an argument
// | _ when com.Options.Language = Python ->
// args @ [ Expr.Value(ValueKind.NewOption(None, genArg, false), None) ]
// | _ -> args
// | Types.adder ->
// args @ [makeGenericAdder com ctx genArg]
// | Types.averager ->
// args @ [makeGenericAverager com ctx genArg]
// | _ -> fail()
// Map.tryFind moduleName ReplacementsInject.fableReplacementsModules
// |> Option.bind (Map.tryFind methName)
// |> function
// | None -> args
// | Some injectInfo -> injectArgInner args injectInfo
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 = 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
| "isDotnet" -> makeBoolConst false |> Some
| "isJavaScript" -> makeBoolConst (com.Options.Language = JavaScript) |> Some
| "isTypeScript" -> makeBoolConst (com.Options.Language = TypeScript) |> Some
| "isPython" -> makeBoolConst (com.Options.Language = Python) |> Some
| "isDart" -> makeBoolConst (com.Options.Language = Dart) |> Some
| "isRust" -> makeBoolConst (com.Options.Language = Rust) |> Some
| "isPhp" -> makeBoolConst (com.Options.Language = Php) |> Some
| "isBeam" -> makeBoolConst (com.Options.Language = Beam) |> Some
| _ -> None
| "Fable.Core.RustInterop", "op_BangHat" -> List.tryHead args
| "Fable.Core.RustInterop", _ ->
match i.CompiledName, args with
| "emitRustExpr", [ args; RequireStringConstOrTemplate com ctx r template ] ->
let args = destructureTupleArgs [ args ]
emitTemplate r t args false template |> Some
| _ -> None
| "Fable.Core.Rust", _ ->
match i.CompiledName, args with
| "import", [ RequireStringConst com ctx r selector; RequireStringConst com ctx r path ] ->
makeImportUserGenerated r t selector path |> Some
| "importAll", [ RequireStringConst com ctx r path ] -> makeImportUserGenerated r t "*" path |> Some
| _ -> None
| _ -> None
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 getMemberName isStatic (i: CallInfo) =
let memberName = i.CompiledName |> FSharp2Fable.Helpers.cleanNameAsRustIdentifier
if String.IsNullOrEmpty(i.OverloadSuffix) then
memberName
else
let sep =
if isStatic then
"__"
else
"_"
memberName + sep + i.OverloadSuffix
let getModuleAndMemberName (i: CallInfo) (thisArg: Expr option) =
let isStatic = Option.isNone thisArg
let entFullName = i.DeclaringEntityFullName.Replace("Microsoft.", "")
let pos = entFullName.LastIndexOf('.')
let moduleName = entFullName.Substring(0, pos)
let entityName =
entFullName.Substring(pos + 1) |> FSharp2Fable.Helpers.cleanNameAsRustIdentifier
let memberName =
if isStatic then
entityName + "::" + (getMemberName isStatic i)
else
getMemberName isStatic i
moduleName, memberName
let bclType (com: ICompiler) (ctx: Context) r t (i: CallInfo) (thisArg: Expr option) (args: Expr list) =
match thisArg with
| Some callee ->
let memberName = getMemberName false i
makeInstanceCall r t i callee memberName args |> Some
| None ->
let moduleName, memberName = getModuleAndMemberName i thisArg
makeStaticLibCall com r t i moduleName memberName args |> Some
let fsharpModule (com: ICompiler) (ctx: Context) r (t: Type) (i: CallInfo) (thisArg: Expr option) (args: Expr list) =
let moduleName, memberName = getModuleAndMemberName i thisArg
Helper.LibCall(com, moduleName, memberName, t, args, i.SignatureArgTypes, ?loc = r)
|> Some
let makeRustFormatString interpolated (fmt: string) =
let pattern1 = @"([^%]?)%([0+\- ]*)(\*|\d+)?(\.\d+)?(\w)"
let pattern2 = @"([^%]?)%([0+\- ]*)(\*|\d+)?(\.\d+)?(?:P\(\)|(\w)(?:%P\(\))?)"
let pattern =
if interpolated then
pattern2
else
pattern1
let input = fmt.Replace("{", "{{").Replace("}", "}}").Replace("%%", "%")
let formatFlags (flags: string) =
let sign =
if flags.Contains("+") then
"+"
else
""
if flags.Contains("-") then
"<" + sign // left-align
elif flags.Contains("0") then
sign + "0" // zero padded
else
sign
let mutable argCount = 0
let rustFmt =
Regex.Replace(
input,
pattern,
fun m ->
argCount <- argCount + 1
let g1 = m.Groups[1].Value
let g2 = m.Groups[2].Value |> formatFlags
let g3 = m.Groups[3].Value.Replace("*", "$") // width parameter
let g4 = m.Groups[4].Value
let g5 = m.Groups[5].Value
let g4 =
if String.IsNullOrEmpty(g4) && (g5 = "f" || g5 = "F") then
".6"
else
g4
let g5 =
match g5 with
| "A" -> "?"
| "B" -> "b"
| ("b" | "c" | "d" | "i" | "s" | "u") -> ""
| ("o" | "x" | "X" | "e" | "E") as t -> t
| _ -> ""
let argFmt =
let formatting = g2 + g3 + g4 + g5
if String.IsNullOrEmpty(formatting) then
g1 + "{}"
else
g1 + "{:" + formatting + "}"
argFmt
)
rustFmt, argCount
let makeRustFormatExpr com r t (fmt: string) args macro =
let macroExpr = Helper.LibValue(com, "String", macro, Any)
let rustFmt, argCount = makeRustFormatString false fmt
let argCount = argCount + 1 + (List.length args) // +1 is for fmt
let applied = Extended(Curry(macroExpr, argCount), r)
let unboxedArgs = args |> FSharp2Fable.Util.unboxBoxedArgs
curriedApply r t applied (unboxedArgs @ [ emitRawString rustFmt ])
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, _ ->
// callee |> Some //TODO:
| ("PrintFormatToString" | "PrintFormatToStringThen"), None, [ StringConst fmt ] ->
"sprintf!" |> makeRustFormatExpr com r t fmt [] |> Some
| ("PrintFormatToString" | "PrintFormatToStringThen"), None, [ MaybeCasted(template) ] -> template |> Some
| ("PrintFormatThen" | "PrintFormatToStringThen"), None, [ cont; StringConst fmt ] ->
"kprintf!" |> makeRustFormatExpr com r t fmt [ cont ] |> Some
| ("PrintFormatThen" | "PrintFormatToStringThen"), None, [ cont; MaybeCasted(template) ] ->
Helper.Application(cont, t, [ template ], ?loc = r) |> Some
| "PrintFormatToError", None, [ StringConst fmt ] -> "eprintf!" |> makeRustFormatExpr com r t fmt [] |> Some
| "PrintFormatToError", None, _ -> "eprintf!" |> emitFormat com r t args |> Some
| "PrintFormatLineToError", None, [ StringConst fmt ] -> "eprintfn!" |> makeRustFormatExpr com r t fmt [] |> Some
| "PrintFormatLineToError", None, _ -> "eprintfn!" |> emitFormat com r t args |> Some
| "PrintFormat", None, [ StringConst fmt ] -> "printf!" |> makeRustFormatExpr com r t fmt [] |> Some
| "PrintFormat", None, _ -> "printf!" |> emitFormat com r t args |> Some
| "PrintFormatLine", None, [ StringConst fmt ] -> "printfn!" |> makeRustFormatExpr com r t fmt [] |> Some
| "PrintFormatLine", None, _ -> "printfn!" |> emitFormat com r t args |> Some
| "PrintFormatToTextWriter", None, [ StringConst fmt ] -> "printf!" |> makeRustFormatExpr com r t fmt [] |> Some
| "PrintFormatToTextWriter", None, _ -> "printf!" |> emitFormat com r t args |> Some
| "PrintFormatLineToTextWriter", None, [ StringConst fmt ] ->
"printfn!" |> makeRustFormatExpr com r t fmt [] |> Some
| "PrintFormatLineToTextWriter", None, _ -> "printfn!" |> emitFormat com r t args |> Some
| "PrintFormatToStringThenFail", None, [ StringConst fmt ] ->
"failwithf!" |> makeRustFormatExpr com r t fmt [] |> Some
| "PrintFormatToStringThenFail", None, _ -> "failwithf!" |> emitFormat com r t args |> Some
| "PrintFormatToStringBuilder", None, [ sb; StringConst fmt ] ->
let cont = Helper.LibCall(com, "Util", "bprintf", t, [ sb ])
"kprintf!" |> makeRustFormatExpr com r t fmt [ cont ] |> Some
| "PrintFormatToStringBuilder", None, [ sb; MaybeCasted(template) ] ->
let cont = Helper.LibCall(com, "Util", "bprintf", t, [ sb ])
Helper.Application(cont, t, [ template ], ?loc = r) |> Some
| "PrintFormatToStringBuilderThen", None, [ cont; sb; StringConst fmt ] ->
let cont = Helper.LibCall(com, "Util", "kbprintf", t, [ cont; sb ])
"kprintf!" |> makeRustFormatExpr com r t fmt [ cont ] |> Some
| "PrintFormatToStringBuilderThen", None, [ cont; sb; MaybeCasted(template) ] ->
let cont = Helper.LibCall(com, "Util", "kbprintf", t, [ cont; sb ])
Helper.Application(cont, t, [ template ], ?loc = r) |> Some
| ".ctor", _, (StringConst fmt) :: (Value(NewArray(ArrayValues templateArgs, _, _), _)) :: _ ->
let rustFmt, _argCount = makeRustFormatString true fmt
let unboxedArgs = templateArgs |> FSharp2Fable.Util.unboxBoxedArgs
StringTemplate(None, [ rustFmt ], unboxedArgs) |> makeValue r |> Some
| ".ctor", _, [ format ] -> format |> Some // just passing along the format
| _ -> None
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
match args with
| thisArg :: restArgs -> makeInstanceCall r t i thisArg meth restArgs
| _ -> "Missing argument." |> addErrorAndReturnNull com ctx.InlinePath r
match i.CompiledName, args with
| ("DefaultArg" | "DefaultValueArg"), [ opt; defValue ] ->
match opt with
| MaybeInScope ctx (Value(NewOption(opt, _, _), _)) ->
match opt with
| Some value -> Some value
| None -> Some defValue
| _ ->
Helper.LibCall(com, "Option", "defaultArg", t, args, i.SignatureArgTypes, ?loc = r)
|> Some
| "DefaultAsyncBuilder", _ -> makeImportLib com t "singleton" "AsyncBuilder" |> Some
// Erased operators.
// Rust compiles KeyValuePair as a struct tuple, but the KeyValue active pattern expects a regular tuple.
| "KeyValuePattern", [ arg ] ->
match arg.Type with
| Builtin(BclKeyValuePair(keyType, valueType)) ->
makeTuple r false [ Get(arg, TupleIndex 0, keyType, r); Get(arg, TupleIndex 1, valueType, r) ]
|> Some
| _ -> TypeCast(arg, t) |> Some
| ("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", _ -> Value(UnitConstant, r) |> Some
// Number and String conversions
| ("ToSByte" | "ToByte" | "ToInt8" | "ToUInt8" | "ToInt16" | "ToUInt16" | "ToInt" | "ToUInt" | "ToInt32" | "ToUInt32" | "ToInt64" | "ToUInt64" | "ToIntPtr" | "ToUIntPtr"),
[ arg ] -> convertTo com ctx r t args |> Some
| ("ToSingle" | "ToDouble" | "ToDecimal"), [ arg ] -> convertTo com ctx r t args |> Some
| "ToChar", [ arg ] -> convertTo com ctx r t args |> Some
| "ToString", _ -> toString com ctx r args |> Some
| "CreateSequence", [ xs ] -> toSeq com t xs |> Some
| ("CreateDictionary" | "CreateReadOnlyDictionary"), [ arg ] ->
Helper.LibCall(com, "HashMap", "new_from_tuple_array", t, [ toArray com t arg ])
|> Some
| "CreateSet", _ -> (genArg com ctx r 0 i.GenericArgs) |> makeSet com ctx r t args |> 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 meth, args =
match genArg with
| Char -> "rangeChar", args
| _ -> "rangeNumeric", addStep args
Helper.LibCall(com, "Range", meth, t, args, i.SignatureArgTypes, ?loc = r)
|> Some
// Pipes and composition
| "op_PipeRight", [ x; f ]