Parsing Java Source Code

2019-02-16 20:53发布

I am asked to develop a software which should be able to create Flow chart/ Control Flow of the input Java source code. So I started researching on it and arrived at following solutions:

To create flow chart/control flow I have to recognize controlling statements and function calls made in the given source code Now I have two ways of recognizing:

  1. Parse the Source code by writing my own grammars (A complex solution I think). I am thinking to use Antlr for this.
  2. Read input source code files as text and search for the specific patterns (May become inefficient)

Am I right here? Or I am missing something very fundamental and simple? Which approach would take less time and do the work efficiently? Any other suggestions in this regard will be welcome too. Any other efficient approach would help because the input source code may span multiple files and can be fairly complex.

I am good in .NET languages but this is my first big project in Java. I have basic knowledge of Compiler Design so writing grammars should not be impossible for me.

Sorry If I am being unclear. Please ask for any clarifications.

9条回答
你好瞎i
2楼-- · 2019-02-16 21:30

Now I have two ways of recognizing:

You have many more ways than that. JavaCC ships with a Java 1.5 grammar already built. I'm sure other parser generators ditto. There is no reason for you to either have to write your own grammar or construct your own parser.

And specifically 'read[ing] input source code files as text and search for the specific patterns' isn't a viable choice at all, as it isn't parsing, and therefore cannot possibly recognize Java programs correctly.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-02-16 21:31

I'd go with Antlr and use an existing Java grammar: https://github.com/antlr/grammars-v4

查看更多
不美不萌又怎样
4楼-- · 2019-02-16 21:34

The way I would do it is to analyse compiled code. This would allow you to read jars without source and avoid parsing the code yourself. I would use Objectwebs ASM to read the class files.

查看更多
登录 后发表回答