I am working on a python library that turns python source code in to a control flow graph (CFG). As an intermediate step, I have converted the source code into an xml representation.
For example, the following source code:
def bar(): # line 32
a += 1 # line 33
for x in [1,2]: # line 34
print x # line 35
if x%2: # line 36
print x**2 # line 37
break # line 38
else: # line 39
print x**3 # line 40
else: # line 41
print "wpp" # line 42
print "done" # line 43
Is converted into the following xml:
<?xml version="1.0" ?>
<module>
: 0
: <functiondef>
: : 32
: : <augassign>
: : : 33
: : : <name>33</name>
: : : <add>add</add>
: : : <num>33</num>
: : </augassign>
: : <for>
: : : 34
: : : <print>
: : : : 35
: : : : <name>35</name>
: : : </print>
: : : <if>
: : : : 36
: : : : <binop>
: : : : : 36
: : : : : <name>36</name>
: : : : : <mod>mod</mod>
: : : : : <num>36</num>
: : : : </binop>
: : : : <print>
: : : : : 37
: : : : : <binop>
: : : : : : 37
: : : : : : <name>37</name>
: : : : : : <pow>pow</pow>
: : : : : : <num>37</num>
: : : : : </binop>
: : : : </print>
: : : : <break>38</break>
: : : : <else>
: : : : : 39
: : : : : <print>
: : : : : : 40
: : : : : : <binop>
: : : : : : : 40
: : : : : : : <name>40</name>
: : : : : : : <pow>pow</pow>
: : : : : : : <num>40</num>
: : : : : : </binop>
: : : : : </print>
: : : : </else>
: : : </if>
: : : <else>
: : : : 41
: : : : <print>
: : : : : 42
: : : : : <str>42</str>
: : : : </print>
: : : </else>
: : </for>
: : <print>
: : : 43
: : : <str>43</str>
: : </print>
: </functiondef>
</module>
Now, what I need to do, is turn this xml into a CFG, represented as follows:
0 [32]
32 [33]
33 [34]
34 [35, 42]
35 [36]
36 [37, 40]
37 [38]
38 [43]
40 [34]
42 [43]
43 []
Now, I've handled most cases I've seen so far. However, I'm having some trouble connecting the correct ends of the for-loop back to the top/definition of the for loop (line 34)
I'd be super appreciative of anyone who can help me figure out how to figure out which nodes of the for loop connect back to the top of the for loop. In this example, there is only one such node, namely the one on line 40