find_clones

Roc

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

cookbook/c/find_clones/find_clones.roc, 142 lines

## find_clones, in Roc on Shale's platform (roc_platform/README.md): the
## same code twice in Shale's C, from the splitter the C recipes share
## (cookbook/c/items/, a package), as twin functions of one shape and runs
## of lines alike as written. Its launcher, cookbook/c/find_clones.shale, is
## how it is run, and its header says the arguments and the rules.
## check_goldens.shale, beside this, holds its output on the plants to its
## goldens, line for line.
##
##   shale cookbook:c/find_clones.shale dir=c/host score=70
##   shale cookbook:c/find_clones.shale self_test=1
##
## The effects: `Shale.arg!` for the arguments, `Shale.glob!` for the files,
## `Shale.read!` for each one's text, and `Shale.print!` and `Shale.fail!`
## for the verdict. Shape, beside this, reads a function's counted lines;
## Clones finds the twins and the runs; SelfTest holds them to the plants.
## budget: steps=200000000 arena_bytes=2000000000 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 Clones
import SelfTest
import Shape

main! : {} => {}
main! = |{}| {
	if integer_or_stop!("self_test", Shale.arg!("self_test", "0")) == 1 {
		SelfTest.run!(find!)
	} else {
		settings = {
			tests: integer_or_stop!("tests", Shale.arg!("tests", "0")) == 1,
			k: integer_or_stop!("k", Shale.arg!("k", "3")),
			score: integer_or_stop!("score", Shale.arg!("score", "80")),
			min: integer_or_stop!("min", Shale.arg!("min", "8")),
			window: integer_or_stop!("window", Shale.arg!("window", "6")),
		}
		folder = Shale.arg!("dir", "c")
		top = integer_or_stop!("top", Shale.arg!("top", "40"))
		found = find!(folder, settings)
		print_top!(found.twins, { top, what: "twins" })
		print_top!(found.runs, { top, what: "runs" })
		which = if settings.tests {
			"tests included"
		} else {
			"tests left out"
		}
		twins = "${found.twins.len().to_str()} twins (structure ${settings.score.to_str()}%+ over runs of ${settings.k.to_str()})"
		runs = "${found.runs.len().to_str()} runs of ${settings.window.to_str()}+ lines alike"
		Shale.print!("find_clones: ${found.functions.to_str()} functions under ${folder}, ${which}; ${twins}, ${runs}")
	}
}

## The first `top` lines, then how many more there are.
print_top! : List(Str), { top : I64, what : Str } => {}
print_top! = |lines, { top, what }| {
	for line in lines.take_first(I64.max(top, 0).to_u64_wrap()) {
		Shale.print!(line)
	}
	more = lines.len().to_i64_wrap() - top
	if more > 0 {
		Shale.print!("... ${more.to_str()} more ${what} (top=)")
	}
}

## 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!("find_clones: ${name}=${given} is not an integer")
			0
		}
	}

## The findings over the folder.
find! : Str, Clones.Settings => Clones.Found
find! = |folder, settings| Clones.found(read_functions!(folder, settings.tests), settings)

## Each function's counted lines under the folder, a test's too with
## `tests`: every function with a body of its own lines, in a file that is
## not the tests' unless `tests`.
read_functions! : Str, Bool => List(Shape.Function)
read_functions! = |folder, tests| {
	var $functions = []
	for path in c_files_under!(folder) {
		text = read_text!(path)
		lines = Split.lines(text)
		is_kept_file = tests or !(Paths.is_test_path(folder, path))
		for item in split_or_stop!(path, text) {
			is_read = item.kind == Function or (tests and item.kind == Test)
			has_body = item.body_first != 0 and item.body_first != item.sig_last
			if is_kept_file and is_read and has_body {
				$functions = $functions.append(Shape.of_item(path, lines, item))
			}
		}
	}
	$functions
}

## The file's text. A file the glob named and the read finds gone stops the
## run.
read_text! : Str => Str
read_text! = |path|
	match Shale.read!(path) {
		Found(text) => text
		Missing => {
			Shale.fail!("find_clones: ${path} went missing during the walk")
			""
		}
	}

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

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

cookbook/c/find_clones/Clones.roc, 298 lines

## The clone finder over functions read for clones (Shape): the twin pairs,
## two functions of one shape, and the runs of lines alike as written in two
## places. The launcher's header says the rules; this is the Shale
## original's arithmetic, its counts and its order, exactly.
import Shape

Clones := [].{

	## What a search takes: the tests or not, the run length a twin's shape
	## is compared by (`k`), the least structure score, the least counted
	## lines a twin has, and the least run of lines alike (`window`).
	Settings : { tests : Bool, k : I64, score : I64, min : I64, window : I64 }

	## The findings: how many functions were read, and each list's lines,
	## twins highest score first, runs longest first.
	Found : { functions : U64, twins : List(Str), runs : List(Str) }

	## The findings over the functions.
	found : List(Shape.Function), Clones.Settings -> Clones.Found
	found = |functions, settings| {
		twins = find_twins(functions, settings)
		twin_lines = twins.map(
			|twin| {
				pair = "${place(function_at(functions, twin.a))} ~ ${place(function_at(functions, twin.b))}"
				"${pair}: twin: structure ${twin.structure.to_str()}%, names ${twin.names.to_str()}%"
			},
		)
		skip = twins.fold(Set.empty(), |pairs, twin| pairs.insert((twin.a, twin.b)))
		run_lines = find_runs(functions, settings.window, skip).map(
			|run| {
				a = function_at(functions, run.a)
				b = function_at(functions, run.b)
				first = "${a.path}:${run.a_first.to_str()}-${run.a_last.to_str()} ${a.name}"
				second = "${b.path}:${run.b_first.to_str()}-${run.b_last.to_str()} ${b.name}"
				"${first} ~ ${second}: run: ${run.count.to_str()} lines alike"
			},
		)
		{ functions: functions.len(), twins: twin_lines, runs: run_lines }
	}
}

## A run of lines common to more places than this is boilerplate, passed by.
common : U64
common = 8

## The function by its number, counted from 1.
function_at : List(Shape.Function), U64 -> Shape.Function
function_at = |functions, number|
	match functions.get(number - 1) {
		Ok(function) => function
		Err(_) => crash "find_clones: no function ${number.to_str()}"
	}

## A function's place and name, `path:first-last name`.
place : Shape.Function -> Str
place = |function|
	"${function.path}:${function.first.to_str()}-${function.last.to_str()} ${function.name}"

## The texts of each run of `k` lines in a row, in order, each joined by
## newlines: one a start, from the first line to the last that leaves `k`.
windows : List(Str), I64 -> List(Str)
windows = |texts, k| {
	count = texts.len().to_i64_wrap() + 1 - k
	var $out = []
	$start : I64
	var $start = 0
	while $start < count {
		window = if k <= 0 {
			""
		} else {
			Str.join_with(texts.sublist({ start: $start.to_u64_wrap(), len: k.to_u64_wrap() }), "\n")
		}
		$out = $out.append(window)
		$start = $start + 1
	}
	$out
}

## The set of a function's runs of `k` lines, by their shapes or as
## written.
runs_of : Shape.Function, [Shaped, Exact], I64 -> Set(Str)
runs_of = |function, field, k| {
	texts = function.lines.map(
		|line|
			match field {
				Shaped => line.shape
				Exact => line.exact
			},
	)
	windows(texts, k).fold(Set.empty(), |set, window| set.insert(window))
}

## Dice's coefficient of two sets, as a whole percent.
dice : Set(Str), Set(Str) -> U64
dice = |a, b| {
	sizes = a.len() + b.len()
	if sizes == 0 {
		0
	} else {
		shared = a.to_list().count_if(|x| b.contains(x))
		(200 * shared) // sizes
	}
}

## Each pair of the places, the first before the second in the list.
pairs_of : List(a) -> List((a, a))
pairs_of = |places| {
	var $pairs = []
	var $x = 0
	while $x < places.len() {
		var $y = $x + 1
		while $y < places.len() {
			match (places.get($x), places.get($y)) {
				(Ok(p), Ok(q)) => {
					$pairs = $pairs.append((p, q))
				}
				_ => {}
			}
			$y = $y + 1
		}
		$x = $x + 1
	}
	$pairs
}

## Whether a run is in two places or more, but no more than `common`.
is_shared : List(a) -> Bool
is_shared = |places| places.len() >= 2 and places.len() <= common

## A twin pair: the two functions' places, the structure score and the
## names score.
Twin : { a : U64, b : U64, structure : U64, names : U64 }

## The twin pairs, highest structure first, then highest names, then by
## place.
find_twins : List(Shape.Function), Clones.Settings -> List(Twin)
find_twins = |functions, settings| {
	sets = functions.map(
		|function|
			if function.lines.len().to_i64_wrap() >= settings.min {
				runs_of(function, Shaped, settings.k)
			} else {
				Set.empty()
			},
	)
	var $index = Dict.empty()
	$number : U64
	var $number = 0
	for set in sets {
		$number = $number + 1
		for key in set.to_list() {
			$index = $index.insert(key, ($index.get(key) ?? []).append($number))
		}
	}
	var $shared = Dict.empty()
	for (_, places) in $index.to_list() {
		if is_shared(places) {
			for pair in pairs_of(places) {
				$shared = $shared.insert(pair, ($shared.get(pair) ?? 0) + 1)
			}
		}
	}
	var $twins = []
	for ((a, b), count) in $shared.to_list() {
		set_a = sets.get(a - 1) ?? Set.empty()
		set_b = sets.get(b - 1) ?? Set.empty()
		structure = (200 * count) // (set_a.len() + set_b.len())
		if structure.to_i64_wrap() >= settings.score {
			exact_a = runs_of(function_at(functions, a), Exact, settings.k)
			exact_b = runs_of(function_at(functions, b), Exact, settings.k)
			$twins = $twins.append({ a, b, structure, names: dice(exact_a, exact_b) })
		}
	}
	$twins.sort_with(twin_order)
}

twin_order : Twin, Twin -> [Before, Same, After]
twin_order = |x, y|
	first_of([down(x.structure, y.structure), down(x.names, y.names), up(x.a, y.a), up(x.b, y.b)])

## A run of lines alike: the two functions' places, how many lines, and
## each side's first and last line numbers.
Run : { a : U64, b : U64, count : U64, a_first : U64, a_last : U64, b_first : U64, b_last : U64 }

## A window's place: the function's, and the counted line it starts at,
## both from 1.
WindowPlace : { function : U64, start : I64 }

## The runs of `window` or more lines alike as written, in two places,
## longest first; a twin pair's own left out.
find_runs : List(Shape.Function), I64, Set((U64, U64)) -> List(Run)
find_runs = |functions, window, skip| {
	var $at = Dict.empty()
	$number : U64
	var $number = 0
	for function in functions {
		$number = $number + 1
		$start : I64
		var $start = 0
		for text in windows(function.lines.map(|line| line.exact), window) {
			$start = $start + 1
			here = { function: $number, start: $start }
			$at = $at.insert(text, ($at.get(text) ?? []).append(here))
		}
	}
	var $pairs = Dict.empty()
	for (_, places) in $at.to_list() {
		if is_shared(places) {
			for (p, q) in pairs_of(places) {
				offset = q.start - p.start
				# A window against itself shifted is no second place.
				if !(p.function == q.function and offset < window) {
					key = (p.function, q.function, offset)
					$pairs = $pairs.insert(key, ($pairs.get(key) ?? []).append(p.start))
				}
			}
		}
	}
	var $runs = []
	for ((a, b, offset), starts) in $pairs.to_list() {
		if !(skip.contains((a, b))) {
			sides = { a: function_at(functions, a), b: function_at(functions, b), a_place: a, b_place: b }
			$runs = $runs.concat(runs_from(sides, { window, offset, starts: starts.sort_with(up_signed) }))
		}
	}
	$runs.sort_with(run_order)
}

## The runs one pair of functions at one offset holds: each stretch of
## starts one after another is a run.
runs_from : { a : Shape.Function, b : Shape.Function, a_place : U64, b_place : U64 }, { window : I64, offset : I64, starts : List(I64) } -> List(Run)
runs_from = |sides, { window, offset, starts }| {
	line_at = |function, number| {
		counted = function.lines.get((number - 1).to_u64_wrap()) ?? { line: 0, exact: "", shape: "" }
		counted.line
	}
	stretch = |first, last| {
		a: sides.a_place,
		b: sides.b_place,
		count: (last - first + window).to_u64_wrap(),
		a_first: line_at(sides.a, first),
		a_last: line_at(sides.a, last + window - 1),
		b_first: line_at(sides.b, first + offset),
		b_last: line_at(sides.b, last + window - 1 + offset),
	}
	match starts {
		[] => []
		[head, .. as rest] => {
			var $runs = []
			var $first = head
			var $last = head
			for start in rest {
				if start == $last + 1 {
					$last = start
				} else {
					$runs = $runs.append(stretch($first, $last))
					$first = start
					$last = start
				}
			}
			$runs.append(stretch($first, $last))
		}
	}
}

run_order : Run, Run -> [Before, Same, After]
run_order = |x, y|
	first_of([down(x.count, y.count), up(x.a, y.a), up(x.a_first, y.a_first), up(x.b, y.b), up(x.b_first, y.b_first)])

## The first of the orders that is not `Same`.
first_of : List([Before, Same, After]) -> [Before, Same, After]
first_of = |orders| orders.find_first(|order| order != Same) ?? Same

## Two numbers, the smaller first.
up : U64, U64 -> [Before, Same, After]
up = |x, y|
	if x < y {
		Before
	} else if x > y {
		After
	} else {
		Same
	}

## Two signed numbers, the smaller first.
up_signed : I64, I64 -> [Before, Same, After]
up_signed = |x, y|
	if x < y {
		Before
	} else if x > y {
		After
	} else {
		Same
	}

## Two numbers, the larger first.
down : U64, U64 -> [Before, Same, After]
down = |x, y| up(y, x)

cookbook/c/find_clones/SelfTest.roc, 47 lines

## find_clones' self-test: the recipe run over cookbook/c/plants/find_clones/
## and held to the plants' findings exactly: a twin with every name and
## number changed, a run of six lines in two unlike functions, and their
## near misses (a function as long as the twins but of another shape, four
## lines alike that a fifth's string breaks, a test's oracle copy unless
## `tests=1`).
import pf.Shale
import Clones

SelfTest := [].{

	## Both checks, each a stop when it fails, then the PASS line. `find!` is
	## the recipe's own, the findings over a folder.
	run! : (Str, Clones.Settings => Clones.Found) => {}
	run! = |find!| {
		file = "${plants}/clones.c"
		settings = { tests: Bool.False, k: 3, score: 80, min: 8, window: 6 }
		found = find!(plants, settings)
		got = "${joined(found.twins)}\n--\n${joined(found.runs)}"
		twin = "${file}:6-16 sum_weights ~ ${file}:18-28 sum_prices: twin: structure 100%, names 0%"
		run = "${file}:49-54 write_header ~ ${file}:64-69 write_trailer: run: 6 lines alike"
		want = "${twin}\n--\n${run}"
		if got != want {
			Shale.fail!("find_clones self-test: the plants' findings are\n${got}\nthey should be\n${want}")
		}
		# With the tests, the oracle's copy is a twin of each, as written of one.
		oracle = "${plants}/tests/test_clones.c"
		with_tests = joined(find!(plants, { ..settings, tests: Bool.True }).twins)
		want_with_tests = joined([
			"${file}:6-16 sum_weights ~ ${oracle}:5-15 oracle_weights: twin: structure 100%, names 100%",
			"${file}:6-16 sum_weights ~ ${file}:18-28 sum_prices: twin: structure 100%, names 0%",
			"${file}:18-28 sum_prices ~ ${oracle}:5-15 oracle_weights: twin: structure 100%, names 0%",
		])
		if with_tests != want_with_tests {
			Shale.fail!("find_clones self-test: with tests=1 the plants' twins are\n${with_tests}\nthey should be\n${want_with_tests}")
		}
		checks = "the twin and the run over the plants, exactly, their near misses left alone, and a test's oracle only with tests=1"
		Shale.print!("PASS find_clones self-test: ${checks}")
	}
}

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

joined : List(Str) -> Str
joined = |lines| Str.join_with(lines, "\n")

cookbook/c/find_clones/Shape.roc, 179 lines

## A function's counted lines, as the clone finder compares them. A line
## counts when it does something: a blank line, a comment and a line of
## brackets alone (`}`, `} else {`, `default:`) are passed by. Each counted
## line is kept twice: as written (`exact`, to where its code ends, its
## spaces made one) and as its shape (`shape`, every name `I`, every number
## `N`, every string `S` and every character literal `C`, a keyword itself).
import items.Item
import items.Mask

Shape := [].{

	## A counted line: its number, its text as written and its shape.
	CountedLine : { line : U64, exact : Str, shape : Str }

	## A function read for clones: where it is, its name and its counted
	## lines.
	Function : {
		path : Str,
		first : U64,
		last : U64,
		name : Str,
		lines : List(Shape.CountedLine),
	}

	## The function the item is, of the file at `path` whose lines are
	## `lines`, its body's lines counted.
	of_item : Str, List(List(U8)), Item -> Shape.Function
	of_item = |path, lines, item| {
		body = lines.sublist({ start: item.body_first - 1, len: item.body_last + 1 - item.body_first })
		var $counted = []
		var $number = item.body_first
		for raw in body {
			masked = Mask.masked(raw)
			code = Mask.trimmed(masked)
			if !(code.is_empty()) and !(is_brackets(code)) {
				$counted = $counted.append({ line: $number, exact: exact_text(raw, masked), shape: shape_of(code) })
			}
			$number = $number + 1
		}
		{ path, first: item.first, last: item.last, name: item.name, lines: $counted }
	}
}

## C's keywords and the words of its types and storage, which stay
## themselves in a shape.
keywords : List(Str)
keywords = [
	"auto",
	"break",
	"case",
	"char",
	"const",
	"continue",
	"default",
	"do",
	"double",
	"else",
	"enum",
	"extern",
	"float",
	"for",
	"goto",
	"if",
	"inline",
	"int",
	"long",
	"register",
	"restrict",
	"return",
	"short",
	"signed",
	"sizeof",
	"static",
	"struct",
	"switch",
	"typedef",
	"union",
	"unsigned",
	"void",
	"volatile",
	"while",
	"_Alignof",
	"_Bool",
	"_Static_assert",
	"bool",
	"true",
	"false",
	"NULL",
]

## A line of brackets alone, or a `default:`: no work of its own,
## `^[{}()\[\];, ]*$|^\} else \{$|^default:$`.
is_brackets : List(U8) -> Bool
is_brackets = |code| {
	is_bracket = |byte| byte == '{' or byte == '}' or byte == '(' or byte == ')' or byte == '[' or byte == ']' or byte == ';' or byte == ',' or byte == ' '
	code.all(is_bracket) or code == "} else {".to_utf8() or code == "default:".to_utf8()
}

## The raw line to where its masked code ends (a comment after it cut),
## trimmed, each run of `\s` in it made one space.
exact_text : List(U8), List(U8) -> Str
exact_text = |raw, masked| {
	code_end = match masked.find_last_index(|byte| !(Mask.is_space(byte))) {
		Ok(last) => last + 1
		Err(_) => 0
	}
	kept = Mask.trimmed(raw.take_first(code_end))
	one_spaced = kept.fold(
		[],
		|out, byte|
			if !(Mask.is_space(byte)) {
				out.append(byte)
			} else if out.last() == Ok(' ') {
				# A space is `\s`, so one that ends `out` is a run's already.
				out
			} else {
				out.append(' ')
			},
	)
	Mask.text(one_spaced)
}

## A byte that is a token of its own, as text: itself when it is ASCII,
## else its value, `x` and two hex digits, so no two bytes share a token.
byte_token : U8 -> Str
byte_token = |byte|
	if byte < 0x80 {
		Mask.text([byte])
	} else {
		digits = "0123456789abcdef".to_utf8()
		high = digits.get((byte // 16).to_u64()) ?? '0'
		low = digits.get((byte % 16).to_u64()) ?? '0'
		Mask.text(['x', high, low])
	}

## A masked line's tokens with every name `I`, number `N`, string `S` and
## character literal `C`, a keyword itself, joined by spaces. A token is
## `[A-Za-z_]\w*|\d\w*|"[^"]*"|'[^']*'|\S`, leftmost first.
shape_of : List(U8) -> Str
shape_of = |code| {
	var $tokens = []
	var $at = 0
	while $at < code.len() {
		byte = code.get($at) ?? 0
		if Mask.is_name_start(byte) {
			end = Mask.word_end(code, $at)
			name = Mask.text(code.sublist({ start: $at, len: end - $at }))
			$tokens = $tokens.append(
				if keywords.contains(name) {
					name
				} else {
					"I"
				},
			)
			$at = end
		} else if byte >= '0' and byte <= '9' {
			$tokens = $tokens.append("N")
			$at = Mask.word_end(code, $at)
		} else if byte == '"' or byte == '\'' {
			$tokens = $tokens.append(
				if byte == '"' {
					"S"
				} else {
					"C"
				},
			)
			$at = match Mask.byte_from(code, byte, $at + 1) {
				Ok(close) => close + 1
				Err(_) => $at + 1
			}
		} else if Mask.is_space(byte) {
			$at = $at + 1
		} else {
			$tokens = $tokens.append(byte_token(byte))
			$at = $at + 1
		}
	}
	Str.join_with($tokens, " ")
}

Shale original

cookbook/c/find_clones.shale, 327 lines, at b8e624ff

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

-- Finds the same code twice in Shale's C, from cookbook/c/items.shale's
-- splitter, as two kinds of pair:
--
--   twin  two functions of one shape: their bodies' lines, each with every
--         name made `I`, every number `N`, every string `S` and every
--         character literal `C`, share most of their runs of `k=` (3) lines.
--         The score is the share, `structure` (Dice's coefficient over the
--         two sets of runs, 100 when every run of each is the other's);
--         `names` is the same over the lines as written, so a twin with
--         every name changed is `names 0%` and a pasted copy near 100%.
--   run   `window=` (6) or more lines alike as written, in a row, in two
--         functions (or twice in one), as cookbook/zig/find_clones.shale
--         finds them: what a shared function would say once.
--
-- A line counts when it does something: a blank line, a comment and a line
-- of brackets alone (`}`, `} else {`, `default:`) are passed by. A string's
-- text counts in a run (`S("a")` is not `S("b")`), and a comment after code
-- does not. A run within a twin pair is the twin's, not listed again.
--
--   path:first-last name ~ path:first-last name: twin: structure 100%, names 0%
--   path:first-last name ~ path:first-last name: run: 6 lines alike
--
-- Twins come first, highest score first, then runs, longest first. A twin
-- needs `min=` (8) counted lines in each function and a structure score of
-- `score=` (80) or more. A run of lines common to more than eight places is
-- boilerplate, passed by, and so is such a run of shapes for twins. The
-- tests (a `TEST(` body, and every function of a file in a `tests` folder or
-- named `test*`) are left out unless `tests=1`: a test's oracle copies the
-- code it judges on purpose. `top=` (40) caps each list; the counts are
-- of all.
--
--   shale cookbook:c/find_clones.shale            over c/
--   shale cookbook:c/find_clones.shale dir=c/host score=70
--   shale cookbook:c/find_clones.shale self_test=1
--
-- A find is a question, not a fix: two functions may be alike on purpose,
-- as the gate's own JSON reader is kept apart from the host's.
--
-- `self_test=1` runs it over cookbook/c/plants/find_clones/ and holds the
-- findings to the plants exactly: a twin with every name and number changed,
-- a run of six lines in two unlike functions, and their near misses (a
-- function as long as the twins but of another shape, four lines alike
-- that a fifth's string breaks, a test's oracle copy unless `tests=1`).
--
-- budget: steps=900000000 arena_bytes=1000000000 kept_bytes=268435456

use("./items.shale")

const PLANTS = "cookbook/c/plants/find_clones"
const COMMON = 8

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

-- A token of C: a name, a number, a string, a character literal, or one
-- other character.
const C_TOKEN = [=[[A-Za-z_]\w*|\d\w*|"[^"]*"|'[^']*'|\S]=]

-- A masked line's tokens with every name `I`, number `N`, string `S` and
-- character literal `C`; a keyword stays itself.
function shape_of(code, keywords)
  local out = {}
  for t in re_find_all(code, C_TOKEN) do
    local s = t.text
    local c = sub(s, 1, 1)
    if c == "\"" then
      s = "S"
    elseif c == "'" then
      s = "C"
    elseif re_match(c, "[0-9]") then
      s = "N"
    elseif re_match(c, "[A-Za-z_]") and not has_key(keywords, s) then
      s = "I"
    end
    push(out, s)
  end
  return join(out, " ")
end

-- A line of brackets alone, or a `default:`: no work of its own.
function is_brackets(code)
  return re_match(code, [=[^[{}()\[\];, ]*$|^\} else \{$|^default:$]=])
end

-- Whether `p`, below `dir`, is the tests': in a `tests` folder, or a file
-- whose name starts with `test` (c/foundation/test.h, the tests' runner).
function is_test_path(dir, p)
  local rel = sub(p, #dir + 2)
  return starts_with(rel, "tests/") or contains(rel, "/tests/") or starts_with(basename(p), "test")
end

-- Each function's counted lines under `dir`: `{path, first, last, name,
-- lines}`, each line `{line, exact, shape}`. `exact` is the raw line to
-- where its code ends (a comment after it cut), its spaces made one.
function read_functions(dir, tests)
  local keywords = set_of(C_KEYWORDS)
  local fns = {}
  for p in c_files_under(dir) do
    local all = lines(read(p))
    local kept_file = tests or not is_test_path(dir, p)
    for it in c_items(p) do
      if kept_file and (it.kind == "function" or (tests and it.kind == "test")) and it.body_first ~= 0 and it.body_first ~= it.sig_last then
        local kept = {}
        local k = it.body_first
        while k <= it.body_last do
          local code = trim(c_mask(all[k]))
          if code ~= "" and not is_brackets(code) then
            local raw = all[k]
            local masked = c_mask(raw)
            local stop = #re_replace(masked, [=[\s+$]=], "")
            local exact = re_replace(trim(sub(raw, 1, stop)), [=[\s+]=], " ")
            push(kept, {line = k, exact = exact, shape = shape_of(code, keywords)})
          end
          k = k + 1
        end
        push(fns, {path = p, first = it.first, last = it.last, name = it.name, lines = kept})
      end
    end
    yield()
  end
  return fns
end

-- The set of runs of `k` lines of function `f`, by `field`, as a map.
function runs_of(f, field, k)
  local got = {}
  local i = 1
  while i + k - 1 <= #f.lines do
    local parts = {}
    local j = i
    while j <= i + k - 1 do
      push(parts, f.lines[j][field])
      j = j + 1
    end
    got[join(parts, "\n")] = true
    i = i + 1
  end
  return got
end

-- Dice's coefficient of two sets, as a whole percent.
function dice(a, b)
  local na = #keys(a)
  local nb = #keys(b)
  if na + nb == 0 then return 0 end
  local shared = 0
  for x in keys(a) do
    if has_key(b, x) then shared = shared + 1 end
  end
  return (200 * shared) // (na + nb)
end

-- A function's place and name, `path:first-last name`.
function place(f)
  return f.path .. ":" .. f.first .. "-" .. f.last .. " " .. f.name
end

-- The twin pairs of `fns`: `{a, b, structure, names}` (indexes), highest
-- structure first.
function find_twins(fns, k, least, min_lines)
  local sets = {}
  local index = {}
  local i = 0
  for f in fns do
    i = i + 1
    local s = {}
    if #f.lines >= min_lines then s = runs_of(f, "shape", k) end
    push(sets, s)
    for key in keys(s) do push_at(index, key, i) end
  end
  local shared = {}
  for key in keys(index) do
    local at = index[key]
    if #at >= 2 and #at <= COMMON then
      local x = 1
      while x < #at do
        local y = x + 1
        while y <= #at do
          incr(shared, at[x] .. ":" .. at[y])
          y = y + 1
        end
        x = x + 1
      end
    end
  end
  local twins = {}
  for id in keys(shared) do
    local ab = split(id, ":")
    local a = parse_int(ab[1])
    local b = parse_int(ab[2])
    local na = #keys(sets[a])
    local nb = #keys(sets[b])
    local score = (200 * shared[id]) // (na + nb)
    if score >= least then
      push(twins, {a = a, b = b, structure = score, names = dice(runs_of(fns[a], "exact", k), runs_of(fns[b], "exact", k))})
    end
  end
  sort(twins, {{key = "structure", desc = true}, {key = "names", desc = true}, "a", "b"})
  return twins
end

-- The runs of `w` or more lines alike as written, in two places: `{a, b,
-- n, a0, a1, b0, b1}` (function indexes, the count, and each side's first
-- and last lines), longest first; a pair in `skip` (`a:b`) left out.
function find_runs(fns, w, skip)
  local at = {}
  local fi = 0
  for f in fns do
    fi = fi + 1
    local i = 1
    while i + w - 1 <= #f.lines do
      local parts = {}
      local j = i
      while j <= i + w - 1 do
        push(parts, f.lines[j].exact)
        j = j + 1
      end
      push_at(at, join(parts, "\n"), {f = fi, i = i})
      i = i + 1
    end
  end
  local pairs = {}
  for key in keys(at) do
    local places = at[key]
    if #places >= 2 and #places <= COMMON then
      local x = 1
      while x < #places do
        local y = x + 1
        while y <= #places do
          local p = places[x]
          local q = places[y]
          -- A window against itself shifted is no second place.
          if not (p.f == q.f and q.i - p.i < w) then push_at(pairs, p.f .. ":" .. q.f .. ":" .. (q.i - p.i), p.i) end
          y = y + 1
        end
        x = x + 1
      end
    end
  end
  local runs = {}
  for id in keys(pairs) do
    local parts = split(id, ":")
    local fa = parse_int(parts[1])
    local fb = parse_int(parts[2])
    local off = parse_int(parts[3])
    if not has_key(skip, fa .. ":" .. fb) then
      local starts = sort(pairs[id])
      local first = starts[1]
      local last = starts[1]
      local k = 2
      while k <= #starts + 1 do
        if k <= #starts and starts[k] == last + 1 then
          last = starts[k]
        else
          local la = fns[fa].lines
          local lb = fns[fb].lines
          push(runs, {a = fa, b = fb, n = last - first + w, a0 = la[first].line, a1 = la[last + w - 1].line, b0 = lb[first + off].line, b1 = lb[last + w - 1 + off].line})
          if k <= #starts then
            first = starts[k]
            last = starts[k]
          end
        end
        k = k + 1
      end
    end
  end
  sort(runs, {{key = "n", desc = true}, "a", "a0", "b", "b0"})
  return runs
end

-- The findings over `dir`, `{functions, twins, runs}`, each list's lines.
function find_clones(dir, o)
  local fns = read_functions(dir, o.tests)
  local twins = find_twins(fns, o.k, o.score, o.min)
  local skip = {}
  local twin_lines = {}
  for t in twins do
    skip[t.a .. ":" .. t.b] = true
    push(twin_lines, place(fns[t.a]) .. " ~ " .. place(fns[t.b]) .. ": twin: structure " .. t.structure .. "%, names " .. t.names .. "%")
  end
  local run_lines = {}
  for r in find_runs(fns, o.window, skip) do
    local a = fns[r.a]
    local b = fns[r.b]
    push(run_lines, a.path .. ":" .. r.a0 .. "-" .. r.a1 .. " " .. a.name .. " ~ " .. b.path .. ":" .. r.b0 .. "-" .. r.b1 .. " " .. b.name .. ": run: " .. r.n .. " lines alike")
  end
  return {functions = #fns, twins = twin_lines, runs = run_lines}
end

function self_test()
  local P = PLANTS .. "/clones.c"
  local r = find_clones(PLANTS, {tests = false, k = 3, score = 80, min = 8, window = 6})
  local got = join(r.twins, "\n") .. "\n--\n" .. join(r.runs, "\n")
  local want = P .. ":6-16 sum_weights ~ " .. P .. ":18-28 sum_prices: twin: structure 100%, names 0%\n--\n" .. P .. ":49-54 write_header ~ " .. P .. ":64-69 write_trailer: run: 6 lines alike"
  if got ~= want then fail("find_clones self-test: the plants' findings are\n" .. got .. "\nthey should be\n" .. want) end
  -- With the tests, the oracle's copy is a twin of each, as written of one.
  local T = PLANTS .. "/tests/test_clones.c"
  local with = join(find_clones(PLANTS, {tests = true, k = 3, score = 80, min = 8, window = 6}).twins, "\n")
  local want_with = join({
    P .. ":6-16 sum_weights ~ " .. T .. ":5-15 oracle_weights: twin: structure 100%, names 100%",
    P .. ":6-16 sum_weights ~ " .. P .. ":18-28 sum_prices: twin: structure 100%, names 0%",
    P .. ":18-28 sum_prices ~ " .. T .. ":5-15 oracle_weights: twin: structure 100%, names 0%"}, "\n")
  if with ~= want_with then fail("find_clones self-test: with tests=1 the plants' twins are\n" .. with .. "\nthey should be\n" .. want_with) end
  print("PASS find_clones self-test: the twin and the run over the plants, exactly, their near misses left alone, and a test's oracle only with tests=1")
  return nil
end

if arg("self_test", 0) == 1 then
  self_test()
else
  local o = {tests = arg("tests", 0) == 1, k = arg("k", 3), score = arg("score", 80), min = arg("min", 8), window = arg("window", 6)}
  local dir = arg("dir", "c")
  local top = arg("top", 40)
  local r = find_clones(dir, o)
  for l in take(r.twins, top) do print(l) end
  if #r.twins > top then print("... " .. (#r.twins - top) .. " more twins (top=)") end
  for l in take(r.runs, top) do print(l) end
  if #r.runs > top then print("... " .. (#r.runs - top) .. " more runs (top=)") end
  print("find_clones: " .. r.functions .. " functions under " .. dir .. (o.tests and ", tests included" or ", tests left out") .. "; " .. #r.twins .. " twins (structure " .. o.score .. "%+ over runs of " .. o.k .. "), " .. #r.runs .. " runs of " .. o.window .. "+ lines alike")
end