Browse files

function refs

  • Loading branch information...
1 parent 7a5118e commit fa0665fe46077726ecc7c3f6e83f684101e71a8b @substack committed Nov 5, 2012
Showing with 39 additions and 9 deletions.
  1. +6 −0 example/run.js
  2. +29 −8 index.js
  3. +4 −1 source.js
View
6 example/run.js
@@ -0,0 +1,6 @@
+var fs = require('fs');
+var scoper = require('../');
+
+var src = fs.readFileSync(process.argv[2], 'utf8');
+var c = Function('return ' + scoper(src))();
+console.dir(c);
View
37 index.js
@@ -1,22 +1,33 @@
var falafel = require('falafel');
module.exports = function (src) {
- var scopeName = '__' + (Math.pow(16, 8) * Math.random()).toString(16);
+ var names = [ 'scope', 'fn' ].reduce(function (acc, name) {
+ acc[name] = '__' + (Math.pow(16, 8) * Math.random()).toString(16);
+ return acc;
+ }, {});
+
var scope = {};
+ var fns = {};
- var out = [ rewriteVars, rewriteIds ].reduce(function (src, fn) {
- return String(falafel(src, fn));
- }, src);
+ var out = [ rewriteVars, rewriteIds, normalizeFns ]
+ .reduce(function (src, fn) {
+ return String(falafel(src, fn));
+ }, src)
+ ;
- return 'function () {\n'
- + 'var ' + scopeName + '='
+ return '(function () {\n'
+ + 'var ' + names.scope + '='
+ JSON.stringify(Object.keys(scope).reduce(function (acc, key) {
acc[key] = {};
return acc;
}, {}))
+ ';\n'
+ + 'var ' + names.fn + '={'
+ + Object.keys(fns).map(function (id) {
+ return JSON.stringify(id) + ':' + fns[id]
+ }, '').join(',\n') + '};\n'
+ out
- + ';return {scope:' + scopeName + '}}'
+ + ';return {scope:' + names.scope + ',fn:' + names.fn + '}})()'
;
function rewriteVars (node) {
@@ -33,7 +44,17 @@ module.exports = function (src) {
function rewriteIds (node) {
if (node.type === 'Identifier' && !isFunction(node.parent)) {
var id = JSON.stringify(lookup(node));
- node.update(scopeName + '[' + id + '].' + node.name);
+ node.update(names.scope + '[' + id + '].' + node.name);
+ }
+ }
+
+ function normalizeFns (node) {
+ if (isFunction(node)) {
+ var id = idOf(node);
+ fns[id] = node.source();
+ node.body.update(
+ '{return ' + names.fn + '[' + JSON.stringify(id) + ']()}'
+ );
}
}
View
5 source.js
@@ -3,11 +3,14 @@ var x = 5;
function foo () {
var y = x + 100;
- (function bar () {
+ return (function bar () {
var z = 6;
var f = function () {
var q = y * 10;
var x = z + 2;
};
+ return f(z);
})();
}
+
+console.log(foo(32));

0 comments on commit fa0665f

Please sign in to comment.