DefaultStringConvertible icon indicating copy to clipboard operation
DefaultStringConvertible copied to clipboard

Stack overflow for reference cycle

Open broadwaylamb opened this issue 9 years ago • 2 comments

New issue checklist

General information

  • Library version: 2.0.1

Expected behavior

The depth of the description of a reference cycled object should be limited.

Actual behavior

Obviously, it is not, which causes stack overflow.

Steps to reproduce

class A : CustomStringConvertible {
    var b: B
    init(b: B) {
        self.b = b
    }
}

class B : CustomStringConvertible {
    weak var a: A?
    init() {}
}

let b = B()
let a = A(b: b)
b.a = a

print(a.description)

broadwaylamb avatar Dec 01 '16 17:12 broadwaylamb

lol

Good catch @broadwaylamb !

jessesquires avatar Dec 02 '16 00:12 jessesquires

@jessesquires well, I've just tried to fix it, but have come up with nothing.

The first idea that comes to mind is to add the currentDepth argument to the generateDefaultDescription and generateDeepDescription and decrease it when calling this function recursively. However we don't and can't always call it explicitly. For example, if an object contains a property of some value type, we cannot determine if this value type provides its description using DefaultStringConvertible implementation or its own, custom description. So we must fetch its description using not the generateDefaultDescription method, but String(describing:) function (or string interpolation, which is the equivalent). So depth counting using recursive calls with a decreasing currentDepth argument is quite difficult if not impossible.

Well we could use completely different solution, which is yet to be developed (and as I said I couldn't come up with one). But I'm afraid it won't be that elegant at all.

I feel that this situation is exactly the reason why classes don't provide any default description.

broadwaylamb avatar Dec 05 '16 22:12 broadwaylamb