[Erlang 0113] Elixir 编译流程梳理
注意:目前Elixir版本还不稳定,代码调整较大,本文随时失效


-module(elixir).
......
start_cli() ->
application:start(?MODULE),
%% start_cli() --> ["+compile","m.ex"]
'Elixir.Kernel.CLI':main(init:get_plain_arguments()).
defmodule Kernel.CLI do
......
if files != [] do
wrapper fn ->
Code.compiler_options(config.compiler_options)
Kernel.ParallelCompiler.files_to_path(files, config.output,
each_file: fn file -> if config.verbose_compile do IO.puts "Compiled #{file}" end end)
end
else
{ :error, "--compile : No files matched patterns #{Enum.join(patterns, ",")}" }
end
defmodule Kernel.ParallelCompiler do
.....
try do
if output do
:elixir_compiler.file_to_path(h, output)
else
:elixir_compiler.file(h)
end
parent <- { :compiled, self(), h }
catch
kind, reason ->
parent <- { :failure, self(), kind, reason, System.stacktrace }
end
-module(elixir_compiler). file(Relative) when is_binary(Relative) ->
File = filename:absname(Relative),
{ ok, Bin } = file:read_file(File),
string(elixir_utils:characters_to_list(Bin), File). string(Contents, File) when is_list(Contents), is_binary(File) ->
Forms = elixir_translator:'forms!'(Contents, 1, File, []),
quoted(Forms, File).
[{defmodule,
[{line,1}],
[{'__aliases__',[{line,1}],['Math']},
[{do,
{def,[{line,2}],[{sum,[{line,2}],[{a,[{line,2}],nil},{b,[{line,2}],nil}]},
[{do,{'__block__',[],[
{'=',[{line,3}],[{a,[{line,3}],nil},123]},
{'=',[{line,4}],[{a,[{line,4}],nil},2365]},
{'+',[{line,5}],[
{a,[{line,5}],nil},{b,[{line,5}],nil}]}
]}}]]}}]]}]
-record(elixir_scope, {
context=nil, %% can be assign, guards or nil
extra=nil, %% extra information about the context, like fn_match for fns
noname=false, %% when true, don't add new names (used by try)
super=false, %% when true, it means super was invoked
caller=false, %% when true, it means caller was invoked
module=nil, %% the current module
function=nil, %% the current function
vars=[], %% a dict of defined variables and their alias
backup_vars=nil, %% a copy of vars to be used on ^var
temp_vars=nil, %% a set of all variables defined in a particular assign
clause_vars=nil, %% a dict of all variables defined in a particular clause
extra_guards=nil, %% extra guards from args expansion
counter=[], %% a counter for the variables defined
local=nil, %% the scope to evaluate local functions against
context_modules=[], %% modules defined in the current context
macro_aliases=[], %% keep aliases defined inside a macro
macro_counter=0, %% macros expansions counter
lexical_tracker=nil, %% holds the lexical tracker pid
aliases, %% an orddict with aliases by new -> old names
file, %% the current scope filename
requires, %% a set with modules required
macros, %% a list with macros imported from module
functions %% a list with functions imported from module
}).
quoted方法最近的变化是使用elixir_lexical:run包装了一下,之前的版本简单直接,可以先看一下:
quoted(Forms, File) when is_binary(File) ->
Previous = get(elixir_compiled),
% M:elixir_compiler Previous undefined
try
put(elixir_compiled, []),
eval_forms(Forms, 1, [], elixir:scope_for_eval([{file,File}])),
lists:reverse(get(elixir_compiled))
after
put(elixir_compiled, Previous)
end.
现在quoted是这样的:
quoted(Forms, File) when is_binary(File) ->
Previous = get(elixir_compiled),
try
put(elixir_compiled, []),
elixir_lexical:run(File, fun
(Pid) ->
Scope = elixir:scope_for_eval([{file,File}]),
eval_forms(Forms, 1, [], Scope#elixir_scope{lexical_tracker=Pid})
end),
lists:reverse(get(elixir_compiled))
after
put(elixir_compiled, Previous)
end.
quoted方法里面我们需要重点关注的是eval_forms方法,在这个方法里面完成了Elixir AST到Erlang AST转换,Elixir表达式通过 elixir_translator:translate被翻译成对应的Erlang Abstract Format.之后eval_mod(Fun, Exprs, Line, File, Module, Vars)完成对表达式和代码其它部分(比如attribute,等等)进行组合.
eval_forms(Forms, Line, Vars, S) ->
{ Module, I } = retrieve_module_name(),
{ Exprs, FS } = elixir_translator:translate(Forms, S), Fun = eval_fun(S#elixir_scope.module),
Form = eval_mod(Fun, Exprs, Line, S#elixir_scope.file, Module, Vars),
Args = list_to_tuple([V || { _, V } <- Vars]), %% Pass { native, false } to speed up bootstrap
%% process when native is set to true
{ module(Form, S#elixir_scope.file, [{native,false}], true,
fun(_, Binary) ->
Res = Module:Fun(Args),
code:delete(Module),
%% If we have labeled locals, anonymous functions
%% were created and therefore we cannot ditch the
%% module
case beam_lib:chunks(Binary, [labeled_locals]) of
{ ok, { _, [{ labeled_locals, []}] } } ->
code:purge(Module),
return_module_name(I);
_ ->
ok
end, Res
end), FS }.
最后完成编译和加载的重头戏就在module(Forms, File, Opts, Callback)方法了:
%% Compile the module by forms based on the scope information
%% executes the callback in case of success. This automatically
%% handles errors and warnings. Used by this module and elixir_module.
module(Forms, File, Opts, Callback) ->
DebugInfo = (get_opt(debug_info) == true) orelse lists:member(debug_info, Opts),
Final =
if DebugInfo -> [debug_info];
true -> []
end,
module(Forms, File, Final, false, Callback). module(Forms, File, RawOptions, Bootstrap, Callback) when
is_binary(File), is_list(Forms), is_list(RawOptions), is_boolean(Bootstrap), is_function(Callback) ->
{ Options, SkipNative } = compile_opts(Forms, RawOptions),
Listname = elixir_utils:characters_to_list(File), case compile:noenv_forms([no_auto_import()|Forms], [return,{source,Listname}|Options]) of
{ok, ModuleName, Binary, RawWarnings} ->
Warnings = case SkipNative of
true -> [{?MODULE,[{0,?MODULE,{skip_native,ModuleName}}]}|RawWarnings];
false -> RawWarnings
end,
format_warnings(Bootstrap, Warnings),
%%%% ModuleName :'Elixir.Math' ListName: "/data2/elixir/m.ex"
code:load_binary(ModuleName, Listname, Binary),
Callback(ModuleName, Binary);
{error, Errors, Warnings} ->
format_warnings(Bootstrap, Warnings),
format_errors(Errors)
end.
到这里编译的流程已经走完,附上几个可能会用到的资料,首先是elixir_parser:parse(Tokens)的代码,你可能会奇怪这个模块的代码在哪里?这个是通过elixir_parser.yrl编译自动生成的模块,你可以使用下面的方法拿到它的代码:
Eshell V5.10.2 (abort with ^G)
1> {ok,{_,[{abstract_code,{_,AC}}]}} = beam_lib:chunks("elixir_parser",[abstract_code]).
{ok,{elixir_parser,
[{abstract_code,
........
{...}|...]}}]}}
2> Dump= fun(Content)-> file:write_file("/data/dump.data", io_lib:fwrite("~ts.\n", [Content])) end.
#Fun<erl_eval.6.80484245>
3> Dump(erl_prettypr:format(erl_syntax:form_list(AC))).
ok
4>
- elixir_aliases的设计
- elixir_scope 的设计
- elixir macro 相关的几个话题:hygiene unquote_splicing
马背上的Godiva夫人
主人公:戈黛娃夫人Lady Godiva,或称Godgifu,约990年—1067年9月10日
作者:约翰·柯里尔(John Collier)所绘,约1898年
据说大约在1040年,统治考文垂(Coventry)城市的Leofric the Dane伯爵决定向人民征收重税,支持军队出战,令人民的生活苦不堪言。伯爵善良美丽的妻子Godiva夫人眼见民生疾苦,决定恳求伯爵减收徵税,减轻人民的负担。Leofric伯爵勃然大怒,认为Godiva夫人为了这班爱哭哭啼啼的贱民苦苦衷求,实在丢脸。Godiva夫人却回答说伯爵定会发现这些人民是多么可敬。他们决定打赌——Godiva夫人要赤裸身躯骑马走过城中大街,仅以长发遮掩身体,假如人民全部留在屋内,不偷望Godiva夫人的话,伯爵便会宣布减税。翌日早上,Godiva夫人骑上马走向城中,Coventry市所有百姓都诚实地躲避在屋内,令大恩人不至蒙羞。事后,Leofric伯爵信守诺言,宣布全城减税。这就是著名的Godiva夫人传说。

[Erlang 0113] Elixir 编译流程梳理的更多相关文章
- .16-浅析webpack源码之编译后流程梳理
这节把编译打包后的流程梳理一下,然后集中处理compile. 之前忽略了一个点,如下: new NodeEnvironmentPlugin().apply(compiler); // 引入插件加载 i ...
- [Erlang 0108] Elixir 入门
Erlang Resources里面关于Elixir的资料越来越多,加上Joe Armstrong的这篇文章,对Elixir的兴趣也越来越浓厚,投入零散时间学习了一下.零零散散,测试代码写了一些,Ev ...
- Erlang 和 Elixir 互相调用 (转)
lixr设计目标之一就是要确保兼容性,可以兼容Erlang和其生态系统.Elixir和Erlang 都是运行同样的虚拟机平台(Erlang Virtual Machine).不管是在Erlang使用E ...
- Erlang 和 Elixir的差异
原文: http://elixir-lang.org/crash-course.html 函数调用 Elixir允许你调用函数的时候省略括号, Erlang不行. Erlang Elixir some ...
- CentOS 7.7安装Erlang和Elixir
安装之前,先看一下它们的简要说明 Erlang Erlang是一种开源编程语言,用于构建对高可用性有要求的大规模可扩展的软实时系统.它通常用于电信,银行,电子商务,计算机电话和即时消息中.Erlang ...
- 从一次编译出发梳理概念: Jetty,Jersey,hk2,glassFish,Javax,Jakarta
从一次编译出发梳理概念: Jetty,Jersey,hk2,glassFish,Javax,Jakarta 目录 从一次编译出发梳理概念: Jetty,Jersey,hk2,glassFish,Jav ...
- zookeeper心跳机制流程梳理
zookeeper心跳机制流程梳理 Processor链Chain protected void setupRequestProcessors() { RequestProcessor finalPr ...
- Gcc的编译流程分为了四个步骤:
http://blog.csdn.net/xiaohouye/article/details/52084770(转) Gcc的编译流程分为了四个步骤: 1.预处理,生成预编译文件(.文件): Gcc ...
- 编译流程,C开发常见文件类型名
编译流程 我们常说的编译是一个整体的概念,是指从源程序到可执行程序的整个过程,实际上,C语言编译的过程可以进一步细分为预编译->编译->汇编->链接 预编译是把include关键字所 ...
随机推荐
- 创建DbContext
返回总目录<一步一步使用ABP框架搭建正式项目系列教程> 上一篇介绍了<创建实体>,这一篇我们顺其自然地介绍<创建DbContext>. 温故: 提到DbConte ...
- ABP框架 - 介绍
文档目录 本节内容: 简介 一个快速示例 其它特性 启动模板 如何使用 简介 我们总是对不同的需求开发不同的应用.但至少在某些层面上,一次又一次地重复实现通用的和类似的功能.如:授权,验证,异常处理, ...
- C# - 缓存OutputCache(二)缓存详细介绍
本文是通过网上&个人总结的 1.缓存介绍 缓存是为了提高访问速度,而做的技术. 缓存主要有以下几类:1)客户端缓存Client Caching 2)代理缓存Proxy Caching 3)方向 ...
- linux shell 中的sleep命令
开始还以为是这样的语法: sleep(1), 后面发现是: linux shell 中的sleep命令 分类: LINUX 在有的shell(比如linux中的bash)中sleep还支持睡眠(分,小 ...
- Atitit 硬件 软件 的开源工作 差异对比
Atitit 硬件 软件 的开源工作 差异对比 1.1. 模块化,标准化,以及修改的便捷性1 1.2. 生产和发布成本 1 1.3. 3. 入行门槛搞2 1.4. 在软件业极度发达的今天,任何具 ...
- iOS 之项目中遇到的问题总结
昨天去一家公司面试,面试官问了我在项目开发中遇到过哪些问题,是什么引起的,怎样解决的? 当时由于有点小紧张只说出了一两点,现在就来好好总结一下. 问题: 1.两表联动 所谓的两表联动就是有左右两个表格 ...
- 【.net深呼吸】动态类型(高级篇)
前面老周给大家介绍了动态类型使用的娱乐级别用法,其实,在很多情景下,娱乐级别的用法已经满足需求了. 如果,你想自己来控制动态类型的行为和数据的存取,那么,就可以考虑用今天所说的高大上技术了.比如,你希 ...
- PostCSS深入学习: PostCSS和Sass、Stylus或LESS一起使用
如果你喜欢使用PostCSS,但又不想抛弃你最喜欢的预处理器.不用担心,你不需要作出二选一的选择,你可以把PostCSS和预处理器(Sass.Stylus或LESS)结合起来使用. 有几个PostCS ...
- 使用UICollectionView实现首页的滚动效果
实现类似这样的效果,可以滚动大概有两种实现方案 1. 使用scrollview来实现 2. 使用UICollectionView来实现 第一种比较简单,而且相对于性能来说不太好,于是我们使用第二种方案 ...
- 【NLP】基于统计学习方法角度谈谈CRF(四)
基于统计学习方法角度谈谈CRF 作者:白宁超 2016年8月2日13:59:46 [摘要]:条件随机场用于序列标注,数据分割等自然语言处理中,表现出很好的效果.在中文分词.中文人名识别和歧义消解等任务 ...