map_file

Roc

It also imports Item, Mask, Paths, Split, Words from the C splitter.

cookbook/c/map_file/map_file.roc, 175 lines

## map_file, in Roc on Shale's platform (roc_platform/README.md): a file of
## Shale's C mapped, each top-level item one line, `first-last kind name`,
## from the splitter the C recipes share (cookbook/c/items/, a package),
## which reads the dialect c/check_discipline.shale holds. Its launcher,
## cookbook/c/map_file.shale, is how it is run, and its header says the
## arguments. check_goldens.shale, beside this, holds its output on the
## plants to its goldens, line for line.
##
##   shale cookbook:c/map_file.shale file=c/script/vm.c
##   shale cookbook:c/map_file.shale tree=c
##   shale cookbook:c/map_file.shale self_test=1
##
## The effects: `Shale.arg!` for the arguments, `Shale.glob!` for a tree's
## files, `Shale.read!` for each one's text, and `Shale.print!` and
## `Shale.fail!` for the verdict. The splitting is the package's, plain
## Roc; SelfTest, beside this, holds it to the plants.
## budget: steps=50000000 arena_bytes=1000000000 roc_cpu_ms=600000
app [main!] {
	items: "../items/main.roc",
	pf: platform "../../../roc_platform/platform/main.roc",
}

import pf.Shale
import items.Item
import items.Paths
import items.Split
import items.Words
import SelfTest

main! : {} => {}
main! = |{}| {
	if integer_or_stop!("self_test", Shale.arg!("self_test", "0")) == 1 {
		SelfTest.run!({})
	} else {
		file = Shale.arg!("file", "")
		tree = Shale.arg!("tree", "")
		if (file == "") == (tree == "") {
			Shale.fail!("map_file: give `file=<a .c or .h>` or `tree=<a folder>`, one of them")
		} else if file != "" {
			for line in map_lines(split_or_stop!(file, read_text!(file))) {
				Shale.print!(line)
			}
		} else {
			map_tree!(tree)
		}
	}
}

## A value given as `name=`, which must be an integer, as Shale's `arg` reads
## one whose default is.
integer_or_stop! : Str, Str => I64
integer_or_stop! = |name, given| {
	match I64.from_str(given) {
		Ok(value) => value
		Err(_) => {
			Shale.fail!("map_file: ${name}=${given} is not an integer")
			0
		}
	}
}

## The map of the items, one `first-last kind name` a line.
map_lines : List(Item) -> List(Str)
map_lines = |items|
	items.map(|item| "${item.first.to_str()}-${item.last.to_str()} ${Item.kind_name(item.kind)} ${item.name}")

## The file's text. A file that is not there stops the run.
read_text! : Str => Str
read_text! = |path|
	match Shale.read!(path) {
		Found(text) => text
		Missing => {
			Shale.fail!("map_file: ${path} is not there")
			""
		}
	}

## The file's items, or the run stopped with the line the dialect does not
## account for.
split_or_stop! : Str, Str => List(Item)
split_or_stop! = |path, text|
	match Split.items({ path, text, uses: Bool.False }) {
		Ok(items) => items
		Err(why) => {
			Shale.fail!(why)
			[]
		}
	}

## The C files under the folder, sorted, any folder named `out` (c/out, the
## build's output) left out. A folder that is not there stops the run, in
## the words of the Shale original's walk: a check that can't run fails.
c_files_under! : Str => List(Str)
c_files_under! = |folder| {
	if Shale.list!(folder) == Missing {
		Shale.fail!("`walk(\"${folder}\")`: not found (FileNotFound)")
	}
	paths = Shale.glob!("${folder}/**/*.c").concat(Shale.glob!("${folder}/**/*.h"))
	paths.keep_if(|path| !(Paths.is_in_out_folder(folder, path))).sort_with(Words.byte_order)
}

## Every C file under the folder split and accounted for, in one line: the
## files, their lines and their items by kind.
map_tree! : Str => {}
map_tree! = |folder| {
	files = c_files_under!(folder)
	var $kinds = []
	$line_count : U64
	var $line_count = 0
	$item_count : U64
	var $item_count = 0
	for path in files {
		text = read_text!(path)
		items = split_or_stop!(path, text)
		match accounted(path, Split.lines(text), items) {
			Ok(count) => {
				$line_count = $line_count + count
			}
			Err(why) => Shale.fail!(why)
		}
		$kinds = $kinds.concat(items.map(|item| Item.kind_name(item.kind)))
		$item_count = $item_count + items.len()
	}
	names = distinct($kinds).sort_with(Words.byte_order)
	parts = names.map(|name| "${$kinds.count_if(|kind| kind == name).to_str()} ${name}")
	lines = "${$line_count.to_str()} lines, each in one item or between them"
	counts = "${$item_count.to_str()} items: ${Str.join_with(parts, ", ")}"
	Shale.print!("PASS c items: ${files.len().to_str()} files under ${folder}, ${lines}; ${counts}")
}

## Each line of the file in exactly one of the items, or blank, or a `//`
## comment line between them: the count of its lines, or the error naming
## the line that is not.
accounted : Str, List(List(U8)), List(Item) -> Try(U64, Str)
accounted = |path, lines, items| {
	# Each line's owner, by its number (place 0 is no line's).
	var $owners = List.repeat(Unowned, lines.len() + 1)
	for item in items {
		var $at = item.first
		while $at <= item.last {
			match $owners.get($at) {
				Ok(Owned(owner)) => return Err("${path}:${$at.to_str()}: in two items, `${owner}` and `${item.name}`")
				_ => {}
			}
			$owners = match $owners.set($at, Owned(item.name)) {
				Ok(owners) => owners
				Err(_) => crash "map_file: an item past its file's last line"
			}
			$at = $at + 1
		}
	}
	$number : U64
	var $number = 0
	for raw in lines {
		$number = $number + 1
		is_owned = $owners.get($number) != Ok(Unowned)
		if !(is_owned) and !(raw.is_empty()) and !(raw.starts_with(['/', '/'])) {
			return Err("${path}:${$number.to_str()}: in no item: ${Str.from_utf8_lossy(raw)}")
		}
	}
	Ok($number)
}

## Each text once, in the order first seen.
distinct : List(Str) -> List(Str)
distinct = |texts|
	texts.fold(
		[],
		|seen, text|
			if seen.contains(text) {
				seen
			} else {
				seen.append(text)
			},
	)

cookbook/c/map_file/SelfTest.roc, 202 lines

## map_file's self-test: the splitter held to the plants in
## cookbook/c/plants/map_file/, a header and a .c file holding an item of
## each kind, each mapped and held to its map, its comments, heads, bodies
## and uses; then each plant in breaks/ split, which must stop naming its
## file and the line it breaks. The masker is held first, to two lines.
import pf.Shale
import items.Item
import items.Mask
import items.Split

SelfTest := [].{

	## Every check, each a stop when it fails, then the PASS line.
	run! : {} => {}
	run! = |{}| {
		masker_checks = check_masker!({})
		header_checks = check_header!({})
		source_checks = check_source!({})
		break_checks = check_breaks!({})
		checks = masker_checks + header_checks + source_checks + break_checks
		kinds = "each item kind mapped and ${break_checks.to_str()} shape breaks stopped at their lines"
		Shale.print!("PASS map_file self-test: ${checks.to_str()} checks, ${kinds}")
	}
}

## Where the plants are.
plants : Str
plants = "cookbook/c/plants/map_file"

## `got` equal to `want`, or the self-test stops, naming `what`.
same! : Str, Str, Str => {}
same! = |what, got, want|
	if got != want {
		Shale.fail!("map_file self-test: ${what} is\n${got}\nit should be\n${want}")
	}

## The masker: every column kept, a `"` in a character literal the
## literal's, a `//` in a string the string's, a macro's `/* */` blanked.
check_masker! : {} => U64
check_masker! = |{}| {
	raw = "    if (c == '\"') { x(\"a // b\"); } // c"
	same!("the mask of `${raw}`", mask(raw), "    if (c == ' ') { x(\"      \"); }     ")
	macro_line = "#define M(x) /* it's */ \\"
	same!("the mask of `${macro_line}`", mask(macro_line), "#define M(x) ${" ".repeat(10)} \\")
	2
}

mask : Str -> Str
mask = |line| Mask.text(Mask.masked(line.to_utf8()))

## The plant's items, with their uses, or the self-test stopped.
split_plant! : Str => List(Item)
split_plant! = |path| {
	text = match Shale.read!(path) {
		Found(found) => found
		Missing => {
			Shale.fail!("map_file self-test: ${path} is not there")
			""
		}
	}
	match Split.items({ path, text, uses: Bool.True }) {
		Ok(items) => items
		Err(why) => {
			Shale.fail!(why)
			[]
		}
	}
}

## The map of the items, one `first-last kind name` a line.
map_text : List(Item) -> Str
map_text = |items| {
	map_lines = items.map(|item| "${item.first.to_str()}-${item.last.to_str()} ${Item.kind_name(item.kind)} ${item.name}")
	Str.join_with(map_lines, "\n")
}

## The item of the kind and name, or the self-test stopped.
item_named! : List(Item), Item.Kind, Str => Item
item_named! = |items, kind, name|
	match items.find_first(|item| item.kind == kind and item.name == name) {
		Ok(item) => item
		Err(_) => {
			Shale.fail!("map_file self-test: no ${Item.kind_name(kind)} `${name}`")
			Item.new(kind, name, { first: 0, last: 0 })
		}
	}

## An item's lines as `comment a-b, sig c-d, body e-f`.
spans : Item -> Str
spans = |item| {
	comment = "comment ${item.comment_first.to_str()}-${item.comment_last.to_str()}"
	sig = "sig ${item.sig_first.to_str()}-${item.sig_last.to_str()}"
	"${comment}, ${sig}, body ${item.body_first.to_str()}-${item.body_last.to_str()}"
}

joined : List(Str) -> Str
joined = |names| Str.join_with(names, ",")

## kinds.h: its map, then its items' spans, macros, enumerators and uses.
check_header! : {} => U64
check_header! = |{}| {
	path = "${plants}/kinds.h"
	items = split_plant!(path)
	map = [
		"2-3 guard SHALE_KINDS_H",
		"5-5 include stdint.h",
		"6-6 include slice.h",
		"9-9 macro KINDS_MAX",
		"10-17 macro KINDS_DEFINE",
		"19-19 directive if defined",
		"20-20 macro KINDS_LINUX",
		"21-21 directive endif",
		"23-26 struct KindsPair",
		"28-28 enum KindsKind",
		"30-33 union KindsWord",
		"35-35 typedef KindsHook",
		"37-40 enum KINDS_FIRST",
		"42-42 generator KindsPairs",
		"43-43 generator KindsVec",
		"45-45 static_assert KindsPair",
		"47-47 function kinds_sum",
		"51-58 function kinds_name",
		"60-61 prototype kinds_check",
		"63-66 data KINDS_NAMES",
		"67-67 data KINDS_ONE",
		"69-69 guard SHALE_KINDS_H",
	]
	same!("${path}'s map", map_text(items), Str.join_with(map, "\n"))
	defined = item_named!(items, Macro, "KINDS_DEFINE")
	same!("KINDS_DEFINE's makes", joined(defined.makes), "make,first")
	same!("KINDS_DEFINE's spans", spans(defined), "comment 0-0, sig 10-10, body 11-17")
	same!("KINDS_MAX's spans", spans(item_named!(items, Macro, "KINDS_MAX")), "comment 8-8, sig 9-9, body 0-0")
	same!("KindsKind's enumerators", joined(item_named!(items, Enum, "KindsKind").enumerators), "KINDS_A,KINDS_B")
	anonymous = item_named!(items, Enum, "KINDS_FIRST")
	same!("the anonymous enum's enumerators", joined(anonymous.enumerators), "KINDS_FIRST,KINDS_SECOND")
	vec = item_named!(items, Generator, "KindsVec")
	same!("KindsVec's macro and type", "${vec.macro} ${vec.held_type}", "VEC_DEFINE KindsPair")
	sum = item_named!(items, Function, "kinds_sum")
	sum_said = "${sum.storage} | ${sum.return_type} | ${spans(sum)} | ${joined(sum.uses)}"
	same!("kinds_sum", sum_said, "static inline | uint32_t | comment 0-0, sig 47-47, body 47-47 | p")
	named = item_named!(items, Function, "kinds_name")
	named_said = "${named.return_type} | ${spans(named)} | ${joined(named.uses)}"
	same!("kinds_name", named_said, "Str | comment 49-50, sig 51-51, body 52-57 | KINDS_A,KINDS_LINUX,S,k,kinds_label")
	check = item_named!(items, Prototype, "kinds_check")
	same!("kinds_check", "${check.return_type} | ${spans(check)}", "Status | comment 0-0, sig 60-61, body 0-0")
	same!("KINDS_NAMES's spans", spans(item_named!(items, Data, "KINDS_NAMES")), "comment 0-0, sig 63-63, body 64-65")
	12
}

## kinds.c: its map, then its function's, test's and test list's uses.
check_source! : {} => U64
check_source! = |{}| {
	path = "${plants}/kinds.c"
	items = split_plant!(path)
	map = [
		"2-2 include test.h",
		"4-4 data kinds_hook",
		"6-11 function kinds_wrapped",
		"13-15 test kinds_test",
		"17-19 test_list TEST_MAIN",
		"21-23 function main",
	]
	same!("${path}'s map", map_text(items), Str.join_with(map, "\n"))
	wrapped = item_named!(items, Function, "kinds_wrapped")
	same!("kinds_wrapped", "${spans(wrapped)} | ${joined(wrapped.uses)}", "comment 0-0, sig 6-7, body 8-10 | a,b,kinds_add,other,p,sum")
	same!("kinds_test's uses", joined(item_named!(items, Test, "kinds_test").uses), "EXPECT,kinds_wrapped")
	same!("TEST_MAIN's uses", joined(item_named!(items, TestList, "TEST_MAIN").uses), "TEST_MAIN,kinds_test")
	same!("main's spans", spans(item_named!(items, Function, "main")), "comment 0-0, sig 21-21, body 22-22")
	5
}

## Each break stops, naming its file, its line and why.
check_breaks! : {} => U64
check_breaks! = |{}| {
	breaks = [
		("indented.c", "indented.c:3: an indented line outside every item"),
		("column0.c", "column0.c:2: a line at column 0 that opens no item the dialect knows"),
		("in_body.c", "in_body.c:3: a line at column 0 inside the function `f` opened at line 2, which only a `}` may close"),
		("unclosed.c", "unclosed.c:2: the function `f` that no `}` at column 0 closes"),
		("no_guard.h", "no_guard.h:1: a header with no `#ifndef SHALE_NO_GUARD_H`"),
		("no_endif.h", "no_endif.h:5: a header whose last item is not its guard's `#endif`"),
		("bad_test.c", "bad_test.c:2: a `TEST(` line that is not `TEST(name) {`"),
		("wrapped_head.c", "wrapped_head.c:3: a line at column 0 inside the head opened at line 2"),
		("bad_generator.c", "bad_generator.c:2: a generator line whose name and type this reader can't find"),
	]
	for (file, said) in breaks {
		path = "${plants}/breaks/${file}"
		wanted = "${plants}/breaks/${said}: "
		text = match Shale.read!(path) {
			Found(found) => found
			Missing => ""
		}
		match Split.items({ path, text, uses: Bool.False }) {
			Ok(items) => Shale.fail!("map_file self-test: ${path} split, with ${items.len().to_str()} items; it should stop with ${said}")
			Err(why) =>
				if !(why.starts_with(wanted)) {
					Shale.fail!("map_file self-test: ${path} stopped with `${why}`; it should stop with `${wanted}<the line>`")
				}
		}
	}
	breaks.len()
}

Shale original

cookbook/c/map_file.shale, 192 lines, at 9c804881

The libraries it loads: cookbook/c/items.shale (499 lines).

-- Maps a file of Shale's C: each top-level item, one a line, as
-- `first-last kind name`, from cookbook/c/items.shale's splitter, which
-- reads the dialect c/check_discipline.shale holds (that library's header
-- has the kinds and what each item carries).
--
--   shale cookbook:c/map_file.shale file=c/script/vm.c
--   shale cookbook:c/map_file.shale tree=c         every .c and .h under c/
--                                                  (c/out left out) split,
--                                                  each line accounted for
--   shale cookbook:c/map_file.shale self_test=1    the plants
--
-- `tree=` splits every file and proves the split: each line is in exactly
-- one item, or blank, or a `//` comment line between items, and it prints
-- one line, the files, lines and items by kind. A line the dialect does not
-- account for stops the run naming its file and line, in either mode.
--
-- `tree=c` takes about 17 million steps and a seventh of a second.
--
-- `self_test=1` maps the plants in cookbook/c/plants/map_file/ (a header and
-- a .c file holding an item of each kind) and holds each to its map, its
-- comments, heads, bodies and uses, then splits each plant in breaks/,
-- which must stop naming its file and the line it breaks.
--
-- budget: steps=50000000

use("./items.shale")

const PLANTS = "cookbook/c/plants/map_file"

-- The map of the items in `items`, one `first-last kind name` a line.
function map_lines(items)
  local out = {}
  for it in items do push(out, it.first .. "-" .. it.last .. " " .. it.kind .. " " .. it.name) end
  return out
end

-- The C files under `dir`, sorted, c/out (the build's output) left out.
function c_files_under(dir)
  local files = {}
  for e in walk_all(dir, {kind = "file", skip = "out"}) do
    if ends_with(e.path, ".c") or ends_with(e.path, ".h") then push(files, e.path) end
  end
  sort(files)
  return files
end

-- Each line of `p` in exactly one of `items`, or blank, or a `//` comment
-- line between them, or the run stops naming the line. Gives the count of
-- lines.
function accounted(p, items)
  local all = lines(read(p))
  local owner = {}
  for it in items do
    local k = it.first
    while k <= it.last do
      if has_key(owner, "" .. k) then fail(p .. ":" .. k .. ": in two items, `" .. owner["" .. k] .. "` and `" .. it.name .. "`") end
      owner["" .. k] = it.name
      k = k + 1
    end
  end
  local n = 0
  for raw in all do
    n = n + 1
    if not has_key(owner, "" .. n) and raw ~= "" and not starts_with(raw, "//") then fail(p .. ":" .. n .. ": in no item: " .. raw) end
  end
  return n
end

-- Every C file under `dir` split and accounted for, in one line.
function map_tree(dir)
  local files = c_files_under(dir)
  local kinds = {}
  local total = 0
  local count = 0
  for p in files do
    local items = c_items(p)
    total = total + accounted(p, items)
    for it in items do incr(kinds, it.kind) end
    count = count + #items
    yield()
  end
  local parts = {}
  local names = keys(kinds)
  sort(names)
  for k in names do push(parts, kinds[k] .. " " .. k) end
  print("PASS c items: " .. #files .. " files under " .. dir .. ", " .. total .. " lines, each in one item or between them; " .. count .. " items: " .. join(parts, ", "))
  return nil
end

-- `got` equal to `want`, or the self-test fails, naming `what`.
function same_or_fail(what, got, want)
  if got ~= want then fail("map_file self-test: " .. what .. " is\n" .. got .. "\nit should be\n" .. want) end
  return nil
end

-- The item named `name` of kind `kind` in `items`.
function item_named(items, kind, name)
  for it in items do
    if it.kind == kind and it.name == name then return it end
  end
  fail("map_file self-test: no " .. kind .. " `" .. name .. "`")
end

-- An item's lines as `comment a-b, sig c-d, body e-f`.
function spans(it)
  return "comment " .. it.comment_first .. "-" .. it.comment_last .. ", sig " .. it.sig_first .. "-" .. it.sig_last .. ", body " .. it.body_first .. "-" .. it.body_last
end

function self_test()
  local checks = 0
  -- The masker: every column kept, a `"` in a character literal the
  -- literal's, a `//` in a string the string's, a macro's `/* */` blanked.
  local raw = [=[    if (c == '"') { x("a // b"); } // c]=]
  same_or_fail("the mask of `" .. raw .. "`", c_mask(raw), [=[    if (c == ' ') { x("      "); }     ]=])
  local macro_line = [=[#define M(x) /* it's */ \]=]
  same_or_fail("the mask of `" .. macro_line .. "`", c_mask(macro_line), "#define M(x) " .. rep(" ", 10) .. " \\")
  checks = checks + 2
  local h = PLANTS .. "/kinds.h"
  local hi = c_items(h, {uses = true})
  accounted(h, hi)
  same_or_fail(h .. "'s map", join(map_lines(hi), "\n"), join({
    "2-3 guard SHALE_KINDS_H", "5-5 include stdint.h", "6-6 include slice.h", "9-9 macro KINDS_MAX",
    "10-17 macro KINDS_DEFINE", "19-19 directive if defined", "20-20 macro KINDS_LINUX", "21-21 directive endif",
    "23-26 struct KindsPair", "28-28 enum KindsKind", "30-33 union KindsWord", "35-35 typedef KindsHook",
    "37-40 enum KINDS_FIRST", "42-42 generator KindsPairs", "43-43 generator KindsVec", "45-45 static_assert KindsPair",
    "47-47 function kinds_sum", "51-58 function kinds_name", "60-61 prototype kinds_check", "63-66 data KINDS_NAMES",
    "67-67 data KINDS_ONE", "69-69 guard SHALE_KINDS_H"}, "\n"))
  checks = checks + 1
  local macro = item_named(hi, "macro", "KINDS_DEFINE")
  same_or_fail("KINDS_DEFINE's makes", join(macro.makes, ","), "make,first")
  same_or_fail("KINDS_DEFINE's spans", spans(macro), "comment 0-0, sig 10-10, body 11-17")
  same_or_fail("KINDS_MAX's spans", spans(item_named(hi, "macro", "KINDS_MAX")), "comment 8-8, sig 9-9, body 0-0")
  same_or_fail("KindsKind's enumerators", join(item_named(hi, "enum", "KindsKind").enumerators, ","), "KINDS_A,KINDS_B")
  same_or_fail("the anonymous enum's enumerators", join(item_named(hi, "enum", "KINDS_FIRST").enumerators, ","), "KINDS_FIRST,KINDS_SECOND")
  local vec = item_named(hi, "generator", "KindsVec")
  same_or_fail("KindsVec's macro and type", vec.macro .. " " .. vec.of, "VEC_DEFINE KindsPair")
  local sum = item_named(hi, "function", "kinds_sum")
  same_or_fail("kinds_sum", sum.storage .. " | " .. sum.type .. " | " .. spans(sum) .. " | " .. join(sum.uses, ","), "static inline | uint32_t | comment 0-0, sig 47-47, body 47-47 | p")
  local name = item_named(hi, "function", "kinds_name")
  same_or_fail("kinds_name", name.type .. " | " .. spans(name) .. " | " .. join(name.uses, ","), "Str | comment 49-50, sig 51-51, body 52-57 | KINDS_A,KINDS_LINUX,S,k,kinds_label")
  local check = item_named(hi, "prototype", "kinds_check")
  same_or_fail("kinds_check", check.type .. " | " .. spans(check), "Status | comment 0-0, sig 60-61, body 0-0")
  same_or_fail("KINDS_NAMES's spans", spans(item_named(hi, "data", "KINDS_NAMES")), "comment 0-0, sig 63-63, body 64-65")
  checks = checks + 11
  local c = PLANTS .. "/kinds.c"
  local ci = c_items(c, {uses = true})
  accounted(c, ci)
  same_or_fail(c .. "'s map", join(map_lines(ci), "\n"), join({
    "2-2 include test.h", "4-4 data kinds_hook", "6-11 function kinds_wrapped", "13-15 test kinds_test",
    "17-19 test_list TEST_MAIN", "21-23 function main"}, "\n"))
  checks = checks + 1
  local wrapped = item_named(ci, "function", "kinds_wrapped")
  same_or_fail("kinds_wrapped", spans(wrapped) .. " | " .. join(wrapped.uses, ","), "comment 0-0, sig 6-7, body 8-10 | a,b,kinds_add,other,p,sum")
  same_or_fail("kinds_test's uses", join(item_named(ci, "test", "kinds_test").uses, ","), "EXPECT,kinds_wrapped")
  same_or_fail("TEST_MAIN's uses", join(item_named(ci, "test_list", "TEST_MAIN").uses, ","), "TEST_MAIN,kinds_test")
  same_or_fail("main's spans", spans(item_named(ci, "function", "main")), "comment 0-0, sig 21-21, body 22-22")
  checks = checks + 4
  -- Each break stops, naming its file, its line and why.
  local breaks = {
    {f = "indented.c", said = "indented.c:3: an indented line outside every item"},
    {f = "column0.c", said = "column0.c:2: a line at column 0 that opens no item the dialect knows"},
    {f = "in_body.c", said = "in_body.c:3: a line at column 0 inside the function `f` opened at line 2, which only a `}` may close"},
    {f = "unclosed.c", said = "unclosed.c:2: the function `f` that no `}` at column 0 closes"},
    {f = "no_guard.h", said = "no_guard.h:1: a header with no `#ifndef SHALE_NO_GUARD_H`"},
    {f = "no_endif.h", said = "no_endif.h:5: a header whose last item is not its guard's `#endif`"},
    {f = "bad_test.c", said = "bad_test.c:2: a `TEST(` line that is not `TEST(name) {`"},
    {f = "wrapped_head.c", said = "wrapped_head.c:3: a line at column 0 inside the head opened at line 2"},
    {f = "bad_generator.c", said = "bad_generator.c:2: a generator line whose name and type this reader can't find"},
  }
  for b in breaks do
    local p = PLANTS .. "/breaks/" .. b.f
    local r = attempt(c_items, p)
    if r.ok then fail("map_file self-test: " .. p .. " split, with " .. #r.value .. " items; it should stop with " .. b.said) end
    if not starts_with(r.error, PLANTS .. "/breaks/" .. b.said .. ": ") then fail("map_file self-test: " .. p .. " stopped with `" .. r.error .. "`; it should stop with `" .. PLANTS .. "/breaks/" .. b.said .. ": <the line>`") end
    checks = checks + 1
  end
  print("PASS map_file self-test: " .. checks .. " checks, each item kind mapped and " .. #breaks .. " shape breaks stopped at their lines")
  return nil
end

if arg("self_test", 0) == 1 then
  self_test()
else
  local file = arg("file", "")
  local tree = arg("tree", "")
  if (file == "") == (tree == "") then fail("map_file: give `file=<a .c or .h>` or `tree=<a folder>`, one of them") end
  if file ~= "" then
    for l in map_lines(c_items(file)) do print(l) end
  else
    map_tree(tree)
  end
end