use std::fmt;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Pos {
pub line: u32,
pub col: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Severity {
Error,
Warning,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Diagnostic {
pub severity: Severity,
pub chunk: String,
pub pos: Pos,
pub end: Pos,
pub line: u32,
pub message: String,
raw: Option<Box<[u8]>>,
}
impl Diagnostic {
pub(crate) fn error(chunk: &str, pos: Pos, msg: impl Into<String>) -> Self {
Diagnostic { severity: Severity::Error, chunk: chunk.to_owned(), pos, end: pos, line: pos.line, message: msg.into(), raw: None }
}
pub(crate) fn warning(chunk: &str, pos: Pos, msg: impl Into<String>) -> Self {
Diagnostic { severity: Severity::Warning, chunk: chunk.to_owned(), pos, end: pos, line: pos.line, message: msg.into(), raw: None }
}
pub(crate) fn error_bytes(chunk: &str, pos: Pos, raw: Vec<u8>) -> Self {
let mut d = Diagnostic::error(chunk, pos, String::from_utf8_lossy(&raw).into_owned());
if std::str::from_utf8(&raw).is_err() {
d.raw = Some(raw.into_boxed_slice());
}
d
}
pub(crate) fn to(mut self, end: Pos) -> Self {
self.end = end.max(self.pos);
self
}
pub(crate) fn lua_line(mut self, line: u32) -> Self {
self.line = line;
self
}
pub fn lua_message(&self) -> String {
format!("{}:{}: {}", self.chunk, self.line, self.message)
}
pub(crate) fn lua_message_bytes(&self) -> Vec<u8> {
match &self.raw {
None => self.lua_message().into_bytes(),
Some(raw) => {
let mut b = format!("{}:{}: ", self.chunk, self.line).into_bytes();
b.extend_from_slice(raw);
b
}
}
}
}
impl fmt::Display for Diagnostic {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let sev = match self.severity {
Severity::Error => "",
Severity::Warning => "warning: ",
};
write!(f, "{}:{}:{}: {sev}{}", self.chunk, self.pos.line, self.pos.col, self.message)
}
}
impl std::error::Error for Diagnostic {}
pub(crate) const COMPILE_WATCH_EVERY: u32 = 1024;
const COMPILE_WORK_PER_TICK: u64 = 16;
pub(crate) const COMPILE_STOPPED: &str = "compile stopped by the host";
thread_local! {
static COMPILE_WATCH: std::cell::RefCell<Option<(crate::stdlib::pattern::Watch, Option<crate::LimitKind>)>> =
const { std::cell::RefCell::new(None) };
static COMPILE_TICKS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
static COMPILE_WORK: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, u64::MAX)) };
static COMPILE_STOP: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
static PARSE_READING: std::cell::Cell<(usize, Option<usize>)> = const { std::cell::Cell::new((0, None)) };
}
pub(crate) fn parse_reading(set: (Option<usize>, Option<usize>)) -> (usize, Option<usize>) {
PARSE_READING.with(|c| {
let (held, room) = c.get();
c.set((set.0.unwrap_or(held), set.1));
(held, room)
})
}
pub(crate) trait Piecewise: Send {
fn free_some(&mut self, n: usize) -> bool;
fn bytes(&self) -> usize;
}
impl<T: Send> Piecewise for Vec<T> {
fn bytes(&self) -> usize {
self.capacity().saturating_mul(std::mem::size_of::<T>())
}
fn free_some(&mut self, n: usize) -> bool {
self.truncate(self.len().saturating_sub(n));
crate::ast::shed(self);
if self.is_empty() {
*self = Vec::new();
}
self.is_empty()
}
}
impl Piecewise for crate::ast::Dropper {
fn free_some(&mut self, n: usize) -> bool {
self.step(n)
}
fn bytes(&self) -> usize {
self.bytes()
}
}
const GROW_WATCHED: usize = 1 << 20;
const GROW_STRETCH: usize = 1 << 15;
pub(crate) fn grow_watched<T: Send + 'static>(v: &mut Vec<T>, cap: usize) -> bool {
if cap <= v.capacity() {
return false;
}
if cap.saturating_mul(std::mem::size_of::<T>()) < GROW_WATCHED || !watching() {
v.reserve_exact(cap - v.len());
return false;
}
let mut new = Vec::with_capacity(cap);
let mut old = std::mem::take(v);
let n = old.len();
let stopped = 'grow: {
let mut i = 0;
while i < n / 2 {
let end = (i + GROW_STRETCH).min(n / 2);
for k in i..end {
old.swap(k, n - 1 - k);
}
i = end;
if compile_ticks(COMPILE_WATCH_EVERY) {
break 'grow true;
}
}
while !old.is_empty() {
new.extend(std::iter::from_fn(|| old.pop()).take(GROW_STRETCH));
crate::ast::shed(&mut old);
if compile_ticks(COMPILE_WATCH_EVERY) {
break 'grow true;
}
}
false
};
if stopped {
defer_pieces(new);
defer_pieces(old);
return true;
}
*v = new;
false
}
fn watching() -> bool {
COMPILE_WATCH.with(|w| w.borrow().is_some())
}
pub(crate) trait KeyHeap {
fn heap(&self) -> usize {
0
}
}
impl KeyHeap for Vec<u8> {
fn heap(&self) -> usize {
self.capacity()
}
}
impl KeyHeap for String {
fn heap(&self) -> usize {
self.capacity()
}
}
impl KeyHeap for std::sync::Arc<str> {
fn heap(&self) -> usize {
if std::sync::Arc::strong_count(self) == 1 { self.len() + 16 } else { 0 }
}
}
pub(crate) fn table_bytes<K, V>(cap: usize) -> usize {
if cap == 0 {
return 0;
}
let buckets = if cap < 8 { (cap + 1).next_power_of_two() } else { (cap * 8 / 7).next_power_of_two() };
let entries = (buckets * std::mem::size_of::<(K, V)>()).next_multiple_of(16);
entries + buckets + 16
}
impl<K: KeyHeap + Send, V: Send> Piecewise for crate::shardmap::ShardPieces<K, V> {
fn free_some(&mut self, n: usize) -> bool {
crate::shardmap::ShardPieces::free_some(self, n)
}
fn bytes(&self) -> usize {
self.held()
}
}
struct Whole(Option<Box<dyn std::any::Any + Send>>, usize);
impl Piecewise for Whole {
fn free_some(&mut self, _: usize) -> bool {
self.0 = None;
true
}
fn bytes(&self) -> usize {
self.1
}
}
thread_local! {
static DEFERRED: std::cell::RefCell<Deferred> = const { std::cell::RefCell::new(Vec::new()) };
}
pub(crate) type Deferred = Vec<(Box<dyn Piecewise>, usize)>;
const FREE_PIECES: usize = 1024;
pub(crate) fn defer_drop<T: Send + 'static>(v: T) {
defer_pieces(Whole(Some(Box::new(v)), std::mem::size_of::<T>()));
}
pub(crate) fn defer_pieces<T: Piecewise + 'static>(v: T) {
let bytes = v.bytes();
DEFERRED.with(|d| d.borrow_mut().push((Box::new(v), bytes)));
}
pub(crate) fn take_deferred() -> Deferred {
DEFERRED.with(|d| std::mem::take(&mut *d.borrow_mut()))
}
thread_local! {
static DEFERRING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub(crate) fn set_deferring(on: bool) -> bool {
DEFERRING.with(|d| d.replace(on))
}
pub(crate) fn release<T: Piecewise + 'static>(v: T) {
if DEFERRING.with(std::cell::Cell::get) {
defer_pieces(v);
} else {
free_watched(v);
}
}
pub(crate) fn defer_tree(b: crate::ast::Block, bytes: usize) {
defer_pieces(crate::ast::Dropper::of_block(b).with_bytes(bytes));
}
pub(crate) fn free_deferred(list: &mut Deferred, stop: impl Fn() -> bool) -> usize {
let mut released = 0usize;
while let Some((mut v, mut bytes)) = list.pop() {
while !v.free_some(FREE_PIECES) {
let now = v.bytes().min(bytes);
released = released.saturating_add(bytes - now);
bytes = now;
settle_frees();
if stop() {
list.push((v, bytes));
return released;
}
}
drop(v);
released = released.saturating_add(bytes);
settle_frees();
if stop() {
return released;
}
}
released
}
pub(crate) fn free_watched<T: Piecewise + 'static>(mut v: T) {
while !v.free_some(FREE_PIECES * 4) {
settle_frees();
if compile_ticks(COMPILE_WATCH_EVERY) {
defer_pieces(v);
return;
}
}
}
fn settle_frees() {
drop(std::hint::black_box(Vec::<u8>::with_capacity(4096)));
}
pub(crate) fn watched<T>(
watch: crate::stdlib::pattern::Watch,
max_work: u64,
f: impl FnOnce() -> T,
) -> (T, Option<crate::LimitKind>, u64) {
let outer = COMPILE_WATCH.with(|w| w.replace(Some((watch, None))));
let outer_work = COMPILE_WORK.with(|w| w.replace((0, max_work)));
let outer_stop = COMPILE_STOP.with(|s| s.replace(false));
let r = f();
COMPILE_STOP.with(|s| s.set(outer_stop));
let (work, _) = COMPILE_WORK.with(|w| w.replace(outer_work));
let stop = COMPILE_WATCH.with(|w| w.replace(outer)).and_then(|(_, k)| k);
(r, stop, work)
}
#[inline]
pub(crate) fn compile_work(n: usize) {
let steps = COMPILE_WORK.with(|w| {
let (before, max) = w.get();
let done = before.saturating_add(n as u64);
w.set((done, max));
if done > max {
COMPILE_STOP.with(|s| s.set(true));
COMPILE_WATCH.with(|c| {
if let Some((_, stop)) = c.borrow_mut().as_mut() {
stop.get_or_insert(crate::LimitKind::Fuel);
}
});
}
done / COMPILE_WORK_PER_TICK - before / COMPILE_WORK_PER_TICK
});
if steps > 0 {
compile_ticks(u32::try_from(steps).unwrap_or(u32::MAX));
}
}
#[inline]
pub(crate) fn compile_stopped() -> bool {
COMPILE_STOP.with(std::cell::Cell::get)
}
#[inline]
pub(crate) fn compile_tick() -> bool {
compile_ticks(1)
}
#[inline]
pub(crate) fn compile_ticks(n: u32) -> bool {
let (before, t) = COMPILE_TICKS.with(|c| {
let before = c.get();
let t = before.wrapping_add(n.max(1));
c.set(t);
(before, t)
});
if t / COMPILE_WATCH_EVERY == before / COMPILE_WATCH_EVERY {
return COMPILE_STOP.with(std::cell::Cell::get);
}
let stop = COMPILE_WATCH.with(|w| {
let mut w = w.borrow_mut();
let Some((watch, stop)) = w.as_mut() else { return false };
if stop.is_none() {
*stop = watch.stop();
}
stop.is_some()
});
if stop {
COMPILE_STOP.with(|s| s.set(true));
}
stop
}