1
//! One monotonic compile-time work budget (ADR-0034 / plan 0011 Phase 0).
2
//!
3
//! [`SharedBudget`] charges work units for every mechanism that can blow up
4
//! super-linearly against its input: `eval_value`'s recursive re-evaluation
5
//! (e.g. `COND`'s constant-test probe, which doubles the work of whatever
6
//! its test expression itself costs to evaluate), macro expansion output,
7
//! and constant folding over a large datum. It is shared — via
8
//! [`SharedBudget`] — by every clone of the `SymbolTable` a single unit
9
//! makes for classification probes, and a discarded probe's work is not
10
//! refunded, so the ceiling bounds the whole unit across its attempts. The
11
//! store scan, which repeats the expansions, counts against a ceiling of its
12
//! own.
13

            
14
use std::sync::Arc;
15
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
16

            
17
use crate::error::{Error, Result};
18

            
19
/// Hard ceiling on the work units a single compilation unit may charge, across
20
/// `eval_value`, macro expansion, datum folds and codegen entries, and again on
21
/// the store scan's own expansions. Confirmed
22
/// provisionally at 2^20, pending the corpus showing otherwise (plan 0011,
23
/// "Budget"). Emitted-instruction / output-byte charging — the plan's
24
/// "emission" bullet — is NOT wired in this phase: charging the finished
25
/// module's byte count after `ctx.finish()` bounds nothing (the module is
26
/// already fully built by then, so a runaway emission has already paid its
27
/// native-stack and heap cost before any charge could reject it), so
28
/// Phase 0 ships without it rather than with a charge that only looks
29
/// protective.
30
pub(crate) const MAX_ELAB_WORK: u64 = 1 << 20;
31

            
32
/// Structured error for a running total that has crossed [`MAX_ELAB_WORK`].
33
787742866
fn exceeded(charged: u64) -> Result<()> {
34
787742866
    if charged > MAX_ELAB_WORK {
35
450
        return Err(Error::Resource(format!(
36
450
            "compile-time work budget exceeded ({MAX_ELAB_WORK} units) — the form is too \
37
450
             large, too deeply recursive, or expands too much to elaborate"
38
450
        )));
39
787742416
    }
40
787742416
    Ok(())
41
787742866
}
42

            
43
/// A work counter shared across every clone of one `SymbolTable`, so probe
44
/// clones (classification on a disposable copy, macro expansion's private
45
/// environment) charge against the SAME ceiling as the table they were
46
/// cloned from. Cloning a `SharedBudget` shares the counter; it does not
47
/// fork it.
48
///
49
/// Backed by an [`AtomicU64`] rather than a plain counter behind a
50
/// `Rc<RefCell<_>>`: `SymbolTable` — and so this counter — is held across
51
/// `.await` points by `rpc::Session`, which callers spawn onto a
52
/// multi-threaded async runtime, so every field it holds must be `Send` +
53
/// `Sync`. The compare-exchange loop below is a genuine saturating-add,
54
/// correct under real cross-thread contention (`concurrent_charges_…`
55
/// pins this), even though the compiler only ever uses one of these from a
56
/// single thread at a time in practice.
57
#[derive(Debug, Clone)]
58
pub(crate) struct SharedBudget(Arc<Counters>, Arc<AtomicU64>, Arc<AtomicU64>);
59

            
60
/// The plan-0014 measurement counters, never refunded: they report what the
61
/// compilation DID, including the work of a discarded trial.
62
#[derive(Debug, Default)]
63
struct Counters {
64
    folds: AtomicU64,
65
    walks: AtomicU64,
66
    exits: AtomicU64,
67
    cell_stores: AtomicU64,
68
    macro_global_reads: AtomicU64,
69
    stored_globals: AtomicU64,
70
    possibly_storing: AtomicBool,
71
    opaque_macro_uses: AtomicU64,
72
}
73

            
74
impl SharedBudget {
75
    #[must_use]
76
5619169
    pub(crate) fn new() -> Self {
77
5619169
        Self(Arc::default(), Arc::default(), Arc::default())
78
5619169
    }
79

            
80
    /// This budget with fresh measurement counters and the same work, so each
81
    /// attempt at a unit measures itself while the unit's work accumulates.
82
    #[must_use]
83
2352271
    pub(crate) fn with_fresh_measurements(&self) -> Self {
84
2352271
        Self(Arc::default(), Arc::clone(&self.1), Arc::clone(&self.2))
85
2352271
    }
86

            
87
    /// A budget that shares the measurement counters but charges the store
88
    /// scan's own work, so the scan that repeats the unit's expansions does
89
    /// not charge the unit twice; the scan still has the whole ceiling.
90
    #[must_use]
91
7187038
    pub(crate) fn for_scan(&self) -> Self {
92
7187038
        Self(self.0.clone(), self.2.clone(), self.2.clone())
93
7187038
    }
94

            
95
787742866
    pub(crate) fn charge(&self, units: u64) -> Result<()> {
96
787742866
        let mut current = self.1.load(Ordering::Relaxed);
97
        let next = loop {
98
787743004
            let candidate = current.saturating_add(units);
99
787743004
            match self.1.compare_exchange_weak(
100
787743004
                current,
101
787743004
                candidate,
102
787743004
                Ordering::Relaxed,
103
787743004
                Ordering::Relaxed,
104
787743004
            ) {
105
787742866
                Ok(_) => break candidate,
106
138
                Err(observed) => current = observed,
107
            }
108
        };
109
787742866
        exceeded(next)
110
787742866
    }
111

            
112
    /// Units charged so far.
113
    #[cfg(test)]
114
    #[must_use]
115
285
    pub(crate) fn charged(&self) -> u64 {
116
285
        self.1.load(Ordering::Relaxed)
117
285
    }
118

            
119
    /// Units still available before [`MAX_ELAB_WORK`] is crossed.
120
    #[must_use]
121
118614
    pub(crate) fn remaining(&self) -> u64 {
122
118614
        MAX_ELAB_WORK.saturating_sub(self.1.load(Ordering::Relaxed))
123
118614
    }
124

            
125
    /// Records one compound form `eval_value` reduced to a constant datum.
126
42401452
    pub(crate) fn note_fold(&self) {
127
42401452
        self.0.folds.fetch_add(1, Ordering::Relaxed);
128
42401452
    }
129

            
130
    /// Folds recorded so far (see [`Self::note_fold`]).
131
    #[must_use]
132
2352271
    pub(crate) fn folds(&self) -> u64 {
133
2352271
        self.0.folds.load(Ordering::Relaxed)
134
2352271
    }
135

            
136
    /// Records one evaluator or divergence walk entered.
137
772032263
    pub(crate) fn note_walk(&self) {
138
772032263
        self.0.walks.fetch_add(1, Ordering::Relaxed);
139
772032263
    }
140

            
141
    /// Walks recorded so far (see [`Self::note_walk`]).
142
    #[must_use]
143
2352271
    pub(crate) fn walks(&self) -> u64 {
144
2352271
        self.0.walks.load(Ordering::Relaxed)
145
2352271
    }
146

            
147
    /// Records one evaluated `return-from` / `error` / `go` form, the only
148
    /// forms that leave their code unreachable.
149
416039
    pub(crate) fn note_exit(&self) {
150
416039
        self.0.exits.fetch_add(1, Ordering::Relaxed);
151
416039
    }
152

            
153
    /// Exit forms recorded so far (see [`Self::note_exit`]).
154
    #[must_use]
155
5363777
    pub(crate) fn exits(&self) -> u64 {
156
5363777
        self.0.exits.load(Ordering::Relaxed)
157
5363777
    }
158

            
159
    /// Records one evaluated store to a global cell, an effect no constant
160
    /// fold may drop.
161
126082
    pub(crate) fn note_cell_store(&self) {
162
126082
        self.0.cell_stores.fetch_add(1, Ordering::Relaxed);
163
126082
    }
164

            
165
    /// Cell stores recorded so far (see [`Self::note_cell_store`]).
166
    #[must_use]
167
81033
    pub(crate) fn cell_stores(&self) -> u64 {
168
81033
        self.0.cell_stores.load(Ordering::Relaxed)
169
81033
    }
170

            
171
    /// Records one macro expansion whose body reads a variable it did not
172
    /// bind itself.
173
19481
    pub(crate) fn note_macro_global_read(&self) {
174
19481
        self.0.macro_global_reads.fetch_add(1, Ordering::Relaxed);
175
19481
    }
176

            
177
    /// Expansions recorded so far (see [`Self::note_macro_global_read`]).
178
    #[must_use]
179
2352271
    pub(crate) fn macro_global_reads(&self) -> u64 {
180
2352271
        self.0.macro_global_reads.load(Ordering::Relaxed)
181
2352271
    }
182

            
183
    /// Records the unit's store scan: directly stored globals, whether a
184
    /// `SETF` escaped the scan, and the opaque macro uses (0014 Stage 2).
185
2341817
    pub(crate) fn note_store_scan(&self, stored: u64, possibly_storing: bool, opaque: u64) {
186
2341817
        self.0.stored_globals.store(stored, Ordering::Relaxed);
187
2341817
        self.0
188
2341817
            .possibly_storing
189
2341817
            .store(possibly_storing, Ordering::Relaxed);
190
2341817
        self.0.opaque_macro_uses.store(opaque, Ordering::Relaxed);
191
2341817
    }
192

            
193
    /// The store scan's measures (see [`Self::note_store_scan`]).
194
    #[must_use]
195
2352271
    pub(crate) fn store_scan(&self) -> (u64, bool, u64) {
196
2352271
        (
197
2352271
            self.0.stored_globals.load(Ordering::Relaxed),
198
2352271
            self.0.possibly_storing.load(Ordering::Relaxed),
199
2352271
            self.0.opaque_macro_uses.load(Ordering::Relaxed),
200
2352271
        )
201
2352271
    }
202
}
203

            
204
impl Default for SharedBudget {
205
3342989
    fn default() -> Self {
206
3342989
        Self::new()
207
3342989
    }
208
}
209

            
210
#[cfg(test)]
211
#[path = "budget_tests.rs"]
212
mod tests;