Skip to main content

bynk_driver/
mutate.rs

1//! `bynk test --mutate` (#3069): check that the suites would notice a small
2//! change to the code.
3//!
4//! The run applies one mutation at a time to a project's own sources, runs the
5//! suites that exercise the mutated unit, and reports the mutants no suite
6//! failed on, each with its source span. A surviving mutant is a gap in the
7//! suites, not a bug in the code.
8//!
9//! **How a mutant is made.** Sites are found in the lexed source of every
10//! non-suite file, inside the declaration items the parser delimits, so each
11//! site knows its unit and declaration. The mutant is the file's text with one
12//! operator token replaced, handed to an ordinary in-process `bynk test` run as
13//! an in-memory source overlay ([`TestArgs::mutant_overlay`]); nothing is
14//! written under the project, and the emitted output goes to a scratch
15//! directory. A mutant that does not compile is `invalid` and left out of the
16//! score, so a mutant is only ever "killed" by a suite that built and failed.
17//!
18//! **Which suites run.** The suites that target the mutated unit, or a unit
19//! that (transitively) `uses` it, or that themselves `uses` it. A mutant no
20//! suite reaches is `no suite`: reported, never run, and not scored.
21//!
22//! The first slice mutates comparison operators (`<`↔`<=`, `>`↔`>=`,
23//! `==`↔`!=`) and boolean connectives (`&&`↔`||`).
24
25use crate::emsg;
26use std::collections::{BTreeMap, BTreeSet, HashMap};
27use std::path::{Path, PathBuf};
28use std::process::ExitCode;
29use std::time::{Duration, Instant};
30
31use bynk_syntax::ast::SourceUnit;
32use bynk_syntax::lexer::{TokenKind, tokenize_in};
33use bynk_syntax::parser::parse_unit;
34use bynk_syntax::span::FileId;
35use serde_json::{Value, json};
36
37use crate::test_json::TestRun;
38use crate::test_runner::{TestArgs, TestFormat, run_test};
39
40/// The seed every run of a `--mutate` session uses unless `--seed` names one:
41/// a property test then draws the same inputs for the baseline and every
42/// mutant, so a mutant is not killed or spared by luck.
43const DEFAULT_SEED: &str = "6d75746174";
44
45/// What `bynk test --mutate` was asked to do.
46pub struct MutateArgs {
47    pub input: PathBuf,
48    pub json: bool,
49    pub seed: Option<String>,
50    /// The user's `--suite` values: they limit which suites may run at all.
51    pub suite: Vec<String>,
52    pub only: Option<String>,
53    pub max_mutants: Option<usize>,
54    pub timeout: Option<Duration>,
55    pub all_suites: bool,
56    pub fail_under: Option<u32>,
57    /// `--changed`: only mutate declarations in files that differ from this ref.
58    pub changed: Option<String>,
59    /// `--mutate-jobs`: how many mutants run at once (at least 1).
60    pub jobs: usize,
61}
62
63/// The project-relative, forward-slashed `.bynk` paths that differ from `rev`
64/// (#3134): what `git diff <rev>` names under `root`, plus files git does not
65/// track yet. A file deleted since `rev` is not listed by the caller's sites
66/// anyway, since it no longer exists.
67fn changed_files(root: &Path, rev: &str) -> Result<BTreeSet<String>, String> {
68    // A leading `-` would be read by git as an option, not a revision.
69    if rev.starts_with('-') {
70        return Err(format!(
71            "`--changed {rev}`: a git ref cannot start with `-`"
72        ));
73    }
74    let git = |args: &[&str]| -> Result<String, String> {
75        let out = crate::tools::git_command()
76            .arg("-C")
77            .arg(root)
78            .args(args)
79            .output()
80            .map_err(|e| format!("`--changed` needs `git`, which could not run: {e}"))?;
81        if !out.status.success() {
82            return Err(format!(
83                "`--changed {rev}`: git could not compare against it: {}",
84                String::from_utf8_lossy(&out.stderr).trim()
85            ));
86        }
87        Ok(String::from_utf8_lossy(&out.stdout).into_owned())
88    };
89    // `--relative` makes the paths relative to `root` (and drops files outside
90    // it); `-z` keeps unusual file names intact.
91    let diff = git(&["diff", "--name-only", "--relative", "-z", rev, "--"])?;
92    let new = git(&[
93        "ls-files",
94        "--others",
95        "--exclude-standard",
96        "-z",
97        "--full-name",
98        "--",
99        ".",
100    ]);
101    let prefix = git(&["rev-parse", "--show-prefix"])?;
102    let prefix = prefix.trim_end();
103    let mut files: BTreeSet<String> = diff.split('\0').map(str::to_string).collect();
104    // `ls-files --full-name` is repository-relative: strip `root`'s prefix.
105    for f in new?.split('\0') {
106        if let Some(rel) = f.strip_prefix(prefix) {
107            files.insert(rel.to_string());
108        }
109    }
110    files.retain(|f| f.ends_with(".bynk"));
111    Ok(files)
112}
113
114/// The replacements a token kind takes, as `(source text, replacement text)`.
115fn replacement(kind: &TokenKind) -> Option<(&'static str, &'static str)> {
116    Some(match kind {
117        TokenKind::Lt => ("<", "<="),
118        TokenKind::LtEq => ("<=", "<"),
119        TokenKind::Gt => (">", ">="),
120        TokenKind::GtEq => (">=", ">"),
121        TokenKind::EqEq => ("==", "!="),
122        TokenKind::BangEq => ("!=", "=="),
123        TokenKind::AmpAmp => ("&&", "||"),
124        TokenKind::PipePipe => ("||", "&&"),
125        _ => return None,
126    })
127}
128
129/// What one lexical piece of a SQL string is, for [`sql_mutations`].
130#[derive(Clone, Copy, PartialEq, Eq)]
131enum SqlTok {
132    Word,
133    Open,
134    Close,
135    Cmp,
136}
137
138/// For each byte of a string literal's decoded value, the source bytes it came
139/// from. `None` when the literal can't be aligned with its source, in which case
140/// it is left alone.
141fn decode_with_map(lit: &str) -> Option<(String, Vec<(usize, usize)>)> {
142    let decoded =
143        bynk_syntax::lexer::decode_string_literal(lit, bynk_syntax::span::Span::new(0, lit.len()))
144            .ok()?;
145    let raw = lit.starts_with('r');
146    let hashes = lit[usize::from(raw)..]
147        .bytes()
148        .take_while(|&b| b == b'#')
149        .count();
150    let (open, close) = if raw {
151        (1 + hashes + 1, 1 + hashes)
152    } else if lit.starts_with("\"\"\"") {
153        (3, 3)
154    } else {
155        (1, 1)
156    };
157    let end = lit.len().checked_sub(close)?;
158    let mut map = Vec::with_capacity(decoded.len());
159    let mut chars = decoded.chars().peekable();
160    let mut i = open;
161    while i < end {
162        let sc = lit[i..].chars().next()?;
163        if !raw && sc == '\\' {
164            // An escape decodes to exactly one char.
165            let len = if lit[i + 1..].starts_with('u') {
166                lit[i..].find('}')? + 1
167            } else {
168                1 + lit[i + 1..].chars().next()?.len_utf8()
169            };
170            let dc = chars.next()?;
171            map.extend(std::iter::repeat_n((i, i + len), dc.len_utf8()));
172            i += len;
173            continue;
174        }
175        // A source char the value lacks (a multi-line literal's indentation)
176        // is skipped.
177        if chars.peek() == Some(&sc) {
178            chars.next();
179            map.extend(std::iter::repeat_n((i, i + sc.len_utf8()), sc.len_utf8()));
180        }
181        i += sc.len_utf8();
182    }
183    (chars.next().is_none() && map.len() == decoded.len()).then_some((decoded, map))
184}
185
186/// The mutations inside one string literal's source text (quotes included),
187/// as `(start, end, from, to)` offsets into it. The caller has established
188/// that the literal is SQL (the checker ties it to a D1 call: see `build_model`); the
189/// scan runs on the literal's *decoded* text, so an escape such as `\n` is the
190/// newline it stands for, and is mapped back to the source span it came from.
191/// Three kinds: a comparison `<`↔`<=`, `>`↔`>=`; `max(`↔`min(`; and, in a
192/// `WHERE` of two or more `AND` conjuncts, dropping one conjunct (`to` is
193/// empty). A `CASE … END` is one unit, never split. The result is only text: a
194/// mutant the checker's SQL check refuses is `invalid`.
195pub fn sql_mutations(src: &str) -> Vec<(usize, usize, String, String)> {
196    let Some((decoded, map)) = decode_with_map(src) else {
197        return Vec::new();
198    };
199    let lit: &str = &decoded;
200    let out = scan_sql(lit);
201    out.into_iter()
202        .filter(|(a, b, ..)| a < b && *b <= map.len())
203        .map(|(a, b, from, to)| (map[a].0, map[b - 1].1, from, to))
204        .collect()
205}
206
207/// The mutations in SQL text, as offsets into it.
208fn scan_sql(lit: &str) -> Vec<(usize, usize, String, String)> {
209    let bytes = lit.as_bytes();
210    let mut toks: Vec<(SqlTok, usize, usize)> = Vec::new();
211    let mut i = 0;
212    while i < bytes.len() {
213        let c = bytes[i];
214        match c {
215            b'\'' => {
216                // A SQL string: skip to its close (`''` escapes a quote).
217                i += 1;
218                while i < bytes.len() {
219                    if bytes[i] == b'\'' {
220                        if bytes.get(i + 1) == Some(&b'\'') {
221                            i += 2;
222                            continue;
223                        }
224                        break;
225                    }
226                    i += 1;
227                }
228                i += 1;
229            }
230            b'-' if bytes.get(i + 1) == Some(&b'-') => {
231                while i < bytes.len() && bytes[i] != b'\n' {
232                    i += 1;
233                }
234            }
235            b'(' => {
236                toks.push((SqlTok::Open, i, i + 1));
237                i += 1;
238            }
239            b')' => {
240                toks.push((SqlTok::Close, i, i + 1));
241                i += 1;
242            }
243            b'<' | b'>' => {
244                let prev = if i > 0 { bytes[i - 1] } else { b' ' };
245                let next = bytes.get(i + 1).copied().unwrap_or(b' ');
246                if next == b'=' {
247                    toks.push((SqlTok::Cmp, i, i + 2));
248                    i += 2;
249                } else if next == b'>'
250                    || next == b'<'
251                    || prev == b'-'
252                    || prev == b'<'
253                    || prev == b'>'
254                {
255                    // `<>`, `<<`, `>>`, `->`: not an ordering comparison.
256                    i += 1;
257                } else {
258                    toks.push((SqlTok::Cmp, i, i + 1));
259                    i += 1;
260                }
261            }
262            c if c.is_ascii_alphanumeric() || c == b'_' => {
263                let s = i;
264                while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
265                    i += 1;
266                }
267                toks.push((SqlTok::Word, s, i));
268            }
269            _ => i += 1,
270        }
271    }
272    let word = |t: &(SqlTok, usize, usize)| lit[t.1..t.2].to_ascii_uppercase();
273    let mut out = Vec::new();
274    for (k, t) in toks.iter().enumerate() {
275        match t.0 {
276            SqlTok::Cmp => {
277                let op = &lit[t.1..t.2];
278                let to = match op {
279                    "<" => "<=",
280                    "<=" => "<",
281                    ">" => ">=",
282                    _ => ">",
283                };
284                out.push((t.1, t.2, op.to_string(), to.to_string()));
285            }
286            SqlTok::Word => {
287                let w = word(t);
288                if (w == "MAX" || w == "MIN")
289                    && toks.get(k + 1).is_some_and(|n| n.0 == SqlTok::Open)
290                {
291                    let from = &lit[t.1..t.2];
292                    let upper = from.chars().all(|c| c.is_ascii_uppercase());
293                    let to = match (w == "MAX", upper) {
294                        (true, true) => "MIN",
295                        (true, false) => "min",
296                        (false, true) => "MAX",
297                        (false, false) => "max",
298                    };
299                    out.push((t.1, t.2, from.to_string(), to.to_string()));
300                }
301            }
302            _ => {}
303        }
304    }
305    // WHERE clauses: split the conjuncts at depth zero and drop one at a time.
306    for (k, t) in toks.iter().enumerate() {
307        if t.0 != SqlTok::Word || word(t) != "WHERE" {
308            continue;
309        }
310        let mut depth = 0usize;
311        let mut ands: Vec<(usize, usize)> = Vec::new();
312        let mut end = lit.trim_end_matches([' ', '\t', '\r', '\n', ';']).len();
313        let mut has_or = false;
314        let mut between = false;
315        let mut case_depth = 0usize;
316        for n in &toks[k + 1..] {
317            match n.0 {
318                SqlTok::Open => depth += 1,
319                SqlTok::Close => {
320                    if depth == 0 {
321                        end = lit[..n.1].trim_end().len();
322                        break;
323                    }
324                    depth -= 1;
325                }
326                SqlTok::Word if depth == 0 => match word(n).as_str() {
327                    // A `CASE … END` is one unit: its `AND`s and `OR`s are its own.
328                    "CASE" => case_depth += 1,
329                    "END" => case_depth = case_depth.saturating_sub(1),
330                    _ if case_depth > 0 => {}
331                    "ORDER" | "GROUP" | "LIMIT" | "HAVING" | "RETURNING" | "UNION" => {
332                        end = lit[..n.1].trim_end().len();
333                        break;
334                    }
335                    "OR" => has_or = true,
336                    "BETWEEN" => between = true,
337                    "AND" if between => between = false,
338                    "AND" => ands.push((n.1, n.2)),
339                    _ => {}
340                },
341                _ => {}
342            }
343        }
344        if has_or || ands.is_empty() {
345            continue;
346        }
347        let start = t.2 + lit[t.2..].len() - lit[t.2..].trim_start().len();
348        // Conjunct i runs from its start to the next AND (or the clause end).
349        let mut starts = vec![start];
350        let mut stops = Vec::new();
351        for &(a, b) in &ands {
352            stops.push(lit[..a].trim_end().len());
353            starts.push(b + lit[b..].len() - lit[b..].trim_start().len());
354        }
355        stops.push(end);
356        for i in 0..starts.len() {
357            let (a, b) = if i == 0 {
358                (starts[0], starts[1])
359            } else {
360                (ands[i - 1].0, stops[i])
361            };
362            if b <= a {
363                continue;
364            }
365            let from = lit[a..b].split_whitespace().collect::<Vec<_>>().join(" ");
366            out.push((a, b, from, String::new()));
367        }
368    }
369    out
370}
371
372/// One place a mutation applies.
373#[derive(Debug, Clone, PartialEq, Eq)]
374pub struct Site {
375    /// The key the file is held under in the project's source map.
376    pub key: PathBuf,
377    /// The project-relative, forward-slashed path shown to the user.
378    pub path: String,
379    pub start: usize,
380    pub end: usize,
381    pub line: usize,
382    pub column: usize,
383    pub end_line: usize,
384    pub end_column: usize,
385    /// The unit (`orders`) and declaration (`refund`) the site is in.
386    pub unit: String,
387    pub decl: String,
388    pub from: String,
389    pub to: String,
390}
391
392impl Site {
393    fn qualified(&self) -> String {
394        format!("{}.{}", self.unit, self.decl)
395    }
396
397    fn id(&self) -> String {
398        format!("{}:{}:{}:{}", self.path, self.line, self.column, self.to)
399    }
400}
401
402/// What the project's files say about how units relate.
403#[derive(Debug, Default)]
404pub struct Model {
405    pub sites: Vec<Site>,
406    /// Unit → the units it `uses`.
407    uses: BTreeMap<String, BTreeSet<String>>,
408    /// Each suite: its target and the units it `uses`.
409    suites: Vec<(String, BTreeSet<String>)>,
410}
411
412impl Model {
413    /// Every unit `unit` depends on, itself included.
414    fn closure(&self, units: impl IntoIterator<Item = String>) -> BTreeSet<String> {
415        let mut seen = BTreeSet::new();
416        let mut work: Vec<String> = units.into_iter().collect();
417        while let Some(u) = work.pop() {
418            if !seen.insert(u.clone()) {
419                continue;
420            }
421            if let Some(next) = self.uses.get(&u) {
422                work.extend(next.iter().cloned());
423            }
424        }
425        seen
426    }
427
428    /// The suite targets (their names as the runner reports them) that reach
429    /// `unit`: they target it, or a unit that depends on it, or `use` it.
430    pub fn suites_reaching(&self, unit: &str) -> BTreeSet<String> {
431        self.suites
432            .iter()
433            .filter(|(target, uses)| {
434                self.closure(std::iter::once(target.clone()).chain(uses.iter().cloned()))
435                    .contains(unit)
436            })
437            .map(|(target, _)| target.clone())
438            .collect()
439    }
440}
441
442/// Lex and parse every file in `sources`, collecting the unit graph and the
443/// mutation sites of the non-suite files. A file that does not parse
444/// contributes nothing (the baseline run fails first on it).
445pub fn build_model(
446    root: &Path,
447    sources: &HashMap<PathBuf, String>,
448    d1: &[crate::project::D1SqlRef],
449) -> Model {
450    let mut keys: Vec<&PathBuf> = sources
451        .keys()
452        .filter(|k| k.extension().is_some_and(|e| e == "bynk"))
453        .collect();
454    keys.sort();
455    let mut model = Model::default();
456    // Pass one: parse every file and collect the unit graph and each unit's
457    // constants, so a D1 call's `const` argument can be found in any file.
458    // (unit, name, file, the literal's span or the name it is bound to)
459    type ConstInit = (String, String, PathBuf, Result<(usize, usize), String>);
460    struct Parsed {
461        key: PathBuf,
462        tokens: Vec<bynk_syntax::lexer::Token>,
463        unit: SourceUnit,
464        name: String,
465    }
466    let mut parsed: Vec<Parsed> = Vec::new();
467    let mut consts: Vec<ConstInit> = Vec::new();
468    for (index, key) in keys.into_iter().enumerate() {
469        let text = &sources[key];
470        let file = FileId(index as u32);
471        let Ok(tokens) = tokenize_in(text, file) else {
472            continue;
473        };
474        let Ok(unit) = parse_unit(&tokens, text) else {
475            continue;
476        };
477        let (name, uses, items) = match &unit {
478            SourceUnit::Commons(c) => (c.name.joined(), &c.uses, &c.items),
479            SourceUnit::Context(c) => (c.name.joined(), &c.uses, &c.items),
480            SourceUnit::Suite(s) => {
481                let used = s.uses.iter().map(|u| u.target.joined()).collect();
482                model.suites.push((s.target.joined(), used));
483                continue;
484            }
485            SourceUnit::Adapter(_) => continue,
486        };
487        model
488            .uses
489            .entry(name.clone())
490            .or_default()
491            .extend(uses.iter().map(|u| u.target.joined()));
492        for item in items {
493            if let bynk_syntax::ast::CommonsItem::Const(c) = item {
494                let init = match &c.init.kind {
495                    bynk_syntax::ast::ExprKind::StrLit(_) => {
496                        Ok((c.init.span.start, c.init.span.end))
497                    }
498                    bynk_syntax::ast::ExprKind::Ident(id) => Err(id.name.clone()),
499                    _ => continue,
500                };
501                consts.push((name.clone(), c.name.name.clone(), key.clone(), init));
502            }
503        }
504        parsed.push(Parsed {
505            key: key.clone(),
506            tokens,
507            unit,
508            name,
509        });
510    }
511    // The D1 arguments: literals directly, and the constants they name, which
512    // resolve in the calling unit or a unit it `uses`; a constant bound to
513    // another constant extends the set the same way.
514    let canon = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
515    let direct: BTreeSet<(PathBuf, usize, usize)> = d1
516        .iter()
517        .filter(|r| r.konst.is_none())
518        .map(|r| (canon(&r.path), r.start, r.end))
519        .collect();
520    let mut wanted: BTreeSet<(String, String)> = d1
521        .iter()
522        .filter_map(|r| Some((r.unit.clone(), r.konst.clone()?)))
523        .collect();
524    let mut sql_consts: BTreeSet<(PathBuf, usize, usize)> = BTreeSet::new();
525    loop {
526        let before = (wanted.len(), sql_consts.len());
527        for (unit, name, file, init) in &consts {
528            let reached = wanted.iter().any(|(u, n)| {
529                n == name && (u == unit || model.uses.get(u).is_some_and(|us| us.contains(unit)))
530            });
531            if !reached {
532                continue;
533            }
534            match init {
535                Ok((a, b)) => {
536                    sql_consts.insert((file.clone(), *a, *b));
537                }
538                Err(next) => {
539                    wanted.insert((unit.clone(), next.clone()));
540                }
541            }
542        }
543        if (wanted.len(), sql_consts.len()) == before {
544            break;
545        }
546    }
547    for Parsed {
548        key,
549        tokens,
550        unit,
551        name,
552    } in parsed
553    {
554        let text = &sources[&key];
555        let key = &key;
556        let items = match &unit {
557            SourceUnit::Commons(c) => &c.items,
558            SourceUnit::Context(c) => &c.items,
559            _ => continue,
560        };
561        let canon_key = canon(key);
562        let path = display(root, key);
563        let positions = LineIndex::new(text);
564        let sig: Vec<&bynk_syntax::lexer::Token> = tokens
565            .iter()
566            .filter(|t| t.kind != TokenKind::Comment)
567            .collect();
568        let mut found: Vec<(usize, usize, String, String)> = Vec::new();
569        for (i, token) in sig.iter().enumerate() {
570            let (start, end) = (token.span.start, token.span.end);
571            if let Some((from, to)) = replacement(&token.kind) {
572                if text.get(start..end) == Some(from) {
573                    found.push((start, end, from.to_string(), to.to_string()));
574                }
575            } else if matches!(token.kind, TokenKind::Plus | TokenKind::Minus) {
576                // Only a binary `+`/`-`: after an operand, not after an
577                // operator, `(` or keyword (where `-` is negation).
578                // A newline between them starts a new line (`-1 => …` after
579                // an arm), where `-` is negation.
580                let same_line = i > 0
581                    && text
582                        .get(sig[i - 1].span.end..start)
583                        .is_some_and(|gap| !gap.contains('\n'));
584                let after_operand = same_line
585                    && matches!(
586                        sig[i - 1].kind,
587                        TokenKind::Ident
588                            | TokenKind::IntLit
589                            | TokenKind::FloatLit
590                            | TokenKind::DecimalLit
591                            | TokenKind::Duration
592                            | TokenKind::RParen
593                            | TokenKind::RBracket
594                    );
595                let (from, to) = if token.kind == TokenKind::Plus {
596                    ("+", "-")
597                } else {
598                    ("-", "+")
599                };
600                if after_operand && text.get(start..end) == Some(from) {
601                    found.push((start, end, from.to_string(), to.to_string()));
602                }
603            } else if token.kind == TokenKind::StrLit {
604                let is_sql = direct.contains(&(canon_key.clone(), start, end))
605                    || sql_consts.contains(&(key.clone(), start, end));
606                if let Some(lit) = text.get(start..end).filter(|_| is_sql) {
607                    for (a, b, from, to) in sql_mutations(lit) {
608                        found.push((start + a, start + b, from, to));
609                    }
610                }
611            } else if token.kind == TokenKind::If {
612                // An `if` condition (or a match arm's `if` guard) runs from
613                // after the keyword to the `{` that opens the branch or the
614                // `=>` that ends the guard, at bracket depth zero. A
615                // condition that spans a `{` mis-cuts here and becomes an
616                // `invalid` mutant, which is dropped.
617                let mut depth = 0usize;
618                let mut close = None;
619                for (j, t) in sig.iter().enumerate().skip(i + 1) {
620                    match t.kind {
621                        TokenKind::LParen | TokenKind::LBracket => depth += 1,
622                        TokenKind::RParen | TokenKind::RBracket => depth = depth.saturating_sub(1),
623                        TokenKind::LBrace | TokenKind::FatArrow if depth == 0 => {
624                            close = Some(j);
625                            break;
626                        }
627                        _ => {}
628                    }
629                }
630                let Some(j) = close else { continue };
631                if j == i + 1 {
632                    continue;
633                }
634                let (cs, ce) = (sig[i + 1].span.start, sig[j - 1].span.end);
635                let Some(cond) = text.get(cs..ce) else {
636                    continue;
637                };
638                for to in ["true", "false"] {
639                    if cond.trim() != to {
640                        found.push((
641                            cs,
642                            ce,
643                            cond.split_whitespace().collect::<Vec<_>>().join(" "),
644                            to.to_string(),
645                        ));
646                    }
647                }
648            }
649        }
650        for (start, end, from, to) in found {
651            let Some(item) = items
652                .iter()
653                .find(|i| i.span().start <= start && end <= i.span().end)
654            else {
655                continue;
656            };
657            let Some(decl) = item.name() else { continue };
658            let (line, column) = positions.at(start);
659            let (end_line, end_column) = positions.at(end);
660            model.sites.push(Site {
661                key: key.clone(),
662                path: path.clone(),
663                start,
664                end,
665                line,
666                column,
667                end_line,
668                end_column,
669                unit: name.clone(),
670                decl: decl.name.clone(),
671                from,
672                to,
673            });
674        }
675    }
676    model
677        .sites
678        .sort_by(|a, b| (&a.path, a.start).cmp(&(&b.path, b.start)));
679    model
680}
681
682fn display(root: &Path, path: &Path) -> String {
683    let rel = path.strip_prefix(root).unwrap_or(path);
684    rel.to_string_lossy().replace('\\', "/")
685}
686
687/// Byte offset → 1-based (line, column in characters).
688struct LineIndex<'a> {
689    text: &'a str,
690    starts: Vec<usize>,
691}
692
693impl<'a> LineIndex<'a> {
694    fn new(text: &'a str) -> Self {
695        let mut starts = vec![0];
696        starts.extend(text.match_indices('\n').map(|(i, _)| i + 1));
697        LineIndex { text, starts }
698    }
699
700    fn at(&self, offset: usize) -> (usize, usize) {
701        let line = self.starts.partition_point(|&s| s <= offset) - 1;
702        let column = self.text[self.starts[line]..offset].chars().count() + 1;
703        (line + 1, column)
704    }
705}
706
707/// `text` with the site's operator replaced.
708pub fn apply(text: &str, site: &Site) -> String {
709    let mut out = String::with_capacity(text.len() + 1);
710    out.push_str(&text[..site.start]);
711    out.push_str(&site.to);
712    out.push_str(&text[site.end..]);
713    out
714}
715
716/// A tiny glob: `*` matches within a path segment, `**` across segments.
717fn glob_matches(pattern: &str, path: &str) -> bool {
718    fn go(p: &[u8], s: &[u8]) -> bool {
719        match p.split_first() {
720            None => s.is_empty(),
721            Some((b'*', rest)) => {
722                if let Some(rest) = rest.strip_prefix(b"*") {
723                    // `**`: any run of characters, `/` included.
724                    let rest = rest.strip_prefix(b"/").unwrap_or(rest);
725                    // Only at a segment boundary: `src/**/x.bynk` is not
726                    // `src/ax.bynk`.
727                    (0..=s.len())
728                        .filter(|&i| i == 0 || i == s.len() || s[i - 1] == b'/')
729                        .any(|i| go(rest, &s[i..]))
730                } else {
731                    let limit = s.iter().position(|&c| c == b'/').unwrap_or(s.len());
732                    (0..=limit).any(|i| go(rest, &s[i..]))
733                }
734            }
735            Some((c, rest)) => s.split_first().is_some_and(|(d, t)| c == d && go(rest, t)),
736        }
737    }
738    go(pattern.as_bytes(), path.as_bytes())
739}
740
741/// Does `entry` (a `bynk.toml` `exclude` item or `--only` value) name `site`?
742/// A name is `unit`, or `unit.decl`; anything with a `/` or `*` is a path glob.
743fn names(entry: &str, site: &Site) -> bool {
744    if entry.contains('/') || entry.contains('*') {
745        glob_matches(entry, &site.path)
746    } else {
747        entry == site.unit || entry == site.qualified()
748    }
749}
750
751/// One mutant's result, filled in by whichever job ran it.
752type Slot = std::sync::Mutex<Option<(Status, Vec<String>)>>;
753
754/// How a mutant's run ended.
755#[derive(Debug, Clone, Copy, PartialEq, Eq)]
756enum Status {
757    Killed,
758    Timeout,
759    Survived,
760    Invalid,
761    NoSuite,
762}
763
764impl Status {
765    fn word(self) -> &'static str {
766        match self {
767            Status::Killed => "killed",
768            Status::Timeout => "timeout",
769            Status::Survived => "survived",
770            Status::Invalid => "invalid",
771            Status::NoSuite => "no_suite",
772        }
773    }
774
775    /// Its colour: a killed or timed-out mutant is a success, a survivor a
776    /// failure, one no suite reaches a warning, and one that didn't compile
777    /// only information.
778    fn style(self) -> crate::colour::Style {
779        use crate::colour::Style;
780        match self {
781            Status::Killed | Status::Timeout => Style::Green,
782            Status::Survived => Style::Red,
783            Status::NoSuite => Style::Amber,
784            Status::Invalid => Style::Blue,
785        }
786    }
787}
788
789/// A mutation run's counts, for its human report.
790struct Tally {
791    total: usize,
792    /// Killed or timed out.
793    killed: usize,
794    survived: usize,
795    no_suite: usize,
796    invalid: usize,
797    score: u32,
798}
799
800/// The human report of a mutation run: the tally, then each mutant that
801/// survived or that no suite reached. With `colour`, the counts and labels take
802/// their statuses' colours, a count of zero staying plain, and the score is red,
803/// amber or green as a coverage percentage is.
804fn human_report(t: &Tally, results: &[(Site, Status, Vec<String>)], colour: bool) -> String {
805    use crate::colour::{Style, coverage_style, paint};
806    let count = |n: usize, what: &str, status: Status| {
807        let text = format!("{n} {what}");
808        if n == 0 {
809            text
810        } else {
811            paint(colour, status.style(), &text)
812        }
813    };
814    let mut out = format!(
815        "{} {} mutants, {}, {}, {}, {} (score {})\n",
816        paint(colour, Style::Bold, "mutation:"),
817        t.total,
818        count(t.killed, "killed", Status::Killed),
819        count(t.survived, "survived", Status::Survived),
820        count(t.no_suite, "not covered by any suite", Status::NoSuite),
821        count(t.invalid, "invalid", Status::Invalid),
822        paint(colour, coverage_style(t.score), &format!("{}%", t.score)),
823    );
824    for (site, status, _) in results {
825        let label = match status {
826            Status::Survived => "SURVIVED",
827            Status::NoSuite => "NO SUITE",
828            _ => continue,
829        };
830        out.push_str(&format!(
831            "  {} {}:{}:{}  {}  `{}` → `{}`\n",
832            paint(colour, status.style(), &format!("{label:<9}")),
833            site.path,
834            site.line,
835            site.column,
836            site.qualified(),
837            site.from,
838            site.to
839        ));
840    }
841    out
842}
843
844/// Classify the document one mutant's run printed.
845fn classify(doc: &Value) -> Status {
846    if let Some(error) = doc.get("error") {
847        // A run that crashes before any case runs (a mutant that throws as the
848        // module loads) is `invalid` with the rest: the suites were not what
849        // told it from the original.
850        return if error.get("kind").and_then(Value::as_str) == Some("timeout") {
851            Status::Timeout
852        } else {
853            Status::Invalid
854        };
855    }
856    match doc.get("failed").and_then(Value::as_u64) {
857        Some(0) => Status::Survived,
858        Some(_) => Status::Killed,
859        None => Status::Invalid,
860    }
861}
862
863struct Scratch(PathBuf);
864
865impl Drop for Scratch {
866    fn drop(&mut self) {
867        let _ = std::fs::remove_dir_all(&self.0);
868    }
869}
870
871fn fail(program: &str, json: bool, message: String) -> ExitCode {
872    if json {
873        crate::test_stream::print_run(false, &TestRun::runtime_error(message, None));
874    } else {
875        emsg!("{program} test: error: {message}");
876    }
877    ExitCode::FAILURE
878}
879
880/// Run one in-process `bynk test` and parse the JSON document it prints.
881fn run_once(args: TestArgs) -> (bool, String, Option<Value>) {
882    let (code, text) = crate::test_stream::capture(|| run_test("bynk", args));
883    let doc = serde_json::from_str(&text).ok();
884    (code == ExitCode::SUCCESS, text, doc)
885}
886
887/// What a failed unmutated run said, for a reader of the rich output.
888fn describe_failure(doc: Option<&Value>, raw: &str) -> String {
889    let Some(doc) = doc else {
890        return raw.trim_end().to_string();
891    };
892    let mut lines = Vec::new();
893    if let Some(error) = doc.get("error") {
894        if let Some(message) = error.get("message").and_then(Value::as_str) {
895            lines.push(message.to_string());
896        }
897        for key in ["diagnostics", "stderr"] {
898            match error.get(key) {
899                Some(Value::Array(items)) => {
900                    lines.extend(items.iter().filter_map(Value::as_str).map(str::to_string))
901                }
902                Some(Value::String(text)) => lines.push(text.trim_end().to_string()),
903                _ => {}
904            }
905        }
906    }
907    for suite in doc
908        .get("suites")
909        .and_then(Value::as_array)
910        .into_iter()
911        .flatten()
912    {
913        let name = suite.get("name").and_then(Value::as_str).unwrap_or("?");
914        for case in suite
915            .get("cases")
916            .and_then(Value::as_array)
917            .into_iter()
918            .flatten()
919            .filter(|c| c.get("outcome").and_then(Value::as_str) == Some("fail"))
920        {
921            let case_name = case.get("name").and_then(Value::as_str).unwrap_or("?");
922            lines.push(format!("✗ {name}: {case_name}"));
923            if let Some(message) = case.get("message").and_then(Value::as_str) {
924                lines.push(format!("    {}", message.replace('\n', "\n    ")));
925            }
926        }
927    }
928    if lines.is_empty() {
929        raw.trim_end().to_string()
930    } else {
931        lines.join("\n")
932    }
933}
934
935/// Run `bynk test --mutate`.
936pub fn run(program: &str, args: MutateArgs) -> ExitCode {
937    let MutateArgs {
938        input,
939        json,
940        seed,
941        suite,
942        only,
943        max_mutants,
944        timeout,
945        all_suites,
946        fail_under,
947        changed,
948        jobs,
949    } = args;
950    if !input.is_dir() {
951        return fail(
952            program,
953            json,
954            format!(
955                "input `{}` must be a project directory containing `.bynk` files",
956                input.display()
957            ),
958        );
959    }
960    let (sources, d1) = match crate::try_project_options(&input) {
961        Ok(options) => {
962            // #3142: which string literals are SQL is the checker's call: the
963            // arguments of D1 calls, not a guess from the text.
964            let d1 = crate::project::check_project(&options).d1_sql_sites;
965            (options.sources.unwrap_or_default(), d1)
966        }
967        Err(e) => return fail(program, json, e.to_string()),
968    };
969    let exclude = match crate::project::try_read_mutate_exclude(&input) {
970        Ok(list) => list,
971        Err(e) => return fail(program, json, e),
972    };
973    let mut model = build_model(&input, &sources, &d1);
974    model.sites.retain(|s| !exclude.iter().any(|e| names(e, s)));
975    if let Some(only) = &only {
976        model.sites.retain(|s| names(only, s));
977        if model.sites.is_empty() {
978            return fail(
979                program,
980                json,
981                format!(
982                    "`--only {only}` names no declaration with anything to mutate (use `unit` or `unit.decl`)"
983                ),
984            );
985        }
986    }
987    let changed_set = match &changed {
988        Some(rev) => match changed_files(&input, rev) {
989            Ok(files) => Some(files),
990            Err(e) => return fail(program, json, e),
991        },
992        None => None,
993    };
994    if let Some(files) = &changed_set {
995        model.sites.retain(|s| files.contains(&s.path));
996    }
997    let scratch = Scratch(std::env::temp_dir().join(format!(
998        "bynk-mutate-{}-{}",
999        std::process::id(),
1000        std::time::SystemTime::now()
1001            .duration_since(std::time::UNIX_EPOCH)
1002            .map_or(0, |d| d.as_nanos())
1003    )));
1004    let seed = Some(seed.unwrap_or_else(|| DEFAULT_SEED.to_string()));
1005    let base_args = |dir: &str, suites: Vec<String>| TestArgs {
1006        no_run: false,
1007        format: TestFormat::Json,
1008        output: Some(scratch.0.join(dir)),
1009        seed: seed.clone(),
1010        suite: suites,
1011        ..TestArgs::discovery(input.clone())
1012    };
1013
1014    // The unmutated project must pass: otherwise every mutant "fails" and is
1015    // killed by the baseline's own failure.
1016    if !json {
1017        emsg!("{program} test: running the unmutated suites first");
1018    }
1019    let started = Instant::now();
1020    let (ok, text, doc) = run_once(base_args("out", suite.clone()));
1021    let baseline_time = started.elapsed();
1022    let Some(mut baseline) = doc.clone().filter(|_| ok) else {
1023        if json {
1024            print!("{text}");
1025        } else {
1026            eprintln!("{}", describe_failure(doc.as_ref(), &text));
1027        }
1028        emsg!(
1029            "{program} test: error: the unmutated project does not pass, so there is nothing to mutate — fix it first"
1030        );
1031        return ExitCode::FAILURE;
1032    };
1033    let suite_names: Vec<String> = baseline
1034        .get("suites")
1035        .and_then(Value::as_array)
1036        .map(|suites| {
1037            suites
1038                .iter()
1039                .filter_map(|s| s.get("name").and_then(Value::as_str).map(str::to_string))
1040                .collect()
1041        })
1042        .unwrap_or_default();
1043    let timeout = timeout.unwrap_or_else(|| (baseline_time * 3).max(Duration::from_secs(10)));
1044
1045    if let Some(max) = max_mutants {
1046        model.sites.truncate(max);
1047    }
1048    let total = model.sites.len();
1049    // Each mutant is independent, so they run on `jobs` threads, each with its
1050    // own scratch output directory. A result lands in the slot of its site's
1051    // index, so the report reads the same whatever `jobs` was (#3134).
1052    let jobs = jobs.clamp(1, total.max(1));
1053    let slots: Vec<Slot> = (0..total).map(|_| std::sync::Mutex::new(None)).collect();
1054    let next = std::sync::atomic::AtomicUsize::new(0);
1055    let finished = std::sync::atomic::AtomicUsize::new(0);
1056    let worker = |w: usize| {
1057        // `bynk test` puts its compiled JavaScript inside the output directory
1058        // (`<out>/out-js`), so each job needs an output directory of its own.
1059        let dir = if jobs == 1 {
1060            "out".to_string()
1061        } else {
1062            format!("job-{w}/out")
1063        };
1064        loop {
1065            let i = next.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1066            let Some(site) = model.sites.get(i) else {
1067                break;
1068            };
1069            let selected: Vec<String> = if all_suites {
1070                suite.clone()
1071            } else {
1072                let reaching = model.suites_reaching(&site.unit);
1073                suite_names
1074                    .iter()
1075                    .filter(|n| reaching.contains(*n))
1076                    .cloned()
1077                    .collect()
1078            };
1079            let status = if !all_suites && selected.is_empty() {
1080                Status::NoSuite
1081            } else {
1082                let text = apply(&sources[&site.key], site);
1083                let (_, _, doc) = run_once(TestArgs {
1084                    mutant_overlay: Some((site.key.clone(), text)),
1085                    run_timeout: Some(timeout),
1086                    ..base_args(&dir, selected.clone())
1087                });
1088                doc.as_ref().map_or(Status::Invalid, classify)
1089            };
1090            if !json {
1091                let n = finished.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
1092                eprintln!(
1093                    "[{n}/{total}] {}:{}:{} `{}` → `{}`: {}",
1094                    site.path,
1095                    site.line,
1096                    site.column,
1097                    site.from,
1098                    site.to,
1099                    crate::colour::paint(
1100                        crate::colour::stderr(),
1101                        status.style(),
1102                        &status.word().replace('_', " ")
1103                    )
1104                );
1105            }
1106            let shown = if all_suites && status != Status::Invalid {
1107                suite_names.clone()
1108            } else {
1109                selected
1110            };
1111            *slots[i].lock().unwrap_or_else(|e| e.into_inner()) = Some((status, shown));
1112        }
1113    };
1114    std::thread::scope(|scope| {
1115        for w in 1..jobs {
1116            let worker = &worker;
1117            scope.spawn(move || worker(w));
1118        }
1119        worker(0);
1120    });
1121    let results: Vec<(Site, Status, Vec<String>)> = model
1122        .sites
1123        .iter()
1124        .cloned()
1125        .zip(slots)
1126        .map(|(site, slot)| {
1127            let (status, shown) = slot
1128                .into_inner()
1129                .unwrap_or_else(|e| e.into_inner())
1130                .unwrap_or((Status::Invalid, Vec::new()));
1131            (site, status, shown)
1132        })
1133        .collect();
1134
1135    let count = |s: Status| results.iter().filter(|(_, st, _)| *st == s).count();
1136    let (killed, timed_out) = (count(Status::Killed), count(Status::Timeout));
1137    let (survived, invalid, no_suite) = (
1138        count(Status::Survived),
1139        count(Status::Invalid),
1140        count(Status::NoSuite),
1141    );
1142    let ran = killed + timed_out + survived;
1143    let score = crate::coverage::percent((killed + timed_out) as u32, ran as u32);
1144
1145    if json {
1146        let mutants: Vec<Value> = results
1147            .iter()
1148            .map(|(s, st, suites)| {
1149                json!({
1150                    "id": s.id(),
1151                    "file": s.path,
1152                    "line": s.line,
1153                    "column": s.column,
1154                    "end_line": s.end_line,
1155                    "end_column": s.end_column,
1156                    "unit": s.unit,
1157                    "decl": s.decl,
1158                    "from": s.from,
1159                    "to": s.to,
1160                    "status": st.word(),
1161                    "suites": suites,
1162                })
1163            })
1164            .collect();
1165        baseline["mutation"] = json!({
1166            "total": total,
1167            "killed": killed,
1168            "timeout": timed_out,
1169            "survived": survived,
1170            "no_suite": no_suite,
1171            "invalid": invalid,
1172            "score": score,
1173            "mutants": mutants,
1174        });
1175        if let (Some(rev), Some(files)) = (&changed, &changed_set) {
1176            baseline["mutation"]["changed"] = json!({ "ref": rev, "files": files });
1177        }
1178        println!(
1179            "{}",
1180            serde_json::to_string_pretty(&baseline).unwrap_or_default()
1181        );
1182    } else {
1183        let tally = Tally {
1184            total,
1185            killed: killed + timed_out,
1186            survived,
1187            no_suite,
1188            invalid,
1189            score,
1190        };
1191        print!(
1192            "{}",
1193            human_report(&tally, &results, crate::colour::stdout())
1194        );
1195        if ran == 0 && total > 0 {
1196            println!("no mutant reached a suite — nothing was scored");
1197        }
1198    }
1199    match fail_under {
1200        // Nothing changed is nothing to fail: a diff with no `.bynk`
1201        // declarations to mutate meets any threshold.
1202        Some(_) if total == 0 && changed.is_some() => {
1203            let rev = changed.as_deref().unwrap_or_default();
1204            if !json {
1205                println!("no declarations changed since {rev}, so nothing was mutated");
1206            }
1207            ExitCode::SUCCESS
1208        }
1209        Some(min) if ran == 0 => {
1210            emsg!(
1211                "{program} test: error: no mutant reached a suite, so --mutate-fail-under {min} cannot be met"
1212            );
1213            ExitCode::FAILURE
1214        }
1215        Some(min) if score < min => {
1216            emsg!(
1217                "{program} test: error: mutation score {score}% is below --mutate-fail-under {min}"
1218            );
1219            ExitCode::FAILURE
1220        }
1221        _ => ExitCode::SUCCESS,
1222    }
1223}
1224
1225#[cfg(test)]
1226mod tests {
1227    /// The human report reads as it always has without colour, and with it
1228    /// each count and label takes its status's colour and the score its band.
1229    #[test]
1230    fn the_human_report_colours_by_status() {
1231        use super::{Site, Status, Tally, human_report};
1232        let site = |line, from: &str, to: &str| Site {
1233            key: "src/todos.bynk".into(),
1234            path: "src/todos.bynk".into(),
1235            start: 0,
1236            end: 1,
1237            line,
1238            column: 3,
1239            end_line: line,
1240            end_column: 4,
1241            unit: "todos".into(),
1242            decl: "add".into(),
1243            from: from.into(),
1244            to: to.into(),
1245        };
1246        let results = vec![
1247            (site(1, "+", "-"), Status::Killed, Vec::new()),
1248            (site(2, "==", "!="), Status::Survived, Vec::new()),
1249            (site(3, "<", "<="), Status::NoSuite, Vec::new()),
1250        ];
1251        let tally = Tally {
1252            total: 3,
1253            killed: 1,
1254            survived: 1,
1255            no_suite: 1,
1256            invalid: 0,
1257            score: 50,
1258        };
1259        assert_eq!(
1260            human_report(&tally, &results, false),
1261            "mutation: 3 mutants, 1 killed, 1 survived, 1 not covered by any suite, 0 invalid (score 50%)\n\
1262             \x20 SURVIVED  src/todos.bynk:2:3  todos.add  `==` → `!=`\n\
1263             \x20 NO SUITE  src/todos.bynk:3:3  todos.add  `<` → `<=`\n"
1264        );
1265        let coloured = human_report(&tally, &results, true);
1266        for part in [
1267            "\x1b[1mmutation:\x1b[22m 3 mutants, ",
1268            "\x1b[32m1 killed\x1b[39m",
1269            "\x1b[31m1 survived\x1b[39m",
1270            "\x1b[33m1 not covered by any suite\x1b[39m",
1271            ", 0 invalid (score \x1b[33m50%\x1b[39m)",
1272            "  \x1b[31mSURVIVED \x1b[39m src/todos.bynk:2:3",
1273            "  \x1b[33mNO SUITE \x1b[39m src/todos.bynk:3:3",
1274        ] {
1275            assert!(coloured.contains(part), "{part:?} in:\n{coloured}");
1276        }
1277    }
1278
1279    use super::*;
1280
1281    fn sources(files: &[(&str, &str)]) -> HashMap<PathBuf, String> {
1282        files
1283            .iter()
1284            .map(|(p, t)| (PathBuf::from(format!("/proj/{p}")), t.to_string()))
1285            .collect()
1286    }
1287
1288    const LIMITS: &str =
1289        "commons limits\n\nfn within(a: Int, b: Int) -> Bool {\n  a < b && b != 0\n}\n";
1290
1291    #[test]
1292    fn finds_comparison_and_connective_sites_with_spans() {
1293        let model = build_model(
1294            Path::new("/proj"),
1295            &sources(&[("src/limits.bynk", LIMITS)]),
1296            &[],
1297        );
1298        let found: Vec<(String, &str, &str, usize, usize)> = model
1299            .sites
1300            .iter()
1301            .map(|s| {
1302                (
1303                    s.qualified(),
1304                    s.from.as_str(),
1305                    s.to.as_str(),
1306                    s.line,
1307                    s.column,
1308                )
1309            })
1310            .collect();
1311        assert_eq!(
1312            found,
1313            vec![
1314                ("limits.within".to_string(), "<", "<=", 4, 5),
1315                ("limits.within".to_string(), "&&", "||", 4, 9),
1316                ("limits.within".to_string(), "!=", "==", 4, 14),
1317            ]
1318        );
1319        assert_eq!(model.sites[0].path, "src/limits.bynk");
1320    }
1321
1322    #[test]
1323    fn finds_if_conditions_match_guards_and_binary_arithmetic() {
1324        let text = "commons c\n\nfn f(a: Int, b: Int) -> Int {\n  if a > 0 { a + b } else { -b - 1 }\n}\n\nfn g(o: Option[Int]) -> Int {\n  match o {\n    Some(n) if n > 1 => n\n    _ => 0\n  }\n}\n";
1325        let model = build_model(Path::new("/proj"), &sources(&[("src/c.bynk", text)]), &[]);
1326        let found: Vec<(&str, &str, &str)> = model
1327            .sites
1328            .iter()
1329            .map(|s| (s.decl.as_str(), s.from.as_str(), s.to.as_str()))
1330            .collect();
1331        for want in [
1332            ("f", "a > 0", "true"),
1333            ("f", "a > 0", "false"),
1334            ("f", "+", "-"),
1335            ("f", "-", "+"),
1336            ("g", "n > 1", "true"),
1337            ("g", "n > 1", "false"),
1338        ] {
1339            assert!(found.contains(&want), "missing {want:?} in {found:?}");
1340        }
1341        // The negation `-b` is not a site: exactly one `-`→`+`.
1342        assert_eq!(found.iter().filter(|f| f.1 == "-").count(), 1);
1343        let cond = model.sites.iter().find(|s| s.to == "true").unwrap();
1344        assert_eq!(
1345            apply(text, cond).lines().nth(3).unwrap(),
1346            "  if true { a + b } else { -b - 1 }"
1347        );
1348    }
1349
1350    #[test]
1351    fn wrapped_conditions_display_on_one_line_and_ids_are_unique() {
1352        let text = "commons c\n\nfn f(a: Int, b: Int) -> Int {\n  if a > 0 &&\n    b > 0 { a } else { b }\n}\n\nfn g(a: Int) -> Int {\n  match a {\n    0 => a\n    -1 => 2\n    _ => 3\n  }\n}\n";
1353        let model = build_model(Path::new("/proj"), &sources(&[("src/c.bynk", text)]), &[]);
1354        let cond: Vec<&Site> = model
1355            .sites
1356            .iter()
1357            .filter(|s| s.to == "true" || s.to == "false")
1358            .collect();
1359        assert_eq!(cond.len(), 2);
1360        assert!(cond.iter().all(|s| s.from == "a > 0 && b > 0"));
1361        let mutant = apply(text, cond[0]);
1362        assert!(mutant.contains("if true { a }") && !mutant.contains("&&"));
1363        let ids: BTreeSet<String> = model.sites.iter().map(Site::id).collect();
1364        assert_eq!(ids.len(), model.sites.len(), "ids are unique");
1365        assert!(
1366            !model.sites.iter().any(|s| s.decl == "g" && s.from == "-"),
1367            "a `-` that starts a line is negation"
1368        );
1369    }
1370
1371    fn froms(lit: &str) -> Vec<(String, String)> {
1372        sql_mutations(lit)
1373            .into_iter()
1374            .map(|(_, _, f, t)| (f, t))
1375            .collect()
1376    }
1377
1378    #[test]
1379    fn sql_literals_yield_comparison_aggregate_and_conjunct_mutants() {
1380        let lit = r#""SELECT max(n) FROM t WHERE a > ?1 AND NOT EXISTS (SELECT 1 FROM u WHERE u.id = t.id AND u.k >= 2) AND b BETWEEN 1 AND 5 ORDER BY n""#;
1381        let found = froms(lit);
1382        for want in [
1383            ("max", "min"),
1384            (">", ">="),
1385            (">=", ">"),
1386            ("a > ?1 AND", ""),
1387            (
1388                "AND NOT EXISTS (SELECT 1 FROM u WHERE u.id = t.id AND u.k >= 2)",
1389                "",
1390            ),
1391            ("AND b BETWEEN 1 AND 5", ""),
1392            ("u.id = t.id AND", ""),
1393            ("AND u.k >= 2", ""),
1394        ] {
1395            assert!(
1396                found.iter().any(|(f, t)| (f.as_str(), t.as_str()) == want),
1397                "missing {want:?} in {found:?}"
1398            );
1399        }
1400        // `BETWEEN … AND …` is one conjunct, never split.
1401        assert!(!found.iter().any(|(f, _)| f == "AND 5"));
1402        // A raw literal is SQL too, and its closing `"#` is not part of a conjunct.
1403        let raw = sql_mutations("r#\"SELECT 1 FROM t WHERE a > 1 AND b = 2\"#");
1404        assert!(raw.iter().any(|m| m.2 == ">" && m.3 == ">="), "{raw:?}");
1405        assert!(
1406            raw.iter().any(|m| m.2 == "AND b = 2" && m.3.is_empty()),
1407            "{raw:?}"
1408        );
1409        // An `OR` in the clause leaves it alone; `<>` is not an ordering.
1410        let or = sql_mutations("\"SELECT 1 WHERE a <> 1 AND b = 2 OR c = 3\"");
1411        assert!(or.is_empty(), "{or:?}");
1412        // Lower-case SQL is scanned like any other.
1413        let lower = froms("\"select 1 from t where a > 1 and b = 2\"");
1414        assert!(
1415            lower.contains(&("a > 1 and".into(), String::new())),
1416            "{lower:?}"
1417        );
1418    }
1419
1420    #[test]
1421    fn an_escaped_newline_is_whitespace_and_ends_a_comment() {
1422        // `\n` is a newline, not the start of the word `nWHERE`.
1423        let lit = r#""SELECT 1 FROM t\nWHERE a > 1 AND b = 2""#;
1424        let found = froms(lit);
1425        assert!(
1426            found.contains(&("a > 1 AND".into(), String::new())),
1427            "{found:?}"
1428        );
1429        assert!(
1430            found.contains(&("AND b = 2".into(), String::new())),
1431            "{found:?}"
1432        );
1433        // A `--` comment ends at the escaped newline, so the `WHERE` after it counts.
1434        let lit = r#""SELECT 1 FROM t -- all rows\nWHERE a > 1 AND b = 2""#;
1435        let found = froms(lit);
1436        assert!(found.contains(&(">".into(), ">=".into())), "{found:?}");
1437        assert!(
1438            found.contains(&("a > 1 AND".into(), String::new())),
1439            "{found:?}"
1440        );
1441        // The offsets are the source's: dropping a conjunct across an escape
1442        // leaves a literal that still reads as one.
1443        let m = sql_mutations(lit)
1444            .into_iter()
1445            .find(|m| m.2 == "AND b = 2")
1446            .unwrap();
1447        let mut mutant = lit.to_string();
1448        mutant.replace_range(m.0..m.1, &m.3);
1449        assert_eq!(mutant, r#""SELECT 1 FROM t -- all rows\nWHERE a > 1 ""#);
1450    }
1451
1452    #[test]
1453    fn a_multi_line_literal_maps_back_through_its_indentation() {
1454        let lit = "\"\"\"\n    SELECT 1 FROM t\n    WHERE a > 1\n      AND b = 2\n    \"\"\"";
1455        let ms = sql_mutations(lit);
1456        let m = ms
1457            .iter()
1458            .find(|m| m.2 == "AND b = 2")
1459            .unwrap_or_else(|| panic!("{ms:?}"));
1460        let mut mutant = lit.to_string();
1461        mutant.replace_range(m.0..m.1, &m.3);
1462        assert!(
1463            mutant.contains("WHERE a > 1") && !mutant.contains("b = 2"),
1464            "{mutant}"
1465        );
1466        assert!(
1467            mutant.starts_with("\"\"\"") && mutant.ends_with("\"\"\""),
1468            "{mutant}"
1469        );
1470        let g = ms.iter().find(|m| m.2 == ">").unwrap();
1471        assert_eq!(&lit[g.0..g.1], ">");
1472    }
1473
1474    #[test]
1475    fn a_case_expression_in_a_where_is_one_conjunct() {
1476        let lit =
1477            "\"SELECT 1 FROM t WHERE CASE WHEN a > 1 AND b > 2 THEN 1 ELSE 0 END = 1 AND c = 3\"";
1478        let found = froms(lit);
1479        // Two conjuncts: the whole `CASE … END = 1` and `c = 3`.
1480        assert!(
1481            found.contains(&(
1482                "CASE WHEN a > 1 AND b > 2 THEN 1 ELSE 0 END = 1 AND".into(),
1483                String::new()
1484            )),
1485            "{found:?}"
1486        );
1487        assert!(
1488            found.contains(&("AND c = 3".into(), String::new())),
1489            "{found:?}"
1490        );
1491        assert!(
1492            !found.iter().any(|(f, _)| f.starts_with("AND b")),
1493            "{found:?}"
1494        );
1495        assert!(
1496            !found.iter().any(|(f, _)| f == "CASE WHEN a > 1 AND"),
1497            "{found:?}"
1498        );
1499        // An `OR` inside the `CASE` does not stop the clause being split.
1500        let lit = "\"SELECT 1 FROM t WHERE CASE WHEN a OR b THEN 1 END = 1 AND c = 3\"";
1501        assert!(
1502            froms(lit)
1503                .iter()
1504                .any(|(f, t)| f == "AND c = 3" && t.is_empty())
1505        );
1506    }
1507
1508    /// A project with a `D1` binding: the checker's D1 sites, then the model.
1509    fn d1_model(unit: &str) -> Model {
1510        let root = std::env::temp_dir().join(format!(
1511            "bynk-mutate-d1-{}-{}",
1512            std::process::id(),
1513            std::time::SystemTime::now()
1514                .duration_since(std::time::UNIX_EPOCH)
1515                .map_or(0, |d| d.as_nanos())
1516        ));
1517        let write = |rel: &str, text: &str| {
1518            let p = root.join(rel);
1519            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
1520            std::fs::write(p, text).unwrap();
1521        };
1522        write("bynk.toml", "");
1523        write("demo.bynk", unit);
1524        write(
1525            "migrations/demo-orders/0001_create.sql",
1526            "CREATE TABLE orders (id TEXT PRIMARY KEY, total INTEGER NOT NULL);",
1527        );
1528        let options = crate::try_project_options(&root).expect("options");
1529        let check = crate::project::check_project(&options);
1530        assert!(
1531            !check.has_errors(),
1532            "{:?}",
1533            check
1534                .errors
1535                .iter()
1536                .map(|e| e.error.message.clone())
1537                .collect::<Vec<_>>()
1538        );
1539        let model = build_model(
1540            &root,
1541            &options.sources.unwrap_or_default(),
1542            &check.d1_sql_sites,
1543        );
1544        let _ = std::fs::remove_dir_all(&root);
1545        model
1546    }
1547
1548    const D1_UNIT: &str = "context demo\n\nconsumes bynk.cloudflare { D1, SqlValue }\n\ncapability Orders = D1\n\n\
1549        const BIG: String = \"select id from orders where total > 1 and id = ?1\"\n\
1550        const ALIAS: String = BIG\n\
1551        const PROSE: String = \"DELETE <b>x</b> FROM here WHERE a > 1 AND b < 2\"\n\n\
1552        service probe {\n  on call(id: String) -> Effect[String] by Caller given Orders {\n    \
1553        let _ <- Orders.all(ALIAS, [Text(id)])\n    \
1554        let _ <- Orders.first(\"SELECT id FROM orders WHERE total >= 2\\n  AND id = ?1\", [Text(id)])\n    \
1555        let _ <- Orders.run(\"update orders set total = total + 1 where id = ?1\", [Text(id)])\n    \
1556        let note = \"Update failed: n > 3\"\n    \
1557        let _ = \"SELECT id FROM orders WHERE total > 5 AND id = ?1\"\n    \
1558        PROSE\n  }\n}\n";
1559
1560    #[test]
1561    fn only_literals_the_checker_ties_to_a_d1_call_get_sql_mutants() {
1562        let model = d1_model(D1_UNIT);
1563        let mut ours: Vec<(&str, &str)> = model
1564            .sites
1565            .iter()
1566            .map(|s| (s.from.as_str(), s.to.as_str()))
1567            .collect();
1568        ours.sort();
1569        // Exactly: the const bound to a call through an alias (lower-case SQL),
1570        // and the literal argument with a `\n` before its `AND`. Nothing from
1571        // prose, from a SQL-looking literal no D1 call takes, or from a const
1572        // none does; `update … set total = total + 1` has no site.
1573        let mut want = vec![
1574            (">", ">="),
1575            ("total > 1 and", ""),
1576            ("and id = ?1", ""),
1577            (">=", ">"),
1578            ("total >= 2 AND", ""),
1579            ("AND id = ?1", ""),
1580        ];
1581        want.sort();
1582        assert_eq!(ours, want);
1583    }
1584
1585    #[test]
1586    fn apply_replaces_exactly_the_operator() {
1587        let model = build_model(
1588            Path::new("/proj"),
1589            &sources(&[("src/limits.bynk", LIMITS)]),
1590            &[],
1591        );
1592        let mutant = apply(LIMITS, &model.sites[0]);
1593        assert_eq!(mutant, LIMITS.replacen("a < b", "a <= b", 1));
1594    }
1595
1596    #[test]
1597    fn operators_in_comments_and_strings_are_not_sites() {
1598        let text = "commons c\n\n// a < b\nfn f() -> String {\n  \"a == b\"\n}\n";
1599        let model = build_model(Path::new("/proj"), &sources(&[("src/c.bynk", text)]), &[]);
1600        assert!(model.sites.is_empty(), "{:?}", model.sites);
1601    }
1602
1603    #[test]
1604    fn a_suite_reaches_its_target_and_the_units_that_use_it() {
1605        let a = "commons a\n\nfn f(x: Int) -> Bool {\n  x > 1\n}\n";
1606        let b = "commons b\n\nuses a\n\nfn g(x: Int) -> Bool {\n  f(x)\n}\n";
1607        let c = "commons c\n\nfn h(x: Int) -> Bool {\n  x > 2\n}\n";
1608        let s = "suite b\n\ncase \"x\" {\n  expect g(2)\n}\n";
1609        let model = build_model(
1610            Path::new("/proj"),
1611            &sources(&[
1612                ("src/a.bynk", a),
1613                ("src/b.bynk", b),
1614                ("src/c.bynk", c),
1615                ("tests/b.bynk", s),
1616            ]),
1617            &[],
1618        );
1619        assert_eq!(
1620            model.suites_reaching("a"),
1621            BTreeSet::from(["b".to_string()])
1622        );
1623        assert_eq!(
1624            model.suites_reaching("b"),
1625            BTreeSet::from(["b".to_string()])
1626        );
1627        assert!(model.suites_reaching("c").is_empty());
1628    }
1629
1630    #[test]
1631    fn globs_and_names() {
1632        assert!(glob_matches("src/generated/**", "src/generated/a/b.bynk"));
1633        assert!(glob_matches("src/*.bynk", "src/a.bynk"));
1634        assert!(glob_matches("src/**/x.bynk", "src/a/x.bynk"));
1635        assert!(glob_matches("src/**/x.bynk", "src/x.bynk"));
1636        assert!(!glob_matches("src/**/x.bynk", "src/ax.bynk"));
1637        assert!(glob_matches("**/lonely.bynk", "src/lonely.bynk"));
1638        assert!(!glob_matches("**/lonely.bynk", "src/notlonely.bynk"));
1639        assert!(!glob_matches("src/*.bynk", "src/a/b.bynk"));
1640        let model = build_model(
1641            Path::new("/proj"),
1642            &sources(&[("src/limits.bynk", LIMITS)]),
1643            &[],
1644        );
1645        let site = &model.sites[0];
1646        assert!(names("limits", site));
1647        assert!(names("limits.within", site));
1648        assert!(!names("limits.other", site));
1649        assert!(names("src/**", site));
1650    }
1651
1652    #[test]
1653    fn classifies_run_documents() {
1654        assert_eq!(
1655            classify(&json!({"passed": 2, "failed": 0})),
1656            Status::Survived
1657        );
1658        assert_eq!(classify(&json!({"passed": 1, "failed": 1})), Status::Killed);
1659        assert_eq!(
1660            classify(&json!({"error": {"kind": "compile"}})),
1661            Status::Invalid
1662        );
1663        assert_eq!(
1664            classify(&json!({"error": {"kind": "timeout", "message": "timed out after 10s"}})),
1665            Status::Timeout
1666        );
1667    }
1668}