Skip to main content

remedy_lua/
diag.rs

1//! Diagnostics: errors and warnings with where they are (chunk, line, column).
2
3use std::fmt;
4
5/// A place in source text: line and column, both from 1.
6#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
7pub struct Pos {
8    /// The line, from 1.
9    pub line: u32,
10    /// The column (byte in the line), from 1.
11    pub col: u32,
12}
13
14/// How serious a diagnostic is. More levels may come: match with a `_` arm.
15#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
16#[non_exhaustive]
17pub enum Severity {
18    /// The code cannot run (syntax) or will not do what its annotations say (types).
19    Error,
20    /// Probably a mistake.
21    Warning,
22}
23
24/// One message about source text.
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub struct Diagnostic {
27    /// How serious.
28    pub severity: Severity,
29    /// The chunk's name (a file name, usually).
30    pub chunk: String,
31    /// Where the text it is about starts.
32    pub pos: Pos,
33    /// Where that text ends: the line and column just past its last character (`pos` when
34    /// it is about a point, such as the end of input).
35    pub end: Pos,
36    /// The line Lua's own error message gives: where C Lua notices the problem, which can
37    /// lie after `end` (an undefined `goto` is noticed where its function ends).
38    pub line: u32,
39    /// What is wrong, for the person who wrote it.
40    pub message: String,
41    /// The message as bytes when it quotes source that is not UTF-8 (`message` has those
42    /// bytes replaced): what Lua's own message holds, as C Lua prints them (S6-FRONT-7).
43    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    /// An error whose message is `raw` (read as text with invalid UTF-8 replaced).
56    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    /// The same, about the text from `pos` to `end`.
65    pub(crate) fn to(mut self, end: Pos) -> Self {
66        self.end = end.max(self.pos);
67        self
68    }
69
70    /// The same, with Lua's message giving `line`.
71    pub(crate) fn lua_line(mut self, line: u32) -> Self {
72        self.line = line;
73        self
74    }
75
76    /// As Lua's own error message reads: `chunk:line: message`.
77    pub fn lua_message(&self) -> String {
78        format!("{}:{}: {}", self.chunk, self.line, self.message)
79    }
80
81    /// Lua's own error message as the bytes C Lua's holds: source it quotes as written.
82    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
106// ---- the host's interrupt and deadline while compiling ----
107
108/// Lexer, parser and compiler steps between looks at the watch.
109/// (A compiler step can take a microsecond, a local made or a constant found: 4,096
110/// steps were 3 to 4 ms between looks; at 1,024, one atomic load per 1,024 steps.)
111pub(crate) const COMPILE_WATCH_EVERY: u32 = 1024;
112
113/// Units of scan work (`compile_work`) that count as one step between looks at the watch.
114/// One step can scan thousands of locals, labels or gotos: counted as one, 4,096 of them
115/// kept the interrupt and deadline unread for over 100 ms (S5C-FRONT-2).
116const COMPILE_WORK_PER_TICK: u64 = 16;
117
118/// The message of the error a stopped compile unwinds with (turned into the limit).
119pub(crate) const COMPILE_STOPPED: &str = "compile stopped by the host";
120
121thread_local! {
122    /// The running compile's watch (the state's interrupt and deadline), steps since the
123    /// last look, and the limit that stopped it.
124    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    /// The running compile's scan work (`compile_work`) and the most it may do.
128    static COMPILE_WORK: std::cell::Cell<(u64, u64)> = const { std::cell::Cell::new((0, u64::MAX)) };
129    /// Whether the running compile must stop (its watch or its scan work said so).
130    static COMPILE_STOP: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
131    /// What the parse reading from `load`'s reader holds as it asks for more, and the room
132    /// it has after the reader ran (`parse_reading`).
133    static PARSE_READING: std::cell::Cell<(usize, Option<usize>)> = const { std::cell::Cell::new((0, None)) };
134}
135
136/// Exchanged around `load`'s reader: the parser sets what it holds before it reads on,
137/// `load` counts that as used while the reader runs and sets the room left after it
138/// (SEC-M13: the tree was in no account while the reader ran, so the reader's allocations
139/// and an inner `load`'s room came on top of it).
140pub(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
148/// What can be freed a piece at a time (`free_deferred`).
149pub(crate) trait Piecewise: Send {
150    /// Frees up to `n` pieces: whether all of it is freed.
151    fn free_some(&mut self, n: usize) -> bool;
152    /// About the bytes it holds (charged to the state's memory while it waits).
153    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
180/// Bytes past which a vector of the front end grows by `grow_watched`.
181/// (1 MB: page faults on fresh memory cost about 0.45 ms per MB, so growing a 16 MB list
182/// in one `realloc` took 10 to 25 ms.)
183const GROW_WATCHED: usize = 1 << 20;
184
185/// Elements moved between steps while a big vector grows.
186const GROW_STRETCH: usize = 1 << 15;
187
188/// Grows `v` to hold `cap` elements. A big buffer is moved to the new one a stretch at a
189/// time, each a look at the host's interrupt (S6-FRONT-4: growing a 2M-field table
190/// constructor's list, 320 MB, took 190 ms in one `realloc`). Whether the compile was told
191/// to stop meanwhile: then `v` is left empty, and what it held is freed later.
192pub(crate) fn grow_watched<T: Send + 'static>(v: &mut Vec<T>, cap: usize) -> bool {
193    if cap <= v.capacity() {
194        return false;
195    }
196    // (With nothing to watch, as for `check` and `format`, at once: `realloc` can often
197    // move a big buffer without copying it.)
198    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    // Reversed in place, then moved from its end, so the old buffer is given back a
205    // stretch at a time as it empties (`shed`): freeing it whole once moved (tens of
206    // megabytes) was 5 to 10 ms of its own. (A stop leaves it in any order: it is only
207    // freed then.)
208    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
239/// Whether a compile with a watch (the host's interrupt) is running on this thread.
240fn watching() -> bool {
241    COMPILE_WATCH.with(|w| w.borrow().is_some())
242}
243
244/// What a map key holds on the heap besides its slot (for `ShardMap::into_pieces`).
245pub(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    /// Its bytes and counts when this is the last reference (else another owner keeps them).
265    fn heap(&self) -> usize {
266        if std::sync::Arc::strong_count(self) == 1 { self.len() + 16 } else { 0 }
267    }
268}
269
270/// The bytes the bucket array of a `HashMap` of capacity `cap` takes, as std's (hashbrown)
271/// allocates it: a power-of-two number of buckets (`cap` is 7/8 of them, or one less
272/// than a small one), each an entry and a control byte, and a group of control bytes more.
273pub(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    /// Exactly: the shards' bucket arrays and their keys' own bytes.
287    fn bytes(&self) -> usize {
288        self.held()
289    }
290}
291
292/// Anything else, freed at once (and its size).
293struct 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    /// What a compile from the host left to free (S5C-FRONT-12, S6-FRONT-4): freed at the
307    /// next compile or call from the host instead of before this one returns (freeing a
308    /// multi-megabyte source's tokens and syntax tree took tens of milliseconds, after
309    /// the interrupt or after a successful compile, with no look at the interrupt).
310    static DEFERRED: std::cell::RefCell<Deferred> = const { std::cell::RefCell::new(Vec::new()) };
311}
312
313/// What waits to be freed, each with the bytes charged for it.
314pub(crate) type Deferred = Vec<(Box<dyn Piecewise>, usize)>;
315
316/// Pieces freed between looks at the interrupt (`free_deferred`): well under a millisecond.
317const FREE_PIECES: usize = 1024;
318
319/// Keeps `v` to free later, at once (`free_deferred`).
320pub(crate) fn defer_drop<T: Send + 'static>(v: T) {
321    defer_pieces(Whole(Some(Box::new(v)), std::mem::size_of::<T>()));
322}
323
324/// Keeps `v` to free later, a piece at a time.
325pub(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
330/// What compiles on this thread deferred since this was last called: the compiling state
331/// takes it (to charge and free; `Lua::adopt_deferred`).
332pub(crate) fn take_deferred() -> Deferred {
333    DEFERRED.with(|d| std::mem::take(&mut *d.borrow_mut()))
334}
335
336thread_local! {
337    /// Whether what the running compile is done with is freed later (`release`): for a
338    /// compile from the host, whose next call frees it.
339    static DEFERRING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
340}
341
342/// Sets whether `release` defers, for the compile about to run: what it was.
343pub(crate) fn set_deferring(on: bool) -> bool {
344    DEFERRING.with(|d| d.replace(on))
345}
346
347/// Frees `v` now, or (in a compile from the host) later, a piece at a time.
348pub(crate) fn release<T: Piecewise + 'static>(v: T) {
349    if DEFERRING.with(std::cell::Cell::get) {
350        defer_pieces(v);
351    } else {
352        // Inside a call: now, but a piece at a time between looks (a `load` in a call of
353        // 600,000 string constants freed its maps in one 30 ms stretch).
354        free_watched(v);
355    }
356}
357
358/// Keeps a syntax tree of about `bytes` to free later, a node at a time.
359pub(crate) fn defer_tree(b: crate::ast::Block, bytes: usize) {
360    defer_pieces(crate::ast::Dropper::of_block(b).with_bytes(bytes));
361}
362
363/// Frees `list` a piece at a time until `stop` says to stop (the host's interrupt): what
364/// is left is freed at a later call. The bytes of each item freed whole: released.
365pub(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            // What each piece gave back is released as it goes (never more than charged).
370            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
389/// Frees `v` now, a piece at a time, each a step of the running compile; told to stop,
390/// it leaves the rest to `free_deferred`.
391pub(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
401/// Asks the allocator for a block larger than the small ones just freed, and gives it back:
402/// an allocator that keeps small freed blocks on quick lists (glibc's) merges them on such
403/// a request, so it does that for each piece now, not for all of a tree at once at some
404/// later allocation (S6-FRONT-4: the first sizeable allocation after freeing a 3M-node
405/// tree took 300 ms).
406fn settle_frees() {
407    drop(std::hint::black_box(Vec::<u8>::with_capacity(4096)));
408}
409
410/// Runs a compile under `watch`, with at most `max_work` units of scan work: the result,
411/// the limit that stopped it (if one did), and the scan work done.
412pub(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/// Scan work in the compiler that grows with the program, not with its length: looking a
428/// name up among the active locals and upvalues, labels and pending gotos, and the like.
429/// (With no limit on locals, labels or gotos, these made compiling quadratic: 40,000
430/// locals took 5 s against about 2M units of fuel for `load`'s up-front charge.) Counted
431/// and paid for as fuel by the caller; past the most a compile may do, it stops on the
432/// fuel limit at the next step. Every `COMPILE_WORK_PER_TICK` units are also a step
433/// between looks at the host's interrupt and deadline.
434#[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        // A stop found here is kept (`COMPILE_STOP`): the next step reports it.
452        compile_ticks(u32::try_from(steps).unwrap_or(u32::MAX));
453    }
454}
455
456/// Whether the running compile was told to stop (by its watch or its scan work).
457#[inline]
458pub(crate) fn compile_stopped() -> bool {
459    COMPILE_STOP.with(std::cell::Cell::get)
460}
461
462/// One step of the lexer, parser or compiler: true when the host's interrupt or deadline
463/// says to stop (looked at every `COMPILE_WATCH_EVERY` steps).
464#[inline]
465pub(crate) fn compile_tick() -> bool {
466    compile_ticks(1)
467}
468
469/// `n` steps of the lexer, parser or compiler at once (a token that took long to read):
470/// true when the host's interrupt or deadline says to stop.
471#[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        // Past its scan work, or told to stop during it, a compile stops at once.
481        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}