def run(text): # Generate tokens # print("RUN1") lexer = lex.Lexer(text) tokens, error = lexer.make_tokens() if error: print() # return None, error # Generate AST print("RUN2 | Токены: ", tokens) parser = pars.Parser(tokens) ast = parser.parse() # print(ast.node) # if ast.error: # print() # return (ast.error) # Run program print("RUN3 | АСТ:", ast.node) interpreter = inter.Interpreter() context = inter.Context('<program>') context.symbol_table = global_symbol_table result = interpreter.visit(ast.node, context) print(result.value) return result.error
def __init__(self, filepaths): # Verify arguments if len(filepaths) < 2: raise Exception( "Game requires at least two players. " "Provide a filepath for the script used for each player") self.strategy_filepaths = filepaths # DEFAULT PARAMETERS self.board_size = [20, 20] self.turn_limit = 10000 self.unit_limit_pct = 0.05 # The maximum number of allowed units per player, as a percentage of board capacity self.log_level = 10 # Level of log info. Use 30 to only display win/lose messages, 20 to also display turn # numbers and the board, and 10 to also display action messages self.write_to_file = True self.log_path = "log.txt" # OBJECT INITIALIZATION self.players = {} # Dict of players, player_id -> player_object self.turn_handler = turn_handler.TurnHandler( ) # Turn handler in charge of determining which unit acts when self.board = board.Board(self.turn_handler, self.players, self.board_size, self.unit_limit_pct) # Board and units self.user_commands = cmd.Commands(self.board, self.turn_handler) self.interpreter = interpreter.Interpreter(self.turn_handler, self.user_commands) # CONFIGURE LOGGER self.configure_logger()
def eval_macro(product, mappings, interpreter): """ Evaluate a macro the has already been matched and mapped. Parameters: product: The product form of the macro or a python function (mappings, interpreter -> nodes) mappings: The mappings from capture nodes to expressions. interpreter: The interpreter to run the macro in. """ if product[0].node_type != NodeType.FUNC: #A normal macro prod_result = fill_in_form(product, mappings) #The inner interpreter has the super, public and private macro spaces as its super macro space sup_mcs_product = i_utils.get_mcs_product_from_macros(interpreter._macros) temp_intp = intp.Interpreter(sup_mcs_product) #No side effects if BALK evaluated = temp_intp.interpret_nodes(prod_result)[0] #The first should be either BALK or a PAREN if evaluated != normal('BALK'): evaluated = evaluated.children #Unwrap # interpreter.set_private_mcs_product(i_utils.get_mcs_product_from_macros(temp_intp.public_macros + interpreter.private_macros)) #Now side effects take place interpreter.set_macro_products(temp_intp) interpreter.queue(temp_intp.output_queue) interpreter.flush_output() return True, evaluated else: return False, None else: #product is a Python function (mappings, interpreter -> nodes). A built-in macro. return product[0](mappings, interpreter)
def setUp(self): """Setup the test harness.""" # Setup logging with a timestamp, the module, and the log level. logging.basicConfig(level=logging.DEBUG, format=('%(asctime)s - %(module)s -' ' %(levelname)s - %(message)s')) # Create a tempfile that would represent the EC UART PTY. self.tempfile = tempfile.NamedTemporaryFile() # Create the pipes that the interpreter will use. self.cmd_pipe_user, self.cmd_pipe_itpr = threadproc_shim.Pipe() self.dbg_pipe_user, self.dbg_pipe_itpr = threadproc_shim.Pipe( duplex=False) # Mock the open() function so we can inspect reads/writes to the EC. self.ec_uart_pty = mock.mock_open() with mock.patch('__builtin__.open', self.ec_uart_pty): # Create an interpreter. self.itpr = interpreter.Interpreter(self.tempfile.name, self.cmd_pipe_itpr, self.dbg_pipe_itpr, log_level=logging.DEBUG, name="EC") # First, check that interpreter is initialized to connected. self.assertTrue(self.itpr.connected, ('The interpreter should be' ' initialized in a connected state'))
def process_message(self, data): intr = interpreter.Interpreter() if data['text'].startswith('<@{}> run'.format(self.user_id)): script = data['text'].replace('<@{}> run'.format(self.user_id), '') script = script.strip() script = script.replace('<', '<') script = script.replace('>', '>') out = "" print script try: intr.compile_interpret(parser.parse(script)) out_list = intr.get_stdout() if len(out_list) > 0: out = '\n```{}```'.format('\n'.join(out_list)) else: out = 'No output' except Exception as e: out += "\n\nError has occured while excecuting SlackMojicode:\n```{}: {}```" \ .format(type(e), e) raise e self.outputs.append([data['channel'], '\n' + out]) if data['text'].startswith('<@{}> convert'.format(self.user_id)): script = data['text'].replace('<@{}> convert'.format(self.user_id), '') script = script.strip() script = script.replace('<', '<') script = script.replace('>', '>') script = converter.convert(script) self.outputs.append([data['channel'], script])
def ifelse(args): args = valueify(args) if len(args) != 3: raise MethodInputError( "Incorrect number of inputs, should be 3, %s were given" % len(args)) elif args[0].type == "bool" and args[1].type == "codeblock": if args[0].val: interpreter.Interpreter().call(args[1]) else: interpreter.Interpreter().call(args[2]) else: raise MethodInputError( "Incorrect type of arguments for function: %s, %s, %s" % (str(args[0].type), str(args[1].type), str(args[2].type))) return tokenz.Token("None", None)
def generate(self): env = environment.Environment(self.source_dir, self.build_dir, self.meson_script_file, options) mlog.initialize(env.get_log_dir()) mlog.log(mlog.bold('The Meson build system')) mlog.log('Version:', coredata.version) mlog.log('Source dir:', mlog.bold(app.source_dir)) mlog.log('Build dir:', mlog.bold(app.build_dir)) if env.is_cross_build(): mlog.log('Build type:', mlog.bold('cross build')) else: mlog.log('Build type:', mlog.bold('native build')) b = build.Build(env) intr = interpreter.Interpreter(b) intr.run() if options.backend == 'ninja': import ninjabackend g = ninjabackend.NinjaBackend(b, intr) elif options.backend == 'vs2010': import vs2010backend g = vs2010backend.Vs2010Backend(b, intr) elif options.backend == 'xcode': import xcodebackend g = xcodebackend.XCodeBackend(b, intr) else: raise RuntimeError('Unknown backend "%s".' % options.backend) g.generate() env.generating_finished() dumpfile = os.path.join(env.get_scratch_dir(), 'build.dat') pickle.dump(b, open(dumpfile, 'wb'))
def execute(self, args): interp_state = interpreter.Interpreter.interp_state if interp_state.module.has_function(self.operands[-1].l_value): # the function is defined in the file being interpreted from state import Frame frame = Frame() for index in range(self.func_param_count): param = self.l_func_params[index] variable = interp_state.lookup_var(self.operands[index]) frame.set_variable(param.addr, variable) func = interp_state.module.get_function(self.operands[-1].l_value) interp_fun = interpreter.Interpreter(module=interp_state.module,\ global_frame=interp_state.global_frame,\ frame=frame) result = interp_fun.run(func) return result else: # the function is not defined in the file being interpreted # XXX currently assuming it is printf or puts str_var = interp_state.lookup_var(self.string_format_ref) assert isinstance(str_var, String) string_format = str_var.value if self.func_name == "printf" or self.func_name == "puts": printf_args = [] for i in range(1, len(self.operands) - 1): var = interp_state.lookup_var(self.operands[i]) printf_args.append(var) interpreter.print_function(string_format, printf_args) else: interpreter.exit_not_implemented(self.func_name) return NoValue()
def eval_macro(product, mappings, interpreter): """ Evaluate a macro the has already been matched and mapped. Parameters: product: The product form of the macro or a python function (mappings, interpreter -> nodes) mappings: The mappings from capture nodes to expressions. interpreter: The interpreter to run the macro in. """ if product[0].node_type != NodeType.FUNC: #A normal macro prod_result = fill_in_form(product, mappings) temp_intp = intp.Interpreter( interpreter.mcs_product) #No side effects if BALK evaluated = temp_intp.interpret_nodes(prod_result)[ 0] #The first should be either BALK or a PAREN if evaluated != normal('BALK'): evaluated = evaluated.children #Unwrap interpreter.set_mcs_product( temp_intp.mcs_product) #Now side effects take place return True, evaluated else: return False, None else: #product is a Python function (mappings, interpreter -> nodes). A built-in macro. return product[0](mappings, interpreter)
def execute(self, args): res = RTResult() interpreter = inter.Interpreter() new_context = Context(self.name, self.context, self.pos_start) new_context.symbol_table = SymbolTable(new_context.parent.symbol_table) if len(args) < len(self.arg_names): return res.failure( RTError( self.pos_start, self.pos_end, f"'{len(self.arg_names) - len(args)}' less args than expected passed into '{self.name}", self.context)) if len(args) > len(self.arg_names): return res.failure( RTError( self.pos_start, self.pos_end, f"'{len(args) - len(self.arg_names)}' more args than expected passed into '{self.name}", self.context)) for i in range(len(args)): arg_name = self.arg_names[i] arg_value = args[i] arg_value.set_context(new_context) new_context.symbol_table.set(arg_name, arg_value) value = res.register(interpreter.visit(self.body_node, new_context)) if res.error: return res return res.success(value)
def setUp(self): self.src = source.StringSource() self.lex = lexer.Lexer(self.src) self.environment = env.Environment() self.parser = pars.Parser(self.lex, self.environment) self.program = interpreter.Interpreter(self.environment, self.parser) self.output = io.StringIO() sys.stdout = self.output
def test_intr_mult_int_prog(): intr = interpreter.Interpreter() tree, _ = intr.parser.parse('int a := 7\nint b := 8\n') intr._interpret_node(tree) assert intr.sym_table[0]['a'].value == 7 assert intr.sym_table[0]['a'].type == 'int' assert intr.sym_table[0]['b'].value == 8 assert intr.sym_table[0]['b'].type == 'int'
def test_intr_assign_links_arr_prog(): intr = interpreter.Interpreter() tree, _ = intr.parser.parse('int a := 1\nint b := [1, a]\n') intr._interpret_node(tree) assert intr.sym_table[0]['a'].value == 1 assert len(intr.sym_table[0]['b'].value) == 2 assert intr.sym_table[0]['b'].value[0].value == 1 assert intr.sym_table[0]['b'].value[1].value == 1
def test_intr_mult_decl_prog(): intr = interpreter.Interpreter() tree, _ = intr.parser.parse('var a, b\n') intr._interpret_node(tree) assert intr.sym_table[0]['a'].value is None assert intr.sym_table[0]['a'].type == 'var' assert intr.sym_table[0]['b'].value is None assert intr.sym_table[0]['b'].type == 'var'
def test_intr_other_var_expr_prog(): intr = interpreter.Interpreter() tree, _ = intr.parser.parse('int a := 7\nint b := a + 4\n') intr._interpret_node(tree) assert intr.sym_table[0]['a'].value == 7 assert intr.sym_table[0]['a'].type == 'int' assert intr.sym_table[0]['b'].value == 11 assert intr.sym_table[0]['b'].type == 'int'
def __init__(self, data, rules, grammar, use_memory=False, memory={}): self.generator = generator.Generator(data, rules) self.interpreter = interpreter.Interpreter(grammar) if use_memory: self.interpreter.use_memory() for k, v in memory.iteritems(): self.interpreter.
def test_function_table(): intr = interpreter.Interpreter() program = """function main(a) do look done """ tree, funcs = intr.parser.parse(program) assert funcs['main'].children['param'].value == 'a'
def run(source): lex = lexer.Lexer(source) tokens = lex.scan_tokens() parser = mapleparser.Parser(tokens) statements = parser.parse() interpret = interpreter.Interpreter() result = interpret.interpret(statements)
def main(): src = source.StreamSource() fo = open("ThirdExample", "r", encoding='utf-8', newline='\n') environment = env.Environment() src.set_data(fo) lex = lexer.Lexer(src) parser = pars.Parser(lex, environment) inter = interpreter.Interpreter(environment, parser) inter.interpret()
def test_function_interpretation(): intr = interpreter.Interpreter() program = """function main(a) do int a := 2 done """ intr.interpret(program) assert intr.funcs['main'].children['param'].value == 'a' assert intr.sym_table[0]['a'].value == 2
def test_intr_assign_array_prog(): intr = interpreter.Interpreter() tree, _ = intr.parser.parse('int a := [1, 2]\n') intr._interpret_node(tree) assert len(intr.sym_table[0]['a'].value) == 2 assert intr.sym_table[0]['a'].value[0].value == 1 assert intr.sym_table[0]['a'].value[0].type == 'int' assert intr.sym_table[0]['a'].value[1].value == 2 assert intr.sym_table[0]['a'].value[1].type == 'int' assert intr.sym_table[0]['a'].type == 'int'
def _test_easy_expr(self): expressions = { '2+2': 4, '1235 + 123': 1235 + 123, '44239 - 523': 44239 - 523 } for exp, val in expressions.items(): intrepreter = i.Interpreter(exp) self.assertEqual(intrepreter.eval(), val)
def test_cast(): intr = interpreter.Interpreter() program = """ function main(argv) do cell a := true done """ intr.interpret(program) assert len(intr.errors) == 1 assert intr.errors[0].split()[0] == 'CastError:'
def test_fibonacci_five(): intr = interpreter.Interpreter() main = """ function main(argv) do int num := 5 fib(num) done """ intr.interpret(fibonacci + main) assert intr.sym_table[0]['num'].value == 5
def test_undecl(): intr = interpreter.Interpreter() program = """ function main(argv) do a := 1 done """ intr.interpret(program) assert len(intr.errors) == 1 assert intr.errors[0].split()[0] == 'UndeclError:'
def generate(self): env = environment.Environment(self.source_dir, self.build_dir, self.meson_script_file, self.options) mlog.initialize(env.get_log_dir()) mlog.debug('Build started at', datetime.datetime.now().isoformat()) mlog.debug('Python binary:', sys.executable) mlog.debug('Python system:', platform.system()) mlog.log(mlog.bold('The Meson build system')) mlog.log('Version:', coredata.version) mlog.log('Source dir:', mlog.bold(self.source_dir)) mlog.log('Build dir:', mlog.bold(self.build_dir)) if env.is_cross_build(): mlog.log('Build type:', mlog.bold('cross build')) else: mlog.log('Build type:', mlog.bold('native build')) b = build.Build(env) if self.options.backend == 'ninja': import ninjabackend g = ninjabackend.NinjaBackend(b) elif self.options.backend == 'vs2010': import vs2010backend g = vs2010backend.Vs2010Backend(b) elif self.options.backend == 'xcode': import xcodebackend g = xcodebackend.XCodeBackend(b) else: raise RuntimeError('Unknown backend "%s".' % self.options.backend) intr = interpreter.Interpreter(b, g) if env.is_cross_build(): mlog.log( 'Host machine cpu family:', mlog.bold(intr.builtin['host_machine'].cpu_family_method([], {}))) mlog.log( 'Host machine cpu:', mlog.bold(intr.builtin['host_machine'].cpu_method([], {}))) mlog.log( 'Target machine cpu family:', mlog.bold(intr.builtin['target_machine'].cpu_family_method( [], {}))) mlog.log( 'Target machine cpu:', mlog.bold(intr.builtin['target_machine'].cpu_method([], {}))) mlog.log( 'Build machine cpu family:', mlog.bold(intr.builtin['build_machine'].cpu_family_method([], {}))) mlog.log('Build machine cpu:', mlog.bold(intr.builtin['build_machine'].cpu_method([], {}))) intr.run() g.generate(intr) env.generating_finished() dumpfile = os.path.join(env.get_scratch_dir(), 'build.dat') pickle.dump(b, open(dumpfile, 'wb'))
def test_simple_if(): intr = interpreter.Interpreter() program = """int a if 2 < 3 do a := 1 done """ tree, _ = intr.parser.parse(program) intr._interpret_node(tree) assert intr.sym_table[0]['a'].value == 1 assert intr.sym_table[0]['a'].type == 'int'
def test_fibonacci_three(): intr = interpreter.Interpreter() main = """ function main(argv) do int num := 3 fib(num) int res := num(1) done """ intr.interpret(fibonacci+main) assert intr.sym_table[0]['res'].value == 2
def __init__(self, debug=False): """ :param bool debug: """ self.debug = debug self.state = cparser.State() self.state.autoSetupSystemMacros() self.state.autoSetupGlobalIncludeWrappers() self.state.readLocalInclude = self._read_local_include_handler self.interp = interpreter.Interpreter() self.interp.register(self.state)
def _test_easy_term(self): expressions = { '-2+-2': -4, '2*2': 4, '123 * (1235 + 123)': 123 * (1235 + 123), '44239 / 523': 44239 / 523 } for exp, val in expressions.items(): intrepreter = i.Interpreter(exp) self.assertEqual(intrepreter.eval(), val)