use std::collections::BTreeMap;
use fusevm::{Chunk, ChunkBuilder, JitCompiler, Op};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Loop {
pub anchor: usize,
pub trace_eligible: bool,
pub traced: bool,
pub blacklisted: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChunkTiers {
pub name: String,
pub ops: usize,
pub block_eligible: bool,
pub block_compiled: bool,
pub largest_eligible_region: Option<(usize, usize)>,
pub loops: Vec<Loop>,
pub ineligible: BTreeMap<String, usize>,
}
impl ChunkTiers {
pub fn reaches_native(&self) -> bool {
self.block_compiled || self.loops.iter().any(|l| l.traced)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Report {
pub chunks: Vec<ChunkTiers>,
}
impl Report {
pub fn reaches_native(&self) -> bool {
self.chunks.iter().any(|c| c.reaches_native())
}
}
impl std::fmt::Display for ChunkTiers {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "ops {}", self.ops)?;
writeln!(f, "block-JIT eligible {}", self.block_eligible)?;
writeln!(f, "block-JIT compiled {}", self.block_compiled)?;
match self.largest_eligible_region {
Some((s, e)) => writeln!(f, "largest eligible region {s}..{e} ({} ops)", e - s)?,
None => writeln!(f, "largest eligible region none")?,
}
if self.loops.is_empty() {
writeln!(f, "loops none")?;
}
for l in &self.loops {
writeln!(
f,
"loop @{:<4} trace-eligible={} traced={} blacklisted={}",
l.anchor, l.trace_eligible, l.traced, l.blacklisted
)?;
}
if self.ineligible.is_empty() {
writeln!(f, "block-ineligible ops none")?;
} else {
writeln!(f, "block-ineligible ops")?;
for (name, count) in &self.ineligible {
writeln!(f, " {name:<22}{count}")?;
}
}
Ok(())
}
}
impl std::fmt::Display for Report {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let label = self.chunks.len() > 1;
for c in &self.chunks {
if label {
writeln!(f, "== {} ==", c.name)?;
}
write!(f, "{c}")?;
}
write!(f, "reaches native code {}", self.reaches_native())
}
}
const REPORT_X: f64 = 1.0;
const WARMUP: usize = 8;
pub fn report(expr_src: &str) -> Result<Report, String> {
let e = crate::expr::parse(expr_src)?;
let resolve = |_: &str| f64::NAN;
let chunk = crate::expr::chunk_of(&e, REPORT_X, &resolve);
for _ in 0..WARMUP {
crate::expr::eval_ctx(&e, REPORT_X, &resolve)?;
}
Ok(inspect_all(&[("expr".to_string(), chunk)]))
}
pub fn inspect(chunk: &Chunk) -> Report {
Report {
chunks: vec![inspect_chunk("main", chunk)],
}
}
pub fn inspect_all(named: &[(String, Chunk)]) -> Report {
Report {
chunks: named.iter().map(|(n, c)| inspect_chunk(n, c)).collect(),
}
}
pub fn inspect_chunk(name: &str, chunk: &Chunk) -> ChunkTiers {
let jit = JitCompiler::new();
let loops = loop_anchors(&chunk.ops)
.into_iter()
.map(|anchor| Loop {
anchor,
trace_eligible: body_of(&chunk.ops, anchor)
.is_some_and(|body| jit.is_trace_eligible(body, anchor)),
traced: jit.trace_is_compiled(chunk, anchor),
blacklisted: jit.trace_is_blacklisted(chunk, anchor),
})
.collect();
let mut ineligible: BTreeMap<String, usize> = BTreeMap::new();
for op in &chunk.ops {
if !op_is_eligible(&jit, op) {
*ineligible.entry(op_name(op)).or_default() += 1;
}
}
ChunkTiers {
name: name.to_string(),
ops: chunk.ops.len(),
block_eligible: jit.is_block_eligible(chunk),
block_compiled: jit.block_jit_is_compiled(chunk),
largest_eligible_region: jit.find_jit_region(chunk),
loops,
ineligible,
}
}
fn loop_anchors(ops: &[Op]) -> Vec<usize> {
let mut anchors: Vec<usize> = ops
.iter()
.enumerate()
.filter_map(|(ip, op)| match op {
Op::Jump(t)
| Op::JumpIfTrue(t)
| Op::JumpIfFalse(t)
| Op::JumpIfTrueKeep(t)
| Op::JumpIfFalseKeep(t)
if *t <= ip =>
{
Some(*t)
}
_ => None,
})
.collect();
anchors.sort_unstable();
anchors.dedup();
anchors
}
fn body_of(ops: &[Op], anchor: usize) -> Option<&[Op]> {
let close = ops.iter().enumerate().position(|(ip, op)| {
ip >= anchor
&& matches!(
op,
Op::Jump(t) | Op::JumpIfTrue(t) | Op::JumpIfFalse(t)
if *t == anchor
)
})?;
Some(&ops[anchor..=close])
}
fn op_is_eligible(jit: &JitCompiler, op: &Op) -> bool {
let mut b = ChunkBuilder::new();
b.emit(op.clone(), 1);
jit.is_block_eligible(&b.build())
}
fn op_name(op: &Op) -> String {
let text = format!("{op:?}");
match text.split_once('(') {
Some((name, _)) => name.to_string(),
None => text,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_arithmetic_expression_is_compiled_by_the_block_tier() {
let report = report("x * 2 + 3 * 4 - 1").expect("evaluates");
assert!(report.chunks[0].block_eligible, "{report}");
assert!(report.chunks[0].block_compiled, "{report}");
assert!(report.chunks[0].ineligible.is_empty(), "{report}");
assert!(report.reaches_native(), "{report}");
}
#[test]
fn a_guarded_ternary_is_still_block_eligible() {
let report = report("x != 0 ? 100 / x : 0").expect("evaluates");
assert!(report.chunks[0].block_eligible, "{report}");
assert!(report.chunks[0].loops.is_empty(), "{report}");
assert!(report.reaches_native(), "{report}");
}
#[test]
fn a_different_x_is_a_different_chunk() {
let e = crate::expr::parse("x * 2 + 1").expect("parses");
let resolve = |_: &str| f64::NAN;
let a = crate::expr::chunk_of(&e, 1.0, &resolve);
let b = crate::expr::chunk_of(&e, 2.0, &resolve);
assert_eq!(a.ops.len(), b.ops.len(), "same shape");
assert_ne!(
a.op_hash, b.op_hash,
"x is baked in as a constant, so the chunks cannot share a cache key"
);
}
}