view python/ir/builder.py @ 257:703321743e8a

Fixed readme
author Windel Bouwman
date Sun, 04 Aug 2013 18:34:06 +0200
parents e41e4109addd
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)