ruxla-core 0.1.0

Internal crate of ruxla (use the `ruxla` crate): the frontend of ruxla (backend-generic values, native and tracing backends)
Documentation
//! The tracing context of the `Trace` backend.
//!
//! Values of the `Trace` backend are [`TraceRef`]s: two integers naming an
//! entry of a trace frame. The frames live on a thread-local stack, so the
//! values can be `Copy`. A frame records the
//! equations of one function being traced; nested functions (the branches of
//! `cond`, the body of `while`, ...) push frames of their own, and values of
//! enclosing frames that they use are captured as extra inputs.

use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU32, Ordering};

use ruxla_ir::{AVal, Atom, Eqn, Function, HostArray, Literal, Params, Prim, Var};

/// A value of the `Trace` backend: an entry of a trace frame.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct TraceRef {
    frame: u32,
    index: u32,
}

/// What a frame entry is.
#[derive(Clone, Debug)]
enum Entry {
    /// A variable defined in the frame (an input or an equation's output).
    Var(Var),
    /// A scalar literal.
    Lit(Literal),
    /// A constant array (a `constvar` of the function).
    Const(Var, HostArray),
}

#[derive(Debug)]
struct Frame {
    id: u32,
    entries: Vec<Entry>,
    invars: Vec<Var>,
    eqns: Vec<Eqn>,
    constvars: Vec<(Var, HostArray)>,
    /// Values of the enclosing frame captured as inputs: the value in the
    /// enclosing frame, and the input variable in this frame.
    captured: Vec<(TraceRef, Var)>,
    /// Entries of other frames already resolved in this frame.
    resolved: HashMap<TraceRef, Atom>,
}

thread_local! {
    static STACK: RefCell<Vec<Frame>> = const { RefCell::new(Vec::new()) };
}

static NEXT_FRAME: AtomicU32 = AtomicU32::new(1);

/// Returns whether a trace is in progress on this thread.
pub fn is_tracing() -> bool {
    STACK.with(|s| !s.borrow().is_empty())
}

fn push_entry(frame: &mut Frame, entry: Entry) -> TraceRef {
    frame.entries.push(entry);
    TraceRef {
        frame: frame.id,
        index: (frame.entries.len() - 1) as u32,
    }
}

/// Returns the atom for `r` in frame `level`, capturing it from enclosing
/// frames if needed.
fn resolve(stack: &mut [Frame], level: usize, r: TraceRef) -> Atom {
    if stack[level].id == r.frame {
        return match &stack[level].entries[r.index as usize] {
            Entry::Var(v) | Entry::Const(v, _) => Atom::Var(v.clone()),
            Entry::Lit(l) => Atom::Lit(l.clone()),
        };
    }
    if let Some(a) = stack[level].resolved.get(&r) {
        return a.clone();
    }
    let Some(owner) = stack[..level].iter().position(|f| f.id == r.frame) else {
        panic!(
            "a traced value was used after its trace ended (or in another thread); \
             traced values must not escape the function being traced"
        );
    };
    let atom = match &stack[owner].entries[r.index as usize] {
        Entry::Lit(l) => Atom::Lit(l.clone()),
        // Constants are copied rather than captured.
        Entry::Const(_, value) => {
            let value = value.clone();
            let v = Var::new(value.aval());
            stack[level].constvars.push((v.clone(), value));
            Atom::Var(v)
        }
        Entry::Var(_) => {
            // Capture from the enclosing frame, which may itself capture.
            let outer = resolve(stack, level - 1, r);
            let Atom::Var(outer_var) = outer else {
                unreachable!("variables resolve to variables")
            };
            let parent = &mut stack[level - 1];
            let outer_ref = push_entry(parent, Entry::Var(outer_var.clone()));
            let v = Var::new(outer_var.aval().clone());
            stack[level].captured.push((outer_ref, v.clone()));
            Atom::Var(v)
        }
    };
    stack[level].resolved.insert(r, atom.clone());
    atom
}

/// Returns the abstract value of a traced value.
pub(crate) fn aval(r: TraceRef) -> AVal {
    STACK.with(|s| {
        let s = s.borrow();
        let Some(frame) = s.iter().find(|f| f.id == r.frame) else {
            panic!("a traced value was used after its trace ended");
        };
        match &frame.entries[r.index as usize] {
            Entry::Var(v) | Entry::Const(v, _) => v.aval().clone(),
            Entry::Lit(l) => l.value().aval(),
        }
    })
}

/// Returns the value of a traced literal, if it is one (for constant
/// folding of static checks).
pub(crate) fn literal_value(r: TraceRef) -> Option<HostArray> {
    STACK.with(|s| {
        let s = s.borrow();
        let frame = s.iter().find(|f| f.id == r.frame)?;
        match &frame.entries[r.index as usize] {
            Entry::Lit(l) => Some(l.value().clone()),
            _ => None,
        }
    })
}

/// Adds a scalar literal to the current frame.
///
/// # Panics
///
/// Panics if no trace is in progress.
pub(crate) fn literal(value: HostArray) -> TraceRef {
    STACK.with(|s| {
        let mut s = s.borrow_mut();
        let top = s
            .last_mut()
            .expect("Trace values can only be created while tracing");
        push_entry(top, Entry::Lit(Literal::new(value)))
    })
}

/// Adds a constant array to the current frame.
pub(crate) fn constant(value: HostArray) -> TraceRef {
    if value.shape().rank() == 0 {
        return literal(value);
    }
    STACK.with(|s| {
        let mut s = s.borrow_mut();
        let top = s
            .last_mut()
            .expect("Trace values can only be created while tracing");
        let v = Var::new(value.aval());
        top.constvars.push((v.clone(), value.clone()));
        push_entry(top, Entry::Const(v, value))
    })
}

/// Records an equation in the current frame and returns its outputs.
///
/// # Panics
///
/// Panics if no trace is in progress, or with the primitive's message if it
/// rejects the inputs.
#[track_caller]
pub(crate) fn bind(prim: Prim, inputs: &[TraceRef], params: Params) -> Vec<TraceRef> {
    let loc = std::panic::Location::caller();
    STACK.with(|s| {
        let mut s = s.borrow_mut();
        let level = s
            .len()
            .checked_sub(1)
            .expect("Trace operations need a trace in progress");
        let atoms: Vec<Atom> = inputs.iter().map(|&r| resolve(&mut s, level, r)).collect();
        let avals: Vec<AVal> = atoms.iter().map(Atom::aval).collect();
        let outs = prim
            .abstract_eval(&avals, &params)
            .unwrap_or_else(|e| panic!("{e}"));
        let outputs: Vec<Var> = outs.into_iter().map(Var::new).collect();
        let top = &mut s[level];
        top.eqns.push(Eqn {
            prim,
            inputs: atoms,
            params,
            outputs: outputs.clone(),
            loc: Some(loc),
        });
        outputs
            .into_iter()
            .map(|v| push_entry(top, Entry::Var(v)))
            .collect()
    })
}

/// The result of [`trace_function`].
#[derive(Debug)]
pub(crate) struct Traced {
    /// The function. Its inputs are the captured values followed by the
    /// arguments.
    pub(crate) function: Function,
    /// The captured values, in the enclosing frame, to pass as the first
    /// arguments.
    pub(crate) captured: Vec<TraceRef>,
}

/// Pops the frame when dropped, so that a panic while tracing does not
/// leave it on the stack.
struct PopOnDrop;

impl Drop for PopOnDrop {
    fn drop(&mut self) {
        STACK.with(|s| {
            s.borrow_mut().pop();
        });
    }
}

/// Traces `f` as a function with inputs of `in_avals`.
pub(crate) fn trace_function(
    in_avals: &[AVal],
    f: impl FnOnce(&[TraceRef]) -> Vec<TraceRef>,
) -> Traced {
    let id = NEXT_FRAME.fetch_add(1, Ordering::Relaxed);
    let args: Vec<TraceRef> = STACK.with(|s| {
        let mut s = s.borrow_mut();
        let mut frame = Frame {
            id,
            entries: Vec::new(),
            invars: Vec::new(),
            eqns: Vec::new(),
            constvars: Vec::new(),
            captured: Vec::new(),
            resolved: HashMap::new(),
        };
        let args = in_avals
            .iter()
            .map(|a| {
                let v = Var::new(a.clone());
                frame.invars.push(v.clone());
                push_entry(&mut frame, Entry::Var(v))
            })
            .collect();
        s.push(frame);
        args
    });
    let guard = PopOnDrop;
    let outs = f(&args);
    let traced = STACK.with(|s| {
        let mut s = s.borrow_mut();
        let level = s.len() - 1;
        assert_eq!(s[level].id, id, "trace frames were not properly nested");
        let outvars: Vec<Atom> = outs.iter().map(|&r| resolve(&mut s, level, r)).collect();
        let frame = &mut s[level];
        let (captured, captured_vars): (Vec<TraceRef>, Vec<Var>) = frame.captured.drain(..).unzip();
        let mut invars = captured_vars;
        invars.append(&mut frame.invars);
        Traced {
            function: Function {
                constvars: std::mem::take(&mut frame.constvars),
                invars,
                eqns: std::mem::take(&mut frame.eqns),
                outvars,
            },
            captured,
        }
    });
    drop(guard);
    traced
}