fallow-mutation 3.51.0

Mutant site discovery and mutation-switching instrumentation for fallow
Documentation
//! Instrumented text emission.
//!
//! The emitter copies the original text and replaces each site with a
//! mutation switch:
//!
//! ```text
//! (A("ID1") ? (MUT1) : A("ID2") ? (MUT2) : (C("ID1"), C("ID2"), (ORIGINAL)))
//! ```
//!
//! `A("ID")` stands for `typeof __fallow_m_a === "function" &&
//! __fallow_m_a("ID")`, and `C("ID")` for the same guard on `__fallow_m_c`.
//! A test can serialize a function with `toString` and run it in another
//! realm, such as a `node:vm` context or a browser page. The prelude
//! functions do not exist there. `typeof` of an undeclared name gives
//! `"undefined"` and does not throw, so the guard is false and the original
//! code runs.
//!
//! A mutated branch copies the raw original text of the site with one region
//! replaced. Only the original branch holds the instrumented inner sites, so
//! inner mutants live only inside the original branch of an outer mutant.
//! A conditional expression introduces no function boundary, so `this`,
//! `arguments`, `super`, `await` and `yield` keep their meaning.
//!
//! A statement site holds a range of statements. The emitter wraps it in an
//! `if` statement in a block:
//!
//! ```text
//! {if (A("ID1")) {MUT1} else if (A("ID2")) {MUT2}
//!   else {C("ID1"); C("ID2"); ORIGINAL}}
//! ```
//!
//! The statements move into a nested block. The collector makes statement
//! sites only where that keeps the scope of each declaration: a block or
//! function body that holds the whole range, or a `case` clause without a
//! lexical declaration.

use std::collections::BTreeSet;

use crate::reach::Probe;
use crate::{ACTIVE_FUNCTION, HIT_FUNCTION, SpliceMap, SpliceSegment, is_identifier_byte};

/// One mutant of a site, ready to emit.
pub struct EmitMutant {
    pub id: String,
    pub region: (u32, u32),
    pub replacement: String,
}

/// One site, ready to emit.
pub struct EmitSite {
    pub span: (u32, u32),
    /// True for a range of statements. See the module docs.
    pub statement: bool,
    pub mutants: Vec<EmitMutant>,
}

/// Text that the emitter inserts at an original offset.
pub struct Insertion {
    pub offset: u32,
    pub text: String,
}

struct Writer<'s> {
    source: &'s str,
    out: String,
    segments: Vec<SpliceSegment>,
}

impl Writer<'_> {
    fn copy(&mut self, from: u32, to: u32) {
        if to <= from {
            return;
        }
        let Some(text) = self.source.get(from as usize..to as usize) else {
            return;
        };
        let generated_start = self.out.len() as u32;
        let len = to - from;
        match self.segments.last_mut() {
            Some(last)
                if last.generated_start + last.len == generated_start
                    && last.original_start + last.len == from =>
            {
                last.len += len;
            }
            _ => self.segments.push(SpliceSegment {
                generated_start,
                original_start: from,
                len,
            }),
        }
        self.out.push_str(text);
    }

    fn push(&mut self, text: &str) {
        self.out.push_str(text);
    }

    /// Pushes a call of a prelude function that is false, and calls nothing,
    /// in a realm without the prelude. See the module docs.
    fn push_guarded(&mut self, function: &str, id: &str) {
        use std::fmt::Write as _;
        let _ = write!(
            self.out,
            "typeof {function} === \"function\" && {function}(\"{id}\")"
        );
    }
}

struct Tree {
    children: Vec<Vec<usize>>,
    roots: Vec<usize>,
}

/// Builds the containment tree. `sites` is ordered by start, then by end
/// descending, and site spans nest or are disjoint.
fn build_tree(sites: &[EmitSite]) -> Tree {
    let mut children = vec![Vec::new(); sites.len()];
    let mut roots = Vec::new();
    let mut stack: Vec<usize> = Vec::new();
    for (index, site) in sites.iter().enumerate() {
        while let Some(&top) = stack.last() {
            let parent = sites[top].span;
            if parent.0 <= site.span.0 && site.span.1 <= parent.1 {
                break;
            }
            stack.pop();
        }
        match stack.last() {
            Some(&parent) => children[parent].push(index),
            None => roots.push(index),
        }
        stack.push(index);
    }
    Tree { children, roots }
}

struct Emitter<'s, 't> {
    writer: Writer<'s>,
    sites: &'t [EmitSite],
    tree: Tree,
    statement_starts: &'t BTreeSet<u32>,
    /// The top-level insertions, sorted by offset, and the index of the next
    /// one to write.
    top_level: &'t [Insertion],
    next_top_level: usize,
    /// The entry probes, sorted by offset. See `copy_original`.
    probes: &'t [Probe],
    /// True for each probe that the output holds.
    placed: Vec<bool>,
    /// The branch of each placed probe: the site whose original branch holds
    /// it, or `None` outside each site.
    placed_in: Vec<Option<usize>>,
    /// The sites whose original branch the emitter writes now, innermost
    /// last.
    branches: Vec<usize>,
}

impl Emitter<'_, '_> {
    /// Copies `from..to` of the original text with each top-level insertion
    /// at an offset in `from..=to`. Only the gaps between root sites call it,
    /// so an insertion never lands in a branch of a site.
    fn copy_top_level(&mut self, from: u32, to: u32) {
        let mut cursor = from;
        while let Some(insertion) = self.top_level.get(self.next_top_level) {
            if insertion.offset > to {
                break;
            }
            let offset = insertion.offset.max(cursor);
            self.copy_original(cursor, offset);
            self.writer.push(&insertion.text);
            cursor = offset;
            self.next_top_level += 1;
        }
        self.copy_original(cursor, to);
    }

    /// Copies `from..to` of the original text on the path that runs with no
    /// active mutant, with each entry probe at an offset in `from..=to`.
    /// A mutated branch copies its text with no probe.
    ///
    /// A probe goes into the first copy that reaches its offset, so a probe
    /// at the start of a site goes before the site. The `)` that ends a comma
    /// expression goes only into a copy of the same branch as its opening
    /// part, so a probe pair around a site expression stays outside the
    /// site, and a pair inside a branch stays inside it.
    fn copy_original(&mut self, from: u32, to: u32) {
        let branch = self.branches.last().copied();
        let mut cursor = from;
        let first = self.probes.partition_point(|probe| probe.offset < from);
        for index in first..self.probes.len() {
            let probe = &self.probes[index];
            if probe.offset > to {
                break;
            }
            if self.placed[index] {
                continue;
            }
            if let Some(opener) = probe.opener
                && (!self.placed[opener] || self.placed_in[opener] != branch)
            {
                continue;
            }
            self.writer.copy(cursor, probe.offset);
            self.writer.push(&probe.text);
            cursor = probe.offset;
            self.placed[index] = true;
            self.placed_in[index] = branch;
        }
        self.writer.copy(cursor, to);
    }

    fn range(&mut self, from: u32, to: u32, nodes: &[usize], parent_start: Option<u32>) {
        let top = parent_start.is_none();
        let mut cursor = from;
        for &node in nodes {
            let span = self.sites[node].span;
            if top {
                self.copy_top_level(cursor, span.0);
            } else {
                self.copy_original(cursor, span.0);
            }
            self.site(node, parent_start);
            cursor = span.1;
        }
        if top {
            self.copy_top_level(cursor, to);
        } else {
            self.copy_original(cursor, to);
        }
    }

    fn site(&mut self, node: usize, parent_start: Option<u32>) {
        let sites = self.sites;
        let site = &sites[node];
        if site.statement {
            self.statement_site(node);
            return;
        }
        let (start, end) = site.span;
        // A statement that starts with `(` can join the line before it. The
        // comma keeps the grouping of the rest of the statement, as in
        // `guard_statement_start`.
        if self.statement_starts.contains(&start) && parent_start != Some(start) {
            // `do++i` has no space after the keyword; `dovoid` would be a name.
            let joins = self
                .writer
                .out
                .bytes()
                .last()
                .is_some_and(is_identifier_byte);
            self.writer
                .push(if joins { " void 0, " } else { "void 0, " });
        }
        self.writer.push("(");
        for mutant in &site.mutants {
            self.writer.push_guarded(ACTIVE_FUNCTION, &mutant.id);
            self.writer.push(" ? (");
            self.writer.copy(start, mutant.region.0);
            self.writer.push(&mutant.replacement);
            self.writer.copy(mutant.region.1, end);
            self.writer.push(") : ");
        }
        self.writer.push("(");
        for mutant in &site.mutants {
            self.writer.push_guarded(HIT_FUNCTION, &mutant.id);
            self.writer.push(", ");
        }
        self.writer.push("(");
        if start == end {
            // An empty site is the missing test of `for (;;)`, which is true.
            self.writer.push("true");
        }
        let children = std::mem::take(&mut self.tree.children[node]);
        self.branches.push(node);
        self.range(start, end, &children, Some(start));
        self.branches.pop();
        self.writer.push(")))");
    }
}

impl Emitter<'_, '_> {
    fn statement_site(&mut self, node: usize) {
        let sites = self.sites;
        let site = &sites[node];
        let (start, end) = site.span;
        self.writer.push("{");
        for mutant in &site.mutants {
            self.writer.push("if (");
            self.writer.push_guarded(ACTIVE_FUNCTION, &mutant.id);
            self.writer.push(") {");
            self.writer.copy(start, mutant.region.0);
            self.writer.push(&mutant.replacement);
            self.writer.copy(mutant.region.1, end);
            self.writer.push("} else ");
        }
        self.writer.push("{");
        for mutant in &site.mutants {
            self.writer.push_guarded(HIT_FUNCTION, &mutant.id);
            self.writer.push("; ");
        }
        let children = std::mem::take(&mut self.tree.children[node]);
        self.branches.push(node);
        self.range(start, end, &children, Some(start));
        self.branches.pop();
        // A statement range ends at a statement end or before the `}` of its
        // block, so it never ends inside a line comment, and the wrapper adds
        // no line.
        self.writer.push("}}");
    }
}

/// The parts of the instrumented text.
pub struct EmitInput<'t> {
    pub sites: &'t [EmitSite],
    pub statement_starts: &'t BTreeSet<u32>,
    /// Insertions before the first site, in order.
    pub insertions: &'t [Insertion],
    /// Insertions at offsets outside each site, or at a boundary of a root
    /// site, sorted by offset.
    pub top_level: &'t [Insertion],
    /// Entry probes, sorted by offset.
    pub probes: &'t [Probe],
}

/// Emits the instrumented text and its splice map. The flag is false when a
/// probe found no place.
pub fn emit(source: &str, input: &EmitInput<'_>) -> (String, SpliceMap, bool) {
    let EmitInput {
        sites,
        statement_starts,
        insertions,
        top_level,
        probes,
    } = *input;
    let tree = build_tree(sites);
    let mut emitter = Emitter {
        writer: Writer {
            source,
            out: String::with_capacity(source.len() * 2),
            segments: Vec::new(),
        },
        sites,
        tree,
        statement_starts,
        top_level,
        next_top_level: 0,
        probes,
        placed: vec![false; probes.len()],
        placed_in: vec![None; probes.len()],
        branches: Vec::new(),
    };
    let mut cursor = 0;
    for insertion in insertions {
        emitter.writer.copy(cursor, insertion.offset);
        emitter.writer.push(&insertion.text);
        cursor = insertion.offset;
    }
    let roots = std::mem::take(&mut emitter.tree.roots);
    emitter.range(cursor, source.len() as u32, &roots, None);
    let placed = emitter.placed.iter().all(|&placed| placed);
    let Writer { out, segments, .. } = emitter.writer;
    (out, SpliceMap { segments }, placed)
}