Skip to content

Instantly share code, notes, and snippets.

@FrankSpierings
Created September 5, 2021 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FrankSpierings/aff1fe42d10e1af4b7858ec7c65ffca4 to your computer and use it in GitHub Desktop.
Save FrankSpierings/aff1fe42d10e1af4b7858ec7c65ffca4 to your computer and use it in GitHub Desktop.
Shift-refactor playground
const { refactor } = require('shift-refactor');
const { commonMethods } = require('refactor-plugin-common');
const Shift = require('shift-ast');
const fs = require('fs');
const src = `
var a = "aap";
function foo() {
function bar() {
var b = "noot";
return b;
}
c = bar();
d = a + c;
return d;
}
function dead() {
var x = 1;
var y = 2;
return x + y * 2;
}
function noVariable() {
return "helloworld"
}
`
const $script = refactor(src, commonMethods);
function findParent(node, type) {
console.log('[+]' + node.type());
if (node.type() === type) {
return node;
}
if (node.parents().nodes.length === 0) {
return undefined;
}
else {
return findParent(node.parents(), type);
}
}
// Examples of stuff we can print as code.
$script('VariableDeclaration').map(n => console.log($script(n).print()))
$script('FunctionDeclaration').map(n => console.log($script(n).print()))
$script('ExpressionStatement').map(n => console.log($script(n).print()))
$script('ReturnStatement').map(n => console.log($script(n).print()))
// Find all variable delcaratiotions and
// find parent functions for these declarations.
var functions = $script('VariableDeclaration').map(n => findParent($script(n), 'FunctionDeclaration')).filter(n => n !== undefined);
// Print only functions with variable declarations
functions.map(n => console.log(n.print()));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment