SlideShare a Scribd company logo
1 of 27
Download to read offline
Type Profiler:
Ambitious Type Inference
for Ruby 3
Yusuke Endoh (@mametter)
RubyKaigi Takeout 2020
1
Goals of Ruby 3’s Static Analysis
•Make Ruby programming easier
• Bug detection before execution
• Completion and document in IDE
… with no type annotation in code!
(Ruby 3 Type Challenge)
2
42 + "str"
Is this a bug?
42.ti|
Do you mean:
42.times {|i|
|
}
Ruby 3 will provide three “type” items
3
# app.rbs
def inc:
(Integer) -> Integer
① Type Signature
Format (RBS)
# app.rb
def inc(n)
n+1
end
Ruby code
② Type Inference
(ruby-type-profiler)
③ Type Check
(Steep, Sorbet, RDL, …)
Ruby 3 Development Experience
4
gem
lib.rb
lib.rbs
app
app.rb
app.rbs
42.ti|
42 + "str"
Is this a bug?
Do you mean:
42.times {|i|
|
}
② Type
Inference
• Generate an RBS prototype
• Simply check the code
③ Type
Checker
• Verify .rb and .rbs
• Serve as LSP server
You can also write RBS
manually if you want
Type-guided
linter
Dynamic
type checker
More dedicated
dev. environments
Monitor and Harness
Ruby code in run-time
Code formatter by
leveraging types
Rubymine, Tabnine, and
other development tools
may use type informationhttps://github.com/pocke/rubocop-typedhttps://github.com/ruby/rbs/blob/master/
lib/rbs/test/type_check.rb
RBS may inspire other dreams
Today
we talk about
①RBS
Agenda
➔Type Profiler: Type Inference for Ruby 3
•Demo
•How to use Type Profiler
•Future plan
5
What is Type Profiler
Abstract ("type-level") interpreter of Ruby
Generates an RBS prototype by gathering
what types a method accepts and returns
6
def foo(n)
n.to_s
end
foo(42)
Integer
(not 42)
String
(not "42")
def foo:
(Integer) -> String
Why is the name "Type Profiler"?
•Just for a historical reason
• The initial version was runtime analysis (profiling)
• Now it is a bit confusing with a normal profiler
•Invite suggestions for the name
• Should it start with "S"? (Steep, Sorbet, …)
7
Difference from traditional type system
•Traditional type systems use
intra-procedural (per-method) analysis
• Can't handle unannotated method parameter well
• … especially when there are
many classes that respond to foo
8
def f(x)
x.foo
end
What type is "x"?
class Foo
def foo; ...; end
end
class Bar
def foo; ...; end
end
class Baz
def foo; ...; end
end
...
Difference from traditional type system
•Solutions
1. Write type annotation → Avoid this
2. Infer type based on its usage
→ Too strict or too conservative
• foo must be unique
• or, structural type inference?
3. Use "inter-procedural" analysis
• Pros: More powerful analysis
• Cons: Slow and hard to control
(Challenging)
9
def f(x: Foo)
x.foo
end
def f(x)
x.foo
end
f(Foo.new)
"x" is
a Foo!
def f(x)
x.foo
end
"x" is an object that
responds to foo that
accepts no argument and
returns the same type of
a return value of this method
There are many, many topics (but omit)
Theoretical issues
• Recursion and closures[RubyKaigi 2019]
• Type-changing variable assignment
• Container types and destructive
operations[Osaka Ruby Kaigi 2019]
• Flow-sensitive analysis[EuRuKo 2019]
• Context-insensitive analysis[PPL 2019]
• Aid of escape analysis
• Cumbersome "untyped" type
• Meta-programming features
• etc, etc.
Practical issues
• Trade-off between precision and
performance [Nagoya Ruby Kaigi 2019]
• Tuple-like and sequential array
• Method-local container type
[Osaka Ruby Kaigi 2019]
• Diagnosis features[Ruby 3 Summit]
• Unreachable method analysis
• Limitation of byte code
• Super-rich Ruby features
• Too complex Ruby features
• etc, etc.
10
Agenda
•Type Profiler: Type Inference for Ruby 3
➔Demo
• Simple case
• Real-world program case
• Library case
•How to use
•Future Plan
11
Demo 1: ao.rb
•Simple case
• A 3D renderer (~300 LoC)
• Written by Hideki Miura
• Original version was
written by Syoyo Fujita
https://code.google.com/archive/p/aobench/
•Analysis time < 1 sec.
12
Demo 1: ao.rb
13
class Vec
attr_accessor x : Float
attr_accessor y : Float
attr_accessor z : Float
def initialize : (Float, Float, Float) -> Float
def vadd : (Vec) -> Vec
def vsub : (Vec) -> Vec
def vcross : (Vec) -> Vec
def vdot : (Vec) -> Float
def vlength : -> Float
def vnormalize : -> Vec
end
NEW! attr_accessor
Formerly, "def x=" and "def x"
Demo 1: ao.rb
14
class Sphere
attr_reader center : Vec
attr_reader radius : Float
def initialize : (Vec, Float) -> Float
def intersect : (Ray, Isect) -> Vec?
end
class Isect
attr_accessor t : Float
attr_accessor hit : bool
attr_accessor pl : Vec
attr_accessor n : Vec
def initialize : -> Vec
end
NEW! optional type
Formerly, "Vec | NilClass"
NEW! bool type
Formerly,
"TrueClass | FalseClass"
Demo 2: Goodcheck
• Real-world program case
• A customizable linter for Ruby (~2000 LoC)
• It has "hand-written" RBS
• Analysis time < 30 sec.
• Note: It requires many libraries which have no RBS
• activesupport, concurrent-ruby, cgi, optparse, etc.
• Type Profiler analyzed not only Goodcheck but also them
• In future, we expect they have own RBS
• Type Profiler can use RBS instead of the code itself
15
Manually reformatted to make comparison easy
Demo 2: Goodcheck
16
class Goodcheck::Trigger
attr_reader patterns :
Array[(Goodcheck::Pattern::Literal |
Goodcheck::Pattern::Regexp |
Goodcheck::Pattern::Token)?]
attr_reader globs : Array[Goodcheck::Glob?]
attr_reader passes : Array[Array[untyped]]
attr_reader fails : Array[Array[untyped]]
attr_reader negated : bool
...
end
class Goodcheck::Trigger
attr_reader patterns :
Array[pattern]
attr_reader globs: Array[Glob]
attr_reader passes: Array[String]
attr_reader fails: Array[String]
attr_reader negated: bool
...
end
type Goodcheck::pattern
= Pattern::Literal|Pattern::Regexp|Pattern::Token
RBS inferred by Type Profiler Hand-written by Soutaro
Wrong guess
Type alias
Not so bad?
Extra optionalRedundant namescope
Demo 2: Goodcheck
17
class Goodcheck::Pattern::Token
attr_reader source : untyped
attr_reader case_sensitive : true
attr_reader variables : {}
def initialize : (source: untyped,
variables: {},
case_sensitive: true) -> true
@regexp : Regexp
def regexp : -> Regexp
def test_variables : (untyped) -> bool
def self.expand :
(untyped, untyped, ?depth: Integer) -> Array[Regexp]
def self.regexp_for_type :
(name: untyped, type: :__, scanner: untyped) -> Regexp?
def self.compile_tokens :
(untyped,
{},
case_sensitive: true) -> Regexp
@@TYPES : {}
end
class Goodcheck::Pattern::Token
attr_reader source: String
attr_reader case_sensitive: bool
attr_reader variables: Hash[Symbol, VarPattern]
def initialize: (source: String,
variables: Hash[Symbol, VarPattern],
case_sensitive: bool) -> void
def regexp: -> ::Regexp
def self.expand:
(String, String, ?depth: Integer) -> Array[::Regexp]
def self.regexp_for_type:
(name: Symbol, type: Symbol, scanner: StringScanner) -> ::Regexp
def self.compile_tokens:
(String source,
Hash[Symbol, VarPattern] variables,
case_sensitive: bool) -> void
@@TYPES: Hash[Symbol, ^(String) -> ::Regexp]
end
RBS inferred by Type Profiler Hand-written by Soutaro
Too specfic
Failed to track
the elements
C lib constant
(Lack of RBS)
void is intended
I think
not so bad
Demo 3: diff-lcs
•Real-world library case
Famous algorithmic library
•Hand-written entry point
•Analysis time < 1 sec.
18
https://bestgems.org/
require_relative "lib/diff/lcs"
class T; end
Diff::LCS.diff([T.new]+[T.new], [T.new]+[T.new]) {}
Demo: diff-lcs
19
class Diff::LCS::Change
include Comparable
attr_reader action : String
attr_reader position : Integer
attr_reader element : (Array[T] | T)?
def self.valid_action? : (String) -> untyped
def initialize : (String, Integer, (Array[T] | T)?) -> nil
def inspect : -> String
...
def == : (untyped) -> bool
def <=> : (untyped) -> Integer?
def adding? : -> bool
def deleting? : -> bool
def unchanged? : -> bool
def changed? : -> bool
def finished_a? : -> bool
def finished_b? : -> bool
end
predicate methods
Agenda
•Type Profiler: Type Inference for Ruby 3
•Demo
➔ How to use Type Profiler
• Planned experience
• Specific usage
•Future plan
20
Typical usage and experience (Plan)
1. Write an entry point program
(if needed)
2. Apply Type Profiler
3. Partially write RBS for
wrong-guessed methods
4. Re-apply Type Profiler
21
lib.rb
app.rb
Type
Profiler
lib.rbs
(may include
wrong guesses)
partial RBS
for difficult methods
lib.rbs
(final)
①
②
③
④
"Partial RBS specification" has been implemented
How to use TP specifically
Will be written until the RubyKaigi Takeout!
(hopefully)
https://github.com/mame/ruby-type-profiler
22
I have written the document
Agenda
•Type Profiler: Type Inference for Ruby 3
•Demo
•How to use Type Profiler
➔Future plan
• Recent updates
• Future plan
• Conclusion
23
Recent updates
• Improve cosmetics (attr_*, optional, bool, …)
• Import Array and Hash methods from RBS
• Type variable
• Support Enumerable, Enumerator, and Struct
• Support global variables
• Improve flow-sensitive analysis
• Improve analysis performance
• Fix many, many bugs
24
Future plan
• Until Ruby 3: Make it possible for plain Ruby code
• Support partial RBS specification
• Write document and release a gem
• Continue to experiment, improve, etc, etc.
• After the release: Support Sinatra app, Rails app…
• Maybe need dedicated hard-coding for the frameworks
• Concern is almost a language extension
• ActiveRecord is super-meta feature
• Please go easy on 🙏
25
Acknowledgment
•Hideki Miura
•Matz, Akr, Ko1
•Soutaro Matsumoto
•Katsuhiro Ueno
•Eijiro Sumii
•Sorbet developers (Stripe, Shopify, etc.)
•Jeff Foster
26
Conclusion
•Type Profiler is crawling to you
• Inviting suggestions for the tool name!
• Ask me anything: @mametter (Twitter)
27

More Related Content

What's hot

Specialized Compiler for Hash Cracking
Specialized Compiler for Hash CrackingSpecialized Compiler for Hash Cracking
Specialized Compiler for Hash CrackingPositive Hack Days
 
Beginning Java for .NET developers
Beginning Java for .NET developersBeginning Java for .NET developers
Beginning Java for .NET developersAndrei Rinea
 
TypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideTypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideNascenia IT
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to Rubykim.mens
 
Louis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLouis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLou Loizides
 
iOS Programming Intro
iOS Programming IntroiOS Programming Intro
iOS Programming IntroLou Loizides
 
FregeDay: Roadmap for resolving differences between Haskell and Frege (Ingo W...
FregeDay: Roadmap for resolving differences between Haskell and Frege (Ingo W...FregeDay: Roadmap for resolving differences between Haskell and Frege (Ingo W...
FregeDay: Roadmap for resolving differences between Haskell and Frege (Ingo W...Dierk König
 
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...Andrey Upadyshev
 
C++17 std::filesystem - Overview
C++17 std::filesystem - OverviewC++17 std::filesystem - Overview
C++17 std::filesystem - OverviewBartlomiej Filipek
 
Hot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move SemanticsHot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move SemanticsAndrey Upadyshev
 
I Know Kung Fu - Juggling Java Bytecode
I Know Kung Fu - Juggling Java BytecodeI Know Kung Fu - Juggling Java Bytecode
I Know Kung Fu - Juggling Java BytecodeAlexander Shopov
 
TypeScript introduction to scalable javascript application
TypeScript introduction to scalable javascript applicationTypeScript introduction to scalable javascript application
TypeScript introduction to scalable javascript applicationAndrea Paciolla
 
Lifting The Veil - Reading Java Bytecode During Lunchtime
Lifting The Veil - Reading Java Bytecode During LunchtimeLifting The Veil - Reading Java Bytecode During Lunchtime
Lifting The Veil - Reading Java Bytecode During LunchtimeAlexander Shopov
 
Lifting The Veil - Reading Java Bytecode
Lifting The Veil - Reading Java BytecodeLifting The Veil - Reading Java Bytecode
Lifting The Veil - Reading Java BytecodeAlexander Shopov
 
JavaScript: The Language
JavaScript: The LanguageJavaScript: The Language
JavaScript: The LanguageEngage Software
 
(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_iNico Ludwig
 
TypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersTypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersRutenis Turcinas
 
Typescript: enjoying large scale browser development
Typescript: enjoying large scale browser developmentTypescript: enjoying large scale browser development
Typescript: enjoying large scale browser developmentJoost de Vries
 
Variables: names, bindings, type, scope
Variables: names, bindings, type, scopeVariables: names, bindings, type, scope
Variables: names, bindings, type, scopesuthi
 
New c sharp4_features_part_vi
New c sharp4_features_part_viNew c sharp4_features_part_vi
New c sharp4_features_part_viNico Ludwig
 

What's hot (20)

Specialized Compiler for Hash Cracking
Specialized Compiler for Hash CrackingSpecialized Compiler for Hash Cracking
Specialized Compiler for Hash Cracking
 
Beginning Java for .NET developers
Beginning Java for .NET developersBeginning Java for .NET developers
Beginning Java for .NET developers
 
TypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation GuideTypeScript: Basic Features and Compilation Guide
TypeScript: Basic Features and Compilation Guide
 
Introduction to Ruby
Introduction to RubyIntroduction to Ruby
Introduction to Ruby
 
Louis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLouis Loizides iOS Programming Introduction
Louis Loizides iOS Programming Introduction
 
iOS Programming Intro
iOS Programming IntroiOS Programming Intro
iOS Programming Intro
 
FregeDay: Roadmap for resolving differences between Haskell and Frege (Ingo W...
FregeDay: Roadmap for resolving differences between Haskell and Frege (Ingo W...FregeDay: Roadmap for resolving differences between Haskell and Frege (Ingo W...
FregeDay: Roadmap for resolving differences between Haskell and Frege (Ingo W...
 
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
[OLD VERSION, SEE DESCRIPTION FOR NEWER VERSION LINK] Hot C++: Rvalue Referen...
 
C++17 std::filesystem - Overview
C++17 std::filesystem - OverviewC++17 std::filesystem - Overview
C++17 std::filesystem - Overview
 
Hot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move SemanticsHot C++: Rvalue References And Move Semantics
Hot C++: Rvalue References And Move Semantics
 
I Know Kung Fu - Juggling Java Bytecode
I Know Kung Fu - Juggling Java BytecodeI Know Kung Fu - Juggling Java Bytecode
I Know Kung Fu - Juggling Java Bytecode
 
TypeScript introduction to scalable javascript application
TypeScript introduction to scalable javascript applicationTypeScript introduction to scalable javascript application
TypeScript introduction to scalable javascript application
 
Lifting The Veil - Reading Java Bytecode During Lunchtime
Lifting The Veil - Reading Java Bytecode During LunchtimeLifting The Veil - Reading Java Bytecode During Lunchtime
Lifting The Veil - Reading Java Bytecode During Lunchtime
 
Lifting The Veil - Reading Java Bytecode
Lifting The Veil - Reading Java BytecodeLifting The Veil - Reading Java Bytecode
Lifting The Veil - Reading Java Bytecode
 
JavaScript: The Language
JavaScript: The LanguageJavaScript: The Language
JavaScript: The Language
 
(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i
 
TypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersTypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack Developers
 
Typescript: enjoying large scale browser development
Typescript: enjoying large scale browser developmentTypescript: enjoying large scale browser development
Typescript: enjoying large scale browser development
 
Variables: names, bindings, type, scope
Variables: names, bindings, type, scopeVariables: names, bindings, type, scope
Variables: names, bindings, type, scope
 
New c sharp4_features_part_vi
New c sharp4_features_part_viNew c sharp4_features_part_vi
New c sharp4_features_part_vi
 

Similar to Type Profiler: Ambitious Type Inference for Ruby 3

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 signaturesmametter
 
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 2Henry S
 
First Class Variables as AST Annotations
 First Class Variables as AST Annotations First Class Variables as AST Annotations
First Class Variables as AST AnnotationsESUG
 
First Class Variables as AST Annotations
First Class Variables as AST AnnotationsFirst Class Variables as AST Annotations
First Class Variables as AST AnnotationsMarcus Denker
 
Enjoy Ruby Programming in IDE and TypeProf
Enjoy Ruby Programming in IDE and TypeProfEnjoy Ruby Programming in IDE and TypeProf
Enjoy Ruby Programming in IDE and TypeProfmametter
 
Advanced Reflection in Pharo
Advanced Reflection in PharoAdvanced Reflection in Pharo
Advanced Reflection in PharoPharo
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerAndrey Karpov
 
Dmytro Kochergin Angular 2 and New Java Script Technologies
Dmytro Kochergin Angular 2 and New Java Script TechnologiesDmytro Kochergin Angular 2 and New Java Script Technologies
Dmytro Kochergin Angular 2 and New Java Script TechnologiesLogeekNightUkraine
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9sagaroceanic11
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9sagaroceanic11
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?Mario Camou Riveroll
 
Compilers Are Databases
Compilers Are DatabasesCompilers Are Databases
Compilers Are DatabasesMartin Odersky
 
error_highlight: User-friendly Error Diagnostics
error_highlight: User-friendly Error Diagnosticserror_highlight: User-friendly Error Diagnostics
error_highlight: User-friendly Error Diagnosticsmametter
 
Raleigh Code Camp 2103 - .Net Metaprogramming Essentials
Raleigh Code Camp 2103 - .Net Metaprogramming EssentialsRaleigh Code Camp 2103 - .Net Metaprogramming Essentials
Raleigh Code Camp 2103 - .Net Metaprogramming EssentialsSean McCarthy
 

Similar to Type Profiler: Ambitious Type Inference for Ruby 3 (20)

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
 
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
 
First Class Variables as AST Annotations
 First Class Variables as AST Annotations First Class Variables as AST Annotations
First Class Variables as AST Annotations
 
First Class Variables as AST Annotations
First Class Variables as AST AnnotationsFirst Class Variables as AST Annotations
First Class Variables as AST Annotations
 
Meta Object Protocols
Meta Object ProtocolsMeta Object Protocols
Meta Object Protocols
 
Enjoy Ruby Programming in IDE and TypeProf
Enjoy Ruby Programming in IDE and TypeProfEnjoy Ruby Programming in IDE and TypeProf
Enjoy Ruby Programming in IDE and TypeProf
 
Advanced Reflection in Pharo
Advanced Reflection in PharoAdvanced Reflection in Pharo
Advanced Reflection in Pharo
 
The operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzerThe operation principles of PVS-Studio static code analyzer
The operation principles of PVS-Studio static code analyzer
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
C# for beginners
C# for beginnersC# for beginners
C# for beginners
 
Dmytro Kochergin Angular 2 and New Java Script Technologies
Dmytro Kochergin Angular 2 and New Java Script TechnologiesDmytro Kochergin Angular 2 and New Java Script Technologies
Dmytro Kochergin Angular 2 and New Java Script Technologies
 
Angular2
Angular2Angular2
Angular2
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
Compilers Are Databases
Compilers Are DatabasesCompilers Are Databases
Compilers Are Databases
 
error_highlight: User-friendly Error Diagnostics
error_highlight: User-friendly Error Diagnosticserror_highlight: User-friendly Error Diagnostics
error_highlight: User-friendly Error Diagnostics
 
Raleigh Code Camp 2103 - .Net Metaprogramming Essentials
Raleigh Code Camp 2103 - .Net Metaprogramming EssentialsRaleigh Code Camp 2103 - .Net Metaprogramming Essentials
Raleigh Code Camp 2103 - .Net Metaprogramming Essentials
 

More from mametter

TRICK 2022 Results
TRICK 2022 ResultsTRICK 2022 Results
TRICK 2022 Resultsmametter
 
クックパッド春の超絶技巧パンまつり 超絶技巧プログラミング編 資料
クックパッド春の超絶技巧パンまつり 超絶技巧プログラミング編 資料クックパッド春の超絶技巧パンまつり 超絶技巧プログラミング編 資料
クックパッド春の超絶技巧パンまつり 超絶技巧プログラミング編 資料mametter
 
Ruby 3の型解析に向けた計画
Ruby 3の型解析に向けた計画Ruby 3の型解析に向けた計画
Ruby 3の型解析に向けた計画mametter
 
emruby: ブラウザで動くRuby
emruby: ブラウザで動くRubyemruby: ブラウザで動くRuby
emruby: ブラウザで動くRubymametter
 
型プロファイラ:抽象解釈に基づくRuby 3の静的解析
型プロファイラ:抽象解釈に基づくRuby 3の静的解析型プロファイラ:抽象解釈に基づくRuby 3の静的解析
型プロファイラ:抽象解釈に基づくRuby 3の静的解析mametter
 
Ruby 3の型推論やってます
Ruby 3の型推論やってますRuby 3の型推論やってます
Ruby 3の型推論やってますmametter
 
マニアックなRuby 2.7新機能紹介
マニアックなRuby 2.7新機能紹介マニアックなRuby 2.7新機能紹介
マニアックなRuby 2.7新機能紹介mametter
 
Ruby 3 の型解析に向けた計画
Ruby 3 の型解析に向けた計画Ruby 3 の型解析に向けた計画
Ruby 3 の型解析に向けた計画mametter
 
本番環境で使える実行コード記録機能
本番環境で使える実行コード記録機能本番環境で使える実行コード記録機能
本番環境で使える実行コード記録機能mametter
 
Transcendental Programming in Ruby
Transcendental Programming in RubyTranscendental Programming in Ruby
Transcendental Programming in Rubymametter
 
Cookpad Hackarade #04: Create Your Own Interpreter
Cookpad Hackarade #04: Create Your Own InterpreterCookpad Hackarade #04: Create Your Own Interpreter
Cookpad Hackarade #04: Create Your Own Interpretermametter
 
Ruby 3のキーワード引数について考える
Ruby 3のキーワード引数について考えるRuby 3のキーワード引数について考える
Ruby 3のキーワード引数について考えるmametter
 
TRICK 2018 results
TRICK 2018 resultsTRICK 2018 results
TRICK 2018 resultsmametter
 
Esoteric, Obfuscated, Artistic Programming in Ruby
Esoteric, Obfuscated, Artistic Programming in RubyEsoteric, Obfuscated, Artistic Programming in Ruby
Esoteric, Obfuscated, Artistic Programming in Rubymametter
 
Cookpad Spring 1day internship 2018 超絶技巧プログラミングコース資料
Cookpad Spring 1day internship 2018 超絶技巧プログラミングコース資料Cookpad Spring 1day internship 2018 超絶技巧プログラミングコース資料
Cookpad Spring 1day internship 2018 超絶技巧プログラミングコース資料mametter
 
Esoteric, Obfuscated, Artistic Programming in Ruby
Esoteric, Obfuscated, Artistic Programming in RubyEsoteric, Obfuscated, Artistic Programming in Ruby
Esoteric, Obfuscated, Artistic Programming in Rubymametter
 
An introduction and future of Ruby coverage library
An introduction and future of Ruby coverage libraryAn introduction and future of Ruby coverage library
An introduction and future of Ruby coverage librarymametter
 
Ruby でつくる型付き Ruby
Ruby でつくる型付き RubyRuby でつくる型付き Ruby
Ruby でつくる型付き Rubymametter
 
Ruby で高速なプログラムを書く
Ruby で高速なプログラムを書くRuby で高速なプログラムを書く
Ruby で高速なプログラムを書くmametter
 
Optcarrot: A Pure-Ruby NES Emulator
Optcarrot: A Pure-Ruby NES EmulatorOptcarrot: A Pure-Ruby NES Emulator
Optcarrot: A Pure-Ruby NES Emulatormametter
 

More from mametter (20)

TRICK 2022 Results
TRICK 2022 ResultsTRICK 2022 Results
TRICK 2022 Results
 
クックパッド春の超絶技巧パンまつり 超絶技巧プログラミング編 資料
クックパッド春の超絶技巧パンまつり 超絶技巧プログラミング編 資料クックパッド春の超絶技巧パンまつり 超絶技巧プログラミング編 資料
クックパッド春の超絶技巧パンまつり 超絶技巧プログラミング編 資料
 
Ruby 3の型解析に向けた計画
Ruby 3の型解析に向けた計画Ruby 3の型解析に向けた計画
Ruby 3の型解析に向けた計画
 
emruby: ブラウザで動くRuby
emruby: ブラウザで動くRubyemruby: ブラウザで動くRuby
emruby: ブラウザで動くRuby
 
型プロファイラ:抽象解釈に基づく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新機能紹介
 
Ruby 3 の型解析に向けた計画
Ruby 3 の型解析に向けた計画Ruby 3 の型解析に向けた計画
Ruby 3 の型解析に向けた計画
 
本番環境で使える実行コード記録機能
本番環境で使える実行コード記録機能本番環境で使える実行コード記録機能
本番環境で使える実行コード記録機能
 
Transcendental Programming in Ruby
Transcendental Programming in RubyTranscendental Programming in Ruby
Transcendental Programming in Ruby
 
Cookpad Hackarade #04: Create Your Own Interpreter
Cookpad Hackarade #04: Create Your Own InterpreterCookpad Hackarade #04: Create Your Own Interpreter
Cookpad Hackarade #04: Create Your Own Interpreter
 
Ruby 3のキーワード引数について考える
Ruby 3のキーワード引数について考えるRuby 3のキーワード引数について考える
Ruby 3のキーワード引数について考える
 
TRICK 2018 results
TRICK 2018 resultsTRICK 2018 results
TRICK 2018 results
 
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
 
An introduction and future of Ruby coverage library
An introduction and future of Ruby coverage libraryAn introduction and future of Ruby coverage library
An introduction and future of Ruby coverage library
 
Ruby でつくる型付き Ruby
Ruby でつくる型付き RubyRuby でつくる型付き Ruby
Ruby でつくる型付き Ruby
 
Ruby で高速なプログラムを書く
Ruby で高速なプログラムを書くRuby で高速なプログラムを書く
Ruby で高速なプログラムを書く
 
Optcarrot: A Pure-Ruby NES Emulator
Optcarrot: A Pure-Ruby NES EmulatorOptcarrot: A Pure-Ruby NES Emulator
Optcarrot: A Pure-Ruby NES Emulator
 

Recently uploaded

Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observabilityitnewsafrica
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...itnewsafrica
 

Recently uploaded (20)

Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security ObservabilityGlenn Lazarus- Why Your Observability Strategy Needs Security Observability
Glenn Lazarus- Why Your Observability Strategy Needs Security Observability
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...Zeshan Sattar- Assessing the skill requirements and industry expectations for...
Zeshan Sattar- Assessing the skill requirements and industry expectations for...
 

Type Profiler: Ambitious Type Inference for Ruby 3

  • 1. Type Profiler: Ambitious Type Inference for Ruby 3 Yusuke Endoh (@mametter) RubyKaigi Takeout 2020 1
  • 2. Goals of Ruby 3’s Static Analysis •Make Ruby programming easier • Bug detection before execution • Completion and document in IDE … with no type annotation in code! (Ruby 3 Type Challenge) 2 42 + "str" Is this a bug? 42.ti| Do you mean: 42.times {|i| | }
  • 3. Ruby 3 will provide three “type” items 3 # app.rbs def inc: (Integer) -> Integer ① Type Signature Format (RBS) # app.rb def inc(n) n+1 end Ruby code ② Type Inference (ruby-type-profiler) ③ Type Check (Steep, Sorbet, RDL, …)
  • 4. Ruby 3 Development Experience 4 gem lib.rb lib.rbs app app.rb app.rbs 42.ti| 42 + "str" Is this a bug? Do you mean: 42.times {|i| | } ② Type Inference • Generate an RBS prototype • Simply check the code ③ Type Checker • Verify .rb and .rbs • Serve as LSP server You can also write RBS manually if you want Type-guided linter Dynamic type checker More dedicated dev. environments Monitor and Harness Ruby code in run-time Code formatter by leveraging types Rubymine, Tabnine, and other development tools may use type informationhttps://github.com/pocke/rubocop-typedhttps://github.com/ruby/rbs/blob/master/ lib/rbs/test/type_check.rb RBS may inspire other dreams Today we talk about ①RBS
  • 5. Agenda ➔Type Profiler: Type Inference for Ruby 3 •Demo •How to use Type Profiler •Future plan 5
  • 6. What is Type Profiler Abstract ("type-level") interpreter of Ruby Generates an RBS prototype by gathering what types a method accepts and returns 6 def foo(n) n.to_s end foo(42) Integer (not 42) String (not "42") def foo: (Integer) -> String
  • 7. Why is the name "Type Profiler"? •Just for a historical reason • The initial version was runtime analysis (profiling) • Now it is a bit confusing with a normal profiler •Invite suggestions for the name • Should it start with "S"? (Steep, Sorbet, …) 7
  • 8. Difference from traditional type system •Traditional type systems use intra-procedural (per-method) analysis • Can't handle unannotated method parameter well • … especially when there are many classes that respond to foo 8 def f(x) x.foo end What type is "x"? class Foo def foo; ...; end end class Bar def foo; ...; end end class Baz def foo; ...; end end ...
  • 9. Difference from traditional type system •Solutions 1. Write type annotation → Avoid this 2. Infer type based on its usage → Too strict or too conservative • foo must be unique • or, structural type inference? 3. Use "inter-procedural" analysis • Pros: More powerful analysis • Cons: Slow and hard to control (Challenging) 9 def f(x: Foo) x.foo end def f(x) x.foo end f(Foo.new) "x" is a Foo! def f(x) x.foo end "x" is an object that responds to foo that accepts no argument and returns the same type of a return value of this method
  • 10. There are many, many topics (but omit) Theoretical issues • Recursion and closures[RubyKaigi 2019] • Type-changing variable assignment • Container types and destructive operations[Osaka Ruby Kaigi 2019] • Flow-sensitive analysis[EuRuKo 2019] • Context-insensitive analysis[PPL 2019] • Aid of escape analysis • Cumbersome "untyped" type • Meta-programming features • etc, etc. Practical issues • Trade-off between precision and performance [Nagoya Ruby Kaigi 2019] • Tuple-like and sequential array • Method-local container type [Osaka Ruby Kaigi 2019] • Diagnosis features[Ruby 3 Summit] • Unreachable method analysis • Limitation of byte code • Super-rich Ruby features • Too complex Ruby features • etc, etc. 10
  • 11. Agenda •Type Profiler: Type Inference for Ruby 3 ➔Demo • Simple case • Real-world program case • Library case •How to use •Future Plan 11
  • 12. Demo 1: ao.rb •Simple case • A 3D renderer (~300 LoC) • Written by Hideki Miura • Original version was written by Syoyo Fujita https://code.google.com/archive/p/aobench/ •Analysis time < 1 sec. 12
  • 13. Demo 1: ao.rb 13 class Vec attr_accessor x : Float attr_accessor y : Float attr_accessor z : Float def initialize : (Float, Float, Float) -> Float def vadd : (Vec) -> Vec def vsub : (Vec) -> Vec def vcross : (Vec) -> Vec def vdot : (Vec) -> Float def vlength : -> Float def vnormalize : -> Vec end NEW! attr_accessor Formerly, "def x=" and "def x"
  • 14. Demo 1: ao.rb 14 class Sphere attr_reader center : Vec attr_reader radius : Float def initialize : (Vec, Float) -> Float def intersect : (Ray, Isect) -> Vec? end class Isect attr_accessor t : Float attr_accessor hit : bool attr_accessor pl : Vec attr_accessor n : Vec def initialize : -> Vec end NEW! optional type Formerly, "Vec | NilClass" NEW! bool type Formerly, "TrueClass | FalseClass"
  • 15. Demo 2: Goodcheck • Real-world program case • A customizable linter for Ruby (~2000 LoC) • It has "hand-written" RBS • Analysis time < 30 sec. • Note: It requires many libraries which have no RBS • activesupport, concurrent-ruby, cgi, optparse, etc. • Type Profiler analyzed not only Goodcheck but also them • In future, we expect they have own RBS • Type Profiler can use RBS instead of the code itself 15
  • 16. Manually reformatted to make comparison easy Demo 2: Goodcheck 16 class Goodcheck::Trigger attr_reader patterns : Array[(Goodcheck::Pattern::Literal | Goodcheck::Pattern::Regexp | Goodcheck::Pattern::Token)?] attr_reader globs : Array[Goodcheck::Glob?] attr_reader passes : Array[Array[untyped]] attr_reader fails : Array[Array[untyped]] attr_reader negated : bool ... end class Goodcheck::Trigger attr_reader patterns : Array[pattern] attr_reader globs: Array[Glob] attr_reader passes: Array[String] attr_reader fails: Array[String] attr_reader negated: bool ... end type Goodcheck::pattern = Pattern::Literal|Pattern::Regexp|Pattern::Token RBS inferred by Type Profiler Hand-written by Soutaro Wrong guess Type alias Not so bad? Extra optionalRedundant namescope
  • 17. Demo 2: Goodcheck 17 class Goodcheck::Pattern::Token attr_reader source : untyped attr_reader case_sensitive : true attr_reader variables : {} def initialize : (source: untyped, variables: {}, case_sensitive: true) -> true @regexp : Regexp def regexp : -> Regexp def test_variables : (untyped) -> bool def self.expand : (untyped, untyped, ?depth: Integer) -> Array[Regexp] def self.regexp_for_type : (name: untyped, type: :__, scanner: untyped) -> Regexp? def self.compile_tokens : (untyped, {}, case_sensitive: true) -> Regexp @@TYPES : {} end class Goodcheck::Pattern::Token attr_reader source: String attr_reader case_sensitive: bool attr_reader variables: Hash[Symbol, VarPattern] def initialize: (source: String, variables: Hash[Symbol, VarPattern], case_sensitive: bool) -> void def regexp: -> ::Regexp def self.expand: (String, String, ?depth: Integer) -> Array[::Regexp] def self.regexp_for_type: (name: Symbol, type: Symbol, scanner: StringScanner) -> ::Regexp def self.compile_tokens: (String source, Hash[Symbol, VarPattern] variables, case_sensitive: bool) -> void @@TYPES: Hash[Symbol, ^(String) -> ::Regexp] end RBS inferred by Type Profiler Hand-written by Soutaro Too specfic Failed to track the elements C lib constant (Lack of RBS) void is intended I think not so bad
  • 18. Demo 3: diff-lcs •Real-world library case Famous algorithmic library •Hand-written entry point •Analysis time < 1 sec. 18 https://bestgems.org/ require_relative "lib/diff/lcs" class T; end Diff::LCS.diff([T.new]+[T.new], [T.new]+[T.new]) {}
  • 19. Demo: diff-lcs 19 class Diff::LCS::Change include Comparable attr_reader action : String attr_reader position : Integer attr_reader element : (Array[T] | T)? def self.valid_action? : (String) -> untyped def initialize : (String, Integer, (Array[T] | T)?) -> nil def inspect : -> String ... def == : (untyped) -> bool def <=> : (untyped) -> Integer? def adding? : -> bool def deleting? : -> bool def unchanged? : -> bool def changed? : -> bool def finished_a? : -> bool def finished_b? : -> bool end predicate methods
  • 20. Agenda •Type Profiler: Type Inference for Ruby 3 •Demo ➔ How to use Type Profiler • Planned experience • Specific usage •Future plan 20
  • 21. Typical usage and experience (Plan) 1. Write an entry point program (if needed) 2. Apply Type Profiler 3. Partially write RBS for wrong-guessed methods 4. Re-apply Type Profiler 21 lib.rb app.rb Type Profiler lib.rbs (may include wrong guesses) partial RBS for difficult methods lib.rbs (final) ① ② ③ ④ "Partial RBS specification" has been implemented
  • 22. How to use TP specifically Will be written until the RubyKaigi Takeout! (hopefully) https://github.com/mame/ruby-type-profiler 22 I have written the document
  • 23. Agenda •Type Profiler: Type Inference for Ruby 3 •Demo •How to use Type Profiler ➔Future plan • Recent updates • Future plan • Conclusion 23
  • 24. Recent updates • Improve cosmetics (attr_*, optional, bool, …) • Import Array and Hash methods from RBS • Type variable • Support Enumerable, Enumerator, and Struct • Support global variables • Improve flow-sensitive analysis • Improve analysis performance • Fix many, many bugs 24
  • 25. Future plan • Until Ruby 3: Make it possible for plain Ruby code • Support partial RBS specification • Write document and release a gem • Continue to experiment, improve, etc, etc. • After the release: Support Sinatra app, Rails app… • Maybe need dedicated hard-coding for the frameworks • Concern is almost a language extension • ActiveRecord is super-meta feature • Please go easy on 🙏 25
  • 26. Acknowledgment •Hideki Miura •Matz, Akr, Ko1 •Soutaro Matsumoto •Katsuhiro Ueno •Eijiro Sumii •Sorbet developers (Stripe, Shopify, etc.) •Jeff Foster 26
  • 27. Conclusion •Type Profiler is crawling to you • Inviting suggestions for the tool name! • Ask me anything: @mametter (Twitter) 27