Slide 1

Slide 1 text

ASTs

Slide 2

Slide 2 text

We want to learn more about the internals of tools we use everyday

Slide 3

Slide 3 text

Abstract syntax trees (AST) are at the core of all of these tools

Slide 4

Slide 4 text

… but what are abstract syntax trees? … how do they work in JavaScript? … how can we use them effectively?

Slide 5

Slide 5 text

const conference = "JavaZone";

Slide 6

Slide 6 text

const conference = "JavaZone"; Lexical analysis (lexer)

Slide 7

Slide 7 text

const conference = "JavaZone"; keyword Lexical analysis (lexer)

Slide 8

Slide 8 text

const conference = "JavaZone"; keyword identifier Lexical analysis (lexer)

Slide 9

Slide 9 text

const conference = "JavaZone"; keyword identifier punctuator string punctuator Lexical analysis (lexer)

Slide 10

Slide 10 text

[ { type: 'Keyword', value: 'const' }, { type: 'Identifier', value: 'conference' }, { type: 'Punctuator', value: '=' }, { type: 'Numeric', value: 'JavaZone' }, { type: 'Punctuator', value: ';' } ] const conference = "JavaZone";

Slide 11

Slide 11 text

Syntax analysis (parser) const conference = "JavaZone"; [ { type: 'Keyword', value: 'const' }, { type: 'Identifier', value: 'conference' }, { type: 'Punctuator', value: '=' }, { type: 'Numeric', value: 'JavaZone' }, { type: 'Punctuator', value: ';' } ]

Slide 12

Slide 12 text

const conference = "JavaZone"; Syntax analysis (parser) const conference = "JavaZone"; Program

Slide 13

Slide 13 text

Syntax analysis (parser) const conference = "JavaZone"; VariableDeclaration Program

Slide 14

Slide 14 text

Syntax analysis (parser) const conference = "JavaZone"; VariableDeclaration VariableDeclarator Program Kind

Slide 15

Slide 15 text

const conference = "JavaZone"; VariableDeclaration VariableDeclarator Identifier Literal Program Kind Syntax analysis (parser)

Slide 16

Slide 16 text

const conference = "JavaZone"; Program VariableDeclaration VariableDeclarator const Identifier Literal conference "JavaZone"

Slide 17

Slide 17 text

No content

Slide 18

Slide 18 text

No content

Slide 19

Slide 19 text

No content

Slide 20

Slide 20 text

No content

Slide 21

Slide 21 text

Okey, so now we know what an AST is

Slide 22

Slide 22 text

… but what can we do with it? Okey, so now we know what an AST is

Slide 23

Slide 23 text

Use-cases Static analysis Syntax highlighting Code completion Minification Compile-time optimisations Source maps Code coverage Transpilers Code formatter One-time code transformations Build-time code transformations

Slide 24

Slide 24 text

No content

Slide 25

Slide 25 text

Static analysis

Slide 26

Slide 26 text

module.exports = { }; Creating our own ESLint plugin that disallows default exports export default myFunction

Slide 27

Slide 27 text

module.exports = { meta: {}, create: function(context) { return { }; } }; ESLint helpers Creating our own ESLint plugin that disallows default exports

Slide 28

Slide 28 text

Node type module.exports = { meta: {}, create: function(context) { return { ExportDefaultDeclaration: function(node) { } }; } }; (we’ll talk about how we find these later) ESLint calls this function to “visit” the node while traversing down the AST Creating our own ESLint plugin that disallows default exports

Slide 29

Slide 29 text

module.exports = { meta: {}, create: function(context) { return { ExportDefaultDeclaration: function(node) { context.report(node, 'Default exports are not allowed.'); } }; } }; Publishes a warning or error Creating our own ESLint plugin that disallows default exports

Slide 30

Slide 30 text

create: function(context) { const dependencies = new Set(); return { ImportDeclaration: function(node) { dependencies.add(node.source.value); }, 'Program:exit': function() { failIfTooManyDeps(dependencies, context); } } } ESLint example: fail if too many dependencies

Slide 31

Slide 31 text

You’ll see the visitor pattern everywhere

Slide 32

Slide 32 text

Build-time transformation

Slide 33

Slide 33 text

No content

Slide 34

Slide 34 text

No content

Slide 35

Slide 35 text

No content

Slide 36

Slide 36 text

No content

Slide 37

Slide 37 text

No content

Slide 38

Slide 38 text

No content

Slide 39

Slide 39 text

No content

Slide 40

Slide 40 text

No content

Slide 41

Slide 41 text

No content

Slide 42

Slide 42 text

WHY!?!?

Slide 43

Slide 43 text

WHY!?!? Legacy, JavaScript is evolving, tools have different needs

Slide 44

Slide 44 text

WHY!?!? “NOTE: Only 'stage 4' (finalized) ECMAScript features are being implemented by Acorn.” “[Babylon has] support for experimental language proposals” "Unfortunately, ESLint relies on more than just the AST to do its job. It relies on […] tokens and comment attachment features to get a complete picture of the source code." “Experimental support for JSX”

Slide 45

Slide 45 text

No content

Slide 46

Slide 46 text

Why isn’t there an AST spec?

Slide 47

Slide 47 text

No content

Slide 48

Slide 48 text

Experimental features Early spec stages JSX, TypeScript, etc Not everyone agrees

Slide 49

Slide 49 text

So … how do we solve this problem?

Slide 50

Slide 50 text

No content

Slide 51

Slide 51 text

No content

Slide 52

Slide 52 text

No content

Slide 53

Slide 53 text

No content

Slide 54

Slide 54 text

Transform AST

Slide 55

Slide 55 text

No content

Slide 56

Slide 56 text

No content

Slide 57

Slide 57 text

Specify parser, then transform ASTs Several almost compatible ASTs

Slide 58

Slide 58 text

However, it's not easy to get the best of both worlds

Slide 59

Slide 59 text

However, it's not easy to get the best of both worlds Only one can parse

Slide 60

Slide 60 text

Working with AST Explorer

Slide 61

Slide 61 text

No content

Slide 62

Slide 62 text

No content

Slide 63

Slide 63 text

No content

Slide 64

Slide 64 text

No content

Slide 65

Slide 65 text

No content

Slide 66

Slide 66 text

Codemods One-time transformation

Slide 67

Slide 67 text

Codemods Using AST-to-AST transformations to enable large-scale, incremental changes

Slide 68

Slide 68 text

Some of the changes we’ve done over time: AMD CommonJS ES6 modules var const / let Change test lib (Mocha to Jest) and assertion lib (e.g. to.be() to toBe()) Remove unused code, e.g. unused variables and functions Object.assign Object spread Introduce support for I18N

Slide 69

Slide 69 text

Some of these might be easy to search-and-replace, but most of them are not

Slide 70

Slide 70 text

Writing a codemod

Slide 71

Slide 71 text

Object.assign to Object spread

Slide 72

Slide 72 text

{ type: 'dashboard', id: indexId, ...additionalOptions } Object.assign( { type: 'dashboard', id: indexId }, additionalOptions ); Object.assign to Object spread

Slide 73

Slide 73 text

Object.assign( {}, query, hashedQuery ); Object.assign to Object spread { ...query, ...hashedQuery };

Slide 74

Slide 74 text

Object.assign( myVar, { type: 'dashboard', id: indexId } ); Object.assign to Object spread Don’t change as it’s mutating myVar

Slide 75

Slide 75 text

// most parsers: visitor pattern const ast = parse(file.source); traverse(ast, { Identifier: function(node) { // do something with node } }); const ast = j(file.source); ast .find(j.Identifier) .forEach(function(path) { // do something with path }); // jscodeshift: fluent interface

Slide 76

Slide 76 text

const ast = j(file.source); ast .find(j.Identifier) .forEach(function(path) { // do something with path }); Collection: Similar to jQuery's $(...) APIs to find, filter, map and remove AST nodes.

Slide 77

Slide 77 text

Wraps an AST node and adds helpers to simplify working with it. Path: Collection: Similar to jQuery's $(...) APIs to find, filter, map and remove AST nodes. const ast = j(file.source); ast .find(j.Identifier) .forEach(function(path) { // do something with path });

Slide 78

Slide 78 text

Let’s look at some code in slides (I’m not tough enough to live code this)

Slide 79

Slide 79 text

Object.assign({}, obj);

Slide 80

Slide 80 text

Object.assign({}, obj); AST { "type": "CallExpression", "callee": { "type": "MemberExpression", "object": { "type": "Identifier", "name": "Object" }, "property": { "type": "Identifier", "name": "assign" } }, "arguments": [ { "type": "ObjectExpression", "properties": [] }, { "type": "Identifier", "name": "obj" } ] }

Slide 81

Slide 81 text

.find( ); Object.assign({}, obj); AST { "type": "CallExpression", "callee": { "type": "MemberExpression", "object": { "type": "Identifier", "name": "Object" }, "property": { "type": "Identifier", "name": "assign" } }, "arguments": [ { "type": "ObjectExpression", "properties": [] }, { "type": "Identifier", "name": "obj" } ] }

Slide 82

Slide 82 text

.find(j.CallExpression ); Object.assign({}, obj); AST { "type": "CallExpression", "callee": { "type": "MemberExpression", "object": { "type": "Identifier", "name": "Object" }, "property": { "type": "Identifier", "name": "assign" } }, "arguments": [ { "type": "ObjectExpression", "properties": [] }, { "type": "Identifier", "name": "obj" } ] }

Slide 83

Slide 83 text

Object.assign({}, obj); .find(j.CallExpression, { callee: { type: "MemberExpression", object: { name: "Object" }, property: { name: "assign" } } }); AST { "type": "CallExpression", "callee": { "type": "MemberExpression", "object": { "type": "Identifier", "name": "Object" }, "property": { "type": "Identifier", "name": "assign" } }, "arguments": [ { "type": "ObjectExpression", "properties": [] }, { "type": "Identifier", "name": "obj" } ] }

Slide 84

Slide 84 text

Object.assign({}, obj); test(); Object.assign( {}, query, hashedQuery ); Object.keys({ hello: 'world' }); console.log('hello world'); export default function transformer(file, api) { const j = api.jscodeshift; const ast = j(file.source); return ast.toSource(); } Input Transform

Slide 85

Slide 85 text

Object.assign({}, obj); test(); Object.assign( {}, query, hashedQuery ); Object.keys({ hello: 'world' }); console.log('hello world'); export default function transformer(file, api) { const j = api.jscodeshift; const ast = j(file.source); ast .find(j.CallExpression, { callee: { type: "MemberExpression", object: { name: "Object" }, property: { name: "assign" } } }) return ast.toSource(); } Input Transform

Slide 86

Slide 86 text

Object.assign({}, obj); test(); Object.assign( {}, query, hashedQuery ); Object.keys({ hello: 'world' }); console.log('hello world'); export default function transformer(file, api) { const j = api.jscodeshift; const ast = j(file.source); ast .find(j.CallExpression, { callee: { type: "MemberExpression", object: { name: "Object" }, property: { name: "assign" } } }) .forEach(path => transformToObject(path)); return ast.toSource(); } Input Transform

Slide 87

Slide 87 text

{ "type": "CallExpression", "callee": { "type": "MemberExpression", "object": { "type": "Identifier", "name": "Object" }, "property": { "type": "Identifier", "name": "assign" } }, "arguments": [ { "type": "ObjectExpression", "properties": [] }, { "type": "Identifier", "name": "obj" } ] } function transformToObject(path) { } Wraps the AST

Slide 88

Slide 88 text

{ "type": "CallExpression", "callee": { "type": "MemberExpression", "object": { "type": "Identifier", "name": "Object" }, "property": { "type": "Identifier", "name": "assign" } }, "arguments": [ { "type": "ObjectExpression", "properties": [] }, { "type": "Identifier", "name": "obj" } ] } function transformToObject(path) { const assignCall = path.value; }

Slide 89

Slide 89 text

{ "type": "CallExpression", "callee": { "type": "MemberExpression", "object": { "type": "Identifier", "name": "Object" }, "property": { "type": "Identifier", "name": "assign" } }, "arguments": [ { "type": "ObjectExpression", "properties": [] }, { "type": "Identifier", "name": "obj" } ] } function transformToObject(path) { const assignCall = path.value; const args = assignCall.arguments; }

Slide 90

Slide 90 text

function transformToObject(path) { const assignCall = path.value; const args = assignCall.arguments; const newProps = createObjectProperties(args); }

Slide 91

Slide 91 text

function transformToObject(path) { const assignCall = path.value; const args = assignCall.arguments; const newProps = createObjectProperties(args); path.replace( j.objectExpression(newProps) ); } Builders to generate AST nodes Replace Object.assign call with an object expression j.identifier("name") j.memberExpression(j.identifier("foo"), j.identifier("bar")) j.objectExpression([ j.property("init", j.literal("key"), j.literal("value")) ]) j.callExpression( j.identifier("foo"), [j.identifier("bar")] ) ...

Slide 92

Slide 92 text

No content

Slide 93

Slide 93 text

No content

Slide 94

Slide 94 text

Then I copy the transform into a local file and run it on the full codebase (and fix all the edge-cases)

Slide 95

Slide 95 text

The goal isn't always to solve 100% of the problems with this

Slide 96

Slide 96 text

if (isStopped) { return
} if (isStopped) { return
Stopped
} Introducing I18N using React-intl and jscodeshift

Slide 97

Slide 97 text

{ name } }} />
Hello { name }
Introducing I18N using React-intl and jscodeshift

Slide 98

Slide 98 text

Took us a couple of days on a 30k+ line codebase to solve 80% of the problems

Slide 99

Slide 99 text

Interesting use-cases: Libraries can include transforms that fix breaking changes, e.g. React deprecating PropTypes Transforms for switching test libraries, e.g. moving from Mocha to Jest Pre-built codemods for moving to ES6+ features, e.g. arrow functions and const/let

Slide 100

Slide 100 text

No content

Slide 101

Slide 101 text

No content