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

@ -31,7 +31,13 @@ class ResponseId(AstNode):
grammar = [
Keyword("response"),
"=",
AnyOf(UseIdent("response_id"), UseNumber("response_id")),
AnyOf(
UseIdent("response_id"),
[
Optional(UseExact("sign", "-")),
UseNumber("response_id"),
],
),
Optional([Keyword("default"), UseLiteral("is_default", True)]),
]
@ -81,14 +87,14 @@ class ResponseId(AstNode):
gir = self.root.gir
response = self.tokens["response_id"]
if isinstance(response, int):
if response < 0:
raise CompileError("Numeric response type can't be negative")
elif isinstance(response, float):
if self.tokens["sign"] == "-":
raise CompileError("Numeric response type can't be negative")
if isinstance(response, float):
raise CompileError(
"Response type must be GtkResponseType member or integer," " not float"
)
else:
elif not isinstance(response, int):
responses = gir.get_type("ResponseType", "Gtk").members.keys()
if response not in responses:
raise CompileError(f'Response type "{response}" doesn\'t exist')

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}")