def main(): if len(sys.argv) == 2: file = open(sys.argv[1], 'r') source = file.read() lexer = Lexer(source) parser = Parser(lexer) interpreter = Interpreter(parser) result = interpreter.interpret() print(result) else: print( "SHELL MODE: still you need to type the whole program in a single line!" ) while True: try: text = input('>>> ') except EOFError: break if not text: continue lexer = Lexer(text) parser = Parser(lexer) interpreter = Interpreter(parser) result = interpreter.interpret() print(result)
def test_feedback_opcode(self): f = FeedbackMachine.FeedbackOutputFactory() i2 = Interpreter.Interpreter([],{},[]) i = Interpreter.Interpreter([4,3,99,7],{4:f.construct,99:Halt}) f.set_outerpreter(i2) i.run() outputs = i2._Interpreter__inputs self.assertEqual(outputs, [7])
def test_feedback_and_fork(self): f = FeedbackMachine.FeedbackOutputFactory(FeedbackMachine.FeedbackAndFork) i = Interpreter.Interpreter([4,3,99,7],{4:f.construct,99:Halt}) i2 = Interpreter.Interpreter([]) f.set_outerpreter(i2) i.run() outputs = i2._Interpreter__inputs self.assertEqual(outputs, [7]) self.assertEqual(i.pop_output(), 7)
def test_fourth_code(self): tape = [3, 3, 1107, -1, 8, 3, 4, 3, 99] i = Interpreter.Interpreter(tape, self.ops, [4]) i.run() self.assertEqual(i.pop_output(), 1) tape = [3, 3, 1107, -1, 8, 3, 4, 3, 99] i = Interpreter.Interpreter(tape, self.ops, [9]) i.run() self.assertEqual(i.pop_output(), 0)
def test_second_code(self): tape = [3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8] i = Interpreter.Interpreter(tape, self.ops, [4]) i.run() self.assertEqual(i.pop_output(), 1) tape = [3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8] i = Interpreter.Interpreter(tape, self.ops, [8]) i.run() self.assertEqual(i.pop_output(), 0)
def test_sixth_code(self): tape = [3, 3, 1105, -1, 9, 1101, 0, 0, 12, 4, 12, 99, 1] i = Interpreter.Interpreter(tape, self.ops, [4]) i.run() self.assertEqual(i.pop_output(), 1) tape = [3, 3, 1105, -1, 9, 1101, 0, 0, 12, 4, 12, 99, 1] i = Interpreter.Interpreter(tape, self.ops, [0]) i.run() self.assertEqual(i.pop_output(), 0)
def test_fifth_code(self): tape = [3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, -1, 0, 1, 9] i = Interpreter.Interpreter(tape, self.ops, [4]) i.run() self.assertEqual(i.pop_output(), 1) tape = [3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, -1, 0, 1, 9] i = Interpreter.Interpreter(tape, self.ops, [0]) i.run() self.assertEqual(i.pop_output(), 0)
def loadInterpreter(self,configPaths, projectName="", subtask_name=""): import sys, os sys.path.append(os.path.abspath(configPaths)) sys.path.append(os.path.abspath(configPaths)+'/Assistant/') import Interpreter from importlib import reload reload(Interpreter) # use 1, 2 to use different config file #self.config = configuration.initConfig(2) #return configuration.initConfig(1) if projectName == "" or subtask_name == "": interpreter = Interpreter.Interpreter() return interpreter interpreter = Interpreter.Interpreter(projectName+'.'+subtask_name) return interpreter#.ParsingConfig()
def test1(): '''test loop \"\" is used to post evaluation of a expression''' value = "International Bussiness Machine" expression = '''substr(value,indexOf(value,',','UWRD',-1),indexOf(value,'LWRD','END',-1))+substr(value,indexOf(value,'LWRD','SYB',1),-6)+substr(value,indexOf(value,'START','NUM',1),indexOf(value,'LWRD','SYB',-1))''' loopexp = "foreach(value.split(),\"substr(value,indexOf(value,'START','UWRD'),indexOf(value,'UWRD','LWRD'))\")" e = Interpreter(loopexp) print e.execute(value)
def test0(): '''test concatenation''' s = "13 Jan 2008 00:00:00 +0000" scripts = '''substr(value,indexOf(value,'START','NUM',1),12)+loop(value,"substr(value,-11,18)")+substr(value,12,-12) ''' a = Interpreter(scripts) print a.execute(s)
def calc(expression): source = InputStream(expression) lexer = Lexer(source) parser = Parser(lexer) tree = parser.parse() function_handler = FunctionHandler() interpreter = Interpreter(function_handler) result = interpreter.visit(tree) if result.type == 'image': response = make_response(base64.b64encode(result.image)) response.headers.set('Content-Type', 'image/jpeg') return response elif result.type == 'float' or result.type == 'integer' or result.type == 'text': if result.type == 'float': response = make_response('{:.5f}'.format(result.value)) elif result.type == 'integer': response = make_response(str(result.value)) elif result.type == 'text': response = make_response(result.text) response.headers.set('Content-Type', 'text/plain') return response
def test5(): '''test loop''' stript = '''substr(value,indexOf(value,'NUM','\.',1),indexOf(value,'\.','22',1))+'edu'+'/'+'images'+'/'+substr(value,indexOf(value,'ANY','NUM',-1),-12)+'/'+substr(value,indexOf(value,'START','NUM',1),-12)+substr(value,-9,-8)+substr(value,5,16) ''' value = "1978.43.8_1a.jpg" e = Interpreter(stript) print e.execute(value)
def runCode(self): if self.windowTitle() == self.settingWindowTitle: # print('run settings') self.settings = self.editor.toPlainText() self.setSettings() return if self.txtClearRun: self.text_res.setText('') else: self.text_res.append('') print('Run Code >>> ') interpreter = Interpreter() run_code = self.editor.toPlainText() # print(run_code) # self.print_debug_info('R', '<font color = "red"><b> RunCode </b></font> <br> <b>Code:</b> ' + run_code) run_code = '( ' + run_code + ' *RETURN* )' run_code = parse(pretrans(run_code)) for code in run_code: self.print_debug_info( 'R', '<font color = "red"><b> RunCode </b></font> <br> <b>Code:</b> ' + str(code)) run_res = interpreter.getResult(code) self.text_res.append(str(run_res)) del interpreter print()
def __init__(self, input, out_file): # input是输入字符串,outfile是输出的文件 self.lex = word_anay.word_anay(input) # 词法分析器 self.line = 1 # 初始行数 self.nextsym() # 符号 self.table = SymbolTable.SymbolTable() # 符号表 self.interp = Interpreter.Interpreter(out_file) self.myErr = Err.Err(out_file) # 错误处理 self.declbegsys = set() self.declbegsys.add('CONST') self.declbegsys.add('VAR') self.declbegsys.add('PROCEDURE') # 表示申明开始的符号集合:声明的FIRST集合 self.statbegsys = set() self.statbegsys.add('BEGIN') self.statbegsys.add('CALL') self.statbegsys.add('IF') self.statbegsys.add('WHILE') self.statbegsys.add('REPEAT') # 表示语句开始的符号集合:语句的FIRST集合 self.facbegsys = set() # 表示因子开始的符号集合:因子的FIRST集合 self.facbegsys.add('ID') self.facbegsys.add('NUMBER') self.facbegsys.add('LPAREN') # 当前作用域的堆栈帧大小,或者说数据大小(datasize) # 计算每个变量在运行栈中相对本过程基地址的偏移量 # 放在symbolTable中的address域 # 生成目标代码时再放在code中的a域 self.dx = 0
def run(self, source, locals_="", globals_=""): # if len(python_varibales_tuple) != 0: # source = run_micropass(source, python_varibales_tuple) # scanning obj = Scanner.Scanner(source) tokens = obj.scan_tokens() # for token in tokens: # print token # Semi parsing: representing code # expression = Binary( # Unary(Token(TokenType.MINUS, "-", None, 1), Literal(123)), # Token(TokenType.STAR, "*", None, 1), # Grouping(Literal(45.67))) # print(AstPrinter.AstPrinter().print_ast(expression)) # Parsing parser = Parser.Parser(self, tokens) statements = parser.parse() # # Stop if there was a syntax error. if self.had_error: return # macros # macropass = MacroPass.MacroPass(dir()) #Todo: delete # macropass.macro_pass(statements) interpreter = Interpreter.Interpreter(locals_, globals_) interpreter.interpret(statements)
def main(): text = """\ FUNC TEST(n,x,y,){ FOR(i=1, i<=n, i=i+1,){ FOR(j=1, j<=n, j=j+1,){ PRINT(i,",",j," ",); } PRINT("\n",); } } FUNC recur(n,){ IF(n==1){ RETURN 1; }RETURN n+CALL recur(n-1,); } FUNC MAIN(){CALL TEST(4,2,3,); n=4;a=5; FOR(i=1,i<=n,i=i+1,){PRINT(i,": ",CALL recur(i,),"\n",);} PRINT(a,"\n;",);} """ Beautifier = Beautify(text) res = Beautifier.solve() print(res) lexer = Lexer(text) parser = Parser(lexer) interpreter = Interpreter(parser) interpreter.interpret()
def test_input_opcode(self): inputs = [] tape = [3, 3, 99, 0] i = Interpreter.Interpreter(tape,{3:FeedbackMachine.HaltingInput,99:Halt},inputs) i.run() self.assertEqual(tape, [3, 3, 99, 0]) inputs.append(7) i.run() self.assertEqual(tape, [3, 3, 99, 7])
def test_first_code(self): import copy tape = [ 109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99 ] i = Interpreter.Interpreter(copy.copy(tape), self.ops) i.run() self.assertEqual(i._Interpreter__outputs, tape)
def test4(): '''test switch function''' condi1 = "len(value) < 10" condi2 = "len(value) < 10" loopexp1 = "foreach(value.split(),\"substr(value,indexOf(value,'START','UWRD'),indexOf(value,'UWRD','LWRD'))\")" loopexp2 = '''foreach(foreach(value.split(),\"substr(value,indexOf(value,'START','UWRD'),indexOf(value,'UWRD','LWRD'))\"),\"value+'see'\")''' tuplist = "[(" + condi1 + "," + loopexp1 + "),(" + condi2 + "," + loopexp2 + ")]" sw = "switch(" + tuplist + ")" value = "International Bussiness Machine" e = Interpreter(sw) print e.execute(value)
def main(): file_object = open('source_code.txt') try: text = file_object.read() lexer = Lexer(text) parser = Parser(lexer) interpreter = Interpreter(parser) interpreter.interpret() print(interpreter.GLOBAL_SCOPE) finally: file_object.close()
def run(fn, text): lexer = lex(fn, text) tokens, error = lexer.make_tokens() if error: return None, error p = parse(tokens) ast = p.parse() if ast.error: return None, ast.error interpreter = Interpreter() context = Context('<program>') result = interpreter.visit(ast.node, context) return result.value, result.error
def test_seventh_code(self): tape = [ 3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31, 1106, 0, 36, 98, 0, 0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999, 1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99 ] i = Interpreter.Interpreter(tape, self.ops, [4]) i.run() self.assertEqual(i.pop_output(), 999) tape = [ 3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31, 1106, 0, 36, 98, 0, 0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999, 1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99 ] i = Interpreter.Interpreter(tape, self.ops, [8]) i.run() self.assertEqual(i.pop_output(), 1000) i = Interpreter.Interpreter(tape, self.ops, [13]) i.run() self.assertEqual(i.pop_output(), 1001)
def main(): while True: # try: # try: # text = raw_input('spi> ') # except NameError: # Python3 # text = input('spi> ') # except EOFError: # break # if not text: # continue text = text = """\ FUNC TEST(){ n=10; x=100000000; FOR(i=1;i<=n;i=i+1;){ FOR(j=1; j<=n; j=j+1;){ PRINT(i,",",j," ",) } PRINT("\n",) x=x-1; } x=x-10; y=10; } FUNC MAIN(){ CALL TEST(); n=8; x=4; FOR(i=1;i<=n;i=i+1;){ FOR(j=1; j<=n; j=j+1;){ PRINT(i,",",j," ",) a=10; b=10; } PRINT("\n",) } PRINT(x,"\n",) } """ lexer = Lexer(text) parser = Parser(lexer) interpreter = Interpreter(parser) result = interpreter.interpret() print(interpreter.GLOBAL_SCOPE.get('hello')) break
def main(): if len(sys.argv) == 2: file = open(sys.argv[1], 'r') source = file.read() try: lexer = Lexer(source) parser = Parser(lexer) interpreter = Interpreter(parser) result = interpreter.interpret() print(result) except Exception as e: print(e) else: print("Usage: ki.py kotlinFilename") sys.exit()
def main(): while True: try: text = input('Input> ') except EOFError: break if not text: continue lexer = Lexar.Lexer(text) parser = Parser.Parser(lexer) interpreter = Interpreter.Interpreter(parser) result = interpreter.interpret() print("\nOutPut: ".join("{} = {}".format(a, b) for a, b in interpreter.GLOBAL_SCOPE.items()))
def main(): while True: # try: # try: # text = raw_input('spi> ') # except NameError: # Python3 # text = input('spi> ') # except EOFError: # break # if not text: # continue text = text = """\ { number = 2523*10; x = 11; IF(x<=11){ hello=2; hello=hello-2; a=0; IF(a<1){ hello=108; }ELSEIF(a<2){ hello=109; }ELSEIF(a<3){ hello=110; }ELSEIF(a<4){ hello=111; }ELSEIF(a<5){ hello=112; }ELSE{ hello=113; } FOR(i=2;i<=10;i=i+2;){ PRINT("Hello World!",) } } } """ lexer = Lexer(text) parser = Parser(lexer) interpreter = Interpreter(parser) result = interpreter.interpret() print(result) print(interpreter.GLOBAL_SCOPE.get('hello')) break
def run(filename, output=True): file = open(filename, "r") prsr = parser.parser text = file.read() ast = prsr.parse(text, lexer=scanner.lexer) # if ast is not None: # ast.printTree() # print() typeChecker = TypeChecker() checkRes = typeChecker.visit(ast) if output: print(checkRes) if isinstance(checkRes, Success): return ast.accept(Interpreter.Interpreter(output))
def main(): while True: # try: # try: # text = raw_input('spi> ') # except NameError: # Python3 # text = input('spi> ') # except EOFError: # break # if not text: # continue text = text = """\ FUNC TEST(n,x,y,){ FOR(i=1, i<=n, i=i+1,){ FOR(j=1, j<=n, j=j+1,){ PRINT(i,",",j," ",); } PRINT("\n",); } } FUNC recur(n,){ IF(n==1){RETURN 1;} RETURN n+CALL recur(n-1,); } FUNC MAIN(){ b=6; a=CALL recur(4,); FOR(i=1,i<=b,i=i+1,){ PRINT(i,": ",CALL recur(i,),"\n",); } PRINT(a,"\n;",); CALL TEST(4,5,5,); } """ Beautifier = Beautify(text) print(str(Beautifier.solve())) lexer = Lexer(text) parser = Parser(lexer) interpreter = Interpreter(parser) interpreter.interpret() break
def run(fn, text): # Generate tokens lexer = Lexer(fn, text) tokens, error = lexer.make_tokens() if error: return None, error # Generate AST parser = Parser(tokens) ast = parser.parse() if ast.error: return None, ast.error # Run program interpreter = Interpreter() context = Context('<program>') context.symbol_table = global_symbol_table result = interpreter.visit(ast.node, context) return result.value, result.error
def run(fn: str, text: str) -> (float, Error): # generate tokens from source with lexical analysis lexer = Lexer(fn, text) tokens, error = lexer.make_tokens() if error: return None, error if len(tokens) <= 1: return None, None # generate an abstract syntax tree by parsing the text, also known as syntax analysis parser = Parser(tokens) ast = parser.parse() if ast.error: return None, ast.error # interpret the ast interpreter = Interpreter() context = Context("<Program>") context.symbol_table = global_symbol_table result = interpreter.visit(ast.node, context) return result.value, result.error