-
Notifications
You must be signed in to change notification settings - Fork 323
Expand file tree
/
Copy pathFable2Python.Util.fs
More file actions
1714 lines (1513 loc) · 80.5 KB
/
Fable2Python.Util.fs
File metadata and controls
1714 lines (1513 loc) · 80.5 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.Util
open System
open Fable
open Fable.AST
open Fable.Py
open Fable.Transforms
open Fable.Transforms.Python.AST
open Fable.Transforms.Python.Types
// 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 Util =
open Lib
/// Returns true if this is a core library union type (Result, Choice) in user code
/// that should import case constructors from fable_library.
/// Only matches Microsoft.FSharp.Core.* (user code), not FSharp.Core.* (library source)
/// to avoid circular imports when compiling the library itself.
let isLibraryUnionType (fullName: string) =
match fullName with
| Types.result -> true
| fn when fn.StartsWith("Microsoft.FSharp.Core.FSharpChoice`", StringComparison.Ordinal) -> true
| _ -> false
/// Returns true if this union type should use simple case names (Choice1Of2, Ok, Error)
/// rather than prefixed names (MyUnion_Case1). Used for naming case classes.
/// This matches both user code (Microsoft.FSharp.Core.*) and library source (FSharp.Core.*).
let usesSimpleCaseNames (fullName: string) =
match fullName with
| Types.result -> true
| fn when fn.StartsWith("Microsoft.FSharp.Core.FSharpChoice`", StringComparison.Ordinal) -> true
| fn when fn.StartsWith("FSharp.Core.FSharpChoice`", StringComparison.Ordinal) -> true
| "FSharp.Core.FSharpResult`2" -> true
| _ -> false
/// Ensures a statement list is non-empty by adding Pass if needed.
/// Python requires at least one statement in function/class/match bodies.
let ensureNonEmptyBody stmts =
match stmts with
| [] -> [ Statement.Pass ]
| _ -> stmts
/// Extract the element type from an array type for vararg annotations.
/// For Array<T>, returns T. For other types, returns Any as fallback.
let getVarArgElementType (paramType: Fable.Type) : Fable.Type =
match paramType with
| Fable.Array(elemType, _) -> elemType
| _ -> Fable.Any // Fallback if not array type
/// Splits a list of items into regular items and an optional vararg item.
/// When hasSpread is true and items is non-empty, the last item becomes the vararg.
let splitVarArg<'T> (hasSpread: bool) (items: 'T list) : 'T list * 'T option =
if hasSpread && not items.IsEmpty then
let regular = items |> List.take (items.Length - 1)
let vararg = items |> List.last
regular, Some vararg
else
items, None
/// Adjusts Arguments to move the last arg to vararg when hasSpread is true.
/// Removes the annotation from vararg since Python infers it from *args.
let adjustArgsForSpread (hasSpread: bool) (args: Arguments) : Arguments =
let len = args.Args.Length
if not hasSpread || len = 0 then
args
else
{ args with
VarArg = Some { args.Args[len - 1] with Annotation = None }
Args = args.Args[.. len - 2]
}
let hasAttribute fullName (atts: Fable.Attribute seq) =
atts |> Seq.exists (fun att -> att.Entity.FullName = fullName)
let hasAnyEmitAttribute (atts: Fable.Attribute seq) =
hasAttribute Atts.emitAttr atts
|| hasAttribute Atts.emitMethod atts
|| hasAttribute Atts.emitConstructor atts
|| hasAttribute Atts.emitIndexer atts
|| hasAttribute Atts.emitProperty atts
/// Check if a type contains any generic parameters (recursively).
/// Used to determine if Option<T> should use Option[T] annotation vs T | None.
/// Note: This is duplicated from Annotation.fs due to compilation order (Util.fs compiles first).
let private containsGenericParams (t: Fable.Type) =
FSharp2Fable.Util.getGenParamNames [ t ] |> List.isEmpty |> not
/// Check if an Option type has a concrete inner type (erases to T | None).
/// Returns true when inner type is concrete, meaning Option[T] -> T | None.
let hasConcreteOptionInner (typ: Fable.Type) =
match typ with
| Fable.Option(innerType, _) -> not (mustWrapOption innerType)
| _ -> false
/// Check if inner type of Option is a callable with generic params (needs wrapping)
let private isCallableWithGenerics (t: Fable.Type) =
match t with
| Fable.LambdaType _
| Fable.DelegateType _ -> containsGenericParams t
| _ -> false
/// Check if a call expression needs Option erase from Option[T] to T | None.
/// When target type is Option<ConcreteType> (erased to T | None), we need to erase
/// because library functions use Option[T] (wrapped form) in their signatures,
/// but actual runtime values are not wrapped for concrete types.
/// Also handles function types (LambdaType) where the return type contains a concrete Option,
/// using the erase() overload for Callable[..., Option[T]] -> Callable[..., T | None].
let rec private needsOptionEraseForCall (targetType: Fable.Type) =
match targetType with
// Don't erase if inner type is callable with generic params - both annotation and runtime use wrapped form
| Fable.Option(tgtInner, _) when not (mustWrapOption tgtInner) && not (isCallableWithGenerics tgtInner) -> true
// Handle function types where return type is a concrete Option
// erase() has an overload: Callable[..., Option[T]] -> Callable[..., T | None]
| Fable.LambdaType(_, returnType) -> needsOptionEraseForCall returnType
| Fable.DelegateType(_, returnType) -> needsOptionEraseForCall returnType
| _ -> false
/// Check if binding needs Option erase from Option[T] to T | None.
let needsOptionEraseForBinding (value: Fable.Expr) (targetType: Fable.Type) =
match value with
| Fable.Call _
| Fable.CurriedApply _ -> needsOptionEraseForCall targetType
| _ -> false
/// Check if return expression needs Option erase from Option[T] to T | None.
/// Used when returning from a function where the expected return type is T | None
/// but the actual expression returns Option[T] (wrapped form).
let needsOptionEraseForReturn (value: Fable.Expr) (expectedReturnType: Fable.Type) =
match value with
| Fable.Call _
| Fable.CurriedApply _ -> needsOptionEraseForCall expectedReturnType
| _ -> false
/// Recursively check if a type contains Option (wrapped or erased).
let rec private containsOption (typ: Fable.Type) =
match typ with
| Fable.Option _ -> true
| Fable.Tuple(types, _) -> types |> List.exists containsOption
| Fable.Array(elemType, _) -> containsOption elemType
| Fable.List elemType -> containsOption elemType
| _ -> false
/// Check if a type is an invariant container (Array or List) with Options inside.
/// This detects cases where function return types use Option[T] for generics
/// but variable annotations would use T | None for concrete types, causing
/// invariance mismatch errors in Pyright.
let private isInvariantContainerWithOptions (typ: Fable.Type) =
match typ with
| Fable.Array(elemType, _) -> containsOption elemType
| Fable.List elemType -> containsOption elemType
| _ -> false
/// Check if we should skip type annotation to avoid Option[T] vs T | None mismatch.
/// When a Call returns an invariant container (Array/List) with Options inside,
/// the function signature uses Option[T] for generics, but the variable annotation
/// would use erased T | None. Since Array/List are invariant, this causes type errors.
/// Skip the annotation and let Python infer from function return type.
let valueExtractsFromInvariantContainer (value: Fable.Expr) (varType: Fable.Type) =
match value with
| Fable.Call _ ->
// When a call returns an invariant container with Options, skip annotation
isInvariantContainerWithOptions varType
| Fable.Get(_, Fable.ListHead, _, _) -> containsOption varType
| Fable.Get(_, Fable.ListTail, _, _) -> containsOption varType
| Fable.Get(expr, Fable.ExprGet _, _, _) -> isInvariantContainerWithOptions expr.Type && containsOption varType
| _ -> false
/// Check if a binding is assigning from a wrapped option after None check.
/// Pattern: `if x is not None: x2 = x` where x has wrapped Option type.
/// After narrowing, x is SomeWrapper[T] | T, but annotation expects T.
/// Skip annotation to avoid type mismatch.
let isWrappedOptionNarrowingAssignment (value: Fable.Expr) =
match value with
| Fable.IdentExpr ident ->
// Check if the source has a wrapped option type
match ident.Type with
| Fable.Option(innerType, _) -> mustWrapOption innerType
| _ -> false
| _ -> false
/// Get narrowed contexts for then/else branches based on a guard expression
/// Returns (thenCtx, elseCtx) with appropriate type narrowing applied
let getNarrowedContexts (ctx: Context) (guardExpr: Fable.Expr) : Context * Context =
match guardExpr with
| Fable.Test(Fable.IdentExpr ident, Fable.TypeTest typ, _) ->
// TypeTest: then branch has the narrowed type
{ ctx with NarrowedTypes = Map.add ident.Name typ ctx.NarrowedTypes }, ctx
| Fable.Test(Fable.IdentExpr ident, Fable.OptionTest nonEmpty, _) ->
// OptionTest: only narrow for erased options (T | None), not wrapped options (Option[T])
// Wrapped options require value() call to unwrap, so the type doesn't change
match ident.Type with
| Fable.Option(innerType, _) when not (mustWrapOption innerType) ->
// Erased option: type narrows from T | None to T
if nonEmpty then
// v is not None: then branch has the unwrapped type
{ ctx with NarrowedTypes = Map.add ident.Name innerType ctx.NarrowedTypes }, ctx
else
// v is None: else branch has the unwrapped type
ctx, { ctx with NarrowedTypes = Map.add ident.Name innerType ctx.NarrowedTypes }
| _ ->
// Wrapped option or non-option: no type narrowing
ctx, ctx
| _ -> ctx, ctx
/// Recursively check if a type contains Option with generic parameter that requires wrapping.
/// This checks return types of lambdas for Option[GenericParam].
let rec private hasWrappedOptionInReturnType (typ: Fable.Type) =
match typ with
| Fable.LambdaType(_, returnType) ->
// Check if return type is Option[GenericParam] or recurse into nested lambdas
match returnType with
| Fable.Option(inner, _) -> mustWrapOption inner
| Fable.LambdaType _ -> hasWrappedOptionInReturnType returnType
| _ -> false
| _ -> false
/// Check if a type would have its Option return type erased (T | None instead of Option[T]).
/// Returns true when the return type is Option[ConcreteType] which gets erased.
let rec private hasErasedOptionReturnType (typ: Fable.Type) =
match typ with
| Fable.LambdaType(_, returnType) ->
match returnType with
| Fable.Option(inner, _) -> not (mustWrapOption inner) // Erased when NOT wrapped
| Fable.LambdaType _ -> hasErasedOptionReturnType returnType
| _ -> false
| _ -> false
/// Check if a callback argument needs widen() to convert erased Option callback
/// to wrapped Option form for type checker compatibility.
/// Returns true when:
/// - Expected type is Callable with Option[GenericParam] in return position
/// - Actual arg is a lambda/function that would have erased Option return type
let needsOptionWidenForArg (expectedType: Fable.Type option) (argExpr: Fable.Expr) =
match expectedType with
| Some sigType when hasWrappedOptionInReturnType sigType ->
// Check if argument is a callable with ERASED Option return type
// If arg already has wrapped Option return, don't apply widen()
match argExpr with
| Fable.Lambda _
| Fable.Delegate _ ->
// Check if the lambda's return type would be erased
hasErasedOptionReturnType argExpr.Type
| Fable.IdentExpr ident ->
// Check if the identifier's type has erased Option return
hasErasedOptionReturnType ident.Type
| Fable.Get(_, Fable.FieldGet fieldInfo, _, _) ->
// Field access to a function
match fieldInfo.FieldType with
| Some typ -> hasErasedOptionReturnType typ
| None -> false
| _ -> false
| _ -> false
/// Wraps None values in cast(type, None) for type safety.
/// Skips if type annotation is also None (unit type).
let wrapNoneInCast (com: IPythonCompiler) ctx (value: Expression) (typeAnnotation: Expression) : Expression =
match value, typeAnnotation with
| Expression.Name { Id = Identifier "None" }, Expression.Name { Id = Identifier "None" } -> value // No cast needed for None: None = None
| Expression.Name { Id = Identifier "None" }, _ ->
let cast = com.GetImportExpr(ctx, "typing", "cast")
Expression.call (cast, [ typeAnnotation; value ])
| _ -> value
let parseClassStyle (styleStr: int) =
match styleStr with
| 0 -> ClassStyle.Properties
| 1 -> ClassStyle.Attributes
| _ -> ClassStyle.Properties // Default to Properties for unknown values
/// Tries to find a ClassAttributesTemplateAttribute on the attribute's type
/// and extract the style and init parameters
let private tryGetTemplateClassAttributes (com: Fable.Compiler) (att: Fable.Attribute) =
com.TryGetEntity(att.Entity)
|> Option.bind (fun attEntity ->
attEntity.Attributes
|> Seq.tryFind (fun a -> a.Entity.FullName = Atts.pyClassAttributesTemplate)
|> Option.bind (fun templateAtt ->
match templateAtt.ConstructorArgs with
| [ :? int as styleParam ] ->
Some
{
Style = parseClassStyle styleParam
Init = false // Default for single-arg constructor
}
| [ :? int as styleParam; :? bool as initParam ] ->
Some
{
Style = parseClassStyle styleParam
Init = initParam
}
| _ -> None
)
)
let hasPythonClassAttribute (com: Fable.Compiler) (atts: Fable.Attribute seq) =
hasAttribute Atts.pyClassAttributes atts
|| atts
|> Seq.exists (fun att -> tryGetTemplateClassAttributes com att |> Option.isSome)
let getPythonClassParameters (com: Fable.Compiler) (atts: Fable.Attribute seq) =
let defaultParams = ClassAttributes.Default
// First check for direct ClassAttributes attribute
let directResult =
atts
|> Seq.tryFind (fun att -> att.Entity.FullName = Atts.pyClassAttributes)
|> Option.map (fun att ->
match att.ConstructorArgs with
| [] -> defaultParams
| [ :? int as styleParam ] -> { defaultParams with Style = parseClassStyle styleParam }
| [ :? int as styleParam; :? bool as initParam ] ->
{
Style = parseClassStyle styleParam
Init = initParam
}
| _ -> defaultParams
)
// If no direct attribute, check for template attributes
match directResult with
| Some result -> result
| None ->
atts
|> Seq.tryPick (fun att -> tryGetTemplateClassAttributes com att)
|> Option.defaultValue defaultParams
/// Tries to find a DecorateTemplateAttribute on the attribute's type
/// and format the template with the attribute's constructor args
let private tryGetTemplateDecoratorInfo (com: Fable.Compiler) (att: Fable.Attribute) =
com.TryGetEntity(att.Entity)
|> Option.bind (fun attEntity ->
attEntity.Attributes
|> Seq.tryFind (fun a -> a.Entity.FullName = Atts.pyDecorateTemplate)
|> Option.bind (fun templateAtt ->
match templateAtt.ConstructorArgs with
| [ :? string as template ] ->
Some
{
Decorator = String.Format(template, att.ConstructorArgs |> List.toArray)
Parameters = ""
ImportFrom = ""
}
| [ :? string as template; :? string as importFrom ] ->
Some
{
Decorator = String.Format(template, att.ConstructorArgs |> List.toArray)
Parameters = ""
ImportFrom = importFrom
}
| _ -> None
)
)
/// Extracts decorator information from entity attributes
/// Constructor args order: (decorator, importFrom, parameters)
let getDecoratorInfo (com: Fable.Compiler) (atts: Fable.Attribute seq) =
atts
|> Seq.choose (fun att ->
if att.Entity.FullName = Atts.pyDecorate then
match att.ConstructorArgs with
| [ :? string as decorator ] ->
Some
{
Decorator = decorator
Parameters = ""
ImportFrom = ""
}
| [ :? string as decorator; :? string as importFrom ] ->
Some
{
Decorator = decorator
Parameters = ""
ImportFrom = importFrom
}
| [ :? string as decorator; :? string as importFrom; :? string as parameters ] ->
Some
{
Decorator = decorator
Parameters = parameters
ImportFrom = importFrom
}
| _ -> None // Invalid decorator
else
// Try to find a DecorateTemplateAttribute on this attribute's type
tryGetTemplateDecoratorInfo com att
)
|> Seq.toList
/// Generates Python decorator expressions from DecoratorInfo
/// The decorator string is emitted verbatim. If ImportFrom is specified,
/// an import statement is generated automatically.
let generateDecorators (com: IPythonCompiler) (ctx: Context) (decoratorInfos: DecoratorInfo list) =
decoratorInfos
|> List.map (fun info ->
// Handle import if ImportFrom is specified
if not (String.IsNullOrEmpty info.ImportFrom) then
// This triggers the import: from {importFrom} import {decorator}
com.GetImportExpr(ctx, info.ImportFrom, info.Decorator) |> ignore
if String.IsNullOrEmpty info.Parameters then
// Simple decorator without parameters: @decorator
Expression.emit (info.Decorator, [])
else
// Decorator with parameters: @decorator(param1=value1, param2=value2)
Expression.emit ($"%s{info.Decorator}(%s{info.Parameters})", [])
)
let getIdentifier (_com: IPythonCompiler) (_ctx: Context) (name: string) =
let name = Helpers.clean name
Identifier name
let (|TransformExpr|) (com: IPythonCompiler) ctx e : Expression * Statement list = com.TransformAsExpr(ctx, e)
let (|Function|_|) =
function
| Fable.Lambda(arg, body, _) -> Some([ arg ], body)
| Fable.Delegate(args, body, _, []) -> Some(args, body)
| _ -> None
let getUniqueNameInRootScope (ctx: Context) name =
let name =
(name, Naming.NoMemberPart)
||> Naming.sanitizeIdent (fun name ->
name <> "str" // Do not rewrite `str`
&& (ctx.UsedNames.RootScope.Contains(name)
|| ctx.UsedNames.DeclarationScopes.Contains(name))
)
ctx.UsedNames.RootScope.Add(name) |> ignore
Helpers.clean name
let getUniqueNameInDeclarationScope (ctx: Context) name =
let name =
(name, Naming.NoMemberPart)
||> Naming.sanitizeIdent (fun name ->
ctx.UsedNames.RootScope.Contains(name)
|| ctx.UsedNames.CurrentDeclarationScope.Contains(name)
)
ctx.UsedNames.CurrentDeclarationScope.Add(name) |> ignore
name
/// Determines if we should use the special record field naming convention (toRecordFieldSnakeCase)
/// for the given entity. Returns true for user-defined F# records, false for built-in types.
let shouldUseRecordFieldNaming (ent: Fable.Entity) =
ent.IsFSharpRecord
&& not (ent.FullName.StartsWith("Microsoft.FSharp.Core", StringComparison.Ordinal))
/// Determines if we should use the special record field naming convention (toRecordFieldSnakeCase)
/// for the given entity reference. Returns true for user-defined F# records, false for built-in types.
let shouldUseRecordFieldNamingForRef (entityRef: Fable.EntityRef) (ent: Fable.Entity) =
ent.IsFSharpRecord
&& not (entityRef.FullName.StartsWith("Microsoft.FSharp.Core", StringComparison.Ordinal))
// Helper function to determine the kind of field access for proper naming
let getFieldNamingKind (com: IPythonCompiler) (typ: Fable.Type) (fieldName: string) : FieldNamingKind =
match typ with
| Fable.DeclaredType(entityRef, _) when fieldName.EndsWith("@", System.StringComparison.Ordinal) ->
match com.TryGetEntity entityRef with
| Some ent ->
ent.MembersFunctionsAndValues
|> Seq.tryFind (fun memb -> (memb.IsGetter || memb.IsSetter) && $"%s{memb.DisplayName}@" = fieldName)
|> function
| Some memb when memb.IsInstance -> InstancePropertyBacking
| Some _ -> StaticProperty
| None -> RegularField
| None -> InstancePropertyBacking // Conservative fallback for unknown entities
| _ -> RegularField
/// Checks if a field name is an actual record field (not a property/method)
let isRecordField (ent: Fable.Entity) (fieldName: string) =
ent.FSharpFields |> List.exists (fun f -> f.Name = fieldName)
// Helper function to apply the appropriate naming convention based on field type and naming kind
let applyFieldNaming
(com: IPythonCompiler)
(narrowedType: Fable.Type)
(fieldName: string)
(handleAnonymousRecords: bool)
=
match getFieldNamingKind com narrowedType fieldName with
| InstancePropertyBacking -> fieldName |> Naming.toPropertyBackingFieldNaming
| StaticProperty -> fieldName |> Naming.toPropertyNaming
| RegularField ->
match narrowedType with
| Fable.AnonymousRecordType _ when handleAnonymousRecords -> fieldName // Use the field name as is for anonymous records
| Fable.DeclaredType(entityRef, _) ->
match com.TryGetEntity entityRef with
| Some ent when shouldUseRecordFieldNamingForRef entityRef ent && isRecordField ent fieldName ->
fieldName |> Naming.toRecordFieldSnakeCase |> Helpers.clean
| _ -> fieldName |> Naming.toPythonNaming // Fallback to Python naming for other types
| _ -> fieldName |> Naming.toPropertyNaming
type NamedTailCallOpportunity(com: IPythonCompiler, ctx, name, args: Fable.Ident list) =
// Capture the current argument values to prevent delayed references from getting corrupted,
// for that we use block-scoped ES2015 variable declarations. See #681, #1859
// TODO: Local unique ident names
let argIds =
args
|> FSharp2Fable.Util.discardUnitArg
|> List.map (fun arg ->
let name = getUniqueNameInDeclarationScope ctx (arg.Name + "_mut")
// Ignore type annotation here as it generates unnecessary typevars
Arg.arg name
)
interface ITailCallOpportunity with
member _.Label = name
member _.Args = argIds
member _.IsRecursiveRef(e) =
match e with
| Fable.IdentExpr id -> name = id.Name
| _ -> false
let getDecisionTarget (ctx: Context) targetIndex =
match List.tryItem targetIndex ctx.DecisionTargets with
| None -> failwith $"Cannot find DecisionTree target %i{targetIndex}"
| Some(idents, target) -> idents, target
let rec isPyStatement ctx preferStatement (expr: Fable.Expr) =
match expr with
| Fable.Unresolved _
| Fable.Value _
| Fable.Import _
| Fable.IdentExpr _
| Fable.Lambda _
| Fable.Delegate _
| Fable.ObjectExpr _
| Fable.Call _
| Fable.CurriedApply _
| Fable.Operation _
| Fable.Get _
| Fable.Test _
| Fable.TypeCast _ -> false
| Fable.TryCatch _
| Fable.Sequential _
| Fable.Let _
| Fable.LetRec _
| Fable.Set _
| Fable.ForLoop _
| Fable.WhileLoop _ -> true
| Fable.Extended(kind, _) ->
match kind with
| Fable.Throw _
| Fable.Debugger -> true
| Fable.Curry _ -> false
// TODO: If IsJsSatement is false, still try to infer it? See #2414
// /^\s*(break|continue|debugger|while|for|switch|if|try|let|const|var)\b/
| Fable.Emit(i, _, _) -> i.IsStatement
| Fable.DecisionTreeSuccess(targetIndex, _, _) ->
getDecisionTarget ctx targetIndex |> snd |> isPyStatement ctx preferStatement
// Make it also statement if we have more than, say, 3 targets?
// That would increase the chances to convert it into a switch
| Fable.DecisionTree(_, targets) -> preferStatement || List.exists (snd >> isPyStatement ctx false) targets
| Fable.IfThenElse(_, thenExpr, elseExpr, _) ->
preferStatement
|| isPyStatement ctx false thenExpr
|| isPyStatement ctx false elseExpr
let addErrorAndReturnNull (com: Compiler) (range: SourceLocation option) (error: string) =
addError com [] range error
Expression.none
let ident (com: IPythonCompiler) (ctx: Context) (id: Fable.Ident) = com.GetIdentifier(ctx, id.Name)
let identAsExpr (com: IPythonCompiler) (ctx: Context) (id: Fable.Ident) =
com.GetIdentifierAsExpr(ctx, Naming.toPythonNaming id.Name)
let getNarrowedType (ctx: Context) (id: Fable.Ident) =
match Map.tryFind id.Name ctx.NarrowedTypes with
| Some narrowedType -> narrowedType
| None -> id.Type
let thisExpr = Expression.name "self"
let ofInt (com: IPythonCompiler) (ctx: Context) (i: int) =
//Expression.intConstant (int i)
libCall com ctx None "core" "int32" [ Expression.intConstant (int i) ]
let ofString (s: string) = Expression.stringConstant s
let memberFromName
(_com: IPythonCompiler)
(_ctx: Context)
(memberName: string)
(_argCount: int option)
: Expression
=
// Name transformations for specific interfaces (Py.Map, etc.) should be handled
// in Replacements.fs, not here. This function just sanitizes the name.
let n = Naming.toPythonNaming memberName
(n, Naming.NoMemberPart)
||> Naming.sanitizeIdent (fun _ -> false)
|> Expression.name
let get (com: IPythonCompiler) ctx _r left memberName subscript =
// printfn "get: %A" (memberName, subscript)
match subscript with
| true ->
let expr = Expression.stringConstant memberName
Expression.subscript (value = left, slice = expr, ctx = Load)
| _ ->
let expr = com.GetIdentifier(ctx, memberName)
Expression.attribute (value = left, attr = expr, ctx = Load)
let getExpr _com _ctx _r (object: Expression) (expr: Expression) =
match expr with
| Expression.Constant(value = StringLiteral name) ->
let name = name |> Identifier
Expression.attribute (value = object, attr = name, ctx = Load), []
| e -> Expression.subscript (value = object, slice = e, ctx = Load), []
let rec getParts com ctx (parts: string list) (expr: Expression) =
match parts with
| [] -> expr
| m :: ms -> get com ctx None expr m false |> getParts com ctx ms
let arrayExpr (com: IPythonCompiler) ctx (expr: Expression) kind typ : Expression =
// printfn "arrayExpr: %A" typ
let array_type =
// printfn "Array type: %A" (kind, typ)
match kind, typ with
| Fable.ResizeArray, _ -> None
| _, Fable.Type.Number(UInt8, _) -> Some "byte"
| _, Fable.Type.Number(Int8, _) -> Some "sbyte"
| _, Fable.Type.Number(Int16, _) -> Some "int16"
| _, Fable.Type.Number(UInt16, _) -> Some "uint16"
| _, Fable.Type.Number(Int32, _) -> Some "int32"
| _, Fable.Type.Number(UInt32, _) -> Some "uint32"
| _, Fable.Type.Number(Int64, _) -> Some "int64"
| _, Fable.Type.Number(UInt64, _) -> Some "uint64"
| _, Fable.Type.Number(Float32, _) -> Some "float32"
| _, Fable.Type.Number(Float64, _) -> Some "float64"
| _ -> Some "Any"
// printfn "Array type: %A" array_type
match array_type with
| Some l ->
let array = libValue com ctx "array_" "Array"
let type_obj =
if l = "Any" then
com.GetImportExpr(ctx, "typing", "Any")
else
libValue com ctx "core" l
let types_array = Expression.subscript (value = array, slice = type_obj, ctx = Load)
Expression.call (types_array, [ expr ])
| None -> expr // <-- Fix: just return expr for ResizeArray
/// Creates an array from a list of Fable expressions.
/// Use this when you have multiple expressions that should become array elements.
/// Example: [1; 2; 3] -> Array[int32]([int32(1), int32(2), int32(3)])
let makeArray (com: IPythonCompiler) ctx exprs kind typ : Expression * Statement list =
// printfn "makeArray: %A" typ
let exprs, stmts =
exprs |> List.map (fun e -> com.TransformAsExpr(ctx, e)) |> Helpers.unzipArgs
arrayExpr com ctx (Expression.list exprs) kind typ, stmts
let makeArrayAllocated (com: IPythonCompiler) ctx typ _kind (size: Fable.Expr) =
// printfn "makeArrayAllocated: %A" (typ, size)
let size, stmts = com.TransformAsExpr(ctx, size)
let array = Expression.list [ Expression.intConstant 0 ]
Expression.binOp (array, Mult, size), stmts
/// Creates an array from a single Fable expression.
/// Use this when you have one expression that should be converted to an array.
/// For literals like [1; 2; 3], it delegates to makeArray.
/// For other expressions, it transforms the expression and wraps it in an array.
/// Example: someList -> Array[int32](someList)
let makeArrayFrom (com: IPythonCompiler) ctx typ kind (fableExpr: Fable.Expr) : Expression * Statement list =
// printfn "makeArrayFrom: %A" (fableExpr, typ, kind)
match fableExpr with
| Replacements.Util.ArrayOrListLiteral(exprs, _) -> makeArray com ctx exprs kind typ
| _ ->
let expr, stmts = com.TransformAsExpr(ctx, fableExpr)
arrayExpr com ctx expr kind typ, stmts
/// Creates a Python list from Fable expressions.
/// Note: This creates a plain Python list, not a Fable array.
/// Use makeArray when you need a Fable array that can be passed to functions like ofArray.
/// Example: [1; 2; 3] -> [int32(1), int32(2), int32(3)]
let makeList (com: IPythonCompiler) ctx exprs =
let expr, stmts =
exprs |> List.map (fun e -> com.TransformAsExpr(ctx, e)) |> Helpers.unzipArgs
expr |> Expression.list, stmts
let makeTuple (com: IPythonCompiler) ctx exprs =
let expr, stmts =
exprs |> List.map (fun e -> com.TransformAsExpr(ctx, e)) |> Helpers.unzipArgs
expr |> Expression.tuple, stmts
let makeStringArray strings =
strings |> List.map (fun x -> Expression.stringConstant x) |> Expression.list
let makePyObject (pairs: seq<string * Expression>) =
pairs
|> Seq.map (fun (name, value) ->
let prop = Expression.stringConstant name
prop, value
)
|> Seq.toList
|> List.unzip
|> Expression.dict
let assign range left right =
Expression.namedExpr (left, right, ?loc = range)
let multiVarDeclaration (ctx: Context) (variables: (Identifier * Expression option) list) =
// printfn "multiVarDeclaration: %A" (variables)
let ids, values =
variables
|> List.distinctBy (fun (Identifier(name = name), _value) -> name)
|> List.map (
function
| i, Some value -> Expression.name (i, Store), value, i
| i, _ -> Expression.name (i, Store), Expression.none, i
)
|> List.unzip3
|> fun (ids, values, ids') ->
ctx.BoundVars.Bind(ids')
(Expression.tuple ids, Expression.tuple values)
[ Statement.assign ([ ids ], values) ]
let varDeclaration (ctx: Context) (var: Expression) (typ: Expression option) value =
// printfn "varDeclaration: %A" (var, value, typ)
match var with
| Name { Id = id } -> do ctx.BoundVars.Bind([ id ])
| _ -> ()
[
match typ with
| Some typ -> Statement.assign (var, annotation = typ, value = value)
| _ -> Statement.assign ([ var ], value)
]
let restElement (var: Identifier) =
let var = Expression.name var
Expression.starred var
let callSuper (args: Expression list) =
let super = Expression.name "super().__init__"
Expression.call (super, args)
let callSuperAsStatement (args: Expression list) = Statement.expr (callSuper args)
let getDefaultValueForType (com: IPythonCompiler) (ctx: Context) (t: Fable.Type) : Expression =
match t with
| Fable.Boolean -> Expression.boolConstant false
| Fable.Number(kind, _) ->
match kind with
| Int8 -> makeInteger com ctx None t "int8" (0uy :> obj) |> fst
| UInt8 -> makeInteger com ctx None t "uint8" (0uy :> obj) |> fst
| Int16 -> makeInteger com ctx None t "int16" (0s :> obj) |> fst
| UInt16 -> makeInteger com ctx None t "uint16" (0us :> obj) |> fst
| Int32 -> makeInteger com ctx None t "int32" (0 :> obj) |> fst
| UInt32 -> makeInteger com ctx None t "uint32" (0u :> obj) |> fst
| Int64 -> makeInteger com ctx None t "int64" (0L :> obj) |> fst
| UInt64 -> makeInteger com ctx None t "uint64" (0UL :> obj) |> fst
| Int128
| UInt128
| BigInt
| NativeInt
| UNativeInt -> Expression.intConstant 0
| Float16 -> makeFloat com ctx None t "float32" 0.0 |> fst
| Float32 -> makeFloat com ctx None t "float32" 0.0 |> fst
| Float64 -> makeFloat com ctx None t "float64" 0.0 |> fst
| Decimal -> makeFloat com ctx None t "float64" 0.0 |> fst
| Fable.String
| Fable.Char -> Expression.stringConstant ""
| Fable.DeclaredType(ent, _) -> Expression.none
| Fable.GenericParam _ -> libValue com ctx "util" "UNIT"
| _ -> Expression.none
/// Extract initialization value from constructor body by looking for backing field assignments
let tryExtractInitializationValueFromConstructor
(com: IPythonCompiler)
(ctx: Context)
(constructorBody: Fable.Expr)
(propertyName: string)
: (Expression * Statement list) option
=
let backingFieldName = propertyName + "@"
let rec findAssignment expr =
match expr with
| Fable.Sequential exprs -> exprs |> List.tryPick findAssignment
| Fable.Set(_, Fable.FieldSet fieldName, _, value, _) when fieldName = backingFieldName ->
let expr, stmts = com.TransformAsExpr(ctx, value)
Some(expr, stmts)
| Fable.Set(Fable.Get(_, Fable.FieldGet { Name = fieldName }, _, _), Fable.FieldSet fieldName2, _, value, _) when
fieldName = backingFieldName
->
let expr, stmts = com.TransformAsExpr(ctx, value)
Some(expr, stmts)
| Fable.Set(Fable.Get(_, Fable.FieldGet { Name = fieldName }, _, _), Fable.ValueSet, _, value, _) when
fieldName = backingFieldName
->
let expr, stmts = com.TransformAsExpr(ctx, value)
Some(expr, stmts)
| _ -> None
findAssignment constructorBody
let makeClassConstructor
(args: Arguments)
(isOptional: bool)
(fieldTypes: Fable.Type list option)
(com: IPythonCompiler)
(ctx: Context)
body
=
// printfn "makeClassConstructor: %A" (args.Args, body)
let name = Identifier "__init__"
let self = Arg.arg "self"
let args_ =
match args.Args, fieldTypes with
| [ _unit ], Some types when isOptional ->
let defaults = types |> List.map (getDefaultValueForType com ctx)
{ args with
Args = self :: args.Args
Defaults = defaults
}
| _, Some types when isOptional ->
let defaults = types |> List.map (getDefaultValueForType com ctx)
{ args with
Args = self :: args.Args
Defaults = defaults
}
| [ _unit ], None when isOptional ->
{ args with
Args = self :: args.Args
Defaults = [ libValue com ctx "util" "UNIT" ]
}
| _ -> { args with Args = self :: args.Args }
match args.Args, body with
| [], []
| [], [ Statement.Pass ] -> [] // Remove empty `__init__` with no arguments
| _ -> [ Statement.functionDef (name, args_, body = body, returns = Expression.none) ]
let callFunction r funcExpr (args: Expression list) (kw: Keyword list) =
Expression.call (funcExpr, args, kw = kw, ?loc = r)
let callFunctionWithThisContext com ctx r funcExpr (args: Expression list) =
let args = thisExpr :: args
Expression.call (get com ctx None funcExpr "call" false, args, ?loc = r)
let emitExpression range (txt: string) args =
let value =
match txt with
| "$0.join('')" -> "''.join($0)"
| "throw $0" -> "raise $0"
| Naming.StartsWith "void " value
| Naming.StartsWith "new " value -> value
| _ -> txt
Expression.emit (value, args, ?loc = range)
let undefined _range : Expression = Expression.none
// Active patterns for type matching
let (|IEnumerableOfKeyValuePair|_|) (targetType: Fable.Type, sourceExpr: Fable.Expr) =
match targetType, sourceExpr.Type with
| Fable.DeclaredType(ent, [ Fable.DeclaredType(kvpEnt, [ _; _ ]) ]), Fable.DeclaredType(sourceEnt, _) when
ent.FullName = Types.ienumerableGeneric
&& kvpEnt.FullName = Types.keyValuePair
&& (sourceEnt.FullName = Types.dictionary || sourceEnt.FullName = Types.idictionary)
->
Some(kvpEnt)
| _ -> None
let makeFieldGet (expr: Expression) (field: string) =
Expression.attribute (expr, Identifier field, ctx = Load), []
let makeInteger (com: IPythonCompiler) (ctx: Context) r _t intName (x: obj) =
let cons = libValue com ctx "core" intName
let value = Expression.intConstant (x, ?loc = r)
// Added support for a few selected literals for performance reasons
match intName, x with
| _, (:? int as i) when i = 0 -> makeFieldGet cons "ZERO"
| _, (:? int as i) when i = 1 -> makeFieldGet cons "ONE"
| _, (:? int as i) when i = -1 -> makeFieldGet cons "NEG_ONE"
| _, (:? int as i) when i = 2 -> makeFieldGet cons "TWO"
| _, (:? int as i) when i = 3 -> makeFieldGet cons "THREE"
| _, (:? int as i) when i = 4 -> makeFieldGet cons "FOUR"
| _, (:? int as i) when i = 5 -> makeFieldGet cons "FIVE"
| _, (:? int as i) when i = 6 -> makeFieldGet cons "SIX"
| _, (:? int as i) when i = 7 -> makeFieldGet cons "SEVEN"
| _, (:? int as i) when i = 8 -> makeFieldGet cons "EIGHT"
| _, (:? int as i) when i = 9 -> makeFieldGet cons "NINE"
| _, (:? int as i) when i = 10 -> makeFieldGet cons "TEN"
| _, (:? int as i) when i = 16 -> makeFieldGet cons "SIXTEEN"
| _, (:? int as i) when i = 32 -> makeFieldGet cons "THIRTY_TWO"
| _, (:? int as i) when i = 64 -> makeFieldGet cons "SIXTY_FOUR"
| _, (:? int8 as i) when i = 0y -> makeFieldGet cons "ZERO"
| _, (:? int8 as i) when i = 1y -> makeFieldGet cons "ONE"
| _, (:? int8 as i) when i = -1y -> makeFieldGet cons "NEG_ONE"
| _, (:? int8 as i) when i = 2y -> makeFieldGet cons "TWO"
| _, (:? int8 as i) when i = 3y -> makeFieldGet cons "THREE"
| _, (:? int8 as i) when i = 4y -> makeFieldGet cons "FOUR"
| _, (:? int8 as i) when i = 5y -> makeFieldGet cons "FIVE"
| _, (:? int8 as i) when i = 6y -> makeFieldGet cons "SIX"
| _, (:? int8 as i) when i = 7y -> makeFieldGet cons "SEVEN"
| _, (:? int8 as i) when i = 8y -> makeFieldGet cons "EIGHT"
| _, (:? int8 as i) when i = 9y -> makeFieldGet cons "NINE"
| _, (:? int8 as i) when i = 10y -> makeFieldGet cons "TEN"
| _, (:? int8 as i) when i = 16y -> makeFieldGet cons "SIXTEEN"
| _, (:? int8 as i) when i = 32y -> makeFieldGet cons "THIRTY_TWO"
| _, (:? int8 as i) when i = 64y -> makeFieldGet cons "SIXTY_FOUR"
| _, (:? uint8 as i) when i = 0uy -> makeFieldGet cons "ZERO"
| _, (:? uint8 as i) when i = 1uy -> makeFieldGet cons "ONE"
| _, (:? uint8 as i) when i = 2uy -> makeFieldGet cons "TWO"
| _, (:? uint8 as i) when i = 3uy -> makeFieldGet cons "THREE"
| _, (:? uint8 as i) when i = 4uy -> makeFieldGet cons "FOUR"
| _, (:? uint8 as i) when i = 5uy -> makeFieldGet cons "FIVE"
| _, (:? uint8 as i) when i = 6uy -> makeFieldGet cons "SIX"
| _, (:? uint8 as i) when i = 7uy -> makeFieldGet cons "SEVEN"
| _, (:? uint8 as i) when i = 8uy -> makeFieldGet cons "EIGHT"
| _, (:? uint8 as i) when i = 9uy -> makeFieldGet cons "NINE"
| _, (:? uint8 as i) when i = 10uy -> makeFieldGet cons "TEN"
| _, (:? uint8 as i) when i = 16uy -> makeFieldGet cons "SIXTEEN"
| _, (:? uint8 as i) when i = 32uy -> makeFieldGet cons "THIRTY_TWO"
| _, (:? uint8 as i) when i = 64uy -> makeFieldGet cons "SIXTY_FOUR"
| _, (:? int16 as i) when i = 0s -> makeFieldGet cons "ZERO"
| _, (:? int16 as i) when i = 1s -> makeFieldGet cons "ONE"
| _, (:? int16 as i) when i = -1s -> makeFieldGet cons "NEG_ONE"
| _, (:? int16 as i) when i = 2s -> makeFieldGet cons "TWO"
| _, (:? int16 as i) when i = 3s -> makeFieldGet cons "THREE"
| _, (:? int16 as i) when i = 4s -> makeFieldGet cons "FOUR"
| _, (:? int16 as i) when i = 5s -> makeFieldGet cons "FIVE"
| _, (:? int16 as i) when i = 6s -> makeFieldGet cons "SIX"
| _, (:? int16 as i) when i = 7s -> makeFieldGet cons "SEVEN"
| _, (:? int16 as i) when i = 8s -> makeFieldGet cons "EIGHT"
| _, (:? int16 as i) when i = 9s -> makeFieldGet cons "NINE"
| _, (:? int16 as i) when i = 10s -> makeFieldGet cons "TEN"
| _, (:? int16 as i) when i = 16s -> makeFieldGet cons "SIXTEEN"
| _, (:? int16 as i) when i = 32s -> makeFieldGet cons "THIRTY_TWO"
| _, (:? int16 as i) when i = 64s -> makeFieldGet cons "SIXTY_FOUR"
| _, (:? uint16 as i) when i = 0us -> makeFieldGet cons "ZERO"
| _, (:? uint16 as i) when i = 1us -> makeFieldGet cons "ONE"
| _, (:? uint16 as i) when i = 2us -> makeFieldGet cons "TWO"
| _, (:? uint16 as i) when i = 3us -> makeFieldGet cons "THREE"
| _, (:? uint16 as i) when i = 4us -> makeFieldGet cons "FOUR"
| _, (:? uint16 as i) when i = 5us -> makeFieldGet cons "FIVE"
| _, (:? uint16 as i) when i = 6us -> makeFieldGet cons "SIX"
| _, (:? uint16 as i) when i = 7us -> makeFieldGet cons "SEVEN"
| _, (:? uint16 as i) when i = 8us -> makeFieldGet cons "EIGHT"
| _, (:? uint16 as i) when i = 9us -> makeFieldGet cons "NINE"
| _, (:? uint16 as i) when i = 10us -> makeFieldGet cons "TEN"
| _, (:? uint16 as i) when i = 16us -> makeFieldGet cons "SIXTEEN"
| _, (:? uint16 as i) when i = 32us -> makeFieldGet cons "THIRTY_TWO"
| _, (:? uint16 as i) when i = 64us -> makeFieldGet cons "SIXTY_FOUR"
| _, (:? uint32 as i) when i = 0u -> makeFieldGet cons "ZERO"
| _, (:? uint32 as i) when i = 1u -> makeFieldGet cons "ONE"
| _, (:? uint32 as i) when i = 2u -> makeFieldGet cons "TWO"