示例#1
0
def main():
    while True:
        try:
            text = input('rafmath: ')
        except (EOFError, KeyboardInterrupt):
            break
        if not text:
            continue

        if (text.lower() == 'exit'):
            break

        try:
            lexer = Lexer(text)
            parser = Parser(lexer)
            interpreter = Interpreter(parser)
            result = interpreter.interpret()

            if isinstance(result, int):
                print(result)
            if isinstance(result, float):
                result *= 1000
                result = int(result)
                result = result / 1000
                print(result)
        except:
            print('ERROR')
            pass
def test_print_string(capsys):
    program = 'print("to moj string")'

    interpreter = Interpreter(program)
    interpreter.interprete()

    out, err = capsys.readouterr()

    assert out == 'to moj string\n'
示例#3
0
    def __init__(self, *, loop=None, **options):
        super().__init__(loop=loop, **options)

        create_log_folder()
        self.logger = logging.getLogger("DiceBot")
        self.init_logging()

        self.lexer = Lexer()
        self.interpreter = Interpreter(self.lexer)
def test_operation_plus():
    z = '777'
    t = '666'
    program = 'var z = ' + z + '  var t = ' + t + ' var p = 0  p =  z + t'

    interpreter2 = Interpreter(program)
    interpreter2.interprete()

    vars2 = interpreter2.variables

    assert int(z) + int(t) == vars2['p']
def test_condition_and_true(capsys):
    program = 'var x = 10' \
              'var y = 1 [USD]' \
              'if( 0 < x & y > 0[USD]){' \
              'print( x) }' \

    interpreter = Interpreter(program)
    interpreter.interprete()

    out, err = capsys.readouterr()

    assert out == '10\n'
def test_while_loop_currency(capsys):
    program = 'var x = 0 [USD]' \
              'while( x < 5 [USD]){' \
              'x = x + 1[USD] }' \
              'print(x)'

    interpreter = Interpreter(program)
    interpreter.interprete()

    out, err = capsys.readouterr()

    assert out == '5.0 USD\n'
def test_while_loop(capsys):
    program = 'var x = 0' \
              'while( 5 > x){' \
              'x = 1 + x }' \
              'print(x)'

    interpreter = Interpreter(program)
    interpreter.interprete()

    out, err = capsys.readouterr()

    assert out == '5\n'
def test_condition_or_and_false(capsys):
    program = 'var x = 0' \
              'var y = 5 [USD]' \
              'if( 0 != x & y < 10 [USD] | 0 != 0 ){' \
              'print(x) } '

    interpreter = Interpreter(program)
    interpreter.interprete()

    out, err = capsys.readouterr()

    assert out == ''
def test_condition_or_false(capsys):
    program = 'var x = 10' \
              'var y = 1 [USD]' \
              'if( 0 > x | y < 0[USD]){' \
              'print( x) }' \

    interpreter = Interpreter(program)
    interpreter.interprete()

    out, err = capsys.readouterr()

    assert out == ''
def test_if_condition_false(capsys):
    program = 'var x = 0' \
              'var y = 10' \
              'if( x > y){' \
              'print(y) }'

    interpreter = Interpreter(program)
    interpreter.interprete()

    out, err = capsys.readouterr()

    assert out == ''
def test_function_return_currency(capsys):
    program = 'def func(x, y, z){' \
              'return x + y + z }' \
              'var result = 0 [USD]' \
              'result = func(1 [USD], 1 [USD] , 1 [USD])' \
              'print(result)'

    interpreter = Interpreter(program)
    interpreter.interprete()

    out, err = capsys.readouterr()

    assert out == '3.0 USD\n'
def test_function_return(capsys):
    program = 'def func(x, y){' \
              'return x + y }' \
              'var x = 0' \
              'x = func(10, 10)' \
              'print(x)'

    interpreter = Interpreter(program)
    interpreter.interprete()

    out, err = capsys.readouterr()

    assert out == str(10 + 10) + '\n'
def test_function_call_currencies(capsys):

    program = 'def func(x, y, z) {  '   \
              'print(x)  '              \
              'print(y)  '              \
              'print(z) } '             \
              'func(1 [USD], 2 [CHF], 3 [DKK])    '

    interpreter = Interpreter(program)
    interpreter.interprete()

    out, err = capsys.readouterr()

    assert out == '1.0 USD\n2.0 CHF\n3.0 DKK\n'
def test_variable_assignment(capsys):
    x = 'var x = 100 '
    y = 'var y = 200 [USD] '
    print = 'print(y) print(x)'

    interpreter = Interpreter(x + y + print)
    interpreter.interprete()

    out, err = capsys.readouterr()

    varss = interpreter.variables

    assert varss['x'] == 100
    assert out == '200.0 USD\n100\n'
def test_function_call(capsys):

    program = 'def func(x, y, z) {  '   \
              'print(x)  '              \
              'print(y)  '              \
              'print(z) } '             \
              'func(1, 2 ,3)    '

    interpreter = Interpreter(program)
    interpreter.interprete()

    out, err = capsys.readouterr()

    assert out == '1\n2\n3\n'
示例#16
0
 def main():
     while True:
         try:
             # To run under Python3 replace 'raw_input' call
             # with 'input'
             text = input('alng >>')
         except EOFError:
             break
         if not text:
             continue
         lexer = Lexer(text)
         parser = Parser(lexer)
         interpreter = Interpreter(parser)
         result = interpreter.interpret()
         print(result)
示例#17
0
    def __init__(
        self,
        top: Toplevel,
        fs: FileSystem,
        contents: Optional[str],
        verbose: bool,
        out: bool,
        on_complete: Optional[Callable[[None], None]] = None,
    ) -> None:
        self.fs = fs
        self.root = top
        self.text = Text(top)
        self.on_complete = on_complete
        self.out = out

        if contents is None or contents == '':
            self.root.destroy()
            return

        files = [(StringIO(), open(file.strip(), 'r'))
                 for file in contents.split(',')]
        self.interpreters = [
            Interpreter(self.fs, file, out=io, log=verbose)
            for io, file in files
        ]

        self.init_view()
        self.launch_threads()
示例#18
0
class HandleCommandThread(QThread):

    processResult = pyqtSignal(object)
    clearDisplayWidget = pyqtSignal()
    makeSnapshot = pyqtSignal()

    stopQueueListener = pyqtSignal()

    interpreter = Interpreter()

    def __init__(self, command, queue):
        super().__init__()
        self.command = command
        self.queue = queue

    def run(self):
        try:
            result = self.interpreter.interpreter(self.command, self.queue)
        except ClearCalled:
            self.stopQueueListener.emit()
            self.clearDisplayWidget.emit()
        except SnapshotCalled:
            self.stopQueueListener.emit()
            self.makeSnapshot.emit()
        else:
            self.stopQueueListener.emit()
            self.processResult.emit(result)
示例#19
0
def main():
    while True:
        try:
            text = input('rafmath: ')
        except (EOFError, KeyboardInterrupt):
            break
        if text == 'exit':
            exit('Goodbye')
        if not text:
            continue
        text += ' '
        lexer = Lexer(text)
        parser = Parser(lexer)
        interpreter = Interpreter(parser)
        result = interpreter.interpret()
        print(result)
def test_basic_operations(capsys):
    program = 'var x = 0' \
              'x = 2 + 2 * 2' \
              'var t = 10' \
              'var y = 10 [CHF]' \
              'y = y /2 + y * 10' \
              'print(y)' \

    interpreter = Interpreter(program)
    interpreter.interprete()

    out, err = capsys.readouterr()

    variables = interpreter.variables

    assert variables['x'] == 6
    assert out == '105.0 CHF\n'
示例#21
0
 def __init__(self):
     Node.__init__(self, "pgcd_comp",
             allow_undeclared_parameters = True,
             automatically_declare_parameters_from_overrides = True)
     Interpreter.__init__(self, self.get_name())
     TFUpdater.__init__(self)
     # program
     self.id = self.get_name()
     self.prog_path = self.get_parameter('program_location')._value + self.id + '.rosl'
     rclpy.logging._root_logger.log("PGCD creating " + self.id + " running " + self.prog_path, LoggingSeverity.INFO)
     # hardware
     module = importlib.import_module(self.get_parameter('object_module_name')._value)
     class_ = getattr(module, self.get_parameter('object_class_name')._value)
     self.robot = class_()
     # runtime
     self.tfBuffer = tf2_ros.Buffer()
     self.tf2_listener = tf2_ros.TransformListener(self.tfBuffer, self)
     self.tf2_setup(self.robot)
示例#22
0
def main():
    while True:
        try:
            text = input('>>>RAFMATH ')
        except (EOFError, KeyboardInterrupt):
            break
        if not text:
            continue

        lexer = Lexer(text)
        parser = Parser(lexer)
        interpreter = Interpreter(parser)
        result = interpreter.interpret()
        if result in (True, False):
            print(result)
        elif float(result).is_integer():
            print("%.0f" % result)
        else:
            print("%.3f" % result)
示例#23
0
def run_interpreter(text):
    result = {}
    result['output'] = []
    with Capturing() as output:
        try:
            lexer = Lexer(text)
            parser = Parser(lexer)
            tree = parser.parse()
            sem_an = SemanticAnalyzer(tree)
            sem_an.analyse()
            interpreter = Interpreter(tree)
            result['final_result'] = interpreter.interpret()
        except Exception as exc:
            result['exception'] = str(exc)

    if output:
        result['output'] = output

    return result
示例#24
0
def interpreter(command):  #, queue):
    q = queue.Queue()

    c = Interpreter()
    try:
        result = c.interpreter(command, q)
    except ClearCalled:
        result = {
            "exception": "clear"
        }
        return json.dumps(result)
    except SnapshotCalled:
        result = {
            "exception": "snapshot"
        }
        return json.dumps(result)

    else:
        json_string = json.dumps(result.__dict__)
        return json_string
示例#25
0
def run(source: str, interpreter: Interpreter) -> None:
    scanner = Scanner(source)
    scanner.scan_tokens()

    if scanner.had_error:
        print(f'Error scanning')
        return

    parser = Parser(scanner.tokens)
    statements = parser.parse()

    if parser.had_error:
        print(f'Error parsing')
        for err in parser.errors:
            parser_error_print(err, scanner.source_lines)
    else:
        resolve_statements(statements)
        try:
            interpreter.interpret(statements)
        except LoxRuntimeError as err:
            print(f'{err.msg}')
示例#26
0
文件: ui.py 项目: eviallet/FishCalc
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.interpreter = Interpreter()

        self.history = History(self)
        self.terminal = Terminal(self.history.last_query_bridge())

        # noinspection PyUnresolvedReferences
        self.terminal.interpret_request.connect(self.interpreter.interpret)
        self.interpreter.interpreted.connect(self.on_interpreted)

        self.setup_ui()
示例#27
0
def run_prompt() -> None:
    interpreter = Interpreter()
    while True:
        try:
            line = input("> ")
        except (EOFError, KeyboardInterrupt) as err:
            if isinstance(err, EOFError):
                sys.exit(0)
            else:
                print("\n")
                continue
        if len(line):
            run(line, interpreter)
示例#28
0
 def run_prg(self, filename):
     self.file_interpreter = Compiler(filename).low_level_file_interpreter
     compiled = "\n".join(self.file_interpreter.compiled)
     #print(compiled)
     interpreter = Interpreter("")
     interpreter.__init__(compiled)
     interpreter.run()
     self.ram = interpreter.ram
示例#29
0
def main():
    arg = sys.argv[1]
    
    processtime_in_ms = time.time() * 1000

    with open(arg) as fs:

        # Generate Tokens
        lexer = Lexer(fs.read())
        tokens = lexer.generate_tokens()

        # Generate AST
        parser = Parser(tokens)
        ast = parser.parse()

        # Global conductor instance
        conductor = Conductor()

        # Interpret AST
        interpreter = Interpreter(ast, conductor)
        interpreter.interpret()

        print(f"\nPROCESS TIME: {time.time() * 1000 - processtime_in_ms}ms")
示例#30
0
class QParallelBibleWidget(QWidget):

    interpreter = Interpreter()
    queue = queue.Queue

    current_sword_module = None

    #modules_list = ['GerNeUe', 'TR', 'GerSch']
    #display_widgets_list = []

    def __init__(self):
        super().__init__()

        self.layout = QVBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.layout)

        self.display_widget = QDisplayLayout()
        self.layout.addWidget(self.display_widget)

        line = QInputLine()
        line.return_pressed.connect(self.commandEntered)
        self.layout.addWidget(line)

    def commandEntered(self, command):
        """ store the originally selected sword module """
        self.current_sword_module = self.interpreter.interpreter(
            'sword.getModule', self.queue).payload

        for i, widget in enumerate(self.display_widget.display_widgets_list):

            try:
                self.interpreter.interpreter(
                    'sword.setModule ' + widget.getModuleName(), self.queue)

                result = self.interpreter.interpreter(command, self.queue)
            except ClearCalled:
                self.clearDisplayWidget()
            else:
                print(result.toString())
                widget.setText(result.toString())
        """ restore the originally seletectd sword module """
        self.interpreter.interpreter(
            'sword.setModule ' + self.current_sword_module, self.queue)

    def clearDisplayWidget(self):
        pass
示例#31
0
 def test_interpreter_nested_conditions(self):
     user_input = 'HD! HD! HD! HD? HD= DH! HD. HD! HD! HD? HD= DH! DH? DH. DH?'
     self.assertEqual(Interpreter.run_interpreter(user_input), '321221121')
示例#32
0
 def setUp(self):
     Interpreter.reset_storage()
示例#33
0
 def test_interpreter_basic_output(self):
     user_input = 'HD! HD!    HD='
     self.assertEqual(Interpreter.run_interpreter(user_input), '2')
示例#34
0
def _calc(characters):
    tokens = imp_lex(characters)
    interpreter = Interpreter(tokens)
    return interpreter.expr()
示例#35
0
 def test_interpreter_hello_world(self):
     user_input = '72 H4ck3rs D3l1ght@ 101 H4ck3rs D3l1ght@ 108 D3l1ght H4ck3rs= H4ck3rs D3l1ght@ H4ck3rs D3l1ght@ H4ck3rs D3l1ght. 111 D3l1ght H4ck3rs= H4ck3rs D3l1ght@  32 H4ck3rs D3l1ght@  87 H4ck3rs D3l1ght@ H4ck3rs D3l1ght@ 114 H4ck3rs D3l1ght@ D3l1ght H4ck3rs. H4ck3rs D3l1ght@ 100 H4ck3rs D3l1ght@ 33 H4ck3rs D3l1ght@'
     self.assertEqual(Interpreter.run_interpreter(user_input), 'Hello World!')
示例#36
0
 def test_interpreter_conditions(self):
     user_input = 'HD! HD! HD! HD? HD= DH! DH? HD! HD='
     self.assertEqual(Interpreter.run_interpreter(user_input), '3211')
示例#37
0
from interpreter.interpreter import Interpreter

Interpreter.start()