Esempio n. 1
0
    def createRroverSpecies():
        '''
ifenemy 8 If there is an enemy
ifwall 6
ifsame 6
hop
go 1
right
go 1
infect
go 1


The rrover constantly moves forward.  When it
runs into a wall or another rrover, it turns right.
        '''

        ins0 = Instruction(OpCode.GO, 1)
        ins1 = Instruction(OpCode.IFENEMY, 8)
        ins2 = Instruction(OpCode.IFWALL, 6)
        ins3 = Instruction(OpCode.IFSAME, 6)
        ins4 = Instruction(OpCode.HOP, None)
        ins5 = Instruction(OpCode.GO, 1)
        ins6 = Instruction(OpCode.RIGHT, None)
        ins7 = Instruction(OpCode.GO, 1)
        ins8 = Instruction(OpCode.INFECT, None)
        ins9 = Instruction(OpCode.GO, 1)

        inss = [ins0, ins1, ins2, ins3, ins4, ins5, ins6, ins7, ins8, ins9]
        return Species("Rrover", inss)
Esempio n. 2
0
    def test_parse_reg_type(self):
        # Syntax (llvm): "if ($Pv4) vmem($Rx32++$Mu2):nt = $Os8.new"
        instr = Instruction(self.json["V6_vS32b_nt_new_pred_ppu"])
        operand = instr.operands["Os8"]
        self.assertEqual(0, instr.operands["Pv4"].syntax_index)
        self.assertEqual(1, instr.operands["Rx32"].syntax_index
                         )  # Rx32 is also an out operand because of the ++
        # self.assertEqual(2, instr.operands["Rx32in"].index)
        self.assertEqual(2, instr.operands["Mu2"].syntax_index)
        self.assertEqual(3, instr.operands["Os8"].syntax_index)
        self.assertEqual(3, instr.new_operand_index)
        self.assertTrue(operand.is_new_value)

        # Syntax (llvm): "if ($Pv4.new) memw($Rs32+$Ru32<<#$Ii) = $Nt8.new"
        instr = Instruction(self.json["S4_pstorerinewtnew_rr"])
        operand = instr.operands["Pv4"]
        self.assertTrue(operand.is_new_value)
        self.assertTrue(operand.is_predicate)

        operand = instr.operands["Nt8"]
        self.assertTrue(operand.is_new_value)

        self.assertEqual(0, instr.operands["Pv4"].syntax_index)
        self.assertEqual(1, instr.operands["Rs32"].syntax_index)
        self.assertEqual(2, instr.operands["Ru32"].syntax_index)
        self.assertEqual(3, instr.operands["Ii"].syntax_index)
        self.assertEqual(4, instr.operands["Nt8"].syntax_index)
Esempio n. 3
0
 def getInstruction(
     self, argumentTuple, relativePoint
 ):  #returns the instruction in the relevent location (or makes the pseudo data for literals)
     if (argumentTuple[0] == "$"):
         return Instruction("dat", [("", self.ROM[int(argumentTuple[1])])])
     atLocation = self.getLocation(argumentTuple, relativePoint)
     if (atLocation == -1):
         return Instruction("dat", [argumentTuple])
     return self.memory[atLocation]
Esempio n. 4
0
    def createHumanSpecies():
        '''
Totally control by human
        '''

        ins0 = Instruction(OpCode.GO, 1)
        ins1 = Instruction(OpCode.INTERACT, None)
        ins2 = Instruction(OpCode.GO, 1)

        inss = [ins0, ins1, ins2]
        return Species("Humanbeing", inss)
Esempio n. 5
0
def generateDistr():

    inss1 = Instruction.createAttackInstructions()
    inss2 = Instruction.createEscapeInstructions()
    inss3 = Instruction.createAttackAllInstructions()
    inss4 = Instruction.createAttackNoEmptyInstructions()
    inss5 = Instruction.createHopAllInstructions()

    species1 = Species("SmartPower", inss1)
    species2 = Species("EscapePower", inss2)
    species3 = Species("KillAllPower", inss3)
    species4 = Species("NoEmptyAttackPower", inss4)
    species5 = Species("HopAllpower", inss5)

    abilites1 = [Ability.FLY, Ability.ARCH]
    abilites2 = [Ability.ARCH]
    abilites3 = [Ability.FLY]
    abilites4 = []

    for number in range(Config.TERRIAN_F):
        terrianDistr.append(Terrian.FOREST)
    for number in range(Config.TERRIAN_H):
        terrianDistr.append(Terrian.HILL)
    for number in range(Config.TERRIAN_L):
        terrianDistr.append(Terrian.LAKE)
    for number in range(Config.TERRIAN_P):
        terrianDistr.append(Terrian.PLAIN)

    for number in range(Config.SPECIES_S):
        speciesDistr.append(species1)
    for number in range(Config.SPECIES_E):
        speciesDistr.append(species2)
    for number in range(Config.SPECIES_K):
        speciesDistr.append(species3)
    for number in range(Config.SPECIES_N):
        speciesDistr.append(species4)
    for number in range(Config.SPECIES_H):
        speciesDistr.append(species5)

    for number in range(Config.ABILITY_FA):
        abilityDistr.append(abilites1)
    for number in range(Config.ABILITY_A):
        abilityDistr.append(abilites2)
    for number in range(Config.ABILITY_F):
        abilityDistr.append(abilites3)
    for number in range(Config.ABILITY_):
        abilityDistr.append(abilites4)

    for number in range(Config.CREATURE_Y):
        creaturDistr.append(True)
    for number in range(Config.CREATURE_N):
        creaturDistr.append(False)
Esempio n. 6
0
    def createFoodSpecies():
        '''
left
go 1


Food just sits there and spins but doesn't infect anyone.
        '''

        ins0 = Instruction(OpCode.GO, 1)
        ins1 = Instruction(OpCode.LEFT, None)
        ins2 = Instruction(OpCode.GO, 1)
        inss = [ins0, ins1, ins2]
        return Species("Food", inss)
Esempio n. 7
0
def build_instructions(opcodes):
    program = []

    for opcode in opcodes:
        if opcode[0] is Instruction.CHAR:
            program.append(Instruction.inst_char(chr(opcode[1])))
        elif opcode[0] is Instruction.MATCH:
            program.append(Instruction.inst_match())
        elif opcode[0] is Instruction.SPLIT:
            program.append(Instruction.inst_split(opcode[1], opcode[2]))
        elif opcode[0] is Instruction.JUMP:
            program.append(Instruction.inst_jump(opcode[1]))

    return program
Esempio n. 8
0
def build_instructions(opcodes):
	program = []
	
	for opcode in opcodes:
		if opcode[0] is Instruction.CHAR:
			program.append(Instruction.inst_char(chr(opcode[1])))
		elif opcode[0] is Instruction.MATCH:
			program.append(Instruction.inst_match())
		elif opcode[0] is Instruction.SPLIT:
			program.append(Instruction.inst_split(opcode[1], opcode[2]))
		elif opcode[0] is Instruction.JUMP:
			program.append(Instruction.inst_jump(opcode[1]))
			
	return program		
Esempio n. 9
0
    def parse(line):
        reg_a = -1
        reg_b = -1
        reg_c = -1
        imm = -1
        type_ = ""

        if re.match("(LW|SW),([^, ]+),([^, ]+),([^, ]+)", line):
            m = re.match("(LW|SW),([^, ]+),([^, ]+),([^, ]+)", line)
            type_ = InstructionParser.get_type(m.group(1))
            reg_a = int(m.group(2))
            reg_b = int(m.group(3))
            imm = int(m.group(4))
        elif re.match("(JMP),([^, ]+),([^, ]+)",line):
            m = re.match("(JMP),([^, ]+),([^, ]+)",line)
            type_ = InstructionParser.get_type(m.group(1))
            reg_b = int(m.group(2))
            imm = int(m.group(3))
        elif re.match("(BEQ),([^, ]+),([^, ]+),([^, ]+)",line):
            m = re.match("(BEQ|ADDI),([^, ]+),([^, ]+),([^, ]+)",line)
            type_ = InstructionParser.get_type(m.group(1))
            reg_b = int(m.group(2))
            reg_c = int(m.group(3))
            imm = int(m.group(4))
        elif re.match("(ADDI),([^, ]+),([^, ]+),([^, ]+)",line):
            m = re.match("(BEQ|ADDI),([^, ]+),([^, ]+),([^, ]+)",line)
            type_ = InstructionParser.get_type(m.group(1))
            reg_a = int(m.group(2))
            reg_b = int(m.group(3))
            imm = int(m.group(4))
        elif re.match("(JALR),([^, ]+),([^, ]+)",line):
            m = re.match("(JALR),([^, ]+),([^, ]+)",line)
            type_ = InstructionParser.get_type(m.group(1))
            reg_a = int(m.group(2))
            reg_b = int(m.group(3))
        elif re.match("(RET),([^, ]+)",line):
            m = re.match("(RET),([^, ]+)",line)
            type_ = InstructionParser.get_type(m.group(1))
            reg_b = int(m.group(2))
        elif re.match("(ADD|SUB|ADDI|NAND|MUL),([^, ]+),([^, ]+),([^, ]+)",line):
            m = re.match("(ADD|SUB|ADDI|NAND|MUL),([^, ]+),([^, ]+),([^, ]+)",line)
            type_ = InstructionParser.get_type(m.group(1))
            reg_a = int(m.group(2))
            reg_b = int(m.group(3))
            reg_c = int(m.group(4))
        elif re.match("(HALT)",line):
            m = re.match("(HALT)",line)
            type_ = InstructionParser.get_type(m.group(1))
        inst = Instruction(type_)
        inst.set_reg_a(reg_a)
        inst.set_reg_b(reg_b)
        inst.set_reg_c(reg_c)
        inst.set_imm(imm)
        return inst
Esempio n. 10
0
    def createHopSpecies():
        '''
hop
go 1


This just hops forward blindly,
it's good for testing that your program works at all.
        '''

        ins0 = Instruction(OpCode.GO, 1)
        ins1 = Instruction(OpCode.HOP, None)
        ins2 = Instruction(OpCode.GO, 1)
        inss = [ins0, ins1, ins2]
        return Species("Hop", inss)
Esempio n. 11
0
    def parse_instructions(self) -> None:
        for i, i_name in enumerate(self.hexArch["!instanceof"]["HInst"]):
            llvm_instruction = self.hexArch[i_name]
            if llvm_instruction is None:
                log(
                    "Could not find instruction with name: {} in json file.".
                    format(i_name),
                    LogLevel.ERROR,
                )
                continue
            if llvm_instruction["isPseudo"]:
                log(
                    "Pseudo instruction passed. Name: {}".format(i_name),
                    LogLevel.VERBOSE,
                )
                continue
            log("{} | Parse {}".format(i, i_name), LogLevel.VERBOSE)
            self.llvm_instructions[i_name] = llvm_instruction

            if llvm_instruction["Type"]["def"] == "TypeSUBINSN":
                self.sub_instruction_names.append(i_name)
                self.sub_instructions[i_name] = SubInstruction(
                    llvm_instruction)
                # log(i_name, LogLevel.DEBUG)
            else:
                self.normal_instruction_names.append(i_name)
                self.normal_instructions[i_name] = Instruction(
                    llvm_instruction)

        log("Parsed {} normal instructions.".format(
            len(self.normal_instructions)))
        log("Parsed {} sub-instructions.".format(len(self.sub_instructions)))
def print_cfg(block):
    if block is not None:
        i = 0
        instructions = block.get_instructions()
        label = '{}\n'.format(block.get_block_name())
        while i < len(block.get_instructions()):
            instruction = instructions[i]
            if instruction.get_label1() == ' ':
                sublabel = '{} {} {} {} => {}\n'.format(
                    instruction.get_operation(), instruction.get_source_reg1(),
                    instruction.get_source_reg2(), instruction.get_immediate(),
                    instruction.get_destination_reg())
            else:
                sublabel = '{} {} {} -> {} {}\n'.format(
                    instruction.get_operation(), instruction.get_source_reg1(),
                    instruction.get_source_reg2(), instruction.get_label1(),
                    instruction.get_label2())
            label = label + sublabel
            i += 1
        dot.node(block.get_block_name(), label, shape='box')
        block.set_visited(True)
        child_blocks = block.get_next_blocks()
        no_of_child_blocks = len(child_blocks)
        if no_of_child_blocks > 0:
            for child_block in child_blocks:
                if not child_block.get_visited():
                    print_cfg(child_block)
                dot.edge(block.get_block_name(), child_block.get_block_name())
        else:
            instruction = Instruction('exit')
            block.add_instructions_to_list(instruction)
            dot.node('exit', 'exit')
            dot.edge(block.get_block_name(), 'exit')
    return
Esempio n. 13
0
def readFile():
    file = open("ejercicios/automata.txt", 'r')

    automata = []

    for i, line in enumerate(file):
        if i == 0:
            states = line.split('\n')[0].split(',')
            # print("States: "+str(states))
        elif i == 1:
            alphabet = line.split('\n')[0].split(',')
            # alphabet.append('E')
            # print("Alphabet: "+str(alphabet))
        elif i == 2:
            initial = line.split('\n')[0].split(',')[0]
            # print("Initial: "+str(initial))
        elif i >= 3:
            state = line.split('-')[0]
            options = line.split('\n')[0].split('>')[1].split('|')
            ins = Instruction(state, options)
            if state == initial:
                initial = ins
            automata.append(ins)

    file.close()

    return {'automata': automata, 'alphabet': alphabet, 'initial': initial, 'states': states}
Esempio n. 14
0
 def predict(self, inst):
     attribute = self.bp_table.get_data(inst.pc)
     if attribute is not None:
         self.total_predictions += 1
         target_pc = attribute.target_pc
         two_bits_prediction = predict_2bits(attribute.bits_state)
         miss_count_flag = attribute.miss_count_decision()
         curr_inst_num = inst.num
         next_inst_num = curr_inst_num + 1
         prediction_final = (not two_bits_prediction
                             ) if miss_count_flag else two_bits_prediction
         # prediction_final = inst.is_anomaly("Branch")
         if prediction_final == bool(inst.br_taken):
             self.success_count += 1
         if prediction_final == (not bool(inst.br_taken)):
             self.false_alarm_count += 1
         if next_inst_num < self.memory.len():
             next_inst = Instruction.inst_from_row(self.memory,
                                                   curr_inst_num + 1,
                                                   self.tid)
             if (next_inst.pc == target_pc) and prediction_final:
                 return next_inst_num
             else:
                 return BTB.WRONG_PC
     return self.NOT_FOUND
Esempio n. 15
0
 def translatePseudoInstruction(self, s):
     if (s[0] in ["neg", "negu"]):
         return Instruction(op="sub",
                            dest=s[1],
                            s1=s[2],
                            s2="$0",
                            regRead=1,
                            regWrite=1,
                            aluop=1)
     elif s[0] == "abs" and n == 0:
         return Instruction(op="abs",
                            s1=s[1],
                            regRead=1,
                            regWrite=1,
                            aluop=1)
     elif s[0] == "break":
         return Instruction(op='nop')
Esempio n. 16
0
    def createLandmineSpecies():
        '''
ifwall 5
ifsame 5
infect
go 1
left
go 1


The Land Mine turns until it is not facing a wall and then
just infects. It's lazy -- taking no risks and expending no
energy. The existence of Food does not favor the LandMine
since it will never move to find the food.
        '''

        ins0 = Instruction(OpCode.GO, 1)
        ins1 = Instruction(OpCode.IFWALL, 5)
        ins2 = Instruction(OpCode.IFSAME, 5)
        ins3 = Instruction(OpCode.INFECT, None)
        ins4 = Instruction(OpCode.GO, 1)
        ins5 = Instruction(OpCode.LEFT, None)
        ins6 = Instruction(OpCode.GO, 1)
        inss = [ins0, ins1, ins2, ins3, ins4, ins5, ins6]
        return Species("Landmine", inss)
    def extract_commands(self, json_dict):
        for jsonBlock in json_dict:
            instruction = Instruction()
            # Handle unknown or non existing keys
            if self.keys["command"] in jsonBlock:
                instruction.command = jsonBlock[self.keys["command"]]

            if self.keys["angle"] in jsonBlock:
                instruction.angle = jsonBlock[self.keys["angle"]]

            if self.keys["text"] in jsonBlock:
                instruction.text = jsonBlock[self.keys["text"]]

            if self.keys["time"] in jsonBlock:
                instruction.time = jsonBlock[self.keys["time"]]

            if self.keys["direction"] in jsonBlock:
                instruction.direction = jsonBlock[self.keys["direction"]]

            if self.keys["bodypart"] in jsonBlock:
                instruction.bodypart = jsonBlock[self.keys["bodypart"]]

            self.instructions.append(instruction)

        return self.instructions
Esempio n. 18
0
 def update(self, inst: Instruction, branch_taken_decision):
     curr_inst_num = inst.num
     next_inst_num = curr_inst_num + 1
     if next_inst_num < self.memory.len():
         next_inst = Instruction.inst_from_row(self.memory,
                                               curr_inst_num + 1, self.tid)
         target_pc = next_inst.pc
         inst_pc = inst.pc
         self.bp_table.add_data(inst_pc, target_pc, branch_taken_decision)
Esempio n. 19
0
def readFile():
    file = open("ejercicios/automata4.txt", 'r')

    automata = []

    for i, line in enumerate(file):
        if i == 0:
            states = line.split('\n')[0].split(',')
            # print("States: "+str(states))
        elif i == 1:
            alphabet = line.split('\n')[0].split(',')
            # alphabet.append('E')
            # print("Alphabet: "+str(alphabet))
        elif i == 2:
            initial = line.split('\n')[0].split(',')
            # print("Initial: "+str(initial))
        elif i == 3:
            final = line.split('\n')[0].split(',')
            # print("Final: "+str(final))
        elif i >= 4:
            initialState = line.split(',')[0]
            symbol = line.split(',')[1].split(':')[0]
            finalState = line.split(':')[1].split('\n')[0]
            ins = Instruction(initialState, finalState, symbol)
            if initialState in states and finalState in states and symbol in alphabet or symbol == 'E':
                automata.append(ins)
                # ins.show()
            else:
                if symbol != 'E':
                    print(
                        "Esta instruccion esta incorrecta, revisa que los estados existan o el simbolo este dentro del alfabeto.\n    Error en numero de linea: "
                        + str(i + 1))
                    ins.show()

    # print("Automata con # de trancisiones: "+str(len(automata)))

    file.close()

    return {
        'automata': automata,
        'alphabet': alphabet,
        'initial': initial,
        'final': final
    }
Esempio n. 20
0
 def add_instruction(self):
     if len(self.instructions) > 1:
         previous_time = self.instructions[-1].get_time()
         previous_date = self.instructions[-1].get_date()
     else:
         previous_time = None
         previous_date = None
     self.instructions.append(Instruction(time=previous_time, date=previous_date))
     self.tab_widget.addTab(self.instructions[-1].get_edit_frame(), str(self.tab_widget.count()))
     self.tab_widget.setCurrentWidget(self.instructions[-1].get_edit_frame())
Esempio n. 21
0
    def extract_instruction(self):
        extractor = CodeExtractor(self.src)
        instructions = extractor.get_instruction()
        arithmetic_ins = ArithmeticInstruction()
        ins = Instruction()
        push_ins = PushInstruction()
        goto_ins = GotoInstruction()
        func_ins = FunctionInstruction()
        lines = []
        func_name = ''
        file_name = 'default'
        for instruction in instructions:
            # print('translate', instruction)
            self.append_code(ins.comment(instruction))
            if instruction[0] == 'push':
                code = push_ins.push_other(instruction[1], instruction[2],
                                           file_name)
            elif instruction[0] == 'pop':
                code = push_ins.pop(instruction[1], instruction[2], file_name)
            elif instruction[0] == 'if-goto':
                label_name = self.get_label_name(func_name, instruction[1])
                code = goto_ins.if_goto(label_name)
            elif instruction[0] == 'goto':
                label_name = self.get_label_name(func_name, instruction[1])
                code = goto_ins.goto(label_name)
            elif instruction[0] == 'label':
                label_name = self.get_label_name(func_name, instruction[1])
                code = goto_ins.label(label_name)
            elif instruction[0] == 'function':
                func_name = instruction[1]
                file_name = func_name.split('.')[0]
                code = func_ins.execute(instruction[1], instruction[2])
            elif instruction[0] == 'call':
                code = func_ins.call(instruction[1], instruction[2],
                                     len(self.codes))
            elif instruction[0] == 'return':
                code = func_ins.return_code()
            else:
                code = arithmetic_ins.push_cal(instruction[0])
            self.append_code(code)

        print('翻译后汇编代码行数 ', len(self.codes))
Esempio n. 22
0
 def createRTypeInstruction(self, s):
     if s[0] in ["jr", "jalr"]:
         return Instruction(op=s[0], s1=s[1], regRead=1, aluop=0, branch=1)
     if (s[0] == "nop" or (s[0] == "sll" and s[1] == "$r0")):
         return Instruction(op='nop')
     if (s[0] in ["mult", "multu"]):
         return Instruction(op=s[0],
                            dest=s[1],
                            s1=s[1],
                            s2=s[2],
                            regRead=1,
                            regWrite=1,
                            aluop=1)
     if (s[0] in ["mflo", "mfhi"]):
         return Instruction(op=s[0],
                            dest=s[1],
                            s1=None,
                            s2=None,
                            regWrite=1,
                            aluop=1)
     if (s[0] in ["mtlo", "mthi"]):
         return Instruction(op=s[0],
                            dest=s[1],
                            s1=None,
                            s2=None,
                            regWrite=1,
                            aluop=1)
     if (s[0] in ['sll', 'srl', 'sra']):
         return Instruction(op=s[0],
                            dest=s[1],
                            s1=s[2],
                            shamt=s[3],
                            regRead=1,
                            regWrite=1,
                            aluop=1)
     if (s[0] in ['mac']):
         return Instruction(op=s[0],
                            dest=s[1],
                            s1=s[2],
                            s2=s[3],
                            s3=s[1],
                            regRead=1,
                            regWrite=1,
                            aluop=1)
     return Instruction(op=s[0],
                        dest=s[1],
                        s1=s[2],
                        s2=s[3],
                        regRead=1,
                        regWrite=1,
                        aluop=1)
def loadProgram(filename, INSTR):
    instructionCount = 0
    PCcount = 0
    placeHolders = getPlaceHolders(filename)

    # Open file
    programFile = open(filename, 'r')
    if (programFile == None):
        print("ERROR - File '%s' not found.\n", filename)
        sys.exit(1)

    while True:
        line = programFile.readline()
        # Stop the loop at end of file
        if not line:
            break

        # Remove blank lines
        if (line == '\n'):
            continue

        words = line.split(' ')
        # Remove comments
        if '//' in words[0]:
            continue

        # Remove commas and line endings
        if (len(words) == 1 and words[0][-1] == '\n'):
            words[0] = words[0][:-1]
            if (words[0][-1] == ':'):
                continue
        else:
            for i in range(1, len(words)):
                words[i] = words[i][:-1]

        newOpcode = words[0]
        newOperands = ['0'] * 3
        for i in range(1, len(words)):
            newOperands[i - 1] = words[i]

        # Replace place holders with correct PC value
        for i in range(0, 3):
            for j in range(0, len(placeHolders)):
                if (newOperands[i] == placeHolders[j][0]):
                    newOperands[i] = str(placeHolders[j][1])

        INSTR[instructionCount] = Instruction(newOpcode, newOperands[0],
                                              newOperands[1], newOperands[2],
                                              0)
        instructionCount += 1

    programFile.close()
 def build_instruction_list(self, instructions):
     instr_list = []
     for instruction in instructions:
         name = None
         index = 1
         for i in range(len(instruction) - 1):
             if instruction[i + 1] in instruction_library:
                 name = instruction[i]
                 index = i
         # if name == None:
         #     print(instruction)
         if name != None:
             instr_list.append(Instruction(instruction, index + 1))
     return instr_list
Esempio n. 25
0
 def get_instructions_bytes(self, code, varnames=None, names=None, constants=None,
                   cells=None, linestarts=None, line_offset=0):
     labels = self.args_jumps(code)
     starts_line = None
     for offset, op, arg in self.get_args(code):
         if self.linestarts is not None:
             starts_line = self.linestarts.get(offset, None)
             if starts_line is not None:
                 starts_line += self.line_offset
         is_jump_target = offset in labels
         argval = None
         argrepr = ''
         if arg is not None:
             argval = arg
             if op == 100: # LOAD_CONST
                 if constants is not None:
                     argval = constants[arg]
                     argrepr = repr(argval)
             elif op in [116, 90, 101, 160]: # LOAD_GLOBAL, LOAD_METHOD, STORE_NAME, LOAD_NAME
                 if names is not None and len(names) > 0:
                     argval = nam    es[arg]
                     argrepr = argval
                 else:
                     argrepr = repr(argval)
             elif op == 124 or op == 125: # LOAD_FAST, STORE_FAST
                 if varnames is not None and len(varnames) > 0:
                     argval = varnames[arg]
                     argrepr = argval
                 else:
                     argrepr = repr(argval)
             elif op == 107: # COMPARE_OP
                 argval = OPERADORES[arg]
                 argrepr = argval
                 pass
             elif op == FORMAT_VALUE:
                 argval, argrepr = FORMAT_VALUE_CONVERTERS[arg & 0x3]
                 argval = (argval, bool(arg & 0x4))
                 if argval[1]:
                     if argrepr:
                         argrepr += ', '
                     argrepr += 'with format'
             elif op == MAKE_FUNCTION:
                 argrepr = ', '.join(s for i, s in enumerate(MAKE_FUNCTION_FLAGS)
                                     if arg & (1<<i))
         yield Instruction(CODES.get(op), op,
                           arg, argval, argrepr, 
                           offset, starts_line, is_jump_target)
Esempio n. 26
0
def main(fileName): 
    global compilersWords
    global compilersWords2
    instructionSuccess = list()
    instructionErrorList = list()
    i = 1
    with open(fileName) as file:
        for line in file: 
            instructionSuccessAux = list()
            if line != '\n' and not re.match(r"#include", line):
                while len(line) > 0:
                    if re.fullmatch(r"\s+",line):
                        break
                    print(line)
                    #time.sleep(2)
                    for key in compilersWords: 
                        if len(line) == 0:
                            break
                        match = re.search(key, line)
                        if match :
                            print(match)
                            print(line)
                            instruction = line[match.start():match.end()]
                            #print(instruction)
                            line = line[0:match.start()] + line[match.end():] 
                            line = line.replace("\n", "")
                            instruction = instruction.replace(" ", "")
                            #print(line)
                            #print('-----------')
                            message = compilersWords[key]['message']
                            instructionObj = Instruction(instruction, message,i)
                            instructionSuccessAux.append(instructionObj)
                            #break
                            
                instructionSuccess.append(instructionSuccessAux) 
            i += 1
    file.close()

    for i in range(len(instructionSuccess)):
        print(f"{i} --> {len(instructionSuccess[i])}")

    return instructionSuccess, instructionErrorList                
Esempio n. 27
0
 def createEndInstruction(self, instructions):
     replaceindex = -1
     # Find index to input END in
     for idx, instr in enumerate(reversed(instructions)):
         if instr.op == 'jr':
             replaceindex = len(instructions) - idx
             break
     if (replaceindex != -1):
         # Create and insert END instruction (only used by simulator)
         instructions.pop(replaceindex - 1)
         instructions.insert(
             replaceindex,
             Instruction(op="END",
                         dest=None,
                         s1=None,
                         s2=None,
                         regRead=0,
                         regWrite=0,
                         aluop=0))
     return instructions
Esempio n. 28
0
    def readInstructions(self):
        #inicializar la memoria:
        '''
		  dMem[0] = DADDR_SIZE - 1 ;
		  for (loc = 1 ; loc < DADDR_SIZE ; loc++)
		      dMem[loc] = 0 ;
		'''
        self.dMem = [0 for x in range(0, DADDR_SIZE)]
        self.dMem[0] = DADDR_SIZE - 1

        #inicializar los registros
        '''
		  for (regNo = 0 ; regNo < NO_REGS ; regNo++)
		      reg[regNo] = 0 ;
		'''
        self.reg = [0 for x in range(0, NO_REGS)]

        for line in self.pgm:
            instruction = Instruction(line)
            if instruction.iop == Mnemonics.DEFINE:
                self.hashTable[instruction.arg3] = instruction
            else:
                self.iMem[instruction.lineNo] = instruction
Esempio n. 29
0
    def __init__(self, code):
        self.labels = {
        }  # Dictionary mapping label name to the index in the instruction list
        self.frame_stack = [
        ]  # Stack(list) with containing local variable frames
        self.tmp_frame = None  # Temporary variable frame
        self.global_frame = Frame()  # Global variable frame
        self.data_stack = [
        ]  # Data stack containing values during program interpretation
        self.call_stack = [
        ]  # Stack of return addresses for CALL/RETURN instruction pairs
        self.instructions = []  # A list of instructions
        self.next_instruction = 0  # Next instruction to execute

        # XML structure validation
        if code.tag != "program":  # Root element check
            raise BadXMLError("Root element needs to be \"program\"!")

        for at in code.attrib:  # Attribute values check
            if not re.match(r'(language|name|description)', at):
                raise BadXMLError("Invalid element %s" % at)

        if code.attrib.get(
                "language",
                None) != "IPPcode18":  # Language attribute validation
            raise BadXMLError("Invalid or missing \"language\" attribute!")

        # Convert XML instructions into internal representation
        for instr in code:
            self.instructions.append(Instruction(instr))

        # Sort instructions based on their order - prepare for in-order execution
        self.instructions.sort(key=lambda i: i.order, reverse=False)

        # Check for invalid instruction orders
        if len(self.instructions) > 0 and self.instructions[0].order < 1:
            raise BadXMLError("Instruction order must be a positive!")
Esempio n. 30
0
    def fetch_instruction (self, is_decoder_stalled = False):
        """Based on PC value, fetch instruction from memory.

        Update PC.
        Return fetcher_buffer for the next cycle.
        """
        if is_decoder_stalled:
            # self.fetcher_buffer.clear()
            return

        # TODO: Maybe use is_valid_PC later
        try:
            self.fetcher_buffer.instr = Instruction(
                self.memory[self.fetch_input_buffer.PC])
            print 'self.fetcher_buffer.instr: ', self.fetcher_buffer.instr
            self.fetcher_buffer.PC = self.fetch_input_buffer.PC
            self.fetcher_buffer.npc = self.fetcher_buffer.PC + 4
            self.fetch_input_buffer.PC = self.fetcher_buffer.npc
            self.fetch_input_buffer.instr_count += 1

            print 'updated PC'
        except IndexError:
            # self.fetcher_buffer.clear()
            pass
Esempio n. 31
0
    def __init__(self, memorySize, programs, doRender=True):
        self.doRender = doRender
        self.tickLimit = -1
        self.size = memorySize
        self.threadLimit = 32
        self.ROM = [memorySize - 1, 0, 0, 0]
        self.playerCounters = []
        self.memory = []
        self.changesList = []

        numberNoOps = memorySize
        for prog in programs:
            numberNoOps -= len(prog)
        if (numberNoOps < 0): return
        nopSizes = [numberNoOps]
        while (len(nopSizes) < len(programs)):
            largest = max(nopSizes)
            nopSizes.remove(largest)
            newVal = random.randint(0, largest)
            newVal2 = largest - newVal
            nopSizes.append(newVal)
            nopSizes.append(newVal2)
        count = 0
        numbers = range(0, len(programs))
        for nopSize in nopSizes:
            if (len(numbers) > 0):
                randomIndex = numbers.pop(random.randint(0, len(numbers) - 1))
                self.memory += programs[randomIndex]
                self.playerCounters.append(
                    PlayerProgramCounter(self, randomIndex, count))
                count += len(programs[randomIndex])
            self.memory += [Instruction() for j in xrange(nopSize)]
            count += nopSize
        self.modValues()
        self.currentPlayer = 0
        return
Esempio n. 32
0
    def __init__(self, instructions=None, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.setContentsMargins(0, 0, 0, 0)
        
        if instructions == None:
            self.instructions = list()
        else:
            self.instructions = instructions
        if len(self.instructions) < 1:
            print 'appending instruction'
            self.instructions.append(Instruction())
        
        self.grid = QtGui.QFormLayout()
        
        self.question_entry = QtGui.QLineEdit()
        self.grid.addRow('Question for patient', self.question_entry)
        
        self.tab_widget = QtGui.QTabWidget()
        self.grid.addRow(self.tab_widget)
        
        for i in range(len(self.instructions)): 
            print 'added to tab widget: ' + str(self.instructions[i])
            self.tab_widget.addTab(self.instructions[i].get_edit_frame(), str(i))
        
        self.delete_button = QtGui.QPushButton('Delete Instruction')
        self.delete_button.clicked.connect(self.delete_instruction)  
        
        self.add_button = QtGui.QPushButton('Add Instruction') 
        self.add_button.clicked.connect(self.add_instruction)

        self.grid2 = QtGui.QGridLayout()
        self.grid2.addWidget(self.add_button, 0, 0)
        self.grid2.addWidget(self.delete_button, 0, 1)
        self.grid.addRow(self.grid2)
            
        self.setLayout(self.grid)
Esempio n. 33
0
    def createPathFinderSpecies():
        '''
ifempty 4
left
go 1
hop
go 1

The path_finder is more intelligent than the hop. If the square it faces is
not empty, it turns left. Otherwise, it moves forward.
        '''

        ins0 = Instruction(OpCode.GO, 1)
        ins1 = Instruction(OpCode.IFEMPTY, 4)
        ins2 = Instruction(OpCode.LEFT, None)
        ins3 = Instruction(OpCode.GO, 1)
        ins4 = Instruction(OpCode.HOP, None)
        ins5 = Instruction(OpCode.GO, 1)

        inss = [ins0, ins1, ins2, ins3, ins4, ins5]
        return Species("PathFinder", inss)
def generate_3address_code(statement_list):
    global block_counter
    block = Block('B' + str(block_counter))
    head = block
    block_counter += 1
    i = 0
    statements = statement_list.get_statements()
    while i < len(statements):
        statement = statements[i]
        if statement.get_name() == ':=':
            left_expr = evaluate_expr(statement.get_left_expr(), block)
            right_expr = evaluate_expr(statement.get_right_expr(), block)
            instruction = Instruction('mov')
            instruction.set_source_reg1(right_expr.get_register())
            instruction.set_destination_reg(left_expr.get_register())
            block.add_instructions_to_list(instruction)
        elif statement.get_name() == 'while':
            block2 = Block('B' + str(block_counter))
            block_counter += 1
            jump_instr = Instruction('jumpl')
            jump_instr.set_label1(block2.get_block_name())
            block.add_instructions_to_list(jump_instr)
            block.add_next_block(block2)
            cond_expr = evaluate_expr(statement.get_cond_expr(), block2)
            success_block = generate_3address_code(statement.get_while_block_stmt_list())
            success_block.add_instructions_to_list(jump_instr)
            success_block.add_next_block(block2)
            instruction = Instruction('cbr')
            instruction.set_source_reg1(cond_expr.get_register())
            instruction.set_label1(success_block.get_block_name())
            block = Block('B' + str(block_counter))
            block_counter += 1
            instruction.set_label2(block.get_block_name())
            block2.add_instructions_to_list(instruction)
            block2.add_next_block(success_block)
            block2.add_next_block(block)
        elif statement.get_name() == 'if':
            block2 = Block('B' + str(block_counter))
            block_counter += 1
            jump_instr = Instruction('jumpl')
            jump_instr.set_label1(block2.get_block_name())
            block.add_instructions_to_list(jump_instr)
            block.add_next_block(block2)
            cond_expr = evaluate_expr(statement.get_cond_expr(), block2)
            if_block = generate_3address_code(statement.get_if_block_stmt_list())
            else_block = generate_3address_code(statement.get_else_block_stmt_list())
            instruction = Instruction('cbr')
            instruction.set_source_reg1(cond_expr.get_register())
            instruction.set_label1(if_block.get_block_name())
            instruction.set_label2(else_block.get_block_name())
            block2.add_instructions_to_list(instruction)
            block2.add_next_block(if_block)
            block2.add_next_block(else_block)
            j = i + 1
            if j < len(statements):
                block = Block('B' + str(block_counter))
                block_counter += 1
                jump_instr.set_label1(block.get_block_name())
                if_block.add_instructions_to_list(jump_instr)
                else_block.add_instructions_to_list(jump_instr)
                if_block.add_next_block(block)
                else_block.add_next_block(block)
        else:
            expr = evaluate_expr(statement.get_expr(), block)
            instruction = Instruction('writeint')
            instruction.set_source_reg1(expr.get_register())
            block.add_instructions_to_list(instruction)
        i += 1

    return head
def evaluate_expr(expr, block):
    if expr.get_node_type() == 'ident':
        expr.set_register(ident_regs[expr.get_name()])
    else:
        if expr.get_node_type() == 'num':
            instruction = Instruction('movi')
            instruction.set_immediate(expr.get_name())
        elif expr.get_node_type() == 'bool':
            if expr.expr.get_name() == 'false':
                numvalue = '0'
            else:
                numvalue = '1'
            instruction = Instruction('movi')
            instruction.set_immediate(numvalue)
        elif expr.get_name() == 'readint':
            instruction = Instruction('readint')
        else:
            if expr.get_name() == '+':
                instruction = Instruction('add')
            elif expr.get_name() == '*':
                instruction = Instruction('mul')
            elif expr.get_name() == '-':
                instruction = Instruction('sub')
            elif expr.get_name() == 'div':
                instruction = Instruction('div')
            elif expr.get_name() == 'mod':
                instruction = Instruction('rem')
            elif expr.get_name() == '=':
                instruction = Instruction('seq')
            elif expr.get_name() == '!=':
                instruction = Instruction('sne')
            elif expr.get_name() == '<':
                instruction = Instruction('slt')
            elif expr.get_name() == '<=':
                instruction = Instruction('sle')
            elif expr.get_name() == '>':
                instruction = Instruction('sgt')
            elif expr.get_name() == '>=':
                instruction = Instruction('sge')
            left_expr = evaluate_expr(expr.get_left_expr(), block)
            right_expr = evaluate_expr(expr.get_right_expr(), block)
            instruction.set_source_reg1(left_expr.get_register())
            instruction.set_source_reg2(right_expr.get_register())
            add_registers_to_queue(left_expr.get_register())
            add_registers_to_queue(right_expr.get_register())
        reg = get_register()
        instruction.set_destination_reg(reg)
        block.add_instructions_to_list(instruction)
        expr.set_register(reg)
    return expr