forked from bartuer/ydiff
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pydiff.py
1989 lines (1485 loc) · 52.1 KB
/
pydiff.py
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 sys
import re
from ast import *
from lists import *
#-------------------------------------------------------------
# global parameters
#-------------------------------------------------------------
DEBUG = False
# sys.setrecursionlimit(10000)
MOVE_RATIO = 0.2
MOVE_SIZE = 10
MOVE_ROUND = 5
FRAME_DEPTH = 1
FRAME_SIZE = 20
NAME_PENALTY = 1
IF_PENALTY = 1
ASSIGN_PENALTY = 1
#-------------------------------------------------------------
# utilities
#-------------------------------------------------------------
IS = isinstance
def debug(*args):
if DEBUG:
print args
def dot():
sys.stdout.write('.')
def isAlpha(c):
return (c == '_'
or ('0' <= c <= '9')
or ('a' <= c <= 'z')
or ('A' <= c <= 'Z'))
def div(m, n):
if n == 0:
return m
else:
return m/float(n)
# for debugging
def ps(s):
v = parse(s).body[0]
if IS(v, Expr):
return v.value
else:
return v
def sz(s):
return nodeSize(parse(s), True) - 1
def dp(s):
return dump(parse(s))
def run(name, closure=True, debug=False):
fullname1 = name + '1.py'
fullname2 = name + '2.py'
global DEBUG
olddebug = DEBUG
DEBUG = debug
diff(fullname1, fullname2, closure)
DEBUG = olddebug
def demo():
run('demo')
def go():
run('heavy')
def pf():
import cProfile
cProfile.run("run('heavy')", sort="cumulative")
#------------------------ file system support -----------------------
def pyFileName(filename):
try:
start = filename.rindex('/') + 1
except ValueError:
start = 0
end = filename.rindex('.py')
return filename[start:end]
## file system support
def parseFile(filename):
f = open(filename, 'r');
lines = f.read()
ast = parse(lines)
improveAST(ast, lines, filename, 'left')
return ast
#-------------------------------------------------------------
# tests and operations on AST nodes
#-------------------------------------------------------------
# get list of fields from a node
def nodeFields(node):
ret = []
for field in node._fields:
if field <> 'ctx' and hasattr(node, field):
ret.append(getattr(node, field))
return ret
# get full source text where the node is from
def nodeSource(node):
if hasattr(node, 'nodeSource'):
return node.nodeSource
else:
return None
# utility for getting exact source code part of the node
def src(node):
return node.nodeSource[node.nodeStart : node.nodeEnd]
def nodeStart(node):
if (hasattr(node, 'nodeStart')):
return node.nodeStart
else:
return 0
def nodeEnd(node):
return node.nodeEnd
def isAtom(x):
return type(x) in [int, str, bool, float]
def isDef(node):
return IS(node, FunctionDef) or IS(node, ClassDef)
# whether a node is a "frame" which can contain others and be
# labeled
def isFrame(node):
return type(node) in [ClassDef, FunctionDef, Import, ImportFrom]
def isEmptyContainer(node):
if IS(node, List) and node.elts == []:
return True
if IS(node, Tuple) and node.elts == []:
return True
if IS(node, Dict) and node.keys == []:
return True
return False
def sameDef(node1, node2):
if IS(node1, FunctionDef) and IS(node2, FunctionDef):
return node1.name == node2.name
elif IS(node1, ClassDef) and IS(node2, ClassDef):
return node1.name == node2.name
else:
return False
def differentDef(node1, node2):
if isDef(node1) and isDef(node2):
return node1.name <> node2.name
return False
# decide whether it is reasonable to consider two nodes to be
# moves of each other
def canMove(node1, node2, c):
return (sameDef(node1, node2) or
c <= (nodeSize(node1) + nodeSize(node2)) * MOVE_RATIO)
# whether the node is considered deleted or inserted because
# the other party matches a substructure of it.
def nodeFramed(node, changes):
for c in changes:
if (c.isFrame and (node == c.orig or node == c.cur)):
return True
return False
# helper for turning nested if statements into sequences,
# otherwise we will be trapped in the nested structure and find
# too many differences
def serializeIf(node):
if IS(node, If):
if not hasattr(node, 'nodeEnd'):
print "has no end:", node
newif = If(node.test, node.body, [])
newif.lineno = node.lineno
newif.col_offset = node.col_offset
newif.nodeStart = node.nodeStart
newif.nodeEnd = node.nodeEnd
newif.nodeSource = node.nodeSource
newif.fileName = node.fileName
return [newif] + serializeIf(node.orelse)
elif IS(node, list):
ret = []
for n in node:
ret += serializeIf(n)
return ret
else:
return [node]
def nodeName(node):
if IS(node, Name):
return node.id
elif IS(node, FunctionDef) or IS(node, ClassDef):
return node.name
else:
return None
def attr2str(node):
if IS(node, Attribute):
vName = attr2str(node.value)
if vName <> None:
return vName + "." + node.attr
else:
return None
elif IS(node, Name):
return node.id
else:
return None
### utility for counting size of terms
def nodeSize(node, test=False):
if not test and hasattr(node, 'nodeSize'):
ret = node.nodeSize
elif IS(node, list):
ret = sum(map(lambda x: nodeSize(x, test), node))
elif isAtom(node):
ret = 1
elif IS(node, Name):
ret = 1
elif IS(node, Num):
ret = 1
elif IS(node, Str):
ret = 1
elif IS(node, Expr):
ret = nodeSize(node.value, test)
elif IS(node, AST):
ret = 1 + sum(map(lambda x: nodeSize(x, test), nodeFields(node)))
else:
ret = 0
if test:
print "node:", node, "size=", ret
if IS(node, AST):
node.nodeSize = ret
return ret
#------------------------------- types ------------------------------
# global storage of running stats
class Stat:
def __init__(self):
pass
stat = Stat()
# The difference between nodes are stored as a Change structure.
class Change:
def __init__(self, orig, cur, cost, isFrame=False):
self.orig = orig
self.cur = cur
if orig == None:
self.cost = nodeSize(cur)
elif cur == None:
self.cost = nodeSize(orig)
elif cost == 'all':
self.cost = nodeSize(orig) + nodeSize(cur)
else:
self.cost = cost
self.isFrame = isFrame
def __repr__(self):
fr = "F" if self.isFrame else "-"
def hole(x):
if x == None:
return "[]"
else:
return x
return ("(C:" + str(hole(self.orig)) + ":" + str(hole(self.cur))
+ ":" + str(self.cost) + ":" + str(self.similarity())
+ ":" + fr + ")")
def similarity(self):
total = nodeSize(self.orig) + nodeSize(self.cur)
return 1 - div(self.cost, total)
# Three major kinds of changes:
# * modification
# * deletion
# *insertion
def modifyNode(node1, node2, cost):
return loner(Change(node1, node2, cost))
def delNode(node):
return loner(Change(node, None, nodeSize(node)))
def insNode(node):
return loner(Change(None, node, nodeSize(node)))
# general cache table for acceleration
class Cache:
def __init__(self):
self.table = {}
def __repr__(self):
return "Cache:" + str(self.table)
def __len__(self):
return len(self.table)
def put(self, key, value):
self.table[key] = value
def get(self, key):
if self.table.has_key(key):
return self.table[key]
else:
return None
# 2-D array table for memoization of dynamic programming
def createTable(x, y):
table = []
for i in range(x+1):
table.append([None] * (y+1))
return table
def tableLookup(t, x, y):
return t[x][y]
def tablePut(t, x, y, v):
t[x][y] = v
#-------------------------------------------------------------
# string distance function
#-------------------------------------------------------------
### diff cache for AST nodes
strDistCache = Cache()
def clearStrDistCache():
global strDistCache
strDistCache = Cache()
### string distance function
def strDist(s1, s2):
cached = strDistCache.get((s1, s2))
if cached <> None:
return cached
if len(s1) > 100 or len(s2) > 100:
if s1 <> s2:
return 2.0
else:
return 0
table = createTable(len(s1), len(s2))
d = dist1(table, s1, s2)
ret = div(2*d, len(s1) + len(s2))
strDistCache.put((s1, s2), ret)
return ret
# the main dynamic programming part
# similar to the structure of diffList
def dist1(table, s1, s2):
def memo(v):
tablePut(table, len(s1), len(s2), v)
return v
cached = tableLookup(table, len(s1), len(s2))
if (cached <> None):
return cached
if s1 == '':
return memo(len(s2))
elif s2 == '':
return memo(len(s1))
else:
if s1[0] == s2[0]:
d0 = 0
elif s1[0].lower() == s2[0].lower():
d0 = 1
else:
d0 = 2
d0 = d0 + dist1(table, s1[1:], s2[1:])
d1 = 1 + dist1(table, s1[1:], s2)
d2 = 1 + dist1(table, s1, s2[1:])
return memo(min(d0, d1, d2))
#-------------------------------------------------------------
# diff of nodes
#-------------------------------------------------------------
stat.diffCount = 0
def diffNode(node1, node2, env1, env2, depth, move):
# try substructural diff
def trysub((changes, cost)):
if not move:
return (changes, cost)
elif canMove(node1, node2, cost):
return (changes, cost)
else:
mc1 = diffSubNode(node1, node2, env1, env2, depth, move)
if mc1 <> None:
return mc1
else:
return (changes, cost)
if IS(node1, list) and not IS(node2, list):
return diffNode(node1, [node2], env1, env2, depth, move)
if not IS(node1, list) and IS(node2, list):
return diffNode([node1], node2, env1, env2, depth, move)
if (IS(node1, list) and IS(node2, list)):
node1 = serializeIf(node1)
node2 = serializeIf(node2)
table = createTable(len(node1), len(node2))
return diffList(table, node1, node2, env1, env2, 0, move)
# statistics
stat.diffCount += 1
if stat.diffCount % 1000 == 0:
dot()
if node1 == node2:
return (modifyNode(node1, node2, 0), 0)
if IS(node1, Num) and IS(node2, Num):
if node1.n == node2.n:
return (modifyNode(node1, node2, 0), 0)
else:
return (modifyNode(node1, node2, 1), 1)
if IS(node1, Str) and IS(node2, Str):
cost = strDist(node1.s, node2.s)
return (modifyNode(node1, node2, cost), cost)
if (IS(node1, Name) and IS(node2, Name)):
v1 = lookup(node1.id, env1)
v2 = lookup(node2.id, env2)
if v1 <> v2 or (v1 == None and v2 == None):
cost = strDist(node1.id, node2.id)
return (modifyNode(node1, node2, cost), cost)
else: # same variable
return (modifyNode(node1, node2, 0), 0)
if (IS(node1, Attribute) and IS(node2, Name) or
IS(node1, Name) and IS(node2, Attribute) or
IS(node1, Attribute) and IS(node2, Attribute)):
s1 = attr2str(node1)
s2 = attr2str(node2)
if s1 <> None and s2 <> None:
cost = strDist(s1, s2)
return (modifyNode(node1, node2, cost), cost)
# else fall through for things like f(x).y vs x.y
# if (IS(node1, ClassDef) and IS(node2, ClassDef)):
# (m1, c1) = diffNode(node1.bases, node2.bases, env1, env2, depth, move)
# (m2, c2) = diffNode(node1.body, node2.body, env1, env2, depth, move)
# (m3, c3) = diffNode(node1.decorator_list, node2.decorator_list,
# env1, env2, depth, move)
# changes = append(m1, m2, m3)
# cost = c1 + c2 + c3 + strDist(node1.name, node2.name)
# return trysub((changes, cost))
# if (IS(node1, FunctionDef) and IS(node2, FunctionDef)):
# return trysub(diffFunctionDef(node1, node2,
# env1, env2, depth, move))
# if (IS(node1, Assign) and IS(node2, Assign)):
# (m1, c1) = diffNode(node1.targets, node2.targets,
# env1, env2, depth, move)
# (m2, c2) = diffNode(node1.value, node2.value,
# env1, env2, depth, move)
# return (append(m1, m2), c1 * ASSIGN_PENALTY + c2)
# # flatten nested if nodes
# if IS(node1, If) and IS(node2, If):
# seq1 = serializeIf(node1)
# seq2 = serializeIf(node2)
# if len(seq1) > 1 and len(seq2) > 1:
# return diffNode(seq1, seq2, env1, env2, depth, move)
# else:
# (m0, c0) = diffNode(node1.test, node2.test, env1, env2, depth, move)
# (m1, c1) = diffNode(node1.body, node2.body, env1, env2, depth, move)
# (m2, c2) = diffNode(node1.orelse, node2.orelse, env1, env2, depth, move)
# changes = append(m0, m1, m2)
# cost = c0 * IF_PENALTY + c1 + c2
# return trysub((changes, cost))
if IS(node1, Module) and IS(node2, Module):
return diffNode(node1.body, node2.body, env1, env2, depth, move)
# other AST nodes
if (IS(node1, AST) and IS(node2, AST) and
type(node1) == type(node2)):
fs1 = nodeFields(node1)
fs2 = nodeFields(node2)
changes, cost = nil, 0
for i in xrange(len(fs1)):
(m, c) = diffNode(fs1[i], fs2[i], env1, env2, depth, move)
changes = append(m, changes)
cost += c
return trysub((changes, cost))
if (type(node1) == type(node2) and
isEmptyContainer(node1) and isEmptyContainer(node2)):
return (modifyNode(node1, node2, 0), 0)
# all unmatched types and unequal values
return trysub((append(delNode(node1), insNode(node2)),
nodeSize(node1) + nodeSize(node2)))
###################### diff of a FunctionDef #####################
# separate out because it is too long
def diffFunctionDef(node1, node2, env1, env2, depth, move):
# positionals
len1 = len(node1.args.args)
len2 = len(node2.args.args)
if len1 < len2:
minlen = len1
rest = node2.args.args[minlen:]
else:
minlen = len2
rest = node1.args.args[minlen:]
ma = nil
for i in xrange(minlen):
a1 = node1.args.args[i]
a2 = node2.args.args[i]
if IS(a1, Name) and IS(a2, Name) and a1.id <> a2.id:
env1 = ext(a1.id, a2, env1)
env2 = ext(a2.id, a2, env2)
(m1, c1) = diffNode(a1, a2, env1, env2, depth, move)
ma = append(m1, ma)
# handle rest of the positionals
ca = 0
if rest <> []:
if len1 < len2:
for arg in rest:
ma = append(insNode(arg), ma)
ca += nodeSize(arg)
else:
for arg in rest:
ma = append(delNode(arg), ma)
ca += nodeSize(arg)
# vararg
va1 = node1.varargName
va2 = node2.varargName
if va1 <> None and va2 <> None:
if va1.id <> va2.id:
env1 = ext(va1.id, va2, env1)
env2 = ext(va2.id, va2, env2)
cost = strDist(va1.id, va2.id)
ma = append(modifyNode(va1, va2, cost), ma)
ca += cost
elif va1 <> None or va2 <> None:
cost = nodeSize(va1) if va1 <> None else nodeSize(va2)
ma = append(modifyNode(va1, va2, cost), ma)
ca += cost
# kwarg
ka1 = node1.kwargName
ka2 = node2.kwargName
if ka1 <> None and ka2 <> None:
if ka1.id <> ka2.id:
env1 = ext(ka1.id, ka2, env1)
env2 = ext(ka2.id, ka2, env2)
cost = strDist(ka1.id, ka2.id)
ma = append(modifyNode(ka1, ka2, cost), ma)
ca += cost
elif ka1 <> None or ka2 <> None:
cost = nodeSize(ka1) if ka1 <> None else nodeSize(ka2)
ma = append(modifyNode(ka1, ka2, cost), ma)
ca += cost
# defaults and body
(md, cd) = diffNode(node1.args.defaults, node2.args.defaults,
env1, env2, depth, move)
(mb, cb) = diffNode(node1.body, node2.body, env1, env2, depth, move)
# sum up cost. penalize functions with different names.
cost = ca + cd + cb + strDist(node1.name, node2.name)
if node1.name <> node2.name:
cost = cost * NAME_PENALTY
return (append(ma, md, mb), cost)
########################## diff of a list ##########################
# diffList is the main part of dynamic programming
def diffList(table, ls1, ls2, env1, env2, depth, move):
def memo(v):
tablePut(table, len(ls1), len(ls2), v)
return v
def guess(table, ls1, ls2, env1, env2):
(m0, c0) = diffNode(ls1[0], ls2[0], env1, env2, depth, move)
(m1, c1) = diffList(table, ls1[1:], ls2[1:], env1, env2, depth, move)
cost1 = c1 + c0
if ((isFrame(ls1[0]) and
isFrame(ls2[0]) and
not nodeFramed(ls1[0], m0) and
not nodeFramed(ls2[0], m0))):
frameChange = modifyNode(ls1[0], ls2[0], c0)
else:
frameChange = nil
# short cut 1 (func and classes with same names)
if canMove(ls1[0], ls2[0], c0):
return (append(frameChange, m0, m1), cost1)
else: # do more work
(m2, c2) = diffList(table, ls1[1:], ls2, env1, env2, depth, move)
(m3, c3) = diffList(table, ls1, ls2[1:], env1, env2, depth, move)
cost2 = c2 + nodeSize(ls1[0])
cost3 = c3 + nodeSize(ls2[0])
if (not differentDef(ls1[0], ls2[0]) and
cost1 <= cost2 and cost1 <= cost3):
return (append(frameChange, m0, m1), cost1)
elif (cost2 <= cost3):
return (append(delNode(ls1[0]), m2), cost2)
else:
return (append(insNode(ls2[0]), m3), cost3)
# cache look up
cached = tableLookup(table, len(ls1), len(ls2))
if (cached <> None):
return cached
if (ls1 == [] and ls2 == []):
return memo((nil, 0))
elif (ls1 <> [] and ls2 <> []):
return memo(guess(table, ls1, ls2, env1, env2))
elif ls1 == []:
d = nil
for n in ls2:
d = append(insNode(n), d)
return memo((d, nodeSize(ls2)))
else: # ls2 == []:
d = nil
for n in ls1:
d = append(delNode(n), d)
return memo((d, nodeSize(ls1)))
###################### diff into a subnode #######################
# Subnode diff is only used in the moving phase. There is no
# need to compare the substructure of two nodes in the first
# run, because they will be reconsidered if we just consider
# them to be complete deletion and insertions.
def diffSubNode(node1, node2, env1, env2, depth, move):
if (depth >= FRAME_DEPTH or
nodeSize(node1) < FRAME_SIZE or
nodeSize(node2) < FRAME_SIZE):
return None
if IS(node1, AST) and IS(node2, AST):
if nodeSize(node1) == nodeSize(node2):
return None
if IS(node1, Expr):
node1 = node1.value
if IS(node2, Expr):
node2 = node2.value
if (nodeSize(node1) < nodeSize(node2)):
for f in nodeFields(node2):
(m0, c0) = diffNode(node1, f, env1, env2, depth+1, move)
if canMove(node1, f, c0):
if not IS(f, list):
m1 = modifyNode(node1, f, c0)
else:
m1 = nil
framecost = nodeSize(node2) - nodeSize(node1)
m2 = loner(Change(None, node2, framecost, True))
return (append(m2, m1, m0), c0 + framecost)
if (nodeSize(node1) > nodeSize(node2)):
for f in nodeFields(node1):
(m0, c0) = diffNode(f, node2, env1, env2, depth+1, move)
if canMove(f, node2, c0):
framecost = nodeSize(node1) - nodeSize(node2)
if not IS(f, list):
m1 = modifyNode(f, node2, c0)
else:
m1 = nil
m2 = loner(Change(node1, None, framecost, True))
return (append(m2, m1, m0), c0 + framecost)
return None
##########################################################################
## move detection
##########################################################################
def moveCandidate(node):
return (isDef(node) or nodeSize(node) >= MOVE_SIZE)
stat.moveCount = 0
stat.moveSavings = 0
def getmoves(ds, round=0):
dels = pylist(filterlist(lambda p: (p.cur == None and
moveCandidate(p.orig) and
not p.isFrame),
ds))
adds = pylist(filterlist(lambda p: (p.orig == None and
moveCandidate(p.cur) and
not p.isFrame),
ds))
# print "dels=", dels
# print "adds=", adds
matched = []
newChanges, total = nil, 0
print("\n[getmoves #%d] %d * %d = %d pairs of nodes to consider ..."
% (round, len(dels), len(adds), len(dels) * len(adds)))
for d0 in dels:
for a0 in adds:
(node1, node2) = (d0.orig, a0.cur)
(changes, cost) = diffNode(node1, node2, nil, nil, 0, True)
nterms = nodeSize(node1) + nodeSize(node2)
if (canMove(node1, node2, cost) or
nodeFramed(node1, changes) or
nodeFramed(node2, changes)):
matched.append(d0)
matched.append(a0)
adds.remove(a0)
newChanges = append(changes, newChanges)
total += cost
if (not nodeFramed(node1, changes) and
not nodeFramed(node2, changes) and
isDef(node1) and isDef(node2)):
newChanges = append(modifyNode(node1, node2, cost),
newChanges)
stat.moveSavings += nterms
stat.moveCount +=1
if stat.moveCount % 1000 == 0:
dot()
break
print("\n\t%d matched pairs found with %d new changes."
% (len(pylist(matched)), len(pylist(newChanges))))
# print "matches=", matched
# print "newChanges=", newChanges
return (matched, newChanges, total)
# Get moves repeatedly because new moves may introduce new
# deletions and insertions.
def closure(res):
(changes, cost) = res
matched = None
moveround = 1
while moveround <= MOVE_ROUND and matched <> []:
(matched, newChanges, c) = getmoves(changes, moveround)
moveround += 1
# print "matched:", matched
# print "changes:", changes
changes = filterlist(lambda c: c not in matched, changes)
changes = append(newChanges, changes)
savings = sum(map(lambda p: nodeSize(p.orig) + nodeSize(p.cur), matched))
cost = cost + c - savings
return (changes, cost)
#-------------------------------------------------------------
# improvements to the AST
#-------------------------------------------------------------
allNodes1 = set()
allNodes2 = set()
def improveNode(node, s, idxmap, filename, side):
if IS(node, list):
for n in node:
improveNode(n, s, idxmap, filename, side)
elif IS(node, AST):
if side == 'left':
allNodes1.add(node)
else:
allNodes2.add(node)
findNodeStart(node, s, idxmap)
findNodeEnd(node, s, idxmap)
addMissingNames(node, s, idxmap)
node.nodeSource = s
node.fileName = filename
for f in nodeFields(node):
improveNode(f, s, idxmap, filename, side)
def improveAST(node, s, filename, side):
idxmap = buildIndexMap(s)
improveNode(node, s, idxmap, filename, side)
#-------------------------------------------------------------
# finding start and end index of nodes
#-------------------------------------------------------------
def findNodeStart(node, s, idxmap):
if hasattr(node, 'nodeStart'):
return node.nodeStart
elif IS(node, list):
ret = findNodeStart(node[0], s, idxmap)
elif IS(node, Module):
ret = findNodeStart(node.body[0], s, idxmap)
elif IS(node, BinOp):
leftstart = findNodeStart(node.left, s, idxmap)
if leftstart <> None:
ret = leftstart
else:
ret = mapIdx(idxmap, node.lineno, node.col_offset)
elif hasattr(node, 'lineno'):
if node.col_offset >= 0:
ret = mapIdx(idxmap, node.lineno, node.col_offset)
else: # special case for """ strings
i = mapIdx(idxmap, node.lineno, node.col_offset)
while i > 0 and i+2 < len(s) and s[i:i+3] <> '"""':
i -= 1
ret = i
else:
ret = None
if ret == None and hasattr(node, 'lineno'):
raise TypeError("got None for node that has lineno", node)
if IS(node, AST) and ret <> None:
node.nodeStart = ret
return ret
def findNodeEnd(node, s, idxmap):
if hasattr(node, 'nodeEnd'):
return node.nodeEnd
elif IS(node, list):
ret = findNodeEnd(node[-1], s, idxmap)
elif IS(node, Module):
ret = findNodeEnd(node.body[-1], s, idxmap)
elif IS(node, Expr):
ret = findNodeEnd(node.value, s, idxmap)
elif IS(node, Str):
i = findNodeStart(node, s, idxmap)
if i+2 < len(s) and s[i:i+3] == '"""':
q = '"""'