1use std::fmt;
4
5#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
7pub struct Pos {
8 pub line: u32,
10 pub col: u32,
12}
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
16#[non_exhaustive]
17pub enum Severity {
18 Error,
20 Warning,
22}
23
24#[derive(Clone, Debug, PartialEq, Eq)]
26pub struct Diagnostic {
27 pub severity: Severity,
29 pub chunk: String,
31 pub pos: Pos,
33 pub end: Pos,
36 pub line: u32,
39 pub message: String,
41 raw: Option<Box<[u8]>>,
44}
45
46impl Diagnostic {
47 pub(crate) fn error(chunk: &str, pos: Pos, msg: impl Into<String>) -> Self {
48 Diagnostic { severity: Severity::Error, chunk: chunk.to_owned(), pos, end: pos, line: pos.line, message: msg.into(), raw: None }
49 }
50
51 pub(crate) fn warning(chunk: &str, pos: Pos, msg: impl Into<String>) -> Self {
52 Diagnostic { severity: Severity::Warning, chunk: chunk.to_owned(), pos, end: pos, line: pos.line, message: msg.into(), raw: None }
53 }
54
55 pub(crate) fn error_bytes(chunk: &str, pos: Pos, raw: Vec<u8>) -> Self {
57 let mut d = Diagnostic::error(chunk, pos, String::from_utf8_lossy(&raw).into_owned());
58 if std::str::from_utf8(&raw).is_err() {
59 d.raw = Some(raw.into_boxed_slice());
60 }
61 d
62 }
63
64 pub(crate) fn to(mut self, end: Pos) -> Self {
66 self.end = end.max(self.pos);
67 self
68 }
69
70 pub(crate) fn lua_line(mut self, line: u32) -> Self {
72 self.line = line;
73 self
74 }
75
76 pub fn lua_message(&self) -> String {
78 format!("{}:{}: {}", self.chunk, self.line, self.message)
79 }
80
81 pub(crate) fn lua_message_bytes(&self) -> Vec<u8> {
83 match &self.raw {
84 None => self.lua_message().into_bytes(),
85 Some(raw) => {
86 let mut b = format!("{}:{}: ", self.chunk, self.line).into_bytes();
87 b.extend_from_slice(raw);
88 b
89 }
90 }
91 }
92}
93
94impl fmt::Display for Diagnostic {
95 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96 let sev = match self.severity {
97 Severity::Error => "",
98 Severity::Warning => "warning: ",
99 };
100 write!(f, "{}:{}:{}: {sev}{}", self.chunk, self.pos.line, self.pos.col, self.message)
101 }
102}
103
104impl std::error::Error for Diagnostic {}
105
106pub(crate) const COMPILE_WATCH_EVERY: u32 = 1024;
112
113const COMPILE_WORK_PER_TICK: u64 = 16;
117
118pub(crate) const COMPILE_STOPPED: &str = "compile stopped by the host";
120
121thread_local! {
122 static COMPILE_WATCH: std::cell::RefCell<Option<(crate::stdlib::pattern::Watch, Option<crate::LimitKind>)>> =
125 const { std::cell::RefCell::new(None) };
126 static COMPILE_TICKS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
127 static COMPILE_WORK: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, u64::MAX)) };
129 static COMPILE_STOP: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
131 static PARSE_READING: std::cell::Cell<(usize, Option<usize>)> = const { std::cell::Cell::new((0, None)) };
134}
135
136pub(crate) fn parse_reading(set: (Option<usize>, Option<usize>)) -> (usize, Option<usize>) {
141 PARSE_READING.with(|c| {
142 let (held, room) = c.get();
143 c.set((set.0.unwrap_or(held), set.1));
144 (held, room)
145 })
146}
147
148pub(crate) trait Piecewise: Send {
150 fn free_some(&mut self, n: usize) -> bool;
152 fn bytes(&self) -> usize;
154}
155
156impl<T: Send> Piecewise for Vec<T> {
157 fn bytes(&self) -> usize {
158 self.capacity().saturating_mul(std::mem::size_of::<T>())
159 }
160
161 fn free_some(&mut self, n: usize) -> bool {
162 self.truncate(self.len().saturating_sub(n));
163 crate::ast::shed(self);
164 if self.is_empty() {
165 *self = Vec::new();
166 }
167 self.is_empty()
168 }
169}
170
171impl Piecewise for crate::ast::Dropper {
172 fn free_some(&mut self, n: usize) -> bool {
173 self.step(n)
174 }
175 fn bytes(&self) -> usize {
176 self.bytes()
177 }
178}
179
180const GROW_WATCHED: usize = 1 << 20;
184
185const GROW_STRETCH: usize = 1 << 15;
187
188pub(crate) fn grow_watched<T: Send + 'static>(v: &mut Vec<T>, cap: usize) -> bool {
193 if cap <= v.capacity() {
194 return false;
195 }
196 if cap.saturating_mul(std::mem::size_of::<T>()) < GROW_WATCHED || !watching() {
199 v.reserve_exact(cap - v.len());
200 return false;
201 }
202 let mut new = Vec::with_capacity(cap);
203 let mut old = std::mem::take(v);
204 let n = old.len();
209 let stopped = 'grow: {
210 let mut i = 0;
211 while i < n / 2 {
212 let end = (i + GROW_STRETCH).min(n / 2);
213 for k in i..end {
214 old.swap(k, n - 1 - k);
215 }
216 i = end;
217 if compile_ticks(COMPILE_WATCH_EVERY) {
218 break 'grow true;
219 }
220 }
221 while !old.is_empty() {
222 new.extend(std::iter::from_fn(|| old.pop()).take(GROW_STRETCH));
223 crate::ast::shed(&mut old);
224 if compile_ticks(COMPILE_WATCH_EVERY) {
225 break 'grow true;
226 }
227 }
228 false
229 };
230 if stopped {
231 defer_pieces(new);
232 defer_pieces(old);
233 return true;
234 }
235 *v = new;
236 false
237}
238
239fn watching() -> bool {
241 COMPILE_WATCH.with(|w| w.borrow().is_some())
242}
243
244pub(crate) trait KeyHeap {
246 fn heap(&self) -> usize {
247 0
248 }
249}
250
251impl KeyHeap for Vec<u8> {
252 fn heap(&self) -> usize {
253 self.capacity()
254 }
255}
256
257impl KeyHeap for String {
258 fn heap(&self) -> usize {
259 self.capacity()
260 }
261}
262
263impl KeyHeap for std::sync::Arc<str> {
264 fn heap(&self) -> usize {
266 if std::sync::Arc::strong_count(self) == 1 { self.len() + 16 } else { 0 }
267 }
268}
269
270pub(crate) fn table_bytes<K, V>(cap: usize) -> usize {
274 if cap == 0 {
275 return 0;
276 }
277 let buckets = if cap < 8 { (cap + 1).next_power_of_two() } else { (cap * 8 / 7).next_power_of_two() };
278 let entries = (buckets * std::mem::size_of::<(K, V)>()).next_multiple_of(16);
279 entries + buckets + 16
280}
281
282impl<K: KeyHeap + Send, V: Send> Piecewise for crate::shardmap::ShardPieces<K, V> {
283 fn free_some(&mut self, n: usize) -> bool {
284 crate::shardmap::ShardPieces::free_some(self, n)
285 }
286 fn bytes(&self) -> usize {
288 self.held()
289 }
290}
291
292struct Whole(Option<Box<dyn std::any::Any + Send>>, usize);
294
295impl Piecewise for Whole {
296 fn free_some(&mut self, _: usize) -> bool {
297 self.0 = None;
298 true
299 }
300 fn bytes(&self) -> usize {
301 self.1
302 }
303}
304
305thread_local! {
306 static DEFERRED: std::cell::RefCell<Deferred> = const { std::cell::RefCell::new(Vec::new()) };
311}
312
313pub(crate) type Deferred = Vec<(Box<dyn Piecewise>, usize)>;
315
316const FREE_PIECES: usize = 1024;
318
319pub(crate) fn defer_drop<T: Send + 'static>(v: T) {
321 defer_pieces(Whole(Some(Box::new(v)), std::mem::size_of::<T>()));
322}
323
324pub(crate) fn defer_pieces<T: Piecewise + 'static>(v: T) {
326 let bytes = v.bytes();
327 DEFERRED.with(|d| d.borrow_mut().push((Box::new(v), bytes)));
328}
329
330pub(crate) fn take_deferred() -> Deferred {
333 DEFERRED.with(|d| std::mem::take(&mut *d.borrow_mut()))
334}
335
336thread_local! {
337 static DEFERRING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
340}
341
342pub(crate) fn set_deferring(on: bool) -> bool {
344 DEFERRING.with(|d| d.replace(on))
345}
346
347pub(crate) fn release<T: Piecewise + 'static>(v: T) {
349 if DEFERRING.with(std::cell::Cell::get) {
350 defer_pieces(v);
351 } else {
352 free_watched(v);
355 }
356}
357
358pub(crate) fn defer_tree(b: crate::ast::Block, bytes: usize) {
360 defer_pieces(crate::ast::Dropper::of_block(b).with_bytes(bytes));
361}
362
363pub(crate) fn free_deferred(list: &mut Deferred, stop: impl Fn() -> bool) -> usize {
366 let mut released = 0usize;
367 while let Some((mut v, mut bytes)) = list.pop() {
368 while !v.free_some(FREE_PIECES) {
369 let now = v.bytes().min(bytes);
371 released = released.saturating_add(bytes - now);
372 bytes = now;
373 settle_frees();
374 if stop() {
375 list.push((v, bytes));
376 return released;
377 }
378 }
379 drop(v);
380 released = released.saturating_add(bytes);
381 settle_frees();
382 if stop() {
383 return released;
384 }
385 }
386 released
387}
388
389pub(crate) fn free_watched<T: Piecewise + 'static>(mut v: T) {
392 while !v.free_some(FREE_PIECES * 4) {
393 settle_frees();
394 if compile_ticks(COMPILE_WATCH_EVERY) {
395 defer_pieces(v);
396 return;
397 }
398 }
399}
400
401fn settle_frees() {
407 drop(std::hint::black_box(Vec::<u8>::with_capacity(4096)));
408}
409
410pub(crate) fn watched<T>(
413 watch: crate::stdlib::pattern::Watch,
414 max_work: u64,
415 f: impl FnOnce() -> T,
416) -> (T, Option<crate::LimitKind>, u64) {
417 let outer = COMPILE_WATCH.with(|w| w.replace(Some((watch, None))));
418 let outer_work = COMPILE_WORK.with(|w| w.replace((0, max_work)));
419 let outer_stop = COMPILE_STOP.with(|s| s.replace(false));
420 let r = f();
421 COMPILE_STOP.with(|s| s.set(outer_stop));
422 let (work, _) = COMPILE_WORK.with(|w| w.replace(outer_work));
423 let stop = COMPILE_WATCH.with(|w| w.replace(outer)).and_then(|(_, k)| k);
424 (r, stop, work)
425}
426
427#[inline]
435pub(crate) fn compile_work(n: usize) {
436 let steps = COMPILE_WORK.with(|w| {
437 let (before, max) = w.get();
438 let done = before.saturating_add(n as u64);
439 w.set((done, max));
440 if done > max {
441 COMPILE_STOP.with(|s| s.set(true));
442 COMPILE_WATCH.with(|c| {
443 if let Some((_, stop)) = c.borrow_mut().as_mut() {
444 stop.get_or_insert(crate::LimitKind::Fuel);
445 }
446 });
447 }
448 done / COMPILE_WORK_PER_TICK - before / COMPILE_WORK_PER_TICK
449 });
450 if steps > 0 {
451 compile_ticks(u32::try_from(steps).unwrap_or(u32::MAX));
453 }
454}
455
456#[inline]
458pub(crate) fn compile_stopped() -> bool {
459 COMPILE_STOP.with(std::cell::Cell::get)
460}
461
462#[inline]
465pub(crate) fn compile_tick() -> bool {
466 compile_ticks(1)
467}
468
469#[inline]
472pub(crate) fn compile_ticks(n: u32) -> bool {
473 let (before, t) = COMPILE_TICKS.with(|c| {
474 let before = c.get();
475 let t = before.wrapping_add(n.max(1));
476 c.set(t);
477 (before, t)
478 });
479 if t / COMPILE_WATCH_EVERY == before / COMPILE_WATCH_EVERY {
480 return COMPILE_STOP.with(std::cell::Cell::get);
482 }
483 let stop = COMPILE_WATCH.with(|w| {
484 let mut w = w.borrow_mut();
485 let Some((watch, stop)) = w.as_mut() else { return false };
486 if stop.is_none() {
487 *stop = watch.stop();
488 }
489 stop.is_some()
490 });
491 if stop {
492 COMPILE_STOP.with(|s| s.set(true));
493 }
494 stop
495}