find_names_that_differ_across_lookalike_modules
Roc
It also imports Declarations, Finding, Headers, Text, Tree from the shared Roc library.
## find_names_that_differ_across_lookalike_modules, in Roc on Shale's platform (roc_platform/README.md):
## modules that look alike but are spelled unlike, and one type name with two
## meanings. A reader who knows `TreeSighting.trees_in_view` looks for
## `RailSighting.rails_in_view`, and one who knows `Cat.Pose` reads
## `Geom.Pose` as the same thing, so a family spelled unlike or a twin of
## another shape costs every reader a wrong guess. Its launcher,
## cookbook/roc/find_names_that_differ_across_lookalike_modules.shale, is how it is run, and its header says
## the rules, `family`, `twin_name` and `unpaired_conversion`. check_goldens.shale, beside this,
## holds its output on the plants to its goldens, line for line.
##
## cd <repo> && shale cookbook:roc/find_names_that_differ_across_lookalike_modules.shale roles=tools/type_roles.txt
## shale cookbook:roc/find_names_that_differ_across_lookalike_modules.shale self_test=1
##
## The arguments: `glob` (`**/*.roc`), `roles` (a file of type names each
## module may declare for itself) and `self_test` (`self_test=1` runs the
## plants, each through the launcher).
##
## This root globs the files (`Shale.glob!`), has Roc's parser read them
## (`Shale.roc_tree!`) and each one's text (`Shale.read!`), reads the roles
## file, and prints the verdict (`Shale.print!`, `Shale.fail!`). Its modules
## are beside it, a module a check (Family, Twin, Conversion) and SelfTest; what they read
## (Tree, Declarations, 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 lib.Declarations
import lib.Finding
import lib.Text
import lib.Tree
import Conversion
import Family
import SelfTest
import Twin
main! : {} => {}
main! = |{}| {
if Shale.arg!("self_test", "") == "1" {
SelfTest.run!(checks)
} else {
run_check!({})
}
}
## What one parsed file gives the checks.
ParsedFile : { is_app : Bool, read : Family.FileRead }
## 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.
run_check! : {} => {}
run_check! = |{}| {
paths = Shale.glob!(Shale.arg!("glob", "**/*.roc"))
var $files = []
var $refused = []
for file in Shale.roc_tree!(paths) {
if file.err == "" {
source_lines = read_text!(file.path).split_on("\n")
read = {
path: file.path,
declared: Declarations.from_file({ path: file.path, nodes: file.nodes, source_lines }),
source_lines,
}
$files = $files.append({ is_app: Tree.is_app(file.nodes), read })
} else if file.err.starts_with(file.path) {
$refused = $refused.append(file.err)
} else {
$refused = $refused.append("${file.path}: ${file.err}")
}
}
findings = run_checks!($files)
found = findings.sort_with(Finding.order).map(Finding.line_of)
summary = summary_of(findings, 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_names_that_differ_across_lookalike_modules: ${refusals}, ${why}")
}
if !(found.is_empty()) {
Shale.fail!(summary)
}
}
## The checks over the files that parsed, the roles file read for
## `twin_name`.
run_checks! : List(ParsedFile) => List(Finding)
run_checks! = |files| {
family_findings = Family.findings(modules_of(files))
roles_file = Shale.arg!("roles", "")
roles = if roles_file == "" {
Set.empty()
} else {
read_word_set!(roles_file)
}
twin_files = files
.keep_if(|file| !(file.is_app))
.map(|file| { path: file.read.path, types: file.read.declared.types })
conversion_findings = Conversion.findings(files.map(|file| file.read.declared.values).join())
family_findings.concat(Twin.findings(twin_files, roles)).concat(conversion_findings)
}
## The modules among the files read, in their order.
modules_of : List(ParsedFile) -> List(Family.Module)
modules_of = |files| {
var $modules = []
for file in files {
match Family.module_of(file.read) {
IsModule(found) => {
$modules = $modules.append(found)
}
NoModule => {}
}
}
$modules
}
## The file's text. A file the parser read and the read finds gone stops the
## run.
read_text! : Str => Str
read_text! = |path|
match Shale.read!(path) {
Found(text) => text
Missing => {
Shale.fail!("find_names_that_differ_across_lookalike_modules: ${path} went missing during the check")
""
}
}
## A list of one word a line, any note after `--` cut off, as a set. A
## missing file, a word listed twice, or a line of two words stops the run.
read_word_set! : Str => Set(Str)
read_word_set! = |path| {
text = match Shale.read!(path) {
Found(found) => found
Missing => {
Shale.fail!("no word list ${path}")
""
}
}
var $words = Set.empty()
for line in Text.lines(text) {
word = Text.trim(Text.before_first(line, "--"))
if word.contains(" ") or $words.contains(word) {
Shale.fail!("${path}: `${word}` is no single new word")
}
if word != "" {
$words = $words.insert(word)
}
}
$words
}
## The checks, in the order the summary counts them.
checks : List(Str)
checks = ["family", "twin_name", "unpaired_conversion"]
## The counts, `find_names_that_differ_across_lookalike_modules (Roc): N files; family N, twin_name N,
## unpaired_conversion N`.
summary_of : List(Finding), U64 -> Str
summary_of = |findings, file_count| {
"find_names_that_differ_across_lookalike_modules (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_names_that_differ_across_lookalike_modules/Conversion.roc, 42 lines
## The `unpaired_conversion` check: inside a type's braces, a function named
## for a noun that gives the type, such as `Distance.metres : F64 ->
## Distance`, when the same type has `to_<noun>`. `Distance.to_metres` turns
## a distance into metres, so the way back reads `Distance.from_metres`, and
## a bare `metres` beside it leaves the reader to guess which way it goes. A
## constructor with no `to_` partner, such as `Clock.at_step`, is no finding.
import lib.Declarations
import lib.Finding
Conversion := [].{
## Each function that gives its own type and has a `to_` partner of its
## name in the same type, a finding, in the order of `values`.
findings : List(Declarations.ValueDeclared) -> List(Finding)
findings = |values| {
names = Set.from_list(values.map(member_key))
is_unpaired = |value| {
gives_its_type = value.is_function and value.result_type == value.owner
partner = member_key({ ..value, name: "to_${value.name}" })
value.owner != "" and gives_its_type and names.contains(partner)
}
values.keep_if(is_unpaired).map(unpaired_finding)
}
}
## A type's member, by its file, its type and its name.
member_key : Declarations.ValueDeclared -> Str
member_key = |value| "${value.path} ${value.owner}.${value.name}"
## The finding of a conversion into the type that isn't named `from_`.
unpaired_finding : Declarations.ValueDeclared -> Finding
unpaired_finding = |value| {
owner = value.owner
name = value.name
beside = "`${owner}.${name}` gives its own type beside `${owner}.to_${name}`"
{
path: value.path,
line: value.line,
check: "unpaired_conversion",
what: "${beside}: name it `from_${name}`, the way back",
}
}
cookbook/roc/find_names_that_differ_across_lookalike_modules/Family.roc, 198 lines
## The `family` check. Modules whose names end in the same word form a family
## when there are three or more of them (`CatSighting`, `TreeSighting`,
## `RailSighting`). A public name that more than half of a family's members
## have is the family's, and each member without it is a finding, unless the
## member names the missing name in its file's opening comment or the doc
## above its type, to say why it differs. A reader who knows one member then
## finds the others' names without looking.
import lib.Declarations
import lib.Finding
import lib.Headers
import lib.Text
import lib.Tree
Family := [].{
## A module: a file that declares a type named for itself at the top
## level, with the names of that type's members, and the text its doc
## gives (the file's opening comment and the comment above its type).
Module : {
name : Str,
path : Str,
line : U64,
members : Set(Str),
doc : Str,
}
## A file as the check reads it: its path, what it declares, and its lines.
FileRead : {
path : Str,
declared : Declarations,
source_lines : List(Str),
}
## The file's module, when it declares one with any member that isn't a
## method Roc calls by name.
module_of : Family.FileRead -> [IsModule(Family.Module), NoModule]
module_of = |file| {
name = Tree.module_name(file.path)
line = module_line(file.declared.types, name)
is_member = |value| value.owner == name and !(Headers.language_fixed_names.contains(value.name))
members = Set.from_list(file.declared.values.keep_if(is_member).map(|value| value.name))
if line == 0 or members.is_empty() {
NoModule
} else {
opening = Str.join_with(opening_comment(file.source_lines), " ")
doc = "${opening} ${doc_above(file.source_lines, line)}"
IsModule({
name,
path: file.path,
line,
members,
doc,
})
}
}
## Each member that lacks a name most of its family has, a finding.
findings : List(Family.Module) -> List(Finding)
findings = |modules| {
var $families = Dict.empty()
for member in modules {
match last_word(member.name) {
Ok(word) => {
$families = $families.insert(word, ($families.get(word) ?? []).append(member))
}
Err(OneWord) => {}
}
}
$families
.to_list()
.sort_with(|(a, _), (b, _)| Text.byte_order(a, b))
.map(|(word, members)| family_findings(word, members))
.join()
}
}
## The smallest family.
smallest_family : U64
smallest_family = 3
## The line of the last top-level type named `name`, the module's own, or 0.
module_line : List(Declarations.TypeDeclared), Str -> U64
module_line = |types, name| {
var $line = 0
for declared in types {
if declared.name == name and declared.owner == "" {
$line = declared.line
}
}
$line
}
## How many of `members` have each name, by name.
holder_counts : List(Family.Module) -> Dict(Str, U64)
holder_counts = |members| {
var $counts = Dict.empty()
for member in members {
for name in member.members.to_list() {
counted = match $counts.get(name) {
Ok(count) => count + 1
Err(_) => 1
}
$counts = $counts.insert(name, counted)
}
}
$counts
}
## The findings of the family whose names end in `word`.
family_findings : Str, List(Family.Module) -> List(Finding)
family_findings = |word, members| {
if members.len() < smallest_family {
return []
}
var $found = []
counts = holder_counts(members).to_list().sort_with(|(a, _), (b, _)| Text.byte_order(a, b))
for (name, holder_count) in counts {
if holder_count * 2 > members.len() {
for member in members {
if !(member.members.contains(name)) and !(member.doc.contains("`${name}`")) {
gap = {
member,
name,
holder_count,
member_count: members.len(),
word,
}
$found = $found.append(missing_name(gap))
}
}
}
}
$found
}
## A member without a name its family has: the name, how many of the
## family's members have it, and the family's last word.
Gap : {
member : Family.Module,
name : Str,
holder_count : U64,
member_count : U64,
word : Str,
}
## The finding of a member without its family's `name`.
missing_name : Gap -> Finding
missing_name = |gap| {
who = "`${gap.member.name}` has no `${gap.name}`"
counted = "${gap.holder_count.to_str()} of the ${gap.member_count.to_str()}"
which = "which ${counted} `*${gap.word}` modules have"
advice = "spell it alike, or name it in the module's doc to say why not"
{
path: gap.member.path,
line: gap.member.line,
check: "family",
what: "${who}, ${which}: ${advice}",
}
}
## The last word of a name of two or more words.
last_word : Str -> Try(Str, [OneWord])
last_word = |name|
match Text.name_words(name) {
[_, .., last] => Ok(last)
_ => Err(OneWord)
}
## The comment lines that open a file, trimmed.
opening_comment : List(Str) -> List(Str)
opening_comment = |source_lines| {
var $out = []
for line in source_lines {
trimmed = Text.trim(line)
if !(trimmed.starts_with("#")) {
return $out
}
$out = $out.append(trimmed)
}
$out
}
## The comment lines directly above line `line`, nearest first, lowercased
## and joined: a declaration's doc.
doc_above : List(Str), U64 -> Str
doc_above = |source_lines, line| {
var $parts = []
var $above = line - 1
while $above >= 1 {
trimmed = Text.trim(Text.line_at(source_lines, $above))
if !(trimmed.starts_with("#")) {
return Str.join_with($parts, " ")
}
$parts = $parts.append(Text.lower(trimmed))
$above = $above - 1
}
Str.join_with($parts, " ")
}
cookbook/roc/find_names_that_differ_across_lookalike_modules/SelfTest.roc, 215 lines
## The recipe's self-test: each plant under
## cookbook/roc/plants/find_names_that_differ_across_lookalike_modules/ run through the launcher, held to its
## findings, its exit and what it says.
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| {
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_names_that_differ_across_lookalike_modules 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_names_that_differ_across_lookalike_modules self_test: PASS (${row_count} rows: ${proof})")
}
}
## The launcher, which the self-test runs each plant through.
launcher : Str
launcher = "cookbook:roc/find_names_that_differ_across_lookalike_modules.shale"
plants : Str
plants = "cookbook:roc/plants/find_names_that_differ_across_lookalike_modules/"
## 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, given as a glob below `plants`, with no finding to give.
quiet : Str, List(Str) -> Row
quiet = |plant, arguments| {
plant: "${plants}${plant}",
arguments,
counts: [],
says: [],
stops: Bool.False,
}
## What a plant that fires is run with and must give.
Firing : {
plant : Str,
arguments : List(Str),
counts : List((Str, U64)),
says : List(Str),
}
## What a plant that stops is run with and must say.
Stopping : {
plant : Str,
arguments : List(Str),
says : List(Str),
}
## A plant with findings, and what they say.
fires : Firing -> Row
fires = |wanted| {
plant: "${plants}${wanted.plant}",
arguments: wanted.arguments,
counts: wanted.counts,
says: wanted.says,
stops: Bool.False,
}
## 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,
}
rows : List(Row)
rows = [
fires({
plant: "family/*.roc",
arguments: [],
counts: [("family", 1)],
says: [
"RailSighting.roc:4: family: `RailSighting` has no `in_view`, "
.concat("which 3 of the 4 `*sighting` modules have"),
],
}),
quiet("family_answered/*.roc", []),
quiet("family_small/*.roc", []),
quiet("family_half/*.roc", []),
fires({
plant: "twin_name/*.roc",
arguments: [],
counts: [("twin_name", 1)],
says: ["Bird.roc:4: twin_name: `Pose` is also declared at", "Cat.roc:4"],
}),
quiet("twin_name/*.roc", ["roles=${plants}roles.txt"]),
fires({
plant: "twin_name/*.roc",
arguments: ["roles=${plants}other_roles.txt"],
counts: [("twin_name", 1)],
says: ["`Pose` is also declared at"],
}),
stops({
plant: "twin_name/*.roc",
arguments: ["roles=${plants}no_such.txt"],
says: ["no word list"],
}),
quiet("twin_app/*.roc", []),
quiet("twin_copy/*.roc", []),
quiet("twin_namespace/*.roc", []),
fires({
plant: "twin_namespace_clash/*.roc",
arguments: [],
counts: [("twin_name", 1)],
says: ["`Lamp` is also declared at"],
}),
fires({
plant: "conversion/*.roc",
arguments: [],
counts: [("unpaired_conversion", 1)],
says: ["Span.roc:4: unpaired_conversion: `Span.metres` gives its own type beside `Span.to_metres`"],
}),
quiet("conversion_paired/*.roc", []),
stops({ plant: "broken/*.roc", arguments: [], says: ["refused: "] }),
]
## 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| {
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_names_that_differ_across_lookalike_modules/Twin.roc, 92 lines
## The `twin_name` check: one type name declared in two modules with two
## different shapes, such as `Cat.Pose` and `Geom.Pose`, one word with two
## meanings, so a reader who knows one guesses the other wrong. It is
## reported once, at its first declaration, with the others listed. Twins of
## one shape are copies, as when a package can't import its platform's type,
## so they are no finding. A namespace module (`Collider := [].{ ... }`)
## builds a type and declares none, and so does an alias of the twin
## (`Pose : Geom.Pose`). App files are left out by the caller, because every
## app declares what its platform asks for.
import lib.Declarations
import lib.Finding
import lib.Text
Twin := [].{
## Where a type is declared, and its shape.
Place : {
path : Str,
line : U64,
shape : Str,
}
## A file's path and the types it declares.
FileTypes : { path : Str, types : List(Declarations.TypeDeclared) }
## The twins among the files' types, in the order the files were read.
## A name in `roles` is each module's own to declare, so it has no twin.
findings : List(Twin.FileTypes), Set(Str) -> List(Finding)
findings = |files, roles| {
is_role = |name| roles.contains(name)
is_twin = |(name, places)| places.len() > 1 and !(is_role(name)) and has_two_shapes(places)
files
.fold(Dict.empty(), with_places)
.to_list()
.sort_with(|(a, _), (b, _)| Text.byte_order(a, b))
.keep_if(is_twin)
.map(|(name, places)| twin_finding(name, places))
}
}
## `places_by_name` with the file's types added, each name once a file, at
## its first declaration, and only where the type declares a shape of its
## own.
with_places : Dict(Str, List(Twin.Place)), Twin.FileTypes -> Dict(Str, List(Twin.Place))
with_places = |places_by_name, file| {
var $places = places_by_name
var $seen = Set.empty()
for declared in file.types {
if !($seen.contains(declared.name)) and !(is_type_elsewhere(declared)) {
$seen = $seen.insert(declared.name)
place = {
path: file.path,
line: declared.line,
shape: declared.shape,
}
named_so_far = $places.get(declared.name) ?? []
$places = $places.insert(declared.name, named_so_far.append(place))
}
}
$places
}
## Whether the type declares nothing of its own: a namespace module, or an
## alias of a type of its own name.
is_type_elsewhere : Declarations.TypeDeclared -> Bool
is_type_elsewhere = |declared| {
shape = declared.shape
shape == "" or shape == "[]" or shape == declared.name
}
has_two_shapes : List(Twin.Place) -> Bool
has_two_shapes = |places|
match places {
[first, .. as rest] => rest.any(|place| place.shape != first.shape)
[] => Bool.False
}
## The finding at the name's first place, naming the others.
twin_finding : Str, List(Twin.Place) -> Finding
twin_finding = |name, places|
match places {
[first, .. as rest] => {
others = Str.join_with(rest.map(|place| "${place.path}:${place.line.to_str()}"), ", ")
{
path: first.path,
line: first.line,
check: "twin_name",
what: "`${name}` is also declared at ${others}, in another shape",
}
}
[] => crash "find_names_that_differ_across_lookalike_modules: a twin with no place"
}
Shale original
cookbook/roc/check_families.shale, 183 lines, at 93d75347
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), cookbook/roc/headers.shale (96 lines).
-- This recipe checks that modules which look alike are spelled alike, and
-- that one type name means one thing.
--
-- cd <repo> && shale <shale>/cookbook/roc/check_families.shale
-- shale cookbook:roc/check_families.shale self_test=1
--
-- The arguments:
-- glob the files to check, `**/*.roc` by default;
-- roles a project's file of type names, one a line, that each module
-- may declare for itself, as `Id` in `Message.Id`: read with its
-- module it is a two-part name, so `twin_name` leaves it alone;
-- self_test with `self_test=1`, check the plants in
-- `cookbook/roc/plants/check_families/`.
--
-- The checks:
--
-- family Modules whose names end in the same word form a family when
-- there are three or more (`CatSighting`, `TreeSighting`,
-- `RailSighting`). A public name that more than half of a
-- family's members have is the family's, and each member
-- without it is a finding. A member that differs for a good
-- reason says so by naming the missing name in the `##` doc
-- above its type, or in the file's opening comment.
-- twin_name One public type name declared in two modules with different
-- shapes, such as `Cat.Pose` and `Geom.Pose`: one word, two
-- meanings. It is reported once, at its first declaration, with
-- the others listed. Twins of one shape are copies, as when a
-- package can't import its platform's type, so they are no
-- finding. A shape ignores what a name is qualified by, and the
-- order of fields and tags. A namespace module
-- (`Collider := [].{ ... }`) builds a type and declares none, and
-- so does an alias of the twin (`Pose : Geom.Pose`). App files are
-- left out, because every app declares what its platform asks for.
--
-- `twin_name` sees only the files read, so give it the whole tree: run by
-- folder, it misses twins in two folders.
--
-- A module is a file that declares a type named for itself, and its public
-- names are that type's members. 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 ROLES_FILE = arg("roles", "")
use("./declared.shale")
use("cookbook:findings.shale")
use("./parsed.shale")
use("./gate_recipe.shale")
use("./headers.shale")
const CHECKS = {"family", "twin_name"}
const SMALLEST_FAMILY = 3
-- The file's opening comment and the doc above line `line`, as one text.
function module_doc_text(path, line)
local src = split(read(path), "\n")
return join(opening_comment(src), " ") .. " " .. doc_above(src, line)
end
-- Each module in the files read, as `{name, path, line, members}`, where
-- `members` is the set of its type's member names.
function modules_of(declared_by_file)
local out = {}
for one in declared_by_file do
local name = module_name(one.path)
local module = {name = name, path = one.path, line = 0, members = {}}
for d in one.declared do
if d.kind == "type" and d.name == name and d.owner == "" then module.line = d.line end
if d.kind == "value" and d.owner == name and not has_key(LANGUAGE_FIXED_NAMES, d.name) then module.members[d.name] = true end
end
if module.line ~= 0 and #keys(module.members) > 0 then push(out, module) end
end
return out
end
function judge_families(modules, report)
local family_of = {}
for m in modules do
local ws = name_words(m.name)
if #ws > 1 then push_at(family_of, ws[#ws], m) end
end
for word in sort(keys(family_of)) do
local members = family_of[word]
if #members >= SMALLEST_FAMILY then
local holders = {}
for m in members do
for name in keys(m.members) do incr(holders, name) end
end
for name in sort(keys(holders)) do
if holders[name] * 2 > #members then
for m in members do
if not has_key(m.members, name) and not contains(module_doc_text(m.path, m.line), "`" .. name .. "`") then
push(report, {path = m.path, line = m.line, check = "family", what = "`" .. m.name .. "` has no `" .. name .. "`, which " .. holders[name] .. " of the " .. #members .. " `*" .. word .. "` modules have: spell it alike, or name it in the module's doc to say why not"})
end
end
end
end
end
end
return nil
end
-- Whether the type `d` declares nothing of its own: a namespace module, or an
-- alias of a type of its own name.
function is_type_elsewhere(d)
return d.shape == "" or d.shape == "[]" or d.shape == d.name
end
function has_two_shapes(places)
for p in drop(places, 1) do
if p.shape ~= places[1].shape then return true end
end
return false
end
function judge_twins(declared_by_file, roles, report)
local places_of = {}
for one in declared_by_file do
if not one.is_app then
local seen = {}
for d in one.declared do
if d.kind == "type" and not has_key(seen, d.name) and not is_type_elsewhere(d) then
seen[d.name] = true
push_at(places_of, d.name, d)
end
end
end
end
for name in sort(keys(places_of)) do
local places = places_of[name]
if #places > 1 and not has_key(roles, name) and has_two_shapes(places) then
local others = {}
for p in drop(places, 1) do push(others, p.path .. ":" .. p.line) end
push(report, {path = places[1].path, line = places[1].line, check = "twin_name", what = "`" .. name .. "` is also declared at " .. join(others, ", ") .. ", in another shape"})
end
end
return nil
end
function self_test()
local at = "cookbook:roc/plants/check_families/"
check_plants("check_families", "cookbook:roc/check_families.shale", CHECKS, {
{glob = at .. "family/*.roc", counts = {family = 1}, says = {"RailSighting.roc:4: family: `RailSighting` has no `in_view`, which 3 of the 4 `*sighting` modules have"}},
{glob = at .. "family_answered/*.roc"},
{glob = at .. "family_small/*.roc"},
{glob = at .. "family_half/*.roc"},
{glob = at .. "twin_name/*.roc", counts = {twin_name = 1}, says = {"Bird.roc:4: twin_name: `Pose` is also declared at", "Cat.roc:4"}},
{glob = at .. "twin_name/*.roc", args = {"roles=" .. at .. "roles.txt"}},
{glob = at .. "twin_name/*.roc", args = {"roles=" .. at .. "other_roles.txt"}, counts = {twin_name = 1}, says = {"`Pose` is also declared at"}},
{glob = at .. "twin_name/*.roc", args = {"roles=" .. at .. "no_such.txt"}, stops = true, says = {"no word list"}},
{glob = at .. "twin_app/*.roc"},
{glob = at .. "twin_copy/*.roc"},
{glob = at .. "twin_namespace/*.roc"},
{glob = at .. "twin_namespace_clash/*.roc", counts = {twin_name = 1}, says = {"`Lamp` is also declared at"}},
{glob = at .. "broken/*.roc", stops = true, says = {"refused: "}},
})
return nil
end
function run_check()
local paths = glob(GLOB)
local parsed = parse_roc_files(paths)
local declared_by_file = {}
for f in parsed.files do push(declared_by_file, {path = f.path, is_app = is_app(f), declared = declarations_of(f)}) end
local report = {}
judge_families(modules_of(declared_by_file), report)
judge_twins(declared_by_file, ROLES_FILE == "" and {} or word_set(ROLES_FILE), report)
local verdict = verdict_of("check_families", CHECKS, report, #paths)
print_findings(verdict.summary, verdict.found)
fail_if_refused("check_families", 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