基于 Java 的 JavaScript 解释器
作为学校的一个项目,我必须制作一个 JavaScript 解释器。 (一切,包括整个后端都必须由我制作)。
一切都必须用 Java 编写 - 我使用 ANTLR 来解析和生成 AST。
目前我可以将一些 .js 代码解析为 AST - 因此需要将此 AST 转换为某种可以在字节码机器上执行的中间表示形式。
我有一些为静态类型语言编写编译器的经验,但我非常怀疑如何从这里开始,因为 JS 是一种动态类型语言。
如果您能给我一些关于如何继续的好建议,我将不胜感激!
就我个人而言,我认为我必须先制作字节码机,然后再制作 IR 适合这台机器。不幸的是,我真的找不到任何关于如何编写字节码机的好的教程。
附言。我熟悉以下有关该主题的书籍:
“Java 中的现代编译器实现(Appel)”, “Java 编程语言处理器 (Watt & Brown)”, “语言实现模式 (Parr)”
问候 Sune
As a project in school i have to make a JavaScript interpreter. (Everything incl. the entire backend has to be made by me).
Everything has to be written in Java - i use ANTLR for parsing and generating ASTs.
currently i can parse some .js code into an AST - and therefore need to translate this AST into som kind of intermediate-representation that can be executed on a bytecode machine.
I have some experience writing compilers for statically typed languages, but im very much in doubt how to proceed from here since JS is a dynamically typed language.
If you can give me some good advices on how to proceed i would be gratefull!
Personally i think i have to make the bytecode-machine first and then make the IR fit this machine afterwards. Unfortunatly i cant really find any good tutorials on how to write a bytecode-machine.
PS. im familiar with following books on the topic :
"modern compiler implementation in Java (Appel)",
"Programming language processors in Java (Watt & Brown)",
"Language implementation patterns (Parr)"
Regards Sune
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您只想执行 javascript,则无需将 AST 转换为 IR,然后转换为(某些?)字节码,这也会迫使您执行字节码执行器。
为什么不只执行 javascript java“引擎”中的 AST?您可以将所有值存储为
Map
并在遍历 AST 时解释它们。新函数获取环境/上下文(新的Map<...>
)。如果您在当前上下文中找不到值,则必须求助于全局上下文 (=
Map
)。对于“动态”行为:如果您需要一个
double
进行加法,则只需使用以下命令将Object.toString()
值解析为double
标准方式(比这更动态的方式很难得到:)):If you only want to execute the javascript you do not need to transform the AST into IR and then into (some?) bytecode that would also force you to do a bytecode executer.
Why not just execute the javascript AST in a java "engine"? You can store all values as a
Map<String, Object>
and interpret them as you walk the AST. A new function get an environment/context (a newMap<...>
).If you cannot find a value in the current context you will have to fall back on the global context (=
Map
).For the "dynamic" behaviour: If you need an
double
for an addition you only parse theObject.toString()
value to andouble
using the standard way (more dynamic than that is hard to get :) ):