Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
199 changes: 138 additions & 61 deletions lib/rbs/test/hook.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,69 @@ module Hook
# Calls `Kernel#is_a?` without dynamic dispatch, so that the check doesn't call a hooked method or a method overridden by the receiver.
IS_A = ::Kernel.instance_method(:is_a?)

# Methods the hooks call without dynamic dispatch through `bind_call`.
#
# Any class can be a test target when the program reopens it, including core classes like `Integer`, `Hash`, or `Thread`.
# Calling the methods through these `UnboundMethod`s reaches the original definitions even if the methods are hooked.
THREAD_CURRENT = ::Thread.singleton_class.instance_method(:current)
THREAD_AREF = ::Thread.instance_method(:[])
THREAD_ASET = ::Thread.instance_method(:[]=)
HASH_AREF = ::Hash.instance_method(:[])
SEND = ::BasicObject.instance_method(:__send__)
EQUAL = ::BasicObject.instance_method(:equal?)
INSTANCE_EXEC = ::BasicObject.instance_method(:instance_exec)
PROC_CALL = ::Proc.instance_method(:call)

# Methods that `rbs test` refuses to hook, keyed by the class that defines them.
#
# The hooks call them before entering the guard (see `.guard`), so hooking them causes infinite recursion.
# Every other method the hooks call is called inside the guard, or through `bind_call` above.
# (The singleton methods of `RBS::Test::Hook` itself are never hooked, because it has no RBS declaration.)
UNHOOKABLE_INSTANCE_METHODS = {
::UnboundMethod => [:bind_call]
} #: Hash[Module, Array[Symbol]]

# The fiber-local variable name that is truthy while `rbs test` runs its own code in hooks.
GUARD_KEY = :__rbs_test_hook_guard__

# Runs the given block as `rbs test`'s own code.
#
# A hooked method called inside the block calls the original method without type checking.
# The hooks do their bookkeeping and type checking inside the guard, because they call methods that can be hooked,
# like `Hash#[]` or `Integer#<` (through `Logger`), and checking them again recurses infinitely.
# The hooks call the original method outside of the guard, so that the hooked methods called from the original are type checked.
def self.guard
thread = THREAD_CURRENT.bind_call(::Thread)
guarded = THREAD_AREF.bind_call(thread, GUARD_KEY)
THREAD_ASET.bind_call(thread, GUARD_KEY, true)
begin
yield
ensure
THREAD_ASET.bind_call(thread, GUARD_KEY, guarded)
end
end

def self.guarded?
THREAD_AREF.bind_call(THREAD_CURRENT.bind_call(::Thread), GUARD_KEY)
end

def self.unhookable_instance_method?(klass, name)
names = UNHOOKABLE_INSTANCE_METHODS[klass] or return false
names.include?(name)
end

# Calls the original method of the hook identified by `random`, without dynamic dispatch.
def self.call_original(receiver, random, without_name, args, block)
owner = HASH_AREF.bind_call(ORIGINAL_OWNERS, random)
bindable = owner ? IS_A.bind_call(receiver, owner) : true

if bindable
HASH_AREF.bind_call(ORIGINAL_METHODS, random).bind_call(receiver, *args, &block)
else
SEND.bind_call(receiver, without_name, *args, &block)
end
end

def self.alias_names(target, random)
suffix = "#{RBS::Test.suffix}_#{random}"

Expand Down Expand Up @@ -100,8 +163,8 @@ def self.setup_alias_method_chain(klass, target, random:)

def self.hook_method_source(prefix, method_name, key, random:, params:)
with_name, without_name = alias_names(method_name, random)
original_method = "::RBS::Test::Hook::ORIGINAL_METHODS[#{random.inspect}]"
original_owner = "::RBS::Test::Hook::ORIGINAL_OWNERS[#{random.inspect}]"
original_method_table = "::RBS::Test::Hook::ORIGINAL_METHODS"
original_owner_table = "::RBS::Test::Hook::ORIGINAL_OWNERS"
full_method_name = "#{prefix}#{method_name}"

param_source = params.take_while {|param| param[0] == :req }
Expand All @@ -116,13 +179,26 @@ def self.hook_method_source(prefix, method_name, key, random:, params:)
[__LINE__ + 1, <<RUBY]
def #{with_name}(#{param_source.join(", ")}, &#{block_param})
args = [#{param_source.join(", ")}]
::RBS.logger.debug { "#{full_method_name} with arguments: [" + args.map(&:inspect).join(", ") + "]" }
hook__#{random} = ::RBS::Test::Hook

if hook__#{random}.guarded?
# Called from `rbs test`'s own code, like the type checker or another hook
return hook__#{random}.call_original(self, #{random.inspect}, #{without_name.to_sym.inspect}, args, #{block_param})
end

return_from_call = false
block_calls = nil
wrapped_block = nil
original__#{random} = nil
bindable__#{random} = nil

hook__#{random}.guard do
::RBS.logger.debug { "#{full_method_name} with arguments: [" + args.map(&:inspect).join(", ") + "]" }

begin
return_from_call = false
block_calls = []

owner__#{random} = #{original_owner}
original__#{random} = ::RBS::Test::Hook::HASH_AREF.bind_call(#{original_method_table}, #{random.inspect})
owner__#{random} = ::RBS::Test::Hook::HASH_AREF.bind_call(#{original_owner_table}, #{random.inspect})
bindable__#{random} = owner__#{random} ? ::RBS::Test::Hook::IS_A.bind_call(self, owner__#{random}) : true

if #{block_param}
Expand All @@ -135,90 +211,91 @@ def #{with_name}(#{param_source.join(", ")}, &#{block_param})
return_from_block = false

begin
block_result = if self.equal?(new_object)
block_result = if ::RBS::Test::Hook::EQUAL.bind_call(self, new_object)
if block_receives_block
#{block_param}.call(*block_args, &block2)
::RBS::Test::Hook::PROC_CALL.bind_call(#{block_param}, *block_args, &block2)
else
yield(*block_args)
end
else
# Detected that `self` inside `proc` is not equal to the `self` outside block (which is saved to `new_object`).
# This means that the block is called with `instance_exec` or `instance_eval`.
self.instance_exec(*block_args, &#{block_param})
::RBS::Test::Hook::INSTANCE_EXEC.bind_call(self, *block_args, &#{block_param})
end

return_from_block = true
ensure
exn = $!

case
when return_from_block
# Returned from yield
block_calls << ::RBS::Test::ArgumentsReturn.return(
arguments: block_args,
value: block_result
)
when exn
# Exception
block_calls << ::RBS::Test::ArgumentsReturn.exception(
arguments: block_args,
exception: exn
)
else
# break?
block_calls << ::RBS::Test::ArgumentsReturn.break(
arguments: block_args
)
hook__#{random}.guard do
case
when return_from_block
# Returned from yield
block_calls << ::RBS::Test::ArgumentsReturn.return(
arguments: block_args,
value: block_result
)
when exn
# Exception
block_calls << ::RBS::Test::ArgumentsReturn.exception(
arguments: block_args,
exception: exn
)
else
# break?
block_calls << ::RBS::Test::ArgumentsReturn.break(
arguments: block_args
)
end
end
end

block_result
end.ruby2_keywords
end
end
end

result = if bindable__#{random}
#{original_method}.bind_call(self, *args, &wrapped_block)
else
__send__(#{without_name.to_sym.inspect}, *args, &wrapped_block)
end
begin
# Calls the original method outside of the guard, so that the hooked methods called from it are type checked
result = if bindable__#{random}
original__#{random}.bind_call(self, *args, &wrapped_block)
else
result = if bindable__#{random}
#{original_method}.bind_call(self, *args)
else
__send__(#{without_name.to_sym.inspect}, *args)
end
::RBS::Test::Hook::SEND.bind_call(self, #{without_name.to_sym.inspect}, *args, &wrapped_block)
end
return_from_call = true
result
ensure
exn = $!

case
when return_from_call
::RBS.logger.debug { "#{full_method_name} return with value: " + result.inspect }
method_call = ::RBS::Test::ArgumentsReturn.return(
arguments: args,
value: result
)
when exn
::RBS.logger.debug { "#{full_method_name} exit with exception: " + exn.inspect }
method_call = ::RBS::Test::ArgumentsReturn.exception(
arguments: args,
exception: exn
)
else
::RBS.logger.debug { "#{full_method_name} exit with jump" }
method_call = ::RBS::Test::ArgumentsReturn.break(arguments: args)
end
hook__#{random}.guard do
case
when return_from_call
::RBS.logger.debug { "#{full_method_name} return with value: " + result.inspect }
method_call = ::RBS::Test::ArgumentsReturn.return(
arguments: args,
value: result
)
when exn
::RBS.logger.debug { "#{full_method_name} exit with exception: " + exn.inspect }
method_call = ::RBS::Test::ArgumentsReturn.exception(
arguments: args,
exception: exn
)
else
::RBS.logger.debug { "#{full_method_name} exit with jump" }
method_call = ::RBS::Test::ArgumentsReturn.break(arguments: args)
end

trace = ::RBS::Test::CallTrace.new(
method_name: #{method_name.inspect},
method_call: method_call,
block_calls: block_calls,
block_given: !#{block_param}.nil?,
)
trace = ::RBS::Test::CallTrace.new(
method_name: #{method_name.inspect},
method_call: method_call,
block_calls: block_calls,
block_given: !#{block_param}.nil?,
)

::RBS::Test::Observer.notify(#{key.inspect}, self, trace)
::RBS::Test::Observer.notify(#{key.inspect}, self, trace)
end
end

result
Expand Down
15 changes: 9 additions & 6 deletions lib/rbs/test/setup.rb
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,16 @@ def to_absolute_typename(type_name)
module_name = Module.instance_method(:name)

TracePoint.trace :end do |tp|
class_name = module_name.bind(tp.self).call&.yield_self {|name| to_absolute_typename name }
# Methods of test targets, which may be core classes like `String` or `Hash`, called here are not type checked
RBS::Test::Hook.guard do
class_name = module_name.bind(tp.self).call&.yield_self {|name| to_absolute_typename name }

if class_name
if filter.any? {|f| match(to_absolute_typename(f).to_s, class_name.to_s) } && skips.none? {|f| match(f, class_name.to_s) }
if env.module_name?(class_name)
logger.info "Setting up hooks for #{class_name}"
tester.install!(tp.self, sample_size: sample_size, unchecked_classes: unchecked_classes)
if class_name
if filter.any? {|f| match(to_absolute_typename(f).to_s, class_name.to_s) } && skips.none? {|f| match(f, class_name.to_s) }
if env.module_name?(class_name)
logger.info "Setting up hooks for #{class_name}"
tester.install!(tp.self, sample_size: sample_size, unchecked_classes: unchecked_classes)
end
end
end
end
Expand Down
4 changes: 3 additions & 1 deletion lib/rbs/test/tester.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,9 @@ def install!(klass, sample_size:, unchecked_classes:)
RBS.logger.info { "Skipping ##{name} because of `#{reason}`..." }
end
else
if !set.include?(name) && (
if Hook.unhookable_instance_method?(klass, name)
RBS.logger.info { "Skipping ##{name} because `rbs test` calls it to run hooks..." }
elsif !set.include?(name) && (
name == :initialize ||
klass.instance_methods(false).include?(name) ||
klass.private_instance_methods(false).include?(name))
Expand Down
67 changes: 67 additions & 0 deletions test/rbs/test/runtime_test_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,73 @@ def size = "1"
assert_match(/TypeError: \[Proxy#size\] ReturnTypeError: expected `::Integer` but returns `"1"`/, output)
end

def test_core_class_integer
output = assert_test_success(other_env: { "RBS_TEST_TARGET" => "Integer" }, rbs_content: <<RBS, ruby_content: <<RUBY)
class Integer
def double: () -> Integer
end
RBS
class Integer
def double = self * 2
end

raise unless 21.double == 42
RUBY
assert_match(/Setting up method hook in #double/, output)
end

def test_core_class_hash
output = assert_test_success(other_env: { "RBS_TEST_TARGET" => "Hash" }, rbs_content: <<RBS, ruby_content: <<RUBY)
class Hash[unchecked out K, unchecked out V]
def double_values: () -> Hash[K, V]
end
RBS
class Hash
def double_values = transform_values { _1 * 2 }
end

raise unless { a: 1 }.double_values == { a: 2 }
RUBY
assert_match(/Setting up method hook in #double_values/, output)
end

def test_core_class_method_called_in_method_under_test
# `Integer#+` called inside `Integer#add_coercible` is checked, and the call doesn't match `Integer#+`'s overloads
output = refute_test_success(other_env: { "RBS_TEST_TARGET" => "Integer" }, rbs_content: <<RBS, ruby_content: <<RUBY)
class Integer
def add_coercible: () -> Integer
end
RBS
class Coercible
def coerce(other) = [other, 2]
end

class Integer
def add_coercible = self + Coercible.new
end

1.add_coercible
RUBY
assert_match(/TypeError: \[Integer#\+\] UnresolvedOverloadingError/, output)
end

def test_unhookable_method
output = assert_test_success(other_env: { "RBS_TEST_TARGET" => "UnboundMethod" }, rbs_content: <<RBS, ruby_content: <<RUBY)
class UnboundMethod
def arity_plus_one: () -> Integer
end
RBS
class UnboundMethod
def arity_plus_one = arity + 1
end

raise unless Integer.instance_method(:+).arity_plus_one == 2
RUBY
assert_match(/Skipping #bind_call because `rbs test` calls it to run hooks/, output)
refute_match(/Setting up method hook in #bind_call/, output)
assert_match(/Setting up method hook in #arity_plus_one/, output)
end

def test_block_arg
assert_test_success(ruby_content: <<RUBY, rbs_content: <<RBS)
class Hello
Expand Down
Loading