Skip to content

Commit

Permalink
Got initial Program detection working
Browse files Browse the repository at this point in the history
  • Loading branch information
crutchcorn committed May 3, 2020
1 parent 8b3dbc2 commit a0ff8aa
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 24 deletions.
76 changes: 52 additions & 24 deletions plugin/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,37 +2,65 @@ const looksLike = require('./looks-like');
const t = require('@babel/types');
const { default: traverse } = require('@babel/traverse');

/**
* The "Map" of if the "./proxy.js" code should be injected to the top of the Program
*/
const Programs = new WeakMap();

module.exports = () => {
return {
name: 'willMutate',
visitor: {
ExpressionStatement(path) {
const isFunc = looksLike(path, {
node: {
type: 'ExpressionStatement',
expression: {
callee: {
name: '$shouldNotMutate',
},
},
},
});
/**
* We need to traverse the "Program" so we can know if we need to inject
* the Proxy handler or not.
*/
Program: {
enter(programPath) {
traverse(programPath.node, {
noScope: true,
enter(path) {
/**
* Look for all $shouldNotMutate functions
*/
if (path.node.type === 'ExpressionStatement') {
const isFunc = looksLike(path, {
node: {
type: 'ExpressionStatement',
expression: {
callee: {
name: '$shouldNotMutate',
},
},
},
});

if (!isFunc) return;
if (!isFunc) return;

// Treat the function as a "decorator" for a function. AKA get the body
const functionNodePath = path.getSibling(path.key + 1);
Programs.set(programPath.node, true);

traverse(functionNodePath.node, {
noScope: true,
enter(path) {
if (path.node.type === 'BlockStatement') {
console.log('HELLO 2');
// debugger;
}
},
});

// Treat the function as a "decorator" for a function. AKA get the function immediately
// After the function itself
const functionNodePath = path.getSibling(path.key + 1);

// Traverse the path to get the "BlockStatement" so we can mutate the code on it's own
traverse(functionNodePath.node, {
noScope: true,
enter(path) {
if (path.node.type === 'BlockStatement') {
console.log('HELLO 2');
// debugger;
}
},
});
}
},
});
},
exit(programPath) {
const val = Programs.get(programPath.node);
console.log('PLEASE ONLY RUN ONCE', val);
},
},
},
};
Expand Down
3 changes: 3 additions & 0 deletions src/poop.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ function bar(poop) {
poop.prop = 'Test';
}

/**
* This does not currently work
*/
$shouldNotMutate(poop);
const pizza = a => console.log(a);

Expand Down

0 comments on commit a0ff8aa

Please sign in to comment.