Skip to main content

fallow_mutation/
exports.rs

1//! The export that a replay calls for one function of a module.
2
3use oxc_ast::ast::{
4    BindingPattern, Declaration, ExportDefaultDeclarationKind, Expression, ModuleExportName,
5    Program, Statement, VariableDeclaration,
6};
7use oxc_span::{GetSpan, Span};
8
9use crate::SourceKind;
10
11/// The name of the export whose declaration holds `span`, for example the
12/// function of a mutant. A mutant in a nested function gives the export of
13/// the outer function. `default` names a default export. A class or an
14/// object literal that holds the function is not a function to call, so it
15/// gives `None`.
16///
17/// The lookup reads the top-level statements only: an export declaration
18/// (`export function f`, `export const f = () => {}`, `export default`), and
19/// a local function or variable that an `export { f as g }` list without a
20/// source exports. `None` when the source does not parse or no export holds
21/// the span.
22pub fn export_containing(source: &str, kind: SourceKind, span: (u32, u32)) -> Option<String> {
23    let allocator = oxc_allocator::Allocator::default();
24    let parsed = oxc_parser::Parser::new(&allocator, source, kind.source_type()).parse();
25    if parsed.fatal_error || parsed.diagnostics.has_errors() {
26        return None;
27    }
28    let target = Span::new(span.0, span.1);
29    declared_export(&parsed.program, target).or_else(|| listed_export(&parsed.program, target))
30}
31
32const fn holds(outer: Span, inner: Span) -> bool {
33    outer.start <= inner.start && inner.end <= outer.end
34}
35
36/// True for an object literal or a class expression, also inside
37/// parentheses or a TypeScript `as`, `satisfies` or `!` wrapper.
38fn is_not_callable(expression: &Expression<'_>) -> bool {
39    matches!(
40        expression.get_inner_expression(),
41        Expression::ObjectExpression(_) | Expression::ClassExpression(_)
42    )
43}
44
45/// The single binding name of a declarator, or `None` for a pattern.
46fn binding_name<'a>(pattern: &'a BindingPattern<'_>) -> Option<&'a str> {
47    pattern.get_binding_identifier().map(|id| id.name.as_str())
48}
49
50/// The name of the declarator of `declaration` whose initializer holds
51/// `target`.
52fn declarator_holding<'a>(
53    declaration: &'a VariableDeclaration<'_>,
54    target: Span,
55) -> Option<&'a str> {
56    declaration.declarations.iter().find_map(|declarator| {
57        let init = declarator.init.as_ref()?;
58        if is_not_callable(init) {
59            return None;
60        }
61        holds(init.span(), target)
62            .then(|| binding_name(&declarator.id))
63            .flatten()
64    })
65}
66
67/// The local name of a top-level declaration that holds `target`.
68fn local_holding<'a>(declaration: &'a Declaration<'_>, target: Span) -> Option<&'a str> {
69    match declaration {
70        Declaration::FunctionDeclaration(function) if holds(function.span, target) => {
71            function.id.as_ref().map(|id| id.name.as_str())
72        }
73        Declaration::VariableDeclaration(variables) => declarator_holding(variables, target),
74        _ => None,
75    }
76}
77
78fn declared_export(program: &Program<'_>, target: Span) -> Option<String> {
79    program.body.iter().find_map(|statement| match statement {
80        Statement::ExportDeclaration(export) => {
81            local_holding(&export.declaration, target).map(str::to_owned)
82        }
83        Statement::ExportDefaultDeclaration(export) => {
84            let span = match &export.declaration {
85                ExportDefaultDeclarationKind::FunctionDeclaration(function) => function.span,
86                ExportDefaultDeclarationKind::ClassDeclaration(_)
87                | ExportDefaultDeclarationKind::TSInterfaceDeclaration(_)
88                | ExportDefaultDeclarationKind::ObjectExpression(_)
89                | ExportDefaultDeclarationKind::ClassExpression(_) => return None,
90                expression => {
91                    if expression.as_expression().is_some_and(is_not_callable) {
92                        return None;
93                    }
94                    expression.span()
95                }
96            };
97            holds(span, target).then(|| "default".to_owned())
98        }
99        _ => None,
100    })
101}
102
103fn export_name(name: &ModuleExportName<'_>) -> String {
104    name.name().to_string()
105}
106
107fn listed_export(program: &Program<'_>, target: Span) -> Option<String> {
108    let local = program.body.iter().find_map(|statement| match statement {
109        Statement::FunctionDeclaration(function) if holds(function.span, target) => {
110            function.id.as_ref().map(|id| id.name.as_str())
111        }
112        Statement::VariableDeclaration(variables) => declarator_holding(variables, target),
113        _ => None,
114    })?;
115    program.body.iter().find_map(|statement| {
116        let Statement::ExportNamedDeclaration(export) = statement else {
117            return None;
118        };
119        export
120            .specifiers
121            .iter()
122            .find(|specifier| export_name(&specifier.local) == local)
123            .map(|specifier| export_name(&specifier.exported))
124    })
125}
126
127#[cfg(test)]
128#[expect(clippy::expect_used, reason = "tests expect to keep the setup short")]
129mod tests {
130    use super::*;
131
132    /// The span of the first occurrence of `needle` in `source`.
133    fn span_of(source: &str, needle: &str) -> (u32, u32) {
134        let start = source.find(needle).expect("needle in source");
135        let start = u32::try_from(start).expect("small source");
136        let end = start + u32::try_from(needle.len()).expect("small needle");
137        (start, end)
138    }
139
140    fn lookup(source: &str, needle: &str) -> Option<String> {
141        export_containing(source, SourceKind::Ts, span_of(source, needle))
142    }
143
144    #[test]
145    fn an_exported_function_declaration_names_itself() {
146        let source = "export function add(a: number, b: number) { return a + b; }";
147        assert_eq!(lookup(source, "a + b").as_deref(), Some("add"));
148    }
149
150    #[test]
151    fn an_exported_arrow_function_names_its_binding() {
152        let source = "export const sum = (a, b) => a + b, other = 1;";
153        assert_eq!(lookup(source, "a + b").as_deref(), Some("sum"));
154    }
155
156    #[test]
157    fn a_nested_function_gives_the_outer_export() {
158        let source = "export function outer(n) { const inner = () => n + 1; return inner(); }";
159        assert_eq!(lookup(source, "n + 1").as_deref(), Some("outer"));
160    }
161
162    #[test]
163    fn a_default_export_is_named_default() {
164        let source = "export default function (n) { return n > 0; }";
165        assert_eq!(lookup(source, "n > 0").as_deref(), Some("default"));
166        let arrow = "export default (n) => n > 0;";
167        assert_eq!(lookup(arrow, "n > 0").as_deref(), Some("default"));
168    }
169
170    #[test]
171    fn an_export_list_gives_the_exported_name_of_the_local() {
172        let source =
173            "function add(a, b) { return a + b; }\nconst x = 1;\nexport { add as plus, x };";
174        assert_eq!(lookup(source, "a + b").as_deref(), Some("plus"));
175    }
176
177    #[test]
178    fn a_function_that_no_export_holds_gives_none() {
179        let source = "function hidden(n) { return n + 1; }\nexport const y = 2;";
180        assert_eq!(lookup(source, "n + 1"), None);
181        let reexport = "function add(a, b) { return a + b; }\nexport { add } from './other';";
182        assert_eq!(lookup(reexport, "a + b"), None);
183    }
184
185    #[test]
186    fn a_class_or_an_object_that_holds_the_function_is_not_callable() {
187        let class = "export class Box { get(n) { return n + 1; } }";
188        assert_eq!(lookup(class, "n + 1"), None);
189        let object = "export const config = { run(n) { return n + 1; } };";
190        assert_eq!(lookup(object, "n + 1"), None);
191        let default_object = "export default { run(n) { return n + 1; } };";
192        assert_eq!(lookup(default_object, "n + 1"), None);
193        let listed = "class Box { get(n) { return n + 1; } }\nexport { Box };";
194        assert_eq!(lookup(listed, "n + 1"), None);
195        let satisfies = "export const config = { run(n) { return n + 1; } } satisfies object;";
196        assert_eq!(lookup(satisfies, "n + 1"), None);
197        let constant = "export const config = ({ run(n) { return n + 1; } }) as const;";
198        assert_eq!(lookup(constant, "n + 1"), None);
199        let wrapped = "export default ({ run(n) { return n + 1; } }) satisfies object;";
200        assert_eq!(lookup(wrapped, "n + 1"), None);
201        let arrow = "export const run = ((n: number) => n + 1) satisfies object;";
202        assert_eq!(lookup(arrow, "n + 1").as_deref(), Some("run"));
203    }
204
205    #[test]
206    fn a_source_that_does_not_parse_gives_none() {
207        assert_eq!(lookup("export function (", "("), None);
208    }
209}