find_names_and_docs_that_say_too_little
Roc
It also imports Declarations, Finding, Headers, Text, Tree from the shared Roc library.
cookbook/roc/find_names_and_docs_that_say_too_little/find_names_and_docs_that_say_too_little.roc, 191 lines
## find_names_and_docs_that_say_too_little, in Roc on Shale's platform (roc_platform/README.md):
## names and top comments that say less than they should. Its launcher,
## cookbook/roc/find_names_and_docs_that_say_too_little.shale, is how it is run, and its header
## says the rules, `pure_mutator`, `abbreviation` and `module_doc`.
## check_goldens.shale, beside this, holds its output on the plants to its
## goldens, line for line.
##
## cd <repo> && shale cookbook:roc/find_names_and_docs_that_say_too_little.shale glob=app/**/*.roc
## shale cookbook:roc/find_names_and_docs_that_say_too_little.shale self_test=1
##
## The arguments: `glob` (`**/*.roc`), `abbreviations`, `words`, `accepted`,
## `terms`, `house` (`house=0` leaves out the house style, `abbreviation`) and
## `self_test` (`self_test=1` runs the plants, each through the launcher).
##
## This root reads the word lists, runs each check on each file and prints
## the verdict. Its modules are beside it: one a check (PureMutator,
## Abbreviation, ModuleDoc) 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 roc_cpu_ms=600000 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 Abbreviation
import ModuleDoc
import PureMutator
import SelfTest
main! : {} => {}
main! = |{}| {
if Shale.arg!("self_test", "") == "1" {
SelfTest.run!(checks)
} else {
verdict = run_check!({})
if !(List.is_empty(verdict.found)) {
Shale.fail!(verdict.summary)
}
}
}
# ── The word lists ───────────────────────────────────────────────────────
read_word_list! : Str => Str
read_word_list! = |path|
match Shale.read!(path) {
Found(text) => text
Missing => {
Shale.fail!("no word list ${path}")
""
}
}
## A list of one word per line, any note after `--` cut off, as a set. A
## word listed twice, or a line of two words, stops the run.
word_set! : Str => Set(Str)
word_set! = |path| {
var $set = Set.empty()
for l in Text.lines(read_word_list!(path)) {
word = Str.trim(Text.before_first(l, "--"))
if Str.contains(word, " ") or Set.contains($set, word) {
Shale.fail!("${path}: `${word}` is no single new word")
}
if word != "" {
$set = Set.insert($set, word)
}
}
$set
}
## The accepted terms file: a term a line, each with its reason after `--`.
## A line without a reason stops the run.
accepted_terms! : Str => Set(Str)
accepted_terms! = |path| {
for l in Text.lines(read_word_list!(path)) {
parts = Str.split_on(l, "--")
term = Str.trim(List.first(parts) ?? "")
reason = Str.trim(List.get(parts, 1) ?? "")
if term != "" and reason == "" {
Shale.fail!("${path}: `${term}` has no reason after `--`")
}
}
word_set!(path)
}
# ── The run ──────────────────────────────────────────────────────────────
## Whether `house=0` leaves the house style out (cookbook/roc/house.shale).
house_is_off! : {} => Bool
house_is_off! = |{}| {
house = Shale.arg!("house", "1")
if house != "0" and house != "1" {
Shale.fail!("house must be 1 (the default) or 0, not ${house}")
}
house == "0"
}
## The checks, in the order the summary counts them.
checks : List(Str)
checks = ["pure_mutator", "abbreviation", "module_doc"]
## The summary and the finding lines, sorted.
verdict_of : List(Finding), U64 -> { summary : Str, found : List(Str) }
verdict_of = |report, file_count| {
sorted = List.sort_with(report, Finding.order)
found = sorted.map(Finding.line_of)
{ summary: "find_names_and_docs_that_say_too_little (Roc): ${U64.to_str(file_count)} files; ${Finding.counts_of(sorted, checks)}", found }
}
run_check! : {} => { summary : Str, found : List(Str) }
run_check! = |{}| {
abbreviations = word_set!(Shale.arg!("abbreviations", "cookbook:words/abbreviations.txt"))
words = word_set!(Shale.arg!("words", "cookbook:words/short_words.txt"))
accepted_here = accepted_terms!("cookbook:words/accepted_terms.txt")
project_accepted = Shale.arg!("accepted", "")
accepted = if project_accepted == "" {
accepted_here
} else {
Set.union(accepted_here, accepted_terms!(project_accepted))
}
lists = { abbreviations, words, accepted }
terms_file = Shale.arg!("terms", "")
terms = if terms_file == "" {
Set.empty()
} else {
word_set!(terms_file)
}
paths = Shale.glob!(Shale.arg!("glob", "**/*.roc"))
var $report = []
var $refused = []
for f in Shale.roc_tree!(paths) {
if f.err != "" {
$refused = $refused.append(
if Str.starts_with(f.err, f.path) {
f.err
} else {
"${f.path}: ${f.err}"
},
)
} else {
src = match Shale.read!(f.path) {
Found(text) => Str.split_on(text, "\n")
Missing => []
}
declared = Declarations.from_file({ path: f.path, nodes: f.nodes, source_lines: src })
aliases = List.fold(
declared.types,
Dict.empty(),
|m, d| if !(d.is_nominal) {
Dict.insert(m, d.name, d.underlying)
} else {
m
},
)
for d in declared.values {
$report = List.concat($report, PureMutator.judge(f.path, d, aliases, terms))
}
if !(house_is_off!({})) {
$report = List.concat($report, Abbreviation.judge(f.path, f.nodes, declared, lists))
}
$report = List.concat($report, ModuleDoc.judge!(f.path, f.nodes, declared, src))
}
}
verdict = verdict_of($report, List.len(paths))
summary = if house_is_off!({}) {
"${verdict.summary}; left out as house style: abbreviation"
} else {
verdict.summary
}
print_findings!(summary, verdict.found)
if !(List.is_empty($refused)) {
for r in $refused {
Shale.print!("refused: ${r}")
}
Shale.fail!("find_names_and_docs_that_say_too_little: roc-ast refused ${U64.to_str(List.len($refused))} files (named above), which have no tree to judge; every other file was judged")
}
{ summary, found: verdict.found }
}
## The summary, each finding, then the summary again (cookbook/findings.shale).
print_findings! : Str, List(Str) => {}
print_findings! = |summary, found| {
Shale.print!(summary)
if !(List.is_empty(found)) {
for l in found {
Shale.print!(l)
}
Shale.print!(summary)
}
}
cookbook/roc/find_names_and_docs_that_say_too_little/Abbreviation.roc, 191 lines
## The `abbreviation` check: a name with a word short for another, read from
## every name a file gives or says (the launcher's header says the rule).
import lib.Declarations
import lib.Finding
import lib.Text
import lib.Tree
Abbreviation := [].{
## The word lists the check reads: the abbreviations, the English words
## of two to four letters, and the accepted terms.
Lists : { abbreviations : Set(Str), words : Set(Str), accepted : Set(Str) }
## The findings of the file at `path`, a name once a file.
judge : Str, List(Tree.Node), Declarations, Abbreviation.Lists -> List(Finding)
judge = |path, tree, declared, lists| {
var $seen = Set.empty()
var $report = []
for given in names_given(path, tree, declared) {
if !(Set.contains($seen, given.name)) {
$seen = Set.insert($seen, given.name)
found = Text.name_words(given.name).keep_if(|w| is_abbreviated(w, lists))
if !(List.is_empty(found)) {
$report = $report.append({ path, line: given.line, check: "abbreviation", what: "`${given.name}` abbreviates: ${Str.join_with(found, ", ")}" })
}
}
}
$report
}
}
## Whether a short word stands as it is: an English word, an accepted term,
## or a letter and an axis (`dx`, `vy`).
is_plain_short_word : Str, Abbreviation.Lists -> Bool
is_plain_short_word = |w, lists| {
if Set.contains(lists.words, w) or Set.contains(lists.accepted, w) {
Bool.True
} else {
bytes = Str.to_utf8(w)
second = List.get(bytes, 1) ?? 0
List.len(bytes) == 2 and (second == 120 or second == 121 or second == 122)
}
}
## Whether a word of two to four letters is short for another.
is_short_abbreviation : Str, Abbreviation.Lists -> Bool
is_short_abbreviation = |w, lists| {
bytes = Str.to_utf8(w)
n = List.len(bytes)
if n < 2 or n > 4 or !(List.all(bytes, Text.is_small_letter)) {
Bool.False
} else {
!(is_plain_short_word(w, lists))
}
}
## The stems a word may be the plural of (`shapes`: `shape`, `shap`; `tries`:
## `trie`, `tri`, `try`), none for a word ending as no plural does.
plural_stems : Str -> List(Str)
plural_stems = |w| {
n = w.count_utf8_bytes()
no_plural = ["ss", "us", "is", "as", "os"].any(|e| Str.ends_with(w, e))
if n < 3 or !(Str.ends_with(w, "s")) or no_plural {
return []
}
one = [Text.bytes_of(w, { start: 0, count: n - 1 })]
two = if Str.ends_with(w, "es") and n > 3 {
one.append(Text.bytes_of(w, { start: 0, count: n - 2 }))
} else {
one
}
if Str.ends_with(w, "ies") and n > 4 {
two.append("${Text.bytes_of(w, { start: 0, count: n - 3 })}y")
} else {
two
}
}
## Whether a stem is a whole word, so its plural is plain.
is_whole_stem : Str, Abbreviation.Lists -> Bool
is_whole_stem = |stem, lists|
if Set.contains(lists.accepted, stem) {
Bool.True
} else if stem.count_utf8_bytes() <= 4 {
is_plain_short_word(stem, lists)
} else {
!(Set.contains(lists.abbreviations, stem))
}
## Whether a word of a name is an abbreviation (the launcher's header says
## the rule).
is_abbreviated : Str, Abbreviation.Lists -> Bool
is_abbreviated = |word, lists| {
letters = Str.to_utf8(word).keep_if(|b| Text.is_small_letter(b) or Text.is_digit(b))
whole = Str.from_utf8_lossy(letters)
if Set.contains(lists.accepted, whole) {
return Bool.False
}
if Set.contains(lists.abbreviations, whole) {
return Bool.True
}
var $end = List.len(letters)
while $end > 0 and Text.is_digit(List.get(letters, $end - 1) ?? 0) {
$end = $end - 1
}
w = Str.from_utf8_lossy(List.take_first(letters, $end))
if Set.contains(lists.accepted, w) {
return Bool.False
}
if Set.contains(lists.abbreviations, w) {
return Bool.True
}
if w.count_utf8_bytes() <= 4 and is_plain_short_word(w, lists) {
return Bool.False
}
stems = plural_stems(w)
if stems.any(|stem| is_whole_stem(stem, lists)) {
Bool.False
} else if stems.any(|stem| Set.contains(lists.abbreviations, stem) or is_short_abbreviation(stem, lists)) {
Bool.True
} else {
is_short_abbreviation(w, lists)
}
}
## The tag a node names, `""` for none: a tag in a union, a pattern or an
## expression, a module's qualified tag by its last part.
tag_named : List(Tree.Node), U64 -> Str
tag_named = |tree, at| {
n = Tree.node_at(tree, at)
if n.kind == "p-tag" or n.kind == "e-tag" {
return Tree.last_part(Tree.attribute(n, "raw"))
}
if n.kind != "ty" or n.parent == 0 {
return ""
}
holder = Tree.node_at(tree, n.parent)
if holder.kind == "tags" {
Tree.attribute(n, "name")
} else if holder.kind == "ty-apply" and List.first(holder.kids) == Ok(at) and Tree.node_at(tree, holder.parent).kind == "tags" {
Tree.attribute(n, "name")
} else {
""
}
}
## The names a file gives or says, with the line each appears on: the
## module's, what it declares in file order, then its parameters, locals and
## tags.
names_given : Str, List(Tree.Node), Declarations -> List({ name : Str, line : U64 })
names_given = |path, tree, declared| {
var $out = if Tree.is_app(tree) {
[]
} else {
[{ name: Tree.module_name(path), line: 1 }]
}
for d in declared_in_file_order(declared) {
$out = $out.append({ name: d.name, line: d.line })
}
var $i = 0
for n in tree {
$i = $i + 1
if n.kind == "p-ident" {
$out = $out.append({ name: Tree.attribute(n, "raw"), line: n.line })
}
tag = tag_named(tree, $i)
if tag != "" and tag != "Ok" and tag != "Err" {
$out = $out.append({ name: tag, line: n.line })
}
}
$out
}
## What the file declares, its types, fields and values together, in file
## order: by the place of each one's node.
declared_in_file_order : Declarations -> List({ place : U64, name : Str, line : U64 })
declared_in_file_order = |declared| {
types = declared.types.map(|d| { place: d.place, name: d.name, line: d.line })
fields = declared.fields.map(|d| { place: d.place, name: d.name, line: d.line })
values = declared.values.map(|d| { place: d.place, name: d.name, line: d.line })
types.concat(fields).concat(values).sort_with(
|first, second|
if first.place < second.place {
Before
} else if first.place > second.place {
After
} else {
Same
},
)
}
cookbook/roc/find_names_and_docs_that_say_too_little/ModuleDoc.roc, 134 lines
## The `module_doc` check: a module with no `##` doc, or a top comment or a
## doc above its type that tells history (the launcher's header says the
## rule). A package's or platform's main.roc says which modules it keeps to
## itself, so it reads files through the platform.
import pf.Shale
import lib.Declarations
import lib.Finding
import lib.Headers
import lib.Text
import lib.Tree
ModuleDoc := [].{
## The findings of the file at `path`, none for an app.
judge! : Str, List(Tree.Node), Declarations, List(Str) => List(Finding)
judge! = |path, tree, declared, src| {
if Tree.is_app(tree) {
return []
}
name = Tree.module_name(path)
type_line = List.fold(
declared.types,
0,
|at, d| if d.name == name and d.owner == "" {
d.line
} else {
at
},
)
if type_line == 0 {
return []
}
top = opening_comment(src)
above_type = if type_line > 1 {
Str.trim(Text.line_at(src, type_line - 1))
} else {
""
}
opens_with_doc = Str.starts_with(List.first(top) ?? "", "##")
has_doc = opens_with_doc or (type_line > 1 and Str.starts_with(above_type, "##"))
kept_to_itself = (
!(List.is_empty(top)) or Str.starts_with(
Str.trim(
Text.line_at(
src,
if type_line > 1 {
type_line - 1
} else {
1
},
),
),
"#",
)
) and is_private_module!(path)
var $report = []
if !(has_doc) and !(kept_to_itself) {
$report = $report.append({ path, line: 1, check: "module_doc", what: "`${name}` has no `##` doc saying what it is for" })
}
history = history_word!(top)
if history != "" {
$report = $report.append({ path, line: 1, check: "module_doc", what: "`${name}`'s top comment says `${history}`: say what the module does, and leave history to git" })
}
doc = comment_above(src, type_line)
doc_history = history_word!(doc.lines)
if doc.first > 1 and doc_history != "" {
$report = $report.append({ path, line: doc.first, check: "module_doc", what: "`${name}`'s doc says `${doc_history}`: say what the module does, and leave history to git" })
}
$report
}
}
## The history word in the comment lines, or `""`. Each line's leading `#`s
## go before the lines are joined, so a phrase wrapped across two lines reads
## as one.
history_word! : List(Str) => Str
history_word! = |comment| {
var $words = []
for l in comment {
$words = $words.append(Str.trim(Shale.re_replace!(l, "^#+", "")))
}
match Shale.re_find!(Str.with_ascii_lowercased(Str.join_with($words, " ")), "\\b(originally|used to|emitted|ported)\\b") {
Found(m) => List.first(m.groups) ?? ""
NoMatch => ""
}
}
## The comment lines just above line `at`, trimmed, and the line they start
## on (`at` when there are none).
comment_above : List(Str), U64 -> { lines : List(Str), first : U64 }
comment_above = |src, at| {
var $first = at
while $first > 1 and Str.starts_with(Str.trim(Text.line_at(src, $first - 1)), "#") {
$first = $first - 1
}
{ lines: List.sublist(src, { start: $first - 1, len: at - $first }).map(Str.trim), first: $first }
}
## The comment lines that open a file, trimmed.
opening_comment : List(Str) -> List(Str)
opening_comment = |src| {
var $out = []
var $going = Bool.True
for l in src {
if $going and Str.starts_with(Str.trim(l), "#") {
$out = $out.append(Str.trim(l))
} else {
$going = Bool.False
}
}
$out
}
## What a folder's `main.roc` exposes, when it is a package's or a
## platform's (cookbook/roc/lib/'s `Headers.exposed_by`).
exposed_by_folder! : Str => { is_package : Bool, modules : List(Str) }
exposed_by_folder! = |dir| {
main = if dir == "" or dir == "." {
"main.roc"
} else {
"${dir}/main.roc"
}
match Shale.read!(main) {
Missing => { is_package: Bool.False, modules: [] }
Found(text) => Headers.exposed_by(text)
}
}
## Whether a file is a module its package keeps to itself.
is_private_module! : Str => Bool
is_private_module! = |path| {
exposed = exposed_by_folder!(Text.dirname(path))
exposed.is_package and !(List.contains(exposed.modules, Tree.module_name(path))) and Text.basename(path) != "main.roc"
}
cookbook/roc/find_names_and_docs_that_say_too_little/PureMutator.roc, 74 lines
## The `pure_mutator` check: an annotated pure function whose first word
## says it changes something though nothing is being added to (the
## launcher's header says the rule).
import lib.Declarations
import lib.Finding
import lib.Text
import lib.Tree
PureMutator := [].{
## The finding for value `d` of the file at `path`, if it is one.
## `aliases` are the file's structural type aliases, by name, and `terms`
## the project's fixed terms that only look like a verb.
judge : Str, Declarations.ValueDeclared, Dict(Str, Str), Set(Str) -> List(Finding)
judge = |path, d, aliases, terms| {
if !(d.is_function) or !(d.annotated) or Str.ends_with(d.name, "!") or opens_with_term(d.name, terms) {
return []
}
first_word = Text.before_first(d.name, "_")
is_mutation = is_mutation_word(first_word) and !(gives_first_back(d, aliases))
if first_word == "get" or is_mutation {
[{ path, line: d.line, check: "pure_mutator", what: "`${d.name}` is pure and gives a new `${d.result_type}`: name it for what it gives" }]
} else {
[]
}
}
}
## The value of a `Try(value, errors)`, or `result` when it is no `Try`.
value_of_try : Str -> Str
value_of_try = |result| {
if !(Str.starts_with(result, "Try(")) {
return result
}
bytes = Str.to_utf8(result)
var $depth = 0
var $k = 4
while $k < List.len(bytes) {
b = List.get(bytes, $k) ?? 0
if b == 40 or b == 123 or b == 91 {
$depth = $depth + 1
} else if b == 41 or b == 125 or b == 93 {
if $depth == 0 {
return result
}
$depth = $depth - 1
} else if b == 44 and $depth == 0 {
return Str.trim(Text.bytes_of(result, { start: 4, count: $k - 4 }))
}
$k = $k + 1
}
result
}
record_holds : Str, Str -> Bool
record_holds = |record, type_name|
Str.starts_with(record, "{") and (Str.contains(record, " : ${type_name},") or Str.contains(record, " : ${type_name} }"))
## Whether a function's result is what its first argument was added to.
gives_first_back : Declarations.ValueDeclared, Dict(Str, Str) -> Bool
gives_first_back = |d, aliases| {
value = value_of_try(d.result_type)
if value == d.first_type or record_holds(d.first_type, value) {
Bool.True
} else {
record_holds(Dict.get(aliases, Tree.last_part(value)) ?? value, d.first_type)
}
}
opens_with_term : Str, Set(Str) -> Bool
opens_with_term = |name, terms| Set.to_list(terms).any(|term| name == term or Str.starts_with(name, "${term}_"))
is_mutation_word : Str -> Bool
is_mutation_word = |w| w == "push" or w == "fill" or w == "set" or w == "append" or w == "add"
cookbook/roc/find_names_and_docs_that_say_too_little/SelfTest.roc, 137 lines
## The recipe's self-test: each plant under
## cookbook/roc/plants/find_names_and_docs_that_say_too_little/ run through the launcher, held to
## its findings, its exit and what it says.
import pf.Shale
import lib.Text
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 {
argv = List.concat(["shale", launcher, "glob=${row.glob}"], row.args)
r = Shale.run!({ argv, keep: Whole(4000000), timeout_ms: 120000, want: "" })
faults = row_faults!(row, r, checks)
for pair in row.counts {
$fired = Set.insert($fired, pair.0)
}
if List.is_empty(faults) {
Shale.print!("ok ${row.glob}")
} else {
Shale.print!("FAIL ${row.glob}: ${Str.join_with(faults, "; ")}")
$wrong = $wrong + 1
Shale.print!(r.out)
}
}
for check in checks {
if !(Set.contains($fired, check)) {
Shale.print!("FAIL `${check}` has no plant")
$wrong = $wrong + 1
}
}
if $wrong > 0 {
Shale.fail!("find_names_and_docs_that_say_too_little self_test: ${U64.to_str($wrong)} wrong")
}
Shale.print!("find_names_and_docs_that_say_too_little self_test: PASS (${U64.to_str(List.len(rows))} rows: each plant gives its findings and a nonzero exit, each clean case none and exit 0)")
}
}
## The launcher, which the self-test runs each plant through.
launcher : Str
launcher = "cookbook:roc/find_names_and_docs_that_say_too_little.shale"
Row : { glob : Str, args : List(Str), counts : List((Str, U64)), says : List(Str), stops : Bool }
plants : Str
plants = "cookbook:roc/plants/find_names_and_docs_that_say_too_little/"
clean : Str -> Row
clean = |glob| { glob: "${plants}${glob}", args: [], counts: [], says: [], stops: Bool.False }
fires : Str, List(Str), List((Str, U64)), List(Str) -> Row
fires = |glob, args, counts, says| { glob: "${plants}${glob}", args, counts, says, stops: Bool.False }
stops : Str, List(Str), List(Str) -> Row
stops = |glob, args, says| { glob: "${plants}${glob}", args, counts: [], says, stops: Bool.True }
rows : List(Row)
rows = [
fires("pure_mutator.roc", [], [("pure_mutator", 7)], ["pure_mutator.roc:3: pure_mutator: `push_cat` is pure and gives a new `List(U64)`", "`get_speed`"]),
clean("quiet_pure_mutator.roc"),
fires("terms.roc", [], [("pure_mutator", 2)], ["`set_cookie_header`", "`set_cookies`"]),
fires("terms.roc", ["terms=${plants}terms.txt"], [("pure_mutator", 1)], ["`set_cookies`"]),
stops("terms.roc", ["terms=${plants}no_such.txt"], ["no word list"]),
fires("abbreviation.roc", [], [("abbreviation", 4)], ["abbreviation.roc:3: abbreviation: `max_vis_cats` abbreviates: vis", "`SunPos` abbreviates: pos", "`dist` abbreviates: dist"]),
clean("quiet_abbreviation.roc"),
fires("abbreviation.roc", ["abbreviations=${plants}project_words.txt"], [("abbreviation", 4)], ["`max_vis_cats` abbreviates: vis, cats"]),
fires("short_words/*.roc", [], [("abbreviation", 5)], ["Tbl.roc:1: abbreviation: `Tbl` abbreviates: tbl", "Tbl.roc:4: abbreviation: `Trk` abbreviates: trk", "Tbl.roc:7: abbreviation: `trk` abbreviates: trk", "`pts` abbreviates: pts", "Tbl.roc:9: abbreviation: `hgt` abbreviates: hgt"]),
clean("quiet_short_words/*.roc"),
fires("short_words/*.roc", ["accepted=${plants}project_terms.txt"], [("abbreviation", 3)], ["`Tbl` abbreviates: tbl", "`pts` abbreviates: pts", "`hgt` abbreviates: hgt"]),
{ ..clean("quiet_short_words/*.roc"), args: ["accepted=${plants}project_terms.txt"] },
stops("quiet_short_words/*.roc", ["accepted=${plants}no_reason.txt"], ["`qty` has no reason"]),
stops("quiet_abbreviation.roc", ["abbreviations=${plants}no_such.txt"], ["no word list"]),
fires("long_abbreviations/*.roc", [], [("abbreviation", 11)], ["Parser.roc:5: abbreviation: `attrs` abbreviates: attrs", "`idxes` abbreviates: idxes", "`vals` abbreviates: vals", "`delim` abbreviates: delim", "`parse_args` abbreviates: args", "`params` abbreviates: params", "`elem_count` abbreviates: elem", "`expr_text` abbreviates: expr", "`stmt_kind` abbreviates: stmt", "`tmpl_name` abbreviates: tmpl"]),
fires("long_abbreviations/*.roc", ["accepted=${plants}project_args.txt"], [("abbreviation", 9)], ["`attrs` abbreviates: attrs", "`params` abbreviates: params"]),
clean("quiet_long_abbreviations/*.roc"),
fires("common_words/*.roc", [], [("abbreviation", 2)], ["`Flw` abbreviates: flw", "`night_dmr` abbreviates: dmr"]),
clean("quiet_common_words/*.roc"),
fires("tags.roc", [], [("abbreviation", 5)], ["tags.roc:14: abbreviation: `TmplGone` abbreviates: tmpl", "tags.roc:4: abbreviation: `NoRef` abbreviates: ref", "tags.roc:4: abbreviation: `Ref` abbreviates: ref", "tags.roc:6: abbreviation: `TmplMissing` abbreviates: tmpl", "tags.roc:12: abbreviation: `BadAttr` abbreviates: attr"]),
clean("quiet_tags.roc"),
fires("module_doc/*.roc", [], [("module_doc", 5)], ["`NoDoc` has no `##` doc", "`Hashless` has no `##` doc", "`Old`'s top comment says `originally`", "`Sky`'s top comment says `used to`", "Sun.roc:3: module_doc: `Sun`'s doc says `originally`"]),
clean("quiet_module_doc/*.roc"),
fires("module_doc_private/*.roc", [], [("module_doc", 2)], ["`Shown` has no `##` doc", "`Silent` has no `##` doc"]),
stops("broken/*.roc", [], ["refused: "]),
]
## The last line of `out` that isn't one of Shale's `──` lines.
last_said : Str -> Str
last_said = |out| List.fold(
Text.lines(Str.trim(out)),
"",
|last, l| if Str.starts_with(l, "──") or Str.trim(l) == "" {
last
} else {
l
},
)
## What is wrong with one row's run.
row_faults! : Row, { code : I64, out : Str }, List(Str) => List(Str)
row_faults! = |row, r, checks| {
must_fail = row.stops or !(List.is_empty(row.counts))
var $faults = []
if must_fail and r.code == 0 {
$faults = $faults.append("it exited 0")
}
if !(must_fail) and r.code != 0 {
$faults = $faults.append("it exited ${I64.to_str(r.code)}")
}
for check in checks {
found = List.len(Shale.re_lines!(r.out, "^[^ ]+:[0-9]+: ${check}: "))
wanted = List.fold(
row.counts,
0,
|n, pair| if pair.0 == check {
pair.1
} else {
n
},
)
if found != wanted {
$faults = $faults.append("${check} printed ${U64.to_str(found)}, not ${U64.to_str(wanted)}")
}
}
if !(row.stops) and !(Str.contains(last_said(r.out), " files; ")) {
$faults = $faults.append("its last line is no summary: ${last_said(r.out)}")
}
for literal in row.says {
if !(Str.contains(r.out, literal)) {
$faults = $faults.append("its output lacks `${literal}`")
}
}
$faults
}
Shale original
cookbook/roc/find_unclear_names.shale, 372 lines, at 7ec0fd04
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), cookbook/roc/house.shale (46 lines).
-- This recipe finds names and top comments that say less than they should: a
-- pure function named like a mutation, an abbreviation in a name, and a
-- module with no doc or with history where its doc belongs.
--
-- cd <repo> && shale <shale>/cookbook/roc/find_unclear_names.shale
-- shale cookbook:roc/find_unclear_names.shale self_test=1
--
-- The arguments:
-- glob the files to check, `**/*.roc` by default;
-- abbreviations the file of abbreviations, one a line, by default
-- cookbook/words/abbreviations.txt, for a project with
-- words of its own to add;
-- words the English words of two to four letters a name may hold,
-- by default cookbook/words/short_words.txt;
-- accepted a project's file of the short terms a name may hold though
-- they are no English word, each with its reason, added to
-- cookbook/words/accepted_terms.txt (`html`, `url`, `utf8`);
-- terms a project's file of fixed terms that open a name and only
-- look like a verb, one a line, such as `set_cookie` for
-- HTTP's header, which `pure_mutator` leaves alone;
-- house with `house=0`, leave out what is only our house style
-- (cookbook/roc/house.shale), for another project's code;
-- self_test with `self_test=1`, check the plants in
-- `cookbook/roc/plants/find_unclear_names/`.
--
-- The checks read top-level names, module members and the record fields of
-- types and annotations; `abbreviation` reads module names, parameters,
-- locals and tags too:
--
-- pure_mutator An annotated pure function whose first word says it changes
-- something (`push`, `fill`, `set`, `append`, `add`), though
-- nothing is being added to. Something is when the result is
-- the first argument's type, on its own, as a `Try`'s value,
-- or as a field of a record or of an alias in the same file
-- (`Try({ users : Users, user : User }, [Full])`), or when the
-- first argument is a record with a field of the result's
-- type (`{ so_far : List(U8), count : U64 }`). A first word
-- `get` always counts, because a Roc function's plain name
-- is already what it gets.
-- abbreviation A name with a word short for another, since Roc's style
-- guide prefers the plain word: a word from the
-- abbreviations file, whatever its length (`delim`,
-- `param`, `args`), the plural of an abbreviation (`attrs`,
-- `params`), or a word of two to four letters (`st`, `tks`,
-- `Inl`, `Emph`) that is no English word of the words file,
-- no accepted term, no plural of either, and no letter and
-- an axis (`dx`). A term accepted, the cookbook's or the
-- project's, is never one, even one the abbreviations file
-- lists (a project's `args`). A word ending as no plural
-- does (`class`, `bonus`, `alias`) is no plural. A type's words are split at
-- its capitals, so `TkKind` holds `tk`. A word's marks and
-- trailing digits go first (`buf0` is `buf`), and a letter
-- alone is hunt_names' `short_name`'s. The names read are a
-- module's own (its file's), every type, member, field and
-- top-level value, every parameter and local, and every tag
-- in a union, a pattern or an expression, split at its
-- capitals as a type is (`NoRef` holds `ref`), but Roc's own
-- `Ok` and `Err`. A name is reported once a file.
-- module_doc A module with no `##` doc at the top of its file or above
-- its type, or a top comment or a doc above its type that
-- tells history (`originally`, `used to`, `emitted`,
-- `ported`, even wrapped across two lines) instead of what
-- the module does. A
-- module its package or platform keeps to itself has no public
-- doc to write, so any comment there will do. App files are
-- left out, as they have no module type.
--
-- 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 ABBREVIATIONS_FILE = arg("abbreviations", "cookbook:words/abbreviations.txt")
const SHORT_WORDS_FILE = arg("words", "cookbook:words/short_words.txt")
const ACCEPTED_FILE = "cookbook:words/accepted_terms.txt"
const PROJECT_ACCEPTED_FILE = arg("accepted", "")
const TERMS_FILE = arg("terms", "")
use("./declared.shale")
use("cookbook:findings.shale")
use("./parsed.shale")
use("./gate_recipe.shale")
use("./headers.shale")
use("./house.shale")
const CHECKS = {"pure_mutator", "abbreviation", "module_doc"}
const MUTATION_WORDS = {push = true, fill = true, set = true, append = true, add = true}
const HISTORY_RE = "\\b(originally|used to|emitted|ported)\\b"
-- The value of a `Try(value, errors)`, or `result` when it is no `Try`.
function value_of_try(result)
if not starts_with(result, "Try(") then return result end
local depth = 0
for i = 5, #result do
local c = sub(result, i, i)
if c == "(" or c == "{" or c == "[" then
depth = depth + 1
elseif c == ")" or c == "}" or c == "]" then
depth = depth - 1
elseif c == "," and depth == 0 then
return trim(sub(result, 5, i - 1))
end
end
return result
end
function record_holds(record, type_name)
return starts_with(record, "{") and (contains(record, " : " .. type_name .. ",") or contains(record, " : " .. type_name .. " }"))
end
-- Whether a function's result is what its first argument was added to.
function gives_first_back(d, aliases)
local value = value_of_try(d.result)
if value == d.first or record_holds(d.first, value) then return true end
return record_holds(get(aliases, last_part(value), value), d.first)
end
function opens_with_term(name, terms)
for term in keys(terms) do
if name == term or starts_with(name, term .. "_") then return true end
end
return false
end
function judge_mutator(d, aliases, terms, report)
if not d.fn or not d.annotated or ends_with(d.name, "!") or opens_with_term(d.name, terms) then return nil end
local first_word = split(d.name, "_")[1]
local is_mutation = has_key(MUTATION_WORDS, first_word) and not gives_first_back(d, aliases)
if first_word == "get" or is_mutation then
push(report, {path = d.path, line = d.line, check = "pure_mutator", what = "`" .. d.name .. "` is pure and gives a new `" .. d.result .. "`: name it for what it gives"})
end
return nil
end
-- The accepted terms file: a term a line, each with its reason after `--`,
-- as a set. A line without a reason fails the run.
function accepted_terms(path)
if not exists(path) then fail("no word list " .. path) end
for l in lines(read(path)) do
local term = trim(split(l, "--")[1])
if term ~= "" and trim(get(split(l, "--"), 2, "")) == "" then fail(path .. ": `" .. term .. "` has no reason after `--`") end
end
return word_set(path)
end
-- Whether a short word stands as it is: an English word, an accepted term,
-- or a letter and an axis (`dx`, `vy`), a coordinate's change or part.
function is_plain_short_word(w, lists)
if has_key(lists.words, w) or has_key(lists.accepted, w) then return true end
return #w == 2 and has_item({"x", "y", "z"}, sub(w, 2, 2))
end
-- Whether a word of two to four letters is short for another: no plain
-- short word.
function is_short_abbreviation(w, lists)
if #w < 2 or #w > 4 or re_find(w, "^[a-z]+$") == nil then return false end
return not is_plain_short_word(w, lists)
end
-- The stems a word may be the plural of, each way English makes one:
-- `shapes` gives `shape` and `shap`, `boxes` `boxe` and `box`, and `tries`
-- `trie`, `tri` and `try`. None for a word that ends as no plural does
-- (`class`, `bonus`, `alias`, `basis`, `chaos`).
function plural_stems(w)
if #w < 3 or not ends_with(w, "s") or re_find(w, "(ss|us|is|as|os)$") ~= nil then return {} end
local stems = {sub(w, 1, #w - 1)}
if ends_with(w, "es") and #w > 3 then push(stems, sub(w, 1, #w - 2)) end
if ends_with(w, "ies") and #w > 4 then push(stems, sub(w, 1, #w - 3) .. "y") end
return stems
end
-- Whether a stem is a whole word, so its plural is plain: an accepted term,
-- a plain short word, or a stem past four letters that the abbreviations
-- file doesn't list, since only a word of two to four letters is judged
-- by its length (`shape` of `shapes`, `frame` of `frames`).
function is_whole_stem(stem, lists)
if has_key(lists.accepted, stem) then return true end
if #stem <= 4 then return is_plain_short_word(stem, lists) end
return not has_key(lists.abbreviations, stem)
end
-- Whether a word of a name is an abbreviation. A term the cookbook or the
-- project accepts never is, and one the abbreviations file lists always is,
-- whatever its length (`delim`, `params`). A plural is judged by every
-- stem it could have (`plural_stems`): it is plain when any stem is a whole
-- word (`ids`, `boxes`, `shapes`, `tries`), and else an abbreviation when a
-- stem is one (`attrs`, `delims`). Past those, a word of two to four
-- letters that is no plain word is one. Its marks (`!`, `$`) and trailing
-- digits (`buf0`) go first; a letter alone is `short_name`'s, in hunt_names.
function is_abbreviated(word, lists)
local w = re_replace(word, "[^a-z0-9]", "")
if has_key(lists.accepted, w) then return false end
if has_key(lists.abbreviations, w) then return true end
w = re_replace(w, "[0-9]+$", "")
if has_key(lists.accepted, w) then return false end
if has_key(lists.abbreviations, w) then return true end
if #w <= 4 and is_plain_short_word(w, lists) then return false end
local stems = plural_stems(w)
for stem in stems do
if is_whole_stem(stem, lists) then return false end
end
for stem in stems do
if has_key(lists.abbreviations, stem) or is_short_abbreviation(stem, lists) then return true end
end
return is_short_abbreviation(w, lists)
end
-- Roc's own tags, which every file may say and none names.
const ROC_TAGS = {Ok = true, Err = true}
-- The tag a node names, `""` for none: a tag in a union (`[NoRef, Ref(Str)]`,
-- the bare one and the head of the one with a payload), in a pattern and in
-- an expression. A tag a module qualifies (`Bool.False`, which a pattern's
-- tree gives as `.False`) is its last part alone: the module's name is
-- judged in the module's own file, and a builtin's (`Bool`) is Roc's.
function tag_named(tree, at)
local n = tree[at]
if n.kind == "p-tag" or n.kind == "e-tag" then
local parts = split(get(n, "raw", ""), ".")
return parts[#parts]
end
if n.kind ~= "ty" or n.parent == 0 then return "" end
local holder = tree[n.parent]
if holder.kind == "tags" then return get(n, "name", "") end
if holder.kind == "ty-apply" and holder.kids[1] == at and tree[holder.parent].kind == "tags" then return get(n, "name", "") end
return ""
end
-- The names a file gives or says, each once, with the line it first appears
-- on: its module's name, what it declares, each parameter and local, and
-- each tag but Roc's own (ROC_TAGS), split at its capitals as a type is.
function names_given(f, declared)
local out = {}
if not is_app(f) then push(out, {name = module_name(f.path), line = 1}) end
for d in declared do push(out, {name = d.name, line = d.line}) end
for i = 1, #f.nodes do
local n = f.nodes[i]
if n.kind == "p-ident" then push(out, {name = get(n, "raw", ""), line = n.line}) end
local tag = tag_named(f.nodes, i)
if tag ~= "" and not has_key(ROC_TAGS, tag) then push(out, {name = tag, line = n.line}) end
end
return out
end
function judge_abbreviations(f, declared, lists, report)
local seen = {}
for given in names_given(f, declared) do
if not has_key(seen, given.name) then
seen[given.name] = true
local found = {}
for w in name_words(given.name) do
if is_abbreviated(w, lists) then push(found, w) end
end
if #found > 0 then push(report, {path = f.path, line = given.line, check = "abbreviation", what = "`" .. given.name .. "` abbreviates: " .. join(found, ", ")}) end
end
end
return nil
end
-- The history word in the comment lines `comment`, or nil. Each line's
-- leading `#`s go before the lines are joined, so a phrase wrapped across
-- two lines reads as one.
function history_word(comment)
local words = {}
for l in comment do push(words, trim(re_replace(l, "^#+", ""))) end
local found = re_find(lower(join(words, " ")), HISTORY_RE)
if found == nil then return nil end
return found.group
end
-- The comment lines just above line `at` of `src`, trimmed, as `{lines,
-- first}`, where `first` is the line the comment starts on, or `at` when
-- there is none.
function comment_above(src, at)
local first = at
while first > 1 and starts_with(trim(src[first - 1]), "#") do first = first - 1 end
local out = {}
for k = first, at - 1 do push(out, trim(src[k])) end
return {lines = out, first = first}
end
function judge_module_doc(f, declared, report)
if is_app(f) then return nil end
local name = module_name(f.path)
local type_line = 0
for d in declared do
if d.kind == "type" and d.name == name and d.owner == "" then type_line = d.line end
end
if type_line == 0 then return nil end
local src = split(read(f.path), "\n")
local top = opening_comment(src)
local has_doc = (#top > 0 and starts_with(top[1], "##")) or (type_line > 1 and starts_with(trim(src[type_line - 1]), "##"))
if is_private_module(f.path) and (#top > 0 or starts_with(trim(src[max(type_line - 1, 1)]), "#")) then has_doc = true end
if not has_doc then push(report, {path = f.path, line = 1, check = "module_doc", what = "`" .. name .. "` has no `##` doc saying what it is for"}) end
local history = history_word(top)
if history ~= nil then push(report, {path = f.path, line = 1, check = "module_doc", what = "`" .. name .. "`'s top comment says `" .. history .. "`: say what the module does, and leave history to git"}) end
local doc = comment_above(src, type_line)
local doc_history = history_word(doc.lines)
if doc.first > 1 and doc_history ~= nil then
push(report, {path = f.path, line = doc.first, check = "module_doc", what = "`" .. name .. "`'s doc says `" .. doc_history .. "`: say what the module does, and leave history to git"})
end
return nil
end
function self_test()
local at = "cookbook:roc/plants/find_unclear_names/"
check_plants("find_unclear_names", "cookbook:roc/find_unclear_names.shale", CHECKS, {
{glob = at .. "pure_mutator.roc", counts = {pure_mutator = 7}, says = {"pure_mutator.roc:3: pure_mutator: `push_cat` is pure and gives a new `List(U64)`", "`get_speed`"}},
{glob = at .. "quiet_pure_mutator.roc"},
{glob = at .. "terms.roc", counts = {pure_mutator = 2}, says = {"`set_cookie_header`", "`set_cookies`"}},
{glob = at .. "terms.roc", args = {"terms=" .. at .. "terms.txt"}, counts = {pure_mutator = 1}, says = {"`set_cookies`"}},
{glob = at .. "terms.roc", args = {"terms=" .. at .. "no_such.txt"}, stops = true, says = {"no word list"}},
{glob = at .. "abbreviation.roc", counts = {abbreviation = 4}, says = {"abbreviation.roc:3: abbreviation: `max_vis_cats` abbreviates: vis", "`SunPos` abbreviates: pos", "`dist` abbreviates: dist"}},
{glob = at .. "quiet_abbreviation.roc"},
{glob = at .. "abbreviation.roc", args = {"abbreviations=" .. at .. "project_words.txt"}, counts = {abbreviation = 4}, says = {"`max_vis_cats` abbreviates: vis, cats"}},
{glob = at .. "short_words/*.roc", counts = {abbreviation = 5}, says = {"Tbl.roc:1: abbreviation: `Tbl` abbreviates: tbl", "Tbl.roc:4: abbreviation: `Trk` abbreviates: trk", "Tbl.roc:7: abbreviation: `trk` abbreviates: trk", "`pts` abbreviates: pts", "Tbl.roc:9: abbreviation: `hgt` abbreviates: hgt"}},
{glob = at .. "quiet_short_words/*.roc"},
{glob = at .. "short_words/*.roc", args = {"accepted=" .. at .. "project_terms.txt"}, counts = {abbreviation = 3}, says = {"`Tbl` abbreviates: tbl", "`pts` abbreviates: pts", "`hgt` abbreviates: hgt"}},
{glob = at .. "quiet_short_words/*.roc", args = {"accepted=" .. at .. "project_terms.txt"}},
{glob = at .. "quiet_short_words/*.roc", args = {"accepted=" .. at .. "no_reason.txt"}, stops = true, says = {"`qty` has no reason"}},
{glob = at .. "quiet_abbreviation.roc", args = {"abbreviations=" .. at .. "no_such.txt"}, stops = true, says = {"no word list"}},
{glob = at .. "long_abbreviations/*.roc", counts = {abbreviation = 11}, says = {"Parser.roc:5: abbreviation: `attrs` abbreviates: attrs", "`idxes` abbreviates: idxes", "`vals` abbreviates: vals", "`delim` abbreviates: delim", "`parse_args` abbreviates: args", "`params` abbreviates: params", "`elem_count` abbreviates: elem", "`expr_text` abbreviates: expr", "`stmt_kind` abbreviates: stmt", "`tmpl_name` abbreviates: tmpl"}},
{glob = at .. "long_abbreviations/*.roc", args = {"accepted=" .. at .. "project_args.txt"}, counts = {abbreviation = 9}, says = {"`attrs` abbreviates: attrs", "`params` abbreviates: params"}},
{glob = at .. "quiet_long_abbreviations/*.roc"},
{glob = at .. "common_words/*.roc", counts = {abbreviation = 2}, says = {"`Flw` abbreviates: flw", "`night_dmr` abbreviates: dmr"}},
{glob = at .. "quiet_common_words/*.roc"},
{glob = at .. "tags.roc", counts = {abbreviation = 5}, says = {"tags.roc:14: abbreviation: `TmplGone` abbreviates: tmpl", "tags.roc:4: abbreviation: `NoRef` abbreviates: ref", "tags.roc:4: abbreviation: `Ref` abbreviates: ref", "tags.roc:6: abbreviation: `TmplMissing` abbreviates: tmpl", "tags.roc:12: abbreviation: `BadAttr` abbreviates: attr"}},
{glob = at .. "quiet_tags.roc"},
{glob = at .. "module_doc/*.roc", counts = {module_doc = 5}, says = {"`NoDoc` has no `##` doc", "`Hashless` has no `##` doc", "`Old`'s top comment says `originally`", "`Sky`'s top comment says `used to`", "Sun.roc:3: module_doc: `Sun`'s doc says `originally`"}},
{glob = at .. "quiet_module_doc/*.roc"},
{glob = at .. "module_doc_private/*.roc", counts = {module_doc = 2}, says = {"`Shown` has no `##` doc", "`Silent` has no `##` doc"}},
{glob = at .. "broken/*.roc", stops = true, says = {"refused: "}},
})
return nil
end
function run_check()
local lists = {abbreviations = word_set(ABBREVIATIONS_FILE), words = word_set(SHORT_WORDS_FILE), accepted = accepted_terms(ACCEPTED_FILE)}
if PROJECT_ACCEPTED_FILE ~= "" then
for term in keys(accepted_terms(PROJECT_ACCEPTED_FILE)) do lists.accepted[term] = true end
end
local terms = TERMS_FILE == "" and {} or word_set(TERMS_FILE)
local paths = glob(GLOB)
local parsed = parse_roc_files(paths)
local report = {}
for f in parsed.files do
local declared = declarations_of(f)
local aliases = {}
for d in declared do
if d.kind == "type" and not d.is_nominal then aliases[d.name] = d.underlying end
end
for d in declared do
if d.kind == "value" then judge_mutator(d, aliases, terms, report) end
end
if not house_leaves_out("find_unclear_names", "abbreviation") then judge_abbreviations(f, declared, lists, report) end
judge_module_doc(f, declared, report)
end
local verdict = verdict_of("find_unclear_names", CHECKS, report, #paths)
verdict.summary = verdict.summary .. house_note("find_unclear_names")
print_findings(verdict.summary, verdict.found)
fail_if_refused("find_unclear_names", 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