ASTs are an incredibly powerful tool for understanding and manipulating JavaScript. We'll explore this topic by looking at examples from ESLint, a pluggable static analysis tool, and Browserify, a client-side module bundler. Through these examples we'll see how ASTs can be great for analyzing and even for modifying your JavaScript. This talk should be interesting to anyone that regularly builds apps in JavaScript either on the client-side or on the server-side.
Theory of automata and formal languageRabia Khalid
KleenE Star Closure, Plus operation, recursive definition of languages, INTEGER, EVEN, factorial, PALINDROME, languages of strings, cursive definition of RE, defining languages by RE,Examples
Most industrial safety-critical systems are developed and validated following safety standards. However even though all safety standards address similar concerns with similar objectives, they are also domain-specific standards. The presentation results from the activity of a working group (formerly CG2E, now part of the recently set-up Embedded France) gathering industrial safety experts from aeronautics, automotive, industrial automation, nuclear, railway and space. The lecture will combine a presentation focused on one industry specific standard (the recent ISO 26262 for automotive), and complementary perspective in comparison with the standards in the other five mentioned domains. After the presentation of the history and position and the various regulation regimes, we will highlight some more technical topics e.g., integrated or external safety systems, fault prevention vs. fault tolerance, objectives vs. means prescription, probabilistic vs. deterministic arguments and the notion of criticality, integrity or assurance levels.
Theory of automata and formal languageRabia Khalid
KleenE Star Closure, Plus operation, recursive definition of languages, INTEGER, EVEN, factorial, PALINDROME, languages of strings, cursive definition of RE, defining languages by RE,Examples
Most industrial safety-critical systems are developed and validated following safety standards. However even though all safety standards address similar concerns with similar objectives, they are also domain-specific standards. The presentation results from the activity of a working group (formerly CG2E, now part of the recently set-up Embedded France) gathering industrial safety experts from aeronautics, automotive, industrial automation, nuclear, railway and space. The lecture will combine a presentation focused on one industry specific standard (the recent ISO 26262 for automotive), and complementary perspective in comparison with the standards in the other five mentioned domains. After the presentation of the history and position and the various regulation regimes, we will highlight some more technical topics e.g., integrated or external safety systems, fault prevention vs. fault tolerance, objectives vs. means prescription, probabilistic vs. deterministic arguments and the notion of criticality, integrity or assurance levels.
Z4R: Intro to Storage and DFSMS for z/OSTony Pearson
This session covers basic storage concepts for z/OS operating system with examples for Flash, Disk and Tape devices and how to use DFSMS policy-based management. Presented at IBM TechU in Johannesburg, South Africa September 2019
XPDS16: AMD's virtualization memory encryption technology - Brijesh Singh, A...The Linux Foundation
AMD recently disclosed new security technologies which leverage hardware-based memory encryption to provide additional security protections. This talk will focus primarily on technology which supports encrypted virtual machines for extra isolation and protection from the hypervisor itself. The presentation will discuss the technical details of this technology with a focus on how it can be integrated within the Xen infrastructure.
High Performance Data Analysis (HPDA): HPC - Big Data Convergenceinside-BigData.com
In this video from the HPC User Forum in Santa Fe, Steve Conway from Hyperion Research presents: High Performance Data Analysis (HPDA): HPC - Big Data Convergence.
"To date, most data-intensive HPC jobs in the government, academic and industrial sectors have involved the modeling and simulation of complex physical and quasi-physical systems. The systems range from product designs for cars, planes, golf clubs and pharmaceuticals, to subatomic particles, global weather and climate patterns, and the cosmos itself. But from the start of the supercomputer era in the 1960s — and even earlier —an important subset of HPC jobs has involved analytics — attempts to uncover useful information and patterns in the data itself. Cryptography, one of the original scientific-technical computing applications, falls predominantly into this category."
Watch the video: http://wp.me/p3RLHQ-gHm
Learn more: http://hpcuserforum.com
An overview presentation of FormsFX, a framework for creating forms via a fluent API in JavaFX. The framework supports internationalisation, validation, automatic layout, tooltips, etc....
This lecture slide contains:
1. Regular Languages
2. Regular Operations
3. Closure of regular languages
4. Regular expression
5. Precedence of regular operations
6. RE for different languages
7. RE to NFA conversion
8. DFA to GNFA to RE conversion
syzkaller is an unsupervised, coverage-guided Linux syscall fuzzer.
The presentation covers basic of operation of the fuzzer, gives tutorial on how to run it and how to extend it to fuzz new drivers.
Kernel address sanitizer (KASan) is a dynamic memory error detector for finding out-of-bounds and use-after-free bugs in Linux kernel. It uses shadow memory to record whether each byte of memory is safe to access and uses compile-time instrumentation to check shadow memory
on each memory access. In this presentation Alexander Popov will describe the successful experience of porting KASan to a bare-metal hypervisor: the main steps, pitfalls and the ways to make KASan checks much more strict and multi-purpose.
This presentation was delivered at LinuxCon Japan 2016 by Alexander Popov
Ajax is the web's hottest user interface. Struts is Java's most popular web framework. What happens when we put Ajax on Struts?
In this session, we look at writing a new Struts 2 application from square one, using the Yahoo User Interface (YUI) Library on the front end, and Struts 2 on the backend. YUI provides the glitz and the glamour, and Struts 2 provides the dreary business logic, input validation, and text formatting.
During the session, we will cover
* How to integrate an Ajax UI with Struts 2
* Basics of the Yahoo User Interface (YUI) Library
* Business services Struts can provide to an Ajax UI
Who should attend: Ajax developers who would like to utilize Struts as a back-end, and Struts developers who would like to utilize Ajax as a front-end.
To get the most from this session, some familiarity with an Ajax library, like YUI or Dojo, is helpful.
Attack monitoring using ElasticSearch Logstash and KibanaPrajal Kulkarni
With growing trend of Big data, companies are tend to rely on high cost SIEM solutions. However, with introduction of open source and lightweight cluster management solution like ElasticSearch this has been the highlight of the year. Similarly, the log aggregation has been simplified by logstash and kibana providing a visual look to the complex data structure. This presentation will exactly cater to this need of having a appropriate log analysis+Detecting Intrusion+Visualizing data in a powerful interface.
Lets look at writing a new Struts 2 application from square one, using the Yahoo User Interface (YUI) Library on the front end, and Struts 2 on the backend. YUI provides the glitz and the glamour, and Struts 2 provides the dreary business logic, input validation, and text formatting.
Z4R: Intro to Storage and DFSMS for z/OSTony Pearson
This session covers basic storage concepts for z/OS operating system with examples for Flash, Disk and Tape devices and how to use DFSMS policy-based management. Presented at IBM TechU in Johannesburg, South Africa September 2019
XPDS16: AMD's virtualization memory encryption technology - Brijesh Singh, A...The Linux Foundation
AMD recently disclosed new security technologies which leverage hardware-based memory encryption to provide additional security protections. This talk will focus primarily on technology which supports encrypted virtual machines for extra isolation and protection from the hypervisor itself. The presentation will discuss the technical details of this technology with a focus on how it can be integrated within the Xen infrastructure.
High Performance Data Analysis (HPDA): HPC - Big Data Convergenceinside-BigData.com
In this video from the HPC User Forum in Santa Fe, Steve Conway from Hyperion Research presents: High Performance Data Analysis (HPDA): HPC - Big Data Convergence.
"To date, most data-intensive HPC jobs in the government, academic and industrial sectors have involved the modeling and simulation of complex physical and quasi-physical systems. The systems range from product designs for cars, planes, golf clubs and pharmaceuticals, to subatomic particles, global weather and climate patterns, and the cosmos itself. But from the start of the supercomputer era in the 1960s — and even earlier —an important subset of HPC jobs has involved analytics — attempts to uncover useful information and patterns in the data itself. Cryptography, one of the original scientific-technical computing applications, falls predominantly into this category."
Watch the video: http://wp.me/p3RLHQ-gHm
Learn more: http://hpcuserforum.com
An overview presentation of FormsFX, a framework for creating forms via a fluent API in JavaFX. The framework supports internationalisation, validation, automatic layout, tooltips, etc....
This lecture slide contains:
1. Regular Languages
2. Regular Operations
3. Closure of regular languages
4. Regular expression
5. Precedence of regular operations
6. RE for different languages
7. RE to NFA conversion
8. DFA to GNFA to RE conversion
syzkaller is an unsupervised, coverage-guided Linux syscall fuzzer.
The presentation covers basic of operation of the fuzzer, gives tutorial on how to run it and how to extend it to fuzz new drivers.
Kernel address sanitizer (KASan) is a dynamic memory error detector for finding out-of-bounds and use-after-free bugs in Linux kernel. It uses shadow memory to record whether each byte of memory is safe to access and uses compile-time instrumentation to check shadow memory
on each memory access. In this presentation Alexander Popov will describe the successful experience of porting KASan to a bare-metal hypervisor: the main steps, pitfalls and the ways to make KASan checks much more strict and multi-purpose.
This presentation was delivered at LinuxCon Japan 2016 by Alexander Popov
Ajax is the web's hottest user interface. Struts is Java's most popular web framework. What happens when we put Ajax on Struts?
In this session, we look at writing a new Struts 2 application from square one, using the Yahoo User Interface (YUI) Library on the front end, and Struts 2 on the backend. YUI provides the glitz and the glamour, and Struts 2 provides the dreary business logic, input validation, and text formatting.
During the session, we will cover
* How to integrate an Ajax UI with Struts 2
* Basics of the Yahoo User Interface (YUI) Library
* Business services Struts can provide to an Ajax UI
Who should attend: Ajax developers who would like to utilize Struts as a back-end, and Struts developers who would like to utilize Ajax as a front-end.
To get the most from this session, some familiarity with an Ajax library, like YUI or Dojo, is helpful.
Attack monitoring using ElasticSearch Logstash and KibanaPrajal Kulkarni
With growing trend of Big data, companies are tend to rely on high cost SIEM solutions. However, with introduction of open source and lightweight cluster management solution like ElasticSearch this has been the highlight of the year. Similarly, the log aggregation has been simplified by logstash and kibana providing a visual look to the complex data structure. This presentation will exactly cater to this need of having a appropriate log analysis+Detecting Intrusion+Visualizing data in a powerful interface.
Lets look at writing a new Struts 2 application from square one, using the Yahoo User Interface (YUI) Library on the front end, and Struts 2 on the backend. YUI provides the glitz and the glamour, and Struts 2 provides the dreary business logic, input validation, and text formatting.
He will start you at the beginning and cover prerequisites; setting up your development environment first. Afterward, you will use npm to install react-native-cli. The CLI is our go to tool. We use it to create and deploy our app.
Next, you will explore the code. React Native will look familiar to all React developers since it is React. The main difference between React on the browser and a mobile device is the lack of a DOM. We take a look a many of the different UI components that are available.
With React Native you have access to all of the devices hardware features like cameras, GPS, fingerprint reader and more. So we'll show some JavaScript code samples demonstrating it. We will wrap up the evening by deploying our app to both iOS and Android devices and with tips on getting ready for both devices stores.
Node has captured the attention of early adopters by clearly differentiating itself as being asynchronous from the ground up while remaining accessible. Now that server side JavaScript is at the cutting edge of the asynchronous, real time web, it is in a much better position to establish itself as the go to language for also making synchronous, CRUD webapps and gain a stronger foothold on the server.
This talk covers the current state of server side JavaScript beyond Node. It introduces Common Node, a synchronous CommonJS compatibility layer using node-fibers which bridges the gap between the different platforms. We look into Common Node's internals, compare its performance to that of other implementations such as RingoJS and go through some ideal use cases.
Welcome to the first live UiPath Community Day Dubai! Join us for this unique occasion to meet our local and global UiPath Community and leaders. You will get a full view of the MEA region's automation landscape and the AI Powered automation technology capabilities of UiPath. Also, hosted by our local partners Marc Ellis, you will enjoy a half-day packed with industry insights and automation peers networking.
📕 Curious on our agenda? Wait no more!
10:00 Welcome note - UiPath Community in Dubai
Lovely Sinha, UiPath Community Chapter Leader, UiPath MVPx3, Hyper-automation Consultant, First Abu Dhabi Bank
10:20 A UiPath cross-region MEA overview
Ashraf El Zarka, VP and Managing Director MEA, UiPath
10:35: Customer Success Journey
Deepthi Deepak, Head of Intelligent Automation CoE, First Abu Dhabi Bank
11:15 The UiPath approach to GenAI with our three principles: improve accuracy, supercharge productivity, and automate more
Boris Krumrey, Global VP, Automation Innovation, UiPath
12:15 To discover how Marc Ellis leverages tech-driven solutions in recruitment and managed services.
Brendan Lingam, Director of Sales and Business Development, Marc Ellis
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofsAlex Pruden
This paper presents Reef, a system for generating publicly verifiable succinct non-interactive zero-knowledge proofs that a committed document matches or does not match a regular expression. We describe applications such as proving the strength of passwords, the provenance of email despite redactions, the validity of oblivious DNS queries, and the existence of mutations in DNA. Reef supports the Perl Compatible Regular Expression syntax, including wildcards, alternation, ranges, capture groups, Kleene star, negations, and lookarounds. Reef introduces a new type of automata, Skipping Alternating Finite Automata (SAFA), that skips irrelevant parts of a document when producing proofs without undermining soundness, and instantiates SAFA with a lookup argument. Our experimental evaluation confirms that Reef can generate proofs for documents with 32M characters; the proofs are small and cheap to verify (under a second).
Paper: https://eprint.iacr.org/2023/1886
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™UiPathCommunity
In questo evento online gratuito, organizzato dalla Community Italiana di UiPath, potrai esplorare le nuove funzionalità di Autopilot, il tool che integra l'Intelligenza Artificiale nei processi di sviluppo e utilizzo delle Automazioni.
📕 Vedremo insieme alcuni esempi dell'utilizzo di Autopilot in diversi tool della Suite UiPath:
Autopilot per Studio Web
Autopilot per Studio
Autopilot per Apps
Clipboard AI
GenAI applicata alla Document Understanding
👨🏫👨💻 Speakers:
Stefano Negro, UiPath MVPx3, RPA Tech Lead @ BSP Consultant
Flavio Martinelli, UiPath MVP 2023, Technical Account Manager @UiPath
Andrei Tasca, RPA Solutions Team Lead @NTT Data
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
The Metaverse and AI: how can decision-makers harness the Metaverse for their...Jen Stirrup
The Metaverse is popularized in science fiction, and now it is becoming closer to being a part of our daily lives through the use of social media and shopping companies. How can businesses survive in a world where Artificial Intelligence is becoming the present as well as the future of technology, and how does the Metaverse fit into business strategy when futurist ideas are developing into reality at accelerated rates? How do we do this when our data isn't up to scratch? How can we move towards success with our data so we are set up for the Metaverse when it arrives?
How can you help your company evolve, adapt, and succeed using Artificial Intelligence and the Metaverse to stay ahead of the competition? What are the potential issues, complications, and benefits that these technologies could bring to us and our organizations? In this session, Jen Stirrup will explain how to start thinking about these technologies as an organisation.
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfPeter Spielvogel
Building better applications for business users with SAP Fiori.
• What is SAP Fiori and why it matters to you
• How a better user experience drives measurable business benefits
• How to get started with SAP Fiori today
• How SAP Fiori elements accelerates application development
• How SAP Build Code includes SAP Fiori tools and other generative artificial intelligence capabilities
• How SAP Fiori paves the way for using AI in SAP apps
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
2. Our Basic Plan
1. High-level overview
2. Static Analysis with ASTs
3. Transforming and refactoring
4. A quick look at the Mozilla Parser API
(de-facto standard AST format)
11. Fix a bug. Add a unit test.
Fix a similar bug…
12. Write some really
solid static analysis.
Never write that same
type of bug again.
13. function loadUser(req, res, next) {
User.loadUser(function(err, user) {
req.session.user = user;
next();
});
}
Bad Example
We forgot to handle the error!
14.
15. handle-callback-err
1. Each time a function is declared check
if there is an error* parameter
If so set a count to 0;
Increment count when error is used
At the end of the function warn when
count is empty
* the parameter name can be defined by the user
17. History Lesson
• 1995: JavaScript
• 2002: JSLint started by Douglas Crockford
• 2011: JSHint comes out as a fork of JSLint.
Esprima AST parser released.
• 2012: plato, escomplex, complexity-report
• 2013: Nicholoas Zakas releases ESLint. Marat
Dulin releases JSCS.
23. no-loop-func
function checkForLoops(node) {
var ancestors = context.getAncestors();
if (ancestors.some(function(ancestor) {
return ancestor.type === "ForStatement" ||
ancestor.type === "WhileStatement" ||
ancestor.type === "DoWhileStatement";
})) {
context.report(node, "Don't make functions within a loop");
}
}
return {
"FunctionExpression": checkForLoops,
"FunctionDeclaration": checkForLoops
};
24. max-params
var numParams = context.options[0] || 3;
function checkParams(node) {
if (node.params.length > numParams) {
context.report(node, "This function has too many parameters
({{count}}). Maximum allowed is {{max}}.", {
count: node.params.length,
max: numParams
});
}
}
return {
“FunctionDeclaration”: checkParams,
“FunctionExpression”: checkParams
}
25. no-jquery
function isjQuery(name) {
return name === '$' || name === 'jquery' || name === 'jQuery';
}
return {
“CallExpression”: function(node) {
var name = node.callee && node.callee.name;
if (isjQuery(name)) {
context.report(node, 'Please avoid using jQuery here.’);
}
}
}
27. Other Areas for Static
Analysis
Code complexity and visualization is another
area where static analysis is really useful. Plato is
an exciting start, but I believe there are tons of
more interesting things that can be done in this
area.
28. Recap
• Static Analysis can help you catch real bugs and keep
your code maintainable
• ESLint and JSCS both use ASTs for inspecting your
code to make it easy to cleanly to add new rules
• Static analysis can also help you manage your code
complexity as well
• What exactly does a for loop sound like?
34. Tools like falafel and recast give
you an API to manipulate an AST
and then convert that back into
source code.
35. Two Types of AST
Transformations
Regenerative
Regenerate the full file from the AST. Often losing
comments and non-essential formatting. Fine for code
not read by humans (i.e. browserify transforms).
Partial-source transformation
Regenerate only the parts of the source that have
changed based on the AST modifications. Nicer for
one-time changes in source.
38. 4 Steps
1. Buffer up the stream of source code
2. Convert the source into an AST
3. Transform the AST
4. Re-generate and output the source
39. Step 1
Use through to grab the source code
var through = require(‘through');
var buffer = [];
return through(function write(data) {
buffer.push(data);
}, function end () {
var source = buffer.join(‘’);
});
40. Step 2
Use falafel to transform create an AST
var falafel = require(‘falafel’);
function end () {
var source = buffer.join(‘’);
var out = falafel(source, parse).toString();
}
41. Step 3
function parse(node) {
if (node.type === 'Identifier' &&
node.value === ‘ui’) {
node.update('browserify');
}
}
Use falafel to transform the AST
42. Step 4
Stream the source with through and close the stream
function end () {
var source = buffer.join(‘’);
var out = falafel(source, parse).toString();
this.queue(out);
this.queue(null); // end the stream
}
43. var through = require('through');
var falafel = require('falafel');
module.exports = function() {
var buffer = [];
return through(function write(data) {
buffer.push(data);
}, function end() {
var source = buffer.join('n');
var out = falafel(source, parse).toString();
this.queue(out);
this.queue(null); // close the stream
});
};
function parse(node) {
if (node.type === 'Identifier' &&
node.name === 'ui') {
node.update('browserify');
}
}
53. A Basic Map/Filter
var a = [1, 2, 3];
var b = a.filter(function(n) {
return n > 1;
}).map(function(k) {
return k * 2;
});
54. Faster Like This
var a = [1, 2, 3];
var b = [];
for (var i = 0; i < a.length; i++) {
if (a[i] > 1) {
b.push(a[i] * 2);
}
}
55.
56. A Basic Recast Script
var recast = require(‘recast’);
var code = fs.readFileSync(‘code.js', 'utf-8');
var ast = recast.parse(code);
var faster = transform(ast);
var output = recast.print(faster).code;
57. function transform(ast) {
var transformedAST = new MapFilterEater({
body: ast.program.body
}).visit(ast);
return transformedAST;
}
var Visitor = recast.Visitor;
var MapFilterEater = Visitor.extend({
init: function(options) {},
visitForStatement: function(ast) {},
visitIfStatement: function(ast) {},
visitCallExpression: function(ast) {},
visitVariableDeclarator: function(ast) {}
});
58. How Does it Work?
1. Move the right side of the b declaration into a for loop
2. Set b = []
3. Place the .filter() contents inside of an if statement
4. Unwrap the .map contents and .push() them into b
5. Replace all of the local counters with a[_i]
59.
60.
61.
62.
63. And Voila….
var a = [1, 2, 3];
var b = [];
for (var i = 0; i < a.length; i++) {
if (a[i] > 1) {
b.push(a[i] * 2);
}
}
80. • When debugging console.log(ast) will not print a
large nested AST properly. Instead you can use
util.inspect:
var util = require('util');
var tree = util.inspect(ast, { depth: null });
console.log(tree);
• When transforming code start with the AST you
want and then work backward.
• Often this means pasting code using the Esprima
online visualization tool or just outputting the trees
into JS files and manually diffing them.
81. Oftentimes it helps to print out the code
representation of a single node.
In recast you can do:
var source = recast.prettyPrint(ast, {
tabWidth: 2 }).code;
In ESLint you can get the current node with:
var source = context.getSource(node)
99. Tools like falafel and recast give
you an API to manipulate an AST
and then convert that back into
source code.
Editor's Notes
Hi I’m Jamund. I work at PayPal doing node stuff and I have an environmental planning degree from the university of washington. Which hopefully qualifies me to talk you about trees today.
Before I get started, how many of you have used these tools before and know what i’m talking about? Cool, so the rest of you. please stick around. It’s to ally worth it and I’m sure these people can attest to that.
Instead of having to worry about string parsing and regexes and all that nonsense.
Here’s an example. This is using the mozilla parser API format used by esprima and respresents the following code.
This single statement creates a tree with 7 different nodes!!!
Each item in this tree is a node of one of several types. We’ll discuss these types in more depth later.
My goals is to help my team not introduce bugs in their code.
Anyone know what’w wrong with this with?
So we just built an ESLint rule that would ensure we never made that same mistake again! And it worked! We haven’t seen that type of bug crop up in our codebase.
I love static analysis and that example proves that it can do a lot more than complain about your formatting.
Essentially since 2011 ever new major static analysis tool has been based on esprima.
Mostly because of this…If I want to add a rule. I can put it in its own file/function. Adding that handle-callback-err thing was no problem at all. Even if ESLint didn’t take it at this point I can just NPM install rules and use them! It rocks.
Mixes the parser with the linter. It’s a great tool. But it’s not as easy to extend.
Everytime there’s a member expression, which is thing.thing you just check to see if the name is the console, in which case it complains…..super simple..
But who cares. You can do this with “grep” or something. Let’s do something more fun.
Pretty awesome. So every time you have a function expression or function declaration we check to see if has an ancestor that’s a loop. Pretty dang slick.
Here’s a custom one we have that we only apply to certain parts of the code-base. For example in our backbone models, to prevent people from using Backbone.sync.
Currently working with our globalization team on rules to help us avoid mistakes in handling dates, and phone numbers worldwide. and much more.
For example: what if you could turn your AST into a series of beats and you could listen to your code to help determine how complicated it is. Short song good. Consistent tones good. Too many high notes bad? I don’t know. Think about that.
We’ll use both of these in the following examples:
How many of you have used browserify?
Say we want to change this to this. Dynamically. Easy.
Through takes 2 callbacks. The first lets you buffer the stream data the 2nd is when you get everything.
This is our parse() function. We use falafel’s node.update to transform the node.
altogether it looks like this
And it works. And you can add them with npm and they just work.
Marihn haverbeke, author of Acorn.js parser and a genius. Asks this question. The answer is no, but don’t let that stop you from writing .forEach() and .map() and .filter(). CODE IS FOR HUMANS
https://github.com/xjamundx/perfify-recast/
But we can do hard things.
But we write code for humans, so we’ll let the transform take care of this.
https://github.com/benjamn/recast uses “partial source transformation” to safely
With browserify when you apply the transforms it rewrites the whole thing. You generally lose comments and stuff that isn’t really needed to form the AST. Recast (and some other tools like falafel) are nice for one-time refactoring because the employ techniques to limit the amount of code that is touched during the re-generation phase.
I can show you the full source it’s online…. https://github.com/xjamundx/perfify-recast/blob/master/index.js
There’s also a Facebook fork of Esprima that supports ES6, so it’s getting some support as well. I assume it will eventually bubble back up to the main branch…hopefully?
You probably just need esprima.
http://esprima.org/demo/parse.html#
It’s also called the SpiderMonkey API. Are th
This single statement creates a tree with 7 different nodes!!!
The key to being successful in working with the JavaScript AST is to study the node types. Memorize them. Get used to them. Think about your JavaScript in this way. Here are the basics.
Essentially acorn came out around the time Uglify2 was coming out and Esprima was still new, so he spent a lot of time improving Uglify and didn’t want to rewrite it again, so he wrote a compatability layer.