如何编译加载到字符串中的erlang代码?

mon*_*y_p 5 erlang compilation

我有一个生成的字符串,其中包含erlang模块的代码.

有没有办法直接从字符串编译生成的模块?

或者有没有办法将字符串转换为所需的格式compile:forms/1?

或者我是否必须先将其保存到临时文件中,然后使用compile:file/1?

或者,我可以添加对编译模块的支持,但必须有一个原因,为什么编写erlang的好人没有添加它.

Zed*_*Zed 15

您需要将字符串扫描到标记中,然后将标记解析为表单.不幸的是,它一次只能解析一个表单,因此您需要在表单边界处剪切字符串或标记.这是一个简短的例子:

% 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
Run Code Online (Sandbox Code Playgroud)

或者,您可以扫描字符串,然后将标记切换为{dot, _}令牌.

  • 如果您需要支持包含,ifdef和帮派,请使用阿勒颇:https://github.com/evanmiller/aleppo (2认同)