Skip to main content

fallow_mutation/
outline.rs

1//! The outline of a source text: the parts that the reach record compares
2//! between two versions of a file.
3//!
4//! The top-level statements fall into four groups:
5//!
6//! - Type-only statements (interfaces, type aliases, `import type`,
7//!   `export type`, `declare` statements). The runtime never sees them, so
8//!   the outline leaves them out.
9//! - Imports. The skeleton holds the source of each import in order, because
10//!   the order of the sources is the order in which the modules load. Each
11//!   imported binding is a binding of the outline.
12//! - Pure declarations: a function declaration with no `export`, and a
13//!   `const`, `let` or `var` with no `export` whose initializers run no code
14//!   (literals, arrays and objects of them, function expressions and arrows).
15//!   Each declared name is a binding: a function declaration gives the hash
16//!   of its name and parameters, a variable the hash of its declarator with
17//!   each function body left out.
18//! - Each other statement is module code: the skeleton holds its text with
19//!   each outer function body replaced by a marker.
20//!
21//! Comments do not count. An outer function gets a key that stays the same
22//! when other code moves: the name of its declaration, or the hash of the
23//! statement that holds it and its index there. Each outer function also
24//! lists the names that its text references, so a change of a binding keeps
25//! only the test files that entered a function that names it.
26
27use std::collections::{BTreeMap, BTreeSet};
28
29use oxc_ast::ast::{
30    ArrayExpressionElement, Declaration, Expression, ImportDeclarationSpecifier,
31    ObjectPropertyKind, Program, Statement, UnaryOperator,
32};
33use oxc_ast_visit::Visit;
34use oxc_span::GetSpan;
35use serde::{Deserialize, Serialize};
36use xxhash_rust::xxh3::Xxh3;
37
38use crate::reach::Body;
39
40/// One outer function.
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42pub struct OutlineBody {
43    /// The byte span of the body: the block with its braces, or the
44    /// expression of an arrow.
45    pub span: (u32, u32),
46    /// The hash of the function text: its name, parameters and body.
47    pub hash: u64,
48    /// The key of the function. Another version of the file gives the same
49    /// function the same key.
50    pub key: String,
51    /// The names that the function text references, sorted.
52    pub refs: Vec<String>,
53}
54
55/// The outline of a source text. See the module docs.
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57pub struct Outline {
58    /// The hash of the module code and of the import sources.
59    pub skeleton: u64,
60    /// The outer functions, in source order. The index is the ordinal of the
61    /// probe id.
62    pub bodies: Vec<OutlineBody>,
63    /// The hash of each binding of an import or a pure declaration.
64    pub bindings: BTreeMap<String, u64>,
65    /// The names that the module code references outside each function
66    /// body, sorted.
67    pub skeleton_refs: Vec<String>,
68    /// Each name that the text references, sorted.
69    pub refs: Vec<String>,
70    /// The span of each declarator of a pure variable declaration, with its
71    /// name, in source order. A mutant in such a declarator runs when the
72    /// module loads, and only code that reads the name can observe it.
73    #[serde(default)]
74    pub declarators: Vec<(String, (u32, u32))>,
75}
76
77impl Outline {
78    /// The ordinal of the outer function body that holds `span`, or `None`
79    /// when the span is outside each function body.
80    pub fn body_of(&self, span: (u32, u32)) -> Option<usize> {
81        let index = self
82            .bodies
83            .partition_point(|body| body.span.0 <= span.0)
84            .checked_sub(1)?;
85        let body = self.bodies.get(index)?;
86        (span.1 <= body.span.1).then_some(index)
87    }
88
89    /// The name of the pure variable declarator that holds `span`.
90    pub fn declarator_of(&self, span: (u32, u32)) -> Option<&str> {
91        self.declarators
92            .iter()
93            .find(|(_, declarator)| declarator.0 <= span.0 && span.1 <= declarator.1)
94            .map(|(name, _)| name.as_str())
95    }
96
97    /// The ordinal of the function with `key`.
98    pub fn function(&self, key: &str) -> Option<usize> {
99        self.bodies.iter().position(|body| body.key == key)
100    }
101}
102
103/// The marker of a left-out function body. No source text has the byte.
104const BODY_MARKER: &[u8] = &[0xff];
105
106/// A part of the text that a hash leaves out: a comment (replaced by a
107/// space, or by a line break when it holds one, as the line break counts for
108/// automatic semicolon insertion) or a function body (replaced by
109/// [`BODY_MARKER`]).
110#[derive(Debug, Clone, Copy)]
111struct Mask {
112    span: (u32, u32),
113    with: &'static [u8],
114}
115
116struct Masker<'s> {
117    source: &'s str,
118    comments: Vec<Mask>,
119}
120
121impl Masker<'_> {
122    /// The hash of `range` with each comment and each of `bodies` left out.
123    fn hash(&self, range: (u32, u32), bodies: &[(u32, u32)], hasher: &mut Xxh3) {
124        let mut masks: Vec<Mask> = bodies
125            .iter()
126            .map(|&span| Mask {
127                span,
128                with: BODY_MARKER,
129            })
130            .collect();
131        masks.extend(self.comments.iter().copied().filter(|comment| {
132            !bodies
133                .iter()
134                .any(|body| body.0 <= comment.span.0 && comment.span.1 <= body.1)
135        }));
136        masks.retain(|mask| range.0 <= mask.span.0 && mask.span.1 <= range.1);
137        masks.sort_by_key(|mask| mask.span.0);
138        let mut cursor = range.0;
139        for mask in masks {
140            if mask.span.0 < cursor {
141                continue;
142            }
143            hasher.update(self.text(cursor, mask.span.0).as_bytes());
144            hasher.update(mask.with);
145            cursor = mask.span.1;
146        }
147        hasher.update(self.text(cursor, range.1).as_bytes());
148    }
149
150    fn digest(&self, range: (u32, u32), bodies: &[(u32, u32)]) -> u64 {
151        let mut hasher = Xxh3::new();
152        self.hash(range, bodies, &mut hasher);
153        hasher.digest()
154    }
155
156    fn text(&self, from: u32, to: u32) -> &str {
157        self.source
158            .get(from as usize..to as usize)
159            .unwrap_or_default()
160    }
161}
162
163/// The names that the text references. A name in a TypeScript type is not a
164/// value reference: the transform removes it, and an import whose names have
165/// only such references does not load its module.
166#[derive(Default)]
167struct References {
168    /// The offset, the name, and true for a value reference.
169    names: Vec<(u32, String, bool)>,
170    types: u32,
171}
172
173impl<'a> Visit<'a> for References {
174    fn visit_identifier_reference(&mut self, it: &oxc_ast::ast::IdentifierReference<'a>) {
175        self.names
176            .push((it.span.start, it.name.to_string(), self.types == 0));
177    }
178
179    fn visit_ts_type(&mut self, it: &oxc_ast::ast::TSType<'a>) {
180        self.types += 1;
181        oxc_ast_visit::walk::walk_ts_type(self, it);
182        self.types -= 1;
183    }
184}
185
186/// True when evaluating `expression` runs no code.
187fn is_pure(expression: &Expression<'_>) -> bool {
188    match expression {
189        Expression::StringLiteral(_)
190        | Expression::NumericLiteral(_)
191        | Expression::BooleanLiteral(_)
192        | Expression::NullLiteral(_)
193        | Expression::BigIntLiteral(_)
194        | Expression::RegExpLiteral(_)
195        | Expression::ArrowFunctionExpression(_)
196        | Expression::FunctionExpression(_) => true,
197        Expression::TemplateLiteral(template) => template.expressions.is_empty(),
198        Expression::ArrayExpression(array) => array.elements.iter().all(|element| match element {
199            ArrayExpressionElement::Elision(_) => true,
200            ArrayExpressionElement::SpreadElement(_) => false,
201            other => other.as_expression().is_some_and(is_pure),
202        }),
203        Expression::ObjectExpression(object) => {
204            object.properties.iter().all(|property| match property {
205                ObjectPropertyKind::ObjectProperty(property) => {
206                    !property.computed && is_pure(&property.value)
207                }
208                ObjectPropertyKind::SpreadProperty(_) => false,
209            })
210        }
211        Expression::UnaryExpression(unary) => {
212            matches!(
213                unary.operator,
214                UnaryOperator::UnaryNegation | UnaryOperator::UnaryPlus | UnaryOperator::LogicalNot
215            ) && is_pure(&unary.argument)
216        }
217        Expression::ParenthesizedExpression(inner) => is_pure(&inner.expression),
218        Expression::TSAsExpression(inner) => is_pure(&inner.expression),
219        Expression::TSSatisfiesExpression(inner) => is_pure(&inner.expression),
220        Expression::TSNonNullExpression(inner) => is_pure(&inner.expression),
221        Expression::TSTypeAssertion(inner) => is_pure(&inner.expression),
222        _ => false,
223    }
224}
225
226/// The group of one top-level statement. See the module docs.
227enum Group {
228    Type,
229    Import {
230        source: String,
231        bindings: Vec<(String, String)>,
232    },
233    Function {
234        name: String,
235    },
236    Variables {
237        /// `const`, `let` or `var`.
238        kind: &'static str,
239        /// The name and the declarator span of each declarator.
240        declarators: Vec<(String, (u32, u32))>,
241    },
242    /// Module code. The prefix of the key of its functions, when the
243    /// statement names them: a declaration name or `default`.
244    Code {
245        name: Option<String>,
246    },
247}
248
249fn group(statement: &Statement<'_>) -> Group {
250    match statement {
251        Statement::TSTypeAliasDeclaration(_)
252        | Statement::TSInterfaceDeclaration(_)
253        | Statement::TSGlobalDeclaration(_) => Group::Type,
254        Statement::TSExternalModuleDeclaration(module) if module.declare => Group::Type,
255        Statement::TSNamespaceDeclaration(module) if module.declare => Group::Type,
256        Statement::ImportDeclaration(import) => import_group(import),
257        Statement::FunctionDeclaration(function) => match (&function.id, &function.body) {
258            _ if function.declare => Group::Type,
259            (Some(id), Some(_)) => Group::Function {
260                name: id.name.to_string(),
261            },
262            _ => Group::Code { name: None },
263        },
264        Statement::VariableDeclaration(declaration) => variables_group(declaration),
265        Statement::ExportNamedDeclaration(export) if export.export_kind.is_type() => Group::Type,
266        Statement::ExportFromDeclaration(export) if export.export_kind.is_type() => Group::Type,
267        Statement::ExportDeclaration(export) => export_group(&export.declaration),
268        Statement::ExportDefaultDeclaration(_) => Group::Code {
269            name: Some("default".to_owned()),
270        },
271        Statement::ClassDeclaration(class) => Group::Code {
272            name: class.id.as_ref().map(|id| format!("class:{}", id.name)),
273        },
274        _ => Group::Code { name: None },
275    }
276}
277
278fn import_group(import: &oxc_ast::ast::ImportDeclaration<'_>) -> Group {
279    if import.import_kind.is_type() {
280        return Group::Type;
281    }
282    let Some(specifiers) = &import.specifiers else {
283        // A side-effect import runs the module.
284        return Group::Code { name: None };
285    };
286    let source = import.source.value.as_str().unwrap_or_default().to_owned();
287    let bindings = specifiers
288        .iter()
289        .filter_map(|specifier| match specifier {
290            ImportDeclarationSpecifier::ImportSpecifier(named) => (!named.import_kind.is_type())
291                .then(|| {
292                    (
293                        named.local.name.to_string(),
294                        named.imported.name().to_string(),
295                    )
296                }),
297            ImportDeclarationSpecifier::ImportDefaultSpecifier(default) => {
298                Some((default.local.name.to_string(), "default".to_owned()))
299            }
300            ImportDeclarationSpecifier::ImportNamespaceSpecifier(namespace) => {
301                Some((namespace.local.name.to_string(), "*".to_owned()))
302            }
303        })
304        .collect();
305    Group::Import { source, bindings }
306}
307
308fn variables_group(declaration: &oxc_ast::ast::VariableDeclaration<'_>) -> Group {
309    if declaration.declare {
310        return Group::Type;
311    }
312    let declarators: Option<Vec<(String, (u32, u32))>> = declaration
313        .declarations
314        .iter()
315        .map(|declarator| {
316            let id = declarator.id.get_binding_identifier()?;
317            let pure = declarator.init.as_ref().is_none_or(is_pure);
318            pure.then(|| {
319                (
320                    id.name.to_string(),
321                    (declarator.span.start, declarator.span.end),
322                )
323            })
324        })
325        .collect();
326    match declarators {
327        Some(declarators) => Group::Variables {
328            kind: declaration.kind.as_str(),
329            declarators,
330        },
331        None => Group::Code {
332            name: single_variable(declaration),
333        },
334    }
335}
336
337fn export_group(declaration: &Declaration<'_>) -> Group {
338    let name = match declaration {
339        Declaration::TSTypeAliasDeclaration(_) | Declaration::TSInterfaceDeclaration(_) => {
340            return Group::Type;
341        }
342        Declaration::FunctionDeclaration(function) if function.declare => return Group::Type,
343        Declaration::VariableDeclaration(declaration) if declaration.declare => {
344            return Group::Type;
345        }
346        Declaration::FunctionDeclaration(function) => {
347            function.id.as_ref().map(|id| format!("fn:{}", id.name))
348        }
349        Declaration::ClassDeclaration(class) => {
350            class.id.as_ref().map(|id| format!("class:{}", id.name))
351        }
352        Declaration::VariableDeclaration(declaration) => single_variable(declaration),
353        _ => None,
354    };
355    Group::Code { name }
356}
357
358fn single_variable(declaration: &oxc_ast::ast::VariableDeclaration<'_>) -> Option<String> {
359    match declaration.declarations.as_slice() {
360        [declarator] => declarator
361            .id
362            .get_binding_identifier()
363            .map(|id| format!("var:{}", id.name)),
364        _ => None,
365    }
366}
367
368/// True for a comment that a transform reads, such as `@jsx` or
369/// `@jsxImportSource`. Such a comment changes the code of the module.
370fn is_pragma(text: &str) -> bool {
371    text.contains("@jsx")
372}
373
374fn masker<'s>(program: &Program<'_>, source: &'s str) -> Masker<'s> {
375    Masker {
376        source,
377        comments: program
378            .comments
379            .iter()
380            .filter_map(|comment| {
381                let text = source
382                    .get(comment.span.start as usize..comment.span.end as usize)
383                    .unwrap_or_default();
384                (!is_pragma(text)).then_some(Mask {
385                    span: (comment.span.start, comment.span.end),
386                    with: if text.contains(['\n', '\r', '\u{2028}', '\u{2029}']) {
387                        b"\n"
388                    } else {
389                        b" "
390                    },
391                })
392            })
393            .collect(),
394    }
395}
396
397/// The state of [`outline`] while it walks the top-level statements.
398struct Builder<'s, 'b> {
399    masker: Masker<'s>,
400    bodies: &'b [Body],
401    body_spans: Vec<(u32, u32)>,
402    /// The references, sorted by offset.
403    refs: Vec<(u32, String, bool)>,
404    /// The imported names that the file reads as values. The binding
405    /// resolution of the semantic pass decides it, so a local of the same
406    /// name in an inner scope does not count.
407    value_imports: BTreeSet<String>,
408    keys: Vec<Option<String>>,
409    skeleton: Xxh3,
410    skeleton_refs: BTreeSet<String>,
411    bindings: BTreeMap<String, u64>,
412    declarators: Vec<(String, (u32, u32))>,
413}
414
415impl Builder<'_, '_> {
416    /// The names that `from..to` references, outside the `outside` spans.
417    fn refs_in(&self, from: u32, to: u32, outside: &[(u32, u32)]) -> BTreeSet<String> {
418        let start = self.refs.partition_point(|(offset, ..)| *offset < from);
419        self.refs[start..]
420            .iter()
421            .take_while(|(offset, ..)| *offset < to)
422            .filter(|(offset, ..)| {
423                !outside
424                    .iter()
425                    .any(|body| body.0 <= *offset && *offset < body.1)
426            })
427            .map(|(_, name, _)| name.clone())
428            .collect()
429    }
430
431    /// The range of the outer functions that start in `span`.
432    fn functions_in(&self, span: (u32, u32)) -> std::ops::Range<usize> {
433        let first = self.bodies.partition_point(|body| body.start < span.0);
434        let last = self.bodies.partition_point(|body| body.start < span.1);
435        first..last
436    }
437
438    fn name_functions(&mut self, range: std::ops::Range<usize>, key: impl Fn(usize) -> String) {
439        let first = range.start;
440        for index in range {
441            self.keys[index] = Some(key(index - first));
442        }
443    }
444
445    fn statement(&mut self, statement: &Statement<'_>) {
446        let span = statement.span();
447        let span = (span.start, span.end);
448        let functions = self.functions_in(span);
449        match group(statement) {
450            Group::Type => {}
451            Group::Import { source, bindings } => self.import(&source, bindings),
452            Group::Function { name } => {
453                self.name_functions(functions.clone(), |index| {
454                    if index == 0 {
455                        format!("fn:{name}")
456                    } else {
457                        format!("fn:{name}#{index}")
458                    }
459                });
460                // The binding is the name and the parameters. The body counts
461                // only for a test file that entered it.
462                let header = self
463                    .bodies
464                    .get(functions.start)
465                    .map_or(span, |body| (span.0, body.span.0));
466                let digest = self.masker.digest(header, &[]);
467                self.bindings.insert(name, digest);
468            }
469            Group::Variables { kind, declarators } => {
470                for (name, declarator) in declarators {
471                    let inner = self.functions_in(declarator);
472                    self.name_functions(inner.clone(), |index| format!("var:{name}#{index}"));
473                    let mut hasher = Xxh3::new();
474                    hasher.update(kind.as_bytes());
475                    hasher.update(b"\0");
476                    self.masker
477                        .hash(declarator, &self.body_spans[inner], &mut hasher);
478                    self.bindings.insert(name.clone(), hasher.digest());
479                    self.declarators.push((name, declarator));
480                }
481            }
482            Group::Code { name } => {
483                let inside = &self.body_spans[functions.clone()];
484                let digest = self.masker.digest(span, inside);
485                self.skeleton.update(b"code\0");
486                self.skeleton.update(&digest.to_le_bytes());
487                let refs = self.refs_in(span.0, span.1, inside);
488                self.skeleton_refs.extend(refs);
489                let prefix = name.unwrap_or_else(|| format!("s{digest:016x}"));
490                self.name_functions(functions, |index| format!("{prefix}#{index}"));
491            }
492        }
493    }
494
495    /// An import is module code by its source and by whether the file reads
496    /// one of its names as a value: a TypeScript transform removes an import
497    /// with no such read, and then the module does not load.
498    fn import(&mut self, source: &str, bindings: Vec<(String, String)>) {
499        self.skeleton.update(b"import\0");
500        self.skeleton.update(source.as_bytes());
501        let loads = bindings
502            .iter()
503            .any(|(local, _)| self.value_imports.contains(local));
504        self.skeleton
505            .update(if loads { b"\0load" } else { b"\0type" });
506        for (local, name) in bindings {
507            let mut hasher = Xxh3::new();
508            hasher.update(source.as_bytes());
509            hasher.update(b"\0");
510            hasher.update(name.as_bytes());
511            self.bindings.insert(local, hasher.digest());
512        }
513        self.skeleton.update(b"\0");
514    }
515
516    fn finish(self) -> Outline {
517        let mut seen: BTreeMap<String, usize> = BTreeMap::new();
518        let bodies = self
519            .bodies
520            .iter()
521            .zip(&self.keys)
522            .enumerate()
523            .map(|(index, (body, key))| {
524                let base = key.clone().unwrap_or_else(|| format!("at{index}"));
525                let count = seen.entry(base.clone()).or_default();
526                let key = if *count == 0 {
527                    base
528                } else {
529                    format!("{base}~{count}")
530                };
531                *count += 1;
532                OutlineBody {
533                    span: body.span,
534                    hash: self.masker.digest((body.start, body.span.1), &[]),
535                    key,
536                    refs: self
537                        .refs_in(body.start, body.span.1, &[])
538                        .into_iter()
539                        .collect(),
540                }
541            })
542            .collect();
543        let refs: BTreeSet<String> = self.refs.into_iter().map(|(_, name, _)| name).collect();
544        Outline {
545            skeleton: self.skeleton.digest(),
546            bodies,
547            bindings: self.bindings,
548            skeleton_refs: self.skeleton_refs.into_iter().collect(),
549            refs: refs.into_iter().collect(),
550            declarators: self.declarators,
551        }
552    }
553}
554
555/// The local names of the imports that the program reads as values. A
556/// TypeScript transform removes an import binding with no such read.
557fn value_imports(program: &Program<'_>) -> BTreeSet<String> {
558    let semantic = oxc_semantic::SemanticBuilder::new().build(program).semantic;
559    let scoping = semantic.scoping();
560    program
561        .body
562        .iter()
563        .filter_map(|statement| match statement {
564            Statement::ImportDeclaration(import) => import.specifiers.as_ref(),
565            _ => None,
566        })
567        .flatten()
568        .filter(|specifier| {
569            scoping
570                .get_resolved_references(specifier.symbol_id())
571                .any(|reference| reference.is_value() && !reference.flags().is_value_as_type())
572        })
573        .map(|specifier| specifier.local().name.to_string())
574        .collect()
575}
576
577/// Gives the outline of `program`, the parsed `source`, with its outer
578/// function `bodies` in source order.
579pub fn outline(program: &Program<'_>, source: &str, bodies: &[Body]) -> Outline {
580    let mut references = References::default();
581    references.visit_program(program);
582    let mut refs = references.names;
583    refs.sort_unstable();
584    let value_imports = value_imports(program);
585    let masker = masker(program, source);
586    let mut skeleton = Xxh3::new();
587    // A directive such as "use strict" changes how each function runs, and
588    // a pragma comment changes the code that the transform gives.
589    for directive in &program.directives {
590        skeleton.update(b"directive\0");
591        skeleton.update(
592            masker
593                .text(directive.span.start, directive.span.end)
594                .as_bytes(),
595        );
596    }
597    for comment in &program.comments {
598        let text = masker.text(comment.span.start, comment.span.end);
599        if is_pragma(text) {
600            skeleton.update(b"pragma\0");
601            skeleton.update(text.as_bytes());
602        }
603    }
604    let mut builder = Builder {
605        masker,
606        bodies,
607        body_spans: bodies.iter().map(|body| body.span).collect(),
608        refs,
609        value_imports,
610        keys: vec![None; bodies.len()],
611        skeleton,
612        skeleton_refs: BTreeSet::new(),
613        bindings: BTreeMap::new(),
614        declarators: Vec::new(),
615    };
616    for statement in &program.body {
617        builder.statement(statement);
618    }
619    builder.finish()
620}