check_how_failure_is_reported

Roc

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

cookbook/roc/check_how_failure_is_reported/check_how_failure_is_reported.roc, 185 lines

## check_how_failure_is_reported, in Roc on Shale's platform (roc_platform/README.md): how Roc
## code reports failure, against the rules in roc-apps docs/roc-style.md
## ("Errors and failure"). Its launcher, cookbook/roc/check_how_failure_is_reported.shale, is
## how it is run, and its header says the five checks, `error_alias`,
## `optional_tag`, `set_fallback`, `placeholder` and `number_fallback`.
## check_goldens.shale, beside this, holds its output on the plants to its
## goldens, line for line.
##
##   cd <repo> && shale cookbook:roc/check_how_failure_is_reported.shale glob='app/**/*.roc'
##   shale cookbook:roc/check_how_failure_is_reported.shale self_test=1
##
## The arguments: `glob` (`**/*.roc`), `types` (`1` asks Roc's type
## checker), `root` (the app or apps the types are read from) and
## `self_test` (`self_test=1` checks the plants, the typed ones with the
## types).
##
## This root reads the optionals' words (`Shale.read!`), globs the files
## (`Shale.glob!`), gathers the types (Types, through `Shale.run!`), has
## Roc's parser read the files (`Shale.roc_tree!`) and prints the verdict
## (`Shale.print!`, `Shale.fail!`). Its modules are beside it: a module a
## check or two (ErrorAlias, OptionalTag, Fallbacks), Types and SelfTest;
## Tree, Forest (the files' trees joined), Text, Finding and RocTypes are the
## cookbook's Roc library, cookbook/roc/lib/.
## budget: steps=400000000 arena_bytes=3000000000 output_bytes=4000000 programs=100
app [main!] { lib: "../lib/main.roc", pf: platform "../../../roc_platform/platform/main.roc" }

import pf.Shale
import ErrorAlias
import Fallbacks
import lib.Finding
import lib.Forest
import OptionalTag
import lib.RocTypes
import SelfTest
import lib.Text
import Types

main! : {} => {}
main! = |{}| {
	self_test = Shale.arg!("self_test", "") == "1"
	plants = SelfTest.plants
	glob_asked = Shale.arg!("glob", "**/*.roc")
	glob = if self_test {
		"${plants}*.roc"
	} else {
		glob_asked
	}
	types_asked = Shale.arg!("types", "0")
	if types_asked != "0" and types_asked != "1" {
		Shale.fail!("check_how_failure_is_reported: types=${types_asked} must be 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_asked = Shale.arg!("root", "")
	root = if self_test {
		"${plants}typed/QuietApp.roc"
	} else {
		root_asked
	}
	optionals = read_word_set!("optionals.txt")
	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!("check_how_failure_is_reported", self_test)
		# The self-test's untyped plants are exempt from being reached by its
		# root.
		exempt = if self_test {
			Set.from_list(Shale.glob!("${plants}*.roc"))
		} else {
			Set.empty()
		}
		Types.gather!({ who: "check_how_failure_is_reported", kind: Expressions, root, roc, paths, exempt })
	} else {
		{ typing: RocTypes.no_types, unreached: [] }
	}
	var $parsed = []
	var $refused = []
	for file in Shale.roc_tree!(paths) {
		if file.err == "" {
			$parsed = $parsed.append({ path: file.path, nodes: file.nodes })
		} else if file.err.starts_with(file.path) {
			$refused = $refused.append(file.err)
		} else {
			$refused = $refused.append("${file.path}: ${file.err}")
		}
	}
	forest = Forest.join($parsed)
	aliases = ErrorAlias.judge(forest)
	optional_found = OptionalTag.judge(forest, optionals)
	findings = aliases.findings
		.concat(optional_found.map(|found| found.finding))
		.concat(Fallbacks.judge!(forest, types.typing))
	unjudged = Text.sort_bytewise(aliases.unjudged.keys())
	counted = unjudged.map(|name| "${name} (${(aliases.unjudged.get(name) ?? 0).to_str()})")
	unjudged_said = if counted.is_empty() {
		""
	} else {
		"; error_alias not judged, declared outside the files hunted: ${Str.join_with(counted, ", ")}"
	}
	summary = "check_how_failure_is_reported (Roc): ${paths.len().to_str()} files; ${Finding.counts_of(findings, checks)}${unjudged_said}"
	print_findings!(summary, findings.map(line_of))
	fail_if_refused!($refused, types.unreached)
	if self_test {
		judged = { paths, findings, optionals: optional_found, unjudged }
		SelfTest.run!(judged, checks)
	}
}

## The checks, in the order the summary counts them.
checks : List(Str)
checks = ["error_alias", "optional_tag", "set_fallback", "placeholder", "number_fallback"]

## A finding as its line, `path:line: check: what`, its line `?` when no node
## from the finding's on has one.
line_of : Finding -> Str
line_of = |finding|
	if finding.line == 0 {
		"${finding.path}:?: ${finding.check}: ${finding.what}"
	} else {
		Finding.line_of(finding)
	}

## The words listed in cookbook/words/<file>, one a line, `--` starting a
## note. A line of two words, or a word listed twice, stops the run.
read_word_set! : Str => Set(Str)
read_word_set! = |file| {
	text = match Shale.read!("cookbook:words/${file}") {
		Found(found) => found
		Missing => {
			Shale.fail!("check_how_failure_is_reported: no cookbook/words/${file}")
			""
		}
	}
	var $words = Set.empty()
	for line in Text.lines(text) {
		word = Text.trim(Text.before_first(line, "--"))
		if word.contains(" ") or $words.contains(word) {
			Shale.fail!("check_how_failure_is_reported: cookbook/words/${file}: `${word}` is not a single word, or is listed twice")
		}
		if word != "" {
			$words = $words.insert(word)
		}
	}
	$words
}

## 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!("check_how_failure_is_reported: ${Str.join_with($why, "; ")}; every other file was judged")
	}
}

cookbook/roc/check_how_failure_is_reported/ErrorAlias.roc, 214 lines

## The `error_alias` check: a function's result is a `Try` whose error is an
## alias of tags (`ReadError : [Missing, Failed]`, or a module's
## `Accounts.Unreadable`) instead of the tags written in place. The alias is
## looked up in the files checked, through up to 8 aliases of aliases: first
## among the file's own declarations, then by its qualified name, which a
## file's top-level types also have by the file's module name (`Access.Answer`
## for `Answer` in Access.roc). Only top-level and module-member annotations
## are read. An error declared outside the files checked can't be judged, and
## is counted by name for the summary.
import lib.Finding
import lib.Forest
import lib.Tree

ErrorAlias := [].{

	## The findings, in the order of the annotations and of the errors inside
	## each result, and how often each error declared outside the files was
	## named.
	judge : Forest -> { findings : List(Finding), unjudged : Dict(Str, U64) }
	judge = |forest| {
		declared = declarations_of(forest)
		var $findings = []
		var $unjudged = Dict.empty()
		$at : U64
		var $at = 0
		while $at < Forest.count(forest) {
			$at = $at + 1
			annotation = $at
			signature = Forest.kid(forest, annotation, 1)
			is_judged = Forest.kind(forest, annotation) == "s-type-anno" and is_top_level(forest, annotation)
			if is_judged and Forest.kind_or_none(forest, signature) == "ty-fn" {
				result = Forest.kids(forest, signature).last() ?? 0
				last = Forest.last_descendant(forest, result)
				$inside : U64
				var $inside = result
				while $inside <= last {
					error = try_error(forest, $inside)
					error_name = if error > 0 {
						Forest.name(forest, error)
					} else {
						""
					}
					if error_name != "" and Forest.kind(forest, error) == "ty" {
						path = Forest.path(forest, annotation)
						match error_kind(forest, declared, { path, name: error_name, hops: 0 }) {
							Union => {
								$findings = $findings.append(alias_finding(forest, annotation, error_name))
							}
							Unknown => {
								counted = ($unjudged.get(error_name) ?? 0) + 1
								$unjudged = $unjudged.insert(error_name, counted)
							}
							Other => {}
						}
					}
					$inside = $inside + 1
				}
			}
		}
		{ findings: $findings, unjudged: $unjudged }
	}
}

## Every type declared in the files checked, by its qualified name (and a
## file's top-level ones by the module's name too), and by its file's path
## and bare name: the place of what it is declared as.
Declared : { qualified : Dict(Str, U64), in_file : Dict(Str, U64) }

declarations_of : Forest -> Declared
declarations_of = |forest| {
	var $qualified = Dict.empty()
	var $in_file = Dict.empty()
	$at : U64
	var $at = 0
	while $at < Forest.count(forest) {
		$at = $at + 1
		name = declared_name(forest, $at)
		if name != "" {
			definition = Forest.kid(forest, $at, 2)
			qualified = nested_name(forest, $at)
			path = Forest.path(forest, $at)
			$qualified = $qualified.insert(qualified, definition)
			if qualified == name {
				$qualified = $qualified.insert("${Tree.module_name(path)}.${name}", definition)
			}
			$in_file = $in_file.insert("${path}|${name}", definition)
		}
	}
	{ qualified: $qualified, in_file: $in_file }
}

## The kinds of node above a top-level or member annotation.
top_level_kinds : Set(Str)
top_level_kinds = Set.from_list(["file", "statements", "s-type-decl", "associated"])

## Whether every node above the one at `at` is a file, its statements, a type
## declaration, or a type's associated block.
is_top_level : Forest, U64 -> Bool
is_top_level = |forest, at| {
	var $above = Forest.parent(forest, at)
	while $above > 0 {
		if !(top_level_kinds.contains(Forest.kind(forest, $above))) {
			return Bool.False
		}
		$above = Forest.parent(forest, $above)
	}
	Bool.True
}

## The name the type declaration at `at` declares, `""` if it is not one.
declared_name : Forest, U64 -> Str
declared_name = |forest, at|
	if Forest.kind(forest, at) != "s-type-decl" or Forest.kids(forest, at).len() < 2 {
		""
	} else {
		Forest.name(forest, Forest.kid(forest, at, 1))
	}

## The declaration's name qualified by the declarations around it
## (`Stored.Problem`).
nested_name : Forest, U64 -> Str
nested_name = |forest, at| {
	var $names = [declared_name(forest, at)]
	var $above = Forest.parent(forest, at)
	while $above > 0 {
		around = declared_name(forest, $above)
		if around != "" {
			$names = List.prepend($names, around)
		}
		$above = Forest.parent(forest, $above)
	}
	Str.join_with($names, ".")
}

builtin_types : Set(Str)
builtin_types = Set.from_list([
	"Str",
	"Bool",
	"U8",
	"U16",
	"U32",
	"U64",
	"U128",
	"I8",
	"I16",
	"I32",
	"I64",
	"I128",
	"F32",
	"F64",
	"Dec",
	"List",
	"Dict",
	"Set",
	"Box",
])

## What an error type is: an alias of tags, a type declared outside the
## files checked, or anything else (a record, a builtin, an empty union).
ErrorKind : [Union, Unknown, Other]

## The kind of the error type `name` named in `path`, followed through `hops`
## aliases so far, at most 8.
error_kind : Forest, Declared, { path : Str, name : Str, hops : U64 } -> ErrorKind
error_kind = |forest, declared, named| {
	found = match declared.in_file.get("${named.path}|${named.name}") {
		Ok(at) => Ok(at)
		Err(_) => declared.qualified.get(named.name)
	}
	if builtin_types.contains(named.name) {
		Other
	} else {
		match found {
			Err(_) => Unknown
			Ok(at) => {
				kind = Forest.kind(forest, at)
				aliased = Forest.name(forest, at)
				if kind == "ty-tag-union" {
					if Forest.union_tags(forest, at).is_empty() {
						Other
					} else {
						Union
					}
				} else if kind == "ty" and aliased != "" and named.hops < 8 {
					error_kind(forest, declared, { ..named, name: aliased, hops: named.hops + 1 })
				} else {
					Other
				}
			}
		}
	}
}

## The error of a `Try(ok, error)` type at `at`, 0 for any other node.
try_error : Forest, U64 -> U64
try_error = |forest, at|
	if Forest.kind(forest, at) != "ty-apply" or Forest.kids(forest, at).len() != 3 {
		0
	} else if Forest.name(forest, Forest.kid(forest, at, 1)) == "Try" {
		Forest.kid(forest, at, 3)
	} else {
		0
	}

alias_finding : Forest, U64, Str -> Finding
alias_finding = |forest, annotation, error_name| {
	fixes = "list the tags it can return in place, or leave the error to inference (`_`)"
	{
		path: Forest.path(forest, annotation),
		line: Forest.line_number(forest, annotation),
		check: "error_alias",
		what: "`${Forest.name(forest, annotation)}` fails with `${error_name}`, a shared alias of tags: ${fixes}",
	}
}

cookbook/roc/check_how_failure_is_reported/Fallbacks.roc, 174 lines

## The checks of what a `??` falls back to:
##
## - `set_fallback`: `List.set(l, i, v) ?? l`, or `l.set(i, v) ?? l`, where
##   the fallback is the list being stored into: a placeholder, and on a
##   list of strings a copy on every store in the dev build.
## - `placeholder`: a fallback that is a string literal with nothing
##   interpolated (`?? "bogus"`, `?? ""`).
## - `number_fallback`: a fallback that is a number after a lookup by index
##   (`List.get(l, i) ?? 0`, `l.get(i) ?? 0`); with the types, after any
##   lookup that fails only with `[OutOfBounds]`.
##
## With the types, a finding names the fallback's type and the tags the
## lookup fails with. Each `??` is judged by the three in that order.
import pf.Shale
import lib.Finding
import lib.Forest
import lib.RocTypes

Fallbacks := [].{

	## The findings, in the order of the `??`s, with the expressions' types
	## when the run has them.
	judge! : Forest, RocTypes.Typing => List(Finding)
	judge! = |forest, typing| {
		var $findings = []
		$at : U64
		var $at = 0
		while $at < Forest.count(forest) {
			$at = $at + 1
			at = $at
			is_fallback = Forest.kind(forest, at) == "e-binop" and Forest.attribute(forest, at, "op") == "??"
			if is_fallback and Forest.kids(forest, at).len() == 2 {
				pair = {
					lookup: Forest.kid(forest, at, 1),
					fallback: Forest.kid(forest, at, 2),
					path: Forest.path(forest, at),
				}
				$findings = $findings.concat(judge_pair!(forest, typing, pair))
			}
		}
		$findings
	}
}

## A `??`'s two sides and its file.
Pair : { lookup : U64, fallback : U64, path : Str }

## What one `??` is: its set_fallback, its placeholder, its number_fallback.
judge_pair! : Forest, RocTypes.Typing, Pair => List(Finding)
judge_pair! = |forest, typing, pair| {
	has_types = typing.real.contains(pair.path)
	lookup_error = if has_types {
		lookup_error_of!(forest, typing, pair)
	} else {
		""
	}
	lookup_said = if lookup_error != "" {
		", for a lookup that fails with `${lookup_error}`"
	} else {
		""
	}
	line = Forest.line_number(forest, pair.fallback)
	at_fallback = |check, what| { path: pair.path, line, check, what }
	var $findings = []
	target = list_stored_into(forest, pair.lookup)
	if target > 0 and is_same(forest, target, pair.fallback) {
		why = "the fallback names `l`, an answer no store means (and on a list of strings a copy on every store in the dev build); write `?? crash \"...\"` instead"
		cited = "(roc-apps CLAUDE.md, \"Performance: know what copies\")"
		$findings = $findings.append(at_fallback("set_fallback", "`List.set(l, i, v) ?? l`: ${why} ${cited}"))
	}
	style = "(roc-apps docs/roc-style.md, \"Errors and failure\")"
	if is_literal_text(forest, pair.fallback) {
		text = Str.join_with(Forest.kids(forest, pair.fallback).map(|part| Forest.raw(forest, part)), "")
		typed = if has_types {
			", a Str${lookup_said}"
		} else {
			""
		}
		why = "if the lookup can't fail, `crash` with a reason, \"never a silent `?? default`\"; if it can, keep that case as a tag"
		$findings = $findings.append(at_fallback("placeholder", "falls back to the literal `\"${text}\"`${typed}: ${why} ${style}"))
	}
	is_judged_lookup = lookup_error == "[OutOfBounds]" or (!(has_types) and is_index_lookup(forest, pair.lookup))
	if is_number(forest, pair.fallback) and is_judged_lookup {
		number = Forest.raw(forest, pair.fallback)
		typed = if has_types {
			", a ${type_at(forest, typing, { path: pair.path, at: pair.fallback }) ?? "?"}"
		} else {
			""
		}
		why = "an index past the end is a bug, not a ${number}; `crash` with a reason, or keep the case as a tag"
		$findings = $findings.append(at_fallback("number_fallback", "falls back to `${number}`${typed}${lookup_said}: ${why} ${style}"))
	}
	$findings
}

## The tag union the lookup's `Try` fails with, such as `[OutOfBounds]`, or
## `""` when the checker gave it no such type.
lookup_error_of! : Forest, RocTypes.Typing, Pair => Str
lookup_error_of! = |forest, typing, pair|
	match type_at(forest, typing, { path: pair.path, at: pair.lookup }) {
		Ok(lookup_type) =>
			match Shale.re_find!(lookup_type, "^Try\\((.*), (\\[[^\\[\\]]*\\])\\)$") {
				Found(matched) => matched.groups.get(1) ?? ""
				NoMatch => ""
			}
		Err(_) => ""
	}

## The checker's type of the expression at a place in a file it reached.
type_at : Forest, RocTypes.Typing, { path : Str, at : U64 } -> Try(Str, [NoType])
type_at = |forest, typing, spot| RocTypes.type_at(typing, spot.path, Forest.node(forest, spot.at))

## Whether the expressions at two places are the same value written twice
## (`board`, `r.b`): the same kinds, names and fields, all the way down.
is_same : Forest, U64, U64 -> Bool
is_same = |forest, first, second| {
	is_alike = |attribute| Forest.attribute(forest, first, attribute) == Forest.attribute(forest, second, attribute)
	first_kids = Forest.kids(forest, first)
	second_kids = Forest.kids(forest, second)
	if Forest.kind(forest, first) != Forest.kind(forest, second) or !(is_alike("raw")) or !(is_alike("field")) {
		Bool.False
	} else if first_kids.len() != second_kids.len() {
		Bool.False
	} else {
		List.map2(first_kids, second_kids, |a, b| (a, b)).all(|(a, b)| is_same(forest, a, b))
	}
}

## The list that the `List.set(l, i, v)` or `l.set(i, v)` call at a place
## stores into, 0 for any other expression.
list_stored_into : Forest, U64 -> U64
list_stored_into = |forest, at| {
	kind = Forest.kind(forest, at)
	kids = Forest.kids(forest, at)
	callee = Forest.kid(forest, at, 1)
	if kind == "e-apply" and kids.len() == 4 and Forest.kind_or_none(forest, callee) == "e-ident" and Forest.raw(forest, callee) == "List.set" {
		Forest.kid(forest, at, 2)
	} else if kind == "e-method-call" and Forest.attribute(forest, at, "method") == ".set" {
		is_receiver = |kid| Forest.kind(forest, kid) == "receiver" and Forest.kids(forest, kid).len() == 1
		match kids.find_first(is_receiver) {
			Ok(receiver) => Forest.kid(forest, receiver, 1)
			Err(_) => 0
		}
	} else {
		0
	}
}

## Whether the expression at a place is a string literal with nothing
## interpolated.
is_literal_text : Forest, U64 -> Bool
is_literal_text = |forest, at| {
	is_part = |kid| Forest.kind(forest, kid) == "e-string-part"
	Forest.kind(forest, at) == "e-string" and Forest.kids(forest, at).all(is_part)
}

## Whether the expression at a place is a lookup by index: `List.get(l, i)`
## or `l.get(i)`.
is_index_lookup : Forest, U64 -> Bool
is_index_lookup = |forest, at| {
	kind = Forest.kind(forest, at)
	callee = Forest.kid(forest, at, 1)
	if kind == "e-apply" and Forest.kind_or_none(forest, callee) == "e-ident" {
		Forest.raw(forest, callee) == "List.get"
	} else {
		kind == "e-method-call" and Forest.attribute(forest, at, "method") == ".get"
	}
}

is_number : Forest, U64 -> Bool
is_number = |forest, at| {
	kind = Forest.kind(forest, at)
	kind == "e-int" or kind == "e-frac"
}

cookbook/roc/check_how_failure_is_reported/OptionalTag.roc, 87 lines

## The `optional_tag` check: a tag named like an optional (`Some`, `None`,
## `Nothing`; cookbook/words/optionals.txt lists them), matched by its whole
## name. A type that names one beside a tag with a payload is a finding at
## the tag's line; with no payload there, the union is a mode with two ways
## (`[Words, None]`). A tag in an expression or a pattern is a finding once a
## file, at its first use, only when no type in the files checked names it.
import lib.Finding
import lib.Forest
import lib.Text

OptionalTag := [].{

	## A finding with the tag it names, which the self-test holds to the
	## finding's line.
	Found : { finding : Finding, tag : Str }

	## The findings of the types, in the order of their tags, then those of
	## the uses no type names, by path and tag.
	judge : Forest, Set(Str) -> List(OptionalTag.Found)
	judge = |forest, optionals| {
		var $found = []
		var $in_types = Set.empty()
		var $first_uses = Dict.empty()
		$at : U64
		var $at = 0
		while $at < Forest.count(forest) {
			$at = $at + 1
			at = $at
			kind = Forest.kind(forest, at)
			path = Forest.path(forest, at)
			if kind == "ty-tag-union" {
				tags = Forest.union_tags(forest, at)
				has_payload = tags.any(|tag| Forest.kind(forest, tag) == "ty-apply")
				for tag in tags {
					name = Forest.tag_name(forest, tag)
					if optionals.contains(name) {
						$in_types = $in_types.insert(name)
						if has_payload {
							line = Forest.line_number(forest, tag)
							$found = $found.append(in_type({ path, line, tag: name }))
						}
					}
				}
			} else if kind == "e-tag" or kind == "p-tag" {
				name = Forest.raw(forest, at)
				key = "${path}|${name}"
				if optionals.contains(name) and !($first_uses.contains(key)) {
					use = { path, line: Forest.line_number(forest, at), tag: name }
					$first_uses = $first_uses.insert(key, use)
				}
			}
		}
		for key in Text.sort_bytewise($first_uses.keys()) {
			match $first_uses.get(key) {
				Ok(use) =>
					if !($in_types.contains(use.tag)) {
						$found = $found.append(unnamed_use(use))
					}
				Err(_) => {}
			}
		}
		$found
	}
}

## Where an optional tag is, and which.
Place : { path : Str, line : U64, tag : Str }

## An optional named by a type beside a tag with a payload.
in_type : Place -> OptionalTag.Found
in_type = |place| {
	why = "tag what the value is, and its absence by why (`[Latest(Message), NoMessage]`)"
	found(place, "`${place.tag}` names an optional: ${why}")
}

## An optional used where no type in the files read names it.
unnamed_use : Place -> OptionalTag.Found
unnamed_use = |place| {
	why = "tag the value by what it is, and its absence by why"
	found(place, "`${place.tag}` names an optional, and no type in the files read says what it is: ${why}")
}

found : Place, Str -> OptionalTag.Found
found = |place, what| {
	finding: { path: place.path, line: place.line, check: "optional_tag", what },
	tag: place.tag,
}

cookbook/roc/check_how_failure_is_reported/SelfTest.roc, 130 lines

## The recipe's self-test, run after the checks over the plants in
## cookbook/roc/plants/check_how_failure_is_reported/ 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; every error a plant names must be
## declared in a plant; and every `optional_tag` finding must point at a line
## that names its tag.
import pf.Shale
import lib.Finding
import lib.Text

SelfTest := [].{

	## What the checks found over the plants.
	Judged : {
		paths : List(Str),
		findings : List(Finding),
		optionals : List({ finding : Finding, tag : Str }),
		unjudged : List(Str),
	}

	## The plants' verdict printed, then a stop when any plant is wrong.
	run! : SelfTest.Judged, List(Str) => {}
	run! = |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_mine = is_plant_for(plant_name(path), check)
				if is_mine {
					$planted = $planted + 1
				}
				did_fire = fired.contains("${path}|${check}")
				if is_mine and !(did_fire) {
					$failures = $failures.append("`${check}` does not fire on its plant ${path}")
				}
				if did_fire and !(is_mine) {
					$failures = $failures.append("`${check}` fires on ${path}, another check's plant")
				}
			}
			if $planted == 0 {
				$failures = $failures.append("`${check}` has no plant")
			}
		}
		# No check would ever fail on a plant named for none of them.
		for path in judged.paths {
			name = plant_name(path)
			is_named = name.starts_with("quiet_") or checks.any(|check| is_plant_for(name, check))
			if !(is_named) {
				$failures = $failures.append("${path}: a plant the table does not judge")
			}
		}
		# Every error a plant names is declared in a plant; otherwise a quiet
		# plant could pass without `error_alias` judging it.
		for error_name in judged.unjudged {
			$failures = $failures.append("`error_alias` cannot judge `${error_name}`, declared in no plant")
		}
		for optional in judged.optionals {
			finding = optional.finding
			source_lines = read_text!(finding.path).split_on("\n")
			is_named_there = finding.line != 0 and Text.line_at(source_lines, finding.line).contains(optional.tag)
			if !(is_named_there) {
				line = if finding.line == 0 {
					"?"
				} else {
					finding.line.to_str()
				}
				$failures = $failures.append("`optional_tag` says ${finding.path}:${line}, a line that does not name `${optional.tag}`")
			}
		}
		for failure in $failures {
			Shale.print!("FAIL ${failure}")
		}
		if !($failures.is_empty()) {
			Shale.fail!("check_how_failure_is_reported self_test: ${$failures.len().to_str()} plants wrong")
		}
		proof = "each check fires on its plants alone, the quiet_ plants on none, each optional at its tag's line"
		Shale.print!("check_how_failure_is_reported (Roc) self_test: PASS (${proof})")
	}

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

read_text! : Str => Str
read_text! = |path|
	match Shale.read!(path) {
		Found(text) => text
		Missing => {
			Shale.fail!("check_how_failure_is_reported self_test: ${path} went missing during the check")
			""
		}
	}

## A plant's name below the plants' folder. A typed plant's module name is
## read in snake case: `typed/PlaceholderIndex.roc` is
## `placeholder_index.roc`.
plant_name : Str -> Str
plant_name = |path| {
	name = path.drop_prefix(SelfTest.plants)
	if name.starts_with("typed/") {
		snake_case(name.drop_prefix("typed/"))
	} else {
		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)
}

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

cookbook/roc/check_how_failure_is_reported/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"
		}
	}

Shale original

cookbook/roc/check_errors.shale, 462 lines, at 37f08365

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).

-- This recipe checks how Roc code reports failure, against the rules in
-- roc-apps docs/roc-style.md ("Errors and failure"). It reads each .roc
-- file's parse tree from Roc's own parser, so text in a comment or a string
-- never matches. A finding is a question for the reader, not a verdict.
-- There are five checks:
--
--   error_alias   A function's result is a `Try` whose error is an alias of
--                 tags (`ReadError : [Missing, Failed]`, or a module's
--                 `Accounts.Unreadable`) instead of the tags written in
--                 place. A shared alias makes every caller handle tags its
--                 function can't return. The alias is looked up in the files
--                 checked, through an alias of an alias. An error that is not
--                 a tag union (a record, a `Str`), an alias in an argument,
--                 an inferred error (`_`) and a type variable are all fine.
--                 An error declared outside the files checked can't be
--                 judged, so the summary line names it.
--   optional_tag  A tag named like an optional (`Some`, `None`, `Nothing`;
--                 the full list is cookbook/words/optionals.txt). A value
--                 that may be absent should be tagged by what it is, and its
--                 absence by why (`[Latest(Message), NoMessage]`). A type
--                 that names such a tag beside a tag with a payload is a
--                 finding at the tag's line. With no payload there, the union
--                 is a mode with two ways (`[Words, None]`), and `None` is one
--                 of them. A tag in an expression or a pattern is a finding,
--                 once per file, only when no type in the files checked names
--                 it, so read the whole tree. A tag matches by its whole name:
--                 `NoneChosen` is not `None`.
--   set_fallback  `List.set(l, i, v) ?? l`, or `l.set(i, v) ?? l`, where the
--                 fallback is the list being stored into. Naming `l` there
--                 makes every store copy the list (roc-apps CLAUDE.md, "Six
--                 shapes copy").
--   placeholder   A `??` whose fallback is a string literal with nothing
--                 interpolated (`?? "bogus"`, `?? ""`). The style guide asks
--                 for a `crash` with a reason when the lookup can't fail, and
--                 a tag for the case when it can.
--   number_fallback  A `??` that falls back to a number after a lookup by
--                 index, `List.get(l, i) ?? 0.0` or `l.get(i) ?? 0.0`. An index
--                 past the end is a bug, not a zero. Without types `.get` is
--                 taken for a `List`'s, so a `Dict`'s may read here; `Dict.get`
--                 and any other lookup are left alone.
--
-- `error_alias` reads only top-level and module-member annotations. The
-- `??` checks read every expression.
--
-- With `types=1 root=app/main.roc` (or `root=a.roc,b.roc` for several apps)
-- the recipe also asks Roc's type checker (cookbook/roc/types.shale). A
-- placeholder finding then names the fallback's type and the tags the lookup
-- fails with, and `number_fallback` goes by the lookup's type instead of its
-- name: any lookup that fails only with `[OutOfBounds]`. A lookup that can
-- fail with `KeyNotFound` or `ListWasEmpty` may fall back to a number, since
-- zero is often the right answer for a count or a total. A file that no root
-- reaches is checked without types, listed after the findings, and fails the
-- run.
--
-- The recipe prints a summary line of counts, one line per finding
-- (`path:line: check: why`), and the summary again. A file that does not
-- parse is listed after the findings and fails the run, once every other
-- file has been checked.
--
--   cd <repo> && shale <shale>/cookbook/roc/check_errors.shale glob='app/**/*.roc'
--   shale cookbook:roc/check_errors.shale self_test=1
--
-- `self_test=1` runs the checks over the plants in cookbook/roc/plants/check_errors/
-- (and its typed/ folder, with the types and root typed/QuietApp.roc). 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. Every `optional_tag` finding must
-- point at a line that names its tag.
-- budget: steps=400000000 arena_bytes=3000000000 output_bytes=4000000

const SELF_TEST = arg("self_test", "") == "1"
const PLANTS = "cookbook:roc/plants/check_errors/"
const GLOB = SELF_TEST and (PLANTS .. "*.roc") or arg("glob", "**/*.roc")
const CHECKS = {"error_alias", "optional_tag", "set_fallback", "placeholder", "number_fallback"}
use("cookbook:findings.shale")
use("./parsed.shale")
use("./pinned.shale")
use("./types.shale")
const TYPES_ARG = arg("types", "0")
if TYPES_ARG ~= "0" and TYPES_ARG ~= "1" then fail("check_errors: types=" .. TYPES_ARG .. " must be 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 words listed in cookbook/words/<file>, one per line, with `--`
-- starting a note.
function read_word_set(file)
  local words = {}
  for l in lines(read("cookbook:words/" .. file)) do
    local w = trim(split(l, "--")[1])
    if contains(w, " ") or has_key(words, w) then fail("check_errors: cookbook/words/" .. file .. ": `" .. w .. "` is not a single word, or is listed twice") end
    if w ~= "" then words[w] = true end
  end
  return words
end
const OPTIONALS = read_word_set("optionals.txt")

const finding_counts = {}
for c in CHECKS do finding_counts[c] = 0 end
const fired = {}
const finding_lines = {}

function record_finding(path, line, check, why)
  push(finding_lines, path .. ":" .. line .. ": " .. check .. ": " .. why)
  finding_counts[check] = finding_counts[check] + 1
  fired[path .. "|" .. check] = true
  return nil
end

const paths = glob(GLOB)
if SELF_TEST then
  for q in glob(PLANTS .. "typed/*.roc") do push(paths, q) end
end
-- The self-test's untyped plants are exempt from being reached by its root.
const TYPES = USE_TYPES and roc_types_for_files("check_errors", ROOT, roc_bin("check_errors", SELF_TEST), paths, SELF_TEST and set_of(glob(PLANTS .. "*.roc")) or {}) or {real = {}, pats = {}, exprs = {}, unreached = {}}
const PARSED = parse_roc_files(paths)

-- Every parsed file's nodes, in one list. Each node's `parent` and `kids`
-- are indexes into this list, and a root's `parent` is 0. NODE_PATH holds
-- each node's file.
const NODES = {}
const NODE_PATH = {}
for f in PARSED.files do
  local offset = #NODES
  for n in f.nodes do
    local ks = {}
    for k in n.kids do push(ks, k + offset) end
    n.kids = ks
    if n.parent > 0 then n.parent = n.parent + offset end
    push(NODES, n)
    push(NODE_PATH, f.path)
  end
end

function kids(at)
  return NODES[at].kids
end

-- Nodes are in source order, each before its kids, so a subtree runs from
-- its root to this node.
function last_descendant(at)
  local i = at
  while #NODES[i].kids > 0 do i = NODES[i].kids[#NODES[i].kids] end
  return i
end

function kind(at)
  return NODES[at].kind
end

function node_name(at)
  return get(NODES[at], "name", "")
end

function node_raw(at)
  return get(NODES[at], "raw", "")
end

-- A node with no line of its own takes the line of the next node that has
-- one.
function node_line(at)
  local i = at
  while i <= #NODES and NODES[i].line == 0 do i = i + 1 end
  return i <= #NODES and NODES[i].line or "?"
end

-- Each tag of the tag union at `at`, as a whole node (`Some(U64)`).
function union_tag_nodes(at)
  local out = {}
  for t in kids(at) do
    if kind(t) == "tags" then
      for g in kids(t) do push(out, g) end
    end
  end
  return out
end

-- The name of a tag node: `Some` for `Some(U64)`.
function tag_name(g)
  if kind(g) == "ty-apply" then return node_name(kids(g)[1]) end
  return node_name(g)
end

function union_tag_names(at)
  local out = {}
  for g in union_tag_nodes(at) do push(out, tag_name(g)) end
  return out
end

-- ── error_alias ──────────────────────────────────────────────────────────

const TOP_LEVEL_KINDS = {file = true, statements = true, ["s-type-decl"] = true, associated = true}

-- Whether the annotation at `at` is top-level or a module member: every
-- node above it is a file, its statements, a type declaration, or a type's
-- associated block.
function is_top_level(at)
  local p = NODES[at].parent
  while p > 0 do
    if not has_key(TOP_LEVEL_KINDS, kind(p)) then return false end
    p = NODES[p].parent
  end
  return true
end

-- The name the type declaration at `at` declares, or "" if `at` is not one.
function declared_name(at)
  local ks = kids(at)
  if kind(at) ~= "s-type-decl" or #ks < 2 then return "" end
  return node_name(ks[1])
end

-- The type declaration at `at`'s name, qualified by the declarations
-- around it (`Stored.Problem`).
function nested_name(at)
  local inner_first = {declared_name(at)}
  local p = NODES[at].parent
  while p > 0 do
    if declared_name(p) ~= "" then push(inner_first, declared_name(p)) end
    p = NODES[p].parent
  end
  local outer_first = {}
  for k = #inner_first, 1, -1 do push(outer_first, inner_first[k]) end
  return join(outer_first, ".")
end

-- Every type declared in the files checked, mapped to the node of what it
-- is declared as. DECLARED_QUALIFIED is keyed by the qualified name, and a
-- file's top-level types also by the file's module name (`Access.Answer`
-- for `Answer` in Access.roc). DECLARED_IN_FILE is keyed by path and bare
-- name.
const DECLARED_QUALIFIED = {}
const DECLARED_IN_FILE = {}
for i = 1, #NODES do
  local name = declared_name(i)
  if name ~= "" then
    local definition = kids(i)[2]
    local qualified = nested_name(i)
    DECLARED_QUALIFIED[qualified] = definition
    if qualified == name then
      local file_name = split(NODE_PATH[i], "/")
      file_name = file_name[#file_name]
      DECLARED_QUALIFIED[sub(file_name, 1, #file_name - 4) .. "." .. name] = definition
    end
    DECLARED_IN_FILE[NODE_PATH[i] .. "|" .. name] = definition
  end
end

const BUILTIN_TYPES = {Str = true, Bool = true, U8 = true, U16 = true, U32 = true, U64 = true, U128 = true, I8 = true, I16 = true, I32 = true, I64 = true, I128 = true, F32 = true, F64 = true, Dec = true, List = true, Dict = true, Set = true, Box = true}

-- What the error type named `name` in `path` is: "union" for an alias of
-- tags (followed through up to 8 aliases of aliases), "unknown" for a type
-- declared outside the files checked, or "other" for anything else (a
-- record, a builtin, an empty module type).
function error_kind(path, name, hops)
  if has_key(BUILTIN_TYPES, name) then return "other" end
  local at = get(DECLARED_IN_FILE, path .. "|" .. name) or get(DECLARED_QUALIFIED, name)
  if at == nil then return "unknown" end
  if kind(at) == "ty-tag-union" then return #union_tag_names(at) > 0 and "union" or "other" end
  if kind(at) == "ty" and node_name(at) ~= "" and hops < 8 then return error_kind(path, node_name(at), hops + 1) end
  return "other"
end

-- The error node of a `Try(ok, error)` type at `at`, or 0 for any other node.
function try_error_node(at)
  local ks = kids(at)
  if kind(at) == "ty-apply" and #ks == 3 and node_name(ks[1]) == "Try" then return ks[3] end
  return 0
end

-- How many times each error declared outside the files checked is named.
const unjudged_errors = {}

for i = 1, #NODES do
  if kind(i) == "s-type-anno" and is_top_level(i) then
    local ks = kids(i)
    if #ks > 0 and kind(ks[1]) == "ty-fn" then
      local parts = kids(ks[1])
      local result = parts[#parts]
      for j = result, last_descendant(result) do
        local err = try_error_node(j)
        if err > 0 and node_name(err) ~= "" and kind(err) == "ty" then
          local name = node_name(err)
          local ek = error_kind(NODE_PATH[i], name, 0)
          if ek == "union" then record_finding(NODE_PATH[i], node_line(i), "error_alias", "`" .. node_name(i) .. "` fails with `" .. name .. "`, a shared alias of tags: list the tags it can return in place, or leave the error to inference (`_`)") end
          if ek == "unknown" then unjudged_errors[name] = get(unjudged_errors, name, 0) + 1 end
        end
      end
    end
  end
end

-- ── optional_tag ─────────────────────────────────────────────────────────

-- The optional tags some type names, and the first use of each optional
-- tag in an expression or pattern, keyed by path and tag.
const optionals_in_types = {}
const first_optional_uses = {}
-- Each `optional_tag` finding as `{path, line, tag}`, for the self-test.
const optional_findings = {}
for i = 1, #NODES do
  local k = kind(i)
  if k == "ty-tag-union" then
    local has_payload = false
    for g in union_tag_nodes(i) do
      if kind(g) == "ty-apply" then has_payload = true end
    end
    for g in union_tag_nodes(i) do
      local t = tag_name(g)
      if has_key(OPTIONALS, t) then
        optionals_in_types[t] = true
        if has_payload then
          push(optional_findings, {path = NODE_PATH[i], line = node_line(g), tag = t})
          record_finding(NODE_PATH[i], node_line(g), "optional_tag", "`" .. t .. "` names an optional: tag what the value is, and its absence by why (`[Latest(Message), NoMessage]`)")
        end
      end
    end
  elseif k == "e-tag" or k == "p-tag" then
    local t = node_raw(i)
    local key = NODE_PATH[i] .. "|" .. t
    if has_key(OPTIONALS, t) and not has_key(first_optional_uses, key) then first_optional_uses[key] = {path = NODE_PATH[i], line = node_line(i), tag = t} end
  end
end
for key in sort(keys(first_optional_uses)) do
  local first_use = first_optional_uses[key]
  if not has_key(optionals_in_types, first_use.tag) then
    push(optional_findings, first_use)
    record_finding(first_use.path, first_use.line, "optional_tag", "`" .. first_use.tag .. "` names an optional, and no type in the files read says what it is: tag the value by what it is, and its absence by why")
  end
end

-- ── set_fallback and placeholder: what a `??` falls back to ──────────────

-- Whether the expressions at `a` and `b` are the same value written twice
-- (`board`, `r.b`): the same kinds, names and fields, all the way down.
function same_expr(a, b)
  if kind(a) ~= kind(b) or node_raw(a) ~= node_raw(b) or get(NODES[a], "field", "") ~= get(NODES[b], "field", "") then return false end
  local ka = kids(a)
  local kb = kids(b)
  if #ka ~= #kb then return false end
  for k = 1, #ka do
    if not same_expr(ka[k], kb[k]) then return false end
  end
  return true
end

-- The list that the `List.set(l, i, v)` or `l.set(i, v)` call at `at`
-- stores into, or 0 for any other expression.
function set_target(at)
  local ks = kids(at)
  if kind(at) == "e-apply" and #ks == 4 and kind(ks[1]) == "e-ident" and node_raw(ks[1]) == "List.set" then return ks[2] end
  if kind(at) == "e-method-call" and get(NODES[at], "method", "") == ".set" then
    for k in ks do
      if kind(k) == "receiver" and #kids(k) == 1 then return kids(k)[1] end
    end
  end
  return 0
end

-- Whether `at` is a string literal with nothing interpolated.
function is_literal_str(at)
  if kind(at) ~= "e-string" then return false end
  for k in kids(at) do
    if kind(k) ~= "e-string-part" then return false end
  end
  return true
end

-- Whether `at` is a lookup by index: `List.get(l, i)` or `l.get(i)`.
function is_index_lookup(at)
  local ks = kids(at)
  if kind(at) == "e-apply" and kind(ks[1]) == "e-ident" then return node_raw(ks[1]) == "List.get" end
  return kind(at) == "e-method-call" and get(NODES[at], "method", "") == ".get"
end

function is_number(at)
  return kind(at) == "e-int" or kind(at) == "e-frac"
end

for i = 1, #NODES do
  local ks = kids(i)
  if kind(i) == "e-binop" and get(NODES[i], "op", "") == "??" and #ks == 2 then
    local lookup = ks[1]
    local fallback = ks[2]
    local path = NODE_PATH[i]
    local target = set_target(lookup)
    if target > 0 and same_expr(target, fallback) then record_finding(path, node_line(fallback), "set_fallback", "`List.set(l, i, v) ?? l`: the fallback names `l`, so every store copies; write `?? crash \"...\"` instead (roc-apps CLAUDE.md, \"Six shapes copy\")") end
    -- With types, the tag union the lookup's `Try` fails with, such as
    -- `[OutOfBounds]`, or "" when it is unknown.
    local has_types = USE_TYPES and has_key(TYPES.real, path)
    local lookup_error = ""
    if has_types then
      local lookup_type = roc_type_at(TYPES, "expr", path, NODES[lookup])
      local m = lookup_type ~= nil and re_find(lookup_type, "^Try\\((.*), (\\[[^\\[\\]]*\\])\\)$") or nil
      if m ~= nil then lookup_error = m.groups[2] end
    end
    local lookup_said = lookup_error ~= "" and (", for a lookup that fails with `" .. lookup_error .. "`") or ""
    if is_literal_str(fallback) then
      local text = ""
      for k in kids(fallback) do text = text .. node_raw(k) end
      record_finding(path, node_line(fallback), "placeholder", "falls back to the literal `\"" .. text .. "\"`" .. (has_types and (", a Str" .. lookup_said) or "") .. ": if the lookup can't fail, `crash` with a reason, \"never a silent `?? default`\"; if it can, keep that case as a tag (roc-apps docs/roc-style.md, \"Errors and failure\")")
    end
    if is_number(fallback) and (lookup_error == "[OutOfBounds]" or (not has_types and is_index_lookup(lookup))) then
      local fallback_type = has_types and (", a " .. (roc_type_at(TYPES, "expr", path, NODES[fallback]) or "?")) or ""
      record_finding(path, node_line(fallback), "number_fallback", "falls back to `" .. node_raw(fallback) .. "`" .. fallback_type .. lookup_said .. ": an index past the end is a bug, not a " .. node_raw(fallback) .. "; `crash` with a reason, or keep the case as a tag (roc-apps docs/roc-style.md, \"Errors and failure\")")
    end
  end
end

local counts = {}
for c in CHECKS do push(counts, c .. " " .. finding_counts[c]) end
local unjudged = {}
for n in sort(keys(unjudged_errors)) do push(unjudged, n .. " (" .. unjudged_errors[n] .. ")") end
local unjudged_said = #unjudged > 0 and ("; error_alias not judged, declared outside the files hunted: " .. join(unjudged, ", ")) or ""
print_findings("check_errors (Roc): " .. #paths .. " files; " .. join(counts, ", ") .. unjudged_said, finding_lines)
fail_if_refused("check_errors", PARSED.refused, TYPES.unreached)

-- A plant's name relative to PLANTS. A typed plant's module name is read
-- in snake case: `typed/PlaceholderIndex.roc` is `placeholder_index.roc`.
function plant_name(path)
  local name = sub(path, #PLANTS + 1)
  if starts_with(name, "typed/") then return snake_case_plant_name(sub(name, 7)) end
  return name
end

function is_plant_for(name, check)
  return name == check .. ".roc" or starts_with(name, check .. "_")
end

if SELF_TEST then
  local failures = {}
  for c in CHECKS do
    local planted = 0
    for p in paths do
      local mine = is_plant_for(plant_name(p), c)
      if mine then planted = planted + 1 end
      local did_fire = has_key(fired, p .. "|" .. c)
      if mine and not did_fire then push(failures, "`" .. c .. "` does not fire on its plant " .. p) end
      if did_fire and not mine then push(failures, "`" .. c .. "` fires on " .. p .. ", another check's plant") end
    end
    if planted == 0 then push(failures, "`" .. c .. "` has no plant") end
  end
  -- No check would ever fail on a plant named for none of them.
  for p in paths do
    local name = plant_name(p)
    local named = starts_with(name, "quiet_")
    for c in CHECKS do
      if is_plant_for(name, c) then named = true end
    end
    if not named then push(failures, p .. ": a plant the table does not judge") end
  end
  -- Every error a plant names is declared in a plant; otherwise a quiet
  -- plant could pass without `error_alias` judging it.
  for n in sort(keys(unjudged_errors)) do push(failures, "`error_alias` cannot judge `" .. n .. "`, declared in no plant") end
  for f in optional_findings do
    local source_lines = split(read(f.path), "\n")
    if f.line == "?" or not contains(source_lines[f.line], f.tag) then push(failures, "`optional_tag` says " .. f.path .. ":" .. f.line .. ", a line that does not name `" .. f.tag .. "`") end
  end
  for w in failures do print("FAIL " .. w) end
  if #failures > 0 then fail("check_errors self_test: " .. #failures .. " plants wrong") end
  print("check_errors (Roc) self_test: PASS (each check fires on its plants alone, the quiet_ plants on none, each optional at its tag's line)")
end