如何编译加载到字符串中的erlang代码? [英] How to compile erlang code loaded into a string?

查看:69
本文介绍了如何编译加载到字符串中的erlang代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a generated string that contains the code for an erlang module.

有没有一种方法可以直接从字符串中编译生成的模块?

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

或者是否可以将字符串转换为 compile:forms/1 所需的格式?

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

还是我必须先将其保存到临时文件中,然后使用 compile:file/1 进行编译?

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

或者,我可以向编译模块添加支持,但是一定有理由为什么写erlang的好人没有添加它.

Alternatively, I can add support to the compile module, but there must be a reason why the good people that write erlang haven't added it.

推荐答案

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

You need to scan your string into tokens, and then parse the tokens into forms. Unfortunately it is only possible to parse one form at a time, so you will need to either cut your string, or your tokens at form boundaries. Here is a short example:

% 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,_} 个令牌.

Alternatively you can scan your string, and then cut the resulting token list at {dot, _} tokens apart.

这篇关于如何编译加载到字符串中的erlang代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆