Slide 1

Slide 1 text

HARNESSING THE POWER OF Abstract Syntax Trees

Slide 2

Slide 2 text

Parsers

Slide 3

Slide 3 text

console.log("UtahJS");

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

{ type: "Program", body: [ { type: "ExpressionStatement", expression: { type: "CallExpression", callee: { type: "MemberExpression", computed: false, object: { type: "Identifier", name: "console" }, property: { type: "Identifier", name: "log" } }, arguments: [ { type: "Literal", value: "UtahJS", raw: "\"UtahJS\"" } ] } } ] }

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

Acorn

Slide 8

Slide 8 text

Esprima

Slide 9

Slide 9 text

Espree

Slide 10

Slide 10 text

PARSING // generate an AST from a string of code espree.parse("console.log('UtahJS')");

Slide 11

Slide 11 text

PARSING // generate an AST from a string of code acorn.parse("console.log('UtahJS')");

Slide 12

Slide 12 text

PARSING ES6 // generate an AST from a string of code acorn.parse("console.log('UtahJS')", { ecmaVersion: 6 });

Slide 13

Slide 13 text

ASTS ARE EVERYWHERE

Slide 14

Slide 14 text

BUILD-TIME CODE TRANFORMATION ONE-OFF CODE MIGRATION CODE INSPECTION

Slide 15

Slide 15 text

CODE Tranformation

Slide 16

Slide 16 text

How many of you use babel?

Slide 17

Slide 17 text

No content

Slide 18

Slide 18 text

BABEL PLUGIN module.exports = function (Babel) { return new Babel.Plugin("plugin-example", { // visitor: { // "FunctionDeclaration": swapWithExpression // } }); };

Slide 19

Slide 19 text

BABEL PLUGIN module.exports = function (Babel) { return new Babel.Plugin("plugin-example", { visitor: { "FunctionDeclaration": swapWithExpression } }); };

Slide 20

Slide 20 text

GUTS function swapWithExpression(node, parent) { var id = node.id; // change the node type // node.type = "FunctionExpression"; // node.id = null; // return a variable declaration // return Babel.types.variableDeclaration("var", [ // Babel.types.variableDeclarator(id, node) // ]); }

Slide 21

Slide 21 text

GUTS function swapWithExpression(node, parent) { var id = node.id; // change the node type node.type = "FunctionExpression"; node.id = null; // return a variable declaration // return Babel.types.variableDeclaration("var", [ // Babel.types.variableDeclarator(id, node) // ]); }

Slide 22

Slide 22 text

GUTS function swapWithExpression(node, parent) { var id = node.id; // change the node type node.type = "FunctionExpression"; node.id = null; // return a variable declaration return Babel.types.variableDeclaration("var", [ Babel.types.variableDeclarator(id, node) ]); }

Slide 23

Slide 23 text

BABEL PLUGIN RESULTS // function declaration function help() {} // transformed to a function expression var help = function() {}

Slide 24

Slide 24 text

CODE Migration

Slide 25

Slide 25 text

No content

Slide 26

Slide 26 text

JSCODESHIFT EXAMPLE module.exports = function(fileInfo, api) { return api.jscodeshift(fileInfo.source) // .findVariableDeclarators('foo') // .renameTo('bar') // .toSource(); };

Slide 27

Slide 27 text

JSCODESHIFT EXAMPLE module.exports = function(fileInfo, api) { return api.jscodeshift(fileInfo.source) .findVariableDeclarators('foo') // .renameTo('bar') // .toSource(); };

Slide 28

Slide 28 text

JSCODESHIFT EXAMPLE module.exports = function(fileInfo, api) { return api.jscodeshift(fileInfo.source) .findVariableDeclarators('foo') .renameTo('bar') // .toSource(); };

Slide 29

Slide 29 text

JSCODESHIFT EXAMPLE module.exports = function(fileInfo, api) { return api.jscodeshift(fileInfo.source) .findVariableDeclarators('foo') .renameTo('bar') .toSource(); };

Slide 30

Slide 30 text

JSCODESHIFT RESULTS // this gets var foo = "UtahJS"; // transformed to var bar = "UtahJS"

Slide 31

Slide 31 text

CODE Inspection

Slide 32

Slide 32 text

No content

Slide 33

Slide 33 text

CUSTOM LINT RULES // lib/rules/no-class.js module.exports = function(context) { return { "ClassDeclaration": function(node) { context.report(node, "Your code has no class"); } } }

Slide 34

Slide 34 text

KNOW YOUR NODES

Slide 35

Slide 35 text

No content

Slide 36

Slide 36 text

AN AST GIVES YOU SUPER POWERS

Slide 37

Slide 37 text

No content

Slide 38

Slide 38 text

"Making easy things easy & hard things possible" - Learning Perl

Slide 39

Slide 39 text

JS AWARE git diff

Slide 40

Slide 40 text

console.log("UtahJS");

Slide 41

Slide 41 text

console.log("SomeOtherConf");

Slide 42

Slide 42 text

console.error("SomeOtherConf");

Slide 43

Slide 43 text

No content

Slide 44

Slide 44 text

No content

Slide 45

Slide 45 text

No content

Slide 46

Slide 46 text

git diff --raw | node compare.js

Slide 47

Slide 47 text

A BETTER DIFF // turn stdin into an array of lines var lines = fs.readFileSync('/dev/stdin').toString().split('\n');

Slide 48

Slide 48 text

A BETTER DIFF // lines now looks something like this [':100644 100644 9a0b08f... 0000000... M tree1.js']

Slide 49

Slide 49 text

A BETTER DIFF lines.map(function(line) { var parts = line.split(' '); // var file = parts.pop().split('\t'); // return [file[1], parts[2].slice(0, -3)]; });

Slide 50

Slide 50 text

A BETTER DIFF lines.map(function(line) { var parts = line.split(' '); var file = parts.pop().split('\t'); // return [file[1], parts[2].slice(0, -3)]; });

Slide 51

Slide 51 text

A BETTER DIFF lines.map(function(line) { var parts = line.split(' '); var file = parts.pop().split('\t'); return [file[1], parts[2].slice(0, -3)]; });

Slide 52

Slide 52 text

A BETTER DIFF // the key parts of our git diff [ [ "tree1.js", "9a0b08f"] ]

Slide 53

Slide 53 text

PARSING // generate an AST from a string of code espree.parse("console.log('UtahJS)");

Slide 54

Slide 54 text

.map(function(files) { var after = fs.readFileSync(files[0]); // var before = child_process.execSync("git show" + files[1]); // return { // filename: files[0], // before: espree.parse(before, options), // after: espree.parse(after, options) // }; })

Slide 55

Slide 55 text

.map(function(files) { var after = fs.readFileSync(files[0]); var before = child_process.execSync("git show" + files[1]); // return { // filename: files[0], // before: espree.parse(before, options), // after: espree.parse(after, options) // }; })

Slide 56

Slide 56 text

.map(function(files) { var after = fs.readFileSync(files[0]); var before = child_process.execSync("git show" + files[1]); return { filename: files[0], before: espree.parse(before, options), after: espree.parse(after, options) }; })

Slide 57

Slide 57 text

[{ filename: "trees1.js", before: { type: "Program", body: [Object] }, after: { type: "Program", body: [Object] } }]

Slide 58

Slide 58 text

FITS ON ONE SLIDE*

Slide 59

Slide 59 text

var lines = fs.readFileSync('/dev/stdin').toString().split('\n'); var trees = lines.map(function(line) { var parts = line.split(' '); var file = parts.pop().split('\t'); return [path.resolve(file[1]), parts[2].slice(0, -3)]; }).filter(function(files) { return files[0].indexOf('.js') > -1; }).map(function(files) { var after = fs.readFileSync(files[0]); var before = child_process.execSync("git show " + files[1]); return { filename: files[0], before: espree.parse(before, options), after: espree.parse(after, options) }; });

Slide 60

Slide 60 text

No content

Slide 61

Slide 61 text

No content

Slide 62

Slide 62 text

DIFFING THE TREES // let's see if something changed var different = deepEqual(treeBefore, treeAfter);

Slide 63

Slide 63 text

function deepEqual(a, b) { if (a === b) { return true; } if (!a || !b) { return false; } if (Array.isArray(a)) { return a.every(function(item, i) { return deepEqual(item, b[i]); }); } if (typeof a === 'object') { return Object.keys(a).every(function(key) { return deepEqual(a[key], b[key]); }); } return false; }

Slide 64

Slide 64 text

if (typeof a === 'object') { return Object.keys(a).every(function(key) { return deepEqual(a[key], b[key]); }); } return false;

Slide 65

Slide 65 text

if (typeof a === 'object') { var equal = Object.keys(a).every(function(key) { return deepEqual(a[key], b[key]); }); return equal; } return false;

Slide 66

Slide 66 text

if (typeof a === 'object') { // var equal = Object.keys(a).every(function(key) { // return deepEqual(a[key], b[key]); // }); if (!equal) { console.log('[' + a.type + '] => [' + b.type + ']'); } // return equal; } console.log('"' + a + '" => "' + b + '"'); // return false;

Slide 67

Slide 67 text

git diff --raw | node compare.js "log" => "error" [Identifier] => [Identifier] [MemberExpressio] => [MemberExpression] [CallExpression] => [CallExpression] [ExpressionStatement] => [ExpressionStatement] [Program] => [Program]

Slide 68

Slide 68 text

No content

Slide 69

Slide 69 text

No content

Slide 70

Slide 70 text

No content

Slide 71

Slide 71 text

I CAN'T PROCESS THIS TREE IN MY HEAD

Slide 72

Slide 72 text

export function buildHouse(lot, color, size, bedrooms) { clearLot(lot); let foundation = buildFoundation(size); let walls = buildWalls(bedrooms); let paintedWalls = paintWalls(color, walls); let roof = buildRoof(foundation, walls); let house = foundation + paintedWalls + roof; // house is all done right-away return house; }

Slide 73

Slide 73 text

function getPermits(callback) { setTimeout(callback, 1.0519e10); // 4 months because trees } export function buildHouse(lot, color, size, bedrooms, callback) { getPermits((permits) => { clearLot(permits, lot); let foundation = buildFoundation(size); let walls = buildWalls(bedrooms); let paintedWalls = paintWalls(color, walls); let roof = buildRoof(foundation, walls); let house = foundation + paintedWalls + roof; // house will be ready in about a year callback(house); }); }

Slide 74

Slide 74 text

No content

Slide 75

Slide 75 text

No content

Slide 76

Slide 76 text

OUR GOAL git diff --raw | node compare.js house.js 1. The exported `buildHouse` function output went from a return to a callback. 2. The private `getPermits` function was added.

Slide 77

Slide 77 text

AN ARRAY OF TREES [{ filename: "trees1.js", before: { type: "Program", body: [Object] }, after: { type: "Program", body: [Object] } }]

Slide 78

Slide 78 text

VISITING OUR TREES esrecurse.visit(diff.before, { // export function a() {} ExportNamedDeclaration: function(node) { /* ... */ }, // function a() {} FunctionDeclaration: function(node) { /* ... */ } });

Slide 79

Slide 79 text

INSPECTING FUNCTION DECLARATIONS function inspectFunction(node, visiblity) { return { name: node.id.name, // "buildHouse", // params: node.params.map(param => param.name), // ["lot", "color", ...] // visibility: visiblity || "private", // outputType: getOutputType(node) }; }

Slide 80

Slide 80 text

INSPECTING FUNCTION NODES function inspectFunction(node, visiblity) { return { name: node.id.name, // "buildHouse" params: node.params.map(param => param.name), // ["lot", "color", ...] // visibility: visiblity || "private", // outputType: getOutputType(node) }; }

Slide 81

Slide 81 text

INSPECTING FUNCTION DECLARATIONS function inspectFunction(node, visiblity) { return { name: node.id.name, // "buildHouse" params: node.params.map(param => param.name), // ["lot", "color", ...] visibility: visiblity || "private", // outputType: getOutputType(node) }; }

Slide 82

Slide 82 text

INSPECTING FUNCTION DECLARATIONS function inspectFunction(node, visiblity) { return { name: node.id.name, // "buildHouse" params: node.params.map(param => param.name), // ["lot", "color", ...] visibility: visiblity || "private", outputType: getOutputType(node) }; }

Slide 83

Slide 83 text

GETTING OUTPUT TYPE function getOutputType(node) { var params = node.params.map(param => param.name); // is there a callback param? var hasCallback = params[params.length - 1] === 'callback'; // is there a return in the immediate body? var hasReturn = node.body.some((node) => node.type === 'ReturnStatement'); // callback or return or '' return hasCallback ? 'callback' : (hasReturn ? 'return' : ''); }

Slide 84

Slide 84 text

THE ESSENCE OF A FUNCTION { name: "getPermits", visibility: "private", params: [ "callback" ], outputType: "callback" }

Slide 85

Slide 85 text

MORE COMPLEX REPRESENTATION [{ filename: "house.js", functions: { "getPermits": { after: { /* ... */ } }, "buildHouse": { before: { /* ... */ }, after: { /* ... */ } } }]

Slide 86

Slide 86 text

REDUCING COMPLEXITY function getReadableOutput(functions) { return Object.keys(functions).reduce(function(ouput, name, i) { var whatHappened = getWhatHappened(functions[name]); // var visibility = functions[name].after.visibility; // var message = `The ${visibility} ${name} function ${whatHappened}.\n` // return `${output}${i + 1}. ${message}`; }, ""); }

Slide 87

Slide 87 text

HUMAN READABLE FTW! function getWhatHappened(func) { if (!func.before) { return "was added" } if (!func.after) { return "was removed" } if (func.before.outputType !== func.after.outputType) { return "output went from a " + func.before.outputType + " to a " + func.after.outputType; } }

Slide 88

Slide 88 text

`1. The exported `buildHouse` function output went from a return to a callback. 2. The private `getPermits` function was added.`

Slide 89

Slide 89 text

UNROLLING OUR ARRAY .map(function(diff) { return diff.filename + "\n" + getReadableOutput(diff.functions); }).join("\n");

Slide 90

Slide 90 text

A HAPPY ENDING git diff --raw | node compare.js house.js 1. The exported `buildHouse` function output went from a return to a callback. 2. The private `getPermits` function was added.

Slide 91

Slide 91 text

TREES ARE SUPER POWERFUL

Slide 92

Slide 92 text

THE END

Slide 93

Slide 93 text

No content