14
14
"""
15
15
16
16
import re
17
- import lib2to3 .pytree as pytree
18
17
from lib2to3 .fixer_util import Leaf , Node , Comma
19
18
from lib2to3 import fixer_base
20
- from lib2to3 .fixer_util import syms , does_tree_import
21
19
from libfuturize .fixer_util import (token , future_import , touch_import_top ,
22
20
wrap_in_fn_call )
23
21
@@ -33,8 +31,8 @@ def match_division(node):
33
31
34
32
const_re = re .compile ('^[0-9]*[.][0-9]*$' )
35
33
36
- def is_floaty (node , div_idx ):
37
- return _is_floaty (node .children [ 0 : div_idx ] ) or _is_floaty (node .children [ div_idx + 1 :] )
34
+ def is_floaty (node ):
35
+ return _is_floaty (node .prev_sibling ) or _is_floaty (node .next_sibling )
38
36
39
37
40
38
def _is_floaty (expr ):
@@ -50,24 +48,6 @@ def _is_floaty(expr):
50
48
return expr .children [0 ].value == u'float'
51
49
return False
52
50
53
- def find_division (node ):
54
- for i , child in enumerate (node .children ):
55
- if match_division (child ):
56
- return i
57
- return False
58
-
59
- def clone_div_operands (node , div_idx ):
60
- children = []
61
- for i , child in enumerate (node .children ):
62
- if i == div_idx :
63
- children .append (Comma ())
64
- else :
65
- children .append (child .clone ())
66
-
67
- # Strip any leading space for the first number:
68
- children [0 ].prefix = u''
69
-
70
- return children
71
51
72
52
class FixDivisionSafe (fixer_base .BaseFix ):
73
53
# BM_compatible = True
@@ -92,18 +72,33 @@ def match(self, node):
92
72
matches, we can start discarding matches after the first.
93
73
"""
94
74
if node .type == self .syms .term :
95
- div_idx = find_division (node )
96
- if div_idx is not False :
97
- # if expr1 or expr2 are obviously floats, we don't need to wrap in
98
- # old_div, as the behavior of division between any number and a float
99
- # should be the same in 2 or 3
100
- if not is_floaty (node , div_idx ):
101
- return clone_div_operands (node , div_idx )
75
+ matched = False
76
+ skip = False
77
+ children = []
78
+ for child in node .children :
79
+ if skip :
80
+ skip = False
81
+ continue
82
+ if match_division (child ) and not is_floaty (child ):
83
+ matched = True
84
+
85
+ # Strip any leading space for the first number:
86
+ children [0 ].prefix = u''
87
+
88
+ children = [wrap_in_fn_call ("old_div" ,
89
+ children + [Comma (), child .next_sibling .clone ()],
90
+ prefix = node .prefix )]
91
+ skip = True
92
+ else :
93
+ children .append (child .clone ())
94
+ if matched :
95
+ return Node (node .type , children , fixers_applied = node .fixers_applied )
96
+
102
97
return False
103
98
104
99
def transform (self , node , results ):
105
100
if self .skip :
106
101
return
107
102
future_import (u"division" , node )
108
103
touch_import_top (u'past.utils' , u'old_div' , node )
109
- return wrap_in_fn_call ( "old_div" , results , prefix = node . prefix )
104
+ return results
0 commit comments