def load_button(self, w): tb = self.textEditor.get_buffer() string = tb.get_text(tb.get_start_iter(), tb.get_end_iter(), False) asm = Assembler() try: asm.Lex(string) try: addr = int(self.loadaddr.get_text(), 16) except: addr = 0 asm.Parse(addr) for byte_list in asm.bytes_list: ad = byte_list["address"] i = 0 for byte in byte_list["bytes"]: ram.Write(ad + i, byte) i += 1 strlbl = "" for lbl in asm.labels: strlbl += "\n" + lbl + " : " + hex(asm.labels[lbl]) self.lblLabel.set_text(strlbl) self.Clear() print("Assembled and loaded succesfully") return True except Exception as ex: self.lblLabel.set_text("") self.Clear() print("Assembling Error: ") print("=======") print(ex) print("at line: \n\t" + asm.line + "\nline no.: " + str(asm.line_no)) return False
def click_run(self): self.console.setText("") if self.select == 'c': try: self.code['c'] = self.editor.get_text() self.code['asm'] = Compiler().parse(self.code['c']) self.code['coe'] = Assembler().parse(self.code['asm']) self.code['debug'] = self.get_debug_code() if str(self.console.toPlainText()) == "": print 'successful complie c code!' else: print 'failed complie c code!!!' except: print traceback.format_exc() print 'failed complie c code!!!' elif self.select == 'asm': try: self.code['asm'] = self.editor.get_text() self.code['coe'] = Assembler().parse(self.code['asm']) self.code['debug'] = self.get_debug_code() if str(self.console.toPlainText()) == "": print 'successful complie asm code!' else: print 'failed complie asm code!!!' except: print traceback.format_exc() print 'failed complie asm code!!!'
def __init__(self): """ Default Constructor that will initialize member variables with reasonable defaults or empty lists/dictionaries where applicable. @ In, None @ Out, None """ BaseType.__init__(self) Assembler.__init__(self) self.counter = 0 # Counter of the samples performed (better the input generated!!!). It is reset by calling the function self.initialize self.auxcnt = 0 # Aux counter of samples performed (for its usage check initialize method) self.limit = sys.maxsize # maximum number of Samples (for example, Monte Carlo = Number of HistorySet to run, DET = Unlimited) self.toBeSampled = { } # Sampling mapping dictionary {'Variable Name':'name of the distribution'} self.dependentSample = { } # Sampling mapping dictionary for dependent variables {'Variable Name':'name of the external function'} self.distDict = { } # Contains the instance of the distribution to be used, it is created every time the sampler is initialized. keys are the variable names self.funcDict = { } # Contains the instance of the function to be used, it is created every time the sampler is initialized. keys are the variable names self.values = { } # for each variable the current value {'var name':value} self.inputInfo = { } # depending on the sampler several different type of keywarded information could be present only one is mandatory, see below self.initSeed = None # if not provided the seed is randomly generated at the istanciation of the sampler, the step can override the seed by sending in another seed self.inputInfo[ 'SampledVars'] = self.values # this is the location where to get the values of the sampled variables self.inputInfo['SampledVarsPb'] = { } # this is the location where to get the probability of the sampled variables self.inputInfo[ 'PointProbability'] = None # this is the location where the point wise probability is stored (probability associated to a sampled point) self.inputInfo['crowDist'] = { } # Stores a dictionary that contains the information to create a crow distribution. Stored as a json object self.constants = {} # In this dictionary self.reseedAtEachIteration = False # Logical flag. True if every newer evaluation is performed after a new reseeding self.FIXME = False # FIXME flag self.printTag = self.type # prefix for all prints (sampler type) self.restartData = None # presampled points to restart from self.restartTolerance = 1e-15 # strictness with which to find matches in the restart data self._endJobRunnable = sys.maxsize # max number of inputs creatable by the sampler right after a job ends (e.g., infinite for MC, 1 for Adaptive, etc) ###### self.variables2distributionsMapping = { } # for each variable 'varName' , the following informations are included: 'varName': {'dim': 1, 'reducedDim': 1,'totDim': 2, 'name': 'distName'} ; dim = dimension of the variable; reducedDim = dimension of the variable in the transformed space; totDim = total dimensionality of its associated distribution self.distributions2variablesMapping = { } # for each variable 'distName' , the following informations are included: 'distName': [{'var1': 1}, {'var2': 2}]} where for each var it is indicated the var dimension self.NDSamplingParams = { } # this dictionary contains a dictionary for each ND distribution (key). This latter dictionary contains the initialization parameters of the ND inverseCDF ('initialGridDisc' and 'tolerance') ###### self.addAssemblerObject('Restart', '-n', True) #used for PCA analysis self.variablesTransformationDict = { } # for each variable 'modelName', the following informations are included: {'modelName': {latentVariables:[latentVar1, latentVar2, ...], manifestVariables:[manifestVar1,manifestVar2,...]}} self.transformationMethod = { } # transformation method used in variablesTransformation node {'modelName':method} self.entitiesToRemove = [ ] # This variable is used in order to make sure the transformation info is printed once in the output xml file.
def setupAssembleMenu(self): assembleMenu = QMenu('汇编(&A)', self) self.menuBar().addMenu(assembleMenu) self.assembler = Assembler() # 创建汇编器对象 assembleMenu.addAction('汇编(&A)', self.assemble, 'F10') # 对当前代码实行汇编操作 assembleMenu.addAction('反汇编(&D)', self.disassemble, 'F11') # 对当前代码实行反汇编操作
def _readMoreXML(self, xmlNode): """ Function to read the portion of the xml input that belongs to this specialized class and initialize some stuff based on the inputs got @ In, xmlNode, xml.etree.ElementTree.Element, Xml element node @ Out, None """ Assembler._readMoreXML(self, xmlNode) self._readMoreXMLbase(xmlNode) self.localInputAndChecks(xmlNode)
def __init__(self, messageHandler): """ Constructor @ In, messageHandler, MessageHandler, message handler object @ Out, None """ Assembler.__init__(self) self.type = self.__class__.__name__ # pp type self.name = self.__class__.__name__ # pp name self.messageHandler = messageHandler
def _readMoreXML(self, xmlNode): """ Function to read the portion of the xml input that belongs to this specialized class and initialize some stuff based on the inputs got @ In, xmlNode, xml.etree.ElementTree.Element, Xml element node @ Out, None """ # TODO can be combined with Sampler's _readMoreXML, but needs to implement paramInput passing to localInputAndChecks (new input checker) Assembler._readMoreXML(self, xmlNode) self._readMoreXMLbase(xmlNode) self.localInputAndChecks(xmlNode)
def __init__(self, messageHandler): """ Constructor @ In, messageHandler, MessageHandler, message handler object @ Out, None """ Assembler.__init__(self) self.type = self.__class__.__name__ # pp type self.name = self.__class__.__name__ # pp name self.messageHandler = messageHandler self.metadataKeys = set() # list of registered metadata keys to expected in this postprocessor self.metadataParams = {} # dictionary of registered metadata keys with respect to their indexes, i.e. {key:list(indexes)}
def _readMoreXML(self, xmlNode): """ Function to read the portion of the xml input that belongs to this specialized class and initialize some stuff based on the inputs got The text is supposed to contain the info where and which variable to change. In case of a code the syntax is specified by the code interface itself @ In, xmlNode, xml.etree.ElementTree.Element, Xml element node @ Out, None """ Assembler._readMoreXML(self, xmlNode) self._readMoreXMLbase(xmlNode) self.localInputAndChecks(xmlNode)
def __init__(self): """ Default Constructor that will initialize member variables with reasonable defaults or empty lists/dictionaries where applicable. @ In, None @ Out, None """ #FIXME: Since the similarity of this class with the base sampler, we should merge this BaseType.__init__(self) Assembler.__init__(self) self.counter = {} # Dict containing counters used for based and derived class self.counter['mdlEval'] = 0 # Counter of the model evaluation performed (better the input generated!!!). It is reset by calling the function self.initialize self.counter['varsUpdate'] = 0 # Counter of the optimization iteration. self.limit = {} # Dict containing limits for each counter self.limit['mdlEval'] = sys.maxsize # Maximum number of the loss function evaluation self.limit['varsUpdate'] = sys.maxsize # Maximum number of the optimization iteration. self.initSeed = None # Seed for random number generators self.optVars = None # Decision variables for optimization self.optVarsInit = {} # Dict containing upper/lower bounds and initial of each decision variables self.optVarsInit['upperBound'] = {} # Dict containing upper bounds of each decision variables self.optVarsInit['lowerBound'] = {} # Dict containing lower bounds of each decision variables self.optVarsInit['initial'] = {} # Dict containing initial values of each decision variables self.optVarsInit['ranges'] = {} # Dict of the ranges (min and max) of each variable's domain self.optVarsHist = {} # History of normalized decision variables for each iteration self.nVar = 0 # Number of decision variables self.objVar = None # Objective variable to be optimized self.optType = None # Either maximize or minimize self.optTraj = None # Identifiers of parallel optimization trajectories self.thresholdTrajRemoval = None # Threshold used to determine the convergence of parallel optimization trajectories self.paramDict = {} # Dict containing additional parameters for derived class self.absConvergenceTol = 0.0 # Convergence threshold (absolute value) self.relConvergenceTol = 1.e-3 # Convergence threshold (relative value) self.solutionExport = None #This is the data used to export the solution (it could also not be present) self.values = {} # for each variable the current value {'var name':value} self.inputInfo = {} # depending on the optimizer several different type of keywarded information could be present only one is mandatory, see below self.inputInfo['SampledVars' ] = self.values # this is the location where to get the values of the sampled variables self.constants = {} # dictionary of constants variables self.FIXME = False # FIXME flag self.printTag = self.type # prefix for all prints (optimizer type) self._endJobRunnable = sys.maxsize # max number of inputs creatable by the optimizer right after a job ends self.constraintFunction = None # External constraint function, could be not present self.mdlEvalHist = None # Containing information of all model evaluation self.objSearchingROM = None # ROM used internally for fast loss function evaluation self.addAssemblerObject('Restart' ,'-n',True) self.addAssemblerObject('TargetEvaluation','1') self.addAssemblerObject('Function','-1')
def __init__(self,runInfoDict): """ Constructor @ In, runInfoDict, dict, the dictionary containing the runInfo (read in the XML input file) @ Out, None """ BaseType.__init__(self) Assembler.__init__(self) #if alias are defined in the input it defines a mapping between the variable names in the framework and the one for the generation of the input #self.alias[framework variable name] = [input code name]. For Example, for a MooseBasedApp, the alias would be self.alias['internal_variable_name'] = 'Material|Fuel|thermal_conductivity' self.alias = {'input':{},'output':{}} self.subType = '' self.runQueue = [] self.printTag = 'MODEL' self.createWorkingDir = False
def setUp(self): self.assembler = Assembler() parser = Parser() self.symbolTable = SymbolTable() self.assembler.setSymbolTable(self.symbolTable) self.assembler.setParser(parser)
def main(): m = argparse.ArgumentParser() m.add_argument("--input", "-i", type=str) m.add_argument("--output", "-o", type=str) options = m.parse_args() asm = AsmEncoder() tree = asm.parse(options.input) coded = Assembler(tree) with open(options.output, "wb") as f: f.write(coded.state)
def Export(self, filename, withAsm=False): fp = open(filename, 'w') tb = self.textEditor.get_buffer() string = tb.get_text(tb.get_start_iter(), tb.get_end_iter(), False) asm = Assembler() try: asm.Lex(string) try: addr = int(self.loadaddr.get_text(), 16) except: addr = 0 asm.Parse(addr) for byte_list in asm.bytes_list: ad = byte_list["address"] i = 0 if withAsm: fp.write(byte_list["asm"] + "\t;") else: fp.write('{:04x}'.format(ad) + ": ") for byte in byte_list["bytes"]: fp.write('{:02x}'.format(byte) + " ") i += 1 if not withAsm: fp.write("\t\t;" + byte_list["asm"]) fp.write("\n") strlbl = "" for lbl in asm.labels: strlbl += "\n" + lbl + " : " + hex(asm.labels[lbl]) self.lblLabel.set_text(strlbl) self.Clear() print("Assembled and exported succesfully") except Exception as ex: self.lblLabel.set_text("") self.Clear() print("Assembling Error: ") print("=======") print(ex) print("at line: \n\t" + asm.line + "\nline no.: " + str(asm.line_no)) fp.close()
def __init__(self, code, debug=False): """Takes a program, runs it through the assembler, and converts that code to bytecode. """ self.variables = {} assembly = str(Assembler(code, debug)) self.bytecode = self.comp(assembly) # If debugging is enabled, set it up. if debug: self.out = open(os.path.join(os.getcwd(), "compiler_output.txt"), "w") self.out.write(self.bytecode) self.out.close()
def _readMoreXML(self,xmlNode): """ Function to read the portion of the xml input that belongs to this specialized class and initialize some stuff based on the inputs got @ In, xmlNode, xml.etree.ElementTree.Element, Xml element node @ Out, None """ Assembler._readMoreXML(self,xmlNode) try: self.subType = xmlNode.attrib['subType'] except KeyError: self.raiseADebug("Failed in Node: "+str(xmlNode),verbostiy='silent') self.raiseAnError(IOError,'missed subType for the model '+self.name) for child in xmlNode: if child.tag =='alias': # the input would be <alias variable='internal_variable_name'>Material|Fuel|thermal_conductivity</alias> if 'variable' in child.attrib.keys(): if 'type' in child.attrib.keys(): if child.attrib['type'].lower() not in ['input','output']: self.raiseAnError(IOError,'the type of alias can be either "input" or "output". Got '+child.attrib['type'].lower()) aliasType = child.attrib['type'].lower().strip() complementAliasType = 'output' if aliasType == 'input' else 'input' else: self.raiseAnError(IOError,'not found the attribute "type" in the definition of one of the alias for model '+str(self.name) +' of type '+self.type) varFramework, varModel = child.attrib['variable'], child.text.strip() if varFramework in self.alias[aliasType].keys(): self.raiseAnError(IOError,' The alias for variable ' +varFramework+' has been already inputted in model '+str(self.name) +' of type '+self.type) if varModel in self.alias[aliasType].values(): self.raiseAnError(IOError,' The alias ' +varModel+' has been already used for another variable in model '+str(self.name) +' of type '+self.type) if varFramework in self.alias[complementAliasType].keys(): self.raiseAnError(IOError,' The alias for variable ' +varFramework+' has been already inputted ('+complementAliasType+') in model '+str(self.name) +' of type '+self.type) if varModel in self.alias[complementAliasType].values(): self.raiseAnError(IOError,' The alias ' +varModel+' has been already used ('+complementAliasType+') for another variable in model '+str(self.name) +' of type '+self.type) self.alias[aliasType][varFramework] = child.text.strip() else: self.raiseAnError(IOError,'not found the attribute "variable" in the definition of one of the alias for model '+str(self.name) +' of type '+self.type) # read local information self.localInputAndChecks(xmlNode)
def main(): teste = './teste.txt' compMemoria = Memoria() motor = MotorDeEventos() assembler = Assembler() programCounter = motor.programCounter assembler.primeiroPasso(teste) instruCodMaq = assembler.segundoPasso(teste) compMemoria.loader(instruCodMaq) motor.acumulador = 5 compMemoria.memoria[200] = '0x0002' compMemoria.memoria[210] = '0x0003' compMemoria.memoria[220] = '0x0005' compMemoria.memoria[100] = 7 #compMemoria.memoria[130] = 2 motor.fluxoEventos(compMemoria) print() print("Acumulador:") print(motor.acumulador) print() print("Posição 0x100 da memória:") print(compMemoria.memoria[100]) print() print("Memoria:") print(compMemoria.memoria)
class TestAssembler(unittest.TestCase): # instructions = ["@2", "A_const", "L", "C_DP1", "C_APDM", "D0", "0JNE"] def setUp(self): self.fakeParser = fakeparser() self.fakeSymbolTable = fakesymboltable() self.assembler = Assembler() self.assembler.setParser(self.fakeParser) self.assembler.setSymbolTable(self.fakeSymbolTable) def test_assemble_A_const(self): binary_instruction = self.assembler.assembleInstruction("@2") self.assertEqual("0b0000000000000010", binary_instruction) def test_assemble_A_sym(self): self.fakeSymbolTable.addEntry("loop", 110) binary_instruction = self.assembler.assembleInstruction("@loop") self.assertEqual("0b0000000001101110", binary_instruction) def test_jumpInstruction(self): binary_instruction = self.assembler.assembleInstruction("0;JNE") self.assertEqual("0b1110101010000101", binary_instruction) def test_D_eq_DplusOne(self): binary_instruction = self.assembler.assembleInstruction("D=D+1") self.assertEqual("0b1110011111010000", binary_instruction) def test_A_eq_DPlusM(self): binary_instruction = self.assembler.assembleInstruction("A=D+M") self.assertEqual("0b1111000010100000", binary_instruction) def testRemoveWhiteSpaceOnLine(self): r = self.assembler.removeWhiteSpaceOnLine(" A = D + 1 //a comment") self.assertEqual("A=D+1//acomment", r) def testRemoveCommentsOnLine(self): r = self.assembler.removeCommentsOnLine(" A = D + 1 //a comment") self.assertEqual(" A = D + 1 ", r) def testAssemble(self): instructions = ["@2", "0;JNE", "D=D+1", "A=D+M"] assembledInstructions = self.assembler.assemble(instructions) self.assertEqual(["0b0000000000000010", "0b1110101010000101", "0b1110011111010000", "0b1111000010100000"], assembledInstructions) def testAssembleWithSymbolicA(self): # symbol table already initialized in setUp() to return 110 for any symbol instructions = ["@2", "0;JNE", "@myVariable", "D=D+1", "A=D+M"] assembledInstructions = self.assembler.assemble(instructions) self.assertEqual(["0b0000000000000010", "0b1110101010000101", "0b0000000001101110", "0b1110011111010000", "0b1111000010100000"], assembledInstructions) def testFirstPass(self): instructions = ["@2", "0;JNE", "@userSymbol", "D=D+1", "A=D+M"] self.assertEqual(5, self.assembler.firstPass(instructions))
exit(-1) if VERBOSE: print 'Parsed Text Section' + inreportStreamName + ':' import json print json.dumps(parsed['instructions'], indent=4) print 'Parsed Data Section' + inreportStreamName + ':' print json.dumps(parsed['data'], indent=4) #pack for assembling streams[streamName] = parsed ################################# # assemble all parsed streams # assembler = Assembler(opts.archFile) for streamName, result in assembler(streams).items(): #set names depending on stream name reportStreamName = ' stream "%s"' % ( streamName) if streamName != '' else '' inreportStreamName = ' in stream "%s"' % ( streamName) if streamName != '' else '' #Error handling and message printing of the assembling success, asm = result #assembler(parsed['instructions'], parsed['data']) if success == False: if VERBOSE: print >> sys.stderr, 'Error while assembling' + reportStreamName print >> sys.stderr, asm exit(-1)
from Assembler import Assembler; file = str(input("Informe o nome do arquivo que deseja converter: ")).strip(); obj = Assembler(file); obj.StepOne(); obj.Print(); obj.StepTwo();
def main(): args = parseArgs() assembler = Assembler(args) assembler.process()
from Assembler import Assembler from SystemBuilder import ProcessorSystem sysbuilder = ProcessorSystem() assembler = Assembler(sysbuilder) assembler.readcommands() sysbuilder.run()
Default_Path_For_mem = "F:/3rd-CSE/PythonScripts/Automated_Test" # The path of the assembly code to be passed to the assembler Path_For_Assembly = 'F:/3rd-CSE/mips_processor2019/Test_cases/assembly_source' # The path for the correct test cases to be compared with the generated ones Path_For_Test = 'F:/3rd-CSE/Test_cases/output_of_modelsim' # Counter for the current iteration in the test files test_number = 1 folder = os.fsencode(Path_For_Assembly) filenames = [] test_result = [] # index = 0 for file in os.listdir(folder): # print(index) filename = os.fsdecode(file) x = Path_For_Assembly + '/' + filename newline = Assembler(x) # The file where the binary is generated newfile_name = "test.txt" newfile_name = open(newfile_name, "w+") for line in newline: newfile_name.write(line) newfile_name.close() # index = index + 1 os.chdir( 'F:/3rd-CSE/1stTerm/COIIProjects/Modeltech_pe_edu_10.4a/win32pe_edu') os.system( 'vsim -c -do "run -all" F:/3rd-CSE/1stTerm/COIIProjects/Modeltech_pe_edu_10.4a/examples/work.MIPS_cpu' ) os.chdir('F:/3rd-CSE/PythonScripts/Automated_Test') #this previous part runs the modelsim giving it the binary file local_mem_file = Default_Path_For_mem + '/' + "mem.txt"
# elif cmd == "stbb": # ppi.StrobeB() # elif cmd == "show": # print("") # alu.Show() # #print("\n") # #ram.Show() # print("\n") # ppi.Show() ram.ShowRange(parser.labels["TABLE"], parser.labels["TABLE"]+0x63) alu.Show() from Assembler import Assembler parser = Assembler() try: #main() filep = open("samples/testlbl.asm", "r") asm = filep.read() filep.close() parser.Lex(asm) parser.Parse() #filep = open("random.bin", "w") for bytes in parser.bytes_list: print(hex(bytes["address"])) for byte in bytes["bytes"]: print(hex(byte)) # filep.write('{0:02x}'.format(byte) + "\n") #filep.close()
def Solve(self): ''' This method builds System Matrix and gets Solution ''' if self.SimulationContext.Id != self.NetworkMesh.Id: raise self.SimulationContext.XMLIdError() try: self.TimeStep = self.SimulationContext.Context['timestep'] self.SquareTimeStep = self.TimeStep * self.TimeStep except KeyError: print "Error, Please set timestep in Simulation Context XML File" raise try: self.Period = self.SimulationContext.Context['period'] self.TimeStepFreq = int(self.Period / self.TimeStep) except KeyError: print "Error, Please set period in Simulation Context XML File" raise try: self.Cycles = self.SimulationContext.Context['cycles'] self.NumberOfIncrements = (self.Cycles * self.TimeStepFreq) except KeyError: print "Error, Please set cycles number in Simulation Context XML File" raise history = [] assembler = Assembler() assembler.SetNetworkMesh(self.NetworkMesh) assembler.SetBoundaryConditions(self.BoundaryConditions) info = { 'dofmap': assembler.DofMap, 'solution': None, 'incrementNumber': self.IncrementNumber, 'history': history } self.Evaluator.SetInfo(info) self.PrescribedPressures = assembler.AssembleBoundaryConditions( self.SimulationContext) self.LinearZeroOrderGlobalMatrix, self.LinearFirstOrderGlobalMatrix, self.LinearSecondOrderGlobalMatrix = \ assembler.AssembleInit(self.SimulationContext, self.Evaluator) self.ZeroOrderGlobalMatrix = assembler.ZeroOrderGlobalMatrix self.FirstOrderGlobalMatrix = assembler.FirstOrderGlobalMatrix self.SecondOrderGlobalMatrix = assembler.SecondOrderGlobalMatrix NumberOfGlobalDofs = assembler.GetNumberOfGlobalDofs( ) # number of dofs self.UnknownPressures = arange(0, NumberOfGlobalDofs).reshape( NumberOfGlobalDofs, 1) # unknown pressures self.UnknownPressures = delete(self.UnknownPressures, s_[self.PrescribedPressures[:, 0]], axis=0) PressuresMatrix = zeros((NumberOfGlobalDofs, self.NumberOfIncrements)) self.p = zeros((NumberOfGlobalDofs, 1)) self.pt = zeros((NumberOfGlobalDofs, 1)) self.ptt = zeros((NumberOfGlobalDofs, 1)) self.dp = zeros((NumberOfGlobalDofs, 1)) self.ddp = zeros((NumberOfGlobalDofs, 1)) self.dpt = zeros((NumberOfGlobalDofs, 1)) self.ddpt = zeros((NumberOfGlobalDofs, 1)) self.fe = zeros((NumberOfGlobalDofs, 1)) self.fet = zeros((NumberOfGlobalDofs, 1)) self.dfe = zeros((NumberOfGlobalDofs, 1)) self.dfet = zeros((NumberOfGlobalDofs, 1)) self.fi = zeros((NumberOfGlobalDofs, 1)) self.fit = zeros((NumberOfGlobalDofs, 1)) self.sumv = zeros((NumberOfGlobalDofs, 1)) sumvbk = zeros((NumberOfGlobalDofs, 1)) nonLinear = False for el in self.NetworkMesh.Elements: if el.IsNonLinear() == True: nonLinear = True break while self.IncrementNumber <= self.NumberOfIncrements: icc = (self.IncrementNumber % self.TimeStepFreq) if icc == 0: icc = self.TimeStepFreq #for flow in self.BoundaryConditions.elementFlow: for el in self.BoundaryConditions.elementFlow: if self.steady == True: self.Flow = assembler.BoundaryConditions.GetSteadyFlow( el, self.TimeStep, icc * self.TimeStep) else: self.Flow = assembler.BoundaryConditions.GetTimeFlow( el, icc * self.TimeStep) self.fe[assembler.FlowDof[el.Id]] = self.Flow CoeffRelax = 0.9 nltol = self.nltol self.pi = None pI = None sumvbk[:, :] = self.sumv[:, :] counter = 0 while True: #Build the algebric equation system for the increment SystemMatrix = ( 2.0 / self.TimeStep ) * self.SecondOrderGlobalMatrix + self.FirstOrderGlobalMatrix + ( self.TimeStep / 2.0) * self.ZeroOrderGlobalMatrix #system matrix RightVector = self.fe + (2.0 / self.TimeStep) * dot( self.SecondOrderGlobalMatrix, (self.pt)) + dot( self.SecondOrderGlobalMatrix, (self.dpt)) - dot( self.ZeroOrderGlobalMatrix, (self.sumv)) - (self.TimeStep / 2.0) * dot( self.ZeroOrderGlobalMatrix, (self.pt)) # right hand side vector #The reduced (partioned) system of equations is generated. RightVector[:, :] = RightVector[:, :] - dot( SystemMatrix[:, self.PrescribedPressures[:, 0]], self.PrescribedPressures[:, 1:]) SystemMatrix = SystemMatrix[:, s_[self.UnknownPressures[:, 0]]] if SystemMatrix.shape[0] > 0.0: SystemMatrix = SystemMatrix[ s_[self.UnknownPressures[:, 0]], :] RightVector = RightVector[s_[self.UnknownPressures[:, 0]], :] #Unknown nodal point values are solved from this system. # Prescribed nodal values are inserted in the solution vector. Solution = solve(SystemMatrix, RightVector) # solutions, unknown pressures self.p[self.UnknownPressures, 0] = Solution[:, :] self.p[self.PrescribedPressures[:, 0], 0] = self.PrescribedPressures[:, 1] #Calculating derivatives. #Calculating internal nodal flow values. self.dp = dot((2.0 / self.TimeStep), (self.p - self.pt)) - self.dpt self.ddp = dot((4.0 / self.SquareTimeStep), (self.p - self.pt)) - dot( (4.0 / self.TimeStep), self.dpt) - self.ddpt self.sumv = sumvbk + dot((self.TimeStep / 2.0), (self.pt + self.p)) self.fi = dot(self.SecondOrderGlobalMatrix, (self.dp)) + dot( self.FirstOrderGlobalMatrix, (self.p)) + dot(self.ZeroOrderGlobalMatrix, (self.sumv)) if not nonLinear: break if self.pi == None: self.pi = zeros((NumberOfGlobalDofs, 1)) self.pi[:, :] = self.pt[:, :] pI = CoeffRelax * self.p + self.pi * (1.0 - CoeffRelax) self.p[:, :] = pI[:, :] den = norm(self.pi, Inf) if den < 1e-12: den = 1.0 nlerr = norm(self.p - self.pi, Inf) / den info = { 'dofmap': assembler.DofMap, 'solution': [self.p, self.pt, self.ptt], 'incrementNumber': self.IncrementNumber, 'history': history } self.Evaluator.SetInfo(info) assembler.Assemble(self.SimulationContext, self.Evaluator, self.LinearZeroOrderGlobalMatrix, self.LinearFirstOrderGlobalMatrix, self.LinearSecondOrderGlobalMatrix) self.ZeroOrderGlobalMatrix = assembler.ZeroOrderGlobalMatrix self.FirstOrderGlobalMatrix = assembler.FirstOrderGlobalMatrix self.SecondOrderGlobalMatrix = assembler.SecondOrderGlobalMatrix #Dynamic nonlinear relaxing coefficient if counter == 100: print "relaxing..." print nlerr, nltol, CoeffRelax counter = 0 self.pi[:, :] = None self.sumv[:, :] = sumvbk[:, :] CoeffRelax *= 0.6 nltol *= 0.95 if nlerr < nltol: nltol = self.nltol counter = 0 break counter += 1 self.pi[:, :] = self.p[:, :] self.ptt[:, :] = self.pt[:, :] self.pt[:, :] = self.p[:, :] self.dpt[:, :] = self.dp[:, :] self.ddpt[:, :] = self.ddp[:, :] self.fet[:, :] = self.fe[:, :] self.fit[:, :] = self.fi[:, :] PressuresMatrix[:, (self.IncrementNumber - 1)] = self.p[:, 0] history.insert(0, self.IncrementNumber) history = history[:3] if self.steady == True: self.MinimumIncrementNumber = 0.01 * self.NumberOfIncrements if norm( self.fi - self.fe, Inf ) < self.convergence and self.IncrementNumber > self.MinimumIncrementNumber: self.IncrementNumber = self.NumberOfIncrements else: pass if self.IncrementNumber == ceil(0.05 * self.NumberOfIncrements): print "->5%" if self.IncrementNumber == ceil(0.25 * self.NumberOfIncrements): print "->25%" if self.IncrementNumber == ceil(0.5 * self.NumberOfIncrements): print "->50%" if self.IncrementNumber == ceil(0.70 * self.NumberOfIncrements): print "->70%" if self.IncrementNumber == ceil(0.90 * self.NumberOfIncrements): print "->90%" if self.IncrementNumber == ceil(0.99 * self.NumberOfIncrements): print "->99%" self.IncrementNumber = self.IncrementNumber + 1 self.EndIncrementTime = self.EndIncrementTime + self.TimeStep # increment info = { 'dofmap': assembler.DofMap, 'solution': [self.p, self.pt, self.ptt], 'incrementNumber': self.IncrementNumber, 'history': history, 'allSolution': PressuresMatrix } self.Evaluator.SetInfo(info) self.Solutions = PressuresMatrix return PressuresMatrix
import sys from pathlib import Path from Assembler import Assembler from c_instruction_map import comp, dest, jump, symbols try: relative_path = Path(sys.argv[1]) except IndexError: relative_path = Path( input("type file path from projects. eg \"06/add/Add.asm\" :")) PROJECT_PATH = Path("D:/nand2tetris/projects") PROGRAM_PATH = PROJECT_PATH / relative_path HACK_PATH = PROGRAM_PATH.parent / (PROGRAM_PATH.stem + ".hack") if __name__ == "__main__": with open(PROGRAM_PATH) as asm_file: assembler_instance = Assembler(comp, dest, jump, symbols, asm_file) assembly = assembler_instance.extract_assembly_from_file() assembler_instance.load_reference_to_symbols_table(assembly) assembly_without_references = assembler_instance.remove_references( assembly) hack_binary = assembler_instance.assemble(assembly_without_references) with open(HACK_PATH, "w") as hack_file: hack_file.writelines(hack_binary)
from Assembler import Assembler from Parser import Parser from SymbolTable import SymbolTable import sys # initialize assembler assembler = Assembler() parser = Parser() symbolTable = SymbolTable() assembler.setParser(parser) assembler.setSymbolTable(symbolTable) # open source file filename = sys.argv[1].split(".")[0] asmFile = open(sys.argv[1]) # get instructions for assembler from source # and remove whitespace and comments as well instructions = [] for line in asmFile: line = assembler.removeCommentsOnLine(line) line = assembler.removeWhiteSpaceOnLine(line) if line != "" and line != "\n": instructions.append(line) asmFile.close()
from Assembler import Assembler def print_usage(): ''' Prints the usage for this script. ''' print ('Usage: python sbasm.py <input file name> <output file name, default a.mif>') if __name__ == "__main__": argc = len(sys.argv) if argc >= 4: print ('ERROR: Too many arguments.') print_usage() elif argc <= 1: print ('ERROR: Too few arguments.') print_usage() else: # Parse the in and out file names from the arguments. # Default the output filename to a.mif. in_filename = sys.argv[1] out_filename = 'a.mif' if argc > 2: out_filename = sys.argv[2] # Create the assembler and assemble. a = Assembler(in_filename, out_filename) a.assemble()
def setUp(self): self.fakeParser = fakeparser() self.fakeSymbolTable = fakesymboltable() self.assembler = Assembler() self.assembler.setParser(self.fakeParser) self.assembler.setSymbolTable(self.fakeSymbolTable)
class Window(QMainWindow): def __init__(self): super(Window, self).__init__() self.setWindowTitle('MIPS') # 窗口标题 # 设置各项菜单 self.setupFileMenu() self.setupAssembleMenu() self.setupDebugMenu() self.setupHelpMenu() self.setupEditor() # 设置编辑器 self.setCentralWidget(self.editor) self.setupDock() # 设置Dock栏 def setupEditor(self): self.editor = Editor() # 创建编辑器对象 def setupFileMenu(self): fileMenu = QMenu('文件(&F)', self) self.menuBar().addMenu(fileMenu) self.currentFile = '' # 设置当前文件路径为空值 fileMenu.addAction('新建(&N)', self.newFile, 'Ctrl+N') # 新建立一个文件 fileMenu.addAction('打开(&O)...', self.openFile, 'Ctrl+O') # 打开已有的文件 fileMenu.addAction('保存(&S)', self.saveFile, 'Ctrl+S') # 将当前文件保存 fileMenu.addAction('另存为(&A)...', self.saveAnotherFile, 'Ctrl+Alt+S') # 将当前文件保存到指定路径 fileMenu.addAction('退出(&X)', self.close, 'Ctrl+F4') # 退出MIPS汇编器 def setupAssembleMenu(self): assembleMenu = QMenu('汇编(&A)', self) self.menuBar().addMenu(assembleMenu) self.assembler = Assembler() # 创建汇编器对象 assembleMenu.addAction('汇编(&A)', self.assemble, 'F10') # 对当前代码实行汇编操作 assembleMenu.addAction('反汇编(&D)', self.disassemble, 'F11') # 对当前代码实行反汇编操作 def setupDebugMenu(self): assembleMenu = QMenu('调试(&D)', self) self.menuBar().addMenu(assembleMenu) self.isStart = False # 设置是否开始调试布尔值为否 assembleMenu.addAction('启动调试(&S)', self.startDebug, 'F5') # 启动调试 assembleMenu.addAction('继续调试(&C)', self.contiuneDebug, 'F5') # 将调试进行到最后一步 assembleMenu.addAction('单步执行(&I)', self.nextDebug, 'F11') # 单步进行调试 assembleMenu.addAction('停止调试(&S)', self.stopDebug, 'Shift+F5') # 停止调试过程 assembleMenu.addAction('重启调试(&R)', self.resetDebug, 'Ctrl+Shift+F5') # 重新启动调试过程 def setupHelpMenu(self): helpMenu = QMenu("帮助(&H)", self) self.menuBar().addMenu(helpMenu) helpMenu.addAction('关于(&A)', self.about) # 本程序的小介绍 def setupDock(self): # 建立输出运行结果的窗口 self.rightBrowser = Browser() # 建立在窗口右端 self.rightDock = QDockWidget('运行结果/内存', self) self.rightDock.setFeatures(QDockWidget.DockWidgetClosable) self.rightDock.setWidget(self.rightBrowser) self.addDockWidget(Qt.RightDockWidgetArea, self.rightDock) self.rightDock.hide() # 窗口自动隐藏 # 建立输出调试过程的窗口 self.bottomBrowser = Browser() # 建立在窗口底端 self.bottomDock = QDockWidget('调试窗口', self) self.bottomDock.setFeatures(QDockWidget.DockWidgetClosable) self.bottomDock.setWidget(self.bottomBrowser) self.addDockWidget(Qt.BottomDockWidgetArea, self.bottomDock) self.bottomDock.hide() def newFile(self): self.editor.clear() # 清空当前屏幕 self.rightDock.hide() # 隐藏Dock栏 self.bottomDock.hide() self.currentFile = '' return True def openFile(self): # 打开汇编文件或二进制文件 path, _ = QFileDialog.getOpenFileName( self, '打开', '', '汇编文件 (*.asm);;二进制文件(*.coe *.bin)') if path: file = open(path, 'r') self.editor.setPlainText(file.read()) file.close() self.rightDock.hide() self.bottomDock.hide() self.currentFile = path return True return False def saveFile(self): # 如果没有文件名则跳转到另存为 if not self.currentFile: return self.saveAnotherFile() # 将编辑器内容写入到当前路径文件 file = open(self.currentFile, 'w') file.write(self.editor.toPlainText()) file.close() return True def saveAnotherFile(self): # 选择存入文件路径 path, _ = QFileDialog.getSaveFileName( self, '另存为', self.currentFile if self.currentFile else '', '汇编文件 (*.asm);;二进制文件(*.coe *.bin)') # 路径存在则将编辑器内容写入 if path: file = open(path, 'w') file.write(self.editor.toPlainText()) file.close() self.currentFile = path return True return False def assemble(self): self.saveFile() # 执行前保存文件 try: self.rightBrowser.setText(self.assembler.assembly( self.currentFile)) # 执行汇编并在右侧输出结果 except: self.rightBrowser.setText( 'error!!! \ncheck your code!!!') # 代码有误不能正确汇编 return self.rightDock.show() def disassemble(self): self.saveFile() try: self.rightBrowser.setText( self.assembler.disassembly(self.currentFile)) # 执行反汇编并在右侧输出结果 except: self.rightBrowser.setText( 'error!!! \ncheck your code!!!') # 代码有误不能正确反汇编 return self.rightDock.show() def startDebug(self): self.saveFile() self.assembler.step = 0 # 初始化执行步数 self.debugStr = '' # 初始化结果字符 self.isStart = True # 设定已经开始 # 初始化寄存器内容 for k in self.assembler.registers: self.assembler.registers[k] = '00000000' self.assembler.memory = {} # 初始化内存 try: self.assembler.debug(self.currentFile) self.debugStr = str(self.assembler.memory).strip("{}").replace( "'", '').replace(':', ' ').replace(',', ' ') # 执行单步模拟操作 except: self.debugStr += '\nthe debug is over\nnow check your code' # 模拟完成或代码有误则停止 return False # 将寄存器内容展示在底部,结果展示在右部 self.bottomBrowser.setText(' ' + str(self.assembler.registers).strip( "{},").replace(':', '\t').replace(',', '\t').replace("'", '')) self.rightBrowser.setText(self.debugStr) self.rightDock.show() self.bottomDock.show() return True def contiuneDebug(self): # 如果没有开始则开始调试 if not self.isStart: self.startDebug() # 模拟进行到最后一步 while self.nextDebug(): continue self.bottomBrowser.setText( str(self.assembler.registers).strip("{},").replace( ':', '\t').replace(',', '\t').replace("'", '')) self.rightBrowser.setText(self.debugStr) self.rightDock.show() self.bottomDock.show() return True def nextDebug(self): if not self.isStart: return self.startDebug() try: self.assembler.debug(self.currentFile) self.debugStr = str(self.assembler.memory).strip("{}").replace( "'", '').replace(':', ' ').replace(',', ' ') except: self.debugStr += '\nthe debug is over\nnow check your code' self.rightBrowser.setText(self.debugStr) self.rightDock.show() return False self.bottomBrowser.setText( str(self.assembler.registers).strip("{},").replace( ':', '\t').replace(',', '\t').replace("'", '')) self.rightBrowser.setText(self.debugStr) self.rightDock.show() self.bottomDock.show() return True def stopDebug(self): self.isStart = False # 结束调试并将开始置否 self.bottomDock.hide() self.rightDock.hide() return True def resetDebug(self): self.stopDebug() return self.startDebug() def about(self): # 简短介绍本程序 QMessageBox.about( self, '关于本MIPS汇编器', '<p style="font-size: 16px;">Made By Aaron</p>' '<p style="font-size: 16px;">可实现MIPS汇编器(支持伪码),反汇编器,调试器</p>' '<p style="font-size: 16px;">介绍请见README.md</p>' '<p style="font-size: 16px;">具体细节请参考实验报告')
def main(): input_file = 'Add.asm' # initiate parser arg_parser = argparse.ArgumentParser() arg_parser.add_argument("-d", "--data", help="print sample data", action="store_true") arg_parser.add_argument("-c", "--clean", help="clear sample data", action="store_true") arg_parser.add_argument("-n", "--normal", help="normalize sample data", action="store_true") arg_parser.add_argument("-a", "--assemble", help="assemble sample data", action="store_true") arg_parser.add_argument("-f", "--file", help="assemble from file", type=str, required=False) arg_parser.add_argument("-b", "--write_bat_file", help="write drag and drop .bat", action="store_true") # read arguments from the command line args = arg_parser.parse_args() # check for --data or -d if args.data: asm_parser = Parser(input_file) asm_parser.print_data("d") # check for --clean or -c if args.clean: asm_parser = Parser(input_file) asm_parser.print_data("c") # check for --normal or -n if args.normal: asm_parser = Parser(input_file) asm_parser.print_data("n") # check for --assemble or -a if args.assemble: asm_parser = Parser(input_file) assembler = Assembler() assembler.print_assembler_data("a", asm_parser.normalize_data()) # check for --file or -f if args.file: asm_parser = Parser(args.file) assembler = Assembler() assembler.write_to_file(args.file, asm_parser.normalize_data()) return # check for --write_bat_file or -k if args.write_bat_file: if Path("Assembler.bat").is_file(): print("File already exists") input() else: file_object = open("Assembler.bat", "w") file_object.write("python \"%~dp0/Main.py\" -f %1\n\nrem cmd /k")
def assembler(): global file_name global content assem = Assembler(content) assem.traverse(assem.tree.root) assem.ass_file_handler.generate_ass_file(file_name)
from CPU import CPU from Assembler import Assembler Assembler('example/example.asm', 'example/example.bin') CPU('example/example.bin')
class TestAssemblerFinal(unittest.TestCase): def setUp(self): self.assembler = Assembler() parser = Parser() self.symbolTable = SymbolTable() self.assembler.setSymbolTable(self.symbolTable) self.assembler.setParser(parser) def testFirstPassSimpleLoop(self): instructions = ["(loop)", "@loop", "0;JNE"] self.assembler.firstPass(instructions) self.assertTrue(self.symbolTable.contains("loop")) self.assertEqual(self.symbolTable.getAddress("loop"), 0) def testFirstPassComplexLoops(self): instructions = ["(loop)", "@loop", "0;JNE", "(bob)", "D=D+1", "(tim)", "M=A+D"] self.assembler.firstPass(instructions) self.assertTrue(self.symbolTable.contains("loop")) self.assertTrue(self.symbolTable.contains("bob")) self.assertTrue(self.symbolTable.contains("tim")) self.assertEqual(self.symbolTable.getAddress("loop"), 0) self.assertEqual(self.symbolTable.getAddress("bob"), 2) self.assertEqual(self.symbolTable.getAddress("tim"), 3) def testFirstPassMaxAsm(self): instructions = ["@R0", "D=M", "@R1", "D=D-M", "@OUTPUT_FIRST", "D;JGT", "@R1", "D=M", "@OUTPUT_D", "0;JMP", "(OUTPUT_FIRST)", "@R0", "D=M", "(OUTPUT_D)", "@R2", "M=D", "(INFINITE_LOOP)", "@INFINITE_LOOP", "0;JMP"] self.assembler.firstPass(instructions) self.assertTrue(self.assembler.symbolTable.contains("OUTPUT_FIRST")) self.assertEqual(self.assembler.symbolTable.getAddress("OUTPUT_FIRST"), 10) def testFirstPassMaxAsmInfiniteLoopAddress(self): instructions = ["@R0", "D=M", "@R1", "D=D-M", "@OUTPUT_FIRST", "D;JGT", "@R1", "D=M", "@OUTPUT_D", "0;JMP", "(OUTPUT_FIRST)", "@R0", "D=M", "(OUTPUT_D)", "@R2", "M=D", "(INFINITE_LOOP)", "@INFINITE_LOOP", "0;JMP"] self.assembler.firstPass(instructions) self.assertTrue(self.assembler.symbolTable.contains("INFINITE_LOOP")) self.assertEqual(self.assembler.symbolTable.getAddress("INFINITE_LOOP"), 14) def testSecondPassMaxAsmInfiniteLoopAddress(self): instructions = ["@R0", "D=M", "@R1", "D=D-M", "@OUTPUT_FIRST", "D;JGT", "@R1", "D=M", "@OUTPUT_D", "0;JMP", "(OUTPUT_FIRST)", "@R0", "D=M", "(OUTPUT_D)", "@R2", "M=D", "(INFINITE_LOOP)", "@INFINITE_LOOP", "0;JMP"] self.assembler.firstPass(instructions) self.assembler.secondPass(instructions) self.assertTrue(self.assembler.symbolTable.contains("INFINITE_LOOP")) self.assertEqual(self.assembler.symbolTable.getAddress("INFINITE_LOOP"), 14) def testSecondPassSimple(self): instructions = ["(loop)", "@myVar", "M=5", "@loop", "0;JNE"] self.assembler.firstPass(instructions) self.assembler.secondPass(instructions) self.assertTrue(self.symbolTable.contains("loop")) self.assertTrue(self.symbolTable.contains("myVar")) self.assertEqual(self.symbolTable.getAddress("myVar"), 16) self.assertEqual(self.symbolTable.getAddress("loop"), 0) def testAssembleInstructions(self): instructions = ["(loop)", "@loop", "0;JEQ"] self.assembler.firstPass(instructions) self.assembler.secondPass(instructions) self.assertEqual(["0b0000000000000000", "0b1110101010000010"], self.assembler.assemble(instructions))