Skip to content

Commit

Permalink
Clear functions (#71)
Browse files Browse the repository at this point in the history
  • Loading branch information
fabriziosestito authored Mar 28, 2023
1 parent d8ef5c8 commit 3927639
Show file tree
Hide file tree
Showing 5 changed files with 39 additions and 1 deletion.
10 changes: 10 additions & 0 deletions lib/rhai/ast.ex
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,16 @@ defmodule Rhai.AST do
|> wrap_resource()
end

@doc """
Clear all function definitions in the AST.
"""
@spec clear_functions(t()) :: t()
def clear_functions(%__MODULE__{resource: resource} = ast) do
Rhai.Native.ast_clear_functions(resource)

ast
end

@doc false
def wrap_resource(resource) do
%__MODULE__{
Expand Down
1 change: 1 addition & 0 deletions lib/rhai/native.ex
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ defmodule Rhai.Native do
def ast_clear_source(_ast), do: err()
def ast_merge(_ast, _other), do: err()
def ast_combine(_ast, _other), do: err()
def ast_clear_functions(_ast), do: err()

defp err, do: :erlang.nif_error(:nif_not_loaded)
end
7 changes: 7 additions & 0 deletions native/rhai_rustler/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,10 @@ fn ast_combine(
ast: Mutex::new(ast.combine(other_ast).clone()),
})
}

#[rustler::nif]
fn ast_clear_functions(resource: ResourceArc<ASTResource>) {
let mut ast = resource.ast.try_lock().unwrap();

ast.clear_functions();
}
3 changes: 2 additions & 1 deletion native/rhai_rustler/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,8 @@ rustler::init!(
ast_set_source,
ast_clear_source,
ast_merge,
ast_combine
ast_combine,
ast_clear_functions,
],
load = load
);
19 changes: 19 additions & 0 deletions test/rhai/ast_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,23 @@ defmodule Rhai.ASTTest do
Engine.eval_ast(engine, ast3)
end
end

describe "clear_functions/1" do
test "should clear all functions" do
engine = Engine.new()

{:ok, ast} =
Engine.compile(engine, """
fn foo(x) { 42 + x }
foo(1)
""")

assert {:ok, 43} ==
Engine.eval_ast(engine, ast)

ast = AST.clear_functions(ast)

assert {:error, {:function_not_found, _}} = Engine.eval_ast(engine, ast)
end
end
end

0 comments on commit 3927639

Please # to comment.