hunt_names_c
Roc
It also imports Item, Mask, Paths, Split, Words from the C splitter.
cookbook/c/hunt_names/hunt_names.roc, 257 lines
## hunt_names, in Roc on Shale's platform (roc_platform/README.md): Shale's C
## hunted for names that break c/docs/style.md's "Names" or say too little,
## from the splitter the C recipes share (cookbook/c/items/, a package). A
## finding is a question for a reader, never a verdict. Its launcher,
## cookbook/c/hunt_names.shale, is how it is run, and its header says the
## arguments and the checks. check_goldens.shale, beside this, holds its
## output on the plants to its goldens, line for line.
##
## shale cookbook:c/hunt_names.shale dir=c/host
## shale cookbook:c/hunt_names.shale self_test=1
##
## The effects: `Shale.arg!` for the arguments, `Shale.read!` for the word
## tables (cookbook/words/) and each file's text, `Shale.list!` and
## `Shale.glob!` for the files, and `Shale.print!` and `Shale.fail!` for the
## verdict. Checks, beside this, checks a file; Abbreviation, the tree's
## names; SelfTest holds it to the plants.
## budget: steps=200000000 arena_bytes=1000000000 roc_cpu_ms=600000
app [main!] {
items: "../items/main.roc",
pf: platform "../../../roc_platform/platform/main.roc",
}
import pf.Shale
import items.Item
import items.Mask
import items.Paths
import items.Split
import items.Words
import Abbreviation
import Checks
import SelfTest
main! : {} => {}
main! = |{}| {
if integer_or_stop!("self_test", Shale.arg!("self_test", "0")) == 1 {
SelfTest.run!(hunt!)
} else {
folder = Shale.arg!("dir", "c")
hunted = hunt!(folder)
for finding in hunted.found {
Shale.print!(Checks.finding_line(finding))
}
Shale.print!(summary(folder, hunted))
for line in by_folder(hunted.found) {
Shale.print!(line)
}
}
}
## A value given as `name=`, which must be an integer, as Shale's `arg` reads
## one whose default is.
integer_or_stop! : Str, Str => I64
integer_or_stop! = |name, given|
match I64.from_str(given) {
Ok(value) => value
Err(_) => {
Shale.fail!("hunt_names: ${name}=${given} is not an integer")
0
}
}
## The findings over the folder, sorted by place, and how many files it
## read.
hunt! : Str => { found : List(Checks.Finding), files : U64 }
hunt! = |folder| {
tables = tables!({})
files = c_files_under!(folder)
var $found = []
var $named = []
for path in files {
text = read_text!(path)
checked = Checks.of_file(path, Split.lines(text), split_or_stop!(path, text), tables)
$found = $found.concat(checked.found)
$named = $named.concat(checked.named)
}
all = $found.concat(Abbreviation.findings($named, tables.abbreviations))
{ found: all.sort_with(place_order), files: files.len() }
}
## Findings in the order of their path, line, check and why.
place_order : Checks.Finding, Checks.Finding -> [Before, Same, After]
place_order = |a, b| {
by_path = Words.byte_order(a.path, b.path)
if by_path != Same {
by_path
} else if a.line < b.line {
Before
} else if a.line > b.line {
After
} else {
by_check = Words.byte_order(a.check, b.check)
if by_check != Same {
by_check
} else {
Words.byte_order(a.why, b.why)
}
}
}
## The line of counts: the files, the findings and each check's.
summary : Str, { found : List(Checks.Finding), files : U64 } -> Str
summary = |folder, hunted| {
parts = Checks.check_names.map(|check| "${check} ${hunted.found.count_if(|finding| finding.check == check).to_str()}")
"hunt_names: ${hunted.files.to_str()} files under ${folder}; ${hunted.found.len().to_str()} findings: ${Str.join_with(parts, ", ")}"
}
## The findings counted by each file's folder and check, a line each, in the
## order of `<folder> <check>`.
by_folder : List(Checks.Finding) -> List(Str)
by_folder = |found| {
no_counts : Dict(Str, U64)
no_counts = Dict.empty()
counts = found.fold(
no_counts,
|so_far, finding| {
key = "${folder_of(finding.path)} ${finding.check}"
so_far.insert(key, (so_far.get(key) ?? 0) + 1)
},
)
counts
.to_list()
.sort_with(|(a, _), (b, _)| Words.byte_order(a, b))
.map(|(key, count)| " ${key}: ${count.to_str()}")
}
## The path's folder, as Shale's `dirname` gives it: up to its last `/`.
folder_of : Str -> Str
folder_of = |path| {
bytes = path.to_utf8()
match bytes.find_last_index(|byte| byte == '/') {
Ok(slash) => Mask.text(bytes.take_first(slash))
Err(_) => ""
}
}
## The word tables of cookbook/words/: vague.txt's, containers.txt's with
## `data` and `info`, and c_abbreviations.txt's.
tables! : {} => Checks.Tables
tables! = |{}| {
containers = word_table!("containers.txt").insert("data").insert("info")
{ vague: word_table!("vague.txt"), containers, abbreviations: abbreviation_table!({}) }
}
## A table's text. A table that is not there stops the run.
table_text! : Str => Str
table_text! = |file|
match Shale.read!("cookbook:words/${file}") {
Found(text) => text
Missing => {
Shale.fail!("hunt_names: cookbook/words/${file} is not there")
""
}
}
## A line's text before its note, the `--` that starts one, trimmed.
before_note : List(U8) -> List(U8)
before_note = |line| {
kept = match Mask.pair_from(line, ('-', '-'), 0) {
Ok(note) => line.take_first(note)
Err(_) => line
}
Mask.trimmed(kept)
}
## A word table of cookbook/words/, a word a line. A word twice, or a line of
## two, is a mistake in the table: it stops the run.
word_table! : Str => Set(Str)
word_table! = |file| {
var $words = Set.empty()
for line in Split.lines(table_text!(file)) {
word = Mask.text(before_note(line))
if word.contains(" ") or $words.contains(word) {
Shale.fail!("hunt_names: cookbook/words/${file}: `${word}` is no single new word")
}
if word != "" {
$words = $words.insert(word)
}
}
$words
}
## cookbook/words/c_abbreviations.txt: an abbreviation to its word, a pair a
## line. An abbreviation twice, or a line of one word or three, stops the
## run.
abbreviation_table! : {} => Dict(Str, Str)
abbreviation_table! = |{}| {
file = "cookbook/words/c_abbreviations.txt"
var $table = Dict.empty()
for line in Split.lines(table_text!("c_abbreviations.txt")) {
words = words_in(before_note(line))
match (words.get(0), words.get(1)) {
(Ok(short), Ok(full)) if words.len() == 2 => {
if $table.get(short) != Err(KeyNotFound) {
Shale.fail!("hunt_names: ${file}: `${short}` twice")
}
$table = $table.insert(short, full)
}
_ =>
if !(words.is_empty()) {
Shale.fail!("hunt_names: ${file}: `${Mask.text(line)}` is no pair of an abbreviation and its word")
}
}
}
$table
}
## The words of a line, as Shale's `words` cuts them: at each run of `\s`.
words_in : List(U8) -> List(Str)
words_in = |line| {
var $words = []
var $at = Mask.spaces_end(line, 0)
while $at < line.len() {
end = match line.drop_first($at).find_first_index(Mask.is_space) {
Ok(offset) => $at + offset
Err(_) => line.len()
}
$words = $words.append(Mask.text(line.sublist({ start: $at, len: end - $at })))
$at = Mask.spaces_end(line, end)
}
$words
}
## The file's text. A file the walk named 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!("hunt_names: ${path} went missing during the walk")
""
}
}
## The file's items, or the run stopped with the line the dialect does not
## account for.
split_or_stop! : Str, Str => List(Item)
split_or_stop! = |path, text|
match Split.items({ path, text, uses: Bool.False }) {
Ok(items) => items
Err(why) => {
Shale.fail!(why)
[]
}
}
## The C files under the folder, sorted, any folder named `out` (c/out, the
## build's output) left out. A folder that is not there stops the run, in
## the words of the Shale original's walk: a check that can't run fails.
c_files_under! : Str => List(Str)
c_files_under! = |folder| {
if Shale.list!(folder) == Missing {
Shale.fail!("`walk(\"${folder}\")`: not found (FileNotFound)")
}
paths = Shale.glob!("${folder}/**/*.c").concat(Shale.glob!("${folder}/**/*.h"))
paths.keep_if(|path| !(Paths.is_in_out_folder(folder, path))).sort_with(Words.byte_order)
}
cookbook/c/hunt_names/Abbreviation.roc, 68 lines
## hunt_names' `abbreviation` check, over the whole tree's top-level names: a
## name with a word of cookbook/words/c_abbreviations.txt whose spelled-out
## word another top-level name of the tree uses is one thing with two
## spellings (`bi_split` beside `builtin_scan`). One finding a file and
## abbreviation, at its first name's line, naming its names, as
## cookbook/c/hunt_names.shale, the Shale original, words it.
import Checks
Abbreviation := [].{
## The tree's findings, from its names in the order the files and their
## items gave them, and the table of each abbreviation's word.
findings : List(Checks.Named), Dict(Str, Str) -> List(Checks.Finding)
findings = |named, table| {
spelled = named.fold(Set.empty(), |words, each| each.words.fold(words, |all, word| all.insert(word)))
var $short = Dict.empty()
for each in named {
for word in distinct(each.words) {
match table.get(word) {
Ok(full) if spelled.contains(full) => {
key = "${each.path}|${word}"
entry = $short.get(key) ?? { path: each.path, line: each.line, word, full, names: [] }
$short = $short.insert(key, { ..entry, names: entry.names.append(each.name) })
}
_ => {}
}
}
}
$short.to_list().map(|(_, entry)| finding(entry))
}
}
## One file's abbreviation: where it is first, the word and its spelled-out
## word, and the names that hold it.
Short : { path : Str, line : U64, word : Str, full : Str, names : List(Str) }
## The finding of a file's abbreviation: its first four names, and how many
## more.
finding : Short -> Checks.Finding
finding = |entry| {
names = distinct(entry.names)
listed = "`${Str.join_with(names.take_first(4), "`, `")}`"
shown = if names.len() > 4 {
"${listed} and ${(names.len() - 4).to_str()} more"
} else {
listed
}
count = if names.len() == 1 {
"1 name"
} else {
"${names.len().to_str()} names"
}
why = "`${entry.word}` for `${entry.full}`, which other names spell out, in ${count} here: ${shown}"
{ path: entry.path, line: entry.line, check: "abbreviation", why }
}
## Each text once, in the order first seen, as Shale's `unique` gives them.
distinct : List(Str) -> List(Str)
distinct = |texts|
texts.fold(
[],
|seen, text|
if seen.contains(text) {
seen
} else {
seen.append(text)
},
)
cookbook/c/hunt_names/Checks.roc, 243 lines
## hunt_names' checks of one file, every one but `abbreviation`, which needs
## the whole tree's names: a type's, a function's and a constant's case, a
## bound's words and their order, a vague function or type, `do`, and a
## vague local or parameter. The file comes split by the C recipes'
## splitter (cookbook/c/items/); each check is cookbook/c/hunt_names.shale's,
## the Shale original's, and its words are the original's.
import items.Item
import items.Mask
import items.Split
import Declared
import Names
Checks := [].{
## A finding: its file and line, its check and why it is one.
Finding : { path : Str, line : U64, check : Str, why : Str }
## A top-level name the file declares, at its item's first line, with its
## words, for `abbreviation`.
Named : { path : Str, line : U64, name : Str, words : List(Str) }
## The word tables the checks read: cookbook/words/vague.txt's,
## containers.txt's (and `data`, `info`), and c_abbreviations.txt's, an
## abbreviation to its word.
Tables : { vague : Set(Str), containers : Set(Str), abbreviations : Dict(Str, Str) }
## The checks, in the order the counts give them.
check_names : List(Str)
check_names = ["type_case", "function_case", "constant_case", "zig_bound", "bound_order", "vague", "do_word", "vague_local", "container_type", "abbreviation"]
## A finding's line: `path:line: check: why`.
finding_line : Checks.Finding -> Str
finding_line = |finding| "${finding.path}:${finding.line.to_str()}: ${finding.check}: ${finding.why}"
## The file's findings by every check but `abbreviation`, and its
## top-level names, in the order of its items.
of_file : Str, List(List(U8)), List(Item), Checks.Tables -> { found : List(Checks.Finding), named : List(Checks.Named) }
of_file = |path, lines, items, tables| {
var $found = []
var $names = []
for item in items {
opening = lines.get(item.first - 1) ?? []
type = type_checks(item, opening, tables)
constants = constant_checks(item)
function = function_checks(lines, item, tables)
$found = $found.concat(type.found).concat(constants.found).concat(function.found)
named_here = type.names.concat(constants.names).concat(other_names(item)).concat(function.names)
$names = $names.concat(named_here.map(|name| { name, line: item.first }))
}
finding = |each| { path, line: each.line, check: each.check, why: each.why }
named = |each| { path, line: each.line, name: each.name, words: Names.words_of(each.name) }
{ found: $found.map(finding), named: $names.map(named) }
}
}
## A finding before its file is known: its line, its check and why.
Found : { line : U64, check : Str, why : Str }
## What a check makes of an item: its findings, and the names it declares.
Checked : { found : List(Found), names : List(Str) }
## The names a local or a parameter says nothing with.
vague_locals : List(Str)
vague_locals = ["data", "info", "tmp", "temp", "stuff", "thing", "things", "misc", "util", "helper", "obj", "handle"]
## A function's lone word that is an entry point's, never vague alone.
entry_words : List(Str)
entry_words = ["run", "handle"]
## A unit a bound's name may end with, after its `MAX` or `MIN`.
units : List(Str)
units = ["MS", "NS", "US", "S", "BYTES"]
## Whether there are words and every one of them is in the table.
is_only : List(Str), Set(Str) -> Bool
is_only = |words, table| !(words.is_empty()) and words.all(|word| table.contains(word))
## A type's checks: a struct, union, typedef or enum, but no anonymous enum
## (its first constant its name, and no `typedef` opening it), which is
## constants, not a type.
type_checks : Item, List(U8), Checks.Tables -> Checked
type_checks = |item, opening, tables| {
is_type = item.kind == Struct or item.kind == Union or item.kind == Typedef or item.kind == Enum
is_anonymous = item.kind == Enum and item.enumerators.first() == Ok(item.name) and !(opening.starts_with("typedef".to_utf8()))
if is_type and !(is_anonymous) {
name = item.name
case = if Names.is_pascal_case(name) {
[]
} else {
[{ line: item.first, check: "type_case", why: "the type `${name}` is not PascalCase" }]
}
container = if is_only(Names.words_of(name), tables.containers) {
[{ line: item.first, check: "container_type", why: "the type `${name}` is only container words: name it for what it holds" }]
} else {
[]
}
{ found: case.concat(container), names: [name] }
} else {
{ found: [], names: [] }
}
}
## A constant's checks: each of an enum's constants, and a macro named in
## UPPER_SNAKE: its case, Zig's bound words, and a bound not last.
constant_checks : Item -> Checked
constant_checks = |item| {
macro = if item.kind == Macro and Names.is_upper_snake(item.name) {
[item.name]
} else {
[]
}
constants = item.enumerators.concat(macro)
cased =
item.enumerators
.keep_if(|constant| !(Names.is_upper_snake(constant)))
.map(|constant| { line: item.first, check: "constant_case", why: "the constant `${constant}` is not UPPER_SNAKE" })
bounds = constants.fold([], |found, constant| found.concat(bound_checks(item.first, constant)))
{ found: cased.concat(bounds), names: constants }
}
## A constant's bound checks: `MOST` or `LEAST` among its words, and its
## first `MAX` or `MIN` before its last word, unless a unit alone follows it.
bound_checks : U64, Str -> List(Found)
bound_checks = |line, constant| {
words = constant.split_on("_")
zig = if words.contains("MOST") or words.contains("LEAST") {
[{ line, check: "zig_bound", why: "`${constant}` is a bound in Zig's words: C's are `_MAX` and `_MIN`" }]
} else {
[]
}
count = words.len()
last_word = words.last() ?? ""
is_misplaced = |(at, word)|
(word == "MAX" or word == "MIN") and at + 1 < count and !(at + 2 == count and units.contains(last_word))
order =
match words.map_with_index(|word, at| (at, word)).find_first(is_misplaced) {
Ok((at, word)) => {
moved = words.drop_at(at).append(word)
why = "`${constant}` has `${word}` before its last word: a bound ends with it, as `${Str.join_with(moved, "_")}` would"
[{ line, check: "bound_order", why }]
}
Err(_) => []
}
zig.concat(order)
}
## The names of a macro not in UPPER_SNAKE and of named data, which no
## check reads but `abbreviation`.
other_names : Item -> List(Str)
other_names = |item|
if item.kind == Macro and !(Names.is_upper_snake(item.name)) {
[item.name]
} else if item.kind == Data and item.name != "" {
[item.name]
} else {
[]
}
## A function's checks: its case (`main` aside), vague words alone, `do`,
## and its vague parameters and locals.
function_checks : List(List(U8)), Item, Checks.Tables -> Checked
function_checks = |lines, item, tables| {
if item.kind != Function {
return { found: [], names: [] }
}
name = item.name
at = item.first
case = if name == "main" or Names.is_snake_case(name) {
[]
} else {
[{ line: at, check: "function_case", why: "the function `${name}` is not snake_case" }]
}
words = Names.words_of(name)
is_entry = words.len() == 1 and words.all(|word| entry_words.contains(word))
vague = if is_only(words, tables.vague) and !(is_entry) {
[{ line: at, check: "vague", why: "`${name}` is only vague words: what does it act on, and how?" }]
} else {
[]
}
do_word = if name.split_on("_").contains("do") {
[{ line: at, check: "do_word", why: "`${name}` has `do` in it, which says only that it acts: name the act" }]
} else {
[]
}
parameters =
Declared.parameters(head_of(lines, item))
.keep_if(|parameter| vague_locals.contains(parameter))
.map(|parameter| { line: at, check: "vague_local", why: "`${name}`'s parameter `${parameter}` says nothing of what it holds" })
{ found: case.concat(vague).concat(do_word).concat(parameters).concat(vague_body_locals(lines, item)), names: [name] }
}
## A function's head, masked, each run of `\s` one space; a head that shares
## its line with the body ends before the body's `{`.
head_of : List(List(U8)), Item -> List(U8)
head_of = |lines, item| {
head = spaces_made_one(Split.masked_text(lines, { first: item.sig_first, last: item.sig_last }))
if item.body_first == item.sig_last {
match Mask.byte_from(head, '{', 0) {
Ok(brace) => head.take_first(brace)
Err(_) => head
}
} else {
head
}
}
## The vague locals a function's body declares, a finding at each one's
## line: a body below its head, each line masked.
vague_body_locals : List(List(U8)), Item -> List(Found)
vague_body_locals = |lines, item| {
if item.body_first == 0 or item.body_first == item.sig_last {
return []
}
var $found = []
var $at = item.body_first
while $at <= item.body_last {
match Declared.local(Mask.masked(lines.get($at - 1) ?? [])) {
Ok(local) if vague_locals.contains(local) => {
why = "`${item.name}`'s local `${local}` says nothing of what it holds"
$found = $found.append({ line: $at, check: "vague_local", why })
}
_ => {}
}
$at = $at + 1
}
$found
}
## The text with each run of `\s` made one space.
spaces_made_one : List(U8) -> List(U8)
spaces_made_one = |text|
text.fold(
[],
|out, byte|
if !(Mask.is_space(byte)) {
out.append(byte)
} else if out.last() == Ok(' ') {
# A space is `\s`, so one that ends `out` is a run's already.
out
} else {
out.append(' ')
},
)
cookbook/c/hunt_names/SelfTest.roc, 71 lines
## hunt_names' self-test: the hunt run over cookbook/c/plants/hunt_names/,
## each plant named for the check it holds (`do_word.c`), each near miss in
## `quiet_<check>.c`, and the findings held to the plants' list exactly:
## every check fires on its own plant and on no other, and a quiet plant on
## none.
import pf.Shale
import Checks
SelfTest := [].{
## Every check, a FAIL line for each that fails and then a stop, else the
## PASS line. `hunt!` is the recipe's own, a folder's findings, sorted.
run! : (Str => { found : List(Checks.Finding), files : U64 }) => {}
run! = |hunt!| {
found = hunt!(plants).found
fired = found.map(|finding| (finding.path, finding.check))
silent =
Checks.check_names
.keep_if(|check| !(fired.contains((plant_of(check), check))))
.map(|check| "`${check}` does not fire on its plant ${plant_of(check)}")
elsewhere =
found
.keep_if(|finding| finding.path != plant_of(finding.check))
.map(|finding| "`${finding.check}` fires on ${finding.path}:${finding.line.to_str()}, not its plant")
got = Str.join_with(found.map(Checks.finding_line), "\n")
want = Str.join_with(wanted, "\n")
listed = if got == want {
[]
} else {
["the plants' findings are\n${got}\nthey should be\n${want}"]
}
wrong = silent.concat(elsewhere).concat(listed)
for why in wrong {
Shale.print!("FAIL ${why}")
}
if !(wrong.is_empty()) {
Shale.fail!("hunt_names self-test: ${wrong.len().to_str()} wrong")
}
checks = "${Checks.check_names.len().to_str()} checks, each firing on its own plant alone"
Shale.print!("PASS hunt_names self-test: ${checks}, ${wanted.len().to_str()} findings exactly, the quiet plants on none")
}
}
## Where the plants are.
plants : Str
plants = "cookbook/c/plants/hunt_names"
## The plant a check fires on.
plant_of : Str -> Str
plant_of = |check| "${plants}/${check}.c"
## The plants' findings, every one, in order.
wanted : List(Str)
wanted = {
p = "${plants}/"
[
"${p}abbreviation.c:4: abbreviation: `bi` for `builtin`, which other names spell out, in 1 name here: `bi_length`",
"${p}bound_order.c:4: bound_order: `BOUND_MAX_NAME` has `MAX` before its last word: a bound ends with it, as `BOUND_NAME_MAX` would",
"${p}constant_case.c:4: constant_case: the constant `constant_wrong` is not UPPER_SNAKE",
"${p}container_type.c:4: container_type: the type `Entry` is only container words: name it for what it holds",
"${p}container_type.c:8: container_type: the type `NodeInfo` is only container words: name it for what it holds",
"${p}do_word.c:4: do_word: `store_do_write` has `do` in it, which says only that it acts: name the act",
"${p}function_case.c:4: function_case: the function `readThing` is not snake_case",
"${p}type_case.c:4: type_case: the type `bad_type` is not PascalCase",
"${p}vague.c:4: vague: `handle_data` is only vague words: what does it act on, and how?",
"${p}vague_local.c:4: vague_local: `vague_local_sum`'s parameter `data` says nothing of what it holds",
"${p}vague_local.c:5: vague_local: `vague_local_sum`'s local `tmp` says nothing of what it holds",
"${p}zig_bound.c:4: zig_bound: `ZIG_BOUND_MOST` is a bound in Zig's words: C's are `_MAX` and `_MIN`",
"${p}zig_bound.c:8: zig_bound: `ZIG_BOUND_LEAST` is a bound in Zig's words: C's are `_MAX` and `_MIN`",
]
}
cookbook/c/hunt_names/Declared.roc, 195 lines
## The names a function declares, as hunt_names reads them from its masked
## lines: its parameters, from its head, and a body line's local. Each is a
## regular expression of cookbook/c/hunt_names.shale, the Shale original,
## done by hand, its alternatives tried in the order the expression's own
## matcher tries them, so the first match is the original's.
import items.Mask
Declared := [].{
## The names a function's head declares as its parameters: each part's last
## word, between the head's first `(` and its last `)`, `void` none. A
## part's name is `(\w+)\s*(\[[^\]]*\])?\s*$`: a word, then at most one
## `[...]`, at the part's end, so a function pointer's part has none.
parameters : List(U8) -> List(Str)
parameters = |head| {
open = head.find_first_index(|byte| byte == '(')
close = head.find_last_index(|byte| byte == ')')
match (open, close) {
(Ok(start), Ok(end)) if end > start => {
inside = head.sublist({ start: start + 1, len: end - start - 1 })
inside
.split_on(',')
.keep_oks(parameter_name)
.keep_if(|name| name != "void")
}
_ => []
}
}
## A body line's declared local, from its masked code: `Type name =`,
## `Type *name;`, `const Type name[`, as the original's
## `^\s*(?:const\s+|static\s+|struct\s+|unsigned\s+)*([A-Za-z_]\w*)(?:\s*\*+\s*|\s+)(?:const\s+)?\*?([a-z_]\w*)\s*(?:=|;|\[)`
## matches it. A first word that is no type (`return x;`) declares
## nothing.
local : List(U8) -> Try(Str, [NoLocal])
local = |code| {
starts = keyword_starts(code, [Mask.spaces_end(code, 0)])
# The `*` takes the most keywords first, then gives them back one by one.
var $left = starts.len()
while $left > 0 {
$left = $left - 1
match declared_from(code, starts.get($left) ?? 0) {
Ok({ type_word, name }) => {
if not_types.contains(type_word) {
return Err(NoLocal)
}
return Ok(name)
}
Err(_) => {}
}
}
Err(NoLocal)
}
}
## A declaration's first word that is no type: `return x;` declares nothing.
not_types : List(Str)
not_types = ["return", "else", "case", "goto", "do", "sizeof", "typedef", "break", "continue"]
## The words a declaration may start with before its type, each with the
## spaces after it.
type_keywords : List(Str)
type_keywords = ["const", "static", "struct", "unsigned"]
## The bytes from `start` to `end` as text.
text_of : List(U8), U64, U64 -> Str
text_of = |bytes, start, end| Mask.text(bytes.sublist({ start, len: end - start }))
## A part of the parameters' name: the first run of `\w` whose rest is
## `\s*(\[[^\]]*\])?\s*$`. Every start inside one run leaves the same rest,
## so the leftmost match is a whole run.
parameter_name : List(U8) -> Try(Str, [NoName])
parameter_name = |part| {
$at : U64
var $at = 0
while $at < part.len() {
end = Mask.word_end(part, $at)
if end == $at {
$at = $at + 1
} else if ends_part(part, end) {
return Ok(text_of(part, $at, end))
} else {
$at = end
}
}
Err(NoName)
}
## Whether what follows `at` is `\s*(\[[^\]]*\])?\s*$`: spaces, at most one
## `[...]`, spaces, and the part's end.
ends_part : List(U8), U64 -> Bool
ends_part = |part, at| {
after = Mask.spaces_end(part, at)
if after == part.len() {
Bool.True
} else if part.get(after) == Ok('[') {
match Mask.byte_from(part, ']', after + 1) {
Ok(close) => Mask.spaces_end(part, close + 1) == part.len()
Err(_) => Bool.False
}
} else {
Bool.False
}
}
## Where the type word may start: `starts`, the first after the leading
## spaces, then after each keyword of `type_keywords` and its spaces, as
## many as follow one another.
keyword_starts : List(U8), List(U64) -> List(U64)
keyword_starts = |code, starts| {
at = starts.last() ?? 0
match type_keywords.find_first(|keyword| Mask.holds_at(code, at, keyword) and Mask.is_space_at(code, at + keyword.count_utf8_bytes())) {
Ok(keyword) => keyword_starts(code, starts.append(Mask.spaces_end(code, at + keyword.count_utf8_bytes())))
Err(_) => starts
}
}
## The type word at `start` and the name after it: `([A-Za-z_]\w*)`, then
## `\s*\*+\s*` (tried first) or `\s+`, then the name.
declared_from : List(U8), U64 -> Try({ type_word : Str, name : Str }, [NoLocal])
declared_from = |code, start| {
if !(Mask.is_name_start(code.get(start) ?? 0)) {
return Err(NoLocal)
}
type_end = Mask.word_end(code, start)
before_stars = Mask.spaces_end(code, type_end)
with_stars =
if code.get(before_stars) == Ok('*') {
[Mask.spaces_end(code, stars_end(code, before_stars))]
} else {
[]
}
with_spaces =
if Mask.is_space_at(code, type_end) {
[Mask.spaces_end(code, type_end)]
} else {
[]
}
match with_stars.concat(with_spaces).keep_oks(|at| name_after(code, at)).first() {
Ok(name) => Ok({ type_word: text_of(code, start, type_end), name })
Err(_) => Err(NoLocal)
}
}
## The first place at `at` or after it that is no `*`.
stars_end : List(U8), U64 -> U64
stars_end = |code, at| {
var $end = at
while code.get($end) == Ok('*') {
$end = $end + 1
}
$end
}
## The name after a declaration's type and its stars:
## `(?:const\s+)?\*?([a-z_]\w*)\s*(?:=|;|\[)`, each optional part taken
## first, then left.
name_after : List(U8), U64 -> Try(Str, [NoLocal])
name_after = |code, at| {
keyword_end = at + 5
after_const =
if Mask.holds_at(code, at, "const") and Mask.is_space_at(code, keyword_end) {
[Mask.spaces_end(code, keyword_end)]
} else {
[]
}
starts = after_const.concat([at]).fold(
[],
|tried, place|
if code.get(place) == Ok('*') {
tried.concat([place + 1, place])
} else {
tried.append(place)
},
)
match starts.keep_oks(|start| name_at(code, start)).first() {
Ok(name) => Ok(name)
Err(_) => Err(NoLocal)
}
}
## The name at `start`, `[a-z_]\w*`, when `\s*` then `=`, `;` or `[`
## follows it.
name_at : List(U8), U64 -> Try(Str, [NoLocal])
name_at = |code, start| {
first = code.get(start) ?? 0
if !((first >= 'a' and first <= 'z') or first == '_') {
return Err(NoLocal)
}
end = Mask.word_end(code, start)
match code.get(Mask.spaces_end(code, end)) {
Ok(byte) if byte == '=' or byte == ';' or byte == '[' => Ok(text_of(code, start, end))
_ => Err(NoLocal)
}
}
cookbook/c/hunt_names/Names.roc, 72 lines
## The words and the cases of a C name, as hunt_names reads them: the
## regular expressions of cookbook/c/hunt_names.shale, the Shale original,
## done by hand over the name's bytes. A name of Shale's C is ASCII, and a
## byte past it is in no class here.
Names := [].{
## A C name's words, lower case: `NodeInfo`, `node_info` and `NODE_INFO`
## all `[node, info]`. A `_` goes between a lower-case letter or a digit
## and the capital after it (`([a-z0-9])([A-Z])`), then the name is cut at
## each `_`, an empty word left out.
words_of : Str -> List(Str)
words_of = |name| {
bytes = name.to_utf8()
var $spelled = []
$at : U64
var $at = 0
while $at < bytes.len() {
byte = bytes.get($at) ?? 0
$spelled = $spelled.append(lowered(byte))
next = bytes.get($at + 1) ?? 0
if (is_lower(byte) or is_digit(byte)) and is_upper(next) {
$spelled = $spelled.append('_')
}
$at = $at + 1
}
$spelled.split_on('_').keep_if(|word| !(word.is_empty())).map(|word| Str.from_utf8_lossy(word))
}
## Whether the name is `^[A-Z][A-Za-z0-9]*$`: a type's PascalCase.
is_pascal_case : Str -> Bool
is_pascal_case = |name|
is_shaped(name, is_upper, |byte| is_upper(byte) or is_lower(byte) or is_digit(byte))
## Whether the name is `^[a-z][a-z0-9_]*$`: a function's snake_case.
is_snake_case : Str -> Bool
is_snake_case = |name|
is_shaped(name, is_lower, |byte| is_lower(byte) or is_digit(byte) or byte == '_')
## Whether the name is `^[A-Z][A-Z0-9_]*$`: a constant's UPPER_SNAKE.
is_upper_snake : Str -> Bool
is_upper_snake = |name|
is_shaped(name, is_upper, |byte| is_upper(byte) or is_digit(byte) or byte == '_')
}
## Whether the name's first byte is `first`'s and every byte after it is
## `rest`'s, an empty name being neither.
is_shaped : Str, (U8 -> Bool), (U8 -> Bool) -> Bool
is_shaped = |name, first, rest| {
bytes = name.to_utf8()
match bytes.first() {
Ok(byte) => first(byte) and bytes.drop_first(1).all(rest)
Err(_) => Bool.False
}
}
is_upper : U8 -> Bool
is_upper = |byte| byte >= 'A' and byte <= 'Z'
is_lower : U8 -> Bool
is_lower = |byte| byte >= 'a' and byte <= 'z'
is_digit : U8 -> Bool
is_digit = |byte| byte >= '0' and byte <= '9'
## The byte lower case, as Shale's `lower` makes it: ASCII alone.
lowered : U8 -> U8
lowered = |byte|
if is_upper(byte) {
byte + 32
} else {
byte
}
Shale original
cookbook/c/hunt_names.shale, 319 lines, at 241fe1f7
The libraries it loads: cookbook/c/items.shale (503 lines).
-- Hunts Shale's C for names that break c/docs/style.md's "Names" or say
-- too little, from cookbook/c/items.shale's splitter. A finding is a
-- question for a reader, never a verdict. The first version is small, each
-- check narrow enough that its findings are worth reading:
--
-- type_case a type (a struct, union, typedef or tagged enum) not
-- `PascalCase`; an anonymous enum is constants, no type
-- function_case a function not `snake_case`
-- constant_case an enum's constant not `UPPER_SNAKE`
-- zig_bound a constant or macro with Zig's bound words, `MOST` or
-- `LEAST`: C's are `_MAX` and `_MIN`
-- bound_order a constant or macro whose `MAX` or `MIN` is not its last
-- word (`STORE_MAX_NAME`, not `STORE_NAME_MAX`), a unit
-- after it (`_MS`, `_BYTES`) left alone
-- vague a function named of nothing but cookbook/words/vague.txt's
-- words (`handle_data`); a lone `run` or `handle` is an
-- entry point's, and a piece's noun before a vague word
-- (`json_value`, `vm_run`) is no finding
-- do_word a function with the word `do` in its name, which says
-- only that it acts
-- vague_local a local or parameter named only `data`, `info`, `tmp`,
-- `temp`, `stuff`, `thing`, `things`, `misc`, `util`,
-- `helper`, `obj` or `handle`
-- container_type a type named of nothing but container words
-- (cookbook/words/containers.txt, and `data`, `info`):
-- `Entry`, `NodeInfo`; a type is named for what it holds
-- abbreviation a top-level name with a word of
-- cookbook/words/c_abbreviations.txt whose spelled-out
-- word another top-level name of the tree uses: one thing,
-- two spellings (`bi_split` beside `builtin_scan`); one
-- finding a file and abbreviation, naming its names
--
-- One line a finding, `path:line: check: why`, then the counts by check and
-- by folder.
--
-- shale cookbook:c/hunt_names.shale over c/
-- shale cookbook:c/hunt_names.shale dir=c/host
-- shale cookbook:c/hunt_names.shale self_test=1
--
-- `self_test=1` runs it over cookbook/c/plants/hunt_names/, each plant named
-- for the check it holds (`do_word.c`), each near miss in `quiet_<check>.c`,
-- and holds the findings to the plants' list exactly: every check fires on
-- its own plant and on no other, and a quiet plant on none.
--
-- budget: steps=400000000 arena_bytes=1000000000 kept_bytes=268435456
use("./items.shale")
const PLANTS = "cookbook/c/plants/hunt_names"
const CHECKS = {"type_case", "function_case", "constant_case", "zig_bound", "bound_order", "vague", "do_word", "vague_local", "container_type", "abbreviation"}
const VAGUE_LOCALS = {"data", "info", "tmp", "temp", "stuff", "thing", "things", "misc", "util", "helper", "obj", "handle"}
const ENTRY = {"run", "handle"}
-- A unit a bound's name may end with, after its `MAX` or `MIN`.
const UNITS = {"MS", "NS", "US", "S", "BYTES"}
-- A declaration's first word that is no type: `return x;` declares nothing.
const NOT_TYPES = {"return", "else", "case", "goto", "do", "sizeof", "typedef", "break", "continue"}
-- A word table of cookbook/words/, a word a line, `--` starting a note. A
-- word twice, or a line of two, is a mistake in the table: it fails.
function word_table(file)
local t = {}
for l in lines(read("cookbook:words/" .. file)) do
local w = trim(split(l, "--")[1])
if contains(w, " ") or has_key(t, w) then fail("hunt_names: cookbook/words/" .. file .. ": `" .. w .. "` is no single new word") end
if w ~= "" then t[w] = true end
end
return t
end
-- cookbook/words/c_abbreviations.txt: an abbreviation to its word.
function abbreviation_table()
local t = {}
for l in lines(read("cookbook:words/c_abbreviations.txt")) do
local ws = words(trim(split(l, "--")[1]))
if #ws == 2 then
if has_key(t, ws[1]) then fail("hunt_names: cookbook/words/c_abbreviations.txt: `" .. ws[1] .. "` twice") end
t[ws[1]] = ws[2]
elseif #ws ~= 0 then
fail("hunt_names: cookbook/words/c_abbreviations.txt: `" .. l .. "` is no pair of an abbreviation and its word")
end
end
return t
end
-- The C files under `dir`, sorted, c/out (the build's output) left out.
function c_files_under(dir)
local files = {}
for e in walk_all(dir, {kind = "file", skip = "out"}) do
if ends_with(e.path, ".c") or ends_with(e.path, ".h") then push(files, e.path) end
end
sort(files)
return files
end
-- A C name's words, lower case: `NodeInfo`, `node_info` and `NODE_INFO` all
-- `{node, info}`.
function words_of(name)
local s = re_replace(name, "([a-z0-9])([A-Z])", "\\1_\\2")
local got = {}
for w in split(lower(s), "_") do
if w ~= "" then push(got, w) end
end
return got
end
-- Every word of every table in `t`.
function all_in(ws, t)
if #ws == 0 then return false end
for w in ws do
if not has_key(t, w) then return false end
end
return true
end
-- The names a function's head declares as its parameters: each part's last
-- word, between the head's first `(` and its last `)`.
function param_names(head)
local open = find(head, "(")
local close = nil
local k = #head
while k > 0 and close == nil do
if sub(head, k, k) == ")" then close = k end
k = k - 1
end
if open == nil or close == nil or close <= open then return {} end
local names = {}
for part in split(sub(head, open + 1, close - 1), ",") do
local m = re_find(part, [=[(\w+)\s*(\[[^\]]*\])?\s*$]=])
if m ~= nil and m.groups[1] ~= "void" then push(names, m.groups[1]) end
end
return names
end
-- A body line's declared local, or nil: `Type name =`, `Type *name;`,
-- `const Type name[`.
const DECL = [=[^\s*(?:const\s+|static\s+|struct\s+|unsigned\s+)*([A-Za-z_]\w*)(?:\s*\*+\s*|\s+)(?:const\s+)?\*?([a-z_]\w*)\s*(?:=|;|\[)]=]
function local_of(code)
local m = re_find(code, DECL)
if m == nil or has_item(NOT_TYPES, m.groups[1]) then return nil end
return m.groups[2]
end
-- What the hunt reads of one file: its findings by every check but
-- `abbreviation`, and its top-level names `{name, line, words}` for that
-- check, which needs the whole tree's.
function hunt_file(p, tables)
local all = lines(read(p))
local found = {}
local named = {}
for it in c_items(p) do
local k = it.kind
local anonymous = k == "enum" and #it.enumerators > 0 and it.enumerators[1] == it.name and not starts_with(all[it.first], "typedef")
if (k == "struct" or k == "union" or k == "typedef" or k == "enum") and not anonymous then
if not re_match(it.name, "^[A-Z][A-Za-z0-9]*$") then push(found, {line = it.first, check = "type_case", why = "the type `" .. it.name .. "` is not PascalCase"}) end
if all_in(words_of(it.name), tables.containers) then push(found, {line = it.first, check = "container_type", why = "the type `" .. it.name .. "` is only container words: name it for what it holds"}) end
push(named, {name = it.name, line = it.first})
end
local constants = {}
for en in it.enumerators do push(constants, en) end
if k == "macro" and re_match(it.name, "^[A-Z][A-Z0-9_]*$") then push(constants, it.name) end
for en in it.enumerators do
if not re_match(en, "^[A-Z][A-Z0-9_]*$") then push(found, {line = it.first, check = "constant_case", why = "the constant `" .. en .. "` is not UPPER_SNAKE"}) end
end
for c in constants do
local ws = split(c, "_")
if has_item(ws, "MOST") or has_item(ws, "LEAST") then push(found, {line = it.first, check = "zig_bound", why = "`" .. c .. "` is a bound in Zig's words: C's are `_MAX` and `_MIN`"}) end
local j = 1
while j < #ws do
if (ws[j] == "MAX" or ws[j] == "MIN") and not (j == #ws - 1 and has_item(UNITS, ws[#ws])) then
local moved = {}
local x = 1
while x <= #ws do
if x ~= j then push(moved, ws[x]) end
x = x + 1
end
push(moved, ws[j])
push(found, {line = it.first, check = "bound_order", why = "`" .. c .. "` has `" .. ws[j] .. "` before its last word: a bound ends with it, as `" .. join(moved, "_") .. "` would"})
j = #ws
end
j = j + 1
end
push(named, {name = c, line = it.first})
end
if k == "macro" and not re_match(it.name, "^[A-Z][A-Z0-9_]*$") then push(named, {name = it.name, line = it.first}) end
if k == "data" and it.name ~= "" then push(named, {name = it.name, line = it.first}) end
if k == "function" then
local n = it.name
push(named, {name = n, line = it.first})
if n ~= "main" and not re_match(n, "^[a-z][a-z0-9_]*$") then push(found, {line = it.first, check = "function_case", why = "the function `" .. n .. "` is not snake_case"}) end
local ws = words_of(n)
if all_in(ws, tables.vague) and not (#ws == 1 and has_item(ENTRY, ws[1])) then push(found, {line = it.first, check = "vague", why = "`" .. n .. "` is only vague words: what does it act on, and how?"}) end
if has_item(split(n, "_"), "do") then push(found, {line = it.first, check = "do_word", why = "`" .. n .. "` has `do` in it, which says only that it acts: name the act"}) end
local head = re_replace(c_masked_text(all, it.sig_first, it.sig_last), [=[\s+]=], " ")
if it.body_first == it.sig_last then head = sub(head, 1, find(head, "{") - 1) end
for q in param_names(head) do
if has_item(VAGUE_LOCALS, q) then push(found, {line = it.first, check = "vague_local", why = "`" .. n .. "`'s parameter `" .. q .. "` says nothing of what it holds"}) end
end
if it.body_first ~= 0 and it.body_first ~= it.sig_last then
local b = it.body_first
while b <= it.body_last do
local l = local_of(c_mask(all[b]))
if l ~= nil and has_item(VAGUE_LOCALS, l) then push(found, {line = b, check = "vague_local", why = "`" .. n .. "`'s local `" .. l .. "` says nothing of what it holds"}) end
b = b + 1
end
end
end
end
return {found = found, named = named}
end
-- The findings over `dir`, sorted by place: `{path, line, check, why}`.
function hunt(dir)
local tables = {vague = word_table("vague.txt"), containers = word_table("containers.txt"), abbreviations = abbreviation_table()}
tables.containers["data"] = true
tables.containers["info"] = true
local found = {}
local named = {}
local files = c_files_under(dir)
for p in files do
local r = hunt_file(p, tables)
for f in r.found do push(found, {path = p, line = f.line, check = f.check, why = f.why}) end
for x in r.named do push(named, {path = p, line = x.line, name = x.name, words = words_of(x.name)}) end
yield()
end
-- The words the tree's top-level names spell, for `abbreviation`.
local spelled = {}
for x in named do
for w in x.words do spelled[w] = true end
end
-- One finding a file and abbreviation, at its first name, naming them.
local short = {}
local order = {}
for x in named do
for w in unique(x.words) do
if has_key(tables.abbreviations, w) and has_key(spelled, tables.abbreviations[w]) then
local key = x.path .. "|" .. w
if not has_key(short, key) then
short[key] = {path = x.path, line = x.line, word = w, names = {}}
push(order, key)
end
push(short[key].names, x.name)
end
end
end
for key in order do
local s = short[key]
local names = unique(s.names)
local shown = "`" .. join(take(names, 4), "`, `") .. "`"
if #names > 4 then shown = shown .. " and " .. (#names - 4) .. " more" end
local count = #names .. " names"
if #names == 1 then count = "1 name" end
push(found, {path = s.path, line = s.line, check = "abbreviation", why = "`" .. s.word .. "` for `" .. tables.abbreviations[s.word] .. "`, which other names spell out, in " .. count .. " here: " .. shown})
end
sort(found, {"path", "line", "check", "why"})
return {found = found, files = #files}
end
-- The findings' lines.
function finding_lines(found)
local out = {}
for f in found do push(out, f.path .. ":" .. f.line .. ": " .. f.check .. ": " .. f.why) end
return out
end
function self_test()
local r = hunt(PLANTS)
local wrong = {}
-- Every check fires on its own plant and no other; a quiet plant on none.
local fired = {}
for f in r.found do fired[f.path .. "|" .. f.check] = true end
for c in CHECKS do
local mine = PLANTS .. "/" .. c .. ".c"
if not has_key(fired, mine .. "|" .. c) then push(wrong, "`" .. c .. "` does not fire on its plant " .. mine) end
end
for f in r.found do
if f.path ~= PLANTS .. "/" .. f.check .. ".c" then push(wrong, "`" .. f.check .. "` fires on " .. f.path .. ":" .. f.line .. ", not its plant") end
end
local P = PLANTS .. "/"
local want = {
P .. "abbreviation.c:4: abbreviation: `bi` for `builtin`, which other names spell out, in 1 name here: `bi_length`",
P .. "bound_order.c:4: bound_order: `BOUND_MAX_NAME` has `MAX` before its last word: a bound ends with it, as `BOUND_NAME_MAX` would",
P .. "constant_case.c:4: constant_case: the constant `constant_wrong` is not UPPER_SNAKE",
P .. "container_type.c:4: container_type: the type `Entry` is only container words: name it for what it holds",
P .. "container_type.c:8: container_type: the type `NodeInfo` is only container words: name it for what it holds",
P .. "do_word.c:4: do_word: `store_do_write` has `do` in it, which says only that it acts: name the act",
P .. "function_case.c:4: function_case: the function `readThing` is not snake_case",
P .. "type_case.c:4: type_case: the type `bad_type` is not PascalCase",
P .. "vague.c:4: vague: `handle_data` is only vague words: what does it act on, and how?",
P .. "vague_local.c:4: vague_local: `vague_local_sum`'s parameter `data` says nothing of what it holds",
P .. "vague_local.c:5: vague_local: `vague_local_sum`'s local `tmp` says nothing of what it holds",
P .. "zig_bound.c:4: zig_bound: `ZIG_BOUND_MOST` is a bound in Zig's words: C's are `_MAX` and `_MIN`",
P .. "zig_bound.c:8: zig_bound: `ZIG_BOUND_LEAST` is a bound in Zig's words: C's are `_MAX` and `_MIN`",
}
local got = join(finding_lines(r.found), "\n")
if got ~= join(want, "\n") then push(wrong, "the plants' findings are\n" .. got .. "\nthey should be\n" .. join(want, "\n")) end
for w in wrong do print("FAIL " .. w) end
if #wrong > 0 then fail("hunt_names self-test: " .. #wrong .. " wrong") end
print("PASS hunt_names self-test: " .. #CHECKS .. " checks, each firing on its own plant alone, " .. #want .. " findings exactly, the quiet plants on none")
return nil
end
if arg("self_test", 0) == 1 then
self_test()
else
local dir = arg("dir", "c")
local r = hunt(dir)
for l in finding_lines(r.found) do print(l) end
local by = {}
local folders = {}
for f in r.found do
incr(by, f.check)
incr(folders, dirname(f.path) .. " " .. f.check)
end
local parts = {}
for c in CHECKS do push(parts, c .. " " .. get(by, c, 0)) end
print("hunt_names: " .. r.files .. " files under " .. dir .. "; " .. #r.found .. " findings: " .. join(parts, ", "))
for k in sort(keys(folders)) do print(" " .. k .. ": " .. folders[k]) end
end