1
//! The table's eval-time inline stack and runtime-guard tracking.
2

            
3
use anodized::spec;
4

            
5
use crate::ast::Expr;
6
use crate::compiler::datum::{self, MAX_ELAB_DEPTH};
7

            
8
use crate::error::{Error, Result};
9

            
10
use super::table::{MAX_SHARED_RECURSION_DEPTH, SymbolTable};
11

            
12
/// Free native stack below which the next level runs on a fresh segment. The
13
/// longest stretch between two guards is a walk of a tree whose nesting the
14
/// expansion ceiling bounds: measured under 8 KiB in release and under 256 KiB
15
/// in debug, so this leaves a 4x debug margin.
16
const RED_ZONE_BYTES: usize = 1024 * 1024;
17

            
18
/// Size of a fresh stack segment; recursion depth itself stays bounded by the
19
/// shared budget, so segments are few.
20
const GROW_BY_BYTES: usize = 4 * 1024 * 1024;
21

            
22
/// Runs `run` on the current stack, or on a fresh segment once less than
23
/// [`RED_ZONE_BYTES`] is left. Every compile-time recursion entry goes through it.
24
7102497165
pub(crate) fn with_sufficient_stack<T>(run: impl FnOnce() -> T) -> T {
25
7102497165
    stacker::maybe_grow(RED_ZONE_BYTES, GROW_BY_BYTES, run)
26
7102497165
}
27

            
28
impl SymbolTable {
29
111519
    pub(crate) fn recursion_ceiling_error() -> Error {
30
111519
        Error::Resource(format!(
31
111519
            "compile-time recursion exceeded the shared budget of \
32
111519
             {MAX_SHARED_RECURSION_DEPTH} levels — macro expansion, function inlining, closure \
33
111519
             factories, and AND/OR/COND runtime-guard nesting share one ceiling, since their native-stack \
34
111519
             costs combine regardless of which mix produced this depth"
35
111519
        ))
36
111519
    }
37

            
38
    /// Enter one level of the SHARED compile-time recursion budget (see
39
    /// [`Self::shared_recursion_depth`]), erroring once
40
    /// [`MAX_SHARED_RECURSION_DEPTH`] is crossed. Called from EVERY
41
    /// individual `enter_*` guard below, in addition to — never instead of
42
    /// — that mechanism's own ceiling.
43
    #[spec(
44
11244164
        maintains: self.shared_recursion_depth <= MAX_SHARED_RECURSION_DEPTH,
45
5622082
        captures: before = self.shared_recursion_depth,
46
        ensures: |ref output| [
47
5622082
            output.is_ok() == (before < MAX_SHARED_RECURSION_DEPTH),
48
5622082
            self.shared_recursion_depth == before + usize::from(output.is_ok()),
49
        ],
50
    )]
51
5622082
    pub(crate) fn enter_shared_recursion(&mut self) -> Result<()> {
52
5622082
        if self.shared_recursion_depth >= MAX_SHARED_RECURSION_DEPTH {
53
110686
            return Err(Self::recursion_ceiling_error());
54
5511396
        }
55
5511396
        self.shared_recursion_depth += 1;
56
5511396
        Ok(())
57
5622082
    }
58

            
59
5306704
    pub(crate) fn exit_shared_recursion(&mut self) -> Result<()> {
60
5306701
        self.shared_recursion_depth =
61
5306704
            self.shared_recursion_depth.checked_sub(1).ok_or_else(|| {
62
3
                Error::Compile(
63
3
                "internal: exit_shared_recursion() called with shared_recursion_depth already 0"
64
3
                    .to_string(),
65
3
            )
66
3
            })?;
67
5306701
        Ok(())
68
5306704
    }
69

            
70
    /// Enter one macro-expansion level, charged entirely against
71
    /// [`Self::shared_recursion_depth`] (see [`MAX_SHARED_RECURSION_DEPTH`](super::MAX_SHARED_RECURSION_DEPTH)
72
    /// — a self-referential macro has no OTHER state worth tracking here
73
    /// once that shared ceiling is the sole guard). Paired with
74
    /// [`Self::exit_macro_expansion`].
75
1137941
    pub(crate) fn enter_macro_expansion(&mut self) -> Result<()> {
76
1137941
        self.enter_shared_recursion()?;
77
1137498
        self.expansion_depths.push(0);
78
1137498
        Ok(())
79
1137941
    }
80

            
81
    /// Records the nesting of the innermost open expansion's `expansion`,
82
    /// refused once the open expansions together nest past
83
    /// [`MAX_ELAB_DEPTH`].
84
1109297
    pub(crate) fn compose_expansion(&mut self, expansion: &Expr, args: &[Expr]) -> Result<()> {
85
1109297
        let args_nesting = args
86
1109297
            .iter()
87
1109297
            .map(datum::nesting)
88
1294448
            .try_fold(0, |deepest, n| n.map(|n: usize| deepest.max(n)))?;
89
1109297
        let nesting = datum::nesting(expansion)?.saturating_sub(args_nesting);
90
1109297
        let outer = self.expansion_depths.iter().rev().skip(1).sum::<usize>();
91
1109297
        if outer + nesting > MAX_ELAB_DEPTH {
92
8113
            return Err(Error::Resource(format!(
93
8113
                "macro expansion nests deeper than {MAX_ELAB_DEPTH} levels"
94
8113
            )));
95
1101184
        }
96
1101184
        if let Some(open) = self.expansion_depths.last_mut() {
97
1101175
            *open = nesting;
98
9
        }
99
1101184
        Ok(())
100
1109297
    }
101

            
102
    /// Undoes [`Self::enter_macro_expansion`]. Errors — rather than silently
103
    /// absorbing the underflow — on a mismatched enter/exit pair: that is a
104
    /// compiler bug (a codegen path that entered twice but exited once, or
105
    /// vice versa), and letting it wrap silently would mask the depth guard
106
    /// instead of surfacing the mistake.
107
932993
    pub(crate) fn exit_macro_expansion(&mut self) -> Result<()> {
108
932993
        self.expansion_depths.pop();
109
932993
        self.exit_shared_recursion()
110
932993
    }
111

            
112
    /// Whether `name` is already being inlined further up the eval-time call
113
    /// chain — i.e. inlining it again would be (mutual) recursion.
114
    #[must_use]
115
3772559
    pub(crate) fn is_inlining(&self, name: &str) -> bool {
116
3772559
        self.inline_stack.iter().any(|n| n == name)
117
3772559
    }
118

            
119
    /// Runs `run` one level deep in the shared recursion budget, released on
120
    /// every exit.
121
1687439
    pub(crate) fn within_shared_recursion<T>(
122
1687439
        &mut self,
123
1687439
        run: impl FnOnce(&mut Self) -> Result<T>,
124
1687439
    ) -> Result<T> {
125
1687439
        self.enter_shared_recursion()?;
126
1681121
        let done = run(self);
127
1681121
        self.leave_shared_recursion(done)
128
1687439
    }
129

            
130
    /// Releases the level an [`Self::enter_shared_recursion`] charged around
131
    /// `done`; the run's own error wins over a release error.
132
1741860
    pub(crate) fn leave_shared_recursion<T>(&mut self, done: Result<T>) -> Result<T> {
133
1741860
        let exited = self.exit_shared_recursion();
134
1741860
        let value = done?;
135
1057069
        exited?;
136
1057069
        Ok(value)
137
1741860
    }
138

            
139
    /// Mark `name` as entering an eval-time inline walk. Paired with
140
    /// [`Self::exit_inline`]; charged entirely against
141
    /// [`Self::shared_recursion_depth`] — the eval-path analogue of
142
    /// [`Self::enter_macro_expansion`]. `inline_stack` itself is kept
143
    /// unbounded in length: it exists for [`Self::is_inlining`]'s
144
    /// recursive-call detection, not as a depth ceiling.
145
    #[spec(
146
1907483
        captures: before = self.inline_stack.len(),
147
        ensures: |ref output| [
148
1907483
            self.inline_stack.len() == before + usize::from(output.is_ok()),
149
1907483
            output.is_err() || self.is_inlining(name),
150
        ],
151
    )]
152
1907483
    pub(crate) fn enter_inline(&mut self, name: &str) -> Result<()> {
153
1907483
        self.enter_shared_recursion()?;
154
1814741
        self.inline_stack.push(name.to_string());
155
1814741
        Ok(())
156
1907483
    }
157

            
158
1814741
    #[spec(requires: !self.inline_stack.is_empty())]
159
1814741
    pub(crate) fn exit_inline(&mut self) -> Result<()> {
160
1814741
        self.inline_stack.pop();
161
1814741
        self.exit_shared_recursion()
162
1814741
    }
163

            
164
    /// Enters a runtime branch and charges one level of
165
    /// [`Self::shared_recursion_depth`], for the hand-offs that recurse
166
    /// natively (AND/OR, effect-position COND). Paired with
167
    /// [`Self::exit_runtime_guard`].
168
    #[spec(
169
330809
        captures: before = self.runtime_guard_depth,
170
        ensures: |ref output| [
171
330809
            self.runtime_guard_depth == before + usize::from(output.is_ok()),
172
        ],
173
    )]
174
330809
    pub(crate) fn enter_runtime_guard(&mut self) -> Result<()> {
175
330809
        self.enter_shared_recursion()?;
176
320409
        self.enter_runtime_branch().or_else(|err| {
177
            self.exit_shared_recursion()?;
178
            Err(err)
179
        })
180
330809
    }
181

            
182
320410
    pub(crate) fn exit_runtime_guard(&mut self) -> Result<()> {
183
320410
        let branch = self.exit_runtime_branch();
184
320410
        let shared = self.exit_shared_recursion();
185
320410
        branch.and(shared)
186
320410
    }
187

            
188
    /// Marks compilation as inside one runtime-conditional branch (see
189
    /// [`Self::is_under_any_runtime_guard`]) without charging the shared
190
    /// recursion budget: a branch arm costs no native recursion of its own.
191
    /// Paired with [`Self::exit_runtime_branch`].
192
    #[spec(
193
6633904
        captures: before = self.runtime_guard_depth,
194
        ensures: |ref output| [
195
6633904
            self.runtime_guard_depth == before + usize::from(output.is_ok()),
196
        ],
197
    )]
198
6633904
    pub(crate) fn enter_runtime_branch(&mut self) -> Result<()> {
199
6633904
        self.runtime_guard_depth = self.runtime_guard_depth.checked_add(1).ok_or_else(|| {
200
            Error::Compile("internal: runtime_guard_depth overflowed".to_string())
201
        })?;
202
6633904
        Ok(())
203
6633904
    }
204

            
205
5645455
    pub(crate) fn exit_runtime_branch(&mut self) -> Result<()> {
206
5645455
        self.runtime_guard_depth = self.runtime_guard_depth.checked_sub(1).ok_or_else(|| {
207
4
            Error::Compile(
208
4
                "internal: exit_runtime_branch() called with runtime_guard_depth already 0"
209
4
                    .to_string(),
210
4
            )
211
4
        })?;
212
5645451
        Ok(())
213
5645455
    }
214

            
215
    /// True while compiling code that runs only when a runtime test selects
216
    /// it (see [`Self::runtime_guard_depth`]). Definition forms and
217
    /// compile-time-only SETFs check this at their own registration site,
218
    /// so the check sees through macro expansion and any nesting.
219
    #[must_use]
220
7972902
    pub(crate) fn is_under_any_runtime_guard(&self) -> bool {
221
7972902
        self.runtime_guard_depth > 0
222
7972902
    }
223

            
224
    /// Suspends runtime-guard tracking (see
225
    /// [`Self::is_under_any_runtime_guard`]) on this table — used only on
226
    /// the DISPOSABLE clone `expand_macro` evaluates a macro's BODY
227
    /// against. A macro's body registers definitions into its own PRIVATE
228
    /// expansion environment (discarded once the expansion's generated
229
    /// code is produced) regardless of whether the macro's CALL SITE
230
    /// happens to sit under a runtime guard — that guard governs the
231
    /// GENERATED code once it's spliced back in and recompiled against the
232
    /// caller's own (unsuspended) table, not the expansion machinery that
233
    /// produced it. Recursion accounting (`shared_recursion_depth`,
234
    /// `inline_stack`) is left untouched.
235
1137094
    pub(crate) fn suspend_runtime_guards(&mut self) {
236
1137094
        self.runtime_guard_depth = 0;
237
1137094
        self.skippable_depth = 0;
238
1137094
        self.function_owner = None;
239
1137094
        self.exit_regions.clear();
240
1137094
        self.close_loop_blocks();
241
1137094
    }
242
}