The goal of this transformation is to extract all common lines from if-else
branches and move them before or after the statement.
Before:
s = input()
if s:
a = 2
b = a + a
print('foo')
x = 1
y = x
print(y)
else:
a = 2
b = a + a
print('bar')
x = 1
y = x
print(y)
After:
s = input()
a = 2
b = a + a
if s:
print('foo')
else:
print('bar')
x = 1
y = x
print(y)
-
Traverse the AST and find the node which represents the if statement
-
Calculate the length of the common suffix and prefix
-
Move the common suffix and prefix before or after the operator respectively
-
Remove the common parts from the
if
operator -
Validate the new
if
operator
- If the common part is in the middle of the statements list the statement does not change, because in this case, the length of the common suffix and prefix is zero. An example of unchanged code:
s = input()
if s:
print('foo')
a = 2
b = a + a
print('bar')
else:
print('foo1')
a = 2
b = a + a
print('bar1')
- The
PyStatment
comparison is done using thetextMatches
function, which compares the text within these statements