Skip to content

Commit

Permalink
Add a special handling for obj.class
Browse files Browse the repository at this point in the history
`self.class` will return the class of its context
  • Loading branch information
mame committed Dec 13, 2024
1 parent 1ec0ab1 commit dc6be92
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 5 deletions.
20 changes: 16 additions & 4 deletions lib/typeprof/core/builtin.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,21 @@ def initialize(genv)
end

def class_new(changes, node, ty, a_args, ret)
ty = ty.get_instance_type(@genv)
recv = Source.new(ty)
changes.add_method_call_box(@genv, recv, :initialize, a_args, false)
changes.add_edge(@genv, Source.new(ty), ret)
if ty.is_a?(Type::Singleton)
ty = ty.get_instance_type(@genv)
recv = Source.new(ty)
changes.add_method_call_box(@genv, recv, :initialize, a_args, false)
changes.add_edge(@genv, Source.new(ty), ret)
end
true
end

def object_class(changes, node, ty, a_args, ret)
ty = ty.base_type(@genv)
mod = ty.is_a?(Type::Instance) ? ty.mod : @genv.mod_class
ty = Type::Singleton.new(@genv, mod)
vtx = Source.new(ty)
changes.add_edge(@genv, vtx, ret)
true
end

Expand Down Expand Up @@ -119,6 +130,7 @@ def hash_aset(changes, node, ty, a_args, ret)
def deploy
{
class_new: [[:Class], false, :new],
object_class: [[:Object], false, :class],
proc_call: [[:Proc], false, :call],
array_aref: [[:Array], false, :[]],
array_aset: [[:Array], false, :[]=],
Expand Down
2 changes: 1 addition & 1 deletion lib/typeprof/core/env.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def initialize

attr_reader :type_table

attr_reader :mod_object, :mod_ary, :mod_hash, :mod_range, :mod_str
attr_reader :mod_class, :mod_object, :mod_ary, :mod_hash, :mod_range, :mod_str
attr_reader :cls_type, :mod_type
attr_reader :obj_type, :nil_type, :true_type, :false_type, :str_type
attr_reader :int_type, :float_type, :rational_type, :complex_type
Expand Down
34 changes: 34 additions & 0 deletions scenario/misc/class_method.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
## update: test.rb
def self_class
self.class
end

def int_class
1.class
end

def array_class
[1].class
end

def hash_class
{ 1 => "str" }.class
end

def class_class
Object.class
end

def unknown_class(x)
x.class
end

## assert
class Object
def self_class: -> singleton(Object)
def int_class: -> singleton(Integer)
def array_class: -> singleton(Array)
def hash_class: -> singleton(Hash)
def class_class: -> singleton(Class)
def unknown_class: (untyped) -> untyped
end

0 comments on commit dc6be92

Please sign in to comment.