phasm/phasm/type3/functions.py
Johan B.W. de Vries c8009403c4 Separates out TypeVariable and constraints
They look a lot like placeholders, but they exist before
the typing system takes place. And there's a (much smaller)
context to deal with.

For now, removes Placeholders in user function definitions
as they were not implemented.

Adds signature to function to try to get them closer to
type class methods. Already seeing some benefit in the
constraint generator.

Stricter zipping for safety.
2025-04-27 15:28:08 +02:00

68 lines
1.9 KiB
Python

from typing import TYPE_CHECKING, Any, Iterable, List, Union
if TYPE_CHECKING:
from .typeclasses import Type3Class
from .types import Type3
class TypeVariable:
"""
Types variable are used in function definition.
They are used in places where you don't know the exact type.
They are different from PlaceholderForType, as those are instanced
during type checking. These type variables are used solely in the
function's definition
"""
__slots__ = ('letter', )
letter: str
def __init__(self, letter: str) -> None:
assert len(letter) == 1, f'{letter} is not a valid type variable'
self.letter = letter
def __hash__(self) -> int:
return hash(self.letter)
def __eq__(self, other: Any) -> bool:
if not isinstance(other, TypeVariable):
raise NotImplementedError
return self.letter == other.letter
def __repr__(self) -> str:
return f'TypeVariable({repr(self.letter)})'
class TypeVariableConstraintBase:
__slots__ = ()
class TypeVariableConstraint_TypeHasTypeClass(TypeVariableConstraintBase):
__slots__ = ('type_class3', )
def __init__(self, type_class3: 'Type3Class') -> None:
self.type_class3 = type_class3
class TypeVariableContext:
__slots__ = ('constraints', )
constraints: dict[TypeVariable, list[TypeVariableConstraintBase]]
def __init__(self) -> None:
self.constraints = {}
def __copy__(self) -> 'TypeVariableContext':
result = TypeVariableContext()
result.constraints.update(self.constraints)
return result
class FunctionSignature:
__slots__ = ('context', 'args', )
context: TypeVariableContext
args: List[Union['Type3', TypeVariable]]
def __init__(self, context: TypeVariableContext, args: Iterable[Union['Type3', TypeVariable]]) -> None:
self.context = context.__copy__()
self.args = list(args)