view python/graph.py @ 270:cdc76d183bcc

first register allocator
author Windel Bouwman
date Mon, 19 Aug 2013 21:14:28 +0200
parents 5f8c04a8d26b
children ea93e0a7a31e
line wrap: on
line source


class Graph:
    """
       Generic graph base class.
       Can dump to graphiz dot format for example!
    """
    def __init__(self):
        self.nodes = []
        self.edges = []

    def newNode(self):
        n = Node(self)
        self.nodes.append(n)
        return n

    def addEdge(self, n, m):
        """ Add an edge from n to m """
        if (n, m) not in self.edges and (m, n) not in self.edges:
            self.edges.append((n, m))
            n.succ.append(m)
            m.pred.append(n)

    def delEdge(self):
        # TODO
        pass
        
    def to_dot(self, f):
        """ Generate graphviz dot representation """
        print('digraph G {', file=f)
        for node in self.nodes:
            print('{} [label="{}" shape=box3d];'.format(id(node), node), file=f)
        for n, m in self.edges:
            print('{} -> {};'.format(id(n), id(m)), file=f)
        print('}', file=f)


class Node:
    """
       Node in a graph.
    """
    def __init__(self, g):
        self.g = g
        self.succ = []
        self.pred = []

    @property
    def Adj(self):
        return set(self.succ) | set(self.pred)