Permalink
Browse files

Added experimental compiler

  • Loading branch information...
1 parent 1cfb9f0 commit 486116be7cfe6999a65598a42066a8e15fc32d06 @zaach committed Mar 30, 2011
View
@@ -0,0 +1,44 @@
+
+var protoParser = require("./experimental/parser").parser,
+ js = require("./js"),
+ nodes = require("./js/nodes"),
+ codegen = require("./js/codegen"),
+ experimentalNodes = require("./experimental/nodes"),
+ experimentalCodegen = require("./experimental/codegen");
+
+function Compiler () {
+ var constructors = {},
+ prototypes = {};
+
+ // Define AST nodes
+ var def = nodes.defineNodes(prototypes, constructors);
+ experimentalNodes.defineNodes(prototypes, constructors, def);
+
+ // extend nodes with JavaScript code generation methods
+ codegen.extend(prototypes);
+ experimentalCodegen.extend(prototypes);
+
+ this.Parser = js.baseParser(protoParser, constructors, prototypes);
+ this.parser = new this.Parser();
+}
+
+Compiler.prototype = js.Compiler.prototype;
+
+exports.Compiler = Compiler;
+
+// Convienience API
+exports.parse = function (source) {
+ return new Compiler().parse(source);
+};
+
+exports.toJS = function (ast) {
+ var s = ast.toJS(0);
+ //print(s);
+ return s;
+};
+
+exports.compile = function (source) {
+ var s = new Compiler.parse(source).toJS(0);
+ return s;
+};
+
@@ -0,0 +1,32 @@
+
+var indentChar = ' '; //4 spaces
+
+function idt (lvl) {
+ return Array(lvl+1).join(indentChar);
+}
+
+var codegens = exports.nodes = {
+ 'BlockCallExpr': function BlockCallExpr_codegen (lvl) {
+ return this.children[0].toJS(lvl);
+ },
+ 'BlockArg': function BlockArg_codegen (lvl) {
+ return 'function ('
+ +this.children[0].toJS() + ') '
+ +'{\n'+idt(lvl)+genStmts(this.children.slice(1), lvl) +'\n'+idt(lvl-1)+'}';
+ },
+ 'BlockParamDecl': function BlockParamDecl_codegen (lvl) {
+ return this.children.map(function(node){return node.toJS(lvl)}).join(', ');
+ },
+};
+
+// convenience function for generating a list of statements
+function genStmts (nodes, lvl) {
+ return nodes.map(function(node){return node.blockgen(lvl)}).join('\n'+idt(lvl));
+}
+// Extend the node prototypes to include code generation functions
+exports.extend = function extend (protos) {
+ var type;
+ for (type in codegens) {
+ protos[type].toJS = codegens[type];
+ }
+};
Oops, something went wrong.

0 comments on commit 486116b

Please sign in to comment.