Last active
November 13, 2021 06:52
-
-
Save SaidBySolo/96d7b645413af30d8a439837faa2d4f5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from hashlib import md5 | |
from typing import Any, Coroutine, Union, cast | |
from js2py.evaljs import EvalJs # type: ignore | |
from js2py.translators.translating_nodes import trans # type: ignore | |
from js2py.translators.translator import DEFAULT_HEADER # type: ignore | |
def make_js_program(body: list[Any]) -> dict[str, Any]: | |
return {"type": "Program", "body": body} | |
def translate_tree(tree: dict[str, Any], HEADER: str = DEFAULT_HEADER) -> str: | |
return HEADER + cast(str, trans(tree)) | |
class ExtendEvalJS(EvalJs): # type: ignore | |
def exec_pycode(self, code: str) -> None: | |
try: | |
cache = self.__dict__["cache"] | |
except KeyError: | |
cache = self.__dict__["cache"] = {} | |
hashkey = md5(code.encode("utf-8")).digest() | |
try: | |
compiled: Union[Any, Any] = cache[hashkey] | |
except KeyError: | |
compiled = cache[hashkey] = compile(code, "<EvalJS snippet>", "exec") | |
exec(compiled, self._context) | |
add_function = { | |
"type": "FunctionDeclaration", | |
"id": {"type": "Identifier", "name": "add"}, | |
"params": [ | |
{"type": "Identifier", "name": "a"}, | |
{"type": "Identifier", "name": "b"}, | |
], | |
"defaults": [], | |
"body": { | |
"type": "BlockStatement", | |
"body": [ | |
{ | |
"type": "ReturnStatement", | |
"argument": { | |
"type": "BinaryExpression", | |
"operator": "+", | |
"left": {"type": "Identifier", "name": "a"}, | |
"right": {"type": "Identifier", "name": "b"}, | |
}, | |
} | |
], | |
}, | |
"generator": False, | |
"expression": False, | |
} | |
tree = make_js_program([add_function]) | |
pycode = translate_tree(tree, "") | |
context = ExtendEvalJS() | |
context.exec_pycode(pycode) | |
print(context.add(1, 2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment