-
Notifications
You must be signed in to change notification settings - Fork 323
Expand file tree
/
Copy pathReplacements.Util.fs
More file actions
1600 lines (1398 loc) · 61 KB
/
Replacements.Util.fs
File metadata and controls
1600 lines (1398 loc) · 61 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.Replacements.Util
#nowarn "1182"
open System
open System.Text.RegularExpressions
open Fable
open Fable.AST
open Fable.AST.Fable
open Fable.Transforms
type Context = FSharp2Fable.Context
type ICompiler = FSharp2Fable.IFableCompiler
type CallInfo = ReplaceCallInfo
type Helper =
static member ConstructorCall
(consExpr: Expr, returnType: Type, args: Expr list, ?argTypes, ?genArgs, ?loc: SourceLocation)
=
let info =
CallInfo.Create(args = args, ?sigArgTypes = argTypes, ?genArgs = genArgs, isCons = true)
Call(consExpr, info, returnType, loc)
static member InstanceCall
(
callee: Expr,
memb: string,
returnType: Type,
args: Expr list,
?argTypes: Type list,
?genArgs,
?loc: SourceLocation
)
=
let callee = getField callee memb
let info = CallInfo.Create(args = args, ?sigArgTypes = argTypes, ?genArgs = genArgs)
Call(callee, info, returnType, loc)
static member Application
(callee: Expr, returnType: Type, args: Expr list, ?argTypes: Type list, ?loc: SourceLocation)
=
let info = defaultArg argTypes [] |> makeCallInfo None args
Call(callee, info, returnType, loc)
static member LibValue(com, coreModule: string, coreMember: string, returnType: Type) =
makeImportLib com returnType coreMember coreModule
static member LibCall
(
com,
coreModule: string,
coreMember: string,
returnType: Type,
args: Expr list,
?argTypes: Type list,
?genArgs,
?thisArg: Expr,
?hasSpread: bool,
?isModuleMember,
?isConstructor: bool,
?loc: SourceLocation
)
=
let isInstanceMember = Option.isSome thisArg
let isModuleMember = defaultArg isModuleMember (not isInstanceMember)
let callee =
LibraryImportInfo.Create(isInstanceMember = isInstanceMember, isModuleMember = isModuleMember)
|> makeImportLibWithInfo com Any coreMember coreModule
let memberRef =
match hasSpread with
| Some true ->
let argTypes =
argTypes |> Option.defaultWith (fun () -> args |> List.map (fun a -> a.Type))
GeneratedMember.Function(
coreMember,
argTypes,
returnType,
isInstance = isInstanceMember,
hasSpread = true
)
|> Some
| Some false
| None -> None
let info =
CallInfo.Create(
?thisArg = thisArg,
args = args,
?sigArgTypes = argTypes,
?genArgs = genArgs,
?memberRef = memberRef,
?isCons = isConstructor
)
Call(callee, info, returnType, loc)
static member ImportedValue(com, coreModule: string, coreMember: string, returnType: Type) =
makeImportUserGenerated None Any coreMember coreModule
static member ImportedCall
(
path: string,
selector: string,
returnType: Type,
args: Expr list,
?argTypes: Type list,
?genArgs,
?thisArg: Expr,
?hasSpread: bool,
?isConstructor: bool,
?loc: SourceLocation
)
=
let callee = makeImportUserGenerated None Any selector path
let memberRef =
match hasSpread with
| Some true ->
let argTypes =
argTypes |> Option.defaultWith (fun () -> args |> List.map (fun a -> a.Type))
GeneratedMember.Function(selector, argTypes, returnType, isInstance = false, hasSpread = true)
|> Some
| Some false
| None -> None
let info =
CallInfo.Create(
?thisArg = thisArg,
args = args,
?sigArgTypes = argTypes,
?genArgs = genArgs,
?memberRef = memberRef,
?isCons = isConstructor
)
Call(callee, info, returnType, loc)
static member GlobalCall
(
ident: string,
returnType: Type,
args: Expr list,
?argTypes: Type list,
?genArgs,
?memb: string,
?isConstructor: bool,
?loc: SourceLocation
)
=
let callee =
match memb with
| Some memb -> getField (makeIdentExpr ident) memb
| None -> makeIdentExpr ident
let info =
CallInfo.Create(args = args, ?sigArgTypes = argTypes, ?genArgs = genArgs, ?isCons = isConstructor)
Call(callee, info, returnType, loc)
static member GlobalIdent(ident: string, memb: string, typ: Type, ?loc: SourceLocation) =
getFieldWith loc typ (makeIdentExpr ident) memb
type NumberKind with
member this.Number = Number(this, NumberInfo.Empty)
let makeUniqueIdent com ctx t name =
FSharp2Fable.Helpers.getIdentUniqueName com ctx name |> makeTypedIdent t
let withTag tag =
function
| Call(e, i, t, r) -> Call(e, { i with Tags = tag :: i.Tags }, t, r)
| Get(e, FieldGet i, t, r) -> Get(e, FieldGet { i with Tags = tag :: i.Tags }, t, r)
| Operation(op, tags, t, r) -> Operation(op, tag :: tags, t, r)
| Emit(i, t, r) -> Emit({ i with EmitInfo.CallInfo.Tags = tag :: i.CallInfo.Tags }, t, r)
| e -> e
let getTags =
function
| Call(e, i, t, r) -> i.Tags
| Get(e, FieldGet i, t, r) -> i.Tags
| _e -> []
let objValue (k, v) : ObjectExprMember =
{
Name = k
Args = []
Body = v
IsMangled = false
MemberRef = GeneratedMember.Value(k, v.Type)
}
let typedObjExpr t kvs =
ObjectExpr(List.map objValue kvs, t, None)
let objExpr kvs = typedObjExpr Any kvs
let add left right =
Operation(Binary(BinaryPlus, left, right), Tags.empty, left.Type, None)
let sub left right =
Operation(Binary(BinaryMinus, left, right), Tags.empty, left.Type, None)
let eq left right =
Operation(Binary(BinaryEqual, left, right), Tags.empty, Boolean, None)
let neq left right =
Operation(Binary(BinaryUnequal, left, right), Tags.empty, Boolean, None)
let nullCheck r isNull expr =
let op =
if isNull then
BinaryEqual
else
BinaryUnequal
Operation(Binary(op, expr, Value(Null expr.Type, None)), Tags.empty, Boolean, r)
let str txt = Value(StringConstant txt, None)
let genArg (com: ICompiler) (ctx: Context) r i (genArgs: Type list) =
List.tryItem i genArgs
|> Option.defaultWith (fun () ->
"Couldn't find generic argument in position " + (string<int> i)
|> addError com ctx.InlinePath r
Any
)
let toArray r t expr =
let t, kind =
match t with
| Array(t, kind) -> t, kind
// This is used also by Seq.cache, which returns `'T seq` instead of `'T array`
| DeclaredType(_, [ t ])
| t -> t, MutableArray
Value(NewArray(ArrayFrom expr, t, kind), r)
type NumberValue with
static member GetZero(kind: NumberKind) : NumberValue =
match kind with
| NumberKind.Int8 -> NumberValue.Int8(0y: int8)
| NumberKind.UInt8 -> NumberValue.UInt8(0uy: uint8)
| NumberKind.Int16 -> NumberValue.Int16(0s: int16)
| NumberKind.UInt16 -> NumberValue.UInt16(0us: uint16)
| NumberKind.Int32 -> NumberValue.Int32(0: int32)
| NumberKind.UInt32 -> NumberValue.UInt32(0u: uint32)
| NumberKind.Int64 -> NumberValue.Int64(0L: int64)
| NumberKind.UInt64 -> NumberValue.UInt64(0UL: uint64)
| NumberKind.Int128 -> NumberValue.Int128(0UL, 0UL) //System.Int128.Zero
| NumberKind.UInt128 -> NumberValue.UInt128(0UL, 0UL) //System.UInt128.Zero
| NumberKind.BigInt -> NumberValue.BigInt(0I: bigint)
| NumberKind.NativeInt -> NumberValue.NativeInt(0n: nativeint)
| NumberKind.UNativeInt -> NumberValue.UNativeInt(0un: unativeint)
| NumberKind.Float16 -> NumberValue.Float16(0.f: float32) //System.Half.Zero
| NumberKind.Float32 -> NumberValue.Float32(0.f: float32)
| NumberKind.Float64 -> NumberValue.Float64(0.: float)
| NumberKind.Decimal -> NumberValue.Decimal(0M: decimal)
static member GetOne(kind: NumberKind) : NumberValue =
match kind with
| NumberKind.Int8 -> NumberValue.Int8(1y: int8)
| NumberKind.UInt8 -> NumberValue.UInt8(1uy: uint8)
| NumberKind.Int16 -> NumberValue.Int16(1s: int16)
| NumberKind.UInt16 -> NumberValue.UInt16(1us: uint16)
| NumberKind.Int32 -> NumberValue.Int32(1: int32)
| NumberKind.UInt32 -> NumberValue.UInt32(1u: uint32)
| NumberKind.Int64 -> NumberValue.Int64(1L: int64)
| NumberKind.UInt64 -> NumberValue.UInt64(1UL: uint64)
| NumberKind.Int128 -> NumberValue.Int128(0UL, 1UL) //System.Int128.One
| NumberKind.UInt128 -> NumberValue.UInt128(0UL, 1UL) //System.UInt128.One
| NumberKind.BigInt -> NumberValue.BigInt(1I: bigint)
| NumberKind.NativeInt -> NumberValue.NativeInt(1n: nativeint)
| NumberKind.UNativeInt -> NumberValue.UNativeInt(1un: unativeint)
| NumberKind.Float16 -> NumberValue.Float16(1.f: float32) //System.Half.One
| NumberKind.Float32 -> NumberValue.Float32(1.f: float32)
| NumberKind.Float64 -> NumberValue.Float64(1.: float)
| NumberKind.Decimal -> NumberValue.Decimal(1M: decimal)
type BuiltinType =
| BclGuid
| BclTimeSpan
| BclDateTime
| BclDateTimeOffset
| BclDateOnly
| BclTimeOnly
| BclTimer
| BclHashSet of Type
| BclDictionary of key: Type * value: Type
| BclKeyValuePair of key: Type * value: Type
| FSharpSet of Type
| FSharpMap of key: Type * value: Type
| FSharpChoice of genArgs: Type list
| FSharpResult of ok: Type * err: Type
| FSharpReference of Type
let (|BuiltinDefinition|_|) =
function
| Types.guid -> Some BclGuid
| Types.timespan -> Some BclTimeSpan
| Types.datetime -> Some BclDateTime
| Types.datetimeOffset -> Some BclDateTimeOffset
| Types.dateOnly -> Some BclDateOnly
| Types.timeOnly -> Some BclTimeOnly
| "System.Timers.Timer" -> Some BclTimer
| Types.fsharpSet -> Some(FSharpSet(Any))
| Types.fsharpMap -> Some(FSharpMap(Any, Any))
| Types.hashset -> Some(BclHashSet(Any))
| Types.dictionary -> Some(BclDictionary(Any, Any))
| Types.keyValuePair -> Some(BclKeyValuePair(Any, Any))
| Types.result -> Some(FSharpResult(Any, Any))
| Types.byref -> Some(FSharpReference(Any))
| Types.byref2 -> Some(FSharpReference(Any))
| Types.refCell -> Some(FSharpReference(Any))
| Naming.StartsWith Types.choiceNonGeneric genArgs -> List.replicate (int genArgs[1..]) Any |> FSharpChoice |> Some
| _ -> None
let (|BuiltinEntity|_|) (ent: string, genArgs) =
match ent, genArgs with
| BuiltinDefinition(FSharpSet _), [ t ] -> Some(FSharpSet(t))
| BuiltinDefinition(FSharpMap _), [ k; v ] -> Some(FSharpMap(k, v))
| BuiltinDefinition(BclHashSet _), [ t ] -> Some(BclHashSet(t))
| BuiltinDefinition(BclDictionary _), [ k; v ] -> Some(BclDictionary(k, v))
| BuiltinDefinition(BclKeyValuePair _), [ k; v ] -> Some(BclKeyValuePair(k, v))
| BuiltinDefinition(FSharpResult _), [ k; v ] -> Some(FSharpResult(k, v))
| BuiltinDefinition(FSharpReference _), [ t ] -> Some(FSharpReference(t))
| BuiltinDefinition(FSharpReference _), [ t; _ ] -> Some(FSharpReference(t))
| BuiltinDefinition(FSharpChoice _), genArgs -> Some(FSharpChoice genArgs)
| BuiltinDefinition t, _ -> Some t
| _ -> None
let (|Builtin|_|) =
function
| DeclaredType(ent, genArgs) ->
match ent.FullName, genArgs with
| BuiltinEntity x -> Some x
| _ -> None
| _ -> None
let (|BuiltinSystemException|_|) (ent: string) =
match ent with
| "System.ApplicationException"
| "System.ArgumentException"
| "System.ArgumentNullException"
| "System.ArgumentOutOfRangeException"
| "System.ArithmeticException"
| "System.DivideByZeroException"
| "System.FormatException"
| "System.IndexOutOfRangeException"
| "System.InvalidOperationException"
| "System.NotFiniteNumberException"
| "System.NotImplementedException"
| "System.NotSupportedException"
| "System.NullReferenceException"
| "System.OutOfMemoryException"
| "System.OverflowException"
| "System.RankException"
| "System.StackOverflowException"
| "System.SystemException"
| "System.TimeoutException" ->
let entName = ent.Substring(ent.LastIndexOf('.') + 1)
Some entName
| _ -> None
let getElementType =
function
| Array(t, _) -> t
| List t -> t
| DeclaredType(_, [ t ]) -> t
| _ -> Any
let genericTypeInfoError (name: string) =
$"Cannot get type info of generic parameter {name}. Fable erases generics at runtime, try inlining the functions so generics can be resolved at compile time."
// This is mainly intended for typeof errors because we want to show the user where the function is originally called
let changeRangeToCallSite (inlinePath: InlinePath list) (range: SourceLocation option) =
List.tryLast inlinePath
|> Option.bind (fun i -> i.FromRange)
|> Option.orElse range
let splitFullName (fullname: string) =
let fullname =
match fullname.IndexOf("[", StringComparison.Ordinal) with
| -1 -> fullname
| i -> fullname[.. i - 1]
match fullname.LastIndexOf(".", StringComparison.Ordinal) with
| -1 -> "", fullname
| i -> fullname.Substring(0, i), fullname.Substring(i + 1)
let getTypeNameFromFullName (fullname: string) =
let fullname =
match fullname.IndexOf("[", StringComparison.Ordinal) with
| -1 -> fullname
| i -> fullname[.. i - 1]
match fullname.LastIndexOf(".", StringComparison.Ordinal) with
| -1 -> fullname
| i -> fullname.Substring(i + 1)
let rec getTypeName com (ctx: Context) r t =
match t with
| GenericParam(name = name) ->
genericTypeInfoError name |> addError com ctx.InlinePath r
name
| Array(elemType, _) -> // TODO: check kind
getTypeName com ctx r elemType + "[]"
| _ -> getTypeFullName false t |> splitFullName |> snd
let makeDeclaredType assemblyName genArgs fullName =
let entRef: EntityRef =
{
FullName = fullName
Path = CoreAssemblyName assemblyName
}
DeclaredType(entRef, genArgs)
let makeRuntimeType genArgs fullName =
makeDeclaredType "System.Runtime" genArgs fullName
let makeFSharpCoreType genArgs fullName =
makeDeclaredType "FSharp.Core" genArgs fullName
let makeStringTemplate
tag
(str: string)
(holes:
{|
Index: int
Length: int
|}[])
values
=
let mutable prevIndex = 0
let parts =
[
for i = 0 to holes.Length - 1 do
let m = holes[i]
let strPart = str.Substring(prevIndex, m.Index - prevIndex)
prevIndex <- m.Index + m.Length
strPart
str.Substring(prevIndex)
]
StringTemplate(tag, parts, values)
// Parses an F# interpolated string format, finds every %P() hole (optionally preceded by a
// printf format specifier or a .NET format specifier), and builds a StringTemplate from the
// literal parts and the supplied value expressions.
//
// The F# compiler encodes holes as:
// %P() – plain hole, no format specifier
// %0.2f%P() – hole with a printf-style format specifier
// %P(N0) – hole with a .NET format specifier (e.g. N0, C2, X)
//
// For each hole the caller supplies:
// `handleFormatSpec`:
// - called when a hole has a non-simple printf format spec (e.g. "%0.2f")
// - returning None aborts the whole template
// `handleDotNetSpec`:
// - called when a hole has a .NET format specifier inside %P(...)
// - returning None aborts the whole template
let private makeStringTemplateFromWith
(simpleFormats: string array)
(handleFormatSpec: string -> Expr -> Expr option)
(handleDotNetSpec: string -> Expr -> Expr option)
(values: Expr list)
=
function
| StringConst str ->
// In the case of interpolated strings, the F# compiler doesn't resolve escaped %
// (though it does resolve double braces {{ }})
let str = str.Replace("%%", "%")
// Group 1: optional printf format spec (e.g. "%0.2f")
// Group 2: optional .NET format spec inside %P(...) (e.g. "N0", "C2")
let matches =
Regex.Matches(str, @"((?<!%)%(?:[0+\- ]*)(?:\d+)?(?:\.\d+)?\w)?%P\(([^)]*)\)")
|> Seq.cast<Match>
(Some([], values), matches)
||> Seq.fold (fun acc m ->
match acc with
| None -> None
| Some(_, []) -> None // fewer values than matches
| Some(mapped, value :: restValues) ->
let dotNetSpec = m.Groups[2].Value
let needsFormat =
m.Groups[1].Success && not (Array.contains m.Groups[1].Value simpleFormats)
let resolved =
if dotNetSpec.Length > 0 then
handleDotNetSpec dotNetSpec value
elif needsFormat then
handleFormatSpec m.Groups[1].Value value
else
Some value
resolved |> Option.map (fun v -> v :: mapped, restValues)
)
|> Option.map (fun (mapped, _) ->
let holes =
matches
|> Seq.map (fun m ->
{|
Index = m.Index
Length = m.Length
|}
)
|> Seq.toArray
let mappedValues = List.rev mapped
makeStringTemplate None str holes mappedValues
)
| _ -> None
/// Try to build a StringTemplate from an F# interpolated string.
/// Returns None if any hole carries a format specifier that is not in simpleFormats,
/// because those require runtime formatting that can't be inlined into a plain template.
let makeStringTemplateFrom simpleFormats values strExpr =
// Abort (return None) for any non-simple format spec.
makeStringTemplateFromWith simpleFormats (fun _ _ -> None) (fun _ _ -> None) values strExpr
/// Like makeStringTemplateFrom but always succeeds for string literals.
/// Values with printf format specifiers not in simpleFormats are individually wrapped in a
/// String.interpolate call, and values with .NET format specifiers are wrapped in a
/// String.format call so they evaluate to formatted strings.
/// Used for JSX templates and sprintf where every hole must produce a string value.
let makeStringTemplateFromAllowingFormat (com: ICompiler) simpleFormats (values: Expr list) strExpr =
makeStringTemplateFromWith
simpleFormats
(fun fmtSpec value ->
// Wrap value in: String.interpolate("%fmtspec%P()", [| value |])
let fmtStr = Value(StringConstant(fmtSpec + "%P()"), None)
let valArr = Value(NewArray(ArrayValues [ value ], Any, MutableArray), None)
Helper.LibCall(com, "String", "interpolate", String, [ fmtStr; valArr ]) |> Some
)
(fun dotNetSpec value ->
// Wrap value in: String.format("{0:spec}", value)
let fmtStr = Value(StringConstant("{0:" + dotNetSpec + "}"), None)
Helper.LibCall(com, "String", "format", String, [ fmtStr; value ]) |> Some
)
values
strExpr
let rec namesof com ctx acc e =
match acc, e with
| acc, Get(e, ExprGet(StringConst prop), _, _) -> namesof com ctx (prop :: acc) e
| acc, Get(e, FieldGet i, _, _) -> namesof com ctx (i.Name :: acc) e
| [], IdentExpr ident -> ident.DisplayName :: acc |> Some
| [], NestedLambda(args, Call(IdentExpr ident, info, _, _), c) ->
if
List.sameLength args info.Args
&& List.zip args info.Args
|> List.forall (fun (a1, a2) ->
match a2 with
| IdentExpr id2 -> a1.Name = id2.Name
| _ -> false
)
then
ident.DisplayName :: acc |> Some
else
None
| [], Value(TypeInfo(t, _), r) -> (getTypeName com ctx r t) :: acc |> Some
| [], _ -> None
| acc, _ -> Some acc
let curriedApply r t applied args = CurriedApply(applied, args, t, r)
let compose (com: ICompiler) ctx r t (f1: Expr) (f2: Expr) =
let argType, retType =
match t with
| LambdaType(argType, retType) -> argType, retType
| _ -> Any, Any
let interType =
match f1.Type with
| LambdaType(_, interType) -> interType
| _ -> Any
let arg = makeUniqueIdent com ctx argType "arg"
// Eagerly evaluate and capture the value of the functions, see #2851
// If possible, the bindings will be optimized away in FableTransforms
let capturedFun1Var = makeUniqueIdent com ctx f1.Type "f1"
let capturedFun2Var = makeUniqueIdent com ctx f2.Type "f2"
let argExpr =
match argType with
// Erase unit references, because the arg may be erased
| Unit -> Value(UnitConstant, None)
| _ -> IdentExpr arg
let body =
[ argExpr ]
|> curriedApply None interType (IdentExpr capturedFun1Var)
|> List.singleton
|> curriedApply r retType (IdentExpr capturedFun2Var)
Let(capturedFun1Var, f1, Let(capturedFun2Var, f2, Lambda(arg, body, None)))
let partialApplyAtRuntime (com: Compiler) t arity (expr: Expr) (partialArgs: Expr list) =
match com.Options.Language with
| JavaScript
| TypeScript
| Dart
| Python ->
match uncurryLambdaType -1 [] expr.Type with
| ([] | [ _ ]), _ -> expr
| argTypes, returnType ->
let curriedType = makeLambdaType argTypes returnType
let curried =
match com.Options.Language with
| Python ->
Helper.LibCall(com, "Curry", "curry", curriedType, [ makeNativeIntConst argTypes.Length; expr ])
| _ -> Helper.LibCall(com, "Util", $"curry%d{argTypes.Length}", curriedType, [ expr ])
match partialArgs with
| [] -> curried
| partialArgs -> curriedApply None t curried partialArgs
| _ ->
// Check if argTypes.Length < arity?
let makeArgIdent i typ = makeTypedIdent typ $"a{i}" // $"a{com.IncrementCounter()}$"
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)
makeLambda argIdents body
let curryExprAtRuntime (com: Compiler) arity (expr: Expr) =
if arity = 1 then
expr
else
match expr with
| Value(Null _, _) -> expr
| Value(NewOption(value, t, isStruct), r) ->
match value with
| None -> expr
| Some v ->
let curried = partialApplyAtRuntime com t arity v []
Value(NewOption(Some curried, t, isStruct), r)
| ExprType(Option(t, isStruct)) ->
let uncurriedType =
let argTypes, returnType = uncurryLambdaType arity [] t
DelegateType(argTypes, returnType)
let f = makeTypedIdent uncurriedType "f"
let fe = makeTypedIdent t "f" |> IdentExpr
let curried = partialApplyAtRuntime com t arity fe []
let fn = Delegate([ f ], curried, None, Tags.empty)
// TODO: This may be different per language
Helper.LibCall(com, "Option", "map", Option(curried.Type, isStruct), [ fn; expr ])
| _ -> partialApplyAtRuntime com expr.Type arity expr []
let uncurryExprAtRuntime (com: Compiler) arity (expr: Expr) =
let uncurry (expr: Expr) =
// Check if argTypes.Length < arity?
let argTypes, returnType = uncurryLambdaType arity [] expr.Type
match com.Options.Language with
| JavaScript
| TypeScript
| Dart
| Python ->
let uncurriedType = DelegateType(argTypes, returnType)
match com.Options.Language with
| Python -> Helper.LibCall(com, "Curry", "uncurry", uncurriedType, [ makeNativeIntConst arity; expr ])
| _ -> Helper.LibCall(com, "Util", $"uncurry%d{arity}", uncurriedType, [ expr ])
| _ ->
// let makeArgIdent typ = makeTypedIdent typ $"a{com.IncrementCounter()}$"
// let argIdents = argTypes |> List.map makeArgIdent
// let expr, argIdents2 =
// match expr with
// | Extended(Curry(expr, arity2),_) when arity2 >= arity ->
// if arity2 = arity
// then expr, []
// else
// let argTypes2, _returnType = uncurryLambdaType arity2 [] expr.Type
// expr, argTypes2 |> List.skip arity |> List.map makeArgIdent
// | _ -> expr, []
// let args = (argIdents1 @ argIdents2) |> List.map IdentExpr
// let body = curriedApply None returnType expr args
// let body = makeLambda argIdents2 body
// Delegate(argIdents1, body, None, Tags.empty)
let argTypes, returnType =
match expr.Type with
| Fable.LambdaType(argType, returnType) -> uncurryLambdaType arity [] expr.Type
| Fable.DelegateType(argTypes, returnType) -> argTypes, returnType
| _ -> [], expr.Type
let makeArgIdent i typ = makeTypedIdent typ $"b{i}" // $"a{com.IncrementCounter()}$"
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)
match expr with
| Value(Null _, _) -> expr
| Value(NewOption(value, t, isStruct), r) ->
let t = Fable.DelegateType(uncurryLambdaType arity [] t)
match value with
| None -> Value(NewOption(None, t, isStruct), r)
| Some v -> Value(NewOption(Some(uncurry v), t, isStruct), r)
| ExprType(Option(t, isStruct)) ->
let f = makeTypedIdent t "f"
let uncurried = uncurry (IdentExpr f)
let fn = Delegate([ f ], uncurried, None, Tags.empty)
// TODO: This may be different per language
Helper.LibCall(com, "Option", "map", Option(uncurried.Type, isStruct), [ fn; expr ])
| expr -> uncurry expr
let (|Namesof|_|) com ctx e = namesof com ctx [] e
let (|Nameof|_|) com ctx e =
namesof com ctx [] e |> Option.bind List.tryLast
let (|ReplaceName|_|) (namesAndReplacements: (string * string) list) name =
namesAndReplacements
|> List.tryPick (fun (name2, replacement) ->
if name2 = name then
Some replacement
else
None
)
let (|OrDefault|) (def: 'T) =
function
| Some v -> v
| None -> def
let (|IsByRefType|_|) (com: Compiler) =
function
| DeclaredType(entRef, genArgs) ->
let ent = com.GetEntity(entRef)
match ent.IsByRef, genArgs with
| true, (genArg :: _) -> Some genArg
| _ -> None
| _ -> None
let (|IsInRefType|_|) (com: Compiler) =
function
| DeclaredType(entRef, genArgs) ->
let ent = com.GetEntity(entRef)
match ent.IsByRef, genArgs with
| true, [ genArg; DeclaredType(byRefKind, _) ] when byRefKind.FullName = Types.byrefKindIn -> Some genArg
| _ -> None
| _ -> None
let (|IsReferenceType|_|) (com: Compiler) (t: Type) =
match t with
| Measure _
| MetaType
| Unit
| Boolean
| Char
| Number _ -> None
| Any
| Regex
| String
| LambdaType _
| DelegateType _ -> Some t
| Array _
| List _ -> Some t
| Nullable(_, isStruct)
| Option(_, isStruct)
| Tuple(_, isStruct)
| AnonymousRecordType(_, _, isStruct) ->
if isStruct then
None
else
Some t
| GenericParam(_name, _isMeasure, constraints) ->
let isNullable = constraints |> List.contains Fable.Constraint.IsNullable
let isReferenceType = constraints |> List.contains Fable.Constraint.IsReferenceType
if isNullable || isReferenceType then
Some t
else
None
| DeclaredType(entRef, _) ->
let ent = com.GetEntity(entRef)
if ent.IsValueType then
None
else
Some t
let rec (|HasReferenceEquality|_|) (com: Compiler) (t: Type) =
match t with
| Measure _
| MetaType
| Unit
| Boolean
| Char
| Number _ -> None
| Any
| Regex
| String
| LambdaType _
| DelegateType _ -> Some t
| Array _
| List _ -> None
| Nullable(genArg, isStruct) ->
if isStruct then
None
else
(|HasReferenceEquality|_|) com genArg
| Option _
| Tuple _
| AnonymousRecordType _ -> None
| GenericParam(_name, _isMeasure, constraints) ->
let isNullable = constraints |> List.contains Fable.Constraint.IsNullable
let isReferenceType = constraints |> List.contains Fable.Constraint.IsReferenceType
if isNullable || isReferenceType then
Some t
else
None
| DeclaredType(entRef, _) ->
let ent = com.GetEntity(entRef)
if ent |> FSharp2Fable.Util.hasStructuralEquality then
None
else
Some t
let (|ListLiteral|_|) expr =
let rec untail t acc =
function
| Value(NewList(None, _), _) -> Some(List.rev acc, t)
| Value(NewList(Some(head, tail), _), _) -> untail t (head :: acc) tail
| _ -> None
match expr with
| NewList(None, t) -> Some([], t)
| NewList(Some(head, tail), t) -> untail t [ head ] tail
| _ -> None
let (|ArrayOrListLiteral|_|) =
function
| MaybeCasted(Value((NewArray(ArrayValues vals, t, _) | ListLiteral(vals, t)), _)) -> Some(vals, t)
| _ -> None
let (|IsEntity|_|) fullName =
function
| DeclaredType(entRef, genArgs) ->
if entRef.FullName = fullName then
Some(entRef, genArgs)
else
None
| _ -> None
let (|IDictionary|IEqualityComparer|Other|) =
function
| MaybeNullable(DeclaredType(entRef, _))
| DeclaredType(entRef, _) ->
match entRef.FullName with
| Types.idictionary -> IDictionary
| Types.iequalityComparerGeneric -> IEqualityComparer
| _ -> Other
| _ -> Other
let (|IEnumerable|IEqualityComparer|Other|) =
function
| MaybeNullable(DeclaredType(entRef, _))
| DeclaredType(entRef, _) ->
match entRef.FullName with
| Types.ienumerableGeneric -> IEnumerable
| Types.iequalityComparerGeneric -> IEqualityComparer
| _ -> Other
| _ -> Other
let (|Enumerator|Other|) =
function
| "System.CharEnumerator"
| "System.Collections.Generic.List`1.Enumerator"
| "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" -> Enumerator
| _ -> Other
let (|IsEnumerator|_|) =
function
| MaybeNullable(DeclaredType(entRef, genArgs))
| DeclaredType(entRef, genArgs) ->
match entRef.FullName with
| Enumerator -> Some(entRef, genArgs)
| _ -> None
| _ -> None
let (|IsNewAnonymousRecord|_|) =
function
// The F# compiler may create some bindings of expression arguments to fix https://github.com/dotnet/fsharp/issues/6487
| NestedRevLets(bindings, Value(NewAnonymousRecord(exprs, fieldNames, genArgs, isStruct), r)) ->
Some(List.rev bindings, exprs, fieldNames, genArgs, isStruct, r)
| Value(NewAnonymousRecord(exprs, fieldNames, genArgs, isStruct), r) ->
Some([], exprs, fieldNames, genArgs, isStruct, r)
| _ -> None
let (|ListSingleton|) x = [ x ]
let tryFindInScope (ctx: Context) identName =
let rec findInScopeInner scope identName =
match scope with
| [] -> None
| (_, ident2: Ident, expr) :: prevScope ->
if identName = ident2.Name then
match expr with
| Some(MaybeCasted(IdentExpr ident)) -> findInScopeInner prevScope ident.Name
| expr -> expr
|> Option.map (fun e ->
if not (isNull ctx.CapturedBindings) then
ctx.CapturedBindings.Add(identName) |> ignore
e
)
else
findInScopeInner prevScope identName
findInScopeInner ctx.Scope identName
let (|MaybeInScope|) (ctx: Context) e =
match e with
| MaybeCasted(IdentExpr ident) when not ident.IsMutable ->
match tryFindInScope ctx ident.Name with
| Some(MaybeCasted e) -> e
| None -> e
| e -> e
let rec (|MaybeInScopeStringConst|_|) ctx =
function
| MaybeInScope ctx expr ->
match expr with
| StringConst s -> Some s
| Operation(Binary(BinaryPlus, (MaybeInScopeStringConst ctx s1), (MaybeInScopeStringConst ctx s2)), _, _, _) ->
Some(s1 + s2)
| Value(StringTemplate(None, start :: parts, values), _) ->
(Some [], values)
||> List.fold (fun acc value ->
match acc, value with
| None, _ -> None
| Some acc, MaybeInScopeStringConst ctx value -> Some(value :: acc)
| _ -> None
)
|> Option.map (fun values ->
let valuesAndParts = List.zip (List.rev values) parts
(start, valuesAndParts) ||> List.fold (fun acc (v, p) -> acc + v + p)
)
| _ -> None
let rec (|RequireStringConst|) com (ctx: Context) r e =
match e with
| MaybeInScopeStringConst ctx s -> s
| _ ->
addError com ctx.InlinePath r "Expecting string literal"
""
let rec (|RequireStringConstOrTemplate|) com (ctx: Context) r e =
match e with
| MaybeInScopeStringConst ctx s -> [ s ], []
// If any of the interpolated values can have side effects, beta binding reduction won't work
// so we don't check interpolation in scope
| Value(StringTemplate(None, parts, values), _) -> parts, values
| _ ->
addError com ctx.InlinePath r "Expecting string literal"
[ "" ], []
let (|CustomOp|_|) (com: ICompiler) (ctx: Context) r t opName (argExprs: Expr list) sourceTypes =
let argTypes = argExprs |> List.map (fun a -> a.Type)