Skip to content

Commit

Permalink
Add generic function to fetch scope variables with a generic type (#293)
Browse files Browse the repository at this point in the history
* Add generic way to fetch scope variables

* Use more specific error

---------

Co-authored-by: Pedro Fontana <[email protected]>
  • Loading branch information
fmoletta and pefontana authored Sep 29, 2023
1 parent 51db1d4 commit 4f3d9e7
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
18 changes: 18 additions & 0 deletions pkg/types/exec_scope_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,3 +258,21 @@ func TestErrExitMainScope(t *testing.T) {
t.Errorf("TestErrExitMainScope should fail with error: %s and fails with: %s", types.ErrCannotExitMainScop, err)
}
}

func TestFetchScopeVar(t *testing.T) {
scope := make(map[string]interface{})
scope["k"] = lambdaworks.FeltOne()

scopes := types.NewExecutionScopes()
scopes.EnterScope(scope)

result, err := types.FetchScopeVar[lambdaworks.Felt]("k", scopes)
if err != nil {
t.Errorf("TestGetLocalVariables failed with error: %s", err)

}
expected := lambdaworks.FeltOne()
if expected != result {
t.Errorf("TestGetLocalVariables failed, expected: %s, got: %s", expected.ToSignedFeltString(), result.ToSignedFeltString())
}
}
21 changes: 21 additions & 0 deletions pkg/types/exec_scopes.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ func ErrVariableNotInScope(varName string) error {
return ExecutionScopesError(errors.Errorf("Variable %s not in scope", varName))
}

func ErrVariableHasWrongType(varName string) error {
return ExecutionScopesError(errors.Errorf("Scope variable %s has wrong type", varName))
}

func NewExecutionScopes() *ExecutionScopes {
data := make([]map[string]interface{}, 1)
data[0] = make(map[string]interface{})
Expand Down Expand Up @@ -82,3 +86,20 @@ func (es *ExecutionScopes) Get(varName string) (interface{}, error) {
}
return val, nil
}

// Generic version of ExecutionScopes.Get which also handles casting
func FetchScopeVar[T interface{}](varName string, scopes *ExecutionScopes) (T, error) {
locals, err := scopes.GetLocalVariables()
if err != nil {
return *new(T), err
}
valAny, prs := locals[varName]
if !prs {
return *new(T), ErrVariableNotInScope(varName)
}
val, ok := valAny.(T)
if !ok {
return *new(T), ErrVariableHasWrongType(varName)
}
return val, nil
}

0 comments on commit 4f3d9e7

Please sign in to comment.