Ruby interpreter
Ruby (Rails)app
RubyGems/Bundler
So many gems
such as Rails, pry, thin, … and so on.
普通のRubyプログラミング
i gigantum umeris insidentes
Standing on the shoulders of giants
5.
Interpret on RubyVM
ふつうのRuby 処理系プログラミング
5
Ruby
script
Parse
Compile
(codegen)
Ruby
Bytecode
Object management
Garbage collectorThreading
Embedded
classes and methods
Bundled
Libraries
Evaluator
Gem
Libraries
AST
Abstract Syntax Tree
VM – StackMachine
12
Ruby Program
a = b + c
getlocal b
getlocal c
send :+, 1
setlocal a
YARV Instructions
a
b
c b
c
b+c
b+c
YARV Stack
Compile
今日は、スタックマシンをたくさん使うよ。
入力と出力
ほかの言語では?
X language
program
Parse
Compile
Code
AST
Abstract SyntaxTree
入力 出力
C コンパイラ(gccとか) C プログラム 機械語(アセンブラ)
Java (javac) Java プログラム JavaVM バイトコード(.class)
JavaScript (babel) JavaScript (ES6, …) JavaScript (ES5)
Ruby Interpreter Ruby プログラム Ruby VM バイトコード
Ruby Interpreter
JIT compiler
Ruby プログラム C ソースコード(実行時にコン
パイル&ロード)
デモ:実際に Ruby VM バイトコードを見てみよう
18.
AST: Abstract SyntaxTree
# Ruby script
a = 10
if a > 1
p :ok
else
p :ng
end
Program
LvarAssign if
a
10
Lvar
send
a
>
1
send
(fcall)
p
:ok
send
(fcall)
p
:ng
字句解析
構文解析
Tips: 字句解析・構文解析について、詳しくは去年の青木さんの資料を読もう
https://speakerdeck.com/aamine/cookpad-2016-summer-intern-programming-paradigm
Seq
Literal
Literal Literal Literal
19.
Ruby Bytecode
# Rubyscript
a = 10
if a > 1
p :ok
else
p :ng
end
0000 putobject 10
0002 setlocal a, 0
0005 getlocal a, 0
0008 putobject 1
0010 send <callinfo!mid:>, argc:1, ARGS_SIMPLE>,
<callcache>, nil
0014 branchunless 27
0016 jump 18
0018 putself
0019 putobject :ok
0021 send <callinfo!mid:p, argc:1, FCALL|ARGS_SIMPLE>,
<callcache>, nil
0025 jump 34
0027 putself
0028 putobject :ng
0030 send <callinfo!mid:p, argc:1, FCALL|ARGS_SIMPLE>,
<callcache>, nil
0034 leave
課題A-5’ else の無いif 文は?
•else の無い次のプログラムを変換
•Hint: 実際に実行して、if文の値を確かめよう
# Ruby script (1)
a = 10
if a > 1
p :ok
end
# Ruby script (2)
a = 10
if a < 1
p :ok
end
56.
課題A-6 while 文
•ヒント:jumpと branch* で while を表現。
•ヒント:pop 命令を(多分)利用します。
a = 0
while(a < 10)
p a
a += 1 #=> a = a.+(1)
end
a #=> 10