-
Notifications
You must be signed in to change notification settings - Fork 328
Expand file tree
/
Copy pathReplacements.fs
More file actions
5738 lines (5488 loc) · 261 KB
/
Copy pathReplacements.fs
File metadata and controls
5738 lines (5488 loc) · 261 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.Beam.Replacements
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 private physicalEquals r (left: Expr) (right: Expr) =
emitExpr r Boolean [ left; right ] "($0 =:= $1)"
// Use fable_comparison:equals/2 for structural equality.
// This handles ref-wrapped arrays (process dict refs) by dereferencing
// before comparison, so structural equality works correctly.
let private equals (com: ICompiler) r equal (left: Expr) (right: Expr) =
let eqCall =
match left.Type with
// ResizeArray (System.Collections.Generic.List) uses reference equality in .NET, see #3718.
// Two distinct refs are never =:=, so this matches .NET semantics directly.
| Array(_, ResizeArray) -> physicalEquals r left right
| _ -> Helper.LibCall(com, "fable_comparison", "equals", Boolean, [ left; right ], ?loc = r)
if equal then
eqCall
else
Operation(Unary(UnaryNot, eqCall), Tags.empty, Boolean, r)
let private compare (com: ICompiler) r (left: Expr) (right: Expr) =
Helper.LibCall(com, "fable_comparison", "compare", Number(Int32, NumberInfo.Empty), [ left; right ], ?loc = r)
/// Deref an array ref to its underlying list (for passing to list BIFs).
/// Byte arrays (UInt8) are atomics — convert to list via fable_utils:byte_array_to_list.
let private derefArr r (expr: Expr) =
match expr.Type with
| Array(Type.Number(UInt8, _), _) -> emitExpr r (List Any) [ expr ] "fable_utils:byte_array_to_list($0)"
| Array _ -> emitExpr r (List Any) [ expr ] "erlang:get($0)"
| _ -> expr
/// Wrap a plain list result as an array ref.
/// Byte arrays become atomics via fable_utils:new_byte_array. Non-array types pass through.
let private wrapArr (com: ICompiler) r (t: Type) (expr: Expr) =
match t with
| Array(Type.Number(UInt8, _), _) -> Helper.LibCall(com, "fable_utils", "new_byte_array", t, [ expr ], ?loc = r)
| Array _ -> Helper.LibCall(com, "fable_utils", "new_ref", t, [ expr ], ?loc = r)
| _ -> expr
let private 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 private fsFormat
(com: ICompiler)
(_ctx: Context)
r
(t: Type)
(i: CallInfo)
(_thisArg: Expr option)
(args: Expr list)
=
match i.CompiledName, _thisArg, args with
| "get_Value", Some callee, _ -> emitExpr r t [ callee ] "maps:get(input, $0)" |> Some
| "PrintFormatToString", _, _ ->
match args with
| [ template ] when template.Type = String -> Some template
| _ ->
Helper.LibCall(com, "fable_string", "to_text", t, args, i.SignatureArgTypes, ?loc = r)
|> Some
| "PrintFormatLine", _, _ ->
Helper.LibCall(com, "fable_string", "to_console", t, args, i.SignatureArgTypes, ?loc = r)
|> Some
| "PrintFormat", _, _ ->
Helper.LibCall(com, "fable_string", "to_console", t, args, i.SignatureArgTypes, ?loc = r)
|> Some
| ("PrintFormatToError" | "PrintFormatLineToError"), _, _ ->
Helper.LibCall(com, "fable_string", "to_console_error", t, args, i.SignatureArgTypes, ?loc = r)
|> Some
| "PrintFormatToStringThenFail", _, _ ->
Helper.LibCall(com, "fable_string", "to_fail", t, args, i.SignatureArgTypes, ?loc = r)
|> Some
| "PrintFormatToStringThen", _, _ ->
match args with
| [ _ ] ->
Helper.LibCall(com, "fable_string", "to_text", t, args, i.SignatureArgTypes, ?loc = r)
|> Some
| [ cont; fmt ] -> emitExpr r t [ fmt; cont ] "(maps:get(cont, $0))($1)" |> Some
| _ -> None
| "PrintFormatThen", _, arg :: callee :: _ -> emitExpr r t [ callee; arg ] "(maps:get(cont, $0))($1)" |> Some
| ".ctor", _, str :: (Value(NewArray(ArrayValues templateArgs, _, _), _) as values) :: _ ->
match makeStringTemplateFrom [| "%s"; "%i" |] templateArgs str with
| Some v -> makeValue r v |> Some
| None ->
Helper.LibCall(com, "fable_string", "interpolate", t, [ str; values ], i.SignatureArgTypes, ?loc = r)
|> Some
| ".ctor", _, arg :: _ ->
Helper.LibCall(com, "fable_string", "printf", t, [ arg ], i.SignatureArgTypes, ?loc = r)
|> Some
| _ -> None
let private operators
(com: ICompiler)
(ctx: Context)
r
(_t: Type)
(info: CallInfo)
(_thisArg: Expr option)
(args: Expr list)
=
match info.CompiledName, args with
| ("DefaultArg" | "DefaultValueArg"), [ opt; defValue ] ->
Helper.LibCall(com, "fable_option", "default_value", _t, [ opt; defValue ])
|> Some
| "FailWith", [ msg ]
| "InvalidOp", [ msg ] -> makeThrow r _t msg |> Some
| "InvalidArg", [ argName; msg ] ->
let msg =
add msg (add (add (Value(StringConstant " (Parameter '", None)) argName) (Value(StringConstant "')", None)))
makeThrow r _t msg |> Some
| "Raise", [ arg ] -> makeThrow r _t arg |> Some
| "NullArg", [ arg ] ->
let msg =
add
(Value(StringConstant "Value cannot be null. (Parameter '", None))
(add arg (Value(StringConstant "')", None)))
makeThrow r _t msg |> Some
| "IsNull", [ arg ] -> emitExpr r _t [ arg ] "($0 =:= undefined)" |> Some
| "IsNotNull", [ arg ] -> emitExpr r _t [ arg ] "($0 =/= undefined)" |> Some
// Nullable active patterns and helpers
| "NullMatchPattern", [ arg ] ->
// Returns {0, ok} (Some(())) if null, {1} (None) otherwise
emitExpr r _t [ arg ] "case $0 of undefined -> {0, ok}; _ -> {1} end" |> Some
| ("NonNull" | "NonNullV"), [ arg ] -> Some arg // Identity - just return the value
| ("NonNullQuickPattern" | "NonNullQuickValuePattern"), [ arg ] ->
// Returns {0, x} (Some(x)) if non-null, {1} (None) otherwise
emitExpr r _t [ arg ] "case $0 of undefined -> {1}; X___ -> {0, X___} end"
|> Some
| "NullValueMatchPattern", [ arg ] -> emitExpr r _t [ arg ] "case $0 of undefined -> {0, ok}; _ -> {1} end" |> Some
| ("WithNull" | "WithNullV"), [ arg ] -> Some arg // Identity
| "NullV", [] -> Value(Null _t, r) |> Some
| ("IsNullV"), [ arg ] -> emitExpr r _t [ arg ] "($0 =:= undefined)" |> Some
| "NullArgCheck", [ argName; arg ] ->
emitExpr
r
_t
[ argName; arg ]
"case $1 of undefined -> erlang:error({badarg, <<\"Value cannot be null. (Parameter '\", $0/binary, \"')\">>}); _ -> $1 end"
|> Some
// Lock — no-op in Erlang (processes are isolated), just call the action
| "Lock", [ _lockObj; action ] -> CurriedApply(action, [ Value(UnitConstant, None) ], _t, r) |> Some
// Using — resource disposal
| "Using", [ resource; action ] ->
// try action(resource) finally resource.Dispose()
Helper.LibCall(com, "fable_utils", "using", _t, [ resource; action ], ?loc = r)
|> Some
// Failure — create exception from message
| "Failure", [ msg ] -> emitExpr r _t [ msg ] "#{message => $0}" |> Some
| "FailurePattern", [ exn ] -> emitExpr r _t [ exn ] "maps:get(message, $0, $0)" |> Some
// LazyPattern — force a lazy value
| "LazyPattern", [ arg ] -> Helper.LibCall(com, "fable_utils", "force_lazy", _t, [ arg ], ?loc = r) |> Some
| "Hash", [ arg ] -> Helper.LibCall(com, "fable_comparison", "hash", _t, [ arg ], ?loc = r) |> Some
| "Compare", [ left; right ] -> compare com r left right |> Some
// Math operators
| "Abs", [ arg ] -> emitExpr r _t [ arg ] "erlang:abs($0)" |> Some
| "Acos", [ arg ] -> emitExpr r _t [ arg ] "math:acos($0)" |> Some
| "Asin", [ arg ] -> emitExpr r _t [ arg ] "math:asin($0)" |> Some
| "Atan", [ arg ] -> emitExpr r _t [ arg ] "math:atan($0)" |> Some
| "Atan2", [ y; x ] -> emitExpr r _t [ y; x ] "math:atan2($0, $1)" |> Some
| "Ceiling", [ arg ] ->
match arg.Type with
| Type.Number(Decimal, _) ->
Helper.LibCall(com, "fable_decimal", "ceil_decimal", _t, [ arg ], ?loc = r)
|> Some
| _ -> emitExpr r _t [ arg ] "float(erlang:ceil($0))" |> Some
| "Cos", [ arg ] -> emitExpr r _t [ arg ] "math:cos($0)" |> Some
| "Exp", [ arg ] -> emitExpr r _t [ arg ] "math:exp($0)" |> Some
| "Floor", [ arg ] ->
match arg.Type with
| Type.Number(Decimal, _) ->
Helper.LibCall(com, "fable_decimal", "floor_decimal", _t, [ arg ], ?loc = r)
|> Some
| _ -> emitExpr r _t [ arg ] "float(erlang:floor($0))" |> Some
| "Log", [ arg ] -> emitExpr r _t [ arg ] "math:log($0)" |> Some
| "Log10", [ arg ] -> emitExpr r _t [ arg ] "math:log10($0)" |> Some
| "Log2", [ arg ] -> emitExpr r _t [ arg ] "math:log2($0)" |> Some
| ("Pow" | "PowInteger" | "op_Exponentiation"), [ base_; exp_ ] ->
match base_.Type with
| Type.Number(Decimal, _) ->
Helper.LibCall(com, "fable_decimal", "pown", _t, [ base_; exp_ ], ?loc = r)
|> Some
| _ -> emitExpr r _t [ base_; exp_ ] "math:pow($0, $1)" |> Some
| "Round", [ arg ] ->
match arg.Type with
| Type.Number(Decimal, _) ->
Helper.LibCall(com, "fable_decimal", "round_decimal", _t, [ arg ], ?loc = r)
|> Some
| _ -> emitExpr r _t [ arg ] "float(erlang:round($0))" |> Some
| "Round", [ arg; digits ] ->
match arg.Type with
| Type.Number(Decimal, _) ->
Helper.LibCall(com, "fable_decimal", "round_decimal", _t, [ arg; digits ], ?loc = r)
|> Some
| _ ->
emitExpr r _t [ arg; digits ] "(erlang:round($0 * math:pow(10, $1)) / math:pow(10, $1))"
|> Some
| "Sign", [ arg ] ->
emitExpr r _t [ arg ] "case $0 > 0 of true -> 1; false -> case $0 < 0 of true -> -1; false -> 0 end end"
|> Some
| "Sin", [ arg ] -> emitExpr r _t [ arg ] "math:sin($0)" |> Some
| "Sqrt", [ arg ] -> emitExpr r _t [ arg ] "math:sqrt($0)" |> Some
| "Tan", [ arg ] -> emitExpr r _t [ arg ] "math:tan($0)" |> Some
| "Cosh", [ arg ] -> emitExpr r _t [ arg ] "math:cosh($0)" |> Some
| "Sinh", [ arg ] -> emitExpr r _t [ arg ] "math:sinh($0)" |> Some
| "Tanh", [ arg ] -> emitExpr r _t [ arg ] "math:tanh($0)" |> Some
| "Truncate", [ arg ] ->
match arg.Type with
| Type.Number(Decimal, _) ->
Helper.LibCall(com, "fable_decimal", "truncate_decimal", _t, [ arg ], ?loc = r)
|> Some
| _ -> emitExpr r _t [ arg ] "float(trunc($0))" |> Some
| ("Max" | "Max_"), [ a; b ] -> emitExpr r _t [ a; b ] "erlang:max($0, $1)" |> Some
| ("Min" | "Min_"), [ a; b ] -> emitExpr r _t [ a; b ] "erlang:min($0, $1)" |> Some
| "Clamp", [ value; min_; max_ ] -> emitExpr r _t [ value; min_; max_ ] "erlang:min(erlang:max($0, $1), $2)" |> Some
| "Log", [ x; base_ ] -> emitExpr r _t [ x; base_ ] "(math:log($0) / math:log($1))" |> Some
| "DivRem", [ x; y ] -> emitExpr r _t [ x; y ] "{$0 div $1, $0 rem $1}" |> Some
| "DivRem", [ x; y; refRem ] ->
Helper.LibCall(com, "fable_utils", "div_rem", _t, [ x; y; refRem ], ?loc = r)
|> Some
| "MinMagnitude", [ a; b ] ->
emitExpr r _t [ a; b ] "case erlang:abs($0) =< erlang:abs($1) of true -> $0; false -> $1 end"
|> Some
| "MaxMagnitude", [ a; b ] ->
emitExpr r _t [ a; b ] "case erlang:abs($0) >= erlang:abs($1) of true -> $0; false -> $1 end"
|> Some
| (Operators.equality | "Eq"), [ left; right ] -> equals com r true left right |> Some
| (Operators.inequality | "Neq"), [ left; right ] -> equals com r false left right |> Some
| (Operators.lessThan | "Lt"), [ left; right ] -> makeBinOp r Boolean left right BinaryLess |> Some
| (Operators.lessThanOrEqual | "Lte"), [ left; right ] -> makeBinOp r Boolean left right BinaryLessOrEqual |> Some
| (Operators.greaterThan | "Gt"), [ left; right ] -> makeBinOp r Boolean left right BinaryGreater |> Some
| (Operators.greaterThanOrEqual | "Gte"), [ left; right ] ->
makeBinOp r Boolean left right BinaryGreaterOrEqual |> Some
| Operators.unaryNegation, [ operand ] -> Operation(Unary(UnaryMinus, operand), Tags.empty, _t, r) |> Some
// Type conversions: int(x), float(x), string(x), etc.
| ("ToSByte" | "ToByte" | "ToInt8" | "ToUInt8" | "ToInt16" | "ToUInt16" | "ToInt" | "ToUInt" | "ToInt32" | "ToUInt32" | "ToInt64" | "ToUInt64" | "ToIntPtr" | "ToUIntPtr"),
[ arg ] ->
match arg.Type with
| Type.String -> Helper.LibCall(com, "fable_convert", "to_int", _t, [ arg ], ?loc = r) |> Some
| Type.Number(kind, _) ->
match kind with
| Decimal -> Helper.LibCall(com, "fable_decimal", "to_int", _t, [ arg ], ?loc = r) |> Some
| Float16
| Float32
| Float64 -> emitExpr r _t [ arg ] "trunc($0)" |> Some
| _ -> Some arg
| Type.Char -> Some arg
| _ -> Some arg
| ("ToSingle" | "ToDouble"), [ arg ] ->
match arg.Type with
| Type.String -> Helper.LibCall(com, "fable_convert", "to_float", _t, [ arg ]) |> Some
| Type.Number(kind, _) ->
match kind with
| Decimal -> Helper.LibCall(com, "fable_decimal", "to_number", _t, [ arg ], ?loc = r) |> Some
| Float16
| Float32
| Float64 -> Some arg
| _ -> emitExpr r _t [ arg ] "float($0)" |> Some
| _ -> emitExpr r _t [ arg ] "float($0)" |> Some
| "ToDecimal", [ arg ] ->
match arg.Type with
| Type.String -> Helper.LibCall(com, "fable_decimal", "parse", _t, [ arg ], ?loc = r) |> Some
| Type.Number(kind, _) ->
match kind with
| Decimal -> Some arg
| Float16
| Float32
| Float64 ->
// float → fixed-scale: trunc(x * 10^28)
emitExpr r _t [ arg ] "trunc($0 * 10000000000000000000000000000)" |> Some
| _ ->
// int → fixed-scale: x * 10^28
emitExpr r _t [ arg ] "($0 * 10000000000000000000000000000)" |> Some
| _ -> emitExpr r _t [ arg ] "($0 * 10000000000000000000000000000)" |> Some
| "ToString", [ arg ] ->
match arg.Type with
| Type.String -> Some arg
| Type.Char -> emitExpr r _t [ arg ] "<<($0)/utf8>>" |> Some
| Type.Number(kind, _) ->
match kind with
| Decimal -> Helper.LibCall(com, "fable_decimal", "to_string", _t, [ arg ], ?loc = r) |> Some
| Float16
| Float32
| Float64 -> Helper.LibCall(com, "fable_convert", "to_string", _t, [ arg ], ?loc = r) |> Some
| _ -> emitExpr r _t [ arg ] "integer_to_binary($0)" |> Some
| Type.Boolean -> emitExpr r _t [ arg ] "atom_to_binary($0)" |> Some
| _ -> Helper.LibCall(com, "fable_convert", "to_string", _t, [ arg ], ?loc = r) |> Some
| "ToChar", [ arg ] ->
match arg.Type with
| Type.String -> emitExpr r _t [ arg ] "binary:first($0)" |> Some
| _ -> Some arg
// CreateSet: the `set [1;2;3]` syntax
| "CreateSet", [ arg ] -> emitExpr r _t [ arg ] "ordsets:from_list($0)" |> Some
// CreateDictionary: the `dict [...]` syntax
| ("CreateDictionary" | "CreateReadOnlyDictionary"), [ arg ] ->
Helper.LibCall(com, "fable_dictionary", "create_from_list", _t, [ arg ], ?loc = r)
|> Some
// Range operators: [start..stop] and [start..step..stop]
| ("op_Range" | "op_RangeStep"), _ ->
let genArg = genArg com ctx r 0 info.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", "range_char", args
| Number(Decimal, _) -> "range", "range_decimal", addStep args
| Number(Int32, _) -> "range", "range_int32", addStep args
| Number(UInt32, _) -> "range", "range_u_int32", addStep args
| Number(Int64, _) -> "range", "range_int64", addStep args
| Number(UInt64, _) -> "range", "range_u_int64", addStep args
| Number(BigInt, _) -> "range", "range_big_int", addStep args
| _ -> "range", "range_double", addStep args
Helper.LibCall(com, modul, meth, _t, args, info.SignatureArgTypes, ?loc = r)
|> Some
// Erlang has native arbitrary-precision integers, so Int64/UInt64/BigInt
// use direct binary ops instead of library calls (like Python's int)
// Bitwise operators — Erlang has native bitwise support for all integer sizes
| Operators.booleanOr, [ left; right ] -> emitExpr r _t [ left; right ] "($0 orelse $1)" |> Some
| Operators.booleanAnd, [ left; right ] -> emitExpr r _t [ left; right ] "($0 andalso $1)" |> Some
| Operators.bitwiseAnd, [ left; right ] -> emitExpr r _t [ left; right ] "($0 band $1)" |> Some
| Operators.bitwiseOr, [ left; right ] -> emitExpr r _t [ left; right ] "($0 bor $1)" |> Some
| Operators.exclusiveOr, [ left; right ] -> emitExpr r _t [ left; right ] "($0 bxor $1)" |> Some
| Operators.leftShift, [ left; right ] -> emitExpr r _t [ left; right ] "($0 bsl $1)" |> Some
| Operators.rightShift, [ left; right ] -> emitExpr r _t [ left; right ] "($0 bsr $1)" |> Some
| Operators.logicalNot, [ operand ] -> emitExpr r _t [ operand ] "(bnot $0)" |> Some
// Erlang has native arbitrary-precision integers, so Int64/UInt64/BigInt
// use direct binary ops instead of library calls
// Ref cells: ref, !, :=, incr, decr
| "op_Dereference", [ arg ] -> emitExpr r _t [ arg ] "get($0)" |> Some
| "op_ColonEquals", [ o; v ] -> emitExpr r Unit [ o; v ] "put($0, $1)" |> Some
| "Ref", [ arg ] -> Helper.LibCall(com, "fable_utils", "new_ref", Any, [ arg ], ?loc = r) |> Some
| ("Increment" | "Decrement"), [ arg ] ->
// incr x → put(x, get(x) + 1); decr x → put(x, get(x) - 1)
let delta =
if info.CompiledName = "Increment" then
"1"
else
"-1"
emitExpr r _t [ arg ] $"put($0, get($0) + %s{delta})" |> Some
// Erased operators — Beam doesn't need special treatment
| ("KeyValuePattern" | "Identity" | "Box" | "Unbox" | "ToEnum"), [ arg ] -> TypeCast(arg, _t) |> Some
| "Ignore", _ -> Sequential [ args.Head; Value(UnitConstant, None) ] |> Some
| "CreateSequence", [ xs ] -> TypeCast(xs, _t) |> Some
// Pipes and composition
| "op_PipeRight", [ x; f ]
| "op_PipeLeft", [ f; x ] -> CurriedApply(f, [ x ], _t, r) |> Some
| "op_PipeRight2", [ x; y; f ]
| "op_PipeLeft2", [ f; x; y ] -> CurriedApply(f, [ x; y ], _t, r) |> Some
| "op_PipeRight3", [ x; y; z; f ]
| "op_PipeLeft3", [ f; x; y; z ] -> CurriedApply(f, [ x; y; z ], _t, r) |> Some
| "op_ComposeRight", [ f1; f2 ] -> compose com ctx r _t f1 f2 |> Some
| "op_ComposeLeft", [ f2; f1 ] -> compose com ctx r _t f1 f2 |> Some
// Not (boolean negation)
| "Not", [ operand ] -> makeUnOp r _t operand UnaryNot |> Some
// Tuples
| "Fst", [ tup ] -> Get(tup, TupleIndex 0, _t, r) |> Some
| "Snd", [ tup ] -> Get(tup, TupleIndex 1, _t, r) |> Some
// List append
| "op_Append", [ left; right ] -> emitExpr r _t [ left; right ] "($0 ++ $1)" |> Some
// TypeOf: typeof<T> → TypeInfo
| "TypeOf", _ -> (genArg com ctx r 0 info.GenericArgs) |> makeTypeInfo r |> Some
// TypeDefOf: typedefof<T> → TypeInfo with generics replaced by obj
| "TypeDefOf", _ -> (genArg com ctx r 0 info.GenericArgs) |> makeTypeDefinitionInfo r |> Some
// Reraise
| "Reraise", _ ->
match ctx.CaughtException with
| Some ex -> makeThrow r _t (IdentExpr ex) |> Some
| None -> makeThrow r _t (Value(StringConstant "reraise", None)) |> Some
// Infinity and NaN — Erlang BEAM VM doesn't support IEEE 754 special float values.
// Use max finite float (1.7976931348623157e308) as practical stand-in for infinity.
| ("Infinity" | "InfinitySingle"), _ ->
com.WarnOnlyOnce(
"Erlang BEAM VM does not support IEEE 754 Infinity. Using max finite float as approximation. Arithmetic with this value may cause 'badarith' errors.",
?range = r
)
emitExpr r _t [] "1.7976931348623157e308" |> Some
| ("NaN" | "NaNSingle"), _ ->
com.WarnOnlyOnce(
"Erlang BEAM VM does not support IEEE 754 NaN. Using atom 'nan' as sentinel. Arithmetic with this value will fail.",
?range = r
)
emitExpr r _t [] "nan" |> Some
// Pow (for Double, via math:pow)
| "Pow", [ base_; exp_ ] -> emitExpr r _t [ base_; exp_ ] "math:pow($0, $1)" |> Some
| Patterns.SetContains Operators.standardSet, _ ->
let argTypes = args |> List.map (fun a -> a.Type)
match argTypes with
| Builtin(FSharpSet _) :: _ ->
match info.CompiledName, args with
| Operators.addition, [ left; right ] -> emitExpr r _t [ left; right ] "ordsets:union($0, $1)" |> Some
| Operators.subtraction, [ left; right ] -> emitExpr r _t [ left; right ] "ordsets:subtract($0, $1)" |> Some
| _ -> None
| Number((Int64 | UInt64 | Int128 | UInt128 | NativeInt | UNativeInt | BigInt), _) :: _ ->
match info.CompiledName, args with
| Operators.addition, [ left; right ] -> makeBinOp r _t left right BinaryPlus |> Some
| Operators.subtraction, [ left; right ] -> makeBinOp r _t left right BinaryMinus |> Some
| Operators.multiply, [ left; right ] -> makeBinOp r _t left right BinaryMultiply |> Some
| (Operators.division | Operators.divideByInt), [ left; right ] ->
makeBinOp r _t left right BinaryDivide |> Some
| Operators.modulus, [ left; right ] -> makeBinOp r _t left right BinaryModulus |> Some
| _ -> None
// String concatenation
| String :: _ ->
match info.CompiledName, args with
| Operators.addition, [ left; right ] -> add left right |> Some
| _ -> None
// Decimal: fixed-scale integer — +, -, rem work natively; *, / need library calls
| Number(Decimal, _) :: _ ->
match info.CompiledName, args with
| Operators.addition, [ left; right ] -> makeBinOp r _t left right BinaryPlus |> Some
| Operators.subtraction, [ left; right ] -> makeBinOp r _t left right BinaryMinus |> Some
| Operators.multiply, [ left; right ] ->
Helper.LibCall(com, "fable_decimal", "multiply", _t, [ left; right ], ?loc = r)
|> Some
| Operators.division, [ left; right ] ->
Helper.LibCall(com, "fable_decimal", "divide", _t, [ left; right ], ?loc = r)
|> Some
| Operators.divideByInt, [ left; right ] ->
Helper.LibCall(com, "fable_decimal", "divide_by_int", _t, [ left; right ], ?loc = r)
|> Some
| Operators.modulus, [ left; right ] -> makeBinOp r _t left right BinaryModulus |> Some
| _ -> None
// DateTime arithmetic: + and - need runtime library calls
| DeclaredType(ent, _) :: _ when ent.FullName = Types.datetime ->
match info.CompiledName, args with
| Operators.addition, [ left; right ] ->
Helper.LibCall(com, "fable_date", "op_addition", _t, [ left; right ], ?loc = r)
|> Some
| Operators.subtraction, [ left; right ] ->
Helper.LibCall(com, "fable_date", "op_subtraction", _t, [ left; right ], ?loc = r)
|> Some
| _ -> None
// Default: check for custom operator on DeclaredType, then fall back to native ops
| _ ->
let opName = info.CompiledName
match (|CustomOp|_|) com ctx r _t opName args argTypes with
| ValueSome e -> Some e
| ValueNone ->
match opName, args with
| Operators.addition, [ left; right ] -> makeBinOp r _t left right BinaryPlus |> Some
| Operators.subtraction, [ left; right ] -> makeBinOp r _t left right BinaryMinus |> Some
| Operators.multiply, [ left; right ] -> makeBinOp r _t left right BinaryMultiply |> Some
| (Operators.division | Operators.divideByInt), [ left; right ] ->
makeBinOp r _t left right BinaryDivide |> Some
| Operators.modulus, [ left; right ] -> makeBinOp r _t left right BinaryModulus |> Some
| Operators.unaryPlus, [ arg ] -> arg |> Some
| _ -> None
| "DefaultAsyncBuilder", _ ->
Helper.LibCall(com, "fable_async_builder", "singleton", _t, [], ?loc = r)
|> Some
| ("PrintFormatToString" | "PrintFormatToStringThen" | "PrintFormat" | "PrintFormatLine" | "PrintFormatToError" | "PrintFormatLineToError" | "PrintFormatThen" | "PrintFormatToStringThenFail"),
_ -> fsFormat com ctx r _t info _thisArg args
| _ -> None
let private languagePrimitives
(com: ICompiler)
(ctx: Context)
r
(t: Type)
(info: CallInfo)
(_thisArg: Expr option)
(args: Expr list)
=
match info.CompiledName, args with
| ("GenericEquality" | "GenericEqualityIntrinsic"), [ left; right ] -> equals com r true left right |> Some
| ("GenericEqualityER" | "GenericEqualityERIntrinsic"), [ left; right ] -> equals com r true left right |> Some
| ("GenericComparison" | "GenericComparisonIntrinsic"), [ left; right ] -> compare com r left right |> Some
| ("GenericLessThan" | "GenericLessThanIntrinsic"), [ left; right ] ->
let cmp = compare com r left right
makeBinOp r Boolean cmp (makeIntConst 0) BinaryLess |> Some
| ("GenericLessOrEqual" | "GenericLessOrEqualIntrinsic"), [ left; right ] ->
let cmp = compare com r left right
makeBinOp r Boolean cmp (makeIntConst 0) BinaryLessOrEqual |> Some
| ("GenericGreaterThan" | "GenericGreaterThanIntrinsic"), [ left; right ] ->
let cmp = compare com r left right
makeBinOp r Boolean cmp (makeIntConst 0) BinaryGreater |> Some
| ("GenericGreaterOrEqual" | "GenericGreaterOrEqualIntrinsic"), [ left; right ] ->
let cmp = compare com r left right
makeBinOp r Boolean cmp (makeIntConst 0) BinaryGreaterOrEqual |> Some
| ("PhysicalEquality" | "PhysicalEqualityIntrinsic"), [ left; right ] ->
emitExpr r Boolean [ left; right ] "$0 =:= $1" |> Some
| ("GenericHash" | "GenericHashIntrinsic"), [ arg ] ->
Helper.LibCall(com, "fable_comparison", "hash", t, [ arg ], ?loc = r) |> Some
| ("PhysicalHash" | "PhysicalHashIntrinsic"), [ arg ] ->
Helper.LibCall(com, "fable_comparison", "hash", t, [ arg ], ?loc = r) |> Some
// GenericZero/GenericOne
| "GenericZero", _ ->
match t with
| Number(Float64, _)
| Number(Float32, _)
| Number(Float16, _)
| Number(Decimal, _) -> makeFloatConst 0.0 |> Some
| _ -> makeIntConst 0 |> Some
| "GenericOne", _ ->
match t with
| Number(Float64, _)
| Number(Float32, _)
| Number(Float16, _)
| Number(Decimal, _) -> makeFloatConst 1.0 |> Some
| _ -> makeIntConst 1 |> Some
// Enum conversions (erased)
| "EnumOfValue", [ arg ]
| "EnumToValue", [ arg ] -> TypeCast(arg, t) |> Some
// Measure annotations (erased)
| ("SByteWithMeasure" | "Int16WithMeasure" | "Int32WithMeasure" | "Int64WithMeasure" | "Float32WithMeasure" | "FloatWithMeasure" | "DecimalWithMeasure"),
[ arg ] -> arg |> Some
// Dynamic operations — used by SRTP (statically resolved type parameters)
| Naming.EndsWith "Dynamic" operation, arg :: _ ->
let operation =
if operation = Operators.divideByInt then
operation
else
"op_" + operation
if operation = "op_Explicit" then
Some arg
else
let argTypes = args |> List.map (fun a -> a.Type)
// Check for custom operator on DeclaredType before falling back to native ops
match (|CustomOp|_|) com ctx r t operation args argTypes with
| ValueSome e -> Some e
| ValueNone ->
// For Dynamic ops, map to standard binary operations
match operation, args with
| "op_Addition", [ left; right ] -> makeBinOp r t left right BinaryPlus |> Some
| "op_Subtraction", [ left; right ] -> makeBinOp r t left right BinaryMinus |> Some
| "op_Multiply", [ left; right ] -> makeBinOp r t left right BinaryMultiply |> Some
| "op_Division", [ left; right ] -> makeBinOp r t left right BinaryDivide |> Some
| "op_Modulus", [ left; right ] -> makeBinOp r t left right BinaryModulus |> Some
| ("DivideByInt" | Operators.divideByInt), [ left; right ] ->
makeBinOp r t left right BinaryDivide |> Some
| "op_UnaryNegation", [ operand ] -> Operation(Unary(UnaryMinus, operand), Tags.empty, t, r) |> Some
| "op_BitwiseAnd", [ left; right ] -> emitExpr r t [ left; right ] "($0 band $1)" |> Some
| "op_BitwiseOr", [ left; right ] -> emitExpr r t [ left; right ] "($0 bor $1)" |> Some
| "op_ExclusiveOr", [ left; right ] -> emitExpr r t [ left; right ] "($0 bxor $1)" |> Some
| "op_LeftShift", [ left; right ] -> emitExpr r t [ left; right ] "($0 bsl $1)" |> Some
| "op_RightShift", [ left; right ] -> emitExpr r t [ left; right ] "($0 bsr $1)" |> Some
| "op_Explicit", [ arg ] -> Some arg
| _ -> None
| "DivideByInt", [ left; right ] -> makeBinOp r t left right BinaryDivide |> Some
// IntrinsicFunctions within LanguagePrimitives
| "UnboxFast", [ arg ] -> TypeCast(arg, t) |> Some
| ("ParseInt32" | "ParseUInt32"), [ arg ] ->
Helper.LibCall(com, "fable_convert", "to_int", t, [ arg ], ?loc = r) |> Some
| ("ParseInt64" | "ParseUInt64"), [ arg ] ->
Helper.LibCall(com, "fable_convert", "to_int", t, [ arg ], ?loc = r) |> Some
| _ -> None
let private unchecked
(com: ICompiler)
(_ctx: Context)
r
(t: Type)
(info: CallInfo)
(_thisArg: Expr option)
(args: Expr list)
=
match info.CompiledName, args with
| "DefaultOf", _ ->
let typ = genArg com _ctx r 0 info.GenericArgs
match typ with
| Boolean -> makeBoolConst false |> Some
| Number(kind, uom) -> NumberConstant(NumberValue.GetZero kind, uom) |> makeValue None |> Some
| Char -> CharConstant '\u0000' |> makeValue None |> Some
| String -> makeStrConst "" |> Some
| _ -> Value(Null typ, r) |> Some
| "Hash", [ arg ] -> Helper.LibCall(com, "fable_comparison", "hash", t, [ arg ], ?loc = r) |> Some
| "Equals", [ left; right ] -> equals com r true left right |> Some
| "Compare", [ left; right ] -> compare com r left right |> Some
| "NonNull", [ arg ] -> Some arg // Identity - unchecked non-null assertion
| _ -> None
/// Beam-specific System.Object replacements.
let private objects
(com: ICompiler)
(_ctx: Context)
r
(t: Type)
(info: CallInfo)
(thisArg: Expr option)
(args: Expr list)
=
match info.CompiledName, thisArg, args with
| ".ctor", _, _ -> emitExpr r t [] "ok" |> Some
| "ReferenceEquals", None, [ left; right ] -> physicalEquals r left right |> Some
| "Equals", Some(MaybeCasted arg1), [ MaybeCasted arg2 ]
| "Equals", None, [ MaybeCasted arg1; MaybeCasted arg2 ] ->
match arg1.Type, arg2.Type with
| Array _, _
| _, Array _ -> physicalEquals r arg1 arg2 |> Some
| _ -> equals com r true arg1 arg2 |> Some
| "GetHashCode", Some thisObj, [] ->
Helper.LibCall(com, "fable_comparison", "hash", t, [ thisObj ], ?loc = r)
|> Some
| "GetType", Some arg, _ -> makeTypeInfo r arg.Type |> Some
| "ToString", Some thisObj, [] ->
match thisObj.Type with
| Type.Char -> emitExpr r t [ thisObj ] "<<($0)/utf8>>" |> Some
| Type.Number(kind, _) ->
match kind with
| Decimal ->
Helper.LibCall(com, "fable_decimal", "to_string", t, [ thisObj ], ?loc = r)
|> Some
| Float16
| Float32
| Float64 ->
Helper.LibCall(com, "fable_convert", "to_string", t, [ thisObj ], ?loc = r)
|> Some
| _ -> emitExpr r t [ thisObj ] "integer_to_binary($0)" |> Some
| Type.Boolean -> emitExpr r t [ thisObj ] "atom_to_binary($0)" |> Some
| Type.String -> Some thisObj
| DeclaredType(ent, _) when ent.FullName = Types.timespan ->
Helper.LibCall(com, "fable_timespan", "to_string", t, [ thisObj ], ?loc = r)
|> Some
| DeclaredType(ent, _) when ent.FullName = Types.datetime ->
Helper.LibCall(com, "fable_date", "to_string", t, [ thisObj ], ?loc = r) |> Some
| DeclaredType(ent, _) when ent.FullName = "System.Uri" ->
Helper.LibCall(com, "fable_uri", "to_string", t, [ thisObj ], ?loc = r) |> Some
| DeclaredType(ent, _) when ent.FullName = "System.Text.StringBuilder" ->
// StringBuilder.ToString() → iolist_to_binary(get(maps:get(field_buf, get(Sb))))
emitExpr r t [ thisObj ] "iolist_to_binary(get(maps:get(field_buf, get($0))))"
|> Some
| _ ->
Helper.LibCall(com, "fable_convert", "to_string", t, [ thisObj ], ?loc = r)
|> Some
| _ -> None
/// Beam-specific System.ValueType replacements.
let private valueTypes
(com: ICompiler)
(_ctx: Context)
r
(t: Type)
(info: CallInfo)
(thisArg: Expr option)
(_args: Expr list)
=
match info.CompiledName, thisArg with
| "Equals", Some thisObj ->
match _args with
| [ arg ] -> equals com r true thisObj arg |> Some
| _ -> None
| "GetHashCode", Some thisObj ->
Helper.LibCall(com, "fable_comparison", "hash", t, [ thisObj ], ?loc = r)
|> Some
| "CompareTo", Some thisObj ->
match _args with
| [ arg ] -> compare com r thisObj arg |> Some
| _ -> None
| _ -> None
/// Beam-specific System.Char replacements.
/// Chars in Erlang are integers (Unicode codepoints).
let private chars
(com: ICompiler)
(_ctx: Context)
r
(t: Type)
(info: CallInfo)
(_thisArg: Expr option)
(args: Expr list)
=
match info.CompiledName, args with
| "ToUpper", [ c ] -> Helper.LibCall(com, "fable_char", "to_upper", t, [ c ]) |> Some
| "ToUpperInvariant", [ c ] -> Helper.LibCall(com, "fable_char", "to_upper", t, [ c ]) |> Some
| "ToLower", [ c ] -> Helper.LibCall(com, "fable_char", "to_lower", t, [ c ]) |> Some
| "ToLowerInvariant", [ c ] -> Helper.LibCall(com, "fable_char", "to_lower", t, [ c ]) |> Some
| "ToString", [ c ] -> Helper.LibCall(com, "fable_char", "to_string", t, [ c ]) |> Some
| "IsLetter", [ c ] -> Helper.LibCall(com, "fable_char", "is_letter", t, [ c ]) |> Some
| "IsLetter", [ str; idx ] ->
Helper.LibCall(com, "fable_char", "is_letter", t, [ emitExpr r Type.Char [ str; idx ] "binary:at($0, $1)" ])
|> Some
| "IsDigit", [ c ] -> Helper.LibCall(com, "fable_char", "is_digit", t, [ c ]) |> Some
| "IsDigit", [ str; idx ] ->
Helper.LibCall(com, "fable_char", "is_digit", t, [ emitExpr r Type.Char [ str; idx ] "binary:at($0, $1)" ])
|> Some
| "IsLetterOrDigit", [ c ] -> Helper.LibCall(com, "fable_char", "is_letter_or_digit", t, [ c ]) |> Some
| "IsLetterOrDigit", [ str; idx ] ->
Helper.LibCall(
com,
"fable_char",
"is_letter_or_digit",
t,
[ emitExpr r Type.Char [ str; idx ] "binary:at($0, $1)" ]
)
|> Some
| "IsUpper", [ c ] -> Helper.LibCall(com, "fable_char", "is_upper", t, [ c ]) |> Some
| "IsUpper", [ str; idx ] ->
Helper.LibCall(com, "fable_char", "is_upper", t, [ emitExpr r Type.Char [ str; idx ] "binary:at($0, $1)" ])
|> Some
| "IsLower", [ c ] -> Helper.LibCall(com, "fable_char", "is_lower", t, [ c ]) |> Some
| "IsLower", [ str; idx ] ->
Helper.LibCall(com, "fable_char", "is_lower", t, [ emitExpr r Type.Char [ str; idx ] "binary:at($0, $1)" ])
|> Some
| "IsNumber", [ c ] -> Helper.LibCall(com, "fable_char", "is_number", t, [ c ]) |> Some
| "IsNumber", [ str; idx ] ->
Helper.LibCall(com, "fable_char", "is_number", t, [ emitExpr r Type.Char [ str; idx ] "binary:at($0, $1)" ])
|> Some
| "IsWhiteSpace", [ c ] -> Helper.LibCall(com, "fable_char", "is_whitespace", t, [ c ]) |> Some
| "IsWhiteSpace", [ str; idx ] ->
Helper.LibCall(com, "fable_char", "is_whitespace", t, [ emitExpr r Type.Char [ str; idx ] "binary:at($0, $1)" ])
|> Some
| "IsControl", [ c ] -> Helper.LibCall(com, "fable_char", "is_control", t, [ c ]) |> Some
| "IsControl", [ str; idx ] ->
Helper.LibCall(com, "fable_char", "is_control", t, [ emitExpr r Type.Char [ str; idx ] "binary:at($0, $1)" ])
|> Some
| "IsPunctuation", [ c ] -> Helper.LibCall(com, "fable_char", "is_punctuation", t, [ c ]) |> Some
| "IsPunctuation", [ str; idx ] ->
Helper.LibCall(
com,
"fable_char",
"is_punctuation",
t,
[ emitExpr r Type.Char [ str; idx ] "binary:at($0, $1)" ]
)
|> Some
| "IsSeparator", [ c ] -> Helper.LibCall(com, "fable_char", "is_separator", t, [ c ]) |> Some
| "IsSeparator", [ str; idx ] ->
Helper.LibCall(com, "fable_char", "is_separator", t, [ emitExpr r Type.Char [ str; idx ] "binary:at($0, $1)" ])
|> Some
| "IsSymbol", [ c ] -> Helper.LibCall(com, "fable_char", "is_symbol", t, [ c ]) |> Some
| "IsSymbol", [ str; idx ] ->
Helper.LibCall(com, "fable_char", "is_symbol", t, [ emitExpr r Type.Char [ str; idx ] "binary:at($0, $1)" ])
|> Some
| "GetUnicodeCategory", [ c ] -> Helper.LibCall(com, "fable_char", "get_unicode_category", t, [ c ]) |> Some
| "GetUnicodeCategory", [ str; idx ] ->
Helper.LibCall(
com,
"fable_char",
"get_unicode_category",
t,
[ emitExpr r Type.Char [ str; idx ] "binary:at($0, $1)" ]
)
|> Some
| "Parse", [ str ] -> Helper.LibCall(com, "fable_char", "parse", t, [ str ]) |> Some
| "TryParse", _ -> Helper.LibCall(com, "fable_char", "try_parse", t, args, ?loc = r) |> Some
| "IsHighSurrogate", [ c ] -> Helper.LibCall(com, "fable_char", "is_high_surrogate", t, [ c ]) |> Some
| "IsHighSurrogate", [ str; idx ] ->
Helper.LibCall(
com,
"fable_char",
"is_high_surrogate",
t,
[ emitExpr r Type.Char [ str; idx ] "binary:at($0, $1)" ]
)
|> Some
| "IsLowSurrogate", [ c ] -> Helper.LibCall(com, "fable_char", "is_low_surrogate", t, [ c ]) |> Some
| "IsLowSurrogate", [ str; idx ] ->
Helper.LibCall(
com,
"fable_char",
"is_low_surrogate",
t,
[ emitExpr r Type.Char [ str; idx ] "binary:at($0, $1)" ]
)
|> Some
| "IsSurrogate", [ c ] -> Helper.LibCall(com, "fable_char", "is_surrogate", t, [ c ]) |> Some
| "IsSurrogate", [ str; idx ] ->
Helper.LibCall(com, "fable_char", "is_surrogate", t, [ emitExpr r Type.Char [ str; idx ] "binary:at($0, $1)" ])
|> Some
| "IsSurrogatePair", [ hi; lo ] when hi.Type = Type.Char ->
Helper.LibCall(com, "fable_char", "is_surrogate_pair", t, [ hi; lo ]) |> Some
| "IsSurrogatePair", [ str; idx ] ->
Helper.LibCall(
com,
"fable_char",
"is_surrogate_pair",
t,
[
emitExpr r Type.Char [ str; idx ] "binary:at($0, $1)"
emitExpr r Type.Char [ str; idx ] "binary:at($0, $1 + 1)"
]
)
|> Some
| _ -> None
/// Beam-specific string method replacements.
/// Erlang strings are UTF-8 binaries (<<>>), so we use binary module functions.
let private strings
(com: ICompiler)
(_ctx: Context)
r
(t: Type)
(info: CallInfo)
(thisArg: Expr option)
(args: Expr list)
=
match info.CompiledName, thisArg, args with
// String constructors: String(char[]), String(char, count), String(char[], start, length)
| ".ctor", _, fstArg :: _ ->
match fstArg.Type with
| Type.Char ->
match args with
| [ ch; count ] ->
Helper.LibCall(com, "fable_string", "string_ctor_char_count", t, [ ch; count ])
|> Some
| _ -> None
| Type.Array _ ->
match args with
| [ chars ] ->
let chars = derefArr r chars
Helper.LibCall(com, "fable_string", "string_ctor_chars", t, [ chars ]) |> Some
| [ chars; start; len ] ->
let chars = derefArr r chars
Helper.LibCall(com, "fable_string", "string_ctor_chars_range", t, [ chars; start; len ])
|> Some
| _ -> None
| _ -> None
// str.Length → byte_size(Str) — works for ASCII; for full Unicode use string:length
| "get_Length", Some c, _ -> emitExpr r t [ c ] "byte_size($0)" |> Some
// str.ToUpper() → string:uppercase(Str)
| ("ToUpper" | "ToUpperInvariant"), Some c, _ -> emitExpr r t [ c ] "string:uppercase($0)" |> Some
// str.ToLower() → string:lowercase(Str)
| ("ToLower" | "ToLowerInvariant"), Some c, _ -> emitExpr r t [ c ] "string:lowercase($0)" |> Some
// str.Trim() → string:trim(Str)
| "Trim", Some c, [] -> emitExpr r t [ c ] "string:trim($0)" |> Some
| "Trim", Some c, [ chars ] ->
let chars = derefArr r chars
Helper.LibCall(com, "fable_string", "trim_chars", t, [ c; chars ]) |> Some
| "TrimStart", Some c, [] -> emitExpr r t [ c ] "string:trim($0, leading)" |> Some
| "TrimStart", Some c, [ chars ] ->
let chars = derefArr r chars
Helper.LibCall(com, "fable_string", "trim_start_chars", t, [ c; chars ]) |> Some
| "TrimEnd", Some c, [] -> emitExpr r t [ c ] "string:trim($0, trailing)" |> Some
| "TrimEnd", Some c, [ chars ] ->
let chars = derefArr r chars
Helper.LibCall(com, "fable_string", "trim_end_chars", t, [ c; chars ]) |> Some
// str.StartsWith(prefix)
| "StartsWith", Some c, [ prefix ] ->
match prefix.Type with
| Type.Char -> emitExpr r t [ c; prefix ] "fable_string:starts_with($0, <<($1)/utf8>>)" |> Some
| _ -> Helper.LibCall(com, "fable_string", "starts_with", t, [ c; prefix ]) |> Some
| "StartsWith", Some c, [ prefix; _compType ] ->
emitExpr r t [ c; prefix ] "fable_string:starts_with(string:lowercase($0), string:lowercase($1))"
|> Some
| "StartsWith", Some c, [ prefix; _ignoreCase; _culture ] ->
emitExpr r t [ c; prefix ] "fable_string:starts_with(string:lowercase($0), string:lowercase($1))"
|> Some
// str.EndsWith(suffix)
| "EndsWith", Some c, [ suffix ] ->
match suffix.Type with
| Type.Char -> emitExpr r t [ c; suffix ] "fable_string:ends_with($0, <<($1)/utf8>>)" |> Some
| _ -> Helper.LibCall(com, "fable_string", "ends_with", t, [ c; suffix ]) |> Some
| "EndsWith", Some c, [ suffix; _compType ] ->
emitExpr r t [ c; suffix ] "fable_string:ends_with(string:lowercase($0), string:lowercase($1))"
|> Some
| "EndsWith", Some c, [ suffix; _ignoreCase; _culture ] ->
emitExpr r t [ c; suffix ] "fable_string:ends_with(string:lowercase($0), string:lowercase($1))"
|> Some
// str.Substring(start)
| "Substring", Some c, [ start ] ->
Helper.LibCall(com, "fable_string", "substring", t, [ c; start ], ?loc = r)
|> Some
// str.Substring(start, length)
| "Substring", Some c, [ start; len ] ->
Helper.LibCall(com, "fable_string", "substring", t, [ c; start; len ], ?loc = r)
|> Some
// str.Replace(old, new)
| "Replace", Some c, [ oldVal; newVal ] ->
Helper.LibCall(com, "fable_string", "replace", t, [ c; oldVal; newVal ]) |> Some
// str.Split(sep) → binary:split(Str, Sep, [global])
| "Split", Some c, [ sep ] ->
let sep = derefArr r sep
Helper.LibCall(com, "fable_string", "split", t, [ c; sep ])
|> wrapArr com r t
|> Some
| "Split", Some c, [ sep; countOrOptions ] ->
let sep = derefArr r sep
match countOrOptions.Type with
| Number(_, NumberInfo.IsEnum _) ->
// Split(char[], StringSplitOptions)
Helper.LibCall(com, "fable_string", "split", t, [ c; sep; countOrOptions ])
|> wrapArr com r t
|> Some
| Number _ ->
// Split(char[], count) — split with count limit
Helper.LibCall(com, "fable_string", "split_with_count", t, [ c; sep; countOrOptions ])
|> wrapArr com r t
|> Some
| _ ->
// Default: treat as options (enum value may come as int in some contexts)
Helper.LibCall(com, "fable_string", "split", t, [ c; sep; countOrOptions ])
|> wrapArr com r t
|> Some
| "Split", Some c, [ sep; count; _options ] ->
let sep = derefArr r sep
Helper.LibCall(com, "fable_string", "split_with_count", t, [ c; sep; count ])
|> wrapArr com r t
|> Some
// String.Join(sep, items)
| "Join", None, [ sep; items ] ->
// Check element type BEFORE derefArr (which erases to List Any).
// Chars need special handling: convert to binaries before joining.
let rec getElemType (ty: Type) =
match ty with
| Type.Array(elemType, _)
| Type.List elemType -> Some elemType
| Type.DeclaredType(_, [ elemType ]) -> Some elemType
| _ -> None
let hasCharElements =
match getElemType items.Type with
| Some Type.Char -> true
| _ -> false
let items = derefArr r items
if hasCharElements then
// Map chars to binaries: [<<C/utf8>> || C <- Items]
emitExpr r t [ sep; items ] "fable_string:join($0, [<<C/utf8>> || C <- $1])"
|> Some
else
Helper.LibCall(com, "fable_string", "join_strings", t, [ sep; items ]) |> Some
| "Join", None, [ sep; items; startIndex; count ] ->
let items = derefArr r items
Helper.LibCall(com, "fable_string", "join", t, [ sep; items; startIndex; count ])
|> Some
// String.Concat(items) → iolist_to_binary(Items)
| "Concat", None, args ->
match args with
| [ items ] -> emitExpr r t [ items ] "fable_string:concat($0)" |> Some
| [ a; b ] -> emitExpr r t [ a; b ] "iolist_to_binary([$0, $1])" |> Some
| [ a; b; c ] -> emitExpr r t [ a; b; c ] "iolist_to_binary([$0, $1, $2])" |> Some
| _ ->
let argsList =
List.foldBack
(fun arg acc -> Value(NewList(Some(arg, acc), String), None))
args
(Value(NewList(None, String), None))
emitExpr r t [ argsList ] "fable_string:concat($0)" |> Some
// String.Compare
| "Compare", None, [ a; b ] -> Helper.LibCall(com, "fable_string", "compare", t, [ a; b ]) |> Some
| "Compare", None, [ a; b; compType ] ->
Helper.LibCall(com, "fable_string", "compare", t, [ a; b; compType ]) |> Some
| "Compare", None, [ a; startA; b; startB; len ] ->
// String.Compare(a, startA, b, startB, len) — substring comparison
emitExpr
r
t
[ a; startA; b; startB; len ]
"fable_string:compare(binary:part($0, $1, $4), binary:part($2, $3, $4))"
|> Some
| "Compare", None, [ a; startA; b; startB; len; compType ] ->
// String.Compare(a, startA, b, startB, len, compType) — substring comparison with comparison type
emitExpr
r
t
[ a; startA; b; startB; len; compType ]
"fable_string:compare(binary:part($0, $1, $4), binary:part($2, $3, $4), $5)"
|> Some
// String.IsNullOrEmpty / IsNullOrWhiteSpace (static on System.String)
| "IsNullOrEmpty", None, [ str ] -> Helper.LibCall(com, "fable_string", "is_null_or_empty", t, [ str ]) |> Some
| "IsNullOrWhiteSpace", None, [ str ] ->
Helper.LibCall(com, "fable_string", "is_null_or_white_space", t, [ str ])
|> Some
// String.Equals static
| "Equals", None, [ a; b ] -> equals com r true a b |> Some
| "Equals", None, [ a; b; compType ] ->
// Dispatch on StringComparison: 5=OrdinalIgnoreCase → lowercase compare, else exact
emitExpr
r
t
[ a; b; compType ]
"case $2 of 5 -> string:lowercase($0) =:= string:lowercase($1); _ -> $0 =:= $1 end"
|> Some
// str.PadLeft(width)
| "PadLeft", Some c, [ width ] -> Helper.LibCall(com, "fable_string", "pad_left", t, [ c; width ]) |> Some