use std::cell::{Cell, RefCell};
const MARGIN: usize = 128 * 1024;
#[derive(Clone, Copy)]
struct Bounds {
base: usize,
top: usize,
soft: usize,
}
impl Bounds {
fn new(base: usize, top: usize) -> Bounds {
Bounds {
base,
top,
soft: base + 2 * MARGIN,
}
}
fn holds(&self, sp: usize) -> bool {
(self.base..self.top).contains(&sp)
}
}
thread_local! {
static BOUNDS: Cell<Option<Bounds>> = const { Cell::new(None) };
static WATERMARK: Cell<usize> = const { Cell::new(usize::MAX) };
static PENDING: RefCell<Option<String>> = const { RefCell::new(None) };
}
#[inline(always)]
fn stack_pointer() -> usize {
let marker = 0u8;
std::hint::black_box(&marker) as *const u8 as usize
}
#[cfg(target_os = "macos")]
fn thread_stack() -> Option<(usize, usize)> {
unsafe {
let this = libc::pthread_self();
let top = libc::pthread_get_stackaddr_np(this) as usize;
let size = libc::pthread_get_stacksize_np(this);
Some((top - size, top))
}
}
#[cfg(all(unix, not(target_os = "macos")))]
fn thread_stack() -> Option<(usize, usize)> {
unsafe {
let mut attr: libc::pthread_attr_t = std::mem::zeroed();
if libc::pthread_getattr_np(libc::pthread_self(), &mut attr) != 0 {
return None;
}
let mut addr: *mut libc::c_void = std::ptr::null_mut();
let mut size: libc::size_t = 0;
let mut guard: libc::size_t = 0;
let err = libc::pthread_attr_getstack(&attr, &mut addr, &mut size)
| libc::pthread_attr_getguardsize(&attr, &mut guard);
libc::pthread_attr_destroy(&mut attr);
(err == 0).then(|| (addr as usize + guard, addr as usize + size))
}
}
#[cfg(not(unix))]
fn thread_stack() -> Option<(usize, usize)> {
None
}
fn set_bounds(b: Option<Bounds>) {
BOUNDS.set(b);
WATERMARK.set(b.map_or(usize::MAX, |b| b.soft + MARGIN));
}
fn roomy(sp: usize) -> bool {
sp > WATERMARK.get()
}
fn bounds(sp: usize) -> Option<Bounds> {
let b = match BOUNDS.get() {
Some(b) => b,
None => {
let (base, top) = thread_stack()?;
let b = Bounds::new(base, top);
set_bounds(Some(b));
b
}
};
b.holds(sp).then_some(b)
}
pub fn with_bounds<R>(base: usize, top: usize, f: impl FnOnce() -> R) -> R {
let outer = BOUNDS.get();
set_bounds(Some(Bounds::new(base, top)));
let r = f();
set_bounds(outer);
r
}
const FRONTEND_STACK: usize = 512 * 1024 * 1024;
const FRONTEND_ROOM: usize = 64 * 1024 * 1024;
pub fn with_frontend_stack<R>(f: impl FnOnce() -> R) -> R {
use corosensei::stack::{DefaultStack, Stack};
let sp = stack_pointer();
if bounds(sp).is_some_and(|b| sp - b.base >= FRONTEND_ROOM) {
return f();
}
let Ok(mut stack) = DefaultStack::new(FRONTEND_STACK) else {
return f();
};
let (base, top) = (stack.limit().get(), stack.base().get());
corosensei::on_stack(&mut stack, || with_bounds(base, top, f))
}
pub fn parser_exhausted() -> bool {
let sp = stack_pointer();
!roomy(sp) && bounds(sp).is_some_and(|b| sp <= b.soft + MARGIN)
}
fn compile_error(b: Bounds, sp: usize) -> String {
format!(
"RecursionError: Stack overflow (used {} kB) during compilation",
(b.top - sp) / 1024
)
}
pub fn enter_compile() -> Result<(), String> {
let sp = stack_pointer();
if roomy(sp) {
return Ok(());
}
match bounds(sp) {
Some(b) if sp < b.soft => Err(compile_error(b, sp)),
_ => Ok(()),
}
}
pub fn compile_overflowed() -> bool {
let sp = stack_pointer();
if roomy(sp) {
return false;
}
match bounds(sp) {
Some(b) if sp < b.soft => {
PENDING.with(|p| {
p.borrow_mut().get_or_insert_with(|| compile_error(b, sp));
});
true
}
_ => false,
}
}
pub fn clear_pending() {
PENDING.with(|p| p.borrow_mut().take());
}
pub fn take_pending() -> Option<String> {
PENDING.with(|p| p.borrow_mut().take())
}