1
use scripting::host::{ExecutionState, WasmHost, define_host_functions};
2
use scripting::nomiscript::{
3
    Compiler, Expr, Program, Reader, Symbol, SymbolKind, SymbolTable, Value,
4
};
5
use 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
};
9
use scripting_format::{ContextType, EntityType, GlobalHeader, OUTPUT_HEADER_SIZE, OutputHeader};
10
use thiserror::Error;
11
use tracing::{debug, warn};
12
use tracing_subscriber::EnvFilter;
13
use tracing_subscriber::prelude::*;
14
use tracing_subscriber::reload;
15
use wasmtime::{AnyRef, Caller, Instance, Linker, Memory, Module, Rooted, Store};
16

            
17
#[derive(Error, Debug)]
18
pub 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

            
30
impl Error {
31
    #[must_use]
32
1496
    pub fn render(&self, use_color: bool) -> String {
33
1496
        match self {
34
1265
            Error::Script(e) => e.render(use_color),
35
            Error::Runtime(_) | Error::Raised { .. } => {
36
231
                if use_color {
37
                    format!("\x1b[31merror:\x1b[0m {self}")
38
                } else {
39
231
                    format!("error: {self}")
40
                }
41
            }
42
        }
43
1496
    }
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
9776
    fn from_run(err: &wasmtime::Error) -> Self {
52
9776
        match classify_runtime_error(err) {
53
            raised @ EngineError::ScriptRaised { .. } => {
54
7591
                let (code, message) = err_code_and_message(&raised);
55
7591
                Error::Raised { code, message }
56
            }
57
2185
            other => Error::Runtime(other.to_string()),
58
        }
59
9776
    }
60
}
61

            
62
pub type Result<T> = std::result::Result<T, Error>;
63

            
64
pub struct Interpreter {
65
    host: WasmHost,
66
    compiler: Compiler,
67
    reload_handle: reload::Handle<EnvFilter, tracing_subscriber::Registry>,
68
}
69

            
70
const DEFAULT_OUTPUT_SIZE: u32 = 64 * 1024;
71
const 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.
79
481522
fn set_interactive_epoch_deadline<T>(store: &mut Store<T>) {
80
481522
    store.set_epoch_deadline(u64::MAX);
81
481522
}
82

            
83
impl Interpreter {
84
209081
    pub fn new(debug_mode: bool) -> anyhow::Result<Self> {
85
209081
        Self::with_profiler(debug_mode, ProfilerStrategy::None)
86
209081
    }
87

            
88
212186
    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
212186
        let engine = build_engine(EngineOpts::baseline().with_profiler(profiler))?;
93

            
94
212186
        let mut symbols = SymbolTable::with_builtins();
95
212186
        symbols.define_special(
96
212186
            Symbol::new("REVISION", SymbolKind::Variable)
97
212186
                .with_value(Expr::String(env!("GIT_REVISION").to_string())),
98
212186
        );
99

            
100
212186
        let default_filter = if debug_mode { "debug" } else { "warn" };
101
        let filter =
102
212186
            EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(default_filter));
103
212186
        let (filter_layer, reload_handle) = reload::Layer::new(filter);
104
212186
        tracing_subscriber::registry()
105
212186
            .with(filter_layer)
106
212186
            .with(tracing_subscriber::fmt::layer().with_writer(std::io::stderr))
107
212186
            .try_init()
108
212186
            .ok();
109

            
110
212186
        let mut interp = Self {
111
212186
            host: WasmHost::new(engine, symbols),
112
212186
            compiler: Compiler::new(),
113
212186
            reload_handle,
114
212186
        };
115
212186
        interp.load_stdlib()?;
116
212186
        Ok(interp)
117
212186
    }
118

            
119
212186
    fn load_stdlib(&mut self) -> Result<()> {
120
        const STDLIB: &str = include_str!("stdlib.lisp");
121
212186
        let program = Reader::parse(STDLIB)?;
122
212186
        self.compile(&program).map(drop)
123
212186
    }
124

            
125
    /// Compiles against the host's persistent symbol table.
126
747414
    fn compile(&mut self, program: &Program) -> Result<Vec<u8>> {
127
747414
        let mut symbols = self
128
747414
            .host
129
747414
            .symbol_table()
130
747414
            .write()
131
            .map_err(|e| Error::Runtime(format!("failed to write symbol table: {e}")))?;
132
747414
        Ok(self.compiler.compile(program, &mut symbols)?)
133
747414
    }
134

            
135
535802
    pub fn eval(&mut self, input: &str) -> Result<Vec<Value>> {
136
535802
        let program = Reader::parse(input)?;
137
535457
        let debug_mode = program.annotations.iter().any(|a| a.name == "debug");
138
535457
        if debug_mode {
139
            self.reload_handle
140
                .modify(|f| *f = EnvFilter::new("debug"))
141
                .ok();
142
535457
        }
143
535457
        let result = self.eval_program(&program);
144
535457
        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
535457
        }
152
535457
        result
153
535802
    }
154

            
155
    /// The program's result values: none for an empty or void program.
156
535457
    fn eval_program(&mut self, program: &Program) -> Result<Vec<Value>> {
157
535457
        if program.exprs.is_empty() {
158
230
            return Ok(vec![]);
159
535227
        }
160
535227
        let wasm = self.compile(program)?;
161
478417
        let input = build_minimal_input(DEFAULT_OUTPUT_SIZE);
162
478417
        let output = self.run_unit(&wasm, &input, true)?;
163
468296
        Ok(decode_output(&output)?.into_iter().collect())
164
535457
    }
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
805
    pub fn run_wasm(&self, wasm: &[u8]) -> Result<Option<Value>> {
169
805
        let input = build_minimal_input(DEFAULT_OUTPUT_SIZE);
170
805
        self.run_wasm_with_input(wasm, &input)
171
805
    }
172

            
173
3106
    pub fn run_wasm_with_input(&self, wasm: &[u8], input: &[u8]) -> Result<Option<Value>> {
174
3106
        let output = self.run_wasm_with_input_raw(wasm, input)?;
175
2990
        decode_output(&output)
176
3106
    }
177

            
178
    /// Runs a script and returns its whole output region.
179
3106
    pub fn run_wasm_with_input_raw(&self, wasm: &[u8], input: &[u8]) -> Result<Vec<u8>> {
180
3106
        self.run_unit(wasm, input, false)
181
3106
    }
182

            
183
    /// Runs `wasm` and, for a unit the interpreter compiled, carries its
184
    /// globals into the session's symbol table.
185
481524
    fn run_unit(&self, wasm: &[u8], input: &[u8], carry: bool) -> Result<Vec<u8>> {
186
481524
        let (mut store, instance, memory, layout) = match self.start_unit(wasm, input) {
187
481522
            Ok(started) => started,
188
            Err(err) => {
189
2
                if carry {
190
1
                    self.carry_not_run();
191
1
                }
192
2
                return Err(err);
193
            }
194
        };
195
481522
        let ran = call_entry_points(&mut store, &instance);
196
481522
        if carry {
197
478417
            self.carry_unit_globals(&mut store, &instance, &ran);
198
3105
        }
199
481522
        ran?;
200
471286
        let output_start = layout.output_offset as usize;
201
471286
        scripting::debug_value::output_region(
202
471286
            memory.data(&store),
203
471286
            output_start,
204
471286
            DEFAULT_OUTPUT_SIZE as usize,
205
471286
        )
206
471286
        .map(<[u8]>::to_vec)
207
471286
        .map_err(Error::runtime)
208
481524
    }
209

            
210
    /// Instantiates `wasm` and places `input` in its memory.
211
481524
    fn start_unit(
212
481524
        &self,
213
481524
        wasm: &[u8],
214
481524
        input: &[u8],
215
481524
    ) -> Result<(Store<ExecutionState>, Instance, Memory, Layout)> {
216
481524
        debug!(wasm_size = wasm.len(), "creating WASM module");
217
481524
        let module = Module::new(self.host.engine(), wasm).map_err(Error::runtime)?;
218
481524
        let layout = Layout::new(input)?;
219
481522
        let exec_state = self.host.execution_state(
220
481522
            layout.input_offset,
221
481522
            layout.output_offset,
222
481522
            layout.strings_offset,
223
481522
        );
224
481522
        let mut store = Store::new(self.host.engine(), exec_state);
225
481522
        set_interactive_epoch_deadline(&mut store);
226
481522
        let instance = self
227
481522
            .linker()?
228
481522
            .instantiate(&mut store, &module)
229
481522
            .map_err(Error::runtime)?;
230
481522
        let memory = instance
231
481522
            .get_memory(&mut store, "memory")
232
            .ok_or_else(|| Error::Runtime("no memory export".to_string()))?;
233
481522
        store.data_mut().memory = Some(memory);
234
481522
        layout.place(&mut store, memory, input)?;
235
481522
        Ok((store, instance, memory, layout))
236
481524
    }
237

            
238
    /// Puts back every slot of a unit the interpreter compiled that never ran.
239
1
    fn carry_not_run(&self) {
240
1
        match self.host.symbol_table().write() {
241
1
            Ok(mut symbols) => carry_not_run(&mut symbols),
242
            Err(err) => warn!(%err, "putting back an unrun unit: symbol table lock poisoned"),
243
        }
244
1
    }
245

            
246
478417
    fn carry_unit_globals(
247
478417
        &self,
248
478417
        store: &mut Store<ExecutionState>,
249
478417
        instance: &Instance,
250
478417
        ran: &Result<()>,
251
478417
    ) {
252
478417
        let end = match ran {
253
468296
            Ok(()) => UnitEnd::Returned,
254
7476
            Err(Error::Raised { .. }) => UnitEnd::Raised,
255
2645
            Err(_) => UnitEnd::Trapped,
256
        };
257
478417
        match self.host.symbol_table().write() {
258
478417
            Ok(mut symbols) => carry_globals(store, instance, &mut symbols, end),
259
            Err(err) => warn!(%err, "carrying unit globals: symbol table lock poisoned"),
260
        }
261
478417
    }
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
481522
    fn linker(&self) -> Result<Linker<ExecutionState>> {
266
481522
        let mut linker = Linker::new(self.host.engine());
267
481522
        define_host_functions(&mut linker).map_err(Error::runtime)?;
268
481522
        linker.allow_shadowing(true);
269
481522
        linker
270
            .func_wrap(
271
481522
                "env",
272
481522
                "log",
273
3335
                |caller: Caller<'_, ExecutionState>, level: u32, ptr: u32, len: u32| {
274
3335
                    if let Some(message) = logged_text(&caller, ptr, len) {
275
3335
                        echo(level, &message);
276
                    }
277
3335
                },
278
            )
279
481522
            .map_err(Error::runtime)?;
280
481522
        linker
281
            .func_wrap(
282
481522
                "env",
283
481522
                "log_value",
284
                |mut caller: Caller<'_, ExecutionState>,
285
                 args: Option<Rooted<AnyRef>>|
286
6325
                 -> wasmtime::Result<i32> {
287
6325
                    let Some(msg) = logged_values(&mut caller, args)? else {
288
                        return Ok(1);
289
                    };
290
6325
                    echo(0, &msg);
291
6325
                    Ok(0)
292
6325
                },
293
            )
294
481522
            .map_err(Error::runtime)?;
295
481522
        Ok(linker)
296
481522
    }
297
}
298

            
299
471286
fn decode_output(output: &[u8]) -> Result<Option<Value>> {
300
471286
    match scripting::debug_value::decode_result(output) {
301
        Ok(value) => {
302
418729
            debug!("result decoded");
303
418729
            Ok(Some(value))
304
        }
305
52557
        Err(scripting::debug_value::DecodeError::Absent(_)) => Ok(None),
306
        Err(err) => Err(Error::runtime(err)),
307
    }
308
471286
}
309

            
310
9660
fn echo(level: u32, message: &str) {
311
9660
    if level >= 2 {
312
        eprintln!("{message}");
313
    } else {
314
9660
        println!("{message}");
315
    }
316
9660
}
317

            
318
/// The logged message, if it lies in memory and is UTF-8.
319
3335
fn logged_text(caller: &Caller<'_, ExecutionState>, ptr: u32, len: u32) -> Option<String> {
320
3335
    let memory = caller.data().memory?;
321
3335
    let start = ptr as usize;
322
3335
    let bytes = memory
323
3335
        .data(caller)
324
3335
        .get(start..start.checked_add(len as usize)?)?;
325
3335
    String::from_utf8(bytes.to_vec()).ok()
326
3335
}
327

            
328
/// Where the input batch and the output buffer sit in linear memory.
329
struct Layout {
330
    input_offset: u32,
331
    output_offset: u32,
332
    strings_offset: u32,
333
}
334

            
335
impl Layout {
336
481524
    fn new(input: &[u8]) -> Result<Self> {
337
481524
        let header = GlobalHeader::from_bytes(input)
338
2
            .ok_or_else(|| Error::Runtime("the input batch has no valid header".to_string()))?;
339
481522
        let input_len = u32::try_from(input.len()).map_err(Error::runtime)?;
340
481522
        let input_offset = scripting_format::BASE_OFFSET;
341
481522
        let output_offset = input_offset
342
481522
            .checked_add(input_len)
343
            .ok_or_else(|| Error::Runtime("the input batch does not fit in memory".to_string()))?;
344
481522
        debug!(
345
            input_offset,
346
            output_offset,
347
            strings_offset = header.strings_pool_offset,
348
            "memory layout offsets"
349
        );
350
481522
        Ok(Self {
351
481522
            input_offset,
352
481522
            output_offset,
353
481522
            strings_offset: header.strings_pool_offset,
354
481522
        })
355
481524
    }
356

            
357
    /// Grows memory to hold both buffers, then writes the batch and an
358
    /// empty output header.
359
481522
    fn place(&self, store: &mut Store<ExecutionState>, memory: Memory, input: &[u8]) -> Result<()> {
360
481522
        let output_start = self.output_offset as usize;
361
481522
        let needed = (output_start + DEFAULT_OUTPUT_SIZE as usize).div_ceil(WASM_PAGE_SIZE);
362
481522
        let current = usize::try_from(memory.size(&*store)).map_err(Error::runtime)?;
363
481522
        if needed > current {
364
481522
            debug!(current, needed, "growing memory");
365
481522
            let delta = u64::try_from(needed - current).map_err(Error::runtime)?;
366
481522
            memory.grow(&mut *store, delta).map_err(Error::runtime)?;
367
        }
368
481522
        let data = memory.data_mut(store);
369
481522
        copy_into(data, self.input_offset as usize, input)?;
370
481522
        copy_into(
371
481522
            data,
372
481522
            output_start,
373
481522
            &OutputHeader::new(0).to_bytes()[..OUTPUT_HEADER_SIZE],
374
481522
        )
375
481522
    }
376
}
377

            
378
963044
fn copy_into(memory: &mut [u8], start: usize, bytes: &[u8]) -> Result<()> {
379
963044
    start
380
963044
        .checked_add(bytes.len())
381
963044
        .and_then(|end| memory.get_mut(start..end))
382
        .ok_or_else(|| Error::Runtime("the buffers do not fit in memory".to_string()))?
383
963044
        .copy_from_slice(bytes);
384
963044
    Ok(())
385
963044
}
386

            
387
/// `should_apply` must answer 1 for the interactive runner; then `process`.
388
481522
fn call_entry_points(store: &mut Store<ExecutionState>, instance: &Instance) -> Result<()> {
389
481522
    let should_apply = instance
390
481522
        .get_typed_func::<(), i32>(&mut *store, "should_apply")
391
481522
        .map_err(Error::runtime)?;
392
481522
    debug!("calling should_apply");
393
481522
    let apply = should_apply
394
481522
        .call(&mut *store, ())
395
115
        .map_err(|e| Error::from_run(&e))?;
396
481407
    debug!(result = apply, "should_apply returned");
397
481407
    if apply != 1 {
398
460
        return Err(Error::Runtime(format!(
399
460
            "should_apply returned {apply}, expected 1"
400
460
        )));
401
480947
    }
402
480947
    let process = instance
403
480947
        .get_typed_func::<(), ()>(&mut *store, "process")
404
480947
        .map_err(Error::runtime)?;
405
480947
    debug!("calling process");
406
480947
    process
407
480947
        .call(&mut *store, ())
408
9661
        .map_err(|e| Error::from_run(&e))
409
481522
}
410

            
411
479222
fn build_minimal_input(output_size: u32) -> Vec<u8> {
412
    use scripting::MemorySerializer;
413
479222
    let mut ser = MemorySerializer::new();
414
479222
    ser.set_context(ContextType::BatchProcess, EntityType::Transaction);
415
479222
    ser.finalize(output_size)
416
479222
}
417

            
418
#[cfg(test)]
419
#[path = "interpreter_tests.rs"]
420
mod tests;