find_functions_and_parameters_that_dont_earn_their_keep
Roc
It also imports Bytes, Finding, Forest, Headers, RocTypes, Text, Tree from the shared Roc library.
## find_functions_and_parameters_that_dont_earn_their_keep, in Roc on Shale's platform (roc_platform/README.md):
## whether each function's boundary earns its keep, and whether each of its
## parameters is really a parameter. Its launcher,
## cookbook/roc/find_functions_and_parameters_that_dont_earn_their_keep.shale, is how it is run, and its header says
## the checks (`single`, `fixed`, `entry`, `constant`, `dead`, `unused_api`,
## `same_branches`, and `bool_param` under the types) and the arguments.
## check_goldens.shale, beside this, holds its output to its goldens, line
## for line.
##
## cd <repo> && shale cookbook:roc/find_functions_and_parameters_that_dont_earn_their_keep.shale glob='app/**/*.roc'
## shale cookbook:roc/find_functions_and_parameters_that_dont_earn_their_keep.shale self_test=1
##
## This root reads the arguments (`Shale.arg!`), globs the files
## (`Shale.glob!`), gathers the types (Types, through `Shale.run!`), has Roc's
## parser read the files (`Shale.roc_tree!`) and each package's main.roc
## (`Shale.read!`), and prints the verdict (`Shale.print!`, `Shale.fail!`).
## Its modules are beside it: the functions (Functions), what reaches them
## (References), the source texts compared (Source), the checks (Checks),
## Types and SelfTest; Forest, Tree, Text, Headers, Bytes, Finding and RocTypes
## are the cookbook's Roc library, cookbook/roc/lib/.
## budget: steps=400000000 arena_bytes=3000000000 output_bytes=8000000 programs=100 roc_cpu_ms=60000
app [main!] { lib: "../lib/main.roc", pf: platform "../../../roc_platform/platform/main.roc" }
import pf.Shale
import Checks
import lib.Finding
import lib.Forest
import Functions
import lib.Headers
import References
import lib.RocTypes
import SelfTest
import lib.Text
import lib.Tree
import Types
main! : {} => {}
main! = |{}| {
asked = read_asked!({})
client_files = globbed!(asked.clients)
client_set = Set.from_list(globbed!(asked.clients))
checked_files = globbed!(asked.glob).drop_if(|path| client_set.contains(path))
checked = Set.from_list(checked_files)
test_paths = Set.from_list(globbed!(asked.tests))
types = if asked.use_types {
roc = Types.roc_bin!("find_functions_and_parameters_that_dont_earn_their_keep", asked.self_test)
exempt = if asked.self_test {
Set.from_list(checked_files.drop_if(|path| path.starts_with(SelfTest.typed_plants)))
} else {
Set.empty()
}
Types.gather!({ who: "find_functions_and_parameters_that_dont_earn_their_keep", kind: Patterns, root: asked.root, roc, paths: checked_files, exempt })
} else {
{ typing: RocTypes.no_types, unreached: [] }
}
read = read_files!(checked_files.concat(client_files))
forest = Forest.join(read.parsed)
ancestry = Functions.ancestry(forest)
limits = { ways: asked.ways, nodes: asked.nodes }
defined = Functions.read(forest, ancestry, { checked, lines_of: read.lines_of, limits })
tallies = References.tally(forest, ancestry, defined, test_paths)
clients_read = if client_files.is_empty() {
""
} else {
" and ${client_files.len().to_str()} clients"
}
judging = {
forest,
lines_of: read.lines_of,
defined,
tallies,
checked,
headers: read.headers,
exposed_modules: exposed_modules!(checked_files),
typing: types.typing,
files_read: " in the ${checked_files.len().to_str()} files read${clients_read}",
is_dead_by_production: asked.is_dead_by_production,
}
is_house_off = read_house_is_off!({})
is_reported = |finding| {
is_house = is_house_off and finding.check == "single"
is_unjudged_plant = asked.self_test and (finding.check == "dead" or finding.check == "unused_api") and !(finding.path.starts_with(SelfTest.dead_plants))
!(is_house) and !(is_unjudged_plant)
}
findings = Checks.judge(judging).keep_if(is_reported)
for finding in findings {
Shale.print!(Finding.line_of(finding))
}
house_note = if is_house_off {
"; left out as house style: single"
} else {
""
}
files_said = "${checked_files.len().to_str()} files${clients_read}, ${defined.by_key.len().to_str()} functions"
Shale.print!("find_functions_and_parameters_that_dont_earn_their_keep (Roc): ${files_said}; ${Finding.counts_of(findings, checks)}${house_note}")
fail_if_refused!(read.refused, types.unreached)
if asked.self_test {
SelfTest.run!({ paths: checked_files, clients: client_files, test_count: test_paths.len(), findings }, checks)
}
}
## The checks, in the order the summary counts them.
checks : List(Str)
checks = ["single", "fixed", "entry", "constant", "bool_param", "dead", "unused_api", "same_branches"]
## The arguments, read and refused in the Shale original's order. The
## self-test reads every plant, those under `dead/clients/` as clients and
## those under `dead/gates/` as tests, with the types under
## `typed/QuietApp.roc` and `test_reach=dead`.
read_asked! : {} => {
self_test : Bool,
glob : Str,
ways : I64,
nodes : I64,
use_types : Bool,
root : Str,
clients : Str,
tests : Str,
is_dead_by_production : Bool,
}
read_asked! = |{}| {
self_test = Shale.arg!("self_test", "") == "1"
plants = SelfTest.plants
glob_asked = Shale.arg!("glob", "**/*.roc")
ways = integer_of!("ways", Shale.arg!("ways", "2"))
nodes = integer_of!("nodes", Shale.arg!("nodes", "24"))
types_asked = Shale.arg!("types", "0")
if types_asked != "0" and types_asked != "1" {
Shale.fail!("find_functions_and_parameters_that_dont_earn_their_keep: types must be 0 (the default) or 1, not ${types_asked}")
}
root_asked = Shale.arg!("root", "")
clients_asked = Shale.arg!("clients", "")
tests_asked = Shale.arg!("tests", "")
reach = Shale.arg!("test_reach", "keeps")
if reach != "keeps" and reach != "dead" {
Shale.fail!("find_functions_and_parameters_that_dont_earn_their_keep: test_reach must be keeps (the default) or dead, not ${reach}")
}
if self_test {
{
self_test,
glob: "${plants}**/*.roc",
ways,
nodes,
use_types: Bool.True,
root: "${SelfTest.typed_plants}QuietApp.roc",
clients: "${SelfTest.dead_plants}clients/*.roc",
tests: "${SelfTest.dead_plants}gates/*.roc",
is_dead_by_production: Bool.True,
}
} else {
{
self_test,
glob: glob_asked,
ways,
nodes,
use_types: types_asked == "1",
root: root_asked,
clients: clients_asked,
tests: tests_asked,
is_dead_by_production: reach == "dead",
}
}
}
## The argument `name`, given as `given`, read as an integer, as Shale's
## `arg` reads one whose default is an integer. Each is read by its own
## `Shale.arg!`, which the launcher finds by name.
integer_of! : Str, Str => I64
integer_of! = |name, given|
match I64.from_str(given) {
Ok(number) => number
Err(_) => {
Shale.fail!("`arg`: ${name}=${given} is not an integer, and its default is one")
0
}
}
## Whether `house=0` leaves the house style, `single`, out
## (cookbook/roc/house.shale).
read_house_is_off! : {} => Bool
read_house_is_off! = |{}| {
house = integer_of!("house", Shale.arg!("house", "1"))
if house != 0 and house != 1 {
Shale.fail!("house must be 1 (the default) or 0, not ${house.to_str()}")
}
house == 0
}
## The files the globs match, a list separated by commas, each file as
## often as a glob matches it.
globbed! : Str => List(Str)
globbed! = |globs| {
var $paths = []
for named in globs.split_on(",") {
pattern = Text.trim(named)
if pattern != "" {
$paths = $paths.concat(Shale.glob!(pattern))
}
}
$paths
}
## The files Roc's parser reads, with each file's lines and header names,
## and a `path: reason` line for each it refuses.
read_files! : List(Str) => {
parsed : List({ path : Str, nodes : List(Tree.Node) }),
lines_of : Dict(Str, List(Str)),
headers : Dict(Str, { dictated : Set(Str), exposed : Set(Str) }),
refused : List(Str),
}
read_files! = |paths| {
var $parsed = []
var $lines_of = Dict.empty()
var $headers = Dict.empty()
var $refused = []
for file in Shale.roc_tree!(paths) {
if file.err == "" {
text = match Shale.read!(file.path) {
Found(found) => found
Missing => {
Shale.fail!("find_functions_and_parameters_that_dont_earn_their_keep: ${file.path} went missing while it was read")
""
}
}
names = Headers.header_names(file.nodes)
$parsed = $parsed.append({ path: file.path, nodes: file.nodes })
$lines_of = $lines_of.insert(file.path, text.split_on("\n"))
$headers = $headers.insert(file.path, { dictated: Set.from_list(names.dictated), exposed: Set.from_list(names.exposed) })
} else if file.err.starts_with(file.path) {
$refused = $refused.append(file.err)
} else {
$refused = $refused.append("${file.path}: ${file.err}")
}
}
{ parsed: $parsed, lines_of: $lines_of, headers: $headers, refused: $refused }
}
## The modules each checked file's folder's main.roc exposes, when it is a
## package's or a platform's (cookbook/roc/lib/'s `Headers.exposed_by`), by
## folder.
exposed_modules! : List(Str) => Dict(Str, List(Str))
exposed_modules! = |paths| {
var $by_folder = Dict.empty()
for path in paths {
folder = Text.dirname(path)
if !($by_folder.contains(folder)) {
main = if folder == "" or folder == "." {
"main.roc"
} else {
"${folder}/main.roc"
}
exposed = match Shale.read!(main) {
Found(text) => Headers.exposed_by(text).modules
Missing => []
}
$by_folder = $by_folder.insert(folder, exposed)
}
}
$by_folder
}
## After the summary: the files that didn't parse, and those no root of the
## types reaches (judged without them), named, then a stop
## (cookbook/roc/parsed.shale's `fail_if_refused`).
fail_if_refused! : List(Str), List(Str) => {}
fail_if_refused! = |refused, unreached| {
if !(refused.is_empty()) or !(unreached.is_empty()) {
for refusal in refused {
Shale.print!("refused: ${refusal}")
}
for missed in unreached {
Shale.print!(missed)
}
var $why = []
if !(refused.is_empty()) {
$why = $why.append("roc-ast refused ${refused.len().to_str()} files (named above), which have no tree to judge")
}
if !(unreached.is_empty()) {
$why = $why.append("${unreached.len().to_str()} files (named above) are reached by no root of the types, so were judged without them")
}
Shale.fail!("find_functions_and_parameters_that_dont_earn_their_keep: ${Str.join_with($why, "; ")}; every other file was judged")
}
}
cookbook/roc/find_functions_and_parameters_that_dont_earn_their_keep/Checks.roc, 264 lines
## The checks of find_functions_and_parameters_that_dont_earn_their_keep, each function judged in the order of its
## key, then each `if`: `dead` or `unused_api`, `single`, `fixed` or
## `entry`, `constant`, `bool_param` and `same_branches`. The launcher's
## header says each rule.
import lib.Finding
import lib.Forest
import lib.Headers
import lib.RocTypes
import lib.Text
import lib.Tree
import Functions
import References
import Source
Checks := [].{
## What the checks read: the forest and each file's lines; the
## functions and their tallies; the checked files; each file's header
## names; the modules each folder's main.roc exposes; the types; the
## words that end a finding's count of the files read; and whether only a
## production call keeps a member out of `dead`.
Judging : {
forest : Forest,
lines_of : Dict(Str, List(Str)),
defined : Functions.Defined,
tallies : List(References.Tally),
checked : Set(Str),
headers : Dict(Str, { dictated : Set(Str), exposed : Set(Str) }),
exposed_modules : Dict(Str, List(Str)),
typing : RocTypes.Typing,
files_read : Str,
is_dead_by_production : Bool,
}
## Every finding, in the order the Shale original reported them.
judge : Checks.Judging -> List(Finding)
judge = |judging| {
defined = judging.defined
order = |first, second| Text.byte_order(Functions.at(defined, first).key, Functions.at(defined, second).key)
var $places = []
$index : U64
var $index = 0
for _ in defined.functions {
$places = $places.append($index)
$index = $index + 1
}
var $findings = []
for place in $places.sort_with(order) {
function = Functions.at(defined, place)
counted = judging.tallies.get(place) ?? crash "find_functions_and_parameters_that_dont_earn_their_keep: a function with no tally"
$findings = $findings.concat(judge_function(judging, function, counted))
}
$findings.concat(same_branches(judging))
}
}
## A function and what reaches it.
Judged : { function : Functions.Function, counted : References.Tally }
judge_function : Checks.Judging, Functions.Function, References.Tally -> List(Finding)
judge_function = |judging, function, counted| {
judged = { function, counted }
is_test = References.is_test_file(function.path)
is_judged = !(counted.is_ambiguous) and !(is_test)
at = |check, what| { path: function.path, line: function.line, check, what }
name = display_name(function)
read = judging.files_read
var $findings = []
if !(is_test) and has_no_caller(judging, judged) and !(is_called_from_outside(judging, function)) {
$findings = $findings.append(
if is_library_api(judging, function) {
at("unused_api", "`${name}` is exposed, and nothing${read} calls or tests it: API with no user here, or left behind?")
} else if counted.expect_refs + counted.test_refs > 0 {
at("dead", "`${name}` has no production caller${read}, only an expect or a test: delete it with its tests, or say who calls it")
} else {
at("dead", "`${name}` has no caller${read}, and no expect or test reaches it: delete it, or say who calls it")
},
)
}
if is_judged and reads_better_inline(judged) {
said = "`${name}` (${function.size}) has one caller${read}, ${counted.first_prod_caller}, and no expect, test or doc"
$findings = $findings.append(at("single", "${said}: read it inline there, or say why it stands alone"))
}
if is_judged and counted.prod_calls.len() >= 2 and counted.value_refs == 0 {
$findings = $findings.concat(fixed_slots(judging, judged))
}
if function.takes_empty_record_alone and !(function.name.contains("!")) and !(is_test) and function.doc_lines == 0 {
effect = "a constant (`${function.name} = ...`), or a `!` if it has an effect"
$findings = $findings.append(at("constant", "`${name}` takes `{}` alone and names no effect, so it gives the same value every call: ${effect}"))
}
if is_judged and function.params.len() > 1 and judging.typing.real.contains(function.path) {
$findings = $findings.concat(bool_params(judging, judged))
}
$findings
}
## The slots the production calls agree on with a literal: `fixed` if the
## function's own calls agree with them too, `entry` if they vary it.
fixed_slots : Checks.Judging, Judged -> List(Finding)
fixed_slots = |judging, judged| {
function = judged.function
counted = judged.counted
outside = Source.agreed(judging.lines_of, judging.forest, counted.prod_calls)
every = Source.agreed(judging.lines_of, judging.forest, counted.prod_calls.concat(counted.self_calls))
own = if counted.self_calls.is_empty() {
""
} else {
" and ${counted.self_calls.len().to_str()} of its own"
}
name = display_name(function)
read = judging.files_read
at = |check, what| { path: function.path, line: function.line, check, what }
var $findings = []
for slot in Text.sort_bytewise(outside.keys()) {
match outside.get(slot) {
Ok(Agreed(text)) if Source.is_literal(text) => {
said = "`${name}`'s argument ${slot} is `${text}` in all ${counted.prod_calls.len().to_str()} production calls"
match every.get(slot) {
Ok(Agreed(_)) =>
if !(is_library_api(judging, function)) {
$findings = $findings.append(at("fixed", "${said}${own}${read}: no parameter, or an entry function that takes only what varies"))
}
_ => {
varies = "its own calls vary it: an entry function that takes only what varies and passes `${text}` itself, its one outside call"
$findings = $findings.append(at("entry", "${said}${read}, and ${varies}"))
}
}
}
_ => {}
}
}
$findings
}
## Each `Bool` parameter, by the checker's type, that some call passes a
## literal: every call counts, a test's and the function's own too.
bool_params : Checks.Judging, Judged -> List(Finding)
bool_params = |judging, judged| {
function = judged.function
counted = judged.counted
every = counted.prod_calls.concat(counted.self_calls).concat(counted.test_calls)
var $findings = []
$number : U64
var $number = 0
for param in function.params {
$number = $number + 1
node = Forest.node(judging.forest, param)
is_bool = node.kind == "p-ident" and RocTypes.type_at(judging.typing, function.path, node) == Ok("Bool")
if is_bool {
var $literal_calls = []
for call in every {
text = Source.argument_texts(judging.lines_of, judging.forest, call).get($number.to_str()) ?? ""
if bool_literals.contains(text) {
$literal_calls = $literal_calls.append("${call.path}:${call.line.to_str()} `${text}`")
}
}
if !($literal_calls.is_empty()) {
more = if $literal_calls.len() > 3 {
", ..."
} else {
""
}
shown = "${Str.join_with($literal_calls.take_first(3), ", ")}${more}"
counts = "at ${$literal_calls.len().to_str()} of its ${every.len().to_str()} calls (${shown})"
param_said = "`${display_name(function)}`'s parameter ${$number.to_str()}, `${Tree.attribute(node, "raw")}`"
tag = "a flag a caller passes is a tag, named for what it means (roc-apps docs/roc-style.md)"
what = "${param_said}, is a `Bool` (the checker's type) passed as a literal ${counts}: ${tag}"
$findings = $findings.append({ path: function.path, line: function.line, check: "bool_param", what })
}
}
}
$findings
}
## Each `if` in a checked file but a test whose two branches are the same
## text, braces aside.
same_branches : Checks.Judging -> List(Finding)
same_branches = |judging| {
forest = judging.forest
var $findings = []
$at : U64
var $at = 1
while $at <= Forest.count(forest) {
path = Forest.path(forest, $at)
is_judged = !(References.is_test_file(path)) and judging.checked.contains(path)
if Forest.kind(forest, $at) == "e-if-then-else" and is_judged and Forest.kids(forest, $at).len() == 3 {
shown = Source.branch_text(judging.lines_of, forest, Forest.kid(forest, $at, 2))
if shown != "?" and shown == Source.branch_text(judging.lines_of, forest, Forest.kid(forest, $at, 3)) {
cut = Str.from_utf8_lossy(shown.to_utf8().take_first(40))
what = "both branches of this `if` are `${cut}`: the condition decides nothing"
$findings = $findings.append({ path, line: Forest.node(forest, $at).line, check: "same_branches", what })
}
}
$at = $at + 1
}
$findings
}
## The pinned Roc defines `Bool := [False, True]`.
bool_literals : Set(Str)
bool_literals = Set.from_list(["Bool.True", "Bool.False", "True", "False"])
display_name : Functions.Function -> Str
display_name = |function|
if function.owner.starts_with("@") {
function.name
} else {
"${function.owner}.${function.name}"
}
## A function that would read better inline at its one production call: a
## small wrapper with no other reference, no doc, no recursion and not a
## question.
reads_better_inline : Judged -> Bool
reads_better_inline = |judged| {
counted = judged.counted
function = judged.function
is_question = function.name.starts_with("is_") or function.name.starts_with("has_")
is_alone = counted.prod_refs == 1 and counted.value_refs == 0 and counted.expect_refs == 0 and counted.test_refs == 0
is_alone and function.doc_lines == 0 and function.is_wrapper and !(counted.is_recursive) and !(counted.is_entry) and !(is_question)
}
## Whether a function is part of a library's API: a name its own `module`
## header exposes, or a module type's member in a file under a `lib/`
## folder or in a module its package or platform exposes.
is_library_api : Checks.Judging, Functions.Function -> Bool
is_library_api = |judging, function| {
path = function.path
header = judging.headers.get(path) ?? { dictated: Set.empty(), exposed: Set.empty() }
if header.exposed.contains(function.name) {
Bool.True
} else if function.owner.starts_with("@") {
Bool.False
} else if path.starts_with("lib/") or path.contains("/lib/") or path.contains(":lib/") {
Bool.True
} else {
(judging.exposed_modules.get(Text.dirname(path)) ?? []).contains(Tree.module_name(path))
}
}
## A function something outside the files calls: what its header dictates,
## or a member Roc calls by name.
is_called_from_outside : Checks.Judging, Functions.Function -> Bool
is_called_from_outside = |judging, function|
if function.owner.starts_with("@") {
header = judging.headers.get(function.path) ?? { dictated: Set.empty(), exposed: Set.empty() }
header.dictated.contains(function.name)
} else {
Headers.language_fixed_names.contains(function.name)
}
## Whether nothing reaches a function. A test of a library's API is a user
## of it, so `unused_api` keeps it.
has_no_caller : Checks.Judging, Judged -> Bool
has_no_caller = |judging, judged| {
counted = judged.counted
is_member = !(judged.function.owner.starts_with("@"))
unreached = counted.prod_refs == 0 and !(counted.is_mentioned)
if judging.is_dead_by_production and is_member and !(is_library_api(judging, judged.function)) {
unreached
} else {
unreached and counted.expect_refs == 0 and counted.test_refs == 0
}
}
cookbook/roc/find_functions_and_parameters_that_dont_earn_their_keep/Functions.roc, 325 lines
## The first pass of find_functions_and_parameters_that_dont_earn_their_keep: what each node's ancestors say, and
## each function defined at a file's top level or as a module type's member,
## with what the checks read of its body, its `##` doc and its parameters.
import lib.Forest
import lib.Text
Functions := [].{
## What each node's ancestors say, by place counted from 1: `top`, every
## ancestor is a file, its statements, a module type or its block of
## members; `owner`, the name of the nearest module type around it, or
## `""`; `enclosing`, the name of the outermost declaration around it, or
## `?`; `in_expect`, it is inside an `expect`.
Ancestry : {
top : List(Bool),
owner : List(Str),
enclosing : List(Str),
in_expect : List(Bool),
}
## A function: its key is `owner|name`, the owner its module type's name
## or `@path` for a file's own; `line` and `end_line` its definition's;
## whether its body is small enough for `single` to call it a wrapper, and
## its size in words; the `##` lines above it; whether it takes `{}`
## alone; and its parameter patterns' places.
Function : {
key : Str,
path : Str,
owner : Str,
name : Str,
line : U64,
end_line : U64,
is_wrapper : Bool,
size : Str,
doc_lines : U64,
takes_empty_record_alone : Bool,
params : List(U64),
}
## The functions found, each key's place among them, and the keys of the
## module types' members by name, a key listed again when its name is
## declared again.
Defined : {
functions : List(Functions.Function),
by_key : Dict(Str, U64),
member_keys : Dict(Str, List(Str)),
}
## The most ways and nodes in a body `single` still calls a wrapper.
Limits : { ways : I64, nodes : I64 }
## Each node's ancestry, worked out from its parent's, which comes
## before it in the forest.
ancestry : Forest -> Functions.Ancestry
ancestry = |forest| {
var $top = []
var $owner = []
var $enclosing = []
var $in_expect = []
$at : U64
var $at = 1
while $at <= Forest.count(forest) {
above = Forest.parent(forest, $at)
if above == 0 {
$top = $top.append(Bool.True)
$owner = $owner.append("")
$enclosing = $enclosing.append("?")
$in_expect = $in_expect.append(Bool.False)
} else {
kind = Forest.kind(forest, above)
is_top = Functions.flag_at($top, above) and top_level_kinds.contains(kind)
$top = $top.append(is_top)
owner = if kind == "s-type-decl" {
type_decl_name(forest, above)
} else {
Functions.text_at($owner, above)
}
$owner = $owner.append(owner)
enclosing = enclosing_name(forest, above, Functions.text_at($enclosing, above))
$enclosing = $enclosing.append(enclosing)
in_expect = Functions.flag_at($in_expect, above) or kind == "s-expect"
$in_expect = $in_expect.append(in_expect)
}
$at = $at + 1
}
{ top: $top, owner: $owner, enclosing: $enclosing, in_expect: $in_expect }
}
## The functions declared in the checked files, `lines_of` each file's
## lines. A key declared twice keeps its last declaration.
read : Forest, Functions.Ancestry, { checked : Set(Str), lines_of : Dict(Str, List(Str)), limits : Functions.Limits } -> Functions.Defined
read = |forest, ancestors, given| {
var $functions = []
var $by_key = Dict.empty()
var $member_keys = Dict.empty()
$at : U64
var $at = 1
while $at <= Forest.count(forest) {
name_at = Forest.kid(forest, $at, 1)
lambda = Forest.kid(forest, $at, 2)
path = Forest.path(forest, $at)
is_declared = Forest.kind(forest, $at) == "s-decl" and lambda != 0
is_function = is_declared and Forest.kind(forest, name_at) == "p-ident" and Forest.kind(forest, lambda) == "e-lambda"
if is_function and Functions.flag_at(ancestors.top, $at) and given.checked.contains(path) {
owned_by = Functions.text_at(ancestors.owner, $at)
owner = if owned_by != "" {
owned_by
} else {
"@${path}"
}
node = Forest.node(forest, $at)
name = Forest.raw(forest, name_at)
key = "${owner}|${name}"
body = body_measure(forest, lambda, given.limits)
function = {
key,
path,
owner,
name,
line: node.line,
end_line: node.end_line,
is_wrapper: body.is_wrapper,
size: body.size,
doc_lines: doc_comment_lines(given.lines_of.get(path) ?? [], name, node.line),
takes_empty_record_alone: takes_empty_record_alone(forest, $at, name),
params: lambda_params(forest, lambda),
}
match $by_key.get(key) {
Ok(index) => {
$functions = $functions.set(index, function) ?? crash "find_functions_and_parameters_that_dont_earn_their_keep: a key past the functions"
}
Err(_) => {
$by_key = $by_key.insert(key, $functions.len())
$functions = $functions.append(function)
}
}
if !(owner.starts_with("@")) {
keys = $member_keys.get(name) ?? []
$member_keys = $member_keys.insert(name, keys.append(key))
}
}
$at = $at + 1
}
{ functions: $functions, by_key: $by_key, member_keys: $member_keys }
}
## The function at a place among them.
at : Functions.Defined, U64 -> Functions.Function
at = |defined, index| defined.functions.get(index) ?? crash "find_functions_and_parameters_that_dont_earn_their_keep: no function ${index.to_str()}"
## A node's flag, by its place counted from 1.
flag_at : List(Bool), U64 -> Bool
flag_at = |flags, place| flags.get(place - 1) ?? Bool.False
## A node's text, by its place counted from 1.
text_at : List(Str), U64 -> Str
text_at = |texts, place| texts.get(place - 1) ?? ""
}
## The kinds of node that can hold a top-level function: a file, its
## statements, a module type's declaration, and the block of its members.
top_level_kinds : Set(Str)
top_level_kinds = Set.from_list(["file", "statements", "s-type-decl", "associated"])
## The name in the header of the module type declared at `at`.
type_decl_name : Forest, U64 -> Str
type_decl_name = |forest, at| {
header = Forest.kid(forest, at, 1)
if header == 0 {
""
} else {
Forest.name(forest, header)
}
}
## The outermost declaration's name below the node at `above`, whose own is
## `was`: a declaration of a plain name is the first to give one.
enclosing_name : Forest, U64, Str -> Str
enclosing_name = |forest, above, was| {
pattern = Forest.kid(forest, above, 1)
is_named = pattern != 0 and Forest.kind(forest, pattern) == "p-ident"
if was == "?" and Forest.kind(forest, above) == "s-decl" and is_named {
Forest.raw(forest, pattern)
} else {
was
}
}
## How many `##` lines stand just above the function defined at `line`, or
## above its annotation (`name : ...`, on one line or several) if it has one.
doc_comment_lines : List(Str), Str, U64 -> U64
doc_comment_lines = |source_lines, name, line| {
trimmed_at = |number| Text.trim(source_lines.get(number - 1) ?? "")
$top : U64
var $top = line - 1
$up : U64
var $up = $top
while $up >= 1 and $up + 12 > line and trimmed_at($up) != "" and !(trimmed_at($up).starts_with("#")) {
if trimmed_at($up).starts_with("${name} :") {
$top = $up - 1
}
$up = $up - 1
}
$count : U64
var $count = 0
while $top >= 1 and trimmed_at($top).starts_with("##") {
$count = $count + 1
$top = $top - 1
}
$count
}
## Whether the body of the lambda at `lambda` is small enough for `single` to
## call it a wrapper, and its size in words for the finding. A wrapper's body
## is one statement: a block of one, or an expression. Its size counts
## syntax-tree nodes, so the layout of its lines changes nothing. It has one
## way through, and one more for each `if` and each `match` arm past the
## first, so only a two-way choice reads as a wrapper.
body_measure : Forest, U64, Functions.Limits -> { is_wrapper : Bool, size : Str }
body_measure = |forest, lambda, limits| {
outer = Forest.kids(forest, lambda).last() ?? crash "find_functions_and_parameters_that_dont_earn_their_keep: a lambda with no body"
var $body = outer
if Forest.kind(forest, outer) == "e-block" {
var $statements = []
for kid in Forest.kids(forest, outer) {
if Forest.kind(forest, kid) == "statements" {
$statements = Forest.kids(forest, kid)
}
}
if $statements.len() != 1 {
return { is_wrapper: Bool.False, size: "${$statements.len().to_str()} statements" }
}
$body = $statements.first() ?? outer
}
last = Forest.last_descendant(forest, $body)
$ways : I64
var $ways = 1
$place : U64
var $place = $body
while $place <= last {
kind = Forest.kind(forest, $place)
if kind == "e-if-then-else" {
$ways = $ways + 1
}
if kind == "branches" {
$ways = $ways + Forest.kids(forest, $place).len().to_i64_wrap() - 1
}
$place = $place + 1
}
count = (last - $body + 1).to_i64_wrap()
is_small = count <= limits.nodes
if $ways > 1 {
{ is_wrapper: is_small and $ways <= limits.ways, size: "a decision of ${$ways.to_str()} ways, ${count.to_str()} nodes" }
} else {
{ is_wrapper: is_small, size: "one expression of ${count.to_str()} nodes" }
}
}
## Whether the subtree at `at` holds a node of `kind`.
holds_kind : Forest, U64, Str -> Bool
holds_kind = |forest, at, kind| {
last = Forest.last_descendant(forest, at)
var $place = at
while $place <= last {
if Forest.kind(forest, $place) == kind {
return Bool.True
}
$place = $place + 1
}
Bool.False
}
## The function type of the annotation just before the declaration at
## `decl`, when that annotation is for `name`, or 0.
annotation_function_type : Forest, U64, Str -> U64
annotation_function_type = |forest, decl, name| {
above = Forest.parent(forest, decl)
if above == 0 {
return 0
}
siblings = Forest.kids(forest, above)
before = match siblings.find_first_index(|kid| kid == decl) {
Ok(index) if index > 0 => siblings.get(index - 1) ?? 0
_ => 0
}
if before == 0 or Forest.kind(forest, before) != "s-type-anno" or Forest.name(forest, before) != name {
0
} else {
signature = Forest.kid(forest, before, 1)
if signature != 0 and Forest.kind(forest, signature) == "ty-fn" {
signature
} else {
0
}
}
}
## Whether the function declared at `decl` takes `{}` alone, by its lambda's
## one pattern or its annotation's one argument, and could be a constant: an
## annotated return type holding a type variable rules that out.
takes_empty_record_alone : Forest, U64, Str -> Bool
takes_empty_record_alone = |forest, decl, name| {
lambda = Forest.kid(forest, decl, 2)
is_empty_record = |at, kind| at != 0 and Forest.kind(forest, at) == kind and Forest.kids(forest, at).is_empty()
by_pattern = Forest.kids(forest, lambda).any(
|kid| Forest.kind(forest, kid) == "args" and Forest.kids(forest, kid).len() == 1 and is_empty_record(Forest.kid(forest, kid, 1), "p-record"),
)
fn_type = annotation_function_type(forest, decl, name)
if fn_type == 0 {
by_pattern
} else {
parts = Forest.kids(forest, fn_type)
by_type = parts.len() == 2 and is_empty_record(parts.first() ?? 0, "ty-record")
result = parts.last() ?? 0
(by_pattern or by_type) and (result == 0 or !(holds_kind(forest, result, "ty-var")))
}
}
## The parameter patterns of the lambda at `lambda`, by position.
lambda_params : Forest, U64 -> List(U64)
lambda_params = |forest, lambda|
match Forest.kids(forest, lambda).find_first(|kid| Forest.kind(forest, kid) == "args") {
Ok(args) => Forest.kids(forest, args)
Err(_) => []
}
cookbook/roc/find_functions_and_parameters_that_dont_earn_their_keep/References.roc, 358 lines
## The second pass of find_functions_and_parameters_that_dont_earn_their_keep: every reference to a function the
## checked files declare, with the call it heads, tallied by function. A
## reference is a function's bare name in the file that defines it,
## `Type.name` anywhere (the type read through the file's `import ... as`),
## a method call `.name(...)`, which counts for every member of that name, or
## a record's shorthand (`{ helper }`). A reference within the function's own
## lines makes it recursive; any other is a test file's, an `expect`'s or
## production's. A name that may reach a member by a way this cannot follow
## (an alias of a type, a name an import exposes) is a mention, which keeps
## every member of that name out of `dead`.
import lib.Forest
import lib.Text
import lib.Tree
import Functions
References := [].{
## A call: the arguments' places, and an arrow or method call's receiver,
## its first argument, or 0 for none.
Call : { path : Str, line : U64, args : List(U64), receiver : U64 }
## What reaches a function, by kind, in the order the forest holds them.
Tally : {
prod_refs : U64,
value_refs : U64,
expect_refs : U64,
test_refs : U64,
first_prod_caller : Str,
prod_calls : List(References.Call),
self_calls : List(References.Call),
test_calls : List(References.Call),
is_recursive : Bool,
is_entry : Bool,
is_ambiguous : Bool,
is_mentioned : Bool,
}
## Each function's tally, by its place among the functions. `test_paths`
## are the files `tests=` names: a reference from one of them to a
## function outside them is a test's.
tally : Forest, Functions.Ancestry, Functions.Defined, Set(Str) -> List(References.Tally)
tally = |forest, ancestry, defined, test_paths| {
found = references_of({ forest, ancestry, defined, aliases: import_aliases(forest) })
sorted = found.events.sort_with(event_order)
var $tallies = []
$cursor : U64
var $cursor = 0
for function in defined.functions {
index = $tallies.len()
$end : U64
var $end = $cursor
while $end < sorted.len() and ((sorted.get($end) ?? crash "find_functions_and_parameters_that_dont_earn_their_keep: no event").function == index) {
$end = $end + 1
}
own = sorted.sublist({ start: $cursor, len: $end - $cursor })
$cursor = $end
counted = tally_of(function, own, test_paths)
$tallies = $tallies.append({
..counted,
is_ambiguous: found.ambiguous.contains(index),
is_mentioned: !(function.owner.starts_with("@")) and found.mentioned.contains(function.name),
})
}
entries = entries_of(defined, $tallies)
$tallies.map_with_index(|counted, index| { ..counted, is_entry: entries.contains(index) })
}
## Whether the file is a test of the rest: a name ending in `twin.roc`, a
## file under a `twin/` or `test/` folder, or a spec app named for its
## module followed by `Spec.roc` (`BlitSpec.roc`).
is_test_file : Str -> Bool
is_test_file = |path| {
in_folder = path.contains("/twin/") or path.contains("/test/") or path.starts_with("test/") or path.starts_with("twin/")
is_spec(Text.basename(path)) or path.ends_with("twin.roc") or in_folder
}
}
## Where a reference is: its file and line, whether an `expect` holds it,
## and the declaration around it.
Reference : { path : Str, line : U64, in_expect : Bool, enclosing : Str }
## A reference to the function at `function` among them, the `seq`th found:
## the call it heads, or none when the function is passed as a value.
Event : { function : U64, seq : U64, reference : Reference, use : [Called(References.Call), AsValue] }
## What the pass reads: the forest, its ancestry, the functions, and the
## module each file's import aliases stand for, by `path|alias`.
Reading : { forest : Forest, ancestry : Functions.Ancestry, defined : Functions.Defined, aliases : Dict(Str, Str) }
## Each file's import aliases, `path|alias`, and the module each names.
import_aliases : Forest -> Dict(Str, Str)
import_aliases = |forest| {
var $aliases = Dict.empty()
$at : U64
var $at = 1
while $at <= Forest.count(forest) {
if Forest.kind(forest, $at) == "s-import" {
match Tree.find_attribute(Forest.node(forest, $at), "alias") {
Ok(alias) => {
$aliases = $aliases.insert("${Forest.path(forest, $at)}|${alias}", Tree.last_part(Forest.raw(forest, $at)))
}
Err(_) => {}
}
}
$at = $at + 1
}
$aliases
}
## Every reference in the forest, in its order; the functions a method call
## of a shared name reaches; and the names mentioned.
references_of : Reading -> { events : List(Event), ambiguous : Set(U64), mentioned : Set(Str) }
references_of = |reading| {
forest = reading.forest
var $events = []
var $ambiguous = Set.empty()
var $mentioned = Set.empty()
$at : U64
var $at = 1
while $at <= Forest.count(forest) {
kind = Forest.kind(forest, $at)
parent_kind = Forest.kind_or_none(forest, Forest.parent(forest, $at))
if kind == "e-method-call" {
name = Str.from_utf8_lossy(Forest.attribute(forest, $at, "method").to_utf8().drop_first(1))
if name != "" {
call = method_call(forest, $at)
keys = reading.defined.member_keys.get(name) ?? []
for key in keys {
index = reading.defined.by_key.get(key) ?? crash "find_functions_and_parameters_that_dont_earn_their_keep: a member key with no function"
$events = $events.append({ function: index, seq: $events.len(), reference: reference_at(reading, $at), use: Called(call) })
if keys.len() > 1 {
$ambiguous = $ambiguous.insert(index)
}
}
}
} else if kind == "e-ident" {
name = Forest.raw(forest, $at)
found = if name == "" {
Err(NoFunction)
} else {
referenced(reading, $at, name)
}
match found {
Ok(index) => {
$events = $events.append({ function: index, seq: $events.len(), reference: reference_at(reading, $at), use: call_headed_by(forest, $at) })
}
Err(_) =>
if name.contains(".") {
$mentioned = $mentioned.insert(Tree.last_part(name))
}
}
} else if kind == "field" and Forest.kids(forest, $at).is_empty() and parent_kind == "e-record" {
# `{ helper }` names `helper` with no identifier node. The field has
# no span, so its record says where it is.
match referenced(reading, $at, Forest.attribute(forest, $at, "field")) {
Ok(index) => {
record = Forest.parent(forest, $at)
$events = $events.append({ function: index, seq: $events.len(), reference: reference_at(reading, record), use: AsValue })
}
Err(_) => {}
}
} else if kind == "text" and parent_kind == "exposed-lower-ident" {
match Tree.find_attribute(Forest.node(forest, $at), "value") {
Ok(value) => {
$mentioned = $mentioned.insert(value)
}
Err(_) => {}
}
}
$at = $at + 1
}
{ events: $events, ambiguous: $ambiguous, mentioned: $mentioned }
}
reference_at : Reading, U64 -> Reference
reference_at = |reading, at| {
path = Forest.path(reading.forest, at)
line = Forest.node(reading.forest, at).line
in_expect = Functions.flag_at(reading.ancestry.in_expect, at)
{ path, line, in_expect, enclosing: Functions.text_at(reading.ancestry.enclosing, at) }
}
## The function the name at `at` refers to, by its place among them.
referenced : Reading, U64, Str -> Try(U64, [NoFunction])
referenced = |reading, at, name| {
path = Forest.path(reading.forest, at)
by_key = reading.defined.by_key
known = |key|
match by_key.get(key) {
Ok(index) => Ok(index)
Err(_) => Err(NoFunction)
}
if name.contains(".") {
parts = name.split_on(".")
owner = parts.get(parts.len() - 2) ?? ""
type_name = reading.aliases.get("${path}|${owner}") ?? owner
known("${type_name}|${Tree.last_part(name)}")
} else {
owner = Functions.text_at(reading.ancestry.owner, at)
if owner != "" and by_key.contains("${owner}|${name}") {
known("${owner}|${name}")
} else if by_key.contains("@${path}|${name}") {
known("@${path}|${name}")
} else {
var $found = Err(NoFunction)
for key in reading.defined.member_keys.get(name) ?? [] {
index = by_key.get(key) ?? crash "find_functions_and_parameters_that_dont_earn_their_keep: a member key with no function"
if Functions.at(reading.defined, index).path == path {
$found = Ok(index)
}
}
$found
}
}
}
## The call whose head is the identifier at `at`, or none. In `x->f(a)`, the
## apply `f(a)` is the arrow call's second kid, and `x` its receiver.
call_headed_by : Forest, U64 -> [Called(References.Call), AsValue]
call_headed_by = |forest, at| {
apply = Forest.parent(forest, at)
if Forest.kind_or_none(forest, apply) != "e-apply" or Forest.kid(forest, apply, 1) != at {
AsValue
} else {
arrow = Forest.parent(forest, apply)
is_arrow = Forest.kind_or_none(forest, arrow) == "e-arrow-call" and Forest.kid(forest, arrow, 2) == apply
receiver = if is_arrow {
Forest.kid(forest, arrow, 1)
} else {
0
}
args = Forest.kids(forest, apply).drop_first(1)
Called({ path: Forest.path(forest, at), line: Forest.node(forest, at).line, args, receiver })
}
}
## The method call at `at`, its receiver the receiver node's value.
method_call : Forest, U64 -> References.Call
method_call = |forest, at| {
var $args = []
var $receiver = 0
for kid in Forest.kids(forest, at) {
kind = Forest.kind(forest, kid)
if kind == "receiver" {
$receiver = Forest.kid(forest, kid, 1)
}
if kind.starts_with("args") {
$args = Forest.kids(forest, kid)
}
}
{ path: Forest.path(forest, at), line: Forest.node(forest, at).line, args: $args, receiver: $receiver }
}
## By function, then in the order found.
event_order : Event, Event -> [Before, Same, After]
event_order = |first, second|
if first.function != second.function {
if first.function < second.function {
Before
} else {
After
}
} else if first.seq < second.seq {
Before
} else if first.seq > second.seq {
After
} else {
Same
}
## A function's tally from its own references, in the order found.
tally_of : Functions.Function, List(Event), Set(Str) -> References.Tally
tally_of = |function, events, test_paths| {
is_own = |event| event.reference.path == function.path and event.reference.line >= function.line and event.reference.line <= function.end_line
own = events.keep_if(is_own)
outside = events.drop_if(is_own)
is_from_test_file = |event| References.is_test_file(event.reference.path) or (test_paths.contains(event.reference.path) and !(test_paths.contains(function.path)))
from_tests = outside.keep_if(is_from_test_file)
from_expects = outside.drop_if(is_from_test_file).keep_if(|event| event.reference.in_expect)
production = outside.drop_if(is_from_test_file).drop_if(|event| event.reference.in_expect)
prod_calls = calls_of(production)
first_prod_caller = match production.first() {
Ok(event) => "${event.reference.path}:${event.reference.line.to_str()} in ${event.reference.enclosing}"
Err(_) => ""
}
{
prod_refs: production.len(),
value_refs: production.len() - prod_calls.len(),
expect_refs: from_expects.len(),
test_refs: from_tests.len(),
first_prod_caller,
prod_calls,
self_calls: calls_of(own),
test_calls: calls_of(outside.keep_if(|event| is_from_test_file(event) or event.reference.in_expect)),
is_recursive: !(own.is_empty()),
is_entry: Bool.False,
is_ambiguous: Bool.False,
is_mentioned: Bool.False,
}
}
## The functions holding a production call of a recursive function: the
## entries into a recursion, by their places among the functions.
entries_of : Functions.Defined, List(References.Tally) -> Set(U64)
entries_of = |defined, tallies| {
var $by_path = Dict.empty()
$index : U64
var $index = 0
for function in defined.functions {
$by_path = $by_path.insert(function.path, ($by_path.get(function.path) ?? []).append($index))
$index = $index + 1
}
var $entries = Set.empty()
for counted in tallies {
if counted.is_recursive {
for call in counted.prod_calls {
for index in $by_path.get(call.path) ?? [] {
holder = Functions.at(defined, index)
if call.line >= holder.line and call.line <= holder.end_line {
$entries = $entries.insert(index)
}
}
}
}
}
$entries
}
## Whether a file's name is a spec app's: `Spec.roc` after a run of letters
## and digits that holds a capital.
is_spec : Str -> Bool
is_spec = |base|
if !(base.ends_with("Spec.roc")) {
Bool.False
} else {
before = base.drop_suffix("Spec.roc").to_utf8()
is_alphanumeric = |byte| (byte >= 'a' and byte <= 'z') or (byte >= 'A' and byte <= 'Z') or (byte >= '0' and byte <= '9')
run_start = match before.find_last_index(|byte| !(is_alphanumeric(byte))) {
Ok(index) => index + 1
Err(_) => 0
}
before.drop_first(run_start).any(|byte| byte >= 'A' and byte <= 'Z')
}
## The calls among the references, in their order.
calls_of : List(Event) -> List(References.Call)
calls_of = |events| {
var $calls = []
for event in events {
match event.use {
Called(call) => {
$calls = $calls.append(call)
}
AsValue => {}
}
}
$calls
}
cookbook/roc/find_functions_and_parameters_that_dont_earn_their_keep/SelfTest.roc, 107 lines
## The recipe's self-test, run after the checks over the plants in
## cookbook/roc/plants/find_functions_and_parameters_that_dont_earn_their_keep/: each plant is named for the check it
## holds (`fixed_string.roc` holds `fixed`), and each check must fire on its
## own plants and on no others, and on no client; a `quiet_*.roc` plant gives
## no finding. A plant under `typed/` or `dead/` is a module, read in snake
## case (`BoolParam.roc` as `bool_param.roc`).
import pf.Shale
import lib.Finding
import lib.Text
SelfTest := [].{
## What the checks found over the plants: the checked files, the clients,
## how many files `tests=` named, and the findings printed.
Judged : {
paths : List(Str),
clients : List(Str),
test_count : U64,
findings : List(Finding),
}
## The plants' verdict printed, then a stop when any plant is wrong.
run! : SelfTest.Judged, List(Str) => {}
run! = |judged, checks| {
fired = Set.from_list(judged.findings.map(|finding| "${finding.path}|${finding.check}"))
var $failures = []
for check in checks {
$planted : U64
var $planted = 0
for path in judged.paths {
name = plant_name(path)
is_mine = name == "${check}.roc" or name.starts_with("${check}_")
if is_mine {
$planted = $planted + 1
}
did_fire = fired.contains("${path}|${check}")
if is_mine and !(did_fire) {
$failures = $failures.append("`${check}` does not fire on its plant ${path}")
}
if did_fire and !(is_mine) {
$failures = $failures.append("`${check}` fires on ${path}, another check's plant")
}
}
if $planted == 0 {
$failures = $failures.append("`${check}` has no plant")
}
for path in judged.clients {
if fired.contains("${path}|${check}") {
$failures = $failures.append("`${check}` fires on the client ${path}, which is read only for its calls")
}
}
}
if judged.clients.is_empty() or judged.test_count == 0 {
$failures = $failures.append("no client or no gate plant read")
}
for failure in $failures {
Shale.print!("FAIL ${failure}")
}
if !($failures.is_empty()) {
Shale.fail!("find_functions_and_parameters_that_dont_earn_their_keep self_test: ${$failures.len().to_str()} plants wrong")
}
Shale.print!("find_functions_and_parameters_that_dont_earn_their_keep (Roc) self_test: PASS (each check fires on its plants alone, the quiet_ plants on none)")
}
## The plants' folder.
plants : Str
plants = "cookbook:roc/plants/find_functions_and_parameters_that_dont_earn_their_keep/"
## The typed plants, judged with the types under `QuietApp.roc`.
typed_plants : Str
typed_plants = "${SelfTest.plants}typed/"
## The plants `dead` and `unused_api` are judged on, since nothing calls
## the others.
dead_plants : Str
dead_plants = "${SelfTest.plants}dead/"
}
## A plant's file name as the self-test reads it: a typed or `dead/` plant's
## in snake case.
plant_name : Str -> Str
plant_name = |path| {
base = Text.basename(path)
if path.starts_with(SelfTest.typed_plants) or path.starts_with(SelfTest.dead_plants) {
snake_case(base)
} else {
base
}
}
## A CamelCase file name in snake case: `_` before each capital but a first,
## and the capital made small.
snake_case : Str -> Str
snake_case = |name| {
var $out = []
for byte in name.to_utf8() {
if Text.is_capital(byte) {
if !($out.is_empty()) {
$out = $out.append('_')
}
$out = $out.append(byte + 32)
} else {
$out = $out.append(byte)
}
}
Str.from_utf8_lossy($out)
}
cookbook/roc/find_functions_and_parameters_that_dont_earn_their_keep/Types.roc, 105 lines
## The effects of a recipe's `types=1`: the tree's Roc found, and roc-types
## (Roc's own checker, https://github.com/showell/roc-types) run on each app
## of `root=`, its pin held to the tree's Roc. Reading and joining its output
## is cookbook/roc/lib/'s RocTypes; this file is the same in check_how_failure_is_reported,
## find_awkward_names, find_functions_and_parameters_that_dont_earn_their_keep and
## find_uses_after_a_consume, since a package reaches no effect.
import pf.Shale
import lib.RocTypes
import lib.Text
Types := [].{
## The OS path of the tree's Roc: the pin in `roc-version` where the run
## starts, or the self-test's pin, which cookbook/roc/pinned.shale names.
## `who` names the recipe in a refusal.
roc_bin! : Str, Bool => Str
roc_bin! = |who, self_test| {
pin = if self_test {
pinned = read_text!(who, "cookbook:roc/pinned.shale")
must!(RocTypes.self_test_pin(pinned).map_err(|_| "${who}: cookbook/roc/pinned.shale names no SELF_TEST_PIN"))
} else if Shale.exists!("roc-version") {
Text.trim(read_text!(who, "roc-version"))
} else {
must!(Err("${who}: no roc-version where the run starts: run it from the repository's root, whose roc-version pins its Roc"))
}
roc = RocTypes.roc_of_pin(pin)
if !(Shale.exists!(roc)) {
must!(Err("${who}: 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}" {
must!(Err("${who}: ${roc} says ${Text.trim(said.out)}, not Roc compiler version ${pin}"))
}
real
}
## The types of the nodes of `kind` in the files `paths`, from roc-types
## run on each app of `root` with the Roc at `roc`, and a line for each
## file no app reaches, except those in `exempt`.
gather! : { who : Str, kind : RocTypes.Kind, root : Str, roc : Str, paths : List(Str), exempt : Set(Str) } => { typing : RocTypes.Typing, unreached : List(Str) }
gather! = |asked| {
roots = must!(RocTypes.root_apps(asked.who, asked.root))
var $by_module = Dict.empty()
for root in roots {
got = modules_of!(root, asked.roc)
$by_module = RocTypes.joined($by_module, got, asked.kind)
for warning in got.warnings {
Shale.print!("${asked.who}: roc-types ${root}: ${warning}")
}
}
var $named = []
for path in asked.paths {
$named = $named.append({ path, real: Shale.real!(path) })
}
RocTypes.typing_of({ by_module: $by_module, named: $named, exempt: asked.exempt, roots })
}
}
## The modules roc-types reports for the app `root`, built with the Roc at
## `roc`, or a stop: roc-types missing, of another format, built for another
## Roc, or refusing the app.
modules_of! : Str, Str => RocTypes.Modules
modules_of! = |root, roc| {
pinned = RocTypes.pinned_checker(roc) ?? RocTypes.default_checker
exe = if Shale.exists!(pinned) {
pinned
} else {
RocTypes.default_checker
}
if !(Shale.exists!(exe)) {
Shale.fail!("`roc_types`: no ${exe}: ${RocTypes.install_hint}")
}
ran = Shale.run!({
argv: [Shale.real!(exe), Shale.real!(root)],
keep: Whole(64000000),
timeout_ms: 300000,
want: "",
})
output_lines = Text.lines(ran.out)
pin = must!(RocTypes.pin_of(output_lines, root))
own = RocTypes.roc_of_pin(pin)
if !(Shale.exists!(own)) or Shale.real!(own) != roc {
Shale.fail!(RocTypes.another_compiler(pin, root, roc))
}
must!(RocTypes.modules_ran(output_lines, ran.code, root))
}
read_text! : Str, Str => Str
read_text! = |who, path|
match Shale.read!(path) {
Found(text) => text
Missing => must!(Err("${who}: no ${path}"))
}
## What `tried` holds, or the run stopped with its refusal.
must! : Try(a, Str) => a
must! = |tried|
match tried {
Ok(value) => value
Err(why) => {
Shale.fail!(why)
crash "Types: Shale.fail! returned"
}
}
cookbook/roc/find_functions_and_parameters_that_dont_earn_their_keep/Source.roc, 150 lines
## The source text the checks compare: a node's text squeezed onto one line,
## a call's argument texts slot by slot and the texts its calls agree on, a
## branch's text without its braces, and whether a text is a literal.
import lib.Bytes
import lib.Forest
import lib.Text
import References
Source := [].{
## What a slot of a function's calls holds: the text every call gives it,
## or `Differs` where the calls differ.
Slot : [Agreed(Str), Differs]
## The node's source text, squeezed onto one line, `?` for a node with no
## span. `lines_of` is each file's lines; a node's end column is one past
## its last byte.
text_of : Dict(Str, List(Str)), Forest, U64 -> Str
text_of = |lines_of, forest, at| {
node = Forest.node(forest, at)
source_lines = lines_of.get(Forest.path(forest, at)) ?? []
line_bytes = |number| Bytes.line_of(source_lines, number)
before_end = if node.end_column == 0 {
0
} else {
node.end_column - 1
}
if node.line == 0 {
"?"
} else if node.line == node.end_line {
Str.from_utf8_lossy(Bytes.span(line_bytes(node.line), node.column, before_end))
} else {
var $parts = [Bytes.trimmed(Bytes.rest_from(line_bytes(node.line), node.column))]
var $number = node.line + 1
while $number < node.end_line {
$parts = $parts.append(Bytes.trimmed(line_bytes($number)))
$number = $number + 1
}
$parts = $parts.append(Bytes.trimmed(Bytes.span(line_bytes(node.end_line), 1, before_end)))
Str.join_with($parts.map(Str.from_utf8_lossy), " ")
}
}
## A call's argument texts by slot (`1`, `2`, ...), the receiver first. A
## record argument gives its fields instead, as `N.field`, so that
## `{ needle, at: 0 }` is judged field by field.
argument_texts : Dict(Str, List(Str)), Forest, References.Call -> Dict(Str, Str)
argument_texts = |lines_of, forest, call| {
arguments = if call.receiver != 0 {
[call.receiver].concat(call.args)
} else {
call.args
}
var $texts = Dict.empty()
$slot : U64
var $slot = 0
for argument in arguments {
$slot = $slot + 1
if Forest.kind(forest, argument) == "e-record" {
for field in Forest.kids(forest, argument) {
field_name = if Forest.kind(forest, field) == "field" {
Forest.attribute(forest, field, "field")
} else {
""
}
if field_name != "" {
value = Forest.kid(forest, field, 1)
text = if value != 0 {
Source.text_of(lines_of, forest, value)
} else {
field_name
}
$texts = $texts.insert("${$slot.to_str()}.${field_name}", text)
}
}
} else {
$texts = $texts.insert($slot.to_str(), Source.text_of(lines_of, forest, argument))
}
}
$texts
}
## For each slot of `calls`, the text every call gives it, or `Differs`.
agreed : Dict(Str, List(Str)), Forest, List(References.Call) -> Dict(Str, Source.Slot)
agreed = |lines_of, forest, calls| {
var $agreed = Dict.empty()
var $is_first = Bool.True
for call in calls {
texts = Source.argument_texts(lines_of, forest, call)
if $is_first {
for (slot, text) in texts.to_list() {
$agreed = $agreed.insert(slot, Agreed(text))
}
$is_first = Bool.False
} else {
for (slot, was) in $agreed.to_list() {
match was {
Agreed(text) =>
if texts.get(slot) != Ok(text) {
$agreed = $agreed.insert(slot, Differs)
}
Differs => {}
}
}
for (slot, _) in texts.to_list() {
if !($agreed.contains(slot)) {
$agreed = $agreed.insert(slot, Differs)
}
}
}
}
$agreed
}
## The text of one branch of an `if`, its braces left out when it holds
## one statement.
branch_text : Dict(Str, List(Str)), Forest, U64 -> Str
branch_text = |lines_of, forest, at| {
is_one = |kid| Forest.kind(forest, kid) == "statements" and Forest.kids(forest, kid).len() == 1
if Forest.kind(forest, at) == "e-block" {
match Forest.kids(forest, at).find_first(is_one) {
Ok(statements) => Source.text_of(lines_of, forest, Forest.kid(forest, statements, 1))
Err(_) => Source.text_of(lines_of, forest, at)
}
} else {
Source.text_of(lines_of, forest, at)
}
}
## Whether a text is a literal: a number, a string, a character, a tag
## (`Begin`) or a module's constant (`Limits.max`).
is_literal : Str -> Bool
is_literal = |text| {
bytes = text.to_utf8()
first = bytes.first() ?? 0
second = bytes.get(1) ?? 0
if first == '"' or first == '\'' or Text.is_digit(first) or (first == '-' and Text.is_digit(second)) {
Bool.True
} else if !(Text.is_capital(first)) {
Bool.False
} else {
is_name_byte = |byte| Bytes.is_letter(byte) or Text.is_digit(byte)
after = bytes.drop_first(1)
rest = after.drop_first(after.find_first_index(|byte| !(is_name_byte(byte))) ?? after.len())
is_lower_byte = |byte| Text.is_small_letter(byte) or Text.is_digit(byte) or byte == '_'
starts_constant = (rest.first() ?? 0) == '.' and Bytes.starts_lower_name(rest.get(1) ?? 0)
rest.is_empty() or (starts_constant and rest.drop_first(2).all(is_lower_byte))
}
}
}
Shale original
cookbook/roc/check_boundaries.shale, 830 lines, at 8d71e21b
The libraries it loads: cookbook/roc/headers.shale (96 lines), cookbook/roc/house.shale (46 lines), cookbook/roc/parsed.shale (34 lines), cookbook/roc/pinned.shale (20 lines), cookbook/roc/types.shale (301 lines).
-- This recipe asks of every function in a tree of .roc files whether its
-- boundary earns its keep, and whether each of its parameters is really a
-- parameter. It reads each file's syntax tree from Roc's own parser
-- (cookbook/roc/parsed.shale), and it checks the functions defined at the
-- top level of a file or as members of a module type, not those inside
-- another function. A finding is a question for a reader, not a verdict.
--
-- cd <repo> && shale <shale>/cookbook/roc/check_boundaries.shale glob=chat/**/*.roc
-- shale cookbook:roc/check_boundaries.shale self_test=1
--
-- The arguments:
-- glob the files to read, `**/*.roc` by default. Read the whole tree,
-- tests too, because a test that reaches a function keeps it
-- quiet, and calls are counted only in the files read;
-- ways the most ways through a body that `single` still calls a
-- wrapper, 2 by default;
-- nodes the most syntax-tree nodes in such a body, 24 by default;
-- house with `house=0`, leave out what is only our house style
-- (cookbook/roc/house.shale), for another project's code;
-- types with `types=1`, Roc's checker gives the types
-- (cookbook/roc/types.shale), which `bool_param` needs. It is off
-- by default, and needs the tree's `roc-version` file;
-- root with `types=1`, the app that imports the files read, or several
-- apps separated by commas (`root=a.roc,b.roc`);
-- clients globs separated by commas, of files read only for the calls
-- they make into the files checked, as apps that import a game.
-- Their own functions and `if`s are not checked, even where `glob`
-- matches them too;
-- tests globs separated by commas, of checked files that are tests of
-- the rest, as a tree's gate apps. A reference from one of them to
-- a function outside them counts as a test's;
-- test_reach `keeps` by default, so an `expect` or a test that reaches a
-- function keeps it out of `dead` and `unused_api`. With
-- `test_reach=dead`, only a production call or reference keeps a
-- module type's member out of `dead`. A file's own top-level
-- function is private to it, so its tests may still be all that
-- reach it, and a test of a library's API is a user of it.
--
-- The checks, most from the Roc style guide (roc-apps docs/roc-style.md):
--
-- single A small function with exactly one production call, and no
-- `expect`, test file or `##` doc comment that reaches or
-- explains it, would read better inline at that call ("A
-- function earns its boundary"; the guide calls it a rule of
-- thumb). Its body must be one statement of at most `nodes`
-- nodes and `ways` ways through: an `if` adds a way, and a
-- `match` adds one for each arm past its first. A function
-- passed as a value (`map_ok(Uid.to_str)`), a question named
-- `is_*` or `has_*`, a recursive function and an entry into
-- one (see `entry`) are quiet.
-- fixed Every production call, two or more, passes the same
-- literal for one parameter, or for one field of a record
-- argument. A literal is a number, a string, a character, a
-- tag (`Begin`, `Bool.True`) or a module's constant
-- (`Limits.max`). "A parameter every caller passes the same
-- value is no parameter": drop it, or add an entry function
-- that takes only what varies. A recursive function's calls
-- to itself must pass the same literal too. The same variable
-- or call at every call site (`me`, `req.me`,
-- `Host.list_srcs!({})`) is the caller's own value handed on,
-- and is not a literal. A library's API keeps its parameters
-- whatever this tree's callers pass, so `fixed` skips a
-- module type's member in a file under a `lib/` folder, or in
-- a module exposed by a `package` or `platform` header in the
-- `main.roc` beside it. A file's own top-level functions there
-- are checked.
-- entry Every production call, two or more, passes the same literal
-- for a parameter that the recursive function's own calls
-- vary (`at: 0` outside, `at + 1` inside). The recursion
-- needs the parameter, so the fix is an entry function that
-- takes only what varies and passes the literal itself
-- (`count = |xs| count_from(xs, 0)`). That entry function
-- makes the one outside call, so it does not fire again.
-- constant A function whose one argument is `{}`, by its annotation or
-- its lambda's pattern, and whose name has no `!`, gives the
-- same value at every call, so it can be a constant
-- (`board = ...`, not `board = |{}| ...`). A function with an
-- effect needs a `!` in its name. Roc refuses a generic
-- constant, so a function whose annotated return type holds a
-- type variable (`{} -> Viewer(id)`) is quiet. An unannotated
-- function's type is unknown, so it is checked. A `##` doc
-- above it (or its annotation) answers it, giving the reason
-- it stays a function, as a `##` doc answers `single`.
-- dead A top-level or member function that nothing reaches in the
-- files read: no production call, no `expect`, no test file, and
-- no reference to it as a value, a record's shorthand
-- (`{ helper }`) included. Its calls to itself don't count. A
-- top-level function is private to its file, even in a package,
-- and a member of a module no package exposes has no caller to
-- come. Left alone are the names something else calls: what an
-- app's header provides, what a platform requires and provides,
-- and a method Roc calls by name (`is_eq`, `to_hash`).
-- unused_api The same, for a member of a module its package or platform
-- exposes, a member under a `lib/` folder, or a name a `module`
-- header exposes. The callers of a public name are mostly
-- outside the tree, so this is a question and not a verdict, and
-- it has its own count. A member only an `expect` reaches is in
-- neither, unless `test_reach=dead`.
-- same_branches An `if` whose two branches are the same text, braces aside
-- (`if m.over { m } else m`). The condition decides nothing, so
-- a rule was lost, or the `if` should go.
-- bool_param With `types=1` only: a parameter whose type is `Bool` is
-- passed `Bool.True`, `Bool.False`, `True` or `False` by some
-- call. "A flag a caller passes is a tag", named for what it
-- means (`Loud`, not `Bool.True`). Every call counts, from an
-- `expect`, a test file or the function itself too. A
-- function with one parameter is quiet, as that parameter is
-- the value it converts (`bool : Bool -> JsonOut`), and so is
-- a field of a record argument.
--
-- A reference to a function is its bare name in the file that defines it,
-- `Type.name` anywhere, the type read through the file's `import ... as`, or
-- a method call `.name(...)`. The receiver of a method call or of an arrow call (`x->f(a)`) is its first argument. A
-- method call counts for every module type with a member of that name, so
-- a member whose name another type's member shares is ambiguous, and only
-- `constant` checks it. A test file is a file whose name ends in
-- `twin.roc`, a file under a `twin/` or `test/` folder, or a spec app,
-- named for its module followed by `Spec.roc` (`BlitSpec.roc`). Its
-- references count as an `expect`'s do, never as production calls, and
-- its own functions are not checked.
--
-- Each finding is one line, `path:line: <check>: <why>`, where the line is
-- the function's definition, and the findings are followed by a summary
-- line of the counts. Files that don't parse are listed after the summary,
-- with the files no root reaches under `types=1`, and then the run fails.
--
-- `self_test=1` checks the plants in `cookbook/roc/plants/check_boundaries/`.
-- Each plant is named for the check it holds (`fixed_string.roc` holds
-- `fixed`), and each check must fire on its own plants and on no others; a
-- `quiet_*.roc` plant must give no finding. `dead` and `unused_api` are judged
-- only under `dead/`, since nothing calls the other plants. The plants under
-- `typed/` are type modules checked with the types under the app `QuietApp.roc`, and
-- their names are read in snake case (`BoolParam.roc` as `bool_param`).
-- The rest are checked without types. The self-test runs with
-- `test_reach=dead`, the plants under `dead/clients/` as `clients`, and those
-- under `dead/gates/` as `tests`. The self-test fails if roc-types is not
-- installed.
-- budget: steps=800000000 arena_bytes=3000000000
const SELF_TEST = arg("self_test", "") == "1"
const PLANTS = "cookbook:roc/plants/check_boundaries/"
const TYPED_PLANTS = PLANTS .. "typed/"
const GLOB = SELF_TEST and (PLANTS .. "**/*.roc") or arg("glob", "**/*.roc")
const MAX_WAYS = arg("ways", 2)
const MAX_NODES = arg("nodes", 24)
const DEAD_PLANTS = PLANTS .. "dead/"
const CHECKS = {"single", "fixed", "entry", "constant", "bool_param", "dead", "unused_api", "same_branches"}
use("./headers.shale")
use("./house.shale")
use("./parsed.shale")
use("./pinned.shale")
use("./types.shale")
const TYPES_ARG = arg("types", "0")
if TYPES_ARG ~= "0" and TYPES_ARG ~= "1" then fail("check_boundaries: types must be 0 (the default) or 1, not " .. TYPES_ARG) end
const USE_TYPES = SELF_TEST or TYPES_ARG == "1"
const ROOT = SELF_TEST and (TYPED_PLANTS .. "QuietApp.roc") or arg("root", "")
-- The self-test reads the plants under `dead/clients/` as clients, and those
-- under `dead/gates/` as tests.
const CLIENTS_ARG = SELF_TEST and (DEAD_PLANTS .. "clients/*.roc") or arg("clients", "")
const TESTS_ARG = SELF_TEST and (DEAD_PLANTS .. "gates/*.roc") or arg("tests", "")
const TEST_REACH = SELF_TEST and "dead" or arg("test_reach", "keeps")
if TEST_REACH ~= "keeps" and TEST_REACH ~= "dead" then fail("check_boundaries: test_reach must be keeps (the default) or dead, not " .. TEST_REACH) end
-- The pinned Roc defines `Bool := [False, True]`.
const BOOL_LITERALS = {["Bool.True"] = true, ["Bool.False"] = true, True = true, False = true}
-- Every file's syntax-tree nodes in one list, so that one index names a
-- node anywhere. `NODE_PATH[g]` is node g's file. A node's `parent` and
-- `kids` count from its own file's first node, so `NODE_OFFSET[g]` is
-- added to them.
const NODES = {}
const NODE_PATH = {}
const NODE_OFFSET = {}
const SOURCE_LINES = {}
-- Each file's `header_names`, and the module each of its import aliases
-- stands for, by `path|alias`.
const HEADER_NAMES = {}
const IMPORT_ALIASES = {}
-- The kinds of node that can hold a top-level function: a file, its
-- statements, a module type's declaration, and the block of its members.
const TOP_LEVEL_KINDS = {file = true, statements = true, ["s-type-decl"] = true, associated = true}
const finding_counts = {}
for c in CHECKS do finding_counts[c] = 0 end
-- The self-test's record of which checks fired on which files, by `path|check`.
const fired = {}
function report(path, line, check, why)
if house_leaves_out("check_boundaries", check) then return nil end
-- The other plants exist to be read by the other checks, and nothing calls them.
if SELF_TEST and (check == "dead" or check == "unused_api") and not starts_with(path, DEAD_PLANTS) then return nil end
print(path .. ":" .. line .. ": " .. check .. ": " .. why)
finding_counts[check] = finding_counts[check] + 1
fired[path .. "|" .. check] = true
return nil
end
function children(g)
local out = {}
for k in NODES[g].kids do push(out, NODE_OFFSET[g] + k) end
return out
end
function parent(g)
local p = NODES[g].parent
if p == 0 then return 0 end
return NODE_OFFSET[g] + p
end
function kind(g)
return NODES[g].kind
end
function raw_text(g)
return get(NODES[g], "raw", "")
end
-- Node g's source text, squeezed onto one line. A node's end column is one
-- past its last character.
function source_text(path, g)
local n = NODES[g]
if n.line == 0 then return "?" end
local src = SOURCE_LINES[path]
if n.line == n.end_line then return sub(src[n.line], n.column, n.end_column - 1) end
local parts = {trim(sub(src[n.line], n.column))}
for l = n.line + 1, n.end_line - 1 do push(parts, trim(src[l])) end
push(parts, trim(sub(src[n.end_line], 1, n.end_column - 1)))
return join(parts, " ")
end
function is_literal(s)
local c = sub(s, 1, 1)
if c == "\"" or c == "'" then return true end
if re_find(s, "^-?[0-9]") ~= nil then return true end
if re_find(s, "^[A-Z][A-Za-z0-9]*(\\.[a-z_][a-z0-9_]*)?$") ~= nil then return true end
return false
end
function is_question_name(name)
return starts_with(name, "is_") or starts_with(name, "has_")
end
function is_test_file(path)
if re_find(basename(path), "[A-Z][A-Za-z0-9]*Spec\\.roc$") ~= nil then return true end
return ends_with(path, "twin.roc") or contains(path, "/twin/") or contains(path, "/test/") or starts_with(path, "test/") or starts_with(path, "twin/")
end
-- Whether a function is part of a library's API: a module type's member in a
-- file under a `lib/` folder, or in a module its package or platform exposes,
-- or a name its own `module` header exposes.
function is_library_api(func)
if has_key(HEADER_NAMES[func.path].exposed, func.name) then return true end
if sub(func.owner, 1, 1) == "@" then return false end
local p = func.path
if starts_with(p, "lib/") or contains(p, "/lib/") or contains(p, ":lib/") then return true end
return is_exposed_module(p)
end
-- The name in the header of the module type declared at `g`.
function type_decl_name(g)
local kids = children(g)
if #kids == 0 then return "" end
return get(NODES[kids[1]], "name", "")
end
-- ── the syntax trees ─────────────────────────────────────────────────────
-- The files matched by `globs`, a list separated by commas, as a set when
-- `as_set`.
function globbed(globs, as_set)
local paths = {}
local set = {}
for g in split(globs, ",") do
if trim(g) ~= "" then
for p in glob(trim(g)) do
push(paths, p)
set[p] = true
end
end
end
return as_set and set or paths
end
-- A file that `clients` and `glob` both match is a client, and not checked.
const CLIENT_FILES = globbed(CLIENTS_ARG, false)
const CLIENT_SET = globbed(CLIENTS_ARG, true)
local checked_files = {}
local checked_set = {}
for p in globbed(GLOB, false) do
if not has_key(CLIENT_SET, p) then
push(checked_files, p)
checked_set[p] = true
end
end
const ROC_FILES = checked_files
const CHECKED = checked_set
const TEST_PATHS = globbed(TESTS_ARG, true)
local untyped_plants = {}
if SELF_TEST then
for p in ROC_FILES do
if not starts_with(p, TYPED_PLANTS) then untyped_plants[p] = true end
end
end
local checker_types = USE_TYPES and roc_types_for_files("check_boundaries", ROOT, roc_bin("check_boundaries", SELF_TEST), ROC_FILES, untyped_plants) or {real = {}, pats = {}, exprs = {}, unreached = {}}
local files_parsed = {}
for p in ROC_FILES do push(files_parsed, p) end
for p in CLIENT_FILES do push(files_parsed, p) end
local parsed = parse_roc_files(files_parsed)
for f in parsed.files do
SOURCE_LINES[f.path] = split(read(f.path), "\n")
HEADER_NAMES[f.path] = header_names(f.nodes)
local offset = #NODES
for n in f.nodes do
push(NODES, n)
push(NODE_PATH, f.path)
push(NODE_OFFSET, offset)
end
end
-- What each node's ancestors say, worked out from its parent's, which
-- comes before it in the list:
-- AT_TOP_LEVEL[g] every ancestor is of a kind in `TOP_LEVEL_KINDS`;
-- OWNER_TYPE[g] the name of the nearest module type around it, or "";
-- ENCLOSING_DECL[g] the name of the outermost declaration around it, or "?";
-- IN_EXPECT[g] it is inside an `expect`.
const AT_TOP_LEVEL = {}
const OWNER_TYPE = {}
const ENCLOSING_DECL = {}
const IN_EXPECT = {}
for g = 1, #NODES do
local p = parent(g)
if p == 0 then
push(AT_TOP_LEVEL, true)
push(OWNER_TYPE, "")
push(ENCLOSING_DECL, "?")
push(IN_EXPECT, false)
else
local parent_kind = kind(p)
push(AT_TOP_LEVEL, AT_TOP_LEVEL[p] and has_key(TOP_LEVEL_KINDS, parent_kind))
push(OWNER_TYPE, parent_kind == "s-type-decl" and type_decl_name(p) or OWNER_TYPE[p])
local enclosing = ENCLOSING_DECL[p]
if enclosing == "?" and parent_kind == "s-decl" then
local pattern = children(p)
if #pattern > 0 and kind(pattern[1]) == "p-ident" then enclosing = raw_text(pattern[1]) end
end
push(ENCLOSING_DECL, enclosing)
push(IN_EXPECT, IN_EXPECT[p] or parent_kind == "s-expect")
end
end
-- How many `##` lines stand just above the function defined at `line`,
-- or above its annotation (`name : ...`, on one line or several) if it
-- has one.
function doc_comment_lines(src, name, line)
local top = line - 1
local k = top
while k >= 1 and k > line - 12 and trim(src[k]) ~= "" and not starts_with(trim(src[k]), "#") do
if starts_with(trim(src[k]), name .. " :") then top = k - 1 end
k = k - 1
end
local n = 0
while top >= 1 and starts_with(trim(src[top]), "##") do
n = n + 1
top = top - 1
end
return n
end
-- The nodes of the subtree at `g`, `g` first.
function subtree_nodes(g)
local out = {g}
local i = 1
while i <= #out do
for k in children(out[i]) do push(out, k) end
i = i + 1
end
return out
end
-- Whether the body of the lambda at `g` is small enough for `single` to
-- call it a wrapper, as `is_wrapper`, and its size in words for the
-- finding, as `size`. A wrapper's body is one statement: a block of one,
-- or an expression. Its size counts syntax-tree nodes, so the layout of
-- its lines changes nothing. It has one way through it, and one more for
-- each `if` and for each `match` arm past the first. So only a two-way
-- choice reads as a wrapper, and an `else if` chain or a nested `if` is a
-- rule of its own however few lines it takes.
function body_measure(g)
local kids = children(g)
local body = kids[#kids]
if kind(body) == "e-block" then
local statements = {}
for k in children(body) do
if kind(k) == "statements" then statements = children(k) end
end
if #statements ~= 1 then return {is_wrapper = false, size = #statements .. " statements"} end
body = statements[1]
end
local all = subtree_nodes(body)
local ways = 1
for k in all do
if kind(k) == "e-if-then-else" then ways = ways + 1 end
if kind(k) == "branches" then ways = ways + #children(k) - 1 end
end
local small = #all <= MAX_NODES
if ways > 1 then return {is_wrapper = small and ways <= MAX_WAYS, size = "a decision of " .. ways .. " ways, " .. #all .. " nodes"} end
return {is_wrapper = small, size = "one expression of " .. #all .. " nodes"}
end
-- The function type in the annotation just before the declaration at `g`,
-- if that annotation is for `name`, or 0.
function annotation_function_type(g, name)
local p = parent(g)
if p == 0 then return 0 end
local before = 0
local prev = 0
for k in children(p) do
if k == g then before = prev end
prev = k
end
if before == 0 or kind(before) ~= "s-type-anno" or get(NODES[before], "name", "") ~= name then return 0 end
local ty = children(before)
if #ty == 0 or kind(ty[1]) ~= "ty-fn" then return 0 end
return ty[1]
end
-- Whether the function declared at `g` takes `{}` alone, by its lambda's
-- one pattern or its annotation's one argument, and could be a constant:
-- an annotated return type holding a type variable (`ty-var`) rules that
-- out.
function takes_empty_record_alone(g, name)
local takes_it = false
local lambda = children(g)[2]
for k in children(lambda) do
if kind(k) == "args" then
local patterns = children(k)
if #patterns == 1 and kind(patterns[1]) == "p-record" and #children(patterns[1]) == 0 then takes_it = true end
end
end
local fn_type = annotation_function_type(g, name)
if fn_type == 0 then return takes_it end
local parts = children(fn_type)
if #parts == 2 and kind(parts[1]) == "ty-record" and #children(parts[1]) == 0 then takes_it = true end
if not takes_it then return false end
for k in subtree_nodes(parts[#parts]) do
if kind(k) == "ty-var" then return false end
end
return true
end
-- The parameter patterns of the lambda at `g`, by position.
function lambda_params(g)
for k in children(g) do
if kind(k) == "args" then return children(k) end
end
return {}
end
-- ── pass 1: the functions ────────────────────────────────────────────────
-- Each function by `owner|name`, where the owner is its module type's name,
-- or `@path` for a file's own top-level function.
const FUNCTIONS = {}
-- The keys of the module types' members, by name.
const MEMBER_KEYS = {}
for g = 1, #NODES do
if kind(g) == "s-decl" then
local kids = children(g)
if #kids > 1 and kind(kids[1]) == "p-ident" and kind(kids[2]) == "e-lambda" and AT_TOP_LEVEL[g] and has_key(CHECKED, NODE_PATH[g]) then
local path = NODE_PATH[g]
local owner = OWNER_TYPE[g] ~= "" and OWNER_TYPE[g] or ("@" .. path)
local n = NODES[g]
local name = raw_text(kids[1])
local key = owner .. "|" .. name
local body = body_measure(kids[2])
FUNCTIONS[key] = {
key = key, path = path, owner = owner, name = name, line = n.line, end_line = n.end_line,
is_wrapper = body.is_wrapper, size = body.size, doc_lines = doc_comment_lines(SOURCE_LINES[path], name, n.line),
takes_empty_record_alone = takes_empty_record_alone(g, name), params = lambda_params(kids[2]),
prod_refs = 0, value_refs = 0, expect_refs = 0, test_refs = 0, prod_callers = {},
prod_calls = {}, self_calls = {}, test_calls = {}, mentions = 0,
is_ambiguous = false, is_recursive = false, is_entry = false,
}
if sub(owner, 1, 1) ~= "@" then
if not has_key(MEMBER_KEYS, name) then MEMBER_KEYS[name] = {} end
push(MEMBER_KEYS[name], key)
end
end
end
end
-- ── pass 2: the references ───────────────────────────────────────────────
-- A call is `{path, line, args, receiver}`, where `args` are the argument
-- nodes and `receiver` is an arrow or method call's receiver, which is
-- the first argument, or 0 for none.
-- The call whose head is the identifier at `g`, or nil if it heads none.
function call_headed_by(g)
local apply = parent(g)
if apply == 0 or kind(apply) ~= "e-apply" then return nil end
local kids = children(apply)
if kids[1] ~= g then return nil end
local call = {path = NODE_PATH[g], line = NODES[g].line, args = drop(kids, 1), receiver = 0}
-- In `x->f(a)`, the apply `f(a)` is the arrow call's second child.
local arrow = parent(apply)
if arrow ~= 0 and kind(arrow) == "e-arrow-call" then
local arrow_kids = children(arrow)
if arrow_kids[2] == apply then call.receiver = arrow_kids[1] end
end
return call
end
function method_call(g)
local args = {}
local receiver = 0
for k in children(g) do
if kind(k) == "receiver" then receiver = children(k)[1] end
if starts_with(kind(k), "args") then args = children(k) end
end
return {path = NODE_PATH[g], line = NODES[g].line, args = args, receiver = receiver}
end
-- The key of the function that the name at `g` refers to, or "".
function referenced_key(g, name)
local path = NODE_PATH[g]
if contains(name, ".") then
local parts = split(name, ".")
local owner = parts[#parts - 1]
local key = get(IMPORT_ALIASES, path .. "|" .. owner, owner) .. "|" .. parts[#parts]
return has_key(FUNCTIONS, key) and key or ""
end
local owner = OWNER_TYPE[g]
if owner ~= "" and has_key(FUNCTIONS, owner .. "|" .. name) then return owner .. "|" .. name end
if has_key(FUNCTIONS, "@" .. path .. "|" .. name) then return "@" .. path .. "|" .. name end
local key = ""
for m in get(MEMBER_KEYS, name, {}) do
if FUNCTIONS[m].path == path then key = m end
end
return key
end
-- A reference within the function's own lines makes it recursive. Any
-- other is from a test file, from an `expect`, or from production, and
-- `call` is nil when the function is passed as a value.
function record_reference(func, ref, call)
if ref.path == func.path and ref.line >= func.line and ref.line <= func.end_line then
func.is_recursive = true
if call ~= nil then push(func.self_calls, call) end
return nil
end
local from_test_file = is_test_file(ref.path) or (has_key(TEST_PATHS, ref.path) and not has_key(TEST_PATHS, func.path))
if (from_test_file or ref.in_expect) and call ~= nil then push(func.test_calls, call) end
if from_test_file then
func.test_refs = func.test_refs + 1
elseif ref.in_expect then
func.expect_refs = func.expect_refs + 1
else
func.prod_refs = func.prod_refs + 1
push(func.prod_callers, ref.path .. ":" .. ref.line .. " in " .. ref.enclosing)
if call == nil then func.value_refs = func.value_refs + 1 else push(func.prod_calls, call) end
end
return nil
end
function reference_at(g)
return {path = NODE_PATH[g], line = NODES[g].line, in_expect = IN_EXPECT[g], enclosing = ENCLOSING_DECL[g]}
end
-- A name that may reach a member by a way this recipe can't follow: an alias
-- of a type, or a name an import exposes. It keeps every member of that name
-- out of `dead`, and counts as no call for the other checks.
function note_mention(name)
for key in get(MEMBER_KEYS, name, {}) do FUNCTIONS[key].mentions = FUNCTIONS[key].mentions + 1 end
return nil
end
function last_dotted_part(name)
local parts = split(name, ".")
return parts[#parts]
end
for g = 1, #NODES do
if kind(g) == "s-import" and has_key(NODES[g], "alias") then
IMPORT_ALIASES[NODE_PATH[g] .. "|" .. NODES[g].alias] = last_dotted_part(raw_text(g))
end
end
for g = 1, #NODES do
local node_kind = kind(g)
if node_kind == "e-method-call" then
local name = sub(get(NODES[g], "method", ""), 2)
if name ~= "" then
local call = method_call(g)
local keys_of_name = get(MEMBER_KEYS, name, {})
for key in keys_of_name do
record_reference(FUNCTIONS[key], reference_at(g), call)
if #keys_of_name > 1 then FUNCTIONS[key].is_ambiguous = true end
end
end
elseif node_kind == "e-ident" then
local name = raw_text(g)
local key = name ~= "" and referenced_key(g, name) or ""
if key ~= "" then record_reference(FUNCTIONS[key], reference_at(g), call_headed_by(g)) end
if key == "" and contains(name, ".") then note_mention(last_dotted_part(name)) end
elseif node_kind == "field" and #children(g) == 0 and kind(parent(g)) == "e-record" then
-- `{ helper }` names `helper` with no identifier node. The field has no
-- span, so its record says where it is.
local key = referenced_key(g, get(NODES[g], "field", ""))
if key ~= "" then record_reference(FUNCTIONS[key], reference_at(parent(g)), nil) end
elseif node_kind == "text" and has_key(NODES[g], "value") and kind(parent(g)) == "exposed-lower-ident" then
note_mention(NODES[g].value)
end
end
-- A function holding a production call of a recursive function is an
-- entry into the recursion.
local functions_by_path = {}
for key in keys(FUNCTIONS) do push_at(functions_by_path, FUNCTIONS[key].path, FUNCTIONS[key]) end
for key in keys(FUNCTIONS) do
local recursive = FUNCTIONS[key]
if recursive.is_recursive then
for c in recursive.prod_calls do
for f in get(functions_by_path, c.path, {}) do
if c.line >= f.line and c.line <= f.end_line then f.is_entry = true end
end
end
end
end
-- ── the checks ───────────────────────────────────────────────────────────
function display_name(func)
if sub(func.owner, 1, 1) == "@" then return func.name end
return func.owner .. "." .. func.name
end
-- A call's argument texts by position ("1", "2", ...), the receiver first.
-- A record argument gives its fields instead, as "N.field", so that
-- `{ needle, at: 0 }` is judged field by field.
function argument_texts(call)
local out = {}
local list = {}
if call.receiver ~= 0 then push(list, call.receiver) end
for a in call.args do push(list, a) end
local n = 0
for a in list do
n = n + 1
if kind(a) == "e-record" then
for f in children(a) do
local field_name = kind(f) == "field" and get(NODES[f], "field", "") or ""
if field_name ~= "" then
local value = children(f)
out[n .. "." .. field_name] = #value > 0 and source_text(call.path, value[1]) or field_name
end
end
else
out[tostring(n)] = source_text(call.path, a)
end
end
return out
end
-- No argument's text can be this, so it marks a slot where calls differ.
const DIFFERS = "\n differs"
-- For each argument slot of `calls`, by `argument_texts`'s keys, the text
-- every call gives it, or `DIFFERS`.
function agreed_argument_texts(calls)
local agreed = {}
local first = true
for c in calls do
local texts = argument_texts(c)
if first then
for k in keys(texts) do agreed[k] = texts[k] end
first = false
else
for k in keys(agreed) do
if agreed[k] ~= DIFFERS and (not has_key(texts, k) or texts[k] ~= agreed[k]) then agreed[k] = DIFFERS end
end
for k in keys(texts) do
if not has_key(agreed, k) then agreed[k] = DIFFERS end
end
end
end
return agreed
end
function concatenated(lists)
local out = {}
for l in lists do
for x in l do push(out, x) end
end
return out
end
function reads_better_inline(func)
return func.prod_refs == 1 and func.value_refs == 0 and func.expect_refs == 0 and func.test_refs == 0 and func.doc_lines == 0 and func.is_wrapper and not func.is_recursive and not func.is_entry and not is_question_name(func.name)
end
const CLIENTS_READ = #CLIENT_FILES > 0 and (" and " .. #CLIENT_FILES .. " clients") or ""
const FILES_READ = " in the " .. #ROC_FILES .. " files read" .. CLIENTS_READ
-- A function something outside the files calls: what its header dictates, or
-- a member Roc calls by name.
function is_called_from_outside(func)
if sub(func.owner, 1, 1) == "@" then return has_key(HEADER_NAMES[func.path].dictated, func.name) end
return has_key(LANGUAGE_FIXED_NAMES, func.name)
end
-- A test of a library's API is a user of it, so `unused_api` keeps it.
function has_no_caller(func)
local is_member = sub(func.owner, 1, 1) ~= "@"
if TEST_REACH == "dead" and is_member and not is_library_api(func) then return func.prod_refs == 0 and func.mentions == 0 end
return func.prod_refs == 0 and func.expect_refs == 0 and func.test_refs == 0 and func.mentions == 0
end
function is_test_only(func)
return func.expect_refs + func.test_refs > 0
end
-- The text of one branch of an `if`, its braces left out when it holds one
-- statement.
function branch_text(path, g)
if kind(g) == "e-block" then
for k in children(g) do
if kind(k) == "statements" and #children(k) == 1 then return source_text(path, children(k)[1]) end
end
end
return source_text(path, g)
end
for key in sort(keys(FUNCTIONS)) do
local func = FUNCTIONS[key]
local name = display_name(func)
local judged = not func.is_ambiguous and not is_test_file(func.path)
if not is_test_file(func.path) and has_no_caller(func) and not is_called_from_outside(func) then
if is_library_api(func) then
report(func.path, func.line, "unused_api", "`" .. name .. "` is exposed, and nothing" .. FILES_READ .. " calls or tests it: API with no user here, or left behind?")
elseif is_test_only(func) then
report(func.path, func.line, "dead", "`" .. name .. "` has no production caller" .. FILES_READ .. ", only an expect or a test: delete it with its tests, or say who calls it")
else
report(func.path, func.line, "dead", "`" .. name .. "` has no caller" .. FILES_READ .. ", and no expect or test reaches it: delete it, or say who calls it")
end
end
if judged and reads_better_inline(func) then
report(func.path, func.line, "single", "`" .. name .. "` (" .. func.size .. ") has one caller" .. FILES_READ .. ", " .. func.prod_callers[1] .. ", and no expect, test or doc: read it inline there, or say why it stands alone")
end
if judged and #func.prod_calls >= 2 and func.value_refs == 0 then
-- A slot the production calls agree on is `fixed` if the function's
-- own calls agree with them too, and `entry` if they vary it.
local outside = agreed_argument_texts(func.prod_calls)
local all = agreed_argument_texts(concatenated({func.prod_calls, func.self_calls}))
local own = #func.self_calls > 0 and (" and " .. #func.self_calls .. " of its own") or ""
for k in sort(keys(outside)) do
local v = outside[k]
if v ~= DIFFERS and is_literal(v) then
local said = "`" .. name .. "`'s argument " .. k .. " is `" .. v .. "` in all " .. #func.prod_calls .. " production calls"
if all[k] ~= DIFFERS then
if not is_library_api(func) then report(func.path, func.line, "fixed", said .. own .. FILES_READ .. ": no parameter, or an entry function that takes only what varies") end
else
report(func.path, func.line, "entry", said .. FILES_READ .. ", and its own calls vary it: an entry function that takes only what varies and passes `" .. v .. "` itself, its one outside call")
end
end
end
end
if func.takes_empty_record_alone and not contains(func.name, "!") and not is_test_file(func.path) and func.doc_lines == 0 then
report(func.path, func.line, "constant", "`" .. name .. "` takes `{}` alone and names no effect, so it gives the same value every call: a constant (`" .. func.name .. " = ...`), or a `!` if it has an effect")
end
if judged and #func.params > 1 and has_key(checker_types.real, func.path) then
local every = concatenated({func.prod_calls, func.self_calls, func.test_calls})
for i = 1, #func.params do
local param = func.params[i]
local ty = kind(param) == "p-ident" and roc_type_at(checker_types, "pat", func.path, NODES[param]) or nil
if ty == "Bool" then
local literal_calls = {}
for c in every do
local v = get(argument_texts(c), tostring(i), "")
if has_key(BOOL_LITERALS, v) then push(literal_calls, c.path .. ":" .. c.line .. " `" .. v .. "`") end
end
if #literal_calls > 0 then report(func.path, func.line, "bool_param", "`" .. name .. "`'s parameter " .. i .. ", `" .. raw_text(param) .. "`, is a `Bool` (the checker's type) passed as a literal at " .. #literal_calls .. " of its " .. #every .. " calls (" .. join(take(literal_calls, 3), ", ") .. (#literal_calls > 3 and ", ..." or "") .. "): a flag a caller passes is a tag, named for what it means (roc-apps docs/roc-style.md)") end
end
end
end
end
for g = 1, #NODES do
if kind(g) == "e-if-then-else" and not is_test_file(NODE_PATH[g]) and has_key(CHECKED, NODE_PATH[g]) then
local kids = children(g)
local shown = #kids == 3 and branch_text(NODE_PATH[g], kids[2]) or "?"
if shown ~= "?" and shown == branch_text(NODE_PATH[g], kids[3]) then
report(NODE_PATH[g], NODES[g].line, "same_branches", "both branches of this `if` are `" .. sub(shown, 1, 40) .. "`: the condition decides nothing")
end
end
end
local counts = {}
for c in CHECKS do push(counts, c .. " " .. finding_counts[c]) end
print("check_boundaries (Roc): " .. #ROC_FILES .. " files" .. CLIENTS_READ .. ", " .. #keys(FUNCTIONS) .. " functions; " .. join(counts, ", ") .. house_note("check_boundaries"))
fail_if_refused("check_boundaries", parsed.refused, checker_types.unreached)
-- A plant's file name as the self-test reads it. A typed plant is a type
-- module, so `typed/BoolParam.roc` reads as `bool_param.roc`, and so does a
-- plant under `dead/`, as a package's header names its modules.
function plant_check_name(p)
if starts_with(p, TYPED_PLANTS) or starts_with(p, DEAD_PLANTS) then return snake_case_plant_name(basename(p)) end
return basename(p)
end
if SELF_TEST then
local wrong = {}
for c in CHECKS do
local planted = 0
for p in ROC_FILES do
local base = plant_check_name(p)
local planted_here = base == c .. ".roc" or starts_with(base, c .. "_")
if planted_here then planted = planted + 1 end
local fired_here = has_key(fired, p .. "|" .. c)
if planted_here and not fired_here then push(wrong, "`" .. c .. "` does not fire on its plant " .. p) end
if fired_here and not planted_here then push(wrong, "`" .. c .. "` fires on " .. p .. ", another check's plant") end
end
if planted == 0 then push(wrong, "`" .. c .. "` has no plant") end
for p in CLIENT_FILES do
if has_key(fired, p .. "|" .. c) then push(wrong, "`" .. c .. "` fires on the client " .. p .. ", which is read only for its calls") end
end
end
if #CLIENT_FILES == 0 or #keys(TEST_PATHS) == 0 then push(wrong, "no client or no gate plant read") end
for w in wrong do print("FAIL " .. w) end
if #wrong > 0 then fail("check_boundaries self_test: " .. #wrong .. " plants wrong") end
print("check_boundaries (Roc) self_test: PASS (each check fires on its plants alone, the quiet_ plants on none)")
end