From d5f4e778b74ec5bae2ae5e6275f1d8101cb739b7 Mon Sep 17 00:00:00 2001 From: Bastien CHAMAGNE Date: Wed, 3 May 2023 15:33:50 +0200 Subject: [PATCH] Catch the invalid elixir syntax error in smart contracts --- lib/archethic/contracts/interpreter.ex | 16 +++++++++++++--- test/archethic/contracts/interpreter_test.exs | 11 +++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/lib/archethic/contracts/interpreter.ex b/lib/archethic/contracts/interpreter.ex index efe2d36fe..a86573a07 100644 --- a/lib/archethic/contracts/interpreter.ex +++ b/lib/archethic/contracts/interpreter.ex @@ -41,6 +41,9 @@ defmodule Archethic.Contracts.Interpreter do |> check_contract_blocks() end + {:error, :invalid_syntax} -> + {:error, "Parse error: invalid language syntax"} + {:error, {[line: line, column: column], _msg_info, _token}} -> {:error, "Parse error at line #{line} column #{column}"} end @@ -77,9 +80,16 @@ defmodule Archethic.Contracts.Interpreter do """ @spec sanitize_code(binary()) :: {:ok, Macro.t()} | {:error, any()} def sanitize_code(code) when is_binary(code) do - code - |> String.trim() - |> Code.string_to_quoted(static_atoms_encoder: &atom_encoder/2) + try do + code + |> String.trim() + |> Code.string_to_quoted(static_atoms_encoder: &atom_encoder/2) + rescue + _ -> + # catch the non-elixir syntax here + # example [key:value] is not valid + {:error, :invalid_syntax} + end end @doc """ diff --git a/test/archethic/contracts/interpreter_test.exs b/test/archethic/contracts/interpreter_test.exs index 6a08ca9a6..4d576b6f3 100644 --- a/test/archethic/contracts/interpreter_test.exs +++ b/test/archethic/contracts/interpreter_test.exs @@ -110,6 +110,17 @@ defmodule Archethic.Contracts.InterpreterTest do """ |> Interpreter.parse() end + + test "should return an human readable error if syntax is not elixir-valid" do + assert {:error, "Parse error: invalid language syntax"} = + """ + @version 1 + actions triggered_by:transaction do + x = "missing space above" + end + """ + |> Interpreter.parse() + end end describe "parse code v0" do