1use 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
33pub const PROBE_FUNCTION: &str = "__fallow_m_r";
41
42pub const PROBE_PRELUDE: &str =
45 " function __fallow_m_r(id) { const m = globalThis.__fallowMutation; if (m) m.c(id); }";
46
47pub fn probe_key(path: &str) -> String {
49 format!("{:016x}", xxh3_64(path.as_bytes()))
50}
51
52pub fn module_probe(key: &str) -> String {
54 format!("r{key}.m")
55}
56
57pub fn function_probe(key: &str, ordinal: usize) -> String {
59 format!("r{key}.{ordinal}")
60}
61
62#[derive(Debug, Clone, Copy)]
64enum ProbeSite {
65 Statement { offset: u32, after_directive: bool },
69 Expression,
71}
72
73#[derive(Debug, Clone, Copy)]
74pub struct Body {
75 pub start: u32,
78 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
149pub fn outline_of(program: &Program<'_>, source: &str) -> Outline {
151 crate::outline::outline(program, source, &collect(program))
152}
153
154#[derive(Debug, Clone, PartialEq, Eq)]
156pub struct Probe {
157 pub offset: u32,
158 pub text: String,
159 pub opener: Option<usize>,
162}
163
164fn guarded_call(id: &str) -> String {
165 format!("typeof {PROBE_FUNCTION} === \"function\" && {PROBE_FUNCTION}(\"{id}\")")
166}
167
168pub 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 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
228pub fn module_statement(key: &str) -> String {
230 format!(" {PROBE_FUNCTION}(\"{}\");", module_probe(key))
231}