我如何解析代码来构建一个Java编译器? [英] How can I parse code to build a compiler in Java?

查看:136
本文介绍了我如何解析代码来构建一个Java编译器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个编译器。它是在大学的家庭作业。老师告诉我们,我们可以使用任何我们想要解析的代码,只要它是一个好的。这样,我们可以更多地关注我们将生成的JVM。

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.

所以是的,我将在Java中编写一个编译器来生成Java。

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

你知道有什么好的API吗?我应该使用regex吗?我通常用手写自己的解析器,虽然在这种情况下是不明智的。

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.

任何帮助都会感激。

推荐答案

Regex在编译器中很好用,但只用于识别令牌(即没有递归结构)。

Regex is good to use in a compiler, but only for recognizing tokens (i.e. no recursive structures).

编写编译器的经典方式是使用词法分析器识别标记,语法分析器用于识别结构,语义分析器中间代码生成器优化程序和最后一个目标代码生成器。任何这些步骤可以合并,或者完全跳过,如果使编译器更容易编写。

The classic way of writing a compiler is having a lexical analyzer for recognizing tokens, a syntax analyzer for recognizing structure, a semantic analyzer for recognizing meaning, an intermediate code generator, an optimizer, and last a target code generator. Any of those steps can be merged, or skipped entirely, if makes the compiler easier to write.

已经开发了许多工具来帮助这个过程。对于Java,您可以查看

There have been many tools developed to help with this process. For Java, you can look at

  • ANTLR - http://www.antlr.org/
  • Coco/R - http://ssw.jku.at/Coco/
  • JavaCC - https://javacc.dev.java.net/
  • SableCC - http://sablecc.org/

这篇关于我如何解析代码来构建一个Java编译器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆