diff options
Diffstat (limited to 'lib/ast.js')
-rw-r--r-- | lib/ast.js | 41 |
1 files changed, 40 insertions, 1 deletions
@@ -248,7 +248,46 @@ var AST_Scope = DEFNODE("Scope", "directives variables functions uses_with uses_ }, AST_Block); var AST_Toplevel = DEFNODE("Toplevel", "globals", { - $documentation: "The toplevel scope" + $documentation: "The toplevel scope", + wrap_commonjs: function(name, export_all) { + var self = this; + if (export_all) { + self.figure_out_scope(); + var to_export = []; + self.walk(new TreeWalker(function(node){ + if (node instanceof AST_SymbolDeclaration && node.definition().global) { + to_export.push(node.name); + } + })); + } + var wrapped_tl = "(function(exports, global){ global['" + name + "'] = exports; '$ORIG'; '$EXPORTS'; }({}, (function(){return this}())))"; + wrapped_tl = parse(wrapped_tl); + wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){ + if (node instanceof AST_SimpleStatement) { + node = node.body; + if (node instanceof AST_String) switch (node.getValue()) { + case "$ORIG": + return new AST_BlockStatement(self); + case "$EXPORTS": + var body = []; + to_export.forEach(function(name){ + body.push(new AST_SimpleStatement({ + body: new AST_Assign({ + left: new AST_Sub({ + expression: new AST_SymbolRef({ name: "exports" }), + property: new AST_String({ value: name }), + }), + operator: "=", + right: new AST_SymbolRef({ name: name }), + }), + })); + }); + return new AST_BlockStatement({ body: body }); + } + } + })); + return wrapped_tl; + } }, AST_Scope); var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments", { |