find_retired_words
Roc
It also imports Finding, Text, Tree from the shared Roc library.
cookbook/roc/find_retired_words/find_retired_words.roc, 117 lines
## find_retired_words, in Roc on Shale's platform (roc_platform/README.md): a
## project held to the words it has decided on. The project keeps a file of
## them, `kept: retired, retired` a line, and the recipe reports each
## identifier and comment in its .roc files that uses a retired word. Its
## launcher, cookbook/roc/find_retired_words.shale, is how it is run, and its
## header says the rules, `retired_name` and `retired_comment`.
## check_goldens.shale, beside this, holds its output on the plants to its
## goldens, line for line.
##
## cd <repo> && shale cookbook:roc/find_retired_words.shale words=vocabulary.txt
## shale cookbook:roc/find_retired_words.shale self_test=1
##
## The arguments: `glob` (`**/*.roc`), `words` (the project's file of
## decided words, which must be given) and `self_test` (`self_test=1` runs
## the plants, each through the launcher).
##
## This root reads the words file (Words), globs the files (`Shale.glob!`),
## has Roc's parser read them (`Shale.roc_tree!`) and each one's text
## (`Shale.read!`), and prints the verdict (`Shale.print!`, `Shale.fail!`).
## Its modules are beside it: Retired, the two checks, over Identifiers and
## Words; and SelfTest. Tree, Text and Finding are the cookbook's Roc
## library, cookbook/roc/lib/.
## budget: steps=800000000 arena_bytes=2000000000 output_bytes=4000000 programs=100 roc_cpu_ms=600000
app [main!] { lib: "../lib/main.roc", pf: platform "../../../roc_platform/platform/main.roc" }
import pf.Shale
import lib.Finding
import Retired
import SelfTest
import Words
main! : {} => {}
main! = |{}| {
is_self_test = Shale.arg!("self_test", "") == "1"
pattern = Shale.arg!("glob", "**/*.roc")
words_file = Shale.arg!("words", "")
if is_self_test {
SelfTest.run!(checks)
} else {
run_check!({ pattern, words_file })
}
}
## The check over the glob's files: the verdict printed, then a stop when a
## file didn't parse, or else when there are findings, the summary the last
## line a caller reads.
run_check! : { pattern : Str, words_file : Str } => {}
run_check! = |{ pattern, words_file }| {
if words_file == "" {
Shale.fail!("find_retired_words: give words=<the project's file of decided words>")
}
decided = Words.read!(words_file)
paths = Shale.glob!(pattern)
var $findings = []
var $refused = []
for file in Shale.roc_tree!(paths) {
if file.err == "" {
names = Retired.names({ path: file.path, syntax_nodes: file.nodes }, decided)
comments = Retired.comments({ path: file.path, text: read_text!(file.path) }, decided)
$findings = $findings.concat(names).concat(comments)
} else if file.err.starts_with(file.path) {
$refused = $refused.append(file.err)
} else {
$refused = $refused.append("${file.path}: ${file.err}")
}
}
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_retired_words: ${refusals}, ${why}")
}
if !(found.is_empty()) {
Shale.fail!(summary)
}
}
## 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_retired_words: ${path} went missing during the check")
""
}
}
## The checks, in the order the summary counts them.
checks : List(Str)
checks = ["retired_name", "retired_comment"]
## The counts, `find_retired_words (Roc): N files; retired_name N,
## retired_comment N`.
summary_of : List(Finding), U64 -> Str
summary_of = |findings, file_count| {
"find_retired_words (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_retired_words/Retired.roc, 110 lines
## The two checks, one for each place a retired word can be: `retired_name`,
## an identifier that holds one, read from Roc's own tree, and
## `retired_comment`, a comment that holds one, read from the file's lines.
import lib.Finding
import Identifiers
import lib.Text
import lib.Tree
import Words
Retired := [].{
## Each identifier in the tree that holds a retired word, a finding at
## its node's line, once a line for each name and word.
names : { path : Str, syntax_nodes : List(Tree.Node) }, Words.Decided -> List(Finding)
names = |file, decided| {
var $found = []
var $seen = Set.empty()
var $place = 0
for node in file.syntax_nodes {
$place = $place + 1
for name in Identifiers.of_node(file.syntax_nodes, node) {
for word in Words.retired_in(name.to_utf8(), decided) {
line = line_of(file.syntax_nodes, $place)
key = "${line.to_str()}|${name}|${word}"
if !($seen.contains(key)) {
$seen = $seen.insert(key)
what = "${name}: ${word} is ${Words.kept_for(decided, word)} here"
$found = $found.append({ path: file.path, line, check: "retired_name", what })
}
}
}
}
$found
}
## Each retired word in a comment of the file's text, a finding at its
## line, once a line.
comments : { path : Str, text : Str }, Words.Decided -> List(Finding)
comments = |file, decided| {
var $found = []
var $number = 0
for source_line in Text.lines(file.text) {
$number = $number + 1
match comment_on_line(source_line) {
Comment(comment) =>
for word in Words.retired_in(comment, decided) {
what = "${word} is ${Words.kept_for(decided, word)} here"
$found = $found.append({ path: file.path, line: $number, check: "retired_comment", what })
}
NoComment => {}
}
}
$found
}
}
## The line of the node at `place`, or of the nearest node around it that
## has one; 0 when none does (the Shale original's `node_line`).
line_of : List(Tree.Node), U64 -> U64
line_of = |syntax_nodes, place| {
var $place = place
var $line = 0
while $place != 0 and $line == 0 {
node = Tree.node_at(syntax_nodes, $place)
if node.line == 0 {
$place = node.parent
} else {
$line = node.line
}
}
$line
}
## The bytes after the `#` that starts the line's comment, or `NoComment`.
## A `#` inside a string or a character starts none, and a line of a `\\`
## multiline string has no comment at all.
comment_on_line : Str -> [Comment(List(U8)), NoComment]
comment_on_line = |line| {
bytes = line.to_utf8()
if !(bytes.contains('#')) {
return NoComment
}
count = bytes.len()
start = bytes.find_first_index(|byte| !(is_space(byte))) ?? count
if (bytes.get(start) ?? 0) == '\\' and (bytes.get(start + 1) ?? 0) == '\\' {
return NoComment
}
var $at = 0
while $at < count {
byte = bytes.get($at) ?? 0
if byte == '"' or byte == '\'' {
$at = $at + 1
while $at < count and (bytes.get($at) ?? 0) != byte {
if (bytes.get($at) ?? 0) == '\\' {
$at = $at + 1
}
$at = $at + 1
}
} else if byte == '#' {
return Comment(bytes.drop_first($at + 1))
}
$at = $at + 1
}
NoComment
}
## A byte Shale's `trim` takes off a text's ends: a space, a tab, a carriage
## return or a newline.
is_space : U8 -> Bool
is_space = |byte| byte == ' ' or byte == '\t' or byte == '\r' or byte == '\n'
cookbook/roc/find_retired_words/SelfTest.roc, 196 lines
## The recipe's self-test: each plant under
## cookbook/roc/plants/find_retired_words/ 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 running and judging of a row,
## 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| {
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_retired_words 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_retired_words self_test: PASS (${row_count} rows: ${proof})")
}
}
## The launcher, which the self-test runs each plant through.
launcher : Str
launcher = "cookbook:roc/find_retired_words.shale"
plants : Str
plants = "cookbook:roc/plants/find_retired_words/"
## The plants' own words file, as the argument that names it.
words : Str
words = "words=${plants}words.txt"
## 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 nonzero whatever its findings.
Row : {
plant : Str,
arguments : List(Str),
counts : List((Str, U64)),
says : List(Str),
stops : Bool,
}
## What a plant is run with and must give: its findings, and what its
## output must hold.
Wanted : {
plant : Str,
arguments : List(Str),
counts : List((Str, U64)),
says : List(Str),
}
## A plant that must give its findings, and exit nonzero when it has any.
fires : Wanted -> Row
fires = |wanted| {
plant: "${plants}${wanted.plant}",
arguments: wanted.arguments,
counts: wanted.counts,
says: wanted.says,
stops: Bool.False,
}
## A plant that must stop, with no summary as its last line.
stops : Wanted -> Row
stops = |wanted| {
firing = fires(wanted)
{ ..firing, stops: Bool.True }
}
## A words file below `plants` the plant `clean.roc` is run with, which must
## stop the run saying what it says.
stops_on_words : Str, Str -> Row
stops_on_words = |words_file, said|
stops({ plant: "clean.roc", arguments: ["words=${plants}${words_file}"], counts: [], says: [said] })
rows : List(Row)
rows = [
fires({
plant: "names.roc",
arguments: [words],
counts: [("retired_name", 9)],
says: [
"names.roc:6: retired_name: tilt_step: tilt is lean here",
"RideTour: tour is ride here",
"names.roc:12: retired_name: tour_stops",
"names.roc:16: retired_name: .tilt",
],
}),
fires({
plant: "names_unseen.roc",
arguments: [words],
counts: [("retired_name", 3)],
says: [
"names_unseen.roc:3: retired_name: tilt_now",
"names_unseen.roc:7: retired_name: tilt_of",
"names_unseen.roc:12: retired_name: tilt_pair",
],
}),
fires({
plant: "comments.roc",
arguments: [words],
counts: [("retired_comment", 3)],
says: ["comments.roc:2: retired_comment: tilt is lean here"],
}),
fires({ plant: "clean.roc", arguments: [words], counts: [], says: [] }),
stops({ plant: "broken/*.roc", arguments: [words], counts: [("retired_name", 1)], says: ["refused: "] }),
stops({ plant: "clean.roc", arguments: [], counts: [], says: ["give words="] }),
stops_on_words("no_such.txt", "no words file"),
stops_on_words("words_malformed.txt", "words_malformed.txt:2: expected"),
stops_on_words("words_twice.txt", "`tilt` is retired twice"),
stops_on_words("words_both.txt", "`tilt` is both kept and retired"),
]
## 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_retired_words/Words.roc, 123 lines
## A project's decided words, read from its words file: each line
## `kept: retired, retired`, in lower case, such as `lean: tilt`, a blank
## line or one starting with `#` skipped. A missing file, a malformed line, a
## word retired twice or a word both kept and retired stops the run, as the
## Shale original did, on the same line and in the same words.
import pf.Shale
import lib.Text
Words := [].{
## Each retired word, with the word kept for it.
Decided : Dict(Str, Str)
## The words file at `path`, read and checked.
read! : Str => Words.Decided
read! = |path| {
if !(Shale.exists!(path)) {
Shale.fail!("find_retired_words: no words file ${path}")
}
text = match Shale.read!(path) {
Found(found) => found
Missing => {
Shale.fail!("find_retired_words: no words file ${path}")
""
}
}
var $decided = Dict.empty()
var $retired_in_order = []
var $kept = Set.empty()
var $number = 0.U64
for raw_line in Text.lines(text) {
$number = $number + 1
line = Text.trim(raw_line)
if line != "" and !(line.starts_with("#")) {
place = "${path}:${$number.to_str()}"
entry = read_entry!(line, place)
$kept = $kept.insert(entry.kept)
for word in entry.retired {
if $decided.contains(word) {
Shale.fail!("find_retired_words: ${place}: `${word}` is retired twice")
}
$decided = $decided.insert(word, entry.kept)
$retired_in_order = $retired_in_order.append(word)
}
}
}
for word in $retired_in_order {
if $kept.contains(word) {
Shale.fail!("find_retired_words: ${path}: `${word}` is both kept and retired")
}
}
$decided
}
## Each retired word in `text`, once, sorted bytewise: the words of each
## name in it (a run of letters, digits and underscores) looked up.
retired_in : List(U8), Words.Decided -> List(Str)
retired_in = |text, decided| {
var $found = []
for run in name_runs(text) {
for word in Text.name_words(Str.from_utf8_lossy(run)) {
if decided.contains(word) and !($found.contains(word)) {
$found = $found.append(word)
}
}
}
$found.sort_with(Text.byte_order)
}
## The word kept for a retired one.
kept_for : Words.Decided, Str -> Str
kept_for = |decided, retired|
match decided.get(retired) {
Ok(kept) => kept
Err(_) => crash "find_retired_words: `${retired}` is not retired"
}
}
## One line of the words file, trimmed: the kept word and the words it
## retires. A line of another shape stops the run, naming its place.
read_entry! : Str, Str => { kept : Str, retired : List(Str) }
read_entry! = |line, place|
match Shale.re_find!(line, entry_pattern) {
Found(found) =>
match found.groups {
[kept, retired] => { kept, retired: retired.split_on(",").map(Text.trim) }
_ => crash "find_retired_words: the entry pattern has two groups"
}
NoMatch => {
Shale.fail!("find_retired_words: ${place}: expected `kept: retired, retired`, in lower case")
{ kept: "", retired: [] }
}
}
## A words file's line: the kept word, a colon, and the retired words
## separated by commas.
entry_pattern : Str
entry_pattern = "^([a-z0-9]+): *([a-z0-9]+(?:, *[a-z0-9]+)*)$"
## The runs of letters, digits and underscores in the bytes, left to right
## (the Shale original's `[A-Za-z0-9_]+`, every match).
name_runs : List(U8) -> List(List(U8))
name_runs = |bytes| {
var $runs = []
var $run = []
for byte in bytes {
if is_name_byte(byte) {
$run = $run.append(byte)
} else if !($run.is_empty()) {
$runs = $runs.append($run)
$run = []
}
}
if $run.is_empty() {
$runs
} else {
$runs.append($run)
}
}
is_name_byte : U8 -> Bool
is_name_byte = |byte|
Text.is_capital(byte) or Text.is_small_letter(byte) or Text.is_digit(byte) or byte == '_'
cookbook/roc/find_retired_words/Identifiers.roc, 59 lines
## The identifiers a node of Roc's tree holds, by its kind: the attribute
## that holds the name, or for a name a header or an import exposes in lower
## case, the `value` of a `text` kid.
import lib.Tree
Identifiers := [].{
## The identifiers a node of the tree holds, in the order the Shale
## original read them: each named attribute that is not empty, then each
## `text` kid's value.
of_node : List(Tree.Node), Tree.Node -> List(Str)
of_node = |syntax_nodes, node| {
named = name_attributes(node.kind)
.map(|attribute_name| Tree.attribute(node, attribute_name))
.keep_if(|name| name != "")
if node.kind == "exposed-lower-ident" {
named.concat(text_kid_values(syntax_nodes, node))
} else {
named
}
}
}
## Which attributes hold the identifier in each kind of node that has one. A
## `field` node may hold a field's name under either attribute. A `method` is
## a `where` clause's constraint, and a `p-as` the name an `as` pattern gives.
name_attributes : Str -> List(Str)
name_attributes = |kind|
match kind {
"ty" => ["name"]
"ty-var" => ["raw"]
"e-ident" => ["raw"]
"p-ident" => ["raw"]
"e-tag" => ["raw"]
"p-tag" => ["raw"]
"s-type-anno" => ["name"]
"s-import" => ["raw"]
"s-var" => ["name"]
"anno-record-field" => ["name"]
"record-field" => ["name"]
"header" => ["name"]
"field" => ["field", "name"]
"segment" => ["field"]
"e-method-call" => ["method"]
"p-list-rest" => ["name"]
"method" => ["name"]
"p-as" => ["name"]
"exposed-upper-ident" => ["text"]
_ => []
}
## The values of the node's `text` kids, those that are not empty.
text_kid_values : List(Tree.Node), Tree.Node -> List(Str)
text_kid_values = |syntax_nodes, node|
node.kids
.map(|kid| Tree.node_at(syntax_nodes, kid))
.keep_if(|kid| kid.kind == "text")
.map(|kid| Tree.attribute(kid, "value"))
.keep_if(|value| value != "")
Shale original
cookbook/roc/check_vocabulary.shale, 209 lines, at 0bfe8904
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 holds a project to the words it has decided on. The project
-- keeps a file of them, and the recipe reports each identifier and comment
-- in its .roc files that uses a word the file retires. The word lists belong
-- to the project, so none is built in here.
--
-- cd <repo> && shale <shale>/cookbook/roc/check_vocabulary.shale words=vocabulary.txt
-- shale cookbook:roc/check_vocabulary.shale self_test=1
--
-- The arguments:
-- glob the files to check, `**/*.roc` by default;
-- words the project's file of decided words, which must be given;
-- self_test with `self_test=1`, check the plants in
-- `cookbook/roc/plants/check_vocabulary/`.
--
-- Each line of the words file is `kept: retired, retired`, in lower case,
-- such as `lean: tilt`. A blank line or one starting with `#` is skipped.
-- The file is matched by whole words, so a plural that should go needs its
-- own entry, and a word with a good second meaning can't be listed at all.
-- A malformed line stops the run, as does a word retired twice or a word
-- both kept and retired.
--
-- Identifiers are read from the tree of Roc's own parser and split into words
-- at underscores and capitals, so `TiltStep` and `tilt_step` both hold
-- `tilt`. They include the names a header or an import exposes, a `where`
-- clause's methods and an `as` pattern's name. Comments are read as words too, and the text of a string doesn't
-- count. There are two checks, one for each place a word can be:
--
-- retired_name an identifier that holds a retired word;
-- retired_comment a comment that holds one.
--
-- The output is the counts, one line per finding,
-- `path:line: retired_name: tilt_step: tilt is lean here`, and the counts
-- again (cookbook/findings.shale). Each word is reported once a line for
-- each name that holds it. 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 WORDS_FILE = arg("words", "")
use("./declared.shale")
use("cookbook:findings.shale")
use("./parsed.shale")
use("./gate_recipe.shale")
const CHECKS = {"retired_name", "retired_comment"}
-- Which attribute holds the identifier in each kind of node that has one. A
-- `field` node may hold a field's name under either attribute. A `method` is a
-- `where` clause's constraint, and a `p-as` the name an `as` pattern gives.
const IDENTIFIER_ATTRIBUTES = {
ty = {"name"},
["ty-var"] = {"raw"},
["e-ident"] = {"raw"},
["p-ident"] = {"raw"},
["e-tag"] = {"raw"},
["p-tag"] = {"raw"},
["s-type-anno"] = {"name"},
["s-import"] = {"raw"},
["s-var"] = {"name"},
["anno-record-field"] = {"name"},
["record-field"] = {"name"},
header = {"name"},
field = {"field", "name"},
segment = {"field"},
["e-method-call"] = {"method"},
["p-list-rest"] = {"name"},
method = {"name"},
["p-as"] = {"name"},
["exposed-upper-ident"] = {"text"},
}
-- The kinds of node whose identifier is the `value` of a `text` node among its
-- kids: a lower-case name a header or an import exposes.
const TEXT_KID_IDENTIFIERS = {["exposed-lower-ident"] = true}
-- The identifiers node `i` of `tree` holds.
function identifiers_at(tree, i)
local out = {}
local node = tree[i]
for name_attribute in get(IDENTIFIER_ATTRIBUTES, node.kind, {}) do
local name = attribute(tree, i, name_attribute)
if name ~= "" then push(out, name) end
end
if has_key(TEXT_KID_IDENTIFIERS, node.kind) then
for k in node.kids do
if tree[k].kind == "text" and get(tree[k], "value", "") ~= "" then push(out, tree[k].value) end
end
end
return out
end
-- The words file as a map from each retired word to the word kept for it.
function retired_words(path)
if not exists(path) then fail("check_vocabulary: no words file " .. path) end
local kept_by_retired = {}
local kept_words = {}
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-z0-9]+): *([a-z0-9]+(?:, *[a-z0-9]+)*)$")
if m == nil then fail("check_vocabulary: " .. path .. ":" .. number .. ": expected `kept: retired, retired`, in lower case") end
kept_words[m.groups[1]] = true
for retired in split(m.groups[2], ",") do
local word = trim(retired)
if has_key(kept_by_retired, word) then fail("check_vocabulary: " .. path .. ":" .. number .. ": `" .. word .. "` is retired twice") end
kept_by_retired[word] = m.groups[1]
end
end
end
for word in keys(kept_by_retired) do
if has_key(kept_words, word) then fail("check_vocabulary: " .. path .. ": `" .. word .. "` is both kept and retired") end
end
return kept_by_retired
end
-- The line of node `at`, or of the nearest node around it that has one.
function node_line(tree, at)
local k = at
while k ~= 0 and tree[k].line == 0 do k = tree[k].parent end
return k == 0 and 0 or tree[k].line
end
-- Each retired word in `text`, once, as the words of the names in it.
function retired_in(text, kept_by_retired)
local found = {}
for m in re_find_all(text, "[A-Za-z0-9_]+") do
for w in name_words(m.text) do
if has_key(kept_by_retired, w) then found[w] = true end
end
end
return sort(keys(found))
end
function judge_names(f, kept_by_retired, report)
local tree = f.nodes
local seen = {}
for i = 1, #tree do
for name in identifiers_at(tree, i) do
for w in retired_in(name, kept_by_retired) do
local line = node_line(tree, i)
local key = line .. "|" .. name .. "|" .. w
if not has_key(seen, key) then
seen[key] = true
push(report, {path = f.path, line = line, check = "retired_name", what = name .. ": " .. w .. " is " .. kept_by_retired[w] .. " here"})
end
end
end
end
return nil
end
function judge_comments(f, kept_by_retired, report)
local number = 0
for l in lines(read(f.path)) do
number = number + 1
local comment = comment_on_line(l)
if comment ~= nil then
for w in retired_in(comment, kept_by_retired) do
push(report, {path = f.path, line = number, check = "retired_comment", what = w .. " is " .. kept_by_retired[w] .. " here"})
end
end
end
return nil
end
function self_test()
local at = "cookbook:roc/plants/check_vocabulary/"
local words = "words=" .. at .. "words.txt"
check_plants("check_vocabulary", "cookbook:roc/check_vocabulary.shale", CHECKS, {
{glob = at .. "names.roc", args = {words}, counts = {retired_name = 9}, says = {"names.roc:6: retired_name: tilt_step: tilt is lean here", "RideTour: tour is ride here", "names.roc:12: retired_name: tour_stops", "names.roc:16: retired_name: .tilt"}},
{glob = at .. "names_unseen.roc", args = {words}, counts = {retired_name = 3}, says = {"names_unseen.roc:3: retired_name: tilt_now", "names_unseen.roc:7: retired_name: tilt_of", "names_unseen.roc:12: retired_name: tilt_pair"}},
{glob = at .. "comments.roc", args = {words}, counts = {retired_comment = 3}, says = {"comments.roc:2: retired_comment: tilt is lean here"}},
{glob = at .. "clean.roc", args = {words}},
{glob = at .. "broken/*.roc", args = {words}, stops = true, counts = {retired_name = 1}, says = {"refused: "}},
{glob = at .. "clean.roc", stops = true, says = {"give words="}},
{glob = at .. "clean.roc", args = {"words=" .. at .. "no_such.txt"}, stops = true, says = {"no words file"}},
{glob = at .. "clean.roc", args = {"words=" .. at .. "words_malformed.txt"}, stops = true, says = {"words_malformed.txt:2: expected"}},
{glob = at .. "clean.roc", args = {"words=" .. at .. "words_twice.txt"}, stops = true, says = {"`tilt` is retired twice"}},
{glob = at .. "clean.roc", args = {"words=" .. at .. "words_both.txt"}, stops = true, says = {"`tilt` is both kept and retired"}},
})
return nil
end
function run_check()
if WORDS_FILE == "" then fail("check_vocabulary: give words=<the project's file of decided words>") end
local kept_by_retired = retired_words(WORDS_FILE)
local paths = glob(GLOB)
local parsed = parse_roc_files(paths)
local report = {}
for f in parsed.files do
judge_names(f, kept_by_retired, report)
judge_comments(f, kept_by_retired, report)
end
local verdict = verdict_of("check_vocabulary", CHECKS, report, #paths)
print_findings(verdict.summary, verdict.found)
fail_if_refused("check_vocabulary", 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