Erlang -- How to convert a fun() object to a String - erlang

Is there a straightforward way to convert an Erlang fun to a string? A call to io_lib:format only prints the function reference, e.g. something like "#Fun<erl_eval.20.67289768>". For example, I'd like to be able to do this:
1> Fun = fun() -> atom_to_list('hello world') end.
2> FunStr = fun_to_str(Fun).
"fun() -> atom_to_list('hello world') end."
I'm looking for how to implement fun_to_str. In javascript, some interpreters have a .toSource() function that can be called on any object, including functions, that print their string representation. Any info is appreciated, thanks.

First, get the environment variables for the fun (which includes the abstract code):
1> {env, [{_, _, _, Abs}]} = erlang:fun_info(Fun, env).
{env,[{[],
{eval,#Fun<shell.21.83096281>},
{value,#Fun<shell.5.83096281>},
[{clause,1,[],[],
[{call,1,{atom,1,atom_to_list},[{atom,1,hello_world}]}]}]}]}
Pretty print the abstract code using erl_pp:
3> Str = erl_pp:expr({'fun', 1, {clauses, Abs}}).
[[[["fun",
[[[[["()"]," ->"],
["\n ",
[["atom_to_list",[[40,["'hello world'",41]]]]]]]]]]],
[10,["end"]]]]
4> io:format([Str|"\n"]).
fun() ->
atom_to_list('hello world')
end
ok
(You have to add {'fun', 1, {clauses, ...}} around it to make it a complete Erlang expression)

You might be able to use erlang:fun_info/2 for that, atleast i get some information from the shell when doing
1> erlang:fun_info(fun() -> test,ok end, env).
{env,[[],
{value,#Fun<shell.7.37281544>},
{eval,#Fun<shell.24.85590193>},
[{clause,1,[],[],[{atom,1,test},{atom,1,ok}]}]]}
2>
You want the last list with the clause atom and then pretty print it using for instance erl_pp

Related

What am I doing wrong with erl_parse:parse_form?

I wrote a Hello-World module and compiled it successfully. And then I tried to learn the things under the hood by using erl_scan and erl_parse.
-module(useless).
-export([hello/0]).
hello() -> io:format("hello world\n").
and I type in the erl shell
{ok, S} = file:read_file("useless.erl").
and
{ok, T, _} = erl_scan:string(binary_to_list(S)).
It works fine apparently. But when I try erl_parse:parse_form(T).
It gives {error,{2,erl_parse,["syntax error before: ","'-'"]}}
What am I doing wrong?
Edit:
the module compile is helpful.
Also this is cool.
The function erl_parse:parse_form/1 works on one form only. So you must split the result of erl_scan:string/1 into individual forms first.
you can use erl_scan:tokens to achieve this (this code wors, but I am not sure I use the function in the right way):
-module(useless).
-export([eval/1]).
eval(File) ->
{ok, B} = file:read_file(File),
Forms = scan(erl_scan:tokens([],binary_to_list(B),1),[]),
F = fun(X) -> {ok,Y} = erl_parse:parse_form(X), Y end,
[F(X) || X <- Forms].
scan({done,{ok,T,N},S},Res) ->
scan(erl_scan:tokens([],S,N),[T|Res]);
scan(_,Res) ->
lists:reverse(Res).
Robert suggestion is to use the re-entrant feature of erl_scan:tokens/3.
The docs on this function are not explicit and it took me some time to understand that the initial string needed to be closed by eof. (if not the tokens function runs an endless loop).
Here is the code I finally came up with, I hope that will help others.
eval(File)->
{ok, Data} = file:read_file(File),
String=erlang:binary_to_list(Data),
scan(String).
scan(String) when is_list(String)->
scan(String++eof,[]). %% appended eof
scan({done, Result, LeftOverChars},Acc)->
scan_done(Result,LeftOverChars,Acc);
scan({more, Continuation},Acc)->
scan(erl_scan:tokens(Continuation,[],1),Acc);
scan(String,Acc) when is_list(String)->
scan(erl_scan:tokens([],String,1),Acc).
scan_done({error,ErrorMsg,_Location},_LeftOverChars,_Acc)->
ErrorMsg;
scan_done({eof,Location},LeftOverChars,Acc)->
Acc;
scan_done({ok,Tokens,Location},LeftOverChars,Acc)->
case erl_parse:parse_form(Tokens) of
{ok,R}->scan(LeftOverChars,Acc++[R]);
{error,R}->scan(LeftOverChars,R)
end.

syntax function into Erlang

I have a module which written into notepad:
-module(hhfuns).
-compile(export_all).
one() -> 1.
two() -> 2.
add(X,Y) - X() + Y().
and I save it as hhfuns.erl. When I run Ok then I called:
hhfuns:add(myfun hhfun:one/0, myfun hhfun:two/0).
this command make syntax error. But when I changed myfun to fun it worked.maybe it's a basic syntax but I'm new at Erlang, so please explain for me why.
When you are passing function from outside module as a parameter you should use syntax fun Module:Function/Arity. Correct version for you will be hhfuns:add(fun hhfun:one/0, fun hhfun:two/0). fun here is a required keyword and you can not use myfun here instead.
In fact myfun is not an Erlang keyword, whereas fun is.

How to mock objects in Erlang using Meck?

Okay, I'm using Meck and I'm lost. My first language (that I've been writing for about 7 months) is Ruby, so I can't seem to wrap my brain around Meck mocking yet. I do get Ruby mocking though. Hoping someone can help me. Also, I've only been writing Erlang for a week.
Updated Code (but mocking still isn't working)...
I have a Erlang console_io prompter module that looks like this:
-module(prompter).
-export([prompt/1, guess/0]).
prompt(Message) ->
console_io:gets(Message).
gets() ->
{_, [Input]} = io:fread("Enter: ", "~s"),
Input.
guess() ->
Guess_Input = gets(),
Guess_List = convert_guess_to_list(Guess_Input).
convert_guess_to_list(Guess_Input) ->
re:split(Guess_Input, "", [{return, list}, trim]).
My test now looks like this:
-module(prompter_test).
-include_lib("eunit/include/eunit.hrl").
guess_1_test() ->
meck:new(prompter),
meck:expect(prompter, gets, fun() -> "aaaa" end),
?assertEqual(prompter:guess(), ["a","a","a","a"]),
?assert(meck:validate(prompter)),
meck:unload(prompter).
The error I'm getting is this:
Eshell V5.9.3.1 (abort with ^G)
1> prompter_test: guess_1_test (module 'prompter_test')...*failed*
in function prompter:guess/0
called as guess()
in call from prompter_test:guess_1_test/0 (test/prompter_test.erl, line 10)
in call from prompter_test:guess_1_test/0
**error:undef
I want to mock (stub?) the gets function in my test so that gets will return "aaaa" and then when I assert on get_guess() it should equal ["a", "a", "a", "a"].
How do I do this?
There are two problems:
The prompter module has two exported functions, but you only mock one of them (gets) with meck:expect. By default, Meck creates a new module that only contains the functions that you explicitly mock. You can change that by using the passthrough option:
meck:new(prompter, [passthrough]),
When you mock the gets function, all module-prefixed calls (i.e. prompter:gets()) are intercepted, but Meck has no way (yet?) of intercepting internal calls (e.g. the gets() call in the guess function), so you would still get the unmocked version of the function. There is no completely satisfactory way to avoid this. You could change the call in guess to prompter:gets(), or you could move gets into a separate module and mock that.
The first line says to create a new mocked module, my_library_module:
meck:new(my_library_module),
Next, we mock the function fib in my_library_module to return 21 when 8 is passed in:
meck:expect(my_library_module, fib, fun(8) -> 21 end),
We have some eunit assertions to test our mocked function. The code_under_test:run call is what you want to replace with the the function using your mocked module, and the 21 is the result you are expecting from the function call:
?assertEqual(21, code_under_test:run(fib, 8)), % Uses my_library_module
?assert(meck:validate(my_library_module)),
Then we unload the mocked module:
meck:unload(my_library_module).
If you wanted to write the same test for your module, you could write:
my_test() ->
meck:new(console_io),
meck:expect(console_io, gets, fun() -> "aaaa" end),
?assertEqual(["a", "a", "a", "a"], console_io:get_guess()), % Uses console_io
?assert(meck:validate(console_io)),
meck:unload(console_io).

How to show Erlang call stack?

I need to debug some module in foreign system. The module has public function foo() - how can I know place (module and function name)
from which foo() given module was called? I mean stack of calls.
I cannot stop system, all work I can do by reload this module (but with some debug info).
-module(given).
-export(foo/0).
foo() ->
%% here is my debug - and
%% i need here(!) known about unknown_module:unknown_foo!
ok.
---
-module(unknown_module).
..
unknown_foo() ->
given:foo(). %% see above
Here's a simple trick:
Trace = try throw(42) catch 42 -> erlang:get_stacktrace() end,
erlang:display(Trace)
This might work:
where_am_i() ->
try throw(a)
catch throw:a:Stacktrace ->
Stacktrace
end.
Except that it doesn't work for tail calls. For example, given these two functions:
foo() ->
where_am_i().
bar() ->
X = where_am_i(),
{ok, X}.
I get these results:
4> foo:foo().
[{foo,where_am_i,0},
{erl_eval,do_apply,5},
{shell,exprs,6},
{shell,eval_exprs,6},
{shell,eval_loop,3}]
5> foo:bar().
{ok,[{foo,where_am_i,0},
{foo,bar,0},
{erl_eval,do_apply,5},
{shell,exprs,6},
{shell,eval_exprs,6},
{shell,eval_loop,3}]}
That is, I can only see bar, since foo's call frame has been left already when where_am_i is called.
io:format("~s~n", [element(2, process_info(self(), backtrace))]).
self() can be replaced by any other pid (rpc:pinfo should even work with remote procs). This helps if you cannot even modify the source or beam.
Here is my code for doing this:
format_stack_entry(S) ->
{Module,Fun,Arity,[{file,File},{line,Line}]}=S,
io_lib:format("{~p,~p,~p,[{file,~p},{line,~p]}",[Module,Fun,Arity,File,Line]).
stacktop([Top|_]) ->
Top.
ancestor(N) ->
{_,Stacktrace}=erlang:process_info(self(),current_stacktrace),
ancestor(N+1,Stacktrace).
ancestor(1,S) ->
format_stack_entry(stacktop(S));
ancestor(N,[_|T]) ->
ancestor(N-1,T).
info(Format) -> io:format(lists:concat([ancestor(2),Format,"\r"])).
info(Format,Args) -> io:format(lists:concat([ancestor(2),Format,"\r"]),Args).
Lists is a custom module in the system. Use your foo module instead.

In Erlang, how do you invoke a function dynamically?

I want to call xyz with the name of a function to be invoked.
-module(sample).
-export([xyz/1]).
xyz(Name) -> Name().
p() -> "you called p".
g() -> "you called g".
But I get the following error:
1> c(sample.erl).
./sample.erl:6: Warning: function p/0 is unused
./sample.erl:7: Warning: function g/0 is unused
{ok,sample}
2> sample:xyz('p').
** exception error: bad function p
in function sample:xyz/1
3>
It is correct that you have to export p and g. You can then use apply/3 to call it.
erlang:apply(sample, p, []).
Only fun-values are usable with the Fun(...) syntax. You are passing in an atom-value. An atom is a 'bad function' as the error message go. You could do something similar to
xyz(p) -> fun p/0;
xyz(g) -> fun g/0.
Then go ahead and call
Fun = xyz(p),
Fun()
-module(sample).
-export([xyz/1, p/0, g/0]).
xyz(Name) -> ?MODULE:Name().
p() -> "you called p".
g() -> "you called g".
1> sample:xyz(p).
"you called p"
Pattern match is the idiom to use:
-module(sample).
-export([xyz/1]).
xyz(p) -> p();
xyz(q) -> g().
p() -> "you called p".
g() -> "you called g".
If you want to be dynamic you can use a gen_event server.
Essentially what this is is a server that holds a state which consists of key/function pair like so:
[{p, #func1},
{g, #func2},
{..., ...},
...]
You can then essentially bind events to functions. (there is, needless to say, a bit more to it than that.
The easiest way to do is to try exporting p and g along with xyz.
-export([xyz/1, p/0,g/0]).
After exporting the function p and g can be called as follows :
1> sample:xyz(fun sample:p/0).
"you called p"
2> sample:xyz(fun sample:g/0).
"you called g"
Another way to look at it is that (depending on the problem you're solving) dynamic calls to functions isn't necessarily the right approach. Given that processes and message passing are the way you organize your code in Erlang since it's a "concurrency oriented language", maybe you could just use message passing with a selective receive rather than mimicking idioms of a sequential language? Send a message for what you want and get the custom reply based on that. It's about the result of each function, not the function itself, after all. (Plus there's the flexibility and scalability of message passing, etc.)
Although processes aren't totally free compared to calling from a library module, Erlang-level processes are dirt cheap (especially if the message communication is within the same node). They're not OS-level processes. The overhead would be comparable (or better) to dynamic function calls and object instantiation in heavier scripting languages.

Resources