erlang 中间码
1. core中间码的形成
对于文件test.erl, 可以在编译的时候,加to_core 参数
c(test, [to_core]).
2. 其他中间码的形成
参考: erlang虚拟机代码执行原理
3. 应用
今天在看代码的时候发现一个写法
-module(test).
-export([test/0]).
test() ->
Hello = lists:concat(["he", "llo"]),
World = lists:concat(["wo", "rld"]),
case Hello =/= "hello" orelse World of
"world" ->
true;
_ ->
false
end.
执行
1> c(test).
{ok,test}
2> test:test().
true
也就是说如果”短路或”的前面一个表达式的值是false,那么结果将会是后面一个表达式的值。还是蛮奇怪的,之前一直以为这是一个错误的表达式。。
为了看下虚拟机怎么处理这个问题, 学了下erlang core code 的生成。
就是c(test, [to_core]).
,可以将test.erl -> test.core
test.core 截取如下
module 'test' ['module_info'/0,
'module_info'/1,
'test'/0]
attributes []
'test'/0 =
%% Line 4
fun () ->
let <Hello> =
call %% Line 5
'lists':%% Line 5
'concat'
(%% Line 5
[[104|[101]]|[[108|[108|[111]]]]])
in let <World> =
call %% Line 6
'lists':%% Line 6
'concat'
(%% Line 6
[[119|[111]]|[[114|[108|[100]]]]])
in let <_cor4> =
case <> of
%% Line 7
( <>
when call 'erlang':'=/='
(Hello,
[104|[101|[108|[108|[111]]]]]) ->
'true'
-| ['compiler_generated'] )
%% Line 7
( <> when 'true' ->
World
-| ['compiler_generated'] )
end
in %% Line 7
case _cor4 of
%% Line 8
<[119|[111|[114|[108|[100]]]]]> when 'true' ->
%% Line 9
'true'
%% Line 10
<_cor6> when 'true' ->
%% Line 11
'false'
end
'module_info'/0 =
fun () ->
call 'erlang':'get_module_info'
('test')
'module_info'/1 =
fun (_cor0) ->
call 'erlang':'get_module_info'
('test', _cor0)
end
可以看出<_cor4> 的赋值, 如果前一个表达式不成立的时候,就直接返回World的值。