find_dead_code

Roc

It also imports Item, Paths, Split, Words from the C splitter.

cookbook/c/find_dead_code/find_dead_code.roc, 165 lines

## find_dead_code, in Roc on Shale's platform (roc_platform/README.md): the
## functions and generators in Shale's C that no program reaches, from the
## splitter the C recipes share (cookbook/c/items/, a package). Its
## launcher, cookbook/c/find_dead_code.shale, is how it is run, and its
## header says the arguments and the rules. check_goldens.shale, beside
## this, holds its output on the plants to its goldens, line for line.
##
##   shale cookbook:c/find_dead_code.shale dir=c/host
##   shale cookbook:c/find_dead_code.shale self_test=1
##
## The effects: `Shale.arg!` for the arguments, `Shale.glob!` for the files,
## `Shale.read!` for each one's text, and `Shale.print!` and `Shale.fail!`
## for the verdict. Graph, beside this, finds what no program reaches;
## SelfTest holds it to the plants.
## budget: steps=200000000 arena_bytes=2000000000 roc_cpu_ms=600000
app [main!] {
	items: "../items/main.roc",
	pf: platform "../../../roc_platform/platform/main.roc",
}

import pf.Shale
import items.Item
import items.Paths
import items.Split
import items.Words
import Graph
import SelfTest

main! : {} => {}
main! = |{}| {
	if integer_or_stop!("self_test", Shale.arg!("self_test", "0")) == 1 {
		SelfTest.run!(find!)
	} else {
		folder = Shale.arg!("dir", "c")
		found = find!(folder)
		for each in found.findings {
			Shale.print!(Graph.finding_line(each))
		}
		for line in summary(folder, found) {
			Shale.print!(line)
		}
	}
}

## A value given as `name=`, which must be an integer, as Shale's `arg` reads
## one whose default is.
integer_or_stop! : Str, Str => I64
integer_or_stop! = |name, given|
	match I64.from_str(given) {
		Ok(value) => value
		Err(_) => {
			Shale.fail!("find_dead_code: ${name}=${given} is not an integer")
			0
		}
	}

## What was found under a folder: the findings, and how many items were
## nodes.
Found : { findings : List(Graph.Finding), nodes : U64 }

## The findings over the folder.
find! : Str => Found
find! = |folder| {
	nodes = read_nodes!(folder)
	{ findings: Graph.findings(nodes), nodes: nodes.len() }
}

## The summary: the counts by rule, then by folder and rule.
summary : Str, Found -> List(Str)
summary = |folder, found| {
	rules = found.findings.fold(Dict.empty(), |counts, each| counted(counts, each.rule))
	folders = found.findings.fold(Dict.empty(), |counts, each| counted(counts, "${folder_of(each.path)} ${each.rule}"))
	parts = sorted_counts(rules).map(|(rule, count)| "${count.to_str()} ${rule}")
	counts = "${found.findings.len().to_str()} findings: ${Str.join_with(parts, ", ")}"
	head = "find_dead_code: ${found.nodes.to_str()} items under ${folder}; ${counts}"
	sorted_counts(folders).map(|(key, count)| "  ${key}: ${count.to_str()}").prepend(head)
}

## The counts with one more of `key`.
counted : Dict(Str, U64), Str -> Dict(Str, U64)
counted = |counts, key| counts.insert(key, (counts.get(key) ?? 0) + 1)

## The counts, by key in the order of their bytes.
sorted_counts : Dict(Str, U64) -> List((Str, U64))
sorted_counts = |counts| counts.to_list().sort_with(|(x, _), (y, _)| Words.byte_order(x, y))

## The folder a path is in, as Shale's `dirname` gives it: up to its last
## `/`, or "" when it has none.
folder_of : Str -> Str
folder_of = |path| {
	bytes = path.to_utf8()
	match bytes.find_last_index(|byte| byte == '/') {
		Ok(slash) => Str.from_utf8_lossy(bytes.take_first(slash))
		Err(_) => ""
	}
}

## The kinds of item that are nodes: each names others, or is named. A type
## is one, since a generator's type may be named only in a struct's field.
node_kinds : List(Item.Kind)
node_kinds = [Function, Test, TestList, Data, Macro, Generator, Struct, Union, Enum, Typedef]

## The kinds whose words are the whole item's text, not a body's uses.
whole_kinds : List(Item.Kind)
whole_kinds = [Data, Macro, Generator, Struct, Union, Enum, Typedef]

## The tree's nodes, one for each item of a node's kind, in file order.
read_nodes! : Str => List(Graph.Node)
read_nodes! = |folder| {
	var $nodes = []
	for path in c_files_under!(folder) {
		text = read_text!(path)
		lines = Split.lines(text)
		test = Paths.is_test_path(folder, path)
		for item in split_or_stop!(path, text) {
			if node_kinds.contains(item.kind) {
				words =
					if whole_kinds.contains(item.kind) {
						Words.uses(Split.masked_text(lines, { first: item.first, last: item.last }))
					} else {
						item.uses
					}
				node = { path, line: item.first, kind: item.kind, name: item.name, test, words, macro: item.macro, makes: item.makes }
				$nodes = $nodes.append(node)
			}
		}
	}
	$nodes
}

## The file's text. A file the glob named and the read finds gone stops the
## run.
read_text! : Str => Str
read_text! = |path|
	match Shale.read!(path) {
		Found(text) => text
		Missing => {
			Shale.fail!("find_dead_code: ${path} went missing during the walk")
			""
		}
	}

## The file's items, each body's uses read, or the run stopped with the line
## the dialect does not account for.
split_or_stop! : Str, Str => List(Item)
split_or_stop! = |path, text|
	match Split.items({ path, text, uses: Bool.True }) {
		Ok(items) => items
		Err(why) => {
			Shale.fail!(why)
			[]
		}
	}

## The C files under the folder, sorted, any folder named `out` (c/out, the
## build's output) left out. A folder that is not there stops the run, in
## the words of the Shale original's walk: a check that can't run fails.
c_files_under! : Str => List(Str)
c_files_under! = |folder| {
	if Shale.list!(folder) == Missing {
		Shale.fail!("`walk(\"${folder}\")`: not found (FileNotFound)")
	}
	paths = Shale.glob!("${folder}/**/*.c").concat(Shale.glob!("${folder}/**/*.h"))
	paths.keep_if(|path| !(Paths.is_in_out_folder(folder, path))).sort_with(Words.byte_order)
}

cookbook/c/find_dead_code/Graph.roc, 251 lines

## The tree's names as a graph, and what no program reaches. Every
## function, test, test list, data item, macro, generator and type is a
## node; its edges are the nodes its words name. A word resolves to its own
## file's node of that name when the file has one, else to every node of
## that name in the tree, never to the node itself. A generator answers to
## its type's name and to each function its macro makes (`Ints`,
## `Ints_make`, `Ints_push`). The roots are the programs: production's each
## `main` outside the tests, the tests' each test, test list and `main` of
## theirs.
import items.Item
import items.Words

Graph := [].{

	## A node: where its item is, its kind and name, whether its file is the
	## tests', the words it names, and a generator's macro or a macro's own
	## functions (`make`, `push`).
	Node : {
		path : Str,
		line : U64,
		kind : Item.Kind,
		name : Str,
		test : Bool,
		words : List(Str),
		macro : Str,
		makes : List(Str),
	}

	## A finding: where it is, its rule (`dead` or `test_only`) and its text.
	Finding : { path : Str, line : U64, rule : Str, text : Str }

	## The findings over the nodes, sorted by place: each function (not a
	## `main`) and generator no program reaches, `dead`, and each outside
	## the tests' files that only the tests reach, `test_only`.
	findings : List(Graph.Node) -> List(Graph.Finding)
	findings = |nodes| {
		edges = edges_of(nodes, index_of(nodes))
		roots = roots_of(nodes)
		in_production = reached(edges, roots.production)
		in_tests = reached(edges, roots.tests)
		users = users_of(edges)
		var $found = []
		$at : U64
		var $at = 0
		for node in nodes {
			is_judged = (node.kind == Function and node.name != "main") or node.kind == Generator
			rule =
				if !(is_judged) or is_marked(in_production, $at) {
					""
				} else if is_marked(in_tests, $at) {
					if node.test {
						""
					} else {
						"test_only"
					}
				} else {
					"dead"
				}
			if rule != "" {
				generated =
					if node.kind == Generator {
						" (a ${node.macro} generator)"
					} else {
						""
					}
				named_by =
					match users.get($at) {
						Ok(who) if rule == "dead" => " (named only by unreached code: ${user_names(nodes, who)})"
						_ => ""
					}
				$found = $found.append({ path: node.path, line: node.line, rule, text: "${node.name}${generated}${named_by}" })
			}
			$at = $at + 1
		}
		$found.sort_with(place_order)
	}

	## A finding's line: `path:line: rule: text`.
	finding_line : Graph.Finding -> Str
	finding_line = |found| "${found.path}:${found.line.to_str()}: ${found.rule}: ${found.text}"
}

## The names to their nodes, each node's place counted from 0: `by_name`
## every node of a name, `by_file` a file's own node of it (the last, when
## the file has two).
Index : { by_name : Dict(Str, List(U64)), by_file : Dict((Str, Str), U64) }

## The names each node answers to, indexed: its own, and a generator's
## functions. A test list answers to none: its name is its macro's
## (`TEST_MAIN`), and a list is a root.
index_of : List(Graph.Node) -> Index
index_of = |nodes| {
	makes = nodes.fold(
		Dict.empty(),
		|so_far, node|
			if node.kind == Macro {
				so_far.insert(node.name, node.makes)
			} else {
				so_far
			},
	)
	var $by_name = Dict.empty()
	var $by_file = Dict.empty()
	$at : U64
	var $at = 0
	for node in nodes {
		if node.name != "" and node.kind != TestList {
			made =
				if node.kind == Generator {
					(makes.get(node.macro) ?? []).map(|suffix| "${node.name}_${suffix}")
				} else {
					[]
				}
			for name in made.prepend(node.name) {
				$by_name = $by_name.insert(name, ($by_name.get(name) ?? []).append($at))
				$by_file = $by_file.insert((node.path, name), $at)
			}
		}
		$at = $at + 1
	}
	{ by_name: $by_name, by_file: $by_file }
}

## Each node's edges, the nodes its words resolve to, in its words' order.
edges_of : List(Graph.Node), Index -> List(List(U64))
edges_of = |nodes, index|
	nodes.map_with_index(|node, at| node.words.fold([], |out, word| out.concat(resolved(index, { node, at, word }))))

## The nodes a word of the node at `at` resolves to: its file's own of that
## name, else every one of it, never the node itself.
resolved : Index, { node : Graph.Node, at : U64, word : Str } -> List(U64)
resolved = |index, { node, at, word }| {
	named =
		match index.by_file.get((node.path, word)) {
			Ok(own) => [own]
			Err(_) => index.by_name.get(word) ?? []
		}
	named.keep_if(|target| target != at)
}

## The roots: production's, each `main` outside the tests; the tests', each
## test, test list and `main` of theirs.
roots_of : List(Graph.Node) -> { production : List(U64), tests : List(U64) }
roots_of = |nodes| {
	var $production = []
	var $tests = []
	$at : U64
	var $at = 0
	for node in nodes {
		if node.kind == Function and node.name == "main" {
			if node.test {
				$tests = $tests.append($at)
			} else {
				$production = $production.append($at)
			}
		} else if node.kind == Test or node.kind == TestList {
			$tests = $tests.append($at)
		}
		$at = $at + 1
	}
	{ production: $production, tests: $tests }
}

## Which nodes the roots reach, a mark a node by its place.
reached : List(List(U64)), List(U64) -> List(Bool)
reached = |edges, roots| {
	var $marks = List.repeat(Bool.False, edges.len())
	var $work = []
	for root in roots {
		if !(is_marked($marks, root)) {
			$marks = marked($marks, root)
			$work = $work.append(root)
		}
	}
	$next : U64
	var $next = 0
	while $next < $work.len() {
		at = $work.get($next) ?? 0
		$next = $next + 1
		for target in edges.get(at) ?? [] {
			if !(is_marked($marks, target)) {
				$marks = marked($marks, target)
				$work = $work.append(target)
			}
		}
	}
	$marks
}

is_marked : List(Bool), U64 -> Bool
is_marked = |marks, at| marks.get(at) ?? Bool.False

marked : List(Bool), U64 -> List(Bool)
marked = |marks, at|
	match marks.set(at, Bool.True) {
		Ok(now) => now
		Err(_) => crash "find_dead_code: an edge past the last node"
	}

## Who names each node: a node's place to the places of the nodes whose
## edges reach it, once for each edge.
users_of : List(List(U64)) -> Dict(U64, List(U64))
users_of = |edges| {
	var $users = Dict.empty()
	$at : U64
	var $at = 0
	for out in edges {
		for target in out {
			$users = $users.insert(target, ($users.get(target) ?? []).append($at))
		}
		$at = $at + 1
	}
	$users
}

## The names of the nodes at the places, sorted, each once, joined by `, `.
user_names : List(Graph.Node), List(U64) -> Str
user_names = |nodes, places| {
	names = places
		.map(|place| (nodes.get(place) ?? no_node).name)
		.sort_with(Words.byte_order)
	once = names.fold(
		[],
		|kept, name|
			if kept.last() == Ok(name) {
				kept
			} else {
				kept.append(name)
			},
	)
	Str.join_with(once, ", ")
}

## The node a place past the last would be, which no edge reaches.
no_node : Graph.Node
no_node = { path: "", line: 0, kind: Function, name: "", test: Bool.False, words: [], macro: "", makes: [] }

## Findings by path, in the order of their bytes, then by line.
place_order : Graph.Finding, Graph.Finding -> [Before, Same, After]
place_order = |x, y|
	match Words.byte_order(x.path, y.path) {
		Same =>
			if x.line < y.line {
				Before
			} else if x.line > y.line {
				After
			} else {
				Same
			}
		other => other
	}

cookbook/c/find_dead_code/SelfTest.roc, 45 lines

## find_dead_code's self-test: the recipe run over
## cookbook/c/plants/find_dead_code/ and held to the plants' own list of
## findings, exactly: each way to be used (a call, a pointer in a table, a
## macro, a generator's function or its type) and each near miss (a comment,
## a string, a member, a prototype, recursion, a macro nobody uses, a
## same-named helper in another test file).
import pf.Shale
import Graph

SelfTest := [].{

	## The check, a stop when it fails, then the PASS line. `find!` is the
	## recipe's own, the findings over a folder.
	run! : (Str => { findings : List(Graph.Finding), nodes : U64 }) => {}
	run! = |find!| {
		got = joined(find!(plants).findings.map(Graph.finding_line))
		want = [
			"lib.c:6: dead: Chars (a VEC_DEFINE generator)",
			"lib.c:18: dead: lib_proto_only",
			"lib.c:43: dead: lib_in_unused_macro (named only by unreached code: LIB_UNUSED_CALL)",
			"lib.c:50: dead: lib_recursive",
			"lib.c:56: dead: lib_by_dead (named only by unreached code: lib_recursive)",
			"lib.c:61: dead: lib_in_comment",
			"lib.c:66: dead: lib_member",
			"lib.c:71: test_only: lib_tested",
			"lib.h:11: dead: lib_header_dead",
			"lib.h:14: test_only: lib_header_tested",
			"test.h:14: dead: test_unused_kit",
			"tests/test_lib.c:10: dead: test_lib_stray",
			"tests/test_lib.c:16: dead: pick",
		]
		wanted = joined(want.map(|line| "${plants}/${line}"))
		if got != wanted {
			Shale.fail!("find_dead_code self-test: the plants' findings are\n${got}\nthey should be\n${wanted}")
		}
		Shale.print!("PASS find_dead_code self-test: ${want.len().to_str()} findings over the plants, exactly, and each near miss left alone")
	}
}

## Where the plants are.
plants : Str
plants = "cookbook/c/plants/find_dead_code"

joined : List(Str) -> Str
joined = |lines| Str.join_with(lines, "\n")

Shale original

cookbook/c/find_dead_code.shale, 277 lines, at 616dab12

The libraries it loads: cookbook/c/items.shale (503 lines).

-- Finds Shale's C that no program reaches, from cookbook/c/items.shale's
-- splitter. GCC's unused-function warning passes by every `static inline`
-- function (each header's and those of .c files a unit may not call), and a
-- function some other dead function calls is no warning at all, so this reads
-- the whole tree's names instead:
--
--   dead       a function, or a generator (`VEC_DEFINE(Name, T)`), that no
--              program reaches: no item names it, or only items that are
--              themselves unreached do (`named only by unreached code: ...`);
--   test_only  a function outside the tests that only tests reach.
--
-- One line a finding, `path:line: dead: name` or `path:line: test_only:
-- name`, then the counts by rule and by folder.
--
--   shale cookbook:c/find_dead_code.shale            over c/
--   shale cookbook:c/find_dead_code.shale dir=c/host
--   shale cookbook:c/find_dead_code.shale self_test=1
--
-- How it reads a use. Every function, test, test list, data item, macro and
-- generator is a node; its edges are the identifiers its masked text names
-- (items.shale's `uses` for a body, the whole item's words for data, a
-- macro and a generator), so a comment, a string and a member after `.` or
-- `->` are never a use, a prototype is none, and a name taken without a
-- call (a function pointer in a table) is one. A name resolves to its own
-- file's item of that name when the file has one (two test files may each
-- have a `pick`), else to every item of that name in the tree. A generator
-- answers to its type's name and to each function its macro `makes`
-- (`VEC_DEFINE(Ints, int)` to `Ints`, `Ints_make`, `Ints_push`), so a use of
-- `Ints_push` reaches it. A macro is reached by being named, and reaches the
-- names in its body.
--
-- The programs are the roots: each `int main(` outside a `tests` folder
-- (c/shale.c, c/shale_gate.c) is production's; each test, test list and
-- `main` under one is the tests'. A function of the tests' own files (under
-- a `tests` folder, or a file named `test*`, as c/foundation/test.h, the
-- runner) that the tests reach is a test's helper, never a finding.
--
-- What it can't see: a name made by `##` outside a generator (only
-- test.h's `TEST` and `TEST_PART` do that, and tests are roots), and a
-- use that a preprocessor branch compiles out: every branch counts.
--
-- `self_test=1` runs it over cookbook/c/plants/find_dead_code/ and holds the
-- findings to the plants' own list, exactly: each way to be used (a call, a
-- pointer in a table, a macro, a generator's function or its type) and each
-- near miss (a comment, a string, a member, a prototype, recursion, a macro
-- nobody uses, a same-named helper in another test file).
--
-- budget: steps=400000000 arena_bytes=1000000000 kept_bytes=268435456

use("./items.shale")

const PLANTS = "cookbook/c/plants/find_dead_code"

-- The C files under `dir`, sorted, c/out (the build's output) left out.
function c_files_under(dir)
  local files = {}
  for e in walk_all(dir, {kind = "file", skip = "out"}) do
    if ends_with(e.path, ".c") or ends_with(e.path, ".h") then push(files, e.path) end
  end
  sort(files)
  return files
end

-- Whether `p`, below `dir`, is the tests': in a `tests` folder, or a file
-- whose name starts with `test` (c/foundation/test.h, the tests' runner).
function is_test_path(dir, p)
  local rel = sub(p, #dir + 2)
  return starts_with(rel, "tests/") or contains(rel, "/tests/") or starts_with(basename(p), "test")
end

-- The kinds that are nodes: each names others, or is named. A type is one,
-- since a generator's type may be named only in a struct's field.
const NODE_KINDS = {"function", "test", "test_list", "data", "macro", "generator", "struct", "union", "enum", "typedef"}

-- The kinds whose words are the whole item's text, not a body's `uses`.
const WHOLE_KINDS = {"data", "macro", "generator", "struct", "union", "enum", "typedef"}

-- The tree's nodes, one for each item that names others or is named:
-- `{path, line, kind, name, test, words, macro}`, `test` whether its file is
-- under a `tests` folder.
function read_nodes(dir)
  local nodes = {}
  for p in c_files_under(dir) do
    local all = lines(read(p))
    local test = is_test_path(dir, p)
    for it in c_items(p, {uses = true}) do
      local k = it.kind
      if has_item(NODE_KINDS, k) then
        local words = it.uses
        if has_item(WHOLE_KINDS, k) then words = c_words_used(c_masked_text(all, it.first, it.last)) end
        push(nodes, {path = p, line = it.first, kind = k, name = it.name, test = test, words = words, macro = it.macro, makes = it.makes})
      end
    end
    yield()
  end
  return nodes
end

-- The names each node answers to: its own, and a generator's functions. A
-- test list answers to none: its name is its macro's (`TEST_MAIN`), and a
-- list is a root.
-- Gives `{by_name, by_file}`: a name to its nodes' indexes, and
-- `path|name` to the file's own node.
function index_nodes(nodes)
  local makes = {}
  for n in nodes do
    if n.kind == "macro" then makes[n.name] = n.makes end
  end
  local by_name = {}
  local by_file = {}
  local i = 0
  for n in nodes do
    i = i + 1
    if n.name ~= "" and n.kind ~= "test_list" then
      local names = {n.name}
      if n.kind == "generator" then
        for m in get(makes, n.macro, {}) do push(names, n.name .. "_" .. m) end
      end
      for nm in names do
        push_at(by_name, nm, i)
        by_file[n.path .. "|" .. nm] = i
      end
    end
  end
  return {by_name = by_name, by_file = by_file}
end

-- Each node's edges, the nodes its words resolve to (never itself).
function resolve_edges(nodes, index)
  local edges = {}
  local i = 0
  for n in nodes do
    i = i + 1
    local out = {}
    for w in n.words do
      local own = n.path .. "|" .. w
      if has_key(index.by_file, own) then
        if index.by_file[own] ~= i then push(out, index.by_file[own]) end
      else
        for t in get(index.by_name, w, {}) do
          if t ~= i then push(out, t) end
        end
      end
    end
    push(edges, out)
  end
  return edges
end

-- The nodes reached from `roots`, as a map of index strings.
function reach(edges, roots)
  local seen = {}
  local work = {}
  for r in roots do
    if not has_key(seen, "" .. r) then
      seen["" .. r] = true
      push(work, r)
    end
  end
  local next = 1
  while next <= #work do
    local at = work[next]
    next = next + 1
    for t in edges[at] do
      if not has_key(seen, "" .. t) then
        seen["" .. t] = true
        push(work, t)
      end
    end
  end
  return seen
end

-- The findings over `dir`, sorted by place: `{path, line, rule, name, text}`.
function find_dead(dir)
  local nodes = read_nodes(dir)
  local index = index_nodes(nodes)
  local edges = resolve_edges(nodes, index)
  local prod_roots = {}
  local test_roots = {}
  local i = 0
  for n in nodes do
    i = i + 1
    if n.kind == "function" and n.name == "main" then
      if n.test then push(test_roots, i) else push(prod_roots, i) end
    elseif n.kind == "test" or n.kind == "test_list" then
      push(test_roots, i)
    end
  end
  local prod = reach(edges, prod_roots)
  local tested = reach(edges, test_roots)
  -- Who names each node, for a dead one's line.
  local users = {}
  i = 0
  for out in edges do
    i = i + 1
    for t in out do push_at(users, "" .. t, i) end
  end
  local found = {}
  i = 0
  for n in nodes do
    i = i + 1
    local key = "" .. i
    if (n.kind == "function" and n.name ~= "main") or n.kind == "generator" then
      local rule = ""
      if has_key(prod, key) then
        rule = ""
      elseif has_key(tested, key) then
        if not n.test then rule = "test_only" end
      else
        rule = "dead"
      end
      if rule ~= "" then
        local text = n.name
        if n.kind == "generator" then text = text .. " (a " .. n.macro .. " generator)" end
        if rule == "dead" and has_key(users, key) then
          local who = {}
          for u in users[key] do push(who, nodes[u].name) end
          text = text .. " (named only by unreached code: " .. join(unique(sort(who)), ", ") .. ")"
        end
        push(found, {path = n.path, line = n.line, rule = rule, name = n.name, text = text})
      end
    end
  end
  sort(found, {"path", "line"})
  return {found = found, nodes = #nodes}
end

-- The findings' lines.
function finding_lines(found)
  local out = {}
  for f in found do push(out, f.path .. ":" .. f.line .. ": " .. f.rule .. ": " .. f.text) end
  return out
end

function self_test()
  local got = finding_lines(find_dead(PLANTS).found)
  local P = PLANTS .. "/"
  local want = {
    P .. "lib.c:6: dead: Chars (a VEC_DEFINE generator)",
    P .. "lib.c:18: dead: lib_proto_only",
    P .. "lib.c:43: dead: lib_in_unused_macro (named only by unreached code: LIB_UNUSED_CALL)",
    P .. "lib.c:50: dead: lib_recursive",
    P .. "lib.c:56: dead: lib_by_dead (named only by unreached code: lib_recursive)",
    P .. "lib.c:61: dead: lib_in_comment",
    P .. "lib.c:66: dead: lib_member",
    P .. "lib.c:71: test_only: lib_tested",
    P .. "lib.h:11: dead: lib_header_dead",
    P .. "lib.h:14: test_only: lib_header_tested",
    P .. "test.h:14: dead: test_unused_kit",
    P .. "tests/test_lib.c:10: dead: test_lib_stray",
    P .. "tests/test_lib.c:16: dead: pick",
  }
  local g = join(got, "\n")
  local w = join(want, "\n")
  if g ~= w then fail("find_dead_code self-test: the plants' findings are\n" .. g .. "\nthey should be\n" .. w) end
  print("PASS find_dead_code self-test: " .. #want .. " findings over the plants, exactly, and each near miss left alone")
  return nil
end

if arg("self_test", 0) == 1 then
  self_test()
else
  local dir = arg("dir", "c")
  local r = find_dead(dir)
  for l in finding_lines(r.found) do print(l) end
  local rules = {}
  local folders = {}
  for f in r.found do
    incr(rules, f.rule)
    incr(folders, dirname(f.path) .. " " .. f.rule)
  end
  local parts = {}
  for k in sort(keys(rules)) do push(parts, rules[k] .. " " .. k) end
  print("find_dead_code: " .. r.nodes .. " items under " .. dir .. "; " .. #r.found .. " findings: " .. join(parts, ", "))
  for k in sort(keys(folders)) do print("  " .. k .. ": " .. folders[k]) end
end