SlideShare uma empresa Scribd logo
1 de 53
Baixar para ler offline
JavaScript Parser
  Infrastructure for
Code Quality Analysis
         Ariya Hidayat

     Twitter: @AriyaHidayat
     http://ariya.ofilabs.com
Who Am I
Do you...


    have a coding style/guidelines?
    use code quality tool such as JSLint or JSHint?
    actively prevent performance & coverage regressions?
    wish you could write your own quality rules?
Code Quality
High Quality: Practical Aspects



                           Do not provoke ambiguities
   Avoid silly mistakes
                          Learn better code pattern
  Write readable code

                    Improve future maintenance
Better Use of the Tools
                                             Not everyone is
                                           a JavaScript ninja

                            Engineer
                 Tools




       •Boring
       •Repetitive        Feedback Cycle
       •Time-consuming
From Spelling Checker to Grammar Enforcement Agent



               Your so wrong,
             therefore you loose!

                  No misspelled word.
                 Wrong choice of words!
Adaptive Quality Criteria



         Explicit                     Implicit

Customize analysis options   Infer from high-quality sample
Define new sets of rules      Observe the engineer’s behavior
Next-Generation Code Quality Tools




   To boldly analyze what no man has analyzed before...
Parser Infrastructure
JavaScript in the Browser

                                  User Interface




                                                              Data Persistence
                               Browser Engine




                               Render Engine



                                 JavaScript        Graphics
              Networking I/O
                                   Engine           Stack
JavaScript Engine Building Blocks

                                                           Built-in objects,
                                              Runtime
                                                           host objects, ...




                               Syntax Tree

                                               Virtual
   Source          Parser                     Machine/
                                             Interpreter
             Fast and conservative
Tokenization



                         identifier           number


           var answer = 42;
               keyword               equal sign
                                                      semicolon
Syntax Tree



                    Variable Declaration



              Identifier              Literal Constant


               answer                      42
JavaScript Parser Written in JavaScript



             Esprima            UglifyJS
                             Narcissus
           ZeParser
                               Traceur
               Es-Lab
Produce Correct Output


                          ECMA-262 compliant
       'use strict';      Automatic semicolon insertion
       var 日本語 = 1
                          Strict Mode, e.g. “use strict”
       return 日本語
                          Unicode for identifiers
Heavily Tested
                  > 500 unit tests
                  Compatibility tests
                  100% code coverage
                  Performance tests


                          Enforced during
                           development
Sensible Syntax Tree                      https://developer.mozilla.org/en/SpiderMonkey/Parser_API


                                      {
                                          type: "Program",
                                          body: [
                                              {
                                                  type: "ExpressionStatement",
                                                  expression: {
              answer = 42                             type: "AssignmentExpression",
                                                      operator: "=",
                                                      left: {
                                                           type: "Identifier",
                                                           name: "answer"
                                                      },
                                                      right: {
                                                           type: "Literal",
                                                           value: 42
                                                      }
 http://esprima.org/demo/parse.html               }
                                              }
                                          ]
                        Try online!   }
Syntax Tree Visualization




     answer = 42
Specification, Parser Code, Syntax Tree
               ECMA-262 Annex A.4        while ( Expression ) Statement



  function parseWhileStatement() {
      var test, body;
   
      expectKeyword('while');
      expect('(');
      test = parseExpression();
      expect(')');
      body = parseStatement();
   
      return {
          type: Syntax.WhileStatement,
          test: test,
          body: body
      };
  }
High Performance                                   http://esprima.org/test/compare.html




                                           Speed Comparison
                                                                          Chrome 18
                                                                          Internet Explorer 9
         Esprima     233 ms               567 ms


 UglifyJS parse-js               620 ms                                   922 ms




                                         Benchmark corpus:
                              jQuery, Prototype, MooTools, ExtCore, ...
Syntax Node Location
   {
       type: "ExpressionStatement",
       expression: {
           type: "AssignmentExpression",
           operator: "=",
           left: {
                                           answer = 42
               type: "Identifier",
               name: "answer",
               range: [0, 6]
           },
           right: {
               type: "Literal",
               value: 42,
               range: [9, 11]
           },
           range: [0, 11]
       },
       range: [0, 11]
   }
Fit for Code Regeneration                https://github.com/Constellation/escodegen




 Source     Esprima                                   Escodegen                  Source


                              Syntax Tree

                                           Shorten variable name
                 Syntax Transformation     Automatically inline short function
                                           Obfuscate
Easily Tweaked                LLJS: Low Level JavaScript   http://mbebenita.github.com/LLJS/




                 Block scope        let x = 0;



                                    let u8 flag;
                 Data types
                                    let i32 position;

                                    struct Point {
                                        int x, y;
                                    };


                   Pointers         let u16 *p = q;
Error Tolerant                                             Useful for IDE, editors, ...



              Mismatched quote        var msg = "Hello’;


                  Too many dots       person..age = 18;

                                       
           Incomplete, still typing   if (person.



                                       
            Strict mode violation     'use strict';
                                      with (person) {
                                      }
Handle the Comments
                           // Life, Universe, and Everything
                           answer = 42



                    comments: [
                        {
                            range: [0, 34],
                            type: "Line",
                            value: " Life, Universe, and Everything"
                        }
                    ]



           Documentation tool                              Code annotation
 https://github.com/thejohnfreeman/jfdoc    https://github.com/goatslacker/node-typedjs
Forward Looking                               Experimental ‘harmony’ branch



  Object initializer shorthand    Destructuring assignment


   var point = {x, y};           point = {14, 3, 77};
                                 {x, y, z} = point;



             Module
                                       Block scope
   module MathExtra {

         // do something           {
                                        let x;
   }                                    const y = 0;
                                   }
Code Quality Tools
Syntax Tree Visualization




                      Block statement




 http://esprima.org/demo/parse.html
Most Popular Keywords
        this                                           3229

  function                                           3108

           if                                    3063

     return                                   2878

         var                           2116                   var fs = require('fs'),
        else                     562
                                                                  esprima = require('esprima'),
         for                   436
                                                                  files = process.argv.splice(2);
       new               232
                                                               
          in             225
                                                              files.forEach(function (filename) {
    typeof               188
                                                                  var content = fs.readFileSync(filename, 'utf-8'),
      while          143
                                                                      tokens = esprima.parse(content, { tokens: true }).tokens;
       case          122
                                                               
     break           115
                                                                  tokens.forEach(function (token) {
         try        84
                                                                      if (token.type === 'Keyword') {
      catch         84
                                                                          console.log(token.value);
     delete         72
                                                                      }
     throw      38
                                                                  });
    switch      35
                                                              });
  continue      25

    default     15

instanceof      14

         do     12

       void     10

     finally    4
                                                http://ariya.ofilabs.com/2012/03/most-popular-javascript-keywords.html
Most Popular Statements
                                                                           var fs = require('fs'),
ExpressionStatement                                            6728
                                                                               esprima = require('esprima'),
     BlockStatement                                         6353               files = process.argv.splice(2);
          IfStatement                       3063                            
    ReturnStatement                        2878                            files.forEach(function (filename) {
  VariableDeclaration               2116                                       var content = fs.readFileSync(filename, 'utf-8'),
                                                                                   syntax = esprima.parse(content);
 FunctionDeclaration          371
                                                                            
        ForStatement         293
                                                                               JSON.stringify(syntax, function (key, value) {
      ForInStatement        143
                                                                                   if (key === 'type') {
     WhileStatement         131
                                                                                       if (value.match(/Declaration$/) ||
     BreakStatement         115                                                            value.match(/Statement$/)) {
        TryStatement    84                                                                     console.log(value);
    EmptyStatement      66                                                                 }
                                                                                   }
    ThrowStatement      38
                                                                                   return value;
    SwitchStatement     35
                                                                               });
 ContinueStatement      25
                                                                           });
   DoWhileStatement     12

   LabeledStatement     6




                                                   http://ariya.ofilabs.com/2012/04/most-popular-javascript-statements.html
Identifier Length Distribution

750                                                      mean of the identifier length is 8.27 characters



500
                                                         prototype-1.7.0.0.js   SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING
                                                         prototype-1.7.0.0.js   MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED
                                                              jquery-1.7.1.js   subtractsBorderForOverflowNotVisible
                                                         jquery.mobile-1.0.js   getClosestElementWithVirtualBinding
250                                                      prototype-1.7.0.0.js   HAS_EXTENDED_CREATE_ELEMENT_SYNTAX




 0
      0   5   10   15   20   25    30    35   40    45


                                  http://ariya.ofilabs.com/2012/05/javascript-identifier-length-distribution.html
“Code Linting”
                                          var fs = require('fs'),
                                              esprima = require('./esprima'),
                                              files = process.argv.splice(2);
                                           
    Not a strict equal                    files.forEach(function (filename) {
                                              var content = fs.readFileSync(filename, 'utf-8'),
                                                  syntax = esprima.parse(content, { loc: true });
if (x == 9) {                              
    // do Something                           JSON.stringify(syntax, function (key, value) {
}                                                 if (key === 'test' && value.operator === '==')
                                                      console.log('Line', value.loc.start.line);
                                                  return value;
                                              });
                                          });




            Another example: next-generation JSHint https://github.com/jshint/jshint-next
Strict Mode Checking
                                             Duplicate data property in object
                                             literal not allowed in strict mode

            'use strict';
            block = {
               color: 'blue',
               height: 20,
               width: 10,
               color: 'red'
            };




                       http://ariya.ofilabs.com/2012/03/strict-mode-checks-with-esprima.html
http://ariya.ofilabs.com/2011/08/hall-of-api-shame-boolean-trap.html
“Boolean Trap” Finder

                              var volumeSlider = new Slider(false);
         Obfuscated choice



                              component.setHidden(false);
           Double-negative    filter.setCaseInsensitive(false);




Can you make up your mind?    treeItem.setState(true, false);




                              event.initKeyEvent("keypress", true, true, null, null,
      The more the merrier?       false, false, false, false, 9, 0);
Style Formatter                                     https://github.com/fawek/codepainter




                           Sample code




       Source             CodePainter                    Formatted source


                  Infer coding styles   Indentation
                                        Quote for string literal
                                        Whitespace
https://github.com/Constellation/escodegen
Rewrite and Regenerate
                          answer = 42;



            var syntax = esprima.parse('answer = 42;');
            syntax.body[0].expression.right.value = 1337;
            escodegen.generate(syntax)




                           answer = 1337;
Code Coverage
                                             https://github.com/itay/node-cover
                                             https://github.com/coveraje/coveraje
      x = 42;
                                             https://github.com/pmlopes/coberturajs
      if (false)
          x = -1;




                    http://ariya.ofilabs.com/2012/03/javascript-code-coverage-and-esprima.html
http://itay.github.com/snug_codecoverage_slides/
Instrumentation for Coverage

                                      {
                                          __statement_ZyyqFc(1);
                   var a = 5;
      Statement                           var a = 5;
                                      }


                                      {
                                          __statement_ZyyqFc(2);
      Expression   foo();                 __expression_kC$jur(3), foo();
                                      }




                   function foo() {   function foo() {
      Block            ...                __block_n53cJc(1);
                   };                     ...
                                      }
Non-Destructive Partial Source Modification


                                    Do not remove comments
                         Intact
                                    Preserve indentation & other formatting




                      Modified       Add “contextual” information
                                    Inject or change function invocation
String Literal Quotes                             May need proper escaping


            console.log("Hello")                     console.log('Hello')




                                     List of tokens
        [
              {   type:   "Identifier", value: "console", range: [0, 7] },
              {   type:   "Punctuator", value: ".", range: [7, 8] },
              {   type:   "Identifier", value: "log", range: [8, 11] },
              {   type:   "Punctuator", value: "(", range: [11, 12] },
              {   type:   "String", value: ""Hello"", range: [12, 19] },
              {   type:   "Punctuator", value: ")", range: [19, 19] }
        ]



                             http://ariya.ofilabs.com/2012/02/from-double-quotes-to-single-quotes.html
Tracking the Scalability

            Array.prototype.swap = function (i, j) {
                var k = this[i]; this[i] = this[j]; this[j] = k;
            }




      Array.prototype.swap = function (i, j) {
      Log({ name: 'Array.prototype.swap', lineNumber: 1, range: [23, 94] });
          var k = this[i]; this[i] = this[j]; this[j] = k;
      }




                     http://ariya.ofilabs.com/2012/01/scalable-web-apps-the-complexity-issue.html
Execution Tracing                                                 4640 function calls


                      jQuery Mobile startup log      https://gist.github.com/1823129



         jquery.js     26     jQuery
         jquery.js    103     init                             undefined, undefined, [object Object]
         jquery.js    274     each                             (Function)
         jquery.js    631     each                             [object Object], (Function), undefined
         jquery.js    495     isFunction                       [object Object]
         jquery.js    512     type                             [object Object]
  jquery.mobile.js   1857     [Anonymous]
  jquery.mobile.js    642     [Anonymous]
  jquery.mobile.js    624     enableMouseBindings
  jquery.mobile.js    620     disableTouchBindings




                            http://ariya.ofilabs.com/2012/02/tracking-javascript-execution-during-startup.html
http://esprima.googlecode.com/git-history/harmony/demo/transpile.html
Transpilation

                // Object literal property shorthand.
                function Point(x, y) {
     Harmony        return { x, y };
                }




                                                                       Intact
                // Object literal property shorthand.
       ES 5.1   function Point(x, y) {
                    return { x: x, y: y };
                }


                         Inserted fragment
Application Structure


                                                      Class manifest
Ext.define('My.sample.Person', {
    name: 'Mr. Unknown',
    age: 42,
                                          {
                                               className: 'My.sample.Person',
      constructor: function(name) {},
                                               functions: ['walk', 'run'],
 
                                               properties: ['name', 'age']
      walk: function(steps) {}
                                          }
      run: function(steps) {}

});



                                        http://www.sencha.com/learn/sencha-class-system/
Code Outline   Eclipse




Functions
   Variables
Content Assist (aka Autocomplete, aka “Intellisense”)

                                                       Eclipse




       http://contraptionsforprogramming.blogspot.com/2012/02/better-javascript-content-assist-in.html
Copy Paste Mistake



function inside(point, rect) {
    return (point.x >= rect.x1) && (point.y >= rect.y1) &&
           (point.x <= rect.x2) && (point.y <= rect.y1);
}
                                             Wrong check
Refactoring Helper



    // Add two numbers          // Add two numbers
    function add(firt, two) {   function add(first, two) {
        return firt + two;          return first + two;
    }                           }
Future



                        Tree traversal
    Scope analysis
                         “Richer” syntax tree
Syntax transformation
                        Pattern Matching
Conclusion
Smart editing
                                          Source transformation
   Instrumentation

                            Modern           Minification & obfuscation
                            Parser
Code coverage

                                           Documentation generator

 Conditional contracts
                               Dependency analysis
Thank You!



             ariya.hidayat@gmail.com

             ariya.ofilabs.com

             @AriyaHidayat

Mais conteúdo relacionado

Mais procurados

Java session05
Java session05Java session05
Java session05Niit Care
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedyearninginjava
 
What is new and cool j2se & java
What is new and cool j2se & javaWhat is new and cool j2se & java
What is new and cool j2se & javaEugene Bogaart
 
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...Jorge Hidalgo
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and BytecodeYoav Avrahami
 
The Art of Metaprogramming in Java
The Art of Metaprogramming in Java  The Art of Metaprogramming in Java
The Art of Metaprogramming in Java Abdelmonaim Remani
 
Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Heiko Behrens
 
Java session08
Java session08Java session08
Java session08Niit Care
 
Java Script Patterns
Java Script PatternsJava Script Patterns
Java Script PatternsAllan Huang
 
Using Stratego/XT for generation of software connectors.
Using Stratego/XT for generation of software connectors.Using Stratego/XT for generation of software connectors.
Using Stratego/XT for generation of software connectors.Michal Malohlava
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeOmar Bashir
 
Introduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIIntroduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIwhite paper
 
javascript teach
javascript teachjavascript teach
javascript teachguest3732fa
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaSanjeev Tripathi
 

Mais procurados (19)

Java session05
Java session05Java session05
Java session05
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experienced
 
Introduction to-programming
Introduction to-programmingIntroduction to-programming
Introduction to-programming
 
What is new and cool j2se & java
What is new and cool j2se & javaWhat is new and cool j2se & java
What is new and cool j2se & java
 
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
JavaOne 2014 - CON2013 - Code Generation in the Java Compiler: Annotation Pro...
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and Bytecode
 
The Art of Metaprogramming in Java
The Art of Metaprogramming in Java  The Art of Metaprogramming in Java
The Art of Metaprogramming in Java
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Invoke dynamics
Invoke dynamicsInvoke dynamics
Invoke dynamics
 
Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009Building DSLs with Xtext - Eclipse Modeling Day 2009
Building DSLs with Xtext - Eclipse Modeling Day 2009
 
Java session08
Java session08Java session08
Java session08
 
Java Script Patterns
Java Script PatternsJava Script Patterns
Java Script Patterns
 
Using Stratego/XT for generation of software connectors.
Using Stratego/XT for generation of software connectors.Using Stratego/XT for generation of software connectors.
Using Stratego/XT for generation of software connectors.
 
An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and Runtime
 
Introduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging APIIntroduction to the Java(TM) Advanced Imaging API
Introduction to the Java(TM) Advanced Imaging API
 
javascript teach
javascript teachjavascript teach
javascript teach
 
Core java
Core javaCore java
Core java
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Presentation to java
Presentation  to  javaPresentation  to  java
Presentation to java
 

Semelhante a JavaScript Parser Infrastructure for Code Quality Analysis

Esprima - What is that
Esprima - What is thatEsprima - What is that
Esprima - What is thatAbhijeet Pawar
 
NLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaNLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaMartijn Blankestijn
 
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 IndiaUsing the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 IndiaArun Gupta
 
Using JS to teach JS at Khan Academy
Using JS to teach JS at Khan AcademyUsing JS to teach JS at Khan Academy
Using JS to teach JS at Khan Academyjeresig
 
JavaParser - A tool to generate, analyze and refactor Java code
JavaParser - A tool to generate, analyze and refactor Java codeJavaParser - A tool to generate, analyze and refactor Java code
JavaParser - A tool to generate, analyze and refactor Java codeFederico Tomassetti
 
2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD WorkshopWolfram Arnold
 
Quick Intro To JRuby
Quick Intro To JRubyQuick Intro To JRuby
Quick Intro To JRubyFrederic Jean
 
Algorithm and Programming (Introduction of dev pascal, data type, value, and ...
Algorithm and Programming (Introduction of dev pascal, data type, value, and ...Algorithm and Programming (Introduction of dev pascal, data type, value, and ...
Algorithm and Programming (Introduction of dev pascal, data type, value, and ...Adam Mukharil Bachtiar
 
Metaprogramming in JavaScript
Metaprogramming in JavaScriptMetaprogramming in JavaScript
Metaprogramming in JavaScriptMehdi Valikhani
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponLaurent Duveau
 
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...GeeksLab Odessa
 
Typescript in 30mins
Typescript in 30mins Typescript in 30mins
Typescript in 30mins Udaya Kumar
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponLaurent Duveau
 
Java Intro
Java IntroJava Intro
Java Introbackdoor
 
Java, Ruby & Rails
Java, Ruby & RailsJava, Ruby & Rails
Java, Ruby & RailsPeter Lind
 
javascript
javascript javascript
javascript Kaya Ota
 

Semelhante a JavaScript Parser Infrastructure for Code Quality Analysis (20)

Esprima - What is that
Esprima - What is thatEsprima - What is that
Esprima - What is that
 
NLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaNLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by Ordina
 
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 IndiaUsing the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
 
Intro to J Ruby
Intro to J RubyIntro to J Ruby
Intro to J Ruby
 
Learning typescript
Learning typescriptLearning typescript
Learning typescript
 
Using JS to teach JS at Khan Academy
Using JS to teach JS at Khan AcademyUsing JS to teach JS at Khan Academy
Using JS to teach JS at Khan Academy
 
Java Basic PART I
Java Basic PART IJava Basic PART I
Java Basic PART I
 
JavaParser - A tool to generate, analyze and refactor Java code
JavaParser - A tool to generate, analyze and refactor Java codeJavaParser - A tool to generate, analyze and refactor Java code
JavaParser - A tool to generate, analyze and refactor Java code
 
2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop
 
Quick Intro To JRuby
Quick Intro To JRubyQuick Intro To JRuby
Quick Intro To JRuby
 
Avro
AvroAvro
Avro
 
Algorithm and Programming (Introduction of dev pascal, data type, value, and ...
Algorithm and Programming (Introduction of dev pascal, data type, value, and ...Algorithm and Programming (Introduction of dev pascal, data type, value, and ...
Algorithm and Programming (Introduction of dev pascal, data type, value, and ...
 
Metaprogramming in JavaScript
Metaprogramming in JavaScriptMetaprogramming in JavaScript
Metaprogramming in JavaScript
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret Weapon
 
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
QA Lab: тестирование ПО. Станислав Шмидт: "Self-testing REST APIs with API Fi...
 
Typescript in 30mins
Typescript in 30mins Typescript in 30mins
Typescript in 30mins
 
TypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret WeaponTypeScript: Angular's Secret Weapon
TypeScript: Angular's Secret Weapon
 
Java Intro
Java IntroJava Intro
Java Intro
 
Java, Ruby & Rails
Java, Ruby & RailsJava, Ruby & Rails
Java, Ruby & Rails
 
javascript
javascript javascript
javascript
 

Mais de Ariya Hidayat

Understanding Webkit Rendering
Understanding Webkit RenderingUnderstanding Webkit Rendering
Understanding Webkit RenderingAriya Hidayat
 
Understanding Hardware Acceleration on Mobile Browsers
Understanding Hardware Acceleration on Mobile BrowsersUnderstanding Hardware Acceleration on Mobile Browsers
Understanding Hardware Acceleration on Mobile BrowsersAriya Hidayat
 
Understanding Hardware Acceleration on Mobile Browsers
Understanding Hardware Acceleration on Mobile BrowsersUnderstanding Hardware Acceleration on Mobile Browsers
Understanding Hardware Acceleration on Mobile BrowsersAriya Hidayat
 
Build HTML5 App (Intel Elements 2011)
Build HTML5 App (Intel Elements 2011)Build HTML5 App (Intel Elements 2011)
Build HTML5 App (Intel Elements 2011)Ariya Hidayat
 
Hybrid Apps (Native + Web) via QtWebKit
Hybrid Apps (Native + Web) via QtWebKitHybrid Apps (Native + Web) via QtWebKit
Hybrid Apps (Native + Web) via QtWebKitAriya Hidayat
 
Analyzing the Performance of Mobile Web
Analyzing the Performance of Mobile WebAnalyzing the Performance of Mobile Web
Analyzing the Performance of Mobile WebAriya Hidayat
 
Hybrid Apps (Native + Web) using WebKit
Hybrid Apps (Native + Web) using WebKitHybrid Apps (Native + Web) using WebKit
Hybrid Apps (Native + Web) using WebKitAriya Hidayat
 
Hybrid Apps (Native + Web) using WebKit
Hybrid Apps (Native + Web) using WebKitHybrid Apps (Native + Web) using WebKit
Hybrid Apps (Native + Web) using WebKitAriya Hidayat
 
Efficient Graphics with Qt
Efficient Graphics with QtEfficient Graphics with Qt
Efficient Graphics with QtAriya Hidayat
 
Introduction to QtWebKit
Introduction to QtWebKitIntroduction to QtWebKit
Introduction to QtWebKitAriya Hidayat
 
Writing Tools using WebKit
Writing Tools using WebKitWriting Tools using WebKit
Writing Tools using WebKitAriya Hidayat
 

Mais de Ariya Hidayat (11)

Understanding Webkit Rendering
Understanding Webkit RenderingUnderstanding Webkit Rendering
Understanding Webkit Rendering
 
Understanding Hardware Acceleration on Mobile Browsers
Understanding Hardware Acceleration on Mobile BrowsersUnderstanding Hardware Acceleration on Mobile Browsers
Understanding Hardware Acceleration on Mobile Browsers
 
Understanding Hardware Acceleration on Mobile Browsers
Understanding Hardware Acceleration on Mobile BrowsersUnderstanding Hardware Acceleration on Mobile Browsers
Understanding Hardware Acceleration on Mobile Browsers
 
Build HTML5 App (Intel Elements 2011)
Build HTML5 App (Intel Elements 2011)Build HTML5 App (Intel Elements 2011)
Build HTML5 App (Intel Elements 2011)
 
Hybrid Apps (Native + Web) via QtWebKit
Hybrid Apps (Native + Web) via QtWebKitHybrid Apps (Native + Web) via QtWebKit
Hybrid Apps (Native + Web) via QtWebKit
 
Analyzing the Performance of Mobile Web
Analyzing the Performance of Mobile WebAnalyzing the Performance of Mobile Web
Analyzing the Performance of Mobile Web
 
Hybrid Apps (Native + Web) using WebKit
Hybrid Apps (Native + Web) using WebKitHybrid Apps (Native + Web) using WebKit
Hybrid Apps (Native + Web) using WebKit
 
Hybrid Apps (Native + Web) using WebKit
Hybrid Apps (Native + Web) using WebKitHybrid Apps (Native + Web) using WebKit
Hybrid Apps (Native + Web) using WebKit
 
Efficient Graphics with Qt
Efficient Graphics with QtEfficient Graphics with Qt
Efficient Graphics with Qt
 
Introduction to QtWebKit
Introduction to QtWebKitIntroduction to QtWebKit
Introduction to QtWebKit
 
Writing Tools using WebKit
Writing Tools using WebKitWriting Tools using WebKit
Writing Tools using WebKit
 

Último

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 

Último (20)

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 

JavaScript Parser Infrastructure for Code Quality Analysis

  • 1. JavaScript Parser Infrastructure for Code Quality Analysis Ariya Hidayat Twitter: @AriyaHidayat http://ariya.ofilabs.com
  • 3. Do you...  have a coding style/guidelines?  use code quality tool such as JSLint or JSHint?  actively prevent performance & coverage regressions?  wish you could write your own quality rules?
  • 5. High Quality: Practical Aspects Do not provoke ambiguities Avoid silly mistakes Learn better code pattern Write readable code Improve future maintenance
  • 6. Better Use of the Tools Not everyone is a JavaScript ninja Engineer Tools •Boring •Repetitive Feedback Cycle •Time-consuming
  • 7. From Spelling Checker to Grammar Enforcement Agent Your so wrong, therefore you loose! No misspelled word. Wrong choice of words!
  • 8. Adaptive Quality Criteria Explicit Implicit Customize analysis options Infer from high-quality sample Define new sets of rules Observe the engineer’s behavior
  • 9. Next-Generation Code Quality Tools To boldly analyze what no man has analyzed before...
  • 11. JavaScript in the Browser User Interface Data Persistence Browser Engine Render Engine JavaScript Graphics Networking I/O Engine Stack
  • 12. JavaScript Engine Building Blocks Built-in objects, Runtime host objects, ... Syntax Tree Virtual Source Parser Machine/ Interpreter Fast and conservative
  • 13. Tokenization identifier number var answer = 42; keyword equal sign semicolon
  • 14. Syntax Tree Variable Declaration Identifier Literal Constant answer 42
  • 15. JavaScript Parser Written in JavaScript Esprima UglifyJS Narcissus ZeParser Traceur Es-Lab
  • 16. Produce Correct Output  ECMA-262 compliant 'use strict';  Automatic semicolon insertion var 日本語 = 1  Strict Mode, e.g. “use strict” return 日本語  Unicode for identifiers
  • 17. Heavily Tested  > 500 unit tests  Compatibility tests  100% code coverage  Performance tests Enforced during development
  • 18. Sensible Syntax Tree https://developer.mozilla.org/en/SpiderMonkey/Parser_API { type: "Program", body: [ { type: "ExpressionStatement", expression: { answer = 42 type: "AssignmentExpression", operator: "=", left: { type: "Identifier", name: "answer" }, right: { type: "Literal", value: 42 } http://esprima.org/demo/parse.html } } ] Try online! }
  • 20. Specification, Parser Code, Syntax Tree ECMA-262 Annex A.4 while ( Expression ) Statement function parseWhileStatement() { var test, body;   expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); body = parseStatement();   return { type: Syntax.WhileStatement, test: test, body: body }; }
  • 21. High Performance http://esprima.org/test/compare.html Speed Comparison Chrome 18 Internet Explorer 9 Esprima 233 ms 567 ms UglifyJS parse-js 620 ms 922 ms Benchmark corpus: jQuery, Prototype, MooTools, ExtCore, ...
  • 22. Syntax Node Location { type: "ExpressionStatement", expression: { type: "AssignmentExpression", operator: "=", left: { answer = 42 type: "Identifier", name: "answer", range: [0, 6] }, right: { type: "Literal", value: 42, range: [9, 11] }, range: [0, 11] }, range: [0, 11] }
  • 23. Fit for Code Regeneration https://github.com/Constellation/escodegen Source Esprima Escodegen Source Syntax Tree Shorten variable name Syntax Transformation Automatically inline short function Obfuscate
  • 24. Easily Tweaked LLJS: Low Level JavaScript http://mbebenita.github.com/LLJS/ Block scope let x = 0; let u8 flag; Data types let i32 position; struct Point { int x, y; }; Pointers let u16 *p = q;
  • 25. Error Tolerant Useful for IDE, editors, ... Mismatched quote var msg = "Hello’; Too many dots person..age = 18;   Incomplete, still typing if (person.   Strict mode violation 'use strict'; with (person) { }
  • 26. Handle the Comments // Life, Universe, and Everything answer = 42 comments: [ { range: [0, 34], type: "Line", value: " Life, Universe, and Everything" } ] Documentation tool Code annotation https://github.com/thejohnfreeman/jfdoc https://github.com/goatslacker/node-typedjs
  • 27. Forward Looking Experimental ‘harmony’ branch Object initializer shorthand Destructuring assignment var point = {x, y}; point = {14, 3, 77}; {x, y, z} = point; Module Block scope module MathExtra { // do something { let x; } const y = 0; }
  • 29. Syntax Tree Visualization Block statement http://esprima.org/demo/parse.html
  • 30. Most Popular Keywords this 3229 function 3108 if 3063 return 2878 var 2116 var fs = require('fs'), else 562 esprima = require('esprima'), for 436 files = process.argv.splice(2); new 232   in 225 files.forEach(function (filename) { typeof 188 var content = fs.readFileSync(filename, 'utf-8'), while 143 tokens = esprima.parse(content, { tokens: true }).tokens; case 122   break 115 tokens.forEach(function (token) { try 84 if (token.type === 'Keyword') { catch 84 console.log(token.value); delete 72 } throw 38 }); switch 35 }); continue 25 default 15 instanceof 14 do 12 void 10 finally 4 http://ariya.ofilabs.com/2012/03/most-popular-javascript-keywords.html
  • 31. Most Popular Statements var fs = require('fs'), ExpressionStatement 6728 esprima = require('esprima'), BlockStatement 6353 files = process.argv.splice(2); IfStatement 3063   ReturnStatement 2878 files.forEach(function (filename) { VariableDeclaration 2116 var content = fs.readFileSync(filename, 'utf-8'), syntax = esprima.parse(content); FunctionDeclaration 371   ForStatement 293 JSON.stringify(syntax, function (key, value) { ForInStatement 143 if (key === 'type') { WhileStatement 131 if (value.match(/Declaration$/) || BreakStatement 115 value.match(/Statement$/)) { TryStatement 84 console.log(value); EmptyStatement 66 } } ThrowStatement 38 return value; SwitchStatement 35 }); ContinueStatement 25 }); DoWhileStatement 12 LabeledStatement 6 http://ariya.ofilabs.com/2012/04/most-popular-javascript-statements.html
  • 32. Identifier Length Distribution 750 mean of the identifier length is 8.27 characters 500 prototype-1.7.0.0.js SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING prototype-1.7.0.0.js MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED jquery-1.7.1.js subtractsBorderForOverflowNotVisible jquery.mobile-1.0.js getClosestElementWithVirtualBinding 250 prototype-1.7.0.0.js HAS_EXTENDED_CREATE_ELEMENT_SYNTAX 0 0 5 10 15 20 25 30 35 40 45 http://ariya.ofilabs.com/2012/05/javascript-identifier-length-distribution.html
  • 33. “Code Linting” var fs = require('fs'), esprima = require('./esprima'), files = process.argv.splice(2);   Not a strict equal files.forEach(function (filename) { var content = fs.readFileSync(filename, 'utf-8'), syntax = esprima.parse(content, { loc: true }); if (x == 9) {   // do Something JSON.stringify(syntax, function (key, value) { } if (key === 'test' && value.operator === '==') console.log('Line', value.loc.start.line); return value; }); }); Another example: next-generation JSHint https://github.com/jshint/jshint-next
  • 34. Strict Mode Checking Duplicate data property in object literal not allowed in strict mode 'use strict'; block = { color: 'blue', height: 20, width: 10, color: 'red' }; http://ariya.ofilabs.com/2012/03/strict-mode-checks-with-esprima.html
  • 35. http://ariya.ofilabs.com/2011/08/hall-of-api-shame-boolean-trap.html “Boolean Trap” Finder var volumeSlider = new Slider(false); Obfuscated choice component.setHidden(false); Double-negative filter.setCaseInsensitive(false); Can you make up your mind? treeItem.setState(true, false); event.initKeyEvent("keypress", true, true, null, null, The more the merrier? false, false, false, false, 9, 0);
  • 36. Style Formatter https://github.com/fawek/codepainter Sample code Source CodePainter Formatted source Infer coding styles Indentation Quote for string literal Whitespace
  • 37. https://github.com/Constellation/escodegen Rewrite and Regenerate answer = 42; var syntax = esprima.parse('answer = 42;'); syntax.body[0].expression.right.value = 1337; escodegen.generate(syntax) answer = 1337;
  • 38. Code Coverage https://github.com/itay/node-cover https://github.com/coveraje/coveraje x = 42; https://github.com/pmlopes/coberturajs if (false) x = -1; http://ariya.ofilabs.com/2012/03/javascript-code-coverage-and-esprima.html
  • 39. http://itay.github.com/snug_codecoverage_slides/ Instrumentation for Coverage { __statement_ZyyqFc(1); var a = 5; Statement var a = 5; } { __statement_ZyyqFc(2); Expression foo(); __expression_kC$jur(3), foo(); } function foo() { function foo() { Block ... __block_n53cJc(1); }; ... }
  • 40. Non-Destructive Partial Source Modification Do not remove comments Intact Preserve indentation & other formatting Modified Add “contextual” information Inject or change function invocation
  • 41. String Literal Quotes May need proper escaping console.log("Hello") console.log('Hello') List of tokens [ { type: "Identifier", value: "console", range: [0, 7] }, { type: "Punctuator", value: ".", range: [7, 8] }, { type: "Identifier", value: "log", range: [8, 11] }, { type: "Punctuator", value: "(", range: [11, 12] }, { type: "String", value: ""Hello"", range: [12, 19] }, { type: "Punctuator", value: ")", range: [19, 19] } ] http://ariya.ofilabs.com/2012/02/from-double-quotes-to-single-quotes.html
  • 42. Tracking the Scalability Array.prototype.swap = function (i, j) { var k = this[i]; this[i] = this[j]; this[j] = k; } Array.prototype.swap = function (i, j) { Log({ name: 'Array.prototype.swap', lineNumber: 1, range: [23, 94] }); var k = this[i]; this[i] = this[j]; this[j] = k; } http://ariya.ofilabs.com/2012/01/scalable-web-apps-the-complexity-issue.html
  • 43. Execution Tracing 4640 function calls jQuery Mobile startup log https://gist.github.com/1823129 jquery.js 26 jQuery jquery.js 103 init undefined, undefined, [object Object] jquery.js 274 each (Function) jquery.js 631 each [object Object], (Function), undefined jquery.js 495 isFunction [object Object] jquery.js 512 type [object Object] jquery.mobile.js 1857 [Anonymous] jquery.mobile.js 642 [Anonymous] jquery.mobile.js 624 enableMouseBindings jquery.mobile.js 620 disableTouchBindings http://ariya.ofilabs.com/2012/02/tracking-javascript-execution-during-startup.html
  • 44. http://esprima.googlecode.com/git-history/harmony/demo/transpile.html Transpilation // Object literal property shorthand. function Point(x, y) { Harmony return { x, y }; } Intact // Object literal property shorthand. ES 5.1 function Point(x, y) { return { x: x, y: y }; } Inserted fragment
  • 45. Application Structure Class manifest Ext.define('My.sample.Person', { name: 'Mr. Unknown',   age: 42, { className: 'My.sample.Person', constructor: function(name) {}, functions: ['walk', 'run'],   properties: ['name', 'age'] walk: function(steps) {} } run: function(steps) {} }); http://www.sencha.com/learn/sencha-class-system/
  • 46. Code Outline Eclipse Functions Variables
  • 47. Content Assist (aka Autocomplete, aka “Intellisense”) Eclipse http://contraptionsforprogramming.blogspot.com/2012/02/better-javascript-content-assist-in.html
  • 48. Copy Paste Mistake function inside(point, rect) { return (point.x >= rect.x1) && (point.y >= rect.y1) && (point.x <= rect.x2) && (point.y <= rect.y1); } Wrong check
  • 49. Refactoring Helper // Add two numbers // Add two numbers function add(firt, two) { function add(first, two) { return firt + two; return first + two; } }
  • 50. Future Tree traversal Scope analysis “Richer” syntax tree Syntax transformation Pattern Matching
  • 52. Smart editing Source transformation Instrumentation Modern Minification & obfuscation Parser Code coverage Documentation generator Conditional contracts Dependency analysis
  • 53. Thank You! ariya.hidayat@gmail.com ariya.ofilabs.com @AriyaHidayat