Fix bugs in number literals

This commit is contained in:
James Westman 2023-03-12 14:29:20 -05:00
parent fad3b35531
commit b636d9ed71
4 changed files with 29 additions and 27 deletions

View file

@ -145,39 +145,35 @@ class NumberLiteral(AstNode):
UseNumber("value"),
]
@property
def type(self) -> gir.GirType:
if isinstance(self.value, int):
return gir.IntType()
else:
return gir.FloatType()
@property
def value(self) -> T.Union[int, float]:
return self.tokens["value"]
if self.tokens["sign"] == "-":
return -self.tokens["value"]
else:
return self.tokens["value"]
@validate()
def validate_for_type(self) -> None:
expected_type = self.context[ValueTypeCtx].value_type
if isinstance(expected_type, gir.IntType):
try:
int(self.tokens["value"])
except:
if not isinstance(self.value, int):
raise CompileError(
f"Cannot convert {self.group.tokens['value']} to integer"
)
elif isinstance(expected_type, gir.UIntType):
try:
int(self.tokens["value"])
if int(self.tokens["value"]) < 0:
raise Exception()
except:
if self.value < 0:
raise CompileError(
f"Cannot convert {self.group.tokens['value']} to unsigned integer"
)
elif isinstance(expected_type, gir.FloatType):
try:
float(self.tokens["value"])
except:
raise CompileError(
f"Cannot convert {self.group.tokens['value']} to float"
)
elif expected_type is not None:
raise CompileError(f"Cannot convert number to {expected_type.full_name}")