Skip to content

@khia /dsl.exs
Last active

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Demo of simple DSL
#!/usr/bin/env elixir
defmodule DSL do
defmacro action(match, [do: body]) do
quote do
def handle_info(unquote(match) = arg, state) do
unquote(body)
{:ok, state}
end
end
end
defmacro createhandler(name, [do: body]) do
quote do
defmodule unquote(name) do
unquote(body)
end
end
end
def compile(namespace, file) do
content = File.read!(file)
content =
"""
defmodule #{namespace} do
#require #{inspect __MODULE__}
import #{inspect __MODULE__}
#{content}
end
"""
{_module, _} = Code.eval(content)
:ok
end
end
[file_name] = System.argv
DSL.compile "MyHandlers", file_name
# Below is how you test it from elixir
MyHandlers.TestHandler.handle_info({:x, 5}, {SomeState})
MyHandlers.TestHandler.handle_info({:y, 3, :erlang.now}, {SomeState})
./dsl.exs test.dsl
x: 5
random.uniform(3) -> 1
createhandler TestHandler do
action {:x, x} do
# printToScreen
IO.puts "x: #{inspect x}"
end
action {:y, y, seed} do
# example of calling erlang modules
:random.seed(seed)
value = :random.uniform(y)
IO.puts "random.uniform(#{y}) -> #{value} "
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.