Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

The base class of an AST is the Node:

#!python

class Node(object):
    """Abstract base class for ast nodes."""
    def getChildren(self):
        pass # implemented by subclasses
    def __iter__(self):
        for n in self.getChildren():
            yield n
    def getChildNodes(self):
        pass # implemented by subclasses

    def accept(self, visitor):
        raise NotImplementedError
    #...

and here a possible subclass

#!python
class Stmt(Node):
    def __init__(self, nodes, lineno=None):
        self.nodes = nodes
        self.lineno = lineno

    def getChildren(self):
        return tuple(flatten(self.nodes))

    def getChildNodes(self):
        nodelist = []
        nodelist.extend(flatten_nodes(self.nodes))
        return tuple(nodelist)

    def accept(self, visitor):
        return visitor.visitStmt(self)

    #...

All the nodes have an "accept" function that takes a visitor instance.

An example of AST Visitor that simply traverse the tree doing nothing

#!python
class ASTVisitor(object):

    def default(self, node):
        for child in node.getChildNodes():
            child.accept(self)

    def visitExpression(self, node):
        return self.default(node)
    def visitEmptyNode(self, node):
        return self.default(node)
    def visitAdd(self, node):
        return self.default( node )
    def visitAnd(self, node):
        return self.default( node )
    # ... and so on for each node type

Of course this could be done in a more dynamic way, but this form should be more simple to understand.

Something went wrong with that request. Please try again.