How to read and evaluate Erlang code with Erlang? Erlang is using metaprogramming in its core, and creating/crafting code with code is a nice way to learn a bit more about parsing and code evaluation. Here some notes.

# Classical Way

# Low Level Way

When loading a file, like sys.config or my_application.app.src file, it is necessary to use a different way to interpret the content. In fact, application_controler (opens new window) module is doing something different than just using file:consult/1 function.

Firstly the code will read the content using erl_prim_loader:get_file/1 (opens new window) function. It will return a tuple containing the content of the file in binary format and the full path, the one set in the first argument of the function.

{ok, Content, Path} = erl_prim_loader:get_file("/path/to/my/file")

The content of this file can now be tokenized using erl_scan:tokens/3 (opens new window) function.

{done, {ok, Tokens, _}, _Rest} = erl_scan:tokens([], Content, 1).

Tokens can now be parsed and converted into erlang terms using erl_parse:parse_term/1 (opens new window) function.

Terms = erl_parse:parse_term(Tokens).

By using this method, it is possible to store more than just standard ETF data. Here an example:

MyTest = "{atom, fun io:format/2."
{done, {ok, Tokens, _, _} = erl_scan:tokens([], MyTest, 1).
Terms = erl_parse:parse_term(Tokens).
% {atom, fun io:format/2}

Unfortunately, it seems we cannot import pid or references terms, but because these terms are dynamically generated in the VM, it seems normal.

# Resources