-
Notifications
You must be signed in to change notification settings - Fork 326
Expand file tree
/
Copy pathPythonPrinter.fs
More file actions
1121 lines (891 loc) · 38.2 KB
/
Copy pathPythonPrinter.fs
File metadata and controls
1121 lines (891 loc) · 38.2 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
// fsharplint:disable InterfaceNames
module Fable.Transforms.PythonPrinter
open System
open Fable
open Fable.AST
open Fable.Transforms.Python.AST
open Fable.Transforms.Printer
module PrinterExtensions =
type Printer with
/// Print a single type parameter (Python 3.12+ syntax)
/// Handles bounds: T: SomeType
member printer.PrintTypeParam(tp: TypeParam) =
match tp with
| TypeVar tv ->
printer.Print tv.Name
match tv.Bound with
| Some bound ->
printer.Print ": "
printer.Print bound
| None -> ()
| ParamSpec ps -> printer.Print ps.Name
| TypeVarTuple tvt -> printer.Print tvt.Name
/// Print type parameters if any (Python 3.12+ syntax)
member printer.PrintTypeParams(typeParams: TypeParam list) =
if not (List.isEmpty typeParams) then
printer.Print "["
for i, tp in List.indexed typeParams do
printer.PrintTypeParam tp
if i < typeParams.Length - 1 then
printer.Print ", "
printer.Print "]"
member printer.Print(stmt: Statement) =
match stmt with
| AsyncFunctionDef def -> printer.Print(def)
| FunctionDef def -> printer.Print(def)
| ImportFrom im -> printer.Print(im)
| NonLocal st -> printer.Print(st)
| ClassDef st -> printer.Print(st)
| AsyncFor st -> printer.Print(st)
| Return rtn -> printer.Print(rtn)
| Global st -> printer.Print(st)
| Assert st -> printer.Print(st)
| Import im -> printer.Print(im)
| Assign st -> printer.Print(st)
| AnnAssign st -> printer.Print(st)
| While wh -> printer.Print(wh)
| Raise st -> printer.Print(st)
| Expr st -> printer.Print(st)
| With wi -> printer.Print(wi)
| Match mt -> printer.Print(mt)
| For st -> printer.Print(st)
| Try st -> printer.Print(st)
| If st -> printer.Print(st)
| TypeAlias st -> printer.Print st
| Pass -> printer.Print("pass")
| Break -> printer.Print("break")
| Continue -> printer.Print("continue")
member printer.Print(node: Try) =
printer.Print("try:", ?loc = node.Loc)
printer.PrintBlock(node.Body)
for handler in node.Handlers do
printer.Print(handler)
if node.OrElse.Length > 0 then
printer.Print("else:")
printer.PrintBlock(node.OrElse)
if node.FinalBody.Length > 0 then
printer.Print("finally:")
printer.PrintBlock(node.FinalBody)
member printer.Print(arg: Arg) =
let (Identifier name) = arg.Arg
printer.Print(name)
match arg.Annotation with
| Some ann ->
printer.Print(": ")
printer.Print(ann)
| _ -> ()
member printer.Print(st: Assert) =
printer.Print("assert ")
printer.Print(st.Test)
if st.Msg.IsSome then
printer.Print(", ")
printer.Print(st.Msg.Value)
member printer.Print(kw: Keyword) =
let (Identifier name) = kw.Arg
printer.Print(name)
printer.Print(" = ")
printer.Print(kw.Value)
member printer.Print(arguments: Arguments) =
let posonlyargs = arguments.PosOnlyArgs |> List.map AST.Arg
let args = arguments.Args |> List.map AST.Arg
let defaults = arguments.Defaults
// Defaults apply to the combined positional args (posonlyargs + args)
let totalPosArgs = posonlyargs.Length + args.Length
// Print positional-only args with their defaults
for i = 0 to posonlyargs.Length - 1 do
printer.Print(posonlyargs.[i])
if i >= totalPosArgs - defaults.Length then
printer.Print("=")
printer.Print(defaults[i - (totalPosArgs - defaults.Length)])
if i < posonlyargs.Length - 1 then
printer.Print(", ")
// Print the / separator if there are positional-only args
if not posonlyargs.IsEmpty then
if args.IsEmpty then
printer.Print(", /")
else
printer.Print(", /, ")
// Print regular args with their defaults
for i = 0 to args.Length - 1 do
printer.Print(args.[i])
let posIndex = posonlyargs.Length + i
if posIndex >= totalPosArgs - defaults.Length then
printer.Print("=")
printer.Print(defaults[posIndex - (totalPosArgs - defaults.Length)])
if i < args.Length - 1 then
printer.Print(", ")
match arguments.PosOnlyArgs, arguments.Args, arguments.VarArg with
| [], [], Some vararg ->
// No positional args at all, just print *vararg
printer.Print("*")
printer.Print(vararg)
| _, _, Some vararg ->
// Has positional-only or regular args, need comma before *vararg
printer.Print(", *")
printer.Print(vararg)
| _ -> ()
member printer.Print(wi: With) =
printer.Print("with ")
printer.PrintCommaSeparatedList(wi.Items)
printer.Print(":")
printer.PrintNewLine()
printer.PushIndentation()
printer.PrintStatements(wi.Body)
printer.PopIndentation()
member printer.Print(wi: WithItem) =
printer.Print(wi.ContextExpr)
match wi.OptionalVars with
| Some vars ->
printer.Print(" as ")
printer.Print(vars)
| None -> ()
member printer.Print(assign: Assign) =
for target in assign.Targets do
printer.Print(target)
printer.Print(" = ")
printer.Print(assign.Value)
member printer.Print(assign: AnnAssign) =
printer.Print(assign.Target)
printer.Print(": ")
printer.Print(assign.Annotation)
match assign.Value with
| Some value ->
printer.Print(" = ")
printer.Print(value)
| _ -> ()
member printer.Print(expr: Expr) = printer.Print(expr.Value)
member printer.Print(forIn: For) =
printer.Print("for ")
printer.Print(forIn.Target)
printer.Print(" in ")
printer.Print(forIn.Iterator)
printer.Print(":")
printer.PrintNewLine()
printer.PushIndentation()
printer.PrintStatements(forIn.Body)
printer.PopIndentation()
member printer.Print(_asyncFor: AsyncFor) = printer.Print("(AsyncFor)")
member printer.Print(wh: While) =
printer.Print("while ")
printer.Print(wh.Test)
printer.Print(":")
printer.PrintNewLine()
printer.PushIndentation()
printer.PrintStatements(wh.Body)
printer.PopIndentation()
member printer.Print(cd: ClassDef) =
for deco in cd.DecoratorList do
printer.Print("@")
printer.Print(deco)
printer.PrintNewLine()
let (Identifier name) = cd.Name
printer.Print("class ", ?loc = cd.Loc)
printer.Print(name)
// Print type parameters if any (Python 3.12+ syntax)
printer.PrintTypeParams(cd.TypeParams)
// Print bases and keywords (like metaclass=StaticPropertyMeta)
let hasBases = not (List.isEmpty cd.Bases)
let hasKeywords = not (List.isEmpty cd.Keywords)
if hasBases || hasKeywords then
printer.Print("(")
// Print bases first
if hasBases then
printer.PrintCommaSeparatedList(cd.Bases)
// Print keywords after bases (if both exist, separate with comma)
if hasKeywords then
if hasBases then
printer.Print(", ")
cd.Keywords
|> List.iteri (fun i kw ->
if i > 0 then
printer.Print(", ")
let (Identifier name) = kw.Arg
printer.Print(name)
printer.Print("=")
printer.Print(kw.Value)
)
printer.Print(")")
printer.Print(":")
printer.PrintNewLine()
printer.PushIndentation()
match cd.Body with
| [] -> printer.PrintStatements([ Statement.ellipsis ])
| body -> printer.PrintStatements(body)
printer.PopIndentation()
member printer.Print(ifElse: If) =
let rec printElse stmts =
match stmts with
| []
| [ Pass ] -> ()
| [ If {
Test = test
Body = body
Else = els
} ] ->
printer.Print("elif ")
printer.Print(test)
printer.Print(":")
printer.PrintBlock(body)
printElse els
| xs ->
printer.Print("else:")
printer.PrintBlock(xs)
printer.Print("if ")
printer.Print(ifElse.Test)
printer.Print(":")
printer.PrintBlock(ifElse.Body)
printElse ifElse.Else
member printer.Print(node: Match) =
printer.Print("match ", ?loc = node.Loc)
printer.Print(node.Subject)
printer.Print(":")
printer.PrintNewLine()
printer.PushIndentation()
for case in node.Cases do
printer.Print(case)
printer.PopIndentation()
member printer.Print(node: MatchCase) =
printer.Print("case ")
printer.Print(node.Pattern)
match node.Guard with
| Some guard ->
printer.Print(" if ")
printer.Print(guard)
| None -> ()
printer.Print(":")
printer.PrintBlock(node.Body)
member printer.Print(node: Pattern) =
match node with
| MatchValue expr -> printer.Print(expr)
| MatchSingleton lit ->
match lit with
| BoolLiteral true -> printer.Print("True")
| BoolLiteral false -> printer.Print("False")
| NoneLiteral -> printer.Print("None")
| _ -> printer.Print(Expression.constant lit)
| MatchSequence patterns ->
printer.Print("[")
printer.PrintCommaSeparatedList(patterns)
printer.Print("]")
| MatchMapping(keys, patterns, rest) ->
printer.Print("{")
for i, (key, pattern) in List.zip keys patterns |> List.indexed do
printer.Print(key)
printer.Print(": ")
printer.Print(pattern)
if i < keys.Length - 1 then
printer.Print(", ")
match rest with
| Some name ->
if not (List.isEmpty keys) then
printer.Print(", ")
printer.Print("**")
printer.Print(name)
| None -> ()
printer.Print("}")
| MatchClass(cls, patterns, kwdAttrs, kwdPatterns) ->
printer.Print(cls)
printer.Print("(")
// Print positional patterns
for i, pattern in patterns |> List.indexed do
printer.Print(pattern)
if i < patterns.Length - 1 then
printer.Print(", ")
// Print keyword patterns
if not (List.isEmpty kwdAttrs) then
if not (List.isEmpty patterns) then
printer.Print(", ")
for i, (attr, pattern) in List.zip kwdAttrs kwdPatterns |> List.indexed do
printer.Print(attr)
printer.Print("=")
printer.Print(pattern)
if i < kwdAttrs.Length - 1 then
printer.Print(", ")
printer.Print(")")
| MatchStar name ->
printer.Print("*")
match name with
| Some n -> printer.Print(n)
| None -> printer.Print("_")
| MatchAs(pattern, name) ->
match pattern, name with
| None, None -> printer.Print("_")
| None, Some n -> printer.Print(n)
| Some pat, None -> printer.Print(pat)
| Some pat, Some n ->
printer.Print(pat)
printer.Print(" as ")
printer.Print(n)
| MatchOr patterns ->
for i, pattern in patterns |> List.indexed do
printer.Print(pattern)
if i < patterns.Length - 1 then
printer.Print(" | ")
member printer.Print(ri: Raise) =
printer.Print("raise ")
printer.Print(ri.Exception)
member printer.Print(func: FunctionDef) =
printer.PrintFunction(
Some func.Name,
func.Args,
func.Body,
func.Returns,
func.DecoratorList,
?comment = func.Comment,
isDeclaration = true,
?typeParams =
(if List.isEmpty func.TypeParams then
None
else
Some func.TypeParams)
)
printer.PrintNewLine()
member printer.Print(func: AsyncFunctionDef) =
printer.PrintFunction(
Some func.Name,
func.Args,
func.Body,
func.Returns,
func.DecoratorList,
?comment = func.Comment,
isDeclaration = true,
isAsync = true,
?typeParams =
(if List.isEmpty func.TypeParams then
None
else
Some func.TypeParams)
)
printer.PrintNewLine()
member printer.Print(gl: Global) =
if not (List.isEmpty gl.Names) then
printer.Print("global ")
printer.PrintCommaSeparatedList(gl.Names)
member printer.Print(nl: NonLocal) =
if not (List.isEmpty nl.Names) then
printer.Print("nonlocal ")
printer.PrintCommaSeparatedList nl.Names
member printer.Print(im: Import) =
if not (List.isEmpty im.Names) then
printer.Print("import ")
if List.length im.Names > 1 then
printer.Print("(")
printer.PrintCommaSeparatedList(im.Names)
if List.length im.Names > 1 then
printer.Print(")")
member printer.Print(im: ImportFrom) =
let (Identifier path) = im.Module |> Option.defaultValue (Identifier ".")
printer.Print("from ")
printer.Print(path)
printer.Print(" import ")
if not (List.isEmpty im.Names) then
if List.length im.Names > 1 then
printer.Print("(")
printer.PrintCommaSeparatedList(im.Names)
if List.length im.Names > 1 then
printer.Print(")")
member printer.Print(node: Return) =
printer.Print("return ")
printer.PrintOptional(node.Value)
member printer.Print(ta: TypeAlias) =
printer.Print("type ", ?loc = ta.Loc)
printer.Print(ta.Name)
// Print type parameters if any (Python 3.12+ syntax)
printer.PrintTypeParams(ta.TypeParams)
printer.Print(" = ")
printer.Print(ta.Value)
member printer.Print(node: Attribute) =
// Wrap complex expressions (like BinOp) in parens for correct precedence
printer.ComplexExpressionWithParens(node.Value)
printer.Print(".")
printer.Print(node.Attr)
member printer.Print(ne: NamedExpr) =
printer.Print(ne.Target)
printer.Print(" := ")
printer.Print(ne.Value)
member printer.Print(node: Subscript) =
printer.Print(node.Value)
printer.Print("[")
match node.Slice with
| Tuple { Elements = [] } -> printer.Print("()")
| Tuple { Elements = elems } -> printer.PrintCommaSeparatedList(elems)
| _ -> printer.Print(node.Slice)
printer.Print("]")
member printer.Print(node: BinOp) =
printer.PrintOperation(node.Left, node.Operator, node.Right)
member printer.Print(node: BoolOp) =
for i, value in node.Values |> List.indexed do
printer.ComplexExpressionWithParens(value)
if i < node.Values.Length - 1 then
printer.Print(node.Operator)
member printer.Print(node: Compare) =
//printer.AddLocation(loc)
printer.ComplexExpressionWithParens(node.Left)
for op, comparator in List.zip node.Ops node.Comparators do
printer.Print(op)
printer.ComplexExpressionWithParens(comparator)
member printer.Print(node: UnaryOp) =
printer.AddLocation(node.Loc)
printer.Print(node.Op)
printer.ComplexExpressionWithParens(node.Operand)
member printer.Print(_node: FormattedValue) = printer.Print("(FormattedValue)")
member printer.Print(node: Call) =
printer.ComplexExpressionWithParens(node.Func)
printer.Print("(")
printer.PrintCommaSeparatedList(node.Args)
if not node.Keywords.IsEmpty then
if not node.Args.IsEmpty then
printer.Print(", ")
printer.PrintCommaSeparatedList(node.Keywords)
printer.Print(")")
member printer.Print(node: Emit) =
let inline replace pattern (f: System.Text.RegularExpressions.Match -> string) input =
System.Text.RegularExpressions.Regex.Replace(input, pattern, f)
let printSegment (printer: Printer) (value: string) segmentStart segmentEnd =
let segmentLength = segmentEnd - segmentStart
if segmentLength > 0 then
let segment = value.Substring(segmentStart, segmentLength)
printer.Print(segment)
// Macro transformations
// https://fable.io/docs/communicate/js-from-fable.html#Emit-when-F-is-not-enough
let value =
node.Value
|> replace
@"\$(\d+)\.\.\."
(fun m ->
let rep = ResizeArray()
let i = int m.Groups[1].Value
for j = i to node.Args.Length - 1 do
rep.Add $"$%d{j}"
String.concat ", " rep
)
|> replace
@"\{\{\s*\$(\d+)\s*\?(.*?):(.*?)\}\}"
(fun m ->
let i = int m.Groups[1].Value
match node.Args[i] with
| Constant(value = BoolLiteral value) when value -> m.Groups[2].Value
| _ -> m.Groups[3].Value
)
|> replace
@"\{\{([^\}]*\$(\d+).*?)\}\}"
(fun m ->
let i = int m.Groups[2].Value
match List.tryItem i node.Args with
| Some _ -> m.Groups[1].Value
| None -> ""
)
// If placeholder is followed by !, emit string literals as JS: "let $0! = $1"
|> replace
@"\$(\d+)!"
(fun m ->
let i = int m.Groups[1].Value
match List.tryItem i node.Args with
| Some(Constant(StringLiteral value, _)) -> value
| _ -> ""
)
let matches = System.Text.RegularExpressions.Regex.Matches(value, @"\$\d+")
if matches.Count > 0 then
for i = 0 to matches.Count - 1 do
let m = matches[i]
let isSurroundedWithParens =
m.Index > 0
&& m.Index + m.Length < value.Length
&& value[m.Index - 1] = '('
&& value[m.Index + m.Length] = ')'
let segmentStart =
if i > 0 then
matches[i - 1].Index + matches[i - 1].Length
else
0
printSegment printer value segmentStart m.Index
let argIndex = int m.Value[1..]
match List.tryItem argIndex node.Args with
| Some e when isSurroundedWithParens -> printer.Print(e)
| Some e -> printer.ComplexExpressionWithParens(e)
| None -> printer.Print("None")
let lastMatch = matches[matches.Count - 1]
printSegment printer value (lastMatch.Index + lastMatch.Length) value.Length
else
printSegment printer value 0 value.Length
member printer.Print(node: IfExp) =
printer.ComplexExpressionWithParens(node.Body)
printer.Print(" if ")
printer.ComplexExpressionWithParens(node.Test)
printer.Print(" else ")
printer.ComplexExpressionWithParens(node.OrElse)
member printer.Print(node: Lambda) =
printer.Print("lambda")
if (List.isEmpty >> not) node.Args.Args then
printer.Print(" ")
printer.Print(node.Args)
printer.Print(": ")
printer.Print(node.Body)
member printer.Print(node: Tuple) =
printer.Print("(", ?loc = node.Loc)
printer.PrintCommaSeparatedList(node.Elements)
if node.Elements.Length = 1 then
printer.Print(",")
printer.Print(")")
member printer.Print(_node: List) = printer.Print("(List)")
member printer.Print(_node: Set) = printer.Print("(Set)")
member printer.Print(node: Dict) =
printer.Print("{")
if not node.Keys.IsEmpty then
printer.PrintNewLine()
printer.PushIndentation()
let nodes = List.zip node.Keys node.Values |> List.mapi (fun i n -> (i, n))
for i, (key, value) in nodes do
printer.Print(key)
printer.Print(": ")
printer.Print(value)
if i < nodes.Length - 1 then
printer.Print(",")
printer.PrintNewLine()
printer.PrintNewLine()
printer.PopIndentation()
printer.Print("}")
member printer.Print(node: Name) =
let (Identifier name) = node.Id
printer.Print(name)
member printer.Print(node: ExceptHandler) =
printer.Print("except ", ?loc = node.Loc)
printer.PrintOptional(node.Type)
printer.PrintOptional(" as ", node.Name)
printer.Print(":")
match node.Body with
| [] -> printer.PrintBlock([ Pass ])
| _ -> printer.PrintBlock(node.Body)
member printer.Print(node: Alias) =
printer.Print(node.Name)
match node.AsName with
| Some(Identifier alias) when Identifier alias <> node.Name ->
printer.Print(" as ")
printer.Print(alias)
| _ -> ()
member printer.Print(node: Module) = printer.PrintStatements(node.Body)
member printer.Print(node: Identifier) =
let (Identifier id) = node
printer.Print(id)
member printer.Print(node: UnaryOperator) =
let op =
match node with
| Invert -> "~"
| Not -> "not "
| UAdd -> "+"
| USub -> "-"
printer.Print(op)
member printer.Print(node: ComparisonOperator) =
let op =
match node with
| Eq -> " == "
| NotEq -> " != "
| Lt -> " < "
| LtE -> " <= "
| Gt -> " > "
| GtE -> " >= "
| Is -> " is "
| IsNot -> " is not "
| In -> " in "
| NotIn -> " not in "
printer.Print(op)
member printer.Print(node: BoolOperator) =
let op =
match node with
| And -> " and "
| Or -> " or "
printer.Print(op)
member printer.Print(node: Operator) =
let op =
match node with
| Add -> " + "
| Sub -> " - "
| Mult -> " * "
| Div -> " / "
| FloorDiv -> " // "
| Mod -> " % "
| Pow -> " ** "
| LShift -> " << "
| RShift -> " >> "
| BitOr -> " | "
| BitXor -> " ^ "
| BitAnd -> " & "
| MatMult -> " @ "
printer.Print(op)
member printer.Print(node: Expression) =
match node with
| Attribute ex -> printer.Print(ex)
| Subscript ex -> printer.Print(ex)
| BoolOp ex -> printer.Print(ex)
| BinOp ex -> printer.Print(ex)
| Emit ex -> printer.Print(ex)
| UnaryOp ex -> printer.Print(ex)
| FormattedValue ex -> printer.Print(ex)
| Constant(value = StringLiteral value) ->
printer.Print("\"")
printer.Print(Naming.escapeString (fun _ -> false) value)
printer.Print("\"")
| Constant(value = FloatLiteral value) ->
let value = string<float> value
printer.Print(value)
// Make sure it's a valid Python float (not int)
if String.forall (fun char -> char = '-' || Char.IsDigit char) value then
printer.Print(".0")
| Constant(value = BoolLiteral value) ->
printer.Print(
if value then
"True"
else
"False"
)
| Constant(value = IntLiteral value) -> printer.Print(string<obj> value)
| Constant(value = value) -> printer.Print(string<obj> value)
| IfExp ex -> printer.Print(ex)
| Call ex -> printer.Print(ex)
| Lambda ex -> printer.Print(ex)
| NamedExpr ex -> printer.Print(ex)
| Name ex -> printer.Print(ex)
| Await ex ->
printer.Print("await ")
printer.Print(ex)
| Yield expr ->
printer.Print("yield")
match expr with
| Some e ->
printer.Print(" ")
printer.Print(e)
| None -> ()
| YieldFrom expr ->
printer.Print("yield from")
match expr with
| Some e ->
printer.Print(" ")
printer.Print(e)
| None -> ()
| Compare cp -> printer.Print(cp)
| Dict di -> printer.Print(di)
| Tuple tu -> printer.Print(tu)
| Slice(lower, upper, _step) ->
if lower.IsSome then
printer.Print(lower.Value)
printer.Print(":")
if upper.IsSome then
printer.Print(upper.Value)
| Starred(ex, _ctx) ->
printer.Print("*")
printer.Print(ex)
| List(elts, _ctx) ->
printer.Print("[")
printer.PrintCommaSeparatedList(elts)
printer.Print("]")
member printer.Print(node: AST) =
match node with
| AST.Expression ex -> printer.Print(ex)
| AST.Operator op -> printer.Print(op)
| AST.BoolOperator op -> printer.Print(op)
| AST.ComparisonOperator op -> printer.Print(op)
| AST.UnaryOperator op -> printer.Print(op)
| AST.ExpressionContext _ -> ()
| AST.Alias al -> printer.Print(al)
| AST.Module mo -> printer.Print(mo)
| AST.Arguments arg -> printer.Print(arg)
| AST.Keyword kw -> printer.Print(kw)
| AST.Arg arg -> printer.Print(arg)
| AST.Statement st -> printer.Print(st)
| AST.Identifier id -> printer.Print(id)
| AST.WithItem wi -> printer.Print(wi)
member printer.PrintBlock
(nodes: 'a list, printNode: Printer -> 'a -> unit, printSeparator: Printer -> unit, ?skipNewLineAtEnd)
=
let skipNewLineAtEnd = defaultArg skipNewLineAtEnd false
printer.Print("")
printer.PrintNewLine()
printer.PushIndentation()
for node in nodes do
printNode printer node
printSeparator printer
printer.PopIndentation()
printer.Print("")
if not skipNewLineAtEnd then
printer.PrintNewLine()
member printer.PrintStatementSeparator() =
if printer.Column > 0 then
printer.Print("")
printer.PrintNewLine()
member printer.PrintStatement(stmt: Statement, ?printSeparator) =
printer.Print(stmt)
printSeparator |> Option.iter (fun fn -> fn printer)
member printer.PrintStatements(statements: Statement list) =
for stmt in statements do
printer.PrintStatement(stmt, (fun p -> p.PrintStatementSeparator()))
member printer.PrintBlock(nodes: Statement list, ?skipNewLineAtEnd) =
printer.PrintBlock(
nodes,
(fun p s -> p.PrintStatement(s)),
(fun p -> p.PrintStatementSeparator()),
?skipNewLineAtEnd = skipNewLineAtEnd
)
member printer.PrintOptional(before: string, node: Identifier option) =
match node with
| None -> ()
| Some node ->
printer.Print(before)
printer.Print(node)
member printer.PrintOptional(before: string, node: AST option, after: string) =
match node with
| None -> ()
| Some node ->
printer.Print(before)
printer.Print(node)
printer.Print(after)
member printer.PrintOptional(node: AST option) =
match node with
| None -> ()
| Some node -> printer.Print(node)
member printer.PrintOptional(node: Expression option) =
printer.PrintOptional(node |> Option.map AST.Expression)
member printer.PrintOptional(node: Identifier option) =
match node with
| None -> ()
| Some node -> printer.Print(node)
member printer.PrintList(nodes: 'a list, printNode: Printer -> 'a -> unit, printSeparator: Printer -> unit) =
for i = 0 to nodes.Length - 1 do
printNode printer nodes[i]
if i < nodes.Length - 1 then
printSeparator printer
member printer.PrintCommaSeparatedList(nodes: AST list) =
printer.PrintList(nodes, (fun p x -> p.Print(x)), (fun p -> p.Print(", ")))
member printer.PrintCommaSeparatedList(nodes: Expression list) =
printer.PrintList(nodes, (fun _ -> printer.Print), (fun p -> p.Print(", ")))
member printer.PrintCommaSeparatedList(nodes: Arg list) =
printer.PrintCommaSeparatedList(nodes |> List.map AST.Arg)
member printer.PrintCommaSeparatedList(nodes: Keyword list) =
printer.PrintCommaSeparatedList(nodes |> List.map AST.Keyword)
member printer.PrintCommaSeparatedList(nodes: Alias list) =
printer.PrintCommaSeparatedList(nodes |> List.map AST.Alias)
member printer.PrintCommaSeparatedList(nodes: Identifier list) =
printer.PrintCommaSeparatedList(nodes |> List.map AST.Identifier)
member printer.PrintCommaSeparatedList(nodes: WithItem list) =
printer.PrintCommaSeparatedList(nodes |> List.map AST.WithItem)
member printer.PrintCommaSeparatedList(nodes: Pattern list) =
printer.PrintList(nodes, (fun (p: Printer) x -> p.Print(x)), (fun p -> p.Print(", ")))
member printer.PrintFunction
(
id: Identifier option,
args: Arguments,
body: Statement list,
returnType: Expression option,
decoratorList: Expression list,
?comment: string,
?isDeclaration,
?isAsync,
?typeParams: TypeParam list
)
=
for deco in decoratorList do
printer.Print("@")
printer.Print(deco)
printer.PrintNewLine()
match isAsync with
| Some true -> printer.Print("async ")
| _ -> ()
printer.Print("def ")
printer.PrintOptional(id)
// Print type parameters if any (Python 3.12+ syntax)
match typeParams with
| Some typeParamList -> printer.PrintTypeParams(typeParamList)
| None -> ()