-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
reference.cr
98 lines (88 loc) · 2.3 KB
/
reference.cr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# Reference is the base class of classes you define in your program.
# It is set as a class' superclass when you don't specify one:
#
# class MyClass # < Reference
# end
#
# A reference type is passed by reference: when you pass it to methods,
# return it from methods or assign it to variables, a pointer is actually passed.
#
# Invoking `new` on a Reference allocates a new instance on the heap.
# The instance's memory is automatically freed (garbage-collected) when
# the instance is no longer referred by any other entity in the program.
class Reference
# Returns true if this reference is the same as other. Invokes `same?`
def ==(other : self)
same?(other)
end
# Returns false (other can only be a `Value` here).
def ==(other)
false
end
# Returns true if this reference is the same as other. This is only
# true if this reference's `object_id` is the same as other's.
def same?(other : Reference)
object_id == other.object_id
end
# Returns false: a reference is never nil.
def same?(other : Nil)
false
end
# Returns a shallow copy of this object.
#
# This allocates a new object and copies the contents of
# `self` into it.
def dup
{% begin %}
dup = {{@type}}.allocate
dup.as(Void*).copy_from(self.as(Void*), instance_sizeof({{@type}}))
dup
{% end %}
end
# Returns this reference's `object_id` as the hash value.
def hash
object_id
end
def inspect(io : IO) : Nil
io << "#<" << {{@type.name.id.stringify}} << ":0x"
object_id.to_s(16, io)
executed = exec_recursive(:inspect) do
{% for ivar, i in @type.instance_vars %}
{% if i > 0 %}
io << ","
{% end %}
io << " @{{ivar.id}}="
@{{ivar.id}}.inspect io
{% end %}
end
unless executed
io << " ..."
end
io << ">"
nil
end
def to_s(io : IO) : Nil
io << "#<" << self.class.name << ":0x"
object_id.to_s(16, io)
io << ">"
nil
end
# :nodoc:
module ExecRecursive
def self.hash
@@exec_recursive ||= {} of {UInt64, Symbol} => Bool
end
end
private def exec_recursive(method)
hash = ExecRecursive.hash
key = {object_id, method}
if hash[key]?
false
else
hash[key] = true
value = yield
hash.delete(key)
true
end
end
end