lehit 0.2.0

Embeddable Lehit language frontend and Cranelift JIT runtime
Documentation
use std::{
    ffi::c_void,
    panic::{AssertUnwindSafe, catch_unwind},
    sync::Arc,
};

pub(crate) const RECORD_BOUNDS_VIOLATION_SYMBOL: &str = "__lehit_record_bounds_violation";

/// Observable failure semantics used by generated entry points.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ExecutionMode {
    /// Uses backend-native traps/wrapping behavior and the smallest internal generated ABI.
    #[default]
    Direct,
    /// Instruments supported runtime failures. The universal ABI exposes their
    /// category through `AbiCallStatus` and optional details through `ErrorChannel`.
    Checked,
}

/// Numeric status stored in the checked-call C ABI context.
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) enum ExecutionErrorCode {
    #[default]
    None = 0,
    BoundsViolation = 1,
    DivisionByZero = 2,
    IntegerOverflow = 3,
    InvalidShift = 4,
}

/// Structured failure reported by a checked generated entry point.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExecutionError {
    /// An array index was outside `0..length`.
    BoundsViolation {
        /// Attempted index.
        index: usize,
        /// Runtime array length.
        length: usize,
    },
    /// Integer division used a zero divisor.
    DivisionByZero,
    /// Checked integer arithmetic overflowed.
    IntegerOverflow,
    /// A shift amount was not valid for the operand width.
    InvalidShift {
        /// Attempted shift amount.
        amount: usize,
        /// Width of the shifted integer in bits.
        bit_width: usize,
    },
}

impl std::fmt::Display for ExecutionError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::BoundsViolation { index, length } => {
                write!(
                    formatter,
                    "array index {index} is out of bounds for length {length}"
                )
            }
            Self::DivisionByZero => formatter.write_str("integer division by zero"),
            Self::IntegerOverflow => formatter.write_str("integer arithmetic overflow"),
            Self::InvalidShift { amount, bit_width } => write!(
                formatter,
                "shift amount {amount} is invalid for a {bit_width}-bit integer"
            ),
        }
    }
}

impl std::error::Error for ExecutionError {}

/// Detailed diagnostic emitted when checked JIT execution detects a runtime error.
///
/// Function calls still return a compact status code. Reports are an optional
/// side channel intended for logging and diagnostics, not programmatic recovery.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RuntimeErrorReport {
    /// Structured runtime failure, including any operation-specific details.
    pub error: ExecutionError,
}

/// Receives detailed checked-execution diagnostics.
///
/// Implementations may be called concurrently. A panic is contained by the
/// runtime trampoline and is never allowed to unwind through generated code.
pub trait ErrorChannel: Send + Sync + 'static {
    /// Handles one runtime-error report at the point where it originated.
    fn report(&self, report: &RuntimeErrorReport);
}

impl<F> ErrorChannel for F
where
    F: Fn(&RuntimeErrorReport) + Send + Sync + 'static,
{
    fn report(&self, report: &RuntimeErrorReport) {
        self(report);
    }
}

#[derive(Clone)]
pub(crate) struct RuntimeErrorSink {
    state: Arc<RuntimeErrorSinkState>,
}

struct RuntimeErrorSinkState {
    channel: Arc<dyn ErrorChannel>,
}

impl RuntimeErrorSink {
    pub(crate) fn new(channel: Arc<dyn ErrorChannel>) -> Self {
        Self {
            state: Arc::new(RuntimeErrorSinkState { channel }),
        }
    }

    pub(crate) fn context(&self) -> *const c_void {
        Arc::as_ptr(&self.state).cast()
    }

    pub(crate) fn callback(&self) -> RuntimeErrorCallback {
        report_runtime_error
    }
}

pub(crate) type RuntimeErrorCallback =
    unsafe extern "C" fn(context: *const c_void, code: u32, first: usize, second: usize);

unsafe extern "C" fn report_runtime_error(
    context: *const c_void,
    code: u32,
    first: usize,
    second: usize,
) {
    let Some(state) = (unsafe { context.cast::<RuntimeErrorSinkState>().as_ref() }) else {
        return;
    };
    let Some(error) = execution_error_from_raw(code, first, second) else {
        return;
    };
    let report = RuntimeErrorReport { error };
    let _ = catch_unwind(AssertUnwindSafe(|| state.channel.report(&report)));
}

pub(crate) fn execution_error_from_raw(
    code: u32,
    first: usize,
    second: usize,
) -> Option<ExecutionError> {
    match code {
        value if value == ExecutionErrorCode::None as u32 => None,
        value if value == ExecutionErrorCode::BoundsViolation as u32 => {
            Some(ExecutionError::BoundsViolation {
                index: first,
                length: second,
            })
        }
        value if value == ExecutionErrorCode::DivisionByZero as u32 => {
            Some(ExecutionError::DivisionByZero)
        }
        value if value == ExecutionErrorCode::IntegerOverflow as u32 => {
            Some(ExecutionError::IntegerOverflow)
        }
        value if value == ExecutionErrorCode::InvalidShift as u32 => {
            Some(ExecutionError::InvalidShift {
                amount: first,
                bit_width: second,
            })
        }
        _ => None,
    }
}

/// C-compatible first-error context passed through checked generated calls.
///
/// One context can be reused after [`ExecutionContext::clear`]. Generated code
/// records only the first failure so cleanup cannot overwrite the root cause.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct ExecutionContext {
    pub(crate) code: ExecutionErrorCode,
    pub(crate) first: usize,
    pub(crate) second: usize,
}

impl ExecutionContext {
    /// Creates an empty context.
    #[cfg(test)]
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// Removes a previously recorded error.
    #[cfg(test)]
    pub(crate) fn clear(&mut self) {
        *self = Self::default();
    }

    /// Returns the first recorded structured error, if any.
    #[cfg(test)]
    pub(crate) fn error(&self) -> Option<ExecutionError> {
        match self.code {
            ExecutionErrorCode::None => None,
            ExecutionErrorCode::BoundsViolation => Some(ExecutionError::BoundsViolation {
                index: self.first,
                length: self.second,
            }),
            ExecutionErrorCode::DivisionByZero => Some(ExecutionError::DivisionByZero),
            ExecutionErrorCode::IntegerOverflow => Some(ExecutionError::IntegerOverflow),
            ExecutionErrorCode::InvalidShift => Some(ExecutionError::InvalidShift {
                amount: self.first,
                bit_width: self.second,
            }),
        }
    }

    pub(crate) fn record_bounds_violation(&mut self, index: usize, length: usize) {
        if self.code == ExecutionErrorCode::None {
            self.code = ExecutionErrorCode::BoundsViolation;
            self.first = index;
            self.second = length;
        }
    }
}

/// Internal JIT ABI. Generated code passes the current checked-execution
/// context and machine-sized bounds operands without interpreting its layout.
pub(crate) unsafe extern "C" fn record_bounds_violation(
    context: *mut ExecutionContext,
    index: usize,
    length: usize,
) {
    // SAFETY: checked JIT entry adapters and internal checked calls always pass
    // the live context pointer belonging to the current execution.
    if let Some(context) = unsafe { context.as_mut() } {
        context.record_bounds_violation(index, length);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn error_sink_reports_details_and_contains_channel_panics() {
        let reports = Arc::new(std::sync::Mutex::new(Vec::new()));
        let captured = Arc::clone(&reports);
        let sink = RuntimeErrorSink::new(Arc::new(move |report: &RuntimeErrorReport| {
            captured.lock().unwrap().push(*report);
        }));

        unsafe {
            (sink.callback())(
                sink.context(),
                ExecutionErrorCode::BoundsViolation as u32,
                7,
                3,
            );
        }
        assert_eq!(
            reports.lock().unwrap().as_slice(),
            &[RuntimeErrorReport {
                error: ExecutionError::BoundsViolation {
                    index: 7,
                    length: 3,
                },
            }]
        );

        let panicking = RuntimeErrorSink::new(Arc::new(|_: &RuntimeErrorReport| panic!("channel")));
        unsafe {
            (panicking.callback())(
                panicking.context(),
                ExecutionErrorCode::DivisionByZero as u32,
                0,
                0,
            );
        }
    }

    #[test]
    fn execution_context_records_the_first_structured_error() {
        let mut context = ExecutionContext::new();
        assert_eq!(context.error(), None);

        context.record_bounds_violation(4, 2);
        context.record_bounds_violation(8, 1);
        assert_eq!(
            context.error(),
            Some(ExecutionError::BoundsViolation {
                index: 4,
                length: 2,
            })
        );

        context.clear();
        assert_eq!(context.error(), None);
    }

    #[test]
    fn execution_context_has_a_c_abi_stable_field_order() {
        assert_eq!(
            std::mem::align_of::<ExecutionContext>(),
            std::mem::align_of::<usize>()
        );
        assert!(std::mem::size_of::<ExecutionContext>() >= std::mem::size_of::<usize>() * 3);
    }
}