SlideShare uma empresa Scribd logo
1 de 40
AST (Abstract Syntax Tree) 
The only true tool for building JavaScript
Source maps 
Epic win in debugging
Source maps – epic win in debugging
Source maps – epic win in debugging
Builders 
Epic fail in debugging
Builders – epic fail in debugging 
umdify: 
// UMD definition 
output += '(function(root, factory) {n'; 
output += ' if (typeof define === "function" && define.amd) {n'; 
output += ' define([' + depNames.join(', ') + '], factory);n'; 
output += ' } else if (typeof exports === "object") {n'; 
output += ' module.exports = factory(require);n'; 
…
Builders – epic fail in debugging 
grunt-amd-wrap: 
var srcText = grunt.file.read(file.src[0]); 
var destText = amdWrap(srcText);
Builders – epic fail in debugging 
gulp-concat: 
buffer.push(file.contents); 
… 
var joinedContents = Buffer.concat(buffer);
Builders – epic fail in debugging 
universal-transformer: 
function transform(srcText) { 
return 'var answer = 42;'; 
}
Your code is not a string 
It has a soul
Your code has a soul 
// Life, Universe, and Everything 
var answer = 6 * 7;
Your code has a soul 
// Life, Universe, and Everything 
var answer = 6 * 7; 
'// Life, Universe and 
Everythingnvar answer 
= 6 * 7;'
Your code has a soul 
// Life, Universe, and Everything 
var answer = 6 * 7; 
[ 
{ type: "Keyword", value: "var" }, 
{ type: "Identifier", value: "answer" }, 
{ type: "Punctuator", value: "=" }, 
{ type: "Numeric", value: "6" }, 
{ type: "Punctuator", value: "*" }, 
{ type: "Numeric", value: "7" }, 
{ type: "Punctuator", value: ";" } 
]
Your code has a soul 
[ 
{ type: "Keyword", value: "var" }, 
{ type: "Identifier", value: "answer" }, 
{ type: "Punctuator", value: "=" }, 
{ type: "Numeric", value: "6" }, 
{ type: "Punctuator", value: "*" }, 
{ type: "Numeric", value: "7" }, 
{ type: "Punctuator", value: ";" } 
] 
{ 
type: "Program", 
body: [{ 
type: "VariableDeclaration", 
declarations: [{ 
type: "VariableDeclarator", 
id: {type: "Identifier", name: "answer"}, 
init: { 
type: "BinaryExpression", 
operator: "*", 
left: {type: "Literal", value: 6}, 
right: {type: "Literal", value: 7} 
} 
}], 
kind: "var" 
}] 
}
Your code has a soul 
{ 
type: "Program", 
body: [{ 
type: "VariableDeclaration", 
declarations: [{ 
type: "VariableDeclarator", 
id: {type: "Identifier", name: "answer"}, 
init: { 
type: "BinaryExpression", 
operator: "*", 
left: {type: "Literal", value: 6}, 
right: {type: "Literal", value: 7} 
} 
}], 
kind: "var" 
}] 
} 
Program 
VariableDeclaration 
VariableDeclarator 
Identifier(“answer”) BinaryExpression(*) 
Literal(6) Literal(7)
Your code has a soul 
// Life, Universe, and Everything 
var answer = 6 * 7; Program 
VariableDeclaration 
VariableDeclarator 
Identifier(“answer”) BinaryExpression(*) 
Literal(6) Literal(7)
Code tools 
How can we work with code AST?
Parsing 
• JavaScript 
• SpiderMonkey: Reflect.parse – Mozilla's Parser API 
• Esprima – most popular ECMAScript parser in JS 
• Acorn – faster alternative ECMAScript parser in JS 
• UglifyJS – has own parser with custom AST format 
• Traceur – has ES6 parser that can be used separately as well 
• … (as a lot of language tools do) … 
• CoffeeScript 
• CoffeeScriptRedux – rewrite of CS compiler that internally uses CS AST with conversion to JS 
AST 
• JSX 
• esprima-fb – Facebook's fork of Esprima Harmony branch 
• jsx-esprima – es* tools based JSX to JS AST transpiler
Parsing 
acorn.parse('var answer = 6 * 7;', {locations: true}); 
// In each node. 
loc: { 
start: { 
line: 2, 
column: 0 
}, 
end: { 
line: 2, 
column: 19 
} 
}
Linting
Querying 
var found; 
estraverse.traverse(tree, { 
enter: function (node) { 
if (node.type === 'Identifier' && node.name[0] === '_') { 
found = node; 
return estraverse.VisitorOption.Break; 
} 
} 
})
Querying 
require('grasp-equery') 
.query('if ($cond) return $yes; else return $no;', ast)
Querying 
require('grasp-squery') 
.query('if[then=return][else=return]', ast)
Constructing 
{ 
type: "Program", 
body: [{ 
type: "VariableDeclaration", 
declarations: [{ 
type: "VariableDeclarator", 
id: {type: "Identifier", name: "answer"}, 
init: { 
type: "BinaryExpression", 
operator: "*", 
left: {type: "Literal", value: 6}, 
right: {type: "Literal", value: 7} 
} 
}], 
kind: "var" 
}] 
}
Constructing 
var b = require('ast-types').builders; 
b.variableDeclaration('var', [ 
b.variableDeclarator( 
b.identifier('answer'), 
b.binaryExpression( 
'*', 
b.literal(6), 
b.literal(7) 
) 
) 
]);
Constructing 
estemplate('var <%= varName %> = 6 * 7;', { 
varName: {type: 'Identifier', name: 'answer'} 
});
Transforming 
var counter = 0, map = Object.create(null); 
result = estraverse.replace(tree, { 
enter: function (node) { 
if (node.type === 'Identifier' && node.name[0] === '_') 
node.name = map[node.name] || (map[node.name] = '$' + counter++); 
} 
});
Transforming 
var Renamer = recast.Visitor.extend({ 
init: function () { 
this.counter = 0; 
this.map = Object.create(null); 
}, 
getId: function (name) { 
return this.map[name] || (this.map[name] = '$' + this.counter++); 
}, 
visitIdentifier: function (node) { 
if (node.name[0] === '_') node.name = this.getId(node.name); 
} 
});
Generating 
var output = escodegen.generate(ast, { 
sourceMap: true, 
sourceMapWithCode: true 
}); 
fs.writeFileSync('out.js', output.code); 
fs.writeFileSync('out.js.map', output.map.toString());
Building with AST 
What can we improve here?
File-based builders (Grunt) 
Parsing 
code 
Transforming 
AST 
Generating 
code 
Reading 
file 
Writing file 
Plugin
Streaming builders (Gulp, Browserify) 
Transforming 
AST 
Generating 
code 
Parsing code 
Reading 
file 
Writing 
file 
Plugin
Transforming 
AST 
Next logical step 
Reading 
file 
Writing 
file 
Parsing 
code 
Generating 
code
aster - AST-based code builder 
https://github.com/asterjs/aster
Already available 
aster 
src 
watch 
dest 
runner 
aster-parse 
js 
esnext 
jsx 
coffee 
aster-changed 
aster-concat 
aster-equery 
aster-squery 
aster-rename-ids 
aster-traverse 
aster-uglify 
aster-umd 
npm keyword: aster-plugin
Sample build script 
aster.watch(['src/**/*.js', 'src/**/*.coffee', 'src/**/*.jsx']) 
.throttle(500) 
.map(changed( 
src => src.map(equery({ 
'if ($cond) return $expr1; else return $expr2;': 
'return <%= cond %> ? <%= expr1 %> : <%= expr2 %>' 
})) 
)) 
.map(concat('built.js')) 
.map(umd({exports: 'superLib'})) 
.map(aster.dest('dist', {sourceMap: true})) 
.subscribe(aster.runner);
Plugins – reactive AST transformers 
module.exports = source => { 
source = source || 'built.js'; 
return files => files 
.flatMap(file => Rx.Observable.fromArray(file.program.body)) 
.toArray() 
.map(body => ({ 
type: 'File', 
program: {type: 'Program', body}, 
loc: {source} 
})); 
};
Integration with generic build systems 
grunt.initConfig({ 
aster: { 
options: { 
equery: { 
'if ($cond) return $expr1; else return $expr2;': 
'return <%= cond %> ? <%= expr1 %> : <%= expr2 %>' 
}, 
concat: 'built.js', 
umd: {exports: 'superLib'}, 
dest: {sourceMap: true} 
}, 
files: { 'dist': ['src/**/*.js', 'src/**/*.coffee', 'src/**/*.jsx'] } 
} 
});
Integration with generic build systems 
gulp.src(['src/**/*.js', 'src/**/*.coffee', 'src/**/*.jsx']) 
.pipe(aster(src => src 
.map(equery({ 
'if ($cond) return $expr1; else return $expr2;': 
'return <%= cond %> ? <%= expr1 %> : <%= expr2 %>' 
}) 
.map(concat('built.js')) 
.map(umd({exports: 'superLib'})) 
)) 
.pipe(gulp.dest('dist'))
Questions? 
https://github.com/asterjs 
@RReverser 
me@rreverser.com

Mais conteúdo relacionado

Mais procurados

ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in RustIngvar Stepanyan
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.boyney123
 
Static Optimization of PHP bytecode (PHPSC 2017)
Static Optimization of PHP bytecode (PHPSC 2017)Static Optimization of PHP bytecode (PHPSC 2017)
Static Optimization of PHP bytecode (PHPSC 2017)Nikita Popov
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?Nikita Popov
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Fwdays
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRaimonds Simanovskis
 
PHP Language Trivia
PHP Language TriviaPHP Language Trivia
PHP Language TriviaNikita Popov
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)James Titcumb
 
PHP Performance Trivia
PHP Performance TriviaPHP Performance Trivia
PHP Performance TriviaNikita Popov
 
Interceptors: Into the Core of Pedestal
Interceptors: Into the Core of PedestalInterceptors: Into the Core of Pedestal
Interceptors: Into the Core of PedestalKent Ohashi
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overviewhesher
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Nikita Popov
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!Brendan Eich
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsMark Baker
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6FITC
 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP GeneratorsMark Baker
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...Fwdays
 

Mais procurados (20)

ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
ES2015 workflows
ES2015 workflowsES2015 workflows
ES2015 workflows
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in Rust
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
 
Static Optimization of PHP bytecode (PHPSC 2017)
Static Optimization of PHP bytecode (PHPSC 2017)Static Optimization of PHP bytecode (PHPSC 2017)
Static Optimization of PHP bytecode (PHPSC 2017)
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
 
PHP Language Trivia
PHP Language TriviaPHP Language Trivia
PHP Language Trivia
 
Rails on Oracle 2011
Rails on Oracle 2011Rails on Oracle 2011
Rails on Oracle 2011
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
 
PHP Performance Trivia
PHP Performance TriviaPHP Performance Trivia
PHP Performance Trivia
 
Interceptors: Into the Core of Pedestal
Interceptors: Into the Core of PedestalInterceptors: Into the Core of Pedestal
Interceptors: Into the Core of Pedestal
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP Generators
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
 

Destaque

(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS EngineZongXian Shen
 
How I tried to compile JavaScript
How I tried to compile JavaScriptHow I tried to compile JavaScript
How I tried to compile JavaScriptIngvar Stepanyan
 
JavaScript Parser Infrastructure for Code Quality Analysis
JavaScript Parser Infrastructure for Code Quality AnalysisJavaScript Parser Infrastructure for Code Quality Analysis
JavaScript Parser Infrastructure for Code Quality AnalysisAriya Hidayat
 
Climbing the Abstract Syntax Tree (Bulgaria PHP 2016)
Climbing the Abstract Syntax Tree (Bulgaria PHP 2016)Climbing the Abstract Syntax Tree (Bulgaria PHP 2016)
Climbing the Abstract Syntax Tree (Bulgaria PHP 2016)James Titcumb
 
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)Tom Lee
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsMichael Pirnat
 
Hyperdex - A closer look
Hyperdex - A closer lookHyperdex - A closer look
Hyperdex - A closer lookDECK36
 
Riak Search - Erlang Factory London 2010
Riak Search - Erlang Factory London 2010Riak Search - Erlang Factory London 2010
Riak Search - Erlang Factory London 2010Rusty Klophaus
 
LXC, Docker, and the future of software delivery | LinuxCon 2013
LXC, Docker, and the future of software delivery | LinuxCon 2013LXC, Docker, and the future of software delivery | LinuxCon 2013
LXC, Docker, and the future of software delivery | LinuxCon 2013dotCloud
 
Blazes: coordination analysis for distributed programs
Blazes: coordination analysis for distributed programsBlazes: coordination analysis for distributed programs
Blazes: coordination analysis for distributed programspalvaro
 
Chloe and the Realtime Web
Chloe and the Realtime WebChloe and the Realtime Web
Chloe and the Realtime WebTrotter Cashion
 
Declarative Syntax Definition - Grammars and Trees
Declarative Syntax Definition - Grammars and TreesDeclarative Syntax Definition - Grammars and Trees
Declarative Syntax Definition - Grammars and TreesGuido Wachsmuth
 
ElasticSearch - index server used as a document database
ElasticSearch - index server used as a document databaseElasticSearch - index server used as a document database
ElasticSearch - index server used as a document databaseRobert Lujo
 
(Functional) reactive programming (@pavlobaron)
(Functional) reactive programming (@pavlobaron)(Functional) reactive programming (@pavlobaron)
(Functional) reactive programming (@pavlobaron)Pavlo Baron
 
Complex Legacy System Archiving/Data Retention with MongoDB and Xquery
Complex Legacy System Archiving/Data Retention with MongoDB and XqueryComplex Legacy System Archiving/Data Retention with MongoDB and Xquery
Complex Legacy System Archiving/Data Retention with MongoDB and XqueryDATAVERSITY
 
Spring Cleaning for Your Smartphone
Spring Cleaning for Your SmartphoneSpring Cleaning for Your Smartphone
Spring Cleaning for Your SmartphoneLookout
 
Web-Oriented Architecture (WOA)
Web-Oriented Architecture (WOA)Web-Oriented Architecture (WOA)
Web-Oriented Architecture (WOA)thetechnicalweb
 
Scalable XQuery Processing with Zorba on top of MongoDB
Scalable XQuery Processing with Zorba on top of MongoDBScalable XQuery Processing with Zorba on top of MongoDB
Scalable XQuery Processing with Zorba on top of MongoDBWilliam Candillon
 

Destaque (20)

(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
 
How I tried to compile JavaScript
How I tried to compile JavaScriptHow I tried to compile JavaScript
How I tried to compile JavaScript
 
JavaScript Parser Infrastructure for Code Quality Analysis
JavaScript Parser Infrastructure for Code Quality AnalysisJavaScript Parser Infrastructure for Code Quality Analysis
JavaScript Parser Infrastructure for Code Quality Analysis
 
Climbing the Abstract Syntax Tree (Bulgaria PHP 2016)
Climbing the Abstract Syntax Tree (Bulgaria PHP 2016)Climbing the Abstract Syntax Tree (Bulgaria PHP 2016)
Climbing the Abstract Syntax Tree (Bulgaria PHP 2016)
 
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)
Hugging Abstract Syntax Trees: A Pythonic Love Story (OSDC 2010)
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Hyperdex - A closer look
Hyperdex - A closer lookHyperdex - A closer look
Hyperdex - A closer look
 
Riak Search - Erlang Factory London 2010
Riak Search - Erlang Factory London 2010Riak Search - Erlang Factory London 2010
Riak Search - Erlang Factory London 2010
 
LXC, Docker, and the future of software delivery | LinuxCon 2013
LXC, Docker, and the future of software delivery | LinuxCon 2013LXC, Docker, and the future of software delivery | LinuxCon 2013
LXC, Docker, and the future of software delivery | LinuxCon 2013
 
Blazes: coordination analysis for distributed programs
Blazes: coordination analysis for distributed programsBlazes: coordination analysis for distributed programs
Blazes: coordination analysis for distributed programs
 
Chloe and the Realtime Web
Chloe and the Realtime WebChloe and the Realtime Web
Chloe and the Realtime Web
 
Brunch With Coffee
Brunch With CoffeeBrunch With Coffee
Brunch With Coffee
 
Declarative Syntax Definition - Grammars and Trees
Declarative Syntax Definition - Grammars and TreesDeclarative Syntax Definition - Grammars and Trees
Declarative Syntax Definition - Grammars and Trees
 
ElasticSearch - index server used as a document database
ElasticSearch - index server used as a document databaseElasticSearch - index server used as a document database
ElasticSearch - index server used as a document database
 
(Functional) reactive programming (@pavlobaron)
(Functional) reactive programming (@pavlobaron)(Functional) reactive programming (@pavlobaron)
(Functional) reactive programming (@pavlobaron)
 
Complex Legacy System Archiving/Data Retention with MongoDB and Xquery
Complex Legacy System Archiving/Data Retention with MongoDB and XqueryComplex Legacy System Archiving/Data Retention with MongoDB and Xquery
Complex Legacy System Archiving/Data Retention with MongoDB and Xquery
 
Spring Cleaning for Your Smartphone
Spring Cleaning for Your SmartphoneSpring Cleaning for Your Smartphone
Spring Cleaning for Your Smartphone
 
NkSIP: The Erlang SIP application server
NkSIP: The Erlang SIP application serverNkSIP: The Erlang SIP application server
NkSIP: The Erlang SIP application server
 
Web-Oriented Architecture (WOA)
Web-Oriented Architecture (WOA)Web-Oriented Architecture (WOA)
Web-Oriented Architecture (WOA)
 
Scalable XQuery Processing with Zorba on top of MongoDB
Scalable XQuery Processing with Zorba on top of MongoDBScalable XQuery Processing with Zorba on top of MongoDB
Scalable XQuery Processing with Zorba on top of MongoDB
 

Semelhante a AST - the only true tool for building JavaScript

Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.jsWebsecurify
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs偉格 高
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说Ting Lv
 
Developing web-apps like it's 2013
Developing web-apps like it's 2013Developing web-apps like it's 2013
Developing web-apps like it's 2013Laurent_VB
 
Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - GuilinJackson Tian
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeJosh Mock
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScriptniklal
 
Using Cerberus and PySpark to validate semi-structured datasets
Using Cerberus and PySpark to validate semi-structured datasetsUsing Cerberus and PySpark to validate semi-structured datasets
Using Cerberus and PySpark to validate semi-structured datasetsBartosz Konieczny
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesSiarhei Barysiuk
 
Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5Doris Chen
 
Types End-to-End @ samsara
Types End-to-End @ samsaraTypes End-to-End @ samsara
Types End-to-End @ samsaraStephen Wan
 
Open Source Search: An Analysis
Open Source Search: An AnalysisOpen Source Search: An Analysis
Open Source Search: An AnalysisJustin Finkelstein
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 

Semelhante a AST - the only true tool for building JavaScript (20)

Security Challenges in Node.js
Security Challenges in Node.jsSecurity Challenges in Node.js
Security Challenges in Node.js
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
 
Developing web-apps like it's 2013
Developing web-apps like it's 2013Developing web-apps like it's 2013
Developing web-apps like it's 2013
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
Mongoskin - Guilin
Mongoskin - GuilinMongoskin - Guilin
Mongoskin - Guilin
 
Intro to Ember.JS 2016
Intro to Ember.JS 2016Intro to Ember.JS 2016
Intro to Ember.JS 2016
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and Node
 
Damn Fine CoffeeScript
Damn Fine CoffeeScriptDamn Fine CoffeeScript
Damn Fine CoffeeScript
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
DataMapper
DataMapperDataMapper
DataMapper
 
Using Cerberus and PySpark to validate semi-structured datasets
Using Cerberus and PySpark to validate semi-structured datasetsUsing Cerberus and PySpark to validate semi-structured datasets
Using Cerberus and PySpark to validate semi-structured datasets
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
Go react codelab
Go react codelabGo react codelab
Go react codelab
 
Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5Developing High Performance Websites and Modern Apps with JavaScript and HTML5
Developing High Performance Websites and Modern Apps with JavaScript and HTML5
 
Einführung in TypeScript
Einführung in TypeScriptEinführung in TypeScript
Einführung in TypeScript
 
Types End-to-End @ samsara
Types End-to-End @ samsaraTypes End-to-End @ samsara
Types End-to-End @ samsara
 
Open Source Search: An Analysis
Open Source Search: An AnalysisOpen Source Search: An Analysis
Open Source Search: An Analysis
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 

Último

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Último (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

AST - the only true tool for building JavaScript

  • 1. AST (Abstract Syntax Tree) The only true tool for building JavaScript
  • 2. Source maps Epic win in debugging
  • 3. Source maps – epic win in debugging
  • 4. Source maps – epic win in debugging
  • 5. Builders Epic fail in debugging
  • 6. Builders – epic fail in debugging umdify: // UMD definition output += '(function(root, factory) {n'; output += ' if (typeof define === "function" && define.amd) {n'; output += ' define([' + depNames.join(', ') + '], factory);n'; output += ' } else if (typeof exports === "object") {n'; output += ' module.exports = factory(require);n'; …
  • 7. Builders – epic fail in debugging grunt-amd-wrap: var srcText = grunt.file.read(file.src[0]); var destText = amdWrap(srcText);
  • 8. Builders – epic fail in debugging gulp-concat: buffer.push(file.contents); … var joinedContents = Buffer.concat(buffer);
  • 9. Builders – epic fail in debugging universal-transformer: function transform(srcText) { return 'var answer = 42;'; }
  • 10. Your code is not a string It has a soul
  • 11. Your code has a soul // Life, Universe, and Everything var answer = 6 * 7;
  • 12. Your code has a soul // Life, Universe, and Everything var answer = 6 * 7; '// Life, Universe and Everythingnvar answer = 6 * 7;'
  • 13. Your code has a soul // Life, Universe, and Everything var answer = 6 * 7; [ { type: "Keyword", value: "var" }, { type: "Identifier", value: "answer" }, { type: "Punctuator", value: "=" }, { type: "Numeric", value: "6" }, { type: "Punctuator", value: "*" }, { type: "Numeric", value: "7" }, { type: "Punctuator", value: ";" } ]
  • 14. Your code has a soul [ { type: "Keyword", value: "var" }, { type: "Identifier", value: "answer" }, { type: "Punctuator", value: "=" }, { type: "Numeric", value: "6" }, { type: "Punctuator", value: "*" }, { type: "Numeric", value: "7" }, { type: "Punctuator", value: ";" } ] { type: "Program", body: [{ type: "VariableDeclaration", declarations: [{ type: "VariableDeclarator", id: {type: "Identifier", name: "answer"}, init: { type: "BinaryExpression", operator: "*", left: {type: "Literal", value: 6}, right: {type: "Literal", value: 7} } }], kind: "var" }] }
  • 15. Your code has a soul { type: "Program", body: [{ type: "VariableDeclaration", declarations: [{ type: "VariableDeclarator", id: {type: "Identifier", name: "answer"}, init: { type: "BinaryExpression", operator: "*", left: {type: "Literal", value: 6}, right: {type: "Literal", value: 7} } }], kind: "var" }] } Program VariableDeclaration VariableDeclarator Identifier(“answer”) BinaryExpression(*) Literal(6) Literal(7)
  • 16. Your code has a soul // Life, Universe, and Everything var answer = 6 * 7; Program VariableDeclaration VariableDeclarator Identifier(“answer”) BinaryExpression(*) Literal(6) Literal(7)
  • 17. Code tools How can we work with code AST?
  • 18. Parsing • JavaScript • SpiderMonkey: Reflect.parse – Mozilla's Parser API • Esprima – most popular ECMAScript parser in JS • Acorn – faster alternative ECMAScript parser in JS • UglifyJS – has own parser with custom AST format • Traceur – has ES6 parser that can be used separately as well • … (as a lot of language tools do) … • CoffeeScript • CoffeeScriptRedux – rewrite of CS compiler that internally uses CS AST with conversion to JS AST • JSX • esprima-fb – Facebook's fork of Esprima Harmony branch • jsx-esprima – es* tools based JSX to JS AST transpiler
  • 19. Parsing acorn.parse('var answer = 6 * 7;', {locations: true}); // In each node. loc: { start: { line: 2, column: 0 }, end: { line: 2, column: 19 } }
  • 21. Querying var found; estraverse.traverse(tree, { enter: function (node) { if (node.type === 'Identifier' && node.name[0] === '_') { found = node; return estraverse.VisitorOption.Break; } } })
  • 22. Querying require('grasp-equery') .query('if ($cond) return $yes; else return $no;', ast)
  • 24. Constructing { type: "Program", body: [{ type: "VariableDeclaration", declarations: [{ type: "VariableDeclarator", id: {type: "Identifier", name: "answer"}, init: { type: "BinaryExpression", operator: "*", left: {type: "Literal", value: 6}, right: {type: "Literal", value: 7} } }], kind: "var" }] }
  • 25. Constructing var b = require('ast-types').builders; b.variableDeclaration('var', [ b.variableDeclarator( b.identifier('answer'), b.binaryExpression( '*', b.literal(6), b.literal(7) ) ) ]);
  • 26. Constructing estemplate('var <%= varName %> = 6 * 7;', { varName: {type: 'Identifier', name: 'answer'} });
  • 27. Transforming var counter = 0, map = Object.create(null); result = estraverse.replace(tree, { enter: function (node) { if (node.type === 'Identifier' && node.name[0] === '_') node.name = map[node.name] || (map[node.name] = '$' + counter++); } });
  • 28. Transforming var Renamer = recast.Visitor.extend({ init: function () { this.counter = 0; this.map = Object.create(null); }, getId: function (name) { return this.map[name] || (this.map[name] = '$' + this.counter++); }, visitIdentifier: function (node) { if (node.name[0] === '_') node.name = this.getId(node.name); } });
  • 29. Generating var output = escodegen.generate(ast, { sourceMap: true, sourceMapWithCode: true }); fs.writeFileSync('out.js', output.code); fs.writeFileSync('out.js.map', output.map.toString());
  • 30. Building with AST What can we improve here?
  • 31. File-based builders (Grunt) Parsing code Transforming AST Generating code Reading file Writing file Plugin
  • 32. Streaming builders (Gulp, Browserify) Transforming AST Generating code Parsing code Reading file Writing file Plugin
  • 33. Transforming AST Next logical step Reading file Writing file Parsing code Generating code
  • 34. aster - AST-based code builder https://github.com/asterjs/aster
  • 35. Already available aster src watch dest runner aster-parse js esnext jsx coffee aster-changed aster-concat aster-equery aster-squery aster-rename-ids aster-traverse aster-uglify aster-umd npm keyword: aster-plugin
  • 36. Sample build script aster.watch(['src/**/*.js', 'src/**/*.coffee', 'src/**/*.jsx']) .throttle(500) .map(changed( src => src.map(equery({ 'if ($cond) return $expr1; else return $expr2;': 'return <%= cond %> ? <%= expr1 %> : <%= expr2 %>' })) )) .map(concat('built.js')) .map(umd({exports: 'superLib'})) .map(aster.dest('dist', {sourceMap: true})) .subscribe(aster.runner);
  • 37. Plugins – reactive AST transformers module.exports = source => { source = source || 'built.js'; return files => files .flatMap(file => Rx.Observable.fromArray(file.program.body)) .toArray() .map(body => ({ type: 'File', program: {type: 'Program', body}, loc: {source} })); };
  • 38. Integration with generic build systems grunt.initConfig({ aster: { options: { equery: { 'if ($cond) return $expr1; else return $expr2;': 'return <%= cond %> ? <%= expr1 %> : <%= expr2 %>' }, concat: 'built.js', umd: {exports: 'superLib'}, dest: {sourceMap: true} }, files: { 'dist': ['src/**/*.js', 'src/**/*.coffee', 'src/**/*.jsx'] } } });
  • 39. Integration with generic build systems gulp.src(['src/**/*.js', 'src/**/*.coffee', 'src/**/*.jsx']) .pipe(aster(src => src .map(equery({ 'if ($cond) return $expr1; else return $expr2;': 'return <%= cond %> ? <%= expr1 %> : <%= expr2 %>' }) .map(concat('built.js')) .map(umd({exports: 'superLib'})) )) .pipe(gulp.dest('dist'))