find_floats_outside_unit_types
Roc
It also imports Finding, Text, Tree from the shared Roc library.
cookbook/roc/find_floats_outside_unit_types/find_floats_outside_unit_types.roc, 116 lines
## find_floats_outside_unit_types, in Roc on Shale's platform (roc_platform/README.md):
## every bare `F64` in a project's declarations, for a project that keeps its
## floats inside unit types, where a `Metres` says what an `F64` doesn't.
## What must stay a float is named in the project's table, with a reason. Its
## launcher, cookbook/roc/find_floats_outside_unit_types.shale, is how it is run, and its
## header says the rules, `bare_float` and `unused_exception`.
## check_goldens.shale, beside this, holds its output on the plants to its
## goldens, line for line.
##
## cd <repo> && shale cookbook:roc/find_floats_outside_unit_types.shale table=bare_floats.txt
## shale cookbook:roc/find_floats_outside_unit_types.shale self_test=1
##
## The arguments: `glob` (`**/*.roc`), `table` (the project's exceptions)
## and `self_test` (`self_test=1` runs the plants, each through the
## launcher).
##
## This root reads the table (`Shale.read!`), globs the files
## (`Shale.glob!`), has Roc's parser read them (`Shale.roc_tree!`), and
## prints the verdict (`Shale.print!`, `Shale.fail!`). Its modules are
## beside it: the rule (Floats), what it spares (TestHelpers, Exceptions)
## and SelfTest; what they read (Tree, Text) and Finding are the cookbook's
## Roc library, cookbook/roc/lib/.
## budget: steps=800000000 arena_bytes=2000000000 output_bytes=4000000 programs=100
app [main!] { lib: "../lib/main.roc", pf: platform "../../../roc_platform/platform/main.roc" }
import pf.Shale
import Exceptions
import lib.Finding
import Floats
import SelfTest
import lib.Tree
main! : {} => {}
main! = |{}| {
if Shale.arg!("self_test", "") == "1" {
SelfTest.run!(checks)
} else {
run_check!({})
}
}
## The check over the glob's files: the verdict printed, then a stop when a
## file didn't parse, or when there are findings, the summary the last line
## a caller reads. The table is read before the files are globbed, so a bad
## table stops the run before anything is judged.
run_check! : {} => {}
run_check! = |{}| {
exceptions = Exceptions.read!(Shale.arg!("table", ""))
paths = Shale.glob!(Shale.arg!("glob", "**/*.roc"))
var $findings = []
var $covered = []
var $read_modules = Set.empty()
$in_helpers : U64
var $in_helpers = 0
var $refused = []
for file in Shale.roc_tree!(paths) {
if file.err == "" {
$read_modules = $read_modules.insert(Tree.module_name(file.path))
judged = Floats.judge_file({ path: file.path, syntax_nodes: file.nodes }, exceptions)
$findings = $findings.concat(judged.findings)
$covered = $covered.concat(judged.covered)
$in_helpers = $in_helpers + judged.in_helpers
} else if file.err.starts_with(file.path) {
$refused = $refused.append(file.err)
} else {
$refused = $refused.append("${file.path}: ${file.err}")
}
}
unused = Exceptions.find_unused!(
exceptions,
{ read_modules: $read_modules, used: Set.from_list($covered) },
)
if $in_helpers > 0 {
spared = "bare `F64`s are in helpers only tests use"
Shale.print!("${$in_helpers.to_str()} ${spared}, and aren't judged")
}
report = $findings.concat(unused)
found = report.sort_with(Finding.order).map(Finding.line_of)
summary = summary_of(report, paths.len())
print_findings!(summary, found)
if !($refused.is_empty()) {
for refusal in $refused {
Shale.print!("refused: ${refusal}")
}
refusals = "roc-ast refused ${$refused.len().to_str()} files (named above)"
why = "which have no tree to judge; every other file was judged"
Shale.fail!("find_floats_outside_unit_types: ${refusals}, ${why}")
}
if !(found.is_empty()) {
Shale.fail!(summary)
}
}
## The checks, in the order the summary counts them.
checks : List(Str)
checks = ["bare_float", "unused_exception"]
## The counts, `find_floats_outside_unit_types (Roc): N files; bare_float N,
## unused_exception N`.
summary_of : List(Finding), U64 -> Str
summary_of = |findings, file_count| {
"find_floats_outside_unit_types (Roc): ${file_count.to_str()} files; ${Finding.counts_of(findings, checks)}"
}
## The summary, each finding, then the summary again (cookbook/findings.shale):
## the first copy survives a cut output, and a gate reads the last line.
print_findings! : Str, List(Str) => {}
print_findings! = |summary, finding_lines| {
Shale.print!(summary)
if !(finding_lines.is_empty()) {
for line in finding_lines {
Shale.print!(line)
}
Shale.print!(summary)
}
}
cookbook/roc/find_floats_outside_unit_types/Exceptions.roc, 124 lines
## A project's table of the floats that stay floats (`table=`), read: each
## line `Name: reason`, a name a module or what is in it (`Pixels`,
## `Scene.fade`, `Animation.Spot.lift`). The longest line that fits a
## finding answers for it, and a line no finding needs, or one naming a
## module no file below the table's folder holds, is a finding of its own,
## `unused_exception`.
import pf.Shale
import lib.Finding
import lib.Text
import lib.Tree
Exceptions := { path : Str, excuses : List(Exceptions.Excuse) }.{
## A table's line, excusing a name's floats: the name, the module that name
## starts with, and the line's number.
Excuse : {
name : Str,
module_name : Str,
line : U64,
}
## The table at `path`, empty when `path` is `""`. A missing table, a line
## with no reason and a name listed twice each stop the run.
read! : Str => Exceptions
read! = |path| {
if path == "" {
return { path, excuses: [] }
}
if !(Shale.exists!(path)) {
Shale.fail!("find_floats_outside_unit_types: no table ${path}")
}
text = match Shale.read!(path) {
Found(found) => found
Missing => {
Shale.fail!("find_floats_outside_unit_types: no table ${path}")
""
}
}
var $excuses = []
$number : U64
var $number = 0
for raw in Text.lines(text) {
$number = $number + 1
line = Text.trim(raw)
if line != "" and !(line.starts_with("#")) {
line_place = "find_floats_outside_unit_types: ${path}:${$number.to_str()}"
name = match Shale.re_find!(line, name_pattern) {
Found(found) => excused_name(found.groups)
NoMatch => {
Shale.fail!("${line_place}: expected `Name: reason`")
""
}
}
if $excuses.any(|excuse| excuse.name == name) {
Shale.fail!("${line_place}: `${name}` is listed twice")
}
module_name = name.split_on(".").first() ?? name
$excuses = $excuses.append({ name, module_name, line: $number })
}
}
{ path, excuses: $excuses }
}
## The longest name of the table that covers `key`, a dotted name: `key`
## itself, or the part of it before one of its dots.
cover : Exceptions, Str -> Try(Str, [Uncovered])
cover = |exceptions, key| {
parts = key.split_on(".")
var $count = parts.len()
while $count >= 1 {
name = Str.join_with(parts.take_first($count), ".")
if exceptions.excuses.any(|excuse| excuse.name == name) {
return Ok(name)
}
$count = $count - 1
}
Err(Uncovered)
}
## The table's lines that excuse nothing: each naming a module no file
## below the table's folder holds, or, for a module the run read, a name
## no finding needed (`used`). A line for a module the run didn't read
## isn't judged.
find_unused! : Exceptions, { read_modules : Set(Str), used : Set(Str) } => List(Finding)
find_unused! = |exceptions, run| {
if exceptions.excuses.is_empty() {
return []
}
below = Text.path_under(Text.dirname(exceptions.path), "**/*.roc")
known = Set.from_list(Shale.glob!(below).map(Tree.module_name))
finding_at = |excuse, what| {
path: exceptions.path,
line: excuse.line,
check: "unused_exception",
what: "`${excuse.name}` ${what}",
}
var $found = []
for excuse in exceptions.excuses {
is_known = known.contains(excuse.module_name)
is_needed = run.used.contains(excuse.name)
is_read = run.read_modules.contains(excuse.module_name)
if !is_known {
$found = $found.append(finding_at(excuse, "names a module no file here holds"))
}
if is_known and is_read and !is_needed {
$found = $found.append(finding_at(excuse, "excuses nothing: no finding needs it"))
}
}
$found
}
}
## A table's line: a name of letters, digits and `_`, its parts joined by
## `.`, a part after the first perhaps ending in `!`, then `:` and a reason.
name_pattern : Str
name_pattern = "^([A-Za-z][A-Za-z0-9_]*(?:\\.[A-Za-z_][A-Za-z0-9_]*!?)*): +[^ ]"
## The name a match of `name_pattern` holds, its one group.
excused_name : List(Str) -> Str
excused_name = |groups|
match groups.first() {
Ok(name) => name
Err(_) => crash "find_floats_outside_unit_types: the table's pattern has a group, the name"
}
cookbook/roc/find_floats_outside_unit_types/Floats.roc, 145 lines
## The rule, `bare_float`: an `F64` in a top-level or member annotation or in
## a type declaration, however deep in the type (a field, a list's element, a
## tag's payload), each `F64` a finding, unless the table excuses it or a
## helper only tests use holds it. A local's annotation is the body's
## business and isn't judged.
import Exceptions
import lib.Finding
import TestHelpers
import lib.Tree
Floats := [].{
## A file Roc's parser read: its path and its tree.
ParsedFile : { path : Str, syntax_nodes : List(Tree.Node) }
## What a file's floats give: the findings, the table's names that excused
## one, and how many sit in helpers only tests use.
Judged : {
findings : List(Finding),
covered : List(Str),
in_helpers : U64,
}
## Each `F64` of the file judged.
judge_file : Floats.ParsedFile, Exceptions -> Floats.Judged
judge_file = |file, exceptions| {
var $float_places = []
$at : U64
var $at = 0
for node in file.syntax_nodes {
$at = $at + 1
if node.kind == "ty" and Tree.last_part(Tree.attribute(node, "name")) == "F64" {
$float_places = $float_places.append($at)
}
}
if $float_places.is_empty() {
return { findings: [], covered: [], in_helpers: 0 }
}
reading = { file, file_module: Tree.module_name(file.path) }
helpers = TestHelpers.helper_names(file.syntax_nodes)
var $findings = []
var $covered = []
$in_helpers : U64
var $in_helpers = 0
for place in $float_places {
match declaration_of(reading, place) {
Err(Local) => {}
Ok(found) =>
if !(found.in_type) and helpers.contains(found.name) {
$in_helpers = $in_helpers + 1
} else {
match Exceptions.cover(exceptions, found.key) {
Ok(name) => {
$covered = $covered.append(name)
}
Err(Uncovered) => {
$findings = $findings.append(bare_float(file, found))
}
}
}
}
}
{
findings: $findings,
covered: $covered,
in_helpers: $in_helpers,
}
}
}
## A file being judged, with the module its name says it holds.
Reading : { file : Floats.ParsedFile, file_module : Str }
## Where a float is declared: `key`, its dotted name (`Scene.Spot.lift`);
## `declaration`, the place of the annotation or type declaration holding
## it, and `name`, that declaration's own; whether a type's block holds it;
## and the float's own line.
Declared : {
key : Str,
declaration : U64,
name : Str,
in_type : Bool,
line : U64,
}
## Where the `F64` at `place` is declared, or `Local` when it belongs to a
## local's annotation or a body. A type's own module isn't repeated in its
## key, so `Unit :: F64` in Unit.roc is `Unit`.
declaration_of : Reading, U64 -> Try(Declared, [Local])
declaration_of = |reading, place| {
syntax_nodes = reading.file.syntax_nodes
float_node = Tree.node_at(syntax_nodes, place)
var $names = []
$declaration : U64
var $declaration = 0
var $in_type = Bool.False
var $above = float_node.parent
while $above != 0 {
node = Tree.node_at(syntax_nodes, $above)
kind = node.kind
if kind.starts_with("e-") or kind.starts_with("p-") or kind == "s-decl" {
return Err(Local)
}
if kind == "anno-record-field" or kind == "s-type-anno" {
$names = [Tree.attribute(node, "name")].concat($names)
}
if kind == "s-type-decl" {
type_name = Tree.attribute(Tree.node_at(syntax_nodes, Tree.kid_at(node, 1)), "name")
if type_name != reading.file_module {
$names = [type_name].concat($names)
}
$in_type = Bool.True
}
if (kind == "s-type-anno" or kind == "s-type-decl") and $declaration == 0 {
$declaration = $above
}
$above = node.parent
}
Ok({
key: Str.join_with([reading.file_module].concat($names), "."),
declaration: $declaration,
name: Tree.attribute(Tree.node_at(syntax_nodes, $declaration), "name"),
in_type: $in_type,
line: float_node.line,
})
}
## A `bare_float` finding: the float's key and the declaration's whole type,
## what a reader will find at the line.
bare_float : Floats.ParsedFile, Declared -> Finding
bare_float = |file, found| {
declaration = Tree.node_at(file.syntax_nodes, found.declaration)
type_place = if declaration.kind == "s-type-anno" {
Tree.kid_at(declaration, 1)
} else {
Tree.kid_at(declaration, 2)
}
type_text = Tree.written_type(file.syntax_nodes, type_place)
{
path: file.path,
line: found.line,
check: "bare_float",
what: "`${found.key}` has a bare `F64`: ${type_text}",
}
}
cookbook/roc/find_floats_outside_unit_types/SelfTest.roc, 268 lines
## The recipe's self-test: each plant under
## cookbook/roc/plants/find_floats_outside_unit_types/ run through the launcher, held to its
## findings, its exit and what it says. It copies
## cookbook/roc/find_names_that_differ_across_lookalike_modules/SelfTest.roc's runner, on purpose: a row is
## run through `Shale.run!`, and cookbook/roc/lib/, a package, reaches no
## effect.
import pf.Shale
SelfTest := [].{
## Each row run as a child of its own, through `launcher`; a check of
## `checks` no row fires fails too, since it could be blind.
run! : List(Str) => {}
run! = |checks| {
$wrong : U64
var $wrong = 0.U64
var $fired = Set.empty()
for row in rows {
command = ["shale", launcher, "glob=${row.plant}"].concat(row.arguments)
result = Shale.run!({
argv: command,
keep: Whole(4000000),
timeout_ms: 120000,
want: "",
})
faults = find_faults!(row, result, checks)
for (check, _) in row.counts {
$fired = $fired.insert(check)
}
if faults.is_empty() {
Shale.print!("ok ${row.plant}")
} else {
Shale.print!("FAIL ${row.plant}: ${Str.join_with(faults, "; ")}")
$wrong = $wrong + 1
Shale.print!(result.out)
}
}
for check in checks {
if !($fired.contains(check)) {
Shale.print!("FAIL `${check}` has no plant")
$wrong = $wrong + 1
}
}
if $wrong > 0 {
Shale.fail!("find_floats_outside_unit_types self_test: ${$wrong.to_str()} wrong")
}
row_count = rows.len().to_str()
proof = "each plant gives its findings and a nonzero exit, each clean case none and exit 0"
Shale.print!("find_floats_outside_unit_types self_test: PASS (${row_count} rows: ${proof})")
}
}
## The launcher, which the self-test runs each plant through.
launcher : Str
launcher = "cookbook:roc/find_floats_outside_unit_types.shale"
plants : Str
plants = "cookbook:roc/plants/find_floats_outside_unit_types/"
## A plant's run: its files (a glob below `plants`) and its other arguments,
## the findings each check must print, the literals its output must hold,
## and whether it must stop without a finding.
Row : {
plant : Str,
arguments : List(Str),
counts : List((Str, U64)),
says : List(Str),
stops : Bool,
}
## A plant's run, before its place below `plants` is spelled out.
Wanted : {
plant : Str,
arguments : List(Str),
counts : List((Str, U64)),
says : List(Str),
}
## A plant that must give its findings, or none when `counts` is empty.
gives : Wanted -> Row
gives = |wanted| {
plant: "${plants}${wanted.plant}",
arguments: wanted.arguments,
counts: wanted.counts,
says: wanted.says,
stops: Bool.False,
}
## What a plant that stops is run with and must say.
Stopping : {
plant : Str,
arguments : List(Str),
says : List(Str),
}
## A plant that must stop before any finding, saying what it says.
stops : Stopping -> Row
stops = |wanted| {
plant: "${plants}${wanted.plant}",
arguments: wanted.arguments,
counts: [],
says: wanted.says,
stops: Bool.True,
}
## The table argument for a table below `plants`.
table : Str -> Str
table = |name| "table=${plants}${name}"
rows : List(Row)
rows = [
gives({
plant: "Signatures.roc",
arguments: [],
counts: [("bare_float", 12)],
says: [
"Signatures.roc:5: bare_float: `Signatures.Reading` has a bare `F64`: F64",
"`Signatures.scaled` has a bare `F64`: (Reading, F64 -> Reading)",
"`Signatures.Trip.length` has a bare `F64`: { length : F64, name : Str }",
"`Signatures.pair` has a bare `F64`: (F64, F64)",
],
}),
gives({ plant: "Quiet.roc", arguments: [], counts: [], says: [] }),
gives({
plant: "Helpers.roc",
arguments: [],
counts: [("bare_float", 7)],
says: [
"`Helpers.used_by_a_member` has",
"`Helpers.used_by_a_definition` has",
"`Helpers.reached_from_production` has",
"`Helpers.in_a_short_record` has",
"`Helpers.used_by_nothing` has",
"`Helpers.only_itself` has",
"`Helpers.member_tests_use` has",
],
}),
gives({
plant: "QuietHelpers.roc",
arguments: [],
counts: [],
says: ["3 bare `F64`s are in helpers only tests use"],
}),
gives({
plant: "helpers_app.roc",
arguments: [],
counts: [("bare_float", 1)],
says: ["`helpers_app.only_tests` has"],
}),
gives({
plant: "whole/*.roc",
arguments: [],
counts: [("bare_float", 7)],
says: [],
}),
gives({
plant: "whole/*.roc",
arguments: [table("whole/table.txt")],
counts: [],
says: [],
}),
gives({
plant: "whole/*.roc",
arguments: [table("whole/narrow.txt")],
counts: [("bare_float", 2)],
says: ["`Held.Spot.left_out` has a bare", "`Held.other` has a bare"],
}),
gives({
plant: "whole/*.roc",
arguments: [table("whole/shadowed.txt")],
counts: [("unused_exception", 1)],
says: ["`Held` excuses nothing"],
}),
gives({
plant: "whole/*.roc",
arguments: [table("whole/unused.txt")],
counts: [("unused_exception", 4)],
says: [
"unused.txt:4: unused_exception: `Held.gone` excuses nothing",
"`Unit.plus` excuses nothing",
"`Held.Spot.gone` excuses nothing",
"`Vanished` names a module no file here holds",
],
}),
gives({
plant: "whole/Held.roc",
arguments: [table("whole/table.txt")],
counts: [],
says: [],
}),
gives({
plant: "whole/Unit.roc",
arguments: [table("whole/unused.txt")],
counts: [("unused_exception", 2)],
says: ["`Unit.plus` excuses nothing", "`Vanished` names a module"],
}),
stops({ plant: "broken/*.roc", arguments: [], says: ["refused: "] }),
stops({
plant: "Quiet.roc",
arguments: [table("no_such.txt")],
says: ["no table"],
}),
stops({
plant: "Quiet.roc",
arguments: [table("table_no_reason.txt")],
says: ["table_no_reason.txt:2: expected"],
}),
stops({
plant: "Quiet.roc",
arguments: [table("table_twice.txt")],
says: ["`Quiet.name` is listed twice"],
}),
]
## The last line of `out` that isn't one of Shale's `──` lines.
last_said : Str -> Str
last_said = |out|
out.trim().split_on("\n").fold(
"",
|last, line|
if line.starts_with("──") or line.trim() == "" {
last
} else {
line
},
)
## The findings `row` wants of `check`.
wanted_count : Row, Str -> U64
wanted_count = |row, check| {
$wanted : U64
var $wanted = 0
for (counted, count) in row.counts {
if counted == check {
$wanted = count
}
}
$wanted
}
## What is wrong with one row's run.
find_faults! : Row, { code : I64, out : Str }, List(Str) => List(Str)
find_faults! = |row, result, checks| {
must_fail = row.stops or !(row.counts.is_empty())
var $faults = []
if must_fail and result.code == 0 {
$faults = $faults.append("it exited 0")
}
if !(must_fail) and result.code != 0 {
$faults = $faults.append("it exited ${result.code.to_str()}")
}
for check in checks {
found = Shale.re_lines!(result.out, "^[^ ]+:[0-9]+: ${check}: ").len()
wanted = wanted_count(row, check)
if found != wanted {
$faults = $faults.append("${check} printed ${found.to_str()}, not ${wanted.to_str()}")
}
}
if !(row.stops) and !(last_said(result.out).contains(" files; ")) {
$faults = $faults.append("its last line is no summary: ${last_said(result.out)}")
}
for literal in row.says {
if !(result.out.contains(literal)) {
$faults = $faults.append("its output lacks `${literal}`")
}
}
$faults
}
cookbook/roc/find_floats_outside_unit_types/TestHelpers.roc, 161 lines
## The helpers only tests use, whose floats aren't judged. A helper is a
## definition at the top level of a type module, outside the type's block,
## which the compiler lets no other module reach, so the file's own tree
## shows everything that uses it. It is one when every use is in an `expect`
## or in another such helper, and there is one. An app's or a `module [...]`
## file's top-level names can be reached from outside, so they have none. A
## local that shares a helper's name counts as a use, which can only report
## more.
import lib.Tree
TestHelpers := [].{
## The names of the file's helpers only tests use.
helper_names : List(Tree.Node) -> Set(Str)
helper_names = |nodes| {
if !(is_type_module(nodes)) {
return Set.empty()
}
definitions = top_level_definitions(nodes)
uses = places_of_uses(nodes, definitions)
var $helpers = Set.from_list(
uses
.to_list()
.keep_if(|(_, places)| !(places.is_empty()))
.map(|(name, _)| name),
)
# A helper falls when anything outside tests uses it, which can bring
# down the helpers only it used.
var $changed = Bool.True
while $changed {
$changed = Bool.False
for (name, places) in uses.to_list() {
if $helpers.contains(name) {
var $falls = Bool.False
for place in places.to_list() {
if place != in_a_test and !($helpers.contains(place)) {
$falls = Bool.True
}
}
if $falls {
$helpers = $helpers.remove(name)
$changed = Bool.True
}
}
}
}
$helpers
}
}
## The place of a node inside a test.
in_a_test : Str
in_a_test = "expect"
## The place of a node in neither a definition nor a test.
in_no_definition : Str
in_no_definition = ""
## The place of a node's parent, which comes before it.
place_of_parent : List(Str), Tree.Node -> Str
place_of_parent = |places, node|
match places.get(node.parent - 1) {
Ok(place) => place
Err(_) => crash "find_floats_outside_unit_types: a node before its parent"
}
## Whether the file is a type module, with a `type-mod` header.
is_type_module : List(Tree.Node) -> Bool
is_type_module = |nodes|
Tree.node_at(nodes, 1).kids.any(|kid| Tree.node_at(nodes, kid).kind == "type-mod")
## The definitions at the top level of the file, outside any type's block:
## each name with its `s-decl`'s place, the last one where a name is defined
## twice.
top_level_definitions : List(Tree.Node) -> Dict(Str, U64)
top_level_definitions = |nodes| {
var $found = Dict.empty()
for top in Tree.node_at(nodes, 1).kids {
statements = Tree.node_at(nodes, top)
if statements.kind == "statements" {
for place in statements.kids {
statement = Tree.node_at(nodes, place)
if statement.kind == "s-decl" {
match statement.kids.first() {
Ok(pattern_place) => {
pattern = Tree.node_at(nodes, pattern_place)
if pattern.kind == "p-ident" {
$found = $found.insert(Tree.attribute(pattern, "raw"), place)
}
}
Err(_) => {}
}
}
}
}
}
$found
}
## Where each definition is used: its name with the places of its uses, a
## place being the definition the use sits in, `in_a_test` in a test, and
## `""` anywhere else. A definition's use of itself is no place. A parent
## comes before its kids, so one pass gives each node its place.
places_of_uses : List(Tree.Node), Dict(Str, U64) -> Dict(Str, Set(Str))
places_of_uses = |nodes, definitions| {
var $defined_at = Dict.empty()
for (name, place) in definitions.to_list() {
$defined_at = $defined_at.insert(place, name)
}
var $uses = Dict.empty()
for (name, _) in definitions.to_list() {
$uses = $uses.insert(name, Set.empty())
}
var $places = []
$at : U64
var $at = 0
for node in nodes {
$at = $at + 1
above = if node.parent == 0 {
""
} else {
place_of_parent($places, node)
}
in_test = if node.kind == "s-expect" {
in_a_test
} else {
above
}
here = if in_test == "" {
match $defined_at.get($at) {
Ok(name) => name
Err(_) => in_no_definition
}
} else {
in_test
}
$places = $places.append(here)
used = name_used(node)
if used != "" and used != here {
match $uses.get(used) {
Ok(places) => {
$uses = $uses.insert(used, places.insert(here))
}
Err(_) => {}
}
}
}
$uses
}
## The name a node uses, or `""`: an identifier, or a field in a record's
## short form, `{ a, b }`, which uses `a` and `b`.
name_used : Tree.Node -> Str
name_used = |node|
if node.kind == "e-ident" {
Tree.attribute(node, "raw")
} else if node.kind == "field" and node.kids.is_empty() {
Tree.attribute(node, "field")
} else {
""
}
Shale original
cookbook/roc/find_bare_floats.shale, 300 lines, at bf8605c5
The libraries it loads: cookbook/roc/declared.shale (1,075 lines), cookbook/findings.shale (21 lines), cookbook/roc/parsed.shale (34 lines), cookbook/roc/gate_recipe.shale (102 lines).
-- This recipe finds every bare `F64` in a project's declarations, for a project
-- that keeps its floats inside unit types. What must stay a float is named in
-- the project's table, with a reason.
--
-- cd <repo> && shale cookbook:roc/find_bare_floats.shale table=bare_floats.txt
-- shale cookbook:roc/find_bare_floats.shale self_test=1
--
-- The arguments:
-- glob the files to check, `**/*.roc` by default;
-- table the project's exceptions, without which every `F64` is a finding;
-- self_test with `self_test=1`, check the plants in
-- `cookbook/roc/plants/find_bare_floats/`.
--
-- Each line of the table is `Name: reason`. A name is a module, or what is in
-- it: `Pixels`, `Scene.fade`, `Animation.Spot.lift`. A type's own module isn't
-- repeated, so `to_metres` in `Distance.roc` is `Distance.to_metres`, whether
-- or not it is a member of the type `Distance`. A record field's name follows
-- what declares it. A line covers its name and whatever is inside it, and only
-- the longest line that fits a finding answers for it. A blank line or one
-- starting with `#` is skipped, and a line with no reason or a name listed
-- twice stops the run.
--
-- The checks:
--
-- bare_float An `F64` in a top-level or member annotation or in a type
-- declaration, however deep in the type: a field, a list's
-- element, a tag's payload. Each `F64` is a finding, so a
-- signature with two gives two. A local's annotation is the
-- body's business and isn't judged. A constant with no
-- annotation has no signature, so it can't be judged.
-- unused_exception A line of the table that no finding needs, or that names
-- a module no file below the table's folder holds. A line
-- for a module the run didn't read isn't judged, so a run
-- over part of a tree still fails only for what it read.
--
-- A helper only tests use is test code and isn't judged, and a line tells it
-- so at the top of the output. It is a definition at the top level of a type
-- module, outside the type's block, which the compiler lets no other module
-- reach, so a file's own text shows everything that uses it. Every use must be
-- in an `expect` or in another such helper, and there must be one. The file has
-- to be a type module for this: an app's or a `module [...]` file's top-level
-- names can be reached from outside, so its helpers are always judged. A local
-- that shares a helper's name counts as a use, which can only report more.
--
-- The output is the counts, one line per finding, and the counts again
-- (cookbook/findings.shale). The run fails if there are findings, or if
-- any file doesn't parse, and the files that do parse are judged either way.
-- budget: steps=800000000 arena_bytes=2000000000 output_bytes=4000000
const SELF_TEST = arg("self_test", "") == "1"
const GLOB = arg("glob", "**/*.roc")
const TABLE_FILE = arg("table", "")
use("./declared.shale")
use("cookbook:findings.shale")
use("./parsed.shale")
use("./gate_recipe.shale")
const CHECKS = {"bare_float", "unused_exception"}
-- The table as `{lines, by_name, used}`: its lines in order, each `{name,
-- module, line}`, the same by name, and an empty set `judge_float` fills.
function exception_table(path)
local lines_of_table = {}
local by_name = {}
if path == "" then return {lines = lines_of_table, by_name = by_name, used = {}} end
if not exists(path) then fail("find_bare_floats: no table " .. path) end
local number = 0
for raw in lines(read(path)) do
number = number + 1
local l = trim(raw)
if l ~= "" and not starts_with(l, "#") then
local m = re_find(l, "^([A-Za-z][A-Za-z0-9_]*(?:\\.[A-Za-z_][A-Za-z0-9_]*!?)*): +[^ ]")
if m == nil then fail("find_bare_floats: " .. path .. ":" .. number .. ": expected `Name: reason`") end
if has_key(by_name, m.group) then fail("find_bare_floats: " .. path .. ":" .. number .. ": `" .. m.group .. "` is listed twice") end
local entry = {name = m.group, module = split(m.group, ".")[1], line = number}
push(lines_of_table, entry)
by_name[m.group] = entry
end
end
return {lines = lines_of_table, by_name = by_name, used = {}}
end
-- The longest name of the table that covers `key`, or nil.
function exception_for(exceptions, key)
local parts = split(key, ".")
local n = #parts
while n >= 1 do
local name = join(take(parts, n), ".")
if has_key(exceptions.by_name, name) then return name end
n = n - 1
end
return nil
end
function is_type_module(tree)
for at in children(tree, 1) do
if tree[at].kind == "type-mod" then return true end
end
return false
end
-- Where the `F64` at `at` is declared, or nil when it belongs to a local. `key`
-- is its dotted name, `declaration` the annotation or type declaration holding
-- it, `name` that declaration's own name, and `in_type` whether a type's block
-- holds it.
function declaration_of(tree, at, module)
local names = {}
local declaration = 0
local in_type = false
local k = tree[at].parent
while k ~= 0 do
local kind = tree[k].kind
if starts_with(kind, "e-") or starts_with(kind, "p-") or kind == "s-decl" then return nil end
if kind == "anno-record-field" or kind == "s-type-anno" then push(names, attribute(tree, k, "name")) end
if kind == "s-type-decl" then
local type_name = attribute(tree, children(tree, k)[1], "name")
if type_name ~= module then push(names, type_name) end
in_type = true
end
if (kind == "s-type-anno" or kind == "s-type-decl") and declaration == 0 then declaration = k end
k = tree[k].parent
end
local parts = {module}
local i = #names
while i >= 1 do
push(parts, names[i])
i = i - 1
end
return {key = join(parts, "."), declaration = declaration, in_type = in_type, name = attribute(tree, declaration, "name")}
end
-- The node's type as text, for a finding: what a reader will find at the line.
function declared_type_text(tree, at)
local kids = children(tree, at)
if tree[at].kind == "s-type-anno" then return render_type(tree, kids[1]) end
return render_type(tree, kids[2])
end
-- The name a node uses, or "": an identifier, or a field in a record's short
-- form, `{ a, b }`, which uses `a` and `b`.
function name_used(tree, at)
local node = tree[at]
if node.kind == "e-ident" then return node.raw end
if node.kind == "field" and #node.kids == 0 then return get(node, "field", "") end
return ""
end
-- The definitions at the top level of the file, outside any type's block, as a
-- map from each name to its `s-decl`.
function top_level_definitions(tree)
local found = {}
for at in children(tree, 1) do
if tree[at].kind == "statements" then
for s in children(tree, at) do
if tree[s].kind == "s-decl" then
local kids = children(tree, s)
if #kids > 0 and tree[kids[1]].kind == "p-ident" then found[attribute(tree, kids[1], "raw")] = s end
end
end
end
end
return found
end
-- The helpers only tests use, by the rule the header gives: a map from each
-- top-level definition to whether it is one.
-- Each node's `place` is the helper it sits in, `expect` in a test, and "" for
-- anything else. A parent comes before its children, so one pass fills it.
function test_only_helpers(tree)
local helpers = {}
if not is_type_module(tree) then return helpers end
local definitions = top_level_definitions(tree)
local definition_at = {}
for name in keys(definitions) do definition_at[tostring(definitions[name])] = name end
local place = {}
local places_of = {}
for name in keys(definitions) do places_of[name] = {} end
for i = 1, #tree do
local node = tree[i]
local here = node.parent == 0 and "" or place[node.parent]
if node.kind == "s-expect" then here = "expect" end
if here == "" and has_key(definition_at, tostring(i)) then here = definition_at[tostring(i)] end
push(place, here)
local used = name_used(tree, i)
if used ~= "" and has_key(places_of, used) and here ~= used then places_of[used][here] = true end
end
for name in keys(definitions) do
helpers[name] = #keys(places_of[name]) > 0
end
-- A helper falls when anything outside tests uses it, which can bring down
-- the helpers only it used.
local changed = true
while changed do
changed = false
for name in keys(helpers) do
for used_at in keys(places_of[name]) do
if helpers[name] and used_at ~= "expect" and not get(helpers, used_at, false) then
helpers[name] = false
changed = true
end
end
end
end
return helpers
end
-- Judges the one `F64` at `at`, and gives 1 when a test's helper holds it.
function judge_float(f, at, module, helpers, exceptions, report)
local tree = f.nodes
local where = declaration_of(tree, at, module)
if where == nil then return 0 end
if not where.in_type and get(helpers, where.name, false) then return 1 end
local covered_by = exception_for(exceptions, where.key)
if covered_by ~= nil then
exceptions.used[covered_by] = true
return 0
end
push(report, {path = f.path, line = tree[at].line, check = "bare_float", what = "`" .. where.key .. "` has a bare `F64`: " .. declared_type_text(tree, where.declaration)})
return 0
end
-- Judges one file, and gives how many of its floats belong to tests' helpers.
function judge_file(f, exceptions, report)
local tree = f.nodes
local module = module_name(f.path)
local helpers = test_only_helpers(tree)
local in_helpers = 0
for i = 1, #tree do
if tree[i].kind == "ty" and last_part(attribute(tree, i, "name")) == "F64" then
in_helpers = in_helpers + judge_float(f, i, module, helpers, exceptions, report)
end
end
return in_helpers
end
function judge_exceptions(exceptions, read_modules, report)
if #exceptions.lines == 0 then return nil end
local known = {}
for p in glob(path_under(dirname(TABLE_FILE), "**/*.roc")) do known[module_name(p)] = true end
for e in exceptions.lines do
if not has_key(known, e.module) then
push(report, {path = TABLE_FILE, line = e.line, check = "unused_exception", what = "`" .. e.name .. "` names a module no file here holds"})
elseif has_key(read_modules, e.module) and not has_key(exceptions.used, e.name) then
push(report, {path = TABLE_FILE, line = e.line, check = "unused_exception", what = "`" .. e.name .. "` excuses nothing: no finding needs it"})
end
end
return nil
end
function self_test()
local at = "cookbook:roc/plants/find_bare_floats/"
local recipe = "cookbook:roc/find_bare_floats.shale"
local table_arg = "table=" .. at .. "whole/table.txt"
check_plants("find_bare_floats", recipe, CHECKS, {
{glob = at .. "Signatures.roc", counts = {bare_float = 12}, says = {"Signatures.roc:5: bare_float: `Signatures.Reading` has a bare `F64`: F64", "`Signatures.scaled` has a bare `F64`: (Reading, F64 -> Reading)", "`Signatures.Trip.length` has a bare `F64`: { length : F64, name : Str }", "`Signatures.pair` has a bare `F64`: (F64, F64)"}},
{glob = at .. "Quiet.roc"},
{glob = at .. "Helpers.roc", counts = {bare_float = 7}, says = {"`Helpers.used_by_a_member` has", "`Helpers.used_by_a_definition` has", "`Helpers.reached_from_production` has", "`Helpers.in_a_short_record` has", "`Helpers.used_by_nothing` has", "`Helpers.only_itself` has", "`Helpers.member_tests_use` has"}},
{glob = at .. "QuietHelpers.roc", says = {"3 bare `F64`s are in helpers only tests use"}},
{glob = at .. "helpers_app.roc", counts = {bare_float = 1}, says = {"`helpers_app.only_tests` has"}},
{glob = at .. "whole/*.roc", counts = {bare_float = 7}},
{glob = at .. "whole/*.roc", args = {table_arg}},
{glob = at .. "whole/*.roc", args = {"table=" .. at .. "whole/narrow.txt"}, counts = {bare_float = 2}, says = {"`Held.Spot.left_out` has a bare", "`Held.other` has a bare"}},
{glob = at .. "whole/*.roc", args = {"table=" .. at .. "whole/shadowed.txt"}, counts = {unused_exception = 1}, says = {"`Held` excuses nothing"}},
{glob = at .. "whole/*.roc", args = {"table=" .. at .. "whole/unused.txt"}, counts = {unused_exception = 4}, says = {"unused.txt:4: unused_exception: `Held.gone` excuses nothing", "`Unit.plus` excuses nothing", "`Held.Spot.gone` excuses nothing", "`Vanished` names a module no file here holds"}},
{glob = at .. "whole/Held.roc", args = {table_arg}},
{glob = at .. "whole/Unit.roc", args = {"table=" .. at .. "whole/unused.txt"}, counts = {unused_exception = 2}, says = {"`Unit.plus` excuses nothing", "`Vanished` names a module"}},
{glob = at .. "broken/*.roc", stops = true, says = {"refused: "}},
{glob = at .. "Quiet.roc", args = {"table=" .. at .. "no_such.txt"}, stops = true, says = {"no table"}},
{glob = at .. "Quiet.roc", args = {"table=" .. at .. "table_no_reason.txt"}, stops = true, says = {"table_no_reason.txt:2: expected"}},
{glob = at .. "Quiet.roc", args = {"table=" .. at .. "table_twice.txt"}, stops = true, says = {"`Quiet.name` is listed twice"}},
})
return nil
end
function run_check()
local exceptions = exception_table(TABLE_FILE)
local paths = glob(GLOB)
local parsed = parse_roc_files(paths)
local report = {}
local read_modules = {}
local in_helpers = 0
for f in parsed.files do
read_modules[module_name(f.path)] = true
in_helpers = in_helpers + judge_file(f, exceptions, report)
end
judge_exceptions(exceptions, read_modules, report)
if in_helpers > 0 then print(in_helpers .. " bare `F64`s are in helpers only tests use, and aren't judged") end
local verdict = verdict_of("find_bare_floats", CHECKS, report, #paths)
print_findings(verdict.summary, verdict.found)
fail_if_refused("find_bare_floats", parsed.refused)
return verdict
end
-- This `fail` stands at the top level so the summary is the last line a
-- caller reads: a stop inside a function prints the calls after it.
if SELF_TEST then
self_test()
else
local verdict = run_check()
if #verdict.found > 0 then fail(verdict.summary) end
end