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.

0284b8950e0f4a57bcc092d4dbb98d97?s=128

Ariya Hidayat

June 23, 2015
Tweet

Transcript

  1. 5.

    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. 6.
  3. 12.

    var answer = 42; var answer = 42; var answer

    = 42 ; var answer = 42 ; same tokens
  4. 14.

    var answer = 42; alert(answer); Program Variable Declaration Call Expression

    Initializer Identifier answer 42 Arguments Identifier alert answer
  5. 16.

    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
  6. 18.

    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.
  7. 20.

    Inspecting The Tree var answer = 6 * 7; literal

    literal 6 7 var answer=6*7 Binary Expression Variable Declaration Identifier answer *
  8. 21.
  9. 22.
  10. 23.

    Using Ranges literal literal 6 7 var answer = 6

    * 7; Binary Expression * range: 13-18 range: 13-14 range: 17-18
  11. 24.

    Using Ranges literal literal 6 7 var answer = 6*

    7; Binary Expression * range: 13-18 range: 13-14 range: 17-18
  12. 25.
  13. 26.

    Using Tokens literal literal 6 7 * range: 13-14 range:

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