find_and_remove_extra_parentheses

Roc

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

cookbook/roc/find_and_remove_extra_parentheses/find_and_remove_extra_parentheses.roc, 89 lines

## find_and_remove_extra_parentheses, in Roc on Shale's platform (roc_platform/README.md):
## the parentheses and braceless `if`s that a code emitter leaves in Roc,
## which neither `roc check` nor `roc fmt` sees, found and, with `write=1`,
## rewritten. Its launcher, cookbook/roc/find_and_remove_extra_parentheses.shale, is how it
## is run, and its header says the checks (`paren_if`, `wrapped_body`,
## `else_block`, `lambda_if`) and the rewrite. check_goldens.shale, beside
## this, holds its output on the plants to its goldens, line for line.
##
##   cd <repo> && shale cookbook:roc/find_and_remove_extra_parentheses.shale glob=chat/**/*.roc
##   cd <repo> && shale cookbook:roc/find_and_remove_extra_parentheses.shale glob=chat/**/*.roc write=1
##   shale cookbook:roc/find_and_remove_extra_parentheses.shale self_test=1
##
## The arguments: `glob` (`**/*.roc`), `house` (`house=0` leaves out the
## house style, `paren_if` and `lambda_if`), `write` (`write=1` rewrites the
## files) and `self_test` (`self_test=1` checks the plants and rewrites
## copies of them).
##
## This root globs the files (`Shale.glob!`), rewrites them when asked
## (Rewriting, by Edits), reports (Report, by Checks) and prints the verdict
## (`Shale.print!`, `Shale.fail!`); SelfTest is the self-test. Finding, Text
## and Tree are the cookbook's Roc library, cookbook/roc/lib/.
## budget: steps=900000000 read_bytes=1000000000 arena_bytes=2000000000 output_bytes=4000000 programs=100
app [main!] { lib: "../lib/main.roc", pf: platform "../../../roc_platform/platform/main.roc" }

import pf.Shale
import lib.Finding
import Report
import Rewriting
import SelfTest

main! : {} => {}
main! = |{}| {
	self_test = Shale.arg!("self_test", "") == "1"
	pattern = if self_test {
		"${SelfTest.plants}/*.roc"
	} else {
		Shale.arg!("glob", "**/*.roc")
	}
	write = Shale.arg!("write", "") == "1"
	paths = Shale.glob!(pattern)
	settled = if write {
		refuse_house_rewrite!({})
		rewritten = Rewriting.rewrite!(paths, Rewriting.roc_bin!(Bool.False))
		Shale.print!("find_and_remove_extra_parentheses: ${rewritten.made.to_str()} edits")
		rewritten.settled
	} else {
		Dict.empty()
	}
	found = Report.make!(paths, settled)
	print_findings!(found.summary, found.findings.map(Finding.line_of))
	fail_if_refused!(found.refused)
	if self_test {
		SelfTest.run!(paths, found)
	}
}

## A rewrite applies our house style, so `house=0` refuses one.
refuse_house_rewrite! : {} => {}
refuse_house_rewrite! = |{}|
	match Report.read_house!({}) {
		Kept => {}
		LeftOut => Shale.fail!("find_and_remove_extra_parentheses: write=1 applies our house style, so it refuses house=0")
	}

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

## The files Roc's parser refused, named, then a stop (cookbook/roc/parsed.shale's
## `fail_if_refused`); nothing when it refused none.
fail_if_refused! : List(Str) => {}
fail_if_refused! = |refused|
	if !(refused.is_empty()) {
		for refusal in refused {
			Shale.print!("refused: ${refusal}")
		}
		refusals = "roc-ast refused ${refused.len().to_str()} files (named above)"
		why = "which have no tree to judge; every other file was judged"
		Shale.fail!("find_and_remove_extra_parentheses: ${refusals}, ${why}")
	}

cookbook/roc/find_and_remove_extra_parentheses/Report.roc, 124 lines

## The findings across a run's files, as the lines the recipe prints, with
## its summary and the files Roc's parser refused. Findings stay in the files'
## order and the tree's, as the Shale original printed them, never sorted.
import pf.Shale
import Checks
import lib.Finding
import lib.Text

Report := [].{

	## A run's report: its summary, its findings (each `path:line: check:
	## source line`) and why each refused file was refused.
	Report : {
		summary : Str,
		findings : List(Finding),
		refused : List(Str),
	}

	## The report over `paths`. Under `house=0`, the house style
	## (cookbook/roc/house.shale's `paren_if` and `lambda_if`) is left out.
	## `settled` is what a rewrite already knows of a file it read last,
	## unchanged since: `""` for no finding, else why it was refused
	## (`Report.refusal_of`); those files are not read again, as Roc's arena
	## frees nothing and a large tree's second parse would not fit beside its
	## first.
	make! : List(Str), Dict(Str, Str) => Report.Report
	make! = |paths, settled| {
		house = Report.read_house!({})
		unsettled = paths.keep_if(|path| !(settled.contains(path)))
		parsed = if unsettled.is_empty() {
			[]
		} else {
			Shale.roc_tree!(unsettled)
		}
		var $findings = []
		var $refused = []
		$next : U64
		var $next = 0
		for path in paths {
			match settled.get(path) {
				Ok(refusal) =>
					if refusal != "" {
						$refused = $refused.append(refusal)
					}
				Err(_) => {
					file = match parsed.get($next) {
						Ok(found) => found
						Err(_) => crash "Report.make!: roc_tree! gave fewer files than it was asked for"
					}
					$next = $next + 1
					if file.err == "" {
						source_lines = Report.read_text!(file.path).split_on("\n")
						for found in Checks.findings_in(file.nodes, source_lines) {
							if is_kept(house, found.check) {
								$findings = $findings.append({
									path: file.path,
									line: found.line,
									check: found.check,
									what: Text.trim(Text.line_at(source_lines, found.line)),
								})
							}
						}
					} else {
						$refused = $refused.append(Report.refusal_of(file.path, file.err))
					}
				}
			}
		}
		house_note = match house {
			Kept => ""
			LeftOut => "; left out as house style: ${Str.join_with(house_style, ", ")}"
		}
		counts = Finding.counts_of($findings, Checks.names)
		summary = "find_and_remove_extra_parentheses (Roc): ${paths.len().to_str()} files; ${counts}${house_note}"
		{ summary, findings: $findings, refused: $refused }
	}

	## Why roc-ast refused a file, beginning with its path
	## (cookbook/roc/parsed.shale's `parse_roc_files`).
	refusal_of : Str, Str -> Str
	refusal_of = |path, err|
		if err.starts_with(path) {
			err
		} else {
			"${path}: ${err}"
		}

	## Whether `house=0` leaves the house style out (cookbook/roc/house.shale).
	read_house! : {} => [Kept, LeftOut]
	read_house! = |{}| {
		house = Shale.arg!("house", "1")
		if house != "0" and house != "1" {
			Shale.fail!("house must be 1 (the default) or 0, not ${house}")
		}
		if house == "0" {
			LeftOut
		} else {
			Kept
		}
	}

	## A file's text; a file gone since the glob stops the run.
	read_text! : Str => Str
	read_text! = |path|
		match Shale.read!(path) {
			Found(text) => text
			Missing => {
				Shale.fail!("find_and_remove_extra_parentheses: no file ${path}")
				""
			}
		}
}

## The checks that are only our house style (cookbook/roc/house.shale).
house_style : List(Str)
house_style = ["paren_if", "lambda_if"]

## Whether a finding of `check` is reported.
is_kept : [Kept, LeftOut], Str -> Bool
is_kept = |house, check|
	match house {
		Kept => Bool.True
		LeftOut => !(house_style.contains(check))
	}

cookbook/roc/find_and_remove_extra_parentheses/Rewriting.roc, 172 lines

## `write=1`: the files rewritten, one check a pass (Edits), each pass's
## files put through `roc fmt`, until a pass changes nothing, because taking
## off one pair of brackets can show the next. The Roc is the tree's own
## (cookbook/roc/pinned.shale), run by its OS path.
import pf.Shale
import Checks
import Edits
import Report
import lib.Text
import lib.Tree

Rewriting := [].{

	## Rewrites `paths` until a pass changes nothing, and answers how many
	## edits it made and what it knows of each file it read last: `settled`,
	## `""` for a file with no finding, else why roc-ast refused it
	## (Report.make!'s `settled`). Such a file is read no more, since no edit
	## will touch it, so a large tree is parsed whole once, not four times a
	## pass, which Roc's arena (it frees nothing) would not hold.
	rewrite! : List(Str), Str => { made : U64, settled : Dict(Str, Str) }
	rewrite! = |paths, roc| {
		$made : U64
		var $made = 0
		var $live = paths
		var $settled = Dict.empty()
		var $changed = Bool.True
		while $changed {
			$changed = Bool.False
			for check in Checks.names {
				pass = rewrite_check!($live, check, roc)
				$live = pass.live
				for (path, verdict) in pass.settled {
					$settled = $settled.insert(path, verdict)
				}
				if pass.made > 0 {
					$made = $made + pass.made
					$changed = Bool.True
				}
			}
		}
		{ made: $made, settled: $settled }
	}

	## The OS path of the Roc to rewrite with: in a self-test the pin every
	## recipe's self-test runs (pinned.shale's `SELF_TEST_PIN`, read there),
	## else the one the `roc-version` where the run starts names.
	roc_bin! : Bool => Str
	roc_bin! = |self_test| {
		pin = if self_test {
			self_test_pin!({})
		} else {
			if !(Shale.exists!("roc-version")) {
				Shale.fail!("find_and_remove_extra_parentheses: no roc-version where the run starts: run it from the repository's root, whose roc-version pins its Roc")
			}
			Text.trim(Report.read_text!("roc-version"))
		}
		roc = "tools:roc-${pin}/roc"
		if !(Shale.exists!(roc)) {
			Shale.fail!("find_and_remove_extra_parentheses: 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}" {
			Shale.fail!("find_and_remove_extra_parentheses: ${roc} says ${Text.trim(said.out)}, not Roc compiler version ${pin}")
		}
		real
	}
}

## Makes one kind of edit across `paths`, and answers how many it made, which
## files had a finding of any check (the files still worth reading) and what
## is settled of the rest, each `(path, verdict)` as `rewrite!` keeps it.
rewrite_check! : List(Str), Str, Str => { made : U64, live : List(Str), settled : List((Str, Str)) }
rewrite_check! = |paths, check, roc| {
	$made : U64
	var $made = 0
	var $touched = []
	var $live = []
	var $settled = []
	if !(paths.is_empty()) {
		for file in Shale.roc_tree!(paths) {
			if file.err == "" {
				done = rewrite_file!({ path: file.path, nodes: file.nodes }, check)
				if done.found_any {
					$live = $live.append(file.path)
				} else {
					$settled = $settled.append((file.path, ""))
				}
				if done.made > 0 {
					$made = $made + done.made
					$touched = $touched.append(file.path)
				}
			} else {
				$settled = $settled.append((file.path, Report.refusal_of(file.path, file.err)))
			}
		}
	}
	if !($touched.is_empty()) {
		format!($touched, roc)
	}
	{ made: $made, live: $live, settled: $settled }
}

## One kind of edit in one file: how many it made, and whether the file had a
## finding of any check. A finding inside another's span of the same kind is
## safe: its brackets are its own.
rewrite_file! : { path : Str, nodes : List(Tree.Node) }, Str => { made : U64, found_any : Bool }
rewrite_file! = |file, check| {
	text = Report.read_text!(file.path)
	source_lines = text.split_on("\n")
	findings = Checks.findings_in(file.nodes, source_lines)
	bytes = text.to_utf8()
	source = { path: file.path, text: bytes, nodes: file.nodes }
	found_any = !(findings.is_empty())
	match Edits.for_check(source, findings, check) {
		Err(why) => {
			Shale.fail!(why)
			{ made: 0, found_any }
		}
		Ok([]) => { made: 0, found_any }
		Ok(edits) =>
			match Edits.applied(bytes, edits) {
				Err(why) => {
					Shale.fail!(why)
					{ made: 0, found_any }
				}
				Ok(rewritten) => {
					Shale.write!(file.path, Str.from_utf8_lossy(rewritten))
					{ made: edits.len(), found_any }
				}
			}
	}
}

## The files put through the tree's own formatter.
format! : List(Str), Str => {}
format! = |paths, roc| {
	var $argv = [roc, "fmt"]
	for path in paths {
		$argv = $argv.append(Shale.real!(path))
	}
	result = Shale.run!({
		argv: $argv,
		keep: Tail(20),
		timeout_ms: 120000,
		want: "roc-pin: the tree's own formatter",
	})
	if result.code != 0 {
		Shale.print!(result.out)
		Shale.fail!("find_and_remove_extra_parentheses: `${roc} fmt` exited ${result.code.to_str()}")
	}
}

## pinned.shale's `SELF_TEST_PIN`, the one home of the self-tests' Roc.
self_test_pin! : {} => Str
self_test_pin! = |{}| {
	pinned = "cookbook:roc/pinned.shale"
	match Shale.re_find!(Report.read_text!(pinned), "\nconst SELF_TEST_PIN = \"([^\"]+)\"") {
		Found(found) =>
			match found.groups {
				[pin] => pin
				_ => {
					Shale.fail!("find_and_remove_extra_parentheses: no SELF_TEST_PIN in ${pinned}")
					""
				}
			}
		NoMatch => {
			Shale.fail!("find_and_remove_extra_parentheses: no SELF_TEST_PIN in ${pinned}")
			""
		}
	}
}

cookbook/roc/find_and_remove_extra_parentheses/SelfTest.roc, 111 lines

## The recipe's self-test, the Shale original's: each plant in
## cookbook/roc/plants/find_and_remove_extra_parentheses/ held to its marks (a line ending
## `# paren_if`, `# wrapped_body`, `# else_block` or `# lambda_if` must give
## that finding, and no unmarked line may give one), then the plants copied
## to `scratch:parens/` and rewritten there: every file must still parse, no
## finding may be left, a second rewrite must change nothing, and a plant with
## a `.want` file must come out as it.
import pf.Shale
import Checks
import Report
import Rewriting
import lib.Finding
import lib.Text

SelfTest := [].{

	## The plants, whose `*.roc` a self-test checks.
	plants : Str
	plants = "cookbook:roc/plants/find_and_remove_extra_parentheses"

	## The self-test of `paths`, the plants, given their report.
	run! : List(Str), Report.Report => {}
	run! = |paths, found| {
		marked = check_marks!(paths, found.findings)
		var $wrong = marked.wrong
		if marked.marks == 0 {
			$wrong = $wrong.append("no plant holds a mark")
		}
		if Shale.exists!(scratch) {
			Shale.remove_tree!(scratch)
		}
		Shale.mkdir!(scratch)
		copies = paths.map(copy_of)
		for path in paths {
			Shale.write!(copy_of(path), Report.read_text!(path))
		}
		roc = Rewriting.roc_bin!(Bool.True)
		rewritten = Rewriting.rewrite!(copies, roc)
		left = Report.make!(copies, rewritten.settled)
		for finding in left.findings {
			$wrong = $wrong.append("left after the rewrite: ${Finding.line_of(finding)}")
		}
		for refusal in left.refused {
			$wrong = $wrong.append("the rewrite broke a file: ${refusal}")
		}
		for path in paths {
			want = "${Text.bytes_of(path, { start: 0, count: path.count_utf8_bytes() - 4 })}.want"
			copy = copy_of(path)
			if Shale.exists!(want) and Report.read_text!(copy) != Report.read_text!(want) {
				$wrong = $wrong.append("${copy}: not as ${want}")
			}
		}
		if Rewriting.rewrite!(copies, roc).made != 0 {
			$wrong = $wrong.append("a second rewrite changed something")
		}
		Shale.remove_tree!(scratch)
		for wrong in $wrong {
			Shale.print!("FAIL ${wrong}")
		}
		if !($wrong.is_empty()) {
			Shale.fail!("find_and_remove_extra_parentheses self_test: ${$wrong.len().to_str()} plants wrong")
		}
		proof = "each marked line gives its finding, no other line one; the rewrite leaves none, and a second changes nothing"
		Shale.print!("find_and_remove_extra_parentheses (Roc) self_test: PASS (${proof})")
	}
}

## Where the self-test rewrites its copies of the plants.
scratch : Str
scratch = "scratch:parens"

## A plant's copy in `scratch`.
copy_of : Str -> Str
copy_of = |path| "${scratch}/${Text.basename(path)}"

## Each plant's lines held to the findings: what is wrong, and how many marks
## there were.
check_marks! : List(Str), List(Finding) => { wrong : List(Str), marks : U64 }
check_marks! = |paths, findings| {
	var $wrong = []
	$marks : U64
	var $marks = 0
	for path in paths {
		$number : U64
		var $number = 0
		for line in Text.lines(Report.read_text!(path)) {
			$number = $number + 1
			number = $number
			key = "${path}:${number.to_str()}"
			got = findings
				.keep_if(|finding| finding.path == path and finding.line == number)
				.map(|finding| finding.check)
			match Checks.names.find_first(|check| line.ends_with("# ${check}")) {
				Ok(mark) => {
					$marks = $marks + 1
					if !(got.contains(mark)) {
						$wrong = $wrong.append("${key}: no ${mark} finding")
					}
					if got.len() > 1 {
						$wrong = $wrong.append("${key}: more than the one finding marked")
					}
				}
				Err(_) =>
					if !(got.is_empty()) {
						$wrong = $wrong.append("${key}: a finding (${Str.join_with(got, ", ")}) on a line not marked for one")
					}
			}
		}
	}
	{ wrong: $wrong, marks: $marks }
}

cookbook/roc/find_and_remove_extra_parentheses/Checks.roc, 145 lines

## The four checks of find_and_remove_extra_parentheses, over Roc's tree of a file: the
## parentheses and braceless `if`s that a code emitter leaves (the launcher,
## cookbook/roc/find_and_remove_extra_parentheses.shale, says each rule). A finding names
## the node it stands on, so a rewrite (Edits) can take its brackets off.
import lib.Text
import lib.Tree

Checks := [].{

	## A finding: its check, its line, and the place of the node it stands
	## on, counted from 1 as the tree counts.
	Found : { check : Str, line : U64, at : U64 }

	## The checks, in the order the summary counts them and a rewrite makes
	## them.
	names : List(Str)
	names = ["paren_if", "wrapped_body", "else_block", "lambda_if"]

	## Each finding in a file, node by node in the tree's order; at one node,
	## `wrapped_body`, `paren_if`, `else_block`, then `lambda_if`.
	## `source_lines` is the file's text split at each newline.
	findings_in : List(Tree.Node), List(Str) -> List(Checks.Found)
	findings_in = |nodes, source_lines| {
		var $found = []
		$place : U64
		var $place = 1
		for node in nodes {
			at = $place
			if wraps_body(nodes, at) {
				$found = $found.append({ check: "wrapped_body", line: node.line, at })
			}
			if Checks.is_paren_if(nodes, at) {
				$found = $found.append({ check: "paren_if", line: node.line, at })
			}
			if is_else_block(nodes, at) {
				$found = $found.append({ check: "else_block", line: node.line, at })
			}
			if is_lambda_if(nodes, at, source_lines) {
				$found = $found.append({ check: "lambda_if", line: node.line, at })
			}
			$place = $place + 1
		}
		$found
	}

	## Whether a node is a pair of parentheses: a one-item tuple.
	is_parens : Tree.Node -> Bool
	is_parens = |node| node.kind == "e-tuple" and node.kids.len() == 1

	## Whether a branch is a block, in braces.
	has_braces : Tree.Node -> Bool
	has_braces = |node| node.kind == "e-block"

	## Whether an `else` branch needs no braces added: it has them, or it is
	## the next `if` of an `else if`.
	else_is_braced : Tree.Node -> Bool
	else_is_braced = |otherwise|
		Checks.has_braces(otherwise) or otherwise.kind == "e-if-then-else"

	## Whether the node at `at` is an `if` with its condition wholly in
	## parentheses, or a branch with no braces.
	is_paren_if : List(Tree.Node), U64 -> Bool
	is_paren_if = |nodes, at| {
		node = Tree.node_at(nodes, at)
		if node.kind != "e-if-then-else" {
			Bool.False
		} else {
			condition = Tree.node_at(nodes, Tree.kid_at(node, 1))
			then_branch = Tree.node_at(nodes, Tree.kid_at(node, 2))
			otherwise = Tree.node_at(nodes, Tree.kid_at(node, 3))
			Checks.is_parens(condition) or !(Checks.has_braces(then_branch)) or !(Checks.else_is_braced(otherwise))
		}
	}
}

## Whether the node at `at` is the last of its parent's kids.
is_last_kid : List(Tree.Node), U64 -> Bool
is_last_kid = |nodes, at| {
	node = Tree.node_at(nodes, at)
	Tree.last_kid(Tree.node_at(nodes, node.parent)) == at
}

## Whether parentheses at `at` wrap a whole body. The value of a declaration
## counts only over several lines; a statement counts wherever it stands, and
## `if`'s branches are paren_if's and the block's own.
wraps_body : List(Tree.Node), U64 -> Bool
wraps_body = |nodes, at| {
	node = Tree.node_at(nodes, at)
	if !(Checks.is_parens(node)) or node.parent == 0 {
		Bool.False
	} else {
		parent_kind = Tree.node_at(nodes, node.parent).kind
		if parent_kind == "statements" {
			Bool.True
		} else if parent_kind == "e-lambda" or parent_kind == "branch" {
			is_last_kid(nodes, at)
		} else if parent_kind == "s-decl" {
			is_last_kid(nodes, at) and node.end_line > node.line
		} else {
			Bool.False
		}
	}
}

## Whether the node at `at` is an `if` whose `else` is a block holding only
## another `if`: `else { if ... }`, which is `else if ...`.
is_else_block : List(Tree.Node), U64 -> Bool
is_else_block = |nodes, at| {
	node = Tree.node_at(nodes, at)
	if node.kind != "e-if-then-else" {
		Bool.False
	} else {
		otherwise = Tree.node_at(nodes, Tree.kid_at(node, 3))
		Checks.has_braces(otherwise) and holds_only_an_if(nodes, otherwise)
	}
}

## Whether a block's one statement is an `if`.
holds_only_an_if : List(Tree.Node), Tree.Node -> Bool
holds_only_an_if = |nodes, block| {
	statements = Tree.node_at(nodes, Tree.first_kid(block))
	match statements.kids {
		[only] => Tree.node_at(nodes, only).kind == "e-if-then-else"
		_ => Bool.False
	}
}

## Whether the node at `at` is an `if` that is a lambda's whole body and
## shares its line with what comes before it, which can only be the lambda's
## `|`.
is_lambda_if : List(Tree.Node), U64, List(Str) -> Bool
is_lambda_if = |nodes, at, source_lines| {
	node = Tree.node_at(nodes, at)
	if node.kind != "e-if-then-else" or node.parent == 0 {
		Bool.False
	} else if Tree.node_at(nodes, node.parent).kind != "e-lambda" or !(is_last_kid(nodes, at)) {
		Bool.False
	} else if Checks.is_paren_if(nodes, at) {
		Bool.False
	} else {
		line = Text.line_at(source_lines, node.line)
		before = Text.bytes_of(line, { start: 0, count: node.column - 1 })
		Text.trim(before) != ""
	}
}

cookbook/roc/find_and_remove_extra_parentheses/Edits.roc, 344 lines

## The edits that fix one check's findings in a file, made by the parser's
## spans, and the file's text with them made. Places in the text are counted
## from 1, as Shale's `sub` counts: an edit at `at` cuts `cut` bytes there and
## puts `put` in their place. A span the tree lacks, or two edits that
## overlap, is an `Err` saying so, which the caller stops the run with: a
## guess here would write braces into the wrong place.
import Checks
import lib.Tree

Edits := [].{

	## A file being rewritten: its path, its text's bytes and its tree.
	Source : { path : Str, text : List(U8), nodes : List(Tree.Node) }

	## One edit: `cut` bytes at `at` taken out, `put` put there.
	Edit : { at : U64, cut : U64, put : Str }

	## The edits that fix the findings of `check` among `findings`.
	for_check : Edits.Source, List(Checks.Found), Str -> Try(List(Edits.Edit), Str)
	for_check = |source, findings, check| {
		src = { path: source.path, text: source.text, nodes: source.nodes, starts: line_starts(source.text) }
		var $edits = []
		for finding in findings {
			if finding.check == check {
				$edits = $edits.concat(edits_of(src, finding)?)
			}
		}
		Ok($edits)
	}

	## The text with the edits made. At one place, an edit that only inserts
	## goes first, so that a closing brace nested in a branch's end stands
	## before the one that cuts the space after it; edits equal in both keep
	## their order.
	applied : List(U8), List(Edits.Edit) -> Try(List(U8), Str)
	applied = |text, edits| {
		var $numbered = []
		for edit in edits {
			$numbered = $numbered.append({ edit, number: $numbered.len() })
		}
		ordered = $numbered.sort_with(edit_order).map(|numbered| numbered.edit)
		var $pieces = []
		$from : U64
		var $from = 1
		for edit in ordered {
			if edit.at < $from {
				return Err("find_and_remove_extra_parentheses: two edits overlap at index ${edit.at.to_str()}")
			}
			$pieces = $pieces.concat(span(text, $from, edit.at - 1)).concat(edit.put.to_utf8())
			$from = edit.at + edit.cut
		}
		Ok($pieces.concat(span(text, $from, text.len())))
	}
}

## A file being rewritten, with where each of its lines starts.
Src : { path : Str, text : List(U8), nodes : List(Tree.Node), starts : List(U64) }

## By place, then by what is cut, then by the order they were made in.
edit_order : { edit : Edits.Edit, number : U64 }, { edit : Edits.Edit, number : U64 } -> [Before, Same, After]
edit_order = |first, second|
	match compare(first.edit.at, second.edit.at) {
		Same =>
			match compare(first.edit.cut, second.edit.cut) {
				Same => compare(first.number, second.number)
				other => other
			}
		other => other
	}

compare : U64, U64 -> [Before, Same, After]
compare = |first, second|
	if first < second {
		Before
	} else if first > second {
		After
	} else {
		Same
	}

## The edits that fix one finding.
edits_of : Src, Checks.Found -> Try(List(Edits.Edit), Str)
edits_of = |src, finding| {
	nodes = src.nodes
	node = Tree.node_at(nodes, finding.at)
	if finding.check == "wrapped_body" {
		inner = Tree.node_at(nodes, Tree.first_kid(node))
		Ok(bracket_removal(src, node, keeps_break(nodes, node, inner)))
	} else if finding.check == "else_block" {
		Ok(bracket_removal(src, Tree.node_at(nodes, Tree.kid_at(node, 3)), Bool.False))
	} else if finding.check == "lambda_if" {
		from = start_of(src, finding.at)?
		after = before_space(src.text, from)
		Ok([{ at: after, cut: from - after, put: "\n" }])
	} else {
		paren_if_edits(src, node)
	}
}

## The edits that take an `if`'s condition out of its parentheses and put
## braces around each branch that has none.
paren_if_edits : Src, Tree.Node -> Try(List(Edits.Edit), Str)
paren_if_edits = |src, node| {
	nodes = src.nodes
	condition_at = Tree.kid_at(node, 1)
	then_at = Tree.kid_at(node, 2)
	otherwise_at = Tree.kid_at(node, 3)
	var $edits = []
	if Checks.is_parens(Tree.node_at(nodes, condition_at)) {
		$edits = $edits.concat(bracket_removal(src, Tree.node_at(nodes, condition_at), Bool.False))
	}
	if !(Checks.has_braces(Tree.node_at(nodes, then_at))) {
		$edits = $edits.append(opening_brace(src, then_at, end_of(src, condition_at)?)?)
		$edits = $edits.append(brace_before_else(src, then_at)?)
	}
	if !(Checks.else_is_braced(Tree.node_at(nodes, otherwise_at))) {
		after_else = past_else(src, end_of(src, then_at)?)?
		$edits = $edits.append(opening_brace(src, otherwise_at, after_else)?)
		$edits = $edits.append({ at: end_of(src, otherwise_at)?, cut: 0, put: " }" })
	}
	Ok($edits)
}

## Where each line starts in `text`, the first line at 1.
line_starts : List(U8) -> List(U64)
line_starts = |text| {
	var $starts = [1]
	$place : U64
	var $place = 1
	for byte in text {
		if byte == '\n' {
			$starts = $starts.append($place + 1)
		}
		$place = $place + 1
	}
	$starts
}

## The place of a line's column, both counted from 1.
offset_of : Src, U64, U64 -> U64
offset_of = |src, line, column| {
	start = match src.starts.get(line - 1) {
		Ok(found) => found
		Err(_) => crash "find_and_remove_extra_parentheses: ${src.path} has no line ${line.to_str()}"
	}
	start + column - 1
}

## The byte at a place counted from 1, 0 past either end.
byte_at : List(U8), U64 -> U8
byte_at = |text, at|
	if at == 0 {
		0
	} else {
		text.get(at - 1) ?? 0
	}

## The bytes from place `from` to place `to`, both counted from 1 and kept
## inside the text, as Shale's `sub` takes them.
span : List(U8), U64, U64 -> List(U8)
span = |text, from, to| {
	start = if from < 1 {
		1
	} else {
		from
	}
	if to < start {
		[]
	} else {
		text.sublist({ start: start - 1, len: to + 1 - start })
	}
}

## Whether the bytes from `from` to `to` hold a `#`.
has_comment : List(U8), U64, U64 -> Bool
has_comment = |text, from, to| span(text, from, to).contains('#')

## Whether the bytes from `from` on spell `word`.
spells : List(U8), U64, Str -> Bool
spells = |text, from, word| span(text, from, from + word.count_utf8_bytes() - 1) == word.to_utf8()

is_space : List(U8), U64 -> Bool
is_space = |text, at| {
	byte = byte_at(text, at)
	byte == ' ' or byte == '\t' or byte == '\n'
}

## The first place at or past `at` that isn't white space.
past_space : List(U8), U64 -> U64
past_space = |text, at| {
	var $place = at
	while is_space(text, $place) {
		$place = $place + 1
	}
	$place
}

## The last place before `at` that isn't white space, plus one.
before_space : List(U8), U64 -> U64
before_space = |text, at| {
	var $place = at
	while $place > 1 and is_space(text, $place - 1) {
		$place = $place - 1
	}
	$place
}

## Where the line holding the place just before `at` starts.
last_line_start : List(U8), U64 -> U64
last_line_start = |text, at| {
	var $place = at - 1
	while $place > 1 and byte_at(text, $place - 1) != '\n' {
		$place = $place - 1
	}
	$place
}

## The first place at or past `at` outside white space and comments.
past_comments : List(U8), U64 -> U64
past_comments = |text, at| {
	var $place = past_space(text, at)
	while byte_at(text, $place) == '#' {
		while $place <= text.len() and byte_at(text, $place) != '\n' {
			$place = $place + 1
		}
		$place = past_space(text, $place)
	}
	$place
}

## The edits that take off the brackets at the ends of `node`: the space
## inside them goes too, so nothing is left of a line that held a bracket
## alone. With `keep_break`, the line break after the opening bracket stays,
## as a body on its own line wants. A comment beside a bracket keeps its line.
bracket_removal : Src, Tree.Node, Bool -> List(Edits.Edit)
bracket_removal = |src, node, keep_break| {
	text = src.text
	opening = offset_of(src, node.line, node.column)
	closing = offset_of(src, node.end_line, node.end_column) - 1
	past_opening = past_space(text, opening + 1)
	cut_to = if keep_break or byte_at(text, past_opening) == '#' {
		opening + 1
	} else {
		past_opening
	}
	before_closing = before_space(text, closing)
	cut_from = if has_comment(text, last_line_start(text, before_closing), before_closing - 1) {
		closing
	} else {
		before_closing
	}
	[
		{ at: opening, cut: cut_to - opening, put: "" },
		{ at: cut_from, cut: closing + 1 - cut_from, put: "" },
	]
}

## A body keeps its own line after `|x|`, `=>` or `=`, unless it is a block,
## whose brace sits there. A statement has nothing before it to keep.
keeps_break : List(Tree.Node), Tree.Node, Tree.Node -> Bool
keeps_break = |nodes, node, inner|
	Tree.node_at(nodes, node.parent).kind != "statements" and inner.kind != "e-block"

no_span : Src, Tree.Node -> Try(U64, Str)
no_span = |src, node| Err("find_and_remove_extra_parentheses: ${src.path}: can't find the ends of a ${node.kind}, which the tree gives no span")

## Where the node at `at` starts. Roc's tree gives a `match` and a unary
## operator no span of their own, so their ends are found from the nodes they
## hold; any other kind with no span is an `Err`.
start_of : Src, U64 -> Try(U64, Str)
start_of = |src, at| {
	node = Tree.node_at(src.nodes, at)
	if node.line != 0 {
		Ok(offset_of(src, node.line, node.column))
	} else if node.kind != "unary" and node.kind != "e-match" {
		no_span(src, node)
	} else {
		before = before_space(src.text, start_of(src, Tree.first_kid(node))?)
		if node.kind == "unary" {
			Ok(before - 1)
		} else if before > 5 and spells(src.text, before - 5, "match") {
			Ok(before - 5)
		} else {
			no_span(src, node)
		}
	}
}

## The place just past the node at `at`.
end_of : Src, U64 -> Try(U64, Str)
end_of = |src, at| {
	node = Tree.node_at(src.nodes, at)
	if node.line != 0 {
		Ok(offset_of(src, node.end_line, node.end_column))
	} else if node.kind == "unary" {
		end_of(src, Tree.first_kid(node))
	} else if node.kind != "e-match" {
		no_span(src, node)
	} else {
		branches = Tree.node_at(src.nodes, Tree.kid_at(node, 2))
		closing = past_comments(src.text, end_of(src, Tree.last_kid(branches))?)
		if byte_at(src.text, closing) == '}' {
			Ok(closing + 1)
		} else {
			no_span(src, node)
		}
	}
}

## The opening brace of the branch at `at`, on the line of what stands before
## it, which ends at `after`, since `roc fmt` keeps a line break before a
## brace. A comment there keeps its place after the brace.
opening_brace : Src, U64, U64 -> Try(Edits.Edit, Str)
opening_brace = |src, at, after| {
	from = start_of(src, at)?
	if has_comment(src.text, after, from - 1) {
		Ok({ at: after, cut: 0, put: " {" })
	} else {
		Ok({ at: after, cut: from - after, put: " { " })
	}
}

## The place just past the `else` that follows `then_end`.
past_else : Src, U64 -> Try(U64, Str)
past_else = |src, then_end| {
	at = past_comments(src.text, then_end)
	if spells(src.text, at, "else") {
		Ok(at + 4)
	} else {
		Err("find_and_remove_extra_parentheses: ${src.path}: no `else` where a branch ended")
	}
}

## The closing brace of a `then` branch, with `else` brought up to it.
brace_before_else : Src, U64 -> Try(Edits.Edit, Str)
brace_before_else = |src, at| {
	to = end_of(src, at)?
	next_word = past_space(src.text, to)
	if spells(src.text, next_word, "else") {
		Ok({ at: to, cut: next_word - to, put: " } " })
	} else {
		Ok({ at: to, cut: 0, put: " }" })
	}
}

Shale original

cookbook/roc/find_extra_parens.shale, 442 lines, at 95f59de8

The libraries it loads: cookbook/findings.shale (21 lines), cookbook/roc/house.shale (46 lines), cookbook/roc/parsed.shale (34 lines), cookbook/roc/pinned.shale (20 lines).

-- This recipe finds the parentheses and braceless `if`s that a code emitter
-- leaves in Roc, and with `write=1` rewrites them. Roc's own formatter keeps
-- both, and adds the condition's parentheses itself to an `if` with no braces,
-- so neither `roc check` nor `roc fmt` sees them. The recipe reads each file's
-- syntax tree from Roc's own parser (cookbook/roc/parsed.shale).
--
--   cd <repo> && shale <shale>/cookbook/roc/find_extra_parens.shale glob=chat/**/*.roc
--   cd <repo> && shale <shale>/cookbook/roc/find_extra_parens.shale glob=chat/**/*.roc write=1
--   shale cookbook:roc/find_extra_parens.shale self_test=1
--
-- The arguments:
--   glob   the files to check, `**/*.roc` by default;
--   house  with `house=0`, leave out `paren_if` and `lambda_if`, which are
--          only our house style (cookbook/roc/house.shale): Luke Boswell's
--          roc-style.md asks for `if (x) a else b`;
--   write  with `write=1`, rewrite the files (see below).
--
-- Each finding is one line, `path:line: check: source line`:
--   paren_if      an `if` written `if (x) a else b`, or with a condition wholly
--                 in parentheses, or a branch with no braces;
--   wrapped_body  parentheses around the whole of a lambda's body, a match
--                 branch's body, a statement or a declaration's multi-line
--                 value (`|x| (...)`, `Some => (...)`, `y = (\n...\n)`);
--   else_block    `else { if ... }`, which is `else if ...`;
--   lambda_if     an `if` that is a lambda's whole body and hangs off its `|`
--                 (`|x| if x > 1 {`). It starts its own line. An `if` that
--                 paren_if also finds gets this finding once that one is fixed.
--
-- Parentheses around one operand or one argument are left alone: they group,
-- and a float's order of operations can rest on them. So is a one-line
-- declaration such as `width = (half * 2.0)`, which holds no structure to hide.
--
-- The output is the counts, the findings, and the counts again
-- (cookbook/findings.shale). Files that don't parse are listed after the
-- findings, and then the run fails.
--
-- With `write=1`, the recipe makes each of these edits by the parser's spans,
-- runs `roc fmt` on the files it changed, and repeats until a pass changes
-- nothing, because taking off one pair can show the next. A comment inside a
-- bracket stays, so it can leave a line a reader tidies. It runs the Roc the
-- tree is built with (cookbook/roc/pinned.shale), from the repository's root.
--
-- `self_test=1` checks the plants in `cookbook/roc/plants/find_extra_parens/`. A plant
-- line ending `# paren_if`, `# wrapped_body`, `# else_block` or `# lambda_if`
-- must give that finding, and no unmarked line may give one. Then the test copies the plants
-- to `scratch:parens/` and rewrites them there: every file must still parse, no
-- finding may be left, a second rewrite must change nothing, and a plant with a
-- `.want` file must come out as it.
--
-- budget: steps=900000000 read_bytes=1000000000 arena_bytes=2000000000 output_bytes=4000000

const SELF_TEST = arg("self_test", "") == "1"
const PLANTS = "cookbook:roc/plants/find_extra_parens"
const SCRATCH = "scratch:parens"
const GLOB = SELF_TEST and (PLANTS .. "/*.roc") or arg("glob", "**/*.roc")
const WRITE = arg("write", "") == "1"
const CHECKS = {"paren_if", "wrapped_body", "else_block", "lambda_if"}
use("cookbook:findings.shale")
use("./house.shale")
use("./parsed.shale")
use("./pinned.shale")

-- A one-item tuple is a pair of parentheses.
function is_parens(node)
  return node.kind == "e-tuple" and #node.kids == 1
end

function is_last_kid(nodes, i)
  local kids = nodes[nodes[i].parent].kids
  return kids[#kids] == i
end

-- Whether parentheses at `i` wrap a whole body. The value of a declaration
-- counts only over several lines; a statement counts wherever it stands, and
-- `if`'s branches are paren_if's and the block's own.
function wraps_body(nodes, i)
  local node = nodes[i]
  if not is_parens(node) or node.parent == 0 then return false end
  local kind = nodes[node.parent].kind
  if kind == "statements" then return true end
  if kind == "e-lambda" or kind == "branch" then return is_last_kid(nodes, i) end
  if kind == "s-decl" then return is_last_kid(nodes, i) and node.end_line > node.line end
  return false
end

function has_braces(node)
  return node.kind == "e-block"
end

function is_paren_if(nodes, i)
  local node = nodes[i]
  if node.kind ~= "e-if-then-else" then return false end
  local kids = node.kids
  local otherwise = nodes[kids[3]]
  return is_parens(nodes[kids[1]]) or not has_braces(nodes[kids[2]])
    or not (has_braces(otherwise) or otherwise.kind == "e-if-then-else")
end

-- The `if` that is the whole of a block, or 0: the block's one statement.
function only_if_in(nodes, block)
  local statements = nodes[nodes[block].kids[1]]
  if #statements.kids ~= 1 then return 0 end
  local only = statements.kids[1]
  if nodes[only].kind == "e-if-then-else" then return only end
  return 0
end

function is_else_block(nodes, i)
  local node = nodes[i]
  if node.kind ~= "e-if-then-else" then return false end
  local otherwise = node.kids[3]
  return has_braces(nodes[otherwise]) and only_if_in(nodes, otherwise) ~= 0
end

-- Whether the node at `i` is an `if` that is a lambda's whole body and shares
-- its line with what comes before it, which can only be the lambda's `|`.
function is_lambda_if(nodes, i, source)
  local node = nodes[i]
  if node.kind ~= "e-if-then-else" or node.parent == 0 then return false end
  if nodes[node.parent].kind ~= "e-lambda" or not is_last_kid(nodes, i) then return false end
  if is_paren_if(nodes, i) then return false end
  return trim(sub(source[node.line], 1, node.col - 1)) ~= ""
end

-- Each file's findings: `{check, line}`, with the node they stand on.
function findings_in(file)
  local found = {}
  local source = split(read(file.path), "\n")
  local i = 1
  while i <= #file.nodes do
    local node = file.nodes[i]
    if wraps_body(file.nodes, i) then push(found, {check = "wrapped_body", line = node.line, at = i}) end
    if is_paren_if(file.nodes, i) then push(found, {check = "paren_if", line = node.line, at = i}) end
    if is_else_block(file.nodes, i) then push(found, {check = "else_block", line = node.line, at = i}) end
    if is_lambda_if(file.nodes, i, source) then push(found, {check = "lambda_if", line = node.line, at = i}) end
    i = i + 1
  end
  return found
end

-- Where each line starts in `text`, as an index into it.
function line_starts(text)
  local starts = {1}
  for at in find_all(text, "\n") do push(starts, at + 1) end
  return starts
end

function offset_of(starts, line, col)
  return starts[line] + col - 1
end

function is_space(text, at)
  local c = sub(text, at, at)
  return c == " " or c == "\t" or c == "\n"
end

-- The first index past `at` that isn't white space.
function past_space(text, at)
  local i = at
  while is_space(text, i) do i = i + 1 end
  return i
end

-- The last index before `at` that isn't white space, plus one.
function before_space(text, at)
  local i = at
  while is_space(text, i - 1) do i = i - 1 end
  return i
end

-- Where the line holding the index just before `at` starts.
function last_line_start(text, at)
  local i = at - 1
  while i > 1 and sub(text, i - 1, i - 1) ~= "\n" do i = i - 1 end
  return i
end

-- The edits that take off the brackets at the ends of `node`: the space inside
-- them goes too, so nothing is left of a line that held a bracket alone. With
-- `keep_break`, the line break after the opening bracket stays, as a body on
-- its own line wants. A comment beside a bracket keeps its line.
function push_bracket_removal(edits, text, starts, node, keep_break)
  local opening = offset_of(starts, node.line, node.col)
  local closing = offset_of(starts, node.end_line, node.end_col) - 1
  local cut_to = past_space(text, opening + 1)
  if keep_break or sub(text, cut_to, cut_to) == "#" then cut_to = opening + 1 end
  push(edits, {at = opening, cut = cut_to - opening, put = ""})
  local cut_from = before_space(text, closing)
  local last_line_from = last_line_start(text, cut_from)
  if contains(sub(text, last_line_from, cut_from - 1), "#") then cut_from = closing end
  push(edits, {at = cut_from, cut = closing + 1 - cut_from, put = ""})
end

-- The first index at or past `at` outside white space and comments.
function past_comments(text, at)
  local i = past_space(text, at)
  while sub(text, i, i) == "#" do
    while i <= #text and sub(text, i, i) ~= "\n" do i = i + 1 end
    i = past_space(text, i)
  end
  return i
end

function fail_no_span(src, node)
  fail("find_extra_parens: " .. src.path .. ": can't find the ends of a " .. node.kind .. ", which the tree gives no span")
end

-- Roc's tree gives a `match` and a unary operator no span of their own, so an
-- edit finds their ends from the nodes they hold. Any other kind with no span
-- stops the run: a guess here would write braces into the wrong place.
function start_of(src, i)
  local node = src.nodes[i]
  if node.line ~= 0 then return offset_of(src.starts, node.line, node.col) end
  if node.kind ~= "unary" and node.kind ~= "e-match" then fail_no_span(src, node) end
  local before = before_space(src.text, start_of(src, node.kids[1]))
  if node.kind == "unary" then return before - 1 end
  if sub(src.text, before - 5, before - 1) ~= "match" then fail_no_span(src, node) end
  return before - 5
end

-- The index just past the node at `i`.
function end_of(src, i)
  local node = src.nodes[i]
  if node.line ~= 0 then return offset_of(src.starts, node.end_line, node.end_col) end
  if node.kind == "unary" then return end_of(src, node.kids[1]) end
  if node.kind ~= "e-match" then fail_no_span(src, node) end
  local branches = src.nodes[node.kids[2]].kids
  local closing = past_comments(src.text, end_of(src, branches[#branches]))
  if sub(src.text, closing, closing) ~= "}" then fail_no_span(src, node) end
  return closing + 1
end

-- The opening brace of the branch at `i`, on the line of what stands before it,
-- which ends at `after`, since `roc fmt` keeps a line break before a brace. A
-- comment there keeps its place after the brace.
function push_opening_brace(edits, src, i, after)
  local from = start_of(src, i)
  if contains(sub(src.text, after, from - 1), "#") then
    push(edits, {at = after, cut = 0, put = " {"})
  else
    push(edits, {at = after, cut = from - after, put = " { "})
  end
end

-- The index just past the `else` that follows `then_end`.
function past_else(src, then_end)
  local at = past_comments(src.text, then_end)
  if sub(src.text, at, at + 3) ~= "else" then fail("find_extra_parens: " .. src.path .. ": no `else` where a branch ended") end
  return at + 4
end

-- The closing brace of a `then` branch, with `else` brought up to it.
function push_brace_before_else(edits, src, i)
  local to = end_of(src, i)
  local next_word = past_space(src.text, to)
  if sub(src.text, next_word, next_word + 3) == "else" then
    push(edits, {at = to, cut = next_word - to, put = " } "})
  else
    push(edits, {at = to, cut = 0, put = " }"})
  end
end

-- A body keeps its own line after `|x|`, `=>` or `=`, unless it is a block,
-- whose brace sits there. A statement has nothing before it to keep.
function keeps_break(nodes, node, inner)
  return nodes[node.parent].kind ~= "statements" and inner.kind ~= "e-block"
end

function push_edits(edits, src, finding)
  local nodes = src.nodes
  local text = src.text
  local starts = src.starts
  local node = nodes[finding.at]
  if finding.check == "wrapped_body" then
    push_bracket_removal(edits, text, starts, node, keeps_break(nodes, node, nodes[node.kids[1]]))
  elseif finding.check == "else_block" then
    push_bracket_removal(edits, text, starts, nodes[node.kids[3]], false)
  elseif finding.check == "lambda_if" then
    local from = start_of(src, finding.at)
    local after = before_space(text, from)
    push(edits, {at = after, cut = from - after, put = "\n"})
  else
    local condition = nodes[node.kids[1]]
    local then_branch = nodes[node.kids[2]]
    local otherwise = nodes[node.kids[3]]
    if is_parens(condition) then push_bracket_removal(edits, text, starts, condition, false) end
    if not has_braces(then_branch) then
      push_opening_brace(edits, src, node.kids[2], end_of(src, node.kids[1]))
      push_brace_before_else(edits, src, node.kids[2])
    end
    if not (has_braces(otherwise) or otherwise.kind == "e-if-then-else") then
      push_opening_brace(edits, src, node.kids[3], past_else(src, end_of(src, node.kids[2])))
      push(edits, {at = end_of(src, node.kids[3]), cut = 0, put = " }"})
    end
  end
end

-- At one index, an edit that only inserts goes first, so that a closing brace
-- nested in a branch's end stands before the one that cuts the space after it.
function with_edits(text, edits)
  sort(edits, {"at", "cut"})
  local pieces = {}
  local from = 1
  for e in edits do
    if e.at < from then fail("find_extra_parens: two edits overlap at index " .. e.at) end
    if e.at > from then push(pieces, sub(text, from, e.at - 1)) end
    push(pieces, e.put)
    from = e.at + e.cut
  end
  if from <= #text then push(pieces, sub(text, from, #text)) end
  return join(pieces, "")
end

-- One kind of edit a pass, so no two edits of a pass touch one place. A finding
-- inside another's span of the same kind is safe: its brackets are its own.
function rewrite_pass(file, check)
  local edits = {}
  local text = read(file.path)
  local src = {path = file.path, text = text, starts = line_starts(text), nodes = file.nodes}
  for finding in findings_in(file) do
    if finding.check == check then push_edits(edits, src, finding) end
  end
  if #edits == 0 then return 0 end
  replace(file.path, with_edits(text, edits))
  return #edits
end

-- Makes one kind of edit across `paths`, and answers how many it made.
function rewrite_check(paths, check, roc)
  local made = 0
  local touched = {}
  for file in parse_roc_files(paths).files do
    local n = rewrite_pass(file, check)
    if n > 0 then
      made = made + n
      push(touched, file.path)
    end
  end
  if #touched > 0 then
    local argv = {roc, "fmt"}
    for p in touched do push(argv, real(p)) end
    must(run(argv, {timeout_ms = 120000, tail = 20, want = "roc-pin: the tree's own formatter"}))
  end
  return made
end

-- Rewrites `paths` until a pass changes nothing, and answers how many edits it
-- made. Each kind runs in its own call, so a tree's parse is gone by the `yield`.
function rewrite(paths, roc)
  local made = 0
  local changed = true
  while changed do
    changed = false
    for check in CHECKS do
      local n = rewrite_check(paths, check, roc)
      if n > 0 then
        made = made + n
        changed = true
      end
      yield()
    end
  end
  return made
end

-- The findings across `paths`, as lines, with the counts.
function report(paths)
  local parsed = parse_roc_files(paths)
  local lines_found = {}
  local counts = {}
  for c in CHECKS do counts[c] = 0 end
  local at_line = {}
  for file in parsed.files do
    local source = split(read(file.path), "\n")
    for f in findings_in(file) do
      if not house_leaves_out("find_extra_parens", f.check) then
        counts[f.check] = counts[f.check] + 1
        push(lines_found, file.path .. ":" .. f.line .. ": " .. f.check .. ": " .. trim(source[f.line]))
        push_at(at_line, file.path .. ":" .. f.line, f.check)
      end
    end
  end
  local said = {}
  for c in CHECKS do push(said, c .. " " .. counts[c]) end
  return {summary = "find_extra_parens (Roc): " .. #paths .. " files; " .. join(said, ", ") .. house_note("find_extra_parens"), lines = lines_found, at_line = at_line, refused = parsed.refused, total = #lines_found}
end

function self_test(paths, found)
  local wrong = {}
  local marks = 0
  for p in paths do
    local n = 0
    for l in lines(read(p)) do
      n = n + 1
      local key = p .. ":" .. n
      local got = {}
      if has_key(found.at_line, key) then got = found.at_line[key] end
      local mark = re_find(l, "# (paren_if|wrapped_body|else_block|lambda_if)$")
      if mark ~= nil then
        marks = marks + 1
        if not has_item(got, mark.group) then push(wrong, key .. ": no " .. mark.group .. " finding") end
        if #got > 1 then push(wrong, key .. ": more than the one finding marked") end
      elseif #got > 0 then
        push(wrong, key .. ": a finding (" .. join(got, ", ") .. ") on a line not marked for one")
      end
    end
  end
  if marks == 0 then push(wrong, "no plant holds a mark") end
  if exists(SCRATCH) then remove_tree(SCRATCH) end
  mkdir(SCRATCH)
  local copies = {}
  for p in paths do
    local copy = SCRATCH .. "/" .. basename(p)
    replace(copy, read(p))
    push(copies, copy)
  end
  local roc = roc_bin("find_extra_parens", true)
  rewrite(copies, roc)
  local left = report(copies)
  for l in left.lines do push(wrong, "left after the rewrite: " .. l) end
  for r in left.refused do push(wrong, "the rewrite broke a file: " .. r) end
  for p in paths do
    local want = sub(p, 1, #p - 4) .. ".want"
    local copy = SCRATCH .. "/" .. basename(p)
    if exists(want) and read(copy) ~= read(want) then push(wrong, copy .. ": not as " .. want) end
  end
  if rewrite(copies, roc) ~= 0 then push(wrong, "a second rewrite changed something") end
  remove_tree(SCRATCH)
  for w in wrong do print("FAIL " .. w) end
  if #wrong > 0 then fail("find_extra_parens self_test: " .. #wrong .. " plants wrong") end
  print("find_extra_parens (Roc) self_test: PASS (each marked line gives its finding, no other line one; the rewrite leaves none, and a second changes nothing)")
end

const paths = glob(GLOB)
if WRITE then
  refuse_house_rewrite("find_extra_parens")
  print("find_extra_parens: " .. rewrite(paths, roc_bin("find_extra_parens", false)) .. " edits")
end
local found = report(paths)
print_findings(found.summary, found.lines)
fail_if_refused("find_extra_parens", found.refused)
if SELF_TEST then self_test(paths, found) end