check_and_fix_group_stacking

Roc

It also imports Bytes, Finding, Groups, Headers, Stacking, Text, Tree from the shared Roc library.

cookbook/roc/check_and_fix_group_stacking/check_and_fix_group_stacking.roc, 157 lines

## check_and_fix_group_stacking, in Roc on Shale's platform (roc_platform/README.md): the
## groups in .roc files laid out against the stacking rule and the lines
## past the width, found and, with `write=1`, laid out by the rule. Its
## launcher, cookbook/roc/check_and_fix_group_stacking.shale, is how it is run, and its
## header says the rule, the findings 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/check_and_fix_group_stacking.shale glob=chat/**/*.roc
##   cd <repo> && shale cookbook:roc/check_and_fix_group_stacking.shale glob=chat/**/*.roc write=1
##   shale cookbook:roc/check_and_fix_group_stacking.shale self_test=1
##
## The arguments: `glob` (`**/*.roc`), `skip` (files the glob finds to leave
## out, comma-separated), `width` (100), `tokens` (6), `dictated` (a table of
## functions whose arguments something outside the file dictates), `house`
## (`house=0` leaves out every finding, all of them house style), `write`
## (`write=1` rewrites the files) and `self_test` (`self_test=1` checks the
## plants and rewrites copies of them).
##
## This root reads the arguments, globs the files, rewrites them when asked
## (Rewrite) and prints the findings (Report, by Annotations) and the
## verdict; SelfTest is the self-test. Groups, Stacking, Headers, Finding
## and Text are the cookbook's Roc library, cookbook/roc/lib/.
## budget: steps=900000000 read_bytes=1000000000 arena_bytes=2000000000 output_bytes=4000000 programs=100 roc_cpu_ms=120000
app [main!] { lib: "../lib/main.roc", pf: platform "../../../roc_platform/platform/main.roc" }

import pf.Shale
import lib.Finding
import lib.Stacking
import Report
import Rewrite
import SelfTest

main! : {} => {}
main! = |{}| {
	self_test = Shale.arg!("self_test", "") == "1"
	pattern = if self_test {
		"${SelfTest.plants}/*.roc"
	} else {
		Shale.arg!("glob", "**/*.roc")
	}
	skip = Shale.arg!("skip", "")
	dictated = if self_test {
		"${SelfTest.plants}/dictated.txt"
	} else {
		Shale.arg!("dictated", "")
	}
	width = integer_of!("width", Shale.arg!("width", "100"))
	write = Shale.arg!("write", "") == "1"
	tokens = integer_of!("tokens", Shale.arg!("tokens", Stacking.stack_tokens.to_str()))
	settings = { rule: { tokens, width }, dictated }
	if self_test {
		SelfTest.run!(chosen_files!(pattern, skip), settings)
	} else if write {
		refuse_house_rewrite!({})
		# Stop before any change if the tree's Roc is missing.
		roc = Rewrite.roc_bin!(Bool.False)
		paths = chosen_files!(pattern, skip)
		_first = Rewrite.trailing_commas!(paths, { rule: settings.rule, roc })
		judged = Report.findings_in!(paths, settings)
		left = judged.found.map(Finding.line_of)
		print_findings!("${left.len().to_str()} left, each a line the rewrite can't reach", left)
		SelfTest.fail_if_refused!(judged.refused)
	} else {
		paths = chosen_files!(pattern, skip)
		judged = Report.findings_in!(paths, settings)
		house_is_off = read_house_is_off!({})
		kept = if house_is_off {
			[]
		} else {
			judged.found
		}
		count_of = |check| kept.count_if(|finding| finding.check == check).to_str()
		counts = "${count_of("stack")} to stack, ${count_of("unstack")} to unstack, ${count_of("long")} long, ${count_of("wide string")} wide string"
		note = if house_is_off {
			"; left out as house style: stack, unstack, long, wide string"
		} else {
			""
		}
		summary = "${kept.len().to_str()} findings in ${paths.len().to_str()} files: ${counts}${note}"
		print_findings!(summary, kept.map(Finding.line_of))
		SelfTest.fail_if_refused!(judged.refused)
	}
}

## The whole number an argument gives; another value stops the run, as
## Shale's `arg` does for an integer default. (Each `Shale.arg!` names its
## argument as a literal, so the launcher's check of the values finds it.)
integer_of! : Str, Str => U64
integer_of! = |name, given|
	match I64.from_str(given) {
		Ok(value) if value >= 0 => value.to_u64_wrap()
		Ok(_) => {
			Shale.fail!("check_and_fix_group_stacking: ${name}=${given} is below 0")
			0
		}
		Err(_) => {
			Shale.fail!("`arg`: ${name}=${given} is not an integer, and its default is one")
			0
		}
	}

## The files the glob finds, less the ones `skip` names. A name in `skip`
## that the glob doesn't find stops the run, so a renamed file can't go
## unchecked.
chosen_files! : Str, Str => List(Str)
chosen_files! = |pattern, skip| {
	found = Shale.glob!(pattern)
	if skip == "" {
		return found
	}
	skipped = skip.split_on(",")
	for name in skipped {
		if !(found.contains(name)) {
			Shale.fail!("check_and_fix_group_stacking: skip names ${name}, which the glob doesn't find")
		}
	}
	found.drop_if(|path| skipped.contains(path))
}

## Whether `house=0` leaves the house style out (cookbook/roc/house.shale):
## here that is every finding.
read_house_is_off! : {} => Bool
read_house_is_off! = |{}| {
	house = Shale.arg!("house", "1")
	number = match I64.from_str(house) {
		Ok(value) => value
		Err(_) => {
			Shale.fail!("`arg`: house=${house} is not an integer, and its default is one")
			1
		}
	}
	if number != 0 and number != 1 {
		Shale.fail!("house must be 1 (the default) or 0, not ${number.to_str()}")
	}
	number == 0
}

## A rewrite applies our house style, so `house=0` refuses one.
refuse_house_rewrite! : {} => {}
refuse_house_rewrite! = |{}| {
	if read_house_is_off!({}) {
		Shale.fail!("check_and_fix_group_stacking: 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)
	}
}

cookbook/roc/check_and_fix_group_stacking/Report.roc, 392 lines

## Every finding in a run's files, in the files' order and each file's line
## order, as the Shale original found them: a group on one line that should
## stack, a function type's bare arguments, a stacked group that should sit
## on one line, and a line wider than the width with nothing to stack, which
## is `wide string` when its strings' text is what makes it wide (by Roc's
## parser) and `long` otherwise. The names a file's header dictates, and
## those the `dictated` table names, are no finding for their arguments.
import pf.Shale
import lib.Bytes
import Annotations
import lib.Finding
import lib.Groups
import lib.Headers
import lib.Stacking
import lib.Text
import lib.Tree

Report := [].{

	## What a run judges by: the stacking rule, and the path of the
	## `dictated` table (`""` for none).
	Settings : { rule : Stacking.Rule, dictated : Str }

	## A run's findings, and why each file roc-ast refused was refused.
	Judged : { found : List(Finding), refused : List(Str) }

	## Every finding in the files.
	findings_in! : List(Str), Report.Settings => Report.Judged
	findings_in! = |paths, settings| {
		var $texts = Dict.empty()
		for path in paths {
			$texts = $texts.insert(path, Report.read_text!(path))
		}
		texts = $texts
		strings = string_columns_in!(paths, { texts, width: settings.rule.width })
		headed = dictated_names_in!(paths, texts)
		dictated = with_dictated_table!(headed.names, { paths, table: settings.dictated })
		var $found = []
		for path in paths {
			source_lines = (texts.get(path) ?? "").split_on("\n")
			file = {
				path,
				source_lines,
				string_columns: strings.columns.get(path) ?? Dict.empty(),
				dictated: dictated.get(path) ?? [],
				rule: settings.rule,
			}
			match file_findings(file) {
				Ok(found) => {
					$found = $found.concat(found)
				}
				Err(NoComma(line)) => Shale.fail!("groups: line ${line.to_str()} does not end in its group's trailing comma")
			}
		}
		var $refused = []
		for refusal in strings.refused.concat(headed.refused) {
			if !($refused.contains(refusal)) {
				$refused = $refused.append(refusal)
			}
		}
		{ found: $found, 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}"
		}

	## 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!("check_and_fix_group_stacking: no file ${path}")
				""
			}
		}
}

## A file to judge: its path, its lines, the columns its strings' text takes
## up by line number, the names whose arguments something else dictates, and
## the rule.
FileToJudge : {
	path : Str,
	source_lines : List(Str),
	string_columns : Dict(U64, U64),
	dictated : List(Str),
	rule : Stacking.Rule,
}

## What a file's scan knows so far: the function whose annotation ended on
## the line before and was a finding for its arguments (`""` for none),
## whose lambda's arguments are not reported again, and the last line of the
## annotation read last.
Annotated : { name : Str, end : U64 }

## The findings in one file, line by line, then the groups to unstack.
file_findings : FileToJudge -> Try(List(Finding), [NoComma(U64)])
file_findings = |file| {
	rule = file.rule
	reachable = Stacking.without_targets_section(file.source_lines)
	var $found = []
	var $annotated = { name: "", end: 0 }
	$number : U64
	var $number = 0
	for text in file.source_lines {
		$number = $number + 1
		number = $number
		on_line = line_findings(
			file,
			{
				number,
				text,
				reachable: reachable.get(number - 1) ?? "",
				annotated: $annotated,
			},
		)
		$annotated = on_line.annotated
		$found = $found.concat(on_line.found)
	}
	for unstacked in Stacking.groups_to_unstack(file.source_lines, rule)? {
		joined = Stacking.group_on_one_line(file.source_lines, unstacked.group) ?? ""
		$found = $found.append({
			path: file.path,
			line: unstacked.group.line,
			check: "unstack",
			what: "${unstacked.group.tokens.to_str()} tokens in ${Annotations.shortened(Text.trim(joined))}",
		})
	}
	Ok($found)
}

## A line to judge: its number, its text, its text with a `targets:` section
## blanked, and what the scan knew of the annotation before it.
LineToJudge : {
	number : U64,
	text : Str,
	reachable : Str,
	annotated : Annotated,
}

## The findings on one line, and what the scan knows after it.
line_findings : FileToJudge, LineToJudge -> { found : List(Finding), annotated : Annotated }
line_findings = |file, at| {
	rule = file.rule
	bytes = at.text.to_utf8()
	place = { path: file.path, line: at.number }
	before = at.annotated
	follows_annotation = before.name != "" and at.number == before.end + 1
	var $skip_lambda = follows_annotation and Text.trim(at.text).starts_with("${before.name} = |")
	var $annotated = if at.number > before.end {
		{ ..before, name: "" }
	} else {
		before
	}
	data_line = Stacking.is_data_line(at.reachable, rule.width)
	var $found = []
	for group in Groups.groups_on_line(at.reachable).sort_with(by_opening) {
		inner = Str.from_utf8_lossy(Bytes.span(bytes, group.open + 1, group.close - 1))
		whole = Str.from_utf8_lossy(Bytes.span(bytes, group.open, group.close))
		opening = Bytes.byte_at(bytes, group.open)
		if opening == '{' {
			for field in Annotations.record_field_functions(inner) {
				if field.items >= 3 and !(file.dictated.contains(field.name)) {
					arguments = {
						items: field.items,
						shown: Annotations.shortened(field.text),
						text: field.text,
					}
					$found = $found.append(Annotations.function_type_finding(place, arguments))
				}
			}
		}
		if group.items >= 3 and group.fn_type {
			text = Text.before_first(Text.before_first(inner, "->"), "=>")
			arguments = {
				items: group.items,
				shown: Annotations.shortened(whole),
				text,
			}
			$found = $found.append(Annotations.function_type_finding(place, arguments))
		} else if $skip_lambda and opening == '|' {
			$skip_lambda = Bool.False
		} else if !(data_line) {
			are_flags = group.items >= 3 and !(group.trailing) and Annotations.are_all_flags(inner)
			if are_flags or Stacking.should_stack({ line: at.text, group }, rule) {
				advice = if are_flags {
					Annotations.flag_advice
				} else {
					""
				}
				what = "${group.tokens.to_str()} tokens in ${Annotations.shortened(whole)}${advice}"
				$found = $found.append({
					path: file.path,
					line: at.number,
					check: "stack",
					what,
				})
			}
		}
	}
	# A line inside a wrapped annotation starts none.
	if at.number > $annotated.end {
		match Annotations.annotation_arguments(file.source_lines, at.number) {
			Ok(annotation) => {
				$annotated = { ..$annotated, end: annotation.last }
				if annotation.items >= 3 {
					$annotated = { ..$annotated, name: annotation.name }
					if !(file.dictated.contains(annotation.name)) {
						arguments = {
							items: annotation.items,
							shown: annotation.shown,
							text: annotation.text,
						}
						$found = $found.append(Annotations.function_type_finding(place, arguments))
					}
				}
			}
			Err(_) => {}
		}
	}
	if $found.is_empty() and Bytes.width_of(bytes) > rule.width {
		$found = $found.append(wide_line_finding(file, at))
	}
	{ found: $found, annotated: $annotated }
}

## The finding for a line wider than the width with nothing else found on it.
wide_line_finding : FileToJudge, LineToJudge -> Finding
wide_line_finding = |file, at| {
	rule = file.rule
	width = Bytes.line_width(at.text)
	strings = file.string_columns.get(at.number) ?? 0
	without_strings = width.to_i64_wrap() - strings.to_i64_wrap()
	if without_strings <= rule.width.to_i64_wrap() {
		what = "${width.to_str()} columns, ${without_strings.to_str()} without its strings"
		{
			path: file.path,
			line: at.number,
			check: "wide string",
			what,
		}
	} else {
		why = if Text.trim(at.text).starts_with("#") {
			"a comment"
		} else if Stacking.group_to_stack(at.reachable, rule).is_ok() {
			"a group to stack"
		} else {
			"nothing to stack"
		}
		{
			path: file.path,
			line: at.number,
			check: "long",
			what: "${width.to_str()} columns, ${why}",
		}
	}
}

## The columns that strings' text takes up in the files, by Roc's parser,
## by path and line number, and why each file roc-ast refused was refused.
## Only a file with a line wider than the width is parsed, so a tree of short
## lines never needs roc-ast.
string_columns_in! : List(Str),
{ texts : Dict(Str, Str), width : U64 } => {
	columns : Dict(Str, Dict(U64, U64)),
	refused : List(Str),
}
string_columns_in! = |paths, given| {
	wide_paths = paths.keep_if(
		|path| {
			text = given.texts.get(path) ?? ""
			Text.lines(text).any(|line| Bytes.line_width(line) > given.width)
		},
	)
	var $columns = Dict.empty()
	var $refused = []
	if !(wide_paths.is_empty()) {
		for file in Shale.roc_tree!(wide_paths) {
			if file.err == "" {
				source_lines = (given.texts.get(file.path) ?? "").split_on("\n")
				match Stacking.string_columns_on_lines(file.nodes, source_lines) {
					Ok(by_line) => {
						$columns = $columns.insert(file.path, by_line)
					}
					Err(CrossesLine(line)) => Shale.fail!("check_and_fix_group_stacking: ${file.path}: line ${line.to_str()}: a run of string text crosses a line")
				}
			} else {
				$refused = $refused.append(Report.refusal_of(file.path, file.err))
			}
		}
	}
	{ columns: $columns, refused: $refused }
}

## The names the headers of the files dictate, by path, and why each file
## roc-ast refused was refused. Only an app's or a platform's file is parsed,
## so a tree of modules needs no roc-ast for this.
dictated_names_in! : List(Str),
Dict(Str, Str) => {
	names : Dict(Str, List(Str)),
	refused : List(Str),
}
dictated_names_in! = |paths, texts| {
	headed = paths.keep_if(
		|path| {
			word = Headers.header_word(texts.get(path) ?? "")
			word == "app" or word == "platform"
		},
	)
	var $names = Dict.empty()
	var $refused = []
	if !(headed.is_empty()) {
		for file in Shale.roc_tree!(headed) {
			if file.err == "" {
				nodes : List(Tree.Node)
				nodes = file.nodes
				$names = $names.insert(file.path, Headers.header_names(nodes).dictated)
			} else {
				$refused = $refused.append(Report.refusal_of(file.path, file.err))
			}
		}
	}
	{ names: $names, refused: $refused }
}

## The names the `dictated` table adds. Each line of the table is a file's
## path, a function's name, and after ` -- ` who dictates its arguments. The
## path names the file the glob finds with that path or ending `/` and that
## path, so the self-test's copies in scratch are found too. A line whose
## file the glob doesn't find, whose function has no annotation there, or
## that gives no reason stops the run, so the table can't go stale.
with_dictated_table! : Dict(Str, List(Str)),
{
	paths : List(Str),
	table : Str,
} => Dict(Str, List(Str))
with_dictated_table! = |names, given| {
	if given.table == "" {
		return names
	}
	var $names = names
	for line in Text.lines(Report.read_text!(given.table)) {
		trimmed = Text.trim(line)
		if trimmed != "" and !(trimmed.starts_with("#")) {
			groups = match Shale.re_find!(line, "^(\\S+) ([a-z_][A-Za-z0-9_]*!?) -- \\S") {
				Found(found) => found.groups
				NoMatch => []
			}
			(wanted_path, name) = match groups {
				[path_given, name_given, ..] => (path_given, name_given)
				_ => {
					Shale.fail!("check_and_fix_group_stacking: ${given.table} has a line that is not `path name -- reason`: ${line}")
					("", "")
				}
			}
			is_named = |path| path == wanted_path or path.ends_with("/${wanted_path}")
			found = given.paths.keep_if(is_named).last()
			match found {
				Err(_) => Shale.fail!("check_and_fix_group_stacking: ${given.table} names ${wanted_path}, which the glob doesn't find")
				Ok(path) => {
					opening = "${name} :"
					path_lines = Text.lines(Report.read_text!(path))
					annotated = path_lines.any(|text| Text.trim(text).starts_with(opening))
					if !(annotated) {
						Shale.fail!("check_and_fix_group_stacking: ${given.table} names ${name}, which has no annotation in ${path}")
					}
					here = $names.get(path) ?? []
					$names = $names.insert(path, here.append(name))
				}
			}
		}
	}
	$names
}

## Two groups of a line in the order of their opening brackets.
by_opening : Groups.Group, Groups.Group -> [Before, Same, After]
by_opening = |first, second|
	if first.open < second.open {
		Before
	} else if first.open > second.open {
		After
	} else {
		Same
	}

cookbook/roc/check_and_fix_group_stacking/Rewrite.roc, 162 lines

## `write=1`: the files rewritten pass after pass until a pass changes
## nothing. A pass takes the trailing comma from each group that should
## unstack and gives one to each line's group that should stack, and `roc
## fmt` lays out the result: it stacks a group with a trailing comma and
## joins a group without one. The Roc is the tree's own
## (cookbook/roc/pinned.shale), run by its OS path.
import pf.Shale
import Report
import lib.Stacking
import lib.Text

Rewrite := [].{

	## Rewrites the files until a pass changes nothing, printing each pass,
	## and answers how many groups the first pass changed. Twelve passes
	## that still change something stop the run.
	trailing_commas! : List(Str), { rule : Stacking.Rule, roc : Str } => U64
	trailing_commas! = |paths, given| {
		$first_pass_count : U64
		var $first_pass_count = 0
		$pass : U64
		var $pass = 1
		$changed : U64
		var $changed = 1
		var $touched = []
		while $changed > 0 and $pass <= max_passes {
			$changed = 0
			$touched = []
			for path in paths {
				n = rewrite_file!(path, given.rule)
				if n > 0 {
					$touched = $touched.append(path)
					$changed = $changed + n
				}
			}
			Shale.print!("pass ${$pass.to_str()}: ${$changed.to_str()} groups rewritten, in ${$touched.len().to_str()} files")
			if $pass == 1 {
				$first_pass_count = $changed
			}
			if !($touched.is_empty()) {
				result = Rewrite.format!($touched, given.roc)
				if result.code != 0 {
					Shale.print!(result.out)
					Shale.fail!("roc fmt failed")
				}
			}
			$pass = $pass + 1
		}
		if $changed > 0 {
			Shale.fail!(
				"check_and_fix_group_stacking: still changing after ${max_passes.to_str()} passes: ${Str.join_with($touched, ", ")}",
			)
		}
		$first_pass_count
	}

	## `roc fmt` run on the files; its code is not 0 when a file does not
	## parse.
	format! : List(Str), Str => { code : I64, out : Str }
	format! = |paths, roc| {
		var $argv = [roc, "fmt"]
		for path in paths {
			$argv = $argv.append(Shale.real!(path))
		}
		Shale.run!({
			argv: $argv,
			keep: Tail(20),
			timeout_ms: 120000,
			want: "",
		})
	}

	## 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!("check_and_fix_group_stacking: 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!("check_and_fix_group_stacking: 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!("check_and_fix_group_stacking: ${roc} says ${Text.trim(said.out)}, not Roc compiler version ${pin}")
		}
		real
	}
}

## The most passes a rewrite makes.
max_passes : U64
max_passes = 12

## One pass over one file: the groups that should unstack lose their trailing
## commas, then each line's group that should stack gets one; the file is
## written when any changed, and the answer is how many did.
rewrite_file! : Str, Stacking.Rule => U64
rewrite_file! = |path, rule| {
	source_lines = Report.read_text!(path).split_on("\n")
	unstacked = match Stacking.groups_to_unstack(source_lines, rule) {
		Ok(found) => found
		Err(NoComma(line)) => {
			Shale.fail!("groups: line ${line.to_str()} does not end in its group's trailing comma")
			[]
		}
	}
	unstacked_lines = Stacking.without_trailing_commas(source_lines, unstacked)
	reachable = Stacking.without_targets_section(unstacked_lines)
	var $lines = unstacked_lines
	$n : U64
	var $n = unstacked.len()
	$index : U64
	var $index = 0
	for text in unstacked_lines {
		if !(Text.trim(text).starts_with("#")) {
			match Stacking.group_to_stack(reachable.get($index) ?? "", rule) {
				Ok(group) => {
					$lines = $lines.set(
						$index,
						Stacking.with_trailing_comma({ line: text, group }),
					) ?? crash "check_and_fix_group_stacking: a line past the file's end"
					$n = $n + 1
				}
				Err(_) => {}
			}
		}
		$index = $index + 1
	}
	if $n > 0 {
		Shale.write!(path, Str.join_with($lines, "\n"))
	}
	$n
}

## 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"
	groups = match Shale.re_find!(
		Report.read_text!(pinned),
		"\nconst SELF_TEST_PIN = \"([^\"]+)\"",
	) {
		Found(found) => found.groups
		NoMatch => []
	}
	match groups {
		[pin, ..] => pin
		[] => {
			Shale.fail!("check_and_fix_group_stacking: no SELF_TEST_PIN in ${pinned}")
			""
		}
	}
}

cookbook/roc/check_and_fix_group_stacking/SelfTest.roc, 193 lines

## The recipe's self-test, the Shale original's: each plant in
## cookbook/roc/plants/check_and_fix_group_stacking/ must give a finding of the kind its
## name starts with (`long`, `wide`, `unstack`, or else `stack`), a `long`
## plant no `wide string` and a `wide` plant no `long`, and a `clean*.roc`
## plant none. A plant line ending `# findings N` must give exactly N
## findings, and with `advice W` after it each of them must contain the word
## W. Then the plants are copied to `scratch:stack/` and rewritten there with
## the self-tests' Roc: the rewrite must end, a second rewrite must change
## nothing, every file must still parse, and a plant with a `.want` file must
## come out as it.
import pf.Shale
import Report
import Rewrite
import lib.Text

SelfTest := [].{

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

	## The self-test of the plants, judged by `settings`.
	run! : List(Str), Report.Settings => {}
	run! = |paths, settings| {
		judged = Report.findings_in!(paths, settings)
		fail_if_refused!(judged.refused)
		marks_wrong = check_marks!(paths, judged)
		kinds_wrong = check_kinds!(paths, judged)
		wrong = marks_wrong + kinds_wrong
		if wrong > 0 {
			Shale.fail!("${wrong.to_str()} plants wrong")
		}
		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 = Rewrite.roc_bin!(Bool.True)
		given = { rule: settings.rule, roc }
		_first = Rewrite.trailing_commas!(copies, given)
		again = Rewrite.trailing_commas!(copies, given)
		if again > 0 {
			Shale.fail!("check_and_fix_group_stacking: a second rewrite changed ${again.to_str()} more groups")
		}
		formatted = Rewrite.format!(copies, roc)
		if formatted.code != 0 {
			Shale.print!(formatted.out)
			Shale.fail!("check_and_fix_group_stacking: a rewritten plant no longer parses")
		}
		$came_out_wrong : U64
		var $came_out_wrong = 0.U64
		for want in Shale.glob!("${plants}/*.want") {
			name = Text.basename(want).drop_suffix(".want")
			ok = Report.read_text!("${scratch}/${name}.roc") == Report.read_text!(want)
			Shale.print!("${verdict(ok)}${name}.roc: comes out as its .want")
			if !(ok) {
				$came_out_wrong = $came_out_wrong + 1
			}
		}
		if $came_out_wrong > 0 {
			Shale.fail!("${$came_out_wrong.to_str()} plants came out wrong")
		}
		Shale.print!("PASS: every plant gives its finding, the clean ones none; the rewrite ends, a second changes nothing, every plant parses and comes out as its .want")
	}

	## 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!("check_and_fix_group_stacking: ${refusals}, ${why}")
		}
	}
}

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

## A plant's name, its path after the plants' folder.
name_of : Str -> Str
name_of = |path| path.drop_prefix("${SelfTest.plants}/")

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

## The start of a verdict's line.
verdict : Bool -> Str
verdict = |ok|
	if ok {
		"ok   "
	} else {
		"FAIL "
	}

## Each line marked `# findings N` (with `advice W`) held to the findings on
## it, a line printed for each: the answer is how many were wrong.
check_marks! : List(Str), Report.Judged => U64
check_marks! = |paths, judged| {
	$bad : U64
	var $bad = 0
	for path in paths {
		$number : U64
		var $number = 0
		for line in Text.lines(Report.read_text!(path)) {
			$number = $number + 1
			number = $number
			match Shale.re_find!(line, "# findings ([0-9]+)(?: advice ([a-z]+))?$") {
				Found(mark) => {
					(count_text, word) = match mark.groups {
						[count_given, word_given, ..] => (count_given, word_given)
						[count_given] => (count_given, "")
						[] => ("", "")
					}
					is_here = |finding| finding.path == path and finding.line == number
					here = judged.found.keep_if(is_here)
					got = here.len()
					var $ok = Ok(got.to_i64_wrap()) == I64.from_str(count_text)
					if word != "" {
						for finding in here {
							if !(finding.what.contains(word)) {
								$ok = Bool.False
							}
						}
					}
					place = "${name_of(path)}:${number.to_str()}"
					Shale.print!("${verdict($ok)}${place}: ${got.to_str()} findings, want ${count_text}")
					if !($ok) {
						$bad = $bad + 1
					}
				}
				NoMatch => {}
			}
		}
	}
	$bad
}

## Each plant held to the kinds of its findings by its name, a line printed
## for each: the answer is how many were wrong.
check_kinds! : List(Str), Report.Judged => U64
check_kinds! = |paths, judged| {
	$bad : U64
	var $bad = 0
	for path in paths {
		name = name_of(path)
		kinds = judged.found.keep_if(|finding| finding.path == path).map(|finding| finding.check)
		got = if kinds.is_empty() {
			""
		} else {
			" ${Str.join_with(kinds, " ")} "
		}
		is_long = name.starts_with("long")
		is_wide = name.starts_with("wide")
		want = if is_long {
			"long"
		} else if is_wide {
			"wide string"
		} else if name.starts_with("unstack") {
			"unstack"
		} else {
			"stack"
		}
		clean = name.starts_with("clean")
		var $ok = (clean and got == "") or (!(clean) and got.contains(" ${want} "))
		if is_long and got.contains("wide string") {
			$ok = Bool.False
		}
		if is_wide and got.contains("long") {
			$ok = Bool.False
		}
		shown = if got == "" {
			"no finding"
		} else {
			got
		}
		Shale.print!("${verdict($ok)}${name}: ${shown}")
		if !($ok) {
			$bad = $bad + 1
		}
	}
	$bad
}

cookbook/roc/check_and_fix_group_stacking/Annotations.roc, 304 lines

## A function type's bare arguments, which no trailing comma can stack, read
## as the Shale original read them: an annotation (`name : A, B, C -> R`) or a
## type alias of a function (`Pick(a) : a, a, a -> a`) to its first arrow,
## over the lines `roc fmt` wraps it onto, and a record type's field whose
## type is a function (`{ on_pick : U8, U8, U8 -> U8 }`). The finding says
## what to do instead: a record for values that travel together, or a tag
## for a run of flags.
import lib.Bytes
import lib.Finding
import lib.Groups
import lib.Text

Annotations := [].{

	## An annotation's arguments: how many, its type's text up to the arrow
	## and that text shortened, the annotated name, and the annotation's last
	## line read.
	Annotation : {
		items : U64,
		shown : Str,
		text : Str,
		name : Str,
		last : U64,
	}

	## A record type's field whose type is a function: its name, how many
	## arguments, and the type's text up to the arrow.
	FieldFunction : {
		name : Str,
		items : U64,
		text : Str,
	}

	## Text cut to 60 bytes for a finding line, its end `...`.
	shortened : Str -> Str
	shortened = |text| {
		bytes = text.to_utf8()
		if bytes.len() > 60 {
			Str.from_utf8_lossy(bytes.take_first(57).concat(['.', '.', '.']))
		} else {
			text
		}
	}

	## The annotation line `number` of the lines starts, when it annotates a
	## function: its arguments before the first arrow outside any bracket,
	## counted by the commas outside any bracket. It goes on to the next line
	## while its text so far is empty, a bracket is open or its text ends in a
	## comma, passing over a comment on a line of its own; a blank line, or a
	## next line that starts another annotation, ends it.
	annotation_arguments : List(Str), U64 -> Try(Annotations.Annotation, [NoFunction])
	annotation_arguments = |source_lines, number| {
		first_line = Bytes.line_of(source_lines, number)
		var $piece = match start_text(type_line(first_line)) {
			Ok(piece) => piece
			Err(NoStart) => return Err(NoFunction)
		}
		name = Bytes.trimmed(before_colon(Bytes.trimmed(first_line)))
		var $type_text = []
		$depth : I64
		var $depth = 0
		$commas : U64
		var $commas = 0
		var $n = number
		while $n <= source_lines.len() {
			start = $type_text.len()
			$type_text = if start == 0 or $piece.is_empty() {
				$type_text.concat($piece)
			} else {
				$type_text.append(' ').concat($piece)
			}
			var $at = start + 1
			while $at <= $type_text.len() {
				c = Bytes.byte_at($type_text, $at)
				if Groups.closer_of(c) != 0 {
					$depth = $depth + 1
				}
				if Groups.is_closer(c) {
					$depth = $depth - 1
				}
				if $depth < 0 {
					return Err(NoFunction)
				}
				if $depth == 0 and c == ',' {
					$commas = $commas + 1
				}
				if $depth == 0 and is_arrow_at($type_text, $at) {
					text = Str.from_utf8_lossy(Bytes.trimmed(Bytes.span($type_text, 1, $at - 1)))
					return Ok({
						items: $commas + 1,
						shown: Annotations.shortened(text),
						text,
						name: Str.from_utf8_lossy(name),
						last: $n,
					})
				}
				$at = $at + 1
			}
			goes_on = $type_text.is_empty() or $depth > 0 or $type_text.last() == Ok(',')
			if !(goes_on) {
				return Err(NoFunction)
			}
			# The next line of code, past any comment on a line of its own.
			$n = $n + 1
			while $n <= source_lines.len() and !(
				Bytes.trimmed(
					Bytes.line_of(source_lines, $n),
				).is_empty()
			) and type_line(Bytes.line_of(source_lines, $n)).is_empty() {
				$n = $n + 1
			}
			if $n > source_lines.len() or Bytes.trimmed(
				Bytes.line_of(source_lines, $n),
			).is_empty() {
				return Err(NoFunction)
			}
			next_line = type_line(Bytes.line_of(source_lines, $n))
			if $depth == 0 and start_text(next_line) != Err(NoStart) {
				return Err(NoFunction)
			}
			$piece = next_line
		}
		Err(NoFunction)
	}

	## The function types among the fields of a record type whose inside,
	## between its braces, is `inner`: a field whose type has an arrow outside
	## any bracket, its arguments counted by the commas before it. A comma
	## starts the next field only when `name : ` follows it, so the commas of a
	## field's function type stay its own.
	record_field_functions : Str -> List(Annotations.FieldFunction)
	record_field_functions = |text| {
		inner = text.to_utf8()
		if !(starts_field(inner)) {
			return []
		}
		var $out = []
		$depth : I64
		var $depth = 0
		$commas : U64
		var $commas = 0
		var $type_start = 0
		var $field_start = 1
		var $name = []
		var $done = Bool.False
		var $at = 1
		while $at <= inner.len() {
			c = Bytes.byte_at(inner, $at)
			if Groups.closer_of(c) != 0 {
				$depth = $depth + 1
			}
			if Groups.is_closer(c) {
				$depth = $depth - 1
			}
			if $depth == 0 {
				if $type_start == 0 and Bytes.span(inner, $at, $at + 2) == [' ', ':', ' '] {
					$type_start = $at + 3
					$name = Bytes.trimmed(Bytes.span(inner, $field_start, $at - 1))
					$at = $at + 2
				} else if c == ',' and starts_field(Bytes.rest_from(inner, $at + 1)) {
					$commas = 0
					$type_start = 0
					$field_start = $at + 1
					$done = Bool.False
				} else if c == ',' {
					$commas = $commas + 1
				} else if !($done) and $type_start > 0 and Bytes.byte_at(
					inner,
					$at - 1,
				) == ' ' and is_arrow_at(inner, $at) {
					type_text = Bytes.trimmed(Bytes.span(inner, $type_start, $at - 1))
					$out = $out.append({
						name: Str.from_utf8_lossy($name),
						items: $commas + 1,
						text: Str.from_utf8_lossy(type_text),
					})
					$done = Bool.True
				}
			}
			$at = $at + 1
		}
		$out
	}

	## Whether every comma-separated item of a text is `Bool` or a Bool
	## literal, like `Bool, Bool, Bool` or `Bool.true, Bool.false, Bool.true`.
	are_all_flags : Str -> Bool
	are_all_flags = |text|
		text.split_on(",").all(
			|item| {
				flag = Text.trim(item)
				flag == "Bool" or flag == "Bool.true" or flag == "Bool.false" or flag == "Bool.True" or flag == "Bool.False"
			},
		)

	## What a flag's finding adds.
	flag_advice : Str
	flag_advice = ": a flag a caller passes is a tag, not a Bool (roc-apps docs/roc-style.md)"

	## The finding for a function type's bare arguments at a file's line.
	function_type_finding : { path : Str, line : U64 },
	{
		items : U64,
		shown : Str,
		text : Str,
	} -> Finding
	function_type_finding = |place, arguments| {
		advice = if Annotations.are_all_flags(arguments.text) {
			Annotations.flag_advice
		} else {
			": take a record (roc-apps docs/roc-style.md, Name what travels together)"
		}
		{
			path: place.path,
			line: place.line,
			check: "stack",
			what: "${arguments.items.to_str()} bare arguments in ${arguments.shown}, which no comma stacks${advice}",
		}
	}
}

## A line without a `#` comment, trimmed. A type has no string, so the first
## `#` starts the comment.
type_line : List(U8) -> List(U8)
type_line = |bytes|
	match bytes.find_first_index(|byte| byte == '#') {
		Ok(at) => Bytes.trimmed(bytes.take_first(at))
		Err(_) => Bytes.trimmed(bytes)
	}

## The text of a trimmed line before its first ` :`, or all of it.
before_colon : List(U8) -> List(U8)
before_colon = |bytes| {
	var $at = 1
	while $at < bytes.len() {
		if Bytes.byte_at(bytes, $at) == ' ' and Bytes.byte_at(bytes, $at + 1) == ':' {
			return Bytes.span(bytes, 1, $at - 1)
		}
		$at = $at + 1
	}
	bytes
}

## Whether `->` or `=>` stands at `place`.
is_arrow_at : List(U8), U64 -> Bool
is_arrow_at = |bytes, place| {
	byte = Bytes.byte_at(bytes, place)
	(byte == '-' or byte == '=') and Bytes.byte_at(bytes, place + 1) == '>'
}

## The type text after the start of a function's annotation (`name :`) or of
## a type alias (`Handler :`, `Pick(a) :`) on a comment-free line, which is
## empty when the type starts on the next line:
## `^[a-z_][A-Za-z0-9_]*!? :(?: (.*))?$` or
## `^[A-Z][A-Za-z0-9_]*(?:\([^()]*\))? :(?: (.*))?$`.
start_text : List(U8) -> Try(List(U8), [NoStart])
start_text = |bytes| {
	first = Bytes.byte_at(bytes, 1)
	name_end =
		if (first >= 'a' and first <= 'z') or first == '_' {
			end = Bytes.word_end(bytes, 2)
			if Bytes.byte_at(bytes, end) == '!' {
				end + 1
			} else {
				end
			}
		} else if first >= 'A' and first <= 'Z' {
			end = Bytes.word_end(bytes, 2)
			if Bytes.byte_at(bytes, end) == '(' {
				match bytes.drop_first(end).find_first_index(|byte| byte == '(' or byte == ')') {
					Ok(offset) if Bytes.byte_at(bytes, end + offset + 1) == ')' => end + offset + 2
					_ => end
				}
			} else {
				end
			}
		} else {
			return Err(NoStart)
		}
	rest = Bytes.rest_from(bytes, name_end)
	if rest == [' ', ':'] {
		Ok([])
	} else if rest.starts_with([' ', ':', ' ']) {
		Ok(rest.drop_first(3))
	} else {
		Err(NoStart)
	}
}

## Whether the bytes start a record type's field: `^ *[a-z_][A-Za-z0-9_]* : `.
starts_field : List(U8) -> Bool
starts_field = |bytes| {
	var $at = 1
	while Bytes.byte_at(bytes, $at) == ' ' {
		$at = $at + 1
	}
	first = Bytes.byte_at(bytes, $at)
	if (first >= 'a' and first <= 'z') or first == '_' {
		end = Bytes.word_end(bytes, $at + 1)
		Bytes.span(bytes, end, end + 2) == [' ', ':', ' ']
	} else {
		Bool.False
	}
}

Shale original

cookbook/roc/check_stacking.shale, 610 lines, at 9901eae2

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

-- This recipe finds groups in .roc files laid out against the stacking rule,
-- and with `write=1` lays them out by it. A group is a list, record, tuple,
-- call's arguments, tag payload or lambda's arguments. A group of three or
-- more items and six or more tokens stacks, one item a line. Any other group
-- sits on one line while that line fits `width`. The rule and what counts as
-- a token are in cookbook/roc/groups.shale.
--
--   cd <repo> && shale <shale>/cookbook/roc/check_stacking.shale glob=chat/**/*.roc
--   cd <repo> && shale <shale>/cookbook/roc/check_stacking.shale glob=chat/**/*.roc write=1
--   shale cookbook:roc/check_stacking.shale self_test=1
--
-- The arguments:
--   glob   the files to check, `**/*.roc` by default;
--   skip   files the glob finds to leave out, by path, comma-separated, for
--          tables of data that read better side by side;
--   width  the widest a line may be, 100 by default, a tab counting four;
--   tokens the tokens from which a group stacks, 6 by default;
--   dictated a table of functions whose arguments something outside the file
--          dictates, one `path name -- reason` a line, judged as a header's
--          names are (below);
--   house  with `house=0`, leave out every finding here, as the stacking rule
--          is our house style (cookbook/roc/house.shale);
--   write  with `write=1`, rewrite the files (see below).
--
-- A group on one line that should stack is a finding, `path:line: stack: ...`,
-- left to right. A stacked group that should sit on one line is a finding,
-- `path:line: unstack: ...`, at the line it opens on. A line wider than `width`
-- with nothing to stack by the rule is a finding too, of one of two kinds. It
-- is `wide string` when
-- it would fit `width` if the text of each string literal on it counted as
-- empty, because Roc has no short way to split a string. Otherwise it is
-- `long`. Roc's own parser says which columns are a string's text, so the
-- code in an interpolation (`"${...}"`) counts, a comment counts, and so does
-- a string in an `import` or the file's header, which has no such node. The
-- output is the counts, the findings, and the counts again
-- (cookbook/findings.shale). A file with a line wider than `width` that
-- roc-ast refuses keeps that line as `long`, and the run fails, naming it, as
-- it does for an app's or platform's file that roc-ast refuses.
--
-- A stacked group stays stacked, with no finding, when its joined line would
-- be wider than `width`, or when it holds a comment, a `\\` string, a blank
-- line, a block's statements, or a group that stays stacked.
--
-- Some groups are not findings, or get special advice:
--   - A list or tuple whose items are all literals (numbers, plain strings,
--     characters, bare tags) is a table's row, like `[0, 0, 0]` or
--     `(0.0, 0.0, 1.5)`, and is read at a glance. It is no finding while
--     its line fits `width`. A call's arguments are never a row.
--   - A group of three or more `Bool`s or Bool literals is told that a flag
--     a caller passes should be a tag, as roc-style.md says, whatever its
--     tokens.
--   - A function's annotation (`name : A, B, C -> R`), or a type alias of a
--     function (`Pick(a) : a, a, a -> a`), is read to its first arrow, over
--     the lines `roc fmt` wraps it onto, from a type that starts on the line
--     after the colon, past a comment on a line of its own, to a blank line.
--     When it is a finding for its arguments, at its first line, the
--     function's lambda arguments on the line after it are not reported
--     again.
--   - A field of a record type on one line whose type is a function
--     (`{ on_pick : U8, U8, U8 -> U8 }`) is read the same way, its arguments
--     counted up to its arrow, unless its file's header dictates it (a
--     platform's `requires { step : U8, U8, U8 -> U8 }`).
--   - The annotation of a name its file's header dictates is no finding for
--     its arguments, as the platform chose them: what an app's header
--     provides, and what a platform's header requires and provides
--     (cookbook/roc/headers.shale). Nor are that name's lambda arguments.
--   - The items of a `where` clause are its method constraints, so
--     `k.is_eq : k, k -> Bool` is one item, and a record or list pattern's
--     rest (`..`) is no item.
--   - The groups of a platform header's `targets:` section are no findings, and
--     the rewrite leaves them alone, as `roc fmt` lays that section out by
--     itself. A line there wider than `width` is still `long`.
-- Strings, characters, `\\` multiline strings and `#` comments are skipped,
-- so a comma or bracket inside one is no item.
--
-- With `write=1`, the recipe gives each group that should stack a trailing
-- comma after its last item, outermost first, takes the trailing comma from
-- each group that should unstack, and runs `roc fmt` on the files it changed,
-- which stacks a group with a trailing comma and joins a group without one. On
-- a long line with no group to stack by the rule, the widest group of two or
-- more items gets the comma, as wrap_long_lines.shale does. This repeats until a
-- pass changes nothing, so a second run changes nothing either. The recipe then
-- prints the findings left, which the rewrite can't reach: long lines, and
-- the arguments of a function type, bare (`three : U8, U8, U8 -> U8`) or in
-- parentheses (`(U8, U8, U8 -> U8)`), because Roc refuses a trailing comma
-- there.
--
-- `roc fmt`'s layout changes between Roc nightlies, so `write=1` runs the
-- Roc the tree is built with: `tools:roc-<pin>/roc`, the pin read from the
-- `roc-version` file in the directory the run starts in, normally the
-- repository's root. Without that file it stops before changing anything
-- (cookbook/roc/pinned.shale).
--
-- `self_test=1` checks the plants in `cookbook/roc/plants/check_stacking/`. Each
-- plant must give a finding of the kind its name starts with (`long`,
-- `wide`, `unstack`, or else `stack`), a `long` plant no `wide string` and a
-- `wide` plant no `long`, and a `clean*.roc` plant none. A plant line ending
-- `# findings N` must give exactly N findings, and with `advice W` after
-- it each of them must contain the word W. Then the test copies the plants
-- to `scratch:stack/` and rewrites them there with the self-test's Roc:
-- the rewrite must end, a second rewrite must change nothing, every file must
-- still parse, and a plant with a `.want` file must come out as it.
--
-- budget: steps=900000000 arena_bytes=2000000000 output_bytes=4000000

const SELF_TEST = arg("self_test", "") == "1"
const PLANTS = "cookbook:roc/plants/check_stacking"
const SCRATCH = "scratch:stack"
const GLOB = SELF_TEST and (PLANTS .. "/*.roc") or arg("glob", "**/*.roc")
const SKIP = arg("skip", "")
const DICTATED = SELF_TEST and (PLANTS .. "/dictated.txt") or arg("dictated", "")
const WIDTH = arg("width", 100)
const WRITE = arg("write", "") == "1"

-- The files the glob finds, less the ones `skip` names. A name in `skip` that
-- the glob doesn't find stops the run, so a renamed file can't go unchecked.
function chosen_files()
  local found = glob(GLOB)
  if SKIP == "" then return found end
  local skipped = {}
  for name in split(SKIP, ",") do skipped[name] = false end
  local kept = {}
  for f in found do
    if has_key(skipped, f) then skipped[f] = true else push(kept, f) end
  end
  for name in keys(skipped) do
    if not skipped[name] then fail("check_stacking: skip names " .. name .. ", which the glob doesn't find") end
  end
  return kept
end
use("./pinned.shale")
use("cookbook:findings.shale")
use("./groups.shale")
use("./parsed.shale")
use("./headers.shale")
use("./house.shale")
const TOKENS = arg("tokens", STACK_TOKENS)
const MAX_PASSES = 12

-- Text cut to 60 characters for a finding line.
function shortened(s)
  if #s > 60 then return sub(s, 1, 57) .. "..." end
  return s
end

-- The start of a function's annotation (`name :`) or of a type alias
-- (`Handler :`, `Pick(a) :`), the type's text after it, which may be empty
-- when the type starts on the next line.
const ANNOTATION_START = "^[a-z_][A-Za-z0-9_]*!? :(?: (.*))?$"
const ALIAS_START = "^[A-Z][A-Za-z0-9_]*(?:\\([^()]*\\))? :(?: (.*))?$"

-- The start of an annotation or alias on the line `l`, read with type_line,
-- or nil.
function annotation_start(l)
  local m = re_find(l, ANNOTATION_START)
  if m ~= nil then return m end
  return re_find(l, ALIAS_START)
end

-- The type text an annotation's start gives on its own line.
function start_text(m)
  local text = get(m.groups, 1, "")
  if text == nil then return "" end
  return text
end

-- Line `l` without a `#` comment, trimmed. A type has no string, so the
-- first `#` starts the comment.
function type_line(l)
  local at = find(l, "#")
  if at == nil then return trim(l) end
  return trim(sub(l, 1, at - 1))
end

-- If line `i` of `ls` starts a function's annotation (`name : A, B, C -> R`),
-- its arguments before the first arrow, counted by the commas outside any
-- brackets: `{items, shown, text, name, last}`, where `shown` is `text`
-- shortened and `last` the annotation's last line read. A type alias of a
-- function (`Handler : U8, U8, U8 -> U8`) counts the same way. `roc fmt` wraps
-- a long signature, so the annotation goes on to the next line while its text
-- so far is empty (the type starts after the colon's line), a bracket is open
-- or its text ends in a comma outside any bracket, until the first arrow
-- outside any bracket. A comment on a line of its own is passed over; a blank
-- line, or a next line that starts another annotation or field, ends it. nil
-- when line `i` annotates no function.
function annotation_arguments(ls, i)
  local m = annotation_start(type_line(ls[i]))
  if m == nil then return nil end
  local name = trim(split(trim(ls[i]), " :")[1])
  local type_text = ""
  local depth = 0
  local commas = 0
  local n = i
  local piece = start_text(m)
  while true do
    local start = #type_text
    type_text = type_text .. ((start == 0 or piece == "") and "" or " ") .. piece
    for at = start + 1, #type_text do
      local c = sub(type_text, at, at)
      if has_key(OPENERS, c) then depth = depth + 1 end
      if has_key(CLOSERS, c) then depth = depth - 1 end
      if depth < 0 then return nil end
      if depth == 0 and c == "," then commas = commas + 1 end
      if depth == 0 and (sub(type_text, at, at + 1) == "->" or sub(type_text, at, at + 1) == "=>") then
        local text = trim(sub(type_text, 1, at - 1))
        return {items = commas + 1, shown = shortened(text), text = text, name = name, last = n}
      end
    end
    local goes_on = type_text == "" or depth > 0 or ends_with(type_text, ",")
    if not goes_on then return nil end
    -- The next line of code, past any comment on a line of its own.
    n = n + 1
    while n <= #ls and trim(ls[n]) ~= "" and type_line(ls[n]) == "" do n = n + 1 end
    if n > #ls or trim(ls[n]) == "" then return nil end
    local next_line = type_line(ls[n])
    if depth == 0 and annotation_start(next_line) ~= nil then return nil end
    piece = next_line
  end
end

-- Whether every comma-separated item of `text` is `Bool` or a Bool
-- literal, like `Bool, Bool, Bool` or `Bool.true, Bool.false, Bool.true`.
const FLAGS = {Bool = true, ["Bool.true"] = true, ["Bool.false"] = true, ["Bool.True"] = true, ["Bool.False"] = true}
function are_all_flags(text)
  for item in split(text, ",") do
    if not has_key(FLAGS, trim(item)) then return false end
  end
  return true
end

const FLAG_ADVICE = ": a flag a caller passes is a tag, not a Bool (roc-apps docs/roc-style.md)"

-- The finding for a function type's arguments, which can't take a
-- trailing comma. The advice is a record for values that travel together,
-- or a tag for a run of flags.
function function_type_finding(path, line, items, shown, text)
  local advice = are_all_flags(text) and FLAG_ADVICE or ": take a record (roc-apps docs/roc-style.md, Name what travels together)"
  return {path = path, line = line, kind = "stack", what = items .. " bare arguments in " .. shown .. ", which no comma stacks" .. advice}
end

-- The start of a record type's field, `name : `.
const FIELD_START = "^ *[a-z_][A-Za-z0-9_]* : "

-- The function types among the fields of a record type whose inside, between
-- its braces, is `inner`, each `{name, items, text}`: a field whose type has an
-- arrow outside any bracket, its arguments counted by the commas before it. A
-- comma starts the next field only when `name : ` follows it, so the commas
-- of a field's function type stay its own.
function record_field_functions(inner)
  local out = {}
  if re_find(inner, FIELD_START) == nil then return out end
  local depth = 0
  local commas = 0
  local type_start = 0
  local field_start = 1
  local name = ""
  local done = false
  local at = 1
  while at <= #inner do
    local c = sub(inner, at, at)
    if has_key(OPENERS, c) then depth = depth + 1 end
    if has_key(CLOSERS, c) then depth = depth - 1 end
    if depth == 0 then
      if type_start == 0 and sub(inner, at, at + 2) == " : " then
        type_start = at + 3
        name = trim(sub(inner, field_start, at - 1))
        at = at + 2
      elseif c == "," and re_find(sub(inner, at + 1), FIELD_START) ~= nil then
        commas = 0
        type_start = 0
        field_start = at + 1
        done = false
      elseif c == "," then
        commas = commas + 1
      elseif not done and type_start > 0 and sub(inner, at - 1, at - 1) == " " and (sub(inner, at, at + 1) == "->" or sub(inner, at, at + 1) == "=>") then
        push(out, {name = name, items = commas + 1, text = trim(sub(inner, type_start, at - 1))})
        done = true
      end
    end
    at = at + 1
  end
  return out
end

-- Whether any line of the file at `p` is wider than WIDTH.
function has_wide_line(p)
  for l in lines(read(p)) do
    if line_width(l) > WIDTH then return true end
  end
  return false
end

-- The columns that strings' text takes up in `files`, by Roc's parser, as
-- `{columns, refused}`. `columns[path]` maps a line's number, as text, to
-- those columns. Only a file with a wide line is parsed, so a tree of short
-- lines never needs roc-ast. `refused` is parse_roc_files' list.
function string_columns_in(files)
  local wide_files = {}
  for p in files do
    if has_wide_line(p) then push(wide_files, p) end
  end
  local columns = {}
  if #wide_files == 0 then return {columns = columns, refused = {}} end
  local parsed = parse_roc_files(wide_files)
  for f in parsed.files do
    columns[f.path] = string_columns_on_lines(f.nodes, split(read(f.path), "\n"), "check_stacking: " .. f.path)
  end
  return {columns = columns, refused = parsed.refused}
end

-- The finding for line `i` of `p`, wider than WIDTH with nothing else found
-- on it. `string_columns` is the columns of strings' text on that file's
-- lines, by line number.
function wide_line_finding(p, i, l, reachable_line, string_columns)
  local width = line_width(l)
  local without_strings = width - get(string_columns, "" .. i, 0)
  if without_strings <= WIDTH then
    return {path = p, line = i, kind = "wide string", what = width .. " columns, " .. without_strings .. " without its strings"}
  end
  local why = starts_with(trim(l), "#") and "a comment" or (group_to_stack(reachable_line, TOKENS, WIDTH) ~= nil and "a group to stack" or "nothing to stack")
  return {path = p, line = i, kind = "long", what = width .. " columns, " .. why}
end

function concat_lists(a, b)
  local out = {}
  for x in a do push(out, x) end
  for x in b do push(out, x) end
  return out
end

-- The names the headers of `files` dictate, by path, as `{names, refused}`.
-- Only an app's or a platform's file is parsed, so a tree of modules needs no
-- roc-ast for this.
function dictated_names_in(files)
  local headed = {}
  for p in files do
    local word = header_word(read(p))
    if word == "app" or word == "platform" then push(headed, p) end
  end
  local names = {}
  if #headed == 0 then return {names = names, refused = {}} end
  local parsed = parse_roc_files(headed)
  for f in parsed.files do names[f.path] = header_names(f.nodes).dictated end
  return {names = names, refused = parsed.refused}
end

-- The names the `dictated` table adds to `names`, the result of
-- dictated_names_in. Each line of the table is a file's path, a function's
-- name, and after ` -- ` who dictates its arguments, such as an API the file
-- copies or an edge with no records. The path names the file the glob finds
-- with that path or ending `/` and that path, so the self-test's copies in
-- scratch are found too. A line whose file the glob doesn't find, whose
-- function has no annotation there, or that gives no reason stops the run, so
-- the table can't go stale.
function with_dictated_table(names, files)
  if DICTATED == "" then return names end
  for l in lines(read(DICTATED)) do
    if trim(l) ~= "" and not starts_with(trim(l), "#") then
      local m = re_find(l, "^(\\S+) ([a-z_][A-Za-z0-9_]*!?) -- \\S")
      if m == nil then fail("check_stacking: " .. DICTATED .. " has a line that is not `path name -- reason`: " .. l) end
      local name = m.groups[2]
      local path = nil
      for p in files do
        if p == m.groups[1] or ends_with(p, "/" .. m.groups[1]) then path = p end
      end
      if path == nil then fail("check_stacking: " .. DICTATED .. " names " .. m.groups[1] .. ", which the glob doesn't find") end
      local annotated = false
      for line in lines(read(path)) do
        if starts_with(trim(line), name .. " :") then annotated = true end
      end
      if not annotated then
        fail("check_stacking: " .. DICTATED .. " names " .. name .. ", which has no annotation in " .. path)
      end
      local here = get(names, path, {})
      here[name] = true
      names[path] = here
    end
  end
  return names
end

-- Every finding in `files`, as `{found, refused}`: `found` holds each as
-- `{path, line, kind, what}`, and `refused` the files roc-ast refused.
function findings_in(files)
  local out = {}
  local strings = string_columns_in(files)
  local dictated = dictated_names_in(files)
  dictated.names = with_dictated_table(dictated.names, files)
  for p in files do
    local ls = split(read(p), "\n")
    local reachable = without_targets_section(ls)
    local string_columns = get(strings.columns, p, {})
    local dictated_here = get(dictated.names, p, {})
    -- The function whose annotation ended on the line before and was a
    -- finding for its arguments, or "". Its lambda's arguments are not
    -- reported again.
    local annotated_fn = ""
    local annotation_end = 0
    for i = 1, #ls do
      local found_on_line = 0
      local skip_lambda = annotated_fn ~= "" and i == annotation_end + 1 and starts_with(trim(ls[i]), annotated_fn .. " = |")
      if i > annotation_end then annotated_fn = "" end
      local data_line = is_data_line(reachable[i], WIDTH)
      for g in sort(groups_on_line(reachable[i]), "open") do
        local inner = sub(ls[i], g.open + 1, g.close - 1)
        if sub(ls[i], g.open, g.open) == "{" then
          for field in record_field_functions(inner) do
            if field.items >= 3 and not has_key(dictated_here, field.name) then
              push(out, function_type_finding(p, i, field.items, shortened(field.text), field.text))
              found_on_line = found_on_line + 1
            end
          end
        end
        if g.items >= 3 and g.fn_type then
          local arguments = split(split(inner, "->")[1], "=>")[1]
          push(out, function_type_finding(p, i, g.items, shortened(sub(ls[i], g.open, g.close)), arguments))
          found_on_line = found_on_line + 1
        elseif skip_lambda and sub(ls[i], g.open, g.open) == "|" then
          skip_lambda = false
        elseif not data_line then
          local are_flags = g.items >= 3 and not g.trailing and are_all_flags(inner)
          if are_flags or should_stack(ls[i], g, TOKENS, WIDTH) then
            local advice = are_flags and FLAG_ADVICE or ""
            push(out, {path = p, line = i, kind = "stack", what = g.tokens .. " tokens in " .. shortened(sub(ls[i], g.open, g.close)) .. advice})
            found_on_line = found_on_line + 1
          end
        end
      end
      -- A line inside a wrapped annotation starts none.
      local annotation = i > annotation_end and annotation_arguments(ls, i) or nil
      if annotation ~= nil then annotation_end = annotation.last end
      if annotation ~= nil and annotation.items >= 3 then
        annotated_fn = annotation.name
        if not has_key(dictated_here, annotation.name) then
          push(out, function_type_finding(p, i, annotation.items, annotation.shown, annotation.text))
          found_on_line = found_on_line + 1
        end
      end
      if found_on_line == 0 and line_width(ls[i]) > WIDTH then
        push(out, wide_line_finding(p, i, ls[i], reachable[i], string_columns))
      end
    end
    for g in groups_to_unstack(ls, TOKENS, WIDTH) do
      push(out, {path = p, line = g.line, kind = "unstack", what = g.tokens .. " tokens in " .. shortened(trim(group_on_one_line(ls, g)))})
    end
  end
  return {found = out, refused = unique(concat_lists(strings.refused, dictated.refused))}
end

-- Runs `roc fmt` on `files`. The result's code is not 0 when a file does
-- not parse.
function roc_fmt(files)
  local argv = {roc_bin("check_stacking", SELF_TEST), "fmt"}
  for p in files do push(argv, real(p)) end
  return run(argv, {timeout_ms = 120000, tail = 20})
end

-- Rewrites `files` pass after pass until a pass changes nothing, and
-- returns how many groups the first pass changed. A pass takes the trailing
-- comma from each group that should unstack and gives one to each line's group
-- that should stack, and `roc fmt` lays out the result.
function rewrite_trailing_commas(files)
  local first_pass_count = 0
  local pass = 1
  local changed = 1
  local touched = {}
  while changed > 0 and pass <= MAX_PASSES do
    changed = 0
    touched = {}
    for p in files do
      local ls = split(read(p), "\n")
      local unstacked = groups_to_unstack(ls, TOKENS, WIDTH)
      ls = without_trailing_commas(ls, unstacked)
      local reachable = without_targets_section(ls)
      local n = #unstacked
      for i = 1, #ls do
        if not starts_with(trim(ls[i]), "#") then
          local g = group_to_stack(reachable[i], TOKENS, WIDTH)
          if g ~= nil then
            ls[i] = with_trailing_comma(ls[i], g)
            n = n + 1
          end
        end
      end
      if n > 0 then
        replace(p, join(ls, "\n"))
        push(touched, p)
        changed = changed + n
      end
    end
    print("pass " .. pass .. ": " .. changed .. " groups rewritten, in " .. #touched .. " files")
    if pass == 1 then first_pass_count = changed end
    if #touched > 0 then
      local r = roc_fmt(touched)
      if r.code ~= 0 then
        print(r.out)
        fail("roc fmt failed")
      end
    end
    pass = pass + 1
  end
  if changed > 0 then fail("check_stacking: still changing after " .. MAX_PASSES .. " passes: " .. join(touched, ", ")) end
  return first_pass_count
end

function self_test()
  local files = chosen_files()
  local kinds_by_plant = {}
  local count_by_line = {}
  local whats_by_line = {}
  local judged = findings_in(files)
  fail_if_refused("check_stacking", judged.refused)
  for f in judged.found do
    local name = sub(f.path, #PLANTS + 2)
    kinds_by_plant[name] = get(kinds_by_plant, name, " ") .. f.kind .. " "
    incr(count_by_line, f.path .. ":" .. f.line)
    push_at(whats_by_line, f.path .. ":" .. f.line, f.what)
  end
  local bad = 0
  for p in files do
    local n = 0
    for l in lines(read(p)) do
      n = n + 1
      local mark = re_find(l, "# findings ([0-9]+)(?: advice ([a-z]+))?$")
      if mark ~= nil then
        local got = get(count_by_line, p .. ":" .. n, 0)
        local ok = got == tonumber(mark.groups[1])
        local word = get(mark.groups, 2, "")
        if word ~= nil and word ~= "" then
          for what in get(whats_by_line, p .. ":" .. n, {}) do
            if not contains(what, word) then ok = false end
          end
        end
        print((ok and "ok   " or "FAIL ") .. sub(p, #PLANTS + 2) .. ":" .. n .. ": " .. got .. " findings, want " .. mark.groups[1])
        if not ok then bad = bad + 1 end
      end
    end
  end
  for p in files do
    local name = sub(p, #PLANTS + 2)
    local is_long = starts_with(name, "long")
    local is_wide = starts_with(name, "wide")
    local want = is_long and "long" or (is_wide and "wide string" or (starts_with(name, "unstack") and "unstack" or "stack"))
    local got = get(kinds_by_plant, name, "")
    local clean = starts_with(name, "clean")
    local ok = (clean and got == "") or (not clean and contains(got, " " .. want .. " "))
    if is_long and contains(got, "wide string") then ok = false end
    if is_wide and contains(got, "long") then ok = false end
    print((ok and "ok   " or "FAIL ") .. name .. ": " .. (got == "" and "no finding" or got))
    if not ok then bad = bad + 1 end
  end
  if bad > 0 then fail(bad .. " plants wrong") end
  if is_dir(SCRATCH) then remove_tree(SCRATCH) end
  mkdir(SCRATCH)
  local copies = {}
  for p in files do
    local to = SCRATCH .. "/" .. sub(p, #PLANTS + 2)
    replace(to, read(p))
    push(copies, to)
  end
  rewrite_trailing_commas(copies)
  local again = rewrite_trailing_commas(copies)
  if again > 0 then fail("check_stacking: a second rewrite changed " .. again .. " more groups") end
  local r = roc_fmt(copies)
  if r.code ~= 0 then
    print(r.out)
    fail("check_stacking: a rewritten plant no longer parses")
  end
  for want in glob(PLANTS .. "/*.want") do
    local name = sub(basename(want), 1, #basename(want) - 5)
    local ok = read(SCRATCH .. "/" .. name .. ".roc") == read(want)
    print((ok and "ok   " or "FAIL ") .. name .. ".roc: comes out as its .want")
    if not ok then bad = bad + 1 end
  end
  if bad > 0 then fail(bad .. " plants came out wrong") end
  print("PASS: every plant gives its finding, the clean ones none; the rewrite ends, a second changes nothing, every plant parses and comes out as its .want")
end

function finding_line(f)
  return f.path .. ":" .. f.line .. ": " .. f.kind .. ": " .. f.what
end

if SELF_TEST then
  self_test()
elseif WRITE then
  refuse_house_rewrite("check_stacking")
  -- Stop before any change if the tree's Roc is missing.
  roc_bin("check_stacking", SELF_TEST)
  local files = chosen_files()
  rewrite_trailing_commas(files)
  local left = {}
  local judged = findings_in(files)
  for f in judged.found do push(left, finding_line(f)) end
  print_findings(#left .. " left, each a line the rewrite can't reach", left)
  fail_if_refused("check_stacking", judged.refused)
else
  local files = chosen_files()
  local all = {}
  local count_by_kind = {}
  local judged = findings_in(files)
  for f in judged.found do
    if not house_leaves_out("check_stacking", f.kind) then
      push(all, finding_line(f))
      incr(count_by_kind, f.kind)
    end
  end
  local counts = get(count_by_kind, "stack", 0) .. " to stack, " .. get(count_by_kind, "unstack", 0) .. " to unstack, " .. get(count_by_kind, "long", 0) .. " long, " .. get(count_by_kind, "wide string", 0) .. " wide string" .. house_note("check_stacking")
  print_findings(#all .. " findings in " .. #files .. " files: " .. counts, all)
  fail_if_refused("check_stacking", judged.refused)
end