-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathnative_function.py
52 lines (46 loc) · 1.69 KB
/
native_function.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import inspect
from function import Function
from type_check_error import display_type
from native_types import n_cmd_type
from ncmd import Cmd
class NativeFunction(Function):
def __init__(
self, scope, arguments, return_type, function, argument_cache=None, public=False
):
super(NativeFunction, self).__init__(
scope, arguments, return_type, None, public=public
)
self.function = function
self.argument_cache = argument_cache or []
async def run(self, arguments):
arguments = self.argument_cache + arguments
if len(arguments) < len(self.arguments):
return NativeFunction(
self.scope,
self.arguments,
self.returntype,
self.function,
argument_cache=self.argument_cache + arguments,
)
maybe_awaitable = self.function(*arguments)
if inspect.isawaitable(maybe_awaitable):
return await maybe_awaitable
else:
return maybe_awaitable
def __str__(self):
return display_type(self.arguments, False)
@classmethod
def from_imported(cls, scope, types, function, pass_scope):
if not isinstance(types, tuple):
# Exported value is not a function
return function
*arg_types, return_type = types
if pass_scope:
function = function(scope)
if n_cmd_type.is_type(return_type):
run_function = lambda *args: Cmd(lambda _: lambda: function(*args))
else:
run_function = function
return cls(
scope, [("whatever", typ) for typ in arg_types], return_type, run_function
)