Writing a custom node visitor with SlimIt

by Ruslan Spivak on December 17, 2011

I’ve added a base node visitor class ASTVisitor to SlimIt to reduce some boilerplate code required for writing a custom node visitor.

The class itself is pretty simple and contains just two methods:

  • a visit method that you want to call to process all node’s children and
  • a generic_visit method that acts as a fallback when your visitor doesn’t know how to visit a particular node

Let’s say that you want to parse a JavaScript object literal. In order to do that your visitor has to inherit from ASTVisitor and add a visit_Object method. One thing to note here is a signature of the method: def visit_NodeType(self, node) where NodeType is the type of a node you want to visit. For a full list of available node types check out ast.py module on GitHub

With that said the code to visit an object literal with our own node visitor now would look like this:

>>> from slimit.parser import Parser
>>> from slimit.visitors.nodevisitor import ASTVisitor
>>>
>>> text = """
... var x = {
...     "key1": "value1",
...     "key2": "value2"
... };
... """
>>>
>>> class MyVisitor(ASTVisitor):
...     def visit_Object(self, node):
...         """Visit object literal."""
...         for prop in node:
...             left, right = prop.left, prop.right
...             print 'Property key=%s, value=%s' % (left.value, right.value)
...             # visit all children in turn
...             self.visit(prop)
...
>>>
>>> parser = Parser()
>>> tree = parser.parse(text)
>>> visitor = MyVisitor()
>>> visitor.visit(tree)
Property key="key1", value="value1"
Property key="key2", value="value2"
If you enjoyed this post why not subscribe via email or my RSS feed and get the latest updates immediately. You can also follow me on GitHub or Twitter.

Speak your mind

Previous post:

Next post: