find_calls_nested_three_deep

Roc

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

cookbook/roc/find_calls_nested_three_deep/find_calls_nested_three_deep.roc, 224 lines

## find_calls_nested_three_deep, in Roc on Shale's platform (roc_platform/README.md):
## calls nested three or more deep, like `f(g(h(x)))`, which have to be read
## from the inside out, where Roc's style guide (roc-apps docs/roc-style.md)
## asks for code that reads left to right: a method chain, a pipe or a named
## middle step. Its launcher, cookbook/roc/find_calls_nested_three_deep.shale, is how it
## is run, and its header says the rule. check_goldens.shale, beside this,
## holds its output on the plants to its goldens, line for line.
##
##   cd <repo> && shale cookbook:roc/find_calls_nested_three_deep.shale glob=app/**/*.roc min=4
##   shale cookbook:roc/find_calls_nested_three_deep.shale self_test=1
##
## The arguments: `glob` (`**/*.roc`), `min` (3), `loose` (`loose=1` passes a
## record's, list's or tuple's depth through), `house` (`house=0` leaves out
## the house style, which here is the whole check) and `self_test`
## (`self_test=1` checks the plants' marks).
##
## The effects: `Shale.arg!` for the arguments, `Shale.glob!` for the files,
## `Shale.roc_tree!` for Roc's own parser's tree of each, `Shale.read!` for
## a finding's source line, and `Shale.print!` and `Shale.fail!` for the
## verdict. Nest, beside this, is the rule, over Tree; NestFinding is how a
## finding prints; SelfTest checks the plants.
## budget: steps=800000000 arena_bytes=3000000000 output_bytes=4000000 roc_cpu_ms=600000
app [main!] { lib: "../lib/main.roc", pf: platform "../../../roc_platform/platform/main.roc" }

import pf.Shale
import NestFinding
import Nest
import SelfTest
import lib.Text
import lib.Tree

## What a run checks: the files a glob names, and the rule, or the plants
## at the self-test's own `min`.
Settings : {
	pattern : Str,
	rule : Nest.Rule,
	house : [Kept, LeftOut],
}

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

# ── The arguments

## The settings the arguments give. `min` is read before the files are
## globbed and `house` after, as the Shale original read them, so a run
## given two bad values stops on the same one.
read_settings! : Bool => Settings
read_settings! = |is_self_test| {
	pattern = if is_self_test {
		"${SelfTest.plants}*.roc"
	} else {
		Shale.arg!("glob", "**/*.roc")
	}
	strictness = if Shale.arg!("loose", "") == "1" {
		Loose
	} else {
		Strict
	}
	min = if is_self_test {
		3
	} else {
		read_min!({})
	}
	{
		pattern,
		rule: { min, strictness },
		house: Kept,
	}
}

## The `min=` depth: 3 unless given, and any integer.
read_min! : {} => I64
read_min! = |{}| {
	given = Shale.arg!("min", "3")
	match I64.from_str(given) {
		Ok(min) => min
		Err(_) => {
			Shale.fail!("find_calls_nested_three_deep: min=${given} is not an integer")
			0
		}
	}
}

## Whether `house=0` leaves the house style out (cookbook/roc/house.shale):
## here that is every finding, since `nested` is house style.
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
	}
}

# ── The run

## The check over the glob's files: the verdict printed, then a stop when a
## file didn't parse. The findings are a report, not a failure, so a run
## that parses every file exits 0; a caller holds the count.
run_check! : Settings => { paths : List(Str), findings : List(NestFinding) }
run_check! = |given| {
	paths = Shale.glob!(given.pattern)
	settings = { ..given, house: read_house!({}) }
	var $findings = []
	var $refused = []
	for file in Shale.roc_tree!(paths) {
		if file.err == "" {
			parsed = { path: file.path, syntax_nodes: file.nodes }
			$findings = $findings.concat(find_file_findings!(parsed, settings))
		} else if file.err.starts_with(file.path) {
			$refused = $refused.append(file.err)
		} else {
			$refused = $refused.append("${file.path}: ${file.err}")
		}
	}
	summary_line = summary($findings, { file_count: paths.len(), settings })
	print_findings!(summary_line, $findings.map(NestFinding.finding_line))
	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_calls_nested_three_deep: ${refusals}, ${why}")
	}
	{ paths, findings: $findings }
}

## A parsed file's findings. Its text is read only when it has a nest, for
## the source lines; a file the parser read and the read finds gone stops
## the run.
find_file_findings! : { path : Str, syntax_nodes : List(Tree.Node) }, Settings => List(NestFinding)
find_file_findings! = |file, settings| {
	nests = match settings.house {
		Kept => Nest.nests_in(file.syntax_nodes, settings.rule)
		LeftOut => []
	}
	if nests.is_empty() {
		[]
	} else {
		source_lines = match Shale.read!(file.path) {
			Found(text) => text.split_on("\n")
			Missing => {
				Shale.fail!("find_calls_nested_three_deep: ${file.path} went missing during the check")
				[]
			}
		}
		nests.map(
			|nest| {
				source_line = match source_lines.get(nest.line - 1) {
					Ok(text) => text
					Err(_) => crash "find_calls_nested_three_deep: a nest starts past its file's last line"
				}
				{ path: file.path, nest, source_line }
			},
		)
	}
}

# ── The verdict

## `find_calls_nested_three_deep (Roc): 9 files; nested 14 (min 3, strict); depth 3 11,
## depth 4 3`: the files, the findings, the rule, and how many at each depth,
## the depths in the order of their text, as the Shale original sorted them.
summary : List(NestFinding), { file_count : U64, settings : Settings } -> Str
summary = |findings, { file_count, settings }| {
	rule = settings.rule
	strictness = match rule.strictness {
		Strict => "strict"
		Loose => "loose"
	}
	counted = "nested ${findings.len().to_str()} (min ${rule.min.to_str()}, ${strictness})"
	depths = findings.map(|finding| finding.nest.depth.to_str())
	by_depth = distinct(depths).sort_with(Text.byte_order).map(
		|depth| "depth ${depth} ${depths.count_if(|d| d == depth).to_str()}",
	)
	counts = if by_depth.is_empty() {
		""
	} else {
		"; ${Str.join_with(by_depth, ", ")}"
	}
	house_note = match settings.house {
		Kept => ""
		LeftOut => "; left out as house style: nested"
	}
	"find_calls_nested_three_deep (Roc): ${file_count.to_str()} files; ${counted}${counts}${house_note}"
}

distinct : List(Str) -> List(Str)
distinct = |texts|
	texts.fold(
		[],
		|seen, text|
			if seen.contains(text) {
				seen
			} else {
				seen.append(text)
			},
	)

## 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_line, finding_lines| {
	Shale.print!(summary_line)
	if !(finding_lines.is_empty()) {
		for line in finding_lines {
			Shale.print!(line)
		}
		Shale.print!(summary_line)
	}
}

cookbook/roc/find_calls_nested_three_deep/NestFinding.roc, 27 lines

## A finding: one nest of calls in a file, and the source line its outermost
## call starts on, printed as
## `path:line:column: nested: depth N, <outermost> to <deepest>: <line>`.
import Nest
import lib.Text

NestFinding := {
	path : Str,
	nest : Nest,
	source_line : Str,
}.{

	## The finding up to its source line: where it is, how deep, and which
	## calls it runs between. The self-test reads this part.
	head : NestFinding -> Str
	head = |finding| {
		nest = finding.nest
		place = "${finding.path}:${nest.line.to_str()}:${nest.column.to_str()}"
		span = "${nest.outermost} to ${nest.deepest}"
		"${place}: nested: depth ${nest.depth.to_str()}, ${span}"
	}

	## The finding's whole line, its source line trimmed.
	finding_line : NestFinding -> Str
	finding_line = |finding|
		"${NestFinding.head(finding)}: ${Text.trim(finding.source_line)}"
}

cookbook/roc/find_calls_nested_three_deep/Nest.roc, 253 lines

## A nest of calls: the outermost call of calls nested in each other's
## arguments, like `f(g(h(x)))`, with its depth and the names of its
## outermost and deepest calls. `Nest.nests_in` finds a file's nests from
## Roc's tree of it; the launcher's header says the rule.
import lib.Tree

Nest := {
	line : U64,
	column : U64,
	depth : U64,
	outermost : Str,
	deepest : Str,
}.{

	## Whether a record, a list or a tuple argument starts the depth again
	## (`Strict`, the default) or passes its parts' depth through (`Loose`).
	Strictness : [Strict, Loose]

	## What to report: nests at least `min` deep, judged as `strictness` says.
	Rule : { min : I64, strictness : Nest.Strictness }

	## The file's nests at least the rule's `min` deep, in source order, each
	## named by its outermost call.
	nests_in : List(Tree.Node), Nest.Rule -> List(Nest)
	nests_in = |syntax_nodes, rule| {
		reading = {
			syntax_nodes,
			depths: call_depths(syntax_nodes, rule.strictness),
			strictness: rule.strictness,
		}
		var $nests = []
		var $place = 1
		while $place <= syntax_nodes.len() {
			is_deep_enough = depth_at(reading, $place).to_i64_wrap() >= rule.min
			is_nest = is_call(Tree.node_at(syntax_nodes, $place)) and is_outermost(reading, $place)
			if is_deep_enough and is_nest {
				$nests = $nests.append(nest_at(reading, $place))
			}
			$place = $place + 1
		}
		$nests
	}
}

## A tree read for nests: each node's call depth beside it, by place.
Reading : {
	syntax_nodes : List(Tree.Node),
	depths : List(U64),
	strictness : Nest.Strictness,
}

nest_at : Reading, U64 -> Nest
nest_at = |reading, place| {
	node = Tree.node_at(reading.syntax_nodes, place)
	{
		line: node.line,
		column: node.column,
		depth: depth_at(reading, place),
		outermost: call_name(reading.syntax_nodes, place),
		deepest: call_name(reading.syntax_nodes, deepest_call(reading, place)),
	}
}

# ── Depth

## The node kinds that pass their parts' depth through: what reads left to
## right, a wrapper, an operator, an access, a string's interpolation. `unary`
## is `!x` or `-x`, `receiver` holds the value whose method is called, and
## `mapper` is the right side of `x |> f`.
pass_through_kinds : List(Str)
pass_through_kinds = [
	"e-arrow-call",
	"e-question-suffix",
	"e-nominal-apply",
	"mapper",
	"e-binop",
	"unary",
	"e-field-access",
	"e-tuple-access",
	"receiver",
	"e-string",
]

## The kinds that pass their parts' depth through only when the rule is
## `Loose`.
loose_pass_through_kinds : List(Str)
loose_pass_through_kinds = ["e-record", "e-list", "e-tuple", "field"]

passes_depth_through : Str, Nest.Strictness -> Bool
passes_depth_through = |kind, strictness|
	match strictness {
		Strict => pass_through_kinds.contains(kind)
		Loose => pass_through_kinds.contains(kind) or loose_pass_through_kinds.contains(kind)
	}

is_call : Tree.Node -> Bool
is_call = |node| node.kind == "e-apply" or node.kind == "e-method-call"

## Every node's call depth, by place. A node's depth is its kids', so the
## places are taken from the last, whose kids come after them all.
call_depths : List(Tree.Node), Nest.Strictness -> List(U64)
call_depths = |syntax_nodes, strictness| {
	var $depths = List.repeat(0, syntax_nodes.len())
	var $place = syntax_nodes.len()
	while $place > 0 {
		depth = depth_from_kids({ syntax_nodes, depths: $depths, strictness }, $place)
		$depths = $depths.set(
			$place - 1,
			depth,
		) ?? crash "find_calls_nested_three_deep: a place past the last node"
		$place = $place - 1
	}
	$depths
}

## A node's call depth from its kids' depths, which `reading` already has.
## A call is one more than its deepest argument; a method call is at least
## as deep as its receiver, which reads left to right; a tag's payload, as
## in `Ok(...)`, adds no level; what passes depth through, and a one-item
## tuple, which is a pair of parentheses, is as deep as its deepest part;
## anything else (a lambda, a record) starts again at zero.
depth_from_kids : Reading, U64 -> U64
depth_from_kids = |reading, place| {
	node = Tree.node_at(reading.syntax_nodes, place)
	if node.kind == "e-apply" {
		deepest_argument = deepest_of(reading, node.kids.drop_first(1))
		function = Tree.node_at(reading.syntax_nodes, Tree.first_kid(node))
		if function.kind == "e-tag" {
			deepest_argument
		} else {
			1 + deepest_argument
		}
	} else if node.kind == "e-method-call" {
		method_call_depth(reading, node)
	} else if passes_depth_through(node.kind, reading.strictness) or is_parenthesized(node) {
		deepest_of(reading, node.kids)
	} else {
		0
	}
}

method_call_depth : Reading, Tree.Node -> U64
method_call_depth = |reading, node| {
	var $receiver_depth = 0
	var $deepest_argument = 0
	for kid in node.kids {
		part = Tree.node_at(reading.syntax_nodes, kid)
		if part.kind == "receiver" {
			$receiver_depth = depth_at(reading, Tree.first_kid(part))
		}
		if part.kind == "args" {
			$deepest_argument = U64.max($deepest_argument, deepest_of(reading, part.kids))
		}
	}
	U64.max(1 + $deepest_argument, $receiver_depth)
}

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

deepest_of : Reading, List(U64) -> U64
deepest_of = |reading, places|
	places.fold(0, |deepest, place| U64.max(deepest, depth_at(reading, place)))

depth_at : Reading, U64 -> U64
depth_at = |reading, place|
	match reading.depths.get(place - 1) {
		Ok(depth) => depth
		Err(_) => crash "find_calls_nested_three_deep: no depth for node ${place.to_str()}"
	}

# ── The nest around a call

## Whether a call nested under this node still belongs to the nest of the
## call above it.
continues_nest : Tree.Node, Nest.Strictness -> Bool
continues_nest = |node, strictness| {
	is_part = node.kind == "args" or node.kind == "e-tuple"
	is_call(node) or is_part or passes_depth_through(node.kind, strictness)
}

## Whether the call at `place` is the outermost of its nest: the first call
## above it, through nodes that continue the nest, is not as deep.
is_outermost : Reading, U64 -> Bool
is_outermost = |reading, place| {
	depth = depth_at(reading, place)
	var $above = Tree.node_at(reading.syntax_nodes, place).parent
	while $above > 0 {
		node = Tree.node_at(reading.syntax_nodes, $above)
		if is_call(node) {
			return depth_at(reading, $above) < depth
		}
		if !(continues_nest(node, reading.strictness)) {
			return Bool.True
		}
		$above = node.parent
	}
	Bool.True
}

## Whether the call at `place` is inside the nest of the call at `top`:
## every node between them continues the nest.
is_in_nest : Reading, { top : U64, place : U64 } -> Bool
is_in_nest = |reading, { top, place }| {
	var $above = Tree.node_at(reading.syntax_nodes, place).parent
	while $above > 0 and $above != top {
		node = Tree.node_at(reading.syntax_nodes, $above)
		if !(continues_nest(node, reading.strictness)) {
			return Bool.False
		}
		$above = node.parent
	}
	$above == top
}

## The deepest call of the nest under the call at `top`: the first call of
## depth 1 inside it, in source order, or `top` itself when it has none.
## The nodes inside it are those after it that are deeper in the tree.
deepest_call : Reading, U64 -> U64
deepest_call = |reading, top| {
	top_depth = Tree.node_at(reading.syntax_nodes, top).depth
	is_inside = |place| Tree.node_at(reading.syntax_nodes, place).depth > top_depth
	var $place = top + 1
	while $place <= reading.syntax_nodes.len() and is_inside($place) {
		node = Tree.node_at(reading.syntax_nodes, $place)
		is_deepest = is_call(node) and depth_at(reading, $place) == 1
		if is_deepest and is_in_nest(reading, { top, place: $place }) {
			return $place
		}
		$place = $place + 1
	}
	top
}

## A call's name: an apply's function as written (`List.concat`, else its
## name, else its kind), or a method call's method (`.concat`).
call_name : List(Tree.Node), U64 -> Str
call_name = |syntax_nodes, place| {
	node = Tree.node_at(syntax_nodes, place)
	if node.kind == "e-method-call" {
		match Tree.find_attribute(node, "method") {
			Ok(method) => method
			Err(_) => crash "find_calls_nested_three_deep: a method call with no method"
		}
	} else {
		function = Tree.node_at(syntax_nodes, Tree.first_kid(node))
		match Tree.find_attribute(function, "raw") {
			Ok(raw) => raw
			Err(_) => Tree.find_attribute(function, "name") ?? function.kind
		}
	}
}

cookbook/roc/find_calls_nested_three_deep/SelfTest.roc, 154 lines

## The recipe's self-test: the plants in cookbook/roc/plants/find_calls_nested_three_deep/,
## checked at `min=3` against the marks they carry. A line ending
## `# depth N` must give one finding of depth N, and one ending
## `# depth N, M` a finding for each, left to right; an added `from A to B`
## means the line's first finding must say `A to B`. No unmarked line may
## give a finding, no two findings may print the same line, and a
## `quiet_*.roc` plant may hold no mark.
import pf.Shale
import NestFinding

SelfTest := [].{

	## Where the plants are.
	plants : Str
	plants = "cookbook:roc/plants/find_calls_nested_three_deep/"

	## Each plant's marks held to the findings the run printed: every fault
	## said, then a stop, or the PASS line.
	run! : { paths : List(Str), findings : List(NestFinding) } => {}
	run! = |{ paths, findings }| {
		var $faults = []
		var $mark_count = 0
		for path in paths {
			text = match Shale.read!(path) {
				Found(found) => found
				Missing => {
					Shale.fail!("find_calls_nested_three_deep self_test: ${path} went missing")
					""
				}
			}
			var $number = 1
			for line in text.split_on("\n") {
				mark = read_mark!(line)
				if mark != Unmarked {
					$mark_count = $mark_count + 1
				}
				judged = {
					place: "${path}:${$number.to_str()}",
					path,
					mark,
					line_findings: findings_at_line(findings, { path, line: $number }),
				}
				$faults = $faults.concat(line_faults(judged))
				$number = $number + 1
			}
		}
		$faults = $faults.concat(duplicate_line_faults(findings))
		if $mark_count == 0 {
			$faults = $faults.append("no plant holds a `# depth` mark")
		}
		for fault in $faults {
			Shale.print!("FAIL ${fault}")
		}
		if !($faults.is_empty()) {
			Shale.fail!("find_calls_nested_three_deep self_test: ${$faults.len().to_str()} plants wrong")
		}
		marks = "each marked line gives its depths left to right, the outermost only"
		others = "no other line a finding, and no two findings print alike"
		Shale.print!("find_calls_nested_three_deep (Roc) self_test: PASS (${marks}, ${others})")
	}
}

## A line's mark: the depths it wants, as written (`3, 4`), and the
## outermost and deepest calls its first finding must name, if it says.
Mark : [Marked({ depths : Str, span : [Says(Str), Silent] }), Unmarked]

read_mark! : Str => Mark
read_mark! = |line| {
	depths = "([0-9]+(?:, [0-9]+)*)"
	span = "(?: from ([A-Za-z0-9_.]+) to ([A-Za-z0-9_.]+))?"
	match Shale.re_find!(line, "# depth ${depths}${span}$") {
		Found(found) =>
			match found.groups {
				[wanted, outermost, deepest] if outermost != "" =>
					Marked({ depths: wanted, span: Says("${outermost} to ${deepest}") })
				[wanted, ..] => Marked({ depths: wanted, span: Silent })
				[] => crash "find_calls_nested_three_deep: a mark matched with no groups"
			}
		NoMatch => Unmarked
	}
}

## The findings on one line of a plant, left to right.
findings_at_line : List(NestFinding), { path : Str, line : U64 } -> List(NestFinding)
findings_at_line = |findings, { path, line }|
	findings
		.keep_if(|finding| finding.path == path and finding.nest.line == line)
		.sort_by(|finding| finding.nest.column)

## A plant's line to judge: where it is, its mark and its findings.
JudgedLine : {
	place : Str,
	path : Str,
	mark : Mark,
	line_findings : List(NestFinding),
}

## What is wrong with one line: its findings against its mark.
line_faults : JudgedLine -> List(Str)
line_faults = |{ place, path, mark, line_findings }| {
	got = Str.join_with(line_findings.map(|finding| finding.nest.depth.to_str()), ", ")
	match mark {
		Marked({ depths, span }) => {
			quiet_fault =
				if path.drop_prefix(SelfTest.plants).starts_with("quiet_") {
					["${place}: a quiet plant holds a `# depth` mark"]
				} else {
					[]
				}
			span_fault =
				match span {
					Says(says) =>
						match line_findings.first() {
							Ok(first) if NestFinding.head(first).contains(says) => []
							_ => ["${place}: the finding does not say `${says}`"]
						}
					Silent => []
				}
			depth_fault =
				if line_findings.is_empty() {
					["${place}: no finding, want depth ${depths}"]
				} else if got != depths {
					["${place}: depth ${got}, want ${depths}"]
				} else {
					[]
				}
			quiet_fault.concat(span_fault).concat(depth_fault)
		}
		Unmarked =>
			if line_findings.is_empty() {
				[]
			} else {
				["${place}: a finding (depth ${got}) on a line not marked for one"]
			}
	}
}

## A fault for each line that two findings print alike.
duplicate_line_faults : List(NestFinding) -> List(Str)
duplicate_line_faults = |findings| {
	finding_lines = findings.map(NestFinding.finding_line)
	is_printed_twice = |line| finding_lines.count_if(|other| other == line) > 1
	once_each = |seen, line| {
		if seen.contains(line) {
			seen
		} else {
			seen.append(line)
		}
	}
	finding_lines
		.keep_if(is_printed_twice)
		.fold([], once_each)
		.map(|line| "two findings print the same line, ${line}")
}

Shale original

cookbook/roc/find_deep_calls.shale, 232 lines, at 30f6d655

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

-- This recipe finds calls nested three or more deep, like `f(g(h(x)))`, in
-- every .roc file of a tree. Such a call has to be read from the inside
-- out. The Roc style guide (roc-apps docs/roc-style.md) asks for code that
-- reads left to right instead: a method chain, a pipe, or a named middle
-- step. The recipe reads each file's syntax tree from Roc's own parser
-- (cookbook/roc/parsed.shale).
--
--   cd <repo> && shale <shale>/cookbook/roc/find_deep_calls.shale glob=chat/**/*.roc min=4
--   shale cookbook:roc/find_deep_calls.shale self_test=1
--
-- The arguments:
--   glob   the files to check, `**/*.roc` by default;
--   min    the least depth to report, 3 by default;
--   house  with `house=0`, leave out what is only our house style
--          (cookbook/roc/house.shale), for another project's code;
--   loose  with `loose=1`, a record, list or tuple argument does not reset
--          the depth.
--
-- A call's depth is one more than the deepest call among its arguments.
-- Some things pass their parts' depth through without adding a level:
-- whatever reads left to right (a method's receiver in `a.f().g()`, the
-- left side of `x |> f` and `x->f()`), a tag or nominal wrapper
-- (`Ok(...)`, `ChatPath.(...)`), `?`, parentheses, operators, field or
-- tuple access, and a string's interpolation. So `f(g(h(x) + 1))`,
-- `f(!g(h(x)))`, `f(g(h(x).a))` and `f("${g(h(x))}")` are each three deep. A lambda argument starts again at zero, since its body
-- is read on its own, and so does a record, list or tuple argument, whose
-- parts have names or places, unless `loose=1`.
--
-- Each finding is the outermost call of one nest:
--   path:line:column: nested: depth N, <outermost> to <deepest>: <source line>
-- The column tells apart two nests on one line. The outermost and deepest
-- calls are named (`List.concat to Str.to_utf8`, or `.concat` for a method)
-- so that a nest spread over several lines says more than its first line.
-- The output is the count by depth, the findings, and the count again
-- (cookbook/findings.shale). Files that don't parse are listed after
-- the findings, and then the run fails.
--
-- `self_test=1` checks the plants in `cookbook/roc/plants/find_deep_calls/` at
-- `min=3`. A plant line ending `# depth N` must give one finding of depth
-- N, and one ending `# depth N, M` a finding for each, left to right; an
-- added `from A to B` means the finding must say `A to B`. No unmarked line
-- may give a finding, no two findings may print the same line, and a
-- `quiet_*.roc` plant may hold no mark.
-- budget: steps=100000000 arena_bytes=3000000000 output_bytes=4000000

const SELF_TEST = arg("self_test", "") == "1"
const PLANTS = "cookbook:roc/plants/find_deep_calls/"
const GLOB = SELF_TEST and (PLANTS .. "*.roc") or arg("glob", "**/*.roc")
const LOOSE = arg("loose", "") == "1"
const MIN = SELF_TEST and 3 or arg("min", 3)
use("cookbook:findings.shale")
use("./house.shale")
use("./parsed.shale")

-- The node kinds that pass their parts' depth through. `unary` is `!x` or
-- `-x`, `receiver` holds the value whose method is called, and an `e-string`
-- holds its interpolations' code.
const PASS_THROUGH = {["e-arrow-call"] = true, ["e-question-suffix"] = true, ["e-nominal-apply"] = true, mapper = true, ["e-binop"] = true, unary = true, ["e-field-access"] = true, ["e-tuple-access"] = true, receiver = true, ["e-string"] = true}
const LOOSE_PASS_THROUGH = {["e-record"] = true, ["e-list"] = true, ["e-tuple"] = true, field = true}

function passes_depth_through(kind, loose)
  return has_key(PASS_THROUGH, kind) or (loose and has_key(LOOSE_PASS_THROUGH, kind))
end

function is_call(node)
  return node.kind == "e-apply" or node.kind == "e-method-call"
end

-- Whether a call nested under a node of this kind still belongs to the
-- same nest as the call above it.
function continues_nest(node, loose)
  local kind = node.kind
  return is_call(node) or kind == "args" or kind == "receiver" or kind == "e-tuple" or passes_depth_through(kind, loose)
end

-- The call depth of node `i`, cached in `memo`, where -1 means not yet
-- computed.
function call_depth(nodes, memo, i, loose)
  if memo[i] >= 0 then return memo[i] end
  local node = nodes[i]
  local kind = node.kind
  local depth = 0
  if kind == "e-apply" then
    -- The first kid is the function called, the rest its arguments.
    local deepest_argument = 0
    for argument in drop(node.kids, 1) do
      deepest_argument = max(deepest_argument, call_depth(nodes, memo, argument, loose))
    end
    -- A tag's payload, as in `Ok(...)`, is no call.
    if nodes[node.kids[1]].kind == "e-tag" then depth = deepest_argument else depth = 1 + deepest_argument end
  elseif kind == "e-method-call" then
    local receiver_depth = 0
    local deepest_argument = 0
    for kid in node.kids do
      if nodes[kid].kind == "receiver" then receiver_depth = call_depth(nodes, memo, nodes[kid].kids[1], loose) end
      if nodes[kid].kind == "args" then
        for argument in nodes[kid].kids do
          deepest_argument = max(deepest_argument, call_depth(nodes, memo, argument, loose))
        end
      end
    end
    depth = max(1 + deepest_argument, receiver_depth)
  elseif passes_depth_through(kind, loose) or (kind == "e-tuple" and #node.kids == 1) then
    -- A one-item tuple is a pair of parentheses.
    for kid in node.kids do
      depth = max(depth, call_depth(nodes, memo, kid, loose))
    end
  end
  memo[i] = depth
  return depth
end

-- Whether the call at `i` is the outermost of its nest: the first call
-- above it, through nodes that continue the nest, is not as deep.
function is_outermost(nodes, memo, i, loose)
  local p = nodes[i].parent
  while p > 0 do
    if is_call(nodes[p]) then return call_depth(nodes, memo, p, loose) < call_depth(nodes, memo, i, loose) end
    if not continues_nest(nodes[p], loose) then return true end
    p = nodes[p].parent
  end
  return true
end

-- A call's name: an apply's function (`List.concat`), or a method call's
-- method (`.concat`).
function call_name(nodes, i)
  local node = nodes[i]
  if node.kind == "e-method-call" then return get(node, "method", "?") end
  local head = nodes[node.kids[1]]
  return get(head, "raw", get(head, "name", head.kind))
end

-- Whether the call at `j` is inside the nest of the call at `top`: every
-- node between them continues the nest.
function is_in_nest(nodes, top, j, loose)
  local p = nodes[j].parent
  while p > 0 and p ~= top do
    if not continues_nest(nodes[p], loose) then return false end
    p = nodes[p].parent
  end
  return p == top
end

-- The deepest call of the nest under the call at `top`: the first call of
-- depth 1 inside it, in source order.
function deepest_call(nodes, memo, top, loose)
  local j = top + 1
  while j <= #nodes and nodes[j].depth > nodes[top].depth do
    if is_call(nodes[j]) and call_depth(nodes, memo, j, loose) == 1 and is_in_nest(nodes, top, j, loose) then return j end
    j = j + 1
  end
  return top
end

const paths = glob(GLOB)
local finding_count = 0
local count_by_depth = {}
local finding_lines = {}
-- For the self-test: each line's findings, `path:line` to a list of
-- `{col, depth, text}`, and how many times each finding line printed.
const findings_at_line = {}
const times_printed = {}
local parsed = parse_roc_files(paths)
for f in parsed.files do
  local nodes = f.nodes
  local memo = {}
  for n in nodes do push(memo, -1) end
  local source_lines = {}
  for i = 1, #nodes do
    if is_call(nodes[i]) and call_depth(nodes, memo, i, LOOSE) >= MIN and is_outermost(nodes, memo, i, LOOSE) then
      if #source_lines == 0 then source_lines = split(read(f.path), "\n") end
      local line = nodes[i].line
      local depth = call_depth(nodes, memo, i, LOOSE)
      local span = call_name(nodes, i) .. " to " .. call_name(nodes, deepest_call(nodes, memo, i, LOOSE))
      local head = f.path .. ":" .. line .. ":" .. nodes[i].col .. ": nested: depth " .. depth .. ", " .. span
      local finding = head .. ": " .. trim(source_lines[line])
      if not house_leaves_out("find_deep_calls", "nested") then
        push(finding_lines, finding)
        incr(times_printed, finding)
        count_by_depth[tostring(depth)] = get(count_by_depth, tostring(depth), 0) + 1
        push_at(findings_at_line, f.path .. ":" .. line, {col = nodes[i].col, depth = depth, text = head})
        finding_count = finding_count + 1
      end
    end
  end
end
local counts = {}
for depth in sort(keys(count_by_depth)) do push(counts, "depth " .. depth .. " " .. count_by_depth[depth]) end
print_findings("find_deep_calls (Roc): " .. #paths .. " files; nested " .. finding_count .. " (min " .. MIN .. ", " .. (LOOSE and "loose" or "strict") .. ")" .. (#counts > 0 and ("; " .. join(counts, ", ")) or "") .. house_note("find_deep_calls"), finding_lines)
fail_if_refused("find_deep_calls", parsed.refused)
if SELF_TEST then
  local wrong = {}
  local marks = 0
  for p in paths do
    local n = 0
    for l in lines(read(p)) do
      n = n + 1
      local mark = re_find(l, "# depth ([0-9]+(?:, [0-9]+)*)(?: from ([A-Za-z0-9_.]+) to ([A-Za-z0-9_.]+))?$")
      local key = p .. ":" .. n
      local got = {}
      local texts = {}
      if has_key(findings_at_line, key) then
        for g in sort(findings_at_line[key], "col") do
          push(got, tostring(g.depth))
          push(texts, g.text)
        end
      end
      if mark ~= nil then
        marks = marks + 1
        if starts_with(sub(p, #PLANTS + 1), "quiet_") then push(wrong, key .. ": a quiet plant holds a `# depth` mark") end
        local want = mark.groups[1]
        local outermost_name = get(mark.groups, 2, "")
        if outermost_name ~= nil and outermost_name ~= "" then
          local says = outermost_name .. " to " .. mark.groups[3]
          if #texts == 0 or not contains(texts[1], says) then push(wrong, key .. ": the finding does not say `" .. says .. "`") end
        end
        if #got == 0 then push(wrong, key .. ": no finding, want depth " .. want)
        elseif join(got, ", ") ~= want then push(wrong, key .. ": depth " .. join(got, ", ") .. ", want " .. want) end
      elseif #got > 0 then
        push(wrong, key .. ": a finding (depth " .. join(got, ", ") .. ") on a line not marked for one")
      end
    end
  end
  for l in keys(times_printed) do
    if times_printed[l] > 1 then push(wrong, "two findings print the same line, " .. l) end
  end
  if marks == 0 then push(wrong, "no plant holds a `# depth` mark") end
  for w in wrong do print("FAIL " .. w) end
  if #wrong > 0 then fail("find_deep_calls self_test: " .. #wrong .. " plants wrong") end
  print("find_deep_calls (Roc) self_test: PASS (each marked line gives its depths left to right, the outermost only, no other line a finding, and no two findings print alike)")
end