-
Notifications
You must be signed in to change notification settings - Fork 322
Expand file tree
/
Copy pathFable2Python.Transforms.fs
More file actions
4766 lines (3985 loc) · 192 KB
/
Fable2Python.Transforms.fs
File metadata and controls
4766 lines (3985 loc) · 192 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 rec Fable.Transforms.Python.Transforms
open System
open System.Collections.Generic
open System.Text.RegularExpressions
open Fable
open Fable.AST
open Fable.Py
open Fable.Transforms.Python.AST
open Fable.Transforms
open Fable.Transforms.Python.Types
open Fable.Transforms.Python.Util
open Fable.Transforms.Python.Annotation
open Fable.Transforms.Python.Reflection
open Lib
open Util
/// Wrap an expression in option.erase() to convert Option[T] -> T | None.
/// This is zero runtime overhead - erase() is an identity function for type checkers.
let wrapInOptionErase (com: IPythonCompiler) ctx (expr: Expression) =
libCall com ctx None "option" "erase" [ expr ]
/// Immediately Invoked Function Expression
let iife (com: IPythonCompiler) ctx (expr: Fable.Expr) =
let args, body, returnType, typeParams =
Annotation.transformFunctionWithAnnotations com ctx None [] expr
let afe, stmts =
makeArrowFunctionExpression com ctx None (Some expr.Type) args body returnType typeParams
Expression.call (afe, []), stmts
let transformImport (com: IPythonCompiler) ctx (_r: SourceLocation option) (name: string) (moduleName: string) =
let name, parts =
let parts = Array.toList (name.Split('.'))
parts.Head, parts.Tail
com.GetImportExpr(ctx, moduleName, name) |> getParts com ctx parts
let getMemberArgsAndBody (com: IPythonCompiler) ctx kind hasSpread (args: Fable.Ident list) (body: Fable.Expr) =
// printfn "getMemberArgsAndBody: %A" hasSpread
let funcName, genTypeParams, args, body =
match kind, args with
| Attached(isStatic = false), thisArg :: args ->
let genTypeParams =
Set.difference (Annotation.getGenericTypeParams [ thisArg.Type ]) ctx.ScopedTypeParams
let body =
// TODO: If ident is not captured maybe we can just replace it with "this"
if isIdentUsed thisArg.Name body then
let thisKeyword = Fable.IdentExpr { thisArg with Name = "self" }
Fable.Let(thisArg, thisKeyword, body)
else
body
None, genTypeParams, args, body
| Attached(isStatic = true), _
| ClassConstructor, _ -> None, ctx.ScopedTypeParams, args, body
| NonAttached funcName, _ -> Some funcName, Set.empty, args, body
| _ -> None, Set.empty, args, body
let ctx =
{ ctx with ScopedTypeParams = Set.union ctx.ScopedTypeParams genTypeParams }
let args, body, returnType, _typeParams =
Annotation.transformFunctionWithAnnotations com ctx funcName args body
let args = adjustArgsForSpread hasSpread args
args, body, returnType
let getUnionCaseName (uci: Fable.UnionCase) =
match uci.CompiledName with
| Some cname -> cname
| None -> uci.Name
let getUnionExprTag (com: IPythonCompiler) ctx r (fableExpr: Fable.Expr) =
Expression.withStmts {
let! expr = com.TransformAsExpr(ctx, fableExpr)
let! finalExpr = getExpr com ctx r expr (Expression.stringConstant "tag")
return finalExpr
}
let wrapIntExpression typ (e: Expression) =
match e, typ with
| Expression.Constant _, _ -> e
| _ -> e
let wrapExprInBlockWithReturn (e, stmts) = stmts @ [ Statement.return' e ]
let makeArrowFunctionExpression
com
ctx
(name: string option)
(bodyType: Fable.Type option)
(args: Arguments)
(body: Statement list)
returnType
(typeParams: TypeParam list)
: Expression * Statement list
=
let isAsync =
match bodyType with
| Some typ -> isTaskType typ
| None -> false
let args =
match args.PosOnlyArgs, args.Args with
| [], [] ->
let ta = com.GetImportExpr(ctx, getLibPath com "util", "Unit")
Arguments.arguments (args = [ Arg.arg ("__unit", annotation = ta) ], defaults = [ Expression.tuple [] ])
| _ -> args
let allDefaultsAreNone =
args.Defaults
|> List.forall (
function
| Expression.Name { Id = Identifier "None" } -> true
| _ -> false
)
let allArgs = args.PosOnlyArgs @ args.Args
let (|ImmediatelyApplied|_|) =
function
| Expression.Call {
Func = callee
Args = appliedArgs
} when allArgs.Length = appliedArgs.Length && allDefaultsAreNone ->
// To be sure we're not running side effects when deleting the function check the callee is an identifier
match callee with
| Expression.Name _ ->
let parameters = allArgs |> List.map (fun a -> (Expression.name a.Arg))
List.zip parameters appliedArgs
|> List.forall (
function
| Expression.Name({ Id = Identifier name1 }), Expression.Name({ Id = Identifier name2 }) ->
name1 = name2
| _ -> false
)
|> function
| true -> Some callee
| false -> None
| _ -> None
| _ -> None
match body with
// Check if we can remove the function
| [ Statement.Return { Value = Some(ImmediatelyApplied(callExpr)) } ] -> callExpr, []
| _ ->
let ident =
name
|> Option.map Identifier
|> Option.defaultWith (fun _ -> Helpers.getUniqueIdentifier "_arrow")
let func =
if isAsync then
createFunctionWithTypeParams ident args body [] returnType None typeParams true
else
createFunctionWithTypeParams ident args body [] returnType None typeParams false
Expression.name ident, [ func ]
/// Check if a Fable type is a Task type (should generate async def)
let isTaskType (typ: Fable.Type) =
match typ with
| Fable.DeclaredType(ent, _) -> ent.FullName = Types.taskGeneric
| _ -> false
let createFunction name args body decoratorList returnType (comment: string option) =
createFunctionWithTypeParams name args body decoratorList returnType comment [] false
let createAsyncFunction name args body decoratorList returnType (comment: string option) =
createFunctionWithTypeParams name args body decoratorList returnType comment [] true
let createFunctionWithTypeParams
name
args
body
decoratorList
returnType
(comment: string option)
(typeParams: TypeParam list)
(isAsync: bool)
=
if isAsync then
Statement.asyncFunctionDef (
name = name,
args = args,
body = Helpers.wrapReturnWithAwait body,
decoratorList = decoratorList,
returns = Helpers.unwrapTaskType returnType,
typeParams = typeParams,
?comment = comment
)
else
Statement.functionDef (
name = name,
args = args,
body = body,
decoratorList = decoratorList,
returns = returnType,
typeParams = typeParams,
?comment = comment
)
let makeFunction name (args: Arguments, body: Expression, decoratorList, returnType) : Statement =
// printfn "makeFunction: %A" name
let body = wrapExprInBlockWithReturn (body, [])
createFunction name args body decoratorList returnType None
let makeFunctionExpression
(com: IPythonCompiler)
ctx
name
(args, body: Expression, decoratorList, returnType: Expression)
: Expression * Statement list
=
let ctx = { ctx with BoundVars = ctx.BoundVars.EnterScope() }
let name =
name
|> Option.map (fun name -> com.GetIdentifier(ctx, name))
|> Option.defaultValue (Helpers.getUniqueIdentifier "_expr")
let func = makeFunction name (args, body, decoratorList, returnType)
Expression.name name, [ func ]
let optimizeTailCall (com: IPythonCompiler) (ctx: Context) range (tc: ITailCallOpportunity) args =
let rec checkCrossRefs tempVars allArgs =
function
| [] -> tempVars
| (argId, _arg) :: rest ->
let found =
allArgs
|> List.exists (
deepExists (
function
| Fable.IdentExpr i -> argId = i.Name
| _ -> false
)
)
let tempVars =
if found then
let tempVarName = Util.getUniqueNameInDeclarationScope ctx (argId + "_tmp")
Map.add argId tempVarName tempVars
else
tempVars
checkCrossRefs tempVars allArgs rest
ctx.OptimizeTailCall()
let zippedArgs =
List.zip (tc.Args |> List.map (fun { Arg = Identifier id } -> id)) args
let tempVars = checkCrossRefs Map.empty args zippedArgs
let tempVarReplacements = tempVars |> Map.map (fun _ v -> makeIdentExpr v)
[
// First declare temp variables
for KeyValue(argId, tempVar) in tempVars do
yield! varDeclaration ctx (com.GetIdentifierAsExpr(ctx, tempVar)) None (com.GetIdentifierAsExpr(ctx, argId))
// Then assign argument expressions to the original argument identifiers
// See https://github.com/fable-compiler/Fable/issues/1368#issuecomment-434142713
for argId, arg in zippedArgs do
let arg = FableTransforms.replaceValues tempVarReplacements arg
let arg, stmts = com.TransformAsExpr(ctx, arg)
yield!
stmts
@ (assign None (com.GetIdentifierAsExpr(ctx, argId)) arg |> exprAsStatement ctx)
yield Statement.continue' (?loc = range)
]
let transformCast (com: IPythonCompiler) (ctx: Context) t e : Expression * Statement list =
// printfn "transformCast: %A" (t, e)
match t, e with
| IEnumerableOfKeyValuePair(kvpEnt) ->
// Call .items() on the dictionary and wrap with to_enumerable for IEnumerable_1 compatibility
let dictExpr, stmts = com.TransformAsExpr(ctx, e)
let itemsCall =
Expression.attribute (value = dictExpr, attr = Identifier "items", ctx = Load)
let itemsExpr = Expression.call (itemsCall, [])
// Wrap with to_enumerable to get IEnumerable_1
libCall com ctx None "util" "to_enumerable" [ itemsExpr ], stmts
// Optimization for (numeric) array or list literals casted to seq
// Done at the very end of the compile pipeline to get more opportunities
// of matching cast and literal expressions after resolving pipes, inlining...
| Fable.DeclaredType(ent, [ _ ]), _ ->
match ent.FullName, e with
| Types.ienumerableGeneric, Replacements.Util.ArrayOrListLiteral(exprs, _typ) ->
let expr, stmts =
exprs |> List.map (fun e -> com.TransformAsExpr(ctx, e)) |> Helpers.unzipArgs
let xs = Expression.list expr
libCall com ctx None "util" "to_enumerable" [ xs ], stmts
// Wrap ResizeArray (Python list) when cast to IEnumerable
// Python lists don't implement IEnumerable_1, so they need wrapping
| Types.ienumerableGeneric, _ when
match e.Type with
| Fable.Array(_, Fable.ArrayKind.ResizeArray) -> true
| Fable.DeclaredType(entRef, _) when entRef.FullName = Types.resizeArray -> true
| _ -> false
->
let listExpr, stmts = com.TransformAsExpr(ctx, e)
libCall com ctx None "util" "to_enumerable" [ listExpr ], stmts
| _ -> com.TransformAsExpr(ctx, e)
| Fable.Number(Float32, _), _ ->
let cons = libValue com ctx "core" "float32"
let value, stmts = com.TransformAsExpr(ctx, e)
Expression.call (cons, [ value ], ?loc = None), stmts
| Fable.Number(Float64, _), _ ->
let cons = libValue com ctx "core" "float64"
let value, stmts = com.TransformAsExpr(ctx, e)
Expression.call (cons, [ value ], ?loc = None), stmts
| Fable.Number(Int32, _), _ ->
let cons = libValue com ctx "core" "int32"
let value, stmts = com.TransformAsExpr(ctx, e)
Expression.call (cons, [ value ], ?loc = None), stmts
| _ -> com.TransformAsExpr(ctx, e)
let transformCurry (com: IPythonCompiler) (ctx: Context) expr arity : Expression * Statement list =
com.TransformAsExpr(ctx, Replacements.Api.curryExprAtRuntime com arity expr)
let transformValue (com: IPythonCompiler) (ctx: Context) r value : Expression * Statement list =
match value with
| Fable.BaseValue(None, _) -> Expression.identifier "super()", []
| Fable.BaseValue(Some boundIdent, _) -> identAsExpr com ctx boundIdent, []
| Fable.ThisValue _ -> Expression.identifier "self", []
| Fable.TypeInfo(t, _) -> transformTypeInfo com ctx r Map.empty t
| Fable.Null t ->
match t with
| Fable.Unit -> Expression.none, []
| _ ->
// Cast None to the expected type to satisfy the type checker
let ta, stmts = Annotation.typeAnnotation com ctx None t
wrapNoneInCast com ctx Expression.none ta, stmts
| Fable.UnitConstant -> undefined r, []
| Fable.BoolConstant x -> Expression.boolConstant (x, ?loc = r), []
| Fable.CharConstant x -> Expression.stringConstant (string<char> x, ?loc = r), []
| Fable.StringConstant x -> Expression.stringConstant (x, ?loc = r), []
| Fable.StringTemplate(_, parts, values) ->
match parts with
| [] -> makeStrConst ""
| [ part ] -> makeStrConst part
| part :: parts ->
let acc = makeStrConst part
(acc, List.zip values parts)
||> List.fold (fun acc (MaybeCasted(value), part) ->
let value =
match value.Type with
| Fable.String -> value
| _ -> Helpers.toString value
let acc = makeBinOp None Fable.String acc value BinaryPlus
makeBinOp None Fable.String acc (makeStrConst part) BinaryPlus
)
|> transformAsExpr com ctx
| Fable.NumberConstant(v, _) ->
match v with
| Fable.NumberValue.Int8 x -> makeInteger com ctx r value.Type "int8" x
| Fable.NumberValue.UInt8 x -> makeInteger com ctx r value.Type "uint8" x
| Fable.NumberValue.Int16 x -> makeInteger com ctx r value.Type "int16" x
| Fable.NumberValue.UInt16 x -> makeInteger com ctx r value.Type "uint16" x
| Fable.NumberValue.Int32 x -> makeInteger com ctx r value.Type "int32" x
| Fable.NumberValue.UInt32 x -> makeInteger com ctx r value.Type "uint32" x
| Fable.NumberValue.Int64 x -> makeInteger com ctx r value.Type "int64" x
| Fable.NumberValue.UInt64 x -> makeInteger com ctx r value.Type "uint64" x
// | Fable.NumberValue.Int128(u,l) -> Expression.intConstant (System.Int128(u,l), ?loc = r), []
// | Fable.NumberValue.UInt128(u,l) -> Expression.intConstant (System.UInt128(u,l), ?loc = r), []
| Fable.NumberValue.BigInt x -> Expression.intConstant (x, ?loc = r), []
| Fable.NumberValue.NativeInt x -> Expression.intConstant (x, ?loc = r), []
| Fable.NumberValue.UNativeInt x -> Expression.intConstant (x, ?loc = r), []
// TODO: special consts also need attention
| Fable.NumberValue.Float64 x when x = infinity -> libValue com ctx "double" "float64.infinity", []
| Fable.NumberValue.Float64 x when x = -infinity -> libValue com ctx "double" "float64.negative_infinity", []
| Fable.NumberValue.Float64 x when Double.IsNaN(x) -> libValue com ctx "double" "float64.nan", []
| Fable.NumberValue.Float32 x when Single.IsNaN(x) ->
libCall com ctx r "core" "float32" [ Expression.stringConstant "nan" ], []
| Fable.NumberValue.Float16 x when Single.IsNaN(x) ->
libCall com ctx r "core" "float32" [ Expression.stringConstant "nan" ], []
| Fable.NumberValue.Float16 x -> makeFloat com ctx r value.Type "float32" (float x)
| Fable.NumberValue.Float32 x -> makeFloat com ctx r value.Type "float32" (float x)
| Fable.NumberValue.Float64 x -> makeFloat com ctx r value.Type "float64" (float x)
| Fable.NumberValue.Decimal x -> Py.Replacements.makeDecimal com r value.Type x |> transformAsExpr com ctx
| _ -> addErrorAndReturnNull com r $"Numeric literal is not supported: %A{v}", []
| Fable.NewArray(newKind, typ, kind) ->
// printfn "NewArray: %A" (typ)
match newKind with
| Fable.ArrayValues values -> makeArray com ctx values kind typ
| Fable.ArrayAlloc size -> makeArrayAllocated com ctx typ kind size
| Fable.ArrayFrom expr -> makeArrayFrom com ctx typ kind expr
| Fable.NewTuple(vals, _) -> makeTuple com ctx vals
// Optimization for bundle size: compile list literals as List.ofArray
| Fable.NewList(headAndTail, elementType) ->
let rec getItems acc =
function
| None -> List.rev acc, None
| Some(head, Fable.Value(Fable.NewList(tail, _), _)) -> getItems (head :: acc) tail
| Some(head, tail) -> List.rev (head :: acc), Some tail
match getItems [] headAndTail with
| [], None -> libCall com ctx r "list" "empty" [], []
| [ TransformExpr com ctx (expr, stmts) ], None -> libCall com ctx r "list" "singleton" [ expr ], stmts
| exprs, None ->
let expr, stmts = makeArray com ctx exprs Fable.MutableArray elementType
[ expr ] |> libCall com ctx r "list" "ofArray", stmts
| [ TransformExpr com ctx (head, stmts) ], Some(TransformExpr com ctx (tail, stmts')) ->
libCall com ctx r "list" "cons" [ head; tail ], stmts @ stmts'
| exprs, Some(TransformExpr com ctx (tail, stmts)) ->
let expr, stmts' = makeArray com ctx exprs Fable.MutableArray elementType
[ expr; tail ] |> libCall com ctx r "list" "ofArrayWithTail", stmts @ stmts'
| Fable.NewOption(value, t, _) ->
match value with
| Some(TransformExpr com ctx (e, stmts)) ->
if mustWrapOption t then
libCall com ctx r "option" "some" [ e ], stmts
else
e, stmts
| None -> undefined r, []
| Fable.NewRecord(values, ent, _genArgs) ->
let ent = com.GetEntity(ent)
let values, stmts =
List.map (fun x -> com.TransformAsExpr(ctx, x)) values |> Helpers.unzipArgs
let consRef, stmts' = ent |> pyConstructor com ctx
Expression.call (consRef, values, ?loc = r), stmts @ stmts'
| Fable.NewAnonymousRecord(values, fieldNames, _genArgs, _isStruct) ->
let values, stmts =
values |> List.map (fun x -> com.TransformAsExpr(ctx, x)) |> Helpers.unzipArgs
List.zip (List.ofArray fieldNames) values |> makePyObject, stmts
| Fable.NewUnion(values, tag, ent, _genArgs) ->
let ent = com.GetEntity(ent)
let values, stmts =
List.map (fun x -> com.TransformAsExpr(ctx, x)) values |> Helpers.unzipArgs
let consRef, stmts' = ent |> pyConstructor com ctx
// let caseName = ent.UnionCases |> List.item tag |> getUnionCaseName |> ofString
let values = ofInt com ctx tag :: values
Expression.call (consRef, values, ?loc = r), stmts @ stmts'
| _ -> failwith $"transformValue: value %A{value} not supported!"
let extractBaseExprFromBaseCall (com: IPythonCompiler) (ctx: Context) (baseType: Fable.DeclaredType option) baseCall =
// printfn "extractBaseExprFromBaseCall: %A" (baseCall, baseType)
match baseCall, baseType with
| Some(Fable.Call(baseRef, info, _, _)), _ ->
let baseExpr, stmts =
match baseRef with
| Fable.IdentExpr id -> com.GetIdentifierAsExpr(ctx, id.Name), []
| _ -> transformAsExpr com ctx baseRef
let expr, keywords, stmts' = transformCallArgs com ctx info true
Some(baseExpr, (expr, keywords, stmts @ stmts'))
| Some(Fable.ObjectExpr([], Fable.Unit, None)), _ ->
let range = baseCall |> Option.bind (fun x -> x.Range)
let name =
baseType
|> Option.map (fun t -> t.Entity.FullName)
|> Option.defaultValue "unknown type"
$"Ignoring base call for %s{name}" |> addWarning com [] range
None
| Some(Fable.Value _), Some baseType ->
// let baseEnt = com.GetEntity(baseType.Entity)
// let entityName = FSharp2Fable.Helpers.getEntityDeclarationName com baseType.Entity
// let entityType = FSharp2Fable.Util.getEntityType baseEnt
// let baseRefId = makeTypedIdent entityType entityName
// let baseExpr = (baseRefId |> typedIdent com ctx) :> Expression
// Some (baseExpr, []) // default base constructor
let range = baseCall |> Option.bind (fun x -> x.Range)
$"Ignoring base call for %s{baseType.Entity.FullName}"
|> addWarning com [] range
None
| Some _, _ ->
let range = baseCall |> Option.bind (fun x -> x.Range)
"Unexpected base call expression, please report" |> addError com [] range
None
| None, _ -> None
let transformObjectExpr
(com: IPythonCompiler)
ctx
(members: Fable.ObjectExprMember list)
typ
baseCall
: Expression * Statement list
=
// printfn "transformObjectExpr: %A" typ
// A generic class nested in another generic class cannot use same type variables. (PEP-484)
let ctx = { ctx with TypeParamsScope = ctx.TypeParamsScope + 1 }
let makeMethod prop hasSpread (fableArgs: Fable.Ident list) (fableBody: Fable.Expr) decorators =
let args, body, returnType =
getMemberArgsAndBody com ctx (Attached(isStatic = false)) hasSpread fableArgs fableBody
let name =
let name =
match prop with
| "ToString" -> "__str__"
| _ -> prop
com.GetIdentifier(ctx, Naming.toPythonNaming name)
let self = Arg.arg "self"
let args =
match decorators with
// Remove extra parameters from getters, i.e __unit=None
| [ Expression.Name { Id = Identifier "property" } ] ->
{ args with
Args = [ self ]
Defaults = []
}
| _ -> { args with Args = self :: args.Args }
// Calculate type parameters for generic object expression methods
let argTypes = fableArgs |> List.map _.Type
let typeParams =
Annotation.calculateMethodTypeParams com ctx argTypes fableBody.Type
createFunctionWithTypeParams name args body decorators returnType None typeParams false
/// Transform a callable property (delegate) into a method statement
let transformCallableProperty (memb: Fable.ObjectExprMember) (fableArgs: Fable.Ident list) (fableBody: Fable.Expr) =
// Transform the function directly without treating first arg as 'this'
let args, body, returnType, typeParams =
Annotation.transformFunctionWithAnnotations com ctx None fableArgs fableBody
let name = com.GetIdentifier(ctx, Naming.toPythonNaming memb.Name)
let self = Arg.arg "self"
let args = { args with Args = self :: args.Args }
createFunctionWithTypeParams name args body [] returnType None typeParams false
let interfaces, stmts =
match typ with
| Fable.Any -> [], [] // Don't inherit from Any
| Fable.DeclaredType(entRef, genArgs) ->
// Map interface names to ABC base class names for inheritance
// Use ABC base classes instead of Protocols for proper method resolution
let name = Helpers.removeNamespace entRef.FullName
let fullName = entRef.FullName
// Map interface names to ABC base class(es) using shared helper
match Bases.getAbcClassesForInterface name fullName with
| Some classes ->
let exprs =
classes
|> List.map (fun abcName -> Bases.makeAbcBaseExpr com ctx abcName genArgs)
exprs, []
| None ->
// Fall back to regular type annotation for non-mapped interfaces
let ta, stmts = Annotation.typeAnnotation com ctx None typ
[ ta ], stmts
| _ ->
let ta, stmts = Annotation.typeAnnotation com ctx None typ
[ ta ], stmts
let members =
members
|> List.collect (fun memb ->
let info = com.GetMember(memb.MemberRef)
if not memb.IsMangled && (info.IsGetter || info.IsValue) then
match memb.Body with
| Fable.Delegate(args, body, _, _) ->
// Transform callable property into method
[ transformCallableProperty memb args body ]
| _ ->
// Regular property
let decorators = [ Expression.name "property" ]
[ makeMethod memb.Name false memb.Args memb.Body decorators ]
elif not memb.IsMangled && info.IsSetter then
let decorators = [ Expression.name $"%s{memb.Name}.setter" ]
[ makeMethod memb.Name false memb.Args memb.Body decorators ]
else
[ makeMethod memb.Name info.HasSpread memb.Args memb.Body [] ]
)
let _baseExpr, classMembers =
baseCall
|> extractBaseExprFromBaseCall com ctx None
|> Option.map (fun (baseExpr, (baseArgs, _kw, _stmts)) ->
let consBody = [ callSuperAsStatement baseArgs ]
let args = Arguments.empty
let classCons = makeClassConstructor args false None com ctx consBody
Some baseExpr, classCons @ members
)
|> Option.defaultValue (None, members)
|> (fun (expr, memb) -> expr |> Option.toList, memb)
let classBody =
match classMembers with
| [] -> [ Pass ]
| _ -> classMembers
let name = Helpers.getUniqueIdentifier "ObjectExpr"
let stmt = Statement.classDef (name, body = classBody, bases = interfaces)
Expression.call (Expression.name name), [ stmt ] @ stmts
let transformCallArgs
(com: IPythonCompiler)
ctx
(callInfo: Fable.CallInfo)
(isBaseConstructorCall: bool)
: Expression list * Keyword list * Statement list
=
let args =
FSharp2Fable.Util.dropUnitCallArg com callInfo.Args callInfo.SignatureArgTypes callInfo.MemberRef
let paramsInfo =
callInfo.MemberRef |> Option.bind com.TryGetMember |> Option.map getParamsInfo
// Enhanced handling for constructor calls with named arguments
let isConstructorCall =
List.contains "new" callInfo.Tags && not isBaseConstructorCall
let getCallArgs paramsInfo args =
paramsInfo
|> Option.map (splitNamedArgs args)
|> function
| None -> args, None, []
| Some(args, None) -> args, None, []
| Some(args, Some namedArgs) ->
let objArg, stmts =
namedArgs
|> List.choose (fun (param, value) ->
match param.Name, value with
| Some keyword, Fable.Value(Fable.NewOption(value, _, _), _) ->
value |> Option.map (fun value -> keyword, value)
| Some keyword, value -> Some(keyword, value)
| None, _ -> None
)
|> List.map (fun (keyword, value) ->
let value, stmts = com.TransformAsExpr(ctx, value)
(keyword, value), stmts
)
|> List.unzip
|> fun (kv, stmts) ->
kv
|> List.map (fun (keyword, value) ->
Keyword.keyword (Identifier(Naming.toPythonNaming keyword), value)
),
stmts |> List.collect id
args, Some objArg, stmts
let args, objArg, stmts =
match paramsInfo, isConstructorCall with
| Some info, true when args.Length <= info.Parameters.Length && args.Length > 0 ->
// For constructor calls, check if we should use keyword arguments
// Only apply if we have parameter names for all arguments
let relevantParams = List.take args.Length info.Parameters
let hasAllParameterNames = relevantParams |> List.forall (fun p -> p.Name.IsSome)
if hasAllParameterNames then
// Try to create keyword arguments for constructor calls
let keywordArgs =
List.zip relevantParams args
|> List.choose (fun (param, arg) ->
match param.Name with
| Some paramName -> Some(paramName, arg)
| None -> None
)
if keywordArgs.Length = args.Length then
// All parameters have names, convert to keyword arguments
let objArg, stmts =
keywordArgs
|> List.map (fun (kw, value) ->
let value, stmts = com.TransformAsExpr(ctx, value)
(kw, value), stmts
)
|> List.unzip
|> fun (kv, stmts) ->
kv
|> List.map (fun (keyword, value) ->
Keyword.keyword (Identifier(Naming.toPythonNaming keyword), value)
),
stmts |> List.collect id
[], Some objArg, stmts
else
// Fallback to regular handling
getCallArgs paramsInfo args
else
// Fallback to regular handling when not all parameters have names
getCallArgs paramsInfo args
| _ ->
// Regular handling for non-constructor calls
getCallArgs paramsInfo args
let hasSpread =
paramsInfo |> Option.map (fun i -> i.HasSpread) |> Option.defaultValue false
// Helper to transform an arg and wrap with widen() if needed
let transformArgWithWiden (sigType: Fable.Type option) (argExpr: Fable.Expr) =
let expr, stmts = com.TransformAsExpr(ctx, argExpr)
if needsOptionWidenForArg sigType argExpr then
let widen = com.TransformImport(ctx, "widen", getLibPath com "option")
Expression.call (widen, [ expr ]), stmts
else
expr, stmts
let args, stmts' =
match args with
| [] -> [], []
| args when hasSpread ->
match List.rev args with
| [] -> [], []
| Replacements.Util.ArrayOrListLiteral(spreadArgs, _) :: rest ->
let rest = List.rev rest |> List.map (fun e -> com.TransformAsExpr(ctx, e))
rest @ List.map (fun e -> com.TransformAsExpr(ctx, e)) spreadArgs
|> Helpers.unzipArgs
| last :: rest ->
let rest, stmts =
List.rev rest
|> List.map (fun e -> com.TransformAsExpr(ctx, e))
|> Helpers.unzipArgs
let expr, stmts' = com.TransformAsExpr(ctx, last)
rest @ [ Expression.starred expr ], stmts @ stmts'
| args ->
// Transform args with widen() where needed based on signature types
args
|> List.mapi (fun i e ->
let sigType = List.tryItem i callInfo.SignatureArgTypes
transformArgWithWiden sigType e
)
|> Helpers.unzipArgs
match objArg with
| None -> args, [], stmts @ stmts'
| Some objArg -> args, objArg, stmts @ stmts'
let resolveExpr (ctx: Context) _t strategy pyExpr : Statement list =
// printfn "resolveExpr: %A" (pyExpr, strategy)
match strategy with
| None
| Some ReturnUnit -> exprAsStatement ctx pyExpr
// TODO: Where to put these int wrappings? Add them also for function arguments?
| Some(ResourceManager strategy) -> resolveExpr ctx _t strategy pyExpr
| Some(Return _) -> [ Statement.return' pyExpr ]
| Some(Assign left) -> exprAsStatement ctx (assign None left pyExpr)
| Some(Target left) -> exprAsStatement ctx (assign None (left |> Expression.identifier) pyExpr)
let transformOperation com ctx range opKind tags : Expression * Statement list =
match opKind with
| Fable.Unary(op, TransformExpr com ctx (expr, stmts)) -> Expression.unaryOp (op, expr, ?loc = range), stmts
| Fable.Binary(op, left, right: Fable.Expr) ->
let typ = right.Type
let left_typ = left.Type
let left, stmts = com.TransformAsExpr(ctx, left)
let right, stmts' = com.TransformAsExpr(ctx, right)
let compare op =
Expression.compare (left, [ op ], [ right ], ?loc = range), stmts @ stmts'
let (|IsNone|_|) =
function
| Name { Id = Identifier "None" } -> Some()
| _ -> None
let strict =
match tags with
| Fable.Tags.Contains "strict" -> true
| _ -> false
match op, strict with
| BinaryEqual, true ->
match left, right with
// Use == with literals
| Constant _, _ -> compare Eq
| _, Constant _ -> compare Eq
| _ -> compare Is
| BinaryEqual, false ->
match left, right with
// Use == with literals
| Constant _, _ -> compare Eq
| _, Constant _ -> compare Eq
// Use `is` with None (except literals)
| _, IsNone -> compare Is
| IsNone, _ -> compare Is
// Use == for the rest
| _ -> compare Eq
| BinaryUnequal, true ->
match left, right with
// Use == with literals
| Constant _, _ -> compare NotEq
| _, Constant _ -> compare NotEq
| _ -> compare IsNot
| BinaryUnequal, false ->
match left, right with
// Use != with literals
| Constant _, _ -> compare NotEq
| _, Constant _ -> compare NotEq
// Use `is not` with None (except literals)
| _, IsNone -> compare IsNot
| IsNone, _ -> compare IsNot
// Use != for the rest
| _ -> compare NotEq
| BinaryLess, _ -> compare Lt
| BinaryLessOrEqual, _ -> compare LtE
| BinaryGreater, _ -> compare Gt
| BinaryGreaterOrEqual, _ -> compare GtE
| BinaryDivide, _ ->
// For integer division, we need to use the // operator
match typ with
| Fable.Number(Int8, _)
| Fable.Number(Int16, _)
| Fable.Number(Int32, _)
| Fable.Number(Int64, _)
| Fable.Number(UInt8, _)
| Fable.Number(UInt16, _)
| Fable.Number(UInt32, _)
| Fable.Number(UInt64, _) ->
// In .NET we only get floor division for left integers on the left
match left_typ with
| Fable.Number(Float32, _)
| Fable.Number(Float64, _) -> Expression.binOp (left, Div, right, ?loc = range), stmts @ stmts'
| _ -> Expression.binOp (left, FloorDiv, right, ?loc = range), stmts @ stmts'
| _ -> Expression.binOp (left, op, right, ?loc = range), stmts @ stmts'
| _ -> Expression.binOp (left, op, right, ?loc = range), stmts @ stmts'
| Fable.Logical(op, TransformExpr com ctx (left, stmts), TransformExpr com ctx (right, stmts')) ->
Expression.boolOp (op, [ left; right ], ?loc = range), stmts @ stmts'
let transformEmit (com: IPythonCompiler) ctx range (info: Fable.EmitInfo) =
let macro = info.Macro
let callInfo = info.CallInfo
let thisArg, stmts =
callInfo.ThisArg
|> Option.map (fun e -> com.TransformAsExpr(ctx, e))
|> Option.toList
|> Helpers.unzipArgs
let exprs, kw, stmts' = transformCallArgs com ctx callInfo false
if macro.StartsWith("functools", StringComparison.Ordinal) then
com.GetImportExpr(ctx, "functools") |> ignore
let args = exprs |> List.append thisArg
// Handle EmitMethod, EmitConstructor and other emit macros that need keywords
match kw with
| [] ->
// No keywords, use regular emit expression
emitExpression range macro args, stmts @ stmts'
| _ ->
// Handle emit patterns with keywords
match tryParseEmitMethodMacro macro with
| Some methodName ->
match thisArg with
| obj :: _ ->
let methodCall = Expression.attribute (obj, Identifier methodName)
callFunction range methodCall exprs kw, stmts @ stmts'
| [] ->
// Fallback to emit if no this arg
emitExpression range macro args, stmts @ stmts'
| None ->
// Try EmitConstructor pattern
match tryParseEmitConstructorMacro macro with
| Some() ->
match thisArg with
| constructorExpr :: _ ->
// Handle EmitConstructor with keywords: new Constructor(keywords)
callFunction range constructorExpr exprs kw, stmts @ stmts'
| [] ->
// Fallback to emit if no constructor expression
emitExpression range macro args, stmts @ stmts'
| None ->
// For other emit patterns with keywords, fallback to emit (might lose keywords)
emitExpression range macro args, stmts @ stmts'
/// Unwrap to_enumerable from a Python expression if present
/// make_dict can handle Python iterables directly, so we can skip the wrapper
let unwrapToEnumerable (expr: Expression) =
match expr with
| Expression.Call {
Func = Expression.Name { Id = Identifier "to_enumerable" }
Args = [ innerArg ]
} -> innerArg
| _ -> expr
let transformCall (com: IPythonCompiler) ctx range callee (callInfo: Fable.CallInfo) : Expression * Statement list =
// printfn "transformCall: %A" (callee, callInfo)
// Optimization: Unwrap to_enumerable for make_dict calls since make_dict can handle Python iterables directly
match callee with
| Fable.Import({
Selector = "make_dict"
Kind = Fable.LibraryImport _
},
_,
_) ->
let callee', stmts = com.TransformAsExpr(ctx, callee)
let args, kw, stmts' = transformCallArgs com ctx callInfo false
// Unwrap to_enumerable from the argument if present
let args = args |> List.map unwrapToEnumerable
callFunction range callee' args kw, stmts @ stmts'
| _ ->
let callee', stmts = com.TransformAsExpr(ctx, callee)
let args, kw, stmts' = transformCallArgs com ctx callInfo false
match callee, callInfo.ThisArg with
| Fable.Get(expr, Fable.FieldGet { Name = "Dispose" }, _, _), _ ->
let expr, stmts'' = com.TransformAsExpr(ctx, expr)
libCall com ctx range "util" "dispose" [ expr ], stmts @ stmts' @ stmts''
| Fable.Get(expr, Fable.FieldGet { Name = "set" }, _, _), _ ->
// printfn "Type: %A" expr.Type
Expression.withStmts {
let! right = com.TransformAsExpr(ctx, callInfo.Args.Head)
let! arg = com.TransformAsExpr(ctx, callInfo.Args.Tail.Head)
let! value = com.TransformAsExpr(ctx, expr)
return! Expression.none, [ Statement.assign ([ Expression.subscript (value, right) ], arg) ]
}
| Fable.Get(_, Fable.FieldGet { Name = "sort" }, _, _), _ -> callFunction range callee' [] kw, stmts @ stmts'
| _, Some(TransformExpr com ctx (thisArg, stmts'')) ->
callFunction range callee' (thisArg :: args) kw, stmts @ stmts' @ stmts''
| _, None when List.contains "new" callInfo.Tags ->
Expression.call (callee', args, kw, ?loc = range), stmts @ stmts'
| _, None -> callFunction range callee' args kw, stmts @ stmts'
let transformCurriedApply com ctx range (TransformExpr com ctx (applied, stmts)) args =
((applied, stmts), args)
||> List.fold (fun (applied, stmts) arg ->
let args, stmts' =
match arg with
// TODO: If arg type is unit but it's an expression with potential
// side-effects, we need to extract it and execute it before the call
// TODO: discardUnitArg may still be needed in some cases
| Fable.Value(Fable.UnitConstant, _) -> [], []
| Fable.IdentExpr ident when ident.Type = Fable.Unit -> [], []
| TransformExpr com ctx (arg, stmts') -> [ arg ], stmts'
callFunction range applied args [], stmts @ stmts'
)
let transformCallAsStatements com ctx range t returnStrategy callee callInfo =
let argsLen (i: Fable.CallInfo) =
List.length i.Args
+ (if Option.isSome i.ThisArg then
1
else
0)
// Warn when there's a recursive call that couldn't be optimized?
match returnStrategy, ctx.TailCallOpportunity with
| Some(Return _ | ReturnUnit), Some tc when tc.IsRecursiveRef(callee) && argsLen callInfo = List.length tc.Args ->
let args =
match callInfo.ThisArg with
| Some thisArg -> thisArg :: callInfo.Args
| None -> callInfo.Args
optimizeTailCall com ctx range tc args