Skip to content

Instantly share code, notes, and snippets.

@fgallaire
Forked from hamidreza-s/main.erl
Last active April 29, 2019 14:30
Show Gist options
  • Save fgallaire/ffafd139f5331ff69afc0397bbb362dd to your computer and use it in GitHub Desktop.
Save fgallaire/ffafd139f5331ff69afc0397bbb362dd to your computer and use it in GitHub Desktop.
How to use Parse Transform feature in Erlang for meta-programming.
-module(main).
-export([hi/0, bye/0, hey/1]).
-compile({parse_transform, main_pt}).
hi() -> io:format("Hi there!~n").
bye() -> io:format("Bye there!~n").
hey(foo) -> io:format("Hey foo!~n");
hey(bar) -> io:format("Hey bar!~n").
-module(main_pt).
-export([parse_transform/2]).
parse_transform(Ast, _Opt) ->
io:format("AST:~p~n",[Ast]),
Ast2 = [parse(Tuple) || Tuple <- Ast],
if Ast =:= Ast2 -> io:format("AST2 == AST !~n");
true -> io:format("AST2:~p~n",[Ast2]) end,
Ast2.
parse({function,Line, FunName, ArgNum, Clauses}) ->
{function, Line, FunName, ArgNum, [parse(Clause) || Clause <- Clauses]};
parse({clause, _Line, _Vars, _Guard, [Call]}=Tuple) ->
erl_eval:expr(Call, erl_eval:new_bindings()),
Tuple;
parse(Tuple) -> Tuple.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment