find_names_that_disagree_with_their_types

Roc

It also imports Declarations, Finding, Text, Tree from the shared Roc library.

cookbook/roc/find_names_that_disagree_with_their_types/find_names_that_disagree_with_their_types.roc, 121 lines

## find_names_that_disagree_with_their_types, in Roc on Shale's platform (roc_platform/README.md):
## names that disagree with their types. A reader who sees `bull_dist` takes
## it for a `Distance`, one who sees `forward : F64` beside `forward :
## Distance` can't tell which is meant, and one who sees `no_frames : Steps`
## can't tell the case from a count, so each costs a wrong guess. Its
## launcher, cookbook/roc/find_names_that_disagree_with_their_types.shale, is how it is run, and its
## header says the rules, `name_type`, `bare_beside_unit` and `no_value`.
## check_goldens.shale, beside this, holds its output on the plants to its
## goldens, line for line.
##
##   cd <repo> && shale cookbook:roc/find_names_that_disagree_with_their_types.shale table=name_types.txt
##   shale cookbook:roc/find_names_that_disagree_with_their_types.shale self_test=1
##
## The arguments: `glob` (`**/*.roc`), `table` (the project's table of words
## and types) and `self_test` (`self_test=1` runs the plants, each through the
## launcher).
##
## This root reads the prepositions and the table, 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: a module a check (NameType,
## BareBesideUnit, NoValue), Words and SelfTest; what they read besides
## (Declarations, Tree, Text) and Finding are the cookbook's Roc library,
## cookbook/roc/lib/.
## budget: steps=800000000 arena_bytes=2000000000 output_bytes=4000000 programs=100
app [main!] { lib: "../lib/main.roc", pf: platform "../../../roc_platform/platform/main.roc" }

import pf.Shale
import BareBesideUnit
import lib.Declarations
import lib.Finding
import NameType
import NoValue
import SelfTest
import Words

main! : {} => {}
main! = |{}| {
	if Shale.arg!("self_test", "") == "1" {
		SelfTest.run!(checks)
	} else {
		run_check!({})
	}
}

## The check over the glob's files: the verdict printed, then a stop when a
## file didn't parse, or when there are findings, the summary the last line
## a caller reads.
run_check! : {} => {}
run_check! = |{}| {
	words = Words.read!(Shale.arg!("table", ""))
	paths = Shale.glob!(Shale.arg!("glob", "**/*.roc"))
	var $declared = Declarations.none_yet
	var $refused = []
	for file in Shale.roc_tree!(paths) {
		if file.err == "" {
			read = {
				path: file.path,
				nodes: file.nodes,
				source_lines: read_text!(file.path).split_on("\n"),
			}
			$declared = Declarations.concat($declared, Declarations.from_file(read))
		} else if file.err.starts_with(file.path) {
			$refused = $refused.append(file.err)
		} else {
			$refused = $refused.append("${file.path}: ${file.err}")
		}
	}
	findings = NameType.findings($declared, words)
		.concat(BareBesideUnit.findings($declared, words))
		.concat(NoValue.findings($declared))
	found = findings.sort_with(Finding.order).map(Finding.line_of)
	summary = summary_of(findings, paths.len())
	print_findings!(summary, found)
	if !($refused.is_empty()) {
		for refusal in $refused {
			Shale.print!("refused: ${refusal}")
		}
		refusals = "roc-ast refused ${$refused.len().to_str()} files (named above)"
		why = "which have no tree to judge; every other file was judged"
		Shale.fail!("find_names_that_disagree_with_their_types: ${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_names_that_disagree_with_their_types: ${path} went missing during the check")
			""
		}
	}

## The checks, in the order the summary counts them.
checks : List(Str)
checks = ["name_type", "bare_beside_unit", "no_value"]

## The counts, `find_names_that_disagree_with_their_types (Roc): N files; name_type N, ...`.
summary_of : List(Finding), U64 -> Str
summary_of = |findings, file_count| {
	"find_names_that_disagree_with_their_types (Roc): ${file_count.to_str()} files; ${Finding.counts_of(findings, checks)}"
}

## The summary, each finding, then the summary again (cookbook/findings.shale):
## the first copy survives a cut output, and a gate reads the last line.
print_findings! : Str, List(Str) => {}
print_findings! = |summary, finding_lines| {
	Shale.print!(summary)
	if !(finding_lines.is_empty()) {
		for line in finding_lines {
			Shale.print!(line)
		}
		Shale.print!(summary)
	}
}

cookbook/roc/find_names_that_disagree_with_their_types/BareBesideUnit.roc, 78 lines

## The `bare_beside_unit` check: a field that is a bare number in one record
## and a unit in another, a unit being a nominal type built on a number and
## declared in the files read. It means a retyping stopped halfway. Each bare
## field is a finding. A field named by a preposition (`from`, `to`, `at`) or
## by a word the table gives `any` (`id`, where a host's number and a user's
## id are two things) is not judged, because that word fits any two things.
import lib.Declarations
import lib.Finding
import lib.Tree
import Words

BareBesideUnit := [].{

	## Each bare field beside a unit field of its name, in the order declared.
	findings : Declarations, Words -> List(Finding)
	findings = |declared, words| {
		units = unit_names(declared.types)
		var $unit_fields = Dict.empty()
		for field in declared.fields {
			if units.contains(Tree.last_part(field.written_type)) {
				$unit_fields = $unit_fields.insert(field.name, field)
			}
		}
		is_judged = |field|
			bare_numbers.contains(field.written_type)
				and !(words.prepositions.contains(field.name))
				and !(Words.promises_nothing(words, field.name))
		var $found = []
		for field in declared.fields {
			match $unit_fields.get(field.name) {
				Ok(typed) =>
					if is_judged(field) {
						$found = $found.append(bare_field(field, typed))
					}
				Err(_) => {}
			}
		}
		$found
	}
}

## The numbers Roc builds in, which a unit is built on.
bare_numbers : Set(Str)
bare_numbers = Set.from_list([
	"U8",
	"U16",
	"U32",
	"U64",
	"U128",
	"I8",
	"I16",
	"I32",
	"I64",
	"I128",
	"F32",
	"F64",
	"Dec",
])

## The nominal types built on a number, by name.
unit_names : List(Declarations.TypeDeclared) -> Set(Str)
unit_names = |types| {
	is_unit = |declared| declared.is_nominal and bare_numbers.contains(declared.underlying)
	Set.from_list(types.keep_if(is_unit).map(|declared| declared.name))
}

## The finding of a bare field, naming the unit field of its name.
bare_field : Declarations.FieldDeclared, Declarations.FieldDeclared -> Finding
bare_field = |field, typed| {
	bare = "the field `${field.name}` is a bare `${field.written_type}` here"
	unit_place = "${typed.path}:${typed.line.to_str()}"
	{
		path: field.path,
		line: field.line,
		check: "bare_beside_unit",
		what: "${bare} and a `${typed.written_type}` at ${unit_place}",
	}
}

cookbook/roc/find_names_that_disagree_with_their_types/NameType.roc, 113 lines

## The `name_type` check: a name whose last word is in the project's table has
## a type the table doesn't allow. A function is judged by what it returns,
## and a type by its last part, so `Geom.Distance` is `Distance`. In a name
## that starts with a preposition or a question, the last word isn't the
## thing named (a function from a fraction, a state after two steps, a
## question whether it is a fraction), so it is not judged. `none` means no
## name may end in the word, whatever its type or start, and `any` means the
## word holds no promise at all.
import lib.Declarations
import lib.Finding
import lib.Text
import lib.Tree
import Words

NameType := [].{

	## Each value and field whose name disagrees with the table: a field
	## judged by its own type, a value by what it gives.
	findings : Declarations, Words -> List(Finding)
	findings = |declared, words| {
		named_fields = declared.fields.map(
			|field| {
				path: field.path,
				line: field.line,
				name: field.name,
				type_judged: field.written_type,
			},
		)
		named_values = declared.values.map(
			|value| {
				path: value.path,
				line: value.line,
				name: value.name,
				type_judged: value.result_type,
			},
		)
		named_fields.concat(named_values).map(|named| name_findings(named, words)).join()
	}

}

## A name judged: a value's or a field's, where it is, and the type that
## stands for it (what a function returns, a field's own type).
Named : {
	path : Str,
	line : U64,
	name : Str,
	type_judged : Str,
}

## The finding of `named`, when its type disagrees with the table.
name_findings : Named, Words -> List(Finding)
name_findings = |named, words| {
	name_words = Text.name_words(named.name.drop_suffix("!"))
	type_judged = named.type_judged
	if type_judged == "" or type_judged == "_" {
		return []
	}
	match (name_words.first(), name_words.last()) {
		(Ok(first_word), Ok(last_word)) => {
			is_question = question_words.contains(first_word)
			names_something_else = words.prepositions.contains(first_word) or is_question
			said = { named, last_word }
			match words.promises.get(last_word) {
				Ok(NoNameMay) => [no_name_may(said)]
				Ok(OneOf(allowed)) =>
					if names_something_else or allowed.contains(Tree.last_part(type_judged)) {
						[]
					} else {
						[not_allowed(said, allowed)]
					}
				Ok(AnyType) => []
				Err(_) => []
			}
		}
		_ => []
	}
}

## The first words that ask a question, so the name's last word is not the
## thing named.
question_words : Set(Str)
question_words = Set.from_list(["is", "has", "can", "should"])

## A name judged, and its last word.
Said : { named : Named, last_word : Str }

## The finding of a name ending in a word no name may end in.
no_name_may : Said -> Finding
no_name_may = |said| {
	named = said.named
	ending = "`${named.name}` ends in `${said.last_word}`"
	{
		path: named.path,
		line: named.line,
		check: "name_type",
		what: "${ending}, which no name here may: its type is `${named.type_judged}`",
	}
}

## The finding of a name whose type is none of those the table allows.
not_allowed : Said, List(Str) -> Finding
not_allowed = |said, allowed| {
	named = said.named
	allowed_said = Str.join_with(allowed, "` or `")
	ending = "a name ending `${said.last_word}` is `${allowed_said}` here"
	{
		path: named.path,
		line: named.line,
		check: "name_type",
		what: "`${named.name}` is `${named.type_judged}`, and ${ending}",
	}
}

cookbook/roc/find_names_that_disagree_with_their_types/NoValue.roc, 70 lines

## The `no_value` check: a constant whose first word is `no`, `none` or
## `unset` and whose type is not a `Bool` or a tag union. An ordinary value
## kept to mean "none" should be a tag. A `List` has its own empty case, and a
## type's own member of that type (`Attention.none : Attention`) is its
## scale's bottom, so neither is judged, and neither is a constant with no
## annotation. An alias of a function type is a function's type (`no_draw :
## Draw`, `Draw : U64 -> List(U64)`), so it is not judged either. A string
## with something in it is words about the case, not a stand-in for it (a
## name of words for no match, say), so only `""` is judged.
import lib.Declarations
import lib.Finding
import lib.Tree

NoValue := [].{

	## Each annotated constant that means none and holds an ordinary value.
	findings : Declarations -> List(Finding)
	findings = |declared| {
		types = declared.types
		names = |kept| Set.from_list(kept.map(|type_declared| type_declared.name))
		tag_unions = names(types.keep_if(|type_declared| type_declared.is_tag_union))
		# An alias of a function type (`Draw : U64 -> List(U64)`) makes a value
		# of it a function, which `is_function` sees only when written out.
		is_function_alias = |type_declared|
			type_declared.is_function_type and !(type_declared.is_nominal)
		function_aliases = names(types.keep_if(is_function_alias))
		kinds = { tag_unions, function_aliases }
		declared.values
			.keep_if(|value| value.annotated and !(value.is_function))
			.keep_if(|value| means_none(value.name) and is_plain(value, kinds))
			.map(no_value)
	}
}

## The first words that mean none.
words_for_none : Set(Str)
words_for_none = Set.from_list(["no", "none", "unset"])

## Whether the name's first word, up to its first `_`, means none.
means_none : Str -> Bool
means_none = |name| {
	first_word = match name.split_first("_") {
		Ok(parts) => parts.before
		Err(_) => name
	}
	words_for_none.contains(first_word)
}

## The names of the tag unions and of the aliases of function types.
TypeKinds : { tag_unions : Set(Str), function_aliases : Set(Str) }

## Whether the value's type is an ordinary one, which a tag should stand for.
is_plain : Declarations.ValueDeclared, TypeKinds -> Bool
is_plain = |value, kinds| {
	written = value.written_type
	named = Tree.last_part(written)
	is_own_bottom = value.owner == named
	is_kept_kind = kinds.tag_unions.contains(named) or kinds.function_aliases.contains(named)
	is_shaped = written == "Bool" or written.starts_with("[") or written.starts_with("List(")
	!(is_shaped or value.has_text or is_own_bottom or is_kept_kind)
}

## The finding of a value that means none.
no_value : Declarations.ValueDeclared -> Finding
no_value = |value| {
	path: value.path,
	line: value.line,
	check: "no_value",
	what: "`${value.name}` means none and is a `${value.written_type}`: keep the case as a tag",
}

cookbook/roc/find_names_that_disagree_with_their_types/SelfTest.roc, 226 lines

## The recipe's self-test: each plant under
## cookbook/roc/plants/find_names_that_disagree_with_their_types/ run through the launcher, held to its
## findings, its exit and what it says. It copies
## cookbook/roc/find_names_that_differ_across_lookalike_modules/SelfTest.roc but for its rows.
import pf.Shale

SelfTest := [].{

	## Each row run as a child of its own, through `launcher`; a check of
	## `checks` no row fires fails too, since it could be blind.
	run! : List(Str) => {}
	run! = |checks| {
		var $wrong = 0.U64
		var $fired = Set.empty()
		for row in rows {
			command = ["shale", launcher, "glob=${row.plant}"].concat(row.arguments)
			result = Shale.run!({
				argv: command,
				keep: Whole(4000000),
				timeout_ms: 120000,
				want: "",
			})
			faults = find_faults!(row, result, checks)
			for (check, _) in row.counts {
				$fired = $fired.insert(check)
			}
			if faults.is_empty() {
				Shale.print!("ok   ${row.plant}")
			} else {
				Shale.print!("FAIL ${row.plant}: ${Str.join_with(faults, "; ")}")
				$wrong = $wrong + 1
				Shale.print!(result.out)
			}
		}
		for check in checks {
			if !($fired.contains(check)) {
				Shale.print!("FAIL `${check}` has no plant")
				$wrong = $wrong + 1
			}
		}
		if $wrong > 0 {
			Shale.fail!("find_names_that_disagree_with_their_types self_test: ${$wrong.to_str()} wrong")
		}
		row_count = rows.len().to_str()
		proof = "each plant gives its findings and a nonzero exit, each clean case none and exit 0"
		Shale.print!("find_names_that_disagree_with_their_types self_test: PASS (${row_count} rows: ${proof})")
	}
}

## The launcher, which the self-test runs each plant through.
launcher : Str
launcher = "cookbook:roc/find_names_that_disagree_with_their_types.shale"

plants : Str
plants = "cookbook:roc/plants/find_names_that_disagree_with_their_types/"

## A plant's run: its files (a glob below `plants`) and its other arguments,
## the findings each check must print, the literals its output must hold,
## and whether it must stop without a finding.
Row : {
	plant : Str,
	arguments : List(Str),
	counts : List((Str, U64)),
	says : List(Str),
	stops : Bool,
}

## A plant, given as a glob below `plants`, with no finding to give.
quiet : Str, List(Str) -> Row
quiet = |plant, arguments| {
	plant: "${plants}${plant}",
	arguments,
	counts: [],
	says: [],
	stops: Bool.False,
}

## What a plant that fires is run with and must give.
Firing : {
	plant : Str,
	arguments : List(Str),
	counts : List((Str, U64)),
	says : List(Str),
}

## What a plant that stops is run with and must say.
Stopping : {
	plant : Str,
	arguments : List(Str),
	says : List(Str),
}

## A plant with findings, and what they say.
fires : Firing -> Row
fires = |wanted| {
	plant: "${plants}${wanted.plant}",
	arguments: wanted.arguments,
	counts: wanted.counts,
	says: wanted.says,
	stops: Bool.False,
}

## A plant that must stop before any finding, saying what it says.
stops : Stopping -> Row
stops = |wanted| {
	plant: "${plants}${wanted.plant}",
	arguments: wanted.arguments,
	counts: [],
	says: wanted.says,
	stops: Bool.True,
}

## The argument that names one of the plants' tables.
table : Str -> Str
table = |file| "table=${plants}${file}"

rows : List(Row)
rows = [
	fires({
		plant: "name_type.roc",
		arguments: [table("table.txt")],
		counts: [("name_type", 6)],
		says: [
			"name_type.roc:3: name_type: `bull_dist` is `Geom.Along`, "
				.concat("and a name ending `dist` is `Distance` here"),
			"`in_2_frames` ends in `frames`",
		],
	}),
	quiet("name_type.roc", []),
	quiet("quiet_name_type.roc", [table("table.txt")]),
	fires({
		plant: "bare_beside_unit/*.roc",
		arguments: [],
		counts: [("bare_beside_unit", 2)],
		says: [
			"Rider.roc:4: bare_beside_unit: the field `forward` is a bare `F64` here "
				.concat("and a `Distance` at"),
		],
	}),
	quiet("quiet_bare/*.roc", []),
	fires({
		plant: "bare_any/*.roc",
		arguments: [],
		counts: [("bare_beside_unit", 1)],
		says: ["the field `id` is a bare `U64` here"],
	}),
	quiet("bare_any/*.roc", [table("table_any.txt")]),
	quiet("name_type.roc", [table("table_any.txt")]),
	fires({
		plant: "no_value.roc",
		arguments: [],
		counts: [("no_value", 4)],
		says: ["no_value.roc:9: no_value: `no_frames` means none and is a `Steps`"],
	}),
	quiet("quiet_no_value.roc", []),
	stops({ plant: "broken/*.roc", arguments: [], says: ["refused: "] }),
	stops({
		plant: "quiet_name_type.roc",
		arguments: [table("no_such.txt")],
		says: ["no table"],
	}),
	stops({
		plant: "quiet_name_type.roc",
		arguments: [table("table_malformed.txt")],
		says: ["table_malformed.txt:2: expected"],
	}),
	stops({
		plant: "quiet_name_type.roc",
		arguments: [table("table_twice.txt")],
		says: ["`dist` is listed twice"],
	}),
]

## The last line of `out` that isn't one of Shale's `──` lines.
last_said : Str -> Str
last_said = |out|
	out.trim().split_on("\n").fold(
		"",
		|last, line|
			if line.starts_with("──") or line.trim() == "" {
				last
			} else {
				line
			},
	)

## The findings `row` wants of `check`.
wanted_count : Row, Str -> U64
wanted_count = |row, check| {
	var $wanted = 0
	for (counted, count) in row.counts {
		if counted == check {
			$wanted = count
		}
	}
	$wanted
}

## What is wrong with one row's run.
find_faults! : Row, { code : I64, out : Str }, List(Str) => List(Str)
find_faults! = |row, result, checks| {
	must_fail = row.stops or !(row.counts.is_empty())
	var $faults = []
	if must_fail and result.code == 0 {
		$faults = $faults.append("it exited 0")
	}
	if !(must_fail) and result.code != 0 {
		$faults = $faults.append("it exited ${result.code.to_str()}")
	}
	for check in checks {
		found = Shale.re_lines!(result.out, "^[^ ]+:[0-9]+: ${check}: ").len()
		wanted = wanted_count(row, check)
		if found != wanted {
			$faults = $faults.append("${check} printed ${found.to_str()}, not ${wanted.to_str()}")
		}
	}
	if !(row.stops) and !(last_said(result.out).contains(" files; ")) {
		$faults = $faults.append("its last line is no summary: ${last_said(result.out)}")
	}
	for literal in row.says {
		if !(result.out.contains(literal)) {
			$faults = $faults.append("its output lacks `${literal}`")
		}
	}
	$faults
}

cookbook/roc/find_names_that_disagree_with_their_types/Words.roc, 140 lines

## The words the checks read beside the code: the prepositions
## (cookbook/words/prepositions.txt) and a project's table of words and the
## types its names must hold, as the `table=` file gives it. Each line of the
## table is `word: Type, Type`, `word: none` or `word: any`, such as `dist:
## Distance`. A blank line or one starting with `#` is skipped, and a
## malformed line or a word listed twice stops the run. The table belongs to
## the project, because what `dist` must be depends on the project's types.
import pf.Shale
import lib.Text

Words := {
	## What the table promises of each word in it.
	promises : Dict(Str, Words.Promise),

	## The prepositions, which a name or a field may start with or be.
	prepositions : Set(Str),
}.{

	## What the table says of a word: no name may end in it, it holds no
	## promise at all, or a name ending in it holds one of the types.
	Promise : [NoNameMay, AnyType, OneOf(List(Str))]

	## The prepositions, then the table in the file at `table_path` (none when
	## it is `""`).
	read! : Str => Words
	read! = |table_path| {
		prepositions = read_word_set!("cookbook:words/prepositions.txt")
		{ promises: read_table!(table_path), prepositions }
	}

	## Whether the table gives `word` as `any`.
	promises_nothing : Words, Str -> Bool
	promises_nothing = |words, word|
		match words.promises.get(word) {
			Ok(AnyType) => Bool.True
			_ => Bool.False
		}
}

## The table in the file at `path`, none when `path` is `""`.
read_table! : Str => Dict(Str, Words.Promise)
read_table! = |path| {
	if path == "" {
		return Dict.empty()
	}
	if !(Shale.exists!(path)) {
		Shale.fail!("find_names_that_disagree_with_their_types: no table ${path}")
	}
	text = match Shale.read!(path) {
		Found(found) => found
		Missing => {
			Shale.fail!("find_names_that_disagree_with_their_types: no table ${path}")
			""
		}
	}
	var $promises = Dict.empty()
	var $number = 0
	for raw in Text.lines(text) {
		$number = $number + 1
		line = Text.trim(raw)
		if line != "" and !(line.starts_with("#")) {
			table_line = { path, number: $number, line }
			entry = read_entry!(table_line)
			if $promises.contains(entry.word) {
				fail_at!(table_line, "`${entry.word}` is listed twice")
			}
			$promises = $promises.insert(entry.word, entry.promise)
		}
	}
	$promises
}

## The line pattern: a word, then `none`, `any` or a list of types.
line_pattern : Str
line_pattern = "^([a-z0-9]+): *(none|any|[A-Z][A-Za-z0-9]*(?:, *[A-Z][A-Za-z0-9]*)*)$"

## One line of the table, with the file and its number to say where it is.
TableLine : {
	path : Str,
	number : U64,
	line : Str,
}

## Stops the run, saying where in the table and what is wrong there.
fail_at! : TableLine, Str => {}
fail_at! = |table_line, why| {
	place = "${table_line.path}:${table_line.number.to_str()}"
	Shale.fail!("find_names_that_disagree_with_their_types: ${place}: ${why}")
}

## The word and its promise on one line. A line that is neither stops the run.
read_entry! : TableLine => { word : Str, promise : Words.Promise }
read_entry! = |table_line| {
	groups = match Shale.re_find!(table_line.line, line_pattern) {
		Found(found) => found.groups
		NoMatch => {
			fail_at!(table_line, "expected `word: Type, Type`, `word: none` or `word: any`")
			[]
		}
	}
	match groups {
		[word, said] => { word, promise: promise_of(said) }
		_ => crash "find_names_that_disagree_with_their_types: a table line's pattern gave no two groups"
	}
}

## What `none`, `any` or a list of types promises.
promise_of : Str -> Words.Promise
promise_of = |said|
	if said == "none" {
		NoNameMay
	} else if said == "any" {
		AnyType
	} else {
		OneOf(said.split_on(",").map(Text.trim))
	}

## A list of one word a line, any note after `--` cut off, as a set. A
## missing file, a word listed twice, or a line of two words stops the run.
read_word_set! : Str => Set(Str)
read_word_set! = |path| {
	text = match Shale.read!(path) {
		Found(found) => found
		Missing => {
			Shale.fail!("no word list ${path}")
			""
		}
	}
	var $words = Set.empty()
	for line in Text.lines(text) {
		word = Text.trim(Text.before_first(line, "--"))
		if word.contains(" ") or $words.contains(word) {
			Shale.fail!("${path}: `${word}` is no single new word")
		}
		if word != "" {
			$words = $words.insert(word)
		}
	}
	$words
}

Shale original

cookbook/roc/check_name_types.shale, 207 lines, at e5cb7ec0

The libraries it loads: cookbook/roc/declared.shale (1,075 lines), cookbook/findings.shale (21 lines), cookbook/roc/parsed.shale (34 lines), cookbook/roc/gate_recipe.shale (102 lines).

-- This recipe finds names that disagree with their types: a number left bare
-- beside a typed one, a constant that means "none" but has an ordinary type,
-- and, given a project's table, a word whose names must hold one type.
--
--   cd <repo> && shale <shale>/cookbook/roc/check_name_types.shale table=name_types.txt
--   shale cookbook:roc/check_name_types.shale self_test=1
--
-- The arguments:
--   glob       the files to check, `**/*.roc` by default;
--   table      the project's table of words and types, without which
--              `name_type` has nothing to judge;
--   self_test  with `self_test=1`, check the plants in
--              `cookbook/roc/plants/check_name_types/`.
--
-- Each line of the table is `word: Type, Type`, `word: none` or `word: any`,
-- such as `dist: Distance`. A blank line or one starting with `#` is skipped,
-- and a malformed line or a word listed twice stops the run. The table belongs
-- to the project, because what `dist` must be depends on the project's types.
--
-- The checks read top-level names, module members and the record fields of
-- types and annotations, never locals:
--
--   name_type         A name whose last word is in the table has a type the
--                     table doesn't allow. A function is judged by what it
--                     returns, and a type by its last part, so
--                     `Geom.Distance` is `Distance`. In a name that starts
--                     with a preposition or a question, the last word isn't
--                     the thing named (`from_fraction`, `after_two_steps`,
--                     `is_fraction`), so it is not judged. `none` means no
--                     name may end in the word, whatever its type or start,
--                     and `any` means the word holds no promise at all.
--   bare_beside_unit  A field that is a bare number in one record and a unit
--                     in another, a unit being a nominal type built on a
--                     number and declared in the files read. It means a
--                     retyping stopped halfway. Each bare field is a finding.
--                     A field named by a preposition (`from`, `to`, `at`) or
--                     by a word the table gives `any` (`id`, where a host's
--                     number and a user's id are two things) is not judged,
--                     because that word fits any two things.
--   no_value          A constant whose first word is `no`, `none` or `unset`
--                     and whose type is not a `Bool` or a tag union. An
--                     ordinary value kept to mean "none" should be a tag.
--                     A `List` has its own empty case, and a type's own member
--                     of that type (`Attention.none : Attention`) is its
--                     scale's bottom, so neither is judged, and neither is a
--                     constant with no annotation. An alias of a function
--                     type is a function's type (`no_draw : Draw`, `Draw : U64
--                     -> List(U64)`), so it is not judged either. A string with something in
--                     it is words about the case, not a stand-in for it
--                     (`no_match_words`), so only `""` is judged.
--
-- The output is the counts, one line per finding, and the counts again
-- (cookbook/findings.shale). The run fails if there are findings, or if
-- any file doesn't parse, and the files that do parse are judged either way.
-- budget: steps=800000000 arena_bytes=2000000000 output_bytes=4000000

const SELF_TEST = arg("self_test", "") == "1"
const GLOB = arg("glob", "**/*.roc")
const TABLE_FILE = arg("table", "")
use("./declared.shale")
use("cookbook:findings.shale")
use("./parsed.shale")
use("./gate_recipe.shale")
const CHECKS = {"name_type", "bare_beside_unit", "no_value"}
const BARE_NUMBERS = {U8 = true, U16 = true, U32 = true, U64 = true, U128 = true, I8 = true, I16 = true, I32 = true, I64 = true, I128 = true, F32 = true, F64 = true, Dec = true}
const NONE_WORDS = {no = true, none = true, unset = true}
const QUESTION_WORDS = {is = true, has = true, can = true, should = true}
const PREPOSITIONS = word_set("cookbook:words/prepositions.txt")

-- The table as a map from each word to the list of types allowed for it,
-- which is empty for `none` and `{"any"}` for `any`.
function name_type_table(path)
  local table_of_words = {}
  if path == "" then return table_of_words end
  if not exists(path) then fail("check_name_types: no table " .. path) end
  local number = 0
  for raw in lines(read(path)) do
    number = number + 1
    local l = trim(raw)
    if l ~= "" and not starts_with(l, "#") then
      local m = re_find(l, "^([a-z0-9]+): *(none|any|[A-Z][A-Za-z0-9]*(?:, *[A-Z][A-Za-z0-9]*)*)$")
      if m == nil then fail("check_name_types: " .. path .. ":" .. number .. ": expected `word: Type, Type`, `word: none` or `word: any`") end
      if has_key(table_of_words, m.groups[1]) then fail("check_name_types: " .. path .. ":" .. number .. ": `" .. m.groups[1] .. "` is listed twice") end
      local allowed = {}
      if m.groups[2] ~= "none" then
        for t in split(m.groups[2], ",") do push(allowed, trim(t)) end
      end
      table_of_words[m.groups[1]] = allowed
    end
  end
  return table_of_words
end

function promises_nothing(table_of_words, word)
  return has_key(table_of_words, word) and has_item(table_of_words[word], "any")
end

function judge_name_type(d, table_of_words, report)
  local ws = name_words(sub(d.name, 1, ends_with(d.name, "!") and #d.name - 1 or #d.name))
  if #ws == 0 or not has_key(table_of_words, ws[#ws]) then return nil end
  local allowed = table_of_words[ws[#ws]]
  if promises_nothing(table_of_words, ws[#ws]) then return nil end
  local type_name = d.kind == "field" and d.type or d.result
  if type_name == "" or type_name == "_" then return nil end
  local names_something_else = has_key(PREPOSITIONS, ws[1]) or has_key(QUESTION_WORDS, ws[1])
  if #allowed == 0 then
    push(report, {path = d.path, line = d.line, check = "name_type", what = "`" .. d.name .. "` ends in `" .. ws[#ws] .. "`, which no name here may: its type is `" .. type_name .. "`"})
  elseif not names_something_else and not has_item(allowed, last_part(type_name)) then
    push(report, {path = d.path, line = d.line, check = "name_type", what = "`" .. d.name .. "` is `" .. type_name .. "`, and a name ending `" .. ws[#ws] .. "` is `" .. join(allowed, "` or `") .. "` here"})
  end
  return nil
end

-- The nominal types built on a number, by name.
function unit_types(all)
  local units = {}
  for d in all do
    if d.kind == "type" and d.is_nominal and has_key(BARE_NUMBERS, d.underlying) then units[d.name] = true end
  end
  return units
end

function judge_bare_fields(all, table_of_words, report)
  local units = unit_types(all)
  local unit_of_field = {}
  for d in all do
    if d.kind == "field" and has_key(units, last_part(d.type)) then unit_of_field[d.name] = d end
  end
  for d in all do
    if d.kind == "field" and has_key(BARE_NUMBERS, d.type) and has_key(unit_of_field, d.name) and not has_key(PREPOSITIONS, d.name) and not promises_nothing(table_of_words, d.name) then
      local typed = unit_of_field[d.name]
      push(report, {path = d.path, line = d.line, check = "bare_beside_unit", what = "the field `" .. d.name .. "` is a bare `" .. d.type .. "` here and a `" .. typed.type .. "` at " .. typed.path .. ":" .. typed.line})
    end
  end
  return nil
end

function judge_no_values(all, report)
  local tag_types = {}
  -- An alias of a function type (`Draw : U64 -> List(U64)`) makes a value
  -- of it a function, which `fn` sees only when written out.
  local function_aliases = {}
  for d in all do
    if d.kind == "type" and d.is_tags then tag_types[d.name] = true end
    if d.kind == "type" and d.is_fn and not d.is_nominal then function_aliases[d.name] = true end
  end
  for d in all do
    if d.kind == "value" and d.annotated and not d.fn then
      local ws = split(d.name, "_")
      local is_none_word = has_key(NONE_WORDS, ws[1])
      local is_plain = d.type ~= "Bool" and not d.has_text and not starts_with(d.type, "[") and not starts_with(d.type, "List(") and d.owner ~= last_part(d.type) and not has_key(tag_types, last_part(d.type)) and not has_key(function_aliases, last_part(d.type))
      if is_none_word and is_plain then push(report, {path = d.path, line = d.line, check = "no_value", what = "`" .. d.name .. "` means none and is a `" .. d.type .. "`: keep the case as a tag"}) end
    end
  end
  return nil
end

function self_test()
  local at = "cookbook:roc/plants/check_name_types/"
  local table_arg = "table=" .. at .. "table.txt"
  check_plants("check_name_types", "cookbook:roc/check_name_types.shale", CHECKS, {
    {glob = at .. "name_type.roc", args = {table_arg}, counts = {name_type = 6}, says = {"name_type.roc:3: name_type: `bull_dist` is `Geom.Along`, and a name ending `dist` is `Distance` here", "`in_2_frames` ends in `frames`"}},
    {glob = at .. "name_type.roc"},
    {glob = at .. "quiet_name_type.roc", args = {table_arg}},
    {glob = at .. "bare_beside_unit/*.roc", counts = {bare_beside_unit = 2}, says = {"Rider.roc:4: bare_beside_unit: the field `forward` is a bare `F64` here and a `Distance` at"}},
    {glob = at .. "quiet_bare/*.roc"},
    {glob = at .. "bare_any/*.roc", counts = {bare_beside_unit = 1}, says = {"the field `id` is a bare `U64` here"}},
    {glob = at .. "bare_any/*.roc", args = {"table=" .. at .. "table_any.txt"}},
    {glob = at .. "name_type.roc", args = {"table=" .. at .. "table_any.txt"}},
    {glob = at .. "no_value.roc", counts = {no_value = 4}, says = {"no_value.roc:9: no_value: `no_frames` means none and is a `Steps`"}},
    {glob = at .. "quiet_no_value.roc"},
    {glob = at .. "broken/*.roc", stops = true, says = {"refused: "}},
    {glob = at .. "quiet_name_type.roc", args = {"table=" .. at .. "no_such.txt"}, stops = true, says = {"no table"}},
    {glob = at .. "quiet_name_type.roc", args = {"table=" .. at .. "table_malformed.txt"}, stops = true, says = {"table_malformed.txt:2: expected"}},
    {glob = at .. "quiet_name_type.roc", args = {"table=" .. at .. "table_twice.txt"}, stops = true, says = {"`dist` is listed twice"}},
  })
  return nil
end

function run_check()
  local table_of_words = name_type_table(TABLE_FILE)
  local paths = glob(GLOB)
  local parsed = parse_roc_files(paths)
  local all = {}
  for f in parsed.files do
    for d in declarations_of(f) do push(all, d) end
  end
  local report = {}
  for d in all do
    if d.kind == "field" or d.kind == "value" then judge_name_type(d, table_of_words, report) end
  end
  judge_bare_fields(all, table_of_words, report)
  judge_no_values(all, report)
  local verdict = verdict_of("check_name_types", CHECKS, report, #paths)
  print_findings(verdict.summary, verdict.found)
  fail_if_refused("check_name_types", 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