はじめに
この記事はHamada.rbでruby-type-profilerを試した時のアレコレをまとめたものです。
使用している環境としては WSL2(Ubuntu 18.04) で使用したRubyはruby 3.0.0dev (2020-09-07T04:29:42Z master 17a27060a7) [x86_64-linux]
です。
ruby-type-profiler のお試し
ほとんどREADMEにある内容をなぞるだけ
まずはruby-type-profilerをcloneする
git clone https://github.com/mame/ruby-type-profiler.git
次に、git submoduleとしてついてきているrbs
を初期化し、update
git submodule init git submodule update
updateが終わったら、bundle install
を実行
bundle install
あとはtype.rb
とかで適当なソースコードを作成して、そこへ以下のコードを貼り付ける
def foo(x) if x > 10 x.to_s else nil end end foo(42)
最後に、ruby exe/type-profiler type.rb
のように型を確認したいファイルを指定して実行します。
すると以下のように型情報などが出力されます。
sh@MyComputer:~/rubydev/ruby-type-profiler$ ruby exe/type-profiler type.rb # Classes class Object def foo : (Integer) -> String? end
こんな感じでソースコードから型情報などを取得できます!やったね!
なお、ruby 2.7.1p83 (2020-03-31 revision a0c7c23c9c) [x86_64-linux]
だと以下のような感じでエラーが出る
sh@MyComputer:~/rubydev/ruby-type-profiler$ ruby exe/type-profiler type.rb Traceback (most recent call last): 6: from exe/type-profiler:3:in `<main>' 5: from exe/type-profiler:3:in `require_relative' 4: from /home/sh/rubydev/ruby-type-profiler/lib/type-profiler.rb:8:in `<top (required)>' 3: from /home/sh/rubydev/ruby-type-profiler/lib/type-profiler.rb:8:in `require_relative' 2: from /home/sh/rubydev/ruby-type-profiler/lib/type-profiler/import.rb:1:in `<top (required)>' 1: from /home/sh/.rbenv/versions/2.7.1/lib/ruby/2.7.0/rubygems/core_ext/kernel_require.rb:92:in `require' /home/sh/.rbenv/versions/2.7.1/lib/ruby/2.7.0/rubygems/core_ext/kernel_require.rb:92:in `require': cannot load such file -- rbs (LoadError) sh@MyComputer:~/rubydev/ruby-type-profiler$ ruby -v ruby 2.7.1p83 (2020-03-31 revision a0c7c23c9c) [x86_64-linux]
なので一旦rbs
ディレクトリに入ってrake install
でgemとしてインストールする
sh@MyComputer:~/rubydev/ruby-type-profiler$ cd rbs sh@MyComputer:~/rubydev/ruby-type-profiler/rbs$ rake install racc -v -o lib/rbs/parser.rb lib/rbs/parser.y 2 reduce/reduce conflicts rbs 0.10.0 built to pkg/rbs-0.10.0.gem. rbs (0.10.0) installed. sh@MyComputer:~/rubydev/ruby-type-profiler/rbs$ cd .. sh@MyComputer:~/rubydev/ruby-type-profiler$ ruby exe/type-profiler type.rb # Classes class Object def foo : (Integer) -> String? end
この辺はちょっと調べてみてチケット作ろう