SlideShare uma empresa Scribd logo
1 de 18
Baixar para ler offline
AST Rewriting Using
recast and esprima
Boston Node
March 22, 2017
Stephen Vance
Ember.js Routes
import Ember from 'ember';
import config from './config/environment';
const Router = Ember.Router.extend({
location: config.locationType,
rootURL: config.rootURL
});
Router.map(function() {
});
export default Router;
2
Ember Route Generator
$ ember generate route foo
import Ember from 'ember';
import config from './config/environment';
const Router = Ember.Router.extend({
location: config.locationType,
rootURL: config.rootURL
});
Router.map(function() {
this.route('foo');
});
export default Router;
3
Bug: Route Removal
$ ember destroy route bar
Router.map(function() {
this.route('bar');
this.route('foo', function() {
this.route('bar');
});
});
export default Router;
Fixed in Fix like-named route removal bug
4
The Tools
Esprima
ECMAScript parsing
infrastructure for multipurpose
analysis
Site: http://esprima.org/
by Ariya Hidayat
recast
JavaScript syntax tree
transformer, nondestructive
pretty-printer, and automatic
source map generator
by Ben Newman
5
Visualizing ASTs
6
Rendered using http://resources.jointjs.com/demos/javascript-ast
You can also use AST Explorer
AST Types
def("Property")
.bases("Node")
.build("kind", "key", "value")
.field(“kind",
or("init", "get", "set"))
.field(“key",
or(def(“Literal”),
def("Identifier")))
.field(“value”,
def("Expression"));
7
def("Literal")
.bases("Node", "Expression")
.build("value")
.field(“value",
or(String, Boolean, null,
Number, RegExp))
.field("regex", or({
pattern: String,
flags: String
}, null), function () {
if (this.value instanceof RegExp) {
var flags = "";
if (this.value.ignoreCase)
flags += "i";
if (this.value.multiline)
flags += "m";
if (this.value.global)
flags += "g";
return {
pattern: this.value.source,
flags: flags
};
}
return null;
});
Using recast
const recast = require('recast');
const fs = require('fs');
const source = fs.readFileSync('some-code.js', 'utf-8');
let ast = recast.parse(source);
// Manipulate ast
let output = recast.print(ast).code;
8
A Real-Life Use
// ember-cli-build.js
module.exports = function(defaults) {

var app = new EmberApp(defaults, {

// Add options here

});



return app.toTree();

};
9
Examples taken from ember-cli-build-config-editor
Finding a Marker
recast.visit(ast, {

visitNewExpression: function (path) {

var node = path.node;



if (node.callee.name === 'EmberApp') {

editor.configNode = node.arguments.find(isObjectExpression);



return false;

} else {

this.traverse(path);

}

}

})
10
Adding Syntax
function findOrAddConfigKey(key) {
var configKey = this.configNode.properties.find(isKey(key));
if (!configKey) {
configKey = builders.property(
'init',
builders.literal(key),
builders.objectExpression([])
);
this.configNode.properties.push(configKey);
}
return configKey;
}
11
What Type Is It?
function isKey(key) {

return function (property) {

return (property.key.type === 'Literal'
&& property.key.value === key)

|| (property.key.type === 'Identifier'
&& property.key.name === key);

};

}
12
Now we have …
module.exports = function(defaults) {

var app = new EmberApp(defaults, {

'some-addon': {

}

});



return app.toTree();

};
13
Editing Simple Values
function addOrUpdateConfigProperty(configObject, property, config) {

var existingProperty = configObject.properties.find(isKey(property));



if (existingProperty) {

existingProperty.value.value = config[property];

} else {

var newProperty = builders.property(

'init',

builders.literal(property),

builders.literal(config[property])

);

configObject.properties.push(newProperty);

}

}
14
The Result
module.exports = function(defaults) {
var app = new EmberApp(defaults, {
'some-addon': {
'booleanProperty': false,
'numericProperty': 17,
'stringProperty': 'wow'
}
});
return app.toTree();
};
15
Adding a Function Call
var node = builders.expressionStatement(
builders.callExpression(
builders.memberExpression(
builders.thisExpression(),
builders.identifier(options.identifier || 'route'),
false
),
[builders.literal(name)]
)
);
16
Example from ember-router-generator
Go forth and rewrite ASTs!
17
Contact Me
Stephen Vance
http://www.vance.com
steve@vance.com
@StephenRVance
srvance on GitHub and LinkedIn
18

Mais conteúdo relacionado

Semelhante a AST Rewriting Using recast and esprima

AST - the only true tool for building JavaScript
AST - the only true tool for building JavaScriptAST - the only true tool for building JavaScript
AST - the only true tool for building JavaScript
Ingvar Stepanyan
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
Ting Lv
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
偉格 高
 

Semelhante a AST Rewriting Using recast and esprima (20)

Intro to Ember.JS 2016
Intro to Ember.JS 2016Intro to Ember.JS 2016
Intro to Ember.JS 2016
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
AST - the only true tool for building JavaScript
AST - the only true tool for building JavaScriptAST - the only true tool for building JavaScript
AST - the only true tool for building JavaScript
 
Rntb20200805
Rntb20200805Rntb20200805
Rntb20200805
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On Rails
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
ECMAScript 6 Review
ECMAScript 6 ReviewECMAScript 6 Review
ECMAScript 6 Review
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
Php 5.6
Php 5.6Php 5.6
Php 5.6
 
Nodejs do teste de unidade ao de integração
Nodejs  do teste de unidade ao de integraçãoNodejs  do teste de unidade ao de integração
Nodejs do teste de unidade ao de integração
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
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
 
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 
Es6 good parts
Es6 good partsEs6 good parts
Es6 good parts
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
 
Symfony tips and tricks
Symfony tips and tricksSymfony tips and tricks
Symfony tips and tricks
 
Node js mongodriver
Node js mongodriverNode js mongodriver
Node js mongodriver
 

Mais de Stephen Vance

Mais de Stephen Vance (8)

Ai and mobile - Power in Your Pocket
Ai and mobile - Power in Your PocketAi and mobile - Power in Your Pocket
Ai and mobile - Power in Your Pocket
 
Ai and mobile
Ai and mobileAi and mobile
Ai and mobile
 
Zero Bugs: State of the Practice
Zero Bugs: State of the PracticeZero Bugs: State of the Practice
Zero Bugs: State of the Practice
 
Ember and OAuth2
Ember and OAuth2Ember and OAuth2
Ember and OAuth2
 
Cultivating People as the Org Grows
Cultivating People as the Org GrowsCultivating People as the Org Grows
Cultivating People as the Org Grows
 
AgileChina 2015: Agile Estimation Workshop
AgileChina 2015: Agile Estimation WorkshopAgileChina 2015: Agile Estimation Workshop
AgileChina 2015: Agile Estimation Workshop
 
AgileChina 2015 Keynote: Understand deeply
AgileChina 2015 Keynote: Understand deeplyAgileChina 2015 Keynote: Understand deeply
AgileChina 2015 Keynote: Understand deeply
 
20160908 Aesthetic-Driven Development
20160908 Aesthetic-Driven Development20160908 Aesthetic-Driven Development
20160908 Aesthetic-Driven Development
 

Último

The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 

Último (20)

The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 

AST Rewriting Using recast and esprima

  • 1. AST Rewriting Using recast and esprima Boston Node March 22, 2017 Stephen Vance
  • 2. Ember.js Routes import Ember from 'ember'; import config from './config/environment'; const Router = Ember.Router.extend({ location: config.locationType, rootURL: config.rootURL }); Router.map(function() { }); export default Router; 2
  • 3. Ember Route Generator $ ember generate route foo import Ember from 'ember'; import config from './config/environment'; const Router = Ember.Router.extend({ location: config.locationType, rootURL: config.rootURL }); Router.map(function() { this.route('foo'); }); export default Router; 3
  • 4. Bug: Route Removal $ ember destroy route bar Router.map(function() { this.route('bar'); this.route('foo', function() { this.route('bar'); }); }); export default Router; Fixed in Fix like-named route removal bug 4
  • 5. The Tools Esprima ECMAScript parsing infrastructure for multipurpose analysis Site: http://esprima.org/ by Ariya Hidayat recast JavaScript syntax tree transformer, nondestructive pretty-printer, and automatic source map generator by Ben Newman 5
  • 6. Visualizing ASTs 6 Rendered using http://resources.jointjs.com/demos/javascript-ast You can also use AST Explorer
  • 7. AST Types def("Property") .bases("Node") .build("kind", "key", "value") .field(“kind", or("init", "get", "set")) .field(“key", or(def(“Literal”), def("Identifier"))) .field(“value”, def("Expression")); 7 def("Literal") .bases("Node", "Expression") .build("value") .field(“value", or(String, Boolean, null, Number, RegExp)) .field("regex", or({ pattern: String, flags: String }, null), function () { if (this.value instanceof RegExp) { var flags = ""; if (this.value.ignoreCase) flags += "i"; if (this.value.multiline) flags += "m"; if (this.value.global) flags += "g"; return { pattern: this.value.source, flags: flags }; } return null; });
  • 8. Using recast const recast = require('recast'); const fs = require('fs'); const source = fs.readFileSync('some-code.js', 'utf-8'); let ast = recast.parse(source); // Manipulate ast let output = recast.print(ast).code; 8
  • 9. A Real-Life Use // ember-cli-build.js module.exports = function(defaults) {
 var app = new EmberApp(defaults, {
 // Add options here
 });
 
 return app.toTree();
 }; 9 Examples taken from ember-cli-build-config-editor
  • 10. Finding a Marker recast.visit(ast, {
 visitNewExpression: function (path) {
 var node = path.node;
 
 if (node.callee.name === 'EmberApp') {
 editor.configNode = node.arguments.find(isObjectExpression);
 
 return false;
 } else {
 this.traverse(path);
 }
 }
 }) 10
  • 11. Adding Syntax function findOrAddConfigKey(key) { var configKey = this.configNode.properties.find(isKey(key)); if (!configKey) { configKey = builders.property( 'init', builders.literal(key), builders.objectExpression([]) ); this.configNode.properties.push(configKey); } return configKey; } 11
  • 12. What Type Is It? function isKey(key) {
 return function (property) {
 return (property.key.type === 'Literal' && property.key.value === key)
 || (property.key.type === 'Identifier' && property.key.name === key);
 };
 } 12
  • 13. Now we have … module.exports = function(defaults) {
 var app = new EmberApp(defaults, {
 'some-addon': {
 }
 });
 
 return app.toTree();
 }; 13
  • 14. Editing Simple Values function addOrUpdateConfigProperty(configObject, property, config) {
 var existingProperty = configObject.properties.find(isKey(property));
 
 if (existingProperty) {
 existingProperty.value.value = config[property];
 } else {
 var newProperty = builders.property(
 'init',
 builders.literal(property),
 builders.literal(config[property])
 );
 configObject.properties.push(newProperty);
 }
 } 14
  • 15. The Result module.exports = function(defaults) { var app = new EmberApp(defaults, { 'some-addon': { 'booleanProperty': false, 'numericProperty': 17, 'stringProperty': 'wow' } }); return app.toTree(); }; 15
  • 16. Adding a Function Call var node = builders.expressionStatement( builders.callExpression( builders.memberExpression( builders.thisExpression(), builders.identifier(options.identifier || 'route'), false ), [builders.literal(name)] ) ); 16 Example from ember-router-generator
  • 17. Go forth and rewrite ASTs! 17