SlideShare a Scribd company logo
1 of 26
Download to read offline
Hackarade #04
"Create your own interpreter"
Yusuke Endoh (@mametter)
2018/10/05 (Fri.)
Today's Goal
• Write a Ruby interpreter in Ruby
Today's Goal
• Write a Ruby interpreter in Ruby
✕ eval(File.read(ARGV[0]))
Today's Goal
• Write a Ruby interpreter in Ruby
✕
✔
eval(File.read(ARGV[0]))
evaluate(
parse(
File.read(ARGV[0])))
A simple structure of interpreter
Parser Evaluator
puts 3*(2+2)
Program
12
Output
+
• Built-in features (String, Array, etc.)
• Memory management (GC)
• Libraries
Interpreter
Parser
• Converts a program text to
"abstract syntax tree" (AST)
Parser
puts 3*(2+2)
Program
func_call
AST
*
+
"puts"
3
2 2
Evaluator
• Runs the instruction by walking AST
func_call
AST
*
+
"puts"
3
2 2
Evaluator
Evaluator
• Runs the instruction by walking AST
func_call
AST
*"puts"
3
Evaluator
4
Evaluator
• Runs the instruction by walking AST
func_call
AST
"puts" 12
Evaluator
Evaluator
• Runs the instruction by walking AST
AST
nil
Evaluator
12
Output
Today's Goal
• Write a Ruby interpreter in Ruby
Today's Goal
• Write a Ruby interpreter in Ruby
– Impossible in one day!
Today's Goal
• Write a Ruby interpreter in Ruby
– Impossible in one day!
• More precisely:
Write a "MinRuby" interpreter in Ruby
Today's Goal
• Write a Ruby interpreter in Ruby
– Impossible in one day!
• More precisely:
Write a "MinRuby" interpreter in Ruby
– Runs a program written in MinRuby
(Target language)
– Is written in Ruby (Host language)
MinRuby
• Very small subset of Ruby
– Arithmetic, comparison:
– Statements, variables:
– Branches, loop:
– Function call:
– Function definition:
– Array and Hash:
1+2*3 42>40
x=42; x=x+1; p(x)
if x < 2 while x < 10
func(1,2) p(42)
def func(x,y); …; end
a=[1,2,3]; a[1]=42; p(a[0])
3*4==5+7
h={}; h["foo"]="bar"; p(h["foo"])
MinRuby
• Very small subset of Ruby
– Arithmetic, comparison:
– Statements, variables:
– Branches, loop:
– Function call:
– Function definition:
– Array and Hash:
• Class? Method call? Block? Not needed.
1+2*3 42>40
x=42; x=x+1; p(x)
if x < 2 while x < 10
func(1,2) p(42)
def func(x,y); …; end
a=[1,2,3]; a[1]=42; p(a[0])
3*4==5+7
h={}; h["foo"]="bar"; p(h["foo"])
Your task
• Write "interp.rb"
• Check if it works as the same as Ruby
# test1-1.rb
p(1 + 1)
def parse(src); …; end
def evaluate(tree); …; end
evaluate(parse(File.read(ARGV[0])))
$ ruby test1-1.rb
2
$ ruby interp.rb test1-1.rb
2
Focus: Evaluator
Parser Evaluator
puts 3*(2+2)
Program
12
Output
Interpreter
Use
"minruby"
gem
A skeleton
code is
provided
"minruby" gem
• Provides a MinRuby parser
require "minruby"
p minruby_parse( "3*(2+2)" )
#=> ["*",
["lit", 3],
["+",
["lit", 2],
["lit", 2]
]
]
*
+3
2 2
Observe!
A evaluator skeleton
• MinRuby interpreter with many "holes"
# An implementation of the evaluator
def evaluate(exp, env)
case exp[0]
when "+"
evaluate(exp[1], env) + evaluate(exp[2], env)
when "-"
raise(NotImplementedError) # Problem 1
…
end
end
evaluate(minruby_parse(minruby_load()), {})
Your task
• Complete "interp.rb" and pass all
test programs ("test*-*.rb")
$ ruby interp.rb test1-1.rb
2
$ ruby interp.rb test1-2.rb
Traceback (most recent call last):
2: from interp.rb:168:in `<main>'
1: from interp.rb:94:in `evaluate'
interp.rb:23:in `evaluate': NotImplementedError
Fix it!
Problems 1..6
1. Arithmetics (test1-*.rb)
2. Statements and variables (test2-*.rb)
3. Branches and loops (test3-*.rb)
4. Function calls (test4-*.rb)
5. User-defined functions (test5-*.rb)
6. Arrays and Hashes (test6-*.rb)
– You can implement and test them in turn
Problem 7
• Self-Hosting
– Write a MinRuby interpreter in MinRuby
• MinRuby is limited but still powerful to
implement a MinRuby interpreter!
$ ruby interp.rb interp.rb test1-1.rb
ary.each do |x|
...
end
i = 0
while ary[i]
x = ary[i]
...
end
$ ruby interp.rb interp.rb interp.rb test1-1.rb
Advanced Problems
• Write your own MinRuby parser
• Support advanced features
– Blocks, class/modules, eval, callcc, …
– Increment, lazy eval., type analysis, …
• Write a XXX interpreter in XXX
– MinSwift, Kotlin, Python, JavaScript, …
• Do true self-hosting
– Write a MinRuby parser in MinRuby
• Write a MinRuby compiler in Ruby
Good luck!
• The files and details are available at:
– https://github.com/mame/cookpad-
hackarade-minruby/
• Feel free to ask me any questions
– Or some experts
Answer [PR]
• A book to learn Ruby
by writing Ruby
interpreter in Ruby
– (written in Japanese)

More Related Content

What's hot

JRuby: Pushing the Java Platform Further
JRuby: Pushing the Java Platform FurtherJRuby: Pushing the Java Platform Further
JRuby: Pushing the Java Platform Further
Charles Nutter
 
Replication Internals: The Life of a Write
Replication Internals: The Life of a WriteReplication Internals: The Life of a Write
Replication Internals: The Life of a Write
MongoDB
 
RubyStack: the easiest way to deploy Ruby on Rails
RubyStack: the easiest way to deploy Ruby on RailsRubyStack: the easiest way to deploy Ruby on Rails
RubyStack: the easiest way to deploy Ruby on Rails
elliando dias
 
Join the dart side of webdevelopment reloaded
Join the dart side of webdevelopment reloadedJoin the dart side of webdevelopment reloaded
Join the dart side of webdevelopment reloaded
Claudio d'Angelis
 

What's hot (20)

JRuby: Pushing the Java Platform Further
JRuby: Pushing the Java Platform FurtherJRuby: Pushing the Java Platform Further
JRuby: Pushing the Java Platform Further
 
Replication Internals: The Life of a Write
Replication Internals: The Life of a WriteReplication Internals: The Life of a Write
Replication Internals: The Life of a Write
 
Bringing Concurrency to Ruby - RubyConf India 2014
Bringing Concurrency to Ruby - RubyConf India 2014Bringing Concurrency to Ruby - RubyConf India 2014
Bringing Concurrency to Ruby - RubyConf India 2014
 
Ruby semweb 2011-12-06
Ruby semweb 2011-12-06Ruby semweb 2011-12-06
Ruby semweb 2011-12-06
 
RubyStack: the easiest way to deploy Ruby on Rails
RubyStack: the easiest way to deploy Ruby on RailsRubyStack: the easiest way to deploy Ruby on Rails
RubyStack: the easiest way to deploy Ruby on Rails
 
Building .NET Core tools using the Roslyn API by Arthur Tabatchnic at .Net fo...
Building .NET Core tools using the Roslyn API by Arthur Tabatchnic at .Net fo...Building .NET Core tools using the Roslyn API by Arthur Tabatchnic at .Net fo...
Building .NET Core tools using the Roslyn API by Arthur Tabatchnic at .Net fo...
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Join the dart side of webdevelopment reloaded
Join the dart side of webdevelopment reloadedJoin the dart side of webdevelopment reloaded
Join the dart side of webdevelopment reloaded
 
Hijacking Ruby Syntax in Ruby (RubyConf 2018)
Hijacking Ruby Syntax in Ruby (RubyConf 2018)Hijacking Ruby Syntax in Ruby (RubyConf 2018)
Hijacking Ruby Syntax in Ruby (RubyConf 2018)
 
Wonders of Golang
Wonders of GolangWonders of Golang
Wonders of Golang
 
How to build SDKs in Go
How to build SDKs in GoHow to build SDKs in Go
How to build SDKs in Go
 
Batch import of large RDF datasets into Semantic MediaWiki
Batch import of large RDF datasets into Semantic MediaWikiBatch import of large RDF datasets into Semantic MediaWiki
Batch import of large RDF datasets into Semantic MediaWiki
 
#Pharo Days 2016 Data Formats and Protocols
#Pharo Days 2016 Data Formats and Protocols#Pharo Days 2016 Data Formats and Protocols
#Pharo Days 2016 Data Formats and Protocols
 
Infinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on androidInfinum android talks_10_getting groovy on android
Infinum android talks_10_getting groovy on android
 
Introduction to D programming language at Weka.IO
Introduction to D programming language at Weka.IOIntroduction to D programming language at Weka.IO
Introduction to D programming language at Weka.IO
 
Golang
GolangGolang
Golang
 
Golang
GolangGolang
Golang
 
New c sharp4_features_part_vi
New c sharp4_features_part_viNew c sharp4_features_part_vi
New c sharp4_features_part_vi
 
Dennis Benkert & Matthias Lübken - Patterns in a containerized world? - code....
Dennis Benkert & Matthias Lübken - Patterns in a containerized world? - code....Dennis Benkert & Matthias Lübken - Patterns in a containerized world? - code....
Dennis Benkert & Matthias Lübken - Patterns in a containerized world? - code....
 
Understanding how concurrency work in os
Understanding how concurrency work in osUnderstanding how concurrency work in os
Understanding how concurrency work in os
 

Similar to Cookpad Hackarade #04: Create Your Own Interpreter

AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)
Paul Chao
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011
Agora Group
 
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverageTesting NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
mlilley
 
Shell Tips & Tricks
Shell Tips & TricksShell Tips & Tricks
Shell Tips & Tricks
MongoDB
 

Similar to Cookpad Hackarade #04: Create Your Own Interpreter (20)

Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring Clojurescript
 
Reproducible Computational Research in R
Reproducible Computational Research in RReproducible Computational Research in R
Reproducible Computational Research in R
 
L3.fa14.ppt
L3.fa14.pptL3.fa14.ppt
L3.fa14.ppt
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2
 
Mongo db japan
Mongo db japanMongo db japan
Mongo db japan
 
AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)AI與大數據數據處理 Spark實戰(20171216)
AI與大數據數據處理 Spark實戰(20171216)
 
mapreduce ppt.ppt
mapreduce ppt.pptmapreduce ppt.ppt
mapreduce ppt.ppt
 
#CNX14 - Using Ruby for Reliability, Consistency, and Speed
#CNX14 - Using Ruby for Reliability, Consistency, and Speed#CNX14 - Using Ruby for Reliability, Consistency, and Speed
#CNX14 - Using Ruby for Reliability, Consistency, and Speed
 
20140918 ruby kaigi2014
20140918 ruby kaigi201420140918 ruby kaigi2014
20140918 ruby kaigi2014
 
Clojure intro
Clojure introClojure intro
Clojure intro
 
JavaScript in 2015
JavaScript in 2015JavaScript in 2015
JavaScript in 2015
 
201705 metaprogramming in julia
201705 metaprogramming in julia201705 metaprogramming in julia
201705 metaprogramming in julia
 
Ropython-windbg-python-extensions
Ropython-windbg-python-extensionsRopython-windbg-python-extensions
Ropython-windbg-python-extensions
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable Lisp
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011
 
Scoobi - Scala for Startups
Scoobi - Scala for StartupsScoobi - Scala for Startups
Scoobi - Scala for Startups
 
R for Pirates. ESCCONF October 27, 2011
R for Pirates. ESCCONF October 27, 2011R for Pirates. ESCCONF October 27, 2011
R for Pirates. ESCCONF October 27, 2011
 
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverageTesting NodeJS with Mocha, Should, Sinon, and JSCoverage
Testing NodeJS with Mocha, Should, Sinon, and JSCoverage
 
Shell Tips & Tricks
Shell Tips & TricksShell Tips & Tricks
Shell Tips & Tricks
 
Week1
Week1Week1
Week1
 

More from mametter

クックパッド春の超絶技巧パンまつり 超絶技巧プログラミング編 資料
クックパッド春の超絶技巧パンまつり 超絶技巧プログラミング編 資料クックパッド春の超絶技巧パンまつり 超絶技巧プログラミング編 資料
クックパッド春の超絶技巧パンまつり 超絶技巧プログラミング編 資料
mametter
 
A Static Type Analyzer of Untyped Ruby Code for Ruby 3
A Static Type Analyzer of Untyped Ruby Code for Ruby 3A Static Type Analyzer of Untyped Ruby Code for Ruby 3
A Static Type Analyzer of Untyped Ruby Code for Ruby 3
mametter
 

More from mametter (20)

error_highlight: User-friendly Error Diagnostics
error_highlight: User-friendly Error Diagnosticserror_highlight: User-friendly Error Diagnostics
error_highlight: User-friendly Error Diagnostics
 
TRICK 2022 Results
TRICK 2022 ResultsTRICK 2022 Results
TRICK 2022 Results
 
クックパッド春の超絶技巧パンまつり 超絶技巧プログラミング編 資料
クックパッド春の超絶技巧パンまつり 超絶技巧プログラミング編 資料クックパッド春の超絶技巧パンまつり 超絶技巧プログラミング編 資料
クックパッド春の超絶技巧パンまつり 超絶技巧プログラミング編 資料
 
TypeProf for IDE: Enrich Development Experience without Annotations
TypeProf for IDE: Enrich Development Experience without AnnotationsTypeProf for IDE: Enrich Development Experience without Annotations
TypeProf for IDE: Enrich Development Experience without Annotations
 
Ruby 3の型解析に向けた計画
Ruby 3の型解析に向けた計画Ruby 3の型解析に向けた計画
Ruby 3の型解析に向けた計画
 
emruby: ブラウザで動くRuby
emruby: ブラウザで動くRubyemruby: ブラウザで動くRuby
emruby: ブラウザで動くRuby
 
Type Profiler: Ambitious Type Inference for Ruby 3
Type Profiler: Ambitious Type Inference for Ruby 3Type Profiler: Ambitious Type Inference for Ruby 3
Type Profiler: Ambitious Type Inference for Ruby 3
 
型プロファイラ:抽象解釈に基づくRuby 3の静的解析
型プロファイラ:抽象解釈に基づくRuby 3の静的解析型プロファイラ:抽象解釈に基づくRuby 3の静的解析
型プロファイラ:抽象解釈に基づくRuby 3の静的解析
 
Ruby 3の型推論やってます
Ruby 3の型推論やってますRuby 3の型推論やってます
Ruby 3の型推論やってます
 
マニアックなRuby 2.7新機能紹介
マニアックなRuby 2.7新機能紹介マニアックなRuby 2.7新機能紹介
マニアックなRuby 2.7新機能紹介
 
A Static Type Analyzer of Untyped Ruby Code for Ruby 3
A Static Type Analyzer of Untyped Ruby Code for Ruby 3A Static Type Analyzer of Untyped Ruby Code for Ruby 3
A Static Type Analyzer of Untyped Ruby Code for Ruby 3
 
Ruby 3 の型解析に向けた計画
Ruby 3 の型解析に向けた計画Ruby 3 の型解析に向けた計画
Ruby 3 の型解析に向けた計画
 
本番環境で使える実行コード記録機能
本番環境で使える実行コード記録機能本番環境で使える実行コード記録機能
本番環境で使える実行コード記録機能
 
Transcendental Programming in Ruby
Transcendental Programming in RubyTranscendental Programming in Ruby
Transcendental Programming in Ruby
 
Ruby 3のキーワード引数について考える
Ruby 3のキーワード引数について考えるRuby 3のキーワード引数について考える
Ruby 3のキーワード引数について考える
 
TRICK 2018 results
TRICK 2018 resultsTRICK 2018 results
TRICK 2018 results
 
Type Profiler: An Analysis to guess type signatures
Type Profiler: An Analysis to guess type signaturesType Profiler: An Analysis to guess type signatures
Type Profiler: An Analysis to guess type signatures
 
Esoteric, Obfuscated, Artistic Programming in Ruby
Esoteric, Obfuscated, Artistic Programming in RubyEsoteric, Obfuscated, Artistic Programming in Ruby
Esoteric, Obfuscated, Artistic Programming in Ruby
 
Cookpad Spring 1day internship 2018 超絶技巧プログラミングコース資料
Cookpad Spring 1day internship 2018 超絶技巧プログラミングコース資料Cookpad Spring 1day internship 2018 超絶技巧プログラミングコース資料
Cookpad Spring 1day internship 2018 超絶技巧プログラミングコース資料
 
Esoteric, Obfuscated, Artistic Programming in Ruby
Esoteric, Obfuscated, Artistic Programming in RubyEsoteric, Obfuscated, Artistic Programming in Ruby
Esoteric, Obfuscated, Artistic Programming in Ruby
 

Recently uploaded

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

Cookpad Hackarade #04: Create Your Own Interpreter

  • 1. Hackarade #04 "Create your own interpreter" Yusuke Endoh (@mametter) 2018/10/05 (Fri.)
  • 2. Today's Goal • Write a Ruby interpreter in Ruby
  • 3. Today's Goal • Write a Ruby interpreter in Ruby ✕ eval(File.read(ARGV[0]))
  • 4. Today's Goal • Write a Ruby interpreter in Ruby ✕ ✔ eval(File.read(ARGV[0])) evaluate( parse( File.read(ARGV[0])))
  • 5. A simple structure of interpreter Parser Evaluator puts 3*(2+2) Program 12 Output + • Built-in features (String, Array, etc.) • Memory management (GC) • Libraries Interpreter
  • 6. Parser • Converts a program text to "abstract syntax tree" (AST) Parser puts 3*(2+2) Program func_call AST * + "puts" 3 2 2
  • 7. Evaluator • Runs the instruction by walking AST func_call AST * + "puts" 3 2 2 Evaluator
  • 8. Evaluator • Runs the instruction by walking AST func_call AST *"puts" 3 Evaluator 4
  • 9. Evaluator • Runs the instruction by walking AST func_call AST "puts" 12 Evaluator
  • 10. Evaluator • Runs the instruction by walking AST AST nil Evaluator 12 Output
  • 11. Today's Goal • Write a Ruby interpreter in Ruby
  • 12. Today's Goal • Write a Ruby interpreter in Ruby – Impossible in one day!
  • 13. Today's Goal • Write a Ruby interpreter in Ruby – Impossible in one day! • More precisely: Write a "MinRuby" interpreter in Ruby
  • 14. Today's Goal • Write a Ruby interpreter in Ruby – Impossible in one day! • More precisely: Write a "MinRuby" interpreter in Ruby – Runs a program written in MinRuby (Target language) – Is written in Ruby (Host language)
  • 15. MinRuby • Very small subset of Ruby – Arithmetic, comparison: – Statements, variables: – Branches, loop: – Function call: – Function definition: – Array and Hash: 1+2*3 42>40 x=42; x=x+1; p(x) if x < 2 while x < 10 func(1,2) p(42) def func(x,y); …; end a=[1,2,3]; a[1]=42; p(a[0]) 3*4==5+7 h={}; h["foo"]="bar"; p(h["foo"])
  • 16. MinRuby • Very small subset of Ruby – Arithmetic, comparison: – Statements, variables: – Branches, loop: – Function call: – Function definition: – Array and Hash: • Class? Method call? Block? Not needed. 1+2*3 42>40 x=42; x=x+1; p(x) if x < 2 while x < 10 func(1,2) p(42) def func(x,y); …; end a=[1,2,3]; a[1]=42; p(a[0]) 3*4==5+7 h={}; h["foo"]="bar"; p(h["foo"])
  • 17. Your task • Write "interp.rb" • Check if it works as the same as Ruby # test1-1.rb p(1 + 1) def parse(src); …; end def evaluate(tree); …; end evaluate(parse(File.read(ARGV[0]))) $ ruby test1-1.rb 2 $ ruby interp.rb test1-1.rb 2
  • 18. Focus: Evaluator Parser Evaluator puts 3*(2+2) Program 12 Output Interpreter Use "minruby" gem A skeleton code is provided
  • 19. "minruby" gem • Provides a MinRuby parser require "minruby" p minruby_parse( "3*(2+2)" ) #=> ["*", ["lit", 3], ["+", ["lit", 2], ["lit", 2] ] ] * +3 2 2 Observe!
  • 20. A evaluator skeleton • MinRuby interpreter with many "holes" # An implementation of the evaluator def evaluate(exp, env) case exp[0] when "+" evaluate(exp[1], env) + evaluate(exp[2], env) when "-" raise(NotImplementedError) # Problem 1 … end end evaluate(minruby_parse(minruby_load()), {})
  • 21. Your task • Complete "interp.rb" and pass all test programs ("test*-*.rb") $ ruby interp.rb test1-1.rb 2 $ ruby interp.rb test1-2.rb Traceback (most recent call last): 2: from interp.rb:168:in `<main>' 1: from interp.rb:94:in `evaluate' interp.rb:23:in `evaluate': NotImplementedError Fix it!
  • 22. Problems 1..6 1. Arithmetics (test1-*.rb) 2. Statements and variables (test2-*.rb) 3. Branches and loops (test3-*.rb) 4. Function calls (test4-*.rb) 5. User-defined functions (test5-*.rb) 6. Arrays and Hashes (test6-*.rb) – You can implement and test them in turn
  • 23. Problem 7 • Self-Hosting – Write a MinRuby interpreter in MinRuby • MinRuby is limited but still powerful to implement a MinRuby interpreter! $ ruby interp.rb interp.rb test1-1.rb ary.each do |x| ... end i = 0 while ary[i] x = ary[i] ... end $ ruby interp.rb interp.rb interp.rb test1-1.rb
  • 24. Advanced Problems • Write your own MinRuby parser • Support advanced features – Blocks, class/modules, eval, callcc, … – Increment, lazy eval., type analysis, … • Write a XXX interpreter in XXX – MinSwift, Kotlin, Python, JavaScript, … • Do true self-hosting – Write a MinRuby parser in MinRuby • Write a MinRuby compiler in Ruby
  • 25. Good luck! • The files and details are available at: – https://github.com/mame/cookpad- hackarade-minruby/ • Feel free to ask me any questions – Or some experts
  • 26. Answer [PR] • A book to learn Ruby by writing Ruby interpreter in Ruby – (written in Japanese)