refactor(checker): move builtins definition to separate file
This commit is contained in:
39
midas/resolver/builtin.py
Normal file
39
midas/resolver/builtin.py
Normal file
@@ -0,0 +1,39 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from midas.checker.types import BaseType, Type
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from midas.resolver.midas import MidasResolver
|
||||
|
||||
|
||||
def basic_op(ctx: MidasResolver, type: Type, op: str):
|
||||
ctx.define_operation(
|
||||
left=type,
|
||||
operator=op,
|
||||
right=type,
|
||||
result=type,
|
||||
)
|
||||
|
||||
|
||||
def define_builtins(ctx: MidasResolver):
|
||||
"""Define builtin types and operations"""
|
||||
bool = ctx.define_type("bool", BaseType(name="bool"))
|
||||
int = ctx.define_type("int", BaseType(name="int"))
|
||||
float = ctx.define_type("float", BaseType(name="float"))
|
||||
str = ctx.define_type("str", BaseType(name="str"))
|
||||
|
||||
basic_op(ctx, int, "__add__")
|
||||
basic_op(ctx, int, "__sub__")
|
||||
basic_op(ctx, int, "__mul__")
|
||||
basic_op(ctx, int, "__pow__")
|
||||
basic_op(ctx, int, "__mod__")
|
||||
basic_op(ctx, int, "__and__")
|
||||
basic_op(ctx, int, "__or__")
|
||||
basic_op(ctx, int, "__xor__")
|
||||
basic_op(ctx, float, "__add__")
|
||||
basic_op(ctx, float, "__sub__")
|
||||
basic_op(ctx, float, "__mul__")
|
||||
basic_op(ctx, float, "__truediv__")
|
||||
basic_op(ctx, str, "__add__")
|
||||
@@ -2,6 +2,7 @@ from typing import Optional
|
||||
|
||||
import midas.ast.midas as m
|
||||
from midas.checker.types import BaseType, SimpleType, Type
|
||||
from midas.resolver.builtin import define_builtins
|
||||
|
||||
|
||||
class MidasResolver(m.Stmt.Visitor[None], m.Expr.Visitor[Type]):
|
||||
@@ -11,7 +12,7 @@ class MidasResolver(m.Stmt.Visitor[None], m.Expr.Visitor[Type]):
|
||||
self._types: dict[str, Type] = {}
|
||||
self._operations: dict[tuple[Type, str, Type], Type] = {}
|
||||
|
||||
self._define_builtin()
|
||||
define_builtins(self)
|
||||
|
||||
def get_type(self, name: str) -> Type:
|
||||
"""Get a type from its name
|
||||
@@ -47,19 +48,6 @@ class MidasResolver(m.Stmt.Visitor[None], m.Expr.Visitor[Type]):
|
||||
result: Optional[Type] = self._operations.get(operation)
|
||||
return result
|
||||
|
||||
def _define_builtin(self):
|
||||
"""Define builtin types and operations"""
|
||||
self.define_type("bool", BaseType(name="bool"))
|
||||
self.define_type("int", BaseType(name="int"))
|
||||
self.define_type("float", BaseType(name="float"))
|
||||
self.define_type("str", BaseType(name="str"))
|
||||
self.define_operation(
|
||||
left=self.get_type("int"),
|
||||
operator="__add__",
|
||||
right=self.get_type("int"),
|
||||
result=self.get_type("int"),
|
||||
)
|
||||
|
||||
def define_type(self, name: str, type: Type) -> Type:
|
||||
"""Define a type in the registry
|
||||
|
||||
|
||||
Reference in New Issue
Block a user