-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrorty.ex
63 lines (52 loc) · 1.16 KB
/
rorty.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
defmodule Rorty do
@moduledoc """
Documentation for `Rorty`.
"""
@doc """
Reeceive
## Examples
iex> Rorty.run("1 + 1")
2
"""
@spec run(String.t()) :: term()
def run(src) do
{result, _} =
src
|> parse()
|> Rorty.Interpreter.interpret(%Rorty.Env{})
result
end
@doc """
Reeceive
## Examples
# iex> Rorty.run_from_file("examples/factorial.rorty")
# 120
"""
@spec run_from_file(String.t()) :: term()
def run_from_file(filename) do
{:ok, src} = filename |> File.read()
src |> run()
end
@spec parse(src :: String.t()) :: [%Rorty.Ast.Expr{}]
def parse(src) do
try do
src |> String.trim() |> Rorty.Grammar.parse!()
rescue
e in Neotomex.Grammar.ParseError ->
e |> handle_exception()
end
end
@spec parse_from_file(String.t()) :: [%Rorty.Ast.Expr{}]
def parse_from_file(filename) do
{:ok, src} = filename |> File.read()
src |> parse()
end
defp handle_exception(ex) do
if ex.error do
IO.puts("Error: reason: #{ex.error}, message: #{ex.description}")
else
IO.puts("Error: #{ex.description}")
end
System.halt(1)
end
end