class TestModule_Architecture(unittest.TestCase): '''Unit Test for the Utils module''' def setUp(self): self.arch1 = Architecture("AVR8") self.arch2 = Architecture("AVR8") self.arch3 = Architecture("x86") self.arch1.setCompiler("gcc") def test_equality(self): # Check the equality operator is correctly overloaded self.assertTrue(self.arch1 == self.arch1) # This should catch that even though the two architectures have the same name, # they aren't the same as arch1 has it's compiler defined and arch2 doesn't self.assertFalse(self.arch1 == self.arch2)
def main(): logger.basicConfig(level=logger.DEBUG) logBanner() # mainThread = Thread.currentThread() st = stats_tracker.StatsTracker() stats = st.getInstance() opts = options.parseOptions() try: arch = Architecture.Architecture(opts.sslFilename) except OSError as e: logger.critical('Unable to open SSL file!', e) return except: logger.critical('Error parsing SSL file!', e) return overallStartTime = time.time() _program = program.create_program(arch) mainfile = os.path.abspath(opts.mainFilename) basefilename = None try: logger.warning("Parsing " + opts.mainFilename + "...") _program.load_main_module(mainfile) if basefilename == None: basefilename = get_base_filename(mainfile) except OSError as e: logger.critical('File not found: ', e) return except IOError as e: logger.critical('IOException while parsing executable!', e) return except Exception as e: logger.critical('Error during parsing', e) return logger.info('Finished parsing executable') if opts.startAddress > 0: logger.log("Setting start address to 0x" + hex(opts.startAddress)) _program.set_entry_address( absolute_address(opt.startAddress.getValue()))
class Shemas: ipgen = Architecture() shema1 = [["1", "2"]] shema2 = [["1", "3"], ["3", "2"]] shema3 = [["1", "2", "4"], ["2", "3", "5"], ["4", "5", "6", "7"]] shema4 = [["1", "2", "4"], ["2", "3", "6"], ["4", "5", "7"], ["8", "5", "6"]] shemaIp1 = ipgen.architecture("192.168.0.0/24", "300,25") shemaIp2 = ipgen.architecture("192.168.0.0/24","200,30,2") shemaIp3 = ipgen.architecture("192.168.0.0/24", "500,400,350,200,2,2,2") shemaIp4 = ipgen.architecture("192.168.0.0/24", "1000,700,300,80,2,2,2,2")
def init(): import numpy as np import Architecture import BluetoothSender import BluetoothListener global device global BTL global BTS global online global bluetoothPaused global isprojector global initfdir global initddir global tfuncdir global settings_dir global screenshot_dir global camMatrix global camMat4x4 global imageXDist global imageYDist global imageZDist device = Architecture.get() online = False #this is used by the handler for the close button also BTL = BluetoothListener.BluetoothListener() BTS = BluetoothSender.BluetoothSender() isprojector = False initfdir = '' initddir = '' tfuncdir = '../Presets\\TransferFunctions\\' settings_dir = 'settings' screenshot_dir = 'screenshots' camMatrix = np.array([ 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.541127, -0.840941, 0.000000, 0.000000, 0.840941, 0.541127, 0.000000, 0.000000, 0.000000, 0.000000, 1.000000 ]) camMat4x4 = np.reshape(camMatrix, (4, 4)) #Represents dimensions of imported image imageXDist = 0 imageYDist = 0 imageZDist = 0
params.add_integer("max_length", 200) # Max length of input. params.print() with tf.Session() as sess: start = time.time() # for counting the time # TRAINING # arch = Architecture.Arch(sess, params, testingModel) # arch.training() # TESTING langs = None # langs = ['ces', 'eng', 'fra', 'deu', 'spa'] arch = Architecture.Arch(sess, params, testingModel, prepare_train_set=False) # not optimised at all # arch.evaluate_dataset("test/LanideNN_testset", langs) # The LanideNN can recognize every character, but this function only # evaluates whole sentence arch.evaluate_string('Text reading assistance: 昨日すき焼きを食べました.', True, ['jpn','eng']) arch.evaluate_string('El chico no tiene en la cabeza nada más que el negocio. Der Junge hat ja nichts im Kopf als das Geschäft.', True, ['deu', 'spa']) arch.evaluate_string('La signora lesse il messaggio e volse a Daisy uno sguardo di intesa. The lady read the message and looked up at Daisy in a knowing way.', True, ['ita','eng']) arch.evaluate_string("At that time of night there were few people around. A cette heure de la nuit il n'y avait pas grand monde aux alentours.", True, ['fra','eng']) arch.evaluate_string('Eravamo tre contro uno, però; e la mozione fu approvata. Men omröstningen utföll tre mot en dock, sa förslaget bifölls.', True, ['ita','swe']) arch.evaluate_string('Ich sag Gute Nacht. And I say good night. Schon leuchtet ein Stern. Yes, I see the light.', True, ['deu', 'eng']) print("Script finished in " + str(int(time.time() - start)) + " s")
def setUp(self): self.arch1 = Architecture("AVR8") self.arch2 = Architecture("AVR8") self.arch3 = Architecture("x86") self.arch1.setCompiler("gcc")
from Architecture import * if __name__ == '__main__': process = Architecture() process.start()
with open(file_path, 'r', encoding='utf-8') as f: data = [line.split() for line in f.readlines()] except: with open(file_path, 'r', encoding='utf-8') as f: data = [line.split() for line in f.readlines()] sentences.extend(data) labels.extend([label] * len(data)) label += 1 print("\n--------Building essays completed!----------\n") essays = Eassy.Eassy(sentences, labels) essays.E2V() print("\n--------Calculating essay vectors completed!----------\n") train_x, test_x, train_y, test_y = essays.split() rnn = Architecture.Representation(64, 64, 64) # loss function loss_fun = torch.nn.CrossEntropyLoss() opt = torch.optim.Adam(rnn.parameters(), lr=0.01) print("\n--------Starting train!----------\n") acclist = [] for epoch in range(200): lab = [] pred = [] for essay, label in zip(train_x, train_y): essay = torch.unsqueeze(essay, 0) essay = torch.unsqueeze(essay, 0) essay = essay.float() label = torch.tensor([label])
acc = Acc(pred,label) accList[step].append(acc) print("\n<<-----epoch:{0} batch:{1} | batch_x_size:{2} | loss:{3:.3f} | acc:{4:.3f}----->>\n".format(epoch,step,batch_x.size(),loss,acc)) loss.backward() opt.step() plt.plot(range(1,iter+1),accList[0],marker='*',mec='b',mfc='w') plt.plot(range(1,iter+1),accList[1],marker='s',mec='g',mfc='w') plt.xlabel("epoch") plt.ylabel("acc") plt.legend() plt.show() if __name__ == "__main__": train_loader,dataLen_train,test_loader,dataLen_test = load_data() print("dataLen: ",dataLen_train) model = Architecture.Representation(5, dataLen_train) loss_fun = torch.nn.CrossEntropyLoss() opt = torch.optim.Adam(model.parameters(), lr=0.001) train(train_loader,300) for step, (batch_x, batch_y) in enumerate(test_loader): test = model.eval() out = test(test_loader) out = out.view(-1, out.shape[2]) # print(out) pred = torch.max(out, 1)[1].data.numpy() print(pred) batch_y = batch_y.view(-1) loss = loss_fun(out, batch_y) label = numpy.asarray(batch_y, dtype=int, order=None) print(label)
def __init__(self): self.ImmediateCode = [] # unoptimized immediate code self.ImmediateCodeOptimized = [] # optimized immediate code self.Variables = [] self.ArchOutput = Architecture() # type: # while begin of a while loop # statement statement of the header # body the body of the while loop (is a list) # number (statement) only a number # value the value of the number # TODO< remove this > # assigment asign a new value to a number # variable the name of the target variable # statement a statement for the assigment of a new value # assigment2 assign the right side to the left # left leftside # right rightside # minusAssigment -= # left leftside # right rightside # variable access a variable # name the name of the variable # mul multiplication # left leftside # right rightside # div division # left leftside # right rightside # add addition # left leftside # right rightside # sub subtraction # left leftside # right rightside # if if thing # statement the statement # block the contained block # else None or another block with the else part # true (statement) # false (statement) # greaterEqual (statement) # left leftside # right rightside # TODO< smallerEqual, Equal, Unequal, Smaller, Greater > # break break expression # postinc (statement) # statement # preinc (statement) # statement # postdec (statement) # statement # preinc (statement) # statement # return (statement) # expression is the expression that have to be avaluated, can also be not set (None) # expressionSet was the Expression set (True or False) # newConstArray creates a new constant unchangable array # name is the name of the array # info Typeinformation, is a 'Datatype' Object # newVar2 allocates space for a new (scoped) variable # name is the Variablename # info Typeinformation, is a 'Datatype' Object # constantFloat is a contant float # value is the floatingpoint value """ self.Root = [ {"type":"newVar", "name":"Counter", "dataType":0,"bits":32}, {"type":"assigment2", "left":{"type":"variable", "name":"Counter"}, "right":{"type":"number", "value":20}}, {"type":"newVar", "name":"Xn", "dataType":0, "bits":32}, {"type":"assigment2", "left":{"type":"variable", "name":"Xn"}, "right":{"type":"number", "value":5}}, {"type":"newVar", "name":"Number", "dataType":0, "bits":32}, {"type":"assigment2", "left":{"type":"variable", "name":"Number"}, "right":{"type":"number", "value":500}}, {"type":"while", "statement":{"type":"number", "value":1}, "body":[ {"type":"minusAssignment", "left":{"type":"variable", "name":"Counter"}, "right":{"type":"number", "value":1}}, {"type":"assigment2", "left":{"type":"variable", "name":"Xn"}, "right":{ "type":"div", "left":{"type":"add", "left":{"type":"variable", "name":"Xn"}, "right":{"type":"div", "left":{"type":"variable", "name":"Number"}, "right":{"type":"variable", "name":"Xn"}}}, "right":{"type":"number", "value":2} }} ]} ]""" # algorithm for calculating of the sqrt # (examples/calc my sqrt) # (is a serial code) # works """ Type1 = Datatype(Datatype.EnumBasetype.UNSIGNED) Type1.Bits = 32 Type2 = Datatype(Datatype.EnumBasetype.UNSIGNED) Type2.Bits = 32 Type3 = Datatype(Datatype.EnumBasetype.UNSIGNED) Type3.Bits = 32 self.Root = [ {"type":"newVar2", "name":"Input", "info":Type1}, {"type":"assigment2", "left":{"type":"variable", "name":"Input"}, "right":{"type":"number", "value":29}}, {"type":"newVar2", "name":"Counter", "info":Type2}, {"type":"assigment2", "left":{"type":"variable", "name":"Counter"}, "right":{"type":"number", "value":0}}, {"type":"newVar2", "name":"Old", "info":Type3}, {"type":"assigment2", "left":{"type":"variable", "name":"Old"}, "right":{"type":"number", "value":0}}, {"type":"while", "statement":{"type":"true"}, "body":[ {"type":"assigment2", "left":{"type":"variable", "name":"Old"}, "right":{ "type":"add", "left":{"type":"variable", "name":"Old"}, "right":{ "type":"add", "left":{"type":"mul", "left":{"type":"number", "value":2}, "right":{"type":"variable", "name":"Counter"}}, "right":{"type":"number", "value":1} } }}, { "type":"if", "statement":{"type":"greaterEqual", "left":{"type":"variable", "name":"Old"}, "right":{"type":"variable", "name":"Input"}}, "block":[ {"type":"break"} ] }, { "type":"postinc", "statement":{"type":"variable", "name":"Counter"} } ]} ] """ # cordic algorithm """ const fixed6p12 ATanTable[1] = [0.7853981633974483 , 0.4636476090008061, 0.24497866312686414, 0.12435499454676144, 0.06241880999595735, 0.031239833430268277, 0.015623728620476831]; """ """ Type1 = Datatype(Datatype.EnumBasetype.FIXEDPOINT) # fixedpoint Datatype Type1.PrePointBits = 6 Type1.PostPointBits = 12 Type1.IsArray = True Type1.IsConst = True Type1.ArrayValues = [0.7853981633974483 , 0.4636476090008061, 0.24497866312686414, 0.12435499454676144, 0.06241880999595735, 0.031239833430268277, 0.015623728620476831] Type2 = Datatype(Datatype.EnumBasetype.FIXEDPOINT) # fixedpoint Datatype Type2.PrePointBits = 6 Type2.PostPointBits = 12 Type3 = Datatype(Datatype.EnumBasetype.FIXEDPOINT) # fixedpoint Datatype Type3.PrePointBits = 6 Type3.PostPointBits = 12 Type4 = Datatype(Datatype.EnumBasetype.FIXEDPOINT) # fixedpoint Datatype Type4.PrePointBits = 6 Type4.PostPointBits = 12 self.Root = [ {"type":"newConstArray", "name":"ATanTable", "info":Type1}, {"type":"newVar2", "name":"X", "info":Type2}, {"type":"assigment2", "left":{"type":"variable", "name":"X"}, "right":{"type":"constantFloat", "value":4.0}}, {"type":"newVar2", "name":"Y", "info":Type3}, {"type":"assigment2", "left":{"type":"variable", "name":"Y"}, "right":{"type":"constantFloat", "value":1.0}}, {"type":"newVar2", "name":"Phi", "info":Type4}, {"type":"assigment2", "left":{"type":"variable", "name":"Phi"}, "right":{"type":"constantFloat", "value":0.907571}} ] """ # Testcode for the parallelistation code Type1 = Datatype(Datatype.EnumBasetype.UNSIGNED) Type1.Bits = 32 Type2 = Datatype(Datatype.EnumBasetype.UNSIGNED) Type2.Bits = 32 Type3 = Datatype(Datatype.EnumBasetype.UNSIGNED) Type3.Bits = 32 self.Root = [ {"type":"newVar2", "name":"A", "info":Type1}, {"type":"newVar2", "name":"B", "info":Type2}, {"type":"newVar2", "name":"C", "info":Type3}, {"type":"assigment2", "left":{"type":"variable", "name":"A"}, "right":{ "type":"add", "left":{"type":"variable", "name":"A"}, "right":{"type":"add", "left":{"type":"variable", "name":"B"}, "right":{"type":"variable", "name":"C"}} #}} }} ] self.ImmediateCodeObj = ImmediateCode()
class Generator(object): class EnumArchitetureType: PARALLEL = 0 SERIAL = 1 def __init__(self): self.ImmediateCode = [] # unoptimized immediate code self.ImmediateCodeOptimized = [] # optimized immediate code self.Variables = [] self.ArchOutput = Architecture() # type: # while begin of a while loop # statement statement of the header # body the body of the while loop (is a list) # number (statement) only a number # value the value of the number # TODO< remove this > # assigment asign a new value to a number # variable the name of the target variable # statement a statement for the assigment of a new value # assigment2 assign the right side to the left # left leftside # right rightside # minusAssigment -= # left leftside # right rightside # variable access a variable # name the name of the variable # mul multiplication # left leftside # right rightside # div division # left leftside # right rightside # add addition # left leftside # right rightside # sub subtraction # left leftside # right rightside # if if thing # statement the statement # block the contained block # else None or another block with the else part # true (statement) # false (statement) # greaterEqual (statement) # left leftside # right rightside # TODO< smallerEqual, Equal, Unequal, Smaller, Greater > # break break expression # postinc (statement) # statement # preinc (statement) # statement # postdec (statement) # statement # preinc (statement) # statement # return (statement) # expression is the expression that have to be avaluated, can also be not set (None) # expressionSet was the Expression set (True or False) # newConstArray creates a new constant unchangable array # name is the name of the array # info Typeinformation, is a 'Datatype' Object # newVar2 allocates space for a new (scoped) variable # name is the Variablename # info Typeinformation, is a 'Datatype' Object # constantFloat is a contant float # value is the floatingpoint value """ self.Root = [ {"type":"newVar", "name":"Counter", "dataType":0,"bits":32}, {"type":"assigment2", "left":{"type":"variable", "name":"Counter"}, "right":{"type":"number", "value":20}}, {"type":"newVar", "name":"Xn", "dataType":0, "bits":32}, {"type":"assigment2", "left":{"type":"variable", "name":"Xn"}, "right":{"type":"number", "value":5}}, {"type":"newVar", "name":"Number", "dataType":0, "bits":32}, {"type":"assigment2", "left":{"type":"variable", "name":"Number"}, "right":{"type":"number", "value":500}}, {"type":"while", "statement":{"type":"number", "value":1}, "body":[ {"type":"minusAssignment", "left":{"type":"variable", "name":"Counter"}, "right":{"type":"number", "value":1}}, {"type":"assigment2", "left":{"type":"variable", "name":"Xn"}, "right":{ "type":"div", "left":{"type":"add", "left":{"type":"variable", "name":"Xn"}, "right":{"type":"div", "left":{"type":"variable", "name":"Number"}, "right":{"type":"variable", "name":"Xn"}}}, "right":{"type":"number", "value":2} }} ]} ]""" # algorithm for calculating of the sqrt # (examples/calc my sqrt) # (is a serial code) # works """ Type1 = Datatype(Datatype.EnumBasetype.UNSIGNED) Type1.Bits = 32 Type2 = Datatype(Datatype.EnumBasetype.UNSIGNED) Type2.Bits = 32 Type3 = Datatype(Datatype.EnumBasetype.UNSIGNED) Type3.Bits = 32 self.Root = [ {"type":"newVar2", "name":"Input", "info":Type1}, {"type":"assigment2", "left":{"type":"variable", "name":"Input"}, "right":{"type":"number", "value":29}}, {"type":"newVar2", "name":"Counter", "info":Type2}, {"type":"assigment2", "left":{"type":"variable", "name":"Counter"}, "right":{"type":"number", "value":0}}, {"type":"newVar2", "name":"Old", "info":Type3}, {"type":"assigment2", "left":{"type":"variable", "name":"Old"}, "right":{"type":"number", "value":0}}, {"type":"while", "statement":{"type":"true"}, "body":[ {"type":"assigment2", "left":{"type":"variable", "name":"Old"}, "right":{ "type":"add", "left":{"type":"variable", "name":"Old"}, "right":{ "type":"add", "left":{"type":"mul", "left":{"type":"number", "value":2}, "right":{"type":"variable", "name":"Counter"}}, "right":{"type":"number", "value":1} } }}, { "type":"if", "statement":{"type":"greaterEqual", "left":{"type":"variable", "name":"Old"}, "right":{"type":"variable", "name":"Input"}}, "block":[ {"type":"break"} ] }, { "type":"postinc", "statement":{"type":"variable", "name":"Counter"} } ]} ] """ # cordic algorithm """ const fixed6p12 ATanTable[1] = [0.7853981633974483 , 0.4636476090008061, 0.24497866312686414, 0.12435499454676144, 0.06241880999595735, 0.031239833430268277, 0.015623728620476831]; """ """ Type1 = Datatype(Datatype.EnumBasetype.FIXEDPOINT) # fixedpoint Datatype Type1.PrePointBits = 6 Type1.PostPointBits = 12 Type1.IsArray = True Type1.IsConst = True Type1.ArrayValues = [0.7853981633974483 , 0.4636476090008061, 0.24497866312686414, 0.12435499454676144, 0.06241880999595735, 0.031239833430268277, 0.015623728620476831] Type2 = Datatype(Datatype.EnumBasetype.FIXEDPOINT) # fixedpoint Datatype Type2.PrePointBits = 6 Type2.PostPointBits = 12 Type3 = Datatype(Datatype.EnumBasetype.FIXEDPOINT) # fixedpoint Datatype Type3.PrePointBits = 6 Type3.PostPointBits = 12 Type4 = Datatype(Datatype.EnumBasetype.FIXEDPOINT) # fixedpoint Datatype Type4.PrePointBits = 6 Type4.PostPointBits = 12 self.Root = [ {"type":"newConstArray", "name":"ATanTable", "info":Type1}, {"type":"newVar2", "name":"X", "info":Type2}, {"type":"assigment2", "left":{"type":"variable", "name":"X"}, "right":{"type":"constantFloat", "value":4.0}}, {"type":"newVar2", "name":"Y", "info":Type3}, {"type":"assigment2", "left":{"type":"variable", "name":"Y"}, "right":{"type":"constantFloat", "value":1.0}}, {"type":"newVar2", "name":"Phi", "info":Type4}, {"type":"assigment2", "left":{"type":"variable", "name":"Phi"}, "right":{"type":"constantFloat", "value":0.907571}} ] """ # Testcode for the parallelistation code Type1 = Datatype(Datatype.EnumBasetype.UNSIGNED) Type1.Bits = 32 Type2 = Datatype(Datatype.EnumBasetype.UNSIGNED) Type2.Bits = 32 Type3 = Datatype(Datatype.EnumBasetype.UNSIGNED) Type3.Bits = 32 self.Root = [ {"type":"newVar2", "name":"A", "info":Type1}, {"type":"newVar2", "name":"B", "info":Type2}, {"type":"newVar2", "name":"C", "info":Type3}, {"type":"assigment2", "left":{"type":"variable", "name":"A"}, "right":{ "type":"add", "left":{"type":"variable", "name":"A"}, "right":{"type":"add", "left":{"type":"variable", "name":"B"}, "right":{"type":"variable", "name":"C"}} #}} }} ] self.ImmediateCodeObj = ImmediateCode() def doIt(self, ArchitectureType): ReturnedTuple = self.transformObjectsIntoCode(self.Root, 0, 0, []) if ReturnedTuple[0]: print("Compilation successfull") else: print("Compilation Error") print(ReturnedTuple[1]) print("\n\n") print(self.ImmediateCodeObj.debugImmediateCode(self.ImmediateCodeObj.ImmCodeData)) self.ImmediateCode = self.ImmediateCodeObj.ImmCodeData OptimizerObj = Optimizer() OptimizerObj.ImmediateInstructions = self.ImmediateCode OptimizerObj.Variables = self.ImmediateCodeObj.Variables OptimizeAddSubToIncDec = True if ArchitectureType == Generator.EnumArchitetureType.PARALLEL: OptimizeAddSubToIncDec = False OptimizerObj.doOptimization(OptimizeAddSubToIncDec) self.ImmediateCodeOptimized = OptimizerObj.ImmediateInstructions self.Variables = OptimizerObj.Variables print("\n\n") print(self.ImmediateCodeObj.debugImmediateCode(self.ImmediateCodeOptimized)) if ArchitectureType == Generator.EnumArchitetureType.PARALLEL: self.ArchOutput.ImmediateCodeOptimized = self.ImmediateCodeOptimized self.ArchOutput.VariablesOptimized = self.Variables (CalleeSuccess, CalleeMessage) = self.ArchOutput.generateParallelDesign() if not CalleeSuccess: print("Error: " + CalleeMessage) elif ArchitectureType == Generator.EnumArchitetureType.SERIAL: pass else: print("Internal error") return False # "IntoVariable" is the Id of the variable the result must be written into # returns (Success State, Error Message) def evaluateStatement(self, Statement, IntoVariable, IntoDatatype, VariableStack): print(Statement["type"]) if Statement["type"] == "variable": # lookup the variable name (Found, VariableId, VariableDatatype) = self.lookupVariable(VariableStack, Statement["name"]) if not Found: return (False, "Variable " + Statement["name"] + " was not declared!") # check if the types and bits are equal TypeCheckResult = VariableDatatype.compareType(IntoType) if TypeCheckResult == Datatype.EnumTypeResult.DIFFERENTBITS: return (False, "Variable " + Statement["name"] + " don't have matching number of bits!") elif TypeCheckResult == Datatype.EnumTypeResult.DIFFERENTTYPE: return (False, "Variable " + Statement["name"] + " is of wrong type!") elif TypeCheckResult == Datatype.EnumTypeResult.EQUAL: # all right pass else: return (False, "Internal Error #42") self.ImmediateCodeObj.writeMov(IntoVariable, VariableId) return (True, 0) elif Statement["type"] == "number": self.ImmediateCodeObj.writeConstAssigment(IntoVariable, Statement["value"]) return (True, 0) elif (Statement["type"] == "div") or (Statement["type"] == "add") or (Statement["type"] == "mul") or (Statement["type"] == "div"): VarLeft = None VarRight = None # do a simple optimization # if it is a variable, we don't need to create a Temporary Variable, evaluate it and move it into it if Statement["left"]["type"] == "variable": (Found, VarLeft, VarLeftDatatype) = self.lookupVariable(VariableStack, Statement["left"]["name"]) if not Found: return (False, "Variable " + Statement["name"] + " was not declared!") else: VarLeft = self.ImmediateCodeObj.allocateVariable(IntoDatatype) VarLeftDatatype = IntoDatatype (CalleeSuccess, CalleeErrorMessage) = self.evaluateStatement(Statement["left"], VarLeft, VarLeftDatatype, VariableStack) if not CalleeSuccess: return (False, CalleeErrorMessage) # the same for the right side if Statement["right"]["type"] == "variable": (Found, VarRight, VarRightDatatype) = self.lookupVariable(VariableStack, Statement["right"]["name"]) if not Found: return (False, "Variable " + Statement["name"] + " was not declared!") else: VarRight = self.ImmediateCodeObj.allocateVariable(IntoDatatype) VarRightDatatype = IntoDatatype (CalleeSuccess, CalleeErrorMessage) = self.evaluateStatement(Statement["right"], VarRight, VarRightDatatype, VariableStack) if not CalleeSuccess: return (False, CalleeErrorMessage) # check if the types are equal TypeCheckResult = VarLeftDatatype.compareType(VarRightDatatype) if TypeCheckResult == Datatype.EnumTypeResult.DIFFERENTBITS: return (False, "Left and right variables don't have matching number of bits!") elif TypeCheckResult == Datatype.EnumTypeResult.DIFFERENTTYPE: return (False, "Left an right variables are of different type!") elif TypeCheckResult == Datatype.EnumTypeResult.EQUAL: # all right pass else: return (False, "Internal Error #42") if Statement["type"] == "add": self.ImmediateCodeObj.writeAdd(VarLeft, VarRight, IntoVariable) elif Statement["type"] == "sub": self.ImmediateCodeObj.writeSub(VarLeft, VarRight, IntoVariable) elif Statement["type"] == "mul": self.ImmediateCodeObj.writeMul(VarLeft, VarRight, IntoVariable) elif Statement["type"] == "div": self.ImmediateCodeObj.writeDiv(VarLeft, VarRight, IntoVariable) return (True, 0) else: # TODO # return an error print("Eval error") return (False,0) # ScopeType is the Type of the Scope # 0 : inside "main" # 1 : inside a "while" # ReturnLabelId is the Id of the Label a return/break instruction would jump to # VariableStack is a stack with lists of the scoped variables # each Element in the List is a dict with # "name" the name of the variable # "id" the id of the Variable # "info" typeinfo as a 'Datatype' object def transformObjectsIntoCode(self, Objects, ScopeType, ReturnLabelId, VariableStack): VariableStack.append([]) for Object in Objects: print(Object["type"]) if Object["type"] == "newVar2": # check if the variable was allready declared inside this scope for Variable in VariableStack[-1]: if Variable["name"] == Object["name"]: return (False, "Variable '{0}' was allready defined in this scope!".format(Object["name"])) VariableId = self.ImmediateCodeObj.allocateVariable(Object["info"]) # store the variable in the variable stack NewVar = {} NewVar["name"] = Object["name"] NewVar["id"] = VariableId NewVar["info"] = Object["info"] VariableStack[-1].append(NewVar) elif Object["type"] == "assigment": # Emit an error return (False, "Internal Error #2 (Outdated)") elif Object["type"] == "assigment2": # check if on the left is a Variable, if not, emit an error # TODO< here is the right place for a struct lookup for for example a C-expression like "blub.a = ..." or "ax->ab = ..." > if Object["left"]["type"] != "variable": # emit an error return (False, "Internal Error #1 (TODO)") # do the variable lookup (VariableFound, LeftVariableId, LeftVariableInfo) = self.lookupVariable(VariableStack, Object["left"]["name"]) if not VariableFound: # emit syntax error return (False, "Variable " + Object["left"]["name"] + " was not declared!") # evaluate the right statement (CalleeSuccess, CalleeMessage) = self.evaluateStatement(Object["right"], LeftVariableId, LeftVariableInfo, VariableStack) # check for errors of the function call if not CalleeSuccess: # TODO< return better error description > return (False, CalleeMessage) elif Object["type"] == "minusAssignment": # check if on the left is a Variable, if not, emit an error # TODO< here is the right place for a struct lookup for for example a C-expression like "blub.a = ..." or "ax->ab = ..." > if Object["left"]["type"] != "variable": # emit an error return (False, "Internal Error #1 (TODO)") (VariableFound, LeftVariableId, LeftVariableInfo) = self.lookupVariable(VariableStack, Object["left"]["name"]) if not VariableFound: # emit syntax error return (False, "Variable " + Object["left"]["name"] + " was not declared!") # create a new temporary variable TempVar = self.ImmediateCodeObj.allocateVariable(LeftVariableInfo) (CalleeSuccess, CalleeMessage) = self.evaluateStatement(Object["right"], TempVar, LeftVariableInfo, VariableStack) # check for errors if not CalleeSuccess: # TODO< return better error description > return (False, CalleeMessage) self.ImmediateCodeObj.writeSub(LeftVariableId, TempVar, LeftVariableId) elif Object["type"] == "while": LabelIdStart = self.ImmediateCodeObj.getNewLableIdentifier() LabelIdEnd = self.ImmediateCodeObj.getNewLableIdentifier() self.ImmediateCodeObj.writeLable(LabelIdStart) # TODO< emit code for evaluation of the statement > (CalleeSuccess, CalleeMessage) = self.transformObjectsIntoCode(Object["body"], 1, LabelIdEnd, VariableStack) if not CalleeSuccess: return (False, CalleeMessage) self.ImmediateCodeObj.writeGoto(LabelIdStart) self.ImmediateCodeObj.writeLable(LabelIdEnd) elif Object["type"] == "if": if Object["statement"]["type"] == "greaterEqual": if (Object["statement"]["left"]["type"] != "variable") and (Object["statement"]["right"]["type"] != "variable"): return (False, "TODO 'if' #2") VariableNameLeft = Object["statement"]["left"]["name"] VariableNameRight = Object["statement"]["right"]["name"] (VariableFound, VariableIdLeft, VarLeftDatatype) = self.lookupVariable(VariableStack, VariableNameLeft) if not VariableFound: return (False, "Variable " + VariableNameLeft + " was not declared!") (VariableFound, VariableIdRight, VarRightDatatype) = self.lookupVariable(VariableStack, VariableNameRight) if not VariableFound: return (False, "Variable " + VariableNameRight + " was not declared!") # check if the types do match TypeCheckResult = VarLeftDatatype.compareType(VarRightDatatype) if TypeCheckResult == Datatype.EnumTypeResult.DIFFERENTBITS: return (False, "Left and right variables don't have matching number of bits!") elif TypeCheckResult == Datatype.EnumTypeResult.DIFFERENTTYPE: return (False, "Left an right variables are of different type!") elif TypeCheckResult == Datatype.EnumTypeResult.EQUAL: # all right pass else: return (False, "Internal Error #42") # write Immediate code LabelIdTrue = self.ImmediateCodeObj.getNewLableIdentifier() LabelIdIfEnd = self.ImmediateCodeObj.getNewLableIdentifier() self.ImmediateCodeObj.writeIf(VariableIdLeft, VariableIdRight, 0, LabelIdTrue, LabelIdIfEnd) self.ImmediateCodeObj.writeLable(LabelIdTrue) # TODO< add and remove new level of variable stack ! > (CalleeSuccess, CalleeMessage) = self.transformObjectsIntoCode(Object["block"], ScopeType, ReturnLabelId, VariableStack) if not CalleeSuccess: return (False, CalleeMessage) self.ImmediateCodeObj.writeLable(LabelIdIfEnd) else: # TODO return (False, "TODO 'if' #1") elif Object["type"] == "break": if (ScopeType != 1) and (ScopeType != 2) : # if we are not in in a while or for return (False, "Using of break outside of an loop!") self.ImmediateCodeObj.writeGoto(ReturnLabelId) elif Object["type"] == "return": # TODO< check for beeing in a function > # TODO< check for needed return argument! > self.ImmediateCodeObj.writeGoto(ReturnLabelId) elif Object["type"] == "postinc": if Object["statement"]["type"] != "variable": return (False, "postinc TODO") (VariableFound, VariableId, VariableDatatype) = self.lookupVariable(VariableStack, Object["statement"]["name"]) if not VariableFound: return (False, "Variable " + Object["statement"]["name"] + " was not declared!") self.ImmediateCodeObj.writeInc(VariableId, VariableId) elif Object["type"] == "preinc": return (False, "TODO #A") elif Object["type"] == "postdec": return (False, "TODO #B") elif Object["type"] == "predec": return (False, "TODO #C") else: # internal error return (False, "Internal Error!") VariableStack.pop() return (True, None) # this does the variable lookup def lookupVariable(self, VariableStack, VariableName): ActualStackIndex = len(VariableStack)-1 Found = False VariableId = None VariableInfo = None while True: for Variable in VariableStack[ActualStackIndex]: if Variable["name"] == VariableName: Found = True VariableId = Variable["id"] VariableInfo = Variable["info"] break if Found: break if ActualStackIndex == 0: break ActualStackIndex -= 1 return (Found, VariableId, VariableInfo)