
Mutate.pudu
Pudu212 lines7.8 KB
1/** @Tools.Mutate.Harness — mutation testing over the source tree */2module Mutate34import Std.Char as Char5import Std.Env as Env6import Std.Io as Io7import Std.List as List8import Std.Math as Math9import Std.Option as Option10import Std.Process as Process11import Std.Result as Result12import Std.Text as Text1314/** @Tools.Mutate.Mutant — one single-point change to one file */15type Mutant = { file: Str, line: Int, column: Int, from: Str, to: Str }1617/** @Tools.Mutate.Verdict — what the checks said about one mutant */18type Verdict = Killed | Survived | Invalid192021const OPERATORS: Array[(Str, Str)] = [22 ("==", "!="), ("!=", "=="), ("<=", "<"), (">=", ">"), ("<", "<="), (">", ">="),23 ("&&", "||"), ("||", "&&"), ("true", "false"), ("false", "true"), ("+ 1", "- 1"), ("- 1", "+ 1"), ("!", "")24]252627const MUTANT_TIMEOUT_MS: Int = 60000282930const DOMAIN: Str = "src/PuduLangLog/Domain"313233fn main() -> Int {34 let every = Option.unwrapOr(Option.andThen(Env.option("--every"), |given: Str| Text.countOf(given)), 1)35 let offset = Option.unwrapOr(Option.andThen(Env.option("--offset"), |given: Str| Text.countOf(given)), 0)36 let threshold = Option.unwrapOr(Option.andThen(Env.option("--threshold"), |given: Str| Text.countOf(given)), 0)37 let files = match Env.option("--file") {38 case Some(one) => [one]39 case None => sources(if Env.hasFlag("--domain") { DOMAIN } else { "src" })40 }41 var all: Array[Mutant] = []42 for file in files {43 all = all.concat(mutantsOf(file, Result.unwrapOr(Io.read(file), "")))44 }45 var chosen: Array[Mutant] = []46 var index = 047 for mutant in all {48 let step = Math.max(1, every)49 if index % step == offset % step { chosen = chosen.push(mutant) }50 index = index + 151 }52 if Env.hasFlag("--dry-run") {53 for mutant in chosen { let _listed = Io.writeLine(describe(&mutant)) }54 let _counted = Io.writeLine(show(chosen.length()) + " mutants")55 return 056 }57 let compiler = Env.variableOr("PUDU_BIN", "pudu")58 if !Process.isAvailable(compiler) {59 let _said = Io.writeErrorLine("Mutate: " + compiler + " was not found; set PUDU_BIN")60 return 161 }62 var killed = 063 var survived = 064 var invalid = 065 var number = 066 for mutant in chosen {67 number = number + 168 match judge(compiler, &mutant) {69 case Killed => { killed = killed + 1 }70 case Survived => {71 survived = survived + 172 let _reported = Io.writeLine("survived " + describe(&mutant))73 }74 case Invalid => { invalid = invalid + 1 }75 }76 let _progress = Io.writeErrorLine("[" + show(number) + "/" + show(chosen.length()) + "] " + describe(&mutant))77 }78 let scored = killed + survived79 let score = if scored == 0 { 100 } else { killed * 100 / scored }80 let _summary = Io.writeLine("killed " + show(killed) + ", survived " + show(survived) + ", invalid " + show(invalid) + ", score " + show(score) + "%")81 if score < threshold { 1 } else { 0 }82}838485fn judge(compiler: Str, mutant: &Mutant) -> Verdict {86 let original = Result.unwrapOr(Io.read(mutant.file), "")87 let _mutated = Io.write(mutant.file, applied(original, mutant))88 let verdict = match Process.within(compiler, &["check", mutant.file], MUTANT_TIMEOUT_MS) {89 case Ok(Some(checked)) => {90 if checked.status != 0 || checked.output.contains("error[") {91 Invalid92 } else {93 match Process.within(compiler, &["test", "test"], MUTANT_TIMEOUT_MS) {94 case Ok(Some(tested)) => if tested.status == 0 { Survived } else { Killed }95 case Ok(None) => Killed96 case Err(_) => Invalid97 }98 }99 }100 case _ => Invalid101 }102 let _restored = Io.write(mutant.file, original)103 verdict104}105106107fn mutantsOf(file: Str, text: Str) -> Array[Mutant] {108 var found: Array[Mutant] = []109 var lineNumber = 0110 for line in text.split("\n") {111 lineNumber = lineNumber + 1112 let trimmed = line.trim()113 if !trimmed.startsWith("//") && !trimmed.startsWith("/*") && !trimmed.startsWith("import ") {114 let code = codeMask(line)115 for operator in OPERATORS {116 var at = 0117 while at < line.length() {118 if matchesAt(line, &code, at, operator[0]) {119 found = found.push(Mutant{file: file, line: lineNumber, column: at + 1, from: operator[0], to: operator[1]})120 }121 at = at + 1122 }123 }124 }125 }126 found127}128129130fn matchesAt(line: Str, code: &Array[Bool], at: Int, operator: Str) -> Bool {131 let end = at + operator.length()132 if end > line.length() || line.slice(at, end) != operator { return false }133 var position = at134 while position < end {135 if !code[position] { return false }136 position = position + 1137 }138 let before = if at > 0 { line.slice(at - 1, at) } else { "" }139 let after = if end < line.length() { line.slice(end, end + 1) } else { "" }140 if operator == "true" || operator == "false" { return !isWord(before) && !isWord(after) }141 if operator == "<" { return after != "=" && after != "-" && before != "<" && isSpaced(before, after) }142 if operator == ">" { return after != "=" && before != "-" && before != "=" && before != ">" && isSpaced(before, after) }143 if operator == "!" { return after != "=" && (isWord(after) || after == "(") }144 if operator == "- 1" || operator == "+ 1" { return !isWord(after) }145 true146}147148149fn isSpaced(before: Str, after: Str) -> Bool { before == " " && after == " " }150151152fn codeMask(line: Str) -> Array[Bool] {153 var mask: Array[Bool] = []154 var inString = false155 var escaped = false156 var commented = false157 var index = 0158 let characters = line.chars()159 for character in characters {160 if commented {161 mask = mask.push(false)162 } else if inString {163 mask = mask.push(false)164 if escaped { escaped = false } else if character == '\\' { escaped = true } else if character == '"' { inString = false }165 } else if character == '"' {166 inString = true167 mask = mask.push(false)168 } else if character == '/' && index + 1 < characters.length() && characters[index + 1] == '/' {169 commented = true170 mask = mask.push(false)171 } else if character == '\'' {172 mask = mask.push(false)173 } else {174 mask = mask.push(true)175 }176 index = index + 1177 }178 mask179}180181182fn applied(text: Str, mutant: &Mutant) -> Str {183 let lines = text.split("\n")184 let target = lines[mutant.line - 1]185 let start = mutant.column - 1186 let changed = target.slice(0, start) + mutant.to + target.drop(start + mutant.from.length())187 lines.slice(0, mutant.line - 1).concat([changed]).concat(lines.slice(mutant.line, lines.length())).join("\n")188}189190191fn describe(mutant: &Mutant) -> Str {192 mutant.file + ":" + show(mutant.line) + ":" + show(mutant.column) + " " + mutant.from + " -> " + (if mutant.to.isEmpty() { "(removed)" } else { mutant.to })193}194195196fn isWord(text: Str) -> Bool {197 !text.isEmpty() && Text.allChars(text, |c: Char| Char.isAlphanumeric(c) || c == '_')198}199200201fn sources(directory: Str) -> Array[Str] {202 var found: Array[Str] = []203 for path in List.sortBy(&Result.unwrapOr(Io.listPaths(directory), []), fn(left: Str, right: Str) -> Bool { left < right }) {204 if path.endsWith(".pudu") {205 found = found.push(path)206 } else if !path.contains(".") {207 found = found.concat(sources(path))208 }209 }210 found211}212