def test_basic_module_orm():
    module = create_module_orm(basic_module)
    assert module == SwiftModule(
        module_name='samples.basic_module',
        vars=[NameAndType(name='a', type=int)],
        functions=[
            Function(name='foo',
                     args=[NameAndType('x', str)],
                     cls='modulefunction',
                     return_type=int)
        ],
        classes=[
            SwiftClass(
                object_name='C',
                module='samples.basic_module',
                static_vars=[],
                instance_vars=[NameAndType(name='c', type=bool)],
                init_params=[[]],
                methods=[
                    Function(
                        name='d',
                        args=[NameAndType('x', int),
                              NameAndType('y', int)],
                        cls='instancemethod',
                        return_type=float)
                ],
                magic_methods=mock.ANY,
            )
        ],
    )
def test_a_typed_params():
    code = 'a: float, b: Tuple[int, float], c: str)'
    tps, i = a_typed_params(code, 0)
    assert get_tk(code, i) == ')'
    assert tps == [
        NameAndType('a', float),
        NameAndType('b', Tuple[int, float]),
        NameAndType('c', str)
    ]
Exemplo n.º 3
0
def test_simple_create_object_orm2():
    assert create_class_orm(BasicClass2) == SwiftClass(
        object_name='BasicClass2',
        module='samples.basic',
        static_vars=[NameAndType(name='b', type=Any)],
        instance_vars=[
            NameAndType(name='a', type=Any),
            NameAndType(name='b', type=Any)
        ],
        init_params=[[]],
        methods=[
            Function(name='f', args=[], return_type=None, cls='instancemethod')
        ],
        magic_methods=mock.ANY,
    )
Exemplo n.º 4
0
def get_functions(cls) -> List[Function]:
    functions = [
        Function(
            name=func_name,
            args=[
                NameAndType(name=k, type=v.annotation, default_value=v.default)
                for k, v in inspect.signature(func).parameters.items()
                if k != 'return' and k != 'self'
            ],
            cls='staticmethod'
            if is_static_method(cls, func_name) else 'instancemethod',
            return_type=func.__annotations__.get('return'),
        )
        for func_name, func in [(
            func_name, func) for func_name, func in inspect.getmembers(
                cls, lambda x: inspect.isfunction(x) or inspect.ismethod(x))
                                if not func_name.startswith("__") and func_name
                                not in ['overload', '_overload_dummy']]
    ]
    overloads = get_overloads(cls, is_module=False)
    functions = [
        x for x in functions if x.name not in {f.name
                                               for f in overloads}
    ] + overloads
    return flatten_functions(functions)
Exemplo n.º 5
0
def get_init_params(cls) -> List[List[NameAndType]]:
    params = [
        NameAndType(name=k, type=v)
        for k, v in inspect.getfullargspec(cls.__init__).annotations.items()
    ]
    flattened_params = flatten_functions(
        [Function(name='__init__', args=params, cls=cls.__name__)])
    return [x.args for x in flattened_params]
Exemplo n.º 6
0
def test_simple_create_object_orm4():
    swift_obj = create_class_orm(BasicClass4)
    assert swift_obj == SwiftClass(
        object_name='BasicClass4',
        module='samples.basic',
        static_vars=[],
        instance_vars=[NameAndType('p', int)],
        init_params=[[]],
        methods=[
            Function(name='f',
                     args=[NameAndType('x', int),
                           NameAndType('y', int, 3)],
                     return_type=None,
                     cls='instancemethod')
        ],
        magic_methods=mock.ANY,
    )
def a_typed_param(source: str, i: int) -> Tuple[NameAndType, int]:
    identifier, i = a_id(source, i)
    i = a_whitespace(source, i, optional=True)
    i = a_str(source, i, ':')
    i = a_whitespace(source, i, optional=True)
    t, i = a_get_type(source, i)
    i = a_whitespace(source, i, optional=True)
    return NameAndType(name=identifier, type=t), i
def test_a_def():
    code = """def f(a: int, b: Tuple[float, int]) -> float: ..."""
    assert a_def('AClass', code) == Function(
        name='f',
        args=[NameAndType('a', int),
              NameAndType('b', Tuple[float, int])],
        cls='AClass',
        return_type=float,
    )

    code = """def f(a: int, b: Tuple[float, int]):
     ..."""
    assert a_def('AClass', code) == Function(
        name='f',
        args=[NameAndType('a', int),
              NameAndType('b', Tuple[float, int])],
        cls='AClass',
        return_type=None,
    )
def test_a_typed_param():
    code = 'a: int, '
    nt, i = a_typed_param(code, 0)
    assert get_tk(code, i) == ','
    assert nt.name == 'a'
    assert nt.type == int
    code = 'a:Tuple[ float ,float ])'
    nt, i = a_typed_param(code, 0)
    assert get_tk(code, i) == ')'
    assert nt == NameAndType(name='a', type=Tuple[float, float])
Exemplo n.º 10
0
def create_module_orm(module) -> SwiftModule:
    return SwiftModule(
        module_name=module.__name__,
        vars=[
            NameAndType(name=k, type=v)
            for k, v in getattr(module, '__annotations__', {}).items()
        ],
        functions=get_module_functions(module),
        classes=get_module_classes(module),
    )
def test_parse_overloads():
    code = """\
from typing import overload

@overload
def f(x: int) -> 'int': ...
@overload
def f(x: float) -> float: ...

class A:
    @overload
    def f(self, x: str) -> str:
        ...
        
    @overload
    def f(self, x: bool) -> bool:
        ...
"""
    assert parse_overloads(code,
                           indentation=0,
                           module_or_class_name='test_module') == [
                               Function(name='f',
                                        args=[NameAndType('x', int)],
                                        cls='test_module',
                                        return_type=int),
                               Function(name='f',
                                        args=[NameAndType('x', float)],
                                        cls='test_module',
                                        return_type=float),
                           ]

    assert parse_overloads(code, indentation=1, module_or_class_name='A') == [
        Function(name='f',
                 args=[NameAndType('x', str)],
                 cls='A',
                 return_type=str),
        Function(name='f',
                 args=[NameAndType('x', bool)],
                 cls='A',
                 return_type=bool),
    ]
Exemplo n.º 12
0
def create_class_orm(cls) -> SwiftClass:
    static_vars = [
        NameAndType(name=k, type=v)
        for k, v in getattr(cls, '__annotations__', {}).items()
        if getattr(cls, k, False)
    ]
    instance_vars = \
        ([NameAndType(name=x, type=None) for x in cls.__slots__] if hasattr(cls, '__slots__') else []) + \
        [NameAndType(name=k, type=v) for k, v in getattr(cls, '__annotations__', {}).items()] + \
        [NameAndType(name, type=getattr(prop.fget, '__annotations__', {}).get('return')) for name, prop in inspect.getmembers(cls, lambda o: isinstance(o, property))]
    init_params = get_init_params(cls)
    return SwiftClass(object_name=cls.__name__,
                      module=cls.__module__,
                      static_vars=static_vars,
                      instance_vars=instance_vars,
                      init_params=init_params,
                      methods=get_functions(cls),
                      magic_methods=get_magic_methods(cls),
                      positional_args='CPython'
                      in get_swift_wrapper_annotations(cls),
                      generic=getattr(cls, '__orig_bases__', [None])[0])
Exemplo n.º 13
0
def test_complex_create_object_orm4():
    swift_obj = create_class_orm(ComplexClass4)
    assert swift_obj == SwiftClass(
        object_name='ComplexClass4',
        module='samples.complex',
        static_vars=[],
        instance_vars=[
            NameAndType('a', int),
            NameAndType('b', mock.ANY),
            NameAndType('shape', mock.ANY)
        ],
        init_params=[[NameAndType('a', int),
                      NameAndType('b', mock.ANY)]],
        methods=[
            Function(name='identity',
                     args=[NameAndType('val', mock.ANY)],
                     return_type=mock.ANY,
                     cls='instancemethod'),
        ],
        magic_methods=mock.ANY,
        generic=mock.ANY,
        positional_args=False,
    )
    identity = swift_obj.methods[0]
    assert identity.mapped_return_type == 'TPList<V>'
    assert identity.args[0].mapped_type == 'TPList<V>'
    shape = swift_obj.instance_vars[2]
    assert shape.type == Tuple[int, swift_obj.type_vars[0]]
    assert swift_obj.render_type_vars() == '<T: TPobject>'
Exemplo n.º 14
0
def test_complex_create_object_orm1():
    swift_obj = create_class_orm(ComplexClass1)
    assert swift_obj == SwiftClass(
        object_name='ComplexClass1',
        module='samples.complex',
        static_vars=[],
        instance_vars=[],
        init_params=[[]],
        methods=[
            Function(name='f',
                     args=[
                         NameAndType('x', int),
                         NameAndType('y', int),
                         NameAndType('z', float)
                     ],
                     return_type=float,
                     cls='instancemethod'),
            Function(name='f',
                     args=[
                         NameAndType('x', int),
                         NameAndType('y', float),
                         NameAndType('z', float)
                     ],
                     return_type=float,
                     cls='instancemethod'),
        ],
        magic_methods=mock.ANY,
    )
Exemplo n.º 15
0
def get_module_functions(module) -> List[Function]:
    functions = [
        Function(
            name=func.__name__,
            args=[
                NameAndType(name=k, type=v)
                for k, v in func.__annotations__.items() if k != 'return'
            ],
            cls='modulefunction',
            return_type=func.__annotations__.get('return'),
        ) for func in [
            obj[1] for obj in inspect.getmembers(module)
            if inspect.isfunction(obj[1])
            and not obj[1].__name__ in ['overload', '_overload_dummy']
        ]
    ]
    overloads = get_overloads(module, is_module=True)
    functions = [
        x for x in functions if x.name not in {f.name
                                               for f in overloads}
    ] + overloads
    return flatten_functions(functions)
Exemplo n.º 16
0
def flatten_functions(functions) -> List[Function]:
    result = []
    for f in functions:
        flattened_args = [[]]
        for arg in f.args:
            if arg.type.__class__ == type(Union):
                new_flattened_args = []
                for t in arg.type.__args__:
                    flattened_args_copy = deepcopy(flattened_args)
                    for l in flattened_args_copy:
                        l.append(NameAndType(arg.name, t))
                    new_flattened_args = new_flattened_args + flattened_args_copy
                flattened_args = new_flattened_args
            else:
                for l in flattened_args:
                    l.append(arg)
        for l in flattened_args:
            result.append(
                Function(name=f.name,
                         args=l,
                         cls=f.cls,
                         return_type=f.return_type))
    return result
Exemplo n.º 17
0
def test_complex_create_object_orm3():
    swift_obj = create_class_orm(ComplexClass3)
    assert swift_obj == SwiftClass(
        object_name='ComplexClass3',
        module='samples.complex',
        static_vars=[],
        instance_vars=[],
        init_params=[[]],
        methods=[
            Function(name='foo',
                     args=[NameAndType('x', List[str])],
                     return_type=List[str],
                     cls='instancemethod'),
        ],
        magic_methods=mock.ANY,
        positional_args=True,
    )
    assert swift_obj.methods[0].mapped_return_type == 'TPList<TPstr>'
    assert swift_obj.magic_methods.expressible_by_literals == [
        ExpressibleByLiteralProtocol('ExpressibleByIntegerLiteral',
                                     literal_type='Int'),
        ExpressibleByLiteralProtocol('ExpressibleByFloatLiteral',
                                     literal_type='Double'),
    ]
Exemplo n.º 18
0
def test_simple_create_object_orm():
    assert create_class_orm(BasicClass) == SwiftClass(
        object_name='BasicClass',
        module='samples.basic',
        static_vars=[NameAndType(name='dimensions', type=int)],
        instance_vars=[
            NameAndType(name='x', type=None),
            NameAndType(name='y', type=None),
            NameAndType('dimensions', type=int)
        ],
        init_params=[[
            NameAndType(name='x', type=float),
            NameAndType(name='y', type=float)
        ]],
        methods=[
            Function(name='magnitude',
                     args=[],
                     return_type=float,
                     cls='instancemethod')
        ],
        magic_methods=mock.ANY,
    )