deadcode

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 6 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package deadcode reports definitions nothing in the index points at, and says how far each one can be trusted as actually unused.

Why this is graded rather than listed

"No caller in the index" and "no caller" are different facts, and a tool that prints the first as the second gets a function deleted that a framework was calling by name. A static index sees a minority of the ways code is reached: reflection, dependency injection, a route table, an interface, a template and a test runner all call things without a call expression the parser can bind.

So every row carries a Certainty and the reasons for it, and the rows that cannot be judged at all are counted and named instead of being dropped:

  • likely: unexported, in a language whose references the index binds, in a cleanly parsed file, with no unbound reference anywhere spelled like it, and its name occurring nowhere in the indexed code outside its own definition. Every ordinary explanation for a missing caller has been checked and ruled out. It can still be wrong (see Limits), and the report says so.
  • possible: something on that list could not be ruled out. The row names which, because "exported, so another module may import it" and "an unresolved call spelled like this exists" call for different checks.

Nothing here is ever `exact`. That word is reserved for facts a compiler proved, and absence of evidence is not one.

Entry points a framework calls

A function a framework invokes has no caller by construction: the router or the broker's client library reaches it through a table, not a call expression. The index records two such shapes, and neither is ever graded likely. A handler a route was BOUND to has an incoming edge from the endpoint and so is never a candidate at all. A definition spelled like a handler some route names and could not bind, and a definition that consumes an event topic, are demoted to possible with a reason of their own (ReasonRouteHandler, ReasonEventConsumer) and counted in EntryPoints.

Code only its tests reach

A definition whose every caller is in a test file is a second finding, kept apart from the first (see testonly.go). It is never likely: whether production code that only its tests keep alive should go is a judgement, not a fact. It is also off unless asked for, and reported in its own section with its own counts, so the default answer is the one it always was.

What is deliberately not reported

Tests, conventional entry points (main, init) and definitions in languages the index only parses are skipped: in each case an empty caller list is the expected state rather than a finding. Skipped is the count of them, so the denominator is visible.

Index

Constants

View Source
const (
	// DefaultLimit is how many candidates are returned unless asked otherwise.
	DefaultLimit = 50
	// DefaultScanBudget is how many unreferenced rows a scan examines.
	DefaultScanBudget = 200_000
)
View Source
const (
	// DefaultTestOnlyScanBudget is how many symbols the test-only pass
	// examines unless told otherwise.
	DefaultTestOnlyScanBudget = 2_000_000
)
View Source
const Limits = "A definition with no caller in the index is not proven unused. Reflection, dependency " +
	"injection, framework registration, templates, build scripts and code in other repositories all " +
	"reach code without a reference this index can bind. Search for the name and check the framework's " +
	"conventions before deleting anything listed here."

Limits is what a reader must know before acting on any row. Appended to every report's caveats by Find, so no caller can omit it.

View Source
const TestOnlyLimits = "A definition listed as reached only from tests HAS callers; every one the index bound " +
	"is in a test file. Direct callers only: a helper called by such a definition is not listed, because " +
	"its own caller is not a test. A use the index could not bind is not counted, tests that live in the " +
	"same file as the code they test are not seen as tests, and code written to support tests is listed " +
	"alongside code that lost its last production caller, because nothing in an index tells them apart. " +
	"Whether to delete any of it is a judgement this report does not make."

TestOnlyLimits is what a reader must know before acting on a test-only row. Find appends it to the report's caveats whenever the pass ran.

Variables

This section is empty.

Functions

This section is empty.

Types

type Candidate

type Candidate struct {
	Name      string    `json:"name"`
	FQN       string    `json:"fqn,omitempty"`
	Kind      string    `json:"kind"`
	Path      string    `json:"path"`
	Line      int       `json:"line"`
	EndLine   int       `json:"end_line,omitempty"`
	Language  string    `json:"language,omitempty"`
	Certainty Certainty `json:"certainty"`
	Reasons   []Reason  `json:"reasons,omitempty"`

	// TestReferences is set only on a test-only row: how many relationships
	// point at the definition, every one of them from a test file. It counts
	// references, so one test calling the definition twice counts twice.
	TestReferences int `json:"test_references,omitempty"`
}

Candidate is one definition with no incoming relationship, or, in the test-only section, one whose incoming relationships all start in test files.

func (Candidate) Lines

func (c Candidate) Lines() int

Lines is the candidate's length in lines, for ranking: a dead 200-line function is worth more attention than a dead one-line accessor.

type Certainty

type Certainty string

Certainty grades one candidate. It is not a model.Confidence: that type describes how an EDGE was established, and a dead-code candidate is the absence of one.

const (
	// CertaintyLikely means every ordinary reason for a missing caller was
	// checked and none applies.
	CertaintyLikely Certainty = "likely"
	// CertaintyPossible means at least one such reason could not be ruled out.
	CertaintyPossible Certainty = "possible"
)

type Options

type Options struct {
	// Limit is the most candidates to return. Zero means DefaultLimit.
	Limit int

	// MinCertainty drops rows below it. Empty means both tiers.
	MinCertainty Certainty

	// PathPrefix restricts the scan to files under it. Empty means everywhere.
	PathPrefix string

	// IncludeExported keeps exported definitions. Off by default: in a library
	// every public function is "unreferenced", and a report that leads with
	// the whole public API is a report nobody reads twice.
	IncludeExported bool

	// Judgeable reports whether the index binds cross-file references for a
	// language. Nil means every language is judged, which is only right in
	// tests; production callers pass the parser's tier table.
	Judgeable func(language string) bool

	// ScanBudget is the most unreferenced rows to examine. Zero means
	// DefaultScanBudget. It bounds the work when filters reject nearly
	// everything, so a narrow PathPrefix on a huge index still returns.
	ScanBudget int

	// TestOnly, when set, also reports definitions whose every caller is in a
	// test file, reading callers through it. Nil, the default, leaves that out:
	// it is a second pass over every referenced definition, and its rows are a
	// judgement call the ordinary question did not ask for. Production callers
	// pass the registry.
	TestOnly TestOnlySource

	// TestOnlyScanBudget is the most symbols the test-only pass examines.
	// Zero means DefaultTestOnlyScanBudget. It is separate from ScanBudget
	// because the two passes read different things: that one counts
	// unreferenced rows, this one counts every symbol it walks past.
	TestOnlyScanBudget int
}

Options bounds and filters a scan.

type Reason

type Reason string

Reason names why a candidate is only possible.

const (
	ReasonExported      Reason = "exported"
	ReasonExportUnknown Reason = "export_status_unknown"
	ReasonNameUnbound   Reason = "unbound_reference_with_same_name"
	ReasonOverrides     Reason = "implements_or_extends"
	ReasonPartialParse  Reason = "file_partially_parsed"
	ReasonMentioned     Reason = "name_appears_elsewhere"

	// ReasonRouteHandler and ReasonEventConsumer mark an entry point a
	// framework calls. The definition has no caller in the index because its
	// caller is a router or a broker client, not because it is unused.
	ReasonRouteHandler  Reason = "route_handler"
	ReasonEventConsumer Reason = "event_consumer"

	// ReasonTestOnly marks the test-only finding: the definition HAS callers,
	// and every one the index bound is in a test file. A row carrying it is
	// never graded likely.
	ReasonTestOnly Reason = "only_reached_from_tests"
)

func Reasons

func Reasons() []Reason

Reasons lists every reason, in a stable order, for a legend.

func (Reason) Label

func (r Reason) Label() string

Label returns a few words for r, for a column that cannot hold a sentence.

func (Reason) Text

func (r Reason) Text() string

Text returns the sentence for r.

type Report

type Report struct {
	RunID      int64       `json:"run_id"`
	Candidates []Candidate `json:"candidates"`

	// Likely and Possible count every candidate found, not just the ones
	// returned, unless Truncated is set — in which case they count what was
	// examined before the scan stopped.
	Likely   int `json:"likely"`
	Possible int `json:"possible"`

	// TextChecked is how many candidates were also checked against the
	// indexed source text for a mention of their name. Every returned `likely`
	// row was. Likely and Possible above include rows graded from the graph
	// alone, so Likely is an upper bound on what a text check of everything
	// would leave.
	TextChecked int `json:"text_checked"`
	// LikelyUnchecked is how many candidates counted in Likely were NOT text
	// checked. Zero means Likely is exact with respect to the text check.
	LikelyUnchecked int `json:"likely_unchecked"`

	// Skipped counts unreferenced definitions left out because an empty caller
	// list is their normal state. SkippedUnjudged is the subset in languages
	// the index cannot bind references for; it is reported separately because
	// it is a coverage limit and the others are not.
	Skipped         int      `json:"skipped"`
	SkippedUnjudged int      `json:"skipped_unjudged_language"`
	UnjudgedLangs   []string `json:"unjudged_languages,omitempty"`

	// EntryPoints counts the candidates graded possible because a framework
	// may call them: a definition spelled like a handler a route names, or a
	// consumer of an event topic. They are included in Possible; this says
	// how many of those are there for that reason.
	EntryPoints int `json:"entry_points"`

	// TestOnly is the separate finding, present only when Options.TestOnly
	// asked for it. Nothing in it is counted in Likely or Possible above.
	TestOnly *TestOnlyReport `json:"test_only,omitempty"`

	// ExportUnknown counts candidates graded possible because the index cannot
	// tell whether they are exported (capability.ExportedKnown), in the
	// languages named by ExportUnknownLangs. Reported so a reader in a Java or
	// TypeScript repository knows why nothing is graded likely.
	ExportUnknown      int      `json:"export_status_unknown"`
	ExportUnknownLangs []string `json:"export_status_unknown_languages,omitempty"`

	Completeness capability.Completeness `json:"completeness"`
}

Report is the answer to "what looks unused?".

func Find

func Find(ctx context.Context, deps capability.Deps, src Source, runID int64, opts Options) (*Report, error)

Find scans runID for unreferenced definitions.

The candidates returned are the top Limit by certainty and then by size, so the first row is the one most worth a reader's minute. Because that order is not the scan order, the scan cannot stop at Limit rows; it keeps only the best Limit seen so far, which is what makes memory a function of Limit and not of how much dead code the repository holds.

type Source

type Source interface {
	UnreferencedSymbols(ctx context.Context, runID, afterID int64, limit int) ([]registry.UnreferencedSymbol, error)
	// UnboundRouteHandlers lists the handler names routes declare and no
	// definition was bound to. A definition spelled like one may be that
	// handler.
	UnboundRouteHandlers(ctx context.Context, runID int64) ([]string, error)
	// IdentifierMentions reports the lines, outside comments, on which name
	// occurs as a whole identifier. ok is false when the text index cannot
	// answer for this name, which must be read as "unknown", never "not
	// mentioned".
	IdentifierMentions(ctx context.Context, runID int64, name string) (mentions []registry.Mention, ok bool, err error)
}

Source is the read surface this package needs.

One paging query, one text lookup and one short list. The registry satisfies it; a test satisfies it with a slice. Declared here, at the consumer, so the storage layer does not grow an opinion about what counts as dead.

type TestOnlyReport

type TestOnlyReport struct {
	// Candidates are the rows returned: confirmed against the text first,
	// largest first, then the ones whose name also appears in code that is
	// not a test. Every row is `possible` and carries ReasonTestOnly.
	Candidates []Candidate `json:"candidates"`

	// Found counts every definition whose bound callers are all in test
	// files, not just the ones returned. It is what the graph says, so it is
	// an upper bound on what the text check would leave.
	Found int `json:"found"`

	// TextChecked is how many of Found were checked against the indexed text,
	// and NameElsewhere how many of those have their name in code that is not
	// a test. Every returned row was checked.
	TextChecked   int `json:"text_checked"`
	NameElsewhere int `json:"name_elsewhere"`

	// Skipped counts definitions that met the graph test and were left out
	// for the reasons the unreferenced scan leaves definitions out: exported
	// (unless asked for), named like an entry point, or in a language the
	// index does not bind references for. SkippedUnjudged is that last part.
	Skipped         int `json:"skipped"`
	SkippedUnjudged int `json:"skipped_unjudged_language"`

	// EntryPoints counts definitions left out because a framework calls them:
	// a route handler or an event consumer whose only CALL expressions are in
	// its tests is not kept alive by its tests.
	EntryPoints int `json:"entry_points"`

	// TestFiles is how many of the run's files count as test files. Zero
	// means the pass had nothing to look for, which is not the same as
	// finding nothing.
	TestFiles int `json:"test_files"`

	// SymbolsExamined is how many symbols the pass walked. Truncated reports
	// that it stopped at its budget with symbols still unread.
	SymbolsExamined int    `json:"symbols_examined"`
	Truncated       bool   `json:"truncated"`
	TruncatedReason string `json:"truncated_reason,omitempty"`
}

TestOnlyReport is the answer to "what does only test code reach?".

type TestOnlySource

type TestOnlySource interface {
	// FilePaths returns the path of every file in the run by file id. The
	// pass turns capability.IsTestPath into a set of ids with it.
	FilePaths(ctx context.Context, runID int64) (map[int64]string, error)
	// SymbolsReferencedOnlyFrom returns the definitions outside fileIDs whose
	// every incoming relationship starts inside fileIDs, examining at most
	// window symbols after afterID. An Examined of zero ends the scan.
	SymbolsReferencedOnlyFrom(ctx context.Context, runID, afterID int64, window int, fileIDs []int64) (registry.ConfinedPage, error)
}

TestOnlySource is the read surface the test-only pass adds to Source.

Separate from Source because it is needed only when the pass is asked for: a caller that never asks does not have to provide it, and a test of the ordinary scan does not have to fake it.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL