def test_inttrait(): builtincode = """ object inttrait: x = 1 def maybe_fortytwo: if self: 42 else: x """ interpreter = Interpreter(builtincode) w_module = interpreter.make_module() # the parent of a normal module is the builtin module builtins = w_module.getparents()[0] inttrait = builtins.getvalue("inttrait") ast = parse(""" x = 5 x # this returns 1, because it looks in the inttrait defined above m0 = 0 maybe_fortytwo m1 = x maybe_fortytwo inttrait x = 2 m2 = 0 maybe_fortytwo tr = inttrait """) interpreter.eval(ast, w_module) x = w_module.getvalue("x") assert w_module.getvalue("tr") is inttrait # the inttrait is defined in the builtin module, so its __parent__ is that # module assert inttrait.getparents() == [builtins] assert x.value == 1 assert x.getparents() == [inttrait] assert w_module.getvalue("m0").value == 1 assert w_module.getvalue("m1").value == 42 assert w_module.getvalue("m2").value == 2
def index(request): if not request.POST: return install(request) response = HttpResponse() try: active_xml = request.POST.get('activexml') if not active_xml: response.write("Failure - Please post with valid XML string to process.") return response interp = Interpreter() interp.processXML(active_xml) interpList = interp.topPhraseList(count = 3) outputList = [interp.word_count] for tup in interpList: outputList.append({'keyPhrase':tup[0], "iCount" : tup[1], "weight":tup[2]}) jsonString = simplejson.dumps( outputList ) print outputList response.write(jsonString) return response except Exception, e: print e response.write(str(e)) return response
def test_builtin_simple(): builtincode = """ x = 1 object None: 1 def pass: None """ # construct the builtin module by running builtincode within the context of # a new empty module interpreter = Interpreter(builtincode) w_module = interpreter.make_module() # the parent of a normal module is the builtin module builtins = w_module.getparents()[0] assert builtins.getvalue('x').value == 1 ast = parse(""" tx = x object a: pass ax = a x """) interpreter.eval(ast, w_module) assert w_module.getvalue("ax").value == 1 assert w_module.getvalue("tx").value == 1
def download_planning(uuid): try: planning = _get_planning(uuid, g.user_id) except CAPException as e: return e.res moodle_archive_path = planning.mbz_fullpath planning_txt = planning.planning_txt if not planning_txt: return _bad_request() # Make tmp directory for MBZ extraction and ics download with tempfile.TemporaryDirectory() as tmp_path: # Download calendar to tmp folder calendar = CalendarReader(planning.ics_fullpath) calendar_meetings = calendar.get_all_meetings() # Extract Moodle course to tmp folder with tarfile.open(moodle_archive_path) as tar_file: tar_file.extractall(tmp_path) course = MoodleCourse(tmp_path) interpreter = Interpreter(calendar_meetings, course) for line in planning_txt.split('\n'): event = interpreter.get_new_event_from_string(line) course.replace_event(event) folder = os.path.join(app.config['UPLOAD_FOLDER'], uuid) latest_mbz_path = os.path.join(folder, 'latest.mbz') course.write(latest_mbz_path) return send_from_directory( folder, 'latest.mbz', as_attachment=True)
def compiler(): text = request.POST.get("text") interpreter = Interpreter(text) interpreter.compile() result = str(interpreter) return {'result':result}
def test_args_order(): ast = parse(""" def f(a, b, c): if a: 4 else: if b: 8 else: if c: 15 else: 16 w = f(1, 1, 1) x = f(0, 1, 1) y = f(0, 0, 1) z = f(0, 0, 0) """) interpreter = Interpreter() w_module = interpreter.make_module() interpreter.eval(ast, w_module) assert w_module.getvalue("w").value == 4 assert w_module.getvalue("x").value == 8 assert w_module.getvalue("y").value == 15 assert w_module.getvalue("z").value == 16
def main(): raw_code = """ Input>>Number(num1) Integer Input>>Number(num2) Integer num1,num2>>Number(ans) Added ans>>Screen(Output) Demo ConsolePlus """ a = Interpreter() a.parser(raw_code) print(a.info) b = SMLHandler(a.source) b.build_dom_tree() print(b.info) ss = b.build_sml() print(ss) c = SMLHandler() c.read_sml(ss) c.read_dom_tree() c.dom = c.builder.getDOMImplementation() c.tree = c.dom.createDocument("http://cp-web.appspot.com/source", "Source", None) c.build_dom_tree() print(c.build_sml())
def test_example(self): example = """addi R10,R0,100 sw R0,24(R0) sw R0,28(R0) LOOP: lw R6,28(R0) mul R7,R6,R6 lw R1,24(R0) add R9,R1,R7 sw R9,24(R0) addi R6,R6,1 sw R6,28(R0) ble R6,R10,LOOP""" text = [ "00100000000010100000000001100100 ; I1: addi R10,R0,100", "10101100000000000000000000011000 ; I2: sw R0,24(R0)", "10101100000000000000000000011100 ; I3: sw R0,28(R0)", "10001100000001100000000000011100 ; I4: lw R6,28(R0)", "00000000110001100011100000011000 ; I5: mul R7,R6,R6", "10001100000000010000000000011000 ; I6: lw R1,24(R0)", "00000000001001110100100000100000 ; I7: add R9,R1,R7", "10101100000010010000000000011000 ; I8: sw R9,24(R0)", "00100000110001100000000000000001 ; I9: addi R6,R6,1", "10101100000001100000000000011100 ; I10: sw R6,28(R0)", "00011100110010100000000000001100 ; I11: ble R6,R10,12", ] interpreter = Interpreter(example) interpreter.compile() for compiled, correct in zip(interpreter.instructions, text): self.assertEqual(compiled, correct)
def test_if_example(self): example = """addi R1,R0,3 addi R2,R0,2 beq R1,R2,EQ jmp NE EQ: addi R1,R0,5 jmp END NE: addi R1,R0,7 END:""" text = [ "00100000000000010000000000000011 ; I1: addi R1,R0,3", "00100000000000100000000000000010 ; I2: addi R2,R0,2", "00010100001000100000000000001000 ; I3: beq R1,R2,8", "00001000000000000000000000011000 ; I4: jmp 24", "00100000000000010000000000000101 ; I5: addi R1,R0,5", "00001000000000000000000000011100 ; I6: jmp 28", "00100000000000010000000000000111 ; I7: addi R1,R0,7", ] interpreter = Interpreter(example) interpreter.compile() for compiled, correct in zip(interpreter.instructions, text): self.assertEqual(compiled, correct)
def compile_pascal(source, dest, is_debug = False, is_interpret = False, out_stream = sys.stdout, output_tokens = False, output_bytecodes = False, lib = ['.'], in_stream = sys.stdin): ''' DID YOU KNOW that compile() is a built in function? ''' set_debug(is_debug) debug("Compiling %s into %s" % (source, dest)) scanner = Scanner(source) tokens = scanner.scan() if output_tokens: write(tokens, source + "_tokenized") debug('scanning complete') parser = Parser(tokens, source, lib = lib) bytecodes, success = parser.parse() if output_bytecodes: if is_debug: write(prettify(bytecodes), source + "_unassembled") else: write(bytecodes, source + "_unassembled") if not success: print 'Parsing error' return debug('parsing complete') assembler = Assembler(bytecodes) assembled = assembler.assemble() if is_debug: write(prettify(assembled), dest + '_debug') write(assembled, dest) debug('assembly complete.' ) if is_interpret: interp = Interpreter(out_stream, in_stream, code = assembled) interp.interpret() else: debug('run program now with `python interpreter.py %s`' % dest)
def test_override__parent__(): ast = parse(""" k = 10 object a: x = 1 y = 2 z = k object b: __parent__ = a y = 5 z = y ax = a x ay = a y az = a z bx = b x by = b y bz = b z """) interpreter = Interpreter() w_module = interpreter.make_module() interpreter.eval(ast, w_module) a = w_module.getvalue("a") assert a.getvalue('__parent__') is w_module assert w_module.getvalue("b").getvalue('__parent__') is a assert w_module.getvalue("b").getparents() == [a] assert w_module.getvalue("ax").value == 1 assert w_module.getvalue("ay").value == 2 assert w_module.getvalue("az").value == 10 assert w_module.getvalue("bx").value == 1 assert w_module.getvalue("by").value == 5 assert w_module.getvalue("bz").value == 5
def download_planning(uuid): planning = _get_planning(uuid) if not planning: return jsonify({"message": 'Planning with uuid "%s" not found' % uuid}), 404 moodle_archive_path = planning.mbz_fullpath planning_txt = planning.planning_txt if not planning_txt: return _bad_request() # Make tmp directory for MBZ extraction and ics download with tempfile.TemporaryDirectory() as tmp_path: # Download calendar to tmp folder calendar_path = _dl_and_save_ics_file(planning.ics_url, tmp_path) calendar = CalendarReader(calendar_path) calendar_meetings = calendar.get_all_meetings() # Extract Moodle course to tmp folder with tarfile.open(moodle_archive_path) as tar_file: tar_file.extractall(tmp_path) course = MoodleCourse(tmp_path) interpreter = Interpreter(calendar_meetings, course) for line in planning_txt.split("\n"): event = interpreter.get_new_event_from_string(line) course.replace_event(event) folder = os.path.join(app.config["UPLOAD_FOLDER"], uuid) latest_mbz_path = os.path.join(folder, "latest.mbz") course.write(latest_mbz_path) return send_from_directory(folder, "latest.mbz", as_attachment=True)
def do_the_twist(code): from simpleparser import parse ast = parse(code) interpreter = Interpreter() w_module = interpreter.make_module() interpreter.eval(ast, w_module) return w_module
def test_huge_negative_intliteral(): ast = parse(""" x = -10000 """) interpreter = Interpreter(empty_builtins) w_module = interpreter.make_module() interpreter.eval(ast, w_module) assert w_module.getvalue("x").value == -10000
def test_ignoring_label_to_string(self): """ Bytecode should not have label names.""" code = """nop label: nop""" interpreter = Interpreter(code) interpreter.compile() self.assertFalse("label" in str(interpreter))
def test_primitive(): ast = parse(""" k = 10 $int_add(31) """) interpreter = Interpreter() w_module = interpreter.make_module() interpreter.eval(ast, w_module) assert w_module.getvalue("k").value == 41
def test_primitive(): ast = parse(""" x = 1 $int_add(2) """) interpreter = Interpreter(empty_builtins) w_module = interpreter.make_module() interpreter.eval(ast, w_module) assert w_module.getvalue("x").value == 3
def test_bne(self): code = """nop LOOP: bne R1,R2,LOOP""" interpreter = Interpreter(code) interpreter.compile() self.assertEqual(len(interpreter.instructions), 2) self.assertEqual(interpreter.instructions[1], "00010000001000100000000000000000 ; I2: bne R1,R2,0")
def test_assignment(): ast = parse(""" x = 1 """) interpreter = Interpreter(empty_builtins) w_module = interpreter.make_module() interpreter.eval(ast, w_module) assert w_module.getvalue("x").value == 1
def test_jmp_back(self): code = """label: jmp label""" interpreter = Interpreter(code) interpreter.compile() self.assertEqual(len(interpreter.instructions), 1) self.assertEqual(interpreter.instructions[0], "00001000000000000000000000000000 ; I1: jmp 0") self.assertEqual(interpreter.labels.get("label"), 0)
def test_jmp_forward(self): code = """jmp label label:""" interpreter = Interpreter(code) interpreter.compile() self.assertEqual(len(interpreter.instructions), 1) self.assertEqual(interpreter.instructions[0], "00001000000000000000000000000100 ; I1: jmp 4") self.assertEqual(interpreter.labels.get("label"), 4)
def run(self): plugin_loader = PluginLoader() plugin_directory = PluginDirectory() commands = plugin_loader.load(plugin_directory) interpreter = Interpreter(commands) while True: print interpreter.interpret(raw_input())
def test_ble(self): code = """nop LOOP: nop ble R1,R2,LOOP""" interpreter = Interpreter(code) interpreter.compile() self.assertEqual(len(interpreter.instructions), 3) self.assertEqual(interpreter.instructions[2], "00011100001000100000000000000100 ; I3: ble R1,R2,4")
def test_pop(): ast = parse(""" x = 1 # the result of this will be popped from the stack x = 2 """) interpreter = Interpreter(empty_builtins) w_module = interpreter.make_module() interpreter.eval(ast, w_module) assert w_module.getvalue("x").value == 2
def create_task(self): interpreter = Interpreter(self.get_content()['data']) interpreter.run() task = Task(based_on_exercise=self.eid, part_of_match=None, part_of_sheet=None) task.set_content(interpreter.globs) db.session.add(task) db.session.commit() return task
def main(): settings._filename = get_settings_filename() dbaccess.connect() interpreter = Interpreter() print_init_message() try: interpreter.cmdloop('') except KeyboardInterrupt: print('') sys.exit(0)
def test_objectdefinition_simple(): ast = parse(""" object x: a = 1 b = 2 """) interpreter = Interpreter(empty_builtins) w_module = interpreter.make_module() interpreter.eval(ast, w_module) assert w_module.getvalue("x").getvalue("a").value == 1 assert w_module.getvalue("x").getvalue("b").value == 2
def test_duplicate_base_error(): ast = parse(""" object base: x = 1 object sub(p1=base, p2=base): x = 2 y = sub x """) interpreter = Interpreter() w_module = interpreter.make_module() py.test.raises(TypeError, interpreter.eval, ast, w_module)
def test_capture(): ast = parse(""" k = 10 object a: j = k k = 11 aj = a j """) interpreter = Interpreter() w_module = interpreter.make_module() interpreter.eval(ast, w_module) assert w_module.getvalue("aj").value == 10
class TestBinaryOperations(unittest.TestCase): def setUp(self): self.interpreter = Interpreter() def test_to_bin(self): self.assertEqual(self.interpreter._to_bin(0), "0") self.assertEqual(self.interpreter._to_bin(2), "10") self.assertEqual(self.interpreter._to_bin(-2, 5), "11110") self.assertEqual(self.interpreter._to_bin(-4, 5), "11100") self.assertEqual(self.interpreter._to_bin(-7, 5), "11001") self.assertEqual(self.interpreter._to_bin(-8, 5), "11000") self.assertEqual(self.interpreter._to_bin(12, 5), "01100")
def __init__(self): Tk.__init__(self) # Create Interpteret object self.interpreter = Interpreter() # Create Graph Object and Initialize self.Graph = Graph_class(self, bg='white', width=900, height=600, varDict=self.interpreter.getVarDict()) self.Graph.place(x=10, y=10) self.Graph.config(highlightbackground='black') # Adding Variable self.interpreter.interpret('graphScale=' + str(self.Graph.scale)) # Setting up input box self.entry = Entry(self, width=56, font=("Times", "10")) self.entry.place(x=920, y=550) self.entry.focus_set() # Setting up terminal window self.inputList = [] self.inputIndex = 0 self.textPad = ScrolledText.ScrolledText(self, width=57, height=17, font=("Times", "10")) # self.textPad.configure(state='disabled') self.textPad.insert(END, 'Type "help" for List of commands\n') self.textPad.place(x=920, y=287) # Binding events to functions self.bind('<Return>', lambda x: self.interpret()) self.bind('<Up>', lambda x: self.prevInp()) self.bind('<Down>', lambda x: self.nextInp()) # Setting up GUI self.setupButtons() self.setupListBox()
def run(fn, text): # 生成Tokens lexer = Lexer(fn, text) tokens, error = lexer.make_tokens() if error: return None, error # print(tokens) # 生成AST,通过__repr__形式打印出树结构而已 parser = Parser(tokens) ast = parser.parse() if ast.error: return None, ast.error # print(ast.node) # 通过解释器执行程序 interpreter = Interpreter() context = Context("<program>") context.symbol_table = global_symbol_table result = interpreter.visit(ast.node, context) return result.value, result.error
class Main(object): def __init__(self): self.interpreter = Interpreter() def run(self, source_code, ignore_errors=False, repl=False): tokens = Scanner(source_code).scanTokens() parser = Parser(tokens) statements = parser.parse() if repl and len(statements) == 1 and isinstance( statements[0], stmt.StmtExpression): statements[0] = stmt.StmtPrint(statements[0].expression) if ErrorHandler.errored: if ignore_errors: ErrorHandler.errored = False return self.interpreter.interpret(statements)
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 test_binary_comparison(self): tests = [ ("1 > 2", False), ("1 > 0", True), ("2 < 2", False), ("2 <= 2", True), ("3 >= 2", True), ] for (source, exp) in tests: res = parseExp(source)[0].expression.accept(Interpreter()) assert res == exp
def test_binary_math(self): tests = [ ("1 + 2", 3), ("1 - 2", -1), ("2 * 4", 8), ("4 / 2", 2), ('"1" + "2"', "12"), ] for (source, exp) in tests: res = parseExp(source)[0].expression.accept(Interpreter()) assert res == exp
def run(fn, text): lexer_ = Lexer(fn, text) tokens, error = lexer_.make_tokens() if error: return '', error print(text) print(tokens) parser = Parser(tokens) ast = parser.parse() print(ast.node) interpreter_ = Interpreter() res = interpreter_.visit(ast.node) print(res['sites'][0]['url']) return res, ''
def main(): try: opts, _args = getopt.getopt(sys.argv[1:], '', OPTIONS) options = {k: v for k, v in opts} # pylint: disable=R1721 except getopt.GetoptError as err: exit_fail(err) try: filename = 'examples/sqrt.m' if '--path' in options: filename = options['--path'] print_main(f'Opening file: {filename}') with open(filename, "r") as file: text = file.read() except IOError: exit_ok(f"Cannot open {filename} file") if '--clear' in options: clear() exit_ok() lexer = Scanner() if '--lexer' in options: run_lexer(lexer, text) exit_ok() if '--use_cache' not in options: clear() if '--zip' in options: out = options['--zip'] if options['--zip'] else 'slawecki_tratnowiecki' zip_files(out) if '--use_cache' in options: move_auto_files(mv_reversed=True) parser = Parser(lexer) ast = parser.parse(text) move_auto_files() if not ast: exit_fail('Cannot run your program: returning.') if '--print_ast' in options: ast.print_tree() type_checker = TypeChecker() type_checker(ast) if not type_checker.accepted: exit_fail('Cannot run your program: returning.') interpreter = Interpreter() interpreter(ast)
class Hal: """ Hal is our speech assistant and he starts to record spoken words after someone said "Hello Hal". And the speech assistant "Hal" reacts with an answer. """ def __init__(self): self.listener = Listener() self.spoken_words = "" self.interpreter = Interpreter() def activate(self): print("mock: Hal is now activated and listening") print("Hello Dave what can I do for you?") self.main_menu() def main_menu(self): while True: utilities.clear_screen() print("*" * 80) print("Hal main menu") print("*" * 80) print("\t press 1 to talk to Hal") print("\t press 2 to turn off Hal") inp = input("Please type 1 or 2 and press enter:") if inp == "1": self.start_listening() elif inp == "2": sys.exit() else: input( "Wrong command please press enter to continue and repeat") def start_listening(self): self.spoken_words = self.listener.listen() self.interpreter.execute(self.spoken_words) self.spoken_words = self.listener.listen() @staticmethod def error(message=''): print(message) input('Invalid input. Please press enter to continue. ')
def main(): # Settings os.environ['DYNACONF_SETTINGS'] = "settings.yml" # Parse arguments parser = argparse.ArgumentParser(description='Tool to manipulate accounts') subparsers = parser.add_subparsers(help='command help', dest='command') parser_balance = subparsers.add_parser('balance', help='balance help') parser_order = subparsers.add_parser('order', help='order help') parser_order.add_argument("market", action='store') parser_order.add_argument("coin", action='store') parser_order.add_argument("order_id", action='store') parser_order = subparsers.add_parser('cancel', help='cancel help') parser_order.add_argument("market", action='store') parser_order.add_argument("coin", action='store') parser_order.add_argument("order_id", action='store') parser_order = subparsers.add_parser('sell', help='sell help') parser_order.add_argument("market", action='store') parser_order.add_argument("coin", action='store') parser_order.add_argument("volume", action='store', type=float) parser_order.add_argument("rate", action='store', type=float) parser_order = subparsers.add_parser('buy', help='buy help') parser_order.add_argument("market", action='store') parser_order.add_argument("coin", action='store') parser_order.add_argument("volume", action='store', type=float) parser_order.add_argument("rate", action='store', type=float) parser_order = subparsers.add_parser('ticker', help='ticker help') parser_order.add_argument("market", action='store') parser_order.add_argument("coin", action='store') args = parser.parse_args() # Interpret command interpreter = Interpreter() interpreter.interpret(args)
def __init__(self, game, speed, sprites, state=None): super().__init__() self.game = game self.sound = QtMultimedia.QSound('beep.wav') self.controller = Controller() path = os.path.join("games", game) self.interpreter = Interpreter(path, self.controller, sprites, self.sound.play) if state is not None: self.interpreter.load_state(state) self.display = Display(self) self.display.move(0, 0) self.display.resize(640, 320) self.resize(640, 320) self.show() self.timer = QtCore.QTimer() self.timer.timeout.connect(self.main_loop) self.timer.start(10 - (speed / 10))
def make_tree(source, o): program = source.read() print('program: ', program) tokens = lexer(program) # removing space and comment tokens before passing list to parser parser_tokens = [ token for token in tokens if token.type != 'COMMENT' and token.type != 'SPACE' ] tree = parser(parser_tokens) print(tree) interpreter = Interpreter() interpreter.eval(tree) brainf = interpreter.result() print('Brainfuck translation: \n', brainf) print('\n') print('Program', o.name, 'saved') o.write(brainf) o.flush()
def main(): if len(sys.argv) != 2: print('Usage: %s FILE' % sys.argv[0]) exit(0) code = eigthxp_read_code(sys.argv[1]) print('%s %s %s' % ('=' * 30, 'Tokenizer', '=' * 30)) tokens = list(Tokenizer(code)) print('%s %s %s' % ('=' * 30, 'Parser', '=' * 30)) instructions = list(Parser(tokens)) print('%s %s %s' % ('=' * 30, 'VM', '=' * 30)) Interpreter().run(instructions)
def main(): while True: try: text = input("calc>>") except Exception as e: break if len(text) == 0: continue if text == 'exit': break interpreter = Interpreter(Lexer(text)) try: result = interpreter.interpret() except Exception as e: print(e) continue print(result)
def test1(self): """ Takes no input and produces a copy of itself as output. """ pgm = parse( '109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99') interpreter = iter(Interpreter(pgm)) # Why is it not copying itself properly? self.assertEqual(list(interpreter), [ 109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99, -1 ])
class Jarvis(object): def __init__(self): self.config = Config() self.interpreter = Interpreter(self.config) self.model = "resources/JARVIS.pmdl" self.sensitivity = 0.3 self.audio_gain = 1.2 self.detector = snowboydecoder.HotwordDetector(self.model, sensitivity=self.sensitivity, audio_gain=self.audio_gain) self.interpreter.calibrate(self.run) def detect_callback(self): self.detector.terminate() snowboydecoder.play_audio_file(snowboydecoder.DETECT_DING) self.interpreter.listen() self.run() def run(self): print "start recognizing word" self.detector.start(detected_callback=self.detect_callback, sleep_time=0.03)
def test_compound_statement(): text = """ BEGIN BEGIN number := 2; a := number; b := 10 * a + 10 * number / 4; c := a - - b END; x := 11; END. """ interpreter = Interpreter(Parser(Lexer(text))) interpreter.interpret() ar = interpreter.call_stack.peek() assert ar["number"] == 2 assert ar["a"] == 2 assert ar["b"] == 25 assert ar["c"] == 27 assert ar["x"] == 11
def main(): file = open('console.psc', 'r') line = file.readline() code = line while len(line) > 0: line = file.readline() code += ' EOL ' + line analyzer = Analyzer(code) interpreter = Interpreter(analyzer)
def test_prime(self): interpreter = Interpreter() self.assertEqual(interpreter.runProgram('21@v'), 'False', 'Should be False') self.assertEqual(interpreter.runProgram('1v'), 'False', 'Should be False') self.assertEqual(interpreter.runProgram('0v'), 'False', 'Should be False') self.assertEqual(interpreter.runProgram('1~v'), 'False', 'Should be False') self.assertEqual(interpreter.runProgram('2v'), 'True', 'Should be True') self.assertEqual(interpreter.runProgram('29@v'), 'True', 'Should be True')
def repl(): print('PyBasic v0.3 (c) 2020 Gently Solutions Ltd') print('Type "exit" to quit.') i = Interpreter() while True: source = input("> ") if source.upper() == "EXIT": break if source.upper() == "DEBUG ON": print("Debug flag turned on.") i.debug = True continue if source.upper() == "DEBUG OFF": print("Debug flag turned off.") i.debug = False continue regex = re.compile('^[0-9]+') result = regex.match(source) if result: lineno = int(result.group()) code = source[result.end():] if code == "": i.program.pop(lineno, -1) # delete code line else: # todo - think about how to process code before storing # should it be parsed and tokenized and grammatically checked ? i.program.update({lineno: code}) # insert plain code line else: try: i.execute(source) except IndexError as e: pass except SyntaxError as e: print(e)
def test19(): i = Interpreter() inp_str = "x=2" out_str = i.eval_string(inp_str) assert out_str == "2" assert "x" in i._variables assert i._variables["x"].val == Number(2) inp_str = "y=x" out_str = i.eval_string(inp_str) assert out_str == "2" assert "y" in i._variables assert i._variables["y"].val == Number(2) inp_str = "y=7" out_str = i.eval_string(inp_str) assert out_str == "7" assert "y" in i._variables assert i._variables["y"].val == Number(7) inp_str = "y = 2 * i - 4" out_str = i.eval_string(inp_str) assert out_str == "-4 + 2i" assert "y" in i._variables assert i._variables["y"].val == ComplexNumber(-4, 2)
def test_individual_operations(self): value = Interpreter().visit(AddNode(NumberNode(27), NumberNode(14)) self.assertEqual(value, Number(41)) value = Interpreter().visit(SubtractNode(NumberNode(27), NumberNode(14)) self.assertEqual(value, Number(13)) value = Interpreter().visit(MultiplyNode(NumberNode(27), NumberNode(14)) self.assertEqual(value, Number(378)) value = Interpreter().visit(DivideNode(NumberNode(27), NumberNode(14)) self.assertEqual(value.value, 1.92857, 5)) with self.assertRaises(Exception): Interpreter().visit(DivideNode(NumberNode(27), NumberNode(0))) def test_full_expression(self): tree=AddNode( NumberNode(27), MultiplyNode( SubtractNode( DivideNode( NumberNode(43), NumberNode(36), ), NumberNode(48), ), NumberNode(51), ) ) result = Interpreter().visit(tree) self.assertAlmostEqual(result.value, -2360.08, 2)
def test_parser_case_insensitive(): sources = ''' PROGRAM Part10; VAR x : INTEGER; y : REAL; PROCEDURE P1(z : REAL; i : integer); VAR A2 : REAL; procedure p2(a : INTEGER); begin a2 := a + 1; end; BEGIN {P1} p2(1); {2} x := x + a2 + z + i; {6} y := x * 2; {12} END; {P1} beGin {Part10} BEGIN x := 1; Y := x / 3; END; P1(1, 2); End. {Part10} ''' tree = Parser(Lexer(sources)).parse() SemanticAnalyzer().analyze(tree) interpreter = Interpreter() top_stack_frame = interpreter.run(tree) assert top_stack_frame['x'] == 6 assert top_stack_frame['y'] == 12
def main(): mode = 'INFIX' interpreter = Interpreter() while True: try: text = input(mode + ' -> ') except EOFError: break if not text: continue if text.strip() == 'exit': break if text.strip().upper() in ['INFIX', 'POSTFIX', 'PREFIX']: mode = text.strip().upper() continue result = interpreter.eval(text, mode) print(result)
def calculate_result(res, literals): combinations = list(itertools.product([1, 0], repeat=len(literals))) truth_table = [] for i in range(len(combinations) - 1, -1, -1): translator = {} for key_ in literals: translator[key_] = combinations[i][literals.index(key_)] interpreter = Interpreter(translator) truth_table.append([ int(interpreter.read(res)), [translator[literal] for literal in literals] ]) knf_form, dnf_form = normal_forms(truth_table, literals) print("KNF:", knf_form) print("DNF:", dnf_form) if len(truth_table) > 1: print(' '.join(literals), "S") for entry in truth_table: print(' '.join(map(str, entry[1])), entry[0])
def run_feedback_loop(program, settings): result = None output = [0] interpreters = [Interpreter(program, [setting]) for setting in settings] while result is None: for count, interpreter in enumerate(interpreters): interpreter.receive_input(output) while not interpreter.halt: result = interpreter.step() output = interpreter.output.copy() interpreter.output = [] return result[0]
async def apply(host='localhost', port='5432'): # this should be simplified into a one line declaration of Store or # some subclass or composition, then pass the single arg to server store = Store() communicator = Communicator(store) interpreter = Interpreter(store) # this could probably be simplified by giving manager a default # value in Service server = Server(host, port, interpreter, communicator) manager = Manager() service = Service(manager, server) await service.run()
def test_proc_call(self): program_code = r''' program Main; procedure Alpha(a : integer; b : integer); var x : integer; begin x := (a + b ) * 2; end; begin { Main } Alpha(3 + 5, 7); { procedure call } end. { Main } ''' lexer = Lexer(program_code) parser = Parser(lexer) tree = parser.parse() semantic_analyzer = SemanticAnalyzer() semantic_analyzer.visit(tree) interpreter = Interpreter(tree) interpreter.interpret()
def run(self, test): for x in test: if x.isdigit(): new = Node(x,None,None) self.push(new) self.leitura() else: node = Node(x) node.r = self.pop() node.l = self.pop() new = node self.push(new) raiz = Tree() raiz.root = self.pop() print("---------------") raiz.em_ordem(raiz.root) result = Interpreter() x = result.process(raiz.root) print(x) output = open('saida.txt', 'w') output.write(str(x)) output.close()
def download_planning(uuid): try: planning = _get_planning(uuid, g.user_id) except CAPException as e: return e.res moodle_archive_path = planning.mbz_fullpath planning_txt = planning.planning_txt if not planning_txt: return _bad_request() # Make tmp directory for MBZ extraction and ics download with tempfile.TemporaryDirectory() as tmp_path: # Download calendar to tmp folder calendar = CalendarReader(planning.ics_fullpath) calendar_meetings = calendar.get_all_meetings() # Extract Moodle course to tmp folder with tarfile.open(moodle_archive_path) as tar_file: tar_file.extractall(tmp_path) course = MoodleCourse(tmp_path) interpreter = Interpreter(calendar_meetings, course) for line in planning_txt.split('\n'): event = interpreter.get_new_event_from_string(line) if not event.is_user_defined(): course.replace_event(event) folder = os.path.join(app.config['UPLOAD_FOLDER'], uuid) latest_mbz_path = os.path.join(folder, 'latest.mbz') course.write(latest_mbz_path) with open(os.path.join(folder, 'latest.mbz'), 'rb') as f: encoded = base64.encodestring(f.read()).decode() return jsonify({'mbz_64': encoded})