From 3dc7d249caa1d1e099421fc07b4cd07ee1709278 Mon Sep 17 00:00:00 2001 From: Ian Leitch Date: Sun, 31 Dec 2023 16:28:37 +0000 Subject: [PATCH] Don't retain RawRepresentable CodingKey enum cases --- .../Mutators/EnumCaseReferenceBuilder.swift | 6 +++++- .../Fixtures/RetentionFixtures/testCodingKeyEnum.swift | 10 ++++++++++ Tests/PeripheryTests/RetentionTest.swift | 9 +++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/Sources/PeripheryKit/SourceGraph/Mutators/EnumCaseReferenceBuilder.swift b/Sources/PeripheryKit/SourceGraph/Mutators/EnumCaseReferenceBuilder.swift index 7f94e516f..706a23841 100644 --- a/Sources/PeripheryKit/SourceGraph/Mutators/EnumCaseReferenceBuilder.swift +++ b/Sources/PeripheryKit/SourceGraph/Mutators/EnumCaseReferenceBuilder.swift @@ -11,7 +11,11 @@ final class EnumCaseReferenceBuilder: SourceGraphMutator { func mutate() { for enumDeclaration in graph.declarations(ofKind: .enum) { - if isRawRepresentable(enumDeclaration) { + let isCodingKey = graph.inheritedTypeReferences(of: enumDeclaration).contains { + $0.kind == .protocol && $0.name == "CodingKey" + } + + if !isCodingKey, isRawRepresentable(enumDeclaration) { let enumCases = enumDeclaration.declarations.filter { $0.kind == .enumelement } for enumCase in enumCases { diff --git a/Tests/Fixtures/RetentionFixtures/testCodingKeyEnum.swift b/Tests/Fixtures/RetentionFixtures/testCodingKeyEnum.swift index e4c5fafeb..ab370d92a 100644 --- a/Tests/Fixtures/RetentionFixtures/testCodingKeyEnum.swift +++ b/Tests/Fixtures/RetentionFixtures/testCodingKeyEnum.swift @@ -72,3 +72,13 @@ public class FixtureClass220: Encodable { case someUnusedVar } } + +public struct FixtureStruct220: Encodable { + public var someUsedVar: String? + var someUnusedVar: String? + + enum CodingKeys: String, CodingKey { + case someUsedVar + case someUnusedVar + } +} diff --git a/Tests/PeripheryTests/RetentionTest.swift b/Tests/PeripheryTests/RetentionTest.swift index 389385f6d..d5792aaaf 100644 --- a/Tests/PeripheryTests/RetentionTest.swift +++ b/Tests/PeripheryTests/RetentionTest.swift @@ -578,6 +578,15 @@ final class RetentionTest: FixtureSourceGraphTestCase { self.assertReferenced(.varInstance("someUsedVar")) self.assertNotReferenced(.varInstance("someUnusedVar")) + self.assertReferenced(.enum("CodingKeys")) { + self.assertReferenced(.enumelement("someUsedVar")) + self.assertNotReferenced(.enumelement("someUnusedVar")) + } + } + assertReferenced(.struct("FixtureStruct220")) { + self.assertReferenced(.varInstance("someUsedVar")) + self.assertNotReferenced(.varInstance("someUnusedVar")) + self.assertReferenced(.enum("CodingKeys")) { self.assertReferenced(.enumelement("someUsedVar")) self.assertNotReferenced(.enumelement("someUnusedVar"))