Skip to content

Instantly share code, notes, and snippets.

@tompng
Forked from gongo/gongo.rb
Last active January 28, 2022 01:15
Show Gist options
  • Save tompng/cdacf00f21c0d756e4bc76a8c58ac1e5 to your computer and use it in GitHub Desktop.
Save tompng/cdacf00f21c0d756e4bc76a8c58ac1e5 to your computer and use it in GitHub Desktop.
それぞれのメソッドで「戻り値になるのはこれとこれ」っていうリストを作りたい
# https://gist.github.com/gongo/c404167ae49165acd4df63c27ae1a54c
# iseqの中から [:putobject, object], :RUBY_EVENT_RETURN や [:putstring, "string"], ?, :RUBY_EVENT_RETURN を雑に探す作戦
def nanika_no_method(code)
flat_iseq = RubyVM::InstructionSequence.new(code).to_a.flatten
flat_iseq.select.with_index do |s, idx|
flat_iseq[idx + 1, 2].include?(:RUBY_EVENT_RETURN) && %i[putobject putstring].include?(flat_iseq[idx - 1])
end.uniq
end
# こういうことをしてくれる nanika_no_method が欲しい
# Ripper とかそこらへん使えばいけるのだろうか
nanika_no_method(<<EOS)
def gongo1
'a'
end
EOS
# => ['a']
nanika_no_method(<<EOS)
def gongo2(num)
num.odd? ? 'b' : 'c'
end
EOS
# => ['b', 'c']
nanika_no_method(<<EOS)
def gongo3(num1, num2)
return 'd' if num1.odd?
num2.odd? ? 'e' : 'f'
end
EOS
# => ['d', 'e', 'f']
nanika_no_method(<<EOS)
def gongo4(num1, num2)
num1 + num2
end
EOS
# => こういうのは対応しなくてOK
@tompng
Copy link
Author

tompng commented Jan 28, 2022

typeprofだと型情報が正確に出てすごい

def nanika_no_code(code)
  require 'typeprof'
  require 'stringio'
  output = StringIO.new
  config = TypeProf::ConfigData.new(rb_files: [['a.rb', code]], rbs_files: [], output:)
  TypeProf.analyze config
  output.rewind
  output.read
end

nanika_no_code(<<EOS)
  def gongo4(num1, num2)
    num1 + num2
  end
  gongo4 3, 4
EOS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment