Skip to main content

nms/
interpreter.rs

1use scripting::host::{ExecutionState, WasmHost, define_host_functions};
2use scripting::nomiscript::{
3    Compiler, Expr, Program, Reader, Symbol, SymbolKind, SymbolTable, Value,
4};
5use scripting::runtime::{
6    EngineError, EngineOpts, ProfilerStrategy, UnitEnd, build_engine, carry_globals, carry_not_run,
7    classify_runtime_error, err_code_and_message, logged_values,
8};
9use scripting_format::{ContextType, EntityType, GlobalHeader, OUTPUT_HEADER_SIZE, OutputHeader};
10use thiserror::Error;
11use tracing::{debug, warn};
12use tracing_subscriber::EnvFilter;
13use tracing_subscriber::prelude::*;
14use tracing_subscriber::reload;
15use wasmtime::{AnyRef, Caller, Instance, Linker, Memory, Module, Rooted, Store};
16
17#[derive(Error, Debug)]
18pub enum Error {
19    #[error("{0}")]
20    Script(#[from] scripting::nomiscript::Error),
21
22    #[error("{0}")]
23    Runtime(String),
24
25    /// A `$nomi_error` no handler caught, by its code and message.
26    #[error("{code}: {message}")]
27    Raised { code: String, message: String },
28}
29
30impl Error {
31    #[must_use]
32    pub fn render(&self, use_color: bool) -> String {
33        match self {
34            Error::Script(e) => e.render(use_color),
35            Error::Runtime(_) | Error::Raised { .. } => {
36                if use_color {
37                    format!("\x1b[31merror:\x1b[0m {self}")
38                } else {
39                    format!("error: {self}")
40                }
41            }
42        }
43    }
44
45    fn runtime(err: impl ToString) -> Self {
46        Error::Runtime(err.to_string())
47    }
48
49    /// A failed `should_apply` / `process` call: a raised condition keeps its
50    /// code and message, anything else its engine text.
51    fn from_run(err: &wasmtime::Error) -> Self {
52        match classify_runtime_error(err) {
53            raised @ EngineError::ScriptRaised { .. } => {
54                let (code, message) = err_code_and_message(&raised);
55                Error::Raised { code, message }
56            }
57            other => Error::Runtime(other.to_string()),
58        }
59    }
60}
61
62pub type Result<T> = std::result::Result<T, Error>;
63
64pub struct Interpreter {
65    host: WasmHost,
66    compiler: Compiler,
67    reload_handle: reload::Handle<EnvFilter, tracing_subscriber::Registry>,
68}
69
70const DEFAULT_OUTPUT_SIZE: u32 = 64 * 1024;
71const WASM_PAGE_SIZE: usize = 65536;
72
73/// `build_engine` turns on epoch interruption, so every store needs a
74/// deadline or it traps at the default tick 0. The interactive
75/// interpreter has no wall-clock budget to enforce (unlike the rpc
76/// `Session`, which spawns an epoch bumper) — it just runs the user's
77/// REPL input to completion. A deadline that's never advanced past
78/// gives the old no-epoch-limit behaviour back.
79fn set_interactive_epoch_deadline<T>(store: &mut Store<T>) {
80    store.set_epoch_deadline(u64::MAX);
81}
82
83impl Interpreter {
84    pub fn new(debug_mode: bool) -> anyhow::Result<Self> {
85        Self::with_profiler(debug_mode, ProfilerStrategy::None)
86    }
87
88    pub fn with_profiler(debug_mode: bool, profiler: ProfilerStrategy) -> anyhow::Result<Self> {
89        // Route through `build_engine` so the wasm feature set (GC,
90        // function-references, exceptions) stays single-sourced — a flag
91        // added there can't silently miss the nms interpreter path.
92        let engine = build_engine(EngineOpts::baseline().with_profiler(profiler))?;
93
94        let mut symbols = SymbolTable::with_builtins();
95        symbols.define_special(
96            Symbol::new("REVISION", SymbolKind::Variable)
97                .with_value(Expr::String(env!("GIT_REVISION").to_string())),
98        );
99
100        let default_filter = if debug_mode { "debug" } else { "warn" };
101        let filter =
102            EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(default_filter));
103        let (filter_layer, reload_handle) = reload::Layer::new(filter);
104        tracing_subscriber::registry()
105            .with(filter_layer)
106            .with(tracing_subscriber::fmt::layer().with_writer(std::io::stderr))
107            .try_init()
108            .ok();
109
110        let mut interp = Self {
111            host: WasmHost::new(engine, symbols),
112            compiler: Compiler::new(),
113            reload_handle,
114        };
115        interp.load_stdlib()?;
116        Ok(interp)
117    }
118
119    fn load_stdlib(&mut self) -> Result<()> {
120        const STDLIB: &str = include_str!("stdlib.lisp");
121        let program = Reader::parse(STDLIB)?;
122        self.compile(&program).map(drop)
123    }
124
125    /// Compiles against the host's persistent symbol table.
126    fn compile(&mut self, program: &Program) -> Result<Vec<u8>> {
127        let mut symbols = self
128            .host
129            .symbol_table()
130            .write()
131            .map_err(|e| Error::Runtime(format!("failed to write symbol table: {e}")))?;
132        Ok(self.compiler.compile(program, &mut symbols)?)
133    }
134
135    pub fn eval(&mut self, input: &str) -> Result<Vec<Value>> {
136        let program = Reader::parse(input)?;
137        let debug_mode = program.annotations.iter().any(|a| a.name == "debug");
138        if debug_mode {
139            self.reload_handle
140                .modify(|f| *f = EnvFilter::new("debug"))
141                .ok();
142        }
143        let result = self.eval_program(&program);
144        if debug_mode {
145            self.reload_handle
146                .modify(|f| {
147                    *f = EnvFilter::try_from_default_env()
148                        .unwrap_or_else(|_| EnvFilter::new("warn"));
149                })
150                .ok();
151        }
152        result
153    }
154
155    /// The program's result values: none for an empty or void program.
156    fn eval_program(&mut self, program: &Program) -> Result<Vec<Value>> {
157        if program.exprs.is_empty() {
158            return Ok(vec![]);
159        }
160        let wasm = self.compile(program)?;
161        let input = build_minimal_input(DEFAULT_OUTPUT_SIZE);
162        let output = self.run_unit(&wasm, &input, true)?;
163        Ok(decode_output(&output)?.into_iter().collect())
164    }
165
166    /// Runs a script against the minimal empty batch; `None` when it wrote
167    /// no result value (a void program is not an error).
168    pub fn run_wasm(&self, wasm: &[u8]) -> Result<Option<Value>> {
169        let input = build_minimal_input(DEFAULT_OUTPUT_SIZE);
170        self.run_wasm_with_input(wasm, &input)
171    }
172
173    pub fn run_wasm_with_input(&self, wasm: &[u8], input: &[u8]) -> Result<Option<Value>> {
174        let output = self.run_wasm_with_input_raw(wasm, input)?;
175        decode_output(&output)
176    }
177
178    /// Runs a script and returns its whole output region.
179    pub fn run_wasm_with_input_raw(&self, wasm: &[u8], input: &[u8]) -> Result<Vec<u8>> {
180        self.run_unit(wasm, input, false)
181    }
182
183    /// Runs `wasm` and, for a unit the interpreter compiled, carries its
184    /// globals into the session's symbol table.
185    fn run_unit(&self, wasm: &[u8], input: &[u8], carry: bool) -> Result<Vec<u8>> {
186        let (mut store, instance, memory, layout) = match self.start_unit(wasm, input) {
187            Ok(started) => started,
188            Err(err) => {
189                if carry {
190                    self.carry_not_run();
191                }
192                return Err(err);
193            }
194        };
195        let ran = call_entry_points(&mut store, &instance);
196        if carry {
197            self.carry_unit_globals(&mut store, &instance, &ran);
198        }
199        ran?;
200        let output_start = layout.output_offset as usize;
201        scripting::debug_value::output_region(
202            memory.data(&store),
203            output_start,
204            DEFAULT_OUTPUT_SIZE as usize,
205        )
206        .map(<[u8]>::to_vec)
207        .map_err(Error::runtime)
208    }
209
210    /// Instantiates `wasm` and places `input` in its memory.
211    fn start_unit(
212        &self,
213        wasm: &[u8],
214        input: &[u8],
215    ) -> Result<(Store<ExecutionState>, Instance, Memory, Layout)> {
216        debug!(wasm_size = wasm.len(), "creating WASM module");
217        let module = Module::new(self.host.engine(), wasm).map_err(Error::runtime)?;
218        let layout = Layout::new(input)?;
219        let exec_state = self.host.execution_state(
220            layout.input_offset,
221            layout.output_offset,
222            layout.strings_offset,
223        );
224        let mut store = Store::new(self.host.engine(), exec_state);
225        set_interactive_epoch_deadline(&mut store);
226        let instance = self
227            .linker()?
228            .instantiate(&mut store, &module)
229            .map_err(Error::runtime)?;
230        let memory = instance
231            .get_memory(&mut store, "memory")
232            .ok_or_else(|| Error::Runtime("no memory export".to_string()))?;
233        store.data_mut().memory = Some(memory);
234        layout.place(&mut store, memory, input)?;
235        Ok((store, instance, memory, layout))
236    }
237
238    /// Puts back every slot of a unit the interpreter compiled that never ran.
239    fn carry_not_run(&self) {
240        match self.host.symbol_table().write() {
241            Ok(mut symbols) => carry_not_run(&mut symbols),
242            Err(err) => warn!(%err, "putting back an unrun unit: symbol table lock poisoned"),
243        }
244    }
245
246    fn carry_unit_globals(
247        &self,
248        store: &mut Store<ExecutionState>,
249        instance: &Instance,
250        ran: &Result<()>,
251    ) {
252        let end = match ran {
253            Ok(()) => UnitEnd::Returned,
254            Err(Error::Raised { .. }) => UnitEnd::Raised,
255            Err(_) => UnitEnd::Trapped,
256        };
257        match self.host.symbol_table().write() {
258            Ok(mut symbols) => carry_globals(store, instance, &mut symbols, end),
259            Err(err) => warn!(%err, "carrying unit globals: symbol table lock poisoned"),
260        }
261    }
262
263    /// The script host with `log` echoed to the terminal: PRINT output
264    /// goes to stdout, a script's warnings and errors to stderr.
265    fn linker(&self) -> Result<Linker<ExecutionState>> {
266        let mut linker = Linker::new(self.host.engine());
267        define_host_functions(&mut linker).map_err(Error::runtime)?;
268        linker.allow_shadowing(true);
269        linker
270            .func_wrap(
271                "env",
272                "log",
273                |caller: Caller<'_, ExecutionState>, level: u32, ptr: u32, len: u32| {
274                    if let Some(message) = logged_text(&caller, ptr, len) {
275                        echo(level, &message);
276                    }
277                },
278            )
279            .map_err(Error::runtime)?;
280        linker
281            .func_wrap(
282                "env",
283                "log_value",
284                |mut caller: Caller<'_, ExecutionState>,
285                 args: Option<Rooted<AnyRef>>|
286                 -> wasmtime::Result<i32> {
287                    let Some(msg) = logged_values(&mut caller, args)? else {
288                        return Ok(1);
289                    };
290                    echo(0, &msg);
291                    Ok(0)
292                },
293            )
294            .map_err(Error::runtime)?;
295        Ok(linker)
296    }
297}
298
299fn decode_output(output: &[u8]) -> Result<Option<Value>> {
300    match scripting::debug_value::decode_result(output) {
301        Ok(value) => {
302            debug!("result decoded");
303            Ok(Some(value))
304        }
305        Err(scripting::debug_value::DecodeError::Absent(_)) => Ok(None),
306        Err(err) => Err(Error::runtime(err)),
307    }
308}
309
310fn echo(level: u32, message: &str) {
311    if level >= 2 {
312        eprintln!("{message}");
313    } else {
314        println!("{message}");
315    }
316}
317
318/// The logged message, if it lies in memory and is UTF-8.
319fn logged_text(caller: &Caller<'_, ExecutionState>, ptr: u32, len: u32) -> Option<String> {
320    let memory = caller.data().memory?;
321    let start = ptr as usize;
322    let bytes = memory
323        .data(caller)
324        .get(start..start.checked_add(len as usize)?)?;
325    String::from_utf8(bytes.to_vec()).ok()
326}
327
328/// Where the input batch and the output buffer sit in linear memory.
329struct Layout {
330    input_offset: u32,
331    output_offset: u32,
332    strings_offset: u32,
333}
334
335impl Layout {
336    fn new(input: &[u8]) -> Result<Self> {
337        let header = GlobalHeader::from_bytes(input)
338            .ok_or_else(|| Error::Runtime("the input batch has no valid header".to_string()))?;
339        let input_len = u32::try_from(input.len()).map_err(Error::runtime)?;
340        let input_offset = scripting_format::BASE_OFFSET;
341        let output_offset = input_offset
342            .checked_add(input_len)
343            .ok_or_else(|| Error::Runtime("the input batch does not fit in memory".to_string()))?;
344        debug!(
345            input_offset,
346            output_offset,
347            strings_offset = header.strings_pool_offset,
348            "memory layout offsets"
349        );
350        Ok(Self {
351            input_offset,
352            output_offset,
353            strings_offset: header.strings_pool_offset,
354        })
355    }
356
357    /// Grows memory to hold both buffers, then writes the batch and an
358    /// empty output header.
359    fn place(&self, store: &mut Store<ExecutionState>, memory: Memory, input: &[u8]) -> Result<()> {
360        let output_start = self.output_offset as usize;
361        let needed = (output_start + DEFAULT_OUTPUT_SIZE as usize).div_ceil(WASM_PAGE_SIZE);
362        let current = usize::try_from(memory.size(&*store)).map_err(Error::runtime)?;
363        if needed > current {
364            debug!(current, needed, "growing memory");
365            let delta = u64::try_from(needed - current).map_err(Error::runtime)?;
366            memory.grow(&mut *store, delta).map_err(Error::runtime)?;
367        }
368        let data = memory.data_mut(store);
369        copy_into(data, self.input_offset as usize, input)?;
370        copy_into(
371            data,
372            output_start,
373            &OutputHeader::new(0).to_bytes()[..OUTPUT_HEADER_SIZE],
374        )
375    }
376}
377
378fn copy_into(memory: &mut [u8], start: usize, bytes: &[u8]) -> Result<()> {
379    start
380        .checked_add(bytes.len())
381        .and_then(|end| memory.get_mut(start..end))
382        .ok_or_else(|| Error::Runtime("the buffers do not fit in memory".to_string()))?
383        .copy_from_slice(bytes);
384    Ok(())
385}
386
387/// `should_apply` must answer 1 for the interactive runner; then `process`.
388fn call_entry_points(store: &mut Store<ExecutionState>, instance: &Instance) -> Result<()> {
389    let should_apply = instance
390        .get_typed_func::<(), i32>(&mut *store, "should_apply")
391        .map_err(Error::runtime)?;
392    debug!("calling should_apply");
393    let apply = should_apply
394        .call(&mut *store, ())
395        .map_err(|e| Error::from_run(&e))?;
396    debug!(result = apply, "should_apply returned");
397    if apply != 1 {
398        return Err(Error::Runtime(format!(
399            "should_apply returned {apply}, expected 1"
400        )));
401    }
402    let process = instance
403        .get_typed_func::<(), ()>(&mut *store, "process")
404        .map_err(Error::runtime)?;
405    debug!("calling process");
406    process
407        .call(&mut *store, ())
408        .map_err(|e| Error::from_run(&e))
409}
410
411fn build_minimal_input(output_size: u32) -> Vec<u8> {
412    use scripting::MemorySerializer;
413    let mut ser = MemorySerializer::new();
414    ser.set_context(ContextType::BatchProcess, EntityType::Transaction);
415    ser.finalize(output_size)
416}
417
418#[cfg(test)]
419#[path = "interpreter_tests.rs"]
420mod tests;