Elixir 到 Erlang 的转换

标签 elixir

我想看看当 Elixir 转换成 Beam 文件时会发生什么。有没有办法在控制台或文件中打印它的翻译方式?我想知道这个模块在 erlang 中是什么样子的。

我在想是否有 Elixir 的 Debug模式,它会输出以上任何内容。

更具体地说,我有这个例子:

defmodule Test do
    def t1(a), do: a
    def t1(a, b \\ 2), do: a + b
end

上面的代码提出了一个警告,考虑到我所做的,这是可以理解的。基本上我想更多地了解正在发生的事情。

最佳答案

首先,您需要将 Elixir 模块编译为 .beam 文件:

$ cat test.ex
defmodule Test do
    def t1(a), do: a
    def t1(a, b \\ 2), do: a + b
end
$ elixirc test.ex
warning: this clause cannot match because a previous clause at line 2 always matches
  test.ex:3

这将生成Elixir.Test.beam。然后,您可以使用以下脚本将此 .beam 反编译为 Erlang 源代码(我不久前从 Stackoverflow 上的一些答案中复制了此代码。不幸的是,我似乎无法找到确切的源代码,但此代码位于此处的许多答案中,包括 this one .):

$ cat decompile.erl
#!/usr/bin/env escript

main([BeamFile]) ->
  {ok,{_,[{abstract_code,{_,AC}}]}} = beam_lib:chunks(BeamFile,[abstract_code]),
  io:fwrite("~s~n", [erl_prettypr:format(erl_syntax:form_list(AC))]).

然后运行它:

$ escript decompile.erl Elixir.Test.beam
-compile(no_auto_import).

-file("test.ex", 1).

-module('Elixir.Test').

-export(['__info__'/1, t1/1, t1/2]).

-spec '__info__'(attributes | compile | exports |
         functions | macros | md5 | module |
         native_addresses) -> atom() |
                      [{atom(), any()} |
                       {atom(), byte(), integer()}].

'__info__'(functions) -> [{t1, 1}, {t1, 2}];
'__info__'(macros) -> [];
'__info__'(info) ->
    erlang:get_module_info('Elixir.Test', info).

t1(a@1) -> a@1;
t1(x0@1) -> t1(x0@1, 2).

t1(a@1, b@1) -> a@1 + b@1.

关于Elixir 到 Erlang 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40757461/

相关文章:

javascript - 如何在 Elixir 中 forEach

elixir - mix deps.get 失败,{ :failed_connect, [{ :to_address, {'repo.hex.pm' , 443}}, { :inet, [ :inet], { :option, :server_only, :honor_cipher_order}}]}

postgresql - 无法使用对等身份验证在没有密码的情况下运行 `mix ecto.migrate`

deployment - Elixir:使用 edeliver 构建和部署伞形应用

elixir - Kubernetes集群和Phoenix自动化 `mix ecto.migrate`吗?

elixir - 在 elixir 中,如何全局安装软件包?

erlang - 如何从 Elixir shell 获取 Erlang 函数的帮助

Elixir Ecto - 未知领域

elixir - 展平/合并嵌套 map

javascript - 在 Phoenix 框架应用程序的某些页面上包含 Javascript