Skip to content

Instantly share code, notes, and snippets.

@romul
Last active May 30, 2016 23:22
Show Gist options
  • Save romul/c88f3ce2fe92610bda1b7830fd95e305 to your computer and use it in GitHub Desktop.
Save romul/c88f3ce2fe92610bda1b7830fd95e305 to your computer and use it in GitHub Desktop.
defmodule MacroHelpers do
@doc """
Converts block AST to a list
You could pass function names which results should be included to the list
Examples:
block_to_list(ast, [:column])
"""
def block_to_list(block, search_for \\ []) do
search_for = MapSet.new(search_for)
case block do
{:__block__, trace, ast} ->
{:__block__, trace, handle_block_ast(ast, search_for)}
_ ->
[block]
end
end
defp handle_block_ast(list, search_for \\ %MapSet{}, acc \\ [])
defp handle_block_ast([], %MapSet{}, acc) do
[{:=, [], [{:buffer, [], __MODULE__}, []]} | acc]
end
defp handle_block_ast([line|tail], [], acc) do
new_line = case line do
{:=, _, _} ->
line
_ ->
{:=, [], [{:buffer, [], __MODULE__}, [{:|, [], [line, {:buffer, [], __MODULE__}]}]]}
end
handle_block_ast(tail, %MapSet{}, [new_line | acc])
end
defp handle_block_ast([line|tail], search_for, acc) do
{function, _, _} = line
new_line = if MapSet.member?(search_for, function) do
{:=, [], [{:buffer, [], __MODULE__}, [{:|, [], [line, {:buffer, [], __MODULE__}]}]]}
else
line
end
handle_block_ast(tail, search_for, [new_line | acc])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment