Skip to content

Commit

Permalink
Use Interpreter parsing to check the prior code
Browse files Browse the repository at this point in the history
  • Loading branch information
tenmoves authored and Neylix committed Jan 10, 2023
1 parent 5b39bb7 commit 1b75ace
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
23 changes: 23 additions & 0 deletions lib/archethic/contracts/interpreter/condition.ex
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,21 @@ defmodule Archethic.Contracts.ConditionInterpreter do
{"content", true}
end

defp validate_condition({"code", nil}, %{
"next" => %{"code" => next_code},
"previous" => %{"code" => prev_code}
}) do
quoted_next_code =
next_code
|> Code.string_to_quoted!(static_atoms_encoder: &atom_encoder/2)

quoted_previous_code =
prev_code
|> Code.string_to_quoted!(static_atoms_encoder: &atom_encoder/2)

{"code", quoted_next_code == quoted_previous_code}
end

# Validation rules for inherit constraints
defp validate_condition({field, nil}, %{"previous" => prev, "next" => next}) do
{field, Map.get(prev, field) == Map.get(next, field)}
Expand Down Expand Up @@ -598,4 +613,12 @@ defmodule Archethic.Contracts.ConditionInterpreter do
{res, _} = Code.eval_quoted(quoted_code, scope: constants)
res
end

defp atom_encoder(atom, _) do
if atom in ["if"] do
{:ok, String.to_atom(atom)}
else
{:ok, {:atom, atom}}
end
end
end
46 changes: 46 additions & 0 deletions test/archethic/contracts/interpreter/condition_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -276,5 +276,51 @@ defmodule Archethic.Contracts.ConditionInterpreterTest do
}
})
end

test "should return true if the ast of the code is the same" do
assert ~s"""
condition inherit: []
"""
|> Interpreter.sanitize_code()
|> elem(1)
|> ConditionInterpreter.parse()
|> elem(2)
|> ConditionInterpreter.valid_conditions?(%{
"previous" => %{
"code" => ~s"""
condition inherit: [ ]
"""
},
"next" => %{
"code" => ~s"""
condition inherit: []
"""
}
})
end

test "should return false if the ast of the code is the different" do
refute ~s"""
condition inherit: []
"""
|> Interpreter.sanitize_code()
|> elem(1)
|> ConditionInterpreter.parse()
|> elem(2)
|> ConditionInterpreter.valid_conditions?(%{
"previous" => %{
"code" => ~s"""
condition inherit: [ ]
"""
},
"next" => %{
"code" => ~s"""
condition inherit: [1]
"""
}
})
end
end
end

0 comments on commit 1b75ace

Please sign in to comment.