時間:2023-06-27 07:03:02 | 來源:網站運營
時間:2023-06-27 07:03:02 來源:網站運營
用Python實現一個虛擬機需要多久?10分鐘?。簛碓矗篜ython高效編程# Python高效編程class Machine: def __init__(self, code): self.code = code self.stack = list() self.addr = 0
原理其實很簡單,我們通過不斷獲取當前指令地址,從指令列表中獲取指令和數據,如果是數字或者字符串,就壓入棧中;如果是指令,就執(zhí)行相應函數。def push(self, value): self.stack.append(value)def pop(self): return self.stack.pop()@propertydef top(self): return self.stack[-1]
我們通過 dispatch 方法,來判斷當前從指令列表中取得的片段是指令還是數據:def dispatch(self, opcode): dispatch_map = { "%": self.mod, "*": self.mul, "+": self.plus, "-": self.minus, "/": self.div, "==": self.eq, "cast_int": self.cast_int, "cast_str": self.cast_str, "drop": self.drop, "dup": self.dup, "exit": self.exit, "if": self.if_stmt, "jmp": self.jmp, "over": self.over, "print": self.print, "println": self.println, "read": self.read, "stack": self.dump_stack, "swap": self.swap, } if opcode in dispatch_map: dispatch_map[opcode]() elif isinstance(opcode, int): self.push(opcode) elif isinstance(opcode, str)/ and opcode[0] == opcode[-1] == '"': self.push(opcode[1:-1])
dispatch_map 就對應我們在 Machine 類中實現的方法。def plus(self): v2 = self.pop() v1 = self.pop() self.push(v1 + v2)def jmp(self): addr = self.pop() if 0 <= addr < len(self.code): self.addr = addr else: raise RuntimeError("addr must be integer")
其余方法也很簡單,大家可以直接查看源代碼。def run(self): while self.addr < len(self.code): opcode = self.code[self.addr] self.addr += 1 self.dispatch(opcode)
我們創(chuàng)建 Machine 類,并執(zhí)行 run 函數,注意字符串要用引號括起來。>>> from vm import Machine>>> Machine([521, 1314,"+", 6, "*","println"]).run()11010
我們還可以給虛擬機加一個交互式界面:def repl(prompt="VM>> "): welcome() while True: try: text = read(prompt) code = list(tokenize(text)) code = constants_fold(code) Machine(code).run() except (RuntimeError, IndexError): stdout.write("1表達式不合法/n") except KeyboardInterrupt: stdout.write("請使用exit退出程序/n")
在讀取用戶輸入字符串之后,對字符串處理:def parse_word(word): try: return int(word) except ValueError: try: return float(word) except ValueError: return worddef tokenize(text): for word in text.split(): yield parse_word(word)
最后放張效果圖:關鍵詞:實現,虛擬