Skip to main content

fallow_mutation/
reach.rs

1//! Entry probes and the outline of a source file.
2//!
3//! A dry run that selects test files by reach records which functions each
4//! test file enters. The instrumented text then calls the prelude function
5//! [`PROBE_FUNCTION`] at the start of the module and at the start of the body
6//! of each outer function, with a probe id. The runtime records a probe id
7//! like a mutant hit.
8//!
9//! An outer function is a function that no other function contains: a
10//! declaration, an expression, an arrow, a method, a getter, a setter or a
11//! constructor. The body of a function is its block, or the expression of an
12//! arrow. A function inside a body runs only after its outer function
13//! entered, so the probe of the outer function covers it.
14//!
15//! The [`Outline`] of a text gives a hash of each outer function body and a
16//! hash of the skeleton: the text with each outer function body replaced by
17//! a marker. The skeleton holds the imports, the top-level statements, the
18//! class field initializers, the static blocks, the decorators, and the name
19//! and parameters of each function. Parameters are not in the body, because
20//! code can read `fn.length` of a function that never runs. When the
21//! skeleton and each body that a test file entered are equal to a recorded
22//! outline, the test file runs the same code as in the recorded run, until it
23//! enters a body that changed.
24
25use oxc_ast::ast::{ArrowFunctionBody, ArrowFunctionExpression, Function, FunctionBody, Program};
26use oxc_ast_visit::{Visit, walk};
27use oxc_span::GetSpan;
28use oxc_syntax::scope::ScopeFlags;
29use xxhash_rust::xxh3::xxh3_64;
30
31pub use crate::outline::{Outline, OutlineBody};
32
33/// The prelude function that records the entry of a function body or a
34/// module.
35///
36/// The instrumented output calls `__fallow_m_r(id)` with a probe id: `r`,
37/// the [`probe_key`] of the path, a dot, and the ordinal of the outer
38/// function in source order, or `m` for the module. Mutant ids are hex
39/// digits, so a probe id never equals one.
40pub const PROBE_FUNCTION: &str = "__fallow_m_r";
41
42/// The prelude part of the entry probes. It follows the other prelude
43/// functions, and the module probe follows it.
44pub const PROBE_PRELUDE: &str =
45    " function __fallow_m_r(id) { const m = globalThis.__fallowMutation; if (m) m.c(id); }";
46
47/// The probe key of a root-relative path: 16 lowercase hex digits.
48pub fn probe_key(path: &str) -> String {
49    format!("{:016x}", xxh3_64(path.as_bytes()))
50}
51
52/// The probe id of the module of `key`.
53pub fn module_probe(key: &str) -> String {
54    format!("r{key}.m")
55}
56
57/// The probe id of the outer function `ordinal` of `key`.
58pub fn function_probe(key: &str, ordinal: usize) -> String {
59    format!("r{key}.{ordinal}")
60}
61
62/// Where the probe of a body goes.
63#[derive(Debug, Clone, Copy)]
64enum ProbeSite {
65    /// A statement at `offset`, after the directive prologue of the block.
66    /// `after_directive` asks for a `;` first, as a directive can end with
67    /// no semicolon.
68    Statement { offset: u32, after_directive: bool },
69    /// A comma expression around the expression of an arrow.
70    Expression,
71}
72
73#[derive(Debug, Clone, Copy)]
74pub struct Body {
75    /// The start of the function node: its parameters and its name start
76    /// here or later.
77    pub start: u32,
78    /// The span of the body.
79    pub span: (u32, u32),
80    site: ProbeSite,
81}
82
83#[derive(Default)]
84struct Collector {
85    bodies: Vec<Body>,
86    depth: u32,
87}
88
89impl Collector {
90    fn block(&mut self, start: u32, body: &FunctionBody<'_>) {
91        let site = match body.directives.last() {
92            Some(directive) => ProbeSite::Statement {
93                offset: directive.span.end,
94                after_directive: true,
95            },
96            None => ProbeSite::Statement {
97                offset: body.span.start + 1,
98                after_directive: false,
99            },
100        };
101        self.bodies.push(Body {
102            start,
103            span: (body.span.start, body.span.end),
104            site,
105        });
106    }
107}
108
109impl<'a> Visit<'a> for Collector {
110    fn visit_function(&mut self, it: &Function<'a>, flags: ScopeFlags) {
111        if self.depth == 0
112            && let Some(body) = &it.body
113        {
114            self.block(it.span.start, body);
115        }
116        self.depth += 1;
117        walk::walk_function(self, it, flags);
118        self.depth -= 1;
119    }
120
121    fn visit_arrow_function_expression(&mut self, it: &ArrowFunctionExpression<'a>) {
122        if self.depth == 0 {
123            match &it.body {
124                ArrowFunctionBody::FunctionBody(body) => self.block(it.span.start, body),
125                expression => {
126                    let span = expression.span();
127                    self.bodies.push(Body {
128                        start: it.span.start,
129                        span: (span.start, span.end),
130                        site: ProbeSite::Expression,
131                    });
132                }
133            }
134        }
135        self.depth += 1;
136        walk::walk_arrow_function_expression(self, it);
137        self.depth -= 1;
138    }
139}
140
141pub fn collect(program: &Program<'_>) -> Vec<Body> {
142    let mut collector = Collector::default();
143    collector.visit_program(program);
144    let mut bodies = collector.bodies;
145    bodies.sort_by_key(|body| body.span.0);
146    bodies
147}
148
149/// The outline of the parsed `program` of `source`.
150pub fn outline_of(program: &Program<'_>, source: &str) -> Outline {
151    crate::outline::outline(program, source, &collect(program))
152}
153
154/// One probe text for the emitter.
155#[derive(Debug, Clone, PartialEq, Eq)]
156pub struct Probe {
157    pub offset: u32,
158    pub text: String,
159    /// For the `)` that ends a comma expression: the index of the probe
160    /// that opens it. The emitter writes both in the same branch.
161    pub opener: Option<usize>,
162}
163
164fn guarded_call(id: &str) -> String {
165    format!("typeof {PROBE_FUNCTION} === \"function\" && {PROBE_FUNCTION}(\"{id}\")")
166}
167
168/// The probes of the outer function bodies of `program`, sorted by offset,
169/// and the outline.
170pub fn probes(program: &Program<'_>, source: &str, key: &str) -> (Vec<Probe>, Outline) {
171    let bodies = collect(program);
172    let mut probes = Vec::with_capacity(bodies.len() + 1);
173    for (ordinal, body) in bodies.iter().enumerate() {
174        let call = guarded_call(&function_probe(key, ordinal));
175        match body.site {
176            ProbeSite::Statement {
177                offset,
178                after_directive,
179            } => probes.push(Probe {
180                offset,
181                text: if after_directive {
182                    format!(";{call};")
183                } else {
184                    format!("{call};")
185                },
186                opener: None,
187            }),
188            ProbeSite::Expression => {
189                let opener = probes.len();
190                probes.push(Probe {
191                    offset: body.span.0,
192                    text: format!("({call}, "),
193                    opener: None,
194                });
195                probes.push(Probe {
196                    offset: body.span.1,
197                    text: ")".to_owned(),
198                    opener: Some(opener),
199                });
200            }
201        }
202    }
203    // Outer bodies never nest, so a stable sort by offset keeps the `)` of
204    // one arrow before the start of a body at the same offset.
205    let order: Vec<usize> = {
206        let mut order: Vec<usize> = (0..probes.len()).collect();
207        order.sort_by_key(|&index| (probes[index].offset, probes[index].opener.is_none()));
208        order
209    };
210    let mut position = vec![0; probes.len()];
211    for (new, &old) in order.iter().enumerate() {
212        position[old] = new;
213    }
214    let sorted = order
215        .iter()
216        .map(|&old| {
217            let probe = &probes[old];
218            Probe {
219                offset: probe.offset,
220                text: probe.text.clone(),
221                opener: probe.opener.map(|opener| position[opener]),
222            }
223        })
224        .collect();
225    (sorted, crate::outline::outline(program, source, &bodies))
226}
227
228/// The module probe statement, which follows the prelude.
229pub fn module_statement(key: &str) -> String {
230    format!(" {PROBE_FUNCTION}(\"{}\");", module_probe(key))
231}