4. 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
12. VM – Stack Machine
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
今日は、スタックマシンをたくさん使うよ。
17. 入力と出力
ほかの言語では?
X language
program
Parse
Compile
Code
AST
Abstract Syntax Tree
入力 出力
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 Syntax Tree
# 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
# Ruby script
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
55. 課題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
60. 課題A-7 メソッド定義
def fib(n)
if n < 2
1
else
fib(n – 2) + fib(n-1)
end
end
fib(10)
# param
def foo(a)
a
end
foo(100)
# no param
def foo()
end
引数+呼び出し fib 定義と fib(10) の呼び出し