Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Code generator, generates a C program that prints the first 100 integers.
- def printGenerator(gen):
- for line in gen:
- print(line)
- def generateCProgram(headers,functions):
- for line in headers:
- yield line
- for function in functions:
- if function.implemented:
- yield ''
- for statement in function.yieldStatement():
- yield statement
- def headerInclude(name):
- return '#include<' + name + '>'
- class CSymbol:
- symbolTable = {}
- def __init__(self,name):
- if name[-1].isdigit():
- raise ValueError("Invalid variable name: " + name + " , cannot end with digit!")
- self.rawname = name
- if name in self.symbolTable:
- self.symbolTable[name] += 1
- self.name = name + str(symbolTable[name])
- else:
- self.symbolTable[name] = 0
- self.name = name
- def __str__(self):
- return self.name
- class CVariable(CSymbol):
- def __init__(self,name,vartype):
- super().__init__(name)
- self.type = vartype
- class CFunction(CSymbol):
- def __init__(self,name,returntype):
- super().__init__(name)
- self.returntype = returntype
- self.implemented = False
- def call(self,*args): # Todo: Implement some form of preliminary type checking.
- output = self.__str__() + '('
- for i,arg in enumerate(args):
- if i > 0:
- output += ' ,'
- output += str(arg)
- output += ')'
- return output
- def implementFunction(self,parameters,body): # Expects a CBlock as the body argument.
- self.parameters = parameters
- self.body = body
- self.implemented = True
- def yieldStatement(self): # For printing the function implementation body.
- if not self.implemented:
- raise Error("Function not implemented.")
- top = self.returntype + ' ' + self.name + '('
- for i,parameter in enumerate(self.parameters):
- if i > 0:
- top += ' ,'
- top += parameter.type + ' ' + parameter.name
- top += ')'
- yield top
- for statement in self.body.yieldStatement():
- yield statement
- class CBlock():
- def __init__(self,*args):
- self.statements = list(args)
- def addStatement(self,statement):
- self.statements.append(statement)
- def yieldStatement(self):
- yield '{'
- for statement in self.statements:
- yield statement
- yield '}'
- class ExprStatement:
- def __init__(self,expr):
- self.expr = expr
- def __str__(self):
- return self.expr.__str__() + ';'
- ## Script part starts here:
- cprintf = CFunction('printf','void')
- printnumber = CFunction('printnumber','void')
- pnnumber = CVariable("number",'int')
- printnumber.implementFunction([pnnumber],
- CBlock(
- ExprStatement(cprintf.call("%f",pnnumber))
- ))
- main = CFunction('main','void')
- mainblock = CBlock()
- for i in range(1,101):
- mainblock.addStatement(ExprStatement(printnumber.call(i)))
- main.implementFunction([],mainblock)
- printGenerator(generateCProgram([headerInclude("stdio")],[printnumber,main]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement