Skip to content

Instantly share code, notes, and snippets.

@devdave
Created January 13, 2012 16:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devdave/1607354 to your computer and use it in GitHub Desktop.
Save devdave/1607354 to your computer and use it in GitHub Desktop.
Truncated base visitor class
class Visitor(object):
CHILD_ATTRS = ['value', 'thenPart', 'elsePart', 'expression', 'body','exception', 'initializer', 'tryBlock', 'condition','update', 'iterator', 'object', 'setup', 'discriminant', 'finallyBlock', 'tryBlock', 'varDecl', 'target']
def __init__(self, filepath):
self.filepath = filepath
#List of functions by line # and set of names
self.functions = defaultdict(set)
with open(filepath) as myFile:
self.source = myFile.read()
self.visited = list()
self.root = jsparser.parse(self.source, self.filepath)
self.initialize()
self.visit(self.root)
def initialize(self):
pass
def look4Childen(self, node):
for attr in self.CHILD_ATTRS:
child = getattr(node, attr, None)
if isinstance(child, jsparser.Node):
self.visit(child)
def visit_ANY(self, node):
pass
def visit(self, root):
if id(root) in self.visited: return
self.visited.append(id(root))
call = lambda n: getattr(self, "visit_%s" % n.type, self.visit_ANY)(n)
call(root)
self.look4Childen(root)
for node in root:
self.visit(node)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment