This was a talk given at HTML5DevConf SF in 2015.
Ever wanted to write your own Browserify or Babel? Maybe have an idea for something new? This talk will get you started understanding how to use a JavaScript AST to transform and generate new code.
32. • How do you get a JavaScript AST?
• How do you use it?
• How do you transform it?
• Building a transpiler.
33. Parsing JavaScript
• Esprima - Fast, conservative. Parses to ESTree format.
• Acorn - Error tolerant. Parses to ESTree format.
• Shift - Most spec-compliant. Parses to Shift format.
34. ESTree Shift
• Community effort
• Wide tool support
• Somewhat backwards
compatible with
SpiderMonkey AST
• Shape Security product
• Limited tool support
• Not compatible with ESTree
• Cross platform
• First spec-based AST
vs
Standardized AST formats
35. Why ever use Shift?
• Shift was developed by Ariya Hidayat (Esprima), Michael Ficarra
(CoffeeScript, loads of ES tools), and several others.
• Shift was designed specifically for simpler and more efficient
transformation and analysis code.
• Shift creators still contribute to ESTree.
• When in doubt, use ESTree for the community.
• If ESTree causes problems, consider Shift.
42. How do you transform an AST?
import {parseScript} from 'shift-parser';
import codegen from 'shift-codegen';
let ast = parse('let a = 2;');
ast.
statements[0].
declaration.
declarators[0].
binding.name = 'b';
let newSource = codegen(ast);
43. OK, Let's build a transpiler.
I really really like Arrow Expressions, how 'bout you?
44. Test first: what are we expecting?
(() => { return 2 })()
If we run* the following in an ES5 environment
it will return
2
* transpile and eval()
76. import {parseScript} from 'shift-parser';
import reduce from 'shift-reducer';
import codegen from 'shift-codegen';
import transpiler from './transpiler';
let ast = parseScript(source);
var result = reduce(transpiler, ast);
var newSource = codegen(result);
console.log(newSource);
78. Analyze Transform
• Linting
• Complexity
• Auto Documentation
• Type Checking
• API Conformance
• Transpiling
• Code generation
• Preprocessing
• Refactoring
• Reformatting
What can you do with an AST?
79. "The worst mistake man ever
committed was treating
source code as text."
- John Stamos
Season 3, episode 20 of "Full House"
80. When have you ever typed this
function greet(target) {
}
without this?
81. Have you ever been concerned about this string?
function greet(target) {
}