use alloc::format;
use alloc::string::String;
pub trait DescentGuard: Sized {
type InitArg: Default + Send + Sync;
fn init(arg: &Self::InitArg) -> Self;
fn try_enter(&mut self) -> Result<Option<DescentWarning>, DescentRefusal>;
fn exit(&mut self);
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DescentRefusal {
pub detail: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DescentWarning {
pub detail: String,
}
#[derive(Debug, Clone, Copy)]
pub struct StdDescentGuardInit {
mode: InitMode,
unconfigured: bool,
}
#[derive(Debug, Clone, Copy)]
enum InitMode {
FixedStackBudget { bytes: usize },
ComputedStackBudget { probe: fn() -> Option<usize> },
DepthLimit { levels: usize },
Off,
}
impl StdDescentGuardInit {
pub fn fixed_stack_budget(bytes: usize) -> StdDescentGuardInit {
StdDescentGuardInit {
mode: InitMode::FixedStackBudget { bytes },
unconfigured: false,
}
}
pub fn computed_stack_budget(probe: fn() -> Option<usize>) -> StdDescentGuardInit {
StdDescentGuardInit {
mode: InitMode::ComputedStackBudget { probe },
unconfigured: false,
}
}
pub fn depth_limit(levels: usize) -> StdDescentGuardInit {
StdDescentGuardInit { mode: InitMode::DepthLimit { levels }, unconfigured: false }
}
pub fn off() -> StdDescentGuardInit {
StdDescentGuardInit { mode: InitMode::Off, unconfigured: false }
}
}
impl Default for StdDescentGuardInit {
fn default() -> StdDescentGuardInit {
StdDescentGuardInit {
mode: InitMode::FixedStackBudget { bytes: StdDescentGuard::DEFAULT_STACK_BUDGET },
unconfigured: true,
}
}
}
#[derive(Debug)]
pub struct StdDescentGuard {
mode: GuardMode,
unconfigured: bool,
warned: bool,
}
#[derive(Debug)]
enum GuardMode {
Measured { anchor: usize, budget: usize },
Depth { limit: usize, current: usize },
Off,
}
impl StdDescentGuard {
pub const DEFAULT_STACK_BUDGET: usize = 250 * 1024;
pub const HEADROOM: usize = 64 * 1024;
}
#[inline(never)]
fn stack_position() -> usize {
let marker = 0u8;
core::hint::black_box(&marker as *const u8 as usize)
}
impl DescentGuard for StdDescentGuard {
type InitArg = StdDescentGuardInit;
fn init(arg: &StdDescentGuardInit) -> StdDescentGuard {
let mode = match arg.mode {
InitMode::FixedStackBudget { bytes } => {
GuardMode::Measured { anchor: stack_position(), budget: bytes }
}
InitMode::ComputedStackBudget { probe } => {
let budget = match probe() {
Some(remaining) => remaining.saturating_sub(StdDescentGuard::HEADROOM),
None => StdDescentGuard::DEFAULT_STACK_BUDGET,
};
GuardMode::Measured { anchor: stack_position(), budget }
}
InitMode::DepthLimit { levels } => GuardMode::Depth { limit: levels, current: 0 },
InitMode::Off => GuardMode::Off,
};
StdDescentGuard { mode, unconfigured: arg.unconfigured, warned: false }
}
fn try_enter(&mut self) -> Result<Option<DescentWarning>, DescentRefusal> {
match &mut self.mode {
GuardMode::Off => Ok(None),
GuardMode::Depth { limit, current } => {
if *current >= *limit {
return Err(DescentRefusal {
detail: format!(
"the run is {} descent levels deep, the configured \
depth limit (StdDescentGuardInit::depth_limit)",
limit
),
});
}
*current += 1;
Ok(None)
}
GuardMode::Measured { anchor, budget } => {
let consumed = anchor.abs_diff(stack_position());
if consumed > *budget {
let detail = if self.unconfigured {
format!(
"the run's estimated stack use ({} bytes) exceeds the \
built-in default budget of {} bytes \
(StdDescentGuard::DEFAULT_STACK_BUDGET); no descent-guard \
configuration was given — choose a limit explicitly with \
with_descent_guard_init (on Language, TreeWalker, \
TreeRestager, TreeRecomposer, or SerdeSession)",
consumed,
StdDescentGuard::DEFAULT_STACK_BUDGET
)
} else {
format!(
"the run's estimated stack use ({} bytes) exceeds the \
configured budget of {} bytes",
consumed, budget
)
};
return Err(DescentRefusal { detail });
}
if self.unconfigured && !self.warned && consumed > *budget / 2 {
self.warned = true;
return Ok(Some(DescentWarning {
detail: format!(
"the run's estimated stack use ({} bytes) has passed half \
of the built-in default budget of {} bytes \
(StdDescentGuard::DEFAULT_STACK_BUDGET); no descent-guard \
configuration was given — deeper input will be refused; \
choose a limit explicitly with with_descent_guard_init \
(on Language, TreeWalker, TreeRestager, \
TreeRecomposer, or SerdeSession)",
consumed,
StdDescentGuard::DEFAULT_STACK_BUDGET
),
}));
}
Ok(None)
}
}
}
fn exit(&mut self) {
if let GuardMode::Depth { current, .. } = &mut self.mode {
*current = current.saturating_sub(1);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const PAD: usize = 8 * 1024;
fn descend(
guard: &mut StdDescentGuard,
levels: usize,
granted: &mut usize,
warnings: &mut usize,
) -> Result<(), DescentRefusal> {
let pad = [0u8; PAD];
core::hint::black_box(&pad);
match guard.try_enter() {
Ok(Some(_)) => *warnings += 1,
Ok(None) => {}
Err(refusal) => return Err(refusal),
}
*granted += 1;
let result = if levels > 1 {
descend(guard, levels - 1, granted, warnings)
} else {
Ok(())
};
guard.exit();
result
}
#[test]
fn the_unconfigured_default_warns_once_at_half_budget_then_refuses() {
let mut guard = StdDescentGuard::init(&StdDescentGuardInit::default());
let (mut granted, mut warnings) = (0, 0);
let refusal = descend(&mut guard, 200, &mut granted, &mut warnings).unwrap_err();
assert_eq!(warnings, 1, "the half-budget warning latches once");
assert!(granted < 200);
assert!(refusal.detail.contains("DEFAULT_STACK_BUDGET"));
assert!(refusal.detail.contains("with_descent_guard_init"));
}
#[test]
fn a_configured_fixed_budget_never_warns_and_names_its_budget() {
let mut guard = StdDescentGuard::init(&StdDescentGuardInit::fixed_stack_budget(
StdDescentGuard::DEFAULT_STACK_BUDGET,
));
let (mut granted, mut warnings) = (0, 0);
let refusal = descend(&mut guard, 200, &mut granted, &mut warnings).unwrap_err();
assert_eq!(warnings, 0, "the warning fires only under the unconfigured default");
assert!(refusal.detail.contains("configured budget"));
assert!(!refusal.detail.contains("with_descent_guard_init"));
}
#[test]
fn a_computed_budget_subtracts_the_headroom_from_the_probe_answer() {
fn probe() -> Option<usize> {
Some(StdDescentGuard::HEADROOM + 1000)
}
let mut guard = StdDescentGuard::init(&StdDescentGuardInit::computed_stack_budget(probe));
let (mut granted, mut warnings) = (0, 0);
let refusal = descend(&mut guard, 10, &mut granted, &mut warnings).unwrap_err();
assert!(
refusal.detail.contains("configured budget of 1000 bytes"),
"refusal names the headroom-subtracted budget: {}",
refusal.detail
);
assert_eq!(warnings, 0);
}
#[test]
fn a_computed_budget_saturates_at_zero_and_falls_back_on_none() {
fn tiny() -> Option<usize> {
Some(StdDescentGuard::HEADROOM - 1)
}
let mut guard = StdDescentGuard::init(&StdDescentGuardInit::computed_stack_budget(tiny));
let (mut granted, mut warnings) = (0, 0);
let refusal = descend(&mut guard, 2, &mut granted, &mut warnings).unwrap_err();
assert!(refusal.detail.contains("configured budget of 0 bytes"));
assert_eq!(granted, 0);
fn unknown() -> Option<usize> {
None
}
let mut guard =
StdDescentGuard::init(&StdDescentGuardInit::computed_stack_budget(unknown));
let (mut granted, mut warnings) = (0, 0);
let refusal = descend(&mut guard, 200, &mut granted, &mut warnings).unwrap_err();
assert!(refusal.detail.contains(&format!(
"configured budget of {} bytes",
StdDescentGuard::DEFAULT_STACK_BUDGET
)));
assert_eq!(warnings, 0);
}
#[test]
fn depth_limit_counts_open_levels_and_exit_rebalances() {
let mut guard = StdDescentGuard::init(&StdDescentGuardInit::depth_limit(3));
let (mut granted, mut warnings) = (0, 0);
assert!(descend(&mut guard, 3, &mut granted, &mut warnings).is_ok());
assert_eq!(granted, 3);
let refusal = descend(&mut guard, 4, &mut granted, &mut warnings).unwrap_err();
assert!(refusal.detail.contains("3 descent levels deep"));
assert!(refusal.detail.contains("depth_limit"));
let (mut granted, mut warnings) = (0, 0);
assert!(descend(&mut guard, 3, &mut granted, &mut warnings).is_ok());
assert_eq!(warnings, 0);
}
#[test]
fn off_grants_everything() {
let mut guard = StdDescentGuard::init(&StdDescentGuardInit::off());
let (mut granted, mut warnings) = (0, 0);
assert!(descend(&mut guard, 64, &mut granted, &mut warnings).is_ok());
assert_eq!((granted, warnings), (64, 0));
}
}