2011-12-20 78 views
2

我最近一直在通過Programming Language Pragmatics 3rd ed的方式工作,以瞭解更多關於語言如何在底層工作的內容,而且我已經看到由真正基本的GCC編譯的C代碼生成的程序集中獲得了很多里程。我開始習慣於C系列的靜態語言,我也想開始研究解釋型語言。看到Ruby的引擎蓋?

Ruby,作爲我最喜歡的腳本語言,將是一個很好的候選人。我認爲可以從MRI開始學習,並確定所有掃描/解析/語義分析/綁定/範圍界定以及其他魔法在幕後發生的情況。

這是詳細描述的任何地方,或者有什麼辦法讓我深入挖掘它,就像說,與反彙編編譯的程序?我還沒有用解釋性語言進行很多挖掘,所以就MRI而言,我不知道從哪裏開始。

謝謝!

回答

4

您可以在Ruby源代碼中的任何一位的YARV字節碼與RubyVM::InstructionSequence

這裏偷看是一個簡單的例子:

class Greeter 
    def initialize(name) 
    @name = name 
    end 
    def greet! 
    puts @name 
    end 
end 

Greeter.new("Charlie").greet! 

然後你可以編譯和拆解:

puts RubyVM::InstructionSequence.compile(src).disassemble 

並得到這樣的一些輸出:

== disasm: <RubyVM::InstructionSequence:<compiled>@<compiled>>========== 
0000 trace   1            ( 1) 
0002 putspecialobject 3 
0004 putnil   
0005 defineclass  :Greeter, <class:Greeter>, 3 
0009 pop    
0010 trace   1            ( 10) 
0012 getinlinecache 19, <ic:0> 
0015 getconstant  :Greeter 
0017 setinlinecache <ic:0> 
0019 putstring  "Charlie" 
0021 send    :new, 1, nil, 0, <ic:1> 
0027 send    :greet!, 0, nil, 0, <ic:2> 
0033 leave    
== disasm: <RubyVM::InstructionSequence:<class:Greeter>@<compiled>>===== 
0000 trace   2            ( 1) 
0002 trace   1            ( 2) 
0004 putspecialobject 1 
0006 putspecialobject 2 
0008 putobject  :initialize 
0010 putiseq   initialize 
0012 send    :"core#define_method", 3, nil, 0, <ic:0> 
0018 pop    
0019 trace   1            ( 5) 
0021 putspecialobject 1 
0023 putspecialobject 2 
0025 putobject  :greet! 
0027 putiseq   greet! 
0029 send    :"core#define_method", 3, nil, 0, <ic:1> 
0035 trace   4            ( 8) 
0037 leave               ( 5) 
== disasm: <RubyVM::InstructionSequence:[email protected]<compiled>>========== 
local table (size: 2, argc: 1 [opts: 0, rest: -1, post: 0, block: -1] s1) 
[ 2] name<Arg> 
0000 trace   8            ( 2) 
0002 trace   1            ( 3) 
0004 getlocal   name 
0006 dup    
0007 setinstancevariable :@name, <ic:0> 
0010 trace   16            ( 4) 
0012 leave               ( 3) 
== disasm: <RubyVM::InstructionSequence:[email protected]<compiled>>============== 
0000 trace   8            ( 5) 
0002 trace   1            ( 6) 
0004 putnil   
0005 getinstancevariable :@name, <ic:0> 
0008 send    :puts, 1, nil, 8, <ic:1> 
0014 trace   16            ( 7) 
0016 leave               ( 6) 
+0

YARV上的維基百科頁面表明,它是從1.9開始運行的節目,所以它看起來像你能看到規範的Ruby(而不是說,rubinius和jruby?)那麼接近嗎?這或多或少是準確的? – 2011-12-20 07:20:28

+0

@ glitch是的。 Rubinius和JRuby都有自己的字節碼,應該很容易查看 – 2011-12-20 07:55:33

1

a Japanese book描述MRI 1.7.3的內部工作稱爲Ruby黑客指南。 A partial English translation可用。

即使翻譯不完整,本書基於舊版本的ruby,但我仍然認爲它是一個極好的資源。本書涵蓋的許多內容在當前的Ruby版本中可能仍然相關,比如對象的結構,實例變量的存儲方式,如何完成方法查找等等。

這是一個非常有趣的閱讀。不過,你必須注意版本之間的差異。始終保持手頭上的ruby source code