view python/ir/builder.py @ 249:e41e4109addd

Added current position arrow
author Windel Bouwman
date Fri, 26 Jul 2013 20:26:05 +0200
parents ef683881c64e
children 5ec7580976d9
line wrap: on
line source

from . import Value, BasicBlock, Function, Variable

class NameGenerator:
   def __init__(self, prefix):
      self.prefix = prefix
      def NumGen():
         a = 0
         while True:
            yield a
            a = a + 1
      self.nums = NumGen()
   def gen(self, prefix=None):
      if not prefix:
         prefix = self.prefix
      return '{0}{1}'.format(prefix, self.nums.__next__())

class ValueGenerator(NameGenerator):
   def __init__(self):
      super().__init__('t')
   def gen(self, prefix=None):
      v = Value(super().gen(prefix))
      return v

class BBGenerator(NameGenerator):
   def __init__(self):
      super().__init__('lab')
   def gen(self):
      v = BasicBlock(super().gen())
      return v

class Builder:
    def __init__(self):
      self.newTmp = ValueGenerator().gen
      self.newBBint = BBGenerator().gen
      self.bb = None
      self.m = None
      self.fn = None
      self.loc = None

    # Helpers:
    def newBB(self):
      bb = self.newBBint()
      self.fn.addBB(bb)
      return bb

    def setModule(self, m):
      self.m = m

    def newFunction(self, name):
      f = Function(name)
      self.m.addFunc(f)
      return f

    def newVariable(self, name):
        v = Variable(name)
        self.m.addVariable(v)
        return v

    def setFunction(self, f):
      self.fn = f

    def setBB(self, bb):
      self.bb = bb

    def setLoc(self, l):
        self.loc = l

    def addIns(self, i):
        i.debugLoc = self.loc
        if not self.bb:
            raise Exception('No basic block')
        self.bb.addInstruction(i)