find_awkward_names

Roc

It also imports Finding, Headers, RocTypes, Text, Tree from the shared Roc library.

cookbook/roc/find_awkward_names/find_awkward_names.roc, 311 lines

## find_awkward_names, in Roc on Shale's platform (roc_platform/README.md): awkward
## names in every .roc file of a tree, from Roc's own parser's trees. Its
## launcher, cookbook/roc/find_awkward_names.shale, is how it is run, and its header
## says the checks, from `state_effect` to `stale_doc_name`.
## check_goldens.shale, beside this, holds its output on the plants to its
## goldens, line for line.
##
##   cd <repo> && shale cookbook:roc/find_awkward_names.shale glob=app/**/*.roc
##   shale cookbook:roc/find_awkward_names.shale self_test=1
##
## The arguments: `glob` (`**/*.roc`), `words` (`words=1` prints the census
## of effects' first words instead), `house` (`house=0` leaves out the house
## style), `types` (`1` asks Roc's type checker), `root` (the app or apps the
## types are read from), `terms` (a project's terms) and `self_test`
## (`self_test=1` checks the plants, the typed ones with the types).
##
## This root reads the word lists (Words), globs the files, gathers the
## types (Types), has Roc's parser read the files, reads each file's
## definitions (Reading), judges them (Judge, with ListNames and Makers),
## then the bindings (ShortNames), the docs (DocNames) and what is judged
## over every file (Passes), and prints the verdict; SelfTest judges the
## plants. Tree, Text, Finding and RocTypes are the cookbook's Roc library,
## cookbook/roc/lib/.
## budget: steps=800000000 arena_bytes=3000000000 output_bytes=4000000 roc_cpu_ms=600000 programs=100
app [main!] { lib: "../lib/main.roc", pf: platform "../../../roc_platform/platform/main.roc" }

import pf.Shale
import lib.Finding
import lib.RocTypes
import lib.Text
import lib.Tree
import DocNames
import Facts
import Judge
import ListNames
import Passes
import Reading
import SelfTest
import ShortNames
import Types
import Words

main! : {} => {}
main! = |{}| {
	self_test = Shale.arg!("self_test", "") == "1"
	plants = SelfTest.plants
	glob = if self_test {
		"${plants}*.roc"
	} else {
		Shale.arg!("glob", "**/*.roc")
	}
	types_asked = Shale.arg!("types", "0")
	if types_asked != "0" and types_asked != "1" {
		Shale.fail!("find_awkward_names: types=${types_asked}: 0 (the default) or 1")
	}
	# The self-test checks its typed plants with the types, and the rest
	# without.
	use_types = self_test or types_asked == "1"
	root = if self_test {
		"${plants}typed/QuietApp.roc"
	} else {
		Shale.arg!("root", "")
	}
	is_census = Shale.arg!("words", "") == "1"
	terms_file = if self_test {
		"${plants}terms.txt"
	} else {
		Shale.arg!("terms", "")
	}
	lists = Words.read!(terms_file)
	house_style = Words.house_style!({})
	paths = if self_test {
		Shale.glob!(glob).concat(Shale.glob!("${plants}typed/*.roc"))
	} else {
		Shale.glob!(glob)
	}
	types = if use_types {
		roc = Types.roc_bin!("find_awkward_names", self_test)
		# The self-test's untyped plants are imported by no root.
		exempt = if self_test {
			Set.from_list(Shale.glob!("${plants}*.roc"))
		} else {
			Set.empty()
		}
		Types.gather!({ who: "find_awkward_names", kind: Patterns, root, roc, paths, exempt })
	} else {
		{ typing: RocTypes.no_types, unreached: [] }
	}
	parsed = parse!(paths)
	read = definitions_of(parsed.files, types.typing)
	found = judged!({ files: parsed.files, read, lists, self_test })
	house = if !(found.is_empty()) or !(is_census) {
		read_house!({})
	} else {
		Kept
	}
	is_kept = |finding|
		match house {
			Kept => Bool.True
			LeftOut => !(house_style.contains(finding.check))
		}
	reported = found.keep_if(is_kept)
	finding_lines = if is_census {
		[]
	} else {
		reported.map(Finding.line_of)
	}
	file_count = paths.len().to_str()
	if is_census {
		census = Passes.census_lines(Passes.census(read.definitions, lists))
		print_findings!("find_awkward_names (Roc) census: ${file_count} files; ${census.summary}", census.lines)
	} else {
		house_note = match house {
			Kept => ""
			LeftOut => "; left out as house style: ${Str.join_with(house_style, ", ")}"
		}
		print_findings!("find_awkward_names (Roc): ${file_count} files; ${Finding.counts_of(reported, checks)}${house_note}", finding_lines)
	}
	fail_if_refused!(parsed.refused, types.unreached)
	if self_test {
		census = Passes.census(read.definitions, lists)
		SelfTest.run!({ paths, findings: reported, census, finding_lines }, checks)
	}
}

## The checks, in the order the summary counts them.
checks : List(Str)
checks = ["state_effect", "question", "vague", "name_type", "negative", "noun_effect", "command_tense", "mixed_tense", "container", "preposition_split", "short_name", "worker_name", "stacked_preposition", "taken_word", "bare_participle", "phrase_name", "singular_list", "world_verb", "where_name", "stale_doc_name"]

## The files Roc's parser read, each with its text cut at each newline, and
## a `path: why` line for each it refused.
parse! : List(Str) => { files : List(Reading.FileRead), refused : List(Str) }
parse! = |paths| {
	var $files = []
	var $refused = []
	for file in Shale.roc_tree!(paths) {
		if file.err == "" {
			source = match Shale.read!(file.path) {
				Found(text) => text
				Missing => ""
			}
			$files = $files.append({ path: file.path, nodes: file.nodes, source_lines: source.split_on("\n") })
		} else if file.err.starts_with(file.path) {
			$refused = $refused.append(file.err)
		} else {
			$refused = $refused.append("${file.path}: ${file.err}")
		}
	}
	{ files: $files, refused: $refused }
}

## What the run asks of the files read: the files, their definitions and
## the facts their reading gathered, the word lists, and whether it is the
## self-test.
Asked : {
	files : List(Reading.FileRead),
	read : { definitions : List(Reading.Definition), facts : Facts.Gathered },
	lists : Words.Lists,
	self_test : Bool,
}

## Every file's definitions, in file order, and the facts their reading
## gathers.
definitions_of : List(Reading.FileRead), RocTypes.Typing -> { definitions : List(Reading.Definition), facts : Facts.Gathered }
definitions_of = |files, typing|
	files.fold(
		{ definitions: [], facts: Facts.none },
		|so_far, file| {
			pattern_types = pattern_types_of(typing, file.path, file.nodes)
			read = Reading.file_definitions(file, pattern_types)
			{ definitions: so_far.definitions.concat(read.definitions), facts: Facts.joined(so_far.facts, read.facts) }
		},
	)

## The checker's type of each plain-name pattern of the file at `path`, by
## its node's place: none when no root reached the file.
pattern_types_of : RocTypes.Typing, Str, List(Tree.Node) -> Dict(U64, Str)
pattern_types_of = |typing, path, nodes| {
	if !(typing.real.contains(path)) {
		return Dict.empty()
	}
	var $typed = Dict.empty()
	$place : U64
	var $place = 0
	for node in nodes {
		$place = $place + 1
		if node.kind == "p-ident" {
			match RocTypes.type_at(typing, path, node) {
				Ok(written) => {
					$typed = $typed.insert($place, written)
				}
				Err(NoType) => {}
			}
		}
	}
	$typed
}

## Every finding, in the Shale original's order: each definition's, each
## file's `where` clauses and bindings, each file's docs, the type and
## field names, and the preposition splits.
judged! : Asked => List(Finding)
judged! = |asked| {
	lists = asked.lists
	read = asked.read
	facts = read.facts
	by_definition = read.definitions.map(|definition| Judge.findings(definition, lists, facts)).join()
	by_file = asked.files
		.map(|file| Passes.where_name_findings(file.path, file.nodes, lists.fixed_names).concat(ShortNames.findings(file.path, file.nodes)))
		.join()
	sources = Words.word_set!("cookbook:words/cited_sources.txt")
	# Each plant opens by naming its check, so in the self-test the check
	# names, and this recipe's, count as names.
	known = if asked.self_test {
		Set.from_list(checks).insert("find_awkward_names")
	} else {
		Set.empty()
	}
	doc_files = asked.files.map(|file| { path: file.path, nodes: file.nodes, source_lines: file.source_lines })
	by_doc = DocNames.findings!(doc_files, DocNames.seen_of(doc_files, known, sources))
	by_name = facts.names
		.map(
			|named| {
				subject = { path: named.path, line: named.line, name: named.name, kind: "field", is_function: named.is_function, first: named.first, gives: named.gives }
				listed = if named.is_field {
					ListNames.findings(subject, lists)
				} else {
					[]
				}
				Passes.container_findings(named, lists).concat(listed)
			},
		)
		.join()
	splits = Passes.preposition_splits(read.definitions, lists, facts.keywords)
	by_definition.concat(by_file).concat(by_doc).concat(by_name).concat(splits)
}

## Whether `house=0` leaves the house style out (cookbook/roc/house.shale):
## `house` is read as an integer, 1 unless given.
read_house! : {} => [Kept, LeftOut]
read_house! = |{}| {
	given = Shale.arg!("house", "1")
	match integer_of(given) {
		Ok(0) => LeftOut
		Ok(1) => Kept
		Ok(other) => {
			Shale.fail!("house must be 1 (the default) or 0, not ${other.to_str()}")
			Kept
		}
		Err(NotAnInteger) => {
			Shale.fail!("`arg`: house=${given} is not an integer, and its default is one")
			Kept
		}
	}
}

## A launch value read as an integer, as Shale's `arg` reads one whose
## default is: digits, a `-` before them or not.
integer_of : Str -> Try(I64, [NotAnInteger])
integer_of = |text| {
	bytes = text.to_utf8()
	digits = match bytes {
		['-', .. as rest] => rest
		_ => bytes
	}
	if digits.is_empty() or !(digits.all(Text.is_digit)) {
		return Err(NotAnInteger)
	}
	value = digits.fold(0, |sum, digit| sum * 10 + (digit - '0').to_i64())
	if bytes.first() == Ok('-') {
		Ok(-value)
	} else {
		Ok(value)
	}
}

## 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)
	}
}

## After the findings: the files that didn't parse, and those no root of the
## types reaches (judged without them), named, then a stop
## (cookbook/roc/parsed.shale's `fail_if_refused`).
fail_if_refused! : List(Str), List(Str) => {}
fail_if_refused! = |refused, unreached| {
	if !(refused.is_empty()) or !(unreached.is_empty()) {
		for refusal in refused {
			Shale.print!("refused: ${refusal}")
		}
		for missed in unreached {
			Shale.print!(missed)
		}
		var $why = []
		if !(refused.is_empty()) {
			$why = $why.append("roc-ast refused ${refused.len().to_str()} files (named above), which have no tree to judge")
		}
		if !(unreached.is_empty()) {
			$why = $why.append("${unreached.len().to_str()} files (named above) are reached by no root of the types, so were judged without them")
		}
		Shale.fail!("find_awkward_names: ${Str.join_with($why, "; ")}; every other file was judged")
	}
}

cookbook/roc/find_awkward_names/DocNames.roc, 399 lines

## What find_awkward_names' `stale_doc_name` reads (the Shale original's
## doc_names.shale): the names a file's comment lines put in backticks, and whether each still
## names something in the file, the modules it imports, or the module a
## `Module.name` names. Only a name a reader can't take for a prose word is
## judged: one of two words or more (`two_opt`), or a module's member
## (`Route.two_opt`). A name cited from another language or library, or
## with a possessive before it, is another's. Reading a module beside the
## file that the run didn't parse is an effect, so this module has them.
import pf.Shale
import lib.Finding
import lib.Text
import lib.Tree

DocNames := [].{

	## What the run has read of names: the self-test's own (`known`), each
	## module's by its name, each file's by its path (`Unread` for one that
	## couldn't be), and the sources a citation names.
	Seen : {
		known : Set(Str),
		by_module : Dict(Str, Set(Str)),
		by_path : Dict(Str, [Read(Set(Str)), Unread]),
		sources : Set(Str),
	}

	## A parsed file, its lines and its tree.
	FileRead : { path : Str, nodes : List(Tree.Node), source_lines : List(Str) }

	## The names the parsed files hold, by module and by path.
	seen_of : List(DocNames.FileRead), Set(Str), Set(Str) -> DocNames.Seen
	seen_of = |files, known, sources| {
		var $by_module = Dict.empty()
		var $by_path = Dict.empty()
		for file in files {
			module_named = Tree.module_name(file.path)
			own = names_in_tree(file.nodes)
			$by_module = $by_module.insert(module_named, ($by_module.get(module_named) ?? Set.empty()).union(own))
			$by_path = $by_path.insert(file.path, Read(own))
		}
		{ known, by_module: $by_module, by_path: $by_path, sources }
	}

	## Each backticked name in a comment of each file that names nothing
	## there, once a line, file by file.
	findings! : List(DocNames.FileRead), DocNames.Seen => List(Finding)
	findings! = |files, seen_before| {
		var $seen = seen_before
		var $found = []
		for file in files {
			judged = file_findings!(file, $seen)
			$seen = judged.seen
			$found = $found.concat(judged.found)
		}
		$found
	}
}

## A backticked name: its line, its module (`""` for a bare name), the name,
## and whether a possessive or a cited source says it is another's.
DocName : { line : U64, module_part : Str, name : Str, is_others : Bool }

## The file's stale names, and what the run has read of names since.
file_findings! : DocNames.FileRead, DocNames.Seen => { found : List(Finding), seen : DocNames.Seen }
file_findings! = |file, seen_before| {
	var $seen = seen_before
	own = match seen_before.by_path.get(file.path) {
		Ok(Read(names)) => names
		_ => names_in_tree(file.nodes)
	}
	base = Text.basename(file.path)
	folder = Str.from_utf8_lossy(file.path.to_utf8().take_first(file.path.count_utf8_bytes() - base.count_utf8_bytes()))
	own_module = Tree.module_name(file.path)
	is_platform = file.nodes.any(|node| node.kind == "platform")
	var $imported = []
	var $all_imports_known = Bool.True
	for imported in imports_in_tree(file.nodes) {
		looked = module_names!(folder, imported, $seen)
		$seen = looked.seen
		match looked.names {
			Ok(names) => {
				$imported = $imported.append(names)
			}
			Err(Unknown) => {
				$all_imports_known = Bool.False
			}
		}
	}
	var $said = Set.empty()
	var $found = []
	for doc_name in doc_names_in(file.source_lines, $seen.sources) {
		name = doc_name.name
		plain = name.drop_suffix("!")
		holds = |names| names.contains(name) or names.contains(plain)
		is_host_symbol = is_platform and plain.starts_with("roc_")
		is_bare = doc_name.module_part == ""
		var $judged = !(is_bare and (doc_name.is_others or !($all_imports_known) or is_host_symbol))
		var $names_something = Bool.False
		if is_bare or doc_name.module_part == own_module {
			if holds(own) or $seen.known.contains(plain) {
				$names_something = Bool.True
			}
			if is_bare and $imported.any(holds) {
				$names_something = Bool.True
			}
		} else {
			looked = module_names!(folder, doc_name.module_part, $seen)
			$seen = looked.seen
			match looked.names {
				Ok(names) => {
					if holds(names) {
						$names_something = Bool.True
					}
				}
				Err(Unknown) => {
					$judged = Bool.False
				}
			}
		}
		shown = if is_bare {
			name
		} else {
			"${doc_name.module_part}.${name}"
		}
		key = "${doc_name.line.to_str()}|${shown}"
		if $judged and !($names_something) and !($said.contains(key)) {
			$said = $said.insert(key)
			place = if is_bare {
				"this file or its imports"
			} else {
				doc_name.module_part
			}
			what = "a comment names `${shown}`, which names nothing in ${place}: a rename left it behind, or it names what is gone"
			$found = $found.append({ path: file.path, line: doc_name.line, check: "stale_doc_name", what })
		}
	}
	{ found: $found, seen: $seen }
}

## The names module `module` holds, or `Unknown` when they can't be known
## (a builtin's module, a package's the run didn't read): those of
## `<folder><module>.roc` beside the file, read once, else those of the
## files read that hold a module of that name.
module_names! : Str, Str, DocNames.Seen => { names : Try(Set(Str), [Unknown]), seen : DocNames.Seen }
module_names! = |folder, module_named, seen| {
	path = "${folder}${module_named}.roc"
	looked_up = match seen.by_path.get(path) {
		Ok(known) => { read: known, after: seen }
		Err(_) => {
			read_now = if Shale.exists!(path) {
				match Shale.roc_tree!([path]) {
					[parsed, ..] if parsed.err == "" => Read(names_in_tree(parsed.nodes))
					_ => Unread
				}
			} else {
				Unread
			}
			{ read: read_now, after: { ..seen, by_path: seen.by_path.insert(path, read_now) } }
		}
	}
	read = looked_up.read
	after = looked_up.after
	names = match read {
		Read(names_read) => Ok(names_read)
		Unread =>
			match seen.by_module.get(module_named) {
				Ok(names_held) => Ok(names_held)
				Err(_) => Err(Unknown)
			}
	}
	{ names, seen: after }
}

## Every name a file's tree holds: what it declares, binds, calls, each
## record field and method it names, and each symbol a platform's
## `provides` gives the host, with and without an effect's `!`.
names_in_tree : List(Tree.Node) -> Set(Str)
names_in_tree = |nodes| {
	var $names = Set.empty()
	for node in nodes {
		for attribute in node.attributes {
			if ["raw", "name", "field", "method", "symbol"].contains(attribute.name) {
				value = attribute.value.drop_prefix(".")
				if value != "" {
					$names = $names.insert(value)
					if value.ends_with("!") {
						$names = $names.insert(value.drop_suffix("!"))
					}
				}
			}
		}
	}
	$names
}

## The modules a file imports, by the name its code calls them (`Route`,
## and `Stdout` for `pf.Stdout`).
imports_in_tree : List(Tree.Node) -> List(Str)
imports_in_tree = |nodes|
	nodes.keep_if(|node| node.kind == "s-import").map(|node| Tree.last_part(Tree.attribute(node, "raw")))

## A file's extensions, so `Screen.roc` is a file's name, not a member's.
file_extensions : List(Str)
file_extensions = ["roc", "md", "txt", "zig", "ts", "js", "mjs", "json", "shale", "html", "tsv"]

## Each backticked name in the comment lines of a file (`#` or `##` first),
## as the header says which are judged.
doc_names_in : List(Str), Set(Str) -> List(DocName)
doc_names_in = |source_lines, sources| {
	var $out = []
	$number : U64
	var $number = 0
	for source_line in source_lines {
		$number = $number + 1
		line = Text.trim(source_line)
		if line.starts_with("#") {
			for span in backticked(line) {
				match doc_name_parts(span.text) {
					Ok(parts) => {
						before_on_line = Text.trim(without_hashes(Text.bytes_of(line, { start: 0, count: span.at })))
						before = if before_on_line == "" and $number > 1 {
							Text.trim(Text.line_at(source_lines, $number - 1))
						} else {
							before_on_line
						}
						is_others = is_possessive("${before} ") or cites_source(sentence_before(source_lines, $number, span.at), sources)
						is_file = parts.module_part != "" and file_extensions.contains(parts.name)
						if (parts.module_part != "" or parts.name.contains("_")) and !(is_file) {
							$out = $out.append({ line: $number, module_part: parts.module_part, name: parts.name, is_others })
						}
					}
					Err(NoName) => {}
				}
			}
		}
	}
	$out
}

## Each run between two backticks with something between them, left to
## right: `at` is how many bytes stand before its opening backtick.
backticked : Str -> List({ at : U64, text : Str })
backticked = |line| {
	bytes = line.to_utf8()
	var $spans = []
	$at : U64
	var $at = 0
	while $at < bytes.len() {
		if bytes.get($at) == Ok('`') {
			rest = bytes.drop_first($at + 1)
			match rest.find_first_index(|byte| byte == '`') {
				Ok(0) => {
					$at = $at + 1
				}
				Ok(length) => {
					$spans = $spans.append({ at: $at, text: Str.from_utf8_lossy(rest.take_first(length)) })
					$at = $at + length + 2
				}
				Err(_) => {
					$at = bytes.len()
				}
			}
		} else {
			$at = $at + 1
		}
	}
	$spans
}

## A backticked text's module and name when it is a doc name:
## `two_opt`, `read_line!`, `Route.two_opt(stops)`
## (the Shale original's DOC_NAME).
doc_name_parts : Str -> Try({ module_part : Str, name : Str }, [NoName])
doc_name_parts = |text| {
	bytes = text.to_utf8()
	match bytes {
		[first, .. as rest] if Text.is_capital(first) => {
			module_length = 1 + (rest.find_first_index(|byte| !(is_letter_or_digit(byte))) ?? rest.len())
			if bytes.get(module_length) != Ok('.') {
				return Err(NoName)
			}
			name = name_of(bytes.drop_first(module_length + 1))?
			Ok({ module_part: Str.from_utf8_lossy(bytes.take_first(module_length)), name })
		}
		_ => Ok({ module_part: "", name: name_of(bytes)? })
	}
}

## The name a doc name's bytes start with, `[a-z][a-z0-9]*(_[a-z0-9]+)*!?`,
## when nothing or a call's parentheses follow it.
name_of : List(U8) -> Try(Str, [NoName])
name_of = |bytes| {
	is_word_byte = |byte| Text.is_small_letter(byte) or Text.is_digit(byte)
	match bytes.first() {
		Ok(first) if Text.is_small_letter(first) => {}
		_ => return Err(NoName)
	}
	$length : U64
	var $length = 1
	while $length < bytes.len() and is_word_byte(bytes.get($length) ?? 0) {
		$length = $length + 1
	}
	while bytes.get($length) == Ok('_') and is_word_byte(bytes.get($length + 1) ?? 0) {
		$length = $length + 2
		while $length < bytes.len() and is_word_byte(bytes.get($length) ?? 0) {
			$length = $length + 1
		}
	}
	if bytes.get($length) == Ok('!') {
		$length = $length + 1
	}
	after = bytes.drop_first($length)
	is_call = after.len() >= 2 and after.first() == Ok('(') and after.last() == Ok(')')
	if after.is_empty() or is_call {
		Ok(Str.from_utf8_lossy(bytes.take_first($length)))
	} else {
		Err(NoName)
	}
}

is_letter_or_digit : U8 -> Bool
is_letter_or_digit = |byte| Text.is_capital(byte) or Text.is_small_letter(byte) or Text.is_digit(byte)

## A text without the `#`s that start it.
without_hashes : Str -> Str
without_hashes = |text| {
	bytes = text.to_utf8()
	start = bytes.find_first_index(|byte| byte != '#') ?? bytes.len()
	Str.from_utf8_lossy(bytes.drop_first(start))
}

## Whether a text, a space after it, ends in a possessive: `'s` or `s'`,
## with `own` after it or not (`Pipeline's`, `the rules' own`).
is_possessive : Str -> Bool
is_possessive = |text| ["'s ", "s' ", "'s own ", "s' own "].any(|ending| text.ends_with(ending))

is_space : U8 -> Bool
is_space = |byte| byte == ' ' or byte == '\t' or byte == '\n' or byte == '\r' or byte == 12 or byte == 11

## The places of a text's sentence ends: a `.`, `?` or `!` with a space or
## the text's end after it.
sentence_ends : Str -> List(U64)
sentence_ends = |text| {
	bytes = text.to_utf8()
	var $ends = []
	$at : U64
	var $at = 0
	for byte in bytes {
		is_mark = byte == '.' or byte == '?' or byte == '!'
		is_last = $at + 1 == bytes.len()
		if is_mark and (is_last or is_space(bytes.get($at + 1) ?? 0)) {
			$ends = $ends.append($at)
		}
		$at = $at + 1
	}
	$ends
}

## The text of the sentence before byte `at` of comment line `number`:
## back across the comment lines above, their `#`s gone, until a `.`, `?`
## or `!` that ends a sentence, a blank comment line, or the comment's
## start.
sentence_before : List(Str), U64, U64 -> Str
sentence_before = |source_lines, number, at| {
	on_line = Text.bytes_of(Text.trim(Text.line_at(source_lines, number)), { start: 0, count: at })
	var $text = Text.trim(without_hashes(on_line))
	var $up = number - 1
	var $is_blank_above = Bool.False
	while !($is_blank_above) and sentence_ends($text).is_empty() and $up >= 1 and Text.trim(Text.line_at(source_lines, $up)).starts_with("#") {
		above = Text.trim(without_hashes(Text.trim(Text.line_at(source_lines, $up))))
		if above == "" {
			$is_blank_above = Bool.True
		} else {
			$text = "${above} ${$text}"
			$up = $up - 1
		}
	}
	match sentence_ends($text).last() {
		Ok(last) => Text.bytes_of($text, { start: last + 1, count: $text.count_utf8_bytes() })
		Err(_) => $text
	}
}

## Whether a sentence names a source a citation names, as a whole word or a
## possessive (`Rust`, `Rust's`, `Zig,`).
cites_source : Str, Set(Str) -> Bool
cites_source = |sentence, sources|
	Text.words(sentence).any(
		|word| {
			unpossessed = if word.ends_with("'s") {
				word.drop_suffix("'s")
			} else if word.ends_with("s'") {
				word.drop_suffix("s'")
			} else {
				word
			}
			bare = Str.from_utf8_lossy(unpossessed.to_utf8().drop_if(|byte| byte == ',' or byte == ';' or byte == ':' or byte == '(' or byte == ')' or byte == '"'))
			sources.contains(bare)
		},
	)

cookbook/roc/find_awkward_names/Facts.roc, 222 lines

## The facts the reading of the files gathers for the checks judged over the
## whole tree: each file's declared
## keywords, the tag unions types name, the aliases of `Bool`, the kinds of
## types a file declares, each type name a file declares, and the type and
## field names `container` reads.
import lib.Text
import lib.Tree
import ShortNames
import TypeText

Facts := [].{

	## A type's or a record field's name, for `container`: its words, the
	## doc above its declaration, lowercased; a field's also whether it is a
	## letter of a set beside its siblings, what it gives and its first
	## argument's type when it is a function.
	Named : {
		path : Str,
		line : U64,
		name : Str,
		words : List(Str),
		is_field : Bool,
		doc : Str,
		is_letter_of_set : Bool,
		gives : Str,
		is_function : Bool,
		first : Str,
	}

	## What the reading gathers: each file's `# keywords:` words, by path;
	## each type's tag union, by the type's name; the names of aliases of
	## `Bool`, bare and as `Owner.Name`; each type a file declares, by path,
	## as whether it is `[].{ ... }`; each type name as `path|Name`; and the
	## type and field names.
	Gathered : {
		keywords : Dict(Str, List(Str)),
		unions : Dict(Str, TypeText.Union),
		bool_aliases : Set(Str),
		type_kinds : Dict(Str, List(Bool)),
		type_names : Set(Str),
		names : List(Facts.Named),
	}

	## A parsed file: its path, its tree and its text cut at each newline.
	FileRead : { path : Str, nodes : List(Tree.Node), source_lines : List(Str) }

	## No facts yet, to add files to.
	none : Facts.Gathered
	none = {
		keywords: Dict.empty(),
		unions: Dict.empty(),
		bool_aliases: Set.empty(),
		type_kinds: Dict.empty(),
		type_names: Set.empty(),
		names: [],
	}

	## The facts of `earlier` files, then those of a `later` one: where both
	## name a type's union, the later's stands.
	joined : Facts.Gathered, Facts.Gathered -> Facts.Gathered
	joined = |earlier, later| {
		keywords: later.keywords.to_list().fold(earlier.keywords, |into, (path, words)| into.insert(path, (into.get(path) ?? []).concat(words))),
		unions: later.unions.to_list().fold(earlier.unions, |into, (name, union)| into.insert(name, union)),
		bool_aliases: earlier.bool_aliases.union(later.bool_aliases),
		type_kinds: later.type_kinds.to_list().fold(earlier.type_kinds, |into, (path, kinds)| into.insert(path, (into.get(path) ?? []).concat(kinds))),
		type_names: earlier.type_names.union(later.type_names),
		names: earlier.names.concat(later.names),
	}

	## A file's first facts: the keywords it declares in a comment line
	## `# keywords: for, on`, lowercased.
	keywords_of : Facts.FileRead -> Facts.Gathered
	keywords_of = |file| {
		var $words = []
		for source_line in file.source_lines {
			trimmed = Text.trim(source_line)
			if trimmed.starts_with("# keywords: ") {
				for word in trimmed.drop_prefix("# keywords: ").split_on(",") {
					if Text.trim(word) != "" {
						$words = $words.append(Text.lower(Text.trim(word)))
					}
				}
			}
		}
		keywords = if $words.is_empty() {
			Dict.empty()
		} else {
			Dict.empty().insert(file.path, $words)
		}
		{ ..Facts.none, keywords }
	}

	## The facts with what the type declaration at `at` declares: its tag
	## union, its kind, its name, and its name as an alias of `Bool` when it
	## is one.
	with_type_declaration : Facts.FileRead, U64, Facts.Gathered -> Facts.Gathered
	with_type_declaration = |file, at, facts| {
		nodes = file.nodes
		node = Tree.node_at(nodes, at)
		declared = match node.kids.first() {
			Ok(name_at) => Tree.attribute(Tree.node_at(nodes, name_at), "name")
			Err(_) => ""
		}
		if declared == "" {
			return facts
		}
		built_on = match node.kids.get(1) {
			Ok(built_at) => Ok(Tree.node_at(nodes, built_at))
			Err(_) => Err(NotBuilt)
		}
		is_union = match built_on {
			Ok(built) => built.kind == "ty-tag-union"
			Err(_) => Bool.False
		}
		unions = if is_union {
			facts.unions.insert(declared, TypeText.union_shape(nodes, Tree.kid_at(node, 2)))
		} else {
			facts.unions
		}
		has_no_tags = (unions.get(declared) ?? { names: [], has_payload: Bool.False }).names.is_empty()
		is_holder = is_union and has_no_tags and Tree.node_at(nodes, Tree.last_kid(node)).kind == "associated"
		named = {
			path: file.path,
			line: node.line,
			name: declared,
			words: Text.name_words(declared),
			is_field: Bool.False,
			doc: doc_above(file.source_lines, node.line),
			is_letter_of_set: Bool.False,
			gives: "",
			is_function: Bool.False,
			first: "",
		}
		is_bool_alias = match built_on {
			Ok(built) => built.kind == "ty" and Tree.attribute(built, "name") == "Bool"
			Err(_) => Bool.False
		}
		{
			..facts,
			unions,
			type_kinds: facts.type_kinds.insert(file.path, (facts.type_kinds.get(file.path) ?? []).append(is_holder)),
			type_names: facts.type_names.insert("${file.path}|${declared}"),
			names: facts.names.append(named),
			bool_aliases: if is_bool_alias {
				facts.bool_aliases.union(Set.from_list(bool_alias_names(nodes, node, declared)))
			} else {
				facts.bool_aliases
			},
		}
	}

	## The facts with the record field at `at`, declared at line
	## `declaration_line`, as a name `container` and `singular_list` read.
	with_field : Facts.FileRead, U64, U64, Facts.Gathered -> Facts.Gathered
	with_field = |file, at, declaration_line, facts| {
		nodes = file.nodes
		node = Tree.node_at(nodes, at)
		field = Tree.attribute(node, "name")
		siblings = Set.from_list(Tree.node_at(nodes, node.parent).kids.map(|kid| Tree.attribute(Tree.node_at(nodes, kid), "name")))
		field_type_at = Tree.first_kid(node)
		field_type = Tree.node_at(nodes, field_type_at)
		is_function = field_type.kind == "ty-fn"
		gives = if is_function {
			Tree.written_type(nodes, Tree.last_kid(field_type))
		} else {
			Tree.written_type(nodes, field_type_at)
		}
		first = if is_function and field_type.kids.len() > 1 {
			Tree.written_type(nodes, Tree.first_kid(field_type))
		} else {
			""
		}
		named = {
			path: file.path,
			line: node.line,
			name: field,
			words: Text.name_words(field),
			is_field: Bool.True,
			doc: doc_above(file.source_lines, declaration_line),
			is_letter_of_set: ShortNames.is_letter_of_set(field, siblings),
			gives,
			is_function,
			first,
		}
		{ ..facts, names: facts.names.append(named) }
	}
}

## An alias of `Bool`'s names: bare, and for a module type's member
## `Owner.Name`, as the checker writes it.
bool_alias_names : List(Tree.Node), Tree.Node, Str -> List(Str)
bool_alias_names = |nodes, node, declared| {
	if node.parent == 0 {
		return [declared]
	}
	parent = Tree.node_at(nodes, node.parent)
	if parent.kind != "associated" or parent.parent == 0 {
		return [declared]
	}
	owner = match Tree.node_at(nodes, parent.parent).kids.first() {
		Ok(owner_at) => Tree.attribute(Tree.node_at(nodes, owner_at), "name")
		Err(_) => ""
	}
	if owner == "" {
		[declared]
	} else {
		[declared, "${owner}.${declared}"]
	}
}

## The comment lines directly above line `line`, nearest first, trimmed,
## lowercased and joined: a declaration's doc.
doc_above : List(Str), U64 -> Str
doc_above = |source_lines, line| {
	var $parts = []
	var $above = line
	while $above > 1 and Text.trim(Text.line_at(source_lines, $above - 1)).starts_with("#") {
		$parts = $parts.append(Text.lower(Text.trim(Text.line_at(source_lines, $above - 1))))
		$above = $above - 1
	}
	Str.join_with($parts, " ")
}

cookbook/roc/find_awkward_names/Judge.roc, 346 lines

## find_awkward_names' checks of one definition (the Shale original's
## `judge_definition`): every check but `container`, `preposition_split`,
## `where_name`, `stale_doc_name` and the bindings' `short_name`, which are
## judged over the files afterwards. The launcher's header says what each
## finds. Also the act an effect's name starts with, which the census
## counts and `noun_effect` and `state_effect` judge.
import lib.Finding
import Facts
import ListNames
import Makers
import Reading
import TypeText
import Words

Judge := [].{

	## The word an effect's name acts by: its first, or the one after a
	## namespace prefix; what that word says (`participle`, `verb`, `vague`,
	## `asks` or `refused`); and how a finding names its place.
	Act : { word : Str, verdict : Str, place : Str }

	## What a name's first word says: `participle`, `verb`, `vague`, `asks`
	## (`is`, `has`) or `refused`.
	first_word_verdict : Str, Words.Lists -> Str
	first_word_verdict = |word, lists|
		if Words.reads_as_participle(word, lists.participles, lists.ed_verbs) {
			"participle"
		} else if lists.verbs.contains(word) {
			"verb"
		} else if lists.vague.contains(word) {
			"vague"
		} else if word == "is" or word == "has" {
			"asks"
		} else {
			"refused"
		}

	## Whether the name is an effect, its `!` its own rather than a
	## callback's.
	is_effectful : Reading.Definition -> Bool
	is_effectful = |definition| definition.name.ends_with("!") and !(definition.has_callback)

	## The act of a name's words, `is_effect` saying whether it is an
	## effect's: a namespace prefix counts only before an effect's act.
	act_of : List(Str), Bool, Words.Lists -> Judge.Act
	act_of = |words, is_effect, lists| {
		first = word_at(words, 1)
		namespace = if is_effect and words.len() > 1 {
			lists.namespaces.get(first)
		} else {
			Err(KeyNotFound)
		}
		match namespace {
			Ok(instructions) => {
				word = word_at(words, 2)
				said = Judge.first_word_verdict(word, lists)
				verdict = if said == "refused" and instructions.contains(word) {
					"verb"
				} else {
					said
				}
				{ word, verdict, place: "the word after its namespace `${first}_`" }
			}
			Err(_) => { word: first, verdict: Judge.first_word_verdict(first, lists), place: "its first word" }
		}
	}

	## What each check judged here finds in one definition, in the Shale
	## original's order. `facts` are every file's.
	findings : Reading.Definition, Words.Lists, Facts.Gathered -> List(Finding)
	findings = |definition, lists, facts| {
		full_name = definition.name
		if lists.fixed_names.contains(full_name) {
			return []
		}
		has_bang = full_name.ends_with("!")
		name = full_name.drop_suffix("!")
		is_effect = Judge.is_effectful(definition)
		words = name.split_on("_")
		first = word_at(words, 1)
		judged_here = !(definition.is_paired)
		is_participle = |word| Words.reads_as_participle(word, lists.participles, lists.ed_verbs)
		act = Judge.act_of(words, is_effect, lists)
		named_as_state = is_participle(act.word) and !(name.contains("_is_") or name.contains("_has_"))
		var $found = []
		report = |check, what| { path: definition.path, line: definition.line, check, what }
		draws_on_surface = match definition.arguments.first() {
			Ok(argument) =>
				match argument.shape {
					Named(named) => named == "Frame" or named == "Canvas"
					_ => Bool.False
				}
			Err(_) => Bool.False
		}
		if is_effect and judged_here and act.verdict == "refused" and !(draws_on_surface) {
			what = if lists.prepositions.contains(act.word) {
				"`${full_name}` has an effect but ${act.place} is a preposition, `${act.word}`: an effect is named for its act"
			} else {
				"`${full_name}` has an effect but ${act.place}, `${act.word}`, is no verb: it reads as a value, not an act"
			}
			$found = $found.append(report("noun_effect", what))
		}
		names_drawn_type = words.len() > 1 and definition.mentioned_types.contains(TypeText.camel_case(words))
		if is_effect and judged_here and named_as_state and !(names_drawn_type) {
			$found = $found.append(report("state_effect", "`${full_name}` has an effect but is named as a state, `${act.word}`: a verb says what it does"))
		}
		named_as_question = words.len() > 1 and ["is", "has", "can", "should"].contains(first)
		signature = signature_of(definition, facts)
		returns_bool = signature.is_function and signature.result == "Bool"
		if named_as_question and judged_here and is_effect and !(returns_bool) {
			gives = if signature.is_function {
				" and gives `${signature.result}`${signature.source_note}"
			} else {
				""
			}
			$found = $found.append(report("question", "`${full_name}` asks a question but has an effect${gives}"))
		}
		if returns_bool and named_as_state and judged_here {
			$found = $found.append(report("question", "`${full_name}` gives a `Bool`${signature.source_note} but is named as a state, `${first}`: ask it (`is_*`, `has_*`)"))
		}
		if named_as_question and judged_here and signature.is_known and signature.is_function and !(is_effect) and signature.result != "Bool" and signature.result != "_" {
			$found = $found.append(report("question", "`${full_name}` asks a question but gives `${signature.result}`${signature.source_note}"))
		}
		if judged_here {
			here = { definition, words, signature, has_bang, returns_bool }
			$found = $found.concat(judged_where_defined(here, lists, facts))
		}
		$found.concat(judged_anywhere(definition, words, lists, facts))
	}
}

## The word at place `at` of `words`, counted from 1.
word_at : List(Str), U64 -> Str
word_at = |words, at|
	if at == 0 {
		""
	} else {
		words.get(at - 1) ?? ""
	}

## What a definition's type says. The type is the checker's when it gave
## one, else the annotation's; it is unknown for a definition with neither.
signature_of : Reading.Definition, Facts.Gathered -> Makers.Signature
signature_of = |definition, facts|
	match definition.typed {
		Typed(written) => {
			parts = TypeText.parts_of(written)
			result = if facts.bool_aliases.contains(parts.result) {
				"Bool"
			} else {
				parts.result
			}
			{ is_function: parts.is_function, first: TypeText.first_argument(parts.arguments), result, is_known: Bool.True, source_note: " (the checker's type)" }
		}
		Untyped => {
			is_function: definition.is_annotation and definition.is_function_type,
			first: definition.first,
			result: definition.result,
			is_known: definition.is_annotation,
			source_note: "",
		}
	}

## A definition judged where it is defined, not at an annotation paired
## with it: its words, what its type says, whether it ends in `!` and gives
## a `Bool`.
Here : {
	definition : Reading.Definition,
	words : List(Str),
	signature : Makers.Signature,
	has_bang : Bool,
	returns_bool : Bool,
}

## The checks judged only where a definition is judged, not at the
## definition an annotation is paired with.
judged_where_defined : Here, Words.Lists, Facts.Gathered -> List(Finding)
judged_where_defined = |here, lists, facts| {
	definition = here.definition
	signature = here.signature
	words = here.words
	full_name = definition.name
	name = full_name.drop_suffix("!")
	first = word_at(words, 1)
	last_word = word_at(words, words.len())
	report = |check, what| { path: definition.path, line: definition.line, check, what }
	var $found = []
	is_entry_point = words.len() == 1 and ["handle", "run", "main"].contains(first)
	if words.all(|word| lists.vague.contains(word)) and !(is_entry_point) {
		$found = $found.append(report("vague", "`${full_name}` is only vague words: what does it handle, and how?"))
	}
	if name.count_utf8_bytes() == 1 {
		$found = $found.append(report("short_name", "`${full_name}` is one letter, read far from where it is defined: name what it holds"))
	}
	leading = if words.len() > 2 {
		words.take_first(words.len() - 2)
	} else {
		[]
	}
	has_leading_noun = leading.any(|word| !(lists.prepositions.contains(word)))
	before_last = word_at(words, words.len() - 1)
	if has_leading_noun and lists.prepositions.contains(last_word) and lists.prepositions.contains(before_last) {
		$found = $found.append(report("stacked_preposition", "`${full_name}` stacks two prepositions, `_${before_last}_${last_word}`: let each read once, the entry named for what it gives (`rest`, `tail_after`) and the worker for what it adds (`rest_onto`)"))
	}
	# A function is known by its type, else by a lambda definition; a value
	# by a type that is no function, else by a definition that is no lambda.
	# An inferred annotation (`two : _`) with no checker's type is neither.
	is_typed = match definition.typed {
		Typed(_) => Bool.True
		Untyped => Bool.False
	}
	has_type = signature.is_known and !(definition.is_annotation and definition.whole == "_" and !(is_typed))
	is_function = signature.is_function or (!(signature.is_known) and definition.is_lambda)
	is_value = (has_type and !(signature.is_function)) or (!(signature.is_known) and !(definition.is_lambda))
	taken_kind = lists.taken.get(name) ?? ""
	capitalized = TypeText.camel_case([name])
	if taken_kind == "roc" and is_function {
		gives_the_word = signature.is_function and (signature.result.split_on(".").last() ?? "") == capitalized
		if !(gives_the_word) {
			$found = $found.append(report("taken_word", "`${full_name}` is Roc's own word, `${name}`, for a function that gives no `${capitalized}`: name it for the domain's thing (`element`, `append`), and keep Roc's words for Roc"))
		}
	}
	if taken_kind == "cardinal" and is_value {
		$found = $found.append(report("taken_word", "`${full_name}` is a number's name for a value: it says how many, not what it holds"))
	}
	is_participle = Words.reads_as_participle(name, lists.participles, lists.ed_verbs)
	if !(here.has_bang) and words.len() == 1 and is_participle and is_function and !(here.returns_bool) {
		$found = $found.append(report("bare_participle", "`${full_name}` is a function named by a bare past participle, which reads as a `Bool`: name it by a noun for what it gives (`user_by_name`) or a verb for what it does (`add_user`)"))
	}
	is_phrase = !(here.has_bang) and lists.prepositions.contains(first) and is_function and !(here.returns_bool) and signature.result != "_"
	if is_phrase and !(Makers.reads_as_maker(definition, words, signature, facts, lists.prepositions)) {
		gives = if signature.is_known {
			"gives `${signature.result}`${signature.source_note}"
		} else {
			"has no annotation to show it makes its own type"
		}
		$found = $found.append(report("phrase_name", "`${full_name}` starts with a preposition, `${first}`, and ${gives}: bare, it reads as a yes or no and hides what it gives; name the thing (`trees_in_view`, not `in_view`)"))
	} else if signature.is_known {
		kind = if signature.is_function {
			"function"
		} else {
			"value"
		}
		subject = { path: definition.path, line: definition.line, name: full_name, kind, is_function: signature.is_function, first: signature.first, gives: signature.result }
		$found = $found.concat(ListNames.findings(subject, lists))
	}
	if !(here.has_bang) and is_function and lists.world_verbs.contains(first) and !(definition.has_doc) {
		$found = $found.append(report("world_verb", "`${full_name}` is pure, and `${first}` claims to act on something outside: name it for the value it gives (`tree_shapes`, not `draw_tree`)"))
	}
	$place : U64
	var $place = 0
	for parameter in definition.parameters {
		$place = $place + 1
		parameter_type = definition.argument_types.get($place - 1) ?? parameter.typed
		if parameter.name != "" {
			subject = { path: definition.path, line: parameter.line, name: parameter.name, kind: "parameter", is_function: Bool.False, first: "", gives: parameter_type }
			$found = $found.concat(ListNames.findings(subject, lists))
		}
	}
	$found
}

## The checks judged at an annotation and at its definition alike.
judged_anywhere : Reading.Definition, List(Str), Words.Lists, Facts.Gathered -> List(Finding)
judged_anywhere = |definition, words, lists, facts| {
	full_name = definition.name
	first = word_at(words, 1)
	last_word = word_at(words, words.len())
	report = |check, what| { path: definition.path, line: definition.line, check, what }
	var $found = []
	# `worker_name` is judged at the definition, which knows whether it calls
	# itself, and at an annotation only when no definition follows it, as
	# with a hosted effect.
	is_annotation_alone = definition.is_annotation and !(definition.has_definition)
	is_helper_suffix = helper_suffixes.contains(last_word) and (is_annotation_alone or !(definition.is_annotation))
	is_recursion_suffix = Reading.recursion_suffixes.contains(last_word) and definition.recurses
	if words.len() > 1 and (is_helper_suffix or is_recursion_suffix) {
		$found = $found.append(report("worker_name", "`${full_name}` is named only as a helper, `_${last_word}`: name the worker for the parameter it adds (`_from` a start point, `_onto` an output built, `_with` other carried state) and give the entry function the plain name"))
	}
	if definition.is_annotation and !(definition.is_function_type) and definition.whole != "_" {
		annotated = definition.whole
		if last_word == "count" and !(integer_types.contains(annotated)) {
			$found = $found.append(report("name_type", "`${full_name}` is a count of type `${annotated}`"))
		}
		if last_word == "path" and annotated != "Str" and !(annotated.contains("Path")) {
			$found = $found.append(report("name_type", "`${full_name}` is a path of type `${annotated}`"))
		}
		if annotated == "Bool" and (first == "no" or first == "not") and words.len() > 1 {
			$found = $found.append(report("negative", "`${full_name}` is a negative flag: `${full_name} = Bool.false` reads twice"))
		}
	}
	if definition.is_annotation and Judge.is_effectful(definition) and definition.is_function_type {
		for argument in definition.arguments {
			$found = $found.concat(tense_findings(definition, argument, lists, facts))
		}
	}
	if definition.is_annotation and words.len() > 2 and first == "is" and word_at(words, 2) == "not" {
		$found = $found.append(report("negative", "`${full_name}` asks a negative: `!${full_name}(...)` reads twice"))
	}
	$found
}

## What `command_tense` and `mixed_tense` find in one argument an effect's
## annotation takes: a tag union written in place, or one a type declared
## in any file checked names.
tense_findings : Reading.Definition, TypeText.ArgumentShape, Words.Lists, Facts.Gathered -> List(Finding)
tense_findings = |definition, argument, lists, facts| {
	union = match argument.shape {
		Written(written) => written
		Named(named) =>
			match facts.unions.get(named) {
				Ok(declared) => declared
				Err(_) => return []
			}
		Unread => return []
	}
	report = |check, what| { path: definition.path, line: definition.line, check, what }
	listed = if argument.is_list {
		"a list of "
	} else {
		""
	}
	shown = "${listed}`[${Str.join_with(union.names, ", ")}]`"
	is_participle = |word| Words.reads_as_participle(word, lists.participles, lists.ed_verbs)
	var $found = []
	all_past = union.names.all(|tag| is_participle(TypeText.tag_first_word(tag)))
	if !(union.has_payload) and union.names.len() >= 2 and all_past {
		$found = $found.append(report("command_tense", "`${definition.name}` takes ${shown}, an instruction named like an event: name its tags as commands (`Pinned` is `Pin`)"))
	}
	event_tags = union.names.keep_if(|tag| is_participle(TypeText.tag_first_word(tag)))
	command_tags = union.names.keep_if(|tag| !(is_participle(TypeText.tag_first_word(tag))) and lists.verbs.contains(TypeText.tag_first_word(tag)))
	if !(command_tags.is_empty()) and !(event_tags.is_empty()) {
		commands = Str.join_with(command_tags, ", ")
		events = Str.join_with(event_tags, ", ")
		$found = $found.append(report("mixed_tense", "`${definition.name}` takes ${shown}: commands (${commands}) beside events (${events}): name what it is told to do in one mood"))
	}
	$found
}

## The suffixes `worker_name` reports always: they say only that a
## function is a helper.
helper_suffixes : List(Str)
helper_suffixes = ["acc", "loop", "inner", "helper", "rec"]

integer_types : List(Str)
integer_types = ["U8", "U16", "U32", "U64", "U128", "I8", "I16", "I32", "I64", "I128"]

cookbook/roc/find_awkward_names/ListNames.roc, 217 lines

## What find_awkward_names' `singular_list` reads of a name whose type says many:
## the word that counts,
## whether it reads as a plural, and the names a finding offers instead. A
## list that is no function and is named from a preposition is
## `phrase_name`'s instead, as the launcher's header says.
import lib.Finding
import lib.Text
import lib.Tree
import TypeText
import Words

ListNames := [].{

	## A name whose type may say many: the file and line it is at, the name,
	## what the finding calls it (`function`, `value`, `parameter`, `field`),
	## whether it is a function, its first argument's type and what it gives
	## or holds.
	Subject : {
		path : Str,
		line : U64,
		name : Str,
		kind : Str,
		is_function : Bool,
		first : Str,
		gives : Str,
	}

	## The finding a name whose type says many and whose head word says one
	## makes, if it makes one.
	findings : ListNames.Subject, Words.Lists -> List(Finding)
	findings = |subject, lists| {
		element = match TypeText.list_element(subject.gives) {
			Ok(found) => found
			Err(NoList) => return []
		}
		bare = subject.name.drop_suffix("!")
		kind_of = |word| lists.list_names.get(word) ?? ""
		if element == "U8" or bare.count_utf8_bytes() < 2 or (lists.taken.get(bare) ?? "") == "cardinal" or kind_of(bare) == "accumulator" {
			return []
		}
		words = joined_terms(bare.split_on("_"), lists.terms)
		says = if subject.is_function {
			"gives"
		} else {
			"holds"
		}
		opening = "the ${subject.kind} `${subject.name}` ${says} `${subject.gives}`"
		at = head_word_at(words, lists)
		head = word_at(words, at)
		first_word = word_at(words, 1)
		if head == "list" or reads_as_plural(head, lists) {
			return []
		}
		term_element = lists.terms.lists.get(head)
		match term_element {
			Ok(named) if named != "" and Tree.last_part(TypeText.type_head(element)) == named => return []
			Ok(named) if named == "" and subject.is_function and words.len() == 1 => return []
			_ => {}
		}
		starts_with_act = subject.is_function and lists.verbs.contains(first_word) and kind_of(first_word) != "one"
		is_changed_copy = subject.is_function and subject.first == subject.gives
		if is_changed_copy and words.len() > 1 {
			return []
		}
		if TypeText.element_word(element) != head {
			if kind_of(head) == "many" or Words.reads_as_participle(head, lists.participles, lists.ed_verbs) {
				return []
			}
			if is_changed_copy or (starts_with_act and words.len() == 1) {
				return []
			}
		}
		said = |check, what| [{ path: subject.path, line: subject.line, check, what }]
		if lists.prepositions.contains(first_word) and !(subject.is_function) {
			said("phrase_name", "${opening} and starts with a preposition, `${first_word}`: bare, it hides what it holds; name the thing (`trees_in_view`, not `in_view`)")
		} else if kind_of(head) == "adjective" {
			held = held_plural(element)
			example = if held != "" {
				" (`${head}_${held}`)"
			} else {
				""
			}
			said("singular_list", "${opening} but the word that counts, `${head}`, is an adjective: the name has no noun; say what the list holds${example}")
		} else {
			said("singular_list", "${opening} but reads as one thing, `${head}`: ${honest_list_names(bare, words, at, element)}")
		}
	}
}

## The word at place `at` of `words`, counted from 1.
word_at : List(Str), U64 -> Str
word_at = |words, at| words.get(at - 1) ?? ""

## `words` with each run of words that spells a term joined into one word,
## the longest term first: `two`, `opt`, `stops` gives `two_opt`, `stops`.
joined_terms : List(Str), Words.Terms -> List(Str)
joined_terms = |words, terms| {
	term_words = terms.words.to_list().map(|(_, spelled)| spelled)
	var $joined = []
	$at : U64
	var $at = 0
	while $at < words.len() {
		rest = words.drop_first($at)
		taken = term_words.fold(
			1,
			|longest, spelled| if spelled.len() > longest and rest.take_first(spelled.len()) == spelled {
				spelled.len()
			} else {
				longest
			},
		)
		$joined = $joined.append(Str.join_with(rest.take_first(taken), "_"))
		$at = $at + taken
	}
	$joined
}

## The place of the word of a name that says what it is, counted from 1:
## the one before the first preposition or word list_names.txt calls
## `after`, past the name's first word (`trees_in_view` gives `trees`), else
## the last that is not digits alone (`corner_2` gives `corner`).
head_word_at : List(Str), Words.Lists -> U64
head_word_at = |words, lists| {
	$place : U64
	var $place = 2
	while $place <= words.len() {
		word = word_at(words, $place)
		if lists.prepositions.contains(word) or lists.list_names.get(word) == Ok("after") {
			return $place - 1
		}
		$place = $place + 1
	}
	var $at = words.len()
	while $at > 1 and is_digits(word_at(words, $at)) {
		$at = $at - 1
	}
	$at
}

is_digits : Str -> Bool
is_digits = |word| {
	bytes = word.to_utf8()
	!(bytes.is_empty()) and bytes.all(Text.is_digit)
}

## Whether a word reads as a plural. An `s` doesn't make one in `class`, in a
## word list_names.txt calls `one` (`axis`), or after letters that are no
## word (`pts`); after one letter it does (`xs`).
reads_as_plural : Str, Words.Lists -> Bool
reads_as_plural = |word, lists| {
	if lists.list_names.get(word) == Ok("one") or !(word.ends_with("s")) or word.ends_with("ss") {
		return Bool.False
	}
	stem = word.drop_suffix("s").to_utf8()
	stem.len() == 1 or stem.any(|byte| byte == 'a' or byte == 'e' or byte == 'i' or byte == 'o' or byte == 'u' or byte == 'y')
}

## A word's plural, as English spells most.
plural_of : Str -> Str
plural_of = |word| {
	is_vowel_before_last = match word.to_utf8() {
		[.., before, _] => before == 'a' or before == 'e' or before == 'i' or before == 'o' or before == 'u'
		_ => Bool.False
	}
	if word.ends_with("y") and !(is_vowel_before_last) {
		"${word.drop_suffix("y")}ies"
	} else if ["s", "x", "z", "ch", "sh"].any(|ending| word.ends_with(ending)) {
		"${word}es"
	} else {
		"${word}s"
	}
}

## The plural of what a list of `element` holds, for a name to say it, or
## `""` when the element has no word of its own: a type variable, a
## number, text.
held_plural : Str -> Str
held_plural = |element| {
	held = TypeText.element_word(element)
	starts_capital = match element.to_utf8().first() {
		Ok(byte) => Text.is_capital(byte)
		Err(_) => Bool.False
	}
	if held == "" or !(starts_capital) or plain_elements.contains(element) {
		""
	} else {
		plural_of(held)
	}
}

## The element types that hold no word of their own.
plain_elements : List(Str)
plain_elements = ["U16", "U32", "U64", "I16", "I32", "I64", "F32", "F64", "Dec", "Str", "Bool"]

## The names `singular_list` offers for `bare`, whose head word is at `at`
## in `words`: the plural of what the list holds put after the head, as in
## `herd_cows`, or the head's own plural when the element is that word, a
## number or text; else the name with `_list`.
honest_list_names : Str, List(Str), U64, Str -> Str
honest_list_names = |bare, words, at, element| {
	held = held_plural(element)
	says_what_it_holds = held != "" and TypeText.element_word(element) != word_at(words, at)
	var $plural_words = []
	$place : U64
	var $place = 0
	for word in words {
		$place = $place + 1
		if $place != at {
			$plural_words = $plural_words.append(word)
		} else if says_what_it_holds {
			$plural_words = $plural_words.append(word).append(held)
		} else {
			$plural_words = $plural_words.append(plural_of(word))
		}
	}
	"`${Str.join_with($plural_words, "_")}`, or `${bare}_list`"
}

cookbook/roc/find_awkward_names/Passes.roc, 237 lines

## find_awkward_names' checks judged over what the whole read gathered, once every
## file is read (the Shale original's naming_passes.shale):
## `preposition_split`, from
## the trailing prepositions each file puts on its stems; `container` and a
## field's `short_name`, from the type and field names; `where_name`, from a
## file's `where` clauses; and the census of effects' first words that
## `words=1` prints. The launcher's header says what each check finds.
import lib.Finding
import lib.Text
import lib.Tree
import Facts
import Judge
import Reading
import Words

Passes := [].{

	## An effect's first word in the census: how many effects start with it
	## and what it says.
	Counted : { count : U64, verdict : Str }

	## What `preposition_split` finds in the definitions, in the order of
	## their files' paths and stems. `keywords` are each file's declared
	## keywords, by path.
	preposition_splits : List(Reading.Definition), Words.Lists, Dict(Str, List(Str)) -> List(Finding)
	preposition_splits = |definitions, lists, keywords| {
		var $groups = Dict.empty()
		var $shapes = Dict.empty()
		var $conventions = Set.empty()
		for definition in definitions {
			words = definition.name.drop_suffix("!").split_on("_")
			preposition = words.last() ?? ""
			is_judged = !(lists.fixed_names.contains(definition.name)) and !(definition.is_paired)
			if is_judged and words.len() > 1 and lists.prepositions.contains(preposition) {
				stem = Str.join_with(words.drop_last(1), "_")
				key = "${definition.path}|${stem}"
				group = $groups.get(key) ?? { path: definition.path, line: definition.line, stem, uses: Dict.empty() }
				if definition.is_annotation and definition.is_function_type {
					shape_key = "${definition.path}|${preposition}|${definition.first}|${definition.result}"
					stems = ($shapes.get(shape_key) ?? Set.empty()).insert(stem)
					$shapes = $shapes.insert(shape_key, stems)
					if stems.len() >= convention_stems {
						$conventions = $conventions.insert("${definition.path}|${preposition}")
					}
				}
				uses = if group.uses.contains(preposition) {
					group.uses
				} else {
					group.uses.insert(preposition, { name: definition.name, arity: definition.arity })
				}
				$groups = $groups.insert(key, { ..group, uses })
			}
		}
		Text.sort_bytewise($groups.keys()).map(
			|key| match $groups.get(key) {
				Ok(group) => split_findings(group, $conventions, keywords)
				Err(_) => []
			},
		).join()
	}

	## What `short_name` and `container` find in one type or field name.
	container_findings : Facts.Named, Words.Lists -> List(Finding)
	container_findings = |named, lists| {
		report = |check, what| { path: named.path, line: named.line, check, what }
		is_container_word = |word| lists.vague.contains(word) or lists.containers.contains(word)
		is_only_containers = !(named.words.is_empty()) and named.words.all(is_container_word)
		is_owned = named.words.any(|word| doc_says_whose(named.doc, word))
		# A field of a plain value (`entry : F64`) holds nothing a container
		# could.
		is_scalar = named.is_field and !(named.is_function) and scalar_types.contains(named.gives)
		var $found = []
		if named.is_field and named.name.count_utf8_bytes() == 1 and !(named.is_letter_of_set) {
			$found = $found.append(report("short_name", "the field `${named.name}` is one letter, read far from where it is set: name what it holds"))
		}
		if is_only_containers and !(is_owned) and !(is_scalar) {
			what = if named.is_field {
				"the field `"
			} else {
				"the type `"
			}
			$found = $found.append(report("container", "${what}${named.name}` is only container words: name it for what it holds, or say whose it is in its doc (`## A folder's entry`)"))
		}
		$found
	}

	## What `where_name` finds in one parsed file. `fixed_names` are the
	## methods Roc calls by name, which pass.
	where_name_findings : Str, List(Tree.Node), Set(Str) -> List(Finding)
	where_name_findings = |path, nodes, fixed_names| {
		is_where_method = |node| node.kind == "method" and node.parent > 0 and Tree.node_at(nodes, node.parent).kind == "where"
		nodes
			.keep_if(is_where_method)
			.keep_if(
				|node| {
					name = Tree.attribute(node, "name")
					name.drop_suffix("!").split_on("_").len() < 2 and !(fixed_names.contains(name))
				},
			)
			.map(
				|node| {
					name = Tree.attribute(node, "name")
					{ path, line: node.line, check: "where_name", what: "the `where` method `${name}` is one word, and a `where` clause matches by name alone: say what it is for (`scenery_height`, not `height`)" }
				},
			)
	}

	## Each first word the definitions' effects start with, counted, with
	## its verdict where the word first appears.
	census : List(Reading.Definition), Words.Lists -> Dict(Str, Passes.Counted)
	census = |definitions, lists| {
		var $counted = Dict.empty()
		for definition in definitions {
			is_effect = Judge.is_effectful(definition)
			if is_effect and !(definition.is_paired) and !(lists.fixed_names.contains(definition.name)) {
				act = Judge.act_of(definition.name.drop_suffix("!").split_on("_"), is_effect, lists)
				before = $counted.get(act.word) ?? { count: 0, verdict: act.verdict }
				$counted = $counted.insert(act.word, { ..before, count: before.count + 1 })
			}
		}
		$counted
	}

	## The census `words=1` prints: a line a word, the most used first, and
	## the summary's counts.
	census_lines : Dict(Str, Passes.Counted) -> { lines : List(Str), summary : Str }
	census_lines = |counted| {
		rows = counted.to_list().sort_with(
			|(word, row), (other_word, other_row)|
				if row.count > other_row.count {
					Before
				} else if row.count < other_row.count {
					After
				} else {
					Text.byte_order(word, other_word)
				},
		)
		row_lines = rows.map(|(word, row)| "${padded_left(row.count.to_str(), 4)} ${padded_right(word, 12)} ${row.verdict}")
		count_of = |counted_rows| counted_rows.map(|(_, row)| row.count).sum()
		total = count_of(rows)
		by_verdict = |verdict| count_of(rows.keep_if(|(_, row)| row.verdict == verdict))
		verdict_counts = ["verb", "participle", "vague", "asks", "refused"].map(|verdict| "${verdict} ${by_verdict(verdict).to_str()}")
		summary = "${total.to_str()} effects, ${rows.len().to_str()} first words; effects by verdict: ${Str.join_with(verdict_counts, ", ")}"
		{ lines: row_lines, summary }
	}
}

## A stem's first use of each trailing preposition, by the preposition.
Group : {
	path : Str,
	line : U64,
	stem : Str,
	uses : Dict(Str, { name : Str, arity : I64 }),
}

## How many stems of one shape make a preposition a file's convention.
convention_stems : U64
convention_stems = 3

## The pairs of opposite prepositions, sorted and joined by `|`.
opposite_pairs : List(Str)
opposite_pairs = ["after|before", "from|to", "with|without", "over|under"]

## A field of one of these holds one plain value, so `container` passes it.
scalar_types : List(Str)
scalar_types = ["U8", "U16", "U32", "U64", "U128", "I8", "I16", "I32", "I64", "I128", "F32", "F64", "Dec", "Str", "Bool"]

## The finding of one stem's group, if its prepositions split it.
split_findings : Group, Set(Str), Dict(Str, List(Str)) -> List(Finding)
split_findings = |group, conventions, keywords| {
	arities = group.uses.to_list().map(|(_, used)| used.arity).keep_if(|arity| arity >= 0)
	fewest = arities.min() ?? -1
	declared = keywords.get(group.path) ?? []
	split = Text.sort_bytewise(group.uses.keys()).keep_if(
		|preposition| {
			arity = (group.uses.get(preposition) ?? { name: "", arity: -1 }).arity
			is_from_worker = preposition == "from" and fewest >= 0 and arity > fewest
			is_convention = conventions.contains("${group.path}|${preposition}")
			!(is_from_worker) and !(is_convention) and !(declared.contains(preposition))
		},
	)
	names = split.map(|preposition| (group.uses.get(preposition) ?? { name: "", arity: -1 }).name)
	is_opposite_pair = split.len() == 2 and opposite_pairs.contains(Str.join_with(split, "|"))
	if split.len() > 1 and !(is_opposite_pair) {
		what = "`${group.stem}` takes ${split.len().to_str()} prepositions here (${Str.join_with(names, ", ")}): one relation keeps one preposition, or the names say how they differ"
		[{ path: group.path, line: group.line, check: "preposition_split", what }]
	} else {
		[]
	}
}

## Whether a doc says whose a container word is (`a folder's entry`, `a
## listing's entries`), in the word's singular or plural.
doc_says_whose : Str, Str -> Bool
doc_says_whose = |doc, word| {
	plain = [word, "${word}s"]
	from_ies = if word.ends_with("ies") {
		["${word.drop_suffix("ies")}y"]
	} else {
		[]
	}
	to_ies = if word.ends_with("y") {
		["${word.drop_suffix("y")}ies"]
	} else {
		[]
	}
	from_s = if word.ends_with("s") {
		[word.drop_suffix("s")]
	} else {
		[]
	}
	plain.concat(from_ies).concat(to_ies).concat(from_s).any(|form| doc.contains("'s ${form}"))
}

## The text with spaces before it to `width` bytes, kept whole when longer
## (Shale's `pad(text, -width)`).
padded_left : Str, U64 -> Str
padded_left = |text, width| {
	length = text.count_utf8_bytes()
	if length >= width {
		text
	} else {
		"${Str.repeat(" ", width - length)}${text}"
	}
}

## The text with spaces after it to `width` bytes (Shale's `pad(text,
## width)`).
padded_right : Str, U64 -> Str
padded_right = |text, width| {
	length = text.count_utf8_bytes()
	if length >= width {
		text
	} else {
		"${text}${Str.repeat(" ", width - length)}"
	}
}

cookbook/roc/find_awkward_names/Reading.roc, 334 lines

## What find_awkward_names reads of each file: a record for every top-level and module-member
## annotation and definition, leaving out the names the file's header
## dictates, and along the way the facts (Facts) the checks judged over the
## whole tree need.
import lib.Headers
import lib.Text
import lib.Tree
import Facts
import TypeText

Reading := [].{

	## A lambda's argument: its name (`""` for a pattern that is no plain
	## name), its line, and the checker's type of it (`""` for none).
	Parameter : { name : Str, line : U64, typed : Str }

	## A definition, from its annotation or its `name = ...`. An annotation
	## has `whole`, its type, and `result`, what it gives; a function's also
	## `first`, `arity` and `argument_types`, and an effect's the type names it
	## mentions and each argument's shape. A definition whose annotation is
	## just above it is paired, and the annotation then has its definition's
	## checker's type, callback and parameters.
	Definition : {
		path : Str,
		line : U64,
		name : Str,
		owner : Str,
		is_annotation : Bool,
		is_function_type : Bool,
		has_callback : Bool,
		is_paired : Bool,
		has_definition : Bool,
		has_doc : Bool,
		whole : Str,
		result : Str,
		first : Str,
		arity : I64,
		argument_types : List(Str),
		mentioned_types : Set(Str),
		arguments : List(TypeText.ArgumentShape),
		is_lambda : Bool,
		parameters : List(Reading.Parameter),
		recurses : Bool,
		typed : [Typed(Str), Untyped],
	}

	## A parsed file: its path, its tree and its text cut at each newline.
	FileRead : Facts.FileRead

	## The suffixes `worker_name` reports only on a definition that calls
	## itself, as they are ordinary words too.
	recursion_suffixes : List(Str)
	recursion_suffixes = ["step", "walk", "go"]

	## The file's definitions in file order, and the facts it adds.
	## `pattern_types` is the checker's type of each plain-name pattern, by
	## its node's place.
	file_definitions : Reading.FileRead, Dict(U64, Str) -> { definitions : List(Reading.Definition), facts : Facts.Gathered }
	file_definitions = |file, pattern_types| {
		nodes = file.nodes
		dictated = Set.from_list(Headers.header_names(nodes).dictated)
		is_kept = |definition| !(dictated.contains(definition.name) and definition.owner == "")
		var $facts = Facts.keywords_of(file)
		var $outer = []
		var $declaration_lines = []
		var $annotation_places = Dict.empty()
		var $definitions = []
		$at : U64
		var $at = 0
		for node in nodes {
			$at = $at + 1
			at = $at
			kind = node.kind
			is_outer = node.parent == 0 or (($outer.get(node.parent - 1) ?? Bool.False) and outer_kinds.contains(Tree.node_at(nodes, node.parent).kind))
			$outer = $outer.append(is_outer)
			is_declaration = is_outer and (kind == "s-type-anno" or kind == "s-type-decl")
			$declaration_lines = $declaration_lines.append(
				if is_declaration {
					node.line
				} else {
					0
				},
			)
			if is_outer and kind == "s-type-decl" {
				$facts = Facts.with_type_declaration(file, at, $facts)
			}
			if kind == "anno-record-field" {
				declaration_line = field_declaration_line(nodes, $declaration_lines, at)
				if declaration_line != 0 and Tree.attribute(node, "name") != "" {
					$facts = Facts.with_field(file, at, declaration_line, $facts)
				}
			}
			if is_outer and kind == "s-type-anno" {
				match annotation_definition(file, at) {
					Ok(definition) if is_kept(definition) => {
						$annotation_places = $annotation_places.insert(at, $definitions.len())
						$definitions = $definitions.append(definition)
					}
					_ => {}
				}
			}
			if is_outer and kind == "s-decl" {
				match value_definition(file, at, pattern_types) {
					Ok(definition) if is_kept(definition) => {
						above_place = $annotation_places.get(TypeText.previous_sibling(nodes, at))
						match above_place {
							Ok(place) => {
								above = definition_at($definitions, place)
								if above.name == definition.name {
									paired = with_definition(above, definition)
									$definitions = replaced($definitions, place, paired).append({ ..definition, is_paired: Bool.True })
								} else {
									$definitions = $definitions.append(definition)
								}
							}
							Err(_) => {
								$definitions = $definitions.append(definition)
							}
						}
					}
					_ => {}
				}
			}
		}
		{ definitions: $definitions, facts: $facts }
	}
}

## The kinds of node a definition may sit in and still be top-level or a
## module type's member, which `associated` holds.
outer_kinds : List(Str)
outer_kinds = ["file", "statements", "s-type-decl", "associated"]

definition_at : List(Reading.Definition), U64 -> Reading.Definition
definition_at = |definitions, place|
	match definitions.get(place) {
		Ok(found) => found
		Err(_) => crash "Reading: an annotation's place is past the definitions"
	}

## The definitions with the one at `place` replaced.
replaced : List(Reading.Definition), U64, Reading.Definition -> List(Reading.Definition)
replaced = |definitions, place, definition|
	match definitions.set(place, definition) {
		Ok(changed) => changed
		Err(_) => crash "Reading: an annotation's place is past the definitions"
	}

## The annotation `above` given what its definition says.
with_definition : Reading.Definition, Reading.Definition -> Reading.Definition
with_definition = |above, definition| {
	typed = match definition.typed {
		Typed(_) => definition.typed
		Untyped => above.typed
	}
	{
		..above,
		has_definition: Bool.True,
		typed,
		has_callback: above.has_callback or definition.has_callback,
		parameters: definition.parameters,
	}
}

## The line of the declaration that the record field at `at` belongs to, as
## `declaration_lines` holds it so far, or 0 when an expression, a pattern
## or a definition lies between them: the field is then a local's.
field_declaration_line : List(Tree.Node), List(U64), U64 -> U64
field_declaration_line = |nodes, declaration_lines, at| {
	var $up = Tree.node_at(nodes, at).parent
	while $up != 0 {
		node = Tree.node_at(nodes, $up)
		if node.kind.starts_with("e-") or node.kind.starts_with("p-") or node.kind == "s-decl" {
			return 0
		}
		if node.kind == "s-type-anno" or node.kind == "s-type-decl" {
			return declaration_lines.get($up - 1) ?? 0
		}
		$up = node.parent
	}
	0
}

## The name of the type declaration around node `at`, or `""` at the top
## level.
owner_of : List(Tree.Node), U64 -> Str
owner_of = |nodes, at| {
	var $up = Tree.node_at(nodes, at).parent
	while $up != 0 {
		node = Tree.node_at(nodes, $up)
		if node.kind == "s-type-decl" {
			return Tree.attribute(Tree.node_at(nodes, Tree.first_kid(node)), "name")
		}
		$up = node.parent
	}
	""
}

## Whether a `##` doc stands directly above line `line`.
has_doc_above : List(Str), U64 -> Bool
has_doc_above = |source_lines, line| line > 1 and Text.trim(Text.line_at(source_lines, line - 1)).starts_with("##")

## A record with nothing read yet, for the file's node at `at`.
blank_definition : Reading.FileRead, U64, Str -> Reading.Definition
blank_definition = |file, at, name| {
	node = Tree.node_at(file.nodes, at)
	{
		path: file.path,
		line: node.line,
		name,
		owner: owner_of(file.nodes, at),
		is_annotation: Bool.False,
		is_function_type: Bool.False,
		has_callback: Bool.False,
		is_paired: Bool.False,
		has_definition: Bool.False,
		has_doc: has_doc_above(file.source_lines, node.line),
		whole: "",
		result: "",
		first: "",
		arity: -1,
		argument_types: [],
		mentioned_types: Set.empty(),
		arguments: [],
		is_lambda: Bool.False,
		parameters: [],
		recurses: Bool.False,
		typed: Untyped,
	}
}

## The annotation at `at`, unless it is only a `where` clause.
annotation_definition : Reading.FileRead, U64 -> Try(Reading.Definition, [OnlyWhere])
annotation_definition = |file, at| {
	nodes = file.nodes
	node = Tree.node_at(nodes, at)
	type_at = match node.kids.first() {
		Ok(found) => found
		Err(_) => return Err(OnlyWhere)
	}
	type_node = Tree.node_at(nodes, type_at)
	if type_node.kind == "where" {
		return Err(OnlyWhere)
	}
	name = Tree.attribute(node, "name")
	whole = Tree.written_type(nodes, type_at)
	blank = { ..blank_definition(file, at, name), is_annotation: Bool.True, whole, result: whole }
	if type_node.kind != "ty-fn" {
		return Ok(blank)
	}
	is_effect = name.ends_with("!")
	arguments = type_node.kids.drop_last(1)
	Ok({
		..blank,
		is_function_type: Bool.True,
		arity: arguments.len().to_i64_wrap(),
		result: Tree.written_type(nodes, Tree.last_kid(type_node)),
		first: if type_node.kids.len() > 1 {
			Tree.written_type(nodes, Tree.first_kid(type_node))
		} else {
			""
		},
		argument_types: arguments.map(|argument| Tree.written_type(nodes, argument)),
		has_callback: arguments.any(|argument| TypeText.span_text(file.source_lines, Tree.node_at(nodes, argument)).contains("=>")),
		mentioned_types: if is_effect {
			TypeText.mentioned_type_names(nodes, type_at, Set.empty())
		} else {
			Set.empty()
		},
		arguments: if is_effect {
			arguments.map(|argument| TypeText.argument_shape(nodes, argument))
		} else {
			[]
		},
	})
}

## The definition `name = ...` at `at`, unless its pattern is no plain name.
value_definition : Reading.FileRead, U64, Dict(U64, Str) -> Try(Reading.Definition, [NoPlainName])
value_definition = |file, at, pattern_types| {
	nodes = file.nodes
	node = Tree.node_at(nodes, at)
	pattern_at = match node.kids.first() {
		Ok(found) => found
		Err(_) => return Err(NoPlainName)
	}
	pattern = Tree.node_at(nodes, pattern_at)
	if pattern.kind != "p-ident" {
		return Err(NoPlainName)
	}
	name = Tree.attribute(pattern, "raw")
	lambda = match node.kids.get(1) {
		Ok(value_at) if Tree.node_at(nodes, value_at).kind == "e-lambda" => Ok(Tree.node_at(nodes, value_at))
		_ => Err(NoLambda)
	}
	arguments = match lambda {
		Ok(lambda_node) =>
			lambda_node.kids
				.keep_if(|part| Tree.node_at(nodes, part).kind == "args")
				.map(|part| Tree.node_at(nodes, part).kids)
				.join()
		Err(_) => []
	}
	parameter_of = |argument| {
		argument_node = Tree.node_at(nodes, argument)
		parameter_name = if argument_node.kind == "p-ident" {
			Tree.attribute(argument_node, "raw")
		} else {
			""
		}
		typed = if parameter_name != "" {
			pattern_types.get(argument) ?? ""
		} else {
			""
		}
		{ name: parameter_name, line: argument_node.line, typed }
	}
	words = name.drop_suffix("!").split_on("_")
	recurses = words.len() > 1 and Reading.recursion_suffixes.contains(words.last() ?? "") and TypeText.calls_itself(nodes, at, name)
	Ok({
		..blank_definition(file, at, name),
		is_lambda: match lambda {
			Ok(_) => Bool.True
			Err(_) => Bool.False
		},
		parameters: arguments.map(parameter_of),
		has_callback: arguments.any(|argument| Tree.attribute(Tree.node_at(nodes, argument), "raw").ends_with("!")),
		recurses,
		typed: match pattern_types.get(pattern_at) {
			Ok(found) => Typed(found)
			Err(_) => Untyped
		},
	})
}

cookbook/roc/find_awkward_names/SelfTest.roc, 153 lines

## The recipe's self-test (the Shale original's naming_plants.shale),
## run after the checks over the plants in cookbook/roc/plants/find_awkward_names/ and its typed/
## folder: each plant is named for the check it holds, and that check must
## fire on it and on no other check's plant; a `quiet_*.roc` plant must draw
## no finding, and a plant named for no check is a failure; the census must
## give one known word of the plants per verdict its verdict; and two plants'
## findings must say something, or must not.
import pf.Shale
import lib.Finding
import lib.Text
import Passes

SelfTest := [].{

	## What the checks found over the plants: the paths read, the findings
	## reported, the census and the finding lines printed.
	Judged : {
		paths : List(Str),
		findings : List(Finding),
		census : Dict(Str, Passes.Counted),
		finding_lines : List(Str),
	}

	## The plants' folder.
	plants : Str
	plants = "cookbook:roc/plants/find_awkward_names/"

	## The plants' verdict printed, then a stop when any plant is wrong.
	run! : SelfTest.Judged, List(Str) => {}
	run! = |judged, checks| {
		failures = failures_of(judged, checks)
		for failure in failures {
			Shale.print!("FAIL ${failure}")
		}
		if !(failures.is_empty()) {
			Shale.fail!("find_awkward_names self_test: ${failures.len().to_str()} plants wrong")
		}
		Shale.print!("find_awkward_names (Roc) self_test: PASS (each check fires on its plants alone, the quiet_ plants on none, and the census gives each verdict its known word)")
	}
}

## Each way the run over the plants is wrong, as a line.
failures_of : SelfTest.Judged, List(Str) -> List(Str)
failures_of = |judged, checks| {
	fired = Set.from_list(judged.findings.map(|finding| "${finding.path}|${finding.check}"))
	var $failures = []
	for check in checks {
		$planted : U64
		var $planted = 0
		for path in judged.paths {
			is_its_plant = is_plant_for(plant_name(path), check)
			if is_its_plant {
				$planted = $planted + 1
			}
			did_fire = fired.contains("${path}|${check}")
			if is_its_plant and !(did_fire) {
				$failures = $failures.append("`${check}` does not fire on its plant ${path}")
			}
			if did_fire and !(is_its_plant) {
				$failures = $failures.append("`${check}` fires on ${path}, another check's plant")
			}
		}
		if $planted == 0 {
			$failures = $failures.append("`${check}` has no plant")
		}
	}
	# A plant named for no check could never fail.
	for path in judged.paths {
		name = plant_name(path)
		if !(name.starts_with("quiet_") or checks.any(|check| is_plant_for(name, check))) {
			$failures = $failures.append("${path}: a plant the table does not judge")
		}
	}
	for known in census_known {
		match judged.census.get(known.word) {
			Ok(counted) if counted.verdict != known.verdict => {
				$failures = $failures.append("the census calls `${known.word}` ${counted.verdict}, not ${known.verdict}")
			}
			Ok(_) => {}
			Err(_) => {
				$failures = $failures.append("the census has no `${known.word}`")
			}
		}
	}
	for expected in plant_says {
		at = "${SelfTest.plants}${expected.plant}:"
		var $is_said = Bool.False
		for line in judged.finding_lines {
			if line.starts_with(at) and line.contains(expected.says) {
				$is_said = Bool.True
			}
			if line.starts_with(at) and line.contains(expected.never) {
				$failures = $failures.append("${line}: says `${expected.never}`")
			}
		}
		if !($is_said) {
			$failures = $failures.append("${expected.plant}: no finding says `${expected.says}`")
		}
	}
	$failures
}

## The census's verdict for one known word of the plants per verdict.
census_known : List({ word : Str, verdict : Str })
census_known = [
	{ word: "read", verdict: "verb" },
	{ word: "held", verdict: "participle" },
	{ word: "process", verdict: "vague" },
	{ word: "links", verdict: "refused" },
]

## The plants whose finding must say something, or must not: `singular_list`
## offers no plural of an adjective, nor `phrase_name` of a preposition's
## noun.
plant_says : List({ plant : Str, says : Str, never : Str })
plant_says = [
	{ plant: "singular_list_adjective.roc", says: "has no noun", never: "stables" },
	{ plant: "phrase_name_list_holder.roc", says: "starts with a preposition, `by`", never: "by_slots" },
]

is_plant_for : Str, Str -> Bool
is_plant_for = |name, check| name == "${check}.roc" or name.starts_with("${check}_")

## A plant's name below the plants' folder. A typed plant is a CamelCase
## module (`typed/QuestionInferred.roc`), as is a plant another imports
## (`QuietDocShelf.roc`), and its name is read in snake case
## (`question_inferred.roc`).
plant_name : Str -> Str
plant_name = |path| {
	name = path.drop_prefix(SelfTest.plants).drop_prefix("typed/")
	match name.to_utf8().first() {
		Ok(byte) if Text.is_capital(byte) => snake_case(name)
		_ => name
	}
}

## A CamelCase file name in snake case: `_` before each capital but a first,
## and the capital made small.
snake_case : Str -> Str
snake_case = |name| {
	var $out = []
	for byte in name.to_utf8() {
		if Text.is_capital(byte) {
			if !($out.is_empty()) {
				$out = $out.append('_')
			}
			$out = $out.append(byte + 32)
		} else {
			$out = $out.append(byte)
		}
	}
	Str.from_utf8_lossy($out)
}

cookbook/roc/find_awkward_names/ShortNames.roc, 289 lines

## find_awkward_names' `short_name` for what a file binds inside its definitions:
## each local,
## parameter, match binding, record destructuring and `var` whose name, past
## a `$` or `_` and before a `!`, is one letter. A loop's variable, a
## coordinate, a colour's channels and a triangle's corners pass, as the
## launcher's header says.
import lib.Finding
import lib.Tree

ShortNames := [].{

	## Whether a name of one letter is a coordinate (`x`, `y`, `z`, and `w`
	## beside `x` and `y`), a colour's channel (`r`, `g`, `b`, and `a` beside
	## them) or a triangle's corner (`a`, `b` and `c`, all three), by
	## `siblings`, the names beside it.
	is_letter_of_set : Str, Set(Str) -> Bool
	is_letter_of_set = |name, siblings| {
		has_all = |names| names.all(|sibling| siblings.contains(sibling))
		if ["x", "y", "z"].contains(name) or (name == "w" and has_all(["x", "y"])) {
			Bool.True
		} else if ["a", "b", "c"].contains(name) and has_all(["a", "b", "c"]) {
			Bool.True
		} else {
			["r", "g", "b", "a"].contains(name) and has_all(["r", "g", "b"])
		}
	}

	## The one-letter bindings of the file at `path`, in the tree's order.
	findings : Str, List(Tree.Node) -> List(Finding)
	findings = |path, nodes| {
		tested = while_tested(nodes)
		vars = Set.from_list(nodes.keep_if(|node| node.kind == "s-var").map(|node| Tree.attribute(node, "name")))
		var $found = []
		$at : U64
		var $at = 0
		for node in nodes {
			$at = $at + 1
			name = name_bound_by(nodes, node)
			letters = if name == "" {
				""
			} else {
				without_marks(name)
			}
			if letters.count_utf8_bytes() == 1 {
				binding = { at: $at, name, letters, tested, vars }
				match judged_binding(nodes, binding) {
					Reported(what) => {
						why = "${what} `${name}` is one letter: name what it holds"
						$found = $found.append({ path, line: node.line, check: "short_name", what: why })
					}
					Passed => {}
				}
			}
		}
		$found
	}
}

## A binding of one letter: its node's place, its name, the name's letters,
## and the names a `while` tests and the `var`s the file declares.
Binding : { at : U64, name : Str, letters : Str, tested : Set(Str), vars : Set(Str) }

## What a one-letter binding is called when it is reported, or that it
## passes.
judged_binding : List(Tree.Node), Binding -> [Reported(Str), Passed]
judged_binding = |nodes, binding| {
	node = Tree.node_at(nodes, binding.at)
	is_var = node.kind == "s-var"
	holder = if node.kind == "p-ident" and Tree.node_at(nodes, node.parent).kind == "field" {
		Tree.node_at(nodes, node.parent).parent
	} else {
		node.parent
	}
	binder = binder_of(nodes, node.parent)
	binder_kind = if is_var {
		"s-var"
	} else {
		Tree.node_at(nodes, binder).kind
	}
	siblings = if is_var {
		Set.empty()
	} else {
		bound_siblings(nodes, holder)
	}
	is_record = Tree.node_at(nodes, holder).kind == "p-record"
	is_colour = ["r", "g", "b"].all(|channel| siblings.contains(channel))
	is_corner_outside_record = ["a", "b", "c"].contains(binding.letters) and !(is_record) and !(is_colour)
	is_reassigned_var = binding.name.starts_with("$") and binding.vars.contains(binding.name)
	skip = (binder_kind == "s-decl" and (is_outer_definition(nodes, binder) or is_reassigned_var))
		or (binder_kind == "s-var" and binding.tested.contains(binding.name))
		or binder_kind == "s-for"
		or (binder_kind == "e-lambda" and is_loop_lambda(nodes, binder))
		or (ShortNames.is_letter_of_set(binding.letters, siblings) and !(is_corner_outside_record))
	if skip {
		Passed
	} else if binder_kind == "s-decl" {
		Reported("the local")
	} else if binder_kind == "e-lambda" {
		Reported("the parameter")
	} else if binder_kind == "branch" {
		Reported("the match binding")
	} else if binder_kind == "s-var" {
		Reported("the var")
	} else {
		Reported("the binding")
	}
}

## The names a `while` tests, in any of the file's loops.
while_tested : List(Tree.Node) -> Set(Str)
while_tested = |nodes| {
	var $tested = Set.empty()
	for node in nodes {
		if node.kind == "s-while" {
			match node.kids.first() {
				Ok(condition) => {
					last = subtree_end(nodes, condition)
					var $place = condition
					while $place <= last {
						inner = Tree.node_at(nodes, $place)
						if inner.kind == "e-ident" {
							$tested = $tested.insert(Tree.attribute(inner, "raw"))
						}
						$place = $place + 1
					}
				}
				Err(_) => {}
			}
		}
	}
	$tested
}

## A name past its leading `$`s and `_`s and before a last `!`.
without_marks : Str -> Str
without_marks = |name| {
	bytes = name.to_utf8()
	start = bytes.find_first_index(|byte| byte != '$' and byte != '_') ?? bytes.len()
	Str.from_utf8_lossy(bytes.drop_first(start)).drop_suffix("!")
}

## The last node of the subtree at `at`: the tree is in order, each subtree
## running on while the depth is deeper than its root's.
subtree_end : List(Tree.Node), U64 -> U64
subtree_end = |nodes, at| {
	depth = Tree.node_at(nodes, at).depth
	var $stop = at
	while $stop < nodes.len() and Tree.node_at(nodes, $stop + 1).depth > depth {
		$stop = $stop + 1
	}
	$stop
}

## The kinds of node a pattern sits in on its way up to what binds it.
pattern_holders : List(Str)
pattern_holders = ["args", "field", "p-record", "p-tuple", "p-list", "p-tag", "p-as"]

## Up through the patterns from `start` to what binds them.
binder_of : List(Tree.Node), U64 -> U64
binder_of = |nodes, start| {
	var $binder = start
	while $binder > 0 and pattern_holders.contains(Tree.node_at(nodes, $binder).kind) {
		$binder = Tree.node_at(nodes, $binder).parent
	}
	$binder
}

## The name a node binds, `""` for none: a pattern's name, a record's pun
## (`{ x }`), a list's rest (`.. as rest`) and a `var`.
bound_name : List(Tree.Node), U64 -> Str
bound_name = |nodes, at| name_bound_by(nodes, Tree.node_at(nodes, at))

## The name the node `node` binds.
name_bound_by : List(Tree.Node), Tree.Node -> Str
name_bound_by = |nodes, node| {
	if node.kind == "p-ident" {
		Tree.attribute(node, "raw")
	} else if node.kind == "field" and node.kids.is_empty() and node.parent > 0 and Tree.node_at(nodes, node.parent).kind == "p-record" {
		Tree.attribute(node, "name")
	} else if node.kind == "p-list-rest" or node.kind == "s-var" {
		Tree.attribute(node, "name")
	} else {
		""
	}
}

## The names bound beside a binding in one pattern, `holder`'s: a lambda's
## parameters, a record's fields, a tuple's or a tag's parts. A record's
## field renamed (`{ y: q }`) binds its pattern, beside the record's others.
bound_siblings : List(Tree.Node), U64 -> Set(Str)
bound_siblings = |nodes, holder| {
	var $names = Set.empty()
	for kid in Tree.node_at(nodes, holder).kids {
		name = bound_name(nodes, kid)
		if name != "" {
			$names = $names.insert(name)
		}
		kid_node = Tree.node_at(nodes, kid)
		if kid_node.kind == "field" {
			for inner in kid_node.kids {
				inner_name = bound_name(nodes, inner)
				if inner_name != "" {
					$names = $names.insert(inner_name)
				}
			}
		}
	}
	$names
}

## The kinds of node a definition may sit in and still be top-level or a
## module type's member.
outer_kinds : List(Str)
outer_kinds = ["file", "statements", "s-type-decl", "associated"]

## Whether a definition at `at` is top-level or a module type's member, its
## ancestors all of the outer kinds: its name is judged as a definition's.
is_outer_definition : List(Tree.Node), U64 -> Bool
is_outer_definition = |nodes, at| {
	var $up = Tree.node_at(nodes, at).parent
	while $up > 0 {
		node = Tree.node_at(nodes, $up)
		if !(outer_kinds.contains(node.kind)) {
			return Bool.False
		}
		$up = node.parent
	}
	Bool.True
}

## The list methods whose one-line lambda is a loop's body, so its
## parameters are loop variables.
loop_methods : List(Str)
loop_methods = [
	"map",
	"map2",
	"map3",
	"map_with_index",
	"map_try",
	"keep_if",
	"drop_if",
	"keep_oks",
	"keep_errs",
	"walk",
	"walk_backwards",
	"walk_until",
	"walk_with_index",
	"walk_try",
	"any",
	"all",
	"count_if",
	"find_first",
	"find_last",
	"find_first_index",
	"find_last_index",
	"sort_with",
	"join_map",
	"for_each!",
	"for_each_try!",
	"walk!",
	"walk_try!",
]

## Whether the lambda at `at` is a loop's body: on one line, and the direct
## argument of a list method, as a method call or a module's
## (`List.map(xs, |x| ...)`).
is_loop_lambda : List(Tree.Node), U64 -> Bool
is_loop_lambda = |nodes, at| {
	lambda = Tree.node_at(nodes, at)
	if lambda.line != lambda.end_line {
		return Bool.False
	}
	holder = Tree.node_at(nodes, lambda.parent)
	if holder.kind == "args" and Tree.node_at(nodes, holder.parent).kind == "e-method-call" {
		method = Tree.attribute(Tree.node_at(nodes, holder.parent), "method")
		return loop_methods.contains(method.drop_prefix("."))
	}
	if holder.kind != "e-apply" or holder.kids.first() == Ok(at) {
		return Bool.False
	}
	callee = Tree.node_at(nodes, Tree.first_kid(holder))
	if callee.kind != "e-ident" {
		return Bool.False
	}
	match Tree.attribute(callee, "raw").split_on(".") {
		["List", method] => loop_methods.contains(method)
		_ => Bool.False
	}
}

cookbook/roc/find_awkward_names/Types.roc, 105 lines

## The effects of a recipe's `types=1`: the tree's Roc found, and roc-types
## (Roc's own checker, https://github.com/showell/roc-types) run on each app
## of `root=`, its pin held to the tree's Roc. Reading and joining its output
## is cookbook/roc/lib/'s RocTypes; this file is the same in check_how_failure_is_reported,
## find_awkward_names, find_functions_and_parameters_that_dont_earn_their_keep and
## find_uses_after_a_consume, since a package reaches no effect.
import pf.Shale
import lib.RocTypes
import lib.Text

Types := [].{

	## The OS path of the tree's Roc: the pin in `roc-version` where the run
	## starts, or the self-test's pin, which cookbook/roc/pinned.shale names.
	## `who` names the recipe in a refusal.
	roc_bin! : Str, Bool => Str
	roc_bin! = |who, self_test| {
		pin = if self_test {
			pinned = read_text!(who, "cookbook:roc/pinned.shale")
			must!(RocTypes.self_test_pin(pinned).map_err(|_| "${who}: cookbook/roc/pinned.shale names no SELF_TEST_PIN"))
		} else if Shale.exists!("roc-version") {
			Text.trim(read_text!(who, "roc-version"))
		} else {
			must!(Err("${who}: no roc-version where the run starts: run it from the repository's root, whose roc-version pins its Roc"))
		}
		roc = RocTypes.roc_of_pin(pin)
		if !(Shale.exists!(roc)) {
			must!(Err("${who}: no ${roc}: install Roc ${pin} into ~/tools/roc-${pin}/ (roc-apps's toolchain release carries it)"))
		}
		real = Shale.real!(roc)
		said = Shale.run!({ argv: [real, "version"], keep: Whole(4000), timeout_ms: 30000, want: "" })
		if Text.trim(said.out) != "Roc compiler version ${pin}" {
			must!(Err("${who}: ${roc} says ${Text.trim(said.out)}, not Roc compiler version ${pin}"))
		}
		real
	}

	## The types of the nodes of `kind` in the files `paths`, from roc-types
	## run on each app of `root` with the Roc at `roc`, and a line for each
	## file no app reaches, except those in `exempt`.
	gather! : { who : Str, kind : RocTypes.Kind, root : Str, roc : Str, paths : List(Str), exempt : Set(Str) } => { typing : RocTypes.Typing, unreached : List(Str) }
	gather! = |asked| {
		roots = must!(RocTypes.root_apps(asked.who, asked.root))
		var $by_module = Dict.empty()
		for root in roots {
			got = modules_of!(root, asked.roc)
			$by_module = RocTypes.joined($by_module, got, asked.kind)
			for warning in got.warnings {
				Shale.print!("${asked.who}: roc-types ${root}: ${warning}")
			}
		}
		var $named = []
		for path in asked.paths {
			$named = $named.append({ path, real: Shale.real!(path) })
		}
		RocTypes.typing_of({ by_module: $by_module, named: $named, exempt: asked.exempt, roots })
	}
}

## The modules roc-types reports for the app `root`, built with the Roc at
## `roc`, or a stop: roc-types missing, of another format, built for another
## Roc, or refusing the app.
modules_of! : Str, Str => RocTypes.Modules
modules_of! = |root, roc| {
	pinned = RocTypes.pinned_checker(roc) ?? RocTypes.default_checker
	exe = if Shale.exists!(pinned) {
		pinned
	} else {
		RocTypes.default_checker
	}
	if !(Shale.exists!(exe)) {
		Shale.fail!("`roc_types`: no ${exe}: ${RocTypes.install_hint}")
	}
	ran = Shale.run!({
		argv: [Shale.real!(exe), Shale.real!(root)],
		keep: Whole(64000000),
		timeout_ms: 300000,
		want: "",
	})
	output_lines = Text.lines(ran.out)
	pin = must!(RocTypes.pin_of(output_lines, root))
	own = RocTypes.roc_of_pin(pin)
	if !(Shale.exists!(own)) or Shale.real!(own) != roc {
		Shale.fail!(RocTypes.another_compiler(pin, root, roc))
	}
	must!(RocTypes.modules_ran(output_lines, ran.code, root))
}

read_text! : Str, Str => Str
read_text! = |who, path|
	match Shale.read!(path) {
		Found(text) => text
		Missing => must!(Err("${who}: no ${path}"))
	}

## What `tried` holds, or the run stopped with its refusal.
must! : Try(a, Str) => a
must! = |tried|
	match tried {
		Ok(value) => value
		Err(why) => {
			Shale.fail!(why)
			crash "Types: Shale.fail! returned"
		}
	}

cookbook/roc/find_awkward_names/Words.roc, 206 lines

## The word lists find_awkward_names judges names by, read from their one home each:
## cookbook/words/ (verbs, participles, the vague and container words,
## prepositions, namespaces, Roc's own words and the numbers, list names,
## world verbs, cited sources), a project's `terms=` file, the house style's
## checks from cookbook/roc/house.shale and the methods Roc calls by name
## from cookbook/roc/lib/'s Headers. Each refusal is worded as the Shale
## original's readers worded it.
import pf.Shale
import lib.Headers
import lib.Text

Words := [].{

	## A project's terms: each term's element type (`""` for none) and its
	## words, by the term.
	Terms : {
		lists : Dict(Str, Str),
		words : Dict(Str, List(Str)),
	}

	## Every table the checks read.
	Lists : {
		verbs : Set(Str),
		participles : Set(Str),
		ed_verbs : Set(Str),
		vague : Set(Str),
		containers : Set(Str),
		prepositions : Set(Str),
		world_verbs : Set(Str),
		namespaces : Dict(Str, Set(Str)),
		taken : Dict(Str, Str),
		list_names : Dict(Str, Str),
		terms : Words.Terms,
		fixed_names : Set(Str),
	}

	## The tables, read in the Shale original's order, and the verbs held to
	## reading as no participle. `terms_file` is `""` for none.
	read! : Str => Words.Lists
	read! = |terms_file| {
		verbs = Words.word_set!("cookbook:words/verbs.txt")
		participles = Words.word_set!("cookbook:words/participles.txt")
		ed_verbs = Words.word_set!("cookbook:words/ed_verbs.txt")
		vague = Words.word_set!("cookbook:words/vague.txt")
		containers = Words.word_set!("cookbook:words/containers.txt")
		prepositions = Words.word_set!("cookbook:words/prepositions.txt")
		namespaces = namespace_instructions!("namespaces.txt")
		taken = taken_word_kinds!("taken.txt")
		list_names = list_name_kinds!("list_names.txt")
		world_verbs = Words.word_set!("cookbook:words/world_verbs.txt")
		terms = project_terms!(terms_file)
		for word in word_list_lines!("cookbook:words/verbs.txt") {
			if Words.reads_as_participle(word, participles, ed_verbs) {
				Shale.fail!("find_awkward_names: `${word}` is in cookbook/words/verbs.txt and reads as a participle, which would make its effects states")
			}
		}
		fixed_names = Headers.language_fixed_names
		{ verbs, participles, ed_verbs, vague, containers, prepositions, world_verbs, namespaces, taken, list_names, terms, fixed_names }
	}

	## A list of one word a line, as a set. A word listed twice, or a line of
	## two words, stops the run.
	word_set! : Str => Set(Str)
	word_set! = |path| {
		if !(Shale.exists!(path)) {
			Shale.fail!("no word list ${path}")
		}
		var $set = Set.empty()
		for word in word_list_lines!(path) {
			if word.contains(" ") or $set.contains(word) {
				Shale.fail!("${path}: `${word}` is no single new word")
			}
			if word != "" {
				$set = $set.insert(word)
			}
		}
		$set
	}

	## Whether a word reads as a past participle: an irregular one of
	## participles.txt, or a word past three letters ending in `ed` that
	## ed_verbs.txt doesn't list.
	reads_as_participle : Str, Set(Str), Set(Str) -> Bool
	reads_as_participle = |word, participles, ed_verbs|
		if participles.contains(word) {
			Bool.True
		} else {
			word.count_utf8_bytes() > 3 and word.ends_with("ed") and !(ed_verbs.contains(word))
		}

	## The checks cookbook/roc/house.shale names as our house style for
	## find_awkward_names, its one home.
	house_style! : {} => List(Str)
	house_style! = |{}| {
		text = read_text!("cookbook:roc/house.shale")
		match Shale.re_find!(text, "\n  find_awkward_names = \\{([^}]*)\\}") {
			Found(matched) => Shale.re_find_all!(matched.groups.first() ?? "", "\"([^\"]+)\"").map(|quoted| quoted.groups.first() ?? "")
			NoMatch => {
				Shale.fail!("find_awkward_names: cookbook/roc/house.shale's HOUSE_CHECKS names no find_awkward_names")
				[]
			}
		}
	}
}

## A file's text, or a stop naming it.
read_text! : Str => Str
read_text! = |path|
	match Shale.read!(path) {
		Found(text) => text
		Missing => {
			Shale.fail!("no word list ${path}")
			""
		}
	}

## The lines of a word list, any note after `--` cut off, trimmed.
word_list_lines! : Str => List(Str)
word_list_lines! = |path| Text.lines(read_text!(path)).map(|line| Text.trim(Text.before_first(line, "--")))

## namespaces.txt: a prefix a line, then the namespace's own instructions
## (`port in out`), as the set of each prefix's instructions.
namespace_instructions! : Str => Dict(Str, Set(Str))
namespace_instructions! = |file| {
	var $by_prefix = Dict.empty()
	for line in word_list_lines!("cookbook:words/${file}") {
		match Text.words(line) {
			[prefix, .. as instructions] => {
				if $by_prefix.contains(prefix) {
					Shale.fail!("find_awkward_names: cookbook/words/${file}: `${prefix}` twice")
				}
				$by_prefix = $by_prefix.insert(prefix, Set.from_list(instructions))
			}
			[] => {}
		}
	}
	$by_prefix
}

## taken.txt: a word a line, then its kind, `roc` or `cardinal`.
taken_word_kinds! : Str => Dict(Str, Str)
taken_word_kinds! = |file| {
	var $kinds = Dict.empty()
	for line in word_list_lines!("cookbook:words/${file}") {
		said = Text.words(line)
		if !(said.is_empty()) {
			match said {
				[word, kind] if (kind == "roc" or kind == "cardinal") and !($kinds.contains(word)) => {
					$kinds = $kinds.insert(word, kind)
				}
				_ => Shale.fail!("find_awkward_names: cookbook/words/${file}: `${Str.join_with(said, " ")}` is no new word with its kind, `roc` or `cardinal`")
			}
		}
	}
	$kinds
}

## list_names.txt: a word a line, then its kind, `many`, `one`, `after`,
## `accumulator` or `adjective`.
list_name_kinds! : Str => Dict(Str, Str)
list_name_kinds! = |file| {
	known_kinds = ["many", "one", "after", "accumulator", "adjective"]
	var $kinds = Dict.empty()
	for line in word_list_lines!("cookbook:words/${file}") {
		said = Text.words(line)
		if !(said.is_empty()) {
			match said {
				[word, kind] if known_kinds.contains(kind) and !($kinds.contains(word)) => {
					$kinds = $kinds.insert(word, kind)
				}
				_ => Shale.fail!("find_awkward_names: cookbook/words/${file}: `${Str.join_with(said, " ")}` is no new word with its kind, `many`, `one`, `after`, `accumulator` or `adjective`")
			}
		}
	}
	$kinds
}

## A project's own terms, none for `""`: a term a line, its words joined by
## `_`, then after a `:` the element type of the list it names.
project_terms! : Str => Words.Terms
project_terms! = |path| {
	var $terms = { lists: Dict.empty(), words: Dict.empty() }
	if path == "" {
		return $terms
	}
	if !(Shale.exists!(path)) {
		Shale.fail!("find_awkward_names: terms=${path}: no such file")
	}
	for line in word_list_lines!(path) {
		if line != "" {
			parts = line.split_on(":")
			term = Text.trim(parts.first() ?? "")
			element = Text.trim(parts.get(1) ?? "")
			is_bad_element = element != "" and !(Shale.re_match!(element, "^[A-Z][A-Za-z0-9]*$"))
			is_bad_term = !(Shale.re_match!(term, "^[a-z][a-z0-9]*(_[a-z0-9]+)*$"))
			if parts.len() > 2 or is_bad_term or is_bad_element or $terms.lists.contains(term) {
				Shale.fail!("find_awkward_names: ${path}: `${line}` is no new term, `word` or `word: Type`")
			}
			$terms = {
				lists: $terms.lists.insert(term, element),
				words: $terms.words.insert(term, term.split_on("_")),
			}
		}
	}
	$terms
}

cookbook/roc/find_awkward_names/TypeText.roc, 306 lines

## What find_awkward_names reads of a type, in the tree or written as text
## a tag union's tags, an argument's shape, the types an
## annotation mentions, a function type's parts, a `Try`'s success and a
## list's element, a tag's first word and words joined as a type's name; and
## where a node sits: its source text, the sibling before it, and whether a
## definition calls itself.
import lib.Text
import lib.Tree

TypeText := [].{

	## A tag union's tag names (`Unpinned` for `Unpinned(Str)` too), and
	## whether any tag carries a payload.
	Union : { names : List(Str), has_payload : Bool }

	## An argument's type as `command_tense` and `mixed_tense` need it: a tag
	## union written in place, a named type by its last part, or neither; and
	## whether it was a `List` of that.
	ArgumentShape : {
		shape : [Written(TypeText.Union), Named(Str), Unread],
		is_list : Bool,
	}

	## A function type's parts as text: whether the type is a function, the
	## text before its arrow and the text after it, its whole text when it is
	## no function.
	Parts : { is_function : Bool, arguments : Str, result : Str }

	## The tags of the tag union at `at`.
	union_shape : List(Tree.Node), U64 -> TypeText.Union
	union_shape = |nodes, at| {
		var $names = []
		var $has_payload = Bool.False
		for part in Tree.node_at(nodes, at).kids {
			part_node = Tree.node_at(nodes, part)
			if part_node.kind == "tags" {
				for tag in part_node.kids {
					tag_node = Tree.node_at(nodes, tag)
					name = if tag_node.kind == "ty-apply" {
						$has_payload = Bool.True
						Tree.attribute(Tree.node_at(nodes, Tree.first_kid(tag_node)), "name")
					} else {
						Tree.attribute(tag_node, "name")
					}
					if name != "" {
						$names = $names.append(name)
					}
				}
			}
		}
		{ names: $names, has_payload: $has_payload }
	}

	## The shape of the argument type at `at`; a `List(T)` gives `T`'s.
	argument_shape : List(Tree.Node), U64 -> TypeText.ArgumentShape
	argument_shape = |nodes, at| {
		node = Tree.node_at(nodes, at)
		unread = { shape: Unread, is_list: Bool.False }
		if node.kind == "ty-tag-union" {
			{ shape: Written(TypeText.union_shape(nodes, at)), is_list: Bool.False }
		} else if node.kind == "ty-apply" {
			match node.kids {
				[head, element] if Tree.attribute(Tree.node_at(nodes, head), "name") == "List" =>
					{ ..TypeText.argument_shape(nodes, element), is_list: Bool.True }
				_ => unread
			}
		} else {
			name = Tree.attribute(node, "name")
			if name == "" {
				unread
			} else {
				{ shape: Named(Tree.last_part(name)), is_list: Bool.False }
			}
		}
	}

	## The names of the types the type at `at` mentions, each by its last
	## part, added to `into`.
	mentioned_type_names : List(Tree.Node), U64, Set(Str) -> Set(Str)
	mentioned_type_names = |nodes, at, into| {
		node = Tree.node_at(nodes, at)
		name = Tree.attribute(node, "name")
		here = if node.kind.starts_with("ty") and name != "" {
			into.insert(Tree.last_part(name))
		} else {
			into
		}
		node.kids.fold(here, |names, kid| TypeText.mentioned_type_names(nodes, kid, names))
	}

	## The first argument in a function type's argument text, `a, b`.
	first_argument : Str -> Str
	first_argument = |arguments| {
		bytes = arguments.to_utf8()
		$depth : I64
		var $depth = 0
		$at : U64
		var $at = 0
		for byte in bytes {
			$depth = $depth + depth_change(byte)
			if $depth == 0 and byte == ',' {
				return Text.trim(Str.from_utf8_lossy(bytes.take_first($at)))
			}
			$at = $at + 1
		}
		Text.trim(arguments)
	}

	## `Try(Fraction, [OutOfRange])` gives `Fraction`, and any other type
	## itself, trimmed.
	success_type : Str -> Str
	success_type = |written| {
		text = Text.trim(written)
		if text.starts_with("Try(") and text.ends_with(")") {
			TypeText.first_argument(inside(text, 4))
		} else {
			text
		}
	}

	## The element type's text of a `List(...)` or a `Try` of one.
	list_element : Str -> Try(Str, [NoList])
	list_element = |written| {
		text = TypeText.success_type(written)
		if text.starts_with("List(") and text.ends_with(")") {
			Ok(inside(text, 5))
		} else {
			Err(NoList)
		}
	}

	## The leading run of name bytes of a type's text (`A-Z`, `a-z`, `0-9`,
	## `_`, `.`), `""` when it starts with none.
	type_head : Str -> Str
	type_head = |text| {
		bytes = text.to_utf8()
		length = bytes.find_first_index(|byte| !(is_type_name_byte(byte))) ?? bytes.len()
		Str.from_utf8_lossy(bytes.take_first(length))
	}

	## The last word of a type's text, or `""` for one with no name:
	## `Shapes.RoundShape(a)` gives `shape`.
	element_word : Str -> Str
	element_word = |element| {
		head = TypeText.type_head(element)
		Text.name_words(Tree.last_part(head)).last() ?? ""
	}

	## Words joined as one type name: `rounded`, `rectangle` gives
	## `RoundedRectangle`.
	camel_case : List(Str) -> Str
	camel_case = |words| Str.join_with(words.map(capitalized), "")

	## A tag's first word, lowercased: `Unpinned` gives `unpinned`, `AddedTo`
	## gives `added`.
	tag_first_word : Str -> Str
	tag_first_word = |tag| {
		bytes = tag.to_utf8()
		match bytes {
			[first, .. as rest] => {
				length = rest.find_first_index(Text.is_capital) ?? rest.len()
				Text.lower(Str.from_utf8_lossy([first].concat(rest.take_first(length))))
			}
			[] => ""
		}
	}

	## A type's text as its parts: a function when an arrow stands outside
	## every bracket, once any `where` clause is dropped.
	parts_of : Str -> TypeText.Parts
	parts_of = |written| {
		bytes = written.to_utf8()
		body = bytes.take_first(where_start(bytes))
		$depth : I64
		var $depth = 0
		$at : U64
		var $at = 0
		while $at + 1 < body.len() {
			byte = body.get($at) ?? 0
			$depth = $depth + depth_change(byte)
			is_arrow = (byte == '-' or byte == '=') and (body.get($at + 1) ?? 0) == '>'
			if $depth == 0 and is_arrow {
				return {
					is_function: Bool.True,
					arguments: Text.trim(Str.from_utf8_lossy(body.take_first($at))),
					result: Text.trim(Str.from_utf8_lossy(body.drop_first($at + 2))),
				}
			}
			$at = $at + 1
		}
		{ is_function: Bool.False, arguments: "", result: Text.trim(Str.from_utf8_lossy(body)) }
	}

	## The source text of a node, from the file's lines: its end column is
	## one past its last byte.
	span_text : List(Str), Tree.Node -> Str
	span_text = |source_lines, node|
		if node.line == 0 {
			""
		} else if node.line == node.end_line {
			columns(Text.line_at(source_lines, node.line), node.column, node.end_column)
		} else {
			first = columns(Text.line_at(source_lines, node.line), node.column, Text.line_at(source_lines, node.line).count_utf8_bytes() + 1)
			middle = source_lines.sublist({ start: node.line, len: node.end_line - node.line - 1 })
			last = columns(Text.line_at(source_lines, node.end_line), 1, node.end_column)
			Str.join_with([first].concat(middle).append(last), "\n")
		}

	## The place of the sibling just before the node at `at`, or 0.
	previous_sibling : List(Tree.Node), U64 -> U64
	previous_sibling = |nodes, at| {
		parent = Tree.node_at(nodes, at).parent
		if parent == 0 {
			return 0
		}
		$previous : U64
		var $previous = 0
		for kid in Tree.node_at(nodes, parent).kids {
			if kid == at {
				return $previous
			}
			$previous = kid
		}
		0
	}

	## Whether the definition at `at` names `name` in its body, as an
	## identifier (`name`, `Tree.name`) or a method call. A node's
	## descendants follow it, each deeper than it.
	calls_itself : List(Tree.Node), U64, Str -> Bool
	calls_itself = |nodes, at, name| {
		depth = Tree.node_at(nodes, at).depth
		var $place = at + 1
		while $place <= nodes.len() and Tree.node_at(nodes, $place).depth > depth {
			node = Tree.node_at(nodes, $place)
			if node.kind == "e-ident" {
				raw = Tree.attribute(node, "raw")
				if raw == name or raw.ends_with(".${name}") {
					return Bool.True
				}
			}
			if node.kind == "e-method-call" and Tree.attribute(node, "method") == name {
				return Bool.True
			}
			$place = $place + 1
		}
		Bool.False
	}
}

## How a byte moves the bracket depth.
depth_change : U8 -> I64
depth_change = |byte|
	if byte == '(' or byte == '[' or byte == '{' {
		1
	} else if byte == ')' or byte == ']' or byte == '}' {
		-1
	} else {
		0
	}

## The bytes before ` where ` outside every bracket, or all of them.
where_start : List(U8) -> U64
where_start = |bytes| {
	clause = " where ".to_utf8()
	$depth : I64
	var $depth = 0
	$at : U64
	var $at = 0
	for byte in bytes {
		$depth = $depth + depth_change(byte)
		if $depth == 0 and bytes.sublist({ start: $at, len: clause.len() }) == clause {
			return $at
		}
		$at = $at + 1
	}
	bytes.len()
}

## A text between its first `opening` bytes and its last byte.
inside : Str, U64 -> Str
inside = |text, opening| {
	length = text.count_utf8_bytes()
	Text.bytes_of(text, { start: opening, count: length - opening - 1 })
}

## Shale's `sub(line, from, to - 1)`: the bytes from column `from` to before
## column `to`, both counted from 1, `""` when none lie between.
columns : Str, U64, U64 -> Str
columns = |line, from, to|
	if to <= from or from == 0 {
		""
	} else {
		Text.bytes_of(line, { start: from - 1, count: to - from })
	}

is_type_name_byte : U8 -> Bool
is_type_name_byte = |byte| Text.is_capital(byte) or Text.is_small_letter(byte) or Text.is_digit(byte) or byte == '_' or byte == '.'

## A word with its first byte made a capital, as Shale's `upper` does.
capitalized : Str -> Str
capitalized = |word|
	match word.to_utf8() {
		[first, .. as rest] if Text.is_small_letter(first) => Str.from_utf8_lossy([first - 32].concat(rest))
		_ => word
	}

cookbook/roc/find_awkward_names/Makers.roc, 122 lines

## What find_awkward_names' `phrase_name` passes as a maker: a constructor that gives
## its own module's type, a
## conversion (`to_*`, `into_*`, and a `from_*` that takes or gives its
## module's type, or sits in a module with no type of its own), and a
## changed copy (`with_*`, `without_*` giving its first argument's type).
import lib.Text
import lib.Tree
import Facts
import Reading
import TypeText

Makers := [].{

	## What a definition's type says: whether it is a function, its first
	## argument's type, what it gives, whether its type is known at all, and
	## the note a finding adds when the type is the checker's.
	Signature : {
		is_function : Bool,
		first : Str,
		result : Str,
		is_known : Bool,
		source_note : Str,
	}

	## Whether a function named `words`, whose first word is a preposition,
	## reads as a constructor, a conversion or a changed copy.
	reads_as_maker : Reading.Definition, List(Str), Makers.Signature, Facts.Gathered, Set(Str) -> Bool
	reads_as_maker = |definition, words, signature, facts, prepositions| {
		word = words.first() ?? ""
		if ["into", "to"].contains(word) {
			Bool.True
		} else if ["with", "without"].contains(word) and signature.result == signature.first {
			Bool.True
		} else if word == "from" {
			is_from_conversion(definition, words, signature, facts, prepositions)
		} else {
			constructor_words.contains(word) and is_own_type(definition, TypeText.success_type(signature.result), facts)
		}
	}
}

## The first words a constructor may start with: the ones constructors use in
## safari, roc-chat and roc-markdown (`Clock.at_step`, `Dm.between`,
## `SignedIn.by_session`, `MdText.for_input`, `Name.of_strict`,
## `Directory.with_founder`).
constructor_words : List(Str)
constructor_words = ["at", "between", "by", "for", "of", "with"]

## Whether `written` names the module the definition is in, a type declared
## in its file, or the type it is a member of. Type arguments don't count.
is_own_type : Reading.Definition, Str, Facts.Gathered -> Bool
is_own_type = |definition, written, facts| {
	head = TypeText.type_head(written)
	if head == "" {
		return Bool.False
	}
	parts = head.split_on(".")
	first_part = parts.first() ?? ""
	last_part = parts.last() ?? ""
	if parts.len() == 1 and facts.type_names.contains("${definition.path}|${first_part}") {
		Bool.True
	} else {
		first_part == Tree.module_name(definition.path) or first_part == definition.owner or last_part == definition.owner
	}
}

## Whether `written` names its module's own type anywhere in it: each run
## that starts with a capital at a word's start.
mentions_own_type : Reading.Definition, Str, Facts.Gathered -> Bool
mentions_own_type = |definition, written, facts|
	capital_runs(written).any(|run| is_own_type(definition, run, facts))

## Each run of name bytes (`A-Z`, `a-z`, `0-9`, `_`, `.`) that starts with a
## capital no word byte stands before, left to right.
capital_runs : Str -> List(Str)
capital_runs = |text| {
	bytes = text.to_utf8()
	var $runs = []
	$at : U64
	var $at = 0
	while $at < bytes.len() {
		byte = bytes.get($at) ?? 0
		before = if $at == 0 {
			' '
		} else {
			bytes.get($at - 1) ?? ' '
		}
		if Text.is_capital(byte) and !(is_word_byte(before)) {
			run = TypeText.type_head(Str.from_utf8_lossy(bytes.drop_first($at)))
			$runs = $runs.append(run)
			$at = $at + run.count_utf8_bytes()
		} else {
			$at = $at + 1
		}
	}
	$runs
}

is_word_byte : U8 -> Bool
is_word_byte = |byte| Text.is_capital(byte) or Text.is_small_letter(byte) or Text.is_digit(byte) or byte == '_'

## Whether the file at `path` declares one type, `[].{ ... }`, which holds
## the module's functions and has no values of its own.
has_no_type_of_its_own : Str, Facts.Gathered -> Bool
has_no_type_of_its_own = |path, facts|
	match facts.type_kinds.get(path) ?? [] {
		[is_holder] => is_holder
		_ => Bool.False
	}

## Whether a function named `words`, whose first word is `from`, reads as a
## conversion.
is_from_conversion : Reading.Definition, List(Str), Makers.Signature, Facts.Gathered, Set(Str) -> Bool
is_from_conversion = |definition, words, signature, facts, prepositions| {
	gives = TypeText.success_type(signature.result)
	if mentions_own_type(definition, signature.first, facts) or mentions_own_type(definition, gives, facts) {
		Bool.True
	} else {
		second = words.get(1) ?? ""
		signature.is_known and has_no_type_of_its_own(definition.path, facts) and words.len() > 1 and !(prepositions.contains(second))
	}
}

Shale original

cookbook/roc/hunt_names.shale, 718 lines, at a69380e1

The libraries it loads: cookbook/findings.shale (21 lines), cookbook/roc/parsed.shale (34 lines), cookbook/roc/pinned.shale (20 lines), cookbook/roc/types.shale (301 lines), cookbook/roc/declared.shale (1,075 lines), cookbook/roc/headers.shale (96 lines), cookbook/roc/house.shale (46 lines), cookbook/roc/doc_names.shale (195 lines), cookbook/roc/naming_plants.shale (65 lines), cookbook/roc/naming_passes.shale (146 lines).

-- This recipe looks for awkward names in every .roc file of a tree: an
-- effect named like a state, a question that returns no `Bool`, a name made
-- only of vague words, and the other checks below. A finding is a question
-- for the reader, not a verdict. The recipe reads the top-level definitions
-- and the members of module types (`Html := [].{ ... }`), and locals only for
-- `short_name`, from the syntax tree of Roc's own parser (cookbook/roc/parsed.shale), so
-- an annotation broken across lines and a `where` clause read as Roc reads
-- them. Files that don't parse are listed after the findings, and then the
-- run fails.
--
--   cd <repo> && shale <shale>/cookbook/roc/hunt_names.shale glob=chat/**/*.roc
--   shale cookbook:roc/hunt_names.shale self_test=1
--
-- The arguments:
--   glob       the files to check, `**/*.roc` by default;
--   words      with `words=1`, print the census of effects' first words
--              (below) instead of the findings;
--   house      with `house=0`, leave out what is only our house style
--              (cookbook/roc/house.shale), for another project's code;
--   types      with `types=1`, also ask Roc's type checker (below);
--   root       the app the type checker starts from, or several
--              (`root=a.roc,b.roc`);
--   terms      a project's file of its own terms, which `singular_list`
--              reads (below): a term a line, its words joined by `_`, and
--              after a `:` the element type of the list it names. Delivery's
--              `route: Stop` says a `List(Stop)` is a route, and `two_opt`
--              alone is one word, an act's name, as a verb is;
--   self_test  with `self_test=1`, check the plants (below).
--
-- An effect is a function whose name ends in `!`. The checks:
--
--   state_effect  An effect whose first word is a past participle
--                 (`held_raw!`, `done!`) is named like a state; a verb would
--                 say what it does. The participle is fine when it starts
--                 the name of a type in the effect's annotation
--                 (`rounded_rectangle! : Frame, RoundedRectangle => {}`),
--                 because there it describes the thing the effect draws.
--   question      A function named as a question (`is_*`, `has_*`, `can_*`,
--                 `should_*`) that returns something other than a `Bool`,
--                 or an effect so named that returns no `Bool`
--                 (`is_open! : Str => Str`); and a function that returns a
--                 `Bool` but is named like a state (`marked : Str -> Bool`).
--                 A name with `_is_` or `_has_` inside (`unsigned_is_even`)
--                 is a question too. An effect that returns a `Bool`
--                 (`is_playing! : Sound => Bool`) is fine, because asking
--                 the host about live state has to be an effect. Only
--                 functions are checked: a value (`has_got : List(Bool)`)
--                 and an inferred type (`is_eq : _`) are not. With
--                 `types=1` a definition's type comes from the checker, so
--                 an unannotated `is_ready = |n| n + 1` is checked, and a
--                 result that is an alias of `Bool` (`Answer : Bool`)
--                 counts as a `Bool`.
--   vague         A name made only of vague words (cookbook/words/vague.txt):
--                 `handle_data`, `process!`, `do_it`. The entry points
--                 `handle`, `run` and `main` are fine.
--   name_type     A value named `*_count` whose type is not an integer, or
--                 `*_path` whose type is neither `Str` nor one naming `Path`.
--   noun_effect   An effect whose first word is not a known verb
--                 (cookbook/words/verbs.txt), such as a plain noun (`links!`,
--                 `page!`), reads as a value rather than an act. When the
--                 first word is a namespace prefix such as `block_` or
--                 `port_` (cookbook/words/namespaces.txt), the word after it
--                 is checked instead, here and by `state_effect`, and the
--                 namespace's own instructions listed in that file count as
--                 verbs (`port_out_32!`). An effect whose first argument is
--                 a surface, a `Frame` or a `Canvas`, is named for what it
--                 draws there (`circle! : Frame, Circle => {}`, called as
--                 `frame.circle!(...)`), so it is not checked. An effect with
--                 no annotation shows no surface, so it is checked.
--   negative      A `Bool` value named `no_*` or `not_*`, or an annotated
--                 name starting `is_not_`: its negation reads twice.
--   preposition_split  One stem given different trailing prepositions in
--                 one file (`blocks_of`, `blocks_in`, `blocks_from`). One
--                 relation should keep one preposition, or the names should
--                 say how they differ. It is reported once, at the first
--                 name. These prepositions are left out before counting:
--                 - one of a pair of opposites (`insert_before` beside
--                   `insert_after`; also `from` and `to`, `with` and
--                   `without`, `over` and `under`);
--                 - a `_from` name that takes more arguments than its
--                   siblings, a recursive worker resuming at an index
--                   (`blocks_from` beside `blocks_in`);
--                 - a module's suffix convention: a preposition on three
--                   or more stems in the same file, whose annotations
--                   share their first argument's type and their result
--                   (roc-markdown's `*_onto` writers each take a `List(U8)`
--                   and return it), so `run_onto` beside `run_at` is no
--                   split. Only the pair's own file counts, so a pair's
--                   verdict never moves when another file gains or loses
--                   a name;
--                 - a word the file declares as a keyword of the language
--                   it interprets, in a comment line such as
--                   `# keywords: for, on` (BASIC's `do_for`, `do_on`).
--   command_tense  An effect that takes a tag union whose tags all start
--                 with a past participle and carry no payload
--                 (`pin! : ..., [Pinned, Unpinned]`) names an instruction
--                 like an event. A command is a verb (`[Pin, Unpin]`). A
--                 union with a payload (`[Known(accounts), Unasked]`)
--                 carries state rather than an order. The union may be
--                 written in place or be a type declared in any file
--                 checked, and a `List(T)` argument is checked as `T`.
--   mixed_tense   An effect that takes a tag union (read as for
--                 `command_tense`, payloads included) with a tag starting
--                 with a verb beside one starting with a past participle
--                 (`apply! : [Pin, Unpinned]`): one of them is in the wrong
--                 mood. Only what an effect is handed is checked. A union an
--                 effect returns, a record field and a pure function's
--                 argument hold the domain's words for states (`Redirect`
--                 beside `Found`).
--   container     A type's name (`Entry`, `NodeInfo`) or a record field's
--                 (`items : List(Str)`) made only of container words
--                 (cookbook/words/containers.txt) and vague words. It says
--                 where a value sits, not what it holds. When the container
--                 word is the domain's own, the doc comment above the
--                 declaration says whose it is: `## A folder's entry` keeps
--                 `Entry`, and `## A listing's entries` keeps a field
--                 `entries`. A type's words are split at its capitals, a
--                 field's at its underscores. A field of one plain value (a
--                 number, a `Str`, a `Bool`: `entry : F64`) holds nothing a
--                 container could, so it passes. Fields in a local's
--                 annotation are not read.
--   short_name    A name of one letter (`w : F64`, `{ k : U64 }`, `p = w *
--                 h`): a top-level or member name, a record field, and every
--                 binding inside a definition, a local, a function's or a
--                 lambda's parameter, a match arm's binding, a destructured
--                 record's field and a `var` (past its `$`). A field or a
--                 binding may be a coordinate (`x`, `y`, `z`, and `w` beside
--                 `x` and `y`), a colour's channel (`r`, `g`, `b`, and `a`
--                 beside them) or a triangle's corner (`a`, `b` and `c`, all
--                 three, a binding's from one record). A loop's variable may
--                 be one letter too: a `for`'s binding, a `var` a `while`
--                 tests, and the parameters of a one-line lambda that is the
--                 direct argument of a list method (`xs.map(|x| x * 2)`,
--                 `List.walk(xs, 0, |n, x| n + x)`; declared.shale's
--                 LOOP_METHODS). A lambda over two lines, or handed to
--                 anything else, names its parameters.
--   worker_name   A name whose last word says only that it is a helper:
--                 `_acc`, `_loop`, `_inner`, `_helper` or `_rec`
--                 (`count_acc`). Name a recursive worker for the parameter
--                 it adds, so that a call reads as a sentence:
--                 `count_from(xs, at)` for a start point,
--                 `html_onto(out, node)` for an output being built,
--                 `walk_with(tree, seen)` for other carried state. The entry
--                 function takes the plain name, `count`. `_step`, `_walk`
--                 and `_go` are ordinary words too, so they are reported
--                 only on a definition that calls itself.
--   stacked_preposition  A name whose last two words are both prepositions
--                 (cookbook/words/prepositions.txt), like `rest_from_onto`:
--                 a worker's suffix added to an entry name that already ends
--                 in one. Let each read once: the entry says what it returns
--                 (`tail_after`), the worker what it adds (`rest_onto`). A
--                 name made only of prepositions (`at_of`) is not reported,
--                 since its first word serves as a noun.
--   taken_word    A name that is a whole word from cookbook/words/taken.txt:
--                 a function named by one of Roc's own words (`record`,
--                 `tag`, `alias`, `module`), which reads as Roc's rather
--                 than the domain's, or a value named by a number from
--                 `one` to `twelve` (`three : List(Fields)`), which says
--                 how many rather than what it holds. A function that
--                 returns the very thing, its result's last part being the
--                 word capitalized (`record : ApiKey.Key -> ApiKey.Record`),
--                 is fine.
--   bare_participle  A pure function whose whole name is one past participle
--                 (`added`, `joined`, `named`, `chosen`), which reads too
--                 easily as a `Bool`. Name it by a noun for what it gives
--                 (`user_by_name`) or a verb for what it does (`add_user`).
--                 A name of two parts or more (`escaped_text`, `is_added`)
--                 and a value are not reported. An effect named this way is
--                 left to `state_effect`, and a function that gives a `Bool`
--                 to `question`.
--   phrase_name   A pure function, not a constant, whose first word is a
--                 preposition (cookbook/words/prepositions.txt) and which gives
--                 something other than a `Bool`: `in_view`, `on_next_segment`,
--                 `over_gap`. Bare like that it reads as a yes or no and hides
--                 what it gives, and a reader of a definition has often lost
--                 the module's context. Name the thing (`trees_in_view`,
--                 `rider_on_next_segment`), even if that repeats the module.
--                 The type decides what reads as a constructor or conversion,
--                 and these pass:
--                 - a constructor: a first word in CONSTRUCTOR_WORDS
--                   (cookbook/roc/declared.shale) and a result, or a `Try`
--                   of one, that is its own module's type, a type declared
--                   in that module, or the type it is a member of (`Clock.at_step : U32 -> Clock`,
--                   `Color.of_hex : U32 -> Color.Rgb`). The word matters as
--                   well as the type: `Scene.in_view : View -> Scene` gives
--                   its own type and still reads as a question;
--                 - a conversion: `to_*` and `into_*`, which name what they
--                   give;
--                 - a `from_*` that takes or gives its own module's type, as
--                   above, even inside a record, a union or a list
--                   (`Along.from_start : Along -> Distance`,
--                   `Key.from_path : Str -> Try({ key : Key }, [NoKey])`). A
--                   `Try` gives its success only: an error that carries the
--                   type is no conversion to it;
--                 - a `from_<noun>` in a module that has no type of its own,
--                   one whose file declares only `Hex :: [].{ ... }`
--                   (`Hex.from_hex : Str -> Try(List(U8), [NotHex])`). Such a
--                   module has no type to take or give. A module with a type
--                   is held to the rule above, so
--                   `DateTime.from_clock : I64 -> Try(Str, [OutOfRange])`,
--                   which neither takes nor gives a `DateTime`, is reported.
--                   The next word has to be no preposition, so `from_behind`
--                   stays a phrase, and the type has to be known;
--                 - a changed copy: `with_*` or `without_*` that gives its
--                   first argument's type (`with_lean : Bike, Angle -> Bike`).
--                 A definition with no annotation shows none of this, so it
--                 is reported unless `types=1` supplies its type. A list that
--                 is no function, a value, a field or a parameter, named from
--                 a preposition, that `singular_list` would report
--                 (`by_slot : List(List(Stop))`) is reported here instead: it
--                 wants its noun (`routes_by_slot`), not a plural.
--   singular_list  A name that holds or gives a `List(...)`, or a `Try` of
--                 one, but reads as one thing: `triangle : List(Shape)`. The
--                 name ends in a plural of what the list holds (`triangles`,
--                 `herd_cows`) or is explicit (`triangle_list`). A collective
--                 noun is no plural: `herd`, `crowd` and `route` are reported.
--                 Read are top-level and member definitions, record fields,
--                 and the plain parameters of a top-level or member lambda.
--                 The word that counts is the one before a preposition or an
--                 `after` word of cookbook/words/list_names.txt, else the
--                 last (`trees_in_view`, `corners_ahead`). These pass:
--                 - a `List(U8)`, whose bytes are plumbing: the name says what
--                   they mean (`boundary`). A `List(F64)` is checked, since a
--                   flat run of coordinates can't be told from many readings;
--                 - a word list_names.txt calls `many`, one that can't be
--                   counted, and a word read as a participle (`clipped`);
--                 - a function whose whole name is a verb (`draw`) or a term
--                   (`two_opt`), and a changed copy: a function that gives
--                   its first argument's type, whatever its first word
--                   (`trim_hull`, `coalesce`, `stable_by_load_desc`);
--                 - a word the project's terms (`terms=`) say names a list
--                   of its element (`route` of `Stop`s);
--                 - one letter, and a value named by a number, which are
--                   `short_name`'s and `taken_word`'s to judge;
--                 - an accumulator's short idiom, as a whole name (`out`);
--                 - a name `phrase_name` reports, to be named again anyway.
--                 The word list, a participle and a verb don't pass a word
--                 that is the element's own (`route : List(Route)`), and a
--                 changed copy of more than one word does, as its object is
--                 one element (`set_run : List(Run), Run -> List(Run)`). A word
--                 verbs.txt holds that list_names.txt calls `one` is no verb
--                 here (`route`). An `s` makes no plural after `s` (`class`),
--                 after letters that are no word (`pts`), or in a `one` word
--                 (`axis`). A word list_names.txt calls `adjective`
--                 (`stable`, `cheapest`) is no noun, so the finding says the
--                 name has none and offers no plural of it. A term's words
--                 read as one (`two_opt_pass`'s word is `pass`). An alias of
--                 a list isn't seen, and with `types=1` an unannotated
--                 definition or parameter is read by its inferred type.
--   world_verb    A pure function whose first word is a verb of
--                 cookbook/words/world_verbs.txt, one that claims to act on
--                 something outside (`draw`, `paint_shape`). Nothing is drawn
--                 by a function that only makes a value, so name it for that
--                 value (`tree_shapes`). A verb that says what happens to its
--                 argument is fine (`plus`, `clamp`, `trim_hull`). An effect,
--                 which does act, and a value are not reported. A `##` doc
--                 directly above the definition (or its annotation) answers
--                 it, saying why the verb stands: a renderer named for what
--                 its output is drawn as, as `single`'s doc answers it in
--                 check_boundaries.
--   where_name    A method in a `where` clause named by one word
--                 (`[a.height : a -> U64]`). A clause matches by name alone,
--                 so the name is the whole contract: two words say what it is
--                 for (`scenery_height`). The methods Roc calls by name
--                 (`is_eq`, `plus`, `map`) are fine. A local's clause is read.
--   stale_doc_name  A backticked name in a comment line (`#` or `##` first)
--                 that names nothing in the file or the modules it imports:
--                 a rename leaves its comments behind (rename.shale counts
--                 and leaves them). A bare name is judged when it has two
--                 words or more (`cheapest_insert`), since a one-word one
--                 (`for`, `fold`) is often the language's or the prose's; a
--                 `Module.name` (`Route.two_opt`, a call's parentheses
--                 allowed) is judged against `Module.roc` beside the file,
--                 else a module of that name among the files read (a
--                 package's, `import game.SunPath`), and left when there is
--                 none, as for `List.map` (cookbook/roc/doc_names.shale).
--                 An import is read the same way, and one whose names can't
--                 be read leaves the file's bare names unjudged, as does a
--                 possessive before one (`roc-ray's`), or a language or
--                 library of cookbook/words/cited_sources.txt before it in
--                 its sentence ("Rust's `is_ascii_digit`", "Zig `isDigit`,
--                 Rust `is_ascii_digit`"): it is another's. A
--                 platform's `provides` symbols (`roc_plan`) are its names,
--                 and its bare `roc_` names (`roc_crashed`) the host's.
--
-- Each name is judged once: from its annotation when it has one, else from
-- its definition. An effect that takes an effectful function (`map2!`,
-- `on_err!`: an argument's type holds a `=>`, or a lambda argument's name
-- ends in `!`) has its `!` from that callback, so it is judged as the name
-- without the `!`. Names chosen elsewhere are skipped: the methods Roc calls
-- by name (cookbook/roc/headers.shale), and the top-level names a platform
-- dictates, which are what an app's header provides (`app [loaded, step]`)
-- and what a platform's header requires and provides.
--
-- The output is the counts, one line per finding,
-- `path:line: <check>: <why>`, and the counts again
-- (cookbook/findings.shale).
--
-- The word lists are in cookbook/words/, shared with the Zig name hunt.
-- participles.txt lists the irregular past participles; any other word
-- ending in `ed` counts as one unless ed_verbs.txt lists it. With `words=1`
-- the recipe prints a census instead of the findings: each first word the
-- effects start with, how many start with it, and its verdict: `verb`,
-- `participle`, `vague`, `asks` (`is`, `has`) or `refused` (what
-- `noun_effect` reports). A verb missing from verbs.txt shows up there as
-- `refused`.
--
-- With `types=1` the recipe asks Roc's type checker for each definition's
-- type (cookbook/roc/types.shale). It needs `root=` and the tree's
-- `roc-version` file. A root the checker refuses, or a roc-types built for
-- another Roc version, stops the run. A file that no root imports is
-- checked without types, listed after the findings, and fails the run.
--
--   cd <repo> && shale <shale>/cookbook/roc/hunt_names.shale glob=app/*.roc root=app/main.roc types=1
--
-- `self_test=1` runs the recipe over `cookbook/roc/plants/hunt_names/`. Each
-- plant is named for the check it holds (`question.roc`,
-- `question_where.roc`) and must make that check report, and no other. A
-- `quiet_*.roc` plant must make no check report. Every check needs a plant,
-- and a plant named for no check fails the test. A plant another imports is
-- a CamelCase module, read as snake case (`QuietDocShelf.roc` is
-- `quiet_doc_shelf.roc`); the plants' terms are `terms.txt` there; each plant
-- opens by naming its check, so the check names count as names for
-- `stale_doc_name`; and cookbook/roc/naming_plants.shale holds these
-- rules, with what a finding must say, or not. The census must also give
-- the right verdict for one known word of the plants per verdict. The
-- plants in `typed/` are checked with the types, from their app
-- `typed/QuietApp.roc`, and their CamelCase module names read as snake case
-- (`QuestionInferred` as `question_inferred`); the rest are checked
-- without. The self-test fails without roc-types.
--
-- The recipe reads each file's source as well as its tree, to tell `->`
-- from `=>`, which the tree writes alike. On a large tree that needs more
-- than the default arena.
--
-- What it reads of each definition is cookbook/roc/declared.shale's
-- `file_definitions`, and the checks judged over the whole tree once every
-- file is read are cookbook/roc/naming_passes.shale's.
-- budget: steps=800000000 arena_bytes=3000000000 output_bytes=4000000

const SELF_TEST = arg("self_test", "") == "1"
use("cookbook:findings.shale")
use("./parsed.shale")
use("./pinned.shale")
use("./types.shale")
use("./declared.shale")
use("./headers.shale")
use("./house.shale")
use("./doc_names.shale")
use("./naming_plants.shale")
use("./naming_passes.shale")
const PLANTS = "cookbook:roc/plants/hunt_names/"
const GLOB = SELF_TEST and (PLANTS .. "*.roc") or arg("glob", "**/*.roc")
const TYPES_ARG = arg("types", "0")
if TYPES_ARG ~= "0" and TYPES_ARG ~= "1" then fail("hunt_names: types=" .. TYPES_ARG .. ": 0 (the default) or 1") end
-- The self-test checks its typed plants with the types, and the rest
-- without.
const USE_TYPES = SELF_TEST or TYPES_ARG == "1"
const ROOT = SELF_TEST and (PLANTS .. "typed/QuietApp.roc") or arg("root", "")
-- The type checker's answers, filled in once the files are known; empty
-- unless USE_TYPES.
const CHECKER_TYPES = {real = {}, pats = {}, exprs = {}, unreached = {}}
const CENSUS_ONLY = arg("words", "") == "1"
const CHECKS = {"state_effect", "question", "vague", "name_type", "negative", "noun_effect", "command_tense", "mixed_tense", "container", "preposition_split", "short_name", "worker_name", "stacked_preposition", "taken_word", "bare_participle", "phrase_name", "singular_list", "world_verb", "where_name", "stale_doc_name"}
-- `worker_name` reports a helper suffix always, and a suffix that is also an
-- ordinary word (a fold's `step`, `List.walk`, `can_go`) only on a
-- definition that calls itself.
const HELPER_SUFFIXES = {acc = true, loop = true, inner = true, helper = true, rec = true}
const RECURSION_SUFFIXES = {step = true, walk = true, go = true}

const VERBS = word_set("cookbook:words/verbs.txt")
const PARTICIPLES = word_set("cookbook:words/participles.txt")
const ED_VERBS = word_set("cookbook:words/ed_verbs.txt")
const VAGUE = word_set("cookbook:words/vague.txt")
const CONTAINERS = word_set("cookbook:words/containers.txt")
const PREPOSITIONS = word_set("cookbook:words/prepositions.txt")

const NAMESPACES = namespace_instructions("namespaces.txt")

const TAKEN_WORDS = taken_word_kinds("taken.txt")

const LIST_NAMES = list_name_kinds("list_names.txt")
const WORLD_VERBS = word_set("cookbook:words/world_verbs.txt")
const PLAIN_ELEMENTS = set_of({"U16", "U32", "U64", "I16", "I32", "I64", "F32", "F64", "Dec", "Str", "Bool"})
const TERMS = project_terms(SELF_TEST and (PLANTS .. "terms.txt") or arg("terms", ""))
-- The tables `singular_list` reads (cookbook/roc/declared.shale's
-- `list_name_finding`).
const LIST_WORDS = {list_names = LIST_NAMES, taken = TAKEN_WORDS, verbs = VERBS, prepositions = PREPOSITIONS, plain = PLAIN_ELEMENTS, participles = PARTICIPLES, ed_verbs = ED_VERBS, terms = TERMS}
const SURFACES = {Frame = true, Canvas = true}
-- The keywords each file declares (`# keywords: for, on`), by path.
const DECLARED_KEYWORDS = {}
const ENTRY_POINT_NAMES = {handle = true, run = true, main = true}
const INTEGER_TYPES = {U8 = true, U16 = true, U32 = true, U64 = true, U128 = true, I8 = true, I16 = true, I32 = true, I64 = true, I128 = true}

-- The tag union each type declaration names, by the type's name: `Edit` of
-- `Edit : [Opened, Closed]` maps to its `union_shape`.
const TAG_UNION_TYPES = {}
-- The aliases of `Bool` declared in the files read, by each name the type
-- checker may write for them (`Answer`, `Owner.Answer`).
const BOOL_ALIASES = {}
-- Each type a file declares, by path, as whether it is `[].{ ... }`: an empty
-- union with members.
const TYPES_DECLARED_IN_FILE = {}
-- Each type name a file declares, at the top or inside a module's own type
-- (`MdText := [].{ Budget : ... }`), as a set of `path|Name`.
const TYPE_NAMES_IN_FILE = {}

-- Every type name and record field name that `container` checks, each
-- `{path, line, name, words, is_field, doc}`, where `doc` is the comment
-- lines above its declaration, lowercased.
const TYPE_AND_FIELD_NAMES = {}
-- The tables declared.shale's `file_definitions` fills.
const FILE_FACTS = {keywords = DECLARED_KEYWORDS, unions = TAG_UNION_TYPES, bool_aliases = BOOL_ALIASES, type_kinds = TYPES_DECLARED_IN_FILE, type_names = TYPE_NAMES_IN_FILE, names = TYPE_AND_FIELD_NAMES}

const count_by_check = {}
for c in CHECKS do count_by_check[c] = 0 end
-- The set of `path|check` pairs where the check reported, for the self-test.
const fired_in_file = {}
-- Each first word an effect starts with, mapped to `{word, count, verdict}`.
const first_word_census = {}
const finding_lines = {}

function report(path, line, check, why)
  if house_leaves_out("hunt_names", check) then return nil end
  if not CENSUS_ONLY then push(finding_lines, path .. ":" .. line .. ": " .. check .. ": " .. why) end
  count_by_check[check] = count_by_check[check] + 1
  fired_in_file[path .. "|" .. check] = true
  return nil
end

function is_participle(word)
  return reads_as_participle(word, PARTICIPLES, ED_VERBS)
end

for word in keys(VERBS) do
  if is_participle(word) then fail("hunt_names: `" .. word .. "` is in cookbook/words/verbs.txt and reads as a participle, which would make its effects states") end
end

-- What an effect's first word says: `participle`, `verb`, `vague`, `asks`
-- (`is`, `has`) or `refused`.
function first_word_verdict(word)
  if is_participle(word) then return "participle" end
  if has_key(VERBS, word) then return "verb" end
  if has_key(VAGUE, word) then return "vague" end
  if word == "is" or word == "has" then return "asks" end
  return "refused"
end

-- ── the syntax tree ──────────────────────────────────────────────────────

-- The checker's type of each plain-name pattern in the parsed file `f`, by
-- its node's index as text: none unless USE_TYPES and the checker reached
-- the file.
function pattern_types_in(f)
  local typed = {}
  if not (USE_TYPES and has_key(CHECKER_TYPES.real, f.path)) then return typed end
  for i = 1, #f.nodes do
    if f.nodes[i].kind == "p-ident" then
      local checker_type = roc_type_at(CHECKER_TYPES, "pat", f.path, f.nodes[i])
      if checker_type ~= nil then typed[tostring(i)] = checker_type end
    end
  end
  return typed
end

-- Every top-level and module-member annotation and definition in the
-- parsed files, as declared.shale's `file_definitions` reads them, filling
-- FILE_FACTS along the way.
function read_definitions(parsed_files)
  local definitions = {}
  for f in parsed_files do
    local src = split(read(f.path), "\n")
    local known = {dictated = header_names(f.nodes).dictated, pattern_types = pattern_types_in(f), recursion_suffixes = RECURSION_SUFFIXES}
    for def in file_definitions(f, src, known, FILE_FACTS) do push(definitions, def) end
  end
  return definitions
end

-- ── the checks ───────────────────────────────────────────────────────────

function all_tags_past(tags)
  for t in tags do
    if not is_participle(tag_first_word(t)) then return false end
  end
  return true
end

-- What a definition's type says, for `question`, `taken_word` and
-- `phrase_name`: `{is_function, first, result, known, source_note}`. The type
-- is the checker's when it gave one, else the annotation's. `known` is false
-- for a definition with no annotation and no checker's type.
function definition_signature(def)
  local signature = {is_function = def.annotation and def.fn, first = get(def, "first", ""), result = get(def, "result", ""), known = def.annotation, source_note = ""}
  if has_key(def, "typed") then
    local checker = roc_type_parts(def.typed)
    signature = {is_function = checker.fn, first = first_argument(checker.args), result = checker.result, known = true, source_note = " (the checker's type)"}
    if has_key(BOOL_ALIASES, checker.result) then signature.result = "Bool" end
  end
  return signature
end

-- Reports a name whose type says many and whose head word says one:
-- `singular_list` in the header. `subject` is `{path, line, name, kind,
-- is_function, first, gives}`, `kind` being what the report calls it.
function judge_list_name(subject)
  local found = list_name_finding(subject, LIST_WORDS)
  if found ~= nil then report(subject.path, subject.line, found.check, found.why) end
  return nil
end

-- Reports what each check finds in one definition record, except
-- `container` and `preposition_split`, which are judged over all the files
-- afterwards.
function judge_definition(def)
  local path = def.path
  local line = def.line
  local full_name = def.name
  if has_key(LANGUAGE_FIXED_NAMES, full_name) then return nil end
  local has_bang = ends_with(full_name, "!")
  local name = has_bang and sub(full_name, 1, #full_name - 1) or full_name
  local is_effect = has_bang and not def.callback
  local ws = split(name, "_")
  local last_word = ws[#ws]
  local is_annotation = def.annotation
  -- A definition paired with an annotation was judged at the annotation.
  local judged_here = not def.paired
  local asks_inside = contains(name, "_is_") or contains(name, "_has_")
  local has_namespace = is_effect and #ws > 1 and has_key(NAMESPACES, ws[1])
  local act_word = has_namespace and ws[2] or ws[1]
  local act_verdict = first_word_verdict(act_word)
  if has_namespace and act_verdict == "refused" and has_key(NAMESPACES[ws[1]], act_word) then act_verdict = "verb" end
  local act_place = has_namespace and ("the word after its namespace `" .. ws[1] .. "_`") or "its first word"
  local named_as_state = is_participle(act_word) and not asks_inside
  if is_effect and judged_here then
    if not has_key(first_word_census, act_word) then first_word_census[act_word] = {word = act_word, count = 0, verdict = act_verdict} end
    first_word_census[act_word].count = first_word_census[act_word].count + 1
  end
  local arguments = get(def, "args") or {}
  local draws_on_surface = #arguments > 0 and has_key(SURFACES, get(arguments[1], "ref", ""))
  if is_effect and judged_here and act_verdict == "refused" and not draws_on_surface then
    if has_key(PREPOSITIONS, act_word) then report(path, line, "noun_effect", "`" .. full_name .. "` has an effect but " .. act_place .. " is a preposition, `" .. act_word .. "`: an effect is named for its act")
    else report(path, line, "noun_effect", "`" .. full_name .. "` has an effect but " .. act_place .. ", `" .. act_word .. "`, is no verb: it reads as a value, not an act") end
  end
  if judged_here and #ws > 1 and has_key(PREPOSITIONS, last_word) then note_trailing_preposition(def, ws) end
  local names_drawn_type = #ws > 1 and has_key(get(def, "types") or {}, camel_case(ws))
  if is_effect and judged_here and named_as_state and not names_drawn_type then report(path, line, "state_effect", "`" .. full_name .. "` has an effect but is named as a state, `" .. act_word .. "`: a verb says what it does") end
  local named_as_question = #ws > 1 and (ws[1] == "is" or ws[1] == "has" or ws[1] == "can" or ws[1] == "should")
  local signature = definition_signature(def)
  local returns_bool = signature.is_function and signature.result == "Bool"
  if named_as_question and judged_here and is_effect and not returns_bool then report(path, line, "question", "`" .. full_name .. "` asks a question but has an effect" .. (signature.is_function and (" and gives `" .. signature.result .. "`" .. signature.source_note) or "")) end
  if returns_bool and named_as_state and judged_here then report(path, line, "question", "`" .. full_name .. "` gives a `Bool`" .. signature.source_note .. " but is named as a state, `" .. ws[1] .. "`: ask it (`is_*`, `has_*`)") end
  if named_as_question and judged_here and signature.known and signature.is_function and not is_effect and signature.result ~= "Bool" and signature.result ~= "_" then report(path, line, "question", "`" .. full_name .. "` asks a question but gives `" .. signature.result .. "`" .. signature.source_note) end
  if judged_here then
    local all_vague = true
    for w in ws do
      if not has_key(VAGUE, w) then all_vague = false end
    end
    if #ws == 1 and has_key(ENTRY_POINT_NAMES, ws[1]) then all_vague = false end
    if all_vague then report(path, line, "vague", "`" .. full_name .. "` is only vague words: what does it handle, and how?") end
    if #name == 1 then report(path, line, "short_name", "`" .. full_name .. "` is one letter, read far from where it is defined: name what it holds") end
    local has_leading_noun = false
    for w in take(ws, max(#ws - 2, 0)) do
      if not has_key(PREPOSITIONS, w) then has_leading_noun = true end
    end
    if has_leading_noun and has_key(PREPOSITIONS, last_word) and has_key(PREPOSITIONS, ws[#ws - 1]) then report(path, line, "stacked_preposition", "`" .. full_name .. "` stacks two prepositions, `_" .. ws[#ws - 1] .. "_" .. last_word .. "`: let each read once, the entry named for what it gives (`rest`, `tail_after`) and the worker for what it adds (`rest_onto`)") end
    -- A function is known by its type, else by a lambda definition; a value
    -- by a type that is no function, else by a definition that is no
    -- lambda. An inferred annotation (`two : _`) with no checker's type is
    -- neither.
    local has_type = signature.known and not (is_annotation and get(def, "whole", "") == "_" and not has_key(def, "typed"))
    local is_lambda = get(def, "lambda", false)
    local is_function = signature.is_function or (not signature.known and is_lambda)
    local is_value = (has_type and not signature.is_function) or (not signature.known and not is_lambda)
    local taken_kind = get(TAKEN_WORDS, name, "")
    if taken_kind == "roc" and is_function then
      local result_parts = split(signature.result, ".")
      local returns_the_word = signature.is_function and result_parts[#result_parts] == camel_case({name})
      if not returns_the_word then report(path, line, "taken_word", "`" .. full_name .. "` is Roc's own word, `" .. name .. "`, for a function that gives no `" .. camel_case({name}) .. "`: name it for the domain's thing (`element`, `append`), and keep Roc's words for Roc") end
    end
    if taken_kind == "cardinal" and is_value then report(path, line, "taken_word", "`" .. full_name .. "` is a number's name for a value: it says how many, not what it holds") end
    -- An effect so named is `state_effect`'s, and a function so named that
    -- gives a `Bool` is `question`'s, so this check takes the rest.
    if not has_bang and #ws == 1 and is_participle(name) and is_function and not returns_bool then report(path, line, "bare_participle", "`" .. full_name .. "` is a function named by a bare past participle, which reads as a `Bool`: name it by a noun for what it gives (`user_by_name`) or a verb for what it does (`add_user`)") end
    -- An effect is `noun_effect`'s, and a result of `_` says nothing.
    if not has_bang and has_key(PREPOSITIONS, ws[1]) and is_function and not returns_bool and signature.result ~= "_" and not reads_as_maker(def, ws, signature, FILE_FACTS, PREPOSITIONS) then
      local gives = signature.known and ("gives `" .. signature.result .. "`" .. signature.source_note) or "has no annotation to show it makes its own type"
      report(path, line, "phrase_name", "`" .. full_name .. "` starts with a preposition, `" .. ws[1] .. "`, and " .. gives .. ": bare, it reads as a yes or no and hides what it gives; name the thing (`trees_in_view`, not `in_view`)")
    elseif signature.known then
      judge_list_name({path = path, line = line, name = full_name, kind = signature.is_function and "function" or "value", is_function = signature.is_function, first = signature.first, gives = signature.result})
    end
    if not has_bang and is_function and has_key(WORLD_VERBS, ws[1]) and not get(def, "has_doc", false) then report(path, line, "world_verb", "`" .. full_name .. "` is pure, and `" .. ws[1] .. "` claims to act on something outside: name it for the value it gives (`tree_shapes`, not `draw_tree`)") end
    local argument_types = get(def, "argument_types", {})
    local parameters = get(def, "parameters", {})
    for k = 1, #parameters do
      local parameter = parameters[k]
      local parameter_type = k <= #argument_types and argument_types[k] or get(parameter, "typed", "")
      if parameter.name ~= "" then judge_list_name({path = path, line = parameter.line, name = parameter.name, kind = "parameter", is_function = false, first = "", gives = parameter_type}) end
    end
  end
  -- `worker_name` is judged at the definition, which knows whether it calls
  -- itself, and at an annotation only when no definition follows it, as
  -- with a hosted effect.
  local annotation_alone = is_annotation and not get(def, "has_def", false)
  local helper_suffix = has_key(HELPER_SUFFIXES, last_word) and (annotation_alone or not is_annotation)
  local recursion_suffix = has_key(RECURSION_SUFFIXES, last_word) and get(def, "recurses", false)
  if #ws > 1 and (helper_suffix or recursion_suffix) then report(path, line, "worker_name", "`" .. full_name .. "` is named only as a helper, `_" .. last_word .. "`: name the worker for the parameter it adds (`_from` a start point, `_onto` an output built, `_with` other carried state) and give the entry function the plain name") end
  if is_annotation and not def.fn and def.whole ~= "_" then
    local annotated_type = def.whole
    if last_word == "count" and not has_key(INTEGER_TYPES, annotated_type) then report(path, line, "name_type", "`" .. full_name .. "` is a count of type `" .. annotated_type .. "`") end
    if last_word == "path" and annotated_type ~= "Str" and not contains(annotated_type, "Path") then report(path, line, "name_type", "`" .. full_name .. "` is a path of type `" .. annotated_type .. "`") end
    if annotated_type == "Bool" and (ws[1] == "no" or ws[1] == "not") and #ws > 1 then report(path, line, "negative", "`" .. full_name .. "` is a negative flag: `" .. full_name .. " = Bool.false` reads twice") end
  end
  if is_annotation and is_effect and def.fn then
    for argument in arguments do
      local union = get(argument, "union")
      local ref = get(argument, "ref")
      if union == nil and ref ~= nil then union = get(TAG_UNION_TYPES, ref) end
      if union ~= nil then
        local shown = (get(argument, "list") and "a list of " or "") .. "`[" .. join(union.names, ", ") .. "]`"
        if not union.payload and #union.names >= 2 and all_tags_past(union.names) then report(path, line, "command_tense", "`" .. full_name .. "` takes " .. shown .. ", an instruction named like an event: name its tags as commands (`Pinned` is `Pin`)") end
        local command_tags = {}
        local event_tags = {}
        for t in union.names do
          local w = tag_first_word(t)
          if is_participle(w) then push(event_tags, t) elseif has_key(VERBS, w) then push(command_tags, t) end
        end
        if #command_tags > 0 and #event_tags > 0 then report(path, line, "mixed_tense", "`" .. full_name .. "` takes " .. shown .. ": commands (" .. join(command_tags, ", ") .. ") beside events (" .. join(event_tags, ", ") .. "): name what it is told to do in one mood") end
      end
    end
  end
  if is_annotation and #ws > 2 and ws[1] == "is" and ws[2] == "not" then report(path, line, "negative", "`" .. full_name .. "` asks a negative: `!" .. full_name .. "(...)` reads twice") end
  return nil
end

local paths = glob(GLOB)
if SELF_TEST then
  for q in glob(PLANTS .. "typed/*.roc") do push(paths, q) end
end
local file_count = #paths
-- The self-test's untyped plants are imported by no root.
const UNTYPED_PLANTS = SELF_TEST and set_of(glob(PLANTS .. "*.roc")) or {}
if USE_TYPES then
  local got = roc_types_for_files("hunt_names", ROOT, roc_bin("hunt_names", SELF_TEST), paths, UNTYPED_PLANTS)
  CHECKER_TYPES.real = got.real
  CHECKER_TYPES.pats = got.pats
  CHECKER_TYPES.exprs = got.exprs
  CHECKER_TYPES.unreached = got.unreached
end
local parsed = parse_roc_files(paths)
-- This loop does not `yield`, because a yield may keep only 1 MiB, and a
-- large tree's definitions pass that. The arena in the header holds them.
for def in read_definitions(parsed.files) do
  judge_definition(def)
end

for file in parsed.files do
  for found in where_name_findings(file, LANGUAGE_FIXED_NAMES) do report(file.path, found.line, "where_name", found.why) end
  for found in short_binding_findings(file) do report(file.path, found.line, "short_name", found.why) end
end

-- `stale_doc_name` in the header. Each plant opens by naming its check, so
-- in the self-test the check names, and this recipe's, count as names.
function plant_doc_names()
  local known = set_of(CHECKS)
  known.hunt_names = true
  return known
end
const DOC_NAMES_SEEN = {known = SELF_TEST and plant_doc_names() or {}, by_module = {}, by_path = {}, sources = word_set("cookbook:words/cited_sources.txt")}
-- Each file read is known by its path too, so `module_names` parses only
-- a module beside one that the run didn't read.
for file in parsed.files do
  local module = module_name(file.path)
  local names = get(DOC_NAMES_SEEN.by_module, module) or {}
  local own = names_in_tree(file.nodes)
  for n in keys(own) do names[n] = true end
  DOC_NAMES_SEEN.by_module[module] = names
  DOC_NAMES_SEEN.by_path[file.path] = {found = true, names = own}
end
for file in parsed.files do
  for found in stale_doc_findings(file.path, split(read(file.path), "\n"), file.nodes, DOC_NAMES_SEEN) do report(file.path, found.line, "stale_doc_name", found.why) end
end

for named in TYPE_AND_FIELD_NAMES do
  for found in container_findings(named, VAGUE, CONTAINERS) do report(named.path, named.line, found.check, found.why) end
  if named.is_field then judge_list_name({path = named.path, line = named.line, name = named.name, kind = "field", is_function = named.is_function, first = named.first, gives = named.gives}) end
end

for found in preposition_split_findings(DECLARED_KEYWORDS) do report(found.path, found.line, "preposition_split", found.why) end

if CENSUS_ONLY then
  local census = census_lines(first_word_census)
  print_findings("hunt_names (Roc) census: " .. file_count .. " files; " .. census.summary, census.lines)
else
  local check_counts = {}
  for c in CHECKS do push(check_counts, c .. " " .. count_by_check[c]) end
  print_findings("hunt_names (Roc): " .. file_count .. " files; " .. join(check_counts, ", ") .. house_note("hunt_names"), finding_lines)
end
fail_if_refused("hunt_names", parsed.refused, CHECKER_TYPES.unreached)

-- A plant's name relative to PLANTS. A typed plant is a CamelCase module
-- (`typed/QuestionInferred.roc`), as is a plant another imports
-- (`QuietDocShelf.roc`), and its name is given in snake case
-- (`question_inferred.roc`).
function plant_name(path)
  local name = sub(path, #PLANTS + 1)
  if starts_with(name, "typed/") then name = sub(name, 7) end
  if re_find(name, "^[A-Z]") ~= nil then return snake_case_plant_name(name) end
  return name
end

if SELF_TEST then
  local names = {}
  for path in paths do names[path] = plant_name(path) end
  local wrong = plants_wrong({plants = PLANTS, checks = CHECKS, paths = paths, names = names, fired = fired_in_file, census = first_word_census, findings = finding_lines})
  for w in wrong do print("FAIL " .. w) end
  if #wrong > 0 then fail("hunt_names self_test: " .. #wrong .. " plants wrong") end
  print("hunt_names (Roc) self_test: PASS (each check fires on its plants alone, the quiet_ plants on none, and the census gives each verdict its known word)")
end