Lines
100 %
Functions
Branches
//! One monotonic compile-time work budget (ADR-0034 / plan 0011 Phase 0).
//!
//! [`SharedBudget`] charges work units for every mechanism that can blow up
//! super-linearly against its input: `eval_value`'s recursive re-evaluation
//! (e.g. `COND`'s constant-test probe, which doubles the work of whatever
//! its test expression itself costs to evaluate), macro expansion output,
//! and constant folding over a large datum. It is shared — via
//! [`SharedBudget`] — by every clone of the `SymbolTable` a single unit
//! makes for classification probes, and a discarded probe's work is not
//! refunded, so the ceiling bounds the whole unit across its attempts. The
//! store scan, which repeats the expansions, counts against a ceiling of its
//! own.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use crate::error::{Error, Result};
/// Hard ceiling on the work units a single compilation unit may charge, across
/// `eval_value`, macro expansion, datum folds and codegen entries, and again on
/// the store scan's own expansions. Confirmed
/// provisionally at 2^20, pending the corpus showing otherwise (plan 0011,
/// "Budget"). Emitted-instruction / output-byte charging — the plan's
/// "emission" bullet — is NOT wired in this phase: charging the finished
/// module's byte count after `ctx.finish()` bounds nothing (the module is
/// already fully built by then, so a runaway emission has already paid its
/// native-stack and heap cost before any charge could reject it), so
/// Phase 0 ships without it rather than with a charge that only looks
/// protective.
pub(crate) const MAX_ELAB_WORK: u64 = 1 << 20;
/// Structured error for a running total that has crossed [`MAX_ELAB_WORK`].
fn exceeded(charged: u64) -> Result<()> {
if charged > MAX_ELAB_WORK {
return Err(Error::Resource(format!(
"compile-time work budget exceeded ({MAX_ELAB_WORK} units) — the form is too \
large, too deeply recursive, or expands too much to elaborate"
)));
}
Ok(())
/// A work counter shared across every clone of one `SymbolTable`, so probe
/// clones (classification on a disposable copy, macro expansion's private
/// environment) charge against the SAME ceiling as the table they were
/// cloned from. Cloning a `SharedBudget` shares the counter; it does not
/// fork it.
///
/// Backed by an [`AtomicU64`] rather than a plain counter behind a
/// `Rc<RefCell<_>>`: `SymbolTable` — and so this counter — is held across
/// `.await` points by `rpc::Session`, which callers spawn onto a
/// multi-threaded async runtime, so every field it holds must be `Send` +
/// `Sync`. The compare-exchange loop below is a genuine saturating-add,
/// correct under real cross-thread contention (`concurrent_charges_…`
/// pins this), even though the compiler only ever uses one of these from a
/// single thread at a time in practice.
#[derive(Debug, Clone)]
pub(crate) struct SharedBudget(Arc<Counters>, Arc<AtomicU64>, Arc<AtomicU64>);
/// The plan-0014 measurement counters, never refunded: they report what the
/// compilation DID, including the work of a discarded trial.
#[derive(Debug, Default)]
struct Counters {
folds: AtomicU64,
walks: AtomicU64,
exits: AtomicU64,
cell_stores: AtomicU64,
macro_global_reads: AtomicU64,
stored_globals: AtomicU64,
possibly_storing: AtomicBool,
opaque_macro_uses: AtomicU64,
impl SharedBudget {
#[must_use]
pub(crate) fn new() -> Self {
Self(Arc::default(), Arc::default(), Arc::default())
/// This budget with fresh measurement counters and the same work, so each
/// attempt at a unit measures itself while the unit's work accumulates.
pub(crate) fn with_fresh_measurements(&self) -> Self {
Self(Arc::default(), Arc::clone(&self.1), Arc::clone(&self.2))
/// A budget that shares the measurement counters but charges the store
/// scan's own work, so the scan that repeats the unit's expansions does
/// not charge the unit twice; the scan still has the whole ceiling.
pub(crate) fn for_scan(&self) -> Self {
Self(self.0.clone(), self.2.clone(), self.2.clone())
pub(crate) fn charge(&self, units: u64) -> Result<()> {
let mut current = self.1.load(Ordering::Relaxed);
let next = loop {
let candidate = current.saturating_add(units);
match self.1.compare_exchange_weak(
current,
candidate,
Ordering::Relaxed,
) {
Ok(_) => break candidate,
Err(observed) => current = observed,
};
exceeded(next)
/// Units charged so far.
#[cfg(test)]
pub(crate) fn charged(&self) -> u64 {
self.1.load(Ordering::Relaxed)
/// Units still available before [`MAX_ELAB_WORK`] is crossed.
pub(crate) fn remaining(&self) -> u64 {
MAX_ELAB_WORK.saturating_sub(self.1.load(Ordering::Relaxed))
/// Records one compound form `eval_value` reduced to a constant datum.
pub(crate) fn note_fold(&self) {
self.0.folds.fetch_add(1, Ordering::Relaxed);
/// Folds recorded so far (see [`Self::note_fold`]).
pub(crate) fn folds(&self) -> u64 {
self.0.folds.load(Ordering::Relaxed)
/// Records one evaluator or divergence walk entered.
pub(crate) fn note_walk(&self) {
self.0.walks.fetch_add(1, Ordering::Relaxed);
/// Walks recorded so far (see [`Self::note_walk`]).
pub(crate) fn walks(&self) -> u64 {
self.0.walks.load(Ordering::Relaxed)
/// Records one evaluated `return-from` / `error` / `go` form, the only
/// forms that leave their code unreachable.
pub(crate) fn note_exit(&self) {
self.0.exits.fetch_add(1, Ordering::Relaxed);
/// Exit forms recorded so far (see [`Self::note_exit`]).
pub(crate) fn exits(&self) -> u64 {
self.0.exits.load(Ordering::Relaxed)
/// Records one evaluated store to a global cell, an effect no constant
/// fold may drop.
pub(crate) fn note_cell_store(&self) {
self.0.cell_stores.fetch_add(1, Ordering::Relaxed);
/// Cell stores recorded so far (see [`Self::note_cell_store`]).
pub(crate) fn cell_stores(&self) -> u64 {
self.0.cell_stores.load(Ordering::Relaxed)
/// Records one macro expansion whose body reads a variable it did not
/// bind itself.
pub(crate) fn note_macro_global_read(&self) {
self.0.macro_global_reads.fetch_add(1, Ordering::Relaxed);
/// Expansions recorded so far (see [`Self::note_macro_global_read`]).
pub(crate) fn macro_global_reads(&self) -> u64 {
self.0.macro_global_reads.load(Ordering::Relaxed)
/// Records the unit's store scan: directly stored globals, whether a
/// `SETF` escaped the scan, and the opaque macro uses (0014 Stage 2).
pub(crate) fn note_store_scan(&self, stored: u64, possibly_storing: bool, opaque: u64) {
self.0.stored_globals.store(stored, Ordering::Relaxed);
self.0
.possibly_storing
.store(possibly_storing, Ordering::Relaxed);
self.0.opaque_macro_uses.store(opaque, Ordering::Relaxed);
/// The store scan's measures (see [`Self::note_store_scan`]).
pub(crate) fn store_scan(&self) -> (u64, bool, u64) {
(
self.0.stored_globals.load(Ordering::Relaxed),
self.0.possibly_storing.load(Ordering::Relaxed),
self.0.opaque_macro_uses.load(Ordering::Relaxed),
)
impl Default for SharedBudget {
fn default() -> Self {
Self::new()
#[path = "budget_tests.rs"]
mod tests;