aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorWilliam Hergès <william@herges.fr>2025-11-08 22:53:41 +0100
committerWilliam Hergès <william@herges.fr>2025-11-08 22:53:41 +0100
commitc7a26d3c6125caa9239cec9bf08db935d98e19c1 (patch)
tree77222ae3903da80d619d7a33d307d0d46c4eb9bb
parentf52f066e7cf6b4c96e452a8f7e803d7f1895e9a1 (diff)
feat(syntax): eval statement
-rw-r--r--example/input.txt7
-rw-r--r--lib/elixir_math_parser.ex7
-rw-r--r--lib/main.ex14
-rw-r--r--src/elixir_math_parser.yrl9
4 files changed, 23 insertions, 14 deletions
diff --git a/example/input.txt b/example/input.txt
index a530f47..7233dc7 100644
--- a/example/input.txt
+++ b/example/input.txt
@@ -1,8 +1,7 @@
-:a = 7
-:b = 4
-:res = (:a + :b) * 10 / 2
+:a = 7;; :b = 4;;
+(:a + :b) * 10 / 2
:x = 20
:y = 3
:z = 6
-:val = 10 + :z / :y * :x / 4
+10 + :z / :y * :x / 4
diff --git a/lib/elixir_math_parser.ex b/lib/elixir_math_parser.ex
index 8d5bcc9..4da4271 100644
--- a/lib/elixir_math_parser.ex
+++ b/lib/elixir_math_parser.ex
@@ -49,6 +49,13 @@ defmodule ElixirMathParser do
end
end
+ defp evaluate_tree([{:eval, expr} | tail], state) do
+ with {:ok, expr} <- reduce_to_value(expr, state) do
+ IO.puts(expr)
+ evaluate_tree(tail, state)
+ end
+ end
+
defp evaluate_tree([], state) do
{:ok, state}
end
diff --git a/lib/main.ex b/lib/main.ex
index f1f0a20..ad657ca 100644
--- a/lib/main.ex
+++ b/lib/main.ex
@@ -7,9 +7,10 @@ defmodule ElixirMathParser.Main do
def process_parse({:ok, tree}) do
IO.puts("\nParse tree")
IO.inspect(tree, pretty: true)
- state = ElixirMathParser.process_tree(tree)
- IO.puts("\nFinal state")
- IO.inspect(state, pretty: true)
+ case ElixirMathParser.process_tree(tree) do
+ {:ok, _} -> :ok
+ {:error, reason} -> reason
+ end
end
def main(args) do
@@ -20,9 +21,10 @@ defmodule ElixirMathParser.Main do
{:ok, tokens, line} = :elixir_math_parser_lexer.string(String.to_charlist(text))
IO.puts("Parsed #{filename}, stopped at line #{line}")
- IO.puts("\nTokens:")
- IO.inspect(tokens, pretty: true)
- process_parse(:elixir_math_parser.parse(tokens))
+ res = process_parse(:elixir_math_parser.parse(tokens))
+ if res != :ok do
+ IO.puts(res)
+ end
end
end
diff --git a/src/elixir_math_parser.yrl b/src/elixir_math_parser.yrl
index 3ec4946..17b46ad 100644
--- a/src/elixir_math_parser.yrl
+++ b/src/elixir_math_parser.yrl
@@ -31,11 +31,12 @@ Left 600 '('.
root -> statements : '$1'.
-statements -> statement : '$1'.
-statements -> statement statements : lists:merge('$1', '$2').
-statements -> statement ';;' statements : lists:merge('$1', '$3').
+statements -> statement : ['$1'].
+statements -> statement statements : ['$1'|'$2'].
+statements -> statement ';;' statements : ['$1'|'$3'].
-statement -> atom '=' expr : [{assign, '$1', '$3'}].
+statement -> atom '=' expr : {assign, '$1', '$3'}.
+statement -> expr : {eval, '$1'}.
expr -> int : unwrap('$1').
expr -> atom : '$1'.