Mark Daggett's Blog

Innovator & Bricoleur

Javascript ParseTrees

I’ve been experimenting with the rkelly Ruby gem to help me explore the JavaScript parse tree. It is really fascinating, and I can see myself spending a lot of time spelunking through the language. Here is a simple example using the gem to iterate over each node in the parse tree and print out its type. Stay tuned, more to come!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
require 'rubygems'
require 'rkelly'
parser = RKelly::Parser.new
src = <<EOF
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
  var top = "pageYOffset" === prop;

  jQuery.fn[ method ] = function( val ) {
    return jQuery.access( this, function( elem, method, val ) {
      var win = getWindow( elem );

      if ( val === undefined ) {
        return win ? win[ prop ] : elem[ method ];
      }

      if ( win ) {
        win.scrollTo(
          !top ? val : window.pageXOffset,
          top ? val : window.pageYOffset
        );

      } else {
        elem[ method ] = val;
      }
    }, method, val, arguments.length, null );
  };
});

function getWindow( elem ) {
  return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}
EOF
ast = parser.parse(src)

=begin
Outputs something like this as it traverses the parseTree
RKelly::Nodes::SourceElementsNode
RKelly::Nodes::ExpressionStatementNode
RKelly::Nodes::FunctionCallNode
RKelly::Nodes::DotAccessorNode
RKelly::Nodes::ResolveNode
RKelly::Nodes::ArgumentsNode
RKelly::Nodes::ObjectLiteralNode
RKelly::Nodes::PropertyNode
...
=end

ast.each do |node|
  puts node.class
end

Like this post, then you'll love my book on JavaScript.

Expert JavaScript is your definitive guide to understanding how and why JavaScript behaves the way it does. Master the inner workings of JavaScript by learning in detail how modern applications are made. In covering lesser-understood aspects of this powerful language and truly understanding how it works, your JavaScript code and programming skills will improve.

Comments