How to compile erlang code loaded into a string?

I have a generated string containing code for the erlang module.

Is there a way to compile the generated module directly from a string?

Or is there a way to convert the string to the format needed for compile:forms/1?

Or do I need to save it to a temp file first and then compile it with compile:file/1?

Alternatively, I can add compilation module support, but there must be a reason why good people who write erlang did not add it.

+3
source share
2 answers

, . , , , . :

% create tokens from strings containing forms
> {ok, MTs, _} = erl_scan:string("-module(z).").
> {ok, ETs, _} = erl_scan:string("-export([f/0]).").
> {ok, FTs, _} = erl_scan:string("f() -> hello_world.").
% tokens to erl_parse trees
> {ok,MF} = erl_parse:parse_form(MTs).
> {ok,EF} = erl_parse:parse_form(ETs).
> {ok,FF} = erl_parse:parse_form(FTs).

% compile forms to binary
> {ok, z, Bin} = compile:forms([MF,EF,FF]).
{ok,z,<<70,79,82,49,0,0,1,164,66,69,65,77,65,116,111,109,0,0,0,...>>}

% load module from binary
> code:load_binary(z, "nofile", Bin).
{module,z}

% test
> z:f().
hello_world

, {dot, _}.

+14

( ) .
. . , .

0

Source: https://habr.com/ru/post/1730510/


All Articles