예제 #1
0
    def test_func(self):
        x = self.MyFunc('my_func',
                        args=OrderedDict(arg1=int, arg2=BuiltInIntVar))
        self.assertEqual(x.id, 0)
        bi = BuiltInIntVar('BI', def_val=1)

        val = x(2, bi)
        self.assertEqual(val._get_compiled(), 'my_func(2, $BI)')
        self.assertEqual(val._get_runtime(), 3)
        val = x(val, bi)
        self.assertEqual(val._get_compiled(), 'my_func(my_func(2, $BI), $BI)')
        self.assertEqual(val._get_runtime(), 4)
        y = self.MyFuncInt('y_func',
                           args=OrderedDict(arg1=int, arg2=BuiltInIntVar))
        self.assertEqual(y.id, 2)
        val = y(x(1, bi), bi)
        self.assertEqual(val._get_compiled(), 'y_func(my_func(1, $BI), $BI)')
        self.assertEqual(val._get_runtime(), 3)
        KSP.set_compiled(True)
        self.assertEqual((y(1, bi) + x(2, bi)).expand(),
                         'y_func(1, $BI) + my_func(2, $BI)')

        Output().refresh()
        y(1, bi)
        self.assertEqual(Output().get()[-1], 'y_func(1, $BI)')
        Output().refresh()
        y(x(1, bi), bi)
        self.assertEqual(unpack_lines(Output().get()),
                         'y_func(my_func(1, $BI), $BI)')
예제 #2
0
    def _generate_ex_proxy(self):
        '''generates lines of function body, wraped in the
        function <name>
        end function
        lines'''
        if not self.called:
            return []
        out = list()
        otpt = Output()

        otpt.blocked = True
        args = self._cashed_args[0]
        passed = self._cashed_args[1]
        FuncStack().push(*args)
        otpt.blocked = False

        FunctionCallback.open()
        otpt.set(out)
        otpt.put(f'function {self.name()}')

        self._func(**passed)

        otpt.put('end function')
        Output().release()
        FunctionCallback.close()

        otpt.blocked = True
        FuncStack().pop()
        otpt.blocked = False
        return out
예제 #3
0
    def test_real(self):
        KSP.set_compiled(True)
        x = kArrReal()
        x.append(2.0)
        self.assertEqual(Output().pop(), '?kArrReal0[0] := 2.0')
        self.assertEqual(x[0].val, '?kArrReal0[0]')
        self.assertEqual(x._get_compiled(), '?kArrReal0')
        x.append(3.0)
        self.assertEqual(Output().pop(), '?kArrReal0[1] := 3.0')
        self.assertEqual(x[1].val, '?kArrReal0[1]')
        self.assertEqual(x._get_runtime(), [2.0, 3.0])
        self.assertEqual(x._generate_init(), ['declare ?kArrReal0[2]'])

        y = kArrReal([1.0, 2.0, 3.0])
        y.append(4.0)
        self.assertEqual(Output().pop(), '?kArrReal1[3] := 4.0')
        self.assertEqual(y._get_runtime(), [1.0, 2.0, 3.0, 4.0])
        self.assertEqual(y._generate_init(),
                         ['declare ?kArrReal1[4] := (1.0, 2.0, 3.0)'])

        IName.set_compact(True)
        z = kArrReal([1.0, 2.0], 'z')
        self.assertEqual(z.name(), '?z3yxf')
        self.assertEqual(z[1].val, '?z3yxf[1]')
        self.assertEqual(z[1]._get_runtime(), 2.0)
        z.read()
        self.assertEqual(Output().pop(), 'read_persistent_var(?z3yxf)')
        self.assertEqual(
            z._generate_init(),
            ['declare ?z3yxf[2] := (1.0, 2.0)', 'make_persistent(?z3yxf)'])

        preserved = kArrReal(name='preserved', preserve=True)
        self.assertEqual(preserved.name(), '?preserved')
예제 #4
0
 def __init__(self, condition):
     call = Output().callable_on_put
     if call:
         call()
         Output().callable_on_put = None
     # if not self.is_compiled():
     #     if callable(condition):
     #         condition = condition()
     self.__condition = condition
예제 #5
0
 def test_mycb(self):
     my_cb = Callback('cb', -1, ())
     my_cb.open()
     Output().put('body')
     self.assertEqual(NI_CALLBACK_TYPE, -1)
     my_cb.close()
     my_cb.open()
     Output().put('body 2')
     my_cb.close()
     self.assertEqual(unpack_lines(my_cb.generate_body()), my_cb_body)
     self.assertEqual(unpack_lines(my_cb.get_all_bodies()), my_cb_body)
예제 #6
0
 def _remove_line(self, line):
     if not self.is_compiled() or Output().blocked:
         return line
     try:
         line_l = Output().pop()
     except IndexError:
         return line
     if line_l == line:
         return line
     Output().put(line_l)
     return line
예제 #7
0
파일: bi_misc.py 프로젝트: Levitanus/pyksp
 def _log_arr_pers(self):
     Output().put('while(1=1)')
     with If(self._log_prev_count != self._log_count):
         check()
         if not self._path:
             save_array(self._log_arr, 1)
         else:
             save_array_str(self._log_arr, self._path)
     self._log_prev_count <<= self._log_count
     wait(200000)
     Output().put('end while')
예제 #8
0
 def open(self, control: KspVar = None):
     super().open()
     if control and control.name() in self.__controls.keys():
         raise RuntimeError(f'callback of {control.name()} has' +
                            ' been set yet')
     if not control:
         control = self._last_control
     else:
         self.__controls[control.name()] = Control(control)
     Output().release()
     Output().set(self.__controls[control.name()].lines)
     self._last_control = control
예제 #9
0
    def test_kReal(self):
        x = kReal()
        self.assertEqual(x.val, 0.0)
        self.assertEqual(x.name(), '~kReal0')
        self.assertEqual(x._generate_init(), ['declare ~kReal0'])

        y = kReal(2.0)
        self.assertEqual(y.val, 2.0)
        self.assertEqual(y.name(), '~kReal1')
        self.assertEqual(y._generate_init(), ['declare ~kReal1 := 2.0'])

        z = kReal(3.0, 'z', persist=True)
        self.assertEqual(z.val, 3)
        self.assertEqual(z.name(), '~z')
        self.assertEqual(z._generate_init(),
                         ['declare ~z := 3.0', 'make_persistent(~z)'])
        read = kReal()
        read.read()
        self.assertEqual(read._generate_init(),
                         ['declare ~kReal2', 'make_persistent(~kReal2)'])
        self.assertEqual(Output().get()[-1], 'read_persistent_var(~kReal2)')
        with self.assertWarns(Warning):
            read.read()
        read.in_init(False)
        with self.assertRaises(RuntimeError):
            read.read()
        read.in_init(True)

        IName.set_compact(True)

        myvar = kReal(1.0, 'myvar')
        self.assertEqual(myvar.name(), '~cra4x')
        myvar_preserved = kReal(0.2, 'myvar_preserved', preserve=True)
        self.assertEqual(myvar_preserved.name(), '~myvar_preserved')
        IName.set_compact(False)
        myvar.set_compiled(True)

        myvar <<= myvar_preserved
        self.assertEqual(Output().get()[-1], '~cra4x := ~myvar_preserved')
        self.assertEqual(myvar.val, '~cra4x')
        self.assertEqual(myvar._get_runtime(), 0.2)
        myvar <<= myvar_preserved + 1.0
        self.assertEqual(Output().get()[-1],
                         '~cra4x := ~myvar_preserved + 1.0')
        self.assertEqual(myvar._get_runtime(), 1.2)
        myvar *= 2.0
        self.assertEqual(Output().get()[-1], '~cra4x := ~cra4x * 2.0')
        self.assertEqual(myvar._get_runtime(), 2.4)

        with self.assertRaises(myvar.TypeWarn):
            myvar += 1
        with self.assertRaises(myvar.TypeWarn):
            myvar += 'string'
예제 #10
0
    def test_kStr(self):
        x = kStr()
        self.assertEqual(x.val, '')
        self.assertEqual(x.name(), '@kStr0')
        self.assertEqual(x._generate_init(), ['declare @kStr0'])

        y = kStr('str')
        self.assertEqual(y.val, 'str')
        self.assertEqual(y.name(), '@kStr1')
        self.assertEqual(y._generate_init(),
                         ['declare @kStr1', '@kStr1 := "str"'])

        z = kStr('3', 'z', persist=True)
        self.assertEqual(z.val, '3')
        self.assertEqual(z.name(), '@z')
        self.assertEqual(z._generate_init(),
                         ['declare @z', '@z := "3"', 'make_persistent(@z)'])
        read = kStr()
        read.read()
        self.assertEqual(read._generate_init(),
                         ['declare @kStr2', 'make_persistent(@kStr2)'])
        self.assertEqual(Output().get()[-1], 'read_persistent_var(@kStr2)')
        with self.assertWarns(Warning):
            read.read()
        read.in_init(False)
        with self.assertRaises(RuntimeError):
            read.read()
        read.in_init(True)

        IName.set_compact(True)

        myvar = kStr('str', 'myvar')
        self.assertEqual(myvar.name(), '@cra4x')
        myvar_preserved = kStr('2', 'myvar_preserved', preserve=True)
        self.assertEqual(myvar_preserved.name(), '@myvar_preserved')
        IName.set_compact(False)
        myvar.set_compiled(True)

        myvar <<= myvar_preserved
        self.assertEqual(Output().get()[-1], '@cra4x := @myvar_preserved')
        self.assertEqual(myvar.val, '@cra4x')
        self.assertEqual(myvar._get_runtime(), '2')
        myvar <<= myvar_preserved + 'string'
        self.assertEqual(Output().get()[-1],
                         '@cra4x := @myvar_preserved & "string"')
        self.assertEqual(myvar._get_runtime(), '2string')

        myvar <<= kInt(name='test', value=1, is_local=True)
        self.assertEqual(Output().pop(), '@cra4x := $test')
        self.assertEqual(myvar._get_runtime(), '1')
예제 #11
0
 def __exit__(self, exc_type, value, traceback):
     """Suppresses KspCondFalse and builds 'end if' lines
     on KspCondBrake exceptions."""
     if exc_type is not None:
         if not isinstance(value, (KspCondFalse, KspCondBrake)):
             return
     if self.is_compiled():
         if exc_type is KspCondBrake:
             raise KspCondBrake('end if')
         Output().put('end if')
     Output().callable_on_put = If.refresh
     if exc_type is KspCondBrake:
         return
     return True
예제 #12
0
    def test_ui_control(self):
        control_1 = kInt()
        control_2 = kInt()
        UiControlCallback.open(control_1)
        Output().put('control_1_line')
        UiControlCallback.close()
        UiControlCallback.open(control_2)
        Output().put('control_2_line')
        UiControlCallback.close()
        with self.assertRaises(RuntimeError):
            UiControlCallback.open(control_1)

        self.assertEqual(unpack_lines(UiControlCallback.generate_body()),
                         ui_lines)
예제 #13
0
 def __exit__(self, exc, value, trace):
     if self._blocked:
         self._blocked = False
         Output().blocked = False
     if exc is not None:
         if exc is not KspCondBrake:
             return
     if self.is_compiled():
         # if isinstance(value, KspCondBrake):
         #     if str(value) != '':
         #         raise KspCondError(
         #             'While loop can not be breaked')
         Output().put('end while')
     return True
예제 #14
0
 def runTest(self):
     kMainWindow()
     self.assertEqual(unpack_lines(Output().get()), null_lines)
     Output().refresh()
     w = kMainWindow(width=800,
                     height=300,
                     wallpaper='wallpaper',
                     icon='icon')
     self.assertEqual(unpack_lines(Output().get()), packed_lines)
     self.assertEqual(w.x, 0)
     self.assertEqual(w.y, 0)
     self.assertEqual(w.width, 800)
     self.assertEqual(w.height, 300)
     with self.assertRaises(AttributeError):
         kMainWindow(width=630)
예제 #15
0
    def code(self):
        x = kInt(2, 'x')
        y = kInt(1, 'y')

        code = list()
        Output().set(code)
        with Select(x):
            with Case(1):
                check()
                y += 1
            with Case(2):
                check()
                y += 2
                with Select(y):
                    with Case(2):
                        check()
                        y += 1
                    with Case(3):
                        check()
                        CondFalse()
        with self.assertRaises(KspCondError):
            with Case(3):
                pass
        if not KSP.is_compiled():
            self.assertEqual(y.val, 3)
        else:
            code = unpack_lines(code)
            self.assertEqual(code, select_string)
예제 #16
0
 def __exit__(self, exc, value, trace):
     '''Supresses Brake exceptions and generates
     postfix (end) code'''
     if exc is not None and exc is not KspCondBrake:
         if self._out_touched:
             Output().blocked = False
             self._out_touched = False
         return
     if isinstance(value, KspCondBrake):
         self.__idx <<= len(self.__seq)
         Output().put(f'{value}')
     self.__generate_exit_code()
     if self._out_touched:
         Output().blocked = False
         self._out_touched = False
     return True
예제 #17
0
 def is_after_if(self):
     """Checks amount of statements and raises exception if
     can_be_else is empty (pure KSP code before Else())"""
     try:
         if_result = can_be_else.pop()
     except IndexError:
         raise KspCondError('has to be right after If()')
     for item in if_result:
         self.__if_count += 1
         if self.is_compiled() and Output().blocked is not True:
             if Output().pop() != 'end if':
                 raise\
                     KspCondError(
                         'something is wrong here. Library bug.')
         last_result = item
     return last_result
예제 #18
0
    def test_calls(self):
        KSP.set_compiled(True)
        self.method()
        self.assertEqual(
            unpack_lines(Output().get()),
            call_out.format(method=Function.get_func_name(self.method)))
        Output().refresh()

        x = kInt(name='x')
        self.method(x)
        self.assertEqual(x._get_compiled(), '$x')
        self.assertEqual(x._get_runtime(), 3)
        self.assertEqual(
            unpack_lines(Output().get()),
            call_with_out.format(method=Function.get_func_name(self.method)))
        Output().refresh()

        self.inlined = True
        self.method(x, inline=True)
        self.assertEqual(unpack_lines(Output().get()), inlined_out)
        Output().refresh()

        arr = kArrInt([1, 2, 3, 4, 5])

        @func
        def foo(loc: kArg(int, 5) = arr):
            with For(arr=loc) as seq:
                for item in seq:
                    self.method(item)

        foo()

        # test for excluding from generation without
        # "calling" it
        @func
        def bar(var: int):
            self.method()

        bar(1, inline=True)

        generated_exec = KspObject.generate_all_executables()
        self.maxDiff = None
        self.assertEqual(
            unpack_lines(generated_exec),
            executables.format(method=Function.get_func_name(self.method),
                               foo=Function.get_func_name(foo)))

        Output().refresh()

        @func
        def foobar(arg=kLoc(int)):
            self.method(arg)

        KSP.in_init(True)
        foobar()
        KSP.in_init(False)
        self.assertEqual(unpack_lines(Output().get()), invoked_in_init)
예제 #19
0
 def setUp(self):
     super().setUp()
     self.x = kInt(0, 'x')
     self.y = kInt(10, 'y')
     self.x <<= 0
     self.y <<= 10
     self.code = list()
     Output().set(self.code)
예제 #20
0
 def __range_handler(self):
     '''Under tests returns generator over range(args) function
     Under compilation idx assignement and while cond lines'''
     self.__idx <<= self.__start
     if self.is_compiled():
         Output().put(
             f'while({self.__idx.val} < {get_string_repr(self.__stop)})')
     for i in range(*get_runtime(*self.__args)):
         self.__idx._set_runtime(i)
         if i > get_runtime(self.__start) and \
                 self.is_compiled()and not Output().blocked:
             self._out_touched = True
             Output().blocked = True
         yield self.__idx
     if self._out_touched:
         self._out_touched = False
         Output().blocked = False
     return
예제 #21
0
 def __exit__(self, exc_type, value, trace):
     """Supresses KspCondFalse and add KspCondError to Output()
     for preventing KSP code before end select or new Case"""
     if exc_type is not None:
         if not isinstance(value, KspCondFalse):
             return
     Output().exception_on_put = KspCondError(
         '''Wrong syntax. all code hase to be in Case block''')
     return True
예제 #22
0
 def _set_compiled(self, other):
     if isinstance(other, KspNumeric):
         runtime = f'{other._get_runtime()}'
     else:
         runtime = other
     if isinstance(other, str):
         other = f'"{other}"'
     self._set_runtime(runtime)
     Output().put(AstAssign(self, other).expand())
예제 #23
0
 def __generate_exit_code(self):
     '''inc(self.__idx) if for, step line if range'''
     if self.is_compiled():
         if self.__func == self.__foreach_handler:
             self.__idx.inc()
         if self.__func == self.__range_handler:
             self.__idx += self.__step
         Output().put('end while')
     For.idx.dec()
예제 #24
0
 def __is_else(self):
     """Checks the condition and puts 'else' to Output()"""
     # self.__if_result = self.is_after_if()
     if not self.is_compiled():
         if self.__if_result:
             # If.__condition = False
             check(False)
             return
         return True
     Output().put('else')
예제 #25
0
 def __is_elif(self):
     """Restoring if order inside can_be_else,
     puts to Output() else and if(condition) lines"""
     cond = self.__condition
     if not self.is_compiled() and not cond:
         # If.__condition = False
         check(False)
         return
     result = list()
     for idx in range(self.__if_count):
         result.append(False)
     result.append(cond)
     self.__if_count += 1
     can_be_else.append(result)
     if self.is_compiled():
         Output().put('else')
         self.set_bool(True)
         Output().put(f'if({cond.expand()})')
         self.set_bool(False)
예제 #26
0
 def test_pop(self):
     KSP.set_compiled(True)
     stack = Stack('test',
                   kArrInt,
                   10)
     with self.assertRaises(IndexError):
         stack.pop()
     stack.push(kLoc(int), kLoc(int, 2), kLoc(int))
     stack.pop()
     self.assertEqual(Output().pop(), 'dec($_stack_test_pointer)')
예제 #27
0
파일: bi_misc.py 프로젝트: Levitanus/pyksp
 def put(self, *args, sep=' '):
     self._check_sep(sep)
     line = ''
     for idx, arg in enumerate(args):
         if idx != 0:
             line += f' & "{sep}" & '
         if isinstance(arg, str):
             arg = f'"{arg}"'
         if hasattr(arg, '_get_compiled'):
             arg = arg._get_compiled()
         if hasattr(arg, 'expand'):
             arg = arg.expand()
         line += f'{arg}'
     if self._type == self.pgs:
         Output().put(f'pgs_set_str_key_val(_log_msg, {line})')
         pgs_set_key_val('_log_flag', 0, 1)
     if self._type is self.array:
         var = self._log_arr[self._log_count]._get_compiled()
         Output().put(f'{var} := {line}')
         self._log_count <<= (self._log_count + 1) % 32768
예제 #28
0
 def tearDown(self):
     KspObject.refresh()
     Output().refresh()
     Callback.refresh()
     # Function.refresh()
     BuiltIn.refresh()
     refresh_names_count()
     IName.refresh()
     gui_refresh()
     For.refresh()
     KSP.refresh()
예제 #29
0
    def __foreach_handler(self):
        '''Uder tests returns iterator over self.__seq,
        under compilation idx assignement and while cond lines'''
        self.__idx <<= 0
        if self.is_compiled():
            Output().put(f'while({self.__idx.val} < {len(self.__seq)})')
        for idx in range(len(self.__seq)):
            if idx > 0 and self.is_compiled() and not Output().blocked:
                self._out_touched = True
                Output().blocked = True
            self.__idx._set_runtime(idx)
            item = self.__seq[self.__idx]
            yield item
        if self._out_touched:
            Output().blocked = False
            self._out_touched = False
        return
        # yield out

        return True
예제 #30
0
 def __call__(self, condition: bool):
     if self.__count and not Output().blocked:
         self._blocked = True
         Output().blocked = True
     if callable(condition):
         condition = condition()
     self.__condition = condition
     if not self.is_compiled():
         if self.__condition:
             return True
         raise KspCondBrake()
     if self.__condition.get_value():
         self.set_bool(True)
         Output().put(f'while({self.__condition.expand()})')
         self.set_bool(False)
         self.__count += 1
         return True
     if self._blocked:
         self._blocked = False
         Output().blocked = False
     raise KspCondBrake()