list_deep_nesting

Roc

It also imports Item, Mask, Paths, Split, Words from the C splitter.

cookbook/c/list_deep_nesting/list_deep_nesting.roc, 127 lines

## list_deep_nesting, in Roc on Shale's platform (roc_platform/README.md):
## Shale's C functions by how deeply their blocks nest, deepest first, from
## the splitter the C recipes share (cookbook/c/items/, a package). The
## kernel's style guide calls more than 3 levels of indentation a smell, so
## the line is depth 4 unless `min=` moves it. Its launcher,
## cookbook/c/list_deep_nesting.shale, is how it is run, and its header says
## the arguments and how depth is counted. check_goldens.shale, beside this,
## holds its output on the plants to its goldens, line for line.
##
##   shale cookbook:c/list_deep_nesting.shale min=5
##   shale cookbook:c/list_deep_nesting.shale self_test=1
##
## The effects: `Shale.arg!` for the arguments, `Shale.glob!` for the files,
## `Shale.read!` for each one's text, and `Shale.print!` and `Shale.fail!`
## for the verdict. Depth, beside this, measures and lists; SelfTest holds
## it to the plants.
## budget: steps=200000000 arena_bytes=1000000000 roc_cpu_ms=600000
app [main!] {
	items: "../items/main.roc",
	pf: platform "../../../roc_platform/platform/main.roc",
}

import pf.Shale
import items.Item
import items.Paths
import items.Split
import items.Words
import Depth
import SelfTest

main! : {} => {}
main! = |{}| {
	if integer_or_stop!("self_test", Shale.arg!("self_test", "0")) == 1 {
		SelfTest.run!(measure!)
	} else {
		folder = Shale.arg!("dir", "c")
		tests = integer_or_stop!("tests", Shale.arg!("tests", "0")) == 1
		min = integer_or_stop!("min", Shale.arg!("min", "4"))
		listing = match Depth.listing(measure!(folder, tests), min) {
			Ok(listed) => listed
			Err(why) => {
				Shale.fail!(why)
				{ summary: "", lines: [] }
			}
		}
		for line in listing.lines {
			Shale.print!(line)
		}
		which = if tests {
			"tests included"
		} else {
			"tests left out"
		}
		Shale.print!("list_deep_nesting: ${folder}, ${which}: ${listing.summary}")
	}
}

## A value given as `name=`, which must be an integer, as Shale's `arg` reads
## one whose default is.
integer_or_stop! : Str, Str => I64
integer_or_stop! = |name, given|
	match I64.from_str(given) {
		Ok(value) => value
		Err(_) => {
			Shale.fail!("list_deep_nesting: ${name}=${given} is not an integer")
			0
		}
	}

## Each function's body under the folder (and each test's, `tests`),
## measured. A body whose braces don't balance stops the run, naming it.
measure! : Str, Bool => List(Depth.Measured)
measure! = |folder, tests| {
	var $measured = []
	for path in c_files_under!(folder) {
		text = read_text!(path)
		lines = Split.lines(text)
		for item in split_or_stop!(path, text) {
			is_measured = item.kind == Function or (tests and item.kind == Test)
			if is_measured and item.body_first != 0 {
				match Depth.of_body(path, lines, item) {
					Ok(measured) => {
						$measured = $measured.append(measured)
					}
					Err(why) => Shale.fail!(why)
				}
			}
		}
	}
	$measured
}

## The file's text. A file the glob named and the read finds gone stops the
## run.
read_text! : Str => Str
read_text! = |path|
	match Shale.read!(path) {
		Found(text) => text
		Missing => {
			Shale.fail!("list_deep_nesting: ${path} went missing during the walk")
			""
		}
	}

## The file's items, or the run stopped with the line the dialect does not
## account for.
split_or_stop! : Str, Str => List(Item)
split_or_stop! = |path, text|
	match Split.items({ path, text, uses: Bool.False }) {
		Ok(items) => items
		Err(why) => {
			Shale.fail!(why)
			[]
		}
	}

## The C files under the folder, sorted, any folder named `out` (c/out, the
## build's output) left out. A folder that is not there stops the run, in
## the words of the Shale original's walk: a check that can't run fails.
c_files_under! : Str => List(Str)
c_files_under! = |folder| {
	if Shale.list!(folder) == Missing {
		Shale.fail!("`walk(\"${folder}\")`: not found (FileNotFound)")
	}
	paths = Shale.glob!("${folder}/**/*.c").concat(Shale.glob!("${folder}/**/*.h"))
	paths.keep_if(|path| !(Paths.is_in_out_folder(folder, path))).sort_with(Words.byte_order)
}

cookbook/c/list_deep_nesting/Depth.roc, 117 lines

## How deeply a function's blocks nest, and the listing of the deep ones. A
## function's own body is depth 1, and each block a `{` opens inside it is
## one deeper. Each body line is read through the splitter's masker, so a
## brace in a string, a character literal or a comment is no brace, and a
## line's braces are counted net (`} else {` stays at its depth). A body
## that shares its head's line is depth 1.
import items.Item
import items.Mask
import items.Words

Depth := [].{

	## A function's body measured: where it starts and its name, its deepest
	## nesting, and the first line that reaches it.
	Measured : {
		path : Str,
		line : U64,
		name : Str,
		depth : U64,
		at : U64,
	}

	## The body of the item, a function or a test of the file at `path` whose
	## lines are `lines`, measured, or the stop's words when its braces close
	## past its body or don't come back to its own depth.
	of_body : Str, List(List(U8)), Item -> Try(Depth.Measured, Str)
	of_body = |path, lines, item| {
		start = { path, line: item.first, name: item.name, depth: 1, at: item.body_first }
		if item.body_first == item.sig_last {
			return Ok(start)
		}
		$depth : I64
		var $depth = 1
		$most : I64
		var $most = 1
		var $at = item.body_first
		var $number = item.body_first
		while $number <= item.body_last {
			code = Mask.masked(lines.get($number - 1) ?? [])
			opens = code.count_if(|byte| byte == '{').to_i64_wrap()
			closes = code.count_if(|byte| byte == '}').to_i64_wrap()
			$depth = $depth + opens - closes
			if $depth > $most {
				$most = $depth
				$at = $number
			}
			if $depth < 1 {
				return Err("${path}:${$number.to_str()}: `${item.name}`'s braces close past its body")
			}
			$number = $number + 1
		}
		if $depth != 1 {
			open = ($depth - 1).to_str()
			return Err("${path}:${item.first.to_str()}: `${item.name}`'s braces don't balance: ${open} left open at its end")
		}
		Ok({ ..start, depth: $most.to_u64_wrap(), at: $at })
	}

	## The listing of the measured functions at depth `min` or past, deepest
	## first, and the summary: the functions read, how many are at `min` or
	## past, and how many at each depth; or the stop's words when there is
	## no function.
	listing : List(Depth.Measured), I64 -> Try({ summary : Str, lines : List(Str) }, Str)
	listing = |functions, min| {
		if functions.is_empty() {
			return Err("list_deep_nesting: no function to measure")
		}
		depths = functions.map(|each| each.depth)
		counts = distinct(depths)
			.sort_with(up)
			.map(|depth| "${depth.to_str()}: ${depths.count_if(|each| each == depth).to_str()}")
		deep = functions
			.keep_if(|each| each.depth.to_i64_wrap() >= min)
			.sort_with(deepest_first)
		deep_lines = deep.map(
			|each| "${each.path}:${each.line.to_str()}: ${each.name}: depth ${each.depth.to_str()} (at line ${each.at.to_str()})",
		)
		read = "${functions.len().to_str()} functions read, ${deep.len().to_str()} at depth ${min.to_str()} or past"
		Ok({ summary: "${read}; by depth, ${Str.join_with(counts, ", ")}", lines: deep_lines })
	}
}

## Each depth once, in the order first seen.
distinct : List(U64) -> List(U64)
distinct = |depths|
	depths.fold(
		[],
		|seen, depth|
			if seen.contains(depth) {
				seen
			} else {
				seen.append(depth)
			},
	)

## Two depths, the shallower first.
up : U64, U64 -> [Before, Same, After]
up = |a, b|
	if a < b {
		Before
	} else if a > b {
		After
	} else {
		Same
	}

## Deepest first, then by path and line.
deepest_first : Depth.Measured, Depth.Measured -> [Before, Same, After]
deepest_first = |a, b|
	match up(b.depth, a.depth) {
		Same =>
			match Words.byte_order(a.path, b.path) {
				Same => up(a.line, b.line)
				order => order
			}
		order => order
	}

cookbook/c/list_deep_nesting/SelfTest.roc, 68 lines

## list_deep_nesting's self-test: the recipe run over
## cookbook/c/plants/list_deep_nesting/ and held to every plant's known depth
## and line, exactly: depths 3, 4 and 5, braces in a string, a character
## literal and a comment, a braceless `if`, an initializer's braces, the
## default `min`, and `tests=1`.
import pf.Shale
import Depth

SelfTest := [].{

	## Every check, each a stop when it fails, then the PASS line. `measure!`
	## is the recipe's own, a folder's functions (and tests, when asked)
	## measured.
	run! : (Str, Bool => List(Depth.Measured)) => {}
	run! = |measure!| {
		file = "${plants}/depths.c"
		functions = measure!(plants, Bool.False)
		every_depth = [
			"${file}:52: depth_five: depth 5 (at line 57)",
			"${file}:40: depth_four: depth 4 (at line 44)",
			"${file}:28: depth_three: depth 3 (at line 31)",
			# The braces in its comment, string and character literal are none.
			"${file}:19: braces_in_text: depth 2 (at line 21)",
			"${file}:6: depth_one: depth 1 (at line 6)",
			# Its braceless `if`s and its initializer's braces are no level.
			"${file}:10: braceless: depth 1 (at line 11)",
		]
		same!("every function's depth", joined(listed!(functions, 1).lines), joined(every_depth))
		default = listed!(functions, 4)
		at_four = [
			"${file}:52: depth_five: depth 5 (at line 57)",
			"${file}:40: depth_four: depth 4 (at line 44)",
		]
		same!("the list at the default min", joined(default.lines), joined(at_four))
		same!("the summary", default.summary, "6 functions read, 2 at depth 4 or past; by depth, 1: 2, 2: 1, 3: 1, 4: 1, 5: 1")
		with_tests = listed!(measure!(plants, Bool.True), 2)
		same!("the summary with the tests", with_tests.summary, "7 functions read, 5 at depth 2 or past; by depth, 1: 2, 2: 2, 3: 1, 4: 1, 5: 1")
		fifth = with_tests.lines.get(4) ?? "<none>"
		same!("the test's depth", fifth, "${file}:69: a_nested_test: depth 2 (at line 70)")
		checks = "5 checks, every plant's depth, the default min, the summaries and a test over the plants"
		Shale.print!("PASS list_deep_nesting self-test: ${checks}")
	}
}

## Where the plants are.
plants : Str
plants = "cookbook/c/plants/list_deep_nesting"

## The listing, or the self-test stopped.
listed! : List(Depth.Measured), I64 => { summary : Str, lines : List(Str) }
listed! = |measured, min|
	match Depth.listing(measured, min) {
		Ok(listing) => listing
		Err(why) => {
			Shale.fail!(why)
			{ summary: "", lines: [] }
		}
	}

## `got` equal to `want`, or the self-test stops, naming `what`.
same! : Str, Str, Str => {}
same! = |what, got, want|
	if got != want {
		Shale.fail!("list_deep_nesting self-test: ${what} is\n${got}\nit should be\n${want}")
	}

joined : List(Str) -> Str
joined = |lines| Str.join_with(lines, "\n")

Shale original

cookbook/c/list_deep_nesting.shale, 156 lines, at dfe2eaaa

The libraries it loads: cookbook/c/items.shale (499 lines).

-- Lists Shale's C functions by how deeply their blocks nest, deepest first,
-- from cookbook/c/items.shale's splitter. The kernel's style guide calls more
-- than 3 levels of indentation a smell, so the line is depth 4 unless `min=`
-- moves it.
--
--   shale cookbook:c/list_deep_nesting.shale             over c/, depth 4 or past
--   shale cookbook:c/list_deep_nesting.shale min=5
--   shale cookbook:c/list_deep_nesting.shale dir=c/host tests=1
--   shale cookbook:c/list_deep_nesting.shale self_test=1
--
-- It ranks functions to look at, never a rule or a gate: it fails on no
-- finding and exits 0 with them. Be aware of the opposite smell too:
-- one workhorse function that does a lot is sometimes better than complexity
-- scattered around the codebase.
--
-- How depth is counted: a function's own body is depth 1, and each block a
-- `{` opens inside it is one deeper, so `if (x) {` in the body makes depth 2.
-- Each body line is read through items.shale's masker, `c_mask` (the one
-- c/check_discipline.shale judges with), so a brace in a string, a character
-- literal or a comment is no brace. The dialect ends an opening brace's line
-- with it, so a line's braces are counted net: `} else {` stays at its depth,
-- and an initializer's `{1, 2}` on one line is no level. A braceless `if (x)
-- return y;`, on one line or two, is no level either: depth is braces, not
-- indentation. A body that shares its head's line (`{ return x; }`) is depth
-- 1. A body whose braces don't come back to its own depth stops the run,
-- naming it.
--
-- One line a function at `min` or past, deepest first:
--
--   path:line: name: depth N (at line L)
--
-- L the first line that reaches it. Then the summary: the functions read, how
-- many are at `min` or past, and how many there are at each depth. `tests=1`
-- measures each `TEST(` body too; by default tests are left out of both.
--
-- `self_test=1` runs it over cookbook/c/plants/list_deep_nesting/ and holds
-- every plant to its known depth and line, exactly: depths 3, 4 and 5,
-- braces in a string, a character literal and a comment, a braceless `if`,
-- an initializer's braces, the default `min`, and `tests=1`.
--
-- budget: steps=200000000 arena_bytes=1000000000 kept_bytes=268435456

use("./items.shale")

const PLANTS = "cookbook/c/plants/list_deep_nesting"

-- The C files under `dir`, sorted, c/out (the build's output) left out.
function c_files_under(dir)
  local files = {}
  for e in walk_all(dir, {kind = "file", skip = "out"}) do
    if ends_with(e.path, ".c") or ends_with(e.path, ".h") then push(files, e.path) end
  end
  sort(files)
  return files
end

-- The deepest nesting of the body of `it`, an item of `p` whose lines are
-- `all`: `{depth, at}`, `at` the first line that reaches it.
function body_depth(p, all, it)
  if it.body_first == it.sig_last then return {depth = 1, at = it.body_first} end
  local depth = 1
  local most = 1
  local at = it.body_first
  local k = it.body_first
  while k <= it.body_last do
    local code = c_mask(all[k])
    depth = depth + #find_all(code, "{") - #find_all(code, "}")
    if depth > most then
      most = depth
      at = k
    end
    if depth < 1 then fail(p .. ":" .. k .. ": `" .. it.name .. "`'s braces close past its body") end
    k = k + 1
  end
  if depth ~= 1 then fail(p .. ":" .. it.first .. ": `" .. it.name .. "`'s braces don't balance: " .. (depth - 1) .. " left open at its end") end
  return {depth = most, at = at}
end

-- Each function's body under `dir` (and each test's, `tests`), measured:
-- `{path, line, name, depth, at}`.
function measure(dir, tests)
  local got = {}
  for p in c_files_under(dir) do
    local all = lines(read(p))
    for it in c_items(p) do
      if (it.kind == "function" or (tests and it.kind == "test")) and it.body_first ~= 0 then
        local d = body_depth(p, all, it)
        push(got, {path = p, line = it.first, name = it.name, depth = d.depth, at = d.at})
      end
    end
    yield()
  end
  return got
end

-- The listing of `measured` at `min` or past, as `{summary, lines}`.
function list_deep(measured, min)
  if #measured == 0 then fail("list_deep_nesting: no function to measure") end
  local by = {}
  local deep = {}
  for m in measured do
    incr(by, "" .. m.depth)
    if m.depth >= min then push(deep, m) end
  end
  local depths = {}
  for k in keys(by) do push(depths, parse_int(k)) end
  sort(depths)
  local parts = {}
  for d in depths do push(parts, d .. ": " .. by["" .. d]) end
  sort(deep, {{key = "depth", desc = true}, "path", "line"})
  local out = {}
  for m in deep do push(out, m.path .. ":" .. m.line .. ": " .. m.name .. ": depth " .. m.depth .. " (at line " .. m.at .. ")") end
  local summary = #measured .. " functions read, " .. #deep .. " at depth " .. min .. " or past; by depth, " .. join(parts, ", ")
  return {summary = summary, lines = out}
end

-- `got` equal to `want`, or the self-test fails, naming `what`.
function same_or_fail(what, got, want)
  if got ~= want then fail("list_deep_nesting self-test: " .. what .. " is\n" .. got .. "\nit should be\n" .. want) end
  return nil
end

function self_test()
  local P = PLANTS .. "/depths.c"
  local fns = measure(PLANTS, false)
  same_or_fail("every function's depth", join(list_deep(fns, 1).lines, "\n"), join({
    P .. ":52: depth_five: depth 5 (at line 57)",
    P .. ":40: depth_four: depth 4 (at line 44)",
    P .. ":28: depth_three: depth 3 (at line 31)",
    -- The braces in its comment, string and character literal are none.
    P .. ":19: braces_in_text: depth 2 (at line 21)",
    P .. ":6: depth_one: depth 1 (at line 6)",
    -- Its braceless `if`s and its initializer's braces are no level.
    P .. ":10: braceless: depth 1 (at line 11)"}, "\n"))
  local d = list_deep(fns, 4)
  same_or_fail("the list at the default min", join(d.lines, "\n"), join({
    P .. ":52: depth_five: depth 5 (at line 57)",
    P .. ":40: depth_four: depth 4 (at line 44)"}, "\n"))
  same_or_fail("the summary", d.summary, "6 functions read, 2 at depth 4 or past; by depth, 1: 2, 2: 1, 3: 1, 4: 1, 5: 1")
  local t = list_deep(measure(PLANTS, true), 2)
  same_or_fail("the summary with the tests", t.summary, "7 functions read, 5 at depth 2 or past; by depth, 1: 2, 2: 2, 3: 1, 4: 1, 5: 1")
  same_or_fail("the test's depth", t.lines[5], P .. ":69: a_nested_test: depth 2 (at line 70)")
  print("PASS list_deep_nesting self-test: 5 checks, every plant's depth, the default min, the summaries and a test over the plants")
  return nil
end

if arg("self_test", 0) == 1 then
  self_test()
else
  local dir = arg("dir", "c")
  local tests = arg("tests", 0) == 1
  local min = arg("min", 4)
  local r = list_deep(measure(dir, tests), min)
  for l in r.lines do print(l) end
  print("list_deep_nesting: " .. dir .. (tests and ", tests included" or ", tests left out") .. ": " .. r.summary)
end