rewrite_module_calls_as_method_calls
Roc
It also imports Imports, RocTypes, Text, Tree from the shared Roc library.
cookbook/roc/rewrite_module_calls_as_method_calls/rewrite_module_calls_as_method_calls.roc, 151 lines
## rewrite_module_calls_as_method_calls, in Roc on Shale's platform (roc_platform/README.md):
## old-style Roc calls rewritten as method calls, `List.map(xs, f)` as
## `xs.map(f)`, wherever the compiler agrees it is the same call. Its
## launcher, cookbook/roc/rewrite_module_calls_as_method_calls.shale, is how it is run, and
## its header says which calls turn, how the types and the compiler judge
## them, and the arguments. check_goldens.shale, beside this, holds its
## output and the files it rewrites on the plants to its goldens.
##
## cd <repo> && shale cookbook:roc/rewrite_module_calls_as_method_calls.shale glob=app/*.roc root=app/main.roc
## cd <repo> && shale cookbook:roc/rewrite_module_calls_as_method_calls.shale glob=app/*.roc root=app/main.roc apply=1
## shale cookbook:roc/rewrite_module_calls_as_method_calls.shale self_test=1
##
## This root reads the arguments, globs the files and prints the verdict.
## Run is the rewrite: the trees (Source), the candidates (Candidates, with
## Literals), the types (Types, judging by Judging and Peers), the trial and
## the confirm (Trial, by Compiler, writing by Rewritten), all on a sheet
## (Tally); Sweep is what the rewrites leave for a sweep; SelfTest runs the
## plants of Plants. Imports, Text and RocTypes are the cookbook's Roc
## library, cookbook/roc/lib/.
## budget: steps=900000000 output_bytes=4000000 arena_bytes=3000000000 kept_bytes=256000000 changes=100000 change_bytes=2000000000 programs=1100 roc_cpu_ms=3600000
app [main!] { lib: "../lib/main.roc", pf: platform "../../../roc_platform/platform/main.roc" }
import pf.Shale
import Compiler
import Run
import SelfTest
import Sweep
import lib.Text
main! : {} => {}
main! = |{}| {
self_test = Shale.arg!("self_test", "") == "1"
apply = self_test or Shale.arg!("apply", "") == "1"
use_types = either!("types", Shale.arg!("types", "1"))
count_only = !(either!("trials", Shale.arg!("trials", "1")))
if count_only and apply and !(self_test) {
Shale.fail!("rewrite_module_calls_as_method_calls: trials=0 writes nothing, so not with apply=1")
}
if count_only and !(use_types) {
Shale.fail!("rewrite_module_calls_as_method_calls: trials=0 counts by the types, so not with types=0")
}
peers = Shale.arg!("peers", "")
if peers != "" and peers != "undo" {
Shale.fail!("rewrite_module_calls_as_method_calls: peers=${peers}: peers takes only `undo`")
}
undo = peers == "undo"
if undo and (count_only or !(use_types)) {
Shale.fail!("rewrite_module_calls_as_method_calls: peers=undo judges peers by the types and turns them in trials, so not with trials=0 or types=0 (trials=0 counts them as peer_receiver)")
}
plant = Shale.arg!("plant", "")
if plant != "" and !(self_test) {
Shale.fail!("rewrite_module_calls_as_method_calls: plant= is for the self-test's child runs, and needs self_test=1")
} else if self_test and plant != "" {
SelfTest.plant!(plant, Compiler.roc_bin!(Bool.True))
} else if self_test {
SelfTest.run!({})
} else {
rewrite!({ apply, use_types, count_only, undo })
}
}
## Whether the argument `name`, given as `value`, is 1 (its default) rather
## than 0; any other value stops the run.
either! : Str, Str => Bool
either! = |name, value| {
if value != "0" and value != "1" {
Shale.fail!("rewrite_module_calls_as_method_calls: ${name}=${value}: ${name} must be 1 (the default) or 0")
}
value == "1"
}
## The rewrite of the glob's files, its summary, its findings and the
## summary again (cookbook/findings.shale), then the files no root reaches.
rewrite! : { apply : Bool, use_types : Bool, count_only : Bool, undo : Bool } => {}
rewrite! = |mode| {
root = Shale.arg!("root", "")
from = U64.from_str(Shale.arg!("from", "1")) ?? 1
types_from = Shale.arg!("types_from", "")
paths = SelfTest.paths_of_globs!(Shale.arg!("glob", "**/*.roc"))
roc = Compiler.roc_bin!(Bool.False)
total = Run.all!({
paths,
root,
from,
use_types: mode.use_types,
types_roc: roc,
judge: { roc, apply: mode.apply },
count_only: mode.count_only,
types_from,
undo: mode.undo,
})
made = Sweep.made!(total.tally)
summary = "${summary_of(mode, total, from, paths.len())}, made_unused_import ${made.unused.to_str()}, made_long_line ${made.long.to_str()}"
kinds = total.tally.kind_counts
.sort_with(|(first, _), (second, _)| Text.byte_order(first, second))
.map(|(kind, count)| "${kind} ${count.to_str()}")
judged = if mode.use_types {
["types: the first arguments of the candidates the types judged: ${Str.join_with(kinds, ", ")}"]
} else {
[]
}
print_findings!(summary, total.lines.concat(made.lines).concat(judged))
for path in total.unreached {
Shale.print!("not reached by ${root}: ${path}")
}
if !(total.unreached.is_empty()) {
Shale.fail!("rewrite_module_calls_as_method_calls: no root reaches ${total.unreached.len().to_str()} file(s) with a call to try, listed above: their calls were left untried")
}
}
## The summary line's counts, and where to go on from when the programs ran
## out.
summary_of : { apply : Bool, use_types : Bool, count_only : Bool, undo : Bool }, Run.Total, U64, U64 -> Str
summary_of = |mode, total, from, file_count| {
count = |n| n.to_str()
programs = count(total.tally.programs_used)
counted = if mode.count_only {
"count: files ${count(total.files)}, candidates ${count(total.candidates)}, proven ${count(total.rewritten)}, unsettled ${count(total.unsettled)}, left ${count(total.left)}, peer_receiver ${count(total.peers)}, programs ${programs} (no trials: the types alone decide)"
} else {
undone = if mode.undo {
"peers=undo, "
} else {
""
}
dry = if mode.apply {
""
} else {
"dry run: "
}
checks = "checks: ${count(total.tally.confirms)} confirming proven calls, ${count(total.tally.rounds)} in trial rounds"
"${undone}${dry}files ${count(total.files)}, candidates ${count(total.candidates)}, rewritten ${count(total.rewritten)}, left ${count(total.left)}, peer_receiver ${count(total.peers)}, programs ${programs} (${checks})"
}
if total.next > 0 {
"${counted}, in files ${count(from)} to ${count(total.next - 1)} of ${count(file_count)}: a run holds ${count(Run.max_programs)} programs; go on with from=${count(total.next)}"
} else {
counted
}
}
## 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/rewrite_module_calls_as_method_calls/Compiler.roc, 125 lines
## The tree's own Roc, which judges each rewrite: `roc check` and its errors,
## `roc test`'s summary, and `roc fmt`. The Roc is the one the tree pins
## (its `roc-version`), since method lookup has changed
## between nightlies. Each refusal is worded as the Shale original's.
import pf.Shale
import Candidates
import lib.Text
Compiler := [].{
## What `roc check` said: whether it passed, each error it reported (a
## warning counts, since a warning fails the build), and its output.
Check : { ok : Bool, errors : List(Candidates.CheckError), out : Str }
## The OS path of the tree's Roc: the pin in `roc-version` where the run
## starts, or in a self-test the pin pinned.shale names.
roc_bin! : Bool => Str
roc_bin! = |self_test| {
pin = if self_test {
Compiler.self_test_pin!({})
} else if Shale.exists!("roc-version") {
Text.trim(Compiler.read_text!("roc-version"))
} else {
Compiler.stop!("rewrite_module_calls_as_method_calls: no roc-version where the run starts: run it from the repository's root, whose roc-version pins its Roc")
}
roc = "tools:roc-${pin}/roc"
if !(Shale.exists!(roc)) {
Compiler.stop!("rewrite_module_calls_as_method_calls: no ${roc}: install Roc ${pin} into ~/tools/roc-${pin}/ (roc-apps's toolchain release carries it)")
} else {
real = Shale.real!(roc)
said = Shale.run!({ argv: [real, "version"], keep: Whole(4000), timeout_ms: 30000, want: "" })
if Text.trim(said.out) == "Roc compiler version ${pin}" {
real
} else {
Compiler.stop!("rewrite_module_calls_as_method_calls: ${roc} says ${Text.trim(said.out)}, not Roc compiler version ${pin}")
}
}
}
## The pin every recipe's self-test runs, from cookbook/roc/pinned.shale's
## `SELF_TEST_PIN`, its one home.
self_test_pin! : {} => Str
self_test_pin! = |{}| {
pinned = Compiler.read_text!("cookbook:roc/pinned.shale")
match Shale.re_find!(pinned, "\nconst SELF_TEST_PIN = \"([^\"]+)\"") {
Found(matched) => matched.groups.first() ?? ""
NoMatch => Compiler.stop!("rewrite_module_calls_as_method_calls: cookbook/roc/pinned.shale names no SELF_TEST_PIN")
}
}
## `roc check` on the app `root`.
check! : Str, Str => Compiler.Check
check! = |roc, root| {
ran = roc_run!([roc, "check", Shale.real!(root)], Whole(64000000), 900000)
var $errors = []
for said in Text.lines(ran.out) {
# An error's heading is `── ✗ <title> ───── <path>:<line>:<col>`, and
# a warning's has `●` in place of `✗`.
if said.starts_with("── ✗ ") or said.starts_with("── ● ") {
match Shale.re_find!(said, " ([^ ]+):([0-9]+):([0-9]+)$") {
Found(at) => {
heading = Str.from_utf8_lossy(said.to_utf8().drop_first(11))
title = Text.trim(Text.before_first(heading, " ─"))
place = at.groups.get(0) ?? ""
line = U64.from_str(at.groups.get(1) ?? "") ?? 0
$errors = $errors.append({ title, file: Text.basename(place), line })
}
NoMatch => {}
}
}
}
{ ok: ran.code == 0, errors: $errors, out: ran.out }
}
## The last line of `roc test` on `root`, without its time, and the exit
## code: what a rewrite may not change.
test_summary! : Str, Str => Str
test_summary! = |roc, root| {
ran = roc_run!([roc, "test", Shale.real!(root)], Whole(64000000), 900000)
last = Text.lines(Text.trim(ran.out)).last() ?? ""
summary = match Shale.re_find!(last, "^(.*) in [0-9.]+ ms\\.") {
Found(matched) => matched.groups.first() ?? ""
NoMatch => last
}
"${summary} (exit ${ran.code.to_str()})"
}
## Whether `roc fmt` finds the file as it would lay it out.
is_fmt_clean! : Str, Str => Bool
is_fmt_clean! = |roc, path| roc_run!([roc, "fmt", "--check", Shale.real!(path)], Tail(20), 120000).code == 0
## The file laid out by `roc fmt`.
fmt! : Str, Str => {}
fmt! = |roc, path| {
_ran = roc_run!([roc, "fmt", Shale.real!(path)], Tail(20), 120000)
{}
}
## The first non-blank line of `out`, for a failure that names no error
## (a crash).
first_line_said : Str -> Str
first_line_said = |out|
match Text.lines(out).find_first(|said| Text.trim(said) != "") {
Ok(said) => Text.trim(said)
Err(_) => "nothing said"
}
## A file's text; a missing one stops the run.
read_text! : Str => Str
read_text! = |path|
match Shale.read!(path) {
Found(text) => text
Missing => Compiler.stop!("rewrite_module_calls_as_method_calls: no ${path}")
}
## The run stopped, saying why; the text is never used.
stop! : Str => Str
stop! = |why| {
Shale.fail!(why)
""
}
}
roc_run! : List(Str), [Head(U64), Tail(U64), Whole(U64)], U64 => { code : I64, out : Str }
roc_run! = |argv, keep, timeout_ms| Shale.run!({ argv, keep, timeout_ms, want: "" })
cookbook/roc/rewrite_module_calls_as_method_calls/Run.roc, 420 lines
## The rewrite of a list of files, each judged on its root: their trees read,
## their candidates found, the types read of each root and judging them, then
## the confirm and the trials in the files' order, as far as the run's
## programs allow (rewrite_module_calls_as_method_calls.shale's `run_all`).
import pf.Shale
import Candidates
import Compiler
import Judging
import Peers
import Source
import Tally
import Trial
import Types
import lib.RocTypes
import lib.Text
Run := [].{
## What to rewrite: the files, the roots (`a.roc,b.roc`), the file to
## start at (counted from 1), whether the types are read, the Roc
## roc-types' pin must match, the Roc that judges, and the modes:
## `count_only` (`trials=0`), `types_from` and `undo` (`peers=undo`).
Asked : {
paths : List(Str),
root : Str,
from : U64,
use_types : Bool,
types_roc : Str,
judge : Trial.Judge,
count_only : Bool,
types_from : Str,
undo : Bool,
}
## What the run did: its counts, a line for each call that stays (and
## each peer method call, and under `trials=0` each call the types left
## unsettled), the file to go on from when the programs ran out (else 0),
## its sheet, and the files with a call to try that no root reaches.
Total : {
files : U64,
candidates : U64,
rewritten : U64,
left : U64,
unsettled : U64,
peers : U64,
lines : List(Str),
next : U64,
tally : Tally.Sheet,
unreached : List(Str),
}
## The programs a run may start, Shale's own budget unset.
max_programs : U64
max_programs = 1000
## Rewrites the files of `asked.paths` from the `asked.from`th on.
all! : Run.Asked => Run.Total
all! = |asked| {
if asked.use_types and asked.root == "" {
Shale.fail!("rewrite_module_calls_as_method_calls: the types need root=, an app importing every file of the glob: roc-types reads an app, and a type module only through one. Give root=, or types=0 to run without them, every candidate tried")
}
if !(asked.use_types) and asked.root.contains(",") {
Shale.fail!("rewrite_module_calls_as_method_calls: root=${asked.root}: several roots need the types, which say which root reaches a file; give one root, or run with the types")
}
roots = if asked.root == "" {
[]
} else {
match RocTypes.root_apps("rewrite_module_calls_as_method_calls", asked.root) {
Ok(apps) => apps
Err(why) => {
Shale.fail!(why)
[]
}
}
}
if asked.types_from != "" and roots.len() != 1 {
Shale.fail!("rewrite_module_calls_as_method_calls: types_from= holds one root's types, and root= names ${roots.len().to_str()}")
}
files = parsed!(asked.paths)
aliases = if asked.use_types {
Peers.declared_aliases(files.values())
} else {
Dict.empty()
}
symmetric = match Peers.symmetric_table(Compiler.read_text!(symmetric_functions)) {
Ok(names) => names
Err(why) => {
Shale.fail!(why)
Set.empty()
}
}
var $judged = []
for path in asked.paths.drop_first(asked.from - 1) {
file = match files.get(path) {
Ok(found) => found
Err(_) => {
Shale.fail!("rewrite_module_calls_as_method_calls: roc-ast gave no tree for ${path}")
Source.of(path, "", [])
}
}
cands = Candidates.of_file(file, module_of_path(path))
method_calls = if asked.use_types {
Peers.method_calls(file, symmetric)
} else {
[]
}
open = cands.any(|cand| cand.why_left == "") or !(method_calls.is_empty())
$judged = $judged.append({ path, file, real: Shale.real!(path), root: roots.first() ?? path, cands, counts: [], open, unreached: Bool.False, method_calls, peers: [] })
}
# The types judge only open candidates, so with none, roc-types never runs.
read_types = asked.use_types and $judged.any(|one| one.open)
typing = { by_region: Dict.empty(), aliases, symmetric }
typed = if read_types {
with_types!(asked, roots, typing, $judged)
} else {
{ tally: Tally.ran(Tally.empty), judged: $judged }
}
unreached = typed.judged.keep_if(|one| one.unreached).map(|one| one.path)
in_mode = typed.judged.map(|one| as_undo(asked.undo, one))
ready = in_mode.map(with_open_count)
total = {
files: 0,
candidates: 0,
rewritten: 0,
left: 0,
unsettled: 0,
peers: 0,
lines: [],
next: 0,
tally: typed.tally,
unreached,
}
if asked.count_only {
counted_by_types(total, ready)
} else {
tried!(asked, total, ready)
}
}
}
## The symmetric functions' list.
symmetric_functions : Str
symmetric_functions = "cookbook:roc/symmetric_functions.txt"
## A file as the run judges it: its tree, real path and root, its
## candidates, the kinds of type the types found, whether the types must
## judge it (`open`: a module call to try, or with the types a symmetric
## method call), whether no root reaches it, its symmetric method calls and
## its peer method calls; then how many calls are open and whether all are
## proven.
Judged : {
path : Str,
file : Source.File,
real : Str,
root : Str,
cands : List(Candidates.Candidate),
counts : Judging.KindCounts,
open : Bool,
unreached : Bool,
method_calls : List(Peers.MethodCall),
peers : List(Candidates.Candidate),
}
Ready : {
path : Str,
file : Source.File,
root : Str,
cands : List(Candidates.Candidate),
counts : Judging.KindCounts,
unreached : Bool,
peers : List(Candidates.Candidate),
open_count : U64,
all_proven : Bool,
}
## The module a .roc file holds, its name without `.roc`.
module_of_path : Str -> Str
module_of_path = |path| Text.basename(path).drop_suffix(".roc")
## Every file's tree from Roc's parser and its text, by path: one program.
parsed! : List(Str) => Dict(Str, Source.File)
parsed! = |paths| {
var $files = Dict.empty()
if !(paths.is_empty()) {
for tree in Shale.roc_tree!(paths) {
if tree.err != "" {
Shale.fail!("rewrite_module_calls_as_method_calls: roc-ast: ${tree.path}: ${tree.err}")
}
$files = $files.insert(tree.path, Source.of(tree.path, Compiler.read_text!(tree.path), tree.nodes))
}
}
$files
}
## The types read of each root, one at a time, each file's root the first
## whose app reaches it, its open candidates judged by that root's types on
## the way. A file with a call to try that no root reaches is `unreached`,
## and the run goes on without it.
with_types! : Run.Asked, List(Str), Judging.Typing, List(Judged) => { tally : Tally.Sheet, judged : List(Judged) }
with_types! = |asked, roots, typing, judged| {
only = if asked.types_from == "" {
Set.empty()
} else {
var $reals = Set.empty()
for path in asked.paths {
$reals = $reals.insert(Shale.real!(path))
}
$reals
}
var $tally = Tally.ran(Tally.empty)
var $judged = judged
var $found = Set.empty()
for root in roots {
if asked.types_from == "" {
$tally = Tally.ran($tally)
}
typed = Types.of_root!({ root, roc: asked.types_roc, types_from: asked.types_from, only })
if !($tally.typed_roots.contains(root)) {
$tally = { ..$tally, typed_roots: $tally.typed_roots.append(root) }
}
types_here = { ..typing, by_region: typed.by_region }
var $judged_here = []
for one in $judged {
if one.open and !($found.contains(one.path)) and typed.modules.contains(one.real) {
$found = $found.insert(one.path)
by_types = Judging.by_types(one.counts, one.file, one.cands, one.real, types_here)
peers = one.peers.concat(Judging.method_peers(one.file, one.method_calls, one.real, types_here))
$judged_here = $judged_here.append({ ..one, root, counts: by_types.counts, cands: by_types.cands, peers })
} else {
$judged_here = $judged_here.append(one)
}
}
$judged = $judged_here
}
var $marked = []
for one in $judged {
$marked = $marked.append({ ..one, unreached: one.open and !($found.contains(one.path)) })
}
{ tally: $tally, judged: $marked }
}
## Under `peers=undo`, a file's candidates are its peer method calls alone.
as_undo : Bool, Judged -> Judged
as_undo = |undo, one|
if undo {
{ ..one, cands: one.peers, peers: [], counts: [] }
} else {
one
}
with_open_count : Judged -> Ready
with_open_count = |one| {
open_cands = one.cands.keep_if(|cand| cand.why_left == "")
all_proven = !(open_cands.is_empty()) and !(one.unreached) and open_cands.all(|cand| cand.proven)
{
path: one.path,
file: one.file,
root: one.root,
cands: one.cands,
counts: one.counts,
unreached: one.unreached,
peers: one.peers,
open_count: open_cands.len(),
all_proven,
}
}
## The file's peer method calls added to the findings, a `path:line:
## peer_receiver: why` each, and to their count.
with_peer_findings : Run.Total, Ready -> Run.Total
with_peer_findings = |total, one| {
said = one.peers.map(
|cand| {
why = "`.${cand.fn}` is symmetric and its receiver and first argument are both ${cand.module_name}s, so neither is the subject"
"${one.path}:${cand.line.to_str()}: peer_receiver: ${why}: ${cand.module_name}.${cand.fn}(...)"
},
)
{ ..total, peers: total.peers + one.peers.len(), lines: total.lines.concat(said) }
}
## A file's kinds of type added to the sheet's, once the file is begun.
with_counts : Run.Total, Ready -> Run.Total
with_counts = |total, one| {
counts = one.counts.fold(total.tally.kind_counts, |all, (kind, count)| Judging.counted(all, kind, count))
{ ..total, tally: { ..total.tally, kind_counts: counts } }
}
## A call that stays, as its finding line.
left_line : Str, Candidates.Candidate -> Str
left_line = |path, cand| "${path}:${cand.line.to_str()}: ${cand.module_name}.${cand.fn}: ${cand.why_left}"
## `trials=0`'s answer: a proven call counts as rewritten, an open one the
## types didn't settle as unsettled, with a line naming the kind of type
## they gave, and a call that stays as left, with its reason. Nothing is
## written or compiled.
counted_by_types : Run.Total, List(Ready) -> Run.Total
counted_by_types = |total, ready| {
var $total = total
for one in ready {
cands = if one.unreached {
[]
} else {
one.cands
}
proven = cands.keep_if(|cand| cand.why_left == "" and cand.proven)
if !(proven.is_empty()) {
$total = { ..$total, tally: Tally.noted($total.tally, one.file, proven) }
}
if !(one.unreached) {
$total = { ..$total, files: $total.files + 1 }
}
$total = with_counts($total, one)
$total = { ..$total, candidates: $total.candidates + cands.len() }
$total = with_peer_findings($total, one)
for cand in cands {
if cand.why_left != "" {
$total = { ..$total, left: $total.left + 1, lines: $total.lines.append(left_line(one.path, cand)) }
} else if cand.proven {
$total = { ..$total, rewritten: $total.rewritten + 1 }
} else {
unsettled = "${one.path}:${cand.line.to_str()}: ${cand.module_name}.${cand.fn}: unsettled: the types gave ${cand.kind}, and only a trial would tell"
$total = { ..$total, unsettled: $total.unsettled + 1, lines: $total.lines.append(unsettled) }
}
}
}
$total
}
## The `roc test` summary of `root` before any rewrite, which every trial on
## that root must match: taken once a root, and `roc check` must pass first.
baseline! : Trial.Judge, Tally.Sheet, Dict(Str, Str), Str => { tally : Tally.Sheet, baselines : Dict(Str, Str), summary : Str }
baseline! = |judge, tally, baselines, root|
match baselines.get(root) {
Ok(summary) => { tally, baselines, summary }
Err(_) => {
if !(Compiler.check!(judge.roc, root).ok) {
Shale.fail!("rewrite_module_calls_as_method_calls: `roc check ${root}` fails before any rewrite: fix it first")
}
summary = Compiler.test_summary!(judge.roc, root)
{ tally: Tally.ran(Tally.ran(tally)), baselines: baselines.insert(root, summary), summary }
}
}
## The confirm and the trials, file by file. A file is begun only while the
## programs it may take are left: `Trial.max_rounds` checks, a test and,
## under `apply`, two `roc fmt`s, and the first file on a root also the
## baseline's check and test.
tried! : Run.Asked, Run.Total, List(Ready) => Run.Total
tried! = |asked, total, ready| {
judge = asked.judge
per_file = Trial.max_rounds + 5
var $total = total
var $baselines = Dict.empty()
var $place = 0
for one in ready {
$place = $place + 1
cands = if one.unreached {
[]
} else {
one.cands
}
if !(one.unreached) and one.all_proven and !($total.tally.confirmed.contains(one.path)) {
# The programs taken before this file's: the baseline's two, if its
# root has none yet, the confirm's checks and test, and this file's
# own trial, should the confirm set it aside. Under `apply` each file
# in the confirm also takes two `roc fmt`s, so only as many join as
# fit.
baseline_programs = if $baselines.contains(one.root) {
0
} else {
2
}
taken = $total.tally.programs_used + baseline_programs + Trial.max_rounds + 1 + per_file
var $files = []
for other in ready.drop_first($place - 1) {
fits = !(judge.apply) or 2 * ($files.len() + 1) + taken <= Run.max_programs
if other.all_proven and other.root == one.root and !($total.tally.confirmed.contains(other.path)) and fits {
$files = $files.append({ path: other.path, file: other.file, cands: other.cands })
}
}
if taken > Run.max_programs or $files.is_empty() {
return { ..$total, next: asked.from + $place - 1 }
}
based = baseline!(judge, $total.tally, $baselines, one.root)
$baselines = based.baselines
$total = { ..$total, tally: Trial.confirm!(judge, based.tally, one.root, $files, based.summary) }
}
kept_by_confirm = $total.tally.confirmed.get(one.path) ?? 0
if !(one.unreached) and one.open_count > 0 and kept_by_confirm == 0 and $total.tally.programs_used + per_file > Run.max_programs {
return { ..$total, next: asked.from + $place - 1 }
}
if !(one.unreached) {
$total = { ..$total, files: $total.files + 1 }
}
$total = with_counts($total, one)
$total = with_peer_findings($total, one)
if !(cands.is_empty()) {
var $cands = Candidates.without_lines(cands)
$kept : U64
var $kept = kept_by_confirm
if $kept == 0 and one.open_count > 0 {
based = baseline!(judge, $total.tally, $baselines, one.root)
$baselines = based.baselines
done = Trial.try_file!(judge, based.tally, one.file, $cands, one.root, based.summary)
$total = { ..$total, tally: done.tally }
$cands = done.cands
$kept = done.turned
}
left = $cands.keep_if(|cand| cand.why_left != "")
$total = {
..$total,
candidates: $total.candidates + $cands.len(),
rewritten: $total.rewritten + $kept,
left: $total.left + left.len(),
lines: $total.lines.concat(left.map(|cand| left_line(one.path, cand))),
}
}
}
$total
}
cookbook/roc/rewrite_module_calls_as_method_calls/SelfTest.roc, 296 lines
## The recipe's self-test: each plant in
## cookbook/roc/plants/rewrite_module_calls_as_method_calls/ judged in a child run of its own,
## through the launcher (`plant=<Name>`), so each plant gets a run's
## programs of its own. The child copies the plants to a fresh folder under
## `scratch:`, runs there with `apply=1` and checks what came out against
## the plant's expectation (Plants).
import pf.Shale
import Compiler
import Plants
import Run
import Sweep
import Types
import lib.Text
SelfTest := [].{
## Every plant in a child run of its own; a failed plant is named, and
## the rest still run.
run! : {} => {}
run! = |{}| {
if !(Shale.exists!(Types.default_checker)) {
Shale.fail!("rewrite_module_calls_as_method_calls: self-test: no ${Types.default_checker}, which the plants marked `types` are judged by: `shale install.shale` in a checkout of https://github.com/showell/roc-types installs it")
}
var $failed = []
globbed = SelfTest.paths_of_globs!("${plants}/Proven.roc, ${plants}/NoC*.roc,${plants}/Proven.roc")
held = globbed.len() == 2 and Text.basename(globbed.get(0) ?? "") == "Proven.roc" and Text.basename(globbed.get(1) ?? "") == "NoCalls.roc"
Shale.print!("${verdict(held)}glob=: two globs and a repeat give Proven.roc, then NoCalls.roc, each once (${Str.join_with(globbed, ", ")})")
if !(held) {
$failed = $failed.append("glob=")
}
for name in listed!(plants) {
plant = name.drop_suffix(".roc")
judged = Plants.table.any(|want| want.name == plant) or Plants.root_plants.contains(plant)
if name.ends_with(".roc") and !(judged) {
Shale.print!("FAIL ${name}: a plant the table does not judge")
$failed = $failed.append(name)
}
}
for want in Plants.table.sort_with(|first, second| Text.byte_order(first.name, second.name)) {
ran = Shale.run!({
argv: ["shale", "--root", ".", launcher, "self_test=1", "plant=${want.name}"],
keep: Tail(200),
timeout_ms: 3600000,
want: "",
})
if want.stop != "" {
stopped = ran.code > 0 and ran.out.contains(want.stop)
shown = if stopped {
""
} else {
": ${Text.trim(ran.out)}"
}
Shale.print!("${verdict(stopped)}${want.name}: stops, saying ${want.stop}${shown}")
if !(stopped) {
$failed = $failed.append(want.name)
}
} else {
for said in Text.lines(ran.out) {
if !(said.starts_with("── budgets")) {
Shale.print!(said)
}
}
if ran.code != 0 {
$failed = $failed.append(want.name)
}
}
}
if !($failed.is_empty()) {
Shale.fail!("rewrite_module_calls_as_method_calls: self-test: ${$failed.len().to_str()} plant(s) failed: ${Str.join_with($failed, ", ")}")
}
Shale.print!("rewrite_module_calls_as_method_calls: self-test: every plant as it says")
}
## The child run `plant=<name>`: the plants copied to a fresh scratch
## folder, the one plant run there with `apply=1`, and the result checked
## against its expectation.
plant! : Str, Str => {}
plant! = |name, self_test_roc| {
want = match Plants.table.find_first(|plant_want| plant_want.name == name) {
Ok(found) => found
Err(_) => {
Shale.fail!("rewrite_module_calls_as_method_calls: self-test: no plant ${name} in the table")
Plants.table.first() ?? crash "SelfTest: the table is empty"
}
}
scratch = Sweep.fresh_dir!("methods")
for listed_name in listed!(plants) {
Shale.write!("${scratch}/${listed_name}", Compiler.read_text!("${plants}/${listed_name}"))
}
file = if want.file == "" {
name
} else {
want.file
}
path = "${scratch}/${file}.roc"
paths = if want.beside == "" {
[path]
} else {
[path, "${scratch}/${want.beside}.roc"]
}
# A plant with `tree_pin` runs as though the tree pinned that Roc.
types_roc = if want.tree_pin == "" {
self_test_roc
} else {
Shale.real!("tools:roc-${want.tree_pin}/roc")
}
roots = want.root.split_on(",").keep_if(|root| root != "").map(|root| "${scratch}/${root}.roc")
# A plant with `types_from` reads the types from a file, as a gate
# keeps them: roc-types' output on the root, written here first.
types_from = if want.types_from {
written = "${scratch}/root.types"
ran = Shale.run!({
argv: [Shale.real!(Types.checker_for!(types_roc)), Shale.real!(roots.first() ?? "")],
keep: Whole(64000000),
timeout_ms: 300000,
want: "",
})
if ran.code != 0 {
Shale.print!(ran.out)
Shale.fail!("rewrite_module_calls_as_method_calls: self-test: roc-types exited ${ran.code.to_str()}")
}
Shale.write!(written, ran.out)
written
} else {
""
}
got = Run.all!({
paths,
root: Str.join_with(roots, ","),
from: 1,
use_types: want.types,
types_roc,
judge: { roc: self_test_roc, apply: Bool.True },
count_only: want.count,
types_from,
undo: want.undo,
})
if want.stop != "" {
Shale.fail!("rewrite_module_calls_as_method_calls: self-test: ${name} ran to its end, and was to stop: ${want.stop}")
}
checks = checks_of!({ want, got, path, plant_file: "${plants}/${file}.roc", roots, types_from, paths })
failures = checks.count_if(|(passed, _)| !(passed))
for (passed, what) in checks {
Shale.print!("${verdict(passed)}${what}")
}
if failures > 0 {
Shale.fail!("rewrite_module_calls_as_method_calls: self-test: ${name}: ${failures.to_str()} failed")
}
Shale.remove_tree!(scratch)
}
## The files of `globs`, several separated by commas, in the order the
## globs give them, each once.
paths_of_globs! : Str => List(Str)
paths_of_globs! = |globs| {
var $paths = []
var $seen = Set.empty()
for pattern in globs.split_on(",") {
for path in Shale.glob!(Text.trim(pattern)) {
if !($seen.contains(path)) {
$seen = $seen.insert(path)
$paths = $paths.append(path)
}
}
}
$paths
}
}
## The launcher each plant's child run goes through.
launcher : Str
launcher = "cookbook:roc/rewrite_module_calls_as_method_calls.shale"
plants : Str
plants = "cookbook:roc/plants/rewrite_module_calls_as_method_calls"
verdict : Bool -> Str
verdict = |passed|
if passed {
"ok "
} else {
"FAIL "
}
## The names in a folder, as Shale's `ls` gives them.
listed! : Str => List(Str)
listed! = |folder|
match Shale.list!(folder) {
Found(names) => names
Missing => {
Shale.fail!("rewrite_module_calls_as_method_calls: self-test: no ${folder}")
[]
}
}
## Each check of a plant's child run, in the Shale original's order: whether
## it passed and what it says.
checks_of! : { want : Plants.Expect, got : Run.Total, path : Str, plant_file : Str, roots : List(Str), types_from : Str, paths : List(Str) } => List((Bool, Str))
checks_of! = |asked| {
want = asked.want
got = asked.got
name = want.name
var $checks = []
if want.count {
$checks = $checks.append((got.rewritten == want.proven, "${name}: ${got.rewritten.to_str()} proven, want ${want.proven.to_str()}"))
$checks = $checks.append((got.unsettled == want.unsettled, "${name}: ${got.unsettled.to_str()} unsettled, want ${want.unsettled.to_str()}"))
$checks = $checks.append((Compiler.read_text!(asked.path) == Compiler.read_text!(asked.plant_file), "${name}: counted, and left as it was"))
}
match want.peers {
Peers(peers) => {
$checks = $checks.append((got.peers == peers, "${name}: ${got.peers.to_str()} peer_receiver, want ${peers.to_str()}"))
}
AnyPeers => {}
}
made = Sweep.made!(got.tally)
listed = if made.lines.is_empty() {
""
} else {
" (${Str.join_with(made.lines, "; ")})"
}
made_held = made.unused == want.made_unused and made.long == want.made_long
made_counts = "${made.unused.to_str()} made_unused_import and ${made.long.to_str()} made_long_line"
$checks = $checks.append((made_held, "${name}: ${made_counts}, want ${want.made_unused.to_str()} and ${want.made_long.to_str()}${listed}"))
if want.made_says != "" {
$checks = $checks.append((Str.join_with(made.lines, "\n").contains(want.made_says), "${name}: reports ${want.made_says}"))
}
if asked.types_from != "" {
used = got.tally.programs_used
$checks = $checks.append((used == 1, "${name}: the types read from a file, so roc-ast the one program (${used.to_str()})"))
}
unreached = got.unreached
$checks = $checks.append((unreached.len() == want.unreached, "${name}: ${unreached.len().to_str()} not reached by a root, want ${want.unreached.to_str()} (${Str.join_with(unreached, ", ")})"))
left = got.lines
left_listed = if left.is_empty() {
""
} else {
" (${Str.join_with(left, "; ")})"
}
$checks = $checks.append((left.len() == want.left, "${name}: ${left.len().to_str()} left, want ${want.left.to_str()}${left_listed}"))
if want.why != "" {
$checks = $checks.append((!(left.is_empty()) and Str.join_with(left, "\n").contains(want.why), "${name}: left because ${want.why}"))
}
file = Text.basename(asked.plant_file).drop_suffix(".roc")
want_path = "${plants}/${file}.want"
has_want = Shale.exists!(want_path)
if has_want and !(want.count) {
$checks = $checks.append((Compiler.read_text!(asked.path) == Compiler.read_text!(want_path), "${name}: comes out as ${file}.want"))
}
# In Typed, the types turn one call and leave the other, so the trial
# decides neither.
kinds = got.tally.kind_counts
if name == "Typed" {
count_of = |kind| kinds.find_first(|(named, _)| named == kind).map_ok(|(_, count)| count) ?? 0
typed_held = kinds.len() == 2 and count_of("another type") == 1 and count_of("the module's type") == 1
$checks = $checks.append((typed_held, "${name}: by type, ${json_of(kinds)}"))
}
confirms = got.tally.confirms
$checks = $checks.append((confirms == want.confirms, "${name}: ${confirms.to_str()} confirm(s), want ${want.confirms.to_str()}"))
match want.rounds {
Rounds(rounds) => {
got_rounds = got.tally.rounds
$checks = $checks.append((got_rounds == rounds, "${name}: ${got_rounds.to_str()} round(s), want ${rounds.to_str()}"))
}
AnyRounds => {}
}
runs = got.tally.typed_roots.len()
if !(want.types) {
$checks = $checks.append((kinds.is_empty() and runs == 0, "${name}: under types=0, no roc-types run"))
}
# With the types, roc-types runs once per root when a candidate is open,
# and not at all on a file with none (`no_types_run`).
if want.types {
want_runs = if want.no_types_run {
0
} else {
asked.roots.len()
}
$checks = $checks.append((runs == want_runs, "${name}: ${runs.to_str()} roc-types run(s), want ${want_runs.to_str()}"))
}
if want.left > 0 and !(has_want) {
$checks = $checks.append((Compiler.read_text!(asked.path) == Compiler.read_text!(asked.plant_file), "${name}: put back as it was"))
}
if want.beside != "" {
beside = asked.paths.get(1) ?? ""
$checks = $checks.append((Compiler.read_text!(beside) == Compiler.read_text!("${plants}/${want.beside}.roc"), "${name}: ${want.beside} left as it was"))
}
$checks
}
## The kinds' counts as Shale's `json_write` writes a map: `{"kind":1,...}`,
## in the order each was first counted.
json_of : List((Str, U64)) -> Str
json_of = |kinds| {
members = kinds.map(|(kind, count)| "\"${kind}\":${count.to_str()}")
"{${Str.join_with(members, ",")}}"
}
cookbook/roc/rewrite_module_calls_as_method_calls/Sweep.roc, 111 lines
## What the rewrites left for a sweep to fix in the same pass, which the
## recipe reports and does not fix: each import that a file used before its
## rewrite and no longer uses after it, by the cookbook's one home of that
## rule (lib's Imports, find_unused_imports'), and each line wider than 100
## columns where a turned call joined its lines (a turn alone only shortens a
## line). A line is named by its number in the rewritten text, before any
## `roc fmt`.
import pf.Shale
import Tally
import lib.Imports
import lib.Text
Sweep := [].{
## The findings, a `path:line: made_unused_import: why` or
## `made_long_line` each, and the count of each kind.
Made : { lines : List(Str), unused : U64, long : U64 }
## What the rewrites on the sheet made. Roc's parser reads files, so both
## texts of each are written to a scratch folder, removed after.
made! : Tally.Sheet => Sweep.Made
made! = |tally| {
rewrites = tally.rewrites.to_list().sort_with(|(first, _), (second, _)| Text.byte_order(first, second))
if rewrites.is_empty() {
return { lines: [], unused: 0, long: 0 }
}
dir = Sweep.fresh_dir!("made_by_rewrites")
var $files = []
$number : U64
var $number = 0
for (_, rewrite) in rewrites {
$number = $number + 1
folder = "${dir}/${$number.to_str()}"
Shale.mkdir!(folder)
Shale.write!("${folder}/before.roc", rewrite.before)
Shale.write!("${folder}/after.roc", rewrite.after)
$files = $files.concat(["${folder}/before.roc", "${folder}/after.roc"])
}
var $trees = Dict.empty()
for tree in Shale.roc_tree!($files) {
if tree.err != "" {
Shale.fail!("rewrite_module_calls_as_method_calls: roc-ast refused a rewritten text (${tree.path}): ${tree.err}")
}
$trees = $trees.insert(tree.path, tree.nodes)
}
var $made = { lines: [], unused: 0, long: 0 }
$number = 0
for (path, rewrite) in rewrites {
$number = $number + 1
folder = "${dir}/${$number.to_str()}"
before = Imports.unused_imports($trees.get("${folder}/before.roc") ?? [], rewrite.before.split_on("\n"))
was_unused = Set.from_list(before.map(|unused| unused.label))
after_lines = rewrite.after.split_on("\n")
for unused in Imports.unused_imports($trees.get("${folder}/after.roc") ?? [], after_lines) {
if !(was_unused.contains(unused.label)) {
said = "${path}:${unused.line.to_str()}: made_unused_import: ${unused.label} was used only by the calls the rewrite turned: delete the line"
$made = { ..$made, unused: $made.unused + 1, lines: $made.lines.append(said) }
}
}
var $seen = Set.empty()
for number in rewrite.joined.sort_with(
|first, second| if first < second {
Before
} else if first > second {
After
} else {
Same
},
) {
text_line = Text.line_at(after_lines, number)
width = columns_of(text_line)
if width > long_line and !($seen.contains(number)) {
$seen = $seen.insert(number)
shown = Text.trim(Text.bytes_of(text_line, { start: 0, count: 120 }))
said = "${path}:${number.to_str()}: made_long_line: ${width.to_str()} columns after the rewrite joined a call's lines: stack it (wrap_long_lines_with_trailing_commas.shale): ${shown}"
$made = { ..$made, long: $made.long + 1, lines: $made.lines.append(said) }
}
}
}
Shale.remove_tree!(dir)
$made
}
## A folder of the run's own below `scratch:`, `<prefix>.XXXXXX`, so two
## runs at once never share one (Shale's `fresh_dir`); the caller removes
## it.
fresh_dir! : Str => Str
fresh_dir! = |prefix| {
made = Shale.run!({
argv: ["mktemp", "-d", "${Shale.real!("scratch:")}/${prefix}.XXXXXX"],
keep: Tail(2),
timeout_ms: 10000,
want: "",
})
if made.code != 0 {
Shale.fail!("rewrite_module_calls_as_method_calls: no scratch folder: ${made.out}")
}
"scratch:${Text.basename(Text.trim(made.out))}"
}
}
## The width past which a line is long, as check_and_fix_group_stacking's `width`.
long_line : U64
long_line = 100
## A line's width, a tab counting four columns.
columns_of : Str -> U64
columns_of = |text_line| {
bytes = text_line.to_utf8()
bytes.len() + 3 * bytes.count_if(|byte| byte == '\t')
}
cookbook/roc/rewrite_module_calls_as_method_calls/Candidates.roc, 262 lines
## The calls a file offers to turn, `Module.fn(first, ...)`, each with why it
## must stay when it must, and what a trial's `roc check` errors say of them.
import Literals
import Rewritten
import Source
Candidates := [].{
## A call to turn, by its node: the module and function it calls, its
## line, why it stays (`""` while it is open to rewriting), whether the
## types prove it, the kind of type they gave when they settled nothing,
## and its lines in the last text that turned it (0 when it was not
## turned). A peer method call turned back is `undo`, its receiver's
## `type` kept.
Candidate : {
node : U64,
module_name : Str,
fn : Str,
line : U64,
why_left : Str,
proven : Bool,
kind : Str,
from_line : U64,
to_line : U64,
undo : Bool,
type : Str,
}
## An error `roc check` reports: its title, the file it names (its base
## name) and the line.
CheckError : { title : Str, file : Str, line : U64 }
## The calls `Module.fn(first, ...)` in the file, except calls of the
## file's own module (`own_module`), in the tree's order.
of_file : Source.File, Str -> List(Candidates.Candidate)
of_file = |file, own_module| {
var $out = []
for (node, place) in file.nodes.map_with_index(|node, index| (node, index + 1)) {
if node.kind == "e-apply" and node.kids.len() >= 2 {
callee = Source.kid_node(file, node, 1)
match module_call(callee.raw) {
Ok(called) if callee.kind == "e-ident" and called.module_name != own_module => {
why = reason_call_stays(file, place, called.module_name, called.fn)
line = Source.line_of_offset(file, node.from)
$out = $out.append(candidate(place, called.module_name, called.fn, line, why))
}
_ => {}
}
}
}
$out
}
## A peer method call to turn back into a module call, proven by the
## receiver's type, which `type` keeps.
undoing : { place : U64, module_name : Str, fn : Str, line : U64, why_left : Str, type : Str } -> Candidates.Candidate
undoing = |call| {
..candidate(call.place, call.module_name, call.fn, call.line, call.why_left),
proven: Bool.True,
undo: Bool.True,
type: call.type,
}
## The open candidates as the rewrite turns them, by node.
turning : List(Candidates.Candidate) -> Dict(U64, Rewritten.Turn)
turning = |cands| {
var $turning = Dict.empty()
for cand in cands {
if cand.why_left == "" {
$turning = $turning.insert(cand.node, { node: cand.node, module_name: cand.module_name, fn: cand.fn, undo: cand.undo })
}
}
$turning
}
## How many candidates are open.
open_count : List(Candidates.Candidate) -> U64
open_count = |cands| cands.count_if(|cand| cand.why_left == "")
## Every open candidate left, for `why`.
leave_open : List(Candidates.Candidate), Str -> List(Candidates.Candidate)
leave_open = |cands, why| cands.map(
|cand| if cand.why_left == "" {
{ ..cand, why_left: why }
} else {
cand
},
)
## The candidates with the lines a rewrite gave the calls it turned; any
## other keeps the lines it had.
with_lines : List(Candidates.Candidate), Rewritten.Written -> List(Candidates.Candidate)
with_lines = |cands, written|
cands.map(
|cand|
match written.turned_lines.get(cand.node) {
Ok(lines) => { ..cand, from_line: lines.from_line, to_line: lines.to_line }
Err(_) => cand
},
)
## The candidates with no lines: none turned.
without_lines : List(Candidates.Candidate) -> List(Candidates.Candidate)
without_lines = |cands| cands.map(|cand| { ..cand, from_line: 0 })
## One error of a trial on the file, laid on each turned call whose lines
## hold it (one error may fall on two calls), or else on a definition's
## value: the candidates, each hit one left with the error's title, and
## whether any call was hit.
blame : Source.File, Dict(U64, U64), Candidates.CheckError, List(Candidates.Candidate) -> { cands : List(Candidates.Candidate), hit : Bool }
blame = |file, line_of_node, error, cands| {
on_lines = |cand| cand.from_line > 0 and error.line >= cand.from_line and error.line <= cand.to_line
if cands.any(on_lines) {
why = "roc check: ${error.title}"
left = cands.map(
|cand| if on_lines(cand) and cand.why_left == "" {
{ ..cand, why_left: why }
} else {
cand
},
)
{ cands: left, hit: Bool.True }
} else {
blame_definition(file, line_of_node, error, cands)
}
}
}
candidate : U64, Str, Str, U64, Str -> Candidates.Candidate
candidate = |place, module_name, fn, line, why_left| {
node: place,
module_name,
fn,
line,
why_left,
proven: Bool.False,
kind: "",
from_line: 0,
to_line: 0,
undo: Bool.False,
type: "",
}
## A callee `Module.fn` split, when it is one: a capital and letters and
## digits, a `.`, then a small letter, letters, digits and `_`, and an
## optional last `!`.
module_call : Str -> Try({ module_name : Str, fn : Str }, [NoModuleCall])
module_call = |raw| {
parts = raw.split_first(".") ?? { before: "", after: "" }
module_name = parts.before.to_utf8()
fn = parts.after.to_utf8()
fn_body = if (fn.last() ?? 0) == '!' {
fn.drop_last(1)
} else {
fn
}
is_module = match module_name.first() {
Ok(first) => is_capital(first) and module_name.all(is_alphanumeric)
Err(_) => Bool.False
}
is_fn = match fn_body.first() {
Ok(first) => first >= 'a' and first <= 'z' and fn_body.all(|byte| is_alphanumeric(byte) or byte == '_')
Err(_) => Bool.False
}
if is_module and is_fn {
Ok({ module_name: parts.before, fn: parts.after })
} else {
Err(NoModuleCall)
}
}
is_capital : U8 -> Bool
is_capital = |byte| byte >= 'A' and byte <= 'Z'
is_alphanumeric : U8 -> Bool
is_alphanumeric = |byte| is_capital(byte) or (byte >= 'a' and byte <= 'z') or (byte >= '0' and byte <= '9')
## Why the call `module.fn(...)` at node `place` must stay whatever the
## types say, or `""` when it may be tried.
reason_call_stays : Source.File, U64, Str, Str -> Str
reason_call_stays = |file, place, module_name, fn| {
node = Source.node_at(file, place)
parent = if node.parent > 0 {
Ok(Source.node_at(file, node.parent))
} else {
Err(NoParent)
}
is_piped = match parent {
Ok(up) => up.kind == "e-arrow-call" and (up.kids.get(1) ?? 0) == place
Err(_) => Bool.False
}
unspanned = node.kids.drop_first(1).find_first(|arg| !(Source.node_at(file, arg).has_span))
first_place = Source.kid(node, 2)
first = Source.node_at(file, first_place)
if is_piped {
"the right of a `|>`, whose first argument the pipe gives"
} else if unspanned.is_ok() {
kind = Source.node_at(file, unspanned ?? 0).kind
"an argument with no span in the tree (${kind}), whose text cannot be moved"
} else if Literals.is_constant_numeric(file, first_place) {
written = Source.text_of(file, first)
text = if first.kind == "e-tuple" {
written
} else {
"(${written})"
}
"a number literal's type would default as a receiver (`${text}.${fn}()` is no longer a ${module_name})"
} else if Literals.takes_literal_type(file, first_place) {
text = Source.text_of(file, first)
taken = "`${text}` takes its type from a number literal, unannotated"
"a number literal's type would default as a receiver (${taken}, and `${text}.${fn}()` is no longer a ${module_name})"
} else {
""
}
}
## Whether node `place` is below node `top`.
is_below : Source.File, U64, U64 -> Bool
is_below = |file, place, top| {
var $at = Source.node_at(file, place).parent
while $at > 0 {
if $at == top {
return Bool.True
}
$at = Source.node_at(file, $at).parent
}
Bool.False
}
## A `missing method` error on the value of a definition `name = <value>`
## means that value's type never resolved because its only use was a turned
## `name.fn()`: the error is laid on each turned call whose first argument
## is the plain `name` within the definition's statements.
blame_definition : Source.File, Dict(U64, U64), Candidates.CheckError, List(Candidates.Candidate) -> { cands : List(Candidates.Candidate), hit : Bool }
blame_definition = |file, line_of_node, error, cands| {
if error.title != "missing method" {
return { cands, hit: Bool.False }
}
var $cands = cands
var $hit = Bool.False
for definition in file.nodes {
name = Literals.defined_name(file, definition)
if name != "" and (line_of_node.get(Source.kid(definition, 2)) ?? 0) == error.line {
why = "roc check: ${error.title} (on `${name}`'s definition)"
is_blamed = |cand| {
first = Source.kid_node(file, Source.node_at(file, cand.node), 2)
cand.from_line > 0 and first.kind == "e-ident" and first.raw == name and is_below(file, cand.node, definition.parent)
}
if $cands.any(is_blamed) {
$hit = Bool.True
$cands = $cands.map(
|cand| if is_blamed(cand) and cand.why_left == "" {
{ ..cand, why_left: why }
} else {
cand
},
)
}
}
}
{ cands: $cands, hit: $hit }
}
cookbook/roc/rewrite_module_calls_as_method_calls/Judging.roc, 158 lines
## The candidates of a file judged by Roc's own types, as roc-types gives
## them by region: a call whose first argument's type is the module's own is
## proven, one of a concrete other type stays, a symmetric call of peers
## stays a module call, and the rest are left to the trial. With
## `peers=undo`, the peer method calls are found here too.
import Candidates
import Peers
import Source
Judging := [].{
## How many candidates the types judged of each kind, in the order each
## kind was first counted.
KindCounts : List((Str, U64))
## What the types say: each expression's type by `<real path>|<region>`,
## the aliases the files declare, and the symmetric functions.
Typing : { by_region : Dict(Str, Str), aliases : Dict(Str, Str), symmetric : Set(Str) }
## `counts` with one more of `kind`, or `count` more.
counted : Judging.KindCounts, Str, U64 -> Judging.KindCounts
counted = |counts, kind, count|
if counts.any(|(named, _)| named == kind) {
counts.map(
|(named, had)| if named == kind {
(named, had + count)
} else {
(named, had)
},
)
} else {
counts.append((kind, count))
}
## Judges each open candidate of the file, whose real path is
## `real_path`, by its first argument's type, and counts each kind.
by_types : Judging.KindCounts, Source.File, List(Candidates.Candidate), Str, Judging.Typing -> { counts : Judging.KindCounts, cands : List(Candidates.Candidate) }
by_types = |counts, file, cands, real_path, typing| {
var $counts = counts
var $cands = []
for cand in cands {
if cand.why_left == "" {
judged = judge_one(file, cand, real_path, typing)
$counts = Judging.counted($counts, judged.kind, 1)
$cands = $cands.append(judged.cand)
} else {
$cands = $cands.append(cand)
}
}
{ counts: $counts, cands: $cands }
}
## The peer method calls of the file, `calls`: each whose receiver and
## first argument are peers, with a module to call through, as a
## candidate that turns it back (`a.max(b)` to `U64.max(a, b)`), proven,
## as the receiver's type is where the method was found. A call with an
## argument that has no span stays, as a module call's does.
method_peers : Source.File, List(Peers.MethodCall), Str, Judging.Typing -> List(Candidates.Candidate)
method_peers = |file, calls, real_path, typing| {
type_at = |place| typing.by_region.get("${real_path}|${Source.node_at(file, place).region}") ?? ""
calls.join_map(
|call| {
verdict = Peers.verdict(type_at(call.receiver), type_at(call.first), typing.aliases)
if verdict.peers {
why_left = if call.spanned {
""
} else {
"an argument with no span in the tree, whose text cannot be moved"
}
line = Source.line_of_offset(file, Source.node_at(file, call.node).from)
[Candidates.undoing({ place: call.node, module_name: verdict.module_name, fn: call.fn, line, why_left, type: verdict.type })]
} else {
[]
}
},
)
}
}
## A type's head: a type variable (`a`, `_a`, `a where [...]`), or its name
## (`List` of `List(U8)`, `Access.Viewer` of `Access.Viewer(Topic.At)`), a
## function's (an arrow outside every bracket) `function`, `{...}`'s
## `record`, `[...]`'s `tag union` and `(a, b)`'s `tuple`.
Head : [Variable, Named(Str)]
type_head : Str -> Head
type_head = |type_text| {
bytes = type_text.to_utf8()
first = bytes.first() ?? 0
if Peers.has_top_arrow(bytes) {
Named("function")
} else if first == '{' {
Named("record")
} else if first == '[' {
Named("tag union")
} else if first == '(' {
Named("tuple")
} else if first < 'A' or first > 'Z' {
Variable
} else {
length = bytes.find_first_index(|byte| !(is_head_byte(byte))) ?? bytes.len()
Named(Str.from_utf8_lossy(bytes.take_first(length)))
}
}
is_head_byte : U8 -> Bool
is_head_byte = |byte|
(byte >= 'A' and byte <= 'Z') or (byte >= 'a' and byte <= 'z') or (byte >= '0' and byte <= '9') or byte == '_' or byte == '.'
## `word` after its indefinite article: "an" before a vowel sound. A U
## usually sounds like "you" (U8, User), so it takes "an" only in `Un...`
## (Unvalidated).
with_article : Str -> Str
with_article = |word| {
first = word.to_utf8().first() ?? 0
vowel = first == 'A' or first == 'E' or first == 'I' or first == 'O' or first == 'a' or first == 'e' or first == 'i' or first == 'o'
if vowel or word.starts_with("Un") or word.starts_with("un") {
"an ${word}"
} else {
"a ${word}"
}
}
## One open candidate judged: the kind it is counted as, and the candidate
## with what the types say. A first argument whose type has the module's own
## name, bare, proves the call: roc-types writes a type by the name it is
## declared with, so a qualified head never does, even one whose last
## segment names the module (`Type.Game` is Type's, not Game's).
judge_one : Source.File, Candidates.Candidate, Str, Judging.Typing -> { kind : Str, cand : Candidates.Candidate }
judge_one = |file, cand, real_path, typing| {
call = Source.node_at(file, cand.node)
type_at = |number| typing.by_region.get("${real_path}|${Source.kid_node(file, call, number).region}")
peers =
if call.kids.len() >= 3 and typing.symmetric.contains(cand.fn) {
Peers.verdict(type_at(2) ?? "", type_at(3) ?? "", typing.aliases)
} else {
{ peers: Bool.False, type: "", module_name: "" }
}
if peers.peers {
why = "peers: `${cand.fn}` is symmetric and both arguments are ${peers.module_name}s, so neither is the subject"
{ kind: "peers", cand: { ..cand, why_left: why } }
} else {
match type_at(2) {
Err(_) => { kind: "no type", cand: { ..cand, kind: "no type" } }
Ok(type_text) =>
match type_head(type_text) {
Variable => { kind: "a type variable", cand: { ..cand, kind: "a type variable" } }
Named(head) =>
if head == cand.module_name {
{ kind: "the module's type", cand: { ..cand, proven: Bool.True } }
} else {
why = "the first argument is ${with_article(head)}, not ${with_article(cand.module_name)}"
{ kind: "another type", cand: { ..cand, why_left: why } }
}
}
}
}
}
cookbook/roc/rewrite_module_calls_as_method_calls/Peers.roc, 267 lines
## Which calls are peer calls (peer_calls.shale). A method call names a
## subject, so a symmetric function, one where no argument is the subject, is
## called through its module: `U64.max(a, b)`, `Str.concat(a, b)`,
## `List.map2(xs, ys, f)`. The symmetric functions are a list of names,
## cookbook/roc/symmetric_functions.txt, and a call of one is a peer call
## when its first two arguments' types have one head, as roc-types writes
## them at the call with each alias read through to what it names (a `Hue :
## U32` is a `U32`). A function off the list (`starts_with`, a unit's `plus`)
## keeps its method call, whatever its arguments.
import Source
import lib.Text
Peers := [].{
## Whether two arguments are peers, values of one type: `type` is the
## first's type with its aliases read through, `module` that type's head.
Verdict : { peers : Bool, type : Str, module_name : Str }
## A symmetric method call that passes an argument, `x.max(y)`: its node,
## its receiver's node, its first argument's, the function, and whether
## every argument has a span, so its text can be moved.
MethodCall : { node : U64, receiver : U64, first : U64, fn : Str, spanned : Bool }
## Every alias the files declare (`Hue : U32`, never `:=` or `::`), by the
## name roc-types gives it, to the text of the type it names. An alias
## with parameters is left out: reading it through would need its
## arguments bound. Where two files declare one name, the later file by
## path wins.
declared_aliases : List(Source.File) -> Dict(Str, Str)
declared_aliases = |files| {
var $out = Dict.empty()
for file in files.sort_with(|first, second| Text.byte_order(first.path, second.path)) {
for (node, place) in file.nodes.map_with_index(|node, index| (node, index + 1)) {
if node.kind == "s-type-decl" and node.kids.len() == 2 {
header = Source.kid_node(file, node, 1)
target = Source.kid_node(file, node, 2)
if is_bare_header(file, header) and header.has_span and target.has_span {
between = Text.trim(Source.text_between(file, header.to, target.from))
if between == ":" {
$out = $out.insert(declared_name(file, place), Source.text_of(file, target))
}
}
}
}
}
$out
}
## Whether two arguments, of the types `first` and `second` as roc-types
## gives them (`""` where it gives none), are peers: both types, their
## aliases read through, have one head to call through (`List(U64)` and
## `List(Str)` are peers to `map2`).
verdict : Str, Str, Dict(Str, Str) -> Peers.Verdict
verdict = |first, second, aliases|
if first == "" or second == "" {
{ peers: Bool.False, type: "", module_name: "" }
} else {
resolved = resolved_type(first, aliases, 0)
module_name = Peers.module_of(resolved)
peers = module_name != "" and module_name == Peers.module_of(resolved_type(second, aliases, 0))
{ peers, type: resolved, module_name }
}
## The module a value of the type `type_text` takes its methods from, the
## type's head (`List` for `List(U8)`, `Shelf.Book`), or `""` for a type
## with none to call through: a type variable, a record, a tuple, a tag
## union or a function.
module_of : Str -> Str
module_of = |type_text| {
bytes = type_text.to_utf8()
if Peers.has_top_arrow(bytes) {
""
} else {
length = type_name_length(bytes, 0)
Str.from_utf8_lossy(bytes.take_first(length))
}
}
## Whether an arrow, `->` or `=>`, stands outside every bracket.
has_top_arrow : List(U8) -> Bool
has_top_arrow = |bytes| {
$depth : I64
var $depth = 0
var $place = 0
while $place + 1 < bytes.len() {
byte = bytes.get($place) ?? 0
if byte == '(' or byte == '[' or byte == '{' {
$depth = $depth + 1
}
if byte == ')' or byte == ']' or byte == '}' {
$depth = $depth - 1
}
next = bytes.get($place + 1) ?? 0
if $depth == 0 and next == '>' and (byte == '-' or byte == '=') {
return Bool.True
}
$place = $place + 1
}
Bool.False
}
## The symmetric functions in `text`, symmetric_functions.txt: a set of
## names, one a line, `#` lines its comments; or why a line is no name.
symmetric_table : Str -> Try(Set(Str), Str)
symmetric_table = |text| {
var $names = Set.empty()
for text_line in Text.lines(text) {
word = Text.trim(text_line)
if word != "" and !(word.starts_with("#")) {
if !(is_function_name(word.to_utf8())) {
return Err("peer_calls: symmetric_functions.txt: `${word}` is not a function's name")
}
$names = $names.insert(word)
}
}
Ok($names)
}
## The method calls in the file of a function in `symmetric` that pass an
## argument.
method_calls : Source.File, Set(Str) -> List(Peers.MethodCall)
method_calls = |file, symmetric| {
var $calls = []
for (node, place) in file.nodes.map_with_index(|node, index| (node, index + 1)) {
if node.kind == "e-method-call" and node.kids.len() == 2 {
receiver = Source.kid_node(file, node, 1)
if receiver.kind == "receiver" and receiver.kids.len() == 1 {
args = Source.kid_node(file, node, 2)
fn = if node.method.starts_with(".") {
Str.from_utf8_lossy(node.method.to_utf8().drop_first(1))
} else {
node.method
}
if args.kind == "args" and !(args.kids.is_empty()) and symmetric.contains(fn) {
value = Source.kid(receiver, 1)
spanned = Source.node_at(file, value).has_span and args.kids.all(|arg| Source.node_at(file, arg).has_span)
call = { node: place, receiver: value, first: args.kids.first() ?? 0, fn, spanned }
$calls = $calls.append(call)
}
}
}
}
$calls
}
}
## Whether a type declaration's header has no parameters.
is_bare_header : Source.File, Source.Node -> Bool
is_bare_header = |file, header|
header.kind == "header" and (header.kids.is_empty() or Source.kid_node(file, header, 1).kids.is_empty())
## The name roc-types gives the type declared at node `place`: the names of
## the declarations around it and its own, joined by dots (`Peers.Hue` for a
## `Hue` declared in `Peers`'s block).
declared_name : Source.File, U64 -> Str
declared_name = |file, place| {
var $names = []
var $at = place
while $at > 0 {
node = Source.node_at(file, $at)
if node.kind == "s-type-decl" {
$names = $names.prepend(Source.kid_node(file, node, 1).name)
}
$at = node.parent
}
Str.join_with($names, ".")
}
## The type `type_text` with every alias in it read through, its runs of
## space made one, up to 8 aliases deep.
resolved_type : Str, Dict(Str, Str), U64 -> Str
resolved_type = |type_text, aliases, depth| {
bytes = type_text.to_utf8()
var $out = []
var $changed = Bool.False
var $place = 0
while $place < bytes.len() {
length = type_name_length(bytes, $place)
if length == 0 {
$out = $out.append(bytes.get($place) ?? 0)
$place = $place + 1
} else {
name = Str.from_utf8_lossy(bytes.sublist({ start: $place, len: length }))
match aliases.get(name) {
Ok(named) => {
$out = $out.concat(named.to_utf8())
$changed = Bool.True
}
Err(_) => {
$out = $out.concat(name.to_utf8())
}
}
$place = $place + length
}
}
spaced = Str.from_utf8_lossy(one_space(Text.trim(Str.from_utf8_lossy($out)).to_utf8()))
if $changed and depth < 8 {
resolved_type(spaced, aliases, depth + 1)
} else {
spaced
}
}
## The bytes with each run of white space made one space.
one_space : List(U8) -> List(U8)
one_space = |bytes| {
var $out = []
var $in_space = Bool.False
for byte in bytes {
if is_space(byte) {
if !($in_space) {
$out = $out.append(' ')
}
$in_space = Bool.True
} else {
$out = $out.append(byte)
$in_space = Bool.False
}
}
$out
}
is_space : U8 -> Bool
is_space = |byte| byte == ' ' or byte == '\t' or byte == '\n' or byte == '\r' or byte == 11 or byte == 12
## The length of the type name at byte `start`, as roc-types writes one
## (`U64`, `List`, `Shelf.Book`): a capital, then letters, digits and `_`,
## and again after each `.` that a capital follows; 0 where none starts.
type_name_length : List(U8), U64 -> U64
type_name_length = |bytes, start| {
if !(Text.is_capital(bytes.get(start) ?? 0)) {
return 0
}
var $end = word_end(bytes, start + 1)
while (bytes.get($end) ?? 0) == '.' and Text.is_capital(bytes.get($end + 1) ?? 0) {
$end = word_end(bytes, $end + 2)
}
$end - start
}
## The place past the letters, digits and `_` from `start` on.
word_end : List(U8), U64 -> U64
word_end = |bytes, start| {
var $end = start
while is_word_byte(bytes.get($end) ?? 0) {
$end = $end + 1
}
$end
}
is_word_byte : U8 -> Bool
is_word_byte = |byte| Text.is_capital(byte) or Text.is_small_letter(byte) or Text.is_digit(byte) or byte == '_'
## Whether the bytes are a function's name: a small letter, then small
## letters, digits and `_`, and an optional last `!`.
is_function_name : List(U8) -> Bool
is_function_name = |bytes| {
body = if (bytes.last() ?? 0) == '!' {
bytes.drop_last(1)
} else {
bytes
}
match body.first() {
Ok(first) => Text.is_small_letter(first) and body.all(|byte| Text.is_small_letter(byte) or Text.is_digit(byte) or byte == '_')
Err(_) => Bool.False
}
}
cookbook/roc/rewrite_module_calls_as_method_calls/Source.roc, 158 lines
## A file as the rewrite reads it: Roc's tree of it, each node's span as byte
## offsets into its text, and where each line starts, so a byte's line is
## found and a span's text cut out.
import lib.Tree
Source := [].{
## A node of the file's tree: its kind and the attributes the rewrite
## reads (`""` where the tree gives none), its span as byte offsets
## (`from` its first byte, counted from 1, `to` one past its last, both 0
## and `has_span` false for a node with no position), its kids and
## parent as places counted from 1 (the root's parent 0), and its region
## as the compiler writes it, `line:col:end_line:end_col`, by which its
## type is found.
Node : {
kind : Str,
raw : Str,
name : Str,
field : Str,
method : Str,
from : U64,
to : U64,
has_span : Bool,
kids : List(U64),
parent : U64,
region : Str,
}
## A file: its path, its text (and its bytes), its nodes, and the byte at
## which each line starts, counted from 1, with one more past the end.
File : {
path : Str,
text : Str,
bytes : List(U8),
nodes : List(Source.Node),
starts : List(U64),
}
## The file at `path`, of text `text`, as Roc's tree of it reads.
of : Str, Str, List(Tree.Node) -> Source.File
of = |path, text, tree_nodes| {
bytes = text.to_utf8()
starts = line_starts(bytes)
nodes = tree_nodes.map(|tree_node| node_of(tree_node, starts))
{ path, text, bytes, nodes, starts }
}
## The node at a place counted from 1.
node_at : Source.File, U64 -> Source.Node
node_at = |file, place|
match file.nodes.get(place - 1) {
Ok(node) => node
Err(_) => crash "Source.node_at: ${file.path} has no node ${place.to_str()}"
}
## The place of a node's kid, the kids counted from 1.
kid : Source.Node, U64 -> U64
kid = |node, number|
match node.kids.get(number - 1) {
Ok(place) => place
Err(_) => crash "Source.kid: a ${node.kind} with no kid ${number.to_str()}"
}
## The node that is a node's kid, the kids counted from 1.
kid_node : Source.File, Source.Node, U64 -> Source.Node
kid_node = |file, node, number| Source.node_at(file, Source.kid(node, number))
## The line the byte at `offset` is on: the last line starting at or
## before it, and line 1 for an offset before the first.
line_of_offset : Source.File, U64 -> U64
line_of_offset = |file, offset| {
var $low = 0
var $high = file.starts.len()
while $low < $high {
middle = ($low + $high) // 2
if (file.starts.get(middle) ?? 0) <= offset {
$low = middle + 1
} else {
$high = middle
}
}
if $low == 0 {
1
} else {
$low
}
}
## The bytes from offset `from` up to, not including, `to`; none when
## `to` is not past `from`.
bytes_between : Source.File, U64, U64 -> List(U8)
bytes_between = |file, from, to|
if to > from and from > 0 {
file.bytes.sublist({ start: from - 1, len: to - from })
} else {
[]
}
## The text from offset `from` up to, not including, `to`.
text_between : Source.File, U64, U64 -> Str
text_between = |file, from, to| Str.from_utf8_lossy(Source.bytes_between(file, from, to))
## A node's text.
text_of : Source.File, Source.Node -> Str
text_of = |file, node| Source.text_between(file, node.from, node.to)
}
## The byte at which each line starts, counted from 1, and one more past the
## last line's end, as method_text.shale's `line_starts` counts them.
line_starts : List(U8) -> List(U64)
line_starts = |bytes| {
var $starts = [1]
$at : U64
var $at = 0
for byte in bytes {
$at = $at + 1
if byte == '\n' {
$starts = $starts.append($at + 1)
}
}
$starts.append(bytes.len() + 2)
}
## A node of Roc's tree with its span made byte offsets.
node_of : Tree.Node, List(U64) -> Source.Node
node_of = |tree_node, starts| {
start_of = |line|
match starts.get(line - 1) {
Ok(start) => start
Err(_) => crash "Source: a node on line ${line.to_str()}, past the file's end"
}
has_span = tree_node.line != 0
from = if has_span {
start_of(tree_node.line) + tree_node.column - 1
} else {
0
}
to = if has_span {
start_of(tree_node.end_line) + tree_node.end_column - 1
} else {
0
}
starts_at = "${tree_node.line.to_str()}:${tree_node.column.to_str()}"
ends_at = "${tree_node.end_line.to_str()}:${tree_node.end_column.to_str()}"
{
kind: tree_node.kind,
raw: Tree.attribute(tree_node, "raw"),
name: Tree.attribute(tree_node, "name"),
field: Tree.attribute(tree_node, "field"),
method: Tree.attribute(tree_node, "method"),
from,
to,
has_span,
kids: tree_node.kids,
parent: tree_node.parent,
region: "${starts_at}:${ends_at}",
}
}
cookbook/roc/rewrite_module_calls_as_method_calls/Tally.roc, 69 lines
## What a run has done so far: the programs it started, its checks, the
## files the confirm kept, the rewrites that passed (for what they leave the
## sweep), the kinds of type the types found, and the roots they were read
## of.
import Candidates
import Judging
import Rewritten
import Source
Tally := [].{
## A rewrite that passed: the text before and after it, before any `roc
## fmt`, and the lines after it where a turned call that spanned several
## lines now sits on one.
Rewrite : { before : Str, after : Str, joined : List(U64) }
## The run's sheet.
Sheet : {
programs_used : U64,
rounds : U64,
confirms : U64,
confirmed : Dict(Str, U64),
rewrites : Dict(Str, Tally.Rewrite),
kind_counts : Judging.KindCounts,
typed_roots : List(Str),
}
## Nothing done yet.
empty : Tally.Sheet
empty = {
programs_used: 0,
rounds: 0,
confirms: 0,
confirmed: Dict.empty(),
rewrites: Dict.empty(),
kind_counts: [],
typed_roots: [],
}
## One program more.
ran : Tally.Sheet -> Tally.Sheet
ran = |tally| { ..tally, programs_used: tally.programs_used + 1 }
## The rewrite of the file with the candidates `turned` turned, by a
## passing trial or confirm, or under `trials=0` the proven calls: noted
## when it changes the text.
noted : Tally.Sheet, Source.File, List(Candidates.Candidate) -> Tally.Sheet
noted = |tally, file, turned| {
turning = Candidates.turning(turned)
written = Rewritten.written(file, turning)
var $joined = []
for cand in turned {
if turning.contains(cand.node) {
lines = written.turned_lines.get(cand.node) ?? { from_line: cand.from_line, to_line: cand.to_line }
node = Source.node_at(file, cand.node)
spanned_lines = Source.line_of_offset(file, node.from) < Source.line_of_offset(file, node.to - 1)
if lines.from_line == lines.to_line and spanned_lines {
$joined = $joined.append(lines.from_line)
}
}
}
if written.text == file.text {
tally
} else {
rewrite = { before: file.text, after: written.text, joined: $joined }
{ ..tally, rewrites: tally.rewrites.insert(file.path, rewrite) }
}
}
}
cookbook/roc/rewrite_module_calls_as_method_calls/Trial.roc, 181 lines
## The compiler's judgement of a rewrite: one file's open calls tried round
## by round until `roc check` passes (the trial), and the files whose calls
## the types all prove written at once and checked together (the confirm).
## A file ends as it began unless `apply` and its rewrite passed.
import pf.Shale
import Candidates
import Compiler
import Rewritten
import Source
import Tally
import lib.Text
Trial := [].{
## The Roc that judges, and whether a rewrite that passes is kept.
Judge : { roc : Str, apply : Bool }
## A file the confirm writes: its path, its tree and its candidates.
Proven : { path : Str, file : Source.File, cands : List(Candidates.Candidate) }
## Tries one file's open candidates, round by round, until `roc check` on
## `root` passes or nothing is left to try, then runs the test, which
## must say `baseline`. Answers how many calls were turned, and the
## candidates, each that stays with its `why_left`.
try_file! : Trial.Judge, Tally.Sheet, Source.File, List(Candidates.Candidate), Str, Str => { tally : Tally.Sheet, cands : List(Candidates.Candidate), turned : U64 }
try_file! = |judge, tally, file, cands, root, baseline| {
var $tally = tally
fmt_was_clean = if judge.apply {
$tally = Tally.ran($tally)
Compiler.is_fmt_clean!(judge.roc, file.path)
} else {
Bool.False
}
var $cands = cands
var $round = 0
while $round < max_rounds {
$round = $round + 1
open = Candidates.open_count($cands)
if open == 0 {
Shale.write!(file.path, file.text)
return { tally: $tally, cands: $cands, turned: 0 }
}
written = Rewritten.written(file, Candidates.turning($cands))
$cands = Candidates.with_lines($cands, written)
Shale.write!(file.path, written.text)
$tally = Tally.ran({ ..$tally, rounds: $tally.rounds + 1 })
checked = Compiler.check!(judge.roc, root)
if checked.ok {
if fmt_was_clean {
$tally = Tally.ran($tally)
Compiler.fmt!(judge.roc, file.path)
}
$tally = Tally.ran($tally)
summary = Compiler.test_summary!(judge.roc, root)
if summary != baseline {
why = "roc test changed: ${summary}, was ${baseline}; the file is put back"
Shale.write!(file.path, file.text)
return { tally: $tally, cands: Candidates.leave_open($cands, why), turned: 0 }
}
$tally = Tally.noted($tally, file, $cands)
if !(judge.apply) {
Shale.write!(file.path, file.text)
}
return { tally: $tally, cands: $cands, turned: open }
}
judged = judge_errors(file, written.line_of_node, checked.errors, $cands)
$cands = judged.cands
if !(judged.refused) and (judged.stray != NoStray or checked.errors.is_empty()) {
why = match judged.stray {
Stray(stray) => "roc check: ${stray.title} at ${stray.file}:${stray.line.to_str()}, on no rewritten call"
NoStray => "roc check failed, naming no line: ${Compiler.first_line_said(checked.out)}"
}
Shale.write!(file.path, file.text)
return { tally: $tally, cands: Candidates.leave_open($cands, "${why}; the file is put back"), turned: 0 }
}
$cands = Candidates.without_lines($cands)
}
Shale.write!(file.path, file.text)
why = "still failing after ${max_rounds.to_str()} rounds; the file is put back"
{ tally: $tally, cands: Candidates.leave_open($cands, why), turned: 0 }
}
## Confirms the files whose open calls are all proven: written with all
## their calls turned, at once, and judged together by one `roc check` on
## `root` and one `roc test`. When the check fails, the files its errors
## name are set aside and the rest written again, up to `max_rounds`
## checks; an error in no file of theirs (a caller's), a failure naming no
## line, or a changed test sets them all aside. `confirmed` holds each
## kept file's count of turned calls, and 0 for a file set aside, which
## the trial then judges alone.
confirm! : Trial.Judge, Tally.Sheet, Str, List(Trial.Proven), Str => Tally.Sheet
confirm! = |judge, tally, root, files, baseline| {
var $tally = tally
var $remaining = []
for proven in files {
$tally = { ..$tally, confirmed: $tally.confirmed.insert(proven.path, 0) }
fmt_was_clean = if judge.apply {
$tally = Tally.ran($tally)
Compiler.is_fmt_clean!(judge.roc, proven.path)
} else {
Bool.False
}
$remaining = $remaining.append({ proven, fmt_was_clean, turned: Candidates.open_count(proven.cands) })
}
var $round = 0
while $round < max_rounds {
$round = $round + 1
if $remaining.is_empty() {
return $tally
}
for one in $remaining {
Shale.write!(one.proven.path, Rewritten.written(one.proven.file, Candidates.turning(one.proven.cands)).text)
}
$tally = Tally.ran({ ..$tally, confirms: $tally.confirms + 1 })
checked = Compiler.check!(judge.roc, root)
if checked.ok {
for one in $remaining {
if one.fmt_was_clean {
$tally = Tally.ran($tally)
Compiler.fmt!(judge.roc, one.proven.path)
}
}
$tally = Tally.ran($tally)
passed = Compiler.test_summary!(judge.roc, root) == baseline
for one in $remaining {
if passed {
$tally = Tally.noted($tally, one.proven.file, one.proven.cands)
}
if !(passed) or !(judge.apply) {
Shale.write!(one.proven.path, one.proven.file.text)
}
if passed {
$tally = { ..$tally, confirmed: $tally.confirmed.insert(one.proven.path, one.turned) }
}
}
return $tally
}
for one in $remaining {
Shale.write!(one.proven.path, one.proven.file.text)
}
named = |one| checked.errors.any(|error| Text.basename(one.proven.path) == error.file)
names_another = |error| !($remaining.any(|one| Text.basename(one.proven.path) == error.file))
if checked.errors.is_empty() or checked.errors.any(names_another) {
return $tally
}
$remaining = $remaining.drop_if(named)
}
$tally
}
## How many checks a file may take: each round leaves out the calls the
## compiler refused, and the next may find more that their errors hid.
max_rounds : U64
max_rounds = 6
}
## A failed round's errors laid on the file's turned calls. An error on no
## turned call is a stray, and counts only in a round that refused no call:
## the compiler may complain where a refused call's value is used, and the
## next round, without that call, shows whether the stray was its.
judge_errors : Source.File, Dict(U64, U64), List(Candidates.CheckError), List(Candidates.Candidate) -> { cands : List(Candidates.Candidate), refused : Bool, stray : [Stray(Candidates.CheckError), NoStray] }
judge_errors = |file, line_of_node, errors, cands| {
var $cands = cands
var $refused = Bool.False
var $stray = NoStray
own = Text.basename(file.path)
for error in errors {
if error.file == own {
blamed = Candidates.blame(file, line_of_node, error, $cands)
$cands = blamed.cands
if blamed.hit {
$refused = Bool.True
} else if $stray == NoStray {
$stray = Stray(error)
}
} else if $stray == NoStray {
$stray = Stray(error)
}
}
{ cands: $cands, refused: $refused, stray: $stray }
}
cookbook/roc/rewrite_module_calls_as_method_calls/Types.roc, 132 lines
## Every expression's type in an app, from roc-types (Roc's own checker,
## https://github.com/showell/roc-types) run on the root with its pin held
## to the tree's Roc, or read from a file a gate kept, and read by
## cookbook/roc/lib/'s RocTypes. Each refusal is worded as the Shale
## original's.
import pf.Shale
import Compiler
import lib.RocTypes
import lib.Text
Types := [].{
## An app's types: each expression's type keyed by `<real path>|<region>`
## (where several share a region, the first roc-types gives, the
## outermost), and the real paths of the modules it reaches.
Typed : { by_region : Dict(Str, Str), modules : Set(Str) }
## The types of the app `root`, from roc-types run with the Roc at `roc`,
## or from `types_from` when it names a file (its records kept for the
## modules in `only` alone). roc-types' warnings are printed.
of_root! : { root : Str, roc : Str, types_from : Str, only : Set(Str) } => Types.Typed
of_root! = |asked| {
got = if asked.types_from == "" {
from_run!(asked.root, asked.roc)
} else {
from_file!(asked.types_from, asked.root, asked.roc, asked.only)
}
var $by_region = Dict.empty()
for path in got.paths {
for record in got.records.get(path) ?? [] {
key = "${path}|${record.span}"
if record.kind == "expr" and !($by_region.contains(key)) {
$by_region = $by_region.insert(key, record.written)
}
}
}
for warning in got.warnings {
Shale.print!("rewrite_module_calls_as_method_calls: roc-types ${asked.root}: ${warning}")
}
{ by_region: $by_region, modules: Set.from_list(got.paths) }
}
## The checker for the compiler at `roc`: the one installed for its pin,
## `tools:roc-types-<pin>/bin/roc-types`, as compilers sit side by side,
## or else the default.
checker_for! : Str => Str
checker_for! = |roc|
match Shale.re_find!(roc, "/roc-([^/]+)/roc$") {
Found(matched) => {
own = "tools:roc-types-${matched.groups.first() ?? ""}/bin/roc-types"
if Shale.exists!(own) {
own
} else {
default_checker
}
}
NoMatch => default_checker
}
## The default checker, which the self-test needs installed.
default_checker : Str
default_checker = "tools:roc-types/bin/roc-types"
}
## roc-types run on `root`: a stop when it is missing, of another format,
## built for another Roc than `roc`, or refusing the app.
from_run! : Str, Str => RocTypes.Modules
from_run! = |root, roc| {
exe = Types.checker_for!(roc)
if !(Shale.exists!(exe)) {
Shale.fail!("`roc_types`: no ${exe}: ${RocTypes.install_hint}")
}
ran = Shale.run!({
argv: [Shale.real!(exe), Shale.real!(root)],
keep: Whole(64000000),
timeout_ms: 300000,
want: "",
})
modules_said!(Text.lines(ran.out), ran.code, root, roc)
}
## The types roc-types wrote of `root` to the file `path`, read with no
## program run: the records of the modules in `only` alone, every module's
## `== ` line kept, so the modules reached stay whole.
from_file! : Str, Str, Str, Set(Str) => RocTypes.Modules
from_file! = |path, root, roc, only| {
if !(Shale.exists!(path)) {
Shale.fail!("`roc_types`: no ${path}, the types of ${root} to read")
}
var $kept = []
var $keeping = Bool.True
for said in Text.lines(Compiler.read_text!(path)) {
if said.starts_with("== ") {
$keeping = only.contains(said.drop_prefix("== "))
$kept = $kept.append(said)
} else if $keeping or $kept.is_empty() {
$kept = $kept.append(said)
}
}
modules_said!($kept, 0, root, roc)
}
## roc-types' lines read, its pin held to `roc` first, since the errors (or
## the silence) of a checker from another Roc say nothing about this tree,
## then its exit `code`.
modules_said! : List(Str), I64, Str, Str => RocTypes.Modules
modules_said! = |output_lines, code, root, roc| {
pin = match RocTypes.pin_of(output_lines, root) {
Ok(found) => found
Err(why) => Compiler.stop!(why)
}
own = "tools:roc-${pin}/roc"
if !(Shale.exists!(own)) or Shale.real!(own) != roc {
another = "its types would be another compiler's. Install the roc-types of the tree's pin (https://github.com/showell/roc-types), or move the tree to ${pin}"
Shale.fail!("`roc_types`: roc-types reads Roc ${pin}, and ${root}'s tree is built with ${roc}: ${another}")
}
if code != 0 {
ended = if code < 0 {
"did not exit"
} else {
"exited ${code.to_str()}"
}
Shale.fail!("`roc_types`: roc-types ${root} ${ended}, what it said:\n${RocTypes.said_on_failure(output_lines)}")
}
match RocTypes.modules_of(output_lines) {
Ok(modules) => modules
Err(why) => {
Shale.fail!(why)
{ paths: [], records: Dict.empty(), warnings: [] }
}
}
}
cookbook/roc/rewrite_module_calls_as_method_calls/Plants.roc, 145 lines
## What each plant in cookbook/roc/plants/rewrite_module_calls_as_method_calls/ must come to
## (rewrite_module_calls_as_method_calls.shale's `EXPECT`), and the plants that serve only
## as roots for others.
Plants := [].{
## A plant's expectation: how many calls it must leave (`left`), a
## reason one of them must give (`why`), the root it is judged on
## (`root`, the plant itself when `""`), whether it runs with the types,
## and how many confirms and trial rounds it takes. A plant with `file`
## judges that plant's file under its own name, one with `with` reads a
## second plant beside it, as a glob of two files would, and one with
## `stop` must stop its run with that text. A `count` plant runs
## `trials=0` and must count `proven` and `unsettled` calls.
Expect : {
name : Str,
file : Str,
beside : Str,
left : U64,
why : Str,
root : Str,
types : Bool,
confirms : U64,
rounds : [Rounds(U64), AnyRounds],
no_types_run : Bool,
unreached : U64,
stop : Str,
tree_pin : Str,
count : Bool,
proven : U64,
unsettled : U64,
types_from : Bool,
peers : [Peers(U64), AnyPeers],
undo : Bool,
made_unused : U64,
made_long : U64,
made_says : Str,
}
## Every plant's expectation, in the table's order.
table : List(Plants.Expect)
table = [
{ ..plain("Rewrite"), left: 0 },
{ ..plain("Chained"), left: 0 },
{ ..plain("FunctionValue"), left: 0 },
{ ..plain("Pipe"), left: 1, why: "the right of a `|>`" },
{ ..plain("Own"), left: 0 },
{ ..plain("OtherType"), left: 1, why: "roc check: missing method" },
{ ..plain("Decode"), left: 1, why: "on no rewritten call; the file is put back", root: "Breaks" },
{ ..plain("Breaks"), left: 1, why: "roc check: missing method" },
{ ..plain("Matched"), left: 1, why: "an argument with no span" },
{ ..plain("Literal"), left: 8, why: "a number literal's type would default as a receiver" },
{ ..plain("Ref"), left: 0 },
{ ..plain("Scrutinee"), left: 1, why: "roc check: missing method (on `text`'s definition)" },
{ ..plain("Knock"), left: 2, why: "roc check: missing method" },
{ ..plain("Header"), left: 0 },
{ ..typed("Typed", "TypedApp", 1, 0), left: 1, why: "the first argument is a List, not a Str" },
{ ..typed("Proven", "TypedApp", 1, 0), left: 0 },
{ ..typed("NoCalls", "TypedApp", 0, 0), left: 0, no_types_run: Bool.True },
{ ..typed("ProvenFails", "TypedApp", 1, 2), left: 2, why: "roc check: type mismatch" },
{ ..plain("Unrooted"), types: Bool.True, stop: "the types need root=" },
{ ..plain("NotApp"), types: Bool.True, root: "Proven", stop: "is not an app" },
{ ..plain("Pin"), types: Bool.True, root: "TypedApp", stop: "roc-types reads Roc 0.1.0_RC1", tree_pin: "nightly-2026-10-29-a0a9fc2" },
{ ..typed("Second", "TypedApp,SecondApp", 1, 0), left: 0 },
# A file no root reaches is listed, and the run goes on to the next.
{ ..typed("Unreached", "TypedApp,SecondApp", 1, 0), file: "Proven", beside: "Unreached", left: 0, unreached: 1 },
{ ..typed("Beside", "TypedApp", 1, 0), file: "Proven", beside: "NoCalls", left: 0 },
# A qualified type whose last segment names the module proves nothing,
# and the compiler agrees: the trial refuses both calls.
{ ..typed("LastSegment", "TypedApp", 0, 0), left: 2, why: "the first argument is a Shelf.Book, not a Book" },
{ ..plain("LastSegmentTried"), file: "LastSegment", left: 2, why: "roc check: missing method" },
# A package's type module, imported as `pk.Meter`, proves its calls.
{ ..typed("Packaged", "PkgApp", 1, 0), left: 0 },
# `trials=0`: the types alone count, and the plant comes out as it was.
# ProvenFails' three calls are all proven, where the trial leaves two:
# the count's cost, held here.
{ ..counted("TypedCount", "Typed", 1), left: 1, why: "the first argument is a List, not a Str" },
{ ..counted("ProvenFailsCount", "ProvenFails", 3), left: 0 },
{ ..counted("ProvenFrom", "Proven", 2), types_from: Bool.True, left: 0 },
{ ..counted("LastSegmentCount", "LastSegment", 0), left: 2, why: "the first argument is a Shelf.Shelf, not a Shelf" },
{ ..counted("PackagedCount", "Packaged", 1), root: "PkgApp", left: 0 },
# A symmetric function's peer calls stay module calls; `peers=undo`
# turns its peer method calls back; every other function's calls turn
# or stay as ever. Each `count` plant's `left` counts its listed lines,
# the peer_receiver findings among them. Line 24 of each is the alias's.
{ ..typed("Peers", "TypedApp", 1, 0), left: 6, why: "Peers.roc:24: U64.max: peers: `max` is symmetric and both arguments are U64s, so neither is the subject", peers: Peers(0) },
{ ..counted("PeersCount", "Peers", 5), left: 6, peers: Peers(0), why: "Peers.roc:24: U64.max: peers: `max` is symmetric" },
{ ..typed("PeerMethods", "TypedApp", 1, 0), undo: Bool.True, left: 0, peers: Peers(0) },
# What a rewrite leaves for the sweep, reported and not fixed: an import
# it made unused, and a line it pushed past 100 columns; KeptImport is
# MadeUnused's near miss, an import a type still names.
{ ..plain("MadeUnused"), left: 0, made_unused: 1, made_says: "MadeUnused.roc:4: made_unused_import: `Ref` was used only by the calls the rewrite turned" },
{ ..plain("KeptImport"), left: 0 },
{ ..plain("MadeLong"), left: 0, made_long: 1, made_says: "MadeLong.roc:11: made_long_line" },
{ ..counted("PeerMethodsCount", "PeerMethods", 0), left: 6, peers: Peers(6), why: "PeerMethods.roc:24: peer_receiver: `.max` is symmetric and its receiver and first argument are both U64s, so neither is the subject: U64.max(...)" },
# A rewrite `roc check` passes and `roc test` refuses puts the file back;
# a root that fails `roc check` before any rewrite stops the run; a file
# `roc fmt` would change is not formatted after its rewrite.
{ ..plain("TestChanged"), left: 2, why: "roc test changed: " },
{ ..plain("BadBase"), stop: "fails before any rewrite: fix it first" },
{ ..plain("Unformatted"), left: 0 },
{ ..plain("Loud"), left: 0 },
]
## The plants that hold no call and serve only as roots for other
## plants: roc-types reads an app, and an app names its platform.
root_plants : List(Str)
root_plants = ["TypedApp", "TypedPf", "SecondApp", "PkgApp", "PlantPkg", "Meter", "Shelf", "Book", "Hues"]
}
## A plant run with `types=0` on itself, that must leave nothing.
plain : Str -> Plants.Expect
plain = |name| {
name,
file: "",
beside: "",
left: 0,
why: "",
root: "",
types: Bool.False,
confirms: 0,
rounds: AnyRounds,
no_types_run: Bool.False,
unreached: 0,
stop: "",
tree_pin: "",
count: Bool.False,
proven: 0,
unsettled: 0,
types_from: Bool.False,
peers: AnyPeers,
undo: Bool.False,
made_unused: 0,
made_long: 0,
made_says: "",
}
## A plant run with the types on `root`, taking `confirms` confirms and
## `rounds` trial rounds.
typed : Str, Str, U64, U64 -> Plants.Expect
typed = |name, root, confirms, rounds| { ..plain(name), root, types: Bool.True, confirms, rounds: Rounds(rounds) }
## A plant `file` counted under `trials=0` on TypedApp, with `proven` calls
## proven and none unsettled.
counted : Str, Str, U64 -> Plants.Expect
counted = |name, file, proven| { ..plain(name), file, root: "TypedApp", types: Bool.True, count: Bool.True, proven }
cookbook/roc/rewrite_module_calls_as_method_calls/Literals.roc, 203 lines
## Whether a value's type comes from unsuffixed number literals alone, read
## from the file's tree (number_literals.shale). Such a value's type
## defaults (to `Dec`) when it is a method call's receiver, so
## `U64.to_str(5)` is "5" while `(5).to_str()` is "5.0", and such a call
## stays as it is.
import Source
Literals := [].{
## Whether node `place` is a constant numeric expression: untyped number
## literals (`5`, `-3`, `0x1F`, `1.5`, `'a'`; not `5.U64`) joined only by
## operators and parentheses (a one-element tuple), as in `5`, `(5)`,
## `2 + 3` or `-(1 + 2)`.
is_constant_numeric : Source.File, U64 -> Bool
is_constant_numeric = |file, place| {
node = Source.node_at(file, place)
if untyped_number_literals.contains(node.kind) {
Bool.True
} else {
joins = node.kind == "e-binop" or node.kind == "unary" or (node.kind == "e-tuple" and node.kids.len() == 1)
joins and !(node.kids.is_empty()) and node.kids.all(|kid| Literals.is_constant_numeric(file, kid))
}
}
## The name a definition `name = <value>` binds, or `""` for any other
## node.
defined_name : Source.File, Source.Node -> Str
defined_name = |file, node|
if node.kind == "s-decl" and node.kids.len() == 2 {
pattern = Source.kid_node(file, node, 1)
if pattern.kind == "p-ident" {
pattern.raw
} else {
""
}
} else {
""
}
## Whether the value at node `place` takes its type from unsuffixed
## number literals alone, so that as a receiver it defaults: a constant
## numeric expression; a plain name bound, unannotated, to one, or to
## another such name; a loop variable over a list of them or a range of
## literals (`for n in [10, 1000]`, `for k in 0..<3`); a `var` whose start
## is one; or a field of a record literal that holds one (`r.a` after
## `r = { a: 5 }`).
takes_literal_type : Source.File, U64 -> Bool
takes_literal_type = |file, place| takes(file, place, Number, 0)
}
## The number literals whose type only their use fixes.
untyped_number_literals : Set(Str)
untyped_number_literals = Set.from_list(["e-int", "e-frac", "e-single-quote"])
## What a value is asked to be: the number itself, or what a `for` walks (a
## list literal of such numbers, a range of literals, or a name bound to
## either).
Asked : [Number, Items]
## How a plain name gets its type: from a definition's value, from a `for`
## that walks a value, or some other way (a parameter, an annotation, no
## binding found).
Binding : [Value(U64), Loop(U64), Unbound]
is_plain_name : Source.Node -> Bool
is_plain_name = |node| node.kind == "e-ident" and !(node.raw.contains("."))
has_parameter_named : Source.File, Source.Node, Str -> Bool
has_parameter_named = |file, lambda, name|
lambda.kids.any(
|kid| {
args = Source.node_at(file, kid)
args.kind == "args" and args.kids.any(|arg| is_parameter_named(file, arg, name))
},
)
is_parameter_named : Source.File, U64, Str -> Bool
is_parameter_named = |file, place, name| {
pattern = Source.node_at(file, place)
pattern.kind == "p-ident" and pattern.raw == name
}
## The binding of the plain name `name`, used at node `at`, that gives it
## its type. The binding that counts is the nearest one up the tree: in a
## block, the last definition before the statement holding the use; at the
## top level, any definition. A `var`'s type is its start's, so for a
## `$name` only its `var` counts, never a reassignment.
binding_of : Source.File, U64, Str -> Binding
binding_of = |file, at, name| {
is_var = name.starts_with("$")
var $child = at
var $up = Source.node_at(file, at).parent
while $up > 0 {
scope = Source.node_at(file, $up)
if scope.kind == "e-lambda" and has_parameter_named(file, scope, name) {
return Unbound
}
if scope.kind == "s-for" and scope.kids.len() == 3 and $child == Source.kid(scope, 3) {
if is_parameter_named(file, Source.kid(scope, 1), name) {
return Loop(Source.kid(scope, 2))
}
}
in_block = scope.kind == "statements" and scope.parent > 0 and Source.node_at(file, scope.parent).kind == "e-block"
var $definition = 0
var $annotated = Bool.False
var $passed = Bool.False
for kid in scope.kids {
if in_block and kid == $child {
$passed = Bool.True
}
if !($passed) {
statement = Source.node_at(file, kid)
if is_var {
if statement.kind == "s-var" and statement.name == name and statement.kids.len() == 1 {
$definition = kid
}
} else if Literals.defined_name(file, statement) == name {
$definition = kid
}
if statement.kind == "s-type-anno" and statement.name == name {
$annotated = Bool.True
}
}
}
if $definition > 0 {
if $annotated {
return Unbound
}
definition = Source.node_at(file, $definition)
return Value(definition.kids.last() ?? 0)
}
$child = $up
$up = scope.parent
}
Unbound
}
## `Literals.takes_literal_type`, for a number or for what a `for` walks, at
## most 8 bindings deep. One function for both, since each asks the other.
takes : Source.File, U64, Asked, U64 -> Bool
takes = |file, place, asked, depth|
if depth > 8 {
Bool.False
} else if Literals.is_constant_numeric(file, place) {
Bool.True
} else {
node = Source.node_at(file, place)
if is_plain_name(node) {
match binding_of(file, place, node.raw) {
Unbound => Bool.False
Loop(walked) => asked == Number and takes(file, walked, Items, depth + 1)
Value(value) => takes(file, value, asked, depth + 1)
}
} else {
match asked {
Items =>
node.kind == "e-list" and !(node.kids.is_empty()) and node.kids.all(|kid| takes(file, kid, Number, depth + 1))
Number => field_takes(file, node, depth)
}
}
}
## Whether a field access `r.a` reads a record literal's field that takes
## its type from number literals.
field_takes : Source.File, Source.Node, U64 -> Bool
field_takes = |file, node, depth|
if node.kind == "e-field-access" and node.kids.len() == 2 {
receiver = Source.kid_node(file, node, 1)
segment = Source.kid_node(file, node, 2)
if receiver.kind != "receiver" or receiver.kids.len() != 1 or segment.kind != "segment" {
Bool.False
} else {
value_place = Source.kid(receiver, 1)
value = Source.node_at(file, value_place)
if !(is_plain_name(value)) {
Bool.False
} else {
match binding_of(file, value_place, value.raw) {
Value(bound) => {
record = Source.node_at(file, bound)
if record.kind != "e-record" {
Bool.False
} else {
matching = record.kids.find_first(|kid| is_field_named(file, kid, segment.field))
match matching {
Ok(field_place) => takes(file, Source.kid(Source.node_at(file, field_place), 1), Number, depth + 1)
Err(_) => Bool.False
}
}
}
_ => Bool.False
}
}
}
} else {
Bool.False
}
is_field_named : Source.File, U64, Str -> Bool
is_field_named = |file, place, name| {
field = Source.node_at(file, place)
field.kind == "field" and field.field == name and field.kids.len() == 1
}
cookbook/roc/rewrite_module_calls_as_method_calls/Rewritten.roc, 168 lines
## A file's text written back with chosen calls turned: `Module.fn(first,
## rest...)` into `first.fn(rest...)`, or a peer method call back into a
## module call, `a.max(b)` into `U64.max(a, b)` (method_text.shale's
## `rewritten_text`). Every other byte is the file's own.
import Source
Rewritten := [].{
## A call to turn, by its node: the module and function it calls, and
## whether it is a peer method call turned back (`undo`).
Turn : { node : U64, module_name : Str, fn : Str, undo : Bool }
## The text written, the lines each turned call took in it, by the
## call's node, and the line each node written starts on.
Written : {
text : Str,
turned_lines : Dict(U64, { from_line : U64, to_line : U64 }),
line_of_node : Dict(U64, U64),
}
## The file's text with every call in `turning` (by its node) turned. The
## file node spans what roc-ast parsed; the bytes outside it, such as a
## last newline, are kept.
written : Source.File, Dict(U64, Rewritten.Turn) -> Rewritten.Written
written = |file, turning| {
root = Source.node_at(file, 1)
start = {
out: [],
line: Source.line_of_offset(file, root.from),
turned_lines: Dict.empty(),
line_of_node: Dict.empty(),
}
done = emit_node(file, turning, start, 1, 0)
before = Source.bytes_between(file, 1, root.from)
after = file.bytes.drop_first(root.to - 1)
{
text: Str.from_utf8_lossy(before.concat(done.out).concat(after)),
turned_lines: done.turned_lines,
line_of_node: done.line_of_node,
}
}
}
## The text written so far, the line it ends on, and what is known of the
## turned calls and the nodes written.
Writer : {
out : List(U8),
line : U64,
turned_lines : Dict(U64, { from_line : U64, to_line : U64 }),
line_of_node : Dict(U64, U64),
}
## The node kinds a receiver can be without parentheses, as in `f(x).len()`
## or `"a".to_utf8()`. Any other (a number, a sum, a lambda, an `if`) is
## wrapped in them: `(a + b).to_str()`.
bare_receiver_kinds : Set(Str)
bare_receiver_kinds = Set.from_list(["e-ident", "e-apply", "e-method-call", "e-field-access", "e-string", "e-list", "e-record", "e-tuple", "e-tag"])
## `bytes` written, the line counted on past each newline.
emit_bytes : Writer, List(U8) -> Writer
emit_bytes = |writer, bytes| {
newlines = bytes.count_if(|byte| byte == '\n')
{ ..writer, out: writer.out.concat(bytes), line: writer.line + newlines }
}
emit : Writer, Str -> Writer
emit = |writer, text| emit_bytes(writer, text.to_utf8())
## The nodes that carry node `place`'s text: itself when it has a span, else
## its nearest descendants that do (`args` and `receiver` have none).
spanned_nodes : Source.File, U64 -> List(U64)
spanned_nodes = |file, place| {
node = Source.node_at(file, place)
if node.has_span {
[place]
} else {
node.kids.join_map(|kid| spanned_nodes(file, kid))
}
}
## Writes node `place`'s text, from byte `start` on. A call being turned is
## written as a method call (or a module call); any other node as it is,
## each kid that has a span written in its place by the same rule, so nested
## calls turn too. Spans may overlap (a type module's `type-mod` and its
## declaration both start at the type's name), so a kid is written from
## where the text so far ends, and one wholly before that is skipped.
emit_node : Source.File, Dict(U64, Rewritten.Turn), Writer, U64, U64 -> Writer
emit_node = |file, turning, writer, place, start| {
node = Source.node_at(file, place)
noted = { ..writer, line_of_node: writer.line_of_node.insert(place, writer.line) }
match turning.get(place) {
Ok(turn) => {
from_line = noted.line
done = if turn.undo {
emit_undone(file, turning, noted, node, turn)
} else {
emit_turned(file, turning, noted, node, turn)
}
lines = { from_line, to_line: done.line }
{ ..done, turned_lines: done.turned_lines.insert(place, lines) }
}
Err(_) => emit_as_written(file, turning, noted, node, start)
}
}
## A module call written as a method call on its first argument.
emit_turned : Source.File, Dict(U64, Rewritten.Turn), Writer, Source.Node, Rewritten.Turn -> Writer
emit_turned = |file, turning, writer, node, turn| {
args = node.kids.drop_first(1)
first = args.first() ?? 0
needs_parens = !(bare_receiver_kinds.contains(Source.node_at(file, first).kind))
var $writer = writer
if needs_parens {
$writer = emit($writer, "(")
}
$writer = emit_node(file, turning, $writer, first, 0)
if needs_parens {
$writer = emit($writer, ")")
}
$writer = emit($writer, ".${turn.fn}(")
var $comma = Bool.False
for arg in args.drop_first(1) {
if $comma {
$writer = emit($writer, ", ")
}
$writer = emit_node(file, turning, $writer, arg, 0)
$comma = Bool.True
}
emit($writer, ")")
}
## A peer method call turned back, `a.max(b)` written `U64.max(a, b)`.
emit_undone : Source.File, Dict(U64, Rewritten.Turn), Writer, Source.Node, Rewritten.Turn -> Writer
emit_undone = |file, turning, writer, node, turn| {
receiver = Source.kid_node(file, node, 1)
var $writer = emit(writer, "${turn.module_name}.${turn.fn}(")
$writer = emit_node(file, turning, $writer, Source.kid(receiver, 1), 0)
for arg in Source.kid_node(file, node, 2).kids {
$writer = emit($writer, ", ")
$writer = emit_node(file, turning, $writer, arg, 0)
}
emit($writer, ")")
}
## A node written as it is, from `start` or its own first byte, whichever is
## later, with its kids written in their places.
emit_as_written : Source.File, Dict(U64, Rewritten.Turn), Writer, Source.Node, U64 -> Writer
emit_as_written = |file, turning, writer, node, start| {
var $at = if start > node.from {
start
} else {
node.from
}
var $writer = writer
for kid in node.kids {
for spanned in spanned_nodes(file, kid) {
span = Source.node_at(file, spanned)
if span.to > $at {
if span.from > $at {
$writer = emit_bytes($writer, Source.bytes_between(file, $at, span.from))
}
$writer = emit_node(file, turning, $writer, spanned, $at)
$at = span.to
}
}
}
emit_bytes($writer, Source.bytes_between(file, $at, node.to))
}
Shale original
cookbook/roc/rewrite_method_calls.shale, 1,195 lines, at 9905eba5
The libraries it loads: cookbook/roc/pinned.shale (20 lines), cookbook/findings.shale (21 lines), cookbook/roc/types.shale (301 lines), cookbook/roc/number_literals.shale (136 lines), cookbook/roc/peer_calls.shale (155 lines), cookbook/roc/imports.shale (106 lines), cookbook/roc/method_text.shale (149 lines).
-- This recipe rewrites old-style Roc calls as method calls. A call
-- `Module.fn(first, rest...)` becomes `first.fn(rest...)` wherever that is
-- the same call, that is, wherever the first argument's type is the
-- module's own: `List.map(xs, f)` becomes `xs.map(f)`, and
-- `Str.concat(a, b)` becomes `a.concat(b)`. Nested calls turn from the
-- inside out, so `List.len(List.keep_if(xs, p))` becomes
-- `xs.keep_if(p).len()`.
--
-- A method call names a subject, so a call of a symmetric function
-- (cookbook/roc/symmetric_functions.txt: `max`, `concat`, `map2`, ...)
-- whose first two arguments' types have one head, aliases read through
-- (`U64.max(a, b)`, `Str.concat(a, b)`), stays a module call, and with the
-- types every run lists each such method call, `a.max(b)`, as a
-- `path:line: peer_receiver: why` finding, counted in the summary;
-- `peers=undo` turns them back (cookbook/roc/peer_calls.shale). Any other
-- function, `starts_with` or a unit's `plus`, keeps its method call.
--
-- cd <repo> && shale --undo-on-stop <shale>/cookbook/roc/rewrite_method_calls.shale glob=app/*.roc root=app/main.roc
-- cd <repo> && shale --undo-on-stop <shale>/cookbook/roc/rewrite_method_calls.shale glob=app/*.roc root=app/main.roc apply=1
-- cd <repo> && shale --undo-on-stop <shale>/cookbook/roc/rewrite_method_calls.shale glob=app/*.roc root=app/main.roc,app/specs.roc
-- cd <repo> && shale --undo-on-stop <shale>/cookbook/roc/rewrite_method_calls.shale glob=src/*.roc root=src/Lib.roc types=0
-- cd <repo> && shale --undo-on-stop <shale>/cookbook/roc/rewrite_method_calls.shale glob=app/*.roc root=app/main.roc peers=undo apply=1
-- shale cookbook:roc/rewrite_method_calls.shale self_test=1
--
-- The arguments:
-- glob the files to rewrite, `**/*.roc` by default; several globs may be
-- given, separated by commas, and a file two of them match is read
-- once.
-- root the app that `roc check` and `roc test` run on. Several apps,
-- comma-separated, serve a tree that no one app imports whole,
-- such as test-only modules with an app of their own; each file is
-- then judged on the first root that imports it. With `types=0`
-- only one root is allowed, and it defaults to each file itself.
-- apply with `apply=1`, the rewrites that pass are kept. Without it the
-- run is a dry run: each trial is written in place and put back
-- byte for byte, so the tree ends as it began.
-- types with `types=0`, the type checker's types (below) are not read.
-- from the glob's file to start at, 1 by default (see the program limit
-- below).
-- trials with `trials=0`, nothing is written and no compiler runs: the
-- types alone say what would turn. A call whose first argument
-- the types prove is counted `proven`, one they leave open is
-- counted `unsettled` (listed, with the kind of type they gave),
-- and the rest are `left` as ever. It is the count a report needs
-- without the trial compiles that make a dry run slow, and it
-- differs from a dry run's `rewritten` in two ways: a proven call
-- that `roc check` would refuse (a literal whose type defaults, the
-- ProvenFails plant) is counted, and an unsettled call that would
-- compile is not. It needs the types, so not with `types=0`, and
-- never with `apply=1`.
-- peers with `peers=undo`, the run's candidates are the peer method
-- calls alone, each turned back into a module call (`a.max(b)` to
-- `U64.max(a, b)`, through the receiver's type) and judged by the
-- compiler as a rewrite is. It needs the types; not with trials=0.
-- types_from a file in roc-types' format holding the one root's types,
-- read in place of running roc-types (a gate that has typed the
-- app already keeps them). Its first line is held to the tree's
-- pin as roc-types' own is. One root only.
-- Run it with `--undo-on-stop`, so that a run stopped in the middle of a
-- trial (by a budget, or Ctrl-C) puts the trial's file back too.
--
-- A syntax tree can't tell a value's type, so the compiler judges each
-- rewrite. The candidates come from `roc_tree` (Roc's own parser), and the
-- types sort them first (below). A file's remaining candidates are written
-- in, and the file passes when `roc check` on its root passes and the
-- summary of `roc test` (its count of expects and their results) is what it
-- was before. When `roc check` reports an error on a rewritten call's
-- lines, that call stays as it was, with the error's title as its reason,
-- and the file is tried again without it. A `missing method` error on a
-- definition `name = <value>` means the value's type never resolved, and it
-- counts against the rewritten calls whose first argument is that `name`.
-- Any other error, a warning included, is a stray. A refused call can cause
-- errors where its value is used (an `unconditional condition` on an `if`
-- it decides), so strays are judged only in a round that refused no call.
-- A stray in such a round, a changed `roc test` summary, or a file still
-- failing after the last round puts the whole file back, and every
-- candidate in it stays, with that reason. Under `apply=1`, a file that
-- `roc fmt` found clean before is formatted again after its rewrite.
--
-- Some calls are not candidates at all:
-- - a function used as a value, like `Str.trim` in `List.map(xs, Str.trim)`;
-- - a call of the file's own module, like `Store.load!(id)` in Store.roc.
-- Inside its module a function is called by the name it is declared
-- with, and listing every such call would bury the ones that need a
-- hand.
-- These calls are candidates that stay, each listed with its reason:
-- - a call on the right of a `|>`, where the pipe gives the first
-- argument: `x |> List.concat(y)` is `List.concat(x, y)`, not
-- `y.concat()`;
-- - a call with an argument that has no span in the tree (the compiler's
-- `match`), since its text can't be moved;
-- - a call whose first argument is a constant numeric expression, that is,
-- number literals (`5`, `-3`, `1.5`, `'a'`) joined only by operators and
-- parentheses (`2 + 3`, `-(1 + 2)`). The module call fixes the number's
-- type, but a receiver's type defaults: `U64.to_str(5)` is "5", while
-- `(5).to_str()` is a `Dec`'s "5.0". Both pass `roc check`, so only an
-- `expect` would notice. The same holds for a plain name bound to such an
-- expression without an annotation, at its nearest definition (`n = 5`
-- earlier in a block, or a top-level `top = 7`), for a loop variable
-- over a list of such literals or a range of them (`for n in [10,
-- 1000]`, `for k in 0..<3`), for a `var` such a literal starts (`var $n
-- = 0`, however it is reassigned) and for a field of a record literal
-- that holds one (`r.a` after `r = { a: 5 }`). A typed literal
-- (`5.U64`), a name, a call or a field anywhere in the expression fixes
-- its type, so `n + 1` is a candidate, and so are an annotated name
-- (`m : U64`) and a parameter. A name bound to anything else whose type
-- only literals give (`start = if c 1 else 0`) is a candidate too, and
-- its type defaults the same way; the compiler catches that only where
-- the default clashes (the ProvenFails plant), and otherwise only an
-- `expect` would.
-- Without the types, a call whose first argument has another type
-- (`Str.from_utf8(bytes)`, a list) is tried, and stays because the
-- compiler reports a `missing method`.
--
-- By default the recipe first reads every expression's type from Roc's own
-- type checker, `roc-types` (`tools:roc-types/bin/roc-types`, from
-- https://github.com/showell/roc-types, read through cookbook/roc/types.shale). It
-- runs once on each root, before any file is tried. The type of each
-- candidate's first argument decides what happens to it:
-- - a concrete type of another kind (`List(U8)` for a `Str` call, a
-- record, a tag union, a function) leaves the call untried, with a
-- reason like `the first argument is a List, not a Str`;
-- - a type whose head is the module itself (`Str`, `List(...)`, `Point`)
-- proves the call (`proves_module_call`, below);
-- - a type variable, or no type at that spot, leaves the call to the trial;
-- - first, a call whose first two arguments are peers stays (`peers`).
-- The summary counts each kind. The files whose open calls are all proven
-- are written at once, and one `roc check` and one `roc test` on their root
-- confirm them together. When that check fails, the files its errors name
-- are set aside and the rest are confirmed again; an error in any other
-- file, or a changed test summary, sets them all aside. A file set aside,
-- and any file with a call the types couldn't settle, goes through the
-- trial alone. A proof is not a pass: in `U8.to(0, 3)` the checker types
-- `0` as a U8 only because the call makes it one, which is why a constant
-- numeric expression is not a candidate.
-- When the types can't be read, the run stops rather than going on without
-- them. That happens with no `root=` (roc-types reads an app, and reads a
-- type module only through an app), a root that is not an app or that the
-- checker refuses, and a roc-types built for a different Roc than the
-- tree's `roc-version`. A file of the glob with a call to try that no root
-- imports is left untouched and the run goes on; such files are listed
-- after the findings (`not reached by <roots>: <path>`), and the run then
-- fails. A file with no call to try needs no root, as a package's header
-- `main.roc` that nothing imports. The roots' types are read one root at a
-- time, so a run holds one root's types at once. With `types=0` every
-- candidate is tried.
--
-- A Shale run starts at most its `programs` budget of programs, and a very
-- large tree needs more. The run then stops before a file it might not finish, prints `go on with
-- from=N`, and the next run, given `from=N`, starts at the glob's Nth file.
-- A file with nothing to try uses no programs. Under `apply=1`, a stopped
-- run has already written the files the confirm kept, and the next run
-- finds their calls already turned. Each trial also adds an entry to Roc's
-- cache (`~/.cache/roc`), so a tree of a few dozen files can fill several
-- gigabytes there.
--
-- The output is the summary line (`files N, candidates N, rewritten N, left
-- N, peer_receiver N`, the programs used, the files being those begun, so a gate can tell
-- that the glob found what it meant, then `made_unused_import N, made_long_line N`), a line
-- `path:line: Module.fn: why` for each call that stays, a `made_*` line for each import
-- the rewrite left unused and each line it pushed past 100 columns, which a sweep fixes in
-- the same pass (`made_by_rewrites`), the count of each kind the types found, and the
-- summary again (cookbook/findings.shale).
--
-- The compiler is the one the tree pins: `tools:roc-<pin>/roc`, with the pin
-- read from the `roc-version` file in the directory the run starts in, and
-- a run without that file stops. Method lookup has changed between Roc
-- nightlies, so a rewrite is judged only by the Roc the tree is built with.
-- The self-test uses `SELF_TEST_PIN`. Both come from `roc_bin` in
-- cookbook/roc/pinned.shale.
--
-- `self_test=1` judges each plant in `cookbook/roc/plants/rewrite_method_calls/` in a
-- child run of its own (`plant=<Name>`, run by the `shale` on PATH), so each
-- plant gets a run's programs of its own. The child copies the plants to a fresh
-- folder under `scratch:` and runs with `apply=1` there. The table `EXPECT`
-- below says how many calls each plant must leave, a reason one of them must
-- give, and how many confirms and rounds it takes; a plant with a
-- `<Name>.want` file must come out as that text. A plant marked `types` runs
-- with the types, its root one of the app plants in `ROOT_PLANTS`; the
-- others run with `types=0`. A plant with a `stop` must stop its child run
-- with that text. The self-test fails at once when roc-types is not
-- installed.
-- budget: steps=900000000 output_bytes=4000000 arena_bytes=2000000000 kept_bytes=256000000 changes=100000 change_bytes=2000000000 call_depth=1000
const SELF_TEST = arg("self_test", "") == "1"
const APPLY = SELF_TEST or arg("apply", "") == "1"
const TYPES_ARG = arg("types", "1")
if TYPES_ARG ~= "0" and TYPES_ARG ~= "1" then fail("rewrite_method_calls: types=" .. TYPES_ARG .. ": types must be 1 (the default) or 0") end
const USE_TYPES = TYPES_ARG == "1"
const PLANT = arg("plant", "")
const PLANTS_DIR = "cookbook:roc/plants/rewrite_method_calls"
const SYMMETRIC_FUNCTIONS = "cookbook:roc/symmetric_functions.txt"
const THIS_SCRIPT = "cookbook:roc/rewrite_method_calls.shale"
const GLOB = arg("glob", "**/*.roc")
const ROOT = arg("root", "")
const FROM = tonumber(arg("from", "1"))
const TRIALS_ARG = arg("trials", "1")
if TRIALS_ARG ~= "0" and TRIALS_ARG ~= "1" then fail("rewrite_method_calls: trials=" .. TRIALS_ARG .. ": trials must be 1 (the default) or 0") end
const COUNT_ONLY = TRIALS_ARG == "0"
const TYPES_FROM = arg("types_from", "")
if COUNT_ONLY and APPLY and not SELF_TEST then fail("rewrite_method_calls: trials=0 writes nothing, so not with apply=1") end
if COUNT_ONLY and not USE_TYPES then fail("rewrite_method_calls: trials=0 counts by the types, so not with types=0") end
const PEERS_ARG = arg("peers", "")
if PEERS_ARG ~= "" and PEERS_ARG ~= "undo" then fail("rewrite_method_calls: peers=" .. PEERS_ARG .. ": peers takes only `undo`") end
const UNDO = PEERS_ARG == "undo"
if UNDO and (COUNT_ONLY or not USE_TYPES) then fail("rewrite_method_calls: peers=undo judges peers by the types and turns them in trials, so not with trials=0 or types=0 (trials=0 counts them as peer_receiver)") end
use("./pinned.shale")
use("cookbook:findings.shale")
use("./types.shale")
use("./number_literals.shale")
use("./peer_calls.shale")
use("./imports.shale")
use("./method_text.shale")
-- Each round leaves out the calls the compiler refused, and the next round
-- may find more that their errors hid.
const MAX_ROUNDS = 6
-- A file may take `MAX_ROUNDS` checks, a test and, under `apply=1`, two
-- `roc fmt`s; the first file on a root also takes the baseline's check and
-- test. A file is begun only while that many programs are left.
const MAX_PROGRAMS = budget().programs
const PROGRAMS_PER_FILE = MAX_ROUNDS + 5
-- ── the candidates ─────────────────────────────────────────────────────
-- The reason the call `module.fn(...)` at node `i` must stay, whatever the
-- types say, or "" when it may be tried.
function reason_call_stays(t, i, module, fn)
local n = t.nodes[i]
local parent = n.parent > 0 and t.nodes[n.parent] or nil
if parent ~= nil and parent.kind == "e-arrow-call" and parent.kids[2] == i then
return "the right of a `|>`, whose first argument the pipe gives"
end
-- An argument with no span (the compiler's `e-match`) begins before any
-- node it holds, at `match`, so its text can't be found, and writing it
-- from no span would copy the whole file.
for a in drop(n.kids, 1) do
if not t.nodes[a].has_span then return "an argument with no span in the tree (" .. t.nodes[a].kind .. "), whose text cannot be moved" end
end
local first = n.kids[2]
local first_node = t.nodes[first]
if is_constant_numeric(t, first) then
local text = sub(t.text, first_node.span.from, first_node.span.to - 1)
if first_node.kind ~= "e-tuple" then text = "(" .. text .. ")" end
return "a number literal's type would default as a receiver (`" .. text .. "." .. fn .. "()` is no longer a " .. module .. ")"
end
if takes_literal_type(t, first, "number", 0) then
local text = sub(t.text, first_node.span.from, first_node.span.to - 1)
return "a number literal's type would default as a receiver (`" .. text .. "` takes its type from a number literal, unannotated, and `" .. text .. "." .. fn .. "()` is no longer a " .. module .. ")"
end
return ""
end
-- The calls `Module.fn(first, ...)` in tree `t`, except calls of the file's
-- own module, each `{node, module, fn, line, why_left, proven, from_line,
-- to_line}`. `why_left` is "" while the call is open to rewriting, else the
-- reason it stays. `from_line` and `to_line` are its lines in a trial's text.
function candidates_in(t, own_module)
local out = {}
for i = 1, #t.nodes do
local n = t.nodes[i]
if n.kind == "e-apply" and #n.kids >= 2 then
local callee = t.nodes[n.kids[1]]
local m = re_find(callee.raw, "^([A-Z][A-Za-z0-9]*)\\.([a-z][A-Za-z0-9_]*!?)$")
if callee.kind == "e-ident" and m ~= nil and m.groups[1] ~= own_module then
local module = m.groups[1]
local fn = m.groups[2]
push(out, {node = i, module = module, fn = fn, line = line_of_offset(t, n.span.from), why_left = reason_call_stays(t, i, module, fn), proven = false, kind = "", from_line = 0, to_line = 0})
end
end
end
return out
end
function is_below(t, i, top)
local at = t.nodes[i].parent
while at > 0 do
if at == top then return true end
at = t.nodes[at].parent
end
return false
end
-- A `missing method` error that `roc check` reports on the value of a
-- definition `name = <value>`, rather than on a call, means that value's
-- type never resolved because its only use was a turned `name.fn()`. The
-- error is blamed on each turned call whose first argument is the plain
-- `name` within the definition's statements. Returns whether any call was.
function blame_calls_on_definition(t, e, cands)
if e.title ~= "missing method" then return false end
local blamed = false
for d = 1, #t.nodes do
local n = t.nodes[d]
local name = defined_name(t, n)
if name ~= "" and get(t.trial_line_of_node, "" .. n.kids[2], 0) == e.line then
for c in cands do
local first = t.nodes[t.nodes[c.node].kids[2]]
if c.from_line > 0 and first.kind == "e-ident" and first.raw == name and is_below(t, c.node, n.parent) then
if c.why_left == "" then c.why_left = "roc check: " .. e.title .. " (on `" .. name .. "`'s definition)" end
blamed = true
end
end
end
end
return blamed
end
-- The open candidates by node, as `rewritten_text` takes them, and their count.
function open_calls(cands)
local turning = {}
local count = 0
for c in cands do
if c.why_left == "" then
turning["" .. c.node] = c
count = count + 1
end
end
return {turning = turning, count = count}
end
function leave_open_calls(cands, why)
for c in cands do
if c.why_left == "" then c.why_left = why end
end
return nil
end
-- ── the compiler ─────────────────────────────────────────────────────────
-- Runs `roc check` on `root`: `{ok, errors, out}`, each error `{title, file,
-- line}`. A warning counts as an error, since a warning fails the build.
function roc_check(ctx, root)
ctx.programs_used = ctx.programs_used + 1
local r = run({roc_bin("rewrite_method_calls", SELF_TEST), "check", real(root)}, {timeout_ms = 900000, whole = 64000000})
local errors = {}
for l in lines(r.out) do
-- An error's heading is `── ✗ <title> ───── <path>:<line>:<col>`, and a
-- warning's has `●` in place of `✗`.
local is_heading = starts_with(l, "── ✗ ") or starts_with(l, "── ● ")
local at = is_heading and re_find(l, " ([^ ]+):([0-9]+):([0-9]+)$") or nil
if at ~= nil then
local title = trim(split(sub(l, #"── ✗ " + 1), " ─")[1])
push(errors, {title = title, file = basename(at.groups[1]), line = tonumber(at.groups[2])})
end
end
return {ok = r.ended == "exit" and r.code == 0, errors = errors, out = r.out}
end
-- The first non-blank line of `out`, for a failure that names no error
-- (a crash).
function first_line_said(out)
for l in lines(out) do
if trim(l) ~= "" then return trim(l) end
end
return "nothing said"
end
-- The last line of `roc test` on `root`, without its time, and the exit
-- code: what a rewrite may not change.
function roc_test_summary(ctx, root)
ctx.programs_used = ctx.programs_used + 1
local r = run({roc_bin("rewrite_method_calls", SELF_TEST), "test", real(root)}, {timeout_ms = 900000, whole = 64000000})
local said = lines(trim(r.out))
local last = said[#said] or ""
local m = re_find(last, "^(.*) in [0-9.]+ ms\\.")
return (m ~= nil and m.groups[1] or last) .. " (exit " .. r.code .. ")"
end
function is_fmt_clean(ctx, p)
ctx.programs_used = ctx.programs_used + 1
return run({roc_bin("rewrite_method_calls", SELF_TEST), "fmt", "--check", real(p)}, {timeout_ms = 120000, tail = 20}).code == 0
end
function roc_fmt(ctx, p)
ctx.programs_used = ctx.programs_used + 1
run({roc_bin("rewrite_method_calls", SELF_TEST), "fmt", real(p)}, {timeout_ms = 120000, tail = 20})
return nil
end
-- The `roc test` summary of `root` before any rewrite, which every trial on
-- that root must match. It is taken once a root, and `roc check` must pass
-- first.
function baseline_test_of(ctx, baselines, root)
if not has_key(baselines, root) then
if not roc_check(ctx, root).ok then fail("rewrite_method_calls: `roc check " .. root .. "` fails before any rewrite: fix it first") end
baselines[root] = roc_test_summary(ctx, root)
end
return baselines[root]
end
-- ── the types (read unless `types=0`) ────────────────────────────────────
-- Every expression's type in the app `root`, from `roc_types` (one program;
-- the library stops the run on a root the checker refuses, whose types
-- would be guesses). Returns `{by_region, modules}`: each type keyed by
-- `<real path>|line:col:end_line:end_col`, and the set of the modules' real
-- paths. Where several expressions share a region, the first that roc-types
-- gives, the outermost, is kept as the value written there. Regions are
-- shared where the compiler desugars (`x?` is a `match` over `x`, `Ok(x)` a
-- nominal over a tag, `a and b` an `if`), and the inner expressions are
-- parts of the desugaring, not the argument's value.
function types_by_region(ctx, root)
local got = nil
if ctx.types_from ~= "" then
got = roc_types_from_file(ctx.types_from, root, ctx.roc, ctx.only)
else
ctx.programs_used = ctx.programs_used + 1
got = roc_types(root, ctx.roc)
end
local by_region = {}
for path in got.paths do
for rec in got.modules[path] do
if rec.kind == "expr" then
local key = path .. "|" .. rec.line .. ":" .. rec.column .. ":" .. rec.end_line .. ":" .. rec.end_column
if not has_key(by_region, key) then by_region[key] = rec.type end
end
end
end
for l in got.warnings do print("rewrite_method_calls: roc-types " .. root .. ": " .. l) end
return {by_region = by_region, modules = set_of(got.paths)}
end
-- A type's head, as `{head}`, or `{var = true}` for a type variable (`a`,
-- `_a`, `a where [...]`). `List(U8)`'s head is `List` and
-- `Access.Viewer(Topic.At)`'s is `Access.Viewer`. A function's (an arrow
-- outside every bracket) is `function`, `{...}`'s is `record`, `[...]`'s
-- is `tag union`, and `(a, b)`'s is `tuple`.
function type_head(ty)
if find(ty, "->") ~= nil or find(ty, "=>") ~= nil then
local depth = 0
for i = 1, #ty - 1 do
local ch = sub(ty, i, i)
if ch == "(" or ch == "[" or ch == "{" then depth = depth + 1 end
if ch == ")" or ch == "]" or ch == "}" then depth = depth - 1 end
local two = sub(ty, i, i + 1)
if depth == 0 and (two == "->" or two == "=>") then return {head = "function"} end
end
end
local first = sub(ty, 1, 1)
if first == "{" then return {head = "record"} end
if first == "[" then return {head = "tag union"} end
if first == "(" then return {head = "tuple"} end
if re_find(first, "^[A-Z]$") == nil then return {var = true} end
local m = re_find(ty, "^([A-Za-z0-9_.]+)")
return {head = m.groups[1]}
end
-- `word` after its indefinite article: "an" before a vowel letter, "a"
-- otherwise (`an Admin`, `a List`).
-- "an" before a vowel sound. A U usually sounds like "you" (U8, User),
-- so it takes "an" only in `Un...` (Unvalidated).
function with_article(word)
if re_match(word, "^([AEIOaeio]|[Uu]n)") then return "an " .. word end
return "a " .. word
end
-- Whether a first argument whose type has the head `head` proves a call of
-- module `module`, that is, whether `x.fn(...)` finds the module's `fn`. A
-- method is looked up in the block of the type's own declaration, so the
-- head must be the module's own type. roc-types writes a type by the name
-- it is declared with (no import's alias, and never a package's
-- shorthand): a type module's own type, or a builtin, bare (`Str`, `Point`,
-- `Meter` from a package imported as `pk.Meter`), and a type declared
-- inside a module's block qualified by that module (`Shapes.Shape`). So
-- the one form that proves is the bare module name, a package's type
-- module included. A qualified head never does, even one whose last
-- segment names the module: `Type.Game` is Type's, not Game's, and
-- `History.History` is a type in History's block, not History itself.
function proves_module_call(head, module)
return head == module
end
-- Judges each open candidate of the file at `p` by its first argument's
-- type in `types` (from the root that reaches the file). A call of a
-- function in `symmetric` whose first two arguments are peers
-- (`peer_verdict`, with the trees' `aliases`) stays a module call; a concrete other type leaves the call, with that reason; a
-- type that proves the call (`proves_module_call`) marks it `proven`; the
-- rest stay open for the trial. Each kind is counted in `kind_counts`.
function judge_by_types(kind_counts, t, cands, p, types, aliases, symmetric)
local real_path = real(p)
for c in cands do
if c.why_left == "" then
local call = t.nodes[c.node]
local key = real_path .. "|" .. t.nodes[call.kids[2]].region
local v = {peers = false}
if #call.kids >= 3 and has_key(symmetric, c.fn) then v = peer_verdict(get(types.by_region, key, ""), get(types.by_region, real_path .. "|" .. t.nodes[call.kids[3]].region, ""), aliases) end
if v.peers then
incr(kind_counts, "peers")
c.why_left = "peers: `" .. c.fn .. "` is symmetric and both arguments are " .. v.module .. "s, so neither is the subject"
elseif not has_key(types.by_region, key) then
incr(kind_counts, "no type")
c.kind = "no type"
else
local h = type_head(types.by_region[key])
if has_key(h, "var") then
incr(kind_counts, "a type variable")
c.kind = "a type variable"
else
if proves_module_call(h.head, c.module) then
incr(kind_counts, "the module's type")
c.proven = true
else
incr(kind_counts, "another type")
c.why_left = "the first argument is " .. with_article(h.head) .. ", not " .. with_article(c.module)
end
end
end
end
end
return nil
end
-- The peer method calls of the file at `p` (`j.method_calls`, judged by
-- `types`): each symmetric method call whose receiver and first argument are peers,
-- with a module to call through, goes in `j.peers` as a candidate that
-- turns it back (`undo`), `a.max(b)` to `U64.max(a, b)`. The types prove
-- the module's function, as the receiver's type is where the method was
-- found. A call with an argument that has no span stays, as a module call's
-- does.
function judge_method_peers(j, t, p, types, aliases)
local real_path = real(p)
for m in j.method_calls do
local v = peer_verdict(get(types.by_region, real_path .. "|" .. t.nodes[m.recv].region, ""), get(types.by_region, real_path .. "|" .. t.nodes[m.first].region, ""), aliases)
if v.peers then
local why = m.spanned and "" or "an argument with no span in the tree, whose text cannot be moved"
push(j.peers, {node = m.node, module = v.module, fn = m.fn, line = line_of_offset(t, t.nodes[m.node].span.from), why_left = why, proven = true, kind = "", from_line = 0, to_line = 0, undo = true, type = v.type})
end
end
return nil
end
-- ── what a rewrite leaves for the sweep ─────────────────────────────────
-- The width past which a line is long, as check_stacking.shale's `long`.
const LONG_LINE = 100
-- Records, for `made_by_rewrites`, that the file at `p`, whose tree is `t`,
-- had the calls in `turning` turned: by a passing trial or confirm, or
-- under `trials=0` the proven calls. The text after is the rewrite's, before
-- any `roc fmt`, and `joined` holds its lines where a turned call that
-- spanned several lines now sits on one, as a stacked call's arguments do.
function note_rewrite(ctx, p, t, turning)
local after = rewritten_text(t, turning)
local joined = {}
for k in keys(turning) do
local c = turning[k]
local s = t.nodes[c.node].span
if c.from_line == c.to_line and line_of_offset(t, s.from) < line_of_offset(t, s.to - 1) then push(joined, c.from_line) end
end
if after ~= t.text then ctx.rewrites[p] = {before = t.text, after = after, joined = joined} end
return nil
end
-- A line's width, a tab counting four columns.
function columns_of(l)
return #l + 3 * (#split(l, "\t") - 1)
end
-- What the rewrites in `ctx.rewrites` left for a sweep to fix in the same
-- pass, which the recipe reports and does not fix: each import that the
-- file used before its rewrite and no longer uses after it, by roc-ast's
-- trees of both texts (imports.shale's `unused_imports`), and each line
-- wider than LONG_LINE columns where a turned call joined its lines (a turn
-- alone only shortens a line). A line is named by its number in the
-- rewritten text, before any `roc fmt`. Returns `{lines, unused, long, programs}`, `lines` a
-- `path:line: made_unused_import: why` or `made_long_line` each.
function made_by_rewrites(ctx)
local out = {lines = {}, unused = 0, long = 0, programs = 0}
local paths = sort(keys(ctx.rewrites))
if #paths == 0 then return out end
-- roc_tree reads files, so both texts are written to a scratch folder.
local dir = fresh_dir("scratch:", "made_by_rewrites")
local files = {}
for k = 1, #paths do
local r = ctx.rewrites[paths[k]]
replace(dir .. "/" .. k .. "/before.roc", r.before)
replace(dir .. "/" .. k .. "/after.roc", r.after)
push(files, dir .. "/" .. k .. "/before.roc")
push(files, dir .. "/" .. k .. "/after.roc")
end
out.programs = 1
local trees = {}
for f in roc_tree(files) do
if f.err ~= "" then fail("rewrite_method_calls: roc-ast refused a rewritten text (" .. f.path .. "): " .. f.err) end
trees[f.path] = f.nodes
end
for k = 1, #paths do
local p = paths[k]
local r = ctx.rewrites[p]
local before_lines = split(r.before, "\n")
local after_lines = split(r.after, "\n")
local was_unused = {}
for imp in unused_imports(trees[dir .. "/" .. k .. "/before.roc"], before_lines) do was_unused[imp.label] = true end
for imp in unused_imports(trees[dir .. "/" .. k .. "/after.roc"], after_lines) do
if not has_key(was_unused, imp.label) then
out.unused = out.unused + 1
push(out.lines, p .. ":" .. imp.line .. ": made_unused_import: " .. imp.label .. " was used only by the calls the rewrite turned: delete the line")
end
end
local seen = {}
for i in sort(r.joined) do
local l = after_lines[i]
if columns_of(l) > LONG_LINE and not has_key(seen, "" .. i) then
seen["" .. i] = true
out.long = out.long + 1
push(out.lines, p .. ":" .. i .. ": made_long_line: " .. columns_of(l) .. " columns after the rewrite joined a call's lines: stack it (wrap_long_lines.shale): " .. trim(sub(l, 1, 120)))
end
end
end
remove_tree(dir)
return out
end
-- ── the trial and the confirm ────────────────────────────────────────────
-- Tries one file's open candidates, round by round, until `roc check`
-- passes or nothing is left to try, then runs the test. Returns how many
-- calls were turned; each call that stays gets its `why_left`. The file
-- ends as it began unless `APPLY` and some call was turned.
function try_file(ctx, p, t, cands, root, baseline_test)
local original = t.text
local fmt_was_clean = APPLY and is_fmt_clean(ctx, p)
for round = 1, MAX_ROUNDS do
local open = open_calls(cands)
if open.count == 0 then
replace(p, original)
return 0
end
replace(p, rewritten_text(t, open.turning))
ctx.rounds = ctx.rounds + 1
local r = roc_check(ctx, root)
if r.ok then
if fmt_was_clean then roc_fmt(ctx, p) end
local test_summary = roc_test_summary(ctx, root)
if test_summary ~= baseline_test then
leave_open_calls(cands, "roc test changed: " .. test_summary .. ", was " .. baseline_test .. "; the file is put back")
replace(p, original)
return 0
end
note_rewrite(ctx, p, t, open.turning)
if not APPLY then replace(p, original) end
return open.count
end
-- Each error on a turned call's lines leaves that call. An error on no
-- turned call is a stray, and counts only in a round that refused no
-- call: the compiler may complain where a refused call's value is used,
-- and the next round, without that call, shows whether the stray was
-- its.
local stray = nil
local refused = false
for e in r.errors do
if e.file == basename(p) then
local hit = false
-- One error may fall on two calls, so every call is checked.
for c in cands do
if c.from_line > 0 and e.line >= c.from_line and e.line <= c.to_line then
if c.why_left == "" then c.why_left = "roc check: " .. e.title end
hit = true
end
end
if not hit then hit = blame_calls_on_definition(t, e, cands) end
if hit then refused = true end
if not hit and stray == nil then stray = e end
elseif stray == nil then
stray = e
end
end
if not refused and (stray ~= nil or #r.errors == 0) then
local why = stray and ("roc check: " .. stray.title .. " at " .. stray.file .. ":" .. stray.line .. ", on no rewritten call") or ("roc check failed, naming no line: " .. first_line_said(r.out))
leave_open_calls(cands, why .. "; the file is put back")
replace(p, original)
return 0
end
for c in cands do c.from_line = 0 end
end
leave_open_calls(cands, "still failing after " .. MAX_ROUNDS .. " rounds; the file is put back")
replace(p, original)
return 0
end
-- Confirms the files whose open calls are all proven: `files` (`{p, t,
-- cands}`) are written with all their calls turned, at once, and one
-- `roc check` on `root` and one `roc test` judge them together. When the
-- check fails, the files its errors name are set aside and the rest written
-- again, up to `MAX_ROUNDS` checks. An error in no file of theirs (a
-- caller's), a failure naming no line, or a changed test sets them all
-- aside. `ctx.confirmed[p]` is each kept file's count of turned calls, and
-- 0 for a file set aside, which `try_file` then judges alone. A file ends
-- as it began unless `APPLY` and it was kept.
function confirm_proven_files(ctx, root, files, baseline_test)
local remaining = {}
for f in files do
ctx.confirmed[f.p] = 0
local open = open_calls(f.cands)
f.turning = open.turning
f.count = open.count
f.fmt_was_clean = APPLY and is_fmt_clean(ctx, f.p)
push(remaining, f)
end
for round = 1, MAX_ROUNDS do
if #remaining == 0 then return nil end
for f in remaining do replace(f.p, rewritten_text(f.t, f.turning)) end
ctx.confirms = ctx.confirms + 1
local r = roc_check(ctx, root)
if r.ok then
for f in remaining do
if f.fmt_was_clean then roc_fmt(ctx, f.p) end
end
local test_summary = roc_test_summary(ctx, root)
if test_summary == baseline_test then for f in remaining do note_rewrite(ctx, f.p, f.t, f.turning) end end
if test_summary ~= baseline_test or not APPLY then for f in remaining do replace(f.p, f.t.text) end end
if test_summary == baseline_test then for f in remaining do ctx.confirmed[f.p] = f.count end end
return nil
end
for f in remaining do replace(f.p, f.t.text) end
local named = {}
local error_elsewhere = #r.errors == 0
for e in r.errors do
local hit = false
for f in remaining do
if basename(f.p) == e.file then
named[f.p] = true
hit = true
end
end
if not hit then error_elsewhere = true end
end
if error_elsewhere then return nil end
local rest = {}
for f in remaining do if not has_key(named, f.p) then push(rest, f) end end
remaining = rest
end
return nil
end
-- The files of `globs`, several separated by commas, in the order the globs
-- give them, each once.
function paths_of_globs(globs)
local seen = {}
local paths = {}
for g in split(globs, ",") do
for q in glob(trim(g)) do
if not has_key(seen, q) then
seen[q] = true
push(paths, q)
end
end
end
return paths
end
-- The root each file is judged on, by path, with the types judging each
-- file's open candidates on the way. With the types read, a file's root is
-- the first of `roots` whose app reaches it; otherwise the one root, or the
-- file itself when there is none. The roots' types are read and used one at
-- a time, but nothing is collected between them: a `yield()` there keeps
-- every file's tree, which on Safari passes the kept budget's ceiling, so
-- the arena holds each root's types until the run ends. A file with a call to try (in the set `open`) that no root
-- reaches is in `unreached`, and the run goes on without it: the types
-- can't judge it, and a path spelled two ways (through a link) would
-- quietly find no type for any of its candidates. A file with none has
-- nothing for the types to judge, so it needs no root.
function roots_of_files(ctx, paths, from, roots, read_types, open, trees, judged)
local out = {}
local unreached = {}
for k = from, #paths do
out[paths[k]] = #roots > 0 and roots[1] or paths[k]
end
if not read_types then return {root_of = out, unreached = unreached} end
local found = {}
for r in roots do
local types = types_by_region(ctx, r)
ctx.types_by_root[r] = true
for k = from, #paths do
local p = paths[k]
if has_key(open, p) and not has_key(found, p) and has_key(types.modules, real(p)) then
found[p] = true
out[p] = r
judge_by_types(judged[p].kind_counts, trees[p], judged[p].cands, p, types, ctx.aliases, ctx.symmetric)
judge_method_peers(judged[p], trees[p], p, types, ctx.aliases)
end
end
types = nil
end
for k = from, #paths do
local p = paths[k]
if has_key(open, p) and not has_key(found, p) then
push(unreached, p)
judged[p].unreached = true
end
end
return {root_of = out, unreached = unreached}
end
-- Adds the peer method calls of the file `p` (`j.peers`) to `total`'s
-- findings, a `path:line: peer_receiver: why` each, and to its count.
function peer_findings(total, p, j)
for c in j.peers do
total.peers = total.peers + 1
push(total.lines, p .. ":" .. c.line .. ": peer_receiver: `." .. c.fn .. "` is symmetric and its receiver and first argument are both " .. c.module .. "s, so neither is the subject: " .. c.module .. "." .. c.fn .. "(...)")
end
return nil
end
-- `trials=0`'s answer, the files of `paths` from the `from`th on as the
-- types judged them (`judged`, by path): a proven call counts as
-- rewritten, an open one the types didn't settle as unsettled, with a line
-- naming the kind of type they gave, and a call that stays as left, with
-- its reason. Nothing is written or compiled.
function counted_by_types(total, paths, from, judged, trees)
for k = from, #paths do
local p = paths[k]
local j = judged[p]
local cands = j.unreached and {} or j.cands
local proven = {}
for c in cands do
if c.why_left == "" and c.proven then proven["" .. c.node] = c end
end
if #keys(proven) > 0 then note_rewrite(total.ctx, p, trees[p], proven) end
if not j.unreached then total.files = total.files + 1 end
for kind in keys(j.kind_counts) do incr(total.ctx.type_kind_counts, kind, j.kind_counts[kind]) end
total.candidates = total.candidates + #cands
peer_findings(total, p, j)
for c in cands do
if c.why_left ~= "" then
total.left = total.left + 1
push(total.lines, p .. ":" .. c.line .. ": " .. c.module .. "." .. c.fn .. ": " .. c.why_left)
elseif c.proven then
total.rewritten = total.rewritten + 1
else
total.unsettled = total.unsettled + 1
push(total.lines, p .. ":" .. c.line .. ": " .. c.module .. "." .. c.fn .. ": unsettled: the types gave " .. c.kind .. ", and only a trial would tell")
end
end
end
return total
end
-- Rewrites the files of `paths` from the `from`th on, each judged on its
-- root (`root` may name several, `a.roc,b.roc`, when `use_types`). Returns
-- `{candidates, rewritten, left, lines, next, ctx}`: `lines` has a
-- `path:line: Module.fn: why` for each call that stays, and `next` is the
-- file to go on from when the program limit stopped the run, else 0.
-- `trees` is the files' parse trees, or nil to read them here (one
-- program). `roc` is the OS path of the tree's Roc, which roc-types' pin
-- must match. `opts` may hold `count_only` (`trials=0`: the types decide,
-- nothing is tried, and `unsettled` counts the calls they leave open) and
-- `types_from` (the one root's types read from that file).
function run_all(paths, root, from, trees, use_types, roc, opts?)
local count_only = opts ~= nil and get(opts, "count_only", false)
local types_from = opts ~= nil and get(opts, "types_from", "") or ""
local undo = opts ~= nil and get(opts, "undo", false)
if use_types and root == "" then fail("rewrite_method_calls: the types need root=, an app importing every file of the glob: roc-types reads an app, and a type module only through one. Give root=, or types=0 to run without them, every candidate tried") end
if not use_types and find(root, ",") ~= nil then fail("rewrite_method_calls: root=" .. root .. ": several roots need the types, which say which root reaches a file; give one root, or run with the types") end
local roots = root == "" and {} or roc_types_root_apps("rewrite_method_calls", root)
if types_from ~= "" and #roots ~= 1 then fail("rewrite_method_calls: types_from= holds one root's types, and root= names " .. #roots) end
-- A root's types read from a file are parsed for the glob's files alone.
local only = {}
if types_from ~= "" then
for p in paths do only[real(p)] = true end
end
local ctx = {programs_used = 0, type_kind_counts = {}, types_by_root = {}, roc = roc, types_from = types_from, only = only, rounds = 0, confirms = 0, confirmed = {}, rewrites = {}}
if trees == nil then
trees = parse_trees(paths)
ctx.programs_used = 1
end
ctx.aliases = use_types and peer_aliases(trees) or {}
ctx.symmetric = peer_symmetric_table(read(SYMMETRIC_FUNCTIONS))
local total = {candidates = 0, rewritten = 0, left = 0, unsettled = 0, peers = 0, lines = {}, files = 0, next = 0, ctx = ctx, unreached = {}}
-- Each file's candidates, `{cands, kind_counts, open_count, all_proven,
-- method_calls, peers}`. A file the types must judge is in `open`: one
-- with a module call to try, or, with the types, a symmetric method
-- call that passes an argument, which may be a peer call.
local judged = {}
local any_open = false
local open = {}
for k = from, #paths do
local p = paths[k]
if not has_key(trees, p) then fail("rewrite_method_calls: roc-ast gave no tree for " .. p) end
local cands = candidates_in(trees[p], strip_suffix(basename(p), ".roc"))
for c in cands do
if c.why_left == "" then
any_open = true
open[p] = true
end
end
local method_calls = use_types and peer_method_calls(trees[p], ctx.symmetric) or {}
if #method_calls > 0 then
any_open = true
open[p] = true
end
judged[p] = {cands = cands, kind_counts = {}, open_count = 0, all_proven = false, unreached = false, method_calls = method_calls, peers = {}}
end
-- The types judge only open candidates, so with none, roc-types never runs.
local read_types = use_types and any_open
local reach = roots_of_files(ctx, paths, from, roots, read_types, open, trees, judged)
local root_of = reach.root_of
total.unreached = reach.unreached
-- `peers=undo`: a file's candidates are its peer method calls alone.
if undo then
for k = from, #paths do
local j = judged[paths[k]]
j.cands = j.peers
j.peers = {}
j.kind_counts = {}
end
end
for k = from, #paths do
local p = paths[k]
local j = judged[p]
j.all_proven = true
for c in j.cands do
if c.why_left == "" then
j.open_count = j.open_count + 1
if not c.proven then j.all_proven = false end
end
end
if j.open_count == 0 or j.unreached then j.all_proven = false end
end
if count_only then return counted_by_types(total, paths, from, judged, trees) end
local baselines = {}
for k = from, #paths do
local p = paths[k]
local j = judged[p]
local cands = j.unreached and {} or j.cands
local r = root_of[p]
if j.unreached then
-- Not begun: listed after the findings.
elseif j.all_proven and not has_key(ctx.confirmed, p) then
-- The programs left after this root's baseline (two, if it has none
-- yet), the confirm's checks and test, and this file's own trial,
-- should the confirm set it aside. Under `apply=1` each file in the
-- confirm also takes two `roc fmt`s, so only as many join as fit.
local room = MAX_PROGRAMS - ctx.programs_used - (has_key(baselines, r) and 0 or 2) - MAX_ROUNDS - 1 - PROGRAMS_PER_FILE
local files = {}
for m = k, #paths do
local q = paths[m]
local jq = judged[q]
if jq.all_proven and root_of[q] == r and not has_key(ctx.confirmed, q) and (not APPLY or 2 * (#files + 1) <= room) then push(files, {p = q, t = trees[q], cands = jq.cands}) end
end
if room < 0 or #files == 0 then
total.next = k
return total
end
confirm_proven_files(ctx, r, files, baseline_test_of(ctx, baselines, r))
for c in cands do c.from_line = 0 end
end
local kept_by_confirm = get(ctx.confirmed, p, 0)
if not j.unreached and j.open_count > 0 and kept_by_confirm == 0 and ctx.programs_used + PROGRAMS_PER_FILE > MAX_PROGRAMS then
total.next = k
return total
end
-- A file's type counts are added once it is begun, so a run that stops
-- before it leaves them to the next run.
if not j.unreached then total.files = total.files + 1 end
for kind in keys(j.kind_counts) do incr(ctx.type_kind_counts, kind, j.kind_counts[kind]) end
peer_findings(total, p, j)
if #cands > 0 then
local kept = kept_by_confirm
if kept == 0 and j.open_count > 0 then kept = try_file(ctx, p, trees[p], cands, r, baseline_test_of(ctx, baselines, r)) end
total.candidates = total.candidates + #cands
total.rewritten = total.rewritten + kept
for c in cands do
if c.why_left ~= "" then
total.left = total.left + 1
push(total.lines, p .. ":" .. c.line .. ": " .. c.module .. "." .. c.fn .. ": " .. c.why_left)
end
end
end
end
return total
end
-- ── the self-test ────────────────────────────────────────────────────────
function report_check(failures, passed, what)
if passed then
print("ok " .. what)
else
print("FAIL " .. what)
failures.count = failures.count + 1
end
return nil
end
-- For each plant: how many calls it must leave (`left`), a reason one of
-- them must give (`why`), the root it is judged on (`root`, the plant
-- itself by default), whether it runs with the types (`types`), and how
-- many confirms and trial rounds it takes. An entry with `file` judges that
-- plant's file, under its own name, and one with `with` reads a second
-- plant beside it, as a glob of two files would. A `stop` plant must stop its
-- run with that text. A plant with a `.want` file must come out as that
-- text; one that leaves calls and has none must come out as it was.
const EXPECT = {
Rewrite = {left = 0},
Chained = {left = 0},
FunctionValue = {left = 0},
Pipe = {left = 1, why = "the right of a `|>`"},
Own = {left = 0},
OtherType = {left = 1, why = "roc check: missing method"},
Decode = {left = 1, why = "on no rewritten call; the file is put back", root = "Breaks"},
Breaks = {left = 1, why = "roc check: missing method"},
Matched = {left = 1, why = "an argument with no span"},
Literal = {left = 8, why = "a number literal's type would default as a receiver"},
Ref = {left = 0},
Scrutinee = {left = 1, why = "roc check: missing method (on `text`'s definition)"},
Knock = {left = 2, why = "roc check: missing method"},
Header = {left = 0},
Typed = {left = 1, why = "the first argument is a List, not a Str", root = "TypedApp", types = true, confirms = 1, rounds = 0},
Proven = {left = 0, root = "TypedApp", types = true, confirms = 1, rounds = 0},
NoCalls = {left = 0, root = "TypedApp", types = true, confirms = 0, rounds = 0, no_types_run = true},
ProvenFails = {left = 2, why = "roc check: type mismatch", root = "TypedApp", types = true, confirms = 1, rounds = 2},
Unrooted = {stop = "the types need root=", types = true},
NotApp = {stop = "is not an app", root = "Proven", types = true},
Pin = {stop = "roc-types reads Roc nightly-2026-11-03-34bd006", root = "TypedApp", types = true, tree_pin = "nightly-2026-10-29-a0a9fc2"},
Second = {left = 0, root = "TypedApp,SecondApp", types = true, confirms = 1, rounds = 0},
-- A file no root reaches is listed, and the run goes on to the next.
Unreached = {file = "Proven", with = "Unreached", left = 0, unreached = 1, root = "TypedApp,SecondApp", types = true, confirms = 1, rounds = 0},
Beside = {file = "Proven", with = "NoCalls", left = 0, root = "TypedApp", types = true, confirms = 1, rounds = 0},
-- A qualified type whose last segment names the module proves nothing,
-- and the compiler agrees: the trial refuses both calls.
LastSegment = {left = 2, why = "the first argument is a Shelf.Book, not a Book", root = "TypedApp", types = true, confirms = 0, rounds = 0},
LastSegmentTried = {file = "LastSegment", left = 2, why = "roc check: missing method"},
-- A package's type module, imported as `pk.Meter`, proves its calls.
Packaged = {left = 0, root = "PkgApp", types = true, confirms = 1, rounds = 0},
-- `trials=0`: the types alone count, and the plant comes out as it was.
-- ProvenFails' three calls are all proven, where the trial leaves two:
-- the count's cost, held here.
TypedCount = {file = "Typed", count = true, proven = 1, unsettled = 0, left = 1, why = "the first argument is a List, not a Str", root = "TypedApp", types = true},
ProvenFailsCount = {file = "ProvenFails", count = true, proven = 3, unsettled = 0, left = 0, root = "TypedApp", types = true},
ProvenFrom = {file = "Proven", count = true, types_from = true, proven = 2, unsettled = 0, left = 0, root = "TypedApp", types = true},
LastSegmentCount = {file = "LastSegment", count = true, proven = 0, unsettled = 0, left = 2, why = "the first argument is a Shelf.Shelf, not a Shelf", root = "TypedApp", types = true},
PackagedCount = {file = "Packaged", count = true, proven = 1, unsettled = 0, left = 0, root = "PkgApp", types = true},
-- A symmetric function's peer calls stay module calls; `peers=undo`
-- turns its peer method calls back; every other function's calls turn
-- or stay as ever. Each `count` plant's `left` counts its listed lines,
-- the peer_receiver findings among them. Line 24 of each is the alias's.
Peers = {left = 6, why = "Peers.roc:24: U64.max: peers: `max` is symmetric and both arguments are U64s, so neither is the subject", root = "TypedApp", types = true, confirms = 1, rounds = 0, peers = 0},
PeersCount = {file = "Peers", count = true, proven = 5, unsettled = 0, left = 6, peers = 0, why = "Peers.roc:24: U64.max: peers: `max` is symmetric", root = "TypedApp", types = true},
PeerMethods = {undo = true, left = 0, peers = 0, root = "TypedApp", types = true, confirms = 1, rounds = 0},
-- What a rewrite leaves for the sweep, reported and not fixed: an import
-- it made unused, and a line it pushed past 100 columns; KeptImport is
-- MadeUnused's near miss, an import a type still names.
MadeUnused = {left = 0, made_unused = 1, made_says = "MadeUnused.roc:4: made_unused_import: `Ref` was used only by the calls the rewrite turned"},
KeptImport = {left = 0},
MadeLong = {left = 0, made_long = 1, made_says = "MadeLong.roc:11: made_long_line"},
PeerMethodsCount = {file = "PeerMethods", count = true, proven = 0, unsettled = 0, left = 6, peers = 6, why = "PeerMethods.roc:24: peer_receiver: `.max` is symmetric and its receiver and first argument are both U64s, so neither is the subject: U64.max(...)", root = "TypedApp", types = true},
-- A rewrite `roc check` passes and `roc test` refuses puts the file back;
-- a root that fails `roc check` before any rewrite stops the run; a file
-- `roc fmt` would change is not formatted after its rewrite.
TestChanged = {left = 2, why = "roc test changed: "},
BadBase = {stop = "fails before any rewrite: fix it first"},
Unformatted = {left = 0},
Loud = {left = 0},
}
-- The plants that hold no call and serve only as roots for other plants:
-- roc-types reads an app, and an app names its platform.
const ROOT_PLANTS = {TypedApp = true, TypedPf = true, SecondApp = true, PkgApp = true, PlantPkg = true, Meter = true, Shelf = true, Book = true, Hues = true}
-- The child run `plant=<name>`: copies the plants to a fresh scratch folder
-- and runs the one plant there with `apply=1`, then checks the result
-- against its `EXPECT` entry.
function self_test_plant(name)
if not has_key(EXPECT, name) then fail("rewrite_method_calls: self-test: no plant " .. name .. " in the table") end
local want = EXPECT[name]
local scratch = fresh_dir("scratch:", "methods")
for f in ls(PLANTS_DIR) do replace(scratch .. "/" .. f, read(PLANTS_DIR .. "/" .. f)) end
local failures = {count = 0}
local file = get(want, "file", name)
local p = scratch .. "/" .. file .. ".roc"
local paths = {p}
if has_key(want, "with") then push(paths, scratch .. "/" .. want.with .. ".roc") end
local with_types = has_key(want, "types")
-- A plant with `tree_pin` runs as though the tree pinned that Roc.
local roc = has_key(want, "tree_pin") and real("tools:roc-" .. want.tree_pin .. "/roc") or roc_bin("rewrite_method_calls", SELF_TEST)
local roots = {}
for r in split(get(want, "root", ""), ",") do
if r ~= "" then push(roots, scratch .. "/" .. r .. ".roc") end
end
-- A plant with `types_from` reads the types from a file, as a gate keeps
-- them: roc-types' output on the root, written here first.
local types_from = ""
if has_key(want, "types_from") then
types_from = scratch .. "/root.types"
replace(types_from, must(run({real(roc_types_exe(roc)), real(roots[1])}, {timeout_ms = 300000, whole = 64000000})).out)
end
local count_only = has_key(want, "count")
local got = run_all(paths, join(roots, ","), 1, nil, with_types, roc, {count_only = count_only, types_from = types_from, undo = has_key(want, "undo")})
if has_key(want, "stop") then fail("rewrite_method_calls: self-test: " .. name .. " ran to its end, and was to stop: " .. want.stop) end
if count_only then
report_check(failures, got.rewritten == want.proven, name .. ": " .. got.rewritten .. " proven, want " .. want.proven)
report_check(failures, got.unsettled == want.unsettled, name .. ": " .. got.unsettled .. " unsettled, want " .. want.unsettled)
report_check(failures, read(p) == read(PLANTS_DIR .. "/" .. file .. ".roc"), name .. ": counted, and left as it was")
end
if has_key(want, "peers") then report_check(failures, got.peers == want.peers, name .. ": " .. got.peers .. " peer_receiver, want " .. want.peers) end
if not has_key(want, "stop") then
local made = made_by_rewrites(got.ctx)
local want_unused = get(want, "made_unused", 0)
local want_long = get(want, "made_long", 0)
report_check(failures, made.unused == want_unused and made.long == want_long, name .. ": " .. made.unused .. " made_unused_import and " .. made.long .. " made_long_line, want " .. want_unused .. " and " .. want_long .. (#made.lines > 0 and (" (" .. join(made.lines, "; ") .. ")") or ""))
if has_key(want, "made_says") then report_check(failures, contains(join(made.lines, "\n"), want.made_says), name .. ": reports " .. want.made_says) end
end
if types_from ~= "" then report_check(failures, got.ctx.programs_used == 1, name .. ": the types read from a file, so roc-ast the one program (" .. got.ctx.programs_used .. ")") end
local want_unreached = get(want, "unreached", 0)
report_check(failures, #got.unreached == want_unreached, name .. ": " .. #got.unreached .. " not reached by a root, want " .. want_unreached .. " (" .. join(got.unreached, ", ") .. ")")
local left = got.lines
report_check(failures, #left == want.left, name .. ": " .. #left .. " left, want " .. want.left .. (#left > 0 and (" (" .. join(left, "; ") .. ")") or ""))
if has_key(want, "why") then report_check(failures, #left > 0 and contains(join(left, "\n"), want.why), name .. ": left because " .. want.why) end
local want_path = PLANTS_DIR .. "/" .. file .. ".want"
if exists(want_path) and not count_only then report_check(failures, read(p) == read(want_path), name .. ": comes out as " .. file .. ".want") end
-- In Typed, the types turn one call and leave the other, so the trial
-- decides neither.
local kinds = got.ctx.type_kind_counts
if name == "Typed" then report_check(failures, #keys(kinds) == 2 and get(kinds, "another type", 0) == 1 and get(kinds, "the module's type", 0) == 1, name .. ": by type, " .. json_write(kinds)) end
local confirms = got.ctx.confirms
local rounds = got.ctx.rounds
local want_confirms = get(want, "confirms", 0)
report_check(failures, confirms == want_confirms, name .. ": " .. confirms .. " confirm(s), want " .. want_confirms)
if has_key(want, "rounds") then report_check(failures, rounds == want.rounds, name .. ": " .. rounds .. " round(s), want " .. want.rounds) end
if not with_types then report_check(failures, #keys(kinds) == 0 and #keys(got.ctx.types_by_root) == 0, name .. ": under types=0, no roc-types run") end
-- With the types, roc-types runs once per root when a candidate is open,
-- and not at all on a file with none (`no_types_run`).
if with_types then
local runs = #keys(got.ctx.types_by_root)
local want_runs = has_key(want, "no_types_run") and 0 or #roots
report_check(failures, runs == want_runs, name .. ": " .. runs .. " roc-types run(s), want " .. want_runs)
end
if want.left > 0 and not exists(want_path) then report_check(failures, read(p) == read(PLANTS_DIR .. "/" .. file .. ".roc"), name .. ": put back as it was") end
if has_key(want, "with") then report_check(failures, read(paths[2]) == read(PLANTS_DIR .. "/" .. want.with .. ".roc"), name .. ": " .. want.with .. " left as it was") end
if failures.count > 0 then fail("rewrite_method_calls: self-test: " .. name .. ": " .. failures.count .. " failed") end
remove_tree(scratch)
return nil
end
-- Runs every plant in a child run of its own; a failed plant is named, and
-- the rest still run.
function self_test()
if not exists(ROC_TYPES_EXE) then fail("rewrite_method_calls: self-test: no " .. ROC_TYPES_EXE .. ", which the plants marked `types` are judged by: " .. ROC_TYPES_INSTALL) end
local failed = {}
local globbed = paths_of_globs(PLANTS_DIR .. "/Proven.roc, " .. PLANTS_DIR .. "/NoC*.roc," .. PLANTS_DIR .. "/Proven.roc")
local globs_held = #globbed == 2 and basename(globbed[1]) == "Proven.roc" and basename(globbed[2]) == "NoCalls.roc"
print((globs_held and "ok " or "FAIL ") .. "glob=: two globs and a repeat give Proven.roc, then NoCalls.roc, each once (" .. join(globbed, ", ") .. ")")
if not globs_held then push(failed, "glob=") end
for file in ls(PLANTS_DIR) do
local name = strip_suffix(file, ".roc")
if ends_with(file, ".roc") and not has_key(EXPECT, name) and not has_key(ROOT_PLANTS, name) then
print("FAIL " .. file .. ": a plant the table does not judge")
push(failed, file)
end
end
for name in sort(keys(EXPECT)) do
local r = run({"shale", "--root", ".", THIS_SCRIPT, "self_test=1", "plant=" .. name}, {timeout_ms = 3600000, tail = 200})
local stop = get(EXPECT[name], "stop", "")
if stop ~= "" then
local held = r.ended == "exit" and r.code ~= 0 and contains(r.out, stop)
print((held and "ok " or "FAIL ") .. name .. ": stops, saying " .. stop .. (held and "" or (": " .. trim(r.out))))
if not held then push(failed, name) end
else
for l in lines(r.out) do
if not starts_with(l, "── budgets") then print(l) end
end
if r.ended ~= "exit" or r.code ~= 0 then push(failed, name) end
end
end
if #failed > 0 then fail("rewrite_method_calls: self-test: " .. #failed .. " plant(s) failed: " .. join(failed, ", ")) end
print("rewrite_method_calls: self-test: every plant as it says")
end
if PLANT ~= "" and not SELF_TEST then
fail("rewrite_method_calls: plant= is for the self-test's child runs, and needs self_test=1")
elseif SELF_TEST and PLANT ~= "" then
self_test_plant(PLANT)
elseif SELF_TEST then
self_test()
else
local paths = paths_of_globs(GLOB)
local total = run_all(paths, ROOT, FROM, nil, USE_TYPES, roc_bin("rewrite_method_calls", SELF_TEST), {count_only = COUNT_ONLY, types_from = TYPES_FROM, undo = UNDO})
local summary = (UNDO and "peers=undo, " or "") .. (APPLY and "" or "dry run: ") .. "files " .. total.files .. ", candidates " .. total.candidates .. ", rewritten " .. total.rewritten .. ", left " .. total.left .. ", peer_receiver " .. total.peers .. ", programs " .. total.ctx.programs_used .. " (checks: " .. total.ctx.confirms .. " confirming proven calls, " .. total.ctx.rounds .. " in trial rounds)"
if COUNT_ONLY then summary = "count: files " .. total.files .. ", candidates " .. total.candidates .. ", proven " .. total.rewritten .. ", unsettled " .. total.unsettled .. ", left " .. total.left .. ", peer_receiver " .. total.peers .. ", programs " .. total.ctx.programs_used .. " (no trials: the types alone decide)" end
if total.next > 0 then summary = summary .. ", in files " .. FROM .. " to " .. (total.next - 1) .. " of " .. #paths .. ": a run holds " .. MAX_PROGRAMS .. " programs; go on with from=" .. total.next end
local made = made_by_rewrites(total.ctx)
summary = summary .. ", made_unused_import " .. made.unused .. ", made_long_line " .. made.long
local finding_lines = total.lines
for l in made.lines do push(finding_lines, l) end
if USE_TYPES then
local kinds = {}
for kind in sort(keys(total.ctx.type_kind_counts)) do push(kinds, kind .. " " .. total.ctx.type_kind_counts[kind]) end
push(finding_lines, "types: the first arguments of the candidates the types judged: " .. join(kinds, ", "))
end
print_findings(summary, finding_lines)
for u in total.unreached do print("not reached by " .. ROOT .. ": " .. u) end
if #total.unreached > 0 then fail("rewrite_method_calls: no root reaches " .. #total.unreached .. " file(s) with a call to try, listed above: their calls were left untried") end
end