I’m not sure that is what you desire, but you can go with something like:
-module(foo).
-compile([debug_info]). %% Required!
-export([example/1]).
example(0) -> nothing;
example(1) -> one;
example(2) -> two;
example(N) when N > 2 -> many.
And then:
-module(ast_utils).
-export([fun_clauses/3]).
fun_clauses(Module, Fun, Arity) ->
case mod_ast(Module) of
{ok, AST} ->
extract_fun_clauses(Fun, Arity, AST);
error ->
error
end.
mod_ast(Module) ->
case code:which(Module) of
BeamFile when is_list(BeamFile) ->
case beam_lib:chunks(BeamFile, [ abstract_code ]) of
{ok, {_, [ {abstract_code, {_, AST}} ]} } ->
{ok, AST};
_ ->
error
end;
_ ->
error
end.
extract_fun_clauses(Fun, Arity, AST) ->
do_extract_fun_clauses(AST, Fun, Arity).
do_extract_fun_clauses([Form | Rest], Fun, Arity) ->
case erl_syntax:type(Form) of
function ->
FFun = erl_syntax:atom_value(erl_syntax:function_name(Form)),
FArity = erl_syntax:function_arity(Form),
case {FFun, FArity} of
{Fun, Arity} ->
{ok, erl_syntax:function_clauses(Form)};
_ ->
do_extract_fun_clauses(Rest, Fun, Arity)
end;
_ ->
do_extract_fun_clauses(Rest, Fun, Arity)
end;
do_extract_fun_clauses([], _, _) ->
error.
Result:
1> ast_utils:fun_clauses(foo, example, 1).
{ok,[{clause,{6,1},
[{integer,{6,9},0}],
[],
[{atom,{6,15},nothing}]},
{clause,{7,1},[{integer,{7,9},1}],[],[{atom,{7,15},one}]},
{clause,{8,1},[{integer,{8,9},2}],[],[{atom,{8,15},two}]},
{clause,{9,1},
[{var,{9,9},'N'}],
[[{op,{9,19},'>',{var,{9,17},'N'},{integer,{9,21},2}}]],
[{atom,{9,26},many}]}]}