find_unused_imports

Roc

It also imports Finding, Imports, Text from the shared Roc library.

cookbook/roc/find_unused_imports/find_unused_imports.roc, 112 lines

## find_unused_imports, in Roc on Shale's platform (roc_platform/README.md):
## the import lines a Roc file never uses, since Roc doesn't warn of one. Its
## launcher, cookbook/roc/find_unused_imports.shale, is how it is run, and
## its header says the rule, `unused_import`. check_goldens.shale, beside
## this, holds its output on the plants to its goldens, line for line.
##
##   cd <repo> && shale cookbook:roc/find_unused_imports.shale glob=app/**/*.roc
##   shale cookbook:roc/find_unused_imports.shale self_test=1
##
## The arguments: `glob` (`**/*.roc`; several, separated by commas) and
## `self_test` (`self_test=1` runs the plants, each through the launcher).
##
## This root globs the files, has Roc's parser read them (`Shale.roc_tree!`)
## and each one's text (`Shale.read!`), and prints the verdict
## (`Shale.print!`, `Shale.fail!`). SelfTest, beside it, is the plants' run.
## The rule is the cookbook's Roc library's Imports (cookbook/roc/lib/), its
## one home, with Tree, Text and Finding.
## budget: steps=800000000 arena_bytes=2000000000 output_bytes=4000000 programs=100
app [main!] { lib: "../lib/main.roc", pf: platform "../../../roc_platform/platform/main.roc" }

import pf.Shale
import lib.Finding
import lib.Imports
import lib.Text
import SelfTest

main! : {} => {}
main! = |{}| {
	if Shale.arg!("self_test", "") == "1" {
		SelfTest.run!({})
	} else {
		run_check!({})
	}
}

## The check over the glob's files: the verdict printed, then a stop when a
## file didn't parse, or when there are findings, the summary the last line
## a caller reads.
run_check! : {} => {}
run_check! = |{}| {
	paths = list_files!(Shale.arg!("glob", "**/*.roc"))
	var $report = []
	var $refused = []
	for file in Shale.roc_tree!(paths) {
		if file.err == "" {
			source_lines = read_text!(file.path).split_on("\n")
			for unused in Imports.unused_imports(file.nodes, source_lines) {
				what = "${unused.label} is imported and never used: delete the line"
				$report = $report.append({ path: file.path, line: unused.line, check: "unused_import", what })
			}
		} else if file.err.starts_with(file.path) {
			$refused = $refused.append(file.err)
		} else {
			$refused = $refused.append("${file.path}: ${file.err}")
		}
	}
	found = $report.sort_with(Finding.order).map(Finding.line_of)
	counts = "${paths.len().to_str()} files; unused_import ${found.len().to_str()}"
	summary = "find_unused_imports (Roc): ${counts}"
	print_findings!(summary, found)
	if !($refused.is_empty()) {
		for refusal in $refused {
			Shale.print!("refused: ${refusal}")
		}
		refused_count = $refused.len().to_str()
		refusals = "roc-ast refused ${refused_count} files (named above)"
		why = "which have no tree to judge; every other file was judged"
		Shale.fail!("find_unused_imports: ${refusals}, ${why}")
	}
	if !(found.is_empty()) {
		Shale.fail!(summary)
	}
}

## The files of each comma-separated glob, in the order given, a file twice
## when two globs name it.
list_files! : Str => List(Str)
list_files! = |patterns| {
	var $paths = []
	for pattern in patterns.split_on(",") {
		matching = Shale.glob!(Text.trim(pattern))
		$paths = $paths.concat(matching)
	}
	$paths
}

## The file's text. A file the parser read 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_unused_imports: ${path} went missing during the check")
			""
		}
	}

# ── The verdict

## The summary, each finding, then the summary again (cookbook/findings.shale):
## the first copy survives a cut output, and a gate reads the last line.
print_findings! : Str, List(Str) => {}
print_findings! = |summary, finding_lines| {
	Shale.print!(summary)
	if !(finding_lines.is_empty()) {
		for line in finding_lines {
			Shale.print!(line)
		}
		Shale.print!(summary)
	}
}

cookbook/roc/find_unused_imports/SelfTest.roc, 151 lines

## The recipe's self-test: each plant under
## cookbook/roc/plants/find_unused_imports/ run through the launcher, held to
## its findings, its exit and what it says.
import pf.Shale

SelfTest := [].{

	## Each row run as a child of its own, through the launcher; a run that
	## fires no `unused_import` anywhere fails too, since the check could be
	## blind.
	run! : {} => {}
	run! = |{}| {
		var $wrong = 0.U64
		for row in rows {
			pattern = "${plants}${row.plant}"
			command = ["shale", launcher, "glob=${pattern}"]
			result = Shale.run!({
				argv: command,
				keep: Whole(4000000),
				timeout_ms: 120000,
				want: "",
			})
			faults = find_faults!(row, result)
			if faults.is_empty() {
				Shale.print!("ok   ${pattern}")
			} else {
				Shale.print!("FAIL ${pattern}: ${Str.join_with(faults, "; ")}")
				$wrong = $wrong + 1
				Shale.print!(result.out)
			}
		}
		if !(rows.any(|row| row.findings > 0)) {
			Shale.print!("FAIL `unused_import` has no plant")
			$wrong = $wrong + 1
		}
		if $wrong > 0 {
			Shale.fail!("find_unused_imports self_test: ${$wrong.to_str()} wrong")
		}
		row_count = rows.len().to_str()
		proof = "each plant gives its findings and a nonzero exit, each clean case none and exit 0"
		Shale.print!("find_unused_imports self_test: PASS (${row_count} rows: ${proof})")
	}
}

## The launcher, which the self-test runs each plant through.
launcher : Str
launcher = "cookbook:roc/find_unused_imports.shale"

plants : Str
plants = "cookbook:roc/plants/find_unused_imports/"

## A plant's run: its files below `plants`, the findings it must print, the
## literals its output must hold, and whether it must stop without a finding.
Row : {
	plant : Str,
	findings : U64,
	says : List(Str),
	stops : Bool,
}

## A plant with no finding to give.
quiet : Str -> Row
quiet = |plant| {
	plant,
	findings: 0,
	says: [],
	stops: Bool.False,
}

## A plant with one finding, and what it says.
fires_once : Str, Str -> Row
fires_once = |plant, saying| {
	plant,
	findings: 1,
	says: [saying],
	stops: Bool.False,
}

rows : List(Row)
rows = [
	fires_once("unused.roc", "unused.roc:3: unused_import: `game.Polygon` is imported"),
	fires_once("unused_alias.roc", "`game.Distance` as `D` is imported and never used"),
	fires_once("unused_exposing.roc", "`pf.Stdout` is imported"),
	fires_once("unused_file_import.roc", "the file import `page` is imported"),
	fires_once("unused_in_prose.roc", "`game.Polygon` is imported"),
	fires_once("unused_method_only.roc", "`game.Distance` is imported"),
	fires_once("unused_tag_namesake.roc", "`game.Other` is imported"),
	fires_once("unused_beside_hosted.roc", "unused_beside_hosted.roc:24: unused_import: `Http`"),
	{
		plant: "unused.roc,${plants}unused_alias.roc",
		findings: 2,
		says: [],
		stops: Bool.False,
	},
	quiet("quiet_qualified.roc"),
	quiet("quiet_annotation.roc"),
	quiet("quiet_expect.roc"),
	quiet("quiet_pattern_tag.roc"),
	quiet("quiet_tag.roc"),
	quiet("quiet_exposing.roc"),
	quiet("quiet_alias.roc"),
	quiet("quiet_interpolation.roc"),
	quiet("quiet_file_import.roc"),
	quiet("quiet_hosted.roc"),
	{
		plant: "broken/*.roc",
		findings: 0,
		says: ["refused: "],
		stops: Bool.True,
	},
]

## The last line of `out` that isn't one of Shale's `──` lines.
last_said : Str -> Str
last_said = |out|
	out.trim().split_on("\n").fold(
		"",
		|last, line|
			if line.starts_with("──") or line.trim() == "" {
				last
			} else {
				line
			},
	)

## What is wrong with one row's run.
find_faults! : Row, { code : I64, out : Str } => List(Str)
find_faults! = |row, result| {
	must_fail = row.stops or row.findings > 0
	var $faults = []
	if must_fail and result.code == 0 {
		$faults = $faults.append("it exited 0")
	}
	if !(must_fail) and result.code != 0 {
		$faults = $faults.append("it exited ${result.code.to_str()}")
	}
	found = Shale.re_lines!(result.out, "^[^ ]+:[0-9]+: unused_import: ").len()
	if found != row.findings {
		printed = "unused_import printed ${found.to_str()}"
		$faults = $faults.append("${printed}, not ${row.findings.to_str()}")
	}
	if !(row.stops) and !(last_said(result.out).contains(" files; ")) {
		$faults = $faults.append("its last line is no summary: ${last_said(result.out)}")
	}
	for literal in row.says {
		if !(result.out.contains(literal)) {
			$faults = $faults.append("its output lacks `${literal}`")
		}
	}
	$faults
}

Shale original

cookbook/roc/find_unused_imports.shale, 106 lines, at 8023162f

The libraries it loads: cookbook/findings.shale (21 lines), cookbook/roc/parsed.shale (34 lines), cookbook/roc/gate_recipe.shale (102 lines), cookbook/roc/imports.shale (104 lines).

-- This recipe finds import lines that the file never uses, since Roc doesn't
-- warn of one.
--
--   cd <repo> && shale <shale>/cookbook/roc/find_unused_imports.shale
--   shale cookbook:roc/find_unused_imports.shale self_test=1
--
-- The arguments:
--   glob       the files to check, `**/*.roc` by default; several globs may
--              be given, separated by commas;
--   self_test  with `self_test=1`, check the plants in
--              `cookbook/roc/plants/find_unused_imports/`.
--
-- The check:
--
--   unused_import  An `import` line whose name the file never refers to. The
--              name is the alias of `import pkg.Mod as M`, else the last part
--              of the module's path: `Mod` of `import pkg.Mod` and of
--              `import Mod`. A use is a value, tag or type whose first part
--              is that name: `Mod.name`, `Mod.Type`, `Mod.Tag(x)`, the
--              module's own type `Mod`, in an annotation, a pattern, an
--              expect or an interpolation alike. A name the line exposes
--              (`exposing [line!]`) and the file uses is a use of the line.
--              A file import, `import "page.html" as page : Str`, is used
--              when the file refers to `page`. An entry of a platform
--              header's `hosted { ... }` block uses the module it names
--              (`"sym": Host.f!` uses `Host`). A name in a comment or a
--              string is no use.
--
-- A method call never names its module, so a module whose only use is a
-- method on a value of its type is unused here, and Roc agrees: the method
-- resolves through the value's type without the import. A bare tag that
-- shares a module's name (`Other`, in an expression, a pattern or a tag union
-- type) is no use of the module, but a nominal type's name before its record
-- (`Point.{ x: 0 }`) is.
--
-- roc-ast drops the qualifier of a tag in a pattern (`Color.Red =>` comes as
-- `.Red`), so that name is read from the source at the pattern's column.
--
-- The output is the counts, one line per finding, and the counts again
-- (cookbook/findings.shale). The run fails if there are findings, or if
-- any file doesn't parse, and the files that do parse are judged either way.
-- budget: steps=800000000 arena_bytes=2000000000 output_bytes=4000000

const SELF_TEST = arg("self_test", "") == "1"
const GLOB = arg("glob", "**/*.roc")
use("cookbook:findings.shale")
use("./parsed.shale")
use("./gate_recipe.shale")
use("./imports.shale")
const CHECKS = {"unused_import"}

function judge_file(f, report)
  for imp in unused_imports(f.nodes, split(read(f.path), "\n")) do
    push(report, {path = f.path, line = imp.line, check = "unused_import", what = imp.label .. " is imported and never used: delete the line"})
  end
  return nil
end
function self_test()
  local at = "cookbook:roc/plants/find_unused_imports/"
  check_plants("find_unused_imports", "cookbook:roc/find_unused_imports.shale", CHECKS, {
    {glob = at .. "unused.roc", counts = {unused_import = 1}, says = {"unused.roc:3: unused_import: `game.Polygon` is imported and never used"}},
    {glob = at .. "unused_alias.roc", counts = {unused_import = 1}, says = {"`game.Distance` as `D` is imported and never used"}},
    {glob = at .. "unused_exposing.roc", counts = {unused_import = 1}, says = {"`pf.Stdout` is imported"}},
    {glob = at .. "unused_file_import.roc", counts = {unused_import = 1}, says = {"the file import `page` is imported"}},
    {glob = at .. "unused_in_prose.roc", counts = {unused_import = 1}, says = {"`game.Polygon` is imported"}},
    {glob = at .. "unused_method_only.roc", counts = {unused_import = 1}, says = {"`game.Distance` is imported"}},
    {glob = at .. "unused_tag_namesake.roc", counts = {unused_import = 1}, says = {"`game.Other` is imported"}},
    {glob = at .. "unused_beside_hosted.roc", counts = {unused_import = 1}, says = {"unused_beside_hosted.roc:24: unused_import: `Http` is imported"}},
    {glob = at .. "unused.roc," .. at .. "unused_alias.roc", counts = {unused_import = 2}},
    {glob = at .. "quiet_qualified.roc"},
    {glob = at .. "quiet_annotation.roc"},
    {glob = at .. "quiet_expect.roc"},
    {glob = at .. "quiet_pattern_tag.roc"},
    {glob = at .. "quiet_tag.roc"},
    {glob = at .. "quiet_exposing.roc"},
    {glob = at .. "quiet_alias.roc"},
    {glob = at .. "quiet_interpolation.roc"},
    {glob = at .. "quiet_file_import.roc"},
    {glob = at .. "quiet_hosted.roc"},
    {glob = at .. "broken/*.roc", stops = true, says = {"refused: "}},
  })
  return nil
end

function run_check()
  local paths = {}
  for g in split(GLOB, ",") do
    for p in glob(trim(g)) do push(paths, p) end
  end
  local parsed = parse_roc_files(paths)
  local report = {}
  for f in parsed.files do judge_file(f, report) end
  local verdict = verdict_of("find_unused_imports", CHECKS, report, #paths)
  print_findings(verdict.summary, verdict.found)
  fail_if_refused("find_unused_imports", parsed.refused)
  return verdict
end

-- This `fail` stands at the top level so the summary is the last line a
-- caller reads: a stop inside a function prints the calls after it.
if SELF_TEST then
  self_test()
else
  local verdict = run_check()
  if #verdict.found > 0 then fail(verdict.summary) end
end