Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to generate a Control Flow-Graph for a method in Python?

I am writing a program that tries to compare two methods. I would like to generate Control flow graphs (CFG) for all matched methods and use either a topological sort to compare the two graphs.

like image 470
user739807 Avatar asked Jun 01 '11 16:06

user739807


People also ask

How do you make a control flow graph?

Note: Secret to drawing a CFG is to treat every statement independent to the program, draw it and then link it's entry and exit to the rest of the graph. Statement 1, 2, and 3 are non conditional so I created three blocks linking them together. Statement 4 is a conditional statement.

What is the control flow graph of a program?

A Control Flow Graph (CFG) is the graphical representation of control flow or computation during the execution of programs or applications. Control flow graphs are mostly used in static analysis as well as compiler applications, as they can accurately represent the flow inside of a program unit.


3 Answers

There's a Python package called staticfg which does exactly the this -- generation of control flow graphs from a piece of Python code.

For instance, putting the first quick sort Python snippet from Rosseta Code in qsort.py, the following code generates its control flow graph.

from staticfg import CFGBuilder

cfg = CFGBuilder().build_from_file('quick sort', 'qsort.py')
cfg.build_visual('qsort', 'png')

quick sort

Note that it doesn't seem to understand more advanced control flow like comprehensions.

like image 179
saaj Avatar answered Oct 08 '22 02:10

saaj


RPython, the translation toolchain behind PyPy, offers a way of grabbing the flow graph (in the pypy/rpython/flowspace directory of the PyPy project) for type inference.

This works quite well in most cases but generators are not supported. The result will be in SSA form, which might be good or bad, depending on what you want.

like image 24
KushalP Avatar answered Oct 08 '22 03:10

KushalP


I found py2cfg has a better representation of Control Flow Graph (CFG) than one from staticfg.

  • https://gitlab.com/classroomcode/py2cfg
  • https://pypi.org/project/py2cfg/

Let's take this function in Python:

    def fib():
        a, b = 0, 1
        while True:
            yield a
            a, b = b, a + b

    fib_gen = fib()
    for _ in range(10):
        next(fib_gen)

Image from StaticCFG: enter image description here

Image from PY2CFG: enter image description here

like image 43
Aditya Mehta Avatar answered Oct 08 '22 03:10

Aditya Mehta