view python/ir/builder.py @ 192:6cd6260789a1

Added more tests for parser generator
author Windel Bouwman
date Sun, 26 May 2013 23:19:27 +0200
parents 46d62dadd61b
children de3a68f677a5
line wrap: on
line source

from . import Value, BasicBlock, Function

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

   # Helpers:
   def newBB(self):
      bb = self.newBBint()
      self.fn.addBB(bb)
      return bb
   def setModule(self, m):
      self.m = m
   def newFunc(self, name):
      f = Function(name)
      self.m.addFunc(f)
      return f
   def setFunc(self, f):
      self.fn = f
   def setBB(self, bb):
      self.bb = bb
   def addIns(self, i):
      if not self.bb:
            raise Exception('No basic block')
      self.bb.addIns(i)