How can I parse code to build a compiler in Java?

2019-03-20 08:02发布

I need to write a compiler. It's homework at the univ. The teacher told us that we can use any API we want to do the parsing of the code, as long as it is a good one. That way we can focus more on the JVM we will generate.

So yes, I'll write a compiler in Java to generate Java.

Do you know any good API for this? Should I use regex? I normally write my own parsers by hand, though it is not advisable in this scenario.

Any help would be appreciated.

12条回答
欢心
2楼-- · 2019-03-20 08:23

I suggest you look at at the source for BeanShell. It has a compiler for Java and is fairly simple to read.

查看更多
Luminary・发光体
3楼-- · 2019-03-20 08:27

JFlex is a scanner generator which, according to the manual, is designed to work with the parser generator CUP.

One of the main design goals of JFlex was to make interfacing with the free Java parser generator CUP as easy as possibly [sic].

It also has support for BYACC/J, which, as its name suggests, is a port of Berkeley YACC to generate Java code.

I have used JFlex itself and liked it. Howeveer, the project I was doing was simple enough that I wrote the parser by hand, so I don't know how good either CUP or BYACC/J is.

查看更多
混吃等死
4楼-- · 2019-03-20 08:29

Have a look at JavaCC, a language parser for Java. It's very easy to use and get the hang of

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-03-20 08:31

Parser combinators is a good choice. Popular Java implementation is JParsec.

查看更多
啃猪蹄的小仙女
6楼-- · 2019-03-20 08:32

I'd recommend using either a metacompiler like ANTLR, or a simple parser combinator library. Functional Java has a parser combinator API. There's also JParsec. Both of these are based on the Parsec library for Haskell.

查看更多
神经病院院长
7楼-- · 2019-03-20 08:36
登录 后发表回答