Skip to content

Commit 765293a

Browse files
committed
Add docstring for the flyweight factory function
1 parent cf937b0 commit 765293a

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/types.jl

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,27 @@ end
341341
### Constructors
342342
###
343343

344+
"""
345+
$(TYPEDSIGNATURES)
346+
347+
Implements hash consing (flyweight design pattern) for `BasicSymbolic` objects.
348+
349+
This function checks if an equivalent `BasicSymbolic` object already exists. It uses a
350+
custom hash function (`hash2`) incorporating metadata and symtypes to search for existing
351+
objects in a `WeakValueDict` (`wvd`). Due to the possibility of hash collisions (where
352+
different objects produce the same hash), a custom equality check (`isequal2`) which
353+
includes metadata comparison, is used to confirm the equivalence of objects with matching
354+
hashes. If an equivalent object is found, the existing object is returned; otherwise, the
355+
input `s` is returned. This reduces memory usage, improves compilation time for runtime
356+
code generation, and supports built-in common subexpression elimination, particularly when
357+
working with symbolic objects with metadata.
358+
359+
Using a `WeakValueDict` ensures that only weak references to `BasicSymbolic` objects are
360+
stored, allowing objects that are no longer strongly referenced to be garbage collected.
361+
Custom functions `hash2` and `isequal2` are used instead of `Base.hash` and `Base.isequal`
362+
to accommodate metadata without disrupting existing tests reliant on the original behavior
363+
of those functions.
364+
"""
344365
function BasicSymbolic(s::BasicSymbolic)::BasicSymbolic
345366
h = hash2(s)
346367
t = get!(wvd, h, s)

0 commit comments

Comments
 (0)