more ideas [skip-ci]

This commit is contained in:
Johan B.W. de Vries 2021-04-05 14:40:18 +02:00
parent 58bd5f0889
commit 07aeb52560
3 changed files with 57 additions and 5 deletions

View File

@ -72,7 +72,37 @@ class Visitor:
return wasm.Import(module, name, intname, _parse_import_args(node.args))
return wasm.Function(node.name, exported)
result = _parse_annotation(node.returns)
statements = [
self.visit_stmt(node, stmt)
for stmt in node.body
]
return wasm.Function(node.name, exported, result, statements)
def visit_stmt(self, func: ast.FunctionDef, stmt: ast.stmt) -> wasm.Statement:
"""
Visits a statement node
"""
if isinstance(stmt, ast.Return):
return self.visit_Return(func, stmt)
raise NotImplementedError
def visit_Return(self, func: ast.FunctionDef, stmt: ast.Return) -> wasm.Statement:
"""
Visits a statement node
"""
assert isinstance(stmt.value, ast.Constant)
assert isinstance(stmt.value.value, int)
return_type = _parse_annotation(func.returns)
return wasm.Statement(
'{}.const'.format(return_type),
str(stmt.value.value)
)
def _parse_import_decorator(func_name: str, args: List[ast.expr]) -> Tuple[str, str, str]:
"""

View File

@ -2,7 +2,7 @@
Python classes for storing the representation of Web Assembly code
"""
from typing import Iterable, List, Tuple
from typing import Iterable, List, Optional, Tuple
class Import:
"""
@ -49,12 +49,18 @@ class Function:
"""
Represents a Web Assembly function
"""
def __init__(self, name: str, exported: bool = True) -> None:
def __init__(
self,
name: str,
exported: bool,
result: Optional[str],
statements: Iterable[Statement],
) -> None:
self.name = name
self.exported = exported
self.params: List[Tuple[str, str]] = []
self.returns = None
self.statements: List[Statement] = []
self.result = result
self.statements = [*statements]
def generate(self) -> str:
"""
@ -65,6 +71,9 @@ class Function:
for nam, typ in self.params:
header += ' (param ${} {})'.format(nam, typ)
if self.result:
header += ' (result {})'.format(self.result)
return '(func {}\n {})'.format(
header,
'\n '.join(x.generate() for x in self.statements),

View File

@ -0,0 +1,13 @@
from .helpers import Suite
def test_return():
code_py = """
@exported
def testEntry() -> i32:
return 13
"""
result = Suite(code_py, 'test_fib').run_code()
assert 13 is result.returned_value
assert [] == result.log_int32_list