Ejemplo n.º 1
0
    def test_should_ignore_invalid_ram_value(self):
        interpreter = Interpreter(['', None, 'Some non Int', '1000'])

        self.assertEqual('000', interpreter.get_ram_value(0))
        self.assertEqual('000', interpreter.get_ram_value(1))
        self.assertEqual('000', interpreter.get_ram_value(2))
        self.assertEqual('000', interpreter.get_ram_value(3))
Ejemplo n.º 2
0
 def parse(self):
     instructions = self._program()
     # do not print any output if error occurs
     if self.total_error_flag == 0:
         if self.print_symbol_table == 0:
             self.observer.print_output()
         elif self.print_symbol_table == 1:
             self.visitor.visitScope(self.program_scope)
             self.visitor.end()
         elif self.print_symbol_table == 2:
             currinstruction = instructions
             self.visitor.start()
             # while(currinstruction is not None):
             currinstruction.visit(self.visitor)
             # currinstruction = currinstruction._next
         elif self.print_symbol_table == 3:
             environment = self.program_scope.make_environment()
             stack = []
             currinstruction = instructions
             # while curr is not None:
             #    self.interpret(curr, environment, stack)
             #    curr = curr._next
             # v = InterpreterVisitor(environment)
             # v.start()
             # currinstruction.int_visit(v)
             v = Interpreter(currinstruction, environment)
             v.start()
Ejemplo n.º 3
0
    def test_0ds_should_not_go_to_location_d_when_s_is_zero(self):
        interpreter = Interpreter(['200', '214', '010', '201', '100'])

        instruction_count = interpreter.execute()

        self.assertEqual('001', interpreter.get_register_value(0))
        self.assertEqual(5, instruction_count)
Ejemplo n.º 4
0
    def test_should_set_ram_given_value(self):
        interpreter = Interpreter(['100'])

        self.assertEqual('100', interpreter.get_ram_value(0))

        for index in range(1, 1000) :
            self.assertEqual('000', interpreter.get_ram_value(index))
Ejemplo n.º 5
0
 def install_builtins(self):
     """ populate with the builtin functions, while adding our own flavors"""
     Interpreter.install_builtins(self)
     
     #input statements, length constructs
     tamil_equiv = {"சரம்_இடமாற்று":"replace", "சரம்_கண்டுபிடி":"find","நீளம்":"len",
                    "சரம்_உள்ளீடு":"raw_input", "உள்ளீடு" : "input" }
     #list operators        
     tamil_equiv.update( {"பட்டியல்":"list","பின்இணை":"append","தலைகீழ்":"reverse",
                          "வரிசைப்படுத்து":"sort","நீட்டிக்க":"extend","நுழைக்க":"insert","குறியீட்டெண்":"index",
                          "வெளியேஎடு":"pop","பொருந்தியஎண்":"count", "எடு":"__getitem__"} )
     
     #file operators
     tamil_equiv.update({"கோப்பை_திற":"file_open", "கோப்பை_மூடு":"file_close","கோப்பை_படி":"file_read",
                         "கோப்பை_எழுது":"file_write","கோப்பை_எழுது_வரிகள்":"file_writelines","கோப்பை_படி_வரிகள்":"file_readlines"})
     
     for k,v in list(tamil_equiv.items()):
         self.builtin_map[k]=self.builtin_map[v];
     
     # translations for turtle module
     turtle_map = { "முன்னாடி":"forward", "பின்னாடி" :"backward",
                    "வலது":"lt", "இடது":"rt",
                    "எழுதுகோல்மேலே":"penup",  "எழுதுகோல்கிழே":"pendown"}
     for k,v in list(turtle_map.items()):
         vv = "turtle_"+v;
         self.builtin_map[k] = self.builtin_map[vv]
     
     return
Ejemplo n.º 6
0
 def test_OP_Cxkk(self):  # RND Vx, byte: Set Vx = random byte AND kk
     patch('Interpreter.getrandbits', lambda _: 0b10101010).start()
     path = os.path.join(os.getcwd(), "test_roms", "RND_Vx_byte.ch8")
     interpreter = Interpreter(path, False)
     interpreter.tick()
     self.assertEqual(interpreter.registers[1], 0b10101010 & 0b1100)
     patch.stopall()
Ejemplo n.º 7
0
 def __init__(self, **kwargs ):
     """ create a Ezhil Interpeter and initialize runtime builtins etc.. in a RAII fashion,
         and associates a Ezhil parser object with this class
     """
     Interpreter.__init__(self,**kwargs)
     Interpreter.change_parser(self,EzhilParser.factory)
     return
Ejemplo n.º 8
0
 def test_OP_8xyE(self):  # SHL Vx {, Vy}: Set Vx = Vx SHL 1
     path = os.path.join(os.getcwd(), "test_roms", "SHL_VX.ch8")
     interpreter = Interpreter(path, False)
     interpreter.registers[1] = 129
     interpreter.tick()
     self.assertEqual(interpreter.registers[1], 2)  # Should wrap
     self.assertEqual(interpreter.registers[0xF], 1)
    def processFile(self):
        interpreter = Interpreter()

        # return all the documents present in the file
        output = self.path + '.bin'
        if isfile(output):
            print('loading tokens')
            self.index = pickle.load(open(output, 'rb'))
            self.indexer = Indexer(self.tokenizer, index=self.index)
        else:
            self.indexer = Indexer(self.tokenizer)
            file = open(self.path, 'r', encoding='utf-8', errors='ignore')
            maximum = os.stat(self.path).st_size
            # initialize the variables
            i = 0
            progress = 0
            document = []
            for line in file:
                progress += len(line)
                if line == '\n':
                    interpreter.process(self.indexer, document)
                    document = []
                else:
                    document += [line]
                i += 1
                if i >= 5000:
                    i = 0
                    log(progress, maximum)

            file.close()
            self.index = self.indexer.index
            print('\nsaving tokens')
            pickle.dump(self.index, open(output, 'wb'))
Ejemplo n.º 10
0
 def __init__(self):
     self.data = Interpreter()
     self.difficulties = ['easy', 'normal', 'hard']
     self.difficultySelected = self.data.getParameter('difficulty')
     self.musicValue = self.data.getParameter('music')
     self.sfxValue = self.data.getParameter('sfx')
     self.buttons = []
     self.menuButtons = []
     self.bigButtons = []
     self.sliders = []
     self.texts = {}
     self.images = []
     self.logo = pygame.image.load('../Assets/menuAssets/logo.png')
     self.logoPos = [5, 0]
     self.animBool = True
     # self.sfxValue = self.data.getParameter('sfx')
     # self.musicValue = self.data.getParameter('music')
     self.loadImages()
     self.mainMenu()
     self.game = game(self)
     self.textGui = textGui()
     self.menuPage = {
         'new': False,
         'load': False,
         'options': False,
         'credits': False,
         'quit': False
     }
     self.screen = pygame.display.set_mode((720, 480))
     self.backgroundMenu = False
     self.sound = Sound()
     self.sound.playMusic(0, 2)
Ejemplo n.º 11
0
 def __init__(self, height, width):
     self.camera = pygame.Rect(0, 0, width, height)
     self.width = width
     self.height = height
     self.data = Interpreter()
     self.screenWidth = self.data.getParameter('screenSize')[0]
     self.screenHeight = self.data.getParameter('screenSize')[1]
Ejemplo n.º 12
0
def run_ide():
    print(": Welcome to Dymond V0.0.0!")
    print(
        ": Play around a little in this nice IDE type simple statements in and we will process them :)"
    )
    print(": Type exit() to exit")
    user_in = ""
    total_user_in = ""

    while user_in != "exit()":
        user_in = input(">>> ")

        if (user_in == "exit()"):
            break

        try:
            test = total_user_in + user_in

            lexer = Lexer(test)
            se_parser = Parser(lexer, "ide")
            semantic_analyzer = SemanticAnalyzer(se_parser)

            semantic_analyzer.analyze()
            lexer = Lexer(test)
            in_parser = Parser(lexer, "ide")
            semantic_analyzer.current_scope.reset_multi_scope_vars()
            interpreter = Interpreter(in_parser,
                                      semantic_analyzer.current_scope)
            interpreter.interpret()

            if "print(" not in user_in and "input(" not in user_in:
                total_user_in += "\n" + user_in
        except Exception as ex:
            print(ex)
Ejemplo n.º 13
0
def main():
    memory = defaultdict(int)
    states = ['PREFIX', 'INFIX', 'POSTFIX']
    state = states[1]
    while True:
        try:
            text = input(state + ' --> ')
        except EOFError:
            break

        if not text:
            continue

        command = text.strip().upper()

        if command == 'EXIT':
            break

        if command in states:
            state = command
            continue

        lexer = Lexer(text)
        interpreter = Interpreter(lexer, state, memory)
        result = interpreter.evaluate()
        print(result)
Ejemplo n.º 14
0
    def assign(self, interpreter_flag=False):
        Interpreter.interpreter_flag = interpreter_flag

        sc = self.scanner
        lexeme_identifier = sc.next_lexeme()

        if Interpreter.interpreter_flag:
            # semantic
            if not self.semantic_tree.is_describe_var_early(sc.get_pointer_line(), sc.get_pointer_position(), sc.lexeme):
                raise SemanticExceptionUndescribeVar(sc.get_pointer_line(), sc.get_pointer_position(), sc.lexeme)
            # semantic

        if Interpreter.interpreter_flag:
            # Interpreter
            node = self.semantic_tree.get_variable_node(sc.lexeme)
            # Interpreter

        sc.next_lexeme()  # =

        value_obj = ValueObj()
        self.expression(value_obj, interpreter_flag=Interpreter.interpreter_flag)

        if Interpreter.interpreter_flag:
            # Interpreter
            Interpreter.to_type(value_obj, node.type_data)
            node.value = value_obj.value
Ejemplo n.º 15
0
 def __init__(self):
     self.musics = [
         pygame.mixer.Sound('../Assets/Sounds/dungeon.ogg'),
         pygame.mixer.Sound('../Assets/Sounds/dungeon2.ogg'),
         pygame.mixer.Sound('../Assets/Sounds/menu.ogg')
     ]
     self.bossMusics = [
         pygame.mixer.Sound('../Assets/Sounds/bossMain.ogg'),
         pygame.mixer.Sound('../Assets/Sounds/bossFinal.ogg')
     ]
     self.effects = [
         pygame.mixer.Sound('../Assets/Sounds/click.ogg'),
         pygame.mixer.Sound('../Assets/Sounds/magic.ogg'),
         pygame.mixer.Sound('../Assets/Sounds/youDied.ogg'),
         pygame.mixer.Sound('../Assets/Sounds/spike.ogg'),
         pygame.mixer.Sound('../Assets/Sounds/openingChest.ogg'),
         pygame.mixer.Sound('../Assets/Sounds/death.ogg')
     ]
     self.musicChannel = pygame.mixer.Channel(0)
     self.sfxChannel = pygame.mixer.Channel(1)
     self.sfx2Channel = pygame.mixer.Channel(2)
     self.musicChannel.set_volume(Interpreter().getParameter('music'))
     self.sfxChannel.set_volume(Interpreter().getParameter('sfx'))
     self.sfx2Channel.set_volume(Interpreter().getParameter('sfx'))
     self.lastMusic = self.musics[0]
     self.equalization()
Ejemplo n.º 16
0
    def test_9sa_set_the_value_in_ram(self):
        interpreter = Interpreter(['209', '215', '901', '100'])

        instruction_count = interpreter.execute()

        self.assertEqual('009', interpreter.get_ram_value(5))
        self.assertEqual(4, instruction_count)
Ejemplo n.º 17
0
 def __init__(self, lexer, debug=False):
     """ create a Ezhil Interpeter and initialize runtime builtins etc.. in a RAII fashion,
         and associates a Ezhil parser object with this class
     """
     Interpreter.__init__(self, lexer, debug)
     Interpreter.change_parser(self, EzhilParser.factory)
     return
Ejemplo n.º 18
0
 def test_OP_2nnn(self):  # CALL addr: Call subroutine at nnn
     path = os.path.join(os.getcwd(), "test_roms", "call_subroutine.ch8")
     interpreter = Interpreter(path, False)
     interpreter.tick()
     correct = [0x202, 0x204] + [0x200] * 14
     self.assertEqual(interpreter.stack, correct)
     self.assertEqual(interpreter.stack_pointer, 1)
Ejemplo n.º 19
0
 def __init__(self):
     self.hadError = False
     self.tokens = []  # saved tokens from previous uncompleted lines
     self.interp = Interpreter(
     )  # for retain inner statements when runPrompt()
     self.resolver = Resolver()
     self.compiler = Compiler()
     self.vm = StackVM()
Ejemplo n.º 20
0
    def test_5ds_should_set_register_d_to_the_value_of_register_s(self):
        interpreter = Interpreter(['209', '510', '100'])

        instruction_count = interpreter.execute()

        self.assertEqual('009', interpreter.get_register_value(0))
        self.assertEqual('009', interpreter.get_register_value(1))
        self.assertEqual(3, instruction_count)
Ejemplo n.º 21
0
def testInterpreter3():

 te.checkComplainAndAdjustExpected( 0)

 i= Interpreter()
 i.evalToken( s( '(')) # baustelle: testbarkeit der repl
 
 te.checkComplainAndAdjustExpected( 0)
Ejemplo n.º 22
0
 def test_OP_8xy7(
         self):  # SUBN Vx, Vy: Set Vx = Vy - Vx, set VF = NOT borrow
     path = os.path.join(os.getcwd(), "test_roms", "SHR_VX.ch8")
     interpreter = Interpreter(path, False)
     interpreter.registers[1] = 0b101
     interpreter.tick()
     self.assertEqual(interpreter.registers[1], 0b10)  # Should wrap
     self.assertEqual(interpreter.registers[0xF], 1)
Ejemplo n.º 23
0
 def test_OP_00E0(self):  # CLS: Clear the Display
     path = os.path.join(os.getcwd(), "test_roms", "clear_display.ch8")
     interpreter = Interpreter(path, False)
     interpreter.display = [1] * len(interpreter.display)
     interpreter.tick()
     self.assertTrue(
         not any(interpreter.display),
         F"Expected cleared display. Got {interpreter.display}")
Ejemplo n.º 24
0
    def test_8da_should_set_register_d_to_the_value_in_ram_whose_address_is_in_register_a(self):
        interpreter = Interpreter(['203', '810', '100', '999'])

        instruction_count = interpreter.execute()

        self.assertEqual('003', interpreter.get_register_value(0))
        self.assertEqual('999', interpreter.get_register_value(1))
        self.assertEqual(3, instruction_count)
Ejemplo n.º 25
0
    def test_7ds_should_multiply_register_d_to_the_value_of_register_s(self):
        interpreter = Interpreter(['209', '212', '710', '100'])

        instruction_count = interpreter.execute()

        self.assertEqual('009', interpreter.get_register_value(0))
        self.assertEqual('018', interpreter.get_register_value(1))
        self.assertEqual(4, instruction_count)
Ejemplo n.º 26
0
def main():

    with open("source.dd") as f:
        code = ''.join(f.readlines())
    #print(code)
    lexer = Lexer(code)
    parser = Parser(lexer)
    interpreter = Interpreter(parser)
    result = interpreter.interpret()
Ejemplo n.º 27
0
def find_accumulator_before_loop(instructions):
    interpreter = Interpreter()
    outputs = set()
    accumulator = 0
    for output in interpreter.launch_process(instructions):
        if output[1] in outputs:
            return accumulator
        outputs.add(output[1])
        accumulator = output[0]
Ejemplo n.º 28
0
 def __init__(self, master=None):
     super().__init__(master)
     self.master = master
     self.master.minsize(600, 400)
     self.master.title("Brainfuck interpreter by Cezary Kania v 0.1")
     self.interpreter = Interpreter(self)
     self.init_menu()
     self.init_body()
     self.pack()
Ejemplo n.º 29
0
 def update(self):
     if not self.musicChannel.get_busy():
         self.musicChannel.queue(self.lastMusic)
     a = Interpreter().getParameter('music')
     b = Interpreter().getParameter('sfx')
     self.musicChannel.queue(self.lastMusic)
     self.musicChannel.set_volume(a)
     self.sfxChannel.set_volume(b)
     self.sfx2Channel.set_volume(b)
Ejemplo n.º 30
0
def main(args):
	input = FileStream(args[1])
	lexer = MiniPLexer(input)
	stream = CommonTokenStream(lexer)
	parser = MiniPParser(stream)
	tree = parser.program()

	interpreter = Interpreter()
	interpreter.visit(tree)
Ejemplo n.º 31
0
def makeOverridenInterpreter():

 ios= InterpreterOverridings()
 i= Interpreter()

 i.readTokenRawInput= ios.readTokenRawInput
 i.essentials_macro_function.ess_print= ios.ess_ess_print # 8c231655685648cc99e5b0bf3b0b8687
 i.s_print= ios.s_print

 return ( ios, i)
Ejemplo n.º 32
0
 def test_OP_Fx29(
         self):  # LD F, Vx: Set I = location of sprite for digit Vx
     path = os.path.join(os.getcwd(), "test_roms", "LD_F_Vx.ch8")
     BYTES_PER_DIGIT = 5
     interpreter = Interpreter(path, False)
     interpreter.registers[1] = 3
     interpreter.tick()
     self.assertEqual(
         interpreter.index_register, interpreter.FONT_SET_START_ADDRESS +
         (interpreter.registers[1] * BYTES_PER_DIGIT))
Ejemplo n.º 33
0
class Shell:
    def __init__(self):
        self._interpreter = Interpreter()
        self._PROMPT = ">>"
        self._run()

    def _run(self):
        while True:
            line = input(self._PROMPT + " ")
            self._interpreter.interpret(line)
Ejemplo n.º 34
0
class InterpreterVisitor:

    def __init__(self, environment):
        self.environment = environment
        self.interpreter = Interpreter()

    def visitNode(self, ast):
        self.interpreter.interpret(ast, self.environment)
        if ast._next is not None:
            ast._next.int_visit(self)
Ejemplo n.º 35
0
	def parseinfo(self,e):
		keycode = e.GetKeyCode()
		if keycode == wx.WXK_RETURN or keycode == wx.WXK_NUMPAD_ENTER or keycode == wx.WXK_TAB:
			if self.editname.GetValue() == "exit" or self.editname.GetValue() == "exit;":
				exit(0)
			else:
				z = Interpreter()
				#thread.start_new_thread(z.parse(self.editname.GetValue()))
				z.parse(self.editname.GetValue())
			e.EventObject.Navigate()
		e.Skip()
Ejemplo n.º 36
0
def run_file(file_name):
    lexer = Lexer(open(file_name, "r").read())
    se_parser = Parser(lexer, "input")
    semantic_analyzer = SemanticAnalyzer(se_parser)
    semantic_analyzer.analyze()

    lexer = Lexer(open(file_name, "r").read())
    in_parser = Parser(lexer, "input")
    semantic_analyzer.current_scope.reset_multi_scope_vars()
    interpreter = Interpreter(in_parser, semantic_analyzer.current_scope)
    result = interpreter.interpret()
Ejemplo n.º 37
0
def entry_point(argv):
	filename = argv[1]
	args = []
	args.append( filename )
	for i in xrange(len(argv)):
		if i > 1:
			args.append( argv[i] )

	interp = Interpreter( filename=filename, argv=args )
	rv = interp.run()

	return rv
Ejemplo n.º 38
0
 def test_OP_Fx65(
     self
 ):  # LD Vx, [I]: Read registers V0 through Vx from memory starting at location I
     path = os.path.join(os.getcwd(), "test_roms", "LD_Vx_I.ch8")
     interpreter = Interpreter(path, False)
     interpreter.index_register = interpreter.MEMORY_START_ADDRESS
     interpreter.tick()
     correct = [
         0xFC, 0x65, 0x01, 0x23, 0x45, 0x67, 0x89, 0x10, 0x11, 0x12, 0x13,
         0x14, 0x15, 0x0, 0x0, 0x0
     ]
     self.assertEqual(interpreter.registers, correct)
Ejemplo n.º 39
0
    def install_builtins(self):
        """ populate with the builtin functions, while adding our own flavors"""
        Interpreter.install_builtins(self)

        #input statements, length constructs
        tamil_equiv = {
            "சரம்_இடமாற்று": "replace",
            "சரம்_கண்டுபிடி": "find",
            "நீளம்": "len",
            "சரம்_உள்ளீடு": "raw_input",
            "உள்ளீடு": "input"
        }
        #list operators
        tamil_equiv.update({
            "பட்டியல்": "list",
            "பின்இணை": "append",
            "தலைகீழ்": "reverse",
            "வரிசைப்படுத்து": "sort",
            "நீட்டிக்க": "extend",
            "நுழைக்க": "insert",
            "குறியீட்டெண்": "index",
            "வெளியேஎடு": "pop",
            "பொருந்தியஎண்": "count",
            "எடு": "__getitem__"
        })

        #file operators
        tamil_equiv.update({
            "கோப்பை_திற": "file_open",
            "கோப்பை_மூடு": "file_close",
            "கோப்பை_படி": "file_read",
            "கோப்பை_எழுது": "file_write",
            "கோப்பை_எழுது_வரிகள்": "file_writelines",
            "கோப்பை_படி_வரிகள்": "file_readlines"
        })

        for k, v in list(tamil_equiv.items()):
            self.builtin_map[k] = self.builtin_map[v]

        # translations for turtle module
        turtle_map = {
            "முன்னாடி": "forward",
            "பின்னாடி": "backward",
            "வலது": "lt",
            "இடது": "rt",
            "எழுதுகோல்மேலே": "penup",
            "எழுதுகோல்கிழே": "pendown"
        }
        for k, v in list(turtle_map.items()):
            vv = "turtle_" + v
            self.builtin_map[k] = self.builtin_map[vv]

        return
Ejemplo n.º 40
0
def start_JVM(cmd):
    class_path = Classpath.parse(cmd.XjreOption, cmd.cpOption)
    print("classpath:{0} class:{1} args:{2}".format(class_path, cmd.class_name, cmd.args))

    class_loader = ClassLoader(class_path, cmd.verbose_class_flag)

    class_name = cmd.class_name.replace(".", "/")
    main_class = class_loader.load_class(class_name)
    main_method = main_class.get_main_method()

    if main_method:
        Interpreter.interpret(main_method, cmd.verbose_inst_flag)
    else:
        print("Main method not found in class {0}".format(cmd.class_name))
Ejemplo n.º 41
0
    def a3(self, value_obj, interpreter_flag=False):
        Interpreter.interpreter_flag = interpreter_flag

        self.a4(value_obj, interpreter_flag=Interpreter.interpreter_flag)
        sc = self.scanner
        old_pointer = sc.get_pointer()
        lexeme_lege = sc.next_lexeme()
        while lexeme_lege == lId.TLess or lexeme_lege == lId.TGreater or \
                        lexeme_lege == lId.TLessEq or lexeme_lege == lId.TGreaterEq:
            _value_obj = ValueObj()
            self.a4(_value_obj, interpreter_flag=Interpreter.interpreter_flag)

            if Interpreter.interpreter_flag:
                # interpreter
                if lexeme_lege == lId.TLess:
                    Interpreter.verify_less(value_obj, _value_obj)
                elif lexeme_lege == lId.TLessEq:
                    Interpreter.verify_less_eq(value_obj, _value_obj)
                elif lexeme_lege == lId.TGreater:
                    Interpreter.verify_greater(value_obj, _value_obj)
                else:
                    Interpreter.verify_greater_eq(value_obj, _value_obj)
                # interpreter

            old_pointer = sc.get_pointer()
            lexeme_lege = sc.next_lexeme()
        sc.set_pointer(old_pointer)
Ejemplo n.º 42
0
def main():
    file = open("examples/example3.txt", 'r').read()

    lexer = Lexer(file)
    # lexer.DEBUG = True
    lexer.run()

    parser = Parser(lexer.tokens)
    # parser.DEBUG = True
    parser.run()

    interpreter = Interpreter(parser.commands)
    # interpreter.DEBUG = True
    interpreter.run()
Ejemplo n.º 43
0
def create_dev(ip):
    dev = Router(ip, username, password, cmd_file, rdeb)
    if dev.err:
        print "Skipping device %s\n" %ip
        return
    #all input values are correct
    #create Interpreter
    i = Interpreter(dev, ideb, ideb)
    i.start()
    if ideb:
        #print last debug info
        print "Oper_st: %s" %i.oper_st
        print "Data_st: %s" %i.data_st
        print "Env: %s" %i.env
Ejemplo n.º 44
0
def run(fname, text):
	lexer = Lexer(fname, text)
	tokens, error = lexer.genTok()
	if error: return None, error
	
	parser = Parser(tokens)
	bTree = parser.parse()
	if bTree.error: return None, bTree.error

	interpreter = Interpreter()
	context = Context('<program>')
	context.symbTable = GlobalSymTable
	result = interpreter.visit(bTree.node, context)

	return result.value, result.error
Ejemplo n.º 45
0
def interpret_file(filename):
    parser = BoolangParser()
    interpreter = Interpreter()

    text = ''
    try:
        with open(filename) as f:
            # read entire file
            text = f.read()
    except FileNotFoundError:
        print('Error: file not found.')
        sys.exit(1)

    program = parser.parse(text)
    interpreter.interpret(program)
Ejemplo n.º 46
0
 def test_one(self,benchmark):
     
     n=1
     while(n<100):
         i = Interpreter()
         f = open('input.bas', 'r')
         for line in f:   
             line = line.strip()
             split_line = line.split(" ")
             line_number = int(split_line[0])
             i.add_line(line_number, split_line[1:])
         i.run()
         f.close()
         n=n+1
     benchmark(time.sleep, 0.000001)
Ejemplo n.º 47
0
def runtest( filename ):
	print "File: %s -> " % os.path.basename(filename),

	# get program contents
	f = open_file_as_stream(filename)
	program = f.readall()
	f.close()
	
	# expect?
	expect_rv = 0
	expect_stack = []
	expect_space = []
	expect_stdout = ''
	
	# look for special tags in out
	for ln in program.split('\n'):
		if ln.startswith( 'Return:' ):
			expect_rv = int(ln.split(' ')[-1])
		elif ln.startswith( 'Stack:' ):
			expect_stack = [Cell(int(v)) for v in ln.split(' ')[1:]]
		elif ln.startswith( 'Space:' ):
			parts = ln.split(' ')[1:]
			expect_space.append( (int(parts[0]),int(parts[1]),Cell(int(parts[2]))) )
		elif ln.startswith( 'Stdout:' ):
			expect_stdout = ln[7:].strip()

	# run the interpreter on the file
	cap = py.io.StdCaptureFD()
	i = Interpreter( filename=filename, argv=['testrunner'] )
	rv = i.run()
	fds = cap.done()
	actual_stdout = fds[0].read().strip()
	
	# check results
	#print "E: %s" % str(expect_stack)
	#print "A: %s" % str(i.stacks.head().inner)
	try:
		assert rv == expect_rv
		for v in expect_stack:
			assert 0 == v.cmp_( i.stacks.pop() )
		for x,y,val in expect_space:
			assert 0 == val.cmp_( i.space.get( x, y ) )
		assert expect_stdout == actual_stdout
	except:
		print ""
		print "RV: %s" % rv
		print str(i.stacks)
		raise
Ejemplo n.º 48
0
def main():
    # Zpracovani argumentu
    args = handleArgs()
    if args is None:
        if '--help' not in sys.argv and '-h' not in sys.argv:
            sys.exit(ErrCodes.PARAM)
        else:
            sys.exit(ErrCodes.OK)

    try:
        file = open(args.source_file, "r")
    except:  # Chyba vstupniho souboru
        sys.exit(ErrCodes.INPUT_FILE)

    try:
        tree = ET.parse(file)
    except ET.ParseError:  # Chybny format xml
        sys.exit(ErrCodes.XML_FORMAT)

    interpreter = Interpreter(tree)  # Vytvoreni objektu interpretu

    # Interpretace
    try:
        interpreter.run_code()
    except MyException as e:  #chyba interpretace
        #print("Exiting with code: %d" % e.arg1)
        sys.exit(e.arg1)

    # rozsireni STATI
    if args.stats_file != None:
        try:
            out_file = open(args.stats_file, 'w')
        except:
            sys.exit(ErrCodes.OUTPUT)

        try:
            optlist, a = getopt.getopt(sys.argv[1:], '',
                                       ['source=', 'stats=', 'insts', 'vars'])
        except getopt.GetoptError:
            pass

        for opt in optlist:
            if opt[0] == '--insts':
                out_file.write(str(interpreter.ins_count) + '\n')
            if opt[0] == '--vars':
                out_file.write(str(interpreter.get_vars()) + '\n')

    exit(ErrCodes.OK)
Ejemplo n.º 49
0
def run (file,text):
	lexer = Lexer(file,text)
	tokens,error = lexer.make_tokens()
	if error: return None,error
	
	#abstract syntax tree
	parser = Parser(tokens)
	abstract_st = parser.parse()
	if abstract_st.error: return None,abstract_st.error

	#run program
	interpreter  = Interpreter()
	context = Context('<basic context>')
	context.symbol_table=global_symbol_table
	result = interpreter.visit(abstract_st.node,context)
	return result.value,result.error
Ejemplo n.º 50
0
class Vector:
    def __init__(self, debug = False):
        self.debug = debug
        self.parser = Parser()
        self.interpreter = Interpreter()

    def eval(self, s):
        if self.debug:
            print "Input: " + s
        lexemes = Lexer.lex(s)
        if self.debug:
            print "Lexemes: " + str(lexemes)
        ast = self.parser.parse(lexemes)
        if self.debug:
            print "AST:"
            self.printAST(ast, 0)
        result = self.interpreter.eval(ast)
        if self.debug:
            print "Result: ",
        print str(result)

    def printAST(self, ast, indent):
        if ast == False:
            print "| " * indent + "ERROR"
            return
        print "| " * indent + str(ast[1])
        if len(ast) < 3:
            return
        for c in ast[2]:
            self.printAST(c, indent + 1)
Ejemplo n.º 51
0
    def __init__(self, **kwargs):
        super(MainLayout, self).__init__(**kwargs)
        self.Interpreter = Interpreter()
        self.command_stack = []

        self.cols = 2
        self.orientation = "vertical"
        self.padding = 10

        self.workspace = Workspace()
        self.command_panel = CommandPanel(self.workspace)
        self.output = Output()

        self.spn_menu = Spinner(text='Menu', values=('New', 'Save', 'RUN', 'Exit'), size_hint =(None, None), size=(200, 44), pos_hint={'x': .1, 'y': .9})
        self.spn_menu.bind(text=self.menu_option_selected_event)
        
        self.command_panel.draw(self.spn_menu)
        self.command_panel.add_expression_btn('LET')
        self.command_panel.add_expression_btn('PRINT')
        self.command_panel.add_expression_btn('GOTO')
        self.command_panel.add_expression_btn('IF')
        self.command_panel.add_expression_btn('GOSUB')
        self.command_panel.add_expression_btn('RETURN')
        self.command_panel.add_expression_btn('END')
        self.add_widget(self.command_panel)

        self.orientation = "horizontal"
        self.workspace.draw()
        self.add_widget(self.workspace)
        
        self.output.draw()
        self.add_widget(self.output)
Ejemplo n.º 52
0
class YazInterpreter:
    def __init__(self):
        self.interpreter = Interpreter()
        
    def menu(self):
        print("Welcome to the YazInterpreter!")
        print("You may interpret a YazLang program and output")
        print("the results to a .txt file or enter console YazInteractions")
        print("mode to run single commands of YazLang.")
        print()

        while(True):
          self.eleccion = input("\033[;37m" + "(C)onsole YazInteractions, (I)nterpret .yzy program, (Q)uit? ")
          if(self.eleccion == "I" or self.eleccion == "i"):
            self.archivos()
          elif(self.eleccion == 'C' or self.eleccion == 'c'):
            print("YazInteractions session. Type END to exit.")
            self.CLI()
          elif(self.eleccion == 'Q' or self.eleccion == 'q'):
            break

    def CLI(self):
        while True:
            self.string = input(">")
            self.a = self.interpreter.evaluateString(self.string)
            if(self.a == False):
                break
            print(self.a)
    def archivos(self):
      archivo = Archivos()
      archivo.menu()
      
Ejemplo n.º 53
0
    def install_builtins(self):
        """ populate with the builtin functions, while adding our own flavors"""
        Interpreter.install_builtins(self)
        
        #input statements, length constructs
        tamil_equiv = {u"சரம்_இடமாற்று":u"replace", u"சரம்_கண்டுபிடி":u"find",u"நீளம்":u"len",
                       u"சரம்_உள்ளீடு":u"raw_input", u"உள்ளீடு" : u"input" }

        # printf - as per survey request
        tamil_equiv.update( { u"அச்சிடு":u"printf" } )        
        
        #list operators
        tamil_equiv.update( {u"பட்டியல்":u"list",u"பின்இணை":u"append",u"தலைகீழ்":u"reverse",
                             u"வரிசைப்படுத்து":u"sort",u"நீட்டிக்க":u"extend",u"நுழைக்க":u"insert",u"குறியீட்டெண்":u"index",
                             u"வெளியேஎடு":u"pop_list",u"பொருந்தியஎண்":u"count"} )
        
        #generic get/set ops for list/dict
        tamil_equiv.update( { u"எடு":u"__getitem__", u"வை":u"__setitem__",u"சாவிகள்":u"keys"} )
        
        #file operators
        tamil_equiv.update({u"கோப்பை_திற":u"file_open", u"கோப்பை_மூடு":u"file_close",u"கோப்பை_படி":u"file_read",
                            u"கோப்பை_எழுது":u"file_write",u"கோப்பை_எழுது_வரிகள்":u"file_writelines",u"கோப்பை_படி_வரிகள்":u"file_readlines"})
        
        #type
        tamil_equiv.update({u"வகை":u"type"})
        
        for k,v in list(tamil_equiv.items()):
            self.builtin_map[k]=self.builtin_map[v];
        
        try:
            import EZTurtle
        except ImportError as ie:
            if ( self.debug ):
                print(u"ImportError => turtle ",unicode(ie))
            return
        
        # translations for turtle module
        turtle_map = { u"முன்னாடி":u"forward", u"பின்னாடி" :u"backward",
                       u"வலது":u"lt", u"இடது":u"rt",
                       u"எழுதுகோல்மேலே":u"penup",  u"எழுதுகோல்கிழே":u"pendown"}
        for k,v in list(turtle_map.items()):
            vv = u"turtle_"+v;
            self.builtin_map[k] = self.builtin_map[vv]
        
        return
Ejemplo n.º 54
0
    def a7(self, value_obj, interpreter_flag=False):
        Interpreter.interpreter_flag = interpreter_flag

        sc = self.scanner
        old_pointer = sc.get_pointer()
        lexeme_open_bracket = sc.next_lexeme()
        fun_name = sc.lexeme
        if lexeme_open_bracket == lId.TOpen:
            self.expression(value_obj, interpreter_flag=Interpreter.interpreter_flag)
            lexeme_close_bracket = sc.next_lexeme()
            if lexeme_close_bracket != lId.TClose:
                raise SyntaxExceptionCharacter(sc.get_pointer_line(), sc.get_pointer_position(), ")", sc.lexeme)
        elif sc.next_lexeme() == lId.TOpen:
            sc.set_pointer(old_pointer)
            self.call_function(interpreter_flag=Interpreter.interpreter_flag)

            if Interpreter.interpreter_flag:
                # Interpreter
                node = self.semantic_tree.get_function_node(fun_name)
                value_obj.value = node.value
                value_obj.type = node.type_data
                # Interpreter
        else:
            sc.set_pointer(old_pointer)
            lexeme_operand = sc.next_lexeme()
            if lexeme_operand != lId.TId and lexeme_operand != lId.TNum10 and lexeme_operand != lId.TNum16:
                raise SyntaxExceptionOperand(sc.get_pointer_line(), sc.get_pointer_position(), sc.lexeme)

            if Interpreter.interpreter_flag:
                # semantic
                if lexeme_operand == lId.TId:
                    if not self.semantic_tree.is_describe_var_early(sc.get_pointer_line(), sc.get_pointer_position(), sc.lexeme):
                        raise SemanticExceptionUndescribeVar(sc.get_pointer_line(), sc.get_pointer_position(), sc.lexeme)
                # semantic

            if Interpreter.interpreter_flag:
                # Interpreter
                if lexeme_operand == lId.TId:
                    _value_obj = self.semantic_tree.get_variable_value_obj(sc.lexeme)
                    value_obj.value = _value_obj.value
                    value_obj.type = _value_obj.type
                elif lexeme_operand == lId.TNum10:
                    Interpreter.set_value_obj_from_num10(value_obj, sc.lexeme)
                else:
                    Interpreter.set_value_obj_from_num16(value_obj, sc.lexeme)
Ejemplo n.º 55
0
    def a6(self, value_obj, interpreter_flag=False):
        Interpreter.interpreter_flag = interpreter_flag

        sc = self.scanner
        old_pointer = sc.get_pointer()
        lexeme_pref = sc.next_lexeme()
        if lexeme_pref == lId.TMinus or lexeme_pref == lId.TPlus:
                #or lexeme_pref == lId.TMinusMinus or lexeme_pref == lId.TPlusPlus:

            if Interpreter.interpreter_flag:
                # Interpreter
                if lexeme_pref == lId.TMinus:
                    Interpreter.sub({'value': 0, 'type': lId.TShort}, value_obj)
                # Interpreter

            self.a7(value_obj, interpreter_flag=Interpreter.interpreter_flag)
        else:
            sc.set_pointer(old_pointer)
            self.a7(value_obj, interpreter_flag=Interpreter.interpreter_flag)
Ejemplo n.º 56
0
    def a4(self, value_obj, interpreter_flag=False):
        Interpreter.interpreter_flag = interpreter_flag

        self.a5(value_obj, interpreter_flag=Interpreter.interpreter_flag)
        sc = self.scanner
        old_pointer = sc.get_pointer()
        lexeme_plus_minus = sc.next_lexeme()
        while lexeme_plus_minus == lId.TPlus or lexeme_plus_minus == lId.TMinus:
            _value_obj = ValueObj()
            self.a5(_value_obj, interpreter_flag=Interpreter.interpreter_flag)

            if Interpreter.interpreter_flag:
                # interpreter
                if lexeme_plus_minus == lId.TPlus:
                    Interpreter.sum(value_obj, _value_obj)
                else:
                    Interpreter.sub(value_obj, _value_obj)
                # interpreter

            old_pointer = sc.get_pointer()
            lexeme_plus_minus = sc.next_lexeme()
        sc.set_pointer(old_pointer)
Ejemplo n.º 57
0
    def a2(self, value_obj, interpreter_flag=False):
        Interpreter.interpreter_flag = interpreter_flag

        self.a3(value_obj, interpreter_flag=Interpreter.interpreter_flag)

        sc = self.scanner
        old_pointer = sc.get_pointer()
        lexeme_equal = sc.next_lexeme()
        while lexeme_equal == lId.TEq or lexeme_equal == lId.TUnEq:
            _value_obj = ValueObj()
            self.a3(_value_obj, interpreter_flag=Interpreter.interpreter_flag)

            if Interpreter.interpreter_flag:
                # interpreter
                if lexeme_equal == lId.TEq:
                    Interpreter.verify_equal(value_obj, _value_obj)
                else:
                    Interpreter.verify_unequal(value_obj, _value_obj)
                # interpreter

            old_pointer = sc.get_pointer()
            lexeme_equal = sc.next_lexeme()
        sc.set_pointer(old_pointer)
Ejemplo n.º 58
0
    def enum_operand(self, interpreter_flag=False):
        Interpreter.interpreter_flag = interpreter_flag

        sc = self.scanner
        old_pointer = sc.get_pointer()
        lexeme = sc.next_lexeme()
        if lexeme != lId.TClose:
            sc.set_pointer(old_pointer)
            value_obj = ValueObj()
            self.expression(value_obj, interpreter_flag=Interpreter.interpreter_flag)

            if Interpreter.interpreter_flag:
                # semantic
                self.semantic_tree.current_count_parameter += 1
                self.semantic_tree.go_left()
                if self.semantic_tree.pointer != self.semantic_tree.dummy:
                    Interpreter.to_type(value_obj, self.semantic_tree.pointer.type_data)
                    self.semantic_tree.pointer.value = value_obj.value
                # semantic

            old_pointer = sc.get_pointer()
            lexeme = sc.next_lexeme()
            while lexeme == lId.TComma:
                value_obj = ValueObj()
                self.expression(value_obj, interpreter_flag=Interpreter.interpreter_flag)
                if Interpreter.interpreter_flag:
                    # semantic
                    self.semantic_tree.current_count_parameter += 1
                    self.semantic_tree.go_left()
                    if self.semantic_tree.pointer != self.semantic_tree.dummy:
                        Interpreter.to_type(value_obj, self.semantic_tree.pointer.type_data)
                        self.semantic_tree.pointer.value = value_obj.value
                    # semantic
                old_pointer = sc.get_pointer()
                lexeme = sc.next_lexeme()
        sc.set_pointer(old_pointer)
Ejemplo n.º 59
0
    def test_3dn_should_add_n_to_register_d(self):
        interpreter = Interpreter(['308', '100'])

        instruction_count = interpreter.execute()

        self.assertEqual('008', interpreter.get_register_value(0))
        self.assertEqual(2, instruction_count)

        ##

        interpreter = Interpreter(['308', '302', '100'])

        instruction_count = interpreter.execute()

        self.assertEqual('010', interpreter.get_register_value(0))
        self.assertEqual(3, instruction_count)
Ejemplo n.º 60
0
    def test_4dn_should_multiply_d_by_n(self):
        interpreter = Interpreter(['408', '100'])

        instruction_count = interpreter.execute()

        self.assertEqual('000', interpreter.get_register_value(0))
        self.assertEqual(2, instruction_count)

        ##

        interpreter = Interpreter(['302', '407', '100'])

        instruction_count = interpreter.execute()

        self.assertEqual('014', interpreter.get_register_value(0))
        self.assertEqual(3, instruction_count)