This one is about finding dead code in a Swift app, and in particular one kind of dead code that the usual tools can’t see at all, a TCA (The Composable Architecture) action that has a reducer arm handling it but that nothing in the app ever sends. I ran into it on a personal iOS app (SwiftUI, TCA and a Rust core, about 4,700 Swift files once tests are counted), where a fix had been moved into exactly such an arm and so never ran, and I wanted a periodic sweep over the whole program that would report actions like that before anyone builds on them.
Why “no references” isn’t enough
The shape of the problem looks like this:
struct Item: Equatable {}
@Reducer
struct ItemsFeature {
@ObservableState
struct State: Equatable {
var items: [Item] = []
}
enum Action {
case itemsLoaded([Item])
case addItem(Item) // nothing sends this
}
var body: some ReducerOf<Self> {
Reduce { state, action in
switch action {
case let .itemsLoaded(items):
state.items = items
return .none
case let .addItem(item):
state.items.append(item) // so this never runs
return .none
}
}
}
}
addItem is dead in every way that matters, but its name appears in the case let .addItem pattern, and to the compiler’s index that pattern is a reference to the case like any other. Any tool built on the rule “a declaration with no references is unused” counts the case as used, and a reducer arm is exactly where every action has a reference, so the tool can never report one.
My first plan was SwiftLint’s unused_declaration analyzer rule over the whole program, tests included, so I measured it on just the feature file and its reducer extension before building anything around it. That run took 89 seconds for two files (the analyzer rules are slow) and reported five things, none of which were the two actions I already knew were dead. Reading the rule’s source (0.65.1) showed a second gap, since it skips any declaration whose cursor info carries key.overrides, which means protocol witnesses and overrides are never reported, and I also wanted a “reached only through a protocol” group in the report. (Earlier, for a different job, I’d had a text scan that looked for senders of the action behind each reducer arm, and of the 15 flags I checked by hand only 2 were real, the same two dead actions, so going back to text wasn’t tempting either.)
Reading the index store directly
Xcode already has all the information we need. With COMPILER_INDEX_STORE_ENABLE=YES the compiler writes every symbol occurrence it resolved into Index.noindex/DataStore under DerivedData, with a set of roles on each one, and the toolchain ships the C library that reads that store, libIndexStore.dylib, in its usr/lib. We can bind it from Python with ctypes, which saves writing a Swift package for it:
import ctypes, os, subprocess
def toolchain_index_library() -> str:
swiftc = subprocess.check_output(["xcrun", "--find", "swiftc"], text=True).strip()
return os.path.realpath(os.path.join(os.path.dirname(swiftc), "..", "lib", "libIndexStore.dylib"))
class StringRef(ctypes.Structure):
# indexstore strings are pointer + length, not NUL-terminated
_fields_ = [("data", ctypes.c_void_p), ("length", ctypes.c_size_t)]
def text(ref: StringRef) -> str:
return ctypes.string_at(ref.data, ref.length).decode("utf-8", "replace") if ref.data else ""
lib = ctypes.CDLL(toolchain_index_library())
lib.indexstore_store_create.restype = ctypes.c_void_p
lib.indexstore_store_create.argtypes = [ctypes.c_char_p, ctypes.POINTER(ctypes.c_void_p)]
lib.indexstore_occurrence_get_roles.restype = ctypes.c_uint64
lib.indexstore_occurrence_get_roles.argtypes = [ctypes.c_void_p]
lib.indexstore_symbol_get_usr.restype = StringRef
lib.indexstore_symbol_get_usr.argtypes = [ctypes.c_void_p]
# ...and the same for units, records, occurrences and relations
The API is callback based (indexstore_store_units_apply_f, indexstore_record_reader_occurrences_apply_f and so on), so the reader walks the units, opens each unit’s records, and turns every occurrence into a small Python value with its USR, name, kind, roles, file, line, column and relations. About twenty functions from indexstore.h were enough. Units also pile up across builds in the same DerivedData, so we keep only the newest unit for each main file and module (indexstore_unit_reader_get_modification_time) and drops units whose source file no longer exists, otherwise deleted and renamed files come back as stale declarations. Reading the whole app takes a few minutes depending on load, which is fine for something that runs now and then.
Each occurrence carries its roles as bit flags from indexstore_symbol_role_t:
ROLE_DEFINITION = 1 << 1
ROLE_REFERENCE = 1 << 2
ROLE_CALL = 1 << 5
ROLE_IMPLICIT = 1 << 8
REL_OVERRIDE_OF = 1 << 11
If we dump the occurrences of a payload case, constructing it (.addItem(item)) comes out as ref,call with a calledBy relation, while the case let .addItem pattern comes out as a bare ref with only containedBy. So the call role settles the common case. A reference with call is a construction and counts as a use.
A reference without call can still be a use, though. A case without a payload (.cancelTapped) never gets call, whether it’s sent or matched, and neither does a payload case used as a function value, like .map(Action.itemsLoaded) in an effect. For every enum-case reference without call we read the source at the line and column the index reports and scans backwards from it. It skips dots, identifiers, a case .a, .b list and the parentheses of an outer pattern (case .delegate(.closed)), until it hits either the word case or catch, which makes it a pattern, or something that ends a pattern first (:, =, an operator, a line that isn’t continued by a comma), which makes it a use:
def is_pattern_position(source_before: str) -> bool:
depth, index = 0, len(source_before)
while index > 0:
index -= 1
c = source_before[index]
if c in ")]":
depth += 1
elif c in "([":
depth = max(depth - 1, 0)
elif depth > 0:
continue
elif c == "\n":
if not source_before[:index].rstrip().endswith(","):
return False
elif c in ":{};=!<>&|?+-*/":
return False
elif c.isalnum() or c == "_":
end = index + 1
while index > 0 and (source_before[index - 1].isalnum() or source_before[index - 1] == "_"):
index -= 1
if source_before[index:end] in ("case", "catch"):
return True
return False
It’s a heuristic, but it only has to answer one question about one token whose position the compiler already resolved, which is a lot easier than finding the token in the first place. It errs towards “used” (a labelled payload pattern like case .x(reason: .y) stops at its colon and counts as a use), so it can miss a dead case but won’t report a live one because of it.
Macros need their own handling. @Reducer makes the Action enum @CasePathable, and the macro’s expansion references every case and generates an AllCasePaths member for each one. Counting those implicit references as uses marks every case in the app as sent (which is how my first version hid both known-dead actions again), so we skip anything with the implicit role on an enum case. Key paths still have to count, because the view sends actions through them without naming the case, as in $store.isOn.sending(\.toggled) or store.scope(state: \.child, action: \.child). So an explicit key-path reference to an AllCasePaths member is credited to its case as a use. That also counts key paths that only match (a reducer’s Scope, action.is(\.x)), which can hide a dead case but never a sender.
Sorting what’s left
With uses counted that way, each production declaration that production code doesn’t use goes into one of three groups:
- unreachable, nothing uses it, in production or in tests,
- test-only, only test sources use it (which is where the two known-dead actions should land, because their reducer tests send them),
- witness-only, nothing names it directly, but it implements a first-party protocol requirement or overrides a member that production calls through an existential or a base class.
The witness group comes from the overrideOf relations, followed as a chain, so a requirement whose conformers are called directly doesn’t count against them. A witness of an SDK requirement (anything whose target isn’t defined in the app’s own sources) is left out, because the framework reaches it and we can’t see that in the index. Cases of enums that are CaseIterable, Codable or have a raw type are left out as well, since allCases, init(rawValue:) and decoders reach them by value, and so are CodingKey conformances, which the synthesized Codable code uses without naming. A case that production only ever matches also gets a matched-never-constructed tag, which is the exact shape I was after.
Building an index that covers everything
The index only knows about code the build compiled, which matters more than it sounds. The app also runs on Mac Catalyst, and code under #if targetEnvironment(macCatalyst) (69 files here) is never compiled for the iOS simulator, so it isn’t in the iOS index at all and everything only those files call showed up as unreachable in the first report. So we have to build twice and read both stores.
The test targets also need indexing, and they had COMPILER_INDEX_STORE_ENABLE: NO in the project, which left no test units in the store, so nothing could ever be test-only, and the fix is to pass YES on the command line. The generic iOS Simulator destination builds x86_64 as well as arm64, so if a binary dependency ships only an arm64 simulator slice we need ARCHS=arm64. On Catalyst code coverage had to go, because its instrumentation broke the link of one C dependency, and since we only need the index, not a test host that runs, the build can be unsigned. Trimmed of the settings only this project needs, the two builds are:
xcodebuild -project App.xcodeproj -scheme App -configuration Debug \
-destination 'generic/platform=iOS Simulator' \
-derivedDataPath .sweep/DerivedData \
COMPILER_INDEX_STORE_ENABLE=YES ARCHS=arm64 ONLY_ACTIVE_ARCH=YES \
build-for-testing
xcodebuild -project App.xcodeproj -scheme App -configuration Debug \
-destination 'platform=macOS,variant=Mac Catalyst' \
-derivedDataPath .sweep/DerivedData-catalyst \
-enableCodeCoverage NO CODE_SIGNING_ALLOWED=NO \
COMPILER_INDEX_STORE_ENABLE=YES \
build-for-testing
Each of those took about 45 minutes cold. A DerivedData folder can’t be moved somewhere else to save one of them either, because it’s full of absolute paths and the moved copy fails looking for frameworks at the old location (I found that out the slow way :|).
How it did
The first full report had 1,117 unreachable, 1,175 test-only and 654 witness-only declarations, and 179 enum cases that production matches and never constructs, which is a lot to triage, so the groups and the tag matter more than the totals. Both known-dead actions came out test-only with the matched-never-constructed tag, and a constant I knew only tests read came out test-only too. Before the Catalyst build and the key-path handling were in, an independent agent hand-checked a 55-row sample of the iOS-only report and 46 rows were right. Most of the nine misses were exactly the problems described above (TCA binding sends, Catalyst-only callers and a CodingKeys enum), and one was a witness reached only through a test-only protocol-extension helper, which the sweep still can’t tell apart. I haven’t re-sampled the final report, so I don’t have a precision number for it. Among the finds was an editor action with a reducer arm and no sender, and a child feature whose whole set of delegate actions the parent matches and nothing constructs, which is the same bug class that started this.
A tool that counts references in Swift’s index can’t find an action nobody sends, because the pattern that matches it in the reducer is a reference too. What made this workable is that the compiler records construction for applied payload cases in the call role, a short backwards scan of the source covers the references that lack it, and the index store turned out to be a lot easier to read than I expected, since libIndexStore.dylib ships with the toolchain and a few dozen lines of ctypes get every resolved occurrence out of it. The sweep is only as complete as the index, though, so every platform the code compiles for has to be built with the test targets indexed, and macro-generated references have to be counted separately, otherwise a single @CasePathable marks every case as used.