开发者

Java-based interpreter for JavaScript

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 开发者_如何学JAVAcant 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


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 new Map<...>).

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 the Object.toString() value to an double using the standard way (more dynamic than that is hard to get :) ):

String value = contextMap.get(key); 
Double dvalue = Double.parseDouble(value.toString());
....
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜