Skip to content

Commit

Permalink
Merge pull request #195 from YusukeHosonuma/hotfix-infinity-loop
Browse files Browse the repository at this point in the history
hotfix: infinity-loop in `@Published` property
  • Loading branch information
YusukeHosonuma committed Jun 20, 2022
2 parents 1ad0d60 + 3cb344c commit 5bc8648
Showing 1 changed file with 40 additions and 2 deletions.
42 changes: 40 additions & 2 deletions Sources/Core/PrettyDescriber.swift
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,6 @@ struct PrettyDescriber {
let typeName = String(describing: target.self)

let propertyWrappers: [(String, String)] = [
("Published", "currentValue"),
("StateObject", "wrappedValue"),
("ObservedObject", "wrappedValue"),
("EnvironmentObject", "_store"),
Expand All @@ -210,7 +209,7 @@ struct PrettyDescriber {
for (type, key) in propertyWrappers {
if typeName.hasPrefix("\(type)<"), let value = lookup(key, from: target) {
if debug {
// e.g. `@Published(42)`
// e.g. `@State(42)`
return "@\(type)(\(__string(value)))"
} else {
return __string(value)
Expand Down Expand Up @@ -241,6 +240,22 @@ struct PrettyDescriber {
}
}

//
// @Published
//
// Note:
// Direct lookups because some data structures infinity-loop with circular references.
//
if typeName.hasPrefix("Published") {
let value = lookup(keyPath: ["storage", "publisher", "subject", "currentValue"], from: target)
if debug {
// e.g. `@Published(42)`
return "@Published\(__string(value)))"
} else {
return __string(value)
}
}

//
// @Namespace
//
Expand Down Expand Up @@ -472,6 +487,29 @@ struct PrettyDescriber {
return nil
}

private func lookup(keyPath: [String], from: Any) -> Any? {
var target: Any = from

for key in keyPath {
if let value = lookup(key: key, from: target) {
target = value
} else {
return nil
}
}

return target
}

private func lookup(key: String, from target: Any) -> Any? {
for child in Mirror(reflecting: target).children {
if let label = child.label, label == key {
return child.value
}
}
return nil
}

private func handleError(_ f: () throws -> String) -> String {
do {
return try f()
Expand Down

0 comments on commit 5bc8648

Please sign in to comment.