Convert Java code to flowchart
Once I said to run C language on JVM as my final project, but find it meaningless and useless without making out any scene. During my internship in Pingan fu, I read the heavy and document-less Java code day by day and did the stuff on the test framework. One day, I was reading a code fragment about the accounting voucher using the cartesian set, the method is long, the condition is complex, the document is none. the … WTF? But the shit of code brought me out with a brilliant idea, why not do some visualization on the mess of code? That’s the point, so I changed my mind.
If the code can be represented in some graphs, it must be more readable and understandable. So what graph should I choose? The UML is great for showing the blueprint of object relationships, its fields, and behaviors, but do nothing on the control flow and algorithm. So I chose the flowchart which presents the control flow of the code fragment. The flowchart is focusing on something smaller, usually, a code snippet where the algorithm or control flow exists. If a tool can convert the Java code snippet to a flowchart, I think I would understand the code more quickly that day.
So let’s convert Java code to flowchart graph! With 2-3 weeks’ learning and hardworking, the demo came out named CodeFlow.
Some features I’ve implemented so far:
Control flow in Java: sequence, loop(
do while) and condition(
Top-level function and statement
Multi-function supported, which represented in subgraphs
Function overload(now, different arguments size only)
Semantic check and warning
To-do or nerver do
- Support labels and
- Support Class method
These features will maybe should not be supported, but I also have a plan. For the labels and
goto, Dijkstra’s Go to statement considered harmful is well-known, yes, goto is harmful, but also useful in some situation. Whatever, Java reserves goto keyword, but not allowed to use.For the class method, as I wrote in comment:
Though our lexer and parser support parsing class declaration, but an object in a flowchart is complicated and confused. An Class/object should not represent in a flowchart, maybe a UML graph is better.
Here is a example of binary search:
Above code will generate a flowchart like this:
How it works
It use ANTLR4 to generate parser to parse Java code.
And then, visit the AST to build flowchart fragment:
- The single flowchart fragment is built directly
- The complex flowchart fragment(like nested conditions and loops) is built recursively
Use graphviz-java library convert node data structure to dot language while flowchart is also a directed graph.
Finally, use Graphviz to convert dot file to graph image.
I’ve created an IDEA plugin demo using the API I’ve built. The UI is simple but the function is fine.
License CC BY-NC-ND 4.0