def check(code, inbyte, outbyte): inp = 0 def infunc(): nonlocal inp if inp < len(inbyte): inp += 1 return bytes([inbyte[inp - 1]]) else: return b'' res = b'' def outfunc(s): nonlocal res res += s run(code, infunc, outfunc, lambda _: True) if res == outbyte: return True else: print('check failure') print('code:', code) print('expect:', outbyte) print('result:', res) assert False
def _test(self): actual = StringIO() try: with redirect_stdout(actual): run(source) except Exception as e: self.fail('Exception: {}'.format(e)) self.assertEqual(expected, actual.getvalue())
def test_some_programs_from_the_tetxbook(): assert run('((2 mul) exec)', 7) == 14 assert run('((0 swap sub) 7 swap exec)') == -7 assert run('(2 3 sel)', 1) == 2 assert run('(2 3 sel)', 0) == 3 assert run('(2 3 sel)', 17) == 2 assert run('((2 mul) 3 4 sel)') == 'INT_EXPECTED' assert run('(lt (add) (mul) sel exec)', 3, 4, 5, 6) == 30 assert run('(lt (add) (mul) sel exec)', 4, 3, 5, 6) == 11 assert run('((7 swap exec) (0 swap sub) swap exec)') == -7 assert run('((mul sub) (1 nget mul) 4 nget swap exec swap exec)', -10, 2) == 42
def main(argv): defs = [] for filename in argv[1:]: with open(filename) as f: text = f.read() try: defs.extend(parser.parse(text)) except parser.Unparsable as e: syntax_error(e, filename) return 1 interpreter.run(defs) return 0
def test_arithmetic_commands(): assert run('(postfix 1 4 sub)', [3]) == -1 assert run('(postfix 1 4 add)', [3]) == 7 assert run('(postfix 1 4 mul)', [3]) == 12 assert run('(postfix 1 4 div)', [8]) == 2 assert run('(postfix 1 4 div)', [7]) == 1 # integer division assert run('(postfix 1 3 rem)', [17]) == 2 assert run('(postfix 1 0 div)', [8]) == 'error' assert run('(postfix 0 4 sub)', []) == 'error' assert run('(postfix 2 (add) (add) sub)', []) == 'error'
def test_interpreter(): interpreter.run("test_fixtures/sample_program.arbiter") with open("test_fixtures/credit_data.csv") as datafile: datafile.readline() # skip header reader = csv.reader(datafile) datapoint = next(reader)[:-1] # skip label with open("test_fixtures/credit_score.model", "rb") as modelfile: model = pickle.load(modelfile) print(model) assert (model.predict([datapoint]) in [1, 2]) os.remove("test_fixtures/credit_score.model")
def test_exercise_1_1(): assert run('(postfix 0 10 (swap 2 mul sub) 1 swap exec)', []) == -19 assert run('(postfix 0 (5 (2 mul) exec) 3 swap)', []) == 'error' assert run('(postfix 0 (() exec) exec)', []) == 'error' assert run('(postfix 0 2 3 1 add mul sel)', []) == 'error' assert run('(postfix 0 2 3 1 add mul sel exec)', []) == 'error' assert run('(postfix 0 0 (2 3 add) 4 sel exec)', []) == 'error' assert run('(postfix 0 1 (2 3 add) 4 sel exec)', []) == 5 assert run('(postfix 0 (5 6 lt) (2 3 add) 4 sel exec)', []) == 'error' assert run( '(postfix 0 (swap exec swap exec) (1 sub) swap (2 mul) swap 3 swap exec)', []) == 5
def poll(interpreter): """Show user interface Wait for user input If input starts with PREFIX, execute it as a command Else execute input as brainfuck code Start again Parameter: interpreter (Interpreter) : brainfuck interpreter """ while True: usr_in = input(DEFAULT_OUTPUT) # input is a command if usr_in.startswith(DEFAULT_PREFIX): try: CLI.__run_cmd(usr_in[1:], interpreter) except KeyboardInterrupt: print(COLOR_FAIL + '\nCommand canceled' + COLOR_END) # input is BF code else: try: out = interpreter.run(code=usr_in) if out: print(COLOR_INFO + out + COLOR_END) except ExecutionException as e: print(COLOR_FAIL + 'Error: ' + e.msg + COLOR_END) except TypeError as e1: print(COLOR_FAIL + 'Error: expected only one char' + COLOR_END) finally: interpreter.clear_tokens()
def post(self): code = self.get_argument('code') try: result = run(code) except: result = "Ошибка..." self.render('index.html', result=result, code=code)
def run_console(i, glob): import lexer import analyze import_readline() i.consolelevel += 1 try: t = "" while True: t = raw_input("oranj> ") + "\n" while not lexer.isdone(t): t += raw_input(" > ") + "\n" try: r = intp.run(t, i) except intp.PyDropI: raise except intp.DropI: raise EOFError except parser.ParseError: pass except Exception, e: libintp.print_exception(e, i) else: if hasattr(r, "isnil") and not r.isnil(): print repr(r) except EOFError, e: print
def fparse(filename: str) -> None: eng = engine.InferenceEngine() with open(filename) as f: for i, line in enumerate(f, 1): try: if line.strip() == "reset": eng = engine.InferenceEngine() continue if line.strip().startswith("display "): print(line.strip()[8:]) continue if not line.strip(): continue processed_input = lexer.lex(line) if not processed_input: continue if processed_input[0] in ("=", "?"): process( eng, interp.run( parse.AST( processed_input[0], parse.ident_serie(processed_input[1:]), ) ), i, ) else: stmt = parse.ifop(processed_input) if stmt.name == "<=>": process( eng, interp.run(parse.AST("=>", stmt.operands)) + interp.run(parse.AST("=>", stmt.operands[::-1])), ) else: process(eng, interp.run(stmt)) except RuntimeError: print( "Line {}: Maximum recursion depth reached, " "please make the expression simpler.".format(i + 1) ) except Exception as e: print(e)
def test_parser_errors_are_detected(): assert run('') == 'PREMATURE_END_OF_PROGRAM' assert run('(mul') == 'PREMATURE_END_OF_PROGRAM' assert run('(mulz)') == 'LEXICAL_ERROR' assert run('(mul4)') == 'LEXICAL_ERROR' assert run('(mul,4)') == 'LEXICAL_ERROR' assert run(')') == 'UNEXPECTED_RIGHT_PAREN' assert run('(3 4 add ) sub)') == 'EXTRA_PROGRAM_TEXT'
def test_arithmetic_commands(): assert run('(4 sub)', 3) == -1 assert run('(4 add 5 mul 6 sub 7 div)', 3) == 4 assert run('(add mul sub swap div)', 7, 6, 5, 4, 3) == -21 assert run('(4000 swap pop add)', 300, 20, 1) == 4020 assert run('(3 div)', 17) == 5 assert run('(3 rem)', 17) == 2 assert run('(4 mul add)', 3) == 'STACK_SIZE_UNDER_2'
def task2_2(): machine = { 0: { 'f': (0, 'f', 1), 'h': (0, 'h', 1), ' ': ('y', ' ', 0), 'p': (1, 'p', 1) }, 1: { 'p': (1, 'p', 1), 'f': (0, 'f', 1), ' ': ('y', ' ', 0), 'h': (2, 'h', -1) }, 2: { 'p': (3, 'f', 1) }, 3: { 'h': (4, ' ', 1) }, 4: { 'p': (4, 'p', 1), 'h': (4, 'h', 1), 'f': (4, 'f', 1), ' ': (5, ' ', -1) }, 5: { ' ': ('y', ' ', 0), 'h': (6, ' ', -1), 'p': (7, ' ', -1), 'f': (8, ' ', -1) }, 6: { 'h': (6, 'h', -1), 'p': (7, 'h', -1), 'f': (8, 'h', -1), ' ': ('y', 'h', 0) }, 7: { 'h': (6, 'p', -1), 'p': (7, 'p', -1), 'f': (8, 'p', -1), ' ': ('y', 'p', 0) }, 8: { 'h': (6, 'f', -1), 'p': (7, 'f', -1), 'f': (8, 'f', -1), ' ': ('y', 'f', 0) } } print('Task 2.2') word = input('Enter an input word: ').strip().lower() result, answer = run(machine, word, log=True) print('Result:', result)
def main(): # while True: # s = input() s = "12 / 6 - 2 * 4" ast = parser.parse(s, debug=False) print("AST:", ast) interpreter = Interpreter(ast) result = interpreter.run() print(result)
def brute(op): if op == 'nop': ops = nops = [i for (i, (op, _)) in enumerate(p_input) if op == 'nop'] else: ops = jmps = [i for (i, (op, _)) in enumerate(p_input) if op == 'jmp'] for o in ops: p_copy = p_input.copy() p_copy[o] = ('jmp' if op == 'nop' else 'nop', p_copy[o][1]) acc, visited, pc = run(p_copy, set(), 0) if pc == len(p_copy): return acc
def test_trivial_pushes_and_pops(): assert run('(1 2 3)') == 3 assert run('(1 2 3 pop)') == 2 assert run('(1 2 3 pop pop)') == 1 assert run('(1 pop 2 3 pop)') == 2 assert run('(1 pop)') == 'NO_RESULT' assert run('(pop)', 5) == 'NO_RESULT'
def stdin_parse() -> None: eng = engine.InferenceEngine() while True: user_input = input("#=> ").strip() try: if user_input == "quit": print("Goodbye !") break if user_input == "reset": eng = engine.InferenceEngine() continue processed_input = lexer.lex(user_input) if not processed_input: continue if processed_input[0] in ("=", "?"): process( eng, interp.run( parse.AST( processed_input[0], parse.ident_serie(processed_input[1:]) ) ), ) else: stmt = parse.ifop(processed_input) if stmt.name == "<=>": process( eng, interp.run(parse.AST("=>", stmt.operands)) + interp.run(parse.AST("=>", stmt.operands[::-1])), ) else: process(eng, interp.run(stmt)) except RuntimeError: print( "Maximum recursion depth reached, " "please make the expression simpler." ) except Exception as e: print(e)
def on_data(self, data): data = json.loads(data) d, user = data["text"], data["user"]["screen_name"] d = d.replace("#gbc", "") d = hp.unescape(d) print d try: context = run(d) with NamedTemporaryFile(suffix=".png") as tf: context.canvas.save(tf.name) API(self.auth).update_status_with_media( tf.name, status="@%s Here ya go!" % user) except Exception as e: print e return True
def task1_23(): machine = { 0: { 'a': (1, ' ', 1), 'b': (5, ' ', 1), ' ': ('y', 'a', 0) }, 1: { 'a': (1, 'a', 1), 'b': (1, 'b', 1), ' ': (2, ' ', -1) }, 2: { 'a': (4, ' ', -1), 'b': (3, ' ', -1), ' ': ('y', 'a', 0) }, 3: { 'a': (3, ' ', -1), 'b': (3, ' ', -1), ' ': ('n', ' ', 0) }, 4: { 'a': (4, 'a', -1), 'b': (4, 'b', -1), ' ': (0, ' ', 1) }, 5: { 'a': (5, 'a', 1), 'b': (5, 'b', 1), ' ': (6, ' ', -1) }, 6: { 'a': (3, ' ', -1), 'b': (4, ' ', -1), ' ': ('y', 'a', 0) } } print('Task 1.23') word = input('Enter an input word: ').strip().lower() result, answer = run(machine, word, log=True) if answer: print('The word is a palindrom, result -', result) else: print('The word is not a palindrom, result -', result)
def main(glob): intp.Interpreter.shell_hook = lambda x: run_console(x, glob) intp.Interpreter.debug_hook = debug_hook base_i = intp.Interpreter() kwargs = parse_args() if len(kwargs["child"]) and "test" not in kwargs: run_file(base_i, kwargs["child"], glob) elif "stdin" in kwargs: wrap(lambda: intp.run(sys.stdin.read(), base_i), base_i, glob) elif "test" in kwargs: import_readline() if kwargs["test"] == "a": import analyze analyze._test(kwargs["child"][0] if len(kwargs["child"]) > 0 else None) elif kwargs["test"] == "p": import parser parser._test(kwargs["child"][0] if len(kwargs["child"]) > 0 else None) elif kwargs["test"] == "l": import lexer lexer._test(kwargs["child"][0] if len(kwargs["child"]) > 0 else None) else: run_console(base_i, glob)
def test_nget_cases(): assert run('(1 nget)', 4, 5) == 4 assert run('(2 nget)', 4, 5) == 5 assert run('(3 nget)', 4, 5) == 'STACK_SIZE_UNDER_3' assert run('(0 nget)', 4, 5) == 'POSITIVE_INT_EXPECTED' assert run('((2 mul) 1 nget)', 3) == 'INT_EXPECTED'
def test_relational_commands(): assert run('(4 lt)', 3) == 1 assert run('(4 lt)', 5) == 0 assert run('(4 lt 10 add)', 3) == 11 assert run('(3 (2 mul) gt)') == 'INT_EXPECTED'
# name = s[0] # content = body[s[1]:s[2]] # if s[3]: # acc += ' ' * indent + '(' + name + ': ' + repr(content) + parse_result(body, s[3], indent + 1, tree) + ')' # else: # acc += ' ' * indent + '(' + name + ': ' + repr(content) + ')' # return acc #print parse_result(test, resultTrees, 0, []) import json def parse_result_list(body, tree): acc = [] for s in tree: name = s[0] content = body[s[1]:s[2]] if s[3]: acc.append([name, content, s[1], s[2], parse_result_list(body, s[3])]) else: acc.append([name, content, s[1], s[2]]) return acc #pp.pprint(parse_result_list(test, resultTrees)) p = parse_result_list(test, resultTrees) import interpreter #interpreter.run(p) interpreter.run(p)
def test_insufficient_stack_sizes_are_detected(): assert run('(swap)', 3) == 'STACK_SIZE_UNDER_2' assert run('(1 ge)') == 'STACK_SIZE_UNDER_2' assert run('(pop)') == 'STACK_SIZE_UNDER_1' assert run('(1 pop pop)') == 'STACK_SIZE_UNDER_1'
def test_swaps(): assert run('(swap)', 3, 4) == 4 assert run('(pop swap)', 3, 4, 5) == 5 assert run('(1 2 swap 3 pop)') == 1
#!/usr/bin/python -u from __future__ import print_function, division """ """ from itertools import chain, islice from functools import partial import sys import os from interpreter import run example_name = sys.argv[1] n_tokens_returned = None if len(sys.argv) < 3 else int(sys.argv[2]) with open('../brainfuck_code/{}.bf'.format(example_name), 'r') as file_: program = ''.join(chain.from_iterable(file_)) map( partial(print, end=''), islice(run(program), n_tokens_returned) )
from tokenizer import tokenize from interpreter import run import argparse from sys import exit if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-t', '--tokens', action='store_const', const=True, default=False, help="show tokens") parser.add_argument('-a', '--ast', action='store_const', const=True, default=False, help="show abstract syntax tree") parser.add_argument('-d', '--debug', action='store_const', const=True, default=False, help="show intermediate output") parser.add_argument('input', help="path to file") parser.add_argument('cmd', nargs="*") args = parser.parse_args() logfilter.rules = [ ('interpreter.*', True) ] if args.debug: logfilter.default = True else: logfilter.default = False with open(args.input) as fd: src = fd.read() tokens = tokenize(src) if args.tokens: print(tokens) ast = parse(tokens) if args.ast: pretty_print(ast) exit(run(ast, args.cmd))
#!/usr/bin/python from interpreter import run import sys if '--frame' in sys.argv: i = sys.argv.index('--frame') frame = int(sys.argv[i + 1]) sys.argv.pop(i) sys.argv.pop(i) else: frame = -1 if len(sys.argv) == 2: run(sys.argv[1], frame) elif len(sys.argv) == 1: run(raw_input("please enter the filename of an mdl script file: \n"), frame) else: print "Too many arguments."
def test_swaps(): assert run('(postfix 2 swap)', [3, 4]) == 4 assert run('(postfix 0 swap)', []) == 'error'
import sys from error import error import lexer import parse import interpreter if __name__ == '__main__': if len(sys.argv) == 1: src = input() else: src = open(sys.argv[1]).read() # print(type(lexem('(', 2, 0))) # print(emojify(lexer(texxxxxt))) print(interpreter.run(parse.parse(lexer.lexer(src))))
def test_num(): assert run('(postfix 0 1 2 3)', []) == 3
from __future__ import print_function, division from timeout_iterator import fetch_until_timeout from sample import random_code_flat from interpreter import run code = str(random_code_flat()) print(code) map(print, map(ord, fetch_until_timeout(timeout=0.01)( run(code) ) ) )
def test_exec(): assert run('(postfix 2 (add) exec)', [3, 4]) == 7 assert run('(postfix 2 1 exec)', [3, 4]) == 'error'
def test_relational_commands(): assert run('(postfix 1 4 lt)', [3]) == 1 assert run('(postfix 1 4 lt)', [5]) == 0
def test_sel(): assert run('(postfix 3 sel)', [3, 4, 0]) == 3 assert run('(postfix 3 sel)', [3, 4, 1]) == 4 assert run('(postfix 3 sel)', [3, 4, 2]) == 4 assert run('(postfix 2 sel)', [3, 4]) == 'error' assert run('(postfix 0 (add) (add) (add) sel)', []) == 'error'
self.program.append(Instruction('PLUS', None)) else: raise ValueError(node.type) def CALL(self, node): for arg in node.args[::-1]: self.eval(arg) self.eval(node.name) self.program.append(Instruction('CALL', len(node.args))) text = 'x:=0; while x < 5 { print(x); x := x+1; }' from grammar import parse from interpreter import Intepreter, run from pprint import pprint # i = Intepreter() ast = parse(text) # pprint(ast) bcc = ByteCodeCompiler() bcc.compile(ast) i = run(bcc.program) # print i.namespace
def test_absolute_value(): program = '(1 nget 0 lt (0 swap sub) () sel exec)' assert run(program, -7) == 7 assert run(program, 7) == 7 assert run(program, 7, 8, 9) == 7
#!/usr/bin/python -u from __future__ import print_function, division """ """ from itertools import chain, islice from functools import partial import sys import os from interpreter import run example_name = sys.argv[1] n_tokens_returned = None if len(sys.argv) < 3 else int(sys.argv[2]) with open('../brainfuck_code/{}.bf'.format(example_name), 'r') as file_: program = ''.join(chain.from_iterable(file_)) map(partial(print, end=''), islice(run(program), n_tokens_returned))
def test_exec_requires_list(): assert run('(3 exec)') == 'LIST_EXPECTED'
parser.add_argument('cmd', nargs="*") args = parser.parse_args() logfilter.rules = [ # ('interpreter.*', False), # ('indent.*', False) ] if args.debug: logfilter.default = True else: logfilter.default = False with open(args.input) as fd: # split source into tokens src = fd.read() tokens = tokenize(src) if args.tokens: print(tokens) # parse indentation ast = indent_parse(tokens) # finalize AST generation ast = parse(ast) if args.ast: pretty_print(ast) cmd = [args.input] + args.cmd # run the program if not args.dry_run: exit(run(ast, cmd, check_types=args.check_types))
def test_nget_cases(): assert run('(postfix 2 1 nget)', [4, 5]) == 4 assert run('(postfix 2 2 nget)', [4, 5]) == 5 assert run('(postfix 2 3 nget)', [4, 5]) == 'error'
def test_empty_program_returns_stack_top(): assert run('()', 3, 4) == 3
def test_pop(): assert run('(postfix 0 1 2 3 pop)', []) == 2 assert run('(postfix 0 1 pop)', []) == 'error'
def test_divide_by_zero_is_caught(): assert run('(2 0 div)') == 'DIVIDE_BY_ZERO' assert run('(4 sub div)', 4, 5) == 'DIVIDE_BY_ZERO' assert run('(4 sub rem)', 4, 5) == 'DIVIDE_BY_ZERO'
#!/usr/bin/python # -*- coding: utf-8 -*- import interpreter if __name__ == "__main__": interpreter.run()
from get_input import get from interpreter import run, preprocess p_input = preprocess(get(8).split('\n')) acc, visited, pc = run(p_input, set(), 0) print("Day eight part one: {}".format(acc)) nops = [i for (i, (op, _)) in enumerate(p_input) if op == 'nop'] jmps = [i for (i, (op, _)) in enumerate(p_input) if op == 'jmp'] def brute(op): if op == 'nop': ops = nops = [i for (i, (op, _)) in enumerate(p_input) if op == 'nop'] else: ops = jmps = [i for (i, (op, _)) in enumerate(p_input) if op == 'jmp'] for o in ops: p_copy = p_input.copy() p_copy[o] = ('jmp' if op == 'nop' else 'nop', p_copy[o][1]) acc, visited, pc = run(p_copy, set(), 0) if pc == len(p_copy): return acc acc = brute('nop') if not acc: acc = brute('jmp') print("Day eight part two: {}".format(acc))
def main(): cmd = sys.argv[1:] interpreter.run(cmd)
def test_average_program_works(): program = '(add 2 div)' assert run(program, 1, 1) == 1 assert run(program, 75, -25) == 25 assert run(program, -30, -20) == -25 assert run(program, 6, 7) == 6
def main(argv): defs = sum(map(load, argv[1:]), ()) interpreter.run(defs)
def test_ax_plus_by_plus_c(): program = '(4 nget 5 nget mul mul swap 4 nget mul add add)' assert run(program, 3, 4, 5, 2) == 25
def test_IF(): assert run('(postfix 2 add)', [1]) == 'error'
parser.add_argument('cmd', nargs="*") args = parser.parse_args() logfilter.rules = [ # ('interpreter.*', False), # ('indent.*', False) ] if args.debug: logfilter.default = True else: logfilter.default = False with open(args.input) as fd: # split source into tokens src = fd.read() tokens = tokenize(src) if args.tokens: print(tokens) # parse indentation ast = indent_parse(tokens) # finalize AST generation ast = parse(ast) if args.ast: pretty_print(ast) cmd = [args.input]+args.cmd # run the program if not args.dry_run: exit(run(ast, cmd, check_types=args.check_types))
def run_file(base_i, child, glob): text = open(child[0]).read() if text.strip() != "": #wrap(lambda: intp.run(text, base_i), base_i, glob) intp.run(text, base_i) cli.run(base_i, child[1:], wrap)
def test_non_integer_result_is_detected(): assert run('((2 mul))') == 'NON_INT_RESULT'
import common import utils from interpreter import run from database import Db from os import path database_file_name = 'database.db' if __name__ == '__main__': database_path = path.join(utils.get_main_module_path(), database_file_name) common.init(database_path) db = Db(database_path) while True: print() run(db) print()
import interpreter while True: text = input('>>>> ') if text.strip() == "": continue result, error = interpreter.run('<stdin>', text) if error != None: print(error.as_string()) elif result: if len(result.elements) == 1: print(repr(result.elements[0])) else: print(repr(result))
""" Cyclone programming language by DatOneLefty """ print """ Cyclone Programming language Pre-Alpha Interpreter Commit 2 """ import interpreter as inter inter.init() while True: codeline = raw_input (">>>") inter.run(codeline)