Elixir代码最终编译成为erlang代码,这个过程是怎样的?本文通过一个小测试做下探索.
![[Erlang 0109] From Elixir to Erlang Code [Erlang 0109] From Elixir to Erlang Code](https://image.miaokee.com:8440/aHR0cHM6Ly9pbWFnZXMwLmNuYmxvZ3MuY29tL2Jsb2cvMTczMjkvMjAxMzExLzI1MTY1MjA4LTk5MTMyMTgwNDdiOTRhMWI5MWE0NmY0NTU0OGQ4ODE0LnBuZw%3D%3D.png?w=700&webp=1)
编译一旦完成,你就看到了真相
Elixir代码组织方式一方面和Erlang一样才用非常扁平的代码模块结构,另一方面Elixir同时支持嵌套.Elixir比较方便的一点是可以在Elixir Shell中完成对模块的定义.看下面的方式:
iex> defmodule Math do
...> def sum(a, b) do
...> a + b
...> end
...> end iex> Math.sum(1, 2)
3
下面我们把代码放在m.ex模块中,模块的名字和代码文件的名字是可以不一样的,在编译之后文件夹中新增了一个Elixir.Math.beam的文件.换句话说,elixirc已经把m.ex文件编译成Elixir.Math.beam,按照Erlang对模块名称和文件名一致性的要求,我们可以在Erlang的Shell中验证一下:
[root@nimbus elixir]# elixirc m.ex
[root@nimbus elixir]# ls
Elixir.Math.beam m.ex [root@nimbus elixir]# erl
Erlang R16B01 (erts-5.10.2) [source] [64-bit] [smp:2:2] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V5.10.2 (abort with ^G)
1> 'Elixir.Math':sum(12,23).
35
2>
是不是和我们预期的一样?之前提到过多次从beam中还原源代码的方法,现在我们动手看下这个Elixir.Math.beam的Erlang代码是怎样的,输出我做了一下排版:
> {ok,{_,[{abstract_code,{_,AC}}]}} = beam_lib:chunks("Elixir.Math",[abstract_code]).
{ok,{'Elixir.Math',
[{abstract_code,
{raw_abstract_v1,
[{attribute,,compile, {no_auto_import,[{bitsize,},{apply,},
{spawn,}, {spawn_link,}, {spawn_monitor,}, {spawn_opt,},
{spawn_opt,}, {spawn,},
{spawn_link,}, {spawn_opt,},
{spawn_opt,}, {nodes,...},
{...}|...]}},
{attribute,,file,{"/data2/elixir/m.ex",}},
{attribute,,module,'Elixir.Math'},
{attribute,,export,[{'__info__',},{sum,}]},
{function,,'__info__',,
[{clause,,
[{atom,,functions}],
[],
[{cons,,{...},...}]},
{clause,,[{atom,,macros}],[],[{nil,}]},
{clause,,[{atom,,docs}],[],[{cons,...}]},
{clause,,[{atom,,...}],[],[{...}]},
{clause,,[{atom,...}],[],[...]},
{clause,,[{...}],[],...}]},
{function,,sum,,
[{clause,,
[{var,,a},{var,,b}],
[],
[{op,,...}]}]}]}}]}}
> io:fwrite("~s~n", [erl_prettypr:format(erl_syntax:form_list(AC))]).
-compile({no_auto_import,
[{bitsize, }, {apply, }, {spawn, }, {spawn_link, },
{spawn_monitor, }, {spawn_opt, }, {spawn_opt, },
{spawn, }, {spawn_link, }, {spawn_opt, },
{spawn_opt, }, {nodes, }, {disconnect_node, },
{integer_to_list, }, {integer_to_binary, }, {max, },
{min, }, {port_control, }, {port_connect, },
{port_command, }, {port_command, }, {port_close, },
{spawn_monitor, }, {spawn, }, {load_module, },
{spawn_link, }, {binary_to_float, },
{float_to_binary, }, {float_to_binary, },
{list_to_integer, }, {integer_to_binary, },
{binary_to_integer, }, {binary_to_integer, },
{check_old_code, }, {binary_part, }, {binary_part, },
{binary_to_term, }, {binary_to_existing_atom, },
{binary_to_atom, }, {atom_to_binary, },
{bitstring_to_list, }, {list_to_bitstring, },
{bit_size, }, {byte_size, }, {tuple_size, },
{is_bitstring, }, {list_to_existing_atom, },
{iolist_to_binary, }, {iolist_size, },
{is_boolean, }, {is_record, }, {is_record, },
{is_function, }, {is_function, }, {is_binary, },
{is_reference, }, {is_port, }, {is_pid, },
{is_number, }, {is_integer, }, {is_float, },
{is_tuple, }, {is_list, }, {is_atom, }, {error, },
{error, }, {is_process_alive, }, {demonitor, },
{demonitor, }, {monitor, }, {whereis, },
{unregister, }, {unlink, }, {tuple_to_list, },
{trunc, }, {tl, }, {time, }, {throw, },
{term_to_binary, }, {term_to_binary, },
{statistics, }, {split_binary, }, {spawn_link, },
{spawn, }, {size, }, {setelement, }, {self, },
{round, }, {registered, }, {register, }, {put, },
{purge_module, }, {processes, }, {process_info, },
{process_info, }, {process_flag, }, {process_flag, },
{pre_loaded, }, {pid_to_list, }, {open_port, },
{now, }, {nodes, }, {node, }, {node, },
{monitor_node, }, {module_loaded, }, {make_ref, },
{list_to_tuple, }, {list_to_pid, },
{list_to_integer, }, {list_to_float, },
{list_to_binary, }, {list_to_atom, }, {link, },
{length, }, {is_alive, }, {integer_to_list, },
{hd, }, {halt, }, {halt, }, {halt, },
{group_leader, }, {group_leader, }, {get_keys, },
{get, }, {get, }, {garbage_collect, },
{garbage_collect, }, {float_to_list, },
{float_to_list, }, {float, }, {exit, }, {exit, },
{erase, }, {erase, }, {element, },
{delete_module, }, {date, }, {check_process_code, },
{binary_to_term, }, {binary_to_list, },
{binary_to_list, }, {atom_to_list, }, {apply, },
{abs, }]}). -file("/data2/elixir/m.ex", ). -module('Elixir.Math'). -export(['__info__'/, sum/]). '__info__'(functions) -> [{sum, }];
'__info__'(macros) -> [];
'__info__'(docs) ->
[{{sum, }, , def,
[{a, [{line, }], nil}, {b, [{line, }], nil}], nil}];
'__info__'(moduledoc) -> {, nil};
'__info__'(module) -> 'Elixir.Math';
'__info__'(atom) -> module_info(atom). sum(a, b) -> a + b.
ok
>
如何编译的?
下面我们探究一下Elixir编译的过程,切入点当然是elixirc,打开这个脚本:
可以看到完成了一些环境变量解析之后,最终是调用了elixir
exec "$SCRIPT_PATH"/elixir +compile "$@"
OK,我们继续跟进elixir,经过一番参数检查,变量解析后,最后执行的命令类似下面:
erl -pa "$SCRIPT_PATH"/../lib/*/ebin -noshell -s elixir start_cli -extra +compile
简单回顾一下erlang 运行时环境启动的参数,erl的参数分三种:加号+后面跟的是 emulator flags,单连字符"-"后面跟的是flags,init进程会完成这些参数的解析; -extra 后面跟的内容都会被当做是plain arguments. http://erlang.org/doc/man/erl.html
% erl +W w -sname arnie +R -s my_init -extra +bertie
(arnie@host)> init:get_argument(sname).
{ok,[["arnie"]]}
(arnie@host)> init:get_plain_arguments().
["+bertie"]
Here +W w and +R 9 are emulator flags. -s my_init is an init flag, interpreted by init. -sname arnie is a user flag, stored by init. It is read by Kernel and will cause the Erlang runtime system to become distributed. Finally, everything after -extra (that is, +bertie) is considered as plain arguments.
% erl -myflag
> init:get_argument(myflag).
{ok,[[""]]}
> init:get_plain_arguments().
[]
Here the user flag -myflag 1 is passed to and stored by the init process. It is a user defined flag, presumably used by some user defined application.
书归正传,elixir代码里面给我们后续跟进的线索"-s elixir start_cli",废话少说,打开文件:
%% Boot and process given options. Invoked by Elixir's script.
start_cli() ->
application:start(?MODULE), 'Elixir.Kernel.CLI':main(init:get_plain_arguments()).
ok,下面我们手工完成m.ex文件的编译过程(为了方便执行你可以去/elixir/lib/elixir/ebin文件夹),我们分两步1.启动elixir 2.调用编译函数 'Elixir.Kernel.CLI':main(["+compile","m.ex"]).之所以要启动elixir,是为了完成类似code_server的职责.
[root@nimbus ebin]# erl
Erlang R16B01 (erts-5.10.) [source] [-bit] [smp::] [async-threads:] [hipe] [kernel-poll:false] Eshell V5.10.2 (abort with ^G)
> application:start(elixir).
ok > 'Elixir.Kernel.CLI':main(["+compile","m.ex"]).
检查文件夹中的文件,是不是已经编译好了.
{ok,"今天就到这里."}
如果你要继续跟进代码,你可以看到:
@doc """
This is the API invoked by Elixir boot process.
"""
def main(argv) do
argv = lc arg inlist argv, do: String.from_char_list!(arg) { config, argv } = process_argv(argv, Kernel.CLI.Config.new)
System.argv(argv) run fn ->
command_results = Enum.map(Enum.reverse(config.commands), &process_command(&1, config))
command_errors = lc { :error, msg } inlist command_results, do: msg
errors = Enum.reverse(config.errors) ++ command_errors if errors != [] do
Enum.each(errors, &IO.puts(:stderr, &1))
System.halt(1)
end
end, config.halt
end
defp process_argv(["+compile"|t], config) do
process_compiler t, config
end
最后,于"金蝉脱壳"上映之际小图一张
![[Erlang 0109] From Elixir to Erlang Code [Erlang 0109] From Elixir to Erlang Code](https://image.miaokee.com:8440/aHR0cHM6Ly9pbWFnZXMwLmNuYmxvZ3MuY29tL2Jsb2cvMTczMjkvMjAxMzExLzI1MTY0ODM4LTM4N2NmOTUzMjJkYzQwYTlhMzc1ZTZhNDE0MjI1YWRhLmdpZg%3D%3D.gif?w=700&webp=1)