Skip to content

Commit 168c3d3

Browse files
committed
fix primitive support
1 parent ae84ff1 commit 168c3d3

2 files changed

Lines changed: 21 additions & 1 deletion

File tree

numba_cfunc_compiler/defaults/primitive_support.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,22 @@ def try_parse_state(cls, node: ast.AnnAssign, var_name: str, globalns: dict) ->
8181
if not isinstance(node.value, ast.Constant):
8282
raise TypeError(f"State '{var_name}' must have a literal initial value")
8383

84-
return StateVariableInfo(var_name, node.value.value, state_type)
84+
initial_value = node.value.value
85+
initial_type = type(initial_value)
86+
87+
# State storage is allocated by the host from the concrete Python value,
88+
# while generated code reads it using the declared State type. Keep those
89+
# representations identical, allowing only the safe numeric widening that
90+
# is already supported for inputs.
91+
if state_type is float and initial_type is int:
92+
initial_value = float(initial_value)
93+
elif initial_type is not state_type:
94+
raise TypeError(
95+
f"State '{var_name}' expected an initial value of type "
96+
f"{state_type.__name__}, got {initial_type.__name__}"
97+
)
98+
99+
return StateVariableInfo(var_name, initial_value, state_type)
85100

86101

87102
def register():

numba_cfunc_compiler/tests/test_support_units.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -475,6 +475,11 @@ def test_models_type_factory_registry_and_source_registry():
475475
assert TypeFactory.try_parse_input(param, int)[1] == ParameterInfo(int)
476476
assert TypeFactory.try_parse_input(param, str) is None
477477
assert TypeFactory.try_parse_state(parse_stmt("x: State[int] = 1"), "x", {}) == StateVariableInfo("x", 1, int)
478+
assert TypeFactory.try_parse_state(parse_stmt("x: State[float] = 1"), "x", {}) == StateVariableInfo("x", 1.0, float)
479+
assert TypeFactory.try_parse_state(parse_stmt("x: State[bool] = True"), "x", {}) == StateVariableInfo("x", True, bool)
480+
for annotation, value in (("int", "1.0"), ("int", "True"), ("float", "True"), ("bool", "1")):
481+
with pytest.raises(TypeError, match=f"expected an initial value of type {annotation}"):
482+
TypeFactory.try_parse_state(parse_stmt(f"x: State[{annotation}] = {value}"), "x", {})
478483
assert TypeFactory.try_parse_state(parse_stmt("x: State[str] = 'a'"), "x", {}) is None
479484

480485
int_info = NumbaTypeRegistry.get_by_python_type(int)

0 commit comments

Comments
 (0)