Compare commits

..

No commits in common. "bee0c845a834669f0f21ebc6b9df9c38bcc9cce0" and "a2e1dfd799515d2ddf286a301f03ada295ef2c68" have entirely different histories.

15 changed files with 121 additions and 287 deletions

View File

@ -29,6 +29,7 @@
- Implemented Bounded: https://hackage.haskell.org/package/base-4.21.0.0/docs/Prelude.html#t:Bounded
- Try to implement the min and max functions using select
- Filter out methods that aren't used; other the other way around (easier?) only add __ methods when needed
- Move UnaryOp.operator into type class methods
- Move foldr into type class methods
- PrimitiveType is just the type, nothing primitive about it (change the name). u32 are still basic types or something.
- Clean up Subscript implementation - it's half implemented in the compiler. Makes more sense to move more parts to stdlib_types.

View File

@ -51,7 +51,7 @@ _CRC32_Table: u32[256] = (
)
def _crc32_f(crc: u32, byt: u8) -> u32:
return (crc >> 8) ^ _CRC32_Table[(crc & 0xFF) ^ extend(byt)]
return (crc >> 8) ^ _CRC32_Table[(crc & 0xFF) ^ u32(byt)]
@exported
def crc32(data: bytes) -> u32:

View File

@ -75,6 +75,16 @@ def expression(inp: ourlang.Expression) -> str:
if isinstance(inp, ourlang.VariableReference):
return str(inp.variable.name)
if isinstance(inp, ourlang.UnaryOp):
if inp.operator == 'cast':
mtyp = type3(inp.type3)
if mtyp is None:
raise NotImplementedError(f'Casting to type {inp.type_var}')
return f'{mtyp}({expression(inp.right)})'
return f'{inp.operator}{expression(inp.right)}'
if isinstance(inp, ourlang.BinaryOp):
return f'{expression(inp.left)} {inp.operator.name} {expression(inp.right)}'

View File

@ -237,28 +237,6 @@ INSTANCES = {
prelude.Sized_.methods['len']: {
'a=bytes': stdlib_types.bytes_sized_len,
},
prelude.Extendable.methods['extend']: {
'a=u8,b=u32': stdlib_types.u8_u32_extend,
'a=u8,b=u64': stdlib_types.u8_u64_extend,
'a=u32,b=u64': stdlib_types.u32_u64_extend,
'a=i8,b=i32': stdlib_types.i8_i32_extend,
'a=i8,b=i64': stdlib_types.i8_i64_extend,
'a=i32,b=i64': stdlib_types.i32_i64_extend,
},
prelude.Extendable.methods['wrap']: {
'a=u8,b=u32': stdlib_types.u8_u32_wrap,
'a=u8,b=u64': stdlib_types.u8_u64_wrap,
'a=u32,b=u64': stdlib_types.u32_u64_wrap,
'a=i8,b=i32': stdlib_types.i8_i32_wrap,
'a=i8,b=i64': stdlib_types.i8_i64_wrap,
'a=i32,b=i64': stdlib_types.i32_i64_wrap,
},
prelude.Promotable.methods['promote']: {
'a=f32,b=f64': stdlib_types.f32_f64_promote,
},
prelude.Promotable.methods['demote']: {
'a=f32,b=f64': stdlib_types.f32_f64_demote,
},
}
def phasm_compile(inp: ourlang.Module) -> wasm.Module:
@ -479,6 +457,18 @@ def expression(wgn: WasmGenerator, inp: ourlang.Expression) -> None:
raise NotImplementedError(inp.operator, instance_key)
if isinstance(inp, ourlang.UnaryOp):
expression(wgn, inp.right)
assert isinstance(inp.type3, type3types.Type3), type3placeholders.TYPE3_ASSERTION_ERROR
if inp.operator == 'cast':
if inp.type3 == prelude.u32 and inp.right.type3 == prelude.u8:
# Nothing to do, you can use an u8 value as a u32 no problem
return
raise NotImplementedError(expression, inp.type3, inp.operator)
if isinstance(inp, ourlang.FunctionCall):
for arg in inp.arguments:
expression(wgn, arg)
@ -497,7 +487,7 @@ def expression(wgn: WasmGenerator, inp: ourlang.Expression) -> None:
instance_key = ','.join(
f'{k.letter}={v.name}'
for k, v in sorted(type_var_map.items(), key=lambda x: x[0].letter)
for k, v in type_var_map.items()
)
instance = INSTANCES.get(inp.function, {}).get(instance_key, None)

View File

@ -127,6 +127,21 @@ class VariableReference(Expression):
super().__init__()
self.variable = variable
class UnaryOp(Expression):
"""
A unary operator expression within a statement
"""
__slots__ = ('operator', 'right', )
operator: str
right: Expression
def __init__(self, operator: str, right: Expression) -> None:
super().__init__()
self.operator = operator
self.right = right
class BinaryOp(Expression):
"""
A binary operator expression within a statement

View File

@ -29,6 +29,7 @@ from .ourlang import (
StructDefinition,
Subscript,
TupleInstantiation,
UnaryOp,
VariableReference,
)
from .prelude import PRELUDE_METHODS, PRELUDE_OPERATORS, PRELUDE_TYPES
@ -388,6 +389,19 @@ class OurVisitor:
self.visit_Module_FunctionDef_expr(module, function, our_locals, node.right),
)
if isinstance(node, ast.UnaryOp):
if isinstance(node.op, ast.UAdd):
operator = '+'
elif isinstance(node.op, ast.USub):
operator = '-'
else:
raise NotImplementedError(f'Operator {node.op}')
return UnaryOp(
operator,
self.visit_Module_FunctionDef_expr(module, function, our_locals, node.operand),
)
if isinstance(node, ast.Compare):
if 1 < len(node.ops):
raise NotImplementedError('Multiple operators')
@ -462,7 +476,7 @@ class OurVisitor:
raise NotImplementedError(f'{node} as expr in FunctionDef')
def visit_Module_FunctionDef_Call(self, module: Module, function: Function, our_locals: OurLocals, node: ast.Call) -> Union[Fold, FunctionCall]:
def visit_Module_FunctionDef_Call(self, module: Module, function: Function, our_locals: OurLocals, node: ast.Call) -> Union[Fold, FunctionCall, UnaryOp]:
if node.keywords:
_raise_static_error(node, 'Keyword calling not supported') # Yet?
@ -475,6 +489,16 @@ class OurVisitor:
if node.func.id in PRELUDE_METHODS:
func = PRELUDE_METHODS[node.func.id]
elif node.func.id == 'u32':
if 1 != len(node.args):
_raise_static_error(node, f'Function {node.func.id} requires 1 arguments but {len(node.args)} are given')
unary_op = UnaryOp(
'cast',
self.visit_Module_FunctionDef_expr(module, function, our_locals, node.args[0]),
)
unary_op.type3 = prelude.u32
return unary_op
elif node.func.id == 'foldl':
if 3 != len(node.args):
_raise_static_error(node, f'Function {node.func.id} requires 3 arguments but {len(node.args)} are given')

View File

@ -14,12 +14,12 @@ from ..type3.types import (
PRELUDE_TYPE_CLASS_INSTANCES_EXISTING: set[tuple[Type3Class, tuple[Type3, ...]]] = set()
def instance_type_class(cls: Type3Class, *typ: Type3) -> None:
def instance_type_class(cls: Type3Class, typ: Type3) -> None:
global PRELUDE_TYPE_CLASS_INSTANCES_EXISTING
# TODO: Check for required existing instantiations
PRELUDE_TYPE_CLASS_INSTANCES_EXISTING.add((cls, tuple(typ), ))
PRELUDE_TYPE_CLASS_INSTANCES_EXISTING.add((cls, (typ, ), ))
none = Type3('none')
"""
@ -141,7 +141,6 @@ PRELUDE_TYPES: dict[str, Type3] = {
}
a = TypeVariable('a')
b = TypeVariable('b')
InternalPassAsPointer = Type3Class('InternalPassAsPointer', [a], methods={}, operators={})
@ -267,25 +266,6 @@ Sized_ = Type3Class('Sized', [a], methods={
instance_type_class(Sized_, bytes_)
Extendable = Type3Class('Extendable', [a, b], methods={
'extend': [a, b],
'wrap': [b, a],
}, operators={})
instance_type_class(Extendable, u8, u32)
instance_type_class(Extendable, u8, u64)
instance_type_class(Extendable, u32, u64)
instance_type_class(Extendable, i8, i32)
instance_type_class(Extendable, i8, i64)
instance_type_class(Extendable, i32, i64)
Promotable = Type3Class('Promotable', [a, b], methods={
'promote': [a, b],
'demote': [b, a],
}, operators={})
instance_type_class(Promotable, f32, f64)
PRELUDE_TYPE_CLASSES = {
'Eq': Eq,
'Ord': Ord,
@ -295,8 +275,6 @@ PRELUDE_TYPE_CLASSES = {
'Integral': Integral,
'Fractional': Fractional,
'Floating': Floating,
'Extendable': Extendable,
'Promotable': Promotable,
}
PRELUDE_OPERATORS = {
@ -319,6 +297,4 @@ PRELUDE_METHODS = {
**IntNum.methods,
**NatNum.methods,
**Sized_.methods,
**Extendable.methods,
**Promotable.methods,
}

View File

@ -865,59 +865,3 @@ def f64_intnum_neg(g: Generator) -> None:
def bytes_sized_len(g: Generator) -> None:
# The length is stored in the first 4 bytes
g.i32.load()
## ###
## Extendable
def u8_u32_extend(g: Generator) -> None:
# No-op
# u8 is already stored as u32
pass
def u8_u64_extend(g: Generator) -> None:
g.i64.extend_i32_u()
def u32_u64_extend(g: Generator) -> None:
g.i64.extend_i32_u()
def i8_i32_extend(g: Generator) -> None:
# No-op
# i8 is already stored as i32
pass
def i8_i64_extend(g: Generator) -> None:
g.i64.extend_i32_s()
def i32_i64_extend(g: Generator) -> None:
g.i64.extend_i32_s()
def u8_u32_wrap(g: Generator) -> None:
g.i32.const(0xFF)
g.i32.and_()
def u8_u64_wrap(g: Generator) -> None:
g.i32.wrap_i64()
g.i32.const(0xFF)
g.i32.and_()
def u32_u64_wrap(g: Generator) -> None:
g.i32.wrap_i64()
def i8_i32_wrap(g: Generator) -> None:
g.i32.const(0xFF)
g.i32.and_()
def i8_i64_wrap(g: Generator) -> None:
g.i32.wrap_i64()
def i32_i64_wrap(g: Generator) -> None:
g.i32.wrap_i64()
## ###
## Promotable
def f32_f64_promote(g: Generator) -> None:
g.f64.promote_f32()
def f32_f64_demote(g: Generator) -> None:
g.f32.demote_f64()

View File

@ -197,6 +197,50 @@ class TupleMatchConstraint(ConstraintBase):
raise NotImplementedError(exp_type)
class CastableConstraint(ConstraintBase):
"""
A type can be cast to another type
"""
__slots__ = ('from_type3', 'to_type3', )
from_type3: placeholders.Type3OrPlaceholder
to_type3: placeholders.Type3OrPlaceholder
def __init__(self, from_type3: placeholders.Type3OrPlaceholder, to_type3: placeholders.Type3OrPlaceholder, comment: Optional[str] = None) -> None:
super().__init__(comment=comment)
self.from_type3 = from_type3
self.to_type3 = to_type3
def check(self) -> CheckResult:
ftyp = self.from_type3
if isinstance(ftyp, placeholders.PlaceholderForType) and ftyp.resolve_as is not None:
ftyp = ftyp.resolve_as
ttyp = self.to_type3
if isinstance(ttyp, placeholders.PlaceholderForType) and ttyp.resolve_as is not None:
ttyp = ttyp.resolve_as
if isinstance(ftyp, placeholders.PlaceholderForType) or isinstance(ttyp, placeholders.PlaceholderForType):
return RequireTypeSubstitutes()
if ftyp is prelude.u8 and ttyp is prelude.u32:
return None
return Error(f'Cannot cast {ftyp.name} to {ttyp.name}')
def human_readable(self) -> HumanReadableRet:
return (
'{to_type3}({from_type3})',
{
'to_type3': self.to_type3,
'from_type3': self.from_type3,
},
)
def __repr__(self) -> str:
return f'CastableConstraint({repr(self.from_type3)}, {repr(self.to_type3)}, comment={repr(self.comment)})'
class MustImplementTypeClassConstraint(ConstraintBase):
"""
A type must implement a given type class

View File

@ -12,6 +12,7 @@ from . import typeclasses as typeclasses
from . import types as type3types
from .constraints import (
CanBeSubscriptedConstraint,
CastableConstraint,
ConstraintBase,
Context,
LiteralFitsConstraint,
@ -48,6 +49,14 @@ def expression(ctx: Context, inp: ourlang.Expression) -> ConstraintGenerator:
comment=f'typeOf("{inp.variable.name}") == typeOf({inp.variable.name})')
return
if isinstance(inp, ourlang.UnaryOp):
if 'cast' == inp.operator:
yield from expression(ctx, inp.right)
yield CastableConstraint(inp.right.type3, inp.type3)
return
raise NotImplementedError(expression, inp, inp.operator)
if isinstance(inp, ourlang.BinaryOp) or isinstance(inp, ourlang.FunctionCall):
signature = inp.operator.signature if isinstance(inp, ourlang.BinaryOp) else inp.function.signature
arguments = [inp.left, inp.right] if isinstance(inp, ourlang.BinaryOp) else inp.arguments

View File

@ -74,9 +74,6 @@ class Generator_i32(Generator_i32i64):
def __init__(self, generator: 'Generator') -> None:
super().__init__('i32', generator)
# 2.4.1. Numeric Instructions
self.wrap_i64 = functools.partial(self.generator.add_statement, 'i32.wrap_i64')
class Generator_i64(Generator_i32i64):
def __init__(self, generator: 'Generator') -> None:
super().__init__('i64', generator)
@ -135,16 +132,10 @@ class Generator_f32(Generator_f32f64):
def __init__(self, generator: 'Generator') -> None:
super().__init__('f32', generator)
# 2.4.1 Numeric Instructions
self.demote_f64 = functools.partial(self.generator.add_statement, 'f32.demote_f64')
class Generator_f64(Generator_f32f64):
def __init__(self, generator: 'Generator') -> None:
super().__init__('f64', generator)
# 2.4.1 Numeric Instructions
self.promote_f32 = functools.partial(self.generator.add_statement, 'f64.promote_f32')
class Generator_Local:
def __init__(self, generator: 'Generator') -> None:
self.generator = generator

View File

@ -264,13 +264,6 @@ def _load_memory_stored_returned_value(
if ret_type3 in (prelude.i8, prelude.i32, prelude.i64):
assert isinstance(wasm_value, int), wasm_value
if ret_type3 is prelude.i8:
# Values are actually i32
# Have to reinterpret to load proper value
data = struct.pack('<i', wasm_value)
wasm_value, = struct.unpack('<bxxx', data)
return wasm_value
if ret_type3 in (prelude.u8, prelude.u32, prelude.u64):

View File

@ -49,7 +49,7 @@ def testEntry(a: bytes, b: bytes) -> u8:
def test_foldl_3():
code_py = """
def xor(l: u32, r: u8) -> u32:
return l ^ extend(r)
return l ^ u32(r)
@exported
def testEntry(a: bytes) -> u32:

View File

@ -1,112 +0,0 @@
import pytest
from phasm.type3.entry import Type3Exception
from ..helpers import Suite
EXTENTABLE = [
('u8', 'u32', ),
('u8', 'u64', ),
('u32', 'u64', ),
('i8', 'i32', ),
('i8', 'i64', ),
('i32', 'i64', ),
]
@pytest.mark.integration_test
def test_extend_not_implemented():
code_py = """
class Foo:
val: i32
class Baz:
val: i32
@exported
def testEntry(x: Foo) -> Baz:
return extend(x)
"""
with pytest.raises(Type3Exception, match='Missing type class instantation: Extendable Foo Baz'):
Suite(code_py).run_code()
@pytest.mark.integration_test
@pytest.mark.parametrize('ext_from,ext_to', EXTENTABLE)
def test_extend_ok(ext_from,ext_to):
code_py = f"""
CONSTANT: {ext_from} = 10
@exported
def testEntry() -> {ext_to}:
return extend(CONSTANT)
"""
result = Suite(code_py).run_code()
assert 10 == result.returned_value
@pytest.mark.integration_test
@pytest.mark.parametrize('ext_from,in_put,ext_to,exp_out', [
('u8', 241, 'u32', 241),
('u32', 4059165169, 'u64', 4059165169),
('u8', 241, 'u64', 241),
('i8', 113, 'i32', 113),
('i32', 1911681521, 'i64', 1911681521),
('i8', 113, 'i64', 113),
('i8', -15, 'i32', -15),
('i32', -15, 'i64', -15),
('i8', -15, 'i64', -15),
])
def test_extend_results(ext_from, ext_to, in_put, exp_out):
code_py = f"""
@exported
def testEntry(x: {ext_from}) -> {ext_to}:
return extend(x)
"""
result = Suite(code_py).run_code(in_put)
assert exp_out == result.returned_value
@pytest.mark.integration_test
@pytest.mark.parametrize('ext_from,ext_to', EXTENTABLE)
def test_wrap_ok(ext_from,ext_to):
code_py = f"""
CONSTANT: {ext_to} = 10
@exported
def testEntry() -> {ext_from}:
return wrap(CONSTANT)
"""
result = Suite(code_py).run_code()
assert 10 == result.returned_value
@pytest.mark.integration_test
@pytest.mark.parametrize('ext_to,in_put,ext_from,exp_out', [
('u32', 0xF1F1F1F1, 'u8', 0xF1),
('u64', 0xF1F1F1F1F1F1F1F1, 'u32', 0xF1F1F1F1),
('u64', 0xF1F1F1F1F1F1F1F1, 'u8', 0xF1),
('i32', 0xF1F1F171, 'i8', 113),
('i32', 0xF1F1F1F1, 'i8', -15),
('i64', 0x71F1F1F171F1F1F1, 'i32', 1911681521),
('i64', 0x71F1F1F1F1F1F1F1, 'i32', -235802127),
('i64', 0xF1F1F1F1F1F1F171, 'i8', 113),
('i64', 0xF1F1F1F1F1F1F1F1, 'i8', -15),
])
def test_wrap_results(ext_from, ext_to, in_put, exp_out):
code_py = f"""
@exported
def testEntry(x: {ext_to}) -> {ext_from}:
return wrap(x)
"""
result = Suite(code_py).run_code(in_put)
assert exp_out == result.returned_value

View File

@ -1,51 +0,0 @@
import pytest
from phasm.type3.entry import Type3Exception
from ..helpers import Suite
@pytest.mark.integration_test
def test_promote_not_implemented():
code_py = """
class Foo:
val: i32
class Baz:
val: i32
@exported
def testEntry(x: Foo) -> Baz:
return promote(x)
"""
with pytest.raises(Type3Exception, match='Missing type class instantation: Promotable Foo Baz'):
Suite(code_py).run_code()
@pytest.mark.integration_test
def test_promote_ok():
code_py = """
CONSTANT: f32 = 10.5
@exported
def testEntry() -> f64:
return promote(CONSTANT)
"""
result = Suite(code_py).run_code()
assert 10.5 == result.returned_value
@pytest.mark.integration_test
def test_demote_ok():
code_py = """
CONSTANT: f64 = 10.5
@exported
def testEntry() -> f32:
return demote(CONSTANT)
"""
result = Suite(code_py).run_code()
assert 10.5 == result.returned_value