Example #1
0
    def p_move(self, player):
        # pierwsza wyswietlanie ma byc wolne
        sec = 0.005
        while True:
            os.system('cls')
            Load.room.introduce(self.id_room - 1, sec)

            if self.id_room < 8:
                print("-" * 20 + "\n\nGdzie się ruszasz? (1/2/3)\n")
                print("1. " + Load.room.rooms_doors[self.id_room * 2 + -1])
                print("2. " + Load.room.rooms_doors[self.id_room * 2])

                if self.id_room > 1:
                    print("3. Zawróć")
                    print("\nLub...\n4. Wykonaj akcje\n")

                move = input(">>>")

                if move == "1":
                    self.id_room *= 2
                    break

                if move == "2":
                    self.id_room = self.id_room * 2 + 1
                    break

                if self.id_room > 1:
                    if move == "3":
                        self.id_room = int(self.id_room / 2)
                        break

                    if move == "4":
                        Load.action[self.id_room - 2].do_action(
                            player, Load.room, self.id_room - 1)
                        break

            else:
                print("-" * 20 + "\nGdzie się ruszasz? (1/2)\n")
                print("1. Wejdź do portalu")
                print("2. Zawróć")
                print("\nLub...\n3. Wykonaj akcje\n")

                move = input(">>>")

                if move == "1":
                    Code.guess(player)
                    exit(0)
                    break

                if move == "2":
                    self.id_room = int(self.id_room / 2)
                    break

                if move == "3":
                    Load.action[self.id_room - 2].do_action(
                        player, Load.room, self.id_room - 1)
                    break

            # kolejne wyswitlanie ma byc szybkie
            sec = 0
Example #2
0
def read_mic_engines():
    configuration = Code.configuration
    file = Code.path_resource("IntFiles", "mic_tourney.eval")

    with open(file) as f:
        li = []
        for linea in f:
            dic = eval(linea.strip())
            alias = dic["ALIAS"]
            nom_base_engine = dic["ENGINE"]
            id_info = dic["IDINFO"]
            elo = dic["ELO"]
            li_uci = [(d["name"], d["valor"]) for d in dic["LIUCI"]]

            engine = configuration.dic_engines.get(nom_base_engine)
            if engine:
                eng = engine.clona()
                eng.name = alias
                eng.id_info = id_info
                eng.alias = alias
                eng.elo = elo
                eng.liUCI = li_uci
                if alias.isupper():
                    eng.name = Util.primera_mayuscula(alias)
                    eng.alias = eng.name
                    eng.book = Code.path_resource("Openings", "Players",
                                                  "%s.bin" % alias.lower())
                else:
                    eng.book = None
                li.append(eng)
    return li
Example #3
0
 def generate_h_code(self, env, result):
     public_vars_and_funcs = []
     public_extension_types = []
     for entry in env.var_entries:
         if entry.visibility == 'public':
             public_vars_and_funcs.append(entry)
     for entry in env.cfunc_entries:
         if entry.visibility == 'public':
             public_vars_and_funcs.append(entry)
     for entry in env.c_class_entries:
         if entry.visibility == 'public':
             public_extension_types.append(entry)
     if public_vars_and_funcs or public_extension_types:
         result.h_file = replace_suffix(result.c_file, ".h")
         result.i_file = replace_suffix(result.c_file, ".pxi")
         h_code = Code.CCodeWriter(open_new_file(result.h_file))
         i_code = Code.PyrexCodeWriter(result.i_file)
         self.generate_extern_c_macro_definition(h_code)
         for entry in public_vars_and_funcs:
             h_code.putln("%s %s;" %
                          (Naming.extern_c_macro,
                           entry.type.declaration_code(
                               entry.cname, dll_linkage="DL_IMPORT")))
             i_code.putln("cdef extern %s" %
                          entry.type.declaration_code(entry.cname, pyrex=1))
         for entry in public_extension_types:
             self.generate_cclass_header_code(entry.type, h_code)
             self.generate_cclass_include_code(entry.type, i_code)
         h_code.putln("PyMODINIT_FUNC init%s(void);" % env.module_name)
Example #4
0
    def selecciona(self, type_play):
        self.game_type = type_play
        if type_play == GT_FICS:
            self._db = Code.path_resource("IntFiles", "FicsElo.db")
            self._activo = self.configuration.ficsActivo
            self._ponActivo = self.configuration.ponFicsActivo
            self.nombreObj = _(
                "Fics-player"
            )  # self.cabs[ "White" if self.human_side else "Black" ]
            self._fichEstad = self.configuration.fichEstadFicsElo
            self._titulo = _("Fics-Elo")
            self._newTitulo = _("New Fics-Elo")
            self._TIPO = "FICS"

        elif type_play == GT_FIDE:
            self._db = Code.path_resource("IntFiles", "FideElo.db")
            self._activo = self.configuration.fideActivo
            self._ponActivo = self.configuration.ponFideActivo
            self.nombreObj = _(
                "Fide-player"
            )  # self.cabs[ "White" if self.human_side else "Black" ]
            self._fichEstad = self.configuration.fichEstadFideElo
            self._titulo = _("Fide-Elo")
            self._newTitulo = _("New Fide-Elo")
            self._TIPO = "FIDE"

        elif type_play == GT_LICHESS:
            self._db = Code.path_resource("IntFiles", "LichessElo.db")
            self._activo = self.configuration.lichessActivo
            self._ponActivo = self.configuration.ponLichessActivo
            self.nombreObj = _("Lichess-player")
            self._fichEstad = self.configuration.fichEstadLichessElo
            self._titulo = _("Lichess-Elo")
            self._newTitulo = _("New Lichess-Elo")
            self._TIPO = "LICHESS"
Example #5
0
    def __init__(self, lexer, parser, parent):
        Token.__init__(self, 'If-condition', lexer, parser, parent)

        # Expect an expression.
        lexer.expect(self, 'keyword', 'if')
        lexer.expect(self, 'whitespace')
        self.expression = Expression(lexer, parser, parent)
        self.mark_end()

        # Body of the if block.
        self.if_block = Code.Code(lexer, parser, parent)
        self.elif_blocks = []
        self.else_block = None

        # If there is no "else" statement, just return.
        lexer.skip(['whitespace', 'newline'])
        if not lexer.next_if('keyword', 'else'):
            return

        # If the "else" statement is followed by an "if" (=elif),
        # read the next if condition recursively and return.
        lexer.skip(['whitespace', 'newline'])
        if lexer.current_is('keyword', 'if'):
            self.else_block = IfCondition(lexer, parser, parent)
            return

        # There was no "elif", so we handle a normal "else" condition here.
        self.else_block = Code.Code(lexer, parser, parent)
Example #6
0
    def generate_c_code(self, env, result):
        modules = []
        self.find_referenced_modules(env, modules, {})
        #code = Code.CCodeWriter(result.c_file)
        code = Code.CCodeWriter(StringIO())
        code.h = Code.CCodeWriter(StringIO())
        code.init_labels()
        self.generate_module_preamble(env, modules, code.h)

        code.putln("")
        code.putln("/* Implementation of %s */" % env.qualified_name)
        self.generate_const_definitions(env, code)
        self.generate_interned_name_decls(env, code)
        self.generate_py_string_decls(env, code)
        self.body.generate_function_definitions(env, code)
        self.generate_interned_name_table(env, code)
        self.generate_py_string_table(env, code)
        self.generate_typeobj_definitions(env, code)
        self.generate_method_table(env, code)
        self.generate_filename_init_prototype(code)
        self.generate_module_init_func(modules[:-1], env, code)
        self.generate_filename_table(code)
        self.generate_utility_functions(env, code)

        for module in modules:
            self.generate_declarations_for_module(module,
                                                  code.h,
                                                  definition=module is env)

        f = open_new_file(result.c_file)
        f.write(code.h.f.getvalue())
        f.write("\n")
        f.write(code.f.getvalue())
        f.close()
        result.c_file_generated = 1
Example #7
0
 def createGuess(self):
     newGuess = Code([])
     # for as long as the game is in one of the first three phases, use makePhaseGuess to create the next guess
     if self.phaseRound:
         newGuess = self.makePhaseGuess()
     else:
         self.guessList = self.environment.getGuessList()
         self.clueList = self.environment.getClueList()
         # first, check to see if the game has been won with the latest guess
         if self.clueList[self.guessCount - 1].getBlackPegs() == 4:
             # if the game has been won, end the program
             self.won = True
             print("Correct guess has been made!")
         if self.testCompleted:
             self.analyzeTest = True
         else:
             # if the game just finished testing out two pins, check the result
             if self.analyzeTest:
                 print("Just finished testing two pins.")
                 self.analyzeTest = False
                 self.testCompleted = False
             # a temporary list used to narrow down color choices for a single guess
             clist = self.viableColors.copy()
             # TODO: Define createGuess past this point
             newGuess = Code([])
     # update the guess list
     self.guess = newGuess
Example #8
0
def main_menu():
    "This function contains the main menu of the game"
    print("1. PLAY THE GAME\n2. EXIT THE GAME\n")

    ##Displaying error if user enters values that aren't integers
    try:
        menu = int(input("Choose 1 or 2 from above menu:"))
    except ValueError:
        print("\nPLEASE ENTER 1 OR 2 AS YOUR CHOICE!\n")
        print("-------------------------------------\n")
        ##Calling 'main_menu' inside 'Menu' module
        main_menu()

    ##Exiting game if user enters 2
    if menu == 2:
        exit()
    else:
        ##Starting game if user enters 1
        if menu == 1:
            ##Calling 'desc_user_interface' inside 'Game_Details' module
            details.desc1()
            ##Calling 'desc_txtfile' inside 'Game_Details' module
            details_txt.desc2()
            ##Calling 'main_code' inside 'Code' module
            Code.main_code()
        else:
            ##If user enters number other than 1 or 2
            if menu != 1 or menu != 2:
                print("\nPLEASE ENTER 1 OR 2 AS YOUR CHOICE!\n")
                print("-------------------------------------\n")
                ##Calling 'main_menu' inside 'Menu' module
                main_menu()
    return
Example #9
0
    def translators(self):
        txt = self.table_ini(center=False, border="0")
        txt += "<tr><td>"
        txt += self.dl_ini()
        li = os.listdir(Code.path_resource("Locale"))
        salto = len(li) // 2
        for n, lng in enumerate(li):
            d = Util.ini_base2dic(
                Code.path_resource("Locale", "%s/lang.ini" % lng))
            if n >= salto:
                salto = 99
                txt += self.dl_end()
                txt += "</td><td>"
                txt += self.dl_ini()
            txt += self.dl_tit(d["NAME"])
            txt += self.dl_elem(d["AUTHOR"])
            if "PREVIOUS" in d:
                txt += self.dl_elem("%s: %s" % (_("Previous"), d["PREVIOUS"]))

        txt += self.dl_end()
        txt += "</td></tr>"
        txt += self.table_end()
        txt += '<br><big><bold><center>%s: <a href="https://poeditor.com">https://poeditor.com</a></center></bold></big>' % _(
            "Web")
        return txt
Example #10
0
File: Parser.py Project: ryoua/OS
def comp(line):
    if line.find('=') > 0:
        complist1 = line.split('=')
        return Code.comp(complist1[1].strip('\n'))
    elif line.find(';') >= 0:
        complist2 = line.split(';')
        return Code.comp(complist2[0].strip(' '))
Example #11
0
 def removeBadCodes(self, blackPegs, whitePegs, currGuess):
     newCandidateCodes = []
     for i in self.candidateCodes:
         response = Code(i).getClue(currGuess)
         if response.getWhitePegs() == whitePegs and response.getBlackPegs(
         ) == blackPegs:
             newCandidateCodes.append(i)
     self.candidateCodes = newCandidateCodes.copy()
Example #12
0
def train(trainingdocs, classes):
	import Code
	print "Beginning training"
	vocab = set()
	docs = []
	bigdoc = []
	logprior = {}
	loglikelihood ={}
	for item in trainingdocs:
		docname = item[0]
		doctext = Code.get_text(docname)
		email = Code.ProcessedEmail(doctext)
		#get vocab
		#V <- set of words in docs
		vocab = vocab | (Code.get_vocab(email))

	print "VOCAB CREATED"
	#Nd =number of docs
	Nd = len(trainingdocs) 

	for c in classes:
		bigdoc = Code.get_docs_in_class(c, trainingdocs)

		#Nc = number of docs from D in c 
		Nc = len(bigdoc)
		
		#calc prior
		logprior[c] = math.log(Nc / float(Nd))
		#print(logprior[c])

		total=total_words_in_docs(bigdoc)

		#bigdoc[c] <- append d for d EE D with class c
		#bigdoc = Code.getdocsinclass(str(c), docs) 
		#print "BIG"
		#print bigdoc
		i=0
		for word in vocab:
			i = i+1
			percent = float(float(i) / len(vocab)) * 100
			#print "class: " + str(c)
			#print "word " + str(i) + "/" + str(len(vocab))
			
	#		print str(float(int(percent*10))/10)+"%"

			countwc = count_words_in_docs(word, bigdoc)
			
			x = float(countwc + 1)
			y = float((total + len(vocab)))
			loglikelihood[word, c] = math.log(x/y)
	
	#ENABLE THIS TO GET GOOD IDEA OF ASSOCIATION OF WORDS AND CLASSES
	#print "likelihoods:"
	#for word in loglikelihood: 
	#	print str(word) + ": " + str(loglikelihood[word])
	
	return (logprior, loglikelihood, vocab)
Example #13
0
    def __call__(self, *args):
        if type(self.code) == Code.FunctionType:
            self.code()
        else:
            Code.execute(self.code, verbose=False)

        Code.LiveObject.__call__(self)

        return
Example #14
0
def buildCode(line):
    binaryString = ''
    if '@' in line:
        binaryString += '0' + symbolToBinary(''.join(line[1:]))
    else:
        binaryString += '111' + c.comp(comp(line)) + c.dest(
            dest(line)) + c.jump(jump(line))
    binaryString += "\n"
    return binaryString
Example #15
0
    def __call__(self, *args):
        if type(self.code) == Code.FunctionType:
            self.code()
        else:
            Code.execute(self.code, verbose=False)

        Code.LiveObject.__call__(self)
        
        return
Example #16
0
 def put_line_debug(self, line: str):
     if self.working:
         Code.xpr(self.name, "put>>> %s\n" % line)
         self.stdin_lock.acquire()
         line = line.encode()
         if self.log:
             self.log_write(">>> %s\n" % line)
         self.stdin.write(line + b"\n")
         self.stdin.flush()
         self.stdin_lock.release()
Example #17
0
def total_words_in_docs(docs):
	import Code
	total=0
	#print "docs; " + str(docs)

	for doc in docs:
		email = Code.ProcessedEmail(Code.get_text(doc))
		total += len(Code.get_vocab(email))
		#print "sum" + str(total)
	return total
Example #18
0
def main():
    if len(sys.argv) < 2:
        print(u"使い方: %s FILENAME" % sys.argv[0])
        sys.exit(1)

    asm_file = sys.argv[1]
    hack_file = os.path.splitext(asm_file)[0] + ".hack"
    st = SymbolTable()

    # SymbolTable作成
    with Parser(asm_file) as hp:
        # ROM アドレス
        op_address = 0

        # 1行ごとに読みながら, ROMアドレス番号を保持
        while hp.advance() != None:
            cmd_type = hp.commandType()
            if cmd_type == A_COMMAND or cmd_type == C_COMMAND:
                op_address += 1
            elif cmd_type == L_COMMAND:
                st.addEntry(hp.symbol(), op_address)

    # シンボルをアドレスに置き換え, 機械語コードの生成
    with Parser(asm_file) as hp:
        with open(hack_file, 'w') as wf:
            # 1行ごとに構文解析
            while hp.advance() != None:
                cmd_type = hp.commandType()
                # print(cmd_type)

                # A_COMMAND の変数を処理
                if cmd_type == A_COMMAND:
                    symbol = hp.symbol()
                    m = SYMBOL_PATTERN.match(symbol)

                    if m.group(1):  # @100など
                        bincode = '0' + int_to_bin(int(m.group(1)))

                    # SymbolTableに書き込み
                    elif m.group(2):  # @SYMBOL など
                        # symbol = m.group(2)
                        if st.contains(symbol):
                            address = st.getAddress(symbol)
                            bincode = '0' + int_to_bin(address, 15)
                        else:
                            st.addVariable(symbol)
                            address = st.getAddress(symbol)
                            bincode = '0' + int_to_bin(address, 15)

                elif cmd_type == C_COMMAND:
                    bincode = "111" + Code.comp(hp.comp()) + Code.dest(
                        hp.dest()) + Code.jump(hp.jump())

                if cmd_type != L_COMMAND:
                    wf.write(bincode + '\n')
Example #19
0
def _c_has_jump(dest_comp_jump):
    if "=" in dest_comp_jump[0]:
        dest_comp = dest_comp_jump[0].split("=")
        dest = Code.c_dest_binary(dest_mnemonic(dest_comp[0]))
        comp = Code.c_comp_binary(comp_mnemonic(dest_comp[1]))
    else:  #no dest in jump scenario
        dest = Code.c_dest_binary("null")
        comp = Code.c_comp_binary(dest_comp_jump[0])

    jump = Code.c_jump_binary(dest_comp_jump[1])
    return comp + dest + jump
Example #20
0
    def jump(self):
        """
        gets where to jump to afterwards
        :return:
        """

        if self.command_type() == CONTROL_COMMAND:
            if ";" in self.current_command:
                return Code.jump(self.current_command.split(';')[1])
            else:
                return Code.jump("")
Example #21
0
def code_setup():
    '''
    Set up code_solution and code_effect dictionaries and send code_solution to Dawn
    '''
    global code_solution
    global code_effect

    code_solution = Code.assign_code_solution()
    code_effect = Code.assign_code_effect()
    msg = {"codes_solutions": code_solution}
    lcm_send(LCM_TARGETS.DAWN, DAWN_HEADER.CODES, msg)
Example #22
0
    def dest(self):
        """
        gets the destination in string form
        :return: the destination
        """

        if self.command_type() == CONTROL_COMMAND:

            if '=' in self.current_command:
                return Code.dest(self.current_command.split('=')[0])
            else:
                return Code.dest("")
Example #23
0
    def __init__(self, target):

        index = target.find('.asm')
        if (index < 1):
            raise RuntimeError("error, cannot use the filename: " + target)

        self.inputFileName = target
        self.outputFileName = self.inputFileName[:index] + '.hack'

        self.parser = Parser(self.inputFileName)

        self.code = Code()
        self.st = SymbolTable()
Example #24
0
 def saveAllPNG(self, name, px):
     for pieza in "pnbrqk":
         for color in "wb":
             fich = Code.path_resource("Pieces", name, "%s%s.svg" % (color, pieza))
             with open(fich, "rb") as f:
                 qb = QtCore.QByteArray(f.read())
             pm = QtGui.QPixmap(px, px)
             pm.fill(QtCore.Qt.transparent)
             render = QtSvg.QSvgRenderer(qb)
             painter = QtGui.QPainter()
             painter.begin(pm)
             render.render(painter)
             painter.end()
             pm.save(Code.path_resource("IntFiles", "Figs", "%s%s.png" % (color, pieza)), "PNG")
Example #25
0
    def test_get_multiple_episodes(self):
        ep_list = Code.get_episodes([8, 10, 15, 16])
        self.assertEqual(len(ep_list), 4)
        self.assertEqual(ep_list[0][0], '8')
        self.assertEqual(ep_list[1][0], '10')
        self.assertEqual(ep_list[2][0], '15')
        self.assertEqual(ep_list[3][0], '16')

        self.assertEqual(Code.get_episodes([]), 'error')
        self.assertRaises(TypeError, Code.get_episodes(), ['b'])

        mocked_parameter = Mock()
        ret_val = Code.get_episodes(mocked_parameter)
        self.assertFalse(mocked_parameter.called)
        self.assertEqual(ret_val, 'error')
Example #26
0
    def test_get_multiple_character(self):
        char_list = Code.get_characters([1, 2, 4, 6])
        self.assertEqual(len(char_list), 4)
        self.assertEqual(char_list[0][0], '1')
        self.assertEqual(char_list[1][0], '2')
        self.assertEqual(char_list[2][0], '4')
        self.assertEqual(char_list[3][0], '6')

        self.assertEqual(Code.get_characters([]), 'error')
        self.assertRaises(TypeError, Code.get_characters(), ['a'])

        mocked_parameter = Mock()
        ret_val = Code.get_characters(mocked_parameter)
        self.assertFalse(mocked_parameter.called)
        self.assertEqual(ret_val, 'error')
Example #27
0
 def __init__(self, filename):
     self.Symbol_Table = Symbol_table_module.Symbol_table()
     self.code = Code.code_module()
     self.rom = 0
     self.Ram_address = 16
     self.file = filename
     self.out_file = open(self.file.replace(".asm", ".hack"), 'w')
Example #28
0
def vm(filename):
    '''implementing virtual machine'''
    pyc_lst=functions.pyc_list(filename)
#    print pyc_lst
    code_obj=Code.code(pyc_lst)
    execute(code_obj)       
    return     
Example #29
0
def main():
    input_file_path = parse_arguments()
    output_file_path = input_file_path[: input_file_path.find('.')] + '.hack'
    symbolTable = SymbolTable()
    parser = Parser(input_file_path, symbolTable)
    parser.add_labels_to_symbol_table()
    with open(output_file_path, "w") as f:
        while parser.has_more_instructions():
            parser.advance()
            code = Code(parser.instruction_type(), parser.get_instruction_fields())
            try:
                machine_instruction = code.convert_instruction_to_machine_code()
                f.write(machine_instruction)
                f.write('\n')
            except InstructionError as e:
                print(str(e) + ' ' + parser.get_instruction())
Example #30
0
 def __init__(self, code=Code([])):
     # the hidden code
     self.code = code
     # the list of all codes guessed over the course of the game
     self.guessList = []
     # the list of all clues returned over the course of the game
     self.clueList = []
Example #31
0
    def create_new(self):
        with open(Code.path_resource("IntFiles", "mate.15"), "rt", encoding="utf-8") as f:
            li = [linea.strip() for linea in f if linea.strip()]

        with self.db_config() as dbc:
            siguiente = dbc["NEXT"]
            if siguiente is None:
                siguiente = 0
            if siguiente >= len(li):
                siguiente = 0
            linea = li[siguiente]
            dbc["NEXT"] = siguiente + 1

        # 8/4K1P1/4B3/4k3/4r3/4R3/8/6Q1 w - - 0 1|Shahmat besteciliyi,2006,ABDULLAYEV Elmar|g1e1|{'e5f4': 'e1g3', 'e4e3': 'e1e3', 'e5d4': 'e1c3'}
        fen, info, move1, cdic = linea.split("|")

        m15 = Mate15()
        m15.fen = fen
        m15.pos = siguiente
        m15.info = info
        m15.move = move1
        m15.resp = eval(cdic)

        with self.db() as db:
            db[str(m15.date)] = m15.save()
            self.li_data.insert(0, m15)

        return m15
Example #32
0
def parse_asm_file(file_name):
    """ Gets the commands list using the parser and scans it twice
        first time searching for labels, second time uses the code to translate
        the A and C commands to machine code.
        Adds the machine code to a new .hack file
        Input: file_name - the .asm file needed to be translated
        Output: the translated file_name.hack file
    """
    line = 0
    symbols_table = SymbolsTable()
    hack_lines = []
    Parser.parse(file_name)
    # First pass
    for command in Parser.get_commands():
        if command.type == Command.L_COMMAND:
            symbols_table.add_label(command.content, line)
        else:
            line += 1
    # Second pass
    for command in Parser.get_commands():
        if command.type == Command.A_COMMAND:
            if not str(command.content).isnumeric():
                if not symbols_table.contains(command.content):
                    # a new variable
                    symbols_table.add_variable(command.content)
                command.content = symbols_table.get_address(command.content)
        elif command.type == Command.L_COMMAND:
            continue
        hack_lines.append(Code.code(command))

    #writes the hack file
    with open(file_name[:-ASM_SUFF_LEN] + HACK_SUFF, mode=W_FILE_MODE, encoding=DEF_ENCODING) as hack_file:
        for line in hack_lines:
            hack_file.write('%s\n' % line)
 def menuFNS(self, menu, label, xopcion):
     td = TrainingDir(Code.path_resource("Trainings"))
     td.addOtherFolder(self.configuration.personal_training_folder)
     td.addOtherFolder(self.configuration.folder_tactics())
     bmenu = menu.submenu(label, Iconos.Carpeta())
     td.reduce()  # Elimina carpetas vacias
     td.menu(bmenu, xopcion)
Example #34
0
def testC(p,exD,exC,exJ):
	d = p.dest()
	c = p.comp()
	j = p.jump()
	
	print d,c,j
	
	dbin = Code.dest(d)
	cbin = Code.comp(c)
	jbin = Code.jump(j)
	
	if dbin != exD:
		print "Dest binary does not match. Expected:",exD,"Got:",dbin
	if cbin != exC:
		print "Comp binary does not match. Expected:",exC,"Got:",cbin
	if jbin != exJ:
		print "Jump binary does not match. Expected:",exJ,"Got:",jbin
		
	return "111" + cbin + dbin + jbin
Example #35
0
def get_comp(c_command):
    """
    Returns the 'comp' mnemonic in the current C-command (28 possibilities). Should be called only when
    command_type() is C_COMMAND
    :param c_command: String
    :return: String
    """
    if '=' in c_command:
        c_command = c_command.split('=')[1]
    if ';' in c_command:
        c_command = c_command.split(';')[0]
    comp = Code.get_comp_bin(c_command)
    return comp
Example #36
0
def get_dest(c_command):
    """
    Returns the 'dest' mnemonic in the current C-command (8 possibilities). Should be called only when command_type()
    is C_COMMAND
    :param c_command: String
    :return: String
    """
    # Get the mnemonic for the destination part of the C-command
    if '=' in c_command:
        dest_str = c_command.split('=')[0]
    else:
        dest_str = ""
    dest = Code.get_dest_bin(dest_str)
    return dest
Example #37
0
def get_jump(c_command):
    """
    Returns the 'jump' mnemonic in the current C-command (8 possibilities). Should be called only when command_type()
    is C_COMMAND
    :param c_command: String
    :return: String
    """
    # Get the mnemonic for the jump part of the C-command
    if ';' in c_command:
        jump_str = c_command.split(';')[-1]
    else:
        jump_str = ""
    jump = Code.get_jump_bin(jump_str)
    return jump
Example #38
0
 def __init__(self, impl, name="__pyxutil", prefix="", requires=None,
              file=None, from_scope=None, context=None):
     # 1) We need to delay the parsing/processing, so that all modules can be
     #    imported without import loops
     # 2) The same utility code object can be used for multiple source files;
     #    while the generated node trees can be altered in the compilation of a
     #    single file.
     # Hence, delay any processing until later.
     if context is not None:
         impl = Code.sub_tempita(impl, context, file, name)
     self.impl = impl
     self.name = name
     self.file = file
     self.prefix = prefix
     self.requires = requires or []
     self.from_scope = from_scope
Example #39
0
 def getParsedEqual(self):
   if '=' in self.currentCommand:
     parsedCommandArray = self.currentCommand.split('=')
     dest = Code.dest(parsedCommandArray[0])
     cmp  = Code.comp(parsedCommandArray[1])
     jmp = Code.jump(None)
   elif ';' in self.currentCommand:
     parsedCommandArray = self.currentCommand.split(';')
     dest = Code.dest(None)
     cmp = Code.comp(parsedCommandArray[0])
     jmp = Code.jump(parsedCommandArray[1])
   return equalString % (cmp, dest, jmp)
Example #40
0
def main():
    """Drives the entire translation process."""

    """Preprocess the file"""
    pp = Preprocessor()
    pp.remove_white_spaces_comments()
    pp.write_temp_file()

    """First pass - adds labels to the symbol table."""
    parser = Parser(sys.argv[1] + '.tmp')
    symbol_table = SymbolTable()
    pc = -1
    while parser.has_more_commands():
        parser.advance()
        command_type = parser.command_type()
        if command_type == 'A_COMMAND' or command_type == 'C_COMMAND':
            pc += 1
        elif command_type == 'L_COMMAND':
            label = parser.symbol()
            symbol_table.addEntry(label, pc + 1)

    """Second pass - handles variables names and writes the *.hack file."""
    ram_address = 16
    parser = Parser(sys.argv[1] + '.tmp')
    code = Code()
    file_name = parser.get_file_name()
    hack_file = open(file_name + '.hack', 'w')

    while parser.has_more_commands():
        parser.advance()
        command_type = parser.command_type()
        if command_type == 'A_COMMAND':
            a_symbol = parser.symbol()
            if a_symbol[0] in '0123456789':
                a_symbol_binary = code.convert_to_binary(a_symbol)
                hack_file.write('0' + a_symbol_binary + '\n')
            else:
                if symbol_table.contains(a_symbol) is False:
                    symbol_table.addEntry(a_symbol, ram_address)
                    ram_address += 1
                address = symbol_table.GetAddress(a_symbol)
                address_binary = code.convert_to_binary(address)
                hack_file.write('0' + address_binary + '\n')

        elif command_type == 'C_COMMAND':
            comp = code.comp(parser.comp())
            dest = code.dest(parser.dest())
            jump = code.jump(parser.jump())
            hack_file.write('111' + comp + dest + jump + '\n')

    hack_file.close()
Example #41
0
 def jump(self):
   if self.commandType() == commandsType.C_COMMAND:
     return Code.jump(self.currentCommand)
   raise Exception("The current command: %s is not of a type %s" % (self.currentCommand, commandsType.C_COMMAND))
Example #42
0
# Second pass
print "second pass"
currentLine = 0
asm_file = Parser.initialize(asm_filename)
decOfNewSymbol = 16

while Parser.hasMoreCommands(numLines, currentLine):

    command = Parser.advance(asm_file)
    commandType = Parser.commandType(command)
    
    if commandType == 'C_COMMAND':
        print command
	destmnemonic = Parser.dest(command)
	print destmnemonic
        destbin = Code.dest(destmnemonic)
	compmnemonic = Parser.comp(command) 
	print compmnemonic
	compbin = Code.comp(compmnemonic)
        jumpmnemonic = Parser.jump(command)
        jumpbin = Code.jump(jumpmnemonic)
        output.write("111%s%s%s\n" % (compbin, destbin, jumpbin))
    elif commandType == 'A_COMMAND':
#	print 'A_command, %s' % command
        # if @number ... output binary of that, else output binary of the corresponding value in the symbolTable
        symbol = Parser.symbol(command)
#	print 'Symbol %r' % symbol
#	print 'R0\r' == symbol
        if re.match('^([0-9]+)', symbol) != None:
#	    print 'found a number'
            binStr = format(int(symbol), 'b')
Example #43
0
p.advance()
print testC(p,"010","1000111","010")

print "A=M;JLT"
p.advance()
print testC(p,"100","1110000","100")

print "D;JGE"
p.advance()
print testC(p,"000","0001100","011")

print "0;JMP"
p.advance()
print testC(p,"000","0101010","111")

print "done testing C====="

print "=====Testing decimalConstantToBinaryString"

binary = Code.decimalConstantToBinaryString("33")

if binary != "000000000100001":
	print "Bad conversion. Got:",binary,"Expected: 000000000100001"

binary = Code.decimalConstantToBinaryString("267")

if binary != "000000100001011":
	print "Bad conversion. Got:",binary,"Expected: 000000100001011"

print "done testing decimalConstantToBinaryString====="
Example #44
0
        symbolTable.addEntry(parser.symbol(), romAddress)
    else:
        romAddress += 1

# This opens the file that will be written to.
hackFilename = asmFilename[:-3] + "hack"
hackFile = open(hackFilename, "w")

# This writes the translated code to the hack file.
parser.restart()
ramAddress = 16
while parser.hasMoreCommands():
    parser.advance()
    commandType = parser.commandType()
    if commandType == "C_COMMAND":
        hackFile.write("111" + Code.comp(parser.comp()) + Code.dest(parser.dest()) + Code.jump(parser.jump()) + "\n")
    elif commandType == "A_COMMAND":
        symbol = parser.symbol()
        try:
            address = int(symbol)
        except:
            if symbolTable.contains(symbol):
                address = symbolTable.getAddress(symbol)
            else:
                address = ramAddress
                # This adds an A command symbol to the symbol table if it's not already in it.
                symbolTable.addEntry(symbol, address)
                ramAddress += 1

        hackFile.write(bin(address)[2:].zfill(16) + "\n")
Example #45
0
def connect_instance_port_names_to_module_port_names(
        parent_module, gbl, list_of_named_port_connections, mod_inst 
    ) :
    for (port_i, expr) in list_of_named_port_connections:
        print port_i,"=>",expr

    for (port_i, expr) in list_of_named_port_connections:

        # first, check the named ports exist in the new instance.
        port_name = port_i[1]  # port_i[0] = 'port_identifier'

        sig = mod_inst.get_named_signal_from_scope(port_name)
        if not sig: return False

        # fixme - check port directions are compatible
        assert sig.is_port

        if sig.port_dir == 'in':  # create code for: assign port = <expr>
            print "Input Port is same as: assign %s = %s" % (sig.hier_name, str(expr[1:]) )

            expr_code, sigs = Code.code_eval_expression(parent_module, gbl, expr[1:])
            #print "expr_code=",expr_code,"   sigs in expr=",
            #for s in sigs: print s.hier_name,
            #print 

            # make the port name look like a net_identifier lvalue
            wire    = port_i[:]
            wire[0] = 'net_identifier'
            lvalue  = [ 'net_lvalue', wire ]
            
            # create code to assign the expr to the lvalue (port)
            code = Code.code_assign_expr_code_to_lvalue( mod_inst, gbl, lvalue, expr_code)

            print "Code=",code
            
            # Add event for initial assignment.
            simcode = gbl.create_and_add_code_to_events( code, 0, 'active_list' )

            # Now we need to add the lvalue to the dependency list of all
            # signals in the expression (in sigs). In practice we need to recompute
            # the expression if any of the signals change. But we already have the
            # simcode to do that - we just need to invoke it when needed.

            if sigs: add_dependent_simcode_to_signals( simcode, sigs )

        else: # sig port is output
            print "Output Port is same as:assign %s = %s" % (str(expr[1:]), sig.hier_name )

            # Create code to evaluate (look up) the value of the child module's signal.
            # First, make signal look like an expression.
            sig_expr = [ 'net_identifier', sig.local_name ]

            expr_code, sigs = Code.code_eval_expression(mod_inst, gbl, sig_expr)

            # Make the expr[1] look like an lvalue
            lvalue  = [ 'net_lvalue', expr[1:] ]
            
            print "lvalue is", str(lvalue), "\ncode to eval sig is",expr_code

            # create code to assign the expr to the lvalue (port)
            code = Code.code_assign_expr_code_to_lvalue( parent_module, gbl, lvalue, expr_code)

            print "Code=",code

            # Add event for initial assignment.
            simcode = gbl.create_and_add_code_to_events( code, 0, 'active_list' )

            # Now we need to invoke code whenever the child signal value changes.
            assert sigs # Must be exactly one.
            add_dependent_simcode_to_signals( simcode, sigs )
           
    return True
Example #46
0
    ctype = Parser.commandType(line)
    #compare command type
    if ctype is 'A_COMMAND':
        AS = Parser.symbol(line)
        AS1 = bin(int(AS))[2:]
        AString = AS1.zfill(15)
        wfile.write('0'+AString+'\n') 

    # L has no meaning
    elif ctype is 'L_COMMAND':
        LString = Parser.symbol(line)
        wfile.write('0'+LString+'\n')

    if ctype is 'C_COMMAND':
        DestString = Code.dest(line)
        CompString = Code.comp(line)
        JumpString = Code.jump(line)
        wfile.write('111'+CompString+DestString+JumpString+'\n')
    
    line = Parser.advance(rfile, line)
    flag = Parser.hasMoreCommands(line)

rfile.close()
wfile.close()
        




Example #47
0
        # Sets whether it's using B in the comp
        comp = parser.comp()
        if comp.find('B') == -1:
            commandStart += '1'
        else:
            commandStart += '0'
            comp = comp.replace('B', 'D')
        
        # Sets whether it's using B in the dest
        dest = parser.dest()
        if dest == None or dest.find('B') == -1:
            commandStart += '1'
        else:
            commandStart += '0'
        
        hackFile.write(commandStart + Code.comp(comp) + Code.dest(dest) + Code.jump(parser.jump()) + '\n')
    elif commandType == 'A_COMMAND':
        symbol = parser.symbol()
        try:
            address = int(symbol)
        except:
            if symbolTable.contains(symbol):
                address = symbolTable.getAddress(symbol)
            else:
                address = ramAddress
                # This adds an A command symbol to the symbol table if it's not already in it.
                symbolTable.addEntry(symbol, address)
                ramAddress += 1
        
        hackFile.write(bin(address)[2:].zfill(16) + '\n')
Example #48
0
 def run(self):
     if type(self.code) == Code.func_type:
         self.code()
     else:
         Code.execute(self.code, verbose=False)
     return
Example #49
0
	else:
		i += 1

#pass 1
parser.reset()

while parser.hasMoreCommands():
	parser.advance()
	
	type = parser.commandType()
	
	if type == "A":
		sym = parser.symbol()
		#sym is a constant
		if ord(sym[0]) >= ord("0") and ord(sym[0]) <= ord("9"):
			outFile.write("0" + Code.decimalConstantToBinaryString(sym) + "\n")
		#sym is in table
		elif symbolTable.contains(sym):
			outFile.write("0" + symbolTable.getAddress(sym) + "\n")
		#sym is a new var
		else:
			symbolTable.addVariable(sym)
			outFile.write("0" + symbolTable.getAddress(sym) + "\n")
		
	elif type == "C":
		d = Code.dest(parser.dest())
		c = Code.comp(parser.comp())
		j = Code.jump(parser.jump())
		outFile.write("111" + c + d + j + "\n")

outFile.close()
Example #50
0
 def dest(self):
   if self.commandType() == commandsType.C_COMMAND:
     return Code.dest(self.currentCommand)
   raise Exception("The current command: %s does not carry a dest" % self.currentCommand)
Example #51
0
 def create_and_add_code_to_events(self, code, c_time, list_type):
     ''' Convenient helper function '''
     simcode = Code.code_create_uniq_SimCode(self, code)
     self.add_simcode_to_events(simcode, c_time, list_type)
     return simcode