-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathpydiff.py
executable file
·1874 lines (1393 loc) · 49.8 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
#!/usr/bin/env python
import sys
import re
import cProfile
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
#-------------------------------------------------------------
def debug(*args):
if DEBUG:
print args
def dot():
sys.stdout.write('.')
def is_alpha(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 isinstance(v, Expr):
return v.value
else:
return v
def sz(s):
return node_size(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():
cProfile.run("run('heavy')", sort="cumulative")
#------------------------ file system support -----------------------
def base_name(filename):
try:
start = filename.rindex('/') + 1
except ValueError:
start = 0
try:
end = filename.rindex('.py')
except ValueError:
end = 0
return filename[start:end]
## file system support
def parse_file(filename):
f = open(filename, 'r');
lines = f.read()
ast = parse(lines)
improve_ast(ast, lines, filename, 'left')
return ast
#-------------------------------------------------------------
# tests and operations on AST nodes
#-------------------------------------------------------------
# get list of fields from a node
def node_fields(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 node_source(node):
if hasattr(node, 'node_source'):
return node.node_source
else:
return None
# utility for getting exact source code part of the node
def src(node):
return node.node_source[node.node_start : node.node_end]
def node_start(node):
if (hasattr(node, 'node_start')):
return node.node_start
else:
return 0
def node_end(node):
return node.node_end
def is_atom(x):
return type(x) in [int, str, bool, float]
def is_def(node):
return isinstance(node, FunctionDef) or isinstance(node, ClassDef)
# whether a node is a "frame" which can contain others and be
# labeled
def is_frame(node):
return type(node) in [ClassDef, FunctionDef, Import, ImportFrom]
def is_empty_container(node):
if isinstance(node, List) and node.elts == []:
return True
if isinstance(node, Tuple) and node.elts == []:
return True
if isinstance(node, Dict) and node.keys == []:
return True
return False
def same_def(node1, node2):
if isinstance(node1, FunctionDef) and isinstance(node2, FunctionDef):
return node1.name == node2.name
elif isinstance(node1, ClassDef) and isinstance(node2, ClassDef):
return node1.name == node2.name
else:
return False
def different_def(node1, node2):
if is_def(node1) and is_def(node2):
return node1.name <> node2.name
return False
# decide whether it is reasonable to consider two nodes to be
# moves of each other
def can_move(node1, node2, c):
return (same_def(node1, node2) or
c <= (node_size(node1) + node_size(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.is_frame 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 serialize_if(node):
if isinstance(node, If):
if not hasattr(node, 'node_end'):
print "has no end:", node
newif = If(node.test, node.body, [])
newif.lineno = node.lineno
newif.col_offset = node.col_offset
newif.node_start = node.node_start
newif.node_end = node.node_end
newif.node_source = node.node_source
newif.fileName = node.fileName
return [newif] + serialize_if(node.orelse)
elif isinstance(node, list):
ret = []
for n in node:
ret += serialize_if(n)
return ret
else:
return [node]
def node_name(node):
if isinstance(node, Name):
return node.id
elif isinstance(node, FunctionDef) or isinstance(node, ClassDef):
return node.name
else:
return None
def attr2str(node):
if isinstance(node, Attribute):
vName = attr2str(node.value)
if vName <> None:
return vName + "." + node.attr
else:
return None
elif isinstance(node, Name):
return node.id
else:
return None
### utility for counting size of terms
def node_size(node, test=False):
if not test and hasattr(node, 'node_size'):
ret = node.node_size
elif isinstance(node, list):
ret = sum(map(lambda x: node_size(x, test), node))
elif is_atom(node):
ret = 1
elif isinstance(node, Name):
ret = 1
elif isinstance(node, Num):
ret = 1
elif isinstance(node, Str):
ret = 1
elif isinstance(node, Expr):
ret = node_size(node.value, test)
elif isinstance(node, AST):
ret = 1 + sum(map(lambda x: node_size(x, test), node_fields(node)))
else:
ret = 0
if test:
print "node:", node, "size=", ret
if isinstance(node, AST):
node.node_size = 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, is_frame=False):
self.orig = orig
self.cur = cur
if orig == None:
self.cost = node_size(cur)
elif cur == None:
self.cost = node_size(orig)
elif cost == 'all':
self.cost = node_size(orig) + node_size(cur)
else:
self.cost = cost
self.is_frame = is_frame
def __repr__(self):
fr = "F" if self.is_frame 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 = node_size(self.orig) + node_size(self.cur)
return 1 - div(self.cost, total)
# Three major kinds of changes:
# * modification
# * deletion
# *insertion
def modify_node(node1, node2, cost):
return loner(Change(node1, node2, cost))
def del_node(node):
return loner(Change(node, None, node_size(node)))
def ins_node(node):
return loner(Change(None, node, node_size(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 create_table(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
str_dist_cache = Cache()
def clear_str_dist_cache():
global str_dist_cache
str_dist_cache = Cache()
### string distance function
def str_dist(s1, s2):
cached = str_dist_cache.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 = create_table(len(s1), len(s2))
d = dist1(table, s1, s2)
ret = div(2*d, len(s1) + len(s2))
str_dist_cache.put((s1, s2), ret)
return ret
# the main dynamic programming part
# similar to the structure of diff_list
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.diff_count = 0
def diff_node(node1, node2, env1, env2, depth, move):
# try substructural diff
def trysub((changes, cost)):
if not move:
return (changes, cost)
elif can_move(node1, node2, cost):
return (changes, cost)
else:
mc1 = diff_subnode(node1, node2, env1, env2, depth, move)
if mc1 <> None:
return mc1
else:
return (changes, cost)
if isinstance(node1, list) and not isinstance(node2, list):
return diff_node(node1, [node2], env1, env2, depth, move)
if not isinstance(node1, list) and isinstance(node2, list):
return diff_node([node1], node2, env1, env2, depth, move)
if (isinstance(node1, list) and isinstance(node2, list)):
node1 = serialize_if(node1)
node2 = serialize_if(node2)
table = create_table(len(node1), len(node2))
return diff_list(table, node1, node2, env1, env2, 0, move)
# statistics
stat.diff_count += 1
if stat.diff_count % 1000 == 0:
dot()
if node1 == node2:
return (modify_node(node1, node2, 0), 0)
if isinstance(node1, Num) and isinstance(node2, Num):
if node1.n == node2.n:
return (modify_node(node1, node2, 0), 0)
else:
return (modify_node(node1, node2, 1), 1)
if isinstance(node1, Str) and isinstance(node2, Str):
cost = str_dist(node1.s, node2.s)
return (modify_node(node1, node2, cost), cost)
if (isinstance(node1, Name) and isinstance(node2, Name)):
v1 = lookup(node1.id, env1)
v2 = lookup(node2.id, env2)
if v1 <> v2 or (v1 == None and v2 == None):
cost = str_dist(node1.id, node2.id)
return (modify_node(node1, node2, cost), cost)
else: # same variable
return (modify_node(node1, node2, 0), 0)
if (isinstance(node1, Attribute) and isinstance(node2, Name) or
isinstance(node1, Name) and isinstance(node2, Attribute) or
isinstance(node1, Attribute) and isinstance(node2, Attribute)):
s1 = attr2str(node1)
s2 = attr2str(node2)
if s1 <> None and s2 <> None:
cost = str_dist(s1, s2)
return (modify_node(node1, node2, cost), cost)
# else fall through for things like f(x).y vs x.y
if isinstance(node1, Module) and isinstance(node2, Module):
return diff_node(node1.body, node2.body, env1, env2, depth, move)
# other AST nodes
if (isinstance(node1, AST) and isinstance(node2, AST) and
type(node1) == type(node2)):
fs1 = node_fields(node1)
fs2 = node_fields(node2)
changes, cost = nil, 0
for i in xrange(len(fs1)):
(m, c) = diff_node(fs1[i], fs2[i], env1, env2, depth, move)
changes = append(m, changes)
cost += c
return trysub((changes, cost))
if (type(node1) == type(node2) and
is_empty_container(node1) and is_empty_container(node2)):
return (modify_node(node1, node2, 0), 0)
# all unmatched types and unequal values
return trysub((append(del_node(node1), ins_node(node2)),
node_size(node1) + node_size(node2)))
########################## diff of a list ##########################
# diff_list is the main part of dynamic programming
def diff_list(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) = diff_node(ls1[0], ls2[0], env1, env2, depth, move)
(m1, c1) = diff_list(table, ls1[1:], ls2[1:], env1, env2, depth, move)
cost1 = c1 + c0
if ((is_frame(ls1[0]) and
is_frame(ls2[0]) and
not nodeFramed(ls1[0], m0) and
not nodeFramed(ls2[0], m0))):
frameChange = modify_node(ls1[0], ls2[0], c0)
else:
frameChange = nil
# short cut 1 (func and classes with same names)
if can_move(ls1[0], ls2[0], c0):
return (append(frameChange, m0, m1), cost1)
else: # do more work
(m2, c2) = diff_list(table, ls1[1:], ls2, env1, env2, depth, move)
(m3, c3) = diff_list(table, ls1, ls2[1:], env1, env2, depth, move)
cost2 = c2 + node_size(ls1[0])
cost3 = c3 + node_size(ls2[0])
if (not different_def(ls1[0], ls2[0]) and
cost1 <= cost2 and cost1 <= cost3):
return (append(frameChange, m0, m1), cost1)
elif (cost2 <= cost3):
return (append(del_node(ls1[0]), m2), cost2)
else:
return (append(ins_node(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(ins_node(n), d)
return memo((d, node_size(ls2)))
else: # ls2 == []:
d = nil
for n in ls1:
d = append(del_node(n), d)
return memo((d, node_size(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 diff_subnode(node1, node2, env1, env2, depth, move):
if (depth >= FRAME_DEPTH or
node_size(node1) < FRAME_SIZE or
node_size(node2) < FRAME_SIZE):
return None
if isinstance(node1, AST) and isinstance(node2, AST):
if node_size(node1) == node_size(node2):
return None
if isinstance(node1, Expr):
node1 = node1.value
if isinstance(node2, Expr):
node2 = node2.value
if (node_size(node1) < node_size(node2)):
for f in node_fields(node2):
(m0, c0) = diff_node(node1, f, env1, env2, depth+1, move)
if can_move(node1, f, c0):
if not isinstance(f, list):
m1 = modify_node(node1, f, c0)
else:
m1 = nil
framecost = node_size(node2) - node_size(node1)
m2 = loner(Change(None, node2, framecost, True))
return (append(m2, m1, m0), c0 + framecost)
if (node_size(node1) > node_size(node2)):
for f in node_fields(node1):
(m0, c0) = diff_node(f, node2, env1, env2, depth+1, move)
if can_move(f, node2, c0):
framecost = node_size(node1) - node_size(node2)
if not isinstance(f, list):
m1 = modify_node(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 move_candidate(node):
return (is_def(node) or node_size(node) >= MOVE_SIZE)
stat.move_count = 0
stat.move_savings = 0
def get_moves(ds, round=0):
dels = pylist(filterlist(lambda p: (p.cur == None and
move_candidate(p.orig) and
not p.is_frame),
ds))
adds = pylist(filterlist(lambda p: (p.orig == None and
move_candidate(p.cur) and
not p.is_frame),
ds))
# print "dels=", dels
# print "adds=", adds
matched = []
newChanges, total = nil, 0
print("\n[get_moves #%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) = diff_node(node1, node2, nil, nil, 0, True)
nterms = node_size(node1) + node_size(node2)
if (can_move(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
is_def(node1) and is_def(node2)):
newChanges = append(modify_node(node1, node2, cost),
newChanges)
stat.move_savings += nterms
stat.move_count +=1
if stat.move_count % 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) = get_moves(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: node_size(p.orig) + node_size(p.cur), matched))
cost = cost + c - savings
return (changes, cost)
#-------------------------------------------------------------
# improvements to the AST
#-------------------------------------------------------------
allNodes1 = set()
allNodes2 = set()
def improve_node(node, s, idxmap, filename, side):
if isinstance(node, list):
for n in node:
improve_node(n, s, idxmap, filename, side)
elif isinstance(node, AST):
if side == 'left':
allNodes1.add(node)
else:
allNodes2.add(node)
find_node_start(node, s, idxmap)
find_node_end(node, s, idxmap)
add_missing_names(node, s, idxmap)
node.node_source = s
node.fileName = filename
for f in node_fields(node):
improve_node(f, s, idxmap, filename, side)
def improve_ast(node, s, filename, side):
idxmap = build_index_map(s)
improve_node(node, s, idxmap, filename, side)
#-------------------------------------------------------------
# finding start and end index of nodes
#-------------------------------------------------------------
def find_node_start(node, s, idxmap):
if hasattr(node, 'node_start'):
return node.node_start
elif isinstance(node, list):
ret = find_node_start(node[0], s, idxmap)
elif isinstance(node, Module):
ret = find_node_start(node.body[0], s, idxmap)
elif isinstance(node, BinOp):
leftstart = find_node_start(node.left, s, idxmap)
if leftstart <> None:
ret = leftstart
else:
ret = map_idx(idxmap, node.lineno, node.col_offset)
elif hasattr(node, 'lineno'):
if node.col_offset >= 0:
ret = map_idx(idxmap, node.lineno, node.col_offset)
else: # special case for """ strings
i = map_idx(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 isinstance(node, AST) and ret <> None:
node.node_start = ret
return ret
def find_node_end(node, s, idxmap):
if hasattr(node, 'node_end'):
return node.node_end
elif isinstance(node, list):
ret = find_node_end(node[-1], s, idxmap)
elif isinstance(node, Module):
ret = find_node_end(node.body[-1], s, idxmap)
elif isinstance(node, Expr):
ret = find_node_end(node.value, s, idxmap)
elif isinstance(node, Str):
i = find_node_start(node, s, idxmap)
if i+2 < len(s) and s[i:i+3] == '"""':
q = '"""'
i += 3
elif s[i] == '"':
q = '"'
i += 1
elif s[i] == "'":
q = "'"
i += 1
else:
print "illegal:", i, s[i]
ret = end_seq(s, q, i)
elif isinstance(node, Name):
ret = find_node_start(node, s, idxmap) + len(node.id)
elif isinstance(node, Attribute):
ret = end_seq(s, node.attr, find_node_end(node.value, s, idxmap))
elif isinstance(node, FunctionDef):
# add_missing_names(node, s, idxmap)
# ret = find_node_end(node.nameName, s, idxmap)
ret = find_node_end(node.body, s, idxmap)
elif isinstance(node, Lambda):
ret = find_node_end(node.body, s, idxmap)
elif isinstance(node, ClassDef):
# add_missing_names(node, s, idxmap)
# ret = find_node_end(node.nameName, s, idxmap)
ret = find_node_end(node.body, s, idxmap)
elif isinstance(node, Call):
ret = match_paren(s, '(', ')', find_node_end(node.func, s, idxmap))
elif isinstance(node, Yield):
ret = find_node_end(node.value, s, idxmap)
elif isinstance(node, Return):
if node.value <> None:
ret = find_node_end(node.value, s, idxmap)
else:
ret = find_node_start(node, s, idxmap) + len('return')
elif isinstance(node, Print):
ret = start_seq(s, '\n', find_node_start(node, s, idxmap))
elif (isinstance(node, For) or
isinstance(node, While) or
isinstance(node, If) or
isinstance(node, IfExp)):
if node.orelse <> []:
ret = find_node_end(node.orelse, s, idxmap)
else:
ret = find_node_end(node.body, s, idxmap)
elif isinstance(node, Assign) or isinstance(node, AugAssign):
ret = find_node_end(node.value, s, idxmap)
elif isinstance(node, BinOp):
ret = find_node_end(node.right, s, idxmap)
elif isinstance(node, BoolOp):
ret = find_node_end(node.values[-1], s, idxmap)
elif isinstance(node, Compare):
ret = find_node_end(node.comparators[-1], s, idxmap)
elif isinstance(node, UnaryOp):
ret = find_node_end(node.operand, s, idxmap)
elif isinstance(node, Num):
ret = find_node_start(node, s, idxmap) + len(str(node.n))
elif isinstance(node, List):
ret = match_paren(s, '[', ']', find_node_start(node, s, idxmap));
elif isinstance(node, Subscript):
ret = match_paren(s, '[', ']', find_node_start(node, s, idxmap));
elif isinstance(node, Tuple):
ret = find_node_end(node.elts[-1], s, idxmap)
elif isinstance(node, Dict):
ret = match_paren(s, '{', '}', find_node_start(node, s, idxmap));
elif isinstance(node, TryExcept):
if node.orelse <> []:
ret = find_node_end(node.orelse, s, idxmap)
elif node.handlers <> []:
ret = find_node_end(node.handlers, s, idxmap)
else:
ret = find_node_end(node.body, s, idxmap)
elif isinstance(node, ExceptHandler):
ret = find_node_end(node.body, s, idxmap)
elif isinstance(node, Pass):
ret = find_node_start(node, s, idxmap) + len('pass')
elif isinstance(node, Break):
ret = find_node_start(node, s, idxmap) + len('break')
elif isinstance(node, Continue):
ret = find_node_start(node, s, idxmap) + len('continue')
elif isinstance(node, Global):
ret = start_seq(s, '\n', find_node_start(node, s, idxmap))
elif isinstance(node, Import):
ret = find_node_start(node, s, idxmap) + len('import')
elif isinstance(node, ImportFrom):
ret = find_node_start(node, s, idxmap) + len('from')
else:
# print "[find_node_end] unrecognized node:", node, "type:", type(node)
start = find_node_start(node, s, idxmap)
if start <> None:
ret = start + 3
else:
ret = None