Skip to content

Commit

Permalink
Use the parent node given by estraverse.
Browse files Browse the repository at this point in the history
Doing so avoids having to maintain a separate stack of our own in order
to achieve the same thing.
  • Loading branch information
null-a committed Jan 25, 2016
1 parent 0b149bf commit 055919e
Showing 1 changed file with 6 additions and 12 deletions.
18 changes: 6 additions & 12 deletions src/transforms/freevars.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,26 @@ var makeGensym = require('../util').makeGensym;
var genid = null;
var boundVarsStack = null;
var freeVarsStack = null;
var nodeStack = null;

var literalIdentifiers = {
undefined: true,
NaN: true,
Infinity: true
};

function identifierIsVar(node) {
function identifierIsVar(node, parent) {
// esprima represents some special literals as Identifer nodes; skip those
if (literalIdentifiers[node.name]) return false;
// exprima also represents non-computed object member access with an
// Identifer node, so skip those as well.
var ntop = nodeStack[nodeStack.length - 1];
if (ntop.type === Syntax.MemberExpression && !ntop.computed &&
node === ntop.property) return false;
if (parent.type === Syntax.MemberExpression && !parent.computed &&
node === parent.property) return false;
// Property keys in object literal expressions are also Identifer nodes
if (ntop.type === Syntax.Property && node === ntop.key) return false;
if (parent.type === Syntax.Property && node === parent.key) return false;
return true;
}

function enter(node) {
function enter(node, parent) {
switch (node.type) {
case Syntax.FunctionExpression:
// Bind the formal parameters of the function
Expand All @@ -54,15 +52,14 @@ function enter(node) {
boundVarsStack[boundVarsStack.length - 1][node.id.name] = true;
break;
case Syntax.Identifier:
if (boundVarsStack.length > 0 && identifierIsVar(node)) {
if (boundVarsStack.length > 0 && identifierIsVar(node, parent)) {
// If the Identifier isn't already bound, then it's a free var
if (!boundVarsStack[boundVarsStack.length - 1][node.name])
freeVarsStack[freeVarsStack.length - 1][node.name] = true;
}
break;
default:
}
nodeStack.push(node);
}

function exit(node) {
Expand Down Expand Up @@ -93,18 +90,15 @@ function exit(node) {
outerFreeVars[name] = true;
}
}
nodeStack.pop();
return wrappedFn;
default:
}
nodeStack.pop();
}

function freevarsMain(node) {
genid = makeGensym();
boundVarsStack = [];
freeVarsStack = [];
nodeStack = [];

return replace(node, { enter: enter, leave: exit });
}
Expand Down

0 comments on commit 055919e

Please sign in to comment.