-
Notifications
You must be signed in to change notification settings - Fork 8
/
compiler.nim
1724 lines (1541 loc) · 59.2 KB
/
compiler.nim
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
import
strformat, os, strutils, sequtils, tables,
python_ast, python_types, nim_types, core, env, tracer, sets,
ast_parser, ast_dsl, generator, module, deduckt_db, helpers,
idioms/[idioms_dsl, operators, string_methods, list_methods]
type
Pass* {.pure.} = enum AST, Generation
Compiler* = object
db*: DeducktDb
command: string
asts*: Table[string, Node]
modules*: Table[string, Module]
maybeModules*: Table[string, bool]
stack*: seq[(string, seq[(Type, string)])]
path*: string
envs*: Table[string, Env]
constants*: Table[string, Type]
untilPass*: Pass
generated*: Table[string, string]
currentModule*: string
currentClass*: Type
currentFunction*: string
currentCalls*: HashSet[string]
base*: string
depth*: int
identifierCollisions*: Table[string, (string, bool)] # idiomaticIdentifier, (existingIdentifier, collision)
# if there is already a different existing identifier
# for that idiomatic one, toggle collision to true
template log(a: Textable) =
if debug:
echo $a
template log(a: string) =
if debug:
echo a
proc newCompiler*(db: DeducktDb, command: string): Compiler =
result = Compiler(db: db, command: command)
proc moduleOf*(compiler: Compiler, name: string): string =
let tokens = compiler.currentModule.split(".")
var m: seq[string] = @[]
for z, token in tokens:
if token == compiler.db.package:
m = tokens[z..^1]
break
m.add(name)
result = m.join(".")
proc compileNode*(compiler: var Compiler, node: var Node, env: var Env): Node
proc mergeFunctionTypeInfo(compiler: var Compiler, node: var Node, env: var Env): Node
proc replaceNode(node: Node, original: Node, newNode: Node): Node
proc registerImport(compiler: var Compiler, label: string)
proc compileDocstring(compiler: var Compiler, node: Node, env: var Env): seq[string]
proc monitorCollisions(compiler: var Compiler, label: string)
proc elementOf(typ: Type): Type
proc firstElementOf(typ: Type): Type
proc secondElementOf(typ: Type): Type
proc findSource(compiler: var Compiler, node: Node): string
proc typed(node: var Node, typ: Type): Node =
node.typ = typ
result = node
proc collapse(node: Node): seq[Node] =
case node.kind:
of Sequence:
result = @[]
for child in node.children.mitems:
result = result.concat(collapse(child))
else:
result = @[node]
proc generalize(typ: Type): Type =
assert typ.kind == N.Function
result = Type(kind: N.Function, functionArgs: typ.functionArgs.mapIt(atomType("auto")), returnType: atomType("auto"))
proc genericCompatible(label: string, a: Type, b: Type): (bool, Table[string, Type]) =
log fmt"genericCompatible? {label} {$a} @ {$b}"
var genericMap = initTable[string, Type]()
if a.isNil or b.isNil:
return (false, genericMap)
# TODO: deep
if a.kind != N.Function or b.kind != N.Function:
return (false, genericMap)
if len(a.functionArgs) == 0 or len(a.functionArgs) != len(b.functionArgs):
return (false, genericMap)
genericMap["T"] = a.functionArgs[0]
for z in 0..<len(a.functionArgs):
if not a.functionArgs[z].unify(b.functionArgs[z], genericMap):
return (false, genericMap)
return (true, genericMap)
proc genericCompatible(label: string, a: Node, b: Node): (bool, Table[string, Type]) =
var genericMap = initTable[string, Type]()
if a.kind != PyFunctionDef or b.kind != PyFunctionDef:
return (false, genericMap)
result = genericCompatible(label, a.typ, b.typ)
if result[0]:
return (a[2].testEq(b[2]), genericMap)
proc compileModule*(compiler: var Compiler, file: string, node: Node): Module =
var moduleEnv = compiler.envs[file]
compiler.currentClass = nil
compiler.depth = 0
var childNodes: seq[Node] = @[]
for child in node.mitems:
childNodes.add(compiler.compileNode(child, moduleEnv))
var collapsedNodes: seq[Node] = @[]
for child in childNodes.mitems:
collapsedNodes = collapsedNodes.concat(collapse(child))
result = compiler.modules[file]
var functions: seq[Node] = @[]
for child in collapsedNodes:
case child.kind:
of PyImport:
result.imports.add(child)
of PyClassDef:
result.types.add(child)
of PyFunctionDef:
functions.add(child)
else:
result.init.add(child)
# var maybeGeneric = initTable[string, (Node, bool, Table[string, Type])]()
# for function in functions:
# if function[0].kind != PyStr:
# continue
# elif not maybeGeneric.hasKey(function[0].s):
# maybeGeneric[function[0].s] = (function, false, initTable[string, Type]())
# else:
# var (equivalent, genericMap) = genericCompatible(function[0].s, maybeGeneric[function[0].s][0], function)
# if equivalent:
# maybeGeneric[function[0].s][0].isGeneric = true
# maybeGeneric[function[0].s] = (function, true, genericMap)
# function.isGeneric = true
# for label, f2 in maybeGeneric:
# var (function, isGeneric, genericMap) = f2
# if isGeneric:
# var f = function
# result.functions.add(replaceGeneric(f, genericMap))
var maybeGeneric = initTable[string, (seq[Node], bool)]()
for function in functions:
if function[0].kind != PyStr:
continue
var label = function[0].s
if not maybeGeneric.hasKey(label):
maybeGeneric[label] = (@[function], false)
else:
for other in maybeGeneric[label][0]:
if len(function[1].children) == len(other[1].children) and function[2].testEq(other[2]):
maybeGeneric[label] = (@[function], true)
function.isGeneric = true
other.isGeneric = true
log fmt"generic? {label} {function.typ} @ {other.typ}: {function.isGeneric}"
if not function.isGeneric:
maybeGeneric[label][0].add(function)
for label, f2 in maybeGeneric:
var (functions, isGeneric) = f2
if isGeneric:
var function = functions[0]
function.typ = generalize(function.typ)
result.functions.add(function)
for function in functions:
if not function.isGeneric:
result.functions.add(function)
proc compileImport(compiler: var Compiler, node: var Node, env: var Env): Node =
# store imports
# by default make them false in maybeModules:
# only if the module is used, toggle it
assert node.kind == PyImport
if node[0].kind == Pyalias and node[0][0].kind == PyStr:
compiler.maybeModules[node[0][0].s] = false
result = Node(kind: PyImport, children: @[pyLabel(node[0][0].s)])
else:
warn("import")
result = Node(kind: Sequence, children: @[])
proc compileImportFrom(compiler: var Compiler, node: var Node, env: var Env): Node =
# from x import original
#
# import x
#
# from x import original as alias
#
# import x
# alias = original
if node.kind != PyImportFrom or node[0].kind != PyStr:
return Node(kind: Sequence, children: @[])
let m = node[0].s
var aliases: seq[Node] = @[]
for child in node[1]:
if child.kind == Pyalias:
assert child[0].kind == PyStr
let original = child[0].s
let alias = if child[1].kind == PyStr: child[1].s else: original
let fullName = fmt"{compiler.db.package}.{m}#{original}"
if compiler.db.types.hasKey(fullName):
env[alias] = compiler.db.types[fullName]
if original != alias:
aliases.add(assign(label(alias), attribute(label(m), original), Declaration.Var))
result = Node(kind: PyImport, children: @[pyLabel(m)], aliases: aliases)
compiler.maybeModules[fmt"{compiler.base}/{m}.py"] = true
proc compileAssign(compiler: var Compiler, node: var Node, env: var Env): Node =
let value = compiler.compileNode(node[1], env)
if len(node[0].children) > 1:
warn("assign")
elif node[0][0].kind == PyLabel:
var label = node[0][0].label
node[1] = value
if not env.types.hasKey(label):
if compiler.path.endsWith("constants.py"):
# weird?
# most libraries I test have it
# so use it for now, if we need, we can make add a flag
node.declaration = Declaration.Const
if compiler.constants.hasKey(label) and compiler.constants[label] != value.typ:
warn(fmt"const type: {label}")
compiler.constants[label] = value.typ
else:
node.declaration = Declaration.Var
env[label] = value.typ
compiler.monitorCollisions(label)
elif node[0][0].kind == PySubscript:
node[0][0] = compiler.compileNode(node[0][0], env)
node[1] = value
result = node
proc compilePrint(compiler: var Compiler, name: string, args: seq[Node], env: var Env): Node =
# variadic
var printArgs = args
# for z, arg in args:
# if arg.typ != T.String:
# printArgs[z] = call(label("$"), @[arg], T.String)
result = call(label("echo"), printArgs, T.Void)
proc compileSpecialStrMethod(compiler: var Compiler, name: string, args: seq[Node], env: var Env): Node =
result = call(label("$"), args, T.String)
proc compileLen(compiler: var Compiler, name: string, args: seq[Node], env: var Env): Node =
if len(args) != 1:
result = call(Node(kind: PyLabel, label: name), args, NIM_ANY)
else:
result = call(Node(kind: PyLabel, label: name), args, T.Int)
proc compileReversed(compiler: var Compiler, name: string, args: seq[Node], env: var Env): Node =
if len(args) == 1:
result = call(Node(kind: PyLabel, label: name), args, args[0].typ)
compiler.registerImport("algorithm")
else:
result = call(Node(kind: PyLabel, label: name), args, NIM_ANY)
proc compileIsinstance(compiler: var Compiler, name: string, args: seq[Node], env: var Env): Node =
result = Node(kind: NimOf, children: args, typ: T.Bool)
proc compileSpecialIntMethod(compiler: var Compiler, name: string, args: seq[Node], env: var Env): Node =
var arg = args[0]
result = attribute(arg, name, T.Int)
proc compileSpecialFloatMethod(compiler: var Compiler, name: string, args: seq[Node], env: var Env): Node =
var arg = args[0]
result = attribute(arg, name, T.Float)
proc compileBytes(compiler: var Compiler, name: string, args: seq[Node], env: var Env): Node =
var arg: Node
if args[0].kind == PyStr:
arg = args[0]
elif args[0].kind == PyList:
var list = args[0]
for z, next in list.children:
list[z] = attribute(next, "char")
arg = call(attribute(list, "join"), @[pyString("")])
compiler.registerImport("strutils")
result = call(Node(kind: PyLabel, label: "cstring"), @[arg], T.Bytes)
proc compileEnumerate(compiler: var Compiler, name: string, args: seq[Node], env: var Env): Node =
if len(args) != 1:
warn("weird enumerate")
result = PY_NIL
else:
result = args[0]
proc compileAbs(compiler: var Compiler, name: string, args: seq[Node], env: var Env): Node =
if len(args) != 2:
warn(fmt"{name} expects 2 args")
result = PY_NIL
else:
result = call(Node(kind: PyLabel, label: name), args, args[0].typ)
var BUILTIN* = {
"print": "echo"
}.toTable()
var SPECIAL_FUNCTIONS* = {
"print": compilePrint,
"str": compileSpecialStrMethod,
"len": compileLen,
"reversed": compileReversed,
"isinstance": compileIsinstance,
"int": compileSpecialIntMethod,
"float": compileSpecialFloatMethod,
"bytes": compileBytes,
"enumerate": compileEnumerate,
"min": compileAbs,
"max": compileAbs
}.toTable()
proc compileCall*(compiler: var Compiler, node: var Node, env: var Env): Node =
let function = compiler.compileNode(node[0], env)
let args = compiler.compileNode(node[1], env)
if function.typ.isNil and (function.kind != PyLabel or function.label notin SPECIAL_FUNCTIONS):
warn("failed to determine type of function:\n" & $node)
function.typ = NIM_ANY
var imports: seq[string] = @[]
if function.kind == PyAttribute:
assert function[1].kind == PyStr
(result, imports) = maybeApplyMethodIdiom(node, function[0], function[1].s, args.children)
elif function.kind == PyLabel:
if function.label in SPECIAL_FUNCTIONS:
result = SPECIAL_FUNCTIONS[function.label](compiler, function.label, args.children, env)
else:
(result, imports) = maybeApplyMethodIdiom(node, nil, function.label, args.children)
else:
result = node
for imp in imports:
compiler.registerImport(imp)
if result.isNil: # no idiom
result = node
case function.typ.kind:
of N.Function:
result.typ = function.typ.returnType
of N.Any:
result.typ = function.typ
of N.Record:
if function.kind != PyLabel or function.label != function.typ.label:
var call = fmt"{function.typ.fullLabel}#__call__"
if compiler.db.types.hasKey(call):
var typ = compiler.db.types[call]
if not typ.isNil and typ.kind == N.Function:
function.typ = typ
result.typ = typ.returnType
return
result.typ = NIM_ANY
else:
result.kind = PyConstr
result[2] = result[1]
var members: seq[Node] = @[]
for member, _ in function.typ.members:
members.add(label(member))
result[1] = Node(kind: Sequence, children: members)
result.typ = function.typ
of N.Overloads:
result.typ = NIM_ANY
for overload in function.typ.overloads:
if overload.kind == N.Function and args.children.zip(overload.functionArgs).allIt(it[0].typ == it[1]):
result.typ = overload.returnType
break
else:
warn fmt"wtf {function.typ}"
result.typ = function.typ
if compiler.currentCalls.isValid() and function.kind == PyLabel:
compiler.currentCalls.incl(function.label)
proc monitorCollisions(compiler: var Compiler, label: string) =
var translated = translateIdentifier(label)
if not compiler.identifierCollisions.hasKey(translated):
compiler.identifierCollisions[translated] = (label, false)
elif compiler.identifierCollisions[translated][0] != label:
compiler.identifierCollisions[translated] = (label, true)
proc compileLabel(compiler: var Compiler, node: var Node, env: var Env): Node =
assert node.kind == PyLabel
if node.label in SPECIAL_FUNCTIONS:
result = node
elif node.label == "True" or node.label == "False":
result = Node(kind: PyLabel, label: node.label.toLowerAscii(), typ: T.Bool)
elif node.label == "None":
result = PY_NIL
else:
var typ = env.get(node.label)
if typ.isNil:
typ = env.get(fmt"{compiler.currentModule}.{node.label}")
result = typed(node, typ)
compiler.monitorCollisions(node.label)
proc compileStr(compiler: var Compiler, node: var Node, env: var Env): Node =
result = typed(node, T.String)
proc compileInt(compiler: var Compiler, node: var Node, env: var Env): Node =
result = typed(node, T.Int)
proc compileHugeInt(compiler: var Compiler, node: var Node, env: var Env): Node =
result = typed(node, T.HugeInt)
proc compileFloat(compiler: var Compiler, node: var Node, env: var Env): Node =
result = typed(node, T.Float)
proc compileConstant(compiler: var Compiler, node: var Node, env: var Env): Node =
result = typed(node, T.Bool)
proc compileExpr(compiler: var Compiler, node: var Node, env: var Env): Node =
result = compiler.compileNode(node[0], env)
proc compileBinOp(compiler: var Compiler, node: var Node, env: var Env): Node =
var left = compiler.compileNode(node[0], env)
var right = compiler.compileNode(node[2], env)
let op = node[1]
if left.typ == T.Float and right.typ == T.Int:
right = attribute(right, "float", T.Float)
elif left.typ == T.Int and right.typ == T.Float:
left = attribute(left, "float", T.Float)
elif right.typ.isNil and left.typ.isNil:
right.typ = NIM_ANY
left.typ = NIM_ANY
elif left.typ.isNil or left.typ.kind == N.Any:
left.typ = right.typ
elif right.typ.isNil or right.typ.kind == N.Any:
right.typ = left.typ
node[0] = left
node[2] = right
result = node
var imports: seq[string] = @[]
if left.typ == T.Int or left.typ == T.Float:
result.typ = left.typ
# TODO:
(result, imports) = applyOperatorIdiom(result)
else:
(result, imports) = applyOperatorIdiom(result)
if result.isNil:
var typ = left.typ
result = binop(left, op, right, typ)
for imp in imports:
compiler.registerImport(imp)
proc pureConstr(compiler: var Compiler, node: var Node): bool =
let args = node[1][0].mapIt(it[0].s)
for child in node[2]:
if child.kind != PyAssign or len(child[0].children) != 1 or child[0][0].kind != PyAttribute or
child[0][0][0].kind != PyLabel or child[0][0][0].label != "self" or child[0][0][1].kind != PyStr or
child[0][0][1].s notin args or child[1].kind != PyLabel or child[1].label != child[0][0][1].s:
return false
return true
proc translateInit(compiler: var Compiler, node: var Node, env: var Env, child: bool = false, assignments: seq[Node] = @[]): Node =
result = node
if not child:
result[0].s = compiler.currentClass.init
result[1][0].children = result[1][0].children[1..^1]
if result.typ.isNil or result.typ.kind != N.Function:
warn("missing init type")
result.typ = Type(kind: N.Function, functionArgs: repeat(NIM_ANY, len(result[1][0].children)))
result.typ.functionArgs = result.typ.functionArgs[1..^1]
result.typ.returnType = compiler.currentClass
result[2].children = assignments.concat(result[2].children)
if compiler.currentClass.isRef:
result[2].children = @[call(label("new"), @[label("result")])].concat(result[2].children)
case node.kind:
of PyLabel:
if node.label == "self":
result.label = "result"
else:
var z = 0
for next in result.mitems:
result[z] = compiler.translateInit(next, env, true)
z += 1
proc replaceReturnYield(node: Node): Node =
if node.kind == PyReturn:
return Node(kind: PyYield, children: node.children)
else:
result = node
var z = 0
for child in node:
result[z] = replaceReturnYield(child)
z += 1
proc loadBranches(node: Node, nimElif: bool = false): seq[Node] =
case node.kind:
of Sequence:
if len(node.children) != 1:
result = @[]
else:
result = loadBranches(node[0])
of PyIf:
var ifBranch = if not nimElif: Node(kind: NimIf, children: @[node[0], node[1]]) else: Node(kind: NimElif, children: @[node[0], node[1]])
case node[2].kind:
of PyNone:
result = @[ifBranch]
of Sequence:
if len(node[2].children) == 1 and node[2][0].kind == PyIf:
result = @[ifBranch].concat(loadBranches(node[2][0], true))
else:
var elseBranch = Node(kind: NimElse, children: @[node[2][0]])
result = @[ifBranch, elseBranch]
of PyIf:
result = @[ifBranch].concat(loadBranches(node[2], true))
else:
var elseBranch = Node(kind: NimElse, children: @[node[2]])
result = @[ifBranch, elseBranch]
else:
result = @[]
proc isDynamicTest(test: Node, args: HashSet[string]): bool =
result = test.kind == PyCall and test[0].kind == PyLabel and test[0].label in @["hasattr", "isinstance"] and len(test[1].children) > 1 and test[1][0].kind == PyLabel and test[1][0].label in args
proc generateDynamic(compiler: var Compiler, test: Node): Type =
if test.kind == PyCall and test[0].kind == PyLabel:
var check = test[0].label
if check == "hasattr" and test[1][1].kind == PyStr:
result = Type(kind: N.Macro, label: "HasField", macroArgs: @[atomType(test[1][1].s)])
compiler.registerImport("py2nim_helpers")
elif check == "isinstance" and test[1][1].kind == PyLabel:
var label = test[1][1].label
if label == "list":
result = T.List
elif label == "dict":
result = T.Dict
else:
result = toType(PyType(kind: PyTypeAtom, label: label))
else:
result = NIM_ANY
else:
result = NIM_ANY
proc generateBranch(compiler: var Compiler, branch: Node, node: Node, typ: Type): Node =
if branch.kind in {NimIf, NimElif}:
var label = branch[0][1][0].label
result = Node(kind: PyFunctionDef, children: @[deepCopy(node[0]), deepCopy(node[1]), deepCopy(branch[1])])
for z, arg in node[1][0].nitems:
if arg[0].s == label:
result.typ = deepCopy(typ)
if result.typ.kind == N.Overloads:
result.typ = result.typ.overloads[0]
result.typ.functionArgs[z] = compiler.generateDynamic(branch[0])
break
elif branch.kind == NimElse:
result = Node(kind: PyFunctionDef, typ: typ, children: @[deepCopy(node[0]), deepCopy(node[1]), deepCopy(branch[0])])
else:
warn $branch.kind
result = PY_NIL
proc dynamicBranches(compiler: var Compiler, node: Node, typ: Type): (bool, seq[Node]) =
if node.kind != PyFunctionDef or typ.isNil or typ.kind notin {N.Function, N.Overloads}:
return (false, @[])
var branches: seq[Node] = @[]
var args = initSet[string]()
for arg in node[1][0]:
args.incl(arg[0].s)
var children = loadBranches(node[2])
for child in children:
if child.kind in {NimIf, NimElif} and
not child[0].isDynamicTest(args):
return (false, @[])
for child in children:
branches.add(compiler.generateBranch(child, node, typ))
result = (len(branches) > 0, branches)
proc compileFunctionDef(compiler: var Compiler, node: var Node, env: var Env, assignments: seq[Node] = @[], fTyp: Type = nil): Node =
assert node.kind == PyFunctionDef
var f = node[0]
assert f.kind == PyStr # TODO: label
var label = f.s
compiler.monitorCollisions(label)
# analyze typr
# ignore weird functions
# if we find an overloaded function, call this function for each overload
node.calls = initSet[string]()
let typ = if fTyp.isNil: env.get(label) else: fTyp
if typ.isNil or typ.kind notin {N.Overloads, N.Function}:
return Node(kind: Sequence, children: @[])
var (isDynamic, branches) = compiler.dynamicBranches(node, typ)
if isDynamic:
result = Node(kind: Sequence, children: @[])
for branch in branches.mitems:
result.children.add(compiler.compileFunctionDef(branch, env, fTyp=branch.typ))
return
elif typ.kind == N.Overloads:
result = Node(kind: Sequence, children: @[])
let originalNode = node
for overload in typ.overloads:
log fmt"compile {overload}"
var tempNode = deepCopy(originalNode)
result.children.add(compiler.compileFunctionDef(tempNode, env, fTyp=overload))
return
# analyze magic methods
var isInit = false
if label == "__init__":
if len(assignments) == 0 and compiler.pureConstr(node):
compiler.currentClass.init = ""
return Node(kind: Sequence, children: @[])
# TODO mark it so we can use PyConstr
# and rename to newType, change return type and remove self otherwise
# idiomatic function
else:
if compiler.currentClass.isRef:
compiler.currentClass.init = fmt"new{compiler.currentClass.label}"
else:
compiler.currentClass.init = fmt"make{compiler.currentClass.label}"
isInit = true
elif label == "__len__":
label = "len"
node[0].s = label
elif label == "__getitem__":
label = "[]"
node[0] = Node(kind: NimAccQuoted, children: @[Node(kind: PyLabel, label: label)])
elif label == "__setitem__":
label = "[]="
node[0] = Node(kind: NimAccQuoted, children: @[Node(kind: PyLabel, label: label)])
elif label == "__contains__":
label = "contains"
node[0].s = label
elif label == "__delitem__":
label = "del"
node[0].s = label
elif label == "__iter__":
if len(node[2].children) != 1 or not node[2][0].testEq(Node(kind: PyReturn, children: @[Node(kind: PyLabel, label: "self")])):
warn("def __iter__(self): return self only supported")
result = Node(kind: Sequence, children: @[])
return
elif label == "__next__":
node[2] = replaceReturnYield(node[2])
node[2] = replaceNode(node[2], Node(kind: PyRaise, children: @[call(Node(kind: PyLabel, label: "StopIteration"), @[], T.Void), PY_NIL]), Node(kind: PyBreak, children: @[]))
node[2] = Node(
kind: Sequence,
children: @[
Node(
kind: PyWhile,
children: @[pyBool(true), node[2]])])
label = "items"
node[0].s = label
typ.functionArgs[0].isVar = true
node.isIterator = true
elif label == "__enter__":
label = "enter"
node[0].s = label
typ.functionArgs[0].isVar = true
elif label == "__exit__":
label = "exit"
node[0].s = label
typ.functionArgs[0].isVar = true
if len(typ.functionArgs) == 4:
typ.functionArgs[1] = Type(kind: N.Atom, label: "Exception", isRef: true)
typ.functionArgs[2] = Type(kind: N.Atom, label: "Exception", isRef: true)
typ.functionArgs[3] = T.String
elif label == "__str__":
label = "$"
node[0] = Node(kind: NimAccQuoted, children: @[Node(kind: PyLabel, label: label)])
elif label == "__call__":
# TODO: use {} in future, () is deprecated
label = "()"
node[0] = Node(kind: NimAccQuoted, children: @[Node(kind: PyLabel, label: label)])
# analyze args
var args = initTable[string, Type]()
var z = 0
for v in node[1][0]:
assert v.kind == Pyarg and v[0].kind == PyStr
args[v[0].s] = typ.functionArgs[z]
z += 1
compiler.monitorCollisions(v[0].s)
var functionEnv = childEnv(env, label, args, typ.returnType)
compiler.currentFunction = typ.fullLabel
compiler.currentCalls = initSet[string]()
var sequence = node[2]
if sequence.kind != Sequence:
sequence = Node(kind: Sequence, children: @[sequence])
for z, child in sequence.nitems:
sequence.children[z] = compiler.compileNode(child, functionEnv)
compiler.currentFunction = ""
node.calls = compiler.currentCalls
typ.returnType = functionEnv.returnType
if functionEnv.hasYield:
node.isIterator = true
if isInit:
result = compiler.translateInit(node, env, assignments=assignments)
else:
result = typed(node, typ)
if not compiler.currentClass.isNil and (not compiler.currentClass.base.isNil or compiler.currentClass.inherited):
result.isMethod = true
if len(node.children) > 5:
result.doc = compiler.compileDocstring(node[5], env)
elif len(result[2].children) > 0 and result[2][0].kind == PyStr:
result.doc = compiler.compileDocstring(result[2][0], env)
result[2].children = result[2].children[1..^1]
else:
result.doc = @[]
proc compileAttribute*(compiler: var Compiler, node: var Node, env: var Env): Node =
result = node
var base = compiler.compileNode(node[0], env)
var typ = base.typ
if typ.isNil or typ.kind == N.Any:
result.typ = NIM_ANY # TODO: experiment with just generating the same code for some nodes
#fail(fmt"no type for node {node}")
return
var fullName = typ.label
var oldTyp = typ
if typ.kind == N.Atom:
fullName = fmt"{compiler.currentModule}.{typ.label}"
typ = env.get(fullName)
if typ.isNil and compiler.db.types.hasKey(fullName):
typ = compiler.db.types[fullName]
env[fullName] = typ
elif typ.isNil:
typ = oldTyp
if typ.kind == N.Record:
assert node[1].kind == PyStr
if node[1].s notin typ.members:
var methodName = fmt"{compiler.currentModule}.{typ.label}#{node[1].s}"
if methodName notin compiler.db.types:
warn(fmt"no type for {node[1].s} in {fullName}")
methodName = fmt"{compiler.currentModule}#{node[1].s}"
if methodName notin compiler.db.types:
warn(fmt"no type for {node[1].s} in {fullName}")
result.typ = NIM_ANY
else:
result.children[0] = base
result.typ = compiler.db.types[methodName]
else:
result.children[0] = base
result.typ = compiler.db.types[methodName]
else:
result.children[0] = base
result.typ = typ.members[node[1].s]
else:
result.typ = NIM_ANY
if not result.typ.isNil and result.typ.kind == N.Function and len(result.typ.functionArgs) == 1:
if result.typ.functionArgs[0].kind == N.Atom:
result.typ = result.typ.returnType
elif result.typ.functionArgs[0].kind == N.Record and result.typ.functionArgs[0].members.hasKey(node[1].s):
result.typ = result.typ.returnType
proc compileSequence*(compiler: var Compiler, node: var Node, env: var Env): Node =
result = node
var z = 0
for child in result.children.mitems:
result.children[z] = compiler.compileNode(child, env)
z += 1
proc compileList*(compiler: var Compiler, node: var Node, env: var Env): Node =
result = node
var z = 0
for child in result.children.mitems:
result[z] = compiler.compileNode(child, env)
z += 1
if len(result.children) > 0:
result.typ = seqType(result[0].typ)
else:
result.typ = seqType(NIM_ANY)
proc compileReturn(compiler: var Compiler, node: var Node, env: var Env): Node =
node[0] = compiler.compileNode(node[0], env)
if node[0].typ != env.returnType:
# TODO
if env.returnType == T.Void:
env.returnType = node[0].typ
else:
warn(fmt"{compiler.currentFunction} expected {$env.returnType} got {$node[0].typ} return")
result = node
proc compileIf(compiler: var Compiler, node: var Node, env: var Env): Node =
result = node
var (line, column) = (node[0].line, node[0].column)
if node[0].kind == PyCompare and node[0][0].kind == PyLabel and
node[0][0].label == "__name__" and
node[0][1][0].kind == PyEq and node[0][2][0].kind == PyStr and node[0][2][0].s == "__main__":
result.kind = NimWhen
result[0] = Node(kind: PyLabel, label: "isMainModule", typ: T.Bool)
else:
result[0] = compiler.compileNode(node[0], env)
if result[0].typ != T.Bool:
var info = findSource(compiler.path, line, column, "test")
warn(fmt"expected bool got {$result[0].typ} if: {info}")
result[1] = compiler.compileNode(node[1], env)
proc compileCompare(compiler: var Compiler, node: var Node, env: var Env): Node =
# TODO: compound compare
var left = compiler.compileNode(node[0], env)
var op = node[1][0]
var right = compiler.compileNode(node[2][0], env)
if not (
left.typ == T.Int and right.typ == T.Int or
left.typ == T.Float and right.typ == T.Float or
op.kind == PyEq or op.kind == PyNotEq):
warn(fmt"{$op} {$left.typ} {$right.typ}")
result = node
result.typ = T.Bool
proc createInit(compiler: var Compiler, assignments: seq[Node]): Node =
if compiler.currentClass.isRef:
compiler.currentClass.init = fmt"new{compiler.currentClass.label}"
else:
compiler.currentClass.init = fmt"make{compiler.currentClass.label}"
result = Node(
kind: PyFunctionDef,
children: @[
Node(kind: PyStr, s: compiler.currentClass.init),
Node(kind: Pyarguments, children: @[Node(kind: Sequence, children: @[]), PY_NIL, Node(kind: Sequence, children: @[])]),
Node(kind: Sequence, children: assignments),
PY_NIL])
result.typ = Type(kind: N.Function, label: compiler.currentClass.init, functionArgs: @[], returnType: compiler.currentClass)
proc compileDocstring(compiler: var Compiler, node: Node, env: var Env): seq[string] =
if node.kind != PyStr:
result = @[]
else:
result = node.s.split("\\n").mapIt(it.strip(leading=false))
if len(result[0]) == 0:
result = result[1..^1]
if len(result) > 0 and len(result[^1]) == 0:
result = result[0..^2]
# var unindent = 200
# for line in result:
# var offset = 0
# for c in line:
# if c == ' ':
# offset += 1
# else:
# break
# if offset < unindent and offset > 0:
# unindent = offset
# result = result.mapIt(if len(it) == 0: it else: it[unindent..^1])
proc compileClassDef(compiler: var Compiler, node: var Node, env: var Env): Node =
assert node[0].kind == PyStr
let label = node[0].s
var typ = env[label]
compiler.currentClass = typ
compiler.currentClass.init = ""
compiler.monitorCollisions(label)
var children = node[3].children
if len(node.children) > 5:
node.docstring = compiler.compileDocstring(node[5], env)
elif len(children) > 0 and children[0].kind == PyExpr and children[0][0].kind == PyStr:
node.docstring = compiler.compileDocstring(children[0][0], env)
children = children[1..^1]
else:
node.docstring = @[]
node[0] = Node(kind: PyLabel, label: label)
if node[1].kind == Sequence and len(node[1].children) > 0:
if len(node[1].children) == 1 and node[1][0].kind == PyLabel:
typ.base = env.get(node[1][0].label)
if typ.base.isNil:
typ.base = Type(kind: N.Atom, label: node[1][0].label)
result = node
if len(children) > 0:
result = Node(kind: Sequence, children: @[result])
var classEnv = childEnv(env, label, initTable[string, Type](), nil)
var z = 0
var assignments: seq[Node] = @[]
for child in children.mitems:
if child.kind == PyFunctionDef:
children[z] = compiler.mergeFunctionTypeInfo(child, classEnv)
elif child.kind == PyAssign and len(child[0].children) == 1 and child[0][0].kind == PyLabel:
var value = compiler.compileNode(child[1], classEnv)
assignments.add(assign(attribute(Node(kind: PyLabel, label: "result"), child[0][0].label), value))
if not typ.members.hasKey(child[0][0].label):
typ.members[child[0][0].label] = value.typ
z += 1
z = 0
var hasInit = false
for child in children.mitems:
if child.kind == PyFunctionDef:
if child[0].kind == PyLabel and child[0].label == "__init__":
hasInit = true
result.children.add(compiler.compileFunctionDef(child, classEnv, assignments))
z += 1
if not hasInit and len(assignments) > 0:
result.children.add(compiler.createInit(assignments))
compiler.currentClass = nil
proc replaceFile(compiler: var Compiler, node: var Node, handler: string, filename: Node): Node =
result = nil
if node.kind == PyCall and node[0].kind == PyAttribute and node[0][0].kind == PyLabel and
node[0][0].label == handler:
result = nil
if node[0][1].s == "read" and len(node[1].children) == 0:
result = call(label("readFile"), @[filename], T.String)
result.ready = true
elif node[0][1].s == "write" and len(node[1].children) == 1:
let arg = node[1][0]
result = call(label("writeFile"), @[filename, arg], T.Void)
result.ready = true
if result.isNil:
result = node
var z = 0
for child in node.mitems:
result[z] = compiler.replaceFile(child, handler, filename)
z += 1
proc compileWith(compiler: var Compiler, node: var Node, env: var Env): Node =
# with open(filename, mode) as f:
# code ..
# f.read() / f.write(source)
# .. code
#
# is translated to
#
# code ..
# readFile() / writeFile(source)
# .. code
# TODO: append etc
# TODO: other common context
assert node.kind == PyWith
assert node[0][0].kind == Pywithitem
var header = node[0][0][0]
var handler = node[0][0][1]
var code = node[1]
if header.kind == PyCall and header[0].kind == PyLabel and header[0].label == "open" and
handler.kind == PyLabel:
let filename = header[1][0]
result = compiler.replaceFile(code, handler.label, filename)
result = compiler.compileNode(result, env)
else:
result = Node(
kind: PyWith,
children: @[
Node(
kind: Pywithitem,
children: @[
compiler.compileNode(header, env),
compiler.compileNode(handler, env)]),
compiler.compileNode(code, env)])
compiler.registerImport("py2nim_helpers")
proc compileFor*(compiler: var Compiler, node: var Node, env: var Env): Node =
# for element in a:
# code
#
# doesn't change
#
# for z, element in enumerate(a):
# code
#
# becomes
#
# for z, element in a: