Skip to content

Commit 3751cb1

Browse files
authored
add get_typed to interp.Frame (#156)
allow better error message when implementing the method table of an interpreter. changing the error from `KeyError` to `InterpreterError` so you can get a stacktrace at where the statement produces the undefined error - I think it's possible due to users' code actually having this error so it doesn't makes sense to terminate the interpreter program right away but instead should return the result as error. cc: @weinbe58 @kaihsin
1 parent 3530e9b commit 3751cb1

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

src/kirin/interp/frame.py

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from typing_extensions import Self
66

77
from kirin.ir import SSAValue, Statement
8+
from kirin.exceptions import InterpreterError
89

910
ValueType = TypeVar("ValueType")
1011

@@ -66,7 +67,47 @@ def from_func_like(cls, code: Statement) -> Self:
6667
return cls(code=code)
6768

6869
def get(self, key: SSAValue) -> ValueType:
69-
return self.entries[key]
70+
"""Get the value for the given [`SSAValue`][kirin.ir.SSAValue].
71+
72+
Args:
73+
key(SSAValue): The key to get the value for.
74+
75+
Returns:
76+
ValueType: The value.
77+
78+
Raises:
79+
InterpreterError: If the value is not found. This will be catched by the interpreter
80+
and will be converted to an [`interp.Err`][kirin.interp.Err] in the interpretation
81+
results.
82+
"""
83+
err = InterpreterError(f"SSAValue {key} not found")
84+
value = self.entries.get(key, err)
85+
if isinstance(value, InterpreterError):
86+
raise err
87+
else:
88+
return value
89+
90+
ExpectedType = TypeVar("ExpectedType")
91+
92+
def get_typed(self, key: SSAValue, type_: type[ExpectedType]) -> ExpectedType:
93+
"""Similar to [`get`][kirin.interp.frame.Frame.get] but also checks the type.
94+
95+
Args:
96+
key(SSAValue): The key to get the value for.
97+
type_(type): The expected type.
98+
99+
Returns:
100+
ExpectedType: The value.
101+
102+
Raises:
103+
InterpreterError: If the value is not of the expected type. This will be catched
104+
by the interpreter and will be converted to an [`interp.Err`][kirin.interp.Err]
105+
in the interpretation results.
106+
"""
107+
value = self.get(key)
108+
if not isinstance(value, type_):
109+
raise InterpreterError(f"expected {type_}, got {type(value)}")
110+
return value
70111

71112
def set(self, key: SSAValue, value: ValueType) -> None:
72113
self.entries[key] = value

0 commit comments

Comments
 (0)