list_long_functions

Roc

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

cookbook/c/list_long_functions/list_long_functions.roc, 133 lines

## list_long_functions, in Roc on Shale's platform (roc_platform/README.md):
## Shale's C functions past a length, longest first, from the splitter the
## C recipes share (cookbook/c/items/, a package). A function's length is
## its body's lines of code; its comment lines and blank lines are counted
## beside it, never in it. Its launcher, cookbook/c/list_long_functions.shale,
## is how it is run, and its header says the arguments and the rules.
## check_goldens.shale, beside this, holds its output on the plants to its
## goldens, line for line.
##
##   shale cookbook:c/list_long_functions.shale over=60
##   shale cookbook:c/list_long_functions.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. Length, 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 Length
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
		over = integer_or_stop!("over", Shale.arg!("over", "0"))
		limit = if over > 0 {
			Given(over.to_u64_wrap())
		} else {
			Percentile
		}
		listing = match Length.listing(measure!(folder, tests), limit) {
			Ok(listed) => listed
			Err(why) => {
				Shale.fail!(why)
				{ summary: "", threshold: 0, lines: [] }
			}
		}
		which = if tests {
			"tests included"
		} else {
			"tests left out"
		}
		Shale.print!("list_long_functions: ${folder}, ${which}: ${listing.summary}")
		for line in listing.lines {
			Shale.print!(line)
		}
		how = match limit {
			Given(_) => "over="
			Percentile => "the 95th percentile"
		}
		past = "${listing.lines.len().to_str()} functions past ${listing.threshold.to_str()} code lines"
		Shale.print!("list_long_functions: ${past} (${how})")
	}
}

## 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_long_functions: ${name}=${given} is not an integer")
			0
		}
	}

## Each function's body under the folder (and each test's, `tests`),
## measured.
measure! : Str, Bool => List(Length.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 {
				$measured = $measured.append(Length.of_body(path, lines, item))
			}
		}
	}
	$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_long_functions: ${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_long_functions/Length.roc, 120 lines

## A function's length and the listing of the long ones. A function's
## length is its body's lines of code: a blank line and a `//` line are
## counted beside it, and a body that shares its head's line
## (`{ return x; }`) is one line of code. A `#` line in a body is code.
import items.Item
import items.Mask
import items.Words

Length := [].{

	## A function's body measured: where it starts and its name, then its
	## lines of code, of comment and blank.
	Measured : {
		path : Str,
		line : U64,
		name : Str,
		code : U64,
		comment : U64,
		blank : U64,
	}

	## The body of the item, a function or a test of the file at `path`
	## whose lines are `lines`, measured.
	of_body : Str, List(List(U8)), Item -> Length.Measured
	of_body = |path, lines, item| {
		start = { path, line: item.first, name: item.name, code: 0, comment: 0, blank: 0 }
		if item.body_first == item.sig_last {
			{ ..start, code: 1 }
		} else {
			body = lines.sublist({ start: item.body_first - 1, len: item.body_last + 1 - item.body_first })
			body.fold(start, with_line)
		}
	}

	## The listing of the measured functions past the limit (`Percentile`:
	## the 95th percentile of their lengths): the distribution, the
	## threshold and a line for each function past it, longest first, or the
	## stop's words when there is no function.
	listing : List(Length.Measured), [Given(U64), Percentile] -> Try({ summary : Str, threshold : U64, lines : List(Str) }, Str)
	listing = |functions, limit| {
		lengths = functions.map(|each| each.code).sort_with(up)
		if lengths.is_empty() {
			return Err("list_long_functions: no function to measure")
		}
		at = |pct| percentile(lengths, pct).to_str()
		longest = (lengths.last() ?? 0).to_str()
		shares = "median ${at(50)}, p75 ${at(75)}, p90 ${at(90)}, p95 ${at(95)}, p99 ${at(99)}"
		summary = "${lengths.len().to_str()} functions: ${shares}, max ${longest} code lines"
		threshold = match limit {
			Given(over) => over
			Percentile => percentile(lengths, 95)
		}
		long_lines = functions
			.keep_if(|each| each.code > threshold)
			.sort_with(longest_first)
			.map(long_line)
		Ok({ summary, threshold, lines: long_lines })
	}
}

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

## The measure with one more of the body's lines counted.
with_line : Length.Measured, List(U8) -> Length.Measured
with_line = |so_far, raw| {
	trimmed = Mask.trimmed(raw)
	if trimmed.is_empty() {
		{ ..so_far, blank: so_far.blank + 1 }
	} else if trimmed.starts_with(['/', '/']) {
		{ ..so_far, comment: so_far.comment + 1 }
	} else {
		{ ..so_far, code: so_far.code + 1 }
	}
}

## The value at a percentile of the lengths, sorted up: the one at rank
## ceil(pct n / 100), counted from 1.
percentile : List(U64), U64 -> U64
percentile = |sorted, pct| {
	rank = U64.max(1, (pct * sorted.len() + 99) // 100)
	sorted.get(rank - 1) ?? 0
}

## Longest first, then by path and line.
longest_first : Length.Measured, Length.Measured -> [Before, Same, After]
longest_first = |a, b|
	if a.code > b.code {
		Before
	} else if a.code < b.code {
		After
	} else {
		match Words.byte_order(a.path, b.path) {
			Same =>
				if a.line < b.line {
					Before
				} else if a.line > b.line {
					After
				} else {
					Same
				}
			order => order
		}
	}

## A long function's line: `path:line: long: name: N code lines (C
## comment, B blank)`.
long_line : Length.Measured -> Str
long_line = |each| {
	counts = "${each.code.to_str()} code lines (${each.comment.to_str()} comment, ${each.blank.to_str()} blank)"
	"${each.path}:${each.line.to_str()}: long: ${each.name}: ${counts}"
}

cookbook/c/list_long_functions/SelfTest.roc, 61 lines

## list_long_functions' self-test: the recipe run over
## cookbook/c/plants/list_long_functions/ and held to the plants' known
## lengths, exactly: the distribution, the default threshold, an `over=` that
## a function's comments and blank lines would pass but its code does not,
## and `tests=1`.
import pf.Shale
import Length

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(Length.Measured)) => {}
	run! = |measure!| {
		file = "${plants}/lengths.c"
		functions = measure!(plants, Bool.False)
		default = listed!(functions, Percentile)
		same!("the distribution", default.summary, "4 functions: median 2, p75 4, p90 6, p95 6, p99 6, max 6 code lines")
		same!("the default threshold", default.threshold.to_str(), "6")
		same!("the list past the 95th percentile", joined(default.lines), "")
		past_three = [
			"${file}:25: long: six_lines: 6 code lines (1 comment, 0 blank)",
			"${file}:13: long: four_with_comments: 4 code lines (3 comment, 2 blank)",
		]
		same!("the list past 3", joined(listed!(functions, Given(3)).lines), joined(past_three))
		# Nine lines of body, four of them code: not past 4.
		past_four = "${file}:25: long: six_lines: 6 code lines (1 comment, 0 blank)"
		same!("the list past 4", joined(listed!(functions, Given(4)).lines), past_four)
		with_tests = listed!(measure!(plants, Bool.True), Given(6))
		past_six = "${file}:35: long: a_long_test: 8 code lines (0 comment, 0 blank)"
		same!("the list past 6 with the tests", joined(with_tests.lines), past_six)
		checks = "6 checks, the distribution, the default threshold and three lists over the plants"
		Shale.print!("PASS list_long_functions self-test: ${checks}")
	}
}

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

## The listing, or the self-test stopped.
listed! : List(Length.Measured), [Given(U64), Percentile] => { summary : Str, threshold : U64, lines : List(Str) }
listed! = |measured, limit|
	match Length.listing(measured, limit) {
		Ok(listing) => listing
		Err(why) => {
			Shale.fail!(why)
			{ summary: "", threshold: 0, 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_long_functions 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_long_functions.shale, 143 lines, at 0cd50789

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

-- Lists Shale's C functions past a length, longest first, from
-- cookbook/c/items.shale's splitter. A function's length is its body's lines
-- of code; its comment lines and blank lines are counted beside it, never in
-- it, so a well-commented function is not taken for a long one.
--
--   shale cookbook:c/list_long_functions.shale             over c/, past its 95th percentile
--   shale cookbook:c/list_long_functions.shale over=60     past 60 lines of code
--   shale cookbook:c/list_long_functions.shale dir=c/host tests=1
--   shale cookbook:c/list_long_functions.shale self_test=1
--
-- The threshold, unless `over=` sets one, is the 95th percentile of the
-- functions' code lines (the length at rank ceil(0.95 n) of n, sorted), so
-- the run lists the longest twentieth, about. The first line is the
-- distribution: how many functions, and the median, 75th, 90th, 95th and
-- 99th percentiles and the longest. Then one line a function past it:
--
--   path:line: long: name: N code lines (C comment, B blank)
--
-- `tests=1` counts each `TEST(` body as a function too; by default a test is
-- left out of both the distribution and the list, since a test's length is
-- its setup's. `main` is a function like any other. A body that shares its
-- head's line (`{ return x; }`) is one line of code. A `#` line in a body
-- is code.
--
-- `self_test=1` runs it over cookbook/c/plants/list_long_functions/ and holds
-- the distribution and the lists to the plants' known lengths, exactly: the
-- default threshold, an `over=` that a function's comments and blank lines
-- would pass but its code does not, and `tests=1`.
--
-- budget: steps=200000000 arena_bytes=1000000000 kept_bytes=268435456

use("./items.shale")

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

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

-- Each function's body under `dir` (and each test's, `tests`), measured:
-- `{path, line, name, code, comment, blank}`.
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 m = {path = p, line = it.first, name = it.name, code = 0, comment = 0, blank = 0}
        if it.body_first == it.sig_last then
          m.code = 1
        else
          local k = it.body_first
          while k <= it.body_last do
            local t = trim(all[k])
            if t == "" then
              m.blank = m.blank + 1
            elseif starts_with(t, "//") then
              m.comment = m.comment + 1
            else
              m.code = m.code + 1
            end
            k = k + 1
          end
        end
        push(got, m)
      end
    end
    yield()
  end
  return got
end

-- The value at percentile `pct` of `sorted`, ascending: rank ceil(pct n / 100).
function percentile(sorted, pct)
  local rank = (pct * #sorted + 99) // 100
  if rank < 1 then rank = 1 end
  return sorted[rank]
end

-- The listing of `measured` past `over` (nil: the 95th percentile), as
-- `{summary, threshold, lines}`.
function list_long(measured, over)
  local lens = {}
  for m in measured do push(lens, m.code) end
  sort(lens)
  if #lens == 0 then fail("list_long_functions: no function to measure") end
  local summary = #lens .. " functions: median " .. percentile(lens, 50) .. ", p75 " .. percentile(lens, 75) .. ", p90 " .. percentile(lens, 90) .. ", p95 " .. percentile(lens, 95) .. ", p99 " .. percentile(lens, 99) .. ", max " .. lens[#lens] .. " code lines"
  local threshold = over
  if threshold == nil then threshold = percentile(lens, 95) end
  local long = {}
  for m in measured do
    if m.code > threshold then push(long, m) end
  end
  sort(long, {{key = "code", desc = true}, "path", "line"})
  local out = {}
  for m in long do push(out, m.path .. ":" .. m.line .. ": long: " .. m.name .. ": " .. m.code .. " code lines (" .. m.comment .. " comment, " .. m.blank .. " blank)") end
  return {summary = summary, threshold = threshold, 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_long_functions self-test: " .. what .. " is\n" .. got .. "\nit should be\n" .. want) end
  return nil
end

function self_test()
  local P = PLANTS .. "/lengths.c"
  local fns = measure(PLANTS, false)
  local d = list_long(fns, nil)
  same_or_fail("the distribution", d.summary, "4 functions: median 2, p75 4, p90 6, p95 6, p99 6, max 6 code lines")
  same_or_fail("the default threshold", "" .. d.threshold, "6")
  same_or_fail("the list past the 95th percentile", join(d.lines, "\n"), "")
  same_or_fail("the list past 3", join(list_long(fns, 3).lines, "\n"), join({
    P .. ":25: long: six_lines: 6 code lines (1 comment, 0 blank)",
    P .. ":13: long: four_with_comments: 4 code lines (3 comment, 2 blank)"}, "\n"))
  -- Nine lines of body, four of them code: not past 4.
  same_or_fail("the list past 4", join(list_long(fns, 4).lines, "\n"), P .. ":25: long: six_lines: 6 code lines (1 comment, 0 blank)")
  same_or_fail("the list past 6 with the tests", join(list_long(measure(PLANTS, true), 6).lines, "\n"), P .. ":35: long: a_long_test: 8 code lines (0 comment, 0 blank)")
  print("PASS list_long_functions self-test: 6 checks, the distribution, the default threshold and three lists 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 over = arg("over", 0)
  local given = nil
  if over > 0 then given = over end
  local r = list_long(measure(dir, tests), given)
  print("list_long_functions: " .. dir .. (tests and ", tests included" or ", tests left out") .. ": " .. r.summary)
  for l in r.lines do print(l) end
  local how = "the 95th percentile"
  if given ~= nil then how = "over=" end
  print("list_long_functions: " .. #r.lines .. " functions past " .. r.threshold .. " code lines (" .. how .. ")")
end