/
reference.cr
260 lines (241 loc) · 6.97 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
{% if flag?(:preview_mt) %}
require "crystal/thread_local_value"
{% end %}
# `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
# Constructs an object in-place at the given *address*, forwarding *args* and
# *opts* to `#initialize`. Returns that object.
#
# This method can be used to decouple object allocation from initialization.
# For example, the instance data might come from a custom allocator, or it
# might reside on the stack using a type like `ReferenceStorage`.
#
# *address* must point to a suitably aligned buffer of at least
# `instance_sizeof(self)` bytes.
#
# WARNING: This method is unsafe, as it assumes the caller is responsible for
# managing the memory at the given *address* manually.
#
# ```
# class Foo
# getter i : Int64
# getter str = "abc"
#
# def initialize(@i)
# end
#
# def finalize
# puts "bye"
# end
# end
#
# foo_buffer = uninitialized ReferenceStorage(Foo)
# foo = Foo.unsafe_construct(pointerof(foo_buffer), 123_i64)
# begin
# foo # => #<Foo:0x... @i=123, @str="abc">
# ensure
# foo.finalize if foo.responds_to?(:finalize) # prints "bye"
# end
# ```
#
# See also: `Reference.pre_initialize`.
@[Experimental("This API is still under development. Join the discussion about custom reference allocation at [#13481](https://github.com/crystal-lang/crystal/issues/13481).")]
def self.unsafe_construct(address : Pointer, *args, **opts) : self
obj = pre_initialize(address)
obj.initialize(*args, **opts)
obj
end
# 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) : Bool
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
{% if @type.abstract? %}
# This shouldn't happen, as the type is abstract,
# but we need to avoid the allocate invocation below
raise "Can't dup {{@type}}"
{% else %}
dup = self.class.allocate
dup.as(Void*).copy_from(self.as(Void*), instance_sizeof(self))
GC.add_finalizer(dup) if dup.responds_to?(:finalize)
dup
{% end %}
end
# See `Object#hash(hasher)`
def hash(hasher)
hasher.reference(self)
end
# Appends a String representation of this object
# which includes its class name, its object address
# and the values of all instance variables.
#
# ```
# class Person
# def initialize(@name : String, @age : Int32)
# end
# end
#
# Person.new("John", 32).inspect # => #<Person:0x10fd31f20 @name="John", @age=32>
# ```
def inspect(io : IO) : Nil
io << "#<" << {{@type.name.id.stringify}} << ":0x"
object_id.to_s(io, 16)
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 << '>'
end
def pretty_print(pp) : Nil
{% if @type.overrides?(Reference, "inspect") %}
pp.text inspect
{% else %}
prefix = "#<#{{{@type.name.id.stringify}}}:0x#{object_id.to_s(16)}"
executed = exec_recursive(:pretty_print) do
pp.surround(prefix, ">", left_break: nil, right_break: nil) do
{% for ivar, i in @type.instance_vars.map(&.name).sort %}
{% if i == 0 %}
pp.breakable
{% else %}
pp.comma
{% end %}
pp.group do
pp.text "@{{ivar.id}}="
pp.nest do
pp.breakable ""
@{{ivar.id}}.pretty_print(pp)
end
end
{% end %}
end
end
unless executed
pp.text "#{prefix} ...>"
end
{% end %}
end
# Appends a short String representation of this object
# which includes its class name and its object address.
#
# ```
# class Person
# def initialize(@name : String, @age : Int32)
# end
# end
#
# Person.new("John", 32).to_s # => #<Person:0x10a199f20>
# ```
def to_s(io : IO) : Nil
io << "#<" << self.class.name << ":0x"
object_id.to_s(io, 16)
io << '>'
end
# :nodoc:
module ExecRecursive
# NOTE: can't use `Set` here because of prelude require order
alias Registry = Hash({UInt64, Symbol}, Nil)
{% if flag?(:preview_mt) %}
@@exec_recursive = Crystal::ThreadLocalValue(Registry).new
{% else %}
@@exec_recursive = Registry.new
{% end %}
def self.hash
{% if flag?(:preview_mt) %}
@@exec_recursive.get { Registry.new }
{% else %}
@@exec_recursive
{% end %}
end
end
private def exec_recursive(method, &)
hash = ExecRecursive.hash
key = {object_id, method}
hash.put(key, nil) do
yield
hash.delete(key)
return true
end
false
end
# :nodoc:
module ExecRecursiveClone
alias Registry = Hash(UInt64, UInt64)
{% if flag?(:preview_mt) %}
@@exec_recursive = Crystal::ThreadLocalValue(Registry).new
{% else %}
@@exec_recursive = Registry.new
{% end %}
def self.hash
{% if flag?(:preview_mt) %}
@@exec_recursive.get { Registry.new }
{% else %}
@@exec_recursive
{% end %}
end
end
# Helper method to perform clone by also checking recursiveness.
# When clone is wanted, call this method. Then create the clone
# instance without any contents (don't fill it out yet), then
# put the clone's object id into the hash yielded into the block.
# At the end of the block return the cloned object.
#
# For example:
#
# ```
# def clone
# exec_recursive_clone do |hash|
# clone = SomeClass.new
# hash[object_id] = clone.object_id
# # fill out the clone object
# clone
# end
# end
# ```
private def exec_recursive_clone(&)
hash = ExecRecursiveClone.hash
clone_object_id = hash[object_id]?
unless clone_object_id
clone_object_id = yield(hash).object_id
hash.delete(object_id)
end
Pointer(Void).new(clone_object_id).as(self)
end
end