示例#1
0
    def compute(self, env: Environment):
        e1 = env.find_object('e1')
        e2 = env.find_object('e2')

        if e1.get_type().name not in ['double', 'logical', 'integer']:
            raise errors.InvalidArgTypeInArgs('x', 'x ** y')
        if e2.get_type().name not in ['double', 'logical', 'integer']:
            raise errors.InvalidArgTypeInArgs('y', 'x ** y')

        as_integer = False

        if e1.get_type().name == 'integer' and e2.get_type().name == 'integer':
            as_integer = True
        elif e1.get_type().name == 'integer' and e2.get_type(
        ).name == 'logical':
            as_integer = True
        elif e1.get_type().name == 'logical' and e2.get_type(
        ).name == 'integer':
            as_integer = True

        res = perform_op_on_vector_or_atomic(
            e1, e2,
            lambda l, r: cast_atomic(atomic_mod(l, r), 'integer'
                                     if as_integer else 'double'))

        res = [VectorItem(None, el) for el in res]

        if len(res) == 0:
            t = get_more_important_vector_type(e1.get_type(), e2.get_type())
            return VectorObj([], t)

        ret = VectorObj.create(res)
        return ret
示例#2
0
 def compute(self, env: Environment):
     e = self.e.evaluate(env)
     func: function.FunctionObj = env.find_function('-')
     new_env = arrange_params_with_function_args([function.Param('e1', e)],
                                                 func, env)
     ret = func.compute(new_env)
     return ret
示例#3
0
 def create_new_environment(initialized_args: Dict[str, RObj],
                            env: Environment):
     new_env: Environment = Environment(env)
     for name, val in initialized_args.items():
         val_val = val.evaluate(new_env)
         new_env.add(name, val_val)
     return new_env
示例#4
0
    def compute(self, env: Environment):
        ln: VectorObj = env.find_object('length')
        if ln.get_type().name not in ['double', 'integer']:
            raise errors.InvalidArg('length')

        if len(ln.items) != 1:
            raise errors.InvalidArg('length')

        val = ln.items[0][1]

        if val.is_inf:
            raise errors.R_RuntimeError('vector size cannot be infinite')
        elif val.is_na:
            raise errors.InvalidArg('length')
        elif val.is_nan:
            raise errors.R_RuntimeError('vector size cannot be NA/NaN')

        count = val.value

        items = [
            VectorItem(None, Atomic(False, types.LogicalType()))
            for _ in range(int(count) * (-1 if val.is_neg else 1))
        ]

        ret = VectorObj(items, types.LogicalType())
        return ret
示例#5
0
 def compute(self, env: Environment):
     x, y = self.x.evaluate(env), self.y.evaluate(env)
     func: function.FunctionObj = env.find_function('!')
     new_env = arrange_params_with_function_args([function.Param('x', x)],
                                                 func, env)
     ret = func.compute(new_env)
     return ret
 def evaluate(self, env: Environment):
     e1, e2 = self.e1.evaluate(env), self.e2.evaluate(env)
     func: function.FunctionObj = env.find_function('^')
     ret = func.compute(
         [function.Param('e1', e1),
          function.Param('e2', e2)], env)
     return ret
示例#7
0
    def compute(self, env: Environment):
        try:
            x: RObj = env.find_object_locally('x')
        except:
            raise errors.InvalidLeftHandAssignment()
        try:
            value: RObj = env.find_object_locally('value')
        except:
            raise errors.InvalidLeftHandAssignment()

        if x.get_type().name == 'symbol':
            val_value = value.evaluate(env)
            if val_value.get_type().name == 'call':
                val_value = val_value.compute(env)
            env.parent_env.add(x.name, val_value)
            return val_value
        raise errors.InvalidLeftHandAssignment()
示例#8
0
 def compute(self, env: Environment):
     e1, e2 = self.e1.evaluate(env), self.e2.evaluate(env)
     func: function.FunctionObj = env.find_function(self.op_name)
     new_env = arrange_params_with_function_args(
         [function.Param('e1', e1),
          function.Param('e2', e2)], func, env)
     ret = func.compute(new_env)
     return ret
示例#9
0
def arrange_params_with_function_args(params, func, env: Environment):
    res = func_args_arrange(params, func.input_args)
    new_env: Environment = Environment(env)

    for name, val in res.items():
        new_env.add(name, val)

    return new_env
示例#10
0
 def compute(self, env: Environment):
     dots: DotsObj = env.find_object('...')
     items = dots.items
     list_items = []
     for item in items:
         itm = ListItem(item.name, item.value)
         list_items.append(itm)
     return ListObj(list_items)
示例#11
0
 def compute(self, env: Environment):
     e1 = env.find_object('x')
     e2 = env.find_object('y')
     if e1.get_type().name not in ['double', 'logical', 'integer']:
         raise errors.InvalidArgTypeInArgs('x', 'x | y')
     if e2.get_type().name not in ['double', 'logical', 'integer']:
         raise errors.InvalidArgTypeInArgs('y', 'x | y')
     res = VectorItem(None, atomic_or(e1.items[0].value, e2.items[0].value))
     ret = VectorObj.create([res])
     return ret
示例#12
0
 def evaluate(self, env: Environment):
     standart_for_env = env.standart_output
     env.standart_output = self.standard_output
     try:
         for item in self.items:
             res = execute_item(item, env)
             self.standard_output(res.show_self())
     except CommandException as e:
         self.standard_output(e.message)
     except R_RuntimeError as e:
         self.standard_output(e.message)
     except RError as e:
         func = env.find_function('print')
         try:
             arrange_params_with_function_args([Param('x', e)], func, env)
         except Exception as e:
             self.standard_output(str(e))
     finally:
         env.standart_output = standart_for_env
         return None
示例#13
0
    def compute(self, env: Environment):
        e: DotsObj = env.find_object('...')

        for index, param in enumerate(e.items):
            if param[1].get_type().name not in [
                    'character', 'double', 'integer', 'logical'
            ]:
                raise errors.ArgumentCannotBeHandledByFun(
                    index + 1, param[1].get_type().name, 'cat')
            for atom in param[1].items:
                rep = atom.show_self()
                print(rep)

        return NULLObj()
示例#14
0
    def compute(self, env: Environment):
        e1 = env.find_object('x')
        e2 = env.find_object('y')
        if e1.get_type().name not in ['double', 'logical', 'integer']:
            raise errors.InvalidArgTypeInArgs('x', 'x || y')
        if e2.get_type().name not in ['double', 'logical', 'integer']:
            raise errors.InvalidArgTypeInArgs('y', 'x || y')

        res = perform_op_on_vector_or_atomic(
            e1, e2, lambda l, r: cast_atomic(atomic_power(l, r)))

        res = [VectorItem(None, el) for el in res]

        ret = VectorObj.create(res)
        return ret
示例#15
0
    def compute(self, env: Environment):
        e1 = env.find_object('e1')
        e2 = env.find_object('e2')

        if isinstance(e2, EmptyParamObj):
            if e1.get_type().name not in ['double', 'logical', 'integer']:
                raise errors.InvalidArgTypeInArgs('x', '- x')

            res = []
            for item in e1.items:
                res.append(
                    atomic_subtract(Atomic(False, types.LogicalType()),
                                    item.value))

            res = [VectorItem(None, el) for el in res]

            ret = VectorObj(res)
            return ret

        if e1.get_type().name not in ['double', 'logical', 'integer']:
            raise errors.InvalidArgTypeInArgs('x', 'x - y')
        if e2.get_type().name not in ['double', 'logical', 'integer']:
            raise errors.InvalidArgTypeInArgs('y', 'x - y')

        as_integer = False

        if e1.get_type().name == 'integer' and e2.get_type().name == 'integer':
            as_integer = True
        elif e1.get_type().name == 'integer' and e2.get_type(
        ).name == 'logical':
            as_integer = True
        elif e1.get_type().name == 'logical' and e2.get_type(
        ).name == 'integer':
            as_integer = True

        res = perform_op_on_vector_or_atomic(
            e1, e2,
            lambda l, r: cast_atomic(atomic_subtract(l, r), 'integer'
                                     if as_integer else 'double'))

        res = [VectorItem(None, el) for el in res]

        if len(res) == 0:
            t = get_more_important_vector_type(e1.get_type(), e2.get_type())
            return VectorObj([], t)

        ret = VectorObj.create(res)
        return ret
示例#16
0
    def compute(self, env: Environment):
        dots: DotsObj = env.find_object('...')

        if dots.get_type().name == 'NULL':
            return NULLObj()

        items = dots.items
        if len(items) == 0:
            return NULLObj()

        items_types = set(map(lambda i: i[1].get_type().name, items))
        casts = ['list', 'character', 'double', 'integer', 'logical']
        if set(casts).issubset(items_types):
            list_fun: FunctionObj = built_in_env.find_function('list')
            ret = list_fun.compute(env)
            return ret

        flat_items = []
        for item in items:
            if isinstance(item[1], Atomic):
                flat_items.append(VectorItem(item[0], item[1]))
            elif isinstance(item[1], VectorObj):
                flat_items.extend(item[1].items)
            else:
                raise Exception('Invalid item in c function - {}'.format(item))

        if 'character' in items_types:
            if len(items_types) > 1:
                flat_items = cast_vector_items(flat_items, str,
                                               types.CharacterType)
        elif 'double' in items_types:
            if len(items_types) > 1:
                flat_items = cast_vector_items(flat_items, float,
                                               types.DoubleType)
        elif 'integer' in items_types:
            if len(items_types) > 1:
                flat_items = cast_vector_items(flat_items, int,
                                               types.IntegerType)
        elif 'logical' in items_types:
            if len(items_types) > 1:
                flat_items = cast_vector_items(flat_items, bool,
                                               types.LogicalType)
        else:
            raise Exception(
                "unknown vector type in types - {}".format(items_types))

        return VectorObj.create(flat_items)
示例#17
0
    def compute(self, env: Environment):
        e1 = env.find_object('x')
        e2 = env.find_object('y')
        if e1.get_type().name not in ['double', 'logical', 'integer']:
            raise errors.InvalidArgTypeInArgs('x', 'x && y')
        if e2.get_type().name not in ['double', 'logical', 'integer']:
            raise errors.InvalidArgTypeInArgs('y', 'x && y')
        try:
            res = perform_op_on_vector_or_atomic(e1, e2, atomic_and)
        except UnsupportedVectorType as e:
            raise errors.InvalidArgTypeInArgs(
                'x' if e.operand_index == 0 else 'y', 'x && y')

        res = [VectorItem(None, el) for el in res]

        ret = VectorObj.create(res)
        return ret
示例#18
0
    def compute(self, env: Environment):
        if self.base_obj.get_type().name == 'symbol':
            fun: FunctionObj = env.find_function(self.base_obj.name)
        else:
            fun: FunctionObj = self.base_obj.evaluate(env)
            if not isinstance(fun, FunctionObj):
                raise errors.ApplyToNonFunction()

        args = []

        assg_obj = RObj.get_r_obj('AssignObj')

        for item in self.items:
            # item_val = item.evaluate(env)
            if isinstance(item, DotsObj):
                args.extend(item.items)
            elif isinstance(item, Atomic):
                n = VectorObj.create([VectorItem(None, item)])
                args.append(Param(None, n))
            elif isinstance(item, assg_obj):
                if item.mode == 'plain':
                    if item.item.get_type().name == 'symbol':
                        name = item.item.name
                    elif isinstance(item.item, Atomic):
                        if item.item.get_type().name == 'character':
                            name = item.item[0]
                        else:
                            raise errors.InvalidLeftHandAssignment()
                    else:
                        raise errors.InvalidLeftHandAssignment()
                    arg = Param(name, item.value.evaluate(env))
                    args.append(arg)
                else:
                    arg = Param(None, item.evaluate(env))
                    args.append(arg)
            else:
                arg = Param(None, item.evaluate(env))
                args.append(arg)

        try:
            ret = fun.compute(args, env)
        except errors.R_RuntimeError as e:
            r = RError(self, e.message)
            if not self.exception_occurred(r):
                raise r
        return ret
示例#19
0
    def compute(self, env: Environment):
        e1 = env.find_object('x')
        if e1.get_type().name not in ['double', 'logical', 'integer']:
            raise errors.InvalidArgType()
        res = []
        if isinstance(e1, VectorObj):
            if len(e1.items) == 0:
                return VectorObj([], type(e1.get_type())())

            for item in e1.items:
                res.append(atomic_not(item[1]))
        else:
            res.append(atomic_not(e1))

        res = [VectorItem(None, el) for el in res]

        ret = VectorObj.create(res)
        return ret
示例#20
0
    def evaluate(self, env: Environment):
        fun_to_find = '<-'

        if isinstance(self.item, DLRObj):
            fun_to_find = '$<-'
        elif isinstance(self.item, AssignObj):
            fun_to_find = '[<-'
        elif isinstance(self.item, SuperAssignObj):
            fun_to_find = '[[<-'

        func: function.FunctionObj = env.find_function(
            fun_to_find, self.item.get_classes_as_python_list())

        new_env = arrange_params_with_function_args([
            function.Param('x', self.item),
            function.Param('value', self.value)
        ], func, env)
        ret = func.compute(new_env)
        return ret
 def evaluate(self, env: Environment):
     x, y = self.x.evaluate(env), self.y.evaluate(env)
     func: function.FunctionObj = env.find_function('!')
     ret = func.compute([function.Param('x', x)], env)
     return ret
示例#22
0
 def evaluate(self, env: Environment):
     ret = env.find_object(self.name)
     return ret
示例#23
0
from R.Environment import Environment
import R.RObj
import R.BuiltIn as builtin
from R.Function import FunctionObj, CallObj, Atomic, Arg
import R.AtomicObjs as objs
import R.Types as types
import R.LanguageObjs as language

this_env: Environment = Environment(builtin.built_in_env)
this_env.set_global(this_env)
print('123')

items1 = [
    language.AssignObj.create(objs.SymbolObj('h'),
                              Atomic.create(1, types.IntegerType())),
    Atomic.create(2, types.IntegerType()),
    Atomic.create(5, types.IntegerType())
]

items2 = [
    Atomic.create(False, types.LogicalType()),
    language.AssignObj.create(objs.SymbolObj('f'),
                              Atomic.create(1, types.IntegerType())),
    Atomic.create(5, types.IntegerType()),
    language.AssignObj.create(objs.SymbolObj('h'),
                              Atomic.create(1, types.IntegerType()))
]

symbol_c = objs.SymbolObj('c')

c_call1 = CallObj(symbol_c, items1)
示例#24
0
from typing import List
from abc import abstractmethod
import R.Types as types

from R.Environment import Environment
from R.Function import FunctionObj, RObj, Arg, DotsObj, Param
from R.AtomicObjs import ListItem, ListObj, VectorObj, VectorItem, Atomic, EmptyParamObj, NULLObj
import R.RuntimeErrors as errors


built_in_env: Environment = Environment(None)


class BuiltInFun(FunctionObj):
    def __init__(self, name, input_args):
        super(BuiltInFun, self).__init__(input_args, None)
        self._type = types.BuiltInType()
        self.name = name

    @staticmethod
    @abstractmethod
    def create(*args):
        pass

    @abstractmethod
    def compute(self, params: List[Param], env: Environment):
        pass


def cast_vector_items(items, python_type, r_type):
    ret = [VectorItem(item.name, Atomic(python_type(item.value.value), r_type())) for item in items]
 def evaluate(self, env: Environment):
     e = self.e.evaluate(env)
     func: function.FunctionObj = env.find_function('-')
     ret = func.compute([function.Param('e1', e)], env)
     return ret
 def evaluate(self, env: Environment):
     if self.mode == 'super':
         env = env.global_env
         if self.item.get_type().name == 'symbol':
             val_value: RObj = self.value.evaluate(env)
             name = self.item.name
             env.add(name, val_value)
             return val_value
         elif isinstance(self.item, RObj.get_r_obj('Atomic')):
             if self.item.get_type().name == "character":
                 name = self.item.value
                 val_value: RObj = self.value.evaluate(env)
                 env.add(name, val_value)
                 return val_value
             else:
                 raise errors.InvalidLeftHandAssignment()
         else:
             val_value: RObj = self.value.evaluate(env)
             ret = self.item.set_value(val_value, env)
             return ret
         # if env == env.global_env:
         #     if self.item.get_type().name == 'symbol':
         #         val_value: RObj = self.init_if_atomic(self.value.evaluate(env))
         #         name = self.item.name
         #         env.add(name, val_value)
         #         return val_value
         #     elif isinstance(self.item, RObj.get_r_obj('Atomic')):
         #         if self.item.get_type().name == "character":
         #             name = self.item.value
         #             val_value: RObj = self.init_if_atomic(self.value.evaluate(env))
         #             env.add(name, val_value)
         #             return val_value
         #         else:
         #             raise errors.InvalidLeftHandAssignment()
         #     else:
         #         val_value: RObj = self.init_if_atomic(self.value.evaluate(env))
         #         ret = self.item.set_value(val_value, env)
         #         return ret
         # else:
         #     if self.item.get_type().name == 'symbol':
         #         val_value: RObj = self.init_if_atomic(self.value.evaluate(env))
         #         name = self.item.name
         #         env.add(name, val_value)
         #         env.global_env.add(name, val_value)
         #         return val_value
         #     elif isinstance(self.item, RObj.get_r_obj('Atomic')):
         #         if self.item.get_type().name == "character":
         #             name = self.item.value
         #             val_value: RObj = self.init_if_atomic(self.value.evaluate(env))
         #             env.add(name, val_value)
         #             env.global_env.add(name, val_value)
         #             return val_value
         #         else:
         #             raise errors.InvalidLeftHandAssignment()
         #     else:
         #         raise errors.InvalidLeftHandAssignment()
     else:
         if self.item.get_type().name == 'symbol':
             val_value: RObj = self.value.evaluate(env)
             name = self.item.name
             env.add(name, val_value)
             return val_value
         elif isinstance(self.item, RObj.get_r_obj('Atomic')):
             if self.item.get_type().name == "character":
                 name = self.item.value
                 val_value: RObj = self.value.evaluate(env)
                 env.add(name, val_value)
                 return val_value
             else:
                 raise errors.InvalidLeftHandAssignment()
         else:
             val_value: RObj = self.value.evaluate(env)
             ret = self.item.set_value(val_value, env)
             return ret
示例#27
0
    def evaluate(self, env: Environment):
        if self.as_from_lang:
            try:
                return self.base_obj.compute(env)
            except errors.R_RuntimeError as e:
                r = RError.create_simple(self, e.message)
                if not self.exception_occurred(r):
                    raise r

        if self.base_obj.get_type().name == 'symbol':
            fun: FunctionObj = env.find_function(self.base_obj.name)
            if not isinstance(fun, FunctionObj):
                raise RError.create_simple(self,
                                           errors.ApplyToNonFunction().message)
        else:
            fun: FunctionObj = self.base_obj.evaluate(env)
            if not isinstance(fun, FunctionObj):
                raise errors.ApplyToNonFunction()

        args = []

        assg_obj = RObj.get_r_obj('AssignObj')

        for item in self.items:
            if isinstance(item, DotsObj):
                args.extend(item.items)
            elif isinstance(item, Atomic):
                n = VectorObj.create([VectorItem(None, item)])
                args.append(Param(None, n))
            elif isinstance(item, assg_obj):
                if item.item.get_type().name == 'symbol':
                    name = item.item.name
                elif isinstance(item.item, Atomic):
                    if item.item.get_type().name == 'character':
                        name = item.item[0]
                    else:
                        raise RError.create_simple(
                            self,
                            errors.InvalidLeftHandAssignment().message)
                else:
                    raise RError.create_simple(
                        self,
                        errors.InvalidLeftHandAssignment().message)
                arg = Param(name, item.value.evaluate(env))
                args.append(arg)
            else:
                arg = Param(None, item.evaluate(env))
                args.append(arg)
            #     if item.mode == 'plain':
            #         if item.item.get_type().name == 'symbol':
            #             name = item.item.name
            #         elif isinstance(item.item, Atomic):
            #             if item.item.get_type().name == 'character':
            #                 name = item.item[0]
            #             else:
            #                 raise errors.InvalidLeftHandAssignment()
            #         else:
            #             raise errors.InvalidLeftHandAssignment()
            #         arg = Param(name, item.value.evaluate(env))
            #         args.append(arg)
            #     else:
            #         arg = Param(None, item.evaluate(env))
            #         args.append(arg)
            # else:
            #     arg = Param(None, item.evaluate(env))
            #     args.append(arg)

        try:
            res = func_args_arrange(args, fun.input_args)
            new_env: Environment = Environment(env)
            for name, val in res.items():
                new_env.add(name, val)
            ret = fun.compute(new_env)
            return ret
        except errors.R_RuntimeError as e:
            r = RError.create_simple(self, e.message)
            if not self.exception_occurred(r):
                raise r