Upgrade to Pro — share decks privately, control downloads, hide ads and more …

JavaScript Syntax Tree Demystified

JavaScript Syntax Tree Demystified

Presented at jQuery SF 2015 in San Francisco.

The structure of any valid JavaScript program can be represented by a syntax tree. In this talk, we will cover the basics of syntax parsing process using Esprima and the popular abstract syntax tree format ESTree. Among other benefits, such a syntax tree can be used to perform any syntactical analysis on the code. This talk will continue to cover the use of Esprima in JSCS, a popular tool to check and enforce coding style for JavaScript program.

Ariya Hidayat

June 23, 2015
Tweet

More Decks by Ariya Hidayat

Other Decks in Programming

Transcript

  1. SpiderMonkey Reflect.js Esprima Escodegen Escope Esmangle Istanbul Acorn Babel JSCS

    js2coffee Webpack ast-query recast falafel ESLint Esformatter Jsfmt Require.js Blanket MetaJS Ibrik JSDoc Rocambole JSComplexity Plato
  2. var answer = 42; var answer = 42; var answer

    = 42 ; var answer = 42 ; same tokens
  3. var answer = 42; alert(answer); Program Variable Declaration Call Expression

    Initializer Identifier answer 42 Arguments Identifier alert answer
  4. Stray Logging function detect_console(code) { function check(node) { if (node.type

    === 'CallExpression') { if (node.callee.type === 'MemberExpression') { if (node.callee.object.name === 'console') { alert('console call at line', node.loc.start.line); } } } } var tree = esprima.parse(code, { loc: true }); estraverse.traverse(tree, { enter:check }); } http://ariya.ofilabs.com/2013/04/automagic-removal-of-javascript-logging.html
  5. A Note on Style... “Arguments over style are pointless. There

    should be a style guide, and you should follow it” - Rebecca Murphey “Have the robots do it.” - Someone, probably.
  6. Inspecting The Tree var answer = 6 * 7; literal

    literal 6 7 var answer=6*7 Binary Expression Variable Declaration Identifier answer *
  7. Using Ranges literal literal 6 7 var answer = 6

    * 7; Binary Expression * range: 13-18 range: 13-14 range: 17-18
  8. Using Ranges literal literal 6 7 var answer = 6*

    7; Binary Expression * range: 13-18 range: 13-14 range: 17-18
  9. Using Tokens literal literal 6 7 * range: 13-14 range:

    17-18 6 7 * 13-14 17-18 ... Tokens Tree 14-15