3 ms·
Compiling a single language into JavaScript source code as well as C or C++ is going to be one hell of a trick. I think it'll be very difficult to keep the sema
by jashkenas 16y ago
Compiling a single language into JavaScript source code as well as C or C++ is going to be one hell of a trick. I think it'll be very difficult to keep the semantics the same, without resorting to running the equivalent of a JavaScript interpreter inside of your C++, but I wish you the best of luck with it.
If you'd like to discuss the implementation, feel free to drop by #coffeescript on freenode. But to give you the rough outline -- the compiler is made up of (in order), a Lexer, Rewriter, Parser, and AST of Nodes. The lexer creates the tokens, the rewriter rewrites the stream of tokens, disambiguating parses and allowing for optional syntax, the parser generates the AST of nodes, and then "compile()" is called on the root node, and walks down the tree, compiling the JavaScript string recursively.
For the parser, I'm using the excellent Jison parser generator for JavaScript, in LALR(1) mode. The only really unorthodox part of this is the Rewriter. It's not kosher to munge a token stream before parsing it -- but it's removed a ton of complexity from the grammar to not ever have to handle the syntactical edge cases, and to have them resolved in advance. All of the source is annotated, so here's some links:
* Jison: http://github.com/zaach/jison http://github.com/zaach/jison
* Lexer: http://jashkenas.github.com/coffee-script/documentation/docs/lexer.html http://jashkenas.github.com/coffee-script/documentation/docs...
* Rewriter: http://jashkenas.github.com/coffee-script/documentation/docs/rewriter.html http://jashkenas.github.com/coffee-script/documentation/docs...
* Grammar: http://jashkenas.github.com/coffee-script/documentation/docs/grammar.html http://jashkenas.github.com/coffee-script/documentation/docs...
- endergen 16y agoYou are totally correct about the C/C++ generation not being easy if I go for making the whole language be elegantly compilable. I was thinking more of a subset, where you can mark a module or function(Not sure about the granularity) and it would raise a compile error if it doesn't maintain semantics that work elegantly in both Javascript and C/C++. It's really to allow Javascript programmers to not have to learn C/C++ and be able to accelerate their server side code (For say large image, or file processing. Or just expensive calculations like Pathfinding or Search-Space type stuff.) Of course it only works elegantly for server side, but it would be future proof for say using Native Client on the client side when or if it becomes available. Thanks for the pointers, I remember now finding those implementation details when I leafed through your code a while back. I'll check out the freenode channel when I get a chance.