-
Notifications
You must be signed in to change notification settings - Fork 311
/
Copy pathFable2Python.fs
4480 lines (3680 loc) · 183 KB
/
Fable2Python.fs
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.Fable2Python
open System
open System.Collections.Generic
open System.Text.RegularExpressions
open Fable
open Fable.AST
open Fable.AST.Python
open Fable.Py
type ReturnStrategy =
/// Return last expression
| Return
| ReturnUnit
/// Return within a with-statement (to make sure we don't TC with statements)
| ResourceManager
| Assign of Expression
| Target of Identifier
type Import =
{
Module: string
LocalIdent: Identifier
Name: string option
}
type ITailCallOpportunity =
abstract Label: string
abstract Args: Arg list
abstract IsRecursiveRef: Fable.Expr -> bool
type UsedNames =
{
RootScope: HashSet<string>
DeclarationScopes: HashSet<string>
CurrentDeclarationScope: HashSet<string>
}
/// Python specific, used for keeping track of existing variable bindings to
/// know if we need to declare an identifier as nonlocal or global.
type BoundVars =
{
EnclosingScope: HashSet<string>
LocalScope: HashSet<string>
Inceptions: int
}
member this.EnterScope() =
// printfn "Entering scope"
let enclosingScope = HashSet<string>()
enclosingScope.UnionWith(this.EnclosingScope)
enclosingScope.UnionWith(this.LocalScope)
{
LocalScope = HashSet()
EnclosingScope = enclosingScope
Inceptions = this.Inceptions + 1
}
member this.Bind(name: string) = this.LocalScope.Add name |> ignore
member this.Bind(ids: Identifier list) =
for Identifier name in ids do
this.LocalScope.Add name |> ignore
member this.NonLocals(idents: Identifier list) =
[
for ident in idents do
let (Identifier name) = ident
if not (this.LocalScope.Contains name) && this.EnclosingScope.Contains name then
ident
else
this.Bind(name)
]
type Context =
{
File: Fable.File
UsedNames: UsedNames
BoundVars: BoundVars
DecisionTargets: (Fable.Ident list * Fable.Expr) list
HoistVars: Fable.Ident list -> bool
TailCallOpportunity: ITailCallOpportunity option
OptimizeTailCall: unit -> unit
ScopedTypeParams: Set<string>
TypeParamsScope: int
}
type IPythonCompiler =
inherit Compiler
abstract AddTypeVar: ctx: Context * name: string -> Expression
abstract AddExport: name: string -> Expression
abstract GetIdentifier: ctx: Context * name: string -> Identifier
abstract GetIdentifierAsExpr: ctx: Context * name: string -> Expression
abstract GetAllImports: unit -> Import list
abstract GetAllExports: unit -> HashSet<string>
abstract GetAllTypeVars: unit -> HashSet<string>
abstract GetImportExpr: Context * moduleName: string * ?name: string * ?loc: SourceLocation -> Expression
abstract TransformAsExpr: Context * Fable.Expr -> Expression * Statement list
abstract TransformAsStatements: Context * ReturnStrategy option * Fable.Expr -> Statement list
abstract TransformImport: Context * selector: string * path: string -> Expression
abstract TransformFunction:
Context * string option * Fable.Ident list * Fable.Expr * Set<string> -> Arguments * Statement list
abstract WarnOnlyOnce: string * ?range: SourceLocation -> unit
// TODO: All things that depend on the library should be moved to Replacements
// to become independent of the specific implementation
module Lib =
let libCall (com: IPythonCompiler) ctx r moduleName memberName args =
Expression.call (com.TransformImport(ctx, memberName, getLibPath com moduleName), args, ?loc = r)
let libConsCall (com: IPythonCompiler) ctx r moduleName memberName args =
Expression.call (com.TransformImport(ctx, memberName, getLibPath com moduleName), args, ?loc = r)
let libValue (com: IPythonCompiler) ctx moduleName memberName =
com.TransformImport(ctx, memberName, getLibPath com moduleName)
let tryPyConstructor (com: IPythonCompiler) ctx ent =
match Py.Replacements.tryConstructor com ent with
| Some e -> com.TransformAsExpr(ctx, e) |> Some
| None -> None
let pyConstructor (com: IPythonCompiler) ctx ent =
let entRef = Py.Replacements.constructor com ent
com.TransformAsExpr(ctx, entRef)
module Reflection =
open Lib
let private libReflectionCall (com: IPythonCompiler) ctx r memberName args =
libCall com ctx r "reflection" (memberName + "_type") args
let private transformRecordReflectionInfo com ctx r (ent: Fable.Entity) generics =
// TODO: Refactor these three bindings to reuse in transformUnionReflectionInfo
let fullname = ent.FullName
let fullnameExpr = Expression.stringConstant fullname
let genMap =
let genParamNames =
ent.GenericParameters |> List.mapToArray (fun x -> x.Name) |> Seq.toList
List.zip genParamNames generics |> Map
let fields, stmts =
ent.FSharpFields
|> Seq.map (fun fi ->
let typeInfo, stmts = transformTypeInfo com ctx r genMap fi.FieldType
let name = fi.Name |> Naming.toSnakeCase |> Helpers.clean
(Expression.tuple [ Expression.stringConstant name; typeInfo ]), stmts
)
|> Seq.toList
|> Helpers.unzipArgs
let fields = Expression.lambda (Arguments.arguments [], Expression.list fields)
let py, stmts' = pyConstructor com ctx ent
[ fullnameExpr; Expression.list generics; py; fields ]
|> libReflectionCall com ctx None "record",
stmts @ stmts'
let private transformUnionReflectionInfo com ctx r (ent: Fable.Entity) generics =
let fullname = ent.FullName
let fullnameExpr = Expression.stringConstant fullname
let genMap =
let genParamNames =
ent.GenericParameters |> List.map (fun x -> x.Name) |> Seq.toList
List.zip genParamNames generics |> Map
let cases =
ent.UnionCases
|> Seq.map (fun uci ->
uci.UnionCaseFields
|> List.map (fun fi ->
Expression.tuple
[
fi.Name |> Expression.stringConstant
let expr, _stmts = transformTypeInfo com ctx r genMap fi.FieldType
expr
]
)
|> Expression.list
)
|> Seq.toList
let cases = Expression.lambda (Arguments.arguments [], Expression.list cases)
let py, stmts = pyConstructor com ctx ent
[ fullnameExpr; Expression.list generics; py; cases ]
|> libReflectionCall com ctx None "union",
stmts
let transformTypeInfo
(com: IPythonCompiler)
ctx
r
(genMap: Map<string, Expression>)
t
: Expression * Statement list
=
let primitiveTypeInfo name =
libValue com ctx "Reflection" (name + "_type")
let numberInfo kind =
getNumberKindName kind |> primitiveTypeInfo
let nonGenericTypeInfo fullname =
[ Expression.stringConstant fullname ] |> libReflectionCall com ctx None "class"
let resolveGenerics generics : Expression list * Statement list =
generics
|> Array.map (transformTypeInfo com ctx r genMap)
|> List.ofArray
|> Helpers.unzipArgs
let genericTypeInfo name genArgs =
let resolved, stmts = resolveGenerics genArgs
libReflectionCall com ctx None name resolved, stmts
let genericEntity (fullname: string) (generics: Expression list) =
libReflectionCall
com
ctx
None
"class"
[
Expression.stringConstant fullname
if not (List.isEmpty generics) then
Expression.list generics
]
match t with
| Fable.Measure _
| Fable.Any -> primitiveTypeInfo "obj", []
| Fable.GenericParam(name = name) ->
match Map.tryFind name genMap with
| Some t -> t, []
| None ->
Replacements.Util.genericTypeInfoError name |> addError com [] r
Expression.none, []
| Fable.Unit -> primitiveTypeInfo "unit", []
| Fable.Boolean -> primitiveTypeInfo "bool", []
| Fable.Char -> primitiveTypeInfo "char", []
| Fable.String -> primitiveTypeInfo "string", []
| Fable.Number(kind, info) ->
match info with
| Fable.NumberInfo.IsEnum entRef ->
let ent = com.GetEntity(entRef)
let cases =
ent.FSharpFields
|> Seq.choose (fun fi ->
match fi.Name with
| "value__" -> None
| name ->
let value =
match fi.LiteralValue with
| Some v -> Convert.ToDouble v
| None -> 0.
Expression.tuple [ Expression.stringConstant name; Expression.floatConstant value ]
|> Some
)
|> Seq.toList
|> Expression.list
[ Expression.stringConstant entRef.FullName; numberInfo kind; cases ]
|> libReflectionCall com ctx None "enum",
[]
| _ -> numberInfo kind, []
| Fable.LambdaType(argType, returnType) -> genericTypeInfo "lambda" [| argType; returnType |]
| Fable.DelegateType(argTypes, returnType) -> genericTypeInfo "delegate" [| yield! argTypes; yield returnType |]
| Fable.Tuple(genArgs, _) -> genericTypeInfo "tuple" (List.toArray genArgs)
| Fable.Option(genArg, _) -> genericTypeInfo "option" [| genArg |]
| Fable.Array(genArg, _) -> genericTypeInfo "array" [| genArg |]
| Fable.List genArg -> genericTypeInfo "list" [| genArg |]
| Fable.Regex -> nonGenericTypeInfo Types.regex, []
| Fable.MetaType -> nonGenericTypeInfo Types.type_, []
| Fable.AnonymousRecordType(fieldNames, genArgs, _isStruct) ->
let genArgs, stmts = resolveGenerics (List.toArray genArgs)
List.zip (List.ofArray fieldNames) genArgs
|> List.map (fun (k, t) -> Expression.tuple [ Expression.stringConstant k; t ])
|> libReflectionCall com ctx None "anonRecord",
stmts
| Fable.DeclaredType(entRef, generics) ->
let fullName = entRef.FullName
match fullName, generics with
| Replacements.Util.BuiltinEntity kind ->
match kind with
| Replacements.Util.BclGuid
| Replacements.Util.BclTimeSpan
| Replacements.Util.BclDateTime
| Replacements.Util.BclDateTimeOffset
| Replacements.Util.BclDateOnly
| Replacements.Util.BclTimeOnly
| Replacements.Util.BclTimer -> genericEntity fullName [], []
| Replacements.Util.BclHashSet gen
| Replacements.Util.FSharpSet gen ->
let gens, stmts = transformTypeInfo com ctx r genMap gen
genericEntity fullName [ gens ], stmts
| Replacements.Util.BclDictionary(key, value)
| Replacements.Util.BclKeyValuePair(key, value)
| Replacements.Util.FSharpMap(key, value) ->
let keys, stmts = transformTypeInfo com ctx r genMap key
let values, stmts' = transformTypeInfo com ctx r genMap value
genericEntity fullName [ keys; values ], stmts @ stmts'
| Replacements.Util.FSharpResult(ok, err) ->
let ent = com.GetEntity(entRef)
let ok', stmts = transformTypeInfo com ctx r genMap ok
let err', stmts' = transformTypeInfo com ctx r genMap err
let expr, stmts'' = transformUnionReflectionInfo com ctx r ent [ ok'; err' ]
expr, stmts @ stmts' @ stmts''
| Replacements.Util.FSharpChoice gen ->
let ent = com.GetEntity(entRef)
let gen, stmts =
List.map (transformTypeInfo com ctx r genMap) gen |> Helpers.unzipArgs
let expr, stmts' = gen |> transformUnionReflectionInfo com ctx r ent
expr, stmts @ stmts'
| Replacements.Util.FSharpReference gen ->
let ent = com.GetEntity(entRef)
let gen, stmts = transformTypeInfo com ctx r genMap gen
let expr, stmts' = [ gen ] |> transformRecordReflectionInfo com ctx r ent
expr, stmts @ stmts'
| _ ->
let ent = com.GetEntity(entRef)
let generics, stmts =
generics |> List.map (transformTypeInfo com ctx r genMap) |> Helpers.unzipArgs
// Check if the entity is actually declared in Python code
if
ent.IsInterface
|| FSharp2Fable.Util.isErasedOrStringEnumEntity ent
|| FSharp2Fable.Util.isGlobalOrImportedEntity ent
|| FSharp2Fable.Util.isReplacementCandidate entRef
then
genericEntity ent.FullName generics, stmts
else
let reflectionMethodExpr =
FSharp2Fable.Util.entityIdentWithSuffix com entRef Naming.reflectionSuffix
let callee, stmts' = com.TransformAsExpr(ctx, reflectionMethodExpr)
Expression.call (callee, generics), stmts @ stmts'
let transformReflectionInfo com ctx r (ent: Fable.Entity) generics =
if ent.IsFSharpRecord then
transformRecordReflectionInfo com ctx r ent generics
elif ent.IsFSharpUnion then
transformUnionReflectionInfo com ctx r ent generics
else
let fullname = ent.FullName
let exprs, stmts =
[
yield Expression.stringConstant fullname, []
match generics with
| [] -> yield Util.undefined None, []
| generics -> yield Expression.list generics, []
match tryPyConstructor com ctx ent with
| Some(Expression.Name { Id = name }, stmts) ->
yield Expression.name (name.Name |> Naming.toSnakeCase), stmts
| Some(cons, stmts) -> yield cons, stmts
| None -> ()
match ent.BaseType with
| Some d ->
let genMap =
Seq.zip ent.GenericParameters generics
|> Seq.map (fun (p, e) -> p.Name, e)
|> Map
yield
Fable.DeclaredType(d.Entity, d.GenericArgs)
|> transformTypeInfo com ctx r genMap
| None -> ()
]
|> Helpers.unzipArgs
exprs |> libReflectionCall com ctx r "class", stmts
let private ofString s = Expression.stringConstant s
let private ofArray exprs = Expression.list exprs
let transformTypeTest (com: IPythonCompiler) ctx range expr (typ: Fable.Type) : Expression * Statement list =
let warnAndEvalToFalse msg =
"Cannot type test (evals to false): " + msg |> addWarning com [] range
Expression.boolConstant false
let pyTypeof (primitiveType: string) (Util.TransformExpr com ctx (expr, stmts)) : Expression * Statement list =
let typeof =
let func = Expression.name (Identifier("type"))
let str = Expression.name (Identifier("str"))
let typ = Expression.call (func, [ expr ])
Expression.call (str, [ typ ])
Expression.compare (typeof, [ Eq ], [ Expression.stringConstant primitiveType ], ?loc = range), stmts
let pyInstanceof consExpr (Util.TransformExpr com ctx (expr, stmts)) : Expression * Statement list =
let func = Expression.name (Identifier("isinstance"))
let args = [ expr; consExpr ]
Expression.call (func, args), stmts
match typ with
| Fable.Measure _ // Dummy, shouldn't be possible to test against a measure type
| Fable.Any -> Expression.boolConstant true, []
| Fable.Unit ->
let expr, stmts = com.TransformAsExpr(ctx, expr)
Expression.compare (expr, [ Is ], [ Util.undefined None ], ?loc = range), stmts
| Fable.Boolean -> pyTypeof "<class 'bool'>" expr
| Fable.Char
| Fable.String -> pyTypeof "<class 'str'>" expr
| Fable.Number(kind, _b) ->
match kind, typ with
| _, Fable.Type.Number(Int8, _) -> pyTypeof "<class 'fable_modules.fable_library.types.int8'>" expr
| _, Fable.Type.Number(UInt8, _) -> pyTypeof "<class 'fable_modules.fable_library.types.uint8'>" expr
| _, Fable.Type.Number(Int16, _) -> pyTypeof "<class 'fable_modules.fable_library.types.int16'>" expr
| _, Fable.Type.Number(UInt16, _) -> pyTypeof "<class 'fable_modules.fable_library.types.uint16'>" expr
| _, Fable.Type.Number(Int32, _) -> pyTypeof "<class 'int'>" expr
| _, Fable.Type.Number(UInt32, _) -> pyTypeof "<class 'fable_modules.fable_library.types.uint32'>" expr
| _, Fable.Type.Number(Int64, _) -> pyTypeof "<class 'fable_modules.fable_library.types.int64'>" expr
| _, Fable.Type.Number(UInt64, _) -> pyTypeof "<class 'fable_modules.fable_library.types.uint64'>" expr
| _, Fable.Type.Number(Float32, _) -> pyTypeof "<class 'fable_modules.fable_library.types.float32'>" expr
| _, Fable.Type.Number(Float64, _) -> pyTypeof "<class 'float'>" expr
| _, Fable.Type.Number(Decimal, _) -> pyTypeof "<class 'decimal.Decimal'>" expr
| _ -> pyTypeof "<class 'int'>" expr
| Fable.Regex -> pyInstanceof (com.GetImportExpr(ctx, "typing", "Pattern")) expr
| Fable.LambdaType _
| Fable.DelegateType _ -> pyTypeof "<class 'function'>" expr
| Fable.Array _
| Fable.Tuple _ ->
let expr, stmts = com.TransformAsExpr(ctx, expr)
libCall com ctx None "util" "isArrayLike" [ expr ], stmts
| Fable.List _ -> pyInstanceof (libValue com ctx "List" "FSharpList") expr
| Fable.AnonymousRecordType _ -> warnAndEvalToFalse "anonymous records", []
| Fable.MetaType -> pyInstanceof (libValue com ctx "Reflection" "TypeInfo") expr
| Fable.Option _ -> warnAndEvalToFalse "options", [] // TODO
| Fable.GenericParam _ -> warnAndEvalToFalse "generic parameters", []
| Fable.DeclaredType(ent, genArgs) ->
match ent.FullName with
| Types.idisposable ->
match expr with
| MaybeCasted(ExprType(Fable.DeclaredType(ent2, _))) when
com.GetEntity(ent2) |> FSharp2Fable.Util.hasInterface Types.idisposable
->
Expression.boolConstant true, []
| _ ->
let expr, stmts = com.TransformAsExpr(ctx, expr)
libCall com ctx None "util" "isDisposable" [ expr ], stmts
| Types.ienumerable ->
let expr, stmts = com.TransformAsExpr(ctx, expr)
[ expr ] |> libCall com ctx None "util" "isIterable", stmts
| Types.array ->
let expr, stmts = com.TransformAsExpr(ctx, expr)
[ expr ] |> libCall com ctx None "util" "isArrayLike", stmts
| Types.exception_ ->
let expr, stmts = com.TransformAsExpr(ctx, expr)
[ expr ] |> libCall com ctx None "types" "isException", stmts
| Types.datetime -> pyInstanceof (com.GetImportExpr(ctx, "datetime", "datetime")) expr
| _ ->
let ent = com.GetEntity(ent)
if ent.IsInterface then
match FSharp2Fable.Util.tryGlobalOrImportedEntity com ent with
| Some typeExpr ->
let typeExpr, stmts = com.TransformAsExpr(ctx, typeExpr)
let expr, stmts' = pyInstanceof typeExpr expr
expr, stmts @ stmts'
| None -> warnAndEvalToFalse "interfaces", []
else
match tryPyConstructor com ctx ent with
| Some(cons, stmts) ->
if not (List.isEmpty genArgs) then
com.WarnOnlyOnce("Generic args are ignored in type testing", ?range = range)
let expr, stmts' = pyInstanceof cons expr
expr, stmts @ stmts'
| None -> warnAndEvalToFalse ent.FullName, []
module Helpers =
/// Returns true if the first field type can be None in Python
let isOptional (fields: Fable.Ident[]) =
if fields.Length < 1 then
false
else
match fields[0].Type with
| Fable.GenericParam _ -> true
| Fable.Option _ -> true
| Fable.Unit -> true
| Fable.Any -> true
| _ -> false
let removeNamespace (fullName: string) =
fullName.Split('.')
|> Array.last
|> (fun name -> name.Replace("`", "_"))
|> Helpers.clean
let getUniqueIdentifier (name: string) : Identifier =
let idx = Naming.getUniqueIndex ()
let deliminator =
if Char.IsLower name[0] then
"_"
else
""
Identifier($"{name}{deliminator}{idx}")
/// Replaces all '$' and `.`with '_'
let clean (name: string) =
(name, Naming.NoMemberPart) ||> Naming.sanitizeIdent (fun _ -> false)
let unzipArgs (args: (Expression * Statement list) list) : Expression list * Statement list =
let stmts = args |> List.map snd |> List.collect id
let args = args |> List.map fst
args, stmts
/// A few statements in the generated Python AST do not produce any effect,
/// and should not be printed.
let isProductiveStatement (stmt: Statement) =
let rec hasNoSideEffects (e: Expression) =
match e with
| Constant _ -> true
| Dict { Keys = keys } -> keys.IsEmpty // Empty object
| Name _ -> true // E.g `void 0` is translated to Name(None)
| _ -> false
match stmt with
// Remove `self = self`
| Statement.Assign {
Targets = [ Name { Id = Identifier x } ]
Value = Name { Id = Identifier y }
} when x = y -> None
| Statement.AnnAssign {
Target = Name { Id = Identifier x }
Value = Some(Name { Id = Identifier y })
} when x = y -> None
| Expr expr ->
if hasNoSideEffects expr.Value then
None
else
Some stmt
| _ -> Some stmt
let toString (e: Fable.Expr) =
let callInfo = Fable.CallInfo.Create(args = [ e ])
makeIdentExpr "str" |> makeCall None Fable.String callInfo
// https://www.python.org/dev/peps/pep-0484/
module Annotation =
open Lib
let getEntityGenParams (ent: Fable.Entity) =
ent.GenericParameters |> Seq.map (fun x -> x.Name) |> Set.ofSeq
let makeTypeParamDecl (com: IPythonCompiler) ctx (genParams: Set<string>) =
if (Set.isEmpty genParams) then
[]
else
com.GetImportExpr(ctx, "typing", "Generic") |> ignore
let genParams =
genParams
|> Set.toList
|> List.map (fun genParam -> com.AddTypeVar(ctx, genParam))
let generic = Expression.name "Generic"
[ Expression.subscript (generic, Expression.tuple genParams) ]
let private libReflectionCall (com: IPythonCompiler) ctx r memberName args =
libCall com ctx r "reflection" (memberName + "_type") args
let fableModuleAnnotation (com: IPythonCompiler) ctx moduleName memberName args =
let expr = com.TransformImport(ctx, memberName, getLibPath com moduleName)
match args with
| [] -> expr
| [ arg ] -> Expression.subscript (expr, arg)
| args -> Expression.subscript (expr, Expression.tuple args)
let stdlibModuleAnnotation (com: IPythonCompiler) ctx moduleName memberName args =
let expr = com.TransformImport(ctx, memberName, moduleName)
match memberName, args with
| "Callable", args ->
let returnType = List.last args
let args =
match args with
| Expression.Name { Id = Identifier Ellipsis } :: _xs -> Expression.ellipsis
| _ ->
args
|> List.removeAt (args.Length - 1)
|> List.choose (
function
| Expression.Name { Id = Identifier "None" } when args.Length = 2 -> None
| x -> Some x
)
|> Expression.list
Expression.subscript (expr, Expression.tuple [ args; returnType ])
| _, [] -> expr
| _, [ arg ] -> Expression.subscript (expr, arg)
| _, args -> Expression.subscript (expr, Expression.tuple args)
let fableModuleTypeHint com ctx moduleName memberName genArgs repeatedGenerics =
let resolved, stmts = resolveGenerics com ctx genArgs repeatedGenerics
fableModuleAnnotation com ctx moduleName memberName resolved, stmts
let stdlibModuleTypeHint com ctx moduleName memberName genArgs =
let resolved, stmts = resolveGenerics com ctx genArgs None
stdlibModuleAnnotation com ctx moduleName memberName resolved, stmts
let makeGenTypeParamInst com ctx (genArgs: Fable.Type list) (repeatedGenerics: Set<string> option) =
match genArgs with
| [] -> []
| _ -> genArgs |> List.map (typeAnnotation com ctx repeatedGenerics) |> List.map fst
let makeGenericTypeAnnotation
(com: IPythonCompiler)
ctx
(id: string)
(genArgs: Fable.Type list)
(repeatedGenerics: Set<string> option)
=
stdlibModuleAnnotation com ctx "__future__" "annotations" [] |> ignore
let typeParamInst = makeGenTypeParamInst com ctx genArgs repeatedGenerics
let name = Expression.name id
if typeParamInst.IsEmpty then
name
else
Expression.subscript (name, Expression.tuple typeParamInst)
let makeGenericTypeAnnotation'
(com: IPythonCompiler)
ctx
(id: string)
(genArgs: string list)
(repeatedGenerics: Set<string> option)
=
stdlibModuleAnnotation com ctx "__future__" "annotations" [] |> ignore
let name = Expression.name id
if genArgs.IsEmpty then
name
else
let genArgs =
match repeatedGenerics with
| Some generics ->
let genArgs = genArgs |> Set.ofList |> Set.intersect generics |> Set.toList
if genArgs.IsEmpty then
[ stdlibModuleAnnotation com ctx "typing" "Any" [] ]
else
genArgs |> List.map (fun name -> com.AddTypeVar(ctx, name))
| _ -> genArgs |> List.map (fun name -> com.AddTypeVar(ctx, name))
Expression.subscript (name, Expression.tuple genArgs)
let resolveGenerics com ctx generics repeatedGenerics : Expression list * Statement list =
generics
|> List.map (typeAnnotation com ctx repeatedGenerics)
|> Helpers.unzipArgs
let typeAnnotation
(com: IPythonCompiler)
ctx
(repeatedGenerics: Set<string> option)
(t: Fable.Type)
: Expression * Statement list
=
// printfn "typeAnnotation: %A" (t, repeatedGenerics)
match t with
| Fable.Measure _
| Fable.Any -> stdlibModuleTypeHint com ctx "typing" "Any" []
| Fable.GenericParam(name = name) when name.StartsWith("$$", StringComparison.Ordinal) ->
stdlibModuleTypeHint com ctx "typing" "Any" []
| Fable.GenericParam(name = name) ->
match repeatedGenerics with
| Some names when names.Contains name ->
let name = Helpers.clean name
com.AddTypeVar(ctx, name), []
| Some _ -> stdlibModuleTypeHint com ctx "typing" "Any" []
| None ->
let name = Helpers.clean name
com.AddTypeVar(ctx, name), []
| Fable.Unit -> Expression.none, []
| Fable.Boolean -> Expression.name "bool", []
| Fable.Char -> Expression.name "str", []
| Fable.String -> Expression.name "str", []
| Fable.Number(kind, info) -> makeNumberTypeAnnotation com ctx kind info
| Fable.LambdaType(argType, returnType) ->
let argTypes, returnType = uncurryLambdaType -1 [ argType ] returnType
stdlibModuleTypeHint com ctx "collections.abc" "Callable" (argTypes @ [ returnType ])
| Fable.DelegateType(argTypes, returnType) ->
stdlibModuleTypeHint com ctx "collections.abc" "Callable" (argTypes @ [ returnType ])
| Fable.Option(genArg, _) ->
let resolved, stmts = resolveGenerics com ctx [ genArg ] repeatedGenerics
Expression.binOp (resolved[0], BitOr, Expression.none), stmts
| Fable.Tuple(genArgs, _) -> makeGenericTypeAnnotation com ctx "tuple" genArgs None, []
| Fable.Array(genArg, _) ->
match genArg with
| Fable.Type.Number(UInt8, _) -> Expression.name "bytearray", []
| Fable.Type.Number(Int8, _)
| Fable.Type.Number(Int16, _)
| Fable.Type.Number(UInt16, _)
| Fable.Type.Number(Int32, _)
| Fable.Type.Number(UInt32, _)
| Fable.Type.Number(Float32, _)
| Fable.Type.Number(Float64, _)
| _ -> fableModuleTypeHint com ctx "types" "Array" [ genArg ] repeatedGenerics
| Fable.List genArg -> fableModuleTypeHint com ctx "list" "FSharpList" [ genArg ] repeatedGenerics
| Replacements.Util.Builtin kind -> makeBuiltinTypeAnnotation com ctx kind repeatedGenerics
| Fable.AnonymousRecordType(_, _genArgs, _) ->
let value = Expression.name "dict"
let any, stmts = stdlibModuleTypeHint com ctx "typing" "Any" []
Expression.subscript (value, Expression.tuple [ Expression.name "str"; any ]), stmts
| Fable.DeclaredType(entRef, genArgs) -> makeEntityTypeAnnotation com ctx entRef genArgs repeatedGenerics
| _ -> stdlibModuleTypeHint com ctx "typing" "Any" []
let makeNumberTypeAnnotation com ctx kind info =
let numberInfo kind =
let name =
match kind with
| Int8 -> "int8"
| UInt8 -> "uint8"
| Int16 -> "int16"
| UInt16 -> "uint16"
| UInt32 -> "uint32"
| Int64 -> "int64"
| UInt64 -> "uint64"
| Int32
| BigInt
| Int128
| UInt128
| NativeInt
| UNativeInt -> "int"
| Float16
| Float32 -> "float32"
| Float64 -> "float"
| _ -> failwith $"Unsupported number type: {kind}"
match name with
| "int"
| "float" -> Expression.name name
| _ -> fableModuleAnnotation com ctx "types" name []
match kind, info with
| _, Fable.NumberInfo.IsEnum entRef ->
let ent = com.GetEntity(entRef)
let cases =
ent.FSharpFields
|> Seq.choose (fun fi ->
match fi.Name with
| "value__" -> None
| name ->
let value =
match fi.LiteralValue with
| Some v -> Convert.ToDouble v
| None -> 0.
Expression.tuple [ Expression.stringConstant name; Expression.floatConstant value ]
|> Some
)
|> Seq.toList
|> Expression.list
[ Expression.stringConstant entRef.FullName; numberInfo kind; cases ]
|> libReflectionCall com ctx None "enum",
[]
| Decimal, _ -> stdlibModuleTypeHint com ctx "decimal" "Decimal" []
| _ -> numberInfo kind, []
let makeImportTypeId (com: IPythonCompiler) ctx moduleName typeName =
let expr = com.GetImportExpr(ctx, getLibPath com moduleName, typeName)
match expr with
| Expression.Name { Id = Identifier id } -> id
| _ -> typeName
let makeImportTypeAnnotation com ctx genArgs moduleName typeName =
let id = makeImportTypeId com ctx moduleName typeName
makeGenericTypeAnnotation com ctx id genArgs None
let makeEntityTypeAnnotation com ctx (entRef: Fable.EntityRef) genArgs repeatedGenerics =
// printfn "DeclaredType: %A" entRef.FullName
match entRef.FullName, genArgs with
| Types.result, _ ->
let resolved, stmts = resolveGenerics com ctx genArgs repeatedGenerics
fableModuleAnnotation com ctx "result" "FSharpResult_2" resolved, stmts
| Replacements.Util.BuiltinEntity _kind -> stdlibModuleTypeHint com ctx "typing" "Any" []
(*
| Replacements.Util.BclGuid
| Replacements.Util.BclTimeSpan
| Replacements.Util.BclDateTime
| Replacements.Util.BclDateTimeOffset
| Replacements.Util.BclDateOnly
| Replacements.Util.BclTimeOnly
| Replacements.Util.BclTimer
| Replacements.Util.BclBigInt -> genericEntity fullName [], []
| Replacements.Util.BclHashSet gen
| Replacements.Util.FSharpSet gen ->
let gens, stmts = transformTypeInfo com ctx r genMap gen
genericEntity fullName [ gens ], stmts
| entName when entName.StartsWith(Types.choiceNonGeneric) ->
makeUnionTypeAnnotation com ctx genArgs
*)
| Types.fsharpAsyncGeneric, _ ->
let resolved, stmts = resolveGenerics com ctx genArgs repeatedGenerics
fableModuleAnnotation com ctx "async_builder" "Async" resolved, stmts
| Types.taskGeneric, _ -> stdlibModuleTypeHint com ctx "typing" "Awaitable" genArgs
| Types.icomparable, _ -> libValue com ctx "util" "IComparable", []
| Types.iStructuralEquatable, _ -> libValue com ctx "util" "IStructuralEquatable", []
| Types.iStructuralComparable, _ -> libValue com ctx "util" "IStructuralComparable", []
| Types.icomparerGeneric, _ ->
let resolved, stmts = resolveGenerics com ctx genArgs repeatedGenerics
fableModuleAnnotation com ctx "util" "IComparer_1" resolved, stmts
| Types.iequalityComparer, _ -> libValue com ctx "util" "IEqualityComparer", []
| Types.iequalityComparerGeneric, _ ->
let resolved, stmts = stdlibModuleTypeHint com ctx "typing" "Any" []
fableModuleAnnotation com ctx "util" "IEqualityComparer_1" [ resolved ], stmts
| Types.ienumerator, _ ->
let resolved, stmts = stdlibModuleTypeHint com ctx "typing" "Any" []
fableModuleAnnotation com ctx "util" "IEnumerator" [ resolved ], stmts
| Types.ienumeratorGeneric, _ ->
let resolved, stmts = resolveGenerics com ctx genArgs repeatedGenerics
fableModuleAnnotation com ctx "util" "IEnumerator" resolved, stmts
| Types.ienumerable, _ ->
let resolved, stmts = stdlibModuleTypeHint com ctx "typing" "Any" []
fableModuleAnnotation com ctx "util" "IEnumerable" [ resolved ], stmts
| Types.ienumerableGeneric, _ ->
let resolved, stmts = resolveGenerics com ctx genArgs repeatedGenerics
fableModuleAnnotation com ctx "util" "IEnumerable_1" resolved, stmts
| Types.iequatableGeneric, _ ->
let resolved, stmts = stdlibModuleTypeHint com ctx "typing" "Any" []
fableModuleAnnotation com ctx "util" "IEquatable" [ resolved ], stmts
| Types.icomparableGeneric, _ ->
let resolved, stmts = resolveGenerics com ctx genArgs repeatedGenerics
fableModuleAnnotation com ctx "util" "IComparable_1" resolved, stmts
| Types.icollection, _
| Types.icollectionGeneric, _ ->
let resolved, stmts = resolveGenerics com ctx genArgs repeatedGenerics
fableModuleAnnotation com ctx "util" "ICollection" resolved, stmts
| Types.idisposable, _ -> libValue com ctx "util" "IDisposable", []
| Types.iobserverGeneric, _ ->
let resolved, stmts = resolveGenerics com ctx genArgs repeatedGenerics
fableModuleAnnotation com ctx "observable" "IObserver" resolved, stmts
| Types.iobservableGeneric, _ ->
let resolved, stmts = resolveGenerics com ctx genArgs repeatedGenerics
fableModuleAnnotation com ctx "observable" "IObservable" resolved, stmts
| Types.idictionary, _ ->
let resolved, stmts = resolveGenerics com ctx genArgs repeatedGenerics
fableModuleAnnotation com ctx "util" "IDictionary" resolved, stmts
| Types.ievent2, _ ->
let resolved, stmts = resolveGenerics com ctx genArgs repeatedGenerics
fableModuleAnnotation com ctx "event" "IEvent_2" resolved, stmts
| Types.cancellationToken, _ -> libValue com ctx "async_builder" "CancellationToken", []
| Types.mailboxProcessor, _ ->
let resolved, stmts = resolveGenerics com ctx genArgs repeatedGenerics
fableModuleAnnotation com ctx "mailbox_processor" "MailboxProcessor" resolved, stmts
| "Fable.Core.Py.Callable", _ ->
let any, stmts = stdlibModuleTypeHint com ctx "typing" "Any" []
let genArgs = [ Expression.ellipsis; any ]
stdlibModuleAnnotation com ctx "collections.abc" "Callable" genArgs, stmts
| _ ->
let ent = com.GetEntity(entRef)
// printfn "DeclaredType: %A" ent.FullName
if ent.IsInterface then
let name = Helpers.removeNamespace ent.FullName
// If the interface is imported then it's erased and we need to add the actual imports
match ent.Attributes with
| FSharp2Fable.Util.ImportAtt(name, importPath) -> com.GetImportExpr(ctx, importPath, name) |> ignore
| _ ->
match entRef.SourcePath with
| Some path when path <> com.CurrentFile ->
// this is just to import the interface
let importPath = Path.getRelativeFileOrDirPath false com.CurrentFile false path
com.GetImportExpr(ctx, importPath, name) |> ignore
| _ -> ()
makeGenericTypeAnnotation com ctx name genArgs repeatedGenerics, []
else
match tryPyConstructor com ctx ent with
| Some(entRef, stmts) ->
match entRef with
(*
| Literal(Literal.StringLiteral(StringLiteral(str, _))) ->
match str with
| "number" -> NumberTypeAnnotation
| "boolean" -> BooleanTypeAnnotation
| "string" -> StringTypeAnnotation
| _ -> AnyTypeAnnotation*)
| Expression.Name { Id = Identifier id } ->
makeGenericTypeAnnotation com ctx id genArgs repeatedGenerics, stmts
// TODO: Resolve references to types in nested modules
| _ -> stdlibModuleTypeHint com ctx "typing" "Any" []
| None -> stdlibModuleTypeHint com ctx "typing" "Any" []
let makeBuiltinTypeAnnotation com ctx kind repeatedGenerics =
match kind with
| Replacements.Util.BclGuid -> Expression.name "str", []
| Replacements.Util.FSharpReference genArg ->
makeImportTypeAnnotation com ctx [ genArg ] "types" "FSharpRef", []
(*
| Replacements.Util.BclTimeSpan -> NumberTypeAnnotation
| Replacements.Util.BclDateTime -> makeSimpleTypeAnnotation com ctx "Date"
| Replacements.Util.BclDateTimeOffset -> makeSimpleTypeAnnotation com ctx "Date"
| Replacements.Util.BclDateOnly -> makeSimpleTypeAnnotation com ctx "Date"
| Replacements.Util.BclTimeOnly -> NumberTypeAnnotation
| Replacements.Util.BclTimer -> makeImportTypeAnnotation com ctx [] "Timer" "Timer"
| Replacements.Util.BclDecimal -> makeImportTypeAnnotation com ctx [] "Decimal" "decimal"
| Replacements.Util.BclBigInt -> makeImportTypeAnnotation com ctx [] "BigInt/z" "BigInteger"
| Replacements.Util.BclHashSet key -> makeNativeTypeAnnotation com ctx [key] "Set"
| Replacements.Util.BclDictionary (key, value) -> makeNativeTypeAnnotation com ctx [key; value] "Map"
| Replacements.Util.BclKeyValuePair (key, value) -> makeTupleTypeAnnotation com ctx [key; value]
| Replacements.Util.FSharpSet key -> makeImportTypeAnnotation com ctx [key] "Set" "FSharpSet"
| Replacements.Util.FSharpMap (key, value) -> makeImportTypeAnnotation com ctx [key; value] "Map" "FSharpMap"
| Replacements.Util.FSharpChoice genArgs ->
$"FSharpChoice${List.length genArgs}"
|> makeImportTypeAnnotation com ctx genArgs "Fable.Core"
*)
| Replacements.Util.FSharpResult(ok, err) ->
let resolved, stmts = resolveGenerics com ctx [ ok; err ] repeatedGenerics
fableModuleAnnotation com ctx "result" "FSharpResult_2" resolved, stmts
| _ -> stdlibModuleTypeHint com ctx "typing" "Any" []
let transformFunctionWithAnnotations (com: IPythonCompiler) ctx name (args: Fable.Ident list) (body: Fable.Expr) =
let argTypes = args |> List.map (fun id -> id.Type)
// In Python a generic type arg must appear both in the argument and the return type (cannot appear only once)
let repeatedGenerics =
Util.getRepeatedGenericTypeParams ctx (argTypes @ [ body.Type ])
let args', body' = com.TransformFunction(ctx, name, args, body, repeatedGenerics)
let returnType, stmts = typeAnnotation com ctx (Some repeatedGenerics) body.Type