use oxc_ast::ast::{ArrowFunctionBody, ArrowFunctionExpression, Function, FunctionBody, Program};
use oxc_ast_visit::{Visit, walk};
use oxc_span::GetSpan;
use oxc_syntax::scope::ScopeFlags;
use xxhash_rust::xxh3::xxh3_64;
pub use crate::outline::{Outline, OutlineBody};
pub const PROBE_FUNCTION: &str = "__fallow_m_r";
pub const PROBE_PRELUDE: &str =
" function __fallow_m_r(id) { const m = globalThis.__fallowMutation; if (m) m.c(id); }";
pub fn probe_key(path: &str) -> String {
format!("{:016x}", xxh3_64(path.as_bytes()))
}
pub fn module_probe(key: &str) -> String {
format!("r{key}.m")
}
pub fn function_probe(key: &str, ordinal: usize) -> String {
format!("r{key}.{ordinal}")
}
#[derive(Debug, Clone, Copy)]
enum ProbeSite {
Statement { offset: u32, after_directive: bool },
Expression,
}
#[derive(Debug, Clone, Copy)]
pub struct Body {
pub start: u32,
pub span: (u32, u32),
site: ProbeSite,
}
#[derive(Default)]
struct Collector {
bodies: Vec<Body>,
depth: u32,
}
impl Collector {
fn block(&mut self, start: u32, body: &FunctionBody<'_>) {
let site = match body.directives.last() {
Some(directive) => ProbeSite::Statement {
offset: directive.span.end,
after_directive: true,
},
None => ProbeSite::Statement {
offset: body.span.start + 1,
after_directive: false,
},
};
self.bodies.push(Body {
start,
span: (body.span.start, body.span.end),
site,
});
}
}
impl<'a> Visit<'a> for Collector {
fn visit_function(&mut self, it: &Function<'a>, flags: ScopeFlags) {
if self.depth == 0
&& let Some(body) = &it.body
{
self.block(it.span.start, body);
}
self.depth += 1;
walk::walk_function(self, it, flags);
self.depth -= 1;
}
fn visit_arrow_function_expression(&mut self, it: &ArrowFunctionExpression<'a>) {
if self.depth == 0 {
match &it.body {
ArrowFunctionBody::FunctionBody(body) => self.block(it.span.start, body),
expression => {
let span = expression.span();
self.bodies.push(Body {
start: it.span.start,
span: (span.start, span.end),
site: ProbeSite::Expression,
});
}
}
}
self.depth += 1;
walk::walk_arrow_function_expression(self, it);
self.depth -= 1;
}
}
pub fn collect(program: &Program<'_>) -> Vec<Body> {
let mut collector = Collector::default();
collector.visit_program(program);
let mut bodies = collector.bodies;
bodies.sort_by_key(|body| body.span.0);
bodies
}
pub fn outline_of(program: &Program<'_>, source: &str) -> Outline {
crate::outline::outline(program, source, &collect(program))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Probe {
pub offset: u32,
pub text: String,
pub opener: Option<usize>,
}
fn guarded_call(id: &str) -> String {
format!("typeof {PROBE_FUNCTION} === \"function\" && {PROBE_FUNCTION}(\"{id}\")")
}
pub fn probes(program: &Program<'_>, source: &str, key: &str) -> (Vec<Probe>, Outline) {
let bodies = collect(program);
let mut probes = Vec::with_capacity(bodies.len() + 1);
for (ordinal, body) in bodies.iter().enumerate() {
let call = guarded_call(&function_probe(key, ordinal));
match body.site {
ProbeSite::Statement {
offset,
after_directive,
} => probes.push(Probe {
offset,
text: if after_directive {
format!(";{call};")
} else {
format!("{call};")
},
opener: None,
}),
ProbeSite::Expression => {
let opener = probes.len();
probes.push(Probe {
offset: body.span.0,
text: format!("({call}, "),
opener: None,
});
probes.push(Probe {
offset: body.span.1,
text: ")".to_owned(),
opener: Some(opener),
});
}
}
}
let order: Vec<usize> = {
let mut order: Vec<usize> = (0..probes.len()).collect();
order.sort_by_key(|&index| (probes[index].offset, probes[index].opener.is_none()));
order
};
let mut position = vec![0; probes.len()];
for (new, &old) in order.iter().enumerate() {
position[old] = new;
}
let sorted = order
.iter()
.map(|&old| {
let probe = &probes[old];
Probe {
offset: probe.offset,
text: probe.text.clone(),
opener: probe.opener.map(|opener| position[opener]),
}
})
.collect();
(sorted, crate::outline::outline(program, source, &bodies))
}
pub fn module_statement(key: &str) -> String {
format!(" {PROBE_FUNCTION}(\"{}\");", module_probe(key))
}