nitr_core/runtime/script.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2// This file is part of Nitr.
3// See https://nitrweb.com/ for more information
4// Copyright (C) 2024-present Jose Quintana <joseluisq.net>
5
6//! Script loading and its diagnostics: the dual expression/block parse
7//! that keeps error line numbers honest, and the load-error renderer that
8//! points at the offending source line.
9
10use std::path::Path;
11
12use mlua::{Function, Value};
13
14use crate::{Error, Result};
15
16use super::Runtime;
17
18impl Runtime {
19 /// The compile half of [`eval_script`](Self::eval_script): the dual
20 /// parse without the call, for callers that pass the chunk arguments (a
21 /// loaded chunk is itself a vararg function) or must call it async.
22 ///
23 /// The expression parse is skipped when the chunk's first token can only
24 /// begin a statement (`local`, `return`, a named `function`, ...): it
25 /// would fail at that very token, so skipping it changes neither the
26 /// result nor the diagnostic, and a handler script — which always starts
27 /// that way — is parsed once instead of twice on every pooled state.
28 pub(super) fn load_chunk(&self, data: Vec<u8>, path: &Path) -> mlua::Result<Function> {
29 load_chunk_in(&self.lua, data, path)
30 }
31
32 /// Loads and evaluates a Lua script file, returning the resulting value.
33 ///
34 /// This does not interpret the result; callers decide what the script is
35 /// expected to return (e.g. a handler function or an application object).
36 pub fn eval_script(&self, path: &Path) -> Result<Value> {
37 self.budgeted(|lua| eval_script(lua, path))
38 }
39}
40
41/// [`Runtime::eval_script`] on a bare state — for code that holds only
42/// the `Lua` handle, such as a builtin that loads the application into
43/// the state it runs in (`nitr test`'s `t.app()`). The same text-only
44/// compile and the same in-context error rendering.
45pub fn eval_script(lua: &mlua::Lua, path: &Path) -> Result<Value> {
46 let data = std::fs::read(path).map_err(|err| {
47 Error::Script(format!(
48 "failed to read the Lua script {}: {err}",
49 path.display()
50 ))
51 })?;
52 load_chunk_in(lua, data, path)
53 .and_then(|chunk| chunk.call(()))
54 .map_err(|err| load_error(path, err))
55}
56
57/// Converts a load-time Lua failure into a [`Error::Script`] that points at
58/// the offending line, with the source rendered around it — parse errors
59/// and runtime errors alike (a misspelled method carries a position the
60/// same way a typo does). Runs only at startup (and on dev-mode reloads),
61/// so reading the file back is fine.
62pub(super) fn load_error(path: &Path, err: mlua::Error) -> Error {
63 let info = crate::error::ErrorInfo::from_error(&Error::Lua(err));
64 // No `error:` prefix of our own: `Error::Script` already displays as
65 // `script error: ...`, and one headline is enough.
66 let mut out = info.message.clone();
67 match info.line {
68 Some(line) => {
69 let token = crate::error::message_token(&info.message);
70 match crate::error::source_snippet(path, line, 2, token) {
71 Some(snippet) => {
72 out.push('\n');
73 out.push_str(&snippet);
74 }
75 None => out.push_str(&format!("\n --> {}:{line}", path.display())),
76 };
77 }
78 None => out.push_str(&format!("\n --> {}", path.display())),
79 }
80 // Runtime failures carry a call stack; parse errors have none. Already
81 // bounded by the classifier.
82 if let Some(traceback) = &info.traceback {
83 out.push_str("\nstack traceback:\n");
84 out.push_str(traceback);
85 }
86 Error::Script(out)
87}
88
89/// Whether the chunk's first token can only begin a statement, so that the
90/// expression form (`return <chunk>`) is guaranteed to fail *at that token*.
91///
92/// Skipping the expression parse in that case is observably identical to
93/// running it: it cannot succeed, and the diagnostic it would produce sits
94/// on the first token's line, which the block parse's error can never
95/// precede — so the "furthest error wins" rule picks the block error either
96/// way. Every answer of `false` means "parse both, as before"; the
97/// function only ever removes a parse it can prove redundant, and an
98/// unrecognized or unterminated prefix (a shebang, an unclosed long
99/// comment, a vertical tab) answers `false`.
100///
101/// A bare call is the one shape that is valid in both forms (`nitr.app()`
102/// is an expression *and* a call statement), so a leading identifier must
103/// keep the expression attempt first: that is what makes such a script
104/// evaluate to the call's result instead of `nil`.
105fn starts_as_statement(src: &[u8]) -> bool {
106 let rest = skip_trivia(src);
107 let is_word = |b: &u8| b.is_ascii_alphanumeric() || *b == b'_';
108 let word_end = rest.iter().position(|b| !is_word(b)).unwrap_or(rest.len());
109 match &rest[..word_end] {
110 b"local" | b"return" | b"if" | b"for" | b"while" | b"do" | b"repeat" | b"goto"
111 | b"break" => true,
112 // `function name(` is a statement; `function(` is an expression.
113 b"function" => skip_trivia(&rest[word_end..])
114 .first()
115 .is_some_and(|b| b.is_ascii_alphabetic() || *b == b'_'),
116 // A label, `::name::`.
117 _ => rest.starts_with(b"::"),
118 }
119}
120
121/// Skips ASCII whitespace and comments (`--` to end of line, or a long
122/// `--[==[ ... ]==]` bracket). An unterminated long comment yields the empty
123/// slice, which `starts_as_statement` treats as "unknown".
124fn skip_trivia(mut src: &[u8]) -> &[u8] {
125 loop {
126 let ws = src
127 .iter()
128 .position(|b| !b.is_ascii_whitespace())
129 .unwrap_or(src.len());
130 src = &src[ws..];
131 let Some(body) = src.strip_prefix(b"--") else {
132 return src;
133 };
134 src = match long_bracket_level(body) {
135 Some(level) => {
136 let open = level + 2;
137 let mut close = Vec::with_capacity(level + 2);
138 close.push(b']');
139 close.extend(std::iter::repeat_n(b'=', level));
140 close.push(b']');
141 match body[open..]
142 .windows(close.len())
143 .position(|window| window == close.as_slice())
144 {
145 Some(at) => &body[open + at + close.len()..],
146 None => return &[],
147 }
148 }
149 None => match body.iter().position(|b| *b == b'\n') {
150 Some(at) => &body[at + 1..],
151 None => return &[],
152 },
153 };
154 }
155}
156
157/// The `=` count of a long bracket opening at the start of `s` (`[[` is
158/// level 0, `[==[` is level 2), or `None` when `s` does not open one.
159fn long_bracket_level(s: &[u8]) -> Option<usize> {
160 let after_open = s.strip_prefix(b"[")?;
161 let level = after_open.iter().take_while(|b| **b == b'=').count();
162 (after_open.get(level) == Some(&b'[')).then_some(level)
163}
164
165/// Compiles a chunk the way `eval` does — expression form first, statement
166/// block second, text only — but with precise diagnostics: when *both*
167/// parses fail, the error that got further into the file wins. mlua's own
168/// `eval` reports only the block fallback, which for an expression-form
169/// script always blames the top-level `function(` line instead of the
170/// actual typo.
171///
172/// The chunk is named after the file (`@` marks a real path) so errors
173/// report `config.lua:12` instead of an anonymous chunk.
174fn load_chunk_in(lua: &mlua::Lua, data: Vec<u8>, path: &Path) -> mlua::Result<Function> {
175 let name = format!("@{}", path.display());
176 // Text only, like every other chunk the runtime compiles: a script
177 // file that is precompiled bytecode is refused rather than trusted
178 // (see `PRELUDE` in the parent module for why bytecode is unsafe).
179 let expr_err = if starts_as_statement(&data) {
180 None
181 } else {
182 // `return ` on the same line keeps every line number intact.
183 let mut wrapped = Vec::with_capacity(data.len() + 7);
184 wrapped.extend_from_slice(b"return ");
185 wrapped.extend_from_slice(&data);
186 match lua
187 .load(wrapped)
188 .set_name(&name)
189 .set_mode(mlua::chunk::ChunkMode::Text)
190 .into_function()
191 {
192 Ok(f) => return Ok(f),
193 Err(err) => Some(err),
194 }
195 };
196 match lua
197 .load(data)
198 .set_name(&name)
199 .set_mode(mlua::chunk::ChunkMode::Text)
200 .into_function()
201 {
202 Ok(f) => Ok(f),
203 Err(block_err) => {
204 let Some(expr_err) = expr_err else {
205 return Err(block_err);
206 };
207 let line = |err: &mlua::Error| {
208 crate::error::ErrorInfo::from_error(&Error::Lua(err.clone()))
209 .line
210 .unwrap_or(0)
211 };
212 if line(&expr_err) > line(&block_err) {
213 Err(expr_err)
214 } else {
215 Err(block_err)
216 }
217 }
218 }
219}
220
221#[cfg(test)]
222mod tests {
223 use super::*;
224
225 #[test]
226 fn statement_only_prefixes_skip_the_expression_parse() {
227 for src in [
228 "local app = nitr.app()",
229 " \n\t-- a comment\n\nlocal x = 1",
230 "--[[ multi\nline ]] return {}",
231 "--[==[ a ]] inside ]==]\nfunction handler(req) end",
232 "-- one\n-- two\nif x then end",
233 "for i = 1, 2 do end",
234 "while true do end",
235 "do end",
236 "repeat until true",
237 "goto top",
238 "break",
239 "::top::",
240 "return",
241 ] {
242 assert!(starts_as_statement(src.as_bytes()), "{src:?}");
243 }
244 }
245
246 #[test]
247 fn expression_capable_prefixes_keep_the_expression_parse() {
248 for src in [
249 "function(req) return req end",
250 "function (req) return req end",
251 "-- comment\nfunction(db)\n return {}\nend",
252 "{ a = 1 }",
253 "nitr.app()",
254 "string.rep('a', 2)",
255 "localx = 1",
256 "returned = 1",
257 "'a string'",
258 "42",
259 "",
260 " ",
261 "-- only a comment",
262 "--[[ unterminated",
263 "#!/usr/bin/lua\nlocal x = 1",
264 "\x0blocal x = 1",
265 ] {
266 assert!(!starts_as_statement(src.as_bytes()), "{src:?}");
267 }
268 }
269
270 #[test]
271 fn long_brackets_parse_by_level() {
272 assert_eq!(long_bracket_level(b"[[x"), Some(0));
273 assert_eq!(long_bracket_level(b"[==[x"), Some(2));
274 assert_eq!(long_bracket_level(b"[=x"), None);
275 assert_eq!(long_bracket_level(b"x"), None);
276 assert_eq!(long_bracket_level(b""), None);
277 // A level-1 close does not end a level-2 comment.
278 assert_eq!(skip_trivia(b"--[==[ ]=] ]==]rest"), b"rest");
279 }
280}