隨着erlang的不斷髮展,它的語法越來越複雜,不便於諸如分析器,調試器此類程序在源碼層次直接進行解析,而CORE Erlang旨在爲Erlang提供一個人類可讀可改的中間表示(Intermediate representation),這樣就能方便麪向程序源碼的工具的開發。
千言萬語不如代碼一句。這裏我們通過一個例子來直觀的瞭解究竟什麼是CORE Erlang。在helloworld.erl中輸入如下代碼:
-module (helloworld).
-export([simple/0, complicated/2]).
simple() ->
atom_to_list(hello_world).
complicated(Type,List) ->
List = [{Type,Elem} || Elem<-List,is_atom(Elem)],
case Type of
bool when bool =:= true -> R1 = bool_true;
bool -> R1 = bool_false;
integer -> R1 = 1+2*3/4
end.
Erlang/OTP R10以及之後發行的版本在編譯helloworld.erl時傳入to_core標誌:
c(helloworld,to_core).
將會生成CORE Erlang文件helloworld.core:
module 'helloworld' ['complicated'/2,
'module_info'/0,
'module_info'/1,
'simple'/0]
attributes [%% Line 1
'file' =
%% Line 1
[{[104|[101|[108|[108|[111|[119|[111|[114|[108|[100|[46|[101|[114|[108]]]]]]]]]]]]]],1}]]
'simple'/0 =
%% Line 4
fun () ->
%% Line 5
[104|[101|[108|[108|[111|[95|[119|[111|[114|[108|[100]]]]]]]]]]]
可以看到,模塊頭部信息和helloworld:simple()函數在CORE Erlang中還是很清楚的,但是對於helloworld:complicated(Type,List)它就完全背離了自己的初衷:
'complicated'/2 =
%% Line 7
fun (_@c1,_@c0) ->
let <_@c6> =
letrec
'lc$^0'/1 =
%% Line 8
fun (_@c4) ->
case _@c4 of
<[Elem|_@c3]>
when call 'erlang':'is_atom'
(Elem) ->
let <_@c5> =
apply 'lc$^0'/1
(_@c3)
in ( [{_@c1,Elem}|_@c5]
-| ['compiler_generated'] )
( <[Elem|_@c3]> when 'true' ->
apply 'lc$^0'/1
(_@c3)
-| ['compiler_generated'] )
<[]> when 'true' ->
[]
( <_@c4> when 'true' ->
( primop 'match_fail'
({'function_clause',_@c4})
-| [{'function_name',{'lc$^0',1}}] )
-| ['compiler_generated'] )
end
in %% Line 8
apply 'lc$^0'/1
(_@c0)
in %% Line 8
case _@c6 of
<_@c16>
when call 'erlang':'=:='
(_@c6,
_@c0) ->
%% Line 9
case _@c1 of
%% Line 11
<'bool'> when 'true' ->
'bool_false'
%% Line 12
<'integer'> when 'true' ->
2.50000000000000000000e+00
( <_@c13> when 'true' ->
primop 'match_fail'
({'case_clause',_@c13})
-| ['compiler_generated'] )
end
( <_@c7> when 'true' ->
primop 'match_fail'
({'badmatch',_@c7})
-| ['compiler_generated'] )
end
'module_info'/0 =
fun () ->
call 'erlang':'get_module_info'
('helloworld')
'module_info'/1 =
fun (_@c0) ->
call 'erlang':'get_module_info'
('helloworld', _@c0)
end
不過話又說回來,CORE Erlang的受衆終究是代碼分析器,調試器之類的工具,人類可讀可改更像是一個崇高追求,如果我們觀察會發現CORE Erlang的中間表示的確降低了語法的解析難度,它將源碼的各種語法用let in,call ,case of,fun等幾個簡單的結構來表示,從這點來看CORE Erlang算是到達了它的初衷。
[+] core erlang project index : http://www.it.uu.se/research/group/hipe/cerl/`