diff options
Diffstat (limited to 'structs.py')
| -rw-r--r-- | structs.py | 86 |
1 files changed, 44 insertions, 42 deletions
@@ -59,6 +59,38 @@ class TokenType(Enum): LIST_TYPE = auto() +class TypeEnum(Enum): + ANY = auto() + STRING = auto() + INT = auto() + FLOAT = auto() + NUMBER = auto() + LIST = auto() + LITERAL = auto() + BOOL = auto() + + def __str__(self): + return f":{self.name.lower()}" + +TYPE_HIERARCHY = { TypeEnum.ANY: None, + TypeEnum.LITERAL: TypeEnum.ANY, + TypeEnum.LIST: TypeEnum.ANY, + TypeEnum.STRING: TypeEnum.LITERAL, + TypeEnum.BOOL: TypeEnum.LITERAL, + TypeEnum.NUMBER: TypeEnum.LITERAL, + TypeEnum.INT: TypeEnum.NUMBER, + TypeEnum.FLOAT: TypeEnum.NUMBER } + +def is_subtype_of(candidate, expected): + if candidate == expected: + return True + parent = TYPE_HIERARCHY[candidate] + while parent is not None: + if parent == expected: + return True + parent = TYPE_HIERARCHY[parent] + return False + @dataclass class Token: type_: TokenType @@ -69,67 +101,37 @@ class Token: def __str__(self): return f"{self.type_.name} {self.text} {self.line}" -class T: - def __repr__(self): - return "T" - class Any: - def __repr__(self): - return ":any" - class List(Any): - pass - class Literal(Any): - def __repr__(self): - return ":literal" - class String(Literal): - def __repr__(self): - return ":string" - pass - class Bool(Literal): - def __repr__(self): - return ":bool" - pass - class Number(Literal): - def __repr__(self): - return ":number" - class Int(Number): - def __repr__(self): - return ":int" - class Float(Number): - def __repr__(self): - return ":float" - -# Literals -class Literal(T.Any): +class Literal: def __init__(self, value, type_=None): self.value = value if type_ is None: - self.type_ = T.Any + self.type_ = TypeEnum.ANY else: self.type_ = type_ def __str__(self): return f"{self.value}:literal" -class Int(Literal, T.Int): +class Int(Literal): def __init__(self, value): - super().__init__(value, T.Int) + super().__init__(value, TypeEnum.INT) def __str__(self): return f"{self.value}" -class Float(Literal, T.Float): +class Float(Literal): def __init__(self, value): - super().__init__(value, T.Float) + super().__init__(value, TypeEnum.FLOAT) def __str__(self): return f"{self.value}" -class Bool(Literal, T.Bool): +class Bool(Literal): def __init__(self, value): - super().__init__(value, T.Bool) + super().__init__(value, TypeEnum.BOOL) def __str__(self): return f"#{str(self.value).lower()}" -class String(Literal, T.String): +class String(Literal): def __init__(self, value): - super().__init__(value, T.String) + super().__init__(value, TypeEnum.STRING) def __str__(self): return f'"{repr(self.value)[1:-1]}"' @@ -146,11 +148,11 @@ class Symbol: def __str__(self): return f"'{self.name}" -class List(T.List): +class List: def __init__(self, args, data=False): self.args = args self.data = data - self.type_ = T.List + self.type_ = TypeEnum.LIST def __str__(self): return "(" + " ".join(f"{arg}" for arg in self.args) + ")" |
