Skip to content
Back to skills

Sweep Code

ASecurity

Scan the code for bugs and dead code, prove each finding, then fix the approved bugs with regression tests and remove the approved dead code.

  • 6 stars
  • 0 votes
  • 0 copies
  • 1 view
  • Added November 26, 2026
developmentjavascripttypescriptpythonrustgojavarubyphpswiftkotlin

Works with

  • cli
  • api

Security analysis

A100/100

Scanned December 2, 2026

npx -y skills add jabbott-iii/Doctrina --skill sweep-code --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Sweep Code?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Sweep Code
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/jabbott-iii-sweep-code/badge)](https://www.skillsdirectory.com/skills/jabbott-iii-sweep-code)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: sweep-code
description: Scan the code for bugs and dead code, prove each finding, then fix the approved bugs with regression tests and remove the approved dead code.
argument-hint: "[path, area, or Git range such as v1.2.0..HEAD] [bugs | dead code]"
disable-model-invocation: true
---

# Sweep the code for bugs and dead code

Requested: `$ARGUMENTS` (empty means the whole repository, and both kinds).

This skill looks for two kinds of problems, and fixes the ones the user approves:

- **Bugs:** code that does the wrong thing, or will for some input, timing, or platform.
- **Dead code:** code, files, and dependencies that no build the project ships ever reaches.

It proves each finding before it reports it, changes nothing until the user approves, and makes
each fix a change of its own. Bold names are values from the "Project details" of the adopted
rules:

- **Git access**, **Done checks**, **Never commit**, and **Breaking changes** from `commits.md`;
- **Check commands**, **Test layout**, **Dependency policy**, **Public API**, and
  **Published crates**, **Published modules**, **Published rocks**, **Published packages**,
  **Published libraries**, **Published gems**, or **Published distributions** from the language
  rules (`rust.md`, `kotlin.md`, `java.md`, `android.md`, `kotlin-multiplatform.md`, `swift.md`,
  `flutter.md`, `lua.md`, `python.md`, `typescript.md`, `c.md`, `cpp.md`, `php.md`, `go.md`,
  `csharp.md`, `ruby.md`, and `perl.md`), **Sanitizer builds** from `c.md` and `cpp.md`,
  **Static analysis** from `php.md`, **Type checking** from `ruby.md`, **Lint configuration** from
  `perl.md`, **Exported components** from `android.md`, and **Test tools** from
  `web-front-end.md`;
- the **Docs folder** and the **Decision log** from `roadmap-and-docs.md`, where it is adopted.

Where a value doesn't exist because a rule isn't adopted, work from what the repository has, and
say so in the report. Ask before each change that a rule's "Decisions that are the user's"
section lists, and where `pair-programming.md` is adopted, work with the user as it describes.

## 1. Set the scope

- **A path or an area:** the code there, its tests, and the files only it uses.
- **A Git range:** the code the range changed (`git diff --stat <range>`) and the code that calls
  it. New bugs most often sit in new code, and new dead code in what the new code replaced.
- **Empty:** the whole repository, one module, crate, or package at a time. If there are more
  than a few, report after each one.
- **"bugs" or "dead code"** after the scope: look for that kind only.

Leave out generated code, vendored third-party code, and the **Never commit** paths. Report a
bug found there, but fix it at its source: the generator's input, or the upstream project.

Run `git status` before you start. If the tree has uncommitted changes you didn't make, leave
them alone and tell the user, because a fix mixed into them can't be reviewed or reverted on its
own. Then tell the user in one or two sentences what you will scan and in what order, and make a
task list whose last item is "Verify and report".

## 2. Record a baseline

Before you change anything, run the **Check commands** (or the **Test tools**) and the
**Done checks**, and record each result: what passes, what fails, and how many warnings each
tool prints. A check that already fails is a finding, not something your work broke. If the code
doesn't build, report that first, and look for findings only by reading until the user decides
what to do.

## 3. Look for bugs

**Run the tools.** Run the project's own checks at the strictest settings it uses, then the tools
in "Tools by language" that the project already has. Read every warning, including the ones the
project has learned to ignore. In C and C++, also run the tests in each of the
**Sanitizer builds**, because a read past a buffer's end or a use after free often shows no
symptom until a sanitizer reports it. Don't install a tool, or run a command that downloads one
(such as `npx` or `dart pub global activate`), without asking the user first.

**Question every suppression.** Each one hides a possible finding: `#[allow(…)]`, `@Suppress`,
`@SuppressWarnings`, `@SuppressLint`, a lint baseline, `// ignore:`, `// swiftlint:disable`,
`eslint-disable`, `@ts-ignore`, `@ts-expect-error`, `# noqa`, `# type: ignore`,
`-- luacheck: ignore`, `---@diagnostic disable`, `#pragma GCC diagnostic ignored`,
`#pragma clang diagnostic ignored`, MSVC's `#pragma warning(disable: …)`, `// NOLINT`,
`// NOLINTNEXTLINE`, `// cppcheck-suppress`, `@phpstan-ignore`, `@psalm-suppress`,
`// phpcs:ignore`, PHP's `@` operator, `//nolint`, `//lint:ignore`, `//lint:file-ignore`, C#'s
`#pragma warning disable`, `[SuppressMessage]`, `GlobalSuppressions.cs`, `<NoWarn>` in a project
file, RuboCop's `# rubocop:disable` and `# rubocop:todo` comments and `.rubocop_todo.yml`, and
Perl's `## no critic` annotations, `no warnings`, and `no strict`. Check that its reason still
holds. In Rust, `#[expect(…)]` in place of `#[allow(…)]` makes the
compiler warn (`unfulfilled_lint_expectations`) when the lint no longer fires, so it shows which
suppressions hide nothing. In Python, mypy's
`warn_unused_ignores` and Ruff's `RUF100` do the same for `# type: ignore` and `# noqa` comments. In
TypeScript, `tsc` reports an `@ts-expect-error` with no error left to expect, and ESLint's
`reportUnusedDisableDirectives` reports an `eslint-disable` comment that suppresses nothing. In
Java, `javac` never reports a `@SuppressWarnings` that suppresses nothing, so remove each one and
compile again to see whether it still hides a warning. The same goes for C and C++: GCC never
reports a `#pragma GCC diagnostic ignored` that hides nothing, and clang-tidy never reports such a
`NOLINT` comment. cppcheck does report its own suppressions that match nothing, as
`unmatchedSuppression`, under `--enable=information`; it reads `// cppcheck-suppress` comments
only with `--inline-suppr`. In PHP, PHPStan reports an ignore comment or a baseline entry that
matches no error (`reportUnmatchedIgnoredErrors`, on by default). Psalm reports a baseline entry
that matches nothing (`findUnusedBaselineEntry`, on by default), and an unused `@psalm-suppress`
once `findUnusedPsalmSuppress` is on. Nothing reports a `phpcs:ignore` comment, or an `@`, that
hides nothing. In Go, golangci-lint's `nolintlint`, once it is turned on, reports a `//nolint`
that suppresses nothing, unless its `allow-unused` option is set; staticcheck reports a
`//lint:ignore` line that matches nothing, but never a `//lint:file-ignore`. In C#, nothing in a
command-line build reports a suppression that hides nothing: the compiler doesn't, and IDE0079,
"Remove unnecessary suppression", runs only in the editor. In Ruby, RuboCop's
`Lint/RedundantCopDisableDirective`, on by default, reports a disable comment that hides nothing,
and `rubocop --report-unused-todo-entries` reports entries in `.rubocop_todo.yml` that nothing
needs. In Perl, Perl::Critic's `Miscellanea::ProhibitUselessNoCritic` reports a `## no critic`
annotation that hides nothing, and `Miscellanea::ProhibitUnrestrictedNoCritic` one that names no
policy. Their severities, 2 and 3, sit below `perlcritic`'s default of 5, so they run only where
the **Lint configuration** or the command line lowers the severity, as `perlcritic --severity 2`
does. Nothing reports a `no warnings` that hides nothing.

**Read the code.** Look for what tools miss, hardest where input enters, where errors are
handled, and where work runs at the same time:

| Kind | What to look for |
| --- | --- |
| Errors | Errors caught and dropped (an empty `catch`, `let _ =`, `try?`, `.ok()`, `runCatching` with its result ignored); errors logged and then ignored; an error code that C code never checks, as from `fclose` or `write`; a `false` that a PHP built-in function, such as `file_get_contents` or `preg_match`, returns on failure and nothing checks; an error assigned to `_` in Go; Ruby's `rescue nil` and modifier `rescue`, which hide every error in an expression; in Perl, an `eval` whose failure nothing checks, and an `open`, `close`, or `system` whose result nothing checks where `autodie` isn't on; a crash on bad input (`unwrap`, `!!`, a force unwrap, an unchecked index) |
| Edges | Off-by-one errors; empty and one-item input; integer overflow and narrowing casts; division by zero; NaN (not a number); `==` on floating-point numbers |
| Untrusted input | Sizes and counts used without a limit; path traversal (`../` in a file name); input pasted into SQL, a shell command, or HTML |
| Concurrency | Data races; check-then-act on shared state (acting on a value another thread may have changed since it was read); a lock held across an `await`; work that is never canceled; futures, promises, and tasks never awaited; in Go, a goroutine that waits forever on a channel that nothing sends to or closes, and a `context` whose `cancel` function is never called; in C#, an `async void` method, whose exceptions no caller can catch, `.Result` or `.Wait()` on a task, which can deadlock, and a `CancellationToken` that isn't passed on; in Ruby, state at the class level, such as `@cache ||= …` in a class method, which every thread of a threaded server such as Puma shares; in Perl, one request's data kept in a package variable, a `state` variable, or a `my` variable at file scope, which a preforking server's worker keeps for its next request, and a database handle used by both a parent and the child it forked |
| Resources | Files, connections, listeners, subscriptions, and timers never closed or removed; reference cycles that keep objects alive |
| Memory | In C and C++: a read or write past a buffer's end; use after free, and a double free; a pointer, reference, `std::string_view`, `std::span`, or iterator that outlives its object, or that a container invalidated when it grew; a read of an uninitialized variable; signed overflow and other undefined behavior, which the optimizer may assume never happens |
| State | A cache that is never invalidated; state left half-updated after a failure; writes that belong in one transaction but aren't |
| Logic | Inverted conditions; the wrong operator; a copied branch with one name left unchanged; a shadowed variable; a `switch` case that falls through; identity compared where equality was meant; in Lua, a method called with `.` instead of `:`, and `#` on a table that can have holes; in Python, a mutable default argument that every call shares, and a closure that reads a loop variable after the loop has moved on; in JavaScript and TypeScript, `sort()` on numbers without a compare function, which sorts them as strings, and `||` where `??` was meant, which replaces a valid `0` or `""`; in Java, `BigDecimal.equals` where `compareTo` was meant, since `equals` also compares the scale, so `1.0` doesn't equal `1.00`; in PHP, `==` on strings that look like numbers (`"1e3" == "1000"` is `true`), `in_array` or `array_search` without `true` as the third argument, `array_merge` on arrays keyed by integer IDs, which renumbers them, and a variable left bound by a `foreach` by reference, which a later loop overwrites; in Go, a nil pointer returned as an `error`, which isn't nil; two `append`s to one slice that overwrite each other's elements; a `defer` inside a loop, which runs only when the function returns; an `err` declared again with `:=` in an inner block, which hides the one the function returns; and closures that capture a loop variable in a module whose `go` line is older than 1.22; in C#, lambdas made in a `for` loop, which all share its one variable, a LINQ query enumerated twice, which runs twice, `==` on two class instances, which compares references, and culture-sensitive `StartsWith`, `IndexOf`, or `ToUpper` used on identifiers or keys; in Ruby, `Hash.new([])` or `Array.new(3, [])`, which share one object among every slot, a test of `0` or `""`, which are true, `and` or `or` in an assignment, which bind more loosely than `=`, a misspelled instance variable, which reads as `nil`, and `^` or `$` in a validation pattern, which match at each line break; in Perl, `==` on strings, which compares them as numbers, `sort` on numbers without `{ $a <=> $b }`, `index` tested for truth, though it returns -1 when the text is missing, `split` without a limit of -1, which drops empty fields at the end, `$1` read after a match that failed, which still holds an earlier match's capture, `return undef` in a sub called in list context, which gives a true one-element list, `my $x = … if …`, whose behavior `perlsyn` leaves undefined, and `$` in a validation pattern, which matches before a final newline |
| Time and place | Time zones and daylight saving time; clocks that can go backward; parsing and formatting that depend on the device's locale |
| Contracts | Code that disagrees with its doc comment, its spec, its test's name, or the decision record that set it; a `TODO` or `FIXME` that describes a known bug |

**Prove each one.** Give every suspected bug a proof before you report it, and say which kind:

- **Confirmed:** a test or a run fails because of it. Write that test now when you can; it
  becomes the fix's regression test.
- **Traced:** an input, timing, or platform that reaches the bug, followed step by step through
  the code, but not run.
- **Suspected:** a pattern that is often a bug, with no path to it found yet. Report it as a
  question, never as a bug.

## 4. Look for dead code

**What counts:**

- Unreachable code: statements after a `return` or a `throw`, and branches whose condition can't
  be true.
- Unused private and internal declarations: functions, types, fields, constants, parameters,
  imports, and local variables.
- Unused public declarations in an application. A library's are different: see "Libraries"
  below.
- Feature flags that are always on or always off, and the branches they hide.
- Compatibility code the project no longer needs, such as a check for an OS version below the
  lowest one it supports.
- Commented-out code.
- Unused files: resources, assets, strings, styles, scripts, config, and fixtures.
- Unused dependencies, and build targets and scripts that nothing runs.
- Tests of dead code only. They are dead too, and go with it.

**Prove it dead.** A search that finds no caller isn't proof. Before you call something dead,
rule out every way code is reached without a direct call:

- Reflection, serialization, and dependency injection: names in annotations, JSON fields, and
  dependency injection modules.
- Names looked up as text: Android resources by name, platform channel and method names, routes,
  event names, CSS classes that JavaScript builds, registries keyed by strings, in Lua, module
  names built as strings for `require` and functions looked up by name (`M[name]`), in Python,
  names passed to `getattr` or `importlib.import_module` that the code builds at run time, and in
  JavaScript and TypeScript, `import()` of a path built at run time and properties read with a
  computed name (`handlers[name]`), in Java, `Class.forName` and method lookups by reflection
  with names built at run time, in C and C++, functions that `dlsym` or `GetProcAddress` looks
  up by name in a shared library, and in PHP, classes and functions named by a string built at run
  time (`new $class`, `$name()`, or `call_user_func`), class names and service IDs in the
  framework's configuration files, and Twig's `user.name`, which reads an array element, a
  property, or a class constant `name`, or calls `name()`, `getName()`, `isName()`, or
  `hasName()`, whichever it finds first. In Go, they include methods that `reflect` finds with
  `MethodByName`, and exported methods that a `text/template` or `html/template` template calls by
  name, as `{{.FullName}}` calls `FullName`. In C#, they include types that `Type.GetType` or
  `Activator.CreateInstance` loads by a name in configuration, services registered by scanning
  assemblies, and properties that only a serializer sets or reads. In Ruby, they include methods
  called through `send` or `public_send`, constants found with `const_get` or `constantize`,
  methods that `method_missing` or `define_method` provides, Rails callbacks named as symbols
  (`before_action :authenticate_user!`), and views, partials, and helpers that Rails finds by
  name. In Perl, they include subs called through a symbolic reference (`&{"handle_$name"}`), a
  method name in a variable (`$obj->$method`), or `can`; subs that `AUTOLOAD` provides; accessors
  that Moo or Moose `has` generates; modules loaded by a name built at run time; and controller
  actions named as strings in routes, such as Mojolicious' `to => 'users#show'`.
- Entry points the platform calls: the components in the Android manifest (the
  **Exported components**), `Info.plist` entries on Apple platforms, `main` functions, scheduled
  jobs, command-line subcommands, the callbacks a Lua host calls by name, and in Python, the entry
  points in `pyproject.toml` (`[project.scripts]` and `[project.entry-points]`), the fixtures and
  hooks that pytest finds by name, and special methods, such as `__eq__` and `__enter__`, that the
  interpreter calls itself. In JavaScript and TypeScript, they include the entry points in
  `package.json` (`bin`, `main`, and each path in `exports`) and the files a framework loads by
  where they sit, such as page and route files. In Java, they include the service providers that
  `ServiceLoader` finds, which `META-INF/services/` or a `provides` clause in `module-info.java`
  names, and the classes a framework finds by their annotations, such as Spring's `@Component` or
  JUnit's `@Test`. In C and C++, they include code that runs before `main`: functions marked
  `__attribute__((constructor))`, and global or static objects whose initialization registers
  something, as Google Test's `TEST` macro registers each test. Nothing names such an object
  again, so it looks unused. In PHP, they include the `bin` scripts and `autoload.files` in
  `composer.json`; the classes a framework finds by attribute or by folder, such as Symfony's
  `#[AsCommand]`, `#[Route]`, and `#[AsEventListener]`, and the event listeners that Laravel 11
  and later discover in `app/Listeners`; WordPress hooks added with `add_action` and
  `add_filter`; and magic methods, such as `__toString`, `__invoke`, and `__get`, that PHP calls
  itself. In Go, they include `init` functions; the `Test`, `Benchmark`, `Fuzz`, and `Example`
  functions that `go test` finds by name; and methods that only satisfy an interface, such as
  `String`, `Error`, `MarshalJSON`, or `ServeHTTP`, which code calls through the interface. In
  C#, they include ASP.NET Core controllers and actions, which the framework finds by convention;
  minimal API handlers; test methods marked `[Fact]` or `[Test]`; `[ModuleInitializer]` methods,
  which run when their assembly loads; event handlers that XAML names; and partial methods whose
  bodies a source generator writes. In Ruby, they include controller actions that Rails routes
  reach, jobs, Rake tasks, the executables a gemspec lists, and hook methods that Ruby calls
  itself, such as `included`, `inherited`, and `method_missing`. In Perl, they include the scripts
  that `Makefile.PL` installs through `EXE_FILES`, the test files in `t/`, `BEGIN` and `END`
  blocks, and subs that perl calls itself: `import`, which `use` calls, `DESTROY`, `AUTOLOAD`, the
  `FETCH` and `STORE` methods of a tied variable, and the handlers that `use overload` names.
- Symbols exported to another language: `#[no_mangle]` and `extern "C"`, Java Native Interface
  (JNI) functions, `@objc`, `@JvmStatic`, the framework API that Kotlin Multiplatform exports to
  Swift, Dart's `@pragma('vm:entry-point')`, C functions registered with Lua (a `luaL_Reg`
  array), the symbols a C or C++ shared library exports: those with default visibility, marked
  `__declspec(dllexport)`, or named in a linker version script or a `.def` file, Go functions
  marked `//export` for C code under cgo, and C# methods marked
  `[UnmanagedCallersOnly(EntryPoint = "…")]`, which a Native AOT library exports.
- Code that only some builds use: platforms, targets, build variants, and features
  (`#[cfg(…)]`, Cargo features, `expect` and `actual`, `#if os(…)`, Gradle product flavors and
  Maven profiles, `kIsWeb`, Lua's checks of `jit` or `_VERSION`, and Python's checks of
  `sys.version_info` or `sys.platform`, and its `if TYPE_CHECKING:` blocks, which only type
  checkers read; in JavaScript, checks of `process.env.NODE_ENV` or `typeof window`, and the
  conditions in `package.json`'s `exports`; in C and C++, `#if` and `#ifdef` on macros that the
  build defines, through `-D` flags and CMake or Meson options, and C++'s `if constexpr`; in PHP,
  checks of `PHP_VERSION_ID`, `function_exists`, `extension_loaded`, or the environment, such as
  `APP_ENV`; and in Go, build constraints, such as `//go:build linux` or a tag such as
  `integration`, and file names that end in an OS or an architecture, such as `_windows.go` or
  `_arm64.go`; and in C#, `#if` on symbols such as `DEBUG` or `NET10_0_OR_GREATER`, methods marked
  `[Conditional("DEBUG")]`, whose calls the compiler leaves out of other builds, and each target
  framework of a project that builds for several; and in Ruby, checks of `RUBY_VERSION`,
  `RUBY_PLATFORM`, or `Rails.env`, and the gems in a Bundler group that only some environments
  install; and in Perl, checks of `$]` or `$^O`, and code that runs only when an optional module
  loads, as in `eval { require JSON::XS; 1 }`).
- Code generators, build scripts, macros, templates, and other repositories that call or copy
  this code.
- Work the roadmap plans: code written ahead for a planned task isn't dead. Check the roadmap in
  the **Docs folder** and the **Decision log**, and ask the user.

**Libraries.** Code you can't see uses a library's public items, so never call one dead because this
repository doesn't use it. The **Public API** and the **Published crates**, **Published modules**,
**Published rocks**, **Published packages**, **Published libraries**, **Published gems**, or
**Published distributions** say what is published. Removing a published item falls under
**Breaking changes** and is the user's decision; suggest deprecating it first.

**Classify each finding:**

- **Dead:** no path reaches it in any build, and the compiler or a tool agrees where one can
  tell.
- **Probably dead:** no use found, but a way in from the list above can't be ruled out. Report it
  with what you checked.

Compilers find only part of the dead code. "Tools by language" says what each one misses.

## 5. Report the findings, then ask

Show every finding in one table before you change anything:

| # | Kind | Where | What's wrong | Proof | Proposed fix | Risk |
| --- | --- | --- | --- | --- | --- | --- |
| 1 | Bug, confirmed | `src/header.rs:88` | A header over 255 bytes wraps its `u8` length to 0 | `rejects_long_header` fails | Reject lengths above 255 | Low: one function |
| 2 | Dead code, dead | `src/legacy.rs` | Nothing has called the v1 parser since v2.0.0 | No reference in any target or feature; the compiler warns | Delete the file and its tests | Low |

List the bugs first, the worst first: data loss and security, then wrong results, then crashes
on rare input. Then the dead code. Then ask the user which findings to fix. Offer to fix every
confirmed bug and every dead private item under one approval, and ask about each of these by its
number:

- a traced or suspected bug;
- a probably-dead item;
- a fix that changes public API, a file format, stored data, or behavior a user can see;
- deleting a whole file, module, or dependency.

## 6. Fix one finding at a time

Make each fix a complete change that one commit can describe.

**A bug:**

1. Write a test that fails because of the bug, where the **Test layout** puts tests. Run it, and
   watch it fail for the reason you expect.
2. Fix the cause, not the symptom: the code that let the bad value in, not the place it crashed.
   Never make a bug go away by suppressing a warning, discarding the error, or loosening a test.
3. Run the test again, and watch it pass.
4. Look for the same mistake elsewhere, because copied code copies its bugs. Add each one you
   find to the findings, and fix it only once the user approves it.

If no test can show the bug, as with a race that rarely happens or a device you don't have, say
so, and tell the user how to confirm the fix.

**Dead code:**

1. Delete all of it: the code, its tests, the docs and comments that mention it, and the
   resources, config, and dependencies only it used. Don't comment it out, rename it `_unused`,
   or hide it behind a flag; Git keeps the history.
2. Remove a dependency with the package manager's own command where it has one (`cargo remove`,
   `npm uninstall`, `dart pub remove`), so the lock file stays right, and follow the
   **Dependency policy**.
3. Leave the code around it as it is: don't refactor, reformat, or rename it in the same change.

Stop and ask if a fix grows bigger than its finding described, or needs a decision the user
hasn't made. If a finding proves wrong while you fix it, drop it, and say so in the report.

## 7. Verify

1. Run the **Check commands** (or the **Test tools**) and the **Done checks** again, and compare
   each result with the baseline: nothing newly failing, and no new warnings.
2. Confirm that each bug's regression test failed before its fix and passes now.
3. After removing dead code, build and test every platform, target, build variant, and feature
   combination the project has, because code that only one of them uses fails only there. For
   example, in Rust run `cargo check --all-targets` with `--all-features` and with
   `--no-default-features`.
4. Search once more for every name you deleted, in the docs, config, and scripts too.
5. Do the checks in "Before finishing" in `writing.md` for each comment and document you
   changed.

## 8. Record what's left

- List the findings you didn't fix, and why: not approved, waiting for a decision, or outside the
  scope.
- If `roadmap-and-docs.md` is adopted, offer to add the ones the user wants to keep to the
  roadmap's backlog. Don't open issues in a tracker unless the user asks.
- For each kind of finding that turned up more than once, suggest a check that would catch it
  next time: a lint to turn on, a stricter compiler setting, a test, or a tool in continuous
  integration (CI). Don't add one unless the user agrees.

## 9. Commit only as the project allows

Follow the **Git access** level in `commits.md`, and leave the changes uncommitted unless the user
asked for a commit and that level allows it. Either way, end the report with copy-ready commit
messages, as `commits.md` describes, one for each fix. A bug fix is a `fix`; removing dead code
without changing behavior is a `refactor`; removing only an unused dependency is a `build`
change.

## 10. Report

End with a summary that contains:

- **Scope:** what you scanned, and what you left out and why.
- **Baseline:** each check's result before you started.
- **Fixed:** each finding fixed, with its regression test, or the proof that the code was dead.
- **Not fixed:** each finding left, by its number, and why.
- **Dropped:** each finding that proved wrong.
- **Checks:** each check after the fixes, with its real result compared with the baseline, and
  each one you couldn't run, and why.
- **Questions:** each decision the user still has to make.
- **Prevention:** the checks you suggest in step 8.
- **Commit messages:** in `text` blocks, as `commits.md` describes, with no attribution lines.

## Tools by language

Use the tools the project already has first. This table says what each compiler reports on its
own, what it misses, and the tools that cover the rest. The compiler columns held for rustc 1.99,
Kotlin 2.4.21, javac 25.0.5, Swift 6.4.3, Dart 3.14.1, TypeScript 7.0.2, Lua 5.1.5, 5.4.9, and
5.5.1, LuaJIT 2.1, GCC 13.3, Go 1.26.9, Ruby 3.2.3, and perl 5.38.2. The PHP and C# rows, and
the tools in the Go, Ruby, and Perl rows, come from each tool's documentation or source.

| Language | What the compiler reports | What it misses, and the tools that find it |
| --- | --- | --- |
| Rust | `dead_code` for items nothing in the crate uses, and `unused_imports`, `unused_variables`, and `unreachable_code`. An item that only tests use counts as unused in `cargo check`. | The `pub` items a library exports. Clippy (`cargo clippy --all-targets --all-features`) for likely bugs; Miri (`cargo +nightly miri test`) for undefined behavior in `unsafe` code, though it can't run most foreign function interface (FFI) calls; `cargo machete` (fast but imprecise) or `cargo +nightly udeps` for unused dependencies; `cargo audit` or `cargo deny check advisories` for dependencies with known vulnerabilities |
| Kotlin and Android | With `-Wextra` only: unused local variables and unreachable code. The experimental `-Xreturn-value-checker=full` reports ignored return values. | Unused private functions, properties, and parameters, and unused imports: detekt's `Unused…` rules in its style rule set, some of them off by default. Android Lint's `UnusedResources`, and `ObsoleteSdkInt` for version checks that `minSdk` makes always true. The Dependency Analysis Gradle Plugin's `buildHealth` task for unused dependencies |
| Java | Nothing about unused code: `-Xlint:all` stays silent about unused imports, private fields and methods, parameters, local variables, and a `@SuppressWarnings` that suppresses nothing. A statement after a `return` is a compile error, but an `if (false)` block compiles without a warning, because the language allows it for conditional compilation. | Error Prone's `UnusedVariable` and `UnusedMethod` checks; PMD's `UnusedPrivateField`, `UnusedPrivateMethod`, `UnusedLocalVariable`, and `UnusedFormalParameter` rules; SpotBugs for likely bugs; and `mvn dependency:analyze`, which lists dependencies the code declares but doesn't use, or uses without declaring. For Gradle, the Dependency Analysis Gradle Plugin in the Kotlin row |
| Swift | Unused local constants and variables, ignored results of functions without `@discardableResult`, and, in a full build but not with `-typecheck`, code after a `return` | Unused functions, types, properties, and parameters: Periphery (`periphery scan`), now a commercial product, which on Linux scans only Swift packages. The sanitizers for bugs: `swift test --sanitize=thread`, `address`, or `undefined` |
| Dart and Flutter | `unused_import`, `unused_local_variable`, `unused_field`, `dead_code`, and `unused_element` for private declarations (names that start with `_`) | Unused public declarations, which no analyzer diagnostic reports: search for them, and rule out the ways in above. `dependency_validator` for unused packages |
| JavaScript and TypeScript | TypeScript with `noUnusedLocals`, `noUnusedParameters`, `allowUnreachableCode: false`, and `noFallthroughCasesInSwitch`; ESLint's `no-unused-vars`, `no-unreachable`, and `no-fallthrough`, which its recommended config turns on | Unused exports, files, and dependencies: knip. Conditions that the types show are always true or always false, and so guard dead branches: typescript-eslint's `no-unnecessary-condition`. CSS and JavaScript a page never runs: the **Coverage** panel in Chrome DevTools. `npm audit` for dependencies with known vulnerabilities |
| Python | No compile step reports unused code | Ruff's `F401` (unused imports) and `F841` (unused local variables), which it checks by default; Vulture for unused functions, classes, and variables, with `--min-confidence`, and a `--make-whitelist` file for its false positives; mypy's `--warn-unreachable`, which `--strict` doesn't turn on, for code its type analysis shows can never run; deptry for dependencies that `pyproject.toml` declares and no code imports; `pip-audit` for dependencies with known vulnerabilities |
| Lua | Nothing: `luac -p` and LuaJIT's compiler check syntax only. The exception is Lua 5.5: after a `global` declaration, an undeclared name, such as a misspelled global, is a compile error. | luacheck's warnings 211 (unused local variable), 212 (unused argument), 213 (unused loop variable), 311 (a value assigned to a local is never used), 511 (unreachable code), and 111 and 113 (setting and reading an undefined global). lua-language-server's `unused` diagnostics, such as `unused-local`, `unused-function`, and `unreachable-code`. selene's `unused_variable`. Each checks one file at a time, so finding a module or a public function that no other file uses takes a search |
| C and C++ | GCC with `-Wall`: unused local variables, variables set but never read, and unused `static` functions and variables, including those in an anonymous namespace; in C, also unused `static const` variables. `-Wextra` adds unused parameters. GCC accepts `-Wunreachable-code` but reports nothing with it. It never reports an unused function or variable that another file could link to, an unused private member, an unused `inline` function or template, or an unused `#include`. A template that nothing instantiates is never checked against a real type, so it can call a member that doesn't exist and still compile. | Unused private fields: Clang's `-Wunused-private-field`, which its `-Wall` turns on. Unreachable code: Clang's `-Wunreachable-code`, which neither `-Wall` nor `-Wextra` turns on. Unused `#include`s: clang-tidy's `misc-include-cleaner`, or include-what-you-use. Functions that nothing calls: cppcheck's `unusedFunction` check (`--enable=unusedFunction`), which needs the whole program in one run, and a `--cppcheck-build-dir` with `-j`; or a link at `-O0` with `-ffunction-sections -Wl,--gc-sections -Wl,--print-gc-sections`, which lists each function the GNU linker drops; at higher levels the list also holds functions that were inlined everywhere they are called. For bugs: the **Sanitizer builds**; clang-tidy's `bugprone-*` checks and the Clang Static Analyzer (`clang-analyzer-*`); GCC's `-fanalyzer`, which GCC 13's manual calls suitable only for C; cppcheck; and Valgrind's Memcheck |
| PHP | Nothing: `php -l` checks syntax only, and PHP never reports an unused variable, function, or class | PHPStan, from level 4: unused private properties, methods, and constants, checked one class at a time and not for private members declared in a trait; code after a `return` or `throw`; and conditions that are always true or always false. Psalm's `findUnusedCode`, on by default since Psalm 6, which reports unused classes, public methods, properties, parameters, and variables across the project, and code that only other unused code uses. The PHPStan extension shipmonk/dead-code-detector, for unused methods, constants, and properties of any visibility, which knows the entry points of Symfony, Laravel, PHPUnit, Doctrine, and Twig, but not unused classes. composer-unused for packages in `require` that no code uses, and composer-require-checker for packages and extensions that the code uses without requiring them. For bugs: the **Static analysis** at its highest level, with phpstan-strict-rules for loose comparisons; `composer audit` for dependencies with known vulnerabilities |
| Go | Unused imports and unused local variables, as compile errors, but nothing about unused functions, parameters, package-level variables, or struct fields. `go vet`'s `unreachable` check reports code after a `return` | staticcheck's U1000, which golangci-lint runs as `unused`, for unused unexported functions, types, methods, fields, and constants; it treats every exported name as used, even in a `main` package. `deadcode` (`golang.org/x/tools/cmd/deadcode`), which finds functions that no `main` package can reach, for one OS, architecture, and set of build tags at a time; run `deadcode -test ./...` on a library, so its tests count as the starting points. `unparam` for unused parameters and results, and `ineffassign` for values assigned and never read. `go mod tidy` removes requirements that no package imports. For bugs: `go vet ./...`, of which `go test` runs only part; staticcheck's `SA` checks; `errcheck` for errors that nothing checks; the race detector (`go test -race ./...`); fuzz tests (`go test -fuzz`); and `govulncheck ./...` for dependencies with known vulnerabilities |
| C# | Warnings for unused code that no other assembly can see: CS0168 (a variable declared and never used), CS0219 (a variable given a constant that is never read), CS0169, CS0414, and CS0649 (a private or internal field never used, never read, or never assigned), CS0067 (an event never used), CS8321 (a local function never called), and CS0162 (unreachable code). Nothing about unused private methods, unused parameters, or anything another assembly can see | IDE0051 (unused private members), IDE0052 (private members written but never read), IDE0060 (unused parameters), and IDE0005 (unneeded `using` directives), which run in a command-line build only with `EnforceCodeStyleInBuild` and a severity set in `.editorconfig`; IDE0005 also needs `GenerateDocumentationFile`. JetBrains InspectCode (`jb inspectcode`, free), whose solution-wide analysis (`--swea`) finds public members that nothing in the solution uses. NuGet's NU1510 warning for package references that the target framework already provides. For bugs: nullable warnings as errors, the .NET SDK's analyzers at a stricter `AnalysisMode`, and `dotnet list package --vulnerable --include-transitive` |
| Ruby | Nothing by default. With `-w`, as in `ruby -wc <file>`, which checks a file without running it: unused local variables ("assigned but unused variable") and code after a `return` ("statement not reached"). Nothing about unused methods, constants, classes, or arguments | RuboCop's `Lint/UselessAssignment`, `Lint/UnreachableCode`, `Lint/UnusedMethodArgument`, and `Lint/UnusedBlockArgument`. debride for methods that nothing calls, which its README says can't be complete for a dynamic language, with `--rails` for Rails' conventions. For bugs: RuboCop's `Lint` cops, the **Type checking**, Brakeman for Rails apps, and `bundle-audit check --update` for gems with known vulnerabilities |
| Perl | `perl -wc <file>` checks syntax without running the program, though it does run every `BEGIN` block and `use` statement. With warnings on, it reports a package variable named only once ("used only once: possible typo"), `=` in a condition ("Found = in conditional"), and a constant in void context. Nothing about unused `my` variables, unused subs, or code after a `return` | Perl::Critic's `Variables::ProhibitUnusedVariables`; `Subroutines::ProhibitUnusedPrivateSubroutines`, which reports a sub named with a leading underscore that nothing in its file calls; and `ControlStructures::ProhibitUnreachableCode`, at severities 3, 3, and 4, below `perlcritic`'s default of 5, so run `perlcritic --severity 3`. Devel::Cover (`cover -test`) shows the subs and branches that the tests never run, which points to dead code without proving it. For bugs: Perl::Critic at a lower severity, the tests with warnings on, and CPAN::Audit (`cpan-audit deps .`), which checks the `cpanfile` or Carton's `cpanfile.snapshot` for dependencies with known vulnerabilities |

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in development →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.